org.opensaml.xml.security.SecurityException Java Examples

The following examples show how to use org.opensaml.xml.security.SecurityException. 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: ChainingCredentialResolver.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Get the iterator from the next resolver in the chain.
 * 
 * @return an iterator of credentials
 */
private Iterator<Credential> getNextCredentialIterator() {
    while (resolverIterator.hasNext()) {
        currentResolver = resolverIterator.next();
            log.debug("Getting credential iterator from next resolver in chain: {}", currentResolver.getClass().toString());
        try {
            return currentResolver.resolve(critSet).iterator();
        } catch (SecurityException e) {
            log.error(String.format("Error resolving credentials from chaining resolver member '%s'",
                    currentResolver.getClass().getName()), e);
            if (resolverIterator.hasNext()) {
                log.error("Will attempt to resolve credentials from next member of resolver chain");
            }
        }
    }

    log.debug("No more credential resolvers available in the resolver chain");
    currentResolver = null;
    return null;
}
 
Example #2
Source File: BasicX509CredentialNameEvaluator.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * {@inheritDoc} 
 * 
 * <p>
 * If the set of trusted names is null or empty, or if no supported name types are configured to be
 * checked, then the evaluation is considered successful.
 * </p>
 * 
 */
@SuppressWarnings("unchecked")
public boolean evaluate(X509Credential credential, Set<String> trustedNames) throws SecurityException {
    if (!isNameCheckingActive()) {
        log.debug("No trusted name options are active, skipping name evaluation");
        return true;
    } else if (trustedNames == null || trustedNames.isEmpty()) {
        log.debug("Supplied trusted names are null or empty, skipping name evaluation");
        return true;
    }

    if (log.isDebugEnabled()) {
        log.debug("Checking trusted names against credential: {}",
                X509Util.getIdentifiersToken(credential, x500DNHandler));
        log.debug("Trusted names being evaluated are: {}",
                trustedNames.toString());
    }        
    return processNameChecks(credential, trustedNames);
}
 
Example #3
Source File: AbstractCriteriaFilteringCredentialResolver.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Extract the evaluable credential criteria from the criteria set.
 * 
 * @param criteriaSet the set of credential criteria to process.
 * @return a set of evaluable Credential criteria
 * @throws SecurityException thrown if there is an error obtaining an instance of EvaluableCredentialCriteria
 *                           from the EvaluableCredentialCriteriaRegistry
 */
private Set<EvaluableCriteria<Credential>> getEvaluableCriteria(CriteriaSet criteriaSet) throws SecurityException {
    Set<EvaluableCriteria<Credential>> evaluable = new HashSet<EvaluableCriteria<Credential>>(criteriaSet.size());
    for (Criteria criteria : criteriaSet) {
        if (criteria instanceof EvaluableCredentialCriteria) {
            evaluable.add((EvaluableCredentialCriteria) criteria);
        } else {
            EvaluableCredentialCriteria evaluableCriteria = 
                EvaluableCredentialCriteriaRegistry.getEvaluator(criteria);
            if (evaluableCriteria != null) {
                evaluable.add(evaluableCriteria);
            }
        }
    }
    return evaluable;
}
 
Example #4
Source File: KeyStoreCredentialResolver.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Build a credential instance from the key store entry.
 * 
 * @param keyStoreEntry the key store entry to process
 * @param entityID the entityID to include in the credential
 * @param usage the usage type to include in the credential
 * @return the new credential instance, appropriate to the type of key store entry being processed
 * @throws SecurityException throw if there is a problem building a credential from the key store entry
 */
protected Credential buildCredential(KeyStore.Entry keyStoreEntry, String entityID, UsageType usage)
        throws SecurityException {

    log.debug("Building credential from keystore entry for entityID {}, usage type {}", entityID, usage);

    Credential credential = null;
    if (keyStoreEntry instanceof KeyStore.PrivateKeyEntry) {
        credential = processPrivateKeyEntry((KeyStore.PrivateKeyEntry) keyStoreEntry, entityID, keystoreUsage);
    } else if (keyStoreEntry instanceof KeyStore.TrustedCertificateEntry) {
        credential = processTrustedCertificateEntry((KeyStore.TrustedCertificateEntry) keyStoreEntry, entityID,
                keystoreUsage);
    } else if (keyStoreEntry instanceof KeyStore.SecretKeyEntry) {
        credential = processSecretKeyEntry((KeyStore.SecretKeyEntry) keyStoreEntry, entityID, keystoreUsage);
    } else {
        throw new SecurityException("KeyStore entry was of an unsupported type: "
                + keyStoreEntry.getClass().getName());
    }
    return credential;
}
 
Example #5
Source File: MetadataCredentialResolver.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Get the list of metadata role descriptors which match the given entityID, role and protocol.
 * 
 * @param entityID entity ID 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)
 * @return a list of role descriptors matching the given parameters, or null
 * @throws SecurityException thrown if there is an error retrieving role descriptors from the metadata provider
 */
protected List<RoleDescriptor> getRoleDescriptors(String entityID, QName role, String protocol)
        throws SecurityException {
    try {
        if (log.isDebugEnabled()) {
            log.debug("Retrieving metadata for entity '{}' in role '{}' for protocol '{}'", 
                    new Object[] {entityID, role, protocol});
        }

        if (DatatypeHelper.isEmpty(protocol)) {
            return metadata.getRole(entityID, role);
        } else {
            RoleDescriptor roleDescriptor = metadata.getRole(entityID, role, protocol);
            if (roleDescriptor == null) {
                return null;
            }
            List<RoleDescriptor> roles = new ArrayList<RoleDescriptor>();
            roles.add(roleDescriptor);
            return roles;
        }
    } catch (MetadataProviderException e) {
        log.error("Unable to read metadata from provider", e);
        throw new SecurityException("Unable to read metadata provider", e);
    }
}
 
Example #6
Source File: LocalKeyInfoCredentialResolver.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/** {@inheritDoc} */
protected void postProcess(KeyInfoResolutionContext kiContext, CriteriaSet criteriaSet,
        List<Credential> credentials) throws SecurityException {
    
    ArrayList<Credential> localCreds = new ArrayList<Credential>();
    
    for (Credential cred : credentials) {
        if (isLocalCredential(cred)) {
            localCreds.add(cred);
        } else if (cred.getPublicKey() != null) {
           localCreds.addAll(resolveByPublicKey(cred.getPublicKey()));
        }
    }
    
    // Also resolve local creds based on any key names that are known
    for (String keyName : kiContext.getKeyNames()) {
        localCreds.addAll(resolveByKeyName(keyName));
    }
    
    credentials.clear();
    credentials.addAll(localCreds);
}
 
Example #7
Source File: PKIXX509CredentialTrustEngine.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Perform PKIX validation on the untrusted credential, using PKIX validation information based on the supplied set
 * of trusted credentials.
 * 
 * @param untrustedX509Credential the credential to evaluate
 * @param validationInfoSet the set of validation information which serves as ths basis for trust evaluation
 * @param trustedNames the set of trusted names for name checking purposes
 * 
 * @return true if PKIX validation of the untrusted credential is successful, otherwise false
 * @throws SecurityException thrown if there is an error validating the untrusted credential
 *          against trusted names or validation information
 */
protected boolean validate(X509Credential untrustedX509Credential, Set<String> trustedNames,
        Iterable<PKIXValidationInformation> validationInfoSet) throws SecurityException {
    
    log.debug("Beginning PKIX validation using trusted validation information");

    if (!checkNames(trustedNames, untrustedX509Credential)) {
        log.debug("Evaluation of credential against trusted names failed. Aborting PKIX validation");
        return false;
    }

    for (PKIXValidationInformation validationInfo : validationInfoSet) {
        try {
            if (pkixTrustEvaluator.validate(validationInfo, untrustedX509Credential)) {
                log.debug("Credential trust established via PKIX validation");
                return true;
            }
        } catch (SecurityException e) {
            // log the operational error, but allow other validation info sets to be tried
            log.debug("Error performing PKIX validation on untrusted credential", e);
        }
    }
    log.debug("Trust of untrusted credential could not be established via PKIX validation");
    return false;
}
 
Example #8
Source File: PKIXX509CredentialTrustEngine.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/** {@inheritDoc} */
public boolean validate(X509Credential untrustedCredential, CriteriaSet trustBasisCriteria)
    throws SecurityException {
    
    log.debug("Attempting PKIX validation of untrusted credential");

    if (untrustedCredential == null) {
        log.error("X.509 credential was null, unable to perform validation");
        return false;
    }

    if (untrustedCredential.getEntityCertificate() == null) {
        log.error("Untrusted X.509 credential's entity certificate was null, unable to perform validation");
        return false;
    }

    Set<String> trustedNames = null;
    if (pkixResolver.supportsTrustedNameResolution()) {
        trustedNames = pkixResolver.resolveTrustedNames(trustBasisCriteria);
    } else {
        log.debug("PKIX resolver does not support resolution of trusted names, skipping name checking");
    }

    return validate(untrustedCredential, trustedNames, pkixResolver.resolve(trustBasisCriteria));
}
 
Example #9
Source File: InlineX509DataProvider.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Find the certificate from the chain that matches one of the specified digests.
 * 
 * @param certs list of certificates to evaluate
 * @param digests X509 digests to use as search criteria
 * @return the matching certificate, or null
 */
protected X509Certificate findCertFromDigest(List<X509Certificate> certs, List<XMLObject> digests) {
    byte[] certValue;
    byte[] xmlValue;
    
    for (XMLObject xo : digests) {
        if (!(xo instanceof X509Digest)) {
            continue;
        }
        X509Digest digest = (X509Digest) xo;
        if (!DatatypeHelper.isEmpty(digest.getValue())) {
            xmlValue = Base64.decode(digest.getValue());
            for (X509Certificate cert : certs) {
                try {
                    certValue = X509Util.getX509Digest(cert, digest.getAlgorithm());
                    if (certValue != null && Arrays.equals(xmlValue, certValue)) {
                        return cert;
                    }
                } catch (SecurityException e) {
                    // Ignore as no match.
                }
            }
        }
    }
    return null;
}
 
Example #10
Source File: X509KeyInfoGeneratorFactory.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/** Process the value of {@link X509Credential#getCRLs()}.
 * 
 * @param keyInfo the KeyInfo that is being built
 * @param x509Data the X509Data that is being built
 * @param credential the Credential that is being processed
 * @throws SecurityException thrown if the CRL data can not be encoded from the Java certificate object
 */
protected void processCRLs(KeyInfo keyInfo, X509Data x509Data, X509Credential credential) 
        throws SecurityException {
    
    if (options.emitCRLs && credential.getCRLs() != null) {
        for (java.security.cert.X509CRL javaCRL : credential.getCRLs()) {
            try {
                X509CRL xmlCRL = KeyInfoHelper.buildX509CRL(javaCRL);
                x509Data.getX509CRLs().add(xmlCRL);
            } catch (CRLException e) {
                throw new SecurityException("Error generating X509CRL element " 
                        + "from a CRL in credential's CRL list", e);
            }
        }
    }
}
 
Example #11
Source File: X509KeyInfoGeneratorFactory.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/** Process the value of {@link X509Credential#getEntityCertificateChain()}.
 * 
 * @param keyInfo the KeyInfo that is being built
 * @param x509Data the X509Data that is being built
 * @param credential the Credential that is being processed
 * @throws SecurityException thrown if the certificate data can not be encoded from the Java certificate object
 */
protected void processEntityCertificateChain(KeyInfo keyInfo, X509Data x509Data, X509Credential credential) 
        throws SecurityException {
    
    if (options.emitEntityCertificateChain && credential.getEntityCertificateChain() != null) {
        for (java.security.cert.X509Certificate javaCert : credential.getEntityCertificateChain()) {
            try {
                X509Certificate xmlCert = KeyInfoHelper.buildX509Certificate(javaCert);
                x509Data.getX509Certificates().add(xmlCert);
            } catch (CertificateEncodingException e) {
                throw new SecurityException("Error generating X509Certificate element " 
                        + "from a certificate in credential's certificate chain", e);
            }
        }
    }
}
 
Example #12
Source File: X509KeyInfoGeneratorFactory.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/** Process the value of {@link X509Credential#getEntityCertificate()}.
 * 
 * @param keyInfo the KeyInfo that is being built
 * @param x509Data the X509Data that is being built
 * @param credential the Credential that is being processed
 * @throws SecurityException thrown if the certificate data can not be encoded from the Java certificate object
 */
protected void processEntityCertificate(KeyInfo keyInfo, X509Data x509Data, X509Credential credential) 
        throws SecurityException {
    
    if (credential.getEntityCertificate() == null) {
        return;
    }
    
    java.security.cert.X509Certificate javaCert = credential.getEntityCertificate();
    
    processCertX509DataOptions(x509Data, javaCert);
    processCertKeyNameOptions(keyInfo, javaCert);
    
    // The cert chain includes the entity cert, so don't add a duplicate
    if (options.emitEntityCertificate && ! options.emitEntityCertificateChain) {
        try {
            X509Certificate xmlCert = KeyInfoHelper.buildX509Certificate(javaCert);
            x509Data.getX509Certificates().add(xmlCert);
        } catch (CertificateEncodingException e) {
            throw new SecurityException("Error generating X509Certificate element " 
                    + "from credential's end-entity certificate", e);
        }
    }
    
}
 
Example #13
Source File: HandlerChainAwareHTTPSOAP11Decoder.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/** {@inheritDoc} */
public void decode(MessageContext messageContext) throws MessageDecodingException, SecurityException {
    log.debug("Beginning to decode message from inbound transport of type: {}", messageContext
            .getInboundMessageTransport().getClass().getName());
    
    doDecode(messageContext);
    
    logDecodedMessage(messageContext);

    processPreSecurityInboundHandlerChain(messageContext);
    log.debug("Successfully processed pre-SecurityPolicy inbound handler chain.");
    
    processSecurityPolicy(messageContext);

    processPostSecurityInboundHandlerChain(messageContext);
    log.debug("Successfully processed post-SecurityPolicy inbound handler chain.");
    
    log.debug("Successfully decoded message.");

    // TODO: This gets executed by BaseSAML2MessageDecoder. Probably needs to be
    // factored out somehow to avoid brittleness in the decode() override.
    checkEndpointURI((SAMLMessageContext) messageContext);
}
 
Example #14
Source File: BaseSignatureTrustEngine.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Check the signature and credential criteria for required values.
 * 
 * @param signature the signature to be evaluated
 * @param content the data over which the signature was computed
 * @param algorithmURI the signing algorithm URI which was used
 * @param trustBasisCriteria the set of trusted credential criteria
 * @throws SecurityException thrown if required values are absent or otherwise invalid
 */
protected void checkParamsRaw(byte[] signature, byte[] content, String algorithmURI, CriteriaSet trustBasisCriteria)
        throws SecurityException {

    if (signature == null || signature.length == 0) {
        throw new SecurityException("Signature byte array was null or empty");
    }
    if (content == null || content.length == 0) {
        throw new SecurityException("Content byte array was null or empty");
    }
    if (DatatypeHelper.isEmpty(algorithmURI)) {
        throw new SecurityException("Signature algorithm was null or empty");
    }
    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: HttpSOAPClient.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/** {@inheritDoc} */
public void send(String endpoint, SOAPMessageContext messageContext) throws SOAPException, SecurityException {
    PostMethod post = null;
    try {
        post = createPostMethod(endpoint, (HttpSOAPRequestParameters) messageContext.getSOAPRequestParameters(),
                (Envelope) messageContext.getOutboundMessage());

        int result = httpClient.executeMethod(post);
        log.debug("Received HTTP status code of {} when POSTing SOAP message to {}", result, endpoint);

        if (result == HttpStatus.SC_OK) {
            processSuccessfulResponse(post, messageContext);
        } else if (result == HttpStatus.SC_INTERNAL_SERVER_ERROR) {
            processFaultResponse(post, messageContext);
        } else {
            throw new SOAPClientException("Received " + result + " HTTP response status code from HTTP request to "
                    + endpoint);
        }
    } catch (IOException e) {
        throw new SOAPClientException("Unable to send request to " + endpoint, e);
    } finally {
        if (post != null) {
            post.releaseConnection();
        }
    }
}
 
Example #16
Source File: BaseMessageDecoder.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Process any {@link SecurityPolicy}s which can be resolved for the message context.
 * 
 * @param messageContext the message context to process
 * @throws SecurityException thrown if the decoded message does not meet the required security constraints
 */
protected void processSecurityPolicy(MessageContext messageContext) throws SecurityException {
    SecurityPolicyResolver policyResolver = messageContext.getSecurityPolicyResolver();
    if (policyResolver != null) {
        Iterable<SecurityPolicy> securityPolicies = policyResolver.resolve(messageContext);
        if (securityPolicies != null) {
            for (SecurityPolicy policy : securityPolicies) {
                if (policy != null) {
                    log.debug("Evaluating security policy of type '{}' for decoded message", policy.getClass()
                            .getName());
                    policy.evaluate(messageContext);
                }
            }
        } else {
            log.debug("No security policy resolved for this message context, no security policy evaluation attempted");
        }
    } else {
        log.debug("No security policy resolver attached to this message context, no security policy evaluation attempted");
    }
}
 
Example #17
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 #18
Source File: BasicProviderKeyInfoCredentialResolver.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Initialize the resolution context that will be used by the providers.
 * 
 * The supplied KeyInfo object is stored in the context, as well as the values of any {@link KeyName} children
 * present. Finally if a credential is resolveble by any registered provider from a plain {@link KeyValue} child,
 * the key from that credential is also stored in the context.
 * 
 * @param kiContext KeyInfo resolution context
 * @param keyInfo the KeyInfo to evaluate
 * @param criteriaSet the credential criteria used to resolve credentials
 * @throws SecurityException thrown if there is an error processing the KeyValue children
 */
protected void initResolutionContext(KeyInfoResolutionContext kiContext, KeyInfo keyInfo, CriteriaSet criteriaSet)
        throws SecurityException {

    kiContext.setKeyInfo(keyInfo);

    // Extract all KeyNames
    kiContext.getKeyNames().addAll(KeyInfoHelper.getKeyNames(keyInfo));
    log.debug("Found {} key names: {}", kiContext.getKeyNames().size(), kiContext.getKeyNames());

    // Extract the Credential based on the (singular) key from an existing KeyValue(s).
    resolveKeyValue(kiContext, criteriaSet, keyInfo.getKeyValues());

    // Extract the Credential based on the (singular) key from an existing DEREncodedKeyValue(s).
    resolveKeyValue(kiContext, criteriaSet, keyInfo.getXMLObjects(DEREncodedKeyValue.DEFAULT_ELEMENT_NAME));
}
 
Example #19
Source File: BasicProviderKeyInfoCredentialResolver.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Process the given KeyInfo child with the registered providers.
 * 
 * The child element is processed by each provider in the ordered list of providers. The credential or credentials
 * resolved by the first provider to successfully do so are returned and processing of the child element is
 * terminated.
 * 
 * @param kiContext KeyInfo resolution context
 * @param criteriaSet the credential criteria used to resolve credentials
 * @param keyInfoChild the KeyInfo to evaluate
 * @return the collection of resolved credentials, or null
 * @throws SecurityException thrown if there is a provider error processing the KeyInfo child
 */
protected Collection<Credential> processKeyInfoChild(KeyInfoResolutionContext kiContext, CriteriaSet criteriaSet,
        XMLObject keyInfoChild) throws SecurityException {

    for (KeyInfoProvider provider : getProviders()) {

        if (!provider.handles(keyInfoChild)) {
            log.debug("Provider {} doesn't handle objects of type {}, skipping", provider.getClass().getName(),
                    keyInfoChild.getElementQName());
            continue;
        }

        log.debug("Processing KeyInfo child {} with provider {}", keyInfoChild.getElementQName(), provider
                .getClass().getName());
        Collection<Credential> creds = provider.process(this, keyInfoChild, criteriaSet, kiContext);

        if (creds != null && !creds.isEmpty()) {
            log.debug("Credentials successfully extracted from child {} by provider {}", keyInfoChild
                    .getElementQName(), provider.getClass().getName());
            return creds;
        }
    }
    return null;
}
 
Example #20
Source File: PKIXSignatureTrustEngine.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Resolve and return a set of trusted validation information.
 * 
 * @param trustBasisCriteria criteria used to describe and/or resolve the information which serves as the basis for
 *            trust evaluation
 * @return a pair consisting of an optional set of trusted names, and an iterable of trusted
 *         PKIXValidationInformation
 * @throws SecurityException thrown if there is an error resolving the information from the trusted resolver
 */
protected Pair<Set<String>, Iterable<PKIXValidationInformation>> resolveValidationInfo(
        CriteriaSet trustBasisCriteria) throws SecurityException {

    Set<String> trustedNames = null;
    if (pkixResolver.supportsTrustedNameResolution()) {
        trustedNames = pkixResolver.resolveTrustedNames(trustBasisCriteria);
    } else {
        log.debug("PKIX resolver does not support resolution of trusted names, skipping name checking");
    }
    Iterable<PKIXValidationInformation> validationInfoSet = pkixResolver.resolve(trustBasisCriteria);

    Pair<Set<String>, Iterable<PKIXValidationInformation>> validationPair = 
        new Pair<Set<String>, Iterable<PKIXValidationInformation>>(trustedNames, validationInfoSet);

    return validationPair;
}
 
Example #21
Source File: ChainingSignatureTrustEngine.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/** {@inheritDoc} */
public boolean validate(byte[] signature, byte[] content, String algorithmURI, CriteriaSet trustBasisCriteria,
        Credential candidateCredential) throws SecurityException {
    for (SignatureTrustEngine engine : engines) {
        if (engine.validate(signature, content, algorithmURI, trustBasisCriteria, candidateCredential)) {
            log.debug("Signature was trusted by chain member: {}", engine.getClass().getName());
            return true;
        }
    }
    return false;
}
 
Example #22
Source File: AbstractCredentialResolver.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/** {@inheritDoc} */
public Credential resolveSingle(CriteriaSet criteriaSet) throws SecurityException {
    Iterable<Credential> creds = resolve(criteriaSet);
    if (creds.iterator().hasNext()) {
        return creds.iterator().next();
    } else {
        return null;
    }
}
 
Example #23
Source File: PKIXSignatureTrustEngine.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/** {@inheritDoc} */
public boolean validate(byte[] signature, byte[] content, String algorithmURI, CriteriaSet trustBasisCriteria,
        Credential candidateCredential) throws SecurityException {

    if (candidateCredential == null || SecurityHelper.extractVerificationKey(candidateCredential) == null) {
        log.debug("Candidate credential was either not supplied or did not contain verification key");
        log.debug("PKIX trust engine requires supplied key, skipping PKIX trust evaluation");
        return false;
    }

    checkParamsRaw(signature, content, algorithmURI, trustBasisCriteria);

    Pair<Set<String>, Iterable<PKIXValidationInformation>> validationPair = 
        resolveValidationInfo(trustBasisCriteria);

    try {
        if (SigningUtil.verifyWithURI(candidateCredential, algorithmURI, signature, content)) {
            log.debug("Successfully verified raw signature using supplied candidate credential");
            log.debug("Attempting to establish trust of supplied candidate credential");
            if (evaluateTrust(candidateCredential, validationPair)) {
                log.debug("Successfully established trust of supplied candidate credential");
                return true;
            } else {
                log.debug("Failed to establish trust of supplied candidate credential");
            }
        } else {
            log.debug("Cryptographic verification of raw signature failed with candidate credential");
        }
    } catch (SecurityException e) {
        // Java 7 now throws this exception under conditions such as mismatched key sizes.
        // Swallow this, it's logged by the verifyWithURI method already.
    }

    log.debug("PKIX validation of raw signature failed, "
            + "unable to establish trust of supplied verification credential");
    return false;
}
 
Example #24
Source File: BaseSAML1MessageDecoder.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/** {@inheritDoc} */
public void decode(MessageContext messageContext) throws MessageDecodingException, SecurityException {
    super.decode(messageContext);
    
    SAMLMessageContext samlMsgCtx = (SAMLMessageContext) messageContext;
    if (samlMsgCtx.getInboundSAMLMessage() instanceof ResponseAbstractType) {
        checkEndpointURI(samlMsgCtx);
    }
}
 
Example #25
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 public key criteria.
 * 
 * @param publicKey the public key criteria
 * @return collection of local credentials which contain the private key
 *          corresponding to the specified public key
 * @throws SecurityException  thrown if there is a problem resolving credentials from the 
 *          local credential resolver
 */
protected Collection<? extends Credential> resolveByPublicKey(PublicKey publicKey) throws SecurityException {
    ArrayList<Credential> localCreds = new ArrayList<Credential>();
    
    CriteriaSet criteriaSet = new CriteriaSet( new PublicKeyCriteria(publicKey) );
    for (Credential cred : getLocalCredentialResolver().resolve(criteriaSet)) {
        if (isLocalCredential(cred)) {
            localCreds.add(cred);
        }
    }
    
    return localCreds;
}
 
Example #26
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 #27
Source File: InlineX509DataProvider.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Extract certificates from the X509Data.
 * 
 * @param x509Data the X509Data element
 * @return a list of X509Certificates
 * @throws SecurityException thrown if there is an error extracting certificates
 */
private List<X509Certificate> extractCertificates(X509Data x509Data) throws SecurityException {
    List<X509Certificate> certs = null;
    try {
        certs = KeyInfoHelper.getCertificates(x509Data);
    } catch (CertificateException e) {
        log.error("Error extracting certificates from X509Data", e);
        throw new SecurityException("Error extracting certificates from X509Data", e);
    }
    log.debug("Found {} X509Certificates", certs.size());
    return certs;
}
 
Example #28
Source File: InlineX509DataProvider.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Extract CRL's from the X509Data.
 * 
 * @param x509Data the X509Data element
 * @return a list of X509CRLs
 * @throws SecurityException thrown if there is an error extracting CRL's
 */
private List<X509CRL> extractCRLs(X509Data x509Data) throws SecurityException {
    List<X509CRL> crls = null;
    try {
        crls = KeyInfoHelper.getCRLs(x509Data);
    } catch (CRLException e) {
        log.error("Error extracting CRL's from X509Data", e);
        throw new SecurityException("Error extracting CRL's from X509Data", e);
    }
    
    log.debug("Found {} X509CRLs", crls.size());
    return crls;
}
 
Example #29
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 #30
Source File: BasicProviderKeyInfoCredentialResolver.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Use registered providers to process the non-KeyValue/DEREncodedKeyValue children of KeyInfo.
 * 
 * Each child element is processed in document order. Each child element is processed by each provider in the
 * ordered list of providers. The credential or credentials resolved by the first provider to successfully do so are
 * added to the effective set resolved by the KeyInfo resolver.
 * 
 * @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 a provider error processing the KeyInfo children
 */
protected void processKeyInfoChildren(KeyInfoResolutionContext kiContext, CriteriaSet criteriaSet,
        List<Credential> credentials) throws SecurityException {

    for (XMLObject keyInfoChild : kiContext.getKeyInfo().getXMLObjects()) {

        if (keyInfoChild instanceof KeyValue || keyInfoChild instanceof DEREncodedKeyValue) {
            continue;
        }

        log.debug("Processing KeyInfo child with qname: {}", keyInfoChild.getElementQName());
        Collection<Credential> childCreds = processKeyInfoChild(kiContext, criteriaSet, keyInfoChild);

        if (childCreds != null && !childCreds.isEmpty()) {
            credentials.addAll(childCreds);
        } else {
            // Not really an error or warning if KeyName doesn't produce a credential
            if (keyInfoChild instanceof KeyName) {
                log.debug("KeyName, with value {}, did not independently produce a credential based on any registered providers",
                                ((KeyName) keyInfoChild).getValue());

            } else {
                log.warn("No credentials could be extracted from KeyInfo child with qname {} by any registered provider",
                                keyInfoChild.getElementQName());
            }
        }
    }
}