/*1* Copyright 2025 The OpenSSL Project Authors. All Rights Reserved.2*3* Licensed under the Apache License 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 at6* https://www.openssl.org/source/license.html7* or in the file LICENSE in the source distribution.8*/910/*11* Test ml-kem operation.12*/13#include <string.h>14#include <openssl/evp.h>15#include <openssl/err.h>16#include <openssl/rand.h>17#include <openssl/byteorder.h>18#include <openssl/ml_kem.h>19#include "internal/nelem.h"20#include "fuzzer.h"2122/**23* @brief Consumes an 8-bit unsigned integer from a buffer.24*25* This function extracts an 8-bit unsigned integer from the provided buffer,26* updates the buffer pointer, and adjusts the remaining length.27*28* @param buf Pointer to the input buffer.29* @param len Pointer to the size of the remaining buffer; updated after consumption.30* @param val Pointer to store the extracted 8-bit value.31*32* @return Pointer to the updated buffer position after reading the value,33* or NULL if the buffer does not contain enough data.34*/35static uint8_t *consume_uint8t(const uint8_t *buf, size_t *len, uint8_t *val)36{37if (*len < sizeof(uint8_t))38return NULL;39*val = *buf;40*len -= sizeof(uint8_t);41return (uint8_t *)buf + 1;42}4344/**45* @brief Selects a key type and size from a buffer.46*47* This function reads a key size value from the buffer, determines the48* corresponding key type and length, and updates the buffer pointer49* accordingly. If `only_valid` is set, it restricts selection to valid50* key sizes; otherwise, it includes some invalid sizes for testing.51*52* @param buf Pointer to the buffer pointer; updated after reading.53* @param len Pointer to the remaining buffer size; updated accordingly.54* @param keytype Pointer to store the selected key type string.55* @param keylen Pointer to store the selected key length.56* @param only_valid Flag to restrict selection to valid key sizes.57*58* @return 1 if a key type is successfully selected, 0 on failure.59*/60static int select_keytype_and_size(uint8_t **buf, size_t *len,61char **keytype, size_t *keylen,62int only_valid)63{64uint16_t keysize;65uint16_t modulus = 6;6667/*68* Note: We don't really care about endianess here, we just69* want a random 16 bit value70*/71*buf = (uint8_t *)OPENSSL_load_u16_le(&keysize, *buf);72*len -= sizeof(uint16_t);7374if (*buf == NULL)75return 0;7677/*78* select from sizes79* ML-KEM-512, ML-KEM-768, and ML-KEM-102480* also select some invalid sizes to trigger81* error paths82*/83if (only_valid)84modulus = 3;8586/*87* Note, keylens for valid values (cases 0-2)88* are taken based on input values from our unit tests89*/90switch (keysize % modulus) {91case 0:92*keytype = "ML-KEM-512";93*keylen = OSSL_ML_KEM_512_PUBLIC_KEY_BYTES;94break;95case 1:96*keytype = "ML-KEM-768";97*keylen = OSSL_ML_KEM_768_PUBLIC_KEY_BYTES;98break;99case 2:100*keytype = "ML-KEM-1024";101*keylen = OSSL_ML_KEM_1024_PUBLIC_KEY_BYTES;102break;103case 3:104/* select invalid alg */105*keytype = "ML-KEM-13";106*keylen = 13;107break;108case 4:109/* Select valid alg, but bogus size */110*keytype = "ML-KEM-1024";111*buf = (uint8_t *)OPENSSL_load_u16_le(&keysize, *buf);112*len -= sizeof(uint16_t);113*keylen = (size_t)keysize;114*keylen %= 1024; /* size to our key buffer */115break;116default:117*keytype = NULL;118*keylen = 0;119break;120}121return 1;122}123124/**125* @brief Creates an ML-KEM raw key from a buffer.126*127* This function selects a key type and size from the buffer, generates128* a random key of the appropriate length, and creates either a public129* or private ML-KEM key using OpenSSL's EVP_PKEY interface.130*131* @param buf Pointer to the buffer pointer; updated after reading.132* @param len Pointer to the remaining buffer size; updated accordingly.133* @param key1 Pointer to store the generated EVP_PKEY key (public or private).134* @param key2 Unused parameter (reserved for future use).135*136* @note The generated key is allocated using OpenSSL's EVP_PKEY functions137* and should be freed appropriately using `EVP_PKEY_free()`.138*/139static void create_mlkem_raw_key(uint8_t **buf, size_t *len,140void **key1, void **key2)141{142EVP_PKEY *pubkey;143char *keytype = NULL;144size_t keylen = 0;145uint8_t key[4096];146int pub = 0;147148if (!select_keytype_and_size(buf, len, &keytype, &keylen, 0))149return;150151/*152* Select public or private key creation based on the low order153* bit of the next buffer value154* Note that keylen as returned from select_keytype_and_size is155* a public key length, private keys for ML-KEM are always double156* the size plus 32, so make that adjustment here157*/158if ((*buf)[0] & 0x1)159pub = 1;160else161keylen = (keylen * 2) + 32;162163/*164* libfuzzer provides by default up to 4096 bit input165* buffers, but its typically much less (between 1 and 100 bytes)166* so use RAND_bytes here instead167*/168if (!RAND_bytes(key, keylen))169return;170171/*172* Try to generate either a raw public or private key using random data173* Because the input is completely random, its effectively certain this174* operation will fail, but it will still exercise the code paths below,175* which is what we want the fuzzer to do176*/177if (pub == 1)178pubkey = EVP_PKEY_new_raw_public_key_ex(NULL, keytype, NULL, key, keylen);179else180pubkey = EVP_PKEY_new_raw_private_key_ex(NULL, keytype, NULL, key, keylen);181182*key1 = pubkey;183return;184}185186/**187* @brief Generates a valid ML-KEM key using OpenSSL.188*189* This function selects a valid ML-KEM key type and size from the buffer,190* initializes an OpenSSL EVP_PKEY context, and generates a cryptographic191* key accordingly.192*193* @param buf Pointer to the buffer pointer; updated after reading.194* @param len Pointer to the remaining buffer size; updated accordingly.195* @param key1 Pointer to store the generated EVP_PKEY key.196* @param unused Unused parameter (reserved for future use).197*198* @note The generated key is allocated using OpenSSL's EVP_PKEY functions199* and should be freed using `EVP_PKEY_free()`.200*/201static void keygen_mlkem_real_key(uint8_t **buf, size_t *len,202void **key1, void **key2)203{204char *keytype = NULL;205size_t keylen = 0;206EVP_PKEY_CTX *ctx = NULL;207EVP_PKEY **key;208209*key1 = *key2 = NULL;210211key = (EVP_PKEY **)key1;212213again:214/*215* Only generate valid key types and lengths216* Note, no adjustment is made to keylen here, as217* the provider is responsible for selecting the keys and sizes218* for us during the EVP_PKEY_keygen call219*/220if (!select_keytype_and_size(buf, len, &keytype, &keylen, 1))221return;222223ctx = EVP_PKEY_CTX_new_from_name(NULL, keytype, NULL);224if (!ctx) {225fprintf(stderr, "Failed to generate ctx\n");226return;227}228229if (!EVP_PKEY_keygen_init(ctx)) {230fprintf(stderr, "Failed to init keygen ctx\n");231goto err;232}233234*key = EVP_PKEY_new();235if (*key == NULL)236goto err;237238if (!EVP_PKEY_generate(ctx, key)) {239fprintf(stderr, "Failed to generate new real key\n");240goto err;241}242243if (key == (EVP_PKEY **)key1) {244EVP_PKEY_CTX_free(ctx);245key = (EVP_PKEY **)key2;246goto again;247}248249err:250EVP_PKEY_CTX_free(ctx);251return;252}253254/**255* @brief Performs key encapsulation and decapsulation using an EVP_PKEY.256*257* This function generates a random key, encapsulates it using the provided258* public key, then decapsulates it to retrieve the original key. It makes259* use of OpenSSL's EVP_PKEY API for encryption and decryption.260*261* @param[out] buf Unused output buffer (reserved for future use).262* @param[out] len Unused length parameter (reserved for future use).263* @param[in] key1 Pointer to an EVP_PKEY structure used for key operations.264* @param[in] in2 Unused input parameter (reserved for future use).265* @param[out] out1 Unused output parameter (reserved for future use).266* @param[out] out2 Unused output parameter (reserved for future use).267*/268static void mlkem_encap_decap(uint8_t **buf, size_t *len, void *key1, void *in2,269void **out1, void **out2)270{271EVP_PKEY *key = (EVP_PKEY *)key1;272EVP_PKEY_CTX *ctx;273unsigned char genkey[32];274size_t genkey_len = 32;275unsigned char unwrappedkey[32];276size_t unwrappedkey_len = 32;277unsigned char wrapkey[1568];278size_t wrapkey_len = 1568;279280ctx = EVP_PKEY_CTX_new_from_pkey(NULL, key, NULL);281if (ctx == NULL) {282fprintf(stderr, "Failed to allocate ctx\n");283goto err;284}285286if (!EVP_PKEY_encapsulate_init(ctx, NULL)) {287fprintf(stderr, "Failed to init encap context\n");288goto err;289}290291if (!RAND_bytes(genkey, genkey_len))292goto err;293294if (EVP_PKEY_encapsulate(ctx, wrapkey, &wrapkey_len, genkey, &genkey_len) <= 0) {295fprintf(stderr, "Failed to encapsulate key\n");296goto err;297}298299EVP_PKEY_CTX_free(ctx);300ctx = EVP_PKEY_CTX_new_from_pkey(NULL, key, NULL);301if (ctx == NULL) {302fprintf(stderr, "Failed to create context\n");303goto err;304}305306if (!EVP_PKEY_decapsulate_init(ctx, NULL)) {307fprintf(stderr, "Failed to init decap\n");308goto err;309}310311if (EVP_PKEY_decapsulate(ctx, unwrappedkey, &unwrappedkey_len,312wrapkey, wrapkey_len) <= 0) {313fprintf(stderr, "Failed to decap key\n");314goto err;315}316317if (memcmp(unwrappedkey, genkey, genkey_len))318fprintf(stderr, "mismatch on secret comparison\n");319err:320EVP_PKEY_CTX_free(ctx);321return;322}323324/**325* @brief Derives a shared secret using the provided key and peer key.326*327* This function performs a key derivation operation using the given328* private key and peer public key. The resulting shared secret is329* allocated dynamically and must be freed by the caller.330*331* @param[in] key The private key used for derivation.332* @param[in] peer The peer's public key.333* @param[out] shared Pointer to the derived shared secret (allocated).334* @param[out] shared_len Length of the derived shared secret.335*336* @note The caller is responsible for freeing the memory allocated337* for `shared` using `OPENSSL_free()`.338*/339static void do_derive(EVP_PKEY *key, EVP_PKEY *peer, uint8_t **shared, size_t *shared_len)340{341EVP_PKEY_CTX *ctx = NULL;342343*shared = NULL;344*shared_len = 0;345346ctx = EVP_PKEY_CTX_new_from_pkey(NULL, key, NULL);347if (ctx == NULL) {348fprintf(stderr, "failed to create keygen context\n");349goto err;350}351352if (!EVP_PKEY_derive_init(ctx)) {353fprintf(stderr, "failed to init derive context\n");354goto err;355}356357if (!EVP_PKEY_derive_set_peer(ctx, peer)) {358fprintf(stderr, "failed to set peer\n");359goto err;360}361362if (!EVP_PKEY_derive(ctx, NULL, shared_len)) {363fprintf(stderr, "Derive failed 1\n");364goto err;365}366367if (*shared_len == 0)368goto err;369370*shared = OPENSSL_zalloc(*shared_len);371if (*shared == NULL) {372fprintf(stderr, "Failed to alloc\n");373goto err;374}375if (!EVP_PKEY_derive(ctx, *shared, shared_len)) {376fprintf(stderr, "Derive failed 2\n");377OPENSSL_free(*shared);378*shared = NULL;379*shared_len = 0;380goto err;381}382err:383EVP_PKEY_CTX_free(ctx);384}385386/**387* @brief Performs a key exchange using ML-KEM.388*389* This function derives shared secrets using the provided key pairs.390* It calls `do_derive()` to compute shared secrets for both participants391* and frees the allocated memory for the shared secrets.392*393* @param[out] buf Unused output buffer (reserved for future use).394* @param[out] len Unused output length (reserved for future use).395* @param[in] key1 First key (typically Alice's key).396* @param[in] key2 Second key (typically Bob's key).397* @param[out] out1 Unused output parameter (reserved for future use).398* @param[out] out2 Unused output parameter (reserved for future use).399*400* @note Currently, this function does not validate whether the derived401* shared secrets match. A check should be added when ML-KEM402* supports this.403*/404static void mlkem_kex(uint8_t **buf, size_t *len, void *key1, void *key2,405void **out1, void **out2)406{407EVP_PKEY *alice = (EVP_PKEY *)key1;408EVP_PKEY *bob = (EVP_PKEY *)key2;409size_t boblen, alicelen;410uint8_t *bobshare = NULL;411uint8_t *aliceshare = NULL;412413do_derive(alice, bob, &aliceshare, &alicelen);414do_derive(bob, alice, &bobshare, &boblen);415416/*417* TODO add check of shared secrets here when ML-KEM supports this418*/419OPENSSL_free(bobshare);420OPENSSL_free(aliceshare);421}422423/**424* @brief Exports and imports an ML-KEM key.425*426* This function extracts key material from the given key (`key1`),427* exports it as parameters, and then attempts to reconstruct a new428* key from those parameters. It uses OpenSSL's `EVP_PKEY_todata()`429* and `EVP_PKEY_fromdata()` functions for this process.430*431* @param[out] buf Unused output buffer (reserved for future use).432* @param[out] len Unused output length (reserved for future use).433* @param[in] key1 The key to be exported and imported.434* @param[in] key2 Unused input key (reserved for future use).435* @param[out] out1 Unused output parameter (reserved for future use).436* @param[out] out2 Unused output parameter (reserved for future use).437*438* @note If any step in the export-import process fails, the function439* logs an error and cleans up allocated resources.440*/441static void mlkem_export_import(uint8_t **buf, size_t *len, void *key1,442void *key2, void **out1, void **out2)443{444EVP_PKEY *alice = (EVP_PKEY *)key1;445EVP_PKEY *new = NULL;446EVP_PKEY_CTX *ctx = NULL;447OSSL_PARAM *params = NULL;448449if (!EVP_PKEY_todata(alice, EVP_PKEY_KEYPAIR, ¶ms)) {450fprintf(stderr, "Failed todata\n");451goto err;452}453454ctx = EVP_PKEY_CTX_new_from_pkey(NULL, alice, NULL);455if (ctx == NULL) {456fprintf(stderr, "Failed new ctx\n");457goto err;458}459460if (!EVP_PKEY_fromdata(ctx, &new, EVP_PKEY_KEYPAIR, params)) {461fprintf(stderr, "Failed fromdata\n");462goto err;463}464465err:466EVP_PKEY_CTX_free(ctx);467EVP_PKEY_free(new);468OSSL_PARAM_free(params);469}470471/**472* @brief Compares two cryptographic keys and performs equality checks.473*474* This function takes in two cryptographic keys, casts them to `EVP_PKEY`475* structures, and checks their equality using `EVP_PKEY_eq()`. The purpose476* of `buf`, `len`, `out1`, and `out2` parameters is not clear from the477* function's current implementation.478*479* @param buf Unused parameter (purpose unclear).480* @param len Unused parameter (purpose unclear).481* @param key1 First key, expected to be an `EVP_PKEY *`.482* @param key2 Second key, expected to be an `EVP_PKEY *`.483* @param out1 Unused parameter (purpose unclear).484* @param out2 Unused parameter (purpose unclear).485*/486static void mlkem_compare(uint8_t **buf, size_t *len, void *key1,487void *key2, void **out1, void **out2)488{489EVP_PKEY *alice = (EVP_PKEY *)key1;490EVP_PKEY *bob = (EVP_PKEY *)key2;491492EVP_PKEY_eq(alice, alice);493EVP_PKEY_eq(alice, bob);494}495496/**497* @brief Frees allocated ML-KEM keys.498*499* This function releases memory associated with up to four EVP_PKEY500* objects by calling `EVP_PKEY_free()` on each provided key.501*502* @param key1 Pointer to the first key to be freed.503* @param key2 Pointer to the second key to be freed.504* @param key3 Pointer to the third key to be freed.505* @param key4 Pointer to the fourth key to be freed.506*507* @note This function assumes that each key is either a valid EVP_PKEY508* object or NULL. Passing NULL is safe and has no effect.509*/510static void cleanup_mlkem_keys(void *key1, void *key2,511void *key3, void *key4)512{513EVP_PKEY_free((EVP_PKEY *)key1);514EVP_PKEY_free((EVP_PKEY *)key2);515EVP_PKEY_free((EVP_PKEY *)key3);516EVP_PKEY_free((EVP_PKEY *)key4);517return;518}519520/**521* @brief Represents an operation table entry for cryptographic operations.522*523* This structure defines a table entry containing function pointers for524* setting up, executing, and cleaning up cryptographic operations, along525* with associated metadata such as a name and description.526*527* @struct op_table_entry528*/529struct op_table_entry {530/** Name of the operation. */531char *name;532533/** Description of the operation. */534char *desc;535536/**537* @brief Function pointer for setting up the operation.538*539* @param buf Pointer to the buffer pointer; may be updated.540* @param len Pointer to the remaining buffer size; may be updated.541* @param out1 Pointer to store the first output of the setup function.542* @param out2 Pointer to store the second output of the setup function.543*/544void (*setup)(uint8_t **buf, size_t *len, void **out1, void **out2);545546/**547* @brief Function pointer for executing the operation.548*549* @param buf Pointer to the buffer pointer; may be updated.550* @param len Pointer to the remaining buffer size; may be updated.551* @param in1 First input parameter for the operation.552* @param in2 Second input parameter for the operation.553* @param out1 Pointer to store the first output of the operation.554* @param out2 Pointer to store the second output of the operation.555*/556void (*doit)(uint8_t **buf, size_t *len, void *in1, void *in2,557void **out1, void **out2);558559/**560* @brief Function pointer for cleaning up after the operation.561*562* @param in1 First input parameter to be cleaned up.563* @param in2 Second input parameter to be cleaned up.564* @param out1 First output parameter to be cleaned up.565* @param out2 Second output parameter to be cleaned up.566*/567void (*cleanup)(void *in1, void *in2, void *out1, void *out2);568};569570static struct op_table_entry ops[] = {571{572"Generate ML-KEM raw key",573"Try generate a raw keypair using random data. Usually fails",574create_mlkem_raw_key,575NULL,576cleanup_mlkem_keys577}, {578"Generate ML-KEM keypair, using EVP_PKEY_keygen",579"Generates a real ML-KEM keypair, should always work",580keygen_mlkem_real_key,581NULL,582cleanup_mlkem_keys583}, {584"Do a key encap/decap operation on a key",585"Generate key, encap it, decap it and compare, should work",586keygen_mlkem_real_key,587mlkem_encap_decap,588cleanup_mlkem_keys589}, {590"Do a key exchange operation on two keys",591"Gen keys, do a key exchange both ways and compare",592keygen_mlkem_real_key,593mlkem_kex,594cleanup_mlkem_keys595}, {596"Do an export/import of key data",597"Exercise EVP_PKEY_todata/fromdata",598keygen_mlkem_real_key,599mlkem_export_import,600cleanup_mlkem_keys601}, {602"Compare keys for equality",603"Compare key1/key1 and key1/key2 for equality",604keygen_mlkem_real_key,605mlkem_compare,606cleanup_mlkem_keys607}608};609610int FuzzerInitialize(int *argc, char ***argv)611{612return 0;613}614615/**616* @brief Processes a fuzzing input by selecting and executing an operation.617*618* This function interprets the first byte of the input buffer to determine619* an operation to execute. It then follows a setup, execution, and cleanup620* sequence based on the selected operation.621*622* @param buf Pointer to the input buffer.623* @param len Length of the input buffer.624*625* @return 0 on successful execution, -1 if the input is too short.626*627* @note The function requires at least 32 bytes in the buffer to proceed.628* It utilizes the `ops` operation table to dynamically determine and629* execute the selected operation.630*/631int FuzzerTestOneInput(const uint8_t *buf, size_t len)632{633uint8_t operation;634uint8_t *buffer_cursor;635void *in1 = NULL, *in2 = NULL;636void *out1 = NULL, *out2 = NULL;637638if (len < 32)639return -1;640/*641* Get the first byte of the buffer to tell us what operation642* to preform643*/644buffer_cursor = consume_uint8t(buf, &len, &operation);645if (buffer_cursor == NULL)646return -1;647648/*649* Adjust for operational array size650*/651operation %= OSSL_NELEM(ops);652653/*654* And run our setup/doit/cleanup sequence655*/656if (ops[operation].setup != NULL)657ops[operation].setup(&buffer_cursor, &len, &in1, &in2);658if (ops[operation].doit != NULL)659ops[operation].doit(&buffer_cursor, &len, in1, in2, &out1, &out2);660if (ops[operation].cleanup != NULL)661ops[operation].cleanup(in1, in2, out1, out2);662663return 0;664}665666void FuzzerCleanup(void)667{668OPENSSL_cleanup();669}670671672