Search in sources :

Example 31 with RolePrincipal

use of org.apache.karaf.jaas.boot.principal.RolePrincipal in project ddf by codice.

the class Security method getAdminJavaSubject.

private static javax.security.auth.Subject getAdminJavaSubject() {
    Set<Principal> principals = new HashSet<>();
    String localRoles = AccessController.doPrivileged((PrivilegedAction<String>) () -> System.getProperty(KARAF_LOCAL_ROLE, ""));
    for (String role : localRoles.split(",")) {
        principals.add(new RolePrincipal(role));
    }
    return new javax.security.auth.Subject(true, principals, new HashSet(), new HashSet());
}
Also used : RolePrincipal(org.apache.karaf.jaas.boot.principal.RolePrincipal) RolePrincipal(org.apache.karaf.jaas.boot.principal.RolePrincipal) Principal(java.security.Principal) Subject(ddf.security.Subject) HashSet(java.util.HashSet)

Example 32 with RolePrincipal

use of org.apache.karaf.jaas.boot.principal.RolePrincipal in project ddf by codice.

the class Security method javaSubjectHasAdminRole.

/**
 * Determines if the current Java {@link Subject} has the admin role.
 *
 * @return {@code true} if the Java {@link Subject} exists and has the admin role, {@code false}
 *     otherwise
 * @throws SecurityException if a security manager exists and the {@link
 *     javax.security.auth.AuthPermission AuthPermission("getSubject")} permission is not
 *     authorized
 */
@Override
public final boolean javaSubjectHasAdminRole() {
    javax.security.auth.Subject subject = javax.security.auth.Subject.getSubject(AccessController.getContext());
    if (subject != null) {
        String localRoles = AccessController.doPrivileged((PrivilegedAction<String>) () -> System.getProperty(KARAF_LOCAL_ROLE, ""));
        Collection<RolePrincipal> principals = new ArrayList<>();
        for (String role : localRoles.split(",")) {
            principals.add(new RolePrincipal(role));
        }
        return subject.getPrincipals().containsAll(principals);
    }
    return false;
}
Also used : ArrayList(java.util.ArrayList) RolePrincipal(org.apache.karaf.jaas.boot.principal.RolePrincipal)

Example 33 with RolePrincipal

use of org.apache.karaf.jaas.boot.principal.RolePrincipal in project ddf by codice.

the class SslLdapLoginModule method doLogin.

protected boolean doLogin() throws LoginException {
    // --------- EXTRACT USERNAME AND PASSWORD FOR LDAP LOOKUP -------------
    Callback[] callbacks = new Callback[2];
    callbacks[0] = new NameCallback("Username: ");
    callbacks[1] = new PasswordCallback("Password: ", false);
    try {
        callbackHandler.handle(callbacks);
    } catch (IOException ioException) {
        LOGGER.debug("Exception while handling login.", ioException);
        throw new LoginException(ioException.getMessage());
    } catch (UnsupportedCallbackException unsupportedCallbackException) {
        LOGGER.debug("Exception while handling login.", unsupportedCallbackException);
        throw new LoginException(unsupportedCallbackException.getMessage() + " not available to obtain information from user.");
    }
    user = ((NameCallback) callbacks[0]).getName();
    if (user == null) {
        return false;
    }
    user = user.trim();
    validateUsername(user);
    char[] tmpPassword = ((PasswordCallback) callbacks[1]).getPassword();
    // this method.
    if ("none".equalsIgnoreCase(getBindMethod()) && (tmpPassword != null)) {
        LOGGER.debug("Changing from authentication = none to simple since user or password was specified.");
        // default to simple so that the provided user/password will get checked
        setBindMethod(DEFAULT_AUTHENTICATION);
    }
    if (tmpPassword == null) {
        tmpPassword = new char[0];
    }
    // ---------------------------------------------------------------------
    // RESET OBJECT STATE AND DECLARE LOCAL VARS
    principals = new HashSet<>();
    Connection connection;
    String userDn;
    // ------------- CREATE CONNECTION #1 ----------------------------------
    try {
        connection = ldapConnectionPool.borrowObject();
    } catch (Exception e) {
        LOGGER.info("Unable to obtain ldap connection from pool", e);
        return false;
    }
    try {
        if (connection != null) {
            // ------------- BIND #1 (CONNECTION USERNAME & PASSWORD) --------------
            try {
                BindRequest request;
                switch(bindMethod) {
                    case "Simple":
                        request = Requests.newSimpleBindRequest(connectionUsername, connectionPassword);
                        break;
                    case "SASL":
                        request = Requests.newPlainSASLBindRequest(connectionUsername, connectionPassword);
                        break;
                    case "GSSAPI SASL":
                        request = Requests.newGSSAPISASLBindRequest(connectionUsername, connectionPassword);
                        ((GSSAPISASLBindRequest) request).setRealm(realm);
                        ((GSSAPISASLBindRequest) request).setKDCAddress(kdcAddress);
                        break;
                    case "Digest MD5 SASL":
                        request = Requests.newDigestMD5SASLBindRequest(connectionUsername, connectionPassword);
                        ((DigestMD5SASLBindRequest) request).setCipher(DigestMD5SASLBindRequest.CIPHER_HIGH);
                        ((DigestMD5SASLBindRequest) request).getQOPs().clear();
                        ((DigestMD5SASLBindRequest) request).getQOPs().add(DigestMD5SASLBindRequest.QOP_AUTH_CONF);
                        ((DigestMD5SASLBindRequest) request).getQOPs().add(DigestMD5SASLBindRequest.QOP_AUTH_INT);
                        ((DigestMD5SASLBindRequest) request).getQOPs().add(DigestMD5SASLBindRequest.QOP_AUTH);
                        if (StringUtils.isNotEmpty(realm)) {
                            ((DigestMD5SASLBindRequest) request).setRealm(realm);
                        }
                        break;
                    default:
                        request = Requests.newSimpleBindRequest(connectionUsername, connectionPassword);
                        break;
                }
                LOGGER.trace("Attempting LDAP bind for administrator: {}", connectionUsername);
                BindResult bindResult = connection.bind(request);
                if (!bindResult.isSuccess()) {
                    LOGGER.debug(BIND_FAILURE_MSG);
                    return false;
                }
            } catch (LdapException e) {
                LOGGER.debug("Unable to bind to LDAP server.", e);
                return false;
            }
            LOGGER.trace("LDAP bind successful for administrator: {}", connectionUsername);
            // --------- SEARCH #1, FIND USER DISTINGUISHED NAME -----------
            SearchScope scope;
            scope = userSearchSubtree ? SearchScope.WHOLE_SUBTREE : SearchScope.SINGLE_LEVEL;
            userFilter = userFilter.replaceAll(Pattern.quote("%u"), Matcher.quoteReplacement(user));
            userFilter = userFilter.replace("\\", "\\\\");
            LOGGER.trace("Performing LDAP query for user: {} at {} with filter {}", user, userBaseDN, userFilter);
            try (ConnectionEntryReader entryReader = connection.search(userBaseDN, scope, userFilter)) {
                while (entryReader.hasNext() && entryReader.isReference()) {
                    LOGGER.debug("Referral ignored while searching for user {}", user);
                    entryReader.readReference();
                }
                if (!entryReader.hasNext()) {
                    LOGGER.info("User {} not found in LDAP.", user);
                    return false;
                }
                SearchResultEntry searchResultEntry = entryReader.readEntry();
                userDn = searchResultEntry.getName().toString();
            } catch (LdapException | SearchResultReferenceIOException e) {
                LOGGER.info("Unable to read contents of LDAP user search.", e);
                return false;
            }
            // Validate user's credentials.
            try {
                LOGGER.trace("Attempting LDAP bind for user: {}", userDn);
                BindResult bindResult = connection.bind(userDn, tmpPassword);
                if (!bindResult.isSuccess()) {
                    LOGGER.info(BIND_FAILURE_MSG);
                    return false;
                }
            } catch (Exception e) {
                LOGGER.info("Unable to bind user: {} to LDAP server.", userDn, e);
                return false;
            }
            LOGGER.trace("LDAP bind successful for user: {}", userDn);
            // ---------- ADD USER AS PRINCIPAL --------------------------------
            principals.add(new UserPrincipal(user));
            // ----- BIND #3 (CONNECTION USERNAME & PASSWORD) --------------
            try {
                LOGGER.trace("Attempting LDAP bind for administrator: {}", connectionUsername);
                BindResult bindResult = connection.bind(connectionUsername, connectionPassword);
                if (!bindResult.isSuccess()) {
                    LOGGER.info(BIND_FAILURE_MSG);
                    return false;
                }
            } catch (LdapException e) {
                LOGGER.info("Unable to bind to LDAP server.", e);
                return false;
            }
            LOGGER.trace("LDAP bind successful for administrator: {}", connectionUsername);
            // --------- SEARCH #3, GET ROLES ------------------------------
            scope = roleSearchSubtree ? SearchScope.WHOLE_SUBTREE : SearchScope.SINGLE_LEVEL;
            roleFilter = roleFilter.replaceAll(Pattern.quote("%u"), Matcher.quoteReplacement(user));
            roleFilter = roleFilter.replaceAll(Pattern.quote("%dn"), Matcher.quoteReplacement(userBaseDN));
            roleFilter = roleFilter.replaceAll(Pattern.quote("%fqdn"), Matcher.quoteReplacement(userDn));
            roleFilter = roleFilter.replace("\\", "\\\\");
            LOGGER.trace("Performing LDAP query for roles for user: {} at {} with filter {} for role attribute {}", user, roleBaseDN, roleFilter, roleNameAttribute);
            // ------------- ADD ROLES AS NEW PRINCIPALS -------------------
            try (ConnectionEntryReader entryReader = connection.search(roleBaseDN, scope, roleFilter, roleNameAttribute)) {
                SearchResultEntry entry;
                while (entryReader.hasNext()) {
                    if (entryReader.isEntry()) {
                        entry = entryReader.readEntry();
                        Attribute attr = entry.getAttribute(roleNameAttribute);
                        if (attr == null) {
                            throw new LoginException("No attributes returned for [" + roleNameAttribute + " : " + roleBaseDN + "]");
                        }
                        for (ByteString role : attr) {
                            principals.add(new RolePrincipal(role.toString()));
                        }
                    } else {
                        // Got a continuation reference.
                        final SearchResultReference ref = entryReader.readReference();
                        LOGGER.debug("Skipping result reference: {}", ref.getURIs());
                    }
                }
            } catch (Exception e) {
                LOGGER.debug("Exception while getting roles for [" + user + "].", e);
                throw new LoginException("Can't get roles for [" + user + "]: " + e.getMessage());
            }
        } else {
            LOGGER.trace("LDAP Connection was null could not authenticate user.");
            return false;
        }
        succeeded = true;
        commitSucceeded = true;
        return true;
    } finally {
        ldapConnectionPool.returnObject(connection);
    }
}
Also used : Attribute(org.forgerock.opendj.ldap.Attribute) ByteString(org.forgerock.opendj.ldap.ByteString) DigestMD5SASLBindRequest(org.forgerock.opendj.ldap.requests.DigestMD5SASLBindRequest) GSSAPISASLBindRequest(org.forgerock.opendj.ldap.requests.GSSAPISASLBindRequest) BindRequest(org.forgerock.opendj.ldap.requests.BindRequest) SearchResultReference(org.forgerock.opendj.ldap.responses.SearchResultReference) ByteString(org.forgerock.opendj.ldap.ByteString) GSSAPISASLBindRequest(org.forgerock.opendj.ldap.requests.GSSAPISASLBindRequest) PasswordCallback(javax.security.auth.callback.PasswordCallback) UnsupportedCallbackException(javax.security.auth.callback.UnsupportedCallbackException) RolePrincipal(org.apache.karaf.jaas.boot.principal.RolePrincipal) LdapException(org.forgerock.opendj.ldap.LdapException) Connection(org.forgerock.opendj.ldap.Connection) IOException(java.io.IOException) SearchResultReferenceIOException(org.forgerock.opendj.ldap.SearchResultReferenceIOException) SearchResultReferenceIOException(org.forgerock.opendj.ldap.SearchResultReferenceIOException) LoginException(javax.security.auth.login.LoginException) UnsupportedCallbackException(javax.security.auth.callback.UnsupportedCallbackException) LdapException(org.forgerock.opendj.ldap.LdapException) InvalidSyntaxException(org.osgi.framework.InvalidSyntaxException) IOException(java.io.IOException) SearchResultReferenceIOException(org.forgerock.opendj.ldap.SearchResultReferenceIOException) UserPrincipal(org.apache.karaf.jaas.boot.principal.UserPrincipal) ConnectionEntryReader(org.forgerock.opendj.ldif.ConnectionEntryReader) PasswordCallback(javax.security.auth.callback.PasswordCallback) NameCallback(javax.security.auth.callback.NameCallback) Callback(javax.security.auth.callback.Callback) NameCallback(javax.security.auth.callback.NameCallback) DigestMD5SASLBindRequest(org.forgerock.opendj.ldap.requests.DigestMD5SASLBindRequest) SearchScope(org.forgerock.opendj.ldap.SearchScope) LoginException(javax.security.auth.login.LoginException) BindResult(org.forgerock.opendj.ldap.responses.BindResult) SearchResultEntry(org.forgerock.opendj.ldap.responses.SearchResultEntry)

Example 34 with RolePrincipal

use of org.apache.karaf.jaas.boot.principal.RolePrincipal in project ddf by codice.

the class UsernamePasswordRealm method createPrincipalCollectionFromSubject.

private SimplePrincipalCollection createPrincipalCollectionFromSubject(Subject subject) {
    SimplePrincipalCollection principals = new SimplePrincipalCollection();
    DefaultSecurityAssertionBuilder assertionBuilder = new DefaultSecurityAssertionBuilder();
    AttributeStatement attributeStatement = new AttributeStatementDefault();
    Principal userPrincipal = subject.getPrincipals().stream().filter(p -> p instanceof UserPrincipal).findFirst().orElseThrow(AuthenticationException::new);
    Set<Principal> rolePrincipals = subject.getPrincipals().stream().filter(p -> p instanceof RolePrincipal).collect(Collectors.toSet());
    for (ClaimsHandler claimsHandler : claimsHandlers) {
        ClaimsCollection claims = claimsHandler.retrieveClaims(new ClaimsParametersImpl(userPrincipal, rolePrincipals, new HashMap<>()));
        mergeClaimsToAttributes(attributeStatement, claims);
    }
    final Instant now = Instant.now();
    assertionBuilder.addAttributeStatement(attributeStatement).userPrincipal(userPrincipal).weight(SecurityAssertion.LOCAL_AUTH_WEIGHT).issuer("DDF").notBefore(Date.from(now)).notOnOrAfter(Date.from(now.plus(fourHours)));
    for (Principal principal : rolePrincipals) {
        assertionBuilder.addPrincipal(principal);
    }
    assertionBuilder.tokenType(USER_PASS_TOKEN_TYPE);
    SecurityAssertion assertion = assertionBuilder.build();
    principals.add(assertion, "UP");
    return principals;
}
Also used : LoginException(javax.security.auth.login.LoginException) NamePasswordCallbackHandler(org.apache.wss4j.common.NamePasswordCallbackHandler) Date(java.util.Date) LoggerFactory(org.slf4j.LoggerFactory) HashMap(java.util.HashMap) AuthenticationToken(org.apache.shiro.authc.AuthenticationToken) DefaultSecurityAssertionBuilder(ddf.security.assertion.impl.DefaultSecurityAssertionBuilder) AttributeStatement(ddf.security.assertion.AttributeStatement) LoginContext(javax.security.auth.login.LoginContext) ArrayList(java.util.ArrayList) JaasRealm(org.apache.karaf.jaas.config.JaasRealm) CallbackHandler(javax.security.auth.callback.CallbackHandler) Duration(java.time.Duration) AuthenticationTokenType(org.codice.ddf.security.handler.AuthenticationTokenType) Bundle(org.osgi.framework.Bundle) ClaimsHandler(ddf.security.claims.ClaimsHandler) ClaimsParametersImpl(ddf.security.claims.impl.ClaimsParametersImpl) SimplePrincipalCollection(org.apache.shiro.subject.SimplePrincipalCollection) ServiceReference(org.osgi.framework.ServiceReference) UserPrincipal(org.apache.karaf.jaas.boot.principal.UserPrincipal) Claim(ddf.security.claims.Claim) SecurityAssertion(ddf.security.assertion.SecurityAssertion) AuthenticationInfo(org.apache.shiro.authc.AuthenticationInfo) Logger(org.slf4j.Logger) Attribute(ddf.security.assertion.Attribute) AttributeDefault(ddf.security.assertion.impl.AttributeDefault) Set(java.util.Set) Instant(java.time.Instant) Collectors(java.util.stream.Collectors) StandardCharsets(java.nio.charset.StandardCharsets) Subject(javax.security.auth.Subject) SimpleAuthenticationInfo(org.apache.shiro.authc.SimpleAuthenticationInfo) ClaimsCollection(ddf.security.claims.ClaimsCollection) Base64(java.util.Base64) List(java.util.List) RolePrincipal(org.apache.karaf.jaas.boot.principal.RolePrincipal) Principal(java.security.Principal) AuthenticationException(org.apache.shiro.authc.AuthenticationException) AttributeStatementDefault(ddf.security.assertion.impl.AttributeStatementDefault) AuthenticatingRealm(org.apache.shiro.realm.AuthenticatingRealm) BaseAuthenticationToken(org.codice.ddf.security.handler.BaseAuthenticationToken) FrameworkUtil(org.osgi.framework.FrameworkUtil) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList) ClaimsHandler(ddf.security.claims.ClaimsHandler) DefaultSecurityAssertionBuilder(ddf.security.assertion.impl.DefaultSecurityAssertionBuilder) AuthenticationException(org.apache.shiro.authc.AuthenticationException) HashMap(java.util.HashMap) Instant(java.time.Instant) SimplePrincipalCollection(org.apache.shiro.subject.SimplePrincipalCollection) SecurityAssertion(ddf.security.assertion.SecurityAssertion) UserPrincipal(org.apache.karaf.jaas.boot.principal.UserPrincipal) ClaimsParametersImpl(ddf.security.claims.impl.ClaimsParametersImpl) AttributeStatement(ddf.security.assertion.AttributeStatement) AttributeStatementDefault(ddf.security.assertion.impl.AttributeStatementDefault) ClaimsCollection(ddf.security.claims.ClaimsCollection) RolePrincipal(org.apache.karaf.jaas.boot.principal.RolePrincipal) UserPrincipal(org.apache.karaf.jaas.boot.principal.UserPrincipal) RolePrincipal(org.apache.karaf.jaas.boot.principal.RolePrincipal) Principal(java.security.Principal)

Example 35 with RolePrincipal

use of org.apache.karaf.jaas.boot.principal.RolePrincipal in project karaf by apache.

the class KarafJaasAuthenticator method authenticate.

public boolean authenticate(final String username, final PublicKey key, final ServerSession session) {
    try {
        Subject subject = new Subject();
        LoginContext loginContext = new LoginContext(realm, subject, callbacks -> {
            for (Callback callback : callbacks) {
                if (callback instanceof NameCallback) {
                    ((NameCallback) callback).setName(username);
                } else if (callback instanceof PublickeyCallback) {
                    ((PublickeyCallback) callback).setPublicKey(key);
                } else {
                    throw new UnsupportedCallbackException(callback);
                }
            }
        });
        loginContext.login();
        int roleCount = 0;
        for (Principal principal : subject.getPrincipals()) {
            if (principal instanceof RolePrincipal) {
                roleCount++;
            }
        }
        if (roleCount == 0) {
            throw new FailedLoginException("User doesn't have role defined");
        }
        session.setAttribute(SUBJECT_ATTRIBUTE_KEY, subject);
        return true;
    } catch (Exception e) {
        LOGGER.debug("User authentication failed with " + e.getMessage(), e);
        return false;
    }
}
Also used : LoginContext(javax.security.auth.login.LoginContext) PasswordCallback(javax.security.auth.callback.PasswordCallback) NameCallback(javax.security.auth.callback.NameCallback) PublickeyCallback(org.apache.karaf.jaas.modules.publickey.PublickeyCallback) Callback(javax.security.auth.callback.Callback) NameCallback(javax.security.auth.callback.NameCallback) FailedLoginException(javax.security.auth.login.FailedLoginException) PublickeyCallback(org.apache.karaf.jaas.modules.publickey.PublickeyCallback) UnsupportedCallbackException(javax.security.auth.callback.UnsupportedCallbackException) RolePrincipal(org.apache.karaf.jaas.boot.principal.RolePrincipal) Subject(javax.security.auth.Subject) RolePrincipal(org.apache.karaf.jaas.boot.principal.RolePrincipal) Principal(java.security.Principal) UnsupportedCallbackException(javax.security.auth.callback.UnsupportedCallbackException) FailedLoginException(javax.security.auth.login.FailedLoginException)

Aggregations

RolePrincipal (org.apache.karaf.jaas.boot.principal.RolePrincipal)61 UserPrincipal (org.apache.karaf.jaas.boot.principal.UserPrincipal)20 Subject (javax.security.auth.Subject)19 Principal (java.security.Principal)15 Test (org.junit.Test)15 LoginException (javax.security.auth.login.LoginException)14 IOException (java.io.IOException)13 NameCallback (javax.security.auth.callback.NameCallback)13 UnsupportedCallbackException (javax.security.auth.callback.UnsupportedCallbackException)13 ArrayList (java.util.ArrayList)12 Callback (javax.security.auth.callback.Callback)11 PasswordCallback (javax.security.auth.callback.PasswordCallback)10 FailedLoginException (javax.security.auth.login.FailedLoginException)10 GroupPrincipal (org.apache.karaf.jaas.boot.principal.GroupPrincipal)9 BundleContext (org.osgi.framework.BundleContext)8 Hashtable (java.util.Hashtable)7 HashSet (java.util.HashSet)6 File (java.io.File)4 Configuration (org.osgi.service.cm.Configuration)4 Attribute (ddf.security.assertion.Attribute)3