/src/node/test/fuzzers/fuzz_sign_verify.cc
Line | Count | Source |
1 | | // Copyright 2025 Google LLC |
2 | | // |
3 | | // Licensed under the Apache License, Version 2.0 (the "License"); |
4 | | // you may not use this file except in compliance with the License. |
5 | | // You may obtain a copy of the License at |
6 | | // |
7 | | // http://www.apache.org/licenses/LICENSE-2.0 |
8 | | // |
9 | | // Unless required by applicable law or agreed to in writing, software |
10 | | // distributed under the License is distributed on an "AS IS" BASIS, |
11 | | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
12 | | // See the License for the specific language governing permissions and |
13 | | // limitations under the License. |
14 | | |
15 | | #include <cstdint> |
16 | | #include <string> |
17 | | #include "fuzzer/FuzzedDataProvider.h" |
18 | | #include "fuzz_common.h" |
19 | | #include "fuzz_js_format.h" |
20 | | |
21 | 10.2k | extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) { |
22 | 10.2k | FuzzedDataProvider fdp(data, size); |
23 | | |
24 | | // Use all remaining bytes as the message string |
25 | 10.2k | const std::string message = fdp.ConsumeRemainingBytesAsString(); |
26 | | |
27 | | // JS template to fuzz crypto signing/verifying using Node.js |
28 | 10.2k | static constexpr std::string_view kTemplate = R"( |
29 | 10.2k | const crypto = require('crypto'); |
30 | 10.2k | |
31 | 10.2k | // Generate an RSA key pair (per fuzz run) |
32 | 10.2k | const { privateKey, publicKey } = crypto.generateKeyPairSync('rsa', { |
33 | 10.2k | modulusLength: 2048 |
34 | 10.2k | }); |
35 | 10.2k | |
36 | 10.2k | // The fuzzed message |
37 | 10.2k | const message = {0}; |
38 | 10.2k | |
39 | 10.2k | // --- SIGNING --- |
40 | 10.2k | try { |
41 | 10.2k | const signer = crypto.createSign('SHA256'); |
42 | 10.2k | signer.update(message); |
43 | 10.2k | signer.end(); |
44 | 10.2k | const signature = signer.sign(privateKey, 'base64'); |
45 | 10.2k | |
46 | 10.2k | // --- VERIFYING --- |
47 | 10.2k | const verifier = crypto.createVerify('SHA256'); |
48 | 10.2k | verifier.update(message); |
49 | 10.2k | verifier.end(); |
50 | 10.2k | const isValid = verifier.verify(publicKey, signature, 'base64'); |
51 | 10.2k | } catch (e) { |
52 | 10.2k | // Catch errors to prevent harness crashes |
53 | 10.2k | } |
54 | 10.2k | )"; |
55 | | |
56 | | // Inject the fuzzed message into the JS template |
57 | 10.2k | const std::string js = FormatJs(kTemplate, ToSingleQuotedJsLiteral(message)); |
58 | | |
59 | | // Execute the JavaScript under a Node isolate |
60 | 10.2k | fuzz::IsolateScope iso; |
61 | 10.2k | if (!iso.ok()) return 0; |
62 | 10.2k | fuzz::RunEnvString(iso.isolate(), js.c_str()); |
63 | | |
64 | 10.2k | return 0; |
65 | 10.2k | } |