Search in sources :

Example 6 with SignableSAMLObject

use of org.opensaml.saml.common.SignableSAMLObject in project cas by apereo.

the class DefaultSSOSamlHttpRequestExtractor method extract.

@Audit(action = AuditableActions.SAML2_REQUEST, actionResolverName = AuditActionResolvers.SAML2_REQUEST_ACTION_RESOLVER, resourceResolverName = AuditResourceResolvers.SAML2_REQUEST_RESOURCE_RESOLVER)
@Override
@SneakyThrows
public Optional<Pair<? extends SignableSAMLObject, MessageContext>> extract(final HttpServletRequest request, final BaseHttpServletRequestXMLMessageDecoder decoder, final Class<? extends SignableSAMLObject> clazz) {
    LOGGER.trace("Received SAML profile request [{}]", request.getRequestURI());
    decoder.setHttpServletRequest(request);
    decoder.setParserPool(this.parserPool);
    decoder.initialize();
    decoder.decode();
    val messageContext = decoder.getMessageContext();
    LOGGER.trace("Locating SAML object from message context...");
    val object = (SignableSAMLObject) messageContext.getMessage();
    if (object == null) {
        LOGGER.debug("SAML object cannot be determined from the decoder [{}]", decoder.getClass().getSimpleName());
        return Optional.empty();
    }
    if (!clazz.isAssignableFrom(object.getClass())) {
        LOGGER.debug("SAML object [{}] type does not match [{}]", object.getClass().getName(), clazz);
        return Optional.empty();
    }
    LOGGER.debug("Decoded SAML object [{}] from http request", object.getElementQName());
    return Optional.of(Pair.of(object, messageContext));
}
Also used : lombok.val(lombok.val) SignableSAMLObject(org.opensaml.saml.common.SignableSAMLObject) Audit(org.apereo.inspektr.audit.annotation.Audit) SneakyThrows(lombok.SneakyThrows)

Example 7 with SignableSAMLObject

use of org.opensaml.saml.common.SignableSAMLObject in project ddf by codice.

the class LogoutMessageImpl method sendSamlLogoutRequest.

@Override
public String sendSamlLogoutRequest(LogoutWrapper request, String targetUri, boolean isSoap, @Nullable Cookie cookie) throws IOException, LogoutSecurityException {
    XMLObject xmlObject = isSoap ? SamlProtocol.createSoapMessage((SignableSAMLObject) request.getMessage()) : (XMLObject) request;
    Element requestElement = getElementFromSaml(new LogoutWrapperImpl(xmlObject));
    String requestMessage = DOM2Writer.nodeToString(requestElement);
    try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
        HttpPost post = new HttpPost(targetUri);
        post.addHeader("Cache-Control", "no-cache, no-store");
        post.addHeader("Pragma", "no-cache");
        post.addHeader("SOAPAction", SAML_SOAP_ACTION);
        post.addHeader("Content-Type", "application/soap+xml");
        post.setEntity(new StringEntity(requestMessage, "utf-8"));
        ResponseHandler<String> responseHandler = new BasicResponseHandler();
        BasicHttpContext context = new BasicHttpContext();
        if (cookie != null) {
            BasicClientCookie basicClientCookie = new BasicClientCookie(cookie.getName(), cookie.getValue());
            basicClientCookie.setDomain(cookie.getDomain());
            basicClientCookie.setPath(cookie.getPath());
            BasicCookieStore cookieStore = new BasicCookieStore();
            cookieStore.addCookie(basicClientCookie);
            context.setAttribute(HttpClientContext.COOKIE_STORE, cookieStore);
        }
        return httpClient.execute(post, responseHandler, context);
    }
}
Also used : CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) HttpPost(org.apache.http.client.methods.HttpPost) BasicHttpContext(org.apache.http.protocol.BasicHttpContext) Element(org.w3c.dom.Element) BasicResponseHandler(org.apache.http.impl.client.BasicResponseHandler) XMLObject(org.opensaml.core.xml.XMLObject) BasicClientCookie(org.apache.http.impl.cookie.BasicClientCookie) StringEntity(org.apache.http.entity.StringEntity) BasicCookieStore(org.apache.http.impl.client.BasicCookieStore) SignableSAMLObject(org.opensaml.saml.common.SignableSAMLObject)

Example 8 with SignableSAMLObject

use of org.opensaml.saml.common.SignableSAMLObject in project ddf by codice.

the class LogoutMessageImpl method extractXmlObject.

@Override
public LogoutWrapper<SignableSAMLObject> extractXmlObject(String samlLogoutResponse) throws LogoutSecurityException, XMLStreamException {
    try {
        Document responseDoc = StaxUtils.read(new ByteArrayInputStream(samlLogoutResponse.getBytes(StandardCharsets.UTF_8)));
        XMLObject xmlObject = OpenSAMLUtil.fromDom(responseDoc.getDocumentElement());
        if (xmlObject instanceof SignableSAMLObject) {
            return new LogoutWrapperImpl<>((SignableSAMLObject) xmlObject);
        }
        return null;
    } catch (WSSecurityException e) {
        throw new LogoutSecurityException(e);
    }
}
Also used : SignableSAMLObject(org.opensaml.saml.common.SignableSAMLObject) ByteArrayInputStream(java.io.ByteArrayInputStream) XMLObject(org.opensaml.core.xml.XMLObject) WSSecurityException(org.apache.wss4j.common.ext.WSSecurityException) Document(org.w3c.dom.Document) LogoutSecurityException(ddf.security.samlp.LogoutSecurityException)

Example 9 with SignableSAMLObject

use of org.opensaml.saml.common.SignableSAMLObject in project cxf by apache.

the class SamlPostBindingFilter method signAuthnRequest.

protected void signAuthnRequest(AuthnRequest authnRequest) throws Exception {
    Crypto crypto = getSignatureCrypto();
    if (crypto == null) {
        LOG.fine("No crypto instance of properties file configured for signature");
        throw ExceptionUtils.toInternalServerErrorException(null, null);
    }
    String signatureUser = getSignatureUsername();
    if (signatureUser == null) {
        LOG.fine("No user configured for signature");
        throw ExceptionUtils.toInternalServerErrorException(null, null);
    }
    CallbackHandler callbackHandler = getCallbackHandler();
    if (callbackHandler == null) {
        LOG.fine("No CallbackHandler configured to supply a password for signature");
        throw ExceptionUtils.toInternalServerErrorException(null, null);
    }
    CryptoType cryptoType = new CryptoType(CryptoType.TYPE.ALIAS);
    cryptoType.setAlias(signatureUser);
    X509Certificate[] issuerCerts = crypto.getX509Certificates(cryptoType);
    if (issuerCerts == null) {
        throw new Exception("No issuer certs were found to sign the request using name: " + signatureUser);
    }
    String sigAlgo = SSOConstants.RSA_SHA1;
    String pubKeyAlgo = issuerCerts[0].getPublicKey().getAlgorithm();
    LOG.fine("automatic sig algo detection: " + pubKeyAlgo);
    if (pubKeyAlgo.equalsIgnoreCase("DSA")) {
        sigAlgo = SSOConstants.DSA_SHA1;
    }
    LOG.fine("Using Signature algorithm " + sigAlgo);
    // Get the password
    WSPasswordCallback[] cb = { new WSPasswordCallback(signatureUser, WSPasswordCallback.SIGNATURE) };
    callbackHandler.handle(cb);
    String password = cb[0].getPassword();
    // Get the private key
    PrivateKey privateKey = crypto.getPrivateKey(signatureUser, password);
    // Create the signature
    Signature signature = OpenSAMLUtil.buildSignature();
    signature.setCanonicalizationAlgorithm(SignatureConstants.ALGO_ID_C14N_EXCL_OMIT_COMMENTS);
    signature.setSignatureAlgorithm(sigAlgo);
    BasicX509Credential signingCredential = new BasicX509Credential(issuerCerts[0], privateKey);
    signature.setSigningCredential(signingCredential);
    X509KeyInfoGeneratorFactory kiFactory = new X509KeyInfoGeneratorFactory();
    kiFactory.setEmitEntityCertificate(true);
    try {
        KeyInfo keyInfo = kiFactory.newInstance().generate(signingCredential);
        signature.setKeyInfo(keyInfo);
    } catch (org.opensaml.security.SecurityException ex) {
        throw new Exception("Error generating KeyInfo from signing credential", ex);
    }
    SignableSAMLObject signableObject = authnRequest;
    signableObject.setSignature(signature);
    signableObject.releaseDOM();
    signableObject.releaseChildrenDOM(true);
}
Also used : CallbackHandler(javax.security.auth.callback.CallbackHandler) PrivateKey(java.security.PrivateKey) CryptoType(org.apache.wss4j.common.crypto.CryptoType) X509Certificate(java.security.cert.X509Certificate) IOException(java.io.IOException) Crypto(org.apache.wss4j.common.crypto.Crypto) SignableSAMLObject(org.opensaml.saml.common.SignableSAMLObject) BasicX509Credential(org.opensaml.security.x509.BasicX509Credential) KeyInfo(org.opensaml.xmlsec.signature.KeyInfo) Signature(org.opensaml.xmlsec.signature.Signature) WSPasswordCallback(org.apache.wss4j.common.ext.WSPasswordCallback) X509KeyInfoGeneratorFactory(org.opensaml.xmlsec.keyinfo.impl.X509KeyInfoGeneratorFactory)

Example 10 with SignableSAMLObject

use of org.opensaml.saml.common.SignableSAMLObject in project cxf by apache.

the class CombinedValidatorTest method signResponse.

private void signResponse(Response response, String issuerKeyName, String issuerKeyPassword, Crypto issuerCrypto, boolean useKeyInfo) throws Exception {
    // 
    // Create the signature
    // 
    Signature signature = OpenSAMLUtil.buildSignature();
    signature.setCanonicalizationAlgorithm(SignatureConstants.ALGO_ID_C14N_EXCL_OMIT_COMMENTS);
    // prepare to sign the SAML token
    CryptoType cryptoType = new CryptoType(CryptoType.TYPE.ALIAS);
    cryptoType.setAlias(issuerKeyName);
    X509Certificate[] issuerCerts = issuerCrypto.getX509Certificates(cryptoType);
    if (issuerCerts == null) {
        throw new Exception("No issuer certs were found to sign the SAML Assertion using issuer name: " + issuerKeyName);
    }
    String sigAlgo = SignatureConstants.ALGO_ID_SIGNATURE_RSA_SHA1;
    String pubKeyAlgo = issuerCerts[0].getPublicKey().getAlgorithm();
    if (pubKeyAlgo.equalsIgnoreCase("DSA")) {
        sigAlgo = SignatureConstants.ALGO_ID_SIGNATURE_DSA;
    }
    PrivateKey privateKey = issuerCrypto.getPrivateKey(issuerKeyName, issuerKeyPassword);
    signature.setSignatureAlgorithm(sigAlgo);
    BasicX509Credential signingCredential = new BasicX509Credential(issuerCerts[0], privateKey);
    signature.setSigningCredential(signingCredential);
    if (useKeyInfo) {
        X509KeyInfoGeneratorFactory kiFactory = new X509KeyInfoGeneratorFactory();
        kiFactory.setEmitEntityCertificate(true);
        try {
            KeyInfo keyInfo = kiFactory.newInstance().generate(signingCredential);
            signature.setKeyInfo(keyInfo);
        } catch (org.opensaml.security.SecurityException ex) {
            throw new Exception("Error generating KeyInfo from signing credential", ex);
        }
    }
    // add the signature to the assertion
    SignableSAMLObject signableObject = response;
    signableObject.setSignature(signature);
    signableObject.releaseDOM();
    signableObject.releaseChildrenDOM(true);
}
Also used : PrivateKey(java.security.PrivateKey) CryptoType(org.apache.wss4j.common.crypto.CryptoType) X509Certificate(java.security.cert.X509Certificate) WSSecurityException(org.apache.wss4j.common.ext.WSSecurityException) SignableSAMLObject(org.opensaml.saml.common.SignableSAMLObject) BasicX509Credential(org.opensaml.security.x509.BasicX509Credential) KeyInfo(org.opensaml.xmlsec.signature.KeyInfo) Signature(org.opensaml.xmlsec.signature.Signature) X509KeyInfoGeneratorFactory(org.opensaml.xmlsec.keyinfo.impl.X509KeyInfoGeneratorFactory)

Aggregations

SignableSAMLObject (org.opensaml.saml.common.SignableSAMLObject)11 WSSecurityException (org.apache.wss4j.common.ext.WSSecurityException)5 PrivateKey (java.security.PrivateKey)4 X509Certificate (java.security.cert.X509Certificate)4 CryptoType (org.apache.wss4j.common.crypto.CryptoType)4 BasicX509Credential (org.opensaml.security.x509.BasicX509Credential)4 X509KeyInfoGeneratorFactory (org.opensaml.xmlsec.keyinfo.impl.X509KeyInfoGeneratorFactory)4 KeyInfo (org.opensaml.xmlsec.signature.KeyInfo)4 Signature (org.opensaml.xmlsec.signature.Signature)4 IOException (java.io.IOException)2 UnauthorizedServiceException (org.apereo.cas.services.UnauthorizedServiceException)2 XMLObject (org.opensaml.core.xml.XMLObject)2 MessageContext (org.opensaml.messaging.context.MessageContext)2 LogoutSecurityException (ddf.security.samlp.LogoutSecurityException)1 SamlProtocol (ddf.security.samlp.SamlProtocol)1 EntityInformation (ddf.security.samlp.impl.EntityInformation)1 ByteArrayInputStream (java.io.ByteArrayInputStream)1 CallbackHandler (javax.security.auth.callback.CallbackHandler)1 NonNull (lombok.NonNull)1 SneakyThrows (lombok.SneakyThrows)1