org.opensaml.xml.security.credential.UsageType Java Examples

The following examples show how to use org.opensaml.xml.security.credential.UsageType. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: PostBindingAdapter.java    From MaxKey with Apache License 2.0 6 votes vote down vote up
public Credential  buildSPSigningCredential() throws Exception{
	KeyStore trustKeyStore = KeyStoreUtil.bytes2KeyStore(getSaml20Details().getKeyStore(),
			getKeyStoreLoader().getKeyStore().getType(),
			getKeyStoreLoader().getKeystorePassword());
	
	TrustResolver trustResolver=new TrustResolver();
	KeyStoreCredentialResolver credentialResolver =trustResolver.buildKeyStoreCredentialResolver(
						trustKeyStore, 
						getSaml20Details().getEntityId(), 
						getKeyStoreLoader().getKeystorePassword());

	CriteriaSet criteriaSet = new CriteriaSet();
	criteriaSet.add(new EntityIDCriteria(getSaml20Details().getEntityId()));
	criteriaSet.add(new UsageCriteria(UsageType.ENCRYPTION));

	try {
		spSigningCredential = credentialResolver.resolveSingle(criteriaSet);
	} catch (SecurityException e) {
		logger.error("Credential Resolver error . ", e);
		throw new Exception(e);
	}
	Validate.notNull(spSigningCredential);
	
	return spSigningCredential;
}
 
Example #2
Source File: ConsumerEndpoint.java    From MaxKey with Apache License 2.0 6 votes vote down vote up
public void afterPropertiesSet() throws Exception {

		authnRequestGenerator = new AuthnRequestGenerator(keyStoreLoader.getEntityName(), timeService, idService);
		endpointGenerator = new EndpointGenerator();

		CriteriaSet criteriaSet = new CriteriaSet();
		criteriaSet.add(new EntityIDCriteria(keyStoreLoader.getEntityName()));
		criteriaSet.add(new UsageCriteria(UsageType.SIGNING));

		try {
			signingCredential = credentialResolver.resolveSingle(criteriaSet);
		} catch (SecurityException e) {
			logger.error("证书解析出错", e);
			throw new Exception(e);
		}
		Validate.notNull(signingCredential);

	}
 
Example #3
Source File: SignatureSecurityPolicyRule.java    From MaxKey with Apache License 2.0 6 votes vote down vote up
private void checkMessageSignature(MessageContext messageContext,SignableSAMLObject samlMessage) throws SecurityPolicyException {
	CriteriaSet criteriaSet = new CriteriaSet();
	logger.debug("Inbound issuer is {}", messageContext.getInboundMessageIssuer());
	// System.out.println("Inbound issuer is {} "+ messageContext.getInboundMessageIssuer());
	//https://localhost-dev-ed.my.salesforce.com
	criteriaSet.add( new EntityIDCriteria(messageContext.getInboundMessageIssuer()));	
	//criteriaSet.add( new EntityIDCriteria("https://localhost-dev-ed.my.salesforce.com"));
	criteriaSet.add( new UsageCriteria(UsageType.SIGNING) );

	try {
		if (!trustEngine.validate( samlMessage.getSignature(), criteriaSet)) {
			throw new SecurityPolicyException("Signature was either invalid or signing key could not be established as trusted");
		}
	} catch (SecurityException se) {
		// System.out.println("Error evaluating the signature"+se.toString());
		throw new SecurityPolicyException("Error evaluating the signature",se);
	}
}
 
Example #4
Source File: KeyDescriptorMarshaller.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/** {@inheritDoc} */
protected void marshallAttributes(XMLObject xmlObject, Element domElement) throws MarshallingException {
    KeyDescriptor keyDescriptor = (KeyDescriptor) xmlObject;

    if (keyDescriptor.getUse() != null) {
        UsageType use = keyDescriptor.getUse();
        // UsageType enum contains more values than are allowed by SAML 2 schema
        if (use.equals(UsageType.SIGNING) || use.equals(UsageType.ENCRYPTION)) {
            domElement.setAttribute(KeyDescriptor.USE_ATTRIB_NAME, use.toString().toLowerCase());
        } else if (use.equals(UsageType.UNSPECIFIED)) {
            // emit nothing for unspecified - this is semantically equivalent to non-existent attribute
        } else {
            // Just in case values are unknowingly added to UsageType in the future...
            throw new MarshallingException("KeyDescriptor had illegal value for use attribute: " + use.toString());
        }
    }
}
 
Example #5
Source File: KeyDescriptorUnmarshaller.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/** {@inheritDoc} */
protected void processAttribute(XMLObject samlObject, Attr attribute) throws UnmarshallingException {
    KeyDescriptor keyDescriptor = (KeyDescriptor) samlObject;

    if (attribute.getName().equals(KeyDescriptor.USE_ATTRIB_NAME)) {
        try {
            UsageType usageType = UsageType.valueOf(UsageType.class, attribute.getValue().toUpperCase());
            // Only allow the enum values specified in the schema.
            if (usageType != UsageType.SIGNING && usageType != UsageType.ENCRYPTION) {
                throw new UnmarshallingException("Invalid key usage type: " + attribute.getValue());
            }
            keyDescriptor.setUse(usageType);
        } catch (IllegalArgumentException e) {
            throw new UnmarshallingException("Invalid key usage type: " + attribute.getValue());
        }
    }

    super.processAttribute(samlObject, attribute);
}
 
Example #6
Source File: BaseSAMLXMLSignatureSecurityPolicyRule.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/** {@inheritDoc} */
protected CriteriaSet buildCriteriaSet(String entityID, MessageContext messageContext)
    throws SecurityPolicyException {
    if (!(messageContext instanceof SAMLMessageContext)) {
        log.error("Supplied message context was not an instance of SAMLMessageContext, can not build criteria set from SAML metadata parameters");
        throw new SecurityPolicyException("Supplied message context was not an instance of SAMLMessageContext");
    }
    
    SAMLMessageContext samlContext = (SAMLMessageContext) messageContext;
    
    CriteriaSet criteriaSet = new CriteriaSet();
    if (! DatatypeHelper.isEmpty(entityID)) {
        criteriaSet.add(new EntityIDCriteria(entityID) );
    }
    
    MetadataCriteria mdCriteria = 
        new MetadataCriteria(samlContext.getPeerEntityRole(), samlContext.getInboundSAMLProtocol());
    criteriaSet.add(mdCriteria);
    
    criteriaSet.add( new UsageCriteria(UsageType.SIGNING) );
    
    return criteriaSet;
}
 
Example #7
Source File: MetadataCredentialResolver.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Constructor.
 * 
 * @param entityID entity ID of the credential owner
 * @param entityRole role in which the entity is operating
 * @param entityProtocol protocol over which the entity is operating (may be null)
 * @param entityUsage usage of the resolved credentials
 */
protected MetadataCacheKey(String entityID, QName entityRole, String entityProtocol, UsageType entityUsage) {
    if (entityID == null) {
        throw new IllegalArgumentException("Entity ID may not be null");
    }
    if (entityRole == null) {
        throw new IllegalArgumentException("Entity role may not be null");
    }
    if (entityUsage == null) {
        throw new IllegalArgumentException("Credential usage may not be null");
    }
    id = entityID;
    role = entityRole;
    protocol = entityProtocol;
    usage = entityUsage;
}
 
Example #8
Source File: BaseSAMLSimpleSignatureSecurityPolicyRule.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Build a criteria set suitable for input to the trust engine.
 * 
 * @param entityID the candidate issuer entity ID which is being evaluated
 * @param samlContext the message context which is being evaluated
 * @return a newly constructly set of criteria suitable for the configured trust engine
 * @throws SecurityPolicyException thrown if criteria set can not be constructed
 */
protected CriteriaSet buildCriteriaSet(String entityID, SAMLMessageContext samlContext)
        throws SecurityPolicyException {

    CriteriaSet criteriaSet = new CriteriaSet();
    if (!DatatypeHelper.isEmpty(entityID)) {
        criteriaSet.add(new EntityIDCriteria(entityID));
    }

    MetadataCriteria mdCriteria = new MetadataCriteria(samlContext.getPeerEntityRole(), samlContext
            .getInboundSAMLProtocol());
    criteriaSet.add(mdCriteria);

    criteriaSet.add(new UsageCriteria(UsageType.SIGNING));

    return criteriaSet;
}
 
Example #9
Source File: ServletRequestX509CredentialAdapter.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Constructor.
 *
 * @param request the servlet request
 */
public ServletRequestX509CredentialAdapter(ServletRequest request) {
    X509Certificate[] chain = (X509Certificate[]) request.getAttribute(X509_CERT_REQUEST_ATTRIBUTE);
    if (chain == null || chain.length == 0) {
        throw new IllegalArgumentException("Servlet request does not contain X.509 certificates in attribute "
                + X509_CERT_REQUEST_ATTRIBUTE);
    }

    setEntityCertificate(chain[0]);
    setEntityCertificateChain(Arrays.asList(chain));
    setUsageType(UsageType.SIGNING);
}
 
Example #10
Source File: MetadataGenerator.java    From MaxKey with Apache License 2.0 5 votes vote down vote up
public KeyDescriptor generateEncryptionKeyDescriptor(Credential signingCredential){
 KeyDescriptor encryptionKeyDescriptor =  new KeyDescriptorBuilder().buildObject();

 encryptionKeyDescriptor.setUse(UsageType.ENCRYPTION); 
 
 // Generating key info. The element will contain the public key. The key is used to by the IDP to encrypt data  
 try {  
  encryptionKeyDescriptor.setKeyInfo(getKeyInfoGenerator().generate(signingCredential));  
 } catch (SecurityException e) {  
  logger.error(e.getMessage(), e);  
 }  
 
 return encryptionKeyDescriptor;
}
 
Example #11
Source File: MetadataGenerator.java    From MaxKey with Apache License 2.0 5 votes vote down vote up
public KeyDescriptor generateSignKeyDescriptor(Credential signingCredential){
 KeyDescriptor signKeyDescriptor = new KeyDescriptorBuilder().buildObject();
    
    signKeyDescriptor.setUse(UsageType.SIGNING);  //Set usage  
    
    // Generating key info. The element will contain the public key. The key is used to by the IDP to verify signatures  
    try {  
     signKeyDescriptor.setKeyInfo(getKeyInfoGenerator().generate(signingCredential));  
    } catch (SecurityException e) {  
 	   logger.error(e.getMessage(), e);  
    }  
    
    return signKeyDescriptor;
}
 
Example #12
Source File: PostBindingAdapter.java    From MaxKey with Apache License 2.0 5 votes vote down vote up
public void  buildCredentialResolver(CredentialResolver credentialResolver) throws Exception{
	this.credentialResolver=credentialResolver;
	CriteriaSet criteriaSet = new CriteriaSet();
	criteriaSet.add(new EntityIDCriteria(getKeyStoreLoader().getEntityName()));
	criteriaSet.add(new UsageCriteria(UsageType.SIGNING));

	try {
		signingCredential = credentialResolver.resolveSingle(criteriaSet);
	} catch (SecurityException e) {
		logger.error("Credential Resolver error . ", e);
		throw new Exception(e);
	}
	Validate.notNull(signingCredential);
}
 
Example #13
Source File: KeyDescriptorImpl.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/** {@inheritDoc} */
public void setUse(UsageType newType) {
    if (newType != null) {
        keyUseType = prepareForAssignment(keyUseType, newType);
    } else {
        keyUseType = prepareForAssignment(keyUseType, UsageType.UNSPECIFIED);
    }
}
 
Example #14
Source File: SignatureValidationFilter.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Build the criteria set which will be used as input to the configured trust engine.
 * 
 * @param signedMetadata the metadata element whose signature is being verified
 * @param metadataEntryName the EntityDescriptor entityID, EntitiesDescriptor Name,
 *                          AffiliationDescriptor affiliationOwnerID, 
 *                          or RoleDescriptor {@link #getRoleIDToken(String, RoleDescriptor)}
 *                          corresponding to the element whose signature is being evaluated.
 *                          This is used exclusively for logging/debugging purposes and
 *                          should not be used operationally (e.g. for building the criteria set).
 * @param isEntityGroup flag indicating whether the signed object is a metadata group (EntitiesDescriptor)
 * @return the newly constructed criteria set
 */
protected CriteriaSet buildCriteriaSet(SignableXMLObject signedMetadata,
        String metadataEntryName, boolean isEntityGroup) {
    
    CriteriaSet newCriteriaSet = new CriteriaSet();
    
    if (getDefaultCriteria() != null) {
        newCriteriaSet.addAll( getDefaultCriteria() );
    }
    
    if (!newCriteriaSet.contains(UsageCriteria.class)) {
        newCriteriaSet.add( new UsageCriteria(UsageType.SIGNING) );
    }
    
    // TODO how to handle adding dynamic entity ID and/or other criteria for trust engine consumption?
    //
    // Have 4 signed metadata types:
    // 1) EntitiesDescriptor
    // 2) EntityDescriptor
    // 3) RoleDescriptor
    // 4) AffiliationDescriptor
    //
    // Logic will likely vary for how to specify criteria to trust engine for different types + specific use cases,
    // e.g. for federation metadata publishers of EntitiesDescriptors vs. "self-signed" EntityDescriptors.
    // May need to delegate to more specialized subclasses.
    
    return newCriteriaSet;
}
 
Example #15
Source File: SAML2HTTPRedirectDeflateSignatureValidator.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
/**
 * Build a criteria set suitable for input to the trust engine.
 *
 * @param issuer
 * @return
 * @throws SecurityPolicyException
 */
private static CriteriaSet buildCriteriaSet(String issuer) {
    CriteriaSet criteriaSet = new CriteriaSet();
    if (!DatatypeHelper.isEmpty(issuer)) {
        criteriaSet.add(new EntityIDCriteria(issuer));
    }
    criteriaSet.add(new UsageCriteria(UsageType.SIGNING));
    return criteriaSet;
}
 
Example #16
Source File: KeyDescriptorSchemaValidator.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Checks that use attribute has only one of allowed values.
 * 
 * @param keyDescriptor the key descriptor to validate
 * @throws ValidationException throw in use attribute does not have a legal value
 */
protected void validateUse(KeyDescriptor keyDescriptor) throws ValidationException {
    UsageType use = keyDescriptor.getUse();
    if (use == null) {
        return;
    }
    if (       ! use.equals(UsageType.SIGNING) 
            && ! use.equals(UsageType.ENCRYPTION) 
            && ! use.equals(UsageType.UNSPECIFIED) ) {
        throw new ValidationException("Invalid value for use attribute: " + use.toString());
    }
}
 
Example #17
Source File: MetadataCredentialResolver.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/** {@inheritDoc} */
protected Iterable<Credential> resolveFromSource(CriteriaSet criteriaSet) throws SecurityException {

    checkCriteriaRequirements(criteriaSet);

    String entityID = criteriaSet.get(EntityIDCriteria.class).getEntityID();
    MetadataCriteria mdCriteria = criteriaSet.get(MetadataCriteria.class);
    QName role = mdCriteria.getRole();
    String protocol = mdCriteria.getProtocol();
    UsageCriteria usageCriteria = criteriaSet.get(UsageCriteria.class);
    UsageType usage = null;
    if (usageCriteria != null) {
        usage = usageCriteria.getUsage();
    } else {
        usage = UsageType.UNSPECIFIED;
    }
    
    // See Jira issue SIDP-229.
    log.debug("Forcing on-demand metadata provider refresh if necessary");
    try {
        metadata.getMetadata();
    } catch (MetadataProviderException e) {
        // don't care about errors at this level
    }

    MetadataCacheKey cacheKey = new MetadataCacheKey(entityID, role, protocol, usage);
    Collection<Credential> credentials = retrieveFromCache(cacheKey);

    if (credentials == null) {
        credentials = retrieveFromMetadata(entityID, role, protocol, usage);
        cacheCredentials(cacheKey, credentials);
    }

    return credentials;
}
 
Example #18
Source File: Decrypter.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Utility method to build a new set of credential criteria based on the KeyInfo of an EncryptedData or
 * EncryptedKey, and any additional static criteria which might have been supplied to the decrypter.
 * 
 * @param encryptedType an EncryptedData or EncryptedKey for which to resolve decryption credentials
 * @param staticCriteria static set of credential criteria to add to the new criteria set
 * @return the new credential criteria set
 */
private CriteriaSet buildCredentialCriteria(EncryptedType encryptedType, CriteriaSet staticCriteria) {

    CriteriaSet newCriteriaSet = new CriteriaSet();

    // This is the main criteria based on the encrypted type's KeyInfo
    newCriteriaSet.add(new KeyInfoCriteria(encryptedType.getKeyInfo()));

    // Also attemtpt to dynamically construct key criteria based on information
    // in the encrypted object
    Set<Criteria> keyCriteria = buildKeyCriteria(encryptedType);
    if (keyCriteria != null && !keyCriteria.isEmpty()) {
        newCriteriaSet.addAll(keyCriteria);
    }

    // Add any static criteria which may have been supplied to the decrypter
    if (staticCriteria != null && !staticCriteria.isEmpty()) {
        newCriteriaSet.addAll(staticCriteria);
    }

    // If don't have a usage criteria yet from static criteria, add encryption usage
    if (!newCriteriaSet.contains(UsageCriteria.class)) {
        newCriteriaSet.add(new UsageCriteria(UsageType.ENCRYPTION));
    }

    return newCriteriaSet;
}
 
Example #19
Source File: ClientCertAuthRule.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/** {@inheritDoc} */
protected CriteriaSet buildCriteriaSet(String entityID, MessageContext messageContext)
        throws SecurityPolicyException {

    CriteriaSet criteriaSet = new CriteriaSet();
    if (!DatatypeHelper.isEmpty(entityID)) {
        criteriaSet.add(new EntityIDCriteria(entityID));
    }

    criteriaSet.add(new UsageCriteria(UsageType.SIGNING));

    return criteriaSet;
}
 
Example #20
Source File: ExplicitKeySignatureTrustEngine.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/** {@inheritDoc} */
public boolean validate(Signature signature, CriteriaSet trustBasisCriteria) throws SecurityException {

    checkParams(signature, trustBasisCriteria);

    CriteriaSet criteriaSet = new CriteriaSet();
    criteriaSet.addAll(trustBasisCriteria);
    if (!criteriaSet.contains(UsageCriteria.class)) {
        criteriaSet.add(new UsageCriteria(UsageType.SIGNING));
    }
    String jcaAlgorithm = SecurityHelper.getKeyAlgorithmFromURI(signature.getSignatureAlgorithm());
    if (!DatatypeHelper.isEmpty(jcaAlgorithm)) {
        criteriaSet.add(new KeyAlgorithmCriteria(jcaAlgorithm), true);
    }

    Iterable<Credential> trustedCredentials = getCredentialResolver().resolve(criteriaSet);

    if (validate(signature, trustedCredentials)) {
        return true;
    }

    // If the credentials extracted from Signature's KeyInfo (if any) did not verify the
    // signature and/or establish trust, as a fall back attempt to verify the signature with
    // the trusted credentials directly.
    log.debug("Attempting to verify signature using trusted credentials");

    for (Credential trustedCredential : trustedCredentials) {
        if (verifySignature(signature, trustedCredential)) {
            log.debug("Successfully verified signature using resolved trusted credential");
            return true;
        }
    }
    log.debug("Failed to verify signature using either KeyInfo-derived or directly trusted credentials");
    return false;
}
 
Example #21
Source File: EvaluableUsageCredentialCriteria.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/** {@inheritDoc} */
public Boolean evaluate(Credential target) {
    if (target == null) {
        log.error("Credential target was null");
        return null;
    }
    UsageType credUsage = target.getUsageType();
    if (credUsage == null) {
        log.info("Could not evaluate criteria, credential contained no usage specifier");
        return null;
    }

    Boolean result = matchUsage(credUsage, usage);
    return result;
}
 
Example #22
Source File: EvaluableUsageCredentialCriteria.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Constructor.
 * 
 * @param newUsage the criteria value which is the basis for evaluation
 */
public EvaluableUsageCredentialCriteria(UsageType newUsage) {
    if (newUsage == null) {
        throw new IllegalArgumentException("Usage may not be null");
    }
    usage = newUsage;
}
 
Example #23
Source File: UsageCriteria.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Set the key usage criteria.
 * 
 * @param usage The usage to set.
 */
public void setUsage(UsageType usage) {
    if (usage != null) {
        credUsage = usage;
    } else {
        credUsage = UsageType.UNSPECIFIED;
    }
}
 
Example #24
Source File: X509CredentialImpl.java    From carbon-identity with Apache License 2.0 4 votes vote down vote up
@Override
public UsageType getUsageType() {
    // TODO Auto-generated method stub
    return null;
}
 
Example #25
Source File: X509CredentialImpl.java    From carbon-identity with Apache License 2.0 4 votes vote down vote up
@Override
public UsageType getUsageType() {
    // TODO Auto-generated method stub
    return null;
}
 
Example #26
Source File: X509CredentialImpl.java    From carbon-commons with Apache License 2.0 4 votes vote down vote up
public UsageType getUsageType() {
       // TODO Auto-generated method stub
	return null;
}
 
Example #27
Source File: X509CredentialImpl.java    From micro-integrator with Apache License 2.0 4 votes vote down vote up
@Override
public UsageType getUsageType() {
    return null;
}
 
Example #28
Source File: X509CredentialImpl.java    From carbon-identity with Apache License 2.0 4 votes vote down vote up
@Override
public UsageType getUsageType() {
    return null;
}
 
Example #29
Source File: X509CredentialImpl.java    From carbon-identity with Apache License 2.0 4 votes vote down vote up
@Override
public UsageType getUsageType() {
    // TODO Auto-generated method stub
    return null;
}
 
Example #30
Source File: X509CredentialImpl.java    From carbon-identity with Apache License 2.0 4 votes vote down vote up
@Override
public UsageType getUsageType() {
    return null;
}