file_path
stringlengths
19
75
code
stringlengths
279
1.37M
./openssl/demos/kdf/argon2.c
/* * Copyright 2023 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <stdio.h> #include <openssl/core_names.h> #include <openssl/crypto.h> #include <openssl/kdf.h> #include <openssl/params.h> #include <openssl/thread.h> /* * Example showing how to use Argon2 KDF. * See man EVP_KDF-ARGON2 for more information. * * test vector from * https://datatracker.ietf.org/doc/html/rfc9106 */ /* * Hard coding a password into an application is very bad. * It is done here solely for educational purposes. */ static unsigned char password[] = { 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01 }; /* * The salt is better not being hard coded too. Each password should have a * different salt if possible. The salt is not considered secret information * and is safe to store with an encrypted password. */ static unsigned char salt[] = { 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02 }; /* * Optional secret for KDF */ static unsigned char secret[] = { 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03 }; /* * Optional additional data */ static unsigned char ad[] = { 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04 }; /* * Argon2 cost parameters */ static uint32_t memory_cost = 32; static uint32_t iteration_cost = 3; static uint32_t parallel_cost = 4; static const unsigned char expected_output[] = { 0x0d, 0x64, 0x0d, 0xf5, 0x8d, 0x78, 0x76, 0x6c, 0x08, 0xc0, 0x37, 0xa3, 0x4a, 0x8b, 0x53, 0xc9, 0xd0, 0x1e, 0xf0, 0x45, 0x2d, 0x75, 0xb6, 0x5e, 0xb5, 0x25, 0x20, 0xe9, 0x6b, 0x01, 0xe6, 0x59 }; int main(int argc, char **argv) { int rv = EXIT_FAILURE; EVP_KDF *kdf = NULL; EVP_KDF_CTX *kctx = NULL; unsigned char out[32]; OSSL_PARAM params[9], *p = params; OSSL_LIB_CTX *library_context = NULL; unsigned int threads; library_context = OSSL_LIB_CTX_new(); if (library_context == NULL) { fprintf(stderr, "OSSL_LIB_CTX_new() returned NULL\n"); goto end; } /* Fetch the key derivation function implementation */ kdf = EVP_KDF_fetch(library_context, "argon2id", NULL); if (kdf == NULL) { fprintf(stderr, "EVP_KDF_fetch() returned NULL\n"); goto end; } /* Create a context for the key derivation operation */ kctx = EVP_KDF_CTX_new(kdf); if (kctx == NULL) { fprintf(stderr, "EVP_KDF_CTX_new() returned NULL\n"); goto end; } /* * Thread support can be turned off; use serialization if we cannot * set requested number of threads. */ threads = parallel_cost; if (OSSL_set_max_threads(library_context, parallel_cost) != 1) { uint64_t max_threads = OSSL_get_max_threads(library_context); if (max_threads == 0) threads = 1; else if (max_threads < parallel_cost) threads = max_threads; } /* Set password */ *p++ = OSSL_PARAM_construct_octet_string(OSSL_KDF_PARAM_PASSWORD, password, sizeof(password)); /* Set salt */ *p++ = OSSL_PARAM_construct_octet_string(OSSL_KDF_PARAM_SALT, salt, sizeof(salt)); /* Set optional additional data */ *p++ = OSSL_PARAM_construct_octet_string(OSSL_KDF_PARAM_ARGON2_AD, ad, sizeof(ad)); /* Set optional secret */ *p++ = OSSL_PARAM_construct_octet_string(OSSL_KDF_PARAM_SECRET, secret, sizeof(secret)); /* Set iteration count */ *p++ = OSSL_PARAM_construct_uint32(OSSL_KDF_PARAM_ITER, &iteration_cost); /* Set threads performing derivation (can be decreased) */ *p++ = OSSL_PARAM_construct_uint(OSSL_KDF_PARAM_THREADS, &threads); /* Set parallel cost */ *p++ = OSSL_PARAM_construct_uint32(OSSL_KDF_PARAM_ARGON2_LANES, &parallel_cost); /* Set memory requirement */ *p++ = OSSL_PARAM_construct_uint32(OSSL_KDF_PARAM_ARGON2_MEMCOST, &memory_cost); *p = OSSL_PARAM_construct_end(); /* Derive the key */ if (EVP_KDF_derive(kctx, out, sizeof(out), params) != 1) { fprintf(stderr, "EVP_KDF_derive() failed\n"); goto end; } if (CRYPTO_memcmp(expected_output, out, sizeof(expected_output)) != 0) { fprintf(stderr, "Generated key does not match expected value\n"); goto end; } printf("Success\n"); rv = EXIT_SUCCESS; end: EVP_KDF_CTX_free(kctx); EVP_KDF_free(kdf); OSSL_LIB_CTX_free(library_context); return rv; }
./openssl/demos/kdf/pbkdf2.c
/* * Copyright 2021-2023 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <stdio.h> #include <openssl/core_names.h> #include <openssl/crypto.h> #include <openssl/kdf.h> #include <openssl/obj_mac.h> #include <openssl/params.h> /* * test vector from * https://datatracker.ietf.org/doc/html/rfc7914 */ /* * Hard coding a password into an application is very bad. * It is done here solely for educational purposes. */ static unsigned char password[] = { 'P', 'a', 's', 's', 'w', 'o', 'r', 'd' }; /* * The salt is better not being hard coded too. Each password should have a * different salt if possible. The salt is not considered secret information * and is safe to store with an encrypted password. */ static unsigned char pbkdf2_salt[] = { 'N', 'a', 'C', 'l' }; /* * The iteration parameter can be variable or hard coded. The disadvantage with * hard coding them is that they cannot easily be adjusted for future * technological improvements appear. */ static unsigned int pbkdf2_iterations = 80000; static const unsigned char expected_output[] = { 0x4d, 0xdc, 0xd8, 0xf6, 0x0b, 0x98, 0xbe, 0x21, 0x83, 0x0c, 0xee, 0x5e, 0xf2, 0x27, 0x01, 0xf9, 0x64, 0x1a, 0x44, 0x18, 0xd0, 0x4c, 0x04, 0x14, 0xae, 0xff, 0x08, 0x87, 0x6b, 0x34, 0xab, 0x56, 0xa1, 0xd4, 0x25, 0xa1, 0x22, 0x58, 0x33, 0x54, 0x9a, 0xdb, 0x84, 0x1b, 0x51, 0xc9, 0xb3, 0x17, 0x6a, 0x27, 0x2b, 0xde, 0xbb, 0xa1, 0xd0, 0x78, 0x47, 0x8f, 0x62, 0xb3, 0x97, 0xf3, 0x3c, 0x8d }; int main(int argc, char **argv) { int ret = EXIT_FAILURE; EVP_KDF *kdf = NULL; EVP_KDF_CTX *kctx = NULL; unsigned char out[64]; OSSL_PARAM params[5], *p = params; OSSL_LIB_CTX *library_context = NULL; library_context = OSSL_LIB_CTX_new(); if (library_context == NULL) { fprintf(stderr, "OSSL_LIB_CTX_new() returned NULL\n"); goto end; } /* Fetch the key derivation function implementation */ kdf = EVP_KDF_fetch(library_context, "PBKDF2", NULL); if (kdf == NULL) { fprintf(stderr, "EVP_KDF_fetch() returned NULL\n"); goto end; } /* Create a context for the key derivation operation */ kctx = EVP_KDF_CTX_new(kdf); if (kctx == NULL) { fprintf(stderr, "EVP_KDF_CTX_new() returned NULL\n"); goto end; } /* Set password */ *p++ = OSSL_PARAM_construct_octet_string(OSSL_KDF_PARAM_PASSWORD, password, sizeof(password)); /* Set salt */ *p++ = OSSL_PARAM_construct_octet_string(OSSL_KDF_PARAM_SALT, pbkdf2_salt, sizeof(pbkdf2_salt)); /* Set iteration count (default 2048) */ *p++ = OSSL_PARAM_construct_uint(OSSL_KDF_PARAM_ITER, &pbkdf2_iterations); /* Set the underlying hash function used to derive the key */ *p++ = OSSL_PARAM_construct_utf8_string(OSSL_KDF_PARAM_DIGEST, "SHA256", 0); *p = OSSL_PARAM_construct_end(); /* Derive the key */ if (EVP_KDF_derive(kctx, out, sizeof(out), params) != 1) { fprintf(stderr, "EVP_KDF_derive() failed\n"); goto end; } if (CRYPTO_memcmp(expected_output, out, sizeof(expected_output)) != 0) { fprintf(stderr, "Generated key does not match expected value\n"); goto end; } printf("Success\n"); ret = EXIT_SUCCESS; end: EVP_KDF_CTX_free(kctx); EVP_KDF_free(kdf); OSSL_LIB_CTX_free(library_context); return ret; }
./openssl/demos/kdf/hkdf.c
/* * Copyright 2021-2023 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <stdio.h> #include <openssl/core_names.h> #include <openssl/crypto.h> #include <openssl/kdf.h> #include <openssl/obj_mac.h> #include <openssl/params.h> /* * test vector from * https://datatracker.ietf.org/doc/html/rfc5869 */ static unsigned char hkdf_salt[] = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c }; static unsigned char hkdf_ikm[] = { 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b }; static unsigned char hkdf_info[] = { 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9 }; /* Expected output keying material */ static unsigned char hkdf_okm[] = { 0x3c, 0xb2, 0x5f, 0x25, 0xfa, 0xac, 0xd5, 0x7a, 0x90, 0x43, 0x4f, 0x64, 0xd0, 0x36, 0x2f, 0x2a, 0x2d, 0x2d, 0x0a, 0x90, 0xcf, 0x1a, 0x5a, 0x4c, 0x5d, 0xb0, 0x2d, 0x56, 0xec, 0xc4, 0xc5, 0xbf, 0x34, 0x00, 0x72, 0x08, 0xd5, 0xb8, 0x87, 0x18, 0x58, 0x65 }; int main(int argc, char **argv) { int ret = EXIT_FAILURE; EVP_KDF *kdf = NULL; EVP_KDF_CTX *kctx = NULL; unsigned char out[42]; OSSL_PARAM params[5], *p = params; OSSL_LIB_CTX *library_context = NULL; library_context = OSSL_LIB_CTX_new(); if (library_context == NULL) { fprintf(stderr, "OSSL_LIB_CTX_new() returned NULL\n"); goto end; } /* Fetch the key derivation function implementation */ kdf = EVP_KDF_fetch(library_context, "HKDF", NULL); if (kdf == NULL) { fprintf(stderr, "EVP_KDF_fetch() returned NULL\n"); goto end; } /* Create a context for the key derivation operation */ kctx = EVP_KDF_CTX_new(kdf); if (kctx == NULL) { fprintf(stderr, "EVP_KDF_CTX_new() returned NULL\n"); goto end; } /* Set the underlying hash function used to derive the key */ *p++ = OSSL_PARAM_construct_utf8_string(OSSL_KDF_PARAM_DIGEST, "SHA256", 0); /* Set input keying material */ *p++ = OSSL_PARAM_construct_octet_string(OSSL_KDF_PARAM_KEY, hkdf_ikm, sizeof(hkdf_ikm)); /* Set application specific information */ *p++ = OSSL_PARAM_construct_octet_string(OSSL_KDF_PARAM_INFO, hkdf_info, sizeof(hkdf_info)); /* Set salt */ *p++ = OSSL_PARAM_construct_octet_string(OSSL_KDF_PARAM_SALT, hkdf_salt, sizeof(hkdf_salt)); *p = OSSL_PARAM_construct_end(); /* Derive the key */ if (EVP_KDF_derive(kctx, out, sizeof(out), params) != 1) { fprintf(stderr, "EVP_KDF_derive() failed\n"); goto end; } if (CRYPTO_memcmp(hkdf_okm, out, sizeof(hkdf_okm)) != 0) { fprintf(stderr, "Generated key does not match expected value\n"); goto end; } printf("Success\n"); ret = EXIT_SUCCESS; end: EVP_KDF_CTX_free(kctx); EVP_KDF_free(kdf); OSSL_LIB_CTX_free(library_context); return ret; }
./openssl/demos/http3/ossl-nghttp3.c
/* * Copyright 2023 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include "ossl-nghttp3.h" #include <openssl/err.h> #include <assert.h> #define ARRAY_LEN(x) (sizeof(x)/sizeof((x)[0])) enum { OSSL_DEMO_H3_STREAM_TYPE_CTRL_SEND, OSSL_DEMO_H3_STREAM_TYPE_QPACK_ENC_SEND, OSSL_DEMO_H3_STREAM_TYPE_QPACK_DEC_SEND, OSSL_DEMO_H3_STREAM_TYPE_REQ, }; #define BUF_SIZE 4096 struct ossl_demo_h3_stream_st { uint64_t id; /* QUIC stream ID */ SSL *s; /* QUIC stream SSL object */ int done_recv_fin; /* Received FIN */ void *user_data; uint8_t buf[BUF_SIZE]; size_t buf_cur, buf_total; }; DEFINE_LHASH_OF_EX(OSSL_DEMO_H3_STREAM); static void h3_stream_free(OSSL_DEMO_H3_STREAM *s) { if (s == NULL) return; SSL_free(s->s); OPENSSL_free(s); } static unsigned long h3_stream_hash(const OSSL_DEMO_H3_STREAM *s) { return (unsigned long)s->id; } static int h3_stream_eq(const OSSL_DEMO_H3_STREAM *a, const OSSL_DEMO_H3_STREAM *b) { if (a->id < b->id) return -1; if (a->id > b->id) return 1; return 0; } void *OSSL_DEMO_H3_STREAM_get_user_data(const OSSL_DEMO_H3_STREAM *s) { return s->user_data; } struct ossl_demo_h3_conn_st { /* QUIC connection SSL object */ SSL *qconn; /* BIO wrapping QCSO */ BIO *qconn_bio; /* HTTP/3 connection object */ nghttp3_conn *h3conn; /* map of stream IDs to OSSL_DEMO_H3_STREAMs */ LHASH_OF(OSSL_DEMO_H3_STREAM) *streams; /* opaque user data pointer */ void *user_data; int pump_res; size_t consumed_app_data; /* Forwarding callbacks */ nghttp3_recv_data recv_data_cb; nghttp3_stream_close stream_close_cb; nghttp3_stop_sending stop_sending_cb; nghttp3_reset_stream reset_stream_cb; nghttp3_deferred_consume deferred_consume_cb; }; void OSSL_DEMO_H3_CONN_free(OSSL_DEMO_H3_CONN *conn) { if (conn == NULL) return; lh_OSSL_DEMO_H3_STREAM_doall(conn->streams, h3_stream_free); nghttp3_conn_del(conn->h3conn); BIO_free_all(conn->qconn_bio); lh_OSSL_DEMO_H3_STREAM_free(conn->streams); OPENSSL_free(conn); } static OSSL_DEMO_H3_STREAM *h3_conn_create_stream(OSSL_DEMO_H3_CONN *conn, int type) { OSSL_DEMO_H3_STREAM *s; uint64_t flags = SSL_STREAM_FLAG_ADVANCE; if ((s = OPENSSL_zalloc(sizeof(OSSL_DEMO_H3_STREAM))) == NULL) return NULL; if (type != OSSL_DEMO_H3_STREAM_TYPE_REQ) flags |= SSL_STREAM_FLAG_UNI; if ((s->s = SSL_new_stream(conn->qconn, flags)) == NULL) { ERR_raise_data(ERR_LIB_USER, ERR_R_INTERNAL_ERROR, "could not create QUIC stream object"); goto err; } s->id = SSL_get_stream_id(s->s); lh_OSSL_DEMO_H3_STREAM_insert(conn->streams, s); return s; err: OPENSSL_free(s); return NULL; } static OSSL_DEMO_H3_STREAM *h3_conn_accept_stream(OSSL_DEMO_H3_CONN *conn, SSL *qstream) { OSSL_DEMO_H3_STREAM *s; if ((s = OPENSSL_zalloc(sizeof(OSSL_DEMO_H3_STREAM))) == NULL) return NULL; s->id = SSL_get_stream_id(qstream); s->s = qstream; lh_OSSL_DEMO_H3_STREAM_insert(conn->streams, s); return s; } static void h3_conn_remove_stream(OSSL_DEMO_H3_CONN *conn, OSSL_DEMO_H3_STREAM *s) { if (s == NULL) return; lh_OSSL_DEMO_H3_STREAM_delete(conn->streams, s); h3_stream_free(s); } static int h3_conn_recv_data(nghttp3_conn *h3conn, int64_t stream_id, const uint8_t *data, size_t datalen, void *conn_user_data, void *stream_user_data) { OSSL_DEMO_H3_CONN *conn = conn_user_data; conn->consumed_app_data += datalen; if (conn->recv_data_cb == NULL) return 0; return conn->recv_data_cb(h3conn, stream_id, data, datalen, conn_user_data, stream_user_data); } static int h3_conn_stream_close(nghttp3_conn *h3conn, int64_t stream_id, uint64_t app_error_code, void *conn_user_data, void *stream_user_data) { int ret = 0; OSSL_DEMO_H3_CONN *conn = conn_user_data; OSSL_DEMO_H3_STREAM *stream = stream_user_data; if (conn->stream_close_cb != NULL) ret = conn->stream_close_cb(h3conn, stream_id, app_error_code, conn_user_data, stream_user_data); h3_conn_remove_stream(conn, stream); return ret; } static int h3_conn_stop_sending(nghttp3_conn *h3conn, int64_t stream_id, uint64_t app_error_code, void *conn_user_data, void *stream_user_data) { int ret = 0; OSSL_DEMO_H3_CONN *conn = conn_user_data; OSSL_DEMO_H3_STREAM *stream = stream_user_data; if (conn->stop_sending_cb != NULL) ret = conn->stop_sending_cb(h3conn, stream_id, app_error_code, conn_user_data, stream_user_data); SSL_free(stream->s); stream->s = NULL; return ret; } static int h3_conn_reset_stream(nghttp3_conn *h3conn, int64_t stream_id, uint64_t app_error_code, void *conn_user_data, void *stream_user_data) { int ret = 0; OSSL_DEMO_H3_CONN *conn = conn_user_data; OSSL_DEMO_H3_STREAM *stream = stream_user_data; SSL_STREAM_RESET_ARGS args = {0}; if (conn->reset_stream_cb != NULL) ret = conn->reset_stream_cb(h3conn, stream_id, app_error_code, conn_user_data, stream_user_data); if (stream->s != NULL) { args.quic_error_code = app_error_code; if (!SSL_stream_reset(stream->s, &args, sizeof(args))) return 1; } return ret; } static int h3_conn_deferred_consume(nghttp3_conn *h3conn, int64_t stream_id, size_t consumed, void *conn_user_data, void *stream_user_data) { int ret = 0; OSSL_DEMO_H3_CONN *conn = conn_user_data; if (conn->deferred_consume_cb != NULL) ret = conn->deferred_consume_cb(h3conn, stream_id, consumed, conn_user_data, stream_user_data); conn->consumed_app_data += consumed; return ret; } OSSL_DEMO_H3_CONN *OSSL_DEMO_H3_CONN_new_for_conn(BIO *qconn_bio, const nghttp3_callbacks *callbacks, const nghttp3_settings *settings, void *user_data) { int ec; OSSL_DEMO_H3_CONN *conn; OSSL_DEMO_H3_STREAM *s_ctl_send = NULL; OSSL_DEMO_H3_STREAM *s_qpenc_send = NULL; OSSL_DEMO_H3_STREAM *s_qpdec_send = NULL; nghttp3_settings dsettings = {0}; nghttp3_callbacks intl_callbacks = {0}; static const unsigned char alpn[] = {2, 'h', '3'}; if (qconn_bio == NULL) { ERR_raise_data(ERR_LIB_USER, ERR_R_PASSED_NULL_PARAMETER, "QUIC connection BIO must be provided"); return NULL; } if ((conn = OPENSSL_zalloc(sizeof(OSSL_DEMO_H3_CONN))) == NULL) return NULL; conn->qconn_bio = qconn_bio; conn->user_data = user_data; if (BIO_get_ssl(qconn_bio, &conn->qconn) == 0) { ERR_raise_data(ERR_LIB_USER, ERR_R_PASSED_INVALID_ARGUMENT, "BIO must be an SSL BIO"); goto err; } /* Create the map of stream IDs to OSSL_DEMO_H3_STREAM structures. */ if ((conn->streams = lh_OSSL_DEMO_H3_STREAM_new(h3_stream_hash, h3_stream_eq)) == NULL) goto err; /* * If the application has not started connecting yet, helpfully * auto-configure ALPN. If the application wants to initiate the connection * itself, it must take care of this itself. */ if (SSL_in_before(conn->qconn)) if (SSL_set_alpn_protos(conn->qconn, alpn, sizeof(alpn))) { /* SSL_set_alpn_protos returns 1 on failure */ ERR_raise_data(ERR_LIB_USER, ERR_R_INTERNAL_ERROR, "failed to configure ALPN"); goto err; } /* * We use the QUIC stack in non-blocking mode so that we can react to * incoming data on different streams, and e.g. incoming streams initiated * by a server, as and when events occur. */ BIO_set_nbio(conn->qconn_bio, 1); /* * Disable default stream mode and create all streams explicitly. Each QUIC * stream will be represented by its own QUIC stream SSL object (QSSO). This * also automatically enables us to accept incoming streams (see * SSL_set_incoming_stream_policy(3)). */ if (!SSL_set_default_stream_mode(conn->qconn, SSL_DEFAULT_STREAM_MODE_NONE)) { ERR_raise_data(ERR_LIB_USER, ERR_R_INTERNAL_ERROR, "failed to configure default stream mode"); goto err; } /* * HTTP/3 requires a couple of unidirectional management streams: a control * stream and some QPACK state management streams for each side of a * connection. These are the instances on our side (with us sending); the * server will also create its own equivalent unidirectional streams on its * side, which we handle subsequently as they come in (see SSL_accept_stream * in the event handling code below). */ if ((s_ctl_send = h3_conn_create_stream(conn, OSSL_DEMO_H3_STREAM_TYPE_CTRL_SEND)) == NULL) goto err; if ((s_qpenc_send = h3_conn_create_stream(conn, OSSL_DEMO_H3_STREAM_TYPE_QPACK_ENC_SEND)) == NULL) goto err; if ((s_qpdec_send = h3_conn_create_stream(conn, OSSL_DEMO_H3_STREAM_TYPE_QPACK_DEC_SEND)) == NULL) goto err; if (settings == NULL) { nghttp3_settings_default(&dsettings); settings = &dsettings; } if (callbacks != NULL) intl_callbacks = *callbacks; /* * We need to do some of our own processing when many of these events occur, * so we note the original callback functions and forward appropriately. */ conn->recv_data_cb = intl_callbacks.recv_data; conn->stream_close_cb = intl_callbacks.stream_close; conn->stop_sending_cb = intl_callbacks.stop_sending; conn->reset_stream_cb = intl_callbacks.reset_stream; conn->deferred_consume_cb = intl_callbacks.deferred_consume; intl_callbacks.recv_data = h3_conn_recv_data; intl_callbacks.stream_close = h3_conn_stream_close; intl_callbacks.stop_sending = h3_conn_stop_sending; intl_callbacks.reset_stream = h3_conn_reset_stream; intl_callbacks.deferred_consume = h3_conn_deferred_consume; /* Create the HTTP/3 client state. */ ec = nghttp3_conn_client_new(&conn->h3conn, &intl_callbacks, settings, NULL, conn); if (ec < 0) { ERR_raise_data(ERR_LIB_USER, ERR_R_INTERNAL_ERROR, "cannot create nghttp3 connection: %s (%d)", nghttp3_strerror(ec), ec); goto err; } /* * Tell the HTTP/3 stack which stream IDs are used for our outgoing control * and QPACK streams. Note that we don't have to tell the HTTP/3 stack what * IDs are used for incoming streams as this is inferred automatically from * the stream type byte which starts every incoming unidirectional stream, * so it will autodetect the correct stream IDs for the incoming control and * QPACK streams initiated by the server. */ ec = nghttp3_conn_bind_control_stream(conn->h3conn, s_ctl_send->id); if (ec < 0) { ERR_raise_data(ERR_LIB_USER, ERR_R_INTERNAL_ERROR, "cannot bind nghttp3 control stream: %s (%d)", nghttp3_strerror(ec), ec); goto err; } ec = nghttp3_conn_bind_qpack_streams(conn->h3conn, s_qpenc_send->id, s_qpdec_send->id); if (ec < 0) { ERR_raise_data(ERR_LIB_USER, ERR_R_INTERNAL_ERROR, "cannot bind nghttp3 QPACK streams: %s (%d)", nghttp3_strerror(ec), ec); goto err; } return conn; err: nghttp3_conn_del(conn->h3conn); h3_stream_free(s_ctl_send); h3_stream_free(s_qpenc_send); h3_stream_free(s_qpdec_send); lh_OSSL_DEMO_H3_STREAM_free(conn->streams); OPENSSL_free(conn); return NULL; } OSSL_DEMO_H3_CONN *OSSL_DEMO_H3_CONN_new_for_addr(SSL_CTX *ctx, const char *addr, const nghttp3_callbacks *callbacks, const nghttp3_settings *settings, void *user_data) { BIO *qconn_bio = NULL; SSL *qconn = NULL; OSSL_DEMO_H3_CONN *conn = NULL; const char *bare_hostname; /* QUIC connection setup */ if ((qconn_bio = BIO_new_ssl_connect(ctx)) == NULL) goto err; /* Pass the 'hostname:port' string into the ssl_connect BIO. */ if (BIO_set_conn_hostname(qconn_bio, addr) == 0) goto err; /* * Get the 'bare' hostname out of the ssl_connect BIO. This is the hostname * without the port. */ bare_hostname = BIO_get_conn_hostname(qconn_bio); if (bare_hostname == NULL) goto err; if (BIO_get_ssl(qconn_bio, &qconn) == 0) goto err; /* Set the hostname we will validate the X.509 certificate against. */ if (SSL_set1_host(qconn, bare_hostname) <= 0) goto err; /* Configure SNI */ if (!SSL_set_tlsext_host_name(qconn, bare_hostname)) goto err; conn = OSSL_DEMO_H3_CONN_new_for_conn(qconn_bio, callbacks, settings, user_data); if (conn == NULL) goto err; return conn; err: BIO_free_all(qconn_bio); return NULL; } int OSSL_DEMO_H3_CONN_connect(OSSL_DEMO_H3_CONN *conn) { return SSL_connect(OSSL_DEMO_H3_CONN_get0_connection(conn)); } void *OSSL_DEMO_H3_CONN_get_user_data(const OSSL_DEMO_H3_CONN *conn) { return conn->user_data; } SSL *OSSL_DEMO_H3_CONN_get0_connection(const OSSL_DEMO_H3_CONN *conn) { return conn->qconn; } /* Pumps received data to the HTTP/3 stack for a single stream. */ static void h3_conn_pump_stream(OSSL_DEMO_H3_STREAM *s, void *conn_) { int ec; OSSL_DEMO_H3_CONN *conn = conn_; size_t num_bytes, consumed; uint64_t aec; if (!conn->pump_res) /* * Handling of a previous stream in the iteration over all streams * failed, so just do nothing. */ return; for (;;) { if (s->s == NULL /* If we already did STOP_SENDING, ignore this stream. */ /* If this is a write-only stream, there is no read data to check. */ || SSL_get_stream_read_state(s->s) == SSL_STREAM_STATE_WRONG_DIR /* * If we already got a FIN for this stream, there is nothing more to * do for it. */ || s->done_recv_fin) break; /* * Pump data from OpenSSL QUIC to the HTTP/3 stack by calling SSL_peek * to get received data and passing it to nghttp3 using * nghttp3_conn_read_stream. Note that this function is confusingly * named and inputs data to the HTTP/3 stack. */ if (s->buf_cur == s->buf_total) { /* Need more data. */ ec = SSL_read_ex(s->s, s->buf, sizeof(s->buf), &num_bytes); if (ec <= 0) { num_bytes = 0; if (SSL_get_error(s->s, ec) == SSL_ERROR_ZERO_RETURN) { /* Stream concluded normally. Pass FIN to HTTP/3 stack. */ ec = nghttp3_conn_read_stream(conn->h3conn, s->id, NULL, 0, /*fin=*/1); if (ec < 0) { ERR_raise_data(ERR_LIB_USER, ERR_R_INTERNAL_ERROR, "cannot pass FIN to nghttp3: %s (%d)", nghttp3_strerror(ec), ec); goto err; } s->done_recv_fin = 1; } else if (SSL_get_stream_read_state(s->s) == SSL_STREAM_STATE_RESET_REMOTE) { /* Stream was reset by peer. */ if (!SSL_get_stream_read_error_code(s->s, &aec)) goto err; ec = nghttp3_conn_close_stream(conn->h3conn, s->id, aec); if (ec < 0) { ERR_raise_data(ERR_LIB_USER, ERR_R_INTERNAL_ERROR, "cannot mark stream as reset: %s (%d)", nghttp3_strerror(ec), ec); goto err; } s->done_recv_fin = 1; } else { /* Other error. */ goto err; } } s->buf_cur = 0; s->buf_total = num_bytes; } if (s->buf_cur == s->buf_total) break; /* * This function is confusingly named as it is is named from nghttp3's * 'perspective'; it is used to pass data *into* the HTTP/3 stack which * has been received from the network. */ assert(conn->consumed_app_data == 0); ec = nghttp3_conn_read_stream(conn->h3conn, s->id, s->buf + s->buf_cur, s->buf_total - s->buf_cur, /*fin=*/0); if (ec < 0) { ERR_raise_data(ERR_LIB_USER, ERR_R_INTERNAL_ERROR, "nghttp3 failed to process incoming data: %s (%d)", nghttp3_strerror(ec), ec); goto err; } /* * read_stream reports the data it consumes from us in two different * ways; the non-application data is returned as a number of bytes 'ec' * above, but the number of bytes of application data has to be recorded * by our callback. We sum the two to determine the total number of * bytes which nghttp3 consumed. */ consumed = ec + conn->consumed_app_data; assert(consumed <= s->buf_total - s->buf_cur); s->buf_cur += consumed; conn->consumed_app_data = 0; } return; err: conn->pump_res = 0; } int OSSL_DEMO_H3_CONN_handle_events(OSSL_DEMO_H3_CONN *conn) { int ec, fin; size_t i, num_vecs, written, total_written, total_len; int64_t stream_id; nghttp3_vec vecs[8] = {0}; OSSL_DEMO_H3_STREAM key, *s; SSL *snew; if (conn == NULL) return 0; /* * We handle events by doing three things: * * 1. Handle new incoming streams * 2. Pump outgoing data from the HTTP/3 stack to the QUIC engine * 3. Pump incoming data from the QUIC engine to the HTTP/3 stack */ /* 1. Check for new incoming streams */ for (;;) { if ((snew = SSL_accept_stream(conn->qconn, SSL_ACCEPT_STREAM_NO_BLOCK)) == NULL) break; /* * Each new incoming stream gets wrapped into an OSSL_DEMO_H3_STREAM object and * added into our stream ID map. */ if (h3_conn_accept_stream(conn, snew) == NULL) { SSL_free(snew); return 0; } } /* 2. Pump outgoing data from HTTP/3 engine to QUIC. */ for (;;) { /* * Get a number of send vectors from the HTTP/3 engine. * * Note that this function is confusingly named as it is named from * nghttp3's 'perspective': this outputs pointers to data which nghttp3 * wants to *write* to the network. */ ec = nghttp3_conn_writev_stream(conn->h3conn, &stream_id, &fin, vecs, ARRAY_LEN(vecs)); if (ec < 0) return 0; if (ec == 0) break; /* For each of the vectors returned, pass it to OpenSSL QUIC. */ key.id = stream_id; if ((s = lh_OSSL_DEMO_H3_STREAM_retrieve(conn->streams, &key)) == NULL) { ERR_raise_data(ERR_LIB_USER, ERR_R_INTERNAL_ERROR, "no stream for ID %zd", stream_id); return 0; } num_vecs = ec; total_len = nghttp3_vec_len(vecs, num_vecs); total_written = 0; for (i = 0; i < num_vecs; ++i) { if (vecs[i].len == 0) continue; if (s->s == NULL) { /* Already did STOP_SENDING and threw away stream, ignore */ written = vecs[i].len; } else if (!SSL_write_ex(s->s, vecs[i].base, vecs[i].len, &written)) { if (SSL_get_error(s->s, 0) == SSL_ERROR_WANT_WRITE) { /* * We have filled our send buffer so tell nghttp3 to stop * generating more data; we have to do this explicitly. */ written = 0; nghttp3_conn_block_stream(conn->h3conn, stream_id); } else { ERR_raise_data(ERR_LIB_USER, ERR_R_INTERNAL_ERROR, "writing HTTP/3 data to network failed"); return 0; } } else { /* * Tell nghttp3 it can resume generating more data in case we * previously called block_stream. */ nghttp3_conn_unblock_stream(conn->h3conn, stream_id); } total_written += written; if (written > 0) { /* * Tell nghttp3 we have consumed the data it output when we * called writev_stream, otherwise subsequent calls to * writev_stream will output the same data. */ ec = nghttp3_conn_add_write_offset(conn->h3conn, stream_id, written); if (ec < 0) return 0; /* * Tell nghttp3 it can free the buffered data because we will * not need it again. In our case we can always do this right * away because we copy the data into our QUIC send buffers * rather than simply storing a reference to it. */ ec = nghttp3_conn_add_ack_offset(conn->h3conn, stream_id, written); if (ec < 0) return 0; } } if (fin && total_written == total_len) { /* * We have written all the data so mark the stream as concluded * (FIN). */ SSL_stream_conclude(s->s, 0); if (total_len == 0) { /* * As a special case, if nghttp3 requested to write a * zero-length stream with a FIN, we have to tell it we did this * by calling add_write_offset(0). */ ec = nghttp3_conn_add_write_offset(conn->h3conn, stream_id, 0); if (ec < 0) return 0; } } } /* 3. Pump incoming data from QUIC to HTTP/3 engine. */ conn->pump_res = 1; /* cleared in below call if an error occurs */ lh_OSSL_DEMO_H3_STREAM_doall_arg(conn->streams, h3_conn_pump_stream, conn); if (!conn->pump_res) return 0; return 1; } int OSSL_DEMO_H3_CONN_submit_request(OSSL_DEMO_H3_CONN *conn, const nghttp3_nv *nva, size_t nvlen, const nghttp3_data_reader *dr, void *user_data) { int ec; OSSL_DEMO_H3_STREAM *s_req = NULL; if (conn == NULL) { ERR_raise_data(ERR_LIB_USER, ERR_R_PASSED_NULL_PARAMETER, "connection must be specified"); return 0; } /* Each HTTP/3 request is represented by a stream. */ if ((s_req = h3_conn_create_stream(conn, OSSL_DEMO_H3_STREAM_TYPE_REQ)) == NULL) goto err; s_req->user_data = user_data; ec = nghttp3_conn_submit_request(conn->h3conn, s_req->id, nva, nvlen, dr, s_req); if (ec < 0) { ERR_raise_data(ERR_LIB_USER, ERR_R_INTERNAL_ERROR, "cannot submit HTTP/3 request: %s (%d)", nghttp3_strerror(ec), ec); goto err; } return 1; err: h3_conn_remove_stream(conn, s_req); return 0; }
./openssl/demos/http3/ossl-nghttp3-demo.c
/* * Copyright 2023 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include "ossl-nghttp3.h" #include <openssl/err.h> static int done; static void make_nv(nghttp3_nv *nv, const char *name, const char *value) { nv->name = (uint8_t *)name; nv->value = (uint8_t *)value; nv->namelen = strlen(name); nv->valuelen = strlen(value); nv->flags = NGHTTP3_NV_FLAG_NONE; } static int on_recv_header(nghttp3_conn *h3conn, int64_t stream_id, int32_t token, nghttp3_rcbuf *name, nghttp3_rcbuf *value, uint8_t flags, void *conn_user_data, void *stream_user_data) { nghttp3_vec vname, vvalue; /* Received a single HTTP header. */ vname = nghttp3_rcbuf_get_buf(name); vvalue = nghttp3_rcbuf_get_buf(value); fwrite(vname.base, vname.len, 1, stderr); fprintf(stderr, ": "); fwrite(vvalue.base, vvalue.len, 1, stderr); fprintf(stderr, "\n"); return 0; } static int on_end_headers(nghttp3_conn *h3conn, int64_t stream_id, int fin, void *conn_user_data, void *stream_user_data) { fprintf(stderr, "\n"); return 0; } static int on_recv_data(nghttp3_conn *h3conn, int64_t stream_id, const uint8_t *data, size_t datalen, void *conn_user_data, void *stream_user_data) { ssize_t wr; /* HTTP response body data - write it to stdout. */ while (datalen > 0) { wr = fwrite(data, 1, datalen, stdout); if (wr < 0) return 1; data += wr; datalen -= wr; } return 0; } static int on_end_stream(nghttp3_conn *h3conn, int64_t stream_id, void *conn_user_data, void *stream_user_data) { /* HTTP transaction is done - set done flag so that we stop looping. */ done = 1; return 0; } int main(int argc, char **argv) { int ret = 1; SSL_CTX *ctx = NULL; OSSL_DEMO_H3_CONN *conn = NULL; nghttp3_nv nva[16]; nghttp3_callbacks callbacks = {0}; size_t num_nv = 0; const char *addr; /* Check arguments. */ if (argc < 2) { fprintf(stderr, "usage: %s <host:port>\n", argv[0]); goto err; } addr = argv[1]; /* Setup SSL_CTX. */ if ((ctx = SSL_CTX_new(OSSL_QUIC_client_method())) == NULL) goto err; SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, NULL); if (SSL_CTX_set_default_verify_paths(ctx) == 0) goto err; /* Setup callbacks. */ callbacks.recv_header = on_recv_header; callbacks.end_headers = on_end_headers; callbacks.recv_data = on_recv_data; callbacks.end_stream = on_end_stream; /* Create connection. */ if ((conn = OSSL_DEMO_H3_CONN_new_for_addr(ctx, addr, &callbacks, NULL, NULL)) == NULL) { ERR_raise_data(ERR_LIB_USER, ERR_R_OPERATION_FAIL, "cannot create HTTP/3 connection"); goto err; } /* Build HTTP headers. */ make_nv(&nva[num_nv++], ":method", "GET"); make_nv(&nva[num_nv++], ":scheme", "https"); make_nv(&nva[num_nv++], ":authority", addr); make_nv(&nva[num_nv++], ":path", "/"); make_nv(&nva[num_nv++], "user-agent", "OpenSSL-Demo/nghttp3"); /* Submit request. */ if (!OSSL_DEMO_H3_CONN_submit_request(conn, nva, num_nv, NULL, NULL)) { ERR_raise_data(ERR_LIB_USER, ERR_R_OPERATION_FAIL, "cannot submit HTTP/3 request"); goto err; } /* Wait for request to complete. */ while (!done) if (!OSSL_DEMO_H3_CONN_handle_events(conn)) { ERR_raise_data(ERR_LIB_USER, ERR_R_OPERATION_FAIL, "cannot handle events"); goto err; } ret = 0; err: if (ret != 0) ERR_print_errors_fp(stderr); OSSL_DEMO_H3_CONN_free(conn); SSL_CTX_free(ctx); return ret; }
./openssl/demos/http3/ossl-nghttp3.h
/* * Copyright 2023 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #ifndef OSSL_NGHTTP3_H # define OSSL_NGHTTP3_H # include <openssl/bio.h> # include <openssl/ssl.h> # include <nghttp3/nghttp3.h> /* * ossl-nghttp3: Demo binding of nghttp3 to OpenSSL QUIC * ===================================================== * * This is a simple library which provides an example binding of the nghttp3 * HTTP/3 library to OpenSSL's QUIC API. */ /* Represents an HTTP/3 connection to a server. */ typedef struct ossl_demo_h3_conn_st OSSL_DEMO_H3_CONN; /* Represents an HTTP/3 request, control or QPACK stream. */ typedef struct ossl_demo_h3_stream_st OSSL_DEMO_H3_STREAM; /* * Creates a HTTP/3 connection using the given QUIC client connection BIO. The * BIO must be able to provide an SSL object pointer using BIO_get_ssl. Takes * ownership of the reference. If the QUIC connection SSL object has not already * been connected, HTTP/3 ALPN is set automatically. If it has already been * connected, HTTP/3 ALPN ("h3") must have been configured and no streams must * have been created yet. * * If settings is NULL, use default settings only. Settings unsupported by * this QUIC binding are ignored. * * user_data is an application-provided opaque value which can be retrieved * using OSSL_DEMO_H3_CONN_get_user_data. Note that the user data value passed * to the callback functions specified in callbacks is a pointer to the * OSSL_DEMO_H3_CONN, not user_data. * * Returns NULL on failure. */ OSSL_DEMO_H3_CONN *OSSL_DEMO_H3_CONN_new_for_conn(BIO *qconn_bio, const nghttp3_callbacks *callbacks, const nghttp3_settings *settings, void *user_data); /* * Works identically to OSSL_DEMO_H3_CONN_new_for_conn except that it manages * the creation of a QUIC connection SSL object automatically using an address * string. addr should be a string such as "www.example.com:443". The created * underlying QUIC connection SSL object is owned by the OSSL_DEMO_H3_CONN and * can be subsequently retrieved using OSSL_DEMO_H3_CONN_get0_connection. * * Returns NULL on failure. ctx must be a SSL_CTX using a QUIC client * SSL_METHOD. */ OSSL_DEMO_H3_CONN *OSSL_DEMO_H3_CONN_new_for_addr(SSL_CTX *ctx, const char *addr, const nghttp3_callbacks *callbacks, const nghttp3_settings *settings, void *user_data); /* Equivalent to SSL_connect(OSSL_DEMO_H3_CONN_get0_connection(conn)). */ int OSSL_DEMO_H3_CONN_connect(OSSL_DEMO_H3_CONN *conn); /* * Free the OSSL_DEMO_H3_CONN and any underlying QUIC connection SSL object and * associated streams. */ void OSSL_DEMO_H3_CONN_free(OSSL_DEMO_H3_CONN *conn); /* * Returns the user data value which was specified in * OSSL_DEMO_H3_CONN_new_for_conn. */ void *OSSL_DEMO_H3_CONN_get_user_data(const OSSL_DEMO_H3_CONN *conn); /* Returns the underlying QUIC connection SSL object. */ SSL *OSSL_DEMO_H3_CONN_get0_connection(const OSSL_DEMO_H3_CONN *conn); /* * Handle any pending events on a given HTTP/3 connection. Returns 0 on error. */ int OSSL_DEMO_H3_CONN_handle_events(OSSL_DEMO_H3_CONN *conn); /* * Submits a new HTTP/3 request on the given connection. Returns 0 on error. * * This works analogously to nghttp3_conn_submit_request(). The stream user data * pointer passed to the callbacks is a OSSL_DEMO_H3_STREAM object pointer; to * retrieve the stream user data pointer passed to this function, use * OSSL_DEMO_H3_STREAM_get_user_data. */ int OSSL_DEMO_H3_CONN_submit_request(OSSL_DEMO_H3_CONN *conn, const nghttp3_nv *hdr, size_t hdrlen, const nghttp3_data_reader *dr, void *stream_user_data); /* * Returns the user data value which was specified in * OSSL_DEMO_H3_CONN_submit_request. */ void *OSSL_DEMO_H3_STREAM_get_user_data(const OSSL_DEMO_H3_STREAM *stream); #endif
./openssl/demos/keyexch/x25519.c
/* * Copyright 2022-2023 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <stdio.h> #include <string.h> #include <openssl/core_names.h> #include <openssl/evp.h> /* * This is a demonstration of key exchange using X25519. * * The variables beginning `peer1_` / `peer2_` are data which would normally be * accessible to that peer. * * Ordinarily you would use random keys, which are demonstrated * below when use_kat=0. A known answer test is demonstrated * when use_kat=1. */ /* A property query used for selecting the X25519 implementation. */ static const char *propq = NULL; static const unsigned char peer1_privk_data[32] = { 0x80, 0x5b, 0x30, 0x20, 0x25, 0x4a, 0x70, 0x2c, 0xad, 0xa9, 0x8d, 0x7d, 0x47, 0xf8, 0x1b, 0x20, 0x89, 0xd2, 0xf9, 0x14, 0xac, 0x92, 0x27, 0xf2, 0x10, 0x7e, 0xdb, 0x21, 0xbd, 0x73, 0x73, 0x5d }; static const unsigned char peer2_privk_data[32] = { 0xf8, 0x84, 0x19, 0x69, 0x79, 0x13, 0x0d, 0xbd, 0xb1, 0x76, 0xd7, 0x0e, 0x7e, 0x0f, 0xb6, 0xf4, 0x8c, 0x4a, 0x8c, 0x5f, 0xd8, 0x15, 0x09, 0x0a, 0x71, 0x78, 0x74, 0x92, 0x0f, 0x85, 0xc8, 0x43 }; static const unsigned char expected_result[32] = { 0x19, 0x71, 0x26, 0x12, 0x74, 0xb5, 0xb1, 0xce, 0x77, 0xd0, 0x79, 0x24, 0xb6, 0x0a, 0x5c, 0x72, 0x0c, 0xa6, 0x56, 0xc0, 0x11, 0xeb, 0x43, 0x11, 0x94, 0x3b, 0x01, 0x45, 0xca, 0x19, 0xfe, 0x09 }; typedef struct peer_data_st { const char *name; /* name of peer */ EVP_PKEY *privk; /* privk generated for peer */ unsigned char pubk_data[32]; /* generated pubk to send to other peer */ unsigned char *secret; /* allocated shared secret buffer */ size_t secret_len; } PEER_DATA; /* * Prepare for X25519 key exchange. The public key to be sent to the remote peer * is put in pubk_data, which should be a 32-byte buffer. Returns 1 on success. */ static int keyexch_x25519_before( OSSL_LIB_CTX *libctx, const unsigned char *kat_privk_data, PEER_DATA *local_peer) { int ret = 0; size_t pubk_data_len = 0; /* Generate or load X25519 key for the peer */ if (kat_privk_data != NULL) local_peer->privk = EVP_PKEY_new_raw_private_key_ex(libctx, "X25519", propq, kat_privk_data, sizeof(peer1_privk_data)); else local_peer->privk = EVP_PKEY_Q_keygen(libctx, propq, "X25519"); if (local_peer->privk == NULL) { fprintf(stderr, "Could not load or generate private key\n"); goto end; } /* Get public key corresponding to the private key */ if (EVP_PKEY_get_octet_string_param(local_peer->privk, OSSL_PKEY_PARAM_PUB_KEY, local_peer->pubk_data, sizeof(local_peer->pubk_data), &pubk_data_len) == 0) { fprintf(stderr, "EVP_PKEY_get_octet_string_param() failed\n"); goto end; } /* X25519 public keys are always 32 bytes */ if (pubk_data_len != 32) { fprintf(stderr, "EVP_PKEY_get_octet_string_param() " "yielded wrong length\n"); goto end; } ret = 1; end: if (ret == 0) { EVP_PKEY_free(local_peer->privk); local_peer->privk = NULL; } return ret; } /* * Complete X25519 key exchange. remote_peer_pubk_data should be the 32 byte * public key value received from the remote peer. On success, returns 1 and the * secret is pointed to by *secret. The caller must free it. */ static int keyexch_x25519_after( OSSL_LIB_CTX *libctx, int use_kat, PEER_DATA *local_peer, const unsigned char *remote_peer_pubk_data) { int ret = 0; EVP_PKEY *remote_peer_pubk = NULL; EVP_PKEY_CTX *ctx = NULL; local_peer->secret = NULL; /* Load public key for remote peer. */ remote_peer_pubk = EVP_PKEY_new_raw_public_key_ex(libctx, "X25519", propq, remote_peer_pubk_data, 32); if (remote_peer_pubk == NULL) { fprintf(stderr, "EVP_PKEY_new_raw_public_key_ex() failed\n"); goto end; } /* Create key exchange context. */ ctx = EVP_PKEY_CTX_new_from_pkey(libctx, local_peer->privk, propq); if (ctx == NULL) { fprintf(stderr, "EVP_PKEY_CTX_new_from_pkey() failed\n"); goto end; } /* Initialize derivation process. */ if (EVP_PKEY_derive_init(ctx) == 0) { fprintf(stderr, "EVP_PKEY_derive_init() failed\n"); goto end; } /* Configure each peer with the other peer's public key. */ if (EVP_PKEY_derive_set_peer(ctx, remote_peer_pubk) == 0) { fprintf(stderr, "EVP_PKEY_derive_set_peer() failed\n"); goto end; } /* Determine the secret length. */ if (EVP_PKEY_derive(ctx, NULL, &local_peer->secret_len) == 0) { fprintf(stderr, "EVP_PKEY_derive() failed\n"); goto end; } /* * We are using X25519, so the secret generated will always be 32 bytes. * However for exposition, the code below demonstrates a generic * implementation for arbitrary lengths. */ if (local_peer->secret_len != 32) { /* unreachable */ fprintf(stderr, "Secret is always 32 bytes for X25519\n"); goto end; } /* Allocate memory for shared secrets. */ local_peer->secret = OPENSSL_malloc(local_peer->secret_len); if (local_peer->secret == NULL) { fprintf(stderr, "Could not allocate memory for secret\n"); goto end; } /* Derive the shared secret. */ if (EVP_PKEY_derive(ctx, local_peer->secret, &local_peer->secret_len) == 0) { fprintf(stderr, "EVP_PKEY_derive() failed\n"); goto end; } printf("Shared secret (%s):\n", local_peer->name); BIO_dump_indent_fp(stdout, local_peer->secret, local_peer->secret_len, 2); putchar('\n'); ret = 1; end: EVP_PKEY_CTX_free(ctx); EVP_PKEY_free(remote_peer_pubk); if (ret == 0) { OPENSSL_clear_free(local_peer->secret, local_peer->secret_len); local_peer->secret = NULL; } return ret; } static int keyexch_x25519(int use_kat) { int ret = 0; OSSL_LIB_CTX *libctx = NULL; PEER_DATA peer1 = {"peer 1"}, peer2 = {"peer 2"}; /* * Each peer generates its private key and sends its public key * to the other peer. The private key is stored locally for * later use. */ if (keyexch_x25519_before(libctx, use_kat ? peer1_privk_data : NULL, &peer1) == 0) return 0; if (keyexch_x25519_before(libctx, use_kat ? peer2_privk_data : NULL, &peer2) == 0) return 0; /* * Each peer uses the other peer's public key to perform key exchange. * After this succeeds, each peer has the same secret in its * PEER_DATA. */ if (keyexch_x25519_after(libctx, use_kat, &peer1, peer2.pubk_data) == 0) return 0; if (keyexch_x25519_after(libctx, use_kat, &peer2, peer1.pubk_data) == 0) return 0; /* * Here we demonstrate the secrets are equal for exposition purposes. * * Although in practice you will generally not need to compare secrets * produced through key exchange, if you do compare cryptographic secrets, * always do so using a constant-time function such as CRYPTO_memcmp, never * using memcmp(3). */ if (CRYPTO_memcmp(peer1.secret, peer2.secret, peer1.secret_len) != 0) { fprintf(stderr, "Negotiated secrets do not match\n"); goto end; } /* If we are doing the KAT, the secret should equal our reference result. */ if (use_kat && CRYPTO_memcmp(peer1.secret, expected_result, peer1.secret_len) != 0) { fprintf(stderr, "Did not get expected result\n"); goto end; } ret = 1; end: /* The secrets are sensitive, so ensure they are erased before freeing. */ OPENSSL_clear_free(peer1.secret, peer1.secret_len); OPENSSL_clear_free(peer2.secret, peer2.secret_len); EVP_PKEY_free(peer1.privk); EVP_PKEY_free(peer2.privk); OSSL_LIB_CTX_free(libctx); return ret; } int main(int argc, char **argv) { /* Test X25519 key exchange with known result. */ printf("Key exchange using known answer (deterministic):\n"); if (keyexch_x25519(1) == 0) return EXIT_FAILURE; /* Test X25519 key exchange with random keys. */ printf("Key exchange using random keys:\n"); if (keyexch_x25519(0) == 0) return EXIT_FAILURE; return EXIT_SUCCESS; }
./openssl/demos/guide/quic-client-block.c
/* * Copyright 2023 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ /* * NB: Changes to this file should also be reflected in * doc/man7/ossl-guide-quic-client-block.pod */ #include <string.h> /* Include the appropriate header file for SOCK_DGRAM */ #ifdef _WIN32 /* Windows */ # include <winsock2.h> #else /* Linux/Unix */ # include <sys/socket.h> #endif #include <openssl/bio.h> #include <openssl/ssl.h> #include <openssl/err.h> /* Helper function to create a BIO connected to the server */ static BIO *create_socket_bio(const char *hostname, const char *port, int family, BIO_ADDR **peer_addr) { int sock = -1; BIO_ADDRINFO *res; const BIO_ADDRINFO *ai = NULL; BIO *bio; /* * Lookup IP address info for the server. */ if (!BIO_lookup_ex(hostname, port, BIO_LOOKUP_CLIENT, family, SOCK_DGRAM, 0, &res)) return NULL; /* * Loop through all the possible addresses for the server and find one * we can connect to. */ for (ai = res; ai != NULL; ai = BIO_ADDRINFO_next(ai)) { /* * Create a UDP socket. We could equally use non-OpenSSL calls such * as "socket" here for this and the subsequent connect and close * functions. But for portability reasons and also so that we get * errors on the OpenSSL stack in the event of a failure we use * OpenSSL's versions of these functions. */ sock = BIO_socket(BIO_ADDRINFO_family(ai), SOCK_DGRAM, 0, 0); if (sock == -1) continue; /* Connect the socket to the server's address */ if (!BIO_connect(sock, BIO_ADDRINFO_address(ai), 0)) { BIO_closesocket(sock); sock = -1; continue; } /* Set to nonblocking mode */ if (!BIO_socket_nbio(sock, 1)) { BIO_closesocket(sock); sock = -1; continue; } break; } if (sock != -1) { *peer_addr = BIO_ADDR_dup(BIO_ADDRINFO_address(ai)); if (*peer_addr == NULL) { BIO_closesocket(sock); return NULL; } } /* Free the address information resources we allocated earlier */ BIO_ADDRINFO_free(res); /* If sock is -1 then we've been unable to connect to the server */ if (sock == -1) return NULL; /* Create a BIO to wrap the socket */ bio = BIO_new(BIO_s_datagram()); if (bio == NULL) { BIO_closesocket(sock); return NULL; } /* * Associate the newly created BIO with the underlying socket. By * passing BIO_CLOSE here the socket will be automatically closed when * the BIO is freed. Alternatively you can use BIO_NOCLOSE, in which * case you must close the socket explicitly when it is no longer * needed. */ BIO_set_fd(bio, sock, BIO_CLOSE); return bio; } /* * Simple application to send a basic HTTP/1.0 request to a server and * print the response on the screen. Note that HTTP/1.0 over QUIC is * non-standard and will not typically be supported by real world servers. This * is for demonstration purposes only. */ int main(int argc, char *argv[]) { SSL_CTX *ctx = NULL; SSL *ssl = NULL; BIO *bio = NULL; int res = EXIT_FAILURE; int ret; unsigned char alpn[] = { 8, 'h', 't', 't', 'p', '/', '1', '.', '0' }; const char *request_start = "GET / HTTP/1.0\r\nConnection: close\r\nHost: "; const char *request_end = "\r\n\r\n"; size_t written, readbytes; char buf[160]; BIO_ADDR *peer_addr = NULL; char *hostname, *port; int argnext = 1; int ipv6 = 0; if (argc < 3) { printf("Usage: quic-client-block [-6] hostname port\n"); goto end; } if (!strcmp(argv[argnext], "-6")) { if (argc < 4) { printf("Usage: quic-client-block [-6] hostname port\n"); goto end; } ipv6 = 1; argnext++; } hostname = argv[argnext++]; port = argv[argnext]; /* * Create an SSL_CTX which we can use to create SSL objects from. We * want an SSL_CTX for creating clients so we use * OSSL_QUIC_client_method() here. */ ctx = SSL_CTX_new(OSSL_QUIC_client_method()); if (ctx == NULL) { printf("Failed to create the SSL_CTX\n"); goto end; } /* * Configure the client to abort the handshake if certificate * verification fails. Virtually all clients should do this unless you * really know what you are doing. */ SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, NULL); /* Use the default trusted certificate store */ if (!SSL_CTX_set_default_verify_paths(ctx)) { printf("Failed to set the default trusted certificate store\n"); goto end; } /* Create an SSL object to represent the TLS connection */ ssl = SSL_new(ctx); if (ssl == NULL) { printf("Failed to create the SSL object\n"); goto end; } /* * Create the underlying transport socket/BIO and associate it with the * connection. */ bio = create_socket_bio(hostname, port, ipv6 ? AF_INET6 : AF_INET, &peer_addr); if (bio == NULL) { printf("Failed to crete the BIO\n"); goto end; } SSL_set_bio(ssl, bio, bio); /* * Tell the server during the handshake which hostname we are attempting * to connect to in case the server supports multiple hosts. */ if (!SSL_set_tlsext_host_name(ssl, hostname)) { printf("Failed to set the SNI hostname\n"); goto end; } /* * Ensure we check during certificate verification that the server has * supplied a certificate for the hostname that we were expecting. * Virtually all clients should do this unless you really know what you * are doing. */ if (!SSL_set1_host(ssl, hostname)) { printf("Failed to set the certificate verification hostname"); goto end; } /* SSL_set_alpn_protos returns 0 for success! */ if (SSL_set_alpn_protos(ssl, alpn, sizeof(alpn)) != 0) { printf("Failed to set the ALPN for the connection\n"); goto end; } /* Set the IP address of the remote peer */ if (!SSL_set1_initial_peer_addr(ssl, peer_addr)) { printf("Failed to set the initial peer address\n"); goto end; } /* Do the handshake with the server */ if (SSL_connect(ssl) < 1) { printf("Failed to connect to the server\n"); /* * If the failure is due to a verification error we can get more * information about it from SSL_get_verify_result(). */ if (SSL_get_verify_result(ssl) != X509_V_OK) printf("Verify error: %s\n", X509_verify_cert_error_string(SSL_get_verify_result(ssl))); goto end; } /* Write an HTTP GET request to the peer */ if (!SSL_write_ex(ssl, request_start, strlen(request_start), &written)) { printf("Failed to write start of HTTP request\n"); goto end; } if (!SSL_write_ex(ssl, hostname, strlen(hostname), &written)) { printf("Failed to write hostname in HTTP request\n"); goto end; } if (!SSL_write_ex(ssl, request_end, strlen(request_end), &written)) { printf("Failed to write end of HTTP request\n"); goto end; } /* * Get up to sizeof(buf) bytes of the response. We keep reading until the * server closes the connection. */ while (SSL_read_ex(ssl, buf, sizeof(buf), &readbytes)) { /* * OpenSSL does not guarantee that the returned data is a string or * that it is NUL terminated so we use fwrite() to write the exact * number of bytes that we read. The data could be non-printable or * have NUL characters in the middle of it. For this simple example * we're going to print it to stdout anyway. */ fwrite(buf, 1, readbytes, stdout); } /* In case the response didn't finish with a newline we add one now */ printf("\n"); /* * Check whether we finished the while loop above normally or as the * result of an error. The 0 argument to SSL_get_error() is the return * code we received from the SSL_read_ex() call. It must be 0 in order * to get here. Normal completion is indicated by SSL_ERROR_ZERO_RETURN. In * QUIC terms this means that the peer has sent FIN on the stream to * indicate that no further data will be sent. */ switch (SSL_get_error(ssl, 0)) { case SSL_ERROR_ZERO_RETURN: /* Normal completion of the stream */ break; case SSL_ERROR_SSL: /* * Some stream fatal error occurred. This could be because of a stream * reset - or some failure occurred on the underlying connection. */ switch (SSL_get_stream_read_state(ssl)) { case SSL_STREAM_STATE_RESET_REMOTE: printf("Stream reset occurred\n"); /* The stream has been reset but the connection is still healthy. */ break; case SSL_STREAM_STATE_CONN_CLOSED: printf("Connection closed\n"); /* Connection is already closed. Skip SSL_shutdown() */ goto end; default: printf("Unknown stream failure\n"); break; } break; default: /* Some other unexpected error occurred */ printf ("Failed reading remaining data\n"); break; } /* * Repeatedly call SSL_shutdown() until the connection is fully * closed. */ do { ret = SSL_shutdown(ssl); if (ret < 0) { printf("Error shutting down: %d\n", ret); goto end; } } while (ret != 1); /* Success! */ res = EXIT_SUCCESS; end: /* * If something bad happened then we will dump the contents of the * OpenSSL error stack to stderr. There might be some useful diagnostic * information there. */ if (res == EXIT_FAILURE) ERR_print_errors_fp(stderr); /* * Free the resources we allocated. We do not free the BIO object here * because ownership of it was immediately transferred to the SSL object * via SSL_set_bio(). The BIO will be freed when we free the SSL object. */ SSL_free(ssl); SSL_CTX_free(ctx); BIO_ADDR_free(peer_addr); return res; }
./openssl/demos/guide/quic-client-non-block.c
/* * Copyright 2023 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ /* * NB: Changes to this file should also be reflected in * doc/man7/ossl-guide-quic-client-non-block.pod */ #include <string.h> /* Include the appropriate header file for SOCK_DGRAM */ #ifdef _WIN32 /* Windows */ # include <winsock2.h> #else /* Linux/Unix */ # include <sys/socket.h> # include <sys/select.h> #endif #include <openssl/bio.h> #include <openssl/ssl.h> #include <openssl/err.h> /* Helper function to create a BIO connected to the server */ static BIO *create_socket_bio(const char *hostname, const char *port, int family, BIO_ADDR **peer_addr) { int sock = -1; BIO_ADDRINFO *res; const BIO_ADDRINFO *ai = NULL; BIO *bio; /* * Lookup IP address info for the server. */ if (!BIO_lookup_ex(hostname, port, BIO_LOOKUP_CLIENT, family, SOCK_DGRAM, 0, &res)) return NULL; /* * Loop through all the possible addresses for the server and find one * we can connect to. */ for (ai = res; ai != NULL; ai = BIO_ADDRINFO_next(ai)) { /* * Create a UDP socket. We could equally use non-OpenSSL calls such * as "socket" here for this and the subsequent connect and close * functions. But for portability reasons and also so that we get * errors on the OpenSSL stack in the event of a failure we use * OpenSSL's versions of these functions. */ sock = BIO_socket(BIO_ADDRINFO_family(ai), SOCK_DGRAM, 0, 0); if (sock == -1) continue; /* Connect the socket to the server's address */ if (!BIO_connect(sock, BIO_ADDRINFO_address(ai), 0)) { BIO_closesocket(sock); sock = -1; continue; } /* Set to nonblocking mode */ if (!BIO_socket_nbio(sock, 1)) { BIO_closesocket(sock); sock = -1; continue; } break; } if (sock != -1) { *peer_addr = BIO_ADDR_dup(BIO_ADDRINFO_address(ai)); if (*peer_addr == NULL) { BIO_closesocket(sock); return NULL; } } /* Free the address information resources we allocated earlier */ BIO_ADDRINFO_free(res); /* If sock is -1 then we've been unable to connect to the server */ if (sock == -1) return NULL; /* Create a BIO to wrap the socket */ bio = BIO_new(BIO_s_datagram()); if (bio == NULL) { BIO_closesocket(sock); return NULL; } /* * Associate the newly created BIO with the underlying socket. By * passing BIO_CLOSE here the socket will be automatically closed when * the BIO is freed. Alternatively you can use BIO_NOCLOSE, in which * case you must close the socket explicitly when it is no longer * needed. */ BIO_set_fd(bio, sock, BIO_CLOSE); return bio; } static void wait_for_activity(SSL *ssl) { fd_set wfds, rfds; int width, sock, isinfinite; struct timeval tv; struct timeval *tvp = NULL; /* Get hold of the underlying file descriptor for the socket */ sock = SSL_get_fd(ssl); FD_ZERO(&wfds); FD_ZERO(&rfds); /* * Find out if we would like to write to the socket, or read from it (or * both) */ if (SSL_net_write_desired(ssl)) FD_SET(sock, &wfds); if (SSL_net_read_desired(ssl)) FD_SET(sock, &rfds); width = sock + 1; /* * Find out when OpenSSL would next like to be called, regardless of * whether the state of the underlying socket has changed or not. */ if (SSL_get_event_timeout(ssl, &tv, &isinfinite) && !isinfinite) tvp = &tv; /* * Wait until the socket is writeable or readable. We use select here * for the sake of simplicity and portability, but you could equally use * poll/epoll or similar functions * * NOTE: For the purposes of this demonstration code this effectively * makes this demo block until it has something more useful to do. In a * real application you probably want to go and do other work here (e.g. * update a GUI, or service other connections). * * Let's say for example that you want to update the progress counter on * a GUI every 100ms. One way to do that would be to use the timeout in * the last parameter to "select" below. If the tvp value is greater * than 100ms then use 100ms instead. Then, when select returns, you * check if it did so because of activity on the file descriptors or * because of the timeout. If the 100ms GUI timeout has expired but the * tvp timeout has not then go and update the GUI and then restart the * "select" (with updated timeouts). */ select(width, &rfds, &wfds, NULL, tvp); } static int handle_io_failure(SSL *ssl, int res) { switch (SSL_get_error(ssl, res)) { case SSL_ERROR_WANT_READ: case SSL_ERROR_WANT_WRITE: /* Temporary failure. Wait until we can read/write and try again */ wait_for_activity(ssl); return 1; case SSL_ERROR_ZERO_RETURN: /* EOF */ return 0; case SSL_ERROR_SYSCALL: return -1; case SSL_ERROR_SSL: /* * Some stream fatal error occurred. This could be because of a * stream reset - or some failure occurred on the underlying * connection. */ switch (SSL_get_stream_read_state(ssl)) { case SSL_STREAM_STATE_RESET_REMOTE: printf("Stream reset occurred\n"); /* * The stream has been reset but the connection is still * healthy. */ break; case SSL_STREAM_STATE_CONN_CLOSED: printf("Connection closed\n"); /* Connection is already closed. */ break; default: printf("Unknown stream failure\n"); break; } /* * If the failure is due to a verification error we can get more * information about it from SSL_get_verify_result(). */ if (SSL_get_verify_result(ssl) != X509_V_OK) printf("Verify error: %s\n", X509_verify_cert_error_string(SSL_get_verify_result(ssl))); return -1; default: return -1; } } /* * Simple application to send a basic HTTP/1.0 request to a server and * print the response on the screen. Note that HTTP/1.0 over QUIC is * non-standard and will not typically be supported by real world servers. This * is for demonstration purposes only. */ int main(int argc, char *argv[]) { SSL_CTX *ctx = NULL; SSL *ssl = NULL; BIO *bio = NULL; int res = EXIT_FAILURE; int ret; unsigned char alpn[] = { 8, 'h', 't', 't', 'p', '/', '1', '.', '0' }; const char *request_start = "GET / HTTP/1.0\r\nConnection: close\r\nHost: "; const char *request_end = "\r\n\r\n"; size_t written, readbytes; char buf[160]; BIO_ADDR *peer_addr = NULL; int eof = 0; char *hostname, *port; int ipv6 = 0; int argnext = 1; if (argc < 3) { printf("Usage: quic-client-non-block [-6] hostname port\n"); goto end; } if (!strcmp(argv[argnext], "-6")) { if (argc < 4) { printf("Usage: quic-client-non-block [-6] hostname port\n"); goto end; } ipv6 = 1; argnext++; } hostname = argv[argnext++]; port = argv[argnext]; /* * Create an SSL_CTX which we can use to create SSL objects from. We * want an SSL_CTX for creating clients so we use * OSSL_QUIC_client_method() here. */ ctx = SSL_CTX_new(OSSL_QUIC_client_method()); if (ctx == NULL) { printf("Failed to create the SSL_CTX\n"); goto end; } /* * Configure the client to abort the handshake if certificate * verification fails. Virtually all clients should do this unless you * really know what you are doing. */ SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, NULL); /* Use the default trusted certificate store */ if (!SSL_CTX_set_default_verify_paths(ctx)) { printf("Failed to set the default trusted certificate store\n"); goto end; } /* Create an SSL object to represent the TLS connection */ ssl = SSL_new(ctx); if (ssl == NULL) { printf("Failed to create the SSL object\n"); goto end; } /* * Create the underlying transport socket/BIO and associate it with the * connection. */ bio = create_socket_bio(hostname, port, ipv6 ? AF_INET6 : AF_INET, &peer_addr); if (bio == NULL) { printf("Failed to crete the BIO\n"); goto end; } SSL_set_bio(ssl, bio, bio); /* * Tell the server during the handshake which hostname we are attempting * to connect to in case the server supports multiple hosts. */ if (!SSL_set_tlsext_host_name(ssl, hostname)) { printf("Failed to set the SNI hostname\n"); goto end; } /* * Ensure we check during certificate verification that the server has * supplied a certificate for the hostname that we were expecting. * Virtually all clients should do this unless you really know what you * are doing. */ if (!SSL_set1_host(ssl, hostname)) { printf("Failed to set the certificate verification hostname"); goto end; } /* SSL_set_alpn_protos returns 0 for success! */ if (SSL_set_alpn_protos(ssl, alpn, sizeof(alpn)) != 0) { printf("Failed to set the ALPN for the connection\n"); goto end; } /* Set the IP address of the remote peer */ if (!SSL_set1_initial_peer_addr(ssl, peer_addr)) { printf("Failed to set the initial peer address\n"); goto end; } /* * The underlying socket is always nonblocking with QUIC, but the default * behaviour of the SSL object is still to block. We set it for nonblocking * mode in this demo. */ if (!SSL_set_blocking_mode(ssl, 0)) { printf("Failed to turn off blocking mode\n"); goto end; } /* Do the handshake with the server */ while ((ret = SSL_connect(ssl)) != 1) { if (handle_io_failure(ssl, ret) == 1) continue; /* Retry */ printf("Failed to connect to server\n"); goto end; /* Cannot retry: error */ } /* Write an HTTP GET request to the peer */ while (!SSL_write_ex(ssl, request_start, strlen(request_start), &written)) { if (handle_io_failure(ssl, 0) == 1) continue; /* Retry */ printf("Failed to write start of HTTP request\n"); goto end; /* Cannot retry: error */ } while (!SSL_write_ex(ssl, hostname, strlen(hostname), &written)) { if (handle_io_failure(ssl, 0) == 1) continue; /* Retry */ printf("Failed to write hostname in HTTP request\n"); goto end; /* Cannot retry: error */ } while (!SSL_write_ex(ssl, request_end, strlen(request_end), &written)) { if (handle_io_failure(ssl, 0) == 1) continue; /* Retry */ printf("Failed to write end of HTTP request\n"); goto end; /* Cannot retry: error */ } do { /* * Get up to sizeof(buf) bytes of the response. We keep reading until * the server closes the connection. */ while (!eof && !SSL_read_ex(ssl, buf, sizeof(buf), &readbytes)) { switch (handle_io_failure(ssl, 0)) { case 1: continue; /* Retry */ case 0: eof = 1; continue; case -1: default: printf("Failed reading remaining data\n"); goto end; /* Cannot retry: error */ } } /* * OpenSSL does not guarantee that the returned data is a string or * that it is NUL terminated so we use fwrite() to write the exact * number of bytes that we read. The data could be non-printable or * have NUL characters in the middle of it. For this simple example * we're going to print it to stdout anyway. */ if (!eof) fwrite(buf, 1, readbytes, stdout); } while (!eof); /* In case the response didn't finish with a newline we add one now */ printf("\n"); /* * Repeatedly call SSL_shutdown() until the connection is fully * closed. */ while ((ret = SSL_shutdown(ssl)) != 1) { if (ret < 0 && handle_io_failure(ssl, ret) == 1) continue; /* Retry */ } /* Success! */ res = EXIT_SUCCESS; end: /* * If something bad happened then we will dump the contents of the * OpenSSL error stack to stderr. There might be some useful diagnostic * information there. */ if (res == EXIT_FAILURE) ERR_print_errors_fp(stderr); /* * Free the resources we allocated. We do not free the BIO object here * because ownership of it was immediately transferred to the SSL object * via SSL_set_bio(). The BIO will be freed when we free the SSL object. */ SSL_free(ssl); SSL_CTX_free(ctx); BIO_ADDR_free(peer_addr); return res; }
./openssl/demos/guide/tls-client-block.c
/* * Copyright 2023 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ /* * NB: Changes to this file should also be reflected in * doc/man7/ossl-guide-tls-client-block.pod */ #include <string.h> /* Include the appropriate header file for SOCK_STREAM */ #ifdef _WIN32 /* Windows */ # include <winsock2.h> #else /* Linux/Unix */ # include <sys/socket.h> #endif #include <openssl/bio.h> #include <openssl/ssl.h> #include <openssl/err.h> /* Helper function to create a BIO connected to the server */ static BIO *create_socket_bio(const char *hostname, const char *port, int family) { int sock = -1; BIO_ADDRINFO *res; const BIO_ADDRINFO *ai = NULL; BIO *bio; /* * Lookup IP address info for the server. */ if (!BIO_lookup_ex(hostname, port, BIO_LOOKUP_CLIENT, family, SOCK_STREAM, 0, &res)) return NULL; /* * Loop through all the possible addresses for the server and find one * we can connect to. */ for (ai = res; ai != NULL; ai = BIO_ADDRINFO_next(ai)) { /* * Create a TCP socket. We could equally use non-OpenSSL calls such * as "socket" here for this and the subsequent connect and close * functions. But for portability reasons and also so that we get * errors on the OpenSSL stack in the event of a failure we use * OpenSSL's versions of these functions. */ sock = BIO_socket(BIO_ADDRINFO_family(ai), SOCK_STREAM, 0, 0); if (sock == -1) continue; /* Connect the socket to the server's address */ if (!BIO_connect(sock, BIO_ADDRINFO_address(ai), BIO_SOCK_NODELAY)) { BIO_closesocket(sock); sock = -1; continue; } /* We have a connected socket so break out of the loop */ break; } /* Free the address information resources we allocated earlier */ BIO_ADDRINFO_free(res); /* If sock is -1 then we've been unable to connect to the server */ if (sock == -1) return NULL; /* Create a BIO to wrap the socket */ bio = BIO_new(BIO_s_socket()); if (bio == NULL) { BIO_closesocket(sock); return NULL; } /* * Associate the newly created BIO with the underlying socket. By * passing BIO_CLOSE here the socket will be automatically closed when * the BIO is freed. Alternatively you can use BIO_NOCLOSE, in which * case you must close the socket explicitly when it is no longer * needed. */ BIO_set_fd(bio, sock, BIO_CLOSE); return bio; } /* * Simple application to send a basic HTTP/1.0 request to a server and * print the response on the screen. */ int main(int argc, char *argv[]) { SSL_CTX *ctx = NULL; SSL *ssl = NULL; BIO *bio = NULL; int res = EXIT_FAILURE; int ret; const char *request_start = "GET / HTTP/1.0\r\nConnection: close\r\nHost: "; const char *request_end = "\r\n\r\n"; size_t written, readbytes; char buf[160]; char *hostname, *port; int argnext = 1; int ipv6 = 0; if (argc < 3) { printf("Usage: tls-client-block [-6] hostname port\n"); goto end; } if (!strcmp(argv[argnext], "-6")) { if (argc < 4) { printf("Usage: tls-client-block [-6] hostname port\n"); goto end; } ipv6 = 1; argnext++; } hostname = argv[argnext++]; port = argv[argnext]; /* * Create an SSL_CTX which we can use to create SSL objects from. We * want an SSL_CTX for creating clients so we use TLS_client_method() * here. */ ctx = SSL_CTX_new(TLS_client_method()); if (ctx == NULL) { printf("Failed to create the SSL_CTX\n"); goto end; } /* * Configure the client to abort the handshake if certificate * verification fails. Virtually all clients should do this unless you * really know what you are doing. */ SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, NULL); /* Use the default trusted certificate store */ if (!SSL_CTX_set_default_verify_paths(ctx)) { printf("Failed to set the default trusted certificate store\n"); goto end; } /* * TLSv1.1 or earlier are deprecated by IETF and are generally to be * avoided if possible. We require a minimum TLS version of TLSv1.2. */ if (!SSL_CTX_set_min_proto_version(ctx, TLS1_2_VERSION)) { printf("Failed to set the minimum TLS protocol version\n"); goto end; } /* Create an SSL object to represent the TLS connection */ ssl = SSL_new(ctx); if (ssl == NULL) { printf("Failed to create the SSL object\n"); goto end; } /* * Create the underlying transport socket/BIO and associate it with the * connection. */ bio = create_socket_bio(hostname, port, ipv6 ? AF_INET6 : AF_INET); if (bio == NULL) { printf("Failed to crete the BIO\n"); goto end; } SSL_set_bio(ssl, bio, bio); /* * Tell the server during the handshake which hostname we are attempting * to connect to in case the server supports multiple hosts. */ if (!SSL_set_tlsext_host_name(ssl, hostname)) { printf("Failed to set the SNI hostname\n"); goto end; } /* * Ensure we check during certificate verification that the server has * supplied a certificate for the hostname that we were expecting. * Virtually all clients should do this unless you really know what you * are doing. */ if (!SSL_set1_host(ssl, hostname)) { printf("Failed to set the certificate verification hostname"); goto end; } /* Do the handshake with the server */ if (SSL_connect(ssl) < 1) { printf("Failed to connect to the server\n"); /* * If the failure is due to a verification error we can get more * information about it from SSL_get_verify_result(). */ if (SSL_get_verify_result(ssl) != X509_V_OK) printf("Verify error: %s\n", X509_verify_cert_error_string(SSL_get_verify_result(ssl))); goto end; } /* Write an HTTP GET request to the peer */ if (!SSL_write_ex(ssl, request_start, strlen(request_start), &written)) { printf("Failed to write start of HTTP request\n"); goto end; } if (!SSL_write_ex(ssl, hostname, strlen(hostname), &written)) { printf("Failed to write hostname in HTTP request\n"); goto end; } if (!SSL_write_ex(ssl, request_end, strlen(request_end), &written)) { printf("Failed to write end of HTTP request\n"); goto end; } /* * Get up to sizeof(buf) bytes of the response. We keep reading until the * server closes the connection. */ while (SSL_read_ex(ssl, buf, sizeof(buf), &readbytes)) { /* * OpenSSL does not guarantee that the returned data is a string or * that it is NUL terminated so we use fwrite() to write the exact * number of bytes that we read. The data could be non-printable or * have NUL characters in the middle of it. For this simple example * we're going to print it to stdout anyway. */ fwrite(buf, 1, readbytes, stdout); } /* In case the response didn't finish with a newline we add one now */ printf("\n"); /* * Check whether we finished the while loop above normally or as the * result of an error. The 0 argument to SSL_get_error() is the return * code we received from the SSL_read_ex() call. It must be 0 in order * to get here. Normal completion is indicated by SSL_ERROR_ZERO_RETURN. */ if (SSL_get_error(ssl, 0) != SSL_ERROR_ZERO_RETURN) { /* * Some error occurred other than a graceful close down by the * peer. */ printf ("Failed reading remaining data\n"); goto end; } /* * The peer already shutdown gracefully (we know this because of the * SSL_ERROR_ZERO_RETURN above). We should do the same back. */ ret = SSL_shutdown(ssl); if (ret < 1) { /* * ret < 0 indicates an error. ret == 0 would be unexpected here * because that means "we've sent a close_notify and we're waiting * for one back". But we already know we got one from the peer * because of the SSL_ERROR_ZERO_RETURN above. */ printf("Error shutting down\n"); goto end; } /* Success! */ res = EXIT_SUCCESS; end: /* * If something bad happened then we will dump the contents of the * OpenSSL error stack to stderr. There might be some useful diagnostic * information there. */ if (res == EXIT_FAILURE) ERR_print_errors_fp(stderr); /* * Free the resources we allocated. We do not free the BIO object here * because ownership of it was immediately transferred to the SSL object * via SSL_set_bio(). The BIO will be freed when we free the SSL object. */ SSL_free(ssl); SSL_CTX_free(ctx); return res; }
./openssl/demos/guide/tls-client-non-block.c
/* * Copyright 2023 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ /* * NB: Changes to this file should also be reflected in * doc/man7/ossl-guide-tls-client-non-block.pod */ #include <string.h> /* Include the appropriate header file for SOCK_STREAM */ #ifdef _WIN32 /* Windows */ # include <winsock2.h> #else /* Linux/Unix */ # include <sys/socket.h> # include <sys/select.h> #endif #include <openssl/bio.h> #include <openssl/ssl.h> #include <openssl/err.h> /* Helper function to create a BIO connected to the server */ static BIO *create_socket_bio(const char *hostname, const char *port, int family) { int sock = -1; BIO_ADDRINFO *res; const BIO_ADDRINFO *ai = NULL; BIO *bio; /* * Lookup IP address info for the server. */ if (!BIO_lookup_ex(hostname, port, BIO_LOOKUP_CLIENT, family, SOCK_STREAM, 0, &res)) return NULL; /* * Loop through all the possible addresses for the server and find one * we can connect to. */ for (ai = res; ai != NULL; ai = BIO_ADDRINFO_next(ai)) { /* * Create a TCP socket. We could equally use non-OpenSSL calls such * as "socket" here for this and the subsequent connect and close * functions. But for portability reasons and also so that we get * errors on the OpenSSL stack in the event of a failure we use * OpenSSL's versions of these functions. */ sock = BIO_socket(BIO_ADDRINFO_family(ai), SOCK_STREAM, 0, 0); if (sock == -1) continue; /* Connect the socket to the server's address */ if (!BIO_connect(sock, BIO_ADDRINFO_address(ai), BIO_SOCK_NODELAY)) { BIO_closesocket(sock); sock = -1; continue; } /* Set to nonblocking mode */ if (!BIO_socket_nbio(sock, 1)) { sock = -1; continue; } /* We have a connected socket so break out of the loop */ break; } /* Free the address information resources we allocated earlier */ BIO_ADDRINFO_free(res); /* If sock is -1 then we've been unable to connect to the server */ if (sock == -1) return NULL; /* Create a BIO to wrap the socket */ bio = BIO_new(BIO_s_socket()); if (bio == NULL) { BIO_closesocket(sock); return NULL; } /* * Associate the newly created BIO with the underlying socket. By * passing BIO_CLOSE here the socket will be automatically closed when * the BIO is freed. Alternatively you can use BIO_NOCLOSE, in which * case you must close the socket explicitly when it is no longer * needed. */ BIO_set_fd(bio, sock, BIO_CLOSE); return bio; } static void wait_for_activity(SSL *ssl, int write) { fd_set fds; int width, sock; /* Get hold of the underlying file descriptor for the socket */ sock = SSL_get_fd(ssl); FD_ZERO(&fds); FD_SET(sock, &fds); width = sock + 1; /* * Wait until the socket is writeable or readable. We use select here * for the sake of simplicity and portability, but you could equally use * poll/epoll or similar functions * * NOTE: For the purposes of this demonstration code this effectively * makes this demo block until it has something more useful to do. In a * real application you probably want to go and do other work here (e.g. * update a GUI, or service other connections). * * Let's say for example that you want to update the progress counter on * a GUI every 100ms. One way to do that would be to add a 100ms timeout * in the last parameter to "select" below. Then, when select returns, * you check if it did so because of activity on the file descriptors or * because of the timeout. If it is due to the timeout then update the * GUI and then restart the "select". */ if (write) select(width, NULL, &fds, NULL, NULL); else select(width, &fds, NULL, NULL, NULL); } static int handle_io_failure(SSL *ssl, int res) { switch (SSL_get_error(ssl, res)) { case SSL_ERROR_WANT_READ: /* Temporary failure. Wait until we can read and try again */ wait_for_activity(ssl, 0); return 1; case SSL_ERROR_WANT_WRITE: /* Temporary failure. Wait until we can write and try again */ wait_for_activity(ssl, 1); return 1; case SSL_ERROR_ZERO_RETURN: /* EOF */ return 0; case SSL_ERROR_SYSCALL: return -1; case SSL_ERROR_SSL: /* * If the failure is due to a verification error we can get more * information about it from SSL_get_verify_result(). */ if (SSL_get_verify_result(ssl) != X509_V_OK) printf("Verify error: %s\n", X509_verify_cert_error_string(SSL_get_verify_result(ssl))); return -1; default: return -1; } } /* * Simple application to send a basic HTTP/1.0 request to a server and * print the response on the screen. */ int main(int argc, char *argv[]) { SSL_CTX *ctx = NULL; SSL *ssl = NULL; BIO *bio = NULL; int res = EXIT_FAILURE; int ret; const char *request_start = "GET / HTTP/1.0\r\nConnection: close\r\nHost: "; const char *request_end = "\r\n\r\n"; size_t written, readbytes; char buf[160]; int eof = 0; char *hostname, *port; int argnext = 1; int ipv6 = 0; if (argc < 3) { printf("Usage: tls-client-non-block [-6] hostname port\n"); goto end; } if (!strcmp(argv[argnext], "-6")) { if (argc < 4) { printf("Usage: tls-client-non-block [-6] hostname port\n"); goto end; } ipv6 = 1; argnext++; } hostname = argv[argnext++]; port = argv[argnext]; /* * Create an SSL_CTX which we can use to create SSL objects from. We * want an SSL_CTX for creating clients so we use TLS_client_method() * here. */ ctx = SSL_CTX_new(TLS_client_method()); if (ctx == NULL) { printf("Failed to create the SSL_CTX\n"); goto end; } /* * Configure the client to abort the handshake if certificate * verification fails. Virtually all clients should do this unless you * really know what you are doing. */ SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, NULL); /* Use the default trusted certificate store */ if (!SSL_CTX_set_default_verify_paths(ctx)) { printf("Failed to set the default trusted certificate store\n"); goto end; } /* * TLSv1.1 or earlier are deprecated by IETF and are generally to be * avoided if possible. We require a minimum TLS version of TLSv1.2. */ if (!SSL_CTX_set_min_proto_version(ctx, TLS1_2_VERSION)) { printf("Failed to set the minimum TLS protocol version\n"); goto end; } /* Create an SSL object to represent the TLS connection */ ssl = SSL_new(ctx); if (ssl == NULL) { printf("Failed to create the SSL object\n"); goto end; } /* * Create the underlying transport socket/BIO and associate it with the * connection. */ bio = create_socket_bio(hostname, port, ipv6 ? AF_INET6 : AF_INET); if (bio == NULL) { printf("Failed to crete the BIO\n"); goto end; } SSL_set_bio(ssl, bio, bio); /* * Tell the server during the handshake which hostname we are attempting * to connect to in case the server supports multiple hosts. */ if (!SSL_set_tlsext_host_name(ssl, hostname)) { printf("Failed to set the SNI hostname\n"); goto end; } /* * Ensure we check during certificate verification that the server has * supplied a certificate for the hostname that we were expecting. * Virtually all clients should do this unless you really know what you * are doing. */ if (!SSL_set1_host(ssl, hostname)) { printf("Failed to set the certificate verification hostname"); goto end; } /* Do the handshake with the server */ while ((ret = SSL_connect(ssl)) != 1) { if (handle_io_failure(ssl, ret) == 1) continue; /* Retry */ printf("Failed to connect to server\n"); goto end; /* Cannot retry: error */ } /* Write an HTTP GET request to the peer */ while (!SSL_write_ex(ssl, request_start, strlen(request_start), &written)) { if (handle_io_failure(ssl, 0) == 1) continue; /* Retry */ printf("Failed to write start of HTTP request\n"); goto end; /* Cannot retry: error */ } while (!SSL_write_ex(ssl, hostname, strlen(hostname), &written)) { if (handle_io_failure(ssl, 0) == 1) continue; /* Retry */ printf("Failed to write hostname in HTTP request\n"); goto end; /* Cannot retry: error */ } while (!SSL_write_ex(ssl, request_end, strlen(request_end), &written)) { if (handle_io_failure(ssl, 0) == 1) continue; /* Retry */ printf("Failed to write end of HTTP request\n"); goto end; /* Cannot retry: error */ } do { /* * Get up to sizeof(buf) bytes of the response. We keep reading until * the server closes the connection. */ while (!eof && !SSL_read_ex(ssl, buf, sizeof(buf), &readbytes)) { switch (handle_io_failure(ssl, 0)) { case 1: continue; /* Retry */ case 0: eof = 1; continue; case -1: default: printf("Failed reading remaining data\n"); goto end; /* Cannot retry: error */ } } /* * OpenSSL does not guarantee that the returned data is a string or * that it is NUL terminated so we use fwrite() to write the exact * number of bytes that we read. The data could be non-printable or * have NUL characters in the middle of it. For this simple example * we're going to print it to stdout anyway. */ if (!eof) fwrite(buf, 1, readbytes, stdout); } while (!eof); /* In case the response didn't finish with a newline we add one now */ printf("\n"); /* * The peer already shutdown gracefully (we know this because of the * SSL_ERROR_ZERO_RETURN (i.e. EOF) above). We should do the same back. */ while ((ret = SSL_shutdown(ssl)) != 1) { if (ret < 0 && handle_io_failure(ssl, ret) == 1) continue; /* Retry */ /* * ret == 0 is unexpected here because that means "we've sent a * close_notify and we're waiting for one back". But we already know * we got one from the peer because of the SSL_ERROR_ZERO_RETURN * (i.e. EOF) above. */ printf("Error shutting down\n"); goto end; /* Cannot retry: error */ } /* Success! */ res = EXIT_SUCCESS; end: /* * If something bad happened then we will dump the contents of the * OpenSSL error stack to stderr. There might be some useful diagnostic * information there. */ if (res == EXIT_FAILURE) ERR_print_errors_fp(stderr); /* * Free the resources we allocated. We do not free the BIO object here * because ownership of it was immediately transferred to the SSL object * via SSL_set_bio(). The BIO will be freed when we free the SSL object. */ SSL_free(ssl); SSL_CTX_free(ctx); return res; }
./openssl/demos/guide/quic-multi-stream.c
/* * Copyright 2023 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ /* * NB: Changes to this file should also be reflected in * doc/man7/ossl-guide-quic-multi-stream.pod */ #include <string.h> /* Include the appropriate header file for SOCK_DGRAM */ #ifdef _WIN32 /* Windows */ # include <winsock2.h> #else /* Linux/Unix */ # include <sys/socket.h> #endif #include <openssl/bio.h> #include <openssl/ssl.h> #include <openssl/err.h> /* Helper function to create a BIO connected to the server */ static BIO *create_socket_bio(const char *hostname, const char *port, int family, BIO_ADDR **peer_addr) { int sock = -1; BIO_ADDRINFO *res; const BIO_ADDRINFO *ai = NULL; BIO *bio; /* * Lookup IP address info for the server. */ if (!BIO_lookup_ex(hostname, port, BIO_LOOKUP_CLIENT, family, SOCK_DGRAM, 0, &res)) return NULL; /* * Loop through all the possible addresses for the server and find one * we can connect to. */ for (ai = res; ai != NULL; ai = BIO_ADDRINFO_next(ai)) { /* * Create a UDP socket. We could equally use non-OpenSSL calls such * as "socket" here for this and the subsequent connect and close * functions. But for portability reasons and also so that we get * errors on the OpenSSL stack in the event of a failure we use * OpenSSL's versions of these functions. */ sock = BIO_socket(BIO_ADDRINFO_family(ai), SOCK_DGRAM, 0, 0); if (sock == -1) continue; /* Connect the socket to the server's address */ if (!BIO_connect(sock, BIO_ADDRINFO_address(ai), 0)) { BIO_closesocket(sock); sock = -1; continue; } /* Set to nonblocking mode */ if (!BIO_socket_nbio(sock, 1)) { BIO_closesocket(sock); sock = -1; continue; } break; } if (sock != -1) { *peer_addr = BIO_ADDR_dup(BIO_ADDRINFO_address(ai)); if (*peer_addr == NULL) { BIO_closesocket(sock); return NULL; } } /* Free the address information resources we allocated earlier */ BIO_ADDRINFO_free(res); /* If sock is -1 then we've been unable to connect to the server */ if (sock == -1) return NULL; /* Create a BIO to wrap the socket */ bio = BIO_new(BIO_s_datagram()); if (bio == NULL) { BIO_closesocket(sock); return NULL; } /* * Associate the newly created BIO with the underlying socket. By * passing BIO_CLOSE here the socket will be automatically closed when * the BIO is freed. Alternatively you can use BIO_NOCLOSE, in which * case you must close the socket explicitly when it is no longer * needed. */ BIO_set_fd(bio, sock, BIO_CLOSE); return bio; } int write_a_request(SSL *stream, const char *request_start, const char *hostname) { const char *request_end = "\r\n\r\n"; size_t written; if (!SSL_write_ex(stream, request_start, strlen(request_start), &written)) return 0; if (!SSL_write_ex(stream, hostname, strlen(hostname), &written)) return 0; if (!SSL_write_ex(stream, request_end, strlen(request_end), &written)) return 0; return 1; } /* * Simple application to send basic HTTP/1.0 requests to a server and print the * response on the screen. Note that HTTP/1.0 over QUIC is not a real protocol * and will not be supported by real world servers. This is for demonstration * purposes only. */ int main(int argc, char *argv[]) { SSL_CTX *ctx = NULL; SSL *ssl = NULL; SSL *stream1 = NULL, *stream2 = NULL, *stream3 = NULL; BIO *bio = NULL; int res = EXIT_FAILURE; int ret; unsigned char alpn[] = { 8, 'h', 't', 't', 'p', '/', '1', '.', '0' }; const char *request1_start = "GET /request1.html HTTP/1.0\r\nConnection: close\r\nHost: "; const char *request2_start = "GET /request2.html HTTP/1.0\r\nConnection: close\r\nHost: "; size_t readbytes; char buf[160]; BIO_ADDR *peer_addr = NULL; char *hostname, *port; int argnext = 1; int ipv6 = 0; if (argc < 3) { printf("Usage: quic-client-non-block [-6] hostname port\n"); goto end; } if (!strcmp(argv[argnext], "-6")) { if (argc < 4) { printf("Usage: quic-client-non-block [-6] hostname port\n"); goto end; } ipv6 = 1; argnext++; } hostname = argv[argnext++]; port = argv[argnext]; /* * Create an SSL_CTX which we can use to create SSL objects from. We * want an SSL_CTX for creating clients so we use * OSSL_QUIC_client_method() here. */ ctx = SSL_CTX_new(OSSL_QUIC_client_method()); if (ctx == NULL) { printf("Failed to create the SSL_CTX\n"); goto end; } /* * Configure the client to abort the handshake if certificate * verification fails. Virtually all clients should do this unless you * really know what you are doing. */ SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, NULL); /* Use the default trusted certificate store */ if (!SSL_CTX_set_default_verify_paths(ctx)) { printf("Failed to set the default trusted certificate store\n"); goto end; } /* Create an SSL object to represent the TLS connection */ ssl = SSL_new(ctx); if (ssl == NULL) { printf("Failed to create the SSL object\n"); goto end; } /* * We will use multiple streams so we will disable the default stream mode. * This is not a requirement for using multiple streams but is recommended. */ if (!SSL_set_default_stream_mode(ssl, SSL_DEFAULT_STREAM_MODE_NONE)) { printf("Failed to disable the default stream mode\n"); goto end; } /* * Create the underlying transport socket/BIO and associate it with the * connection. */ bio = create_socket_bio(hostname, port, ipv6 ? AF_INET6 : AF_INET, &peer_addr); if (bio == NULL) { printf("Failed to crete the BIO\n"); goto end; } SSL_set_bio(ssl, bio, bio); /* * Tell the server during the handshake which hostname we are attempting * to connect to in case the server supports multiple hosts. */ if (!SSL_set_tlsext_host_name(ssl, hostname)) { printf("Failed to set the SNI hostname\n"); goto end; } /* * Ensure we check during certificate verification that the server has * supplied a certificate for the hostname that we were expecting. * Virtually all clients should do this unless you really know what you * are doing. */ if (!SSL_set1_host(ssl, hostname)) { printf("Failed to set the certificate verification hostname"); goto end; } /* SSL_set_alpn_protos returns 0 for success! */ if (SSL_set_alpn_protos(ssl, alpn, sizeof(alpn)) != 0) { printf("Failed to set the ALPN for the connection\n"); goto end; } /* Set the IP address of the remote peer */ if (!SSL_set1_initial_peer_addr(ssl, peer_addr)) { printf("Failed to set the initial peer address\n"); goto end; } /* Do the handshake with the server */ if (SSL_connect(ssl) < 1) { printf("Failed to connect to the server\n"); /* * If the failure is due to a verification error we can get more * information about it from SSL_get_verify_result(). */ if (SSL_get_verify_result(ssl) != X509_V_OK) printf("Verify error: %s\n", X509_verify_cert_error_string(SSL_get_verify_result(ssl))); goto end; } /* * We create two new client initiated streams. The first will be * bi-directional, and the second will be uni-directional. */ stream1 = SSL_new_stream(ssl, 0); stream2 = SSL_new_stream(ssl, SSL_STREAM_FLAG_UNI); if (stream1 == NULL || stream2 == NULL) { printf("Failed to create streams\n"); goto end; } /* Write an HTTP GET request on each of our streams to the peer */ if (!write_a_request(stream1, request1_start, hostname)) { printf("Failed to write HTTP request on stream 1\n"); goto end; } if (!write_a_request(stream2, request2_start, hostname)) { printf("Failed to write HTTP request on stream 2\n"); goto end; } /* * In this demo we read all the data from one stream before reading all the * data from the next stream for simplicity. In practice there is no need to * do this. We can interleave IO on the different streams if we wish, or * manage the streams entirely separately on different threads. */ printf("Stream 1 data:\n"); /* * Get up to sizeof(buf) bytes of the response from stream 1 (which is a * bidirectional stream). We keep reading until the server closes the * connection. */ while (SSL_read_ex(stream1, buf, sizeof(buf), &readbytes)) { /* * OpenSSL does not guarantee that the returned data is a string or * that it is NUL terminated so we use fwrite() to write the exact * number of bytes that we read. The data could be non-printable or * have NUL characters in the middle of it. For this simple example * we're going to print it to stdout anyway. */ fwrite(buf, 1, readbytes, stdout); } /* In case the response didn't finish with a newline we add one now */ printf("\n"); /* * Check whether we finished the while loop above normally or as the * result of an error. The 0 argument to SSL_get_error() is the return * code we received from the SSL_read_ex() call. It must be 0 in order * to get here. Normal completion is indicated by SSL_ERROR_ZERO_RETURN. In * QUIC terms this means that the peer has sent FIN on the stream to * indicate that no further data will be sent. */ switch (SSL_get_error(stream1, 0)) { case SSL_ERROR_ZERO_RETURN: /* Normal completion of the stream */ break; case SSL_ERROR_SSL: /* * Some stream fatal error occurred. This could be because of a stream * reset - or some failure occurred on the underlying connection. */ switch (SSL_get_stream_read_state(stream1)) { case SSL_STREAM_STATE_RESET_REMOTE: printf("Stream reset occurred\n"); /* The stream has been reset but the connection is still healthy. */ break; case SSL_STREAM_STATE_CONN_CLOSED: printf("Connection closed\n"); /* Connection is already closed. Skip SSL_shutdown() */ goto end; default: printf("Unknown stream failure\n"); break; } break; default: /* Some other unexpected error occurred */ printf ("Failed reading remaining data\n"); break; } /* * In our hypothetical HTTP/1.0 over QUIC protocol that we are using we * assume that the server will respond with a server initiated stream * containing the data requested in our uni-directional stream. This doesn't * really make sense to do in a real protocol, but its just for * demonstration purposes. * * We're using blocking mode so this will block until a stream becomes * available. We could override this behaviour if we wanted to by setting * the SSL_ACCEPT_STREAM_NO_BLOCK flag in the second argument below. */ stream3 = SSL_accept_stream(ssl, 0); if (stream3 == NULL) { printf("Failed to accept a new stream\n"); goto end; } printf("Stream 3 data:\n"); /* * Read the data from stream 3 like we did for stream 1 above. Note that * stream 2 was uni-directional so there is no data to be read from that * one. */ while (SSL_read_ex(stream3, buf, sizeof(buf), &readbytes)) fwrite(buf, 1, readbytes, stdout); printf("\n"); /* Check for errors on the stream */ switch (SSL_get_error(stream3, 0)) { case SSL_ERROR_ZERO_RETURN: /* Normal completion of the stream */ break; case SSL_ERROR_SSL: switch (SSL_get_stream_read_state(stream3)) { case SSL_STREAM_STATE_RESET_REMOTE: printf("Stream reset occurred\n"); break; case SSL_STREAM_STATE_CONN_CLOSED: printf("Connection closed\n"); goto end; default: printf("Unknown stream failure\n"); break; } break; default: printf ("Failed reading remaining data\n"); break; } /* * Repeatedly call SSL_shutdown() until the connection is fully * closed. */ do { ret = SSL_shutdown(ssl); if (ret < 0) { printf("Error shutting down: %d\n", ret); goto end; } } while (ret != 1); /* Success! */ res = EXIT_SUCCESS; end: /* * If something bad happened then we will dump the contents of the * OpenSSL error stack to stderr. There might be some useful diagnostic * information there. */ if (res == EXIT_FAILURE) ERR_print_errors_fp(stderr); /* * Free the resources we allocated. We do not free the BIO object here * because ownership of it was immediately transferred to the SSL object * via SSL_set_bio(). The BIO will be freed when we free the SSL object. */ SSL_free(ssl); SSL_free(stream1); SSL_free(stream2); SSL_free(stream3); SSL_CTX_free(ctx); BIO_ADDR_free(peer_addr); return res; }
./openssl/demos/pkey/EVP_PKEY_DSA_paramgen.c
/*- * Copyright 2022-2023 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ /* * Example showing how to generate DSA params using * FIPS 186-4 DSA FFC parameter generation. */ #include <openssl/evp.h> #include "dsa.inc" int main(int argc, char **argv) { int ret = EXIT_FAILURE; OSSL_LIB_CTX *libctx = NULL; const char *propq = NULL; EVP_PKEY_CTX *ctx = NULL; EVP_PKEY *dsaparamkey = NULL; OSSL_PARAM params[7]; unsigned int pbits = 2048; unsigned int qbits = 256; int gindex = 42; ctx = EVP_PKEY_CTX_new_from_name(libctx, "DSA", propq); if (ctx == NULL) goto cleanup; /* * Demonstrate how to set optional DSA fields as params. * See doc/man7/EVP_PKEY-FFC.pod and doc/man7/EVP_PKEY-DSA.pod * for more information. */ params[0] = OSSL_PARAM_construct_utf8_string(OSSL_PKEY_PARAM_FFC_TYPE, "fips186_4", 0); params[1] = OSSL_PARAM_construct_uint(OSSL_PKEY_PARAM_FFC_PBITS, &pbits); params[2] = OSSL_PARAM_construct_uint(OSSL_PKEY_PARAM_FFC_QBITS, &qbits); params[3] = OSSL_PARAM_construct_int(OSSL_PKEY_PARAM_FFC_GINDEX, &gindex); params[4] = OSSL_PARAM_construct_utf8_string(OSSL_PKEY_PARAM_FFC_DIGEST, "SHA384", 0); params[5] = OSSL_PARAM_construct_utf8_string(OSSL_PKEY_PARAM_FFC_DIGEST_PROPS, "provider=default", 0); params[6] = OSSL_PARAM_construct_end(); /* Generate a dsa param key using optional params */ if (EVP_PKEY_paramgen_init(ctx) <= 0 || EVP_PKEY_CTX_set_params(ctx, params) <= 0 || EVP_PKEY_paramgen(ctx, &dsaparamkey) <= 0) { fprintf(stderr, "DSA paramgen failed\n"); goto cleanup; } if (!dsa_print_key(dsaparamkey, 0, libctx, propq)) goto cleanup; ret = EXIT_SUCCESS; cleanup: EVP_PKEY_free(dsaparamkey); EVP_PKEY_CTX_free(ctx); return ret; }
./openssl/demos/pkey/EVP_PKEY_DSA_paramfromdata.c
/*- * Copyright 2022-2023 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ /* * Example showing how to load DSA params from raw data * using EVP_PKEY_fromdata() */ #include <openssl/param_build.h> #include <openssl/evp.h> #include <openssl/core_names.h> #include "dsa.inc" int main(int argc, char **argv) { int ret = EXIT_FAILURE; OSSL_LIB_CTX *libctx = NULL; const char *propq = NULL; EVP_PKEY_CTX *ctx = NULL; EVP_PKEY *dsaparamkey = NULL; OSSL_PARAM_BLD *bld = NULL; OSSL_PARAM *params = NULL; BIGNUM *p = NULL, *q = NULL, *g = NULL; p = BN_bin2bn(dsa_p, sizeof(dsa_p), NULL); q = BN_bin2bn(dsa_q, sizeof(dsa_q), NULL); g = BN_bin2bn(dsa_g, sizeof(dsa_g), NULL); if (p == NULL || q == NULL || g == NULL) goto cleanup; /* Use OSSL_PARAM_BLD if you need to handle BIGNUM Parameters */ bld = OSSL_PARAM_BLD_new(); if (bld == NULL) goto cleanup; if (!OSSL_PARAM_BLD_push_BN(bld, OSSL_PKEY_PARAM_FFC_P, p) || !OSSL_PARAM_BLD_push_BN(bld, OSSL_PKEY_PARAM_FFC_Q, q) || !OSSL_PARAM_BLD_push_BN(bld, OSSL_PKEY_PARAM_FFC_G, g)) goto cleanup; params = OSSL_PARAM_BLD_to_param(bld); if (params == NULL) goto cleanup; ctx = EVP_PKEY_CTX_new_from_name(libctx, "DSA", propq); if (ctx == NULL) { fprintf(stderr, "EVP_PKEY_CTX_new_from_name() failed\n"); goto cleanup; } if (EVP_PKEY_fromdata_init(ctx) <= 0 || EVP_PKEY_fromdata(ctx, &dsaparamkey, EVP_PKEY_KEY_PARAMETERS, params) <= 0) { fprintf(stderr, "EVP_PKEY_fromdata() failed\n"); goto cleanup; } if (!dsa_print_key(dsaparamkey, 0, libctx, propq)) goto cleanup; ret = EXIT_SUCCESS; cleanup: EVP_PKEY_free(dsaparamkey); EVP_PKEY_CTX_free(ctx); OSSL_PARAM_free(params); OSSL_PARAM_BLD_free(bld); BN_free(g); BN_free(q); BN_free(p); return ret; }
./openssl/demos/pkey/EVP_PKEY_DSA_keygen.c
/*- * Copyright 2022-2023 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ /* * Example showing how to generate an DSA key pair. */ #include <openssl/evp.h> #include "dsa.inc" /* * Generate dsa params using default values. * See the EVP_PKEY_DSA_param_fromdata demo if you need * to load DSA params from raw values. * See the EVP_PKEY_DSA_paramgen demo if you need to * use non default parameters. */ EVP_PKEY *dsa_genparams(OSSL_LIB_CTX *libctx, const char *propq) { EVP_PKEY *dsaparamkey = NULL; EVP_PKEY_CTX *ctx = NULL; /* Use the dsa params in a EVP_PKEY ctx */ ctx = EVP_PKEY_CTX_new_from_name(libctx, "DSA", propq); if (ctx == NULL) { fprintf(stderr, "EVP_PKEY_CTX_new_from_name() failed\n"); return NULL; } if (EVP_PKEY_paramgen_init(ctx) <= 0 || EVP_PKEY_paramgen(ctx, &dsaparamkey) <= 0) { fprintf(stderr, "DSA paramgen failed\n"); goto cleanup; } cleanup: EVP_PKEY_CTX_free(ctx); return dsaparamkey; } int main(int argc, char **argv) { int ret = EXIT_FAILURE; OSSL_LIB_CTX *libctx = NULL; const char *propq = NULL; EVP_PKEY *dsaparamskey = NULL; EVP_PKEY *dsakey = NULL; EVP_PKEY_CTX *ctx = NULL; /* Generate random dsa params */ dsaparamskey = dsa_genparams(libctx, propq); if (dsaparamskey == NULL) goto cleanup; /* Use the dsa params in a EVP_PKEY ctx */ ctx = EVP_PKEY_CTX_new_from_pkey(libctx, dsaparamskey, propq); if (ctx == NULL) { fprintf(stderr, "EVP_PKEY_CTX_new_from_pkey() failed\n"); goto cleanup; } /* Generate a key using the dsa params */ if (EVP_PKEY_keygen_init(ctx) <= 0 || EVP_PKEY_keygen(ctx, &dsakey) <= 0) { fprintf(stderr, "DSA keygen failed\n"); goto cleanup; } if (!dsa_print_key(dsakey, 1, libctx, propq)) goto cleanup; ret = EXIT_SUCCESS; cleanup: EVP_PKEY_free(dsakey); EVP_PKEY_free(dsaparamskey); EVP_PKEY_CTX_free(ctx); return ret; }
./openssl/demos/pkey/EVP_PKEY_EC_keygen.c
/*- * Copyright 2021-2023 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ /* * Example showing how to generate an EC key and extract values from the * generated key. */ #include <string.h> #include <stdio.h> #include <openssl/err.h> #include <openssl/evp.h> #include <openssl/core_names.h> static int get_key_values(EVP_PKEY *pkey); /* * The following code shows how to generate an EC key from a curve name * with additional parameters. If only the curve name is required then the * simple helper can be used instead i.e. Either * pkey = EVP_EC_gen(curvename); OR * pkey = EVP_PKEY_Q_keygen(libctx, propq, "EC", curvename); */ static EVP_PKEY *do_ec_keygen(void) { /* * The libctx and propq can be set if required, they are included here * to show how they are passed to EVP_PKEY_CTX_new_from_name(). */ OSSL_LIB_CTX *libctx = NULL; const char *propq = NULL; EVP_PKEY *key = NULL; OSSL_PARAM params[3]; EVP_PKEY_CTX *genctx = NULL; const char *curvename = "P-256"; int use_cofactordh = 1; genctx = EVP_PKEY_CTX_new_from_name(libctx, "EC", propq); if (genctx == NULL) { fprintf(stderr, "EVP_PKEY_CTX_new_from_name() failed\n"); goto cleanup; } if (EVP_PKEY_keygen_init(genctx) <= 0) { fprintf(stderr, "EVP_PKEY_keygen_init() failed\n"); goto cleanup; } params[0] = OSSL_PARAM_construct_utf8_string(OSSL_PKEY_PARAM_GROUP_NAME, (char *)curvename, 0); /* * This is an optional parameter. * For many curves where the cofactor is 1, setting this has no effect. */ params[1] = OSSL_PARAM_construct_int(OSSL_PKEY_PARAM_USE_COFACTOR_ECDH, &use_cofactordh); params[2] = OSSL_PARAM_construct_end(); if (!EVP_PKEY_CTX_set_params(genctx, params)) { fprintf(stderr, "EVP_PKEY_CTX_set_params() failed\n"); goto cleanup; } fprintf(stdout, "Generating EC key\n\n"); if (EVP_PKEY_generate(genctx, &key) <= 0) { fprintf(stderr, "EVP_PKEY_generate() failed\n"); goto cleanup; } cleanup: EVP_PKEY_CTX_free(genctx); return key; } /* * The following code shows how retrieve key data from the generated * EC key. See doc/man7/EVP_PKEY-EC.pod for more information. * * EVP_PKEY_print_private() could also be used to display the values. */ static int get_key_values(EVP_PKEY *pkey) { int ret = 0; char out_curvename[80]; unsigned char out_pubkey[80]; unsigned char out_privkey[80]; BIGNUM *out_priv = NULL; size_t out_pubkey_len, out_privkey_len = 0; if (!EVP_PKEY_get_utf8_string_param(pkey, OSSL_PKEY_PARAM_GROUP_NAME, out_curvename, sizeof(out_curvename), NULL)) { fprintf(stderr, "Failed to get curve name\n"); goto cleanup; } if (!EVP_PKEY_get_octet_string_param(pkey, OSSL_PKEY_PARAM_PUB_KEY, out_pubkey, sizeof(out_pubkey), &out_pubkey_len)) { fprintf(stderr, "Failed to get public key\n"); goto cleanup; } if (!EVP_PKEY_get_bn_param(pkey, OSSL_PKEY_PARAM_PRIV_KEY, &out_priv)) { fprintf(stderr, "Failed to get private key\n"); goto cleanup; } out_privkey_len = BN_bn2bin(out_priv, out_privkey); if (out_privkey_len <= 0 || out_privkey_len > sizeof(out_privkey)) { fprintf(stderr, "BN_bn2bin failed\n"); goto cleanup; } fprintf(stdout, "Curve name: %s\n", out_curvename); fprintf(stdout, "Public key:\n"); BIO_dump_indent_fp(stdout, out_pubkey, out_pubkey_len, 2); fprintf(stdout, "Private Key:\n"); BIO_dump_indent_fp(stdout, out_privkey, out_privkey_len, 2); ret = 1; cleanup: /* Zeroize the private key data when we free it */ BN_clear_free(out_priv); return ret; } int main(void) { int ret = EXIT_FAILURE; EVP_PKEY *pkey; pkey = do_ec_keygen(); if (pkey == NULL) goto cleanup; if (!get_key_values(pkey)) goto cleanup; /* * At this point we can write out the generated key using * i2d_PrivateKey() and i2d_PublicKey() if required. */ ret = EXIT_SUCCESS; cleanup: if (ret != EXIT_SUCCESS) ERR_print_errors_fp(stderr); EVP_PKEY_free(pkey); return ret; }
./openssl/demos/pkey/EVP_PKEY_RSA_keygen.c
/*- * Copyright 2022-2023 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ /* * Example showing how to generate an RSA key pair. * * When generating an RSA key, you must specify the number of bits in the key. A * reasonable value would be 4096. Avoid using values below 2048. These values * are reasonable as of 2022. */ #include <string.h> #include <stdio.h> #include <openssl/err.h> #include <openssl/evp.h> #include <openssl/rsa.h> #include <openssl/core_names.h> #include <openssl/pem.h> /* A property query used for selecting algorithm implementations. */ static const char *propq = NULL; /* * Generates an RSA public-private key pair and returns it. * The number of bits is specified by the bits argument. * * This uses the long way of generating an RSA key. */ static EVP_PKEY *generate_rsa_key_long(OSSL_LIB_CTX *libctx, unsigned int bits) { EVP_PKEY_CTX *genctx = NULL; EVP_PKEY *pkey = NULL; unsigned int primes = 2; /* Create context using RSA algorithm. "RSA-PSS" could also be used here. */ genctx = EVP_PKEY_CTX_new_from_name(libctx, "RSA", propq); if (genctx == NULL) { fprintf(stderr, "EVP_PKEY_CTX_new_from_name() failed\n"); goto cleanup; } /* Initialize context for key generation purposes. */ if (EVP_PKEY_keygen_init(genctx) <= 0) { fprintf(stderr, "EVP_PKEY_keygen_init() failed\n"); goto cleanup; } /* * Here we set the number of bits to use in the RSA key. * See comment at top of file for information on appropriate values. */ if (EVP_PKEY_CTX_set_rsa_keygen_bits(genctx, bits) <= 0) { fprintf(stderr, "EVP_PKEY_CTX_set_rsa_keygen_bits() failed\n"); goto cleanup; } /* * It is possible to create an RSA key using more than two primes. * Do not do this unless you know why you need this. * You ordinarily do not need to specify this, as the default is two. * * Both of these parameters can also be set via EVP_PKEY_CTX_set_params, but * these functions provide a more concise way to do so. */ if (EVP_PKEY_CTX_set_rsa_keygen_primes(genctx, primes) <= 0) { fprintf(stderr, "EVP_PKEY_CTX_set_rsa_keygen_primes() failed\n"); goto cleanup; } /* * Generating an RSA key with a number of bits large enough to be secure for * modern applications can take a fairly substantial amount of time (e.g. * one second). If you require fast key generation, consider using an EC key * instead. * * If you require progress information during the key generation process, * you can set a progress callback using EVP_PKEY_set_cb; see the example in * EVP_PKEY_generate(3). */ fprintf(stdout, "Generating RSA key, this may take some time...\n"); if (EVP_PKEY_generate(genctx, &pkey) <= 0) { fprintf(stderr, "EVP_PKEY_generate() failed\n"); goto cleanup; } /* pkey is now set to an object representing the generated key pair. */ cleanup: EVP_PKEY_CTX_free(genctx); return pkey; } /* * Generates an RSA public-private key pair and returns it. * The number of bits is specified by the bits argument. * * This uses a more concise way of generating an RSA key, which is suitable for * simple cases. It is used if -s is passed on the command line, otherwise the * long method above is used. The ability to choose between these two methods is * shown here only for demonstration; the results are equivalent. */ static EVP_PKEY *generate_rsa_key_short(OSSL_LIB_CTX *libctx, unsigned int bits) { EVP_PKEY *pkey = NULL; fprintf(stdout, "Generating RSA key, this may take some time...\n"); pkey = EVP_PKEY_Q_keygen(libctx, propq, "RSA", (size_t)bits); if (pkey == NULL) fprintf(stderr, "EVP_PKEY_Q_keygen() failed\n"); return pkey; } /* * Prints information on an EVP_PKEY object representing an RSA key pair. */ static int dump_key(const EVP_PKEY *pkey) { int ret = 0; int bits = 0; BIGNUM *n = NULL, *e = NULL, *d = NULL, *p = NULL, *q = NULL; /* * Retrieve value of n. This value is not secret and forms part of the * public key. * * Calling EVP_PKEY_get_bn_param with a NULL BIGNUM pointer causes * a new BIGNUM to be allocated, so these must be freed subsequently. */ if (EVP_PKEY_get_bn_param(pkey, OSSL_PKEY_PARAM_RSA_N, &n) == 0) { fprintf(stderr, "Failed to retrieve n\n"); goto cleanup; } /* * Retrieve value of e. This value is not secret and forms part of the * public key. It is typically 65537 and need not be changed. */ if (EVP_PKEY_get_bn_param(pkey, OSSL_PKEY_PARAM_RSA_E, &e) == 0) { fprintf(stderr, "Failed to retrieve e\n"); goto cleanup; } /* * Retrieve value of d. This value is secret and forms part of the private * key. It must not be published. */ if (EVP_PKEY_get_bn_param(pkey, OSSL_PKEY_PARAM_RSA_D, &d) == 0) { fprintf(stderr, "Failed to retrieve d\n"); goto cleanup; } /* * Retrieve value of the first prime factor, commonly known as p. This value * is secret and forms part of the private key. It must not be published. */ if (EVP_PKEY_get_bn_param(pkey, OSSL_PKEY_PARAM_RSA_FACTOR1, &p) == 0) { fprintf(stderr, "Failed to retrieve p\n"); goto cleanup; } /* * Retrieve value of the second prime factor, commonly known as q. This value * is secret and forms part of the private key. It must not be published. * * If you are creating an RSA key with more than two primes for special * applications, you can retrieve these primes with * OSSL_PKEY_PARAM_RSA_FACTOR3, etc. */ if (EVP_PKEY_get_bn_param(pkey, OSSL_PKEY_PARAM_RSA_FACTOR2, &q) == 0) { fprintf(stderr, "Failed to retrieve q\n"); goto cleanup; } /* * We can also retrieve the key size in bits for informational purposes. */ if (EVP_PKEY_get_int_param(pkey, OSSL_PKEY_PARAM_BITS, &bits) == 0) { fprintf(stderr, "Failed to retrieve bits\n"); goto cleanup; } /* Output hexadecimal representations of the BIGNUM objects. */ fprintf(stdout, "\nNumber of bits: %d\n\n", bits); fprintf(stdout, "Public values:\n"); fprintf(stdout, " n = 0x"); BN_print_fp(stdout, n); fprintf(stdout, "\n"); fprintf(stdout, " e = 0x"); BN_print_fp(stdout, e); fprintf(stdout, "\n\n"); fprintf(stdout, "Private values:\n"); fprintf(stdout, " d = 0x"); BN_print_fp(stdout, d); fprintf(stdout, "\n"); fprintf(stdout, " p = 0x"); BN_print_fp(stdout, p); fprintf(stdout, "\n"); fprintf(stdout, " q = 0x"); BN_print_fp(stdout, q); fprintf(stdout, "\n\n"); /* Output a PEM encoding of the public key. */ if (PEM_write_PUBKEY(stdout, pkey) == 0) { fprintf(stderr, "Failed to output PEM-encoded public key\n"); goto cleanup; } /* * Output a PEM encoding of the private key. Please note that this output is * not encrypted. You may wish to use the arguments to specify encryption of * the key if you are storing it on disk. See PEM_write_PrivateKey(3). */ if (PEM_write_PrivateKey(stdout, pkey, NULL, NULL, 0, NULL, NULL) == 0) { fprintf(stderr, "Failed to output PEM-encoded private key\n"); goto cleanup; } ret = 1; cleanup: BN_free(n); /* not secret */ BN_free(e); /* not secret */ BN_clear_free(d); /* secret - scrub before freeing */ BN_clear_free(p); /* secret - scrub before freeing */ BN_clear_free(q); /* secret - scrub before freeing */ return ret; } int main(int argc, char **argv) { int ret = EXIT_FAILURE; OSSL_LIB_CTX *libctx = NULL; EVP_PKEY *pkey = NULL; unsigned int bits = 4096; int bits_i, use_short = 0; /* usage: [-s] [<bits>] */ if (argc > 1 && strcmp(argv[1], "-s") == 0) { --argc; ++argv; use_short = 1; } if (argc > 1) { bits_i = atoi(argv[1]); if (bits < 512) { fprintf(stderr, "Invalid RSA key size\n"); return EXIT_FAILURE; } bits = (unsigned int)bits_i; } /* Avoid using key sizes less than 2048 bits; see comment at top of file. */ if (bits < 2048) fprintf(stderr, "Warning: very weak key size\n\n"); /* Generate RSA key. */ if (use_short) pkey = generate_rsa_key_short(libctx, bits); else pkey = generate_rsa_key_long(libctx, bits); if (pkey == NULL) goto cleanup; /* Dump the integers comprising the key. */ if (dump_key(pkey) == 0) { fprintf(stderr, "Failed to dump key\n"); goto cleanup; } ret = EXIT_SUCCESS; cleanup: EVP_PKEY_free(pkey); OSSL_LIB_CTX_free(libctx); return ret; }
./openssl/demos/pkey/EVP_PKEY_DSA_paramvalidate.c
/*- * Copyright 2022-2023 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ /* * Example showing how to validate DSA parameters. * * Proper FIPS 186-4 DSA (FFC) parameter validation requires that all * the parameters used during parameter generation are supplied * when doing the validation. Unfortunately saving DSA parameters as * a PEM or DER file does not write out all required fields. Because * of this the default provider normally only does a partial * validation. The FIPS provider will however try to do a full * validation. To force the default provider to use full * validation the 'seed' that is output during generation must be * added to the key. See doc/man7/EVP_PKEY-FFC for more information. */ #include <openssl/evp.h> #include <openssl/core_names.h> #include <openssl/pem.h> #include "dsa.inc" /* The following values were output from the EVP_PKEY_DSA_paramgen demo */ static const char dsapem[] = "-----BEGIN DSA PARAMETERS-----\n" "MIICLAKCAQEA1pobSR1FJ3+Tvi0J6Tk1PSV2owZey1Nuo847hGw/59VCS6RPQEqr\n" "vp5fhbvBjupBeVGA/AMH6rI4i4h6jlhurrqH1CqUHVcDhJzxV668bMLiP3mIxg5o\n" "9Yq8x6BnSOtH5Je0tpeE0/fEvvLjCwBUbwnwWxzjANcvDUEt9XYeRrtB2v52fr56\n" "hVYz3wMMNog4CEDOLTvx7/84eVPuUeWDRQFH1EaHMdulP34KBcatEEpEZapkepng\n" "nohm9sFSPQhq2utpkH7pNXdG0EILBtRDCvUpF5720a48LYofdggh2VEZfgElAGFk\n" "dW/CkvyBDmGIzil5aTz4MMsdudaVYgzt6wIhAPsSGC42Qa+X0AFGvonb5nmfUVm/\n" "8aC+tHk7Nb2AYLHXAoIBADx5C0H1+QHsmGKvuOaY+WKUt7aWUrEivD1zBMJAQ6bL\n" "Wv9lbCq1CFHvVzojeOVpn872NqDEpkx4HTpvqhxWL5CkbN/HaGItsQzkD59AQg3v\n" "4YsLlkesq9Jq6x/aWetJXWO36fszFv1gpD3NY3wliBvMYHx62jfc5suh9D3ZZvu7\n" "PLGH4X4kcfzK/R2b0oVbEBjVTe5GMRYZRqnvfSW2f2fA7BzI1OL83UxDDe58cL2M\n" "GcAoUYXOBAfZ37qLMm2juf+o5gCrT4CXfRPu6kbapt7V/YIc1nsNgeAOKKoFBHBQ\n" "gc5u5G6G/j79FVoSDq9DYwTJcHPsU+eHj1uWHso1AjQ=\n" "-----END DSA PARAMETERS-----\n"; static const char hexseed[] = "cba30ccd905aa7675a0b81769704bf3c" "ccf2ca1892b2eaf6b9e2b38d9bf6affc" "42ada55986d8a1772b442770954d0b65"; const int gindex = 42; const int pcounter = 363; static const char digest[] = "SHA384"; /* * Create a new dsa param key that is the combination of an existing param key * plus extra parameters. */ EVP_PKEY_CTX *create_merged_key(EVP_PKEY *dsaparams, const OSSL_PARAM *newparams, OSSL_LIB_CTX *libctx, const char *propq) { EVP_PKEY_CTX *out = NULL; EVP_PKEY_CTX *ctx = NULL; EVP_PKEY *pkey = NULL; OSSL_PARAM *mergedparams = NULL; OSSL_PARAM *loadedparams = NULL; /* Specify EVP_PKEY_KEY_PUBLIC here if you have a public key */ if (EVP_PKEY_todata(dsaparams, EVP_PKEY_KEY_PARAMETERS, &loadedparams) <= 0) { fprintf(stderr, "EVP_PKEY_todata() failed\n"); goto cleanup; } mergedparams = OSSL_PARAM_merge(loadedparams, newparams); if (mergedparams == NULL) { fprintf(stderr, "OSSL_PARAM_merge() failed\n"); goto cleanup; } ctx = EVP_PKEY_CTX_new_from_name(libctx, "DSA", propq); if (ctx == NULL) { fprintf(stderr, "EVP_PKEY_CTX_new_from_name() failed\n"); goto cleanup; } if (EVP_PKEY_fromdata_init(ctx) <= 0 || EVP_PKEY_fromdata(ctx, &pkey, EVP_PKEY_KEY_PARAMETERS, mergedparams) <= 0) { fprintf(stderr, "EVP_PKEY_fromdata() failed\n"); goto cleanup; } out = EVP_PKEY_CTX_new_from_pkey(libctx, pkey, propq); if (out == NULL) { fprintf(stderr, "EVP_PKEY_CTX_new_from_pkey() failed\n"); goto cleanup; } cleanup: EVP_PKEY_free(pkey); OSSL_PARAM_free(loadedparams); OSSL_PARAM_free(mergedparams); EVP_PKEY_CTX_free(ctx); return out; } int main(int argc, char **argv) { int ret = EXIT_FAILURE; OSSL_LIB_CTX *libctx = NULL; const char *propq = NULL; EVP_PKEY *dsaparamskey = NULL; EVP_PKEY_CTX *ctx = NULL; EVP_PKEY_CTX *ctx1 = NULL; EVP_PKEY_CTX *ctx2 = NULL; BIO *in = NULL; OSSL_PARAM params[6]; unsigned char seed[64]; size_t seedlen; if (!OPENSSL_hexstr2buf_ex(seed, sizeof(seed), &seedlen, hexseed, '\0')) goto cleanup; /* * This example loads the PEM data from a memory buffer * Use BIO_new_fp() to load a PEM file instead */ in = BIO_new_mem_buf(dsapem, strlen(dsapem)); if (in == NULL) { fprintf(stderr, "BIO_new_mem_buf() failed\n"); goto cleanup; } /* Load DSA params from pem data */ dsaparamskey = PEM_read_bio_Parameters_ex(in, NULL, libctx, propq); if (dsaparamskey == NULL) { fprintf(stderr, "Failed to load dsa params\n"); goto cleanup; } ctx = EVP_PKEY_CTX_new_from_pkey(libctx, dsaparamskey, propq); if (ctx == NULL) { fprintf(stderr, "EVP_PKEY_CTX_new_from_pkey() failed\n"); goto cleanup; } /* * When using the default provider this only does a partial check to * make sure that the values of p, q and g are ok. * This will fail however if the FIPS provider is used since it does * a proper FIPS 186-4 key validation which requires extra parameters */ if (EVP_PKEY_param_check(ctx) <= 0) { fprintf(stderr, "Simple EVP_PKEY_param_check() failed \n"); goto cleanup; } /* * Setup parameters that we want to add. * For illustration purposes it deliberately omits a required parameter. */ params[0] = OSSL_PARAM_construct_utf8_string(OSSL_PKEY_PARAM_FFC_TYPE, "fips186_4", 0); /* Force it to do a proper validation by setting the seed */ params[1] = OSSL_PARAM_construct_octet_string(OSSL_PKEY_PARAM_FFC_SEED, (void *)seed, seedlen); params[2] = OSSL_PARAM_construct_int(OSSL_PKEY_PARAM_FFC_GINDEX, (int *)&gindex); params[3] = OSSL_PARAM_construct_int(OSSL_PKEY_PARAM_FFC_PCOUNTER, (int *)&pcounter); params[4] = OSSL_PARAM_construct_end(); /* generate a new key that is the combination of the existing key and the new params */ ctx1 = create_merged_key(dsaparamskey, params, libctx, propq); if (ctx1 == NULL) goto cleanup; /* This will fail since not all the parameters used for key generation are added */ if (EVP_PKEY_param_check(ctx1) > 0) { fprintf(stderr, "EVP_PKEY_param_check() should fail\n"); goto cleanup; } /* * Add the missing parameters onto the end of the existing list of params * If the default was used for the generation then this parameter is not * needed */ params[4] = OSSL_PARAM_construct_utf8_string(OSSL_PKEY_PARAM_FFC_DIGEST, (char *)digest, 0); params[5] = OSSL_PARAM_construct_end(); ctx2 = create_merged_key(dsaparamskey, params, libctx, propq); if (ctx2 == NULL) goto cleanup; if (EVP_PKEY_param_check(ctx2) <= 0) { fprintf(stderr, "EVP_PKEY_param_check() failed\n"); goto cleanup; } if (!dsa_print_key(EVP_PKEY_CTX_get0_pkey(ctx2), 0, libctx, propq)) goto cleanup; ret = EXIT_SUCCESS; cleanup: EVP_PKEY_free(dsaparamskey); EVP_PKEY_CTX_free(ctx2); EVP_PKEY_CTX_free(ctx1); EVP_PKEY_CTX_free(ctx); BIO_free(in); return ret; }
./openssl/demos/encode/ec_encode.c
/*- * Copyright 2022-2023 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <string.h> #include <openssl/decoder.h> #include <openssl/encoder.h> #include <openssl/evp.h> /* * Example showing the encoding and decoding of EC public and private keys. A * PEM-encoded EC key is read in from stdin, decoded, and then re-encoded and * output for demonstration purposes. Both public and private keys are accepted. * * This can be used to load EC keys from a file or save EC keys to a file. */ /* A property query used for selecting algorithm implementations. */ static const char *propq = NULL; /* * Load a PEM-encoded EC key from a file, optionally decrypting it with a * supplied passphrase. */ static EVP_PKEY *load_key(OSSL_LIB_CTX *libctx, FILE *f, const char *passphrase) { int ret = 0; EVP_PKEY *pkey = NULL; OSSL_DECODER_CTX *dctx = NULL; int selection = 0; /* * Create PEM decoder context expecting an EC key. * * For raw (non-PEM-encoded) keys, change "PEM" to "DER". * * The selection argument here specifies whether we are willing to accept a * public key, private key, or either. If it is set to zero, either will be * accepted. If set to EVP_PKEY_KEYPAIR, a private key will be required, and * if set to EVP_PKEY_PUBLIC_KEY, a public key will be required. */ dctx = OSSL_DECODER_CTX_new_for_pkey(&pkey, "PEM", NULL, "EC", selection, libctx, propq); if (dctx == NULL) { fprintf(stderr, "OSSL_DECODER_CTX_new_for_pkey() failed\n"); goto cleanup; } /* * Set passphrase if provided; needed to decrypt encrypted PEM files. * If the input is not encrypted, any passphrase provided is ignored. * * Alternative methods for specifying passphrases exist, such as a callback * (see OSSL_DECODER_CTX_set_passphrase_cb(3)), which may be more useful for * interactive applications which do not know if a passphrase should be * prompted for in advance, or for GUI applications. */ if (passphrase != NULL) { if (OSSL_DECODER_CTX_set_passphrase(dctx, (const unsigned char *)passphrase, strlen(passphrase)) == 0) { fprintf(stderr, "OSSL_DECODER_CTX_set_passphrase() failed\n"); goto cleanup; } } /* Do the decode, reading from file. */ if (OSSL_DECODER_from_fp(dctx, f) == 0) { fprintf(stderr, "OSSL_DECODER_from_fp() failed\n"); goto cleanup; } ret = 1; cleanup: OSSL_DECODER_CTX_free(dctx); /* * pkey is created by OSSL_DECODER_CTX_new_for_pkey, but we * might fail subsequently, so ensure it's properly freed * in this case. */ if (ret == 0) { EVP_PKEY_free(pkey); pkey = NULL; } return pkey; } /* * Store a EC public or private key to a file using PEM encoding. * * If a passphrase is supplied, the file is encrypted, otherwise * it is unencrypted. */ static int store_key(EVP_PKEY *pkey, FILE *f, const char *passphrase) { int ret = 0; int selection; OSSL_ENCODER_CTX *ectx = NULL; /* * Create a PEM encoder context. * * For raw (non-PEM-encoded) output, change "PEM" to "DER". * * The selection argument controls whether the private key is exported * (EVP_PKEY_KEYPAIR), or only the public key (EVP_PKEY_PUBLIC_KEY). The * former will fail if we only have a public key. * * Note that unlike the decode API, you cannot specify zero here. * * Purely for the sake of demonstration, here we choose to export the whole * key if a passphrase is provided and the public key otherwise. */ selection = (passphrase != NULL) ? EVP_PKEY_KEYPAIR : EVP_PKEY_PUBLIC_KEY; ectx = OSSL_ENCODER_CTX_new_for_pkey(pkey, selection, "PEM", NULL, propq); if (ectx == NULL) { fprintf(stderr, "OSSL_ENCODER_CTX_new_for_pkey() failed\n"); goto cleanup; } /* * Set passphrase if provided; the encoded output will then be encrypted * using the passphrase. * * Alternative methods for specifying passphrases exist, such as a callback * (see OSSL_ENCODER_CTX_set_passphrase_cb(3), just as for OSSL_DECODER_CTX; * however you are less likely to need them as you presumably know whether * encryption is desired in advance. * * Note that specifying a passphrase alone is not enough to cause the * key to be encrypted. You must set both a cipher and a passphrase. */ if (passphrase != NULL) { /* * Set cipher. Let's use AES-256-CBC, because it is * more quantum resistant. */ if (OSSL_ENCODER_CTX_set_cipher(ectx, "AES-256-CBC", propq) == 0) { fprintf(stderr, "OSSL_ENCODER_CTX_set_cipher() failed\n"); goto cleanup; } /* Set passphrase. */ if (OSSL_ENCODER_CTX_set_passphrase(ectx, (const unsigned char *)passphrase, strlen(passphrase)) == 0) { fprintf(stderr, "OSSL_ENCODER_CTX_set_passphrase() failed\n"); goto cleanup; } } /* Do the encode, writing to the given file. */ if (OSSL_ENCODER_to_fp(ectx, f) == 0) { fprintf(stderr, "OSSL_ENCODER_to_fp() failed\n"); goto cleanup; } ret = 1; cleanup: OSSL_ENCODER_CTX_free(ectx); return ret; } int main(int argc, char **argv) { int ret = EXIT_FAILURE; OSSL_LIB_CTX *libctx = NULL; EVP_PKEY *pkey = NULL; const char *passphrase_in = NULL, *passphrase_out = NULL; /* usage: ec_encode <passphrase-in> <passphrase-out> */ if (argc > 1 && argv[1][0]) passphrase_in = argv[1]; if (argc > 2 && argv[2][0]) passphrase_out = argv[2]; /* Decode PEM key from stdin and then PEM encode it to stdout. */ pkey = load_key(libctx, stdin, passphrase_in); if (pkey == NULL) { fprintf(stderr, "Failed to decode key\n"); goto cleanup; } if (store_key(pkey, stdout, passphrase_out) == 0) { fprintf(stderr, "Failed to encode key\n"); goto cleanup; } ret = EXIT_SUCCESS; cleanup: EVP_PKEY_free(pkey); OSSL_LIB_CTX_free(libctx); return ret; }
./openssl/demos/encode/rsa_encode.c
/*- * Copyright 2022-2023 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <string.h> #include <openssl/decoder.h> #include <openssl/encoder.h> #include <openssl/evp.h> /* * Example showing the encoding and decoding of RSA public and private keys. A * PEM-encoded RSA key is read in from stdin, decoded, and then re-encoded and * output for demonstration purposes. Both public and private keys are accepted. * * This can be used to load RSA keys from a file or save RSA keys to a file. */ /* A property query used for selecting algorithm implementations. */ static const char *propq = NULL; /* * Load a PEM-encoded RSA key from a file, optionally decrypting it with a * supplied passphrase. */ static EVP_PKEY *load_key(OSSL_LIB_CTX *libctx, FILE *f, const char *passphrase) { int ret = 0; EVP_PKEY *pkey = NULL; OSSL_DECODER_CTX *dctx = NULL; int selection = 0; /* * Create PEM decoder context expecting an RSA key. * * For raw (non-PEM-encoded) keys, change "PEM" to "DER". * * The selection argument here specifies whether we are willing to accept a * public key, private key, or either. If it is set to zero, either will be * accepted. If set to EVP_PKEY_KEYPAIR, a private key will be required, and * if set to EVP_PKEY_PUBLIC_KEY, a public key will be required. */ dctx = OSSL_DECODER_CTX_new_for_pkey(&pkey, "PEM", NULL, "RSA", selection, libctx, propq); if (dctx == NULL) { fprintf(stderr, "OSSL_DECODER_CTX_new_for_pkey() failed\n"); goto cleanup; } /* * Set passphrase if provided; needed to decrypt encrypted PEM files. * If the input is not encrypted, any passphrase provided is ignored. * * Alternative methods for specifying passphrases exist, such as a callback * (see OSSL_DECODER_CTX_set_passphrase_cb(3)), which may be more useful for * interactive applications which do not know if a passphrase should be * prompted for in advance, or for GUI applications. */ if (passphrase != NULL) { if (OSSL_DECODER_CTX_set_passphrase(dctx, (const unsigned char *)passphrase, strlen(passphrase)) == 0) { fprintf(stderr, "OSSL_DECODER_CTX_set_passphrase() failed\n"); goto cleanup; } } /* Do the decode, reading from file. */ if (OSSL_DECODER_from_fp(dctx, f) == 0) { fprintf(stderr, "OSSL_DECODER_from_fp() failed\n"); goto cleanup; } ret = 1; cleanup: OSSL_DECODER_CTX_free(dctx); /* * pkey is created by OSSL_DECODER_CTX_new_for_pkey, but we * might fail subsequently, so ensure it's properly freed * in this case. */ if (ret == 0) { EVP_PKEY_free(pkey); pkey = NULL; } return pkey; } /* * Store an RSA public or private key to a file using PEM encoding. * * If a passphrase is supplied, the file is encrypted, otherwise * it is unencrypted. */ static int store_key(EVP_PKEY *pkey, FILE *f, const char *passphrase) { int ret = 0; int selection; OSSL_ENCODER_CTX *ectx = NULL; /* * Create a PEM encoder context. * * For raw (non-PEM-encoded) output, change "PEM" to "DER". * * The selection argument controls whether the private key is exported * (EVP_PKEY_KEYPAIR), or only the public key (EVP_PKEY_PUBLIC_KEY). The * former will fail if we only have a public key. * * Note that unlike the decode API, you cannot specify zero here. * * Purely for the sake of demonstration, here we choose to export the whole * key if a passphrase is provided and the public key otherwise. */ selection = (passphrase != NULL) ? EVP_PKEY_KEYPAIR : EVP_PKEY_PUBLIC_KEY; ectx = OSSL_ENCODER_CTX_new_for_pkey(pkey, selection, "PEM", NULL, propq); if (ectx == NULL) { fprintf(stderr, "OSSL_ENCODER_CTX_new_for_pkey() failed\n"); goto cleanup; } /* * Set passphrase if provided; the encoded output will then be encrypted * using the passphrase. * * Alternative methods for specifying passphrases exist, such as a callback * (see OSSL_ENCODER_CTX_set_passphrase_cb(3), just as for OSSL_DECODER_CTX; * however you are less likely to need them as you presumably know whether * encryption is desired in advance. * * Note that specifying a passphrase alone is not enough to cause the * key to be encrypted. You must set both a cipher and a passphrase. */ if (passphrase != NULL) { /* Set cipher. AES-128-CBC is a reasonable default. */ if (OSSL_ENCODER_CTX_set_cipher(ectx, "AES-128-CBC", propq) == 0) { fprintf(stderr, "OSSL_ENCODER_CTX_set_cipher() failed\n"); goto cleanup; } /* Set passphrase. */ if (OSSL_ENCODER_CTX_set_passphrase(ectx, (const unsigned char *)passphrase, strlen(passphrase)) == 0) { fprintf(stderr, "OSSL_ENCODER_CTX_set_passphrase() failed\n"); goto cleanup; } } /* Do the encode, writing to the given file. */ if (OSSL_ENCODER_to_fp(ectx, f) == 0) { fprintf(stderr, "OSSL_ENCODER_to_fp() failed\n"); goto cleanup; } ret = 1; cleanup: OSSL_ENCODER_CTX_free(ectx); return ret; } int main(int argc, char **argv) { int ret = EXIT_FAILURE; OSSL_LIB_CTX *libctx = NULL; EVP_PKEY *pkey = NULL; const char *passphrase_in = NULL, *passphrase_out = NULL; /* usage: rsa_encode <passphrase-in> <passphrase-out> */ if (argc > 1 && argv[1][0]) passphrase_in = argv[1]; if (argc > 2 && argv[2][0]) passphrase_out = argv[2]; /* Decode PEM key from stdin and then PEM encode it to stdout. */ pkey = load_key(libctx, stdin, passphrase_in); if (pkey == NULL) { fprintf(stderr, "Failed to decode key\n"); goto cleanup; } if (store_key(pkey, stdout, passphrase_out) == 0) { fprintf(stderr, "Failed to encode key\n"); goto cleanup; } ret = EXIT_SUCCESS; cleanup: EVP_PKEY_free(pkey); OSSL_LIB_CTX_free(libctx); return ret; }
./openssl/demos/signature/rsa_pss_hash.c
/* * Copyright 2022-2023 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <stdio.h> #include <stdlib.h> #include <openssl/core_names.h> #include <openssl/evp.h> #include <openssl/rsa.h> #include <openssl/params.h> #include <openssl/err.h> #include <openssl/bio.h> #include "rsa_pss.h" /* The data to be signed. This will be hashed. */ static const char test_message[] = "This is an example message to be signed."; /* A property query used for selecting algorithm implementations. */ static const char *propq = NULL; /* * This function demonstrates RSA signing of an arbitrary-length message. * Hashing is performed automatically. In this example, SHA-256 is used. If you * have already hashed your message and simply want to sign the hash directly, * see rsa_pss_direct.c. */ static int sign(OSSL_LIB_CTX *libctx, unsigned char **sig, size_t *sig_len) { int ret = 0; EVP_PKEY *pkey = NULL; EVP_MD_CTX *mctx = NULL; OSSL_PARAM params[2], *p = params; const unsigned char *ppriv_key = NULL; *sig = NULL; /* Load DER-encoded RSA private key. */ ppriv_key = rsa_priv_key; pkey = d2i_PrivateKey_ex(EVP_PKEY_RSA, NULL, &ppriv_key, sizeof(rsa_priv_key), libctx, propq); if (pkey == NULL) { fprintf(stderr, "Failed to load private key\n"); goto end; } /* Create MD context used for signing. */ mctx = EVP_MD_CTX_new(); if (mctx == NULL) { fprintf(stderr, "Failed to create MD context\n"); goto end; } /* Initialize MD context for signing. */ *p++ = OSSL_PARAM_construct_utf8_string(OSSL_SIGNATURE_PARAM_PAD_MODE, OSSL_PKEY_RSA_PAD_MODE_PSS, 0); *p = OSSL_PARAM_construct_end(); if (EVP_DigestSignInit_ex(mctx, NULL, "SHA256", libctx, propq, pkey, params) == 0) { fprintf(stderr, "Failed to initialize signing context\n"); goto end; } /* * Feed data to be signed into the algorithm. This may * be called multiple times. */ if (EVP_DigestSignUpdate(mctx, test_message, sizeof(test_message)) == 0) { fprintf(stderr, "Failed to hash message into signing context\n"); goto end; } /* Determine signature length. */ if (EVP_DigestSignFinal(mctx, NULL, sig_len) == 0) { fprintf(stderr, "Failed to get signature length\n"); goto end; } /* Allocate memory for signature. */ *sig = OPENSSL_malloc(*sig_len); if (*sig == NULL) { fprintf(stderr, "Failed to allocate memory for signature\n"); goto end; } /* Generate signature. */ if (EVP_DigestSignFinal(mctx, *sig, sig_len) == 0) { fprintf(stderr, "Failed to sign\n"); goto end; } ret = 1; end: EVP_MD_CTX_free(mctx); EVP_PKEY_free(pkey); if (ret == 0) OPENSSL_free(*sig); return ret; } /* * This function demonstrates verification of an RSA signature over an * arbitrary-length message using the PSS signature scheme. Hashing is performed * automatically. */ static int verify(OSSL_LIB_CTX *libctx, const unsigned char *sig, size_t sig_len) { int ret = 0; EVP_PKEY *pkey = NULL; EVP_MD_CTX *mctx = NULL; OSSL_PARAM params[2], *p = params; const unsigned char *ppub_key = NULL; /* Load DER-encoded RSA public key. */ ppub_key = rsa_pub_key; pkey = d2i_PublicKey(EVP_PKEY_RSA, NULL, &ppub_key, sizeof(rsa_pub_key)); if (pkey == NULL) { fprintf(stderr, "Failed to load public key\n"); goto end; } /* Create MD context used for verification. */ mctx = EVP_MD_CTX_new(); if (mctx == NULL) { fprintf(stderr, "Failed to create MD context\n"); goto end; } /* Initialize MD context for verification. */ *p++ = OSSL_PARAM_construct_utf8_string(OSSL_SIGNATURE_PARAM_PAD_MODE, OSSL_PKEY_RSA_PAD_MODE_PSS, 0); *p = OSSL_PARAM_construct_end(); if (EVP_DigestVerifyInit_ex(mctx, NULL, "SHA256", libctx, propq, pkey, params) == 0) { fprintf(stderr, "Failed to initialize signing context\n"); goto end; } /* * Feed data to be signed into the algorithm. This may * be called multiple times. */ if (EVP_DigestVerifyUpdate(mctx, test_message, sizeof(test_message)) == 0) { fprintf(stderr, "Failed to hash message into signing context\n"); goto end; } /* Verify signature. */ if (EVP_DigestVerifyFinal(mctx, sig, sig_len) == 0) { fprintf(stderr, "Failed to verify signature; " "signature may be invalid\n"); goto end; } ret = 1; end: EVP_MD_CTX_free(mctx); EVP_PKEY_free(pkey); return ret; } int main(int argc, char **argv) { int ret = EXIT_FAILURE; OSSL_LIB_CTX *libctx = NULL; unsigned char *sig = NULL; size_t sig_len = 0; if (sign(libctx, &sig, &sig_len) == 0) goto end; if (verify(libctx, sig, sig_len) == 0) goto end; printf("Success\n"); ret = EXIT_SUCCESS; end: OPENSSL_free(sig); OSSL_LIB_CTX_free(libctx); return ret; }
./openssl/demos/signature/rsa_pss_direct.c
/* * Copyright 2022-2023 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <stdio.h> #include <stdlib.h> #include <openssl/core_names.h> #include <openssl/evp.h> #include <openssl/rsa.h> #include <openssl/params.h> #include <openssl/err.h> #include <openssl/bio.h> #include "rsa_pss.h" /* * The digest to be signed. This should be the output of a hash function. * Here we sign an all-zeroes digest for demonstration purposes. */ static const unsigned char test_digest[32] = {0}; /* A property query used for selecting algorithm implementations. */ static const char *propq = NULL; /* * This function demonstrates RSA signing of a SHA-256 digest using the PSS * padding scheme. You must already have hashed the data you want to sign. * For a higher-level demonstration which does the hashing for you, see * rsa_pss_hash.c. * * For more information, see RFC 8017 section 9.1. The digest passed in * (test_digest above) corresponds to the 'mHash' value. */ static int sign(OSSL_LIB_CTX *libctx, unsigned char **sig, size_t *sig_len) { int ret = 0; EVP_PKEY *pkey = NULL; EVP_PKEY_CTX *ctx = NULL; EVP_MD *md = NULL; const unsigned char *ppriv_key = NULL; *sig = NULL; /* Load DER-encoded RSA private key. */ ppriv_key = rsa_priv_key; pkey = d2i_PrivateKey_ex(EVP_PKEY_RSA, NULL, &ppriv_key, sizeof(rsa_priv_key), libctx, propq); if (pkey == NULL) { fprintf(stderr, "Failed to load private key\n"); goto end; } /* Fetch hash algorithm we want to use. */ md = EVP_MD_fetch(libctx, "SHA256", propq); if (md == NULL) { fprintf(stderr, "Failed to fetch hash algorithm\n"); goto end; } /* Create signing context. */ ctx = EVP_PKEY_CTX_new_from_pkey(libctx, pkey, propq); if (ctx == NULL) { fprintf(stderr, "Failed to create signing context\n"); goto end; } /* Initialize context for signing and set options. */ if (EVP_PKEY_sign_init(ctx) == 0) { fprintf(stderr, "Failed to initialize signing context\n"); goto end; } if (EVP_PKEY_CTX_set_rsa_padding(ctx, RSA_PKCS1_PSS_PADDING) == 0) { fprintf(stderr, "Failed to configure padding\n"); goto end; } if (EVP_PKEY_CTX_set_signature_md(ctx, md) == 0) { fprintf(stderr, "Failed to configure digest type\n"); goto end; } /* Determine length of signature. */ if (EVP_PKEY_sign(ctx, NULL, sig_len, test_digest, sizeof(test_digest)) == 0) { fprintf(stderr, "Failed to get signature length\n"); goto end; } /* Allocate memory for signature. */ *sig = OPENSSL_malloc(*sig_len); if (*sig == NULL) { fprintf(stderr, "Failed to allocate memory for signature\n"); goto end; } /* Generate signature. */ if (EVP_PKEY_sign(ctx, *sig, sig_len, test_digest, sizeof(test_digest)) != 1) { fprintf(stderr, "Failed to sign\n"); goto end; } ret = 1; end: EVP_PKEY_CTX_free(ctx); EVP_PKEY_free(pkey); EVP_MD_free(md); if (ret == 0) OPENSSL_free(*sig); return ret; } /* * This function demonstrates verification of an RSA signature over a SHA-256 * digest using the PSS signature scheme. */ static int verify(OSSL_LIB_CTX *libctx, const unsigned char *sig, size_t sig_len) { int ret = 0; const unsigned char *ppub_key = NULL; EVP_PKEY *pkey = NULL; EVP_PKEY_CTX *ctx = NULL; EVP_MD *md = NULL; /* Load DER-encoded RSA public key. */ ppub_key = rsa_pub_key; pkey = d2i_PublicKey(EVP_PKEY_RSA, NULL, &ppub_key, sizeof(rsa_pub_key)); if (pkey == NULL) { fprintf(stderr, "Failed to load public key\n"); goto end; } /* Fetch hash algorithm we want to use. */ md = EVP_MD_fetch(libctx, "SHA256", propq); if (md == NULL) { fprintf(stderr, "Failed to fetch hash algorithm\n"); goto end; } /* Create verification context. */ ctx = EVP_PKEY_CTX_new_from_pkey(libctx, pkey, propq); if (ctx == NULL) { fprintf(stderr, "Failed to create verification context\n"); goto end; } /* Initialize context for verification and set options. */ if (EVP_PKEY_verify_init(ctx) == 0) { fprintf(stderr, "Failed to initialize verification context\n"); goto end; } if (EVP_PKEY_CTX_set_rsa_padding(ctx, RSA_PKCS1_PSS_PADDING) == 0) { fprintf(stderr, "Failed to configure padding\n"); goto end; } if (EVP_PKEY_CTX_set_signature_md(ctx, md) == 0) { fprintf(stderr, "Failed to configure digest type\n"); goto end; } /* Verify signature. */ if (EVP_PKEY_verify(ctx, sig, sig_len, test_digest, sizeof(test_digest)) == 0) { fprintf(stderr, "Failed to verify signature; " "signature may be invalid\n"); goto end; } ret = 1; end: EVP_PKEY_CTX_free(ctx); EVP_PKEY_free(pkey); EVP_MD_free(md); return ret; } int main(int argc, char **argv) { int ret = EXIT_FAILURE; OSSL_LIB_CTX *libctx = NULL; unsigned char *sig = NULL; size_t sig_len = 0; if (sign(libctx, &sig, &sig_len) == 0) goto end; if (verify(libctx, sig, sig_len) == 0) goto end; printf("Success\n"); ret = EXIT_SUCCESS; end: OPENSSL_free(sig); OSSL_LIB_CTX_free(libctx); return ret; }
./openssl/demos/signature/EVP_EC_Signature_demo.c
/*- * Copyright 2021-2023 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ /* * An example that uses the EVP_MD*, EVP_DigestSign* and EVP_DigestVerify* * methods to calculate and verify a signature of two static buffers. */ #include <string.h> #include <stdio.h> #include <openssl/err.h> #include <openssl/evp.h> #include <openssl/decoder.h> #include "EVP_EC_Signature_demo.h" /* * This demonstration will calculate and verify a signature of data using * the soliloquy from Hamlet scene 1 act 3 */ static const char *hamlet_1 = "To be, or not to be, that is the question,\n" "Whether tis nobler in the minde to suffer\n" "The slings and arrowes of outragious fortune,\n" "Or to take Armes again in a sea of troubles,\n" ; static const char *hamlet_2 = "And by opposing, end them, to die to sleep;\n" "No more, and by a sleep, to say we end\n" "The heart-ache, and the thousand natural shocks\n" "That flesh is heir to? tis a consumation\n" ; /* * For demo_sign, load EC private key priv_key from priv_key_der[]. * For demo_verify, load EC public key pub_key from pub_key_der[]. */ static EVP_PKEY *get_key(OSSL_LIB_CTX *libctx, const char *propq, int public) { OSSL_DECODER_CTX *dctx = NULL; EVP_PKEY *pkey = NULL; int selection; const unsigned char *data; size_t data_len; if (public) { selection = EVP_PKEY_PUBLIC_KEY; data = pub_key_der; data_len = sizeof(pub_key_der); } else { selection = EVP_PKEY_KEYPAIR; data = priv_key_der; data_len = sizeof(priv_key_der); } dctx = OSSL_DECODER_CTX_new_for_pkey(&pkey, "DER", NULL, "EC", selection, libctx, propq); (void)OSSL_DECODER_from_data(dctx, &data, &data_len); OSSL_DECODER_CTX_free(dctx); if (pkey == NULL) fprintf(stderr, "Failed to load %s key.\n", public ? "public" : "private"); return pkey; } static int demo_sign(OSSL_LIB_CTX *libctx, const char *sig_name, size_t *sig_out_len, unsigned char **sig_out_value) { int ret = 0, public = 0; size_t sig_len; unsigned char *sig_value = NULL; const char *propq = NULL; EVP_MD_CTX *sign_context = NULL; EVP_PKEY *priv_key = NULL; /* Get private key */ priv_key = get_key(libctx, propq, public); if (priv_key == NULL) { fprintf(stderr, "Get private key failed.\n"); goto cleanup; } /* * Make a message signature context to hold temporary state * during signature creation */ sign_context = EVP_MD_CTX_new(); if (sign_context == NULL) { fprintf(stderr, "EVP_MD_CTX_new failed.\n"); goto cleanup; } /* * Initialize the sign context to use the fetched * sign provider. */ if (!EVP_DigestSignInit_ex(sign_context, NULL, sig_name, libctx, NULL, priv_key, NULL)) { fprintf(stderr, "EVP_DigestSignInit_ex failed.\n"); goto cleanup; } /* * EVP_DigestSignUpdate() can be called several times on the same context * to include additional data. */ if (!EVP_DigestSignUpdate(sign_context, hamlet_1, strlen(hamlet_1))) { fprintf(stderr, "EVP_DigestSignUpdate(hamlet_1) failed.\n"); goto cleanup; } if (!EVP_DigestSignUpdate(sign_context, hamlet_2, strlen(hamlet_2))) { fprintf(stderr, "EVP_DigestSignUpdate(hamlet_2) failed.\n"); goto cleanup; } /* Call EVP_DigestSignFinal to get signature length sig_len */ if (!EVP_DigestSignFinal(sign_context, NULL, &sig_len)) { fprintf(stderr, "EVP_DigestSignFinal failed.\n"); goto cleanup; } if (sig_len <= 0) { fprintf(stderr, "EVP_DigestSignFinal returned invalid signature length.\n"); goto cleanup; } sig_value = OPENSSL_malloc(sig_len); if (sig_value == NULL) { fprintf(stderr, "No memory.\n"); goto cleanup; } if (!EVP_DigestSignFinal(sign_context, sig_value, &sig_len)) { fprintf(stderr, "EVP_DigestSignFinal failed.\n"); goto cleanup; } *sig_out_len = sig_len; *sig_out_value = sig_value; fprintf(stdout, "Generating signature:\n"); BIO_dump_indent_fp(stdout, sig_value, sig_len, 2); fprintf(stdout, "\n"); ret = 1; cleanup: /* OpenSSL free functions will ignore NULL arguments */ if (!ret) OPENSSL_free(sig_value); EVP_PKEY_free(priv_key); EVP_MD_CTX_free(sign_context); return ret; } static int demo_verify(OSSL_LIB_CTX *libctx, const char *sig_name, size_t sig_len, unsigned char *sig_value) { int ret = 0, public = 1; const char *propq = NULL; EVP_MD_CTX *verify_context = NULL; EVP_PKEY *pub_key = NULL; /* * Make a verify signature context to hold temporary state * during signature verification */ verify_context = EVP_MD_CTX_new(); if (verify_context == NULL) { fprintf(stderr, "EVP_MD_CTX_new failed.\n"); goto cleanup; } /* Get public key */ pub_key = get_key(libctx, propq, public); if (pub_key == NULL) { fprintf(stderr, "Get public key failed.\n"); goto cleanup; } /* Verify */ if (!EVP_DigestVerifyInit_ex(verify_context, NULL, sig_name, libctx, NULL, pub_key, NULL)) { fprintf(stderr, "EVP_DigestVerifyInit failed.\n"); goto cleanup; } /* * EVP_DigestVerifyUpdate() can be called several times on the same context * to include additional data. */ if (!EVP_DigestVerifyUpdate(verify_context, hamlet_1, strlen(hamlet_1))) { fprintf(stderr, "EVP_DigestVerifyUpdate(hamlet_1) failed.\n"); goto cleanup; } if (!EVP_DigestVerifyUpdate(verify_context, hamlet_2, strlen(hamlet_2))) { fprintf(stderr, "EVP_DigestVerifyUpdate(hamlet_2) failed.\n"); goto cleanup; } if (EVP_DigestVerifyFinal(verify_context, sig_value, sig_len) <= 0) { fprintf(stderr, "EVP_DigestVerifyFinal failed.\n"); goto cleanup; } fprintf(stdout, "Signature verified.\n"); ret = 1; cleanup: /* OpenSSL free functions will ignore NULL arguments */ EVP_PKEY_free(pub_key); EVP_MD_CTX_free(verify_context); return ret; } int main(void) { OSSL_LIB_CTX *libctx = NULL; const char *sig_name = "SHA3-512"; size_t sig_len = 0; unsigned char *sig_value = NULL; int ret = EXIT_FAILURE; libctx = OSSL_LIB_CTX_new(); if (libctx == NULL) { fprintf(stderr, "OSSL_LIB_CTX_new() returned NULL\n"); goto cleanup; } if (!demo_sign(libctx, sig_name, &sig_len, &sig_value)) { fprintf(stderr, "demo_sign failed.\n"); goto cleanup; } if (!demo_verify(libctx, sig_name, sig_len, sig_value)) { fprintf(stderr, "demo_verify failed.\n"); goto cleanup; } ret = EXIT_SUCCESS; cleanup: if (ret != EXIT_SUCCESS) ERR_print_errors_fp(stderr); /* OpenSSL free functions will ignore NULL arguments */ OSSL_LIB_CTX_free(libctx); OPENSSL_free(sig_value); return ret; }
./openssl/demos/signature/EVP_ED_Signature_demo.c
/*- * Copyright 2023 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ /* * This demonstration will calculate and verify an ED25519 signature of * a message using EVP_DigestSign() and EVP_DigestVerify(). */ #include <string.h> #include <stdio.h> #include <openssl/err.h> #include <openssl/evp.h> #include <openssl/core_names.h> /* A test message to be signed (TBS) */ static const unsigned char hamlet[] = "To be, or not to be, that is the question,\n" "Whether tis nobler in the minde to suffer\n" "The slings and arrowes of outragious fortune,\n" "Or to take Armes again in a sea of troubles,\n"; static int demo_sign(EVP_PKEY *priv, const unsigned char *tbs, size_t tbs_len, OSSL_LIB_CTX *libctx, unsigned char **sig_out_value, size_t *sig_out_len) { int ret = 0; size_t sig_len; unsigned char *sig_value = NULL; EVP_MD_CTX *sign_context = NULL; /* Create a signature context */ sign_context = EVP_MD_CTX_new(); if (sign_context == NULL) { fprintf(stderr, "EVP_MD_CTX_new failed.\n"); goto cleanup; } /* * Initialize the sign context using an ED25519 private key * Notice that the digest name must NOT be used. * In this demo we don't specify any additional parameters via * OSSL_PARAM, which means it will use default values. * For more information, refer to doc/man7/EVP_SIGNATURE-ED25519.pod * "ED25519 and ED448 Signature Parameters" */ if (!EVP_DigestSignInit_ex(sign_context, NULL, NULL, libctx, NULL, priv, NULL)) { fprintf(stderr, "EVP_DigestSignInit_ex failed.\n"); goto cleanup; } /* Calculate the required size for the signature by passing a NULL buffer. */ if (!EVP_DigestSign(sign_context, NULL, &sig_len, tbs, tbs_len)) { fprintf(stderr, "EVP_DigestSign using NULL buffer failed.\n"); goto cleanup; } sig_value = OPENSSL_malloc(sig_len); if (sig_value == NULL) { fprintf(stderr, "OPENSSL_malloc failed.\n"); goto cleanup; } fprintf(stdout, "Generating signature:\n"); if (!EVP_DigestSign(sign_context, sig_value, &sig_len, tbs, tbs_len)) { fprintf(stderr, "EVP_DigestSign failed.\n"); goto cleanup; } *sig_out_len = sig_len; *sig_out_value = sig_value; BIO_dump_indent_fp(stdout, sig_value, sig_len, 2); fprintf(stdout, "\n"); ret = 1; cleanup: if (!ret) OPENSSL_free(sig_value); EVP_MD_CTX_free(sign_context); return ret; } static int demo_verify(EVP_PKEY *pub, const unsigned char *tbs, size_t tbs_len, const unsigned char *sig_value, size_t sig_len, OSSL_LIB_CTX *libctx) { int ret = 0; EVP_MD_CTX *verify_context = NULL; /* * Make a verify signature context to hold temporary state * during signature verification */ verify_context = EVP_MD_CTX_new(); if (verify_context == NULL) { fprintf(stderr, "EVP_MD_CTX_new failed.\n"); goto cleanup; } /* Initialize the verify context with a ED25519 public key */ if (!EVP_DigestVerifyInit_ex(verify_context, NULL, NULL, libctx, NULL, pub, NULL)) { fprintf(stderr, "EVP_DigestVerifyInit_ex failed.\n"); goto cleanup; } /* * ED25519 only supports the one shot interface using EVP_DigestVerify() * The streaming EVP_DigestVerifyUpdate() API is not supported. */ if (!EVP_DigestVerify(verify_context, sig_value, sig_len, tbs, tbs_len)) { fprintf(stderr, "EVP_DigestVerify() failed.\n"); goto cleanup; } fprintf(stdout, "Signature verified.\n"); ret = 1; cleanup: EVP_MD_CTX_free(verify_context); return ret; } static int create_key(OSSL_LIB_CTX *libctx, EVP_PKEY **privout, EVP_PKEY **pubout) { int ret = 0; EVP_PKEY *priv = NULL, *pub = NULL; unsigned char pubdata[32]; size_t pubdata_len = 0; /* * In this demo we just create a keypair, and extract the * public key. We could also use EVP_PKEY_new_raw_private_key_ex() * to create a key from raw data. */ priv = EVP_PKEY_Q_keygen(libctx, NULL, "ED25519"); if (priv == NULL) { fprintf(stderr, "EVP_PKEY_Q_keygen() failed\n"); goto end; } if (!EVP_PKEY_get_octet_string_param(priv, OSSL_PKEY_PARAM_PUB_KEY, pubdata, sizeof(pubdata), &pubdata_len)) { fprintf(stderr, "EVP_PKEY_get_octet_string_param() failed\n"); goto end; } pub = EVP_PKEY_new_raw_public_key_ex(libctx, "ED25519", NULL, pubdata, pubdata_len); if (pub == NULL) { fprintf(stderr, "EVP_PKEY_new_raw_public_key_ex() failed\n"); goto end; } ret = 1; end: if (ret) { *pubout = pub; *privout = priv; } else { EVP_PKEY_free(priv); } return ret; } int main(void) { OSSL_LIB_CTX *libctx = NULL; size_t sig_len = 0; unsigned char *sig_value = NULL; int ret = EXIT_FAILURE; EVP_PKEY *priv = NULL, *pub = NULL; libctx = OSSL_LIB_CTX_new(); if (libctx == NULL) { fprintf(stderr, "OSSL_LIB_CTX_new() returned NULL\n"); goto cleanup; } if (!create_key(libctx, &priv, &pub)) { fprintf(stderr, "Failed to create key.\n"); goto cleanup; } if (!demo_sign(priv, hamlet, sizeof(hamlet), libctx, &sig_value, &sig_len)) { fprintf(stderr, "demo_sign failed.\n"); goto cleanup; } if (!demo_verify(pub, hamlet, sizeof(hamlet), sig_value, sig_len, libctx)) { fprintf(stderr, "demo_verify failed.\n"); goto cleanup; } ret = EXIT_SUCCESS; cleanup: if (ret != EXIT_SUCCESS) ERR_print_errors_fp(stderr); EVP_PKEY_free(pub); EVP_PKEY_free(priv); OSSL_LIB_CTX_free(libctx); OPENSSL_free(sig_value); return ret; }
./openssl/demos/signature/rsa_pss.h
/*- * Copyright 2022 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ /* 4096-bit RSA private key, DER. */ static const unsigned char rsa_priv_key[] = { 0x30, 0x82, 0x09, 0x28, 0x02, 0x01, 0x00, 0x02, 0x82, 0x02, 0x01, 0x00, 0xa3, 0x14, 0xe4, 0xb8, 0xd8, 0x58, 0x0d, 0xab, 0xd7, 0x87, 0xa4, 0xf6, 0x84, 0x51, 0x74, 0x60, 0x4c, 0xe3, 0x60, 0x28, 0x89, 0x49, 0x65, 0x18, 0x5c, 0x8f, 0x1a, 0x1b, 0xe9, 0xdb, 0xc1, 0xc1, 0xf7, 0x08, 0x27, 0x44, 0xe5, 0x9d, 0x9a, 0x33, 0xc3, 0xac, 0x5a, 0xca, 0xba, 0x20, 0x5a, 0x9e, 0x3a, 0x18, 0xb5, 0x3d, 0xe3, 0x9d, 0x94, 0x58, 0xa7, 0xa9, 0x5a, 0x0b, 0x4f, 0xb8, 0xe5, 0xa3, 0x7b, 0x01, 0x11, 0x0f, 0x16, 0x11, 0xb8, 0x65, 0x2f, 0xa8, 0x95, 0xf7, 0x58, 0x2c, 0xec, 0x1d, 0x41, 0xad, 0xd1, 0x12, 0xca, 0x4a, 0x80, 0x35, 0x35, 0x43, 0x7e, 0xe0, 0x97, 0xfc, 0x86, 0x8f, 0xcf, 0x4b, 0xdc, 0xbc, 0x15, 0x2c, 0x8e, 0x90, 0x84, 0x26, 0x83, 0xc1, 0x96, 0x97, 0xf4, 0xd7, 0x90, 0xce, 0xfe, 0xd4, 0xf3, 0x70, 0x22, 0xa8, 0xb0, 0x1f, 0xed, 0x08, 0xd7, 0xc5, 0xc0, 0xd6, 0x41, 0x6b, 0x24, 0x68, 0x5c, 0x07, 0x1f, 0x44, 0x97, 0x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x2e, 0xc1, 0x11, 0xe9, 0x24, 0x70, 0x40, 0xba, 0x0b, 0x0e, 0x4a, 0xac, 0x45, 0x21, 0xcc, 0x6d, 0xa4, 0x1d, 0x55, 0x33, 0x89, 0x4c, 0x65, 0x21, 0x23, 0xab, 0x61, 0x31, 0xcb, 0x11, 0x65, 0xb3, 0x80, 0xa4, 0x5a, 0x2b, 0xf1, 0x65, 0xdb, 0x4c, 0x58, 0x5a, 0xbe, 0xf3, 0x15, 0xcd, 0x94, 0xa1, 0xe4, 0xcb, 0x30, 0xfa, 0xe1, 0x28, 0x51, 0x52, 0xd2, 0xb8, 0xb4, 0x8c, 0xfc, 0x3a, 0xcc, 0xd1, 0x19, 0xa2, 0x27, 0x36, 0xfa, 0xc4, 0x23, 0x96, 0xb9, 0xc7, 0x74, 0xca, 0xf1, 0x45, 0x1f, 0x4b, 0xc2, 0x77, 0x4d, 0x32, 0x3f, 0xab, 0x7a, 0xd9, 0x2b, 0x22, 0x1d, 0xcb, 0x24, 0x58, 0x29, 0xa3, 0xb8, 0x92, 0xdb, 0x1c, 0xda, 0x84, 0x01, 0xca, 0x6d, 0x4a, 0x50, 0xd4, 0x2b, 0x79, 0xfa, 0xc5, 0x4c, 0x9d, 0x79, 0x49, 0xf1, 0xde, 0xbd, 0x3f, 0x50, 0xa7, 0xa6, 0xc6, 0xc7, 0x99, 0x61, 0x9b, 0xda, 0x38, 0xdc, 0xbe, 0x85, 0x75, 0x81, 0xb9, 0x0f, 0x33, 0xd0, 0xd4, 0xd0, 0xaa, 0xbd, 0x32, 0xc9, 0x62, 0xe8, 0x21, 0x24, 0xeb, 0x03, 0x73, 0x46, 0xb3, 0x84, 0x65, 0xf2, 0x40, 0x7d, 0x1b, 0x1b, 0x8f, 0x86, 0x7c, 0xe7 }; /* The corresponding public key, DER. */ static const unsigned char rsa_pub_key[] = { 0x30, 0x82, 0x02, 0x0a, 0x02, 0x82, 0x02, 0x01, 0x00, 0xa3, 0x14, 0xe4, 0xb8, 0xd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xf9, 0x6a, 0xd7, 0x2e, 0xd0, 0xa7, 0x2c, 0x60, 0x58, 0xc4, 0x8f, 0x46, 0x63, 0x61, 0x8d, 0x29, 0x6f, 0xe2, 0x5f, 0xe2, 0x43, 0x90, 0x9c, 0xe6, 0xfc, 0x08, 0x41, 0xc8, 0xb5, 0x23, 0x56, 0x24, 0x3e, 0x3a, 0x2c, 0x41, 0x22, 0x43, 0xda, 0x22, 0x15, 0x2b, 0xad, 0xd0, 0xfa, 0xc8, 0x47, 0x44, 0xe6, 0x2a, 0xf9, 0x38, 0x90, 0x13, 0x62, 0x22, 0xea, 0x06, 0x8c, 0x44, 0x9c, 0xd6, 0xca, 0x50, 0x93, 0xe9, 0xd4, 0x03, 0xd8, 0x3e, 0x71, 0x36, 0x4b, 0xaa, 0xab, 0xbb, 0xe2, 0x48, 0x66, 0x26, 0x53, 0xb1, 0x6d, 0x3b, 0x82, 0x2c, 0x8c, 0x25, 0x05, 0xf0, 0xf8, 0xcf, 0x55, 0xbf, 0x8e, 0x29, 0xf7, 0x54, 0x5b, 0x6f, 0x30, 0x54, 0xa6, 0xad, 0x46, 0xff, 0x22, 0x95, 0xb1, 0x87, 0x98, 0x00, 0x51, 0x69, 0x15, 0x07, 0xbd, 0x3d, 0x9c, 0x6e, 0xaa, 0xaa, 0x3b, 0x0b, 0x74, 0x65, 0x4c, 0x04, 0xe0, 0x80, 0x3e, 0xaf, 0x5e, 0x10, 0xd6, 0x9b, 0x28, 0x37, 0x6f, 0x02, 0x03, 0x01, 0x00, 0x01 };
./openssl/demos/signature/EVP_DSA_Signature_demo.c
/*- * Copyright 2022-2023 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ /* * An example that uses the EVP_PKEY*, EVP_DigestSign* and EVP_DigestVerify* * methods to calculate public/private DSA keypair and to sign and verify * two static buffers. */ #include <string.h> #include <stdio.h> #include <openssl/err.h> #include <openssl/evp.h> #include <openssl/decoder.h> #include <openssl/dsa.h> /* * This demonstration will calculate and verify a signature of data using * the soliloquy from Hamlet scene 1 act 3 */ static const char *hamlet_1 = "To be, or not to be, that is the question,\n" "Whether tis nobler in the minde to suffer\n" "The slings and arrowes of outragious fortune,\n" "Or to take Armes again in a sea of troubles,\n" ; static const char *hamlet_2 = "And by opposing, end them, to die to sleep;\n" "No more, and by a sleep, to say we end\n" "The heart-ache, and the thousand natural shocks\n" "That flesh is heir to? tis a consumation\n" ; static const char ALG[] = "DSA"; static const char DIGEST[] = "SHA256"; static const int NUMBITS = 2048; static const char * const PROPQUERY = NULL; static int generate_dsa_params(OSSL_LIB_CTX *libctx, EVP_PKEY **p_params) { int ret = 0; EVP_PKEY_CTX *pkey_ctx = NULL; EVP_PKEY *params = NULL; pkey_ctx = EVP_PKEY_CTX_new_from_name(libctx, ALG, PROPQUERY); if (pkey_ctx == NULL) goto end; if (EVP_PKEY_paramgen_init(pkey_ctx) <= 0) goto end; if (EVP_PKEY_CTX_set_dsa_paramgen_bits(pkey_ctx, NUMBITS) <= 0) goto end; if (EVP_PKEY_paramgen(pkey_ctx, &params) <= 0) goto end; if (params == NULL) goto end; ret = 1; end: if(ret != 1) { EVP_PKEY_free(params); params = NULL; } EVP_PKEY_CTX_free(pkey_ctx); *p_params = params; fprintf(stdout, "Params:\n"); EVP_PKEY_print_params_fp(stdout, params, 4, NULL); fprintf(stdout, "\n"); return ret; } static int generate_dsa_key(OSSL_LIB_CTX *libctx, EVP_PKEY *params, EVP_PKEY **p_pkey) { int ret = 0; EVP_PKEY_CTX *ctx = NULL; EVP_PKEY *pkey = NULL; ctx = EVP_PKEY_CTX_new_from_pkey(libctx, params, NULL); if (ctx == NULL) goto end; if (EVP_PKEY_keygen_init(ctx) <= 0) goto end; if (EVP_PKEY_keygen(ctx, &pkey) <= 0) goto end; if (pkey == NULL) goto end; ret = 1; end: if(ret != 1) { EVP_PKEY_free(pkey); pkey = NULL; } EVP_PKEY_CTX_free(ctx); *p_pkey = pkey; fprintf(stdout, "Generating public/private key pair:\n"); EVP_PKEY_print_public_fp(stdout, pkey, 4, NULL); fprintf(stdout, "\n"); EVP_PKEY_print_private_fp(stdout, pkey, 4, NULL); fprintf(stdout, "\n"); EVP_PKEY_print_params_fp(stdout, pkey, 4, NULL); fprintf(stdout, "\n"); return ret; } static int extract_public_key(const EVP_PKEY *pkey, OSSL_PARAM **p_public_key) { int ret = 0; OSSL_PARAM *public_key = NULL; if (EVP_PKEY_todata(pkey, EVP_PKEY_PUBLIC_KEY, &public_key) != 1) goto end; ret = 1; end: if (ret != 1) { OSSL_PARAM_free(public_key); public_key = NULL; } *p_public_key = public_key; return ret; } static int extract_keypair(const EVP_PKEY *pkey, OSSL_PARAM **p_keypair) { int ret = 0; OSSL_PARAM *keypair = NULL; if (EVP_PKEY_todata(pkey, EVP_PKEY_KEYPAIR, &keypair) != 1) goto end; ret = 1; end: if (ret != 1) { OSSL_PARAM_free(keypair); keypair = NULL; } *p_keypair = keypair; return ret; } static int demo_sign(OSSL_LIB_CTX *libctx, size_t *p_sig_len, unsigned char **p_sig_value, OSSL_PARAM keypair[]) { int ret = 0; size_t sig_len = 0; unsigned char *sig_value = NULL; EVP_MD_CTX *ctx = NULL; EVP_PKEY_CTX *pkey_ctx = NULL; EVP_PKEY *pkey = NULL; pkey_ctx = EVP_PKEY_CTX_new_from_name(libctx, ALG, PROPQUERY); if (pkey_ctx == NULL) goto end; if (EVP_PKEY_fromdata_init(pkey_ctx) != 1) goto end; if (EVP_PKEY_fromdata(pkey_ctx, &pkey, EVP_PKEY_KEYPAIR, keypair) != 1) goto end; ctx = EVP_MD_CTX_create(); if (ctx == NULL) goto end; if (EVP_DigestSignInit_ex(ctx, NULL, DIGEST, libctx, NULL, pkey, NULL) != 1) goto end; if (EVP_DigestSignUpdate(ctx, hamlet_1, sizeof(hamlet_1)) != 1) goto end; if (EVP_DigestSignUpdate(ctx, hamlet_2, sizeof(hamlet_2)) != 1) goto end; /* Calculate the signature size */ if (EVP_DigestSignFinal(ctx, NULL, &sig_len) != 1) goto end; if (sig_len == 0) goto end; sig_value = OPENSSL_malloc(sig_len); if (sig_value == NULL) goto end; /* Calculate the signature */ if (EVP_DigestSignFinal(ctx, sig_value, &sig_len) != 1) goto end; ret = 1; end: EVP_MD_CTX_free(ctx); if (ret != 1) { OPENSSL_free(sig_value); sig_len = 0; sig_value = NULL; } *p_sig_len = sig_len; *p_sig_value = sig_value; EVP_PKEY_free(pkey); EVP_PKEY_CTX_free(pkey_ctx); fprintf(stdout, "Generating signature:\n"); BIO_dump_indent_fp(stdout, sig_value, sig_len, 2); fprintf(stdout, "\n"); return ret; } static int demo_verify(OSSL_LIB_CTX *libctx, size_t sig_len, unsigned char *sig_value, OSSL_PARAM public_key[]) { int ret = 0; EVP_MD_CTX *ctx = NULL; EVP_PKEY_CTX *pkey_ctx = NULL; EVP_PKEY *pkey = NULL; pkey_ctx = EVP_PKEY_CTX_new_from_name(libctx, ALG, PROPQUERY); if (pkey_ctx == NULL) goto end; if (EVP_PKEY_fromdata_init(pkey_ctx) != 1) goto end; if (EVP_PKEY_fromdata(pkey_ctx, &pkey, EVP_PKEY_PUBLIC_KEY, public_key) != 1) goto end; ctx = EVP_MD_CTX_create(); if(ctx == NULL) goto end; if (EVP_DigestVerifyInit_ex(ctx, NULL, DIGEST, libctx, NULL, pkey, NULL) != 1) goto end; if (EVP_DigestVerifyUpdate(ctx, hamlet_1, sizeof(hamlet_1)) != 1) goto end; if (EVP_DigestVerifyUpdate(ctx, hamlet_2, sizeof(hamlet_2)) != 1) goto end; if (EVP_DigestVerifyFinal(ctx, sig_value, sig_len) != 1) goto end; ret = 1; end: EVP_PKEY_free(pkey); EVP_PKEY_CTX_free(pkey_ctx); EVP_MD_CTX_free(ctx); return ret; } int main(void) { int ret = EXIT_FAILURE; OSSL_LIB_CTX *libctx = NULL; EVP_PKEY *params = NULL; EVP_PKEY *pkey = NULL; OSSL_PARAM *public_key = NULL; OSSL_PARAM *keypair = NULL; size_t sig_len = 0; unsigned char *sig_value = NULL; libctx = OSSL_LIB_CTX_new(); if (libctx == NULL) goto end; if (generate_dsa_params(libctx, &params) != 1) goto end; if (generate_dsa_key(libctx, params, &pkey) != 1) goto end; if (extract_public_key(pkey, &public_key) != 1) goto end; if (extract_keypair(pkey, &keypair) != 1) goto end; /* The signer signs with his private key, and distributes his public key */ if (demo_sign(libctx, &sig_len, &sig_value, keypair) != 1) goto end; /* A verifier uses the signers public key to verify the signature */ if (demo_verify(libctx, sig_len, sig_value, public_key) != 1) goto end; ret = EXIT_SUCCESS; end: if (ret != EXIT_SUCCESS) ERR_print_errors_fp(stderr); OPENSSL_free(sig_value); EVP_PKEY_free(params); EVP_PKEY_free(pkey); OSSL_PARAM_free(public_key); OSSL_PARAM_free(keypair); OSSL_LIB_CTX_free(libctx); return ret; }
./openssl/demos/signature/EVP_EC_Signature_demo.h
/*- * Copyright 2021 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ /* Signers private EC key */ static const unsigned char priv_key_der[] = { 0x30, 0x82, 0x01, 0x68, 0x02, 0x01, 0x01, 0x04, 0x20, 0x51, 0x77, 0xae, 0xf4, 0x18, 0xf4, 0x6b, 0xc4, 0xe5, 0xbb, 0xe9, 0xe6, 0x9e, 0x6d, 0xb0, 0xea, 0x12, 0xf9, 0xf3, 0xdb, 0x9d, 0x56, 0x59, 0xf7, 0x5a, 0x17, 0xd7, 0xd1, 0xe4, 0xd7, 0x47, 0x28, 0xa0, 0x81, 0xfa, 0x30, 0x81, 0xf7, 0x02, 0x01, 0x01, 0x30, 0x2c, 0x06, 0x07, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x01, 0x01, 0x02, 0x21, 0x00, 0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x30, 0x5b, 0x04, 0x20, 0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfc, 0x04, 0x20, 0x5a, 0xc6, 0x35, 0xd8, 0xaa, 0x3a, 0x93, 0xe7, 0xb3, 0xeb, 0xbd, 0x55, 0x76, 0x98, 0x86, 0xbc, 0x65, 0x1d, 0x06, 0xb0, 0xcc, 0x53, 0xb0, 0xf6, 0x3b, 0xce, 0x3c, 0x3e, 0x27, 0xd2, 0x60, 0x4b, 0x03, 0x15, 0x00, 0xc4, 0x9d, 0x36, 0x08, 0x86, 0xe7, 0x04, 0x93, 0x6a, 0x66, 0x78, 0xe1, 0x13, 0x9d, 0x26, 0xb7, 0x81, 0x9f, 0x7e, 0x90, 0x04, 0x41, 0x04, 0x6b, 0x17, 0xd1, 0xf2, 0xe1, 0x2c, 0x42, 0x47, 0xf8, 0xbc, 0xe6, 0xe5, 0x63, 0xa4, 0x40, 0xf2, 0x77, 0x03, 0x7d, 0x81, 0x2d, 0xeb, 0x33, 0xa0, 0xf4, 0xa1, 0x39, 0x45, 0xd8, 0x98, 0xc2, 0x96, 0x4f, 0xe3, 0x42, 0xe2, 0xfe, 0x1a, 0x7f, 0x9b, 0x8e, 0xe7, 0xeb, 0x4a, 0x7c, 0x0f, 0x9e, 0x16, 0x2b, 0xce, 0x33, 0x57, 0x6b, 0x31, 0x5e, 0xce, 0xcb, 0xb6, 0x40, 0x68, 0x37, 0xbf, 0x51, 0xf5, 0x02, 0x21, 0x00, 0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xbc, 0xe6, 0xfa, 0xad, 0xa7, 0x17, 0x9e, 0x84, 0xf3, 0xb9, 0xca, 0xc2, 0xfc, 0x63, 0x25, 0x51, 0x02, 0x01, 0x01, 0xa1, 0x44, 0x03, 0x42, 0x00, 0x04, 0x4f, 0xe7, 0x7b, 0xb6, 0xbb, 0x54, 0x42, 0x39, 0xed, 0x5d, 0xe5, 0x40, 0xc8, 0xd8, 0x71, 0xca, 0x6d, 0x83, 0x71, 0xd1, 0x88, 0x2a, 0x65, 0x00, 0x6c, 0xc6, 0x2f, 0x01, 0x31, 0x49, 0xbe, 0x76, 0x7a, 0x67, 0x6a, 0x28, 0x33, 0xc7, 0x5b, 0xb9, 0x24, 0x45, 0x24, 0x6e, 0xf0, 0x6d, 0x2f, 0x34, 0x06, 0x53, 0x73, 0x6a, 0xff, 0x90, 0x90, 0xc1, 0x6d, 0x9b, 0x94, 0x0d, 0x0e, 0x1f, 0x95, 0x65, }; /* The matching public key used for verifying */ static const unsigned char pub_key_der[] = { 0x30, 0x82, 0x01, 0x4b, 0x30, 0x82, 0x01, 0x03, 0x06, 0x07, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x02, 0x01, 0x30, 0x81, 0xf7, 0x02, 0x01, 0x01, 0x30, 0x2c, 0x06, 0x07, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x01, 0x01, 0x02, 0x21, 0x00, 0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x30, 0x5b, 0x04, 0x20, 0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfc, 0x04, 0x20, 0x5a, 0xc6, 0x35, 0xd8, 0xaa, 0x3a, 0x93, 0xe7, 0xb3, 0xeb, 0xbd, 0x55, 0x76, 0x98, 0x86, 0xbc, 0x65, 0x1d, 0x06, 0xb0, 0xcc, 0x53, 0xb0, 0xf6, 0x3b, 0xce, 0x3c, 0x3e, 0x27, 0xd2, 0x60, 0x4b, 0x03, 0x15, 0x00, 0xc4, 0x9d, 0x36, 0x08, 0x86, 0xe7, 0x04, 0x93, 0x6a, 0x66, 0x78, 0xe1, 0x13, 0x9d, 0x26, 0xb7, 0x81, 0x9f, 0x7e, 0x90, 0x04, 0x41, 0x04, 0x6b, 0x17, 0xd1, 0xf2, 0xe1, 0x2c, 0x42, 0x47, 0xf8, 0xbc, 0xe6, 0xe5, 0x63, 0xa4, 0x40, 0xf2, 0x77, 0x03, 0x7d, 0x81, 0x2d, 0xeb, 0x33, 0xa0, 0xf4, 0xa1, 0x39, 0x45, 0xd8, 0x98, 0xc2, 0x96, 0x4f, 0xe3, 0x42, 0xe2, 0xfe, 0x1a, 0x7f, 0x9b, 0x8e, 0xe7, 0xeb, 0x4a, 0x7c, 0x0f, 0x9e, 0x16, 0x2b, 0xce, 0x33, 0x57, 0x6b, 0x31, 0x5e, 0xce, 0xcb, 0xb6, 0x40, 0x68, 0x37, 0xbf, 0x51, 0xf5, 0x02, 0x21, 0x00, 0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xbc, 0xe6, 0xfa, 0xad, 0xa7, 0x17, 0x9e, 0x84, 0xf3, 0xb9, 0xca, 0xc2, 0xfc, 0x63, 0x25, 0x51, 0x02, 0x01, 0x01, 0x03, 0x42, 0x00, 0x04, 0x4f, 0xe7, 0x7b, 0xb6, 0xbb, 0x54, 0x42, 0x39, 0xed, 0x5d, 0xe5, 0x40, 0xc8, 0xd8, 0x71, 0xca, 0x6d, 0x83, 0x71, 0xd1, 0x88, 0x2a, 0x65, 0x00, 0x6c, 0xc6, 0x2f, 0x01, 0x31, 0x49, 0xbe, 0x76, 0x7a, 0x67, 0x6a, 0x28, 0x33, 0xc7, 0x5b, 0xb9, 0x24, 0x45, 0x24, 0x6e, 0xf0, 0x6d, 0x2f, 0x34, 0x06, 0x53, 0x73, 0x6a, 0xff, 0x90, 0x90, 0xc1, 0x6d, 0x9b, 0x94, 0x0d, 0x0e, 0x1f, 0x95, 0x65, };
./openssl/demos/encrypt/rsa_encrypt.c
/*- * Copyright 2021 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ /* * An example that uses EVP_PKEY_encrypt and EVP_PKEY_decrypt methods * to encrypt and decrypt data using an RSA keypair. * RSA encryption produces different encrypted output each time it is run, * hence this is not a known answer test. */ #include <stdio.h> #include <stdlib.h> #include <openssl/err.h> #include <openssl/evp.h> #include <openssl/decoder.h> #include <openssl/core_names.h> #include "rsa_encrypt.h" /* Input data to encrypt */ static const unsigned char msg[] = "To be, or not to be, that is the question,\n" "Whether tis nobler in the minde to suffer\n" "The slings and arrowes of outragious fortune,\n" "Or to take Armes again in a sea of troubles"; /* * For do_encrypt(), load an RSA public key from pub_key_der[]. * For do_decrypt(), load an RSA private key from priv_key_der[]. */ static EVP_PKEY *get_key(OSSL_LIB_CTX *libctx, const char *propq, int public) { OSSL_DECODER_CTX *dctx = NULL; EVP_PKEY *pkey = NULL; int selection; const unsigned char *data; size_t data_len; if (public) { selection = EVP_PKEY_PUBLIC_KEY; data = pub_key_der; data_len = sizeof(pub_key_der); } else { selection = EVP_PKEY_KEYPAIR; data = priv_key_der; data_len = sizeof(priv_key_der); } dctx = OSSL_DECODER_CTX_new_for_pkey(&pkey, "DER", NULL, "RSA", selection, libctx, propq); (void)OSSL_DECODER_from_data(dctx, &data, &data_len); OSSL_DECODER_CTX_free(dctx); return pkey; } /* Set optional parameters for RSA OAEP Padding */ static void set_optional_params(OSSL_PARAM *p, const char *propq) { static unsigned char label[] = "label"; /* "pkcs1" is used by default if the padding mode is not set */ *p++ = OSSL_PARAM_construct_utf8_string(OSSL_ASYM_CIPHER_PARAM_PAD_MODE, OSSL_PKEY_RSA_PAD_MODE_OAEP, 0); /* No oaep_label is used if this is not set */ *p++ = OSSL_PARAM_construct_octet_string(OSSL_ASYM_CIPHER_PARAM_OAEP_LABEL, label, sizeof(label)); /* "SHA1" is used if this is not set */ *p++ = OSSL_PARAM_construct_utf8_string(OSSL_ASYM_CIPHER_PARAM_OAEP_DIGEST, "SHA256", 0); /* * If a non default property query needs to be specified when fetching the * OAEP digest then it needs to be specified here. */ if (propq != NULL) *p++ = OSSL_PARAM_construct_utf8_string(OSSL_ASYM_CIPHER_PARAM_OAEP_DIGEST_PROPS, (char *)propq, 0); /* * OSSL_ASYM_CIPHER_PARAM_MGF1_DIGEST and * OSSL_ASYM_CIPHER_PARAM_MGF1_DIGEST_PROPS can also be optionally added * here if the MGF1 digest differs from the OAEP digest. */ *p = OSSL_PARAM_construct_end(); } /* * The length of the input data that can be encrypted is limited by the * RSA key length minus some additional bytes that depends on the padding mode. * */ static int do_encrypt(OSSL_LIB_CTX *libctx, const unsigned char *in, size_t in_len, unsigned char **out, size_t *out_len) { int ret = 0, public = 1; size_t buf_len = 0; unsigned char *buf = NULL; const char *propq = NULL; EVP_PKEY_CTX *ctx = NULL; EVP_PKEY *pub_key = NULL; OSSL_PARAM params[5]; /* Get public key */ pub_key = get_key(libctx, propq, public); if (pub_key == NULL) { fprintf(stderr, "Get public key failed.\n"); goto cleanup; } ctx = EVP_PKEY_CTX_new_from_pkey(libctx, pub_key, propq); if (ctx == NULL) { fprintf(stderr, "EVP_PKEY_CTX_new_from_pkey() failed.\n"); goto cleanup; } set_optional_params(params, propq); /* If no optional parameters are required then NULL can be passed */ if (EVP_PKEY_encrypt_init_ex(ctx, params) <= 0) { fprintf(stderr, "EVP_PKEY_encrypt_init_ex() failed.\n"); goto cleanup; } /* Calculate the size required to hold the encrypted data */ if (EVP_PKEY_encrypt(ctx, NULL, &buf_len, in, in_len) <= 0) { fprintf(stderr, "EVP_PKEY_encrypt() failed.\n"); goto cleanup; } buf = OPENSSL_zalloc(buf_len); if (buf == NULL) { fprintf(stderr, "Malloc failed.\n"); goto cleanup; } if (EVP_PKEY_encrypt(ctx, buf, &buf_len, in, in_len) <= 0) { fprintf(stderr, "EVP_PKEY_encrypt() failed.\n"); goto cleanup; } *out_len = buf_len; *out = buf; fprintf(stdout, "Encrypted:\n"); BIO_dump_indent_fp(stdout, buf, buf_len, 2); fprintf(stdout, "\n"); ret = 1; cleanup: if (!ret) OPENSSL_free(buf); EVP_PKEY_free(pub_key); EVP_PKEY_CTX_free(ctx); return ret; } static int do_decrypt(OSSL_LIB_CTX *libctx, const unsigned char *in, size_t in_len, unsigned char **out, size_t *out_len) { int ret = 0, public = 0; size_t buf_len = 0; unsigned char *buf = NULL; const char *propq = NULL; EVP_PKEY_CTX *ctx = NULL; EVP_PKEY *priv_key = NULL; OSSL_PARAM params[5]; /* Get private key */ priv_key = get_key(libctx, propq, public); if (priv_key == NULL) { fprintf(stderr, "Get private key failed.\n"); goto cleanup; } ctx = EVP_PKEY_CTX_new_from_pkey(libctx, priv_key, propq); if (ctx == NULL) { fprintf(stderr, "EVP_PKEY_CTX_new_from_pkey() failed.\n"); goto cleanup; } /* The parameters used for encryption must also be used for decryption */ set_optional_params(params, propq); /* If no optional parameters are required then NULL can be passed */ if (EVP_PKEY_decrypt_init_ex(ctx, params) <= 0) { fprintf(stderr, "EVP_PKEY_decrypt_init_ex() failed.\n"); goto cleanup; } /* Calculate the size required to hold the decrypted data */ if (EVP_PKEY_decrypt(ctx, NULL, &buf_len, in, in_len) <= 0) { fprintf(stderr, "EVP_PKEY_decrypt() failed.\n"); goto cleanup; } buf = OPENSSL_zalloc(buf_len); if (buf == NULL) { fprintf(stderr, "Malloc failed.\n"); goto cleanup; } if (EVP_PKEY_decrypt(ctx, buf, &buf_len, in, in_len) <= 0) { fprintf(stderr, "EVP_PKEY_decrypt() failed.\n"); goto cleanup; } *out_len = buf_len; *out = buf; fprintf(stdout, "Decrypted:\n"); BIO_dump_indent_fp(stdout, buf, buf_len, 2); fprintf(stdout, "\n"); ret = 1; cleanup: if (!ret) OPENSSL_free(buf); EVP_PKEY_free(priv_key); EVP_PKEY_CTX_free(ctx); return ret; } int main(void) { int ret = EXIT_FAILURE; size_t msg_len = sizeof(msg) - 1; size_t encrypted_len = 0, decrypted_len = 0; unsigned char *encrypted = NULL, *decrypted = NULL; OSSL_LIB_CTX *libctx = NULL; if (!do_encrypt(libctx, msg, msg_len, &encrypted, &encrypted_len)) { fprintf(stderr, "encryption failed.\n"); goto cleanup; } if (!do_decrypt(libctx, encrypted, encrypted_len, &decrypted, &decrypted_len)) { fprintf(stderr, "decryption failed.\n"); goto cleanup; } if (CRYPTO_memcmp(msg, decrypted, decrypted_len) != 0) { fprintf(stderr, "Decrypted data does not match expected value\n"); goto cleanup; } ret = EXIT_SUCCESS; cleanup: OPENSSL_free(decrypted); OPENSSL_free(encrypted); OSSL_LIB_CTX_free(libctx); if (ret != EXIT_SUCCESS) ERR_print_errors_fp(stderr); return ret; }
./openssl/demos/encrypt/rsa_encrypt.h
/*- * Copyright 2021 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ /* Private RSA key used for decryption */ static const unsigned char priv_key_der[] = { 0x30, 0x82, 0x04, 0xa4, 0x02, 0x01, 0x00, 0x02, 0x82, 0x01, 0x01, 0x00, 0xc2, 0x44, 0xbc, 0xcf, 0x5b, 0xca, 0xcd, 0x80, 0x77, 0xae, 0xf9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c, 0x20, 0xa2, 0x5a, 0x08, 0xf6, 0x90, 0x0d, 0x9a, 0xd7, 0x20, 0xf1, 0x10, 0x66, 0x28, 0x4c, 0x22, 0x56, 0xa6, 0xb9, 0xff, 0xd0, 0x6a, 0x62, 0x8c, 0x9f, 0xf8, 0x7c, 0xf4, 0xad, 0xd7, 0xe8, 0xf9, 0x87, 0x43, 0xbf, 0x73, 0x5b, 0x04, 0xc7, 0xd0, 0x77, 0xcc, 0xe3, 0xbe, 0xda, 0xc2, 0x07, 0xed, 0x8d, 0x2a, 0x15, 0x77, 0x1d, 0x53, 0x47, 0xe0, 0xa2, 0x11, 0x41, 0x0d, 0xe2, 0xe7, }; /* The matching public key used for encryption*/ static const unsigned char pub_key_der[] = { 0x30, 0x82, 0x01, 0x22, 0x30, 0x0d, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x01, 0x05, 0x00, 0x03, 0x82, 0x01, 0x0f, 0x00, 0x30, 0x82, 0x01, 0x0a, 0x02, 0x82, 0x01, 0x01, 0x00, 0xc2, 0x44, 0xbc, 0xcf, 0x5b, 0xca, 0xcd, 0x80, 0x77, 0xae, 0xf9, 0x7a, 0x34, 0xbb, 0x37, 0x6f, 0x5c, 0x76, 0x4c, 0xe4, 0xbb, 0x0c, 0x1d, 0xe7, 0xfe, 0x0f, 0xda, 0xcf, 0x8c, 0x56, 0x65, 0x72, 0x6e, 0x2c, 0xf9, 0xfd, 0x87, 0x43, 0xeb, 0x4c, 0x26, 0xb1, 0xd3, 0xf0, 0x87, 0xb1, 0x18, 0x68, 0x14, 0x7d, 0x3c, 0x2a, 0xfa, 0xc2, 0x5d, 0x70, 0x19, 0x11, 0x00, 0x2e, 0xb3, 0x9c, 0x8e, 0x38, 0x08, 0xbe, 0xe3, 0xeb, 0x7d, 0x6e, 0xc7, 0x19, 0xc6, 0x7f, 0x59, 0x48, 0x84, 0x1b, 0xe3, 0x27, 0x30, 0x46, 0x30, 0xd3, 0xfc, 0xfc, 0xb3, 0x35, 0x75, 0xc4, 0x31, 0x1a, 0xc0, 0xc2, 0x4c, 0x0b, 0xc7, 0x01, 0x95, 0xb2, 0xdc, 0x17, 0x77, 0x9b, 0x09, 0x15, 0x04, 0xbc, 0xdb, 0x57, 0x0b, 0x26, 0xda, 0x59, 0x54, 0x0d, 0x6e, 0xb7, 0x89, 0xbc, 0x53, 0x9d, 0x5f, 0x8c, 0xad, 0x86, 0x97, 0xd2, 0x48, 0x4f, 0x5c, 0x94, 0xdd, 0x30, 0x2f, 0xcf, 0xfc, 0xde, 0x20, 0x31, 0x25, 0x9d, 0x29, 0x25, 0x78, 0xb7, 0xd2, 0x5b, 0x5d, 0x99, 0x5b, 0x08, 0x12, 0x81, 0x79, 0x89, 0xa0, 0xcf, 0x8f, 0x40, 0xb1, 0x77, 0x72, 0x3b, 0x13, 0xfc, 0x55, 0x43, 0x70, 0x29, 0xd5, 0x41, 0xed, 0x31, 0x4b, 0x2d, 0x6c, 0x7d, 0xcf, 0x99, 0x5f, 0xd1, 0x72, 0x9f, 0x8b, 0x32, 0x96, 0xde, 0x5d, 0x8b, 0x19, 0x77, 0x75, 0xff, 0x09, 0xbf, 0x26, 0xe9, 0xd7, 0x3d, 0xc7, 0x1a, 0x81, 0xcf, 0x05, 0x1b, 0x89, 0xbf, 0x45, 0x32, 0xbf, 0x5e, 0xc9, 0xe3, 0x5c, 0x33, 0x4a, 0x72, 0x47, 0xf4, 0x24, 0xae, 0x9b, 0x38, 0x24, 0x76, 0x9a, 0xa2, 0x9a, 0x50, 0x50, 0x49, 0xf5, 0x26, 0xb9, 0x55, 0xa6, 0x47, 0xc9, 0x14, 0xa2, 0xca, 0xd4, 0xa8, 0x8a, 0x9f, 0xe9, 0x5a, 0x5a, 0x12, 0xaa, 0x30, 0xd5, 0x78, 0x8b, 0x39, 0x02, 0x03, 0x01, 0x00, 0x01, };
./openssl/demos/digest/EVP_MD_xof.c
/*- * Copyright 2022-2023 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <stdio.h> #include <string.h> #include <openssl/err.h> #include <openssl/evp.h> #include <openssl/core_names.h> /* * Example of using an extendable-output hash function (XOF). A XOF is a hash * function with configurable output length and which can generate an * arbitrarily large output. * * This example uses SHAKE256, an extendable output variant of SHA3 (Keccak). * * To generate different output lengths, you can pass a single integer argument * on the command line, which is the output size in bytes. By default, a 20-byte * output is generated and (for this length only) a known answer test is * performed. */ /* Our input to the XOF hash function. */ const char message[] = "This is a test message."; /* Expected output when an output length of 20 bytes is used. */ static const char known_answer[] = { 0x52, 0x97, 0x93, 0x78, 0x27, 0x58, 0x7d, 0x62, 0x8b, 0x00, 0x25, 0xb5, 0xec, 0x39, 0x5e, 0x2d, 0x7f, 0x3e, 0xd4, 0x19 }; /* * A property query used for selecting the SHAKE256 implementation. */ static const char *propq = NULL; int main(int argc, char **argv) { int ret = EXIT_FAILURE; OSSL_LIB_CTX *libctx = NULL; EVP_MD *md = NULL; EVP_MD_CTX *ctx = NULL; unsigned int digest_len = 20; int digest_len_i; unsigned char *digest = NULL; /* Allow digest length to be changed for demonstration purposes. */ if (argc > 1) { digest_len_i = atoi(argv[1]); if (digest_len_i <= 0) { fprintf(stderr, "Specify a non-negative digest length\n"); goto end; } digest_len = (unsigned int)digest_len_i; } /* * Retrieve desired algorithm. This must be a hash algorithm which supports * XOF. */ md = EVP_MD_fetch(libctx, "SHAKE256", propq); if (md == NULL) { fprintf(stderr, "Failed to retrieve SHAKE256 algorithm\n"); goto end; } /* Create context. */ ctx = EVP_MD_CTX_new(); if (ctx == NULL) { fprintf(stderr, "Failed to create digest context\n"); goto end; } /* Initialize digest context. */ if (EVP_DigestInit(ctx, md) == 0) { fprintf(stderr, "Failed to initialize digest\n"); goto end; } /* * Feed our message into the digest function. * This may be called multiple times. */ if (EVP_DigestUpdate(ctx, message, sizeof(message)) == 0) { fprintf(stderr, "Failed to hash input message\n"); goto end; } /* Allocate enough memory for our digest length. */ digest = OPENSSL_malloc(digest_len); if (digest == NULL) { fprintf(stderr, "Failed to allocate memory for digest\n"); goto end; } /* Get computed digest. The digest will be of whatever length we specify. */ if (EVP_DigestFinalXOF(ctx, digest, digest_len) == 0) { fprintf(stderr, "Failed to finalize hash\n"); goto end; } printf("Output digest:\n"); BIO_dump_indent_fp(stdout, digest, digest_len, 2); /* If digest length is 20 bytes, check it matches our known answer. */ if (digest_len == 20) { /* * Always use a constant-time function such as CRYPTO_memcmp * when comparing cryptographic values. Do not use memcmp(3). */ if (CRYPTO_memcmp(digest, known_answer, sizeof(known_answer)) != 0) { fprintf(stderr, "Output does not match expected result\n"); goto end; } } ret = EXIT_SUCCESS; end: OPENSSL_free(digest); EVP_MD_CTX_free(ctx); EVP_MD_free(md); OSSL_LIB_CTX_free(libctx); return ret; }
./openssl/demos/digest/EVP_MD_stdin.c
/*- * Copyright 2019-2023 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ /*- * Example of using EVP_MD_fetch and EVP_Digest* methods to calculate * a digest of static buffers * You can find SHA3 test vectors from NIST here: * https://csrc.nist.gov/CSRC/media/Projects/Cryptographic-Algorithm-Validation-Program/documents/sha3/sha-3bytetestvectors.zip * For example, contains these lines: Len = 80 Msg = 1ca984dcc913344370cf MD = 6915ea0eeffb99b9b246a0e34daf3947852684c3d618260119a22835659e4f23d4eb66a15d0affb8e93771578f5e8f25b7a5f2a55f511fb8b96325ba2cd14816 * use xxd convert the hex message string to binary input for EVP_MD_stdin: * echo "1ca984dcc913344370cf" | xxd -r -p | ./EVP_MD_stdin * and then verify the output matches MD above. */ #include <string.h> #include <stdio.h> #include <openssl/err.h> #include <openssl/evp.h> /*- * This demonstration will show how to digest data using * a BIO created to read from stdin */ int demonstrate_digest(BIO *input) { OSSL_LIB_CTX *library_context = NULL; int ret = 0; const char *option_properties = NULL; EVP_MD *message_digest = NULL; EVP_MD_CTX *digest_context = NULL; unsigned int digest_length; unsigned char *digest_value = NULL; unsigned char buffer[512]; int ii; library_context = OSSL_LIB_CTX_new(); if (library_context == NULL) { fprintf(stderr, "OSSL_LIB_CTX_new() returned NULL\n"); goto cleanup; } /* * Fetch a message digest by name * The algorithm name is case insensitive. * See providers(7) for details about algorithm fetching */ message_digest = EVP_MD_fetch(library_context, "SHA3-512", option_properties); if (message_digest == NULL) { fprintf(stderr, "EVP_MD_fetch could not find SHA3-512."); ERR_print_errors_fp(stderr); OSSL_LIB_CTX_free(library_context); return 0; } /* Determine the length of the fetched digest type */ digest_length = EVP_MD_get_size(message_digest); if (digest_length <= 0) { fprintf(stderr, "EVP_MD_get_size returned invalid size.\n"); goto cleanup; } digest_value = OPENSSL_malloc(digest_length); if (digest_value == NULL) { fprintf(stderr, "No memory.\n"); goto cleanup; } /* * Make a message digest context to hold temporary state * during digest creation */ digest_context = EVP_MD_CTX_new(); if (digest_context == NULL) { fprintf(stderr, "EVP_MD_CTX_new failed.\n"); ERR_print_errors_fp(stderr); goto cleanup; } /* * Initialize the message digest context to use the fetched * digest provider */ if (EVP_DigestInit(digest_context, message_digest) != 1) { fprintf(stderr, "EVP_DigestInit failed.\n"); ERR_print_errors_fp(stderr); goto cleanup; } while ((ii = BIO_read(input, buffer, sizeof(buffer))) > 0) { if (EVP_DigestUpdate(digest_context, buffer, ii) != 1) { fprintf(stderr, "EVP_DigestUpdate() failed.\n"); goto cleanup; } } if (EVP_DigestFinal(digest_context, digest_value, &digest_length) != 1) { fprintf(stderr, "EVP_DigestFinal() failed.\n"); goto cleanup; } ret = 1; for (ii=0; ii<digest_length; ii++) { fprintf(stdout, "%02x", digest_value[ii]); } fprintf(stdout, "\n"); cleanup: if (ret != 1) ERR_print_errors_fp(stderr); /* OpenSSL free functions will ignore NULL arguments */ EVP_MD_CTX_free(digest_context); OPENSSL_free(digest_value); EVP_MD_free(message_digest); OSSL_LIB_CTX_free(library_context); return ret; } int main(void) { int ret = EXIT_FAILURE; BIO *input = BIO_new_fd(fileno(stdin), 1); if (input != NULL) { ret = (demonstrate_digest(input) ? EXIT_SUCCESS : EXIT_FAILURE); BIO_free(input); } if (ret != EXIT_SUCCESS) ERR_print_errors_fp(stderr); return ret; }
./openssl/demos/digest/BIO_f_md.c
/*- * Copyright 2019-2023 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ /*- * Example of using EVP_MD_fetch and EVP_Digest* methods to calculate * a digest of static buffers * You can find SHA3 test vectors from NIST here: * https://csrc.nist.gov/CSRC/media/Projects/Cryptographic-Algorithm-Validation-Program/documents/sha3/sha-3bytetestvectors.zip * For example, contains these lines: Len = 80 Msg = 1ca984dcc913344370cf MD = 6915ea0eeffb99b9b246a0e34daf3947852684c3d618260119a22835659e4f23d4eb66a15d0affb8e93771578f5e8f25b7a5f2a55f511fb8b96325ba2cd14816 * use xxd convert the hex message string to binary input for BIO_f_md: * echo "1ca984dcc913344370cf" | xxd -r -p | ./BIO_f_md * and then verify the output matches MD above. */ #include <string.h> #include <stdio.h> #include <openssl/err.h> #include <openssl/bio.h> #include <openssl/evp.h> /*- * This demonstration will show how to digest data using * a BIO configured with a message digest * A message digest name may be passed as an argument. * The default digest is SHA3-512 */ int main(int argc, char *argv[]) { int ret = EXIT_FAILURE; OSSL_LIB_CTX *library_context = NULL; BIO *input = NULL; BIO *bio_digest = NULL, *reading = NULL; EVP_MD *md = NULL; unsigned char buffer[512]; size_t digest_size; char *digest_value = NULL; int j; input = BIO_new_fd(fileno(stdin), 1); if (input == NULL) { fprintf(stderr, "BIO_new_fd() for stdin returned NULL\n"); goto cleanup; } library_context = OSSL_LIB_CTX_new(); if (library_context == NULL) { fprintf(stderr, "OSSL_LIB_CTX_new() returned NULL\n"); goto cleanup; } /* * Fetch a message digest by name * The algorithm name is case insensitive. * See providers(7) for details about algorithm fetching */ md = EVP_MD_fetch(library_context, "SHA3-512", NULL); if (md == NULL) { fprintf(stderr, "EVP_MD_fetch did not find SHA3-512.\n"); goto cleanup; } digest_size = EVP_MD_get_size(md); digest_value = OPENSSL_malloc(digest_size); if (digest_value == NULL) { fprintf(stderr, "Can't allocate %lu bytes for the digest value.\n", (unsigned long)digest_size); goto cleanup; } /* Make a bio that uses the digest */ bio_digest = BIO_new(BIO_f_md()); if (bio_digest == NULL) { fprintf(stderr, "BIO_new(BIO_f_md()) returned NULL\n"); goto cleanup; } /* set our bio_digest BIO to digest data */ if (BIO_set_md(bio_digest, md) != 1) { fprintf(stderr, "BIO_set_md failed.\n"); goto cleanup; } /*- * We will use BIO chaining so that as we read, the digest gets updated * See the man page for BIO_push */ reading = BIO_push(bio_digest, input); while (BIO_read(reading, buffer, sizeof(buffer)) > 0) ; /*- * BIO_gets must be used to calculate the final * digest value and then copy it to digest_value. */ if (BIO_gets(bio_digest, digest_value, digest_size) != digest_size) { fprintf(stderr, "BIO_gets(bio_digest) failed\n"); goto cleanup; } for (j = 0; j < digest_size; j++) { fprintf(stdout, "%02x", (unsigned char)digest_value[j]); } fprintf(stdout, "\n"); ret = EXIT_SUCCESS; cleanup: if (ret != EXIT_SUCCESS) ERR_print_errors_fp(stderr); OPENSSL_free(digest_value); BIO_free(input); BIO_free(bio_digest); EVP_MD_free(md); OSSL_LIB_CTX_free(library_context); return ret; }
./openssl/demos/digest/EVP_MD_demo.c
/*- * Copyright 2021-2023 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ /* * Example of using EVP_MD_fetch and EVP_Digest* methods to calculate * a digest of static buffers */ #include <string.h> #include <stdio.h> #include <openssl/err.h> #include <openssl/evp.h> /*- * This demonstration will show how to digest data using * the soliloqy from Hamlet scene 1 act 3 * The soliloqy is split into two parts to demonstrate using EVP_DigestUpdate * more than once. */ const char *hamlet_1 = "To be, or not to be, that is the question,\n" "Whether tis nobler in the minde to suffer\n" "The ſlings and arrowes of outragious fortune,\n" "Or to take Armes again in a sea of troubles,\n" "And by opposing, end them, to die to sleep;\n" "No more, and by a sleep, to say we end\n" "The heart-ache, and the thousand natural shocks\n" "That flesh is heir to? tis a consumation\n" "Devoutly to be wished. To die to sleep,\n" "To sleepe, perchance to dreame, Aye, there's the rub,\n" "For in that sleep of death what dreams may come\n" "When we haue shuffled off this mortal coil\n" "Must give us pause. There's the respect\n" "That makes calamity of so long life:\n" "For who would bear the Ships and Scorns of time,\n" "The oppressor's wrong, the proud man's Contumely,\n" "The pangs of dispised love, the Law's delay,\n" ; const char *hamlet_2 = "The insolence of Office, and the spurns\n" "That patient merit of the'unworthy takes,\n" "When he himself might his Quietas make\n" "With a bare bodkin? Who would fardels bear,\n" "To grunt and sweat under a weary life,\n" "But that the dread of something after death,\n" "The undiscovered country, from whose bourn\n" "No traveller returns, puzzles the will,\n" "And makes us rather bear those ills we have,\n" "Then fly to others we know not of?\n" "Thus conscience does make cowards of us all,\n" "And thus the native hue of Resolution\n" "Is sickled o'er with the pale cast of Thought,\n" "And enterprises of great pith and moment,\n" "With this regard their currents turn awry,\n" "And lose the name of Action. Soft you now,\n" "The fair Ophelia? Nymph in thy Orisons\n" "Be all my sins remember'd.\n" ; /* The known value of the SHA3-512 digest of the above soliloqy */ const unsigned char known_answer[] = { 0xbb, 0x69, 0xf8, 0x09, 0x9c, 0x2e, 0x00, 0x3d, 0xa4, 0x29, 0x5f, 0x59, 0x4b, 0x89, 0xe4, 0xd9, 0xdb, 0xa2, 0xe5, 0xaf, 0xa5, 0x87, 0x73, 0x9d, 0x83, 0x72, 0xcf, 0xea, 0x84, 0x66, 0xc1, 0xf9, 0xc9, 0x78, 0xef, 0xba, 0x3d, 0xe9, 0xc1, 0xff, 0xa3, 0x75, 0xc7, 0x58, 0x74, 0x8e, 0x9c, 0x1d, 0x14, 0xd9, 0xdd, 0xd1, 0xfd, 0x24, 0x30, 0xd6, 0x81, 0xca, 0x8f, 0x78, 0x29, 0x19, 0x9a, 0xfe, }; int demonstrate_digest(void) { OSSL_LIB_CTX *library_context; int ret = 0; const char *option_properties = NULL; EVP_MD *message_digest = NULL; EVP_MD_CTX *digest_context = NULL; unsigned int digest_length; unsigned char *digest_value = NULL; int j; library_context = OSSL_LIB_CTX_new(); if (library_context == NULL) { fprintf(stderr, "OSSL_LIB_CTX_new() returned NULL\n"); goto cleanup; } /* * Fetch a message digest by name * The algorithm name is case insensitive. * See providers(7) for details about algorithm fetching */ message_digest = EVP_MD_fetch(library_context, "SHA3-512", option_properties); if (message_digest == NULL) { fprintf(stderr, "EVP_MD_fetch could not find SHA3-512."); goto cleanup; } /* Determine the length of the fetched digest type */ digest_length = EVP_MD_get_size(message_digest); if (digest_length <= 0) { fprintf(stderr, "EVP_MD_get_size returned invalid size.\n"); goto cleanup; } digest_value = OPENSSL_malloc(digest_length); if (digest_value == NULL) { fprintf(stderr, "No memory.\n"); goto cleanup; } /* * Make a message digest context to hold temporary state * during digest creation */ digest_context = EVP_MD_CTX_new(); if (digest_context == NULL) { fprintf(stderr, "EVP_MD_CTX_new failed.\n"); goto cleanup; } /* * Initialize the message digest context to use the fetched * digest provider */ if (EVP_DigestInit(digest_context, message_digest) != 1) { fprintf(stderr, "EVP_DigestInit failed.\n"); goto cleanup; } /* Digest parts one and two of the soliloqy */ if (EVP_DigestUpdate(digest_context, hamlet_1, strlen(hamlet_1)) != 1) { fprintf(stderr, "EVP_DigestUpdate(hamlet_1) failed.\n"); goto cleanup; } if (EVP_DigestUpdate(digest_context, hamlet_2, strlen(hamlet_2)) != 1) { fprintf(stderr, "EVP_DigestUpdate(hamlet_2) failed.\n"); goto cleanup; } if (EVP_DigestFinal(digest_context, digest_value, &digest_length) != 1) { fprintf(stderr, "EVP_DigestFinal() failed.\n"); goto cleanup; } for (j=0; j<digest_length; j++) { fprintf(stdout, "%02x", digest_value[j]); } fprintf(stdout, "\n"); /* Check digest_value against the known answer */ if ((size_t)digest_length != sizeof(known_answer)) { fprintf(stdout, "Digest length(%d) not equal to known answer length(%lu).\n", digest_length, sizeof(known_answer)); } else if (memcmp(digest_value, known_answer, digest_length) != 0) { for (j=0; j<sizeof(known_answer); j++) { fprintf(stdout, "%02x", known_answer[j] ); } fprintf(stdout, "\nDigest does not match known answer\n"); } else { fprintf(stdout, "Digest computed properly.\n"); ret = 1; } cleanup: if (ret != 1) ERR_print_errors_fp(stderr); /* OpenSSL free functions will ignore NULL arguments */ EVP_MD_CTX_free(digest_context); OPENSSL_free(digest_value); EVP_MD_free(message_digest); OSSL_LIB_CTX_free(library_context); return ret; } int main(void) { return demonstrate_digest() ? EXIT_SUCCESS : EXIT_FAILURE; }
./openssl/test/quic_txp_test.c
/* * Copyright 2022-2023 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include "internal/packet.h" #include "internal/quic_txp.h" #include "internal/quic_statm.h" #include "internal/quic_demux.h" #include "internal/quic_record_rx.h" #include "testutil.h" #include "quic_record_test_util.h" static const QUIC_CONN_ID scid_1 = { 1, { 0x5f } }; static const QUIC_CONN_ID dcid_1 = { 8, { 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, 0xa8 } }; static const QUIC_CONN_ID cid_1 = { 8, { 0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7, 0xb8 } }; static const unsigned char reset_token_1[16] = { 0x99, 0x88, 0x77, 0x66, 0x55, 0x44, 0x33, 0x22, 0x11, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff, 0x12, }; static const unsigned char secret_1[32] = { 0x01 }; static OSSL_TIME fake_now(void *arg) { return ossl_time_now(); /* TODO */ } struct helper { OSSL_QUIC_TX_PACKETISER *txp; OSSL_QUIC_TX_PACKETISER_ARGS args; OSSL_QTX_ARGS qtx_args; BIO *bio1, *bio2; QUIC_TXFC conn_txfc; QUIC_RXFC conn_rxfc, stream_rxfc; QUIC_RXFC max_streams_bidi_rxfc, max_streams_uni_rxfc; OSSL_STATM statm; OSSL_CC_DATA *cc_data; const OSSL_CC_METHOD *cc_method; QUIC_STREAM_MAP qsm; char have_statm, have_qsm; QUIC_DEMUX *demux; OSSL_QRX *qrx; OSSL_QRX_ARGS qrx_args; OSSL_QRX_PKT *qrx_pkt; PACKET pkt; uint64_t frame_type; union { uint64_t max_data; OSSL_QUIC_FRAME_NEW_CONN_ID new_conn_id; OSSL_QUIC_FRAME_ACK ack; struct { const unsigned char *token; size_t token_len; } new_token; OSSL_QUIC_FRAME_CRYPTO crypto; OSSL_QUIC_FRAME_STREAM stream; OSSL_QUIC_FRAME_STOP_SENDING stop_sending; OSSL_QUIC_FRAME_RESET_STREAM reset_stream; OSSL_QUIC_FRAME_CONN_CLOSE conn_close; } frame; OSSL_QUIC_ACK_RANGE ack_ranges[16]; }; static void helper_cleanup(struct helper *h) { size_t i; uint32_t pn_space; ossl_qrx_pkt_release(h->qrx_pkt); h->qrx_pkt = NULL; for (pn_space = QUIC_PN_SPACE_INITIAL; pn_space < QUIC_PN_SPACE_NUM; ++pn_space) ossl_ackm_on_pkt_space_discarded(h->args.ackm, pn_space); ossl_quic_tx_packetiser_free(h->txp); ossl_qtx_free(h->args.qtx); ossl_quic_txpim_free(h->args.txpim); ossl_quic_cfq_free(h->args.cfq); if (h->cc_data != NULL) h->cc_method->free(h->cc_data); if (h->have_statm) ossl_statm_destroy(&h->statm); if (h->have_qsm) ossl_quic_stream_map_cleanup(&h->qsm); for (i = 0; i < QUIC_PN_SPACE_NUM; ++i) ossl_quic_sstream_free(h->args.crypto[i]); ossl_ackm_free(h->args.ackm); ossl_qrx_free(h->qrx); ossl_quic_demux_free(h->demux); BIO_free(h->bio1); BIO_free(h->bio2); } static void demux_default_handler(QUIC_URXE *e, void *arg, const QUIC_CONN_ID *dcid) { struct helper *h = arg; if (dcid == NULL || !ossl_quic_conn_id_eq(dcid, &dcid_1)) return; ossl_qrx_inject_urxe(h->qrx, e); } static int helper_init(struct helper *h) { int rc = 0; size_t i; memset(h, 0, sizeof(*h)); /* Initialisation */ if (!TEST_true(BIO_new_bio_dgram_pair(&h->bio1, 0, &h->bio2, 0))) goto err; h->qtx_args.bio = h->bio1; h->qtx_args.mdpl = 1200; if (!TEST_ptr(h->args.qtx = ossl_qtx_new(&h->qtx_args))) goto err; if (!TEST_ptr(h->args.txpim = ossl_quic_txpim_new())) goto err; if (!TEST_ptr(h->args.cfq = ossl_quic_cfq_new())) goto err; if (!TEST_true(ossl_quic_txfc_init(&h->conn_txfc, NULL))) goto err; if (!TEST_true(ossl_quic_rxfc_init(&h->conn_rxfc, NULL, 2 * 1024 * 1024, 10 * 1024 * 1024, fake_now, NULL))) goto err; if (!TEST_true(ossl_quic_rxfc_init(&h->stream_rxfc, &h->conn_rxfc, 1 * 1024 * 1024, 5 * 1024 * 1024, fake_now, NULL))) goto err; if (!TEST_true(ossl_quic_rxfc_init(&h->max_streams_bidi_rxfc, NULL, 100, 100, fake_now, NULL))) goto err; if (!TEST_true(ossl_quic_rxfc_init(&h->max_streams_uni_rxfc, NULL, 100, 100, fake_now, NULL))) if (!TEST_true(ossl_statm_init(&h->statm))) goto err; h->have_statm = 1; h->cc_method = &ossl_cc_dummy_method; if (!TEST_ptr(h->cc_data = h->cc_method->new(fake_now, NULL))) goto err; if (!TEST_ptr(h->args.ackm = ossl_ackm_new(fake_now, NULL, &h->statm, h->cc_method, h->cc_data))) goto err; if (!TEST_true(ossl_quic_stream_map_init(&h->qsm, NULL, NULL, &h->max_streams_bidi_rxfc, &h->max_streams_uni_rxfc, /*is_server=*/0))) goto err; h->have_qsm = 1; for (i = 0; i < QUIC_PN_SPACE_NUM; ++i) if (!TEST_ptr(h->args.crypto[i] = ossl_quic_sstream_new(4096))) goto err; h->args.cur_scid = scid_1; h->args.cur_dcid = dcid_1; h->args.qsm = &h->qsm; h->args.conn_txfc = &h->conn_txfc; h->args.conn_rxfc = &h->conn_rxfc; h->args.max_streams_bidi_rxfc = &h->max_streams_bidi_rxfc; h->args.max_streams_uni_rxfc = &h->max_streams_uni_rxfc; h->args.cc_method = h->cc_method; h->args.cc_data = h->cc_data; h->args.now = fake_now; if (!TEST_ptr(h->txp = ossl_quic_tx_packetiser_new(&h->args))) goto err; if (!TEST_ptr(h->demux = ossl_quic_demux_new(h->bio2, 8, fake_now, NULL))) goto err; ossl_quic_demux_set_default_handler(h->demux, demux_default_handler, h); h->qrx_args.demux = h->demux; h->qrx_args.short_conn_id_len = 8; h->qrx_args.max_deferred = 32; if (!TEST_ptr(h->qrx = ossl_qrx_new(&h->qrx_args))) goto err; ossl_qrx_allow_1rtt_processing(h->qrx); rc = 1; err: if (!rc) helper_cleanup(h); return rc; } #define OPK_END 0 /* End of Script */ #define OPK_TXP_GENERATE 1 /* Call generate, expect packet output */ #define OPK_TXP_GENERATE_NONE 2 /* Call generate, expect no packet output */ #define OPK_RX_PKT 3 /* Receive, expect packet */ #define OPK_RX_PKT_NONE 4 /* Receive, expect no packet */ #define OPK_EXPECT_DGRAM_LEN 5 /* Expect received datagram length in range */ #define OPK_EXPECT_FRAME 6 /* Expect next frame is of type */ #define OPK_EXPECT_INITIAL_TOKEN 7 /* Expect initial token buffer match */ #define OPK_EXPECT_HDR 8 /* Expect header structure match */ #define OPK_CHECK 9 /* Call check function */ #define OPK_NEXT_FRAME 10 /* Next frame */ #define OPK_EXPECT_NO_FRAME 11 /* Expect no further frames */ #define OPK_PROVIDE_SECRET 12 /* Provide secret to QTX and QRX */ #define OPK_DISCARD_EL 13 /* Discard QTX EL */ #define OPK_CRYPTO_SEND 14 /* Push data into crypto send stream */ #define OPK_STREAM_NEW 15 /* Create new application stream */ #define OPK_STREAM_SEND 16 /* Push data into application send stream */ #define OPK_STREAM_FIN 17 /* Mark stream as finished */ #define OPK_STOP_SENDING 18 /* Mark stream for STOP_SENDING */ #define OPK_RESET_STREAM 19 /* Mark stream for RESET_STREAM */ #define OPK_CONN_TXFC_BUMP 20 /* Bump connection TXFC CWM */ #define OPK_STREAM_TXFC_BUMP 21 /* Bump stream TXFC CWM */ #define OPK_HANDSHAKE_COMPLETE 22 /* Mark handshake as complete */ #define OPK_NOP 23 /* No-op */ struct script_op { uint32_t opcode; uint64_t arg0, arg1; const void *buf; size_t buf_len; int (*check_func)(struct helper *h); }; #define OP_END \ { OPK_END } #define OP_TXP_GENERATE() \ { OPK_TXP_GENERATE }, #define OP_TXP_GENERATE_NONE() \ { OPK_TXP_GENERATE_NONE }, #define OP_RX_PKT() \ { OPK_RX_PKT }, #define OP_RX_PKT_NONE() \ { OPK_RX_PKT_NONE }, #define OP_EXPECT_DGRAM_LEN(lo, hi) \ { OPK_EXPECT_DGRAM_LEN, (lo), (hi) }, #define OP_EXPECT_FRAME(frame_type) \ { OPK_EXPECT_FRAME, (frame_type) }, #define OP_EXPECT_INITIAL_TOKEN(buf) \ { OPK_EXPECT_INITIAL_TOKEN, sizeof(buf), 0, buf }, #define OP_EXPECT_HDR(hdr) \ { OPK_EXPECT_HDR, 0, 0, &(hdr) }, #define OP_CHECK(func) \ { OPK_CHECK, 0, 0, NULL, 0, (func) }, #define OP_NEXT_FRAME() \ { OPK_NEXT_FRAME }, #define OP_EXPECT_NO_FRAME() \ { OPK_EXPECT_NO_FRAME }, #define OP_PROVIDE_SECRET(el, suite, secret) \ { OPK_PROVIDE_SECRET, (el), (suite), (secret), sizeof(secret) }, #define OP_DISCARD_EL(el) \ { OPK_DISCARD_EL, (el) }, #define OP_CRYPTO_SEND(pn_space, buf) \ { OPK_CRYPTO_SEND, (pn_space), 0, (buf), sizeof(buf) }, #define OP_STREAM_NEW(id) \ { OPK_STREAM_NEW, (id) }, #define OP_STREAM_SEND(id, buf) \ { OPK_STREAM_SEND, (id), 0, (buf), sizeof(buf) }, #define OP_STREAM_FIN(id) \ { OPK_STREAM_FIN, (id) }, #define OP_STOP_SENDING(id, aec) \ { OPK_STOP_SENDING, (id), (aec) }, #define OP_RESET_STREAM(id, aec) \ { OPK_RESET_STREAM, (id), (aec) }, #define OP_CONN_TXFC_BUMP(cwm) \ { OPK_CONN_TXFC_BUMP, (cwm) }, #define OP_STREAM_TXFC_BUMP(id, cwm) \ { OPK_STREAM_TXFC_BUMP, (cwm), (id) }, #define OP_HANDSHAKE_COMPLETE() \ { OPK_HANDSHAKE_COMPLETE }, #define OP_NOP() \ { OPK_NOP }, static int schedule_handshake_done(struct helper *h) { ossl_quic_tx_packetiser_schedule_handshake_done(h->txp); return 1; } static int schedule_ack_eliciting_app(struct helper *h) { ossl_quic_tx_packetiser_schedule_ack_eliciting(h->txp, QUIC_PN_SPACE_APP); return 1; } /* 1. 1-RTT, Single Handshake Done Frame */ static const struct script_op script_1[] = { OP_PROVIDE_SECRET(QUIC_ENC_LEVEL_1RTT, QRL_SUITE_AES128GCM, secret_1) OP_TXP_GENERATE_NONE() OP_CHECK(schedule_handshake_done) OP_TXP_GENERATE() OP_RX_PKT() /* Should not be long */ OP_EXPECT_DGRAM_LEN(21, 32) OP_NEXT_FRAME() OP_EXPECT_FRAME(OSSL_QUIC_FRAME_TYPE_HANDSHAKE_DONE) OP_EXPECT_NO_FRAME() OP_RX_PKT_NONE() OP_TXP_GENERATE_NONE() OP_END }; /* 2. 1-RTT, Forced ACK-Eliciting Frame */ static const struct script_op script_2[] = { OP_PROVIDE_SECRET(QUIC_ENC_LEVEL_1RTT, QRL_SUITE_AES128GCM, secret_1) OP_TXP_GENERATE_NONE() OP_CHECK(schedule_ack_eliciting_app) OP_TXP_GENERATE() OP_RX_PKT() /* Should not be long */ OP_EXPECT_DGRAM_LEN(21, 32) /* A PING frame should have been added */ OP_NEXT_FRAME() OP_EXPECT_FRAME(OSSL_QUIC_FRAME_TYPE_PING) OP_EXPECT_NO_FRAME() OP_RX_PKT_NONE() OP_TXP_GENERATE_NONE() OP_END }; /* 3. 1-RTT, MAX_DATA */ static int schedule_max_data(struct helper *h) { uint64_t cwm; cwm = ossl_quic_rxfc_get_cwm(&h->stream_rxfc); if (!TEST_true(ossl_quic_rxfc_on_rx_stream_frame(&h->stream_rxfc, cwm, 0)) || !TEST_true(ossl_quic_rxfc_on_retire(&h->stream_rxfc, cwm, ossl_ticks2time(OSSL_TIME_MS)))) return 0; return 1; } static const struct script_op script_3[] = { OP_PROVIDE_SECRET(QUIC_ENC_LEVEL_1RTT, QRL_SUITE_AES128GCM, secret_1) OP_TXP_GENERATE_NONE() OP_CHECK(schedule_max_data) OP_TXP_GENERATE() OP_RX_PKT() /* Should not be long */ OP_EXPECT_DGRAM_LEN(21, 40) /* A PING frame should have been added */ OP_NEXT_FRAME() OP_EXPECT_FRAME(OSSL_QUIC_FRAME_TYPE_MAX_DATA) OP_EXPECT_NO_FRAME() OP_RX_PKT_NONE() OP_TXP_GENERATE_NONE() OP_END }; /* 4. 1-RTT, CFQ (NEW_CONN_ID) */ static void free_buf_mem(unsigned char *buf, size_t buf_len, void *arg) { BUF_MEM_free((BUF_MEM *)arg); } static int schedule_cfq_new_conn_id(struct helper *h) { int rc = 0; QUIC_CFQ_ITEM *cfq_item; WPACKET wpkt; BUF_MEM *buf_mem = NULL; size_t l = 0; OSSL_QUIC_FRAME_NEW_CONN_ID ncid = {0}; ncid.seq_num = 2345; ncid.retire_prior_to = 1234; ncid.conn_id = cid_1; memcpy(ncid.stateless_reset.token, reset_token_1, sizeof(reset_token_1)); if (!TEST_ptr(buf_mem = BUF_MEM_new())) goto err; if (!TEST_true(WPACKET_init(&wpkt, buf_mem))) goto err; if (!TEST_true(ossl_quic_wire_encode_frame_new_conn_id(&wpkt, &ncid))) { WPACKET_cleanup(&wpkt); goto err; } WPACKET_finish(&wpkt); if (!TEST_true(WPACKET_get_total_written(&wpkt, &l))) goto err; if (!TEST_ptr(cfq_item = ossl_quic_cfq_add_frame(h->args.cfq, 1, QUIC_PN_SPACE_APP, OSSL_QUIC_FRAME_TYPE_NEW_CONN_ID, 0, (unsigned char *)buf_mem->data, l, free_buf_mem, buf_mem))) goto err; rc = 1; err: if (!rc) BUF_MEM_free(buf_mem); return rc; } static int check_cfq_new_conn_id(struct helper *h) { if (!TEST_uint64_t_eq(h->frame.new_conn_id.seq_num, 2345) || !TEST_uint64_t_eq(h->frame.new_conn_id.retire_prior_to, 1234) || !TEST_mem_eq(&h->frame.new_conn_id.conn_id, sizeof(cid_1), &cid_1, sizeof(cid_1)) || !TEST_mem_eq(&h->frame.new_conn_id.stateless_reset.token, sizeof(reset_token_1), reset_token_1, sizeof(reset_token_1))) return 0; return 1; } static const struct script_op script_4[] = { OP_PROVIDE_SECRET(QUIC_ENC_LEVEL_1RTT, QRL_SUITE_AES128GCM, secret_1) OP_TXP_GENERATE_NONE() OP_CHECK(schedule_cfq_new_conn_id) OP_TXP_GENERATE() OP_RX_PKT() OP_EXPECT_DGRAM_LEN(21, 128) OP_NEXT_FRAME() OP_EXPECT_FRAME(OSSL_QUIC_FRAME_TYPE_NEW_CONN_ID) OP_CHECK(check_cfq_new_conn_id) OP_EXPECT_NO_FRAME() OP_RX_PKT_NONE() OP_TXP_GENERATE_NONE() OP_END }; /* 5. 1-RTT, CFQ (NEW_TOKEN) */ static const unsigned char token_1[] = { 0x10, 0x11, 0x12, 0x13, 0x14, 0x15 }; static int schedule_cfq_new_token(struct helper *h) { int rc = 0; QUIC_CFQ_ITEM *cfq_item; WPACKET wpkt; BUF_MEM *buf_mem = NULL; size_t l = 0; if (!TEST_ptr(buf_mem = BUF_MEM_new())) goto err; if (!TEST_true(WPACKET_init(&wpkt, buf_mem))) goto err; if (!TEST_true(ossl_quic_wire_encode_frame_new_token(&wpkt, token_1, sizeof(token_1)))) { WPACKET_cleanup(&wpkt); goto err; } WPACKET_finish(&wpkt); if (!TEST_true(WPACKET_get_total_written(&wpkt, &l))) goto err; if (!TEST_ptr(cfq_item = ossl_quic_cfq_add_frame(h->args.cfq, 1, QUIC_PN_SPACE_APP, OSSL_QUIC_FRAME_TYPE_NEW_TOKEN, 0, (unsigned char *)buf_mem->data, l, free_buf_mem, buf_mem))) goto err; rc = 1; err: if (!rc) BUF_MEM_free(buf_mem); return rc; } static int check_cfq_new_token(struct helper *h) { if (!TEST_mem_eq(h->frame.new_token.token, h->frame.new_token.token_len, token_1, sizeof(token_1))) return 0; return 1; } static const struct script_op script_5[] = { OP_PROVIDE_SECRET(QUIC_ENC_LEVEL_1RTT, QRL_SUITE_AES128GCM, secret_1) OP_TXP_GENERATE_NONE() OP_CHECK(schedule_cfq_new_token) OP_TXP_GENERATE() OP_RX_PKT() OP_EXPECT_DGRAM_LEN(21, 512) OP_NEXT_FRAME() OP_EXPECT_FRAME(OSSL_QUIC_FRAME_TYPE_NEW_TOKEN) OP_CHECK(check_cfq_new_token) OP_EXPECT_NO_FRAME() OP_RX_PKT_NONE() OP_TXP_GENERATE_NONE() OP_END }; /* 6. 1-RTT, ACK */ static int schedule_ack(struct helper *h) { size_t i; OSSL_ACKM_RX_PKT rx_pkt = {0}; /* Stimulate ACK emission by simulating a few received packets. */ for (i = 0; i < 5; ++i) { rx_pkt.pkt_num = i; rx_pkt.time = fake_now(NULL); rx_pkt.pkt_space = QUIC_PN_SPACE_APP; rx_pkt.is_ack_eliciting = 1; if (!TEST_true(ossl_ackm_on_rx_packet(h->args.ackm, &rx_pkt))) return 0; } return 1; } static const struct script_op script_6[] = { OP_PROVIDE_SECRET(QUIC_ENC_LEVEL_1RTT, QRL_SUITE_AES128GCM, secret_1) OP_TXP_GENERATE_NONE() OP_CHECK(schedule_ack) OP_TXP_GENERATE() OP_RX_PKT() OP_EXPECT_DGRAM_LEN(21, 512) OP_NEXT_FRAME() OP_EXPECT_FRAME(OSSL_QUIC_FRAME_TYPE_ACK_WITHOUT_ECN) OP_EXPECT_NO_FRAME() OP_RX_PKT_NONE() OP_TXP_GENERATE_NONE() OP_END }; /* 7. 1-RTT, ACK, NEW_TOKEN */ static const struct script_op script_7[] = { OP_PROVIDE_SECRET(QUIC_ENC_LEVEL_1RTT, QRL_SUITE_AES128GCM, secret_1) OP_TXP_GENERATE_NONE() OP_CHECK(schedule_cfq_new_token) OP_CHECK(schedule_ack) OP_TXP_GENERATE() OP_RX_PKT() OP_EXPECT_DGRAM_LEN(21, 512) /* ACK must come before NEW_TOKEN */ OP_NEXT_FRAME() OP_EXPECT_FRAME(OSSL_QUIC_FRAME_TYPE_ACK_WITHOUT_ECN) OP_NEXT_FRAME() OP_EXPECT_FRAME(OSSL_QUIC_FRAME_TYPE_NEW_TOKEN) OP_EXPECT_NO_FRAME() OP_RX_PKT_NONE() OP_TXP_GENERATE_NONE() OP_END }; /* 8. 1-RTT, CRYPTO */ static const unsigned char crypto_1[] = { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09 }; static const struct script_op script_8[] = { OP_PROVIDE_SECRET(QUIC_ENC_LEVEL_1RTT, QRL_SUITE_AES128GCM, secret_1) OP_TXP_GENERATE_NONE() OP_CRYPTO_SEND(QUIC_PN_SPACE_APP, crypto_1) OP_TXP_GENERATE() OP_RX_PKT() OP_EXPECT_DGRAM_LEN(21, 512) OP_NEXT_FRAME() OP_EXPECT_FRAME(OSSL_QUIC_FRAME_TYPE_CRYPTO) OP_EXPECT_NO_FRAME() OP_RX_PKT_NONE() OP_TXP_GENERATE_NONE() OP_END }; /* 9. 1-RTT, STREAM */ static const unsigned char stream_9[] = { 0x7a, 0x7b, 0x7c, 0x7d, 0x7e, 0x7f, 0x7a, 0x7b }; static int check_stream_9(struct helper *h) { if (!TEST_mem_eq(h->frame.stream.data, (size_t)h->frame.stream.len, stream_9, sizeof(stream_9))) return 0; return 1; } static const struct script_op script_9[] = { OP_PROVIDE_SECRET(QUIC_ENC_LEVEL_1RTT, QRL_SUITE_AES128GCM, secret_1) OP_HANDSHAKE_COMPLETE() OP_TXP_GENERATE_NONE() OP_STREAM_NEW(42) OP_STREAM_SEND(42, stream_9) /* Still no output because of TXFC */ OP_TXP_GENERATE_NONE() /* Now grant a TXFC budget */ OP_CONN_TXFC_BUMP(1000) OP_STREAM_TXFC_BUMP(42, 1000) OP_TXP_GENERATE() OP_RX_PKT() OP_EXPECT_DGRAM_LEN(21, 512) OP_NEXT_FRAME() OP_EXPECT_FRAME(OSSL_QUIC_FRAME_TYPE_STREAM) OP_CHECK(check_stream_9) OP_EXPECT_NO_FRAME() OP_RX_PKT_NONE() OP_TXP_GENERATE_NONE() OP_END }; /* 10. 1-RTT, STREAM, round robin */ /* The data below is randomly generated data. */ static const unsigned char stream_10a[1300] = { 0x40, 0x0d, 0xb6, 0x0d, 0x25, 0x5f, 0xdd, 0xb9, 0x05, 0x79, 0xa8, 0xe3, 0x79, 0x32, 0xb2, 0xa7, 0x30, 0x6d, 0x29, 0xf6, 0xba, 0x50, 0xbe, 0x83, 0xcb, 0x56, 0xec, 0xd6, 0xc7, 0x80, 0x84, 0xa2, 0x2f, 0xeb, 0xc4, 0x37, 0x40, 0x44, 0xef, 0xd8, 0x78, 0xbb, 0x92, 0x80, 0x22, 0x33, 0xc0, 0xce, 0x33, 0x5b, 0x75, 0x8c, 0xa5, 0x1a, 0x7a, 0x2a, 0xa9, 0x88, 0xaf, 0xf6, 0x3a, 0xe2, 0x5e, 0x60, 0x52, 0x6d, 0xef, 0x7f, 0x2a, 0x9a, 0xaa, 0x17, 0x0e, 0x12, 0x51, 0x82, 0x08, 0x2f, 0x0f, 0x5b, 0xff, 0xf5, 0x7c, 0x7c, 0x89, 0x04, 0xfb, 0xa7, 0x80, 0x4e, 0xda, 0x12, 0x89, 0x01, 0x4a, 0x81, 0x84, 0x78, 0x15, 0xa9, 0x12, 0x28, 0x69, 0x4a, 0x25, 0xe5, 0x8b, 0x69, 0xc2, 0x9f, 0xb6, 0x59, 0x49, 0xe3, 0x53, 0x90, 0xef, 0xc9, 0xb8, 0x40, 0xdd, 0x62, 0x5f, 0x99, 0x68, 0xd2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x1f, 0xde, 0x86, 0x15, 0x67, 0x04, 0x9d, 0x41, 0x1f, 0xe8, 0xe1, 0x23, 0xe4, 0x56, 0xb9, 0xdb, 0x4e, 0xe4, 0x84, 0x6c, 0x63, 0x39, 0xad, 0x44, 0x6d, 0x4e, 0x28, 0xcd, 0xf6, 0xac, 0xec, 0xc2, 0xad, 0xcd, 0xc3, 0xed, 0x03, 0x63, 0x5d, 0xef, 0x1d, 0x40, 0x8d, 0x9a, 0x02, 0x67, 0x4b, 0x55, 0xb5, 0xfe, 0x75, 0xb6, 0x53, 0x34, 0x1d, 0x7b, 0x26, 0x23, 0xfe, 0xb9, 0x21, 0xd3, 0xe0, 0xa0, 0x1a, 0x85, 0xe5 }; static const unsigned char stream_10b[1300] = { 0x18, 0x00, 0xd7, 0xfb, 0x12, 0xda, 0xdb, 0x68, 0xeb, 0x38, 0x4d, 0xf6, 0xb2, 0x45, 0x74, 0x4c, 0xcc, 0xe7, 0xa7, 0xc1, 0x26, 0x84, 0x3d, 0xdf, 0x7d, 0xc5, 0xe9, 0xd4, 0x31, 0xa2, 0x51, 0x38, 0x95, 0xe2, 0x68, 0x11, 0x9d, 0xd1, 0x52, 0xb5, 0xef, 0x76, 0xe0, 0x3d, 0x11, 0x50, 0xd7, 0xb2, 0xc1, 0x7d, 0x12, 0xaf, 0x02, 0x52, 0x97, 0x03, 0xf3, 0x2e, 0x54, 0xdf, 0xa0, 0x40, 0x76, 0x52, 0x82, 0x23, 0x3c, 0xbd, 0x20, 0x6d, 0x0a, 0x6f, 0x81, 0xfc, 0x41, 0x9d, 0x2e, 0xa7, 0x2c, 0x78, 0x9c, 0xd8, 0x56, 0xb0, 0x31, 0x35, 0xc8, 0x53, 0xef, 0xf9, 0x43, 0x17, 0xc0, 0x8c, 0x2c, 0x8f, 0x4a, 0x68, 0xe8, 0x9f, 0xbd, 0x3f, 0xf2, 0x18, 0xb8, 0xe6, 0x55, 0xea, 0x2a, 0x37, 0x3e, 0xac, 0xb0, 0x75, 0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89, 0x73, 0x3a, 0xeb, 0x55, 0x15, 0xc9, 0x3d, 0xe1, 0xf8, 0xea, 0xf6, 0x11, 0x28, 0xe0, 0x80, 0x93, 0xcc, 0xba, 0xe1, 0xf1, 0x81, 0xbc, 0xa4, 0x30, 0xbc, 0x98, 0xe8, 0x9e, 0x8d, 0x17, 0x7e, 0xb7, 0xb1, 0x27, 0x6f, 0xcf, 0x9c, 0x0d, 0x1d, 0x01, 0xea, 0x45, 0xc0, 0x90, 0xda, 0x53, 0xf6, 0xde, 0xdf, 0x12, 0xa1, 0x23, 0x3d, 0x92, 0x89, 0x77, 0xa7, 0x2a, 0xe7, 0x45, 0x24, 0xdd, 0xf2, 0x17, 0x10, 0xca, 0x6e, 0x14, 0xb2, 0x77, 0x08, 0xc4, 0x18, 0xcd }; static uint64_t stream_10a_off, stream_10b_off; static int check_stream_10a(struct helper *h) { /* * Must have filled or almost filled the packet (using default MDPL of * 1200). */ if (!TEST_uint64_t_ge(h->frame.stream.len, 1150) || !TEST_uint64_t_le(h->frame.stream.len, 1200)) return 0; if (!TEST_mem_eq(h->frame.stream.data, (size_t)h->frame.stream.len, stream_10a, (size_t)h->frame.stream.len)) return 0; stream_10a_off = h->frame.stream.offset + h->frame.stream.len; return 1; } static int check_stream_10b(struct helper *h) { if (!TEST_uint64_t_ge(h->frame.stream.len, 1150) || !TEST_uint64_t_le(h->frame.stream.len, 1200)) return 0; if (!TEST_mem_eq(h->frame.stream.data, (size_t)h->frame.stream.len, stream_10b, (size_t)h->frame.stream.len)) return 0; stream_10b_off = h->frame.stream.offset + h->frame.stream.len; return 1; } static int check_stream_10c(struct helper *h) { if (!TEST_uint64_t_ge(h->frame.stream.len, 5) || !TEST_uint64_t_le(h->frame.stream.len, 200)) return 0; if (!TEST_mem_eq(h->frame.stream.data, (size_t)h->frame.stream.len, stream_10a + stream_10a_off, (size_t)h->frame.stream.len)) return 0; return 1; } static int check_stream_10d(struct helper *h) { if (!TEST_uint64_t_ge(h->frame.stream.len, 5) || !TEST_uint64_t_le(h->frame.stream.len, 200)) return 0; if (!TEST_mem_eq(h->frame.stream.data, (size_t)h->frame.stream.len, stream_10b + stream_10b_off, (size_t)h->frame.stream.len)) return 0; return 1; } static const struct script_op script_10[] = { OP_PROVIDE_SECRET(QUIC_ENC_LEVEL_1RTT, QRL_SUITE_AES128GCM, secret_1) OP_HANDSHAKE_COMPLETE() OP_TXP_GENERATE_NONE() OP_STREAM_NEW(42) OP_STREAM_NEW(43) OP_CONN_TXFC_BUMP(10000) OP_STREAM_TXFC_BUMP(42, 5000) OP_STREAM_TXFC_BUMP(43, 5000) OP_STREAM_SEND(42, stream_10a) OP_STREAM_SEND(43, stream_10b) /* First packet containing data from stream 42 */ OP_TXP_GENERATE() OP_RX_PKT() OP_EXPECT_DGRAM_LEN(1100, 1200) OP_NEXT_FRAME() OP_EXPECT_FRAME(OSSL_QUIC_FRAME_TYPE_STREAM) OP_CHECK(check_stream_10a) OP_EXPECT_NO_FRAME() /* Second packet containing data from stream 43 */ OP_TXP_GENERATE() OP_RX_PKT() OP_EXPECT_DGRAM_LEN(1100, 1200) OP_NEXT_FRAME() OP_EXPECT_FRAME(OSSL_QUIC_FRAME_TYPE_STREAM) OP_CHECK(check_stream_10b) OP_EXPECT_NO_FRAME() /* Third packet containing data from stream 42 */ OP_TXP_GENERATE() OP_RX_PKT() OP_EXPECT_DGRAM_LEN(200, 500) OP_NEXT_FRAME() OP_EXPECT_FRAME(OSSL_QUIC_FRAME_TYPE_STREAM_OFF_LEN) OP_CHECK(check_stream_10c) OP_NEXT_FRAME() OP_EXPECT_FRAME(OSSL_QUIC_FRAME_TYPE_STREAM_OFF) OP_CHECK(check_stream_10d) OP_EXPECT_NO_FRAME() OP_RX_PKT_NONE() OP_TXP_GENERATE_NONE() OP_END }; /* 11. Initial, CRYPTO */ static const struct script_op script_11[] = { OP_PROVIDE_SECRET(QUIC_ENC_LEVEL_INITIAL, QRL_SUITE_AES128GCM, secret_1) OP_TXP_GENERATE_NONE() OP_CRYPTO_SEND(QUIC_PN_SPACE_INITIAL, crypto_1) OP_TXP_GENERATE() OP_RX_PKT() OP_EXPECT_DGRAM_LEN(1200, 1200) OP_NEXT_FRAME() OP_EXPECT_FRAME(OSSL_QUIC_FRAME_TYPE_CRYPTO) OP_EXPECT_NO_FRAME() OP_RX_PKT_NONE() OP_TXP_GENERATE_NONE() OP_END }; /* 12. 1-RTT, STOP_SENDING */ static int check_stream_12(struct helper *h) { if (!TEST_uint64_t_eq(h->frame.stop_sending.stream_id, 42) || !TEST_uint64_t_eq(h->frame.stop_sending.app_error_code, 4568)) return 0; return 1; } static const struct script_op script_12[] = { OP_PROVIDE_SECRET(QUIC_ENC_LEVEL_1RTT, QRL_SUITE_AES128GCM, secret_1) OP_HANDSHAKE_COMPLETE() OP_TXP_GENERATE_NONE() OP_STREAM_NEW(42) OP_STOP_SENDING(42, 4568) OP_TXP_GENERATE() OP_RX_PKT() OP_EXPECT_DGRAM_LEN(21, 128) OP_NEXT_FRAME() OP_EXPECT_FRAME(OSSL_QUIC_FRAME_TYPE_STOP_SENDING) OP_CHECK(check_stream_12) OP_EXPECT_NO_FRAME() OP_RX_PKT_NONE() OP_TXP_GENERATE_NONE() OP_END }; /* 13. 1-RTT, RESET_STREAM */ static const unsigned char stream_13[] = { 0x7a, 0x7b, 0x7c, 0x7d, 0x7e, 0x7f, 0x7a, 0x7b }; static ossl_unused int check_stream_13(struct helper *h) { if (!TEST_uint64_t_eq(h->frame.reset_stream.stream_id, 42) || !TEST_uint64_t_eq(h->frame.reset_stream.app_error_code, 4568) || !TEST_uint64_t_eq(h->frame.reset_stream.final_size, 0)) return 0; return 1; } static const struct script_op script_13[] = { OP_PROVIDE_SECRET(QUIC_ENC_LEVEL_1RTT, QRL_SUITE_AES128GCM, secret_1) OP_HANDSHAKE_COMPLETE() OP_TXP_GENERATE_NONE() OP_STREAM_NEW(42) OP_CONN_TXFC_BUMP(8) OP_STREAM_TXFC_BUMP(42, 8) OP_STREAM_SEND(42, stream_13) OP_RESET_STREAM(42, 4568) OP_TXP_GENERATE() OP_RX_PKT() OP_EXPECT_DGRAM_LEN(21, 128) OP_NEXT_FRAME() OP_EXPECT_FRAME(OSSL_QUIC_FRAME_TYPE_RESET_STREAM) OP_CHECK(check_stream_13) OP_NEXT_FRAME() OP_EXPECT_NO_FRAME() OP_RX_PKT_NONE() OP_TXP_GENERATE_NONE() OP_END }; /* 14. 1-RTT, CONNECTION_CLOSE */ static int gen_conn_close(struct helper *h) { OSSL_QUIC_FRAME_CONN_CLOSE f = {0}; f.error_code = 2345; f.frame_type = OSSL_QUIC_FRAME_TYPE_HANDSHAKE_DONE; f.reason = "Reason string"; f.reason_len = strlen(f.reason); if (!TEST_true(ossl_quic_tx_packetiser_schedule_conn_close(h->txp, &f))) return 0; return 1; } static int check_14(struct helper *h) { if (!TEST_int_eq(h->frame.conn_close.is_app, 0) || !TEST_uint64_t_eq(h->frame.conn_close.frame_type, OSSL_QUIC_FRAME_TYPE_HANDSHAKE_DONE) || !TEST_uint64_t_eq(h->frame.conn_close.error_code, 2345) || !TEST_mem_eq(h->frame.conn_close.reason, h->frame.conn_close.reason_len, "Reason string", 13)) return 0; return 1; } static const struct script_op script_14[] = { OP_PROVIDE_SECRET(QUIC_ENC_LEVEL_1RTT, QRL_SUITE_AES128GCM, secret_1) OP_HANDSHAKE_COMPLETE() OP_TXP_GENERATE_NONE() OP_CHECK(gen_conn_close) OP_TXP_GENERATE() OP_RX_PKT() OP_EXPECT_DGRAM_LEN(21, 512) OP_NEXT_FRAME() OP_EXPECT_FRAME(OSSL_QUIC_FRAME_TYPE_CONN_CLOSE_TRANSPORT) OP_CHECK(check_14) OP_EXPECT_NO_FRAME() OP_RX_PKT_NONE() OP_END }; /* 15. INITIAL, Anti-Deadlock Probe Simulation */ static int gen_probe_initial(struct helper *h) { OSSL_ACKM_PROBE_INFO *probe = ossl_ackm_get0_probe_request(h->args.ackm); /* * Pretend the ACKM asked for an anti-deadlock Initial probe. * We test output of this in the ACKM unit tests. */ ++probe->anti_deadlock_initial; return 1; } static const struct script_op script_15[] = { OP_PROVIDE_SECRET(QUIC_ENC_LEVEL_INITIAL, QRL_SUITE_AES128GCM, secret_1) OP_TXP_GENERATE_NONE() OP_CHECK(gen_probe_initial) OP_TXP_GENERATE() OP_RX_PKT() OP_EXPECT_DGRAM_LEN(1200, 1200) OP_NEXT_FRAME() OP_EXPECT_FRAME(OSSL_QUIC_FRAME_TYPE_PING) OP_EXPECT_NO_FRAME() OP_RX_PKT_NONE() OP_TXP_GENERATE_NONE() OP_END }; /* 16. HANDSHAKE, Anti-Deadlock Probe Simulation */ static int gen_probe_handshake(struct helper *h) { OSSL_ACKM_PROBE_INFO *probe = ossl_ackm_get0_probe_request(h->args.ackm); /* * Pretend the ACKM asked for an anti-deadlock Handshake probe. * We test output of this in the ACKM unit tests. */ ++probe->anti_deadlock_handshake; return 1; } static const struct script_op script_16[] = { OP_DISCARD_EL(QUIC_ENC_LEVEL_INITIAL) OP_PROVIDE_SECRET(QUIC_ENC_LEVEL_HANDSHAKE, QRL_SUITE_AES128GCM, secret_1) OP_TXP_GENERATE_NONE() OP_CHECK(gen_probe_handshake) OP_TXP_GENERATE() OP_RX_PKT() OP_EXPECT_DGRAM_LEN(21, 512) OP_NEXT_FRAME() OP_EXPECT_FRAME(OSSL_QUIC_FRAME_TYPE_PING) OP_EXPECT_NO_FRAME() OP_RX_PKT_NONE() OP_TXP_GENERATE_NONE() OP_END }; /* 17. 1-RTT, Probe Simulation */ static int gen_probe_1rtt(struct helper *h) { OSSL_ACKM_PROBE_INFO *probe = ossl_ackm_get0_probe_request(h->args.ackm); /* * Pretend the ACKM asked for a 1-RTT PTO probe. * We test output of this in the ACKM unit tests. */ ++probe->pto[QUIC_PN_SPACE_APP]; return 1; } static const struct script_op script_17[] = { OP_DISCARD_EL(QUIC_ENC_LEVEL_INITIAL) OP_DISCARD_EL(QUIC_ENC_LEVEL_HANDSHAKE) OP_PROVIDE_SECRET(QUIC_ENC_LEVEL_1RTT, QRL_SUITE_AES128GCM, secret_1) OP_TXP_GENERATE_NONE() OP_CHECK(gen_probe_1rtt) OP_TXP_GENERATE() OP_RX_PKT() OP_EXPECT_DGRAM_LEN(21, 512) OP_NEXT_FRAME() OP_EXPECT_FRAME(OSSL_QUIC_FRAME_TYPE_PING) OP_EXPECT_NO_FRAME() OP_RX_PKT_NONE() OP_TXP_GENERATE_NONE() OP_END }; /* 18. Big Token Rejection */ static const unsigned char big_token[1950]; static int try_big_token(struct helper *h) { size_t i; /* Ensure big token is rejected */ if (!TEST_false(ossl_quic_tx_packetiser_set_initial_token(h->txp, big_token, sizeof(big_token), NULL, NULL))) return 0; /* * Keep trying until we find an acceptable size, then make sure * that works for generation */ for (i = sizeof(big_token) - 1;; --i) { if (!TEST_size_t_gt(i, 0)) return 0; if (ossl_quic_tx_packetiser_set_initial_token(h->txp, big_token, i, NULL, NULL)) break; } return 1; } static const struct script_op script_18[] = { OP_PROVIDE_SECRET(QUIC_ENC_LEVEL_INITIAL, QRL_SUITE_AES128GCM, secret_1) OP_TXP_GENERATE_NONE() OP_CHECK(try_big_token) OP_TXP_GENERATE_NONE() OP_CRYPTO_SEND(QUIC_PN_SPACE_INITIAL, crypto_1) OP_TXP_GENERATE() OP_RX_PKT() OP_EXPECT_DGRAM_LEN(1200, 1200) OP_NEXT_FRAME() OP_EXPECT_FRAME(OSSL_QUIC_FRAME_TYPE_CRYPTO) OP_EXPECT_NO_FRAME() OP_RX_PKT_NONE() OP_TXP_GENERATE_NONE() OP_END }; static const struct script_op *const scripts[] = { script_1, script_2, script_3, script_4, script_5, script_6, script_7, script_8, script_9, script_10, script_11, script_12, script_13, script_14, script_15, script_16, script_17, script_18 }; static void skip_padding(struct helper *h) { uint64_t frame_type; if (!ossl_quic_wire_peek_frame_header(&h->pkt, &frame_type, NULL)) return; /* EOF */ if (frame_type == OSSL_QUIC_FRAME_TYPE_PADDING) ossl_quic_wire_decode_padding(&h->pkt); } static int run_script(int script_idx, const struct script_op *script) { int testresult = 0, have_helper = 0; QUIC_TXP_STATUS status; struct helper h; const struct script_op *op; size_t opn = 0; if (!helper_init(&h)) goto err; have_helper = 1; for (op = script, opn = 0; op->opcode != OPK_END; ++op, ++opn) { switch (op->opcode) { case OPK_TXP_GENERATE: if (!TEST_true(ossl_quic_tx_packetiser_generate(h.txp, &status)) && !TEST_size_t_gt(status.sent_pkt, 0)) goto err; ossl_qtx_finish_dgram(h.args.qtx); ossl_qtx_flush_net(h.args.qtx); break; case OPK_TXP_GENERATE_NONE: if (!TEST_true(ossl_quic_tx_packetiser_generate(h.txp, &status)) && !TEST_size_t_eq(status.sent_pkt, 0)) goto err; break; case OPK_RX_PKT: ossl_quic_demux_pump(h.demux); ossl_qrx_pkt_release(h.qrx_pkt); h.qrx_pkt = NULL; if (!TEST_true(ossl_qrx_read_pkt(h.qrx, &h.qrx_pkt))) goto err; if (!TEST_true(PACKET_buf_init(&h.pkt, h.qrx_pkt->hdr->data, h.qrx_pkt->hdr->len))) goto err; h.frame_type = UINT64_MAX; break; case OPK_RX_PKT_NONE: ossl_quic_demux_pump(h.demux); if (!TEST_false(ossl_qrx_read_pkt(h.qrx, &h.qrx_pkt))) goto err; h.frame_type = UINT64_MAX; break; case OPK_EXPECT_DGRAM_LEN: if (!TEST_size_t_ge(h.qrx_pkt->datagram_len, (size_t)op->arg0) || !TEST_size_t_le(h.qrx_pkt->datagram_len, (size_t)op->arg1)) goto err; break; case OPK_EXPECT_FRAME: if (!TEST_uint64_t_eq(h.frame_type, op->arg0)) goto err; break; case OPK_EXPECT_INITIAL_TOKEN: if (!TEST_mem_eq(h.qrx_pkt->hdr->token, h.qrx_pkt->hdr->token_len, op->buf, (size_t)op->arg0)) goto err; break; case OPK_EXPECT_HDR: if (!TEST_true(cmp_pkt_hdr(h.qrx_pkt->hdr, op->buf, NULL, 0, 0))) goto err; break; case OPK_CHECK: if (!TEST_true(op->check_func(&h))) goto err; break; case OPK_NEXT_FRAME: skip_padding(&h); if (!ossl_quic_wire_peek_frame_header(&h.pkt, &h.frame_type, NULL)) { h.frame_type = UINT64_MAX; break; } switch (h.frame_type) { case OSSL_QUIC_FRAME_TYPE_HANDSHAKE_DONE: if (!TEST_true(ossl_quic_wire_decode_frame_handshake_done(&h.pkt))) goto err; break; case OSSL_QUIC_FRAME_TYPE_PING: if (!TEST_true(ossl_quic_wire_decode_frame_ping(&h.pkt))) goto err; break; case OSSL_QUIC_FRAME_TYPE_MAX_DATA: if (!TEST_true(ossl_quic_wire_decode_frame_max_data(&h.pkt, &h.frame.max_data))) goto err; break; case OSSL_QUIC_FRAME_TYPE_NEW_CONN_ID: if (!TEST_true(ossl_quic_wire_decode_frame_new_conn_id(&h.pkt, &h.frame.new_conn_id))) goto err; break; case OSSL_QUIC_FRAME_TYPE_NEW_TOKEN: if (!TEST_true(ossl_quic_wire_decode_frame_new_token(&h.pkt, &h.frame.new_token.token, &h.frame.new_token.token_len))) goto err; break; case OSSL_QUIC_FRAME_TYPE_ACK_WITH_ECN: case OSSL_QUIC_FRAME_TYPE_ACK_WITHOUT_ECN: h.frame.ack.ack_ranges = h.ack_ranges; h.frame.ack.num_ack_ranges = OSSL_NELEM(h.ack_ranges); if (!TEST_true(ossl_quic_wire_decode_frame_ack(&h.pkt, h.args.ack_delay_exponent, &h.frame.ack, NULL))) goto err; break; case OSSL_QUIC_FRAME_TYPE_CRYPTO: if (!TEST_true(ossl_quic_wire_decode_frame_crypto(&h.pkt, 0, &h.frame.crypto))) goto err; break; case OSSL_QUIC_FRAME_TYPE_STREAM: case OSSL_QUIC_FRAME_TYPE_STREAM_FIN: case OSSL_QUIC_FRAME_TYPE_STREAM_LEN: case OSSL_QUIC_FRAME_TYPE_STREAM_LEN_FIN: case OSSL_QUIC_FRAME_TYPE_STREAM_OFF: case OSSL_QUIC_FRAME_TYPE_STREAM_OFF_FIN: case OSSL_QUIC_FRAME_TYPE_STREAM_OFF_LEN: case OSSL_QUIC_FRAME_TYPE_STREAM_OFF_LEN_FIN: if (!TEST_true(ossl_quic_wire_decode_frame_stream(&h.pkt, 0, &h.frame.stream))) goto err; break; case OSSL_QUIC_FRAME_TYPE_STOP_SENDING: if (!TEST_true(ossl_quic_wire_decode_frame_stop_sending(&h.pkt, &h.frame.stop_sending))) goto err; break; case OSSL_QUIC_FRAME_TYPE_RESET_STREAM: if (!TEST_true(ossl_quic_wire_decode_frame_reset_stream(&h.pkt, &h.frame.reset_stream))) goto err; break; case OSSL_QUIC_FRAME_TYPE_CONN_CLOSE_TRANSPORT: case OSSL_QUIC_FRAME_TYPE_CONN_CLOSE_APP: if (!TEST_true(ossl_quic_wire_decode_frame_conn_close(&h.pkt, &h.frame.conn_close))) goto err; break; default: TEST_error("unknown frame type"); goto err; } break; case OPK_EXPECT_NO_FRAME: skip_padding(&h); if (!TEST_size_t_eq(PACKET_remaining(&h.pkt), 0)) goto err; break; case OPK_PROVIDE_SECRET: if (!TEST_true(ossl_qtx_provide_secret(h.args.qtx, (uint32_t)op->arg0, (uint32_t)op->arg1, NULL, op->buf, op->buf_len))) goto err; if (!TEST_true(ossl_qrx_provide_secret(h.qrx, (uint32_t)op->arg0, (uint32_t)op->arg1, NULL, op->buf, op->buf_len))) goto err; break; case OPK_DISCARD_EL: if (!TEST_true(ossl_quic_tx_packetiser_discard_enc_level(h.txp, (uint32_t)op->arg0))) goto err; /* * We do not discard on the QRX here, the object is to test the * TXP so if the TXP does erroneously send at a discarded EL we * want to know about it. */ break; case OPK_CRYPTO_SEND: { size_t consumed = 0; if (!TEST_true(ossl_quic_sstream_append(h.args.crypto[op->arg0], op->buf, op->buf_len, &consumed))) goto err; if (!TEST_size_t_eq(consumed, op->buf_len)) goto err; } break; case OPK_STREAM_NEW: { QUIC_STREAM *s; if (!TEST_ptr(s = ossl_quic_stream_map_alloc(h.args.qsm, op->arg0, QUIC_STREAM_DIR_BIDI))) goto err; if (!TEST_ptr(s->sstream = ossl_quic_sstream_new(512 * 1024)) || !TEST_true(ossl_quic_txfc_init(&s->txfc, &h.conn_txfc)) || !TEST_true(ossl_quic_rxfc_init(&s->rxfc, &h.conn_rxfc, 1 * 1024 * 1024, 16 * 1024 * 1024, fake_now, NULL)) || !TEST_ptr(s->rstream = ossl_quic_rstream_new(&s->rxfc, NULL, 1024))) { ossl_quic_sstream_free(s->sstream); ossl_quic_stream_map_release(h.args.qsm, s); goto err; } } break; case OPK_STREAM_SEND: { QUIC_STREAM *s; size_t consumed = 0; if (!TEST_ptr(s = ossl_quic_stream_map_get_by_id(h.args.qsm, op->arg0))) goto err; if (!TEST_true(ossl_quic_sstream_append(s->sstream, op->buf, op->buf_len, &consumed))) goto err; if (!TEST_size_t_eq(consumed, op->buf_len)) goto err; ossl_quic_stream_map_update_state(h.args.qsm, s); } break; case OPK_STREAM_FIN: { QUIC_STREAM *s; if (!TEST_ptr(s = ossl_quic_stream_map_get_by_id(h.args.qsm, op->arg0))) goto err; ossl_quic_sstream_fin(s->sstream); } break; case OPK_STOP_SENDING: { QUIC_STREAM *s; if (!TEST_ptr(s = ossl_quic_stream_map_get_by_id(h.args.qsm, op->arg0))) goto err; if (!TEST_true(ossl_quic_stream_map_stop_sending_recv_part(h.args.qsm, s, op->arg1))) goto err; ossl_quic_stream_map_update_state(h.args.qsm, s); if (!TEST_true(s->active)) goto err; } break; case OPK_RESET_STREAM: { QUIC_STREAM *s; if (!TEST_ptr(s = ossl_quic_stream_map_get_by_id(h.args.qsm, op->arg0))) goto err; if (!TEST_true(ossl_quic_stream_map_reset_stream_send_part(h.args.qsm, s, op->arg1))) goto err; ossl_quic_stream_map_update_state(h.args.qsm, s); if (!TEST_true(s->active)) goto err; } break; case OPK_CONN_TXFC_BUMP: if (!TEST_true(ossl_quic_txfc_bump_cwm(h.args.conn_txfc, op->arg0))) goto err; break; case OPK_STREAM_TXFC_BUMP: { QUIC_STREAM *s; if (!TEST_ptr(s = ossl_quic_stream_map_get_by_id(h.args.qsm, op->arg1))) goto err; if (!TEST_true(ossl_quic_txfc_bump_cwm(&s->txfc, op->arg0))) goto err; ossl_quic_stream_map_update_state(h.args.qsm, s); } break; case OPK_HANDSHAKE_COMPLETE: ossl_quic_tx_packetiser_notify_handshake_complete(h.txp); break; case OPK_NOP: break; default: TEST_error("bad opcode"); goto err; } } testresult = 1; err: if (!testresult) TEST_error("script %d failed at op %zu", script_idx + 1, opn + 1); if (have_helper) helper_cleanup(&h); return testresult; } static int test_script(int idx) { return run_script(idx, scripts[idx]); } /* * Dynamic Script 1. * * This script exists to test the interactions between multiple packets (ELs) in * the same datagram when there is a padding requirement (due to the datagram * containing an Initial packet). There are boundary cases which are difficult * to get right so it is important to test this entire space. Examples of such * edge cases include: * * - If we are planning on generating both an Initial and Handshake packet in a * datagram ordinarily we would plan on adding the padding frames to meet the * mandatory minimum size to the last packet in the datagram (i.e., the * Handshake packet). But if the amount of room remaining in a datagram is * e.g. only 3 bytes after generating the Initial packet, this is not * enough room for another packet and we have a problem as having finished * the Initial packet we have no way to add the necessary padding. * * - If we do have room for another packet but it is not enough room to encode * any desired frame. * * This test confirms we handle these cases correctly for multi-packet datagrams * by placing two packets in a datagram and varying the size of the first * datagram. */ static const unsigned char dyn_script_1_crypto_1a[1200]; static const unsigned char dyn_script_1_crypto_1b[1]; static int check_is_initial(struct helper *h) { return h->qrx_pkt->hdr->type == QUIC_PKT_TYPE_INITIAL; } static int check_is_handshake(struct helper *h) { return h->qrx_pkt->hdr->type == QUIC_PKT_TYPE_HANDSHAKE; } static struct script_op dyn_script_1[] = { OP_PROVIDE_SECRET(QUIC_ENC_LEVEL_INITIAL, QRL_SUITE_AES128GCM, secret_1) OP_PROVIDE_SECRET(QUIC_ENC_LEVEL_HANDSHAKE, QRL_SUITE_AES128GCM, secret_1) OP_TXP_GENERATE_NONE() OP_CRYPTO_SEND(QUIC_PN_SPACE_INITIAL, dyn_script_1_crypto_1a) /* [crypto_idx] */ OP_CRYPTO_SEND(QUIC_PN_SPACE_HANDSHAKE, dyn_script_1_crypto_1b) OP_TXP_GENERATE() OP_RX_PKT() OP_EXPECT_DGRAM_LEN(1200, 1200) OP_CHECK(check_is_initial) OP_NOP() /* [pkt_idx] */ OP_NOP() /* [check_idx] */ OP_END }; static const size_t dyn_script_1_crypto_idx = 3; static const size_t dyn_script_1_pkt_idx = 9; static const size_t dyn_script_1_check_idx = 10; static const size_t dyn_script_1_start_from = 1000; static int test_dyn_script_1(int idx) { size_t target_size = dyn_script_1_start_from + (size_t)idx; int expect_handshake_pkt_in_same_dgram = (target_size <= 1115); dyn_script_1[dyn_script_1_crypto_idx].buf_len = target_size; if (expect_handshake_pkt_in_same_dgram) { dyn_script_1[dyn_script_1_pkt_idx].opcode = OPK_RX_PKT; dyn_script_1[dyn_script_1_check_idx].opcode = OPK_CHECK; dyn_script_1[dyn_script_1_check_idx].check_func = check_is_handshake; } else { dyn_script_1[dyn_script_1_pkt_idx].opcode = OPK_RX_PKT_NONE; dyn_script_1[dyn_script_1_check_idx].opcode = OPK_NOP; } if (!run_script(idx, dyn_script_1)) { TEST_error("failed dyn script 1 with target size %zu", target_size); return 0; } return 1; } int setup_tests(void) { ADD_ALL_TESTS(test_script, OSSL_NELEM(scripts)); ADD_ALL_TESTS(test_dyn_script_1, OSSL_NELEM(dyn_script_1_crypto_1a) - dyn_script_1_start_from + 1); return 1; }
./openssl/test/sysdefaulttest.c
/* * Copyright 2016-2018 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <stdio.h> #include <openssl/opensslconf.h> #include <string.h> #include <openssl/evp.h> #include <openssl/ssl.h> #include <openssl/tls1.h> #include "testutil.h" static SSL_CTX *ctx; static int test_func(void) { if (!TEST_int_eq(SSL_CTX_get_min_proto_version(ctx), TLS1_2_VERSION) && !TEST_int_eq(SSL_CTX_get_max_proto_version(ctx), TLS1_2_VERSION)) { TEST_info("min/max version setting incorrect"); return 0; } return 1; } int global_init(void) { if (!OPENSSL_init_ssl(OPENSSL_INIT_ENGINE_ALL_BUILTIN | OPENSSL_INIT_LOAD_CONFIG, NULL)) return 0; return 1; } int setup_tests(void) { if (!TEST_ptr(ctx = SSL_CTX_new(TLS_method()))) return 0; ADD_TEST(test_func); return 1; } void cleanup_tests(void) { SSL_CTX_free(ctx); }
./openssl/test/ext_internal_test.c
/* * Copyright 1995-2023 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include "internal/nelem.h" #include "../ssl/ssl_local.h" #include "../ssl/statem/statem_local.h" #include "testutil.h" #define EXT_ENTRY(name) { TLSEXT_IDX_##name, TLSEXT_TYPE_##name, #name } #define EXT_EXCEPTION(name) { TLSEXT_IDX_##name, TLSEXT_TYPE_invalid, #name } #define EXT_END(name) { TLSEXT_IDX_##name, TLSEXT_TYPE_out_of_range, #name } typedef struct { size_t idx; unsigned int type; char *name; } EXT_LIST; /* The order here does matter! */ static EXT_LIST ext_list[] = { EXT_ENTRY(renegotiate), EXT_ENTRY(server_name), EXT_ENTRY(max_fragment_length), #ifndef OPENSSL_NO_SRP EXT_ENTRY(srp), #else EXT_EXCEPTION(srp), #endif EXT_ENTRY(ec_point_formats), EXT_ENTRY(supported_groups), EXT_ENTRY(session_ticket), #ifndef OPENSSL_NO_OCSP EXT_ENTRY(status_request), #else EXT_EXCEPTION(status_request), #endif #ifndef OPENSSL_NO_NEXTPROTONEG EXT_ENTRY(next_proto_neg), #else EXT_EXCEPTION(next_proto_neg), #endif EXT_ENTRY(application_layer_protocol_negotiation), #ifndef OPENSSL_NO_SRTP EXT_ENTRY(use_srtp), #else EXT_EXCEPTION(use_srtp), #endif EXT_ENTRY(encrypt_then_mac), #ifndef OPENSSL_NO_CT EXT_ENTRY(signed_certificate_timestamp), #else EXT_EXCEPTION(signed_certificate_timestamp), #endif EXT_ENTRY(extended_master_secret), EXT_ENTRY(signature_algorithms_cert), EXT_ENTRY(post_handshake_auth), EXT_ENTRY(client_cert_type), EXT_ENTRY(server_cert_type), EXT_ENTRY(signature_algorithms), EXT_ENTRY(supported_versions), EXT_ENTRY(psk_kex_modes), EXT_ENTRY(key_share), EXT_ENTRY(cookie), EXT_ENTRY(cryptopro_bug), EXT_ENTRY(compress_certificate), EXT_ENTRY(early_data), EXT_ENTRY(certificate_authorities), EXT_ENTRY(padding), EXT_ENTRY(psk), EXT_END(num_builtins) }; static int test_extension_list(void) { size_t n = OSSL_NELEM(ext_list); size_t i; unsigned int type; int retval = 1; for (i = 0; i < n; i++) { if (!TEST_size_t_eq(i, ext_list[i].idx)) { retval = 0; TEST_error("TLSEXT_IDX_%s=%zd, found at=%zd\n", ext_list[i].name, ext_list[i].idx, i); } type = ossl_get_extension_type(ext_list[i].idx); if (!TEST_uint_eq(type, ext_list[i].type)) { retval = 0; TEST_error("TLSEXT_IDX_%s=%zd expected=0x%05X got=0x%05X", ext_list[i].name, ext_list[i].idx, ext_list[i].type, type); } } return retval; } int setup_tests(void) { ADD_TEST(test_extension_list); return 1; }
./openssl/test/tls13ccstest.c
/* * Copyright 2017-2023 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <openssl/ssl.h> #include <string.h> #include "helpers/ssltestlib.h" #include "testutil.h" #include "internal/packet.h" static char *cert = NULL; static char *privkey = NULL; static BIO *s_to_c_fbio = NULL, *c_to_s_fbio = NULL; static int chseen = 0, shseen = 0, sccsseen = 0, ccsaftersh = 0; static int ccsbeforesh = 0, sappdataseen = 0, cappdataseen = 0, badccs = 0; static int badvers = 0, badsessid = 0; static unsigned char chsessid[SSL_MAX_SSL_SESSION_ID_LENGTH]; static size_t chsessidlen = 0; static int watchccs_new(BIO *bi); static int watchccs_free(BIO *a); static int watchccs_read(BIO *b, char *out, int outl); static int watchccs_write(BIO *b, const char *in, int inl); static long watchccs_ctrl(BIO *b, int cmd, long num, void *ptr); static int watchccs_gets(BIO *bp, char *buf, int size); static int watchccs_puts(BIO *bp, const char *str); /* Choose a sufficiently large type likely to be unused for this custom BIO */ # define BIO_TYPE_WATCHCCS_FILTER (0x80 | BIO_TYPE_FILTER) static BIO_METHOD *method_watchccs = NULL; static const BIO_METHOD *bio_f_watchccs_filter(void) { if (method_watchccs == NULL) { method_watchccs = BIO_meth_new(BIO_TYPE_WATCHCCS_FILTER, "Watch CCS filter"); if (method_watchccs == NULL || !BIO_meth_set_write(method_watchccs, watchccs_write) || !BIO_meth_set_read(method_watchccs, watchccs_read) || !BIO_meth_set_puts(method_watchccs, watchccs_puts) || !BIO_meth_set_gets(method_watchccs, watchccs_gets) || !BIO_meth_set_ctrl(method_watchccs, watchccs_ctrl) || !BIO_meth_set_create(method_watchccs, watchccs_new) || !BIO_meth_set_destroy(method_watchccs, watchccs_free)) return NULL; } return method_watchccs; } static int watchccs_new(BIO *bio) { BIO_set_init(bio, 1); return 1; } static int watchccs_free(BIO *bio) { BIO_set_init(bio, 0); return 1; } static int watchccs_read(BIO *bio, char *out, int outl) { int ret = 0; BIO *next = BIO_next(bio); if (outl <= 0) return 0; if (next == NULL) return 0; BIO_clear_retry_flags(bio); ret = BIO_read(next, out, outl); if (ret <= 0 && BIO_should_read(next)) BIO_set_retry_read(bio); return ret; } static int watchccs_write(BIO *bio, const char *in, int inl) { int ret = 0; BIO *next = BIO_next(bio); PACKET pkt, msg, msgbody, sessionid; unsigned int rectype, recvers, msgtype, expectedrecvers; if (inl <= 0) return 0; if (next == NULL) return 0; BIO_clear_retry_flags(bio); if (!PACKET_buf_init(&pkt, (const unsigned char *)in, inl)) return 0; /* We assume that we always write complete records each time */ while (PACKET_remaining(&pkt)) { if (!PACKET_get_1(&pkt, &rectype) || !PACKET_get_net_2(&pkt, &recvers) || !PACKET_get_length_prefixed_2(&pkt, &msg)) return 0; expectedrecvers = TLS1_2_VERSION; if (rectype == SSL3_RT_HANDSHAKE) { if (!PACKET_get_1(&msg, &msgtype) || !PACKET_get_length_prefixed_3(&msg, &msgbody)) return 0; if (msgtype == SSL3_MT_CLIENT_HELLO) { chseen++; /* * Skip legacy_version (2 bytes) and Random (32 bytes) to read * session_id. */ if (!PACKET_forward(&msgbody, 34) || !PACKET_get_length_prefixed_1(&msgbody, &sessionid)) return 0; if (chseen == 1) { expectedrecvers = TLS1_VERSION; /* Save the session id for later */ chsessidlen = PACKET_remaining(&sessionid); if (!PACKET_copy_bytes(&sessionid, chsessid, chsessidlen)) return 0; } else { /* * Check the session id for the second ClientHello is the * same as the first one. */ if (PACKET_remaining(&sessionid) != chsessidlen || (chsessidlen > 0 && memcmp(chsessid, PACKET_data(&sessionid), chsessidlen) != 0)) badsessid = 1; } } else if (msgtype == SSL3_MT_SERVER_HELLO) { shseen++; /* * Skip legacy_version (2 bytes) and Random (32 bytes) to read * session_id. */ if (!PACKET_forward(&msgbody, 34) || !PACKET_get_length_prefixed_1(&msgbody, &sessionid)) return 0; /* * Check the session id is the same as the one in the * ClientHello */ if (PACKET_remaining(&sessionid) != chsessidlen || (chsessidlen > 0 && memcmp(chsessid, PACKET_data(&sessionid), chsessidlen) != 0)) badsessid = 1; } } else if (rectype == SSL3_RT_CHANGE_CIPHER_SPEC) { if (bio == s_to_c_fbio) { /* * Server writing. We shouldn't have written any app data * yet, and we should have seen both the ClientHello and the * ServerHello */ if (!sappdataseen && chseen == 1 && shseen == 1 && !sccsseen) sccsseen = 1; else badccs = 1; } else if (!cappdataseen) { /* * Client writing. We shouldn't have written any app data * yet, and we should have seen the ClientHello */ if (shseen == 1 && !ccsaftersh) ccsaftersh = 1; else if (shseen == 0 && !ccsbeforesh) ccsbeforesh = 1; else badccs = 1; } else { badccs = 1; } } else if (rectype == SSL3_RT_APPLICATION_DATA) { if (bio == s_to_c_fbio) sappdataseen = 1; else cappdataseen = 1; } if (recvers != expectedrecvers) badvers = 1; } ret = BIO_write(next, in, inl); if (ret <= 0 && BIO_should_write(next)) BIO_set_retry_write(bio); return ret; } static long watchccs_ctrl(BIO *bio, int cmd, long num, void *ptr) { long ret; BIO *next = BIO_next(bio); if (next == NULL) return 0; switch (cmd) { case BIO_CTRL_DUP: ret = 0; break; default: ret = BIO_ctrl(next, cmd, num, ptr); break; } return ret; } static int watchccs_gets(BIO *bio, char *buf, int size) { /* We don't support this - not needed anyway */ return -1; } static int watchccs_puts(BIO *bio, const char *str) { return watchccs_write(bio, str, strlen(str)); } static int test_tls13ccs(int tst) { SSL_CTX *sctx = NULL, *cctx = NULL; SSL *sssl = NULL, *cssl = NULL; int ret = 0; const char msg[] = "Dummy data"; char buf[80]; size_t written, readbytes; SSL_SESSION *sess = NULL; chseen = shseen = sccsseen = ccsaftersh = ccsbeforesh = 0; sappdataseen = cappdataseen = badccs = badvers = badsessid = 0; chsessidlen = 0; if (!TEST_true(create_ssl_ctx_pair(NULL, TLS_server_method(), TLS_client_method(), TLS1_VERSION, 0, &sctx, &cctx, cert, privkey)) || !TEST_true(SSL_CTX_set_max_early_data(sctx, SSL3_RT_MAX_PLAIN_LENGTH))) goto err; /* * Test 0: Simple Handshake * Test 1: Simple Handshake, client middlebox compat mode disabled * Test 2: Simple Handshake, server middlebox compat mode disabled * Test 3: HRR Handshake * Test 4: HRR Handshake, client middlebox compat mode disabled * Test 5: HRR Handshake, server middlebox compat mode disabled * Test 6: Early data handshake * Test 7: Early data handshake, client middlebox compat mode disabled * Test 8: Early data handshake, server middlebox compat mode disabled * Test 9: Early data then HRR * Test 10: Early data then HRR, client middlebox compat mode disabled * Test 11: Early data then HRR, server middlebox compat mode disabled */ switch (tst) { case 0: case 3: case 6: case 9: break; case 1: case 4: case 7: case 10: SSL_CTX_clear_options(cctx, SSL_OP_ENABLE_MIDDLEBOX_COMPAT); break; case 2: case 5: case 8: case 11: SSL_CTX_clear_options(sctx, SSL_OP_ENABLE_MIDDLEBOX_COMPAT); break; default: TEST_error("Invalid test value"); goto err; } if (tst >= 6) { /* Get a session suitable for early_data */ if (!TEST_true(create_ssl_objects(sctx, cctx, &sssl, &cssl, NULL, NULL)) || !TEST_true(create_ssl_connection(sssl, cssl, SSL_ERROR_NONE))) goto err; sess = SSL_get1_session(cssl); if (!TEST_ptr(sess)) goto err; SSL_shutdown(cssl); SSL_shutdown(sssl); SSL_free(sssl); SSL_free(cssl); sssl = cssl = NULL; } if ((tst >= 3 && tst <= 5) || tst >= 9) { /* HRR handshake */ #if defined(OPENSSL_NO_EC) # if !defined(OPENSSL_NO_DH) if (!TEST_true(SSL_CTX_set1_groups_list(sctx, "ffdhe3072"))) goto err; # endif #else if (!TEST_true(SSL_CTX_set1_groups_list(sctx, "P-384"))) goto err; #endif } s_to_c_fbio = BIO_new(bio_f_watchccs_filter()); c_to_s_fbio = BIO_new(bio_f_watchccs_filter()); if (!TEST_ptr(s_to_c_fbio) || !TEST_ptr(c_to_s_fbio)) { BIO_free(s_to_c_fbio); BIO_free(c_to_s_fbio); goto err; } /* BIOs get freed on error */ if (!TEST_true(create_ssl_objects(sctx, cctx, &sssl, &cssl, s_to_c_fbio, c_to_s_fbio))) goto err; if (tst >= 6) { /* Early data */ if (!TEST_true(SSL_set_session(cssl, sess)) || !TEST_true(SSL_write_early_data(cssl, msg, strlen(msg), &written)) || (tst <= 8 && !TEST_int_eq(SSL_read_early_data(sssl, buf, sizeof(buf), &readbytes), SSL_READ_EARLY_DATA_SUCCESS))) goto err; if (tst <= 8) { if (!TEST_int_gt(SSL_connect(cssl), 0)) goto err; } else { if (!TEST_int_le(SSL_connect(cssl), 0)) goto err; } if (!TEST_int_eq(SSL_read_early_data(sssl, buf, sizeof(buf), &readbytes), SSL_READ_EARLY_DATA_FINISH)) goto err; } /* Perform handshake (or complete it if doing early data ) */ if (!TEST_true(create_ssl_connection(sssl, cssl, SSL_ERROR_NONE))) goto err; /* * Check there were no unexpected CCS messages, all record versions * were as expected, and that the session ids were reflected by the server * correctly. */ if (!TEST_false(badccs) || !TEST_false(badvers) || !TEST_false(badsessid)) goto err; switch (tst) { case 0: if (!TEST_true(sccsseen) || !TEST_true(ccsaftersh) || !TEST_false(ccsbeforesh) || !TEST_size_t_gt(chsessidlen, 0)) goto err; break; case 1: if (!TEST_true(sccsseen) || !TEST_false(ccsaftersh) || !TEST_false(ccsbeforesh) || !TEST_size_t_eq(chsessidlen, 0)) goto err; break; case 2: if (!TEST_false(sccsseen) || !TEST_true(ccsaftersh) || !TEST_false(ccsbeforesh) || !TEST_size_t_gt(chsessidlen, 0)) goto err; break; case 3: if (!TEST_true(sccsseen) || !TEST_true(ccsaftersh) || !TEST_false(ccsbeforesh) || !TEST_size_t_gt(chsessidlen, 0)) goto err; break; case 4: if (!TEST_true(sccsseen) || !TEST_false(ccsaftersh) || !TEST_false(ccsbeforesh) || !TEST_size_t_eq(chsessidlen, 0)) goto err; break; case 5: if (!TEST_false(sccsseen) || !TEST_true(ccsaftersh) || !TEST_false(ccsbeforesh) || !TEST_size_t_gt(chsessidlen, 0)) goto err; break; case 6: if (!TEST_true(sccsseen) || !TEST_false(ccsaftersh) || !TEST_true(ccsbeforesh) || !TEST_size_t_gt(chsessidlen, 0)) goto err; break; case 7: if (!TEST_true(sccsseen) || !TEST_false(ccsaftersh) || !TEST_false(ccsbeforesh) || !TEST_size_t_eq(chsessidlen, 0)) goto err; break; case 8: if (!TEST_false(sccsseen) || !TEST_false(ccsaftersh) || !TEST_true(ccsbeforesh) || !TEST_size_t_gt(chsessidlen, 0)) goto err; break; case 9: if (!TEST_true(sccsseen) || !TEST_false(ccsaftersh) || !TEST_true(ccsbeforesh) || !TEST_size_t_gt(chsessidlen, 0)) goto err; break; case 10: if (!TEST_true(sccsseen) || !TEST_false(ccsaftersh) || !TEST_false(ccsbeforesh) || !TEST_size_t_eq(chsessidlen, 0)) goto err; break; case 11: if (!TEST_false(sccsseen) || !TEST_false(ccsaftersh) || !TEST_true(ccsbeforesh) || !TEST_size_t_gt(chsessidlen, 0)) goto err; break; default: TEST_error("Invalid test value"); goto err; } ret = 1; err: SSL_SESSION_free(sess); SSL_free(sssl); SSL_free(cssl); SSL_CTX_free(sctx); SSL_CTX_free(cctx); return ret; } OPT_TEST_DECLARE_USAGE("certfile privkeyfile\n") int setup_tests(void) { if (!test_skip_common_options()) { TEST_error("Error parsing test options\n"); return 0; } if (!TEST_ptr(cert = test_get_argument(0)) || !TEST_ptr(privkey = test_get_argument(1))) return 0; ADD_ALL_TESTS(test_tls13ccs, 12); return 1; } void cleanup_tests(void) { BIO_meth_free(method_watchccs); }
./openssl/test/quic_rcidm_test.c
/* * Copyright 2023 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include "internal/quic_rcidm.h" #include "testutil.h" static const QUIC_CONN_ID cid8_1 = { 8, { 1 } }; static const QUIC_CONN_ID cid8_2 = { 8, { 2 } }; static const QUIC_CONN_ID cid8_3 = { 8, { 3 } }; static const QUIC_CONN_ID cid8_4 = { 8, { 4 } }; static const QUIC_CONN_ID cid8_5 = { 8, { 5 } }; /* * 0: Client, Initial ODCID * 1: Client, Initial ODCID + Retry ODCID * 2: Server, doesn't start with Initial ODCID */ static int test_rcidm(int idx) { int testresult = 0; QUIC_RCIDM *rcidm; OSSL_QUIC_FRAME_NEW_CONN_ID ncid_frame_1 = {0}, ncid_frame_2 = {0}; QUIC_CONN_ID dcid_out; const QUIC_CONN_ID *odcid = NULL; uint64_t seq_num_out; ncid_frame_1.seq_num = 2; ncid_frame_1.conn_id.id_len = 8; ncid_frame_1.conn_id.id[0] = 3; ncid_frame_2.seq_num = 3; ncid_frame_2.conn_id.id_len = 8; ncid_frame_2.conn_id.id[0] = 4; odcid = ((idx == 2) ? NULL : &cid8_1); if (!TEST_ptr(rcidm = ossl_quic_rcidm_new(odcid))) goto err; if (idx != 2) { if (/* ODCID not counted */ !TEST_true(ossl_quic_rcidm_get_preferred_tx_dcid_changed(rcidm, 1)) || !TEST_false(ossl_quic_rcidm_get_preferred_tx_dcid_changed(rcidm, 0)) || !TEST_true(ossl_quic_rcidm_get_preferred_tx_dcid(rcidm, &dcid_out)) || !TEST_true(ossl_quic_conn_id_eq(&dcid_out, &cid8_1)) || !TEST_size_t_eq(ossl_quic_rcidm_get_num_active(rcidm), 0)) goto err; } else { if (!TEST_false(ossl_quic_rcidm_get_preferred_tx_dcid(rcidm, &dcid_out)) || !TEST_size_t_eq(ossl_quic_rcidm_get_num_active(rcidm), 0)) goto err; } if (idx == 1) { if (!TEST_true(ossl_quic_rcidm_add_from_server_retry(rcidm, &cid8_5)) || !TEST_true(ossl_quic_rcidm_get_preferred_tx_dcid_changed(rcidm, 1)) || !TEST_false(ossl_quic_rcidm_get_preferred_tx_dcid_changed(rcidm, 0)) || !TEST_true(ossl_quic_rcidm_get_preferred_tx_dcid(rcidm, &dcid_out)) || !TEST_true(ossl_quic_conn_id_eq(&dcid_out, &cid8_5)) || !TEST_size_t_eq(ossl_quic_rcidm_get_num_active(rcidm), 0)) goto err; } if (!TEST_true(ossl_quic_rcidm_add_from_initial(rcidm, &cid8_2)) /* Initial SCID (seq=0) is counted */ || !TEST_size_t_eq(ossl_quic_rcidm_get_num_active(rcidm), 1) || !TEST_true(ossl_quic_rcidm_get_preferred_tx_dcid_changed(rcidm, 1)) || !TEST_false(ossl_quic_rcidm_get_preferred_tx_dcid_changed(rcidm, 0)) || !TEST_true(ossl_quic_rcidm_get_preferred_tx_dcid(rcidm, &dcid_out)) || !TEST_true(ossl_quic_conn_id_eq(&dcid_out, &cid8_2)) || !TEST_true(ossl_quic_rcidm_add_from_ncid(rcidm, &ncid_frame_1)) || !TEST_size_t_eq(ossl_quic_rcidm_get_num_active(rcidm), 2) /* Not changed over yet - handshake not confirmed */ || !TEST_false(ossl_quic_rcidm_get_preferred_tx_dcid_changed(rcidm, 0)) || !TEST_true(ossl_quic_rcidm_get_preferred_tx_dcid(rcidm, &dcid_out)) || !TEST_true(ossl_quic_conn_id_eq(&dcid_out, &cid8_2)) || !TEST_true(ossl_quic_rcidm_add_from_ncid(rcidm, &ncid_frame_2)) || !TEST_size_t_eq(ossl_quic_rcidm_get_num_active(rcidm), 3) || !TEST_size_t_eq(ossl_quic_rcidm_get_num_retiring(rcidm), 0) || !TEST_false(ossl_quic_rcidm_pop_retire_seq_num(rcidm, &seq_num_out)) /* Not changed over yet - handshake not confirmed */ || !TEST_false(ossl_quic_rcidm_get_preferred_tx_dcid_changed(rcidm, 0)) || !TEST_true(ossl_quic_rcidm_get_preferred_tx_dcid(rcidm, &dcid_out)) || !TEST_true(ossl_quic_conn_id_eq(&dcid_out, &cid8_2))) goto err; ossl_quic_rcidm_on_handshake_complete(rcidm); if (!TEST_true(ossl_quic_rcidm_get_preferred_tx_dcid_changed(rcidm, 1)) || !TEST_false(ossl_quic_rcidm_get_preferred_tx_dcid_changed(rcidm, 1)) || !TEST_true(ossl_quic_rcidm_get_preferred_tx_dcid(rcidm, &dcid_out)) || !TEST_true(ossl_quic_conn_id_eq(&dcid_out, &cid8_3)) || !TEST_size_t_eq(ossl_quic_rcidm_get_num_retiring(rcidm), 1) || !TEST_true(ossl_quic_rcidm_peek_retire_seq_num(rcidm, &seq_num_out)) || !TEST_uint64_t_eq(seq_num_out, 0)) goto err; ossl_quic_rcidm_request_roll(rcidm); if (!TEST_true(ossl_quic_rcidm_get_preferred_tx_dcid_changed(rcidm, 1)) || !TEST_false(ossl_quic_rcidm_get_preferred_tx_dcid_changed(rcidm, 1)) || !TEST_true(ossl_quic_rcidm_get_preferred_tx_dcid(rcidm, &dcid_out)) || !TEST_true(ossl_quic_conn_id_eq(&dcid_out, &cid8_4)) || !TEST_size_t_eq(ossl_quic_rcidm_get_num_retiring(rcidm), 2) || !TEST_true(ossl_quic_rcidm_peek_retire_seq_num(rcidm, &seq_num_out)) || !TEST_uint64_t_eq(seq_num_out, 0) || !TEST_true(ossl_quic_rcidm_pop_retire_seq_num(rcidm, &seq_num_out)) || !TEST_uint64_t_eq(seq_num_out, 0) || !TEST_true(ossl_quic_rcidm_pop_retire_seq_num(rcidm, &seq_num_out)) || !TEST_uint64_t_eq(seq_num_out, 2)) goto err; testresult = 1; err: ossl_quic_rcidm_free(rcidm); return testresult; } int setup_tests(void) { ADD_ALL_TESTS(test_rcidm, 3); return 1; }
./openssl/test/ossl_store_test.c
/* * Copyright 2020-2021 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <string.h> #include <limits.h> #include <openssl/store.h> #include <openssl/ui.h> #include "testutil.h" #ifndef PATH_MAX # if defined(_WIN32) && defined(_MAX_PATH) # define PATH_MAX _MAX_PATH # else # define PATH_MAX 4096 # endif #endif typedef enum OPTION_choice { OPT_ERR = -1, OPT_EOF = 0, OPT_INPUTDIR, OPT_INFILE, OPT_SM2FILE, OPT_DATADIR, OPT_TEST_ENUM } OPTION_CHOICE; static const char *inputdir = NULL; static const char *infile = NULL; static const char *sm2file = NULL; static const char *datadir = NULL; static int test_store_open(void) { int ret = 0; OSSL_STORE_CTX *sctx = NULL; OSSL_STORE_SEARCH *search = NULL; UI_METHOD *ui_method = NULL; char *input = test_mk_file_path(inputdir, infile); ret = TEST_ptr(input) && TEST_ptr(search = OSSL_STORE_SEARCH_by_alias("nothing")) && TEST_ptr(ui_method= UI_create_method("DummyUI")) && TEST_ptr(sctx = OSSL_STORE_open_ex(input, NULL, NULL, ui_method, NULL, NULL, NULL, NULL)) && TEST_false(OSSL_STORE_find(sctx, NULL)) && TEST_true(OSSL_STORE_find(sctx, search)); UI_destroy_method(ui_method); OSSL_STORE_SEARCH_free(search); OSSL_STORE_close(sctx); OPENSSL_free(input); return ret; } static int test_store_search_by_key_fingerprint_fail(void) { int ret; OSSL_STORE_SEARCH *search = NULL; ret = TEST_ptr_null(search = OSSL_STORE_SEARCH_by_key_fingerprint( EVP_sha256(), NULL, 0)); OSSL_STORE_SEARCH_free(search); return ret; } static int get_params(const char *uri, const char *type) { EVP_PKEY *pkey = NULL; OSSL_STORE_CTX *ctx = NULL; OSSL_STORE_INFO *info; int ret = 0; ctx = OSSL_STORE_open_ex(uri, NULL, NULL, NULL, NULL, NULL, NULL, NULL); if (!TEST_ptr(ctx)) goto err; while (!OSSL_STORE_eof(ctx) && (info = OSSL_STORE_load(ctx)) != NULL && pkey == NULL) { if (OSSL_STORE_INFO_get_type(info) == OSSL_STORE_INFO_PARAMS) { pkey = OSSL_STORE_INFO_get1_PARAMS(info); } OSSL_STORE_INFO_free(info); info = NULL; } if (pkey != NULL) ret = EVP_PKEY_is_a(pkey, type); EVP_PKEY_free(pkey); err: OSSL_STORE_close(ctx); return ret; } static int test_store_get_params(int idx) { const char *type; const char *urifmt; char uri[PATH_MAX]; switch (idx) { #ifndef OPENSSL_NO_DH case 0: type = "DH"; break; case 1: type = "DHX"; break; #else case 0: case 1: return 1; #endif case 2: #ifndef OPENSSL_NO_DSA type = "DSA"; break; #else return 1; #endif default: TEST_error("Invalid test index"); return 0; } urifmt = "%s/%s-params.pem"; #ifdef __VMS { char datadir_end = datadir[strlen(datadir) - 1]; if (datadir_end == ':' || datadir_end == ']' || datadir_end == '>') urifmt = "%s%s-params.pem"; } #endif if (!TEST_true(BIO_snprintf(uri, sizeof(uri), urifmt, datadir, type))) return 0; TEST_info("Testing uri: %s", uri); if (!TEST_true(get_params(uri, type))) return 0; return 1; } /* * This test verifies that calling OSSL_STORE_ATTACH does not set an * "unregistered scheme" error when called. */ static int test_store_attach_unregistered_scheme(void) { int ret; OSSL_STORE_CTX *store_ctx = NULL; OSSL_PROVIDER *provider = NULL; OSSL_LIB_CTX *libctx = NULL; BIO *bio = NULL; char *input = test_mk_file_path(inputdir, sm2file); ret = TEST_ptr(input) && TEST_ptr(libctx = OSSL_LIB_CTX_new()) && TEST_ptr(provider = OSSL_PROVIDER_load(libctx, "default")) && TEST_ptr(bio = BIO_new_file(input, "r")) && TEST_ptr(store_ctx = OSSL_STORE_attach(bio, "file", libctx, NULL, NULL, NULL, NULL, NULL, NULL)) && TEST_int_ne(ERR_GET_LIB(ERR_peek_error()), ERR_LIB_OSSL_STORE) && TEST_int_ne(ERR_GET_REASON(ERR_peek_error()), OSSL_STORE_R_UNREGISTERED_SCHEME); BIO_free(bio); OSSL_STORE_close(store_ctx); OSSL_PROVIDER_unload(provider); OSSL_LIB_CTX_free(libctx); OPENSSL_free(input); return ret; } const OPTIONS *test_get_options(void) { static const OPTIONS test_options[] = { OPT_TEST_OPTIONS_DEFAULT_USAGE, { "dir", OPT_INPUTDIR, '/' }, { "in", OPT_INFILE, '<' }, { "sm2", OPT_SM2FILE, '<' }, { "data", OPT_DATADIR, 's' }, { NULL } }; return test_options; } int setup_tests(void) { OPTION_CHOICE o; while ((o = opt_next()) != OPT_EOF) { switch (o) { case OPT_INPUTDIR: inputdir = opt_arg(); break; case OPT_INFILE: infile = opt_arg(); break; case OPT_SM2FILE: sm2file = opt_arg(); break; case OPT_DATADIR: datadir = opt_arg(); break; case OPT_TEST_CASES: break; default: case OPT_ERR: return 0; } } if (datadir == NULL) { TEST_error("No data directory specified"); return 0; } if (inputdir == NULL) { TEST_error("No input directory specified"); return 0; } if (infile != NULL) ADD_TEST(test_store_open); ADD_TEST(test_store_search_by_key_fingerprint_fail); ADD_ALL_TESTS(test_store_get_params, 3); if (sm2file != NULL) ADD_TEST(test_store_attach_unregistered_scheme); return 1; }
./openssl/test/params_test.c
/* * Copyright 2019-2022 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * https://www.openssl.org/source/license.html * or in the file LICENSE in the source distribution. */ /* * This program tests the use of OSSL_PARAM, currently in raw form. */ #include <string.h> #include <openssl/bn.h> #include <openssl/core.h> #include <openssl/params.h> #include "internal/numbers.h" #include "internal/nelem.h" #include "testutil.h" /*- * PROVIDER SECTION * ================ * * Even though it's not necessarily ONLY providers doing this part, * they are naturally going to be the most common users of * set_params and get_params functions. */ /* * In real use cases, setters and getters would take an object with * which the parameters are associated. This structure is a cheap * simulation. */ struct object_st { /* * Documented as a native integer, of the size given by sizeof(int). * Assumed data type OSSL_PARAM_INTEGER */ int p1; /* * Documented as a native double, of the size given by sizeof(double). * Assumed data type OSSL_PARAM_REAL */ double p2; /* * Documented as an arbitrarily large unsigned integer. * The data size must be large enough to accommodate. * Assumed data type OSSL_PARAM_UNSIGNED_INTEGER */ BIGNUM *p3; /* * Documented as a C string. * The data size must be large enough to accommodate. * Assumed data type OSSL_PARAM_UTF8_STRING */ char *p4; size_t p4_l; /* * Documented as a C string. * Assumed data type OSSL_PARAM_UTF8_STRING */ char p5[256]; size_t p5_l; /* * Documented as a pointer to a constant C string. * Assumed data type OSSL_PARAM_UTF8_PTR */ const char *p6; size_t p6_l; }; #define p1_init 42 /* The ultimate answer */ #define p2_init 6.283 /* Magic number */ /* Stolen from evp_data, BLAKE2s256 test */ #define p3_init \ "4142434445464748494a4b4c4d4e4f50" \ "5152535455565758595a616263646566" \ "6768696a6b6c6d6e6f70717273747576" \ "7778797a30313233343536373839" #define p4_init "BLAKE2s256" /* Random string */ #define p5_init "Hellow World" /* Random string */ #define p6_init OPENSSL_FULL_VERSION_STR /* Static string */ static void cleanup_object(void *vobj) { struct object_st *obj = vobj; BN_free(obj->p3); obj->p3 = NULL; OPENSSL_free(obj->p4); obj->p4 = NULL; OPENSSL_free(obj); } static void *init_object(void) { struct object_st *obj; if (!TEST_ptr(obj = OPENSSL_zalloc(sizeof(*obj)))) return NULL; obj->p1 = p1_init; obj->p2 = p2_init; if (!TEST_true(BN_hex2bn(&obj->p3, p3_init))) goto fail; if (!TEST_ptr(obj->p4 = OPENSSL_strdup(p4_init))) goto fail; strcpy(obj->p5, p5_init); obj->p6 = p6_init; return obj; fail: cleanup_object(obj); obj = NULL; return NULL; } /* * RAW provider, which handles the parameters in a very raw manner, * with no fancy API and very minimal checking. The application that * calls these to set or request parameters MUST get its OSSL_PARAM * array right. */ static int raw_set_params(void *vobj, const OSSL_PARAM *params) { struct object_st *obj = vobj; for (; params->key != NULL; params++) if (strcmp(params->key, "p1") == 0) { obj->p1 = *(int *)params->data; } else if (strcmp(params->key, "p2") == 0) { obj->p2 = *(double *)params->data; } else if (strcmp(params->key, "p3") == 0) { BN_free(obj->p3); if (!TEST_ptr(obj->p3 = BN_native2bn(params->data, params->data_size, NULL))) return 0; } else if (strcmp(params->key, "p4") == 0) { OPENSSL_free(obj->p4); if (!TEST_ptr(obj->p4 = OPENSSL_strndup(params->data, params->data_size))) return 0; obj->p4_l = strlen(obj->p4); } else if (strcmp(params->key, "p5") == 0) { /* * Protect obj->p5 against too much data. This should not * happen, we don't use that long strings. */ size_t data_length = OPENSSL_strnlen(params->data, params->data_size); if (!TEST_size_t_lt(data_length, sizeof(obj->p5))) return 0; strncpy(obj->p5, params->data, data_length); obj->p5[data_length] = '\0'; obj->p5_l = strlen(obj->p5); } else if (strcmp(params->key, "p6") == 0) { obj->p6 = *(const char **)params->data; obj->p6_l = params->data_size; } return 1; } static int raw_get_params(void *vobj, OSSL_PARAM *params) { struct object_st *obj = vobj; for (; params->key != NULL; params++) if (strcmp(params->key, "p1") == 0) { params->return_size = sizeof(obj->p1); *(int *)params->data = obj->p1; } else if (strcmp(params->key, "p2") == 0) { params->return_size = sizeof(obj->p2); *(double *)params->data = obj->p2; } else if (strcmp(params->key, "p3") == 0) { params->return_size = BN_num_bytes(obj->p3); if (!TEST_size_t_ge(params->data_size, params->return_size)) return 0; BN_bn2nativepad(obj->p3, params->data, params->return_size); } else if (strcmp(params->key, "p4") == 0) { params->return_size = strlen(obj->p4); if (!TEST_size_t_gt(params->data_size, params->return_size)) return 0; strcpy(params->data, obj->p4); } else if (strcmp(params->key, "p5") == 0) { params->return_size = strlen(obj->p5); if (!TEST_size_t_gt(params->data_size, params->return_size)) return 0; strcpy(params->data, obj->p5); } else if (strcmp(params->key, "p6") == 0) { params->return_size = strlen(obj->p6); *(const char **)params->data = obj->p6; } return 1; } /* * API provider, which handles the parameters using the API from params.h */ static int api_set_params(void *vobj, const OSSL_PARAM *params) { struct object_st *obj = vobj; const OSSL_PARAM *p = NULL; if ((p = OSSL_PARAM_locate_const(params, "p1")) != NULL && !TEST_true(OSSL_PARAM_get_int(p, &obj->p1))) return 0; if ((p = OSSL_PARAM_locate_const(params, "p2")) != NULL && !TEST_true(OSSL_PARAM_get_double(p, &obj->p2))) return 0; if ((p = OSSL_PARAM_locate_const(params, "p3")) != NULL && !TEST_true(OSSL_PARAM_get_BN(p, &obj->p3))) return 0; if ((p = OSSL_PARAM_locate_const(params, "p4")) != NULL) { OPENSSL_free(obj->p4); obj->p4 = NULL; /* If the value pointer is NULL, we get it automatically allocated */ if (!TEST_true(OSSL_PARAM_get_utf8_string(p, &obj->p4, 0))) return 0; } if ((p = OSSL_PARAM_locate_const(params, "p5")) != NULL) { char *p5_ptr = obj->p5; if (!TEST_true(OSSL_PARAM_get_utf8_string(p, &p5_ptr, sizeof(obj->p5)))) return 0; obj->p5_l = strlen(obj->p5); } if ((p = OSSL_PARAM_locate_const(params, "p6")) != NULL) { if (!TEST_true(OSSL_PARAM_get_utf8_ptr(p, &obj->p6))) return 0; obj->p6_l = strlen(obj->p6); } return 1; } static int api_get_params(void *vobj, OSSL_PARAM *params) { struct object_st *obj = vobj; OSSL_PARAM *p = NULL; if ((p = OSSL_PARAM_locate(params, "p1")) != NULL && !TEST_true(OSSL_PARAM_set_int(p, obj->p1))) return 0; if ((p = OSSL_PARAM_locate(params, "p2")) != NULL && !TEST_true(OSSL_PARAM_set_double(p, obj->p2))) return 0; if ((p = OSSL_PARAM_locate(params, "p3")) != NULL && !TEST_true(OSSL_PARAM_set_BN(p, obj->p3))) return 0; if ((p = OSSL_PARAM_locate(params, "p4")) != NULL && !TEST_true(OSSL_PARAM_set_utf8_string(p, obj->p4))) return 0; if ((p = OSSL_PARAM_locate(params, "p5")) != NULL && !TEST_true(OSSL_PARAM_set_utf8_string(p, obj->p5))) return 0; if ((p = OSSL_PARAM_locate(params, "p6")) != NULL && !TEST_true(OSSL_PARAM_set_utf8_ptr(p, obj->p6))) return 0; return 1; } /* * This structure only simulates a provider dispatch, the real deal is * a bit more code that's not necessary in these tests. */ struct provider_dispatch_st { int (*set_params)(void *obj, const OSSL_PARAM *params); int (*get_params)(void *obj, OSSL_PARAM *params); }; /* "raw" provider */ static const struct provider_dispatch_st provider_raw = { raw_set_params, raw_get_params }; /* "api" provider */ static const struct provider_dispatch_st provider_api = { api_set_params, api_get_params }; /*- * APPLICATION SECTION * =================== */ /* In all our tests, these are variables that get manipulated as parameters * * These arrays consistently do nothing with the "p2" parameter, and * always include a "foo" parameter. This is to check that the * set_params and get_params calls ignore the lack of parameters that * the application isn't interested in, as well as ignore parameters * they don't understand (the application may have one big bag of * parameters). */ static int app_p1; /* "p1" */ static double app_p2; /* "p2" is ignored */ static BIGNUM *app_p3 = NULL; /* "p3" */ static unsigned char bignumbin[4096]; /* "p3" */ static char app_p4[256]; /* "p4" */ static char app_p5[256]; /* "p5" */ static const char *app_p6 = NULL; /* "p6" */ static unsigned char foo[1]; /* "foo" */ #define app_p1_init 17 /* A random number */ #define app_p2_init 47.11 /* Another random number */ #define app_p3_init "deadbeef" /* Classic */ #define app_p4_init "Hello" #define app_p5_init "World" #define app_p6_init "Cookie" #define app_foo_init 'z' static int cleanup_app_variables(void) { BN_free(app_p3); app_p3 = NULL; return 1; } static int init_app_variables(void) { int l = 0; cleanup_app_variables(); app_p1 = app_p1_init; app_p2 = app_p2_init; if (!BN_hex2bn(&app_p3, app_p3_init) || (l = BN_bn2nativepad(app_p3, bignumbin, sizeof(bignumbin))) < 0) return 0; strcpy(app_p4, app_p4_init); strcpy(app_p5, app_p5_init); app_p6 = app_p6_init; foo[0] = app_foo_init; return 1; } /* * Here, we define test OSSL_PARAM arrays */ /* An array of OSSL_PARAM, specific in the most raw manner possible */ static OSSL_PARAM static_raw_params[] = { { "p1", OSSL_PARAM_INTEGER, &app_p1, sizeof(app_p1), 0 }, { "p3", OSSL_PARAM_UNSIGNED_INTEGER, &bignumbin, sizeof(bignumbin), 0 }, { "p4", OSSL_PARAM_UTF8_STRING, &app_p4, sizeof(app_p4), 0 }, { "p5", OSSL_PARAM_UTF8_STRING, &app_p5, sizeof(app_p5), 0 }, /* sizeof(app_p6_init) - 1, because we know that's what we're using */ { "p6", OSSL_PARAM_UTF8_PTR, &app_p6, sizeof(app_p6_init) - 1, 0 }, { "foo", OSSL_PARAM_OCTET_STRING, &foo, sizeof(foo), 0 }, { NULL, 0, NULL, 0, 0 } }; /* The same array of OSSL_PARAM, specified with the macros from params.h */ static OSSL_PARAM static_api_params[] = { OSSL_PARAM_int("p1", &app_p1), OSSL_PARAM_BN("p3", &bignumbin, sizeof(bignumbin)), OSSL_PARAM_DEFN("p4", OSSL_PARAM_UTF8_STRING, &app_p4, sizeof(app_p4)), OSSL_PARAM_DEFN("p5", OSSL_PARAM_UTF8_STRING, &app_p5, sizeof(app_p5)), /* sizeof(app_p6_init), because we know that's what we're using */ OSSL_PARAM_DEFN("p6", OSSL_PARAM_UTF8_PTR, &app_p6, sizeof(app_p6_init) - 1), OSSL_PARAM_DEFN("foo", OSSL_PARAM_OCTET_STRING, &foo, sizeof(foo)), OSSL_PARAM_END }; /* * The same array again, but constructed at run-time * This exercises the OSSL_PARAM constructor functions */ static OSSL_PARAM *construct_api_params(void) { size_t n = 0; static OSSL_PARAM params[10]; params[n++] = OSSL_PARAM_construct_int("p1", &app_p1); params[n++] = OSSL_PARAM_construct_BN("p3", bignumbin, sizeof(bignumbin)); params[n++] = OSSL_PARAM_construct_utf8_string("p4", app_p4, sizeof(app_p4)); params[n++] = OSSL_PARAM_construct_utf8_string("p5", app_p5, sizeof(app_p5)); /* sizeof(app_p6_init), because we know that's what we're using */ params[n++] = OSSL_PARAM_construct_utf8_ptr("p6", (char **)&app_p6, sizeof(app_p6_init)); params[n++] = OSSL_PARAM_construct_octet_string("foo", &foo, sizeof(foo)); params[n++] = OSSL_PARAM_construct_end(); return params; } struct param_owner_st { OSSL_PARAM *static_params; OSSL_PARAM *(*constructed_params)(void); }; static const struct param_owner_st raw_params = { static_raw_params, NULL }; static const struct param_owner_st api_params = { static_api_params, construct_api_params }; /*- * TESTING * ======= */ /* * Test cases to combine parameters with "provider side" functions */ static struct { const struct provider_dispatch_st *prov; const struct param_owner_st *app; const char *desc; } test_cases[] = { /* Tests within specific methods */ { &provider_raw, &raw_params, "raw provider vs raw params" }, { &provider_api, &api_params, "api provider vs api params" }, /* Mixed methods */ { &provider_raw, &api_params, "raw provider vs api params" }, { &provider_api, &raw_params, "api provider vs raw params" }, }; /* Generic tester of combinations of "providers" and params */ static int test_case_variant(OSSL_PARAM *params, const struct provider_dispatch_st *prov) { BIGNUM *verify_p3 = NULL; void *obj = NULL; int errcnt = 0; OSSL_PARAM *p; /* * Initialize */ if (!TEST_ptr(obj = init_object()) || !TEST_true(BN_hex2bn(&verify_p3, p3_init))) { errcnt++; goto fin; } /* * Get parameters a first time, just to see that getting works and * gets us the values we expect. */ init_app_variables(); if (!TEST_true(prov->get_params(obj, params)) || !TEST_int_eq(app_p1, p1_init) /* "provider" value */ || !TEST_double_eq(app_p2, app_p2_init) /* Should remain untouched */ || !TEST_ptr(p = OSSL_PARAM_locate(params, "p3")) || !TEST_ptr(BN_native2bn(bignumbin, p->return_size, app_p3)) || !TEST_BN_eq(app_p3, verify_p3) /* "provider" value */ || !TEST_str_eq(app_p4, p4_init) /* "provider" value */ || !TEST_ptr(p = OSSL_PARAM_locate(params, "p5")) || !TEST_size_t_eq(p->return_size, sizeof(p5_init) - 1) /* "provider" value */ || !TEST_str_eq(app_p5, p5_init) /* "provider" value */ || !TEST_ptr(p = OSSL_PARAM_locate(params, "p6")) || !TEST_size_t_eq(p->return_size, sizeof(p6_init) - 1) /* "provider" value */ || !TEST_str_eq(app_p6, p6_init) /* "provider" value */ || !TEST_char_eq(foo[0], app_foo_init) /* Should remain untouched */ || !TEST_ptr(p = OSSL_PARAM_locate(params, "foo"))) errcnt++; /* * Set parameters, then sneak into the object itself and check * that its attributes got set (or ignored) properly. */ init_app_variables(); if (!TEST_true(prov->set_params(obj, params))) { errcnt++; } else { struct object_st *sneakpeek = obj; if (!TEST_int_eq(sneakpeek->p1, app_p1) /* app value set */ || !TEST_double_eq(sneakpeek->p2, p2_init) /* Should remain untouched */ || !TEST_BN_eq(sneakpeek->p3, app_p3) /* app value set */ || !TEST_str_eq(sneakpeek->p4, app_p4) /* app value set */ || !TEST_str_eq(sneakpeek->p5, app_p5) /* app value set */ || !TEST_str_eq(sneakpeek->p6, app_p6)) /* app value set */ errcnt++; } /* * Get parameters again, checking that we get different values * than earlier where relevant. */ BN_free(verify_p3); verify_p3 = NULL; if (!TEST_true(BN_hex2bn(&verify_p3, app_p3_init))) { errcnt++; goto fin; } if (!TEST_true(prov->get_params(obj, params)) || !TEST_int_eq(app_p1, app_p1_init) /* app value */ || !TEST_double_eq(app_p2, app_p2_init) /* Should remain untouched */ || !TEST_ptr(p = OSSL_PARAM_locate(params, "p3")) || !TEST_ptr(BN_native2bn(bignumbin, p->return_size, app_p3)) || !TEST_BN_eq(app_p3, verify_p3) /* app value */ || !TEST_str_eq(app_p4, app_p4_init) /* app value */ || !TEST_ptr(p = OSSL_PARAM_locate(params, "p5")) || !TEST_size_t_eq(p->return_size, sizeof(app_p5_init) - 1) /* app value */ || !TEST_str_eq(app_p5, app_p5_init) /* app value */ || !TEST_ptr(p = OSSL_PARAM_locate(params, "p6")) || !TEST_size_t_eq(p->return_size, sizeof(app_p6_init) - 1) /* app value */ || !TEST_str_eq(app_p6, app_p6_init) /* app value */ || !TEST_char_eq(foo[0], app_foo_init) /* Should remain untouched */ || !TEST_ptr(p = OSSL_PARAM_locate(params, "foo"))) errcnt++; fin: BN_free(verify_p3); verify_p3 = NULL; cleanup_app_variables(); cleanup_object(obj); return errcnt == 0; } static int test_case(int i) { TEST_info("Case: %s", test_cases[i].desc); return test_case_variant(test_cases[i].app->static_params, test_cases[i].prov) && (test_cases[i].app->constructed_params == NULL || test_case_variant(test_cases[i].app->constructed_params(), test_cases[i].prov)); } /*- * OSSL_PARAM_allocate_from_text() tests * ===================================== */ static const OSSL_PARAM params_from_text[] = { /* Fixed size buffer */ OSSL_PARAM_int32("int", NULL), OSSL_PARAM_DEFN("short", OSSL_PARAM_INTEGER, NULL, sizeof(int16_t)), OSSL_PARAM_DEFN("ushort", OSSL_PARAM_UNSIGNED_INTEGER, NULL, sizeof(uint16_t)), /* Arbitrary size buffer. Make sure the result fits in a long */ OSSL_PARAM_DEFN("num", OSSL_PARAM_INTEGER, NULL, 0), OSSL_PARAM_DEFN("unum", OSSL_PARAM_UNSIGNED_INTEGER, NULL, 0), OSSL_PARAM_END, }; struct int_from_text_test_st { const char *argname; const char *strval; long int expected_intval; int expected_res; size_t expected_bufsize; }; static struct int_from_text_test_st int_from_text_test_cases[] = { { "int", "", 0, 0, 0 }, { "int", "0", 0, 1, 4 }, { "int", "101", 101, 1, 4 }, { "int", "-102", -102, 1, 4 }, { "int", "12A", 12, 1, 4 }, /* incomplete */ { "int", "0x12B", 0x12B, 1, 4 }, { "hexint", "12C", 0x12C, 1, 4 }, { "hexint", "0x12D", 0, 1, 4 }, /* zero */ /* test check of the target buffer size */ { "int", "0x7fffffff", INT32_MAX, 1, 4 }, { "int", "2147483647", INT32_MAX, 1, 4 }, { "int", "2147483648", 0, 0, 0 }, /* too small buffer */ { "int", "-2147483648", INT32_MIN, 1, 4 }, { "int", "-2147483649", 0, 0, 4 }, /* too small buffer */ { "short", "0x7fff", INT16_MAX, 1, 2 }, { "short", "32767", INT16_MAX, 1, 2 }, { "short", "32768", 0, 0, 0 }, /* too small buffer */ { "ushort", "0xffff", UINT16_MAX, 1, 2 }, { "ushort", "65535", UINT16_MAX, 1, 2 }, { "ushort", "65536", 0, 0, 0 }, /* too small buffer */ /* test check of sign extension in arbitrary size results */ { "num", "0", 0, 1, 1 }, { "num", "0", 0, 1, 1 }, { "num", "0xff", 0xff, 1, 2 }, /* sign extension */ { "num", "-0xff", -0xff, 1, 2 }, /* sign extension */ { "num", "0x7f", 0x7f, 1, 1 }, /* no sign extension */ { "num", "-0x7f", -0x7f, 1, 1 }, /* no sign extension */ { "num", "0x80", 0x80, 1, 2 }, /* sign extension */ { "num", "-0x80", -0x80, 1, 1 }, /* no sign extension */ { "num", "0x81", 0x81, 1, 2 }, /* sign extension */ { "num", "-0x81", -0x81, 1, 2 }, /* sign extension */ { "unum", "0xff", 0xff, 1, 1 }, { "unum", "-0xff", -0xff, 0, 0 }, /* invalid neg number */ { "unum", "0x7f", 0x7f, 1, 1 }, { "unum", "-0x7f", -0x7f, 0, 0 }, /* invalid neg number */ { "unum", "0x80", 0x80, 1, 1 }, { "unum", "-0x80", -0x80, 0, 0 }, /* invalid neg number */ { "unum", "0x81", 0x81, 1, 1 }, { "unum", "-0x81", -0x81, 0, 0 }, /* invalid neg number */ }; static int check_int_from_text(const struct int_from_text_test_st a) { OSSL_PARAM param; long int val = 0; int res; if (!OSSL_PARAM_allocate_from_text(&param, params_from_text, a.argname, a.strval, 0, NULL)) { if (a.expected_res) TEST_error("unexpected OSSL_PARAM_allocate_from_text() return for %s \"%s\"", a.argname, a.strval); return !a.expected_res; } /* For data size zero, OSSL_PARAM_get_long() may crash */ if (param.data_size == 0) { OPENSSL_free(param.data); TEST_error("unexpected zero size for %s \"%s\"", a.argname, a.strval); return 0; } res = OSSL_PARAM_get_long(&param, &val); OPENSSL_free(param.data); if (res ^ a.expected_res) { TEST_error("unexpected OSSL_PARAM_get_long() return for %s \"%s\": " "%d != %d", a.argname, a.strval, a.expected_res, res); return 0; } if (val != a.expected_intval) { TEST_error("unexpected result for %s \"%s\": %li != %li", a.argname, a.strval, a.expected_intval, val); return 0; } if (param.data_size != a.expected_bufsize) { TEST_error("unexpected size for %s \"%s\": %d != %d", a.argname, a.strval, (int)a.expected_bufsize, (int)param.data_size); return 0; } return a.expected_res; } static int test_allocate_from_text(int i) { return check_int_from_text(int_from_text_test_cases[i]); } int setup_tests(void) { ADD_ALL_TESTS(test_case, OSSL_NELEM(test_cases)); ADD_ALL_TESTS(test_allocate_from_text, OSSL_NELEM(int_from_text_test_cases)); return 1; }
./openssl/test/rsa_x931_test.c
/* * Copyright 2022-2023 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include "internal/deprecated.h" #include <openssl/rsa.h> #include <openssl/bn.h> #include "crypto/rsa.h" #include "testutil.h" static OSSL_PROVIDER *prov_null = NULL; static OSSL_LIB_CTX *libctx = NULL; static int test_rsa_x931_keygen(void) { int ret = 0; BIGNUM *e = NULL; RSA *rsa = NULL; ret = TEST_ptr(rsa = ossl_rsa_new_with_ctx(libctx)) && TEST_ptr(e = BN_new()) && TEST_int_eq(BN_set_word(e, RSA_F4), 1) && TEST_int_eq(RSA_X931_generate_key_ex(rsa, 1024, e, NULL), 1); BN_free(e); RSA_free(rsa); return ret; } int setup_tests(void) { if (!test_get_libctx(&libctx, &prov_null, NULL, NULL, NULL)) return 0; ADD_TEST(test_rsa_x931_keygen); return 1; } void cleanup_tests(void) { OSSL_PROVIDER_unload(prov_null); OSSL_LIB_CTX_free(libctx); }
./openssl/test/pairwise_fail_test.c
/* * Copyright 2023 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <openssl/pem.h> #include <openssl/core_names.h> #include <openssl/self_test.h> #include "testutil.h" typedef enum OPTION_choice { OPT_ERR = -1, OPT_EOF = 0, OPT_PROVIDER_NAME, OPT_CONFIG_FILE, OPT_PAIRWISETEST, OPT_DSAPARAM, OPT_TEST_ENUM } OPTION_CHOICE; struct self_test_arg { const char *type; }; static OSSL_LIB_CTX *libctx = NULL; static char *pairwise_name = NULL; static char *dsaparam_file = NULL; static struct self_test_arg self_test_args = { 0 }; const OPTIONS *test_get_options(void) { static const OPTIONS test_options[] = { OPT_TEST_OPTIONS_DEFAULT_USAGE, { "config", OPT_CONFIG_FILE, '<', "The configuration file to use for the libctx" }, { "pairwise", OPT_PAIRWISETEST, 's', "Test keygen pairwise test failures" }, { "dsaparam", OPT_DSAPARAM, 's', "DSA param file" }, { NULL } }; return test_options; } static int self_test_on_pairwise_fail(const OSSL_PARAM params[], void *arg) { struct self_test_arg *args = arg; const OSSL_PARAM *p = NULL; const char *type = NULL, *phase = NULL; p = OSSL_PARAM_locate_const(params, OSSL_PROV_PARAM_SELF_TEST_PHASE); if (p == NULL || p->data_type != OSSL_PARAM_UTF8_STRING) return 0; phase = (const char *)p->data; if (strcmp(phase, OSSL_SELF_TEST_PHASE_CORRUPT) == 0) { p = OSSL_PARAM_locate_const(params, OSSL_PROV_PARAM_SELF_TEST_TYPE); if (p == NULL || p->data_type != OSSL_PARAM_UTF8_STRING) return 0; type = (const char *)p->data; if (strcmp(type, args->type) == 0) return 0; } return 1; } static int setup_selftest_pairwise_failure(const char *type) { int ret = 0; OSSL_PROVIDER *prov = NULL; if (!TEST_ptr(prov = OSSL_PROVIDER_load(libctx, "fips"))) goto err; /* Setup a callback that corrupts the pairwise self tests and causes failures */ self_test_args.type = type; OSSL_SELF_TEST_set_callback(libctx, self_test_on_pairwise_fail, &self_test_args); ret = 1; err: OSSL_PROVIDER_unload(prov); return ret; } static int test_keygen_pairwise_failure(void) { BIO *bio = NULL; EVP_PKEY_CTX *ctx = NULL; EVP_PKEY *pParams = NULL; EVP_PKEY *pkey = NULL; const char *type = OSSL_SELF_TEST_TYPE_PCT; int ret = 0; if (strcmp(pairwise_name, "rsa") == 0) { if (!TEST_true(setup_selftest_pairwise_failure(type))) goto err; if (!TEST_ptr_null(pkey = EVP_PKEY_Q_keygen(libctx, NULL, "RSA", 2048))) goto err; } else if (strncmp(pairwise_name, "ec", 2) == 0) { if (strcmp(pairwise_name, "eckat") == 0) type = OSSL_SELF_TEST_TYPE_PCT_KAT; if (!TEST_true(setup_selftest_pairwise_failure(type))) goto err; if (!TEST_ptr_null(pkey = EVP_PKEY_Q_keygen(libctx, NULL, "EC", "P-256"))) goto err; } else if (strncmp(pairwise_name, "dsa", 3) == 0) { if (strcmp(pairwise_name, "dsakat") == 0) type = OSSL_SELF_TEST_TYPE_PCT_KAT; if (!TEST_true(setup_selftest_pairwise_failure(type))) goto err; if (!TEST_ptr(bio = BIO_new_file(dsaparam_file, "r"))) goto err; if (!TEST_ptr(pParams = PEM_read_bio_Parameters_ex(bio, NULL, libctx, NULL))) goto err; if (!TEST_ptr(ctx = EVP_PKEY_CTX_new_from_pkey(libctx, pParams, NULL))) goto err; if (!TEST_int_eq(EVP_PKEY_keygen_init(ctx), 1)) goto err; if (!TEST_int_le(EVP_PKEY_keygen(ctx, &pkey), 0)) goto err; if (!TEST_ptr_null(pkey)) goto err; } ret = 1; err: EVP_PKEY_free(pkey); EVP_PKEY_CTX_free(ctx); BIO_free(bio); EVP_PKEY_free(pParams); return ret; } int setup_tests(void) { OPTION_CHOICE o; char *config_file = NULL; while ((o = opt_next()) != OPT_EOF) { switch (o) { case OPT_CONFIG_FILE: config_file = opt_arg(); break; case OPT_PAIRWISETEST: pairwise_name = opt_arg(); break; case OPT_DSAPARAM: dsaparam_file = opt_arg(); break; case OPT_TEST_CASES: break; default: case OPT_ERR: return 0; } } libctx = OSSL_LIB_CTX_new(); if (libctx == NULL) return 0; if (!OSSL_LIB_CTX_load_config(libctx, config_file)) { opt_printf_stderr("Failed to load config\n"); return 0; } ADD_TEST(test_keygen_pairwise_failure); return 1; } void cleanup_tests(void) { OSSL_LIB_CTX_free(libctx); }
./openssl/test/crltest.c
/* * Copyright 2015-2022 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include "internal/nelem.h" #include <string.h> #include <openssl/bio.h> #include <openssl/crypto.h> #include <openssl/err.h> #include <openssl/pem.h> #include <openssl/x509.h> #include "testutil.h" #define PARAM_TIME 1474934400 /* Sep 27th, 2016 */ static const char *kCRLTestRoot[] = { "-----BEGIN CERTIFICATE-----\n", "MIIDbzCCAlegAwIBAgIJAODri7v0dDUFMA0GCSqGSIb3DQEBCwUAME4xCzAJBgNV\n", "BAYTAlVTMRMwEQYDVQQIDApDYWxpZm9ybmlhMRYwFAYDVQQHDA1Nb3VudGFpbiBW\n", "aWV3MRIwEAYDVQQKDAlCb3JpbmdTU0wwHhcNMTYwOTI2MTUwNjI2WhcNMjYwOTI0\n", "MTUwNjI2WjBOMQswCQYDVQQGEwJVUzETMBEGA1UECAwKQ2FsaWZvcm5pYTEWMBQG\n", "A1UEBwwNTW91bnRhaW4gVmlldzESMBAGA1UECgwJQm9yaW5nU1NMMIIBIjANBgkq\n", "hkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAo16WiLWZuaymsD8n5SKPmxV1y6jjgr3B\n", "S/dUBpbrzd1aeFzNlI8l2jfAnzUyp+I21RQ+nh/MhqjGElkTtK9xMn1Y+S9GMRh+\n", "5R/Du0iCb1tCZIPY07Tgrb0KMNWe0v2QKVVruuYSgxIWodBfxlKO64Z8AJ5IbnWp\n", "uRqO6rctN9qUoMlTIAB6dL4G0tDJ/PGFWOJYwOMEIX54bly2wgyYJVBKiRRt4f7n\n", "8H922qmvPNA9idmX9G1VAtgV6x97XXi7ULORIQvn9lVQF6nTYDBJhyuPB+mLThbL\n", "P2o9orxGx7aCtnnBZUIxUvHNOI0FaSaZH7Fi0xsZ/GkG2HZe7ImPJwIDAQABo1Aw\n", "TjAdBgNVHQ4EFgQUWPt3N5cZ/CRvubbrkqfBnAqhq94wHwYDVR0jBBgwFoAUWPt3\n", "N5cZ/CRvubbrkqfBnAqhq94wDAYDVR0TBAUwAwEB/zANBgkqhkiG9w0BAQsFAAOC\n", "AQEAORu6M0MOwXy+3VEBwNilfTxyqDfruQsc1jA4PT8Oe8zora1WxE1JB4q2FJOz\n", "EAuM3H/NXvEnBuN+ITvKZAJUfm4NKX97qmjMJwLKWe1gVv+VQTr63aR7mgWJReQN\n", "XdMztlVeZs2dppV6uEg3ia1X0G7LARxGpA9ETbMyCpb39XxlYuTClcbA5ftDN99B\n", "3Xg9KNdd++Ew22O3HWRDvdDpTO/JkzQfzi3sYwUtzMEonENhczJhGf7bQMmvL/w5\n", "24Wxj4Z7KzzWIHsNqE/RIs6RV3fcW61j/mRgW2XyoWnMVeBzvcJr9NXp4VQYmFPw\n", "amd8GKMZQvP0ufGnUn7D7uartA==\n", "-----END CERTIFICATE-----\n", NULL }; static const char *kCRLTestLeaf[] = { "-----BEGIN CERTIFICATE-----\n", "MIIDkDCCAnigAwIBAgICEAAwDQYJKoZIhvcNAQELBQAwTjELMAkGA1UEBhMCVVMx\n", "EzARBgNVBAgMCkNhbGlmb3JuaWExFjAUBgNVBAcMDU1vdW50YWluIFZpZXcxEjAQ\n", "BgNVBAoMCUJvcmluZ1NTTDAeFw0xNjA5MjYxNTA4MzFaFw0xNzA5MjYxNTA4MzFa\n", "MEsxCzAJBgNVBAYTAlVTMRMwEQYDVQQIDApDYWxpZm9ybmlhMRIwEAYDVQQKDAlC\n", "b3JpbmdTU0wxEzARBgNVBAMMCmJvcmluZy5zc2wwggEiMA0GCSqGSIb3DQEBAQUA\n", "A4IBDwAwggEKAoIBAQDc5v1S1M0W+QWM+raWfO0LH8uvqEwuJQgODqMaGnSlWUx9\n", "8iQcnWfjyPja3lWg9K62hSOFDuSyEkysKHDxijz5R93CfLcfnVXjWQDJe7EJTTDP\n", "ozEvxN6RjAeYv7CF000euYr3QT5iyBjg76+bon1p0jHZBJeNPP1KqGYgyxp+hzpx\n", "e0gZmTlGAXd8JQK4v8kpdYwD6PPifFL/jpmQpqOtQmH/6zcLjY4ojmqpEdBqIKIX\n", "+saA29hMq0+NK3K+wgg31RU+cVWxu3tLOIiesETkeDgArjWRS1Vkzbi4v9SJxtNu\n", "OZuAxWiynRJw3JwH/OFHYZIvQqz68ZBoj96cepjPAgMBAAGjezB5MAkGA1UdEwQC\n", "MAAwLAYJYIZIAYb4QgENBB8WHU9wZW5TU0wgR2VuZXJhdGVkIENlcnRpZmljYXRl\n", "MB0GA1UdDgQWBBTGn0OVVh/aoYt0bvEKG+PIERqnDzAfBgNVHSMEGDAWgBRY+3c3\n", "lxn8JG+5tuuSp8GcCqGr3jANBgkqhkiG9w0BAQsFAAOCAQEAd2nM8gCQN2Dc8QJw\n", "XSZXyuI3DBGGCHcay/3iXu0JvTC3EiQo8J6Djv7WLI0N5KH8mkm40u89fJAB2lLZ\n", "ShuHVtcC182bOKnePgwp9CNwQ21p0rDEu/P3X46ZvFgdxx82E9xLa0tBB8PiPDWh\n", "lV16jbaKTgX5AZqjnsyjR5o9/mbZVupZJXx5Syq+XA8qiJfstSYJs4KyKK9UOjql\n", "ICkJVKpi2ahDBqX4MOH4SLfzVk8pqSpviS6yaA1RXqjpkxiN45WWaXDldVHMSkhC\n", "5CNXsXi4b1nAntu89crwSLA3rEwzCWeYj+BX7e1T9rr3oJdwOU/2KQtW1js1yQUG\n", "tjJMFw==\n", "-----END CERTIFICATE-----\n", NULL }; static const char *kBasicCRL[] = { "-----BEGIN X509 CRL-----\n", "MIIBpzCBkAIBATANBgkqhkiG9w0BAQsFADBOMQswCQYDVQQGEwJVUzETMBEGA1UE\n", "CAwKQ2FsaWZvcm5pYTEWMBQGA1UEBwwNTW91bnRhaW4gVmlldzESMBAGA1UECgwJ\n", "Qm9yaW5nU1NMFw0xNjA5MjYxNTEwNTVaFw0xNjEwMjYxNTEwNTVaoA4wDDAKBgNV\n", "HRQEAwIBATANBgkqhkiG9w0BAQsFAAOCAQEAnrBKKgvd9x9zwK9rtUvVeFeJ7+LN\n", "ZEAc+a5oxpPNEsJx6hXoApYEbzXMxuWBQoCs5iEBycSGudct21L+MVf27M38KrWo\n", "eOkq0a2siqViQZO2Fb/SUFR0k9zb8xl86Zf65lgPplALun0bV/HT7MJcl04Tc4os\n", "dsAReBs5nqTGNEd5AlC1iKHvQZkM//MD51DspKnDpsDiUVi54h9C1SpfZmX8H2Vv\n", "diyu0fZ/bPAM3VAGawatf/SyWfBMyKpoPXEG39oAzmjjOj8en82psn7m474IGaho\n", "/vBbhl1ms5qQiLYPjm4YELtnXQoFyC72tBjbdFd/ZE9k4CNKDbxFUXFbkw==\n", "-----END X509 CRL-----\n", NULL }; static const char *kRevokedCRL[] = { "-----BEGIN X509 CRL-----\n", "MIIBvjCBpwIBATANBgkqhkiG9w0BAQsFADBOMQswCQYDVQQGEwJVUzETMBEGA1UE\n", "CAwKQ2FsaWZvcm5pYTEWMBQGA1UEBwwNTW91bnRhaW4gVmlldzESMBAGA1UECgwJ\n", "Qm9yaW5nU1NMFw0xNjA5MjYxNTEyNDRaFw0xNjEwMjYxNTEyNDRaMBUwEwICEAAX\n", "DTE2MDkyNjE1MTIyNlqgDjAMMAoGA1UdFAQDAgECMA0GCSqGSIb3DQEBCwUAA4IB\n", "AQCUGaM4DcWzlQKrcZvI8TMeR8BpsvQeo5BoI/XZu2a8h//PyRyMwYeaOM+3zl0d\n", "sjgCT8b3C1FPgT+P2Lkowv7rJ+FHJRNQkogr+RuqCSPTq65ha4WKlRGWkMFybzVH\n", "NloxC+aU3lgp/NlX9yUtfqYmJek1CDrOOGPrAEAwj1l/BUeYKNGqfBWYJQtPJu+5\n", "OaSvIYGpETCZJscUWODmLEb/O3DM438vLvxonwGqXqS0KX37+CHpUlyhnSovxXxp\n", "Pz4aF+L7OtczxL0GYtD2fR9B7TDMqsNmHXgQrixvvOY7MUdLGbd4RfJL3yA53hyO\n", "xzfKY2TzxLiOmctG0hXFkH5J\n", "-----END X509 CRL-----\n", NULL }; static const char *kBadIssuerCRL[] = { "-----BEGIN X509 CRL-----\n", "MIIBwjCBqwIBATANBgkqhkiG9w0BAQsFADBSMQswCQYDVQQGEwJVUzETMBEGA1UE\n", "CAwKQ2FsaWZvcm5pYTEWMBQGA1UEBwwNTW91bnRhaW4gVmlldzEWMBQGA1UECgwN\n", "Tm90IEJvcmluZ1NTTBcNMTYwOTI2MTUxMjQ0WhcNMTYxMDI2MTUxMjQ0WjAVMBMC\n", "AhAAFw0xNjA5MjYxNTEyMjZaoA4wDDAKBgNVHRQEAwIBAjANBgkqhkiG9w0BAQsF\n", "AAOCAQEAlBmjOA3Fs5UCq3GbyPEzHkfAabL0HqOQaCP12btmvIf/z8kcjMGHmjjP\n", "t85dHbI4Ak/G9wtRT4E/j9i5KML+6yfhRyUTUJKIK/kbqgkj06uuYWuFipURlpDB\n", "cm81RzZaMQvmlN5YKfzZV/clLX6mJiXpNQg6zjhj6wBAMI9ZfwVHmCjRqnwVmCUL\n", "TybvuTmkryGBqREwmSbHFFjg5ixG/ztwzON/Ly78aJ8Bql6ktCl9+/gh6VJcoZ0q\n", "L8V8aT8+Ghfi+zrXM8S9BmLQ9n0fQe0wzKrDZh14EK4sb7zmOzFHSxm3eEXyS98g\n", "Od4cjsc3ymNk88S4jpnLRtIVxZB+SQ==\n", "-----END X509 CRL-----\n", NULL }; /* * This is kBasicCRL but with a critical issuing distribution point * extension. */ static const char *kKnownCriticalCRL[] = { "-----BEGIN X509 CRL-----\n", "MIIBujCBowIBATANBgkqhkiG9w0BAQsFADBOMQswCQYDVQQGEwJVUzETMBEGA1UE\n", "CAwKQ2FsaWZvcm5pYTEWMBQGA1UEBwwNTW91bnRhaW4gVmlldzESMBAGA1UECgwJ\n", "Qm9yaW5nU1NMFw0xNjA5MjYxNTEwNTVaFw0xNjEwMjYxNTEwNTVaoCEwHzAKBgNV\n", "HRQEAwIBATARBgNVHRwBAf8EBzAFoQMBAf8wDQYJKoZIhvcNAQELBQADggEBAA+3\n", "i+5e5Ub8sccfgOBs6WVJFI9c8gvJjrJ8/dYfFIAuCyeocs7DFXn1n13CRZ+URR/Q\n", "mVWgU28+xeusuSPYFpd9cyYTcVyNUGNTI3lwgcE/yVjPaOmzSZKdPakApRxtpKKQ\n", "NN/56aQz3bnT/ZSHQNciRB8U6jiD9V30t0w+FDTpGaG+7bzzUH3UVF9xf9Ctp60A\n", "3mfLe0scas7owSt4AEFuj2SPvcE7yvdOXbu+IEv21cEJUVExJAbhvIweHXh6yRW+\n", "7VVeiNzdIjkZjyTmAzoXGha4+wbxXyBRbfH+XWcO/H+8nwyG8Gktdu2QB9S9nnIp\n", "o/1TpfOMSGhMyMoyPrk=\n", "-----END X509 CRL-----\n", NULL }; /* * kUnknownCriticalCRL is kBasicCRL but with an unknown critical extension. */ static const char *kUnknownCriticalCRL[] = { "-----BEGIN X509 CRL-----\n", "MIIBvDCBpQIBATANBgkqhkiG9w0BAQsFADBOMQswCQYDVQQGEwJVUzETMBEGA1UE\n", "CAwKQ2FsaWZvcm5pYTEWMBQGA1UEBwwNTW91bnRhaW4gVmlldzESMBAGA1UECgwJ\n", "Qm9yaW5nU1NMFw0xNjA5MjYxNTEwNTVaFw0xNjEwMjYxNTEwNTVaoCMwITAKBgNV\n", "HRQEAwIBATATBgwqhkiG9xIEAYS3CQABAf8EADANBgkqhkiG9w0BAQsFAAOCAQEA\n", "GvBP0xqL509InMj/3493YVRV+ldTpBv5uTD6jewzf5XdaxEQ/VjTNe5zKnxbpAib\n", "Kf7cwX0PMSkZjx7k7kKdDlEucwVvDoqC+O9aJcqVmM6GDyNb9xENxd0XCXja6MZC\n", "yVgP4AwLauB2vSiEprYJyI1APph3iAEeDm60lTXX/wBM/tupQDDujKh2GPyvBRfJ\n", "+wEDwGg3ICwvu4gO4zeC5qnFR+bpL9t5tOMAQnVZ0NWv+k7mkd2LbHdD44dxrfXC\n", "nhtfERx99SDmC/jtUAJrGhtCO8acr7exCeYcduN7KKCm91OeCJKK6OzWst0Og1DB\n", "kwzzU2rL3G65CrZ7H0SZsQ==\n", "-----END X509 CRL-----\n", NULL }; /* * kUnknownCriticalCRL2 is kBasicCRL but with a critical issuing distribution * point extension followed by an unknown critical extension */ static const char *kUnknownCriticalCRL2[] = { "-----BEGIN X509 CRL-----\n", "MIIBzzCBuAIBATANBgkqhkiG9w0BAQsFADBOMQswCQYDVQQGEwJVUzETMBEGA1UE\n", "CAwKQ2FsaWZvcm5pYTEWMBQGA1UEBwwNTW91bnRhaW4gVmlldzESMBAGA1UECgwJ\n", "Qm9yaW5nU1NMFw0xNjA5MjYxNTEwNTVaFw0xNjEwMjYxNTEwNTVaoDYwNDAKBgNV\n", "HRQEAwIBATARBgNVHRwBAf8EBzAFoQMBAf8wEwYMKoZIhvcSBAGEtwkAAQH/BAAw\n", "DQYJKoZIhvcNAQELBQADggEBACTcpQC8jXL12JN5YzOcQ64ubQIe0XxRAd30p7qB\n", "BTXGpgqBjrjxRfLms7EBYodEXB2oXMsDq3km0vT1MfYdsDD05S+SQ9CDsq/pUfaC\n", "E2WNI5p8WircRnroYvbN2vkjlRbMd1+yNITohXYXCJwjEOAWOx3XIM10bwPYBv4R\n", "rDobuLHoMgL3yHgMHmAkP7YpkBucNqeBV8cCdeAZLuhXFWi6yfr3r/X18yWbC/r2\n", "2xXdkrSqXLFo7ToyP8YKTgiXpya4x6m53biEYwa2ULlas0igL6DK7wjYZX95Uy7H\n", "GKljn9weIYiMPV/BzGymwfv2EW0preLwtyJNJPaxbdin6Jc=\n", "-----END X509 CRL-----\n", NULL }; static const char **unknown_critical_crls[] = { kUnknownCriticalCRL, kUnknownCriticalCRL2 }; static X509 *test_root = NULL; static X509 *test_leaf = NULL; /* * Glue an array of strings together. Return a BIO and put the string * into |*out| so we can free it. */ static BIO *glue2bio(const char **pem, char **out) { size_t s = 0; *out = glue_strings(pem, &s); return BIO_new_mem_buf(*out, s); } /* * Create a CRL from an array of strings. */ static X509_CRL *CRL_from_strings(const char **pem) { X509_CRL *crl; char *p; BIO *b = glue2bio(pem, &p); if (b == NULL) { OPENSSL_free(p); return NULL; } crl = PEM_read_bio_X509_CRL(b, NULL, NULL, NULL); OPENSSL_free(p); BIO_free(b); return crl; } /* * Create an X509 from an array of strings. */ static X509 *X509_from_strings(const char **pem) { X509 *x; char *p; BIO *b = glue2bio(pem, &p); if (b == NULL) { OPENSSL_free(p); return NULL; } x = PEM_read_bio_X509(b, NULL, NULL, NULL); OPENSSL_free(p); BIO_free(b); return x; } /* * Verify |leaf| certificate (chained up to |root|). |crls| if * not NULL, is a list of CRLs to include in the verification. It is * also free'd before returning, which is kinda yucky but convenient. * Returns a value from X509_V_ERR_xxx or X509_V_OK. */ static int verify(X509 *leaf, X509 *root, STACK_OF(X509_CRL) *crls, unsigned long flags) { X509_STORE_CTX *ctx = X509_STORE_CTX_new(); X509_STORE *store = X509_STORE_new(); X509_VERIFY_PARAM *param = X509_VERIFY_PARAM_new(); STACK_OF(X509) *roots = sk_X509_new_null(); int status = X509_V_ERR_UNSPECIFIED; if (!TEST_ptr(ctx) || !TEST_ptr(store) || !TEST_ptr(param) || !TEST_ptr(roots)) goto err; /* Create a stack; upref the cert because we free it below. */ X509_up_ref(root); if (!TEST_true(sk_X509_push(roots, root)) || !TEST_true(X509_STORE_CTX_init(ctx, store, leaf, NULL))) goto err; X509_STORE_CTX_set0_trusted_stack(ctx, roots); X509_STORE_CTX_set0_crls(ctx, crls); X509_VERIFY_PARAM_set_time(param, PARAM_TIME); if (!TEST_long_eq((long)X509_VERIFY_PARAM_get_time(param), PARAM_TIME)) goto err; X509_VERIFY_PARAM_set_depth(param, 16); if (flags) X509_VERIFY_PARAM_set_flags(param, flags); X509_STORE_CTX_set0_param(ctx, param); param = NULL; ERR_clear_error(); status = X509_verify_cert(ctx) == 1 ? X509_V_OK : X509_STORE_CTX_get_error(ctx); err: OSSL_STACK_OF_X509_free(roots); sk_X509_CRL_pop_free(crls, X509_CRL_free); X509_VERIFY_PARAM_free(param); X509_STORE_CTX_free(ctx); X509_STORE_free(store); return status; } /* * Create a stack of CRL's. Upref each one because we call pop_free on * the stack and need to keep the CRL's around until the test exits. * Yes this crashes on malloc failure; it forces us to debug. */ static STACK_OF(X509_CRL) *make_CRL_stack(X509_CRL *x1, X509_CRL *x2) { STACK_OF(X509_CRL) *sk = sk_X509_CRL_new_null(); sk_X509_CRL_push(sk, x1); X509_CRL_up_ref(x1); if (x2 != NULL) { sk_X509_CRL_push(sk, x2); X509_CRL_up_ref(x2); } return sk; } static int test_basic_crl(void) { X509_CRL *basic_crl = CRL_from_strings(kBasicCRL); X509_CRL *revoked_crl = CRL_from_strings(kRevokedCRL); int r; r = TEST_ptr(basic_crl) && TEST_ptr(revoked_crl) && TEST_int_eq(verify(test_leaf, test_root, make_CRL_stack(basic_crl, NULL), X509_V_FLAG_CRL_CHECK), X509_V_OK) && TEST_int_eq(verify(test_leaf, test_root, make_CRL_stack(basic_crl, revoked_crl), X509_V_FLAG_CRL_CHECK), X509_V_ERR_CERT_REVOKED); X509_CRL_free(basic_crl); X509_CRL_free(revoked_crl); return r; } static int test_no_crl(void) { return TEST_int_eq(verify(test_leaf, test_root, NULL, X509_V_FLAG_CRL_CHECK), X509_V_ERR_UNABLE_TO_GET_CRL); } static int test_bad_issuer_crl(void) { X509_CRL *bad_issuer_crl = CRL_from_strings(kBadIssuerCRL); int r; r = TEST_ptr(bad_issuer_crl) && TEST_int_eq(verify(test_leaf, test_root, make_CRL_stack(bad_issuer_crl, NULL), X509_V_FLAG_CRL_CHECK), X509_V_ERR_UNABLE_TO_GET_CRL); X509_CRL_free(bad_issuer_crl); return r; } static int test_known_critical_crl(void) { X509_CRL *known_critical_crl = CRL_from_strings(kKnownCriticalCRL); int r; r = TEST_ptr(known_critical_crl) && TEST_int_eq(verify(test_leaf, test_root, make_CRL_stack(known_critical_crl, NULL), X509_V_FLAG_CRL_CHECK), X509_V_OK); X509_CRL_free(known_critical_crl); return r; } static int test_unknown_critical_crl(int n) { X509_CRL *unknown_critical_crl = CRL_from_strings(unknown_critical_crls[n]); int r; r = TEST_ptr(unknown_critical_crl) && TEST_int_eq(verify(test_leaf, test_root, make_CRL_stack(unknown_critical_crl, NULL), X509_V_FLAG_CRL_CHECK), X509_V_ERR_UNHANDLED_CRITICAL_CRL_EXTENSION); X509_CRL_free(unknown_critical_crl); return r; } static int test_reuse_crl(void) { X509_CRL *reused_crl = CRL_from_strings(kBasicCRL); char *p; BIO *b = glue2bio(kRevokedCRL, &p); if (b == NULL) { OPENSSL_free(p); X509_CRL_free(reused_crl); return 0; } reused_crl = PEM_read_bio_X509_CRL(b, &reused_crl, NULL, NULL); OPENSSL_free(p); BIO_free(b); X509_CRL_free(reused_crl); return 1; } int setup_tests(void) { if (!TEST_ptr(test_root = X509_from_strings(kCRLTestRoot)) || !TEST_ptr(test_leaf = X509_from_strings(kCRLTestLeaf))) return 0; ADD_TEST(test_no_crl); ADD_TEST(test_basic_crl); ADD_TEST(test_bad_issuer_crl); ADD_TEST(test_known_critical_crl); ADD_ALL_TESTS(test_unknown_critical_crl, OSSL_NELEM(unknown_critical_crls)); ADD_TEST(test_reuse_crl); return 1; } void cleanup_tests(void) { X509_free(test_root); X509_free(test_leaf); }
./openssl/test/params_api_test.c
/* * Copyright 2019-2022 The OpenSSL Project Authors. All Rights Reserved. * Copyright (c) 2019, Oracle and/or its affiliates. All rights reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <string.h> #include "testutil.h" #include "internal/nelem.h" #include "internal/endian.h" #include <openssl/params.h> #include <openssl/bn.h> /* The maximum size of the static buffers used to test most things */ #define MAX_LEN 20 static void swap_copy(unsigned char *out, const void *in, size_t len) { size_t j; for (j = 0; j < len; j++) out[j] = ((unsigned char *)in)[len - j - 1]; } /* * A memory copy that converts the native byte ordering either to or from * little endian format. * * On a little endian machine copying either is just a memcpy(3), on a * big endian machine copying from native to or from little endian involves * byte reversal. */ static void le_copy(unsigned char *out, size_t outlen, const void *in, size_t inlen) { DECLARE_IS_ENDIAN; if (IS_LITTLE_ENDIAN) { memcpy(out, in, outlen); } else { if (outlen < inlen) in = (const char *)in + inlen - outlen; swap_copy(out, in, outlen); } } static const struct { size_t len; unsigned char value[MAX_LEN]; } raw_values[] = { { 1, { 0x47 } }, { 1, { 0xd0 } }, { 2, { 0x01, 0xe9 } }, { 2, { 0xff, 0x53 } }, { 3, { 0x16, 0xff, 0x7c } }, { 3, { 0xa8, 0x9c, 0x0e } }, { 4, { 0x38, 0x27, 0xbf, 0x3b } }, { 4, { 0x9f, 0x26, 0x48, 0x22 } }, { 5, { 0x30, 0x65, 0xfa, 0xe4, 0x81 } }, { 5, { 0xd1, 0x76, 0x01, 0x1b, 0xcd } }, { 8, { 0x59, 0xb2, 0x1a, 0xe9, 0x2a, 0xd8, 0x46, 0x40 } }, { 8, { 0xb4, 0xae, 0xbd, 0xb4, 0xdd, 0x04, 0xb1, 0x4c } }, { 16, { 0x61, 0xe8, 0x7e, 0x31, 0xe9, 0x33, 0x83, 0x3d, 0x87, 0x99, 0xc7, 0xd8, 0x5d, 0xa9, 0x8b, 0x42 } }, { 16, { 0xee, 0x6e, 0x8b, 0xc3, 0xec, 0xcf, 0x37, 0xcc, 0x89, 0x67, 0xf2, 0x68, 0x33, 0xa0, 0x14, 0xb0 } }, }; static int test_param_type_null(OSSL_PARAM *param) { int rc = 0; uint64_t intval; double dval; BIGNUM *bn; switch(param->data_type) { case OSSL_PARAM_INTEGER: if (param->data_size == sizeof(int32_t)) rc = OSSL_PARAM_get_int32(param, (int32_t *)&intval); else if (param->data_size == sizeof(uint64_t)) rc = OSSL_PARAM_get_int64(param, (int64_t *)&intval); else return 1; break; case OSSL_PARAM_UNSIGNED_INTEGER: if (param->data_size == sizeof(uint32_t)) rc = OSSL_PARAM_get_uint32(param, (uint32_t *)&intval); else if (param->data_size == sizeof(uint64_t)) rc = OSSL_PARAM_get_uint64(param, &intval); else rc = OSSL_PARAM_get_BN(param, &bn); break; case OSSL_PARAM_REAL: rc = OSSL_PARAM_get_double(param, &dval); break; case OSSL_PARAM_UTF8_STRING: case OSSL_PARAM_OCTET_STRING: case OSSL_PARAM_UTF8_PTR: case OSSL_PARAM_OCTET_PTR: /* these are allowed to be null */ return 1; break; } /* * we expect the various OSSL_PARAM_get functions above * to return failure when the data is set to NULL */ return rc == 0; } static int test_param_type_extra(OSSL_PARAM *param, const unsigned char *cmp, size_t width) { int32_t i32; int64_t i64; size_t s, sz; unsigned char buf[MAX_LEN]; const int bit32 = param->data_size <= sizeof(int32_t); const int sizet = param->data_size <= sizeof(size_t); const int signd = param->data_type == OSSL_PARAM_INTEGER; /* * Set the unmodified sentinel directly because there is no param array * for these tests. */ param->return_size = OSSL_PARAM_UNMODIFIED; if (signd) { if ((bit32 && !TEST_true(OSSL_PARAM_get_int32(param, &i32))) || !TEST_true(OSSL_PARAM_get_int64(param, &i64))) return 0; } else { if ((bit32 && !TEST_true(OSSL_PARAM_get_uint32(param, (uint32_t *)&i32))) || !TEST_true(OSSL_PARAM_get_uint64(param, (uint64_t *)&i64)) || (sizet && !TEST_true(OSSL_PARAM_get_size_t(param, &s)))) return 0; } if (!TEST_false(OSSL_PARAM_modified(param))) return 0; /* Check signed types */ if (bit32) { le_copy(buf, sizeof(i32), &i32, sizeof(i32)); sz = sizeof(i32) < width ? sizeof(i32) : width; if (!TEST_mem_eq(buf, sz, cmp, sz)) return 0; } le_copy(buf, sizeof(i64), &i64, sizeof(i64)); sz = sizeof(i64) < width ? sizeof(i64) : width; if (!TEST_mem_eq(buf, sz, cmp, sz)) return 0; if (sizet && !signd) { le_copy(buf, sizeof(s), &s, sizeof(s)); sz = sizeof(s) < width ? sizeof(s) : width; if (!TEST_mem_eq(buf, sz, cmp, sz)) return 0; } /* Check a widening write if possible */ if (sizeof(size_t) > width) { if (signd) { if (!TEST_true(OSSL_PARAM_set_int32(param, 12345)) || !TEST_true(OSSL_PARAM_get_int64(param, &i64)) || !TEST_size_t_eq((size_t)i64, 12345)) return 0; } else { if (!TEST_true(OSSL_PARAM_set_uint32(param, 12345)) || !TEST_true(OSSL_PARAM_get_uint64(param, (uint64_t *)&i64)) || !TEST_size_t_eq((size_t)i64, 12345)) return 0; } if (!TEST_true(OSSL_PARAM_modified(param))) return 0; } return 1; } /* * The test cases for each of the bastic integral types are similar. * For each type, a param of that type is set and an attempt to read it * get is made. Finally, the above function is called to verify that * the params can be read as other types. * * All the real work is done via byte buffers which are converted to machine * byte order and to little endian for comparisons. Narrower values are best * compared using little endian because their values and positions don't * change. */ static int test_param_int(int n) { int in, out; unsigned char buf[MAX_LEN], cmp[sizeof(int)]; const size_t len = raw_values[n].len >= sizeof(int) ? sizeof(int) : raw_values[n].len; OSSL_PARAM param = OSSL_PARAM_int("a", NULL); if (!TEST_int_eq(test_param_type_null(&param), 1)) return 0; memset(buf, 0, sizeof(buf)); le_copy(buf, sizeof(in), raw_values[n].value, sizeof(in)); memcpy(&in, buf, sizeof(in)); param.data = &out; if (!TEST_true(OSSL_PARAM_set_int(&param, in))) return 0; le_copy(cmp, sizeof(out), &out, sizeof(out)); if (!TEST_mem_eq(cmp, len, raw_values[n].value, len)) return 0; in = 0; if (!TEST_true(OSSL_PARAM_get_int(&param, &in))) return 0; le_copy(cmp, sizeof(in), &in, sizeof(in)); if (!TEST_mem_eq(cmp, sizeof(in), raw_values[n].value, sizeof(in))) return 0; param.data = &out; return test_param_type_extra(&param, raw_values[n].value, sizeof(int)); } static int test_param_long(int n) { long int in, out; unsigned char buf[MAX_LEN], cmp[sizeof(long int)]; const size_t len = raw_values[n].len >= sizeof(long int) ? sizeof(long int) : raw_values[n].len; OSSL_PARAM param = OSSL_PARAM_long("a", NULL); if (!TEST_int_eq(test_param_type_null(&param), 1)) return 0; memset(buf, 0, sizeof(buf)); le_copy(buf, sizeof(in), raw_values[n].value, sizeof(in)); memcpy(&in, buf, sizeof(in)); param.data = &out; if (!TEST_true(OSSL_PARAM_set_long(&param, in))) return 0; le_copy(cmp, sizeof(out), &out, sizeof(out)); if (!TEST_mem_eq(cmp, len, raw_values[n].value, len)) return 0; in = 0; if (!TEST_true(OSSL_PARAM_get_long(&param, &in))) return 0; le_copy(cmp, sizeof(in), &in, sizeof(in)); if (!TEST_mem_eq(cmp, sizeof(in), raw_values[n].value, sizeof(in))) return 0; param.data = &out; return test_param_type_extra(&param, raw_values[n].value, sizeof(long int)); } static int test_param_uint(int n) { unsigned int in, out; unsigned char buf[MAX_LEN], cmp[sizeof(unsigned int)]; const size_t len = raw_values[n].len >= sizeof(unsigned int) ? sizeof(unsigned int) : raw_values[n].len; OSSL_PARAM param = OSSL_PARAM_uint("a", NULL); if (!TEST_int_eq(test_param_type_null(&param), 1)) return 0; memset(buf, 0, sizeof(buf)); le_copy(buf, sizeof(in), raw_values[n].value, sizeof(in)); memcpy(&in, buf, sizeof(in)); param.data = &out; if (!TEST_true(OSSL_PARAM_set_uint(&param, in))) return 0; le_copy(cmp, sizeof(out), &out, sizeof(out)); if (!TEST_mem_eq(cmp, len, raw_values[n].value, len)) return 0; in = 0; if (!TEST_true(OSSL_PARAM_get_uint(&param, &in))) return 0; le_copy(cmp, sizeof(in), &in, sizeof(in)); if (!TEST_mem_eq(cmp, sizeof(in), raw_values[n].value, sizeof(in))) return 0; param.data = &out; return test_param_type_extra(&param, raw_values[n].value, sizeof(unsigned int)); } static int test_param_ulong(int n) { unsigned long int in, out; unsigned char buf[MAX_LEN], cmp[sizeof(unsigned long int)]; const size_t len = raw_values[n].len >= sizeof(unsigned long int) ? sizeof(unsigned long int) : raw_values[n].len; OSSL_PARAM param = OSSL_PARAM_ulong("a", NULL); if (!TEST_int_eq(test_param_type_null(&param), 1)) return 0; memset(buf, 0, sizeof(buf)); le_copy(buf, sizeof(in), raw_values[n].value, sizeof(in)); memcpy(&in, buf, sizeof(in)); param.data = &out; if (!TEST_true(OSSL_PARAM_set_ulong(&param, in))) return 0; le_copy(cmp, sizeof(out), &out, sizeof(out)); if (!TEST_mem_eq(cmp, len, raw_values[n].value, len)) return 0; in = 0; if (!TEST_true(OSSL_PARAM_get_ulong(&param, &in))) return 0; le_copy(cmp, sizeof(in), &in, sizeof(in)); if (!TEST_mem_eq(cmp, sizeof(in), raw_values[n].value, sizeof(in))) return 0; param.data = &out; return test_param_type_extra(&param, raw_values[n].value, sizeof(unsigned long int)); } static int test_param_int32(int n) { int32_t in, out; unsigned char buf[MAX_LEN], cmp[sizeof(int32_t)]; const size_t len = raw_values[n].len >= sizeof(int32_t) ? sizeof(int32_t) : raw_values[n].len; OSSL_PARAM param = OSSL_PARAM_int32("a", NULL); if (!TEST_int_eq(test_param_type_null(&param), 1)) return 0; memset(buf, 0, sizeof(buf)); le_copy(buf, sizeof(in), raw_values[n].value, sizeof(in)); memcpy(&in, buf, sizeof(in)); param.data = &out; if (!TEST_true(OSSL_PARAM_set_int32(&param, in))) return 0; le_copy(cmp, sizeof(out), &out, sizeof(out)); if (!TEST_mem_eq(cmp, len, raw_values[n].value, len)) return 0; in = 0; if (!TEST_true(OSSL_PARAM_get_int32(&param, &in))) return 0; le_copy(cmp, sizeof(in), &in, sizeof(in)); if (!TEST_mem_eq(cmp, sizeof(in), raw_values[n].value, sizeof(in))) return 0; param.data = &out; return test_param_type_extra(&param, raw_values[n].value, sizeof(int32_t)); } static int test_param_uint32(int n) { uint32_t in, out; unsigned char buf[MAX_LEN], cmp[sizeof(uint32_t)]; const size_t len = raw_values[n].len >= sizeof(uint32_t) ? sizeof(uint32_t) : raw_values[n].len; OSSL_PARAM param = OSSL_PARAM_uint32("a", NULL); if (!TEST_int_eq(test_param_type_null(&param), 1)) return 0; memset(buf, 0, sizeof(buf)); le_copy(buf, sizeof(in), raw_values[n].value, sizeof(in)); memcpy(&in, buf, sizeof(in)); param.data = &out; if (!TEST_true(OSSL_PARAM_set_uint32(&param, in))) return 0; le_copy(cmp, sizeof(out), &out, sizeof(out)); if (!TEST_mem_eq(cmp, len, raw_values[n].value, len)) return 0; in = 0; if (!TEST_true(OSSL_PARAM_get_uint32(&param, &in))) return 0; le_copy(cmp, sizeof(in), &in, sizeof(in)); if (!TEST_mem_eq(cmp, sizeof(in), raw_values[n].value, sizeof(in))) return 0; param.data = &out; return test_param_type_extra(&param, raw_values[n].value, sizeof(uint32_t)); } static int test_param_int64(int n) { int64_t in, out; unsigned char buf[MAX_LEN], cmp[sizeof(int64_t)]; const size_t len = raw_values[n].len >= sizeof(int64_t) ? sizeof(int64_t) : raw_values[n].len; OSSL_PARAM param = OSSL_PARAM_int64("a", NULL); if (!TEST_int_eq(test_param_type_null(&param), 1)) return 0; memset(buf, 0, sizeof(buf)); le_copy(buf, sizeof(in), raw_values[n].value, sizeof(in)); memcpy(&in, buf, sizeof(in)); param.data = &out; if (!TEST_true(OSSL_PARAM_set_int64(&param, in))) return 0; le_copy(cmp, sizeof(out), &out, sizeof(out)); if (!TEST_mem_eq(cmp, len, raw_values[n].value, len)) return 0; in = 0; if (!TEST_true(OSSL_PARAM_get_int64(&param, &in))) return 0; le_copy(cmp, sizeof(in), &in, sizeof(in)); if (!TEST_mem_eq(cmp, sizeof(in), raw_values[n].value, sizeof(in))) return 0; param.data = &out; return test_param_type_extra(&param, raw_values[n].value, sizeof(int64_t)); } static int test_param_uint64(int n) { uint64_t in, out; unsigned char buf[MAX_LEN], cmp[sizeof(uint64_t)]; const size_t len = raw_values[n].len >= sizeof(uint64_t) ? sizeof(uint64_t) : raw_values[n].len; OSSL_PARAM param = OSSL_PARAM_uint64("a", NULL); if (!TEST_int_eq(test_param_type_null(&param), 1)) return 0; memset(buf, 0, sizeof(buf)); le_copy(buf, sizeof(in), raw_values[n].value, sizeof(in)); memcpy(&in, buf, sizeof(in)); param.data = &out; if (!TEST_true(OSSL_PARAM_set_uint64(&param, in))) return 0; le_copy(cmp, sizeof(out), &out, sizeof(out)); if (!TEST_mem_eq(cmp, len, raw_values[n].value, len)) return 0; in = 0; if (!TEST_true(OSSL_PARAM_get_uint64(&param, &in))) return 0; le_copy(cmp, sizeof(in), &in, sizeof(in)); if (!TEST_mem_eq(cmp, sizeof(in), raw_values[n].value, sizeof(in))) return 0; param.data = &out; return test_param_type_extra(&param, raw_values[n].value, sizeof(uint64_t)); } static int test_param_size_t(int n) { size_t in, out; unsigned char buf[MAX_LEN], cmp[sizeof(size_t)]; const size_t len = raw_values[n].len >= sizeof(size_t) ? sizeof(size_t) : raw_values[n].len; OSSL_PARAM param = OSSL_PARAM_size_t("a", NULL); if (!TEST_int_eq(test_param_type_null(&param), 1)) return 0; memset(buf, 0, sizeof(buf)); le_copy(buf, sizeof(in), raw_values[n].value, sizeof(in)); memcpy(&in, buf, sizeof(in)); param.data = &out; if (!TEST_true(OSSL_PARAM_set_size_t(&param, in))) return 0; le_copy(cmp, sizeof(out), &out, sizeof(out)); if (!TEST_mem_eq(cmp, len, raw_values[n].value, len)) return 0; in = 0; if (!TEST_true(OSSL_PARAM_get_size_t(&param, &in))) return 0; le_copy(cmp, sizeof(in), &in, sizeof(in)); if (!TEST_mem_eq(cmp, sizeof(in), raw_values[n].value, sizeof(in))) return 0; param.data = &out; return test_param_type_extra(&param, raw_values[n].value, sizeof(size_t)); } static int test_param_time_t(int n) { time_t in, out; unsigned char buf[MAX_LEN], cmp[sizeof(time_t)]; const size_t len = raw_values[n].len >= sizeof(time_t) ? sizeof(time_t) : raw_values[n].len; OSSL_PARAM param = OSSL_PARAM_time_t("a", NULL); if (!TEST_int_eq(test_param_type_null(&param), 1)) return 0; memset(buf, 0, sizeof(buf)); le_copy(buf, sizeof(in), raw_values[n].value, sizeof(in)); memcpy(&in, buf, sizeof(in)); param.data = &out; if (!TEST_true(OSSL_PARAM_set_time_t(&param, in))) return 0; le_copy(cmp, sizeof(out), &out, sizeof(out)); if (!TEST_mem_eq(cmp, len, raw_values[n].value, len)) return 0; in = 0; if (!TEST_true(OSSL_PARAM_get_time_t(&param, &in))) return 0; le_copy(cmp, sizeof(in), &in, sizeof(in)); if (!TEST_mem_eq(cmp, sizeof(in), raw_values[n].value, sizeof(in))) return 0; param.data = &out; return test_param_type_extra(&param, raw_values[n].value, sizeof(size_t)); } static int test_param_bignum(int n) { unsigned char buf[MAX_LEN], bnbuf[MAX_LEN]; const size_t len = raw_values[n].len; BIGNUM *b = NULL, *c = NULL; OSSL_PARAM param = OSSL_PARAM_DEFN("bn", OSSL_PARAM_UNSIGNED_INTEGER, NULL, 0); int ret = 0; if (!TEST_int_eq(test_param_type_null(&param), 1)) return 0; param.data = bnbuf; param.data_size = sizeof(bnbuf); if (!TEST_ptr(b = BN_lebin2bn(raw_values[n].value, (int)len, NULL))) goto err; if (!TEST_true(OSSL_PARAM_set_BN(&param, b))) goto err; le_copy(buf, len, bnbuf, sizeof(bnbuf)); if (!TEST_mem_eq(raw_values[n].value, len, buf, len)) goto err; param.data_size = param.return_size; if (!TEST_true(OSSL_PARAM_get_BN(&param, &c)) || !TEST_BN_eq(b, c)) goto err; ret = 1; err: BN_free(b); BN_free(c); return ret; } static int test_param_signed_bignum(int n) { unsigned char buf[MAX_LEN], bnbuf[MAX_LEN]; const size_t len = raw_values[n].len; BIGNUM *b = NULL, *c = NULL; OSSL_PARAM param = OSSL_PARAM_DEFN("bn", OSSL_PARAM_INTEGER, NULL, 0); int ret = 0; if (!TEST_int_eq(test_param_type_null(&param), 1)) return 0; param.data = bnbuf; param.data_size = sizeof(bnbuf); if (!TEST_ptr(b = BN_signed_lebin2bn(raw_values[n].value, (int)len, NULL))) goto err; /* raw_values are little endian */ if (!TEST_false(!!(raw_values[n].value[len - 1] & 0x80) ^ BN_is_negative(b))) goto err; if (!TEST_true(OSSL_PARAM_set_BN(&param, b))) goto err; le_copy(buf, len, bnbuf, sizeof(bnbuf)); if (!TEST_mem_eq(raw_values[n].value, len, buf, len)) goto err; param.data_size = param.return_size; if (!TEST_true(OSSL_PARAM_get_BN(&param, &c)) || !TEST_BN_eq(b, c)) { BN_print_fp(stderr, c); goto err; } ret = 1; err: BN_free(b); BN_free(c); return ret; } static int test_param_real(void) { double p; OSSL_PARAM param = OSSL_PARAM_double("r", NULL); if (!TEST_int_eq(test_param_type_null(&param), 1)) return 0; param.data = &p; return TEST_true(OSSL_PARAM_set_double(&param, 3.14159)) && TEST_double_eq(p, 3.14159); } static int test_param_construct(int tstid) { static const char *int_names[] = { "int", "long", "int32", "int64" }; static const char *uint_names[] = { "uint", "ulong", "uint32", "uint64", "size_t" }; static const unsigned char bn_val[16] = { 0xac, 0x75, 0x22, 0x7d, 0x81, 0x06, 0x7a, 0x23, 0xa6, 0xed, 0x87, 0xc7, 0xab, 0xf4, 0x73, 0x22 }; OSSL_PARAM *p = NULL, *p1 = NULL; static const OSSL_PARAM params_empty[] = { OSSL_PARAM_END }; OSSL_PARAM params[20]; char buf[100], buf2[100], *bufp, *bufp2; unsigned char ubuf[100]; void *vp, *vpn = NULL, *vp2; OSSL_PARAM *cp; int i, n = 0, ret = 0; unsigned int u; long int l; unsigned long int ul; int32_t i32; uint32_t u32; int64_t i64; uint64_t u64; size_t j, k, s; double d, d2; BIGNUM *bn = NULL, *bn2 = NULL; params[n++] = OSSL_PARAM_construct_int("int", &i); params[n++] = OSSL_PARAM_construct_uint("uint", &u); params[n++] = OSSL_PARAM_construct_long("long", &l); params[n++] = OSSL_PARAM_construct_ulong("ulong", &ul); params[n++] = OSSL_PARAM_construct_int32("int32", &i32); params[n++] = OSSL_PARAM_construct_int64("int64", &i64); params[n++] = OSSL_PARAM_construct_uint32("uint32", &u32); params[n++] = OSSL_PARAM_construct_uint64("uint64", &u64); params[n++] = OSSL_PARAM_construct_size_t("size_t", &s); params[n++] = OSSL_PARAM_construct_double("double", &d); params[n++] = OSSL_PARAM_construct_BN("bignum", ubuf, sizeof(ubuf)); params[n++] = OSSL_PARAM_construct_utf8_string("utf8str", buf, sizeof(buf)); params[n++] = OSSL_PARAM_construct_octet_string("octstr", buf, sizeof(buf)); params[n++] = OSSL_PARAM_construct_utf8_ptr("utf8ptr", &bufp, 0); params[n++] = OSSL_PARAM_construct_octet_ptr("octptr", &vp, 0); params[n] = OSSL_PARAM_construct_end(); switch (tstid) { case 0: p = params; break; case 1: p = OSSL_PARAM_merge(params, params_empty); break; case 2: p = OSSL_PARAM_dup(params); break; default: p1 = OSSL_PARAM_dup(params); p = OSSL_PARAM_merge(p1, params_empty); break; } /* Search failure */ if (!TEST_ptr_null(OSSL_PARAM_locate(p, "fnord"))) goto err; /* All signed integral types */ for (j = 0; j < OSSL_NELEM(int_names); j++) { if (!TEST_ptr(cp = OSSL_PARAM_locate(p, int_names[j])) || !TEST_true(OSSL_PARAM_set_int32(cp, (int32_t)(3 + j))) || !TEST_true(OSSL_PARAM_get_int64(cp, &i64)) || !TEST_size_t_eq(cp->data_size, cp->return_size) || !TEST_size_t_eq((size_t)i64, 3 + j)) { TEST_note("iteration %zu var %s", j + 1, int_names[j]); goto err; } } /* All unsigned integral types */ for (j = 0; j < OSSL_NELEM(uint_names); j++) { if (!TEST_ptr(cp = OSSL_PARAM_locate(p, uint_names[j])) || !TEST_true(OSSL_PARAM_set_uint32(cp, (uint32_t)(3 + j))) || !TEST_true(OSSL_PARAM_get_uint64(cp, &u64)) || !TEST_size_t_eq(cp->data_size, cp->return_size) || !TEST_size_t_eq((size_t)u64, 3 + j)) { TEST_note("iteration %zu var %s", j + 1, uint_names[j]); goto err; } } /* Real */ if (!TEST_ptr(cp = OSSL_PARAM_locate(p, "double")) || !TEST_true(OSSL_PARAM_set_double(cp, 3.14)) || !TEST_true(OSSL_PARAM_get_double(cp, &d2)) || !TEST_size_t_eq(cp->return_size, sizeof(double)) || !TEST_double_eq(d2, 3.14) || (tstid <= 1 && !TEST_double_eq(d, d2))) goto err; /* UTF8 string */ bufp = NULL; if (!TEST_ptr(cp = OSSL_PARAM_locate(p, "utf8str")) || !TEST_true(OSSL_PARAM_set_utf8_string(cp, "abcdef")) || !TEST_size_t_eq(cp->return_size, sizeof("abcdef") - 1) || !TEST_true(OSSL_PARAM_get_utf8_string(cp, &bufp, 0)) || !TEST_str_eq(bufp, "abcdef")) { OPENSSL_free(bufp); goto err; } OPENSSL_free(bufp); bufp = buf2; if (!TEST_true(OSSL_PARAM_get_utf8_string(cp, &bufp, sizeof(buf2))) || !TEST_str_eq(buf2, "abcdef")) goto err; /* UTF8 pointer */ /* Note that the size of a UTF8 string does *NOT* include the NUL byte */ bufp = buf; if (!TEST_ptr(cp = OSSL_PARAM_locate(p, "utf8ptr")) || !TEST_true(OSSL_PARAM_set_utf8_ptr(cp, "tuvwxyz")) || !TEST_size_t_eq(cp->return_size, sizeof("tuvwxyz") - 1) || !TEST_true(OSSL_PARAM_get_utf8_ptr(cp, (const char **)&bufp2)) || !TEST_str_eq(bufp2, "tuvwxyz") || (tstid <= 1 && !TEST_ptr_eq(bufp2, bufp))) goto err; /* OCTET string */ if (!TEST_ptr(cp = OSSL_PARAM_locate(p, "octstr")) || !TEST_true(OSSL_PARAM_set_octet_string(cp, "abcdefghi", sizeof("abcdefghi"))) || !TEST_size_t_eq(cp->return_size, sizeof("abcdefghi"))) goto err; /* Match the return size to avoid trailing garbage bytes */ cp->data_size = cp->return_size; if (!TEST_true(OSSL_PARAM_get_octet_string(cp, &vpn, 0, &s)) || !TEST_size_t_eq(s, sizeof("abcdefghi")) || !TEST_mem_eq(vpn, sizeof("abcdefghi"), "abcdefghi", sizeof("abcdefghi"))) goto err; vp = buf2; if (!TEST_true(OSSL_PARAM_get_octet_string(cp, &vp, sizeof(buf2), &s)) || !TEST_size_t_eq(s, sizeof("abcdefghi")) || !TEST_mem_eq(vp, sizeof("abcdefghi"), "abcdefghi", sizeof("abcdefghi"))) goto err; /* OCTET pointer */ vp = &l; if (!TEST_ptr(cp = OSSL_PARAM_locate(p, "octptr")) || !TEST_true(OSSL_PARAM_set_octet_ptr(cp, &ul, sizeof(ul))) || !TEST_size_t_eq(cp->return_size, sizeof(ul)) || (tstid <= 1 && !TEST_ptr_eq(vp, &ul))) goto err; /* Match the return size to avoid trailing garbage bytes */ cp->data_size = cp->return_size; if (!TEST_true(OSSL_PARAM_get_octet_ptr(cp, (const void **)&vp2, &k)) || !TEST_size_t_eq(k, sizeof(ul)) || (tstid <= 1 && !TEST_ptr_eq(vp2, vp))) goto err; /* BIGNUM */ if (!TEST_ptr(cp = OSSL_PARAM_locate(p, "bignum")) || !TEST_ptr(bn = BN_lebin2bn(bn_val, (int)sizeof(bn_val), NULL)) || !TEST_true(OSSL_PARAM_set_BN(cp, bn)) || !TEST_size_t_eq(cp->data_size, cp->return_size)) goto err; /* Match the return size to avoid trailing garbage bytes */ cp->data_size = cp->return_size; if (!TEST_true(OSSL_PARAM_get_BN(cp, &bn2)) || !TEST_BN_eq(bn, bn2)) goto err; ret = 1; err: if (p != params) OPENSSL_free(p); OPENSSL_free(p1); OPENSSL_free(vpn); BN_free(bn); BN_free(bn2); return ret; } static int test_param_modified(void) { OSSL_PARAM param[3] = { OSSL_PARAM_int("a", NULL), OSSL_PARAM_int("b", NULL), OSSL_PARAM_END }; int a, b; param->data = &a; param[1].data = &b; if (!TEST_false(OSSL_PARAM_modified(param)) && !TEST_true(OSSL_PARAM_set_int32(param, 1234)) && !TEST_true(OSSL_PARAM_modified(param)) && !TEST_false(OSSL_PARAM_modified(param + 1)) && !TEST_true(OSSL_PARAM_set_int32(param + 1, 1)) && !TEST_true(OSSL_PARAM_modified(param + 1))) return 0; OSSL_PARAM_set_all_unmodified(param); if (!TEST_false(OSSL_PARAM_modified(param)) && !TEST_true(OSSL_PARAM_set_int32(param, 4321)) && !TEST_true(OSSL_PARAM_modified(param)) && !TEST_false(OSSL_PARAM_modified(param + 1)) && !TEST_true(OSSL_PARAM_set_int32(param + 1, 2)) && !TEST_true(OSSL_PARAM_modified(param + 1))) return 0; return 1; } static int test_param_copy_null(void) { int ret, val; int a = 1, b = 2, i = 0; OSSL_PARAM *cp1 = NULL, *cp2 = NULL, *p; OSSL_PARAM param[3]; param[i++] = OSSL_PARAM_construct_int("a", &a); param[i++] = OSSL_PARAM_construct_int("b", &b); param[i] = OSSL_PARAM_construct_end(); ret = TEST_ptr_null(OSSL_PARAM_dup(NULL)) && TEST_ptr(cp1 = OSSL_PARAM_merge(NULL, param)) && TEST_ptr(p = OSSL_PARAM_locate(cp1, "a")) && TEST_true(OSSL_PARAM_get_int(p, &val)) && TEST_int_eq(val, 1) && TEST_ptr(p = OSSL_PARAM_locate(cp1, "b")) && TEST_true(OSSL_PARAM_get_int(p, &val)) && TEST_int_eq(val, 2) && TEST_ptr(cp2 = OSSL_PARAM_merge(param, NULL)) && TEST_ptr(p = OSSL_PARAM_locate(cp2, "a")) && TEST_true(OSSL_PARAM_get_int(p, &val)) && TEST_int_eq(val, 1) && TEST_ptr(p = OSSL_PARAM_locate(cp2, "b")) && TEST_true(OSSL_PARAM_get_int(p, &val)) && TEST_int_eq(val, 2) && TEST_ptr_null(OSSL_PARAM_merge(NULL, NULL)); OSSL_PARAM_free(cp2); OSSL_PARAM_free(cp1); return ret; } int setup_tests(void) { ADD_ALL_TESTS(test_param_int, OSSL_NELEM(raw_values)); ADD_ALL_TESTS(test_param_long, OSSL_NELEM(raw_values)); ADD_ALL_TESTS(test_param_uint, OSSL_NELEM(raw_values)); ADD_ALL_TESTS(test_param_ulong, OSSL_NELEM(raw_values)); ADD_ALL_TESTS(test_param_int32, OSSL_NELEM(raw_values)); ADD_ALL_TESTS(test_param_uint32, OSSL_NELEM(raw_values)); ADD_ALL_TESTS(test_param_size_t, OSSL_NELEM(raw_values)); ADD_ALL_TESTS(test_param_time_t, OSSL_NELEM(raw_values)); ADD_ALL_TESTS(test_param_int64, OSSL_NELEM(raw_values)); ADD_ALL_TESTS(test_param_uint64, OSSL_NELEM(raw_values)); ADD_ALL_TESTS(test_param_bignum, OSSL_NELEM(raw_values)); ADD_ALL_TESTS(test_param_signed_bignum, OSSL_NELEM(raw_values)); ADD_TEST(test_param_real); ADD_ALL_TESTS(test_param_construct, 4); ADD_TEST(test_param_modified); ADD_TEST(test_param_copy_null); return 1; }
./openssl/test/conf_include_test.c
/* * Copyright 2016-2021 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <stdlib.h> #include <string.h> #include <openssl/conf.h> #include <openssl/err.h> #include "testutil.h" #ifdef _WIN32 # include <direct.h> # define DIRSEP "/\\" # ifndef __BORLANDC__ # define chdir _chdir # endif # define DIRSEP_PRESERVE 0 #elif !defined(OPENSSL_NO_POSIX_IO) # include <unistd.h> # ifndef OPENSSL_SYS_VMS # define DIRSEP "/" # define DIRSEP_PRESERVE 0 # else # define DIRSEP "/]:" # define DIRSEP_PRESERVE 1 # endif #else /* the test does not work without chdir() */ # define chdir(x) (-1); # define DIRSEP "/" # define DIRSEP_PRESERVE 0 #endif /* changes path to that of the filename */ static char *change_path(const char *file) { char *s = OPENSSL_strdup(file); char *p = s; char *last = NULL; int ret = 0; char *new_config_name = NULL; if (s == NULL) return NULL; while ((p = strpbrk(p, DIRSEP)) != NULL) { last = p++; } if (last == NULL) goto err; last[DIRSEP_PRESERVE] = 0; TEST_note("changing path to %s", s); ret = chdir(s); if (ret == 0) new_config_name = strdup(last + DIRSEP_PRESERVE + 1); err: OPENSSL_free(s); return new_config_name; } /* * This test program checks the operation of the .include directive. */ static CONF *conf; static BIO *in; static int expect_failure = 0; static int test_providers = 0; static OSSL_LIB_CTX *libctx = NULL; static char *rel_conf_file = NULL; static int test_load_config(void) { long errline; long val; char *str; long err; if (!TEST_int_gt(NCONF_load_bio(conf, in, &errline), 0) || !TEST_int_eq(err = ERR_peek_error(), 0)) { if (expect_failure) return 1; TEST_note("Failure loading the configuration at line %ld", errline); return 0; } if (expect_failure) { TEST_note("Failure expected but did not happen"); return 0; } if (!TEST_int_gt(CONF_modules_load(conf, NULL, 0), 0)) { TEST_note("Failed in CONF_modules_load"); return 0; } /* verify whether CA_default/default_days is set */ val = 0; if (!TEST_int_eq(NCONF_get_number(conf, "CA_default", "default_days", &val), 1) || !TEST_int_eq(val, 365)) { TEST_note("default_days incorrect"); return 0; } /* verify whether req/default_bits is set */ val = 0; if (!TEST_int_eq(NCONF_get_number(conf, "req", "default_bits", &val), 1) || !TEST_int_eq(val, 2048)) { TEST_note("default_bits incorrect"); return 0; } /* verify whether countryName_default is set correctly */ str = NCONF_get_string(conf, "req_distinguished_name", "countryName_default"); if (!TEST_ptr(str) || !TEST_str_eq(str, "AU")) { TEST_note("countryName_default incorrect"); return 0; } if (test_providers != 0) { /* test for `active` directive in configuration file */ val = 0; if (!TEST_int_eq(NCONF_get_number(conf, "null_sect", "activate", &val), 1) || !TEST_int_eq(val, 1)) { TEST_note("null provider not activated"); return 0; } val = 0; if (!TEST_int_eq(NCONF_get_number(conf, "default_sect", "activate", &val), 1) || !TEST_int_eq(val, 1)) { TEST_note("default provider not activated"); return 0; } val = 0; if (!TEST_int_eq(NCONF_get_number(conf, "legacy_sect", "activate", &val), 1) || !TEST_int_eq(val, 1)) { TEST_note("legacy provider not activated"); return 0; } } return 1; } static int test_check_null_numbers(void) { #if defined(_BSD_SOURCE) \ || (defined(_POSIX_C_SOURCE) && _POSIX_C_SOURCE >= 200112L) \ || (defined(_XOPEN_SOURCE) && _XOPEN_SOURCE >= 600) long val = 0; /* Verify that a NULL config with a present environment variable returns * success and the value. */ if (!TEST_int_eq(setenv("FNORD", "123", 1), 0) || !TEST_true(NCONF_get_number(NULL, "missing", "FNORD", &val)) || !TEST_long_eq(val, 123)) { TEST_note("environment variable with NULL conf failed"); return 0; } /* * Verify that a NULL config with a missing environment variable returns * a failure code. */ if (!TEST_int_eq(unsetenv("FNORD"), 0) || !TEST_false(NCONF_get_number(NULL, "missing", "FNORD", &val))) { TEST_note("missing environment variable with NULL conf failed"); return 0; } #endif return 1; } static int test_check_overflow(void) { #if defined(_BSD_SOURCE) \ || (defined(_POSIX_C_SOURCE) && _POSIX_C_SOURCE >= 200112L) \ || (defined(_XOPEN_SOURCE) && _XOPEN_SOURCE >= 600) long val = 0; char max[(sizeof(long) * 8) / 3 + 3]; char *p; p = max + sprintf(max, "0%ld", LONG_MAX) - 1; setenv("FNORD", max, 1); if (!TEST_true(NCONF_get_number(NULL, "missing", "FNORD", &val)) || !TEST_long_eq(val, LONG_MAX)) return 0; while (++*p > '9') *p-- = '0'; setenv("FNORD", max, 1); if (!TEST_false(NCONF_get_number(NULL, "missing", "FNORD", &val))) return 0; #endif return 1; } static int test_available_providers(void) { libctx = OSSL_LIB_CTX_new(); if (!TEST_ptr(libctx)) return 0; if (!TEST_ptr(rel_conf_file) || !OSSL_LIB_CTX_load_config(libctx, rel_conf_file)) { TEST_note("Failed to load config"); return 0; } if (OSSL_PROVIDER_available(libctx, "default") != 1) { TEST_note("Default provider is missing"); return 0; } if (OSSL_PROVIDER_available(libctx, "legacy") != 1) { TEST_note("Legacy provider is missing"); return 0; } return 1; } typedef enum OPTION_choice { OPT_ERR = -1, OPT_EOF = 0, OPT_FAIL, OPT_TEST_PROV, OPT_TEST_ENUM } OPTION_CHOICE; const OPTIONS *test_get_options(void) { static const OPTIONS test_options[] = { OPT_TEST_OPTIONS_WITH_EXTRA_USAGE("conf_file\n"), { "f", OPT_FAIL, '-', "A failure is expected" }, { "providers", OPT_TEST_PROV, '-', "Test for activated default and legacy providers"}, { NULL } }; return test_options; } int setup_tests(void) { char *conf_file = NULL; OPTION_CHOICE o; if (!TEST_ptr(conf = NCONF_new(NULL))) return 0; while ((o = opt_next()) != OPT_EOF) { switch (o) { case OPT_FAIL: expect_failure = 1; break; case OPT_TEST_PROV: test_providers = 1; case OPT_TEST_CASES: break; default: return 0; } } conf_file = test_get_argument(0); if (!TEST_ptr(conf_file) || !TEST_ptr(in = BIO_new_file(conf_file, "r"))) { TEST_note("Unable to open the file argument"); return 0; } /* * For this test we need to chdir as we use relative * path names in the config files. */ rel_conf_file = change_path(conf_file); if (!TEST_ptr(rel_conf_file)) { TEST_note("Unable to change path"); return 0; } ADD_TEST(test_load_config); ADD_TEST(test_check_null_numbers); ADD_TEST(test_check_overflow); if (test_providers != 0) ADD_TEST(test_available_providers); return 1; } void cleanup_tests(void) { OPENSSL_free(rel_conf_file); BIO_vfree(in); NCONF_free(conf); CONF_modules_unload(1); }
./openssl/test/uitest.c
/* * Copyright 2002-2020 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <stdio.h> #include <string.h> #include <openssl/opensslconf.h> #include <openssl/err.h> #include "apps_ui.h" #include "testutil.h" #include <openssl/ui.h> /* Old style PEM password callback */ static int test_pem_password_cb(char *buf, int size, int rwflag, void *userdata) { OPENSSL_strlcpy(buf, (char *)userdata, (size_t)size); return strlen(buf); } /* * Test wrapping old style PEM password callback in a UI method through the * use of UI utility functions */ static int test_old(void) { UI_METHOD *ui_method = NULL; UI *ui = NULL; char defpass[] = "password"; char pass[16]; int ok = 0; if (!TEST_ptr(ui_method = UI_UTIL_wrap_read_pem_callback(test_pem_password_cb, 0)) || !TEST_ptr(ui = UI_new_method(ui_method))) goto err; /* The wrapper passes the UI userdata as the callback userdata param */ UI_add_user_data(ui, defpass); if (UI_add_input_string(ui, "prompt", UI_INPUT_FLAG_DEFAULT_PWD, pass, 0, sizeof(pass) - 1) <= 0) goto err; switch (UI_process(ui)) { case -2: TEST_info("test_old: UI process interrupted or cancelled"); /* fall through */ case -1: goto err; default: break; } if (TEST_str_eq(pass, defpass)) ok = 1; err: UI_free(ui); UI_destroy_method(ui_method); return ok; } /* Test of UI. This uses the UI method defined in apps/apps.c */ static int test_new_ui(void) { PW_CB_DATA cb_data = { "password", "prompt" }; char pass[16]; int ok = 0; (void)setup_ui_method(); if (TEST_int_gt(password_callback(pass, sizeof(pass), 0, &cb_data), 0) && TEST_str_eq(pass, cb_data.password)) ok = 1; destroy_ui_method(); return ok; } int setup_tests(void) { ADD_TEST(test_old); ADD_TEST(test_new_ui); return 1; }
./openssl/test/rsa_complex.c
/* * Copyright 2018 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ /* * Check to see if there is a conflict between complex.h and openssl/rsa.h. * The former defines "I" as a macro and earlier versions of the latter use * for function arguments. * * Will always succeed on djgpp, since its libc does not have complex.h. */ #if !defined(__DJGPP__) # if defined(__STDC_VERSION__) # if __STDC_VERSION__ >= 199901L # include <complex.h> # endif # endif # include <openssl/rsa.h> #endif #include <stdlib.h> int main(int argc, char *argv[]) { /* There are explicitly no run time checks for this one */ return EXIT_SUCCESS; }
./openssl/test/cipher_overhead_test.c
/* * Copyright 2016-2021 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include "internal/nelem.h" #include "testutil.h" #include "../ssl/ssl_local.h" static int cipher_enabled(const SSL_CIPHER *ciph) { /* * ssl_cipher_get_overhead() actually works with AEAD ciphers even if the * underlying implementation is not present. */ if ((ciph->algorithm_mac & SSL_AEAD) != 0) return 1; if (ciph->algorithm_enc != SSL_eNULL && EVP_get_cipherbynid(SSL_CIPHER_get_cipher_nid(ciph)) == NULL) return 0; if (EVP_get_digestbynid(SSL_CIPHER_get_digest_nid(ciph)) == NULL) return 0; return 1; } static int cipher_overhead(void) { int ret = 1, i, n = ssl3_num_ciphers(); const SSL_CIPHER *ciph; size_t mac, in, blk, ex; for (i = 0; i < n; i++) { ciph = ssl3_get_cipher(i); if (!ciph->min_dtls) continue; if (!cipher_enabled(ciph)) { TEST_skip("Skipping disabled cipher %s", ciph->name); continue; } if (!TEST_true(ssl_cipher_get_overhead(ciph, &mac, &in, &blk, &ex))) { TEST_info("Failed getting %s", ciph->name); ret = 0; } else { TEST_info("Cipher %s: %zu %zu %zu %zu", ciph->name, mac, in, blk, ex); } } return ret; } int setup_tests(void) { ADD_TEST(cipher_overhead); return 1; }
./openssl/test/ssl_test.c
/* * Copyright 2016-2023 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <stdio.h> #include <string.h> #include <openssl/conf.h> #include <openssl/err.h> #include <openssl/ssl.h> #include <openssl/provider.h> #include "helpers/handshake.h" #include "helpers/ssl_test_ctx.h" #include "testutil.h" static CONF *conf = NULL; static OSSL_PROVIDER *defctxnull = NULL, *thisprov = NULL; static OSSL_LIB_CTX *libctx = NULL; /* Currently the section names are of the form test-<number>, e.g. test-15. */ #define MAX_TESTCASE_NAME_LENGTH 100 static const char *print_alert(int alert) { return alert ? SSL_alert_desc_string_long(alert) : "no alert"; } static int check_result(HANDSHAKE_RESULT *result, SSL_TEST_CTX *test_ctx) { if (!TEST_int_eq(result->result, test_ctx->expected_result)) { TEST_info("ExpectedResult mismatch: expected %s, got %s.", ssl_test_result_name(test_ctx->expected_result), ssl_test_result_name(result->result)); return 0; } return 1; } static int check_alerts(HANDSHAKE_RESULT *result, SSL_TEST_CTX *test_ctx) { if (!TEST_int_eq(result->client_alert_sent, result->client_alert_received)) { TEST_info("Client sent alert %s but server received %s.", print_alert(result->client_alert_sent), print_alert(result->client_alert_received)); /* * We can't bail here because the peer doesn't always get far enough * to process a received alert. Specifically, in protocol version * negotiation tests, we have the following scenario. * Client supports TLS v1.2 only; Server supports TLS v1.1. * Client proposes TLS v1.2; server responds with 1.1; * Client now sends a protocol alert, using TLS v1.2 in the header. * The server, however, rejects the alert because of version mismatch * in the record layer; therefore, the server appears to never * receive the alert. */ /* return 0; */ } if (!TEST_int_eq(result->server_alert_sent, result->server_alert_received)) { TEST_info("Server sent alert %s but client received %s.", print_alert(result->server_alert_sent), print_alert(result->server_alert_received)); /* return 0; */ } /* Tolerate an alert if one wasn't explicitly specified in the test. */ if (test_ctx->expected_client_alert /* * The info callback alert value is computed as * (s->s3->send_alert[0] << 8) | s->s3->send_alert[1] * where the low byte is the alert code and the high byte is other stuff. */ && (result->client_alert_sent & 0xff) != test_ctx->expected_client_alert) { TEST_error("ClientAlert mismatch: expected %s, got %s.", print_alert(test_ctx->expected_client_alert), print_alert(result->client_alert_sent)); return 0; } if (test_ctx->expected_server_alert && (result->server_alert_sent & 0xff) != test_ctx->expected_server_alert) { TEST_error("ServerAlert mismatch: expected %s, got %s.", print_alert(test_ctx->expected_server_alert), print_alert(result->server_alert_sent)); return 0; } if (!TEST_int_le(result->client_num_fatal_alerts_sent, 1)) return 0; if (!TEST_int_le(result->server_num_fatal_alerts_sent, 1)) return 0; return 1; } static int check_protocol(HANDSHAKE_RESULT *result, SSL_TEST_CTX *test_ctx) { if (!TEST_int_eq(result->client_protocol, result->server_protocol)) { TEST_info("Client has protocol %s but server has %s.", ssl_protocol_name(result->client_protocol), ssl_protocol_name(result->server_protocol)); return 0; } if (test_ctx->expected_protocol) { if (!TEST_int_eq(result->client_protocol, test_ctx->expected_protocol)) { TEST_info("Protocol mismatch: expected %s, got %s.\n", ssl_protocol_name(test_ctx->expected_protocol), ssl_protocol_name(result->client_protocol)); return 0; } } return 1; } static int check_servername(HANDSHAKE_RESULT *result, SSL_TEST_CTX *test_ctx) { if (!TEST_int_eq(result->servername, test_ctx->expected_servername)) { TEST_info("Client ServerName mismatch, expected %s, got %s.", ssl_servername_name(test_ctx->expected_servername), ssl_servername_name(result->servername)); return 0; } return 1; } static int check_session_ticket(HANDSHAKE_RESULT *result, SSL_TEST_CTX *test_ctx) { if (test_ctx->session_ticket_expected == SSL_TEST_SESSION_TICKET_IGNORE) return 1; if (!TEST_int_eq(result->session_ticket, test_ctx->session_ticket_expected)) { TEST_info("Client SessionTicketExpected mismatch, expected %s, got %s.", ssl_session_ticket_name(test_ctx->session_ticket_expected), ssl_session_ticket_name(result->session_ticket)); return 0; } return 1; } static int check_session_id(HANDSHAKE_RESULT *result, SSL_TEST_CTX *test_ctx) { if (test_ctx->session_id_expected == SSL_TEST_SESSION_ID_IGNORE) return 1; if (!TEST_int_eq(result->session_id, test_ctx->session_id_expected)) { TEST_info("Client SessionIdExpected mismatch, expected %s, got %s\n.", ssl_session_id_name(test_ctx->session_id_expected), ssl_session_id_name(result->session_id)); return 0; } return 1; } static int check_compression(HANDSHAKE_RESULT *result, SSL_TEST_CTX *test_ctx) { if (!TEST_int_eq(result->compression, test_ctx->compression_expected)) return 0; return 1; } #ifndef OPENSSL_NO_NEXTPROTONEG static int check_npn(HANDSHAKE_RESULT *result, SSL_TEST_CTX *test_ctx) { int ret = 1; if (!TEST_str_eq(result->client_npn_negotiated, result->server_npn_negotiated)) ret = 0; if (!TEST_str_eq(test_ctx->expected_npn_protocol, result->client_npn_negotiated)) ret = 0; return ret; } #endif static int check_alpn(HANDSHAKE_RESULT *result, SSL_TEST_CTX *test_ctx) { int ret = 1; if (!TEST_str_eq(result->client_alpn_negotiated, result->server_alpn_negotiated)) ret = 0; if (!TEST_str_eq(test_ctx->expected_alpn_protocol, result->client_alpn_negotiated)) ret = 0; return ret; } static int check_session_ticket_app_data(HANDSHAKE_RESULT *result, SSL_TEST_CTX *test_ctx) { size_t result_len = 0; size_t expected_len = 0; /* consider empty and NULL strings to be the same */ if (result->result_session_ticket_app_data != NULL) result_len = strlen(result->result_session_ticket_app_data); if (test_ctx->expected_session_ticket_app_data != NULL) expected_len = strlen(test_ctx->expected_session_ticket_app_data); if (result_len == 0 && expected_len == 0) return 1; if (!TEST_str_eq(result->result_session_ticket_app_data, test_ctx->expected_session_ticket_app_data)) return 0; return 1; } static int check_resumption(HANDSHAKE_RESULT *result, SSL_TEST_CTX *test_ctx) { if (!TEST_int_eq(result->client_resumed, result->server_resumed)) return 0; if (!TEST_int_eq(result->client_resumed, test_ctx->resumption_expected)) return 0; return 1; } static int check_nid(const char *name, int expected_nid, int nid) { if (expected_nid == 0 || expected_nid == nid) return 1; TEST_error("%s type mismatch, %s vs %s\n", name, OBJ_nid2ln(expected_nid), nid == NID_undef ? "absent" : OBJ_nid2ln(nid)); return 0; } static void print_ca_names(STACK_OF(X509_NAME) *names) { int i; if (names == NULL || sk_X509_NAME_num(names) == 0) { TEST_note(" <empty>"); return; } for (i = 0; i < sk_X509_NAME_num(names); i++) { X509_NAME_print_ex(bio_err, sk_X509_NAME_value(names, i), 4, XN_FLAG_ONELINE); BIO_puts(bio_err, "\n"); } } static int check_ca_names(const char *name, STACK_OF(X509_NAME) *expected_names, STACK_OF(X509_NAME) *names) { int i; if (expected_names == NULL) return 1; if (names == NULL || sk_X509_NAME_num(names) == 0) { if (TEST_int_eq(sk_X509_NAME_num(expected_names), 0)) return 1; goto err; } if (sk_X509_NAME_num(names) != sk_X509_NAME_num(expected_names)) goto err; for (i = 0; i < sk_X509_NAME_num(names); i++) { if (!TEST_int_eq(X509_NAME_cmp(sk_X509_NAME_value(names, i), sk_X509_NAME_value(expected_names, i)), 0)) { goto err; } } return 1; err: TEST_info("%s: list mismatch", name); TEST_note("Expected Names:"); print_ca_names(expected_names); TEST_note("Received Names:"); print_ca_names(names); return 0; } static int check_tmp_key(HANDSHAKE_RESULT *result, SSL_TEST_CTX *test_ctx) { return check_nid("Tmp key", test_ctx->expected_tmp_key_type, result->tmp_key_type); } static int check_server_cert_type(HANDSHAKE_RESULT *result, SSL_TEST_CTX *test_ctx) { return check_nid("Server certificate", test_ctx->expected_server_cert_type, result->server_cert_type); } static int check_server_sign_hash(HANDSHAKE_RESULT *result, SSL_TEST_CTX *test_ctx) { return check_nid("Server signing hash", test_ctx->expected_server_sign_hash, result->server_sign_hash); } static int check_server_sign_type(HANDSHAKE_RESULT *result, SSL_TEST_CTX *test_ctx) { return check_nid("Server signing", test_ctx->expected_server_sign_type, result->server_sign_type); } static int check_server_ca_names(HANDSHAKE_RESULT *result, SSL_TEST_CTX *test_ctx) { return check_ca_names("Server CA names", test_ctx->expected_server_ca_names, result->server_ca_names); } static int check_client_cert_type(HANDSHAKE_RESULT *result, SSL_TEST_CTX *test_ctx) { return check_nid("Client certificate", test_ctx->expected_client_cert_type, result->client_cert_type); } static int check_client_sign_hash(HANDSHAKE_RESULT *result, SSL_TEST_CTX *test_ctx) { return check_nid("Client signing hash", test_ctx->expected_client_sign_hash, result->client_sign_hash); } static int check_client_sign_type(HANDSHAKE_RESULT *result, SSL_TEST_CTX *test_ctx) { return check_nid("Client signing", test_ctx->expected_client_sign_type, result->client_sign_type); } static int check_client_ca_names(HANDSHAKE_RESULT *result, SSL_TEST_CTX *test_ctx) { return check_ca_names("Client CA names", test_ctx->expected_client_ca_names, result->client_ca_names); } static int check_cipher(HANDSHAKE_RESULT *result, SSL_TEST_CTX *test_ctx) { if (test_ctx->expected_cipher == NULL) return 1; if (!TEST_ptr(result->cipher)) return 0; if (!TEST_str_eq(test_ctx->expected_cipher, result->cipher)) return 0; return 1; } /* * This could be further simplified by constructing an expected * HANDSHAKE_RESULT, and implementing comparison methods for * its fields. */ static int check_test(HANDSHAKE_RESULT *result, SSL_TEST_CTX *test_ctx) { int ret = 1; ret &= check_result(result, test_ctx); ret &= check_alerts(result, test_ctx); if (result->result == SSL_TEST_SUCCESS) { ret &= check_protocol(result, test_ctx); ret &= check_servername(result, test_ctx); ret &= check_session_ticket(result, test_ctx); ret &= check_compression(result, test_ctx); ret &= check_session_id(result, test_ctx); ret &= (result->session_ticket_do_not_call == 0); #ifndef OPENSSL_NO_NEXTPROTONEG ret &= check_npn(result, test_ctx); #endif ret &= check_cipher(result, test_ctx); ret &= check_alpn(result, test_ctx); ret &= check_session_ticket_app_data(result, test_ctx); ret &= check_resumption(result, test_ctx); ret &= check_tmp_key(result, test_ctx); ret &= check_server_cert_type(result, test_ctx); ret &= check_server_sign_hash(result, test_ctx); ret &= check_server_sign_type(result, test_ctx); ret &= check_server_ca_names(result, test_ctx); ret &= check_client_cert_type(result, test_ctx); ret &= check_client_sign_hash(result, test_ctx); ret &= check_client_sign_type(result, test_ctx); ret &= check_client_ca_names(result, test_ctx); } return ret; } static int test_handshake(int idx) { int ret = 0; SSL_CTX *server_ctx = NULL, *server2_ctx = NULL, *client_ctx = NULL, *resume_server_ctx = NULL, *resume_client_ctx = NULL; SSL_TEST_CTX *test_ctx = NULL; HANDSHAKE_RESULT *result = NULL; char test_app[MAX_TESTCASE_NAME_LENGTH]; BIO_snprintf(test_app, sizeof(test_app), "test-%d", idx); test_ctx = SSL_TEST_CTX_create(conf, test_app, libctx); if (!TEST_ptr(test_ctx)) goto err; /* Verify that the FIPS provider supports this test */ if (test_ctx->fips_version != NULL && !fips_provider_version_match(libctx, test_ctx->fips_version)) { ret = TEST_skip("FIPS provider unable to run this test"); goto err; } #ifndef OPENSSL_NO_DTLS if (test_ctx->method == SSL_TEST_METHOD_DTLS) { server_ctx = SSL_CTX_new_ex(libctx, NULL, DTLS_server_method()); if (!TEST_true(SSL_CTX_set_options(server_ctx, SSL_OP_ALLOW_CLIENT_RENEGOTIATION)) || !TEST_true(SSL_CTX_set_max_proto_version(server_ctx, 0))) goto err; if (test_ctx->extra.server.servername_callback != SSL_TEST_SERVERNAME_CB_NONE) { if (!TEST_ptr(server2_ctx = SSL_CTX_new_ex(libctx, NULL, DTLS_server_method())) || !TEST_true(SSL_CTX_set_options(server2_ctx, SSL_OP_ALLOW_CLIENT_RENEGOTIATION))) goto err; } client_ctx = SSL_CTX_new_ex(libctx, NULL, DTLS_client_method()); if (!TEST_true(SSL_CTX_set_max_proto_version(client_ctx, 0))) goto err; if (test_ctx->handshake_mode == SSL_TEST_HANDSHAKE_RESUME) { resume_server_ctx = SSL_CTX_new_ex(libctx, NULL, DTLS_server_method()); if (!TEST_true(SSL_CTX_set_max_proto_version(resume_server_ctx, 0)) || !TEST_true(SSL_CTX_set_options(resume_server_ctx, SSL_OP_ALLOW_CLIENT_RENEGOTIATION))) goto err; resume_client_ctx = SSL_CTX_new_ex(libctx, NULL, DTLS_client_method()); if (!TEST_true(SSL_CTX_set_max_proto_version(resume_client_ctx, 0))) goto err; if (!TEST_ptr(resume_server_ctx) || !TEST_ptr(resume_client_ctx)) goto err; } } #endif if (test_ctx->method == SSL_TEST_METHOD_TLS) { #if !defined(OPENSSL_NO_TLS1_3) \ && defined(OPENSSL_NO_EC) \ && defined(OPENSSL_NO_DH) /* Without ec or dh there are no built-in groups for TLSv1.3 */ int maxversion = TLS1_2_VERSION; #else int maxversion = 0; #endif server_ctx = SSL_CTX_new_ex(libctx, NULL, TLS_server_method()); if (!TEST_true(SSL_CTX_set_max_proto_version(server_ctx, maxversion)) || !TEST_true(SSL_CTX_set_options(server_ctx, SSL_OP_ALLOW_CLIENT_RENEGOTIATION))) goto err; /* SNI on resumption isn't supported/tested yet. */ if (test_ctx->extra.server.servername_callback != SSL_TEST_SERVERNAME_CB_NONE) { if (!TEST_ptr(server2_ctx = SSL_CTX_new_ex(libctx, NULL, TLS_server_method())) || !TEST_true(SSL_CTX_set_options(server2_ctx, SSL_OP_ALLOW_CLIENT_RENEGOTIATION))) goto err; if (!TEST_true(SSL_CTX_set_max_proto_version(server2_ctx, maxversion))) goto err; } client_ctx = SSL_CTX_new_ex(libctx, NULL, TLS_client_method()); if (!TEST_true(SSL_CTX_set_max_proto_version(client_ctx, maxversion))) goto err; if (test_ctx->handshake_mode == SSL_TEST_HANDSHAKE_RESUME) { resume_server_ctx = SSL_CTX_new_ex(libctx, NULL, TLS_server_method()); if (!TEST_true(SSL_CTX_set_max_proto_version(resume_server_ctx, maxversion)) || !TEST_true(SSL_CTX_set_options(resume_server_ctx, SSL_OP_ALLOW_CLIENT_RENEGOTIATION))) goto err; resume_client_ctx = SSL_CTX_new_ex(libctx, NULL, TLS_client_method()); if (!TEST_true(SSL_CTX_set_max_proto_version(resume_client_ctx, maxversion))) goto err; if (!TEST_ptr(resume_server_ctx) || !TEST_ptr(resume_client_ctx)) goto err; } } #ifdef OPENSSL_NO_AUTOLOAD_CONFIG if (!TEST_true(OPENSSL_init_ssl(OPENSSL_INIT_LOAD_CONFIG, NULL))) goto err; #endif if (!TEST_ptr(server_ctx) || !TEST_ptr(client_ctx) || !TEST_int_gt(CONF_modules_load(conf, test_app, 0), 0)) goto err; if (!SSL_CTX_config(server_ctx, "server") || !SSL_CTX_config(client_ctx, "client")) { goto err; } if (server2_ctx != NULL && !SSL_CTX_config(server2_ctx, "server2")) goto err; if (resume_server_ctx != NULL && !SSL_CTX_config(resume_server_ctx, "resume-server")) goto err; if (resume_client_ctx != NULL && !SSL_CTX_config(resume_client_ctx, "resume-client")) goto err; result = do_handshake(server_ctx, server2_ctx, client_ctx, resume_server_ctx, resume_client_ctx, test_ctx); if (result != NULL) ret = check_test(result, test_ctx); err: CONF_modules_unload(0); SSL_CTX_free(server_ctx); SSL_CTX_free(server2_ctx); SSL_CTX_free(client_ctx); SSL_CTX_free(resume_server_ctx); SSL_CTX_free(resume_client_ctx); SSL_TEST_CTX_free(test_ctx); HANDSHAKE_RESULT_free(result); return ret; } #define USAGE "conf_file module_name [module_conf_file]\n" OPT_TEST_DECLARE_USAGE(USAGE) int setup_tests(void) { long num_tests; if (!test_skip_common_options()) { TEST_error("Error parsing test options\n"); return 0; } if (!TEST_ptr(conf = NCONF_new(NULL)) /* argv[1] should point to the test conf file */ || !TEST_int_gt(NCONF_load(conf, test_get_argument(0), NULL), 0) || !TEST_int_ne(NCONF_get_number_e(conf, NULL, "num_tests", &num_tests), 0)) { TEST_error("usage: ssl_test %s", USAGE); return 0; } if (!test_arg_libctx(&libctx, &defctxnull, &thisprov, 1, USAGE)) return 0; ADD_ALL_TESTS(test_handshake, (int)num_tests); return 1; } void cleanup_tests(void) { NCONF_free(conf); OSSL_PROVIDER_unload(defctxnull); OSSL_PROVIDER_unload(thisprov); OSSL_LIB_CTX_free(libctx); }
./openssl/test/simpledynamic.c
/* * Copyright 2016-2021 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <string.h> #include <stdlib.h> /* For NULL */ #include <openssl/macros.h> /* For NON_EMPTY_TRANSLATION_UNIT */ #include <openssl/e_os2.h> #include "simpledynamic.h" #if defined(DSO_DLFCN) || defined(DSO_VMS) int sd_load(const char *filename, SD *lib, int type) { int dl_flags = type; #ifdef _AIX if (filename[strlen(filename) - 1] == ')') dl_flags |= RTLD_MEMBER; #endif *lib = dlopen(filename, dl_flags); return *lib == NULL ? 0 : 1; } int sd_sym(SD lib, const char *symname, SD_SYM *sym) { *sym = dlsym(lib, symname); return *sym != NULL; } int sd_close(SD lib) { return dlclose(lib) != 0 ? 0 : 1; } const char *sd_error(void) { return dlerror(); } #elif defined(DSO_WIN32) int sd_load(const char *filename, SD *lib, ossl_unused int type) { *lib = LoadLibraryA(filename); return *lib == NULL ? 0 : 1; } int sd_sym(SD lib, const char *symname, SD_SYM *sym) { *sym = (SD_SYM)GetProcAddress(lib, symname); return *sym != NULL; } int sd_close(SD lib) { return FreeLibrary(lib) == 0 ? 0 : 1; } const char *sd_error(void) { static char buffer[255]; buffer[0] = '\0'; FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM, NULL, GetLastError(), 0, buffer, sizeof(buffer), NULL); return buffer; } #else NON_EMPTY_TRANSLATION_UNIT #endif
./openssl/test/bio_core_test.c
/* * Copyright 2021-2023 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <string.h> #include <openssl/bio.h> #include "testutil.h" struct ossl_core_bio_st { int dummy; BIO *bio; }; static int tst_bio_core_read_ex(OSSL_CORE_BIO *bio, char *data, size_t data_len, size_t *bytes_read) { return BIO_read_ex(bio->bio, data, data_len, bytes_read); } static int tst_bio_core_write_ex(OSSL_CORE_BIO *bio, const char *data, size_t data_len, size_t *written) { return BIO_write_ex(bio->bio, data, data_len, written); } static int tst_bio_core_gets(OSSL_CORE_BIO *bio, char *buf, int size) { return BIO_gets(bio->bio, buf, size); } static int tst_bio_core_puts(OSSL_CORE_BIO *bio, const char *str) { return BIO_puts(bio->bio, str); } static long tst_bio_core_ctrl(OSSL_CORE_BIO *bio, int cmd, long num, void *ptr) { return BIO_ctrl(bio->bio, cmd, num, ptr); } static int tst_bio_core_up_ref(OSSL_CORE_BIO *bio) { return BIO_up_ref(bio->bio); } static int tst_bio_core_free(OSSL_CORE_BIO *bio) { return BIO_free(bio->bio); } static const OSSL_DISPATCH biocbs[] = { { OSSL_FUNC_BIO_READ_EX, (void (*)(void))tst_bio_core_read_ex }, { OSSL_FUNC_BIO_WRITE_EX, (void (*)(void))tst_bio_core_write_ex }, { OSSL_FUNC_BIO_GETS, (void (*)(void))tst_bio_core_gets }, { OSSL_FUNC_BIO_PUTS, (void (*)(void))tst_bio_core_puts }, { OSSL_FUNC_BIO_CTRL, (void (*)(void))tst_bio_core_ctrl }, { OSSL_FUNC_BIO_UP_REF, (void (*)(void))tst_bio_core_up_ref }, { OSSL_FUNC_BIO_FREE, (void (*)(void))tst_bio_core_free }, OSSL_DISPATCH_END }; static int test_bio_core(void) { BIO *cbio = NULL, *cbiobad = NULL; OSSL_LIB_CTX *libctx = OSSL_LIB_CTX_new_from_dispatch(NULL, biocbs); int testresult = 0; OSSL_CORE_BIO corebio; const char *msg = "Hello world"; char buf[80]; corebio.bio = BIO_new(BIO_s_mem()); if (!TEST_ptr(corebio.bio) || !TEST_ptr(libctx) /* * Attempting to create a corebio in a libctx that was not * created via OSSL_LIB_CTX_new_from_dispatch() should fail. */ || !TEST_ptr_null((cbiobad = BIO_new_from_core_bio(NULL, &corebio))) || !TEST_ptr((cbio = BIO_new_from_core_bio(libctx, &corebio)))) goto err; if (!TEST_int_gt(BIO_puts(corebio.bio, msg), 0) /* Test a ctrl via BIO_eof */ || !TEST_false(BIO_eof(cbio)) || !TEST_int_gt(BIO_gets(cbio, buf, sizeof(buf)), 0) || !TEST_true(BIO_eof(cbio)) || !TEST_str_eq(buf, msg)) goto err; buf[0] = '\0'; if (!TEST_int_gt(BIO_write(cbio, msg, strlen(msg) + 1), 0) || !TEST_int_gt(BIO_read(cbio, buf, sizeof(buf)), 0) || !TEST_str_eq(buf, msg)) goto err; testresult = 1; err: BIO_free(cbiobad); BIO_free(cbio); BIO_free(corebio.bio); OSSL_LIB_CTX_free(libctx); return testresult; } int setup_tests(void) { if (!test_skip_common_options()) { TEST_error("Error parsing test options\n"); return 0; } ADD_TEST(test_bio_core); return 1; }
./openssl/test/ectest.c
/* * Copyright 2001-2023 The OpenSSL Project Authors. All Rights Reserved. * Copyright (c) 2002, Oracle and/or its affiliates. All rights reserved * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ /* * EC_KEY low level APIs are deprecated for public use, but still ok for * internal use. */ #include "internal/deprecated.h" #include <string.h> #include "internal/nelem.h" #include "testutil.h" #include <openssl/ec.h> #ifndef OPENSSL_NO_ENGINE # include <openssl/engine.h> #endif #include <openssl/err.h> #include <openssl/obj_mac.h> #include <openssl/objects.h> #include <openssl/rand.h> #include <openssl/bn.h> #include <openssl/opensslconf.h> #include <openssl/core_names.h> #include <openssl/param_build.h> #include <openssl/evp.h> static size_t crv_len = 0; static EC_builtin_curve *curves = NULL; /* test multiplication with group order, long and negative scalars */ static int group_order_tests(EC_GROUP *group) { BIGNUM *n1 = NULL, *n2 = NULL, *order = NULL; EC_POINT *P = NULL, *Q = NULL, *R = NULL, *S = NULL; const EC_POINT *G = NULL; BN_CTX *ctx = NULL; int i = 0, r = 0; if (!TEST_ptr(n1 = BN_new()) || !TEST_ptr(n2 = BN_new()) || !TEST_ptr(order = BN_new()) || !TEST_ptr(ctx = BN_CTX_new()) || !TEST_ptr(G = EC_GROUP_get0_generator(group)) || !TEST_ptr(P = EC_POINT_new(group)) || !TEST_ptr(Q = EC_POINT_new(group)) || !TEST_ptr(R = EC_POINT_new(group)) || !TEST_ptr(S = EC_POINT_new(group))) goto err; if (!TEST_true(EC_GROUP_get_order(group, order, ctx)) || !TEST_true(EC_POINT_mul(group, Q, order, NULL, NULL, ctx)) || !TEST_true(EC_POINT_is_at_infinity(group, Q)) #ifndef OPENSSL_NO_DEPRECATED_3_0 || !TEST_true(EC_GROUP_precompute_mult(group, ctx)) #endif || !TEST_true(EC_POINT_mul(group, Q, order, NULL, NULL, ctx)) || !TEST_true(EC_POINT_is_at_infinity(group, Q)) || !TEST_true(EC_POINT_copy(P, G)) || !TEST_true(BN_one(n1)) || !TEST_true(EC_POINT_mul(group, Q, n1, NULL, NULL, ctx)) || !TEST_int_eq(0, EC_POINT_cmp(group, Q, P, ctx)) || !TEST_true(BN_sub(n1, order, n1)) || !TEST_true(EC_POINT_mul(group, Q, n1, NULL, NULL, ctx)) || !TEST_true(EC_POINT_invert(group, Q, ctx)) || !TEST_int_eq(0, EC_POINT_cmp(group, Q, P, ctx))) goto err; for (i = 1; i <= 2; i++) { #ifndef OPENSSL_NO_DEPRECATED_3_0 const BIGNUM *scalars[6]; const EC_POINT *points[6]; #endif if (!TEST_true(BN_set_word(n1, i)) /* * If i == 1, P will be the predefined generator for which * EC_GROUP_precompute_mult has set up precomputation. */ || !TEST_true(EC_POINT_mul(group, P, n1, NULL, NULL, ctx)) || (i == 1 && !TEST_int_eq(0, EC_POINT_cmp(group, P, G, ctx))) || !TEST_true(BN_one(n1)) /* n1 = 1 - order */ || !TEST_true(BN_sub(n1, n1, order)) || !TEST_true(EC_POINT_mul(group, Q, NULL, P, n1, ctx)) || !TEST_int_eq(0, EC_POINT_cmp(group, Q, P, ctx)) /* n2 = 1 + order */ || !TEST_true(BN_add(n2, order, BN_value_one())) || !TEST_true(EC_POINT_mul(group, Q, NULL, P, n2, ctx)) || !TEST_int_eq(0, EC_POINT_cmp(group, Q, P, ctx)) /* n2 = (1 - order) * (1 + order) = 1 - order^2 */ || !TEST_true(BN_mul(n2, n1, n2, ctx)) || !TEST_true(EC_POINT_mul(group, Q, NULL, P, n2, ctx)) || !TEST_int_eq(0, EC_POINT_cmp(group, Q, P, ctx))) goto err; /* n2 = order^2 - 1 */ BN_set_negative(n2, 0); if (!TEST_true(EC_POINT_mul(group, Q, NULL, P, n2, ctx)) /* Add P to verify the result. */ || !TEST_true(EC_POINT_add(group, Q, Q, P, ctx)) || !TEST_true(EC_POINT_is_at_infinity(group, Q)) || !TEST_false(EC_POINT_is_at_infinity(group, P))) goto err; #ifndef OPENSSL_NO_DEPRECATED_3_0 /* Exercise EC_POINTs_mul, including corner cases. */ scalars[0] = scalars[1] = BN_value_one(); points[0] = points[1] = P; if (!TEST_true(EC_POINTs_mul(group, R, NULL, 2, points, scalars, ctx)) || !TEST_true(EC_POINT_dbl(group, S, points[0], ctx)) || !TEST_int_eq(0, EC_POINT_cmp(group, R, S, ctx))) goto err; scalars[0] = n1; points[0] = Q; /* => infinity */ scalars[1] = n2; points[1] = P; /* => -P */ scalars[2] = n1; points[2] = Q; /* => infinity */ scalars[3] = n2; points[3] = Q; /* => infinity */ scalars[4] = n1; points[4] = P; /* => P */ scalars[5] = n2; points[5] = Q; /* => infinity */ if (!TEST_true(EC_POINTs_mul(group, P, NULL, 6, points, scalars, ctx)) || !TEST_true(EC_POINT_is_at_infinity(group, P))) goto err; #endif } r = 1; err: if (r == 0 && i != 0) TEST_info(i == 1 ? "allowing precomputation" : "without precomputation"); EC_POINT_free(P); EC_POINT_free(Q); EC_POINT_free(R); EC_POINT_free(S); BN_free(n1); BN_free(n2); BN_free(order); BN_CTX_free(ctx); return r; } static int prime_field_tests(void) { BN_CTX *ctx = NULL; BIGNUM *p = NULL, *a = NULL, *b = NULL, *scalar3 = NULL; EC_GROUP *group = NULL; EC_POINT *P = NULL, *Q = NULL, *R = NULL; BIGNUM *x = NULL, *y = NULL, *z = NULL, *yplusone = NULL; #ifndef OPENSSL_NO_DEPRECATED_3_0 const EC_POINT *points[4]; const BIGNUM *scalars[4]; #endif unsigned char buf[100]; size_t len, r = 0; int k; if (!TEST_ptr(ctx = BN_CTX_new()) || !TEST_ptr(p = BN_new()) || !TEST_ptr(a = BN_new()) || !TEST_ptr(b = BN_new()) || !TEST_true(BN_hex2bn(&p, "17")) || !TEST_true(BN_hex2bn(&a, "1")) || !TEST_true(BN_hex2bn(&b, "1")) || !TEST_ptr(group = EC_GROUP_new_curve_GFp(p, a, b, ctx)) || !TEST_true(EC_GROUP_get_curve(group, p, a, b, ctx))) goto err; TEST_info("Curve defined by Weierstrass equation"); TEST_note(" y^2 = x^3 + a*x + b (mod p)"); test_output_bignum("a", a); test_output_bignum("b", b); test_output_bignum("p", p); buf[0] = 0; if (!TEST_ptr(P = EC_POINT_new(group)) || !TEST_ptr(Q = EC_POINT_new(group)) || !TEST_ptr(R = EC_POINT_new(group)) || !TEST_true(EC_POINT_set_to_infinity(group, P)) || !TEST_true(EC_POINT_is_at_infinity(group, P)) || !TEST_true(EC_POINT_oct2point(group, Q, buf, 1, ctx)) || !TEST_true(EC_POINT_add(group, P, P, Q, ctx)) || !TEST_true(EC_POINT_is_at_infinity(group, P)) || !TEST_ptr(x = BN_new()) || !TEST_ptr(y = BN_new()) || !TEST_ptr(z = BN_new()) || !TEST_ptr(yplusone = BN_new()) || !TEST_true(BN_hex2bn(&x, "D")) || !TEST_true(EC_POINT_set_compressed_coordinates(group, Q, x, 1, ctx))) goto err; if (!TEST_int_gt(EC_POINT_is_on_curve(group, Q, ctx), 0)) { if (!TEST_true(EC_POINT_get_affine_coordinates(group, Q, x, y, ctx))) goto err; TEST_info("Point is not on curve"); test_output_bignum("x", x); test_output_bignum("y", y); goto err; } TEST_note("A cyclic subgroup:"); k = 100; do { if (!TEST_int_ne(k--, 0)) goto err; if (EC_POINT_is_at_infinity(group, P)) { TEST_note(" point at infinity"); } else { if (!TEST_true(EC_POINT_get_affine_coordinates(group, P, x, y, ctx))) goto err; test_output_bignum("x", x); test_output_bignum("y", y); } if (!TEST_true(EC_POINT_copy(R, P)) || !TEST_true(EC_POINT_add(group, P, P, Q, ctx))) goto err; } while (!EC_POINT_is_at_infinity(group, P)); if (!TEST_true(EC_POINT_add(group, P, Q, R, ctx)) || !TEST_true(EC_POINT_is_at_infinity(group, P))) goto err; len = EC_POINT_point2oct(group, Q, POINT_CONVERSION_COMPRESSED, buf, sizeof(buf), ctx); if (!TEST_size_t_ne(len, 0) || !TEST_true(EC_POINT_oct2point(group, P, buf, len, ctx)) || !TEST_int_eq(0, EC_POINT_cmp(group, P, Q, ctx))) goto err; test_output_memory("Generator as octet string, compressed form:", buf, len); len = EC_POINT_point2oct(group, Q, POINT_CONVERSION_UNCOMPRESSED, buf, sizeof(buf), ctx); if (!TEST_size_t_ne(len, 0) || !TEST_true(EC_POINT_oct2point(group, P, buf, len, ctx)) || !TEST_int_eq(0, EC_POINT_cmp(group, P, Q, ctx))) goto err; test_output_memory("Generator as octet string, uncompressed form:", buf, len); len = EC_POINT_point2oct(group, Q, POINT_CONVERSION_HYBRID, buf, sizeof(buf), ctx); if (!TEST_size_t_ne(len, 0) || !TEST_true(EC_POINT_oct2point(group, P, buf, len, ctx)) || !TEST_int_eq(0, EC_POINT_cmp(group, P, Q, ctx))) goto err; test_output_memory("Generator as octet string, hybrid form:", buf, len); if (!TEST_true(EC_POINT_invert(group, P, ctx)) || !TEST_int_eq(0, EC_POINT_cmp(group, P, R, ctx)) /* * Curve secp160r1 (Certicom Research SEC 2 Version 1.0, section 2.4.2, * 2000) -- not a NIST curve, but commonly used */ || !TEST_true(BN_hex2bn(&p, "FFFFFFFF" "FFFFFFFFFFFFFFFFFFFFFFFF7FFFFFFF")) || !TEST_int_eq(1, BN_check_prime(p, ctx, NULL)) || !TEST_true(BN_hex2bn(&a, "FFFFFFFF" "FFFFFFFFFFFFFFFFFFFFFFFF7FFFFFFC")) || !TEST_true(BN_hex2bn(&b, "1C97BEFC" "54BD7A8B65ACF89F81D4D4ADC565FA45")) || !TEST_true(EC_GROUP_set_curve(group, p, a, b, ctx)) || !TEST_true(BN_hex2bn(&x, "4A96B568" "8EF573284664698968C38BB913CBFC82")) || !TEST_true(BN_hex2bn(&y, "23a62855" "3168947d59dcc912042351377ac5fb32")) || !TEST_true(BN_add(yplusone, y, BN_value_one())) /* * When (x, y) is on the curve, (x, y + 1) is, as it happens, not, * and therefore setting the coordinates should fail. */ || !TEST_false(EC_POINT_set_affine_coordinates(group, P, x, yplusone, ctx)) || !TEST_true(EC_POINT_set_affine_coordinates(group, P, x, y, ctx)) || !TEST_int_gt(EC_POINT_is_on_curve(group, P, ctx), 0) || !TEST_true(BN_hex2bn(&z, "0100000000" "000000000001F4C8F927AED3CA752257")) || !TEST_true(EC_GROUP_set_generator(group, P, z, BN_value_one())) || !TEST_true(EC_POINT_get_affine_coordinates(group, P, x, y, ctx))) goto err; TEST_info("SEC2 curve secp160r1 -- Generator"); test_output_bignum("x", x); test_output_bignum("y", y); /* G_y value taken from the standard: */ if (!TEST_true(BN_hex2bn(&z, "23a62855" "3168947d59dcc912042351377ac5fb32")) || !TEST_BN_eq(y, z) || !TEST_int_eq(EC_GROUP_get_degree(group), 160) || !group_order_tests(group) /* Curve P-192 (FIPS PUB 186-2, App. 6) */ || !TEST_true(BN_hex2bn(&p, "FFFFFFFFFFFFFFFF" "FFFFFFFFFFFFFFFEFFFFFFFFFFFFFFFF")) || !TEST_int_eq(1, BN_check_prime(p, ctx, NULL)) || !TEST_true(BN_hex2bn(&a, "FFFFFFFFFFFFFFFF" "FFFFFFFFFFFFFFFEFFFFFFFFFFFFFFFC")) || !TEST_true(BN_hex2bn(&b, "64210519E59C80E7" "0FA7E9AB72243049FEB8DEECC146B9B1")) || !TEST_true(EC_GROUP_set_curve(group, p, a, b, ctx)) || !TEST_true(BN_hex2bn(&x, "188DA80EB03090F6" "7CBF20EB43A18800F4FF0AFD82FF1012")) || !TEST_true(EC_POINT_set_compressed_coordinates(group, P, x, 1, ctx)) || !TEST_int_gt(EC_POINT_is_on_curve(group, P, ctx), 0) || !TEST_true(BN_hex2bn(&z, "FFFFFFFFFFFFFFFF" "FFFFFFFF99DEF836146BC9B1B4D22831")) || !TEST_true(EC_GROUP_set_generator(group, P, z, BN_value_one())) || !TEST_true(EC_POINT_get_affine_coordinates(group, P, x, y, ctx))) goto err; TEST_info("NIST curve P-192 -- Generator"); test_output_bignum("x", x); test_output_bignum("y", y); /* G_y value taken from the standard: */ if (!TEST_true(BN_hex2bn(&z, "07192B95FFC8DA78" "631011ED6B24CDD573F977A11E794811")) || !TEST_BN_eq(y, z) || !TEST_true(BN_add(yplusone, y, BN_value_one())) /* * When (x, y) is on the curve, (x, y + 1) is, as it happens, not, * and therefore setting the coordinates should fail. */ || !TEST_false(EC_POINT_set_affine_coordinates(group, P, x, yplusone, ctx)) || !TEST_int_eq(EC_GROUP_get_degree(group), 192) || !group_order_tests(group) /* Curve P-224 (FIPS PUB 186-2, App. 6) */ || !TEST_true(BN_hex2bn(&p, "FFFFFFFFFFFFFFFFFFFFFFFF" "FFFFFFFF000000000000000000000001")) || !TEST_int_eq(1, BN_check_prime(p, ctx, NULL)) || !TEST_true(BN_hex2bn(&a, "FFFFFFFFFFFFFFFFFFFFFFFF" "FFFFFFFEFFFFFFFFFFFFFFFFFFFFFFFE")) || !TEST_true(BN_hex2bn(&b, "B4050A850C04B3ABF5413256" "5044B0B7D7BFD8BA270B39432355FFB4")) || !TEST_true(EC_GROUP_set_curve(group, p, a, b, ctx)) || !TEST_true(BN_hex2bn(&x, "B70E0CBD6BB4BF7F321390B9" "4A03C1D356C21122343280D6115C1D21")) || !TEST_true(EC_POINT_set_compressed_coordinates(group, P, x, 0, ctx)) || !TEST_int_gt(EC_POINT_is_on_curve(group, P, ctx), 0) || !TEST_true(BN_hex2bn(&z, "FFFFFFFFFFFFFFFFFFFFFFFF" "FFFF16A2E0B8F03E13DD29455C5C2A3D")) || !TEST_true(EC_GROUP_set_generator(group, P, z, BN_value_one())) || !TEST_true(EC_POINT_get_affine_coordinates(group, P, x, y, ctx))) goto err; TEST_info("NIST curve P-224 -- Generator"); test_output_bignum("x", x); test_output_bignum("y", y); /* G_y value taken from the standard: */ if (!TEST_true(BN_hex2bn(&z, "BD376388B5F723FB4C22DFE6" "CD4375A05A07476444D5819985007E34")) || !TEST_BN_eq(y, z) || !TEST_true(BN_add(yplusone, y, BN_value_one())) /* * When (x, y) is on the curve, (x, y + 1) is, as it happens, not, * and therefore setting the coordinates should fail. */ || !TEST_false(EC_POINT_set_affine_coordinates(group, P, x, yplusone, ctx)) || !TEST_int_eq(EC_GROUP_get_degree(group), 224) || !group_order_tests(group) /* Curve P-256 (FIPS PUB 186-2, App. 6) */ || !TEST_true(BN_hex2bn(&p, "FFFFFFFF000000010000000000000000" "00000000FFFFFFFFFFFFFFFFFFFFFFFF")) || !TEST_int_eq(1, BN_check_prime(p, ctx, NULL)) || !TEST_true(BN_hex2bn(&a, "FFFFFFFF000000010000000000000000" "00000000FFFFFFFFFFFFFFFFFFFFFFFC")) || !TEST_true(BN_hex2bn(&b, "5AC635D8AA3A93E7B3EBBD55769886BC" "651D06B0CC53B0F63BCE3C3E27D2604B")) || !TEST_true(EC_GROUP_set_curve(group, p, a, b, ctx)) || !TEST_true(BN_hex2bn(&x, "6B17D1F2E12C4247F8BCE6E563A440F2" "77037D812DEB33A0F4A13945D898C296")) || !TEST_true(EC_POINT_set_compressed_coordinates(group, P, x, 1, ctx)) || !TEST_int_gt(EC_POINT_is_on_curve(group, P, ctx), 0) || !TEST_true(BN_hex2bn(&z, "FFFFFFFF00000000FFFFFFFFFFFFFFFF" "BCE6FAADA7179E84F3B9CAC2FC632551")) || !TEST_true(EC_GROUP_set_generator(group, P, z, BN_value_one())) || !TEST_true(EC_POINT_get_affine_coordinates(group, P, x, y, ctx))) goto err; TEST_info("NIST curve P-256 -- Generator"); test_output_bignum("x", x); test_output_bignum("y", y); /* G_y value taken from the standard: */ if (!TEST_true(BN_hex2bn(&z, "4FE342E2FE1A7F9B8EE7EB4A7C0F9E16" "2BCE33576B315ECECBB6406837BF51F5")) || !TEST_BN_eq(y, z) || !TEST_true(BN_add(yplusone, y, BN_value_one())) /* * When (x, y) is on the curve, (x, y + 1) is, as it happens, not, * and therefore setting the coordinates should fail. */ || !TEST_false(EC_POINT_set_affine_coordinates(group, P, x, yplusone, ctx)) || !TEST_int_eq(EC_GROUP_get_degree(group), 256) || !group_order_tests(group) /* Curve P-384 (FIPS PUB 186-2, App. 6) */ || !TEST_true(BN_hex2bn(&p, "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF" "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFE" "FFFFFFFF0000000000000000FFFFFFFF")) || !TEST_int_eq(1, BN_check_prime(p, ctx, NULL)) || !TEST_true(BN_hex2bn(&a, "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF" "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFE" "FFFFFFFF0000000000000000FFFFFFFC")) || !TEST_true(BN_hex2bn(&b, "B3312FA7E23EE7E4988E056BE3F82D19" "181D9C6EFE8141120314088F5013875A" "C656398D8A2ED19D2A85C8EDD3EC2AEF")) || !TEST_true(EC_GROUP_set_curve(group, p, a, b, ctx)) || !TEST_true(BN_hex2bn(&x, "AA87CA22BE8B05378EB1C71EF320AD74" "6E1D3B628BA79B9859F741E082542A38" "5502F25DBF55296C3A545E3872760AB7")) || !TEST_true(EC_POINT_set_compressed_coordinates(group, P, x, 1, ctx)) || !TEST_int_gt(EC_POINT_is_on_curve(group, P, ctx), 0) || !TEST_true(BN_hex2bn(&z, "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF" "FFFFFFFFFFFFFFFFC7634D81F4372DDF" "581A0DB248B0A77AECEC196ACCC52973")) || !TEST_true(EC_GROUP_set_generator(group, P, z, BN_value_one())) || !TEST_true(EC_POINT_get_affine_coordinates(group, P, x, y, ctx))) goto err; TEST_info("NIST curve P-384 -- Generator"); test_output_bignum("x", x); test_output_bignum("y", y); /* G_y value taken from the standard: */ if (!TEST_true(BN_hex2bn(&z, "3617DE4A96262C6F5D9E98BF9292DC29" "F8F41DBD289A147CE9DA3113B5F0B8C0" "0A60B1CE1D7E819D7A431D7C90EA0E5F")) || !TEST_BN_eq(y, z) || !TEST_true(BN_add(yplusone, y, BN_value_one())) /* * When (x, y) is on the curve, (x, y + 1) is, as it happens, not, * and therefore setting the coordinates should fail. */ || !TEST_false(EC_POINT_set_affine_coordinates(group, P, x, yplusone, ctx)) || !TEST_int_eq(EC_GROUP_get_degree(group), 384) || !group_order_tests(group) /* Curve P-521 (FIPS PUB 186-2, App. 6) */ || !TEST_true(BN_hex2bn(&p, "1FF" "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF" "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF" "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF" "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF")) || !TEST_int_eq(1, BN_check_prime(p, ctx, NULL)) || !TEST_true(BN_hex2bn(&a, "1FF" "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF" "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF" "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF" "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFC")) || !TEST_true(BN_hex2bn(&b, "051" "953EB9618E1C9A1F929A21A0B68540EE" "A2DA725B99B315F3B8B489918EF109E1" "56193951EC7E937B1652C0BD3BB1BF07" "3573DF883D2C34F1EF451FD46B503F00")) || !TEST_true(EC_GROUP_set_curve(group, p, a, b, ctx)) || !TEST_true(BN_hex2bn(&x, "C6" "858E06B70404E9CD9E3ECB662395B442" "9C648139053FB521F828AF606B4D3DBA" "A14B5E77EFE75928FE1DC127A2FFA8DE" "3348B3C1856A429BF97E7E31C2E5BD66")) || !TEST_true(EC_POINT_set_compressed_coordinates(group, P, x, 0, ctx)) || !TEST_int_gt(EC_POINT_is_on_curve(group, P, ctx), 0) || !TEST_true(BN_hex2bn(&z, "1FF" "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF" "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFA" "51868783BF2F966B7FCC0148F709A5D0" "3BB5C9B8899C47AEBB6FB71E91386409")) || !TEST_true(EC_GROUP_set_generator(group, P, z, BN_value_one())) || !TEST_true(EC_POINT_get_affine_coordinates(group, P, x, y, ctx))) goto err; TEST_info("NIST curve P-521 -- Generator"); test_output_bignum("x", x); test_output_bignum("y", y); /* G_y value taken from the standard: */ if (!TEST_true(BN_hex2bn(&z, "118" "39296A789A3BC0045C8A5FB42C7D1BD9" "98F54449579B446817AFBD17273E662C" "97EE72995EF42640C550B9013FAD0761" "353C7086A272C24088BE94769FD16650")) || !TEST_BN_eq(y, z) || !TEST_true(BN_add(yplusone, y, BN_value_one())) /* * When (x, y) is on the curve, (x, y + 1) is, as it happens, not, * and therefore setting the coordinates should fail. */ || !TEST_false(EC_POINT_set_affine_coordinates(group, P, x, yplusone, ctx)) || !TEST_int_eq(EC_GROUP_get_degree(group), 521) || !group_order_tests(group) /* more tests using the last curve */ /* Restore the point that got mangled in the (x, y + 1) test. */ || !TEST_true(EC_POINT_set_affine_coordinates(group, P, x, y, ctx)) || !TEST_true(EC_POINT_copy(Q, P)) || !TEST_false(EC_POINT_is_at_infinity(group, Q)) || !TEST_true(EC_POINT_dbl(group, P, P, ctx)) || !TEST_int_gt(EC_POINT_is_on_curve(group, P, ctx), 0) || !TEST_true(EC_POINT_invert(group, Q, ctx)) /* P = -2Q */ || !TEST_true(EC_POINT_add(group, R, P, Q, ctx)) || !TEST_true(EC_POINT_add(group, R, R, Q, ctx)) || !TEST_true(EC_POINT_is_at_infinity(group, R)) /* R = P + 2Q */ || !TEST_false(EC_POINT_is_at_infinity(group, Q))) goto err; #ifndef OPENSSL_NO_DEPRECATED_3_0 TEST_note("combined multiplication ..."); points[0] = Q; points[1] = Q; points[2] = Q; points[3] = Q; if (!TEST_true(EC_GROUP_get_order(group, z, ctx)) || !TEST_true(BN_add(y, z, BN_value_one())) || !TEST_BN_even(y) || !TEST_true(BN_rshift1(y, y))) goto err; scalars[0] = y; /* (group order + 1)/2, so y*Q + y*Q = Q */ scalars[1] = y; /* z is still the group order */ if (!TEST_true(EC_POINTs_mul(group, P, NULL, 2, points, scalars, ctx)) || !TEST_true(EC_POINTs_mul(group, R, z, 2, points, scalars, ctx)) || !TEST_int_eq(0, EC_POINT_cmp(group, P, R, ctx)) || !TEST_int_eq(0, EC_POINT_cmp(group, R, Q, ctx)) || !TEST_true(BN_rand(y, BN_num_bits(y), 0, 0)) || !TEST_true(BN_add(z, z, y))) goto err; BN_set_negative(z, 1); scalars[0] = y; scalars[1] = z; /* z = -(order + y) */ if (!TEST_true(EC_POINTs_mul(group, P, NULL, 2, points, scalars, ctx)) || !TEST_true(EC_POINT_is_at_infinity(group, P)) || !TEST_true(BN_rand(x, BN_num_bits(y) - 1, 0, 0)) || !TEST_true(BN_add(z, x, y))) goto err; BN_set_negative(z, 1); scalars[0] = x; scalars[1] = y; scalars[2] = z; /* z = -(x+y) */ if (!TEST_ptr(scalar3 = BN_new())) goto err; BN_zero(scalar3); scalars[3] = scalar3; if (!TEST_true(EC_POINTs_mul(group, P, NULL, 4, points, scalars, ctx)) || !TEST_true(EC_POINT_is_at_infinity(group, P))) goto err; #endif TEST_note(" ok\n"); r = 1; err: BN_CTX_free(ctx); BN_free(p); BN_free(a); BN_free(b); EC_GROUP_free(group); EC_POINT_free(P); EC_POINT_free(Q); EC_POINT_free(R); BN_free(x); BN_free(y); BN_free(z); BN_free(yplusone); BN_free(scalar3); return r; } #ifndef OPENSSL_NO_EC2M static struct c2_curve_test { const char *name; const char *p; const char *a; const char *b; const char *x; const char *y; int ybit; const char *order; const char *cof; int degree; } char2_curve_tests[] = { /* Curve K-163 (FIPS PUB 186-2, App. 6) */ { "NIST curve K-163", "0800000000000000000000000000000000000000C9", "1", "1", "02FE13C0537BBC11ACAA07D793DE4E6D5E5C94EEE8", "0289070FB05D38FF58321F2E800536D538CCDAA3D9", 1, "04000000000000000000020108A2E0CC0D99F8A5EF", "2", 163 }, /* Curve B-163 (FIPS PUB 186-2, App. 6) */ { "NIST curve B-163", "0800000000000000000000000000000000000000C9", "1", "020A601907B8C953CA1481EB10512F78744A3205FD", "03F0EBA16286A2D57EA0991168D4994637E8343E36", "00D51FBC6C71A0094FA2CDD545B11C5C0C797324F1", 1, "040000000000000000000292FE77E70C12A4234C33", "2", 163 }, /* Curve K-233 (FIPS PUB 186-2, App. 6) */ { "NIST curve K-233", "020000000000000000000000000000000000000004000000000000000001", "0", "1", "017232BA853A7E731AF129F22FF4149563A419C26BF50A4C9D6EEFAD6126", "01DB537DECE819B7F70F555A67C427A8CD9BF18AEB9B56E0C11056FAE6A3", 0, "008000000000000000000000000000069D5BB915BCD46EFB1AD5F173ABDF", "4", 233 }, /* Curve B-233 (FIPS PUB 186-2, App. 6) */ { "NIST curve B-233", "020000000000000000000000000000000000000004000000000000000001", "000000000000000000000000000000000000000000000000000000000001", "0066647EDE6C332C7F8C0923BB58213B333B20E9CE4281FE115F7D8F90AD", "00FAC9DFCBAC8313BB2139F1BB755FEF65BC391F8B36F8F8EB7371FD558B", "01006A08A41903350678E58528BEBF8A0BEFF867A7CA36716F7E01F81052", 1, "01000000000000000000000000000013E974E72F8A6922031D2603CFE0D7", "2", 233 }, /* Curve K-283 (FIPS PUB 186-2, App. 6) */ { "NIST curve K-283", "08000000" "00000000000000000000000000000000000000000000000000000000000010A1", "0", "1", "0503213F" "78CA44883F1A3B8162F188E553CD265F23C1567A16876913B0C2AC2458492836", "01CCDA38" "0F1C9E318D90F95D07E5426FE87E45C0E8184698E45962364E34116177DD2259", 0, "01FFFFFF" "FFFFFFFFFFFFFFFFFFFFFFFFFFFFE9AE2ED07577265DFF7F94451E061E163C61", "4", 283 }, /* Curve B-283 (FIPS PUB 186-2, App. 6) */ { "NIST curve B-283", "08000000" "00000000000000000000000000000000000000000000000000000000000010A1", "00000000" "0000000000000000000000000000000000000000000000000000000000000001", "027B680A" "C8B8596DA5A4AF8A19A0303FCA97FD7645309FA2A581485AF6263E313B79A2F5", "05F93925" "8DB7DD90E1934F8C70B0DFEC2EED25B8557EAC9C80E2E198F8CDBECD86B12053", "03676854" "FE24141CB98FE6D4B20D02B4516FF702350EDDB0826779C813F0DF45BE8112F4", 1, "03FFFFFF" "FFFFFFFFFFFFFFFFFFFFFFFFFFFFEF90399660FC938A90165B042A7CEFADB307", "2", 283 }, /* Curve K-409 (FIPS PUB 186-2, App. 6) */ { "NIST curve K-409", "0200000000000000000000000000000000000000" "0000000000000000000000000000000000000000008000000000000000000001", "0", "1", "0060F05F658F49C1AD3AB1890F7184210EFD0987" "E307C84C27ACCFB8F9F67CC2C460189EB5AAAA62EE222EB1B35540CFE9023746", "01E369050B7C4E42ACBA1DACBF04299C3460782F" "918EA427E6325165E9EA10E3DA5F6C42E9C55215AA9CA27A5863EC48D8E0286B", 1, "007FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF" "FFFFFFFFFFFFFE5F83B2D4EA20400EC4557D5ED3E3E7CA5B4B5C83B8E01E5FCF", "4", 409 }, /* Curve B-409 (FIPS PUB 186-2, App. 6) */ { "NIST curve B-409", "0200000000000000000000000000000000000000" "0000000000000000000000000000000000000000008000000000000000000001", "0000000000000000000000000000000000000000" "0000000000000000000000000000000000000000000000000000000000000001", "0021A5C2C8EE9FEB5C4B9A753B7B476B7FD6422E" "F1F3DD674761FA99D6AC27C8A9A197B272822F6CD57A55AA4F50AE317B13545F", "015D4860D088DDB3496B0C6064756260441CDE4A" "F1771D4DB01FFE5B34E59703DC255A868A1180515603AEAB60794E54BB7996A7", "0061B1CFAB6BE5F32BBFA78324ED106A7636B9C5" "A7BD198D0158AA4F5488D08F38514F1FDF4B4F40D2181B3681C364BA0273C706", 1, "0100000000000000000000000000000000000000" "00000000000001E2AAD6A612F33307BE5FA47C3C9E052F838164CD37D9A21173", "2", 409 }, /* Curve K-571 (FIPS PUB 186-2, App. 6) */ { "NIST curve K-571", "800000000000000" "0000000000000000000000000000000000000000000000000000000000000000" "0000000000000000000000000000000000000000000000000000000000000425", "0", "1", "026EB7A859923FBC" "82189631F8103FE4AC9CA2970012D5D46024804801841CA44370958493B205E6" "47DA304DB4CEB08CBBD1BA39494776FB988B47174DCA88C7E2945283A01C8972", "0349DC807F4FBF37" "4F4AEADE3BCA95314DD58CEC9F307A54FFC61EFC006D8A2C9D4979C0AC44AEA7" "4FBEBBB9F772AEDCB620B01A7BA7AF1B320430C8591984F601CD4C143EF1C7A3", 0, "0200000000000000" "00000000000000000000000000000000000000000000000000000000131850E1" "F19A63E4B391A8DB917F4138B630D84BE5D639381E91DEB45CFE778F637C1001", "4", 571 }, /* Curve B-571 (FIPS PUB 186-2, App. 6) */ { "NIST curve B-571", "800000000000000" "0000000000000000000000000000000000000000000000000000000000000000" "0000000000000000000000000000000000000000000000000000000000000425", "0000000000000000" "0000000000000000000000000000000000000000000000000000000000000000" "0000000000000000000000000000000000000000000000000000000000000001", "02F40E7E2221F295" "DE297117B7F3D62F5C6A97FFCB8CEFF1CD6BA8CE4A9A18AD84FFABBD8EFA5933" "2BE7AD6756A66E294AFD185A78FF12AA520E4DE739BACA0C7FFEFF7F2955727A", "0303001D34B85629" "6C16C0D40D3CD7750A93D1D2955FA80AA5F40FC8DB7B2ABDBDE53950F4C0D293" "CDD711A35B67FB1499AE60038614F1394ABFA3B4C850D927E1E7769C8EEC2D19", "037BF27342DA639B" "6DCCFFFEB73D69D78C6C27A6009CBBCA1980F8533921E8A684423E43BAB08A57" "6291AF8F461BB2A8B3531D2F0485C19B16E2F1516E23DD3C1A4827AF1B8AC15B", 1, "03FFFFFFFFFFFFFF" "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFE661CE18" "FF55987308059B186823851EC7DD9CA1161DE93D5174D66E8382E9BB2FE84E47", "2", 571 } }; static int char2_curve_test(int n) { int r = 0; BN_CTX *ctx = NULL; BIGNUM *p = NULL, *a = NULL, *b = NULL; BIGNUM *x = NULL, *y = NULL, *z = NULL, *cof = NULL, *yplusone = NULL; EC_GROUP *group = NULL; EC_POINT *P = NULL, *Q = NULL, *R = NULL; # ifndef OPENSSL_NO_DEPRECATED_3_0 const EC_POINT *points[3]; const BIGNUM *scalars[3]; # endif struct c2_curve_test *const test = char2_curve_tests + n; if (!TEST_ptr(ctx = BN_CTX_new()) || !TEST_ptr(p = BN_new()) || !TEST_ptr(a = BN_new()) || !TEST_ptr(b = BN_new()) || !TEST_ptr(x = BN_new()) || !TEST_ptr(y = BN_new()) || !TEST_ptr(z = BN_new()) || !TEST_ptr(yplusone = BN_new()) || !TEST_true(BN_hex2bn(&p, test->p)) || !TEST_true(BN_hex2bn(&a, test->a)) || !TEST_true(BN_hex2bn(&b, test->b)) || !TEST_true(group = EC_GROUP_new_curve_GF2m(p, a, b, ctx)) || !TEST_ptr(P = EC_POINT_new(group)) || !TEST_ptr(Q = EC_POINT_new(group)) || !TEST_ptr(R = EC_POINT_new(group)) || !TEST_true(BN_hex2bn(&x, test->x)) || !TEST_true(BN_hex2bn(&y, test->y)) || !TEST_true(BN_add(yplusone, y, BN_value_one()))) goto err; /* Change test based on whether binary point compression is enabled or not. */ # ifdef OPENSSL_EC_BIN_PT_COMP /* * When (x, y) is on the curve, (x, y + 1) is, as it happens, not, * and therefore setting the coordinates should fail. */ if (!TEST_false(EC_POINT_set_affine_coordinates(group, P, x, yplusone, ctx)) || !TEST_true(EC_POINT_set_compressed_coordinates(group, P, x, test->y_bit, ctx)) || !TEST_int_gt(EC_POINT_is_on_curve(group, P, ctx), 0) || !TEST_true(BN_hex2bn(&z, test->order)) || !TEST_true(BN_hex2bn(&cof, test->cof)) || !TEST_true(EC_GROUP_set_generator(group, P, z, cof)) || !TEST_true(EC_POINT_get_affine_coordinates(group, P, x, y, ctx))) goto err; TEST_info("%s -- Generator", test->name); test_output_bignum("x", x); test_output_bignum("y", y); /* G_y value taken from the standard: */ if (!TEST_true(BN_hex2bn(&z, test->y)) || !TEST_BN_eq(y, z)) goto err; # else /* * When (x, y) is on the curve, (x, y + 1) is, as it happens, not, * and therefore setting the coordinates should fail. */ if (!TEST_false(EC_POINT_set_affine_coordinates(group, P, x, yplusone, ctx)) || !TEST_true(EC_POINT_set_affine_coordinates(group, P, x, y, ctx)) || !TEST_int_gt(EC_POINT_is_on_curve(group, P, ctx), 0) || !TEST_true(BN_hex2bn(&z, test->order)) || !TEST_true(BN_hex2bn(&cof, test->cof)) || !TEST_true(EC_GROUP_set_generator(group, P, z, cof))) goto err; TEST_info("%s -- Generator:", test->name); test_output_bignum("x", x); test_output_bignum("y", y); # endif if (!TEST_int_eq(EC_GROUP_get_degree(group), test->degree) || !group_order_tests(group)) goto err; /* more tests using the last curve */ if (n == OSSL_NELEM(char2_curve_tests) - 1) { if (!TEST_true(EC_POINT_set_affine_coordinates(group, P, x, y, ctx)) || !TEST_true(EC_POINT_copy(Q, P)) || !TEST_false(EC_POINT_is_at_infinity(group, Q)) || !TEST_true(EC_POINT_dbl(group, P, P, ctx)) || !TEST_int_gt(EC_POINT_is_on_curve(group, P, ctx), 0) || !TEST_true(EC_POINT_invert(group, Q, ctx)) /* P = -2Q */ || !TEST_true(EC_POINT_add(group, R, P, Q, ctx)) || !TEST_true(EC_POINT_add(group, R, R, Q, ctx)) || !TEST_true(EC_POINT_is_at_infinity(group, R)) /* R = P + 2Q */ || !TEST_false(EC_POINT_is_at_infinity(group, Q))) goto err; # ifndef OPENSSL_NO_DEPRECATED_3_0 TEST_note("combined multiplication ..."); points[0] = Q; points[1] = Q; points[2] = Q; if (!TEST_true(BN_add(y, z, BN_value_one())) || !TEST_BN_even(y) || !TEST_true(BN_rshift1(y, y))) goto err; scalars[0] = y; /* (group order + 1)/2, so y*Q + y*Q = Q */ scalars[1] = y; /* z is still the group order */ if (!TEST_true(EC_POINTs_mul(group, P, NULL, 2, points, scalars, ctx)) || !TEST_true(EC_POINTs_mul(group, R, z, 2, points, scalars, ctx)) || !TEST_int_eq(0, EC_POINT_cmp(group, P, R, ctx)) || !TEST_int_eq(0, EC_POINT_cmp(group, R, Q, ctx))) goto err; if (!TEST_true(BN_rand(y, BN_num_bits(y), 0, 0)) || !TEST_true(BN_add(z, z, y))) goto err; BN_set_negative(z, 1); scalars[0] = y; scalars[1] = z; /* z = -(order + y) */ if (!TEST_true(EC_POINTs_mul(group, P, NULL, 2, points, scalars, ctx)) || !TEST_true(EC_POINT_is_at_infinity(group, P))) goto err; if (!TEST_true(BN_rand(x, BN_num_bits(y) - 1, 0, 0)) || !TEST_true(BN_add(z, x, y))) goto err; BN_set_negative(z, 1); scalars[0] = x; scalars[1] = y; scalars[2] = z; /* z = -(x+y) */ if (!TEST_true(EC_POINTs_mul(group, P, NULL, 3, points, scalars, ctx)) || !TEST_true(EC_POINT_is_at_infinity(group, P))) goto err; # endif } r = 1; err: BN_CTX_free(ctx); BN_free(p); BN_free(a); BN_free(b); BN_free(x); BN_free(y); BN_free(z); BN_free(yplusone); BN_free(cof); EC_POINT_free(P); EC_POINT_free(Q); EC_POINT_free(R); EC_GROUP_free(group); return r; } static int char2_field_tests(void) { BN_CTX *ctx = NULL; BIGNUM *p = NULL, *a = NULL, *b = NULL; EC_GROUP *group = NULL; EC_POINT *P = NULL, *Q = NULL, *R = NULL; BIGNUM *x = NULL, *y = NULL, *z = NULL, *cof = NULL, *yplusone = NULL; unsigned char buf[100]; size_t len; int k, r = 0; if (!TEST_ptr(ctx = BN_CTX_new()) || !TEST_ptr(p = BN_new()) || !TEST_ptr(a = BN_new()) || !TEST_ptr(b = BN_new()) || !TEST_true(BN_hex2bn(&p, "13")) || !TEST_true(BN_hex2bn(&a, "3")) || !TEST_true(BN_hex2bn(&b, "1"))) goto err; if (!TEST_ptr(group = EC_GROUP_new_curve_GF2m(p, a, b, ctx)) || !TEST_true(EC_GROUP_get_curve(group, p, a, b, ctx))) goto err; TEST_info("Curve defined by Weierstrass equation"); TEST_note(" y^2 + x*y = x^3 + a*x^2 + b (mod p)"); test_output_bignum("a", a); test_output_bignum("b", b); test_output_bignum("p", p); if (!TEST_ptr(P = EC_POINT_new(group)) || !TEST_ptr(Q = EC_POINT_new(group)) || !TEST_ptr(R = EC_POINT_new(group)) || !TEST_true(EC_POINT_set_to_infinity(group, P)) || !TEST_true(EC_POINT_is_at_infinity(group, P))) goto err; buf[0] = 0; if (!TEST_true(EC_POINT_oct2point(group, Q, buf, 1, ctx)) || !TEST_true(EC_POINT_add(group, P, P, Q, ctx)) || !TEST_true(EC_POINT_is_at_infinity(group, P)) || !TEST_ptr(x = BN_new()) || !TEST_ptr(y = BN_new()) || !TEST_ptr(z = BN_new()) || !TEST_ptr(cof = BN_new()) || !TEST_ptr(yplusone = BN_new()) || !TEST_true(BN_hex2bn(&x, "6")) /* Change test based on whether binary point compression is enabled or not. */ # ifdef OPENSSL_EC_BIN_PT_COMP || !TEST_true(EC_POINT_set_compressed_coordinates(group, Q, x, 1, ctx)) # else || !TEST_true(BN_hex2bn(&y, "8")) || !TEST_true(EC_POINT_set_affine_coordinates(group, Q, x, y, ctx)) # endif ) goto err; if (!TEST_int_gt(EC_POINT_is_on_curve(group, Q, ctx), 0)) { /* Change test based on whether binary point compression is enabled or not. */ # ifdef OPENSSL_EC_BIN_PT_COMP if (!TEST_true(EC_POINT_get_affine_coordinates(group, Q, x, y, ctx))) goto err; # endif TEST_info("Point is not on curve"); test_output_bignum("x", x); test_output_bignum("y", y); goto err; } TEST_note("A cyclic subgroup:"); k = 100; do { if (!TEST_int_ne(k--, 0)) goto err; if (EC_POINT_is_at_infinity(group, P)) TEST_note(" point at infinity"); else { if (!TEST_true(EC_POINT_get_affine_coordinates(group, P, x, y, ctx))) goto err; test_output_bignum("x", x); test_output_bignum("y", y); } if (!TEST_true(EC_POINT_copy(R, P)) || !TEST_true(EC_POINT_add(group, P, P, Q, ctx))) goto err; } while (!EC_POINT_is_at_infinity(group, P)); if (!TEST_true(EC_POINT_add(group, P, Q, R, ctx)) || !TEST_true(EC_POINT_is_at_infinity(group, P))) goto err; /* Change test based on whether binary point compression is enabled or not. */ # ifdef OPENSSL_EC_BIN_PT_COMP len = EC_POINT_point2oct(group, Q, POINT_CONVERSION_COMPRESSED, buf, sizeof(buf), ctx); if (!TEST_size_t_ne(len, 0) || !TEST_true(EC_POINT_oct2point(group, P, buf, len, ctx)) || !TEST_int_eq(0, EC_POINT_cmp(group, P, Q, ctx))) goto err; test_output_memory("Generator as octet string, compressed form:", buf, len); # endif len = EC_POINT_point2oct(group, Q, POINT_CONVERSION_UNCOMPRESSED, buf, sizeof(buf), ctx); if (!TEST_size_t_ne(len, 0) || !TEST_true(EC_POINT_oct2point(group, P, buf, len, ctx)) || !TEST_int_eq(0, EC_POINT_cmp(group, P, Q, ctx))) goto err; test_output_memory("Generator as octet string, uncompressed form:", buf, len); /* Change test based on whether binary point compression is enabled or not. */ # ifdef OPENSSL_EC_BIN_PT_COMP len = EC_POINT_point2oct(group, Q, POINT_CONVERSION_HYBRID, buf, sizeof(buf), ctx); if (!TEST_size_t_ne(len, 0) || !TEST_true(EC_POINT_oct2point(group, P, buf, len, ctx)) || !TEST_int_eq(0, EC_POINT_cmp(group, P, Q, ctx))) goto err; test_output_memory("Generator as octet string, hybrid form:", buf, len); # endif if (!TEST_true(EC_POINT_invert(group, P, ctx)) || !TEST_int_eq(0, EC_POINT_cmp(group, P, R, ctx))) goto err; TEST_note("\n"); r = 1; err: BN_CTX_free(ctx); BN_free(p); BN_free(a); BN_free(b); EC_GROUP_free(group); EC_POINT_free(P); EC_POINT_free(Q); EC_POINT_free(R); BN_free(x); BN_free(y); BN_free(z); BN_free(cof); BN_free(yplusone); return r; } static int hybrid_point_encoding_test(void) { BIGNUM *x = NULL, *y = NULL; EC_GROUP *group = NULL; EC_POINT *point = NULL; unsigned char *buf = NULL; size_t len; int r = 0; if (!TEST_true(BN_dec2bn(&x, "0")) || !TEST_true(BN_dec2bn(&y, "1")) || !TEST_ptr(group = EC_GROUP_new_by_curve_name(NID_sect571k1)) || !TEST_ptr(point = EC_POINT_new(group)) || !TEST_true(EC_POINT_set_affine_coordinates(group, point, x, y, NULL)) || !TEST_size_t_ne(0, (len = EC_POINT_point2oct(group, point, POINT_CONVERSION_HYBRID, NULL, 0, NULL))) || !TEST_ptr(buf = OPENSSL_malloc(len)) || !TEST_size_t_eq(len, EC_POINT_point2oct(group, point, POINT_CONVERSION_HYBRID, buf, len, NULL))) goto err; r = 1; /* buf contains a valid hybrid point, check that we can decode it. */ if (!TEST_true(EC_POINT_oct2point(group, point, buf, len, NULL))) r = 0; /* Flip the y_bit and verify that the invalid encoding is rejected. */ buf[0] ^= 1; if (!TEST_false(EC_POINT_oct2point(group, point, buf, len, NULL))) r = 0; err: BN_free(x); BN_free(y); EC_GROUP_free(group); EC_POINT_free(point); OPENSSL_free(buf); return r; } #endif static int internal_curve_test(int n) { EC_GROUP *group = NULL; int nid = curves[n].nid; if (!TEST_ptr(group = EC_GROUP_new_by_curve_name(nid))) { TEST_info("EC_GROUP_new_curve_name() failed with curve %s\n", OBJ_nid2sn(nid)); return 0; } if (!TEST_true(EC_GROUP_check(group, NULL))) { TEST_info("EC_GROUP_check() failed with curve %s\n", OBJ_nid2sn(nid)); EC_GROUP_free(group); return 0; } EC_GROUP_free(group); return 1; } static int internal_curve_test_method(int n) { int r, nid = curves[n].nid; EC_GROUP *group; if (!TEST_ptr(group = EC_GROUP_new_by_curve_name(nid))) { TEST_info("Curve %s failed\n", OBJ_nid2sn(nid)); return 0; } r = group_order_tests(group); EC_GROUP_free(group); return r; } static int group_field_test(void) { int r = 1; BIGNUM *secp521r1_field = NULL; BIGNUM *sect163r2_field = NULL; EC_GROUP *secp521r1_group = NULL; EC_GROUP *sect163r2_group = NULL; BN_hex2bn(&secp521r1_field, "01FFFFFFFFFFFFFFFFFFFFFFFFFFFFFF" "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF" "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF" "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF" "FFFF"); BN_hex2bn(&sect163r2_field, "08000000000000000000000000000000" "00000000C9"); secp521r1_group = EC_GROUP_new_by_curve_name(NID_secp521r1); if (BN_cmp(secp521r1_field, EC_GROUP_get0_field(secp521r1_group))) r = 0; # ifndef OPENSSL_NO_EC2M sect163r2_group = EC_GROUP_new_by_curve_name(NID_sect163r2); if (BN_cmp(sect163r2_field, EC_GROUP_get0_field(sect163r2_group))) r = 0; # endif EC_GROUP_free(secp521r1_group); EC_GROUP_free(sect163r2_group); BN_free(secp521r1_field); BN_free(sect163r2_field); return r; } /* * nistp_test_params contains magic numbers for testing * several NIST curves with characteristic > 3. */ struct nistp_test_params { const int nid; int degree; /* * Qx, Qy and D are taken from * http://csrc.nist.gov/groups/ST/toolkit/documents/Examples/ECDSA_Prime.pdf * Otherwise, values are standard curve parameters from FIPS 180-3 */ const char *p, *a, *b, *Qx, *Qy, *Gx, *Gy, *order, *d; }; static const struct nistp_test_params nistp_tests_params[] = { { /* P-224 */ NID_secp224r1, 224, /* p */ "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF000000000000000000000001", /* a */ "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFFFFFFFFFFFE", /* b */ "B4050A850C04B3ABF54132565044B0B7D7BFD8BA270B39432355FFB4", /* Qx */ "E84FB0B8E7000CB657D7973CF6B42ED78B301674276DF744AF130B3E", /* Qy */ "4376675C6FC5612C21A0FF2D2A89D2987DF7A2BC52183B5982298555", /* Gx */ "B70E0CBD6BB4BF7F321390B94A03C1D356C21122343280D6115C1D21", /* Gy */ "BD376388B5F723FB4C22DFE6CD4375A05A07476444D5819985007E34", /* order */ "FFFFFFFFFFFFFFFFFFFFFFFFFFFF16A2E0B8F03E13DD29455C5C2A3D", /* d */ "3F0C488E987C80BE0FEE521F8D90BE6034EC69AE11CA72AA777481E8", }, { /* P-256 */ NID_X9_62_prime256v1, 256, /* p */ "ffffffff00000001000000000000000000000000ffffffffffffffffffffffff", /* a */ "ffffffff00000001000000000000000000000000fffffffffffffffffffffffc", /* b */ "5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b", /* Qx */ "b7e08afdfe94bad3f1dc8c734798ba1c62b3a0ad1e9ea2a38201cd0889bc7a19", /* Qy */ "3603f747959dbf7a4bb226e41928729063adc7ae43529e61b563bbc606cc5e09", /* Gx */ "6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296", /* Gy */ "4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5", /* order */ "ffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551", /* d */ "c477f9f65c22cce20657faa5b2d1d8122336f851a508a1ed04e479c34985bf96", }, { /* P-521 */ NID_secp521r1, 521, /* p */ "1ff" "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff" "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", /* a */ "1ff" "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff" "fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc", /* b */ "051" "953eb9618e1c9a1f929a21a0b68540eea2da725b99b315f3b8b489918ef109e1" "56193951ec7e937b1652c0bd3bb1bf073573df883d2c34f1ef451fd46b503f00", /* Qx */ "0098" "e91eef9a68452822309c52fab453f5f117c1da8ed796b255e9ab8f6410cca16e" "59df403a6bdc6ca467a37056b1e54b3005d8ac030decfeb68df18b171885d5c4", /* Qy */ "0164" "350c321aecfc1cca1ba4364c9b15656150b4b78d6a48d7d28e7f31985ef17be8" "554376b72900712c4b83ad668327231526e313f5f092999a4632fd50d946bc2e", /* Gx */ "c6" "858e06b70404e9cd9e3ecb662395b4429c648139053fb521f828af606b4d3dba" "a14b5e77efe75928fe1dc127a2ffa8de3348b3c1856a429bf97e7e31c2e5bd66", /* Gy */ "118" "39296a789a3bc0045c8a5fb42c7d1bd998f54449579b446817afbd17273e662c" "97ee72995ef42640c550b9013fad0761353c7086a272c24088be94769fd16650", /* order */ "1ff" "fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffa" "51868783bf2f966b7fcc0148f709a5d03bb5c9b8899c47aebb6fb71e91386409", /* d */ "0100" "085f47b8e1b8b11b7eb33028c0b2888e304bfc98501955b45bba1478dc184eee" "df09b86a5f7c21994406072787205e69a63709fe35aa93ba333514b24f961722", }, }; static int nistp_single_test(int idx) { const struct nistp_test_params *test = nistp_tests_params + idx; BN_CTX *ctx = NULL; BIGNUM *p = NULL, *a = NULL, *b = NULL, *x = NULL, *y = NULL; BIGNUM *n = NULL, *m = NULL, *order = NULL, *yplusone = NULL; EC_GROUP *NISTP = NULL; EC_POINT *G = NULL, *P = NULL, *Q = NULL, *Q_CHECK = NULL; int r = 0; TEST_note("NIST curve P-%d (optimised implementation):", test->degree); if (!TEST_ptr(ctx = BN_CTX_new()) || !TEST_ptr(p = BN_new()) || !TEST_ptr(a = BN_new()) || !TEST_ptr(b = BN_new()) || !TEST_ptr(x = BN_new()) || !TEST_ptr(y = BN_new()) || !TEST_ptr(m = BN_new()) || !TEST_ptr(n = BN_new()) || !TEST_ptr(order = BN_new()) || !TEST_ptr(yplusone = BN_new()) || !TEST_ptr(NISTP = EC_GROUP_new_by_curve_name(test->nid)) || !TEST_true(BN_hex2bn(&p, test->p)) || !TEST_int_eq(1, BN_check_prime(p, ctx, NULL)) || !TEST_true(BN_hex2bn(&a, test->a)) || !TEST_true(BN_hex2bn(&b, test->b)) || !TEST_true(EC_GROUP_set_curve(NISTP, p, a, b, ctx)) || !TEST_ptr(G = EC_POINT_new(NISTP)) || !TEST_ptr(P = EC_POINT_new(NISTP)) || !TEST_ptr(Q = EC_POINT_new(NISTP)) || !TEST_ptr(Q_CHECK = EC_POINT_new(NISTP)) || !TEST_true(BN_hex2bn(&x, test->Qx)) || !TEST_true(BN_hex2bn(&y, test->Qy)) || !TEST_true(BN_add(yplusone, y, BN_value_one())) /* * When (x, y) is on the curve, (x, y + 1) is, as it happens, not, * and therefore setting the coordinates should fail. */ || !TEST_false(EC_POINT_set_affine_coordinates(NISTP, Q_CHECK, x, yplusone, ctx)) || !TEST_true(EC_POINT_set_affine_coordinates(NISTP, Q_CHECK, x, y, ctx)) || !TEST_true(BN_hex2bn(&x, test->Gx)) || !TEST_true(BN_hex2bn(&y, test->Gy)) || !TEST_true(EC_POINT_set_affine_coordinates(NISTP, G, x, y, ctx)) || !TEST_true(BN_hex2bn(&order, test->order)) || !TEST_true(EC_GROUP_set_generator(NISTP, G, order, BN_value_one())) || !TEST_int_eq(EC_GROUP_get_degree(NISTP), test->degree)) goto err; TEST_note("NIST test vectors ... "); if (!TEST_true(BN_hex2bn(&n, test->d))) goto err; /* fixed point multiplication */ EC_POINT_mul(NISTP, Q, n, NULL, NULL, ctx); if (!TEST_int_eq(0, EC_POINT_cmp(NISTP, Q, Q_CHECK, ctx))) goto err; /* random point multiplication */ EC_POINT_mul(NISTP, Q, NULL, G, n, ctx); if (!TEST_int_eq(0, EC_POINT_cmp(NISTP, Q, Q_CHECK, ctx)) /* set generator to P = 2*G, where G is the standard generator */ || !TEST_true(EC_POINT_dbl(NISTP, P, G, ctx)) || !TEST_true(EC_GROUP_set_generator(NISTP, P, order, BN_value_one())) /* set the scalar to m=n/2, where n is the NIST test scalar */ || !TEST_true(BN_rshift(m, n, 1))) goto err; /* test the non-standard generator */ /* fixed point multiplication */ EC_POINT_mul(NISTP, Q, m, NULL, NULL, ctx); if (!TEST_int_eq(0, EC_POINT_cmp(NISTP, Q, Q_CHECK, ctx))) goto err; /* random point multiplication */ EC_POINT_mul(NISTP, Q, NULL, P, m, ctx); if (!TEST_int_eq(0, EC_POINT_cmp(NISTP, Q, Q_CHECK, ctx)) #ifndef OPENSSL_NO_DEPRECATED_3_0 /* We have not performed precomp so this should be false */ || !TEST_false(EC_GROUP_have_precompute_mult(NISTP)) /* now repeat all tests with precomputation */ || !TEST_true(EC_GROUP_precompute_mult(NISTP, ctx)) #endif ) goto err; /* fixed point multiplication */ EC_POINT_mul(NISTP, Q, m, NULL, NULL, ctx); if (!TEST_int_eq(0, EC_POINT_cmp(NISTP, Q, Q_CHECK, ctx))) goto err; /* random point multiplication */ EC_POINT_mul(NISTP, Q, NULL, P, m, ctx); if (!TEST_int_eq(0, EC_POINT_cmp(NISTP, Q, Q_CHECK, ctx)) /* reset generator */ || !TEST_true(EC_GROUP_set_generator(NISTP, G, order, BN_value_one()))) goto err; /* fixed point multiplication */ EC_POINT_mul(NISTP, Q, n, NULL, NULL, ctx); if (!TEST_int_eq(0, EC_POINT_cmp(NISTP, Q, Q_CHECK, ctx))) goto err; /* random point multiplication */ EC_POINT_mul(NISTP, Q, NULL, G, n, ctx); if (!TEST_int_eq(0, EC_POINT_cmp(NISTP, Q, Q_CHECK, ctx))) goto err; /* regression test for felem_neg bug */ if (!TEST_true(BN_set_word(m, 32)) || !TEST_true(BN_set_word(n, 31)) || !TEST_true(EC_POINT_copy(P, G)) || !TEST_true(EC_POINT_invert(NISTP, P, ctx)) || !TEST_true(EC_POINT_mul(NISTP, Q, m, P, n, ctx)) || !TEST_int_eq(0, EC_POINT_cmp(NISTP, Q, G, ctx))) goto err; r = 1; err: EC_GROUP_free(NISTP); EC_POINT_free(G); EC_POINT_free(P); EC_POINT_free(Q); EC_POINT_free(Q_CHECK); BN_free(n); BN_free(m); BN_free(p); BN_free(a); BN_free(b); BN_free(x); BN_free(y); BN_free(order); BN_free(yplusone); BN_CTX_free(ctx); return r; } static const unsigned char p521_named[] = { 0x06, 0x05, 0x2b, 0x81, 0x04, 0x00, 0x23, }; static const unsigned char p521_explicit[] = { 0x30, 0x82, 0x01, 0xc3, 0x02, 0x01, 0x01, 0x30, 0x4d, 0x06, 0x07, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x01, 0x01, 0x02, 0x42, 0x01, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x30, 0x81, 0x9f, 0x04, 0x42, 0x01, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfc, 0x04, 0x42, 0x00, 0x51, 0x95, 0x3e, 0xb9, 0x61, 0x8e, 0x1c, 0x9a, 0x1f, 0x92, 0x9a, 0x21, 0xa0, 0xb6, 0x85, 0x40, 0xee, 0xa2, 0xda, 0x72, 0x5b, 0x99, 0xb3, 0x15, 0xf3, 0xb8, 0xb4, 0x89, 0x91, 0x8e, 0xf1, 0x09, 0xe1, 0x56, 0x19, 0x39, 0x51, 0xec, 0x7e, 0x93, 0x7b, 0x16, 0x52, 0xc0, 0xbd, 0x3b, 0xb1, 0xbf, 0x07, 0x35, 0x73, 0xdf, 0x88, 0x3d, 0x2c, 0x34, 0xf1, 0xef, 0x45, 0x1f, 0xd4, 0x6b, 0x50, 0x3f, 0x00, 0x03, 0x15, 0x00, 0xd0, 0x9e, 0x88, 0x00, 0x29, 0x1c, 0xb8, 0x53, 0x96, 0xcc, 0x67, 0x17, 0x39, 0x32, 0x84, 0xaa, 0xa0, 0xda, 0x64, 0xba, 0x04, 0x81, 0x85, 0x04, 0x00, 0xc6, 0x85, 0x8e, 0x06, 0xb7, 0x04, 0x04, 0xe9, 0xcd, 0x9e, 0x3e, 0xcb, 0x66, 0x23, 0x95, 0xb4, 0x42, 0x9c, 0x64, 0x81, 0x39, 0x05, 0x3f, 0xb5, 0x21, 0xf8, 0x28, 0xaf, 0x60, 0x6b, 0x4d, 0x3d, 0xba, 0xa1, 0x4b, 0x5e, 0x77, 0xef, 0xe7, 0x59, 0x28, 0xfe, 0x1d, 0xc1, 0x27, 0xa2, 0xff, 0xa8, 0xde, 0x33, 0x48, 0xb3, 0xc1, 0x85, 0x6a, 0x42, 0x9b, 0xf9, 0x7e, 0x7e, 0x31, 0xc2, 0xe5, 0xbd, 0x66, 0x01, 0x18, 0x39, 0x29, 0x6a, 0x78, 0x9a, 0x3b, 0xc0, 0x04, 0x5c, 0x8a, 0x5f, 0xb4, 0x2c, 0x7d, 0x1b, 0xd9, 0x98, 0xf5, 0x44, 0x49, 0x57, 0x9b, 0x44, 0x68, 0x17, 0xaf, 0xbd, 0x17, 0x27, 0x3e, 0x66, 0x2c, 0x97, 0xee, 0x72, 0x99, 0x5e, 0xf4, 0x26, 0x40, 0xc5, 0x50, 0xb9, 0x01, 0x3f, 0xad, 0x07, 0x61, 0x35, 0x3c, 0x70, 0x86, 0xa2, 0x72, 0xc2, 0x40, 0x88, 0xbe, 0x94, 0x76, 0x9f, 0xd1, 0x66, 0x50, 0x02, 0x42, 0x01, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfa, 0x51, 0x86, 0x87, 0x83, 0xbf, 0x2f, 0x96, 0x6b, 0x7f, 0xcc, 0x01, 0x48, 0xf7, 0x09, 0xa5, 0xd0, 0x3b, 0xb5, 0xc9, 0xb8, 0x89, 0x9c, 0x47, 0xae, 0xbb, 0x6f, 0xb7, 0x1e, 0x91, 0x38, 0x64, 0x09, 0x02, 0x01, 0x01, }; /* * This test validates a named curve's group parameters using * EC_GROUP_check_named_curve(). It also checks that modifying any of the * group parameters results in the curve not being valid. */ static int check_named_curve_test(int id) { int ret = 0, nid, field_nid, has_seed; EC_GROUP *group = NULL, *gtest = NULL; const EC_POINT *group_gen = NULL; EC_POINT *other_gen = NULL; BIGNUM *group_p = NULL, *group_a = NULL, *group_b = NULL; BIGNUM *other_p = NULL, *other_a = NULL, *other_b = NULL; BIGNUM *group_cofactor = NULL, *other_cofactor = NULL; BIGNUM *other_order = NULL; const BIGNUM *group_order = NULL; BN_CTX *bn_ctx = NULL; static const unsigned char invalid_seed[] = "THIS IS NOT A VALID SEED"; static size_t invalid_seed_len = sizeof(invalid_seed); /* Do some setup */ nid = curves[id].nid; if (!TEST_ptr(bn_ctx = BN_CTX_new()) || !TEST_ptr(group = EC_GROUP_new_by_curve_name(nid)) || !TEST_ptr(gtest = EC_GROUP_dup(group)) || !TEST_ptr(group_p = BN_new()) || !TEST_ptr(group_a = BN_new()) || !TEST_ptr(group_b = BN_new()) || !TEST_ptr(group_cofactor = BN_new()) || !TEST_ptr(group_gen = EC_GROUP_get0_generator(group)) || !TEST_ptr(group_order = EC_GROUP_get0_order(group)) || !TEST_true(EC_GROUP_get_cofactor(group, group_cofactor, NULL)) || !TEST_true(EC_GROUP_get_curve(group, group_p, group_a, group_b, NULL)) || !TEST_ptr(other_gen = EC_POINT_dup(group_gen, group)) || !TEST_true(EC_POINT_add(group, other_gen, group_gen, group_gen, NULL)) || !TEST_ptr(other_order = BN_dup(group_order)) || !TEST_true(BN_add_word(other_order, 1)) || !TEST_ptr(other_a = BN_dup(group_a)) || !TEST_true(BN_add_word(other_a, 1)) || !TEST_ptr(other_b = BN_dup(group_b)) || !TEST_true(BN_add_word(other_b, 1)) || !TEST_ptr(other_cofactor = BN_dup(group_cofactor)) || !TEST_true(BN_add_word(other_cofactor, 1))) goto err; /* Determine if the built-in curve has a seed field set */ has_seed = (EC_GROUP_get_seed_len(group) > 0); field_nid = EC_GROUP_get_field_type(group); if (field_nid == NID_X9_62_characteristic_two_field) { if (!TEST_ptr(other_p = BN_dup(group_p)) || !TEST_true(BN_lshift1(other_p, other_p))) goto err; } else { if (!TEST_ptr(other_p = BN_dup(group_p))) goto err; /* * Just choosing any arbitrary prime does not work.. * Setting p via ec_GFp_nist_group_set_curve() needs the prime to be a * nist prime. So only select one of these as an alternate prime. */ if (!TEST_ptr(BN_copy(other_p, BN_ucmp(BN_get0_nist_prime_192(), other_p) == 0 ? BN_get0_nist_prime_256() : BN_get0_nist_prime_192()))) goto err; } /* Passes because this is a valid curve */ if (!TEST_int_eq(EC_GROUP_check_named_curve(group, 0, NULL), nid) /* Only NIST curves pass */ || !TEST_int_eq(EC_GROUP_check_named_curve(group, 1, NULL), EC_curve_nid2nist(nid) != NULL ? nid : NID_undef)) goto err; /* Fail if the curve name doesn't match the parameters */ EC_GROUP_set_curve_name(group, nid + 1); ERR_set_mark(); if (!TEST_int_le(EC_GROUP_check_named_curve(group, 0, NULL), 0)) goto err; ERR_pop_to_mark(); /* Restore curve name and ensure it's passing */ EC_GROUP_set_curve_name(group, nid); if (!TEST_int_eq(EC_GROUP_check_named_curve(group, 0, NULL), nid)) goto err; if (!TEST_int_eq(EC_GROUP_set_seed(group, invalid_seed, invalid_seed_len), invalid_seed_len)) goto err; if (has_seed) { /* * If the built-in curve has a seed and we set the seed to another value * then it will fail the check. */ if (!TEST_int_eq(EC_GROUP_check_named_curve(group, 0, NULL), 0)) goto err; } else { /* * If the built-in curve does not have a seed then setting the seed will * pass the check (as the seed is optional). */ if (!TEST_int_eq(EC_GROUP_check_named_curve(group, 0, NULL), nid)) goto err; } /* Pass if the seed is unknown (as it is optional) */ if (!TEST_int_eq(EC_GROUP_set_seed(group, NULL, 0), 1) || !TEST_int_eq(EC_GROUP_check_named_curve(group, 0, NULL), nid)) goto err; /* Check that a duped group passes */ if (!TEST_int_eq(EC_GROUP_check_named_curve(gtest, 0, NULL), nid)) goto err; /* check that changing any generator parameter fails */ if (!TEST_true(EC_GROUP_set_generator(gtest, other_gen, group_order, group_cofactor)) || !TEST_int_eq(EC_GROUP_check_named_curve(gtest, 0, NULL), 0) || !TEST_true(EC_GROUP_set_generator(gtest, group_gen, other_order, group_cofactor)) || !TEST_int_eq(EC_GROUP_check_named_curve(gtest, 0, NULL), 0) /* The order is not an optional field, so this should fail */ || !TEST_false(EC_GROUP_set_generator(gtest, group_gen, NULL, group_cofactor)) || !TEST_true(EC_GROUP_set_generator(gtest, group_gen, group_order, other_cofactor)) || !TEST_int_eq(EC_GROUP_check_named_curve(gtest, 0, NULL), 0) /* Check that if the cofactor is not set then it still passes */ || !TEST_true(EC_GROUP_set_generator(gtest, group_gen, group_order, NULL)) || !TEST_int_eq(EC_GROUP_check_named_curve(gtest, 0, NULL), nid) /* check that restoring the generator passes */ || !TEST_true(EC_GROUP_set_generator(gtest, group_gen, group_order, group_cofactor)) || !TEST_int_eq(EC_GROUP_check_named_curve(gtest, 0, NULL), nid)) goto err; /* * check that changing any curve parameter fails * * Setting arbitrary p, a or b might fail for some EC_GROUPs * depending on the internal EC_METHOD implementation, hence run * these tests conditionally to the success of EC_GROUP_set_curve(). */ ERR_set_mark(); if (EC_GROUP_set_curve(gtest, other_p, group_a, group_b, NULL)) { if (!TEST_int_le(EC_GROUP_check_named_curve(gtest, 0, NULL), 0)) goto err; } else { /* clear the error stack if EC_GROUP_set_curve() failed */ ERR_pop_to_mark(); ERR_set_mark(); } if (EC_GROUP_set_curve(gtest, group_p, other_a, group_b, NULL)) { if (!TEST_int_le(EC_GROUP_check_named_curve(gtest, 0, NULL), 0)) goto err; } else { /* clear the error stack if EC_GROUP_set_curve() failed */ ERR_pop_to_mark(); ERR_set_mark(); } if (EC_GROUP_set_curve(gtest, group_p, group_a, other_b, NULL)) { if (!TEST_int_le(EC_GROUP_check_named_curve(gtest, 0, NULL), 0)) goto err; } else { /* clear the error stack if EC_GROUP_set_curve() failed */ ERR_pop_to_mark(); ERR_set_mark(); } ERR_pop_to_mark(); /* Check that restoring the curve parameters passes */ if (!TEST_true(EC_GROUP_set_curve(gtest, group_p, group_a, group_b, NULL)) || !TEST_int_eq(EC_GROUP_check_named_curve(gtest, 0, NULL), nid)) goto err; ret = 1; err: BN_free(group_p); BN_free(other_p); BN_free(group_a); BN_free(other_a); BN_free(group_b); BN_free(other_b); BN_free(group_cofactor); BN_free(other_cofactor); BN_free(other_order); EC_POINT_free(other_gen); EC_GROUP_free(gtest); EC_GROUP_free(group); BN_CTX_free(bn_ctx); return ret; } /* * This checks the lookup capability of EC_GROUP_check_named_curve() * when the given group was created with explicit parameters. * * It is possible to retrieve an alternative alias that does not match * the original nid in this case. */ static int check_named_curve_lookup_test(int id) { int ret = 0, nid, rv = 0; EC_GROUP *g = NULL , *ga = NULL; ECPARAMETERS *p = NULL, *pa = NULL; BN_CTX *ctx = NULL; /* Do some setup */ nid = curves[id].nid; if (!TEST_ptr(ctx = BN_CTX_new()) || !TEST_ptr(g = EC_GROUP_new_by_curve_name(nid)) || !TEST_ptr(p = EC_GROUP_get_ecparameters(g, NULL))) goto err; /* replace with group from explicit parameters */ EC_GROUP_free(g); if (!TEST_ptr(g = EC_GROUP_new_from_ecparameters(p))) goto err; if (!TEST_int_gt(rv = EC_GROUP_check_named_curve(g, 0, NULL), 0)) goto err; if (rv != nid) { /* * Found an alias: * fail if the returned nid is not an alias of the original group. * * The comparison here is done by comparing two explicit * parameter EC_GROUPs with EC_GROUP_cmp(), to ensure the * comparison happens with unnamed EC_GROUPs using the same * EC_METHODs. */ if (!TEST_ptr(ga = EC_GROUP_new_by_curve_name(rv)) || !TEST_ptr(pa = EC_GROUP_get_ecparameters(ga, NULL))) goto err; /* replace with group from explicit parameters, then compare */ EC_GROUP_free(ga); if (!TEST_ptr(ga = EC_GROUP_new_from_ecparameters(pa)) || !TEST_int_eq(EC_GROUP_cmp(g, ga, ctx), 0)) goto err; } ret = 1; err: EC_GROUP_free(g); EC_GROUP_free(ga); ECPARAMETERS_free(p); ECPARAMETERS_free(pa); BN_CTX_free(ctx); return ret; } /* * Sometime we cannot compare nids for equality, as the built-in curve table * includes aliases with different names for the same curve. * * This function returns TRUE (1) if the checked nids are identical, or if they * alias to the same curve. FALSE (0) otherwise. */ static ossl_inline int are_ec_nids_compatible(int n1d, int n2d) { int ret = 0; switch (n1d) { #ifndef OPENSSL_NO_EC2M case NID_sect113r1: case NID_wap_wsg_idm_ecid_wtls4: ret = (n2d == NID_sect113r1 || n2d == NID_wap_wsg_idm_ecid_wtls4); break; case NID_sect163k1: case NID_wap_wsg_idm_ecid_wtls3: ret = (n2d == NID_sect163k1 || n2d == NID_wap_wsg_idm_ecid_wtls3); break; case NID_sect233k1: case NID_wap_wsg_idm_ecid_wtls10: ret = (n2d == NID_sect233k1 || n2d == NID_wap_wsg_idm_ecid_wtls10); break; case NID_sect233r1: case NID_wap_wsg_idm_ecid_wtls11: ret = (n2d == NID_sect233r1 || n2d == NID_wap_wsg_idm_ecid_wtls11); break; case NID_X9_62_c2pnb163v1: case NID_wap_wsg_idm_ecid_wtls5: ret = (n2d == NID_X9_62_c2pnb163v1 || n2d == NID_wap_wsg_idm_ecid_wtls5); break; #endif /* OPENSSL_NO_EC2M */ case NID_secp112r1: case NID_wap_wsg_idm_ecid_wtls6: ret = (n2d == NID_secp112r1 || n2d == NID_wap_wsg_idm_ecid_wtls6); break; case NID_secp160r2: case NID_wap_wsg_idm_ecid_wtls7: ret = (n2d == NID_secp160r2 || n2d == NID_wap_wsg_idm_ecid_wtls7); break; #ifdef OPENSSL_NO_EC_NISTP_64_GCC_128 case NID_secp224r1: case NID_wap_wsg_idm_ecid_wtls12: ret = (n2d == NID_secp224r1 || n2d == NID_wap_wsg_idm_ecid_wtls12); break; #else /* * For SEC P-224 we want to ensure that the SECP nid is returned, as * that is associated with a specialized method. */ case NID_wap_wsg_idm_ecid_wtls12: ret = (n2d == NID_secp224r1); break; #endif /* def(OPENSSL_NO_EC_NISTP_64_GCC_128) */ default: ret = (n1d == n2d); } return ret; } /* * This checks that EC_GROUP_bew_from_ecparameters() returns a "named" * EC_GROUP for built-in curves. * * Note that it is possible to retrieve an alternative alias that does not match * the original nid. * * Ensure that the OPENSSL_EC_EXPLICIT_CURVE ASN1 flag is set. */ static int check_named_curve_from_ecparameters(int id) { int ret = 0, nid, tnid; EC_GROUP *group = NULL, *tgroup = NULL, *tmpg = NULL; const EC_POINT *group_gen = NULL; EC_POINT *other_gen = NULL; BIGNUM *group_cofactor = NULL, *other_cofactor = NULL; BIGNUM *other_gen_x = NULL, *other_gen_y = NULL; const BIGNUM *group_order = NULL; BIGNUM *other_order = NULL; BN_CTX *bn_ctx = NULL; static const unsigned char invalid_seed[] = "THIS IS NOT A VALID SEED"; static size_t invalid_seed_len = sizeof(invalid_seed); ECPARAMETERS *params = NULL, *other_params = NULL; EC_GROUP *g_ary[8] = {NULL}; EC_GROUP **g_next = &g_ary[0]; ECPARAMETERS *p_ary[8] = {NULL}; ECPARAMETERS **p_next = &p_ary[0]; /* Do some setup */ nid = curves[id].nid; TEST_note("Curve %s", OBJ_nid2sn(nid)); if (!TEST_ptr(bn_ctx = BN_CTX_new())) return ret; BN_CTX_start(bn_ctx); if (/* Allocations */ !TEST_ptr(group_cofactor = BN_CTX_get(bn_ctx)) || !TEST_ptr(other_gen_x = BN_CTX_get(bn_ctx)) || !TEST_ptr(other_gen_y = BN_CTX_get(bn_ctx)) || !TEST_ptr(other_order = BN_CTX_get(bn_ctx)) || !TEST_ptr(other_cofactor = BN_CTX_get(bn_ctx)) /* Generate reference group and params */ || !TEST_ptr(group = EC_GROUP_new_by_curve_name(nid)) || !TEST_ptr(params = EC_GROUP_get_ecparameters(group, NULL)) || !TEST_ptr(group_gen = EC_GROUP_get0_generator(group)) || !TEST_ptr(group_order = EC_GROUP_get0_order(group)) || !TEST_true(EC_GROUP_get_cofactor(group, group_cofactor, NULL)) /* compute `other_*` values */ || !TEST_ptr(tmpg = EC_GROUP_dup(group)) || !TEST_ptr(other_gen = EC_POINT_dup(group_gen, group)) || !TEST_true(EC_POINT_add(group, other_gen, group_gen, group_gen, NULL)) || !TEST_true(EC_POINT_get_affine_coordinates(group, other_gen, other_gen_x, other_gen_y, bn_ctx)) || !TEST_true(BN_copy(other_order, group_order)) || !TEST_true(BN_add_word(other_order, 1)) || !TEST_true(BN_copy(other_cofactor, group_cofactor)) || !TEST_true(BN_add_word(other_cofactor, 1))) goto err; EC_POINT_free(other_gen); other_gen = NULL; if (!TEST_ptr(other_gen = EC_POINT_new(tmpg)) || !TEST_true(EC_POINT_set_affine_coordinates(tmpg, other_gen, other_gen_x, other_gen_y, bn_ctx))) goto err; /* * ########################### * # Actual tests start here # * ########################### */ /* * Creating a group from built-in explicit parameters returns a * "named" EC_GROUP */ if (!TEST_ptr(tgroup = *g_next++ = EC_GROUP_new_from_ecparameters(params)) || !TEST_int_ne((tnid = EC_GROUP_get_curve_name(tgroup)), NID_undef)) goto err; /* * We cannot always guarantee the names match, as the built-in table * contains aliases for the same curve with different names. */ if (!TEST_true(are_ec_nids_compatible(nid, tnid))) { TEST_info("nid = %s, tnid = %s", OBJ_nid2sn(nid), OBJ_nid2sn(tnid)); goto err; } /* Ensure that the OPENSSL_EC_EXPLICIT_CURVE ASN1 flag is set. */ if (!TEST_int_eq(EC_GROUP_get_asn1_flag(tgroup), OPENSSL_EC_EXPLICIT_CURVE)) goto err; /* * An invalid seed in the parameters should be ignored: expect a "named" * group. */ if (!TEST_int_eq(EC_GROUP_set_seed(tmpg, invalid_seed, invalid_seed_len), invalid_seed_len) || !TEST_ptr(other_params = *p_next++ = EC_GROUP_get_ecparameters(tmpg, NULL)) || !TEST_ptr(tgroup = *g_next++ = EC_GROUP_new_from_ecparameters(other_params)) || !TEST_int_ne((tnid = EC_GROUP_get_curve_name(tgroup)), NID_undef) || !TEST_true(are_ec_nids_compatible(nid, tnid)) || !TEST_int_eq(EC_GROUP_get_asn1_flag(tgroup), OPENSSL_EC_EXPLICIT_CURVE)) { TEST_info("nid = %s, tnid = %s", OBJ_nid2sn(nid), OBJ_nid2sn(tnid)); goto err; } /* * A null seed in the parameters should be ignored, as it is optional: * expect a "named" group. */ if (!TEST_int_eq(EC_GROUP_set_seed(tmpg, NULL, 0), 1) || !TEST_ptr(other_params = *p_next++ = EC_GROUP_get_ecparameters(tmpg, NULL)) || !TEST_ptr(tgroup = *g_next++ = EC_GROUP_new_from_ecparameters(other_params)) || !TEST_int_ne((tnid = EC_GROUP_get_curve_name(tgroup)), NID_undef) || !TEST_true(are_ec_nids_compatible(nid, tnid)) || !TEST_int_eq(EC_GROUP_get_asn1_flag(tgroup), OPENSSL_EC_EXPLICIT_CURVE)) { TEST_info("nid = %s, tnid = %s", OBJ_nid2sn(nid), OBJ_nid2sn(tnid)); goto err; } /* * Check that changing any of the generator parameters does not yield a * match with the built-in curves */ if (/* Other gen, same group order & cofactor */ !TEST_true(EC_GROUP_set_generator(tmpg, other_gen, group_order, group_cofactor)) || !TEST_ptr(other_params = *p_next++ = EC_GROUP_get_ecparameters(tmpg, NULL)) || !TEST_ptr(tgroup = *g_next++ = EC_GROUP_new_from_ecparameters(other_params)) || !TEST_int_eq((tnid = EC_GROUP_get_curve_name(tgroup)), NID_undef) /* Same gen & cofactor, different order */ || !TEST_true(EC_GROUP_set_generator(tmpg, group_gen, other_order, group_cofactor)) || !TEST_ptr(other_params = *p_next++ = EC_GROUP_get_ecparameters(tmpg, NULL)) || !TEST_ptr(tgroup = *g_next++ = EC_GROUP_new_from_ecparameters(other_params)) || !TEST_int_eq((tnid = EC_GROUP_get_curve_name(tgroup)), NID_undef) /* The order is not an optional field, so this should fail */ || !TEST_false(EC_GROUP_set_generator(tmpg, group_gen, NULL, group_cofactor)) /* Check that a wrong cofactor is ignored, and we still match */ || !TEST_true(EC_GROUP_set_generator(tmpg, group_gen, group_order, other_cofactor)) || !TEST_ptr(other_params = *p_next++ = EC_GROUP_get_ecparameters(tmpg, NULL)) || !TEST_ptr(tgroup = *g_next++ = EC_GROUP_new_from_ecparameters(other_params)) || !TEST_int_ne((tnid = EC_GROUP_get_curve_name(tgroup)), NID_undef) || !TEST_true(are_ec_nids_compatible(nid, tnid)) || !TEST_int_eq(EC_GROUP_get_asn1_flag(tgroup), OPENSSL_EC_EXPLICIT_CURVE) /* Check that if the cofactor is not set then it still matches */ || !TEST_true(EC_GROUP_set_generator(tmpg, group_gen, group_order, NULL)) || !TEST_ptr(other_params = *p_next++ = EC_GROUP_get_ecparameters(tmpg, NULL)) || !TEST_ptr(tgroup = *g_next++ = EC_GROUP_new_from_ecparameters(other_params)) || !TEST_int_ne((tnid = EC_GROUP_get_curve_name(tgroup)), NID_undef) || !TEST_true(are_ec_nids_compatible(nid, tnid)) || !TEST_int_eq(EC_GROUP_get_asn1_flag(tgroup), OPENSSL_EC_EXPLICIT_CURVE) /* check that restoring the generator passes */ || !TEST_true(EC_GROUP_set_generator(tmpg, group_gen, group_order, group_cofactor)) || !TEST_ptr(other_params = *p_next++ = EC_GROUP_get_ecparameters(tmpg, NULL)) || !TEST_ptr(tgroup = *g_next++ = EC_GROUP_new_from_ecparameters(other_params)) || !TEST_int_ne((tnid = EC_GROUP_get_curve_name(tgroup)), NID_undef) || !TEST_true(are_ec_nids_compatible(nid, tnid)) || !TEST_int_eq(EC_GROUP_get_asn1_flag(tgroup), OPENSSL_EC_EXPLICIT_CURVE)) goto err; ret = 1; err: for (g_next = &g_ary[0]; g_next < g_ary + OSSL_NELEM(g_ary); g_next++) EC_GROUP_free(*g_next); for (p_next = &p_ary[0]; p_next < p_ary + OSSL_NELEM(g_ary); p_next++) ECPARAMETERS_free(*p_next); ECPARAMETERS_free(params); EC_POINT_free(other_gen); EC_GROUP_free(tmpg); EC_GROUP_free(group); BN_CTX_end(bn_ctx); BN_CTX_free(bn_ctx); return ret; } static int parameter_test(void) { EC_GROUP *group = NULL, *group2 = NULL; ECPARAMETERS *ecparameters = NULL; unsigned char *buf = NULL; int r = 0, len; if (!TEST_ptr(group = EC_GROUP_new_by_curve_name(NID_secp384r1)) || !TEST_ptr(ecparameters = EC_GROUP_get_ecparameters(group, NULL)) || !TEST_ptr(group2 = EC_GROUP_new_from_ecparameters(ecparameters)) || !TEST_int_eq(EC_GROUP_cmp(group, group2, NULL), 0)) goto err; EC_GROUP_free(group); group = NULL; /* Test the named curve encoding, which should be default. */ if (!TEST_ptr(group = EC_GROUP_new_by_curve_name(NID_secp521r1)) || !TEST_true((len = i2d_ECPKParameters(group, &buf)) >= 0) || !TEST_mem_eq(buf, len, p521_named, sizeof(p521_named))) goto err; OPENSSL_free(buf); buf = NULL; /* * Test the explicit encoding. P-521 requires correctly zero-padding the * curve coefficients. */ EC_GROUP_set_asn1_flag(group, OPENSSL_EC_EXPLICIT_CURVE); if (!TEST_true((len = i2d_ECPKParameters(group, &buf)) >= 0) || !TEST_mem_eq(buf, len, p521_explicit, sizeof(p521_explicit))) goto err; r = 1; err: EC_GROUP_free(group); EC_GROUP_free(group2); ECPARAMETERS_free(ecparameters); OPENSSL_free(buf); return r; } /* * This test validates converting an EC_GROUP to an OSSL_PARAM array * using EC_GROUP_to_params(). A named and an explicit curve are tested. */ static int ossl_parameter_test(void) { EC_GROUP *group_nmd = NULL, *group_nmd2 = NULL, *group_nmd3 = NULL; EC_GROUP *group_exp = NULL, *group_exp2 = NULL; OSSL_PARAM *params_nmd = NULL, *params_nmd2 = NULL; OSSL_PARAM *params_exp = NULL, *params_exp2 = NULL; unsigned char *buf = NULL, *buf2 = NULL; BN_CTX *bn_ctx = NULL; OSSL_PARAM_BLD *bld = NULL; BIGNUM *p, *a, *b; const EC_POINT *group_gen = NULL; size_t bsize; int r = 0; if (!TEST_ptr(bn_ctx = BN_CTX_new())) goto err; /* test named curve */ if (!TEST_ptr(group_nmd = EC_GROUP_new_by_curve_name(NID_secp384r1)) /* test with null BN_CTX */ || !TEST_ptr(params_nmd = EC_GROUP_to_params( group_nmd, NULL, NULL, NULL)) || !TEST_ptr(group_nmd2 = EC_GROUP_new_from_params( params_nmd, NULL, NULL)) || !TEST_int_eq(EC_GROUP_cmp(group_nmd, group_nmd2, NULL), 0) /* test with BN_CTX set */ || !TEST_ptr(params_nmd2 = EC_GROUP_to_params( group_nmd, NULL, NULL, bn_ctx)) || !TEST_ptr(group_nmd3 = EC_GROUP_new_from_params( params_nmd2, NULL, NULL)) || !TEST_int_eq(EC_GROUP_cmp(group_nmd, group_nmd3, NULL), 0)) goto err; /* test explicit curve */ if (!TEST_ptr(bld = OSSL_PARAM_BLD_new())) goto err; BN_CTX_start(bn_ctx); p = BN_CTX_get(bn_ctx); a = BN_CTX_get(bn_ctx); b = BN_CTX_get(bn_ctx); if (!TEST_true(EC_GROUP_get_curve(group_nmd, p, a, b, bn_ctx)) || !TEST_true(OSSL_PARAM_BLD_push_utf8_string( bld, OSSL_PKEY_PARAM_EC_FIELD_TYPE, SN_X9_62_prime_field, 0)) || !TEST_true(OSSL_PARAM_BLD_push_BN(bld, OSSL_PKEY_PARAM_EC_P, p)) || !TEST_true(OSSL_PARAM_BLD_push_BN(bld, OSSL_PKEY_PARAM_EC_A, a)) || !TEST_true(OSSL_PARAM_BLD_push_BN(bld, OSSL_PKEY_PARAM_EC_B, b))) goto err; if (EC_GROUP_get0_seed(group_nmd) != NULL) { if (!TEST_true(OSSL_PARAM_BLD_push_octet_string( bld, OSSL_PKEY_PARAM_EC_SEED, EC_GROUP_get0_seed(group_nmd), EC_GROUP_get_seed_len(group_nmd)))) goto err; } if (EC_GROUP_get0_cofactor(group_nmd) != NULL) { if (!TEST_true(OSSL_PARAM_BLD_push_BN( bld, OSSL_PKEY_PARAM_EC_COFACTOR, EC_GROUP_get0_cofactor(group_nmd)))) goto err; } if (!TEST_ptr(group_gen = EC_GROUP_get0_generator(group_nmd)) || !TEST_size_t_gt(bsize = EC_POINT_point2oct( group_nmd, EC_GROUP_get0_generator(group_nmd), POINT_CONVERSION_UNCOMPRESSED, NULL, 0, bn_ctx), 0) || !TEST_ptr(buf2 = OPENSSL_malloc(bsize)) || !TEST_size_t_eq(EC_POINT_point2oct( group_nmd, EC_GROUP_get0_generator(group_nmd), POINT_CONVERSION_UNCOMPRESSED, buf2, bsize, bn_ctx), bsize) || !TEST_true(OSSL_PARAM_BLD_push_octet_string( bld, OSSL_PKEY_PARAM_EC_GENERATOR, buf2, bsize)) || !TEST_true(OSSL_PARAM_BLD_push_BN( bld, OSSL_PKEY_PARAM_EC_ORDER, EC_GROUP_get0_order(group_nmd)))) goto err; if (!TEST_ptr(params_exp = OSSL_PARAM_BLD_to_param(bld)) || !TEST_ptr(group_exp = EC_GROUP_new_from_params(params_exp, NULL, NULL)) || !TEST_ptr(params_exp2 = EC_GROUP_to_params(group_exp, NULL, NULL, NULL)) || !TEST_ptr(group_exp2 = EC_GROUP_new_from_params(params_exp2, NULL, NULL)) || !TEST_int_eq(EC_GROUP_cmp(group_exp, group_exp2, NULL), 0)) goto err; r = 1; err: EC_GROUP_free(group_nmd); EC_GROUP_free(group_nmd2); EC_GROUP_free(group_nmd3); OSSL_PARAM_free(params_nmd); OSSL_PARAM_free(params_nmd2); OPENSSL_free(buf); EC_GROUP_free(group_exp); EC_GROUP_free(group_exp2); BN_CTX_end(bn_ctx); BN_CTX_free(bn_ctx); OPENSSL_free(buf2); OSSL_PARAM_BLD_free(bld); OSSL_PARAM_free(params_exp); OSSL_PARAM_free(params_exp2); return r; } /*- * random 256-bit explicit parameters curve, cofactor absent * order: 0x0c38d96a9f892b88772ec2e39614a82f4f (132 bit) * cofactor: 0x12bc94785251297abfafddf1565100da (125 bit) */ static const unsigned char params_cf_pass[] = { 0x30, 0x81, 0xcd, 0x02, 0x01, 0x01, 0x30, 0x2c, 0x06, 0x07, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x01, 0x01, 0x02, 0x21, 0x00, 0xe5, 0x00, 0x1f, 0xc5, 0xca, 0x71, 0x9d, 0x8e, 0xf7, 0x07, 0x4b, 0x48, 0x37, 0xf9, 0x33, 0x2d, 0x71, 0xbf, 0x79, 0xe7, 0xdc, 0x91, 0xc2, 0xff, 0xb6, 0x7b, 0xc3, 0x93, 0x44, 0x88, 0xe6, 0x91, 0x30, 0x44, 0x04, 0x20, 0xe5, 0x00, 0x1f, 0xc5, 0xca, 0x71, 0x9d, 0x8e, 0xf7, 0x07, 0x4b, 0x48, 0x37, 0xf9, 0x33, 0x2d, 0x71, 0xbf, 0x79, 0xe7, 0xdc, 0x91, 0xc2, 0xff, 0xb6, 0x7b, 0xc3, 0x93, 0x44, 0x88, 0xe6, 0x8e, 0x04, 0x20, 0x18, 0x8c, 0x59, 0x57, 0xc4, 0xbc, 0x85, 0x57, 0xc3, 0x66, 0x9f, 0x89, 0xd5, 0x92, 0x0d, 0x7e, 0x42, 0x27, 0x07, 0x64, 0xaa, 0x26, 0xed, 0x89, 0xc4, 0x09, 0x05, 0x4d, 0xc7, 0x23, 0x47, 0xda, 0x04, 0x41, 0x04, 0x1b, 0x6b, 0x41, 0x0b, 0xf9, 0xfb, 0x77, 0xfd, 0x50, 0xb7, 0x3e, 0x23, 0xa3, 0xec, 0x9a, 0x3b, 0x09, 0x31, 0x6b, 0xfa, 0xf6, 0xce, 0x1f, 0xff, 0xeb, 0x57, 0x93, 0x24, 0x70, 0xf3, 0xf4, 0xba, 0x7e, 0xfa, 0x86, 0x6e, 0x19, 0x89, 0xe3, 0x55, 0x6d, 0x5a, 0xe9, 0xc0, 0x3d, 0xbc, 0xfb, 0xaf, 0xad, 0xd4, 0x7e, 0xa6, 0xe5, 0xfa, 0x1a, 0x58, 0x07, 0x9e, 0x8f, 0x0d, 0x3b, 0xf7, 0x38, 0xca, 0x02, 0x11, 0x0c, 0x38, 0xd9, 0x6a, 0x9f, 0x89, 0x2b, 0x88, 0x77, 0x2e, 0xc2, 0xe3, 0x96, 0x14, 0xa8, 0x2f, 0x4f }; /*- * random 256-bit explicit parameters curve, cofactor absent * order: 0x045a75c0c17228ebd9b169a10e34a22101 (131 bit) * cofactor: 0x2e134b4ede82649f67a2e559d361e5fe (126 bit) */ static const unsigned char params_cf_fail[] = { 0x30, 0x81, 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d, 0x02, 0x11, 0x04, 0x5a, 0x75, 0xc0, 0xc1, 0x72, 0x28, 0xeb, 0xd9, 0xb1, 0x69, 0xa1, 0x0e, 0x34, 0xa2, 0x21, 0x01 }; /*- * Test two random 256-bit explicit parameters curves with absent cofactor. * The two curves are chosen to roughly straddle the bounds at which the lib * can compute the cofactor automatically, roughly 4*sqrt(p). So test that: * * - params_cf_pass: order is sufficiently close to p to compute cofactor * - params_cf_fail: order is too far away from p to compute cofactor * * For standards-compliant curves, cofactor is chosen as small as possible. * So you can see neither of these curves are fit for cryptographic use. * * Some standards even mandate an upper bound on the cofactor, e.g. SECG1 v2: * h <= 2**(t/8) where t is the security level of the curve, for which the lib * will always succeed in computing the cofactor. Neither of these curves * conform to that -- this is just robustness testing. */ static int cofactor_range_test(void) { EC_GROUP *group = NULL; BIGNUM *cf = NULL; int ret = 0; const unsigned char *b1 = (const unsigned char *)params_cf_fail; const unsigned char *b2 = (const unsigned char *)params_cf_pass; if (!TEST_ptr(group = d2i_ECPKParameters(NULL, &b1, sizeof(params_cf_fail))) || !TEST_BN_eq_zero(EC_GROUP_get0_cofactor(group)) || !TEST_ptr(group = d2i_ECPKParameters(&group, &b2, sizeof(params_cf_pass))) || !TEST_int_gt(BN_hex2bn(&cf, "12bc94785251297abfafddf1565100da"), 0) || !TEST_BN_eq(cf, EC_GROUP_get0_cofactor(group))) goto err; ret = 1; err: BN_free(cf); EC_GROUP_free(group); return ret; } /*- * For named curves, test that: * - the lib correctly computes the cofactor if passed a NULL or zero cofactor * - a nonsensical cofactor throws an error (negative test) * - nonsensical orders throw errors (negative tests) */ static int cardinality_test(int n) { int ret = 0, is_binary = 0; int nid = curves[n].nid; BN_CTX *ctx = NULL; EC_GROUP *g1 = NULL, *g2 = NULL; EC_POINT *g2_gen = NULL; BIGNUM *g1_p = NULL, *g1_a = NULL, *g1_b = NULL, *g1_x = NULL, *g1_y = NULL, *g1_order = NULL, *g1_cf = NULL, *g2_cf = NULL; TEST_info("Curve %s cardinality test", OBJ_nid2sn(nid)); if (!TEST_ptr(ctx = BN_CTX_new()) || !TEST_ptr(g1 = EC_GROUP_new_by_curve_name(nid))) { BN_CTX_free(ctx); return 0; } is_binary = (EC_GROUP_get_field_type(g1) == NID_X9_62_characteristic_two_field); BN_CTX_start(ctx); g1_p = BN_CTX_get(ctx); g1_a = BN_CTX_get(ctx); g1_b = BN_CTX_get(ctx); g1_x = BN_CTX_get(ctx); g1_y = BN_CTX_get(ctx); g1_order = BN_CTX_get(ctx); g1_cf = BN_CTX_get(ctx); if (!TEST_ptr(g2_cf = BN_CTX_get(ctx)) /* pull out the explicit curve parameters */ || !TEST_true(EC_GROUP_get_curve(g1, g1_p, g1_a, g1_b, ctx)) || !TEST_true(EC_POINT_get_affine_coordinates(g1, EC_GROUP_get0_generator(g1), g1_x, g1_y, ctx)) || !TEST_true(BN_copy(g1_order, EC_GROUP_get0_order(g1))) || !TEST_true(EC_GROUP_get_cofactor(g1, g1_cf, ctx)) /* construct g2 manually with g1 parameters */ #ifndef OPENSSL_NO_EC2M || !TEST_ptr(g2 = (is_binary) ? EC_GROUP_new_curve_GF2m(g1_p, g1_a, g1_b, ctx) : EC_GROUP_new_curve_GFp(g1_p, g1_a, g1_b, ctx)) #else || !TEST_int_eq(0, is_binary) || !TEST_ptr(g2 = EC_GROUP_new_curve_GFp(g1_p, g1_a, g1_b, ctx)) #endif || !TEST_ptr(g2_gen = EC_POINT_new(g2)) || !TEST_true(EC_POINT_set_affine_coordinates(g2, g2_gen, g1_x, g1_y, ctx)) /* pass NULL cofactor: lib should compute it */ || !TEST_true(EC_GROUP_set_generator(g2, g2_gen, g1_order, NULL)) || !TEST_true(EC_GROUP_get_cofactor(g2, g2_cf, ctx)) || !TEST_BN_eq(g1_cf, g2_cf) /* pass zero cofactor: lib should compute it */ || !TEST_true(BN_set_word(g2_cf, 0)) || !TEST_true(EC_GROUP_set_generator(g2, g2_gen, g1_order, g2_cf)) || !TEST_true(EC_GROUP_get_cofactor(g2, g2_cf, ctx)) || !TEST_BN_eq(g1_cf, g2_cf) /* negative test for invalid cofactor */ || !TEST_true(BN_set_word(g2_cf, 0)) || !TEST_true(BN_sub(g2_cf, g2_cf, BN_value_one())) || !TEST_false(EC_GROUP_set_generator(g2, g2_gen, g1_order, g2_cf)) /* negative test for NULL order */ || !TEST_false(EC_GROUP_set_generator(g2, g2_gen, NULL, NULL)) /* negative test for zero order */ || !TEST_true(BN_set_word(g1_order, 0)) || !TEST_false(EC_GROUP_set_generator(g2, g2_gen, g1_order, NULL)) /* negative test for negative order */ || !TEST_true(BN_set_word(g2_cf, 0)) || !TEST_true(BN_sub(g2_cf, g2_cf, BN_value_one())) || !TEST_false(EC_GROUP_set_generator(g2, g2_gen, g1_order, NULL)) /* negative test for too large order */ || !TEST_true(BN_lshift(g1_order, g1_p, 2)) || !TEST_false(EC_GROUP_set_generator(g2, g2_gen, g1_order, NULL))) goto err; ret = 1; err: EC_POINT_free(g2_gen); EC_GROUP_free(g1); EC_GROUP_free(g2); BN_CTX_end(ctx); BN_CTX_free(ctx); return ret; } static int check_ec_key_field_public_range_test(int id) { int ret = 0, type = 0; const EC_POINT *pub = NULL; const EC_GROUP *group = NULL; const BIGNUM *field = NULL; BIGNUM *x = NULL, *y = NULL; EC_KEY *key = NULL; if (!TEST_ptr(x = BN_new()) || !TEST_ptr(y = BN_new()) || !TEST_ptr(key = EC_KEY_new_by_curve_name(curves[id].nid)) || !TEST_ptr(group = EC_KEY_get0_group(key)) || !TEST_ptr(field = EC_GROUP_get0_field(group)) || !TEST_int_gt(EC_KEY_generate_key(key), 0) || !TEST_int_gt(EC_KEY_check_key(key), 0) || !TEST_ptr(pub = EC_KEY_get0_public_key(key)) || !TEST_int_gt(EC_POINT_get_affine_coordinates(group, pub, x, y, NULL), 0)) goto err; /* * Make the public point out of range by adding the field (which will still * be the same point on the curve). The add is different for char2 fields. */ type = EC_GROUP_get_field_type(group); #ifndef OPENSSL_NO_EC2M if (type == NID_X9_62_characteristic_two_field) { /* test for binary curves */ if (!TEST_true(BN_GF2m_add(x, x, field))) goto err; } else #endif if (type == NID_X9_62_prime_field) { /* test for prime curves */ if (!TEST_true(BN_add(x, x, field))) goto err; } else { /* this should never happen */ TEST_error("Unsupported EC_METHOD field_type"); goto err; } if (!TEST_int_le(EC_KEY_set_public_key_affine_coordinates(key, x, y), 0)) goto err; ret = 1; err: BN_free(x); BN_free(y); EC_KEY_free(key); return ret; } /* * Helper for ec_point_hex2point_test * * Self-tests EC_POINT_point2hex() against EC_POINT_hex2point() for the given * (group,P) pair. * * If P is NULL use point at infinity. */ static ossl_inline int ec_point_hex2point_test_helper(const EC_GROUP *group, const EC_POINT *P, point_conversion_form_t form, BN_CTX *bnctx) { int ret = 0; EC_POINT *Q = NULL, *Pinf = NULL; char *hex = NULL; if (P == NULL) { /* If P is NULL use point at infinity. */ if (!TEST_ptr(Pinf = EC_POINT_new(group)) || !TEST_true(EC_POINT_set_to_infinity(group, Pinf))) goto err; P = Pinf; } if (!TEST_ptr(hex = EC_POINT_point2hex(group, P, form, bnctx)) || !TEST_ptr(Q = EC_POINT_hex2point(group, hex, NULL, bnctx)) || !TEST_int_eq(0, EC_POINT_cmp(group, Q, P, bnctx))) goto err; /* * The next check is most likely superfluous, as EC_POINT_cmp should already * cover this. * Nonetheless it increases the test coverage for EC_POINT_is_at_infinity, * so we include it anyway! */ if (Pinf != NULL && !TEST_true(EC_POINT_is_at_infinity(group, Q))) goto err; ret = 1; err: EC_POINT_free(Pinf); OPENSSL_free(hex); EC_POINT_free(Q); return ret; } /* * This test self-validates EC_POINT_hex2point() and EC_POINT_point2hex() */ static int ec_point_hex2point_test(int id) { int ret = 0, nid; EC_GROUP *group = NULL; const EC_POINT *G = NULL; EC_POINT *P = NULL; BN_CTX *bnctx = NULL; /* Do some setup */ nid = curves[id].nid; if (!TEST_ptr(bnctx = BN_CTX_new()) || !TEST_ptr(group = EC_GROUP_new_by_curve_name(nid)) || !TEST_ptr(G = EC_GROUP_get0_generator(group)) || !TEST_ptr(P = EC_POINT_dup(G, group))) goto err; if (!TEST_true(ec_point_hex2point_test_helper(group, P, POINT_CONVERSION_COMPRESSED, bnctx)) || !TEST_true(ec_point_hex2point_test_helper(group, NULL, POINT_CONVERSION_COMPRESSED, bnctx)) || !TEST_true(ec_point_hex2point_test_helper(group, P, POINT_CONVERSION_UNCOMPRESSED, bnctx)) || !TEST_true(ec_point_hex2point_test_helper(group, NULL, POINT_CONVERSION_UNCOMPRESSED, bnctx)) || !TEST_true(ec_point_hex2point_test_helper(group, P, POINT_CONVERSION_HYBRID, bnctx)) || !TEST_true(ec_point_hex2point_test_helper(group, NULL, POINT_CONVERSION_HYBRID, bnctx))) goto err; ret = 1; err: EC_POINT_free(P); EC_GROUP_free(group); BN_CTX_free(bnctx); return ret; } static int do_test_custom_explicit_fromdata(EC_GROUP *group, BN_CTX *ctx, unsigned char *gen, int gen_size) { int ret = 0, i_out; EVP_PKEY_CTX *pctx = NULL; EVP_PKEY *pkeyparam = NULL; OSSL_PARAM_BLD *bld = NULL; const char *field_name; OSSL_PARAM *params = NULL; const OSSL_PARAM *gettable; BIGNUM *p, *a, *b; BIGNUM *p_out = NULL, *a_out = NULL, *b_out = NULL; BIGNUM *order_out = NULL, *cofactor_out = NULL; char name[80]; unsigned char buf[1024]; size_t buf_len, name_len; #ifndef OPENSSL_NO_EC2M unsigned int k1 = 0, k2 = 0, k3 = 0; const char *basis_name = NULL; #endif p = BN_CTX_get(ctx); a = BN_CTX_get(ctx); b = BN_CTX_get(ctx); if (!TEST_ptr(b) || !TEST_ptr(bld = OSSL_PARAM_BLD_new())) goto err; if (EC_GROUP_get_field_type(group) == NID_X9_62_prime_field) { field_name = SN_X9_62_prime_field; } else { field_name = SN_X9_62_characteristic_two_field; #ifndef OPENSSL_NO_EC2M if (EC_GROUP_get_basis_type(group) == NID_X9_62_tpBasis) { basis_name = SN_X9_62_tpBasis; if (!TEST_true(EC_GROUP_get_trinomial_basis(group, &k1))) goto err; } else { basis_name = SN_X9_62_ppBasis; if (!TEST_true(EC_GROUP_get_pentanomial_basis(group, &k1, &k2, &k3))) goto err; } #endif /* OPENSSL_NO_EC2M */ } if (!TEST_true(EC_GROUP_get_curve(group, p, a, b, ctx)) || !TEST_true(OSSL_PARAM_BLD_push_utf8_string(bld, OSSL_PKEY_PARAM_EC_FIELD_TYPE, field_name, 0)) || !TEST_true(OSSL_PARAM_BLD_push_BN(bld, OSSL_PKEY_PARAM_EC_P, p)) || !TEST_true(OSSL_PARAM_BLD_push_BN(bld, OSSL_PKEY_PARAM_EC_A, a)) || !TEST_true(OSSL_PARAM_BLD_push_BN(bld, OSSL_PKEY_PARAM_EC_B, b))) goto err; if (EC_GROUP_get0_seed(group) != NULL) { if (!TEST_true(OSSL_PARAM_BLD_push_octet_string(bld, OSSL_PKEY_PARAM_EC_SEED, EC_GROUP_get0_seed(group), EC_GROUP_get_seed_len(group)))) goto err; } if (EC_GROUP_get0_cofactor(group) != NULL) { if (!TEST_true(OSSL_PARAM_BLD_push_BN(bld, OSSL_PKEY_PARAM_EC_COFACTOR, EC_GROUP_get0_cofactor(group)))) goto err; } if (!TEST_true(OSSL_PARAM_BLD_push_octet_string(bld, OSSL_PKEY_PARAM_EC_GENERATOR, gen, gen_size)) || !TEST_true(OSSL_PARAM_BLD_push_BN(bld, OSSL_PKEY_PARAM_EC_ORDER, EC_GROUP_get0_order(group)))) goto err; if (!TEST_ptr(params = OSSL_PARAM_BLD_to_param(bld)) || !TEST_ptr(pctx = EVP_PKEY_CTX_new_from_name(NULL, "EC", NULL)) || !TEST_int_gt(EVP_PKEY_fromdata_init(pctx), 0) || !TEST_int_gt(EVP_PKEY_fromdata(pctx, &pkeyparam, EVP_PKEY_KEY_PARAMETERS, params), 0)) goto err; /*- Check that all the set values are retrievable -*/ /* There should be no match to a group name since the generator changed */ if (!TEST_false(EVP_PKEY_get_utf8_string_param(pkeyparam, OSSL_PKEY_PARAM_GROUP_NAME, name, sizeof(name), &name_len))) goto err; /* The encoding should be explicit as it has no group */ if (!TEST_true(EVP_PKEY_get_utf8_string_param(pkeyparam, OSSL_PKEY_PARAM_EC_ENCODING, name, sizeof(name), &name_len)) || !TEST_str_eq(name, OSSL_PKEY_EC_ENCODING_EXPLICIT)) goto err; if (!TEST_true(EVP_PKEY_get_utf8_string_param(pkeyparam, OSSL_PKEY_PARAM_EC_FIELD_TYPE, name, sizeof(name), &name_len)) || !TEST_str_eq(name, field_name)) goto err; if (!TEST_true(EVP_PKEY_get_octet_string_param(pkeyparam, OSSL_PKEY_PARAM_EC_GENERATOR, buf, sizeof(buf), &buf_len)) || !TEST_mem_eq(buf, (int)buf_len, gen, gen_size)) goto err; if (!TEST_true(EVP_PKEY_get_bn_param(pkeyparam, OSSL_PKEY_PARAM_EC_P, &p_out)) || !TEST_BN_eq(p_out, p) || !TEST_true(EVP_PKEY_get_bn_param(pkeyparam, OSSL_PKEY_PARAM_EC_A, &a_out)) || !TEST_BN_eq(a_out, a) || !TEST_true(EVP_PKEY_get_bn_param(pkeyparam, OSSL_PKEY_PARAM_EC_B, &b_out)) || !TEST_BN_eq(b_out, b) || !TEST_true(EVP_PKEY_get_bn_param(pkeyparam, OSSL_PKEY_PARAM_EC_ORDER, &order_out)) || !TEST_BN_eq(order_out, EC_GROUP_get0_order(group))) goto err; if (EC_GROUP_get0_cofactor(group) != NULL) { if (!TEST_true(EVP_PKEY_get_bn_param(pkeyparam, OSSL_PKEY_PARAM_EC_COFACTOR, &cofactor_out)) || !TEST_BN_eq(cofactor_out, EC_GROUP_get0_cofactor(group))) goto err; } if (EC_GROUP_get0_seed(group) != NULL) { if (!TEST_true(EVP_PKEY_get_octet_string_param(pkeyparam, OSSL_PKEY_PARAM_EC_SEED, buf, sizeof(buf), &buf_len)) || !TEST_mem_eq(buf, buf_len, EC_GROUP_get0_seed(group), EC_GROUP_get_seed_len(group))) goto err; } if (EC_GROUP_get_field_type(group) == NID_X9_62_prime_field) { /* No extra fields should be set for a prime field */ if (!TEST_false(EVP_PKEY_get_int_param(pkeyparam, OSSL_PKEY_PARAM_EC_CHAR2_M, &i_out)) || !TEST_false(EVP_PKEY_get_int_param(pkeyparam, OSSL_PKEY_PARAM_EC_CHAR2_TP_BASIS, &i_out)) || !TEST_false(EVP_PKEY_get_int_param(pkeyparam, OSSL_PKEY_PARAM_EC_CHAR2_PP_K1, &i_out)) || !TEST_false(EVP_PKEY_get_int_param(pkeyparam, OSSL_PKEY_PARAM_EC_CHAR2_PP_K2, &i_out)) || !TEST_false(EVP_PKEY_get_int_param(pkeyparam, OSSL_PKEY_PARAM_EC_CHAR2_PP_K3, &i_out)) || !TEST_false(EVP_PKEY_get_utf8_string_param(pkeyparam, OSSL_PKEY_PARAM_EC_CHAR2_TYPE, name, sizeof(name), &name_len))) goto err; } else { #ifndef OPENSSL_NO_EC2M if (!TEST_true(EVP_PKEY_get_int_param(pkeyparam, OSSL_PKEY_PARAM_EC_CHAR2_M, &i_out)) || !TEST_int_eq(EC_GROUP_get_degree(group), i_out) || !TEST_true(EVP_PKEY_get_utf8_string_param(pkeyparam, OSSL_PKEY_PARAM_EC_CHAR2_TYPE, name, sizeof(name), &name_len)) || !TEST_str_eq(name, basis_name)) goto err; if (EC_GROUP_get_basis_type(group) == NID_X9_62_tpBasis) { if (!TEST_true(EVP_PKEY_get_int_param(pkeyparam, OSSL_PKEY_PARAM_EC_CHAR2_TP_BASIS, &i_out)) || !TEST_int_eq(k1, i_out) || !TEST_false(EVP_PKEY_get_int_param(pkeyparam, OSSL_PKEY_PARAM_EC_CHAR2_PP_K1, &i_out)) || !TEST_false(EVP_PKEY_get_int_param(pkeyparam, OSSL_PKEY_PARAM_EC_CHAR2_PP_K2, &i_out)) || !TEST_false(EVP_PKEY_get_int_param(pkeyparam, OSSL_PKEY_PARAM_EC_CHAR2_PP_K3, &i_out))) goto err; } else { if (!TEST_false(EVP_PKEY_get_int_param(pkeyparam, OSSL_PKEY_PARAM_EC_CHAR2_TP_BASIS, &i_out)) || !TEST_true(EVP_PKEY_get_int_param(pkeyparam, OSSL_PKEY_PARAM_EC_CHAR2_PP_K1, &i_out)) || !TEST_int_eq(k1, i_out) || !TEST_true(EVP_PKEY_get_int_param(pkeyparam, OSSL_PKEY_PARAM_EC_CHAR2_PP_K2, &i_out)) || !TEST_int_eq(k2, i_out) || !TEST_true(EVP_PKEY_get_int_param(pkeyparam, OSSL_PKEY_PARAM_EC_CHAR2_PP_K3, &i_out)) || !TEST_int_eq(k3, i_out)) goto err; } #endif /* OPENSSL_NO_EC2M */ } if (!TEST_ptr(gettable = EVP_PKEY_gettable_params(pkeyparam)) || !TEST_ptr(OSSL_PARAM_locate_const(gettable, OSSL_PKEY_PARAM_GROUP_NAME)) || !TEST_ptr(OSSL_PARAM_locate_const(gettable, OSSL_PKEY_PARAM_EC_ENCODING)) || !TEST_ptr(OSSL_PARAM_locate_const(gettable, OSSL_PKEY_PARAM_EC_FIELD_TYPE)) || !TEST_ptr(OSSL_PARAM_locate_const(gettable, OSSL_PKEY_PARAM_EC_P)) || !TEST_ptr(OSSL_PARAM_locate_const(gettable, OSSL_PKEY_PARAM_EC_A)) || !TEST_ptr(OSSL_PARAM_locate_const(gettable, OSSL_PKEY_PARAM_EC_B)) || !TEST_ptr(OSSL_PARAM_locate_const(gettable, OSSL_PKEY_PARAM_EC_GENERATOR)) || !TEST_ptr(OSSL_PARAM_locate_const(gettable, OSSL_PKEY_PARAM_EC_ORDER)) || !TEST_ptr(OSSL_PARAM_locate_const(gettable, OSSL_PKEY_PARAM_EC_COFACTOR)) || !TEST_ptr(OSSL_PARAM_locate_const(gettable, OSSL_PKEY_PARAM_EC_SEED)) #ifndef OPENSSL_NO_EC2M || !TEST_ptr(OSSL_PARAM_locate_const(gettable, OSSL_PKEY_PARAM_EC_CHAR2_M)) || !TEST_ptr(OSSL_PARAM_locate_const(gettable, OSSL_PKEY_PARAM_EC_CHAR2_TYPE)) || !TEST_ptr(OSSL_PARAM_locate_const(gettable, OSSL_PKEY_PARAM_EC_CHAR2_TP_BASIS)) || !TEST_ptr(OSSL_PARAM_locate_const(gettable, OSSL_PKEY_PARAM_EC_CHAR2_PP_K1)) || !TEST_ptr(OSSL_PARAM_locate_const(gettable, OSSL_PKEY_PARAM_EC_CHAR2_PP_K2)) || !TEST_ptr(OSSL_PARAM_locate_const(gettable, OSSL_PKEY_PARAM_EC_CHAR2_PP_K3)) #endif ) goto err; ret = 1; err: BN_free(order_out); BN_free(cofactor_out); BN_free(a_out); BN_free(b_out); BN_free(p_out); OSSL_PARAM_free(params); OSSL_PARAM_BLD_free(bld); EVP_PKEY_free(pkeyparam); EVP_PKEY_CTX_free(pctx); return ret; } /* * check the EC_METHOD respects the supplied EC_GROUP_set_generator G */ static int custom_generator_test(int id) { int ret = 0, nid, bsize; EC_GROUP *group = NULL; EC_POINT *G2 = NULL, *Q1 = NULL, *Q2 = NULL; BN_CTX *ctx = NULL; BIGNUM *k = NULL; unsigned char *b1 = NULL, *b2 = NULL; /* Do some setup */ nid = curves[id].nid; TEST_note("Curve %s", OBJ_nid2sn(nid)); if (!TEST_ptr(ctx = BN_CTX_new())) return 0; BN_CTX_start(ctx); if (!TEST_ptr(group = EC_GROUP_new_by_curve_name(nid))) goto err; /* expected byte length of encoded points */ bsize = (EC_GROUP_get_degree(group) + 7) / 8; bsize = 1 + 2 * bsize; /* UNCOMPRESSED_POINT format */ if (!TEST_ptr(k = BN_CTX_get(ctx)) /* fetch a testing scalar k != 0,1 */ || !TEST_true(BN_rand(k, EC_GROUP_order_bits(group) - 1, BN_RAND_TOP_ONE, BN_RAND_BOTTOM_ANY)) /* make k even */ || !TEST_true(BN_clear_bit(k, 0)) || !TEST_ptr(G2 = EC_POINT_new(group)) || !TEST_ptr(Q1 = EC_POINT_new(group)) /* Q1 := kG */ || !TEST_true(EC_POINT_mul(group, Q1, k, NULL, NULL, ctx)) /* pull out the bytes of that */ || !TEST_int_eq(EC_POINT_point2oct(group, Q1, POINT_CONVERSION_UNCOMPRESSED, NULL, 0, ctx), bsize) || !TEST_ptr(b1 = OPENSSL_malloc(bsize)) || !TEST_int_eq(EC_POINT_point2oct(group, Q1, POINT_CONVERSION_UNCOMPRESSED, b1, bsize, ctx), bsize) /* new generator is G2 := 2G */ || !TEST_true(EC_POINT_dbl(group, G2, EC_GROUP_get0_generator(group), ctx)) || !TEST_true(EC_GROUP_set_generator(group, G2, EC_GROUP_get0_order(group), EC_GROUP_get0_cofactor(group))) || !TEST_ptr(Q2 = EC_POINT_new(group)) || !TEST_true(BN_rshift1(k, k)) /* Q2 := k/2 G2 */ || !TEST_true(EC_POINT_mul(group, Q2, k, NULL, NULL, ctx)) || !TEST_int_eq(EC_POINT_point2oct(group, Q2, POINT_CONVERSION_UNCOMPRESSED, NULL, 0, ctx), bsize) || !TEST_ptr(b2 = OPENSSL_malloc(bsize)) || !TEST_int_eq(EC_POINT_point2oct(group, Q2, POINT_CONVERSION_UNCOMPRESSED, b2, bsize, ctx), bsize) /* Q1 = kG = k/2 G2 = Q2 should hold */ || !TEST_mem_eq(b1, bsize, b2, bsize)) goto err; if (!do_test_custom_explicit_fromdata(group, ctx, b1, bsize)) goto err; ret = 1; err: EC_POINT_free(Q1); EC_POINT_free(Q2); EC_POINT_free(G2); EC_GROUP_free(group); BN_CTX_end(ctx); BN_CTX_free(ctx); OPENSSL_free(b1); OPENSSL_free(b2); return ret; } /* * check creation of curves from explicit params through the public API */ static int custom_params_test(int id) { int ret = 0, nid, bsize; const char *curve_name = NULL; EC_GROUP *group = NULL, *altgroup = NULL; EC_POINT *G2 = NULL, *Q1 = NULL, *Q2 = NULL; const EC_POINT *Q = NULL; BN_CTX *ctx = NULL; BIGNUM *k = NULL; unsigned char *buf1 = NULL, *buf2 = NULL; const BIGNUM *z = NULL, *cof = NULL, *priv1 = NULL; BIGNUM *p = NULL, *a = NULL, *b = NULL; int is_prime = 0; EC_KEY *eckey1 = NULL, *eckey2 = NULL; EVP_PKEY *pkey1 = NULL, *pkey2 = NULL; EVP_PKEY_CTX *pctx1 = NULL, *pctx2 = NULL; size_t sslen, t; unsigned char *pub1 = NULL , *pub2 = NULL; OSSL_PARAM_BLD *param_bld = NULL; OSSL_PARAM *params1 = NULL, *params2 = NULL; /* Do some setup */ nid = curves[id].nid; curve_name = OBJ_nid2sn(nid); TEST_note("Curve %s", curve_name); if (nid == NID_sm2) return TEST_skip("custom params not supported with SM2"); if (!TEST_ptr(ctx = BN_CTX_new())) return 0; BN_CTX_start(ctx); if (!TEST_ptr(p = BN_CTX_get(ctx)) || !TEST_ptr(a = BN_CTX_get(ctx)) || !TEST_ptr(b = BN_CTX_get(ctx)) || !TEST_ptr(k = BN_CTX_get(ctx))) goto err; if (!TEST_ptr(group = EC_GROUP_new_by_curve_name(nid))) goto err; is_prime = EC_GROUP_get_field_type(group) == NID_X9_62_prime_field; #ifdef OPENSSL_NO_EC2M if (!is_prime) { ret = TEST_skip("binary curves not supported in this build"); goto err; } #endif /* expected byte length of encoded points */ bsize = (EC_GROUP_get_degree(group) + 7) / 8; bsize = 1 + 2 * bsize; /* UNCOMPRESSED_POINT format */ /* extract parameters from built-in curve */ if (!TEST_true(EC_GROUP_get_curve(group, p, a, b, ctx)) || !TEST_ptr(G2 = EC_POINT_new(group)) /* new generator is G2 := 2G */ || !TEST_true(EC_POINT_dbl(group, G2, EC_GROUP_get0_generator(group), ctx)) /* pull out the bytes of that */ || !TEST_int_eq(EC_POINT_point2oct(group, G2, POINT_CONVERSION_UNCOMPRESSED, NULL, 0, ctx), bsize) || !TEST_ptr(buf1 = OPENSSL_malloc(bsize)) || !TEST_int_eq(EC_POINT_point2oct(group, G2, POINT_CONVERSION_UNCOMPRESSED, buf1, bsize, ctx), bsize) || !TEST_ptr(z = EC_GROUP_get0_order(group)) || !TEST_ptr(cof = EC_GROUP_get0_cofactor(group)) ) goto err; /* create a new group using same params (but different generator) */ if (is_prime) { if (!TEST_ptr(altgroup = EC_GROUP_new_curve_GFp(p, a, b, ctx))) goto err; } #ifndef OPENSSL_NO_EC2M else { if (!TEST_ptr(altgroup = EC_GROUP_new_curve_GF2m(p, a, b, ctx))) goto err; } #endif /* set 2*G as the generator of altgroup */ EC_POINT_free(G2); /* discard G2 as it refers to the original group */ if (!TEST_ptr(G2 = EC_POINT_new(altgroup)) || !TEST_true(EC_POINT_oct2point(altgroup, G2, buf1, bsize, ctx)) || !TEST_int_eq(EC_POINT_is_on_curve(altgroup, G2, ctx), 1) || !TEST_true(EC_GROUP_set_generator(altgroup, G2, z, cof)) ) goto err; /* verify math checks out */ if (/* allocate temporary points on group and altgroup */ !TEST_ptr(Q1 = EC_POINT_new(group)) || !TEST_ptr(Q2 = EC_POINT_new(altgroup)) /* fetch a testing scalar k != 0,1 */ || !TEST_true(BN_rand(k, EC_GROUP_order_bits(group) - 1, BN_RAND_TOP_ONE, BN_RAND_BOTTOM_ANY)) /* make k even */ || !TEST_true(BN_clear_bit(k, 0)) /* Q1 := kG on group */ || !TEST_true(EC_POINT_mul(group, Q1, k, NULL, NULL, ctx)) /* pull out the bytes of that */ || !TEST_int_eq(EC_POINT_point2oct(group, Q1, POINT_CONVERSION_UNCOMPRESSED, NULL, 0, ctx), bsize) || !TEST_int_eq(EC_POINT_point2oct(group, Q1, POINT_CONVERSION_UNCOMPRESSED, buf1, bsize, ctx), bsize) /* k := k/2 */ || !TEST_true(BN_rshift1(k, k)) /* Q2 := k/2 G2 on altgroup */ || !TEST_true(EC_POINT_mul(altgroup, Q2, k, NULL, NULL, ctx)) /* pull out the bytes of that */ || !TEST_int_eq(EC_POINT_point2oct(altgroup, Q2, POINT_CONVERSION_UNCOMPRESSED, NULL, 0, ctx), bsize) || !TEST_ptr(buf2 = OPENSSL_malloc(bsize)) || !TEST_int_eq(EC_POINT_point2oct(altgroup, Q2, POINT_CONVERSION_UNCOMPRESSED, buf2, bsize, ctx), bsize) /* Q1 = kG = k/2 G2 = Q2 should hold */ || !TEST_mem_eq(buf1, bsize, buf2, bsize)) goto err; /* create two `EC_KEY`s on altgroup */ if (!TEST_ptr(eckey1 = EC_KEY_new()) || !TEST_true(EC_KEY_set_group(eckey1, altgroup)) || !TEST_true(EC_KEY_generate_key(eckey1)) || !TEST_ptr(eckey2 = EC_KEY_new()) || !TEST_true(EC_KEY_set_group(eckey2, altgroup)) || !TEST_true(EC_KEY_generate_key(eckey2))) goto err; /* retrieve priv1 for later */ if (!TEST_ptr(priv1 = EC_KEY_get0_private_key(eckey1))) goto err; /* * retrieve bytes for pub1 for later * * We compute the pub key in the original group as we will later use it to * define a provider key in the built-in group. */ if (!TEST_true(EC_POINT_mul(group, Q1, priv1, NULL, NULL, ctx)) || !TEST_int_eq(EC_POINT_point2oct(group, Q1, POINT_CONVERSION_UNCOMPRESSED, NULL, 0, ctx), bsize) || !TEST_ptr(pub1 = OPENSSL_malloc(bsize)) || !TEST_int_eq(EC_POINT_point2oct(group, Q1, POINT_CONVERSION_UNCOMPRESSED, pub1, bsize, ctx), bsize)) goto err; /* retrieve bytes for pub2 for later */ if (!TEST_ptr(Q = EC_KEY_get0_public_key(eckey2)) || !TEST_int_eq(EC_POINT_point2oct(altgroup, Q, POINT_CONVERSION_UNCOMPRESSED, NULL, 0, ctx), bsize) || !TEST_ptr(pub2 = OPENSSL_malloc(bsize)) || !TEST_int_eq(EC_POINT_point2oct(altgroup, Q, POINT_CONVERSION_UNCOMPRESSED, pub2, bsize, ctx), bsize)) goto err; /* create two `EVP_PKEY`s from the `EC_KEY`s */ if (!TEST_ptr(pkey1 = EVP_PKEY_new()) || !TEST_int_eq(EVP_PKEY_assign_EC_KEY(pkey1, eckey1), 1)) goto err; eckey1 = NULL; /* ownership passed to pkey1 */ if (!TEST_ptr(pkey2 = EVP_PKEY_new()) || !TEST_int_eq(EVP_PKEY_assign_EC_KEY(pkey2, eckey2), 1)) goto err; eckey2 = NULL; /* ownership passed to pkey2 */ /* Compute keyexchange in both directions */ if (!TEST_ptr(pctx1 = EVP_PKEY_CTX_new(pkey1, NULL)) || !TEST_int_eq(EVP_PKEY_derive_init(pctx1), 1) || !TEST_int_eq(EVP_PKEY_derive_set_peer(pctx1, pkey2), 1) || !TEST_int_eq(EVP_PKEY_derive(pctx1, NULL, &sslen), 1) || !TEST_int_gt(bsize, sslen) || !TEST_int_eq(EVP_PKEY_derive(pctx1, buf1, &sslen), 1)) goto err; if (!TEST_ptr(pctx2 = EVP_PKEY_CTX_new(pkey2, NULL)) || !TEST_int_eq(EVP_PKEY_derive_init(pctx2), 1) || !TEST_int_eq(EVP_PKEY_derive_set_peer(pctx2, pkey1), 1) || !TEST_int_eq(EVP_PKEY_derive(pctx2, NULL, &t), 1) || !TEST_int_gt(bsize, t) || !TEST_int_le(sslen, t) || !TEST_int_eq(EVP_PKEY_derive(pctx2, buf2, &t), 1)) goto err; /* Both sides should expect the same shared secret */ if (!TEST_mem_eq(buf1, sslen, buf2, t)) goto err; /* Build parameters for provider-native keys */ if (!TEST_ptr(param_bld = OSSL_PARAM_BLD_new()) || !TEST_true(OSSL_PARAM_BLD_push_utf8_string(param_bld, OSSL_PKEY_PARAM_GROUP_NAME, curve_name, 0)) || !TEST_true(OSSL_PARAM_BLD_push_octet_string(param_bld, OSSL_PKEY_PARAM_PUB_KEY, pub1, bsize)) || !TEST_true(OSSL_PARAM_BLD_push_BN(param_bld, OSSL_PKEY_PARAM_PRIV_KEY, priv1)) || !TEST_ptr(params1 = OSSL_PARAM_BLD_to_param(param_bld))) goto err; OSSL_PARAM_BLD_free(param_bld); if (!TEST_ptr(param_bld = OSSL_PARAM_BLD_new()) || !TEST_true(OSSL_PARAM_BLD_push_utf8_string(param_bld, OSSL_PKEY_PARAM_GROUP_NAME, curve_name, 0)) || !TEST_true(OSSL_PARAM_BLD_push_octet_string(param_bld, OSSL_PKEY_PARAM_PUB_KEY, pub2, bsize)) || !TEST_ptr(params2 = OSSL_PARAM_BLD_to_param(param_bld))) goto err; /* create two new provider-native `EVP_PKEY`s */ EVP_PKEY_CTX_free(pctx2); if (!TEST_ptr(pctx2 = EVP_PKEY_CTX_new_from_name(NULL, "EC", NULL)) || !TEST_int_eq(EVP_PKEY_fromdata_init(pctx2), 1) || !TEST_int_eq(EVP_PKEY_fromdata(pctx2, &pkey1, EVP_PKEY_KEYPAIR, params1), 1) || !TEST_int_eq(EVP_PKEY_fromdata(pctx2, &pkey2, EVP_PKEY_PUBLIC_KEY, params2), 1)) goto err; /* compute keyexchange once more using the provider keys */ EVP_PKEY_CTX_free(pctx1); if (!TEST_ptr(pctx1 = EVP_PKEY_CTX_new(pkey1, NULL)) || !TEST_int_eq(EVP_PKEY_derive_init(pctx1), 1) || !TEST_int_eq(EVP_PKEY_derive_set_peer(pctx1, pkey2), 1) || !TEST_int_eq(EVP_PKEY_derive(pctx1, NULL, &t), 1) || !TEST_int_gt(bsize, t) || !TEST_int_le(sslen, t) || !TEST_int_eq(EVP_PKEY_derive(pctx1, buf1, &t), 1) /* compare with previous result */ || !TEST_mem_eq(buf1, t, buf2, sslen)) goto err; ret = 1; err: BN_CTX_end(ctx); BN_CTX_free(ctx); OSSL_PARAM_BLD_free(param_bld); OSSL_PARAM_free(params1); OSSL_PARAM_free(params2); EC_POINT_free(Q1); EC_POINT_free(Q2); EC_POINT_free(G2); EC_GROUP_free(group); EC_GROUP_free(altgroup); OPENSSL_free(buf1); OPENSSL_free(buf2); OPENSSL_free(pub1); OPENSSL_free(pub2); EC_KEY_free(eckey1); EC_KEY_free(eckey2); EVP_PKEY_free(pkey1); EVP_PKEY_free(pkey2); EVP_PKEY_CTX_free(pctx1); EVP_PKEY_CTX_free(pctx2); return ret; } static int ec_d2i_publickey_test(void) { unsigned char buf[1000]; unsigned char *pubkey_enc = buf; const unsigned char *pk_enc = pubkey_enc; EVP_PKEY *gen_key = NULL, *decoded_key = NULL; EVP_PKEY_CTX *pctx = NULL; int pklen, ret = 0; OSSL_PARAM params[2]; if (!TEST_ptr(gen_key = EVP_EC_gen("P-256"))) goto err; if (!TEST_int_gt(pklen = i2d_PublicKey(gen_key, &pubkey_enc), 0)) goto err; params[0] = OSSL_PARAM_construct_utf8_string(OSSL_PKEY_PARAM_GROUP_NAME, "P-256", 0); params[1] = OSSL_PARAM_construct_end(); if (!TEST_ptr(pctx = EVP_PKEY_CTX_new_from_name(NULL, "EC", NULL)) || !TEST_true(EVP_PKEY_fromdata_init(pctx)) || !TEST_true(EVP_PKEY_fromdata(pctx, &decoded_key, OSSL_KEYMGMT_SELECT_DOMAIN_PARAMETERS, params)) || !TEST_ptr(decoded_key) || !TEST_ptr(decoded_key = d2i_PublicKey(EVP_PKEY_EC, &decoded_key, &pk_enc, pklen))) goto err; if (!TEST_true(EVP_PKEY_eq(gen_key, decoded_key))) goto err; ret = 1; err: EVP_PKEY_CTX_free(pctx); EVP_PKEY_free(gen_key); EVP_PKEY_free(decoded_key); return ret; } int setup_tests(void) { crv_len = EC_get_builtin_curves(NULL, 0); if (!TEST_ptr(curves = OPENSSL_malloc(sizeof(*curves) * crv_len)) || !TEST_true(EC_get_builtin_curves(curves, crv_len))) return 0; ADD_TEST(parameter_test); ADD_TEST(ossl_parameter_test); ADD_TEST(cofactor_range_test); ADD_ALL_TESTS(cardinality_test, crv_len); ADD_TEST(prime_field_tests); #ifndef OPENSSL_NO_EC2M ADD_TEST(hybrid_point_encoding_test); ADD_TEST(char2_field_tests); ADD_ALL_TESTS(char2_curve_test, OSSL_NELEM(char2_curve_tests)); #endif ADD_ALL_TESTS(nistp_single_test, OSSL_NELEM(nistp_tests_params)); ADD_ALL_TESTS(internal_curve_test, crv_len); ADD_ALL_TESTS(internal_curve_test_method, crv_len); ADD_TEST(group_field_test); ADD_ALL_TESTS(check_named_curve_test, crv_len); ADD_ALL_TESTS(check_named_curve_lookup_test, crv_len); ADD_ALL_TESTS(check_ec_key_field_public_range_test, crv_len); ADD_ALL_TESTS(check_named_curve_from_ecparameters, crv_len); ADD_ALL_TESTS(ec_point_hex2point_test, crv_len); ADD_ALL_TESTS(custom_generator_test, crv_len); ADD_ALL_TESTS(custom_params_test, crv_len); ADD_TEST(ec_d2i_publickey_test); return 1; } void cleanup_tests(void) { OPENSSL_free(curves); }
./openssl/test/cmp_status_test.c
/* * Copyright 2007-2021 The OpenSSL Project Authors. All Rights Reserved. * Copyright Nokia 2007-2019 * Copyright Siemens AG 2015-2019 * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include "helpers/cmp_testlib.h" typedef struct test_fixture { const char *test_case_name; int pkistatus; const char *str; /* Not freed by tear_down */ const char *text; /* Not freed by tear_down */ int pkifailure; } CMP_STATUS_TEST_FIXTURE; static CMP_STATUS_TEST_FIXTURE *set_up(const char *const test_case_name) { CMP_STATUS_TEST_FIXTURE *fixture; if (!TEST_ptr(fixture = OPENSSL_zalloc(sizeof(*fixture)))) return NULL; fixture->test_case_name = test_case_name; return fixture; } static void tear_down(CMP_STATUS_TEST_FIXTURE *fixture) { OPENSSL_free(fixture); } /* * Tests PKIStatusInfo creation and get-functions */ static int execute_PKISI_test(CMP_STATUS_TEST_FIXTURE *fixture) { OSSL_CMP_PKISI *si = NULL; int status; ASN1_UTF8STRING *statusString = NULL; int res = 0, i; if (!TEST_ptr(si = OSSL_CMP_STATUSINFO_new(fixture->pkistatus, fixture->pkifailure, fixture->text))) goto end; status = ossl_cmp_pkisi_get_status(si); if (!TEST_int_eq(fixture->pkistatus, status) || !TEST_str_eq(fixture->str, ossl_cmp_PKIStatus_to_string(status))) goto end; if (!TEST_ptr(statusString = sk_ASN1_UTF8STRING_value(ossl_cmp_pkisi_get0_statusString(si), 0)) || !TEST_mem_eq(fixture->text, strlen(fixture->text), (char *)statusString->data, statusString->length)) goto end; if (!TEST_int_eq(fixture->pkifailure, ossl_cmp_pkisi_get_pkifailureinfo(si))) goto end; for (i = 0; i <= OSSL_CMP_PKIFAILUREINFO_MAX; i++) if (!TEST_int_eq((fixture->pkifailure >> i) & 1, ossl_cmp_pkisi_check_pkifailureinfo(si, i))) goto end; res = 1; end: OSSL_CMP_PKISI_free(si); return res; } static int test_PKISI(void) { SETUP_TEST_FIXTURE(CMP_STATUS_TEST_FIXTURE, set_up); fixture->pkistatus = OSSL_CMP_PKISTATUS_revocationNotification; fixture->str = "PKIStatus: revocation notification - a revocation of the cert has occurred"; fixture->text = "this is an additional text describing the failure"; fixture->pkifailure = OSSL_CMP_CTX_FAILINFO_unsupportedVersion | OSSL_CMP_CTX_FAILINFO_badDataFormat; EXECUTE_TEST(execute_PKISI_test, tear_down); return result; } void cleanup_tests(void) { return; } int setup_tests(void) { /*- * this tests all of: * OSSL_CMP_STATUSINFO_new() * ossl_cmp_pkisi_get_status() * ossl_cmp_PKIStatus_to_string() * ossl_cmp_pkisi_get0_statusString() * ossl_cmp_pkisi_get_pkifailureinfo() * ossl_cmp_pkisi_check_pkifailureinfo() */ ADD_TEST(test_PKISI); return 1; }
./openssl/test/v3ext.c
/* * Copyright 2016-2020 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <stdio.h> #include <string.h> #include <openssl/x509.h> #include <openssl/x509v3.h> #include <openssl/pem.h> #include <openssl/err.h> #include "internal/nelem.h" #include "testutil.h" static const char *infile; static int test_pathlen(void) { X509 *x = NULL; BIO *b = NULL; long pathlen; int ret = 0; if (!TEST_ptr(b = BIO_new_file(infile, "r")) || !TEST_ptr(x = PEM_read_bio_X509(b, NULL, NULL, NULL)) || !TEST_int_eq(pathlen = X509_get_pathlen(x), 6)) goto end; ret = 1; end: BIO_free(b); X509_free(x); return ret; } #ifndef OPENSSL_NO_RFC3779 static int test_asid(void) { ASN1_INTEGER *val1 = NULL, *val2 = NULL; ASIdentifiers *asid1 = ASIdentifiers_new(), *asid2 = ASIdentifiers_new(), *asid3 = ASIdentifiers_new(), *asid4 = ASIdentifiers_new(); int testresult = 0; if (!TEST_ptr(asid1) || !TEST_ptr(asid2) || !TEST_ptr(asid3)) goto err; if (!TEST_ptr(val1 = ASN1_INTEGER_new()) || !TEST_true(ASN1_INTEGER_set_int64(val1, 64496))) goto err; if (!TEST_true(X509v3_asid_add_id_or_range(asid1, V3_ASID_ASNUM, val1, NULL))) goto err; val1 = NULL; if (!TEST_ptr(val2 = ASN1_INTEGER_new()) || !TEST_true(ASN1_INTEGER_set_int64(val2, 64497))) goto err; if (!TEST_true(X509v3_asid_add_id_or_range(asid2, V3_ASID_ASNUM, val2, NULL))) goto err; val2 = NULL; if (!TEST_ptr(val1 = ASN1_INTEGER_new()) || !TEST_true(ASN1_INTEGER_set_int64(val1, 64496)) || !TEST_ptr(val2 = ASN1_INTEGER_new()) || !TEST_true(ASN1_INTEGER_set_int64(val2, 64497))) goto err; /* * Just tests V3_ASID_ASNUM for now. Could be extended at some point to also * test V3_ASID_RDI if we think it is worth it. */ if (!TEST_true(X509v3_asid_add_id_or_range(asid3, V3_ASID_ASNUM, val1, val2))) goto err; val1 = val2 = NULL; /* Actual subsets */ if (!TEST_true(X509v3_asid_subset(NULL, NULL)) || !TEST_true(X509v3_asid_subset(NULL, asid1)) || !TEST_true(X509v3_asid_subset(asid1, asid1)) || !TEST_true(X509v3_asid_subset(asid2, asid2)) || !TEST_true(X509v3_asid_subset(asid1, asid3)) || !TEST_true(X509v3_asid_subset(asid2, asid3)) || !TEST_true(X509v3_asid_subset(asid3, asid3)) || !TEST_true(X509v3_asid_subset(asid4, asid1)) || !TEST_true(X509v3_asid_subset(asid4, asid2)) || !TEST_true(X509v3_asid_subset(asid4, asid3))) goto err; /* Not subsets */ if (!TEST_false(X509v3_asid_subset(asid1, NULL)) || !TEST_false(X509v3_asid_subset(asid1, asid2)) || !TEST_false(X509v3_asid_subset(asid2, asid1)) || !TEST_false(X509v3_asid_subset(asid3, asid1)) || !TEST_false(X509v3_asid_subset(asid3, asid2)) || !TEST_false(X509v3_asid_subset(asid1, asid4)) || !TEST_false(X509v3_asid_subset(asid2, asid4)) || !TEST_false(X509v3_asid_subset(asid3, asid4))) goto err; testresult = 1; err: ASN1_INTEGER_free(val1); ASN1_INTEGER_free(val2); ASIdentifiers_free(asid1); ASIdentifiers_free(asid2); ASIdentifiers_free(asid3); ASIdentifiers_free(asid4); return testresult; } static struct ip_ranges_st { const unsigned int afi; const char *ip1; const char *ip2; int rorp; } ranges[] = { { IANA_AFI_IPV4, "192.168.0.0", "192.168.0.1", IPAddressOrRange_addressPrefix}, { IANA_AFI_IPV4, "192.168.0.0", "192.168.0.2", IPAddressOrRange_addressRange}, { IANA_AFI_IPV4, "192.168.0.0", "192.168.0.3", IPAddressOrRange_addressPrefix}, { IANA_AFI_IPV4, "192.168.0.0", "192.168.0.254", IPAddressOrRange_addressRange}, { IANA_AFI_IPV4, "192.168.0.0", "192.168.0.255", IPAddressOrRange_addressPrefix}, { IANA_AFI_IPV4, "192.168.0.1", "192.168.0.255", IPAddressOrRange_addressRange}, { IANA_AFI_IPV4, "192.168.0.1", "192.168.0.1", IPAddressOrRange_addressPrefix}, { IANA_AFI_IPV4, "192.168.0.0", "192.168.255.255", IPAddressOrRange_addressPrefix}, { IANA_AFI_IPV4, "192.168.1.0", "192.168.255.255", IPAddressOrRange_addressRange}, { IANA_AFI_IPV6, "2001:0db8::0", "2001:0db8::1", IPAddressOrRange_addressPrefix}, { IANA_AFI_IPV6, "2001:0db8::0", "2001:0db8::2", IPAddressOrRange_addressRange}, { IANA_AFI_IPV6, "2001:0db8::0", "2001:0db8::3", IPAddressOrRange_addressPrefix}, { IANA_AFI_IPV6, "2001:0db8::0", "2001:0db8::fffe", IPAddressOrRange_addressRange}, { IANA_AFI_IPV6, "2001:0db8::0", "2001:0db8::ffff", IPAddressOrRange_addressPrefix}, { IANA_AFI_IPV6, "2001:0db8::1", "2001:0db8::ffff", IPAddressOrRange_addressRange}, { IANA_AFI_IPV6, "2001:0db8::1", "2001:0db8::1", IPAddressOrRange_addressPrefix}, { IANA_AFI_IPV6, "2001:0db8::0:0", "2001:0db8::ffff:ffff", IPAddressOrRange_addressPrefix}, { IANA_AFI_IPV6, "2001:0db8::1:0", "2001:0db8::ffff:ffff", IPAddressOrRange_addressRange} }; static int check_addr(IPAddrBlocks *addr, int type) { IPAddressFamily *fam; IPAddressOrRange *aorr; if (!TEST_int_eq(sk_IPAddressFamily_num(addr), 1)) return 0; fam = sk_IPAddressFamily_value(addr, 0); if (!TEST_ptr(fam)) return 0; if (!TEST_int_eq(fam->ipAddressChoice->type, IPAddressChoice_addressesOrRanges)) return 0; if (!TEST_int_eq(sk_IPAddressOrRange_num(fam->ipAddressChoice->u.addressesOrRanges), 1)) return 0; aorr = sk_IPAddressOrRange_value(fam->ipAddressChoice->u.addressesOrRanges, 0); if (!TEST_ptr(aorr)) return 0; if (!TEST_int_eq(aorr->type, type)) return 0; return 1; } static int test_addr_ranges(void) { IPAddrBlocks *addr = NULL; ASN1_OCTET_STRING *ip1 = NULL, *ip2 = NULL; size_t i; int testresult = 0; for (i = 0; i < OSSL_NELEM(ranges); i++) { addr = sk_IPAddressFamily_new_null(); if (!TEST_ptr(addr)) goto end; /* * Has the side effect of installing the comparison function onto the * stack. */ if (!TEST_true(X509v3_addr_canonize(addr))) goto end; ip1 = a2i_IPADDRESS(ranges[i].ip1); if (!TEST_ptr(ip1)) goto end; if (!TEST_true(ip1->length == 4 || ip1->length == 16)) goto end; ip2 = a2i_IPADDRESS(ranges[i].ip2); if (!TEST_ptr(ip2)) goto end; if (!TEST_int_eq(ip2->length, ip1->length)) goto end; if (!TEST_true(memcmp(ip1->data, ip2->data, ip1->length) <= 0)) goto end; if (!TEST_true(X509v3_addr_add_range(addr, ranges[i].afi, NULL, ip1->data, ip2->data))) goto end; if (!TEST_true(X509v3_addr_is_canonical(addr))) goto end; if (!check_addr(addr, ranges[i].rorp)) goto end; sk_IPAddressFamily_pop_free(addr, IPAddressFamily_free); addr = NULL; ASN1_OCTET_STRING_free(ip1); ASN1_OCTET_STRING_free(ip2); ip1 = ip2 = NULL; } testresult = 1; end: sk_IPAddressFamily_pop_free(addr, IPAddressFamily_free); ASN1_OCTET_STRING_free(ip1); ASN1_OCTET_STRING_free(ip2); return testresult; } static int test_addr_fam_len(void) { int testresult = 0; IPAddrBlocks *addr = NULL; IPAddressFamily *f1 = NULL; ASN1_OCTET_STRING *ip1 = NULL, *ip2 = NULL; unsigned char key[6]; unsigned int keylen; unsigned afi = IANA_AFI_IPV4; /* Create the IPAddrBlocks with a good IPAddressFamily */ addr = sk_IPAddressFamily_new_null(); if (!TEST_ptr(addr)) goto end; ip1 = a2i_IPADDRESS(ranges[0].ip1); if (!TEST_ptr(ip1)) goto end; ip2 = a2i_IPADDRESS(ranges[0].ip2); if (!TEST_ptr(ip2)) goto end; if (!TEST_true(X509v3_addr_add_range(addr, ranges[0].afi, NULL, ip1->data, ip2->data))) goto end; if (!TEST_true(X509v3_addr_is_canonical(addr))) goto end; /* Create our malformed IPAddressFamily */ key[0] = (afi >> 8) & 0xFF; key[1] = afi & 0xFF; key[2] = 0xD; key[3] = 0xE; key[4] = 0xA; key[5] = 0xD; keylen = 6; if ((f1 = IPAddressFamily_new()) == NULL) goto end; if (f1->ipAddressChoice == NULL && (f1->ipAddressChoice = IPAddressChoice_new()) == NULL) goto end; if (f1->addressFamily == NULL && (f1->addressFamily = ASN1_OCTET_STRING_new()) == NULL) goto end; if (!ASN1_OCTET_STRING_set(f1->addressFamily, key, keylen)) goto end; if (!sk_IPAddressFamily_push(addr, f1)) goto end; /* Shouldn't be able to canonize this as the len is > 3*/ if (!TEST_false(X509v3_addr_canonize(addr))) goto end; /* Create a well formed IPAddressFamily */ f1 = sk_IPAddressFamily_pop(addr); IPAddressFamily_free(f1); key[0] = (afi >> 8) & 0xFF; key[1] = afi & 0xFF; key[2] = 0x1; keylen = 3; if ((f1 = IPAddressFamily_new()) == NULL) goto end; if (f1->ipAddressChoice == NULL && (f1->ipAddressChoice = IPAddressChoice_new()) == NULL) goto end; if (f1->addressFamily == NULL && (f1->addressFamily = ASN1_OCTET_STRING_new()) == NULL) goto end; if (!ASN1_OCTET_STRING_set(f1->addressFamily, key, keylen)) goto end; /* Mark this as inheritance so we skip some of the is_canonize checks */ f1->ipAddressChoice->type = IPAddressChoice_inherit; if (!sk_IPAddressFamily_push(addr, f1)) goto end; /* Should be able to canonize now */ if (!TEST_true(X509v3_addr_canonize(addr))) goto end; testresult = 1; end: sk_IPAddressFamily_pop_free(addr, IPAddressFamily_free); ASN1_OCTET_STRING_free(ip1); ASN1_OCTET_STRING_free(ip2); return testresult; } static struct extvalues_st { const char *value; int pass; } extvalues[] = { /* No prefix is ok */ { "sbgp-ipAddrBlock = IPv4:192.0.0.1\n", 1 }, { "sbgp-ipAddrBlock = IPv4:192.0.0.0/0\n", 1 }, { "sbgp-ipAddrBlock = IPv4:192.0.0.0/1\n", 1 }, { "sbgp-ipAddrBlock = IPv4:192.0.0.0/32\n", 1 }, /* Prefix is too long */ { "sbgp-ipAddrBlock = IPv4:192.0.0.0/33\n", 0 }, /* Unreasonably large prefix */ { "sbgp-ipAddrBlock = IPv4:192.0.0.0/12341234\n", 0 }, /* Invalid IP addresses */ { "sbgp-ipAddrBlock = IPv4:192.0.0\n", 0 }, { "sbgp-ipAddrBlock = IPv4:256.0.0.0\n", 0 }, { "sbgp-ipAddrBlock = IPv4:-1.0.0.0\n", 0 }, { "sbgp-ipAddrBlock = IPv4:192.0.0.0.0\n", 0 }, { "sbgp-ipAddrBlock = IPv3:192.0.0.0\n", 0 }, /* IPv6 */ /* No prefix is ok */ { "sbgp-ipAddrBlock = IPv6:2001:db8::\n", 1 }, { "sbgp-ipAddrBlock = IPv6:2001::db8\n", 1 }, { "sbgp-ipAddrBlock = IPv6:2001:0db8:0000:0000:0000:0000:0000:0000\n", 1 }, { "sbgp-ipAddrBlock = IPv6:2001:db8::/0\n", 1 }, { "sbgp-ipAddrBlock = IPv6:2001:db8::/1\n", 1 }, { "sbgp-ipAddrBlock = IPv6:2001:db8::/32\n", 1 }, { "sbgp-ipAddrBlock = IPv6:2001:0db8:0000:0000:0000:0000:0000:0000/32\n", 1 }, { "sbgp-ipAddrBlock = IPv6:2001:db8::/128\n", 1 }, /* Prefix is too long */ { "sbgp-ipAddrBlock = IPv6:2001:db8::/129\n", 0 }, /* Unreasonably large prefix */ { "sbgp-ipAddrBlock = IPv6:2001:db8::/12341234\n", 0 }, /* Invalid IP addresses */ /* Not enough blocks of numbers */ { "sbgp-ipAddrBlock = IPv6:2001:0db8:0000:0000:0000:0000:0000\n", 0 }, /* Too many blocks of numbers */ { "sbgp-ipAddrBlock = IPv6:2001:0db8:0000:0000:0000:0000:0000:0000:0000\n", 0 }, /* First value too large */ { "sbgp-ipAddrBlock = IPv6:1ffff:0db8:0000:0000:0000:0000:0000:0000\n", 0 }, /* First value with invalid characters */ { "sbgp-ipAddrBlock = IPv6:fffg:0db8:0000:0000:0000:0000:0000:0000\n", 0 }, /* First value is negative */ { "sbgp-ipAddrBlock = IPv6:-1:0db8:0000:0000:0000:0000:0000:0000\n", 0 } }; static int test_ext_syntax(void) { size_t i; int testresult = 1; for (i = 0; i < OSSL_NELEM(extvalues); i++) { X509V3_CTX ctx; BIO *extbio = BIO_new_mem_buf(extvalues[i].value, strlen(extvalues[i].value)); CONF *conf; long eline; if (!TEST_ptr(extbio)) return 0 ; conf = NCONF_new_ex(NULL, NULL); if (!TEST_ptr(conf)) { BIO_free(extbio); return 0; } if (!TEST_long_gt(NCONF_load_bio(conf, extbio, &eline), 0)) { testresult = 0; } else { X509V3_set_ctx_test(&ctx); X509V3_set_nconf(&ctx, conf); if (extvalues[i].pass) { if (!TEST_true(X509V3_EXT_add_nconf(conf, &ctx, "default", NULL))) { TEST_info("Value: %s", extvalues[i].value); testresult = 0; } } else { ERR_set_mark(); if (!TEST_false(X509V3_EXT_add_nconf(conf, &ctx, "default", NULL))) { testresult = 0; TEST_info("Value: %s", extvalues[i].value); ERR_clear_last_mark(); } else { ERR_pop_to_mark(); } } } BIO_free(extbio); NCONF_free(conf); } return testresult; } static int test_addr_subset(void) { int i; int ret = 0; IPAddrBlocks *addrEmpty = NULL; IPAddrBlocks *addr[3] = { NULL, NULL }; ASN1_OCTET_STRING *ip1[3] = { NULL, NULL }; ASN1_OCTET_STRING *ip2[3] = { NULL, NULL }; int sz = OSSL_NELEM(addr); for (i = 0; i < sz; ++i) { /* Create the IPAddrBlocks with a good IPAddressFamily */ if (!TEST_ptr(addr[i] = sk_IPAddressFamily_new_null()) || !TEST_ptr(ip1[i] = a2i_IPADDRESS(ranges[i].ip1)) || !TEST_ptr(ip2[i] = a2i_IPADDRESS(ranges[i].ip2)) || !TEST_true(X509v3_addr_add_range(addr[i], ranges[i].afi, NULL, ip1[i]->data, ip2[i]->data))) goto end; } ret = TEST_ptr(addrEmpty = sk_IPAddressFamily_new_null()) && TEST_true(X509v3_addr_subset(NULL, NULL)) && TEST_true(X509v3_addr_subset(NULL, addr[0])) && TEST_true(X509v3_addr_subset(addrEmpty, addr[0])) && TEST_true(X509v3_addr_subset(addr[0], addr[0])) && TEST_true(X509v3_addr_subset(addr[0], addr[1])) && TEST_true(X509v3_addr_subset(addr[0], addr[2])) && TEST_true(X509v3_addr_subset(addr[1], addr[2])) && TEST_false(X509v3_addr_subset(addr[0], NULL)) && TEST_false(X509v3_addr_subset(addr[1], addr[0])) && TEST_false(X509v3_addr_subset(addr[2], addr[1])) && TEST_false(X509v3_addr_subset(addr[0], addrEmpty)); end: sk_IPAddressFamily_pop_free(addrEmpty, IPAddressFamily_free); for (i = 0; i < sz; ++i) { sk_IPAddressFamily_pop_free(addr[i], IPAddressFamily_free); ASN1_OCTET_STRING_free(ip1[i]); ASN1_OCTET_STRING_free(ip2[i]); } return ret; } #endif /* OPENSSL_NO_RFC3779 */ OPT_TEST_DECLARE_USAGE("cert.pem\n") int setup_tests(void) { if (!test_skip_common_options()) { TEST_error("Error parsing test options\n"); return 0; } if (!TEST_ptr(infile = test_get_argument(0))) return 0; ADD_TEST(test_pathlen); #ifndef OPENSSL_NO_RFC3779 ADD_TEST(test_asid); ADD_TEST(test_addr_ranges); ADD_TEST(test_ext_syntax); ADD_TEST(test_addr_fam_len); ADD_TEST(test_addr_subset); #endif /* OPENSSL_NO_RFC3779 */ return 1; }
./openssl/test/evp_extra_test.c
/* * Copyright 2015-2023 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ /* We need to use some deprecated APIs */ #define OPENSSL_SUPPRESS_DEPRECATED #include <stdio.h> #include <stdlib.h> #include <string.h> #include <openssl/bio.h> #include <openssl/conf.h> #include <openssl/crypto.h> #include <openssl/err.h> #include <openssl/evp.h> #include <openssl/x509.h> #include <openssl/pem.h> #include <openssl/kdf.h> #include <openssl/provider.h> #include <openssl/core_names.h> #include <openssl/params.h> #include <openssl/param_build.h> #include <openssl/dsa.h> #include <openssl/dh.h> #include <openssl/aes.h> #include <openssl/decoder.h> #include <openssl/rsa.h> #include <openssl/engine.h> #include <openssl/proverr.h> #include "testutil.h" #include "internal/nelem.h" #include "internal/sizes.h" #include "crypto/evp.h" #include "fake_rsaprov.h" #ifdef STATIC_LEGACY OSSL_provider_init_fn ossl_legacy_provider_init; #endif static OSSL_LIB_CTX *testctx = NULL; static char *testpropq = NULL; static OSSL_PROVIDER *nullprov = NULL; static OSSL_PROVIDER *deflprov = NULL; static OSSL_PROVIDER *lgcyprov = NULL; /* * kExampleRSAKeyDER is an RSA private key in ASN.1, DER format. Of course, you * should never use this key anywhere but in an example. */ static const unsigned char kExampleRSAKeyDER[] = { 0x30, 0x82, 0x02, 0x5c, 0x02, 0x01, 0x00, 0x02, 0x81, 0x81, 0x00, 0xf8, 0xb8, 0x6c, 0x83, 0xb4, 0xbc, 0xd9, 0xa8, 0x57, 0xc0, 0xa5, 0xb4, 0x59, 0x76, 0x8c, 0x54, 0x1d, 0x79, 0xeb, 0x22, 0x52, 0x04, 0x7e, 0xd3, 0x37, 0xeb, 0x41, 0xfd, 0x83, 0xf9, 0xf0, 0xa6, 0x85, 0x15, 0x34, 0x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0x2d, 0x86, 0x9d, 0xa5, 0x20, 0x1b, 0xe5, 0xdf, }; /* * kExampleDSAKeyDER is a DSA private key in ASN.1, DER format. Of course, you * should never use this key anywhere but in an example. */ #ifndef OPENSSL_NO_DSA static const unsigned char kExampleDSAKeyDER[] = { 0x30, 0x82, 0x01, 0xba, 0x02, 0x01, 0x00, 0x02, 0x81, 0x81, 0x00, 0x9a, 0x05, 0x6d, 0x33, 0xcd, 0x5d, 0x78, 0xa1, 0xbb, 0xcb, 0x7d, 0x5b, 0x8d, 0xb4, 0xcc, 0xbf, 0x03, 0x99, 0x64, 0xde, 0x38, 0x78, 0x06, 0x15, 0x2f, 0x86, 0x26, 0x77, 0xf3, 0xb1, 0x85, 0x00, 0xed, 0xfc, 0x28, 0x3a, 0x42, 0x4d, 0xab, 0xab, 0xdf, 0xbc, 0x9c, 0x16, 0xd0, 0x22, 0x50, 0xd1, 0x38, 0xdd, 0x3f, 0x64, 0x05, 0x9e, 0x68, 0x7a, 0x1e, 0xf1, 0x56, 0xbf, 0x1e, 0x2c, 0xc5, 0x97, 0x2a, 0xfe, 0x7a, 0x22, 0xdc, 0x6c, 0x68, 0xb8, 0x2e, 0x06, 0xdb, 0x41, 0xca, 0x98, 0xd8, 0x54, 0xc7, 0x64, 0x48, 0x24, 0x04, 0x20, 0xbc, 0x59, 0xe3, 0x6b, 0xea, 0x7e, 0xfc, 0x7e, 0xc5, 0x4e, 0xd4, 0xd8, 0x3a, 0xed, 0xcd, 0x5d, 0x99, 0xb8, 0x5c, 0xa2, 0x8b, 0xbb, 0x0b, 0xac, 0xe6, 0x8e, 0x25, 0x56, 0x22, 0x3a, 0x2d, 0x3a, 0x56, 0x41, 0x14, 0x1f, 0x1c, 0x8f, 0x53, 0x46, 0x13, 0x85, 0x02, 0x15, 0x00, 0x98, 0x7e, 0x92, 0x81, 0x88, 0xc7, 0x3f, 0x70, 0x49, 0x54, 0xf6, 0x76, 0xb4, 0xa3, 0x9e, 0x1d, 0x45, 0x98, 0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92, 0x6c, 0x07, 0xb4, 0x1e, 0x64, 0x62, 0x87, 0xc6, 0xa4, 0xfd, 0x0d, 0x5f, 0xe5, 0xf9, 0x1b, 0x4f, 0x85, 0x5f, 0xae, 0xf3, 0x11, 0xe5, 0x18, 0xd4, 0x4d, 0x79, 0x9f, 0xc4, 0x79, 0x26, 0x04, 0x27, 0xf0, 0x0b, 0xee, 0x2b, 0x86, 0x9f, 0x86, 0x61, 0xe6, 0x51, 0xce, 0x04, 0x9b, 0x5d, 0x6b, 0x34, 0x43, 0x8c, 0x85, 0x3c, 0xf1, 0x51, 0x9b, 0x08, 0x23, 0x1b, 0xf5, 0x7e, 0x33, 0x12, 0xea, 0xab, 0x1f, 0xb7, 0x2d, 0xe2, 0x5f, 0xe6, 0x97, 0x99, 0xb5, 0x45, 0x16, 0x5b, 0xc3, 0x41, 0x02, 0x14, 0x61, 0xbf, 0x51, 0x60, 0xcf, 0xc8, 0xf1, 0x8c, 0x82, 0x97, 0xf2, 0xf4, 0x19, 0xba, 0x2b, 0xf3, 0x16, 0xbe, 0x40, 0x48 }; #endif /* * kExampleBadRSAKeyDER is an RSA private key in ASN.1, DER format. The private * components are not correct. */ static const unsigned char kExampleBadRSAKeyDER[] = { 0x30, 0x82, 0x04, 0x27, 0x02, 0x01, 0x00, 0x02, 0x82, 0x01, 0x01, 0x00, 0xa6, 0x1a, 0x1e, 0x6e, 0x7b, 0xee, 0xc6, 0x89, 0x66, 0xe7, 0x93, 0xef, 0x54, 0x12, 0x68, 0xea, 0xbf, 0x86, 0x2f, 0xdd, 0xd2, 0x79, 0xb8, 0xa9, 0x6e, 0x03, 0xc2, 0xa3, 0xb9, 0xa3, 0xe1, 0x4b, 0x2a, 0xb3, 0xf8, 0xb4, 0xcd, 0xea, 0xbe, 0x24, 0xa6, 0x57, 0x5b, 0x83, 0x1f, 0x0f, 0xf2, 0xd3, 0xb7, 0xac, 0x7e, 0xd6, 0x8e, 0x6e, 0x1e, 0xbf, 0xb8, 0x73, 0x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81, 0x07, 0xe4, 0x75, 0x39, 0xe9, 0x53, 0xca, 0xbb, 0x5c, 0xaa, 0x93, 0x07, 0x0e, 0xa8, 0x2f, 0xba, 0x98, 0x49, 0x30, 0xa7, 0xcc, 0x1a, 0x3c, 0x68, 0x0c, 0xe1, 0xa4, 0xb1, 0x05, 0xe6, 0xe0, 0x25, 0x78, 0x58, 0x14, 0x37, 0xf5, 0x1f, 0xe3, 0x22, 0xef, 0xa8, 0x0e, 0x22, 0xa0, 0x94, 0x3a, 0xf6, 0xc9, 0x13, 0xe6, 0x06, 0xbf, 0x7f, 0x99, 0xc6, 0xcc, 0xd8, 0xc6, 0xbe, 0xd9, 0x2e, 0x24, 0xc7, 0x69, 0x8c, 0x95, 0xba, 0xf6, 0x04, 0xb3, 0x0a, 0xf4, 0xcb, 0xf0, 0xce, }; /* * kExampleBad2RSAKeyDER is an RSA private key in ASN.1, DER format. All * values are 0. */ static const unsigned char kExampleBad2RSAKeyDER[] = { 0x30, 0x1b, 0x02, 0x01, 0x00, 0x02, 0x01, 0x00, 0x02, 0x01, 0x00, 0x02, 0x01, 0x00, 0x02, 0x01, 0x00, 0x02, 0x01, 0x00, 0x02, 0x01, 0x00, 0x02, 0x01, 0x00, 0x02, 0x01, 0x00 }; static const unsigned char kMsg[] = { 1, 2, 3, 4 }; static const unsigned char kSignature[] = { 0xa5, 0xf0, 0x8a, 0x47, 0x5d, 0x3c, 0xb3, 0xcc, 0xa9, 0x79, 0xaf, 0x4d, 0x8c, 0xae, 0x4c, 0x14, 0xef, 0xc2, 0x0b, 0x34, 0x36, 0xde, 0xf4, 0x3e, 0x3d, 0xbb, 0x4a, 0x60, 0x5c, 0xc8, 0x91, 0x28, 0xda, 0xfb, 0x7e, 0x04, 0x96, 0x7e, 0x63, 0x13, 0x90, 0xce, 0xb9, 0xb4, 0x62, 0x7a, 0xfd, 0x09, 0x3d, 0xc7, 0x67, 0x78, 0x54, 0x04, 0xeb, 0x52, 0x62, 0x6e, 0x24, 0x67, 0xb4, 0x40, 0xfc, 0x57, 0x62, 0xc6, 0xf1, 0x67, 0xc1, 0x97, 0x8f, 0x6a, 0xa8, 0xae, 0x44, 0x46, 0x5e, 0xab, 0x67, 0x17, 0x53, 0x19, 0x3a, 0xda, 0x5a, 0xc8, 0x16, 0x3e, 0x86, 0xd5, 0xc5, 0x71, 0x2f, 0xfc, 0x23, 0x48, 0xd9, 0x0b, 0x13, 0xdd, 0x7b, 0x5a, 0x25, 0x79, 0xef, 0xa5, 0x7b, 0x04, 0xed, 0x44, 0xf6, 0x18, 0x55, 0xe4, 0x0a, 0xe9, 0x57, 0x79, 0x5d, 0xd7, 0x55, 0xa7, 0xab, 0x45, 0x02, 0x97, 0x60, 0x42, }; /* * kExampleRSAKeyPKCS8 is kExampleRSAKeyDER encoded in a PKCS #8 * PrivateKeyInfo. */ static const unsigned char kExampleRSAKeyPKCS8[] = { 0x30, 0x82, 0x02, 0x76, 0x02, 0x01, 0x00, 0x30, 0x0d, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x01, 0x05, 0x00, 0x04, 0x82, 0x02, 0x60, 0x30, 0x82, 0x02, 0x5c, 0x02, 0x01, 0x00, 0x02, 0x81, 0x81, 0x00, 0xf8, 0xb8, 0x6c, 0x83, 0xb4, 0xbc, 0xd9, 0xa8, 0x57, 0xc0, 0xa5, 0xb4, 0x59, 0x76, 0x8c, 0x54, 0x1d, 0x79, 0xeb, 0x22, 0x52, 0x04, 0x7e, 0xd3, 0x37, 0xeb, 0x41, 0xfd, 0x83, 0xf9, 0xf0, 0xa6, 0x85, 0x15, 0x34, 0x75, 0x71, 0x5a, 0x84, 0xa8, 0x3c, 0xd2, 0xef, 0x5a, 0x4e, 0xd3, 0xde, 0x97, 0x8a, 0xdd, 0xff, 0xbb, 0xcf, 0x0a, 0xaa, 0x86, 0x92, 0xbe, 0xb8, 0x50, 0xe4, 0xcd, 0x6f, 0x80, 0x33, 0x30, 0x76, 0x13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f, 0x7e, 0xb8, 0xeb, 0x81, 0xf4, 0x9d, 0xfe, 0x07, 0x2b, 0x0b, 0x63, 0x0b, 0x5a, 0x55, 0x90, 0x71, 0x7d, 0xf1, 0xdb, 0xd9, 0xb1, 0x41, 0x41, 0x68, 0x2f, 0x4e, 0x39, 0x02, 0x40, 0x5a, 0x34, 0x66, 0xd8, 0xf5, 0xe2, 0x7f, 0x18, 0xb5, 0x00, 0x6e, 0x26, 0x84, 0x27, 0x14, 0x93, 0xfb, 0xfc, 0xc6, 0x0f, 0x5e, 0x27, 0xe6, 0xe1, 0xe9, 0xc0, 0x8a, 0xe4, 0x34, 0xda, 0xe9, 0xa2, 0x4b, 0x73, 0xbc, 0x8c, 0xb9, 0xba, 0x13, 0x6c, 0x7a, 0x2b, 0x51, 0x84, 0xa3, 0x4a, 0xe0, 0x30, 0x10, 0x06, 0x7e, 0xed, 0x17, 0x5a, 0x14, 0x00, 0xc9, 0xef, 0x85, 0xea, 0x52, 0x2c, 0xbc, 0x65, 0x02, 0x40, 0x51, 0xe3, 0xf2, 0x83, 0x19, 0x9b, 0xc4, 0x1e, 0x2f, 0x50, 0x3d, 0xdf, 0x5a, 0xa2, 0x18, 0xca, 0x5f, 0x2e, 0x49, 0xaf, 0x6f, 0xcc, 0xfa, 0x65, 0x77, 0x94, 0xb5, 0xa1, 0x0a, 0xa9, 0xd1, 0x8a, 0x39, 0x37, 0xf4, 0x0b, 0xa0, 0xd7, 0x82, 0x27, 0x5e, 0xae, 0x17, 0x17, 0xa1, 0x1e, 0x54, 0x34, 0xbf, 0x6e, 0xc4, 0x8e, 0x99, 0x5d, 0x08, 0xf1, 0x2d, 0x86, 0x9d, 0xa5, 0x20, 0x1b, 0xe5, 0xdf, }; #ifndef OPENSSL_NO_EC /* * kExampleECKeyDER is a sample EC private key encoded as an ECPrivateKey * structure. */ static const unsigned char kExampleECKeyDER[] = { 0x30, 0x77, 0x02, 0x01, 0x01, 0x04, 0x20, 0x07, 0x0f, 0x08, 0x72, 0x7a, 0xd4, 0xa0, 0x4a, 0x9c, 0xdd, 0x59, 0xc9, 0x4d, 0x89, 0x68, 0x77, 0x08, 0xb5, 0x6f, 0xc9, 0x5d, 0x30, 0x77, 0x0e, 0xe8, 0xd1, 0xc9, 0xce, 0x0a, 0x8b, 0xb4, 0x6a, 0xa0, 0x0a, 0x06, 0x08, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x03, 0x01, 0x07, 0xa1, 0x44, 0x03, 0x42, 0x00, 0x04, 0xe6, 0x2b, 0x69, 0xe2, 0xbf, 0x65, 0x9f, 0x97, 0xbe, 0x2f, 0x1e, 0x0d, 0x94, 0x8a, 0x4c, 0xd5, 0x97, 0x6b, 0xb7, 0xa9, 0x1e, 0x0d, 0x46, 0xfb, 0xdd, 0xa9, 0xa9, 0x1e, 0x9d, 0xdc, 0xba, 0x5a, 0x01, 0xe7, 0xd6, 0x97, 0xa8, 0x0a, 0x18, 0xf9, 0xc3, 0xc4, 0xa3, 0x1e, 0x56, 0xe2, 0x7c, 0x83, 0x48, 0xdb, 0x16, 0x1a, 0x1c, 0xf5, 0x1d, 0x7e, 0xf1, 0x94, 0x2d, 0x4b, 0xcf, 0x72, 0x22, 0xc1, }; /* * kExampleBadECKeyDER is a sample EC private key encoded as an ECPrivateKey * structure. The private key is equal to the order and will fail to import */ static const unsigned char kExampleBadECKeyDER[] = { 0x30, 0x66, 0x02, 0x01, 0x00, 0x30, 0x13, 0x06, 0x07, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x02, 0x01, 0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x01, 0x07, 0x04, 0x4C, 0x30, 0x4A, 0x02, 0x01, 0x01, 0x04, 0x20, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xBC, 0xE6, 0xFA, 0xAD, 0xA7, 0x17, 0x9E, 0x84, 0xF3, 0xB9, 0xCA, 0xC2, 0xFC, 0x63, 0x25, 0x51, 0xA1, 0x23, 0x03, 0x21, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xBC, 0xE6, 0xFA, 0xAD, 0xA7, 0x17, 0x9E, 0x84, 0xF3, 0xB9, 0xCA, 0xC2, 0xFC, 0x63, 0x25, 0x51 }; /* prime256v1 */ static const unsigned char kExampleECPubKeyDER[] = { 0x30, 0x59, 0x30, 0x13, 0x06, 0x07, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x02, 0x01, 0x06, 0x08, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x03, 0x01, 0x07, 0x03, 0x42, 0x00, 0x04, 0xba, 0xeb, 0x83, 0xfb, 0x3b, 0xb2, 0xff, 0x30, 0x53, 0xdb, 0xce, 0x32, 0xf2, 0xac, 0xae, 0x44, 0x0d, 0x3d, 0x13, 0x53, 0xb8, 0xd1, 0x68, 0x55, 0xde, 0x44, 0x46, 0x05, 0xa6, 0xc9, 0xd2, 0x04, 0xb7, 0xe3, 0xa2, 0x96, 0xc8, 0xb2, 0x5e, 0x22, 0x03, 0xd7, 0x03, 0x7a, 0x8b, 0x13, 0x5c, 0x42, 0x49, 0xc2, 0xab, 0x86, 0xd6, 0xac, 0x6b, 0x93, 0x20, 0x56, 0x6a, 0xc6, 0xc8, 0xa5, 0x0b, 0xe5 }; /* * kExampleBadECPubKeyDER is a sample EC public key with a wrong OID * 1.2.840.10045.2.2 instead of 1.2.840.10045.2.1 - EC Public Key */ static const unsigned char kExampleBadECPubKeyDER[] = { 0x30, 0x59, 0x30, 0x13, 0x06, 0x07, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x02, 0x02, 0x06, 0x08, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x03, 0x01, 0x07, 0x03, 0x42, 0x00, 0x04, 0xba, 0xeb, 0x83, 0xfb, 0x3b, 0xb2, 0xff, 0x30, 0x53, 0xdb, 0xce, 0x32, 0xf2, 0xac, 0xae, 0x44, 0x0d, 0x3d, 0x13, 0x53, 0xb8, 0xd1, 0x68, 0x55, 0xde, 0x44, 0x46, 0x05, 0xa6, 0xc9, 0xd2, 0x04, 0xb7, 0xe3, 0xa2, 0x96, 0xc8, 0xb2, 0x5e, 0x22, 0x03, 0xd7, 0x03, 0x7a, 0x8b, 0x13, 0x5c, 0x42, 0x49, 0xc2, 0xab, 0x86, 0xd6, 0xac, 0x6b, 0x93, 0x20, 0x56, 0x6a, 0xc6, 0xc8, 0xa5, 0x0b, 0xe5 }; static const unsigned char pExampleECParamDER[] = { 0x06, 0x08, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x03, 0x01, 0x07 }; # ifndef OPENSSL_NO_ECX static const unsigned char kExampleED25519KeyDER[] = { 0x30, 0x2e, 0x02, 0x01, 0x00, 0x30, 0x05, 0x06, 0x03, 0x2b, 0x65, 0x70, 0x04, 0x22, 0x04, 0x20, 0xba, 0x7b, 0xba, 0x20, 0x1b, 0x02, 0x75, 0x3a, 0xe8, 0x88, 0xfe, 0x00, 0xcd, 0x8b, 0xc6, 0xf4, 0x5c, 0x47, 0x09, 0x46, 0x66, 0xe4, 0x72, 0x85, 0x25, 0x26, 0x5e, 0x12, 0x33, 0x48, 0xf6, 0x50 }; static const unsigned char kExampleED25519PubKeyDER[] = { 0x30, 0x2a, 0x30, 0x05, 0x06, 0x03, 0x2b, 0x65, 0x70, 0x03, 0x21, 0x00, 0xf5, 0xc5, 0xeb, 0x52, 0x3e, 0x7d, 0x07, 0x86, 0xb2, 0x55, 0x07, 0x45, 0xef, 0x5b, 0x7c, 0x20, 0xe8, 0x66, 0x28, 0x30, 0x3c, 0x8a, 0x82, 0x40, 0x97, 0xa3, 0x08, 0xdc, 0x65, 0x80, 0x39, 0x29 }; # ifndef OPENSSL_NO_DEPRECATED_3_0 static const unsigned char kExampleX25519KeyDER[] = { 0x30, 0x2e, 0x02, 0x01, 0x00, 0x30, 0x05, 0x06, 0x03, 0x2b, 0x65, 0x6e, 0x04, 0x22, 0x04, 0x20, 0xa0, 0x24, 0x3a, 0x31, 0x24, 0xc3, 0x3f, 0xf6, 0x7b, 0x96, 0x0b, 0xd4, 0x8f, 0xd1, 0xee, 0x67, 0xf2, 0x9b, 0x88, 0xac, 0x50, 0xce, 0x97, 0x36, 0xdd, 0xaf, 0x25, 0xf6, 0x10, 0x34, 0x96, 0x6e }; # endif # endif #endif /* kExampleDHKeyDER is a DH private key in ASN.1, DER format. */ #ifndef OPENSSL_NO_DEPRECATED_3_0 # ifndef OPENSSL_NO_DH static const unsigned char kExampleDHKeyDER[] = { 0x30, 0x82, 0x01, 0x21, 0x02, 0x01, 0x00, 0x30, 0x81, 0x95, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x03, 0x01, 0x30, 0x81, 0x87, 0x02, 0x81, 0x81, 0x00, 0xf7, 0x52, 0xc2, 0x68, 0xcc, 0x66, 0xc4, 0x8d, 0x03, 0x3f, 0xfa, 0x9c, 0x52, 0xd0, 0xd8, 0x33, 0xf2, 0xe1, 0xc9, 0x9e, 0xb7, 0xe7, 0x6e, 0x90, 0x97, 0xeb, 0x92, 0x91, 0x6a, 0x9a, 0x85, 0x63, 0x92, 0x79, 0xab, 0xb6, 0x3d, 0x23, 0x58, 0x5a, 0xe8, 0x45, 0x06, 0x81, 0x97, 0x77, 0xe1, 0xcc, 0x34, 0x4e, 0xae, 0x36, 0x80, 0xf2, 0xc4, 0x7f, 0x8a, 0x52, 0xb8, 0xdb, 0x58, 0xc8, 0x4b, 0x12, 0x4c, 0xf1, 0x4c, 0x53, 0xc1, 0x89, 0x39, 0x8d, 0xb6, 0x06, 0xd8, 0xea, 0x7f, 0x2d, 0x36, 0x53, 0x96, 0x29, 0xbe, 0xb6, 0x75, 0xfc, 0xe7, 0xf3, 0x36, 0xd6, 0xf4, 0x8f, 0x16, 0xa6, 0xc7, 0xec, 0x7b, 0xce, 0x42, 0x8d, 0x48, 0x2e, 0xb7, 0x74, 0x00, 0x11, 0x52, 0x61, 0xb4, 0x19, 0x35, 0xec, 0x5c, 0xe4, 0xbe, 0x34, 0xc6, 0x59, 0x64, 0x5e, 0x42, 0x61, 0x70, 0x54, 0xf4, 0xe9, 0x6b, 0x53, 0x02, 0x01, 0x02, 0x04, 0x81, 0x83, 0x02, 0x81, 0x80, 0x64, 0xc2, 0xe3, 0x09, 0x69, 0x37, 0x3c, 0xd2, 0x4a, 0xba, 0xc3, 0x78, 0x6a, 0x9b, 0x8a, 0x2a, 0xdb, 0xe7, 0xe6, 0xc0, 0xfa, 0x3a, 0xbe, 0x39, 0x67, 0xc0, 0xa9, 0x2a, 0xf0, 0x0a, 0xc1, 0x53, 0x1c, 0xdb, 0xfa, 0x1a, 0x26, 0x98, 0xb0, 0x8c, 0xc6, 0x06, 0x4a, 0xa2, 0x48, 0xd3, 0xa4, 0x3b, 0xbd, 0x05, 0x48, 0xea, 0x59, 0xdb, 0x18, 0xa4, 0xca, 0x66, 0xd9, 0x5d, 0xb8, 0x95, 0xd1, 0xeb, 0x97, 0x3d, 0x66, 0x97, 0x5c, 0x86, 0x8f, 0x7e, 0x90, 0xd3, 0x43, 0xd1, 0xa2, 0x0d, 0xcb, 0xe7, 0xeb, 0x90, 0xea, 0x09, 0x40, 0xb1, 0x6f, 0xf7, 0x4c, 0xf2, 0x41, 0x83, 0x1d, 0xd0, 0x76, 0xef, 0xaf, 0x55, 0x6f, 0x5d, 0xa9, 0xa3, 0x55, 0x81, 0x2a, 0xd1, 0x5d, 0x9d, 0x22, 0x77, 0x97, 0x83, 0xde, 0xad, 0xb6, 0x5d, 0x19, 0xc1, 0x53, 0xec, 0xfb, 0xaf, 0x06, 0x2e, 0x87, 0x2a, 0x0b, 0x7a }; # endif #endif static const unsigned char kCFBDefaultKey[] = { 0x2B, 0x7E, 0x15, 0x16, 0x28, 0xAE, 0xD2, 0xA6, 0xAB, 0xF7, 0x15, 0x88, 0x09, 0xCF, 0x4F, 0x3C }; static const unsigned char kGCMDefaultKey[32] = { 0 }; static const unsigned char kGCMResetKey[] = { 0xfe, 0xff, 0xe9, 0x92, 0x86, 0x65, 0x73, 0x1c, 0x6d, 0x6a, 0x8f, 0x94, 0x67, 0x30, 0x83, 0x08, 0xfe, 0xff, 0xe9, 0x92, 0x86, 0x65, 0x73, 0x1c, 0x6d, 0x6a, 0x8f, 0x94, 0x67, 0x30, 0x83, 0x08 }; static const unsigned char iCFBIV[] = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F }; static const unsigned char iGCMDefaultIV[12] = { 0 }; static const unsigned char iGCMResetIV1[] = { 0xca, 0xfe, 0xba, 0xbe, 0xfa, 0xce, 0xdb, 0xad }; static const unsigned char iGCMResetIV2[] = { 0xca, 0xfe, 0xba, 0xbe, 0xfa, 0xce, 0xdb, 0xad, 0xde, 0xca, 0xf8, 0x88 }; static const unsigned char cfbPlaintext[] = { 0x6B, 0xC1, 0xBE, 0xE2, 0x2E, 0x40, 0x9F, 0x96, 0xE9, 0x3D, 0x7E, 0x11, 0x73, 0x93, 0x17, 0x2A }; static const unsigned char cfbPlaintext_partial[] = { 0x6B, 0xC1, 0xBE, 0xE2, 0x2E, 0x40, 0x9F, 0x96, 0xE9, 0x3D, 0x7E, 0x11, 0x73, 0x93, 0x17, 0x2A, 0x6B, 0xC1, 0xBE, 0xE2, 0x2E, 0x40, 0x9F, 0x96, }; static const unsigned char gcmDefaultPlaintext[16] = { 0 }; static const unsigned char gcmResetPlaintext[] = { 0xd9, 0x31, 0x32, 0x25, 0xf8, 0x84, 0x06, 0xe5, 0xa5, 0x59, 0x09, 0xc5, 0xaf, 0xf5, 0x26, 0x9a, 0x86, 0xa7, 0xa9, 0x53, 0x15, 0x34, 0xf7, 0xda, 0x2e, 0x4c, 0x30, 0x3d, 0x8a, 0x31, 0x8a, 0x72, 0x1c, 0x3c, 0x0c, 0x95, 0x95, 0x68, 0x09, 0x53, 0x2f, 0xcf, 0x0e, 0x24, 0x49, 0xa6, 0xb5, 0x25, 0xb1, 0x6a, 0xed, 0xf5, 0xaa, 0x0d, 0xe6, 0x57, 0xba, 0x63, 0x7b, 0x39 }; static const unsigned char cfbCiphertext[] = { 0x3B, 0x3F, 0xD9, 0x2E, 0xB7, 0x2D, 0xAD, 0x20, 0x33, 0x34, 0x49, 0xF8, 0xE8, 0x3C, 0xFB, 0x4A }; static const unsigned char cfbCiphertext_partial[] = { 0x3B, 0x3F, 0xD9, 0x2E, 0xB7, 0x2D, 0xAD, 0x20, 0x33, 0x34, 0x49, 0xF8, 0xE8, 0x3C, 0xFB, 0x4A, 0x0D, 0x4A, 0x71, 0x82, 0x90, 0xF0, 0x9A, 0x35 }; static const unsigned char ofbCiphertext_partial[] = { 0x3B, 0x3F, 0xD9, 0x2E, 0xB7, 0x2D, 0xAD, 0x20, 0x33, 0x34, 0x49, 0xF8, 0xE8, 0x3C, 0xFB, 0x4A, 0xB2, 0x65, 0x64, 0x38, 0x26, 0xD2, 0xBC, 0x09 }; static const unsigned char gcmDefaultCiphertext[] = { 0xce, 0xa7, 0x40, 0x3d, 0x4d, 0x60, 0x6b, 0x6e, 0x07, 0x4e, 0xc5, 0xd3, 0xba, 0xf3, 0x9d, 0x18 }; static const unsigned char gcmResetCiphertext1[] = { 0xc3, 0x76, 0x2d, 0xf1, 0xca, 0x78, 0x7d, 0x32, 0xae, 0x47, 0xc1, 0x3b, 0xf1, 0x98, 0x44, 0xcb, 0xaf, 0x1a, 0xe1, 0x4d, 0x0b, 0x97, 0x6a, 0xfa, 0xc5, 0x2f, 0xf7, 0xd7, 0x9b, 0xba, 0x9d, 0xe0, 0xfe, 0xb5, 0x82, 0xd3, 0x39, 0x34, 0xa4, 0xf0, 0x95, 0x4c, 0xc2, 0x36, 0x3b, 0xc7, 0x3f, 0x78, 0x62, 0xac, 0x43, 0x0e, 0x64, 0xab, 0xe4, 0x99, 0xf4, 0x7c, 0x9b, 0x1f }; static const unsigned char gcmResetCiphertext2[] = { 0x52, 0x2d, 0xc1, 0xf0, 0x99, 0x56, 0x7d, 0x07, 0xf4, 0x7f, 0x37, 0xa3, 0x2a, 0x84, 0x42, 0x7d, 0x64, 0x3a, 0x8c, 0xdc, 0xbf, 0xe5, 0xc0, 0xc9, 0x75, 0x98, 0xa2, 0xbd, 0x25, 0x55, 0xd1, 0xaa, 0x8c, 0xb0, 0x8e, 0x48, 0x59, 0x0d, 0xbb, 0x3d, 0xa7, 0xb0, 0x8b, 0x10, 0x56, 0x82, 0x88, 0x38, 0xc5, 0xf6, 0x1e, 0x63, 0x93, 0xba, 0x7a, 0x0a, 0xbc, 0xc9, 0xf6, 0x62 }; static const unsigned char gcmAAD[] = { 0xfe, 0xed, 0xfa, 0xce, 0xde, 0xad, 0xbe, 0xef, 0xfe, 0xed, 0xfa, 0xce, 0xde, 0xad, 0xbe, 0xef, 0xab, 0xad, 0xda, 0xd2 }; static const unsigned char gcmDefaultTag[] = { 0xd0, 0xd1, 0xc8, 0xa7, 0x99, 0x99, 0x6b, 0xf0, 0x26, 0x5b, 0x98, 0xb5, 0xd4, 0x8a, 0xb9, 0x19 }; static const unsigned char gcmResetTag1[] = { 0x3a, 0x33, 0x7d, 0xbf, 0x46, 0xa7, 0x92, 0xc4, 0x5e, 0x45, 0x49, 0x13, 0xfe, 0x2e, 0xa8, 0xf2 }; static const unsigned char gcmResetTag2[] = { 0x76, 0xfc, 0x6e, 0xce, 0x0f, 0x4e, 0x17, 0x68, 0xcd, 0xdf, 0x88, 0x53, 0xbb, 0x2d, 0x55, 0x1b }; typedef struct APK_DATA_st { const unsigned char *kder; size_t size; const char *keytype; int evptype; int check; int pub_check; int param_check; int type; /* 0 for private, 1 for public, 2 for params */ } APK_DATA; static APK_DATA keydata[] = { {kExampleRSAKeyDER, sizeof(kExampleRSAKeyDER), "RSA", EVP_PKEY_RSA}, {kExampleRSAKeyPKCS8, sizeof(kExampleRSAKeyPKCS8), "RSA", EVP_PKEY_RSA}, #ifndef OPENSSL_NO_EC {kExampleECKeyDER, sizeof(kExampleECKeyDER), "EC", EVP_PKEY_EC} #endif }; static APK_DATA keycheckdata[] = { {kExampleRSAKeyDER, sizeof(kExampleRSAKeyDER), "RSA", EVP_PKEY_RSA, 1, 1, 1, 0}, {kExampleBadRSAKeyDER, sizeof(kExampleBadRSAKeyDER), "RSA", EVP_PKEY_RSA, 0, 1, 1, 0}, {kExampleBad2RSAKeyDER, sizeof(kExampleBad2RSAKeyDER), "RSA", EVP_PKEY_RSA, 0, 0, 1 /* Since there are no "params" in an RSA key this passes */, 0}, #ifndef OPENSSL_NO_EC {kExampleECKeyDER, sizeof(kExampleECKeyDER), "EC", EVP_PKEY_EC, 1, 1, 1, 0}, /* group is also associated in our pub key */ {kExampleECPubKeyDER, sizeof(kExampleECPubKeyDER), "EC", EVP_PKEY_EC, 0, 1, 1, 1}, {pExampleECParamDER, sizeof(pExampleECParamDER), "EC", EVP_PKEY_EC, 0, 0, 1, 2}, # ifndef OPENSSL_NO_ECX {kExampleED25519KeyDER, sizeof(kExampleED25519KeyDER), "ED25519", EVP_PKEY_ED25519, 1, 1, 1, 0}, {kExampleED25519PubKeyDER, sizeof(kExampleED25519PubKeyDER), "ED25519", EVP_PKEY_ED25519, 0, 1, 1, 1}, # endif #endif }; static EVP_PKEY *load_example_key(const char *keytype, const unsigned char *data, size_t data_len) { const unsigned char **pdata = &data; EVP_PKEY *pkey = NULL; OSSL_DECODER_CTX *dctx = OSSL_DECODER_CTX_new_for_pkey(&pkey, "DER", NULL, keytype, 0, testctx, testpropq); /* |pkey| will be NULL on error */ (void)OSSL_DECODER_from_data(dctx, pdata, &data_len); OSSL_DECODER_CTX_free(dctx); return pkey; } static EVP_PKEY *load_example_rsa_key(void) { return load_example_key("RSA", kExampleRSAKeyDER, sizeof(kExampleRSAKeyDER)); } #ifndef OPENSSL_NO_DSA static EVP_PKEY *load_example_dsa_key(void) { return load_example_key("DSA", kExampleDSAKeyDER, sizeof(kExampleDSAKeyDER)); } #endif #ifndef OPENSSL_NO_EC static EVP_PKEY *load_example_ec_key(void) { return load_example_key("EC", kExampleECKeyDER, sizeof(kExampleECKeyDER)); } #endif #ifndef OPENSSL_NO_DEPRECATED_3_0 # ifndef OPENSSL_NO_DH static EVP_PKEY *load_example_dh_key(void) { return load_example_key("DH", kExampleDHKeyDER, sizeof(kExampleDHKeyDER)); } # endif # ifndef OPENSSL_NO_ECX static EVP_PKEY *load_example_ed25519_key(void) { return load_example_key("ED25519", kExampleED25519KeyDER, sizeof(kExampleED25519KeyDER)); } static EVP_PKEY *load_example_x25519_key(void) { return load_example_key("X25519", kExampleX25519KeyDER, sizeof(kExampleX25519KeyDER)); } # endif #endif /* OPENSSL_NO_DEPRECATED_3_0 */ static EVP_PKEY *load_example_hmac_key(void) { EVP_PKEY *pkey = NULL; unsigned char key[] = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f }; pkey = EVP_PKEY_new_raw_private_key_ex(testctx, "HMAC", NULL, key, sizeof(key)); if (!TEST_ptr(pkey)) return NULL; return pkey; } static int test_EVP_set_default_properties(void) { OSSL_LIB_CTX *ctx; EVP_MD *md = NULL; int res = 0; if (!TEST_ptr(ctx = OSSL_LIB_CTX_new()) || !TEST_ptr(md = EVP_MD_fetch(ctx, "sha256", NULL))) goto err; EVP_MD_free(md); md = NULL; if (!TEST_true(EVP_set_default_properties(ctx, "provider=fizzbang")) || !TEST_ptr_null(md = EVP_MD_fetch(ctx, "sha256", NULL)) || !TEST_ptr(md = EVP_MD_fetch(ctx, "sha256", "-provider"))) goto err; EVP_MD_free(md); md = NULL; if (!TEST_true(EVP_set_default_properties(ctx, NULL)) || !TEST_ptr(md = EVP_MD_fetch(ctx, "sha256", NULL))) goto err; res = 1; err: EVP_MD_free(md); OSSL_LIB_CTX_free(ctx); return res; } #if !defined(OPENSSL_NO_DH) || !defined(OPENSSL_NO_DSA) || !defined(OPENSSL_NO_EC) static EVP_PKEY *make_key_fromdata(char *keytype, OSSL_PARAM *params) { EVP_PKEY_CTX *pctx = NULL; EVP_PKEY *tmp_pkey = NULL, *pkey = NULL; if (!TEST_ptr(pctx = EVP_PKEY_CTX_new_from_name(testctx, keytype, testpropq))) goto err; if (!TEST_int_gt(EVP_PKEY_fromdata_init(pctx), 0) || !TEST_int_gt(EVP_PKEY_fromdata(pctx, &tmp_pkey, EVP_PKEY_KEYPAIR, params), 0)) goto err; if (!TEST_ptr(tmp_pkey)) goto err; pkey = tmp_pkey; tmp_pkey = NULL; err: EVP_PKEY_free(tmp_pkey); EVP_PKEY_CTX_free(pctx); return pkey; } static int test_selection(EVP_PKEY *pkey, int selection) { int testresult = 0; int ret; BIO *bio = BIO_new(BIO_s_mem()); ret = PEM_write_bio_PUBKEY(bio, pkey); if ((selection & OSSL_KEYMGMT_SELECT_PUBLIC_KEY) != 0) { if (!TEST_true(ret)) goto err; } else { if (!TEST_false(ret)) goto err; } ret = PEM_write_bio_PrivateKey_ex(bio, pkey, NULL, NULL, 0, NULL, NULL, testctx, NULL); if ((selection & OSSL_KEYMGMT_SELECT_PRIVATE_KEY) != 0) { if (!TEST_true(ret)) goto err; } else { if (!TEST_false(ret)) goto err; } testresult = 1; err: BIO_free(bio); return testresult; } #endif /* !OPENSSL_NO_DH || !OPENSSL_NO_DSA || !OPENSSL_NO_EC */ /* * Test combinations of private, public, missing and private + public key * params to ensure they are all accepted */ #if !defined(OPENSSL_NO_DH) || !defined(OPENSSL_NO_DSA) static int test_EVP_PKEY_ffc_priv_pub(char *keytype) { OSSL_PARAM_BLD *bld = NULL; OSSL_PARAM *params = NULL; EVP_PKEY *just_params = NULL; EVP_PKEY *params_and_priv = NULL; EVP_PKEY *params_and_pub = NULL; EVP_PKEY *params_and_keypair = NULL; BIGNUM *p = NULL, *q = NULL, *g = NULL, *pub = NULL, *priv = NULL; int ret = 0; /* * Setup the parameters for our pkey object. For our purposes they don't * have to actually be *valid* parameters. We just need to set something. */ if (!TEST_ptr(p = BN_new()) || !TEST_ptr(q = BN_new()) || !TEST_ptr(g = BN_new()) || !TEST_ptr(pub = BN_new()) || !TEST_ptr(priv = BN_new())) goto err; /* Test !priv and !pub */ if (!TEST_ptr(bld = OSSL_PARAM_BLD_new()) || !TEST_true(OSSL_PARAM_BLD_push_BN(bld, OSSL_PKEY_PARAM_FFC_P, p)) || !TEST_true(OSSL_PARAM_BLD_push_BN(bld, OSSL_PKEY_PARAM_FFC_Q, q)) || !TEST_true(OSSL_PARAM_BLD_push_BN(bld, OSSL_PKEY_PARAM_FFC_G, g))) goto err; if (!TEST_ptr(params = OSSL_PARAM_BLD_to_param(bld)) || !TEST_ptr(just_params = make_key_fromdata(keytype, params))) goto err; OSSL_PARAM_free(params); OSSL_PARAM_BLD_free(bld); params = NULL; bld = NULL; if (!test_selection(just_params, OSSL_KEYMGMT_SELECT_ALL_PARAMETERS) || test_selection(just_params, OSSL_KEYMGMT_SELECT_KEYPAIR)) goto err; /* Test priv and !pub */ if (!TEST_ptr(bld = OSSL_PARAM_BLD_new()) || !TEST_true(OSSL_PARAM_BLD_push_BN(bld, OSSL_PKEY_PARAM_FFC_P, p)) || !TEST_true(OSSL_PARAM_BLD_push_BN(bld, OSSL_PKEY_PARAM_FFC_Q, q)) || !TEST_true(OSSL_PARAM_BLD_push_BN(bld, OSSL_PKEY_PARAM_FFC_G, g)) || !TEST_true(OSSL_PARAM_BLD_push_BN(bld, OSSL_PKEY_PARAM_PRIV_KEY, priv))) goto err; if (!TEST_ptr(params = OSSL_PARAM_BLD_to_param(bld)) || !TEST_ptr(params_and_priv = make_key_fromdata(keytype, params))) goto err; OSSL_PARAM_free(params); OSSL_PARAM_BLD_free(bld); params = NULL; bld = NULL; if (!test_selection(params_and_priv, OSSL_KEYMGMT_SELECT_PRIVATE_KEY) || test_selection(params_and_priv, OSSL_KEYMGMT_SELECT_PUBLIC_KEY)) goto err; /* Test !priv and pub */ if (!TEST_ptr(bld = OSSL_PARAM_BLD_new()) || !TEST_true(OSSL_PARAM_BLD_push_BN(bld, OSSL_PKEY_PARAM_FFC_P, p)) || !TEST_true(OSSL_PARAM_BLD_push_BN(bld, OSSL_PKEY_PARAM_FFC_Q, q)) || !TEST_true(OSSL_PARAM_BLD_push_BN(bld, OSSL_PKEY_PARAM_FFC_G, g)) || !TEST_true(OSSL_PARAM_BLD_push_BN(bld, OSSL_PKEY_PARAM_PUB_KEY, pub))) goto err; if (!TEST_ptr(params = OSSL_PARAM_BLD_to_param(bld)) || !TEST_ptr(params_and_pub = make_key_fromdata(keytype, params))) goto err; OSSL_PARAM_free(params); OSSL_PARAM_BLD_free(bld); params = NULL; bld = NULL; if (!test_selection(params_and_pub, OSSL_KEYMGMT_SELECT_PUBLIC_KEY) || test_selection(params_and_pub, OSSL_KEYMGMT_SELECT_PRIVATE_KEY)) goto err; /* Test priv and pub */ if (!TEST_ptr(bld = OSSL_PARAM_BLD_new()) || !TEST_true(OSSL_PARAM_BLD_push_BN(bld, OSSL_PKEY_PARAM_FFC_P, p)) || !TEST_true(OSSL_PARAM_BLD_push_BN(bld, OSSL_PKEY_PARAM_FFC_Q, q)) || !TEST_true(OSSL_PARAM_BLD_push_BN(bld, OSSL_PKEY_PARAM_FFC_G, g)) || !TEST_true(OSSL_PARAM_BLD_push_BN(bld, OSSL_PKEY_PARAM_PUB_KEY, pub)) || !TEST_true(OSSL_PARAM_BLD_push_BN(bld, OSSL_PKEY_PARAM_PRIV_KEY, priv))) goto err; if (!TEST_ptr(params = OSSL_PARAM_BLD_to_param(bld)) || !TEST_ptr(params_and_keypair = make_key_fromdata(keytype, params))) goto err; if (!test_selection(params_and_keypair, EVP_PKEY_KEYPAIR)) goto err; ret = 1; err: OSSL_PARAM_free(params); OSSL_PARAM_BLD_free(bld); EVP_PKEY_free(just_params); EVP_PKEY_free(params_and_priv); EVP_PKEY_free(params_and_pub); EVP_PKEY_free(params_and_keypair); BN_free(p); BN_free(q); BN_free(g); BN_free(pub); BN_free(priv); return ret; } #endif /* !OPENSSL_NO_DH || !OPENSSL_NO_DSA */ /* * Test combinations of private, public, missing and private + public key * params to ensure they are all accepted for EC keys */ #ifndef OPENSSL_NO_EC static unsigned char ec_priv[] = { 0xe9, 0x25, 0xf7, 0x66, 0x58, 0xa4, 0xdd, 0x99, 0x61, 0xe7, 0xe8, 0x23, 0x85, 0xc2, 0xe8, 0x33, 0x27, 0xc5, 0x5c, 0xeb, 0xdb, 0x43, 0x9f, 0xd5, 0xf2, 0x5a, 0x75, 0x55, 0xd0, 0x2e, 0x6d, 0x16 }; static unsigned char ec_pub[] = { 0x04, 0xad, 0x11, 0x90, 0x77, 0x4b, 0x46, 0xee, 0x72, 0x51, 0x15, 0x97, 0x4a, 0x6a, 0xa7, 0xaf, 0x59, 0xfa, 0x4b, 0xf2, 0x41, 0xc8, 0x3a, 0x81, 0x23, 0xb6, 0x90, 0x04, 0x6c, 0x67, 0x66, 0xd0, 0xdc, 0xf2, 0x15, 0x1d, 0x41, 0x61, 0xb7, 0x95, 0x85, 0x38, 0x5a, 0x84, 0x56, 0xe8, 0xb3, 0x0e, 0xf5, 0xc6, 0x5d, 0xa4, 0x54, 0x26, 0xb0, 0xf7, 0xa5, 0x4a, 0x33, 0xf1, 0x08, 0x09, 0xb8, 0xdb, 0x03 }; static int test_EC_priv_pub(void) { OSSL_PARAM_BLD *bld = NULL; OSSL_PARAM *params = NULL; EVP_PKEY *just_params = NULL; EVP_PKEY *params_and_priv = NULL; EVP_PKEY *params_and_pub = NULL; EVP_PKEY *params_and_keypair = NULL; BIGNUM *priv = NULL; int ret = 0; unsigned char *encoded = NULL; size_t len = 0; unsigned char buffer[128]; /* * Setup the parameters for our pkey object. For our purposes they don't * have to actually be *valid* parameters. We just need to set something. */ if (!TEST_ptr(priv = BN_bin2bn(ec_priv, sizeof(ec_priv), NULL))) goto err; /* Test !priv and !pub */ if (!TEST_ptr(bld = OSSL_PARAM_BLD_new()) || !TEST_true(OSSL_PARAM_BLD_push_utf8_string(bld, OSSL_PKEY_PARAM_GROUP_NAME, "P-256", 0))) goto err; if (!TEST_ptr(params = OSSL_PARAM_BLD_to_param(bld)) || !TEST_ptr(just_params = make_key_fromdata("EC", params))) goto err; OSSL_PARAM_free(params); OSSL_PARAM_BLD_free(bld); params = NULL; bld = NULL; if (!test_selection(just_params, OSSL_KEYMGMT_SELECT_ALL_PARAMETERS) || test_selection(just_params, OSSL_KEYMGMT_SELECT_KEYPAIR)) goto err; /* Test priv and !pub */ if (!TEST_ptr(bld = OSSL_PARAM_BLD_new()) || !TEST_true(OSSL_PARAM_BLD_push_utf8_string(bld, OSSL_PKEY_PARAM_GROUP_NAME, "P-256", 0)) || !TEST_true(OSSL_PARAM_BLD_push_BN(bld, OSSL_PKEY_PARAM_PRIV_KEY, priv))) goto err; if (!TEST_ptr(params = OSSL_PARAM_BLD_to_param(bld)) || !TEST_ptr(params_and_priv = make_key_fromdata("EC", params))) goto err; OSSL_PARAM_free(params); OSSL_PARAM_BLD_free(bld); params = NULL; bld = NULL; /* * We indicate only parameters here, in spite of having built a key that * has a private part, because the PEM_write_bio_PrivateKey_ex call is * expected to fail because it does not support exporting a private EC * key without a corresponding public key */ if (!test_selection(params_and_priv, OSSL_KEYMGMT_SELECT_ALL_PARAMETERS) || test_selection(params_and_priv, OSSL_KEYMGMT_SELECT_PUBLIC_KEY)) goto err; /* Test !priv and pub */ if (!TEST_ptr(bld = OSSL_PARAM_BLD_new()) || !TEST_true(OSSL_PARAM_BLD_push_utf8_string(bld, OSSL_PKEY_PARAM_GROUP_NAME, "P-256", 0)) || !TEST_true(OSSL_PARAM_BLD_push_octet_string(bld, OSSL_PKEY_PARAM_PUB_KEY, ec_pub, sizeof(ec_pub)))) goto err; if (!TEST_ptr(params = OSSL_PARAM_BLD_to_param(bld)) || !TEST_ptr(params_and_pub = make_key_fromdata("EC", params))) goto err; OSSL_PARAM_free(params); OSSL_PARAM_BLD_free(bld); params = NULL; bld = NULL; if (!test_selection(params_and_pub, OSSL_KEYMGMT_SELECT_PUBLIC_KEY) || test_selection(params_and_pub, OSSL_KEYMGMT_SELECT_PRIVATE_KEY)) goto err; /* Test priv and pub */ if (!TEST_ptr(bld = OSSL_PARAM_BLD_new()) || !TEST_true(OSSL_PARAM_BLD_push_utf8_string(bld, OSSL_PKEY_PARAM_GROUP_NAME, "P-256", 0)) || !TEST_true(OSSL_PARAM_BLD_push_octet_string(bld, OSSL_PKEY_PARAM_PUB_KEY, ec_pub, sizeof(ec_pub))) || !TEST_true(OSSL_PARAM_BLD_push_BN(bld, OSSL_PKEY_PARAM_PRIV_KEY, priv))) goto err; if (!TEST_ptr(params = OSSL_PARAM_BLD_to_param(bld)) || !TEST_ptr(params_and_keypair = make_key_fromdata("EC", params))) goto err; if (!test_selection(params_and_keypair, EVP_PKEY_KEYPAIR)) goto err; /* Try key equality */ if (!TEST_int_gt(EVP_PKEY_parameters_eq(just_params, just_params), 0) || !TEST_int_gt(EVP_PKEY_parameters_eq(just_params, params_and_pub), 0) || !TEST_int_gt(EVP_PKEY_parameters_eq(just_params, params_and_priv), 0) || !TEST_int_gt(EVP_PKEY_parameters_eq(just_params, params_and_keypair), 0) || !TEST_int_gt(EVP_PKEY_eq(params_and_pub, params_and_pub), 0) || !TEST_int_gt(EVP_PKEY_eq(params_and_priv, params_and_priv), 0) || !TEST_int_gt(EVP_PKEY_eq(params_and_keypair, params_and_pub), 0) || !TEST_int_gt(EVP_PKEY_eq(params_and_keypair, params_and_priv), 0)) goto err; /* Positive and negative testcase for EVP_PKEY_get1_encoded_public_key */ if (!TEST_int_gt(EVP_PKEY_get1_encoded_public_key(params_and_pub, &encoded), 0)) goto err; OPENSSL_free(encoded); encoded = NULL; if (!TEST_int_eq(EVP_PKEY_get1_encoded_public_key(just_params, &encoded), 0)) { OPENSSL_free(encoded); encoded = NULL; goto err; } /* Positive and negative testcase for EVP_PKEY_get_octet_string_param */ if (!TEST_int_eq(EVP_PKEY_get_octet_string_param(params_and_pub, OSSL_PKEY_PARAM_ENCODED_PUBLIC_KEY, buffer, sizeof(buffer), &len), 1) || !TEST_int_eq(len, 65)) goto err; len = 0; if (!TEST_int_eq(EVP_PKEY_get_octet_string_param(params_and_pub, OSSL_PKEY_PARAM_ENCODED_PUBLIC_KEY, NULL, 0, &len), 1) || !TEST_int_eq(len, 65)) goto err; /* too-short buffer len*/ if (!TEST_int_eq(EVP_PKEY_get_octet_string_param(params_and_pub, OSSL_PKEY_PARAM_ENCODED_PUBLIC_KEY, buffer, 10, &len), 0)) goto err; ret = 1; err: OSSL_PARAM_free(params); OSSL_PARAM_BLD_free(bld); EVP_PKEY_free(just_params); EVP_PKEY_free(params_and_priv); EVP_PKEY_free(params_and_pub); EVP_PKEY_free(params_and_keypair); BN_free(priv); return ret; } /* Also test that we can read the EC PUB affine coordinates */ static int test_evp_get_ec_pub(void) { OSSL_PARAM_BLD *bld = NULL; OSSL_PARAM *params = NULL; unsigned char *pad = NULL; EVP_PKEY *keypair = NULL; BIGNUM *priv = NULL; BIGNUM *x = NULL; BIGNUM *y = NULL; int ret = 0; if (!TEST_ptr(priv = BN_bin2bn(ec_priv, sizeof(ec_priv), NULL))) goto err; if (!TEST_ptr(bld = OSSL_PARAM_BLD_new()) || !TEST_true(OSSL_PARAM_BLD_push_utf8_string(bld, OSSL_PKEY_PARAM_GROUP_NAME, "P-256", 0)) || !TEST_true(OSSL_PARAM_BLD_push_octet_string(bld, OSSL_PKEY_PARAM_PUB_KEY, ec_pub, sizeof(ec_pub))) || !TEST_true(OSSL_PARAM_BLD_push_BN(bld, OSSL_PKEY_PARAM_PRIV_KEY, priv))) goto err; if (!TEST_ptr(params = OSSL_PARAM_BLD_to_param(bld)) || !TEST_ptr(keypair = make_key_fromdata("EC", params))) goto err; if (!test_selection(keypair, EVP_PKEY_KEYPAIR)) goto err; if (!EVP_PKEY_get_bn_param(keypair, OSSL_PKEY_PARAM_EC_PUB_X, &x) || !EVP_PKEY_get_bn_param(keypair, OSSL_PKEY_PARAM_EC_PUB_Y, &y)) goto err; if (!TEST_ptr(pad = OPENSSL_zalloc(sizeof(ec_pub)))) goto err; pad[0] = ec_pub[0]; BN_bn2bin(x, &pad[1]); BN_bn2bin(y, &pad[33]); if (!TEST_true(memcmp(ec_pub, pad, sizeof(ec_pub)) == 0)) goto err; ret = 1; err: OSSL_PARAM_free(params); OSSL_PARAM_BLD_free(bld); EVP_PKEY_free(keypair); OPENSSL_free(pad); BN_free(priv); BN_free(x); BN_free(y); return ret; } /* Test that using a legacy EC key with only a private key in it works */ # ifndef OPENSSL_NO_DEPRECATED_3_0 static int test_EC_priv_only_legacy(void) { BIGNUM *priv = NULL; int ret = 0; EC_KEY *eckey = NULL; EVP_PKEY *pkey = NULL, *dup_pk = NULL; EVP_MD_CTX *ctx = NULL; /* Create the low level EC_KEY */ if (!TEST_ptr(priv = BN_bin2bn(ec_priv, sizeof(ec_priv), NULL))) goto err; eckey = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1); if (!TEST_ptr(eckey)) goto err; if (!TEST_true(EC_KEY_set_private_key(eckey, priv))) goto err; pkey = EVP_PKEY_new(); if (!TEST_ptr(pkey)) goto err; if (!TEST_true(EVP_PKEY_assign_EC_KEY(pkey, eckey))) goto err; eckey = NULL; while (dup_pk == NULL) { ret = 0; ctx = EVP_MD_CTX_new(); if (!TEST_ptr(ctx)) goto err; /* * The EVP_DigestSignInit function should create the key on the * provider side which is sufficient for this test. */ if (!TEST_true(EVP_DigestSignInit_ex(ctx, NULL, NULL, testctx, testpropq, pkey, NULL))) goto err; EVP_MD_CTX_free(ctx); ctx = NULL; if (!TEST_ptr(dup_pk = EVP_PKEY_dup(pkey))) goto err; /* EVP_PKEY_eq() returns -2 with missing public keys */ ret = TEST_int_eq(EVP_PKEY_eq(pkey, dup_pk), -2); EVP_PKEY_free(pkey); pkey = dup_pk; if (!ret) goto err; } err: EVP_MD_CTX_free(ctx); EVP_PKEY_free(pkey); EC_KEY_free(eckey); BN_free(priv); return ret; } static int test_evp_get_ec_pub_legacy(void) { OSSL_LIB_CTX *libctx = NULL; unsigned char *pad = NULL; EVP_PKEY *pkey = NULL; EC_KEY *eckey = NULL; BIGNUM *priv = NULL; BIGNUM *x = NULL; BIGNUM *y = NULL; int ret = 0; if (!TEST_ptr(libctx = OSSL_LIB_CTX_new())) goto err; /* Create the legacy key */ if (!TEST_ptr(eckey = EC_KEY_new_by_curve_name_ex(libctx, NULL, NID_X9_62_prime256v1))) goto err; if (!TEST_ptr(priv = BN_bin2bn(ec_priv, sizeof(ec_priv), NULL))) goto err; if (!TEST_true(EC_KEY_set_private_key(eckey, priv))) goto err; if (!TEST_ptr(x = BN_bin2bn(&ec_pub[1], 32, NULL))) goto err; if (!TEST_ptr(y = BN_bin2bn(&ec_pub[33], 32, NULL))) goto err; if (!TEST_true(EC_KEY_set_public_key_affine_coordinates(eckey, x, y))) goto err; if (!TEST_ptr(pkey = EVP_PKEY_new())) goto err; /* Transfer the legacy key */ if (!TEST_true(EVP_PKEY_assign_EC_KEY(pkey, eckey))) goto err; eckey = NULL; if (!TEST_true(EVP_PKEY_get_bn_param(pkey, OSSL_PKEY_PARAM_EC_PUB_X, &x)) || !TEST_true(EVP_PKEY_get_bn_param(pkey, OSSL_PKEY_PARAM_EC_PUB_Y, &y))) goto err; if (!TEST_ptr(pad = OPENSSL_zalloc(sizeof(ec_pub)))) goto err; pad[0] = ec_pub[0]; BN_bn2bin(x, &pad[1]); BN_bn2bin(y, &pad[33]); if (!TEST_true(memcmp(ec_pub, pad, sizeof(ec_pub)) == 0)) goto err; ret = 1; err: OSSL_LIB_CTX_free(libctx); EVP_PKEY_free(pkey); EC_KEY_free(eckey); OPENSSL_free(pad); BN_free(priv); BN_free(x); BN_free(y); return ret; } # endif /* OPENSSL_NO_DEPRECATED_3_0 */ #endif /* OPENSSL_NO_EC */ static int test_EVP_PKEY_sign(int tst) { int ret = 0; EVP_PKEY *pkey = NULL; unsigned char *sig = NULL; size_t sig_len = 0, shortsig_len = 1; EVP_PKEY_CTX *ctx = NULL; unsigned char tbs[] = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13 }; if (tst == 0) { if (!TEST_ptr(pkey = load_example_rsa_key())) goto out; } else if (tst == 1) { #ifndef OPENSSL_NO_DSA if (!TEST_ptr(pkey = load_example_dsa_key())) goto out; #else ret = 1; goto out; #endif } else { #ifndef OPENSSL_NO_EC if (!TEST_ptr(pkey = load_example_ec_key())) goto out; #else ret = 1; goto out; #endif } ctx = EVP_PKEY_CTX_new_from_pkey(testctx, pkey, NULL); if (!TEST_ptr(ctx) || !TEST_int_gt(EVP_PKEY_sign_init(ctx), 0) || !TEST_int_gt(EVP_PKEY_sign(ctx, NULL, &sig_len, tbs, sizeof(tbs)), 0)) goto out; sig = OPENSSL_malloc(sig_len); if (!TEST_ptr(sig) /* Test sending a signature buffer that is too short is rejected */ || !TEST_int_le(EVP_PKEY_sign(ctx, sig, &shortsig_len, tbs, sizeof(tbs)), 0) || !TEST_int_gt(EVP_PKEY_sign(ctx, sig, &sig_len, tbs, sizeof(tbs)), 0) /* Test the signature round-trips */ || !TEST_int_gt(EVP_PKEY_verify_init(ctx), 0) || !TEST_int_gt(EVP_PKEY_verify(ctx, sig, sig_len, tbs, sizeof(tbs)), 0)) goto out; ret = 1; out: EVP_PKEY_CTX_free(ctx); OPENSSL_free(sig); EVP_PKEY_free(pkey); return ret; } #ifndef OPENSSL_NO_DEPRECATED_3_0 static int test_EVP_PKEY_sign_with_app_method(int tst) { int ret = 0; EVP_PKEY *pkey = NULL; RSA *rsa = NULL; RSA_METHOD *rsa_meth = NULL; #ifndef OPENSSL_NO_DSA DSA *dsa = NULL; DSA_METHOD *dsa_meth = NULL; #endif unsigned char *sig = NULL; size_t sig_len = 0, shortsig_len = 1; EVP_PKEY_CTX *ctx = NULL; unsigned char tbs[] = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13 }; if (tst == 0) { if (!TEST_ptr(pkey = load_example_rsa_key())) goto out; if (!TEST_ptr(rsa_meth = RSA_meth_dup(RSA_get_default_method()))) goto out; if (!TEST_ptr(rsa = EVP_PKEY_get1_RSA(pkey)) || !TEST_int_gt(RSA_set_method(rsa, rsa_meth), 0) || !TEST_int_gt(EVP_PKEY_assign_RSA(pkey, rsa), 0)) goto out; rsa = NULL; /* now owned by the pkey */ } else { #ifndef OPENSSL_NO_DSA if (!TEST_ptr(pkey = load_example_dsa_key())) goto out; if (!TEST_ptr(dsa_meth = DSA_meth_dup(DSA_get_default_method()))) goto out; if (!TEST_ptr(dsa = EVP_PKEY_get1_DSA(pkey)) || !TEST_int_gt(DSA_set_method(dsa, dsa_meth), 0) || !TEST_int_gt(EVP_PKEY_assign_DSA(pkey, dsa), 0)) goto out; dsa = NULL; /* now owned by the pkey */ #else ret = 1; goto out; #endif } ctx = EVP_PKEY_CTX_new_from_pkey(testctx, pkey, NULL); if (!TEST_ptr(ctx) || !TEST_int_gt(EVP_PKEY_sign_init(ctx), 0) || !TEST_int_gt(EVP_PKEY_sign(ctx, NULL, &sig_len, tbs, sizeof(tbs)), 0)) goto out; sig = OPENSSL_malloc(sig_len); if (!TEST_ptr(sig) /* Test sending a signature buffer that is too short is rejected */ || !TEST_int_le(EVP_PKEY_sign(ctx, sig, &shortsig_len, tbs, sizeof(tbs)), 0) || !TEST_int_gt(EVP_PKEY_sign(ctx, sig, &sig_len, tbs, sizeof(tbs)), 0) /* Test the signature round-trips */ || !TEST_int_gt(EVP_PKEY_verify_init(ctx), 0) || !TEST_int_gt(EVP_PKEY_verify(ctx, sig, sig_len, tbs, sizeof(tbs)), 0)) goto out; ret = 1; out: EVP_PKEY_CTX_free(ctx); OPENSSL_free(sig); EVP_PKEY_free(pkey); RSA_free(rsa); RSA_meth_free(rsa_meth); #ifndef OPENSSL_NO_DSA DSA_free(dsa); DSA_meth_free(dsa_meth); #endif return ret; } #endif /* !OPENSSL_NO_DEPRECATED_3_0 */ /* * n = 0 => test using legacy cipher * n = 1 => test using fetched cipher */ static int test_EVP_Enveloped(int n) { int ret = 0; EVP_CIPHER_CTX *ctx = NULL; EVP_PKEY *keypair = NULL; unsigned char *kek = NULL; unsigned char iv[EVP_MAX_IV_LENGTH]; static const unsigned char msg[] = { 1, 2, 3, 4, 5, 6, 7, 8 }; int len, kek_len, ciphertext_len, plaintext_len; unsigned char ciphertext[32], plaintext[16]; EVP_CIPHER *type = NULL; if (nullprov != NULL) return TEST_skip("Test does not support a non-default library context"); if (n == 0) type = (EVP_CIPHER *)EVP_aes_256_cbc(); else if (!TEST_ptr(type = EVP_CIPHER_fetch(testctx, "AES-256-CBC", testpropq))) goto err; if (!TEST_ptr(keypair = load_example_rsa_key()) || !TEST_ptr(kek = OPENSSL_zalloc(EVP_PKEY_get_size(keypair))) || !TEST_ptr(ctx = EVP_CIPHER_CTX_new()) || !TEST_true(EVP_SealInit(ctx, type, &kek, &kek_len, iv, &keypair, 1)) || !TEST_true(EVP_SealUpdate(ctx, ciphertext, &ciphertext_len, msg, sizeof(msg))) || !TEST_true(EVP_SealFinal(ctx, ciphertext + ciphertext_len, &len))) goto err; ciphertext_len += len; if (!TEST_true(EVP_OpenInit(ctx, type, kek, kek_len, iv, keypair)) || !TEST_true(EVP_OpenUpdate(ctx, plaintext, &plaintext_len, ciphertext, ciphertext_len)) || !TEST_true(EVP_OpenFinal(ctx, plaintext + plaintext_len, &len))) goto err; plaintext_len += len; if (!TEST_mem_eq(msg, sizeof(msg), plaintext, plaintext_len)) goto err; ret = 1; err: if (n != 0) EVP_CIPHER_free(type); OPENSSL_free(kek); EVP_PKEY_free(keypair); EVP_CIPHER_CTX_free(ctx); return ret; } /* * Test 0: Standard calls to EVP_DigestSignInit/Update/Final (Implicit fetch digest, RSA) * Test 1: Standard calls to EVP_DigestSignInit/Update/Final (Implicit fetch digest, DSA) * Test 2: Standard calls to EVP_DigestSignInit/Update/Final (Implicit fetch digest, HMAC) * Test 3: Standard calls to EVP_DigestSignInit/Update/Final (Explicit fetch digest, RSA) * Test 4: Standard calls to EVP_DigestSignInit/Update/Final (Explicit fetch digest, DSA) * Test 5: Standard calls to EVP_DigestSignInit/Update/Final (Explicit fetch diegst, HMAC) * Test 6: Use an MD BIO to do the Update calls instead (RSA) * Test 7: Use an MD BIO to do the Update calls instead (DSA) * Test 8: Use an MD BIO to do the Update calls instead (HMAC) * Test 9: Use EVP_DigestSign (Implicit fetch digest, RSA, short sig) * Test 10: Use EVP_DigestSign (Implicit fetch digest, DSA, short sig) * Test 11: Use EVP_DigestSign (Implicit fetch digest, HMAC, short sig) * Test 12: Use EVP_DigestSign (Implicit fetch digest, RSA) * Test 13: Use EVP_DigestSign (Implicit fetch digest, DSA) * Test 14: Use EVP_DigestSign (Implicit fetch digest, HMAC) * Test 15-29: Same as above with reinitialization */ static int test_EVP_DigestSignInit(int tst) { int ret = 0; EVP_PKEY *pkey = NULL; unsigned char *sig = NULL, *sig2 = NULL; size_t sig_len = 0, sig2_len = 0, shortsig_len = 1; EVP_MD_CTX *md_ctx = NULL, *md_ctx_verify = NULL; EVP_MD_CTX *a_md_ctx = NULL, *a_md_ctx_verify = NULL; BIO *mdbio = NULL, *membio = NULL; size_t written; const EVP_MD *md; EVP_MD *mdexp = NULL; int reinit = 0; if (nullprov != NULL) return TEST_skip("Test does not support a non-default library context"); if (tst >= 15) { reinit = 1; tst -= 15; } if (tst >= 6 && tst <= 8) { membio = BIO_new(BIO_s_mem()); mdbio = BIO_new(BIO_f_md()); if (!TEST_ptr(membio) || !TEST_ptr(mdbio)) goto out; BIO_push(mdbio, membio); if (!TEST_int_gt(BIO_get_md_ctx(mdbio, &md_ctx), 0)) goto out; } else { if (!TEST_ptr(a_md_ctx = md_ctx = EVP_MD_CTX_new()) || !TEST_ptr(a_md_ctx_verify = md_ctx_verify = EVP_MD_CTX_new())) goto out; } if (tst % 3 == 0) { if (!TEST_ptr(pkey = load_example_rsa_key())) goto out; } else if (tst % 3 == 1) { #ifndef OPENSSL_NO_DSA if (!TEST_ptr(pkey = load_example_dsa_key())) goto out; #else ret = 1; goto out; #endif } else { if (!TEST_ptr(pkey = load_example_hmac_key())) goto out; } if (tst >= 3 && tst <= 5) md = mdexp = EVP_MD_fetch(NULL, "SHA256", NULL); else md = EVP_sha256(); if (!TEST_true(EVP_DigestSignInit(md_ctx, NULL, md, NULL, pkey))) goto out; if (reinit && !TEST_true(EVP_DigestSignInit(md_ctx, NULL, NULL, NULL, NULL))) goto out; if (tst >= 6 && tst <= 8) { if (!BIO_write_ex(mdbio, kMsg, sizeof(kMsg), &written)) goto out; } else if (tst < 6) { if (!TEST_true(EVP_DigestSignUpdate(md_ctx, kMsg, sizeof(kMsg)))) goto out; } if (tst >= 9) { /* Determine the size of the signature. */ if (!TEST_true(EVP_DigestSign(md_ctx, NULL, &sig_len, kMsg, sizeof(kMsg))) || !TEST_ptr(sig = OPENSSL_malloc(sig_len))) goto out; if (tst <= 11) { /* Test that supply a short sig buffer fails */ if (!TEST_false(EVP_DigestSign(md_ctx, sig, &shortsig_len, kMsg, sizeof(kMsg)))) goto out; /* * We end here because once EVP_DigestSign() has failed you should * not call it again without re-initing the ctx */ ret = 1; goto out; } if (!TEST_true(EVP_DigestSign(md_ctx, sig, &sig_len, kMsg, sizeof(kMsg)))) goto out; } else { /* Determine the size of the signature. */ if (!TEST_true(EVP_DigestSignFinal(md_ctx, NULL, &sig_len)) || !TEST_ptr(sig = OPENSSL_malloc(sig_len)) /* * Trying to create a signature with a deliberately short * buffer should fail. */ || !TEST_false(EVP_DigestSignFinal(md_ctx, sig, &shortsig_len)) || !TEST_true(EVP_DigestSignFinal(md_ctx, sig, &sig_len))) goto out; } /* * Ensure that the signature round-trips (Verification isn't supported for * HMAC via EVP_DigestVerify*) */ if (tst % 3 != 2) { if (tst >= 6 && tst <= 8) { if (!TEST_int_gt(BIO_reset(mdbio), 0) || !TEST_int_gt(BIO_get_md_ctx(mdbio, &md_ctx_verify), 0)) goto out; } if (!TEST_true(EVP_DigestVerifyInit(md_ctx_verify, NULL, md, NULL, pkey))) goto out; if (tst >= 6 && tst <= 8) { if (!TEST_true(BIO_write_ex(mdbio, kMsg, sizeof(kMsg), &written))) goto out; } else { if (!TEST_true(EVP_DigestVerifyUpdate(md_ctx_verify, kMsg, sizeof(kMsg)))) goto out; } if (!TEST_int_gt(EVP_DigestVerifyFinal(md_ctx_verify, sig, sig_len), 0)) goto out; /* Multiple calls to EVP_DigestVerifyFinal should work */ if (!TEST_int_gt(EVP_DigestVerifyFinal(md_ctx_verify, sig, sig_len), 0)) goto out; } else { /* * For HMAC a doubled call to DigestSignFinal should produce the same * value as finalization should not happen. */ if (!TEST_true(EVP_DigestSignFinal(md_ctx, NULL, &sig2_len)) || !TEST_ptr(sig2 = OPENSSL_malloc(sig2_len)) || !TEST_true(EVP_DigestSignFinal(md_ctx, sig2, &sig2_len))) goto out; if (!TEST_mem_eq(sig, sig_len, sig2, sig2_len)) goto out; } ret = 1; out: BIO_free(membio); BIO_free(mdbio); EVP_MD_CTX_free(a_md_ctx); EVP_MD_CTX_free(a_md_ctx_verify); EVP_PKEY_free(pkey); OPENSSL_free(sig); OPENSSL_free(sig2); EVP_MD_free(mdexp); return ret; } static int test_EVP_DigestVerifyInit(void) { int ret = 0; EVP_PKEY *pkey = NULL; EVP_MD_CTX *md_ctx = NULL; if (nullprov != NULL) return TEST_skip("Test does not support a non-default library context"); if (!TEST_ptr(md_ctx = EVP_MD_CTX_new()) || !TEST_ptr(pkey = load_example_rsa_key())) goto out; if (!TEST_true(EVP_DigestVerifyInit(md_ctx, NULL, EVP_sha256(), NULL, pkey)) || !TEST_true(EVP_DigestVerifyUpdate(md_ctx, kMsg, sizeof(kMsg))) || !TEST_int_gt(EVP_DigestVerifyFinal(md_ctx, kSignature, sizeof(kSignature)), 0)) goto out; /* test with reinitialization */ if (!TEST_true(EVP_DigestVerifyInit(md_ctx, NULL, NULL, NULL, NULL)) || !TEST_true(EVP_DigestVerifyUpdate(md_ctx, kMsg, sizeof(kMsg))) || !TEST_int_gt(EVP_DigestVerifyFinal(md_ctx, kSignature, sizeof(kSignature)), 0)) goto out; ret = 1; out: EVP_MD_CTX_free(md_ctx); EVP_PKEY_free(pkey); return ret; } #ifndef OPENSSL_NO_SIPHASH /* test SIPHASH MAC via EVP_PKEY with non-default parameters and reinit */ static int test_siphash_digestsign(void) { unsigned char key[16]; unsigned char buf[8], digest[8]; unsigned char expected[8] = { 0x6d, 0x3e, 0x54, 0xc2, 0x2f, 0xf1, 0xfe, 0xe2 }; EVP_PKEY *pkey = NULL; EVP_MD_CTX *mdctx = NULL; EVP_PKEY_CTX *ctx = NULL; int ret = 0; size_t len = 8; if (nullprov != NULL) return TEST_skip("Test does not support a non-default library context"); memset(buf, 0, 8); memset(key, 1, 16); if (!TEST_ptr(pkey = EVP_PKEY_new_raw_private_key(EVP_PKEY_SIPHASH, NULL, key, 16))) goto out; if (!TEST_ptr(mdctx = EVP_MD_CTX_create())) goto out; if (!TEST_true(EVP_DigestSignInit(mdctx, &ctx, NULL, NULL, pkey))) goto out; if (!TEST_int_eq(EVP_PKEY_CTX_ctrl(ctx, -1, EVP_PKEY_OP_SIGNCTX, EVP_PKEY_CTRL_SET_DIGEST_SIZE, 8, NULL), 1)) goto out; /* reinitialize */ if (!TEST_true(EVP_DigestSignInit(mdctx, NULL, NULL, NULL, NULL))) goto out; if (!TEST_true(EVP_DigestSignUpdate(mdctx, buf, 8))) goto out; if (!TEST_true(EVP_DigestSignFinal(mdctx, digest, &len))) goto out; if (!TEST_mem_eq(digest, len, expected, sizeof(expected))) goto out; ret = 1; out: EVP_PKEY_free(pkey); EVP_MD_CTX_free(mdctx); return ret; } #endif /* * Test corner cases of EVP_DigestInit/Update/Final API call behavior. */ static int test_EVP_Digest(void) { int ret = 0; EVP_MD_CTX *md_ctx = NULL; unsigned char md[EVP_MAX_MD_SIZE]; EVP_MD *sha256 = NULL; EVP_MD *shake256 = NULL; if (!TEST_ptr(md_ctx = EVP_MD_CTX_new())) goto out; if (!TEST_ptr(sha256 = EVP_MD_fetch(testctx, "sha256", testpropq)) || !TEST_ptr(shake256 = EVP_MD_fetch(testctx, "shake256", testpropq))) goto out; if (!TEST_true(EVP_DigestInit_ex(md_ctx, sha256, NULL)) || !TEST_true(EVP_DigestUpdate(md_ctx, kMsg, sizeof(kMsg))) || !TEST_true(EVP_DigestFinal(md_ctx, md, NULL)) /* EVP_DigestFinal resets the EVP_MD_CTX. */ || !TEST_ptr_eq(EVP_MD_CTX_get0_md(md_ctx), NULL)) goto out; if (!TEST_true(EVP_DigestInit_ex(md_ctx, sha256, NULL)) || !TEST_true(EVP_DigestUpdate(md_ctx, kMsg, sizeof(kMsg))) || !TEST_true(EVP_DigestFinal_ex(md_ctx, md, NULL)) /* EVP_DigestFinal_ex does not reset the EVP_MD_CTX. */ || !TEST_ptr(EVP_MD_CTX_get0_md(md_ctx)) /* * EVP_DigestInit_ex with NULL type should work on * pre-initialized context. */ || !TEST_true(EVP_DigestInit_ex(md_ctx, NULL, NULL))) goto out; if (!TEST_true(EVP_DigestInit_ex(md_ctx, shake256, NULL)) || !TEST_true(EVP_DigestUpdate(md_ctx, kMsg, sizeof(kMsg))) || !TEST_true(EVP_DigestFinalXOF(md_ctx, md, sizeof(md))) /* EVP_DigestFinalXOF does not reset the EVP_MD_CTX. */ || !TEST_ptr(EVP_MD_CTX_get0_md(md_ctx)) || !TEST_true(EVP_DigestInit_ex(md_ctx, NULL, NULL))) goto out; ret = 1; out: EVP_MD_CTX_free(md_ctx); EVP_MD_free(sha256); EVP_MD_free(shake256); return ret; } static int test_EVP_md_null(void) { int ret = 0; EVP_MD_CTX *md_ctx = NULL; const EVP_MD *md_null = EVP_md_null(); unsigned char md_value[EVP_MAX_MD_SIZE]; unsigned int md_len = sizeof(md_value); if (nullprov != NULL) return TEST_skip("Test does not support a non-default library context"); if (!TEST_ptr(md_null) || !TEST_ptr(md_ctx = EVP_MD_CTX_new())) goto out; if (!TEST_true(EVP_DigestInit_ex(md_ctx, md_null, NULL)) || !TEST_true(EVP_DigestUpdate(md_ctx, "test", 4)) || !TEST_true(EVP_DigestFinal_ex(md_ctx, md_value, &md_len))) goto out; if (!TEST_uint_eq(md_len, 0)) goto out; ret = 1; out: EVP_MD_CTX_free(md_ctx); return ret; } static int test_d2i_AutoPrivateKey(int i) { int ret = 0; const unsigned char *p; EVP_PKEY *pkey = NULL; const APK_DATA *ak = &keydata[i]; const unsigned char *input = ak->kder; size_t input_len = ak->size; int expected_id = ak->evptype; p = input; if (!TEST_ptr(pkey = d2i_AutoPrivateKey(NULL, &p, input_len)) || !TEST_ptr_eq(p, input + input_len) || !TEST_int_eq(EVP_PKEY_get_id(pkey), expected_id)) goto done; ret = 1; done: EVP_PKEY_free(pkey); return ret; } #ifndef OPENSSL_NO_EC static const unsigned char ec_public_sect163k1_validxy[] = { 0x30, 0x40, 0x30, 0x10, 0x06, 0x07, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x02, 0x01, 0x06, 0x05, 0x2b, 0x81, 0x04, 0x00, 0x01, 0x03, 0x2c, 0x00, 0x04, 0x02, 0x84, 0x58, 0xa6, 0xd4, 0xa0, 0x35, 0x2b, 0xae, 0xf0, 0xc0, 0x69, 0x05, 0xcf, 0x2a, 0x50, 0x33, 0xf9, 0xe3, 0x92, 0x79, 0x02, 0xd1, 0x7b, 0x9f, 0x22, 0x00, 0xf0, 0x3b, 0x0e, 0x5d, 0x2e, 0xb7, 0x23, 0x24, 0xf3, 0x6a, 0xd8, 0x17, 0x65, 0x41, 0x2f }; static const unsigned char ec_public_sect163k1_badx[] = { 0x30, 0x40, 0x30, 0x10, 0x06, 0x07, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x02, 0x01, 0x06, 0x05, 0x2b, 0x81, 0x04, 0x00, 0x01, 0x03, 0x2c, 0x00, 0x04, 0x0a, 0x84, 0x58, 0xa6, 0xd4, 0xa0, 0x35, 0x2b, 0xae, 0xf0, 0xc0, 0x69, 0x05, 0xcf, 0x2a, 0x50, 0x33, 0xf9, 0xe3, 0x92, 0xb0, 0x02, 0xd1, 0x7b, 0x9f, 0x22, 0x00, 0xf0, 0x3b, 0x0e, 0x5d, 0x2e, 0xb7, 0x23, 0x24, 0xf3, 0x6a, 0xd8, 0x17, 0x65, 0x41, 0x2f }; static const unsigned char ec_public_sect163k1_bady[] = { 0x30, 0x40, 0x30, 0x10, 0x06, 0x07, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x02, 0x01, 0x06, 0x05, 0x2b, 0x81, 0x04, 0x00, 0x01, 0x03, 0x2c, 0x00, 0x04, 0x02, 0x84, 0x58, 0xa6, 0xd4, 0xa0, 0x35, 0x2b, 0xae, 0xf0, 0xc0, 0x69, 0x05, 0xcf, 0x2a, 0x50, 0x33, 0xf9, 0xe3, 0x92, 0x79, 0x0a, 0xd1, 0x7b, 0x9f, 0x22, 0x00, 0xf0, 0x3b, 0x0e, 0x5d, 0x2e, 0xb7, 0x23, 0x24, 0xf3, 0x6a, 0xd8, 0x17, 0x65, 0x41, 0xe6 }; static struct ec_der_pub_keys_st { const unsigned char *der; size_t len; int valid; } ec_der_pub_keys[] = { { ec_public_sect163k1_validxy, sizeof(ec_public_sect163k1_validxy), 1 }, { ec_public_sect163k1_badx, sizeof(ec_public_sect163k1_badx), 0 }, { ec_public_sect163k1_bady, sizeof(ec_public_sect163k1_bady), 0 }, }; /* * Tests the range of the decoded EC char2 public point. * See ec_GF2m_simple_oct2point(). */ static int test_invalide_ec_char2_pub_range_decode(int id) { int ret = 0; EVP_PKEY *pkey; pkey = load_example_key("EC", ec_der_pub_keys[id].der, ec_der_pub_keys[id].len); ret = (ec_der_pub_keys[id].valid && TEST_ptr(pkey)) || TEST_ptr_null(pkey); EVP_PKEY_free(pkey); return ret; } /* Tests loading a bad key in PKCS8 format */ static int test_EVP_PKCS82PKEY(void) { int ret = 0; const unsigned char *derp = kExampleBadECKeyDER; PKCS8_PRIV_KEY_INFO *p8inf = NULL; EVP_PKEY *pkey = NULL; if (!TEST_ptr(p8inf = d2i_PKCS8_PRIV_KEY_INFO(NULL, &derp, sizeof(kExampleBadECKeyDER)))) goto done; if (!TEST_ptr_eq(derp, kExampleBadECKeyDER + sizeof(kExampleBadECKeyDER))) goto done; if (!TEST_ptr_null(pkey = EVP_PKCS82PKEY(p8inf))) goto done; ret = 1; done: PKCS8_PRIV_KEY_INFO_free(p8inf); EVP_PKEY_free(pkey); return ret; } #endif static int test_EVP_PKCS82PKEY_wrong_tag(void) { EVP_PKEY *pkey = NULL; EVP_PKEY *pkey2 = NULL; BIO *membio = NULL; char *membuf = NULL; PKCS8_PRIV_KEY_INFO *p8inf = NULL; int ok = 0; if (testctx != NULL) /* test not supported with non-default context */ return 1; if (!TEST_ptr(membio = BIO_new(BIO_s_mem())) || !TEST_ptr(pkey = load_example_rsa_key()) || !TEST_int_gt(i2d_PKCS8PrivateKey_bio(membio, pkey, NULL, NULL, 0, NULL, NULL), 0) || !TEST_int_gt(BIO_get_mem_data(membio, &membuf), 0) || !TEST_ptr(p8inf = d2i_PKCS8_PRIV_KEY_INFO_bio(membio, NULL)) || !TEST_ptr(pkey2 = EVP_PKCS82PKEY(p8inf)) || !TEST_int_eq(ERR_peek_last_error(), 0)) { goto done; } ok = 1; done: EVP_PKEY_free(pkey); EVP_PKEY_free(pkey2); PKCS8_PRIV_KEY_INFO_free(p8inf); BIO_free_all(membio); return ok; } /* This uses kExampleRSAKeyDER and kExampleRSAKeyPKCS8 to verify encoding */ static int test_privatekey_to_pkcs8(void) { EVP_PKEY *pkey = NULL; BIO *membio = NULL; char *membuf = NULL; long membuf_len = 0; int ok = 0; if (!TEST_ptr(membio = BIO_new(BIO_s_mem())) || !TEST_ptr(pkey = load_example_rsa_key()) || !TEST_int_gt(i2d_PKCS8PrivateKey_bio(membio, pkey, NULL, NULL, 0, NULL, NULL), 0) || !TEST_int_gt(membuf_len = BIO_get_mem_data(membio, &membuf), 0) || !TEST_ptr(membuf) || !TEST_mem_eq(membuf, (size_t)membuf_len, kExampleRSAKeyPKCS8, sizeof(kExampleRSAKeyPKCS8)) /* * We try to write PEM as well, just to see that it doesn't err, but * assume that the result is correct. */ || !TEST_int_gt(PEM_write_bio_PKCS8PrivateKey(membio, pkey, NULL, NULL, 0, NULL, NULL), 0)) goto done; ok = 1; done: EVP_PKEY_free(pkey); BIO_free_all(membio); return ok; } #ifndef OPENSSL_NO_EC static const struct { int encoding; const char *encoding_name; } ec_encodings[] = { { OPENSSL_EC_EXPLICIT_CURVE, OSSL_PKEY_EC_ENCODING_EXPLICIT }, { OPENSSL_EC_NAMED_CURVE, OSSL_PKEY_EC_ENCODING_GROUP } }; static int ec_export_get_encoding_cb(const OSSL_PARAM params[], void *arg) { const OSSL_PARAM *p; const char *enc_name = NULL; int *enc = arg; size_t i; *enc = -1; if (!TEST_ptr(p = OSSL_PARAM_locate_const(params, OSSL_PKEY_PARAM_EC_ENCODING)) || !TEST_true(OSSL_PARAM_get_utf8_string_ptr(p, &enc_name))) return 0; for (i = 0; i < OSSL_NELEM(ec_encodings); i++) { if (OPENSSL_strcasecmp(enc_name, ec_encodings[i].encoding_name) == 0) { *enc = ec_encodings[i].encoding; break; } } return (*enc != -1); } static int test_EC_keygen_with_enc(int idx) { EVP_PKEY *params = NULL, *key = NULL; EVP_PKEY_CTX *pctx = NULL, *kctx = NULL; int enc; int ret = 0; enc = ec_encodings[idx].encoding; /* Create key parameters */ if (!TEST_ptr(pctx = EVP_PKEY_CTX_new_from_name(testctx, "EC", NULL)) || !TEST_int_gt(EVP_PKEY_paramgen_init(pctx), 0) || !TEST_int_gt(EVP_PKEY_CTX_set_group_name(pctx, "P-256"), 0) || !TEST_int_gt(EVP_PKEY_CTX_set_ec_param_enc(pctx, enc), 0) || !TEST_true(EVP_PKEY_paramgen(pctx, &params)) || !TEST_ptr(params)) goto done; /* Create key */ if (!TEST_ptr(kctx = EVP_PKEY_CTX_new_from_pkey(testctx, params, NULL)) || !TEST_int_gt(EVP_PKEY_keygen_init(kctx), 0) || !TEST_true(EVP_PKEY_keygen(kctx, &key)) || !TEST_ptr(key)) goto done; /* Check that the encoding got all the way into the key */ if (!TEST_true(evp_keymgmt_util_export(key, OSSL_KEYMGMT_SELECT_ALL, ec_export_get_encoding_cb, &enc)) || !TEST_int_eq(enc, ec_encodings[idx].encoding)) goto done; ret = 1; done: EVP_PKEY_free(key); EVP_PKEY_free(params); EVP_PKEY_CTX_free(kctx); EVP_PKEY_CTX_free(pctx); return ret; } #endif #if !defined(OPENSSL_NO_SM2) static int test_EVP_SM2_verify(void) { const char *pubkey = "-----BEGIN PUBLIC KEY-----\n" "MFkwEwYHKoZIzj0CAQYIKoEcz1UBgi0DQgAEp1KLWq1ZE2jmoAnnBJE1LBGxVr18\n" "YvvqECWCpXfAQ9qUJ+UmthnUPf0iM3SaXKHe6PlLIDyNlWMWb9RUh/yU3g==\n" "-----END PUBLIC KEY-----\n"; const char *msg = "message digest"; const char *id = "ALICE123@YAHOO.COM"; const uint8_t signature[] = { 0x30, 0x44, 0x02, 0x20, 0x5b, 0xdb, 0xab, 0x81, 0x4f, 0xbb, 0x8b, 0x69, 0xb1, 0x05, 0x9c, 0x99, 0x3b, 0xb2, 0x45, 0x06, 0x4a, 0x30, 0x15, 0x59, 0x84, 0xcd, 0xee, 0x30, 0x60, 0x36, 0x57, 0x87, 0xef, 0x5c, 0xd0, 0xbe, 0x02, 0x20, 0x43, 0x8d, 0x1f, 0xc7, 0x77, 0x72, 0x39, 0xbb, 0x72, 0xe1, 0xfd, 0x07, 0x58, 0xd5, 0x82, 0xc8, 0x2d, 0xba, 0x3b, 0x2c, 0x46, 0x24, 0xe3, 0x50, 0xff, 0x04, 0xc7, 0xa0, 0x71, 0x9f, 0xa4, 0x70 }; int rc = 0; BIO *bio = NULL; EVP_PKEY *pkey = NULL; EVP_MD_CTX *mctx = NULL; EVP_PKEY_CTX *pctx = NULL; EVP_MD *sm3 = NULL; bio = BIO_new_mem_buf(pubkey, strlen(pubkey)); if (!TEST_true(bio != NULL)) goto done; pkey = PEM_read_bio_PUBKEY_ex(bio, NULL, NULL, NULL, testctx, testpropq); if (!TEST_true(pkey != NULL)) goto done; if (!TEST_true(EVP_PKEY_is_a(pkey, "SM2"))) goto done; if (!TEST_ptr(mctx = EVP_MD_CTX_new())) goto done; if (!TEST_ptr(pctx = EVP_PKEY_CTX_new_from_pkey(testctx, pkey, testpropq))) goto done; EVP_MD_CTX_set_pkey_ctx(mctx, pctx); if (!TEST_ptr(sm3 = EVP_MD_fetch(testctx, "sm3", testpropq))) goto done; if (!TEST_true(EVP_DigestVerifyInit(mctx, NULL, sm3, NULL, pkey))) goto done; if (!TEST_int_gt(EVP_PKEY_CTX_set1_id(pctx, id, strlen(id)), 0)) goto done; if (!TEST_true(EVP_DigestVerifyUpdate(mctx, msg, strlen(msg)))) goto done; if (!TEST_int_gt(EVP_DigestVerifyFinal(mctx, signature, sizeof(signature)), 0)) goto done; rc = 1; done: BIO_free(bio); EVP_PKEY_free(pkey); EVP_PKEY_CTX_free(pctx); EVP_MD_CTX_free(mctx); EVP_MD_free(sm3); return rc; } static int test_EVP_SM2(void) { int ret = 0; EVP_PKEY *pkey = NULL; EVP_PKEY *pkeyparams = NULL; EVP_PKEY_CTX *pctx = NULL; EVP_PKEY_CTX *kctx = NULL; EVP_PKEY_CTX *sctx = NULL; size_t sig_len = 0; unsigned char *sig = NULL; EVP_MD_CTX *md_ctx = NULL; EVP_MD_CTX *md_ctx_verify = NULL; EVP_PKEY_CTX *cctx = NULL; EVP_MD *check_md = NULL; uint8_t ciphertext[128]; size_t ctext_len = sizeof(ciphertext); uint8_t plaintext[8]; size_t ptext_len = sizeof(plaintext); uint8_t sm2_id[] = {1, 2, 3, 4, 'l', 'e', 't', 't', 'e', 'r'}; OSSL_PARAM sparams[2] = {OSSL_PARAM_END, OSSL_PARAM_END}; OSSL_PARAM gparams[2] = {OSSL_PARAM_END, OSSL_PARAM_END}; int i; char mdname[OSSL_MAX_NAME_SIZE]; if (!TEST_ptr(pctx = EVP_PKEY_CTX_new_from_name(testctx, "SM2", testpropq))) goto done; if (!TEST_true(EVP_PKEY_paramgen_init(pctx) == 1)) goto done; if (!TEST_int_gt(EVP_PKEY_CTX_set_ec_paramgen_curve_nid(pctx, NID_sm2), 0)) goto done; if (!TEST_true(EVP_PKEY_paramgen(pctx, &pkeyparams))) goto done; if (!TEST_ptr(kctx = EVP_PKEY_CTX_new_from_pkey(testctx, pkeyparams, testpropq))) goto done; if (!TEST_int_gt(EVP_PKEY_keygen_init(kctx), 0)) goto done; if (!TEST_true(EVP_PKEY_keygen(kctx, &pkey))) goto done; if (!TEST_ptr(md_ctx = EVP_MD_CTX_new())) goto done; if (!TEST_ptr(md_ctx_verify = EVP_MD_CTX_new())) goto done; if (!TEST_ptr(sctx = EVP_PKEY_CTX_new_from_pkey(testctx, pkey, testpropq))) goto done; EVP_MD_CTX_set_pkey_ctx(md_ctx, sctx); EVP_MD_CTX_set_pkey_ctx(md_ctx_verify, sctx); if (!TEST_ptr(check_md = EVP_MD_fetch(testctx, "sm3", testpropq))) goto done; if (!TEST_true(EVP_DigestSignInit(md_ctx, NULL, check_md, NULL, pkey))) goto done; if (!TEST_int_gt(EVP_PKEY_CTX_set1_id(sctx, sm2_id, sizeof(sm2_id)), 0)) goto done; if (!TEST_true(EVP_DigestSignUpdate(md_ctx, kMsg, sizeof(kMsg)))) goto done; /* Determine the size of the signature. */ if (!TEST_true(EVP_DigestSignFinal(md_ctx, NULL, &sig_len))) goto done; if (!TEST_ptr(sig = OPENSSL_malloc(sig_len))) goto done; if (!TEST_true(EVP_DigestSignFinal(md_ctx, sig, &sig_len))) goto done; /* Ensure that the signature round-trips. */ if (!TEST_true(EVP_DigestVerifyInit(md_ctx_verify, NULL, check_md, NULL, pkey))) goto done; if (!TEST_int_gt(EVP_PKEY_CTX_set1_id(sctx, sm2_id, sizeof(sm2_id)), 0)) goto done; if (!TEST_true(EVP_DigestVerifyUpdate(md_ctx_verify, kMsg, sizeof(kMsg)))) goto done; if (!TEST_int_gt(EVP_DigestVerifyFinal(md_ctx_verify, sig, sig_len), 0)) goto done; /* * Try verify again with non-matching 0 length id but ensure that it can * be set on the context and overrides the previous value. */ if (!TEST_true(EVP_DigestVerifyInit(md_ctx_verify, NULL, check_md, NULL, pkey))) goto done; if (!TEST_int_gt(EVP_PKEY_CTX_set1_id(sctx, NULL, 0), 0)) goto done; if (!TEST_true(EVP_DigestVerifyUpdate(md_ctx_verify, kMsg, sizeof(kMsg)))) goto done; if (!TEST_int_eq(EVP_DigestVerifyFinal(md_ctx_verify, sig, sig_len), 0)) goto done; /* now check encryption/decryption */ gparams[0] = OSSL_PARAM_construct_utf8_string(OSSL_ASYM_CIPHER_PARAM_DIGEST, mdname, sizeof(mdname)); for (i = 0; i < 2; i++) { const char *mdnames[] = { #ifndef OPENSSL_NO_SM3 "SM3", #else NULL, #endif "SHA2-256" }; EVP_PKEY_CTX_free(cctx); if (mdnames[i] == NULL) continue; sparams[0] = OSSL_PARAM_construct_utf8_string(OSSL_ASYM_CIPHER_PARAM_DIGEST, (char *)mdnames[i], 0); if (!TEST_ptr(cctx = EVP_PKEY_CTX_new_from_pkey(testctx, pkey, testpropq))) goto done; if (!TEST_true(EVP_PKEY_encrypt_init(cctx))) goto done; if (!TEST_true(EVP_PKEY_CTX_set_params(cctx, sparams))) goto done; if (!TEST_true(EVP_PKEY_encrypt(cctx, ciphertext, &ctext_len, kMsg, sizeof(kMsg)))) goto done; if (!TEST_int_gt(EVP_PKEY_decrypt_init(cctx), 0)) goto done; if (!TEST_true(EVP_PKEY_CTX_set_params(cctx, sparams))) goto done; if (!TEST_int_gt(EVP_PKEY_decrypt(cctx, plaintext, &ptext_len, ciphertext, ctext_len), 0)) goto done; if (!TEST_true(EVP_PKEY_CTX_get_params(cctx, gparams))) goto done; /* * Test we're still using the digest we think we are. * Because of aliases, the easiest is to fetch the digest and * check the name with EVP_MD_is_a(). */ EVP_MD_free(check_md); if (!TEST_ptr(check_md = EVP_MD_fetch(testctx, mdname, testpropq))) goto done; if (!TEST_true(EVP_MD_is_a(check_md, mdnames[i]))) { TEST_info("Fetched md %s isn't %s", mdname, mdnames[i]); goto done; } if (!TEST_true(ptext_len == sizeof(kMsg))) goto done; if (!TEST_true(memcmp(plaintext, kMsg, sizeof(kMsg)) == 0)) goto done; } ret = 1; done: EVP_PKEY_CTX_free(pctx); EVP_PKEY_CTX_free(kctx); EVP_PKEY_CTX_free(sctx); EVP_PKEY_CTX_free(cctx); EVP_PKEY_free(pkey); EVP_PKEY_free(pkeyparams); EVP_MD_CTX_free(md_ctx); EVP_MD_CTX_free(md_ctx_verify); EVP_MD_free(check_md); OPENSSL_free(sig); return ret; } #endif static struct keys_st { int type; char *priv; char *pub; } keys[] = { { EVP_PKEY_HMAC, "0123456789", NULL }, { EVP_PKEY_HMAC, "", NULL #ifndef OPENSSL_NO_POLY1305 }, { EVP_PKEY_POLY1305, "01234567890123456789012345678901", NULL #endif #ifndef OPENSSL_NO_SIPHASH }, { EVP_PKEY_SIPHASH, "0123456789012345", NULL #endif }, #ifndef OPENSSL_NO_ECX { EVP_PKEY_X25519, "01234567890123456789012345678901", "abcdefghijklmnopqrstuvwxyzabcdef" }, { EVP_PKEY_ED25519, "01234567890123456789012345678901", "abcdefghijklmnopqrstuvwxyzabcdef" }, { EVP_PKEY_X448, "01234567890123456789012345678901234567890123456789012345", "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcd" }, { EVP_PKEY_ED448, "012345678901234567890123456789012345678901234567890123456", "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcde" } #endif }; static int test_set_get_raw_keys_int(int tst, int pub, int uselibctx) { int ret = 0; unsigned char buf[80]; unsigned char *in; size_t inlen, len = 0, shortlen = 1; EVP_PKEY *pkey; /* Check if this algorithm supports public keys */ if (pub && keys[tst].pub == NULL) return 1; memset(buf, 0, sizeof(buf)); if (pub) { #ifndef OPENSSL_NO_EC inlen = strlen(keys[tst].pub); in = (unsigned char *)keys[tst].pub; if (uselibctx) { pkey = EVP_PKEY_new_raw_public_key_ex( testctx, OBJ_nid2sn(keys[tst].type), NULL, in, inlen); } else { pkey = EVP_PKEY_new_raw_public_key(keys[tst].type, NULL, in, inlen); } #else return 1; #endif } else { inlen = strlen(keys[tst].priv); in = (unsigned char *)keys[tst].priv; if (uselibctx) { pkey = EVP_PKEY_new_raw_private_key_ex( testctx, OBJ_nid2sn(keys[tst].type), NULL, in, inlen); } else { pkey = EVP_PKEY_new_raw_private_key(keys[tst].type, NULL, in, inlen); } } if (!TEST_ptr(pkey) || !TEST_int_eq(EVP_PKEY_eq(pkey, pkey), 1) || (!pub && !TEST_true(EVP_PKEY_get_raw_private_key(pkey, NULL, &len))) || (pub && !TEST_true(EVP_PKEY_get_raw_public_key(pkey, NULL, &len))) || !TEST_true(len == inlen)) goto done; if (tst != 1) { /* * Test that supplying a buffer that is too small fails. Doesn't apply * to HMAC with a zero length key */ if ((!pub && !TEST_false(EVP_PKEY_get_raw_private_key(pkey, buf, &shortlen))) || (pub && !TEST_false(EVP_PKEY_get_raw_public_key(pkey, buf, &shortlen)))) goto done; } if ((!pub && !TEST_true(EVP_PKEY_get_raw_private_key(pkey, buf, &len))) || (pub && !TEST_true(EVP_PKEY_get_raw_public_key(pkey, buf, &len))) || !TEST_mem_eq(in, inlen, buf, len)) goto done; ret = 1; done: EVP_PKEY_free(pkey); return ret; } static int test_set_get_raw_keys(int tst) { return (nullprov != NULL || test_set_get_raw_keys_int(tst, 0, 0)) && test_set_get_raw_keys_int(tst, 0, 1) && (nullprov != NULL || test_set_get_raw_keys_int(tst, 1, 0)) && test_set_get_raw_keys_int(tst, 1, 1); } #ifndef OPENSSL_NO_DEPRECATED_3_0 static int pkey_custom_check(EVP_PKEY *pkey) { return 0xbeef; } static int pkey_custom_pub_check(EVP_PKEY *pkey) { return 0xbeef; } static int pkey_custom_param_check(EVP_PKEY *pkey) { return 0xbeef; } static EVP_PKEY_METHOD *custom_pmeth; #endif static int test_EVP_PKEY_check(int i) { int ret = 0; EVP_PKEY *pkey = NULL; EVP_PKEY_CTX *ctx = NULL; #ifndef OPENSSL_NO_DEPRECATED_3_0 EVP_PKEY_CTX *ctx2 = NULL; #endif const APK_DATA *ak = &keycheckdata[i]; const unsigned char *input = ak->kder; size_t input_len = ak->size; int expected_id = ak->evptype; int expected_check = ak->check; int expected_pub_check = ak->pub_check; int expected_param_check = ak->param_check; int type = ak->type; if (!TEST_ptr(pkey = load_example_key(ak->keytype, input, input_len))) goto done; if (type == 0 && !TEST_int_eq(EVP_PKEY_get_id(pkey), expected_id)) goto done; if (!TEST_ptr(ctx = EVP_PKEY_CTX_new_from_pkey(testctx, pkey, testpropq))) goto done; if (!TEST_int_eq(EVP_PKEY_check(ctx), expected_check)) goto done; if (!TEST_int_eq(EVP_PKEY_public_check(ctx), expected_pub_check)) goto done; if (!TEST_int_eq(EVP_PKEY_param_check(ctx), expected_param_check)) goto done; #ifndef OPENSSL_NO_DEPRECATED_3_0 ctx2 = EVP_PKEY_CTX_new_id(0xdefaced, NULL); /* assign the pkey directly, as an internal test */ EVP_PKEY_up_ref(pkey); ctx2->pkey = pkey; if (!TEST_int_eq(EVP_PKEY_check(ctx2), 0xbeef)) goto done; if (!TEST_int_eq(EVP_PKEY_public_check(ctx2), 0xbeef)) goto done; if (!TEST_int_eq(EVP_PKEY_param_check(ctx2), 0xbeef)) goto done; #endif ret = 1; done: EVP_PKEY_CTX_free(ctx); #ifndef OPENSSL_NO_DEPRECATED_3_0 EVP_PKEY_CTX_free(ctx2); #endif EVP_PKEY_free(pkey); return ret; } #ifndef OPENSSL_NO_CMAC static int get_cmac_val(EVP_PKEY *pkey, unsigned char *mac) { EVP_MD_CTX *mdctx = EVP_MD_CTX_new(); const char msg[] = "Hello World"; size_t maclen = AES_BLOCK_SIZE; int ret = 1; if (!TEST_ptr(mdctx) || !TEST_true(EVP_DigestSignInit_ex(mdctx, NULL, NULL, testctx, testpropq, pkey, NULL)) || !TEST_true(EVP_DigestSignUpdate(mdctx, msg, sizeof(msg))) || !TEST_true(EVP_DigestSignFinal(mdctx, mac, &maclen)) || !TEST_size_t_eq(maclen, AES_BLOCK_SIZE)) ret = 0; EVP_MD_CTX_free(mdctx); return ret; } static int test_CMAC_keygen(void) { static unsigned char key[] = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f }; EVP_PKEY_CTX *kctx = NULL; int ret = 0; EVP_PKEY *pkey = NULL; unsigned char mac[AES_BLOCK_SIZE]; # if !defined(OPENSSL_NO_DEPRECATED_3_0) unsigned char mac2[AES_BLOCK_SIZE]; # endif if (nullprov != NULL) return TEST_skip("Test does not support a non-default library context"); /* * This is a legacy method for CMACs, but should still work. * This verifies that it works without an ENGINE. */ kctx = EVP_PKEY_CTX_new_id(EVP_PKEY_CMAC, NULL); /* Test a CMAC key created using the "generated" method */ if (!TEST_int_gt(EVP_PKEY_keygen_init(kctx), 0) || !TEST_int_gt(EVP_PKEY_CTX_ctrl(kctx, -1, EVP_PKEY_OP_KEYGEN, EVP_PKEY_CTRL_CIPHER, 0, (void *)EVP_aes_256_cbc()), 0) || !TEST_int_gt(EVP_PKEY_CTX_ctrl(kctx, -1, EVP_PKEY_OP_KEYGEN, EVP_PKEY_CTRL_SET_MAC_KEY, sizeof(key), (void *)key), 0) || !TEST_int_gt(EVP_PKEY_keygen(kctx, &pkey), 0) || !TEST_ptr(pkey) || !TEST_true(get_cmac_val(pkey, mac))) goto done; # if !defined(OPENSSL_NO_DEPRECATED_3_0) EVP_PKEY_free(pkey); /* * Test a CMAC key using the direct method, and compare with the mac * created above. */ pkey = EVP_PKEY_new_CMAC_key(NULL, key, sizeof(key), EVP_aes_256_cbc()); if (!TEST_ptr(pkey) || !TEST_true(get_cmac_val(pkey, mac2)) || !TEST_mem_eq(mac, sizeof(mac), mac2, sizeof(mac2))) goto done; # endif ret = 1; done: EVP_PKEY_free(pkey); EVP_PKEY_CTX_free(kctx); return ret; } #endif static int test_HKDF(void) { EVP_PKEY_CTX *pctx; unsigned char out[20]; size_t outlen; int i, ret = 0; unsigned char salt[] = "0123456789"; unsigned char key[] = "012345678901234567890123456789"; unsigned char info[] = "infostring"; const unsigned char expected[] = { 0xe5, 0x07, 0x70, 0x7f, 0xc6, 0x78, 0xd6, 0x54, 0x32, 0x5f, 0x7e, 0xc5, 0x7b, 0x59, 0x3e, 0xd8, 0x03, 0x6b, 0xed, 0xca }; size_t expectedlen = sizeof(expected); if (!TEST_ptr(pctx = EVP_PKEY_CTX_new_from_name(testctx, "HKDF", testpropq))) goto done; /* We do this twice to test reuse of the EVP_PKEY_CTX */ for (i = 0; i < 2; i++) { outlen = sizeof(out); memset(out, 0, outlen); if (!TEST_int_gt(EVP_PKEY_derive_init(pctx), 0) || !TEST_int_gt(EVP_PKEY_CTX_set_hkdf_md(pctx, EVP_sha256()), 0) || !TEST_int_gt(EVP_PKEY_CTX_set1_hkdf_salt(pctx, salt, sizeof(salt) - 1), 0) || !TEST_int_gt(EVP_PKEY_CTX_set1_hkdf_key(pctx, key, sizeof(key) - 1), 0) || !TEST_int_gt(EVP_PKEY_CTX_add1_hkdf_info(pctx, info, sizeof(info) - 1), 0) || !TEST_int_gt(EVP_PKEY_derive(pctx, out, &outlen), 0) || !TEST_mem_eq(out, outlen, expected, expectedlen)) goto done; } ret = 1; done: EVP_PKEY_CTX_free(pctx); return ret; } static int test_emptyikm_HKDF(void) { EVP_PKEY_CTX *pctx; unsigned char out[20]; size_t outlen; int ret = 0; unsigned char salt[] = "9876543210"; unsigned char key[] = ""; unsigned char info[] = "stringinfo"; const unsigned char expected[] = { 0x68, 0x81, 0xa5, 0x3e, 0x5b, 0x9c, 0x7b, 0x6f, 0x2e, 0xec, 0xc8, 0x47, 0x7c, 0xfa, 0x47, 0x35, 0x66, 0x82, 0x15, 0x30 }; size_t expectedlen = sizeof(expected); if (!TEST_ptr(pctx = EVP_PKEY_CTX_new_from_name(testctx, "HKDF", testpropq))) goto done; outlen = sizeof(out); memset(out, 0, outlen); if (!TEST_int_gt(EVP_PKEY_derive_init(pctx), 0) || !TEST_int_gt(EVP_PKEY_CTX_set_hkdf_md(pctx, EVP_sha256()), 0) || !TEST_int_gt(EVP_PKEY_CTX_set1_hkdf_salt(pctx, salt, sizeof(salt) - 1), 0) || !TEST_int_gt(EVP_PKEY_CTX_set1_hkdf_key(pctx, key, sizeof(key) - 1), 0) || !TEST_int_gt(EVP_PKEY_CTX_add1_hkdf_info(pctx, info, sizeof(info) - 1), 0) || !TEST_int_gt(EVP_PKEY_derive(pctx, out, &outlen), 0) || !TEST_mem_eq(out, outlen, expected, expectedlen)) goto done; ret = 1; done: EVP_PKEY_CTX_free(pctx); return ret; } #ifndef OPENSSL_NO_EC static int test_X509_PUBKEY_inplace(void) { int ret = 0; X509_PUBKEY *xp = X509_PUBKEY_new_ex(testctx, testpropq); const unsigned char *p = kExampleECPubKeyDER; size_t input_len = sizeof(kExampleECPubKeyDER); if (!TEST_ptr(xp)) goto done; if (!TEST_ptr(d2i_X509_PUBKEY(&xp, &p, input_len))) goto done; if (!TEST_ptr(X509_PUBKEY_get0(xp))) goto done; p = kExampleBadECPubKeyDER; input_len = sizeof(kExampleBadECPubKeyDER); if (!TEST_ptr(xp = d2i_X509_PUBKEY(&xp, &p, input_len))) goto done; if (!TEST_true(X509_PUBKEY_get0(xp) == NULL)) goto done; ret = 1; done: X509_PUBKEY_free(xp); return ret; } static int test_X509_PUBKEY_dup(void) { int ret = 0; X509_PUBKEY *xp = NULL, *xq = NULL; const unsigned char *p = kExampleECPubKeyDER; size_t input_len = sizeof(kExampleECPubKeyDER); xp = X509_PUBKEY_new_ex(testctx, testpropq); if (!TEST_ptr(xp) || !TEST_ptr(d2i_X509_PUBKEY(&xp, &p, input_len)) || !TEST_ptr(xq = X509_PUBKEY_dup(xp)) || !TEST_ptr_ne(xp, xq)) goto done; if (!TEST_ptr(X509_PUBKEY_get0(xq)) || !TEST_ptr(X509_PUBKEY_get0(xp)) || !TEST_ptr_ne(X509_PUBKEY_get0(xq), X509_PUBKEY_get0(xp))) goto done; X509_PUBKEY_free(xq); xq = NULL; p = kExampleBadECPubKeyDER; input_len = sizeof(kExampleBadECPubKeyDER); if (!TEST_ptr(xp = d2i_X509_PUBKEY(&xp, &p, input_len)) || !TEST_ptr(xq = X509_PUBKEY_dup(xp))) goto done; X509_PUBKEY_free(xp); xp = NULL; if (!TEST_true(X509_PUBKEY_get0(xq) == NULL)) goto done; ret = 1; done: X509_PUBKEY_free(xp); X509_PUBKEY_free(xq); return ret; } #endif /* OPENSSL_NO_EC */ /* Test getting and setting parameters on an EVP_PKEY_CTX */ static int test_EVP_PKEY_CTX_get_set_params(EVP_PKEY *pkey) { EVP_MD_CTX *mdctx = NULL; EVP_PKEY_CTX *ctx = NULL; const OSSL_PARAM *params; OSSL_PARAM ourparams[2], *param = ourparams, *param_md; int ret = 0; const EVP_MD *md; char mdname[OSSL_MAX_NAME_SIZE]; char ssl3ms[48]; /* Initialise a sign operation */ ctx = EVP_PKEY_CTX_new_from_pkey(testctx, pkey, testpropq); if (!TEST_ptr(ctx) || !TEST_int_gt(EVP_PKEY_sign_init(ctx), 0)) goto err; /* * We should be able to query the parameters now. */ params = EVP_PKEY_CTX_settable_params(ctx); if (!TEST_ptr(params) || !TEST_ptr(OSSL_PARAM_locate_const(params, OSSL_SIGNATURE_PARAM_DIGEST))) goto err; params = EVP_PKEY_CTX_gettable_params(ctx); if (!TEST_ptr(params) || !TEST_ptr(OSSL_PARAM_locate_const(params, OSSL_SIGNATURE_PARAM_ALGORITHM_ID)) || !TEST_ptr(OSSL_PARAM_locate_const(params, OSSL_SIGNATURE_PARAM_DIGEST))) goto err; /* * Test getting and setting params via EVP_PKEY_CTX_set_params() and * EVP_PKEY_CTX_get_params() */ strcpy(mdname, "SHA512"); param_md = param; *param++ = OSSL_PARAM_construct_utf8_string(OSSL_SIGNATURE_PARAM_DIGEST, mdname, 0); *param++ = OSSL_PARAM_construct_end(); if (!TEST_true(EVP_PKEY_CTX_set_params(ctx, ourparams))) goto err; mdname[0] = '\0'; *param_md = OSSL_PARAM_construct_utf8_string(OSSL_SIGNATURE_PARAM_DIGEST, mdname, sizeof(mdname)); if (!TEST_true(EVP_PKEY_CTX_get_params(ctx, ourparams)) || !TEST_str_eq(mdname, "SHA512")) goto err; /* * Test the TEST_PKEY_CTX_set_signature_md() and * TEST_PKEY_CTX_get_signature_md() functions */ if (!TEST_int_gt(EVP_PKEY_CTX_set_signature_md(ctx, EVP_sha256()), 0) || !TEST_int_gt(EVP_PKEY_CTX_get_signature_md(ctx, &md), 0) || !TEST_ptr_eq(md, EVP_sha256())) goto err; /* * Test getting MD parameters via an associated EVP_PKEY_CTX */ mdctx = EVP_MD_CTX_new(); if (!TEST_ptr(mdctx) || !TEST_true(EVP_DigestSignInit_ex(mdctx, NULL, "SHA1", testctx, testpropq, pkey, NULL))) goto err; /* * We now have an EVP_MD_CTX with an EVP_PKEY_CTX inside it. We should be * able to obtain the digest's settable parameters from the provider. */ params = EVP_MD_CTX_settable_params(mdctx); if (!TEST_ptr(params) || !TEST_int_eq(strcmp(params[0].key, OSSL_DIGEST_PARAM_SSL3_MS), 0) /* The final key should be NULL */ || !TEST_ptr_null(params[1].key)) goto err; param = ourparams; memset(ssl3ms, 0, sizeof(ssl3ms)); *param++ = OSSL_PARAM_construct_octet_string(OSSL_DIGEST_PARAM_SSL3_MS, ssl3ms, sizeof(ssl3ms)); *param++ = OSSL_PARAM_construct_end(); if (!TEST_true(EVP_MD_CTX_set_params(mdctx, ourparams))) goto err; ret = 1; err: EVP_MD_CTX_free(mdctx); EVP_PKEY_CTX_free(ctx); return ret; } #ifndef OPENSSL_NO_DSA static int test_DSA_get_set_params(void) { OSSL_PARAM_BLD *bld = NULL; OSSL_PARAM *params = NULL; BIGNUM *p = NULL, *q = NULL, *g = NULL, *pub = NULL, *priv = NULL; EVP_PKEY_CTX *pctx = NULL; EVP_PKEY *pkey = NULL; int ret = 0; /* * Setup the parameters for our DSA object. For our purposes they don't * have to actually be *valid* parameters. We just need to set something. */ if (!TEST_ptr(pctx = EVP_PKEY_CTX_new_from_name(testctx, "DSA", NULL)) || !TEST_ptr(bld = OSSL_PARAM_BLD_new()) || !TEST_ptr(p = BN_new()) || !TEST_ptr(q = BN_new()) || !TEST_ptr(g = BN_new()) || !TEST_ptr(pub = BN_new()) || !TEST_ptr(priv = BN_new())) goto err; if (!TEST_true(OSSL_PARAM_BLD_push_BN(bld, OSSL_PKEY_PARAM_FFC_P, p)) || !TEST_true(OSSL_PARAM_BLD_push_BN(bld, OSSL_PKEY_PARAM_FFC_Q, q)) || !TEST_true(OSSL_PARAM_BLD_push_BN(bld, OSSL_PKEY_PARAM_FFC_G, g)) || !TEST_true(OSSL_PARAM_BLD_push_BN(bld, OSSL_PKEY_PARAM_PUB_KEY, pub)) || !TEST_true(OSSL_PARAM_BLD_push_BN(bld, OSSL_PKEY_PARAM_PRIV_KEY, priv))) goto err; if (!TEST_ptr(params = OSSL_PARAM_BLD_to_param(bld))) goto err; if (!TEST_int_gt(EVP_PKEY_fromdata_init(pctx), 0) || !TEST_int_gt(EVP_PKEY_fromdata(pctx, &pkey, EVP_PKEY_KEYPAIR, params), 0)) goto err; if (!TEST_ptr(pkey)) goto err; ret = test_EVP_PKEY_CTX_get_set_params(pkey); err: EVP_PKEY_free(pkey); EVP_PKEY_CTX_free(pctx); OSSL_PARAM_free(params); OSSL_PARAM_BLD_free(bld); BN_free(p); BN_free(q); BN_free(g); BN_free(pub); BN_free(priv); return ret; } /* * Test combinations of private, public, missing and private + public key * params to ensure they are all accepted */ static int test_DSA_priv_pub(void) { return test_EVP_PKEY_ffc_priv_pub("DSA"); } #endif /* !OPENSSL_NO_DSA */ static int test_RSA_get_set_params(void) { OSSL_PARAM_BLD *bld = NULL; OSSL_PARAM *params = NULL; BIGNUM *n = NULL, *e = NULL, *d = NULL; EVP_PKEY_CTX *pctx = NULL; EVP_PKEY *pkey = NULL; int ret = 0; /* * Setup the parameters for our RSA object. For our purposes they don't * have to actually be *valid* parameters. We just need to set something. */ if (!TEST_ptr(pctx = EVP_PKEY_CTX_new_from_name(testctx, "RSA", NULL)) || !TEST_ptr(bld = OSSL_PARAM_BLD_new()) || !TEST_ptr(n = BN_new()) || !TEST_ptr(e = BN_new()) || !TEST_ptr(d = BN_new())) goto err; if (!TEST_true(OSSL_PARAM_BLD_push_BN(bld, OSSL_PKEY_PARAM_RSA_N, n)) || !TEST_true(OSSL_PARAM_BLD_push_BN(bld, OSSL_PKEY_PARAM_RSA_E, e)) || !TEST_true(OSSL_PARAM_BLD_push_BN(bld, OSSL_PKEY_PARAM_RSA_D, d))) goto err; if (!TEST_ptr(params = OSSL_PARAM_BLD_to_param(bld))) goto err; if (!TEST_int_gt(EVP_PKEY_fromdata_init(pctx), 0) || !TEST_int_gt(EVP_PKEY_fromdata(pctx, &pkey, EVP_PKEY_KEYPAIR, params), 0)) goto err; if (!TEST_ptr(pkey)) goto err; ret = test_EVP_PKEY_CTX_get_set_params(pkey); err: EVP_PKEY_free(pkey); EVP_PKEY_CTX_free(pctx); OSSL_PARAM_free(params); OSSL_PARAM_BLD_free(bld); BN_free(n); BN_free(e); BN_free(d); return ret; } static int test_RSA_OAEP_set_get_params(void) { int ret = 0; EVP_PKEY *key = NULL; EVP_PKEY_CTX *key_ctx = NULL; if (nullprov != NULL) return TEST_skip("Test does not support a non-default library context"); if (!TEST_ptr(key = load_example_rsa_key()) || !TEST_ptr(key_ctx = EVP_PKEY_CTX_new_from_pkey(0, key, 0))) goto err; { int padding = RSA_PKCS1_OAEP_PADDING; OSSL_PARAM params[4]; params[0] = OSSL_PARAM_construct_int(OSSL_SIGNATURE_PARAM_PAD_MODE, &padding); params[1] = OSSL_PARAM_construct_utf8_string(OSSL_ASYM_CIPHER_PARAM_OAEP_DIGEST, OSSL_DIGEST_NAME_SHA2_256, 0); params[2] = OSSL_PARAM_construct_utf8_string(OSSL_ASYM_CIPHER_PARAM_MGF1_DIGEST, OSSL_DIGEST_NAME_SHA1, 0); params[3] = OSSL_PARAM_construct_end(); if (!TEST_int_gt(EVP_PKEY_encrypt_init_ex(key_ctx, params),0)) goto err; } { OSSL_PARAM params[3]; char oaepmd[30] = { '\0' }; char mgf1md[30] = { '\0' }; params[0] = OSSL_PARAM_construct_utf8_string(OSSL_ASYM_CIPHER_PARAM_OAEP_DIGEST, oaepmd, sizeof(oaepmd)); params[1] = OSSL_PARAM_construct_utf8_string(OSSL_ASYM_CIPHER_PARAM_MGF1_DIGEST, mgf1md, sizeof(mgf1md)); params[2] = OSSL_PARAM_construct_end(); if (!TEST_true(EVP_PKEY_CTX_get_params(key_ctx, params))) goto err; if (!TEST_str_eq(oaepmd, OSSL_DIGEST_NAME_SHA2_256) || !TEST_str_eq(mgf1md, OSSL_DIGEST_NAME_SHA1)) goto err; } ret = 1; err: EVP_PKEY_free(key); EVP_PKEY_CTX_free(key_ctx); return ret; } /* https://github.com/openssl/openssl/issues/21288 */ static int test_RSA_OAEP_set_null_label(void) { int ret = 0; EVP_PKEY *key = NULL; EVP_PKEY_CTX *key_ctx = NULL; if (!TEST_ptr(key = load_example_rsa_key()) || !TEST_ptr(key_ctx = EVP_PKEY_CTX_new_from_pkey(testctx, key, NULL)) || !TEST_true(EVP_PKEY_encrypt_init(key_ctx))) goto err; if (!TEST_true(EVP_PKEY_CTX_set_rsa_padding(key_ctx, RSA_PKCS1_OAEP_PADDING))) goto err; if (!TEST_true(EVP_PKEY_CTX_set0_rsa_oaep_label(key_ctx, OPENSSL_strdup("foo"), 0))) goto err; if (!TEST_true(EVP_PKEY_CTX_set0_rsa_oaep_label(key_ctx, NULL, 0))) goto err; ret = 1; err: EVP_PKEY_free(key); EVP_PKEY_CTX_free(key_ctx); return ret; } #ifndef OPENSSL_NO_DEPRECATED_3_0 static int test_RSA_legacy(void) { int ret = 0; BIGNUM *p = NULL; BIGNUM *q = NULL; BIGNUM *n = NULL; BIGNUM *e = NULL; BIGNUM *d = NULL; const EVP_MD *md = EVP_sha256(); EVP_MD_CTX *ctx = NULL; EVP_PKEY *pkey = NULL; RSA *rsa = NULL; if (nullprov != NULL) return TEST_skip("Test does not support a non-default library context"); if (!TEST_ptr(p = BN_dup(BN_value_one())) || !TEST_ptr(q = BN_dup(BN_value_one())) || !TEST_ptr(n = BN_dup(BN_value_one())) || !TEST_ptr(e = BN_dup(BN_value_one())) || !TEST_ptr(d = BN_dup(BN_value_one()))) goto err; if (!TEST_ptr(rsa = RSA_new()) || !TEST_ptr(pkey = EVP_PKEY_new()) || !TEST_ptr(ctx = EVP_MD_CTX_new())) goto err; if (!TEST_true(RSA_set0_factors(rsa, p, q))) goto err; p = NULL; q = NULL; if (!TEST_true(RSA_set0_key(rsa, n, e, d))) goto err; n = NULL; e = NULL; d = NULL; if (!TEST_true(EVP_PKEY_assign_RSA(pkey, rsa))) goto err; rsa = NULL; if (!TEST_true(EVP_DigestSignInit(ctx, NULL, md, NULL, pkey))) goto err; ret = 1; err: RSA_free(rsa); EVP_MD_CTX_free(ctx); EVP_PKEY_free(pkey); BN_free(p); BN_free(q); BN_free(n); BN_free(e); BN_free(d); return ret; } #endif #if !defined(OPENSSL_NO_CHACHA) && !defined(OPENSSL_NO_POLY1305) static int test_decrypt_null_chunks(void) { EVP_CIPHER_CTX* ctx = NULL; EVP_CIPHER *cipher = NULL; const unsigned char key[32] = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1 }; unsigned char iv[12] = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b }; unsigned char msg[] = "It was the best of times, it was the worst of times"; unsigned char ciphertext[80]; unsigned char plaintext[80]; /* We initialise tmp to a non zero value on purpose */ int ctlen, ptlen, tmp = 99; int ret = 0; const int enc_offset = 10, dec_offset = 20; if (!TEST_ptr(cipher = EVP_CIPHER_fetch(testctx, "ChaCha20-Poly1305", testpropq)) || !TEST_ptr(ctx = EVP_CIPHER_CTX_new()) || !TEST_true(EVP_EncryptInit_ex(ctx, cipher, NULL, key, iv)) || !TEST_true(EVP_EncryptUpdate(ctx, ciphertext, &ctlen, msg, enc_offset)) /* Deliberate add a zero length update */ || !TEST_true(EVP_EncryptUpdate(ctx, ciphertext + ctlen, &tmp, NULL, 0)) || !TEST_int_eq(tmp, 0) || !TEST_true(EVP_EncryptUpdate(ctx, ciphertext + ctlen, &tmp, msg + enc_offset, sizeof(msg) - enc_offset)) || !TEST_int_eq(ctlen += tmp, sizeof(msg)) || !TEST_true(EVP_EncryptFinal(ctx, ciphertext + ctlen, &tmp)) || !TEST_int_eq(tmp, 0)) goto err; /* Deliberately initialise tmp to a non zero value */ tmp = 99; if (!TEST_true(EVP_DecryptInit_ex(ctx, cipher, NULL, key, iv)) || !TEST_true(EVP_DecryptUpdate(ctx, plaintext, &ptlen, ciphertext, dec_offset)) /* * Deliberately add a zero length update. We also deliberately do * this at a different offset than for encryption. */ || !TEST_true(EVP_DecryptUpdate(ctx, plaintext + ptlen, &tmp, NULL, 0)) || !TEST_int_eq(tmp, 0) || !TEST_true(EVP_DecryptUpdate(ctx, plaintext + ptlen, &tmp, ciphertext + dec_offset, ctlen - dec_offset)) || !TEST_int_eq(ptlen += tmp, sizeof(msg)) || !TEST_true(EVP_DecryptFinal(ctx, plaintext + ptlen, &tmp)) || !TEST_int_eq(tmp, 0) || !TEST_mem_eq(msg, sizeof(msg), plaintext, ptlen)) goto err; ret = 1; err: EVP_CIPHER_CTX_free(ctx); EVP_CIPHER_free(cipher); return ret; } #endif /* !defined(OPENSSL_NO_CHACHA) && !defined(OPENSSL_NO_POLY1305) */ #ifndef OPENSSL_NO_DH /* * Test combinations of private, public, missing and private + public key * params to ensure they are all accepted */ static int test_DH_priv_pub(void) { return test_EVP_PKEY_ffc_priv_pub("DH"); } # ifndef OPENSSL_NO_DEPRECATED_3_0 static int test_EVP_PKEY_set1_DH(void) { DH *x942dh = NULL, *noqdh = NULL; EVP_PKEY *pkey1 = NULL, *pkey2 = NULL; int ret = 0; BIGNUM *p, *g = NULL; BIGNUM *pubkey = NULL; unsigned char pub[2048 / 8]; size_t len = 0; if (!TEST_ptr(p = BN_new()) || !TEST_ptr(g = BN_new()) || !TEST_ptr(pubkey = BN_new()) || !TEST_true(BN_set_word(p, 9999)) || !TEST_true(BN_set_word(g, 2)) || !TEST_true(BN_set_word(pubkey, 4321)) || !TEST_ptr(noqdh = DH_new()) || !TEST_true(DH_set0_pqg(noqdh, p, NULL, g)) || !TEST_true(DH_set0_key(noqdh, pubkey, NULL)) || !TEST_ptr(pubkey = BN_new()) || !TEST_true(BN_set_word(pubkey, 4321))) goto err; p = g = NULL; x942dh = DH_get_2048_256(); pkey1 = EVP_PKEY_new(); pkey2 = EVP_PKEY_new(); if (!TEST_ptr(x942dh) || !TEST_ptr(noqdh) || !TEST_ptr(pkey1) || !TEST_ptr(pkey2) || !TEST_true(DH_set0_key(x942dh, pubkey, NULL))) goto err; pubkey = NULL; if (!TEST_true(EVP_PKEY_set1_DH(pkey1, x942dh)) || !TEST_int_eq(EVP_PKEY_get_id(pkey1), EVP_PKEY_DHX)) goto err; if (!TEST_true(EVP_PKEY_get_bn_param(pkey1, OSSL_PKEY_PARAM_PUB_KEY, &pubkey)) || !TEST_ptr(pubkey)) goto err; if (!TEST_true(EVP_PKEY_set1_DH(pkey2, noqdh)) || !TEST_int_eq(EVP_PKEY_get_id(pkey2), EVP_PKEY_DH)) goto err; if (!TEST_true(EVP_PKEY_get_octet_string_param(pkey2, OSSL_PKEY_PARAM_PUB_KEY, pub, sizeof(pub), &len)) || !TEST_size_t_ne(len, 0)) goto err; ret = 1; err: BN_free(p); BN_free(g); BN_free(pubkey); EVP_PKEY_free(pkey1); EVP_PKEY_free(pkey2); DH_free(x942dh); DH_free(noqdh); return ret; } # endif /* !OPENSSL_NO_DEPRECATED_3_0 */ #endif /* !OPENSSL_NO_DH */ /* * We test what happens with an empty template. For the sake of this test, * the template must be ignored, and we know that's the case for RSA keys * (this might arguably be a misfeature, but that's what we currently do, * even in provider code, since that's how the legacy RSA implementation * does things) */ static int test_keygen_with_empty_template(int n) { EVP_PKEY_CTX *ctx = NULL; EVP_PKEY *pkey = NULL; EVP_PKEY *tkey = NULL; int ret = 0; if (nullprov != NULL) return TEST_skip("Test does not support a non-default library context"); switch (n) { case 0: /* We do test with no template at all as well */ if (!TEST_ptr(ctx = EVP_PKEY_CTX_new_id(EVP_PKEY_RSA, NULL))) goto err; break; case 1: /* Here we create an empty RSA key that serves as our template */ if (!TEST_ptr(tkey = EVP_PKEY_new()) || !TEST_true(EVP_PKEY_set_type(tkey, EVP_PKEY_RSA)) || !TEST_ptr(ctx = EVP_PKEY_CTX_new(tkey, NULL))) goto err; break; } if (!TEST_int_gt(EVP_PKEY_keygen_init(ctx), 0) || !TEST_int_gt(EVP_PKEY_keygen(ctx, &pkey), 0)) goto err; ret = 1; err: EVP_PKEY_CTX_free(ctx); EVP_PKEY_free(pkey); EVP_PKEY_free(tkey); return ret; } /* * Test that we fail if we attempt to use an algorithm that is not available * in the current library context (unless we are using an algorithm that * should be made available via legacy codepaths). * * 0: RSA * 1: SM2 */ static int test_pkey_ctx_fail_without_provider(int tst) { OSSL_LIB_CTX *tmpctx = OSSL_LIB_CTX_new(); OSSL_PROVIDER *tmpnullprov = NULL; EVP_PKEY_CTX *pctx = NULL; const char *keytype = NULL; int expect_null = 0; int ret = 0; if (!TEST_ptr(tmpctx)) goto err; tmpnullprov = OSSL_PROVIDER_load(tmpctx, "null"); if (!TEST_ptr(tmpnullprov)) goto err; /* * We check for certain algos in the null provider. * If an algo is expected to have a provider keymgmt, constructing an * EVP_PKEY_CTX is expected to fail (return NULL). * Otherwise, if it's expected to have legacy support, constructing an * EVP_PKEY_CTX is expected to succeed (return non-NULL). */ switch (tst) { case 0: keytype = "RSA"; expect_null = 1; break; case 1: keytype = "SM2"; expect_null = 1; #ifdef OPENSSL_NO_EC TEST_info("EC disable, skipping SM2 check..."); goto end; #endif #ifdef OPENSSL_NO_SM2 TEST_info("SM2 disable, skipping SM2 check..."); goto end; #endif break; default: TEST_error("No test for case %d", tst); goto err; } pctx = EVP_PKEY_CTX_new_from_name(tmpctx, keytype, ""); if (expect_null ? !TEST_ptr_null(pctx) : !TEST_ptr(pctx)) goto err; #if defined(OPENSSL_NO_EC) || defined(OPENSSL_NO_SM2) end: #endif ret = 1; err: EVP_PKEY_CTX_free(pctx); OSSL_PROVIDER_unload(tmpnullprov); OSSL_LIB_CTX_free(tmpctx); return ret; } static int test_rand_agglomeration(void) { EVP_RAND *rand; EVP_RAND_CTX *ctx; OSSL_PARAM params[3], *p = params; int res; unsigned int step = 7; static unsigned char seed[] = "It does not matter how slowly you go " "as long as you do not stop."; unsigned char out[sizeof(seed)]; if (!TEST_int_ne(sizeof(seed) % step, 0) || !TEST_ptr(rand = EVP_RAND_fetch(testctx, "TEST-RAND", testpropq))) return 0; ctx = EVP_RAND_CTX_new(rand, NULL); EVP_RAND_free(rand); if (!TEST_ptr(ctx)) return 0; memset(out, 0, sizeof(out)); *p++ = OSSL_PARAM_construct_octet_string(OSSL_RAND_PARAM_TEST_ENTROPY, seed, sizeof(seed)); *p++ = OSSL_PARAM_construct_uint(OSSL_RAND_PARAM_MAX_REQUEST, &step); *p = OSSL_PARAM_construct_end(); res = TEST_true(EVP_RAND_CTX_set_params(ctx, params)) && TEST_true(EVP_RAND_generate(ctx, out, sizeof(out), 0, 1, NULL, 0)) && TEST_mem_eq(seed, sizeof(seed), out, sizeof(out)); EVP_RAND_CTX_free(ctx); return res; } /* * Test that we correctly return the original or "running" IV after * an encryption operation. * Run multiple times for some different relevant algorithms/modes. */ static int test_evp_iv_aes(int idx) { int ret = 0; EVP_CIPHER_CTX *ctx = NULL; unsigned char key[16] = {0x4c, 0x43, 0xdb, 0xdd, 0x42, 0x73, 0x47, 0xd1, 0xe5, 0x62, 0x7d, 0xcd, 0x4d, 0x76, 0x4d, 0x57}; unsigned char init_iv[EVP_MAX_IV_LENGTH] = {0x57, 0x71, 0x7d, 0xad, 0xdb, 0x9b, 0x98, 0x82, 0x5a, 0x55, 0x91, 0x81, 0x42, 0xa8, 0x89, 0x34}; static const unsigned char msg[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 }; unsigned char ciphertext[32], oiv[16], iv[16]; unsigned char *ref_iv; unsigned char cbc_state[16] = {0x10, 0x2f, 0x05, 0xcc, 0xc2, 0x55, 0x72, 0xb9, 0x88, 0xe6, 0x4a, 0x17, 0x10, 0x74, 0x22, 0x5e}; unsigned char ofb_state[16] = {0x76, 0xe6, 0x66, 0x61, 0xd0, 0x8a, 0xe4, 0x64, 0xdd, 0x66, 0xbf, 0x00, 0xf0, 0xe3, 0x6f, 0xfd}; unsigned char cfb_state[16] = {0x77, 0xe4, 0x65, 0x65, 0xd5, 0x8c, 0xe3, 0x6c, 0xd4, 0x6c, 0xb4, 0x0c, 0xfd, 0xed, 0x60, 0xed}; unsigned char gcm_state[12] = {0x57, 0x71, 0x7d, 0xad, 0xdb, 0x9b, 0x98, 0x82, 0x5a, 0x55, 0x91, 0x81}; unsigned char ccm_state[7] = {0x57, 0x71, 0x7d, 0xad, 0xdb, 0x9b, 0x98}; #ifndef OPENSSL_NO_OCB unsigned char ocb_state[12] = {0x57, 0x71, 0x7d, 0xad, 0xdb, 0x9b, 0x98, 0x82, 0x5a, 0x55, 0x91, 0x81}; #endif int len = sizeof(ciphertext); size_t ivlen, ref_len; const EVP_CIPHER *type = NULL; int iv_reset = 0; if (nullprov != NULL && idx < 6) return TEST_skip("Test does not support a non-default library context"); switch (idx) { case 0: type = EVP_aes_128_cbc(); /* FALLTHROUGH */ case 6: type = (type != NULL) ? type : EVP_CIPHER_fetch(testctx, "aes-128-cbc", testpropq); ref_iv = cbc_state; ref_len = sizeof(cbc_state); iv_reset = 1; break; case 1: type = EVP_aes_128_ofb(); /* FALLTHROUGH */ case 7: type = (type != NULL) ? type : EVP_CIPHER_fetch(testctx, "aes-128-ofb", testpropq); ref_iv = ofb_state; ref_len = sizeof(ofb_state); iv_reset = 1; break; case 2: type = EVP_aes_128_cfb(); /* FALLTHROUGH */ case 8: type = (type != NULL) ? type : EVP_CIPHER_fetch(testctx, "aes-128-cfb", testpropq); ref_iv = cfb_state; ref_len = sizeof(cfb_state); iv_reset = 1; break; case 3: type = EVP_aes_128_gcm(); /* FALLTHROUGH */ case 9: type = (type != NULL) ? type : EVP_CIPHER_fetch(testctx, "aes-128-gcm", testpropq); ref_iv = gcm_state; ref_len = sizeof(gcm_state); break; case 4: type = EVP_aes_128_ccm(); /* FALLTHROUGH */ case 10: type = (type != NULL) ? type : EVP_CIPHER_fetch(testctx, "aes-128-ccm", testpropq); ref_iv = ccm_state; ref_len = sizeof(ccm_state); break; #ifdef OPENSSL_NO_OCB case 5: case 11: return 1; #else case 5: type = EVP_aes_128_ocb(); /* FALLTHROUGH */ case 11: type = (type != NULL) ? type : EVP_CIPHER_fetch(testctx, "aes-128-ocb", testpropq); ref_iv = ocb_state; ref_len = sizeof(ocb_state); break; #endif default: return 0; } if (!TEST_ptr(type) || !TEST_ptr((ctx = EVP_CIPHER_CTX_new())) || !TEST_true(EVP_EncryptInit_ex(ctx, type, NULL, key, init_iv)) || !TEST_true(EVP_EncryptUpdate(ctx, ciphertext, &len, msg, (int)sizeof(msg))) || !TEST_true(EVP_CIPHER_CTX_get_original_iv(ctx, oiv, sizeof(oiv))) || !TEST_true(EVP_CIPHER_CTX_get_updated_iv(ctx, iv, sizeof(iv))) || !TEST_true(EVP_EncryptFinal_ex(ctx, ciphertext, &len))) goto err; ivlen = EVP_CIPHER_CTX_get_iv_length(ctx); if (!TEST_mem_eq(init_iv, ivlen, oiv, ivlen) || !TEST_mem_eq(ref_iv, ref_len, iv, ivlen)) goto err; /* CBC, OFB, and CFB modes: the updated iv must be reset after reinit */ if (!TEST_true(EVP_EncryptInit_ex(ctx, NULL, NULL, NULL, NULL)) || !TEST_true(EVP_CIPHER_CTX_get_updated_iv(ctx, iv, sizeof(iv)))) goto err; if (iv_reset) { if (!TEST_mem_eq(init_iv, ivlen, iv, ivlen)) goto err; } else { if (!TEST_mem_eq(ref_iv, ivlen, iv, ivlen)) goto err; } ret = 1; err: EVP_CIPHER_CTX_free(ctx); if (idx >= 6) EVP_CIPHER_free((EVP_CIPHER *)type); return ret; } #ifndef OPENSSL_NO_DES static int test_evp_iv_des(int idx) { int ret = 0; EVP_CIPHER_CTX *ctx = NULL; static const unsigned char key[24] = { 0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef, 0xf1, 0xe0, 0xd3, 0xc2, 0xb5, 0xa4, 0x97, 0x86, 0xfe, 0xdc, 0xba, 0x98, 0x76, 0x54, 0x32, 0x10 }; static const unsigned char init_iv[8] = { 0xfe, 0xdc, 0xba, 0x98, 0x76, 0x54, 0x32, 0x10 }; static const unsigned char msg[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 }; unsigned char ciphertext[32], oiv[8], iv[8]; unsigned const char *ref_iv; static const unsigned char cbc_state_des[8] = { 0x4f, 0xa3, 0x85, 0xcd, 0x8b, 0xf3, 0x06, 0x2a }; static const unsigned char cbc_state_3des[8] = { 0x35, 0x27, 0x7d, 0x65, 0x6c, 0xfb, 0x50, 0xd9 }; static const unsigned char ofb_state_des[8] = { 0xa7, 0x0d, 0x1d, 0x45, 0xf9, 0x96, 0x3f, 0x2c }; static const unsigned char ofb_state_3des[8] = { 0xab, 0x16, 0x24, 0xbb, 0x5b, 0xac, 0xed, 0x5e }; static const unsigned char cfb_state_des[8] = { 0x91, 0xeb, 0x6d, 0x29, 0x4b, 0x08, 0xbd, 0x73 }; static const unsigned char cfb_state_3des[8] = { 0x34, 0xdd, 0xfb, 0x47, 0x33, 0x1c, 0x61, 0xf7 }; int len = sizeof(ciphertext); size_t ivlen, ref_len; EVP_CIPHER *type = NULL; if (lgcyprov == NULL && idx < 3) return TEST_skip("Test requires legacy provider to be loaded"); switch (idx) { case 0: type = EVP_CIPHER_fetch(testctx, "des-cbc", testpropq); ref_iv = cbc_state_des; ref_len = sizeof(cbc_state_des); break; case 1: type = EVP_CIPHER_fetch(testctx, "des-ofb", testpropq); ref_iv = ofb_state_des; ref_len = sizeof(ofb_state_des); break; case 2: type = EVP_CIPHER_fetch(testctx, "des-cfb", testpropq); ref_iv = cfb_state_des; ref_len = sizeof(cfb_state_des); break; case 3: type = EVP_CIPHER_fetch(testctx, "des-ede3-cbc", testpropq); ref_iv = cbc_state_3des; ref_len = sizeof(cbc_state_3des); break; case 4: type = EVP_CIPHER_fetch(testctx, "des-ede3-ofb", testpropq); ref_iv = ofb_state_3des; ref_len = sizeof(ofb_state_3des); break; case 5: type = EVP_CIPHER_fetch(testctx, "des-ede3-cfb", testpropq); ref_iv = cfb_state_3des; ref_len = sizeof(cfb_state_3des); break; default: return 0; } if (!TEST_ptr(type) || !TEST_ptr((ctx = EVP_CIPHER_CTX_new())) || !TEST_true(EVP_EncryptInit_ex(ctx, type, NULL, key, init_iv)) || !TEST_true(EVP_EncryptUpdate(ctx, ciphertext, &len, msg, (int)sizeof(msg))) || !TEST_true(EVP_CIPHER_CTX_get_original_iv(ctx, oiv, sizeof(oiv))) || !TEST_true(EVP_CIPHER_CTX_get_updated_iv(ctx, iv, sizeof(iv))) || !TEST_true(EVP_EncryptFinal_ex(ctx, ciphertext, &len))) goto err; ivlen = EVP_CIPHER_CTX_get_iv_length(ctx); if (!TEST_mem_eq(init_iv, ivlen, oiv, ivlen) || !TEST_mem_eq(ref_iv, ref_len, iv, ivlen)) goto err; if (!TEST_true(EVP_EncryptInit_ex(ctx, NULL, NULL, NULL, NULL)) || !TEST_true(EVP_CIPHER_CTX_get_updated_iv(ctx, iv, sizeof(iv)))) goto err; if (!TEST_mem_eq(init_iv, ivlen, iv, ivlen)) goto err; ret = 1; err: EVP_CIPHER_CTX_free(ctx); EVP_CIPHER_free(type); return ret; } #endif #ifndef OPENSSL_NO_BF static int test_evp_bf_default_keylen(int idx) { int ret = 0; static const char *algos[4] = { "bf-ecb", "bf-cbc", "bf-cfb", "bf-ofb" }; int ivlen[4] = { 0, 8, 8, 8 }; EVP_CIPHER *cipher = NULL; if (lgcyprov == NULL) return TEST_skip("Test requires legacy provider to be loaded"); if (!TEST_ptr(cipher = EVP_CIPHER_fetch(testctx, algos[idx], testpropq)) || !TEST_int_eq(EVP_CIPHER_get_key_length(cipher), 16) || !TEST_int_eq(EVP_CIPHER_get_iv_length(cipher), ivlen[idx])) goto err; ret = 1; err: EVP_CIPHER_free(cipher); return ret; } #endif #ifndef OPENSSL_NO_EC static int ecpub_nids[] = { NID_brainpoolP256r1, NID_X9_62_prime256v1, NID_secp384r1, NID_secp521r1, # ifndef OPENSSL_NO_EC2M NID_sect233k1, NID_sect233r1, NID_sect283r1, NID_sect409k1, NID_sect409r1, NID_sect571k1, NID_sect571r1, # endif NID_brainpoolP384r1, NID_brainpoolP512r1 }; static int test_ecpub(int idx) { int ret = 0, len, savelen; int nid; unsigned char buf[1024]; unsigned char *p; EVP_PKEY *pkey = NULL; EVP_PKEY_CTX *ctx = NULL; # ifndef OPENSSL_NO_DEPRECATED_3_0 const unsigned char *q; EVP_PKEY *pkey2 = NULL; EC_KEY *ec = NULL; # endif if (nullprov != NULL) return TEST_skip("Test does not support a non-default library context"); nid = ecpub_nids[idx]; ctx = EVP_PKEY_CTX_new_id(EVP_PKEY_EC, NULL); if (!TEST_ptr(ctx) || !TEST_int_gt(EVP_PKEY_keygen_init(ctx), 0) || !TEST_int_gt(EVP_PKEY_CTX_set_ec_paramgen_curve_nid(ctx, nid), 0) || !TEST_true(EVP_PKEY_keygen(ctx, &pkey))) goto done; len = i2d_PublicKey(pkey, NULL); savelen = len; if (!TEST_int_ge(len, 1) || !TEST_int_lt(len, 1024)) goto done; p = buf; len = i2d_PublicKey(pkey, &p); if (!TEST_int_ge(len, 1) || !TEST_int_eq(len, savelen)) goto done; # ifndef OPENSSL_NO_DEPRECATED_3_0 /* Now try to decode the just-created DER. */ q = buf; if (!TEST_ptr((pkey2 = EVP_PKEY_new())) || !TEST_ptr((ec = EC_KEY_new_by_curve_name(nid))) || !TEST_true(EVP_PKEY_assign_EC_KEY(pkey2, ec))) goto done; /* EC_KEY ownership transferred */ ec = NULL; if (!TEST_ptr(d2i_PublicKey(EVP_PKEY_EC, &pkey2, &q, savelen))) goto done; /* The keys should match. */ if (!TEST_int_eq(EVP_PKEY_eq(pkey, pkey2), 1)) goto done; # endif ret = 1; done: EVP_PKEY_CTX_free(ctx); EVP_PKEY_free(pkey); # ifndef OPENSSL_NO_DEPRECATED_3_0 EVP_PKEY_free(pkey2); EC_KEY_free(ec); # endif return ret; } #endif static int test_EVP_rsa_pss_with_keygen_bits(void) { int ret = 0; EVP_PKEY_CTX *ctx = NULL; EVP_PKEY *pkey = NULL; EVP_MD *md; md = EVP_MD_fetch(testctx, "sha256", testpropq); ret = TEST_ptr(md) && TEST_ptr((ctx = EVP_PKEY_CTX_new_from_name(testctx, "RSA-PSS", testpropq))) && TEST_int_gt(EVP_PKEY_keygen_init(ctx), 0) && TEST_int_gt(EVP_PKEY_CTX_set_rsa_keygen_bits(ctx, 512), 0) && TEST_int_gt(EVP_PKEY_CTX_set_rsa_pss_keygen_md(ctx, md), 0) && TEST_true(EVP_PKEY_keygen(ctx, &pkey)); EVP_MD_free(md); EVP_PKEY_free(pkey); EVP_PKEY_CTX_free(ctx); return ret; } static int test_EVP_rsa_pss_set_saltlen(void) { int ret = 0; EVP_PKEY *pkey = NULL; EVP_PKEY_CTX *pkey_ctx = NULL; EVP_MD *sha256 = NULL; EVP_MD_CTX *sha256_ctx = NULL; int saltlen = 9999; /* buggy EVP_PKEY_CTX_get_rsa_pss_saltlen() didn't update this */ const int test_value = 32; ret = TEST_ptr(pkey = load_example_rsa_key()) && TEST_ptr(sha256 = EVP_MD_fetch(testctx, "sha256", NULL)) && TEST_ptr(sha256_ctx = EVP_MD_CTX_new()) && TEST_true(EVP_DigestSignInit(sha256_ctx, &pkey_ctx, sha256, NULL, pkey)) && TEST_true(EVP_PKEY_CTX_set_rsa_padding(pkey_ctx, RSA_PKCS1_PSS_PADDING)) && TEST_int_gt(EVP_PKEY_CTX_set_rsa_pss_saltlen(pkey_ctx, test_value), 0) && TEST_int_gt(EVP_PKEY_CTX_get_rsa_pss_saltlen(pkey_ctx, &saltlen), 0) && TEST_int_eq(saltlen, test_value); EVP_MD_CTX_free(sha256_ctx); EVP_PKEY_free(pkey); EVP_MD_free(sha256); return ret; } static int success = 1; static void md_names(const char *name, void *vctx) { OSSL_LIB_CTX *ctx = (OSSL_LIB_CTX *)vctx; /* Force a namemap update */ EVP_CIPHER *aes128 = EVP_CIPHER_fetch(ctx, "AES-128-CBC", NULL); if (!TEST_ptr(aes128)) success = 0; EVP_CIPHER_free(aes128); } /* * Test that changing the namemap in a user callback works in a names_do_all * function. */ static int test_names_do_all(void) { /* We use a custom libctx so that we know the state of the namemap */ OSSL_LIB_CTX *ctx = OSSL_LIB_CTX_new(); EVP_MD *sha256 = NULL; int testresult = 0; if (!TEST_ptr(ctx)) goto err; sha256 = EVP_MD_fetch(ctx, "SHA2-256", NULL); if (!TEST_ptr(sha256)) goto err; /* * We loop through all the names for a given digest. This should still work * even if the namemap changes part way through. */ if (!TEST_true(EVP_MD_names_do_all(sha256, md_names, ctx))) goto err; if (!TEST_true(success)) goto err; testresult = 1; err: EVP_MD_free(sha256); OSSL_LIB_CTX_free(ctx); return testresult; } typedef struct { const char *cipher; const unsigned char *key; const unsigned char *iv; const unsigned char *input; const unsigned char *expected; const unsigned char *tag; size_t ivlen; /* 0 if we do not need to set a specific IV len */ size_t inlen; size_t expectedlen; size_t taglen; int keyfirst; int initenc; int finalenc; } EVP_INIT_TEST_st; static const EVP_INIT_TEST_st evp_init_tests[] = { { "aes-128-cfb", kCFBDefaultKey, iCFBIV, cfbPlaintext, cfbCiphertext, NULL, 0, sizeof(cfbPlaintext), sizeof(cfbCiphertext), 0, 1, 0, 1 }, { "aes-256-gcm", kGCMDefaultKey, iGCMDefaultIV, gcmDefaultPlaintext, gcmDefaultCiphertext, gcmDefaultTag, sizeof(iGCMDefaultIV), sizeof(gcmDefaultPlaintext), sizeof(gcmDefaultCiphertext), sizeof(gcmDefaultTag), 1, 0, 1 }, { "aes-128-cfb", kCFBDefaultKey, iCFBIV, cfbPlaintext, cfbCiphertext, NULL, 0, sizeof(cfbPlaintext), sizeof(cfbCiphertext), 0, 0, 0, 1 }, { "aes-256-gcm", kGCMDefaultKey, iGCMDefaultIV, gcmDefaultPlaintext, gcmDefaultCiphertext, gcmDefaultTag, sizeof(iGCMDefaultIV), sizeof(gcmDefaultPlaintext), sizeof(gcmDefaultCiphertext), sizeof(gcmDefaultTag), 0, 0, 1 }, { "aes-128-cfb", kCFBDefaultKey, iCFBIV, cfbCiphertext, cfbPlaintext, NULL, 0, sizeof(cfbCiphertext), sizeof(cfbPlaintext), 0, 1, 1, 0 }, { "aes-256-gcm", kGCMDefaultKey, iGCMDefaultIV, gcmDefaultCiphertext, gcmDefaultPlaintext, gcmDefaultTag, sizeof(iGCMDefaultIV), sizeof(gcmDefaultCiphertext), sizeof(gcmDefaultPlaintext), sizeof(gcmDefaultTag), 1, 1, 0 }, { "aes-128-cfb", kCFBDefaultKey, iCFBIV, cfbCiphertext, cfbPlaintext, NULL, 0, sizeof(cfbCiphertext), sizeof(cfbPlaintext), 0, 0, 1, 0 }, { "aes-256-gcm", kGCMDefaultKey, iGCMDefaultIV, gcmDefaultCiphertext, gcmDefaultPlaintext, gcmDefaultTag, sizeof(iGCMDefaultIV), sizeof(gcmDefaultCiphertext), sizeof(gcmDefaultPlaintext), sizeof(gcmDefaultTag), 0, 1, 0 } }; /* use same key, iv and plaintext for cfb and ofb */ static const EVP_INIT_TEST_st evp_reinit_tests[] = { { "aes-128-cfb", kCFBDefaultKey, iCFBIV, cfbPlaintext_partial, cfbCiphertext_partial, NULL, 0, sizeof(cfbPlaintext_partial), sizeof(cfbCiphertext_partial), 0, 0, 1, 0 }, { "aes-128-cfb", kCFBDefaultKey, iCFBIV, cfbCiphertext_partial, cfbPlaintext_partial, NULL, 0, sizeof(cfbCiphertext_partial), sizeof(cfbPlaintext_partial), 0, 0, 0, 0 }, { "aes-128-ofb", kCFBDefaultKey, iCFBIV, cfbPlaintext_partial, ofbCiphertext_partial, NULL, 0, sizeof(cfbPlaintext_partial), sizeof(ofbCiphertext_partial), 0, 0, 1, 0 }, { "aes-128-ofb", kCFBDefaultKey, iCFBIV, ofbCiphertext_partial, cfbPlaintext_partial, NULL, 0, sizeof(ofbCiphertext_partial), sizeof(cfbPlaintext_partial), 0, 0, 0, 0 }, }; static int evp_init_seq_set_iv(EVP_CIPHER_CTX *ctx, const EVP_INIT_TEST_st *t) { int res = 0; if (t->ivlen != 0) { if (!TEST_int_gt(EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_IVLEN, t->ivlen, NULL), 0)) goto err; } if (!TEST_true(EVP_CipherInit_ex(ctx, NULL, NULL, NULL, t->iv, -1))) goto err; res = 1; err: return res; } /* * Test step-wise cipher initialization via EVP_CipherInit_ex where the * arguments are given one at a time and a final adjustment to the enc * parameter sets the correct operation. */ static int test_evp_init_seq(int idx) { int outlen1, outlen2; int testresult = 0; unsigned char outbuf[1024]; unsigned char tag[16]; const EVP_INIT_TEST_st *t = &evp_init_tests[idx]; EVP_CIPHER_CTX *ctx = NULL; EVP_CIPHER *type = NULL; size_t taglen = sizeof(tag); char *errmsg = NULL; ctx = EVP_CIPHER_CTX_new(); if (ctx == NULL) { errmsg = "CTX_ALLOC"; goto err; } if (!TEST_ptr(type = EVP_CIPHER_fetch(testctx, t->cipher, testpropq))) { errmsg = "CIPHER_FETCH"; goto err; } if (!TEST_true(EVP_CipherInit_ex(ctx, type, NULL, NULL, NULL, t->initenc))) { errmsg = "EMPTY_ENC_INIT"; goto err; } if (!TEST_true(EVP_CIPHER_CTX_set_padding(ctx, 0))) { errmsg = "PADDING"; goto err; } if (t->keyfirst && !TEST_true(EVP_CipherInit_ex(ctx, NULL, NULL, t->key, NULL, -1))) { errmsg = "KEY_INIT (before iv)"; goto err; } if (!evp_init_seq_set_iv(ctx, t)) { errmsg = "IV_INIT"; goto err; } if (t->keyfirst == 0 && !TEST_true(EVP_CipherInit_ex(ctx, NULL, NULL, t->key, NULL, -1))) { errmsg = "KEY_INIT (after iv)"; goto err; } if (!TEST_true(EVP_CipherInit_ex(ctx, NULL, NULL, NULL, NULL, t->finalenc))) { errmsg = "FINAL_ENC_INIT"; goto err; } if (!TEST_true(EVP_CipherUpdate(ctx, outbuf, &outlen1, t->input, t->inlen))) { errmsg = "CIPHER_UPDATE"; goto err; } if (t->finalenc == 0 && t->tag != NULL) { /* Set expected tag */ if (!TEST_int_gt(EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_SET_TAG, t->taglen, (void *)t->tag), 0)) { errmsg = "SET_TAG"; goto err; } } if (!TEST_true(EVP_CipherFinal_ex(ctx, outbuf + outlen1, &outlen2))) { errmsg = "CIPHER_FINAL"; goto err; } if (!TEST_mem_eq(t->expected, t->expectedlen, outbuf, outlen1 + outlen2)) { errmsg = "WRONG_RESULT"; goto err; } if (t->finalenc != 0 && t->tag != NULL) { if (!TEST_int_gt(EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_GET_TAG, taglen, tag), 0)) { errmsg = "GET_TAG"; goto err; } if (!TEST_mem_eq(t->tag, t->taglen, tag, taglen)) { errmsg = "TAG_ERROR"; goto err; } } testresult = 1; err: if (errmsg != NULL) TEST_info("evp_init_test %d: %s", idx, errmsg); EVP_CIPHER_CTX_free(ctx); EVP_CIPHER_free(type); return testresult; } /* * Test re-initialization of cipher context without changing key or iv. * The result of both iteration should be the same. */ static int test_evp_reinit_seq(int idx) { int outlen1, outlen2, outlen_final; int testresult = 0; unsigned char outbuf1[1024]; unsigned char outbuf2[1024]; const EVP_INIT_TEST_st *t = &evp_reinit_tests[idx]; EVP_CIPHER_CTX *ctx = NULL; EVP_CIPHER *type = NULL; if (!TEST_ptr(ctx = EVP_CIPHER_CTX_new()) || !TEST_ptr(type = EVP_CIPHER_fetch(testctx, t->cipher, testpropq)) /* setup cipher context */ || !TEST_true(EVP_CipherInit_ex2(ctx, type, t->key, t->iv, t->initenc, NULL)) /* first iteration */ || !TEST_true(EVP_CipherUpdate(ctx, outbuf1, &outlen1, t->input, t->inlen)) || !TEST_true(EVP_CipherFinal_ex(ctx, outbuf1, &outlen_final)) /* check test results iteration 1 */ || !TEST_mem_eq(t->expected, t->expectedlen, outbuf1, outlen1 + outlen_final) /* now re-init the context (same cipher, key and iv) */ || !TEST_true(EVP_CipherInit_ex2(ctx, NULL, NULL, NULL, -1, NULL)) /* second iteration */ || !TEST_true(EVP_CipherUpdate(ctx, outbuf2, &outlen2, t->input, t->inlen)) || !TEST_true(EVP_CipherFinal_ex(ctx, outbuf2, &outlen_final)) /* check test results iteration 2 */ || !TEST_mem_eq(t->expected, t->expectedlen, outbuf2, outlen2 + outlen_final)) goto err; testresult = 1; err: EVP_CIPHER_CTX_free(ctx); EVP_CIPHER_free(type); return testresult; } typedef struct { const unsigned char *input; const unsigned char *expected; size_t inlen; size_t expectedlen; int enc; } EVP_RESET_TEST_st; static const EVP_RESET_TEST_st evp_reset_tests[] = { { cfbPlaintext, cfbCiphertext, sizeof(cfbPlaintext), sizeof(cfbCiphertext), 1 }, { cfbCiphertext, cfbPlaintext, sizeof(cfbCiphertext), sizeof(cfbPlaintext), 0 } }; /* * Test a reset of a cipher via EVP_CipherInit_ex after the cipher has already * been used. */ static int test_evp_reset(int idx) { const EVP_RESET_TEST_st *t = &evp_reset_tests[idx]; int outlen1, outlen2; int testresult = 0; unsigned char outbuf[1024]; EVP_CIPHER_CTX *ctx = NULL; EVP_CIPHER *type = NULL; char *errmsg = NULL; if (!TEST_ptr(ctx = EVP_CIPHER_CTX_new())) { errmsg = "CTX_ALLOC"; goto err; } if (!TEST_ptr(type = EVP_CIPHER_fetch(testctx, "aes-128-cfb", testpropq))) { errmsg = "CIPHER_FETCH"; goto err; } if (!TEST_true(EVP_CipherInit_ex(ctx, type, NULL, kCFBDefaultKey, iCFBIV, t->enc))) { errmsg = "CIPHER_INIT"; goto err; } if (!TEST_true(EVP_CIPHER_CTX_set_padding(ctx, 0))) { errmsg = "PADDING"; goto err; } if (!TEST_true(EVP_CipherUpdate(ctx, outbuf, &outlen1, t->input, t->inlen))) { errmsg = "CIPHER_UPDATE"; goto err; } if (!TEST_true(EVP_CipherFinal_ex(ctx, outbuf + outlen1, &outlen2))) { errmsg = "CIPHER_FINAL"; goto err; } if (!TEST_mem_eq(t->expected, t->expectedlen, outbuf, outlen1 + outlen2)) { errmsg = "WRONG_RESULT"; goto err; } if (!TEST_true(EVP_CipherInit_ex(ctx, NULL, NULL, NULL, NULL, -1))) { errmsg = "CIPHER_REINIT"; goto err; } if (!TEST_true(EVP_CipherUpdate(ctx, outbuf, &outlen1, t->input, t->inlen))) { errmsg = "CIPHER_UPDATE (reinit)"; goto err; } if (!TEST_true(EVP_CipherFinal_ex(ctx, outbuf + outlen1, &outlen2))) { errmsg = "CIPHER_FINAL (reinit)"; goto err; } if (!TEST_mem_eq(t->expected, t->expectedlen, outbuf, outlen1 + outlen2)) { errmsg = "WRONG_RESULT (reinit)"; goto err; } testresult = 1; err: if (errmsg != NULL) TEST_info("test_evp_reset %d: %s", idx, errmsg); EVP_CIPHER_CTX_free(ctx); EVP_CIPHER_free(type); return testresult; } typedef struct { const char *cipher; int enc; } EVP_UPDATED_IV_TEST_st; static const EVP_UPDATED_IV_TEST_st evp_updated_iv_tests[] = { { "aes-128-cfb", 1 }, { "aes-128-cfb", 0 }, { "aes-128-cfb1", 1 }, { "aes-128-cfb1", 0 }, { "aes-128-cfb8", 1 }, { "aes-128-cfb8", 0 }, { "aes-128-ofb", 1 }, { "aes-128-ofb", 0 }, { "aes-128-ctr", 1 }, { "aes-128-ctr", 0 }, { "aes-128-cbc", 1 }, { "aes-128-cbc", 0 } }; /* * Test that the IV in the context is updated during a crypto operation for CFB * and OFB. */ static int test_evp_updated_iv(int idx) { const EVP_UPDATED_IV_TEST_st *t = &evp_updated_iv_tests[idx]; int outlen1, outlen2; int testresult = 0; unsigned char outbuf[1024]; EVP_CIPHER_CTX *ctx = NULL; EVP_CIPHER *type = NULL; unsigned char updated_iv[EVP_MAX_IV_LENGTH]; int iv_len; char *errmsg = NULL; if (!TEST_ptr(ctx = EVP_CIPHER_CTX_new())) { errmsg = "CTX_ALLOC"; goto err; } if ((type = EVP_CIPHER_fetch(testctx, t->cipher, testpropq)) == NULL) { TEST_info("cipher %s not supported, skipping", t->cipher); goto ok; } if (!TEST_true(EVP_CipherInit_ex(ctx, type, NULL, kCFBDefaultKey, iCFBIV, t->enc))) { errmsg = "CIPHER_INIT"; goto err; } if (!TEST_true(EVP_CIPHER_CTX_set_padding(ctx, 0))) { errmsg = "PADDING"; goto err; } if (!TEST_true(EVP_CipherUpdate(ctx, outbuf, &outlen1, cfbPlaintext, sizeof(cfbPlaintext)))) { errmsg = "CIPHER_UPDATE"; goto err; } if (!TEST_true(EVP_CIPHER_CTX_get_updated_iv(ctx, updated_iv, sizeof(updated_iv)))) { errmsg = "CIPHER_CTX_GET_UPDATED_IV"; goto err; } if (!TEST_true(iv_len = EVP_CIPHER_CTX_get_iv_length(ctx))) { errmsg = "CIPHER_CTX_GET_IV_LEN"; goto err; } if (!TEST_mem_ne(iCFBIV, sizeof(iCFBIV), updated_iv, iv_len)) { errmsg = "IV_NOT_UPDATED"; goto err; } if (!TEST_true(EVP_CipherFinal_ex(ctx, outbuf + outlen1, &outlen2))) { errmsg = "CIPHER_FINAL"; goto err; } ok: testresult = 1; err: if (errmsg != NULL) TEST_info("test_evp_updated_iv %d: %s", idx, errmsg); EVP_CIPHER_CTX_free(ctx); EVP_CIPHER_free(type); return testresult; } typedef struct { const unsigned char *iv1; const unsigned char *iv2; const unsigned char *expected1; const unsigned char *expected2; const unsigned char *tag1; const unsigned char *tag2; size_t ivlen1; size_t ivlen2; size_t expectedlen1; size_t expectedlen2; } TEST_GCM_IV_REINIT_st; static const TEST_GCM_IV_REINIT_st gcm_reinit_tests[] = { { iGCMResetIV1, iGCMResetIV2, gcmResetCiphertext1, gcmResetCiphertext2, gcmResetTag1, gcmResetTag2, sizeof(iGCMResetIV1), sizeof(iGCMResetIV2), sizeof(gcmResetCiphertext1), sizeof(gcmResetCiphertext2) }, { iGCMResetIV2, iGCMResetIV1, gcmResetCiphertext2, gcmResetCiphertext1, gcmResetTag2, gcmResetTag1, sizeof(iGCMResetIV2), sizeof(iGCMResetIV1), sizeof(gcmResetCiphertext2), sizeof(gcmResetCiphertext1) } }; static int test_gcm_reinit(int idx) { int outlen1, outlen2, outlen3; int testresult = 0; unsigned char outbuf[1024]; unsigned char tag[16]; const TEST_GCM_IV_REINIT_st *t = &gcm_reinit_tests[idx]; EVP_CIPHER_CTX *ctx = NULL; EVP_CIPHER *type = NULL; size_t taglen = sizeof(tag); char *errmsg = NULL; if (!TEST_ptr(ctx = EVP_CIPHER_CTX_new())) { errmsg = "CTX_ALLOC"; goto err; } if (!TEST_ptr(type = EVP_CIPHER_fetch(testctx, "aes-256-gcm", testpropq))) { errmsg = "CIPHER_FETCH"; goto err; } if (!TEST_true(EVP_CipherInit_ex(ctx, type, NULL, NULL, NULL, 1))) { errmsg = "ENC_INIT"; goto err; } if (!TEST_int_gt(EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_IVLEN, t->ivlen1, NULL), 0)) { errmsg = "SET_IVLEN1"; goto err; } if (!TEST_true(EVP_CipherInit_ex(ctx, NULL, NULL, kGCMResetKey, t->iv1, 1))) { errmsg = "SET_IV1"; goto err; } if (!TEST_true(EVP_CipherUpdate(ctx, NULL, &outlen3, gcmAAD, sizeof(gcmAAD)))) { errmsg = "AAD1"; goto err; } EVP_CIPHER_CTX_set_padding(ctx, 0); if (!TEST_true(EVP_CipherUpdate(ctx, outbuf, &outlen1, gcmResetPlaintext, sizeof(gcmResetPlaintext)))) { errmsg = "CIPHER_UPDATE1"; goto err; } if (!TEST_true(EVP_CipherFinal_ex(ctx, outbuf + outlen1, &outlen2))) { errmsg = "CIPHER_FINAL1"; goto err; } if (!TEST_mem_eq(t->expected1, t->expectedlen1, outbuf, outlen1 + outlen2)) { errmsg = "WRONG_RESULT1"; goto err; } if (!TEST_int_gt(EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_GET_TAG, taglen, tag), 0)) { errmsg = "GET_TAG1"; goto err; } if (!TEST_mem_eq(t->tag1, taglen, tag, taglen)) { errmsg = "TAG_ERROR1"; goto err; } /* Now reinit */ if (!TEST_int_gt(EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_IVLEN, t->ivlen2, NULL), 0)) { errmsg = "SET_IVLEN2"; goto err; } if (!TEST_true(EVP_CipherInit_ex(ctx, NULL, NULL, NULL, t->iv2, -1))) { errmsg = "SET_IV2"; goto err; } if (!TEST_true(EVP_CipherUpdate(ctx, NULL, &outlen3, gcmAAD, sizeof(gcmAAD)))) { errmsg = "AAD2"; goto err; } if (!TEST_true(EVP_CipherUpdate(ctx, outbuf, &outlen1, gcmResetPlaintext, sizeof(gcmResetPlaintext)))) { errmsg = "CIPHER_UPDATE2"; goto err; } if (!TEST_true(EVP_CipherFinal_ex(ctx, outbuf + outlen1, &outlen2))) { errmsg = "CIPHER_FINAL2"; goto err; } if (!TEST_mem_eq(t->expected2, t->expectedlen2, outbuf, outlen1 + outlen2)) { errmsg = "WRONG_RESULT2"; goto err; } if (!TEST_int_gt(EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_GET_TAG, taglen, tag), 0)) { errmsg = "GET_TAG2"; goto err; } if (!TEST_mem_eq(t->tag2, taglen, tag, taglen)) { errmsg = "TAG_ERROR2"; goto err; } testresult = 1; err: if (errmsg != NULL) TEST_info("evp_init_test %d: %s", idx, errmsg); EVP_CIPHER_CTX_free(ctx); EVP_CIPHER_free(type); return testresult; } static const char *ivlen_change_ciphers[] = { "AES-256-GCM", #ifndef OPENSSL_NO_OCB "AES-256-OCB", #endif "AES-256-CCM" }; /* Negative test for ivlen change after iv being set */ static int test_ivlen_change(int idx) { int outlen; int res = 0; unsigned char outbuf[1024]; static const unsigned char iv[] = { 0x57, 0x71, 0x7d, 0xad, 0xdb, 0x9b, 0x98, 0x82, 0x5a, 0x55, 0x91, 0x81, 0x42, 0xa8, 0x89, 0x34 }; EVP_CIPHER_CTX *ctx = NULL; EVP_CIPHER *ciph = NULL; OSSL_PARAM params[] = { OSSL_PARAM_END, OSSL_PARAM_END }; size_t ivlen = 13; /* non-default IV length */ if (!TEST_ptr(ctx = EVP_CIPHER_CTX_new())) goto err; if (!TEST_ptr(ciph = EVP_CIPHER_fetch(testctx, ivlen_change_ciphers[idx], testpropq))) goto err; if (!TEST_true(EVP_CipherInit_ex(ctx, ciph, NULL, kGCMDefaultKey, iv, 1))) goto err; if (!TEST_true(EVP_CipherUpdate(ctx, outbuf, &outlen, gcmDefaultPlaintext, sizeof(gcmDefaultPlaintext)))) goto err; params[0] = OSSL_PARAM_construct_size_t(OSSL_CIPHER_PARAM_AEAD_IVLEN, &ivlen); if (!TEST_true(EVP_CIPHER_CTX_set_params(ctx, params))) goto err; ERR_set_mark(); if (!TEST_false(EVP_CipherUpdate(ctx, outbuf, &outlen, gcmDefaultPlaintext, sizeof(gcmDefaultPlaintext)))) { ERR_clear_last_mark(); goto err; } ERR_pop_to_mark(); res = 1; err: EVP_CIPHER_CTX_free(ctx); EVP_CIPHER_free(ciph); return res; } static const char *keylen_change_ciphers[] = { #ifndef OPENSSL_NO_BF "BF-ECB", #endif #ifndef OPENSSL_NO_CAST "CAST5-ECB", #endif #ifndef OPENSSL_NO_RC2 "RC2-ECB", #endif #ifndef OPENSSL_NO_RC4 "RC4", #endif #ifndef OPENSSL_NO_RC5 "RC5-ECB", #endif NULL }; /* Negative test for keylen change after key was set */ static int test_keylen_change(int idx) { int outlen; int res = 0; unsigned char outbuf[1024]; static const unsigned char key[] = { 0x57, 0x71, 0x7d, 0xad, 0xdb, 0x9b, 0x98, 0x82, 0x5a, 0x55, 0x91, 0x81, 0x42, 0xa8, 0x89, 0x34 }; EVP_CIPHER_CTX *ctx = NULL; EVP_CIPHER *ciph = NULL; OSSL_PARAM params[] = { OSSL_PARAM_END, OSSL_PARAM_END }; size_t keylen = 12; /* non-default key length */ if (lgcyprov == NULL) return TEST_skip("Test requires legacy provider to be loaded"); if (!TEST_ptr(ctx = EVP_CIPHER_CTX_new())) goto err; if (!TEST_ptr(ciph = EVP_CIPHER_fetch(testctx, keylen_change_ciphers[idx], testpropq))) goto err; if (!TEST_true(EVP_CipherInit_ex(ctx, ciph, NULL, key, NULL, 1))) goto err; if (!TEST_true(EVP_CipherUpdate(ctx, outbuf, &outlen, gcmDefaultPlaintext, sizeof(gcmDefaultPlaintext)))) goto err; params[0] = OSSL_PARAM_construct_size_t(OSSL_CIPHER_PARAM_KEYLEN, &keylen); if (!TEST_true(EVP_CIPHER_CTX_set_params(ctx, params))) goto err; ERR_set_mark(); if (!TEST_false(EVP_CipherUpdate(ctx, outbuf, &outlen, gcmDefaultPlaintext, sizeof(gcmDefaultPlaintext)))) { ERR_clear_last_mark(); goto err; } ERR_pop_to_mark(); res = 1; err: EVP_CIPHER_CTX_free(ctx); EVP_CIPHER_free(ciph); return res; } #ifndef OPENSSL_NO_DEPRECATED_3_0 static EVP_PKEY_METHOD *custom_pmeth = NULL; static const EVP_PKEY_METHOD *orig_pmeth = NULL; # define EVP_PKEY_CTRL_MY_COMMAND 9999 static int custom_pmeth_init(EVP_PKEY_CTX *ctx) { int (*pinit)(EVP_PKEY_CTX *ctx); EVP_PKEY_meth_get_init(orig_pmeth, &pinit); return pinit(ctx); } static void custom_pmeth_cleanup(EVP_PKEY_CTX *ctx) { void (*pcleanup)(EVP_PKEY_CTX *ctx); EVP_PKEY_meth_get_cleanup(orig_pmeth, &pcleanup); pcleanup(ctx); } static int custom_pmeth_sign(EVP_PKEY_CTX *ctx, unsigned char *out, size_t *outlen, const unsigned char *in, size_t inlen) { int (*psign)(EVP_PKEY_CTX *ctx, unsigned char *sig, size_t *siglen, const unsigned char *tbs, size_t tbslen); EVP_PKEY_meth_get_sign(orig_pmeth, NULL, &psign); return psign(ctx, out, outlen, in, inlen); } static int custom_pmeth_digestsign(EVP_MD_CTX *ctx, unsigned char *sig, size_t *siglen, const unsigned char *tbs, size_t tbslen) { int (*pdigestsign)(EVP_MD_CTX *ctx, unsigned char *sig, size_t *siglen, const unsigned char *tbs, size_t tbslen); EVP_PKEY_meth_get_digestsign(orig_pmeth, &pdigestsign); return pdigestsign(ctx, sig, siglen, tbs, tbslen); } static int custom_pmeth_derive(EVP_PKEY_CTX *ctx, unsigned char *key, size_t *keylen) { int (*pderive)(EVP_PKEY_CTX *ctx, unsigned char *key, size_t *keylen); EVP_PKEY_meth_get_derive(orig_pmeth, NULL, &pderive); return pderive(ctx, key, keylen); } static int custom_pmeth_copy(EVP_PKEY_CTX *dst, const EVP_PKEY_CTX *src) { int (*pcopy)(EVP_PKEY_CTX *dst, const EVP_PKEY_CTX *src); EVP_PKEY_meth_get_copy(orig_pmeth, &pcopy); return pcopy(dst, src); } static int ctrl_called; static int custom_pmeth_ctrl(EVP_PKEY_CTX *ctx, int type, int p1, void *p2) { int (*pctrl)(EVP_PKEY_CTX *ctx, int type, int p1, void *p2); EVP_PKEY_meth_get_ctrl(orig_pmeth, &pctrl, NULL); if (type == EVP_PKEY_CTRL_MY_COMMAND) { ctrl_called = 1; return 1; } return pctrl(ctx, type, p1, p2); } static int test_custom_pmeth(int idx) { EVP_PKEY_CTX *pctx = NULL; EVP_MD_CTX *ctx = NULL; EVP_PKEY *pkey = NULL; int id, orig_id, orig_flags; int testresult = 0; size_t reslen; unsigned char *res = NULL; unsigned char msg[] = { 'H', 'e', 'l', 'l', 'o' }; const EVP_MD *md = EVP_sha256(); int doderive = 0; ctrl_called = 0; /* We call deprecated APIs so this test doesn't support a custom libctx */ if (testctx != NULL) return 1; switch (idx) { case 0: case 6: id = EVP_PKEY_RSA; pkey = load_example_rsa_key(); break; case 1: case 7: # ifndef OPENSSL_NO_DSA id = EVP_PKEY_DSA; pkey = load_example_dsa_key(); break; # else return 1; # endif case 2: case 8: # ifndef OPENSSL_NO_EC id = EVP_PKEY_EC; pkey = load_example_ec_key(); break; # else return 1; # endif case 3: case 9: # ifndef OPENSSL_NO_ECX id = EVP_PKEY_ED25519; md = NULL; pkey = load_example_ed25519_key(); break; # else return 1; # endif case 4: case 10: # ifndef OPENSSL_NO_DH id = EVP_PKEY_DH; doderive = 1; pkey = load_example_dh_key(); break; # else return 1; # endif case 5: case 11: # ifndef OPENSSL_NO_ECX id = EVP_PKEY_X25519; doderive = 1; pkey = load_example_x25519_key(); break; # else return 1; # endif default: TEST_error("Should not happen"); goto err; } if (!TEST_ptr(pkey)) goto err; if (idx < 6) { if (!TEST_true(evp_pkey_is_provided(pkey))) goto err; } else { EVP_PKEY *tmp = pkey; /* Convert to a legacy key */ pkey = EVP_PKEY_new(); if (!TEST_ptr(pkey)) { pkey = tmp; goto err; } if (!TEST_true(evp_pkey_copy_downgraded(&pkey, tmp))) { EVP_PKEY_free(tmp); goto err; } EVP_PKEY_free(tmp); if (!TEST_true(evp_pkey_is_legacy(pkey))) goto err; } if (!TEST_ptr(orig_pmeth = EVP_PKEY_meth_find(id)) || !TEST_ptr(pkey)) goto err; EVP_PKEY_meth_get0_info(&orig_id, &orig_flags, orig_pmeth); if (!TEST_int_eq(orig_id, id) || !TEST_ptr(custom_pmeth = EVP_PKEY_meth_new(id, orig_flags))) goto err; if (id == EVP_PKEY_ED25519) { EVP_PKEY_meth_set_digestsign(custom_pmeth, custom_pmeth_digestsign); } if (id == EVP_PKEY_DH || id == EVP_PKEY_X25519) { EVP_PKEY_meth_set_derive(custom_pmeth, NULL, custom_pmeth_derive); } else { EVP_PKEY_meth_set_sign(custom_pmeth, NULL, custom_pmeth_sign); } if (id != EVP_PKEY_ED25519 && id != EVP_PKEY_X25519) { EVP_PKEY_meth_set_init(custom_pmeth, custom_pmeth_init); EVP_PKEY_meth_set_cleanup(custom_pmeth, custom_pmeth_cleanup); EVP_PKEY_meth_set_copy(custom_pmeth, custom_pmeth_copy); } EVP_PKEY_meth_set_ctrl(custom_pmeth, custom_pmeth_ctrl, NULL); if (!TEST_true(EVP_PKEY_meth_add0(custom_pmeth))) goto err; if (doderive) { pctx = EVP_PKEY_CTX_new(pkey, NULL); if (!TEST_ptr(pctx) || !TEST_int_eq(EVP_PKEY_derive_init(pctx), 1) || !TEST_int_ge(EVP_PKEY_CTX_ctrl(pctx, -1, -1, EVP_PKEY_CTRL_MY_COMMAND, 0, NULL), 1) || !TEST_int_eq(ctrl_called, 1) || !TEST_int_ge(EVP_PKEY_derive_set_peer(pctx, pkey), 1) || !TEST_int_ge(EVP_PKEY_derive(pctx, NULL, &reslen), 1) || !TEST_ptr(res = OPENSSL_malloc(reslen)) || !TEST_int_ge(EVP_PKEY_derive(pctx, res, &reslen), 1)) goto err; } else { ctx = EVP_MD_CTX_new(); reslen = EVP_PKEY_size(pkey); res = OPENSSL_malloc(reslen); if (!TEST_ptr(ctx) || !TEST_ptr(res) || !TEST_true(EVP_DigestSignInit(ctx, &pctx, md, NULL, pkey)) || !TEST_int_ge(EVP_PKEY_CTX_ctrl(pctx, -1, -1, EVP_PKEY_CTRL_MY_COMMAND, 0, NULL), 1) || !TEST_int_eq(ctrl_called, 1)) goto err; if (id == EVP_PKEY_ED25519) { if (!TEST_true(EVP_DigestSign(ctx, res, &reslen, msg, sizeof(msg)))) goto err; } else { if (!TEST_true(EVP_DigestUpdate(ctx, msg, sizeof(msg))) || !TEST_true(EVP_DigestSignFinal(ctx, res, &reslen))) goto err; } } testresult = 1; err: OPENSSL_free(res); EVP_MD_CTX_free(ctx); if (doderive) EVP_PKEY_CTX_free(pctx); EVP_PKEY_free(pkey); EVP_PKEY_meth_remove(custom_pmeth); EVP_PKEY_meth_free(custom_pmeth); custom_pmeth = NULL; return testresult; } static int test_evp_md_cipher_meth(void) { EVP_MD *md = EVP_MD_meth_dup(EVP_sha256()); EVP_CIPHER *ciph = EVP_CIPHER_meth_dup(EVP_aes_128_cbc()); int testresult = 0; if (!TEST_ptr(md) || !TEST_ptr(ciph)) goto err; testresult = 1; err: EVP_MD_meth_free(md); EVP_CIPHER_meth_free(ciph); return testresult; } typedef struct { int data; } custom_dgst_ctx; static int custom_md_init_called = 0; static int custom_md_cleanup_called = 0; static int custom_md_init(EVP_MD_CTX *ctx) { custom_dgst_ctx *p = EVP_MD_CTX_md_data(ctx); if (p == NULL) return 0; custom_md_init_called++; return 1; } static int custom_md_cleanup(EVP_MD_CTX *ctx) { custom_dgst_ctx *p = EVP_MD_CTX_md_data(ctx); if (p == NULL) /* Nothing to do */ return 1; custom_md_cleanup_called++; return 1; } static int test_custom_md_meth(void) { EVP_MD_CTX *mdctx = NULL; EVP_MD *tmp = NULL; char mess[] = "Test Message\n"; unsigned char md_value[EVP_MAX_MD_SIZE]; unsigned int md_len; int testresult = 0; int nid; /* * We are testing deprecated functions. We don't support a non-default * library context in this test. */ if (testctx != NULL) return TEST_skip("Non-default libctx"); custom_md_init_called = custom_md_cleanup_called = 0; nid = OBJ_create("1.3.6.1.4.1.16604.998866.1", "custom-md", "custom-md"); if (!TEST_int_ne(nid, NID_undef)) goto err; tmp = EVP_MD_meth_new(nid, NID_undef); if (!TEST_ptr(tmp)) goto err; if (!TEST_true(EVP_MD_meth_set_init(tmp, custom_md_init)) || !TEST_true(EVP_MD_meth_set_cleanup(tmp, custom_md_cleanup)) || !TEST_true(EVP_MD_meth_set_app_datasize(tmp, sizeof(custom_dgst_ctx)))) goto err; mdctx = EVP_MD_CTX_new(); if (!TEST_ptr(mdctx) /* * Initing our custom md and then initing another md should * result in the init and cleanup functions of the custom md * being called. */ || !TEST_true(EVP_DigestInit_ex(mdctx, tmp, NULL)) || !TEST_true(EVP_DigestInit_ex(mdctx, EVP_sha256(), NULL)) || !TEST_true(EVP_DigestUpdate(mdctx, mess, strlen(mess))) || !TEST_true(EVP_DigestFinal_ex(mdctx, md_value, &md_len)) || !TEST_int_eq(custom_md_init_called, 1) || !TEST_int_eq(custom_md_cleanup_called, 1)) goto err; testresult = 1; err: EVP_MD_CTX_free(mdctx); EVP_MD_meth_free(tmp); return testresult; } typedef struct { int data; } custom_ciph_ctx; static int custom_ciph_init_called = 0; static int custom_ciph_cleanup_called = 0; static int custom_ciph_init(EVP_CIPHER_CTX *ctx, const unsigned char *key, const unsigned char *iv, int enc) { custom_ciph_ctx *p = EVP_CIPHER_CTX_get_cipher_data(ctx); if (p == NULL) return 0; custom_ciph_init_called++; return 1; } static int custom_ciph_cleanup(EVP_CIPHER_CTX *ctx) { custom_ciph_ctx *p = EVP_CIPHER_CTX_get_cipher_data(ctx); if (p == NULL) /* Nothing to do */ return 1; custom_ciph_cleanup_called++; return 1; } static int test_custom_ciph_meth(void) { EVP_CIPHER_CTX *ciphctx = NULL; EVP_CIPHER *tmp = NULL; int testresult = 0; int nid; /* * We are testing deprecated functions. We don't support a non-default * library context in this test. */ if (testctx != NULL) return TEST_skip("Non-default libctx"); custom_ciph_init_called = custom_ciph_cleanup_called = 0; nid = OBJ_create("1.3.6.1.4.1.16604.998866.2", "custom-ciph", "custom-ciph"); if (!TEST_int_ne(nid, NID_undef)) goto err; tmp = EVP_CIPHER_meth_new(nid, 16, 16); if (!TEST_ptr(tmp)) goto err; if (!TEST_true(EVP_CIPHER_meth_set_init(tmp, custom_ciph_init)) || !TEST_true(EVP_CIPHER_meth_set_flags(tmp, EVP_CIPH_ALWAYS_CALL_INIT)) || !TEST_true(EVP_CIPHER_meth_set_cleanup(tmp, custom_ciph_cleanup)) || !TEST_true(EVP_CIPHER_meth_set_impl_ctx_size(tmp, sizeof(custom_ciph_ctx)))) goto err; ciphctx = EVP_CIPHER_CTX_new(); if (!TEST_ptr(ciphctx) /* * Initing our custom cipher and then initing another cipher * should result in the init and cleanup functions of the custom * cipher being called. */ || !TEST_true(EVP_CipherInit_ex(ciphctx, tmp, NULL, NULL, NULL, 1)) || !TEST_true(EVP_CipherInit_ex(ciphctx, EVP_aes_128_cbc(), NULL, NULL, NULL, 1)) || !TEST_int_eq(custom_ciph_init_called, 1) || !TEST_int_eq(custom_ciph_cleanup_called, 1)) goto err; testresult = 1; err: EVP_CIPHER_CTX_free(ciphctx); EVP_CIPHER_meth_free(tmp); return testresult; } # ifndef OPENSSL_NO_DYNAMIC_ENGINE /* Test we can create a signature keys with an associated ENGINE */ static int test_signatures_with_engine(int tst) { ENGINE *e; const char *engine_id = "dasync"; EVP_PKEY *pkey = NULL; const unsigned char badcmackey[] = { 0x00, 0x01 }; const unsigned char cmackey[] = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f }; const unsigned char ed25519key[] = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f }; const unsigned char msg[] = { 0x00, 0x01, 0x02, 0x03 }; int testresult = 0; EVP_MD_CTX *ctx = NULL; unsigned char *mac = NULL; size_t maclen = 0; int ret; # ifdef OPENSSL_NO_CMAC /* Skip CMAC tests in a no-cmac build */ if (tst <= 1) return 1; # endif # ifdef OPENSSL_NO_ECX /* Skip ECX tests in a no-ecx build */ if (tst == 2) return 1; # endif if (!TEST_ptr(e = ENGINE_by_id(engine_id))) return 0; if (!TEST_true(ENGINE_init(e))) { ENGINE_free(e); return 0; } switch (tst) { case 0: pkey = EVP_PKEY_new_CMAC_key(e, cmackey, sizeof(cmackey), EVP_aes_128_cbc()); break; case 1: pkey = EVP_PKEY_new_CMAC_key(e, badcmackey, sizeof(badcmackey), EVP_aes_128_cbc()); break; case 2: pkey = EVP_PKEY_new_raw_private_key(EVP_PKEY_ED25519, e, ed25519key, sizeof(ed25519key)); break; default: TEST_error("Invalid test case"); goto err; } if (!TEST_ptr(pkey)) goto err; if (!TEST_ptr(ctx = EVP_MD_CTX_new())) goto err; ret = EVP_DigestSignInit(ctx, NULL, tst == 2 ? NULL : EVP_sha256(), NULL, pkey); if (tst == 0) { if (!TEST_true(ret)) goto err; if (!TEST_true(EVP_DigestSignUpdate(ctx, msg, sizeof(msg))) || !TEST_true(EVP_DigestSignFinal(ctx, NULL, &maclen))) goto err; if (!TEST_ptr(mac = OPENSSL_malloc(maclen))) goto err; if (!TEST_true(EVP_DigestSignFinal(ctx, mac, &maclen))) goto err; } else { /* We used a bad key. We expect a failure here */ if (!TEST_false(ret)) goto err; } testresult = 1; err: EVP_MD_CTX_free(ctx); OPENSSL_free(mac); EVP_PKEY_free(pkey); ENGINE_finish(e); ENGINE_free(e); return testresult; } static int test_cipher_with_engine(void) { ENGINE *e; const char *engine_id = "dasync"; const unsigned char keyiv[] = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f }; const unsigned char msg[] = { 0x00, 0x01, 0x02, 0x03 }; int testresult = 0; EVP_CIPHER_CTX *ctx = NULL, *ctx2 = NULL; unsigned char buf[AES_BLOCK_SIZE]; int len = 0; if (!TEST_ptr(e = ENGINE_by_id(engine_id))) return 0; if (!TEST_true(ENGINE_init(e))) { ENGINE_free(e); return 0; } if (!TEST_ptr(ctx = EVP_CIPHER_CTX_new()) || !TEST_ptr(ctx2 = EVP_CIPHER_CTX_new())) goto err; if (!TEST_true(EVP_EncryptInit_ex(ctx, EVP_aes_128_cbc(), e, keyiv, keyiv))) goto err; /* Copy the ctx, and complete the operation with the new ctx */ if (!TEST_true(EVP_CIPHER_CTX_copy(ctx2, ctx))) goto err; if (!TEST_true(EVP_EncryptUpdate(ctx2, buf, &len, msg, sizeof(msg))) || !TEST_true(EVP_EncryptFinal_ex(ctx2, buf + len, &len))) goto err; testresult = 1; err: EVP_CIPHER_CTX_free(ctx); EVP_CIPHER_CTX_free(ctx2); ENGINE_finish(e); ENGINE_free(e); return testresult; } # endif /* OPENSSL_NO_DYNAMIC_ENGINE */ #endif /* OPENSSL_NO_DEPRECATED_3_0 */ #ifndef OPENSSL_NO_ECX static int ecxnids[] = { NID_X25519, NID_X448, NID_ED25519, NID_ED448 }; /* Test that creating ECX keys with a short private key fails as expected */ static int test_ecx_short_keys(int tst) { unsigned char ecxkeydata = 1; EVP_PKEY *pkey; pkey = EVP_PKEY_new_raw_private_key_ex(testctx, OBJ_nid2sn(ecxnids[tst]), NULL, &ecxkeydata, 1); if (!TEST_ptr_null(pkey)) { EVP_PKEY_free(pkey); return 0; } return 1; } #endif typedef enum OPTION_choice { OPT_ERR = -1, OPT_EOF = 0, OPT_CONTEXT, OPT_TEST_ENUM } OPTION_CHOICE; const OPTIONS *test_get_options(void) { static const OPTIONS options[] = { OPT_TEST_OPTIONS_DEFAULT_USAGE, { "context", OPT_CONTEXT, '-', "Explicitly use a non-default library context" }, { NULL } }; return options; } #ifndef OPENSSL_NO_ECX /* Test that trying to sign with a public key errors out gracefully */ static int test_ecx_not_private_key(int tst) { EVP_PKEY *pkey = NULL; const unsigned char msg[] = { 0x00, 0x01, 0x02, 0x03 }; int testresult = 0; EVP_MD_CTX *ctx = NULL; unsigned char *mac = NULL; size_t maclen = 0; unsigned char *pubkey; size_t pubkeylen; switch (keys[tst].type) { case NID_X25519: case NID_X448: return TEST_skip("signing not supported for X25519/X448"); } /* Check if this algorithm supports public keys */ if (keys[tst].pub == NULL) return TEST_skip("no public key present"); pubkey = (unsigned char *)keys[tst].pub; pubkeylen = strlen(keys[tst].pub); pkey = EVP_PKEY_new_raw_public_key_ex(testctx, OBJ_nid2sn(keys[tst].type), NULL, pubkey, pubkeylen); if (!TEST_ptr(pkey)) goto err; if (!TEST_ptr(ctx = EVP_MD_CTX_new())) goto err; if (EVP_DigestSignInit(ctx, NULL, NULL, NULL, pkey) != 1) goto check_err; if (EVP_DigestSign(ctx, NULL, &maclen, msg, sizeof(msg)) != 1) goto check_err; if (!TEST_ptr(mac = OPENSSL_malloc(maclen))) goto err; if (!TEST_int_eq(EVP_DigestSign(ctx, mac, &maclen, msg, sizeof(msg)), 0)) goto err; check_err: /* * Currently only EVP_DigestSign will throw PROV_R_NOT_A_PRIVATE_KEY, * but we relax the check to allow error also thrown by * EVP_DigestSignInit and EVP_DigestSign. */ if (ERR_GET_REASON(ERR_peek_error()) == PROV_R_NOT_A_PRIVATE_KEY) { testresult = 1; ERR_clear_error(); } err: EVP_MD_CTX_free(ctx); OPENSSL_free(mac); EVP_PKEY_free(pkey); return testresult; } #endif /* OPENSSL_NO_ECX */ static int test_sign_continuation(void) { OSSL_PROVIDER *fake_rsa = NULL; int testresult = 0; EVP_PKEY *pkey = NULL; EVP_PKEY_CTX *pctx = NULL; EVP_MD_CTX *mctx = NULL; const char sigbuf[] = "To Be Signed"; unsigned char signature[256]; size_t siglen = 256; static int nodupnum = 1; static const OSSL_PARAM nodup_params[] = { OSSL_PARAM_int("NO_DUP", &nodupnum), OSSL_PARAM_END }; if (!TEST_ptr(fake_rsa = fake_rsa_start(testctx))) return 0; /* Construct a pkey using precise propq to use our provider */ if (!TEST_ptr(pctx = EVP_PKEY_CTX_new_from_name(testctx, "RSA", "provider=fake-rsa")) || !TEST_true(EVP_PKEY_fromdata_init(pctx)) || !TEST_true(EVP_PKEY_fromdata(pctx, &pkey, EVP_PKEY_KEYPAIR, NULL)) || !TEST_ptr(pkey)) goto end; /* First test it continues (classic behavior) */ if (!TEST_ptr(mctx = EVP_MD_CTX_new()) || !TEST_true(EVP_DigestSignInit_ex(mctx, NULL, NULL, testctx, NULL, pkey, NULL)) || !TEST_true(EVP_DigestSignUpdate(mctx, sigbuf, sizeof(sigbuf))) || !TEST_true(EVP_DigestSignFinal(mctx, signature, &siglen)) || !TEST_true(EVP_DigestSignUpdate(mctx, sigbuf, sizeof(sigbuf))) || !TEST_true(EVP_DigestSignFinal(mctx, signature, &siglen))) goto end; EVP_MD_CTX_free(mctx); /* try again but failing the continuation */ if (!TEST_ptr(mctx = EVP_MD_CTX_new()) || !TEST_true(EVP_DigestSignInit_ex(mctx, NULL, NULL, testctx, NULL, pkey, nodup_params)) || !TEST_true(EVP_DigestSignUpdate(mctx, sigbuf, sizeof(sigbuf))) || !TEST_true(EVP_DigestSignFinal(mctx, signature, &siglen)) || !TEST_false(EVP_DigestSignUpdate(mctx, sigbuf, sizeof(sigbuf))) || !TEST_false(EVP_DigestSignFinal(mctx, signature, &siglen))) goto end; testresult = 1; end: EVP_MD_CTX_free(mctx); EVP_PKEY_free(pkey); EVP_PKEY_CTX_free(pctx); fake_rsa_finish(fake_rsa); return testresult; } static int aes_gcm_encrypt(const unsigned char *gcm_key, size_t gcm_key_s, const unsigned char *gcm_iv, size_t gcm_ivlen, const unsigned char *gcm_pt, size_t gcm_pt_s, const unsigned char *gcm_aad, size_t gcm_aad_s, const unsigned char *gcm_ct, size_t gcm_ct_s, const unsigned char *gcm_tag, size_t gcm_tag_s) { int ret = 0; EVP_CIPHER_CTX *ctx; EVP_CIPHER *cipher = NULL; int outlen, tmplen; unsigned char outbuf[1024]; unsigned char outtag[16]; OSSL_PARAM params[2] = { OSSL_PARAM_END, OSSL_PARAM_END }; if (!TEST_ptr(ctx = EVP_CIPHER_CTX_new()) || !TEST_ptr(cipher = EVP_CIPHER_fetch(testctx, "AES-256-GCM", ""))) goto err; params[0] = OSSL_PARAM_construct_size_t(OSSL_CIPHER_PARAM_AEAD_IVLEN, &gcm_ivlen); if (!TEST_true(EVP_EncryptInit_ex2(ctx, cipher, gcm_key, gcm_iv, params)) || (gcm_aad != NULL && !TEST_true(EVP_EncryptUpdate(ctx, NULL, &outlen, gcm_aad, gcm_aad_s))) || !TEST_true(EVP_EncryptUpdate(ctx, outbuf, &outlen, gcm_pt, gcm_pt_s)) || !TEST_true(EVP_EncryptFinal_ex(ctx, outbuf, &tmplen))) goto err; params[0] = OSSL_PARAM_construct_octet_string(OSSL_CIPHER_PARAM_AEAD_TAG, outtag, sizeof(outtag)); if (!TEST_true(EVP_CIPHER_CTX_get_params(ctx, params)) || !TEST_mem_eq(outbuf, outlen, gcm_ct, gcm_ct_s) || !TEST_mem_eq(outtag, gcm_tag_s, gcm_tag, gcm_tag_s)) goto err; ret = 1; err: EVP_CIPHER_free(cipher); EVP_CIPHER_CTX_free(ctx); return ret; } static int aes_gcm_decrypt(const unsigned char *gcm_key, size_t gcm_key_s, const unsigned char *gcm_iv, size_t gcm_ivlen, const unsigned char *gcm_pt, size_t gcm_pt_s, const unsigned char *gcm_aad, size_t gcm_aad_s, const unsigned char *gcm_ct, size_t gcm_ct_s, const unsigned char *gcm_tag, size_t gcm_tag_s) { int ret = 0; EVP_CIPHER_CTX *ctx; EVP_CIPHER *cipher = NULL; int outlen; unsigned char outbuf[1024]; OSSL_PARAM params[2] = { OSSL_PARAM_END, OSSL_PARAM_END }; if ((ctx = EVP_CIPHER_CTX_new()) == NULL) goto err; if ((cipher = EVP_CIPHER_fetch(testctx, "AES-256-GCM", "")) == NULL) goto err; params[0] = OSSL_PARAM_construct_size_t(OSSL_CIPHER_PARAM_AEAD_IVLEN, &gcm_ivlen); if (!TEST_true(EVP_DecryptInit_ex2(ctx, cipher, gcm_key, gcm_iv, params)) || (gcm_aad != NULL && !TEST_true(EVP_DecryptUpdate(ctx, NULL, &outlen, gcm_aad, gcm_aad_s))) || !TEST_true(EVP_DecryptUpdate(ctx, outbuf, &outlen, gcm_ct, gcm_ct_s)) || !TEST_mem_eq(outbuf, outlen, gcm_pt, gcm_pt_s)) goto err; params[0] = OSSL_PARAM_construct_octet_string(OSSL_CIPHER_PARAM_AEAD_TAG, (void*)gcm_tag, gcm_tag_s); if (!TEST_true(EVP_CIPHER_CTX_set_params(ctx, params)) ||!TEST_true(EVP_DecryptFinal_ex(ctx, outbuf, &outlen))) goto err; ret = 1; err: EVP_CIPHER_free(cipher); EVP_CIPHER_CTX_free(ctx); return ret; } static int test_aes_gcm_ivlen_change_cve_2023_5363(void) { /* AES-GCM test data obtained from NIST public test vectors */ static const unsigned char gcm_key[] = { 0xd0, 0xc2, 0x67, 0xc1, 0x9f, 0x30, 0xd8, 0x0b, 0x89, 0x14, 0xbb, 0xbf, 0xb7, 0x2f, 0x73, 0xb8, 0xd3, 0xcd, 0x5f, 0x6a, 0x78, 0x70, 0x15, 0x84, 0x8a, 0x7b, 0x30, 0xe3, 0x8f, 0x16, 0xf1, 0x8b, }; static const unsigned char gcm_iv[] = { 0xb6, 0xdc, 0xda, 0x95, 0xac, 0x99, 0x77, 0x76, 0x25, 0xae, 0x87, 0xf8, 0xa3, 0xa9, 0xdd, 0x64, 0xd7, 0x9b, 0xbd, 0x5f, 0x4a, 0x0e, 0x54, 0xca, 0x1a, 0x9f, 0xa2, 0xe3, 0xf4, 0x5f, 0x5f, 0xc2, 0xce, 0xa7, 0xb6, 0x14, 0x12, 0x6f, 0xf0, 0xaf, 0xfd, 0x3e, 0x17, 0x35, 0x6e, 0xa0, 0x16, 0x09, 0xdd, 0xa1, 0x3f, 0xd8, 0xdd, 0xf3, 0xdf, 0x4f, 0xcb, 0x18, 0x49, 0xb8, 0xb3, 0x69, 0x2c, 0x5d, 0x4f, 0xad, 0x30, 0x91, 0x08, 0xbc, 0xbe, 0x24, 0x01, 0x0f, 0xbe, 0x9c, 0xfb, 0x4f, 0x5d, 0x19, 0x7f, 0x4c, 0x53, 0xb0, 0x95, 0x90, 0xac, 0x7b, 0x1f, 0x7b, 0xa0, 0x99, 0xe1, 0xf3, 0x48, 0x54, 0xd0, 0xfc, 0xa9, 0xcc, 0x91, 0xf8, 0x1f, 0x9b, 0x6c, 0x9a, 0xe0, 0xdc, 0x63, 0xea, 0x7d, 0x2a, 0x4a, 0x7d, 0xa5, 0xed, 0x68, 0x57, 0x27, 0x6b, 0x68, 0xe0, 0xf2, 0xb8, 0x51, 0x50, 0x8d, 0x3d, }; static const unsigned char gcm_pt[] = { 0xb8, 0xb6, 0x88, 0x36, 0x44, 0xe2, 0x34, 0xdf, 0x24, 0x32, 0x91, 0x07, 0x4f, 0xe3, 0x6f, 0x81, }; static const unsigned char gcm_ct[] = { 0xff, 0x4f, 0xb3, 0xf3, 0xf9, 0xa2, 0x51, 0xd4, 0x82, 0xc2, 0xbe, 0xf3, 0xe2, 0xd0, 0xec, 0xed, }; static const unsigned char gcm_tag[] = { 0xbd, 0x06, 0x38, 0x09, 0xf7, 0xe1, 0xc4, 0x72, 0x0e, 0xf2, 0xea, 0x63, 0xdb, 0x99, 0x6c, 0x21, }; return aes_gcm_encrypt(gcm_key, sizeof(gcm_key), gcm_iv, sizeof(gcm_iv), gcm_pt, sizeof(gcm_pt), NULL, 0, gcm_ct, sizeof(gcm_ct), gcm_tag, sizeof(gcm_tag)) && aes_gcm_decrypt(gcm_key, sizeof(gcm_key), gcm_iv, sizeof(gcm_iv), gcm_pt, sizeof(gcm_pt), NULL, 0, gcm_ct, sizeof(gcm_ct), gcm_tag, sizeof(gcm_tag)); } #ifndef OPENSSL_NO_RC4 static int rc4_encrypt(const unsigned char *rc4_key, size_t rc4_key_s, const unsigned char *rc4_pt, size_t rc4_pt_s, const unsigned char *rc4_ct, size_t rc4_ct_s) { int ret = 0; EVP_CIPHER_CTX *ctx; EVP_CIPHER *cipher = NULL; int outlen, tmplen; unsigned char outbuf[1024]; OSSL_PARAM params[2] = { OSSL_PARAM_END, OSSL_PARAM_END }; if (!TEST_ptr(ctx = EVP_CIPHER_CTX_new()) || !TEST_ptr(cipher = EVP_CIPHER_fetch(testctx, "RC4", ""))) goto err; params[0] = OSSL_PARAM_construct_size_t(OSSL_CIPHER_PARAM_KEYLEN, &rc4_key_s); if (!TEST_true(EVP_EncryptInit_ex2(ctx, cipher, rc4_key, NULL, params)) || !TEST_true(EVP_EncryptUpdate(ctx, outbuf, &outlen, rc4_pt, rc4_pt_s)) || !TEST_true(EVP_EncryptFinal_ex(ctx, outbuf, &tmplen))) goto err; if (!TEST_mem_eq(outbuf, outlen, rc4_ct, rc4_ct_s)) goto err; ret = 1; err: EVP_CIPHER_free(cipher); EVP_CIPHER_CTX_free(ctx); return ret; } static int rc4_decrypt(const unsigned char *rc4_key, size_t rc4_key_s, const unsigned char *rc4_pt, size_t rc4_pt_s, const unsigned char *rc4_ct, size_t rc4_ct_s) { int ret = 0; EVP_CIPHER_CTX *ctx; EVP_CIPHER *cipher = NULL; int outlen; unsigned char outbuf[1024]; OSSL_PARAM params[2] = { OSSL_PARAM_END, OSSL_PARAM_END }; if ((ctx = EVP_CIPHER_CTX_new()) == NULL) goto err; if ((cipher = EVP_CIPHER_fetch(testctx, "RC4", "")) == NULL) goto err; params[0] = OSSL_PARAM_construct_size_t(OSSL_CIPHER_PARAM_KEYLEN, &rc4_key_s); if (!TEST_true(EVP_DecryptInit_ex2(ctx, cipher, rc4_key, NULL, params)) || !TEST_true(EVP_DecryptUpdate(ctx, outbuf, &outlen, rc4_ct, rc4_ct_s)) || !TEST_mem_eq(outbuf, outlen, rc4_pt, rc4_pt_s)) goto err; ret = 1; err: EVP_CIPHER_free(cipher); EVP_CIPHER_CTX_free(ctx); return ret; } static int test_aes_rc4_keylen_change_cve_2023_5363(void) { /* RC4 test data obtained from RFC 6229 */ static const struct { unsigned char key[5]; unsigned char padding[11]; } rc4_key = { { /* Five bytes of key material */ 0x83, 0x32, 0x22, 0x77, 0x2a, }, { /* Random padding to 16 bytes */ 0x80, 0xad, 0x97, 0xbd, 0xc9, 0x73, 0xdf, 0x8a, 0xaa, 0x32, 0x91 } }; static const unsigned char rc4_pt[] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; static const unsigned char rc4_ct[] = { 0x80, 0xad, 0x97, 0xbd, 0xc9, 0x73, 0xdf, 0x8a, 0x2e, 0x87, 0x9e, 0x92, 0xa4, 0x97, 0xef, 0xda }; if (lgcyprov == NULL) return TEST_skip("Test requires legacy provider to be loaded"); return rc4_encrypt(rc4_key.key, sizeof(rc4_key.key), rc4_pt, sizeof(rc4_pt), rc4_ct, sizeof(rc4_ct)) && rc4_decrypt(rc4_key.key, sizeof(rc4_key.key), rc4_pt, sizeof(rc4_pt), rc4_ct, sizeof(rc4_ct)); } #endif int setup_tests(void) { OPTION_CHOICE o; while ((o = opt_next()) != OPT_EOF) { switch (o) { case OPT_CONTEXT: /* Set up an alternate library context */ testctx = OSSL_LIB_CTX_new(); if (!TEST_ptr(testctx)) return 0; #ifdef STATIC_LEGACY /* * This test is always statically linked against libcrypto. We must not * attempt to load legacy.so that might be dynamically linked against * libcrypto. Instead we use a built-in version of the legacy provider. */ if (!OSSL_PROVIDER_add_builtin(testctx, "legacy", ossl_legacy_provider_init)) return 0; #endif /* Swap the libctx to test non-default context only */ nullprov = OSSL_PROVIDER_load(NULL, "null"); deflprov = OSSL_PROVIDER_load(testctx, "default"); #ifndef OPENSSL_SYS_TANDEM lgcyprov = OSSL_PROVIDER_load(testctx, "legacy"); #endif break; case OPT_TEST_CASES: break; default: return 0; } } ADD_TEST(test_EVP_set_default_properties); ADD_ALL_TESTS(test_EVP_DigestSignInit, 30); ADD_TEST(test_EVP_DigestVerifyInit); #ifndef OPENSSL_NO_SIPHASH ADD_TEST(test_siphash_digestsign); #endif ADD_TEST(test_EVP_Digest); ADD_TEST(test_EVP_md_null); ADD_ALL_TESTS(test_EVP_PKEY_sign, 3); #ifndef OPENSSL_NO_DEPRECATED_3_0 ADD_ALL_TESTS(test_EVP_PKEY_sign_with_app_method, 2); #endif ADD_ALL_TESTS(test_EVP_Enveloped, 2); ADD_ALL_TESTS(test_d2i_AutoPrivateKey, OSSL_NELEM(keydata)); ADD_TEST(test_privatekey_to_pkcs8); ADD_TEST(test_EVP_PKCS82PKEY_wrong_tag); #ifndef OPENSSL_NO_EC ADD_TEST(test_EVP_PKCS82PKEY); #endif #ifndef OPENSSL_NO_EC ADD_ALL_TESTS(test_EC_keygen_with_enc, OSSL_NELEM(ec_encodings)); #endif #if !defined(OPENSSL_NO_SM2) ADD_TEST(test_EVP_SM2); ADD_TEST(test_EVP_SM2_verify); #endif ADD_ALL_TESTS(test_set_get_raw_keys, OSSL_NELEM(keys)); #ifndef OPENSSL_NO_DEPRECATED_3_0 custom_pmeth = EVP_PKEY_meth_new(0xdefaced, 0); if (!TEST_ptr(custom_pmeth)) return 0; EVP_PKEY_meth_set_check(custom_pmeth, pkey_custom_check); EVP_PKEY_meth_set_public_check(custom_pmeth, pkey_custom_pub_check); EVP_PKEY_meth_set_param_check(custom_pmeth, pkey_custom_param_check); if (!TEST_int_eq(EVP_PKEY_meth_add0(custom_pmeth), 1)) return 0; #endif ADD_ALL_TESTS(test_EVP_PKEY_check, OSSL_NELEM(keycheckdata)); #ifndef OPENSSL_NO_CMAC ADD_TEST(test_CMAC_keygen); #endif ADD_TEST(test_HKDF); ADD_TEST(test_emptyikm_HKDF); #ifndef OPENSSL_NO_EC ADD_TEST(test_X509_PUBKEY_inplace); ADD_TEST(test_X509_PUBKEY_dup); ADD_ALL_TESTS(test_invalide_ec_char2_pub_range_decode, OSSL_NELEM(ec_der_pub_keys)); #endif #ifndef OPENSSL_NO_DSA ADD_TEST(test_DSA_get_set_params); ADD_TEST(test_DSA_priv_pub); #endif ADD_TEST(test_RSA_get_set_params); ADD_TEST(test_RSA_OAEP_set_get_params); ADD_TEST(test_RSA_OAEP_set_null_label); #ifndef OPENSSL_NO_DEPRECATED_3_0 ADD_TEST(test_RSA_legacy); #endif #if !defined(OPENSSL_NO_CHACHA) && !defined(OPENSSL_NO_POLY1305) ADD_TEST(test_decrypt_null_chunks); #endif #ifndef OPENSSL_NO_DH ADD_TEST(test_DH_priv_pub); # ifndef OPENSSL_NO_DEPRECATED_3_0 ADD_TEST(test_EVP_PKEY_set1_DH); # endif #endif #ifndef OPENSSL_NO_EC ADD_TEST(test_EC_priv_pub); ADD_TEST(test_evp_get_ec_pub); # ifndef OPENSSL_NO_DEPRECATED_3_0 ADD_TEST(test_EC_priv_only_legacy); ADD_TEST(test_evp_get_ec_pub_legacy); # endif #endif ADD_ALL_TESTS(test_keygen_with_empty_template, 2); ADD_ALL_TESTS(test_pkey_ctx_fail_without_provider, 2); ADD_TEST(test_rand_agglomeration); ADD_ALL_TESTS(test_evp_iv_aes, 12); #ifndef OPENSSL_NO_DES ADD_ALL_TESTS(test_evp_iv_des, 6); #endif #ifndef OPENSSL_NO_BF ADD_ALL_TESTS(test_evp_bf_default_keylen, 4); #endif ADD_TEST(test_EVP_rsa_pss_with_keygen_bits); ADD_TEST(test_EVP_rsa_pss_set_saltlen); #ifndef OPENSSL_NO_EC ADD_ALL_TESTS(test_ecpub, OSSL_NELEM(ecpub_nids)); #endif ADD_TEST(test_names_do_all); ADD_ALL_TESTS(test_evp_init_seq, OSSL_NELEM(evp_init_tests)); ADD_ALL_TESTS(test_evp_reset, OSSL_NELEM(evp_reset_tests)); ADD_ALL_TESTS(test_evp_reinit_seq, OSSL_NELEM(evp_reinit_tests)); ADD_ALL_TESTS(test_gcm_reinit, OSSL_NELEM(gcm_reinit_tests)); ADD_ALL_TESTS(test_evp_updated_iv, OSSL_NELEM(evp_updated_iv_tests)); ADD_ALL_TESTS(test_ivlen_change, OSSL_NELEM(ivlen_change_ciphers)); if (OSSL_NELEM(keylen_change_ciphers) - 1 > 0) ADD_ALL_TESTS(test_keylen_change, OSSL_NELEM(keylen_change_ciphers) - 1); #ifndef OPENSSL_NO_DEPRECATED_3_0 ADD_ALL_TESTS(test_custom_pmeth, 12); ADD_TEST(test_evp_md_cipher_meth); ADD_TEST(test_custom_md_meth); ADD_TEST(test_custom_ciph_meth); # ifndef OPENSSL_NO_DYNAMIC_ENGINE /* Tests only support the default libctx */ if (testctx == NULL) { # ifndef OPENSSL_NO_EC ADD_ALL_TESTS(test_signatures_with_engine, 3); # else ADD_ALL_TESTS(test_signatures_with_engine, 2); # endif ADD_TEST(test_cipher_with_engine); } # endif #endif #ifndef OPENSSL_NO_ECX ADD_ALL_TESTS(test_ecx_short_keys, OSSL_NELEM(ecxnids)); ADD_ALL_TESTS(test_ecx_not_private_key, OSSL_NELEM(keys)); #endif ADD_TEST(test_sign_continuation); /* Test cases for CVE-2023-5363 */ ADD_TEST(test_aes_gcm_ivlen_change_cve_2023_5363); #ifndef OPENSSL_NO_RC4 ADD_TEST(test_aes_rc4_keylen_change_cve_2023_5363); #endif return 1; } void cleanup_tests(void) { OSSL_PROVIDER_unload(nullprov); OSSL_PROVIDER_unload(deflprov); #ifndef OPENSSL_SYS_TANDEM OSSL_PROVIDER_unload(lgcyprov); #endif OSSL_LIB_CTX_free(testctx); }
./openssl/test/lhash_test.c
/* * Copyright 2017-2020 The OpenSSL Project Authors. All Rights Reserved. * Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <stdio.h> #include <string.h> #include <openssl/opensslconf.h> #include <openssl/lhash.h> #include <openssl/err.h> #include <openssl/crypto.h> #include "internal/nelem.h" #include "testutil.h" /* * The macros below generate unused functions which error out one of the clang * builds. We disable this check here. */ #ifdef __clang__ #pragma clang diagnostic ignored "-Wunused-function" #endif DEFINE_LHASH_OF_EX(int); static int int_tests[] = { 65537, 13, 1, 3, -5, 6, 7, 4, -10, -12, -14, 22, 9, -17, 16, 17, -23, 35, 37, 173, 11 }; static const unsigned int n_int_tests = OSSL_NELEM(int_tests); static short int_found[OSSL_NELEM(int_tests)]; static short int_not_found; static unsigned long int int_hash(const int *p) { return 3 & *p; /* To force collisions */ } static int int_cmp(const int *p, const int *q) { return *p != *q; } static int int_find(int n) { unsigned int i; for (i = 0; i < n_int_tests; i++) if (int_tests[i] == n) return i; return -1; } static void int_doall(int *v) { const int n = int_find(*v); if (n < 0) int_not_found++; else int_found[n]++; } static void int_doall_arg(int *p, short *f) { const int n = int_find(*p); if (n < 0) int_not_found++; else f[n]++; } IMPLEMENT_LHASH_DOALL_ARG(int, short); static int test_int_lhash(void) { static struct { int data; int null; } dels[] = { { 65537, 0 }, { 173, 0 }, { 999, 1 }, { 37, 0 }, { 1, 0 }, { 34, 1 } }; const unsigned int n_dels = OSSL_NELEM(dels); LHASH_OF(int) *h = lh_int_new(&int_hash, &int_cmp); unsigned int i; int testresult = 0, j, *p; if (!TEST_ptr(h)) goto end; /* insert */ for (i = 0; i < n_int_tests; i++) if (!TEST_ptr_null(lh_int_insert(h, int_tests + i))) { TEST_info("int insert %d", i); goto end; } /* num_items */ if (!TEST_int_eq(lh_int_num_items(h), n_int_tests)) goto end; /* retrieve */ for (i = 0; i < n_int_tests; i++) if (!TEST_int_eq(*lh_int_retrieve(h, int_tests + i), int_tests[i])) { TEST_info("lhash int retrieve value %d", i); goto end; } for (i = 0; i < n_int_tests; i++) if (!TEST_ptr_eq(lh_int_retrieve(h, int_tests + i), int_tests + i)) { TEST_info("lhash int retrieve address %d", i); goto end; } j = 1; if (!TEST_ptr_eq(lh_int_retrieve(h, &j), int_tests + 2)) goto end; /* replace */ j = 13; if (!TEST_ptr(p = lh_int_insert(h, &j))) goto end; if (!TEST_ptr_eq(p, int_tests + 1)) goto end; if (!TEST_ptr_eq(lh_int_retrieve(h, int_tests + 1), &j)) goto end; /* do_all */ memset(int_found, 0, sizeof(int_found)); int_not_found = 0; lh_int_doall(h, &int_doall); if (!TEST_int_eq(int_not_found, 0)) { TEST_info("lhash int doall encountered a not found condition"); goto end; } for (i = 0; i < n_int_tests; i++) if (!TEST_int_eq(int_found[i], 1)) { TEST_info("lhash int doall %d", i); goto end; } /* do_all_arg */ memset(int_found, 0, sizeof(int_found)); int_not_found = 0; lh_int_doall_short(h, int_doall_arg, int_found); if (!TEST_int_eq(int_not_found, 0)) { TEST_info("lhash int doall arg encountered a not found condition"); goto end; } for (i = 0; i < n_int_tests; i++) if (!TEST_int_eq(int_found[i], 1)) { TEST_info("lhash int doall arg %d", i); goto end; } /* delete */ for (i = 0; i < n_dels; i++) { const int b = lh_int_delete(h, &dels[i].data) == NULL; if (!TEST_int_eq(b ^ dels[i].null, 0)) { TEST_info("lhash int delete %d", i); goto end; } } /* error */ if (!TEST_int_eq(lh_int_error(h), 0)) goto end; testresult = 1; end: lh_int_free(h); return testresult; } static unsigned long int stress_hash(const int *p) { return *p; } static int test_stress(void) { LHASH_OF(int) *h = lh_int_new(&stress_hash, &int_cmp); const unsigned int n = 2500000; unsigned int i; int testresult = 0, *p; if (!TEST_ptr(h)) goto end; /* insert */ for (i = 0; i < n; i++) { p = OPENSSL_malloc(sizeof(i)); if (!TEST_ptr(p)) { TEST_info("lhash stress out of memory %d", i); goto end; } *p = 3 * i + 1; lh_int_insert(h, p); } /* num_items */ if (!TEST_int_eq(lh_int_num_items(h), n)) goto end; /* delete in a different order */ for (i = 0; i < n; i++) { const int j = (7 * i + 4) % n * 3 + 1; if (!TEST_ptr(p = lh_int_delete(h, &j))) { TEST_info("lhash stress delete %d\n", i); goto end; } if (!TEST_int_eq(*p, j)) { TEST_info("lhash stress bad value %d", i); goto end; } OPENSSL_free(p); } testresult = 1; end: lh_int_free(h); return testresult; } int setup_tests(void) { ADD_TEST(test_int_lhash); ADD_TEST(test_stress); return 1; }
./openssl/test/upcallstest.c
/* * Copyright 2021-2023 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <openssl/objects.h> #include <openssl/crypto.h> #include <openssl/provider.h> #include "testutil.h" static const OSSL_ALGORITHM *obj_query(void *provctx, int operation_id, int *no_cache) { *no_cache = 0; return NULL; } static const OSSL_DISPATCH obj_dispatch_table[] = { { OSSL_FUNC_PROVIDER_QUERY_OPERATION, (void (*)(void))obj_query }, OSSL_DISPATCH_END }; static OSSL_FUNC_core_obj_add_sigid_fn *c_obj_add_sigid = NULL; static OSSL_FUNC_core_obj_create_fn *c_obj_create = NULL; /* test signature ids requiring digest */ #define SIG_OID "1.3.6.1.4.1.16604.998877.1" #define SIG_SN "my-sig" #define SIG_LN "my-sig-long" #define DIGEST_OID "1.3.6.1.4.1.16604.998877.2" #define DIGEST_SN "my-digest" #define DIGEST_LN "my-digest-long" #define SIGALG_OID "1.3.6.1.4.1.16604.998877.3" #define SIGALG_SN "my-sigalg" #define SIGALG_LN "my-sigalg-long" /* test signature ids requiring no digest */ #define NODIG_SIG_OID "1.3.6.1.4.1.16604.998877.4" #define NODIG_SIG_SN "my-nodig-sig" #define NODIG_SIG_LN "my-nodig-sig-long" #define NODIG_SIGALG_OID "1.3.6.1.4.1.16604.998877.5" #define NODIG_SIGALG_SN "my-nodig-sigalg" #define NODIG_SIGALG_LN "my-nodig-sigalg-long" static int obj_provider_init(const OSSL_CORE_HANDLE *handle, const OSSL_DISPATCH *in, const OSSL_DISPATCH **out, void **provctx) { *provctx = (void *)handle; *out = obj_dispatch_table; for (; in->function_id != 0; in++) { switch (in->function_id) { case OSSL_FUNC_CORE_OBJ_ADD_SIGID: c_obj_add_sigid = OSSL_FUNC_core_obj_add_sigid(in); break; case OSSL_FUNC_CORE_OBJ_CREATE: c_obj_create = OSSL_FUNC_core_obj_create(in); break; break; default: /* Just ignore anything we don't understand */ break; } } if (!c_obj_create(handle, DIGEST_OID, DIGEST_SN, DIGEST_LN) || !c_obj_create(handle, SIG_OID, SIG_SN, SIG_LN) || !c_obj_create(handle, SIGALG_OID, SIGALG_SN, SIGALG_LN)) return 0; if (!c_obj_create(handle, NODIG_SIG_OID, NODIG_SIG_SN, NODIG_SIG_LN) || !c_obj_create(handle, NODIG_SIGALG_OID, NODIG_SIGALG_SN, NODIG_SIGALG_LN)) return 0; if (!c_obj_add_sigid(handle, SIGALG_OID, DIGEST_SN, SIG_LN)) return 0; /* additional tests checking empty digest algs are accepted, too */ if (!c_obj_add_sigid(handle, NODIG_SIGALG_OID, "", NODIG_SIG_LN)) return 0; /* checking wrong digest alg name is rejected: */ if (c_obj_add_sigid(handle, NODIG_SIGALG_OID, "NonsenseAlg", NODIG_SIG_LN)) return 0; return 1; } static int obj_create_test(void) { OSSL_LIB_CTX *libctx = OSSL_LIB_CTX_new(); OSSL_PROVIDER *objprov = NULL; int sigalgnid, digestnid, signid, foundsid; int testresult = 0; if (!TEST_ptr(libctx)) goto err; if (!TEST_true(OSSL_PROVIDER_add_builtin(libctx, "obj-prov", obj_provider_init)) || !TEST_ptr(objprov = OSSL_PROVIDER_load(libctx, "obj-prov"))) goto err; /* Check that the provider created the OIDs/NIDs we expected */ sigalgnid = OBJ_txt2nid(SIGALG_OID); if (!TEST_int_ne(sigalgnid, NID_undef) || !TEST_true(OBJ_find_sigid_algs(sigalgnid, &digestnid, &signid)) || !TEST_int_ne(digestnid, NID_undef) || !TEST_int_ne(signid, NID_undef) || !TEST_int_eq(digestnid, OBJ_sn2nid(DIGEST_SN)) || !TEST_int_eq(signid, OBJ_ln2nid(SIG_LN))) goto err; /* Check empty digest alg storage capability */ sigalgnid = OBJ_txt2nid(NODIG_SIGALG_OID); if (!TEST_int_ne(sigalgnid, NID_undef) || !TEST_true(OBJ_find_sigid_algs(sigalgnid, &digestnid, &signid)) || !TEST_int_eq(digestnid, NID_undef) || !TEST_int_ne(signid, NID_undef)) goto err; /* Testing OBJ_find_sigid_by_algs */ /* First check exact sig/digest recall: */ sigalgnid = OBJ_sn2nid(SIGALG_SN); digestnid = OBJ_sn2nid(DIGEST_SN); signid = OBJ_ln2nid(SIG_LN); if ((!OBJ_find_sigid_by_algs(&foundsid, digestnid, signid)) || (foundsid != sigalgnid)) return 0; /* Check wrong signature/digest combination is rejected */ if ((OBJ_find_sigid_by_algs(&foundsid, OBJ_sn2nid("SHA512"), signid)) && (foundsid == sigalgnid)) return 0; /* Now also check signature not needing digest is found */ /* a) when some digest is given */ sigalgnid = OBJ_sn2nid(NODIG_SIGALG_SN); digestnid = OBJ_sn2nid("SHA512"); signid = OBJ_ln2nid(NODIG_SIG_LN); if ((!OBJ_find_sigid_by_algs(&foundsid, digestnid, signid)) || (foundsid != sigalgnid)) return 0; /* b) when NID_undef is passed */ digestnid = NID_undef; if ((!OBJ_find_sigid_by_algs(&foundsid, digestnid, signid)) || (foundsid != sigalgnid)) return 0; testresult = 1; err: OSSL_PROVIDER_unload(objprov); OSSL_LIB_CTX_free(libctx); return testresult; } int setup_tests(void) { ADD_TEST(obj_create_test); return 1; }
./openssl/test/rpktest.c
/* * Copyright 2023 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <openssl/ssl.h> #include "helpers/ssltestlib.h" #include "internal/dane.h" #include "testutil.h" #undef OSSL_NO_USABLE_TLS1_3 #if defined(OPENSSL_NO_TLS1_3) \ || (defined(OPENSSL_NO_EC) && defined(OPENSSL_NO_DH)) /* * If we don't have ec or dh then there are no built-in groups that are usable * with TLSv1.3 */ # define OSSL_NO_USABLE_TLS1_3 #endif static char *certsdir = NULL; static char *rootcert = NULL; static char *cert = NULL; static char *privkey = NULL; static char *cert2 = NULL; static char *privkey2 = NULL; static char *cert448 = NULL; static char *privkey448 = NULL; static char *cert25519 = NULL; static char *privkey25519 = NULL; static OSSL_LIB_CTX *libctx = NULL; static OSSL_PROVIDER *defctxnull = NULL; static const unsigned char cert_type_rpk[] = { TLSEXT_cert_type_rpk, TLSEXT_cert_type_x509 }; static const unsigned char SID_CTX[] = { 'r', 'p', 'k' }; static int rpk_verify_client_cb(int ok, X509_STORE_CTX *ctx) { int err = X509_STORE_CTX_get_error(ctx); if (X509_STORE_CTX_get0_rpk(ctx) != NULL) { if (err != X509_V_OK) { TEST_info("rpk_verify_client_cb: ok=%d err=%d", ok, err); return 0; } } return 1; } static int rpk_verify_server_cb(int ok, X509_STORE_CTX *ctx) { int err = X509_STORE_CTX_get_error(ctx); if (X509_STORE_CTX_get0_rpk(ctx) != NULL) { if (err != X509_V_OK) { TEST_info("rpk_verify_server_cb: ok=%d err=%d", ok, err); return 0; } } return 1; } /* * Test dimensions: * (2) server_cert_type RPK off/on for server * (2) client_cert_type RPK off/on for server * (2) server_cert_type RPK off/on for client * (2) client_cert_type RPK off/on for client * (4) RSA vs ECDSA vs Ed25519 vs Ed448 certificates * (2) TLSv1.2 vs TLSv1.3 * * Tests: * idx = 0 - is the normal success case, certificate, single peer key * idx = 1 - only a private key * idx = 2 - add client authentication * idx = 3 - add second peer key (rootcert.pem) * idx = 4 - add second peer key (different, RSA or ECDSA) * idx = 5 - reverse peer keys (rootcert.pem, different order) * idx = 6 - reverse peer keys (RSA or ECDSA, different order) * idx = 7 - expects failure due to mismatched key (RSA or ECDSA) * idx = 8 - expects failure due to no configured key on client * idx = 9 - add client authentication (PHA) * idx = 10 - add client authentication (privake key only) * idx = 11 - simple resumption * idx = 12 - simple resumption, no ticket * idx = 13 - resumption with client authentication * idx = 14 - resumption with client authentication, no ticket * idx = 15 - like 0, but use non-default libctx * * 16 * 2 * 4 * 2 * 2 * 2 * 2 = 2048 tests */ static int test_rpk(int idx) { # define RPK_TESTS 16 # define RPK_DIMS (2 * 4 * 2 * 2 * 2 * 2) SSL_CTX *cctx = NULL, *sctx = NULL; SSL *clientssl = NULL, *serverssl = NULL; EVP_PKEY *pkey = NULL, *other_pkey = NULL, *root_pkey = NULL; X509 *x509 = NULL, *other_x509 = NULL, *root_x509 = NULL; int testresult = 0, ret, expected = 1; int client_expected = X509_V_OK; int verify; int tls_version; char *cert_file = NULL; char *privkey_file = NULL; char *other_cert_file = NULL; SSL_SESSION *client_sess = NULL; SSL_SESSION *server_sess = NULL; int idx_server_server_rpk, idx_server_client_rpk; int idx_client_server_rpk, idx_client_client_rpk; int idx_cert, idx_prot; int client_auth = 0; int resumption = 0; long server_verify_result = 0; long client_verify_result = 0; OSSL_LIB_CTX *test_libctx = NULL; if (!TEST_int_le(idx, RPK_TESTS * RPK_DIMS)) return 0; idx_server_server_rpk = idx / (RPK_TESTS * 2 * 4 * 2 * 2 * 2); idx %= RPK_TESTS * 2 * 4 * 2 * 2 * 2; idx_server_client_rpk = idx / (RPK_TESTS * 2 * 4 * 2 * 2); idx %= RPK_TESTS * 2 * 4 * 2 * 2; idx_client_server_rpk = idx / (RPK_TESTS * 2 * 4 * 2); idx %= RPK_TESTS * 2 * 4 * 2; idx_client_client_rpk = idx / (RPK_TESTS * 2 * 4); idx %= RPK_TESTS * 2 * 4; idx_cert = idx / (RPK_TESTS * 2); idx %= RPK_TESTS * 2; idx_prot = idx / RPK_TESTS; idx %= RPK_TESTS; /* Load "root" cert/pubkey */ root_x509 = load_cert_pem(rootcert, NULL); if (!TEST_ptr(root_x509)) goto end; root_pkey = X509_get0_pubkey(root_x509); if (!TEST_ptr(root_pkey)) goto end; switch (idx_cert) { case 0: /* use RSA */ cert_file = cert; privkey_file = privkey; other_cert_file = cert2; break; #ifndef OPENSSL_NO_ECDSA case 1: /* use ECDSA */ cert_file = cert2; privkey_file = privkey2; other_cert_file = cert; break; # ifndef OPENSSL_NO_ECX case 2: /* use Ed448 */ cert_file = cert448; privkey_file = privkey448; other_cert_file = cert; break; case 3: /* use Ed25519 */ cert_file = cert25519; privkey_file = privkey25519; other_cert_file = cert; break; # endif #endif default: testresult = TEST_skip("EDCSA disabled"); goto end; } /* Load primary cert */ x509 = load_cert_pem(cert_file, NULL); if (!TEST_ptr(x509)) goto end; pkey = X509_get0_pubkey(x509); /* load other cert */ other_x509 = load_cert_pem(other_cert_file, NULL); if (!TEST_ptr(other_x509)) goto end; other_pkey = X509_get0_pubkey(other_x509); #ifdef OPENSSL_NO_ECDSA /* Can't get other_key if it's ECDSA */ if (other_pkey == NULL && idx_cert == 0 && (idx == 4 || idx == 6 || idx == 7)) { testresult = TEST_skip("EDCSA disabled"); goto end; } #endif switch (idx_prot) { case 0: #ifdef OSSL_NO_USABLE_TLS1_3 testresult = TEST_skip("TLSv1.3 disabled"); goto end; #else tls_version = TLS1_3_VERSION; break; #endif case 1: #ifdef OPENSSL_NO_TLS1_2 testresult = TEST_skip("TLSv1.2 disabled"); goto end; #else tls_version = TLS1_2_VERSION; break; #endif default: goto end; } if (idx == 15) { test_libctx = libctx; defctxnull = OSSL_PROVIDER_load(NULL, "null"); if (!TEST_ptr(defctxnull)) goto end; } if (!TEST_true(create_ssl_ctx_pair(test_libctx, TLS_server_method(), TLS_client_method(), tls_version, tls_version, &sctx, &cctx, NULL, NULL))) goto end; if (idx_server_server_rpk) if (!TEST_true(SSL_CTX_set1_server_cert_type(sctx, cert_type_rpk, sizeof(cert_type_rpk)))) goto end; if (idx_server_client_rpk) if (!TEST_true(SSL_CTX_set1_client_cert_type(sctx, cert_type_rpk, sizeof(cert_type_rpk)))) goto end; if (idx_client_server_rpk) if (!TEST_true(SSL_CTX_set1_server_cert_type(cctx, cert_type_rpk, sizeof(cert_type_rpk)))) goto end; if (idx_client_client_rpk) if (!TEST_true(SSL_CTX_set1_client_cert_type(cctx, cert_type_rpk, sizeof(cert_type_rpk)))) goto end; if (!TEST_true(SSL_CTX_set_session_id_context(sctx, SID_CTX, sizeof(SID_CTX)))) goto end; if (!TEST_true(SSL_CTX_set_session_id_context(cctx, SID_CTX, sizeof(SID_CTX)))) goto end; if (!TEST_int_gt(SSL_CTX_dane_enable(sctx), 0)) goto end; if (!TEST_int_gt(SSL_CTX_dane_enable(cctx), 0)) goto end; /* NEW */ SSL_CTX_set_verify(cctx, SSL_VERIFY_PEER, rpk_verify_client_cb); if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl, NULL, NULL))) goto end; if (!TEST_int_gt(SSL_dane_enable(serverssl, NULL), 0)) goto end; if (!TEST_int_gt(SSL_dane_enable(clientssl, "example.com"), 0)) goto end; /* Set private key and certificate */ if (!TEST_int_eq(SSL_use_PrivateKey_file(serverssl, privkey_file, SSL_FILETYPE_PEM), 1)) goto end; /* Only a private key */ if (idx == 1) { if (idx_server_server_rpk == 0 || idx_client_server_rpk == 0) expected = 0; } else { /* Add certificate */ if (!TEST_int_eq(SSL_use_certificate_file(serverssl, cert_file, SSL_FILETYPE_PEM), 1)) goto end; if (!TEST_int_eq(SSL_check_private_key(serverssl), 1)) goto end; } switch (idx) { default: if (!TEST_true(idx < RPK_TESTS)) goto end; break; case 0: if (!TEST_true(SSL_add_expected_rpk(clientssl, pkey))) goto end; break; case 1: if (!TEST_true(SSL_add_expected_rpk(clientssl, pkey))) goto end; break; case 2: if (!TEST_true(SSL_add_expected_rpk(clientssl, pkey))) goto end; if (!TEST_true(SSL_add_expected_rpk(serverssl, pkey))) goto end; /* Use the same key for client auth */ if (!TEST_int_eq(SSL_use_PrivateKey_file(clientssl, privkey_file, SSL_FILETYPE_PEM), 1)) goto end; if (!TEST_int_eq(SSL_use_certificate_file(clientssl, cert_file, SSL_FILETYPE_PEM), 1)) goto end; if (!TEST_int_eq(SSL_check_private_key(clientssl), 1)) goto end; SSL_set_verify(serverssl, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, rpk_verify_server_cb); client_auth = 1; break; case 3: if (!TEST_true(SSL_add_expected_rpk(clientssl, pkey))) goto end; if (!TEST_true(SSL_add_expected_rpk(clientssl, root_pkey))) goto end; break; case 4: if (!TEST_true(SSL_add_expected_rpk(clientssl, pkey))) goto end; if (!TEST_true(SSL_add_expected_rpk(clientssl, other_pkey))) goto end; break; case 5: if (!TEST_true(SSL_add_expected_rpk(clientssl, root_pkey))) goto end; if (!TEST_true(SSL_add_expected_rpk(clientssl, pkey))) goto end; break; case 6: if (!TEST_true(SSL_add_expected_rpk(clientssl, other_pkey))) goto end; if (!TEST_true(SSL_add_expected_rpk(clientssl, pkey))) goto end; break; case 7: if (idx_server_server_rpk == 1 && idx_client_server_rpk == 1) client_expected = -1; if (!TEST_true(SSL_add_expected_rpk(clientssl, other_pkey))) goto end; client_verify_result = X509_V_ERR_DANE_NO_MATCH; break; case 8: if (idx_server_server_rpk == 1 && idx_client_server_rpk == 1) client_expected = -1; /* no peer keys */ client_verify_result = X509_V_ERR_RPK_UNTRUSTED; break; case 9: if (tls_version != TLS1_3_VERSION) { testresult = TEST_skip("PHA requires TLSv1.3"); goto end; } if (!TEST_true(SSL_add_expected_rpk(clientssl, pkey))) goto end; if (!TEST_true(SSL_add_expected_rpk(serverssl, pkey))) goto end; /* Use the same key for client auth */ if (!TEST_int_eq(SSL_use_PrivateKey_file(clientssl, privkey_file, SSL_FILETYPE_PEM), 1)) goto end; if (!TEST_int_eq(SSL_use_certificate_file(clientssl, cert_file, SSL_FILETYPE_PEM), 1)) goto end; if (!TEST_int_eq(SSL_check_private_key(clientssl), 1)) goto end; SSL_set_verify(serverssl, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT | SSL_VERIFY_POST_HANDSHAKE, rpk_verify_server_cb); SSL_set_post_handshake_auth(clientssl, 1); client_auth = 1; break; case 10: if (!TEST_true(SSL_add_expected_rpk(clientssl, pkey))) goto end; if (!TEST_true(SSL_add_expected_rpk(serverssl, pkey))) goto end; /* Use the same key for client auth */ if (!TEST_int_eq(SSL_use_PrivateKey_file(clientssl, privkey_file, SSL_FILETYPE_PEM), 1)) goto end; /* Since there's no cert, this is expected to fail without RPK support */ if (!idx_server_client_rpk || !idx_client_client_rpk) expected = 0; SSL_set_verify(serverssl, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, rpk_verify_server_cb); client_auth = 1; break; case 11: if (!idx_server_server_rpk || !idx_client_server_rpk) { testresult = TEST_skip("Only testing resumption with server RPK"); goto end; } if (!TEST_true(SSL_add_expected_rpk(clientssl, pkey))) goto end; resumption = 1; break; case 12: if (!idx_server_server_rpk || !idx_client_server_rpk) { testresult = TEST_skip("Only testing resumption with server RPK"); goto end; } if (!TEST_true(SSL_add_expected_rpk(clientssl, pkey))) goto end; SSL_set_options(serverssl, SSL_OP_NO_TICKET); SSL_set_options(clientssl, SSL_OP_NO_TICKET); resumption = 1; break; case 13: if (!idx_server_server_rpk || !idx_client_server_rpk) { testresult = TEST_skip("Only testing resumption with server RPK"); goto end; } if (!idx_server_client_rpk || !idx_client_client_rpk) { testresult = TEST_skip("Only testing client authentication resumption with client RPK"); goto end; } if (!TEST_true(SSL_add_expected_rpk(clientssl, pkey))) goto end; if (!TEST_true(SSL_add_expected_rpk(serverssl, pkey))) goto end; /* Use the same key for client auth */ if (!TEST_int_eq(SSL_use_PrivateKey_file(clientssl, privkey_file, SSL_FILETYPE_PEM), 1)) goto end; if (!TEST_int_eq(SSL_use_certificate_file(clientssl, cert_file, SSL_FILETYPE_PEM), 1)) goto end; if (!TEST_int_eq(SSL_check_private_key(clientssl), 1)) goto end; SSL_set_verify(serverssl, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, rpk_verify_server_cb); client_auth = 1; resumption = 1; break; case 14: if (!idx_server_server_rpk || !idx_client_server_rpk) { testresult = TEST_skip("Only testing resumption with server RPK"); goto end; } if (!idx_server_client_rpk || !idx_client_client_rpk) { testresult = TEST_skip("Only testing client authentication resumption with client RPK"); goto end; } if (!TEST_true(SSL_add_expected_rpk(clientssl, pkey))) goto end; if (!TEST_true(SSL_add_expected_rpk(serverssl, pkey))) goto end; /* Use the same key for client auth */ if (!TEST_int_eq(SSL_use_PrivateKey_file(clientssl, privkey_file, SSL_FILETYPE_PEM), 1)) goto end; if (!TEST_int_eq(SSL_use_certificate_file(clientssl, cert_file, SSL_FILETYPE_PEM), 1)) goto end; if (!TEST_int_eq(SSL_check_private_key(clientssl), 1)) goto end; SSL_set_verify(serverssl, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, rpk_verify_server_cb); SSL_set_options(serverssl, SSL_OP_NO_TICKET); SSL_set_options(clientssl, SSL_OP_NO_TICKET); client_auth = 1; resumption = 1; break; case 15: if (!TEST_true(SSL_add_expected_rpk(clientssl, pkey))) goto end; break; } ret = create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE); if (!TEST_int_eq(expected, ret)) goto end; /* Make sure client gets RPK or certificate as configured */ if (expected == 1) { if (idx_server_server_rpk && idx_client_server_rpk) { if (!TEST_long_eq(SSL_get_verify_result(clientssl), client_verify_result)) goto end; if (!TEST_ptr(SSL_get0_peer_rpk(clientssl))) goto end; if (!TEST_int_eq(SSL_get_negotiated_server_cert_type(serverssl), TLSEXT_cert_type_rpk)) goto end; if (!TEST_int_eq(SSL_get_negotiated_server_cert_type(clientssl), TLSEXT_cert_type_rpk)) goto end; } else { if (!TEST_ptr(SSL_get0_peer_certificate(clientssl))) goto end; if (!TEST_int_eq(SSL_get_negotiated_server_cert_type(serverssl), TLSEXT_cert_type_x509)) goto end; if (!TEST_int_eq(SSL_get_negotiated_server_cert_type(clientssl), TLSEXT_cert_type_x509)) goto end; } } if (idx == 9) { /* Make PHA happen... */ if (!TEST_true(SSL_verify_client_post_handshake(serverssl))) goto end; if (!TEST_true(SSL_do_handshake(serverssl))) goto end; if (!TEST_int_le(SSL_read(clientssl, NULL, 0), 0)) goto end; if (!TEST_int_le(SSL_read(serverssl, NULL, 0), 0)) goto end; } /* Make sure server gets an RPK or certificate as configured */ if (client_auth) { if (idx_server_client_rpk && idx_client_client_rpk) { if (!TEST_long_eq(SSL_get_verify_result(serverssl), server_verify_result)) goto end; if (!TEST_ptr(SSL_get0_peer_rpk(serverssl))) goto end; if (!TEST_int_eq(SSL_get_negotiated_client_cert_type(serverssl), TLSEXT_cert_type_rpk)) goto end; if (!TEST_int_eq(SSL_get_negotiated_client_cert_type(clientssl), TLSEXT_cert_type_rpk)) goto end; } else { /* only if connection is expected to succeed */ if (expected == 1 && !TEST_ptr(SSL_get0_peer_certificate(serverssl))) goto end; if (!TEST_int_eq(SSL_get_negotiated_client_cert_type(serverssl), TLSEXT_cert_type_x509)) goto end; if (!TEST_int_eq(SSL_get_negotiated_client_cert_type(clientssl), TLSEXT_cert_type_x509)) goto end; } } if (resumption) { EVP_PKEY *client_pkey = NULL; EVP_PKEY *server_pkey = NULL; if (!TEST_ptr((client_sess = SSL_get1_session(clientssl))) || !TEST_ptr((client_pkey = SSL_SESSION_get0_peer_rpk(client_sess)))) goto end; if (client_auth) { if (!TEST_ptr((server_sess = SSL_get1_session(serverssl))) || !TEST_ptr((server_pkey = SSL_SESSION_get0_peer_rpk(server_sess)))) goto end; } SSL_shutdown(clientssl); SSL_shutdown(serverssl); SSL_free(clientssl); SSL_free(serverssl); serverssl = clientssl = NULL; if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl, NULL, NULL)) || !TEST_true(SSL_set_session(clientssl, client_sess))) goto end; /* Set private key (and maybe certificate) */ if (!TEST_int_eq(SSL_use_PrivateKey_file(serverssl, privkey_file, SSL_FILETYPE_PEM), 1)) goto end; if (!TEST_int_eq(SSL_use_certificate_file(serverssl, cert_file, SSL_FILETYPE_PEM), 1)) goto end; if (!TEST_int_eq(SSL_check_private_key(serverssl), 1)) goto end; if (!TEST_int_gt(SSL_dane_enable(serverssl, "example.com"), 0)) goto end; if (!TEST_int_gt(SSL_dane_enable(clientssl, "example.com"), 0)) goto end; switch (idx) { default: break; case 11: if (!TEST_true(SSL_add_expected_rpk(clientssl, client_pkey))) goto end; break; case 12: if (!TEST_true(SSL_add_expected_rpk(clientssl, client_pkey))) goto end; SSL_set_options(clientssl, SSL_OP_NO_TICKET); SSL_set_options(serverssl, SSL_OP_NO_TICKET); break; case 13: if (!TEST_true(SSL_add_expected_rpk(clientssl, client_pkey))) goto end; if (!TEST_true(SSL_add_expected_rpk(serverssl, server_pkey))) goto end; /* Use the same key for client auth */ if (!TEST_int_eq(SSL_use_PrivateKey_file(clientssl, privkey_file, SSL_FILETYPE_PEM), 1)) goto end; if (!TEST_int_eq(SSL_use_certificate_file(clientssl, cert_file, SSL_FILETYPE_PEM), 1)) goto end; if (!TEST_int_eq(SSL_check_private_key(clientssl), 1)) goto end; SSL_set_verify(serverssl, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, rpk_verify_server_cb); break; case 14: if (!TEST_true(SSL_add_expected_rpk(clientssl, client_pkey))) goto end; if (!TEST_true(SSL_add_expected_rpk(serverssl, server_pkey))) goto end; /* Use the same key for client auth */ if (!TEST_int_eq(SSL_use_PrivateKey_file(clientssl, privkey_file, SSL_FILETYPE_PEM), 1)) goto end; if (!TEST_int_eq(SSL_use_certificate_file(clientssl, cert_file, SSL_FILETYPE_PEM), 1)) goto end; if (!TEST_int_eq(SSL_check_private_key(clientssl), 1)) goto end; SSL_set_verify(serverssl, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, rpk_verify_server_cb); SSL_set_options(serverssl, SSL_OP_NO_TICKET); SSL_set_options(clientssl, SSL_OP_NO_TICKET); break; } ret = create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE); if (!TEST_int_eq(expected, ret)) goto end; verify = SSL_get_verify_result(clientssl); if (!TEST_int_eq(client_expected, verify)) goto end; if (!TEST_true(SSL_session_reused(clientssl))) goto end; if (!TEST_ptr(SSL_get0_peer_rpk(clientssl))) goto end; if (!TEST_int_eq(SSL_get_negotiated_server_cert_type(serverssl), TLSEXT_cert_type_rpk)) goto end; if (!TEST_int_eq(SSL_get_negotiated_server_cert_type(clientssl), TLSEXT_cert_type_rpk)) goto end; if (client_auth) { if (!TEST_ptr(SSL_get0_peer_rpk(serverssl))) goto end; if (!TEST_int_eq(SSL_get_negotiated_client_cert_type(serverssl), TLSEXT_cert_type_rpk)) goto end; if (!TEST_int_eq(SSL_get_negotiated_client_cert_type(clientssl), TLSEXT_cert_type_rpk)) goto end; } } testresult = 1; end: OSSL_PROVIDER_unload(defctxnull); defctxnull = NULL; SSL_SESSION_free(client_sess); SSL_SESSION_free(server_sess); SSL_free(serverssl); SSL_free(clientssl); SSL_CTX_free(sctx); SSL_CTX_free(cctx); X509_free(x509); X509_free(other_x509); X509_free(root_x509); if (testresult == 0) { TEST_info("idx_ss_rpk=%d, idx_sc_rpk=%d, idx_cs_rpk=%d, idx_cc_rpk=%d, idx_cert=%d, idx_prot=%d, idx=%d", idx_server_server_rpk, idx_server_client_rpk, idx_client_server_rpk, idx_client_client_rpk, idx_cert, idx_prot, idx); } return testresult; } static int test_rpk_api(void) { int ret = 0; SSL_CTX *cctx = NULL, *sctx = NULL; unsigned char cert_type_dups[] = { TLSEXT_cert_type_rpk, TLSEXT_cert_type_x509, TLSEXT_cert_type_x509 }; unsigned char cert_type_bad[] = { 0xFF }; unsigned char cert_type_extra[] = { TLSEXT_cert_type_rpk, TLSEXT_cert_type_x509, 0xFF }; unsigned char cert_type_unsup[] = { TLSEXT_cert_type_pgp, TLSEXT_cert_type_1609dot2 }; unsigned char cert_type_just_x509[] = { TLSEXT_cert_type_x509 }; unsigned char cert_type_just_rpk[] = { TLSEXT_cert_type_rpk }; if (!TEST_true(create_ssl_ctx_pair(NULL, TLS_server_method(), TLS_client_method(), TLS1_2_VERSION, TLS1_2_VERSION, &sctx, &cctx, NULL, NULL))) goto end; if (!TEST_false(SSL_CTX_set1_server_cert_type(sctx, cert_type_dups, sizeof(cert_type_dups)))) goto end; if (!TEST_false(SSL_CTX_set1_server_cert_type(sctx, cert_type_bad, sizeof(cert_type_bad)))) goto end; if (!TEST_false(SSL_CTX_set1_server_cert_type(sctx, cert_type_extra, sizeof(cert_type_extra)))) goto end; if (!TEST_false(SSL_CTX_set1_server_cert_type(sctx, cert_type_unsup, sizeof(cert_type_unsup)))) goto end; if (!TEST_true(SSL_CTX_set1_server_cert_type(sctx, cert_type_just_x509, sizeof(cert_type_just_x509)))) goto end; if (!TEST_true(SSL_CTX_set1_server_cert_type(sctx, cert_type_just_rpk, sizeof(cert_type_just_rpk)))) goto end; ret = 1; end: SSL_CTX_free(sctx); SSL_CTX_free(cctx); return ret; } OPT_TEST_DECLARE_USAGE("certdir\n") int setup_tests(void) { if (!test_skip_common_options()) { TEST_error("Error parsing test options\n"); return 0; } if (!TEST_ptr(certsdir = test_get_argument(0))) return 0; rootcert = test_mk_file_path(certsdir, "rootcert.pem"); if (rootcert == NULL) goto err; cert = test_mk_file_path(certsdir, "servercert.pem"); if (cert == NULL) goto err; privkey = test_mk_file_path(certsdir, "serverkey.pem"); if (privkey == NULL) goto err; cert2 = test_mk_file_path(certsdir, "server-ecdsa-cert.pem"); if (cert2 == NULL) goto err; privkey2 = test_mk_file_path(certsdir, "server-ecdsa-key.pem"); if (privkey2 == NULL) goto err; cert448 = test_mk_file_path(certsdir, "server-ed448-cert.pem"); if (cert2 == NULL) goto err; privkey448 = test_mk_file_path(certsdir, "server-ed448-key.pem"); if (privkey2 == NULL) goto err; cert25519 = test_mk_file_path(certsdir, "server-ed25519-cert.pem"); if (cert2 == NULL) goto err; privkey25519 = test_mk_file_path(certsdir, "server-ed25519-key.pem"); if (privkey2 == NULL) goto err; libctx = OSSL_LIB_CTX_new(); if (libctx == NULL) goto err; ADD_TEST(test_rpk_api); ADD_ALL_TESTS(test_rpk, RPK_TESTS * RPK_DIMS); return 1; err: return 0; } void cleanup_tests(void) { OPENSSL_free(rootcert); OPENSSL_free(cert); OPENSSL_free(privkey); OPENSSL_free(cert2); OPENSSL_free(privkey2); OPENSSL_free(cert448); OPENSSL_free(privkey448); OPENSSL_free(cert25519); OPENSSL_free(privkey25519); OSSL_LIB_CTX_free(libctx); }
./openssl/test/bn_rand_range.h
/* * WARNING: do not edit! * Generated by statistics/bn_rand_range.py in the OpenSSL tool repository. * * Copyright 2019 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ static const struct { unsigned int range; unsigned int iterations; double critical; } rand_range_cases[] = { { 2, 200, 3.841459 }, { 3, 300, 5.991465 }, { 4, 400, 7.814728 }, { 5, 500, 9.487729 }, { 6, 600, 11.070498 }, { 7, 700, 12.591587 }, { 8, 800, 14.067140 }, { 9, 900, 15.507313 }, { 10, 1000, 16.918978 }, { 11, 1100, 18.307038 }, { 12, 1200, 19.675138 }, { 13, 1300, 21.026070 }, { 14, 1400, 22.362032 }, { 15, 1500, 23.684791 }, { 16, 1600, 24.995790 }, { 17, 1700, 26.296228 }, { 18, 1800, 27.587112 }, { 19, 1900, 28.869299 }, { 20, 2000, 30.143527 }, { 30, 3000, 42.556968 }, { 40, 4000, 54.572228 }, { 50, 5000, 66.338649 }, { 60, 6000, 77.930524 }, { 70, 7000, 89.391208 }, { 80, 8000, 100.748619 }, { 90, 9000, 112.021986 }, { 100, 10000, 123.225221 }, { 1000, 10000, 1073.642651 }, { 2000, 20000, 2104.128222 }, { 3000, 30000, 3127.515432 }, { 4000, 40000, 4147.230012 }, { 5000, 50000, 5164.598069 }, { 6000, 60000, 6180.299514 }, { 7000, 70000, 7194.738181 }, { 8000, 80000, 8208.177159 }, { 9000, 90000, 9220.799176 }, { 10000, 100000, 10232.737266 }, }; static const int binomial_critical = 29;
./openssl/test/d2i_test.c
/* * Copyright 2016-2020 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ /* Regression tests for ASN.1 parsing bugs. */ #include <stdio.h> #include <string.h> #include "testutil.h" #include <openssl/asn1.h> #include <openssl/asn1t.h> #include <openssl/bio.h> #include <openssl/err.h> #include <openssl/x509.h> #include <openssl/x509v3.h> #include "internal/nelem.h" static const ASN1_ITEM *item_type; static const char *test_file; typedef enum { ASN1_UNKNOWN, ASN1_OK, ASN1_BIO, ASN1_DECODE, ASN1_ENCODE, ASN1_COMPARE } expected_error_t; typedef struct { const char *str; expected_error_t code; } error_enum; static expected_error_t expected_error = ASN1_UNKNOWN; static int test_bad_asn1(void) { BIO *bio = NULL; ASN1_VALUE *value = NULL; int ret = 0; unsigned char buf[2048]; const unsigned char *buf_ptr = buf; unsigned char *der = NULL; int derlen; int len; bio = BIO_new_file(test_file, "r"); if (!TEST_ptr(bio)) return 0; if (expected_error == ASN1_BIO) { if (TEST_ptr_null(ASN1_item_d2i_bio(item_type, bio, NULL))) ret = 1; goto err; } /* * Unless we are testing it we don't use ASN1_item_d2i_bio because it * performs sanity checks on the input and can reject it before the * decoder is called. */ len = BIO_read(bio, buf, sizeof(buf)); if (!TEST_int_ge(len, 0)) goto err; value = ASN1_item_d2i(NULL, &buf_ptr, len, item_type); if (value == NULL) { if (TEST_int_eq(expected_error, ASN1_DECODE)) ret = 1; goto err; } derlen = ASN1_item_i2d(value, &der, item_type); if (der == NULL || derlen < 0) { if (TEST_int_eq(expected_error, ASN1_ENCODE)) ret = 1; goto err; } if (derlen != len || memcmp(der, buf, derlen) != 0) { if (TEST_int_eq(expected_error, ASN1_COMPARE)) ret = 1; goto err; } if (TEST_int_eq(expected_error, ASN1_OK)) ret = 1; err: /* Don't indicate success for memory allocation errors */ if (ret == 1 && !TEST_false(ERR_GET_REASON(ERR_peek_error()) == ERR_R_MALLOC_FAILURE)) ret = 0; BIO_free(bio); OPENSSL_free(der); ASN1_item_free(value, item_type); return ret; } OPT_TEST_DECLARE_USAGE("item_name expected_error test_file.der\n") /* * Usage: d2i_test <name> <type> <file>, e.g. * d2i_test generalname bad_generalname.der */ int setup_tests(void) { const char *test_type_name; const char *expected_error_string; size_t i; static error_enum expected_errors[] = { {"OK", ASN1_OK}, {"BIO", ASN1_BIO}, {"decode", ASN1_DECODE}, {"encode", ASN1_ENCODE}, {"compare", ASN1_COMPARE} }; if (!test_skip_common_options()) { TEST_error("Error parsing test options\n"); return 0; } if (!TEST_ptr(test_type_name = test_get_argument(0)) || !TEST_ptr(expected_error_string = test_get_argument(1)) || !TEST_ptr(test_file = test_get_argument(2))) return 0; item_type = ASN1_ITEM_lookup(test_type_name); if (item_type == NULL) { TEST_error("Unknown type %s", test_type_name); TEST_note("Supported types:"); for (i = 0;; i++) { const ASN1_ITEM *it = ASN1_ITEM_get(i); if (it == NULL) break; TEST_note("\t%s", it->sname); } return 0; } for (i = 0; i < OSSL_NELEM(expected_errors); i++) { if (strcmp(expected_errors[i].str, expected_error_string) == 0) { expected_error = expected_errors[i].code; break; } } if (expected_error == ASN1_UNKNOWN) { TEST_error("Unknown expected error %s\n", expected_error_string); return 0; } ADD_TEST(test_bad_asn1); return 1; }
./openssl/test/list_test.c
/* * Copyright 2022 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <stdio.h> #include <string.h> #include <openssl/opensslconf.h> #include <openssl/err.h> #include <openssl/crypto.h> #include "internal/list.h" #include "internal/nelem.h" #include "testutil.h" typedef struct testl_st TESTL; struct testl_st { int n; OSSL_LIST_MEMBER(fizz, TESTL); OSSL_LIST_MEMBER(buzz, TESTL); }; DEFINE_LIST_OF(fizz, TESTL); DEFINE_LIST_OF(buzz, TESTL); static int test_fizzbuzz(void) { OSSL_LIST(fizz) a; OSSL_LIST(buzz) b; TESTL elem[20]; const int nelem = OSSL_NELEM(elem); int i, na = 0, nb = 0; ossl_list_fizz_init(&a); ossl_list_buzz_init(&b); if (!TEST_true(ossl_list_fizz_is_empty(&a))) return 0; for (i = 1; i < nelem; i++) { ossl_list_fizz_init_elem(elem + i); ossl_list_buzz_init_elem(elem + i); elem[i].n = i; if (i % 3 == 0) { ossl_list_fizz_insert_tail(&a, elem + i); na++; } if (i % 5 == 0) { ossl_list_buzz_insert_head(&b, elem + i); nb++; } } if (!TEST_false(ossl_list_fizz_is_empty(&a)) || !TEST_size_t_eq(ossl_list_fizz_num(&a), na) || !TEST_size_t_eq(ossl_list_buzz_num(&b), nb) || !TEST_ptr(ossl_list_fizz_head(&a)) || !TEST_ptr(ossl_list_fizz_tail(&a)) || !TEST_ptr(ossl_list_buzz_head(&b)) || !TEST_ptr(ossl_list_buzz_tail(&b)) || !TEST_int_eq(ossl_list_fizz_head(&a)->n, 3) || !TEST_int_eq(ossl_list_fizz_tail(&a)->n, na * 3) || !TEST_int_eq(ossl_list_buzz_head(&b)->n, nb * 5) || !TEST_int_eq(ossl_list_buzz_tail(&b)->n, 5)) return 0; ossl_list_fizz_remove(&a, ossl_list_fizz_head(&a)); ossl_list_buzz_remove(&b, ossl_list_buzz_tail(&b)); if (!TEST_size_t_eq(ossl_list_fizz_num(&a), --na) || !TEST_size_t_eq(ossl_list_buzz_num(&b), --nb) || !TEST_ptr(ossl_list_fizz_head(&a)) || !TEST_ptr(ossl_list_buzz_tail(&b)) || !TEST_int_eq(ossl_list_fizz_head(&a)->n, 6) || !TEST_int_eq(ossl_list_buzz_tail(&b)->n, 10) || !TEST_ptr(ossl_list_fizz_next(ossl_list_fizz_head(&a))) || !TEST_ptr(ossl_list_fizz_prev(ossl_list_fizz_tail(&a))) || !TEST_int_eq(ossl_list_fizz_next(ossl_list_fizz_head(&a))->n, 9) || !TEST_int_eq(ossl_list_fizz_prev(ossl_list_fizz_tail(&a))->n, 15)) return 0; return 1; } typedef struct int_st INTL; struct int_st { int n; OSSL_LIST_MEMBER(int, INTL); }; DEFINE_LIST_OF(int, INTL); static int test_insert(void) { INTL *c, *d; OSSL_LIST(int) l; INTL elem[20]; size_t i; int n = 1; ossl_list_int_init(&l); for (i = 0; i < OSSL_NELEM(elem); i++) { ossl_list_int_init_elem(elem + i); elem[i].n = i; } /* Check various insert options - head, tail, middle */ ossl_list_int_insert_head(&l, elem + 3); /* 3 */ ossl_list_int_insert_tail(&l, elem + 6); /* 3 6 */ ossl_list_int_insert_before(&l, elem + 6, elem + 5); /* 3 5 6 */ ossl_list_int_insert_before(&l, elem + 3, elem + 1); /* 1 3 5 6 */ ossl_list_int_insert_after(&l, elem + 1, elem + 2); /* 1 2 3 5 6 */ ossl_list_int_insert_after(&l, elem + 6, elem + 7); /* 1 2 3 5 6 7 */ ossl_list_int_insert_after(&l, elem + 3, elem + 4); /* 1 2 3 4 5 6 7 */ if (!TEST_size_t_eq(ossl_list_int_num(&l), 7)) return 0; c = ossl_list_int_head(&l); d = ossl_list_int_tail(&l); while (c != NULL && d != NULL) { if (!TEST_int_eq(c->n, n) || !TEST_int_eq(d->n, 8 - n)) return 0; c = ossl_list_int_next(c); d = ossl_list_int_prev(d); n++; } if (!TEST_ptr_null(c) || !TEST_ptr_null(d)) return 0; /* Check removing head, tail and middle */ ossl_list_int_remove(&l, elem + 1); /* 2 3 4 5 6 7 */ ossl_list_int_remove(&l, elem + 6); /* 2 3 4 5 7 */ ossl_list_int_remove(&l, elem + 7); /* 2 3 4 5 */ n = 2; c = ossl_list_int_head(&l); d = ossl_list_int_tail(&l); while (c != NULL && d != NULL) { if (!TEST_int_eq(c->n, n) || !TEST_int_eq(d->n, 7 - n)) return 0; c = ossl_list_int_next(c); d = ossl_list_int_prev(d); n++; } if (!TEST_ptr_null(c) || !TEST_ptr_null(d)) return 0; /* Check removing the head of a two element list works */ ossl_list_int_remove(&l, elem + 2); /* 3 4 5 */ ossl_list_int_remove(&l, elem + 4); /* 3 5 */ ossl_list_int_remove(&l, elem + 3); /* 5 */ if (!TEST_ptr(ossl_list_int_head(&l)) || !TEST_ptr(ossl_list_int_tail(&l)) || !TEST_int_eq(ossl_list_int_head(&l)->n, 5) || !TEST_int_eq(ossl_list_int_tail(&l)->n, 5)) return 0; /* Check removing the tail of a two element list works */ ossl_list_int_insert_head(&l, elem); /* 0 5 */ ossl_list_int_remove(&l, elem + 5); /* 0 */ if (!TEST_ptr(ossl_list_int_head(&l)) || !TEST_ptr(ossl_list_int_tail(&l)) || !TEST_int_eq(ossl_list_int_head(&l)->n, 0) || !TEST_int_eq(ossl_list_int_tail(&l)->n, 0)) return 0; /* Check removing the only element works */ ossl_list_int_remove(&l, elem); if (!TEST_ptr_null(ossl_list_int_head(&l)) || !TEST_ptr_null(ossl_list_int_tail(&l))) return 0; return 1; } int setup_tests(void) { ADD_TEST(test_fizzbuzz); ADD_TEST(test_insert); return 1; }
./openssl/test/fake_rsaprov.c
/* * Copyright 2021-2023 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * https://www.openssl.org/source/license.html * or in the file LICENSE in the source distribution. */ #include <string.h> #include <openssl/core_names.h> #include <openssl/core_object.h> #include <openssl/rand.h> #include <openssl/provider.h> #include "testutil.h" #include "fake_rsaprov.h" static OSSL_FUNC_keymgmt_new_fn fake_rsa_keymgmt_new; static OSSL_FUNC_keymgmt_free_fn fake_rsa_keymgmt_free; static OSSL_FUNC_keymgmt_has_fn fake_rsa_keymgmt_has; static OSSL_FUNC_keymgmt_query_operation_name_fn fake_rsa_keymgmt_query; static OSSL_FUNC_keymgmt_import_fn fake_rsa_keymgmt_import; static OSSL_FUNC_keymgmt_import_types_fn fake_rsa_keymgmt_imptypes; static OSSL_FUNC_keymgmt_export_fn fake_rsa_keymgmt_export; static OSSL_FUNC_keymgmt_export_types_fn fake_rsa_keymgmt_exptypes; static OSSL_FUNC_keymgmt_load_fn fake_rsa_keymgmt_load; static int has_selection; static int imptypes_selection; static int exptypes_selection; static int query_id; static int key_deleted; struct fake_rsa_keydata { int selection; int status; }; void fake_rsa_restore_store_state(void) { key_deleted = 0; } static void *fake_rsa_keymgmt_new(void *provctx) { struct fake_rsa_keydata *key; if (!TEST_ptr(key = OPENSSL_zalloc(sizeof(struct fake_rsa_keydata)))) return NULL; /* clear test globals */ has_selection = 0; imptypes_selection = 0; exptypes_selection = 0; query_id = 0; return key; } static void fake_rsa_keymgmt_free(void *keydata) { OPENSSL_free(keydata); } static int fake_rsa_keymgmt_has(const void *key, int selection) { /* record global for checking */ has_selection = selection; return 1; } static const char *fake_rsa_keymgmt_query(int id) { /* record global for checking */ query_id = id; return "RSA"; } static int fake_rsa_keymgmt_import(void *keydata, int selection, const OSSL_PARAM *p) { struct fake_rsa_keydata *fake_rsa_key = keydata; /* key was imported */ fake_rsa_key->status = 1; return 1; } static unsigned char fake_rsa_n[] = "\x00\xAA\x36\xAB\xCE\x88\xAC\xFD\xFF\x55\x52\x3C\x7F\xC4\x52\x3F" "\x90\xEF\xA0\x0D\xF3\x77\x4A\x25\x9F\x2E\x62\xB4\xC5\xD9\x9C\xB5" "\xAD\xB3\x00\xA0\x28\x5E\x53\x01\x93\x0E\x0C\x70\xFB\x68\x76\x93" "\x9C\xE6\x16\xCE\x62\x4A\x11\xE0\x08\x6D\x34\x1E\xBC\xAC\xA0\xA1" "\xF5"; static unsigned char fake_rsa_e[] = "\x11"; static unsigned char fake_rsa_d[] = "\x0A\x03\x37\x48\x62\x64\x87\x69\x5F\x5F\x30\xBC\x38\xB9\x8B\x44" "\xC2\xCD\x2D\xFF\x43\x40\x98\xCD\x20\xD8\xA1\x38\xD0\x90\xBF\x64" "\x79\x7C\x3F\xA7\xA2\xCD\xCB\x3C\xD1\xE0\xBD\xBA\x26\x54\xB4\xF9" "\xDF\x8E\x8A\xE5\x9D\x73\x3D\x9F\x33\xB3\x01\x62\x4A\xFD\x1D\x51"; static unsigned char fake_rsa_p[] = "\x00\xD8\x40\xB4\x16\x66\xB4\x2E\x92\xEA\x0D\xA3\xB4\x32\x04\xB5" "\xCF\xCE\x33\x52\x52\x4D\x04\x16\xA5\xA4\x41\xE7\x00\xAF\x46\x12" "\x0D"; static unsigned char fake_rsa_q[] = "\x00\xC9\x7F\xB1\xF0\x27\xF4\x53\xF6\x34\x12\x33\xEA\xAA\xD1\xD9" "\x35\x3F\x6C\x42\xD0\x88\x66\xB1\xD0\x5A\x0F\x20\x35\x02\x8B\x9D" "\x89"; static unsigned char fake_rsa_dmp1[] = "\x59\x0B\x95\x72\xA2\xC2\xA9\xC4\x06\x05\x9D\xC2\xAB\x2F\x1D\xAF" "\xEB\x7E\x8B\x4F\x10\xA7\x54\x9E\x8E\xED\xF5\xB4\xFC\xE0\x9E\x05"; static unsigned char fake_rsa_dmq1[] = "\x00\x8E\x3C\x05\x21\xFE\x15\xE0\xEA\x06\xA3\x6F\xF0\xF1\x0C\x99" "\x52\xC3\x5B\x7A\x75\x14\xFD\x32\x38\xB8\x0A\xAD\x52\x98\x62\x8D" "\x51"; static unsigned char fake_rsa_iqmp[] = "\x36\x3F\xF7\x18\x9D\xA8\xE9\x0B\x1D\x34\x1F\x71\xD0\x9B\x76\xA8" "\xA9\x43\xE1\x1D\x10\xB2\x4D\x24\x9F\x2D\xEA\xFE\xF8\x0C\x18\x26"; OSSL_PARAM *fake_rsa_key_params(int priv) { if (priv) { OSSL_PARAM params[] = { OSSL_PARAM_BN(OSSL_PKEY_PARAM_RSA_N, fake_rsa_n, sizeof(fake_rsa_n) -1), OSSL_PARAM_BN(OSSL_PKEY_PARAM_RSA_E, fake_rsa_e, sizeof(fake_rsa_e) -1), OSSL_PARAM_BN(OSSL_PKEY_PARAM_RSA_D, fake_rsa_d, sizeof(fake_rsa_d) -1), OSSL_PARAM_BN(OSSL_PKEY_PARAM_RSA_FACTOR1, fake_rsa_p, sizeof(fake_rsa_p) -1), OSSL_PARAM_BN(OSSL_PKEY_PARAM_RSA_FACTOR2, fake_rsa_q, sizeof(fake_rsa_q) -1), OSSL_PARAM_BN(OSSL_PKEY_PARAM_RSA_EXPONENT1, fake_rsa_dmp1, sizeof(fake_rsa_dmp1) -1), OSSL_PARAM_BN(OSSL_PKEY_PARAM_RSA_EXPONENT2, fake_rsa_dmq1, sizeof(fake_rsa_dmq1) -1), OSSL_PARAM_BN(OSSL_PKEY_PARAM_RSA_COEFFICIENT1, fake_rsa_iqmp, sizeof(fake_rsa_iqmp) -1), OSSL_PARAM_END }; return OSSL_PARAM_dup(params); } else { OSSL_PARAM params[] = { OSSL_PARAM_BN(OSSL_PKEY_PARAM_RSA_N, fake_rsa_n, sizeof(fake_rsa_n) -1), OSSL_PARAM_BN(OSSL_PKEY_PARAM_RSA_E, fake_rsa_e, sizeof(fake_rsa_e) -1), OSSL_PARAM_END }; return OSSL_PARAM_dup(params); } } static int fake_rsa_keymgmt_export(void *keydata, int selection, OSSL_CALLBACK *param_callback, void *cbarg) { OSSL_PARAM *params = NULL; int ret; if (selection & OSSL_KEYMGMT_SELECT_PRIVATE_KEY) return 0; if (!TEST_ptr(params = fake_rsa_key_params(0))) return 0; ret = param_callback(params, cbarg); OSSL_PARAM_free(params); return ret; } static const OSSL_PARAM fake_rsa_import_key_types[] = { OSSL_PARAM_BN(OSSL_PKEY_PARAM_RSA_N, NULL, 0), OSSL_PARAM_BN(OSSL_PKEY_PARAM_RSA_E, NULL, 0), OSSL_PARAM_BN(OSSL_PKEY_PARAM_RSA_D, NULL, 0), OSSL_PARAM_BN(OSSL_PKEY_PARAM_RSA_FACTOR1, NULL, 0), OSSL_PARAM_BN(OSSL_PKEY_PARAM_RSA_FACTOR2, NULL, 0), OSSL_PARAM_BN(OSSL_PKEY_PARAM_RSA_EXPONENT1, NULL, 0), OSSL_PARAM_BN(OSSL_PKEY_PARAM_RSA_EXPONENT2, NULL, 0), OSSL_PARAM_BN(OSSL_PKEY_PARAM_RSA_COEFFICIENT1, NULL, 0), OSSL_PARAM_END }; static const OSSL_PARAM *fake_rsa_keymgmt_imptypes(int selection) { /* record global for checking */ imptypes_selection = selection; return fake_rsa_import_key_types; } static const OSSL_PARAM fake_rsa_export_key_types[] = { OSSL_PARAM_BN(OSSL_PKEY_PARAM_RSA_N, NULL, 0), OSSL_PARAM_BN(OSSL_PKEY_PARAM_RSA_E, NULL, 0), OSSL_PARAM_END }; static const OSSL_PARAM *fake_rsa_keymgmt_exptypes(int selection) { /* record global for checking */ exptypes_selection = selection; return fake_rsa_export_key_types; } static void *fake_rsa_keymgmt_load(const void *reference, size_t reference_sz) { struct fake_rsa_keydata *key = NULL; if (reference_sz != sizeof(*key)) return NULL; key = *(struct fake_rsa_keydata **)reference; if (key->status != 1) return NULL; /* detach the reference */ *(struct fake_rsa_keydata **)reference = NULL; return key; } static void *fake_rsa_gen_init(void *provctx, int selection, const OSSL_PARAM params[]) { unsigned char *gctx = NULL; if (!TEST_ptr(gctx = OPENSSL_malloc(1))) return NULL; *gctx = 1; return gctx; } static void *fake_rsa_gen(void *genctx, OSSL_CALLBACK *osslcb, void *cbarg) { unsigned char *gctx = genctx; static const unsigned char inited[] = { 1 }; struct fake_rsa_keydata *keydata; if (!TEST_ptr(gctx) || !TEST_mem_eq(gctx, sizeof(*gctx), inited, sizeof(inited))) return NULL; if (!TEST_ptr(keydata = fake_rsa_keymgmt_new(NULL))) return NULL; keydata->status = 2; return keydata; } static void fake_rsa_gen_cleanup(void *genctx) { OPENSSL_free(genctx); } static const OSSL_DISPATCH fake_rsa_keymgmt_funcs[] = { { OSSL_FUNC_KEYMGMT_NEW, (void (*)(void))fake_rsa_keymgmt_new }, { OSSL_FUNC_KEYMGMT_FREE, (void (*)(void))fake_rsa_keymgmt_free} , { OSSL_FUNC_KEYMGMT_HAS, (void (*)(void))fake_rsa_keymgmt_has }, { OSSL_FUNC_KEYMGMT_QUERY_OPERATION_NAME, (void (*)(void))fake_rsa_keymgmt_query }, { OSSL_FUNC_KEYMGMT_IMPORT, (void (*)(void))fake_rsa_keymgmt_import }, { OSSL_FUNC_KEYMGMT_IMPORT_TYPES, (void (*)(void))fake_rsa_keymgmt_imptypes }, { OSSL_FUNC_KEYMGMT_EXPORT, (void (*)(void))fake_rsa_keymgmt_export }, { OSSL_FUNC_KEYMGMT_EXPORT_TYPES, (void (*)(void))fake_rsa_keymgmt_exptypes }, { OSSL_FUNC_KEYMGMT_LOAD, (void (*)(void))fake_rsa_keymgmt_load }, { OSSL_FUNC_KEYMGMT_GEN_INIT, (void (*)(void))fake_rsa_gen_init }, { OSSL_FUNC_KEYMGMT_GEN, (void (*)(void))fake_rsa_gen }, { OSSL_FUNC_KEYMGMT_GEN_CLEANUP, (void (*)(void))fake_rsa_gen_cleanup }, OSSL_DISPATCH_END }; static const OSSL_ALGORITHM fake_rsa_keymgmt_algs[] = { { "RSA:rsaEncryption", "provider=fake-rsa", fake_rsa_keymgmt_funcs, "Fake RSA Key Management" }, { NULL, NULL, NULL, NULL } }; static OSSL_FUNC_signature_newctx_fn fake_rsa_sig_newctx; static OSSL_FUNC_signature_freectx_fn fake_rsa_sig_freectx; static OSSL_FUNC_signature_sign_init_fn fake_rsa_sig_sign_init; static OSSL_FUNC_signature_sign_fn fake_rsa_sig_sign; static void *fake_rsa_sig_newctx(void *provctx, const char *propq) { unsigned char *sigctx = OPENSSL_zalloc(1); TEST_ptr(sigctx); return sigctx; } static void fake_rsa_sig_freectx(void *sigctx) { OPENSSL_free(sigctx); } static int fake_rsa_sig_sign_init(void *ctx, void *provkey, const OSSL_PARAM params[]) { unsigned char *sigctx = ctx; struct fake_rsa_keydata *keydata = provkey; /* we must have a ctx */ if (!TEST_ptr(sigctx)) return 0; /* we must have some initialized key */ if (!TEST_ptr(keydata) || !TEST_int_gt(keydata->status, 0)) return 0; /* record that sign init was called */ *sigctx = 1; return 1; } static int fake_rsa_sig_sign(void *ctx, unsigned char *sig, size_t *siglen, size_t sigsize, const unsigned char *tbs, size_t tbslen) { unsigned char *sigctx = ctx; /* we must have a ctx and init was called upon it */ if (!TEST_ptr(sigctx) || !TEST_int_eq(*sigctx, 1)) return 0; *siglen = 256; /* record that the real sign operation was called */ if (sig != NULL) { if (!TEST_int_ge(sigsize, *siglen)) return 0; *sigctx = 2; /* produce a fake signature */ memset(sig, 'a', *siglen); } return 1; } #define FAKE_DGSTSGN_SIGN 0x01 #define FAKE_DGSTSGN_VERIFY 0x02 #define FAKE_DGSTSGN_UPDATED 0x04 #define FAKE_DGSTSGN_FINALISED 0x08 #define FAKE_DGSTSGN_NO_DUP 0xA0 static void *fake_rsa_sig_dupctx(void *ctx) { unsigned char *sigctx = ctx; unsigned char *newctx; if ((*sigctx & FAKE_DGSTSGN_NO_DUP) != 0) return NULL; if (!TEST_ptr(newctx = OPENSSL_zalloc(1))) return NULL; *newctx = *sigctx; return newctx; } static int fake_rsa_dgstsgnvfy_init(void *ctx, unsigned char type, void *provkey, const OSSL_PARAM params[]) { unsigned char *sigctx = ctx; struct fake_rsa_keydata *keydata = provkey; /* we must have a ctx */ if (!TEST_ptr(sigctx)) return 0; /* we must have some initialized key */ if (!TEST_ptr(keydata) || !TEST_int_gt(keydata->status, 0)) return 0; /* record that sign/verify init was called */ *sigctx = type; if (params) { const OSSL_PARAM *p; int dup; p = OSSL_PARAM_locate_const(params, "NO_DUP"); if (p != NULL) { if (OSSL_PARAM_get_int(p, &dup)) { *sigctx |= FAKE_DGSTSGN_NO_DUP; } } } return 1; } static int fake_rsa_dgstsgn_init(void *ctx, const char *mdname, void *provkey, const OSSL_PARAM params[]) { return fake_rsa_dgstsgnvfy_init(ctx, FAKE_DGSTSGN_SIGN, provkey, params); } static int fake_rsa_dgstvfy_init(void *ctx, const char *mdname, void *provkey, const OSSL_PARAM params[]) { return fake_rsa_dgstsgnvfy_init(ctx, FAKE_DGSTSGN_VERIFY, provkey, params); } static int fake_rsa_dgstsgnvfy_update(void *ctx, const unsigned char *data, size_t datalen) { unsigned char *sigctx = ctx; /* we must have a ctx */ if (!TEST_ptr(sigctx)) return 0; if (*sigctx == 0 || (*sigctx & FAKE_DGSTSGN_FINALISED) != 0) return 0; *sigctx |= FAKE_DGSTSGN_UPDATED; return 1; } static int fake_rsa_dgstsgnvfy_final(void *ctx, unsigned char *sig, size_t *siglen, size_t sigsize) { unsigned char *sigctx = ctx; /* we must have a ctx */ if (!TEST_ptr(sigctx)) return 0; if (*sigctx == 0 || (*sigctx & FAKE_DGSTSGN_FINALISED) != 0) return 0; if ((*sigctx & FAKE_DGSTSGN_SIGN) != 0 && (siglen == NULL)) return 0; if ((*sigctx & FAKE_DGSTSGN_VERIFY) != 0 && (siglen != NULL)) return 0; /* this is sign op */ if (siglen) { *siglen = 256; /* record that the real sign operation was called */ if (sig != NULL) { if (!TEST_int_ge(sigsize, *siglen)) return 0; /* produce a fake signature */ memset(sig, 'a', *siglen); } } /* simulate inability to duplicate context and finalise it */ if ((*sigctx & FAKE_DGSTSGN_NO_DUP) != 0) { *sigctx |= FAKE_DGSTSGN_FINALISED; } return 1; } static int fake_rsa_dgstvfy_final(void *ctx, unsigned char *sig, size_t siglen) { return fake_rsa_dgstsgnvfy_final(ctx, sig, NULL, siglen); } static int fake_rsa_dgstsgn(void *ctx, unsigned char *sig, size_t *siglen, size_t sigsize, const unsigned char *tbs, size_t tbslen) { if (!fake_rsa_dgstsgnvfy_update(ctx, tbs, tbslen)) return 0; return fake_rsa_dgstsgnvfy_final(ctx, sig, siglen, sigsize); } static int fake_rsa_dgstvfy(void *ctx, unsigned char *sig, size_t siglen, const unsigned char *tbv, size_t tbvlen) { if (!fake_rsa_dgstsgnvfy_update(ctx, tbv, tbvlen)) return 0; return fake_rsa_dgstvfy_final(ctx, sig, siglen); } static const OSSL_DISPATCH fake_rsa_sig_funcs[] = { { OSSL_FUNC_SIGNATURE_NEWCTX, (void (*)(void))fake_rsa_sig_newctx }, { OSSL_FUNC_SIGNATURE_FREECTX, (void (*)(void))fake_rsa_sig_freectx }, { OSSL_FUNC_SIGNATURE_SIGN_INIT, (void (*)(void))fake_rsa_sig_sign_init }, { OSSL_FUNC_SIGNATURE_SIGN, (void (*)(void))fake_rsa_sig_sign }, { OSSL_FUNC_SIGNATURE_DUPCTX, (void (*)(void))fake_rsa_sig_dupctx }, { OSSL_FUNC_SIGNATURE_DIGEST_SIGN_INIT, (void (*)(void))fake_rsa_dgstsgn_init }, { OSSL_FUNC_SIGNATURE_DIGEST_SIGN_UPDATE, (void (*)(void))fake_rsa_dgstsgnvfy_update }, { OSSL_FUNC_SIGNATURE_DIGEST_SIGN_FINAL, (void (*)(void))fake_rsa_dgstsgnvfy_final }, { OSSL_FUNC_SIGNATURE_DIGEST_SIGN, (void (*)(void))fake_rsa_dgstsgn }, { OSSL_FUNC_SIGNATURE_DIGEST_VERIFY_INIT, (void (*)(void))fake_rsa_dgstvfy_init }, { OSSL_FUNC_SIGNATURE_DIGEST_VERIFY_UPDATE, (void (*)(void))fake_rsa_dgstsgnvfy_update }, { OSSL_FUNC_SIGNATURE_DIGEST_VERIFY_FINAL, (void (*)(void))fake_rsa_dgstvfy_final }, { OSSL_FUNC_SIGNATURE_DIGEST_VERIFY, (void (*)(void))fake_rsa_dgstvfy }, OSSL_DISPATCH_END }; static const OSSL_ALGORITHM fake_rsa_sig_algs[] = { { "RSA:rsaEncryption", "provider=fake-rsa", fake_rsa_sig_funcs, "Fake RSA Signature" }, { NULL, NULL, NULL, NULL } }; static OSSL_FUNC_store_open_fn fake_rsa_st_open; static OSSL_FUNC_store_open_ex_fn fake_rsa_st_open_ex; static OSSL_FUNC_store_settable_ctx_params_fn fake_rsa_st_settable_ctx_params; static OSSL_FUNC_store_set_ctx_params_fn fake_rsa_st_set_ctx_params; static OSSL_FUNC_store_load_fn fake_rsa_st_load; static OSSL_FUNC_store_eof_fn fake_rsa_st_eof; static OSSL_FUNC_store_close_fn fake_rsa_st_close; static OSSL_FUNC_store_delete_fn fake_rsa_st_delete; static const char fake_rsa_scheme[] = "fake_rsa:"; static const char fake_rsa_openpwtest[] = "fake_rsa:openpwtest"; static const char fake_rsa_prompt[] = "Fake Prompt Info"; static void *fake_rsa_st_open_ex(void *provctx, const char *uri, const OSSL_PARAM params[], OSSL_PASSPHRASE_CALLBACK *pw_cb, void *pw_cbarg) { unsigned char *storectx = NULL; /* First check whether the uri is ours */ if (strncmp(uri, fake_rsa_scheme, sizeof(fake_rsa_scheme) - 1) != 0) return NULL; if (strncmp(uri, fake_rsa_openpwtest, sizeof(fake_rsa_openpwtest) - 1) == 0) { const char *pw_check = FAKE_PASSPHRASE; char fakepw[sizeof(FAKE_PASSPHRASE) + 1] = { 0 }; size_t fakepw_len = 0; OSSL_PARAM pw_params[2] = { OSSL_PARAM_utf8_string(OSSL_PASSPHRASE_PARAM_INFO, (void *)fake_rsa_prompt, sizeof(fake_rsa_prompt) - 1), OSSL_PARAM_END, }; if (pw_cb == NULL) { return NULL; } if (!pw_cb(fakepw, sizeof(fakepw), &fakepw_len, pw_params, pw_cbarg)) { TEST_info("fake_rsa_open_ex failed passphrase callback"); return NULL; } if (strncmp(pw_check, fakepw, sizeof(pw_check) - 1) != 0) { TEST_info("fake_rsa_open_ex failed passphrase check"); return NULL; } } storectx = OPENSSL_zalloc(1); if (!TEST_ptr(storectx)) return NULL; TEST_info("fake_rsa_open_ex called"); return storectx; } static void *fake_rsa_st_open(void *provctx, const char *uri) { unsigned char *storectx = NULL; storectx = fake_rsa_st_open_ex(provctx, uri, NULL, NULL, NULL); TEST_info("fake_rsa_open called"); return storectx; } static const OSSL_PARAM *fake_rsa_st_settable_ctx_params(void *provctx) { static const OSSL_PARAM known_settable_ctx_params[] = { OSSL_PARAM_END }; return known_settable_ctx_params; } static int fake_rsa_st_set_ctx_params(void *loaderctx, const OSSL_PARAM params[]) { return 1; } static int fake_rsa_st_load(void *loaderctx, OSSL_CALLBACK *object_cb, void *object_cbarg, OSSL_PASSPHRASE_CALLBACK *pw_cb, void *pw_cbarg) { unsigned char *storectx = loaderctx; OSSL_PARAM params[4]; int object_type = OSSL_OBJECT_PKEY; struct fake_rsa_keydata *key = NULL; int rv = 0; switch (*storectx) { case 0: if (key_deleted == 1) { *storectx = 1; break; } /* Construct a new key using our keymgmt functions */ if (!TEST_ptr(key = fake_rsa_keymgmt_new(NULL))) break; if (!TEST_int_gt(fake_rsa_keymgmt_import(key, 0, NULL), 0)) break; params[0] = OSSL_PARAM_construct_int(OSSL_OBJECT_PARAM_TYPE, &object_type); params[1] = OSSL_PARAM_construct_utf8_string(OSSL_OBJECT_PARAM_DATA_TYPE, "RSA", 0); /* The address of the key becomes the octet string */ params[2] = OSSL_PARAM_construct_octet_string(OSSL_OBJECT_PARAM_REFERENCE, &key, sizeof(*key)); params[3] = OSSL_PARAM_construct_end(); rv = object_cb(params, object_cbarg); *storectx = 1; break; case 2: TEST_info("fake_rsa_load() called in error state"); break; default: TEST_info("fake_rsa_load() called in eof state"); break; } TEST_info("fake_rsa_load called - rv: %d", rv); if (rv == 0 && key_deleted == 0) { fake_rsa_keymgmt_free(key); *storectx = 2; } return rv; } static int fake_rsa_st_delete(void *loaderctx, const char *uri, const OSSL_PARAM params[], OSSL_PASSPHRASE_CALLBACK *pw_cb, void *pw_cbarg) { key_deleted = 1; return 1; } static int fake_rsa_st_eof(void *loaderctx) { unsigned char *storectx = loaderctx; /* just one key for now in the fake_rsa store */ return *storectx != 0; } static int fake_rsa_st_close(void *loaderctx) { OPENSSL_free(loaderctx); return 1; } static const OSSL_DISPATCH fake_rsa_store_funcs[] = { { OSSL_FUNC_STORE_OPEN, (void (*)(void))fake_rsa_st_open }, { OSSL_FUNC_STORE_OPEN_EX, (void (*)(void))fake_rsa_st_open_ex }, { OSSL_FUNC_STORE_SETTABLE_CTX_PARAMS, (void (*)(void))fake_rsa_st_settable_ctx_params }, { OSSL_FUNC_STORE_SET_CTX_PARAMS, (void (*)(void))fake_rsa_st_set_ctx_params }, { OSSL_FUNC_STORE_LOAD, (void (*)(void))fake_rsa_st_load }, { OSSL_FUNC_STORE_EOF, (void (*)(void))fake_rsa_st_eof }, { OSSL_FUNC_STORE_CLOSE, (void (*)(void))fake_rsa_st_close }, { OSSL_FUNC_STORE_DELETE, (void (*)(void))fake_rsa_st_delete }, OSSL_DISPATCH_END, }; static const OSSL_ALGORITHM fake_rsa_store_algs[] = { { "fake_rsa", "provider=fake-rsa", fake_rsa_store_funcs }, { NULL, NULL, NULL } }; static const OSSL_ALGORITHM *fake_rsa_query(void *provctx, int operation_id, int *no_cache) { *no_cache = 0; switch (operation_id) { case OSSL_OP_SIGNATURE: return fake_rsa_sig_algs; case OSSL_OP_KEYMGMT: return fake_rsa_keymgmt_algs; case OSSL_OP_STORE: return fake_rsa_store_algs; } return NULL; } /* Functions we provide to the core */ static const OSSL_DISPATCH fake_rsa_method[] = { { OSSL_FUNC_PROVIDER_TEARDOWN, (void (*)(void))OSSL_LIB_CTX_free }, { OSSL_FUNC_PROVIDER_QUERY_OPERATION, (void (*)(void))fake_rsa_query }, OSSL_DISPATCH_END }; static int fake_rsa_provider_init(const OSSL_CORE_HANDLE *handle, const OSSL_DISPATCH *in, const OSSL_DISPATCH **out, void **provctx) { if (!TEST_ptr(*provctx = OSSL_LIB_CTX_new())) return 0; *out = fake_rsa_method; return 1; } OSSL_PROVIDER *fake_rsa_start(OSSL_LIB_CTX *libctx) { OSSL_PROVIDER *p; if (!TEST_true(OSSL_PROVIDER_add_builtin(libctx, "fake-rsa", fake_rsa_provider_init)) || !TEST_ptr(p = OSSL_PROVIDER_try_load(libctx, "fake-rsa", 1))) return NULL; return p; } void fake_rsa_finish(OSSL_PROVIDER *p) { OSSL_PROVIDER_unload(p); }
./openssl/test/bio_prefix_text.c
/* * Copyright 2019 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <string.h> #include <stdarg.h> #include <openssl/bio.h> #include <openssl/safestack.h> #include "opt.h" static BIO *bio_in = NULL; static BIO *bio_out = NULL; static BIO *bio_err = NULL; /*- * This program sets up a chain of BIO_f_filter() on top of bio_out, how * many is governed by the user through -n. It allows the user to set the * indentation for each individual filter using -i and -p. Then it reads * text from bio_in and prints it out through the BIO chain. * * The filter index is counted from the source/sink, i.e. index 0 is closest * to it. * * Example: * * $ echo foo | ./bio_prefix_text -n 2 -i 1:32 -p 1:FOO -i 0:3 * FOO foo * ^^^ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ * | | * | +------ 32 spaces from filter 1 * +-------------------------- 3 spaces from filter 0 */ static size_t amount = 0; static BIO **chain = NULL; typedef enum OPTION_choice { OPT_ERR = -1, OPT_EOF = 0, OPT_AMOUNT, OPT_INDENT, OPT_PREFIX } OPTION_CHOICE; static const OPTIONS options[] = { { "n", OPT_AMOUNT, 'p', "Amount of BIO_f_prefix() filters" }, /* * idx is the index to the BIO_f_filter chain(), where 0 is closest * to the source/sink BIO. If idx isn't given, 0 is assumed */ { "i", OPT_INDENT, 's', "Indentation in form '[idx:]indent'" }, { "p", OPT_PREFIX, 's', "Prefix in form '[idx:]prefix'" }, { NULL } }; int opt_printf_stderr(const char *fmt, ...) { va_list ap; int ret; va_start(ap, fmt); ret = BIO_vprintf(bio_err, fmt, ap); va_end(ap); return ret; } static int run_pipe(void) { char buf[4096]; while (!BIO_eof(bio_in)) { size_t bytes_in; size_t bytes_out; if (!BIO_read_ex(bio_in, buf, sizeof(buf), &bytes_in)) return 0; bytes_out = 0; while (bytes_out < bytes_in) { size_t bytes; if (!BIO_write_ex(chain[amount - 1], buf, bytes_in, &bytes)) return 0; bytes_out += bytes; } } return 1; } static int setup_bio_chain(const char *progname) { BIO *next = NULL; size_t n = amount; chain = OPENSSL_zalloc(sizeof(*chain) * n); if (chain != NULL) { size_t i; next = bio_out; BIO_up_ref(next); /* Protection against freeing */ for (i = 0; n > 0; i++, n--) { BIO *curr = BIO_new(BIO_f_prefix()); if (curr == NULL) goto err; chain[i] = BIO_push(curr, next); if (chain[i] == NULL) goto err; next = chain[i]; } } return chain != NULL; err: /* Free the chain we built up */ BIO_free_all(next); OPENSSL_free(chain); return 0; } static void cleanup(void) { if (chain != NULL) { BIO_free_all(chain[amount - 1]); OPENSSL_free(chain); } BIO_free_all(bio_in); BIO_free_all(bio_out); BIO_free_all(bio_err); } static int setup(void) { OPTION_CHOICE o; char *arg; char *colon; char *endptr; size_t idx, indent; const char *progname = opt_getprog(); bio_in = BIO_new_fp(stdin, BIO_NOCLOSE | BIO_FP_TEXT); bio_out = BIO_new_fp(stdout, BIO_NOCLOSE | BIO_FP_TEXT); bio_err = BIO_new_fp(stderr, BIO_NOCLOSE | BIO_FP_TEXT); #ifdef __VMS bio_out = BIO_push(BIO_new(BIO_f_linebuffer()), bio_out); bio_err = BIO_push(BIO_new(BIO_f_linebuffer()), bio_err); #endif OPENSSL_assert(bio_in != NULL); OPENSSL_assert(bio_out != NULL); OPENSSL_assert(bio_err != NULL); while ((o = opt_next()) != OPT_EOF) { switch (o) { case OPT_AMOUNT: arg = opt_arg(); amount = strtoul(arg, &endptr, 10); if (endptr[0] != '\0') { BIO_printf(bio_err, "%s: -n argument isn't a decimal number: %s", progname, arg); return 0; } if (amount < 1) { BIO_printf(bio_err, "%s: must set up at least one filter", progname); return 0; } if (!setup_bio_chain(progname)) { BIO_printf(bio_err, "%s: failed setting up filter chain", progname); return 0; } break; case OPT_INDENT: if (chain == NULL) { BIO_printf(bio_err, "%s: -i given before -n", progname); return 0; } arg = opt_arg(); colon = strchr(arg, ':'); idx = 0; if (colon != NULL) { idx = strtoul(arg, &endptr, 10); if (endptr[0] != ':') { BIO_printf(bio_err, "%s: -i index isn't a decimal number: %s", progname, arg); return 0; } colon++; } else { colon = arg; } indent = strtoul(colon, &endptr, 10); if (endptr[0] != '\0') { BIO_printf(bio_err, "%s: -i value isn't a decimal number: %s", progname, arg); return 0; } if (idx >= amount) { BIO_printf(bio_err, "%s: index (%zu) not within range 0..%zu", progname, idx, amount - 1); return 0; } if (BIO_set_indent(chain[idx], (long)indent) <= 0) { BIO_printf(bio_err, "%s: failed setting indentation: %s", progname, arg); return 0; } break; case OPT_PREFIX: if (chain == NULL) { BIO_printf(bio_err, "%s: -p given before -n", progname); return 0; } arg = opt_arg(); colon = strchr(arg, ':'); idx = 0; if (colon != NULL) { idx = strtoul(arg, &endptr, 10); if (endptr[0] != ':') { BIO_printf(bio_err, "%s: -p index isn't a decimal number: %s", progname, arg); return 0; } colon++; } else { colon = arg; } if (idx >= amount) { BIO_printf(bio_err, "%s: index (%zu) not within range 0..%zu", progname, idx, amount - 1); return 0; } if (BIO_set_prefix(chain[idx], colon) <= 0) { BIO_printf(bio_err, "%s: failed setting prefix: %s", progname, arg); return 0; } break; default: case OPT_ERR: return 0; } } return 1; } int main(int argc, char **argv) { int rv = EXIT_SUCCESS; opt_init(argc, argv, options); rv = (setup() && run_pipe()) ? EXIT_SUCCESS : EXIT_FAILURE; cleanup(); return rv; }
./openssl/test/mdc2_internal_test.c
/* * Copyright 2016-2020 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ /* Internal tests for the mdc2 module */ /* * MDC2 low level APIs are deprecated for public use, but still ok for * internal use. */ #include "internal/deprecated.h" #include <stdio.h> #include <string.h> #include <openssl/mdc2.h> #include "testutil.h" #include "internal/nelem.h" typedef struct { const char *input; const unsigned char expected[MDC2_DIGEST_LENGTH]; } TESTDATA; /********************************************************************** * * Test driver * ***/ static TESTDATA tests[] = { { "Now is the time for all ", { 0x42, 0xE5, 0x0C, 0xD2, 0x24, 0xBA, 0xCE, 0xBA, 0x76, 0x0B, 0xDD, 0x2B, 0xD4, 0x09, 0x28, 0x1A } } }; /********************************************************************** * * Test of mdc2 internal functions * ***/ static int test_mdc2(int idx) { unsigned char md[MDC2_DIGEST_LENGTH]; MDC2_CTX c; const TESTDATA testdata = tests[idx]; MDC2_Init(&c); MDC2_Update(&c, (const unsigned char *)testdata.input, strlen(testdata.input)); MDC2_Final(&(md[0]), &c); if (!TEST_mem_eq(testdata.expected, MDC2_DIGEST_LENGTH, md, MDC2_DIGEST_LENGTH)) { TEST_info("mdc2 test %d: unexpected output", idx); return 0; } return 1; } int setup_tests(void) { ADD_ALL_TESTS(test_mdc2, OSSL_NELEM(tests)); return 1; }
./openssl/test/dsatest.c
/* * Copyright 1995-2023 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ /* * DSA low level APIs are deprecated for public use, but still ok for * internal use. */ #include "internal/deprecated.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/types.h> #include <sys/stat.h> #include <openssl/crypto.h> #include <openssl/rand.h> #include <openssl/bn.h> #include <openssl/dsa.h> #include <openssl/evp.h> #include <openssl/core_names.h> #include "testutil.h" #include "internal/nelem.h" #ifndef OPENSSL_NO_DSA static int dsa_cb(int p, int n, BN_GENCB *arg); static unsigned char out_p[] = { 0x8d, 0xf2, 0xa4, 0x94, 0x49, 0x22, 0x76, 0xaa, 0x3d, 0x25, 0x75, 0x9b, 0xb0, 0x68, 0x69, 0xcb, 0xea, 0xc0, 0xd8, 0x3a, 0xfb, 0x8d, 0x0c, 0xf7, 0xcb, 0xb8, 0x32, 0x4f, 0x0d, 0x78, 0x82, 0xe5, 0xd0, 0x76, 0x2f, 0xc5, 0xb7, 0x21, 0x0e, 0xaf, 0xc2, 0xe9, 0xad, 0xac, 0x32, 0xab, 0x7a, 0xac, 0x49, 0x69, 0x3d, 0xfb, 0xf8, 0x37, 0x24, 0xc2, 0xec, 0x07, 0x36, 0xee, 0x31, 0xc8, 0x02, 0x91, }; static unsigned char out_q[] = { 0xc7, 0x73, 0x21, 0x8c, 0x73, 0x7e, 0xc8, 0xee, 0x99, 0x3b, 0x4f, 0x2d, 0xed, 0x30, 0xf4, 0x8e, 0xda, 0xce, 0x91, 0x5f, }; static unsigned char out_g[] = { 0x62, 0x6d, 0x02, 0x78, 0x39, 0xea, 0x0a, 0x13, 0x41, 0x31, 0x63, 0xa5, 0x5b, 0x4c, 0xb5, 0x00, 0x29, 0x9d, 0x55, 0x22, 0x95, 0x6c, 0xef, 0xcb, 0x3b, 0xff, 0x10, 0xf3, 0x99, 0xce, 0x2c, 0x2e, 0x71, 0xcb, 0x9d, 0xe5, 0xfa, 0x24, 0xba, 0xbf, 0x58, 0xe5, 0xb7, 0x95, 0x21, 0x92, 0x5c, 0x9c, 0xc4, 0x2e, 0x9f, 0x6f, 0x46, 0x4b, 0x08, 0x8c, 0xc5, 0x72, 0xaf, 0x53, 0xe6, 0xd7, 0x88, 0x02, }; static int dsa_test(void) { BN_GENCB *cb; DSA *dsa = NULL; int counter, ret = 0, i, j; unsigned char buf[256]; unsigned long h; unsigned char sig[256]; unsigned int siglen; const BIGNUM *p = NULL, *q = NULL, *g = NULL; /* * seed, out_p, out_q, out_g are taken from the updated Appendix 5 to FIPS * PUB 186 and also appear in Appendix 5 to FIPS PIB 186-1 */ static unsigned char seed[20] = { 0xd5, 0x01, 0x4e, 0x4b, 0x60, 0xef, 0x2b, 0xa8, 0xb6, 0x21, 0x1b, 0x40, 0x62, 0xba, 0x32, 0x24, 0xe0, 0x42, 0x7d, 0xd3, }; static const unsigned char str1[] = "12345678901234567890"; if (!TEST_ptr(cb = BN_GENCB_new())) goto end; BN_GENCB_set(cb, dsa_cb, NULL); if (!TEST_ptr(dsa = DSA_new()) || !TEST_true(DSA_generate_parameters_ex(dsa, 512, seed, 20, &counter, &h, cb))) goto end; if (!TEST_int_eq(counter, 105)) goto end; if (!TEST_int_eq(h, 2)) goto end; DSA_get0_pqg(dsa, &p, &q, &g); i = BN_bn2bin(q, buf); j = sizeof(out_q); if (!TEST_int_eq(i, j) || !TEST_mem_eq(buf, i, out_q, i)) goto end; i = BN_bn2bin(p, buf); j = sizeof(out_p); if (!TEST_int_eq(i, j) || !TEST_mem_eq(buf, i, out_p, i)) goto end; i = BN_bn2bin(g, buf); j = sizeof(out_g); if (!TEST_int_eq(i, j) || !TEST_mem_eq(buf, i, out_g, i)) goto end; if (!TEST_true(DSA_generate_key(dsa))) goto end; if (!TEST_true(DSA_sign(0, str1, 20, sig, &siglen, dsa))) goto end; if (TEST_int_gt(DSA_verify(0, str1, 20, sig, siglen, dsa), 0)) ret = 1; end: DSA_free(dsa); BN_GENCB_free(cb); return ret; } static int dsa_cb(int p, int n, BN_GENCB *arg) { static int ok = 0, num = 0; if (p == 0) num++; if (p == 2) ok++; if (!ok && (p == 0) && (num > 1)) { TEST_error("dsa_cb error"); return 0; } return 1; } # define P 0 # define Q 1 # define G 2 # define SEED 3 # define PCOUNT 4 # define GINDEX 5 # define HCOUNT 6 # define GROUP 7 static int dsa_keygen_test(void) { int ret = 0; EVP_PKEY *param_key = NULL, *key = NULL; EVP_PKEY_CTX *pg_ctx = NULL, *kg_ctx = NULL; BIGNUM *p_in = NULL, *q_in = NULL, *g_in = NULL; BIGNUM *p_out = NULL, *q_out = NULL, *g_out = NULL; int gindex_out = 0, pcount_out = 0, hcount_out = 0; unsigned char seed_out[32]; char group_out[32]; size_t len = 0; const OSSL_PARAM *settables = NULL; static const unsigned char seed_data[] = { 0xa6, 0xf5, 0x28, 0x8c, 0x50, 0x77, 0xa5, 0x68, 0x6d, 0x3a, 0xf5, 0xf1, 0xc6, 0x4c, 0xdc, 0x35, 0x95, 0x26, 0x3f, 0x03, 0xdc, 0x00, 0x3f, 0x44, 0x7b, 0x2a, 0xc7, 0x29 }; static const unsigned char expected_p[]= { 0xdb, 0x47, 0x07, 0xaf, 0xf0, 0x06, 0x49, 0x55, 0xc9, 0xbb, 0x09, 0x41, 0xb8, 0xdb, 0x1f, 0xbc, 0xa8, 0xed, 0x12, 0x06, 0x7f, 0x88, 0x49, 0xb8, 0xc9, 0x12, 0x87, 0x21, 0xbb, 0x08, 0x6c, 0xbd, 0xf1, 0x89, 0xef, 0x84, 0xd9, 0x7a, 0x93, 0xe8, 0x45, 0x40, 0x81, 0xec, 0x37, 0x27, 0x1a, 0xa4, 0x22,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b, 0x0b, 0x8e, 0xfc, 0x1a, 0x7e, 0x79, 0xb1, 0x1b, 0x0d, 0xfc, 0x70, 0xec, 0x85, 0xc2, 0xc5, 0xba, 0xb9, 0x69, 0x3f, 0x88, 0xbc, 0xcb }; static const unsigned char expected_q[]= { 0x99, 0xb6, 0xa0, 0xee, 0xb3, 0xa6, 0x99, 0x1a, 0xb6, 0x67, 0x8d, 0xc1, 0x2b, 0x9b, 0xce, 0x2b, 0x01, 0x72, 0x5a, 0x65, 0x76, 0x3d, 0x93, 0x69, 0xe2, 0x56, 0xae, 0xd7 }; static const unsigned char expected_g[]= { 0x63, 0xf8, 0xb6, 0xee, 0x2a, 0x27, 0xaf, 0x4f, 0x4c, 0xf6, 0x08, 0x28, 0x87, 0x4a, 0xe7, 0x1f, 0x45, 0x46, 0x27, 0x52, 0x3b, 0x7f, 0x6f, 0xd2, 0x29, 0xcb, 0xe8, 0x11, 0x19, 0x25, 0x35, 0x76, 0x99, 0xcb, 0x4f, 0x1b, 0xe0, 0xed, 0x32, 0x9e, 0x05, 0xb5, 0xbe, 0xd7, 0xf6, 0x5a, 0xb2, 0xf6, 0x0e, 0x0c, 0x7e, 0xf5, 0xe1, 0x05, 0xfe, 0xda, 0xaf, 0x0f, 0x27, 0x1e, 0x40, 0x2a, 0xf7, 0xa7, 0x23, 0x49, 0x2c, 0xd9, 0x1b, 0x0a, 0xbe, 0xff, 0xc7, 0x7c, 0x7d, 0x60, 0xca, 0xa3, 0x19, 0xc3, 0xb7, 0xe4, 0x43, 0xb0, 0xf5, 0x75, 0x44, 0x90, 0x46, 0x47, 0xb1, 0xa6, 0x48, 0x0b, 0x21, 0x8e, 0xee, 0x75, 0xe6, 0x3d, 0xa7, 0xd3, 0x7b, 0x31, 0xd1, 0xd2, 0x9d, 0xe2, 0x8a, 0xfc, 0x57, 0xfd, 0x8a, 0x10, 0x31, 0xeb, 0x87, 0x36, 0x3f, 0x65, 0x72, 0x23, 0x2c, 0xd3, 0xd6, 0x17, 0xa5, 0x62, 0x58, 0x65, 0x57, 0x6a, 0xd4, 0xa8, 0xfe, 0xec, 0x57, 0x76, 0x0c, 0xb1, 0x4c, 0x93, 0xed, 0xb0, 0xb4, 0xf9, 0x45, 0xb3, 0x3e, 0xdd, 0x47, 0xf1, 0xfb, 0x7d, 0x25, 0x79, 0x3d, 0xfc, 0xa7, 0x39, 0x90, 0x68, 0x6a, 0x6b, 0xae, 0xf2, 0x6e, 0x64, 0x8c, 0xfb, 0xb8, 0xdd, 0x76, 0x4e, 0x4a, 0x69, 0x8c, 0x97, 0x15, 0x77, 0xb2, 0x67, 0xdc, 0xeb, 0x4a, 0x40, 0x6b, 0xb9, 0x47, 0x8f, 0xa6, 0xab, 0x6e, 0x98, 0xc0, 0x97, 0x9a, 0x0c, 0xea, 0x00, 0xfd, 0x56, 0x1a, 0x74, 0x9a, 0x32, 0x6b, 0xfe, 0xbd, 0xdf, 0x6c, 0x82, 0x54, 0x53, 0x4d, 0x70, 0x65, 0xe3, 0x8b, 0x37, 0xb8, 0xe4, 0x70, 0x08, 0xb7, 0x3b, 0x30, 0x27, 0xaf, 0x1c, 0x77, 0xf3, 0x62, 0xd4, 0x9a, 0x59, 0xba, 0xd1, 0x6e, 0x89, 0x5c, 0x34, 0x9a, 0xa1, 0xb7, 0x4f, 0x7d, 0x8c, 0xdc, 0xbc, 0x74, 0x25, 0x5e, 0xbf, 0x77, 0x46 }; int expected_c = 1316; int expected_h = 2; if (!TEST_ptr(p_in = BN_bin2bn(expected_p, sizeof(expected_p), NULL)) || !TEST_ptr(q_in = BN_bin2bn(expected_q, sizeof(expected_q), NULL)) || !TEST_ptr(g_in = BN_bin2bn(expected_g, sizeof(expected_g), NULL))) goto end; if (!TEST_ptr(pg_ctx = EVP_PKEY_CTX_new_from_name(NULL, "DSA", NULL)) || !TEST_int_gt(EVP_PKEY_paramgen_init(pg_ctx), 0) || !TEST_ptr_null(EVP_PKEY_CTX_gettable_params(pg_ctx)) || !TEST_ptr(settables = EVP_PKEY_CTX_settable_params(pg_ctx)) || !TEST_ptr(OSSL_PARAM_locate_const(settables, OSSL_PKEY_PARAM_FFC_PBITS)) || !TEST_true(EVP_PKEY_CTX_set_dsa_paramgen_type(pg_ctx, "fips186_4")) || !TEST_true(EVP_PKEY_CTX_set_dsa_paramgen_bits(pg_ctx, 2048)) || !TEST_true(EVP_PKEY_CTX_set_dsa_paramgen_q_bits(pg_ctx, 224)) || !TEST_true(EVP_PKEY_CTX_set_dsa_paramgen_seed(pg_ctx, seed_data, sizeof(seed_data))) || !TEST_true(EVP_PKEY_CTX_set_dsa_paramgen_md_props(pg_ctx, "SHA256", "")) || !TEST_int_gt(EVP_PKEY_generate(pg_ctx, &param_key), 0) || !TEST_ptr(kg_ctx = EVP_PKEY_CTX_new_from_pkey(NULL, param_key, NULL)) || !TEST_int_gt(EVP_PKEY_keygen_init(kg_ctx), 0) || !TEST_int_gt(EVP_PKEY_generate(kg_ctx, &key), 0)) goto end; if (!TEST_true(EVP_PKEY_get_bn_param(key, OSSL_PKEY_PARAM_FFC_P, &p_out)) || !TEST_BN_eq(p_in, p_out) || !TEST_true(EVP_PKEY_get_bn_param(key, OSSL_PKEY_PARAM_FFC_Q, &q_out)) || !TEST_BN_eq(q_in, q_out) || !TEST_true(EVP_PKEY_get_bn_param(key, OSSL_PKEY_PARAM_FFC_G, &g_out)) || !TEST_BN_eq(g_in, g_out) || !TEST_true(EVP_PKEY_get_octet_string_param( key, OSSL_PKEY_PARAM_FFC_SEED, seed_out, sizeof(seed_out), &len)) || !TEST_mem_eq(seed_out, len, seed_data, sizeof(seed_data)) || !TEST_true(EVP_PKEY_get_int_param(key, OSSL_PKEY_PARAM_FFC_GINDEX, &gindex_out)) || !TEST_int_eq(gindex_out, -1) || !TEST_true(EVP_PKEY_get_int_param(key, OSSL_PKEY_PARAM_FFC_H, &hcount_out)) || !TEST_int_eq(hcount_out, expected_h) || !TEST_true(EVP_PKEY_get_int_param(key, OSSL_PKEY_PARAM_FFC_PCOUNTER, &pcount_out)) || !TEST_int_eq(pcount_out, expected_c) || !TEST_false(EVP_PKEY_get_utf8_string_param(key, OSSL_PKEY_PARAM_GROUP_NAME, group_out, sizeof(group_out), &len))) goto end; ret = 1; end: BN_free(p_in); BN_free(q_in); BN_free(g_in); BN_free(p_out); BN_free(q_out); BN_free(g_out); EVP_PKEY_free(param_key); EVP_PKEY_free(key); EVP_PKEY_CTX_free(kg_ctx); EVP_PKEY_CTX_free(pg_ctx); return ret; } static int test_dsa_default_paramgen_validate(int i) { int ret; EVP_PKEY_CTX *gen_ctx = NULL; EVP_PKEY_CTX *check_ctx = NULL; EVP_PKEY *params = NULL; ret = TEST_ptr(gen_ctx = EVP_PKEY_CTX_new_from_name(NULL, "DSA", NULL)) && TEST_int_gt(EVP_PKEY_paramgen_init(gen_ctx), 0) && (i == 0 || TEST_true(EVP_PKEY_CTX_set_dsa_paramgen_bits(gen_ctx, 512))) && TEST_int_gt(EVP_PKEY_generate(gen_ctx, &params), 0) && TEST_ptr(check_ctx = EVP_PKEY_CTX_new_from_pkey(NULL, params, NULL)) && TEST_int_gt(EVP_PKEY_param_check(check_ctx), 0); EVP_PKEY_free(params); EVP_PKEY_CTX_free(check_ctx); EVP_PKEY_CTX_free(gen_ctx); return ret; } static int test_dsa_sig_infinite_loop(void) { int ret = 0; DSA *dsa = NULL; BIGNUM *p = NULL, *q = NULL, *g = NULL, *priv = NULL, *pub = NULL, *priv2 = NULL; BIGNUM *badq = NULL, *badpriv = NULL; const unsigned char msg[] = { 0x00 }; unsigned int signature_len; unsigned char signature[64]; static unsigned char out_priv[] = { 0x17, 0x00, 0xb2, 0x8d, 0xcb, 0x24, 0xc9, 0x98, 0xd0, 0x7f, 0x1f, 0x83, 0x1a, 0xa1, 0xc4, 0xa4, 0xf8, 0x0f, 0x7f, 0x12 }; static unsigned char out_pub[] = { 0x04, 0x72, 0xee, 0x8d, 0xaa, 0x4d, 0x89, 0x60, 0x0e, 0xb2, 0xd4, 0x38, 0x84, 0xa2, 0x2a, 0x60, 0x5f, 0x67, 0xd7, 0x9e, 0x24, 0xdd, 0xe8, 0x50, 0xf2, 0x23, 0x71, 0x55, 0x53, 0x94, 0x0d, 0x6b, 0x2e, 0xcd, 0x30, 0xda, 0x6f, 0x1e, 0x2c, 0xcf, 0x59, 0xbe, 0x05, 0x6c, 0x07, 0x0e, 0xc6, 0x38, 0x05, 0xcb, 0x0c, 0x44, 0x0a, 0x08, 0x13, 0xb6, 0x0f, 0x14, 0xde, 0x4a, 0xf6, 0xed, 0x4e, 0xc3 }; if (!TEST_ptr(p = BN_bin2bn(out_p, sizeof(out_p), NULL)) || !TEST_ptr(q = BN_bin2bn(out_q, sizeof(out_q), NULL)) || !TEST_ptr(g = BN_bin2bn(out_g, sizeof(out_g), NULL)) || !TEST_ptr(pub = BN_bin2bn(out_pub, sizeof(out_pub), NULL)) || !TEST_ptr(priv = BN_bin2bn(out_priv, sizeof(out_priv), NULL)) || !TEST_ptr(priv2 = BN_dup(priv)) || !TEST_ptr(badq = BN_new()) || !TEST_true(BN_set_word(badq, 1)) || !TEST_ptr(badpriv = BN_new()) || !TEST_true(BN_set_word(badpriv, 0)) || !TEST_ptr(dsa = DSA_new())) goto err; if (!TEST_true(DSA_set0_pqg(dsa, p, q, g))) goto err; p = q = g = NULL; if (!TEST_true(DSA_set0_key(dsa, pub, priv))) goto err; pub = priv = NULL; if (!TEST_int_le(DSA_size(dsa), sizeof(signature))) goto err; /* Test passing signature as NULL */ if (!TEST_true(DSA_sign(0, msg, sizeof(msg), NULL, &signature_len, dsa))) goto err; if (!TEST_true(DSA_sign(0, msg, sizeof(msg), signature, &signature_len, dsa))) goto err; /* Test using a private key of zero fails - this causes an infinite loop without the retry test */ if (!TEST_true(DSA_set0_key(dsa, NULL, badpriv))) goto err; badpriv = NULL; if (!TEST_false(DSA_sign(0, msg, sizeof(msg), signature, &signature_len, dsa))) goto err; /* Restore private and set a bad q - this caused an infinite loop in the setup */ if (!TEST_true(DSA_set0_key(dsa, NULL, priv2))) goto err; priv2 = NULL; if (!TEST_true(DSA_set0_pqg(dsa, NULL, badq, NULL))) goto err; badq = NULL; if (!TEST_false(DSA_sign(0, msg, sizeof(msg), signature, &signature_len, dsa))) goto err; ret = 1; err: BN_free(badq); BN_free(badpriv); BN_free(pub); BN_free(priv); BN_free(priv2); BN_free(g); BN_free(q); BN_free(p); DSA_free(dsa); return ret; } static int test_dsa_sig_neg_param(void) { int ret = 0, setpqg = 0; DSA *dsa = NULL; BIGNUM *p = NULL, *q = NULL, *g = NULL, *priv = NULL, *pub = NULL; const unsigned char msg[] = { 0x00 }; unsigned int signature_len; unsigned char signature[64]; static unsigned char out_priv[] = { 0x17, 0x00, 0xb2, 0x8d, 0xcb, 0x24, 0xc9, 0x98, 0xd0, 0x7f, 0x1f, 0x83, 0x1a, 0xa1, 0xc4, 0xa4, 0xf8, 0x0f, 0x7f, 0x12 }; static unsigned char out_pub[] = { 0x04, 0x72, 0xee, 0x8d, 0xaa, 0x4d, 0x89, 0x60, 0x0e, 0xb2, 0xd4, 0x38, 0x84, 0xa2, 0x2a, 0x60, 0x5f, 0x67, 0xd7, 0x9e, 0x24, 0xdd, 0xe8, 0x50, 0xf2, 0x23, 0x71, 0x55, 0x53, 0x94, 0x0d, 0x6b, 0x2e, 0xcd, 0x30, 0xda, 0x6f, 0x1e, 0x2c, 0xcf, 0x59, 0xbe, 0x05, 0x6c, 0x07, 0x0e, 0xc6, 0x38, 0x05, 0xcb, 0x0c, 0x44, 0x0a, 0x08, 0x13, 0xb6, 0x0f, 0x14, 0xde, 0x4a, 0xf6, 0xed, 0x4e, 0xc3 }; if (!TEST_ptr(p = BN_bin2bn(out_p, sizeof(out_p), NULL)) || !TEST_ptr(q = BN_bin2bn(out_q, sizeof(out_q), NULL)) || !TEST_ptr(g = BN_bin2bn(out_g, sizeof(out_g), NULL)) || !TEST_ptr(pub = BN_bin2bn(out_pub, sizeof(out_pub), NULL)) || !TEST_ptr(priv = BN_bin2bn(out_priv, sizeof(out_priv), NULL)) || !TEST_ptr(dsa = DSA_new())) goto err; if (!TEST_true(DSA_set0_pqg(dsa, p, q, g))) goto err; setpqg = 1; if (!TEST_true(DSA_set0_key(dsa, pub, priv))) goto err; pub = priv = NULL; BN_set_negative(p, 1); if (!TEST_false(DSA_sign(0, msg, sizeof(msg), signature, &signature_len, dsa))) goto err; BN_set_negative(p, 0); BN_set_negative(q, 1); if (!TEST_false(DSA_sign(0, msg, sizeof(msg), signature, &signature_len, dsa))) goto err; BN_set_negative(q, 0); BN_set_negative(g, 1); if (!TEST_false(DSA_sign(0, msg, sizeof(msg), signature, &signature_len, dsa))) goto err; BN_set_negative(p, 1); BN_set_negative(q, 1); BN_set_negative(g, 1); if (!TEST_false(DSA_sign(0, msg, sizeof(msg), signature, &signature_len, dsa))) goto err; ret = 1; err: BN_free(pub); BN_free(priv); if (setpqg == 0) { BN_free(g); BN_free(q); BN_free(p); } DSA_free(dsa); return ret; } #endif /* OPENSSL_NO_DSA */ int setup_tests(void) { #ifndef OPENSSL_NO_DSA ADD_TEST(dsa_test); ADD_TEST(dsa_keygen_test); ADD_TEST(test_dsa_sig_infinite_loop); ADD_TEST(test_dsa_sig_neg_param); ADD_ALL_TESTS(test_dsa_default_paramgen_validate, 2); #endif return 1; }
./openssl/test/nodefltctxtest.c
/* * Copyright 2023 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <openssl/evp.h> #include "testutil.h" /* * Test that the default libctx does not get initialised when using a custom * libctx. We assume that this test application has been executed such that the * null provider is loaded via the config file. */ static int test_no_deflt_ctx_init(void) { int testresult = 0; EVP_MD *md = NULL; OSSL_LIB_CTX *ctx = OSSL_LIB_CTX_new(); if (!TEST_ptr(ctx)) return 0; md = EVP_MD_fetch(ctx, "SHA2-256", NULL); if (!TEST_ptr(md)) goto err; /* * Since we're using a non-default libctx above, the default libctx should * not have been initialised via config file, and so it is not too late to * use OPENSSL_INIT_NO_LOAD_CONFIG. */ OPENSSL_init_crypto(OPENSSL_INIT_NO_LOAD_CONFIG, NULL); /* * If the config file was incorrectly loaded then the null provider will * have been initialised and the default provider loading will have been * blocked. If the config file was NOT loaded (as we expect) then the * default provider should be available. */ if (!TEST_true(OSSL_PROVIDER_available(NULL, "default"))) goto err; if (!TEST_false(OSSL_PROVIDER_available(NULL, "null"))) goto err; testresult = 1; err: EVP_MD_free(md); OSSL_LIB_CTX_free(ctx); return testresult; } int setup_tests(void) { ADD_TEST(test_no_deflt_ctx_init); return 1; }
./openssl/test/tls13secretstest.c
/* * Copyright 2016-2023 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <openssl/ssl.h> #include <openssl/evp.h> #include "../ssl/ssl_local.h" #include "testutil.h" #define IVLEN 12 #define KEYLEN 16 /* * Based on the test vectors available in: * https://tools.ietf.org/html/draft-ietf-tls-tls13-vectors-06 */ static unsigned char hs_start_hash[] = { 0xc6, 0xc9, 0x18, 0xad, 0x2f, 0x41, 0x99, 0xd5, 0x59, 0x8e, 0xaf, 0x01, 0x16, 0xcb, 0x7a, 0x5c, 0x2c, 0x14, 0xcb, 0x54, 0x78, 0x12, 0x18, 0x88, 0x8d, 0xb7, 0x03, 0x0d, 0xd5, 0x0d, 0x5e, 0x6d }; static unsigned char hs_full_hash[] = { 0xf8, 0xc1, 0x9e, 0x8c, 0x77, 0xc0, 0x38, 0x79, 0xbb, 0xc8, 0xeb, 0x6d, 0x56, 0xe0, 0x0d, 0xd5, 0xd8, 0x6e, 0xf5, 0x59, 0x27, 0xee, 0xfc, 0x08, 0xe1, 0xb0, 0x02, 0xb6, 0xec, 0xe0, 0x5d, 0xbf }; static unsigned char early_secret[] = { 0x33, 0xad, 0x0a, 0x1c, 0x60, 0x7e, 0xc0, 0x3b, 0x09, 0xe6, 0xcd, 0x98, 0x93, 0x68, 0x0c, 0xe2, 0x10, 0xad, 0xf3, 0x00, 0xaa, 0x1f, 0x26, 0x60, 0xe1, 0xb2, 0x2e, 0x10, 0xf1, 0x70, 0xf9, 0x2a }; static unsigned char ecdhe_secret[] = { 0x81, 0x51, 0xd1, 0x46, 0x4c, 0x1b, 0x55, 0x53, 0x36, 0x23, 0xb9, 0xc2, 0x24, 0x6a, 0x6a, 0x0e, 0x6e, 0x7e, 0x18, 0x50, 0x63, 0xe1, 0x4a, 0xfd, 0xaf, 0xf0, 0xb6, 0xe1, 0xc6, 0x1a, 0x86, 0x42 }; static unsigned char handshake_secret[] = { 0x5b, 0x4f, 0x96, 0x5d, 0xf0, 0x3c, 0x68, 0x2c, 0x46, 0xe6, 0xee, 0x86, 0xc3, 0x11, 0x63, 0x66, 0x15, 0xa1, 0xd2, 0xbb, 0xb2, 0x43, 0x45, 0xc2, 0x52, 0x05, 0x95, 0x3c, 0x87, 0x9e, 0x8d, 0x06 }; static const char *client_hts_label = "c hs traffic"; static unsigned char client_hts[] = { 0xe2, 0xe2, 0x32, 0x07, 0xbd, 0x93, 0xfb, 0x7f, 0xe4, 0xfc, 0x2e, 0x29, 0x7a, 0xfe, 0xab, 0x16, 0x0e, 0x52, 0x2b, 0x5a, 0xb7, 0x5d, 0x64, 0xa8, 0x6e, 0x75, 0xbc, 0xac, 0x3f, 0x3e, 0x51, 0x03 }; static unsigned char client_hts_key[] = { 0x26, 0x79, 0xa4, 0x3e, 0x1d, 0x76, 0x78, 0x40, 0x34, 0xea, 0x17, 0x97, 0xd5, 0xad, 0x26, 0x49 }; static unsigned char client_hts_iv[] = { 0x54, 0x82, 0x40, 0x52, 0x90, 0xdd, 0x0d, 0x2f, 0x81, 0xc0, 0xd9, 0x42 }; static const char *server_hts_label = "s hs traffic"; static unsigned char server_hts[] = { 0x3b, 0x7a, 0x83, 0x9c, 0x23, 0x9e, 0xf2, 0xbf, 0x0b, 0x73, 0x05, 0xa0, 0xe0, 0xc4, 0xe5, 0xa8, 0xc6, 0xc6, 0x93, 0x30, 0xa7, 0x53, 0xb3, 0x08, 0xf5, 0xe3, 0xa8, 0x3a, 0xa2, 0xef, 0x69, 0x79 }; static unsigned char server_hts_key[] = { 0xc6, 0x6c, 0xb1, 0xae, 0xc5, 0x19, 0xdf, 0x44, 0xc9, 0x1e, 0x10, 0x99, 0x55, 0x11, 0xac, 0x8b }; static unsigned char server_hts_iv[] = { 0xf7, 0xf6, 0x88, 0x4c, 0x49, 0x81, 0x71, 0x6c, 0x2d, 0x0d, 0x29, 0xa4 }; static unsigned char master_secret[] = { 0x5c, 0x79, 0xd1, 0x69, 0x42, 0x4e, 0x26, 0x2b, 0x56, 0x32, 0x03, 0x62, 0x7b, 0xe4, 0xeb, 0x51, 0x03, 0x3f, 0x58, 0x8c, 0x43, 0xc9, 0xce, 0x03, 0x73, 0x37, 0x2d, 0xbc, 0xbc, 0x01, 0x85, 0xa7 }; static const char *client_ats_label = "c ap traffic"; static unsigned char client_ats[] = { 0xe2, 0xf0, 0xdb, 0x6a, 0x82, 0xe8, 0x82, 0x80, 0xfc, 0x26, 0xf7, 0x3c, 0x89, 0x85, 0x4e, 0xe8, 0x61, 0x5e, 0x25, 0xdf, 0x28, 0xb2, 0x20, 0x79, 0x62, 0xfa, 0x78, 0x22, 0x26, 0xb2, 0x36, 0x26 }; static unsigned char client_ats_key[] = { 0x88, 0xb9, 0x6a, 0xd6, 0x86, 0xc8, 0x4b, 0xe5, 0x5a, 0xce, 0x18, 0xa5, 0x9c, 0xce, 0x5c, 0x87 }; static unsigned char client_ats_iv[] = { 0xb9, 0x9d, 0xc5, 0x8c, 0xd5, 0xff, 0x5a, 0xb0, 0x82, 0xfd, 0xad, 0x19 }; static const char *server_ats_label = "s ap traffic"; static unsigned char server_ats[] = { 0x5b, 0x73, 0xb1, 0x08, 0xd9, 0xac, 0x1b, 0x9b, 0x0c, 0x82, 0x48, 0xca, 0x39, 0x26, 0xec, 0x6e, 0x7b, 0xc4, 0x7e, 0x41, 0x17, 0x06, 0x96, 0x39, 0x87, 0xec, 0x11, 0x43, 0x5d, 0x30, 0x57, 0x19 }; static unsigned char server_ats_key[] = { 0xa6, 0x88, 0xeb, 0xb5, 0xac, 0x82, 0x6d, 0x6f, 0x42, 0xd4, 0x5c, 0x0c, 0xc4, 0x4b, 0x9b, 0x7d }; static unsigned char server_ats_iv[] = { 0xc1, 0xca, 0xd4, 0x42, 0x5a, 0x43, 0x8b, 0x5d, 0xe7, 0x14, 0x83, 0x0a }; /* Mocked out implementations of various functions */ int ssl3_digest_cached_records(SSL_CONNECTION *s, int keep) { return 1; } static int full_hash = 0; /* Give a hash of the currently set handshake */ int ssl_handshake_hash(SSL_CONNECTION *s, unsigned char *out, size_t outlen, size_t *hashlen) { if (sizeof(hs_start_hash) > outlen || sizeof(hs_full_hash) != sizeof(hs_start_hash)) return 0; if (full_hash) { memcpy(out, hs_full_hash, sizeof(hs_full_hash)); *hashlen = sizeof(hs_full_hash); } else { memcpy(out, hs_start_hash, sizeof(hs_start_hash)); *hashlen = sizeof(hs_start_hash); } return 1; } const EVP_MD *ssl_handshake_md(SSL_CONNECTION *s) { return EVP_sha256(); } int ssl_cipher_get_evp_cipher(SSL_CTX *ctx, const SSL_CIPHER *sslc, const EVP_CIPHER **enc) { return 0; } int ssl_cipher_get_evp(SSL_CTX *ctx, const SSL_SESSION *s, const EVP_CIPHER **enc, const EVP_MD **md, int *mac_pkey_type, size_t *mac_secret_size, SSL_COMP **comp, int use_etm) { return 0; } int tls1_alert_code(int code) { return code; } int ssl_log_secret(SSL_CONNECTION *sc, const char *label, const uint8_t *secret, size_t secret_len) { return 1; } const EVP_MD *ssl_md(SSL_CTX *ctx, int idx) { return EVP_sha256(); } void ossl_statem_send_fatal(SSL_CONNECTION *s, int al) { } void ossl_statem_fatal(SSL_CONNECTION *s, int al, int reason, const char *fmt, ...) { } int ossl_statem_export_allowed(SSL_CONNECTION *s) { return 1; } int ossl_statem_export_early_allowed(SSL_CONNECTION *s) { return 1; } void ssl_evp_cipher_free(const EVP_CIPHER *cipher) { } void ssl_evp_md_free(const EVP_MD *md) { } int ssl_set_new_record_layer(SSL_CONNECTION *s, int version, int direction, int level, unsigned char *secret, size_t secretlen, unsigned char *key, size_t keylen, unsigned char *iv, size_t ivlen, unsigned char *mackey, size_t mackeylen, const EVP_CIPHER *ciph, size_t taglen, int mactype, const EVP_MD *md, const SSL_COMP *comp, const EVP_MD *kdfdigest) { return 0; } /* End of mocked out code */ static int test_secret(SSL_CONNECTION *s, unsigned char *prk, const unsigned char *label, size_t labellen, const unsigned char *ref_secret, const unsigned char *ref_key, const unsigned char *ref_iv) { size_t hashsize; unsigned char gensecret[EVP_MAX_MD_SIZE]; unsigned char hash[EVP_MAX_MD_SIZE]; unsigned char key[KEYLEN]; unsigned char iv[IVLEN]; const EVP_MD *md = ssl_handshake_md(s); if (!ssl_handshake_hash(s, hash, sizeof(hash), &hashsize)) { TEST_error("Failed to get hash"); return 0; } if (!tls13_hkdf_expand(s, md, prk, label, labellen, hash, hashsize, gensecret, hashsize, 1)) { TEST_error("Secret generation failed"); return 0; } if (!TEST_mem_eq(gensecret, hashsize, ref_secret, hashsize)) return 0; if (!tls13_derive_key(s, md, gensecret, key, KEYLEN)) { TEST_error("Key generation failed"); return 0; } if (!TEST_mem_eq(key, KEYLEN, ref_key, KEYLEN)) return 0; if (!tls13_derive_iv(s, md, gensecret, iv, IVLEN)) { TEST_error("IV generation failed"); return 0; } if (!TEST_mem_eq(iv, IVLEN, ref_iv, IVLEN)) return 0; return 1; } static int test_handshake_secrets(void) { SSL_CTX *ctx = NULL; SSL *ssl = NULL; SSL_CONNECTION *s; int ret = 0; size_t hashsize; unsigned char out_master_secret[EVP_MAX_MD_SIZE]; size_t master_secret_length; ctx = SSL_CTX_new(TLS_method()); if (!TEST_ptr(ctx)) goto err; ssl = SSL_new(ctx); if (!TEST_ptr(ssl) || !TEST_ptr(s = SSL_CONNECTION_FROM_SSL_ONLY(ssl))) goto err; s->session = SSL_SESSION_new(); if (!TEST_ptr(s->session)) goto err; if (!TEST_true(tls13_generate_secret(s, ssl_handshake_md(s), NULL, NULL, 0, (unsigned char *)&s->early_secret))) { TEST_info("Early secret generation failed"); goto err; } if (!TEST_mem_eq(s->early_secret, sizeof(early_secret), early_secret, sizeof(early_secret))) { TEST_info("Early secret does not match"); goto err; } if (!TEST_true(tls13_generate_handshake_secret(s, ecdhe_secret, sizeof(ecdhe_secret)))) { TEST_info("Handshake secret generation failed"); goto err; } if (!TEST_mem_eq(s->handshake_secret, sizeof(handshake_secret), handshake_secret, sizeof(handshake_secret))) goto err; hashsize = EVP_MD_get_size(ssl_handshake_md(s)); if (!TEST_size_t_eq(sizeof(client_hts), hashsize)) goto err; if (!TEST_size_t_eq(sizeof(client_hts_key), KEYLEN)) goto err; if (!TEST_size_t_eq(sizeof(client_hts_iv), IVLEN)) goto err; if (!TEST_true(test_secret(s, s->handshake_secret, (unsigned char *)client_hts_label, strlen(client_hts_label), client_hts, client_hts_key, client_hts_iv))) { TEST_info("Client handshake secret test failed"); goto err; } if (!TEST_size_t_eq(sizeof(server_hts), hashsize)) goto err; if (!TEST_size_t_eq(sizeof(server_hts_key), KEYLEN)) goto err; if (!TEST_size_t_eq(sizeof(server_hts_iv), IVLEN)) goto err; if (!TEST_true(test_secret(s, s->handshake_secret, (unsigned char *)server_hts_label, strlen(server_hts_label), server_hts, server_hts_key, server_hts_iv))) { TEST_info("Server handshake secret test failed"); goto err; } /* * Ensure the mocked out ssl_handshake_hash() returns the full handshake * hash. */ full_hash = 1; if (!TEST_true(tls13_generate_master_secret(s, out_master_secret, s->handshake_secret, hashsize, &master_secret_length))) { TEST_info("Master secret generation failed"); goto err; } if (!TEST_mem_eq(out_master_secret, master_secret_length, master_secret, sizeof(master_secret))) { TEST_info("Master secret does not match"); goto err; } if (!TEST_size_t_eq(sizeof(client_ats), hashsize)) goto err; if (!TEST_size_t_eq(sizeof(client_ats_key), KEYLEN)) goto err; if (!TEST_size_t_eq(sizeof(client_ats_iv), IVLEN)) goto err; if (!TEST_true(test_secret(s, out_master_secret, (unsigned char *)client_ats_label, strlen(client_ats_label), client_ats, client_ats_key, client_ats_iv))) { TEST_info("Client application data secret test failed"); goto err; } if (!TEST_size_t_eq(sizeof(server_ats), hashsize)) goto err; if (!TEST_size_t_eq(sizeof(server_ats_key), KEYLEN)) goto err; if (!TEST_size_t_eq(sizeof(server_ats_iv), IVLEN)) goto err; if (!TEST_true(test_secret(s, out_master_secret, (unsigned char *)server_ats_label, strlen(server_ats_label), server_ats, server_ats_key, server_ats_iv))) { TEST_info("Server application data secret test failed"); goto err; } ret = 1; err: SSL_free(ssl); SSL_CTX_free(ctx); return ret; } int setup_tests(void) { ADD_TEST(test_handshake_secrets); return 1; }
./openssl/test/bntest.c
/* * Copyright 1995-2023 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <assert.h> #include <errno.h> #include <stdio.h> #include <string.h> #ifdef __TANDEM # include <strings.h> /* strcasecmp */ #endif #include <ctype.h> #include <openssl/bn.h> #include <openssl/crypto.h> #include <openssl/err.h> #include <openssl/rand.h> #include "internal/nelem.h" #include "internal/numbers.h" #include "testutil.h" /* * Things in boring, not in openssl. */ #define HAVE_BN_SQRT 0 typedef struct filetest_st { const char *name; int (*func)(STANZA *s); } FILETEST; typedef struct mpitest_st { const char *base10; const char *mpi; size_t mpi_len; } MPITEST; static const int NUM0 = 100; /* number of tests */ static const int NUM1 = 50; /* additional tests for some functions */ static const int NUM_PRIME_TESTS = 20; static BN_CTX *ctx; /* * Polynomial coefficients used in GFM tests. */ #ifndef OPENSSL_NO_EC2M static int p0[] = { 163, 7, 6, 3, 0, -1 }; static int p1[] = { 193, 15, 0, -1 }; #endif /* * Look for |key| in the stanza and return it or NULL if not found. */ static const char *findattr(STANZA *s, const char *key) { int i = s->numpairs; PAIR *pp = s->pairs; for ( ; --i >= 0; pp++) if (OPENSSL_strcasecmp(pp->key, key) == 0) return pp->value; return NULL; } /* * Parse BIGNUM from sparse hex-strings, return |BN_hex2bn| result. */ static int parse_bigBN(BIGNUM **out, const char *bn_strings[]) { char *bigstring = glue_strings(bn_strings, NULL); int ret = BN_hex2bn(out, bigstring); OPENSSL_free(bigstring); return ret; } /* * Parse BIGNUM, return number of bytes parsed. */ static int parseBN(BIGNUM **out, const char *in) { *out = NULL; return BN_hex2bn(out, in); } static int parsedecBN(BIGNUM **out, const char *in) { *out = NULL; return BN_dec2bn(out, in); } static BIGNUM *getBN(STANZA *s, const char *attribute) { const char *hex; BIGNUM *ret = NULL; if ((hex = findattr(s, attribute)) == NULL) { TEST_error("%s:%d: Can't find %s", s->test_file, s->start, attribute); return NULL; } if (parseBN(&ret, hex) != (int)strlen(hex)) { TEST_error("Could not decode '%s'", hex); return NULL; } return ret; } static int getint(STANZA *s, int *out, const char *attribute) { BIGNUM *ret; BN_ULONG word; int st = 0; if (!TEST_ptr(ret = getBN(s, attribute)) || !TEST_ulong_le(word = BN_get_word(ret), INT_MAX)) goto err; *out = (int)word; st = 1; err: BN_free(ret); return st; } static int equalBN(const char *op, const BIGNUM *expected, const BIGNUM *actual) { if (BN_cmp(expected, actual) == 0) return 1; TEST_error("unexpected %s value", op); TEST_BN_eq(expected, actual); return 0; } /* * Return a "random" flag for if a BN should be negated. */ static int rand_neg(void) { static unsigned int neg = 0; static int sign[8] = { 0, 0, 0, 1, 1, 0, 1, 1 }; return sign[(neg++) % 8]; } static int test_swap(void) { BIGNUM *a = NULL, *b = NULL, *c = NULL, *d = NULL; int top, cond, st = 0; if (!TEST_ptr(a = BN_new()) || !TEST_ptr(b = BN_new()) || !TEST_ptr(c = BN_new()) || !TEST_ptr(d = BN_new())) goto err; if (!(TEST_true(BN_bntest_rand(a, 1024, 1, 0)) && TEST_true(BN_bntest_rand(b, 1024, 1, 0)) && TEST_ptr(BN_copy(c, a)) && TEST_ptr(BN_copy(d, b)))) goto err; top = BN_num_bits(a) / BN_BITS2; /* regular swap */ BN_swap(a, b); if (!equalBN("swap", a, d) || !equalBN("swap", b, c)) goto err; /* regular swap: same pointer */ BN_swap(a, a); if (!equalBN("swap with same pointer", a, d)) goto err; /* conditional swap: true */ cond = 1; BN_consttime_swap(cond, a, b, top); if (!equalBN("cswap true", a, c) || !equalBN("cswap true", b, d)) goto err; /* conditional swap: true, same pointer */ BN_consttime_swap(cond, a, a, top); if (!equalBN("cswap true", a, c)) goto err; /* conditional swap: false */ cond = 0; BN_consttime_swap(cond, a, b, top); if (!equalBN("cswap false", a, c) || !equalBN("cswap false", b, d)) goto err; /* conditional swap: false, same pointer */ BN_consttime_swap(cond, a, a, top); if (!equalBN("cswap false", a, c)) goto err; /* same tests but checking flag swap */ BN_set_flags(a, BN_FLG_CONSTTIME); BN_swap(a, b); if (!equalBN("swap, flags", a, d) || !equalBN("swap, flags", b, c) || !TEST_true(BN_get_flags(b, BN_FLG_CONSTTIME)) || !TEST_false(BN_get_flags(a, BN_FLG_CONSTTIME))) goto err; cond = 1; BN_consttime_swap(cond, a, b, top); if (!equalBN("cswap true, flags", a, c) || !equalBN("cswap true, flags", b, d) || !TEST_true(BN_get_flags(a, BN_FLG_CONSTTIME)) || !TEST_false(BN_get_flags(b, BN_FLG_CONSTTIME))) goto err; cond = 0; BN_consttime_swap(cond, a, b, top); if (!equalBN("cswap false, flags", a, c) || !equalBN("cswap false, flags", b, d) || !TEST_true(BN_get_flags(a, BN_FLG_CONSTTIME)) || !TEST_false(BN_get_flags(b, BN_FLG_CONSTTIME))) goto err; st = 1; err: BN_free(a); BN_free(b); BN_free(c); BN_free(d); return st; } static int test_sub(void) { BIGNUM *a = NULL, *b = NULL, *c = NULL; int i, st = 0; if (!TEST_ptr(a = BN_new()) || !TEST_ptr(b = BN_new()) || !TEST_ptr(c = BN_new())) goto err; for (i = 0; i < NUM0 + NUM1; i++) { if (i < NUM1) { if (!(TEST_true(BN_bntest_rand(a, 512, 0, 0))) && TEST_ptr(BN_copy(b, a)) && TEST_int_ne(BN_set_bit(a, i), 0) && TEST_true(BN_add_word(b, i))) goto err; } else { if (!TEST_true(BN_bntest_rand(b, 400 + i - NUM1, 0, 0))) goto err; BN_set_negative(a, rand_neg()); BN_set_negative(b, rand_neg()); } if (!(TEST_true(BN_sub(c, a, b)) && TEST_true(BN_add(c, c, b)) && TEST_true(BN_sub(c, c, a)) && TEST_BN_eq_zero(c))) goto err; } st = 1; err: BN_free(a); BN_free(b); BN_free(c); return st; } static int test_div_recip(void) { BIGNUM *a = NULL, *b = NULL, *c = NULL, *d = NULL, *e = NULL; BN_RECP_CTX *recp = NULL; int st = 0, i; if (!TEST_ptr(a = BN_new()) || !TEST_ptr(b = BN_new()) || !TEST_ptr(c = BN_new()) || !TEST_ptr(d = BN_new()) || !TEST_ptr(e = BN_new()) || !TEST_ptr(recp = BN_RECP_CTX_new())) goto err; for (i = 0; i < NUM0 + NUM1; i++) { if (i < NUM1) { if (!(TEST_true(BN_bntest_rand(a, 400, 0, 0)) && TEST_ptr(BN_copy(b, a)) && TEST_true(BN_lshift(a, a, i)) && TEST_true(BN_add_word(a, i)))) goto err; } else { if (!(TEST_true(BN_bntest_rand(b, 50 + 3 * (i - NUM1), 0, 0)))) goto err; } BN_set_negative(a, rand_neg()); BN_set_negative(b, rand_neg()); if (!(TEST_true(BN_RECP_CTX_set(recp, b, ctx)) && TEST_true(BN_div_recp(d, c, a, recp, ctx)) && TEST_true(BN_mul(e, d, b, ctx)) && TEST_true(BN_add(d, e, c)) && TEST_true(BN_sub(d, d, a)) && TEST_BN_eq_zero(d))) goto err; } st = 1; err: BN_free(a); BN_free(b); BN_free(c); BN_free(d); BN_free(e); BN_RECP_CTX_free(recp); return st; } static struct { int n, divisor, result, remainder; } signed_mod_tests[] = { { 10, 3, 3, 1 }, { -10, 3, -3, -1 }, { 10, -3, -3, 1 }, { -10, -3, 3, -1 }, }; static BIGNUM *set_signed_bn(int value) { BIGNUM *bn = BN_new(); if (bn == NULL) return NULL; if (!BN_set_word(bn, value < 0 ? -value : value)) { BN_free(bn); return NULL; } BN_set_negative(bn, value < 0); return bn; } static int test_signed_mod_replace_ab(int n) { BIGNUM *a = NULL, *b = NULL, *c = NULL, *d = NULL; int st = 0; if (!TEST_ptr(a = set_signed_bn(signed_mod_tests[n].n)) || !TEST_ptr(b = set_signed_bn(signed_mod_tests[n].divisor)) || !TEST_ptr(c = set_signed_bn(signed_mod_tests[n].result)) || !TEST_ptr(d = set_signed_bn(signed_mod_tests[n].remainder))) goto err; if (TEST_true(BN_div(a, b, a, b, ctx)) && TEST_BN_eq(a, c) && TEST_BN_eq(b, d)) st = 1; err: BN_free(a); BN_free(b); BN_free(c); BN_free(d); return st; } static int test_signed_mod_replace_ba(int n) { BIGNUM *a = NULL, *b = NULL, *c = NULL, *d = NULL; int st = 0; if (!TEST_ptr(a = set_signed_bn(signed_mod_tests[n].n)) || !TEST_ptr(b = set_signed_bn(signed_mod_tests[n].divisor)) || !TEST_ptr(c = set_signed_bn(signed_mod_tests[n].result)) || !TEST_ptr(d = set_signed_bn(signed_mod_tests[n].remainder))) goto err; if (TEST_true(BN_div(b, a, a, b, ctx)) && TEST_BN_eq(b, c) && TEST_BN_eq(a, d)) st = 1; err: BN_free(a); BN_free(b); BN_free(c); BN_free(d); return st; } static int test_mod(void) { BIGNUM *a = NULL, *b = NULL, *c = NULL, *d = NULL, *e = NULL; int st = 0, i; if (!TEST_ptr(a = BN_new()) || !TEST_ptr(b = BN_new()) || !TEST_ptr(c = BN_new()) || !TEST_ptr(d = BN_new()) || !TEST_ptr(e = BN_new())) goto err; if (!(TEST_true(BN_bntest_rand(a, 1024, 0, 0)))) goto err; for (i = 0; i < NUM0; i++) { if (!(TEST_true(BN_bntest_rand(b, 450 + i * 10, 0, 0)))) goto err; BN_set_negative(a, rand_neg()); BN_set_negative(b, rand_neg()); if (!(TEST_true(BN_mod(c, a, b, ctx)) && TEST_true(BN_div(d, e, a, b, ctx)) && TEST_BN_eq(e, c) && TEST_true(BN_mul(c, d, b, ctx)) && TEST_true(BN_add(d, c, e)) && TEST_BN_eq(d, a))) goto err; } st = 1; err: BN_free(a); BN_free(b); BN_free(c); BN_free(d); BN_free(e); return st; } static const char *bn1strings[] = { "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF", "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF", "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF", "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF", "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF", "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF", "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF", "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF00000000000000FFFFFFFF00", "0000000000000000000000000000000000000000000000000000000000000000", "0000000000000000000000000000000000000000000000000000000000000000", "0000000000000000000000000000000000000000000000000000000000000000", "0000000000000000000000000000000000000000000000000000000000000000", "0000000000000000000000000000000000000000000000000000000000000000", "0000000000000000000000000000000000000000000000000000000000000000", "0000000000000000000000000000000000000000000000000000000000000000", "00000000000000000000000000000000000000000000000000FFFFFFFFFFFFFF", NULL }; static const char *bn2strings[] = { "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF", "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF", "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF", "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF", "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF", "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF", "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF", "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF00000000000000FFFFFFFF0000000000", "0000000000000000000000000000000000000000000000000000000000000000", "0000000000000000000000000000000000000000000000000000000000000000", "0000000000000000000000000000000000000000000000000000000000000000", "0000000000000000000000000000000000000000000000000000000000000000", "0000000000000000000000000000000000000000000000000000000000000000", "0000000000000000000000000000000000000000000000000000000000000000", "0000000000000000000000000000000000000000000000000000000000000000", "000000000000000000000000000000000000000000FFFFFFFFFFFFFF00000000", NULL }; /* * Test constant-time modular exponentiation with 1024-bit inputs, which on * x86_64 cause a different code branch to be taken. */ static int test_modexp_mont5(void) { BIGNUM *a = NULL, *p = NULL, *m = NULL, *d = NULL, *e = NULL; BIGNUM *b = NULL, *n = NULL, *c = NULL; BN_MONT_CTX *mont = NULL; int st = 0; if (!TEST_ptr(a = BN_new()) || !TEST_ptr(p = BN_new()) || !TEST_ptr(m = BN_new()) || !TEST_ptr(d = BN_new()) || !TEST_ptr(e = BN_new()) || !TEST_ptr(b = BN_new()) || !TEST_ptr(n = BN_new()) || !TEST_ptr(c = BN_new()) || !TEST_ptr(mont = BN_MONT_CTX_new())) goto err; /* must be odd for montgomery */ if (!(TEST_true(BN_bntest_rand(m, 1024, 0, 1)) /* Zero exponent */ && TEST_true(BN_bntest_rand(a, 1024, 0, 0)))) goto err; BN_zero(p); if (!TEST_true(BN_mod_exp_mont_consttime(d, a, p, m, ctx, NULL))) goto err; if (!TEST_BN_eq_one(d)) goto err; /* Regression test for carry bug in mulx4x_mont */ if (!(TEST_true(BN_hex2bn(&a, "7878787878787878787878787878787878787878787878787878787878787878" "7878787878787878787878787878787878787878787878787878787878787878" "7878787878787878787878787878787878787878787878787878787878787878" "7878787878787878787878787878787878787878787878787878787878787878")) && TEST_true(BN_hex2bn(&b, "095D72C08C097BA488C5E439C655A192EAFB6380073D8C2664668EDDB4060744" "E16E57FB4EDB9AE10A0CEFCDC28A894F689A128379DB279D48A2E20849D68593" "9B7803BCF46CEBF5C533FB0DD35B080593DE5472E3FE5DB951B8BFF9B4CB8F03" "9CC638A5EE8CDD703719F8000E6A9F63BEED5F2FCD52FF293EA05A251BB4AB81")) && TEST_true(BN_hex2bn(&n, "D78AF684E71DB0C39CFF4E64FB9DB567132CB9C50CC98009FEB820B26F2DED9B" "91B9B5E2B83AE0AE4EB4E0523CA726BFBE969B89FD754F674CE99118C3F2D1C5" "D81FDC7C54E02B60262B241D53C040E99E45826ECA37A804668E690E1AFC1CA4" "2C9A15D84D4954425F0B7642FC0BD9D7B24E2618D2DCC9B729D944BADACFDDAF")))) goto err; if (!(TEST_true(BN_MONT_CTX_set(mont, n, ctx)) && TEST_true(BN_mod_mul_montgomery(c, a, b, mont, ctx)) && TEST_true(BN_mod_mul_montgomery(d, b, a, mont, ctx)) && TEST_BN_eq(c, d))) goto err; /* Regression test for carry bug in sqr[x]8x_mont */ if (!(TEST_true(parse_bigBN(&n, bn1strings)) && TEST_true(parse_bigBN(&a, bn2strings)))) goto err; BN_free(b); if (!(TEST_ptr(b = BN_dup(a)) && TEST_true(BN_MONT_CTX_set(mont, n, ctx)) && TEST_true(BN_mod_mul_montgomery(c, a, a, mont, ctx)) && TEST_true(BN_mod_mul_montgomery(d, a, b, mont, ctx)) && TEST_BN_eq(c, d))) goto err; /* Regression test for carry bug in bn_sqrx8x_internal */ { static const char *ahex[] = { "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF", "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF", "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF", "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF", "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF8FFEADBCFC4DAE7FFF908E92820306B", "9544D954000000006C0000000000000000000000000000000000000000000000", "00000000000000000000FF030202FFFFF8FFEBDBCFC4DAE7FFF908E92820306B", "9544D954000000006C000000FF0302030000000000FFFFFFFFFFFFFFFFFFFFFF", "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF01FC00FF02FFFFFFFF", "00FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF00FCFD", "FCFFFFFFFFFF000000000000000000FF0302030000000000FFFFFFFFFFFFFFFF", "FF00FCFDFDFF030202FF00000000FFFFFFFFFFFFFFFFFF00FCFDFCFFFFFFFFFF", NULL }; static const char *nhex[] = { "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF", "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF", "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF", "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF", "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF8F8F8F8000000", "00000010000000006C0000000000000000000000000000000000000000000000", "00000000000000000000000000000000000000FFFFFFFFFFFFF8F8F8F8000000", "00000010000000006C000000000000000000000000FFFFFFFFFFFFFFFFFFFFFF", "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF", "00FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF", "FFFFFFFFFFFF000000000000000000000000000000000000FFFFFFFFFFFFFFFF", "FFFFFFFFFFFFFFFFFFFF00000000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF", NULL }; if (!(TEST_true(parse_bigBN(&a, ahex)) && TEST_true(parse_bigBN(&n, nhex)))) goto err; } BN_free(b); if (!(TEST_ptr(b = BN_dup(a)) && TEST_true(BN_MONT_CTX_set(mont, n, ctx)))) goto err; if (!TEST_true(BN_mod_mul_montgomery(c, a, a, mont, ctx)) || !TEST_true(BN_mod_mul_montgomery(d, a, b, mont, ctx)) || !TEST_BN_eq(c, d)) goto err; /* Regression test for bug in BN_from_montgomery_word */ if (!(TEST_true(BN_hex2bn(&a, "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF" "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF" "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF")) && TEST_true(BN_hex2bn(&n, "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF" "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF")) && TEST_true(BN_MONT_CTX_set(mont, n, ctx)) && TEST_false(BN_mod_mul_montgomery(d, a, a, mont, ctx)))) goto err; /* Regression test for bug in rsaz_1024_mul_avx2 */ if (!(TEST_true(BN_hex2bn(&a, "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF" "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF" "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF" "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF2020202020DF")) && TEST_true(BN_hex2bn(&b, "2020202020202020202020202020202020202020202020202020202020202020" "2020202020202020202020202020202020202020202020202020202020202020" "20202020202020FF202020202020202020202020202020202020202020202020" "2020202020202020202020202020202020202020202020202020202020202020")) && TEST_true(BN_hex2bn(&n, "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF" "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF" "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF" "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF2020202020FF")) && TEST_true(BN_MONT_CTX_set(mont, n, ctx)) && TEST_true(BN_mod_exp_mont_consttime(c, a, b, n, ctx, mont)) && TEST_true(BN_mod_exp_mont(d, a, b, n, ctx, mont)) && TEST_BN_eq(c, d))) goto err; /* * rsaz_1024_mul_avx2 expects fully-reduced inputs. * BN_mod_exp_mont_consttime should reduce the input first. */ if (!(TEST_true(BN_hex2bn(&a, "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF" "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF" "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF" "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF2020202020DF")) && TEST_true(BN_hex2bn(&b, "1FA53F26F8811C58BE0357897AA5E165693230BC9DF5F01DFA6A2D59229EC69D" "9DE6A89C36E3B6957B22D6FAAD5A3C73AE587B710DBE92E83D3A9A3339A085CB" "B58F508CA4F837924BB52CC1698B7FDC2FD74362456A595A5B58E38E38E38E38" "E38E38E38E38E38E38E38E38E38E38E38E38E38E38E38E38E38E38E38E38E38E")) && TEST_true(BN_hex2bn(&n, "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF" "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF" "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF" "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF2020202020DF")) && TEST_true(BN_MONT_CTX_set(mont, n, ctx)) && TEST_true(BN_mod_exp_mont_consttime(c, a, b, n, ctx, mont)))) goto err; BN_zero(d); if (!TEST_BN_eq(c, d)) goto err; /* * Regression test for overflow bug in bn_sqr_comba4/8 for * mips-linux-gnu and mipsel-linux-gnu 32bit targets. */ { static const char *ehex[] = { "95564994a96c45954227b845a1e99cb939d5a1da99ee91acc962396ae999a9ee", "38603790448f2f7694c242a875f0cad0aae658eba085f312d2febbbd128dd2b5", "8f7d1149f03724215d704344d0d62c587ae3c5939cba4b9b5f3dc5e8e911ef9a", "5ce1a5a749a4989d0d8368f6e1f8cdf3a362a6c97fb02047ff152b480a4ad985", "2d45efdf0770542992afca6a0590d52930434bba96017afbc9f99e112950a8b1", "a359473ec376f329bdae6a19f503be6d4be7393c4e43468831234e27e3838680", "b949390d2e416a3f9759e5349ab4c253f6f29f819a6fe4cbfd27ada34903300e", "da021f62839f5878a36f1bc3085375b00fd5fa3e68d316c0fdace87a97558465", NULL}; static const char *phex[] = { "f95dc0f980fbd22e90caa5a387cc4a369f3f830d50dd321c40db8c09a7e1a241", "a536e096622d3280c0c1ba849c1f4a79bf490f60006d081e8cf69960189f0d31", "2cd9e17073a3fba7881b21474a13b334116cb2f5dbf3189a6de3515d0840f053", "c776d3982d391b6d04d642dda5cc6d1640174c09875addb70595658f89efb439", "dc6fbd55f903aadd307982d3f659207f265e1ec6271b274521b7a5e28e8fd7a5", "5df089292820477802a43cf5b6b94e999e8c9944ddebb0d0e95a60f88cb7e813", "ba110d20e1024774107dd02949031864923b3cb8c3f7250d6d1287b0a40db6a4", "7bd5a469518eb65aa207ddc47d8c6e5fc8e0c105be8fc1d4b57b2e27540471d5", NULL}; static const char *mhex[] = { "fef15d5ce4625f1bccfbba49fc8439c72bf8202af039a2259678941b60bb4a8f", "2987e965d58fd8cf86a856674d519763d0e1211cc9f8596971050d56d9b35db3", "785866cfbca17cfdbed6060be3629d894f924a89fdc1efc624f80d41a22f1900", "9503fcc3824ef62ccb9208430c26f2d8ceb2c63488ec4c07437aa4c96c43dd8b", "9289ed00a712ff66ee195dc71f5e4ead02172b63c543d69baf495f5fd63ba7bc", "c633bd309c016e37736da92129d0b053d4ab28d21ad7d8b6fab2a8bbdc8ee647", "d2fbcf2cf426cf892e6f5639e0252993965dfb73ccd277407014ea784aaa280c", "b7b03972bc8b0baa72360bdb44b82415b86b2f260f877791cd33ba8f2d65229b", NULL}; if (!TEST_true(parse_bigBN(&e, ehex)) || !TEST_true(parse_bigBN(&p, phex)) || !TEST_true(parse_bigBN(&m, mhex)) || !TEST_true(BN_mod_exp_mont_consttime(d, e, p, m, ctx, NULL)) || !TEST_true(BN_mod_exp_simple(a, e, p, m, ctx)) || !TEST_BN_eq(a, d)) goto err; } /* Zero input */ if (!TEST_true(BN_bntest_rand(p, 1024, 0, 0))) goto err; BN_zero(a); if (!TEST_true(BN_mod_exp_mont_consttime(d, a, p, m, ctx, NULL)) || !TEST_BN_eq_zero(d)) goto err; /* * Craft an input whose Montgomery representation is 1, i.e., shorter * than the modulus m, in order to test the const time precomputation * scattering/gathering. */ if (!(TEST_true(BN_one(a)) && TEST_true(BN_MONT_CTX_set(mont, m, ctx)))) goto err; if (!TEST_true(BN_from_montgomery(e, a, mont, ctx)) || !TEST_true(BN_mod_exp_mont_consttime(d, e, p, m, ctx, NULL)) || !TEST_true(BN_mod_exp_simple(a, e, p, m, ctx)) || !TEST_BN_eq(a, d)) goto err; /* Finally, some regular test vectors. */ if (!(TEST_true(BN_bntest_rand(e, 1024, 0, 0)) && TEST_true(BN_mod_exp_mont_consttime(d, e, p, m, ctx, NULL)) && TEST_true(BN_mod_exp_simple(a, e, p, m, ctx)) && TEST_BN_eq(a, d))) goto err; st = 1; err: BN_MONT_CTX_free(mont); BN_free(a); BN_free(p); BN_free(m); BN_free(d); BN_free(e); BN_free(b); BN_free(n); BN_free(c); return st; } #ifndef OPENSSL_NO_EC2M static int test_gf2m_add(void) { BIGNUM *a = NULL, *b = NULL, *c = NULL; int i, st = 0; if (!TEST_ptr(a = BN_new()) || !TEST_ptr(b = BN_new()) || !TEST_ptr(c = BN_new())) goto err; for (i = 0; i < NUM0; i++) { if (!(TEST_true(BN_rand(a, 512, 0, 0)) && TEST_ptr(BN_copy(b, BN_value_one())))) goto err; BN_set_negative(a, rand_neg()); BN_set_negative(b, rand_neg()); if (!(TEST_true(BN_GF2m_add(c, a, b)) /* Test that two added values have the correct parity. */ && TEST_false((BN_is_odd(a) && BN_is_odd(c)) || (!BN_is_odd(a) && !BN_is_odd(c))))) goto err; if (!(TEST_true(BN_GF2m_add(c, c, c)) /* Test that c + c = 0. */ && TEST_BN_eq_zero(c))) goto err; } st = 1; err: BN_free(a); BN_free(b); BN_free(c); return st; } static int test_gf2m_mod(void) { BIGNUM *a = NULL, *b[2] = {NULL, NULL}, *c = NULL, *d = NULL, *e = NULL; int i, j, st = 0; if (!TEST_ptr(a = BN_new()) || !TEST_ptr(b[0] = BN_new()) || !TEST_ptr(b[1] = BN_new()) || !TEST_ptr(c = BN_new()) || !TEST_ptr(d = BN_new()) || !TEST_ptr(e = BN_new())) goto err; if (!(TEST_true(BN_GF2m_arr2poly(p0, b[0])) && TEST_true(BN_GF2m_arr2poly(p1, b[1])))) goto err; for (i = 0; i < NUM0; i++) { if (!TEST_true(BN_bntest_rand(a, 1024, 0, 0))) goto err; for (j = 0; j < 2; j++) { if (!(TEST_true(BN_GF2m_mod(c, a, b[j])) && TEST_true(BN_GF2m_add(d, a, c)) && TEST_true(BN_GF2m_mod(e, d, b[j])) /* Test that a + (a mod p) mod p == 0. */ && TEST_BN_eq_zero(e))) goto err; } } st = 1; err: BN_free(a); BN_free(b[0]); BN_free(b[1]); BN_free(c); BN_free(d); BN_free(e); return st; } static int test_gf2m_mul(void) { BIGNUM *a, *b[2] = {NULL, NULL}, *c = NULL, *d = NULL; BIGNUM *e = NULL, *f = NULL, *g = NULL, *h = NULL; int i, j, st = 0; if (!TEST_ptr(a = BN_new()) || !TEST_ptr(b[0] = BN_new()) || !TEST_ptr(b[1] = BN_new()) || !TEST_ptr(c = BN_new()) || !TEST_ptr(d = BN_new()) || !TEST_ptr(e = BN_new()) || !TEST_ptr(f = BN_new()) || !TEST_ptr(g = BN_new()) || !TEST_ptr(h = BN_new())) goto err; if (!(TEST_true(BN_GF2m_arr2poly(p0, b[0])) && TEST_true(BN_GF2m_arr2poly(p1, b[1])))) goto err; for (i = 0; i < NUM0; i++) { if (!(TEST_true(BN_bntest_rand(a, 1024, 0, 0)) && TEST_true(BN_bntest_rand(c, 1024, 0, 0)) && TEST_true(BN_bntest_rand(d, 1024, 0, 0)))) goto err; for (j = 0; j < 2; j++) { if (!(TEST_true(BN_GF2m_mod_mul(e, a, c, b[j], ctx)) && TEST_true(BN_GF2m_add(f, a, d)) && TEST_true(BN_GF2m_mod_mul(g, f, c, b[j], ctx)) && TEST_true(BN_GF2m_mod_mul(h, d, c, b[j], ctx)) && TEST_true(BN_GF2m_add(f, e, g)) && TEST_true(BN_GF2m_add(f, f, h)) /* Test that (a+d)*c = a*c + d*c. */ && TEST_BN_eq_zero(f))) goto err; } } st = 1; err: BN_free(a); BN_free(b[0]); BN_free(b[1]); BN_free(c); BN_free(d); BN_free(e); BN_free(f); BN_free(g); BN_free(h); return st; } static int test_gf2m_sqr(void) { BIGNUM *a = NULL, *b[2] = {NULL, NULL}, *c = NULL, *d = NULL; int i, j, st = 0; if (!TEST_ptr(a = BN_new()) || !TEST_ptr(b[0] = BN_new()) || !TEST_ptr(b[1] = BN_new()) || !TEST_ptr(c = BN_new()) || !TEST_ptr(d = BN_new())) goto err; if (!(TEST_true(BN_GF2m_arr2poly(p0, b[0])) && TEST_true(BN_GF2m_arr2poly(p1, b[1])))) goto err; for (i = 0; i < NUM0; i++) { if (!TEST_true(BN_bntest_rand(a, 1024, 0, 0))) goto err; for (j = 0; j < 2; j++) { if (!(TEST_true(BN_GF2m_mod_sqr(c, a, b[j], ctx)) && TEST_true(BN_copy(d, a)) && TEST_true(BN_GF2m_mod_mul(d, a, d, b[j], ctx)) && TEST_true(BN_GF2m_add(d, c, d)) /* Test that a*a = a^2. */ && TEST_BN_eq_zero(d))) goto err; } } st = 1; err: BN_free(a); BN_free(b[0]); BN_free(b[1]); BN_free(c); BN_free(d); return st; } static int test_gf2m_modinv(void) { BIGNUM *a = NULL, *b[2] = {NULL, NULL}, *c = NULL, *d = NULL; int i, j, st = 0; if (!TEST_ptr(a = BN_new()) || !TEST_ptr(b[0] = BN_new()) || !TEST_ptr(b[1] = BN_new()) || !TEST_ptr(c = BN_new()) || !TEST_ptr(d = BN_new())) goto err; /* Test that a non-sensical, too small value causes a failure */ if (!TEST_true(BN_one(b[0]))) goto err; if (!TEST_true(BN_bntest_rand(a, 512, 0, 0))) goto err; if (!TEST_false(BN_GF2m_mod_inv(c, a, b[0], ctx))) goto err; if (!(TEST_true(BN_GF2m_arr2poly(p0, b[0])) && TEST_true(BN_GF2m_arr2poly(p1, b[1])))) goto err; for (i = 0; i < NUM0; i++) { if (!TEST_true(BN_bntest_rand(a, 512, 0, 0))) goto err; for (j = 0; j < 2; j++) { if (!(TEST_true(BN_GF2m_mod_inv(c, a, b[j], ctx)) && TEST_true(BN_GF2m_mod_mul(d, a, c, b[j], ctx)) /* Test that ((1/a)*a) = 1. */ && TEST_BN_eq_one(d))) goto err; } } st = 1; err: BN_free(a); BN_free(b[0]); BN_free(b[1]); BN_free(c); BN_free(d); return st; } static int test_gf2m_moddiv(void) { BIGNUM *a = NULL, *b[2] = {NULL, NULL}, *c = NULL, *d = NULL; BIGNUM *e = NULL, *f = NULL; int i, j, st = 0; if (!TEST_ptr(a = BN_new()) || !TEST_ptr(b[0] = BN_new()) || !TEST_ptr(b[1] = BN_new()) || !TEST_ptr(c = BN_new()) || !TEST_ptr(d = BN_new()) || !TEST_ptr(e = BN_new()) || !TEST_ptr(f = BN_new())) goto err; if (!(TEST_true(BN_GF2m_arr2poly(p0, b[0])) && TEST_true(BN_GF2m_arr2poly(p1, b[1])))) goto err; for (i = 0; i < NUM0; i++) { if (!(TEST_true(BN_bntest_rand(a, 512, 0, 0)) && TEST_true(BN_bntest_rand(c, 512, 0, 0)))) goto err; for (j = 0; j < 2; j++) { if (!(TEST_true(BN_GF2m_mod_div(d, a, c, b[j], ctx)) && TEST_true(BN_GF2m_mod_mul(e, d, c, b[j], ctx)) && TEST_true(BN_GF2m_mod_div(f, a, e, b[j], ctx)) /* Test that ((a/c)*c)/a = 1. */ && TEST_BN_eq_one(f))) goto err; } } st = 1; err: BN_free(a); BN_free(b[0]); BN_free(b[1]); BN_free(c); BN_free(d); BN_free(e); BN_free(f); return st; } static int test_gf2m_modexp(void) { BIGNUM *a = NULL, *b[2] = {NULL, NULL}, *c = NULL, *d = NULL; BIGNUM *e = NULL, *f = NULL; int i, j, st = 0; if (!TEST_ptr(a = BN_new()) || !TEST_ptr(b[0] = BN_new()) || !TEST_ptr(b[1] = BN_new()) || !TEST_ptr(c = BN_new()) || !TEST_ptr(d = BN_new()) || !TEST_ptr(e = BN_new()) || !TEST_ptr(f = BN_new())) goto err; if (!(TEST_true(BN_GF2m_arr2poly(p0, b[0])) && TEST_true(BN_GF2m_arr2poly(p1, b[1])))) goto err; for (i = 0; i < NUM0; i++) { if (!(TEST_true(BN_bntest_rand(a, 512, 0, 0)) && TEST_true(BN_bntest_rand(c, 512, 0, 0)) && TEST_true(BN_bntest_rand(d, 512, 0, 0)))) goto err; for (j = 0; j < 2; j++) { if (!(TEST_true(BN_GF2m_mod_exp(e, a, c, b[j], ctx)) && TEST_true(BN_GF2m_mod_exp(f, a, d, b[j], ctx)) && TEST_true(BN_GF2m_mod_mul(e, e, f, b[j], ctx)) && TEST_true(BN_add(f, c, d)) && TEST_true(BN_GF2m_mod_exp(f, a, f, b[j], ctx)) && TEST_true(BN_GF2m_add(f, e, f)) /* Test that a^(c+d)=a^c*a^d. */ && TEST_BN_eq_zero(f))) goto err; } } st = 1; err: BN_free(a); BN_free(b[0]); BN_free(b[1]); BN_free(c); BN_free(d); BN_free(e); BN_free(f); return st; } static int test_gf2m_modsqrt(void) { BIGNUM *a = NULL, *b[2] = {NULL, NULL}, *c = NULL, *d = NULL; BIGNUM *e = NULL, *f = NULL; int i, j, st = 0; if (!TEST_ptr(a = BN_new()) || !TEST_ptr(b[0] = BN_new()) || !TEST_ptr(b[1] = BN_new()) || !TEST_ptr(c = BN_new()) || !TEST_ptr(d = BN_new()) || !TEST_ptr(e = BN_new()) || !TEST_ptr(f = BN_new())) goto err; if (!(TEST_true(BN_GF2m_arr2poly(p0, b[0])) && TEST_true(BN_GF2m_arr2poly(p1, b[1])))) goto err; for (i = 0; i < NUM0; i++) { if (!TEST_true(BN_bntest_rand(a, 512, 0, 0))) goto err; for (j = 0; j < 2; j++) { if (!(TEST_true(BN_GF2m_mod(c, a, b[j])) && TEST_true(BN_GF2m_mod_sqrt(d, a, b[j], ctx)) && TEST_true(BN_GF2m_mod_sqr(e, d, b[j], ctx)) && TEST_true(BN_GF2m_add(f, c, e)) /* Test that d^2 = a, where d = sqrt(a). */ && TEST_BN_eq_zero(f))) goto err; } } st = 1; err: BN_free(a); BN_free(b[0]); BN_free(b[1]); BN_free(c); BN_free(d); BN_free(e); BN_free(f); return st; } static int test_gf2m_modsolvequad(void) { BIGNUM *a = NULL, *b[2] = {NULL, NULL}, *c = NULL, *d = NULL; BIGNUM *e = NULL; int i, j, s = 0, t, st = 0; if (!TEST_ptr(a = BN_new()) || !TEST_ptr(b[0] = BN_new()) || !TEST_ptr(b[1] = BN_new()) || !TEST_ptr(c = BN_new()) || !TEST_ptr(d = BN_new()) || !TEST_ptr(e = BN_new())) goto err; if (!(TEST_true(BN_GF2m_arr2poly(p0, b[0])) && TEST_true(BN_GF2m_arr2poly(p1, b[1])))) goto err; for (i = 0; i < NUM0; i++) { if (!TEST_true(BN_bntest_rand(a, 512, 0, 0))) goto err; for (j = 0; j < 2; j++) { t = BN_GF2m_mod_solve_quad(c, a, b[j], ctx); if (t) { s++; if (!(TEST_true(BN_GF2m_mod_sqr(d, c, b[j], ctx)) && TEST_true(BN_GF2m_add(d, c, d)) && TEST_true(BN_GF2m_mod(e, a, b[j])) && TEST_true(BN_GF2m_add(e, e, d)) /* * Test that solution of quadratic c * satisfies c^2 + c = a. */ && TEST_BN_eq_zero(e))) goto err; } } } if (!TEST_int_ge(s, 0)) { TEST_info("%d tests found no roots; probably an error", NUM0); goto err; } st = 1; err: BN_free(a); BN_free(b[0]); BN_free(b[1]); BN_free(c); BN_free(d); BN_free(e); return st; } #endif static int test_kronecker(void) { BIGNUM *a = NULL, *b = NULL, *r = NULL, *t = NULL; int i, legendre, kronecker, st = 0; if (!TEST_ptr(a = BN_new()) || !TEST_ptr(b = BN_new()) || !TEST_ptr(r = BN_new()) || !TEST_ptr(t = BN_new())) goto err; /* * We test BN_kronecker(a, b, ctx) just for b odd (Jacobi symbol). In * this case we know that if b is prime, then BN_kronecker(a, b, ctx) is * congruent to $a^{(b-1)/2}$, modulo $b$ (Legendre symbol). So we * generate a random prime b and compare these values for a number of * random a's. (That is, we run the Solovay-Strassen primality test to * confirm that b is prime, except that we don't want to test whether b * is prime but whether BN_kronecker works.) */ if (!TEST_true(BN_generate_prime_ex(b, 512, 0, NULL, NULL, NULL))) goto err; BN_set_negative(b, rand_neg()); for (i = 0; i < NUM0; i++) { if (!TEST_true(BN_bntest_rand(a, 512, 0, 0))) goto err; BN_set_negative(a, rand_neg()); /* t := (|b|-1)/2 (note that b is odd) */ if (!TEST_true(BN_copy(t, b))) goto err; BN_set_negative(t, 0); if (!TEST_true(BN_sub_word(t, 1))) goto err; if (!TEST_true(BN_rshift1(t, t))) goto err; /* r := a^t mod b */ BN_set_negative(b, 0); if (!TEST_true(BN_mod_exp_recp(r, a, t, b, ctx))) goto err; BN_set_negative(b, 1); if (BN_is_word(r, 1)) legendre = 1; else if (BN_is_zero(r)) legendre = 0; else { if (!TEST_true(BN_add_word(r, 1))) goto err; if (!TEST_int_eq(BN_ucmp(r, b), 0)) { TEST_info("Legendre symbol computation failed"); goto err; } legendre = -1; } if (!TEST_int_ge(kronecker = BN_kronecker(a, b, ctx), -1)) goto err; /* we actually need BN_kronecker(a, |b|) */ if (BN_is_negative(a) && BN_is_negative(b)) kronecker = -kronecker; if (!TEST_int_eq(legendre, kronecker)) goto err; } st = 1; err: BN_free(a); BN_free(b); BN_free(r); BN_free(t); return st; } static int file_sum(STANZA *s) { BIGNUM *a = NULL, *b = NULL, *sum = NULL, *ret = NULL; BN_ULONG b_word; int st = 0; if (!TEST_ptr(a = getBN(s, "A")) || !TEST_ptr(b = getBN(s, "B")) || !TEST_ptr(sum = getBN(s, "Sum")) || !TEST_ptr(ret = BN_new())) goto err; if (!TEST_true(BN_add(ret, a, b)) || !equalBN("A + B", sum, ret) || !TEST_true(BN_sub(ret, sum, a)) || !equalBN("Sum - A", b, ret) || !TEST_true(BN_sub(ret, sum, b)) || !equalBN("Sum - B", a, ret)) goto err; /* * Test that the functions work when |r| and |a| point to the same BIGNUM, * or when |r| and |b| point to the same BIGNUM. * There is no test for all of |r|, |a|, and |b| pointint to the same BIGNUM. */ if (!TEST_true(BN_copy(ret, a)) || !TEST_true(BN_add(ret, ret, b)) || !equalBN("A + B (r is a)", sum, ret) || !TEST_true(BN_copy(ret, b)) || !TEST_true(BN_add(ret, a, ret)) || !equalBN("A + B (r is b)", sum, ret) || !TEST_true(BN_copy(ret, sum)) || !TEST_true(BN_sub(ret, ret, a)) || !equalBN("Sum - A (r is a)", b, ret) || !TEST_true(BN_copy(ret, a)) || !TEST_true(BN_sub(ret, sum, ret)) || !equalBN("Sum - A (r is b)", b, ret) || !TEST_true(BN_copy(ret, sum)) || !TEST_true(BN_sub(ret, ret, b)) || !equalBN("Sum - B (r is a)", a, ret) || !TEST_true(BN_copy(ret, b)) || !TEST_true(BN_sub(ret, sum, ret)) || !equalBN("Sum - B (r is b)", a, ret)) goto err; /* * Test BN_uadd() and BN_usub() with the prerequisites they are * documented as having. Note that these functions are frequently used * when the prerequisites don't hold. In those cases, they are supposed * to work as if the prerequisite hold, but we don't test that yet. */ if (!BN_is_negative(a) && !BN_is_negative(b) && BN_cmp(a, b) >= 0) { if (!TEST_true(BN_uadd(ret, a, b)) || !equalBN("A +u B", sum, ret) || !TEST_true(BN_usub(ret, sum, a)) || !equalBN("Sum -u A", b, ret) || !TEST_true(BN_usub(ret, sum, b)) || !equalBN("Sum -u B", a, ret)) goto err; /* * Test that the functions work when |r| and |a| point to the same * BIGNUM, or when |r| and |b| point to the same BIGNUM. * There is no test for all of |r|, |a|, and |b| pointint to the same * BIGNUM. */ if (!TEST_true(BN_copy(ret, a)) || !TEST_true(BN_uadd(ret, ret, b)) || !equalBN("A +u B (r is a)", sum, ret) || !TEST_true(BN_copy(ret, b)) || !TEST_true(BN_uadd(ret, a, ret)) || !equalBN("A +u B (r is b)", sum, ret) || !TEST_true(BN_copy(ret, sum)) || !TEST_true(BN_usub(ret, ret, a)) || !equalBN("Sum -u A (r is a)", b, ret) || !TEST_true(BN_copy(ret, a)) || !TEST_true(BN_usub(ret, sum, ret)) || !equalBN("Sum -u A (r is b)", b, ret) || !TEST_true(BN_copy(ret, sum)) || !TEST_true(BN_usub(ret, ret, b)) || !equalBN("Sum -u B (r is a)", a, ret) || !TEST_true(BN_copy(ret, b)) || !TEST_true(BN_usub(ret, sum, ret)) || !equalBN("Sum -u B (r is b)", a, ret)) goto err; } /* * Test with BN_add_word() and BN_sub_word() if |b| is small enough. */ b_word = BN_get_word(b); if (!BN_is_negative(b) && b_word != (BN_ULONG)-1) { if (!TEST_true(BN_copy(ret, a)) || !TEST_true(BN_add_word(ret, b_word)) || !equalBN("A + B (word)", sum, ret) || !TEST_true(BN_copy(ret, sum)) || !TEST_true(BN_sub_word(ret, b_word)) || !equalBN("Sum - B (word)", a, ret)) goto err; } st = 1; err: BN_free(a); BN_free(b); BN_free(sum); BN_free(ret); return st; } static int file_lshift1(STANZA *s) { BIGNUM *a = NULL, *lshift1 = NULL, *zero = NULL, *ret = NULL; BIGNUM *two = NULL, *remainder = NULL; int st = 0; if (!TEST_ptr(a = getBN(s, "A")) || !TEST_ptr(lshift1 = getBN(s, "LShift1")) || !TEST_ptr(zero = BN_new()) || !TEST_ptr(ret = BN_new()) || !TEST_ptr(two = BN_new()) || !TEST_ptr(remainder = BN_new())) goto err; BN_zero(zero); if (!TEST_true(BN_set_word(two, 2)) || !TEST_true(BN_add(ret, a, a)) || !equalBN("A + A", lshift1, ret) || !TEST_true(BN_mul(ret, a, two, ctx)) || !equalBN("A * 2", lshift1, ret) || !TEST_true(BN_div(ret, remainder, lshift1, two, ctx)) || !equalBN("LShift1 / 2", a, ret) || !equalBN("LShift1 % 2", zero, remainder) || !TEST_true(BN_lshift1(ret, a)) || !equalBN("A << 1", lshift1, ret) || !TEST_true(BN_rshift1(ret, lshift1)) || !equalBN("LShift >> 1", a, ret) || !TEST_true(BN_rshift1(ret, lshift1)) || !equalBN("LShift >> 1", a, ret)) goto err; /* Set the LSB to 1 and test rshift1 again. */ if (!TEST_true(BN_set_bit(lshift1, 0)) || !TEST_true(BN_div(ret, NULL /* rem */ , lshift1, two, ctx)) || !equalBN("(LShift1 | 1) / 2", a, ret) || !TEST_true(BN_rshift1(ret, lshift1)) || !equalBN("(LShift | 1) >> 1", a, ret)) goto err; st = 1; err: BN_free(a); BN_free(lshift1); BN_free(zero); BN_free(ret); BN_free(two); BN_free(remainder); return st; } static int file_lshift(STANZA *s) { BIGNUM *a = NULL, *lshift = NULL, *ret = NULL; int n = 0, st = 0; if (!TEST_ptr(a = getBN(s, "A")) || !TEST_ptr(lshift = getBN(s, "LShift")) || !TEST_ptr(ret = BN_new()) || !getint(s, &n, "N")) goto err; if (!TEST_true(BN_lshift(ret, a, n)) || !equalBN("A << N", lshift, ret) || !TEST_true(BN_rshift(ret, lshift, n)) || !equalBN("A >> N", a, ret)) goto err; st = 1; err: BN_free(a); BN_free(lshift); BN_free(ret); return st; } static int file_rshift(STANZA *s) { BIGNUM *a = NULL, *rshift = NULL, *ret = NULL; int n = 0, st = 0; if (!TEST_ptr(a = getBN(s, "A")) || !TEST_ptr(rshift = getBN(s, "RShift")) || !TEST_ptr(ret = BN_new()) || !getint(s, &n, "N")) goto err; if (!TEST_true(BN_rshift(ret, a, n)) || !equalBN("A >> N", rshift, ret)) goto err; /* If N == 1, try with rshift1 as well */ if (n == 1) { if (!TEST_true(BN_rshift1(ret, a)) || !equalBN("A >> 1 (rshift1)", rshift, ret)) goto err; } st = 1; err: BN_free(a); BN_free(rshift); BN_free(ret); return st; } static int file_square(STANZA *s) { BIGNUM *a = NULL, *square = NULL, *zero = NULL, *ret = NULL; BIGNUM *remainder = NULL, *tmp = NULL; int st = 0; if (!TEST_ptr(a = getBN(s, "A")) || !TEST_ptr(square = getBN(s, "Square")) || !TEST_ptr(zero = BN_new()) || !TEST_ptr(ret = BN_new()) || !TEST_ptr(remainder = BN_new())) goto err; BN_zero(zero); if (!TEST_true(BN_sqr(ret, a, ctx)) || !equalBN("A^2", square, ret) || !TEST_true(BN_mul(ret, a, a, ctx)) || !equalBN("A * A", square, ret) || !TEST_true(BN_div(ret, remainder, square, a, ctx)) || !equalBN("Square / A", a, ret) || !equalBN("Square % A", zero, remainder)) goto err; #if HAVE_BN_SQRT BN_set_negative(a, 0); if (!TEST_true(BN_sqrt(ret, square, ctx)) || !equalBN("sqrt(Square)", a, ret)) goto err; /* BN_sqrt should fail on non-squares and negative numbers. */ if (!TEST_BN_eq_zero(square)) { if (!TEST_ptr(tmp = BN_new()) || !TEST_true(BN_copy(tmp, square))) goto err; BN_set_negative(tmp, 1); if (!TEST_int_eq(BN_sqrt(ret, tmp, ctx), 0)) goto err; ERR_clear_error(); BN_set_negative(tmp, 0); if (BN_add(tmp, tmp, BN_value_one())) goto err; if (!TEST_int_eq(BN_sqrt(ret, tmp, ctx))) goto err; ERR_clear_error(); } #endif st = 1; err: BN_free(a); BN_free(square); BN_free(zero); BN_free(ret); BN_free(remainder); BN_free(tmp); return st; } static int file_product(STANZA *s) { BIGNUM *a = NULL, *b = NULL, *product = NULL, *ret = NULL; BIGNUM *remainder = NULL, *zero = NULL; int st = 0; if (!TEST_ptr(a = getBN(s, "A")) || !TEST_ptr(b = getBN(s, "B")) || !TEST_ptr(product = getBN(s, "Product")) || !TEST_ptr(ret = BN_new()) || !TEST_ptr(remainder = BN_new()) || !TEST_ptr(zero = BN_new())) goto err; BN_zero(zero); if (!TEST_true(BN_mul(ret, a, b, ctx)) || !equalBN("A * B", product, ret) || !TEST_true(BN_div(ret, remainder, product, a, ctx)) || !equalBN("Product / A", b, ret) || !equalBN("Product % A", zero, remainder) || !TEST_true(BN_div(ret, remainder, product, b, ctx)) || !equalBN("Product / B", a, ret) || !equalBN("Product % B", zero, remainder)) goto err; st = 1; err: BN_free(a); BN_free(b); BN_free(product); BN_free(ret); BN_free(remainder); BN_free(zero); return st; } static int file_quotient(STANZA *s) { BIGNUM *a = NULL, *b = NULL, *quotient = NULL, *remainder = NULL; BIGNUM *ret = NULL, *ret2 = NULL, *nnmod = NULL; BN_ULONG b_word, ret_word; int st = 0; if (!TEST_ptr(a = getBN(s, "A")) || !TEST_ptr(b = getBN(s, "B")) || !TEST_ptr(quotient = getBN(s, "Quotient")) || !TEST_ptr(remainder = getBN(s, "Remainder")) || !TEST_ptr(ret = BN_new()) || !TEST_ptr(ret2 = BN_new()) || !TEST_ptr(nnmod = BN_new())) goto err; if (!TEST_true(BN_div(ret, ret2, a, b, ctx)) || !equalBN("A / B", quotient, ret) || !equalBN("A % B", remainder, ret2) || !TEST_true(BN_mul(ret, quotient, b, ctx)) || !TEST_true(BN_add(ret, ret, remainder)) || !equalBN("Quotient * B + Remainder", a, ret)) goto err; /* * Test with BN_mod_word() and BN_div_word() if the divisor is * small enough. */ b_word = BN_get_word(b); if (!BN_is_negative(b) && b_word != (BN_ULONG)-1) { BN_ULONG remainder_word = BN_get_word(remainder); assert(remainder_word != (BN_ULONG)-1); if (!TEST_ptr(BN_copy(ret, a))) goto err; ret_word = BN_div_word(ret, b_word); if (ret_word != remainder_word) { #ifdef BN_DEC_FMT1 TEST_error( "Got A %% B (word) = " BN_DEC_FMT1 ", wanted " BN_DEC_FMT1, ret_word, remainder_word); #else TEST_error("Got A %% B (word) mismatch"); #endif goto err; } if (!equalBN ("A / B (word)", quotient, ret)) goto err; ret_word = BN_mod_word(a, b_word); if (ret_word != remainder_word) { #ifdef BN_DEC_FMT1 TEST_error( "Got A %% B (word) = " BN_DEC_FMT1 ", wanted " BN_DEC_FMT1 "", ret_word, remainder_word); #else TEST_error("Got A %% B (word) mismatch"); #endif goto err; } } /* Test BN_nnmod. */ if (!BN_is_negative(b)) { if (!TEST_true(BN_copy(nnmod, remainder)) || (BN_is_negative(nnmod) && !TEST_true(BN_add(nnmod, nnmod, b))) || !TEST_true(BN_nnmod(ret, a, b, ctx)) || !equalBN("A % B (non-negative)", nnmod, ret)) goto err; } st = 1; err: BN_free(a); BN_free(b); BN_free(quotient); BN_free(remainder); BN_free(ret); BN_free(ret2); BN_free(nnmod); return st; } static int file_modmul(STANZA *s) { BIGNUM *a = NULL, *b = NULL, *m = NULL, *mod_mul = NULL, *ret = NULL; int st = 0; if (!TEST_ptr(a = getBN(s, "A")) || !TEST_ptr(b = getBN(s, "B")) || !TEST_ptr(m = getBN(s, "M")) || !TEST_ptr(mod_mul = getBN(s, "ModMul")) || !TEST_ptr(ret = BN_new())) goto err; if (!TEST_true(BN_mod_mul(ret, a, b, m, ctx)) || !equalBN("A * B (mod M)", mod_mul, ret)) goto err; if (BN_is_odd(m)) { /* Reduce |a| and |b| and test the Montgomery version. */ BN_MONT_CTX *mont = BN_MONT_CTX_new(); BIGNUM *a_tmp = BN_new(); BIGNUM *b_tmp = BN_new(); if (mont == NULL || a_tmp == NULL || b_tmp == NULL || !TEST_true(BN_MONT_CTX_set(mont, m, ctx)) || !TEST_true(BN_nnmod(a_tmp, a, m, ctx)) || !TEST_true(BN_nnmod(b_tmp, b, m, ctx)) || !TEST_true(BN_to_montgomery(a_tmp, a_tmp, mont, ctx)) || !TEST_true(BN_to_montgomery(b_tmp, b_tmp, mont, ctx)) || !TEST_true(BN_mod_mul_montgomery(ret, a_tmp, b_tmp, mont, ctx)) || !TEST_true(BN_from_montgomery(ret, ret, mont, ctx)) || !equalBN("A * B (mod M) (mont)", mod_mul, ret)) st = 0; else st = 1; BN_MONT_CTX_free(mont); BN_free(a_tmp); BN_free(b_tmp); if (st == 0) goto err; } st = 1; err: BN_free(a); BN_free(b); BN_free(m); BN_free(mod_mul); BN_free(ret); return st; } static int file_modexp(STANZA *s) { BIGNUM *a = NULL, *e = NULL, *m = NULL, *mod_exp = NULL, *ret = NULL; BIGNUM *b = NULL, *c = NULL, *d = NULL; int st = 0; if (!TEST_ptr(a = getBN(s, "A")) || !TEST_ptr(e = getBN(s, "E")) || !TEST_ptr(m = getBN(s, "M")) || !TEST_ptr(mod_exp = getBN(s, "ModExp")) || !TEST_ptr(ret = BN_new()) || !TEST_ptr(d = BN_new())) goto err; if (!TEST_true(BN_mod_exp(ret, a, e, m, ctx)) || !equalBN("A ^ E (mod M)", mod_exp, ret)) goto err; if (BN_is_odd(m)) { if (!TEST_true(BN_mod_exp_mont(ret, a, e, m, ctx, NULL)) || !equalBN("A ^ E (mod M) (mont)", mod_exp, ret) || !TEST_true(BN_mod_exp_mont_consttime(ret, a, e, m, ctx, NULL)) || !equalBN("A ^ E (mod M) (mont const", mod_exp, ret)) goto err; } /* Regression test for carry propagation bug in sqr8x_reduction */ BN_hex2bn(&a, "050505050505"); BN_hex2bn(&b, "02"); BN_hex2bn(&c, "4141414141414141414141274141414141414141414141414141414141414141" "4141414141414141414141414141414141414141414141414141414141414141" "4141414141414141414141800000000000000000000000000000000000000000" "0000000000000000000000000000000000000000000000000000000000000000" "0000000000000000000000000000000000000000000000000000000000000000" "0000000000000000000000000000000000000000000000000000000001"); if (!TEST_true(BN_mod_exp(d, a, b, c, ctx)) || !TEST_true(BN_mul(e, a, a, ctx)) || !TEST_BN_eq(d, e)) goto err; st = 1; err: BN_free(a); BN_free(b); BN_free(c); BN_free(d); BN_free(e); BN_free(m); BN_free(mod_exp); BN_free(ret); return st; } static int file_exp(STANZA *s) { BIGNUM *a = NULL, *e = NULL, *exp = NULL, *ret = NULL; int st = 0; if (!TEST_ptr(a = getBN(s, "A")) || !TEST_ptr(e = getBN(s, "E")) || !TEST_ptr(exp = getBN(s, "Exp")) || !TEST_ptr(ret = BN_new())) goto err; if (!TEST_true(BN_exp(ret, a, e, ctx)) || !equalBN("A ^ E", exp, ret)) goto err; st = 1; err: BN_free(a); BN_free(e); BN_free(exp); BN_free(ret); return st; } static int file_modsqrt(STANZA *s) { BIGNUM *a = NULL, *p = NULL, *mod_sqrt = NULL, *ret = NULL, *ret2 = NULL; int st = 0; if (!TEST_ptr(a = getBN(s, "A")) || !TEST_ptr(p = getBN(s, "P")) || !TEST_ptr(mod_sqrt = getBN(s, "ModSqrt")) || !TEST_ptr(ret = BN_new()) || !TEST_ptr(ret2 = BN_new())) goto err; if (BN_is_negative(mod_sqrt)) { /* A negative testcase */ if (!TEST_ptr_null(BN_mod_sqrt(ret, a, p, ctx))) goto err; st = 1; goto err; } /* There are two possible answers. */ if (!TEST_ptr(BN_mod_sqrt(ret, a, p, ctx)) || !TEST_true(BN_sub(ret2, p, ret))) goto err; /* The first condition should NOT be a test. */ if (BN_cmp(ret2, mod_sqrt) != 0 && !equalBN("sqrt(A) (mod P)", mod_sqrt, ret)) goto err; st = 1; err: BN_free(a); BN_free(p); BN_free(mod_sqrt); BN_free(ret); BN_free(ret2); return st; } static int file_gcd(STANZA *s) { BIGNUM *a = NULL, *b = NULL, *gcd = NULL, *ret = NULL; int st = 0; if (!TEST_ptr(a = getBN(s, "A")) || !TEST_ptr(b = getBN(s, "B")) || !TEST_ptr(gcd = getBN(s, "GCD")) || !TEST_ptr(ret = BN_new())) goto err; if (!TEST_true(BN_gcd(ret, a, b, ctx)) || !equalBN("gcd(A,B)", gcd, ret)) goto err; st = 1; err: BN_free(a); BN_free(b); BN_free(gcd); BN_free(ret); return st; } static int test_bn2padded(void) { uint8_t zeros[256], out[256], reference[128]; size_t bytes; BIGNUM *n; int st = 0; /* Test edge case at 0. */ if (!TEST_ptr((n = BN_new()))) goto err; if (!TEST_int_eq(BN_bn2binpad(n, NULL, 0), 0)) goto err; memset(out, -1, sizeof(out)); if (!TEST_int_eq(BN_bn2binpad(n, out, sizeof(out)), sizeof(out))) goto err; memset(zeros, 0, sizeof(zeros)); if (!TEST_mem_eq(zeros, sizeof(zeros), out, sizeof(out))) goto err; /* Test a random numbers at various byte lengths. */ for (bytes = 128 - 7; bytes <= 128; bytes++) { # define TOP_BIT_ON 0 # define BOTTOM_BIT_NOTOUCH 0 if (!TEST_true(BN_rand(n, bytes * 8, TOP_BIT_ON, BOTTOM_BIT_NOTOUCH))) goto err; if (!TEST_int_eq(BN_num_bytes(n), bytes) || !TEST_int_eq(BN_bn2bin(n, reference), bytes)) goto err; /* Empty buffer should fail. */ if (!TEST_int_eq(BN_bn2binpad(n, NULL, 0), -1)) goto err; /* One byte short should fail. */ if (!TEST_int_eq(BN_bn2binpad(n, out, bytes - 1), -1)) goto err; /* Exactly right size should encode. */ if (!TEST_int_eq(BN_bn2binpad(n, out, bytes), bytes) || !TEST_mem_eq(out, bytes, reference, bytes)) goto err; /* Pad up one byte extra. */ if (!TEST_int_eq(BN_bn2binpad(n, out, bytes + 1), bytes + 1) || !TEST_mem_eq(out + 1, bytes, reference, bytes) || !TEST_mem_eq(out, 1, zeros, 1)) goto err; /* Pad up to 256. */ if (!TEST_int_eq(BN_bn2binpad(n, out, sizeof(out)), sizeof(out)) || !TEST_mem_eq(out + sizeof(out) - bytes, bytes, reference, bytes) || !TEST_mem_eq(out, sizeof(out) - bytes, zeros, sizeof(out) - bytes)) goto err; } st = 1; err: BN_free(n); return st; } static const MPITEST kSignedTests_BE[] = { {"-1", "\xff", 1}, {"0", "", 0}, {"1", "\x01", 1}, /* * The above cover the basics, now let's go for possible bignum * chunk edges and other word edges (for a broad definition of * "word", i.e. 1 byte included). */ /* 1 byte edge */ {"127", "\x7f", 1}, {"-127", "\x81", 1}, {"128", "\x00\x80", 2}, {"-128", "\x80", 1}, {"129", "\x00\x81", 2}, {"-129", "\xff\x7f", 2}, {"255", "\x00\xff", 2}, {"-255", "\xff\x01", 2}, {"256", "\x01\x00", 2}, {"-256", "\xff\x00", 2}, /* 2 byte edge */ {"32767", "\x7f\xff", 2}, {"-32767", "\x80\x01", 2}, {"32768", "\x00\x80\x00", 3}, {"-32768", "\x80\x00", 2}, {"32769", "\x00\x80\x01", 3}, {"-32769", "\xff\x7f\xff", 3}, {"65535", "\x00\xff\xff", 3}, {"-65535", "\xff\x00\x01", 3}, {"65536", "\x01\x00\x00", 3}, {"-65536", "\xff\x00\x00", 3}, /* 4 byte edge */ {"2147483647", "\x7f\xff\xff\xff", 4}, {"-2147483647", "\x80\x00\x00\x01", 4}, {"2147483648", "\x00\x80\x00\x00\x00", 5}, {"-2147483648", "\x80\x00\x00\x00", 4}, {"2147483649", "\x00\x80\x00\x00\x01", 5}, {"-2147483649", "\xff\x7f\xff\xff\xff", 5}, {"4294967295", "\x00\xff\xff\xff\xff", 5}, {"-4294967295", "\xff\x00\x00\x00\x01", 5}, {"4294967296", "\x01\x00\x00\x00\x00", 5}, {"-4294967296", "\xff\x00\x00\x00\x00", 5}, /* 8 byte edge */ {"9223372036854775807", "\x7f\xff\xff\xff\xff\xff\xff\xff", 8}, {"-9223372036854775807", "\x80\x00\x00\x00\x00\x00\x00\x01", 8}, {"9223372036854775808", "\x00\x80\x00\x00\x00\x00\x00\x00\x00", 9}, {"-9223372036854775808", "\x80\x00\x00\x00\x00\x00\x00\x00", 8}, {"9223372036854775809", "\x00\x80\x00\x00\x00\x00\x00\x00\x01", 9}, {"-9223372036854775809", "\xff\x7f\xff\xff\xff\xff\xff\xff\xff", 9}, {"18446744073709551615", "\x00\xff\xff\xff\xff\xff\xff\xff\xff", 9}, {"-18446744073709551615", "\xff\x00\x00\x00\x00\x00\x00\x00\x01", 9}, {"18446744073709551616", "\x01\x00\x00\x00\x00\x00\x00\x00\x00", 9}, {"-18446744073709551616", "\xff\x00\x00\x00\x00\x00\x00\x00\x00", 9}, }; static int copy_reversed(uint8_t *dst, uint8_t *src, size_t len) { for (dst += len - 1; len > 0; src++, dst--, len--) *dst = *src; return 1; } static int test_bn2signed(int i) { uint8_t scratch[10], reversed[10]; const MPITEST *test = &kSignedTests_BE[i]; BIGNUM *bn = NULL, *bn2 = NULL; int st = 0; if (!TEST_ptr(bn = BN_new()) || !TEST_true(BN_asc2bn(&bn, test->base10))) goto err; /* * Check BN_signed_bn2bin() / BN_signed_bin2bn() * The interesting stuff happens in the last bytes of the buffers, * the beginning is just padding (i.e. sign extension). */ i = sizeof(scratch) - test->mpi_len; if (!TEST_int_eq(BN_signed_bn2bin(bn, scratch, sizeof(scratch)), sizeof(scratch)) || !TEST_true(copy_reversed(reversed, scratch, sizeof(scratch))) || !TEST_mem_eq(test->mpi, test->mpi_len, scratch + i, test->mpi_len)) goto err; if (!TEST_ptr(bn2 = BN_signed_bin2bn(scratch, sizeof(scratch), NULL)) || !TEST_BN_eq(bn, bn2)) goto err; BN_free(bn2); bn2 = NULL; /* Check that a parse of the reversed buffer works too */ if (!TEST_ptr(bn2 = BN_signed_lebin2bn(reversed, sizeof(reversed), NULL)) || !TEST_BN_eq(bn, bn2)) goto err; BN_free(bn2); bn2 = NULL; /* * Check BN_signed_bn2lebin() / BN_signed_lebin2bn() * The interesting stuff happens in the first bytes of the buffers, * the end is just padding (i.e. sign extension). */ i = sizeof(reversed) - test->mpi_len; if (!TEST_int_eq(BN_signed_bn2lebin(bn, scratch, sizeof(scratch)), sizeof(scratch)) || !TEST_true(copy_reversed(reversed, scratch, sizeof(scratch))) || !TEST_mem_eq(test->mpi, test->mpi_len, reversed + i, test->mpi_len)) goto err; if (!TEST_ptr(bn2 = BN_signed_lebin2bn(scratch, sizeof(scratch), NULL)) || !TEST_BN_eq(bn, bn2)) goto err; BN_free(bn2); bn2 = NULL; /* Check that a parse of the reversed buffer works too */ if (!TEST_ptr(bn2 = BN_signed_bin2bn(reversed, sizeof(reversed), NULL)) || !TEST_BN_eq(bn, bn2)) goto err; st = 1; err: BN_free(bn2); BN_free(bn); return st; } static int test_dec2bn(void) { BIGNUM *bn = NULL; int st = 0; if (!TEST_int_eq(parsedecBN(&bn, "0"), 1) || !TEST_BN_eq_word(bn, 0) || !TEST_BN_eq_zero(bn) || !TEST_BN_le_zero(bn) || !TEST_BN_ge_zero(bn) || !TEST_BN_even(bn)) goto err; BN_free(bn); bn = NULL; if (!TEST_int_eq(parsedecBN(&bn, "256"), 3) || !TEST_BN_eq_word(bn, 256) || !TEST_BN_ge_zero(bn) || !TEST_BN_gt_zero(bn) || !TEST_BN_ne_zero(bn) || !TEST_BN_even(bn)) goto err; BN_free(bn); bn = NULL; if (!TEST_int_eq(parsedecBN(&bn, "-42"), 3) || !TEST_BN_abs_eq_word(bn, 42) || !TEST_BN_lt_zero(bn) || !TEST_BN_le_zero(bn) || !TEST_BN_ne_zero(bn) || !TEST_BN_even(bn)) goto err; BN_free(bn); bn = NULL; if (!TEST_int_eq(parsedecBN(&bn, "1"), 1) || !TEST_BN_eq_word(bn, 1) || !TEST_BN_ne_zero(bn) || !TEST_BN_gt_zero(bn) || !TEST_BN_ge_zero(bn) || !TEST_BN_eq_one(bn) || !TEST_BN_odd(bn)) goto err; BN_free(bn); bn = NULL; if (!TEST_int_eq(parsedecBN(&bn, "-0"), 2) || !TEST_BN_eq_zero(bn) || !TEST_BN_ge_zero(bn) || !TEST_BN_le_zero(bn) || !TEST_BN_even(bn)) goto err; BN_free(bn); bn = NULL; if (!TEST_int_eq(parsedecBN(&bn, "42trailing garbage is ignored"), 2) || !TEST_BN_abs_eq_word(bn, 42) || !TEST_BN_ge_zero(bn) || !TEST_BN_gt_zero(bn) || !TEST_BN_ne_zero(bn) || !TEST_BN_even(bn)) goto err; st = 1; err: BN_free(bn); return st; } static int test_hex2bn(void) { BIGNUM *bn = NULL; int st = 0; if (!TEST_int_eq(parseBN(&bn, "0"), 1) || !TEST_BN_eq_zero(bn) || !TEST_BN_ge_zero(bn) || !TEST_BN_even(bn)) goto err; BN_free(bn); bn = NULL; if (!TEST_int_eq(parseBN(&bn, "256"), 3) || !TEST_BN_eq_word(bn, 0x256) || !TEST_BN_ge_zero(bn) || !TEST_BN_gt_zero(bn) || !TEST_BN_ne_zero(bn) || !TEST_BN_even(bn)) goto err; BN_free(bn); bn = NULL; if (!TEST_int_eq(parseBN(&bn, "-42"), 3) || !TEST_BN_abs_eq_word(bn, 0x42) || !TEST_BN_lt_zero(bn) || !TEST_BN_le_zero(bn) || !TEST_BN_ne_zero(bn) || !TEST_BN_even(bn)) goto err; BN_free(bn); bn = NULL; if (!TEST_int_eq(parseBN(&bn, "cb"), 2) || !TEST_BN_eq_word(bn, 0xCB) || !TEST_BN_ge_zero(bn) || !TEST_BN_gt_zero(bn) || !TEST_BN_ne_zero(bn) || !TEST_BN_odd(bn)) goto err; BN_free(bn); bn = NULL; if (!TEST_int_eq(parseBN(&bn, "-0"), 2) || !TEST_BN_eq_zero(bn) || !TEST_BN_ge_zero(bn) || !TEST_BN_le_zero(bn) || !TEST_BN_even(bn)) goto err; BN_free(bn); bn = NULL; if (!TEST_int_eq(parseBN(&bn, "abctrailing garbage is ignored"), 3) || !TEST_BN_eq_word(bn, 0xabc) || !TEST_BN_ge_zero(bn) || !TEST_BN_gt_zero(bn) || !TEST_BN_ne_zero(bn) || !TEST_BN_even(bn)) goto err; st = 1; err: BN_free(bn); return st; } static int test_asc2bn(void) { BIGNUM *bn = NULL; int st = 0; if (!TEST_ptr(bn = BN_new())) goto err; if (!TEST_true(BN_asc2bn(&bn, "0")) || !TEST_BN_eq_zero(bn) || !TEST_BN_ge_zero(bn)) goto err; if (!TEST_true(BN_asc2bn(&bn, "256")) || !TEST_BN_eq_word(bn, 256) || !TEST_BN_ge_zero(bn)) goto err; if (!TEST_true(BN_asc2bn(&bn, "-42")) || !TEST_BN_abs_eq_word(bn, 42) || !TEST_BN_lt_zero(bn)) goto err; if (!TEST_true(BN_asc2bn(&bn, "0x1234")) || !TEST_BN_eq_word(bn, 0x1234) || !TEST_BN_ge_zero(bn)) goto err; if (!TEST_true(BN_asc2bn(&bn, "0X1234")) || !TEST_BN_eq_word(bn, 0x1234) || !TEST_BN_ge_zero(bn)) goto err; if (!TEST_true(BN_asc2bn(&bn, "-0xabcd")) || !TEST_BN_abs_eq_word(bn, 0xabcd) || !TEST_BN_lt_zero(bn)) goto err; if (!TEST_true(BN_asc2bn(&bn, "-0")) || !TEST_BN_eq_zero(bn) || !TEST_BN_ge_zero(bn)) goto err; if (!TEST_true(BN_asc2bn(&bn, "123trailing garbage is ignored")) || !TEST_BN_eq_word(bn, 123) || !TEST_BN_ge_zero(bn)) goto err; st = 1; err: BN_free(bn); return st; } static const MPITEST kMPITests[] = { {"0", "\x00\x00\x00\x00", 4}, {"1", "\x00\x00\x00\x01\x01", 5}, {"-1", "\x00\x00\x00\x01\x81", 5}, {"128", "\x00\x00\x00\x02\x00\x80", 6}, {"256", "\x00\x00\x00\x02\x01\x00", 6}, {"-256", "\x00\x00\x00\x02\x81\x00", 6}, }; static int test_mpi(int i) { uint8_t scratch[8]; const MPITEST *test = &kMPITests[i]; size_t mpi_len, mpi_len2; BIGNUM *bn = NULL; BIGNUM *bn2 = NULL; int st = 0; if (!TEST_ptr(bn = BN_new()) || !TEST_true(BN_asc2bn(&bn, test->base10))) goto err; mpi_len = BN_bn2mpi(bn, NULL); if (!TEST_size_t_le(mpi_len, sizeof(scratch))) goto err; if (!TEST_size_t_eq(mpi_len2 = BN_bn2mpi(bn, scratch), mpi_len) || !TEST_mem_eq(test->mpi, test->mpi_len, scratch, mpi_len)) goto err; if (!TEST_ptr(bn2 = BN_mpi2bn(scratch, mpi_len, NULL))) goto err; if (!TEST_BN_eq(bn, bn2)) { BN_free(bn2); goto err; } BN_free(bn2); st = 1; err: BN_free(bn); return st; } static int test_bin2zero(void) { unsigned char input[] = { 0 }; BIGNUM *zbn = NULL; int ret = 0; if (!TEST_ptr(zbn = BN_new())) goto err; #define zerotest(fn) \ if (!TEST_ptr(fn(input, 1, zbn)) \ || !TEST_true(BN_is_zero(zbn)) \ || !TEST_ptr(fn(input, 0, zbn)) \ || !TEST_true(BN_is_zero(zbn)) \ || !TEST_ptr(fn(NULL, 0, zbn)) \ || !TEST_true(BN_is_zero(zbn))) \ goto err zerotest(BN_bin2bn); zerotest(BN_signed_bin2bn); zerotest(BN_lebin2bn); zerotest(BN_signed_lebin2bn); #undef zerotest ret = 1; err: BN_free(zbn); return ret; } static int test_bin2bn_lengths(void) { unsigned char input[] = { 1, 2 }; BIGNUM *bn_be = NULL, *bn_expected_be = NULL; BIGNUM *bn_le = NULL, *bn_expected_le = NULL; int ret = 0; if (!TEST_ptr(bn_be = BN_new()) || !TEST_ptr(bn_expected_be = BN_new()) || !TEST_true(BN_set_word(bn_expected_be, 0x102)) || !TEST_ptr(bn_le = BN_new()) || !TEST_ptr(bn_expected_le = BN_new()) || !TEST_true(BN_set_word(bn_expected_le, 0x201))) goto err; #define lengthtest(fn, e) \ if (!TEST_ptr_null(fn(input, -1, bn_##e)) \ || !TEST_ptr(fn(input, 0, bn_##e)) \ || !TEST_true(BN_is_zero(bn_##e)) \ || !TEST_ptr(fn(input, 2, bn_##e)) \ || !TEST_int_eq(BN_cmp(bn_##e, bn_expected_##e), 0)) \ goto err lengthtest(BN_bin2bn, be); lengthtest(BN_signed_bin2bn, be); lengthtest(BN_lebin2bn, le); lengthtest(BN_signed_lebin2bn, le); #undef lengthtest ret = 1; err: BN_free(bn_be); BN_free(bn_expected_be); BN_free(bn_le); BN_free(bn_expected_le); return ret; } static int test_rand(void) { BIGNUM *bn = NULL; int st = 0; if (!TEST_ptr(bn = BN_new())) return 0; /* Test BN_rand for degenerate cases with |top| and |bottom| parameters. */ if (!TEST_false(BN_rand(bn, 0, 0 /* top */ , 0 /* bottom */ )) || !TEST_false(BN_rand(bn, 0, 1 /* top */ , 1 /* bottom */ )) || !TEST_true(BN_rand(bn, 1, 0 /* top */ , 0 /* bottom */ )) || !TEST_BN_eq_one(bn) || !TEST_false(BN_rand(bn, 1, 1 /* top */ , 0 /* bottom */ )) || !TEST_true(BN_rand(bn, 1, -1 /* top */ , 1 /* bottom */ )) || !TEST_BN_eq_one(bn) || !TEST_true(BN_rand(bn, 2, 1 /* top */ , 0 /* bottom */ )) || !TEST_BN_eq_word(bn, 3)) goto err; st = 1; err: BN_free(bn); return st; } /* * Run some statistical tests to provide a degree confidence that the * BN_rand_range() function works as expected. The test cases and * critical values are generated by the bn_rand_range script. * * Each individual test is a Chi^2 goodness of fit for a specified number * of samples and range. The samples are assumed to be independent and * that they are from a discrete uniform distribution. * * Some of these individual tests are expected to fail, the success/failure * of each is an independent Bernoulli trial. The number of such successes * will form a binomial distribution. The count of the successes is compared * against a precomputed critical value to determine the overall outcome. */ struct rand_range_case { unsigned int range; unsigned int iterations; double critical; }; #include "bn_rand_range.h" static int test_rand_range_single(size_t n) { const unsigned int range = rand_range_cases[n].range; const unsigned int iterations = rand_range_cases[n].iterations; const double critical = rand_range_cases[n].critical; const double expected = iterations / (double)range; double sum = 0; BIGNUM *rng = NULL, *val = NULL; size_t *counts; unsigned int i, v; int res = 0; if (!TEST_ptr(counts = OPENSSL_zalloc(sizeof(*counts) * range)) || !TEST_ptr(rng = BN_new()) || !TEST_ptr(val = BN_new()) || !TEST_true(BN_set_word(rng, range))) goto err; for (i = 0; i < iterations; i++) { if (!TEST_true(BN_rand_range(val, rng)) || !TEST_uint_lt(v = (unsigned int)BN_get_word(val), range)) goto err; counts[v]++; } for (i = 0; i < range; i++) { const double delta = counts[i] - expected; sum += delta * delta; } sum /= expected; if (sum > critical) { TEST_info("Chi^2 test negative %.4f > %4.f", sum, critical); TEST_note("test case %zu range %u iterations %u", n + 1, range, iterations); goto err; } res = 1; err: BN_free(rng); BN_free(val); OPENSSL_free(counts); return res; } static int test_rand_range(void) { int n_success = 0; size_t i; for (i = 0; i < OSSL_NELEM(rand_range_cases); i++) n_success += test_rand_range_single(i); if (TEST_int_ge(n_success, binomial_critical)) return 1; TEST_note("This test is expected to fail by chance 0.01%% of the time."); return 0; } static int test_negzero(void) { BIGNUM *a = NULL, *b = NULL, *c = NULL, *d = NULL; BIGNUM *numerator = NULL, *denominator = NULL; int consttime, st = 0; if (!TEST_ptr(a = BN_new()) || !TEST_ptr(b = BN_new()) || !TEST_ptr(c = BN_new()) || !TEST_ptr(d = BN_new())) goto err; /* Test that BN_mul never gives negative zero. */ if (!TEST_true(BN_set_word(a, 1))) goto err; BN_set_negative(a, 1); BN_zero(b); if (!TEST_true(BN_mul(c, a, b, ctx))) goto err; if (!TEST_BN_eq_zero(c) || !TEST_BN_ge_zero(c)) goto err; for (consttime = 0; consttime < 2; consttime++) { if (!TEST_ptr(numerator = BN_new()) || !TEST_ptr(denominator = BN_new())) goto err; if (consttime) { BN_set_flags(numerator, BN_FLG_CONSTTIME); BN_set_flags(denominator, BN_FLG_CONSTTIME); } /* Test that BN_div never gives negative zero in the quotient. */ if (!TEST_true(BN_set_word(numerator, 1)) || !TEST_true(BN_set_word(denominator, 2))) goto err; BN_set_negative(numerator, 1); if (!TEST_true(BN_div(a, b, numerator, denominator, ctx)) || !TEST_BN_eq_zero(a) || !TEST_BN_ge_zero(a)) goto err; /* Test that BN_div never gives negative zero in the remainder. */ if (!TEST_true(BN_set_word(denominator, 1)) || !TEST_true(BN_div(a, b, numerator, denominator, ctx)) || !TEST_BN_eq_zero(b) || !TEST_BN_ge_zero(b)) goto err; BN_free(numerator); BN_free(denominator); numerator = denominator = NULL; } /* Test that BN_set_negative will not produce a negative zero. */ BN_zero(a); BN_set_negative(a, 1); if (BN_is_negative(a)) goto err; st = 1; err: BN_free(a); BN_free(b); BN_free(c); BN_free(d); BN_free(numerator); BN_free(denominator); return st; } static int test_badmod(void) { BIGNUM *a = NULL, *b = NULL, *zero = NULL; BN_MONT_CTX *mont = NULL; int st = 0; if (!TEST_ptr(a = BN_new()) || !TEST_ptr(b = BN_new()) || !TEST_ptr(zero = BN_new()) || !TEST_ptr(mont = BN_MONT_CTX_new())) goto err; BN_zero(zero); if (!TEST_false(BN_div(a, b, BN_value_one(), zero, ctx))) goto err; ERR_clear_error(); if (!TEST_false(BN_mod_mul(a, BN_value_one(), BN_value_one(), zero, ctx))) goto err; ERR_clear_error(); if (!TEST_false(BN_mod_exp(a, BN_value_one(), BN_value_one(), zero, ctx))) goto err; ERR_clear_error(); if (!TEST_false(BN_mod_exp_mont(a, BN_value_one(), BN_value_one(), zero, ctx, NULL))) goto err; ERR_clear_error(); if (!TEST_false(BN_mod_exp_mont_consttime(a, BN_value_one(), BN_value_one(), zero, ctx, NULL))) goto err; ERR_clear_error(); if (!TEST_false(BN_MONT_CTX_set(mont, zero, ctx))) goto err; ERR_clear_error(); /* Some operations also may not be used with an even modulus. */ if (!TEST_true(BN_set_word(b, 16))) goto err; if (!TEST_false(BN_MONT_CTX_set(mont, b, ctx))) goto err; ERR_clear_error(); if (!TEST_false(BN_mod_exp_mont(a, BN_value_one(), BN_value_one(), b, ctx, NULL))) goto err; ERR_clear_error(); if (!TEST_false(BN_mod_exp_mont_consttime(a, BN_value_one(), BN_value_one(), b, ctx, NULL))) goto err; ERR_clear_error(); st = 1; err: BN_free(a); BN_free(b); BN_free(zero); BN_MONT_CTX_free(mont); return st; } static int test_expmodzero(void) { BIGNUM *a = NULL, *r = NULL, *zero = NULL; int st = 0; if (!TEST_ptr(zero = BN_new()) || !TEST_ptr(a = BN_new()) || !TEST_ptr(r = BN_new())) goto err; BN_zero(zero); if (!TEST_true(BN_mod_exp(r, a, zero, BN_value_one(), NULL)) || !TEST_BN_eq_zero(r) || !TEST_true(BN_mod_exp_mont(r, a, zero, BN_value_one(), NULL, NULL)) || !TEST_BN_eq_zero(r) || !TEST_true(BN_mod_exp_mont_consttime(r, a, zero, BN_value_one(), NULL, NULL)) || !TEST_BN_eq_zero(r) || !TEST_true(BN_mod_exp_mont_word(r, 42, zero, BN_value_one(), NULL, NULL)) || !TEST_BN_eq_zero(r)) goto err; st = 1; err: BN_free(zero); BN_free(a); BN_free(r); return st; } static int test_expmodone(void) { int ret = 0, i; BIGNUM *r = BN_new(); BIGNUM *a = BN_new(); BIGNUM *p = BN_new(); BIGNUM *m = BN_new(); if (!TEST_ptr(r) || !TEST_ptr(a) || !TEST_ptr(p) || !TEST_ptr(p) || !TEST_ptr(m) || !TEST_true(BN_set_word(a, 1)) || !TEST_true(BN_set_word(p, 0)) || !TEST_true(BN_set_word(m, 1))) goto err; /* Calculate r = 1 ^ 0 mod 1, and check the result is always 0 */ for (i = 0; i < 2; i++) { if (!TEST_true(BN_mod_exp(r, a, p, m, NULL)) || !TEST_BN_eq_zero(r) || !TEST_true(BN_mod_exp_mont(r, a, p, m, NULL, NULL)) || !TEST_BN_eq_zero(r) || !TEST_true(BN_mod_exp_mont_consttime(r, a, p, m, NULL, NULL)) || !TEST_BN_eq_zero(r) || !TEST_true(BN_mod_exp_mont_word(r, 1, p, m, NULL, NULL)) || !TEST_BN_eq_zero(r) || !TEST_true(BN_mod_exp_simple(r, a, p, m, NULL)) || !TEST_BN_eq_zero(r) || !TEST_true(BN_mod_exp_recp(r, a, p, m, NULL)) || !TEST_BN_eq_zero(r)) goto err; /* Repeat for r = 1 ^ 0 mod -1 */ if (i == 0) BN_set_negative(m, 1); } ret = 1; err: BN_free(r); BN_free(a); BN_free(p); BN_free(m); return ret; } static int test_smallprime(int kBits) { BIGNUM *r; int st = 0; if (!TEST_ptr(r = BN_new())) goto err; if (kBits <= 1) { if (!TEST_false(BN_generate_prime_ex(r, kBits, 0, NULL, NULL, NULL))) goto err; } else { if (!TEST_true(BN_generate_prime_ex(r, kBits, 0, NULL, NULL, NULL)) || !TEST_int_eq(BN_num_bits(r), kBits)) goto err; } st = 1; err: BN_free(r); return st; } static int test_smallsafeprime(int kBits) { BIGNUM *r; int st = 0; if (!TEST_ptr(r = BN_new())) goto err; if (kBits <= 5 && kBits != 3) { if (!TEST_false(BN_generate_prime_ex(r, kBits, 1, NULL, NULL, NULL))) goto err; } else { if (!TEST_true(BN_generate_prime_ex(r, kBits, 1, NULL, NULL, NULL)) || !TEST_int_eq(BN_num_bits(r), kBits)) goto err; } st = 1; err: BN_free(r); return st; } static int primes[] = { 2, 3, 5, 7, 17863 }; static int test_is_prime(int i) { int ret = 0; BIGNUM *r = NULL; int trial; if (!TEST_ptr(r = BN_new())) goto err; for (trial = 0; trial <= 1; ++trial) { if (!TEST_true(BN_set_word(r, primes[i])) || !TEST_int_eq(BN_check_prime(r, ctx, NULL), 1)) goto err; } ret = 1; err: BN_free(r); return ret; } static int not_primes[] = { -1, 0, 1, 4 }; static int test_not_prime(int i) { int ret = 0; BIGNUM *r = NULL; int trial; if (!TEST_ptr(r = BN_new())) goto err; for (trial = 0; trial <= 1; ++trial) { if (!TEST_true(BN_set_word(r, not_primes[i])) || !TEST_false(BN_check_prime(r, ctx, NULL))) goto err; } ret = 1; err: BN_free(r); return ret; } static int test_ctx_set_ct_flag(BN_CTX *c) { int st = 0; size_t i; BIGNUM *b[15]; BN_CTX_start(c); for (i = 0; i < OSSL_NELEM(b); i++) { if (!TEST_ptr(b[i] = BN_CTX_get(c))) goto err; if (i % 2 == 1) BN_set_flags(b[i], BN_FLG_CONSTTIME); } st = 1; err: BN_CTX_end(c); return st; } static int test_ctx_check_ct_flag(BN_CTX *c) { int st = 0; size_t i; BIGNUM *b[30]; BN_CTX_start(c); for (i = 0; i < OSSL_NELEM(b); i++) { if (!TEST_ptr(b[i] = BN_CTX_get(c))) goto err; if (!TEST_false(BN_get_flags(b[i], BN_FLG_CONSTTIME))) goto err; } st = 1; err: BN_CTX_end(c); return st; } static int test_ctx_consttime_flag(void) { /*- * The constant-time flag should not "leak" among BN_CTX frames: * * - test_ctx_set_ct_flag() starts a frame in the given BN_CTX and * sets the BN_FLG_CONSTTIME flag on some of the BIGNUMs obtained * from the frame before ending it. * - test_ctx_check_ct_flag() then starts a new frame and gets a * number of BIGNUMs from it. In absence of leaks, none of the * BIGNUMs in the new frame should have BN_FLG_CONSTTIME set. * * In actual BN_CTX usage inside libcrypto the leak could happen at * any depth level in the BN_CTX stack, with varying results * depending on the patterns of sibling trees of nested function * calls sharing the same BN_CTX object, and the effect of * unintended BN_FLG_CONSTTIME on the called BN_* functions. * * This simple unit test abstracts away this complexity and verifies * that the leak does not happen between two sibling functions * sharing the same BN_CTX object at the same level of nesting. * */ BN_CTX *nctx = NULL; BN_CTX *sctx = NULL; size_t i = 0; int st = 0; if (!TEST_ptr(nctx = BN_CTX_new()) || !TEST_ptr(sctx = BN_CTX_secure_new())) goto err; for (i = 0; i < 2; i++) { BN_CTX *c = i == 0 ? nctx : sctx; if (!TEST_true(test_ctx_set_ct_flag(c)) || !TEST_true(test_ctx_check_ct_flag(c))) goto err; } st = 1; err: BN_CTX_free(nctx); BN_CTX_free(sctx); return st; } static int test_coprime(void) { BIGNUM *a = NULL, *b = NULL; int ret = 0; ret = TEST_ptr(a = BN_new()) && TEST_ptr(b = BN_new()) && TEST_true(BN_set_word(a, 66)) && TEST_true(BN_set_word(b, 99)) && TEST_int_eq(BN_are_coprime(a, b, ctx), 0) && TEST_int_eq(BN_are_coprime(b, a, ctx), 0) && TEST_true(BN_set_word(a, 67)) && TEST_int_eq(BN_are_coprime(a, b, ctx), 1) && TEST_int_eq(BN_are_coprime(b, a, ctx), 1); BN_free(a); BN_free(b); return ret; } static int test_gcd_prime(void) { BIGNUM *a = NULL, *b = NULL, *gcd = NULL; int i, st = 0; if (!TEST_ptr(a = BN_new()) || !TEST_ptr(b = BN_new()) || !TEST_ptr(gcd = BN_new())) goto err; if (!TEST_true(BN_generate_prime_ex(a, 1024, 0, NULL, NULL, NULL))) goto err; for (i = 0; i < NUM_PRIME_TESTS; i++) { if (!TEST_true(BN_generate_prime_ex(b, 1024, 0, NULL, NULL, NULL)) || !TEST_true(BN_gcd(gcd, a, b, ctx)) || !TEST_true(BN_is_one(gcd)) || !TEST_true(BN_are_coprime(a, b, ctx))) goto err; } st = 1; err: BN_free(a); BN_free(b); BN_free(gcd); return st; } typedef struct mod_exp_test_st { const char *base; const char *exp; const char *mod; const char *res; } MOD_EXP_TEST; static const MOD_EXP_TEST ModExpTests[] = { /* original test vectors for rsaz_512_sqr bug, by OSS-Fuzz */ { "1166180238001879113042182292626169621106255558914000595999312084" "4627946820899490684928760491249738643524880720584249698100907201" "002086675047927600340800371", "8000000000000000000000000000000000000000000000000000000000000000" "0000000000000000000000000000000000000000000000000000000000000000" "00000000", "1340780792684523720980737645613191762604395855615117867483316354" "3294276330515137663421134775482798690129946803802212663956180562" "088664022929883876655300863", "8243904058268085430037326628480645845409758077568738532059032482" "8294114415890603594730158120426756266457928475330450251339773498" "26758407619521544102068438" }, { "4974270041410803822078866696159586946995877618987010219312844726" "0284386121835740784990869050050504348861513337232530490826340663" "197278031692737429054", "4974270041410803822078866696159586946995877428188754995041148539" "1663243362592271353668158565195557417149981094324650322556843202" "946445882670777892608", "1340780716511420227215592830971452482815377482627251725537099028" "4429769497230131760206012644403029349547320953206103351725462999" "947509743623340557059752191", "5296244594780707015616522701706118082963369547253192207884519362" "1767869984947542695665420219028522815539559194793619684334900442" "49304558011362360473525933" }, /* test vectors for rsaz_512_srq bug, with rcx/rbx=1 */ { /* between first and second iteration */ "5148719036160389201525610950887605325980251964889646556085286545" "3931548809178823413169359635978762036512397113080988070677858033" "36463909753993540214027190", "6703903964971298549787012499102923063739682910296196688861780721" "8608820150367734884009371490834517138450159290932430254268769414" "05973284973216824503042158", "6703903964971298549787012499102923063739682910296196688861780721" "8608820150367734884009371490834517138450159290932430254268769414" "05973284973216824503042159", "1" }, { /* between second and third iteration */ "8908340854353752577419678771330460827942371434853054158622636544" "8151360109722890949471912566649465436296659601091730745087014189" "2672764191218875181826063", "6703903964971298549787012499102923063739682910296196688861780721" "8608820150367734884009371490834517138450159290932430254268769414" "05973284973216824503042158", "6703903964971298549787012499102923063739682910296196688861780721" "8608820150367734884009371490834517138450159290932430254268769414" "05973284973216824503042159", "1" }, { /* between third and fourth iteration */ "3427446396505596330634350984901719674479522569002785244080234738" "4288743635435746136297299366444548736533053717416735379073185344" "26985272974404612945608761", "6703903964971298549787012499102923063739682910296196688861780721" "8608820150367734884009371490834517138450159290932430254268769414" "05973284973216824503042158", "6703903964971298549787012499102923063739682910296196688861780721" "8608820150367734884009371490834517138450159290932430254268769414" "05973284973216824503042159", "1" }, { /* between fourth and fifth iteration */ "3472743044917564564078857826111874560045331237315597383869652985" "6919870028890895988478351133601517365908445058405433832718206902" "4088133164805266956353542", "6703903964971298549787012499102923063739682910296196688861780721" "8608820150367734884009371490834517138450159290932430254268769414" "05973284973216824503042158", "6703903964971298549787012499102923063739682910296196688861780721" "8608820150367734884009371490834517138450159290932430254268769414" "05973284973216824503042159", "1" }, { /* between fifth and sixth iteration */ "3608632990153469264412378349742339216742409743898601587274768025" "0110772032985643555192767717344946174122842255204082586753499651" "14483434992887431333675068", "6703903964971298549787012499102923063739682910296196688861780721" "8608820150367734884009371490834517138450159290932430254268769414" "05973284973216824503042158", "6703903964971298549787012499102923063739682910296196688861780721" "8608820150367734884009371490834517138450159290932430254268769414" "05973284973216824503042159", "1" }, { /* between sixth and seventh iteration */ "8455374370234070242910508226941981520235709767260723212165264877" "8689064388017521524568434328264431772644802567028663962962025746" "9283458217850119569539086", "6703903964971298549787012499102923063739682910296196688861780721" "8608820150367734884009371490834517138450159290932430254268769414" "05973284973216824503042158", "6703903964971298549787012499102923063739682910296196688861780721" "8608820150367734884009371490834517138450159290932430254268769414" "05973284973216824503042159", "1" }, { /* between seventh and eighth iteration */ "5155371529688532178421209781159131443543419764974688878527112131" "7446518205609427412336183157918981038066636807317733319323257603" "04416292040754017461076359", "1005585594745694782468051874865438459560952436544429503329267108" "2791323022555160232601405723625177570767523893639864538140315412" "108959927459825236754563832", "1005585594745694782468051874865438459560952436544429503329267108" "2791323022555160232601405723625177570767523893639864538140315412" "108959927459825236754563833", "1" }, /* test vectors for rsaz_512_srq bug, with rcx/rbx=2 */ { /* between first and second iteration */ "3155666506033786929967309937640790361084670559125912405342594979" "4345142818528956285490897841406338022378565972533508820577760065" "58494345853302083699912572", "6703903964971298549787012499102923063739682910296196688861780721" "8608820150367734884009371490834517138450159290932430254268769414" "05973284973216824503042158", "6703903964971298549787012499102923063739682910296196688861780721" "8608820150367734884009371490834517138450159290932430254268769414" "05973284973216824503042159", "1" }, { /* between second and third iteration */ "3789819583801342198190405714582958759005991915505282362397087750" "4213544724644823098843135685133927198668818185338794377239590049" "41019388529192775771488319", "6703903964971298549787012499102923063739682910296196688861780721" "8608820150367734884009371490834517138450159290932430254268769414" "05973284973216824503042158", "6703903964971298549787012499102923063739682910296196688861780721" "8608820150367734884009371490834517138450159290932430254268769414" "05973284973216824503042159", "1" }, { /* between third and forth iteration */ "4695752552040706867080542538786056470322165281761525158189220280" "4025547447667484759200742764246905647644662050122968912279199065" "48065034299166336940507214", "6703903964971298549787012499102923063739682910296196688861780721" "8608820150367734884009371490834517138450159290932430254268769414" "05973284973216824503042158", "6703903964971298549787012499102923063739682910296196688861780721" "8608820150367734884009371490834517138450159290932430254268769414" "05973284973216824503042159", "1" }, { /* between forth and fifth iteration */ "2159140240970485794188159431017382878636879856244045329971239574" "8919691133560661162828034323196457386059819832804593989740268964" "74502911811812651475927076", "6703903964971298549787012499102923063739682910296196688861780721" "8608820150367734884009371490834517138450159290932430254268769414" "05973284973216824503042158", "6703903964971298549787012499102923063739682910296196688861780721" "8608820150367734884009371490834517138450159290932430254268769414" "05973284973216824503042159", "1" }, { /* between fifth and sixth iteration */ "5239312332984325668414624633307915097111691815000872662334695514" "5436533521392362443557163429336808208137221322444780490437871903" "99972784701334569424519255", "6703903964971298549787012499102923063739682910296196688861780721" "8608820150367734884009371490834517138450159290932430254268769414" "05973284973216824503042158", "6703903964971298549787012499102923063739682910296196688861780721" "8608820150367734884009371490834517138450159290932430254268769414" "05973284973216824503042159", "1" }, { /* between sixth and seventh iteration */ "1977953647322612860406858017869125467496941904523063466791308891" "1172796739058531929470539758361774569875505293428856181093904091" "33788264851714311303725089", "6703903964971298549787012499102923063739682910296196688861780721" "8608820150367734884009371490834517138450159290932430254268769414" "05973284973216824503042158", "6703903964971298549787012499102923063739682910296196688861780721" "8608820150367734884009371490834517138450159290932430254268769414" "05973284973216824503042159", "1" }, { /* between seventh and eighth iteration */ "6456987954117763835533395796948878140715006860263624787492985786" "8514630216966738305923915688821526449499763719943997120302368211" "04813318117996225041943964", "1340780792994259709957402499820584612747936582059239337772356144" "3721764030073546976801874298166903427690031858186486050853753882" "811946551499689575296532556", "1340780792994259709957402499820584612747936582059239337772356144" "3721764030073546976801874298166903427690031858186486050853753882" "811946551499689575296532557", "1" } }; static int test_mod_exp(int i) { const MOD_EXP_TEST *test = &ModExpTests[i]; int res = 0; BIGNUM* result = NULL; BIGNUM *base = NULL, *exponent = NULL, *modulo = NULL; char *s = NULL; if (!TEST_ptr(result = BN_new()) || !TEST_true(BN_dec2bn(&base, test->base)) || !TEST_true(BN_dec2bn(&exponent, test->exp)) || !TEST_true(BN_dec2bn(&modulo, test->mod))) goto err; if (!TEST_int_eq(BN_mod_exp(result, base, exponent, modulo, ctx), 1)) goto err; if (!TEST_ptr(s = BN_bn2dec(result))) goto err; if (!TEST_mem_eq(s, strlen(s), test->res, strlen(test->res))) goto err; res = 1; err: OPENSSL_free(s); BN_free(result); BN_free(base); BN_free(exponent); BN_free(modulo); return res; } static int test_mod_exp_consttime(int i) { const MOD_EXP_TEST *test = &ModExpTests[i]; int res = 0; BIGNUM* result = NULL; BIGNUM *base = NULL, *exponent = NULL, *modulo = NULL; char *s = NULL; if (!TEST_ptr(result = BN_new()) || !TEST_true(BN_dec2bn(&base, test->base)) || !TEST_true(BN_dec2bn(&exponent, test->exp)) || !TEST_true(BN_dec2bn(&modulo, test->mod))) goto err; BN_set_flags(base, BN_FLG_CONSTTIME); BN_set_flags(exponent, BN_FLG_CONSTTIME); BN_set_flags(modulo, BN_FLG_CONSTTIME); if (!TEST_int_eq(BN_mod_exp(result, base, exponent, modulo, ctx), 1)) goto err; if (!TEST_ptr(s = BN_bn2dec(result))) goto err; if (!TEST_mem_eq(s, strlen(s), test->res, strlen(test->res))) goto err; res = 1; err: OPENSSL_free(s); BN_free(result); BN_free(base); BN_free(exponent); BN_free(modulo); return res; } /* * Regression test to ensure BN_mod_exp2_mont fails safely if argument m is * zero. */ static int test_mod_exp2_mont(void) { int res = 0; BIGNUM *exp_result = NULL; BIGNUM *exp_a1 = NULL, *exp_p1 = NULL, *exp_a2 = NULL, *exp_p2 = NULL, *exp_m = NULL; if (!TEST_ptr(exp_result = BN_new()) || !TEST_ptr(exp_a1 = BN_new()) || !TEST_ptr(exp_p1 = BN_new()) || !TEST_ptr(exp_a2 = BN_new()) || !TEST_ptr(exp_p2 = BN_new()) || !TEST_ptr(exp_m = BN_new())) goto err; if (!TEST_true(BN_one(exp_a1)) || !TEST_true(BN_one(exp_p1)) || !TEST_true(BN_one(exp_a2)) || !TEST_true(BN_one(exp_p2))) goto err; BN_zero(exp_m); /* input of 0 is even, so must fail */ if (!TEST_int_eq(BN_mod_exp2_mont(exp_result, exp_a1, exp_p1, exp_a2, exp_p2, exp_m, ctx, NULL), 0)) goto err; res = 1; err: BN_free(exp_result); BN_free(exp_a1); BN_free(exp_p1); BN_free(exp_a2); BN_free(exp_p2); BN_free(exp_m); return res; } static int test_mod_inverse(void) { int res = 0; char *str = NULL; BIGNUM *a = NULL; BIGNUM *b = NULL; BIGNUM *r = NULL; if (!TEST_true(BN_dec2bn(&a, "5193817943"))) goto err; if (!TEST_true(BN_dec2bn(&b, "3259122431"))) goto err; if (!TEST_ptr(r = BN_new())) goto err; if (!TEST_ptr_eq(BN_mod_inverse(r, a, b, ctx), r)) goto err; if (!TEST_ptr_ne(str = BN_bn2dec(r), NULL)) goto err; if (!TEST_int_eq(strcmp(str, "2609653924"), 0)) goto err; /* Note that this aliases the result with the modulus. */ if (!TEST_ptr_null(BN_mod_inverse(b, a, b, ctx))) goto err; res = 1; err: BN_free(a); BN_free(b); BN_free(r); OPENSSL_free(str); return res; } static int test_mod_exp_alias(int idx) { int res = 0; char *str = NULL; BIGNUM *a = NULL; BIGNUM *b = NULL; BIGNUM *c = NULL; BIGNUM *r = NULL; if (!TEST_true(BN_dec2bn(&a, "15"))) goto err; if (!TEST_true(BN_dec2bn(&b, "10"))) goto err; if (!TEST_true(BN_dec2bn(&c, "39"))) goto err; if (!TEST_ptr(r = BN_new())) goto err; if (!TEST_int_eq((idx == 0 ? BN_mod_exp_simple : BN_mod_exp_recp)(r, a, b, c, ctx), 1)) goto err; if (!TEST_ptr_ne(str = BN_bn2dec(r), NULL)) goto err; if (!TEST_str_eq(str, "36")) goto err; OPENSSL_free(str); str = NULL; BN_copy(r, b); /* Aliasing with exponent must work. */ if (!TEST_int_eq((idx == 0 ? BN_mod_exp_simple : BN_mod_exp_recp)(r, a, r, c, ctx), 1)) goto err; if (!TEST_ptr_ne(str = BN_bn2dec(r), NULL)) goto err; if (!TEST_str_eq(str, "36")) goto err; OPENSSL_free(str); str = NULL; /* Aliasing with modulus should return failure for the simple call. */ if (idx == 0) { if (!TEST_int_eq(BN_mod_exp_simple(c, a, b, c, ctx), 0)) goto err; } else { if (!TEST_int_eq(BN_mod_exp_recp(c, a, b, c, ctx), 1)) goto err; if (!TEST_ptr_ne(str = BN_bn2dec(c), NULL)) goto err; if (!TEST_str_eq(str, "36")) goto err; } res = 1; err: BN_free(a); BN_free(b); BN_free(c); BN_free(r); OPENSSL_free(str); return res; } static int file_test_run(STANZA *s) { static const FILETEST filetests[] = { {"Sum", file_sum}, {"LShift1", file_lshift1}, {"LShift", file_lshift}, {"RShift", file_rshift}, {"Square", file_square}, {"Product", file_product}, {"Quotient", file_quotient}, {"ModMul", file_modmul}, {"ModExp", file_modexp}, {"Exp", file_exp}, {"ModSqrt", file_modsqrt}, {"GCD", file_gcd}, }; int numtests = OSSL_NELEM(filetests); const FILETEST *tp = filetests; for ( ; --numtests >= 0; tp++) { if (findattr(s, tp->name) != NULL) { if (!tp->func(s)) { TEST_info("%s:%d: Failed %s test", s->test_file, s->start, tp->name); return 0; } return 1; } } TEST_info("%s:%d: Unknown test", s->test_file, s->start); return 0; } static int run_file_tests(int i) { STANZA *s = NULL; char *testfile = test_get_argument(i); int c; if (!TEST_ptr(s = OPENSSL_zalloc(sizeof(*s)))) return 0; if (!test_start_file(s, testfile)) { OPENSSL_free(s); return 0; } /* Read test file. */ while (!BIO_eof(s->fp) && test_readstanza(s)) { if (s->numpairs == 0) continue; if (!file_test_run(s)) s->errors++; s->numtests++; test_clearstanza(s); } test_end_file(s); c = s->errors; OPENSSL_free(s); return c == 0; } typedef enum OPTION_choice { OPT_ERR = -1, OPT_EOF = 0, OPT_STOCHASTIC_TESTS, OPT_TEST_ENUM } OPTION_CHOICE; const OPTIONS *test_get_options(void) { static const OPTIONS test_options[] = { OPT_TEST_OPTIONS_WITH_EXTRA_USAGE("[file...]\n"), { "stochastic", OPT_STOCHASTIC_TESTS, '-', "Run stochastic tests" }, { OPT_HELP_STR, 1, '-', "file\tFile to run tests on. Normal tests are not run\n" }, { NULL } }; return test_options; } int setup_tests(void) { OPTION_CHOICE o; int n, stochastic = 0; while ((o = opt_next()) != OPT_EOF) { switch (o) { case OPT_STOCHASTIC_TESTS: stochastic = 1; break; case OPT_TEST_CASES: break; default: case OPT_ERR: return 0; } } n = test_get_argument_count(); if (!TEST_ptr(ctx = BN_CTX_new())) return 0; if (n == 0) { ADD_TEST(test_sub); ADD_TEST(test_div_recip); ADD_ALL_TESTS(test_signed_mod_replace_ab, OSSL_NELEM(signed_mod_tests)); ADD_ALL_TESTS(test_signed_mod_replace_ba, OSSL_NELEM(signed_mod_tests)); ADD_TEST(test_mod); ADD_TEST(test_mod_inverse); ADD_ALL_TESTS(test_mod_exp_alias, 2); ADD_TEST(test_modexp_mont5); ADD_TEST(test_kronecker); ADD_TEST(test_rand); ADD_TEST(test_bn2padded); ADD_TEST(test_dec2bn); ADD_TEST(test_hex2bn); ADD_TEST(test_asc2bn); ADD_TEST(test_bin2zero); ADD_TEST(test_bin2bn_lengths); ADD_ALL_TESTS(test_mpi, (int)OSSL_NELEM(kMPITests)); ADD_ALL_TESTS(test_bn2signed, (int)OSSL_NELEM(kSignedTests_BE)); ADD_TEST(test_negzero); ADD_TEST(test_badmod); ADD_TEST(test_expmodzero); ADD_TEST(test_expmodone); ADD_ALL_TESTS(test_smallprime, 16); ADD_ALL_TESTS(test_smallsafeprime, 16); ADD_TEST(test_swap); ADD_TEST(test_ctx_consttime_flag); #ifndef OPENSSL_NO_EC2M ADD_TEST(test_gf2m_add); ADD_TEST(test_gf2m_mod); ADD_TEST(test_gf2m_mul); ADD_TEST(test_gf2m_sqr); ADD_TEST(test_gf2m_modinv); ADD_TEST(test_gf2m_moddiv); ADD_TEST(test_gf2m_modexp); ADD_TEST(test_gf2m_modsqrt); ADD_TEST(test_gf2m_modsolvequad); #endif ADD_ALL_TESTS(test_is_prime, (int)OSSL_NELEM(primes)); ADD_ALL_TESTS(test_not_prime, (int)OSSL_NELEM(not_primes)); ADD_TEST(test_gcd_prime); ADD_TEST(test_coprime); ADD_ALL_TESTS(test_mod_exp, (int)OSSL_NELEM(ModExpTests)); ADD_ALL_TESTS(test_mod_exp_consttime, (int)OSSL_NELEM(ModExpTests)); ADD_TEST(test_mod_exp2_mont); if (stochastic) ADD_TEST(test_rand_range); } else { ADD_ALL_TESTS(run_file_tests, n); } return 1; } void cleanup_tests(void) { BN_CTX_free(ctx); }
./openssl/test/chacha_internal_test.c
/* * Copyright 2017-2023 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ /* * Internal tests for the chacha module. EVP tests would exercise * complete 32-byte blocks. This test goes per byte... */ #include <string.h> #include <openssl/opensslconf.h> #include "testutil.h" #include "crypto/chacha.h" static const unsigned int key[] = { 0x03020100, 0x07060504, 0x0b0a0908, 0x0f0e0d0c, 0x13121110, 0x17161514, 0x1b1a1918, 0x1f1e1d1c }; static const unsigned int ivp[] = { 0x00000000, 0x00000000, 0x03020100, 0x07060504 }; static const unsigned char ref[] = { 0xf7, 0x98, 0xa1, 0x89, 0xf1, 0x95, 0xe6, 0x69, 0x82, 0x10, 0x5f, 0xfb, 0x64, 0x0b, 0xb7, 0x75, 0x7f, 0x57, 0x9d, 0xa3, 0x16, 0x02, 0xfc, 0x93, 0xec, 0x01, 0xac, 0x56, 0xf8, 0x5a, 0xc3, 0xc1, 0x34, 0xa4, 0x54, 0x7b, 0x73, 0x3b, 0x46, 0x41, 0x30, 0x42, 0xc9, 0x44, 0x00, 0x49, 0x17, 0x69, 0x05, 0xd3, 0xbe, 0x59, 0xea, 0x1c, 0x53, 0xf1, 0x59, 0x16, 0x15, 0x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 0x4c, 0x67, 0xaf, 0xf8, 0x57, 0xe5, 0xea, 0x15, 0xa9, 0x08, 0xd8, 0x3a, 0x1d, 0x97, 0x04, 0xf8, 0xe5, 0x5e, 0x73, 0x52, 0xb2, 0x0b, 0x69, 0x4b, 0xf9, 0x97, 0x02, 0x98, 0xe6, 0xb5, 0xaa, 0xd3, 0x3e, 0xa2, 0x15, 0x5d, 0x10, 0x5d, 0x4e }; static int test_cha_cha_internal(int n) { unsigned char buf[sizeof(ref)]; unsigned int i = n + 1, j; memset(buf, 0, i); memcpy(buf + i, ref + i, sizeof(ref) - i); ChaCha20_ctr32(buf, buf, i, key, ivp); /* * Idea behind checking for whole sizeof(ref) is that if * ChaCha20_ctr32 oversteps i-th byte, then we'd know */ for (j = 0; j < sizeof(ref); j++) if (!TEST_uchar_eq(buf[j], ref[j])) { TEST_info("%d failed at %u (%02x)\n", i, j, buf[j]); return 0; } return 1; } int setup_tests(void) { #ifdef OPENSSL_CPUID_OBJ OPENSSL_cpuid_setup(); #endif ADD_ALL_TESTS(test_cha_cha_internal, sizeof(ref)); return 1; }
./openssl/test/aborttest.c
/* * Copyright 2016 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <openssl/crypto.h> int main(int argc, char **argv) { OPENSSL_die("Voluntary abort", __FILE__, __LINE__); return 0; }
./openssl/test/bioprinttest.c
/* * Copyright 2016-2020 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #define TESTUTIL_NO_size_t_COMPARISON #include <stdio.h> #include <string.h> #include <openssl/bio.h> #include "internal/numbers.h" #include "testutil.h" #include "testutil/output.h" #define nelem(x) (int)(sizeof(x) / sizeof((x)[0])) static int justprint = 0; static char *fpexpected[][10][5] = { { /* 00 */ { "0.0000e+00", "0.0000", "0", "0.0000E+00", "0" }, /* 01 */ { "6.7000e-01", "0.6700", "0.67", "6.7000E-01", "0.67" }, /* 02 */ { "6.6667e-01", "0.6667", "0.6667", "6.6667E-01", "0.6667" }, /* 03 */ { "6.6667e-04", "0.0007", "0.0006667", "6.6667E-04", "0.0006667" }, /* 04 */ { "6.6667e-05", "0.0001", "6.667e-05", "6.6667E-05", "6.667E-05" }, /* 05 */ { "6.6667e+00", "6.6667", "6.667", "6.6667E+00", "6.667" }, /* 06 */ { "6.6667e+01", "66.6667", "66.67", "6.6667E+01", "66.67" }, /* 07 */ { "6.6667e+02", "666.6667", "666.7", "6.6667E+02", "666.7" }, /* 08 */ { "6.6667e+03", "6666.6667", "6667", "6.6667E+03", "6667" }, /* 09 */ { "6.6667e+04", "66666.6667", "6.667e+04", "6.6667E+04", "6.667E+04" }, }, { /* 10 */ { "0.00000e+00", "0.00000", "0", "0.00000E+00", "0" }, /* 11 */ { "6.70000e-01", "0.67000", "0.67", "6.70000E-01", "0.67" }, /* 12 */ { "6.66667e-01", "0.66667", "0.66667", "6.66667E-01", "0.66667" }, /* 13 */ { "6.66667e-04", "0.00067", "0.00066667", "6.66667E-04", "0.00066667" }, /* 14 */ { "6.66667e-05", "0.00007", "6.6667e-05", "6.66667E-05", "6.6667E-05" }, /* 15 */ { "6.66667e+00", "6.66667", "6.6667", "6.66667E+00", "6.6667" }, /* 16 */ { "6.66667e+01", "66.66667", "66.667", "6.66667E+01", "66.667" }, /* 17 */ { "6.66667e+02", "666.66667", "666.67", "6.66667E+02", "666.67" }, /* 18 */ { "6.66667e+03", "6666.66667", "6666.7", "6.66667E+03", "6666.7" }, /* 19 */ { "6.66667e+04", "66666.66667", "66667", "6.66667E+04", "66667" }, }, { /* 20 */ { " 0.0000e+00", " 0.0000", " 0", " 0.0000E+00", " 0" }, /* 21 */ { " 6.7000e-01", " 0.6700", " 0.67", " 6.7000E-01", " 0.67" }, /* 22 */ { " 6.6667e-01", " 0.6667", " 0.6667", " 6.6667E-01", " 0.6667" }, /* 23 */ { " 6.6667e-04", " 0.0007", " 0.0006667", " 6.6667E-04", " 0.0006667" }, /* 24 */ { " 6.6667e-05", " 0.0001", " 6.667e-05", " 6.6667E-05", " 6.667E-05" }, /* 25 */ { " 6.6667e+00", " 6.6667", " 6.667", " 6.6667E+00", " 6.667" }, /* 26 */ { " 6.6667e+01", " 66.6667", " 66.67", " 6.6667E+01", " 66.67" }, /* 27 */ { " 6.6667e+02", " 666.6667", " 666.7", " 6.6667E+02", " 666.7" }, /* 28 */ { " 6.6667e+03", " 6666.6667", " 6667", " 6.6667E+03", " 6667" }, /* 29 */ { " 6.6667e+04", " 66666.6667", " 6.667e+04", " 6.6667E+04", " 6.667E+04" }, }, { /* 30 */ { " 0.00000e+00", " 0.00000", " 0", " 0.00000E+00", " 0" }, /* 31 */ { " 6.70000e-01", " 0.67000", " 0.67", " 6.70000E-01", " 0.67" }, /* 32 */ { " 6.66667e-01", " 0.66667", " 0.66667", " 6.66667E-01", " 0.66667" }, /* 33 */ { " 6.66667e-04", " 0.00067", " 0.00066667", " 6.66667E-04", " 0.00066667" }, /* 34 */ { " 6.66667e-05", " 0.00007", " 6.6667e-05", " 6.66667E-05", " 6.6667E-05" }, /* 35 */ { " 6.66667e+00", " 6.66667", " 6.6667", " 6.66667E+00", " 6.6667" }, /* 36 */ { " 6.66667e+01", " 66.66667", " 66.667", " 6.66667E+01", " 66.667" }, /* 37 */ { " 6.66667e+02", " 666.66667", " 666.67", " 6.66667E+02", " 666.67" }, /* 38 */ { " 6.66667e+03", " 6666.66667", " 6666.7", " 6.66667E+03", " 6666.7" }, /* 39 */ { " 6.66667e+04", " 66666.66667", " 66667", " 6.66667E+04", " 66667" }, }, { /* 40 */ { "0e+00", "0", "0", "0E+00", "0" }, /* 41 */ { "7e-01", "1", "0.7", "7E-01", "0.7" }, /* 42 */ { "7e-01", "1", "0.7", "7E-01", "0.7" }, /* 43 */ { "7e-04", "0", "0.0007", "7E-04", "0.0007" }, /* 44 */ { "7e-05", "0", "7e-05", "7E-05", "7E-05" }, /* 45 */ { "7e+00", "7", "7", "7E+00", "7" }, /* 46 */ { "7e+01", "67", "7e+01", "7E+01", "7E+01" }, /* 47 */ { "7e+02", "667", "7e+02", "7E+02", "7E+02" }, /* 48 */ { "7e+03", "6667", "7e+03", "7E+03", "7E+03" }, /* 49 */ { "7e+04", "66667", "7e+04", "7E+04", "7E+04" }, }, { /* 50 */ { "0.000000e+00", "0.000000", "0", "0.000000E+00", "0" }, /* 51 */ { "6.700000e-01", "0.670000", "0.67", "6.700000E-01", "0.67" }, /* 52 */ { "6.666667e-01", "0.666667", "0.666667", "6.666667E-01", "0.666667" }, /* 53 */ { "6.666667e-04", "0.000667", "0.000666667", "6.666667E-04", "0.000666667" }, /* 54 */ { "6.666667e-05", "0.000067", "6.66667e-05", "6.666667E-05", "6.66667E-05" }, /* 55 */ { "6.666667e+00", "6.666667", "6.66667", "6.666667E+00", "6.66667" }, /* 56 */ { "6.666667e+01", "66.666667", "66.6667", "6.666667E+01", "66.6667" }, /* 57 */ { "6.666667e+02", "666.666667", "666.667", "6.666667E+02", "666.667" }, /* 58 */ { "6.666667e+03", "6666.666667", "6666.67", "6.666667E+03", "6666.67" }, /* 59 */ { "6.666667e+04", "66666.666667", "66666.7", "6.666667E+04", "66666.7" }, }, { /* 60 */ { "0.0000e+00", "000.0000", "00000000", "0.0000E+00", "00000000" }, /* 61 */ { "6.7000e-01", "000.6700", "00000.67", "6.7000E-01", "00000.67" }, /* 62 */ { "6.6667e-01", "000.6667", "000.6667", "6.6667E-01", "000.6667" }, /* 63 */ { "6.6667e-04", "000.0007", "0.0006667", "6.6667E-04", "0.0006667" }, /* 64 */ { "6.6667e-05", "000.0001", "6.667e-05", "6.6667E-05", "6.667E-05" }, /* 65 */ { "6.6667e+00", "006.6667", "0006.667", "6.6667E+00", "0006.667" }, /* 66 */ { "6.6667e+01", "066.6667", "00066.67", "6.6667E+01", "00066.67" }, /* 67 */ { "6.6667e+02", "666.6667", "000666.7", "6.6667E+02", "000666.7" }, /* 68 */ { "6.6667e+03", "6666.6667", "00006667", "6.6667E+03", "00006667" }, /* 69 */ { "6.6667e+04", "66666.6667", "6.667e+04", "6.6667E+04", "6.667E+04" }, }, }; typedef struct z_data_st { size_t value; const char *format; const char *expected; } z_data; static z_data zu_data[] = { { SIZE_MAX, "%zu", (sizeof(size_t) == 4 ? "4294967295" : sizeof(size_t) == 8 ? "18446744073709551615" : "") }, /* * in 2-complement, the unsigned number divided by two plus one becomes the * smallest possible negative signed number of the corresponding type */ { SIZE_MAX / 2 + 1, "%zi", (sizeof(size_t) == 4 ? "-2147483648" : sizeof(size_t) == 8 ? "-9223372036854775808" : "") }, { 0, "%zu", "0" }, { 0, "%zi", "0" }, }; static int test_zu(int i) { char bio_buf[80]; const z_data *data = &zu_data[i]; BIO_snprintf(bio_buf, sizeof(bio_buf) - 1, data->format, data->value); if (!TEST_str_eq(bio_buf, data->expected)) return 0; return 1; } typedef struct j_data_st { uint64_t value; const char *format; const char *expected; } j_data; static j_data jf_data[] = { { 0xffffffffffffffffULL, "%ju", "18446744073709551615" }, { 0xffffffffffffffffULL, "%jx", "ffffffffffffffff" }, { 0x8000000000000000ULL, "%ju", "9223372036854775808" }, /* * These tests imply two's-complement, but it's the only binary * representation we support, see test/sanitytest.c... */ { 0x8000000000000000ULL, "%ji", "-9223372036854775808" }, }; static int test_j(int i) { const j_data *data = &jf_data[i]; char bio_buf[80]; BIO_snprintf(bio_buf, sizeof(bio_buf) - 1, data->format, data->value); if (!TEST_str_eq(bio_buf, data->expected)) return 0; return 1; } /* Precision and width. */ typedef struct pw_st { int p; const char *w; } pw; static pw pw_params[] = { { 4, "" }, { 5, "" }, { 4, "12" }, { 5, "12" }, { 0, "" }, { -1, "" }, { 4, "08" } }; static int dofptest(int test, int sub, double val, const char *width, int prec) { static const char *fspecs[] = { "e", "f", "g", "E", "G" }; char format[80], result[80]; int ret = 1, i; for (i = 0; i < nelem(fspecs); i++) { const char *fspec = fspecs[i]; if (prec >= 0) BIO_snprintf(format, sizeof(format), "%%%s.%d%s", width, prec, fspec); else BIO_snprintf(format, sizeof(format), "%%%s%s", width, fspec); BIO_snprintf(result, sizeof(result), format, val); if (justprint) { if (i == 0) printf(" /* %d%d */ { \"%s\"", test, sub, result); else printf(", \"%s\"", result); } else if (!TEST_str_eq(fpexpected[test][sub][i], result)) { TEST_info("test %d format=|%s| exp=|%s|, ret=|%s|", test, format, fpexpected[test][sub][i], result); ret = 0; } } if (justprint) printf(" },\n"); return ret; } static int test_fp(int i) { int t = 0, r; const double frac = 2.0 / 3.0; const pw *pwp = &pw_params[i]; if (justprint) printf(" {\n"); r = TEST_true(dofptest(i, t++, 0.0, pwp->w, pwp->p)) && TEST_true(dofptest(i, t++, 0.67, pwp->w, pwp->p)) && TEST_true(dofptest(i, t++, frac, pwp->w, pwp->p)) && TEST_true(dofptest(i, t++, frac / 1000, pwp->w, pwp->p)) && TEST_true(dofptest(i, t++, frac / 10000, pwp->w, pwp->p)) && TEST_true(dofptest(i, t++, 6.0 + frac, pwp->w, pwp->p)) && TEST_true(dofptest(i, t++, 66.0 + frac, pwp->w, pwp->p)) && TEST_true(dofptest(i, t++, 666.0 + frac, pwp->w, pwp->p)) && TEST_true(dofptest(i, t++, 6666.0 + frac, pwp->w, pwp->p)) && TEST_true(dofptest(i, t++, 66666.0 + frac, pwp->w, pwp->p)); if (justprint) printf(" },\n"); return r; } static int test_big(void) { char buf[80]; /* Test excessively big number. Should fail */ if (!TEST_int_eq(BIO_snprintf(buf, sizeof(buf), "%f\n", 2 * (double)ULONG_MAX), -1)) return 0; return 1; } typedef enum OPTION_choice { OPT_ERR = -1, OPT_EOF = 0, OPT_PRINT, OPT_TEST_ENUM } OPTION_CHOICE; const OPTIONS *test_get_options(void) { static const OPTIONS options[] = { OPT_TEST_OPTIONS_DEFAULT_USAGE, { "expected", OPT_PRINT, '-', "Output values" }, { NULL } }; return options; } int setup_tests(void) { OPTION_CHOICE o; while ((o = opt_next()) != OPT_EOF) { switch (o) { case OPT_PRINT: justprint = 1; break; case OPT_TEST_CASES: break; default: return 0; } } ADD_TEST(test_big); ADD_ALL_TESTS(test_fp, nelem(pw_params)); ADD_ALL_TESTS(test_zu, nelem(zu_data)); ADD_ALL_TESTS(test_j, nelem(jf_data)); return 1; } /* * Replace testutil output routines. We do this to eliminate possible sources * of BIO error */ BIO *bio_out = NULL; BIO *bio_err = NULL; static int tap_level = 0; void test_open_streams(void) { } void test_adjust_streams_tap_level(int level) { tap_level = level; } void test_close_streams(void) { } /* * This works out as long as caller doesn't use any "fancy" formats. * But we are caller's caller, and test_str_eq is the only one called, * and it uses only "%s", which is not "fancy"... */ int test_vprintf_stdout(const char *fmt, va_list ap) { return fprintf(stdout, "%*s# ", tap_level, "") + vfprintf(stdout, fmt, ap); } int test_vprintf_stderr(const char *fmt, va_list ap) { return fprintf(stderr, "%*s# ", tap_level, "") + vfprintf(stderr, fmt, ap); } int test_flush_stdout(void) { return fflush(stdout); } int test_flush_stderr(void) { return fflush(stderr); } int test_vprintf_tapout(const char *fmt, va_list ap) { return fprintf(stdout, "%*s", tap_level, "") + vfprintf(stdout, fmt, ap); } int test_vprintf_taperr(const char *fmt, va_list ap) { return fprintf(stderr, "%*s", tap_level, "") + vfprintf(stderr, fmt, ap); } int test_flush_tapout(void) { return fflush(stdout); } int test_flush_taperr(void) { return fflush(stderr); }
./openssl/test/pkcs12_format_test.c
/* * Copyright 2020-2023 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <stdio.h> #include <string.h> #include <stdlib.h> #include <openssl/pkcs12.h> #include <openssl/x509.h> #include <openssl/x509v3.h> #include <openssl/pem.h> #include "testutil.h" #include "helpers/pkcs12.h" static int default_libctx = 1; static OSSL_LIB_CTX *testctx = NULL; static OSSL_PROVIDER *nullprov = NULL; static OSSL_PROVIDER *deflprov = NULL; static OSSL_PROVIDER *lgcyprov = NULL; /* -------------------------------------------------------------------------- * PKCS12 component test data */ static const unsigned char CERT1[] = { 0x30, 0x82, 0x01, 0xed, 0x30, 0x82, 0x01, 0x56, 0xa0, 0x03, 0x02, 0x01, 0x02, 0x02, 0x09, 0x00, 0x8b, 0x4b, 0x5e, 0x6c, 0x03, 0x28, 0x4e, 0xe6, 0x30, 0x0d, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x0b, 0x05, 0x00, 0x30, 0x19, 0x31, 0x17, 0x30, 0x15, 0x06, 0x03, 0x55, 0x04, 0x03, 0x0c, 0x0e, 0x50, 0x31, 0x32, 0x54, 0x65, 0x73, 0x74, 0x2d, 0x52, 0x6f, 0x6f, 0x74, 0x2d, 0x41, 0x30, 0x1e, 0x17, 0x0d, 0x31, 0x39, 0x30, 0x39, 0x33, 0x30, 0x30, 0x30, 0x34, 0x36, 0x35, 0x36, 0x5a, 0x17, 0x0d, 0x32, 0x39, 0x30, 0x39, 0x32, 0x37, 0x30, 0x30, 0x34, 0x36, 0x35, 0x36, 0x5a, 0x30, 0x1b, 0x31, 0x19, 0x30, 0x17, 0x06, 0x03, 0x55, 0x04, 0x03, 0x0c, 0x10, 0x50, 0x31, 0x32, 0x54, 0x65, 0x73, 0x74, 0x2d, 0x53, 0x65, 0x72, 0x76, 0x65, 0x72, 0x2d, 0x31, 0x30, 0x81, 0x9f, 0x30, 0x0d, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x01, 0x05, 0x00, 0x03, 0x81, 0x8d, 0x00, 0x30, 0x81, 0x89, 0x02, 0x81, 0x81, 0x00, 0xbc, 0xdc, 0x6f, 0x8c, 0x7a, 0x2a, 0x4b, 0xea, 0x66, 0x66, 0x04, 0xa9, 0x05, 0x92, 0x53, 0xd7, 0x13, 0x3c, 0x49, 0xe1, 0xc8, 0xbb, 0xdf, 0x3d, 0xcb, 0x88, 0x31, 0x07, 0x20, 0x59, 0x93, 0x24, 0x7f, 0x7d, 0xc6, 0x84, 0x81, 0x16, 0x64, 0x4a, 0x52, 0xa6, 0x30, 0x44, 0xdc, 0x1a, 0x30, 0xde, 0xae, 0x29, 0x18, 0xcf, 0xc7, 0xf3, 0xcf, 0x0c, 0xb7, 0x8e, 0x2b, 0x1e, 0x21, 0x01, 0x0b, 0xfb, 0xe5, 0xe6, 0xcf, 0x2b, 0x84, 0xe1, 0x33, 0xf8, 0xba, 0x02, 0xfc, 0x30, 0xfa, 0xc4, 0x33, 0xc7, 0x37, 0xc6, 0x7f, 0x72, 0x31, 0x92, 0x1d, 0x8f, 0xa0, 0xfb, 0xe5, 0x4a, 0x08, 0x31, 0x78, 0x80, 0x9c, 0x23, 0xb4, 0xe9, 0x19, 0x56, 0x04, 0xfa, 0x0d, 0x07, 0x04, 0xb7, 0x43, 0xac, 0x4c, 0x49, 0x7c, 0xc2, 0xa1, 0x44, 0xc1, 0x48, 0x7d, 0x28, 0xe5, 0x23, 0x66, 0x07, 0x22, 0xd5, 0xf0, 0xf1, 0x02, 0x03, 0x01, 0x00, 0x01, 0xa3, 0x3b, 0x30, 0x39, 0x30, 0x1f, 0x06, 0x03, 0x55, 0x1d, 0x23, 0x04, 0x18, 0x30, 0x16, 0x80, 0x14, 0xdb, 0xbb, 0xb8, 0x92, 0x4e, 0x24, 0x0b, 0x1b, 0xbb, 0x78, 0x33, 0xf9, 0x01, 0x02, 0x23, 0x0d, 0x96, 0x18, 0x30, 0x47, 0x30, 0x09, 0x06, 0x03, 0x55, 0x1d, 0x13, 0x04, 0x02, 0x30, 0x00, 0x30, 0x0b, 0x06, 0x03, 0x55, 0x1d, 0x0f, 0x04, 0x04, 0x03, 0x02, 0x04, 0xf0, 0x30, 0x0d, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x0b, 0x05, 0x00, 0x03, 0x81, 0x81, 0x00, 0x1c, 0x13, 0xdc, 0x02, 0xf1, 0x44, 0x36, 0x65, 0xa9, 0xbe, 0x30, 0x1c, 0x66, 0x14, 0x20, 0x86, 0x5a, 0xa8, 0x69, 0x25, 0xf8, 0x1a, 0xb6, 0x9e, 0x5e, 0xe9, 0x89, 0xb8, 0x67, 0x70, 0x19, 0x87, 0x60, 0xeb, 0x4b, 0x11, 0x71, 0x85, 0xf8, 0xe9, 0xa7, 0x3e, 0x20, 0x42, 0xec, 0x43, 0x25, 0x01, 0x03, 0xe5, 0x4d, 0x83, 0x22, 0xf5, 0x8e, 0x3a, 0x1a, 0x1b, 0xd4, 0x1c, 0xda, 0x6b, 0x9d, 0x10, 0x1b, 0xee, 0x67, 0x4e, 0x1f, 0x69, 0xab, 0xbc, 0xaa, 0x62, 0x8e, 0x9e, 0xc6, 0xee, 0xd6, 0x09, 0xc0, 0xca, 0xe0, 0xaa, 0x9f, 0x07, 0xb2, 0xc2, 0xbb, 0x31, 0x96, 0xa2, 0x04, 0x62, 0xd3, 0x13, 0x32, 0x29, 0x67, 0x6e, 0xad, 0x2e, 0x0b, 0xea, 0x04, 0x7c, 0x8c, 0x5a, 0x5d, 0xac, 0x14, 0xaa, 0x61, 0x7f, 0x28, 0x6c, 0x2d, 0x64, 0x2d, 0xc3, 0xaf, 0x77, 0x52, 0x90, 0xb4, 0x37, 0xc0, 0x30, }; static const unsigned char CERT2[] = { 0x30, 0x82, 0x01, 0xed, 0x30, 0x82, 0x01, 0x56, 0xa0, 0x03, 0x02, 0x01, 0x02, 0x02, 0x09, 0x00, 0x8b, 0x4b, 0x5e, 0x6c, 0x03, 0x28, 0x4e, 0xe7, 0x30, 0x0d, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x0b, 0x05, 0x00, 0x30, 0x19, 0x31, 0x17, 0x30, 0x15, 0x06, 0x03, 0x55, 0x04, 0x03, 0x0c, 0x0e, 0x50, 0x31, 0x32, 0x54, 0x65, 0x73, 0x74, 0x2d, 0x52, 0x6f, 0x6f, 0x74, 0x2d, 0x41, 0x30, 0x1e, 0x17, 0x0d, 0x31, 0x39, 0x30, 0x39, 0x33, 0x30, 0x30, 0x30, 0x34, 0x36, 0x35, 0x36, 0x5a, 0x17, 0x0d, 0x32, 0x39, 0x30, 0x39, 0x32, 0x37, 0x30, 0x30, 0x34, 0x36, 0x35, 0x36, 0x5a, 0x30, 0x1b, 0x31, 0x19, 0x30, 0x17, 0x06, 0x03, 0x55, 0x04, 0x03, 0x0c, 0x10, 0x50, 0x31, 0x32, 0x54, 0x65, 0x73, 0x74, 0x2d, 0x43, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x2d, 0x31, 0x30, 0x81, 0x9f, 0x30, 0x0d, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x01, 0x05, 0x00, 0x03, 0x81, 0x8d, 0x00, 0x30, 0x81, 0x89, 0x02, 0x81, 0x81, 0x00, 0xa8, 0x6e, 0x40, 0x86, 0x9f, 0x98, 0x59, 0xfb, 0x57, 0xbf, 0xc1, 0x55, 0x12, 0x38, 0xeb, 0xb3, 0x46, 0x34, 0xc9, 0x35, 0x4d, 0xfd, 0x03, 0xe9, 0x3a, 0x88, 0x9e, 0x97, 0x8f, 0xf4, 0xec, 0x36, 0x7b, 0x3f, 0xba, 0xb8, 0xa5, 0x96, 0x30, 0x03, 0xc5, 0xc6, 0xd9, 0xa8, 0x4e, 0xbc, 0x23, 0x51, 0xa1, 0x96, 0xd2, 0x03, 0x98, 0x73, 0xb6, 0x17, 0x9c, 0x77, 0xd4, 0x95, 0x1e, 0x1b, 0xb3, 0x1b, 0xc8, 0x71, 0xd1, 0x2e, 0x31, 0xc7, 0x6a, 0x75, 0x57, 0x08, 0x7f, 0xba, 0x70, 0x76, 0xf7, 0x67, 0xf4, 0x4e, 0xbe, 0xfc, 0x70, 0x61, 0x41, 0x07, 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xcd, 0xe6, 0xb2, 0xa1, 0x83, 0x09, 0xdb, 0x9e, 0x4f, 0xff, 0x6a, 0x17, 0x4f, 0x33, 0xc9, 0xcc, 0x90, 0x2a, 0x67, 0xff, 0x16, 0x78, 0xa8, 0x2c, 0x10, 0xe0, 0x52, 0x8c, 0xe6, 0xe9, 0x90, 0x8d, 0xe0, 0x62, 0x04, 0x9a, 0x0f, 0x44, 0x01, 0x82, 0x14, 0x92, 0x44, 0x25, 0x69, 0x22, 0xb7, 0xb8, 0xc5, 0x94, 0x4c, 0x4b, 0x1c, 0x9b, 0x92, 0x60, 0x66, 0x90, 0x4e, 0xb9, 0xa8, 0x4c, 0x89, 0xbb, 0x0f, 0x0b, }; static const unsigned char KEY1[] = { 0x30, 0x82, 0x02, 0x5d, 0x02, 0x01, 0x00, 0x02, 0x81, 0x81, 0x00, 0xbc, 0xdc, 0x6f, 0x8c, 0x7a, 0x2a, 0x4b, 0xea, 0x66, 0x66, 0x04, 0xa9, 0x05, 0x92, 0x53, 0xd7, 0x13, 0x3c, 0x49, 0xe1, 0xc8, 0xbb, 0xdf, 0x3d, 0xcb, 0x88, 0x31, 0x07, 0x20, 0x59, 0x93, 0x24, 0x7f, 0x7d, 0xc6, 0x84, 0x81, 0x16, 0x64, 0x4a, 0x52, 0xa6, 0x30, 0x44, 0xdc, 0x1a, 0x30, 0xde, 0xae, 0x29, 0x18, 0xcf, 0xc7, 0xf3, 0xcf, 0x0c, 0xb7, 0x8e, 0x2b, 0x1e, 0x21, 0x01, 0x0b, 0xfb, 0xe5, 0xe6, 0xcf, 0x2b, 0x84, 0xe1, 0x33, 0xf8, 0xba, 0x02, 0xfc, 0x30, 0xfa, 0xc4, 0x33, 0xc7, 0x37, 0xc6, 0x7f, 0x72, 0x31, 0x92, 0x1d, 0x8f, 0xa0, 0xfb, 0xe5, 0x4a, 0x08, 0x31, 0x78, 0x80, 0x9c, 0x23, 0xb4, 0xe9, 0x19, 0x56, 0x04, 0xfa, 0x0d, 0x07,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a, 0x2e, 0xea, 0x4f, 0x07, 0xd3, 0x68, 0x62, 0xee, 0x1a, 0x04, 0x16, 0x44, 0x0d, 0xef, 0xf6, 0x1b, 0x95, 0x65, 0xa5, 0xd1, 0x47, 0x81, 0x2c, 0x14, 0xb3, 0x8e, 0xf9, 0x08, 0xcf, 0x11, 0x07, 0x55, 0xca, 0x2a, 0xad, 0xf7, 0xd3, 0xbd, 0x0f, 0x97, 0xf0, 0xde, 0xde, 0x70, 0xb6, 0x44, 0x70, 0x47, 0xf7, 0xf9, 0xcf, 0x75, 0x61, 0x7f, 0xf3, 0x02, 0x40, 0x38, 0x4a, 0x67, 0xaf, 0xae, 0xb6, 0xb2, 0x6a, 0x00, 0x25, 0x5a, 0xa4, 0x65, 0x20, 0xb1, 0x13, 0xbd, 0x83, 0xff, 0xb4, 0xbc, 0xf4, 0xdd, 0xa1, 0xbb, 0x1c, 0x96, 0x37, 0x35, 0xf4, 0xbf, 0xed, 0x4c, 0xed, 0x92, 0xe8, 0xac, 0xc9, 0xc1, 0xa5, 0xa3, 0x23, 0x66, 0x40, 0x8a, 0xa1, 0xe6, 0xe3, 0x95, 0xfe, 0xc4, 0x53, 0xf5, 0x7d, 0x6e, 0xca, 0x45, 0x42, 0xe4, 0xc2, 0x9f, 0xe5, 0x1e, 0xb5, }; static const unsigned char KEY2[] = { 0x30, 0x82, 0x02, 0x5c, 0x02, 0x01, 0x00, 0x02, 0x81, 0x81, 0x00, 0xa8, 0x6e, 0x40, 0x86, 0x9f, 0x98, 0x59, 0xfb, 0x57, 0xbf, 0xc1, 0x55, 0x12, 0x38, 0xeb, 0xb3, 0x46, 0x34, 0xc9, 0x35, 0x4d, 0xfd, 0x03, 0xe9, 0x3a, 0x88, 0x9e, 0x97, 0x8f, 0xf4, 0xec, 0x36, 0x7b, 0x3f, 0xba, 0xb8, 0xa5, 0x96, 0x30, 0x03, 0xc5, 0xc6, 0xd9, 0xa8, 0x4e, 0xbc, 0x23, 0x51, 0xa1, 0x96, 0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0xa4, 0x73, 0x3b, 0x72, 0x9e, 0x92, 0x55, 0x6e, 0x51, 0x3c, 0x39, 0x43, 0x5a, 0xe4, 0xa4, 0x71, 0xcc, 0xc5, 0xaf, 0x3f, 0xbb, 0xc8, 0x80, 0x65, 0x67, 0x2d, 0x9e, 0x32, 0x10, 0x99, 0x03, 0x2c, 0x99, 0xc8, 0xab, 0x71, 0xed, 0x31, 0xf8, 0xbb, 0xde, 0xee, 0x69, 0x7f, 0xba, 0x31, 0x02, 0x40, 0x7e, 0xbc, 0x60, 0x55, 0x4e, 0xd5, 0xc8, 0x6e, 0xf4, 0x0e, 0x57, 0xbe, 0x2e, 0xf9, 0x39, 0xbe, 0x59, 0x3f, 0xa2, 0x30, 0xbb, 0x57, 0xd1, 0xa3, 0x13, 0x2e, 0x55, 0x7c, 0x7c, 0x6a, 0xd8, 0xde, 0x02, 0xbe, 0x9e, 0xed, 0x10, 0xd0, 0xc5, 0x73, 0x1d, 0xea, 0x3e, 0xb1, 0x55, 0x81, 0x02, 0xef, 0x48, 0xc8, 0x1c, 0x5c, 0x7a, 0x92, 0xb0, 0x58, 0xd3, 0x19, 0x5b, 0x5d, 0xa2, 0xb6, 0x56, 0x69, 0x02, 0x40, 0x1e, 0x00, 0x6a, 0x9f, 0xba, 0xee, 0x46, 0x5a, 0xc5, 0xb5, 0x9f, 0x91, 0x33, 0xdd, 0xc9, 0x96, 0x75, 0xb7, 0x87, 0xcf, 0x18, 0x1c, 0xb7, 0xb9, 0x3f, 0x04, 0x10, 0xb8, 0x75, 0xa9, 0xb8, 0xa0, 0x31, 0x35, 0x03, 0x30, 0x89, 0xc8, 0x37, 0x68, 0x20, 0x30, 0x99, 0x39, 0x96, 0xd6, 0x2b, 0x3d, 0x5e, 0x45, 0x84, 0xf7, 0xd2, 0x61, 0x50, 0xc9, 0x50, 0xba, 0x8d, 0x08, 0xaa, 0xd0, 0x08, 0x1e, }; static const PKCS12_ATTR ATTRS1[] = { { "friendlyName", "george" }, { "localKeyID", "1234567890" }, { "1.2.3.4.5", "MyCustomAttribute" }, { NULL, NULL } }; static const PKCS12_ATTR ATTRS2[] = { { "friendlyName", "janet" }, { "localKeyID", "987654321" }, { "1.2.3.5.8.13", "AnotherCustomAttribute" }, { NULL, NULL } }; static const PKCS12_ATTR ATTRS3[] = { { "friendlyName", "wildduk" }, { "localKeyID", "1122334455" }, { "oracle-jdk-trustedkeyusage", "anyExtendedKeyUsage" }, { NULL, NULL } }; static const PKCS12_ATTR ATTRS4[] = { { "friendlyName", "wildduk" }, { "localKeyID", "1122334455" }, { NULL, NULL } }; static const PKCS12_ENC enc_default = { #ifndef OPENSSL_NO_DES NID_pbe_WithSHA1And3_Key_TripleDES_CBC, #else NID_aes_128_cbc, #endif "Password1", 1000 }; static const PKCS12_ENC mac_default = { NID_sha1, "Password1", 1000 }; static const int enc_nids_all[] = { /* NOTE: To use PBES2 we pass the desired cipher NID instead of NID_pbes2 */ NID_aes_128_cbc, NID_aes_256_cbc, #ifndef OPENSSL_NO_DES NID_des_ede3_cbc, NID_des_cbc, #endif #ifndef OPENSSL_NO_RC5 NID_rc5_cbc, #endif #ifndef OPENSSL_NO_RC4 NID_rc4, #endif #ifndef OPENSSL_NO_RC2 NID_rc2_cbc, #endif #ifndef OPENSSL_NO_MD2 # ifndef OPENSSL_NO_DES NID_pbeWithMD2AndDES_CBC, # endif # ifndef OPENSSL_NO_RC2 NID_pbeWithMD2AndRC2_CBC, # endif #endif #ifndef OPENSSL_NO_MD5 # ifndef OPENSSL_NO_DES NID_pbeWithMD5AndDES_CBC, # endif # ifndef OPENSSL_NO_RC2 NID_pbeWithMD5AndRC2_CBC, # endif #endif #ifndef OPENSSL_NO_DES NID_pbeWithSHA1AndDES_CBC, #endif #ifndef OPENSSL_NO_RC2 NID_pbe_WithSHA1And128BitRC2_CBC, NID_pbe_WithSHA1And40BitRC2_CBC, NID_pbeWithSHA1AndRC2_CBC, #endif #ifndef OPENSSL_NO_RC4 NID_pbe_WithSHA1And128BitRC4, NID_pbe_WithSHA1And40BitRC4, #endif #ifndef OPENSSL_NO_DES NID_pbe_WithSHA1And2_Key_TripleDES_CBC, NID_pbe_WithSHA1And3_Key_TripleDES_CBC, #endif }; static const int enc_nids_no_legacy[] = { /* NOTE: To use PBES2 we pass the desired cipher NID instead of NID_pbes2 */ NID_aes_128_cbc, NID_aes_256_cbc, #ifndef OPENSSL_NO_DES NID_des_ede3_cbc, NID_pbe_WithSHA1And2_Key_TripleDES_CBC, NID_pbe_WithSHA1And3_Key_TripleDES_CBC, #endif }; static const int mac_nids[] = { NID_sha1, NID_md5, NID_sha256, NID_sha512, NID_sha3_256, NID_sha3_512 }; static const int iters[] = { 1, 1000 }; static const char *passwords[] = { "Password1", "", }; /* -------------------------------------------------------------------------- * Local functions */ static int get_custom_oid(void) { static int sec_nid = -1; if (sec_nid != -1) return sec_nid; if (!TEST_true(OBJ_create("1.3.5.7.9", "CustomSecretOID", "My custom secret OID"))) return -1; return sec_nid = OBJ_txt2nid("CustomSecretOID"); } /* -------------------------------------------------------------------------- * PKCS12 format tests */ static int test_single_cert_no_attrs(void) { PKCS12_BUILDER *pb = new_pkcs12_builder("1cert.p12"); /* Generate/encode */ start_pkcs12(pb); start_contentinfo(pb); add_certbag(pb, CERT1, sizeof(CERT1), NULL); end_contentinfo(pb); end_pkcs12(pb); /* Read/decode */ start_check_pkcs12(pb); start_check_contentinfo(pb); check_certbag(pb, CERT1, sizeof(CERT1), NULL); end_check_contentinfo(pb); end_check_pkcs12(pb); return end_pkcs12_builder(pb); } static int test_single_key(PKCS12_ENC *enc) { char fname[80]; PKCS12_BUILDER *pb; sprintf(fname, "1key_ciph-%s_iter-%d.p12", OBJ_nid2sn(enc->nid), enc->iter); pb = new_pkcs12_builder(fname); /* Generate/encode */ start_pkcs12(pb); start_contentinfo(pb); add_keybag(pb, KEY1, sizeof(KEY1), NULL, enc); end_contentinfo(pb); end_pkcs12(pb); /* Read/decode */ start_check_pkcs12(pb); start_check_contentinfo(pb); check_keybag(pb, KEY1, sizeof(KEY1), NULL, enc); end_check_contentinfo(pb); end_check_pkcs12(pb); return end_pkcs12_builder(pb); } static int test_single_key_enc_alg(int z) { PKCS12_ENC enc; if (lgcyprov == NULL) enc.nid = enc_nids_no_legacy[z]; else enc.nid = enc_nids_all[z]; enc.pass = enc_default.pass; enc.iter = enc_default.iter; return test_single_key(&enc); } static int test_single_key_enc_pass(int z) { PKCS12_ENC enc; enc.nid = enc_default.nid; enc.pass = passwords[z]; enc.iter = enc_default.iter; return test_single_key(&enc); } static int test_single_key_enc_iter(int z) { PKCS12_ENC enc; enc.nid = enc_default.nid; enc.pass = enc_default.pass; enc.iter = iters[z]; return test_single_key(&enc); } static int test_single_key_with_attrs(void) { PKCS12_BUILDER *pb = new_pkcs12_builder("1keyattrs.p12"); /* Generate/encode */ start_pkcs12(pb); start_contentinfo(pb); add_keybag(pb, KEY1, sizeof(KEY1), ATTRS1, &enc_default); end_contentinfo(pb); end_pkcs12(pb); /* Read/decode */ start_check_pkcs12(pb); start_check_contentinfo(pb); check_keybag(pb, KEY1, sizeof(KEY1), ATTRS1, &enc_default); end_check_contentinfo(pb); end_check_pkcs12(pb); return end_pkcs12_builder(pb); } static int test_single_cert_mac(PKCS12_ENC *mac) { char fname[80]; PKCS12_BUILDER *pb; sprintf(fname, "1cert_mac-%s_iter-%d.p12", OBJ_nid2sn(mac->nid), mac->iter); pb = new_pkcs12_builder(fname); /* Generate/encode */ start_pkcs12(pb); start_contentinfo(pb); add_certbag(pb, CERT1, sizeof(CERT1), NULL); end_contentinfo(pb); end_pkcs12_with_mac(pb, mac); /* Read/decode */ start_check_pkcs12_with_mac(pb, mac); start_check_contentinfo(pb); check_certbag(pb, CERT1, sizeof(CERT1), NULL); end_check_contentinfo(pb); end_check_pkcs12(pb); return end_pkcs12_builder(pb); } static int test_single_cert_mac_alg(int z) { PKCS12_ENC mac; mac.nid = mac_nids[z]; mac.pass = mac_default.pass; mac.iter = mac_default.iter; return test_single_cert_mac(&mac); } static int test_single_cert_mac_pass(int z) { PKCS12_ENC mac; mac.nid = mac_default.nid; mac.pass = passwords[z]; mac.iter = mac_default.iter; return test_single_cert_mac(&mac); } static int test_single_cert_mac_iter(int z) { PKCS12_ENC mac; mac.nid = mac_default.nid; mac.pass = mac_default.pass; mac.iter = iters[z]; return test_single_cert_mac(&mac); } static int test_cert_key_with_attrs_and_mac(void) { PKCS12_BUILDER *pb = new_pkcs12_builder("1cert1key.p12"); /* Generate/encode */ start_pkcs12(pb); start_contentinfo(pb); add_certbag(pb, CERT1, sizeof(CERT1), ATTRS1); add_keybag(pb, KEY1, sizeof(KEY1), ATTRS1, &enc_default); end_contentinfo(pb); end_pkcs12_with_mac(pb, &mac_default); /* Read/decode */ start_check_pkcs12_with_mac(pb, &mac_default); start_check_contentinfo(pb); check_certbag(pb, CERT1, sizeof(CERT1), ATTRS1); check_keybag(pb, KEY1, sizeof(KEY1), ATTRS1, &enc_default); end_check_contentinfo(pb); end_check_pkcs12(pb); return end_pkcs12_builder(pb); } static int test_cert_key_encrypted_content(void) { PKCS12_BUILDER *pb = new_pkcs12_builder("1cert1key_enc.p12"); /* Generate/encode */ start_pkcs12(pb); start_contentinfo(pb); add_certbag(pb, CERT1, sizeof(CERT1), ATTRS1); add_keybag(pb, KEY1, sizeof(KEY1), ATTRS1, &enc_default); end_contentinfo_encrypted(pb, &enc_default); end_pkcs12_with_mac(pb, &mac_default); /* Read/decode */ start_check_pkcs12_with_mac(pb, &mac_default); start_check_contentinfo_encrypted(pb, &enc_default); check_certbag(pb, CERT1, sizeof(CERT1), ATTRS1); check_keybag(pb, KEY1, sizeof(KEY1), ATTRS1, &enc_default); end_check_contentinfo(pb); end_check_pkcs12(pb); return end_pkcs12_builder(pb); } static int test_single_secret_encrypted_content(void) { PKCS12_BUILDER *pb = new_pkcs12_builder("1secret.p12"); int custom_nid = get_custom_oid(); /* Generate/encode */ start_pkcs12(pb); start_contentinfo(pb); add_secretbag(pb, custom_nid, "VerySecretMessage", ATTRS1); end_contentinfo_encrypted(pb, &enc_default); end_pkcs12_with_mac(pb, &mac_default); /* Read/decode */ start_check_pkcs12_with_mac(pb, &mac_default); start_check_contentinfo_encrypted(pb, &enc_default); check_secretbag(pb, custom_nid, "VerySecretMessage", ATTRS1); end_check_contentinfo(pb); end_check_pkcs12(pb); return end_pkcs12_builder(pb); } static int test_single_secret(PKCS12_ENC *enc) { int custom_nid; char fname[80]; PKCS12_BUILDER *pb; sprintf(fname, "1secret_ciph-%s_iter-%d.p12", OBJ_nid2sn(enc->nid), enc->iter); pb = new_pkcs12_builder(fname); custom_nid = get_custom_oid(); /* Generate/encode */ start_pkcs12(pb); start_contentinfo(pb); add_secretbag(pb, custom_nid, "VerySecretMessage", ATTRS1); end_contentinfo_encrypted(pb, enc); end_pkcs12_with_mac(pb, &mac_default); /* Read/decode */ start_check_pkcs12_with_mac(pb, &mac_default); start_check_contentinfo_encrypted(pb, enc); check_secretbag(pb, custom_nid, "VerySecretMessage", ATTRS1); end_check_contentinfo(pb); end_check_pkcs12(pb); return end_pkcs12_builder(pb); } static int test_single_secret_enc_alg(int z) { PKCS12_ENC enc; if (lgcyprov == NULL) enc.nid = enc_nids_no_legacy[z]; else enc.nid = enc_nids_all[z]; enc.pass = enc_default.pass; enc.iter = enc_default.iter; return test_single_secret(&enc); } static int test_multiple_contents(void) { PKCS12_BUILDER *pb = new_pkcs12_builder("multi_contents.p12"); int custom_nid = get_custom_oid(); /* Generate/encode */ start_pkcs12(pb); start_contentinfo(pb); add_certbag(pb, CERT1, sizeof(CERT1), ATTRS1); add_certbag(pb, CERT2, sizeof(CERT2), ATTRS2); add_keybag(pb, KEY1, sizeof(KEY1), ATTRS1, &enc_default); add_keybag(pb, KEY2, sizeof(KEY2), ATTRS2, &enc_default); end_contentinfo(pb); start_contentinfo(pb); add_secretbag(pb, custom_nid, "VeryVerySecretMessage", ATTRS1); end_contentinfo_encrypted(pb, &enc_default); end_pkcs12_with_mac(pb, &mac_default); /* Read/decode */ start_check_pkcs12_with_mac(pb, &mac_default); start_check_contentinfo(pb); check_certbag(pb, CERT1, sizeof(CERT1), ATTRS1); check_certbag(pb, CERT2, sizeof(CERT2), ATTRS2); check_keybag(pb, KEY1, sizeof(KEY1), ATTRS1, &enc_default); check_keybag(pb, KEY2, sizeof(KEY2), ATTRS2, &enc_default); end_check_contentinfo(pb); start_check_contentinfo_encrypted(pb, &enc_default); check_secretbag(pb, custom_nid, "VeryVerySecretMessage", ATTRS1); end_check_contentinfo(pb); end_check_pkcs12(pb); return end_pkcs12_builder(pb); } static int test_jdk_trusted_attr(void) { PKCS12_BUILDER *pb = new_pkcs12_builder("jdk_trusted.p12"); /* Generate/encode */ start_pkcs12(pb); start_contentinfo(pb); add_certbag(pb, CERT1, sizeof(CERT1), ATTRS3); end_contentinfo(pb); end_pkcs12_with_mac(pb, &mac_default); /* Read/decode */ start_check_pkcs12_with_mac(pb, &mac_default); start_check_contentinfo(pb); check_certbag(pb, CERT1, sizeof(CERT1), ATTRS3); end_check_contentinfo(pb); end_check_pkcs12(pb); return end_pkcs12_builder(pb); } static int test_set0_attrs(void) { PKCS12_BUILDER *pb = new_pkcs12_builder("attrs.p12"); PKCS12_SAFEBAG *bag = NULL; STACK_OF(X509_ATTRIBUTE) *attrs = NULL; X509_ATTRIBUTE *attr = NULL; start_pkcs12(pb); start_contentinfo(pb); /* Add cert and attrs (name/locakkey only) */ add_certbag(pb, CERT1, sizeof(CERT1), ATTRS4); bag = sk_PKCS12_SAFEBAG_value(pb->bags, 0); attrs = (STACK_OF(X509_ATTRIBUTE)*)PKCS12_SAFEBAG_get0_attrs(bag); /* Create new attr, add to list and confirm return attrs is not NULL */ attr = X509_ATTRIBUTE_create(NID_oracle_jdk_trustedkeyusage, V_ASN1_OBJECT, OBJ_txt2obj("anyExtendedKeyUsage", 0)); X509at_add1_attr(&attrs, attr); PKCS12_SAFEBAG_set0_attrs(bag, attrs); attrs = (STACK_OF(X509_ATTRIBUTE)*)PKCS12_SAFEBAG_get0_attrs(bag); X509_ATTRIBUTE_free(attr); if(!TEST_ptr(attrs)) { goto err; } end_contentinfo(pb); end_pkcs12(pb); /* Read/decode */ start_check_pkcs12(pb); start_check_contentinfo(pb); /* Use existing check functionality to confirm cert bag attrs identical to ATTRS3 */ check_certbag(pb, CERT1, sizeof(CERT1), ATTRS3); end_check_contentinfo(pb); end_check_pkcs12(pb); return end_pkcs12_builder(pb); err: (void)end_pkcs12_builder(pb); return 0; } #ifndef OPENSSL_NO_DES static int pkcs12_create_test(void) { int ret = 0; EVP_PKEY *pkey = NULL; PKCS12 *p12 = NULL; const unsigned char *p; static const unsigned char rsa_key[] = { 0x30, 0x82, 0x02, 0x5d, 0x02, 0x01, 0x00, 0x02, 0x81, 0x81, 0x00, 0xbb, 0x24, 0x7a, 0x09, 0x7e, 0x0e, 0xb2, 0x37, 0x32, 0xcc, 0x39, 0x67, 0xad, 0xf1, 0x9e, 0x3d, 0x6b, 0x82, 0x83, 0xd1, 0xd0, 0xac, 0xa4, 0xc0, 0x18, 0xbe, 0x8d, 0x98, 0x00, 0xc0, 0x7b, 0xff, 0x07, 0x44, 0xc9, 0xca, 0x1c, 0xba, 0x36, 0xe1, 0x27, 0x69, 0xff, 0xb1, 0xe3, 0x8d, 0x8b, 0xee, 0x57, 0xa9, 0x3a, 0xaa, 0x16, 0x43, 0x39, 0x54, 0x19, 0x7c, 0xae, 0x69, 0x24, 0x14, 0xf6, 0x64, 0xff, 0xbc, 0x74, 0xc6, 0x67, 0x6c, 0x4c, 0xf1, 0x02, 0x49, 0x69, 0xc7, 0x2b, 0xe1, 0xe1, 0xa1, 0xa3, 0x43, 0x14, 0xf4, 0x77, 0x8f, 0xc8, 0xd0, 0x85, 0x5a, 0x35, 0x95, 0xac, 0x62, 0xa9, 0xc1, 0x21, 0x00, 0x77, 0xa0, 0x8b, 0x97, 0x30, 0xb4, 0x5a, 0x2c, 0xb8, 0x90, 0x2f, 0x48, 0xa0, 0x05, 0x28, 0x4b, 0xf2, 0x0f, 0x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89, 0xb1, 0x72, 0x31, 0xb8, 0x39, 0x8b, 0xcf, 0xe2, 0x8e, 0xa5, 0xda, 0x4f, 0x45, 0x1e, 0x53, 0x42, 0x66, 0xc4, 0x30, 0x4b, 0x29, 0x8e, 0xc1, 0x69, 0x17, 0x29, 0x8c, 0x8a, 0xe6, 0x0f, 0x82, 0x68, 0xa1, 0x41, 0xb3, 0xb6, 0x70, 0x99, 0x75, 0xa9, 0x27, 0x18, 0xe4, 0xe9, 0x02, 0x41, 0x00, 0x89, 0xea, 0x6e, 0x6d, 0x70, 0xdf, 0x25, 0x5f, 0x18, 0x3f, 0x48, 0xda, 0x63, 0x10, 0x8b, 0xfe, 0xa8, 0x0c, 0x94, 0x0f, 0xde, 0x97, 0x56, 0x53, 0x89, 0x94, 0xe2, 0x1e, 0x2c, 0x74, 0x3c, 0x91, 0x81, 0x34, 0x0b, 0xa6, 0x40, 0xf8, 0xcb, 0x2a, 0x60, 0x8c, 0xe0, 0x02, 0xb7, 0x89, 0x93, 0xcf, 0x18, 0x9f, 0x49, 0x54, 0xfd, 0x7d, 0x3f, 0x9a, 0xef, 0xd4, 0xa4, 0x4f, 0xc1, 0x45, 0x99, 0x91, }; p = rsa_key; if (!TEST_ptr(pkey = d2i_PrivateKey_ex(EVP_PKEY_RSA, NULL, &p, sizeof(rsa_key), NULL, NULL))) goto err; if (!TEST_int_eq(ERR_peek_error(), 0)) goto err; p12 = PKCS12_create(NULL, NULL, pkey, NULL, NULL, NID_pbe_WithSHA1And3_Key_TripleDES_CBC, NID_pbe_WithSHA1And3_Key_TripleDES_CBC, 2, 1, 0); if (!TEST_ptr(p12)) goto err; if (!TEST_int_eq(ERR_peek_error(), 0)) goto err; ret = 1; err: PKCS12_free(p12); EVP_PKEY_free(pkey); return ret; } #endif static int pkcs12_recreate_test(void) { int ret = 0; X509 *cert = NULL; X509 *cert_parsed = NULL; EVP_PKEY *pkey = NULL; EVP_PKEY *pkey_parsed = NULL; PKCS12 *p12 = NULL; PKCS12 *p12_parsed = NULL; PKCS12 *p12_recreated = NULL; const unsigned char *cert_bytes = CERT1; const unsigned char *key_bytes = KEY1; BIO *bio = NULL; cert = d2i_X509(NULL, &cert_bytes, sizeof(CERT1)); if (!TEST_ptr(cert)) goto err; pkey = d2i_AutoPrivateKey(NULL, &key_bytes, sizeof(KEY1)); if (!TEST_ptr(pkey)) goto err; p12 = PKCS12_create("pass", NULL, pkey, cert, NULL, NID_aes_256_cbc, NID_aes_256_cbc, 2, 1, 0); if (!TEST_ptr(p12)) goto err; if (!TEST_int_eq(ERR_peek_error(), 0)) goto err; bio = BIO_new(BIO_s_mem()); if (!TEST_ptr(bio)) goto err; if (!TEST_int_eq(i2d_PKCS12_bio(bio, p12), 1)) goto err; p12_parsed = PKCS12_init_ex(NID_pkcs7_data, testctx, NULL); if (!TEST_ptr(p12_parsed)) goto err; p12_parsed = d2i_PKCS12_bio(bio, &p12_parsed); if (!TEST_ptr(p12_parsed)) goto err; if (!TEST_int_eq(PKCS12_parse(p12_parsed, "pass", &pkey_parsed, &cert_parsed, NULL), 1)) goto err; /* cert_parsed also contains auxiliary data */ p12_recreated = PKCS12_create("new_pass", NULL, pkey_parsed, cert_parsed, NULL, NID_aes_256_cbc, NID_aes_256_cbc, 2, 1, 0); if (!TEST_ptr(p12_recreated)) goto err; if (!TEST_int_eq(ERR_peek_error(), 0)) goto err; ret = 1; err: BIO_free(bio); PKCS12_free(p12); PKCS12_free(p12_parsed); PKCS12_free(p12_recreated); EVP_PKEY_free(pkey); EVP_PKEY_free(pkey_parsed); X509_free(cert); X509_free(cert_parsed); return ret; } typedef enum OPTION_choice { OPT_ERR = -1, OPT_EOF = 0, OPT_WRITE, OPT_LEGACY, OPT_CONTEXT, OPT_TEST_ENUM } OPTION_CHOICE; const OPTIONS *test_get_options(void) { static const OPTIONS options[] = { OPT_TEST_OPTIONS_DEFAULT_USAGE, { "write", OPT_WRITE, '-', "Write PKCS12 objects to file" }, { "legacy", OPT_LEGACY, '-', "Test the legacy APIs" }, { "context", OPT_CONTEXT, '-', "Explicitly use a non-default library context" }, { NULL } }; return options; } int setup_tests(void) { OPTION_CHOICE o; while ((o = opt_next()) != OPT_EOF) { switch (o) { case OPT_WRITE: PKCS12_helper_set_write_files(1); break; case OPT_LEGACY: PKCS12_helper_set_legacy(1); break; case OPT_CONTEXT: default_libctx = 0; break; case OPT_TEST_CASES: break; default: return 0; } } if (!default_libctx) { testctx = OSSL_LIB_CTX_new(); if (!TEST_ptr(testctx)) return 0; nullprov = OSSL_PROVIDER_load(NULL, "null"); if (!TEST_ptr(nullprov)) return 0; } deflprov = OSSL_PROVIDER_load(testctx, "default"); if (!TEST_ptr(deflprov)) return 0; lgcyprov = OSSL_PROVIDER_load(testctx, "legacy"); PKCS12_helper_set_libctx(testctx); /* * Verify that the default and fips providers in the default libctx are not * available if we are using a standalone context */ if (!default_libctx) { if (!TEST_false(OSSL_PROVIDER_available(NULL, "default")) || !TEST_false(OSSL_PROVIDER_available(NULL, "fips"))) return 0; } ADD_TEST(test_single_cert_no_attrs); if (lgcyprov == NULL) { ADD_ALL_TESTS(test_single_key_enc_alg, OSSL_NELEM(enc_nids_no_legacy)); ADD_ALL_TESTS(test_single_secret_enc_alg, OSSL_NELEM(enc_nids_no_legacy)); } else { ADD_ALL_TESTS(test_single_key_enc_alg, OSSL_NELEM(enc_nids_all)); ADD_ALL_TESTS(test_single_secret_enc_alg, OSSL_NELEM(enc_nids_all)); } #ifndef OPENSSL_NO_DES if (default_libctx) ADD_TEST(pkcs12_create_test); #endif if (default_libctx) ADD_TEST(pkcs12_recreate_test); ADD_ALL_TESTS(test_single_key_enc_pass, OSSL_NELEM(passwords)); ADD_ALL_TESTS(test_single_key_enc_iter, OSSL_NELEM(iters)); ADD_TEST(test_single_key_with_attrs); ADD_ALL_TESTS(test_single_cert_mac_alg, OSSL_NELEM(mac_nids)); ADD_ALL_TESTS(test_single_cert_mac_pass, OSSL_NELEM(passwords)); ADD_ALL_TESTS(test_single_cert_mac_iter, OSSL_NELEM(iters)); ADD_TEST(test_cert_key_with_attrs_and_mac); ADD_TEST(test_cert_key_encrypted_content); ADD_TEST(test_single_secret_encrypted_content); ADD_TEST(test_multiple_contents); ADD_TEST(test_jdk_trusted_attr); ADD_TEST(test_set0_attrs); return 1; } void cleanup_tests(void) { OSSL_PROVIDER_unload(nullprov); OSSL_PROVIDER_unload(deflprov); OSSL_PROVIDER_unload(lgcyprov); OSSL_LIB_CTX_free(testctx); }
./openssl/test/ssl_ctx_test.c
/* * Copyright 2018-2023 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include "testutil.h" #include <openssl/ssl.h> typedef struct { int proto; int min_version; int max_version; int min_ok; int max_ok; int expected_min; int expected_max; } version_test; #define PROTO_TLS 0 #define PROTO_DTLS 1 #define PROTO_QUIC 2 /* * If a version is valid for *any* protocol then setting the min/max protocol is * expected to return success, even if that version is not valid for *this* * protocol. However it only has an effect if it is valid for *this* protocol - * otherwise it is ignored. */ static const version_test version_testdata[] = { /* proto min max ok expected min expected max */ {PROTO_TLS, 0, 0, 1, 1, 0, 0}, {PROTO_TLS, SSL3_VERSION, TLS1_3_VERSION, 1, 1, SSL3_VERSION, TLS1_3_VERSION}, {PROTO_TLS, TLS1_VERSION, TLS1_3_VERSION, 1, 1, TLS1_VERSION, TLS1_3_VERSION}, {PROTO_TLS, TLS1_VERSION, TLS1_2_VERSION, 1, 1, TLS1_VERSION, TLS1_2_VERSION}, {PROTO_TLS, TLS1_2_VERSION, TLS1_2_VERSION, 1, 1, TLS1_2_VERSION, TLS1_2_VERSION}, {PROTO_TLS, TLS1_2_VERSION, TLS1_1_VERSION, 1, 1, TLS1_2_VERSION, TLS1_1_VERSION}, {PROTO_TLS, SSL3_VERSION - 1, TLS1_3_VERSION, 0, 1, 0, TLS1_3_VERSION}, {PROTO_TLS, SSL3_VERSION, TLS1_3_VERSION + 1, 1, 0, SSL3_VERSION, 0}, #ifndef OPENSSL_NO_DTLS {PROTO_TLS, DTLS1_VERSION, DTLS1_2_VERSION, 1, 1, 0, 0}, #endif {PROTO_TLS, OSSL_QUIC1_VERSION, OSSL_QUIC1_VERSION, 0, 0, 0, 0}, {PROTO_TLS, 7, 42, 0, 0, 0, 0}, {PROTO_DTLS, 0, 0, 1, 1, 0, 0}, {PROTO_DTLS, DTLS1_VERSION, DTLS1_2_VERSION, 1, 1, DTLS1_VERSION, DTLS1_2_VERSION}, #ifndef OPENSSL_NO_DTLS1_2 {PROTO_DTLS, DTLS1_2_VERSION, DTLS1_2_VERSION, 1, 1, DTLS1_2_VERSION, DTLS1_2_VERSION}, #endif #ifndef OPENSSL_NO_DTLS1 {PROTO_DTLS, DTLS1_VERSION, DTLS1_VERSION, 1, 1, DTLS1_VERSION, DTLS1_VERSION}, #endif #if !defined(OPENSSL_NO_DTLS1) && !defined(OPENSSL_NO_DTLS1_2) {PROTO_DTLS, DTLS1_2_VERSION, DTLS1_VERSION, 1, 1, DTLS1_2_VERSION, DTLS1_VERSION}, #endif {PROTO_DTLS, DTLS1_VERSION + 1, DTLS1_2_VERSION, 0, 1, 0, DTLS1_2_VERSION}, {PROTO_DTLS, DTLS1_VERSION, DTLS1_2_VERSION - 1, 1, 0, DTLS1_VERSION, 0}, {PROTO_DTLS, TLS1_VERSION, TLS1_3_VERSION, 1, 1, 0, 0}, {PROTO_DTLS, OSSL_QUIC1_VERSION, OSSL_QUIC1_VERSION, 0, 0, 0, 0}, /* These functions never have an effect when called on a QUIC object */ {PROTO_QUIC, 0, 0, 1, 1, 0, 0}, {PROTO_QUIC, OSSL_QUIC1_VERSION, OSSL_QUIC1_VERSION, 0, 0, 0, 0}, {PROTO_QUIC, OSSL_QUIC1_VERSION, OSSL_QUIC1_VERSION + 1, 0, 0, 0, 0}, {PROTO_QUIC, TLS1_VERSION, TLS1_3_VERSION, 1, 1, 0, 0}, #ifndef OPENSSL_NO_DTLS {PROTO_QUIC, DTLS1_VERSION, DTLS1_2_VERSION, 1, 1, 0, 0}, #endif }; static int test_set_min_max_version(int idx_tst) { SSL_CTX *ctx = NULL; SSL *ssl = NULL; int testresult = 0; version_test t = version_testdata[idx_tst]; const SSL_METHOD *meth = NULL; switch (t.proto) { case PROTO_TLS: meth = TLS_client_method(); break; #ifndef OPENSSL_NO_DTLS case PROTO_DTLS: meth = DTLS_client_method(); break; #endif #ifndef OPENSSL_NO_QUIC case PROTO_QUIC: meth = OSSL_QUIC_client_method(); break; #endif } if (meth == NULL) return TEST_skip("Protocol not supported"); ctx = SSL_CTX_new(meth); if (ctx == NULL) goto end; ssl = SSL_new(ctx); if (ssl == NULL) goto end; if (!TEST_int_eq(SSL_CTX_set_min_proto_version(ctx, t.min_version), t.min_ok)) goto end; if (!TEST_int_eq(SSL_CTX_set_max_proto_version(ctx, t.max_version), t.max_ok)) goto end; if (!TEST_int_eq(SSL_CTX_get_min_proto_version(ctx), t.expected_min)) goto end; if (!TEST_int_eq(SSL_CTX_get_max_proto_version(ctx), t.expected_max)) goto end; if (!TEST_int_eq(SSL_set_min_proto_version(ssl, t.min_version), t.min_ok)) goto end; if (!TEST_int_eq(SSL_set_max_proto_version(ssl, t.max_version), t.max_ok)) goto end; if (!TEST_int_eq(SSL_get_min_proto_version(ssl), t.expected_min)) goto end; if (!TEST_int_eq(SSL_get_max_proto_version(ssl), t.expected_max)) goto end; testresult = 1; end: SSL_free(ssl); SSL_CTX_free(ctx); return testresult; } int setup_tests(void) { ADD_ALL_TESTS(test_set_min_max_version, sizeof(version_testdata) / sizeof(version_test)); return 1; }
./openssl/test/http_test.c
/* * Copyright 2020-2021 The OpenSSL Project Authors. All Rights Reserved. * Copyright Siemens AG 2020 * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <openssl/http.h> #include <openssl/pem.h> #include <openssl/x509v3.h> #include <string.h> #include "testutil.h" static const ASN1_ITEM *x509_it = NULL; static X509 *x509 = NULL; #define RPATH "/path/result.crt" typedef struct { BIO *out; const char *content_type; const char *txt; char version; int keep_alive; } server_args; /*- * Pretty trivial HTTP mock server: * For POST, copy request headers+body from mem BIO |in| as response to |out|. * For GET, redirect to RPATH unless already there, else use |content_type| and * respond with |txt| if not NULL, else with |rsp| of ASN1 type |it|. * Response hdr has HTTP version 1.|version| and |keep_alive| (unless implicit). */ static int mock_http_server(BIO *in, BIO *out, char version, int keep_alive, const char *content_type, const char *txt, ASN1_VALUE *rsp, const ASN1_ITEM *it) { const char *req, *path; long count = BIO_get_mem_data(in, (unsigned char **)&req); const char *hdr = (char *)req; int len; int is_get = count >= 4 && CHECK_AND_SKIP_PREFIX(hdr, "GET "); /* first line should contain "(GET|POST) <path> HTTP/1.x" */ if (!is_get && !(TEST_true(count >= 5 && CHECK_AND_SKIP_PREFIX(hdr, "POST ")))) return 0; path = hdr; hdr = strchr(hdr, ' '); if (hdr == NULL) return 0; len = strlen("HTTP/1."); if (!TEST_strn_eq(++hdr, "HTTP/1.", len)) return 0; hdr += len; /* check for HTTP version 1.0 .. 1.1 */ if (!TEST_char_le('0', *hdr) || !TEST_char_le(*hdr++, '1')) return 0; if (!TEST_char_eq(*hdr++, '\r') || !TEST_char_eq(*hdr++, '\n')) return 0; count -= (hdr - req); if (count < 0 || out == NULL) return 0; if (!HAS_PREFIX(path, RPATH)) { if (!is_get) return 0; return BIO_printf(out, "HTTP/1.%c 301 Moved Permanently\r\n" "Location: %s\r\n\r\n", version, RPATH) > 0; /* same server */ } if (BIO_printf(out, "HTTP/1.%c 200 OK\r\n", version) <= 0) return 0; if ((version == '0') == keep_alive) /* otherwise, default */ if (BIO_printf(out, "Connection: %s\r\n", version == '0' ? "keep-alive" : "close") <= 0) return 0; if (is_get) { /* construct new header and body */ if (txt != NULL) len = strlen(txt); else if ((len = ASN1_item_i2d(rsp, NULL, it)) <= 0) return 0; if (BIO_printf(out, "Content-Type: %s\r\n" "Content-Length: %d\r\n\r\n", content_type, len) <= 0) return 0; if (txt != NULL) return BIO_puts(out, txt); return ASN1_item_i2d_bio(it, out, rsp); } else { if (CHECK_AND_SKIP_PREFIX(hdr, "Connection: ")) { /* skip req Connection header */ hdr = strstr(hdr, "\r\n"); if (hdr == NULL) return 0; hdr += 2; } /* echo remaining request header and body */ return BIO_write(out, hdr, count) == count; } } static long http_bio_cb_ex(BIO *bio, int oper, const char *argp, size_t len, int cmd, long argl, int ret, size_t *processed) { server_args *args = (server_args *)BIO_get_callback_arg(bio); if (oper == (BIO_CB_CTRL | BIO_CB_RETURN) && cmd == BIO_CTRL_FLUSH) ret = mock_http_server(bio, args->out, args->version, args->keep_alive, args->content_type, args->txt, (ASN1_VALUE *)x509, x509_it); return ret; } #define text1 "test\n" #define text2 "more\n" #define REAL_SERVER_URL "http://httpbin.org/" #define DOCTYPE_HTML "<!DOCTYPE html>\n" static int test_http_method(int do_get, int do_txt) { BIO *wbio = BIO_new(BIO_s_mem()); BIO *rbio = BIO_new(BIO_s_mem()); server_args mock_args = { NULL, NULL, NULL, '0', 0 }; BIO *req, *rsp; STACK_OF(CONF_VALUE) *headers = NULL; const char *content_type; int res = 0; int real_server = do_txt && 0; /* remove "&& 0" for using real server */ if (do_txt) { content_type = "text/plain"; req = BIO_new(BIO_s_mem()); if (req == NULL || BIO_puts(req, text1) != sizeof(text1) - 1 || BIO_puts(req, text2) != sizeof(text2) - 1) { BIO_free(req); req = NULL; } mock_args.txt = text1; } else { content_type = "application/x-x509-ca-cert"; req = ASN1_item_i2d_mem_bio(x509_it, (ASN1_VALUE *)x509); mock_args.txt = NULL; } if (wbio == NULL || rbio == NULL || req == NULL) goto err; mock_args.out = rbio; mock_args.content_type = content_type; BIO_set_callback_ex(wbio, http_bio_cb_ex); BIO_set_callback_arg(wbio, (char *)&mock_args); rsp = do_get ? OSSL_HTTP_get(real_server ? REAL_SERVER_URL : do_txt ? RPATH : "/will-be-redirected", NULL /* proxy */, NULL /* no_proxy */, real_server ? NULL : wbio, real_server ? NULL : rbio, NULL /* bio_update_fn */, NULL /* arg */, 0 /* buf_size */, headers, real_server ? "text/html; charset=utf-8": content_type, !do_txt /* expect_asn1 */, OSSL_HTTP_DEFAULT_MAX_RESP_LEN, 0 /* timeout */) : OSSL_HTTP_transfer(NULL, NULL /* host */, NULL /* port */, RPATH, 0 /* use_ssl */,NULL /* proxy */, NULL /* no_pr */, wbio, rbio, NULL /* bio_fn */, NULL /* arg */, 0 /* buf_size */, headers, content_type, req, content_type, !do_txt /* expect_asn1 */, OSSL_HTTP_DEFAULT_MAX_RESP_LEN, 0 /* timeout */, 0 /* keep_alive */); if (rsp != NULL) { if (do_get && real_server) { char rtext[sizeof(DOCTYPE_HTML)]; res = TEST_int_eq(BIO_gets(rsp, rtext, sizeof(rtext)), sizeof(DOCTYPE_HTML) - 1) && TEST_str_eq(rtext, DOCTYPE_HTML); } else if (do_txt) { char rtext[sizeof(text1) + 1 /* more space than needed */]; res = TEST_int_eq(BIO_gets(rsp, rtext, sizeof(rtext)), sizeof(text1) - 1) && TEST_str_eq(rtext, text1); } else { X509 *rcert = d2i_X509_bio(rsp, NULL); res = TEST_ptr(rcert) && TEST_int_eq(X509_cmp(x509, rcert), 0); X509_free(rcert); } BIO_free(rsp); } err: BIO_free(req); BIO_free(wbio); BIO_free(rbio); sk_CONF_VALUE_pop_free(headers, X509V3_conf_free); return res; } static int test_http_keep_alive(char version, int keep_alive, int kept_alive) { BIO *wbio = BIO_new(BIO_s_mem()); BIO *rbio = BIO_new(BIO_s_mem()); BIO *rsp; const char *const content_type = "application/x-x509-ca-cert"; server_args mock_args = { NULL, NULL, NULL, '0', 0 }; OSSL_HTTP_REQ_CTX *rctx = NULL; int i, res = 0; if (wbio == NULL || rbio == NULL) goto err; mock_args.out = rbio; mock_args.content_type = content_type; mock_args.version = version; mock_args.keep_alive = kept_alive; BIO_set_callback_ex(wbio, http_bio_cb_ex); BIO_set_callback_arg(wbio, (char *)&mock_args); for (res = 1, i = 1; res && i <= 2; i++) { rsp = OSSL_HTTP_transfer(&rctx, NULL /* server */, NULL /* port */, RPATH, 0 /* use_ssl */, NULL /* proxy */, NULL /* no_proxy */, wbio, rbio, NULL /* bio_update_fn */, NULL, 0 /* buf_size */, NULL /* headers */, NULL /* content_type */, NULL /* req => GET */, content_type, 0 /* ASN.1 not expected */, 0 /* max_resp_len */, 0 /* timeout */, keep_alive); if (keep_alive == 2 && kept_alive == 0) res = res && TEST_ptr_null(rsp) && TEST_int_eq(OSSL_HTTP_is_alive(rctx), 0); else res = res && TEST_ptr(rsp) && TEST_int_eq(OSSL_HTTP_is_alive(rctx), keep_alive > 0); BIO_free(rsp); (void)BIO_reset(rbio); /* discard response contents */ keep_alive = 0; } OSSL_HTTP_close(rctx, res); err: BIO_free(wbio); BIO_free(rbio); return res; } static int test_http_url_ok(const char *url, int exp_ssl, const char *exp_host, const char *exp_port, const char *exp_path) { char *user, *host, *port, *path, *query, *frag; int exp_num, num, ssl; int res; if (!TEST_int_eq(sscanf(exp_port, "%d", &exp_num), 1)) return 0; res = TEST_true(OSSL_HTTP_parse_url(url, &ssl, &user, &host, &port, &num, &path, &query, &frag)) && TEST_str_eq(host, exp_host) && TEST_str_eq(port, exp_port) && TEST_int_eq(num, exp_num) && TEST_str_eq(path, exp_path) && TEST_int_eq(ssl, exp_ssl); if (res && *user != '\0') res = TEST_str_eq(user, "user:pass"); if (res && *frag != '\0') res = TEST_str_eq(frag, "fr"); if (res && *query != '\0') res = TEST_str_eq(query, "q"); OPENSSL_free(user); OPENSSL_free(host); OPENSSL_free(port); OPENSSL_free(path); OPENSSL_free(query); OPENSSL_free(frag); return res; } static int test_http_url_path_query_ok(const char *url, const char *exp_path_qu) { char *host, *path; int res; res = TEST_true(OSSL_HTTP_parse_url(url, NULL, NULL, &host, NULL, NULL, &path, NULL, NULL)) && TEST_str_eq(host, "host") && TEST_str_eq(path, exp_path_qu); OPENSSL_free(host); OPENSSL_free(path); return res; } static int test_http_url_dns(void) { return test_http_url_ok("host:65535/path", 0, "host", "65535", "/path"); } static int test_http_url_path_query(void) { return test_http_url_path_query_ok("http://usr@host:1/p?q=x#frag", "/p?q=x") && test_http_url_path_query_ok("http://host?query#frag", "/?query") && test_http_url_path_query_ok("http://host:9999#frag", "/"); } static int test_http_url_userinfo_query_fragment(void) { return test_http_url_ok("user:pass@host/p?q#fr", 0, "host", "80", "/p"); } static int test_http_url_ipv4(void) { return test_http_url_ok("https://1.2.3.4/p/q", 1, "1.2.3.4", "443", "/p/q"); } static int test_http_url_ipv6(void) { return test_http_url_ok("http://[FF01::101]:6", 0, "[FF01::101]", "6", "/"); } static int test_http_url_invalid(const char *url) { char *host = "1", *port = "1", *path = "1"; int num = 1, ssl = 1; int res; res = TEST_false(OSSL_HTTP_parse_url(url, &ssl, NULL, &host, &port, &num, &path, NULL, NULL)) && TEST_ptr_null(host) && TEST_ptr_null(port) && TEST_ptr_null(path); if (!res) { OPENSSL_free(host); OPENSSL_free(port); OPENSSL_free(path); } return res; } static int test_http_url_invalid_prefix(void) { return test_http_url_invalid("htttps://1.2.3.4:65535/pkix"); } static int test_http_url_invalid_port(void) { return test_http_url_invalid("https://1.2.3.4:65536/pkix") && test_http_url_invalid("https://1.2.3.4:"); } static int test_http_url_invalid_path(void) { return test_http_url_invalid("https://[FF01::101]pkix"); } static int test_http_get_txt(void) { return test_http_method(1 /* GET */, 1); } static int test_http_post_txt(void) { return test_http_method(0 /* POST */, 1); } static int test_http_get_x509(void) { return test_http_method(1 /* GET */, 0); /* includes redirection */ } static int test_http_post_x509(void) { return test_http_method(0 /* POST */, 0); } static int test_http_keep_alive_0_no_no(void) { return test_http_keep_alive('0', 0, 0); } static int test_http_keep_alive_1_no_no(void) { return test_http_keep_alive('1', 0, 0); } static int test_http_keep_alive_0_prefer_yes(void) { return test_http_keep_alive('0', 1, 1); } static int test_http_keep_alive_1_prefer_yes(void) { return test_http_keep_alive('1', 1, 1); } static int test_http_keep_alive_0_require_yes(void) { return test_http_keep_alive('0', 2, 1); } static int test_http_keep_alive_1_require_yes(void) { return test_http_keep_alive('1', 2, 1); } static int test_http_keep_alive_0_require_no(void) { return test_http_keep_alive('0', 2, 0); } static int test_http_keep_alive_1_require_no(void) { return test_http_keep_alive('1', 2, 0); } void cleanup_tests(void) { X509_free(x509); } OPT_TEST_DECLARE_USAGE("cert.pem\n") int setup_tests(void) { if (!test_skip_common_options()) return 0; x509_it = ASN1_ITEM_rptr(X509); if (!TEST_ptr((x509 = load_cert_pem(test_get_argument(0), NULL)))) return 0; ADD_TEST(test_http_url_dns); ADD_TEST(test_http_url_path_query); ADD_TEST(test_http_url_userinfo_query_fragment); ADD_TEST(test_http_url_ipv4); ADD_TEST(test_http_url_ipv6); ADD_TEST(test_http_url_invalid_prefix); ADD_TEST(test_http_url_invalid_port); ADD_TEST(test_http_url_invalid_path); ADD_TEST(test_http_get_txt); ADD_TEST(test_http_post_txt); ADD_TEST(test_http_get_x509); ADD_TEST(test_http_post_x509); ADD_TEST(test_http_keep_alive_0_no_no); ADD_TEST(test_http_keep_alive_1_no_no); ADD_TEST(test_http_keep_alive_0_prefer_yes); ADD_TEST(test_http_keep_alive_1_prefer_yes); ADD_TEST(test_http_keep_alive_0_require_yes); ADD_TEST(test_http_keep_alive_1_require_yes); ADD_TEST(test_http_keep_alive_0_require_no); ADD_TEST(test_http_keep_alive_1_require_no); return 1; }
./openssl/test/membio_test.c
/* * Copyright 2022-2023 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <openssl/bio.h> #include "testutil.h" #ifndef OPENSSL_NO_DGRAM static int test_dgram(void) { BIO *bio = BIO_new(BIO_s_dgram_mem()), *rbio = NULL; int testresult = 0; const char msg1[] = "12345656"; const char msg2[] = "abcdefghijklmno"; const char msg3[] = "ABCDEF"; const char msg4[] = "FEDCBA"; char buf[80]; if (!TEST_ptr(bio)) goto err; rbio = BIO_new_mem_buf(msg1, sizeof(msg1)); if (!TEST_ptr(rbio)) goto err; /* Setting the EOF return value on a non datagram mem BIO should be fine */ if (!TEST_int_gt(BIO_set_mem_eof_return(rbio, 0), 0)) goto err; /* Setting the EOF return value on a datagram mem BIO should fail */ if (!TEST_int_le(BIO_set_mem_eof_return(bio, 0), 0)) goto err; /* Write 4 dgrams */ if (!TEST_int_eq(BIO_write(bio, msg1, sizeof(msg1)), sizeof(msg1))) goto err; if (!TEST_int_eq(BIO_write(bio, msg2, sizeof(msg2)), sizeof(msg2))) goto err; if (!TEST_int_eq(BIO_write(bio, msg3, sizeof(msg3)), sizeof(msg3))) goto err; if (!TEST_int_eq(BIO_write(bio, msg4, sizeof(msg4)), sizeof(msg4))) goto err; /* Reading all 4 dgrams out again should all be the correct size */ if (!TEST_int_eq(BIO_read(bio, buf, sizeof(buf)), sizeof(msg1)) || !TEST_mem_eq(buf, sizeof(msg1), msg1, sizeof(msg1)) || !TEST_int_eq(BIO_read(bio, buf, sizeof(buf)), sizeof(msg2)) || !TEST_mem_eq(buf, sizeof(msg2), msg2, sizeof(msg2)) || !TEST_int_eq(BIO_read(bio, buf, sizeof(buf)), sizeof(msg3)) || !TEST_mem_eq(buf, sizeof(msg3), msg3, sizeof(msg3)) || !TEST_int_eq(BIO_read(bio, buf, sizeof(buf)), sizeof(msg4)) || !TEST_mem_eq(buf, sizeof(msg4), msg4, sizeof(msg4))) goto err; /* Interleaving writes and reads should be fine */ if (!TEST_int_eq(BIO_write(bio, msg1, sizeof(msg1)), sizeof(msg1))) goto err; if (!TEST_int_eq(BIO_write(bio, msg2, sizeof(msg2)), sizeof(msg2))) goto err; if (!TEST_int_eq(BIO_read(bio, buf, sizeof(buf)), sizeof(msg1)) || !TEST_mem_eq(buf, sizeof(msg1), msg1, sizeof(msg1))) goto err; if (!TEST_int_eq(BIO_write(bio, msg3, sizeof(msg3)), sizeof(msg3))) goto err; if (!TEST_int_eq(BIO_read(bio, buf, sizeof(buf)), sizeof(msg2)) || !TEST_mem_eq(buf, sizeof(msg2), msg2, sizeof(msg2)) || !TEST_int_eq(BIO_read(bio, buf, sizeof(buf)), sizeof(msg3)) || !TEST_mem_eq(buf, sizeof(msg3), msg3, sizeof(msg3))) goto err; /* * Requesting less than the available data in a dgram should not impact the * next packet. */ if (!TEST_int_eq(BIO_write(bio, msg1, sizeof(msg1)), sizeof(msg1))) goto err; if (!TEST_int_eq(BIO_write(bio, msg2, sizeof(msg2)), sizeof(msg2))) goto err; if (!TEST_int_eq(BIO_read(bio, buf, /* Short buffer */ 2), 2) || !TEST_mem_eq(buf, 2, msg1, 2)) goto err; if (!TEST_int_eq(BIO_read(bio, buf, sizeof(buf)), sizeof(msg2)) || !TEST_mem_eq(buf, sizeof(msg2), msg2, sizeof(msg2))) goto err; /* * Writing a zero length datagram will return zero, but no datagrams will * be written. Attempting to read when there are no datagrams to read should * return a negative result, but not eof. Retry flags will be set. */ if (!TEST_int_eq(BIO_write(bio, NULL, 0), 0) || !TEST_int_lt(BIO_read(bio, buf, sizeof(buf)), 0) || !TEST_false(BIO_eof(bio)) || !TEST_true(BIO_should_retry(bio))) goto err; if (!TEST_int_eq(BIO_dgram_set_mtu(bio, 123456), 1) || !TEST_int_eq(BIO_dgram_get_mtu(bio), 123456)) goto err; testresult = 1; err: BIO_free(rbio); BIO_free(bio); return testresult; } #endif int setup_tests(void) { if (!test_skip_common_options()) { TEST_error("Error parsing test options\n"); return 0; } #ifndef OPENSSL_NO_DGRAM ADD_TEST(test_dgram); #endif return 1; }
./openssl/test/event_queue_test.c
/* * Copyright 2022 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include "internal/event_queue.h" #include "internal/nelem.h" #include "testutil.h" static OSSL_TIME cur_time = { 100 }; OSSL_TIME ossl_time_now(void) { return cur_time; } #define PAYLOAD(s) s, strlen(s) + 1 static int event_test(void) { int res = 0; size_t len = 0; OSSL_EVENT *e1, *e2, e3, *e4 = NULL, *ep = NULL; OSSL_EVENT_QUEUE *q = NULL; void *p; static char payload[] = "payload"; /* Create an event queue and add some events */ if (!TEST_ptr(q = ossl_event_queue_new()) || !TEST_ptr(e1 = ossl_event_queue_add_new(q, 1, 10, ossl_ticks2time(1100), "ctx 1", PAYLOAD(payload))) || !TEST_ptr(e2 = ossl_event_queue_add_new(q, 2, 5, ossl_ticks2time(1100), "ctx 2", PAYLOAD("data"))) || !TEST_true(ossl_event_queue_add(q, &e3, 3, 20, ossl_ticks2time(1200), "ctx 3", PAYLOAD("more data"))) || !TEST_ptr(e4 = ossl_event_queue_add_new(q, 2, 5, ossl_ticks2time(1150), "ctx 2", PAYLOAD("data"))) /* Verify some event details */ || !TEST_uint_eq(ossl_event_get_type(e1), 1) || !TEST_uint_eq(ossl_event_get_priority(e1), 10) || !TEST_uint64_t_eq(ossl_time2ticks(ossl_event_get_when(e1)) , 1100) || !TEST_str_eq(ossl_event_get0_ctx(e1), "ctx 1") || !TEST_ptr(p = ossl_event_get0_payload(e1, &len)) || !TEST_str_eq((char *)p, payload) || !TEST_uint64_t_eq(ossl_time2ticks(ossl_event_time_until(&e3)), 1100) || !TEST_uint64_t_eq(ossl_time2ticks(ossl_event_queue_time_until_next(q)), 1000) /* Modify an event's time */ || !TEST_true(ossl_event_queue_postpone_until(q, e1, ossl_ticks2time(1200))) || !TEST_uint64_t_eq(ossl_time2ticks(ossl_event_get_when(e1)), 1200) || !TEST_true(ossl_event_queue_remove(q, e4))) goto err; ossl_event_free(e4); /* Execute the queue */ cur_time = ossl_ticks2time(1000); if (!TEST_true(ossl_event_queue_get1_next_event(q, &ep)) || !TEST_ptr_null(ep)) goto err; cur_time = ossl_ticks2time(1100); if (!TEST_true(ossl_event_queue_get1_next_event(q, &ep)) || !TEST_ptr_eq(ep, e2)) goto err; ossl_event_free(ep); ep = e2 = NULL; if (!TEST_true(ossl_event_queue_get1_next_event(q, &ep)) || !TEST_ptr_null(ep)) goto err; cur_time = ossl_ticks2time(1250); if (!TEST_true(ossl_event_queue_get1_next_event(q, &ep)) || !TEST_ptr_eq(ep, &e3)) goto err; ossl_event_free(ep); ep = NULL; if (!TEST_true(ossl_event_queue_get1_next_event(q, &ep)) || !TEST_ptr_eq(ep, e1)) goto err; ossl_event_free(ep); ep = e1 = NULL; if (!TEST_true(ossl_event_queue_get1_next_event(q, &ep)) || !TEST_ptr_null(ep)) goto err; res = 1; err: ossl_event_free(ep); ossl_event_queue_free(q); return res; } int setup_tests(void) { ADD_TEST(event_test); return 1; }
./openssl/test/srptest.c
/* * Copyright 2011-2021 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ /* * SRP is deprecated, so we're going to have to use some deprecated APIs in * order to test it. */ #define OPENSSL_SUPPRESS_DEPRECATED #include <openssl/opensslconf.h> # include "testutil.h" #ifdef OPENSSL_NO_SRP # include <stdio.h> #else # include <openssl/srp.h> # include <openssl/rand.h> # include <openssl/err.h> # define RANDOM_SIZE 32 /* use 256 bits on each side */ static int run_srp(const char *username, const char *client_pass, const char *server_pass) { int ret = 0; BIGNUM *s = NULL; BIGNUM *v = NULL; BIGNUM *a = NULL; BIGNUM *b = NULL; BIGNUM *u = NULL; BIGNUM *x = NULL; BIGNUM *Apub = NULL; BIGNUM *Bpub = NULL; BIGNUM *Kclient = NULL; BIGNUM *Kserver = NULL; unsigned char rand_tmp[RANDOM_SIZE]; /* use builtin 1024-bit params */ const SRP_gN *GN; if (!TEST_ptr(GN = SRP_get_default_gN("1024"))) return 0; /* Set up server's password entry */ if (!TEST_true(SRP_create_verifier_BN(username, server_pass, &s, &v, GN->N, GN->g))) goto end; test_output_bignum("N", GN->N); test_output_bignum("g", GN->g); test_output_bignum("Salt", s); test_output_bignum("Verifier", v); /* Server random */ RAND_bytes(rand_tmp, sizeof(rand_tmp)); b = BN_bin2bn(rand_tmp, sizeof(rand_tmp), NULL); if (!TEST_BN_ne_zero(b)) goto end; test_output_bignum("b", b); /* Server's first message */ Bpub = SRP_Calc_B(b, GN->N, GN->g, v); test_output_bignum("B", Bpub); if (!TEST_true(SRP_Verify_B_mod_N(Bpub, GN->N))) goto end; /* Client random */ RAND_bytes(rand_tmp, sizeof(rand_tmp)); a = BN_bin2bn(rand_tmp, sizeof(rand_tmp), NULL); if (!TEST_BN_ne_zero(a)) goto end; test_output_bignum("a", a); /* Client's response */ Apub = SRP_Calc_A(a, GN->N, GN->g); test_output_bignum("A", Apub); if (!TEST_true(SRP_Verify_A_mod_N(Apub, GN->N))) goto end; /* Both sides calculate u */ u = SRP_Calc_u(Apub, Bpub, GN->N); /* Client's key */ x = SRP_Calc_x(s, username, client_pass); Kclient = SRP_Calc_client_key(GN->N, Bpub, GN->g, x, a, u); test_output_bignum("Client's key", Kclient); /* Server's key */ Kserver = SRP_Calc_server_key(Apub, v, u, b, GN->N); test_output_bignum("Server's key", Kserver); if (!TEST_BN_eq(Kclient, Kserver)) goto end; ret = 1; end: BN_clear_free(Kclient); BN_clear_free(Kserver); BN_clear_free(x); BN_free(u); BN_free(Apub); BN_clear_free(a); BN_free(Bpub); BN_clear_free(b); BN_free(s); BN_clear_free(v); return ret; } static int check_bn(const char *name, const BIGNUM *bn, const char *hexbn) { BIGNUM *tmp = NULL; int r; if (!TEST_true(BN_hex2bn(&tmp, hexbn))) return 0; if (BN_cmp(bn, tmp) != 0) TEST_error("unexpected %s value", name); r = TEST_BN_eq(bn, tmp); BN_free(tmp); return r; } /* SRP test vectors from RFC5054 */ static int run_srp_kat(void) { int ret = 0; BIGNUM *s = NULL; BIGNUM *v = NULL; BIGNUM *a = NULL; BIGNUM *b = NULL; BIGNUM *u = NULL; BIGNUM *x = NULL; BIGNUM *Apub = NULL; BIGNUM *Bpub = NULL; BIGNUM *Kclient = NULL; BIGNUM *Kserver = NULL; /* use builtin 1024-bit params */ const SRP_gN *GN; if (!TEST_ptr(GN = SRP_get_default_gN("1024"))) goto err; BN_hex2bn(&s, "BEB25379D1A8581EB5A727673A2441EE"); /* Set up server's password entry */ if (!TEST_true(SRP_create_verifier_BN("alice", "password123", &s, &v, GN->N, GN->g))) goto err; TEST_info("checking v"); if (!TEST_true(check_bn("v", v, "7E273DE8696FFC4F4E337D05B4B375BEB0DDE1569E8FA00A9886D812" "9BADA1F1822223CA1A605B530E379BA4729FDC59F105B4787E5186F5" "C671085A1447B52A48CF1970B4FB6F8400BBF4CEBFBB168152E08AB5" "EA53D15C1AFF87B2B9DA6E04E058AD51CC72BFC9033B564E26480D78" "E955A5E29E7AB245DB2BE315E2099AFB"))) goto err; TEST_note(" okay"); /* Server random */ BN_hex2bn(&b, "E487CB59D31AC550471E81F00F6928E01DDA08E974A004F49E61F5D1" "05284D20"); /* Server's first message */ Bpub = SRP_Calc_B(b, GN->N, GN->g, v); if (!TEST_true(SRP_Verify_B_mod_N(Bpub, GN->N))) goto err; TEST_info("checking B"); if (!TEST_true(check_bn("B", Bpub, "BD0C61512C692C0CB6D041FA01BB152D4916A1E77AF46AE105393011" "BAF38964DC46A0670DD125B95A981652236F99D9B681CBF87837EC99" "6C6DA04453728610D0C6DDB58B318885D7D82C7F8DEB75CE7BD4FBAA" "37089E6F9C6059F388838E7A00030B331EB76840910440B1B27AAEAE" "EB4012B7D7665238A8E3FB004B117B58"))) goto err; TEST_note(" okay"); /* Client random */ BN_hex2bn(&a, "60975527035CF2AD1989806F0407210BC81EDC04E2762A56AFD529DD" "DA2D4393"); /* Client's response */ Apub = SRP_Calc_A(a, GN->N, GN->g); if (!TEST_true(SRP_Verify_A_mod_N(Apub, GN->N))) goto err; TEST_info("checking A"); if (!TEST_true(check_bn("A", Apub, "61D5E490F6F1B79547B0704C436F523DD0E560F0C64115BB72557EC4" "4352E8903211C04692272D8B2D1A5358A2CF1B6E0BFCF99F921530EC" "8E39356179EAE45E42BA92AEACED825171E1E8B9AF6D9C03E1327F44" "BE087EF06530E69F66615261EEF54073CA11CF5858F0EDFDFE15EFEA" "B349EF5D76988A3672FAC47B0769447B"))) goto err; TEST_note(" okay"); /* Both sides calculate u */ u = SRP_Calc_u(Apub, Bpub, GN->N); if (!TEST_true(check_bn("u", u, "CE38B9593487DA98554ED47D70A7AE5F462EF019"))) goto err; /* Client's key */ x = SRP_Calc_x(s, "alice", "password123"); Kclient = SRP_Calc_client_key(GN->N, Bpub, GN->g, x, a, u); TEST_info("checking client's key"); if (!TEST_true(check_bn("Client's key", Kclient, "B0DC82BABCF30674AE450C0287745E7990A3381F63B387AAF271A10D" "233861E359B48220F7C4693C9AE12B0A6F67809F0876E2D013800D6C" "41BB59B6D5979B5C00A172B4A2A5903A0BDCAF8A709585EB2AFAFA8F" "3499B200210DCC1F10EB33943CD67FC88A2F39A4BE5BEC4EC0A3212D" "C346D7E474B29EDE8A469FFECA686E5A"))) goto err; TEST_note(" okay"); /* Server's key */ Kserver = SRP_Calc_server_key(Apub, v, u, b, GN->N); TEST_info("checking server's key"); if (!TEST_true(check_bn("Server's key", Kserver, "B0DC82BABCF30674AE450C0287745E7990A3381F63B387AAF271A10D" "233861E359B48220F7C4693C9AE12B0A6F67809F0876E2D013800D6C" "41BB59B6D5979B5C00A172B4A2A5903A0BDCAF8A709585EB2AFAFA8F" "3499B200210DCC1F10EB33943CD67FC88A2F39A4BE5BEC4EC0A3212D" "C346D7E474B29EDE8A469FFECA686E5A"))) goto err; TEST_note(" okay"); ret = 1; err: BN_clear_free(Kclient); BN_clear_free(Kserver); BN_clear_free(x); BN_free(u); BN_free(Apub); BN_clear_free(a); BN_free(Bpub); BN_clear_free(b); BN_free(s); BN_clear_free(v); return ret; } static int run_srp_tests(void) { /* "Negative" test, expect a mismatch */ TEST_info("run_srp: expecting a mismatch"); if (!TEST_false(run_srp("alice", "password1", "password2"))) return 0; /* "Positive" test, should pass */ TEST_info("run_srp: expecting a match"); if (!TEST_true(run_srp("alice", "password", "password"))) return 0; return 1; } #endif int setup_tests(void) { #ifdef OPENSSL_NO_SRP printf("No SRP support\n"); #else ADD_TEST(run_srp_tests); ADD_TEST(run_srp_kat); #endif return 1; }
./openssl/test/p_test.c
/* * Copyright 2019-2023 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ /* * This is a very simple provider that does absolutely nothing except respond * to provider global parameter requests. It does this by simply echoing back * a parameter request it makes to the loading library. */ #include <string.h> #include <stdio.h> /* * When built as an object file to link the application with, we get the * init function name through the macro PROVIDER_INIT_FUNCTION_NAME. If * not defined, we use the standard init function name for the shared * object form. */ #ifdef PROVIDER_INIT_FUNCTION_NAME # define OSSL_provider_init PROVIDER_INIT_FUNCTION_NAME #endif #include "internal/e_os.h" #include <openssl/core.h> #include <openssl/core_dispatch.h> #include <openssl/err.h> #include <openssl/evp.h> #include <openssl/crypto.h> #include <openssl/provider.h> typedef struct p_test_ctx { char *thisfile; char *thisfunc; const OSSL_CORE_HANDLE *handle; OSSL_LIB_CTX *libctx; } P_TEST_CTX; static OSSL_FUNC_core_gettable_params_fn *c_gettable_params = NULL; static OSSL_FUNC_core_get_params_fn *c_get_params = NULL; static OSSL_FUNC_core_new_error_fn *c_new_error; static OSSL_FUNC_core_set_error_debug_fn *c_set_error_debug; static OSSL_FUNC_core_vset_error_fn *c_vset_error; /* Tell the core what params we provide and what type they are */ static const OSSL_PARAM p_param_types[] = { { "greeting", OSSL_PARAM_UTF8_STRING, NULL, 0, 0 }, { "digest-check", OSSL_PARAM_UNSIGNED_INTEGER, NULL, 0, 0}, { NULL, 0, NULL, 0, 0 } }; /* This is a trick to ensure we define the provider functions correctly */ static OSSL_FUNC_provider_gettable_params_fn p_gettable_params; static OSSL_FUNC_provider_get_params_fn p_get_params; static OSSL_FUNC_provider_get_reason_strings_fn p_get_reason_strings; static OSSL_FUNC_provider_teardown_fn p_teardown; static void p_set_error(int lib, int reason, const char *file, int line, const char *func, const char *fmt, ...) { va_list ap; va_start(ap, fmt); c_new_error(NULL); c_set_error_debug(NULL, file, line, func); c_vset_error(NULL, ERR_PACK(lib, 0, reason), fmt, ap); va_end(ap); } static const OSSL_PARAM *p_gettable_params(void *_) { return p_param_types; } static int p_get_params(void *provctx, OSSL_PARAM params[]) { P_TEST_CTX *ctx = (P_TEST_CTX *)provctx; const OSSL_CORE_HANDLE *hand = ctx->handle; OSSL_PARAM *p = params; int ok = 1; for (; ok && p->key != NULL; p++) { if (strcmp(p->key, "greeting") == 0) { static char *opensslv; static char *provname; static char *greeting; static OSSL_PARAM counter_request[] = { /* Known libcrypto provided parameters */ { "openssl-version", OSSL_PARAM_UTF8_PTR, &opensslv, sizeof(&opensslv), 0 }, { "provider-name", OSSL_PARAM_UTF8_PTR, &provname, sizeof(&provname), 0}, /* This might be present, if there's such a configuration */ { "greeting", OSSL_PARAM_UTF8_PTR, &greeting, sizeof(&greeting), 0 }, { NULL, 0, NULL, 0, 0 } }; char buf[256]; size_t buf_l; opensslv = provname = greeting = NULL; if (c_get_params(hand, counter_request)) { if (greeting) { strcpy(buf, greeting); } else { const char *versionp = *(void **)counter_request[0].data; const char *namep = *(void **)counter_request[1].data; sprintf(buf, "Hello OpenSSL %.20s, greetings from %s!", versionp, namep); } } else { sprintf(buf, "Howdy stranger..."); } p->return_size = buf_l = strlen(buf) + 1; if (p->data_size >= buf_l) strcpy(p->data, buf); else ok = 0; } else if (strcmp(p->key, "digest-check") == 0) { unsigned int digestsuccess = 0; /* * Test we can use an algorithm from another provider. We're using * legacy to check that legacy is actually available and we haven't * just fallen back to default. */ #ifdef PROVIDER_INIT_FUNCTION_NAME EVP_MD *md4 = EVP_MD_fetch(ctx->libctx, "MD4", NULL); EVP_MD_CTX *mdctx = EVP_MD_CTX_new(); const char *msg = "Hello world"; unsigned char out[16]; OSSL_PROVIDER *deflt; /* * "default" has not been loaded into the parent libctx. We should be able * to explicitly load it as a non-child provider. */ deflt = OSSL_PROVIDER_load(ctx->libctx, "default"); if (deflt == NULL || !OSSL_PROVIDER_available(ctx->libctx, "default")) { /* We set error "3" for a failure to load the default provider */ p_set_error(ERR_LIB_PROV, 3, ctx->thisfile, OPENSSL_LINE, ctx->thisfunc, NULL); ok = 0; } /* * We should have the default provider available that we loaded * ourselves, and the base and legacy providers which we inherit * from the parent libctx. We should also have "this" provider * available. */ if (ok && OSSL_PROVIDER_available(ctx->libctx, "default") && OSSL_PROVIDER_available(ctx->libctx, "base") && OSSL_PROVIDER_available(ctx->libctx, "legacy") && OSSL_PROVIDER_available(ctx->libctx, "p_test") && md4 != NULL && mdctx != NULL) { if (EVP_DigestInit_ex(mdctx, md4, NULL) && EVP_DigestUpdate(mdctx, (const unsigned char *)msg, strlen(msg)) && EVP_DigestFinal(mdctx, out, NULL)) digestsuccess = 1; } EVP_MD_CTX_free(mdctx); EVP_MD_free(md4); OSSL_PROVIDER_unload(deflt); #endif if (p->data_size >= sizeof(digestsuccess)) { *(unsigned int *)p->data = digestsuccess; p->return_size = sizeof(digestsuccess); } else { ok = 0; } } else if (strcmp(p->key, "stop-property-mirror") == 0) { /* * Setting the default properties explicitly should stop mirroring * of properties from the parent libctx. */ unsigned int stopsuccess = 0; #ifdef PROVIDER_INIT_FUNCTION_NAME stopsuccess = EVP_set_default_properties(ctx->libctx, NULL); #endif if (p->data_size >= sizeof(stopsuccess)) { *(unsigned int *)p->data = stopsuccess; p->return_size = sizeof(stopsuccess); } else { ok = 0; } } } return ok; } static const OSSL_ITEM *p_get_reason_strings(void *_) { static const OSSL_ITEM reason_strings[] = { {1, "dummy reason string"}, {2, "Can't create child library context"}, {3, "Can't load default provider"}, {0, NULL} }; return reason_strings; } static const OSSL_DISPATCH p_test_table[] = { { OSSL_FUNC_PROVIDER_GETTABLE_PARAMS, (void (*)(void))p_gettable_params }, { OSSL_FUNC_PROVIDER_GET_PARAMS, (void (*)(void))p_get_params }, { OSSL_FUNC_PROVIDER_GET_REASON_STRINGS, (void (*)(void))p_get_reason_strings}, { OSSL_FUNC_PROVIDER_TEARDOWN, (void (*)(void))p_teardown }, OSSL_DISPATCH_END }; int OSSL_provider_init(const OSSL_CORE_HANDLE *handle, const OSSL_DISPATCH *oin, const OSSL_DISPATCH **out, void **provctx) { P_TEST_CTX *ctx; const OSSL_DISPATCH *in = oin; for (; in->function_id != 0; in++) { switch (in->function_id) { case OSSL_FUNC_CORE_GETTABLE_PARAMS: c_gettable_params = OSSL_FUNC_core_gettable_params(in); break; case OSSL_FUNC_CORE_GET_PARAMS: c_get_params = OSSL_FUNC_core_get_params(in); break; case OSSL_FUNC_CORE_NEW_ERROR: c_new_error = OSSL_FUNC_core_new_error(in); break; case OSSL_FUNC_CORE_SET_ERROR_DEBUG: c_set_error_debug = OSSL_FUNC_core_set_error_debug(in); break; case OSSL_FUNC_CORE_VSET_ERROR: c_vset_error = OSSL_FUNC_core_vset_error(in); break; default: /* Just ignore anything we don't understand */ break; } } /* * We want to test that libcrypto doesn't use the file and func pointers * that we provide to it via c_set_error_debug beyond the time that they * are valid for. Therefore we dynamically allocate these strings now and * free them again when the provider is torn down. If anything tries to * use those strings after that point there will be a use-after-free and * asan will complain (and hence the tests will fail). * This file isn't linked against libcrypto, so we use malloc and strdup * instead of OPENSSL_malloc and OPENSSL_strdup */ ctx = malloc(sizeof(*ctx)); if (ctx == NULL) return 0; ctx->thisfile = strdup(OPENSSL_FILE); ctx->thisfunc = strdup(OPENSSL_FUNC); ctx->handle = handle; #ifdef PROVIDER_INIT_FUNCTION_NAME /* We only do this if we are linked with libcrypto */ ctx->libctx = OSSL_LIB_CTX_new_child(handle, oin); if (ctx->libctx == NULL) { /* We set error "2" for a failure to create the child libctx*/ p_set_error(ERR_LIB_PROV, 2, ctx->thisfile, OPENSSL_LINE, ctx->thisfunc, NULL); p_teardown(ctx); return 0; } /* * The default provider is loaded - but the default properties should not * allow its use. */ { EVP_MD *sha256 = EVP_MD_fetch(ctx->libctx, "SHA2-256", NULL); if (sha256 != NULL) { EVP_MD_free(sha256); p_teardown(ctx); return 0; } } #endif /* * Set a spurious error to check error handling works correctly. This will * be ignored */ p_set_error(ERR_LIB_PROV, 1, ctx->thisfile, OPENSSL_LINE, ctx->thisfunc, NULL); *provctx = (void *)ctx; *out = p_test_table; return 1; } static void p_teardown(void *provctx) { P_TEST_CTX *ctx = (P_TEST_CTX *)provctx; #ifdef PROVIDER_INIT_FUNCTION_NAME OSSL_LIB_CTX_free(ctx->libctx); #endif free(ctx->thisfile); free(ctx->thisfunc); free(ctx); }
./openssl/test/memleaktest.c
/* * Copyright 2016-2021 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <string.h> #include <openssl/bio.h> #include <openssl/crypto.h> #include "testutil.h" /* __has_feature is a clang-ism, while __SANITIZE_ADDRESS__ is a gcc-ism */ #if defined(__has_feature) # if __has_feature(address_sanitizer) # define __SANITIZE_ADDRESS__ 1 # endif #endif /* If __SANITIZE_ADDRESS__ isn't defined, define it to be false */ /* Leak detection is not yet supported with MSVC on Windows, so */ /* set __SANITIZE_ADDRESS__ to false in this case as well. */ #if !defined(__SANITIZE_ADDRESS__) || defined(_MSC_VER) # undef __SANITIZE_ADDRESS__ # define __SANITIZE_ADDRESS__ 0 #endif /* * We use a proper main function here instead of the custom main from the * test framework to avoid CRYPTO_mem_leaks stuff. */ int main(int argc, char *argv[]) { #if __SANITIZE_ADDRESS__ int exitcode = EXIT_SUCCESS; #else /* * When we don't sanitize, we set the exit code to what we would expect * to get when we are sanitizing. This makes it easy for wrapper scripts * to detect that we get the result we expect. */ int exitcode = EXIT_FAILURE; #endif char *lost; lost = OPENSSL_malloc(3); if (!TEST_ptr(lost)) return EXIT_FAILURE; strcpy(lost, "ab"); if (argv[1] && strcmp(argv[1], "freeit") == 0) { OPENSSL_free(lost); exitcode = EXIT_SUCCESS; } lost = NULL; return exitcode; }
./openssl/test/sha_test.c
/* * Copyright 2021 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <string.h> #include <openssl/sha.h> #include "testutil.h" static int test_static_sha_common(const char *input, size_t length, const unsigned char *out, unsigned char *(*md)(const unsigned char *d, size_t n, unsigned char *md)) { unsigned char buf[EVP_MAX_MD_SIZE], *sbuf; const unsigned char *in = (unsigned char *)input; const size_t in_len = strlen(input); sbuf = (*md)(in, in_len, buf); if (!TEST_ptr(sbuf) || !TEST_ptr_eq(sbuf, buf) || !TEST_mem_eq(sbuf, length, out, length)) return 0; sbuf = (*md)(in, in_len, NULL); if (!TEST_ptr(sbuf) || !TEST_ptr_ne(sbuf, buf) || !TEST_mem_eq(sbuf, length, out, length)) return 0; return 1; } static int test_static_sha1(void) { static const unsigned char output[SHA_DIGEST_LENGTH] = { 0xa9, 0x99, 0x3e, 0x36, 0x47, 0x06, 0x81, 0x6a, 0xba, 0x3e, 0x25, 0x71, 0x78, 0x50, 0xc2, 0x6c, 0x9c, 0xd0, 0xd8, 0x9d }; return test_static_sha_common("abc", SHA_DIGEST_LENGTH, output, &SHA1); } static int test_static_sha224(void) { static const unsigned char output[SHA224_DIGEST_LENGTH] = { 0x23, 0x09, 0x7d, 0x22, 0x34, 0x05, 0xd8, 0x22, 0x86, 0x42, 0xa4, 0x77, 0xbd, 0xa2, 0x55, 0xb3, 0x2a, 0xad, 0xbc, 0xe4, 0xbd, 0xa0, 0xb3, 0xf7, 0xe3, 0x6c, 0x9d, 0xa7 }; return test_static_sha_common("abc", SHA224_DIGEST_LENGTH, output, &SHA224); } static int test_static_sha256(void) { static const unsigned char output[SHA256_DIGEST_LENGTH] = { 0xba, 0x78, 0x16, 0xbf, 0x8f, 0x01, 0xcf, 0xea, 0x41, 0x41, 0x40, 0xde, 0x5d, 0xae, 0x22, 0x23, 0xb0, 0x03, 0x61, 0xa3, 0x96, 0x17, 0x7a, 0x9c, 0xb4, 0x10, 0xff, 0x61, 0xf2, 0x00, 0x15, 0xad }; return test_static_sha_common("abc", SHA256_DIGEST_LENGTH, output, &SHA256); } static int test_static_sha384(void) { static const unsigned char output[SHA384_DIGEST_LENGTH] = { 0xcb, 0x00, 0x75, 0x3f, 0x45, 0xa3, 0x5e, 0x8b, 0xb5, 0xa0, 0x3d, 0x69, 0x9a, 0xc6, 0x50, 0x07, 0x27, 0x2c, 0x32, 0xab, 0x0e, 0xde, 0xd1, 0x63, 0x1a, 0x8b, 0x60, 0x5a, 0x43, 0xff, 0x5b, 0xed, 0x80, 0x86, 0x07, 0x2b, 0xa1, 0xe7, 0xcc, 0x23, 0x58, 0xba, 0xec, 0xa1, 0x34, 0xc8, 0x25, 0xa7 }; return test_static_sha_common("abc", SHA384_DIGEST_LENGTH, output, &SHA384); } static int test_static_sha512(void) { static const unsigned char output[SHA512_DIGEST_LENGTH] = { 0xdd, 0xaf, 0x35, 0xa1, 0x93, 0x61, 0x7a, 0xba, 0xcc, 0x41, 0x73, 0x49, 0xae, 0x20, 0x41, 0x31, 0x12, 0xe6, 0xfa, 0x4e, 0x89, 0xa9, 0x7e, 0xa2, 0x0a, 0x9e, 0xee, 0xe6, 0x4b, 0x55, 0xd3, 0x9a, 0x21, 0x92, 0x99, 0x2a, 0x27, 0x4f, 0xc1, 0xa8, 0x36, 0xba, 0x3c, 0x23, 0xa3, 0xfe, 0xeb, 0xbd, 0x45, 0x4d, 0x44, 0x23, 0x64, 0x3c, 0xe8, 0x0e, 0x2a, 0x9a, 0xc9, 0x4f, 0xa5, 0x4c, 0xa4, 0x9f }; return test_static_sha_common("abc", SHA512_DIGEST_LENGTH, output, &SHA512); } int setup_tests(void) { ADD_TEST(test_static_sha1); ADD_TEST(test_static_sha224); ADD_TEST(test_static_sha256); ADD_TEST(test_static_sha384); ADD_TEST(test_static_sha512); return 1; }
./openssl/test/cmp_asn_test.c
/* * Copyright 2007-2023 The OpenSSL Project Authors. All Rights Reserved. * Copyright Nokia 2007-2019 * Copyright Siemens AG 2015-2019 * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include "helpers/cmp_testlib.h" static unsigned char rand_data[OSSL_CMP_TRANSACTIONID_LENGTH]; typedef struct test_fixture { const char *test_case_name; int expected; ASN1_OCTET_STRING *src_string; ASN1_OCTET_STRING *tgt_string; } CMP_ASN_TEST_FIXTURE; static CMP_ASN_TEST_FIXTURE *set_up(const char *const test_case_name) { CMP_ASN_TEST_FIXTURE *fixture; if (!TEST_ptr(fixture = OPENSSL_zalloc(sizeof(*fixture)))) return NULL; fixture->test_case_name = test_case_name; return fixture; } static void tear_down(CMP_ASN_TEST_FIXTURE *fixture) { ASN1_OCTET_STRING_free(fixture->src_string); if (fixture->tgt_string != fixture->src_string) ASN1_OCTET_STRING_free(fixture->tgt_string); OPENSSL_free(fixture); } static int execute_cmp_asn1_get_int_test(CMP_ASN_TEST_FIXTURE *fixture) { int res = 0; ASN1_INTEGER *asn1integer = ASN1_INTEGER_new(); const int good_int = 77; const int64_t max_int = INT_MAX; if (!TEST_ptr(asn1integer)) return res; if (!TEST_true(ASN1_INTEGER_set(asn1integer, good_int))) { ASN1_INTEGER_free(asn1integer); return 0; } res = TEST_int_eq(good_int, ossl_cmp_asn1_get_int(asn1integer)); if (res == 0) goto err; res = 0; if (!TEST_true(ASN1_INTEGER_set_int64(asn1integer, max_int + 1))) goto err; res = TEST_int_eq(-2, ossl_cmp_asn1_get_int(asn1integer)); err: ASN1_INTEGER_free(asn1integer); return res; } static int test_cmp_asn1_get_int(void) { SETUP_TEST_FIXTURE(CMP_ASN_TEST_FIXTURE, set_up); fixture->expected = 1; EXECUTE_TEST(execute_cmp_asn1_get_int_test, tear_down); return result; } static int execute_CMP_ASN1_OCTET_STRING_set1_test(CMP_ASN_TEST_FIXTURE * fixture) { if (!TEST_int_eq(fixture->expected, ossl_cmp_asn1_octet_string_set1(&fixture->tgt_string, fixture->src_string))) return 0; if (fixture->expected != 0) return TEST_int_eq(0, ASN1_OCTET_STRING_cmp(fixture->tgt_string, fixture->src_string)); return 1; } static int test_ASN1_OCTET_STRING_set(void) { SETUP_TEST_FIXTURE(CMP_ASN_TEST_FIXTURE, set_up); fixture->expected = 1; if (!TEST_ptr(fixture->tgt_string = ASN1_OCTET_STRING_new()) || !TEST_ptr(fixture->src_string = ASN1_OCTET_STRING_new()) || !TEST_true(ASN1_OCTET_STRING_set(fixture->src_string, rand_data, sizeof(rand_data)))) { tear_down(fixture); fixture = NULL; } EXECUTE_TEST(execute_CMP_ASN1_OCTET_STRING_set1_test, tear_down); return result; } static int test_ASN1_OCTET_STRING_set_tgt_is_src(void) { SETUP_TEST_FIXTURE(CMP_ASN_TEST_FIXTURE, set_up); fixture->expected = 1; if (!TEST_ptr(fixture->src_string = ASN1_OCTET_STRING_new()) || !(fixture->tgt_string = fixture->src_string) || !TEST_true(ASN1_OCTET_STRING_set(fixture->src_string, rand_data, sizeof(rand_data)))) { tear_down(fixture); fixture = NULL; } EXECUTE_TEST(execute_CMP_ASN1_OCTET_STRING_set1_test, tear_down); return result; } void cleanup_tests(void) { return; } int setup_tests(void) { RAND_bytes(rand_data, OSSL_CMP_TRANSACTIONID_LENGTH); /* ASN.1 related tests */ ADD_TEST(test_cmp_asn1_get_int); ADD_TEST(test_ASN1_OCTET_STRING_set); ADD_TEST(test_ASN1_OCTET_STRING_set_tgt_is_src); return 1; }
./openssl/test/threadpool_test.c
/* * Copyright 2022 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <string.h> #include <internal/cryptlib.h> #include <internal/thread_arch.h> #include <internal/thread.h> #include <openssl/thread.h> #include "testutil.h" static int test_thread_reported_flags(void) { uint32_t flags = OSSL_get_thread_support_flags(); #if !defined(OPENSSL_THREADS) if (!TEST_int_eq(flags, 0)) return 0; #endif #if defined(OPENSSL_NO_THREAD_POOL) if (!TEST_int_eq(flags & OSSL_THREAD_SUPPORT_FLAG_THREAD_POOL, 0)) return 0; #else if (!TEST_int_eq(flags & OSSL_THREAD_SUPPORT_FLAG_THREAD_POOL, OSSL_THREAD_SUPPORT_FLAG_THREAD_POOL)) return 0; #endif #if defined(OPENSSL_NO_DEFAULT_THREAD_POOL) if (!TEST_int_eq(flags & OSSL_THREAD_SUPPORT_FLAG_DEFAULT_SPAWN, 0)) return 0; #else if (!TEST_int_eq(flags & OSSL_THREAD_SUPPORT_FLAG_DEFAULT_SPAWN, OSSL_THREAD_SUPPORT_FLAG_DEFAULT_SPAWN)) return 0; #endif return 1; } #ifndef OPENSSL_NO_THREAD_POOL # define TEST_THREAD_NATIVE_FN_SET_VALUE 1 static uint32_t test_thread_native_fn(void *data) { uint32_t *ldata = (uint32_t*) data; *ldata = *ldata + 1; return *ldata - 1; } /* Tests of native threads */ static int test_thread_native(void) { uint32_t retval; uint32_t local; CRYPTO_THREAD *t; /* thread spawn, join */ local = 1; t = ossl_crypto_thread_native_start(test_thread_native_fn, &local, 1); if (!TEST_ptr(t)) return 0; /* * pthread_join results in undefined behaviour if called on a joined * thread. We do not impose such restrictions, so it's up to us to * ensure that this does not happen (thread sanitizer will warn us * if we do). */ if (!TEST_int_eq(ossl_crypto_thread_native_join(t, &retval), 1)) return 0; if (!TEST_int_eq(ossl_crypto_thread_native_join(t, &retval), 1)) return 0; if (!TEST_int_eq(retval, 1) || !TEST_int_eq(local, 2)) return 0; if (!TEST_int_eq(ossl_crypto_thread_native_clean(t), 1)) return 0; t = NULL; if (!TEST_int_eq(ossl_crypto_thread_native_clean(t), 0)) return 0; return 1; } # if !defined(OPENSSL_NO_DEFAULT_THREAD_POOL) static int test_thread_internal(void) { uint32_t retval[3]; uint32_t local[3] = { 0 }; uint32_t threads_supported; size_t i; void *t[3]; OSSL_LIB_CTX *cust_ctx = OSSL_LIB_CTX_new(); threads_supported = OSSL_get_thread_support_flags(); threads_supported &= OSSL_THREAD_SUPPORT_FLAG_DEFAULT_SPAWN; if (threads_supported == 0) { if (!TEST_uint64_t_eq(OSSL_get_max_threads(NULL), 0)) return 0; if (!TEST_uint64_t_eq(OSSL_get_max_threads(cust_ctx), 0)) return 0; if (!TEST_int_eq(OSSL_set_max_threads(NULL, 1), 0)) return 0; if (!TEST_int_eq(OSSL_set_max_threads(cust_ctx, 1), 0)) return 0; if (!TEST_uint64_t_eq(OSSL_get_max_threads(NULL), 0)) return 0; if (!TEST_uint64_t_eq(OSSL_get_max_threads(cust_ctx), 0)) return 0; t[0] = ossl_crypto_thread_start(NULL, test_thread_native_fn, &local[0]); if (!TEST_ptr_null(t[0])) return 0; return 1; } /* fail when not allowed to use threads */ if (!TEST_uint64_t_eq(OSSL_get_max_threads(NULL), 0)) return 0; t[0] = ossl_crypto_thread_start(NULL, test_thread_native_fn, &local[0]); if (!TEST_ptr_null(t[0])) return 0; /* fail when enabled on a different context */ if (!TEST_uint64_t_eq(OSSL_get_max_threads(cust_ctx), 0)) return 0; if (!TEST_int_eq(OSSL_set_max_threads(cust_ctx, 1), 1)) return 0; if (!TEST_uint64_t_eq(OSSL_get_max_threads(NULL), 0)) return 0; if (!TEST_uint64_t_eq(OSSL_get_max_threads(cust_ctx), 1)) return 0; t[0] = ossl_crypto_thread_start(NULL, test_thread_native_fn, &local[0]); if (!TEST_ptr_null(t[0])) return 0; if (!TEST_int_eq(OSSL_set_max_threads(cust_ctx, 0), 1)) return 0; /* sequential startup */ if (!TEST_int_eq(OSSL_set_max_threads(NULL, 1), 1)) return 0; if (!TEST_uint64_t_eq(OSSL_get_max_threads(NULL), 1)) return 0; if (!TEST_uint64_t_eq(OSSL_get_max_threads(cust_ctx), 0)) return 0; for (i = 0; i < OSSL_NELEM(t); ++i) { local[0] = i + 1; t[i] = ossl_crypto_thread_start(NULL, test_thread_native_fn, &local[0]); if (!TEST_ptr(t[i])) return 0; /* * pthread_join results in undefined behaviour if called on a joined * thread. We do not impose such restrictions, so it's up to us to * ensure that this does not happen (thread sanitizer will warn us * if we do). */ if (!TEST_int_eq(ossl_crypto_thread_join(t[i], &retval[0]), 1)) return 0; if (!TEST_int_eq(ossl_crypto_thread_join(t[i], &retval[0]), 1)) return 0; if (!TEST_int_eq(retval[0], i + 1) || !TEST_int_eq(local[0], i + 2)) return 0; if (!TEST_int_eq(ossl_crypto_thread_clean(t[i]), 1)) return 0; t[i] = NULL; if (!TEST_int_eq(ossl_crypto_thread_clean(t[i]), 0)) return 0; } /* parallel startup */ if (!TEST_int_eq(OSSL_set_max_threads(NULL, OSSL_NELEM(t)), 1)) return 0; for (i = 0; i < OSSL_NELEM(t); ++i) { local[i] = i + 1; t[i] = ossl_crypto_thread_start(NULL, test_thread_native_fn, &local[i]); if (!TEST_ptr(t[i])) return 0; } for (i = 0; i < OSSL_NELEM(t); ++i) { if (!TEST_int_eq(ossl_crypto_thread_join(t[i], &retval[i]), 1)) return 0; } for (i = 0; i < OSSL_NELEM(t); ++i) { if (!TEST_int_eq(retval[i], i + 1) || !TEST_int_eq(local[i], i + 2)) return 0; if (!TEST_int_eq(ossl_crypto_thread_clean(t[i]), 1)) return 0; } /* parallel startup, bottleneck */ if (!TEST_int_eq(OSSL_set_max_threads(NULL, OSSL_NELEM(t) - 1), 1)) return 0; for (i = 0; i < OSSL_NELEM(t); ++i) { local[i] = i + 1; t[i] = ossl_crypto_thread_start(NULL, test_thread_native_fn, &local[i]); if (!TEST_ptr(t[i])) return 0; } for (i = 0; i < OSSL_NELEM(t); ++i) { if (!TEST_int_eq(ossl_crypto_thread_join(t[i], &retval[i]), 1)) return 0; } for (i = 0; i < OSSL_NELEM(t); ++i) { if (!TEST_int_eq(retval[i], i + 1) || !TEST_int_eq(local[i], i + 2)) return 0; if (!TEST_int_eq(ossl_crypto_thread_clean(t[i]), 1)) return 0; } if (!TEST_int_eq(OSSL_set_max_threads(NULL, 0), 1)) return 0; OSSL_LIB_CTX_free(cust_ctx); return 1; } # endif static uint32_t test_thread_native_multiple_joins_fn1(void *data) { return 0; } static uint32_t test_thread_native_multiple_joins_fn2(void *data) { ossl_crypto_thread_native_join((CRYPTO_THREAD *)data, NULL); return 0; } static uint32_t test_thread_native_multiple_joins_fn3(void *data) { ossl_crypto_thread_native_join((CRYPTO_THREAD *)data, NULL); return 0; } static int test_thread_native_multiple_joins(void) { CRYPTO_THREAD *t, *t1, *t2; t = ossl_crypto_thread_native_start(test_thread_native_multiple_joins_fn1, NULL, 1); t1 = ossl_crypto_thread_native_start(test_thread_native_multiple_joins_fn2, t, 1); t2 = ossl_crypto_thread_native_start(test_thread_native_multiple_joins_fn3, t, 1); if (!TEST_ptr(t) || !TEST_ptr(t1) || !TEST_ptr(t2)) return 0; if (!TEST_int_eq(ossl_crypto_thread_native_join(t2, NULL), 1)) return 0; if (!TEST_int_eq(ossl_crypto_thread_native_join(t1, NULL), 1)) return 0; if (!TEST_int_eq(ossl_crypto_thread_native_clean(t2), 1)) return 0; if (!TEST_int_eq(ossl_crypto_thread_native_clean(t1), 1)) return 0; if (!TEST_int_eq(ossl_crypto_thread_native_clean(t), 1)) return 0; return 1; } #endif int setup_tests(void) { ADD_TEST(test_thread_reported_flags); #if !defined(OPENSSL_NO_THREAD_POOL) ADD_TEST(test_thread_native); ADD_TEST(test_thread_native_multiple_joins); # if !defined(OPENSSL_NO_DEFAULT_THREAD_POOL) ADD_TEST(test_thread_internal); # endif #endif return 1; }
./openssl/test/quic_stream_test.c
/* * Copyright 2022-2023 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include "internal/packet.h" #include "internal/quic_stream.h" #include "testutil.h" static int compare_iov(const unsigned char *ref, size_t ref_len, const OSSL_QTX_IOVEC *iov, size_t iov_len) { size_t i, total_len = 0; const unsigned char *cur = ref; for (i = 0; i < iov_len; ++i) total_len += iov[i].buf_len; if (ref_len != total_len) return 0; for (i = 0; i < iov_len; ++i) { if (memcmp(cur, iov[i].buf, iov[i].buf_len)) return 0; cur += iov[i].buf_len; } return 1; } static const unsigned char data_1[] = { 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5a, 0x5b, 0x5c, 0x5d, 0x5e, 0x5f }; static int test_sstream_simple(void) { int testresult = 0; QUIC_SSTREAM *sstream = NULL; OSSL_QUIC_FRAME_STREAM hdr; OSSL_QTX_IOVEC iov[2]; size_t num_iov = 0, wr = 0, i, init_size = 8192; if (!TEST_ptr(sstream = ossl_quic_sstream_new(init_size))) goto err; /* A stream with nothing yet appended is totally acked */ if (!TEST_true(ossl_quic_sstream_is_totally_acked(sstream))) goto err; /* Should not have any data yet */ num_iov = OSSL_NELEM(iov); if (!TEST_false(ossl_quic_sstream_get_stream_frame(sstream, 0, &hdr, iov, &num_iov))) goto err; /* Append data */ if (!TEST_true(ossl_quic_sstream_append(sstream, data_1, sizeof(data_1), &wr)) || !TEST_size_t_eq(wr, sizeof(data_1))) goto err; /* No longer totally acked */ if (!TEST_false(ossl_quic_sstream_is_totally_acked(sstream))) goto err; /* Read data */ num_iov = OSSL_NELEM(iov); if (!TEST_true(ossl_quic_sstream_get_stream_frame(sstream, 0, &hdr, iov, &num_iov)) || !TEST_size_t_gt(num_iov, 0) || !TEST_uint64_t_eq(hdr.offset, 0) || !TEST_uint64_t_eq(hdr.len, sizeof(data_1)) || !TEST_false(hdr.is_fin)) goto err; if (!TEST_true(compare_iov(data_1, sizeof(data_1), iov, num_iov))) goto err; /* Mark data as half transmitted */ if (!TEST_true(ossl_quic_sstream_mark_transmitted(sstream, 0, 7))) goto err; /* Read data */ num_iov = OSSL_NELEM(iov); if (!TEST_true(ossl_quic_sstream_get_stream_frame(sstream, 0, &hdr, iov, &num_iov)) || !TEST_size_t_gt(num_iov, 0) || !TEST_uint64_t_eq(hdr.offset, 8) || !TEST_uint64_t_eq(hdr.len, sizeof(data_1) - 8) || !TEST_false(hdr.is_fin)) goto err; if (!TEST_true(compare_iov(data_1 + 8, sizeof(data_1) - 8, iov, num_iov))) goto err; if (!TEST_true(ossl_quic_sstream_mark_transmitted(sstream, 8, 15))) goto err; /* Read more data; should not be any more */ num_iov = OSSL_NELEM(iov); if (!TEST_false(ossl_quic_sstream_get_stream_frame(sstream, 0, &hdr, iov, &num_iov))) goto err; /* Now we have lost bytes 4-6 */ if (!TEST_true(ossl_quic_sstream_mark_lost(sstream, 4, 6))) goto err; /* Should be able to read them */ num_iov = OSSL_NELEM(iov); if (!TEST_true(ossl_quic_sstream_get_stream_frame(sstream, 0, &hdr, iov, &num_iov)) || !TEST_size_t_gt(num_iov, 0) || !TEST_uint64_t_eq(hdr.offset, 4) || !TEST_uint64_t_eq(hdr.len, 3) || !TEST_false(hdr.is_fin)) goto err; if (!TEST_true(compare_iov(data_1 + 4, 3, iov, num_iov))) goto err; /* Retransmit */ if (!TEST_true(ossl_quic_sstream_mark_transmitted(sstream, 4, 6))) goto err; /* Read more data; should not be any more */ num_iov = OSSL_NELEM(iov); if (!TEST_false(ossl_quic_sstream_get_stream_frame(sstream, 0, &hdr, iov, &num_iov))) goto err; if (!TEST_size_t_eq(ossl_quic_sstream_get_buffer_used(sstream), 16)) goto err; /* Data has been acknowledged, space should be not be freed yet */ if (!TEST_true(ossl_quic_sstream_mark_acked(sstream, 1, 7)) || !TEST_size_t_eq(ossl_quic_sstream_get_buffer_used(sstream), 16)) goto err; /* Now data should be freed */ if (!TEST_true(ossl_quic_sstream_mark_acked(sstream, 0, 0)) || !TEST_size_t_eq(ossl_quic_sstream_get_buffer_used(sstream), 8)) goto err; if (!TEST_true(ossl_quic_sstream_mark_acked(sstream, 0, 15)) || !TEST_size_t_eq(ossl_quic_sstream_get_buffer_used(sstream), 0)) goto err; /* Now FIN */ ossl_quic_sstream_fin(sstream); /* Get FIN frame */ for (i = 0; i < 2; ++i) { num_iov = OSSL_NELEM(iov); if (!TEST_true(ossl_quic_sstream_get_stream_frame(sstream, 0, &hdr, iov, &num_iov)) || !TEST_uint64_t_eq(hdr.offset, 16) || !TEST_uint64_t_eq(hdr.len, 0) || !TEST_true(hdr.is_fin) || !TEST_size_t_eq(num_iov, 0)) goto err; } if (!TEST_true(ossl_quic_sstream_mark_transmitted_fin(sstream, 16))) goto err; /* Read more data; FIN should not be returned any more */ num_iov = OSSL_NELEM(iov); if (!TEST_false(ossl_quic_sstream_get_stream_frame(sstream, 0, &hdr, iov, &num_iov))) goto err; /* Lose FIN frame */ if (!TEST_true(ossl_quic_sstream_mark_lost_fin(sstream))) goto err; /* Get FIN frame */ for (i = 0; i < 2; ++i) { num_iov = OSSL_NELEM(iov); if (!TEST_true(ossl_quic_sstream_get_stream_frame(sstream, 0, &hdr, iov, &num_iov)) || !TEST_uint64_t_eq(hdr.offset, 16) || !TEST_uint64_t_eq(hdr.len, 0) || !TEST_true(hdr.is_fin) || !TEST_size_t_eq(num_iov, 0)) goto err; } if (!TEST_true(ossl_quic_sstream_mark_transmitted_fin(sstream, 16))) goto err; /* Read more data; FIN should not be returned any more */ num_iov = OSSL_NELEM(iov); if (!TEST_false(ossl_quic_sstream_get_stream_frame(sstream, 0, &hdr, iov, &num_iov))) goto err; /* Acknowledge fin. */ if (!TEST_true(ossl_quic_sstream_mark_acked_fin(sstream))) goto err; if (!TEST_true(ossl_quic_sstream_is_totally_acked(sstream))) goto err; testresult = 1; err: ossl_quic_sstream_free(sstream); return testresult; } static int test_sstream_bulk(int idx) { int testresult = 0; QUIC_SSTREAM *sstream = NULL; OSSL_QUIC_FRAME_STREAM hdr; OSSL_QTX_IOVEC iov[2]; size_t i, j, num_iov = 0, init_size = 8192, l; size_t consumed = 0, total_written = 0, rd, cur_rd, expected = 0, start_at; unsigned char *src_buf = NULL, *dst_buf = NULL; unsigned char *ref_src_buf = NULL, *ref_dst_buf = NULL; unsigned char *ref_dst_cur, *ref_src_cur, *dst_cur; if (!TEST_ptr(sstream = ossl_quic_sstream_new(init_size))) goto err; if (!TEST_size_t_eq(ossl_quic_sstream_get_buffer_size(sstream), init_size)) goto err; if (!TEST_ptr(src_buf = OPENSSL_zalloc(init_size))) goto err; if (!TEST_ptr(dst_buf = OPENSSL_malloc(init_size))) goto err; if (!TEST_ptr(ref_src_buf = OPENSSL_malloc(init_size))) goto err; if (!TEST_ptr(ref_dst_buf = OPENSSL_malloc(init_size))) goto err; /* * Append a preliminary buffer to allow later code to exercise wraparound. */ if (!TEST_true(ossl_quic_sstream_append(sstream, src_buf, init_size / 2, &consumed)) || !TEST_size_t_eq(consumed, init_size / 2) || !TEST_true(ossl_quic_sstream_mark_transmitted(sstream, 0, init_size / 2 - 1)) || !TEST_true(ossl_quic_sstream_mark_acked(sstream, 0, init_size / 2 - 1))) goto err; start_at = init_size / 2; /* Generate a random buffer. */ for (i = 0; i < init_size; ++i) src_buf[i] = (unsigned char)(test_random() & 0xFF); /* Append bytes into the buffer in chunks of random length. */ ref_src_cur = ref_src_buf; do { l = (test_random() % init_size) + 1; if (!TEST_true(ossl_quic_sstream_append(sstream, src_buf, l, &consumed))) goto err; memcpy(ref_src_cur, src_buf, consumed); ref_src_cur += consumed; total_written += consumed; } while (consumed > 0); if (!TEST_size_t_eq(ossl_quic_sstream_get_buffer_used(sstream), init_size) || !TEST_size_t_eq(ossl_quic_sstream_get_buffer_avail(sstream), 0)) goto err; /* * Randomly select bytes out of the buffer by marking them as transmitted. * Record the remaining bytes, which should be the sequence of bytes * returned. */ ref_src_cur = ref_src_buf; ref_dst_cur = ref_dst_buf; for (i = 0; i < total_written; ++i) { if ((test_random() & 1) != 0) { *ref_dst_cur++ = *ref_src_cur; ++expected; } else if (!TEST_true(ossl_quic_sstream_mark_transmitted(sstream, start_at + i, start_at + i))) goto err; ++ref_src_cur; } /* Exercise resize. */ if (!TEST_true(ossl_quic_sstream_set_buffer_size(sstream, init_size * 2)) || !TEST_true(ossl_quic_sstream_set_buffer_size(sstream, init_size))) goto err; /* Readout and verification. */ dst_cur = dst_buf; for (i = 0, rd = 0; rd < expected; ++i) { num_iov = OSSL_NELEM(iov); if (!TEST_true(ossl_quic_sstream_get_stream_frame(sstream, i, &hdr, iov, &num_iov))) goto err; cur_rd = 0; for (j = 0; j < num_iov; ++j) { if (!TEST_size_t_le(iov[j].buf_len + rd, expected)) goto err; memcpy(dst_cur, iov[j].buf, iov[j].buf_len); dst_cur += iov[j].buf_len; cur_rd += iov[j].buf_len; } if (!TEST_uint64_t_eq(cur_rd, hdr.len)) goto err; rd += cur_rd; } if (!TEST_mem_eq(dst_buf, rd, ref_dst_buf, expected)) goto err; testresult = 1; err: OPENSSL_free(src_buf); OPENSSL_free(dst_buf); OPENSSL_free(ref_src_buf); OPENSSL_free(ref_dst_buf); ossl_quic_sstream_free(sstream); return testresult; } static int test_single_copy_read(QUIC_RSTREAM *qrs, unsigned char *buf, size_t size, size_t *readbytes, int *fin) { const unsigned char *record; size_t rec_len; *readbytes = 0; for (;;) { if (!ossl_quic_rstream_get_record(qrs, &record, &rec_len, fin)) return 0; if (rec_len == 0) break; if (rec_len > size) { rec_len = size; *fin = 0; } memcpy(buf, record, rec_len); size -= rec_len; *readbytes += rec_len; buf += rec_len; if (!ossl_quic_rstream_release_record(qrs, rec_len)) return 0; if (*fin || size == 0) break; } return 1; } static const unsigned char simple_data[] = "Hello world! And thank you for all the fish!"; static int test_rstream_simple(int idx) { QUIC_RSTREAM *rstream = NULL; int ret = 0; unsigned char buf[sizeof(simple_data)]; size_t readbytes = 0, avail = 0; int fin = 0; int use_rbuf = idx > 1; int use_sc = idx % 2; int (* read_fn)(QUIC_RSTREAM *, unsigned char *, size_t, size_t *, int *) = use_sc ? test_single_copy_read : ossl_quic_rstream_read; if (!TEST_ptr(rstream = ossl_quic_rstream_new(NULL, NULL, 0))) goto err; if (!TEST_true(ossl_quic_rstream_queue_data(rstream, NULL, 5, simple_data + 5, 10, 0)) || !TEST_true(ossl_quic_rstream_queue_data(rstream, NULL, sizeof(simple_data) - 1, simple_data + sizeof(simple_data) - 1, 1, 1)) || !TEST_true(ossl_quic_rstream_peek(rstream, buf, sizeof(buf), &readbytes, &fin)) || !TEST_false(fin) || !TEST_size_t_eq(readbytes, 0) || !TEST_true(ossl_quic_rstream_queue_data(rstream, NULL, sizeof(simple_data) - 10, simple_data + sizeof(simple_data) - 10, 10, 1)) || !TEST_true(ossl_quic_rstream_queue_data(rstream, NULL, 0, simple_data, 1, 0)) || !TEST_true(ossl_quic_rstream_peek(rstream, buf, sizeof(buf), &readbytes, &fin)) || !TEST_false(fin) || !TEST_size_t_eq(readbytes, 1) || !TEST_mem_eq(buf, 1, simple_data, 1) || (use_rbuf && !TEST_false(ossl_quic_rstream_move_to_rbuf(rstream))) || (use_rbuf && !TEST_true(ossl_quic_rstream_resize_rbuf(rstream, sizeof(simple_data)))) || (use_rbuf && !TEST_true(ossl_quic_rstream_move_to_rbuf(rstream))) || !TEST_true(ossl_quic_rstream_queue_data(rstream, NULL, 0, simple_data, 10, 0)) || !TEST_true(ossl_quic_rstream_queue_data(rstream, NULL, sizeof(simple_data), NULL, 0, 1)) || !TEST_true(ossl_quic_rstream_peek(rstream, buf, sizeof(buf), &readbytes, &fin)) || !TEST_false(fin) || !TEST_size_t_eq(readbytes, 15) || !TEST_mem_eq(buf, 15, simple_data, 15) || !TEST_true(ossl_quic_rstream_queue_data(rstream, NULL, 15, simple_data + 15, sizeof(simple_data) - 15, 1)) || !TEST_true(ossl_quic_rstream_available(rstream, &avail, &fin)) || !TEST_true(fin) || !TEST_size_t_eq(avail, sizeof(simple_data)) || !TEST_true(read_fn(rstream, buf, 2, &readbytes, &fin)) || !TEST_false(fin) || !TEST_size_t_eq(readbytes, 2) || !TEST_mem_eq(buf, 2, simple_data, 2) || !TEST_true(read_fn(rstream, buf + 2, 12, &readbytes, &fin)) || !TEST_false(fin) || !TEST_size_t_eq(readbytes, 12) || !TEST_mem_eq(buf + 2, 12, simple_data + 2, 12) || !TEST_true(ossl_quic_rstream_queue_data(rstream, NULL, sizeof(simple_data), NULL, 0, 1)) || (use_rbuf && !TEST_true(ossl_quic_rstream_resize_rbuf(rstream, 2 * sizeof(simple_data)))) || (use_rbuf && !TEST_true(ossl_quic_rstream_move_to_rbuf(rstream))) || !TEST_true(read_fn(rstream, buf + 14, 5, &readbytes, &fin)) || !TEST_false(fin) || !TEST_size_t_eq(readbytes, 5) || !TEST_mem_eq(buf, 14 + 5, simple_data, 14 + 5) || !TEST_true(read_fn(rstream, buf + 14 + 5, sizeof(buf) - 14 - 5, &readbytes, &fin)) || !TEST_true(fin) || !TEST_size_t_eq(readbytes, sizeof(buf) - 14 - 5) || !TEST_mem_eq(buf, sizeof(buf), simple_data, sizeof(simple_data)) || (use_rbuf && !TEST_true(ossl_quic_rstream_move_to_rbuf(rstream))) || !TEST_true(read_fn(rstream, buf, sizeof(buf), &readbytes, &fin)) || !TEST_true(fin) || !TEST_size_t_eq(readbytes, 0)) goto err; ret = 1; err: ossl_quic_rstream_free(rstream); return ret; } static int test_rstream_random(int idx) { unsigned char *bulk_data = NULL; unsigned char *read_buf = NULL; QUIC_RSTREAM *rstream = NULL; size_t i, read_off, queued_min, queued_max; const size_t data_size = 10000; int r, s, fin = 0, fin_set = 0; int ret = 0; size_t readbytes = 0; if (!TEST_ptr(bulk_data = OPENSSL_malloc(data_size)) || !TEST_ptr(read_buf = OPENSSL_malloc(data_size)) || !TEST_ptr(rstream = ossl_quic_rstream_new(NULL, NULL, 0))) goto err; if (idx % 3 == 0) ossl_quic_rstream_set_cleanse(rstream, 1); for (i = 0; i < data_size; ++i) bulk_data[i] = (unsigned char)(test_random() & 0xFF); read_off = queued_min = queued_max = 0; for (r = 0; r < 100; ++r) { for (s = 0; s < 10; ++s) { size_t off = (r * 10 + s) * 10, size = 10; if (test_random() % 10 == 0) /* drop packet */ continue; if (off <= queued_min && off + size > queued_min) queued_min = off + size; if (!TEST_true(ossl_quic_rstream_queue_data(rstream, NULL, off, bulk_data + off, size, 0))) goto err; if (queued_max < off + size) queued_max = off + size; if (test_random() % 5 != 0) continue; /* random overlapping retransmit */ off = read_off + test_random() % 50; if (off > 50) off -= 50; size = test_random() % 100 + 1; if (off + size > data_size) off = data_size - size; if (off <= queued_min && off + size > queued_min) queued_min = off + size; if (!TEST_true(ossl_quic_rstream_queue_data(rstream, NULL, off, bulk_data + off, size, 0))) goto err; if (queued_max < off + size) queued_max = off + size; } if (idx % 2 == 0) { if (!TEST_true(test_single_copy_read(rstream, read_buf, data_size, &readbytes, &fin))) goto err; } else if (!TEST_true(ossl_quic_rstream_read(rstream, read_buf, data_size, &readbytes, &fin))) { goto err; } if (!TEST_size_t_ge(readbytes, queued_min - read_off) || !TEST_size_t_le(readbytes + read_off, data_size) || (idx % 3 != 0 && !TEST_mem_eq(read_buf, readbytes, bulk_data + read_off, readbytes))) goto err; read_off += readbytes; queued_min = read_off; if (test_random() % 50 == 0) if (!TEST_true(ossl_quic_rstream_resize_rbuf(rstream, queued_max - read_off + 1)) || !TEST_true(ossl_quic_rstream_move_to_rbuf(rstream))) goto err; if (!fin_set && queued_max >= data_size - test_random() % 200) { fin_set = 1; /* Queue empty fin frame */ if (!TEST_true(ossl_quic_rstream_queue_data(rstream, NULL, data_size, NULL, 0, 1))) goto err; } } TEST_info("Total read bytes: %zu Fin rcvd: %d", read_off, fin); if (idx % 3 == 0) for (i = 0; i < read_off; i++) if (!TEST_uchar_eq(bulk_data[i], 0)) goto err; if (read_off == data_size && fin_set && !fin) { /* We might still receive the final empty frame */ if (idx % 2 == 0) { if (!TEST_true(test_single_copy_read(rstream, read_buf, data_size, &readbytes, &fin))) goto err; } else if (!TEST_true(ossl_quic_rstream_read(rstream, read_buf, data_size, &readbytes, &fin))) { goto err; } if (!TEST_size_t_eq(readbytes, 0) || !TEST_true(fin)) goto err; } ret = 1; err: ossl_quic_rstream_free(rstream); OPENSSL_free(bulk_data); OPENSSL_free(read_buf); return ret; } int setup_tests(void) { ADD_TEST(test_sstream_simple); ADD_ALL_TESTS(test_sstream_bulk, 100); ADD_ALL_TESTS(test_rstream_simple, 4); ADD_ALL_TESTS(test_rstream_random, 100); return 1; }
./openssl/test/x509_dup_cert_test.c
/* * Copyright 2017-2020 The OpenSSL Project Authors. All Rights Reserved. * Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <stdio.h> #include <openssl/err.h> #include <openssl/x509_vfy.h> #include "testutil.h" static int test_509_dup_cert(int n) { int ret = 0; X509_STORE *store = NULL; X509_LOOKUP *lookup = NULL; const char *cert_f = test_get_argument(n); if (TEST_ptr(store = X509_STORE_new()) && TEST_ptr(lookup = X509_STORE_add_lookup(store, X509_LOOKUP_file())) && TEST_true(X509_load_cert_file(lookup, cert_f, X509_FILETYPE_PEM)) && TEST_true(X509_load_cert_file(lookup, cert_f, X509_FILETYPE_PEM))) ret = 1; X509_STORE_free(store); return ret; } OPT_TEST_DECLARE_USAGE("cert.pem...\n") int setup_tests(void) { size_t n; if (!test_skip_common_options()) { TEST_error("Error parsing test options\n"); return 0; } n = test_get_argument_count(); if (!TEST_int_gt(n, 0)) return 0; ADD_ALL_TESTS(test_509_dup_cert, n); return 1; }
./openssl/test/ecdsatest.c
/* * Copyright 2002-2023 The OpenSSL Project Authors. All Rights Reserved. * Copyright (c) 2002, Oracle and/or its affiliates. All rights reserved * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ /* * Low level APIs are deprecated for public use, but still ok for internal use. */ #include "internal/deprecated.h" #include <openssl/opensslconf.h> /* To see if OPENSSL_NO_EC is defined */ #include "testutil.h" #ifndef OPENSSL_NO_EC # include <openssl/evp.h> # include <openssl/bn.h> # include <openssl/ec.h> # include <openssl/rand.h> # include "internal/nelem.h" # include "ecdsatest.h" static fake_random_generate_cb fbytes; static const char *numbers[2]; static size_t crv_len = 0; static EC_builtin_curve *curves = NULL; static OSSL_PROVIDER *fake_rand = NULL; static int fbytes(unsigned char *buf, size_t num, ossl_unused const char *name, EVP_RAND_CTX *ctx) { int ret = 0; static int fbytes_counter = 0; BIGNUM *tmp = NULL; fake_rand_set_callback(ctx, NULL); if (!TEST_ptr(tmp = BN_new()) || !TEST_int_lt(fbytes_counter, OSSL_NELEM(numbers)) || !TEST_true(BN_hex2bn(&tmp, numbers[fbytes_counter])) /* tmp might need leading zeros so pad it out */ || !TEST_int_le(BN_num_bytes(tmp), num) || !TEST_int_gt(BN_bn2binpad(tmp, buf, num), 0)) goto err; fbytes_counter = (fbytes_counter + 1) % OSSL_NELEM(numbers); ret = 1; err: BN_free(tmp); return ret; } /*- * This function hijacks the RNG to feed it the chosen ECDSA key and nonce. * The ECDSA KATs are from: * - the X9.62 draft (4) * - NIST CAVP (720) * * It uses the low-level ECDSA_sign_setup instead of EVP to control the RNG. * NB: This is not how applications should use ECDSA; this is only for testing. * * Tests the library can successfully: * - generate public keys that matches those KATs * - create ECDSA signatures that match those KATs * - accept those signatures as valid */ static int x9_62_tests(int n) { int nid, md_nid, ret = 0; const char *r_in = NULL, *s_in = NULL, *tbs = NULL; unsigned char *pbuf = NULL, *qbuf = NULL, *message = NULL; unsigned char digest[EVP_MAX_MD_SIZE]; unsigned int dgst_len = 0; long q_len, msg_len = 0; size_t p_len; EVP_MD_CTX *mctx = NULL; EC_KEY *key = NULL; ECDSA_SIG *signature = NULL; BIGNUM *r = NULL, *s = NULL; BIGNUM *kinv = NULL, *rp = NULL; const BIGNUM *sig_r = NULL, *sig_s = NULL; nid = ecdsa_cavs_kats[n].nid; md_nid = ecdsa_cavs_kats[n].md_nid; r_in = ecdsa_cavs_kats[n].r; s_in = ecdsa_cavs_kats[n].s; tbs = ecdsa_cavs_kats[n].msg; numbers[0] = ecdsa_cavs_kats[n].d; numbers[1] = ecdsa_cavs_kats[n].k; TEST_info("ECDSA KATs for curve %s", OBJ_nid2sn(nid)); #ifdef FIPS_MODULE if (EC_curve_nid2nist(nid) == NULL) return TEST_skip("skip non approved curves"); #endif /* FIPS_MODULE */ if (!TEST_ptr(mctx = EVP_MD_CTX_new()) /* get the message digest */ || !TEST_ptr(message = OPENSSL_hexstr2buf(tbs, &msg_len)) || !TEST_true(EVP_DigestInit_ex(mctx, EVP_get_digestbynid(md_nid), NULL)) || !TEST_true(EVP_DigestUpdate(mctx, message, msg_len)) || !TEST_true(EVP_DigestFinal_ex(mctx, digest, &dgst_len)) /* create the key */ || !TEST_ptr(key = EC_KEY_new_by_curve_name(nid)) /* load KAT variables */ || !TEST_ptr(r = BN_new()) || !TEST_ptr(s = BN_new()) || !TEST_true(BN_hex2bn(&r, r_in)) || !TEST_true(BN_hex2bn(&s, s_in))) goto err; /* public key must match KAT */ fake_rand_set_callback(RAND_get0_private(NULL), &fbytes); if (!TEST_true(EC_KEY_generate_key(key)) || !TEST_true(p_len = EC_KEY_key2buf(key, POINT_CONVERSION_UNCOMPRESSED, &pbuf, NULL)) || !TEST_ptr(qbuf = OPENSSL_hexstr2buf(ecdsa_cavs_kats[n].Q, &q_len)) || !TEST_int_eq(q_len, p_len) || !TEST_mem_eq(qbuf, q_len, pbuf, p_len)) goto err; /* create the signature via ECDSA_sign_setup to avoid use of ECDSA nonces */ fake_rand_set_callback(RAND_get0_private(NULL), &fbytes); if (!TEST_true(ECDSA_sign_setup(key, NULL, &kinv, &rp)) || !TEST_ptr(signature = ECDSA_do_sign_ex(digest, dgst_len, kinv, rp, key)) /* verify the signature */ || !TEST_int_eq(ECDSA_do_verify(digest, dgst_len, signature, key), 1)) goto err; /* compare the created signature with the expected signature */ ECDSA_SIG_get0(signature, &sig_r, &sig_s); if (!TEST_BN_eq(sig_r, r) || !TEST_BN_eq(sig_s, s)) goto err; ret = 1; err: OPENSSL_free(message); OPENSSL_free(pbuf); OPENSSL_free(qbuf); EC_KEY_free(key); ECDSA_SIG_free(signature); BN_free(r); BN_free(s); EVP_MD_CTX_free(mctx); BN_clear_free(kinv); BN_clear_free(rp); return ret; } /*- * Positive and negative ECDSA testing through EVP interface: * - EVP_DigestSign (this is the one-shot version) * - EVP_DigestVerify * * Tests the library can successfully: * - create a key * - create a signature * - accept that signature * - reject that signature with a different public key * - reject that signature if its length is not correct * - reject that signature after modifying the message * - accept that signature after un-modifying the message * - reject that signature after modifying the signature * - accept that signature after un-modifying the signature */ static int set_sm2_id(EVP_MD_CTX *mctx, EVP_PKEY *pkey) { /* With the SM2 key type, the SM2 ID is mandatory */ static const char sm2_id[] = { 1, 2, 3, 4, 'l', 'e', 't', 't', 'e', 'r' }; EVP_PKEY_CTX *pctx; if (!TEST_ptr(pctx = EVP_MD_CTX_get_pkey_ctx(mctx)) || !TEST_int_gt(EVP_PKEY_CTX_set1_id(pctx, sm2_id, sizeof(sm2_id)), 0)) return 0; return 1; } static int test_builtin(int n, int as) { EC_KEY *eckey_neg = NULL, *eckey = NULL; unsigned char dirt, offset, tbs[128]; unsigned char *sig = NULL; EVP_PKEY *pkey_neg = NULL, *pkey = NULL, *dup_pk = NULL; EVP_MD_CTX *mctx = NULL; size_t sig_len; int nid, ret = 0; int temp; nid = curves[n].nid; /* skip built-in curves where ord(G) is not prime */ if (nid == NID_ipsec4 || nid == NID_ipsec3) { TEST_info("skipped: ECDSA unsupported for curve %s", OBJ_nid2sn(nid)); return 1; } /* * skip SM2 curve if 'as' is equal to EVP_PKEY_EC or, skip all curves * except SM2 curve if 'as' is equal to EVP_PKEY_SM2 */ if (nid == NID_sm2 && as == EVP_PKEY_EC) { TEST_info("skipped: EC key type unsupported for curve %s", OBJ_nid2sn(nid)); return 1; } else if (nid != NID_sm2 && as == EVP_PKEY_SM2) { TEST_info("skipped: SM2 key type unsupported for curve %s", OBJ_nid2sn(nid)); return 1; } TEST_info("testing ECDSA for curve %s as %s key type", OBJ_nid2sn(nid), as == EVP_PKEY_EC ? "EC" : "SM2"); if (!TEST_ptr(mctx = EVP_MD_CTX_new()) /* get some random message data */ || !TEST_int_gt(RAND_bytes(tbs, sizeof(tbs)), 0) /* real key */ || !TEST_ptr(eckey = EC_KEY_new_by_curve_name(nid)) || !TEST_true(EC_KEY_generate_key(eckey)) || !TEST_ptr(pkey = EVP_PKEY_new()) || !TEST_true(EVP_PKEY_assign_EC_KEY(pkey, eckey)) /* fake key for negative testing */ || !TEST_ptr(eckey_neg = EC_KEY_new_by_curve_name(nid)) || !TEST_true(EC_KEY_generate_key(eckey_neg)) || !TEST_ptr(pkey_neg = EVP_PKEY_new()) || !TEST_false(EVP_PKEY_assign_EC_KEY(pkey_neg, NULL)) || !TEST_true(EVP_PKEY_assign_EC_KEY(pkey_neg, eckey_neg))) goto err; if (!TEST_ptr(dup_pk = EVP_PKEY_dup(pkey)) || !TEST_int_eq(EVP_PKEY_eq(pkey, dup_pk), 1)) goto err; temp = ECDSA_size(eckey); if (!TEST_int_ge(temp, 0) || !TEST_ptr(sig = OPENSSL_malloc(sig_len = (size_t)temp)) /* create a signature */ || !TEST_true(EVP_DigestSignInit(mctx, NULL, NULL, NULL, pkey)) || (as == EVP_PKEY_SM2 && !set_sm2_id(mctx, pkey)) || !TEST_true(EVP_DigestSign(mctx, sig, &sig_len, tbs, sizeof(tbs))) || !TEST_int_le(sig_len, ECDSA_size(eckey)) || !TEST_true(EVP_MD_CTX_reset(mctx)) /* negative test, verify with wrong key, 0 return */ || !TEST_true(EVP_DigestVerifyInit(mctx, NULL, NULL, NULL, pkey_neg)) || (as == EVP_PKEY_SM2 && !set_sm2_id(mctx, pkey_neg)) || !TEST_int_eq(EVP_DigestVerify(mctx, sig, sig_len, tbs, sizeof(tbs)), 0) || !TEST_true(EVP_MD_CTX_reset(mctx)) /* negative test, verify with wrong signature length, -1 return */ || !TEST_true(EVP_DigestVerifyInit(mctx, NULL, NULL, NULL, pkey)) || (as == EVP_PKEY_SM2 && !set_sm2_id(mctx, pkey)) || !TEST_int_eq(EVP_DigestVerify(mctx, sig, sig_len - 1, tbs, sizeof(tbs)), -1) || !TEST_true(EVP_MD_CTX_reset(mctx)) /* positive test, verify with correct key, 1 return */ || !TEST_true(EVP_DigestVerifyInit(mctx, NULL, NULL, NULL, pkey)) || (as == EVP_PKEY_SM2 && !set_sm2_id(mctx, pkey)) || !TEST_int_eq(EVP_DigestVerify(mctx, sig, sig_len, tbs, sizeof(tbs)), 1) || !TEST_true(EVP_MD_CTX_reset(mctx))) goto err; /* muck with the message, test it fails with 0 return */ tbs[0] ^= 1; if (!TEST_true(EVP_DigestVerifyInit(mctx, NULL, NULL, NULL, pkey)) || (as == EVP_PKEY_SM2 && !set_sm2_id(mctx, pkey)) || !TEST_int_eq(EVP_DigestVerify(mctx, sig, sig_len, tbs, sizeof(tbs)), 0) || !TEST_true(EVP_MD_CTX_reset(mctx))) goto err; /* un-muck and test it verifies */ tbs[0] ^= 1; if (!TEST_true(EVP_DigestVerifyInit(mctx, NULL, NULL, NULL, pkey)) || (as == EVP_PKEY_SM2 && !set_sm2_id(mctx, pkey)) || !TEST_int_eq(EVP_DigestVerify(mctx, sig, sig_len, tbs, sizeof(tbs)), 1) || !TEST_true(EVP_MD_CTX_reset(mctx))) goto err; /*- * Muck with the ECDSA signature. The DER encoding is one of: * - 30 LL 02 .. * - 30 81 LL 02 .. * * - Sometimes this mucks with the high level DER sequence wrapper: * in that case, DER-parsing of the whole signature should fail. * * - Sometimes this mucks with the DER-encoding of ECDSA.r: * in that case, DER-parsing of ECDSA.r should fail. * * - Sometimes this mucks with the DER-encoding of ECDSA.s: * in that case, DER-parsing of ECDSA.s should fail. * * - Sometimes this mucks with ECDSA.r: * in that case, the signature verification should fail. * * - Sometimes this mucks with ECDSA.s: * in that case, the signature verification should fail. * * The usual case is changing the integer value of ECDSA.r or ECDSA.s. * Because the ratio of DER overhead to signature bytes is small. * So most of the time it will be one of the last two cases. * * In any case, EVP_PKEY_verify should not return 1 for valid. */ offset = tbs[0] % sig_len; dirt = tbs[1] ? tbs[1] : 1; sig[offset] ^= dirt; if (!TEST_true(EVP_DigestVerifyInit(mctx, NULL, NULL, NULL, pkey)) || (as == EVP_PKEY_SM2 && !set_sm2_id(mctx, pkey)) || !TEST_int_ne(EVP_DigestVerify(mctx, sig, sig_len, tbs, sizeof(tbs)), 1) || !TEST_true(EVP_MD_CTX_reset(mctx))) goto err; /* un-muck and test it verifies */ sig[offset] ^= dirt; if (!TEST_true(EVP_DigestVerifyInit(mctx, NULL, NULL, NULL, pkey)) || (as == EVP_PKEY_SM2 && !set_sm2_id(mctx, pkey)) || !TEST_int_eq(EVP_DigestVerify(mctx, sig, sig_len, tbs, sizeof(tbs)), 1) || !TEST_true(EVP_MD_CTX_reset(mctx))) goto err; ret = 1; err: EVP_PKEY_free(pkey); EVP_PKEY_free(pkey_neg); EVP_PKEY_free(dup_pk); EVP_MD_CTX_free(mctx); OPENSSL_free(sig); return ret; } static int test_builtin_as_ec(int n) { return test_builtin(n, EVP_PKEY_EC); } # ifndef OPENSSL_NO_SM2 static int test_builtin_as_sm2(int n) { return test_builtin(n, EVP_PKEY_SM2); } # endif static int test_ecdsa_sig_NULL(void) { int ret; unsigned int siglen; unsigned char dgst[128] = { 0 }; EC_KEY *eckey = NULL; ret = TEST_ptr(eckey = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1)) && TEST_int_eq(EC_KEY_generate_key(eckey), 1) && TEST_int_eq(ECDSA_sign(0, dgst, sizeof(dgst), NULL, &siglen, eckey), 1) && TEST_int_gt(siglen, 0); EC_KEY_free(eckey); return ret; } #endif /* OPENSSL_NO_EC */ int setup_tests(void) { #ifdef OPENSSL_NO_EC TEST_note("Elliptic curves are disabled."); #else fake_rand = fake_rand_start(NULL); if (fake_rand == NULL) return 0; /* get a list of all internal curves */ crv_len = EC_get_builtin_curves(NULL, 0); if (!TEST_ptr(curves = OPENSSL_malloc(sizeof(*curves) * crv_len)) || !TEST_true(EC_get_builtin_curves(curves, crv_len))) { fake_rand_finish(fake_rand); return 0; } ADD_ALL_TESTS(test_builtin_as_ec, crv_len); ADD_TEST(test_ecdsa_sig_NULL); # ifndef OPENSSL_NO_SM2 ADD_ALL_TESTS(test_builtin_as_sm2, crv_len); # endif ADD_ALL_TESTS(x9_62_tests, OSSL_NELEM(ecdsa_cavs_kats)); #endif return 1; } void cleanup_tests(void) { #ifndef OPENSSL_NO_EC fake_rand_finish(fake_rand); OPENSSL_free(curves); #endif }
./openssl/test/provider_internal_test.c
/* * Copyright 2019-2023 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <stddef.h> #include <openssl/crypto.h> #include "internal/provider.h" #include "testutil.h" extern OSSL_provider_init_fn PROVIDER_INIT_FUNCTION_NAME; static char buf[256]; static OSSL_PARAM greeting_request[] = { { "greeting", OSSL_PARAM_UTF8_STRING, buf, sizeof(buf), 0 }, { NULL, 0, NULL, 0, 0 } }; static int test_provider(OSSL_PROVIDER *prov, const char *expected_greeting) { const char *greeting = NULL; int ret = 0; ret = TEST_true(ossl_provider_activate(prov, 1, 0)) && TEST_true(ossl_provider_get_params(prov, greeting_request)) && TEST_ptr(greeting = greeting_request[0].data) && TEST_size_t_gt(greeting_request[0].data_size, 0) && TEST_str_eq(greeting, expected_greeting) && TEST_true(ossl_provider_deactivate(prov, 1)); TEST_info("Got this greeting: %s\n", greeting); ossl_provider_free(prov); return ret; } static const char *expected_greeting1(const char *name) { static char expected_greeting[256] = ""; BIO_snprintf(expected_greeting, sizeof(expected_greeting), "Hello OpenSSL %.20s, greetings from %s!", OPENSSL_VERSION_STR, name); return expected_greeting; } static int test_builtin_provider(void) { const char *name = "p_test_builtin"; OSSL_PROVIDER *prov = NULL; int ret; /* * We set properties that we know the providers we are using don't have. * This should mean that the p_test provider will fail any fetches - which * is something we test inside the provider. */ EVP_set_default_properties(NULL, "fips=yes"); ret = TEST_ptr(prov = ossl_provider_new(NULL, name, PROVIDER_INIT_FUNCTION_NAME, NULL, 0)) && test_provider(prov, expected_greeting1(name)); EVP_set_default_properties(NULL, ""); return ret; } #ifndef NO_PROVIDER_MODULE static int test_loaded_provider(void) { const char *name = "p_test"; OSSL_PROVIDER *prov = NULL; return TEST_ptr(prov = ossl_provider_new(NULL, name, NULL, NULL, 0)) && test_provider(prov, expected_greeting1(name)); } # ifndef OPENSSL_NO_AUTOLOAD_CONFIG static int test_configured_provider(void) { const char *name = "p_test_configured"; OSSL_PROVIDER *prov = NULL; /* This MUST match the config file */ const char *expected_greeting = "Hello OpenSSL, greetings from Test Provider"; return TEST_ptr(prov = ossl_provider_find(NULL, name, 0)) && test_provider(prov, expected_greeting); } # endif #endif static int test_cache_flushes(void) { OSSL_LIB_CTX *ctx; OSSL_PROVIDER *prov = NULL; EVP_MD *md = NULL; int ret = 0; if (!TEST_ptr(ctx = OSSL_LIB_CTX_new()) || !TEST_ptr(prov = OSSL_PROVIDER_load(ctx, "default")) || !TEST_true(OSSL_PROVIDER_available(ctx, "default")) || !TEST_ptr(md = EVP_MD_fetch(ctx, "SHA256", NULL))) goto err; EVP_MD_free(md); md = NULL; OSSL_PROVIDER_unload(prov); prov = NULL; if (!TEST_false(OSSL_PROVIDER_available(ctx, "default"))) goto err; if (!TEST_ptr_null(md = EVP_MD_fetch(ctx, "SHA256", NULL))) { const char *provname = OSSL_PROVIDER_get0_name(EVP_MD_get0_provider(md)); if (OSSL_PROVIDER_available(NULL, provname)) TEST_info("%s provider is available\n", provname); else TEST_info("%s provider is not available\n", provname); } ret = 1; err: OSSL_PROVIDER_unload(prov); EVP_MD_free(md); OSSL_LIB_CTX_free(ctx); return ret; } int setup_tests(void) { ADD_TEST(test_builtin_provider); #ifndef NO_PROVIDER_MODULE ADD_TEST(test_loaded_provider); # ifndef OPENSSL_NO_AUTOLOAD_CONFIG ADD_TEST(test_configured_provider); # endif #endif ADD_TEST(test_cache_flushes); return 1; }
./openssl/test/x509aux.c
/* * Copyright 2016-2021 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * https://www.openssl.org/source/license.html * or in the file LICENSE in the source distribution. */ #include <stdio.h> #include <string.h> #include <errno.h> #include <openssl/x509.h> #include <openssl/pem.h> #include <openssl/conf.h> #include <openssl/err.h> #include "testutil.h" static int test_certs(int num) { int c; char *name = 0; char *header = 0; unsigned char *data = 0; long len; typedef X509 *(*d2i_X509_t)(X509 **, const unsigned char **, long); typedef int (*i2d_X509_t)(const X509 *, unsigned char **); int err = 0; BIO *fp = BIO_new_file(test_get_argument(num), "r"); if (!TEST_ptr(fp)) return 0; for (c = 0; !err && PEM_read_bio(fp, &name, &header, &data, &len); ++c) { const int trusted = (strcmp(name, PEM_STRING_X509_TRUSTED) == 0); d2i_X509_t d2i = trusted ? d2i_X509_AUX : d2i_X509; i2d_X509_t i2d = trusted ? i2d_X509_AUX : i2d_X509; X509 *cert = NULL; X509 *reuse = NULL; const unsigned char *p = data; unsigned char *buf = NULL; unsigned char *bufp; long enclen; if (!trusted && strcmp(name, PEM_STRING_X509) != 0 && strcmp(name, PEM_STRING_X509_OLD) != 0) { TEST_error("unexpected PEM object: %s", name); err = 1; goto next; } cert = d2i(NULL, &p, len); if (cert == NULL || (p - data) != len) { TEST_error("error parsing input %s", name); err = 1; goto next; } /* Test traditional 2-pass encoding into caller allocated buffer */ enclen = i2d(cert, NULL); if (len != enclen) { TEST_error("encoded length %ld of %s != input length %ld", enclen, name, len); err = 1; goto next; } if ((buf = bufp = OPENSSL_malloc(len)) == NULL) { TEST_perror("malloc"); err = 1; goto next; } enclen = i2d(cert, &bufp); if (len != enclen) { TEST_error("encoded length %ld of %s != input length %ld", enclen, name, len); err = 1; goto next; } enclen = (long) (bufp - buf); if (enclen != len) { TEST_error("unexpected buffer position after encoding %s", name); err = 1; goto next; } if (memcmp(buf, data, len) != 0) { TEST_error("encoded content of %s does not match input", name); err = 1; goto next; } p = buf; reuse = d2i(NULL, &p, enclen); if (reuse == NULL) { TEST_error("second d2i call failed for %s", name); err = 1; goto next; } err = X509_cmp(reuse, cert); if (err != 0) { TEST_error("X509_cmp for %s resulted in %d", name, err); err = 1; goto next; } OPENSSL_free(buf); buf = NULL; /* Test 1-pass encoding into library allocated buffer */ enclen = i2d(cert, &buf); if (len != enclen) { TEST_error("encoded length %ld of %s != input length %ld", enclen, name, len); err = 1; goto next; } if (memcmp(buf, data, len) != 0) { TEST_error("encoded content of %s does not match input", name); err = 1; goto next; } if (trusted) { /* Encode just the cert and compare with initial encoding */ OPENSSL_free(buf); buf = NULL; /* Test 1-pass encoding into library allocated buffer */ enclen = i2d(cert, &buf); if (enclen > len) { TEST_error("encoded length %ld of %s > input length %ld", enclen, name, len); err = 1; goto next; } if (memcmp(buf, data, enclen) != 0) { TEST_error("encoded cert content does not match input"); err = 1; goto next; } } /* * If any of these were null, PEM_read() would have failed. */ next: X509_free(cert); X509_free(reuse); OPENSSL_free(buf); OPENSSL_free(name); OPENSSL_free(header); OPENSSL_free(data); } BIO_free(fp); if (ERR_GET_REASON(ERR_peek_last_error()) == PEM_R_NO_START_LINE) { /* Reached end of PEM file */ if (c > 0) { ERR_clear_error(); return 1; } } /* Some other PEM read error */ return 0; } OPT_TEST_DECLARE_USAGE("certfile...\n") int setup_tests(void) { size_t n; if (!test_skip_common_options()) { TEST_error("Error parsing test options\n"); return 0; } n = test_get_argument_count(); if (n == 0) return 0; ADD_ALL_TESTS(test_certs, (int)n); return 1; }
./openssl/test/pbelutest.c
/* * Copyright 2015-2017 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <openssl/evp.h> #include "testutil.h" /* * Password based encryption (PBE) table ordering test. * Attempt to look up all supported algorithms. */ static int test_pbelu(void) { int i, failed = 0; int pbe_type, pbe_nid, last_type = -1, last_nid = -1; for (i = 0; EVP_PBE_get(&pbe_type, &pbe_nid, i) != 0; i++) { if (!TEST_true(EVP_PBE_find(pbe_type, pbe_nid, NULL, NULL, 0))) { TEST_note("i=%d, pbe_type=%d, pbe_nid=%d", i, pbe_type, pbe_nid); failed = 1; break; } } if (!failed) return 1; /* Error: print out whole table */ for (i = 0; EVP_PBE_get(&pbe_type, &pbe_nid, i) != 0; i++) { failed = pbe_type < last_type || (pbe_type == last_type && pbe_nid < last_nid); TEST_note("PBE type=%d %d (%s): %s\n", pbe_type, pbe_nid, OBJ_nid2sn(pbe_nid), failed ? "ERROR" : "OK"); last_type = pbe_type; last_nid = pbe_nid; } return 0; } int setup_tests(void) { ADD_TEST(test_pbelu); return 1; }
./openssl/test/bio_enc_test.c
/* * Copyright 2016-2022 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <stdio.h> #include <string.h> #include <openssl/evp.h> #include <openssl/bio.h> #include <openssl/rand.h> #include "testutil.h" #define ENCRYPT 1 #define DECRYPT 0 #define DATA_SIZE 1024 #define MAX_IV 32 #define BUF_SIZE (DATA_SIZE + MAX_IV) static const unsigned char KEY[] = { 0x51, 0x50, 0xd1, 0x77, 0x2f, 0x50, 0x83, 0x4a, 0x50, 0x3e, 0x06, 0x9a, 0x97, 0x3f, 0xbd, 0x7c, 0xe6, 0x1c, 0x43, 0x2b, 0x72, 0x0b, 0x19, 0xd1, 0x8e, 0xc8, 0xd8, 0x4b, 0xdc, 0x63, 0x15, 0x1b }; static const unsigned char IV[] = { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08 }; static int do_bio_cipher(const EVP_CIPHER* cipher, const unsigned char* key, const unsigned char* iv) { BIO *b, *mem; static unsigned char inp[BUF_SIZE] = { 0 }; unsigned char out[BUF_SIZE], ref[BUF_SIZE]; int i, lref, len; /* Fill buffer with non-zero data so that over steps can be detected */ if (!TEST_int_gt(RAND_bytes(inp, DATA_SIZE), 0)) return 0; /* Encrypt tests */ /* reference output for single-chunk operation */ b = BIO_new(BIO_f_cipher()); if (!TEST_ptr(b)) return 0; if (!TEST_true(BIO_set_cipher(b, cipher, key, iv, ENCRYPT))) goto err; mem = BIO_new_mem_buf(inp, DATA_SIZE); if (!TEST_ptr(mem)) goto err; BIO_push(b, mem); lref = BIO_read(b, ref, sizeof(ref)); BIO_free_all(b); /* perform split operations and compare to reference */ for (i = 1; i < lref; i++) { b = BIO_new(BIO_f_cipher()); if (!TEST_ptr(b)) return 0; if (!TEST_true(BIO_set_cipher(b, cipher, key, iv, ENCRYPT))) { TEST_info("Split encrypt failed @ operation %d", i); goto err; } mem = BIO_new_mem_buf(inp, DATA_SIZE); if (!TEST_ptr(mem)) goto err; BIO_push(b, mem); memset(out, 0, sizeof(out)); out[i] = ~ref[i]; len = BIO_read(b, out, i); /* check for overstep */ if (!TEST_uchar_eq(out[i], (unsigned char)~ref[i])) { TEST_info("Encrypt overstep check failed @ operation %d", i); goto err; } len += BIO_read(b, out + len, sizeof(out) - len); BIO_free_all(b); if (!TEST_mem_eq(out, len, ref, lref)) { TEST_info("Encrypt compare failed @ operation %d", i); return 0; } } /* perform small-chunk operations and compare to reference */ for (i = 1; i < lref / 2; i++) { int delta; b = BIO_new(BIO_f_cipher()); if (!TEST_ptr(b)) return 0; if (!TEST_true(BIO_set_cipher(b, cipher, key, iv, ENCRYPT))) { TEST_info("Small chunk encrypt failed @ operation %d", i); goto err; } mem = BIO_new_mem_buf(inp, DATA_SIZE); if (!TEST_ptr(mem)) goto err; BIO_push(b, mem); memset(out, 0, sizeof(out)); for (len = 0; (delta = BIO_read(b, out + len, i)); ) { len += delta; } BIO_free_all(b); if (!TEST_mem_eq(out, len, ref, lref)) { TEST_info("Small chunk encrypt compare failed @ operation %d", i); return 0; } } /* Decrypt tests */ /* reference output for single-chunk operation */ b = BIO_new(BIO_f_cipher()); if (!TEST_ptr(b)) return 0; if (!TEST_true(BIO_set_cipher(b, cipher, key, iv, DECRYPT))) goto err; /* Use original reference output as input */ mem = BIO_new_mem_buf(ref, lref); if (!TEST_ptr(mem)) goto err; BIO_push(b, mem); (void)BIO_flush(b); memset(out, 0, sizeof(out)); len = BIO_read(b, out, sizeof(out)); BIO_free_all(b); if (!TEST_mem_eq(inp, DATA_SIZE, out, len)) return 0; /* perform split operations and compare to reference */ for (i = 1; i < lref; i++) { b = BIO_new(BIO_f_cipher()); if (!TEST_ptr(b)) return 0; if (!TEST_true(BIO_set_cipher(b, cipher, key, iv, DECRYPT))) { TEST_info("Split decrypt failed @ operation %d", i); goto err; } mem = BIO_new_mem_buf(ref, lref); if (!TEST_ptr(mem)) goto err; BIO_push(b, mem); memset(out, 0, sizeof(out)); out[i] = ~ref[i]; len = BIO_read(b, out, i); /* check for overstep */ if (!TEST_uchar_eq(out[i], (unsigned char)~ref[i])) { TEST_info("Decrypt overstep check failed @ operation %d", i); goto err; } len += BIO_read(b, out + len, sizeof(out) - len); BIO_free_all(b); if (!TEST_mem_eq(inp, DATA_SIZE, out, len)) { TEST_info("Decrypt compare failed @ operation %d", i); return 0; } } /* perform small-chunk operations and compare to reference */ for (i = 1; i < lref / 2; i++) { int delta; b = BIO_new(BIO_f_cipher()); if (!TEST_ptr(b)) return 0; if (!TEST_true(BIO_set_cipher(b, cipher, key, iv, DECRYPT))) { TEST_info("Small chunk decrypt failed @ operation %d", i); goto err; } mem = BIO_new_mem_buf(ref, lref); if (!TEST_ptr(mem)) goto err; BIO_push(b, mem); memset(out, 0, sizeof(out)); for (len = 0; (delta = BIO_read(b, out + len, i)); ) { len += delta; } BIO_free_all(b); if (!TEST_mem_eq(inp, DATA_SIZE, out, len)) { TEST_info("Small chunk decrypt compare failed @ operation %d", i); return 0; } } return 1; err: BIO_free_all(b); return 0; } static int do_test_bio_cipher(const EVP_CIPHER* cipher, int idx) { switch (idx) { case 0: return do_bio_cipher(cipher, KEY, NULL); case 1: return do_bio_cipher(cipher, KEY, IV); } return 0; } static int test_bio_enc_aes_128_cbc(int idx) { return do_test_bio_cipher(EVP_aes_128_cbc(), idx); } static int test_bio_enc_aes_128_ctr(int idx) { return do_test_bio_cipher(EVP_aes_128_ctr(), idx); } static int test_bio_enc_aes_256_cfb(int idx) { return do_test_bio_cipher(EVP_aes_256_cfb(), idx); } static int test_bio_enc_aes_256_ofb(int idx) { return do_test_bio_cipher(EVP_aes_256_ofb(), idx); } # ifndef OPENSSL_NO_CHACHA static int test_bio_enc_chacha20(int idx) { return do_test_bio_cipher(EVP_chacha20(), idx); } # ifndef OPENSSL_NO_POLY1305 static int test_bio_enc_chacha20_poly1305(int idx) { return do_test_bio_cipher(EVP_chacha20_poly1305(), idx); } # endif # endif int setup_tests(void) { ADD_ALL_TESTS(test_bio_enc_aes_128_cbc, 2); ADD_ALL_TESTS(test_bio_enc_aes_128_ctr, 2); ADD_ALL_TESTS(test_bio_enc_aes_256_cfb, 2); ADD_ALL_TESTS(test_bio_enc_aes_256_ofb, 2); # ifndef OPENSSL_NO_CHACHA ADD_ALL_TESTS(test_bio_enc_chacha20, 2); # ifndef OPENSSL_NO_POLY1305 ADD_ALL_TESTS(test_bio_enc_chacha20_poly1305, 2); # endif # endif return 1; }
./openssl/test/ocspapitest.c
/* * Copyright 2017-2023 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <string.h> #include <openssl/opensslconf.h> #include <openssl/crypto.h> #include <openssl/ocsp.h> #include <openssl/x509.h> #include <openssl/asn1.h> #include <openssl/pem.h> #include "testutil.h" static const char *certstr; static const char *privkeystr; #ifndef OPENSSL_NO_OCSP static int get_cert_and_key(X509 **cert_out, EVP_PKEY **key_out) { BIO *certbio, *keybio; X509 *cert = NULL; EVP_PKEY *key = NULL; if (!TEST_ptr(certbio = BIO_new_file(certstr, "r"))) return 0; cert = PEM_read_bio_X509(certbio, NULL, NULL, NULL); BIO_free(certbio); if (!TEST_ptr(keybio = BIO_new_file(privkeystr, "r"))) goto end; key = PEM_read_bio_PrivateKey(keybio, NULL, NULL, NULL); BIO_free(keybio); if (!TEST_ptr(cert) || !TEST_ptr(key)) goto end; *cert_out = cert; *key_out = key; return 1; end: X509_free(cert); EVP_PKEY_free(key); return 0; } static int get_cert(X509 **cert_out) { BIO *certbio; X509 *cert = NULL; if (!TEST_ptr(certbio = BIO_new_file(certstr, "r"))) return 0; cert = PEM_read_bio_X509(certbio, NULL, NULL, NULL); BIO_free(certbio); if (!TEST_ptr(cert)) goto end; *cert_out = cert; return 1; end: X509_free(cert); return 0; } static OCSP_BASICRESP *make_dummy_resp(void) { const unsigned char namestr[] = "openssl.example.com"; unsigned char keybytes[128] = {7}; OCSP_BASICRESP *bs = OCSP_BASICRESP_new(); OCSP_BASICRESP *bs_out = NULL; OCSP_CERTID *cid = NULL; ASN1_TIME *thisupd = ASN1_TIME_set(NULL, time(NULL)); ASN1_TIME *nextupd = ASN1_TIME_set(NULL, time(NULL) + 200); X509_NAME *name = X509_NAME_new(); ASN1_BIT_STRING *key = ASN1_BIT_STRING_new(); ASN1_INTEGER *serial = ASN1_INTEGER_new(); if (!TEST_ptr(name) || !TEST_ptr(key) || !TEST_ptr(serial) || !TEST_true(X509_NAME_add_entry_by_NID(name, NID_commonName, MBSTRING_ASC, namestr, -1, -1, 1)) || !TEST_true(ASN1_BIT_STRING_set(key, keybytes, sizeof(keybytes))) || !TEST_true(ASN1_INTEGER_set_uint64(serial, (uint64_t)1))) goto err; cid = OCSP_cert_id_new(EVP_sha256(), name, key, serial); if (!TEST_ptr(bs) || !TEST_ptr(thisupd) || !TEST_ptr(nextupd) || !TEST_ptr(cid) || !TEST_true(OCSP_basic_add1_status(bs, cid, V_OCSP_CERTSTATUS_UNKNOWN, 0, NULL, thisupd, nextupd))) goto err; bs_out = bs; bs = NULL; err: ASN1_TIME_free(thisupd); ASN1_TIME_free(nextupd); ASN1_BIT_STRING_free(key); ASN1_INTEGER_free(serial); OCSP_CERTID_free(cid); OCSP_BASICRESP_free(bs); X509_NAME_free(name); return bs_out; } static int test_resp_signer(void) { OCSP_BASICRESP *bs = NULL; X509 *signer = NULL, *tmp; EVP_PKEY *key = NULL; STACK_OF(X509) *extra_certs = NULL; int ret = 0; /* * Test a response with no certs at all; get the signer from the * extra certs given to OCSP_resp_get0_signer(). */ bs = make_dummy_resp(); extra_certs = sk_X509_new_null(); if (!TEST_ptr(bs) || !TEST_ptr(extra_certs) || !TEST_true(get_cert_and_key(&signer, &key)) || !TEST_true(sk_X509_push(extra_certs, signer)) || !TEST_true(OCSP_basic_sign(bs, signer, key, EVP_sha1(), NULL, OCSP_NOCERTS))) goto err; if (!TEST_true(OCSP_resp_get0_signer(bs, &tmp, extra_certs)) || !TEST_int_eq(X509_cmp(tmp, signer), 0)) goto err; OCSP_BASICRESP_free(bs); /* Do it again but include the signer cert */ bs = make_dummy_resp(); tmp = NULL; if (!TEST_ptr(bs) || !TEST_true(OCSP_basic_sign(bs, signer, key, EVP_sha1(), NULL, 0))) goto err; if (!TEST_true(OCSP_resp_get0_signer(bs, &tmp, NULL)) || !TEST_int_eq(X509_cmp(tmp, signer), 0)) goto err; ret = 1; err: OCSP_BASICRESP_free(bs); sk_X509_free(extra_certs); X509_free(signer); EVP_PKEY_free(key); return ret; } static int test_access_description(int testcase) { ACCESS_DESCRIPTION *ad = ACCESS_DESCRIPTION_new(); int ret = 0; if (!TEST_ptr(ad)) goto err; switch (testcase) { case 0: /* no change */ break; case 1: /* check and release current location */ if (!TEST_ptr(ad->location)) goto err; GENERAL_NAME_free(ad->location); ad->location = NULL; break; case 2: /* replace current location */ GENERAL_NAME_free(ad->location); ad->location = GENERAL_NAME_new(); if (!TEST_ptr(ad->location)) goto err; break; } ACCESS_DESCRIPTION_free(ad); ret = 1; err: return ret; } static int test_ocsp_url_svcloc_new(void) { static const char *urls[] = { "www.openssl.org", "www.openssl.net", NULL }; X509 *issuer = NULL; X509_EXTENSION *ext = NULL; int ret = 0; if (!TEST_true(get_cert(&issuer))) goto err; /* * Test calling this ocsp method to catch any memory leak */ ext = OCSP_url_svcloc_new(X509_get_issuer_name(issuer), urls); if (!TEST_ptr(ext)) goto err; X509_EXTENSION_free(ext); ret = 1; err: X509_free(issuer); return ret; } #endif /* OPENSSL_NO_OCSP */ OPT_TEST_DECLARE_USAGE("certfile privkeyfile\n") int setup_tests(void) { if (!test_skip_common_options()) { TEST_error("Error parsing test options\n"); return 0; } if (!TEST_ptr(certstr = test_get_argument(0)) || !TEST_ptr(privkeystr = test_get_argument(1))) return 0; #ifndef OPENSSL_NO_OCSP ADD_TEST(test_resp_signer); ADD_ALL_TESTS(test_access_description, 3); ADD_TEST(test_ocsp_url_svcloc_new); #endif return 1; }
./openssl/test/evp_extra_test2.c
/* * Copyright 2015-2023 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ /* We need to use some deprecated APIs */ #define OPENSSL_SUPPRESS_DEPRECATED /* * Really these tests should be in evp_extra_test - but that doesn't * yet support testing with a non-default libctx. Once it does we should move * everything into one file. Consequently some things are duplicated between * the two files. */ #include <openssl/evp.h> #include <openssl/pem.h> #include <openssl/provider.h> #include <openssl/rsa.h> #include <openssl/dh.h> #include <openssl/core_names.h> #include <openssl/ui.h> #include "testutil.h" #include "internal/nelem.h" static OSSL_LIB_CTX *mainctx = NULL; static OSSL_PROVIDER *nullprov = NULL; /* * kExampleRSAKeyDER is an RSA private key in ASN.1, DER format. Of course, you * should never use this key anywhere but in an example. */ static const unsigned char kExampleRSAKeyDER[] = { 0x30, 0x82, 0x02, 0x5c, 0x02, 0x01, 0x00, 0x02, 0x81, 0x81, 0x00, 0xf8, 0xb8, 0x6c, 0x83, 0xb4, 0xbc, 0xd9, 0xa8, 0x57, 0xc0, 0xa5, 0xb4, 0x59, 0x76, 0x8c, 0x54, 0x1d, 0x79, 0xeb, 0x22, 0x52, 0x04, 0x7e, 0xd3, 0x37, 0xeb, 0x41, 0xfd, 0x83, 0xf9, 0xf0, 0xa6, 0x85, 0x15, 0x34, 0x75, 0x71, 0x5a, 0x84, 0xa8, 0x3c, 0xd2, 0xef, 0x5a, 0x4e, 0xd3, 0xde, 0x97, 0x8a, 0xdd, 0xff, 0xbb, 0xcf, 0x0a, 0xaa, 0x86, 0x92, 0xbe, 0xb8, 0x50, 0xe4, 0xcd, 0x6f, 0x80, 0x33, 0x30, 0x76, 0x13, 0x8f, 0xca, 0x7b, 0xdc, 0xec, 0x5a, 0xca, 0x63, 0xc7, 0x03, 0x25, 0xef, 0xa8, 0x8a, 0x83, 0x58, 0x76, 0x20, 0xfa, 0x16, 0x77, 0xd7, 0x79, 0x92, 0x63, 0x01, 0x48, 0x1a, 0xd8, 0x7b, 0x67, 0xf1, 0x52, 0x55, 0x49, 0x4e, 0xd6, 0x6e, 0x4a, 0x5c, 0xd7, 0x7a, 0x37, 0x36, 0x0c, 0xde, 0xdd, 0x8f, 0x44, 0xe8, 0xc2, 0xa7, 0x2c, 0x2b, 0xb5, 0xaf, 0x64, 0x4b, 0x61, 0x07, 0x02, 0x03, 0x01, 0x00, 0x01, 0x02, 0x81, 0x80, 0x74, 0x88, 0x64, 0x3f, 0x69, 0x45, 0x3a, 0x6d, 0xc7, 0x7f, 0xb9, 0xa3, 0xc0, 0x6e, 0xec, 0xdc, 0xd4, 0x5a, 0xb5, 0x32, 0x85, 0x5f, 0x19, 0xd4, 0xf8, 0xd4, 0x3f, 0x3c, 0xfa, 0xc2, 0xf6, 0x5f, 0xee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9b, 0xc4, 0x1e, 0x2f, 0x50, 0x3d, 0xdf, 0x5a, 0xa2, 0x18, 0xca, 0x5f, 0x2e, 0x49, 0xaf, 0x6f, 0xcc, 0xfa, 0x65, 0x77, 0x94, 0xb5, 0xa1, 0x0a, 0xa9, 0xd1, 0x8a, 0x39, 0x37, 0xf4, 0x0b, 0xa0, 0xd7, 0x82, 0x27, 0x5e, 0xae, 0x17, 0x17, 0xa1, 0x1e, 0x54, 0x34, 0xbf, 0x6e, 0xc4, 0x8e, 0x99, 0x5d, 0x08, 0xf1, 0x2d, 0x86, 0x9d, 0xa5, 0x20, 0x1b, 0xe5, 0xdf, }; /* * kExampleRSAKeyPKCS8 is kExampleRSAKeyDER encoded in a PKCS #8 * PrivateKeyInfo. */ static const unsigned char kExampleRSAKeyPKCS8[] = { 0x30, 0x82, 0x02, 0x76, 0x02, 0x01, 0x00, 0x30, 0x0d, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x01, 0x05, 0x00, 0x04, 0x82, 0x02, 0x60, 0x30, 0x82, 0x02, 0x5c, 0x02, 0x01, 0x00, 0x02, 0x81, 0x81, 0x00, 0xf8, 0xb8, 0x6c, 0x83, 0xb4, 0xbc, 0xd9, 0xa8, 0x57, 0xc0, 0xa5, 0xb4, 0x59, 0x76, 0x8c, 0x54, 0x1d, 0x79, 0xeb, 0x22, 0x52, 0x04, 0x7e, 0xd3, 0x37, 0xeb, 0x41, 0xfd, 0x83, 0xf9, 0xf0, 0xa6, 0x85, 0x15, 0x34, 0x75, 0x71, 0x5a, 0x84, 0xa8, 0x3c, 0xd2, 0xef, 0x5a, 0x4e, 0xd3, 0xde, 0x97, 0x8a, 0xdd, 0xff, 0xbb, 0xcf, 0x0a, 0xaa, 0x86, 0x92, 0xbe, 0xb8, 0x50, 0xe4, 0xcd, 0x6f, 0x80, 0x33, 0x30, 0x76, 0x13, 0x8f, 0xca, 0x7b, 0xdc, 0xec, 0x5a, 0xca,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fe, 0x07, 0x2b, 0x0b, 0x63, 0x0b, 0x5a, 0x55, 0x90, 0x71, 0x7d, 0xf1, 0xdb, 0xd9, 0xb1, 0x41, 0x41, 0x68, 0x2f, 0x4e, 0x39, 0x02, 0x40, 0x5a, 0x34, 0x66, 0xd8, 0xf5, 0xe2, 0x7f, 0x18, 0xb5, 0x00, 0x6e, 0x26, 0x84, 0x27, 0x14, 0x93, 0xfb, 0xfc, 0xc6, 0x0f, 0x5e, 0x27, 0xe6, 0xe1, 0xe9, 0xc0, 0x8a, 0xe4, 0x34, 0xda, 0xe9, 0xa2, 0x4b, 0x73, 0xbc, 0x8c, 0xb9, 0xba, 0x13, 0x6c, 0x7a, 0x2b, 0x51, 0x84, 0xa3, 0x4a, 0xe0, 0x30, 0x10, 0x06, 0x7e, 0xed, 0x17, 0x5a, 0x14, 0x00, 0xc9, 0xef, 0x85, 0xea, 0x52, 0x2c, 0xbc, 0x65, 0x02, 0x40, 0x51, 0xe3, 0xf2, 0x83, 0x19, 0x9b, 0xc4, 0x1e, 0x2f, 0x50, 0x3d, 0xdf, 0x5a, 0xa2, 0x18, 0xca, 0x5f, 0x2e, 0x49, 0xaf, 0x6f, 0xcc, 0xfa, 0x65, 0x77, 0x94, 0xb5, 0xa1, 0x0a, 0xa9, 0xd1, 0x8a, 0x39, 0x37, 0xf4, 0x0b, 0xa0, 0xd7, 0x82, 0x27, 0x5e, 0xae, 0x17, 0x17, 0xa1, 0x1e, 0x54, 0x34, 0xbf, 0x6e, 0xc4, 0x8e, 0x99, 0x5d, 0x08, 0xf1, 0x2d, 0x86, 0x9d, 0xa5, 0x20, 0x1b, 0xe5, 0xdf, }; #ifndef OPENSSL_NO_DH static const unsigned char kExampleDHPrivateKeyDER[] = { 0x30, 0x82, 0x02, 0x26, 0x02, 0x01, 0x00, 0x30, 0x82, 0x01, 0x17, 0x06, 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x03, 0x01, 0x30, 0x82, 0x01, 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 0x15, 0x3E, 0x63, 0x37, 0x8C, 0x1B, 0xF1, 0xB3, 0x99, 0xB6, 0xAE, 0x5A, 0xEB, 0xB3, 0x3D, 0x30, 0x39, 0x69, 0xDB, 0xF2, 0x4F, 0x94, 0xB7, 0x71, 0xAF, 0xBA, 0x5C, 0x1F, 0xF8, 0x6B, 0xE5, 0xD1, 0xB1, 0x00, 0x81, 0xE2, 0x6D, 0xEC, 0x65, 0xF7, 0x7E, 0xCE, 0x03, 0x84, 0x68, 0x42, 0x6A, 0x8B, 0x47, 0x8E, 0x4A, 0x88, 0xDE, 0x82, 0xDD, 0xAF, 0xA9, 0x6F, 0x18, 0xF7, 0xC6, 0xE2, 0xB9, 0x97, 0xCE, 0x47, 0x8F, 0x85, 0x19, 0x61, 0x42, 0x67, 0x21, 0x7D, 0x13, 0x6E, 0xB5, 0x5A, 0x62, 0xF3, 0x08, 0xE2, 0x70, 0x3B, 0x0E, 0x85, 0x3C, 0xA1, 0xD3, 0xED, 0x7A, 0x43, 0xD6, 0xDE, 0x30, 0x5C, 0x48, 0xB2, 0x99, 0xAB, 0x3E, 0x65, 0xA6, 0x66, 0x80, 0x22, 0xFF, 0x92, 0xC1, 0x42, 0x1C, 0x30, 0x87, 0x74, 0x1E, 0x53, 0x57, 0x7C, 0xF8, 0x77, 0x51, 0xF1, 0x74, 0x16, 0xF4, 0x45, 0x26, 0x77, 0x0A, 0x05, 0x96, 0x13, 0x12, 0x06, 0x86, 0x2B, 0xB8, 0x49, 0x82, 0x69, 0x43, 0x0A, 0x57, 0xA7, 0x30, 0x19, 0x4C, 0xB8, 0x47, 0x82, 0x6E, 0x64, 0x7A, 0x06, 0x13, 0x5A, 0x82, 0x98, 0xD6, 0x7A, 0x09, 0xEC, 0x03, 0x8D, 0x03 }; #endif /* OPENSSL_NO_DH */ #ifndef OPENSSL_NO_EC /* * kExampleECKeyDER is a sample EC private key encoded as an ECPrivateKey * structure. */ static const unsigned char kExampleECKeyDER[] = { 0x30, 0x77, 0x02, 0x01, 0x01, 0x04, 0x20, 0x07, 0x0f, 0x08, 0x72, 0x7a, 0xd4, 0xa0, 0x4a, 0x9c, 0xdd, 0x59, 0xc9, 0x4d, 0x89, 0x68, 0x77, 0x08, 0xb5, 0x6f, 0xc9, 0x5d, 0x30, 0x77, 0x0e, 0xe8, 0xd1, 0xc9, 0xce, 0x0a, 0x8b, 0xb4, 0x6a, 0xa0, 0x0a, 0x06, 0x08, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x03, 0x01, 0x07, 0xa1, 0x44, 0x03, 0x42, 0x00, 0x04, 0xe6, 0x2b, 0x69, 0xe2, 0xbf, 0x65, 0x9f, 0x97, 0xbe, 0x2f, 0x1e, 0x0d, 0x94, 0x8a, 0x4c, 0xd5, 0x97, 0x6b, 0xb7, 0xa9, 0x1e, 0x0d, 0x46, 0xfb, 0xdd, 0xa9, 0xa9, 0x1e, 0x9d, 0xdc, 0xba, 0x5a, 0x01, 0xe7, 0xd6, 0x97, 0xa8, 0x0a, 0x18, 0xf9, 0xc3, 0xc4, 0xa3, 0x1e, 0x56, 0xe2, 0x7c, 0x83, 0x48, 0xdb, 0x16, 0x1a, 0x1c, 0xf5, 0x1d, 0x7e, 0xf1, 0x94, 0x2d, 0x4b, 0xcf, 0x72, 0x22, 0xc1, }; /* P-384 sample EC private key in PKCS8 format (no public key) */ static const unsigned char kExampleECKey2DER[] = { 0x30, 0x4E, 0x02, 0x01, 0x00, 0x30, 0x10, 0x06, 0x07, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x02, 0x01, 0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x22, 0x04, 0x37, 0x30, 0x35, 0x02, 0x01, 0x01, 0x04, 0x30, 0x73, 0xE3, 0x3A, 0x05, 0xF2, 0xB6, 0x99, 0x6D, 0x0C, 0x33, 0x7F, 0x15, 0x9E, 0x10, 0xA9, 0x17, 0x4C, 0x0A, 0x82, 0x57, 0x71, 0x13, 0x7A, 0xAC, 0x46, 0xA2, 0x5E, 0x1C, 0xE0, 0xC7, 0xB2, 0xF8, 0x20, 0x40, 0xC2, 0x27, 0xC8, 0xBE, 0x02, 0x7E, 0x96, 0x69, 0xE0, 0x04, 0xCB, 0x89, 0x0B, 0x42 }; # ifndef OPENSSL_NO_ECX static const unsigned char kExampleECXKey2DER[] = { 0x30, 0x2E, 0x02, 0x01, 0x00, 0x30, 0x05, 0x06, 0x03, 0x2b, 0x65, 0x6e, 0x04, 0x22, 0x04, 0x20, 0xc8, 0xa9, 0xd5, 0xa9, 0x10, 0x91, 0xad, 0x85, 0x1c, 0x66, 0x8b, 0x07, 0x36, 0xc1, 0xc9, 0xa0, 0x29, 0x36, 0xc0, 0xd3, 0xad, 0x62, 0x67, 0x08, 0x58, 0x08, 0x80, 0x47, 0xba, 0x05, 0x74, 0x75 }; # endif #endif typedef struct APK_DATA_st { const unsigned char *kder; size_t size; int evptype; } APK_DATA; static APK_DATA keydata[] = { {kExampleRSAKeyDER, sizeof(kExampleRSAKeyDER), EVP_PKEY_RSA}, {kExampleRSAKeyPKCS8, sizeof(kExampleRSAKeyPKCS8), EVP_PKEY_RSA}, #ifndef OPENSSL_NO_EC # ifndef OPENSSL_NO_ECX {kExampleECXKey2DER, sizeof(kExampleECXKey2DER), EVP_PKEY_X25519}, # endif {kExampleECKeyDER, sizeof(kExampleECKeyDER), EVP_PKEY_EC}, {kExampleECKey2DER, sizeof(kExampleECKey2DER), EVP_PKEY_EC}, #endif #ifndef OPENSSL_NO_DH {kExampleDHPrivateKeyDER, sizeof(kExampleDHPrivateKeyDER), EVP_PKEY_DH}, #endif }; static int pkey_has_private(EVP_PKEY *key, const char *privtag, int use_octstring) { int ret = 0; if (use_octstring) { unsigned char buf[64]; ret = EVP_PKEY_get_octet_string_param(key, privtag, buf, sizeof(buf), NULL); } else { BIGNUM *bn = NULL; ret = EVP_PKEY_get_bn_param(key, privtag, &bn); BN_free(bn); } return ret; } static int do_pkey_tofrom_data_select(EVP_PKEY *key, const char *keytype) { int ret = 0; OSSL_PARAM *pub_params = NULL, *keypair_params = NULL; EVP_PKEY *fromkey = NULL, *fromkeypair = NULL; EVP_PKEY_CTX *fromctx = NULL; const char *privtag = strcmp(keytype, "RSA") == 0 ? "d" : "priv"; const int use_octstring = strcmp(keytype, "X25519") == 0; /* * Select only the public key component when using EVP_PKEY_todata() and * check that the resulting param array does not contain a private key. */ if (!TEST_int_eq(EVP_PKEY_todata(key, EVP_PKEY_PUBLIC_KEY, &pub_params), 1) || !TEST_ptr_null(OSSL_PARAM_locate(pub_params, privtag))) goto end; /* * Select the keypair when using EVP_PKEY_todata() and check that * the param array contains a private key. */ if (!TEST_int_eq(EVP_PKEY_todata(key, EVP_PKEY_KEYPAIR, &keypair_params), 1) || !TEST_ptr(OSSL_PARAM_locate(keypair_params, privtag))) goto end; /* * Select only the public key when using EVP_PKEY_fromdata() and check that * the resulting key does not contain a private key. */ if (!TEST_ptr(fromctx = EVP_PKEY_CTX_new_from_name(mainctx, keytype, NULL)) || !TEST_int_eq(EVP_PKEY_fromdata_init(fromctx), 1) || !TEST_int_eq(EVP_PKEY_fromdata(fromctx, &fromkey, EVP_PKEY_PUBLIC_KEY, keypair_params), 1) || !TEST_false(pkey_has_private(fromkey, privtag, use_octstring))) goto end; /* * Select the keypair when using EVP_PKEY_fromdata() and check that * the resulting key contains a private key. */ if (!TEST_int_eq(EVP_PKEY_fromdata(fromctx, &fromkeypair, EVP_PKEY_KEYPAIR, keypair_params), 1) || !TEST_true(pkey_has_private(fromkeypair, privtag, use_octstring))) goto end; ret = 1; end: EVP_PKEY_free(fromkeypair); EVP_PKEY_free(fromkey); EVP_PKEY_CTX_free(fromctx); OSSL_PARAM_free(keypair_params); OSSL_PARAM_free(pub_params); return ret; } #ifndef OPENSSL_NO_DH static int test_dh_tofrom_data_select(void) { int ret; OSSL_PARAM params[2]; EVP_PKEY *key = NULL; EVP_PKEY_CTX *gctx = NULL; # ifndef OPENSSL_NO_DEPRECATED_3_0 const DH *dhkey; const BIGNUM *privkey; # endif params[0] = OSSL_PARAM_construct_utf8_string("group", "ffdhe2048", 0); params[1] = OSSL_PARAM_construct_end(); ret = TEST_ptr(gctx = EVP_PKEY_CTX_new_from_name(mainctx, "DHX", NULL)) && TEST_int_gt(EVP_PKEY_keygen_init(gctx), 0) && TEST_true(EVP_PKEY_CTX_set_params(gctx, params)) && TEST_int_gt(EVP_PKEY_generate(gctx, &key), 0) && TEST_true(do_pkey_tofrom_data_select(key, "DHX")); # ifndef OPENSSL_NO_DEPRECATED_3_0 ret = ret && TEST_ptr(dhkey = EVP_PKEY_get0_DH(key)) && TEST_ptr(privkey = DH_get0_priv_key(dhkey)) && TEST_int_le(BN_num_bits(privkey), 225); # endif EVP_PKEY_free(key); EVP_PKEY_CTX_free(gctx); return ret; } static int test_dh_paramgen(void) { int ret; OSSL_PARAM params[3]; EVP_PKEY *pkey = NULL; EVP_PKEY_CTX *gctx = NULL; unsigned int pbits = 512; /* minimum allowed for speed */ params[0] = OSSL_PARAM_construct_uint(OSSL_PKEY_PARAM_FFC_PBITS, &pbits); params[1] = OSSL_PARAM_construct_utf8_string(OSSL_PKEY_PARAM_FFC_TYPE, "generator", 0); params[2] = OSSL_PARAM_construct_end(); ret = TEST_ptr(gctx = EVP_PKEY_CTX_new_from_name(mainctx, "DH", NULL)) && TEST_int_gt(EVP_PKEY_paramgen_init(gctx), 0) && TEST_true(EVP_PKEY_CTX_set_params(gctx, params)) && TEST_true(EVP_PKEY_paramgen(gctx, &pkey)) && TEST_ptr(pkey); EVP_PKEY_CTX_free(gctx); gctx = NULL; ret = ret && TEST_ptr(gctx = EVP_PKEY_CTX_new_from_pkey(mainctx, pkey, NULL)) && TEST_int_eq(EVP_PKEY_param_check(gctx), 1) && TEST_int_eq(EVP_PKEY_param_check_quick(gctx), 1); EVP_PKEY_CTX_free(gctx); EVP_PKEY_free(pkey); return ret; } static int set_fromdata_string(EVP_PKEY_CTX *ctx, const char *name, char *value) { int ret; OSSL_PARAM params[2]; EVP_PKEY *pkey = NULL; if (EVP_PKEY_fromdata_init(ctx) != 1) return -1; params[0] = OSSL_PARAM_construct_utf8_string(name, value, 0); params[1] = OSSL_PARAM_construct_end(); ret = EVP_PKEY_fromdata(ctx, &pkey, EVP_PKEY_KEY_PARAMETERS, params); EVP_PKEY_free(pkey); return ret; } static int set_fromdata_uint(EVP_PKEY_CTX *ctx, const char *name) { int ret; unsigned int tmp = 0; OSSL_PARAM params[2]; EVP_PKEY *pkey = NULL; if (EVP_PKEY_fromdata_init(ctx) != 1) return -1; params[0] = OSSL_PARAM_construct_uint(name, &tmp); params[1] = OSSL_PARAM_construct_end(); ret = EVP_PKEY_fromdata(ctx, &pkey, EVP_PKEY_KEY_PARAMETERS, params); EVP_PKEY_free(pkey); return ret; } static int test_dh_paramfromdata(void) { EVP_PKEY_CTX *ctx = NULL; int ret = 0; /* Test failure paths for FFC - mainly due to setting the wrong param type */ ret = TEST_ptr(ctx = EVP_PKEY_CTX_new_from_name(mainctx, "DH", NULL)) && TEST_int_eq(set_fromdata_uint(ctx, OSSL_PKEY_PARAM_GROUP_NAME), 0) && TEST_int_eq(set_fromdata_string(ctx, OSSL_PKEY_PARAM_GROUP_NAME, "bad"), 0) && TEST_int_eq(set_fromdata_string(ctx, OSSL_PKEY_PARAM_FFC_P, "bad"), 0) && TEST_int_eq(set_fromdata_string(ctx, OSSL_PKEY_PARAM_FFC_GINDEX, "bad"), 0) && TEST_int_eq(set_fromdata_string(ctx, OSSL_PKEY_PARAM_FFC_PCOUNTER, "bad"), 0) && TEST_int_eq(set_fromdata_string(ctx, OSSL_PKEY_PARAM_FFC_COFACTOR, "bad"), 0) && TEST_int_eq(set_fromdata_string(ctx, OSSL_PKEY_PARAM_FFC_H, "bad"), 0) && TEST_int_eq(set_fromdata_uint(ctx, OSSL_PKEY_PARAM_FFC_SEED), 0) && TEST_int_eq(set_fromdata_string(ctx, OSSL_PKEY_PARAM_FFC_VALIDATE_PQ, "bad"), 0) && TEST_int_eq(set_fromdata_string(ctx, OSSL_PKEY_PARAM_FFC_VALIDATE_G, "bad"), 0) && TEST_int_eq(set_fromdata_string(ctx, OSSL_PKEY_PARAM_FFC_VALIDATE_LEGACY, "bad"), 0) && TEST_int_eq(set_fromdata_uint(ctx, OSSL_PKEY_PARAM_FFC_DIGEST), 0); EVP_PKEY_CTX_free(ctx); return ret; } #endif #ifndef OPENSSL_NO_EC static int test_ec_d2i_i2d_pubkey(void) { int ret = 0; FILE *fp = NULL; EVP_PKEY *key = NULL, *outkey = NULL; static const char *filename = "pubkey.der"; if (!TEST_ptr(fp = fopen(filename, "wb")) || !TEST_ptr(key = EVP_PKEY_Q_keygen(mainctx, NULL, "EC", "P-256")) || !TEST_true(i2d_PUBKEY_fp(fp, key)) || !TEST_int_eq(fclose(fp), 0)) goto err; fp = NULL; if (!TEST_ptr(fp = fopen(filename, "rb")) || !TEST_ptr(outkey = d2i_PUBKEY_ex_fp(fp, NULL, mainctx, NULL)) || !TEST_int_eq(EVP_PKEY_eq(key, outkey), 1)) goto err; ret = 1; err: EVP_PKEY_free(outkey); EVP_PKEY_free(key); fclose(fp); return ret; } static int test_ec_tofrom_data_select(void) { int ret; EVP_PKEY *key = NULL; ret = TEST_ptr(key = EVP_PKEY_Q_keygen(mainctx, NULL, "EC", "P-256")) && TEST_true(do_pkey_tofrom_data_select(key, "EC")); EVP_PKEY_free(key); return ret; } # ifndef OPENSSL_NO_ECX static int test_ecx_tofrom_data_select(void) { int ret; EVP_PKEY *key = NULL; ret = TEST_ptr(key = EVP_PKEY_Q_keygen(mainctx, NULL, "X25519")) && TEST_true(do_pkey_tofrom_data_select(key, "X25519")); EVP_PKEY_free(key); return ret; } # endif #endif #ifndef OPENSSL_NO_SM2 static int test_sm2_tofrom_data_select(void) { int ret; EVP_PKEY *key = NULL; ret = TEST_ptr(key = EVP_PKEY_Q_keygen(mainctx, NULL, "SM2")) && TEST_true(do_pkey_tofrom_data_select(key, "SM2")); EVP_PKEY_free(key); return ret; } #endif static int test_rsa_tofrom_data_select(void) { int ret; EVP_PKEY *key = NULL; const unsigned char *pdata = kExampleRSAKeyDER; int pdata_len = sizeof(kExampleRSAKeyDER); ret = TEST_ptr(key = d2i_AutoPrivateKey_ex(NULL, &pdata, pdata_len, mainctx, NULL)) && TEST_true(do_pkey_tofrom_data_select(key, "RSA")); EVP_PKEY_free(key); return ret; } /* This is the equivalent of test_d2i_AutoPrivateKey in evp_extra_test */ static int test_d2i_AutoPrivateKey_ex(int i) { int ret = 0; const unsigned char *p; EVP_PKEY *pkey = NULL; const APK_DATA *ak = &keydata[i]; const unsigned char *input = ak->kder; size_t input_len = ak->size; int expected_id = ak->evptype; BIGNUM *p_bn = NULL; BIGNUM *g_bn = NULL; BIGNUM *priv_bn = NULL; p = input; if (!TEST_ptr(pkey = d2i_AutoPrivateKey_ex(NULL, &p, input_len, mainctx, NULL)) || !TEST_ptr_eq(p, input + input_len) || !TEST_int_eq(EVP_PKEY_get_id(pkey), expected_id)) goto done; if (ak->evptype == EVP_PKEY_RSA) { if (!TEST_true(EVP_PKEY_get_bn_param(pkey, OSSL_PKEY_PARAM_RSA_D, &priv_bn))) goto done; } else if (ak->evptype == EVP_PKEY_X25519) { unsigned char buffer[32]; size_t len; if (!TEST_true(EVP_PKEY_get_octet_string_param(pkey, OSSL_PKEY_PARAM_PRIV_KEY, buffer, sizeof(buffer), &len))) goto done; } else { if (!TEST_true(EVP_PKEY_get_bn_param(pkey, OSSL_PKEY_PARAM_PRIV_KEY, &priv_bn))) goto done; } if (ak->evptype == EVP_PKEY_DH) { if (!TEST_true(EVP_PKEY_get_bn_param(pkey, OSSL_PKEY_PARAM_FFC_P, &p_bn)) || !TEST_true(EVP_PKEY_get_bn_param(pkey, OSSL_PKEY_PARAM_FFC_G, &g_bn))) goto done; } ret = 1; done: BN_free(p_bn); BN_free(g_bn); BN_free(priv_bn); EVP_PKEY_free(pkey); return ret; } #ifndef OPENSSL_NO_DES static int test_pkcs8key_nid_bio(void) { int ret; const int nid = NID_pbe_WithSHA1And3_Key_TripleDES_CBC; static const char pwd[] = "PASSWORD"; EVP_PKEY *pkey = NULL, *pkey_dec = NULL; BIO *in = NULL, *enc_bio = NULL; char *enc_data = NULL; long enc_datalen = 0; OSSL_PROVIDER *provider = NULL; ret = TEST_ptr(provider = OSSL_PROVIDER_load(NULL, "default")) && TEST_ptr(enc_bio = BIO_new(BIO_s_mem())) && TEST_ptr(in = BIO_new_mem_buf(kExampleRSAKeyPKCS8, sizeof(kExampleRSAKeyPKCS8))) && TEST_ptr(pkey = d2i_PrivateKey_ex_bio(in, NULL, NULL, NULL)) && TEST_int_eq(i2d_PKCS8PrivateKey_nid_bio(enc_bio, pkey, nid, pwd, sizeof(pwd) - 1, NULL, NULL), 1) && TEST_int_gt(enc_datalen = BIO_get_mem_data(enc_bio, &enc_data), 0) && TEST_ptr(pkey_dec = d2i_PKCS8PrivateKey_bio(enc_bio, NULL, NULL, (void *)pwd)) && TEST_true(EVP_PKEY_eq(pkey, pkey_dec)); EVP_PKEY_free(pkey_dec); EVP_PKEY_free(pkey); BIO_free(in); BIO_free(enc_bio); OSSL_PROVIDER_unload(provider); return ret; } #endif /* OPENSSL_NO_DES */ static int test_alternative_default(void) { OSSL_LIB_CTX *oldctx; EVP_MD *sha256; int ok = 0; /* * setup_tests() loaded the "null" provider in the current default, so * we know this fetch should fail. */ if (!TEST_ptr_null(sha256 = EVP_MD_fetch(NULL, "SHA2-256", NULL))) goto err; /* * Now we switch to our main library context, and try again. Since no * providers are loaded in this one, it should fall back to the default. */ if (!TEST_ptr(oldctx = OSSL_LIB_CTX_set0_default(mainctx)) || !TEST_ptr(sha256 = EVP_MD_fetch(NULL, "SHA2-256", NULL))) goto err; EVP_MD_free(sha256); sha256 = NULL; /* * Switching back should give us our main library context back, and * fetching SHA2-256 should fail again. */ if (!TEST_ptr_eq(OSSL_LIB_CTX_set0_default(oldctx), mainctx) || !TEST_ptr_null(sha256 = EVP_MD_fetch(NULL, "SHA2-256", NULL))) goto err; ok = 1; err: EVP_MD_free(sha256); return ok; } static int test_provider_unload_effective(int testid) { EVP_MD *sha256 = NULL; OSSL_PROVIDER *provider = NULL; int ok = 0; if (!TEST_ptr(provider = OSSL_PROVIDER_load(NULL, "default")) || !TEST_ptr(sha256 = EVP_MD_fetch(NULL, "SHA2-256", NULL))) goto err; if (testid > 0) { OSSL_PROVIDER_unload(provider); provider = NULL; EVP_MD_free(sha256); sha256 = NULL; } else { EVP_MD_free(sha256); sha256 = NULL; OSSL_PROVIDER_unload(provider); provider = NULL; } /* * setup_tests() loaded the "null" provider in the current default, and * we unloaded it above after the load so we know this fetch should fail. */ if (!TEST_ptr_null(sha256 = EVP_MD_fetch(NULL, "SHA2-256", NULL))) goto err; ok = 1; err: EVP_MD_free(sha256); OSSL_PROVIDER_unload(provider); return ok; } static int test_d2i_PrivateKey_ex(int testid) { int ok = 0; OSSL_PROVIDER *provider = NULL; BIO *key_bio = NULL; EVP_PKEY *pkey = NULL; int id = (testid == 0) ? 0 : 2; if (!TEST_ptr(provider = OSSL_PROVIDER_load(NULL, "default"))) goto err; if (!TEST_ptr(key_bio = BIO_new_mem_buf(keydata[id].kder, keydata[id].size))) goto err; if (!TEST_ptr_null(pkey = PEM_read_bio_PrivateKey(key_bio, NULL, NULL, NULL))) goto err; ERR_clear_error(); if (!TEST_int_ge(BIO_seek(key_bio, 0), 0)) goto err; ok = TEST_ptr(pkey = d2i_PrivateKey_bio(key_bio, NULL)); TEST_int_eq(ERR_peek_error(), 0); test_openssl_errors(); err: EVP_PKEY_free(pkey); BIO_free(key_bio); OSSL_PROVIDER_unload(provider); return ok; } static int test_PEM_read_bio_negative(int testid) { int ok = 0; OSSL_PROVIDER *provider = NULL; BIO *key_bio = NULL; EVP_PKEY *pkey = NULL; if (!TEST_ptr(key_bio = BIO_new_mem_buf(keydata[testid].kder, keydata[testid].size))) goto err; ERR_clear_error(); if (!TEST_ptr_null(pkey = PEM_read_bio_PrivateKey(key_bio, NULL, NULL, NULL))) goto err; if (!TEST_int_ne(ERR_peek_error(), 0)) goto err; if (!TEST_ptr(provider = OSSL_PROVIDER_load(NULL, "default"))) goto err; if (!TEST_int_ge(BIO_seek(key_bio, 0), 0)) goto err; ERR_clear_error(); if (!TEST_ptr_null(pkey = PEM_read_bio_PrivateKey(key_bio, NULL, NULL, NULL))) goto err; if (!TEST_int_ne(ERR_peek_error(), 0)) goto err; ok = 1; err: test_openssl_errors(); EVP_PKEY_free(pkey); BIO_free(key_bio); OSSL_PROVIDER_unload(provider); return ok; } static int test_PEM_read_bio_negative_wrong_password(int testid) { int ok = 0; OSSL_PROVIDER *provider = OSSL_PROVIDER_load(NULL, "default"); EVP_PKEY *read_pkey = NULL; EVP_PKEY *write_pkey = EVP_RSA_gen(1024); BIO *key_bio = BIO_new(BIO_s_mem()); const UI_METHOD *undo_ui_method = NULL; const UI_METHOD *ui_method = NULL; if (testid > 0) ui_method = UI_null(); if (!TEST_ptr(provider)) goto err; if (!TEST_ptr(key_bio)) goto err; if (!TEST_ptr(write_pkey)) goto err; undo_ui_method = UI_get_default_method(); UI_set_default_method(ui_method); if (/* Output Encrypted private key in PEM form */ !TEST_true(PEM_write_bio_PrivateKey(key_bio, write_pkey, EVP_aes_256_cbc(), NULL, 0, NULL, "pass"))) goto err; ERR_clear_error(); read_pkey = PEM_read_bio_PrivateKey(key_bio, NULL, NULL, NULL); if (!TEST_ptr_null(read_pkey)) goto err; if (!TEST_int_eq(ERR_GET_REASON(ERR_get_error()), PEM_R_PROBLEMS_GETTING_PASSWORD)) goto err; ok = 1; err: test_openssl_errors(); EVP_PKEY_free(read_pkey); EVP_PKEY_free(write_pkey); BIO_free(key_bio); OSSL_PROVIDER_unload(provider); UI_set_default_method(undo_ui_method); return ok; } static int do_fromdata_key_is_equal(const OSSL_PARAM params[], const EVP_PKEY *expected, const char *type) { EVP_PKEY_CTX *ctx = NULL; EVP_PKEY *pkey = NULL; int ret; ret = TEST_ptr(ctx = EVP_PKEY_CTX_new_from_name(mainctx, type, NULL)) && TEST_int_eq(EVP_PKEY_fromdata_init(ctx), 1) && TEST_int_eq(EVP_PKEY_fromdata(ctx, &pkey, EVP_PKEY_KEYPAIR, (OSSL_PARAM *)params), 1) && TEST_true(EVP_PKEY_eq(pkey, expected)); EVP_PKEY_CTX_free(ctx); EVP_PKEY_free(pkey); return ret; } #ifndef OPENSSL_NO_DSA /* * This data was generated using: * > openssl genpkey \ * -genparam -algorithm DSA -pkeyopt type:fips186_4 -text \ * -pkeyopt gindex:5 -out dsa_param.pem * > openssl genpkey \ * -paramfile dsa_param.pem -pkeyopt type:fips186_4 -out dsa_priv.pem */ static const unsigned char dsa_key[] = { 0x30, 0x82, 0x03, 0x4e, 0x02, 0x01, 0x00, 0x02, 0x82, 0x01, 0x01, 0x00, 0xda, 0xb3, 0x46, 0x4d, 0x54, 0x57, 0xc7, 0xb4, 0x61, 0xa0, 0x6f, 0x66, 0x17, 0xda, 0xeb, 0x90, 0xf0, 0xa3, 0xd1, 0x29, 0xc9, 0x5f, 0xf2, 0x21, 0x3d, 0x85, 0xa3, 0x4a, 0xf0, 0xf8, 0x36, 0x39, 0x1b, 0xe3, 0xee, 0x37, 0x70, 0x06, 0x9b, 0xe8, 0xe3, 0x0a, 0xd2, 0xf1, 0xf6, 0xc4, 0x42, 0x23, 0x1f, 0x74, 0x78, 0xc2, 0x16, 0xf5, 0xce, 0xd6, 0xab, 0xa0, 0xc6, 0xe8, 0x99, 0x3d, 0xf8, 0x8b, 0xfb, 0x47, 0xf8, 0x5e, 0x05, 0x68, 0x6d, 0x8b, 0xa8, 0xad, 0xa1, 0xc2, 0x3a, 0x4e, 0xe0, 0xad, 0xec, 0x38, 0x75, 0x21, 0x55, 0x22, 0xce, 0xa2, 0xe9, 0xe5, 0x3b, 0xd7, 0x44, 0xeb, 0x5a, 0x03, 0x59, 0xa0, 0xc5, 0x7a, 0x92, 0x59, 0x7d, 0x7a, 0x07, 0x80, 0xfc, 0x4e, 0xf8, 0x56, 0x7e, 0xf1, 0x06, 0xe0, 0xba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63, 0x56, 0x72, 0x7c, 0x4e, 0x6c, 0xad, 0x5f, 0x26, 0x8c, 0xd2, 0x80, 0x41, 0xaf, 0x88, 0x23, 0x20, 0x03, 0xa4, 0xd5, 0x3c, 0x53, 0x54, 0xb0, 0x3d, 0xed, 0x0e, 0x9e, 0x53, 0x0a, 0x63, 0x5f, 0xfd, 0x28, 0x57, 0x09, 0x07, 0x73, 0xf4, 0x0c, 0xd4, 0x71, 0x5d, 0x6b, 0xa0, 0xd7, 0x86, 0x99, 0x29, 0x9b, 0xca, 0xfb, 0xcc, 0xd6, 0x2f, 0xfe, 0xbe, 0x94, 0xef, 0x1a, 0x0e, 0x55, 0x84, 0xa7, 0xaf, 0x7b, 0xfa, 0xed, 0x77, 0x61, 0x28, 0x22, 0xee, 0x6b, 0x11, 0xdd, 0xb0, 0x17, 0x1e, 0x06, 0xe4, 0x29, 0x4c, 0xc2, 0x3f, 0xd6, 0x75, 0xb6, 0x08, 0x04, 0x55, 0x13, 0x48, 0x4f, 0x44, 0xea, 0x8d, 0xaf, 0xcb, 0xac, 0x22, 0xc4, 0x6a, 0xb3, 0x86, 0xe5, 0x47, 0xa9, 0xb5, 0x72, 0x17, 0x23, 0x11, 0x81, 0x7f, 0x00, 0x00, 0x67, 0x5c, 0xf4, 0x58, 0xcc, 0xe2, 0x46, 0xce, 0xf5, 0x6d, 0xd8, 0x18, 0x91, 0xc4, 0x20, 0xbf, 0x07, 0x48, 0x45, 0xfd, 0x02, 0x1c, 0x2f, 0x68, 0x44, 0xcb, 0xfb, 0x6b, 0xcb, 0x8d, 0x02, 0x49, 0x7c, 0xee, 0xd2, 0xa6, 0xd3, 0x43, 0xb8, 0xa4, 0x09, 0xb7, 0xc1, 0xd4, 0x4b, 0xc3, 0x66, 0xa7, 0xe0, 0x21, }; static const unsigned char dsa_p[] = { 0x00, 0xda, 0xb3, 0x46, 0x4d, 0x54, 0x57, 0xc7, 0xb4, 0x61, 0xa0, 0x6f, 0x66, 0x17, 0xda, 0xeb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56, 0x85, 0x49, 0x21, 0x43, 0x12, 0x79, 0xbd, 0xa0, 0x70, 0x47, 0x2f, 0xae, 0xb6, 0xd7, 0x6c, 0xc6, 0x07, 0x76, 0xa9, 0x8a, 0xa2, 0x16, 0x02, 0x89, 0x1f, 0x1a, 0xd1, 0xa2, 0x96, 0x56, 0xd1, 0x1f, 0x10, 0xe1, 0xe5, 0x9f, 0x3f, 0xdd, 0x09, 0x0c, 0x40, 0x90, 0x71, 0xef, 0x14, 0x41, 0x02, 0x82, 0x3a, 0x6b, 0xe1, 0xf8, 0x2c, 0x5d, 0xbe, 0xfd, 0x1b }; static const unsigned char dsa_q[] = { 0x00, 0xe0, 0x20, 0xe0, 0x7c, 0x02, 0x16, 0xa7, 0x6c, 0x6a, 0x19, 0xba, 0xd5, 0x83, 0x73, 0xf3, 0x7d, 0x31, 0xef, 0xa7, 0xe1, 0x5d, 0x5b, 0x7f, 0xf3, 0xfc, 0xda, 0x84, 0x31 }; static const unsigned char dsa_g[] = { 0x00, 0x83, 0xdb, 0xa1, 0xbc, 0x3e, 0xc7, 0x29, 0xa5, 0x6a, 0x5c, 0x2c, 0xe8, 0x7a, 0x8c, 0x7e, 0xe8, 0xb8, 0x3e, 0x13, 0x47, 0xcd, 0x36, 0x7e, 0x79, 0x30, 0x7a, 0x28, 0x03, 0xd3, 0xd4, 0xd2, 0xe3, 0xee, 0x3b, 0x46, 0xda, 0xe0, 0x71, 0xe6, 0xcf, 0x46, 0x86, 0x0a, 0x37, 0x57, 0xb6, 0xe9, 0xcf, 0xa1, 0x78, 0x19, 0xb8, 0x72, 0x9f, 0x30, 0x8c, 0x2a, 0x04, 0x7c, 0x2f, 0x0c, 0x27, 0xa7, 0xb3, 0x23, 0xe0, 0x46, 0xf2, 0x75, 0x0c, 0x03, 0x4c, 0xad, 0xfb, 0xc1, 0xcb, 0x28, 0xcd, 0xa0, 0x63, 0xdb, 0x44, 0x88, 0xe0, 0xda, 0x6c, 0x5b, 0x89, 0xb2, 0x5b, 0x40, 0x6d, 0xeb, 0x78, 0x7a, 0xd5, 0xaf, 0x40, 0x52, 0x46, 0x63, 0x92, 0x13, 0x0d, 0xee, 0xee, 0xf9, 0x53, 0xca, 0x2d, 0x4e, 0x3b, 0x13, 0xd8, 0x0f, 0x50, 0xd0, 0x44, 0x57, 0x67, 0x0f, 0x45, 0x8f, 0x21, 0x30, 0x97, 0x9e, 0x80, 0xd9, 0xd0, 0x91, 0xb7, 0xc9, 0x5a, 0x69, 0xda, 0xeb, 0xd5, 0xea, 0x37, 0xf6, 0xb3, 0xbe, 0x1f, 0x24, 0xf1, 0x55, 0x14, 0x28, 0x05, 0xb5, 0xd8, 0x84, 0x0f, 0x62, 0x85, 0xaa, 0xec, 0x77, 0x64, 0xfd, 0x80, 0x7c, 0x41, 0x00, 0x88, 0xa3, 0x79, 0x7d, 0x4f, 0x6f, 0xe3, 0x76, 0xf4, 0xb5, 0x97, 0xb7, 0xeb, 0x67, 0x28, 0xba, 0x07, 0x1a, 0x59, 0x32, 0xc1, 0x53, 0xd9, 0x05, 0x6b, 0x63, 0x93, 0xce, 0xa1, 0xd9, 0x7a, 0xb2, 0xff, 0x1c, 0x12, 0x0a, 0x9a, 0xe5, 0x51, 0x1e, 0xba, 0xfc, 0x95, 0x2e, 0x28, 0xa9, 0xfc, 0x4c, 0xed, 0x7b, 0x05, 0xca, 0x67, 0xe0, 0x2d, 0xd7, 0x54, 0xb3, 0x05, 0x1c, 0x23, 0x2b, 0x35, 0x2e, 0x19, 0x48, 0x59, 0x0e, 0x58, 0xa8, 0x01, 0x56, 0xfb, 0x78, 0x90, 0xba, 0x08, 0x77, 0x94, 0x45, 0x05, 0x13, 0xc7, 0x6b, 0x96, 0xd2, 0xa3, 0xa6, 0x01, 0x9f, 0x34 }; static const unsigned char dsa_priv[] = { 0x2f, 0x68, 0x44, 0xcb, 0xfb, 0x6b, 0xcb, 0x8d, 0x02, 0x49, 0x7c, 0xee, 0xd2, 0xa6, 0xd3, 0x43, 0xb8, 0xa4, 0x09, 0xb7, 0xc1, 0xd4, 0x4b, 0xc3, 0x66, 0xa7, 0xe0, 0x21 }; static const unsigned char dsa_pub[] = { 0x16, 0x1a, 0xb4, 0x6d, 0x9f, 0x16, 0x6c, 0xcc, 0x91, 0x66, 0xfe, 0x30, 0xeb, 0x8e, 0x44, 0xba, 0x2b, 0x7a, 0xc9, 0xa8, 0x95, 0xf2, 0xa6, 0x38, 0xd8, 0xaf, 0x3e, 0x91, 0x68, 0xe8, 0x52, 0xf3, 0x97, 0x37, 0x70, 0xf2, 0x47, 0xa3, 0xf4, 0x62, 0x26, 0xf5, 0x3b, 0x71, 0x52, 0x50, 0x15, 0x9c, 0x6d, 0xa6, 0x6d, 0x92, 0x4c, 0x48, 0x76, 0x31, 0x54, 0x48, 0xa5, 0x99, 0x7a, 0xd4, 0x61, 0xf7, 0x21, 0x44, 0xe7, 0xd8, 0x82, 0xc3, 0x50, 0xd3, 0xd9, 0xd4, 0x66, 0x20, 0xab, 0x70, 0x4c, 0x97, 0x9b, 0x8d, 0xac, 0x1f, 0x78, 0x27, 0x1e, 0x47, 0xf8, 0x3b, 0xd1, 0x55, 0x73, 0xf3, 0xb4, 0x8e, 0x6d, 0x45, 0x40, 0x54, 0xc6, 0xd8, 0x95, 0x15, 0x27, 0xb7, 0x5f, 0x65, 0xaa, 0xcb, 0x24, 0xc9, 0x49, 0x87, 0x32, 0xad, 0xcb, 0xf8, 0x35, 0x63, 0x56, 0x72, 0x7c, 0x4e, 0x6c, 0xad, 0x5f, 0x26, 0x8c, 0xd2, 0x80, 0x41, 0xaf, 0x88, 0x23, 0x20, 0x03, 0xa4, 0xd5, 0x3c, 0x53, 0x54, 0xb0, 0x3d, 0xed, 0x0e, 0x9e, 0x53, 0x0a, 0x63, 0x5f, 0xfd, 0x28, 0x57, 0x09, 0x07, 0x73, 0xf4, 0x0c, 0xd4, 0x71, 0x5d, 0x6b, 0xa0, 0xd7, 0x86, 0x99, 0x29, 0x9b, 0xca, 0xfb, 0xcc, 0xd6, 0x2f, 0xfe, 0xbe, 0x94, 0xef, 0x1a, 0x0e, 0x55, 0x84, 0xa7, 0xaf, 0x7b, 0xfa, 0xed, 0x77, 0x61, 0x28, 0x22, 0xee, 0x6b, 0x11, 0xdd, 0xb0, 0x17, 0x1e, 0x06, 0xe4, 0x29, 0x4c, 0xc2, 0x3f, 0xd6, 0x75, 0xb6, 0x08, 0x04, 0x55, 0x13, 0x48, 0x4f, 0x44, 0xea, 0x8d, 0xaf, 0xcb, 0xac, 0x22, 0xc4, 0x6a, 0xb3, 0x86, 0xe5, 0x47, 0xa9, 0xb5, 0x72, 0x17, 0x23, 0x11, 0x81, 0x7f, 0x00, 0x00, 0x67, 0x5c, 0xf4, 0x58, 0xcc, 0xe2, 0x46, 0xce, 0xf5, 0x6d, 0xd8, 0x18, 0x91, 0xc4, 0x20, 0xbf, 0x07, 0x48, 0x45, 0xfd }; static int do_check_params(OSSL_PARAM key_params[], int expected) { EVP_PKEY_CTX *gen_ctx = NULL, *check_ctx = NULL; EVP_PKEY *pkey = NULL; int ret; ret = TEST_ptr(gen_ctx = EVP_PKEY_CTX_new_from_name(mainctx, "DSA", NULL)) && TEST_int_eq(EVP_PKEY_fromdata_init(gen_ctx), 1) && TEST_int_eq(EVP_PKEY_fromdata(gen_ctx, &pkey, EVP_PKEY_KEYPAIR, key_params), 1) && TEST_ptr(check_ctx = EVP_PKEY_CTX_new_from_pkey(mainctx, pkey, NULL)) && TEST_int_eq(EVP_PKEY_param_check(check_ctx), expected); EVP_PKEY_CTX_free(check_ctx); EVP_PKEY_CTX_free(gen_ctx); EVP_PKEY_free(pkey); return ret; } static int do_check_bn(OSSL_PARAM params[], const char *key, const unsigned char *expected, size_t expected_len) { OSSL_PARAM *p; BIGNUM *bn = NULL; unsigned char buffer[256 + 1]; int ret, len; ret = TEST_ptr(p = OSSL_PARAM_locate(params, key)) && TEST_true(OSSL_PARAM_get_BN(p, &bn)) && TEST_int_gt(len = BN_bn2binpad(bn, buffer, expected_len), 0) && TEST_mem_eq(expected, expected_len, buffer, len); BN_free(bn); return ret; } static int do_check_int(OSSL_PARAM params[], const char *key, int expected) { OSSL_PARAM *p; int val = 0; return TEST_ptr(p = OSSL_PARAM_locate(params, key)) && TEST_true(OSSL_PARAM_get_int(p, &val)) && TEST_int_eq(val, expected); } static int test_dsa_tofrom_data_select(void) { int ret; EVP_PKEY *key = NULL; const unsigned char *pkeydata = dsa_key; ret = TEST_ptr(key = d2i_AutoPrivateKey_ex(NULL, &pkeydata, sizeof(dsa_key), mainctx, NULL)) && TEST_true(do_pkey_tofrom_data_select(key, "DSA")); EVP_PKEY_free(key); return ret; } static int test_dsa_todata(void) { EVP_PKEY *pkey = NULL; OSSL_PARAM *to_params = NULL, *all_params = NULL; OSSL_PARAM gen_params[4]; int ret = 0; const unsigned char *pkeydata = dsa_key; unsigned char dsa_seed[] = { 0xbc, 0x8a, 0x81, 0x64, 0x9e, 0x9d, 0x63, 0xa7, 0xa3, 0x5d, 0x87, 0xdd, 0x32, 0xf3, 0xc1, 0x9f, 0x18, 0x22, 0xeb, 0x73, 0x63, 0xad, 0x5e, 0x7b, 0x90, 0xc1, 0xe3, 0xe0 }; int dsa_pcounter = 319; int dsa_gindex = 5; gen_params[0] = OSSL_PARAM_construct_octet_string(OSSL_PKEY_PARAM_FFC_SEED, (void*)dsa_seed, sizeof(dsa_seed)); gen_params[1] = OSSL_PARAM_construct_int(OSSL_PKEY_PARAM_FFC_GINDEX, &dsa_gindex); gen_params[2] = OSSL_PARAM_construct_int(OSSL_PKEY_PARAM_FFC_PCOUNTER, &dsa_pcounter); gen_params[3] = OSSL_PARAM_construct_end(); if (!TEST_ptr(pkey = d2i_AutoPrivateKey_ex(NULL, &pkeydata, sizeof(dsa_key), mainctx, NULL)) || !TEST_int_eq(EVP_PKEY_todata(pkey, EVP_PKEY_KEYPAIR, &to_params), 1) || !do_check_bn(to_params, OSSL_PKEY_PARAM_FFC_P, dsa_p, sizeof(dsa_p)) || !do_check_bn(to_params, OSSL_PKEY_PARAM_FFC_Q, dsa_q, sizeof(dsa_q)) || !do_check_bn(to_params, OSSL_PKEY_PARAM_FFC_G, dsa_g, sizeof(dsa_g)) || !do_check_bn(to_params, OSSL_PKEY_PARAM_PUB_KEY, dsa_pub, sizeof(dsa_pub)) || !do_check_bn(to_params, OSSL_PKEY_PARAM_PRIV_KEY, dsa_priv, sizeof(dsa_priv)) || !do_check_int(to_params, OSSL_PKEY_PARAM_FFC_GINDEX, -1) || !do_check_int(to_params, OSSL_PKEY_PARAM_FFC_PCOUNTER, -1) || !do_check_int(to_params, OSSL_PKEY_PARAM_FFC_H, 0) || !do_check_int(to_params, OSSL_PKEY_PARAM_FFC_VALIDATE_PQ, 1) || !do_check_int(to_params, OSSL_PKEY_PARAM_FFC_VALIDATE_G, 1) || !do_check_int(to_params, OSSL_PKEY_PARAM_FFC_VALIDATE_LEGACY, 0) || !TEST_ptr_null(OSSL_PARAM_locate(to_params, OSSL_PKEY_PARAM_FFC_SEED))) goto err; if (!do_fromdata_key_is_equal(to_params, pkey, "DSA")) goto err; if (!TEST_ptr(all_params = OSSL_PARAM_merge(to_params, gen_params)) || !do_check_params(all_params, 1)) goto err; gen_params[1] = OSSL_PARAM_construct_int(OSSL_PKEY_PARAM_FFC_GINDEX, &dsa_gindex); gen_params[2] = OSSL_PARAM_construct_int(OSSL_PKEY_PARAM_FFC_PCOUNTER, &dsa_pcounter); /* * Check that modifying the shallow copy values used in OSSL_PARAM_merge() * results in an invalid key. This also verifies that the fips186-4 * validation code is running. */ dsa_gindex++; if (!do_check_params(all_params, 0)) goto err; dsa_gindex--; dsa_pcounter++; if (!do_check_params(all_params, 0)) goto err; dsa_pcounter--; dsa_seed[0] = 0xb0; if (!do_check_params(all_params, 0)) goto err; ret = 1; err: EVP_PKEY_free(pkey); OSSL_PARAM_free(all_params); OSSL_PARAM_free(to_params); return ret; } /* * Test that OSSL_PKEY_PARAM_FFC_DIGEST_PROPS is set properly when using fromdata * This test: * checks for failure when the property query is bad (tstid == 0) * checks for success when the property query is valid (tstid == 1) */ static int test_dsa_fromdata_digest_prop(int tstid) { EVP_PKEY_CTX *ctx = NULL, *gctx = NULL; EVP_PKEY *pkey = NULL, *pkey2 = NULL; OSSL_PARAM params[4], *p = params; int ret = 0; int expected = (tstid == 0 ? 0 : 1); unsigned int pbits = 512; /* minimum allowed for speed */ *p++ = OSSL_PARAM_construct_uint(OSSL_PKEY_PARAM_FFC_PBITS, &pbits); *p++ = OSSL_PARAM_construct_utf8_string(OSSL_PKEY_PARAM_FFC_DIGEST, "SHA512", 0); /* Setting a bad prop query here should fail during paramgen - when it tries to do a fetch */ *p++ = OSSL_PARAM_construct_utf8_string(OSSL_PKEY_PARAM_FFC_DIGEST_PROPS, tstid == 0 ? "provider=unknown" : "provider=default", 0); *p++ = OSSL_PARAM_construct_end(); if (!TEST_ptr(ctx = EVP_PKEY_CTX_new_from_name(mainctx, "DSA", NULL)) || !TEST_int_eq(EVP_PKEY_fromdata_init(ctx), 1) || !TEST_int_eq(EVP_PKEY_fromdata(ctx, &pkey, EVP_PKEY_KEY_PARAMETERS, params), 1)) goto err; if (!TEST_ptr(gctx = EVP_PKEY_CTX_new_from_pkey(mainctx, pkey, NULL)) || !TEST_int_eq(EVP_PKEY_paramgen_init(gctx), 1) || !TEST_int_eq(EVP_PKEY_paramgen(gctx, &pkey2), expected)) goto err; ret = 1; err: EVP_PKEY_free(pkey2); EVP_PKEY_free(pkey); EVP_PKEY_CTX_free(ctx); EVP_PKEY_CTX_free(gctx); return ret; } #endif /* OPENSSL_NO_DSA */ static int test_pkey_todata_null(void) { OSSL_PARAM *params = NULL; EVP_PKEY *pkey = NULL; int ret = 0; const unsigned char *pdata = keydata[0].kder; ret = TEST_ptr(pkey = d2i_AutoPrivateKey_ex(NULL, &pdata, keydata[0].size, mainctx, NULL)) && TEST_int_eq(EVP_PKEY_todata(NULL, EVP_PKEY_KEYPAIR, &params), 0) && TEST_int_eq(EVP_PKEY_todata(pkey, EVP_PKEY_KEYPAIR, NULL), 0); EVP_PKEY_free(pkey); return ret; } static OSSL_CALLBACK test_pkey_export_cb; static int test_pkey_export_cb(const OSSL_PARAM params[], void *arg) { if (arg == NULL) return 0; return do_fromdata_key_is_equal(params, (EVP_PKEY *)arg, "RSA"); } static int test_pkey_export_null(void) { EVP_PKEY *pkey = NULL; int ret = 0; const unsigned char *pdata = keydata[0].kder; ret = TEST_ptr(pkey = d2i_AutoPrivateKey_ex(NULL, &pdata, keydata[0].size, mainctx, NULL)) && TEST_int_eq(EVP_PKEY_export(NULL, EVP_PKEY_KEYPAIR, test_pkey_export_cb, NULL), 0) && TEST_int_eq(EVP_PKEY_export(pkey, EVP_PKEY_KEYPAIR, NULL, NULL), 0); EVP_PKEY_free(pkey); return ret; } static int test_pkey_export(void) { EVP_PKEY *pkey = NULL; #ifndef OPENSSL_NO_DEPRECATED_3_0 RSA *rsa = NULL; #endif int ret = 1; const unsigned char *pdata = keydata[0].kder; int pdata_len = keydata[0].size; if (!TEST_ptr(pkey = d2i_AutoPrivateKey_ex(NULL, &pdata, pdata_len, mainctx, NULL)) || !TEST_true(EVP_PKEY_export(pkey, EVP_PKEY_KEYPAIR, test_pkey_export_cb, pkey)) || !TEST_false(EVP_PKEY_export(pkey, EVP_PKEY_KEYPAIR, test_pkey_export_cb, NULL))) ret = 0; EVP_PKEY_free(pkey); #ifndef OPENSSL_NO_DEPRECATED_3_0 /* Now, try with a legacy key */ pdata = keydata[0].kder; pdata_len = keydata[0].size; if (!TEST_ptr(rsa = d2i_RSAPrivateKey(NULL, &pdata, pdata_len)) || !TEST_ptr(pkey = EVP_PKEY_new()) || !TEST_true(EVP_PKEY_assign_RSA(pkey, rsa)) || !TEST_true(EVP_PKEY_export(pkey, EVP_PKEY_KEYPAIR, test_pkey_export_cb, pkey)) || !TEST_false(EVP_PKEY_export(pkey, EVP_PKEY_KEYPAIR, test_pkey_export_cb, NULL))) ret = 0; EVP_PKEY_free(pkey); #endif return ret; } static int test_rsa_pss_sign(void) { EVP_PKEY *pkey = NULL; EVP_PKEY_CTX *pctx = NULL; int ret = 0; const unsigned char *pdata = keydata[0].kder; const char *mdname = "SHA2-256"; OSSL_PARAM sig_params[3]; unsigned char mdbuf[256 / 8] = { 0 }; int padding = RSA_PKCS1_PSS_PADDING; unsigned char *sig = NULL; size_t sig_len = 0; sig_params[0] = OSSL_PARAM_construct_int(OSSL_PKEY_PARAM_PAD_MODE, &padding); sig_params[1] = OSSL_PARAM_construct_utf8_string(OSSL_SIGNATURE_PARAM_DIGEST, (char *)mdname, 0); sig_params[2] = OSSL_PARAM_construct_end(); ret = TEST_ptr(pkey = d2i_AutoPrivateKey_ex(NULL, &pdata, keydata[0].size, mainctx, NULL)) && TEST_ptr(pctx = EVP_PKEY_CTX_new_from_pkey(mainctx, pkey, NULL)) && TEST_int_gt(EVP_PKEY_sign_init_ex(pctx, sig_params), 0) && TEST_int_gt(EVP_PKEY_sign(pctx, NULL, &sig_len, mdbuf, sizeof(mdbuf)), 0) && TEST_int_gt(sig_len, 0) && TEST_ptr(sig = OPENSSL_malloc(sig_len)) && TEST_int_gt(EVP_PKEY_sign(pctx, sig, &sig_len, mdbuf, sizeof(mdbuf)), 0); EVP_PKEY_CTX_free(pctx); OPENSSL_free(sig); EVP_PKEY_free(pkey); return ret; } static int test_evp_md_ctx_dup(void) { EVP_MD_CTX *mdctx; EVP_MD_CTX *copyctx = NULL; int ret; /* test copying freshly initialized context */ ret = TEST_ptr(mdctx = EVP_MD_CTX_new()) && TEST_ptr(copyctx = EVP_MD_CTX_dup(mdctx)); EVP_MD_CTX_free(mdctx); EVP_MD_CTX_free(copyctx); return ret; } static int test_evp_md_ctx_copy(void) { EVP_MD_CTX *mdctx = NULL; EVP_MD_CTX *copyctx = NULL; int ret; /* test copying freshly initialized context */ ret = TEST_ptr(mdctx = EVP_MD_CTX_new()) && TEST_ptr(copyctx = EVP_MD_CTX_new()) && TEST_true(EVP_MD_CTX_copy_ex(copyctx, mdctx)); EVP_MD_CTX_free(mdctx); EVP_MD_CTX_free(copyctx); return ret; } #if !defined OPENSSL_NO_DES && !defined OPENSSL_NO_MD5 static int test_evp_pbe_alg_add(void) { int ret = 0; int cipher_nid = 0, md_nid = 0; EVP_PBE_KEYGEN_EX *keygen_ex = NULL; EVP_PBE_KEYGEN *keygen = NULL; if (!TEST_true(EVP_PBE_alg_add(NID_pbeWithMD5AndDES_CBC, EVP_des_cbc(), EVP_md5(), PKCS5_PBE_keyivgen))) goto err; if (!TEST_true(EVP_PBE_find_ex(EVP_PBE_TYPE_OUTER, NID_pbeWithMD5AndDES_CBC, &cipher_nid, &md_nid, &keygen, &keygen_ex))) goto err; if (!TEST_true(keygen != NULL)) goto err; if (!TEST_true(keygen_ex == NULL)) goto err; ret = 1; err: return ret; } #endif /* * Currently, EVP_<OBJ>_fetch doesn't support * colon separated alternative names for lookup * so add a test here to ensure that when one is provided * libcrypto returns an error */ static int evp_test_name_parsing(void) { EVP_MD *md; if (!TEST_ptr_null(md = EVP_MD_fetch(mainctx, "SHA256:BogusName", NULL))) { EVP_MD_free(md); return 0; } return 1; } int setup_tests(void) { if (!test_get_libctx(&mainctx, &nullprov, NULL, NULL, NULL)) { OSSL_LIB_CTX_free(mainctx); mainctx = NULL; return 0; } ADD_TEST(evp_test_name_parsing); ADD_TEST(test_alternative_default); ADD_ALL_TESTS(test_d2i_AutoPrivateKey_ex, OSSL_NELEM(keydata)); #ifndef OPENSSL_NO_EC ADD_ALL_TESTS(test_d2i_PrivateKey_ex, 2); ADD_TEST(test_ec_tofrom_data_select); # ifndef OPENSSL_NO_ECX ADD_TEST(test_ecx_tofrom_data_select); # endif ADD_TEST(test_ec_d2i_i2d_pubkey); #else ADD_ALL_TESTS(test_d2i_PrivateKey_ex, 1); #endif #ifndef OPENSSL_NO_SM2 ADD_TEST(test_sm2_tofrom_data_select); #endif #ifndef OPENSSL_NO_DSA ADD_TEST(test_dsa_todata); ADD_TEST(test_dsa_tofrom_data_select); ADD_ALL_TESTS(test_dsa_fromdata_digest_prop, 2); #endif #ifndef OPENSSL_NO_DH ADD_TEST(test_dh_tofrom_data_select); ADD_TEST(test_dh_paramgen); ADD_TEST(test_dh_paramfromdata); #endif ADD_TEST(test_rsa_tofrom_data_select); ADD_TEST(test_pkey_todata_null); ADD_TEST(test_pkey_export_null); ADD_TEST(test_pkey_export); #ifndef OPENSSL_NO_DES ADD_TEST(test_pkcs8key_nid_bio); #endif ADD_ALL_TESTS(test_PEM_read_bio_negative, OSSL_NELEM(keydata)); ADD_ALL_TESTS(test_PEM_read_bio_negative_wrong_password, 2); ADD_TEST(test_rsa_pss_sign); ADD_TEST(test_evp_md_ctx_dup); ADD_TEST(test_evp_md_ctx_copy); ADD_ALL_TESTS(test_provider_unload_effective, 2); #if !defined OPENSSL_NO_DES && !defined OPENSSL_NO_MD5 ADD_TEST(test_evp_pbe_alg_add); #endif return 1; } void cleanup_tests(void) { OSSL_LIB_CTX_free(mainctx); OSSL_PROVIDER_unload(nullprov); }
./openssl/test/secmemtest.c
/* * Copyright 2015-2022 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <openssl/crypto.h> #include "testutil.h" #include "internal/e_os.h" static int test_sec_mem(void) { #ifndef OPENSSL_NO_SECURE_MEMORY int testresult = 0; char *p = NULL, *q = NULL, *r = NULL, *s = NULL; TEST_info("Secure memory is implemented."); s = OPENSSL_secure_malloc(20); /* s = non-secure 20 */ if (!TEST_ptr(s) || !TEST_false(CRYPTO_secure_allocated(s))) goto end; r = OPENSSL_secure_malloc(20); /* r = non-secure 20, s = non-secure 20 */ if (!TEST_ptr(r) || !TEST_true(CRYPTO_secure_malloc_init(4096, 32)) || !TEST_false(CRYPTO_secure_allocated(r))) goto end; p = OPENSSL_secure_malloc(20); if (!TEST_ptr(p) /* r = non-secure 20, p = secure 20, s = non-secure 20 */ || !TEST_true(CRYPTO_secure_allocated(p)) /* 20 secure -> 32-byte minimum allocation unit */ || !TEST_size_t_eq(CRYPTO_secure_used(), 32)) goto end; q = OPENSSL_malloc(20); if (!TEST_ptr(q)) goto end; /* r = non-secure 20, p = secure 20, q = non-secure 20, s = non-secure 20 */ if (!TEST_false(CRYPTO_secure_allocated(q))) goto end; OPENSSL_secure_clear_free(s, 20); s = OPENSSL_secure_malloc(20); if (!TEST_ptr(s) /* r = non-secure 20, p = secure 20, q = non-secure 20, s = secure 20 */ || !TEST_true(CRYPTO_secure_allocated(s)) /* 2 * 20 secure -> 64 bytes allocated */ || !TEST_size_t_eq(CRYPTO_secure_used(), 64)) goto end; OPENSSL_secure_clear_free(p, 20); p = NULL; /* 20 secure -> 32 bytes allocated */ if (!TEST_size_t_eq(CRYPTO_secure_used(), 32)) goto end; OPENSSL_free(q); q = NULL; /* should not complete, as secure memory is still allocated */ if (!TEST_false(CRYPTO_secure_malloc_done()) || !TEST_true(CRYPTO_secure_malloc_initialized())) goto end; OPENSSL_secure_free(s); s = NULL; /* secure memory should now be 0, so done should complete */ if (!TEST_size_t_eq(CRYPTO_secure_used(), 0) || !TEST_true(CRYPTO_secure_malloc_done()) || !TEST_false(CRYPTO_secure_malloc_initialized())) goto end; TEST_info("Possible infinite loop: allocate more than available"); if (!TEST_true(CRYPTO_secure_malloc_init(32768, 16))) goto end; TEST_ptr_null(OPENSSL_secure_malloc((size_t)-1)); TEST_true(CRYPTO_secure_malloc_done()); /* * If init fails, then initialized should be false, if not, this * could cause an infinite loop secure_malloc, but we don't test it */ if (TEST_false(CRYPTO_secure_malloc_init(16, 16)) && !TEST_false(CRYPTO_secure_malloc_initialized())) { TEST_true(CRYPTO_secure_malloc_done()); goto end; } /*- * There was also a possible infinite loop when the number of * elements was 1<<31, as |int i| was set to that, which is a * negative number. However, it requires minimum input values: * * CRYPTO_secure_malloc_init((size_t)1<<34, 1<<4); * * Which really only works on 64-bit systems, since it took 16 GB * secure memory arena to trigger the problem. It naturally takes * corresponding amount of available virtual and physical memory * for test to be feasible/representative. Since we can't assume * that every system is equipped with that much memory, the test * remains disabled. If the reader of this comment really wants * to make sure that infinite loop is fixed, they can enable the * code below. */ # if 0 /*- * On Linux and BSD this test has a chance to complete in minimal * time and with minimum side effects, because mlock is likely to * fail because of RLIMIT_MEMLOCK, which is customarily [much] * smaller than 16GB. In other words Linux and BSD users can be * limited by virtual space alone... */ if (sizeof(size_t) > 4) { TEST_info("Possible infinite loop: 1<<31 limit"); if (TEST_true(CRYPTO_secure_malloc_init((size_t)1<<34, 1<<4) != 0)) TEST_true(CRYPTO_secure_malloc_done()); } # endif /* this can complete - it was not really secure */ testresult = 1; end: OPENSSL_secure_free(p); OPENSSL_free(q); OPENSSL_secure_free(r); OPENSSL_secure_free(s); return testresult; #else TEST_info("Secure memory is *not* implemented."); /* Should fail. */ return TEST_false(CRYPTO_secure_malloc_init(4096, 32)); #endif } static int test_sec_mem_clear(void) { #ifndef OPENSSL_NO_SECURE_MEMORY const int size = 64; unsigned char *p = NULL; int i, res = 0; if (!TEST_true(CRYPTO_secure_malloc_init(4096, 32)) || !TEST_ptr(p = OPENSSL_secure_malloc(size))) goto err; for (i = 0; i < size; i++) if (!TEST_uchar_eq(p[i], 0)) goto err; for (i = 0; i < size; i++) p[i] = (unsigned char)(i + ' ' + 1); OPENSSL_secure_free(p); /* * A deliberate use after free here to verify that the memory has been * cleared properly. Since secure free doesn't return the memory to * libc's memory pool, it technically isn't freed. However, the header * bytes have to be skipped and these consist of two pointers in the * current implementation. */ for (i = sizeof(void *) * 2; i < size; i++) if (!TEST_uchar_eq(p[i], 0)) return 0; res = 1; p = NULL; err: OPENSSL_secure_free(p); CRYPTO_secure_malloc_done(); return res; #else return 1; #endif } int setup_tests(void) { ADD_TEST(test_sec_mem); ADD_TEST(test_sec_mem_clear); return 1; }
./openssl/test/params_conversion_test.c
/* * Copyright 2019-2022 The OpenSSL Project Authors. All Rights Reserved. * Copyright (c) 2019, Oracle and/or its affiliates. All rights reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <string.h> #include <openssl/params.h> #include "testutil.h" /* On machines that dont support <inttypes.h> just disable the tests */ #if !defined(OPENSSL_NO_INTTYPES_H) # ifdef OPENSSL_SYS_VMS # define strtoumax strtoull # define strtoimax strtoll # endif typedef struct { OSSL_PARAM *param; int32_t i32; int64_t i64; uint32_t u32; uint64_t u64; double d; int valid_i32, valid_i64, valid_u32, valid_u64, valid_d; void *ref, *datum; size_t size; } PARAM_CONVERSION; static int param_conversion_load_stanza(PARAM_CONVERSION *pc, const STANZA *s) { static int32_t datum_i32, ref_i32; static int64_t datum_i64, ref_i64; static uint32_t datum_u32, ref_u32; static uint64_t datum_u64, ref_u64; static double datum_d, ref_d; static OSSL_PARAM params[] = { OSSL_PARAM_int32("int32", &datum_i32), OSSL_PARAM_int64("int64", &datum_i64), OSSL_PARAM_uint32("uint32", &datum_u32), OSSL_PARAM_uint64("uint64", &datum_u64), OSSL_PARAM_double("double", &datum_d), OSSL_PARAM_END }; int def_i32 = 0, def_i64 = 0, def_u32 = 0, def_u64 = 0, def_d = 0; const PAIR *pp = s->pairs; const char *type = NULL; char *p; int i; memset(pc, 0, sizeof(*pc)); for (i = 0; i < s->numpairs; i++, pp++) { p = ""; if (OPENSSL_strcasecmp(pp->key, "type") == 0) { if (type != NULL) { TEST_info("Line %d: multiple type lines", s->curr); return 0; } pc->param = OSSL_PARAM_locate(params, type = pp->value); if (pc->param == NULL) { TEST_info("Line %d: unknown type line", s->curr); return 0; } } else if (OPENSSL_strcasecmp(pp->key, "int32") == 0) { if (def_i32++) { TEST_info("Line %d: multiple int32 lines", s->curr); return 0; } if (OPENSSL_strcasecmp(pp->value, "invalid") != 0) { pc->valid_i32 = 1; pc->i32 = (int32_t)strtoimax(pp->value, &p, 10); } } else if (OPENSSL_strcasecmp(pp->key, "int64") == 0) { if (def_i64++) { TEST_info("Line %d: multiple int64 lines", s->curr); return 0; } if (OPENSSL_strcasecmp(pp->value, "invalid") != 0) { pc->valid_i64 = 1; pc->i64 = (int64_t)strtoimax(pp->value, &p, 10); } } else if (OPENSSL_strcasecmp(pp->key, "uint32") == 0) { if (def_u32++) { TEST_info("Line %d: multiple uint32 lines", s->curr); return 0; } if (OPENSSL_strcasecmp(pp->value, "invalid") != 0) { pc->valid_u32 = 1; pc->u32 = (uint32_t)strtoumax(pp->value, &p, 10); } } else if (OPENSSL_strcasecmp(pp->key, "uint64") == 0) { if (def_u64++) { TEST_info("Line %d: multiple uint64 lines", s->curr); return 0; } if (OPENSSL_strcasecmp(pp->value, "invalid") != 0) { pc->valid_u64 = 1; pc->u64 = (uint64_t)strtoumax(pp->value, &p, 10); } } else if (OPENSSL_strcasecmp(pp->key, "double") == 0) { if (def_d++) { TEST_info("Line %d: multiple double lines", s->curr); return 0; } if (OPENSSL_strcasecmp(pp->value, "invalid") != 0) { pc->valid_d = 1; pc->d = strtod(pp->value, &p); } } else { TEST_info("Line %d: unknown keyword %s", s->curr, pp->key); return 0; } if (*p != '\0') { TEST_info("Line %d: extra characters at end '%s' for %s", s->curr, p, pp->key); return 0; } } if (!TEST_ptr(type)) { TEST_info("Line %d: type not found", s->curr); return 0; } if (OPENSSL_strcasecmp(type, "int32") == 0) { if (!TEST_true(def_i32) || !TEST_true(pc->valid_i32)) { TEST_note("errant int32 on line %d", s->curr); return 0; } datum_i32 = ref_i32 = pc->i32; pc->datum = &datum_i32; pc->ref = &ref_i32; pc->size = sizeof(ref_i32); } else if (OPENSSL_strcasecmp(type, "int64") == 0) { if (!TEST_true(def_i64) || !TEST_true(pc->valid_i64)) { TEST_note("errant int64 on line %d", s->curr); return 0; } datum_i64 = ref_i64 = pc->i64; pc->datum = &datum_i64; pc->ref = &ref_i64; pc->size = sizeof(ref_i64); } else if (OPENSSL_strcasecmp(type, "uint32") == 0) { if (!TEST_true(def_u32) || !TEST_true(pc->valid_u32)) { TEST_note("errant uint32 on line %d", s->curr); return 0; } datum_u32 = ref_u32 = pc->u32; pc->datum = &datum_u32; pc->ref = &ref_u32; pc->size = sizeof(ref_u32); } else if (OPENSSL_strcasecmp(type, "uint64") == 0) { if (!TEST_true(def_u64) || !TEST_true(pc->valid_u64)) { TEST_note("errant uint64 on line %d", s->curr); return 0; } datum_u64 = ref_u64 = pc->u64; pc->datum = &datum_u64; pc->ref = &ref_u64; pc->size = sizeof(ref_u64); } else if (OPENSSL_strcasecmp(type, "double") == 0) { if (!TEST_true(def_d) || !TEST_true(pc->valid_d)) { TEST_note("errant double on line %d", s->curr); return 0; } datum_d = ref_d = pc->d; pc->datum = &datum_d; pc->ref = &ref_d; pc->size = sizeof(ref_d); } else { TEST_error("type unknown at line %d", s->curr); return 0; } return 1; } static int param_conversion_test(const PARAM_CONVERSION *pc, int line) { int32_t i32; int64_t i64; uint32_t u32; uint64_t u64; double d; if (!pc->valid_i32) { if (!TEST_false(OSSL_PARAM_get_int32(pc->param, &i32)) || !TEST_ulong_ne(ERR_get_error(), 0)) { TEST_note("unexpected valid conversion to int32 on line %d", line); return 0; } } else { if (!TEST_true(OSSL_PARAM_get_int32(pc->param, &i32)) || !TEST_true(i32 == pc->i32)) { TEST_note("unexpected conversion to int32 on line %d", line); return 0; } memset(pc->datum, 44, pc->size); if (!TEST_true(OSSL_PARAM_set_int32(pc->param, i32)) || !TEST_mem_eq(pc->datum, pc->size, pc->ref, pc->size)) { TEST_note("unexpected valid conversion from int32 on line %d", line); return 0; } } if (!pc->valid_i64) { if (!TEST_false(OSSL_PARAM_get_int64(pc->param, &i64)) || !TEST_ulong_ne(ERR_get_error(), 0)) { TEST_note("unexpected valid conversion to int64 on line %d", line); return 0; } } else { if (!TEST_true(OSSL_PARAM_get_int64(pc->param, &i64)) || !TEST_true(i64 == pc->i64)) { TEST_note("unexpected conversion to int64 on line %d", line); return 0; } memset(pc->datum, 44, pc->size); if (!TEST_true(OSSL_PARAM_set_int64(pc->param, i64)) || !TEST_mem_eq(pc->datum, pc->size, pc->ref, pc->size)) { TEST_note("unexpected valid conversion from int64 on line %d", line); return 0; } } if (!pc->valid_u32) { if (!TEST_false(OSSL_PARAM_get_uint32(pc->param, &u32)) || !TEST_ulong_ne(ERR_get_error(), 0)) { TEST_note("unexpected valid conversion to uint32 on line %d", line); return 0; } } else { if (!TEST_true(OSSL_PARAM_get_uint32(pc->param, &u32)) || !TEST_true(u32 == pc->u32)) { TEST_note("unexpected conversion to uint32 on line %d", line); return 0; } memset(pc->datum, 44, pc->size); if (!TEST_true(OSSL_PARAM_set_uint32(pc->param, u32)) || !TEST_mem_eq(pc->datum, pc->size, pc->ref, pc->size)) { TEST_note("unexpected valid conversion from uint32 on line %d", line); return 0; } } if (!pc->valid_u64) { if (!TEST_false(OSSL_PARAM_get_uint64(pc->param, &u64)) || !TEST_ulong_ne(ERR_get_error(), 0)) { TEST_note("unexpected valid conversion to uint64 on line %d", line); return 0; } } else { if (!TEST_true(OSSL_PARAM_get_uint64(pc->param, &u64)) || !TEST_true(u64 == pc->u64)) { TEST_note("unexpected conversion to uint64 on line %d", line); return 0; } memset(pc->datum, 44, pc->size); if (!TEST_true(OSSL_PARAM_set_uint64(pc->param, u64)) || !TEST_mem_eq(pc->datum, pc->size, pc->ref, pc->size)) { TEST_note("unexpected valid conversion from uint64 on line %d", line); return 0; } } if (!pc->valid_d) { if (!TEST_false(OSSL_PARAM_get_double(pc->param, &d)) || !TEST_ulong_ne(ERR_get_error(), 0)) { TEST_note("unexpected valid conversion to double on line %d", line); return 0; } } else { if (!TEST_true(OSSL_PARAM_get_double(pc->param, &d))) { TEST_note("unable to convert to double on line %d", line); return 0; } /* * Check for not a number (NaN) without using the libm functions. * When d is a NaN, the standard requires d == d to be false. * It's less clear if d != d should be true even though it generally is. * Hence we use the equality test and a not. */ if (!(d == d)) { /* * We've encountered a NaN so check it's really meant to be a NaN. * We ignore the case where the two values are both different NaN, * that's not resolvable without knowing the underlying format * or using libm functions. */ if (!TEST_false(pc->d == pc->d)) { TEST_note("unexpected NaN on line %d", line); return 0; } } else if (!TEST_true(d == pc->d)) { TEST_note("unexpected conversion to double on line %d", line); return 0; } memset(pc->datum, 44, pc->size); if (!TEST_true(OSSL_PARAM_set_double(pc->param, d)) || !TEST_mem_eq(pc->datum, pc->size, pc->ref, pc->size)) { TEST_note("unexpected valid conversion from double on line %d", line); return 0; } } return 1; } static int run_param_file_tests(int i) { STANZA *s; PARAM_CONVERSION pc; const char *testfile = test_get_argument(i); int res = 1; if (!TEST_ptr(s = OPENSSL_zalloc(sizeof(*s)))) return 0; if (!test_start_file(s, testfile)) { OPENSSL_free(s); return 0; } while (!BIO_eof(s->fp)) { if (!test_readstanza(s)) { res = 0; goto end; } if (s->numpairs != 0) if (!param_conversion_load_stanza(&pc, s) || !param_conversion_test(&pc, s->curr)) res = 0; test_clearstanza(s); } end: test_end_file(s); OPENSSL_free(s); return res; } #endif /* OPENSSL_NO_INTTYPES_H */ OPT_TEST_DECLARE_USAGE("file...\n") int setup_tests(void) { size_t n; if (!test_skip_common_options()) { TEST_error("Error parsing test options\n"); return 0; } n = test_get_argument_count(); if (n == 0) return 0; #if !defined(OPENSSL_NO_INTTYPES_H) ADD_ALL_TESTS(run_param_file_tests, n); #endif /* OPENSSL_NO_INTTYPES_H */ return 1; }
./openssl/test/servername_test.c
/* * Copyright 2017-2021 The OpenSSL Project Authors. All Rights Reserved. * Copyright 2017 BaishanCloud. All rights reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <string.h> #include <openssl/opensslconf.h> #include <openssl/bio.h> #include <openssl/crypto.h> #include <openssl/evp.h> #include <openssl/ssl.h> #include <openssl/err.h> #include <time.h> #include "internal/packet.h" #include "testutil.h" #include "internal/nelem.h" #include "helpers/ssltestlib.h" #define CLIENT_VERSION_LEN 2 static const char *host = "dummy-host"; static char *cert = NULL; static char *privkey = NULL; #if defined(OPENSSL_NO_TLS1_3) || \ (defined(OPENSSL_NO_EC) && defined(OPENSSL_NO_DH)) static int maxversion = TLS1_2_VERSION; #else static int maxversion = 0; #endif static int get_sni_from_client_hello(BIO *bio, char **sni) { long len; unsigned char *data; PACKET pkt, pkt2, pkt3, pkt4, pkt5; unsigned int servname_type = 0, type = 0; int ret = 0; memset(&pkt, 0, sizeof(pkt)); memset(&pkt2, 0, sizeof(pkt2)); memset(&pkt3, 0, sizeof(pkt3)); memset(&pkt4, 0, sizeof(pkt4)); memset(&pkt5, 0, sizeof(pkt5)); if (!TEST_long_ge(len = BIO_get_mem_data(bio, (char **)&data), 0) || !TEST_true(PACKET_buf_init(&pkt, data, len)) /* Skip the record header */ || !PACKET_forward(&pkt, SSL3_RT_HEADER_LENGTH) /* Skip the handshake message header */ || !TEST_true(PACKET_forward(&pkt, SSL3_HM_HEADER_LENGTH)) /* Skip client version and random */ || !TEST_true(PACKET_forward(&pkt, CLIENT_VERSION_LEN + SSL3_RANDOM_SIZE)) /* Skip session id */ || !TEST_true(PACKET_get_length_prefixed_1(&pkt, &pkt2)) /* Skip ciphers */ || !TEST_true(PACKET_get_length_prefixed_2(&pkt, &pkt2)) /* Skip compression */ || !TEST_true(PACKET_get_length_prefixed_1(&pkt, &pkt2)) /* Extensions len */ || !TEST_true(PACKET_as_length_prefixed_2(&pkt, &pkt2))) goto end; /* Loop through all extensions for SNI */ while (PACKET_remaining(&pkt2)) { if (!TEST_true(PACKET_get_net_2(&pkt2, &type)) || !TEST_true(PACKET_get_length_prefixed_2(&pkt2, &pkt3))) goto end; if (type == TLSEXT_TYPE_server_name) { if (!TEST_true(PACKET_get_length_prefixed_2(&pkt3, &pkt4)) || !TEST_uint_ne(PACKET_remaining(&pkt4), 0) || !TEST_true(PACKET_get_1(&pkt4, &servname_type)) || !TEST_uint_eq(servname_type, TLSEXT_NAMETYPE_host_name) || !TEST_true(PACKET_get_length_prefixed_2(&pkt4, &pkt5)) || !TEST_uint_le(PACKET_remaining(&pkt5), TLSEXT_MAXLEN_host_name) || !TEST_false(PACKET_contains_zero_byte(&pkt5)) || !TEST_true(PACKET_strndup(&pkt5, sni))) goto end; ret = 1; goto end; } } end: return ret; } static int client_setup_sni_before_state(void) { SSL_CTX *ctx; SSL *con = NULL; BIO *rbio; BIO *wbio; char *hostname = NULL; int ret = 0; /* use TLS_method to blur 'side' */ ctx = SSL_CTX_new(TLS_method()); if (!TEST_ptr(ctx)) goto end; if (maxversion > 0 && !TEST_true(SSL_CTX_set_max_proto_version(ctx, maxversion))) goto end; con = SSL_new(ctx); if (!TEST_ptr(con)) goto end; /* set SNI before 'client side' is set */ SSL_set_tlsext_host_name(con, host); rbio = BIO_new(BIO_s_mem()); wbio = BIO_new(BIO_s_mem()); if (!TEST_ptr(rbio)|| !TEST_ptr(wbio)) { BIO_free(rbio); BIO_free(wbio); goto end; } SSL_set_bio(con, rbio, wbio); if (!TEST_int_le(SSL_connect(con), 0)) /* This shouldn't succeed because we don't have a server! */ goto end; if (!TEST_true(get_sni_from_client_hello(wbio, &hostname))) /* no SNI in client hello */ goto end; if (!TEST_str_eq(hostname, host)) /* incorrect SNI value */ goto end; ret = 1; end: OPENSSL_free(hostname); SSL_free(con); SSL_CTX_free(ctx); return ret; } static int client_setup_sni_after_state(void) { SSL_CTX *ctx; SSL *con = NULL; BIO *rbio; BIO *wbio; char *hostname = NULL; int ret = 0; /* use TLS_method to blur 'side' */ ctx = SSL_CTX_new(TLS_method()); if (!TEST_ptr(ctx)) goto end; if (maxversion > 0 && !TEST_true(SSL_CTX_set_max_proto_version(ctx, maxversion))) goto end; con = SSL_new(ctx); if (!TEST_ptr(con)) goto end; rbio = BIO_new(BIO_s_mem()); wbio = BIO_new(BIO_s_mem()); if (!TEST_ptr(rbio)|| !TEST_ptr(wbio)) { BIO_free(rbio); BIO_free(wbio); goto end; } SSL_set_bio(con, rbio, wbio); SSL_set_connect_state(con); /* set SNI after 'client side' is set */ SSL_set_tlsext_host_name(con, host); if (!TEST_int_le(SSL_connect(con), 0)) /* This shouldn't succeed because we don't have a server! */ goto end; if (!TEST_true(get_sni_from_client_hello(wbio, &hostname))) /* no SNI in client hello */ goto end; if (!TEST_str_eq(hostname, host)) /* incorrect SNI value */ goto end; ret = 1; end: OPENSSL_free(hostname); SSL_free(con); SSL_CTX_free(ctx); return ret; } static int server_setup_sni(void) { SSL_CTX *cctx = NULL, *sctx = NULL; SSL *clientssl = NULL, *serverssl = NULL; int testresult = 0; if (!TEST_true(create_ssl_ctx_pair(NULL, TLS_server_method(), TLS_client_method(), TLS1_VERSION, 0, &sctx, &cctx, cert, privkey)) || !TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl, NULL, NULL))) goto end; /* set SNI at server side */ SSL_set_tlsext_host_name(serverssl, host); if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE))) goto end; if (!TEST_ptr_null(SSL_get_servername(serverssl, TLSEXT_NAMETYPE_host_name))) { /* SNI should have been cleared during handshake */ goto end; } testresult = 1; end: SSL_free(serverssl); SSL_free(clientssl); SSL_CTX_free(sctx); SSL_CTX_free(cctx); return testresult; } typedef int (*sni_test_fn)(void); static sni_test_fn sni_test_fns[3] = { client_setup_sni_before_state, client_setup_sni_after_state, server_setup_sni }; static int test_servername(int test) { /* * For each test set up an SSL_CTX and SSL and see * what SNI behaves. */ return sni_test_fns[test](); } int setup_tests(void) { if (!test_skip_common_options()) { TEST_error("Error parsing test options\n"); return 0; } if (!TEST_ptr(cert = test_get_argument(0)) || !TEST_ptr(privkey = test_get_argument(1))) return 0; ADD_ALL_TESTS(test_servername, OSSL_NELEM(sni_test_fns)); return 1; }
./openssl/test/sm4_internal_test.c
/* * Copyright 2017-2021 The OpenSSL Project Authors. All Rights Reserved. * Copyright 2017 Ribose Inc. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ /* * Internal tests for the SM4 module. */ #include <string.h> #include <openssl/opensslconf.h> #include "testutil.h" #ifndef OPENSSL_NO_SM4 # include "crypto/sm4.h" static int test_sm4_ecb(void) { static const uint8_t k[SM4_BLOCK_SIZE] = { 0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef, 0xfe, 0xdc, 0xba, 0x98, 0x76, 0x54, 0x32, 0x10 }; static const uint8_t input[SM4_BLOCK_SIZE] = { 0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef, 0xfe, 0xdc, 0xba, 0x98, 0x76, 0x54, 0x32, 0x10 }; /* * This test vector comes from Example 1 of GB/T 32907-2016, * and described in Internet Draft draft-ribose-cfrg-sm4-02. */ static const uint8_t expected[SM4_BLOCK_SIZE] = { 0x68, 0x1e, 0xdf, 0x34, 0xd2, 0x06, 0x96, 0x5e, 0x86, 0xb3, 0xe9, 0x4f, 0x53, 0x6e, 0x42, 0x46 }; /* * This test vector comes from Example 2 from GB/T 32907-2016, * and described in Internet Draft draft-ribose-cfrg-sm4-02. * After 1,000,000 iterations. */ static const uint8_t expected_iter[SM4_BLOCK_SIZE] = { 0x59, 0x52, 0x98, 0xc7, 0xc6, 0xfd, 0x27, 0x1f, 0x04, 0x02, 0xf8, 0x04, 0xc3, 0x3d, 0x3f, 0x66 }; int i; SM4_KEY key; uint8_t block[SM4_BLOCK_SIZE]; ossl_sm4_set_key(k, &key); memcpy(block, input, SM4_BLOCK_SIZE); ossl_sm4_encrypt(block, block, &key); if (!TEST_mem_eq(block, SM4_BLOCK_SIZE, expected, SM4_BLOCK_SIZE)) return 0; for (i = 0; i != 999999; ++i) ossl_sm4_encrypt(block, block, &key); if (!TEST_mem_eq(block, SM4_BLOCK_SIZE, expected_iter, SM4_BLOCK_SIZE)) return 0; for (i = 0; i != 1000000; ++i) ossl_sm4_decrypt(block, block, &key); if (!TEST_mem_eq(block, SM4_BLOCK_SIZE, input, SM4_BLOCK_SIZE)) return 0; return 1; } #endif int setup_tests(void) { #ifndef OPENSSL_NO_SM4 ADD_TEST(test_sm4_ecb); #endif return 1; }
./openssl/test/drbgtest.c
/* * Copyright 2011-2023 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ /* We need to use some deprecated APIs */ #define OPENSSL_SUPPRESS_DEPRECATED #include <string.h> #include "internal/nelem.h" #include <openssl/crypto.h> #include <openssl/err.h> #include <openssl/rand.h> #include <openssl/obj_mac.h> #include <openssl/evp.h> #include <openssl/aes.h> #include "../crypto/rand/rand_local.h" #include "../include/crypto/rand.h" #include "../include/crypto/evp.h" #include "../providers/implementations/rands/drbg_local.h" #include "../crypto/evp/evp_local.h" #if defined(_WIN32) # include <windows.h> #endif #if defined(__TANDEM) # if defined(OPENSSL_TANDEM_FLOSS) # include <floss.h(floss_fork)> # endif #endif #if defined(OPENSSL_SYS_UNIX) # include <sys/types.h> # include <sys/wait.h> # include <unistd.h> #endif #include "testutil.h" /* * DRBG generate wrappers */ static int gen_bytes(EVP_RAND_CTX *drbg, unsigned char *buf, int num) { #ifndef OPENSSL_NO_DEPRECATED_3_0 const RAND_METHOD *meth = RAND_get_rand_method(); if (meth != NULL && meth != RAND_OpenSSL()) { if (meth->bytes != NULL) return meth->bytes(buf, num); return -1; } #endif if (drbg != NULL) return EVP_RAND_generate(drbg, buf, num, 0, 0, NULL, 0); return 0; } static int rand_bytes(unsigned char *buf, int num) { return gen_bytes(RAND_get0_public(NULL), buf, num); } static int rand_priv_bytes(unsigned char *buf, int num) { return gen_bytes(RAND_get0_private(NULL), buf, num); } /* size of random output generated in test_drbg_reseed() */ #define RANDOM_SIZE 16 /* * DRBG query functions */ static int state(EVP_RAND_CTX *drbg) { return EVP_RAND_get_state(drbg); } static unsigned int query_rand_uint(EVP_RAND_CTX *drbg, const char *name) { OSSL_PARAM params[2] = { OSSL_PARAM_END, OSSL_PARAM_END }; unsigned int n; *params = OSSL_PARAM_construct_uint(name, &n); if (EVP_RAND_CTX_get_params(drbg, params)) return n; return 0; } #define DRBG_UINT(name) \ static unsigned int name(EVP_RAND_CTX *drbg) \ { \ return query_rand_uint(drbg, #name); \ } DRBG_UINT(reseed_counter) static PROV_DRBG *prov_rand(EVP_RAND_CTX *drbg) { return (PROV_DRBG *)drbg->algctx; } static void set_reseed_counter(EVP_RAND_CTX *drbg, unsigned int n) { PROV_DRBG *p = prov_rand(drbg); p->reseed_counter = n; } static void inc_reseed_counter(EVP_RAND_CTX *drbg) { set_reseed_counter(drbg, reseed_counter(drbg) + 1); } static time_t reseed_time(EVP_RAND_CTX *drbg) { OSSL_PARAM params[2] = { OSSL_PARAM_END, OSSL_PARAM_END }; time_t t; *params = OSSL_PARAM_construct_time_t(OSSL_DRBG_PARAM_RESEED_TIME, &t); if (EVP_RAND_CTX_get_params(drbg, params)) return t; return 0; } /* * When building the FIPS module, it isn't possible to disable the continuous * RNG tests. Tests that require this are skipped and this means a detection * mechanism for the FIPS provider being in use. */ static int using_fips_rng(void) { EVP_RAND_CTX *primary = RAND_get0_primary(NULL); const OSSL_PROVIDER *prov; const char *name; if (!TEST_ptr(primary)) return 0; prov = EVP_RAND_get0_provider(EVP_RAND_CTX_get0_rand(primary)); if (!TEST_ptr(prov)) return 0; name = OSSL_PROVIDER_get0_name(prov); return strcmp(name, "OpenSSL FIPS Provider") == 0; } /* * Disable CRNG testing if it is enabled. * This stub remains to indicate the calling locations where it is necessary. * Once the RNG infrastructure is able to disable these tests, it should be * reconstituted. */ static int disable_crngt(EVP_RAND_CTX *drbg) { return 1; } /* * Generates random output using rand_bytes() and rand_priv_bytes() * and checks whether the three shared DRBGs were reseeded as * expected. * * |expect_success|: expected outcome (as reported by RAND_status()) * |primary|, |public|, |private|: pointers to the three shared DRBGs * |public_random|, |private_random|: generated random output * |expect_xxx_reseed| = * 1: it is expected that the specified DRBG is reseeded * 0: it is expected that the specified DRBG is not reseeded * -1: don't check whether the specified DRBG was reseeded or not * |reseed_when|: if nonzero, used instead of time(NULL) to set the * |before_reseed| time. */ static int test_drbg_reseed(int expect_success, EVP_RAND_CTX *primary, EVP_RAND_CTX *public, EVP_RAND_CTX *private, unsigned char *public_random, unsigned char *private_random, int expect_primary_reseed, int expect_public_reseed, int expect_private_reseed, time_t reseed_when ) { time_t before_reseed, after_reseed; int expected_state = (expect_success ? DRBG_READY : DRBG_ERROR); unsigned int primary_reseed, public_reseed, private_reseed; unsigned char dummy[RANDOM_SIZE]; if (public_random == NULL) public_random = dummy; if (private_random == NULL) private_random = dummy; /* * step 1: check preconditions */ /* Test whether seed propagation is enabled */ if (!TEST_int_ne(primary_reseed = reseed_counter(primary), 0) || !TEST_int_ne(public_reseed = reseed_counter(public), 0) || !TEST_int_ne(private_reseed = reseed_counter(private), 0)) return 0; /* * step 2: generate random output */ if (reseed_when == 0) reseed_when = time(NULL); /* Generate random output from the public and private DRBG */ before_reseed = expect_primary_reseed == 1 ? reseed_when : 0; if (!TEST_int_eq(rand_bytes((unsigned char*)public_random, RANDOM_SIZE), expect_success) || !TEST_int_eq(rand_priv_bytes((unsigned char*) private_random, RANDOM_SIZE), expect_success)) return 0; after_reseed = time(NULL); /* * step 3: check postconditions */ /* Test whether reseeding succeeded as expected */ if (!TEST_int_eq(state(primary), expected_state) || !TEST_int_eq(state(public), expected_state) || !TEST_int_eq(state(private), expected_state)) return 0; if (expect_primary_reseed >= 0) { /* Test whether primary DRBG was reseeded as expected */ if (!TEST_int_ge(reseed_counter(primary), primary_reseed)) return 0; } if (expect_public_reseed >= 0) { /* Test whether public DRBG was reseeded as expected */ if (!TEST_int_ge(reseed_counter(public), public_reseed) || !TEST_uint_ge(reseed_counter(public), reseed_counter(primary))) return 0; } if (expect_private_reseed >= 0) { /* Test whether public DRBG was reseeded as expected */ if (!TEST_int_ge(reseed_counter(private), private_reseed) || !TEST_uint_ge(reseed_counter(private), reseed_counter(primary))) return 0; } if (expect_success == 1) { /* Test whether reseed time of primary DRBG is set correctly */ if (!TEST_time_t_le(before_reseed, reseed_time(primary)) || !TEST_time_t_le(reseed_time(primary), after_reseed)) return 0; /* Test whether reseed times of child DRBGs are synchronized with primary */ if (!TEST_time_t_ge(reseed_time(public), reseed_time(primary)) || !TEST_time_t_ge(reseed_time(private), reseed_time(primary))) return 0; } else { ERR_clear_error(); } return 1; } #if defined(OPENSSL_SYS_UNIX) && !defined(OPENSSL_RAND_SEED_EGD) /* number of children to fork */ #define DRBG_FORK_COUNT 9 /* two results per child, two for the parent */ #define DRBG_FORK_RESULT_COUNT (2 * (DRBG_FORK_COUNT + 1)) typedef struct drbg_fork_result_st { unsigned char random[RANDOM_SIZE]; /* random output */ int pindex; /* process index (0: parent, 1,2,3...: children)*/ pid_t pid; /* process id */ int private; /* true if the private drbg was used */ char name[10]; /* 'parent' resp. 'child 1', 'child 2', ... */ } drbg_fork_result; /* * Sort the drbg_fork_result entries in lexicographical order * * This simplifies finding duplicate random output and makes * the printout in case of an error more readable. */ static int compare_drbg_fork_result(const void *left, const void *right) { int result; const drbg_fork_result *l = left; const drbg_fork_result *r = right; /* separate public and private results */ result = l->private - r->private; if (result == 0) result = memcmp(l->random, r->random, RANDOM_SIZE); if (result == 0) result = l->pindex - r->pindex; return result; } /* * Sort two-byte chunks of random data * * Used for finding collisions in two-byte chunks */ static int compare_rand_chunk(const void *left, const void *right) { return memcmp(left, right, 2); } /* * Test whether primary, public and private DRBG are reseeded * in the child after forking the process. Collect the random * output of the public and private DRBG and send it back to * the parent process. */ static int test_drbg_reseed_in_child(EVP_RAND_CTX *primary, EVP_RAND_CTX *public, EVP_RAND_CTX *private, drbg_fork_result result[2]) { int rv = 0, status; int fd[2]; pid_t pid; unsigned char random[2 * RANDOM_SIZE]; if (!TEST_int_ge(pipe(fd), 0)) return 0; if (!TEST_int_ge(pid = fork(), 0)) { close(fd[0]); close(fd[1]); return 0; } else if (pid > 0) { /* I'm the parent; close the write end */ close(fd[1]); /* wait for children to terminate and collect their random output */ if (TEST_int_eq(waitpid(pid, &status, 0), pid) && TEST_int_eq(status, 0) && TEST_true(read(fd[0], &random[0], sizeof(random)) == sizeof(random))) { /* random output of public drbg */ result[0].pid = pid; result[0].private = 0; memcpy(result[0].random, &random[0], RANDOM_SIZE); /* random output of private drbg */ result[1].pid = pid; result[1].private = 1; memcpy(result[1].random, &random[RANDOM_SIZE], RANDOM_SIZE); rv = 1; } /* close the read end */ close(fd[0]); return rv; } else { /* I'm the child; close the read end */ close(fd[0]); /* check whether all three DRBGs reseed and send output to parent */ if (TEST_true(test_drbg_reseed(1, primary, public, private, &random[0], &random[RANDOM_SIZE], 1, 1, 1, 0)) && TEST_true(write(fd[1], random, sizeof(random)) == sizeof(random))) { rv = 1; } /* close the write end */ close(fd[1]); /* convert boolean to exit code */ exit(rv == 0); } } static int test_rand_reseed_on_fork(EVP_RAND_CTX *primary, EVP_RAND_CTX *public, EVP_RAND_CTX *private) { unsigned int i; pid_t pid = getpid(); int verbose = (getenv("V") != NULL); int success = 1; int duplicate[2] = {0, 0}; unsigned char random[2 * RANDOM_SIZE]; unsigned char sample[DRBG_FORK_RESULT_COUNT * RANDOM_SIZE]; unsigned char *psample = &sample[0]; drbg_fork_result result[DRBG_FORK_RESULT_COUNT]; drbg_fork_result *presult = &result[2]; memset(&result, 0, sizeof(result)); for (i = 1 ; i <= DRBG_FORK_COUNT ; ++i) { presult[0].pindex = presult[1].pindex = i; sprintf(presult[0].name, "child %d", i); strcpy(presult[1].name, presult[0].name); /* collect the random output of the children */ if (!TEST_true(test_drbg_reseed_in_child(primary, public, private, presult))) return 0; presult += 2; } /* collect the random output of the parent */ if (!TEST_true(test_drbg_reseed(1, primary, public, private, &random[0], &random[RANDOM_SIZE], 0, 0, 0, 0))) return 0; strcpy(result[0].name, "parent"); strcpy(result[1].name, "parent"); /* output of public drbg */ result[0].pid = pid; result[0].private = 0; memcpy(result[0].random, &random[0], RANDOM_SIZE); /* output of private drbg */ result[1].pid = pid; result[1].private = 1; memcpy(result[1].random, &random[RANDOM_SIZE], RANDOM_SIZE); /* collect all sampled random data in a single buffer */ for (i = 0 ; i < DRBG_FORK_RESULT_COUNT ; ++i) { memcpy(psample, &result[i].random[0], RANDOM_SIZE); psample += RANDOM_SIZE; } /* sort the results... */ qsort(result, DRBG_FORK_RESULT_COUNT, sizeof(drbg_fork_result), compare_drbg_fork_result); /* ...and count duplicate prefixes by looking at the first byte only */ for (i = 1 ; i < DRBG_FORK_RESULT_COUNT ; ++i) { if (result[i].random[0] == result[i-1].random[0]) { /* count public and private duplicates separately */ ++duplicate[result[i].private]; } } if (duplicate[0] >= DRBG_FORK_COUNT - 1) { /* just too many duplicates to be a coincidence */ TEST_note("ERROR: %d duplicate prefixes in public random output", duplicate[0]); success = 0; } if (duplicate[1] >= DRBG_FORK_COUNT - 1) { /* just too many duplicates to be a coincidence */ TEST_note("ERROR: %d duplicate prefixes in private random output", duplicate[1]); success = 0; } duplicate[0] = 0; /* sort the two-byte chunks... */ qsort(sample, sizeof(sample)/2, 2, compare_rand_chunk); /* ...and count duplicate chunks */ for (i = 2, psample = sample + 2 ; i < sizeof(sample) ; i += 2, psample += 2) { if (compare_rand_chunk(psample - 2, psample) == 0) ++duplicate[0]; } if (duplicate[0] >= DRBG_FORK_COUNT - 1) { /* just too many duplicates to be a coincidence */ TEST_note("ERROR: %d duplicate chunks in random output", duplicate[0]); success = 0; } if (verbose || !success) { for (i = 0 ; i < DRBG_FORK_RESULT_COUNT ; ++i) { char *rand_hex = OPENSSL_buf2hexstr(result[i].random, RANDOM_SIZE); TEST_note(" random: %s, pid: %d (%s, %s)", rand_hex, result[i].pid, result[i].name, result[i].private ? "private" : "public" ); OPENSSL_free(rand_hex); } } return success; } static int test_rand_fork_safety(int i) { int success = 1; unsigned char random[1]; EVP_RAND_CTX *primary, *public, *private; /* All three DRBGs should be non-null */ if (!TEST_ptr(primary = RAND_get0_primary(NULL)) || !TEST_ptr(public = RAND_get0_public(NULL)) || !TEST_ptr(private = RAND_get0_private(NULL))) return 0; /* run the actual test */ if (!TEST_true(test_rand_reseed_on_fork(primary, public, private))) success = 0; /* request a single byte from each of the DRBGs before the next run */ if (!TEST_int_gt(RAND_bytes(random, 1), 0) || !TEST_int_gt(RAND_priv_bytes(random, 1), 0)) success = 0; return success; } #endif /* * Test whether the default rand_method (RAND_OpenSSL()) is * setup correctly, in particular whether reseeding works * as designed. */ static int test_rand_reseed(void) { EVP_RAND_CTX *primary, *public, *private; unsigned char rand_add_buf[256]; int rv = 0; time_t before_reseed; if (using_fips_rng()) return TEST_skip("CRNGT cannot be disabled"); #ifndef OPENSSL_NO_DEPRECATED_3_0 /* Check whether RAND_OpenSSL() is the default method */ if (!TEST_ptr_eq(RAND_get_rand_method(), RAND_OpenSSL())) return 0; #endif /* All three DRBGs should be non-null */ if (!TEST_ptr(primary = RAND_get0_primary(NULL)) || !TEST_ptr(public = RAND_get0_public(NULL)) || !TEST_ptr(private = RAND_get0_private(NULL))) return 0; /* There should be three distinct DRBGs, two of them chained to primary */ if (!TEST_ptr_ne(public, private) || !TEST_ptr_ne(public, primary) || !TEST_ptr_ne(private, primary) || !TEST_ptr_eq(prov_rand(public)->parent, prov_rand(primary)) || !TEST_ptr_eq(prov_rand(private)->parent, prov_rand(primary))) return 0; /* Disable CRNG testing for the primary DRBG */ if (!TEST_true(disable_crngt(primary))) return 0; /* uninstantiate the three global DRBGs */ EVP_RAND_uninstantiate(primary); EVP_RAND_uninstantiate(private); EVP_RAND_uninstantiate(public); /* * Test initial seeding of shared DRBGs */ if (!TEST_true(test_drbg_reseed(1, primary, public, private, NULL, NULL, 1, 1, 1, 0))) goto error; /* * Test initial state of shared DRBGs */ if (!TEST_true(test_drbg_reseed(1, primary, public, private, NULL, NULL, 0, 0, 0, 0))) goto error; /* * Test whether the public and private DRBG are both reseeded when their * reseed counters differ from the primary's reseed counter. */ inc_reseed_counter(primary); if (!TEST_true(test_drbg_reseed(1, primary, public, private, NULL, NULL, 0, 1, 1, 0))) goto error; /* * Test whether the public DRBG is reseeded when its reseed counter differs * from the primary's reseed counter. */ inc_reseed_counter(primary); inc_reseed_counter(private); if (!TEST_true(test_drbg_reseed(1, primary, public, private, NULL, NULL, 0, 1, 0, 0))) goto error; /* * Test whether the private DRBG is reseeded when its reseed counter differs * from the primary's reseed counter. */ inc_reseed_counter(primary); inc_reseed_counter(public); if (!TEST_true(test_drbg_reseed(1, primary, public, private, NULL, NULL, 0, 0, 1, 0))) goto error; /* fill 'randomness' buffer with some arbitrary data */ memset(rand_add_buf, 'r', sizeof(rand_add_buf)); /* * Test whether all three DRBGs are reseeded by RAND_add(). * The before_reseed time has to be measured here and passed into the * test_drbg_reseed() test, because the primary DRBG gets already reseeded * in RAND_add(), whence the check for the condition * before_reseed <= reseed_time(primary) will fail if the time value happens * to increase between the RAND_add() and the test_drbg_reseed() call. */ before_reseed = time(NULL); RAND_add(rand_add_buf, sizeof(rand_add_buf), sizeof(rand_add_buf)); if (!TEST_true(test_drbg_reseed(1, primary, public, private, NULL, NULL, 1, 1, 1, before_reseed))) goto error; rv = 1; error: return rv; } #if defined(OPENSSL_THREADS) static int multi_thread_rand_bytes_succeeded = 1; static int multi_thread_rand_priv_bytes_succeeded = 1; static int set_reseed_time_interval(EVP_RAND_CTX *drbg, int t) { OSSL_PARAM params[2]; params[0] = OSSL_PARAM_construct_int(OSSL_DRBG_PARAM_RESEED_TIME_INTERVAL, &t); params[1] = OSSL_PARAM_construct_end(); return EVP_RAND_CTX_set_params(drbg, params); } static void run_multi_thread_test(void) { unsigned char buf[256]; time_t start = time(NULL); EVP_RAND_CTX *public = NULL, *private = NULL; if (!TEST_ptr(public = RAND_get0_public(NULL)) || !TEST_ptr(private = RAND_get0_private(NULL)) || !TEST_true(set_reseed_time_interval(private, 1)) || !TEST_true(set_reseed_time_interval(public, 1))) { multi_thread_rand_bytes_succeeded = 0; return; } do { if (rand_bytes(buf, sizeof(buf)) <= 0) multi_thread_rand_bytes_succeeded = 0; if (rand_priv_bytes(buf, sizeof(buf)) <= 0) multi_thread_rand_priv_bytes_succeeded = 0; } while (time(NULL) - start < 5); } # if defined(OPENSSL_SYS_WINDOWS) typedef HANDLE thread_t; static DWORD WINAPI thread_run(LPVOID arg) { run_multi_thread_test(); /* * Because we're linking with a static library, we must stop each * thread explicitly, or so says OPENSSL_thread_stop(3) */ OPENSSL_thread_stop(); return 0; } static int run_thread(thread_t *t) { *t = CreateThread(NULL, 0, thread_run, NULL, 0, NULL); return *t != NULL; } static int wait_for_thread(thread_t thread) { return WaitForSingleObject(thread, INFINITE) == 0; } # else typedef pthread_t thread_t; static void *thread_run(void *arg) { run_multi_thread_test(); /* * Because we're linking with a static library, we must stop each * thread explicitly, or so says OPENSSL_thread_stop(3) */ OPENSSL_thread_stop(); return NULL; } static int run_thread(thread_t *t) { return pthread_create(t, NULL, thread_run, NULL) == 0; } static int wait_for_thread(thread_t thread) { return pthread_join(thread, NULL) == 0; } # endif /* * The main thread will also run the test, so we'll have THREADS+1 parallel * tests running */ # define THREADS 3 static int test_multi_thread(void) { thread_t t[THREADS]; int i; for (i = 0; i < THREADS; i++) run_thread(&t[i]); run_multi_thread_test(); for (i = 0; i < THREADS; i++) wait_for_thread(t[i]); if (!TEST_true(multi_thread_rand_bytes_succeeded)) return 0; if (!TEST_true(multi_thread_rand_priv_bytes_succeeded)) return 0; return 1; } #endif static EVP_RAND_CTX *new_drbg(EVP_RAND_CTX *parent) { OSSL_PARAM params[2]; EVP_RAND *rand = NULL; EVP_RAND_CTX *drbg = NULL; params[0] = OSSL_PARAM_construct_utf8_string(OSSL_DRBG_PARAM_CIPHER, "AES-256-CTR", 0); params[1] = OSSL_PARAM_construct_end(); if (!TEST_ptr(rand = EVP_RAND_fetch(NULL, "CTR-DRBG", NULL)) || !TEST_ptr(drbg = EVP_RAND_CTX_new(rand, parent)) || !TEST_true(EVP_RAND_CTX_set_params(drbg, params))) { EVP_RAND_CTX_free(drbg); drbg = NULL; } EVP_RAND_free(rand); return drbg; } static int test_rand_prediction_resistance(void) { EVP_RAND_CTX *x = NULL, *y = NULL, *z = NULL; unsigned char buf1[51], buf2[sizeof(buf1)]; int ret = 0, xreseed, yreseed, zreseed; if (using_fips_rng()) return TEST_skip("CRNGT cannot be disabled"); /* Initialise a three long DRBG chain */ if (!TEST_ptr(x = new_drbg(NULL)) || !TEST_true(disable_crngt(x)) || !TEST_true(EVP_RAND_instantiate(x, 0, 0, NULL, 0, NULL)) || !TEST_ptr(y = new_drbg(x)) || !TEST_true(EVP_RAND_instantiate(y, 0, 0, NULL, 0, NULL)) || !TEST_ptr(z = new_drbg(y)) || !TEST_true(EVP_RAND_instantiate(z, 0, 0, NULL, 0, NULL))) goto err; /* * During a normal reseed, only the last DRBG in the chain should * be reseeded. */ inc_reseed_counter(y); xreseed = reseed_counter(x); yreseed = reseed_counter(y); zreseed = reseed_counter(z); if (!TEST_true(EVP_RAND_reseed(z, 0, NULL, 0, NULL, 0)) || !TEST_int_eq(reseed_counter(x), xreseed) || !TEST_int_eq(reseed_counter(y), yreseed) || !TEST_int_gt(reseed_counter(z), zreseed)) goto err; /* * When prediction resistance is requested, the request should be * propagated to the primary, so that the entire DRBG chain reseeds. */ zreseed = reseed_counter(z); if (!TEST_true(EVP_RAND_reseed(z, 1, NULL, 0, NULL, 0)) || !TEST_int_gt(reseed_counter(x), xreseed) || !TEST_int_gt(reseed_counter(y), yreseed) || !TEST_int_gt(reseed_counter(z), zreseed)) goto err; /* * During a normal generate, only the last DRBG should be reseed */ inc_reseed_counter(y); xreseed = reseed_counter(x); yreseed = reseed_counter(y); zreseed = reseed_counter(z); if (!TEST_true(EVP_RAND_generate(z, buf1, sizeof(buf1), 0, 0, NULL, 0)) || !TEST_int_eq(reseed_counter(x), xreseed) || !TEST_int_eq(reseed_counter(y), yreseed) || !TEST_int_gt(reseed_counter(z), zreseed)) goto err; /* * When a prediction resistant generate is requested, the request * should be propagated to the primary, reseeding the entire DRBG chain. */ zreseed = reseed_counter(z); if (!TEST_true(EVP_RAND_generate(z, buf2, sizeof(buf2), 0, 1, NULL, 0)) || !TEST_int_gt(reseed_counter(x), xreseed) || !TEST_int_gt(reseed_counter(y), yreseed) || !TEST_int_gt(reseed_counter(z), zreseed) || !TEST_mem_ne(buf1, sizeof(buf1), buf2, sizeof(buf2))) goto err; /* Verify that a normal reseed still only reseeds the last DRBG */ inc_reseed_counter(y); xreseed = reseed_counter(x); yreseed = reseed_counter(y); zreseed = reseed_counter(z); if (!TEST_true(EVP_RAND_reseed(z, 0, NULL, 0, NULL, 0)) || !TEST_int_eq(reseed_counter(x), xreseed) || !TEST_int_eq(reseed_counter(y), yreseed) || !TEST_int_gt(reseed_counter(z), zreseed)) goto err; ret = 1; err: EVP_RAND_CTX_free(z); EVP_RAND_CTX_free(y); EVP_RAND_CTX_free(x); return ret; } int setup_tests(void) { ADD_TEST(test_rand_reseed); #if defined(OPENSSL_SYS_UNIX) && !defined(OPENSSL_RAND_SEED_EGD) ADD_ALL_TESTS(test_rand_fork_safety, RANDOM_SIZE); #endif ADD_TEST(test_rand_prediction_resistance); #if defined(OPENSSL_THREADS) ADD_TEST(test_multi_thread); #endif return 1; }
./openssl/test/x509_internal_test.c
/* * Copyright 2016-2021 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ /* Internal tests for the x509 and x509v3 modules */ #include <stdio.h> #include <string.h> #include <openssl/x509.h> #include <openssl/x509v3.h> #include "testutil.h" #include "internal/nelem.h" /********************************************************************** * * Test of x509v3 * ***/ #include "../crypto/x509/ext_dat.h" #include "../crypto/x509/standard_exts.h" static int test_standard_exts(void) { size_t i; int prev = -1, good = 1; const X509V3_EXT_METHOD **tmp; tmp = standard_exts; for (i = 0; i < OSSL_NELEM(standard_exts); i++, tmp++) { if ((*tmp)->ext_nid < prev) good = 0; prev = (*tmp)->ext_nid; } if (!good) { tmp = standard_exts; TEST_error("Extensions out of order!"); for (i = 0; i < STANDARD_EXTENSION_COUNT; i++, tmp++) TEST_note("%d : %s", (*tmp)->ext_nid, OBJ_nid2sn((*tmp)->ext_nid)); } return good; } typedef struct { const char *ipasc; const char *data; int length; } IP_TESTDATA; static IP_TESTDATA a2i_ipaddress_tests[] = { {"127.0.0.1", "\x7f\x00\x00\x01", 4}, {"1.2.3.4", "\x01\x02\x03\x04", 4}, {"1.2.3.255", "\x01\x02\x03\xff", 4}, {"1.2.3", NULL, 0}, {"1.2.3 .4", NULL, 0}, {"::1", "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01", 16}, {"1:1:1:1:1:1:1:1", "\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01", 16}, {"2001:db8::ff00:42:8329", "\x20\x01\x0d\xb8\x00\x00\x00\x00\x00\x00\xff\x00\x00\x42\x83\x29", 16}, {"1:1:1:1:1:1:1:1.test", NULL, 0}, {":::1", NULL, 0}, {"2001::123g", NULL, 0}, {"example.test", NULL, 0}, {"", NULL, 0}, {"1.2.3.4 ", "\x01\x02\x03\x04", 4}, {" 1.2.3.4", "\x01\x02\x03\x04", 4}, {" 1.2.3.4 ", "\x01\x02\x03\x04", 4}, {"1.2.3.4.example.test", NULL, 0}, }; static int test_a2i_ipaddress(int idx) { int good = 1; ASN1_OCTET_STRING *ip; int len = a2i_ipaddress_tests[idx].length; ip = a2i_IPADDRESS(a2i_ipaddress_tests[idx].ipasc); if (len == 0) { if (!TEST_ptr_null(ip)) { good = 0; TEST_note("'%s' should not be parsed as IP address", a2i_ipaddress_tests[idx].ipasc); } } else { if (!TEST_ptr(ip) || !TEST_int_eq(ASN1_STRING_length(ip), len) || !TEST_mem_eq(ASN1_STRING_get0_data(ip), len, a2i_ipaddress_tests[idx].data, len)) { good = 0; } } ASN1_OCTET_STRING_free(ip); return good; } int setup_tests(void) { ADD_TEST(test_standard_exts); ADD_ALL_TESTS(test_a2i_ipaddress, OSSL_NELEM(a2i_ipaddress_tests)); return 1; }
./openssl/test/exdatatest.c
/* * Copyright 2015-2021 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <stdio.h> #include <string.h> #include <stdlib.h> #include <openssl/crypto.h> #include "testutil.h" static long saved_argl; static void *saved_argp; static int saved_idx; static int saved_idx2; static int saved_idx3; static int gbl_result; /* * SIMPLE EX_DATA IMPLEMENTATION * Apps explicitly set/get ex_data as needed */ static void exnew(void *parent, void *ptr, CRYPTO_EX_DATA *ad, int idx, long argl, void *argp) { if (!TEST_int_eq(idx, saved_idx) || !TEST_long_eq(argl, saved_argl) || !TEST_ptr_eq(argp, saved_argp) || !TEST_ptr_null(ptr)) gbl_result = 0; } static int exdup(CRYPTO_EX_DATA *to, const CRYPTO_EX_DATA *from, void **from_d, int idx, long argl, void *argp) { if (!TEST_int_eq(idx, saved_idx) || !TEST_long_eq(argl, saved_argl) || !TEST_ptr_eq(argp, saved_argp) || !TEST_ptr(from_d)) gbl_result = 0; return 1; } static void exfree(void *parent, void *ptr, CRYPTO_EX_DATA *ad, int idx, long argl, void *argp) { if (!TEST_int_eq(idx, saved_idx) || !TEST_long_eq(argl, saved_argl) || !TEST_ptr_eq(argp, saved_argp)) gbl_result = 0; } /* * PRE-ALLOCATED EX_DATA IMPLEMENTATION * Extended data structure is allocated in exnew2/freed in exfree2 * Data is stored inside extended data structure */ typedef struct myobj_ex_data_st { char *hello; int new; int dup; } MYOBJ_EX_DATA; static void exnew2(void *parent, void *ptr, CRYPTO_EX_DATA *ad, int idx, long argl, void *argp) { MYOBJ_EX_DATA *ex_data = OPENSSL_zalloc(sizeof(*ex_data)); if (!TEST_true(idx == saved_idx2 || idx == saved_idx3) || !TEST_long_eq(argl, saved_argl) || !TEST_ptr_eq(argp, saved_argp) || !TEST_ptr_null(ptr) || !TEST_ptr(ex_data) || !TEST_true(CRYPTO_set_ex_data(ad, idx, ex_data))) { gbl_result = 0; OPENSSL_free(ex_data); } else { ex_data->new = 1; } } static int exdup2(CRYPTO_EX_DATA *to, const CRYPTO_EX_DATA *from, void **from_d, int idx, long argl, void *argp) { MYOBJ_EX_DATA **update_ex_data = (MYOBJ_EX_DATA**)from_d; MYOBJ_EX_DATA *ex_data = NULL; if (!TEST_true(idx == saved_idx2 || idx == saved_idx3) || !TEST_long_eq(argl, saved_argl) || !TEST_ptr_eq(argp, saved_argp) || !TEST_ptr(from_d) || !TEST_ptr(*update_ex_data) || !TEST_ptr(ex_data = CRYPTO_get_ex_data(to, idx)) || !TEST_true(ex_data->new)) { gbl_result = 0; } else { /* Copy hello over */ ex_data->hello = (*update_ex_data)->hello; /* indicate this is a dup */ ex_data->dup = 1; /* Keep my original ex_data */ *update_ex_data = ex_data; } return 1; } static void exfree2(void *parent, void *ptr, CRYPTO_EX_DATA *ad, int idx, long argl, void *argp) { MYOBJ_EX_DATA *ex_data = CRYPTO_get_ex_data(ad, idx); if (!TEST_true(idx == saved_idx2 || idx == saved_idx3) || !TEST_long_eq(argl, saved_argl) || !TEST_ptr_eq(argp, saved_argp) || !TEST_true(CRYPTO_set_ex_data(ad, idx, NULL))) gbl_result = 0; OPENSSL_free(ex_data); } typedef struct myobj_st { CRYPTO_EX_DATA ex_data; int id; int st; } MYOBJ; static MYOBJ *MYOBJ_new(void) { static int count = 0; MYOBJ *obj = OPENSSL_malloc(sizeof(*obj)); if (obj != NULL) { obj->id = ++count; obj->st = CRYPTO_new_ex_data(CRYPTO_EX_INDEX_APP, obj, &obj->ex_data); } return obj; } static void MYOBJ_sethello(MYOBJ *obj, char *cp) { obj->st = CRYPTO_set_ex_data(&obj->ex_data, saved_idx, cp); if (!TEST_int_eq(obj->st, 1)) gbl_result = 0; } static char *MYOBJ_gethello(MYOBJ *obj) { return CRYPTO_get_ex_data(&obj->ex_data, saved_idx); } static void MYOBJ_sethello2(MYOBJ *obj, char *cp) { MYOBJ_EX_DATA* ex_data = CRYPTO_get_ex_data(&obj->ex_data, saved_idx2); if (TEST_ptr(ex_data)) ex_data->hello = cp; else obj->st = gbl_result = 0; } static char *MYOBJ_gethello2(MYOBJ *obj) { MYOBJ_EX_DATA* ex_data = CRYPTO_get_ex_data(&obj->ex_data, saved_idx2); if (TEST_ptr(ex_data)) return ex_data->hello; obj->st = gbl_result = 0; return NULL; } static void MYOBJ_allochello3(MYOBJ *obj, char *cp) { MYOBJ_EX_DATA* ex_data = NULL; if (TEST_ptr_null(ex_data = CRYPTO_get_ex_data(&obj->ex_data, saved_idx3)) && TEST_true(CRYPTO_alloc_ex_data(CRYPTO_EX_INDEX_APP, obj, &obj->ex_data, saved_idx3)) && TEST_ptr(ex_data = CRYPTO_get_ex_data(&obj->ex_data, saved_idx3))) ex_data->hello = cp; else obj->st = gbl_result = 0; } static char *MYOBJ_gethello3(MYOBJ *obj) { MYOBJ_EX_DATA* ex_data = CRYPTO_get_ex_data(&obj->ex_data, saved_idx3); if (TEST_ptr(ex_data)) return ex_data->hello; obj->st = gbl_result = 0; return NULL; } static void MYOBJ_free(MYOBJ *obj) { if (obj != NULL) { CRYPTO_free_ex_data(CRYPTO_EX_INDEX_APP, obj, &obj->ex_data); OPENSSL_free(obj); } } static MYOBJ *MYOBJ_dup(MYOBJ *in) { MYOBJ *obj = MYOBJ_new(); if (obj != NULL) obj->st |= CRYPTO_dup_ex_data(CRYPTO_EX_INDEX_APP, &obj->ex_data, &in->ex_data); return obj; } static int test_exdata(void) { MYOBJ *t1 = NULL, *t2 = NULL, *t3 = NULL; MYOBJ_EX_DATA *ex_data = NULL; const char *cp; char *p; int res = 0; gbl_result = 1; if (!TEST_ptr(p = OPENSSL_strdup("hello world"))) return 0; saved_argl = 21; if (!TEST_ptr(saved_argp = OPENSSL_malloc(1))) goto err; saved_idx = CRYPTO_get_ex_new_index(CRYPTO_EX_INDEX_APP, saved_argl, saved_argp, exnew, exdup, exfree); saved_idx2 = CRYPTO_get_ex_new_index(CRYPTO_EX_INDEX_APP, saved_argl, saved_argp, exnew2, exdup2, exfree2); t1 = MYOBJ_new(); t2 = MYOBJ_new(); if (!TEST_int_eq(t1->st, 1) || !TEST_int_eq(t2->st, 1)) goto err; if (!TEST_ptr(CRYPTO_get_ex_data(&t1->ex_data, saved_idx2))) goto err; /* * saved_idx3 differs from other indexes by being created after the exdata * was initialized. */ saved_idx3 = CRYPTO_get_ex_new_index(CRYPTO_EX_INDEX_APP, saved_argl, saved_argp, exnew2, exdup2, exfree2); if (!TEST_ptr_null(CRYPTO_get_ex_data(&t1->ex_data, saved_idx3))) goto err; MYOBJ_sethello(t1, p); cp = MYOBJ_gethello(t1); if (!TEST_ptr_eq(cp, p)) goto err; MYOBJ_sethello2(t1, p); cp = MYOBJ_gethello2(t1); if (!TEST_ptr_eq(cp, p)) goto err; MYOBJ_allochello3(t1, p); cp = MYOBJ_gethello3(t1); if (!TEST_ptr_eq(cp, p)) goto err; cp = MYOBJ_gethello(t2); if (!TEST_ptr_null(cp)) goto err; cp = MYOBJ_gethello2(t2); if (!TEST_ptr_null(cp)) goto err; t3 = MYOBJ_dup(t1); if (!TEST_int_eq(t3->st, 1)) goto err; ex_data = CRYPTO_get_ex_data(&t3->ex_data, saved_idx2); if (!TEST_ptr(ex_data)) goto err; if (!TEST_int_eq(ex_data->dup, 1)) goto err; cp = MYOBJ_gethello(t3); if (!TEST_ptr_eq(cp, p)) goto err; cp = MYOBJ_gethello2(t3); if (!TEST_ptr_eq(cp, p)) goto err; cp = MYOBJ_gethello3(t3); if (!TEST_ptr_eq(cp, p)) goto err; if (gbl_result) res = 1; err: MYOBJ_free(t1); MYOBJ_free(t2); MYOBJ_free(t3); OPENSSL_free(saved_argp); saved_argp = NULL; OPENSSL_free(p); return res; } int setup_tests(void) { ADD_TEST(test_exdata); return 1; }
./openssl/test/ct_test.c
/* * Copyright 2016-2022 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <ctype.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <openssl/ct.h> #include <openssl/err.h> #include <openssl/pem.h> #include <openssl/x509.h> #include <openssl/x509v3.h> #include "testutil.h" #include <openssl/crypto.h> #ifndef OPENSSL_NO_CT /* Used when declaring buffers to read text files into */ # define CT_TEST_MAX_FILE_SIZE 8096 static char *certs_dir = NULL; static char *ct_dir = NULL; typedef struct ct_test_fixture { const char *test_case_name; /* The current time in milliseconds */ uint64_t epoch_time_in_ms; /* The CT log store to use during tests */ CTLOG_STORE* ctlog_store; /* Set the following to test handling of SCTs in X509 certificates */ const char *certs_dir; char *certificate_file; char *issuer_file; /* Expected number of SCTs */ int expected_sct_count; /* Expected number of valid SCTS */ int expected_valid_sct_count; /* Set the following to test handling of SCTs in TLS format */ const unsigned char *tls_sct_list; size_t tls_sct_list_len; STACK_OF(SCT) *sct_list; /* * A file to load the expected SCT text from. * This text will be compared to the actual text output during the test. * A maximum of |CT_TEST_MAX_FILE_SIZE| bytes will be read of this file. */ const char *sct_dir; const char *sct_text_file; /* Whether to test the validity of the SCT(s) */ int test_validity; } CT_TEST_FIXTURE; static CT_TEST_FIXTURE *set_up(const char *const test_case_name) { CT_TEST_FIXTURE *fixture = NULL; if (!TEST_ptr(fixture = OPENSSL_zalloc(sizeof(*fixture)))) goto end; fixture->test_case_name = test_case_name; fixture->epoch_time_in_ms = 1580335307000ULL; /* Wed 29 Jan 2020 10:01:47 PM UTC */ if (!TEST_ptr(fixture->ctlog_store = CTLOG_STORE_new()) || !TEST_int_eq( CTLOG_STORE_load_default_file(fixture->ctlog_store), 1)) goto end; return fixture; end: if (fixture != NULL) CTLOG_STORE_free(fixture->ctlog_store); OPENSSL_free(fixture); TEST_error("Failed to setup"); return NULL; } static void tear_down(CT_TEST_FIXTURE *fixture) { if (fixture != NULL) { CTLOG_STORE_free(fixture->ctlog_store); SCT_LIST_free(fixture->sct_list); } OPENSSL_free(fixture); } static X509 *load_pem_cert(const char *dir, const char *file) { X509 *cert = NULL; char *file_path = test_mk_file_path(dir, file); if (file_path != NULL) { BIO *cert_io = BIO_new_file(file_path, "r"); if (cert_io != NULL) cert = PEM_read_bio_X509(cert_io, NULL, NULL, NULL); BIO_free(cert_io); } OPENSSL_free(file_path); return cert; } static int read_text_file(const char *dir, const char *file, char *buffer, int buffer_length) { int len = -1; char *file_path = test_mk_file_path(dir, file); if (file_path != NULL) { BIO *file_io = BIO_new_file(file_path, "r"); if (file_io != NULL) len = BIO_read(file_io, buffer, buffer_length); BIO_free(file_io); } OPENSSL_free(file_path); return len; } static int compare_sct_list_printout(STACK_OF(SCT) *sct, const char *expected_output) { BIO *text_buffer = NULL; char *actual_output = NULL; int result = 0; if (!TEST_ptr(text_buffer = BIO_new(BIO_s_mem()))) goto end; SCT_LIST_print(sct, text_buffer, 0, "\n", NULL); /* Append \0 because we're about to use the buffer contents as a string. */ if (!TEST_true(BIO_write(text_buffer, "\0", 1))) goto end; BIO_get_mem_data(text_buffer, &actual_output); if (!TEST_str_eq(actual_output, expected_output)) goto end; result = 1; end: BIO_free(text_buffer); return result; } static int compare_extension_printout(X509_EXTENSION *extension, const char *expected_output) { BIO *text_buffer = NULL; char *actual_output = NULL; int result = 0; if (!TEST_ptr(text_buffer = BIO_new(BIO_s_mem())) || !TEST_true(X509V3_EXT_print(text_buffer, extension, X509V3_EXT_DEFAULT, 0))) goto end; /* Append \n because it's easier to create files that end with one. */ if (!TEST_true(BIO_write(text_buffer, "\n", 1))) goto end; /* Append \0 because we're about to use the buffer contents as a string. */ if (!TEST_true(BIO_write(text_buffer, "\0", 1))) goto end; BIO_get_mem_data(text_buffer, &actual_output); if (!TEST_str_eq(actual_output, expected_output)) goto end; result = 1; end: BIO_free(text_buffer); return result; } static int assert_validity(CT_TEST_FIXTURE *fixture, STACK_OF(SCT) *scts, CT_POLICY_EVAL_CTX *policy_ctx) { int invalid_sct_count = 0; int valid_sct_count = 0; int i; if (!TEST_int_ge(SCT_LIST_validate(scts, policy_ctx), 0)) return 0; for (i = 0; i < sk_SCT_num(scts); ++i) { SCT *sct_i = sk_SCT_value(scts, i); switch (SCT_get_validation_status(sct_i)) { case SCT_VALIDATION_STATUS_VALID: ++valid_sct_count; break; case SCT_VALIDATION_STATUS_INVALID: ++invalid_sct_count; break; case SCT_VALIDATION_STATUS_NOT_SET: case SCT_VALIDATION_STATUS_UNKNOWN_LOG: case SCT_VALIDATION_STATUS_UNVERIFIED: case SCT_VALIDATION_STATUS_UNKNOWN_VERSION: /* Ignore other validation statuses. */ break; } } if (!TEST_int_eq(valid_sct_count, fixture->expected_valid_sct_count)) { int unverified_sct_count = sk_SCT_num(scts) - invalid_sct_count - valid_sct_count; TEST_info("%d SCTs failed, %d SCTs unverified", invalid_sct_count, unverified_sct_count); return 0; } return 1; } static int execute_cert_test(CT_TEST_FIXTURE *fixture) { int success = 0; X509 *cert = NULL, *issuer = NULL; STACK_OF(SCT) *scts = NULL; SCT *sct = NULL; char expected_sct_text[CT_TEST_MAX_FILE_SIZE]; int sct_text_len = 0; unsigned char *tls_sct_list = NULL; size_t tls_sct_list_len = 0; CT_POLICY_EVAL_CTX *ct_policy_ctx = CT_POLICY_EVAL_CTX_new(); if (fixture->sct_text_file != NULL) { sct_text_len = read_text_file(fixture->sct_dir, fixture->sct_text_file, expected_sct_text, CT_TEST_MAX_FILE_SIZE - 1); if (!TEST_int_ge(sct_text_len, 0)) goto end; expected_sct_text[sct_text_len] = '\0'; } CT_POLICY_EVAL_CTX_set_shared_CTLOG_STORE( ct_policy_ctx, fixture->ctlog_store); CT_POLICY_EVAL_CTX_set_time(ct_policy_ctx, fixture->epoch_time_in_ms); if (fixture->certificate_file != NULL) { int sct_extension_index; int i; X509_EXTENSION *sct_extension = NULL; if (!TEST_ptr(cert = load_pem_cert(fixture->certs_dir, fixture->certificate_file))) goto end; CT_POLICY_EVAL_CTX_set1_cert(ct_policy_ctx, cert); if (fixture->issuer_file != NULL) { if (!TEST_ptr(issuer = load_pem_cert(fixture->certs_dir, fixture->issuer_file))) goto end; CT_POLICY_EVAL_CTX_set1_issuer(ct_policy_ctx, issuer); } sct_extension_index = X509_get_ext_by_NID(cert, NID_ct_precert_scts, -1); sct_extension = X509_get_ext(cert, sct_extension_index); if (fixture->expected_sct_count > 0) { if (!TEST_ptr(sct_extension)) goto end; if (fixture->sct_text_file && !compare_extension_printout(sct_extension, expected_sct_text)) goto end; scts = X509V3_EXT_d2i(sct_extension); for (i = 0; i < sk_SCT_num(scts); ++i) { SCT *sct_i = sk_SCT_value(scts, i); if (!TEST_int_eq(SCT_get_source(sct_i), SCT_SOURCE_X509V3_EXTENSION)) { goto end; } } if (fixture->test_validity) { if (!assert_validity(fixture, scts, ct_policy_ctx)) goto end; } } else if (!TEST_ptr_null(sct_extension)) { goto end; } } if (fixture->tls_sct_list != NULL) { const unsigned char *p = fixture->tls_sct_list; if (!TEST_ptr(o2i_SCT_LIST(&scts, &p, fixture->tls_sct_list_len))) goto end; if (fixture->test_validity && cert != NULL) { if (!assert_validity(fixture, scts, ct_policy_ctx)) goto end; } if (fixture->sct_text_file && !compare_sct_list_printout(scts, expected_sct_text)) { goto end; } tls_sct_list_len = i2o_SCT_LIST(scts, &tls_sct_list); if (!TEST_mem_eq(fixture->tls_sct_list, fixture->tls_sct_list_len, tls_sct_list, tls_sct_list_len)) goto end; } success = 1; end: X509_free(cert); X509_free(issuer); SCT_LIST_free(scts); SCT_free(sct); CT_POLICY_EVAL_CTX_free(ct_policy_ctx); OPENSSL_free(tls_sct_list); return success; } # define SETUP_CT_TEST_FIXTURE() SETUP_TEST_FIXTURE(CT_TEST_FIXTURE, set_up) # define EXECUTE_CT_TEST() EXECUTE_TEST(execute_cert_test, tear_down) static int test_no_scts_in_certificate(void) { SETUP_CT_TEST_FIXTURE(); fixture->certs_dir = certs_dir; fixture->certificate_file = "leaf.pem"; fixture->issuer_file = "subinterCA.pem"; fixture->expected_sct_count = 0; EXECUTE_CT_TEST(); return result; } static int test_one_sct_in_certificate(void) { SETUP_CT_TEST_FIXTURE(); fixture->certs_dir = certs_dir; fixture->certificate_file = "embeddedSCTs1.pem"; fixture->issuer_file = "embeddedSCTs1_issuer.pem"; fixture->expected_sct_count = 1; fixture->sct_dir = certs_dir; fixture->sct_text_file = "embeddedSCTs1.sct"; EXECUTE_CT_TEST(); return result; } static int test_multiple_scts_in_certificate(void) { SETUP_CT_TEST_FIXTURE(); fixture->certs_dir = certs_dir; fixture->certificate_file = "embeddedSCTs3.pem"; fixture->issuer_file = "embeddedSCTs3_issuer.pem"; fixture->expected_sct_count = 3; fixture->sct_dir = certs_dir; fixture->sct_text_file = "embeddedSCTs3.sct"; EXECUTE_CT_TEST(); return result; } static int test_verify_one_sct(void) { SETUP_CT_TEST_FIXTURE(); fixture->certs_dir = certs_dir; fixture->certificate_file = "embeddedSCTs1.pem"; fixture->issuer_file = "embeddedSCTs1_issuer.pem"; fixture->expected_sct_count = fixture->expected_valid_sct_count = 1; fixture->test_validity = 1; EXECUTE_CT_TEST(); return result; } static int test_verify_multiple_scts(void) { SETUP_CT_TEST_FIXTURE(); fixture->certs_dir = certs_dir; fixture->certificate_file = "embeddedSCTs3.pem"; fixture->issuer_file = "embeddedSCTs3_issuer.pem"; fixture->expected_sct_count = fixture->expected_valid_sct_count = 3; fixture->test_validity = 1; EXECUTE_CT_TEST(); return result; } static int test_verify_fails_for_future_sct(void) { SETUP_CT_TEST_FIXTURE(); fixture->epoch_time_in_ms = 1365094800000ULL; /* Apr 4 17:00:00 2013 GMT */ fixture->certs_dir = certs_dir; fixture->certificate_file = "embeddedSCTs1.pem"; fixture->issuer_file = "embeddedSCTs1_issuer.pem"; fixture->expected_sct_count = 1; fixture->expected_valid_sct_count = 0; fixture->test_validity = 1; EXECUTE_CT_TEST(); return result; } static int test_decode_tls_sct(void) { const unsigned char tls_sct_list[] = "\x00\x78" /* length of list */ "\x00\x76" "\x00" /* version */ /* log ID */ "\xDF\x1C\x2E\xC1\x15\x00\x94\x52\x47\xA9\x61\x68\x32\x5D\xDC\x5C\x79" "\x59\xE8\xF7\xC6\xD3\x88\xFC\x00\x2E\x0B\xBD\x3F\x74\xD7\x64" "\x00\x00\x01\x3D\xDB\x27\xDF\x93" /* timestamp */ "\x00\x00" /* extensions length */ "" /* extensions */ "\x04\x03" /* hash and signature algorithms */ "\x00\x47" /* signature length */ /* signature */ "\x30\x45\x02\x20\x48\x2F\x67\x51\xAF\x35\xDB\xA6\x54\x36\xBE\x1F\xD6" "\x64\x0F\x3D\xBF\x9A\x41\x42\x94\x95\x92\x45\x30\x28\x8F\xA3\xE5\xE2" "\x3E\x06\x02\x21\x00\xE4\xED\xC0\xDB\x3A\xC5\x72\xB1\xE2\xF5\xE8\xAB" "\x6A\x68\x06\x53\x98\x7D\xCF\x41\x02\x7D\xFE\xFF\xA1\x05\x51\x9D\x89" "\xED\xBF\x08"; SETUP_CT_TEST_FIXTURE(); fixture->tls_sct_list = tls_sct_list; fixture->tls_sct_list_len = 0x7a; fixture->sct_dir = ct_dir; fixture->sct_text_file = "tls1.sct"; EXECUTE_CT_TEST(); return result; } static int test_encode_tls_sct(void) { const char log_id[] = "3xwuwRUAlFJHqWFoMl3cXHlZ6PfG04j8AC4LvT9012Q="; const uint64_t timestamp = 1; const char extensions[] = ""; const char signature[] = "BAMARzBAMiBIL2dRrzXbplQ2vh/WZA89v5pBQpSVkkUwKI+j5" "eI+BgIhAOTtwNs6xXKx4vXoq2poBlOYfc9BAn3+/6EFUZ2J7b8I"; SCT *sct = NULL; SETUP_CT_TEST_FIXTURE(); fixture->sct_list = sk_SCT_new_null(); if (fixture->sct_list == NULL) return 0; if (!TEST_ptr(sct = SCT_new_from_base64(SCT_VERSION_V1, log_id, CT_LOG_ENTRY_TYPE_X509, timestamp, extensions, signature))) return 0; sk_SCT_push(fixture->sct_list, sct); fixture->sct_dir = ct_dir; fixture->sct_text_file = "tls1.sct"; EXECUTE_CT_TEST(); return result; } /* * Tests that the CT_POLICY_EVAL_CTX default time is approximately now. * Allow +-10 minutes, as it may compensate for clock skew. */ static int test_default_ct_policy_eval_ctx_time_is_now(void) { int success = 0; CT_POLICY_EVAL_CTX *ct_policy_ctx = CT_POLICY_EVAL_CTX_new(); const time_t default_time = (time_t)(CT_POLICY_EVAL_CTX_get_time(ct_policy_ctx) / 1000); const time_t time_tolerance = 600; /* 10 minutes */ if (!TEST_time_t_le(abs((int)difftime(time(NULL), default_time)), time_tolerance)) goto end; success = 1; end: CT_POLICY_EVAL_CTX_free(ct_policy_ctx); return success; } static int test_ctlog_from_base64(void) { CTLOG *ctlogp = NULL; const char notb64[] = "\01\02\03\04"; const char pad[] = "===="; const char name[] = "name"; /* We expect these to both fail! */ if (!TEST_true(!CTLOG_new_from_base64(&ctlogp, notb64, name)) || !TEST_true(!CTLOG_new_from_base64(&ctlogp, pad, name))) return 0; return 1; } #endif int setup_tests(void) { #ifndef OPENSSL_NO_CT if ((ct_dir = getenv("CT_DIR")) == NULL) ct_dir = "ct"; if ((certs_dir = getenv("CERTS_DIR")) == NULL) certs_dir = "certs"; ADD_TEST(test_no_scts_in_certificate); ADD_TEST(test_one_sct_in_certificate); ADD_TEST(test_multiple_scts_in_certificate); ADD_TEST(test_verify_one_sct); ADD_TEST(test_verify_multiple_scts); ADD_TEST(test_verify_fails_for_future_sct); ADD_TEST(test_decode_tls_sct); ADD_TEST(test_encode_tls_sct); ADD_TEST(test_default_ct_policy_eval_ctx_time_is_now); ADD_TEST(test_ctlog_from_base64); #else printf("No CT support\n"); #endif return 1; }
./openssl/test/provider_fallback_test.c
/* * Copyright 2020-2021 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <stddef.h> #include <openssl/provider.h> #include <openssl/evp.h> #include "testutil.h" static int test_provider(OSSL_LIB_CTX *ctx) { EVP_KEYMGMT *rsameth = NULL; const OSSL_PROVIDER *prov = NULL; int ok; ok = TEST_true(OSSL_PROVIDER_available(ctx, "default")) && TEST_ptr(rsameth = EVP_KEYMGMT_fetch(ctx, "RSA", NULL)) && TEST_ptr(prov = EVP_KEYMGMT_get0_provider(rsameth)) && TEST_str_eq(OSSL_PROVIDER_get0_name(prov), "default"); EVP_KEYMGMT_free(rsameth); return ok; } static int test_fallback_provider(void) { return test_provider(NULL); } static int test_explicit_provider(void) { OSSL_LIB_CTX *ctx = NULL; OSSL_PROVIDER *prov = NULL; int ok; ok = TEST_ptr(ctx = OSSL_LIB_CTX_new()) && TEST_ptr(prov = OSSL_PROVIDER_load(ctx, "default")) && test_provider(ctx) && TEST_true(OSSL_PROVIDER_unload(prov)); OSSL_LIB_CTX_free(ctx); return ok; } int setup_tests(void) { ADD_TEST(test_fallback_provider); ADD_TEST(test_explicit_provider); return 1; }