Java Code Examples for org.opensaml.xml.security.CriteriaSet#add()

The following examples show how to use org.opensaml.xml.security.CriteriaSet#add() . 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: 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 2
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 3
Source File: SAMLMDClientCertAuthRule.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 = super.buildCriteriaSet(entityID, messageContext);
    MetadataCriteria mdCriteria = 
        new MetadataCriteria(samlContext.getPeerEntityRole(), samlContext.getInboundSAMLProtocol());
    criteriaSet.add(mdCriteria);

    return criteriaSet;
}
 
Example 4
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 5
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 6
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 7
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 8
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 9
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 10
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 11
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 12
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 13
Source File: KeyInfoReferenceProvider.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
/** {@inheritDoc} */
public Collection<Credential> process(KeyInfoCredentialResolver resolver, XMLObject keyInfoChild,
        CriteriaSet criteriaSet, KeyInfoResolutionContext kiContext) throws SecurityException {

    KeyInfoReference ref = getKeyInfoReference(keyInfoChild);
    if (ref == null) {
        return null;
    }

    log.debug("Attempting to follow same-document KeyInfoReference");

    XMLObject target = ref.resolveIDFromRoot(ref.getURI().substring(1));
    if (target == null) {
        log.warn("KeyInfoReference URI could not be dereferenced");
        return null;
    } else if (!(target instanceof KeyInfo)) {
        log.warn("The product of dereferencing the KeyInfoReference was not a KeyInfo");
        return null;
    } else if (!((KeyInfo) target).getXMLObjects(KeyInfoReference.DEFAULT_ELEMENT_NAME).isEmpty()) {
        log.warn("The dereferenced KeyInfo contained a KeyInfoReference, cannot process");
        return null;
    }
    
    log.debug("Recursively processing KeyInfoReference referent");
    
    // Copy the existing CriteriaSet, excluding the KeyInfoCriteria, which is reset to the target.
    CriteriaSet newCriteria = new CriteriaSet();
    newCriteria.add(new KeyInfoCriteria((KeyInfo) target));
    for (Criteria crit : criteriaSet) {
        if (!(crit instanceof KeyInfoCriteria)) {
            newCriteria.add(crit);
        }
    }
    
    // Resolve the new target and copy the results into a collection to return.
    Iterable<Credential> creds = resolver.resolve(newCriteria);
    if (creds != null) {
        Collection<Credential> result = new ArrayList<Credential>();
        for (Credential c : creds) {
            result.add(c);
        }
        return result;
    }
    
    return null;
}
 
Example 14
Source File: MetadataCredentialResolver.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Retrieves credentials from the provided metadata.
 * 
 * @param entityID entityID of the credential owner
 * @param role role in which the entity is operating
 * @param protocol protocol over which the entity is operating (may be null)
 * @param usage intended usage of resolved credentials
 * 
 * @return the resolved credentials or null
 * 
 * @throws SecurityException thrown if the key, certificate, or CRL information is represented in an unsupported
 *             format
 */
protected Collection<Credential> retrieveFromMetadata(String entityID, QName role, String protocol, UsageType usage)
        throws SecurityException {

    log.debug("Attempting to retrieve credentials from metadata for entity: {}", entityID);
    Collection<Credential> credentials = new HashSet<Credential>(3);

    List<RoleDescriptor> roleDescriptors = getRoleDescriptors(entityID, role, protocol);
    if(roleDescriptors == null || roleDescriptors.isEmpty()){
        return credentials;
    }
        
    for (RoleDescriptor roleDescriptor : roleDescriptors) {
        List<KeyDescriptor> keyDescriptors = roleDescriptor.getKeyDescriptors();
        if(keyDescriptors == null || keyDescriptors.isEmpty()){
            return credentials;
        }            
        for (KeyDescriptor keyDescriptor : keyDescriptors) {
            UsageType mdUsage = keyDescriptor.getUse();
            if (mdUsage == null) {
                mdUsage = UsageType.UNSPECIFIED;
            }
            if (matchUsage(mdUsage, usage)) {
                if (keyDescriptor.getKeyInfo() != null) {
                    CriteriaSet critSet = new CriteriaSet();
                    critSet.add(new KeyInfoCriteria(keyDescriptor.getKeyInfo()));

                    Iterable<Credential> creds = getKeyInfoCredentialResolver().resolve(critSet);
                    if(credentials == null){
                        continue;
                    }
                    for (Credential cred : creds) {
                        if (cred instanceof BasicCredential) {
                            BasicCredential basicCred = (BasicCredential) cred;
                            basicCred.setEntityId(entityID);
                            basicCred.setUsageType(mdUsage);
                            basicCred.getCredentalContextSet().add(new SAMLMDCredentialContext(keyDescriptor));
                        }
                        credentials.add(cred);
                    }
                }
            }
        }

    }

    return credentials;
}
 
Example 15
Source File: ConsumerEndpoint.java    From MaxKey with Apache License 2.0 4 votes vote down vote up
/**
 * 初始化sp证书
 * 
 * @throws Exception
 */
private void initCredential(String spId) throws Exception {
	// 1. 获取 sp keyStore
	AppsSAML20Details saml20Details = saml20DetailsService.get(spId);
	if (saml20Details == null) {
		// TODO
		logger.error("spid[" + spId + "] not exists");
		throw new Exception();
	}
	byte[] keyStoreBytes = saml20Details.getKeyStore();
	InputStream keyStoreStream = new ByteArrayInputStream(keyStoreBytes);

	try {
		KeyStore keyStore = KeyStore.getInstance(keyStoreLoader.getKeystoreType());
		keyStore.load(keyStoreStream, keyStoreLoader.getKeystorePassword().toCharArray());

		Map<String, String> passwords = new HashMap<String, String>();
		for (Enumeration<String> en = keyStore.aliases(); en.hasMoreElements();) {
			String aliase = en.nextElement();
			if (aliase.equalsIgnoreCase(keyStoreLoader.getEntityName())) {
				passwords.put(aliase, keyStoreLoader.getKeystorePassword());
			}
		}
		// TrustResolver trustResolver = new
		// TrustResolver(keyStore,keyStoreLoader.getIdpIssuingEntityName(),keyStoreLoader.getKeystorePassword());

		AuthnResponseGenerator authnResponseGenerator = new AuthnResponseGenerator(
				keyStoreLoader.getEntityName(), timeService,
				idService);
		// endpointGenerator = new EndpointGenerator();

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

		KeyStoreCredentialResolver credentialResolver = new KeyStoreCredentialResolver(
				keyStore, passwords);
		signingCredential = credentialResolver.resolveSingle(criteriaSet);
		Validate.notNull(signingCredential);

		// adapter set resolver
		TrustResolver trustResolver = new TrustResolver(keyStore,
				keyStoreLoader.getEntityName(),
				keyStoreLoader.getKeystorePassword(), issueInstantRule,
				messageReplayRule,"POST");
		extractBindingAdapter.setSecurityPolicyResolver(trustResolver
				.getStaticSecurityPolicyResolver());
	} catch (Exception e) {
		logger.error("初始化sp证书出错");
		throw new Exception(e);
	}
}