Search in sources :

Example 21 with Broker

use of org.apache.qpid.server.model.Broker in project qpid-broker-j by apache.

the class BrokerStoreUpgraderAndRecoverer method upgradeAndRecover.

@Override
public Broker<?> upgradeAndRecover(List<ConfiguredObjectRecord> records) {
    final DurableConfigurationStore store = _systemConfig.getConfigurationStore();
    List<ConfiguredObjectRecord> upgradedRecords = upgrade(store, records);
    new GenericRecoverer(_systemConfig).recover(upgradedRecords, false);
    final StoreConfigurationChangeListener configChangeListener = new StoreConfigurationChangeListener(store);
    applyRecursively(_systemConfig.getContainer(Broker.class), new RecursiveAction<ConfiguredObject<?>>() {

        @Override
        public void performAction(final ConfiguredObject<?> object) {
            object.addChangeListener(configChangeListener);
        }

        @Override
        public boolean applyToChildren(ConfiguredObject<?> object) {
            return !object.managesChildStorage();
        }
    });
    return _systemConfig.getContainer(Broker.class);
}
Also used : Broker(org.apache.qpid.server.model.Broker) ConfiguredObject(org.apache.qpid.server.model.ConfiguredObject) StoreConfigurationChangeListener(org.apache.qpid.server.configuration.store.StoreConfigurationChangeListener)

Example 22 with Broker

use of org.apache.qpid.server.model.Broker in project qpid-broker-j by apache.

the class TCPandSSLTransportTest method checkHandshakeWithTlsProtocol.

private void checkHandshakeWithTlsProtocol(String clientProtocol, final Transport... transports) throws Exception {
    KeyStore keyStore = KeyStore.getInstance("JKS");
    keyStore.load(new ByteArrayInputStream(Base64.getDecoder().decode(KEYSTORE_STRING)), "password".toCharArray());
    final SSLContext sslContext = SSLContext.getInstance("TLS");
    KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
    kmf.init(keyStore, "password".toCharArray());
    sslContext.init(kmf.getKeyManagers(), null, null);
    final AmqpPort<?> port = mock(AmqpPort.class);
    when(port.getPort()).thenReturn(0);
    when(port.getName()).thenReturn("testAmqp");
    when(port.getNetworkBufferSize()).thenReturn(64 * 1024);
    when(port.acceptNewConnectionAndIncrementCount(any(SocketAddress.class))).thenReturn(true);
    when(port.getThreadPoolSize()).thenReturn(2);
    when(port.getNumberOfSelectors()).thenReturn(1);
    when(port.getSSLContext()).thenReturn(sslContext);
    when(port.getContextValue(Long.class, AmqpPort.PORT_AMQP_THREAD_POOL_KEEP_ALIVE_TIMEOUT)).thenReturn(1L);
    when(port.getContextValue(Integer.class, AmqpPort.PORT_AMQP_ACCEPT_BACKLOG)).thenReturn(AmqpPort.DEFAULT_PORT_AMQP_ACCEPT_BACKLOG);
    when(port.getProtocolHandshakeTimeout()).thenReturn(AmqpPort.DEFAULT_PROTOCOL_HANDSHAKE_TIMEOUT);
    when(port.getContextValue(Boolean.class, AmqpPort.PORT_DIAGNOSIS_OF_SSL_ENGINE_LOOPING)).thenReturn(false);
    when(port.getContextValue(Integer.class, AmqpPort.PORT_DIAGNOSIS_OF_SSL_ENGINE_LOOPING_WARN_THRESHOLD)).thenReturn(1000);
    when(port.getContextValue(Integer.class, AmqpPort.PORT_DIAGNOSIS_OF_SSL_ENGINE_LOOPING_BREAK_THRESHOLD)).thenReturn(1005);
    ObjectMapper mapper = new ObjectMapper();
    JavaType type = mapper.getTypeFactory().constructCollectionType(List.class, String.class);
    List<String> allowList = mapper.readValue(Broker.DEFAULT_SECURITY_TLS_PROTOCOL_ALLOW_LIST, type);
    List<String> denyList = mapper.readValue(Broker.DEFAULT_SECURITY_TLS_PROTOCOL_DENY_LIST, type);
    when(port.getTlsProtocolDenyList()).thenReturn(denyList);
    when(port.getTlsProtocolAllowList()).thenReturn(allowList);
    final Broker broker = mock(Broker.class);
    when(broker.getEventLogger()).thenReturn(mock(EventLogger.class));
    when(port.getParent()).thenReturn(broker);
    TCPandSSLTransport transport = new TCPandSSLTransport(new HashSet<>(Arrays.asList(transports)), port, new HashSet<>(Arrays.asList(Protocol.AMQP_0_8, Protocol.AMQP_0_9, Protocol.AMQP_0_9_1, Protocol.AMQP_0_10, Protocol.AMQP_1_0)), Protocol.AMQP_0_9_1);
    transport.start();
    SSLContext clientContext = SSLContext.getInstance("TLS");
    TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    tmf.init(keyStore);
    clientContext.init(null, tmf.getTrustManagers(), null);
    try (SSLSocket sslSocket = (SSLSocket) clientContext.getSocketFactory().createSocket(InetAddress.getLoopbackAddress(), transport.getAcceptingPort())) {
        sslSocket.setEnabledProtocols(new String[] { clientProtocol });
        sslSocket.startHandshake();
    } finally {
        transport.close();
    }
}
Also used : Broker(org.apache.qpid.server.model.Broker) EventLogger(org.apache.qpid.server.logging.EventLogger) SSLSocket(javax.net.ssl.SSLSocket) SSLContext(javax.net.ssl.SSLContext) KeyStore(java.security.KeyStore) KeyManagerFactory(javax.net.ssl.KeyManagerFactory) JavaType(com.fasterxml.jackson.databind.JavaType) ByteArrayInputStream(java.io.ByteArrayInputStream) TrustManagerFactory(javax.net.ssl.TrustManagerFactory) SocketAddress(java.net.SocketAddress) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper)

Example 23 with Broker

use of org.apache.qpid.server.model.Broker in project qpid-broker-j by apache.

the class AnonymousInteractiveAuthenticator method getLoginHandler.

private void getLoginHandler(final HttpServletRequest request, final HttpServletResponse response, final AnonymousAuthenticationManager authenticationProvider, final Port<?> port) throws ServletException, IOException {
    final AuthenticationResult authenticationResult = authenticationProvider.getAnonymousAuthenticationResult();
    try {
        final SubjectAuthenticationResult result = port.getSubjectCreator(request.isSecure(), request.getServerName()).createResultWithGroups(authenticationResult);
        final Subject original = result.getSubject();
        if (original == null) {
            throw new SecurityException("Only authenticated users can access the management interface");
        }
        final Broker broker = (Broker) authenticationProvider.getParent();
        HttpManagementUtil.createServletConnectionSubjectAssertManagementAccessAndSave(broker, request, original);
        request.getRequestDispatcher(HttpManagement.DEFAULT_LOGIN_URL).forward(request, response);
    } catch (AccessControlException e) {
        LOGGER.info("User '{}' is not authorised for management", authenticationResult.getMainPrincipal());
        response.sendError(HttpServletResponse.SC_FORBIDDEN, "User is not authorised for management");
    } catch (SecurityException e) {
        LOGGER.info("Authentication failed", authenticationResult.getCause());
        response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
    }
}
Also used : Broker(org.apache.qpid.server.model.Broker) AccessControlException(java.security.AccessControlException) SubjectAuthenticationResult(org.apache.qpid.server.security.auth.SubjectAuthenticationResult) Subject(javax.security.auth.Subject) SubjectAuthenticationResult(org.apache.qpid.server.security.auth.SubjectAuthenticationResult) AuthenticationResult(org.apache.qpid.server.security.auth.AuthenticationResult)

Example 24 with Broker

use of org.apache.qpid.server.model.Broker 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 {
                        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");
                        }
                        Broker broker = (Broker) oauth2Provider.getParent();
                        HttpManagementUtil.createServletConnectionSubjectAssertManagementAccessAndSave(broker, request, original);
                        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);
                        }
                    }
                }
            };
        }
    } 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) Base64(java.util.Base64) 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) 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) 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) OAuth2AuthenticationProvider(org.apache.qpid.server.security.auth.manager.oauth2.OAuth2AuthenticationProvider) SubjectCreator(org.apache.qpid.server.security.SubjectCreator)

Example 25 with Broker

use of org.apache.qpid.server.model.Broker in project qpid-broker-j by apache.

the class VirtualHostNameAndLevelLogInclusionRuleImplTest method setUp.

@Before
public void setUp() throws Exception {
    _taskExecutor = new TaskExecutorImpl();
    _taskExecutor.start();
    Model model = BrokerModel.getInstance();
    Broker broker = mock(Broker.class);
    when(broker.getModel()).thenReturn(model);
    when(broker.getChildExecutor()).thenReturn(_taskExecutor);
    doReturn(Broker.class).when(broker).getCategoryClass();
    VirtualHostNode<?> node = mock(VirtualHostNode.class);
    when(node.getModel()).thenReturn(model);
    when(node.getChildExecutor()).thenReturn(_taskExecutor);
    when(node.getParent()).thenReturn(broker);
    doReturn(VirtualHostNode.class).when(node).getCategoryClass();
    when(_virtualhost.getModel()).thenReturn(model);
    when(_virtualhost.getParent()).thenReturn(node);
    doReturn(VirtualHost.class).when(_virtualhost).getCategoryClass();
    _virtualHostLogger = mock(VirtualHostLogger.class);
    when(_virtualHostLogger.getModel()).thenReturn(model);
    when(_virtualHostLogger.getChildExecutor()).thenReturn(_taskExecutor);
    when(_virtualHostLogger.getParent()).thenReturn(_virtualhost);
    doReturn(VirtualHostLogger.class).when(_virtualHostLogger).getCategoryClass();
}
Also used : TaskExecutorImpl(org.apache.qpid.server.configuration.updater.TaskExecutorImpl) VirtualHostLogger(org.apache.qpid.server.model.VirtualHostLogger) Broker(org.apache.qpid.server.model.Broker) BrokerModel(org.apache.qpid.server.model.BrokerModel) Model(org.apache.qpid.server.model.Model) Before(org.junit.Before)

Aggregations

Broker (org.apache.qpid.server.model.Broker)38 ConfiguredObject (org.apache.qpid.server.model.ConfiguredObject)15 EventLogger (org.apache.qpid.server.logging.EventLogger)13 Before (org.junit.Before)11 Test (org.junit.Test)8 Subject (javax.security.auth.Subject)7 HashMap (java.util.HashMap)6 TaskExecutor (org.apache.qpid.server.configuration.updater.TaskExecutor)6 VirtualHost (org.apache.qpid.server.model.VirtualHost)6 VirtualHostNode (org.apache.qpid.server.model.VirtualHostNode)6 CurrentThreadTaskExecutor (org.apache.qpid.server.configuration.updater.CurrentThreadTaskExecutor)5 Model (org.apache.qpid.server.model.Model)5 TaskExecutorImpl (org.apache.qpid.server.configuration.updater.TaskExecutorImpl)4 SubjectAuthenticationResult (org.apache.qpid.server.security.auth.SubjectAuthenticationResult)4 DurableConfigurationStore (org.apache.qpid.server.store.DurableConfigurationStore)4 AccessControlException (java.security.AccessControlException)3 Principal (java.security.Principal)3 SSLContext (javax.net.ssl.SSLContext)3 BrokerModel (org.apache.qpid.server.model.BrokerModel)3 Queue (org.apache.qpid.server.model.Queue)3