wsc 0.8.1

WebAssembly Signature Component - WASM signing and verification toolkit
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
490
use crate::signature::*;
use crate::wasm_module::*;
use crate::*;

use ct_codecs::verify as ct_eq;
use log::*;
use std::collections::{HashMap, HashSet};
use std::io::Read;
use zeroize::Zeroizing;

/// Constant-time check if a hash exists in a set of valid hashes.
/// SECURITY: Uses constant-time comparison to prevent timing attacks.
fn ct_contains_hash<T: AsRef<[u8]>>(valid_hashes: &HashSet<T>, h: &[u8]) -> bool {
    // Check all hashes to maintain constant time regardless of match position
    let mut found = false;
    for valid_hash in valid_hashes {
        if ct_eq(valid_hash.as_ref(), h) {
            found = true;
            // Don't break early - continue checking all to maintain constant time
        }
    }
    found
}

impl SecretKey {
    /// Sign a module with the secret key.
    ///
    /// If the module was already signed, the signature is replaced.
    ///
    /// `key_id` is the key identifier of the public key, to be stored with the signature.
    /// This parameter is optional.
    pub fn sign(&self, mut module: Module, key_id: Option<&Vec<u8>>) -> Result<Module, WSError> {
        let mut out_sections = vec![Section::Custom(CustomSection::default())];
        let mut hasher = Hash::new();
        for section in module.sections.into_iter() {
            if section.is_signature_header() {
                continue;
            }
            section.serialize(&mut hasher)?;
            out_sections.push(section);
        }
        let h = hasher.finalize().to_vec();

        // SECURITY: Zeroize message buffer on drop to prevent key material leakage
        let mut msg: Zeroizing<Vec<u8>> = Zeroizing::new(vec![]);
        msg.extend_from_slice(SIGNATURE_WASM_DOMAIN.as_bytes());
        msg.extend_from_slice(&[
            SIGNATURE_VERSION,
            SIGNATURE_WASM_MODULE_CONTENT_TYPE,
            SIGNATURE_HASH_FUNCTION,
        ]);
        msg.extend_from_slice(&h);

        let signature = self.sk.sign(msg.to_vec(), None).to_vec();

        let signature_for_hashes = SignatureForHashes {
            key_id: key_id.cloned(),
            alg_id: ED25519_PK_ID,
            signature,
            certificate_chain: None, // No certificates for simple signing
        };
        let signed_hashes_set = vec![SignedHashes {
            hashes: vec![h],
            signatures: vec![signature_for_hashes],
        }];
        let signature_data = SignatureData {
            specification_version: SIGNATURE_VERSION,
            content_type: SIGNATURE_WASM_MODULE_CONTENT_TYPE,
            hash_function: SIGNATURE_HASH_FUNCTION,
            signed_hashes_set,
        };
        out_sections[0] = Section::Custom(CustomSection::new(
            SIGNATURE_SECTION_HEADER_NAME.to_string(),
            signature_data.serialize()?,
        ));

        module.sections = out_sections;
        Ok(module)
    }
}

impl PublicKey {
    /// Verify a module's signature.
    ///
    /// `reader` is a reader over the raw module data.
    ///
    /// `detached_signature` allows the caller to verify a module without an embedded signature.
    ///
    /// This simplified interface verifies the entire module, with a single public key.
    pub fn verify(
        &self,
        reader: &mut impl Read,
        detached_signature: Option<&[u8]>,
    ) -> Result<(), WSError> {
        let stream = Module::init_from_reader(reader)?;
        let mut sections = Module::iterate(stream)?;

        // Read the signature header from the module, or reconstruct it from the detached signature.
        let signature_header_section = if let Some(detached_signature) = &detached_signature {
            Section::Custom(CustomSection::new(
                SIGNATURE_SECTION_HEADER_NAME.to_string(),
                detached_signature.to_vec(),
            ))
        } else {
            sections.next().ok_or(WSError::ParseError)??
        };
        let signature_header = match signature_header_section {
            Section::Custom(custom_section) if custom_section.is_signature_header() => {
                custom_section
            }
            _ => {
                debug!("This module is not signed");
                return Err(WSError::NoSignatures);
            }
        };

        // Actual signature verification starts here.
        let signature_data = signature_header.signature_data()?;
        if signature_data.hash_function != SIGNATURE_HASH_FUNCTION {
            debug!(
                "Unsupported hash function: {:02x}",
                signature_data.specification_version
            );
            return Err(WSError::ParseError);
        }

        let signed_hashes_set = signature_data.signed_hashes_set;
        let valid_hashes = self.valid_hashes_for_pk(&signed_hashes_set)?;
        if valid_hashes.is_empty() {
            debug!("No valid signatures");
            return Err(WSError::VerificationFailed);
        }

        let mut hasher = Hash::new();
        let mut buf = vec![0u8; 65536];
        loop {
            match reader.read(&mut buf)? {
                0 => break,
                n => {
                    hasher.update(&buf[..n]);
                }
            }
        }
        let h = hasher.finalize().to_vec();

        // SECURITY: Use constant-time comparison to prevent timing attacks
        if ct_contains_hash(&valid_hashes, &h) {
            Ok(())
        } else {
            Err(WSError::VerificationFailed)
        }
    }
}

impl PublicKeySet {
    /// Verify a module's signature with multiple public keys.
    ///
    /// `reader` is a reader over the raw module data.
    ///
    /// `detached_signature` allows the caller to verify a module without an embedded signature.
    ///
    /// This simplified interface verifies the entire module, with all public keys from the set.
    /// It returns the set of public keys for which a valid signature was found.
    pub fn verify(
        &self,
        reader: &mut impl Read,
        detached_signature: Option<&[u8]>,
    ) -> Result<HashSet<&PublicKey>, WSError> {
        let mut sections = Module::iterate(Module::init_from_reader(reader)?)?;

        // Read the signature header from the module, or reconstruct it from the detached signature.
        let signature_header: &Section;
        let signature_header_from_detached_signature;
        let signature_header_from_stream;
        if let Some(detached_signature) = &detached_signature {
            signature_header_from_detached_signature = Section::Custom(CustomSection::new(
                SIGNATURE_SECTION_HEADER_NAME.to_string(),
                detached_signature.to_vec(),
            ));
            signature_header = &signature_header_from_detached_signature;
        } else {
            signature_header_from_stream = sections.next().ok_or(WSError::ParseError)??;
            signature_header = &signature_header_from_stream;
        }
        let signature_header = match signature_header {
            Section::Custom(custom_section) if custom_section.is_signature_header() => {
                custom_section
            }
            _ => {
                debug!("This module is not signed");
                return Err(WSError::NoSignatures);
            }
        };

        // Actual signature verification starts here.
        let signature_data = signature_header.signature_data()?;
        if signature_data.content_type != SIGNATURE_WASM_MODULE_CONTENT_TYPE {
            debug!(
                "Unsupported content type: {:02x}",
                signature_data.content_type
            );
            return Err(WSError::ParseError);
        }
        if signature_data.hash_function != SIGNATURE_HASH_FUNCTION {
            debug!(
                "Unsupported hash function: {:02x}",
                signature_data.specification_version
            );
            return Err(WSError::ParseError);
        }
        let signed_hashes_set = signature_data.signed_hashes_set;
        let valid_hashes_for_pks: HashMap<&PublicKey, HashSet<&Vec<u8>>> = self
            .pks
            .iter()
            .filter_map(|pk| match pk.valid_hashes_for_pk(&signed_hashes_set) {
                Ok(valid_hashes) if !valid_hashes.is_empty() => Some((pk, valid_hashes)),
                _ => None,
            })
            .collect();
        if valid_hashes_for_pks.is_empty() {
            debug!("No valid signatures");
            return Err(WSError::VerificationFailed);
        }

        let mut hasher = Hash::new();
        let mut buf = vec![0u8; 65536];
        loop {
            match reader.read(&mut buf)? {
                0 => break,
                n => {
                    hasher.update(&buf[..n]);
                }
            }
        }
        let h = hasher.finalize().to_vec();
        let mut valid_pks = HashSet::new();
        for (pk, valid_hashes) in valid_hashes_for_pks {
            // SECURITY: Use constant-time comparison to prevent timing attacks
        if ct_contains_hash(&valid_hashes, &h) {
                valid_pks.insert(pk);
            }
        }
        if valid_pks.is_empty() {
            debug!("No valid signatures");
            return Err(WSError::VerificationFailed);
        }
        Ok(valid_pks)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::io::Cursor;

    fn create_test_module() -> Module {
        Module {
            header: [0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00],
            sections: vec![
                Section::Standard(StandardSection::new(SectionId::Type, vec![1, 2, 3])),
                Section::Standard(StandardSection::new(SectionId::Function, vec![4, 5, 6])),
                Section::Standard(StandardSection::new(SectionId::Code, vec![7, 8, 9])),
            ],
        }
    }

    fn serialize_module(module: &Module) -> Vec<u8> {
        let mut buffer = Vec::new();
        module.serialize(&mut buffer).unwrap();
        buffer
    }

    #[test]
    fn test_sign_module() {
        let kp = KeyPair::generate();
        let module = create_test_module();

        let signed_module = kp.sk.sign(module, None).unwrap();

        // First section should be signature
        assert!(signed_module.sections[0].is_signature_header());
    }

    #[test]
    fn test_sign_module_with_key_id() {
        let kp = KeyPair::generate();
        let module = create_test_module();
        let key_id = vec![1, 2, 3, 4];

        let signed_module = kp.sk.sign(module, Some(&key_id)).unwrap();

        // Verify signature header exists
        assert!(signed_module.sections[0].is_signature_header());
    }

    #[test]
    fn test_sign_replaces_existing_signature() {
        let kp = KeyPair::generate();
        let module = create_test_module();

        // Sign once
        let signed_module = kp.sk.sign(module, None).unwrap();

        // Sign again - should replace signature
        let signed_module2 = kp.sk.sign(signed_module, None).unwrap();

        // Should still have only one signature header
        let sig_headers: Vec<_> = signed_module2
            .sections
            .iter()
            .filter(|s| s.is_signature_header())
            .collect();
        assert_eq!(sig_headers.len(), 1);
    }

    #[test]
    fn test_verify_signed_module() {
        let kp = KeyPair::generate();
        let module = create_test_module();

        let signed_module = kp.sk.sign(module, None).unwrap();
        let signed_bytes = serialize_module(&signed_module);

        let mut reader = Cursor::new(signed_bytes);
        let result = kp.pk.verify(&mut reader, None);
        assert!(result.is_ok());
    }

    #[test]
    fn test_verify_unsigned_module() {
        let kp = KeyPair::generate();
        let module = create_test_module();
        let unsigned_bytes = serialize_module(&module);

        let mut reader = Cursor::new(unsigned_bytes);
        let result = kp.pk.verify(&mut reader, None);
        assert!(result.is_err());
        assert!(matches!(result.unwrap_err(), WSError::NoSignatures));
    }

    #[test]
    fn test_verify_with_wrong_key() {
        let kp1 = KeyPair::generate();
        let kp2 = KeyPair::generate();
        let module = create_test_module();

        // Sign with key 1
        let signed_module = kp1.sk.sign(module, None).unwrap();
        let signed_bytes = serialize_module(&signed_module);

        // Try to verify with key 2
        let mut reader = Cursor::new(signed_bytes);
        let result = kp2.pk.verify(&mut reader, None);
        assert!(result.is_err());
        assert!(matches!(result.unwrap_err(), WSError::VerificationFailed));
    }

    #[test]
    fn test_verify_with_detached_signature() {
        let kp = KeyPair::generate();
        let module = create_test_module();

        // Sign and detach
        let signed_module = kp.sk.sign(module, None).unwrap();
        let (unsigned_module, detached_sig) = signed_module.detach_signature().unwrap();
        let unsigned_bytes = serialize_module(&unsigned_module);

        // Verify with detached signature
        let mut reader = Cursor::new(unsigned_bytes);
        let result = kp.pk.verify(&mut reader, Some(&detached_sig));
        assert!(result.is_ok());
    }

    #[test]
    fn test_public_key_set_verify() {
        let kp1 = KeyPair::generate();
        let kp2 = KeyPair::generate();
        let module = create_test_module();

        // Sign with key 1
        let signed_module = kp1.sk.sign(module, None).unwrap();
        let signed_bytes = serialize_module(&signed_module);

        // Create a key set with both keys
        let mut key_set = PublicKeySet::empty();
        key_set.insert(kp1.pk.clone()).unwrap();
        key_set.insert(kp2.pk).unwrap();

        // Verify - should find key 1
        let mut reader = Cursor::new(signed_bytes);
        let result = key_set.verify(&mut reader, None);
        assert!(result.is_ok());
        let valid_pks = result.unwrap();
        assert_eq!(valid_pks.len(), 1);
        assert!(valid_pks.contains(&kp1.pk));
    }

    #[test]
    fn test_public_key_set_verify_unsigned() {
        let kp = KeyPair::generate();
        let module = create_test_module();
        let unsigned_bytes = serialize_module(&module);

        let mut key_set = PublicKeySet::empty();
        key_set.insert(kp.pk).unwrap();

        let mut reader = Cursor::new(unsigned_bytes);
        let result = key_set.verify(&mut reader, None);
        assert!(result.is_err());
        assert!(matches!(result.unwrap_err(), WSError::NoSignatures));
    }

    #[test]
    fn test_public_key_set_verify_no_matching_keys() {
        let kp1 = KeyPair::generate();
        let kp2 = KeyPair::generate();
        let module = create_test_module();

        // Sign with key 1
        let signed_module = kp1.sk.sign(module, None).unwrap();
        let signed_bytes = serialize_module(&signed_module);

        // Create key set with only key 2 (different)
        let mut key_set = PublicKeySet::empty();
        key_set.insert(kp2.pk).unwrap();

        let mut reader = Cursor::new(signed_bytes);
        let result = key_set.verify(&mut reader, None);
        assert!(result.is_err());
        assert!(matches!(result.unwrap_err(), WSError::VerificationFailed));
    }

    #[test]
    fn test_public_key_set_verify_with_detached_signature() {
        let kp = KeyPair::generate();
        let module = create_test_module();

        // Sign and detach
        let signed_module = kp.sk.sign(module, None).unwrap();
        let (unsigned_module, detached_sig) = signed_module.detach_signature().unwrap();
        let unsigned_bytes = serialize_module(&unsigned_module);

        let mut key_set = PublicKeySet::empty();
        key_set.insert(kp.pk.clone()).unwrap();

        // Verify with detached signature
        let mut reader = Cursor::new(unsigned_bytes);
        let result = key_set.verify(&mut reader, Some(&detached_sig));
        assert!(result.is_ok());
        let valid_pks = result.unwrap();
        assert_eq!(valid_pks.len(), 1);
    }

    #[test]
    fn test_sign_verify_roundtrip() {
        let kp = KeyPair::generate();
        let module = create_test_module();

        // Sign
        let signed_module = kp.sk.sign(module, None).unwrap();

        // Serialize
        let signed_bytes = serialize_module(&signed_module);

        // Verify
        let mut reader = Cursor::new(signed_bytes);
        let result = kp.pk.verify(&mut reader, None);
        assert!(result.is_ok());
    }

    #[test]
    fn test_sign_with_modified_module_fails() {
        let kp = KeyPair::generate();
        let module = create_test_module();

        // Sign
        let signed_module = kp.sk.sign(module, None).unwrap();
        let mut signed_bytes = serialize_module(&signed_module);

        // Modify the signed bytes (corrupt the module)
        if signed_bytes.len() > 50 {
            signed_bytes[50] ^= 0xFF;
        }

        // Verify should fail
        let mut reader = Cursor::new(signed_bytes);
        let result = kp.pk.verify(&mut reader, None);
        assert!(result.is_err());
    }
}