servo-script 0.1.0

A component of the servo web-engine.
Documentation
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
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at https://mozilla.org/MPL/2.0/. */

use aws_lc_rs::constant_time::verify_slices_are_equal;
use aws_lc_rs::hmac;
use js::context::JSContext;
use rand::TryRngCore;
use rand::rngs::OsRng;
use script_bindings::codegen::GenericBindings::CryptoKeyBinding::CryptoKeyMethods;
use script_bindings::domstring::DOMString;

use crate::dom::bindings::codegen::Bindings::CryptoKeyBinding::{KeyType, KeyUsage};
use crate::dom::bindings::codegen::Bindings::SubtleCryptoBinding::{JsonWebKey, KeyFormat};
use crate::dom::bindings::error::Error;
use crate::dom::bindings::root::DomRoot;
use crate::dom::cryptokey::{CryptoKey, Handle};
use crate::dom::globalscope::GlobalScope;
use crate::dom::subtlecrypto::{
    CryptoAlgorithm, ExportedKey, JsonWebKeyExt, JwkStringField, KeyAlgorithmAndDerivatives,
    NormalizedAlgorithm, SubtleHmacImportParams, SubtleHmacKeyAlgorithm, SubtleHmacKeyGenParams,
    SubtleKeyAlgorithm,
};

/// <https://w3c.github.io/webcrypto/#hmac-operations-sign>
pub(crate) fn sign(key: &CryptoKey, message: &[u8]) -> Result<Vec<u8>, Error> {
    // Step 1. Let mac be the result of performing the MAC Generation operation described in
    // Section 4 of [FIPS-198-1] using the key represented by the [[handle]] internal slot of key,
    // the hash function identified by the hash attribute of the [[algorithm]] internal slot of key
    // and message as the input data text.
    let hash_function = match key.algorithm() {
        KeyAlgorithmAndDerivatives::HmacKeyAlgorithm(algo) => match algo.hash.name {
            CryptoAlgorithm::Sha1 => hmac::HMAC_SHA1_FOR_LEGACY_USE_ONLY,
            CryptoAlgorithm::Sha256 => hmac::HMAC_SHA256,
            CryptoAlgorithm::Sha384 => hmac::HMAC_SHA384,
            CryptoAlgorithm::Sha512 => hmac::HMAC_SHA512,
            _ => {
                return Err(Error::NotSupported(Some(
                    "Unsupported hash algorithm for HMAC".into(),
                )));
            },
        },
        _ => {
            return Err(Error::NotSupported(Some(
                "The key algorithm is not HMAC".into(),
            )));
        },
    };
    let sign_key = hmac::Key::new(hash_function, key.handle().as_bytes());
    let mac = hmac::sign(&sign_key, message);

    // Step 2. Return mac.
    Ok(mac.as_ref().to_vec())
}

/// <https://w3c.github.io/webcrypto/#hmac-operations-verify>
pub(crate) fn verify(key: &CryptoKey, message: &[u8], signature: &[u8]) -> Result<bool, Error> {
    // Step 1. Let mac be the result of performing the MAC Generation operation described in
    // Section 4 of [FIPS-198-1] using the key represented by the [[handle]] internal slot of key,
    // the hash function identified by the hash attribute of the [[algorithm]] internal slot of key
    // and message as the input data text.
    let hash_function = match key.algorithm() {
        KeyAlgorithmAndDerivatives::HmacKeyAlgorithm(algo) => match algo.hash.name {
            CryptoAlgorithm::Sha1 => hmac::HMAC_SHA1_FOR_LEGACY_USE_ONLY,
            CryptoAlgorithm::Sha256 => hmac::HMAC_SHA256,
            CryptoAlgorithm::Sha384 => hmac::HMAC_SHA384,
            CryptoAlgorithm::Sha512 => hmac::HMAC_SHA512,
            _ => {
                return Err(Error::NotSupported(Some(
                    "Unsupported hash algorithm for HMAC".into(),
                )));
            },
        },
        _ => {
            return Err(Error::NotSupported(Some(
                "The key algorithm is not HMAC".into(),
            )));
        },
    };
    let sign_key = hmac::Key::new(hash_function, key.handle().as_bytes());
    let mac = hmac::sign(&sign_key, message);

    // Step 2. Return true if mac is equal to signature and false otherwise. This comparison must
    // be performed in constant-time.
    Ok(verify_slices_are_equal(mac.as_ref(), signature).is_ok())
}

/// <https://w3c.github.io/webcrypto/#hmac-operations-generate-key>
pub(crate) fn generate_key(
    cx: &mut JSContext,
    global: &GlobalScope,
    normalized_algorithm: &SubtleHmacKeyGenParams,
    extractable: bool,
    usages: Vec<KeyUsage>,
) -> Result<DomRoot<CryptoKey>, Error> {
    // Step 1. If usages contains any entry which is not "sign" or "verify", then throw a SyntaxError.
    if usages
        .iter()
        .any(|usage| !matches!(usage, KeyUsage::Sign | KeyUsage::Verify))
    {
        return Err(Error::Syntax(Some(
            "Usages contains an entry which is not \"sign\" or \"verify\"".into(),
        )));
    }

    // Step 2.
    let length = match normalized_algorithm.length {
        // If the length member of normalizedAlgorithm is not present:
        None => {
            // Let length be the block size in bits of the hash function identified by the
            // hash member of normalizedAlgorithm.
            hash_function_block_size_in_bits(normalized_algorithm.hash.name())?
        },
        // Otherwise, if the length member of normalizedAlgorithm is non-zero:
        Some(length) if length != 0 => {
            // Let length be equal to the length member of normalizedAlgorithm.
            length
        },
        // Otherwise:
        _ => {
            // throw an OperationError.
            return Err(Error::Operation(Some(
                "The length member of normalizedAlgorithm is zero".into(),
            )));
        },
    };

    // Step 3. Generate a key of length length bits.
    // Step 4. If the key generation step fails, then throw an OperationError.
    let mut key_data = vec![0; length as usize];
    if OsRng.try_fill_bytes(&mut key_data).is_err() {
        return Err(Error::JSFailed);
    }

    // Step 6. Let algorithm be a new HmacKeyAlgorithm.
    // Step 7. Set the name attribute of algorithm to "HMAC".
    // Step 8. Set the length attribute of algorithm to length.
    // Step 9. Let hash be a new KeyAlgorithm.
    // Step 10. Set the name attribute of hash to equal the name member of the hash member of
    // normalizedAlgorithm.
    // Step 11. Set the hash attribute of algorithm to hash.
    let hash = SubtleKeyAlgorithm {
        name: normalized_algorithm.hash.name(),
    };
    let algorithm = SubtleHmacKeyAlgorithm {
        name: CryptoAlgorithm::Hmac,
        hash,
        length,
    };

    // Step 5. Let key be a new CryptoKey object representing the generated key.
    // Step 12. Set the [[type]] internal slot of key to "secret".
    // Step 13. Set the [[algorithm]] internal slot of key to algorithm.
    // Step 14. Set the [[extractable]] internal slot of key to be extractable.
    // Step 15. Set the [[usages]] internal slot of key to be usages.
    let key = CryptoKey::new(
        cx,
        global,
        KeyType::Secret,
        extractable,
        KeyAlgorithmAndDerivatives::HmacKeyAlgorithm(algorithm),
        usages,
        Handle::Hmac(key_data),
    );

    // Step 16. Return key.
    Ok(key)
}

/// <https://w3c.github.io/webcrypto/#hmac-operations-import-key>
pub(crate) fn import_key(
    cx: &mut JSContext,
    global: &GlobalScope,
    normalized_algorithm: &SubtleHmacImportParams,
    format: KeyFormat,
    key_data: &[u8],
    extractable: bool,
    usages: Vec<KeyUsage>,
) -> Result<DomRoot<CryptoKey>, Error> {
    // Step 1. Let keyData be the key data to be imported.

    // Step 2. If usages contains an entry which is not "sign" or "verify", then throw a SyntaxError.
    // Note: This is not explicitly spec'ed, but also throw a SyntaxError if usages is empty
    if usages
        .iter()
        .any(|usage| !matches!(usage, KeyUsage::Sign | KeyUsage::Verify)) ||
        usages.is_empty()
    {
        return Err(Error::Syntax(Some(
            "Usages contains an entry which is not \"sign\" or \"verify\", or is empty".into(),
        )));
    }

    // Step 3. Let hash be a new KeyAlgorithm.
    let hash;

    // Step 4.
    let data;
    match format {
        // If format is "raw":
        KeyFormat::Raw | KeyFormat::Raw_secret => {
            // Step 4.1. Let data be keyData.
            data = key_data.to_vec();

            // Step 4.2. Set hash to equal the hash member of normalizedAlgorithm.
            hash = &normalized_algorithm.hash;
        },
        // If format is "jwk":
        KeyFormat::Jwk => {
            // Step 2.1. If keyData is a JsonWebKey dictionary: Let jwk equal keyData.
            // Otherwise: Throw a DataError.
            // NOTE: Deserialize keyData to JsonWebKey dictionary by running JsonWebKey::parse
            let jwk = JsonWebKey::parse(cx, key_data)?;

            // Step 2.2. If the kty field of jwk is not "oct", then throw a DataError.
            if jwk.kty.as_ref().is_none_or(|kty| kty != "oct") {
                return Err(Error::Data(Some(
                    "The kty field of jwk is not \"oct\"".into(),
                )));
            }

            // Step 2.3. If jwk does not meet the requirements of Section 6.4 of JSON Web
            // Algorithms [JWA], then throw a DataError.
            // NOTE: Done by Step 2.4 and 2.6.

            // Step 2.4. Let data be the byte sequence obtained by decoding the k field of jwk.
            data = jwk.decode_required_string_field(JwkStringField::K)?;

            // Step 2.5. Set the hash to equal the hash member of normalizedAlgorithm.
            hash = &normalized_algorithm.hash;

            // Step 2.6.
            match hash.name() {
                // If the name attribute of hash is "SHA-1":
                CryptoAlgorithm::Sha1 => {
                    // If the alg field of jwk is present and is not "HS1", then throw a DataError.
                    if jwk.alg.as_ref().is_some_and(|alg| alg != "HS1") {
                        return Err(Error::Data(Some(
                            "The alg field of jwk is present, and is not \"HS1\"".into(),
                        )));
                    }
                },
                // If the name attribute of hash is "SHA-256":
                CryptoAlgorithm::Sha256 => {
                    // If the alg field of jwk is present and is not "HS256", then throw a DataError.
                    if jwk.alg.as_ref().is_some_and(|alg| alg != "HS256") {
                        return Err(Error::Data(Some(
                            "The alg field of jwk is present, and is not \"HS256\"".into(),
                        )));
                    }
                },
                // If the name attribute of hash is "SHA-384":
                CryptoAlgorithm::Sha384 => {
                    // If the alg field of jwk is present and is not "HS384", then throw a DataError.
                    if jwk.alg.as_ref().is_some_and(|alg| alg != "HS384") {
                        return Err(Error::Data(Some(
                            "The alg field of jwk is present, and is not \"HS384\"".into(),
                        )));
                    }
                },
                // If the name attribute of hash is "SHA-512":
                CryptoAlgorithm::Sha512 => {
                    // If the alg field of jwk is present and is not "HS512", then throw a DataError.
                    if jwk.alg.as_ref().is_some_and(|alg| alg != "HS512") {
                        return Err(Error::Data(Some(
                            "The alg field of jwk is present, and is not \"HS512\"".into(),
                        )));
                    }
                },
                // Otherwise,
                _name => {
                    // if the name attribute of hash is defined in another applicable specification:
                    // Perform any key import steps defined by other applicable specifications,
                    // passing format, jwk and hash and obtaining hash
                    // NOTE: Currently not support applicable specification.
                    return Err(Error::NotSupported(Some(
                        "Unsupported hash algorithm".into(),
                    )));
                },
            }

            // Step 2.7. If usages is non-empty and the use field of jwk is present and is not
            // "sig", then throw a DataError.
            if !usages.is_empty() && jwk.use_.as_ref().is_some_and(|use_| use_ != "sig") {
                return Err(Error::Data(Some(
                    "Usages is non-empty and the use field of jwk is present and is not \"sig\""
                        .into(),
                )));
            }

            // Step 2.8. If the key_ops field of jwk is present, and is invalid according to
            // the requirements of JSON Web Key [JWK] or does not contain all of the specified
            // usages values, then throw a DataError.
            jwk.check_key_ops(&usages)?;

            // Step 2.9. If the ext field of jwk is present and has the value false and
            // extractable is true, then throw a DataError.
            if jwk.ext.is_some_and(|ext| !ext) && extractable {
                return Err(Error::Data(Some(
                    "The ext field of jwk is present and has the value false and extractable is true"
                        .into(),
                )));
            }
        },
        // Otherwise:
        _ => {
            // throw a NotSupportedError.
            return Err(Error::NotSupported(Some(
                "Unsupported import key format for HMAC key".into(),
            )));
        },
    }

    // Step 5. Let length be the length in bits of data.
    let mut length = data.len() as u32 * 8;

    // Step 6. If length is zero then throw a DataError.
    if length == 0 {
        return Err(Error::Data(Some(
            "The length in bits of data is zero".into(),
        )));
    }

    // Step 7. If the length member of normalizedAlgorithm is present:
    if let Some(given_length) = normalized_algorithm.length {
        //  If the length member of normalizedAlgorithm is greater than length:
        if given_length > length {
            // throw a DataError.
            return Err(Error::Data(Some(
                "The length member of normalizedAlgorithm is greater than the length in bits of data"
                    .into(),
            )));
        }
        // Otherwise:
        else {
            // Set length equal to the length member of normalizedAlgorithm.
            length = given_length;
        }
    }

    // Step 10. Let algorithm be a new HmacKeyAlgorithm.
    // Step 11. Set the name attribute of algorithm to "HMAC".
    // Step 12. Set the length attribute of algorithm to length.
    // Step 13. Set the hash attribute of algorithm to hash.
    let algorithm = SubtleHmacKeyAlgorithm {
        name: CryptoAlgorithm::Hmac,
        hash: SubtleKeyAlgorithm { name: hash.name() },
        length,
    };

    // Step 8. Let key be a new CryptoKey object representing an HMAC key with the first length
    // bits of data.
    // Step 9. Set the [[type]] internal slot of key to "secret".
    // Step 14. Set the [[algorithm]] internal slot of key to algorithm.
    let truncated_data = data[..length as usize / 8].to_vec();
    let key = CryptoKey::new(
        cx,
        global,
        KeyType::Secret,
        extractable,
        KeyAlgorithmAndDerivatives::HmacKeyAlgorithm(algorithm),
        usages,
        Handle::Hmac(truncated_data),
    );

    // Step 15. Return key.
    Ok(key)
}

/// <https://w3c.github.io/webcrypto/#hmac-operations-export-key>
pub(crate) fn export_key(format: KeyFormat, key: &CryptoKey) -> Result<ExportedKey, Error> {
    match format {
        KeyFormat::Raw | KeyFormat::Raw_secret => match key.handle() {
            Handle::Hmac(key_data) => Ok(ExportedKey::Bytes(key_data.as_slice().to_vec())),
            _ => Err(Error::Operation(Some(
                "The key handle is not representing an HMAC key".into(),
            ))),
        },
        KeyFormat::Jwk => {
            // Step 4.1. Let jwk be a new JsonWebKey dictionary.
            // Step 4.2. Set the kty attribute of jwk to the string "oct".
            let mut jwk = JsonWebKey {
                kty: Some(DOMString::from("oct")),
                ..Default::default()
            };

            // Step 4.3. Set the k attribute of jwk to be a string containing data, encoded according
            // to Section 6.4 of JSON Web Algorithms [JWA].
            let key_data = key.handle().as_bytes();
            jwk.encode_string_field(JwkStringField::K, key_data);

            // Step 4.4. Let algorithm be the [[algorithm]] internal slot of key.
            // Step 4.5. Let hash be the hash attribute of algorithm.
            // Step 4.6.
            // If the name attribute of hash is "SHA-1":
            //     Set the alg attribute of jwk to the string "HS1".
            // If the name attribute of hash is "SHA-256":
            //     Set the alg attribute of jwk to the string "HS256".
            // If the name attribute of hash is "SHA-384":
            //     Set the alg attribute of jwk to the string "HS384".
            // If the name attribute of hash is "SHA-512":
            //     Set the alg attribute of jwk to the string "HS512".
            // Otherwise, the name attribute of hash is defined in another applicable
            // specification:
            //     Perform any key export steps defined by other applicable specifications, passing
            //     format and key and obtaining alg.
            //     Set the alg attribute of jwk to alg.
            let hash_algorithm = match key.algorithm() {
                KeyAlgorithmAndDerivatives::HmacKeyAlgorithm(algorithm) => {
                    match algorithm.hash.name {
                        CryptoAlgorithm::Sha1 => "HS1",
                        CryptoAlgorithm::Sha256 => "HS256",
                        CryptoAlgorithm::Sha384 => "HS384",
                        CryptoAlgorithm::Sha512 => "HS512",
                        _ => {
                            return Err(Error::NotSupported(Some(
                                "Unsupported hash algorithm for HMAC".into(),
                            )));
                        },
                    }
                },
                _ => {
                    return Err(Error::NotSupported(Some(
                        "The key algorithm is not HMAC".into(),
                    )));
                },
            };
            jwk.alg = Some(DOMString::from(hash_algorithm));

            // Step 4.7. Set the key_ops attribute of jwk to the usages attribute of key.
            jwk.set_key_ops(key.usages());

            // Step 4.8. Set the ext attribute of jwk to the [[extractable]] internal slot of key.
            jwk.ext = Some(key.Extractable());

            // Step 4.9. Let result be jwk.
            Ok(ExportedKey::Jwk(Box::new(jwk)))
        },
        // Otherwise:
        _ => {
            // throw a NotSupportedError.
            Err(Error::NotSupported(Some(
                "Unsupported export key format for HMAC key".into(),
            )))
        },
    }
}

/// <https://w3c.github.io/webcrypto/#hmac-operations-get-key-length>
pub(crate) fn get_key_length(
    normalized_derived_key_algorithm: &SubtleHmacImportParams,
) -> Result<Option<u32>, Error> {
    // Step 1.
    let length = match normalized_derived_key_algorithm.length {
        // If the length member of normalizedDerivedKeyAlgorithm is not present:
        None => {
            // Let length be the block size in bits of the hash function identified by the hash
            // member of normalizedDerivedKeyAlgorithm.
            hash_function_block_size_in_bits(normalized_derived_key_algorithm.hash.name())?
        },
        // Otherwise, if the length member of normalizedDerivedKeyAlgorithm is non-zero:
        Some(length) if length != 0 => {
            // Let length be equal to the length member of normalizedDerivedKeyAlgorithm.
            length
        },
        // Otherwise:
        _ => {
            // throw a TypeError.
            return Err(Error::Type(c"[[length]] must not be zero".to_owned()));
        },
    };

    // Step 2. Return length.
    Ok(Some(length))
}

/// Return the block size in bits of a hash function, according to Figure 1 of
/// <https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf>.
fn hash_function_block_size_in_bits(hash: CryptoAlgorithm) -> Result<u32, Error> {
    match hash {
        CryptoAlgorithm::Sha1 => Ok(512),
        CryptoAlgorithm::Sha256 => Ok(512),
        CryptoAlgorithm::Sha384 => Ok(1024),
        CryptoAlgorithm::Sha512 => Ok(1024),
        _ => Err(Error::NotSupported(Some(
            "Unidentified hash member".to_string(),
        ))),
    }
}