Gathering detailed insights and metrics for xml-crypto
Gathering detailed insights and metrics for xml-crypto
Gathering detailed insights and metrics for xml-crypto
Gathering detailed insights and metrics for xml-crypto
@types/xml-crypto
TypeScript definitions for xml-crypto
@redocly/xml-crypto
Xml digital signature and encryption library for Node.js
xml_crypto_payme
Custom xml-crypto-payme
web-xml-crypto
Xml digital signature and encryption library for web js. Based on the https://github.com/yaronn/xml-crypto (Yaron Naveh <yaronn01@gmail.com> (http://webservices20.blogspot.com/))
npm install xml-crypto
99.2
Supply Chain
98.7
Quality
83.8
Maintenance
100
Vulnerability
100
License
Module System
Min. Node Version
Typescript Support
Node Version
NPM Version
199 Stars
426 Commits
173 Forks
18 Watching
13 Branches
56 Contributors
Updated on 25 Nov 2024
TypeScript (89.53%)
C# (7.32%)
Java (1.99%)
JavaScript (1.16%)
Cumulative downloads
Total Downloads
Last day
-26.1%
178,944
Compared to previous day
Last week
-8.5%
1,151,416
Compared to previous week
Last month
5.1%
5,117,943
Compared to previous month
Last year
8.4%
52,211,623
Compared to previous year
3
23
An xml digital signature library for node. Xml encryption is coming soon. Written in pure javascript!
For more information visit my blog or my twitter.
Install with npm:
1npm install xml-crypto
A pre requisite it to have openssl installed and its /bin to be on the system path. I used version 1.0.1c but it should work on older versions too.
HMAC-SHA1 is also available but it is disabled by default
to enable HMAC-SHA1, call enableHMAC()
on your instance of SignedXml
.
This will enable HMAC and disable digital signature algorithms. Due to key confusion issues, it is risky to have both HMAC-based and public key digital signature algorithms enabled at same time.
You are able to extend xml-crypto with custom algorithms.
When signing a xml document you can pass the following options to the SignedXml
constructor to customize the signature process:
privateKey
- [required] a Buffer
or pem encoded String
containing your private keypublicCert
- [optional] a Buffer
or pem encoded String
containing your public keysignatureAlgorithm
- [required] one of the supported signature algorithms. Ex: sign.signatureAlgorithm = "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256"
canonicalizationAlgorithm
- [required] one of the supported canonicalization algorithms. Ex: sign.canonicalizationAlgorithm = "http://www.w3.org/2001/10/xml-exc-c14n#WithComments"
Use this code:
1var SignedXml = require("xml-crypto").SignedXml, 2 fs = require("fs"); 3 4var xml = "<library>" + "<book>" + "<name>Harry Potter</name>" + "</book>" + "</library>"; 5 6var sig = new SignedXml({ privateKey: fs.readFileSync("client.pem") }); 7sig.addReference({ 8 xpath: "//*[local-name(.)='book']", 9 digestAlgorithm: "http://www.w3.org/2000/09/xmldsig#sha1", 10 transforms: ["http://www.w3.org/2001/10/xml-exc-c14n#"], 11}); 12sig.canonicalizationAlgorithm = "http://www.w3.org/2001/10/xml-exc-c14n#"; 13sig.signatureAlgorithm = "http://www.w3.org/2000/09/xmldsig#rsa-sha1"; 14sig.computeSignature(xml); 15fs.writeFileSync("signed.xml", sig.getSignedXml());
The result will be:
1<library> 2 <book Id="_0"> 3 <name>Harry Potter</name> 4 </book> 5 <Signature xmlns="http://www.w3.org/2000/09/xmldsig#"> 6 <SignedInfo> 7 <CanonicalizationMethod Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#" /> 8 <SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1" /> 9 <Reference URI="#_0"> 10 <Transforms> 11 <Transform Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#" /> 12 </Transforms> 13 <DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1" /> 14 <DigestValue>cdiS43aFDQMnb3X8yaIUej3+z9Q=</DigestValue> 15 </Reference> 16 </SignedInfo> 17 <SignatureValue>vhWzpQyIYuncHUZV9W...[long base64 removed]...</SignatureValue> 18 </Signature> 19</library>
Note:
If you set the publicCert
and the getKeyInfoContent
properties, a <KeyInfo></KeyInfo>
element with the public certificate will be generated in the signature:
1<Signature xmlns="http://www.w3.org/2000/09/xmldsig#"> 2 <SignedInfo> 3 ...[signature info removed]... 4 </SignedInfo> 5 <SignatureValue>vhWzpQyIYuncHUZV9W...[long base64 removed]...</SignatureValue> 6 <KeyInfo> 7 <X509Data> 8 <X509Certificate>MIIGYjCCBJagACCBN...[long base64 removed]...</X509Certificate> 9 </X509Data> 10 </KeyInfo> 11</Signature>
For getKeyInfoContent
, a default implementation SignedXml.getKeyInfoContent
is available.
To customize this see customizing algorithms for an example.
When verifying a xml document you can pass the following options to the SignedXml
constructor to customize the verify process:
publicCert
- [optional] your certificate as a string, a string of multiple certs in PEM format, or a BufferprivateKey
- [optional] your private key as a string or a Buffer - used for verifying symmetrical signatures (HMAC)The certificate that will be used to check the signature will first be determined by calling this.getCertFromKeyInfo()
, which function you can customize as you see fit. If that returns null
, then publicCert
is used. If that is null
, then privateKey
is used (for symmetrical signing applications).
Example:
1new SignedXml({ 2 publicCert: client_public_pem, 3 getCertFromKeyInfo: () => null, 4});
You can use any dom parser you want in your code (or none, depending on your usage). This sample uses xmldom, so you should install it first:
1npm install @xmldom/xmldom
Example:
1var select = require("xml-crypto").xpath, 2 dom = require("@xmldom/xmldom").DOMParser, 3 SignedXml = require("xml-crypto").SignedXml, 4 fs = require("fs"); 5 6var xml = fs.readFileSync("signed.xml").toString(); 7var doc = new dom().parseFromString(xml); 8 9var signature = select( 10 doc, 11 "//*[local-name(.)='Signature' and namespace-uri(.)='http://www.w3.org/2000/09/xmldsig#']", 12)[0]; 13var sig = new SignedXml({ publicCert: fs.readFileSync("client_public.pem") }); 14sig.loadSignature(signature); 15try { 16 var res = sig.checkSignature(xml); 17} catch (ex) { 18 console.log(ex); 19}
In order to protect from some attacks we must check the content we want to use is the one that has been signed:
1// Roll your own 2const elem = xpath.select("/xpath_to_interesting_element", doc); 3const uri = sig.getReferences()[0].uri; // might not be 0; it depends on the document 4const id = uri[0] === "#" ? uri.substring(1) : uri; 5if ( 6 elem.getAttribute("ID") != id && 7 elem.getAttribute("Id") != id && 8 elem.getAttribute("id") != id 9) { 10 throw new Error("The interesting element was not the one verified by the signature"); 11} 12 13// Get the validated element directly from a reference 14const elem = sig.references[0].getValidatedElement(); // might not be 0; it depends on the document 15const matchingReference = xpath.select1("/xpath_to_interesting_element", elem); 16if (!isDomNode.isNodeLike(matchingReference)) { 17 throw new Error("The interesting element was not the one verified by the signature"); 18} 19 20// Use the built-in method 21const elem = xpath.select1("/xpath_to_interesting_element", doc); 22try { 23 const matchingReference = sig.validateElementAgainstReferences(elem, doc); 24} catch { 25 throw new Error("The interesting element was not the one verified by the signature"); 26} 27 28// Use the built-in method with a an xpath expression 29try { 30 const matchingReference = sig.validateReferenceWithXPath("/xpath_to_interesting_element", doc); 31} catch { 32 throw new Error("The interesting element was not the one verified by the signature"); 33}
Note:
The xml-crypto api requires you to supply it separately the xml signature ("<Signature>...</Signature>", in loadSignature) and the signed xml (in checkSignature). The signed xml may or may not contain the signature in it, but you are still required to supply the signature separately.
If you fail to verify signed XML, then one possible cause is that there are some hidden implicit transforms(#).
(#) Normalizing XML document to be verified. i.e. remove extra space within a tag, sorting attributes, importing namespace declared in ancestor nodes, etc.
The reason for these implicit transform might come from complex xml signature specification, which makes XML developers confused and then leads to incorrect implementation for signing XML document.
If you keep failing verification, it is worth trying to guess such a hidden transform and specify it to the option as below:
1var options = { 2 implicitTransforms: ["http://www.w3.org/TR/2001/REC-xml-c14n-20010315"], 3 publicCert: fs.readFileSync("client_public.pem"), 4}; 5var sig = new SignedXml(options); 6sig.loadSignature(signature); 7var res = sig.checkSignature(xml);
You might find it difficult to guess such transforms, but there are typical transforms you can try.
See xpath.js for usage. Note that this is actually using another library as the underlying implementation.
The SignedXml
constructor provides an abstraction for sign and verify xml documents. The object is constructed using new SignedXml(options?: SignedXmlOptions)
where the possible options are:
idMode
- default null
- if the value of wssecurity
is passed it will create/validate id's with the ws-security namespace.idAttribute
- string - default Id
or ID
or id
- the name of the attribute that contains the id of the elementprivateKey
- string or Buffer - default null
- the private key to use for signingpublicCert
- string or Buffer - default null
- the public certificate to use for verifyingsignatureAlgorithm
- string - the signature algorithm to usecanonicalizationAlgorithm
- string - default undefined
- the canonicalization algorithm to useinclusiveNamespacesPrefixList
- string - default null
- a list of namespace prefixes to include during canonicalizationimplicitTransforms
- string[] - default []
- a list of implicit transforms to use during verificationkeyInfoAttributes
- object - default {}
- a hash of attributes and values attrName: value
to add to the KeyInfo nodegetKeyInfoContent
- function - default noop
- a function that returns the content of the KeyInfo nodegetCertFromKeyInfo
- function - default SignedXml.getCertFromKeyInfo
- a function that returns the certificate from the <KeyInfo />
nodeA SignedXml
object provides the following methods:
To sign xml documents:
addReference(xpath, transforms, digestAlgorithm)
- adds a reference to a xml element where:
xpath
- a string containing a XPath expression referencing a xml elementtransforms
- an array of transform algorithms, the referenced element will be transformed for each value in the arraydigestAlgorithm
- one of the supported hashing algorithmscomputeSignature(xml, [options])
- compute the signature of the given xml where:
xml
- a string containing a xml documentoptions
- an object with the following properties:
prefix
- adds this value as a prefix for the generated signature tagsattrs
- a hash of attributes and values attrName: value
to add to the signature root nodelocation
- customize the location of the signature, pass an object with a reference
key which should contain a XPath expression to a reference node, an action
key which should contain one of the following values: append
, prepend
, before
, after
existingPrefixes
- A hash of prefixes and namespaces prefix: namespace
that shouldn't be in the signature because they already exist in the xmlgetSignedXml()
- returns the original xml document with the signature in it, must be called only after computeSignature
getSignatureXml()
- returns just the signature part, must be called only after computeSignature
getOriginalXmlWithIds()
- returns the original xml with Id attributes added on relevant elements (required for validation), must be called only after computeSignature
To verify xml documents:
loadSignature(signatureXml)
- loads the signature where:
signatureXml
- a string or node object (like an xmldom node) containing the xml representation of the signaturecheckSignature(xml)
- validates the given xml document and returns true
if the validation was successfulThe following sample shows how to sign a message using custom algorithms.
First import some modules:
1var SignedXml = require("xml-crypto").SignedXml, 2 fs = require("fs");
Now define the extension point you want to implement. You can choose one or more.
To determine the inclusion and contents of a <KeyInfo />
element, the function
this.getKeyInfoContent()
is called. There is a default implementation of this. If you wish to change
this implementation, provide your own function assigned to the property this.getKeyInfoContent
. If you prefer to use the default implementation, assign SignedXml.getKeyInfoContent
to this.getKeyInfoContent
If
there are no attributes and no contents to the <KeyInfo />
element, it won't be included in the
generated XML.
To specify custom attributes on <KeyInfo />
, add the properties to the .keyInfoAttributes
property.
A custom hash algorithm is used to calculate digests. Implement it if you want a hash other than the built-in methods.
1function MyDigest() { 2 this.getHash = function (xml) { 3 return "the base64 hash representation of the given xml string"; 4 }; 5 6 this.getAlgorithmName = function () { 7 return "http://myDigestAlgorithm"; 8 }; 9}
A custom signing algorithm.
1function MySignatureAlgorithm() { 2 /*sign the given SignedInfo using the key. return base64 signature value*/ 3 this.getSignature = function (signedInfo, privateKey) { 4 return "signature of signedInfo as base64..."; 5 }; 6 7 this.getAlgorithmName = function () { 8 return "http://mySigningAlgorithm"; 9 }; 10}
Custom transformation algorithm.
1function MyTransformation() { 2 /*given a node (from the xmldom module) return its canonical representation (as string)*/ 3 this.process = function (node) { 4 //you should apply your transformation before returning 5 return node.toString(); 6 }; 7 8 this.getAlgorithmName = function () { 9 return "http://myTransformation"; 10 }; 11}
Custom canonicalization is actually the same as custom transformation. It is applied on the SignedInfo rather than on references.
1function MyCanonicalization() { 2 /*given a node (from the xmldom module) return its canonical representation (as string)*/ 3 this.process = function (node) { 4 //you should apply your transformation before returning 5 return "< x/>"; 6 }; 7 8 this.getAlgorithmName = function () { 9 return "http://myCanonicalization"; 10 }; 11}
Now you need to register the new algorithms:
1/*register all the custom algorithms*/ 2 3signedXml.CanonicalizationAlgorithms["http://MyTransformation"] = MyTransformation; 4signedXml.CanonicalizationAlgorithms["http://MyCanonicalization"] = MyCanonicalization; 5signedXml.HashAlgorithms["http://myDigestAlgorithm"] = MyDigest; 6signedXml.SignatureAlgorithms["http://mySigningAlgorithm"] = MySignatureAlgorithm;
Now do the signing. Note how we configure the signature to use the above algorithms:
1function signXml(xml, xpath, key, dest) { 2 var options = { 3 publicCert: fs.readFileSync("my_public_cert.pem", "latin1"), 4 privateKey: fs.readFileSync(key), 5 /*configure the signature object to use the custom algorithms*/ 6 signatureAlgorithm: "http://mySignatureAlgorithm", 7 canonicalizationAlgorithm: "http://MyCanonicalization", 8 }; 9 10 var sig = new SignedXml(options); 11 12 sig.addReference({ 13 xpath: "//*[local-name(.)='x']", 14 transforms: ["http://MyTransformation"], 15 digestAlgorithm: "http://myDigestAlgorithm", 16 }); 17 18 sig.addReference({ 19 xpath, 20 transforms: ["http://MyTransformation"], 21 digestAlgorithm: "http://myDigestAlgorithm", 22 }); 23 sig.canonicalizationAlgorithm = "http://www.w3.org/2001/10/xml-exc-c14n#"; 24 sig.signatureAlgorithm = "http://www.w3.org/2000/09/xmldsig#rsa-sha1"; 25 sig.computeSignature(xml); 26 fs.writeFileSync(dest, sig.getSignedXml()); 27} 28 29var xml = "<library>" + "<book>" + "<name>Harry Potter</name>" + "</book>"; 30("</library>"); 31 32signXml(xml, "//*[local-name(.)='book']", "client.pem", "result.xml");
You can always look at the actual code as a sample.
If the private key is not stored locally, and you wish to use a signing server or Hardware Security Module (HSM) to sign documents, you can create a custom signing algorithm that uses an asynchronous callback.
1function AsyncSignatureAlgorithm() { 2 this.getSignature = function (signedInfo, privateKey, callback) { 3 var signer = crypto.createSign("RSA-SHA1"); 4 signer.update(signedInfo); 5 var res = signer.sign(privateKey, "base64"); 6 //Do some asynchronous things here 7 callback(null, res); 8 }; 9 this.getAlgorithmName = function () { 10 return "http://www.w3.org/2000/09/xmldsig#rsa-sha1"; 11 }; 12} 13 14var sig = new SignedXml({ signatureAlgorithm: "http://asyncSignatureAlgorithm" }); 15sig.SignatureAlgorithms["http://asyncSignatureAlgorithm"] = AsyncSignatureAlgorithm; 16sig.signatureAlgorithm = "http://asyncSignatureAlgorithm"; 17sig.canonicalizationAlgorithm = "http://www.w3.org/2001/10/xml-exc-c14n#"; 18sig.computeSignature(xml, opts, function (err) { 19 var signedResponse = sig.getSignedXml(); 20});
The function sig.checkSignature
may also use a callback if asynchronous verification is needed.
Xml-Crypto internally relies on node's crypto module. This means pem encoded certificates are supported. So to sign an xml use key.pem that looks like this (only the beginning of the key content is shown):
1-----BEGIN PRIVATE KEY----- 2MIICdwIBADANBgkqhkiG9w0... 3-----END PRIVATE KEY-----
And for verification use key_public.pem:
1-----BEGIN CERTIFICATE----- 2MIIBxDCCAW6gAwIBAgIQxUSX... 3-----END CERTIFICATE-----
If you have .pfx certificates you can convert them to .pem using openssl:
1openssl pkcs12 -in c:\certs\yourcert.pfx -out c:\certs\cag.pem
Then you could use the result as is for the purpose of signing. For the purpose of validation open the resulting .pem with a text editor and copy from -----BEGIN CERTIFICATE----- to -----END CERTIFICATE----- (including) to a new text file and save it as .pem.
Use the prefix
option when calling computeSignature
to add a prefix to the signature.
1var SignedXml = require("xml-crypto").SignedXml, 2 fs = require("fs"); 3 4var xml = "<library>" + "<book>" + "<name>Harry Potter</name>" + "</book>" + "</library>"; 5 6var sig = new SignedXml({ privateKey: fs.readFileSync("client.pem") }); 7sig.addReference({ 8 xpath: "//*[local-name(.)='book']", 9 digestAlgorithm: "http://www.w3.org/2000/09/xmldsig#sha1", 10 transforms: ["http://www.w3.org/2001/10/xml-exc-c14n#"], 11}); 12sig.canonicalizationAlgorithm = "http://www.w3.org/2001/10/xml-exc-c14n#"; 13sig.signatureAlgorithm = "http://www.w3.org/2000/09/xmldsig#rsa-sha1"; 14sig.computeSignature(xml, { 15 prefix: "ds", 16});
Use the location
option when calling computeSignature
to move the signature around.
Set action
to one of the following:
referenceNode
property)referenceNode
property)1var SignedXml = require("xml-crypto").SignedXml, 2 fs = require("fs"); 3 4var xml = "<library>" + "<book>" + "<name>Harry Potter</name>" + "</book>" + "</library>"; 5 6var sig = new SignedXml({ privateKey: fs.readFileSync("client.pem") }); 7sig.addReference({ 8 xpath: "//*[local-name(.)='book']", 9 digestAlgorithm: "http://www.w3.org/2000/09/xmldsig#sha1", 10 transforms: ["http://www.w3.org/2001/10/xml-exc-c14n#"], 11}); 12sig.canonicalizationAlgorithm = "http://www.w3.org/2001/10/xml-exc-c14n#"; 13sig.signatureAlgorithm = "http://www.w3.org/2000/09/xmldsig#rsa-sha1"; 14sig.computeSignature(xml, { 15 location: { reference: "//*[local-name(.)='book']", action: "after" }, //This will place the signature after the book element 16});
The testing framework we use is Mocha with Chai as the assertion framework.
To run tests use:
1npm test
This project is licensed under the MIT License. See the LICENSE file for more info.
The latest stable version of the package.
Stable Version
1
10/10
Summary
xml-crypto vulnerable to XML signature verification bypass due improper verification of signature/signature spoofing
Affected Versions
>= 4.0.0, < 6.0.0
Patched Versions
6.0.0
1
0/10
Summary
xml-crypto's HMAC-SHA1 signatures can bypass validation via key confusion
Affected Versions
<= 1.5.3
Patched Versions
2.0.0
No security vulnerabilities found.