/*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 slh-dsa 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/core_names.h>19#include "crypto/slh_dsa.h"20#include "internal/nelem.h"21#include "fuzzer.h"2223/**24* @brief Consumes an 8-bit unsigned integer from a buffer.25*26* This function extracts an 8-bit unsigned integer from the provided buffer,27* updates the buffer pointer, and adjusts the remaining length.28*29* @param buf Pointer to the input buffer.30* @param len Pointer to the size of the remaining buffer; updated after consumption.31* @param val Pointer to store the extracted 8-bit value.32*33* @return Pointer to the updated buffer position after reading the value,34* or NULL if the buffer does not contain enough data.35*/36static uint8_t *consume_uint8t(const uint8_t *buf, size_t *len, uint8_t *val)37{38if (*len < sizeof(uint8_t))39return NULL;40*val = *buf;41*len -= sizeof(uint8_t);42return (uint8_t *)buf + 1;43}4445/**46* @brief Generates a DSA key pair using OpenSSL EVP API.47*48* This function creates a DSA key pair based on the specified key size and49* parameters. It supports generating keys using explicit parameters if provided.50*51* @param name The name of the key type (e.g., "DSA").52* @param keysize The desired key size in bits.53* @param params Optional OpenSSL parameters for key generation.54* @param param_broken A flag indicating if the parameters are broken.55* If true, key generation will fail.56*57* @return A pointer to the generated EVP_PKEY structure on success,58* or NULL on failure.59*/60static EVP_PKEY *slh_dsa_gen_key(const char *name, uint32_t keysize,61OSSL_PARAM params[], uint8_t *param_broken)62{63EVP_PKEY_CTX *ctx;64EVP_PKEY *new = NULL;65int rc;6667ctx = EVP_PKEY_CTX_new_from_name(NULL, name, NULL);68OPENSSL_assert(ctx != NULL);69if (params != NULL) {70new = EVP_PKEY_new();71OPENSSL_assert(EVP_PKEY_fromdata_init(ctx));72if (*param_broken) {73rc = EVP_PKEY_fromdata(ctx, &new, EVP_PKEY_KEYPAIR, params);74OPENSSL_assert(rc == 0);75EVP_PKEY_free(new);76new = NULL;77} else {78OPENSSL_assert(EVP_PKEY_fromdata(ctx, &new, EVP_PKEY_KEYPAIR, params) == 1);79}80goto out;81}8283OPENSSL_assert(EVP_PKEY_keygen_init(ctx));84OPENSSL_assert(EVP_PKEY_generate(ctx, &new));8586out:87EVP_PKEY_CTX_free(ctx);88return new;89}9091/**92* @brief Selects a key type and determines the key size.93*94* This function maps a selector value to a specific SLH-DSA algorithm95* using a modulo operation. It then retrieves the corresponding96* algorithm name and assigns an appropriate key size based on the97* selected algorithm.98*99* @param selector A random selector value used to determine the key type.100* @param keysize Pointer to a variable where the determined key size101* (in bytes) will be stored.102*103* @return A pointer to a string containing the long name of the104* selected key type, or NULL if invalid.105*/106static const char *select_keytype(uint8_t selector, uint32_t *keysize)107{108unsigned int choice;109const char *name = NULL;110111*keysize = 0;112/*113* There are 12 SLH-DSA algs with registered NIDS at the moment114* So use our random selector value to get one of them by computing115* its modulo 12 value and adding the offset of the first NID, 1460116* Then convert that to a long name117*/118choice = (selector % 12) + 1460;119120name = OBJ_nid2ln(choice);121122/*123* Select a keysize, values taken from124* man7/EVP_PKEY-SLH-DSA.pod125*/126switch (choice) {127case NID_SLH_DSA_SHA2_128s:128case NID_SLH_DSA_SHA2_128f:129case NID_SLH_DSA_SHAKE_128s:130case NID_SLH_DSA_SHAKE_128f:131*keysize = 16;132break;133case NID_SLH_DSA_SHA2_192s:134case NID_SLH_DSA_SHA2_192f:135case NID_SLH_DSA_SHAKE_192s:136case NID_SLH_DSA_SHAKE_192f:137*keysize = 24;138break;139case NID_SLH_DSA_SHA2_256s:140case NID_SLH_DSA_SHA2_256f:141case NID_SLH_DSA_SHAKE_256s:142case NID_SLH_DSA_SHAKE_256f:143*keysize = 32;144break;145default:146fprintf(stderr, "Selecting invalid key size\n");147*keysize = 0;148break;149}150return name;151}152153/**154* @brief Generates two SLH-DSA key pairs based on consumed selector values.155*156* This function extracts two selector values from the provided buffer,157* determines the corresponding key types and sizes, and generates two158* SLH-DSA key pairs.159*160* @param buf Pointer to a buffer containing selector values. The buffer161* pointer is updated as values are consumed.162* @param len Pointer to the remaining buffer length, updated as values163* are consumed.164* @param out1 Pointer to store the first generated key.165* @param out2 Pointer to store the second generated key.166*/167static void slh_dsa_gen_keys(uint8_t **buf, size_t *len,168void **out1, void **out2)169{170uint8_t selector = 0;171const char *keytype = NULL;172uint32_t keysize;173174*buf = consume_uint8t(*buf, len, &selector);175keytype = select_keytype(selector, &keysize);176*out1 = (void *)slh_dsa_gen_key(keytype, keysize, NULL, 0);177178*buf = consume_uint8t(*buf, len, &selector);179keytype = select_keytype(selector, &keysize);180*out2 = (void *)slh_dsa_gen_key(keytype, keysize, NULL, 0);181return;182}183184#define PARAM_BUF_SZ 256185186/**187* @brief Generates an SLH-DSA key pair with custom parameters.188*189* This function extracts a selector value from the provided buffer,190* determines the corresponding key type and size, and generates an191* SLH-DSA key pair using randomly generated public and private key192* buffers. It also introduces intentional modifications to test193* invalid parameter handling.194*195* @param buf Pointer to a buffer containing the selector value. The196* buffer pointer is updated as values are consumed.197* @param len Pointer to the remaining buffer length, updated as values198* are consumed.199* @param out1 Pointer to store the generated key. Will be NULL if key200* generation fails due to invalid parameters.201* @param out2 Unused output parameter (placeholder for symmetry with202* other key generation functions).203*/204static void slh_dsa_gen_key_with_params(uint8_t **buf, size_t *len,205void **out1, void **out2)206{207uint8_t selector = 0;208const char *keytype = NULL;209uint32_t keysize;210uint8_t pubbuf[PARAM_BUF_SZ]; /* expressly bigger than max key size * 3 */211uint8_t prvbuf[PARAM_BUF_SZ]; /* expressly bigger than max key size * 3 */212uint8_t sdbuf[PARAM_BUF_SZ]; /* expressly bigger than max key size * 3 */213uint8_t *bufptr;214OSSL_PARAM params[3];215size_t buflen;216uint8_t broken = 0;217218*out1 = NULL;219220*buf = consume_uint8t(*buf, len, &selector);221keytype = select_keytype(selector, &keysize);222223RAND_bytes(pubbuf, PARAM_BUF_SZ);224RAND_bytes(prvbuf, PARAM_BUF_SZ);225RAND_bytes(sdbuf, PARAM_BUF_SZ);226227/*228* select an invalid length if the buffer 0th bit is one229* make it too big if the 2nd bit is 0, smaller otherwise230*/231buflen = keysize * 2; /* these params are 2 * the keysize */232if ((*buf)[0] & 0x1) {233buflen = ((*buf)[0] & 0x2) ? buflen - 1 : buflen + 1;234broken = 1;235}236237/* pass a null buffer if the third bit of the buffer is 1 */238bufptr = ((*buf)[0] & 0x4) ? NULL : pubbuf;239if (!broken)240broken = (bufptr == NULL) ? 1 : 0;241242params[0] = OSSL_PARAM_construct_octet_string(OSSL_PKEY_PARAM_PUB_KEY,243(char *)bufptr, buflen);244245buflen = keysize * 2;246/* select an invalid length if the 4th bit is true */247if ((*buf)[0] & 0x8) {248buflen = (*buf[0] & 0x1) ? buflen - 1 : buflen + 1;249broken = 1;250}251252/* pass a null buffer if the 5th bit is true */253bufptr = ((*buf)[0] & 0x10) ? NULL : prvbuf;254if (!broken)255broken = (bufptr == NULL) ? 1 : 0;256params[1] = OSSL_PARAM_construct_octet_string(OSSL_PKEY_PARAM_PRIV_KEY,257(char *)bufptr, buflen);258259params[2] = OSSL_PARAM_construct_end();260261*out1 = (void *)slh_dsa_gen_key(keytype, keysize, params, &broken);262263if (broken)264OPENSSL_assert(*out1 == NULL);265else266OPENSSL_assert(*out1 != NULL);267return;268}269270/**271* @brief Frees allocated SLH-DSA key structures.272*273* This function releases memory allocated for SLH-DSA key pairs274* by freeing the provided EVP_PKEY structures.275*276* @param in1 Pointer to the first input key to be freed.277* @param in2 Pointer to the second input key to be freed.278* @param out1 Pointer to the first output key to be freed.279* @param out2 Pointer to the second output key to be freed.280*/281static void slh_dsa_clean_keys(void *in1, void *in2, void *out1, void *out2)282{283EVP_PKEY_free((EVP_PKEY *)in1);284EVP_PKEY_free((EVP_PKEY *)in2);285EVP_PKEY_free((EVP_PKEY *)out1);286EVP_PKEY_free((EVP_PKEY *)out2);287}288289/**290* @brief Performs SLH-DSA signing and verification on a given message.291*292* This function generates an SLH-DSA key, signs a message, and verifies293* the generated signature. It extracts necessary parameters from the buffer294* to determine signing options.295*296* @param buf Pointer to a buffer containing the selector and message data.297* The buffer pointer is updated as values are consumed.298* @param len Pointer to the remaining buffer length, updated as values299* are consumed.300* @param key1 Unused key parameter (placeholder for function signature consistency).301* @param key2 Unused key parameter (placeholder for function signature consistency).302* @param out1 Pointer to store the generated key (for cleanup purposes).303* @param out2 Unused output parameter (placeholder for consistency).304*/305static void slh_dsa_sign_verify(uint8_t **buf, size_t *len, void *key1,306void *key2, void **out1, void **out2)307{308EVP_PKEY_CTX *ctx = NULL;309EVP_PKEY *key = NULL;310EVP_SIGNATURE *sig_alg = NULL;311const char *keytype;312uint32_t keylen;313uint8_t selector = 0;314unsigned char *msg = NULL;315size_t msg_len;316size_t sig_len;317unsigned char *sig = NULL;318OSSL_PARAM params[4];319int paramidx = 0;320int intval1, intval2;321int expect_init_rc = 1;322323*buf = consume_uint8t(*buf, len, &selector);324if (*buf == NULL)325return;326327keytype = select_keytype(selector, &keylen);328329/*330* Consume another byte to figure out our params331*/332*buf = consume_uint8t(*buf, len, &selector);333if (*buf == NULL)334return;335336/*337* Remainder of the buffer is the msg to sign338*/339msg = (unsigned char *)*buf;340msg_len = *len;341342/* if msg_len > 255, sign_message_init will fail */343if (msg_len > 255 && (selector & 0x1) != 0)344expect_init_rc = 0;345346*len = 0;347348if (selector & 0x1)349params[paramidx++] = OSSL_PARAM_construct_octet_string(OSSL_SIGNATURE_PARAM_CONTEXT_STRING,350msg, msg_len);351352if (selector & 0x2) {353intval1 = selector & 0x4;354params[paramidx++] = OSSL_PARAM_construct_int(OSSL_SIGNATURE_PARAM_MESSAGE_ENCODING,355&intval1);356}357358if (selector & 0x8) {359intval2 = selector & 0x10;360params[paramidx++] = OSSL_PARAM_construct_int(OSSL_SIGNATURE_PARAM_DETERMINISTIC,361&intval2);362}363364params[paramidx] = OSSL_PARAM_construct_end();365366key = (void *)slh_dsa_gen_key(keytype, keylen, NULL, 0);367OPENSSL_assert(key != NULL);368*out1 = key; /* for cleanup */369370ctx = EVP_PKEY_CTX_new_from_pkey(NULL, key, NULL);371OPENSSL_assert(ctx != NULL);372373sig_alg = EVP_SIGNATURE_fetch(NULL, keytype, NULL);374OPENSSL_assert(sig_alg != NULL);375376OPENSSL_assert(EVP_PKEY_sign_message_init(ctx, sig_alg, params) == expect_init_rc);377/*378* the context_string parameter can be no more than 255 bytes, so if379* our random input buffer is greater than that, we expect failure above,380* which we check for. In that event, theres nothing more we can do here381* so bail out382*/383if (expect_init_rc == 0)384goto out;385386OPENSSL_assert(EVP_PKEY_sign(ctx, NULL, &sig_len, msg, msg_len));387sig = OPENSSL_zalloc(sig_len);388OPENSSL_assert(sig != NULL);389390OPENSSL_assert(EVP_PKEY_sign(ctx, sig, &sig_len, msg, msg_len));391392OPENSSL_assert(EVP_PKEY_verify_message_init(ctx, sig_alg, params));393OPENSSL_assert(EVP_PKEY_verify(ctx, sig, sig_len, msg, msg_len));394395out:396OPENSSL_free(sig);397EVP_SIGNATURE_free(sig_alg);398EVP_PKEY_CTX_free(ctx);399}400401/**402* @brief Exports and imports SLH-DSA key pairs, verifying equivalence.403*404* This function extracts key data from two given SLH-DSA keys (`alice` and `bob`),405* reconstructs new keys from the extracted data, and verifies that the imported406* keys are equivalent to the originals. It ensures that key export/import407* functionality is working correctly.408*409* @param buf Unused buffer parameter (placeholder for function signature consistency).410* @param len Unused length parameter (placeholder for function signature consistency).411* @param key1 Pointer to the first key (`alice`) to be exported and imported.412* @param key2 Pointer to the second key (`bob`) to be exported and imported.413* @param out1 Unused output parameter (placeholder for consistency).414* @param out2 Unused output parameter (placeholder for consistency).415*/416static void slh_dsa_export_import(uint8_t **buf, size_t *len, void *key1,417void *key2, void **out1, void **out2)418{419int rc;420EVP_PKEY *alice = (EVP_PKEY *)key1;421EVP_PKEY *bob = (EVP_PKEY *)key2;422EVP_PKEY *new = NULL;423EVP_PKEY_CTX *ctx = NULL;424OSSL_PARAM *params = NULL;425426OPENSSL_assert(EVP_PKEY_todata(alice, EVP_PKEY_KEYPAIR, ¶ms) == 1);427428ctx = EVP_PKEY_CTX_new_from_pkey(NULL, alice, NULL);429OPENSSL_assert(ctx != NULL);430431OPENSSL_assert(EVP_PKEY_fromdata_init(ctx));432433new = EVP_PKEY_new();434OPENSSL_assert(new != NULL);435OPENSSL_assert(EVP_PKEY_fromdata(ctx, &new, EVP_PKEY_KEYPAIR, params) == 1);436437/*438* EVP_PKEY returns:439* 1 if the keys are equivalent440* 0 if the keys are not equivalent441* -1 if the key types are differnt442* -2 if the operation is not supported443*/444OPENSSL_assert(EVP_PKEY_eq(alice, new) == 1);445EVP_PKEY_free(new);446EVP_PKEY_CTX_free(ctx);447OSSL_PARAM_free(params);448params = NULL;449ctx = NULL;450new = NULL;451452OPENSSL_assert(EVP_PKEY_todata(bob, EVP_PKEY_KEYPAIR, ¶ms) == 1);453454ctx = EVP_PKEY_CTX_new_from_pkey(NULL, bob, NULL);455OPENSSL_assert(ctx != NULL);456457OPENSSL_assert(EVP_PKEY_fromdata_init(ctx));458459new = EVP_PKEY_new();460OPENSSL_assert(new != NULL);461OPENSSL_assert(EVP_PKEY_fromdata(ctx, &new, EVP_PKEY_KEYPAIR, params) == 1);462463OPENSSL_assert(EVP_PKEY_eq(bob, new) == 1);464465/*466* Depending on the types of eys that get generated467* we might get a simple non-equivalence or a type mismatch here468*/469rc = EVP_PKEY_eq(alice, new);470OPENSSL_assert(rc == 0 || rc == -1);471472EVP_PKEY_CTX_free(ctx);473EVP_PKEY_free(new);474OSSL_PARAM_free(params);475}476477/**478* @brief Represents an operation table entry for cryptographic operations.479*480* This structure defines a table entry containing function pointers for481* setting up, executing, and cleaning up cryptographic operations, along482* with associated metadata such as a name and description.483*484* @struct op_table_entry485*/486struct op_table_entry {487/** Name of the operation. */488char *name;489490/**491* @brief Function pointer for setting up the operation.492*493* @param buf Pointer to the buffer pointer; may be updated.494* @param len Pointer to the remaining buffer size; may be updated.495* @param out1 Pointer to store the first output of the setup function.496* @param out2 Pointer to store the second output of the setup function.497*/498void (*setup)(uint8_t **buf, size_t *len, void **out1, void **out2);499500/**501* @brief Function pointer for executing the operation.502*503* @param buf Pointer to the buffer pointer; may be updated.504* @param len Pointer to the remaining buffer size; may be updated.505* @param in1 First input parameter for the operation.506* @param in2 Second input parameter for the operation.507* @param out1 Pointer to store the first output of the operation.508* @param out2 Pointer to store the second output of the operation.509*/510void (*doit)(uint8_t **buf, size_t *len, void *in1, void *in2,511void **out1, void **out2);512513/**514* @brief Function pointer for cleaning up after the operation.515*516* @param in1 First input parameter to be cleaned up.517* @param in2 Second input parameter to be cleaned up.518* @param out1 First output parameter to be cleaned up.519* @param out2 Second output parameter to be cleaned up.520*/521void (*cleanup)(void *in1, void *in2, void *out1, void *out2);522};523524static struct op_table_entry ops[] = {525{526"Generate SLH-DSA keys",527slh_dsa_gen_keys,528NULL,529slh_dsa_clean_keys530}, {531"Generate SLH-DSA keys with params",532slh_dsa_gen_key_with_params,533NULL,534slh_dsa_clean_keys535}, {536"SLH-DSA Export/Import",537slh_dsa_gen_keys,538slh_dsa_export_import,539slh_dsa_clean_keys540}, {541"SLH-DSA sign and verify",542NULL,543slh_dsa_sign_verify,544slh_dsa_clean_keys545}546};547548int FuzzerInitialize(int *argc, char ***argv)549{550return 0;551}552553/**554* @brief Processes a fuzzing input by selecting and executing an operation.555*556* This function interprets the first byte of the input buffer to determine557* an operation to execute. It then follows a setup, execution, and cleanup558* sequence based on the selected operation.559*560* @param buf Pointer to the input buffer.561* @param len Length of the input buffer.562*563* @return 0 on successful execution, -1 if the input is too short.564*565* @note The function requires at least 32 bytes in the buffer to proceed.566* It utilizes the `ops` operation table to dynamically determine and567* execute the selected operation.568*/569int FuzzerTestOneInput(const uint8_t *buf, size_t len)570{571uint8_t operation;572uint8_t *buffer_cursor;573void *in1 = NULL, *in2 = NULL;574void *out1 = NULL, *out2 = NULL;575576if (len < 32)577return -1;578/*579* Get the first byte of the buffer to tell us what operation580* to preform581*/582buffer_cursor = consume_uint8t(buf, &len, &operation);583if (buffer_cursor == NULL)584return -1;585586/*587* Adjust for operational array size588*/589operation %= OSSL_NELEM(ops);590591/*592* And run our setup/doit/cleanup sequence593*/594if (ops[operation].setup != NULL)595ops[operation].setup(&buffer_cursor, &len, &in1, &in2);596if (ops[operation].doit != NULL)597ops[operation].doit(&buffer_cursor, &len, in1, in2, &out1, &out2);598if (ops[operation].cleanup != NULL)599ops[operation].cleanup(in1, in2, out1, out2);600601return 0;602}603604void FuzzerCleanup(void)605{606OPENSSL_cleanup();607}608609610