Skip to content

Latest commit

 

History

461 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

xml-crypto

Build Status code style: prettier codecov DeepScan grade

NPM

Sponsors

workos workos

Upgrading

Canonicalization output

Inclusive canonicalization (http://www.w3.org/TR/2001/REC-xml-c14n-20010315 and its #WithComments variant) renders namespace declarations as the C14N specification requires, including when:

  • a prefixed element in the signed content declares a default namespace, as in <p:item xmlns="urn:x">
  • the signed element inherits a default namespace and declares a prefixed namespace of its own
  • the signed element is prefixed, inherits a default namespace, and contains an element that clears it with xmlns=""
  • the signed element redeclares a prefix that an ancestor binds, after declaring another namespace

Exclusive canonicalization (http://www.w3.org/2001/10/xml-exc-c14n# and its #WithComments variant) renders the last case the same way when the redeclared prefix is listed in the InclusiveNamespaces PrefixList.

Comments in referenced content

A Reference whose URI is empty or # followed by an ID, such as #item, removes comments from the referenced content before its transforms run, as same-document references require.

  • Comments in that content are not signed, even with a #WithComments transform: adding, removing or changing one does not invalidate the signature. Read signed content from getSignedReferences(), which does not contain them.
  • A custom transform in such a reference does not receive comment nodes.
  • A #WithComments CanonicalizationMethod signs the comments inside SignedInfo.

Transforms that end in a DOM node

When the last transform of a Reference returns a DOM Node, it is converted to octets with inclusive canonicalization, as the reference processing model requires. A SignedInfo canonicalization algorithm that returns a Node is converted the same way, and getCanonXml() returns canonical XML for such transform lists, for example <y></y>.

Transforms that follow a canonicalization

When a transform returns a string and another transform follows it in the same Reference, the string is parsed into a new document and the next transform is applied to that, as the reference processing model requires. Every built-in canonicalization algorithm returns a string, so:

  • enveloped-signature after a canonicalization removes the Signature, including one inside the referenced element.
  • The result of a #WithComments canonicalization followed by enveloped-signature is canonicalized without comments.
  • Exclusive canonicalization after inclusive canonicalization omits inherited namespace declarations that the referenced element does not use.
  • A custom transform after a canonicalization receives the parsed document.
  • A transform throws when the string returned by the transform before it is not well-formed XML.

Copies of an enveloped signature

The enveloped-signature transform removes only the Signature element being verified, as XMLDSig requires.

  • checkSignature() finds that element by its SignatureValue, and throws when the document contains more than one Signature element with that value.
  • getCanonXml() finds the loaded signature in the node's document the same way, and removes nothing when the signature is not there.

Deprecated ahead of 7.0

These exports are deprecated and will be removed in 7.0:

Deprecated Instead
findAttr, findChildren, findChilds, isDescendantOf use a DOM API, or xpath
encodeSpecialCharactersInAttribute, encodeSpecialCharactersInText these are the escaping step of C14nCanonicalization and ExclusiveCanonicalization, so use those; a custom canonicalizer must apply C14N escaping itself
isArrayHasLength Array.isArray(x) && x.length > 0
validateDigestValue decode both from base64, then compare with a.length === b.length && crypto.timingSafeEqual(a, b)timingSafeEqual alone throws on a length mismatch instead of returning false. Never ===
BASE64_REGEX, EXTRACT_X509_CERTS, PEM_FORMAT_REGEX no replacement; these are internal parsing details

Calling one prints a DeprecationWarning naming its replacement. The three regexes cannot warn — util.deprecate needs a call to intercept — so TypeScript users see the @deprecated tag and JavaScript users get no signal until the names go away.

derToPem, pemToDer, normalizePem and findAncestorNs are not deprecated and stay exported.

getReferences() and references are deprecated. Do not use them to obtain signed XML; use getSignedReferences() instead, as shown in Verifying Xml documents.

Supported Algorithms

Canonicalization and Transformation Algorithms

Hashing Algorithms

Signature Algorithms

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.

Signing Xml documents

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 key
  • publicCert - [optional] a Buffer or pem encoded String containing your public key
  • signatureAlgorithm - [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:

const { SignedXml } = require("xml-crypto");
const fs = require("fs");

const xml = "<library><book><name>Harry Potter</name></book></library>";

const sig = new SignedXml({
  privateKey: fs.readFileSync("client.pem"),
  canonicalizationAlgorithm: "http://www.w3.org/2001/10/xml-exc-c14n#",
  signatureAlgorithm: "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256",
});
sig.addReference({
  xpath: "//*[local-name(.)='book']",
  digestAlgorithm: "http://www.w3.org/2001/04/xmlenc#sha256",
  transforms: ["http://www.w3.org/2001/10/xml-exc-c14n#"],
});
sig.computeSignature(xml);
fs.writeFileSync("signed.xml", sig.getSignedXml());

The result will be:

<library>
  <book Id="_0">
    <name>Harry Potter</name>
  </book>
  <Signature xmlns="http://www.w3.org/2000/09/xmldsig#">
    <SignedInfo>
      <CanonicalizationMethod Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#" />
      <SignatureMethod Algorithm="http://www.w3.org/2001/04/xmldsig-more#rsa-sha256" />
      <Reference URI="#_0">
        <Transforms>
          <Transform Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#" />
        </Transforms>
        <DigestMethod Algorithm="http://www.w3.org/2001/04/xmlenc#sha256" />
        <DigestValue>9d/ciWlVZkaJnJ3KBB5WY1H2Y8WRXPB2DquM0goT8jY=</DigestValue>
      </Reference>
    </SignedInfo>
    <SignatureValue>uxmxGw2O3B6ylkhEXOaZ...[long base64 removed]...</SignatureValue>
  </Signature>
</library>

Note:

If publicCert contains an X.509 certificate, the default SignedXml.getKeyInfoContent includes it in a <KeyInfo> element:

<Signature xmlns="http://www.w3.org/2000/09/xmldsig#">
  <SignedInfo>
    ...[signature info removed]...
  </SignedInfo>
  <SignatureValue>uxmxGw2O3B6ylkhEXOaZ...[long base64 removed]...</SignatureValue>
  <KeyInfo>
    <X509Data>
      <X509Certificate>MIIGYjCCBJagACCBN...[long base64 removed]...</X509Certificate>
    </X509Data>
  </KeyInfo>
</Signature>

To customize this see customizing algorithms for an example.

Verifying Xml documents

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 Buffer
  • privateKey - [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:

new SignedXml({
  publicCert: client_public_pem,
  getCertFromKeyInfo: () => null,
});

You can use any dom parser you want in your code (or none, depending on your usage). This sample uses xmldom and xpath, so you should install them first:

npm install @xmldom/xmldom xpath

Example:

const { DOMParser } = require("@xmldom/xmldom");
const xpath = require("xpath");
const { SignedXml } = require("xml-crypto");
const fs = require("fs");

const xml = fs.readFileSync("signed.xml", "utf8");
const doc = new DOMParser().parseFromString(xml, "text/xml");

// DO NOT attempt to parse whatever data object you have here in `doc`
// and then use it to verify the signature. This can lead to security issues.
// i.e. BAD: parseAssertion(doc),
// good: see below

const signature = xpath.select1(
  "//*[local-name(.)='Signature' and namespace-uri(.)='http://www.w3.org/2000/09/xmldsig#']",
  doc,
);
const sig = new SignedXml({ publicCert: fs.readFileSync("client_public.pem") });
sig.loadSignature(signature);
const res = sig.checkSignature(xml);

In order to protect from some attacks we must check the content we want to use is the one that has been signed:

if (!res) {
  throw new Error("Invalid signature");
}
// good: The XML Signature has been verified, meaning some subset of XML is verified.
const signedBytes = sig.getSignedReferences();

const authenticatedDoc = new DOMParser().parseFromString(signedBytes[0], "text/xml"); // Take the first signed reference
// It is now safe to load SAML, obtain the assertion XML, or do whatever else is needed.
// Be sure to only use authenticated data.
const signedAssertionNode = extractAssertion(authenticatedDoc);
const parsedAssertion = parseAssertion(signedAssertionNode);

return parsedAssertion; // This the correctly verified signed Assertion

// BAD example: DO not use the .getReferences() API.

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.

Caring for Implicit transform

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:

const sig = new SignedXml({
  implicitTransforms: ["http://www.w3.org/2001/10/xml-exc-c14n#"],
  publicCert: fs.readFileSync("client_public.pem"),
});
sig.loadSignature(signature);
const res = sig.checkSignature(xml);

Implicit transforms run after the transforms a <Reference> declares. xml-crypto converts a node-set left after the last transform to octets with Canonical XML 1.0, so an implicit http://www.w3.org/TR/2001/REC-xml-c14n-20010315 changes nothing where the transforms end in a node-set, such as when there are none or the last one is enveloped-signature.

You might find it difficult to guess such transforms, but there are typical transforms you can try.

API

SignedXml

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 undefined - the name of an additional attribute that holds an element's id; it is checked before Id, ID and id
  • privateKey - string or Buffer - default null - the private key to use for signing
  • publicCert - string or Buffer - default null - the public certificate to use for verifying
  • signatureAlgorithm - string - the signature algorithm to use
  • canonicalizationAlgorithm - string - default undefined - the canonicalization algorithm to use
  • inclusiveNamespacesPrefixList - string - default null - a list of namespace prefixes to include during canonicalization
  • implicitTransforms - string[] - default [] - a list of implicit transforms to use during verification
  • keyInfoAttributes - object - default {} - a hash of attributes and values attrName: value to add to the KeyInfo node
  • getKeyInfoContent - function - default SignedXml.getKeyInfoContent - a function that returns the content of the KeyInfo node
  • getCertFromKeyInfo - function - default noop - a function that returns the certificate from the <KeyInfo /> node

API

A SignedXml object provides the following methods:

To sign xml documents:

  • addReference({ xpath, transforms, digestAlgorithm, id, type }) - adds a reference to a xml element where:
    • xpath - a string containing a XPath expression referencing a xml element
    • transforms - an array of transform algorithms, the referenced element will be transformed for each value in the array
    • digestAlgorithm - one of the supported hashing algorithms
    • id - an optional Id attribute to add to the reference element
    • type - the optional Type attribute to add to the reference element (represented as a URI)
  • computeSignature(xml, [options]) - compute the signature of the given xml where:
    • xml - a string containing a xml document
    • options - an object with the following properties:
      • prefix - adds this value as a prefix for the generated signature tags
      • attrs - a hash of attributes and values attrName: value to add to the signature root node
      • location - 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 xml
  • getSignedXml() - 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() - [deprecated] returns the original xml with Id attributes added on relevant elements, must be called only after computeSignature. Use the location option of computeSignature() to place the signature, then getSignedXml(). See how to specify the location of the signature. For a detached signature, put an ID attribute the signer recognizes on each referenced element (wsu:Id for WS-Security), sign that document, and send it alongside getSignatureXml(). Make sure each reference XPath still selects its intended element once those IDs are present, for example by selecting on the ID itself.

Every reference XPath is evaluated against the input document before any IDs or the signature are added, so the order of addReference() calls does not change what a reference selects. A reference that matches nothing in the input is evaluated after the signature is inserted and selects only elements inside the new signature, such as generated Object or KeyInfo elements. Use separate addReference() calls for input elements and generated signature content.

An input match takes precedence, so a reference whose XPath also matches an input element signs that element and leaves the generated one unsigned. Select generated content by the Id you configured for it, as in how to add custom Objects to the signature, rather than by element name.

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 signature
  • checkSignature(xml) - validates the given xml document and returns true if the validation was successful
  • getSignedReferences() - returns the canonical XML of each reference, only after checkSignature succeeds
  • validateElementAgainstReferences(elemOrXpath, doc) - [deprecated] after checkSignature succeeds, use the XML that getSignedReferences() returns instead of nodes from the original document

Customizing Algorithms

The following sample shows how to sign a message using custom algorithms.

First import some modules:

const { SignedXml } = require("xml-crypto");
const 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 it returns no content, the <KeyInfo /> element is not included in the generated XML, even when keyInfoAttributes are set.

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.

class MyDigest {
  getHash(xml) {
    return "the base64 hash representation of the given xml string";
  }

  getAlgorithmName() {
    return "http://myDigestAlgorithm";
  }
}

A custom signing algorithm.

class MySignatureAlgorithm {
  // Sign the given SignedInfo using the key. Return the base64 signature value.
  getSignature(signedInfo, privateKey) {
    return "signature of signedInfo as base64...";
  }

  getAlgorithmName() {
    return "http://mySigningAlgorithm";
  }
}

Custom transformation algorithm.

class MyTransformation {
  // Given a node (from the xmldom module), return its canonical representation as a string.
  process(node) {
    // You should apply your transformation before returning.
    return node.toString();
  }

  getAlgorithmName() {
    return "http://myTransformation";
  }
}

Custom canonicalization is actually the same as custom transformation. It is applied on the SignedInfo rather than on references.

class MyCanonicalization {
  // Given a node (from the xmldom module), return its canonical representation as a string.
  process(node) {
    // You should apply your canonicalization before returning.
    return node.toString();
  }

  getAlgorithmName() {
    return "http://myCanonicalization";
  }
}

Now register the new algorithms on a SignedXml instance, under the names their getAlgorithmName() returns, and configure the instance to use them:

function signXml(xml, xpath, key, dest) {
  const sig = new SignedXml({
    publicCert: fs.readFileSync("my_public_cert.pem", "latin1"),
    privateKey: fs.readFileSync(key),
    // Configure the signature object to use the custom algorithms.
    signatureAlgorithm: "http://mySigningAlgorithm",
    canonicalizationAlgorithm: "http://myCanonicalization",
  });

  // Register all the custom algorithms.
  sig.CanonicalizationAlgorithms["http://myTransformation"] = MyTransformation;
  sig.CanonicalizationAlgorithms["http://myCanonicalization"] = MyCanonicalization;
  sig.HashAlgorithms["http://myDigestAlgorithm"] = MyDigest;
  sig.SignatureAlgorithms["http://mySigningAlgorithm"] = MySignatureAlgorithm;

  sig.addReference({
    xpath,
    transforms: ["http://myTransformation"],
    digestAlgorithm: "http://myDigestAlgorithm",
  });
  sig.computeSignature(xml);
  fs.writeFileSync(dest, sig.getSignedXml());
}

const xml = "<library><book><name>Harry Potter</name></book></library>";

signXml(xml, "//*[local-name(.)='book']", "client.pem", "result.xml");

You can always look at the actual code as a sample.

Asynchronous signing

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. Register it under the URI of the algorithm it implements, which is the SignatureMethod a verifier reads.

const { SignedXml } = require("xml-crypto");
const crypto = require("crypto");
const fs = require("fs");

class AsyncRsaSha256 {
  getSignature(signedInfo, privateKey, callback) {
    // Do some asynchronous things here, such as calling a signing server.
    const signer = crypto.createSign("RSA-SHA256");
    signer.update(signedInfo);
    callback(null, signer.sign(privateKey, "base64"));
  }

  getAlgorithmName() {
    return "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256";
  }
}

const xml = "<library><book><name>Harry Potter</name></book></library>";

const sig = new SignedXml({
  privateKey: fs.readFileSync("client.pem"),
  canonicalizationAlgorithm: "http://www.w3.org/2001/10/xml-exc-c14n#",
  signatureAlgorithm: "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256",
});
sig.SignatureAlgorithms["http://www.w3.org/2001/04/xmldsig-more#rsa-sha256"] = AsyncRsaSha256;
sig.addReference({
  xpath: "//*[local-name(.)='book']",
  digestAlgorithm: "http://www.w3.org/2001/04/xmlenc#sha256",
  transforms: ["http://www.w3.org/2001/10/xml-exc-c14n#"],
});
sig.computeSignature(xml, (err) => {
  if (err) {
    console.error(err);
    return;
  }
  fs.writeFileSync("signed.xml", sig.getSignedXml());
});

X.509 / Key formats

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):

-----BEGIN PRIVATE KEY-----
MIICdwIBADANBgkqhkiG9w0...
-----END PRIVATE KEY-----

And for verification use key_public.pem:

-----BEGIN CERTIFICATE-----
MIIBxDCCAW6gAwIBAgIQxUSX...
-----END CERTIFICATE-----

Converting .pfx certificates to pem

If you have .pfx certificates you can convert them to .pem using openssl:

openssl 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.

Examples

how to add a prefix for the signature

Use the prefix option when calling computeSignature to add a prefix to the signature.

const { SignedXml } = require("xml-crypto");
const fs = require("fs");

const xml = "<library><book><name>Harry Potter</name></book></library>";

const sig = new SignedXml({
  privateKey: fs.readFileSync("client.pem"),
  canonicalizationAlgorithm: "http://www.w3.org/2001/10/xml-exc-c14n#",
  signatureAlgorithm: "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256",
});
sig.addReference({
  xpath: "//*[local-name(.)='book']",
  digestAlgorithm: "http://www.w3.org/2001/04/xmlenc#sha256",
  transforms: ["http://www.w3.org/2001/10/xml-exc-c14n#"],
});
sig.computeSignature(xml, {
  prefix: "ds",
});

how to specify the location of the signature

Use the location option when calling computeSignature to move the signature around. Set reference to an XPath expression that selects a node (default /*, the document element), and action to one of the following:

  • append (default) - insert the signature as the last child of the reference node
  • prepend - insert the signature as the first child of the reference node
  • before - insert the signature just before the reference node
  • after - insert the signature just after the reference node
const { SignedXml } = require("xml-crypto");
const fs = require("fs");

const xml = "<library><book><name>Harry Potter</name></book></library>";

const sig = new SignedXml({
  privateKey: fs.readFileSync("client.pem"),
  canonicalizationAlgorithm: "http://www.w3.org/2001/10/xml-exc-c14n#",
  signatureAlgorithm: "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256",
});
sig.addReference({
  xpath: "//*[local-name(.)='book']",
  digestAlgorithm: "http://www.w3.org/2001/04/xmlenc#sha256",
  transforms: ["http://www.w3.org/2001/10/xml-exc-c14n#"],
});
sig.computeSignature(xml, {
  location: { reference: "//*[local-name(.)='book']", action: "after" }, // This will place the signature after the book element
});

How to add custom Objects to the signature

Use the objects option when creating a SignedXml instance to add custom Objects to the signature.

const { SignedXml } = require("xml-crypto");
const fs = require("fs");

const xml = "<library><book><name>Harry Potter</name></book></library>";

const sig = new SignedXml({
  privateKey: fs.readFileSync("client.pem"),
  canonicalizationAlgorithm: "http://www.w3.org/2001/10/xml-exc-c14n#",
  signatureAlgorithm: "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256",
  objects: [
    {
      content: "<TestObject>Test data in Object</TestObject>",
      attributes: {
        Id: "Object1",
        MimeType: "text/xml",
      },
    },
  ],
});

// Add a reference to the Object element
sig.addReference({
  xpath: "//*[@Id='Object1']",
  digestAlgorithm: "http://www.w3.org/2001/04/xmlenc#sha256",
  transforms: ["http://www.w3.org/2001/10/xml-exc-c14n#"],
});

sig.computeSignature(xml);
fs.writeFileSync("signed.xml", sig.getSignedXml());

Development

The testing framework we use is Mocha with Chai as the assertion framework.

To run tests use:

npm test

Sponsors

Short-io logo Short-io

RideAmigosCorp logo RideAmigosCorp

Past sponsors

stytchauth stytchauth

License

This project is licensed under the MIT License. See the LICENSE file for more info.

About

Xml digital signature and encryption library for Node.js

Resources

Stars

212 stars

Watchers

13 watching

Forks

Releases

Packages

Used by

Contributors

Languages