Search in sources :

Example 6 with SubjectAuthenticationResult

use of org.apache.qpid.server.security.auth.SubjectAuthenticationResult in project qpid-broker-j by apache.

the class AMQPConnection_0_8Impl method processSaslResponse.

private void processSaslResponse(final byte[] response, final SubjectCreator subjectCreator) {
    MethodRegistry methodRegistry = getMethodRegistry();
    SubjectAuthenticationResult authResult = _successfulAuthenticationResult;
    byte[] challenge = null;
    if (authResult == null) {
        authResult = subjectCreator.authenticate(_saslNegotiator, response);
        challenge = authResult.getChallenge();
    }
    switch(authResult.getStatus()) {
        case ERROR:
            Exception cause = authResult.getCause();
            LOGGER.debug("Authentication failed: {}", (cause == null ? "" : cause.getMessage()));
            sendConnectionClose(ErrorCodes.NOT_ALLOWED, "Authentication failed", 0);
            disposeSaslNegotiator();
            break;
        case SUCCESS:
            _successfulAuthenticationResult = authResult;
            if (challenge == null || challenge.length == 0) {
                LOGGER.debug("Connected as: {}", authResult.getSubject());
                setSubject(authResult.getSubject());
                int frameMax = getDefaultMaxFrameSize();
                if (frameMax <= 0) {
                    frameMax = Integer.MAX_VALUE;
                }
                ConnectionTuneBody tuneBody = methodRegistry.createConnectionTuneBody(getPort().getSessionCountLimit(), frameMax, getPort().getHeartbeatDelay());
                writeFrame(tuneBody.generateFrame(0));
                _state = ConnectionState.AWAIT_TUNE_OK;
                disposeSaslNegotiator();
            } else {
                continueSaslNegotiation(challenge);
            }
            break;
        case CONTINUE:
            continueSaslNegotiation(challenge);
            break;
    }
}
Also used : SubjectAuthenticationResult(org.apache.qpid.server.security.auth.SubjectAuthenticationResult) QpidException(org.apache.qpid.server.QpidException) StoreException(org.apache.qpid.server.store.StoreException) VirtualHostUnavailableException(org.apache.qpid.server.virtualhost.VirtualHostUnavailableException) AccessControlException(java.security.AccessControlException) ConnectionScopedRuntimeException(org.apache.qpid.server.util.ConnectionScopedRuntimeException) ServerScopedRuntimeException(org.apache.qpid.server.util.ServerScopedRuntimeException) NoSuchElementException(java.util.NoSuchElementException) IOException(java.io.IOException) TransportException(org.apache.qpid.server.transport.TransportException)

Example 7 with SubjectAuthenticationResult

use of org.apache.qpid.server.security.auth.SubjectAuthenticationResult in project qpid-broker-j by apache.

the class ServerConnectionDelegate method secure.

protected void secure(final ServerConnection sconn, final byte[] response) {
    SubjectAuthenticationResult authResult = _successfulAuthenticationResult;
    byte[] challenge = null;
    if (authResult == null) {
        authResult = _subjectCreator.authenticate(_saslNegotiator, response);
        challenge = authResult.getChallenge();
    }
    if (AuthenticationStatus.SUCCESS.equals(authResult.getStatus())) {
        _successfulAuthenticationResult = authResult;
        if (challenge == null || challenge.length == 0) {
            sconn.sendConnectionTune(getChannelMax(), getFrameMax(), 0, getHeartbeatMax());
            sconn.setAuthorizedSubject(authResult.getSubject());
            _state = ConnectionState.AWAIT_TUNE_OK;
            disposeSaslNegotiator();
        } else {
            sconn.sendConnectionSecure(authResult.getChallenge());
            _state = ConnectionState.AWAIT_SECURE_OK;
        }
    } else if (AuthenticationStatus.CONTINUE.equals(authResult.getStatus())) {
        sconn.sendConnectionSecure(authResult.getChallenge());
        _state = ConnectionState.AWAIT_SECURE_OK;
    } else {
        connectionAuthFailed(sconn, authResult.getCause());
    }
}
Also used : SubjectAuthenticationResult(org.apache.qpid.server.security.auth.SubjectAuthenticationResult)

Example 8 with SubjectAuthenticationResult

use of org.apache.qpid.server.security.auth.SubjectAuthenticationResult in project qpid-broker-j by apache.

the class AMQPConnection_0_8Test method setUp.

@Override
public void setUp() throws Exception {
    super.setUp();
    EventLogger value = new EventLogger();
    SystemConfig systemConfig = mock(SystemConfig.class);
    when(systemConfig.getEventLogger()).thenReturn(mock(EventLogger.class));
    _taskExecutor = new TaskExecutorImpl();
    _taskExecutor.start();
    Model model = BrokerModel.getInstance();
    _broker = mock(Broker.class);
    when(_broker.getParent()).thenReturn(systemConfig);
    when(_broker.getModel()).thenReturn(model);
    when(_broker.getCategoryClass()).thenReturn(Broker.class);
    when(_broker.getTaskExecutor()).thenReturn(_taskExecutor);
    when(_broker.getChildExecutor()).thenReturn(_taskExecutor);
    when(_broker.getEventLogger()).thenReturn(value);
    when(_broker.getContextValue(eq(Long.class), eq(Broker.CHANNEL_FLOW_CONTROL_ENFORCEMENT_TIMEOUT))).thenReturn(0l);
    _virtualHostNode = mock(VirtualHostNode.class);
    when(_virtualHostNode.getParent()).thenReturn(_broker);
    when(_virtualHostNode.getModel()).thenReturn(model);
    when(_virtualHostNode.getCategoryClass()).thenReturn(VirtualHostNode.class);
    when(_virtualHostNode.getTaskExecutor()).thenReturn(_taskExecutor);
    when(_virtualHostNode.getChildExecutor()).thenReturn(_taskExecutor);
    _virtualHost = mock(QueueManagingVirtualHost.class);
    VirtualHostPrincipal virtualHostPrincipal = new VirtualHostPrincipal(_virtualHost);
    when(_virtualHost.getParent()).thenReturn(_virtualHostNode);
    when(_virtualHost.getModel()).thenReturn(model);
    when(_virtualHost.getCategoryClass()).thenReturn(VirtualHost.class);
    when(_virtualHost.getState()).thenReturn(State.ACTIVE);
    when(_virtualHost.isActive()).thenReturn(true);
    when(_virtualHost.getTaskExecutor()).thenReturn(_taskExecutor);
    when(_virtualHost.getPrincipal()).thenReturn(virtualHostPrincipal);
    when(_virtualHost.getContextValue(Integer.class, Broker.MESSAGE_COMPRESSION_THRESHOLD_SIZE)).thenReturn(1024);
    when(_virtualHost.getContextValue(Long.class, Connection.MAX_UNCOMMITTED_IN_MEMORY_SIZE)).thenReturn(1024l);
    when(_virtualHost.getContextValue(Boolean.class, Broker.BROKER_MSG_AUTH)).thenReturn(false);
    when(_virtualHost.authoriseCreateConnection(any(AMQPConnection.class))).thenReturn(true);
    when(_virtualHost.getEventLogger()).thenReturn(value);
    SubjectCreator subjectCreator = mock(SubjectCreator.class);
    SaslNegotiator saslNegotiator = mock(SaslNegotiator.class);
    when(subjectCreator.createSaslNegotiator(eq(SASL_MECH.toString()), any(SaslSettings.class))).thenReturn(saslNegotiator);
    when(subjectCreator.authenticate(saslNegotiator, SASL_RESPONSE)).thenReturn(new SubjectAuthenticationResult(new AuthenticationResult(new AuthenticatedPrincipal(new UsernamePrincipal("username", null))), new Subject()));
    AuthenticationProvider authenticationProvider = mock(AuthenticationProvider.class);
    when(authenticationProvider.getAvailableMechanisms(anyBoolean())).thenReturn(Collections.singletonList(SASL_MECH.toString()));
    _port = mock(AmqpPort.class);
    when(_port.getParent()).thenReturn(_broker);
    when(_port.getCategoryClass()).thenReturn(Port.class);
    when(_port.getChildExecutor()).thenReturn(_taskExecutor);
    when(_port.getModel()).thenReturn(model);
    when(_port.getAuthenticationProvider()).thenReturn(authenticationProvider);
    when(_port.getAddressSpace(VIRTUAL_HOST_NAME)).thenReturn(_virtualHost);
    when(_port.getContextValue(Long.class, Port.CONNECTION_MAXIMUM_AUTHENTICATION_DELAY)).thenReturn(2500l);
    when(_port.getContextValue(Integer.class, Connection.MAX_MESSAGE_SIZE)).thenReturn(Connection.DEFAULT_MAX_MESSAGE_SIZE);
    when(_port.getSubjectCreator(eq(false), anyString())).thenReturn(subjectCreator);
    _sender = mock(ByteBufferSender.class);
    _network = mock(ServerNetworkConnection.class);
    when(_network.getSender()).thenReturn(_sender);
    when(_network.getLocalAddress()).thenReturn(new InetSocketAddress("localhost", 12345));
    _transport = Transport.TCP;
    _protocol = Protocol.AMQP_0_8;
    _ticker = new AggregateTicker();
}
Also used : ByteBufferSender(org.apache.qpid.server.transport.ByteBufferSender) ServerNetworkConnection(org.apache.qpid.server.transport.ServerNetworkConnection) SystemConfig(org.apache.qpid.server.model.SystemConfig) TaskExecutorImpl(org.apache.qpid.server.configuration.updater.TaskExecutorImpl) Broker(org.apache.qpid.server.model.Broker) QueueManagingVirtualHost(org.apache.qpid.server.virtualhost.QueueManagingVirtualHost) EventLogger(org.apache.qpid.server.logging.EventLogger) InetSocketAddress(java.net.InetSocketAddress) AuthenticationProvider(org.apache.qpid.server.model.AuthenticationProvider) AggregateTicker(org.apache.qpid.server.transport.AggregateTicker) SubjectAuthenticationResult(org.apache.qpid.server.security.auth.SubjectAuthenticationResult) Subject(javax.security.auth.Subject) AuthenticationResult(org.apache.qpid.server.security.auth.AuthenticationResult) SubjectAuthenticationResult(org.apache.qpid.server.security.auth.SubjectAuthenticationResult) AuthenticatedPrincipal(org.apache.qpid.server.security.auth.AuthenticatedPrincipal) SaslSettings(org.apache.qpid.server.security.auth.sasl.SaslSettings) UsernamePrincipal(org.apache.qpid.server.security.auth.UsernamePrincipal) AMQPConnection(org.apache.qpid.server.transport.AMQPConnection) BrokerModel(org.apache.qpid.server.model.BrokerModel) Model(org.apache.qpid.server.model.Model) VirtualHostPrincipal(org.apache.qpid.server.virtualhost.VirtualHostPrincipal) SaslNegotiator(org.apache.qpid.server.security.auth.sasl.SaslNegotiator) AmqpPort(org.apache.qpid.server.model.port.AmqpPort) SubjectCreator(org.apache.qpid.server.security.SubjectCreator) VirtualHostNode(org.apache.qpid.server.model.VirtualHostNode)

Example 9 with SubjectAuthenticationResult

use of org.apache.qpid.server.security.auth.SubjectAuthenticationResult in project qpid-broker-j by apache.

the class BasicAuthPreemptiveAuthenticator method attemptAuthentication.

@Override
public Subject attemptAuthentication(final HttpServletRequest request, final HttpManagementConfiguration managementConfiguration) {
    String header = request.getHeader("Authorization");
    final Port<?> port = managementConfiguration.getPort(request);
    final AuthenticationProvider<?> authenticationProvider = managementConfiguration.getAuthenticationProvider(request);
    SubjectCreator subjectCreator = port.getSubjectCreator(request.isSecure(), request.getServerName());
    if (header != null && authenticationProvider instanceof UsernamePasswordAuthenticationProvider) {
        UsernamePasswordAuthenticationProvider<?> namePasswdAuthProvider = (UsernamePasswordAuthenticationProvider<?>) authenticationProvider;
        String[] tokens = header.split("\\s");
        if (tokens.length >= 2 && "BASIC".equalsIgnoreCase(tokens[0])) {
            boolean isBasicAuthSupported = false;
            if (request.isSecure()) {
                isBasicAuthSupported = managementConfiguration.isHttpsBasicAuthenticationEnabled();
            } else {
                isBasicAuthSupported = managementConfiguration.isHttpBasicAuthenticationEnabled();
            }
            if (isBasicAuthSupported) {
                String base64UsernameAndPassword = tokens[1];
                String[] credentials = (new String(Strings.decodeBase64(base64UsernameAndPassword), StandardCharsets.UTF_8)).split(":", 2);
                if (credentials.length == 2) {
                    String username = credentials[0];
                    String password = credentials[1];
                    AuthenticationResult authenticationResult = namePasswdAuthProvider.authenticate(username, password);
                    SubjectAuthenticationResult result = subjectCreator.createResultWithGroups(authenticationResult);
                    return result.getSubject();
                }
            }
        }
    }
    return null;
}
Also used : SubjectCreator(org.apache.qpid.server.security.SubjectCreator) UsernamePasswordAuthenticationProvider(org.apache.qpid.server.security.auth.manager.UsernamePasswordAuthenticationProvider) SubjectAuthenticationResult(org.apache.qpid.server.security.auth.SubjectAuthenticationResult) SubjectAuthenticationResult(org.apache.qpid.server.security.auth.SubjectAuthenticationResult) AuthenticationResult(org.apache.qpid.server.security.auth.AuthenticationResult)

Example 10 with SubjectAuthenticationResult

use of org.apache.qpid.server.security.auth.SubjectAuthenticationResult in project qpid-broker-j by apache.

the class OAuth2InteractiveAuthenticator method getAuthenticationHandler.

@Override
public AuthenticationHandler getAuthenticationHandler(final HttpServletRequest request, final HttpManagementConfiguration configuration) {
    final Port<?> port = configuration.getPort(request);
    if (configuration.getAuthenticationProvider(request) instanceof OAuth2AuthenticationProvider) {
        final OAuth2AuthenticationProvider oauth2Provider = (OAuth2AuthenticationProvider) configuration.getAuthenticationProvider(request);
        final Map<String, String> requestParameters;
        try {
            requestParameters = getRequestParameters(request);
        } catch (IllegalArgumentException e) {
            return new FailedAuthenticationHandler(400, "Some request parameters are included more than once " + request, e);
        }
        String error = requestParameters.get("error");
        if (error != null) {
            int responseCode = decodeErrorAsResponseCode(error);
            String errorDescription = requestParameters.get("error_description");
            if (responseCode == 403) {
                LOGGER.debug("Resource owner denies the access request");
                return new FailedAuthenticationHandler(responseCode, "Resource owner denies the access request");
            } else {
                LOGGER.warn("Authorization endpoint failed, error : '{}', error description '{}'", error, errorDescription);
                return new FailedAuthenticationHandler(responseCode, String.format("Authorization request failed :'%s'", error));
            }
        }
        final String authorizationCode = requestParameters.get("code");
        if (authorizationCode == null) {
            final String authorizationRedirectURL = buildAuthorizationRedirectURL(request, oauth2Provider);
            return response -> {
                final NamedAddressSpace addressSpace = configuration.getPort(request).getAddressSpace(request.getServerName());
                LOGGER.debug("Sending redirect to authorization endpoint {}", oauth2Provider.getAuthorizationEndpointURI(addressSpace));
                response.sendRedirect(authorizationRedirectURL);
            };
        } else {
            final HttpSession httpSession = request.getSession();
            String state = requestParameters.get("state");
            if (state == null) {
                LOGGER.warn("Deny login attempt with wrong state: {}", state);
                return new FailedAuthenticationHandler(400, "No state set on request with authorization code grant: " + request);
            }
            if (!checkState(request, state)) {
                LOGGER.warn("Deny login attempt with wrong state: {}", state);
                return new FailedAuthenticationHandler(401, "Received request with wrong state: " + state);
            }
            final String redirectUri = (String) httpSession.getAttribute(HttpManagementUtil.getRequestSpecificAttributeName(REDIRECT_URI_SESSION_ATTRIBUTE, request));
            final String originalRequestUri = (String) httpSession.getAttribute(HttpManagementUtil.getRequestSpecificAttributeName(ORIGINAL_REQUEST_URI_SESSION_ATTRIBUTE, request));
            final NamedAddressSpace addressSpace = configuration.getPort(request).getAddressSpace(request.getServerName());
            return new AuthenticationHandler() {

                @Override
                public void handleAuthentication(final HttpServletResponse response) throws IOException {
                    AuthenticationResult authenticationResult = oauth2Provider.authenticateViaAuthorizationCode(authorizationCode, redirectUri, addressSpace);
                    try {
                        Subject subject = createSubject(authenticationResult);
                        authoriseManagement(subject);
                        HttpManagementUtil.saveAuthorisedSubject(request, subject);
                        LOGGER.debug("Successful login. Redirect to original resource {}", originalRequestUri);
                        response.sendRedirect(originalRequestUri);
                    } catch (SecurityException e) {
                        if (e instanceof AccessControlException) {
                            LOGGER.info("User '{}' is not authorised for management", authenticationResult.getMainPrincipal());
                            response.sendError(403, "User is not authorised for management");
                        } else {
                            LOGGER.info("Authentication failed", authenticationResult.getCause());
                            response.sendError(401);
                        }
                    }
                }

                private Subject createSubject(final AuthenticationResult authenticationResult) {
                    SubjectCreator subjectCreator = port.getSubjectCreator(request.isSecure(), request.getServerName());
                    SubjectAuthenticationResult result = subjectCreator.createResultWithGroups(authenticationResult);
                    Subject original = result.getSubject();
                    if (original == null) {
                        throw new SecurityException("Only authenticated users can access the management interface");
                    }
                    Subject subject = HttpManagementUtil.createServletConnectionSubject(request, original);
                    return subject;
                }

                private void authoriseManagement(final Subject subject) {
                    Broker broker = (Broker) oauth2Provider.getParent();
                    HttpManagementUtil.assertManagementAccess(broker, subject);
                }
            };
        }
    } else {
        return null;
    }
}
Also used : HttpManagementUtil(org.apache.qpid.server.management.plugin.HttpManagementUtil) Enumeration(java.util.Enumeration) URISyntaxException(java.net.URISyntaxException) LoggerFactory(org.slf4j.LoggerFactory) HashMap(java.util.HashMap) AuthenticationResult(org.apache.qpid.server.security.auth.AuthenticationResult) SecureRandom(java.security.SecureRandom) HttpServletRequest(javax.servlet.http.HttpServletRequest) HttpRequestInteractiveAuthenticator(org.apache.qpid.server.management.plugin.HttpRequestInteractiveAuthenticator) OAuth2Utils(org.apache.qpid.server.security.auth.manager.oauth2.OAuth2Utils) Map(java.util.Map) URI(java.net.URI) HttpSession(javax.servlet.http.HttpSession) SubjectAuthenticationResult(org.apache.qpid.server.security.auth.SubjectAuthenticationResult) Logger(org.slf4j.Logger) Port(org.apache.qpid.server.model.Port) OAuth2AuthenticationProvider(org.apache.qpid.server.security.auth.manager.oauth2.OAuth2AuthenticationProvider) Broker(org.apache.qpid.server.model.Broker) HttpServletResponse(javax.servlet.http.HttpServletResponse) IOException(java.io.IOException) HttpManagementConfiguration(org.apache.qpid.server.management.plugin.HttpManagementConfiguration) Subject(javax.security.auth.Subject) SubjectCreator(org.apache.qpid.server.security.SubjectCreator) PluggableService(org.apache.qpid.server.plugin.PluggableService) NamedAddressSpace(org.apache.qpid.server.model.NamedAddressSpace) AccessControlException(java.security.AccessControlException) Collections(java.util.Collections) DatatypeConverter(javax.xml.bind.DatatypeConverter) Broker(org.apache.qpid.server.model.Broker) HttpSession(javax.servlet.http.HttpSession) NamedAddressSpace(org.apache.qpid.server.model.NamedAddressSpace) HttpServletResponse(javax.servlet.http.HttpServletResponse) AccessControlException(java.security.AccessControlException) Subject(javax.security.auth.Subject) SubjectAuthenticationResult(org.apache.qpid.server.security.auth.SubjectAuthenticationResult) AuthenticationResult(org.apache.qpid.server.security.auth.AuthenticationResult) SubjectAuthenticationResult(org.apache.qpid.server.security.auth.SubjectAuthenticationResult) OAuth2AuthenticationProvider(org.apache.qpid.server.security.auth.manager.oauth2.OAuth2AuthenticationProvider) SubjectCreator(org.apache.qpid.server.security.SubjectCreator)

Aggregations

SubjectAuthenticationResult (org.apache.qpid.server.security.auth.SubjectAuthenticationResult)14 AuthenticationResult (org.apache.qpid.server.security.auth.AuthenticationResult)8 Subject (javax.security.auth.Subject)7 SubjectCreator (org.apache.qpid.server.security.SubjectCreator)6 Broker (org.apache.qpid.server.model.Broker)4 AuthenticatedPrincipal (org.apache.qpid.server.security.auth.AuthenticatedPrincipal)4 OAuth2AuthenticationProvider (org.apache.qpid.server.security.auth.manager.oauth2.OAuth2AuthenticationProvider)4 IOException (java.io.IOException)3 URISyntaxException (java.net.URISyntaxException)3 AccessControlException (java.security.AccessControlException)3 UsernamePrincipal (org.apache.qpid.server.security.auth.UsernamePrincipal)3 URI (java.net.URI)2 SecureRandom (java.security.SecureRandom)2 InetSocketAddress (java.net.InetSocketAddress)1 Principal (java.security.Principal)1 Collections (java.util.Collections)1 Enumeration (java.util.Enumeration)1 HashMap (java.util.HashMap)1 LinkedHashMap (java.util.LinkedHashMap)1 Map (java.util.Map)1