Search in sources :

Example 1 with SubjectCreator

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

the class OAuth2InteractiveAuthenticatorTest method createMockOAuth2AuthenticationProvider.

private OAuth2AuthenticationProvider<?> createMockOAuth2AuthenticationProvider(final HttpPort mockPort) throws URISyntaxException {
    OAuth2AuthenticationProvider authenticationProvider = mock(OAuth2AuthenticationProvider.class);
    Broker mockBroker = mock(Broker.class);
    SubjectCreator mockSubjectCreator = mock(SubjectCreator.class);
    when(_mockPort.getSubjectCreator(anyBoolean(), anyString())).thenReturn(mockSubjectCreator);
    SubjectAuthenticationResult mockSuccessfulSubjectAuthenticationResult = mock(SubjectAuthenticationResult.class);
    SubjectAuthenticationResult mockUnauthorizedSubjectAuthenticationResult = mock(SubjectAuthenticationResult.class);
    final Subject successfulSubject = new Subject(true, Collections.singleton(new AuthenticatedPrincipal(new UsernamePrincipal(TEST_AUTHORIZED_USER, null))), Collections.emptySet(), Collections.emptySet());
    final Subject unauthorizedSubject = new Subject(true, Collections.singleton(new AuthenticatedPrincipal(new UsernamePrincipal(TEST_UNAUTHORIZED_USER, null))), Collections.emptySet(), Collections.emptySet());
    AuthenticationResult mockSuccessfulAuthenticationResult = mock(AuthenticationResult.class);
    AuthenticationResult mockUnauthorizedAuthenticationResult = mock(AuthenticationResult.class);
    AuthenticationResult failedAuthenticationResult = new AuthenticationResult(AuthenticationResult.AuthenticationStatus.ERROR, new Exception("authentication failed"));
    SubjectAuthenticationResult failedSubjectAuthenticationResult = new SubjectAuthenticationResult(failedAuthenticationResult);
    doAnswer(new Answer() {

        @Override
        public Object answer(final InvocationOnMock invocationOnMock) throws Throwable {
            final Subject subject = Subject.getSubject(AccessController.getContext());
            if (!subject.getPrincipals().iterator().next().getName().equals(TEST_AUTHORIZED_USER)) {
                throw new AccessControlException("access denied");
            }
            return null;
        }
    }).when(mockBroker).authorise(eq(Operation.PERFORM_ACTION("manage")));
    when(authenticationProvider.getAuthorizationEndpointURI(any())).thenReturn(new URI(TEST_AUTHORIZATION_ENDPOINT));
    when(authenticationProvider.getClientId()).thenReturn(TEST_CLIENT_ID);
    when(authenticationProvider.getScope()).thenReturn(TEST_OAUTH2_SCOPE);
    when(authenticationProvider.getParent()).thenReturn(mockBroker);
    when(authenticationProvider.authenticateViaAuthorizationCode(matches(TEST_VALID_AUTHORIZATION_CODE), matches(TEST_REQUEST_HOST), any())).thenReturn(mockSuccessfulAuthenticationResult);
    when(authenticationProvider.authenticateViaAuthorizationCode(matches(TEST_INVALID_AUTHORIZATION_CODE), matches(TEST_REQUEST_HOST), any())).thenReturn(failedAuthenticationResult);
    when(authenticationProvider.authenticateViaAuthorizationCode(matches(TEST_UNAUTHORIZED_AUTHORIZATION_CODE), matches(TEST_REQUEST_HOST), any())).thenReturn(mockUnauthorizedAuthenticationResult);
    when(mockSuccessfulSubjectAuthenticationResult.getSubject()).thenReturn(successfulSubject);
    when(mockUnauthorizedSubjectAuthenticationResult.getSubject()).thenReturn(unauthorizedSubject);
    when(mockSubjectCreator.createResultWithGroups(mockSuccessfulAuthenticationResult)).thenReturn(mockSuccessfulSubjectAuthenticationResult);
    when(mockSubjectCreator.createResultWithGroups(mockUnauthorizedAuthenticationResult)).thenReturn(mockUnauthorizedSubjectAuthenticationResult);
    when(mockSubjectCreator.createResultWithGroups(failedAuthenticationResult)).thenReturn(failedSubjectAuthenticationResult);
    return authenticationProvider;
}
Also used : Broker(org.apache.qpid.server.model.Broker) AccessControlException(java.security.AccessControlException) HttpURI(org.eclipse.jetty.http.HttpURI) URI(java.net.URI) SubjectAuthenticationResult(org.apache.qpid.server.security.auth.SubjectAuthenticationResult) Subject(javax.security.auth.Subject) URISyntaxException(java.net.URISyntaxException) IOException(java.io.IOException) AccessControlException(java.security.AccessControlException) AuthenticatedPrincipal(org.apache.qpid.server.security.auth.AuthenticatedPrincipal) AuthenticationResult(org.apache.qpid.server.security.auth.AuthenticationResult) SubjectAuthenticationResult(org.apache.qpid.server.security.auth.SubjectAuthenticationResult) UsernamePrincipal(org.apache.qpid.server.security.auth.UsernamePrincipal) Answer(org.mockito.stubbing.Answer) Mockito.doAnswer(org.mockito.Mockito.doAnswer) InvocationOnMock(org.mockito.invocation.InvocationOnMock) OAuth2AuthenticationProvider(org.apache.qpid.server.security.auth.manager.oauth2.OAuth2AuthenticationProvider) SubjectCreator(org.apache.qpid.server.security.SubjectCreator)

Example 2 with SubjectCreator

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

the class ProtocolEngine_1_0_0Test method setUp.

@Override
public void setUp() throws Exception {
    super.setUp();
    _networkConnection = mock(ServerNetworkConnection.class);
    when(_networkConnection.getLocalAddress()).thenReturn(new InetSocketAddress(0));
    _broker = mock(Broker.class);
    when(_broker.getModel()).thenReturn(BrokerModel.getInstance());
    when(_broker.getNetworkBufferSize()).thenReturn(256 * 1026);
    final TaskExecutor taskExecutor = new TaskExecutorImpl();
    taskExecutor.start();
    when(_broker.getChildExecutor()).thenReturn(taskExecutor);
    when(_broker.getTaskExecutor()).thenReturn(taskExecutor);
    when(_broker.getId()).thenReturn(UUID.randomUUID());
    when(_broker.getEventLogger()).thenReturn(new EventLogger());
    when(((Broker) _broker).getCategoryClass()).thenReturn(Broker.class);
    _port = mock(AmqpPort.class);
    when(_port.getChildExecutor()).thenReturn(taskExecutor);
    when(_port.getCategoryClass()).thenReturn(Port.class);
    when(_port.getModel()).thenReturn(BrokerModel.getInstance());
    final SubjectCreator subjectCreator = mock(SubjectCreator.class);
    _authenticationProvider = mock(AuthenticationProvider.class);
    when(_port.getAuthenticationProvider()).thenReturn(_authenticationProvider);
    _virtualHost = mock(VirtualHost.class);
    when(_virtualHost.getChildExecutor()).thenReturn(taskExecutor);
    when(_virtualHost.getModel()).thenReturn(BrokerModel.getInstance());
    when(_virtualHost.getState()).thenReturn(State.ACTIVE);
    when(_virtualHost.isActive()).thenReturn(true);
    final ArgumentCaptor<AMQPConnection> connectionCaptor = ArgumentCaptor.forClass(AMQPConnection.class);
    final ArgumentCaptor<ConnectionEstablishmentPolicy> establishmentPolicyCaptor = ArgumentCaptor.forClass(ConnectionEstablishmentPolicy.class);
    doAnswer(new Answer() {

        @Override
        public Object answer(final InvocationOnMock invocation) throws Throwable {
            _connection = connectionCaptor.getValue();
            return null;
        }
    }).when(_virtualHost).registerConnection(connectionCaptor.capture(), establishmentPolicyCaptor.capture());
    when(_virtualHost.getPrincipal()).thenReturn(mock(VirtualHostPrincipal.class));
    when(_port.getAddressSpace(anyString())).thenReturn(_virtualHost);
    when(_port.getSubjectCreator(anyBoolean(), anyString())).thenReturn(subjectCreator);
    final ArgumentCaptor<Principal> userCaptor = ArgumentCaptor.forClass(Principal.class);
    when(subjectCreator.createSubjectWithGroups(userCaptor.capture())).then(new Answer<Subject>() {

        @Override
        public Subject answer(final InvocationOnMock invocation) throws Throwable {
            Subject subject = new Subject();
            subject.getPrincipals().add(userCaptor.getValue());
            return subject;
        }
    });
    final ByteBufferSender sender = mock(ByteBufferSender.class);
    when(_networkConnection.getSender()).thenReturn(sender);
    AMQPDescribedTypeRegistry registry = AMQPDescribedTypeRegistry.newInstance().registerTransportLayer().registerMessagingLayer().registerTransactionLayer().registerSecurityLayer();
    _frameWriter = new FrameWriter(registry, new ByteBufferSender() {

        @Override
        public boolean isDirectBufferPreferred() {
            return false;
        }

        @Override
        public void send(final QpidByteBuffer msg) {
            _protocolEngine_1_0_0.received(msg);
        }

        @Override
        public void flush() {
        }

        @Override
        public void close() {
        }
    });
}
Also used : ByteBufferSender(org.apache.qpid.server.transport.ByteBufferSender) InetSocketAddress(java.net.InetSocketAddress) VirtualHostPrincipal(org.apache.qpid.server.virtualhost.VirtualHostPrincipal) AmqpPort(org.apache.qpid.server.model.port.AmqpPort) ServerNetworkConnection(org.apache.qpid.server.transport.ServerNetworkConnection) TaskExecutorImpl(org.apache.qpid.server.configuration.updater.TaskExecutorImpl) AMQPDescribedTypeRegistry(org.apache.qpid.server.protocol.v1_0.type.codec.AMQPDescribedTypeRegistry) Broker(org.apache.qpid.server.model.Broker) EventLogger(org.apache.qpid.server.logging.EventLogger) AuthenticationProvider(org.apache.qpid.server.model.AuthenticationProvider) Subject(javax.security.auth.Subject) FrameWriter(org.apache.qpid.server.protocol.v1_0.codec.FrameWriter) ConnectionEstablishmentPolicy(org.apache.qpid.server.virtualhost.ConnectionEstablishmentPolicy) Mockito.doAnswer(org.mockito.Mockito.doAnswer) Answer(org.mockito.stubbing.Answer) TaskExecutor(org.apache.qpid.server.configuration.updater.TaskExecutor) AMQPConnection(org.apache.qpid.server.transport.AMQPConnection) InvocationOnMock(org.mockito.invocation.InvocationOnMock) ConfiguredObject(org.apache.qpid.server.model.ConfiguredObject) QpidByteBuffer(org.apache.qpid.server.bytebuffer.QpidByteBuffer) VirtualHost(org.apache.qpid.server.model.VirtualHost) SubjectCreator(org.apache.qpid.server.security.SubjectCreator) VirtualHostPrincipal(org.apache.qpid.server.virtualhost.VirtualHostPrincipal) Principal(java.security.Principal) AuthenticatedPrincipal(org.apache.qpid.server.security.auth.AuthenticatedPrincipal)

Example 3 with SubjectCreator

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

the class SSLClientCertPreemptiveAuthenticator method attemptAuthentication.

@Override
public Subject attemptAuthentication(final HttpServletRequest request, final HttpManagementConfiguration managementConfig) {
    final AuthenticationProvider authenticationProvider = managementConfig.getAuthenticationProvider(request);
    final Port<?> port = managementConfig.getPort(request);
    SubjectCreator subjectCreator = port.getSubjectCreator(request.isSecure(), request.getServerName());
    if (request.isSecure() && authenticationProvider instanceof ExternalAuthenticationManager && Collections.list(request.getAttributeNames()).contains(CERTIFICATE_ATTRIBUTE_NAME)) {
        ExternalAuthenticationManager<?> externalAuthManager = (ExternalAuthenticationManager<?>) authenticationProvider;
        X509Certificate[] certificates = (X509Certificate[]) request.getAttribute(CERTIFICATE_ATTRIBUTE_NAME);
        if (certificates != null && certificates.length != 0) {
            Principal principal = certificates[0].getSubjectX500Principal();
            if (!externalAuthManager.getUseFullDN()) {
                String username;
                String dn = ((X500Principal) principal).getName(X500Principal.RFC2253);
                username = SSLUtil.getIdFromSubjectDN(dn);
                principal = new UsernamePrincipal(username, authenticationProvider);
            }
            return subjectCreator.createSubjectWithGroups(new AuthenticatedPrincipal(principal));
        }
    }
    return null;
}
Also used : UsernamePrincipal(org.apache.qpid.server.security.auth.UsernamePrincipal) AuthenticationProvider(org.apache.qpid.server.model.AuthenticationProvider) X500Principal(javax.security.auth.x500.X500Principal) ExternalAuthenticationManager(org.apache.qpid.server.security.auth.manager.ExternalAuthenticationManager) SubjectCreator(org.apache.qpid.server.security.SubjectCreator) X509Certificate(java.security.cert.X509Certificate) UsernamePrincipal(org.apache.qpid.server.security.auth.UsernamePrincipal) X500Principal(javax.security.auth.x500.X500Principal) Principal(java.security.Principal) AuthenticatedPrincipal(org.apache.qpid.server.security.auth.AuthenticatedPrincipal) AuthenticatedPrincipal(org.apache.qpid.server.security.auth.AuthenticatedPrincipal)

Example 4 with SubjectCreator

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

the class ProtocolEngine_1_0_0Test method testProtocolEngineWithSaslNonTLSandAnon.

public void testProtocolEngineWithSaslNonTLSandAnon() throws Exception {
    final Map<String, Object> attrs = Collections.singletonMap(ConfiguredObject.NAME, getTestName());
    final AnonymousAuthenticationManager anonymousAuthenticationManager = (new AnonymousAuthenticationManagerFactory()).create(null, attrs, _broker);
    when(_port.getAuthenticationProvider()).thenReturn(anonymousAuthenticationManager);
    when(_port.getSubjectCreator(anyBoolean(), anyString())).thenReturn(new SubjectCreator(anonymousAuthenticationManager, Collections.emptyList(), null));
    allowMechanisms(AnonymousAuthenticationManager.MECHANISM_NAME);
    createEngine(Transport.TCP);
    _protocolEngine_1_0_0.received(QpidByteBuffer.wrap(ProtocolEngineCreator_1_0_0_SASL.getInstance().getHeaderIdentifier()));
    SaslInit init = new SaslInit();
    init.setMechanism(Symbol.valueOf("ANONYMOUS"));
    _frameWriter.send(new SASLFrame(init));
    _protocolEngine_1_0_0.received(QpidByteBuffer.wrap(ProtocolEngineCreator_1_0_0.getInstance().getHeaderIdentifier()));
    Open open = new Open();
    open.setContainerId("testContainerId");
    _frameWriter.send(AMQFrame.createAMQFrame((short) 0, open));
    verify(_virtualHost).registerConnection(any(AMQPConnection.class), any(ConnectionEstablishmentPolicy.class));
    AuthenticatedPrincipal principal = (AuthenticatedPrincipal) _connection.getAuthorizedPrincipal();
    assertNotNull(principal);
    assertEquals(principal, new AuthenticatedPrincipal(anonymousAuthenticationManager.getAnonymousPrincipal()));
}
Also used : ConnectionEstablishmentPolicy(org.apache.qpid.server.virtualhost.ConnectionEstablishmentPolicy) AnonymousAuthenticationManagerFactory(org.apache.qpid.server.security.auth.manager.AnonymousAuthenticationManagerFactory) AnonymousAuthenticationManager(org.apache.qpid.server.security.auth.manager.AnonymousAuthenticationManager) AMQPConnection(org.apache.qpid.server.transport.AMQPConnection) SaslInit(org.apache.qpid.server.protocol.v1_0.type.security.SaslInit) SASLFrame(org.apache.qpid.server.protocol.v1_0.framing.SASLFrame) ConfiguredObject(org.apache.qpid.server.model.ConfiguredObject) Matchers.anyString(org.mockito.Matchers.anyString) SubjectCreator(org.apache.qpid.server.security.SubjectCreator) Open(org.apache.qpid.server.protocol.v1_0.type.transport.Open) AuthenticatedPrincipal(org.apache.qpid.server.security.auth.AuthenticatedPrincipal)

Example 5 with SubjectCreator

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

the class AMQPConnection_0_8Impl method receiveConnectionStartOk.

@Override
public void receiveConnectionStartOk(final FieldTable clientProperties, final AMQShortString mechanism, final byte[] response, final AMQShortString locale) {
    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("RECV ConnectionStartOk[" + " clientProperties: " + clientProperties + " mechanism: " + mechanism + " response: ********" + " locale: " + locale + " ]");
    }
    assertState(ConnectionState.AWAIT_START_OK);
    LOGGER.debug("SASL Mechanism selected: {} Locale : {}", mechanism, locale);
    if (mechanism == null || mechanism.length() == 0) {
        sendConnectionClose(ErrorCodes.CONNECTION_FORCED, "No Sasl mechanism was specified", 0);
        return;
    }
    SubjectCreator subjectCreator = getSubjectCreator();
    _saslNegotiator = subjectCreator.createSaslNegotiator(String.valueOf(mechanism), this);
    if (_saslNegotiator == null) {
        sendConnectionClose(ErrorCodes.CONNECTION_FORCED, "No SaslServer could be created for mechanism: " + mechanism, 0);
    } else {
        setClientProperties(clientProperties);
        processSaslResponse(response, subjectCreator);
    }
}
Also used : SubjectCreator(org.apache.qpid.server.security.SubjectCreator)

Aggregations

SubjectCreator (org.apache.qpid.server.security.SubjectCreator)13 AuthenticatedPrincipal (org.apache.qpid.server.security.auth.AuthenticatedPrincipal)6 AuthenticationResult (org.apache.qpid.server.security.auth.AuthenticationResult)6 SubjectAuthenticationResult (org.apache.qpid.server.security.auth.SubjectAuthenticationResult)6 Subject (javax.security.auth.Subject)5 AuthenticationProvider (org.apache.qpid.server.model.AuthenticationProvider)4 Broker (org.apache.qpid.server.model.Broker)4 UsernamePrincipal (org.apache.qpid.server.security.auth.UsernamePrincipal)4 OAuth2AuthenticationProvider (org.apache.qpid.server.security.auth.manager.oauth2.OAuth2AuthenticationProvider)4 URISyntaxException (java.net.URISyntaxException)3 AMQPConnection (org.apache.qpid.server.transport.AMQPConnection)3 IOException (java.io.IOException)2 InetSocketAddress (java.net.InetSocketAddress)2 URI (java.net.URI)2 AccessControlException (java.security.AccessControlException)2 Principal (java.security.Principal)2 HttpSession (javax.servlet.http.HttpSession)2 TaskExecutorImpl (org.apache.qpid.server.configuration.updater.TaskExecutorImpl)2 EventLogger (org.apache.qpid.server.logging.EventLogger)2 ConfiguredObject (org.apache.qpid.server.model.ConfiguredObject)2