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);
}
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;
}
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);
}
}
}
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()));
}
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;
}
Aggregations