/src/crypto_kdf_fuzzer.cc
Line | Count | Source |
1 | | // Copyright 2026 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 <stddef.h> |
16 | | #include <stdint.h> |
17 | | #include <string.h> |
18 | | |
19 | | #include <sodium.h> |
20 | | |
21 | 38 | extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) { |
22 | 38 | if (sodium_init() == -1) { |
23 | 0 | return 0; |
24 | 0 | } |
25 | | |
26 | 38 | if (size < crypto_kdf_KEYBYTES + 8 + 8) { |
27 | 11 | return 0; |
28 | 11 | } |
29 | | |
30 | 27 | const uint8_t *key = data; |
31 | 27 | uint64_t subkey_id; |
32 | 27 | memcpy(&subkey_id, data + crypto_kdf_KEYBYTES, 8); |
33 | | |
34 | 27 | char ctx[crypto_kdf_CONTEXTBYTES]; |
35 | 27 | memcpy(ctx, data + crypto_kdf_KEYBYTES + 8, crypto_kdf_CONTEXTBYTES > (size - (crypto_kdf_KEYBYTES + 8)) ? (size - (crypto_kdf_KEYBYTES + 8)) : crypto_kdf_CONTEXTBYTES); |
36 | 27 | if (crypto_kdf_CONTEXTBYTES > (size - (crypto_kdf_KEYBYTES + 8))) { |
37 | 0 | memset(ctx + (size - (crypto_kdf_KEYBYTES + 8)), 0, crypto_kdf_CONTEXTBYTES - (size - (crypto_kdf_KEYBYTES + 8))); |
38 | 0 | } |
39 | | |
40 | | // subkey length can be between crypto_kdf_BYTES_MIN and crypto_kdf_BYTES_MAX |
41 | 27 | size_t subkey_len = crypto_kdf_BYTES_MIN + (data[size-1] % (crypto_kdf_BYTES_MAX - crypto_kdf_BYTES_MIN + 1)); |
42 | | |
43 | 27 | unsigned char *subkey = (unsigned char *)malloc(subkey_len); |
44 | | |
45 | 27 | crypto_kdf_derive_from_key(subkey, subkey_len, subkey_id, ctx, key); |
46 | | |
47 | 27 | free(subkey); |
48 | | |
49 | 27 | return 0; |
50 | 38 | } |