Search in sources :

Example 1 with Principal

use of java.security.Principal in project jetty.project by eclipse.

the class JaspiAuthenticator method validateRequest.

public Authentication validateRequest(JaspiMessageInfo messageInfo) throws ServerAuthException {
    try {
        String authContextId = _authConfig.getAuthContextID(messageInfo);
        ServerAuthContext authContext = _authConfig.getAuthContext(authContextId, _serviceSubject, _authProperties);
        Subject clientSubject = new Subject();
        AuthStatus authStatus = authContext.validateRequest(messageInfo, clientSubject, _serviceSubject);
        if (authStatus == AuthStatus.SEND_CONTINUE)
            return Authentication.SEND_CONTINUE;
        if (authStatus == AuthStatus.SEND_FAILURE)
            return Authentication.SEND_FAILURE;
        if (authStatus == AuthStatus.SUCCESS) {
            Set<UserIdentity> ids = clientSubject.getPrivateCredentials(UserIdentity.class);
            UserIdentity userIdentity;
            if (ids.size() > 0) {
                userIdentity = ids.iterator().next();
            } else {
                CallerPrincipalCallback principalCallback = _callbackHandler.getThreadCallerPrincipalCallback();
                if (principalCallback == null) {
                    return Authentication.UNAUTHENTICATED;
                }
                Principal principal = principalCallback.getPrincipal();
                if (principal == null) {
                    String principalName = principalCallback.getName();
                    Set<Principal> principals = principalCallback.getSubject().getPrincipals();
                    for (Principal p : principals) {
                        if (p.getName().equals(principalName)) {
                            principal = p;
                            break;
                        }
                    }
                    if (principal == null) {
                        return Authentication.UNAUTHENTICATED;
                    }
                }
                GroupPrincipalCallback groupPrincipalCallback = _callbackHandler.getThreadGroupPrincipalCallback();
                String[] groups = groupPrincipalCallback == null ? null : groupPrincipalCallback.getGroups();
                userIdentity = _identityService.newUserIdentity(clientSubject, principal, groups);
            }
            HttpSession session = ((HttpServletRequest) messageInfo.getRequestMessage()).getSession(false);
            Authentication cached = (session == null ? null : (SessionAuthentication) session.getAttribute(SessionAuthentication.__J_AUTHENTICATED));
            if (cached != null)
                return cached;
            return new UserAuthentication(getAuthMethod(), userIdentity);
        }
        if (authStatus == AuthStatus.SEND_SUCCESS) {
            // we are processing a message in a secureResponse dialog.
            return Authentication.SEND_SUCCESS;
        }
        if (authStatus == AuthStatus.FAILURE) {
            HttpServletResponse response = (HttpServletResponse) messageInfo.getResponseMessage();
            response.sendError(HttpServletResponse.SC_FORBIDDEN);
            return Authentication.SEND_FAILURE;
        }
        // should not happen
        throw new IllegalStateException("No AuthStatus returned");
    } catch (IOException | AuthException e) {
        throw new ServerAuthException(e);
    }
}
Also used : HttpSession(javax.servlet.http.HttpSession) UserIdentity(org.eclipse.jetty.server.UserIdentity) HttpServletResponse(javax.servlet.http.HttpServletResponse) AuthException(javax.security.auth.message.AuthException) ServerAuthException(org.eclipse.jetty.security.ServerAuthException) SessionAuthentication(org.eclipse.jetty.security.authentication.SessionAuthentication) IOException(java.io.IOException) ServerAuthException(org.eclipse.jetty.security.ServerAuthException) UserAuthentication(org.eclipse.jetty.security.UserAuthentication) Subject(javax.security.auth.Subject) ServerAuthContext(javax.security.auth.message.config.ServerAuthContext) HttpServletRequest(javax.servlet.http.HttpServletRequest) CallerPrincipalCallback(javax.security.auth.message.callback.CallerPrincipalCallback) GroupPrincipalCallback(javax.security.auth.message.callback.GroupPrincipalCallback) AuthStatus(javax.security.auth.message.AuthStatus) DeferredAuthentication(org.eclipse.jetty.security.authentication.DeferredAuthentication) SessionAuthentication(org.eclipse.jetty.security.authentication.SessionAuthentication) UserAuthentication(org.eclipse.jetty.security.UserAuthentication) Authentication(org.eclipse.jetty.server.Authentication) Principal(java.security.Principal)

Example 2 with Principal

use of java.security.Principal in project jetty.project by eclipse.

the class StrictRoleCheckPolicy method checkRole.

public boolean checkRole(String roleName, Principal runAsRole, Group roles) {
    //them. If so, then only check if the user has that role.
    if (runAsRole != null) {
        return (roleName.equals(runAsRole.getName()));
    } else {
        if (roles == null)
            return false;
        Enumeration<? extends Principal> rolesEnum = roles.members();
        boolean found = false;
        while (rolesEnum.hasMoreElements() && !found) {
            Principal p = (Principal) rolesEnum.nextElement();
            found = roleName.equals(p.getName());
        }
        return found;
    }
}
Also used : Principal(java.security.Principal)

Example 3 with Principal

use of java.security.Principal in project elasticsearch by elastic.

the class HdfsBlobStoreContainerTests method createContext.

@SuppressForbidden(reason = "lesser of two evils (the other being a bunch of JNI/classloader nightmares)")
private FileContext createContext(URI uri) {
    // mirrors HdfsRepository.java behaviour
    Configuration cfg = new Configuration(true);
    cfg.setClassLoader(HdfsRepository.class.getClassLoader());
    cfg.reloadConfiguration();
    Constructor<?> ctor;
    Subject subject;
    try {
        Class<?> clazz = Class.forName("org.apache.hadoop.security.User");
        ctor = clazz.getConstructor(String.class);
        ctor.setAccessible(true);
    } catch (ClassNotFoundException | NoSuchMethodException e) {
        throw new RuntimeException(e);
    }
    try {
        Principal principal = (Principal) ctor.newInstance(System.getProperty("user.name"));
        subject = new Subject(false, Collections.singleton(principal), Collections.emptySet(), Collections.emptySet());
    } catch (InstantiationException | IllegalAccessException | InvocationTargetException e) {
        throw new RuntimeException(e);
    }
    // disable file system cache
    cfg.setBoolean("fs.hdfs.impl.disable.cache", true);
    // set file system to TestingFs to avoid a bunch of security
    // checks, similar to what is done in HdfsTests.java
    cfg.set("fs.AbstractFileSystem." + uri.getScheme() + ".impl", TestingFs.class.getName());
    // create the FileContext with our user
    return Subject.doAs(subject, (PrivilegedAction<FileContext>) () -> {
        try {
            TestingFs fs = (TestingFs) AbstractFileSystem.get(uri, cfg);
            return FileContext.getFileContext(fs, cfg);
        } catch (UnsupportedFileSystemException e) {
            throw new RuntimeException(e);
        }
    });
}
Also used : Configuration(org.apache.hadoop.conf.Configuration) Subject(javax.security.auth.Subject) InvocationTargetException(java.lang.reflect.InvocationTargetException) UnsupportedFileSystemException(org.apache.hadoop.fs.UnsupportedFileSystemException) Principal(java.security.Principal) FileContext(org.apache.hadoop.fs.FileContext) SuppressForbidden(org.elasticsearch.common.SuppressForbidden)

Example 4 with Principal

use of java.security.Principal in project storm by apache.

the class NimbusClient method withConfiguredClient.

public static void withConfiguredClient(WithNimbus cb, Map conf) throws Exception {
    ReqContext context = ReqContext.context();
    Principal principal = context.principal();
    String user = principal == null ? null : principal.getName();
    try (NimbusClient client = getConfiguredClientAs(conf, user)) {
        cb.run(client.getClient());
    }
}
Also used : ReqContext(org.apache.storm.security.auth.ReqContext) Principal(java.security.Principal)

Example 5 with Principal

use of java.security.Principal in project Openfire by igniterealtime.

the class CertificateManager method validateReply.

/**
     * Validates chain in certification reply, and returns the ordered
     * elements of the chain (with user certificate first, and root
     * certificate last in the array).
     *
     * @param alias the alias name
     * @param userCert the user certificate of the alias
     * @param certs the chain provided in the reply
     */
private static List<X509Certificate> validateReply(KeyStore keyStore, KeyStore trustStore, String alias, X509Certificate userCert, Collection<X509Certificate> certs) throws Exception {
    List<X509Certificate> replyCerts = new ArrayList<>(certs);
    // order the certs in the reply (bottom-up).
    int i;
    X509Certificate tmpCert;
    if (userCert != null) {
        PublicKey userPubKey = userCert.getPublicKey();
        for (i = 0; i < replyCerts.size(); i++) {
            if (userPubKey.equals(replyCerts.get(i).getPublicKey())) {
                break;
            }
        }
        if (i == replyCerts.size()) {
            throw new Exception("Certificate reply does not contain public key for <alias>: " + alias);
        }
        tmpCert = replyCerts.get(0);
        replyCerts.set(0, replyCerts.get(i));
        replyCerts.set(i, tmpCert);
    }
    Principal issuer = replyCerts.get(0).getIssuerDN();
    for (i = 1; i < replyCerts.size() - 1; i++) {
        // find a cert in the reply whose "subject" is the same as the
        // given "issuer"
        int j;
        for (j = i; j < replyCerts.size(); j++) {
            Principal subject = replyCerts.get(j).getSubjectDN();
            if (subject.equals(issuer)) {
                tmpCert = replyCerts.get(i);
                replyCerts.set(i, replyCerts.get(j));
                replyCerts.set(j, tmpCert);
                issuer = replyCerts.get(i).getIssuerDN();
                break;
            }
        }
        if (j == replyCerts.size()) {
            throw new Exception("Incomplete certificate chain in reply");
        }
    }
    // now verify each cert in the ordered chain
    for (i = 0; i < replyCerts.size() - 1; i++) {
        PublicKey pubKey = replyCerts.get(i + 1).getPublicKey();
        try {
            replyCerts.get(i).verify(pubKey);
        } catch (Exception e) {
            throw new Exception("Certificate chain in reply does not verify: " + e.getMessage());
        }
    }
    // do we trust the (root) cert at the top?
    X509Certificate topCert = replyCerts.get(replyCerts.size() - 1);
    boolean foundInKeyStore = keyStore.getCertificateAlias(topCert) != null;
    boolean foundInCAStore = trustStore.getCertificateAlias(topCert) != null;
    if (!foundInKeyStore && !foundInCAStore) {
        boolean verified = false;
        X509Certificate rootCert = null;
        for (Enumeration<String> aliases = trustStore.aliases(); aliases.hasMoreElements(); ) {
            String name = aliases.nextElement();
            rootCert = (X509Certificate) trustStore.getCertificate(name);
            if (rootCert != null) {
                try {
                    topCert.verify(rootCert.getPublicKey());
                    verified = true;
                    break;
                } catch (Exception e) {
                // Ignore
                }
            }
        }
        if (!verified) {
            return null;
        } else {
            // Check if the cert is a self-signed cert
            if (!topCert.getSubjectDN().equals(topCert.getIssuerDN())) {
                // append the (self-signed) root CA cert to the chain
                replyCerts.add(rootCert);
            }
        }
    }
    return replyCerts;
}
Also used : PublicKey(java.security.PublicKey) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList) ArrayList(java.util.ArrayList) X509Certificate(java.security.cert.X509Certificate) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException) KeyStoreException(java.security.KeyStoreException) GeneralSecurityException(java.security.GeneralSecurityException) CertPathValidatorException(java.security.cert.CertPathValidatorException) CertException(org.bouncycastle.cert.CertException) CertPathBuilderException(java.security.cert.CertPathBuilderException) PKCSException(org.bouncycastle.pkcs.PKCSException) IOException(java.io.IOException) CertificateException(java.security.cert.CertificateException) NoSuchProviderException(java.security.NoSuchProviderException) Principal(java.security.Principal)

Aggregations

Principal (java.security.Principal)1967 Test (org.junit.Test)442 Subject (javax.security.auth.Subject)262 HashSet (java.util.HashSet)172 IOException (java.io.IOException)121 EveryonePrincipal (org.apache.jackrabbit.oak.spi.security.principal.EveryonePrincipal)118 HttpServletRequest (javax.servlet.http.HttpServletRequest)115 ArrayList (java.util.ArrayList)114 GroupPrincipal (org.apache.jackrabbit.api.security.principal.GroupPrincipal)87 HashMap (java.util.HashMap)86 SecurityContext (org.apache.cxf.security.SecurityContext)76 X500Principal (javax.security.auth.x500.X500Principal)75 User (org.apache.jackrabbit.api.security.user.User)75 X509Certificate (java.security.cert.X509Certificate)74 Group (org.apache.jackrabbit.api.security.user.Group)71 List (java.util.List)67 CustomTokenPrincipal (org.apache.wss4j.common.principal.CustomTokenPrincipal)67 Map (java.util.Map)64 HttpServletResponse (javax.servlet.http.HttpServletResponse)64 Privilege (javax.jcr.security.Privilege)63