Search in sources :

Example 66 with KerberosPrincipal

use of javax.security.auth.kerberos.KerberosPrincipal in project ddf by codice.

the class SubjectUtilsTest method testKerberosDisplayName.

@Test
public void testKerberosDisplayName() {
    ddf.security.Subject subject = getSubjectWithPrincipal(new KerberosPrincipal("kerby/ddf.org@REALM"));
    assertEquals("kerby", subjectUtils.getName(subject, null, true));
}
Also used : KerberosPrincipal(javax.security.auth.kerberos.KerberosPrincipal) Test(org.junit.Test)

Example 67 with KerberosPrincipal

use of javax.security.auth.kerberos.KerberosPrincipal in project cxf by apache.

the class DefaultWSS4JSecurityContextCreator method createSecurityContext.

protected SecurityContext createSecurityContext(SoapMessage msg, boolean useJAASSubject, WSSecurityEngineResult wsResult) {
    final Principal p = (Principal) wsResult.get(WSSecurityEngineResult.TAG_PRINCIPAL);
    final Subject subject = (Subject) wsResult.get(WSSecurityEngineResult.TAG_SUBJECT);
    if (subject != null && !(p instanceof KerberosPrincipal) && useJAASSubject) {
        String roleClassifier = (String) msg.getContextualProperty(SecurityConstants.SUBJECT_ROLE_CLASSIFIER);
        if (roleClassifier != null && !"".equals(roleClassifier)) {
            String roleClassifierType = (String) msg.getContextualProperty(SecurityConstants.SUBJECT_ROLE_CLASSIFIER_TYPE);
            if (roleClassifierType == null || "".equals(roleClassifierType)) {
                roleClassifierType = "prefix";
            }
            return new RolePrefixSecurityContextImpl(subject, roleClassifier, roleClassifierType);
        }
        return new DefaultSecurityContext(p, subject);
    } else if (p != null) {
        boolean utWithCallbacks = MessageUtils.getContextualBoolean(msg, SecurityConstants.VALIDATE_TOKEN, true);
        if (!utWithCallbacks) {
            WSS4JTokenConverter.convertToken(msg, p);
        }
        Object receivedAssertion = wsResult.get(WSSecurityEngineResult.TAG_TRANSFORMED_TOKEN);
        if (receivedAssertion == null) {
            receivedAssertion = wsResult.get(WSSecurityEngineResult.TAG_SAML_ASSERTION);
        }
        if (wsResult.get(WSSecurityEngineResult.TAG_DELEGATION_CREDENTIAL) != null) {
            msg.put(SecurityConstants.DELEGATED_CREDENTIAL, wsResult.get(WSSecurityEngineResult.TAG_DELEGATION_CREDENTIAL));
        }
        if (receivedAssertion instanceof SamlAssertionWrapper) {
            String roleAttributeName = (String) SecurityUtils.getSecurityPropertyValue(SecurityConstants.SAML_ROLE_ATTRIBUTENAME, msg);
            if (roleAttributeName == null || roleAttributeName.length() == 0) {
                roleAttributeName = WSS4JInInterceptor.SAML_ROLE_ATTRIBUTENAME_DEFAULT;
            }
            ClaimCollection claims = SAMLUtils.getClaims((SamlAssertionWrapper) receivedAssertion);
            Set<Principal> roles = SAMLUtils.parseRolesFromClaims(claims, roleAttributeName, null);
            SAMLSecurityContext context = new SAMLSecurityContext(p, roles, claims);
            context.setIssuer(SAMLUtils.getIssuer(receivedAssertion));
            context.setAssertionElement(SAMLUtils.getAssertionElement(receivedAssertion));
            return context;
        }
        return createSecurityContext(p);
    }
    return null;
}
Also used : DefaultSecurityContext(org.apache.cxf.interceptor.security.DefaultSecurityContext) KerberosPrincipal(javax.security.auth.kerberos.KerberosPrincipal) RolePrefixSecurityContextImpl(org.apache.cxf.interceptor.security.RolePrefixSecurityContextImpl) Set(java.util.Set) SAMLSecurityContext(org.apache.cxf.rt.security.saml.claims.SAMLSecurityContext) SamlAssertionWrapper(org.apache.wss4j.common.saml.SamlAssertionWrapper) ClaimCollection(org.apache.cxf.rt.security.claims.ClaimCollection) KerberosPrincipal(javax.security.auth.kerberos.KerberosPrincipal) Principal(java.security.Principal) Subject(javax.security.auth.Subject)

Example 68 with KerberosPrincipal

use of javax.security.auth.kerberos.KerberosPrincipal in project cxf by apache.

the class LdapGroupClaimsHandler method retrieveClaimValues.

public ProcessedClaimCollection retrieveClaimValues(ClaimCollection claims, ClaimsParameters parameters) {
    boolean found = false;
    for (Claim claim : claims) {
        if (claim.getClaimType().toString().equals(this.groupURI)) {
            found = true;
            break;
        }
    }
    if (!found) {
        return new ProcessedClaimCollection();
    }
    String user = null;
    Principal principal = parameters.getPrincipal();
    if (principal instanceof KerberosPrincipal) {
        KerberosPrincipal kp = (KerberosPrincipal) principal;
        StringTokenizer st = new StringTokenizer(kp.getName(), "@");
        user = st.nextToken();
    } else if (principal instanceof X500Principal) {
        X500Principal x500p = (X500Principal) principal;
        LOG.warning("Unsupported principal type X500: " + x500p.getName());
    } else if (principal != null) {
        user = principal.getName();
        if (user == null) {
            LOG.warning("Principal name must not be null");
        }
    } else {
        LOG.warning("Principal is null");
    }
    if (user == null) {
        return new ProcessedClaimCollection();
    }
    if (!LdapUtils.isDN(user)) {
        Name dn = LdapUtils.getDnOfEntry(ldap, this.userBaseDn, this.getUserObjectClass(), this.getUserNameAttribute(), user);
        if (dn != null) {
            user = dn.toString();
            if (LOG.isLoggable(Level.FINE)) {
                LOG.fine("DN for (" + this.getUserNameAttribute() + "=" + user + ") found: " + user);
            }
        } else {
            LOG.warning("DN not found for user '" + user + "'");
            return new ProcessedClaimCollection();
        }
    }
    if (LOG.isLoggable(Level.FINER)) {
        LOG.finer("Retrieve groups for user " + user);
    }
    List<Filter> filters = new ArrayList<>();
    filters.add(new EqualsFilter(this.groupMemberAttribute, user));
    if (customFilters != null && !customFilters.isEmpty()) {
        filters.addAll(customFilters);
    }
    List<String> groups = LdapUtils.getAttributeOfEntries(ldap, this.groupBaseDn, this.getGroupObjectClass(), filters, "cn");
    if (groups == null || groups.isEmpty()) {
        if (LOG.isLoggable(Level.INFO)) {
            LOG.info("No groups found for user '" + user + "'");
        }
        return new ProcessedClaimCollection();
    }
    if (LOG.isLoggable(Level.FINE)) {
        LOG.fine("Groups for user '" + parameters.getPrincipal().getName() + "': " + groups);
    }
    String scope = null;
    if (getAppliesToScopeMapping() != null && !getAppliesToScopeMapping().isEmpty() && parameters.getAppliesToAddress() != null) {
        scope = getAppliesToScopeMapping().get(parameters.getAppliesToAddress());
        if (LOG.isLoggable(Level.FINE)) {
            LOG.fine("AppliesTo matches with scope: " + scope);
        }
    }
    String regex = this.groupNameGlobalFilter;
    regex = regex.replaceAll(ROLE, ".*");
    Pattern globalPattern = Pattern.compile(regex);
    // If AppliesTo value can be mapped to a Scope Name
    // ex. https://localhost/doubleit/services/doubleittransport  -> Demo
    Pattern scopePattern = null;
    if (scope != null) {
        regex = this.groupNameScopedFilter;
        regex = regex.replaceAll(SCOPE, scope).replaceAll(ROLE, ".*");
        scopePattern = Pattern.compile(regex);
    }
    List<String> filteredGroups = new ArrayList<>();
    for (String group : groups) {
        if (scopePattern != null && scopePattern.matcher(group).matches()) {
            // Group matches the scoped filter
            // ex. (default groupNameScopeFilter)
            // Demo_User -> Role=User
            // Demo_Admin -> Role=Admin
            String filter = this.groupNameScopedFilter;
            final String role;
            if (isUseFullGroupNameAsValue()) {
                role = group;
            } else {
                role = parseRole(group, filter.replaceAll(SCOPE, scope));
            }
            filteredGroups.add(role);
        } else {
            if (globalPattern.matcher(group).matches()) {
                // Group matches the global filter
                // ex. (default groupNameGlobalFilter)
                // User -> Role=User
                // Admin -> Role=Admin
                final String role;
                if (isUseFullGroupNameAsValue()) {
                    role = group;
                } else {
                    role = parseRole(group, this.groupNameGlobalFilter);
                }
                filteredGroups.add(role);
            } else if (LOG.isLoggable(Level.FINER)) {
                LOG.finer("Group '" + group + "' doesn't match scoped and global group filter");
            }
        }
    }
    LOG.info("Filtered groups: " + filteredGroups);
    if (filteredGroups.isEmpty()) {
        LOG.info("No matching groups found for user '" + principal + "'");
        return new ProcessedClaimCollection();
    }
    ProcessedClaimCollection claimsColl = new ProcessedClaimCollection();
    ProcessedClaim c = new ProcessedClaim();
    c.setClaimType(URI.create(this.groupURI));
    c.setPrincipal(principal);
    c.setValues(new ArrayList<>(filteredGroups));
    // c.setIssuer(issuer);
    // c.setOriginalIssuer(originalIssuer);
    // c.setNamespace(namespace);
    claimsColl.add(c);
    return claimsColl;
}
Also used : KerberosPrincipal(javax.security.auth.kerberos.KerberosPrincipal) Pattern(java.util.regex.Pattern) ArrayList(java.util.ArrayList) Name(javax.naming.Name) StringTokenizer(java.util.StringTokenizer) Filter(org.springframework.ldap.filter.Filter) EqualsFilter(org.springframework.ldap.filter.EqualsFilter) X500Principal(javax.security.auth.x500.X500Principal) EqualsFilter(org.springframework.ldap.filter.EqualsFilter) Claim(org.apache.cxf.rt.security.claims.Claim) X500Principal(javax.security.auth.x500.X500Principal) KerberosPrincipal(javax.security.auth.kerberos.KerberosPrincipal) Principal(java.security.Principal)

Example 69 with KerberosPrincipal

use of javax.security.auth.kerberos.KerberosPrincipal in project cxf by apache.

the class DefaultSubjectProvider method createSubjectBean.

/**
 * Create the SubjectBean using the specified principal.
 */
protected SubjectBean createSubjectBean(Principal principal, SubjectProviderParameters subjectProviderParameters) {
    TokenProviderParameters providerParameters = subjectProviderParameters.getProviderParameters();
    TokenRequirements tokenRequirements = providerParameters.getTokenRequirements();
    KeyRequirements keyRequirements = providerParameters.getKeyRequirements();
    String tokenType = tokenRequirements.getTokenType();
    String keyType = keyRequirements.getKeyType();
    String confirmationMethod = getSubjectConfirmationMethod(tokenType, keyType);
    String subjectName = principal.getName();
    String localSubjectNameIDFormat = subjectNameIDFormat;
    if (SAML2Constants.NAMEID_FORMAT_UNSPECIFIED.equals(localSubjectNameIDFormat) && principal instanceof X500Principal) {
        // Just use the "cn" instead of the entire DN
        try {
            LdapName ln = new LdapName(principal.getName());
            for (Rdn rdn : ln.getRdns()) {
                if ("CN".equalsIgnoreCase(rdn.getType()) && (rdn.getValue() instanceof String)) {
                    subjectName = (String) rdn.getValue();
                    break;
                }
            }
        } catch (Throwable ex) {
            subjectName = principal.getName();
        // Ignore, not X500 compliant thus use the whole string as the value
        }
    } else if (!SAML2Constants.NAMEID_FORMAT_UNSPECIFIED.equals(localSubjectNameIDFormat)) {
        /* Set subjectNameIDFormat correctly based on type of principal
                unless already set to some value other than unspecified */
        if (principal instanceof UsernameTokenPrincipal) {
            localSubjectNameIDFormat = SAML2Constants.NAMEID_FORMAT_PERSISTENT;
        } else if (principal instanceof X500Principal) {
            localSubjectNameIDFormat = SAML2Constants.NAMEID_FORMAT_X509_SUBJECT_NAME;
        } else if (principal instanceof KerberosPrincipal) {
            localSubjectNameIDFormat = SAML2Constants.NAMEID_FORMAT_KERBEROS;
        } else if (localSubjectNameIDFormat == null) {
            localSubjectNameIDFormat = SAML2Constants.NAMEID_FORMAT_UNSPECIFIED;
        }
    }
    SubjectBean subjectBean = new SubjectBean(subjectName, subjectNameQualifier, confirmationMethod);
    if (LOG.isLoggable(Level.FINE)) {
        LOG.fine("Creating new subject with principal name: " + principal.getName());
    }
    subjectBean.setSubjectNameIDFormat(localSubjectNameIDFormat);
    return subjectBean;
}
Also used : KerberosPrincipal(javax.security.auth.kerberos.KerberosPrincipal) SubjectBean(org.apache.wss4j.common.saml.bean.SubjectBean) TokenRequirements(org.apache.cxf.sts.request.TokenRequirements) UsernameTokenPrincipal(org.apache.wss4j.common.principal.UsernameTokenPrincipal) X500Principal(javax.security.auth.x500.X500Principal) KeyRequirements(org.apache.cxf.sts.request.KeyRequirements) Rdn(javax.naming.ldap.Rdn) LdapName(javax.naming.ldap.LdapName)

Example 70 with KerberosPrincipal

use of javax.security.auth.kerberos.KerberosPrincipal in project athenz by yahoo.

the class KerberosAuthorityTest method testKerberosAuthorityIsOurPrincipal.

@Test(groups = "kerberos-tests")
public void testKerberosAuthorityIsOurPrincipal() {
    System.setProperty(KerberosAuthority.KRB_PROP_KEYTAB, "src/test/resources/example.keytab");
    System.setProperty(KerberosAuthority.KRB_PROP_SVCPRPL, "myserver@EXAMPLE.COM");
    System.setProperty(KerberosAuthority.KRB_PROP_LOGIN_CB_CLASS, KRB_LOGIN_CB_CLASS);
    System.setProperty("sun.security.krb5.debug", "true");
    KerberosAuthority kauth = new KerberosAuthority();
    kauth.initialize();
    Exception initState = kauth.getInitState();
    assertNull(initState);
    KerberosPrincipal princ = new KerberosPrincipal("myserver@EXAMPLE.COM");
    String token = "YIIB6wYJKoZIhvcSAQICAQBuggHaMIIB1qADAgEFoQMCAQ6iBwMFAAAAAACjggEGYYIBAjCB/6ADAgEFoQ0bC0VYQU1QTEUuQ09NojAwLqADAgEAoScwJRsHZGF0YWh1YhsTZGF0YWh1Yi5leGFtcGxlLmNvbRsFYnVsbHmjgbYwgbOgAwIBA6KBqwSBqMJGf4H5nrRIdDyNxHp5fwxW6lsiFi+qUjryPvgiOAl/XldfwmKd9wXbQn00VBNhK+oVxmKv0V0J80e4oTdUnc+NlU/BJNCfsLPFTdYntc4A/ffdnsY7/U5HktTaWMfhvWxYocvhqISFTIFUT1+pH5742IWYNTgvFd5vkudibB3ijCanbMYv9CQXEjV+380rnf3gdLD2JGuxmaU78aJjDDKETL6Ck/qz8KSBtjCBs6ADAgEDooGrBIGoMrzLCTUi59wEoWX02+42K5m1MzW6HMNSuvfQeVGJdzPBsiFmZweNfJF6L9LdmLjQR4jSVUhVo3neFZmUN8G532wvZeKbHOtkXTnLRRdif+DoKyI8GOkbHu1CZlevcQZ0sgzyiH0wfQ/0nguE4kH7a2bM7HlV7N6MRGkC4DDkJZDNHxQr27FbZqrqEyw498HXPTtF93JGsKjXB8Z/wDaPs4PpdfoThTol";
    byte[] asn1Encoding = token.getBytes();
    byte[] sessionKey = "xyz".getBytes();
    long endMillis = System.currentTimeMillis() + 2000;
    java.util.Date endDate = new java.util.Date();
    endDate.setTime(endMillis);
    KerberosTicket ticket = new KerberosTicket(asn1Encoding, princ, princ, sessionKey, 0, null, null, null, endDate, null, null);
    boolean ours = kauth.isTargetPrincipal(ticket, "myserver@EXAMPLE.COM");
    assertTrue(ours);
    KerberosPrincipal clientPrinc = new KerberosPrincipal("myclient@EXAMPLE.COM");
    ticket = new KerberosTicket(asn1Encoding, princ, clientPrinc, sessionKey, 0, null, null, null, endDate, null, null);
    ours = kauth.isTargetPrincipal(ticket, "myservice@EXAPLE.COM");
    assertFalse(ours);
    System.clearProperty(KerberosAuthority.KRB_PROP_SVCPRPL);
    System.clearProperty(KerberosAuthority.KRB_PROP_KEYTAB);
    System.clearProperty(KerberosAuthority.KRB_PROP_LOGIN_CB_CLASS);
}
Also used : KerberosPrincipal(javax.security.auth.kerberos.KerberosPrincipal) KerberosTicket(javax.security.auth.kerberos.KerberosTicket) Test(org.testng.annotations.Test)

Aggregations

KerberosPrincipal (javax.security.auth.kerberos.KerberosPrincipal)71 Principal (java.security.Principal)36 Subject (javax.security.auth.Subject)31 HashSet (java.util.HashSet)21 LoginContext (javax.security.auth.login.LoginContext)20 Test (org.junit.Test)14 X500Principal (javax.security.auth.x500.X500Principal)13 KerberosTicket (javax.security.auth.kerberos.KerberosTicket)11 IOException (java.io.IOException)10 File (java.io.File)9 KerberosKey (javax.security.auth.kerberos.KerberosKey)9 PrivilegedActionException (java.security.PrivilegedActionException)8 StringTokenizer (java.util.StringTokenizer)6 PrivilegedExceptionAction (java.security.PrivilegedExceptionAction)3 ArrayList (java.util.ArrayList)3 Date (java.util.Date)3 HashMap (java.util.HashMap)3 Properties (java.util.Properties)3 CallbackHandler (javax.security.auth.callback.CallbackHandler)3 KeyTab (javax.security.auth.kerberos.KeyTab)3