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

The following examples show how to use org.opensaml.xml.security.credential.Credential. 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: SecurityHelper.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Obtains a {@link KeyInfoGenerator} for the specified {@link Credential}.
 * 
 * <p>
 * The KeyInfoGenerator returned is based on the {@link NamedKeyInfoGeneratorManager} defined by the specified
 * security configuration via {@link SecurityConfiguration#getKeyInfoGeneratorManager()}, and is determined by the
 * type of the signing credential and an optional KeyInfo generator manager name. If the latter is ommited, the
 * default manager ({@link NamedKeyInfoGeneratorManager#getDefaultManager()}) of the security configuration's
 * named generator manager will be used.
 * </p>
 * 
 * <p>
 * The generator is determined by the specified {@link SecurityConfiguration}. If a security configuration is not
 * supplied, the global security configuration ({@link Configuration#getGlobalSecurityConfiguration()}) will be
 * used.
 * </p>
 * 
 * @param credential the credential for which a generator is desired
 * @param config the SecurityConfiguration to use (may be null)
 * @param keyInfoGenName the named KeyInfoGeneratorManager configuration to use (may be null)
 * @return a KeyInfoGenerator appropriate for the specified credential
 */
public static KeyInfoGenerator getKeyInfoGenerator(Credential credential, SecurityConfiguration config,
        String keyInfoGenName) {

    SecurityConfiguration secConfig;
    if (config != null) {
        secConfig = config;
    } else {
        secConfig = Configuration.getGlobalSecurityConfiguration();
    }

    NamedKeyInfoGeneratorManager kiMgr = secConfig.getKeyInfoGeneratorManager();
    if (kiMgr != null) {
        KeyInfoGeneratorFactory kiFactory = null;
        if (DatatypeHelper.isEmpty(keyInfoGenName)) {
            kiFactory = kiMgr.getDefaultManager().getFactory(credential);
        } else {
            kiFactory = kiMgr.getFactory(keyInfoGenName, credential);
        }
        if (kiFactory != null) {
            return kiFactory.newInstance();
        }
    }
    return null;
}
 
Example #2
Source File: CertManager.java    From saml-generator with Apache License 2.0 6 votes vote down vote up
/**
 * gets credential used to sign saml assertionts that are produced. This method
 * assumes the cert and pkcs formatted primary key are on file system. this data
 * could be stored elsewhere e.g keystore
 * 
 * a credential is used to sign saml response, and includes the private key
 * as well as a cert for the public key
 * 
 * @return
 * @throws Throwable
 */
public Credential getSigningCredential(String publicKeyLocation, String privateKeyLocation) throws Throwable {
	// create public key (cert) portion of credential
	InputStream inStream = new FileInputStream(publicKeyLocation);
	CertificateFactory cf = CertificateFactory.getInstance("X.509");
	X509Certificate publicKey = (X509Certificate)cf.generateCertificate(inStream);
	inStream.close();
	    
	// create private key
	RandomAccessFile raf = new RandomAccessFile(privateKeyLocation, "r");
	byte[] buf = new byte[(int)raf.length()];
	raf.readFully(buf);
	raf.close();
	
	PKCS8EncodedKeySpec kspec = new PKCS8EncodedKeySpec(buf);
	KeyFactory kf = KeyFactory.getInstance("RSA");
	PrivateKey privateKey = kf.generatePrivate(kspec);
	
	// create credential and initialize
	BasicX509Credential credential = new BasicX509Credential();
	credential.setEntityCertificate(publicKey);
	credential.setPrivateKey(privateKey);
	
	return credential;
}
 
Example #3
Source File: EvaluableKeyLengthCredentialCriteria.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/** {@inheritDoc} */
public Boolean evaluate(Credential target) {
    if (target == null) {
        log.error("Credential target was null");
        return null;
    }
    Key key = getKey(target);
    if (key == null) {
        log.info("Could not evaluate criteria, credential contained no key");
        return null;
    }
    Integer length = SecurityHelper.getKeyLength(key);
    if (length == null) {
        log.info("Could not evaluate criteria, can not determine length of key");
        return null;
    }

    Boolean result = keyLength.equals(length);
    return result;
}
 
Example #4
Source File: EvaluableX509IssuerSerialCredentialCriteria.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/** {@inheritDoc} */
public Boolean evaluate(Credential target) {
    if (target == null) {
        log.error("Credential target was null");
        return null;
    }
    if (!(target instanceof X509Credential)) {
        log.info("Credential is not an X509Credential, does not satisfy issuer name and serial number criteria");
        return Boolean.FALSE;
    }
    X509Credential x509Cred = (X509Credential) target;

    X509Certificate entityCert = x509Cred.getEntityCertificate();
    if (entityCert == null) {
        log.info("X509Credential did not contain an entity certificate, does not satisfy criteria");
        return Boolean.FALSE;
    }

    if (!entityCert.getIssuerX500Principal().equals(issuer)) {
        return false;
    }
    Boolean result = entityCert.getSerialNumber().equals(serialNumber);
    return result;
}
 
Example #5
Source File: SAML2HTTPRedirectDeflateSignatureValidator.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
/**
 * @param queryString
 * @param issuer
 * @param alias
 * @param domainName
 * @return
 * @throws SecurityException
 * @throws IdentitySAML2SSOException
 */
@Override
public boolean validateSignature(String queryString, String issuer, String alias,
                                 String domainName) throws SecurityException,
        IdentitySAML2SSOException {
    byte[] signature = getSignature(queryString);
    byte[] signedContent = getSignedContent(queryString);
    String algorithmUri = getSigAlg(queryString);
    CriteriaSet criteriaSet = buildCriteriaSet(issuer);

    // creating the SAML2HTTPRedirectDeflateSignatureRule
    X509CredentialImpl credential =
            SAMLSSOUtil.getX509CredentialImplForTenant(domainName,
                    alias);

    List<Credential> credentials = new ArrayList<Credential>();
    credentials.add(credential);
    CollectionCredentialResolver credResolver = new CollectionCredentialResolver(credentials);
    KeyInfoCredentialResolver kiResolver = SecurityHelper.buildBasicInlineKeyInfoResolver();
    SignatureTrustEngine engine = new ExplicitKeySignatureTrustEngine(credResolver, kiResolver);
    return engine.validate(signature, signedContent, algorithmUri, criteriaSet, null);
}
 
Example #6
Source File: BasicProviderKeyInfoCredentialResolver.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Resolve the key from any KeyValue or DEREncodedKeyValue element that may be present, and store the resulting
 * key in the resolution context.
 * 
 * Each element is processed in turn in document order. Each element will be processed by each provider in
 * the ordered list of registered providers. The key from the first credential successfully resolved
 * will be stored in the resolution context.
 * 
 * Note: This resolver implementation assumes that KeyInfo will not be abused via-a-vis the Signature
 * specificiation, and that therefore all elements (if there are even more than one) will all resolve to the
 * same key value. The KeyInfo might, for example have multiple KeyValue children, containing different
 * representations of the same key. Therefore, only the first credential derived will be be utilized.
 * 
 * @param kiContext KeyInfo resolution context
 * @param criteriaSet the credential criteria used to resolve credentials
 * @param keyValues the KeyValue or DEREncodedKeyValue children to evaluate
 * @throws SecurityException thrown if there is an error resolving the key from the KeyValue
 */
protected void resolveKeyValue(KeyInfoResolutionContext kiContext, CriteriaSet criteriaSet,
        List<? extends XMLObject> keyValues) throws SecurityException {

    for (XMLObject keyValue : keyValues) {
        if (!(keyValue instanceof KeyValue) && !(keyValue instanceof DEREncodedKeyValue)) {
            continue;
        }
        Collection<Credential> creds = processKeyInfoChild(kiContext, criteriaSet, keyValue);
        if (creds != null) {
            for (Credential cred : creds) {
                Key key = extractKeyValue(cred);
                if (key != null) {
                    kiContext.setKey(key);
                    log.debug("Found a credential based on a KeyValue/DEREncodedKeyValue having key type: {}",
                            key.getAlgorithm());
                    return;
                }
            }
        }
    }
}
 
Example #7
Source File: HTTPPostSimpleSignEncoder.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Gets the signature algorithm URI to use with the given signing credential.
 * 
 * @param credential the credential that will be used to sign the message
 * @param config the SecurityConfiguration to use (may be null)
 * 
 * @return signature algorithm to use with the given signing credential
 * 
 * @throws MessageEncodingException thrown if the algorithm URI could not be derived from the supplied credential
 */
protected String getSignatureAlgorithmURI(Credential credential, SecurityConfiguration config)
        throws MessageEncodingException {

    SecurityConfiguration secConfig;
    if (config != null) {
        secConfig = config;
    } else {
        secConfig = Configuration.getGlobalSecurityConfiguration();
    }

    String signAlgo = secConfig.getSignatureAlgorithmURI(credential);

    if (signAlgo == null) {
        throw new MessageEncodingException("The signing credential's algorithm URI could not be derived");
    }

    return signAlgo;
}
 
Example #8
Source File: AbstractKeyInfoProvider.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Utility method to extract any key that might be present in the specified Credential.
 * 
 * @param cred the Credential to evaluate
 * @return the Key contained in the credential, or null if it does not contain a key.
 */
protected Key extractKeyValue(Credential cred) {
    if (cred == null) {
        return null;
    }
    if (cred.getPublicKey() != null) {
        return cred.getPublicKey();
    } 
    // This could happen if key is derived, e.g. key agreement, etc
    if (cred.getSecretKey() != null) {
        return cred.getSecretKey();
    }
    // Perhaps unlikely, but go ahead and check
    if (cred.getPrivateKey() != null) {
        return cred.getPrivateKey(); 
    }
    return null;
}
 
Example #9
Source File: ExplicitX509CertificateTrustEvaluator.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Evaluate trust.
 * 
 * @param untrustedCredential the untrusted X509Credential to evaluate
 * @param trustedCredentials basis for trust
 * @return true if trust can be established, false otherwise
 */
public boolean validate(X509Credential untrustedCredential, Iterable<Credential> trustedCredentials) {

    for (Credential trustedCredential : trustedCredentials) {
        if (!(trustedCredential instanceof X509Credential)) {
            log.debug("Skipping evaluation against trusted, non-X509Credential");
            continue;
        }
        X509Credential trustedX509Credential = (X509Credential) trustedCredential;
        if (validate(untrustedCredential, trustedX509Credential)) {
            return true;
        }
    }

    return false;
}
 
Example #10
Source File: MetadataController.java    From spring-security-saml-java-sp with Apache License 2.0 6 votes vote down vote up
protected Map<String, String> getAvailablePrivateKeys() throws KeyStoreException {
    Map<String, String> availableKeys = new HashMap<String, String>();
    Set<String> aliases = keyManager.getAvailableCredentials();
    for (String key : aliases) {
        try {
            log.debug("Found key {}", key);
            Credential credential = keyManager.getCredential(key);
            if (credential.getPrivateKey() != null) {
                log.debug("Adding private key with alias {} and entityID {}", key, credential.getEntityId());
                availableKeys.put(key, key + " (" + credential.getEntityId() + ")");
            }
        } catch (Exception e) {
            log.debug("Error loading key", e);
        }
    }
    return availableKeys;
}
 
Example #11
Source File: MetadataCredentialResolver.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Retrieves pre-resolved credentials from the cache.
 * 
 * @param cacheKey the key to the metadata cache
 * 
 * @return the collection of cached credentials or null
 */
protected Collection<Credential> retrieveFromCache(MetadataCacheKey cacheKey) {
    log.debug("Attempting to retrieve credentials from cache using index: {}", cacheKey);
    Lock readLock = getReadWriteLock().readLock();
    readLock.lock();
    log.trace("Read lock over cache acquired");
    try {
        if (cache.containsKey(cacheKey)) {
            SoftReference<Collection<Credential>> reference = cache.get(cacheKey);
            if (reference.get() != null) {
                log.debug("Retrieved credentials from cache using index: {}", cacheKey);
                return reference.get();
            }
        }
    } finally {
        readLock.unlock();
        log.trace("Read lock over cache released");
    }

    log.debug("Unable to retrieve credentials from cache using index: {}", cacheKey);
    return null;
}
 
Example #12
Source File: SigningUtil.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Verify the signature value computed over the supplied input against the supplied signature value.
 * 
 * It is up to the caller to ensure that the specified algorithm ID and isMAC flag are consistent with the type of
 * verification credential supplied.
 * 
 * @param verificationCredential the credential containing the verification key
 * @param jcaAlgorithmID the Java JCA algorithm ID to use
 * @param isMAC flag indicating whether the operation to be performed is a signature or MAC computation
 * @param signature the computed signature value received from the signer
 * @param input the input over which the signature is computed and verified
 * @return true if the signature value computed over the input using the supplied key and algorithm ID is identical
 *         to the supplied signature value
 * @throws SecurityException thrown if the signature computation or verification process results in an error
 */
public static boolean verify(Credential verificationCredential, String jcaAlgorithmID, boolean isMAC,
        byte[] signature, byte[] input) throws SecurityException {
    Logger log = getLogger();

    Key verificationKey = SecurityHelper.extractVerificationKey(verificationCredential);
    if (verificationKey == null) {
        log.error("No verification key supplied in verification credential for signature verification");
        throw new SecurityException("No verification key supplied in verification credential");
    }

    if (isMAC) {
        return verifyMAC(verificationKey, jcaAlgorithmID, signature, input);
    } else if (verificationKey instanceof PublicKey) {
        return verify((PublicKey) verificationKey, jcaAlgorithmID, signature, input);
    } else {
        log.error("No PublicKey present in verification credential for signature verification");
        throw new SecurityException("No PublicKey supplied for signature verification");
    }
}
 
Example #13
Source File: WebServicePostEncoder.java    From MaxKey with Apache License 2.0 6 votes vote down vote up
protected String getSignatureAlgorithmURI(Credential credential,
		SecurityConfiguration config) throws MessageEncodingException {

	SecurityConfiguration secConfig;
	if (config != null) {
		secConfig = config;
	} else {
		secConfig = Configuration.getGlobalSecurityConfiguration();
	}

	String signAlgo = secConfig.getSignatureAlgorithmURI(credential);

	if (signAlgo == null) {
		throw new MessageEncodingException(
				"The signing credential's algorithm URI could not be derived");
	}

	return signAlgo;
}
 
Example #14
Source File: ExplicitKeyTrustEngine.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Check the parameters for required values.
 * 
 * @param untrustedCredential the credential to be evaluated
 * @param trustBasisCriteria the set of trusted credential criteria
 * @throws SecurityException thrown if required values are absent or otherwise invalid
 */
protected void checkParams(Credential untrustedCredential, CriteriaSet trustBasisCriteria)
    throws SecurityException {

    if (untrustedCredential == null) {
        throw new SecurityException("Untrusted credential was null");
    }
    if (trustBasisCriteria == null) {
        throw new SecurityException("Trust basis criteria set was null");
    }
    if (trustBasisCriteria.isEmpty()) {
        throw new SecurityException("Trust basis criteria set was empty");
    }
}
 
Example #15
Source File: SigningUtil.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Compute the signature or MAC value over the supplied input.
 * 
 * It is up to the caller to ensure that the specified algorithm URI is consistent with the type of signing key
 * supplied in the signing credential.
 * 
 * @param signingCredential the credential containing the signing key
 * @param algorithmURI the algorithm URI to use
 * @param input the input over which to compute the signature
 * @return the computed signature or MAC value
 * @throws SecurityException throw if the computation process results in an error
 */
public static byte[] signWithURI(Credential signingCredential, String algorithmURI, byte[] input)
        throws SecurityException {

    String jcaAlgorithmID = SecurityHelper.getAlgorithmIDFromURI(algorithmURI);
    if (jcaAlgorithmID == null) {
        throw new SecurityException("Could not derive JCA algorithm identifier from algorithm URI");
    }

    boolean isHMAC = SecurityHelper.isHMAC(algorithmURI);

    return sign(signingCredential, jcaAlgorithmID, isHMAC, input);
}
 
Example #16
Source File: DefaultSSOEncrypter.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
@Override
public EncryptedAssertion doEncryptedAssertion(Assertion assertion, X509Credential cred, String alias, String encryptionAlgorithm) throws IdentityException {
    try {

        Credential symmetricCredential = SecurityHelper.getSimpleCredential(
                SecurityHelper.generateSymmetricKey(EncryptionConstants.ALGO_ID_BLOCKCIPHER_AES256));

        EncryptionParameters encParams = new EncryptionParameters();
        encParams.setAlgorithm(EncryptionConstants.ALGO_ID_BLOCKCIPHER_AES256);
        encParams.setEncryptionCredential(symmetricCredential);

        KeyEncryptionParameters keyEncryptionParameters = new KeyEncryptionParameters();
        keyEncryptionParameters.setAlgorithm(EncryptionConstants.ALGO_ID_KEYTRANSPORT_RSA15);
        keyEncryptionParameters.setEncryptionCredential(cred);

        Encrypter encrypter = new Encrypter(encParams, keyEncryptionParameters);
        encrypter.setKeyPlacement(Encrypter.KeyPlacement.INLINE);

        EncryptedAssertion encrypted = encrypter.encrypt(assertion);
        return encrypted;
    } catch (Exception e) {
        throw IdentityException.error("Error while Encrypting Assertion", e);
    }
}
 
Example #17
Source File: EvaluableKeyAlgorithmCredentialCriteria.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Get the key contained within the credential.
 * 
 * @param credential the credential containing a key
 * @return the key from the credential
 */
private Key getKey(Credential credential) {
    if (credential.getPublicKey() != null) {
        return credential.getPublicKey();
    } else if (credential.getSecretKey() != null) {
        return credential.getSecretKey();
    } else if (credential.getPrivateKey() != null) {
        // There should have been a corresponding public key, but just in case...
        return credential.getPrivateKey();
    } else {
        return null;
    }

}
 
Example #18
Source File: MetadataCredentialResolver.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Adds resolved credentials to the cache.
 * 
 * @param cacheKey the key for caching the credentials
 * @param credentials collection of credentials to cache
 */
protected void cacheCredentials(MetadataCacheKey cacheKey, Collection<Credential> credentials) {
    Lock writeLock = getReadWriteLock().writeLock();
    writeLock.lock();
    log.trace("Write lock over cache acquired");
    try {
        cache.put(cacheKey, new SoftReference<Collection<Credential>>(credentials));
        log.debug("Added new credential collection to cache with key: {}", cacheKey);
    } finally {
        writeLock.unlock();
        log.trace("Write lock over cache released"); 
    }
}
 
Example #19
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 #20
Source File: SecurityHelper.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Extract the decryption key from the credential.
 * 
 * @param credential the credential containing the decryption key
 * @return the decryption key (either a private key or a secret (symmetric) key
 */
public static Key extractDecryptionKey(Credential credential) {
    if (credential == null) {
        return null;
    }
    if (credential.getPrivateKey() != null) {
        return credential.getPrivateKey();
    } else {
        return credential.getSecretKey();
    }
}
 
Example #21
Source File: ExplicitKeyTrustEvaluator.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Evaluate trust.
 * 
 * @param untrustedCredential the untrusted credential to evaluate
 * @param trustedCredential basis for trust
 * @return true if trust can be established, false otherwise
 */
public boolean validate(Credential untrustedCredential, Credential trustedCredential) {

    Key untrustedKey = null;
    Key trustedKey = null;
    if (untrustedCredential.getPublicKey() != null) {
        untrustedKey = untrustedCredential.getPublicKey();
        trustedKey = trustedCredential.getPublicKey();
    } else {
        untrustedKey = untrustedCredential.getSecretKey();
        trustedKey = trustedCredential.getSecretKey();
    }
    if (untrustedKey == null) {
        log.debug("Untrusted credential contained no key, unable to evaluate");
        return false;
    } else if (trustedKey == null) {
        log.debug("Trusted credential contained no key of the appropriate type, unable to evaluate");
        return false;
    }

    if (validate(untrustedKey, trustedKey)) {
        log.debug("Successfully validated untrusted credential against trusted key");
        return true;
    }

    log.debug("Failed to validate untrusted credential against trusted key");
    return false;
}
 
Example #22
Source File: LocalKeyInfoCredentialResolver.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Resolve credentials from local resolver using key name criteria.
 * 
 * @param keyName the key name criteria
 * @return collection of local credentials identified by the specified key name
 * @throws SecurityException  thrown if there is a problem resolving credentials from the 
 *          local credential resolver
 */
protected Collection<? extends Credential> resolveByKeyName(String keyName) throws SecurityException {
    ArrayList<Credential> localCreds = new ArrayList<Credential>();
    
    CriteriaSet criteriaSet = new CriteriaSet( new KeyNameCriteria(keyName) );
    for (Credential cred : getLocalCredentialResolver().resolve(criteriaSet)) {
        if (isLocalCredential(cred)) {
            localCreds.add(cred);
        }
    }
    
    return localCreds;
}
 
Example #23
Source File: BaseSignatureTrustEngine.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Attempt to verify a signature using the key from the supplied credential.
 * 
 * @param signature the signature on which to attempt verification
 * @param credential the credential containing the candidate validation key
 * @return true if the signature can be verified using the key from the credential, otherwise false
 */
protected boolean verifySignature(Signature signature, Credential credential) {
    SignatureValidator validator = new SignatureValidator(credential);
    try {
        validator.validate(signature);
    } catch (ValidationException e) {
        log.debug("Signature validation using candidate validation credential failed", e);
        return false;
    }
    
    log.debug("Signature validation using candidate credential was successful");
    return true;
}
 
Example #24
Source File: NamedKeyInfoGeneratorManager.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Lookup and return the named generator factory for the type of the credential specified.
 * 
 * @param name the name of the factory manger
 * @param credential the credential to evaluate
 * @return a factory for generators appropriate for the specified credential
 */
public KeyInfoGeneratorFactory getFactory(String name, Credential credential) {
    KeyInfoGeneratorManager manager = managers.get(name);
    if (manager == null) {
        throw new IllegalArgumentException("Manager with name '" + name + "' does not exist");
    }
        
    KeyInfoGeneratorFactory factory = manager.getFactory(credential);
    if (factory == null) {
        if (useDefaultManager) {
            factory = defaultManager.getFactory(credential);
        }
    }
    return factory;
}
 
Example #25
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 #26
Source File: BasicSecurityConfiguration.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/** {@inheritDoc} */
public String getKeyTransportEncryptionAlgorithmURI(Credential credential, String wrappedKeyAlgorithm) {
    Key key = SecurityHelper.extractEncryptionKey(credential);
    if (key == null) {
        log.debug("Could not extract key transport encryption key from credential, unable to map to algorithm URI");
        return null;
    } else if (key.getAlgorithm() == null){
        log.debug("Key transport encryption key algorithm value was not available, unable to map to algorithm URI");
        return null;
    }
    Integer length = SecurityHelper.getKeyLength(key);
    return getKeyTransportEncryptionAlgorithmURI(key.getAlgorithm(), length, wrappedKeyAlgorithm);
}
 
Example #27
Source File: BasicProviderKeyInfoCredentialResolver.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Construct a basic credential containing the specified key and set of key names.
 * 
 * @param key the key to include in the credential
 * @param keyNames the key names to include in the credential
 * @return a basic credential with the specified key and key names
 * @throws SecurityException if there is an error building the credential
 */
protected Credential buildBasicCredential(Key key, Set<String> keyNames) throws SecurityException {
    if (key == null) {
        log.debug("Key supplied was null, could not build credential");
        return null;
    }

    BasicCredential basicCred = new BasicCredential();

    basicCred.getKeyNames().addAll(keyNames);

    if (key instanceof PublicKey) {
        basicCred.setPublicKey((PublicKey) key);
    } else if (key instanceof SecretKey) {
        basicCred.setSecretKey((SecretKey) key);
    } else if (key instanceof PrivateKey) {
        // This would be unusual for most KeyInfo use cases,
        // but go ahead and try and handle it
        PrivateKey privateKey = (PrivateKey) key;
        try {
            PublicKey publicKey = SecurityHelper.derivePublicKey(privateKey);
            if (publicKey != null) {
                basicCred.setPublicKey(publicKey);
                basicCred.setPrivateKey(privateKey);
            } else {
                log.error("Failed to derive public key from private key");
                return null;
            }
        } catch (KeyException e) {
            log.error("Could not derive public key from private key", e);
            return null;
        }
    } else {
        log.error(String.format("Key was of an unsupported type '%s'", key.getClass().getName()));
        return null;
    }

    return basicCred;
}
 
Example #28
Source File: BasicProviderKeyInfoCredentialResolver.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 {
    KeyInfoCriteria kiCriteria = criteriaSet.get(KeyInfoCriteria.class);
    if (kiCriteria == null) {
        log.error("No KeyInfo criteria supplied, resolver could not process");
        throw new SecurityException("Credential criteria set did not contain an instance of"
                + "KeyInfoCredentialCriteria");
    }
    KeyInfo keyInfo = kiCriteria.getKeyInfo();

    // This will be the list of credentials to return.
    List<Credential> credentials = new ArrayList<Credential>();

    KeyInfoResolutionContext kiContext = new KeyInfoResolutionContext(credentials);

    // Note: we allow KeyInfo to be null to handle case where application context,
    // other accompanying criteria, etc, should be used to resolve credentials via hooks below.
    if (keyInfo != null) {
        processKeyInfo(keyInfo, kiContext, criteriaSet, credentials);
    } else {
        log.info("KeyInfo was null, any credentials will be resolved by post-processing hooks only");
    }

    // Postprocessing hook
    postProcess(kiContext, criteriaSet, credentials);

    // Final empty credential hook
    if (credentials.isEmpty()) {
        log.debug("No credentials were found, calling empty credentials post-processing hook");
        postProcessEmptyCredentials(kiContext, criteriaSet, credentials);
    }

    log.debug("A total of {} credentials were resolved", credentials.size());
    return credentials;
}
 
Example #29
Source File: BasicProviderKeyInfoCredentialResolver.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * The main processing logic implemented by this resolver.
 * 
 * @param keyInfo the KeyInfo being processed
 * @param kiContext KeyInfo resolution context
 * @param criteriaSet the credential criteria used to resolve credentials
 * @param credentials the list which will store the resolved credentials
 * @throws SecurityException thrown if there is an error during processing
 */
private void processKeyInfo(KeyInfo keyInfo, KeyInfoResolutionContext kiContext, CriteriaSet criteriaSet,
        List<Credential> credentials) throws SecurityException {

    // Initialize the resolution context that will be used by the provider plugins.
    // This processes the KeyName and the KeyValue children, if either are present.
    initResolutionContext(kiContext, keyInfo, criteriaSet);

    // Store these off so we later use the original values,
    // unmodified by other providers which later run.
    Key keyValueKey = kiContext.getKey();
    HashSet<String> keyNames = new HashSet<String>();
    keyNames.addAll(kiContext.getKeyNames());

    // Now process all (non-KeyValue) children
    processKeyInfoChildren(kiContext, criteriaSet, credentials);

    if (credentials.isEmpty() && keyValueKey != null) {
        // Add the credential based on plain KeyValue if no more specifc cred type was found
        Credential keyValueCredential = buildBasicCredential(keyValueKey, keyNames);
        if (keyValueCredential != null) {
            log.debug("No credentials were extracted by registered non-KeyValue handling providers, "
                    + "adding KeyValue credential to returned credential set");
            credentials.add(keyValueCredential);
        }
    }
}
 
Example #30
Source File: HTTPRedirectDeflateEncoder.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Builds the URL to redirect the client to.
 * 
 * @param messagesContext current message context
 * @param endpointURL endpoint URL to send encoded message to
 * @param message Deflated and Base64 encoded message
 * 
 * @return URL to redirect client to
 * 
 * @throws MessageEncodingException thrown if the SAML message is neither a RequestAbstractType or Response
 */
protected String buildRedirectURL(SAMLMessageContext messagesContext, String endpointURL, String message)
        throws MessageEncodingException {
    log.debug("Building URL to redirect client to");
    URLBuilder urlBuilder = new URLBuilder(endpointURL);

    List<Pair<String, String>> queryParams = urlBuilder.getQueryParams();
    queryParams.clear();

    if (messagesContext.getOutboundSAMLMessage() instanceof RequestAbstractType) {
        queryParams.add(new Pair<String, String>("SAMLRequest", message));
    } else if (messagesContext.getOutboundSAMLMessage() instanceof StatusResponseType) {
        queryParams.add(new Pair<String, String>("SAMLResponse", message));
    } else {
        throw new MessageEncodingException(
                "SAML message is neither a SAML RequestAbstractType or StatusResponseType");
    }

    String relayState = messagesContext.getRelayState();
    if (checkRelayState(relayState)) {
        queryParams.add(new Pair<String, String>("RelayState", relayState));
    }

    Credential signingCredential = messagesContext.getOuboundSAMLMessageSigningCredential();
    if (signingCredential != null) {
        // TODO pull SecurityConfiguration from SAMLMessageContext? needs to be added
        String sigAlgURI = getSignatureAlgorithmURI(signingCredential, null);
        Pair<String, String> sigAlg = new Pair<String, String>("SigAlg", sigAlgURI);
        queryParams.add(sigAlg);
        String sigMaterial = urlBuilder.buildQueryString();

        queryParams.add(new Pair<String, String>("Signature", generateSignature(signingCredential, sigAlgURI,
                sigMaterial)));
    }

    return urlBuilder.buildURL();
}