Search in sources :

Example 16 with SecurityIdentity

use of org.wildfly.security.auth.server.SecurityIdentity 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 17 with SecurityIdentity

use of org.wildfly.security.auth.server.SecurityIdentity in project wildfly by wildfly.

the class RoleAddingInterceptor method processInvocation.

public Object processInvocation(final InterceptorContext context) throws Exception {
    final SecurityDomain securityDomain = context.getPrivateData(SecurityDomain.class);
    Assert.checkNotNullParam("securityDomain", securityDomain);
    final SecurityIdentity currentIdentity = securityDomain.getCurrentSecurityIdentity();
    final RoleMapper mergeMapper = roleMapper.or((roles) -> currentIdentity.getRoles(category));
    final SecurityIdentity newIdentity = currentIdentity.withRoleMapper(category, mergeMapper);
    try {
        return newIdentity.runAs(context);
    } catch (PrivilegedActionException e) {
        Throwable cause = e.getCause();
        if (cause != null) {
            if (cause instanceof Exception) {
                throw (Exception) cause;
            } else {
                throw new RuntimeException(e);
            }
        } else {
            throw e;
        }
    }
}
Also used : SecurityIdentity(org.wildfly.security.auth.server.SecurityIdentity) RoleMapper(org.wildfly.security.authz.RoleMapper) PrivilegedActionException(java.security.PrivilegedActionException) PrivilegedActionException(java.security.PrivilegedActionException) SecurityDomain(org.wildfly.security.auth.server.SecurityDomain)

Example 18 with SecurityIdentity

use of org.wildfly.security.auth.server.SecurityIdentity in project wildfly by wildfly.

the class RolesAllowedInterceptor method processInvocation.

public Object processInvocation(final InterceptorContext context) throws Exception {
    final Component component = context.getPrivateData(Component.class);
    if (!(component instanceof EJBComponent)) {
        throw EjbLogger.ROOT_LOGGER.unexpectedComponent(component, EJBComponent.class);
    }
    final Iterator<String> iterator = rolesAllowed.iterator();
    if (iterator.hasNext()) {
        final SecurityDomain securityDomain = context.getPrivateData(SecurityDomain.class);
        final SecurityIdentity identity = securityDomain.getCurrentSecurityIdentity();
        final Roles ejbRoles = identity.getRoles("ejb", true);
        do {
            final String role = iterator.next();
            if (ejbRoles.contains(role) || (role.equals("**") && !identity.isAnonymous())) {
                return context.proceed();
            }
        } while (iterator.hasNext());
    }
    throw EjbLogger.ROOT_LOGGER.invocationOfMethodNotAllowed(context.getMethod(), ((EJBComponent) component).getComponentName());
}
Also used : SecurityIdentity(org.wildfly.security.auth.server.SecurityIdentity) Roles(org.wildfly.security.authz.Roles) EJBComponent(org.jboss.as.ejb3.component.EJBComponent) Component(org.jboss.as.ee.component.Component) EJBComponent(org.jboss.as.ejb3.component.EJBComponent) SecurityDomain(org.wildfly.security.auth.server.SecurityDomain)

Example 19 with SecurityIdentity

use of org.wildfly.security.auth.server.SecurityIdentity in project wildfly by wildfly.

the class ElytronSASClientInterceptor method send_request.

@Override
public void send_request(ClientRequestInfo ri) throws ForwardRequest {
    try {
        CompoundSecMech secMech = CSIv2Util.getMatchingSecurityMech(ri, codec, EstablishTrustInClient.value, /* client supports */
        (short) 0);
        if (secMech == null) {
            return;
        }
        // these "null tokens" will be changed if needed.
        IdentityToken identityToken = ABSENT_IDENTITY_TOKEN;
        byte[] encodedAuthenticationToken = NO_AUTHENTICATION_TOKEN;
        final URI uri = this.getURI(ri);
        if (uri == null) {
            return;
        }
        SecurityDomain domain = SecurityDomain.getCurrent();
        SecurityIdentity currentIdentity = null;
        if (domain != null) {
            currentIdentity = domain.getCurrentSecurityIdentity();
        }
        final AuthenticationContext authContext;
        if (this.authContext != null) {
            authContext = this.authContext;
        } else if (currentIdentity == null || currentIdentity.isAnonymous()) {
            authContext = AuthenticationContext.captureCurrent();
        } else {
            authContext = AuthenticationContext.empty().with(MatchRule.ALL, AuthenticationConfiguration.EMPTY.useForwardedIdentity(domain));
        }
        if ((secMech.sas_context_mech.target_supports & IdentityAssertion.value) != 0) {
            final AuthenticationConfiguration configuration = AUTH_CONFIG_CLIENT.getAuthenticationConfiguration(uri, authContext, -1, null, null, "client-auth");
            final Principal principal = AUTH_CONFIG_CLIENT.getPrincipal(configuration);
            if (principal != null && principal != AnonymousPrincipal.getInstance()) {
                // The name scope needs to be externalized.
                String name = principal.getName();
                if (name.indexOf('@') < 0) {
                    // hardcoded (REVISIT!)
                    name += "@default";
                }
                byte[] principalName = name.getBytes(StandardCharsets.UTF_8);
                // encode the principal name as mandated by RFC2743.
                byte[] encodedName = CSIv2Util.encodeGssExportedName(principalName);
                // encapsulate the encoded name.
                Any any = ORB.init().create_any();
                byte[] encapsulatedEncodedName;
                GSS_NT_ExportedNameHelper.insert(any, encodedName);
                try {
                    encapsulatedEncodedName = codec.encode_value(any);
                } catch (InvalidTypeForEncoding e) {
                    throw IIOPLogger.ROOT_LOGGER.unexpectedException(e);
                }
                // create identity token.
                identityToken = new IdentityToken();
                identityToken.principal_name(encapsulatedEncodedName);
            } else if ((secMech.sas_context_mech.supported_identity_types & ITTAnonymous.value) != 0) {
                // no run-as or caller identity and the target supports ITTAnonymous: use the anonymous identity.
                identityToken = new IdentityToken();
                identityToken.anonymous(true);
            }
            // target might require an additional initial context token with a username/password pair for authentication.
            if ((secMech.as_context_mech.target_requires & EstablishTrustInClient.value) != 0) {
                encodedAuthenticationToken = this.createInitialContextToken(uri, "server-auth", secMech);
            }
        } else if ((secMech.as_context_mech.target_supports & EstablishTrustInClient.value) != 0) {
            // target doesn't require an identity token but supports username/password authentication - try to build
            // an initial context token using the configuration.
            encodedAuthenticationToken = this.createInitialContextToken(uri, "client-auth", secMech);
        }
        if (identityToken != ABSENT_IDENTITY_TOKEN || encodedAuthenticationToken != NO_AUTHENTICATION_TOKEN) {
            // at least one non-null token was created, create EstablishContext message with it.
            EstablishContext message = new // stateless ctx id
            EstablishContext(// stateless ctx id
            0, NO_AUTHORIZATION_TOKEN, identityToken, encodedAuthenticationToken);
            // create SAS context with the EstablishContext message.
            SASContextBody contextBody = new SASContextBody();
            contextBody.establish_msg(message);
            // stuff the SAS context into the outgoing request.
            final Any any = ORB.init().create_any();
            SASContextBodyHelper.insert(any, contextBody);
            ServiceContext sc = new ServiceContext(SAS_CONTEXT_ID, codec.encode_value(any));
            ri.add_request_service_context(sc, true);
        }
    } catch (Exception e) {
        throw IIOPLogger.ROOT_LOGGER.unexpectedException(e);
    }
}
Also used : AuthenticationConfiguration(org.wildfly.security.auth.client.AuthenticationConfiguration) AuthenticationContext(org.wildfly.security.auth.client.AuthenticationContext) CompoundSecMech(org.omg.CSIIOP.CompoundSecMech) ServiceContext(org.omg.IOP.ServiceContext) SASContextBody(org.omg.CSI.SASContextBody) URI(java.net.URI) Any(org.omg.CORBA.Any) InvalidTypeForEncoding(org.omg.IOP.CodecPackage.InvalidTypeForEncoding) URISyntaxException(java.net.URISyntaxException) UnsupportedCallbackException(javax.security.auth.callback.UnsupportedCallbackException) SecurityDomain(org.wildfly.security.auth.server.SecurityDomain) SecurityIdentity(org.wildfly.security.auth.server.SecurityIdentity) IdentityToken(org.omg.CSI.IdentityToken) EstablishContext(org.omg.CSI.EstablishContext) AnonymousPrincipal(org.wildfly.security.auth.principal.AnonymousPrincipal) Principal(java.security.Principal)

Example 20 with SecurityIdentity

use of org.wildfly.security.auth.server.SecurityIdentity in project wildfly by wildfly.

the class ElytronCallbackHandler method handle.

/**
     * {@inheritDoc}
     */
public void handle(javax.security.auth.callback.Callback[] callbacks) throws UnsupportedCallbackException, IOException {
    if (SUBSYSTEM_RA_LOGGER.isTraceEnabled())
        SUBSYSTEM_RA_LOGGER.elytronHandlerHandle(Arrays.toString(callbacks));
    // is the anonymous one.
    if (this.executionSubject != null) {
        final SecurityIdentity subjectIdentity = this.getPrivateCredential(this.executionSubject, SecurityIdentity.class);
        if (subjectIdentity != null && !subjectIdentity.isAnonymous()) {
            return;
        }
    }
    if (callbacks != null && callbacks.length > 0) {
        if (this.mappings != null && this.mappings.isMappingRequired()) {
            callbacks = this.mappings.mapCallbacks(callbacks);
        }
        GroupPrincipalCallback groupPrincipalCallback = null;
        CallerPrincipalCallback callerPrincipalCallback = null;
        PasswordValidationCallback passwordValidationCallback = null;
        for (javax.security.auth.callback.Callback callback : callbacks) {
            if (callback instanceof GroupPrincipalCallback) {
                groupPrincipalCallback = (GroupPrincipalCallback) callback;
                if (this.executionSubject == null) {
                    this.executionSubject = groupPrincipalCallback.getSubject();
                } else if (!this.executionSubject.equals(groupPrincipalCallback.getSubject())) {
                // TODO merge the contents of the subjects?
                }
            } else if (callback instanceof CallerPrincipalCallback) {
                callerPrincipalCallback = (CallerPrincipalCallback) callback;
                if (this.executionSubject == null) {
                    this.executionSubject = callerPrincipalCallback.getSubject();
                } else if (!this.executionSubject.equals(callerPrincipalCallback.getSubject())) {
                // TODO merge the contents of the subjects?
                }
            } else if (callback instanceof PasswordValidationCallback) {
                passwordValidationCallback = (PasswordValidationCallback) callback;
                if (this.executionSubject == null) {
                    this.executionSubject = passwordValidationCallback.getSubject();
                } else if (!this.executionSubject.equals(passwordValidationCallback.getSubject())) {
                // TODO merge the contents of the subjects?
                }
            } else {
                throw new UnsupportedCallbackException(callback);
            }
        }
        this.handleInternal(callerPrincipalCallback, groupPrincipalCallback, passwordValidationCallback);
    }
}
Also used : SecurityIdentity(org.wildfly.security.auth.server.SecurityIdentity) CallerPrincipalCallback(javax.security.auth.message.callback.CallerPrincipalCallback) GroupPrincipalCallback(javax.security.auth.message.callback.GroupPrincipalCallback) PasswordValidationCallback(javax.security.auth.message.callback.PasswordValidationCallback) UnsupportedCallbackException(javax.security.auth.callback.UnsupportedCallbackException)

Aggregations

SecurityIdentity (org.wildfly.security.auth.server.SecurityIdentity)37 Test (org.junit.Test)10 Properties (java.util.Properties)8 SecurityDomain (org.wildfly.security.auth.server.SecurityDomain)8 Principal (java.security.Principal)7 PrivilegedActionException (java.security.PrivilegedActionException)5 JobSecurityException (javax.batch.operations.JobSecurityException)5 Component (org.jboss.as.ee.component.Component)4 EJBComponent (org.jboss.as.ejb3.component.EJBComponent)4 Connection (org.jboss.remoting3.Connection)4 HashSet (java.util.HashSet)3 RealmUser (org.jboss.as.core.security.RealmUser)3 InterceptorContext (org.jboss.invocation.InterceptorContext)3 SecurityContext (org.jboss.security.SecurityContext)3 PrivilegedAction (java.security.PrivilegedAction)2 PrivilegedExceptionAction (java.security.PrivilegedExceptionAction)2 ManagedTask (javax.enterprise.concurrent.ManagedTask)2 Subject (javax.security.auth.Subject)2 UnsupportedCallbackException (javax.security.auth.callback.UnsupportedCallbackException)2 SessionBeanComponent (org.jboss.as.ejb3.component.session.SessionBeanComponent)2