I am trying to connect to a soap service, that expects my request to be encrypted with standard XML encryption (according to the documentation). I am using Python requests to send requests to the endpoint but unfortunately, I do not know how to get from the raw request, to the encrypted one.
I have some examples (bellow) extracted from SoapUI, that show the request before and after the encryption process, but, unfortunately do not describe the encryption process itself. I have tried using py-wsse to encrypt the information, but it it did not match the required format. I have also attempted to use OpenSSL to encrypt the information from the request, but I do not know enough about Soap encryption to be able to structure it in the required format
What would be the steps to get from the raw request to the encrypted one
My attempt:
import uuid
import base64
import requests
from wsse import encryption
headers = {'SOAPAction': '"urn:CorporateService:activateServiceAgreement"',
'Content-Type': 'text/xml; charset=utf-8'}
url= "https://stest.bankconnect.dk/2019/04/04/services/CorporateService?wsdl"
csr_pem = "some generated CSR string without 'Begin' and 'End' tags, any string works for testing"
registration_number = '1234'
funtion_identification = '00123456789'
unique_id = uuid.uuid4().hex
activation_code = '1234123412341234'
path_to_cert = "some_cert.crt"
data = f"""<soap-env:Envelope xmlns:soap-env="http://schemas.xmlsoap.org/soap/envelope/">
<soap-env:Header>
<wsse:Security mustUnderstand="false"
xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd"
xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd"/>
<ns0:technicalAddress xmlns:ns0="http://bankconnect.dk/schema/2014">
<ns0:ipAddress>{{http://bankconnect.dk/schema/2014}}technicalAddress</ns0:ipAddress>
</ns0:technicalAddress>
<ns1:activationHeader xmlns:ns1="http://bankconnect.dk/schema/2014">
<ns1:organisationIdentification>
<ns1:mainRegistrationNumber>{registration_number}</ns1:mainRegistrationNumber>
<ns1:isoCountryCode>DK</ns1:isoCountryCode>
</ns1:organisationIdentification>
<ns1:functionIdentification>{funtion_identification}</ns1:functionIdentification>
<ns1:erpInformation>
<ns1:erpsystem>{{http://bankconnect.dk/schema/2014}}erpInformation</ns1:erpsystem>
</ns1:erpInformation>
<ns1:endToEndMessageId>{unique_id}</ns1:endToEndMessageId>
<ns1:createDateTime>2021-12-07T11:08:25</ns1:createDateTime>
</ns1:activationHeader>
</soap-env:Header>
<soap-env:Body>
<ns0:activateServiceAgreement xmlns:ns0="http://bankconnect.dk/schema/2014">
<ns0:activationAgreement>
<ns0:activationCode>{base64.b64encode(str.encode(activation_code))}</ns0:activationCode>
<ns0:certificateRequest>{csr_pem}=</ns0:certificateRequest>
</ns0:activationAgreement>
</ns0:activateServiceAgreement>
</soap-env:Body>
</soap-env:Envelope>
"""
encryptedData = encryption.encrypt(data, path_to_cert) # this outputs a different format than needed (example below)
requests.post(url,data=encryptedData.decode(), headers=headers) # the request will fail as data is not in the correct format
resulting encrypted SOAP from my attempt (formated for readability):
<soap-env:Envelope xmlns:soap-env="http://schemas.xmlsoap.org/soap/envelope/">
<soap-env:Header>
<wsse:Security xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd"
xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd">
<wsse:BinarySecurityToken EncodingType="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0#Base64Binary" ValueType="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-x509-token-profile-1.0#X509v3" wsu:Id="id-70b626c1-3e8f-4827-abc2-a3004f7f00ef">MIIEpjCCAo6gAwIBAgICE6AwDQYJKoZIhvcNAQELBQAwdTEnMCUGA1UEAxMeQkQgQmFua0Nvbm5lY3QgUHJpbWFyeSBDQSBUZXN0MRwwGgYDVQQHExNFcnJpdHNvZSBGcmVkZXJpY2lhMQwwCgYDVQQLEwNWQkYxETAPBgNVBAoTCEJhbmtkYXRhMQswCQYDVQQGEwJESzAeFw0yMDA0MTYwNzE1MzJaFw0yNTA0MTYwNzE0NDBaMHMxJTAjBgNVBAMTHEJEIEJhbmtDb25uZWN0IEJhbmtkYXRhIFRlc3QxHDAaBgNVBAcTE0Vycml0c29lIEZ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3WcVkSqUGy9T0Yhc0sejNWjT9qyuuEN0X/bH/nbf8kPDc15VJoIN6NxIfhU1NZ/2XnvX4UL+MrMwlX87WKTZnhglIuT+N6lNCK/hMRInMppzHwfcsPuXMLJc+GOhVZwHQQGBgwTGnBl3spCYNjj0yDmgeChI5c0A3/oinNj/N54Ewr6+9TnmDEk</wsse:BinarySecurityToken>
<xenc:EncryptedKey xmlns:xenc="http://www.w3.org/2001/04/xmlenc#">
<xenc:EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#rsa-oaep-mgf1p"/>
<ds:KeyInfo xmlns:ds="http://www.w3.org/2000/09/xmldsig#">
<wsse:SecurityTokenReference wsse:TokenType="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-x509-token-profile-1.0#X509v3">
<wsse:Reference ValueType="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-x509-token-profile-1.0#X509v3" URI="#id-70b626c1-3e8f-4827-abc2-a3004f7f00ef"/>
</wsse:SecurityTokenReference>
</ds:KeyInfo>
<xenc:CipherData>
<xenc:CipherValue>L8/N579SnH/XPWsVvI8nVEvW67bFoV1wEaoRM3Bvpc0fS6Ihay90aonrvc8AJdEH 73z/UoUizrLhT4KPkqr3pLJ3UO42aKf6PRXyJ1pYaN5SbZH75kdL7VpiGBNjhaFK Zzn5SpIQElIjxrvVjbyDkTKzlzLaU8qzCvR08PHEgs452uIjDKuSEIPt49uAhExI /d7fRMGgXn9PpiH4jJGO/GfMUV3V2nNL/eB9jn00Dlz7vfEqeYwBaoegzq3ZyC25 nTSYXOkGvFU7dQAmrQ4QYEqYhmr3Sey3fEzcyb0lAPhZ3JBwDI5oo5GxbVXa+xVQ IL85p8Xrw0niGvLGbspXTQ==</xenc:CipherValue>
</xenc:CipherData>
<xenc:ReferenceList>
<xenc:DataReference URI="#id-a1155f0f-8c75-4de3-9bc2-c26e23ea1873"/>
</xenc:ReferenceList>
</xenc:EncryptedKey>
</wsse:Security>
<ns0:technicalAddress xmlns:ns0="http://bankconnect.dk/schema/2014">
<ns0:ipAddress>{http://bankconnect.dk/schema/2014}technicalAddress</ns0:ipAddress>
</ns0:technicalAddress>
<ns1:activationHeader xmlns:ns1="http://bankconnect.dk/schema/2014">
<ns1:organisationIdentification>
<ns1:mainRegistrationNumber>1234</ns1:mainRegistrationNumber>
<ns1:isoCountryCode>DK</ns1:isoCountryCode>
</ns1:organisationIdentification>
<ns1:functionIdentification>00123456789</ns1:functionIdentification>
<ns1:erpInformation>
<ns1:erpsystem>{http://bankconnect.dk/schema/2014}erpInformation</ns1:erpsystem>
</ns1:erpInformation>
<ns1:endToEndMessageId>some-uuid</ns1:endToEndMessageId>
<ns1:createDateTime>2021-12-06T15:18:25</ns1:createDateTime>
</ns1:activationHeader>
</soap-env:Header>
<soap-env:Body>
<xenc:EncryptedData xmlns:xenc="http://www.w3.org/2001/04/xmlenc#"
xmlns:ns0="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd" Type="http://www.w3.org/2001/04/xmlenc#Element" ns0:Id="id-a1155f0f-8c75-4de3-9bc2-c26e23ea1873">
<xenc:EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#tripledes-cbc"/>
<xenc:CipherData>
<xenc:CipherValue>VBocX0ZNKgJ98E/1mZLQY6gJaFDIdxh+lLy38xyau3GYzT8G88XqVff7hSbBRCnt Z5zXa3sNhMl4e88GuuWnMrTe4j8QbcXuXrxVjCuZ+6TnKG1YIJ5t3L8myt+VI3+5 4FI15xQAOqATdxbtwE89xV0/n4szsxJ0nczBTK8pm/WL5rjks0Ks5o+F3wkBqwcF w+YYEE8zPD6ejlmAs+fye0gjsBAKF96RAe63kvT7gHrHKkj2GlEI5f2+bp7ebe2V U5PokQso22WBYidA8FdTBu9GGc8YD6gbTPq93GpOM1f6AV0fPd7vQCTw1d1F73HZ 9+NTZzPXqJb5RAPGSMEHlGgH3TYXOD7eBUgj0aZClGU5JsouusTmC7eiXWd5ys+b bN6LLkHvv6p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C9JVCB8Sl/6eGYum58OrP1Hp01VqgkdMcrRwiyQPPN//Yk/N5oS cb30w2AdeKPMbjihDnfRCiRSzWQfBs7Fat1MWxp80H6gqnaVq0Paf/buMpMJYa9Z hqNGFtMUJkMd+PTconOxF5a1SUWwAj0Op/J24mOd3XFy39HZnZb67rWzNATuh34p 2G+XInAmKvkxBcKR94HGfajFAE1794q2L9O6mIIiZufuKnZM0JGoQeNEdP6TETX3 G5zl7F0Xn4iZgEFPRkMREf+66+CxSwxWnmi4m8W1SHXLmmuP5pyS8wPt+q4Lg3Jd 5G54J3he3g5dyhaJVj6WD1bPgwQkN+ha4aPl+2gVNLh79u7CL/uJWwBqrKfy1a64 mJbTWRAM4aNnPIcixdWxrHYM+J7rzBTmYSANEcdhCfv534Kjd8ZH8vL/47I8C+wG VV0x6P+yJCH63UZ4tQScxMdMPKl+INmEqI1bnpq9/vXnSTkoezY2pmtAx7VpgyZm Mp+rHiEmbjMMAaLmHtw7lqUf0PtrGzUEDyXanruaY68tKLFNJyFod1Ubgo8znAfD u0/iFcpruhNtvThwCP3AmgvTWjhoDPtXobxkR54akl4TWRaZNka8LfCATouaOGsu dWDqeIQikIhwNPsv144XVpF09JLfejOhUkARj+D1OSTRAtZ/lbia7g==</xenc:CipherValue>
</xenc:CipherData>
</xenc:EncryptedData>
</soap-env:Body>
</soap-env:Envelope>
Example of expected encrypted SOAP
<soapenv:Envelope xmlns:ns="http://bankconnect.dk/schema/2014"
xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
<soapenv:Header>
<wsse:Security xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd"
xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd">
<xenc:EncryptedKey Id="EK-F3FCAC3C34D9D25B87163351066951111"
xmlns:xenc="http://www.w3.org/2001/04/xmlenc#">
<xenc:EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#rsa-oaep-mgf1p"/>
<ds:KeyInfo xmlns:ds="http://www.w3.org/2000/09/xmldsig#">
<wsse:SecurityTokenReference>
<wsse:KeyIdentifier EncodingType="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0#Base64Binary" ValueType="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-x509-token-profile-1.0#X509v3">MIIEpjCCAo6gAwIBAgICE6AwDQYJKoZIhvcNAQELBQAwdTEnMCUGA1UEAxMeQkQgQmFua0Nvbm5lY3QgUHJpbWFyeSBDQSBUZXN0MRwwGgYDVQQHExNFcnJpdHNvZSBGcmVkZXJpY2lhMQwwCgYDVQQLEwNWQkYxETAPBgNVBAoTCEJhbmtkYXRhMQswCQYDVQQGEwJESzAeFw0yMDA0MTYwNzE1MzJaFw0yNTA0MTYwNzE0NDBaMHMxJTAjBgNVBAMTHEJEIEJhbmtDb25uZWN0IEJhbmtkYXRhIFRlc3QxHDAaBgNVBAcTE0Vycml0c29lIEZyZWRlcmljaWExDDAKBgNVBAsTA1ZCRjERMA8GA1UEChMIQmFua2RhdGExCzAJBgNVBAYTAkRLMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA2uY58IUvzsFKqzfkO6AMEQ0VKSXTwy30CYNR95WO6cdbGBegkv4PEQtTDNDr95zR0LPROsarAITLt/2bg8YDRodgbSKJWoZkS2/GlVztLTQROv+ReZXCFOYR3ean5K1gaPtfobOJxUPRV8r6UyF6/BPCCE2EuVgDDplLfCAv7bhofajvtsfRAU7GclRXxvb6fPGsKQRDvwSg4NWfhLEhXUjMhsIOGd1XqtePRd63yowbB/MhFmAdXw3gz1tj12HTMZ4D7QELawfMTC+f+XQq3f1DZFdYcPdqBdRPeOEPIoma+2YvBmtTSWoRLpVmAHiEG5RLlV5iOEqGGbcXAMhtwwIDAQABo0IwQDAdBgNVHQ4EFgQUjm2b2Xh70dT09RSGxyhYhyLbfEowHwYDVR0jBBgwFoAUhDYWOyZP7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SH8ldoqxm9qlHsm80OIhYSFhXWjnOei8Snls6PtcliR3f3DYcaivJw==</xenc:CipherValue>
</xenc:CipherData>
<xenc:ReferenceList>
<xenc:DataReference URI="#ED-F3FCAC3C34D9D25B87163351066951112"/>
</xenc:ReferenceList>
</xenc:EncryptedKey>
</wsse:Security>
<ns:activationHeader>
<ns:organisationIdentification>
<ns:mainRegistrationNumber>1234</ns:mainRegistrationNumber>
<ns:isoCountryCode>DK</ns:isoCountryCode>
</ns:organisationIdentification>
<ns:functionIdentification>00123456789</ns:functionIdentification>
<ns:erpInformation>
<!--Optional:-->
<ns:erpsystem>TEST</ns:erpsystem>
<!--Optional:-->
<ns:erpversion>1</ns:erpversion>
</ns:erpInformation>
<ns:endToEndMessageId>TEST</ns:endToEndMessageId>
<ns:createDateTime>2021-09-14T14:58:33.258+02:00</ns:createDateTime>
</ns:activationHeader>
<technicalAddress xmlns="http://bankconnect.dk/schema/2014"
xmlns:ns2="http://www.w3.org/2000/09/xmldsig#"/>
</soapenv:Header>
<soapenv:Body>
<xenc:EncryptedData Id="ED-F3FCAC3C34D9D25B87163351066951112" Type="http://www.w3.org/2001/04/xmlenc#Content"
xmlns:xenc="http://www.w3.org/2001/04/xmlenc#">
<xenc:EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#aes256-cbc"/>
<ds:KeyInfo xmlns:ds="http://www.w3.org/2000/09/xmldsig#">
<wsse:SecurityTokenReference wsse11:TokenType="http://docs.oasis-open.org/wss/oasis-wss-soap-message-security-1.1#EncryptedKey"
xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd"
xmlns:wsse11="http://docs.oasis-open.org/wss/oasis-wss-wssecurity-secext-1.1.xsd">
<wsse:Reference URI="#EK-F3FCAC3C34D9D25B87163351066951111"/>
</wsse:SecurityTokenReference>
</ds:KeyInfo>
<xenc:CipherData>
<xenc:CipherValue>cTBg4srW4xEOlz2/ycn8PLbBeh7FzZflqZ/k87oD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+xFz34HFFbHDmuN5FohLUt/Z/ICmLtaSVzD6EIWLf2sLl9jk4xFfIHI3d/nmvE8tqnKh54VVDYkow1oBv5NM0M2I1U7NfkOneOj3g9yLItQM472HU7UQDY+xkwZ9N6Zj3Q/ipakXlD6/oDulPIwB/QhNKSMRHoczY32b/qjiBkvEC8eYT3XZgdsGQ1WUQo+g5AhuYNtEseu5hIYjXxp/SeLfKRIDtDiNOKlsIocAkJo9VXD77zTvt90ydUUp2sLkThZlxvn0XqrSEpowgKBOeVyH0Y1Ok4Sk/iP3IyJzg28izuo7eL5KxlTnGdr0Cr26J9C1H5+lN/9FFf+4bXAznkNUqOItMGP/jUIXr8MqnGS8us/F32qMjCnNJmYUvKNykY5U+Jjyiz3NUo5GZMQpx+kNEgr/WDbg54rHJmmyGVDD9XyvfIg1ZEMaJHHb/egn/bhIUjEAYj8ByYVruovKtUq6CLKFSvKrRg/2Zvr8J1vAsPrVgTOUFSuyVeTaH6xz+nc0fr+9kp6swuMp/pKs3xVWG0d/SqdcSyq9u</xenc:CipherValue>
</xenc:CipherData>
</xenc:EncryptedData>
</soapenv:Body>
</soapenv:Envelope>
Although I assume I can get the Cipher data by encrypting my initial body with openSSL, I do not know how to build the security header, and how to get the parameters (such as Id, URI, etc). As I mentioned previously, the examples were generated with SoapUi. Is there a way to do the same in Python?
yes, I would recommend just using a 3rd party github lib and call WSE Encrypt, or just use this function specific code. It will encrypt it with X509 cert.
"""Functions for WS-Security (WSSE) encryption and decryption.
Heavily based on test examples in https://github.com/mehcode/python-xmlsec as
well as the xmlsec documentation at https://www.aleksey.com/xmlsec/. Some
functions from https://github.com/mvantellingen/py-soap-wsse.
Reading the xmldsig, xmlenc, and ws-security standards documents, though
admittedly painful, will likely assist in understanding the code in this
module.
"""
import base64
from lxml import etree
from OpenSSL import crypto
import xmlsec
from .constants import BASE64B, X509TOKEN, DS_NS, ENC_NS, SOAP_NS, WSSE_NS
from .xml import ensure_id, ns
def encrypt(envelope, certfile):
"""Encrypt body contents of given SOAP envelope using given X509 cert.
Currently only encrypts the first child node of the body, so doesn't really
support a body with multiple child nodes (the later ones won't be
encrypted), and doesn't support encryption of multiple nodes.
Expects to encrypt an incoming document something like this (xmlns
attributes omitted for readability):
<soap:Envelope>
<soap:Header>
<wsse:Security mustUnderstand="true">
<wsu:Timestamp>
<wsu:Created>2015-06-25T21:53:25.246276+00:00</wsu:Created>
<wsu:Expires>2015-06-25T21:58:25.246276+00:00</wsu:Expires>
</wsu:Timestamp>
</wsse:Security>
</soap:Header>
<soap:Body>
...
</soap:Body>
</soap:Envelope>
Encryption results in an XML structure something like this (note the added
wsse:BinarySecurityToken and xenc:EncryptedKey nodes in the wsse:Security
header, and that the contents of the soap:Body have now been replaced by a
wsse:EncryptedData node):
<soap:Envelope>
<soap:Header>
<wsse:Security mustUnderstand="true">
<wsse:BinarySecurityToken
wsu:Id="id-31e55a42-adef-4312-aa02-6da738177b25"
EncodingType="...-wss-soap-message-security-1.0#Base64Binary"
ValueType=".../oasis-200401-wss-x509-token-profile-1.0#X509v3">
MIIGRTCC...7RaVeFVB/w==
</wsse:BinarySecurityToken>
<xenc:EncryptedKey>
<xenc:EncryptionMethod
Algorithm="http://www.w3.org/2001/04/xmlenc#rsa-oaep-mgf1p"/>
<ds:KeyInfo>
<wsse:SecurityTokenReference
wsse:TokenType="...wss-x509-token-profile-1.0#X509v3">
<wsse:Reference
ValueType="...-wss-x509-token-profile-1.0#X509v3"
URI="#id-31e55a42-adef-4312-aa02-6da738177b25"
/>
</wsse:SecurityTokenReference>
</ds:KeyInfo>
<xenc:CipherData>
<xenc:CipherValue>0m23u5UVh...YLcEcmgzng==</xenc:CipherValue>
</xenc:CipherData>
<xenc:ReferenceList>
<xenc:DataReference
URI="#id-094305bf-f73e-4940-88d9-00688bc78718"/>
</xenc:ReferenceList>
</xenc:EncryptedKey>
<wsu:Timestamp wsu:Id="id-d449ec14-f31c-4174-b51c-2a56843eeda5">
<wsu:Created>2015-06-25T22:26:57.618091+00:00</wsu:Created>
<wsu:Expires>2015-06-25T22:31:57.618091+00:00</wsu:Expires>
</wsu:Timestamp>
</wsse:Security>
</soap:Header>
<soap:Body wsu:Id="id-73bc3f79-1597-4e35-91d5-354fc6197858">
<xenc:EncryptedData
Type="http://www.w3.org/2001/04/xmlenc#Element"
wsu:Id="id-094305bf-f73e-4940-88d9-00688bc78718">
<xenc:EncryptionMethod
Algorithm="http://www.w3.org/2001/04/xmlenc#tripledes-cbc"/>
<xenc:CipherData>
<xenc:CipherValue>rSJC8m...js2RQfw/5</xenc:CipherValue>
</xenc:CipherData>
</xenc:EncryptedData>
</soap:Body>
</soap:Envelope>
(In practice, we'll generally be encrypting an already-signed document, so
the Signature node would also be present in the header, but we aren't
encrypting it and for simplicity it's omitted in this example.)
"""
doc = etree.fromstring(envelope)
header = doc.find(ns(SOAP_NS, 'Header'))
security = header.find(ns(WSSE_NS, 'Security'))
# Create a keys manager and load the cert into it.
manager = xmlsec.KeysManager()
key = xmlsec.Key.from_file(certfile, xmlsec.KeyFormat.CERT_PEM, None)
manager.add_key(key)
# Encrypt first child node of the soap:Body.
body = doc.find(ns(SOAP_NS, 'Body'))
target = body[0]
# Create the EncryptedData node we will replace the target node with,
# and make sure it has the contents XMLSec expects (a CipherValue node,
# a KeyInfo node, and an EncryptedKey node within the KeyInfo which
# itself has a CipherValue).
enc_data = xmlsec.template.encrypted_data_create(
doc,
xmlsec.Transform.DES3,
type=xmlsec.EncryptionType.ELEMENT,
ns='xenc',
)
xmlsec.template.encrypted_data_ensure_cipher_value(enc_data)
key_info = xmlsec.template.encrypted_data_ensure_key_info(
enc_data, ns='dsig')
enc_key = xmlsec.template.add_encrypted_key(
key_info, xmlsec.Transform.RSA_OAEP)
xmlsec.template.encrypted_data_ensure_cipher_value(enc_key)
enc_ctx = xmlsec.EncryptionContext(manager)
# Generate a per-session DES key (will be encrypted using the cert).
enc_ctx.key = xmlsec.Key.generate(
xmlsec.KeyData.DES, 192, xmlsec.KeyDataType.SESSION)
# Ask XMLSec to actually do the encryption.
enc_data = enc_ctx.encrypt_xml(enc_data, target)
# XMLSec inserts the EncryptedKey node directly within EncryptedData,
# but WSSE wants it in the Security header instead, and referencing the
# EncryptedData as well as the actual cert in a BinarySecurityToken.
# Move the EncryptedKey node up into the wsse:Security header.
security.insert(0, enc_key)
# Create a wsse:BinarySecurityToken node containing the cert and add it
# to the Security header.
cert_bst = create_binary_security_token(certfile)
security.insert(0, cert_bst)
# Create a ds:KeyInfo node referencing the BinarySecurityToken we just
# created, and insert it into the EncryptedKey node.
enc_key.insert(1, create_key_info_bst(cert_bst))
# Add a DataReference from the EncryptedKey node to the EncryptedData.
add_data_reference(enc_key, enc_data)
# Remove the now-empty KeyInfo node from EncryptedData (it used to
# contain EncryptedKey, but we moved that up into the Security header).
enc_data.remove(key_info)
return etree.tostring(doc)
def decrypt(envelope, keyfile):
"""Decrypt all EncryptedData, using EncryptedKey from Security header.
EncryptedKey should be a session key encrypted for given ``keyfile``.
Expects XML similar to the example in the ``encrypt`` docstring.
"""
# Create a key manager and load our key into it.
manager = xmlsec.KeysManager()
key = xmlsec.Key.from_file(keyfile, xmlsec.KeyFormat.PEM)
manager.add_key(key)
doc = etree.fromstring(envelope)
header = doc.find(ns(SOAP_NS, 'Header'))
security = header.find(ns(WSSE_NS, 'Security'))
enc_key = security.find(ns(ENC_NS, 'EncryptedKey'))
# Find each referenced encrypted block (each DataReference in the
# ReferenceList of the EncryptedKey) and decrypt it.
ref_list = enc_key.find(ns(ENC_NS, 'ReferenceList'))
for ref in ref_list:
# Find the EncryptedData node referenced by this DataReference.
ref_uri = ref.get('URI')
referenced_id = ref_uri[1:]
enc_data = doc.xpath(
"//enc:EncryptedData[@Id='%s']" % referenced_id,
namespaces={'enc': ENC_NS},
)[0]
# XMLSec doesn't understand WSSE, therefore it doesn't understand
# SecurityTokenReference. It expects to find EncryptedKey within the
# KeyInfo of the EncryptedData. So we get rid of the
# SecurityTokenReference and replace it with the EncryptedKey before
# trying to decrypt.
key_info = enc_data.find(ns(DS_NS, 'KeyInfo'))
key_info.remove(key_info[0])
key_info.append(enc_key)
# When XMLSec decrypts, it automatically replaces the EncryptedData
# node with the decrypted contents.
ctx = xmlsec.EncryptionContext(manager)
ctx.decrypt(enc_data)
return etree.tostring(doc)
def add_data_reference(enc_key, enc_data):
"""Add DataReference to ``enc_data`` in ReferenceList of ``enc_key``.
``enc_data`` should be an EncryptedData node; ``enc_key`` an EncryptedKey
node.
Add a wsu:Id attribute to the EncryptedData if it doesn't already have one,
so the EncryptedKey's URI attribute can reference it.
(See the example XML in the ``encrypt()`` docstring.)
Return created DataReference node.
"""
# Ensure the target EncryptedData has a wsu:Id.
data_id = ensure_id(enc_data)
# Ensure the EncryptedKey has a ReferenceList.
ref_list = ensure_reference_list(enc_key)
# Create the DataReference, with URI attribute referencing the target
# node's id, add it to the ReferenceList, and return it.
data_ref = etree.SubElement(ref_list, ns(ENC_NS, 'DataReference'))
data_ref.set('URI', '#' + data_id)
return data_ref
def ensure_reference_list(encrypted_key):
"""Ensure that given EncryptedKey node has a ReferenceList node.
Return the found or created ReferenceList node.
"""
ref_list = encrypted_key.find(ns(ENC_NS, 'ReferenceList'))
if ref_list is None:
ref_list = etree.SubElement(encrypted_key, ns(ENC_NS, 'ReferenceList'))
return ref_list
def create_key_info_bst(security_token):
"""Create and return a KeyInfo node referencing given BinarySecurityToken.
(See the example XML in the ``encrypt()`` docstring.)
Modified from https://github.com/mvantellingen/py-soap-wsse.
"""
# Create the KeyInfo node.
key_info = etree.Element(ns(DS_NS, 'KeyInfo'), nsmap={'ds': DS_NS})
# Create a wsse:SecurityTokenReference node within KeyInfo.
sec_token_ref = etree.SubElement(
key_info, ns(WSSE_NS, 'SecurityTokenReference'))
sec_token_ref.set(
ns(WSSE_NS, 'TokenType'), security_token.get('ValueType'))
# Add a Reference to the BinarySecurityToken in the SecurityTokenReference.
bst_id = ensure_id(security_token)
reference = etree.SubElement(sec_token_ref, ns(WSSE_NS, 'Reference'))
reference.set('ValueType', security_token.get('ValueType'))
reference.set('URI', '#%s' % bst_id)
return key_info
def create_binary_security_token(certfile):
"""Create a BinarySecurityToken node containing the x509 certificate.
Modified from https://github.com/mvantellingen/py-soap-wsse.
"""
# Create the BinarySecurityToken node with appropriate attributes.
node = etree.Element(ns(WSSE_NS, 'BinarySecurityToken'))
node.set('EncodingType', BASE64B)
node.set('ValueType', X509TOKEN)
# Set the node contents.
with open(certfile) as fh:
cert = crypto.load_certificate(crypto.FILETYPE_PEM, fh.read())
node.text = base64.b64encode(
crypto.dump_certificate(crypto.FILETYPE_ASN1, cert))
return node
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With