Search in sources :

Example 1 with NamePrincipal

use of org.wildfly.security.auth.principal.NamePrincipal in project wildfly by wildfly.

the class ElytronCallbackHandler method handleInternal.

protected void handleInternal(final CallerPrincipalCallback callerPrincipalCallback, final GroupPrincipalCallback groupPrincipalCallback, final PasswordValidationCallback passwordValidationCallback) throws IOException {
    if (this.executionSubject == null) {
        throw SUBSYSTEM_RA_LOGGER.executionSubjectNotSetInHandler();
    }
    SecurityIdentity identity = this.securityDomain.getAnonymousSecurityIdentity();
    // establish the caller principal using the info from the callback.
    Principal callerPrincipal = null;
    if (callerPrincipalCallback != null) {
        Principal callbackPrincipal = callerPrincipalCallback.getPrincipal();
        callerPrincipal = callbackPrincipal != null ? new NamePrincipal(callbackPrincipal.getName()) : callerPrincipalCallback.getName() != null ? new NamePrincipal(callerPrincipalCallback.getName()) : null;
    }
    // a null principal is the ra contract for requiring the use of the unauthenticated identity - no point in attempting to authenticate.
    if (callerPrincipal != null) {
        // check if we have a username/password pair to authenticate - first try the password validation callback.
        if (passwordValidationCallback != null) {
            final String username = passwordValidationCallback.getUsername();
            final char[] password = passwordValidationCallback.getPassword();
            try {
                identity = this.authenticate(username, password);
                // add a password credential to the execution subject and set the successful result in the callback.
                this.addPrivateCredential(this.executionSubject, new PasswordCredential(username, password));
                passwordValidationCallback.setResult(true);
            } catch (SecurityException e) {
                passwordValidationCallback.setResult(false);
                return;
            }
        } else {
            // identity not established using the callback - check if the execution subject contains a password credential.
            PasswordCredential passwordCredential = this.getPrivateCredential(this.executionSubject, PasswordCredential.class);
            if (passwordCredential != null) {
                try {
                    identity = this.authenticate(passwordCredential.getUserName(), passwordCredential.getPassword());
                } catch (SecurityException e) {
                    return;
                }
            } else {
                identity = securityDomain.createAdHocIdentity(callerPrincipal);
            }
        }
        // is different from the identity principal and switch to the caller principal identity if needed.
        if (!callerPrincipal.equals(identity.getPrincipal())) {
            identity = identity.createRunAsIdentity(callerPrincipal.getName());
        }
        // if we have new roles coming from the group callback, set a new mapper in the identity.
        if (groupPrincipalCallback != null) {
            String[] groups = groupPrincipalCallback.getGroups();
            if (groups != null) {
                Set<String> roles = new HashSet<>(Arrays.asList(groups));
                // TODO what category should we use here?
                identity = identity.withRoleMapper("ejb", RoleMapper.constant(Roles.fromSet(roles)));
            }
        }
    }
    // set the authenticated identity as a private credential in the subject.
    this.executionSubject.getPrincipals().add(identity.getPrincipal());
    this.addPrivateCredential(executionSubject, identity);
}
Also used : SecurityIdentity(org.wildfly.security.auth.server.SecurityIdentity) NamePrincipal(org.wildfly.security.auth.principal.NamePrincipal) PasswordCredential(javax.resource.spi.security.PasswordCredential) NamePrincipal(org.wildfly.security.auth.principal.NamePrincipal) Principal(java.security.Principal) HashSet(java.util.HashSet)

Example 2 with NamePrincipal

use of org.wildfly.security.auth.principal.NamePrincipal in project wildfly by wildfly.

the class ElytronSubjectFactory method createSubject.

/**
     * Create a {@link Subject} with the principal and password credential obtained from the authentication configuration
     * that matches the target {@link URI}.
     *
     * @param authenticationContext the {@link AuthenticationContext} used to select a configuration that matches the
     *                              target {@link URI}.
     * @return the constructed {@link Subject}. It contains a single principal and a {@link PasswordCredential}.
     */
private Subject createSubject(final AuthenticationContext authenticationContext) {
    final AuthenticationConfiguration configuration = AUTH_CONFIG_CLIENT.getAuthenticationConfiguration(this.targetURI, authenticationContext);
    final CallbackHandler handler = AUTH_CONFIG_CLIENT.getCallbackHandler(configuration);
    final NameCallback nameCallback = new NameCallback("Username: ");
    final PasswordCallback passwordCallback = new PasswordCallback("Password: ", false);
    try {
        handler.handle(new Callback[] { nameCallback, passwordCallback });
        Subject subject = new Subject();
        if (nameCallback.getName() != null) {
            subject.getPrincipals().add(new NamePrincipal(nameCallback.getName()));
        }
        // add the password as a private credential in the Subject.
        if (passwordCallback.getPassword() != null) {
            this.addPrivateCredential(subject, new PasswordCredential(nameCallback.getName(), passwordCallback.getPassword()));
        }
        return subject;
    } catch (IOException | UnsupportedCallbackException e) {
        throw new SecurityException(e);
    }
}
Also used : AuthenticationConfiguration(org.wildfly.security.auth.client.AuthenticationConfiguration) CallbackHandler(javax.security.auth.callback.CallbackHandler) NameCallback(javax.security.auth.callback.NameCallback) NamePrincipal(org.wildfly.security.auth.principal.NamePrincipal) PasswordCredential(javax.resource.spi.security.PasswordCredential) PasswordCallback(javax.security.auth.callback.PasswordCallback) IOException(java.io.IOException) UnsupportedCallbackException(javax.security.auth.callback.UnsupportedCallbackException) Subject(javax.security.auth.Subject)

Example 3 with NamePrincipal

use of org.wildfly.security.auth.principal.NamePrincipal in project wildfly by wildfly.

the class EjbCorbaServant method _invoke.

/**
     * Receives IIOP requests to this servant's <code>EJBObject</code>s
     * and forwards them to the bean container, through the JBoss
     * <code>MBean</code> server.
     */
public OutputStream _invoke(final String opName, final InputStream in, final ResponseHandler handler) {
    EjbLogger.ROOT_LOGGER.tracef("EJBObject invocation: %s", opName);
    SkeletonStrategy op = methodInvokerMap.get(opName);
    if (op == null) {
        EjbLogger.ROOT_LOGGER.debugf("Unable to find opname '%s' valid operations:%s", opName, methodInvokerMap.keySet());
        throw new BAD_OPERATION(opName);
    }
    final NamespaceContextSelector selector = componentView.getComponent().getNamespaceContextSelector();
    final ClassLoader oldCl = WildFlySecurityManager.getCurrentContextClassLoaderPrivileged();
    NamespaceContextSelector.pushCurrentSelector(selector);
    try {
        WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(classLoader);
        org.omg.CORBA_2_3.portable.OutputStream out;
        try {
            Object retVal;
            if (!home && opName.equals("_get_handle")) {
                retVal = new HandleImplIIOP(orb.object_to_string(_this_object()));
            } else if (home && opName.equals("_get_homeHandle")) {
                retVal = homeHandle;
            } else if (home && opName.equals("_get_EJBMetaData")) {
                retVal = ejbMetaData;
            } else {
                Principal identityPrincipal = null;
                Principal principal = null;
                Object credential = null;
                if (this.sasCurrent != null) {
                    final byte[] incomingIdentity = this.sasCurrent.get_incoming_principal_name();
                    //we have an identity token, which is a trust based mechanism
                    if (incomingIdentity != null && incomingIdentity.length > 0) {
                        String name = new String(incomingIdentity, StandardCharsets.UTF_8);
                        int domainIndex = name.indexOf('@');
                        if (domainIndex > 0)
                            name = name.substring(0, domainIndex);
                        identityPrincipal = new NamePrincipal(name);
                    }
                    final byte[] incomingUsername = this.sasCurrent.get_incoming_username();
                    if (incomingUsername != null && incomingUsername.length > 0) {
                        final byte[] incomingPassword = this.sasCurrent.get_incoming_password();
                        String name = new String(incomingUsername, StandardCharsets.UTF_8);
                        int domainIndex = name.indexOf('@');
                        if (domainIndex > 0) {
                            name = name.substring(0, domainIndex);
                        }
                        principal = new NamePrincipal(name);
                        credential = new String(incomingPassword, StandardCharsets.UTF_8).toCharArray();
                    }
                }
                final Object[] params = op.readParams((org.omg.CORBA_2_3.portable.InputStream) in);
                if (!this.home && opName.equals("isIdentical") && params.length == 1) {
                    //handle isIdentical specially
                    Object val = params[0];
                    retVal = val instanceof org.omg.CORBA.Object && handleIsIdentical((org.omg.CORBA.Object) val);
                } else {
                    if (this.securityDomain != null) {
                        // an elytron security domain is available: authenticate and authorize the client before invoking the component.
                        SecurityIdentity identity = this.securityDomain.getAnonymousSecurityIdentity();
                        AuthenticationConfiguration authenticationConfiguration = AuthenticationConfiguration.EMPTY;
                        if (identityPrincipal != null) {
                            // permission to run as the identity token principal.
                            if (principal != null) {
                                char[] password = (char[]) credential;
                                authenticationConfiguration = authenticationConfiguration.useName(principal.getName()).usePassword(password);
                                SecurityIdentity authenticatedIdentity = this.authenticate(principal, password);
                                identity = authenticatedIdentity.createRunAsIdentity(identityPrincipal.getName(), true);
                            } else {
                                // no TLS nor initial context token found - check if the anonymous identity has
                                // permission to run as the identity principal.
                                identity = this.securityDomain.getAnonymousSecurityIdentity().createRunAsIdentity(identityPrincipal.getName(), true);
                            }
                        } else if (principal != null) {
                            char[] password = (char[]) credential;
                            // we have an initial context token containing a username/password pair.
                            authenticationConfiguration = authenticationConfiguration.useName(principal.getName()).usePassword(password);
                            identity = this.authenticate(principal, password);
                        }
                        final InterceptorContext interceptorContext = new InterceptorContext();
                        this.prepareInterceptorContext(op, params, interceptorContext);
                        try {
                            final AuthenticationContext context = AuthenticationContext.captureCurrent().with(MatchRule.ALL.matchProtocol("iiop"), authenticationConfiguration);
                            retVal = identity.runAs((PrivilegedExceptionAction<Object>) () -> context.run((PrivilegedExceptionAction<Object>) () -> this.componentView.invoke(interceptorContext)));
                        } catch (PrivilegedActionException e) {
                            throw e.getCause();
                        }
                    } else {
                        // legacy security behavior: setup the security context if a SASCurrent is available and invoke the component.
                        // One of the EJB security interceptors will authenticate and authorize the client.
                        SecurityContext legacyContext = null;
                        if (this.legacySecurityDomain != null && (identityPrincipal != null || principal != null)) {
                            // we don't have any real way to establish trust in identity based auth so we just use
                            // the SASCurrent as a credential, and a custom legacy login module can make a decision for us.
                            final Object finalCredential = identityPrincipal != null ? this.sasCurrent : credential;
                            final Principal finalPrincipal = identityPrincipal != null ? identityPrincipal : principal;
                            if (WildFlySecurityManager.isChecking()) {
                                legacyContext = AccessController.doPrivileged((PrivilegedExceptionAction<SecurityContext>) () -> {
                                    SecurityContext sc = SecurityContextFactory.createSecurityContext(this.legacySecurityDomain);
                                    sc.getUtil().createSubjectInfo(finalPrincipal, finalCredential, null);
                                    return sc;
                                });
                            } else {
                                legacyContext = SecurityContextFactory.createSecurityContext(this.legacySecurityDomain);
                                legacyContext.getUtil().createSubjectInfo(finalPrincipal, finalCredential, null);
                            }
                        }
                        if (legacyContext != null) {
                            setSecurityContextOnAssociation(legacyContext);
                        }
                        try {
                            final InterceptorContext interceptorContext = new InterceptorContext();
                            if (legacyContext != null) {
                                interceptorContext.putPrivateData(SecurityContext.class, legacyContext);
                            }
                            prepareInterceptorContext(op, params, interceptorContext);
                            retVal = this.componentView.invoke(interceptorContext);
                        } finally {
                            if (legacyContext != null) {
                                clearSecurityContextOnAssociation();
                            }
                        }
                    }
                }
            }
            out = (org.omg.CORBA_2_3.portable.OutputStream) handler.createReply();
            if (op.isNonVoid()) {
                op.writeRetval(out, retVal);
            }
        } catch (Throwable e) {
            EjbLogger.ROOT_LOGGER.trace("Exception in EJBObject invocation", e);
            if (e instanceof MBeanException) {
                e = ((MBeanException) e).getTargetException();
            }
            RmiIdlUtil.rethrowIfCorbaSystemException(e);
            out = (org.omg.CORBA_2_3.portable.OutputStream) handler.createExceptionReply();
            op.writeException(out, e);
        }
        return out;
    } finally {
        NamespaceContextSelector.popCurrentSelector();
        WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(oldCl);
    }
}
Also used : ServerAuthenticationContext(org.wildfly.security.auth.server.ServerAuthenticationContext) AuthenticationContext(org.wildfly.security.auth.client.AuthenticationContext) NamePrincipal(org.wildfly.security.auth.principal.NamePrincipal) OutputStream(org.omg.CORBA.portable.OutputStream) NamespaceContextSelector(org.jboss.as.naming.context.NamespaceContextSelector) HandleImplIIOP(org.jboss.ejb.iiop.HandleImplIIOP) InterceptorContext(org.jboss.invocation.InterceptorContext) AuthenticationConfiguration(org.wildfly.security.auth.client.AuthenticationConfiguration) PrivilegedActionException(java.security.PrivilegedActionException) SkeletonStrategy(org.wildfly.iiop.openjdk.rmi.marshal.strategy.SkeletonStrategy) PrivilegedExceptionAction(java.security.PrivilegedExceptionAction) SecurityIdentity(org.wildfly.security.auth.server.SecurityIdentity) SecurityContext(org.jboss.security.SecurityContext) MBeanException(javax.management.MBeanException) BAD_OPERATION(org.omg.CORBA.BAD_OPERATION) NamePrincipal(org.wildfly.security.auth.principal.NamePrincipal) Principal(java.security.Principal)

Example 4 with NamePrincipal

use of org.wildfly.security.auth.principal.NamePrincipal in project wildfly by wildfly.

the class SubjectUtil method fromSecurityIdentity.

public static Subject fromSecurityIdentity(final SecurityIdentity securityIdentity, Subject subject) {
    if (subject == null) {
        subject = new Subject();
    }
    subject.getPrincipals().add(securityIdentity.getPrincipal());
    // add the 'Roles' group to the subject containing the identity's mapped roles.
    Group rolesGroup = new SimpleGroup("Roles");
    for (String role : securityIdentity.getRoles()) {
        rolesGroup.addMember(new NamePrincipal(role));
    }
    subject.getPrincipals().add(rolesGroup);
    // add a 'CallerPrincipal' group containing the identity's principal.
    Group callerPrincipalGroup = new SimpleGroup("CallerPrincipal");
    callerPrincipalGroup.addMember(securityIdentity.getPrincipal());
    subject.getPrincipals().add(callerPrincipalGroup);
    // process the identity's public and private credentials.
    for (Credential credential : securityIdentity.getPublicCredentials()) {
        if (credential instanceof PublicKeyCredential) {
            subject.getPublicCredentials().add(credential.castAs(PublicKeyCredential.class).getPublicKey());
        } else if (credential instanceof X509CertificateChainPublicCredential) {
            subject.getPublicCredentials().add(credential.castAs(X509CertificateChainPublicCredential.class).getCertificateChain());
        } else {
            subject.getPublicCredentials().add(credential);
        }
    }
    for (Credential credential : securityIdentity.getPrivateCredentials()) {
        if (credential instanceof PasswordCredential) {
            addPrivateCredential(subject, credential.castAs(PasswordCredential.class).getPassword());
        } else if (credential instanceof SecretKeyCredential) {
            addPrivateCredential(subject, credential.castAs(SecretKeyCredential.class).getSecretKey());
        } else if (credential instanceof KeyPairCredential) {
            addPrivateCredential(subject, credential.castAs(KeyPairCredential.class).getKeyPair());
        } else if (credential instanceof X509CertificateChainPrivateCredential) {
            addPrivateCredential(subject, credential.castAs(X509CertificateChainPrivateCredential.class).getCertificateChain());
        } else {
            addPrivateCredential(subject, credential);
        }
    }
    // add the identity itself as a private credential - integration code can interact with the SI instead of the Subject if desired.
    addPrivateCredential(subject, securityIdentity);
    return subject;
}
Also used : Group(java.security.acl.Group) X509CertificateChainPrivateCredential(org.wildfly.security.credential.X509CertificateChainPrivateCredential) X509CertificateChainPublicCredential(org.wildfly.security.credential.X509CertificateChainPublicCredential) PublicKeyCredential(org.wildfly.security.credential.PublicKeyCredential) KeyPairCredential(org.wildfly.security.credential.KeyPairCredential) PasswordCredential(org.wildfly.security.credential.PasswordCredential) SecretKeyCredential(org.wildfly.security.credential.SecretKeyCredential) Credential(org.wildfly.security.credential.Credential) KeyPairCredential(org.wildfly.security.credential.KeyPairCredential) X509CertificateChainPrivateCredential(org.wildfly.security.credential.X509CertificateChainPrivateCredential) NamePrincipal(org.wildfly.security.auth.principal.NamePrincipal) PasswordCredential(org.wildfly.security.credential.PasswordCredential) PublicKeyCredential(org.wildfly.security.credential.PublicKeyCredential) X509CertificateChainPublicCredential(org.wildfly.security.credential.X509CertificateChainPublicCredential) Subject(javax.security.auth.Subject) SecretKeyCredential(org.wildfly.security.credential.SecretKeyCredential)

Aggregations

NamePrincipal (org.wildfly.security.auth.principal.NamePrincipal)4 Principal (java.security.Principal)2 PasswordCredential (javax.resource.spi.security.PasswordCredential)2 Subject (javax.security.auth.Subject)2 AuthenticationConfiguration (org.wildfly.security.auth.client.AuthenticationConfiguration)2 SecurityIdentity (org.wildfly.security.auth.server.SecurityIdentity)2 IOException (java.io.IOException)1 PrivilegedActionException (java.security.PrivilegedActionException)1 PrivilegedExceptionAction (java.security.PrivilegedExceptionAction)1 Group (java.security.acl.Group)1 HashSet (java.util.HashSet)1 MBeanException (javax.management.MBeanException)1 CallbackHandler (javax.security.auth.callback.CallbackHandler)1 NameCallback (javax.security.auth.callback.NameCallback)1 PasswordCallback (javax.security.auth.callback.PasswordCallback)1 UnsupportedCallbackException (javax.security.auth.callback.UnsupportedCallbackException)1 NamespaceContextSelector (org.jboss.as.naming.context.NamespaceContextSelector)1 HandleImplIIOP (org.jboss.ejb.iiop.HandleImplIIOP)1 InterceptorContext (org.jboss.invocation.InterceptorContext)1 SecurityContext (org.jboss.security.SecurityContext)1