Search in sources :

Example 6 with Crypto

use of org.apache.wss4j.common.crypto.Crypto in project cxf by apache.

the class AbstractXmlSigInHandler method checkSignature.

protected void checkSignature(Message message) {
    Document doc = getDocument(message);
    if (doc == null) {
        return;
    }
    Element root = doc.getDocumentElement();
    Element signatureElement = getSignatureElement(root);
    if (signatureElement == null) {
        throwFault("XML Signature is not available", null);
    }
    String cryptoKey = null;
    String propKey = null;
    if (RSSecurityUtils.isSignedAndEncryptedTwoWay(message)) {
        cryptoKey = SecurityConstants.ENCRYPT_CRYPTO;
        propKey = SecurityConstants.ENCRYPT_PROPERTIES;
    } else {
        cryptoKey = SecurityConstants.SIGNATURE_CRYPTO;
        propKey = SecurityConstants.SIGNATURE_PROPERTIES;
    }
    Crypto crypto = null;
    try {
        CryptoLoader loader = new CryptoLoader();
        crypto = loader.getCrypto(message, cryptoKey, propKey);
    } catch (Exception ex) {
        throwFault("Crypto can not be loaded", ex);
    }
    boolean valid = false;
    Reference ref = null;
    try {
        XMLSignature signature = new XMLSignature(signatureElement, "", true);
        if (sigProps != null) {
            SignedInfo sInfo = signature.getSignedInfo();
            if (sigProps.getSignatureAlgo() != null && !sigProps.getSignatureAlgo().equals(sInfo.getSignatureMethodURI())) {
                throwFault("Signature Algorithm is not supported", null);
            }
            if (sigProps.getSignatureC14nMethod() != null && !sigProps.getSignatureC14nMethod().equals(sInfo.getCanonicalizationMethodURI())) {
                throwFault("Signature C14n Algorithm is not supported", null);
            }
        }
        ref = getReference(signature);
        Element signedElement = validateReference(root, ref);
        if (signedElement.hasAttributeNS(null, "ID")) {
            signedElement.setIdAttributeNS(null, "ID", true);
        }
        if (signedElement.hasAttributeNS(null, "Id")) {
            signedElement.setIdAttributeNS(null, "Id", true);
        }
        X509Certificate cert = null;
        PublicKey publicKey = null;
        // See also WSS4J SAMLUtil.getCredentialFromKeyInfo
        KeyInfo keyInfo = signature.getKeyInfo();
        if (keyInfo != null) {
            cert = keyInfo.getX509Certificate();
            if (cert != null) {
                valid = signature.checkSignatureValue(cert);
            } else {
                publicKey = keyInfo.getPublicKey();
                if (publicKey != null) {
                    valid = signature.checkSignatureValue(publicKey);
                }
            }
        } else if (!keyInfoMustBeAvailable) {
            String user = getUserName(crypto, message);
            cert = RSSecurityUtils.getCertificates(crypto, user)[0];
            publicKey = cert.getPublicKey();
            valid = signature.checkSignatureValue(cert);
        }
        // validate trust
        new TrustValidator().validateTrust(crypto, cert, publicKey, getSubjectContraints(message));
        if (valid && persistSignature) {
            if (signature.getKeyInfo() != null) {
                message.put(SIGNING_CERT, signature.getKeyInfo().getX509Certificate());
            }
            if (signature.getKeyInfo() != null) {
                message.put(SIGNING_PUBLIC_KEY, signature.getKeyInfo().getPublicKey());
            }
            message.setContent(Element.class, signedElement);
        }
    } catch (Exception ex) {
        throwFault("Signature validation failed", ex);
    }
    if (!valid) {
        throwFault("Signature validation failed", null);
    }
    if (removeSignature) {
        if (!isEnveloping(root)) {
            Element signedEl = getSignedElement(root, ref);
            signedEl.removeAttribute("ID");
            root.removeChild(signatureElement);
        } else {
            Element actualBody = getActualBody(root);
            Document newDoc = DOMUtils.createDocument();
            newDoc.adoptNode(actualBody);
            root = actualBody;
        }
    }
    message.setContent(XMLStreamReader.class, new W3CDOMStreamReader(root));
    message.setContent(InputStream.class, null);
}
Also used : TrustValidator(org.apache.cxf.rs.security.common.TrustValidator) Reference(org.apache.xml.security.signature.Reference) PublicKey(java.security.PublicKey) Element(org.w3c.dom.Element) CryptoLoader(org.apache.cxf.rs.security.common.CryptoLoader) Document(org.w3c.dom.Document) PatternSyntaxException(java.util.regex.PatternSyntaxException) XMLSecurityException(org.apache.xml.security.exceptions.XMLSecurityException) X509Certificate(java.security.cert.X509Certificate) SignedInfo(org.apache.xml.security.signature.SignedInfo) Crypto(org.apache.wss4j.common.crypto.Crypto) KeyInfo(org.apache.xml.security.keys.KeyInfo) W3CDOMStreamReader(org.apache.cxf.staxutils.W3CDOMStreamReader) XMLSignature(org.apache.xml.security.signature.XMLSignature)

Example 7 with Crypto

use of org.apache.wss4j.common.crypto.Crypto in project cxf by apache.

the class XmlEncOutInterceptor method encryptDocument.

protected Document encryptDocument(Message message, Document payloadDoc) throws Exception {
    String symEncAlgo = encProps.getEncryptionSymmetricKeyAlgo() == null ? XMLCipher.AES_256 : encProps.getEncryptionSymmetricKeyAlgo();
    byte[] secretKey = getSymmetricKey(symEncAlgo);
    Document encryptedDataDoc = DOMUtils.createDocument();
    Element encryptedDataElement = createEncryptedDataElement(encryptedDataDoc, symEncAlgo);
    if (encryptSymmetricKey) {
        X509Certificate receiverCert = null;
        String userName = (String) SecurityUtils.getSecurityPropertyValue(SecurityConstants.ENCRYPT_USERNAME, message);
        if (RSSecurityUtils.USE_REQUEST_SIGNATURE_CERT.equals(userName) && !MessageUtils.isRequestor(message)) {
            receiverCert = (X509Certificate) message.getExchange().getInMessage().get(AbstractXmlSecInHandler.SIGNING_CERT);
            if (receiverCert == null) {
                receiverCert = (X509Certificate) message.getExchange().getInMessage().get(SecurityConstants.ENCRYPT_CERT);
            }
        } else {
            CryptoLoader loader = new CryptoLoader();
            Crypto crypto = loader.getCrypto(message, SecurityConstants.ENCRYPT_CRYPTO, SecurityConstants.ENCRYPT_PROPERTIES);
            userName = RSSecurityUtils.getUserName(crypto, userName);
            if (StringUtils.isEmpty(userName)) {
                throw new Exception("User name is not available");
            }
            receiverCert = getReceiverCertificateFromCrypto(crypto, userName);
        }
        if (receiverCert == null) {
            throw new Exception("Receiver certificate is not available");
        }
        String keyEncAlgo = encProps.getEncryptionKeyTransportAlgo() == null ? XMLCipher.RSA_OAEP : encProps.getEncryptionKeyTransportAlgo();
        String digestAlgo = encProps.getEncryptionDigestAlgo();
        byte[] encryptedSecretKey = encryptSymmetricKey(secretKey, receiverCert, keyEncAlgo, digestAlgo);
        addEncryptedKeyElement(encryptedDataElement, receiverCert, encryptedSecretKey, keyEncAlgo, digestAlgo);
    }
    // encrypt payloadDoc
    XMLCipher xmlCipher = EncryptionUtils.initXMLCipher(symEncAlgo, XMLCipher.ENCRYPT_MODE, symmetricKey);
    Document result = xmlCipher.doFinal(payloadDoc, payloadDoc.getDocumentElement(), false);
    NodeList list = result.getElementsByTagNameNS(ENC_NS, "CipherValue");
    if (list.getLength() != 1) {
        throw new Exception("Payload CipherData is missing");
    }
    String cipherText = ((Element) list.item(0)).getTextContent().trim();
    Element cipherValue = createCipherValue(encryptedDataDoc, encryptedDataDoc.getDocumentElement());
    cipherValue.appendChild(encryptedDataDoc.createTextNode(cipherText));
    // StaxUtils.copy(new DOMSource(encryptedDataDoc), System.out);
    return encryptedDataDoc;
}
Also used : Crypto(org.apache.wss4j.common.crypto.Crypto) Element(org.w3c.dom.Element) CryptoLoader(org.apache.cxf.rs.security.common.CryptoLoader) NodeList(org.w3c.dom.NodeList) XMLCipher(org.apache.xml.security.encryption.XMLCipher) Document(org.w3c.dom.Document) X509Certificate(java.security.cert.X509Certificate) WSSecurityException(org.apache.wss4j.common.ext.WSSecurityException) IllegalBlockSizeException(javax.crypto.IllegalBlockSizeException) BadPaddingException(javax.crypto.BadPaddingException) CertificateEncodingException(java.security.cert.CertificateEncodingException)

Example 8 with Crypto

use of org.apache.wss4j.common.crypto.Crypto in project cxf by apache.

the class XmlSecOutInterceptor method configureEncryption.

private void configureEncryption(Message message, XMLSecurityProperties properties) throws Exception {
    String symEncAlgo = encryptionProperties.getEncryptionSymmetricKeyAlgo() == null ? XMLCipher.AES_256 : encryptionProperties.getEncryptionSymmetricKeyAlgo();
    properties.setEncryptionSymAlgorithm(symEncAlgo);
    properties.setEncryptionKey(getSymmetricKey(symEncAlgo));
    if (encryptSymmetricKey) {
        X509Certificate sendingCert = null;
        String userName = (String) SecurityUtils.getSecurityPropertyValue(SecurityConstants.ENCRYPT_USERNAME, message);
        if (RSSecurityUtils.USE_REQUEST_SIGNATURE_CERT.equals(userName) && !MessageUtils.isRequestor(message)) {
            sendingCert = message.getExchange().getInMessage().getContent(X509Certificate.class);
            if (sendingCert == null) {
                @SuppressWarnings("unchecked") final List<SecurityEvent> incomingSecurityEventList = (List<SecurityEvent>) message.getExchange().get(SecurityEvent.class.getName() + ".in");
                sendingCert = getUseReqSigCert(incomingSecurityEventList);
            }
        } else {
            CryptoLoader loader = new CryptoLoader();
            Crypto crypto = loader.getCrypto(message, SecurityConstants.ENCRYPT_CRYPTO, SecurityConstants.ENCRYPT_PROPERTIES);
            userName = RSSecurityUtils.getUserName(crypto, userName);
            if (StringUtils.isEmpty(userName)) {
                throw new Exception("User name is not available");
            }
            sendingCert = getCertificateFromCrypto(crypto, userName);
        }
        if (sendingCert == null) {
            throw new Exception("Sending certificate is not available");
        }
        properties.setEncryptionUseThisCertificate(sendingCert);
        properties.setEncryptionKeyIdentifier(convertKeyIdentifier(encryptionProperties.getEncryptionKeyIdType()));
        properties.setEncryptionKeyName(encryptionProperties.getEncryptionKeyName());
        if (encryptionProperties.getEncryptionKeyTransportAlgo() != null) {
            properties.setEncryptionKeyTransportAlgorithm(encryptionProperties.getEncryptionKeyTransportAlgo());
        }
        if (encryptionProperties.getEncryptionDigestAlgo() != null) {
            properties.setEncryptionKeyTransportDigestAlgorithm(encryptionProperties.getEncryptionDigestAlgo());
        }
    }
    properties.addAction(XMLSecurityConstants.ENCRYPT);
    if (elementsToEncrypt == null || elementsToEncrypt.isEmpty()) {
        LOG.fine("No Elements to encrypt are specified, so the entire request is encrypt");
        SecurePart securePart = new SecurePart((QName) null, SecurePart.Modifier.Element);
        securePart.setSecureEntireRequest(true);
        properties.addEncryptionPart(securePart);
    } else {
        for (QName element : elementsToEncrypt) {
            SecurePart securePart = new SecurePart(element, SecurePart.Modifier.Element);
            properties.addEncryptionPart(securePart);
        }
    }
}
Also used : SecurePart(org.apache.xml.security.stax.ext.SecurePart) TokenSecurityEvent(org.apache.xml.security.stax.securityEvent.TokenSecurityEvent) SecurityEvent(org.apache.xml.security.stax.securityEvent.SecurityEvent) Crypto(org.apache.wss4j.common.crypto.Crypto) QName(javax.xml.namespace.QName) CryptoLoader(org.apache.cxf.rs.security.common.CryptoLoader) ArrayList(java.util.ArrayList) List(java.util.List) X509Certificate(java.security.cert.X509Certificate) WSSecurityException(org.apache.wss4j.common.ext.WSSecurityException) XMLStreamException(javax.xml.stream.XMLStreamException) XMLSecurityException(org.apache.xml.security.exceptions.XMLSecurityException)

Example 9 with Crypto

use of org.apache.wss4j.common.crypto.Crypto in project cxf by apache.

the class SamlRedirectBindingFilter method signRequest.

/**
 * Sign a request according to the redirect binding spec for Web SSO
 */
private void signRequest(String authnRequest, String relayState, UriBuilder ub) 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();
    String jceSigAlgo = "SHA1withRSA";
    LOG.fine("automatic sig algo detection: " + pubKeyAlgo);
    if (pubKeyAlgo.equalsIgnoreCase("DSA")) {
        sigAlgo = SSOConstants.DSA_SHA1;
        jceSigAlgo = "SHA1withDSA";
    }
    LOG.fine("Using Signature algorithm " + sigAlgo);
    ub.queryParam(SSOConstants.SIG_ALG, URLEncoder.encode(sigAlgo, StandardCharsets.UTF_8.name()));
    // 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);
    // Sign the request
    Signature signature = Signature.getInstance(jceSigAlgo);
    signature.initSign(privateKey);
    String requestToSign = SSOConstants.SAML_REQUEST + "=" + authnRequest + "&" + SSOConstants.RELAY_STATE + "=" + relayState + "&" + SSOConstants.SIG_ALG + "=" + URLEncoder.encode(sigAlgo, StandardCharsets.UTF_8.name());
    signature.update(requestToSign.getBytes(StandardCharsets.UTF_8));
    byte[] signBytes = signature.sign();
    String encodedSignature = Base64.getEncoder().encodeToString(signBytes);
    ub.queryParam(SSOConstants.SIGNATURE, URLEncoder.encode(encodedSignature, StandardCharsets.UTF_8.name()));
}
Also used : Crypto(org.apache.wss4j.common.crypto.Crypto) CallbackHandler(javax.security.auth.callback.CallbackHandler) PrivateKey(java.security.PrivateKey) Signature(java.security.Signature) CryptoType(org.apache.wss4j.common.crypto.CryptoType) WSPasswordCallback(org.apache.wss4j.common.ext.WSPasswordCallback) X509Certificate(java.security.cert.X509Certificate) IOException(java.io.IOException)

Example 10 with Crypto

use of org.apache.wss4j.common.crypto.Crypto in project cxf by apache.

the class CombinedValidatorTest method createResponse.

private Response createResponse(Document doc) throws Exception {
    Status status = SAML2PResponseComponentBuilder.createStatus(SAMLProtocolResponseValidator.SAML2_STATUSCODE_SUCCESS, null);
    Response response = SAML2PResponseComponentBuilder.createSAMLResponse("http://cxf.apache.org/saml", "http://cxf.apache.org/issuer", status);
    response.setDestination("http://recipient.apache.org");
    // Create an AuthenticationAssertion
    SAML2CallbackHandler callbackHandler = new SAML2CallbackHandler();
    callbackHandler.setStatement(SAML2CallbackHandler.Statement.AUTHN);
    callbackHandler.setIssuer("http://cxf.apache.org/issuer");
    callbackHandler.setConfirmationMethod(SAML2Constants.CONF_BEARER);
    callbackHandler.setSubjectName("alice");
    SubjectConfirmationDataBean subjectConfirmationData = new SubjectConfirmationDataBean();
    subjectConfirmationData.setAddress("http://apache.org");
    subjectConfirmationData.setInResponseTo("12345");
    subjectConfirmationData.setNotAfter(new DateTime().plusMinutes(5));
    subjectConfirmationData.setRecipient("http://recipient.apache.org");
    callbackHandler.setSubjectConfirmationData(subjectConfirmationData);
    ConditionsBean conditions = new ConditionsBean();
    conditions.setNotBefore(new DateTime());
    conditions.setNotAfter(new DateTime().plusMinutes(5));
    AudienceRestrictionBean audienceRestriction = new AudienceRestrictionBean();
    audienceRestriction.setAudienceURIs(Collections.singletonList("http://service.apache.org"));
    conditions.setAudienceRestrictions(Collections.singletonList(audienceRestriction));
    callbackHandler.setConditions(conditions);
    SAMLCallback samlCallback = new SAMLCallback();
    SAMLUtil.doSAMLCallback(callbackHandler, samlCallback);
    SamlAssertionWrapper assertion = new SamlAssertionWrapper(samlCallback);
    Crypto issuerCrypto = new Merlin();
    KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
    ClassLoader loader = Loader.getClassLoader(CombinedValidatorTest.class);
    InputStream input = Merlin.loadInputStream(loader, "alice.jks");
    keyStore.load(input, "password".toCharArray());
    ((Merlin) issuerCrypto).setKeyStore(keyStore);
    assertion.signAssertion("alice", "password", issuerCrypto, false);
    response.getAssertions().add(assertion.getSaml2());
    return response;
}
Also used : Status(org.opensaml.saml.saml2.core.Status) AudienceRestrictionBean(org.apache.wss4j.common.saml.bean.AudienceRestrictionBean) InputStream(java.io.InputStream) ConditionsBean(org.apache.wss4j.common.saml.bean.ConditionsBean) SamlAssertionWrapper(org.apache.wss4j.common.saml.SamlAssertionWrapper) KeyStore(java.security.KeyStore) DateTime(org.joda.time.DateTime) Response(org.opensaml.saml.saml2.core.Response) Crypto(org.apache.wss4j.common.crypto.Crypto) SubjectConfirmationDataBean(org.apache.wss4j.common.saml.bean.SubjectConfirmationDataBean) SAMLCallback(org.apache.wss4j.common.saml.SAMLCallback) Merlin(org.apache.wss4j.common.crypto.Merlin)

Aggregations

Crypto (org.apache.wss4j.common.crypto.Crypto)266 PasswordCallbackHandler (org.apache.cxf.sts.common.PasswordCallbackHandler)148 Element (org.w3c.dom.Element)132 WrappedMessageContext (org.apache.cxf.jaxws.context.WrappedMessageContext)113 MessageImpl (org.apache.cxf.message.MessageImpl)113 StaticSTSProperties (org.apache.cxf.sts.StaticSTSProperties)111 CustomTokenPrincipal (org.apache.wss4j.common.principal.CustomTokenPrincipal)109 STSPropertiesMBean (org.apache.cxf.sts.STSPropertiesMBean)88 ArrayList (java.util.ArrayList)85 Document (org.w3c.dom.Document)83 CallbackHandler (javax.security.auth.callback.CallbackHandler)82 JAXBElement (javax.xml.bind.JAXBElement)82 RequestSecurityTokenType (org.apache.cxf.ws.security.sts.provider.model.RequestSecurityTokenType)77 RequestSecurityTokenResponseType (org.apache.cxf.ws.security.sts.provider.model.RequestSecurityTokenResponseType)74 TokenRequirements (org.apache.cxf.sts.request.TokenRequirements)67 TokenProvider (org.apache.cxf.sts.token.provider.TokenProvider)66 Principal (java.security.Principal)63 WSSecurityException (org.apache.wss4j.common.ext.WSSecurityException)55 ReceivedToken (org.apache.cxf.sts.request.ReceivedToken)54 TokenValidator (org.apache.cxf.sts.token.validator.TokenValidator)54