aboutsummaryrefslogtreecommitdiff
path: root/test/xml/saml_verify.t.mjs
blob: 65d4e06b7e9f0a191e5572b4954f13b6e812f2a6 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
/*---
includes: [compatFs.js, compatWebcrypto.js, compatNjs.js, runTsuite.js]
flags: [async]
---*/

import xml from 'xml';

async function verify(params) {
    let file_data = fs.readFileSync(`test/xml/${params.saml}`);
    let key_data = fs.readFileSync(`test/webcrypto/${params.key.file}`);

    if (params.sign) {
        let sign_key_data = fs.readFileSync(`test/webcrypto/${params.key.sign_file}`);
        let signed = await signSAML(xml.parse(file_data), sign_key_data);
        file_data = xml.c14n(signed);
    }

    let saml = xml.parse(file_data);

    let r = await verifySAMLSignature(saml, key_data)
                .catch (e => {
                    if (e.message.startsWith("EVP_PKEY_CTX_set_signature_md() failed")) {
                        /* Red Hat Enterprise Linux: SHA-1 is disabled */
                        return "SKIPPED";
                    }
                });

    if (r == "SKIPPED") {
        return r;
    }

    if (params.expected !== r) {
        throw Error(`VERIFY ${params.saml} with key ${params.key.file} failed expected: "${params.expected}" vs "${r}"`);
    }

    return 'SUCCESS';
}

/*
 * signSAML() signs a SAML message template
 *
 *  The message to sign should already contain a full Signature element
 *  with SignedInfo and Reference elements below.
 *  The only parts that are missing are DigestValue and SignatureValue.
 *   <ds:Signature xmlns:ds="http://www.w3.org/2000/09/xmldsig#">
 *       <ds:SignedInfo>
 *           <ds:CanonicalizationMethod Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#" />
 *           <ds:SignatureMethod Algorithm="http://www.w3.org/2001/04/xmldsig-more#rsa-sha256" />
 *           <ds:Reference URI="#_0x14956c887e664bdb71d7685b89b70619">
 *               <ds:Transforms>
 *                   <ds:Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature" />
 *                   <ds:Transform Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#" />
 *               </ds:Transforms>
 *               <ds:DigestMethod Algorithm="http://www.w3.org/2001/04/xmlenc#sha256" />
 *               <ds:DigestValue></ds:DigestValue>
 *           </ds:Reference>
 *       </ds:SignedInfo>
 *       <ds:SignatureValue></ds:SignatureValue>
 *   </ds:Signature>
 *
 * The following signature algorithms are supported:
 * - http://www.w3.org/2001/04/xmldsig-more#rsa-sha256
 * - http://www.w3.org/2000/09/xmldsig#rsa-sha1
 *
 * The following digest algorithms are supported:
 * - http://www.w3.org/2000/09/xmldsig#sha1
 * - http://www.w3.org/2001/04/xmlenc#sha256
 *
 * As a part of the signing process, the following attributes are set:
 * - xml:ID
 *   The value is a random 16 bytes hex string.
 * - IssueInstant
 *   The value is the current time in ISO 8601 format.
 *
 * @param doc an XMLDoc object returned by xml.parse().
 * @param key_data is PKCS #8 in PEM format.
 */
async function signSAML(saml, key_data) {
    const root = saml.$root;
    const rootSignature = root.Signature;

    const rnd = Buffer.alloc(16);
    crypto.getRandomValues(rnd);
    const id = rnd.toString('hex');

    root.setAttribute('xml:ID', id);
    rootSignature.SignedInfo.Reference.setAttribute('URI', `#${id}`);
    root.setAttribute('IssueInstant', (new Date()).toISOString());

    await digestSAML(rootSignature, true);
    await signatureSAML(rootSignature, key_data, true);
    return saml;
}

/*
 * verifySAMLSignature() implements a verify clause
 * from Profiles for the OASIS SAML V2.0
 * 4.1.4.3 <Response> Message Processing Rules
 *  Verify any signatures present on the assertion(s) or the response
 *
 * verification is done in accordance with
 * Assertions and Protocols for the OASIS SAML V2.0
 * 5.4 XML Signature Profile
 *
 * The following signature algorithms are supported:
 * - http://www.w3.org/2001/04/xmldsig-more#rsa-sha256
 * - http://www.w3.org/2000/09/xmldsig#rsa-sha1
 *
 * The following digest algorithms are supported:
 * - http://www.w3.org/2000/09/xmldsig#sha1
 * - http://www.w3.org/2001/04/xmlenc#sha256
 *
 * @param doc an XMLDoc object returned by xml.parse().
 * @param key_data is SubjectPublicKeyInfo in PEM format.
 */

async function verifySAMLSignature(saml, key_data) {
    const root = saml.$root;
    const rootSignature = root.Signature;

    if (!rootSignature) {
        throw Error(`SAML message is unsigned`);
    }

    const assertion = root.Assertion;
    const assertionSignature = assertion ? assertion.Signature : null;

    if (assertionSignature) {
        if (!await digestSAML(assertionSignature)) {
            return false;
        }

        if (!await signatureSAML(assertionSignature, key_data)) {
            return false;
        }
    }

    if (rootSignature) {
        if (!await digestSAML(rootSignature)) {
            return false;
        }

        if (!await signatureSAML(rootSignature, key_data)) {
            return false;
        }
    }

    return true;
}

async function digestSAML(signature, produce) {
    const parent = signature.$parent;
    const signedInfo = signature.SignedInfo;
    const reference = signedInfo.Reference;

    /* Sanity check. */

    const URI = reference.$attr$URI;
    const ID = parent.$attr$ID;

    if (URI != `#${ID}`) {
        throw Error(`signed reference URI ${URI} does not point to the parent ${ID}`);
    }

    /*
     * Assertions and Protocols for the OASIS SAML V2.0
     * 5.4.4 Transforms
     *
     * Signatures in SAML messages SHOULD NOT contain transforms other than
     * the http://www.w3.org/2000/09/xmldsig#enveloped-signature and
     * canonicalization transforms http://www.w3.org/2001/10/xml-exc-c14n# or
     * http://www.w3.org/2001/10/xml-exc-c14n#WithComments.
     */

    const transforms = reference.Transforms.$tags$Transform;
    const transformAlgs = transforms.map(t => t.$attr$Algorithm);

    if (transformAlgs[0] != 'http://www.w3.org/2000/09/xmldsig#enveloped-signature') {
        throw Error(`unexpected digest transform ${transforms[0]}`);
    }

    if (!transformAlgs[1].startsWith('http://www.w3.org/2001/10/xml-exc-c14n#')) {
        throw Error(`unexpected digest transform ${transforms[1]}`);
    }

    const namespaces = transformAlgs[1].InclusiveNamespaces;
    const prefixList = namespaces ? namespaces.$attr$PrefixList: null;

    const withComments = transformAlgs[1].slice(39) == 'WithComments';

    let hash;
    const alg = reference.DigestMethod.$attr$Algorithm;

    switch (alg) {
    case "http://www.w3.org/2000/09/xmldsig#sha1":
        hash = "SHA-1";
        break;
    case "http://www.w3.org/2001/04/xmlenc#sha256":
        hash = "SHA-256";
        break;
    default:
        throw Error(`unexpected digest Algorithm ${alg}`);
    }

    const c14n = xml.exclusiveC14n(parent, signature, withComments, prefixList);
    const dgst = await crypto.subtle.digest(hash, c14n);
    const b64dgst = Buffer.from(dgst).toString('base64');

    if (produce) {
        signedInfo.Reference.DigestValue.$text = b64dgst;
        return b64dgst;
    }

    const expectedDigest = signedInfo.Reference.DigestValue.$text;

    return expectedDigest === b64dgst;
}

function keyPem2Der(pem, type) {
    const pemJoined = pem.toString().split('\n').join('');
    const pemHeader = `-----BEGIN ${type} KEY-----`;
    const pemFooter = `-----END ${type} KEY-----`;
    const pemContents = pemJoined.substring(pemHeader.length, pemJoined.length - pemFooter.length);
    return Buffer.from(pemContents, 'base64');
}

function base64decode(b64) {
    const joined = b64.toString().split('\n').join('');
    return Buffer.from(joined, 'base64');
}

async function signatureSAML(signature, key_data, produce) {
    let method, hash;
    const signedInfo = signature.SignedInfo;
    const alg = signedInfo.SignatureMethod.$attr$Algorithm;

    switch (alg) {
    case "http://www.w3.org/2000/09/xmldsig#rsa-sha1":
        method = "RSASSA-PKCS1-v1_5";
        hash = "SHA-1";
        break;
    case "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256":
        method = "RSASSA-PKCS1-v1_5";
        hash = "SHA-256";
        break;
    default:
        throw Error(`unexpected signature Algorithm ${alg}`);
    }

    const withComments = signedInfo.CanonicalizationMethod
                         .$attr$Algorithm.slice(39) == 'WithComments';

    const signedInfoC14n = xml.exclusiveC14n(signedInfo, null, withComments);

    if (produce) {
        const der = keyPem2Der(key_data, "PRIVATE");
        const key = await crypto.subtle.importKey("pkcs8", der, { name: method, hash },
                                                  false, [ "sign" ]);

        let sig =  await crypto.subtle.sign({ name: method }, key, signedInfoC14n);

        signature.SignatureValue.$text = Buffer.from(sig).toString('base64');
        return signature;
    }

    const der = keyPem2Der(key_data, "PUBLIC");
    const key = await crypto.subtle.importKey("spki", der, { name: method, hash },
                                              false, [ "verify" ]);

    const expectedValue = base64decode(signature.SignatureValue.$text);
    return await crypto.subtle.verify({ name: method }, key, expectedValue,
                                      signedInfoC14n);
}

let saml_verify_tsuite = {
    name: "SAML verify",
    skip: () => (!has_njs() || !has_webcrypto()),
    T: verify,
    opts: {
        key: { fmt: "spki", file: "rsa.spki" },
    },

    tests: [
        { saml: "auth_r_signed.xml", expected: true },
        { saml: "auth_r_with_comments_signed.xml", expected: true },
        { saml: "auth_r_prefix_list_signed.xml", expected: true },
        { saml: "auth_r_signed2.xml", expected: false },
        { saml: "auth_r_signed.xml", key: { file: "rsa2.spki"}, expected: false },
        { saml: "auth_r_signed2.xml", key: { file: "rsa2.spki"}, expected: true },
        { saml: "response_signed.xml", expected: true },
        { saml: "response_signed_broken.xml", expected: false },
        { saml: "response_signed_broken2.xml", expected: false },
        { saml: "response_signed.xml", key: { file: "rsa2.spki"}, expected: false },
        { saml: "response_assertion_and_message_signed.xml", expected: true },

        { saml: "auth_r.xml", sign: true, key: { sign_file: "rsa.pkcs8" }, expected: true },
]};

run([
    saml_verify_tsuite,
])
.then($DONE, $DONE);