Tuesday, June 25, 2013

Validating Windows Mobile App Store Receipts Using Node.js

@YaronNaveh

When your windows phone user performs an in-app purchase you can get its receipt using the API:

<Receipt Version="1.0" ReceiptDate="2012-08-30T23:10:05Z" CertificateId="b809e47cd0110a4db043b3f73e83acd917fe1336" ReceiptDeviceId="4e362949-acc3-fe3a-e71b-89893eb4f528">
<AppReceipt Id="8ffa256d-eca8-712a-7cf8-cbf5522df24b" AppId="55428GreenlakeApps.CurrentAppSimulatorEventTest_z7q3q7z11crfr" PurchaseDate="2012-06-04T23:07:24Z" LicenseType="Full" />
<ProductReceipt Id="6bbf4366-6fb2-8be8-7947-92fd5f683530" ProductId="Product1" PurchaseDate="2012-08-30T23:08:52Z" ExpirationDate="2012-09-02T23:08:49Z" ProductType="Durable" AppId="55428GreenlakeApps.CurrentAppSimulatorEventTest_z7q3q7z11crfr" />
<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="">
<Transforms>
<Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature" />
</Transforms>
<DigestMethod Algorithm="http://www.w3.org/2001/04/xmlenc#sha256" />
<DigestValue>cdiU06eD8X/w1aGCHeaGCG9w/kWZ8I099rw4mmPpvdU=</DigestValue>
</Reference>
</SignedInfo>
<SignatureValue>SjRIxS/2r2P6ZdgaR9bwUSa6ZItYYFpKLJZrnAa3zkMylbiWjh9oZGGng2p6/gtBHC2dSTZlLbqnysJjl7mQp/A3wKaIkzjyRXv3kxoVaSV0pkqiPt04cIfFTP0JZkE5QD/vYxiWjeyGp1dThEM2RV811sRWvmEs/hHhVxb32e8xCLtpALYx3a9lW51zRJJN0eNdPAvNoiCJlnogAoTToUQLHs72I1dECnSbeNPXiG7klpy5boKKMCZfnVXXkneWvVFtAA1h2sB7ll40LEHO4oYN6VzD+uKd76QOgGmsu9iGVyRvvmMtahvtL1/pxoxsTRedhKq6zrzCfT8qfh3C1w==</SignatureValue>
</Signature>
</Receipt>
view raw gistfile1.xml hosted with ❤ by GitHub

You need to send this receipt to your backend system to validate the signature. If that backend system happens to be in C# your life is easy as the official documentation provides exact validation instructions. If you use another platform then be aware that there are a few gotchas to this validation process.

Based on several requests I have checked the feasibility to use my xml-crytpo node.js module to perform this validation. There were two challenges that required to patch xml-crypto. Both of them caused the signature digest calculation to differ from the stated one by the store. This had failed the validation process.

White spaces
As you can see in the sample receipt above it contains white spaces. White spaces in Xml are meaningful and once an Xml has been signed it is not legal to remove or alter the white spaces. However take a look at these lines from Microsoft C# validation instructions:

XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load("..\\..\\receipt.xml");
view raw gistfile1.cs hosted with ❤ by GitHub

The receipt is loaded into an XmlDocument. Since not defined otherwise, the PreserveWhitespace property defaults to false. This means that the actual validaiton code later on is performed not on the actuall Xml received from the network/disk but on an altered version of it which strips all white space. This is not standard and confusing. Anyway if you use node.js remember to first remove the whitespace before processing the document further. Unfortunately xmldom, the module which xml-crypto uses for xml processing, does not provide this utility. I did a quick patch for it and for now have put it in my private xmldom repo. Just initialize the parser with the ignoreWhiteSpace flag:

var dom = require('xmldom').DOMParser
var doc = new dom({ignoreWhiteSpace: true}).parseFromString(xmlstr);
view raw gistfile1.js hosted with ❤ by GitHub


Debugging this was quite painfull which is why I posted this tweet shortly after:



Implicit Exclusive Xml Canonicalization
Canonicalization is probably one of the most confusing topics regarding xml digital signature. In a nutshell, before processing Xml (either when signing it or when validating the signature) we need to transform it to a canonical form in terms of attribute order, namespace definition, whitespace and etc. There are multiple standard to do so and they can be chained together so the signed xml should state which standard(s) it uses:

<Transforms>
<Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature" />
<Transform Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#" />
</Transforms>
view raw gistfile1.xml hosted with ❤ by GitHub

This is the transformation stated by the windows store receipt

<Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature" />
view raw gistfile1.xml hosted with ❤ by GitHub

In practice when trying to validate according to this transformation xml-crypto shows this validation error:

[ 'invalid signature: for uri calculated digest is aBE4HWVLJ8EyKMu7Q3moFzcT72NPx9OngF0E1X4dRJw= but the xml to validate supplies digest Uvi8jkTYd3HtpMmAMpOm94fLeqmcQ2KCrV1XmSuY1xI=' ]
view raw gistfile1.txt hosted with ❤ by GitHub

I have built a simple C# app to do this validation according to the Microsoft sample - it worked. The sample uses the high level SignedXml class. I have then built a C# snippet to do the validation in a more low level way by applying the enveloped-signature transformation myself - this failed.

I had to dig deep in the reflector to find that internally the SignedXml .net class always applies the Exclusive Xml Canonicalization standard in addition to any explicitly defined transformation. This happens in TransformChain.TransformToOctetStream() method which is used internally in the signing process when it starts with SignedXml:

internal Stream TransformToOctetStream(object inputObject, Type inputType, XmlResolver resolver, string baseUri)
{
...
CanonicalXml xml4 = new CanonicalXml((XmlDocument) output, resolver);
return new MemoryStream(xml4.GetBytes());
}
view raw gistfile1.cs hosted with ❤ by GitHub

The CanonicalXml class has an internal property m_c14nDoc which holds the canonicalized version.

Once I have forced xml-crypto to use c14n at all times the validation was successful.

I have not found any evidence in the xml digital signature or exclusive xml canonicalization specs that the way SignedXml works complies with the definitions.

All Together Now
I have committed the changes to the xml-crytpo windows-store branch and have not checked them in to npm since this is not necessarily the correct behavior with other platforms. So you should use xml-crypto from there (a quick way is to "npm install xml-crypto" and then override the created folder with the windows-store branch zip. There is a way to tell npm to install directly from github but not sure if this can happen from a branch. This is the usage example:

var crypto = require('xml-crypto')
, Dom = require('xmldom').DOMParser
, fs = require('fs')
var xml = fs.readFileSync('./windows_store_signature.xml', 'utf-8');
var doc = new Dom({ignoreWhiteSpace: true}).parseFromString(xml);
xml = doc.firstChild.toString()
var signature = crypto.xpath(doc, "//*//*[local-name(.)='Signature' and namespace-uri(.)='http://www.w3.org/2000/09/xmldsig#']")[0];
var sig = new crypto.SignedXml();
sig.keyInfoProvider = new crypto.FileKeyInfo("./windows_store_certificate.pem");
sig.loadSignature(signature.toString());
var result = sig.checkSignature(xml);
if (result)
console.log("signature is valid")
else
console.log("signature is invalid: " + sig.validationErrors)
view raw gistfile1.js hosted with ❤ by GitHub

The pem file contains the raw content of the certificate which you get from the windows store provided url:

-----BEGIN CERTIFICATE-----
MIIDyTCCArGgAwIBAgIQNP+YKvSo8IVArhlhpgc/xjANBgkqhkiG9w0BAQsFADCB
jjELMAkGA1UEBhMCVVMxEzARBgNVBAgMCldhc2hpbmd0b24xEDAOBgNVBAcMB1Jl
ZG1vbmQxHjAcBgNVBAoMFU1pY3Jvc29mdCBDb3Jwb3JhdGlvbjEWMBQGA1UECwwN
V2luZG93cyBTdG9yZTEgMB4GA1UEAwwXV2luZG93cyBTdG9yZSBMaWNlbnNpbmcw
HhcNMTExMTE3MjMwNTAyWhcNMzYxMTEwMjMxMzQ0WjCBjjELMAkGA1UEBhMCVVMx
EzARBgNVBAgMCldhc2hpbmd0b24xEDAOBgNVBAcMB1JlZG1vbmQxHjAcBgNVBAoM
FU1pY3Jvc29mdCBDb3Jwb3JhdGlvbjEWMBQGA1UECwwNV2luZG93cyBTdG9yZTEg
MB4GA1UEAwwXV2luZG93cyBTdG9yZSBMaWNlbnNpbmcwggEiMA0GCSqGSIb3DQEB
AQUAA4IBDwAwggEKAoIBAQCcr4/vgqZFtzMqy3jO0XHjBUNx6j7ZTXEnNpLl2VSe
zVQA9KK2RlvroXKhYMUUdJpw+txm1mqi/W7D9QOYTq1e83GLhWC9IRh/OSmSYt0e
kgVLB+icyRH3dtpYcJ5sspU2huPf4I/Nc06OuXlMsD9MU4Ug9IBD2HSDBEquhGRo
xV64YuEH4645oB14LlEay0+JZlkKZ/mVhx/sdzSBfrda1X/Ckc7SOgnTSM3d/DnO
5DKwV2WYn+7i/rBqe4/op6IqQMrPpHyem9Sny+i0xiUMA+1IwkX0hs0gvHM6zDww
TMDiTapbCy9LnmMx65oMq56hhsQydLEmquq8lVYUDEzLAgMBAAGjITAfMB0GA1Ud
DgQWBBREzrOBz7zw+HWskxonOXAPMa6+NzANBgkqhkiG9w0BAQsFAAOCAQEAeVtN
4c6muxO6yfht9SaxEfleUBIjGfe0ewLBp00Ix7b7ldJ/lUQcA6y+Drrl7vjmkHQK
OU3uZiFbCxTvgTcoz9o+1rzR/WPXmqH5bqu6ua/UrobGKavAScqqI/G6o56Xmx/y
oErWN0VapN370crKJvNWxh3yw8DCl+W0EcVRiWX5lFsMBNBbVpK4Whp+VhkSJilu
iRpe1B35Q8EqOz/4RQkOpVI0dREnuSYkBy/h2ggCtiQ5yfvH5zCdcfhFednYDevS
axmt3W5WuHz8zglkg+OQ3qpXaXySRlrmLdxEmWu2MOiZbQkU2ZjBSQmvFAOy0dd6
P1YLS4+Eyh5drQJc0Q==
-----END CERTIFICATE-----
view raw gistfile1.txt hosted with ❤ by GitHub

I hope your app will be successful and you will use this procedure a lot...

@YaronNaveh

What's next? get this blog rss updates or register for mail updates!