Search in sources :

Example 1 with AuthenticatedPrincipal

use of org.apache.qpid.server.security.auth.AuthenticatedPrincipal 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 2 with AuthenticatedPrincipal

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

the class ConnectionAndUserPredicate method evaluate.

@Override
public final boolean evaluate(final ILoggingEvent event) {
    String userPrincipalString = "";
    String connectionString = "";
    String remoteContainerName = "";
    final Subject subject = Subject.getSubject(AccessController.getContext());
    final Set<SocketConnectionPrincipal> connectionPrincipals = subject.getPrincipals(SocketConnectionPrincipal.class);
    final Set<AuthenticatedPrincipal> userPrincipals = subject.getPrincipals(AuthenticatedPrincipal.class);
    if (!connectionPrincipals.isEmpty()) {
        final SocketConnectionPrincipal socketConnectionPrincipal = connectionPrincipals.iterator().next();
        connectionString = socketConnectionPrincipal.getName();
        if (socketConnectionPrincipal instanceof ConnectionPrincipal) {
            remoteContainerName = ((ConnectionPrincipal) socketConnectionPrincipal).getConnection().getRemoteContainerName();
            if (remoteContainerName == null) {
                remoteContainerName = "";
            }
        }
    }
    if (!userPrincipals.isEmpty()) {
        userPrincipalString = new GenericPrincipal(userPrincipals.iterator().next()).toExternalForm();
    }
    return _usernamePattern.matcher(userPrincipalString).matches() && _connectionNamePattern.matcher(connectionString).matches() && _remoteContainerIdPattern.matcher(remoteContainerName).matches();
}
Also used : GenericPrincipal(org.apache.qpid.server.model.preferences.GenericPrincipal) SocketConnectionPrincipal(org.apache.qpid.server.security.auth.SocketConnectionPrincipal) SocketConnectionPrincipal(org.apache.qpid.server.security.auth.SocketConnectionPrincipal) ConnectionPrincipal(org.apache.qpid.server.connection.ConnectionPrincipal) Subject(javax.security.auth.Subject) AuthenticatedPrincipal(org.apache.qpid.server.security.auth.AuthenticatedPrincipal)

Example 3 with AuthenticatedPrincipal

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

the class AbstractQueue method onOpen.

@Override
protected void onOpen() {
    super.onOpen();
    final Map<String, Object> attributes = getActualAttributes();
    final LinkedHashMap<String, Object> arguments = new LinkedHashMap<>(attributes);
    arguments.put(Queue.EXCLUSIVE, _exclusive);
    arguments.put(Queue.LIFETIME_POLICY, getLifetimePolicy());
    _arguments = Collections.synchronizedMap(arguments);
    _queueHouseKeepingTask = new AdvanceConsumersTask();
    final Set<SessionPrincipal> sessionPrincipals = getSessionPrincipals();
    final AMQPSession<?, ?> session;
    if (sessionPrincipals.isEmpty()) {
        session = null;
    } else {
        final SessionPrincipal sessionPrincipal = sessionPrincipals.iterator().next();
        session = sessionPrincipal.getSession();
    }
    if (session != null) {
        switch(_exclusive) {
            case PRINCIPAL:
                _exclusiveOwner = session.getAMQPConnection().getAuthorizedPrincipal();
                break;
            case CONTAINER:
                _exclusiveOwner = session.getAMQPConnection().getRemoteContainerName();
                break;
            case CONNECTION:
                _exclusiveOwner = session.getAMQPConnection();
                addExclusivityConstraint(session.getAMQPConnection());
                break;
            case SESSION:
                _exclusiveOwner = session;
                addExclusivityConstraint(session);
                break;
            case NONE:
            case LINK:
            case SHARED_SUBSCRIPTION:
                break;
            default:
                throw new ServerScopedRuntimeException("Unknown exclusivity policy: " + _exclusive + " this is a coding error inside Qpid");
        }
    } else if (_exclusive == ExclusivityPolicy.PRINCIPAL) {
        if (attributes.get(Queue.OWNER) != null) {
            final String owner = String.valueOf(attributes.get(Queue.OWNER));
            Principal ownerPrincipal;
            try {
                ownerPrincipal = new GenericPrincipal(owner);
            } catch (IllegalArgumentException e) {
                ownerPrincipal = new GenericPrincipal(owner + "@('')");
            }
            _exclusiveOwner = new AuthenticatedPrincipal(ownerPrincipal);
        }
    } else if (_exclusive == ExclusivityPolicy.CONTAINER) {
        if (attributes.get(Queue.OWNER) != null) {
            _exclusiveOwner = String.valueOf(attributes.get(Queue.OWNER));
        }
    }
    if (getLifetimePolicy() == LifetimePolicy.DELETE_ON_CONNECTION_CLOSE) {
        if (session != null) {
            addLifetimeConstraint(session.getAMQPConnection());
        } else {
            throw new IllegalArgumentException("Queues created with a lifetime policy of " + getLifetimePolicy() + " must be created from a connection.");
        }
    } else if (getLifetimePolicy() == LifetimePolicy.DELETE_ON_SESSION_END) {
        if (session != null) {
            addLifetimeConstraint(session);
        } else {
            throw new IllegalArgumentException("Queues created with a lifetime policy of " + getLifetimePolicy() + " must be created from a connection.");
        }
    } else if (getLifetimePolicy() == LifetimePolicy.DELETE_ON_CREATING_LINK_CLOSE) {
        if (_creatingLinkInfo != null) {
            final LinkModel link;
            if (_creatingLinkInfo.isSendingLink()) {
                link = _virtualHost.getSendingLink(_creatingLinkInfo.getRemoteContainerId(), _creatingLinkInfo.getLinkName());
            } else {
                link = _virtualHost.getReceivingLink(_creatingLinkInfo.getRemoteContainerId(), _creatingLinkInfo.getLinkName());
            }
            addLifetimeConstraint(link);
        } else {
            throw new IllegalArgumentException("Queues created with a lifetime policy of " + getLifetimePolicy() + " must be created from a AMQP 1.0 link.");
        }
    }
    switch(getMessageGroupType()) {
        case NONE:
            _messageGroupManager = null;
            break;
        case STANDARD:
            _messageGroupManager = new AssignedConsumerMessageGroupManager(getMessageGroupKeyOverride(), getMaximumDistinctGroups());
            break;
        case SHARED_GROUPS:
            _messageGroupManager = new DefinedGroupMessageGroupManager(getMessageGroupKeyOverride(), getMessageGroupDefaultGroup(), this);
            break;
        default:
            throw new IllegalArgumentException("Unknown messageGroupType type " + _messageGroupType);
    }
    _mimeTypeToFileExtension = getContextValue(Map.class, MAP_OF_STRING_STRING, MIME_TYPE_TO_FILE_EXTENSION);
    _messageConversionExceptionHandlingPolicy = getContextValue(MessageConversionExceptionHandlingPolicy.class, MESSAGE_CONVERSION_EXCEPTION_HANDLING_POLICY);
    _flowToDiskThreshold = getAncestor(Broker.class).getFlowToDiskThreshold();
    if (_defaultFilters != null) {
        final QpidServiceLoader qpidServiceLoader = new QpidServiceLoader();
        final Map<String, MessageFilterFactory> messageFilterFactories = qpidServiceLoader.getInstancesByType(MessageFilterFactory.class);
        for (Map.Entry<String, Map<String, List<String>>> entry : _defaultFilters.entrySet()) {
            final String name = String.valueOf(entry.getKey());
            final Map<String, List<String>> filterValue = entry.getValue();
            if (filterValue.size() == 1) {
                final String filterTypeName = String.valueOf(filterValue.keySet().iterator().next());
                final MessageFilterFactory filterFactory = messageFilterFactories.get(filterTypeName);
                if (filterFactory != null) {
                    final List<String> filterArguments = filterValue.values().iterator().next();
                    // check the arguments are valid
                    filterFactory.newInstance(filterArguments);
                    _defaultFiltersMap.put(name, new Callable<MessageFilter>() {

                        @Override
                        public MessageFilter call() {
                            return filterFactory.newInstance(filterArguments);
                        }
                    });
                } else {
                    throw new IllegalArgumentException("Unknown filter type " + filterTypeName + ", known types are: " + messageFilterFactories.keySet());
                }
            } else {
                throw new IllegalArgumentException("Filter value should be a map with one entry, having the type as key and the value being the filter arguments, not " + filterValue);
            }
        }
    }
    if (isHoldOnPublishEnabled()) {
        _holdMethods.add(new HoldMethod() {

            @Override
            public boolean isHeld(final MessageReference<?> messageReference, final long evaluationTime) {
                return messageReference.getMessage().getMessageHeader().getNotValidBefore() >= evaluationTime;
            }
        });
    }
    if (getAlternateBinding() != null) {
        final String alternateDestination = getAlternateBinding().getDestination();
        _alternateBindingDestination = getOpenedMessageDestination(alternateDestination);
        if (_alternateBindingDestination != null) {
            _alternateBindingDestination.addReference(this);
        } else {
            LOGGER.warn("Cannot find alternate binding destination '{}' for queue '{}'", alternateDestination, toString());
        }
    }
    createOverflowPolicyHandlers(_overflowPolicy);
    updateAlertChecks();
}
Also used : QpidServiceLoader(org.apache.qpid.server.plugin.QpidServiceLoader) SessionPrincipal(org.apache.qpid.server.connection.SessionPrincipal) LinkModel(org.apache.qpid.server.protocol.LinkModel) LinkedHashMap(java.util.LinkedHashMap) ServerScopedRuntimeException(org.apache.qpid.server.util.ServerScopedRuntimeException) AuthenticatedPrincipal(org.apache.qpid.server.security.auth.AuthenticatedPrincipal) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList) ArrayList(java.util.ArrayList) List(java.util.List) MessageFilterFactory(org.apache.qpid.server.plugin.MessageFilterFactory) GenericPrincipal(org.apache.qpid.server.model.preferences.GenericPrincipal) MessageFilter(org.apache.qpid.server.filter.MessageFilter) Map(java.util.Map) LinkedHashMap(java.util.LinkedHashMap) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) ConcurrentMap(java.util.concurrent.ConcurrentMap) GenericPrincipal(org.apache.qpid.server.model.preferences.GenericPrincipal) SessionPrincipal(org.apache.qpid.server.connection.SessionPrincipal) Principal(java.security.Principal) AuthenticatedPrincipal(org.apache.qpid.server.security.auth.AuthenticatedPrincipal)

Example 4 with AuthenticatedPrincipal

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

the class UserPreferencesImpl method augmentForUpdate.

private Collection<Preference> augmentForUpdate(final Collection<Preference> preferences) {
    HashSet<Preference> augmentedPreferences = new HashSet<>(preferences.size());
    for (final Preference preference : preferences) {
        Map<String, Object> attributes = new HashMap<>(preference.getAttributes());
        AuthenticatedPrincipal currentUser = AuthenticatedPrincipal.getCurrentUser();
        Date currentTime = new Date();
        attributes.put(Preference.LAST_UPDATED_DATE_ATTRIBUTE, currentTime);
        attributes.put(Preference.CREATED_DATE_ATTRIBUTE, currentTime);
        attributes.put(Preference.OWNER_ATTRIBUTE, currentUser);
        if (preference.getId() == null) {
            attributes.put(Preference.ID_ATTRIBUTE, UUID.randomUUID());
        } else {
            Preference existingPreference = _preferences.get(preference.getId());
            if (existingPreference != null) {
                attributes.put(Preference.CREATED_DATE_ATTRIBUTE, existingPreference.getCreatedDate());
            }
        }
        augmentedPreferences.add(PreferenceFactory.fromAttributes(preference.getAssociatedObject(), attributes));
    }
    return augmentedPreferences;
}
Also used : HashMap(java.util.HashMap) ConfiguredObject(org.apache.qpid.server.model.ConfiguredObject) Date(java.util.Date) HashSet(java.util.HashSet) AuthenticatedPrincipal(org.apache.qpid.server.security.auth.AuthenticatedPrincipal)

Example 5 with AuthenticatedPrincipal

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

the class BrokerImpl method doPurgeUser.

private void doPurgeUser(final AuthenticationProvider<?> origin, final String username) {
    // remove from AuthenticationProvider
    if (origin instanceof PasswordCredentialManagingAuthenticationProvider) {
        try {
            ((PasswordCredentialManagingAuthenticationProvider) origin).deleteUser(username);
        } catch (AccountNotFoundException e) {
        // pass
        }
    }
    // remove from Groups
    final Collection<GroupProvider> groupProviders = getChildren(GroupProvider.class);
    for (GroupProvider<?> groupProvider : groupProviders) {
        final Collection<Group> groups = groupProvider.getChildren(Group.class);
        for (Group<?> group : groups) {
            final Collection<GroupMember> members = group.getChildren(GroupMember.class);
            for (GroupMember<?> member : members) {
                if (username.equals(member.getName())) {
                    member.delete();
                }
            }
        }
    }
    // remove Preferences from all ConfiguredObjects
    Subject userSubject = new Subject(true, Collections.singleton(new AuthenticatedPrincipal(new UsernamePrincipal(username, origin))), Collections.EMPTY_SET, Collections.EMPTY_SET);
    java.util.Queue<ConfiguredObject<?>> configuredObjects = new LinkedList<>();
    configuredObjects.add(BrokerImpl.this);
    while (!configuredObjects.isEmpty()) {
        final ConfiguredObject<?> currentObject = configuredObjects.poll();
        final Collection<Class<? extends ConfiguredObject>> childClasses = getModel().getChildTypes(currentObject.getClass());
        for (Class<? extends ConfiguredObject> childClass : childClasses) {
            final Collection<? extends ConfiguredObject> children = currentObject.getChildren(childClass);
            for (ConfiguredObject child : children) {
                configuredObjects.add(child);
            }
        }
        Subject.doAs(userSubject, new PrivilegedAction<Void>() {

            @Override
            public Void run() {
                currentObject.getUserPreferences().delete(null, null, null);
                return null;
            }
        });
    }
}
Also used : AuthenticatedPrincipal(org.apache.qpid.server.security.auth.AuthenticatedPrincipal) Subject(javax.security.auth.Subject) LinkedList(java.util.LinkedList) UsernamePrincipal(org.apache.qpid.server.security.auth.UsernamePrincipal) AccountNotFoundException(javax.security.auth.login.AccountNotFoundException)

Aggregations

AuthenticatedPrincipal (org.apache.qpid.server.security.auth.AuthenticatedPrincipal)27 Subject (javax.security.auth.Subject)12 UsernamePrincipal (org.apache.qpid.server.security.auth.UsernamePrincipal)11 Principal (java.security.Principal)7 ConfiguredObject (org.apache.qpid.server.model.ConfiguredObject)7 Before (org.junit.Before)6 Test (org.junit.Test)6 Date (java.util.Date)5 EventLogger (org.apache.qpid.server.logging.EventLogger)5 SubjectCreator (org.apache.qpid.server.security.SubjectCreator)5 ArrayList (java.util.ArrayList)4 AmqpPort (org.apache.qpid.server.model.port.AmqpPort)4 AMQPConnection (org.apache.qpid.server.transport.AMQPConnection)4 HashMap (java.util.HashMap)3 HashSet (java.util.HashSet)3 Broker (org.apache.qpid.server.model.Broker)3 GenericPrincipal (org.apache.qpid.server.model.preferences.GenericPrincipal)3 TransportFrame (org.apache.qpid.server.protocol.v1_0.framing.TransportFrame)3 SubjectAuthenticationResult (org.apache.qpid.server.security.auth.SubjectAuthenticationResult)3 URISyntaxException (java.net.URISyntaxException)2