repo
stringlengths
1
152
file
stringlengths
14
221
code
stringlengths
501
25k
file_length
int64
501
25k
avg_line_length
float64
20
99.5
max_line_length
int64
21
134
extension_type
stringclasses
2 values
openssl
openssl-master/test/moduleloadtest.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 */ /* * Extremely simple dynamic loader, must never be linked with anything other * than the standard C library. Its purpose is to try to load a dynamic module * and verify the presence of one symbol, if that's given. */ #include <stdio.h> #include <stdlib.h> #include <openssl/core.h> #include "simpledynamic.h" static int test_load(const char *path, const char *symbol) { #ifdef SD_INIT SD sd = SD_INIT; SD_SYM sym; int ret; if (!sd_load(path, &sd, SD_MODULE)) return 0; ret = symbol == NULL || sd_sym(sd, symbol, &sym); if (!sd_close(sd)) ret = 0; return ret; #else fprintf(stderr, "No dynamic loader\n"); return 0; #endif } int main(int argc, char *argv[]) { const char *m, *s; if (argc != 2 && argc != 3) { fprintf(stderr, "Usage: %s sharedobject [ entrypoint ]\n", argv[0]); return 1; } m = argv[1]; s = argc == 3 ? argv[2] : NULL; return test_load(m, s) ? 0 : 1; }
1,310
23.277778
79
c
openssl
openssl-master/test/namemap_internal_test.c
/* * Copyright 2019-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 <openssl/evp.h> #include "internal/namemap.h" #include "testutil.h" #define NAME1 "name1" #define NAME2 "name2" #define ALIAS1 "alias1" #define ALIAS1_UC "ALIAS1" static int test_namemap_empty(void) { OSSL_NAMEMAP *nm = NULL; int ok; ok = TEST_int_eq(ossl_namemap_empty(NULL), 1) && TEST_ptr(nm = ossl_namemap_new()) && TEST_int_eq(ossl_namemap_empty(nm), 1) && TEST_int_ne(ossl_namemap_add_name(nm, 0, NAME1), 0) && TEST_int_eq(ossl_namemap_empty(nm), 0); ossl_namemap_free(nm); return ok; } static int test_namemap(OSSL_NAMEMAP *nm) { int num1 = ossl_namemap_add_name(nm, 0, NAME1); int num2 = ossl_namemap_add_name(nm, 0, NAME2); int num3 = ossl_namemap_add_name(nm, num1, ALIAS1); int num4 = ossl_namemap_add_name(nm, 0, ALIAS1_UC); int check1 = ossl_namemap_name2num(nm, NAME1); int check2 = ossl_namemap_name2num(nm, NAME2); int check3 = ossl_namemap_name2num(nm, ALIAS1); int check4 = ossl_namemap_name2num(nm, ALIAS1_UC); int false1 = ossl_namemap_name2num(nm, "cookie"); return TEST_int_ne(num1, 0) && TEST_int_ne(num2, 0) && TEST_int_eq(num1, num3) && TEST_int_eq(num3, num4) && TEST_int_eq(num1, check1) && TEST_int_eq(num2, check2) && TEST_int_eq(num3, check3) && TEST_int_eq(num4, check4) && TEST_int_eq(false1, 0); } static int test_namemap_independent(void) { OSSL_NAMEMAP *nm = ossl_namemap_new(); int ok = TEST_ptr(nm) && test_namemap(nm); ossl_namemap_free(nm); return ok; } static int test_namemap_stored(void) { OSSL_NAMEMAP *nm = ossl_namemap_stored(NULL); return TEST_ptr(nm) && test_namemap(nm); } /* * Test that EVP_get_digestbyname() will use the namemap when it can't find * entries in the legacy method database. */ static int test_digestbyname(void) { int id; OSSL_NAMEMAP *nm = ossl_namemap_stored(NULL); const EVP_MD *sha256, *foo; if (!TEST_ptr(nm)) return 0; id = ossl_namemap_add_name(nm, 0, "SHA256"); if (!TEST_int_ne(id, 0)) return 0; if (!TEST_int_eq(ossl_namemap_add_name(nm, id, "foo"), id)) return 0; sha256 = EVP_get_digestbyname("SHA256"); if (!TEST_ptr(sha256)) return 0; foo = EVP_get_digestbyname("foo"); if (!TEST_ptr_eq(sha256, foo)) return 0; return 1; } /* * Test that EVP_get_cipherbyname() will use the namemap when it can't find * entries in the legacy method database. */ static int test_cipherbyname(void) { int id; OSSL_NAMEMAP *nm = ossl_namemap_stored(NULL); const EVP_CIPHER *aes128, *bar; if (!TEST_ptr(nm)) return 0; id = ossl_namemap_add_name(nm, 0, "AES-128-CBC"); if (!TEST_int_ne(id, 0)) return 0; if (!TEST_int_eq(ossl_namemap_add_name(nm, id, "bar"), id)) return 0; aes128 = EVP_get_cipherbyname("AES-128-CBC"); if (!TEST_ptr(aes128)) return 0; bar = EVP_get_cipherbyname("bar"); if (!TEST_ptr_eq(aes128, bar)) return 0; return 1; } /* * Test that EVP_CIPHER_is_a() responds appropriately, even for ciphers that * are entirely legacy. */ static int test_cipher_is_a(void) { EVP_CIPHER *fetched = EVP_CIPHER_fetch(NULL, "AES-256-CCM", NULL); int rv = 1; if (!TEST_ptr(fetched)) return 0; if (!TEST_true(EVP_CIPHER_is_a(fetched, "id-aes256-CCM")) || !TEST_false(EVP_CIPHER_is_a(fetched, "AES-128-GCM"))) rv = 0; if (!TEST_true(EVP_CIPHER_is_a(EVP_aes_256_gcm(), "AES-256-GCM")) || !TEST_false(EVP_CIPHER_is_a(EVP_aes_256_gcm(), "AES-128-CCM"))) rv = 0; EVP_CIPHER_free(fetched); return rv; } /* * Test that EVP_MD_is_a() responds appropriately, even for MDs that are * entirely legacy. */ static int test_digest_is_a(void) { EVP_MD *fetched = EVP_MD_fetch(NULL, "SHA2-512", NULL); int rv = 1; if (!TEST_ptr(fetched)) return 0; if (!TEST_true(EVP_MD_is_a(fetched, "SHA512")) || !TEST_false(EVP_MD_is_a(fetched, "SHA1"))) rv = 0; if (!TEST_true(EVP_MD_is_a(EVP_sha256(), "SHA2-256")) || !TEST_false(EVP_MD_is_a(EVP_sha256(), "SHA3-256"))) rv = 0; EVP_MD_free(fetched); return rv; } int setup_tests(void) { ADD_TEST(test_namemap_empty); ADD_TEST(test_namemap_independent); ADD_TEST(test_namemap_stored); ADD_TEST(test_digestbyname); ADD_TEST(test_cipherbyname); ADD_TEST(test_digest_is_a); ADD_TEST(test_cipher_is_a); return 1; }
4,909
25.684783
76
c
openssl
openssl-master/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; }
1,757
27.819672
79
c
openssl
openssl-master/test/ocspapitest.c
/* * Copyright 2017-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 <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; }
6,421
26.097046
75
c
openssl
openssl-master/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; }
6,085
24.464435
82
c
openssl
openssl-master/test/p_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 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); }
11,196
33.88162
85
c
openssl
openssl-master/test/packettest.c
/* * Copyright 2015-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 "internal/packet_quic.h" #include "testutil.h" #define BUF_LEN 255 static unsigned char smbuf[BUF_LEN + 1]; static int test_PACKET_remaining(void) { PACKET pkt; if (!TEST_true(PACKET_buf_init(&pkt, smbuf, BUF_LEN)) || !TEST_size_t_eq(PACKET_remaining(&pkt), BUF_LEN) || !TEST_true(PACKET_forward(&pkt, BUF_LEN - 1)) || !TEST_size_t_eq(PACKET_remaining(&pkt), 1) || !TEST_true(PACKET_forward(&pkt, 1)) || !TEST_size_t_eq(PACKET_remaining(&pkt), 0)) return 0; return 1; } static int test_PACKET_end(void) { PACKET pkt; if (!TEST_true(PACKET_buf_init(&pkt, smbuf, BUF_LEN)) || !TEST_size_t_eq(PACKET_remaining(&pkt), BUF_LEN) || !TEST_ptr_eq(PACKET_end(&pkt), smbuf + BUF_LEN) || !TEST_true(PACKET_forward(&pkt, BUF_LEN - 1)) || !TEST_ptr_eq(PACKET_end(&pkt), smbuf + BUF_LEN) || !TEST_true(PACKET_forward(&pkt, 1)) || !TEST_ptr_eq(PACKET_end(&pkt), smbuf + BUF_LEN)) return 0; return 1; } static int test_PACKET_get_1(void) { unsigned int i = 0; PACKET pkt; if (!TEST_true(PACKET_buf_init(&pkt, smbuf, BUF_LEN)) || !TEST_true(PACKET_get_1(&pkt, &i)) || !TEST_uint_eq(i, 0x02) || !TEST_true(PACKET_forward(&pkt, BUF_LEN - 2)) || !TEST_true(PACKET_get_1(&pkt, &i)) || !TEST_uint_eq(i, 0xfe) || !TEST_false(PACKET_get_1(&pkt, &i))) return 0; return 1; } static int test_PACKET_get_4(void) { unsigned long i = 0; PACKET pkt; if (!TEST_true(PACKET_buf_init(&pkt, smbuf, BUF_LEN)) || !TEST_true(PACKET_get_4(&pkt, &i)) || !TEST_ulong_eq(i, 0x08060402UL) || !TEST_true(PACKET_forward(&pkt, BUF_LEN - 8)) || !TEST_true(PACKET_get_4(&pkt, &i)) || !TEST_ulong_eq(i, 0xfefcfaf8UL) || !TEST_false(PACKET_get_4(&pkt, &i))) return 0; return 1; } static int test_PACKET_get_net_2(void) { unsigned int i = 0; PACKET pkt; if (!TEST_true(PACKET_buf_init(&pkt, smbuf, BUF_LEN)) || !TEST_true(PACKET_get_net_2(&pkt, &i)) || !TEST_uint_eq(i, 0x0204) || !TEST_true(PACKET_forward(&pkt, BUF_LEN - 4)) || !TEST_true(PACKET_get_net_2(&pkt, &i)) || !TEST_uint_eq(i, 0xfcfe) || !TEST_false(PACKET_get_net_2(&pkt, &i))) return 0; return 1; } static int test_PACKET_get_net_3(void) { unsigned long i = 0; PACKET pkt; if (!TEST_true(PACKET_buf_init(&pkt, smbuf, BUF_LEN)) || !TEST_true(PACKET_get_net_3(&pkt, &i)) || !TEST_ulong_eq(i, 0x020406UL) || !TEST_true(PACKET_forward(&pkt, BUF_LEN - 6)) || !TEST_true(PACKET_get_net_3(&pkt, &i)) || !TEST_ulong_eq(i, 0xfafcfeUL) || !TEST_false(PACKET_get_net_3(&pkt, &i))) return 0; return 1; } static int test_PACKET_get_net_4(void) { unsigned long i = 0; PACKET pkt; if (!TEST_true(PACKET_buf_init(&pkt, smbuf, BUF_LEN)) || !TEST_true(PACKET_get_net_4(&pkt, &i)) || !TEST_ulong_eq(i, 0x02040608UL) || !TEST_true(PACKET_forward(&pkt, BUF_LEN - 8)) || !TEST_true(PACKET_get_net_4(&pkt, &i)) || !TEST_ulong_eq(i, 0xf8fafcfeUL) || !TEST_false(PACKET_get_net_4(&pkt, &i))) return 0; return 1; } static int test_PACKET_get_sub_packet(void) { PACKET pkt, subpkt; unsigned long i = 0; if (!TEST_true(PACKET_buf_init(&pkt, smbuf, BUF_LEN)) || !TEST_true(PACKET_get_sub_packet(&pkt, &subpkt, 4)) || !TEST_true(PACKET_get_net_4(&subpkt, &i)) || !TEST_ulong_eq(i, 0x02040608UL) || !TEST_size_t_eq(PACKET_remaining(&subpkt), 0) || !TEST_true(PACKET_forward(&pkt, BUF_LEN - 8)) || !TEST_true(PACKET_get_sub_packet(&pkt, &subpkt, 4)) || !TEST_true(PACKET_get_net_4(&subpkt, &i)) || !TEST_ulong_eq(i, 0xf8fafcfeUL) || !TEST_size_t_eq(PACKET_remaining(&subpkt), 0) || !TEST_false(PACKET_get_sub_packet(&pkt, &subpkt, 4))) return 0; return 1; } static int test_PACKET_get_bytes(void) { const unsigned char *bytes = NULL; PACKET pkt; if (!TEST_true(PACKET_buf_init(&pkt, smbuf, BUF_LEN)) || !TEST_true(PACKET_get_bytes(&pkt, &bytes, 4)) || !TEST_uchar_eq(bytes[0], 2) || !TEST_uchar_eq(bytes[1], 4) || !TEST_uchar_eq(bytes[2], 6) || !TEST_uchar_eq(bytes[3], 8) || !TEST_size_t_eq(PACKET_remaining(&pkt), BUF_LEN -4) || !TEST_true(PACKET_forward(&pkt, BUF_LEN - 8)) || !TEST_true(PACKET_get_bytes(&pkt, &bytes, 4)) || !TEST_uchar_eq(bytes[0], 0xf8) || !TEST_uchar_eq(bytes[1], 0xfa) || !TEST_uchar_eq(bytes[2], 0xfc) || !TEST_uchar_eq(bytes[3], 0xfe) || !TEST_false(PACKET_remaining(&pkt))) return 0; return 1; } static int test_PACKET_copy_bytes(void) { unsigned char bytes[4]; PACKET pkt; if (!TEST_true(PACKET_buf_init(&pkt, smbuf, BUF_LEN)) || !TEST_true(PACKET_copy_bytes(&pkt, bytes, 4)) || !TEST_char_eq(bytes[0], 2) || !TEST_char_eq(bytes[1], 4) || !TEST_char_eq(bytes[2], 6) || !TEST_char_eq(bytes[3], 8) || !TEST_size_t_eq(PACKET_remaining(&pkt), BUF_LEN - 4) || !TEST_true(PACKET_forward(&pkt, BUF_LEN - 8)) || !TEST_true(PACKET_copy_bytes(&pkt, bytes, 4)) || !TEST_uchar_eq(bytes[0], 0xf8) || !TEST_uchar_eq(bytes[1], 0xfa) || !TEST_uchar_eq(bytes[2], 0xfc) || !TEST_uchar_eq(bytes[3], 0xfe) || !TEST_false(PACKET_remaining(&pkt))) return 0; return 1; } static int test_PACKET_copy_all(void) { unsigned char tmp[BUF_LEN]; PACKET pkt; size_t len; if (!TEST_true(PACKET_buf_init(&pkt, smbuf, BUF_LEN)) || !TEST_true(PACKET_copy_all(&pkt, tmp, BUF_LEN, &len)) || !TEST_size_t_eq(len, BUF_LEN) || !TEST_mem_eq(smbuf, BUF_LEN, tmp, BUF_LEN) || !TEST_size_t_eq(PACKET_remaining(&pkt), BUF_LEN) || !TEST_false(PACKET_copy_all(&pkt, tmp, BUF_LEN - 1, &len))) return 0; return 1; } static int test_PACKET_memdup(void) { unsigned char *data = NULL; size_t len; PACKET pkt; int result = 0; if (!TEST_true(PACKET_buf_init(&pkt, smbuf, BUF_LEN)) || !TEST_true(PACKET_memdup(&pkt, &data, &len)) || !TEST_size_t_eq(len, BUF_LEN) || !TEST_mem_eq(data, len, PACKET_data(&pkt), len) || !TEST_true(PACKET_forward(&pkt, 10)) || !TEST_true(PACKET_memdup(&pkt, &data, &len)) || !TEST_size_t_eq(len, BUF_LEN - 10) || !TEST_mem_eq(data, len, PACKET_data(&pkt), len)) goto end; result = 1; end: OPENSSL_free(data); return result; } static int test_PACKET_strndup(void) { char buf1[10], buf2[10]; char *data = NULL; PACKET pkt; int result = 0; memset(buf1, 'x', 10); memset(buf2, 'y', 10); buf2[5] = '\0'; if (!TEST_true(PACKET_buf_init(&pkt, (unsigned char*)buf1, 10)) || !TEST_true(PACKET_strndup(&pkt, &data)) || !TEST_size_t_eq(strlen(data), 10) || !TEST_strn_eq(data, buf1, 10) || !TEST_true(PACKET_buf_init(&pkt, (unsigned char*)buf2, 10)) || !TEST_true(PACKET_strndup(&pkt, &data)) || !TEST_size_t_eq(strlen(data), 5) || !TEST_str_eq(data, buf2)) goto end; result = 1; end: OPENSSL_free(data); return result; } static int test_PACKET_contains_zero_byte(void) { char buf1[10], buf2[10]; PACKET pkt; memset(buf1, 'x', 10); memset(buf2, 'y', 10); buf2[5] = '\0'; if (!TEST_true(PACKET_buf_init(&pkt, (unsigned char*)buf1, 10)) || !TEST_false(PACKET_contains_zero_byte(&pkt)) || !TEST_true(PACKET_buf_init(&pkt, (unsigned char*)buf2, 10)) || !TEST_true(PACKET_contains_zero_byte(&pkt))) return 0; return 1; } static int test_PACKET_forward(void) { const unsigned char *byte = NULL; PACKET pkt; if (!TEST_true(PACKET_buf_init(&pkt, smbuf, BUF_LEN)) || !TEST_true(PACKET_forward(&pkt, 1)) || !TEST_true(PACKET_get_bytes(&pkt, &byte, 1)) || !TEST_uchar_eq(byte[0], 4) || !TEST_true(PACKET_forward(&pkt, BUF_LEN - 3)) || !TEST_true(PACKET_get_bytes(&pkt, &byte, 1)) || !TEST_uchar_eq(byte[0], 0xfe)) return 0; return 1; } static int test_PACKET_buf_init(void) { unsigned char buf1[BUF_LEN] = { 0 }; PACKET pkt; /* Also tests PACKET_remaining() */ if (!TEST_true(PACKET_buf_init(&pkt, buf1, 4)) || !TEST_size_t_eq(PACKET_remaining(&pkt), 4) || !TEST_true(PACKET_buf_init(&pkt, buf1, BUF_LEN)) || !TEST_size_t_eq(PACKET_remaining(&pkt), BUF_LEN) || !TEST_false(PACKET_buf_init(&pkt, buf1, -1))) return 0; return 1; } static int test_PACKET_null_init(void) { PACKET pkt; PACKET_null_init(&pkt); if (!TEST_size_t_eq(PACKET_remaining(&pkt), 0) || !TEST_false(PACKET_forward(&pkt, 1))) return 0; return 1; } static int test_PACKET_equal(void) { PACKET pkt; if (!TEST_true(PACKET_buf_init(&pkt, smbuf, 4)) || !TEST_true(PACKET_equal(&pkt, smbuf, 4)) || !TEST_false(PACKET_equal(&pkt, smbuf + 1, 4)) || !TEST_true(PACKET_buf_init(&pkt, smbuf, BUF_LEN)) || !TEST_true(PACKET_equal(&pkt, smbuf, BUF_LEN)) || !TEST_false(PACKET_equal(&pkt, smbuf, BUF_LEN - 1)) || !TEST_false(PACKET_equal(&pkt, smbuf, BUF_LEN + 1)) || !TEST_false(PACKET_equal(&pkt, smbuf, 0))) return 0; return 1; } static int test_PACKET_get_length_prefixed_1(void) { unsigned char buf1[BUF_LEN]; const size_t len = 16; unsigned int i; PACKET pkt, short_pkt, subpkt; memset(&subpkt, 0, sizeof(subpkt)); buf1[0] = (unsigned char)len; for (i = 1; i < BUF_LEN; i++) buf1[i] = (i * 2) & 0xff; if (!TEST_true(PACKET_buf_init(&pkt, buf1, BUF_LEN)) || !TEST_true(PACKET_buf_init(&short_pkt, buf1, len)) || !TEST_true(PACKET_get_length_prefixed_1(&pkt, &subpkt)) || !TEST_size_t_eq(PACKET_remaining(&subpkt), len) || !TEST_true(PACKET_get_net_2(&subpkt, &i)) || !TEST_uint_eq(i, 0x0204) || !TEST_false(PACKET_get_length_prefixed_1(&short_pkt, &subpkt)) || !TEST_size_t_eq(PACKET_remaining(&short_pkt), len)) return 0; return 1; } static int test_PACKET_get_length_prefixed_2(void) { unsigned char buf1[1024]; const size_t len = 516; /* 0x0204 */ unsigned int i; PACKET pkt, short_pkt, subpkt; memset(&subpkt, 0, sizeof(subpkt)); for (i = 1; i <= 1024; i++) buf1[i - 1] = (i * 2) & 0xff; if (!TEST_true(PACKET_buf_init(&pkt, buf1, 1024)) || !TEST_true(PACKET_buf_init(&short_pkt, buf1, len)) || !TEST_true(PACKET_get_length_prefixed_2(&pkt, &subpkt)) || !TEST_size_t_eq(PACKET_remaining(&subpkt), len) || !TEST_true(PACKET_get_net_2(&subpkt, &i)) || !TEST_uint_eq(i, 0x0608) || !TEST_false(PACKET_get_length_prefixed_2(&short_pkt, &subpkt)) || !TEST_size_t_eq(PACKET_remaining(&short_pkt), len)) return 0; return 1; } static int test_PACKET_get_length_prefixed_3(void) { unsigned char buf1[1024]; const size_t len = 516; /* 0x000204 */ unsigned int i; PACKET pkt, short_pkt, subpkt; memset(&subpkt, 0, sizeof(subpkt)); for (i = 0; i < 1024; i++) buf1[i] = (i * 2) & 0xff; if (!TEST_true(PACKET_buf_init(&pkt, buf1, 1024)) || !TEST_true(PACKET_buf_init(&short_pkt, buf1, len)) || !TEST_true(PACKET_get_length_prefixed_3(&pkt, &subpkt)) || !TEST_size_t_eq(PACKET_remaining(&subpkt), len) || !TEST_true(PACKET_get_net_2(&subpkt, &i)) || !TEST_uint_eq(i, 0x0608) || !TEST_false(PACKET_get_length_prefixed_3(&short_pkt, &subpkt)) || !TEST_size_t_eq(PACKET_remaining(&short_pkt), len)) return 0; return 1; } static int test_PACKET_as_length_prefixed_1(void) { unsigned char buf1[BUF_LEN]; const size_t len = 16; unsigned int i; PACKET pkt, exact_pkt, subpkt; memset(&subpkt, 0, sizeof(subpkt)); buf1[0] = (unsigned char)len; for (i = 1; i < BUF_LEN; i++) buf1[i] = (i * 2) & 0xff; if (!TEST_true(PACKET_buf_init(&pkt, buf1, BUF_LEN)) || !TEST_true(PACKET_buf_init(&exact_pkt, buf1, len + 1)) || !TEST_false(PACKET_as_length_prefixed_1(&pkt, &subpkt)) || !TEST_size_t_eq(PACKET_remaining(&pkt), BUF_LEN) || !TEST_true(PACKET_as_length_prefixed_1(&exact_pkt, &subpkt)) || !TEST_size_t_eq(PACKET_remaining(&exact_pkt), 0) || !TEST_size_t_eq(PACKET_remaining(&subpkt), len)) return 0; return 1; } static int test_PACKET_as_length_prefixed_2(void) { unsigned char buf[1024]; const size_t len = 516; /* 0x0204 */ unsigned int i; PACKET pkt, exact_pkt, subpkt; memset(&subpkt, 0, sizeof(subpkt)); for (i = 1; i <= 1024; i++) buf[i-1] = (i * 2) & 0xff; if (!TEST_true(PACKET_buf_init(&pkt, buf, 1024)) || !TEST_true(PACKET_buf_init(&exact_pkt, buf, len + 2)) || !TEST_false(PACKET_as_length_prefixed_2(&pkt, &subpkt)) || !TEST_size_t_eq(PACKET_remaining(&pkt), 1024) || !TEST_true(PACKET_as_length_prefixed_2(&exact_pkt, &subpkt)) || !TEST_size_t_eq(PACKET_remaining(&exact_pkt), 0) || !TEST_size_t_eq(PACKET_remaining(&subpkt), len)) return 0; return 1; } #ifndef OPENSSL_NO_QUIC static int test_PACKET_get_quic_vlint(void) { struct quic_test_case { unsigned char buf[16]; size_t expected_read_count; uint64_t value; }; static const struct quic_test_case cases[] = { { {0x00}, 1, 0 }, { {0x01}, 1, 1 }, { {0x3e}, 1, 62 }, { {0x3f}, 1, 63 }, { {0x40,0x00}, 2, 0 }, { {0x40,0x01}, 2, 1 }, { {0x40,0x02}, 2, 2 }, { {0x40,0xff}, 2, 255 }, { {0x41,0x00}, 2, 256 }, { {0x7f,0xfe}, 2, 16382 }, { {0x7f,0xff}, 2, 16383 }, { {0x80,0x00,0x00,0x00}, 4, 0 }, { {0x80,0x00,0x00,0x01}, 4, 1 }, { {0x80,0x00,0x01,0x02}, 4, 258 }, { {0x80,0x18,0x49,0x65}, 4, 1591653 }, { {0xbe,0x18,0x49,0x65}, 4, 1041779045 }, { {0xbf,0xff,0xff,0xff}, 4, 1073741823 }, { {0xc0,0x00,0x00,0x00,0x00,0x00,0x00,0x00}, 8, 0 }, { {0xc0,0x00,0x00,0x00,0x00,0x00,0x01,0x02}, 8, 258 }, { {0xfd,0x1f,0x59,0x8d,0xc9,0xf8,0x71,0x8a}, 8, 4404337426105397642 }, }; PACKET pkt; size_t i; uint64_t v; for (i = 0; i < OSSL_NELEM(cases); ++i) { memset(&pkt, 0, sizeof(pkt)); v = 55; if (!TEST_true(PACKET_buf_init(&pkt, cases[i].buf, sizeof(cases[i].buf))) || !TEST_true(PACKET_get_quic_vlint(&pkt, &v)) || !TEST_uint64_t_eq(v, cases[i].value) || !TEST_size_t_eq(PACKET_remaining(&pkt), sizeof(cases[i].buf) - cases[i].expected_read_count) ) return 0; } return 1; } static int test_PACKET_get_quic_length_prefixed(void) { struct quic_test_case { unsigned char buf[16]; size_t enclen, len; int fail; }; static const struct quic_test_case cases[] = { /* success cases */ { {0x00}, 1, 0, 0 }, { {0x01}, 1, 1, 0 }, { {0x02}, 1, 2, 0 }, { {0x03}, 1, 3, 0 }, { {0x04}, 1, 4, 0 }, { {0x05}, 1, 5, 0 }, /* failure cases */ { {0x10}, 1, 0, 1 }, { {0x3f}, 1, 0, 1 }, }; size_t i; PACKET pkt, subpkt = {0}; for (i = 0; i < OSSL_NELEM(cases); ++i) { memset(&pkt, 0, sizeof(pkt)); if (!TEST_true(PACKET_buf_init(&pkt, cases[i].buf, cases[i].fail ? sizeof(cases[i].buf) : cases[i].enclen + cases[i].len))) return 0; if (!TEST_int_eq(PACKET_get_quic_length_prefixed(&pkt, &subpkt), !cases[i].fail)) return 0; if (cases[i].fail) { if (!TEST_ptr_eq(pkt.curr, cases[i].buf)) return 0; continue; } if (!TEST_ptr_eq(subpkt.curr, cases[i].buf + cases[i].enclen)) return 0; if (!TEST_size_t_eq(subpkt.remaining, cases[i].len)) return 0; } return 1; } #endif int setup_tests(void) { unsigned int i; for (i = 1; i <= BUF_LEN; i++) smbuf[i - 1] = (i * 2) & 0xff; ADD_TEST(test_PACKET_buf_init); ADD_TEST(test_PACKET_null_init); ADD_TEST(test_PACKET_remaining); ADD_TEST(test_PACKET_end); ADD_TEST(test_PACKET_equal); ADD_TEST(test_PACKET_get_1); ADD_TEST(test_PACKET_get_4); ADD_TEST(test_PACKET_get_net_2); ADD_TEST(test_PACKET_get_net_3); ADD_TEST(test_PACKET_get_net_4); ADD_TEST(test_PACKET_get_sub_packet); ADD_TEST(test_PACKET_get_bytes); ADD_TEST(test_PACKET_copy_bytes); ADD_TEST(test_PACKET_copy_all); ADD_TEST(test_PACKET_memdup); ADD_TEST(test_PACKET_strndup); ADD_TEST(test_PACKET_contains_zero_byte); ADD_TEST(test_PACKET_forward); ADD_TEST(test_PACKET_get_length_prefixed_1); ADD_TEST(test_PACKET_get_length_prefixed_2); ADD_TEST(test_PACKET_get_length_prefixed_3); ADD_TEST(test_PACKET_as_length_prefixed_1); ADD_TEST(test_PACKET_as_length_prefixed_2); #ifndef OPENSSL_NO_QUIC ADD_TEST(test_PACKET_get_quic_vlint); ADD_TEST(test_PACKET_get_quic_length_prefixed); #endif return 1; }
18,697
29.552288
89
c
openssl
openssl-master/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); }
5,011
27.804598
85
c
openssl
openssl-master/test/param_build_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 <openssl/param_build.h> #include "internal/nelem.h" #include "testutil.h" static const OSSL_PARAM params_empty[] = { OSSL_PARAM_END }; static int template_public_single_zero_test(void) { OSSL_PARAM_BLD *bld = NULL; OSSL_PARAM *params = NULL, *params_blt = NULL, *p; BIGNUM *zbn = NULL, *zbn_res = NULL; int res = 0; if (!TEST_ptr(bld = OSSL_PARAM_BLD_new()) || !TEST_ptr(zbn = BN_new()) || !TEST_true(OSSL_PARAM_BLD_push_BN(bld, "zeronumber", zbn)) || !TEST_ptr(params_blt = OSSL_PARAM_BLD_to_param(bld))) goto err; params = params_blt; /* Check BN (zero BN becomes unsigned integer) */ if (!TEST_ptr(p = OSSL_PARAM_locate(params, "zeronumber")) || !TEST_str_eq(p->key, "zeronumber") || !TEST_uint_eq(p->data_type, OSSL_PARAM_UNSIGNED_INTEGER) || !TEST_true(OSSL_PARAM_get_BN(p, &zbn_res)) || !TEST_BN_eq(zbn_res, zbn)) goto err; res = 1; err: if (params != params_blt) OPENSSL_free(params); OSSL_PARAM_free(params_blt); OSSL_PARAM_BLD_free(bld); BN_free(zbn); BN_free(zbn_res); return res; } static int template_private_single_zero_test(void) { OSSL_PARAM_BLD *bld = NULL; OSSL_PARAM *params = NULL, *params_blt = NULL, *p; BIGNUM *zbn = NULL, *zbn_res = NULL; int res = 0; if (!TEST_ptr(bld = OSSL_PARAM_BLD_new()) || !TEST_ptr(zbn = BN_secure_new()) || !TEST_true(OSSL_PARAM_BLD_push_BN(bld, "zeronumber", zbn)) || !TEST_ptr(params_blt = OSSL_PARAM_BLD_to_param(bld))) goto err; params = params_blt; /* Check BN (zero BN becomes unsigned integer) */ if (!TEST_ptr(p = OSSL_PARAM_locate(params, "zeronumber")) || !TEST_true(CRYPTO_secure_allocated(p->data)) || !TEST_str_eq(p->key, "zeronumber") || !TEST_uint_eq(p->data_type, OSSL_PARAM_UNSIGNED_INTEGER) || !TEST_true(OSSL_PARAM_get_BN(p, &zbn_res)) || !TEST_int_eq(BN_get_flags(zbn, BN_FLG_SECURE), BN_FLG_SECURE) || !TEST_BN_eq(zbn_res, zbn)) goto err; res = 1; err: if (params != params_blt) OPENSSL_free(params); OSSL_PARAM_free(params_blt); OSSL_PARAM_BLD_free(bld); BN_free(zbn); BN_free(zbn_res); return res; } static int template_public_test(int tstid) { OSSL_PARAM_BLD *bld = OSSL_PARAM_BLD_new(); OSSL_PARAM *params = NULL, *params_blt = NULL, *p1 = NULL, *p; BIGNUM *zbn = NULL, *zbn_res = NULL; BIGNUM *pbn = NULL, *pbn_res = NULL; BIGNUM *nbn = NULL, *nbn_res = NULL; int i; long int l; int32_t i32; int64_t i64; double d; time_t t; char *utf = NULL; const char *cutf; int res = 0; if (!TEST_ptr(bld) || !TEST_true(OSSL_PARAM_BLD_push_long(bld, "l", 42)) || !TEST_true(OSSL_PARAM_BLD_push_int32(bld, "i32", 1532)) || !TEST_true(OSSL_PARAM_BLD_push_int64(bld, "i64", -9999999)) || !TEST_true(OSSL_PARAM_BLD_push_time_t(bld, "t", 11224)) || !TEST_true(OSSL_PARAM_BLD_push_double(bld, "d", 1.61803398875)) || !TEST_ptr(zbn = BN_new()) || !TEST_true(OSSL_PARAM_BLD_push_BN(bld, "zeronumber", zbn)) || !TEST_ptr(pbn = BN_new()) || !TEST_true(BN_set_word(pbn, 1729)) || !TEST_true(OSSL_PARAM_BLD_push_BN(bld, "bignumber", pbn)) || !TEST_ptr(nbn = BN_secure_new()) || !TEST_true(BN_set_word(nbn, 1733)) || !TEST_true((BN_set_negative(nbn, 1), 1)) || !TEST_true(OSSL_PARAM_BLD_push_BN(bld, "negativebignumber", nbn)) || !TEST_true(OSSL_PARAM_BLD_push_utf8_string(bld, "utf8_s", "foo", sizeof("foo"))) || !TEST_true(OSSL_PARAM_BLD_push_utf8_ptr(bld, "utf8_p", "bar-boom", 0)) || !TEST_true(OSSL_PARAM_BLD_push_int(bld, "i", -6)) || !TEST_ptr(params_blt = OSSL_PARAM_BLD_to_param(bld))) goto err; switch (tstid) { case 0: params = params_blt; break; case 1: params = OSSL_PARAM_merge(params_blt, params_empty); break; case 2: params = OSSL_PARAM_dup(params_blt); break; case 3: p1 = OSSL_PARAM_merge(params_blt, params_empty); params = OSSL_PARAM_dup(p1); break; default: p1 = OSSL_PARAM_dup(params_blt); params = OSSL_PARAM_merge(p1, params_empty); break; } /* Check int */ if (!TEST_ptr(p = OSSL_PARAM_locate(params, "i")) || !TEST_true(OSSL_PARAM_get_int(p, &i)) || !TEST_str_eq(p->key, "i") || !TEST_uint_eq(p->data_type, OSSL_PARAM_INTEGER) || !TEST_size_t_eq(p->data_size, sizeof(int)) || !TEST_int_eq(i, -6) /* Check int32 */ || !TEST_ptr(p = OSSL_PARAM_locate(params, "i32")) || !TEST_true(OSSL_PARAM_get_int32(p, &i32)) || !TEST_str_eq(p->key, "i32") || !TEST_uint_eq(p->data_type, OSSL_PARAM_INTEGER) || !TEST_size_t_eq(p->data_size, sizeof(int32_t)) || !TEST_int_eq((int)i32, 1532) /* Check int64 */ || !TEST_ptr(p = OSSL_PARAM_locate(params, "i64")) || !TEST_str_eq(p->key, "i64") || !TEST_uint_eq(p->data_type, OSSL_PARAM_INTEGER) || !TEST_size_t_eq(p->data_size, sizeof(int64_t)) || !TEST_true(OSSL_PARAM_get_int64(p, &i64)) || !TEST_long_eq((long)i64, -9999999) /* Check long */ || !TEST_ptr(p = OSSL_PARAM_locate(params, "l")) || !TEST_str_eq(p->key, "l") || !TEST_uint_eq(p->data_type, OSSL_PARAM_INTEGER) || !TEST_size_t_eq(p->data_size, sizeof(long int)) || !TEST_true(OSSL_PARAM_get_long(p, &l)) || !TEST_long_eq(l, 42) /* Check time_t */ || !TEST_ptr(p = OSSL_PARAM_locate(params, "t")) || !TEST_str_eq(p->key, "t") || !TEST_uint_eq(p->data_type, OSSL_PARAM_INTEGER) || !TEST_size_t_eq(p->data_size, sizeof(time_t)) || !TEST_true(OSSL_PARAM_get_time_t(p, &t)) || !TEST_time_t_eq(t, 11224) /* Check double */ || !TEST_ptr(p = OSSL_PARAM_locate(params, "d")) || !TEST_true(OSSL_PARAM_get_double(p, &d)) || !TEST_str_eq(p->key, "d") || !TEST_uint_eq(p->data_type, OSSL_PARAM_REAL) || !TEST_size_t_eq(p->data_size, sizeof(double)) || !TEST_double_eq(d, 1.61803398875) /* Check UTF8 string */ || !TEST_ptr(p = OSSL_PARAM_locate(params, "utf8_s")) || !TEST_str_eq(p->data, "foo") || !TEST_true(OSSL_PARAM_get_utf8_string(p, &utf, 0)) || !TEST_str_eq(utf, "foo") /* Check UTF8 pointer */ || !TEST_ptr(p = OSSL_PARAM_locate(params, "utf8_p")) || !TEST_true(OSSL_PARAM_get_utf8_ptr(p, &cutf)) || !TEST_str_eq(cutf, "bar-boom") /* Check BN (zero BN becomes unsigned integer) */ || !TEST_ptr(p = OSSL_PARAM_locate(params, "zeronumber")) || !TEST_str_eq(p->key, "zeronumber") || !TEST_uint_eq(p->data_type, OSSL_PARAM_UNSIGNED_INTEGER) || !TEST_true(OSSL_PARAM_get_BN(p, &zbn_res)) || !TEST_BN_eq(zbn_res, zbn) /* Check BN (positive BN becomes unsigned integer) */ || !TEST_ptr(p = OSSL_PARAM_locate(params, "bignumber")) || !TEST_str_eq(p->key, "bignumber") || !TEST_uint_eq(p->data_type, OSSL_PARAM_UNSIGNED_INTEGER) || !TEST_true(OSSL_PARAM_get_BN(p, &pbn_res)) || !TEST_BN_eq(pbn_res, pbn) /* Check BN (negative BN becomes signed integer) */ || !TEST_ptr(p = OSSL_PARAM_locate(params, "negativebignumber")) || !TEST_str_eq(p->key, "negativebignumber") || !TEST_uint_eq(p->data_type, OSSL_PARAM_INTEGER) || !TEST_true(OSSL_PARAM_get_BN(p, &nbn_res)) || !TEST_BN_eq(nbn_res, nbn)) goto err; res = 1; err: OPENSSL_free(p1); if (params != params_blt) OPENSSL_free(params); OSSL_PARAM_free(params_blt); OSSL_PARAM_BLD_free(bld); OPENSSL_free(utf); BN_free(zbn); BN_free(zbn_res); BN_free(pbn); BN_free(pbn_res); BN_free(nbn); BN_free(nbn_res); return res; } static int template_private_test(int tstid) { int *data1 = NULL, *data2 = NULL, j; const int data1_num = 12; const int data1_size = data1_num * sizeof(int); const int data2_num = 5; const int data2_size = data2_num * sizeof(int); OSSL_PARAM_BLD *bld = NULL; OSSL_PARAM *params = NULL, *params_blt = NULL, *p1 = NULL, *p; unsigned int i; unsigned long int l; uint32_t i32; uint64_t i64; size_t st; BIGNUM *zbn = NULL, *zbn_res = NULL; BIGNUM *pbn = NULL, *pbn_res = NULL; BIGNUM *nbn = NULL, *nbn_res = NULL; int res = 0; if (!TEST_ptr(data1 = OPENSSL_secure_malloc(data1_size)) || !TEST_ptr(data2 = OPENSSL_secure_malloc(data2_size)) || !TEST_ptr(bld = OSSL_PARAM_BLD_new())) goto err; for (j = 0; j < data1_num; j++) data1[j] = -16 * j; for (j = 0; j < data2_num; j++) data2[j] = 2 * j; if (!TEST_true(OSSL_PARAM_BLD_push_uint(bld, "i", 6)) || !TEST_true(OSSL_PARAM_BLD_push_ulong(bld, "l", 42)) || !TEST_true(OSSL_PARAM_BLD_push_uint32(bld, "i32", 1532)) || !TEST_true(OSSL_PARAM_BLD_push_uint64(bld, "i64", 9999999)) || !TEST_true(OSSL_PARAM_BLD_push_size_t(bld, "st", 65537)) || !TEST_ptr(zbn = BN_secure_new()) || !TEST_true(OSSL_PARAM_BLD_push_BN(bld, "zeronumber", zbn)) || !TEST_ptr(pbn = BN_secure_new()) || !TEST_true(BN_set_word(pbn, 1729)) || !TEST_true(OSSL_PARAM_BLD_push_BN(bld, "bignumber", pbn)) || !TEST_ptr(nbn = BN_secure_new()) || !TEST_true(BN_set_word(nbn, 1733)) || !TEST_true((BN_set_negative(nbn, 1), 1)) || !TEST_true(OSSL_PARAM_BLD_push_BN(bld, "negativebignumber", nbn)) || !TEST_true(OSSL_PARAM_BLD_push_octet_string(bld, "oct_s", data1, data1_size)) || !TEST_true(OSSL_PARAM_BLD_push_octet_ptr(bld, "oct_p", data2, data2_size)) || !TEST_ptr(params_blt = OSSL_PARAM_BLD_to_param(bld))) goto err; switch (tstid) { case 0: params = params_blt; break; case 1: params = OSSL_PARAM_merge(params_blt, params_empty); break; case 2: params = OSSL_PARAM_dup(params_blt); break; case 3: p1 = OSSL_PARAM_merge(params_blt, params_empty); params = OSSL_PARAM_dup(p1); break; default: p1 = OSSL_PARAM_dup(params_blt); params = OSSL_PARAM_merge(p1, params_empty); break; } /* Check unsigned int */ if (!TEST_ptr(p = OSSL_PARAM_locate(params, "i")) || !TEST_false(CRYPTO_secure_allocated(p->data)) || !TEST_true(OSSL_PARAM_get_uint(p, &i)) || !TEST_str_eq(p->key, "i") || !TEST_uint_eq(p->data_type, OSSL_PARAM_UNSIGNED_INTEGER) || !TEST_size_t_eq(p->data_size, sizeof(int)) || !TEST_uint_eq(i, 6) /* Check unsigned int32 */ || !TEST_ptr(p = OSSL_PARAM_locate(params, "i32")) || !TEST_false(CRYPTO_secure_allocated(p->data)) || !TEST_true(OSSL_PARAM_get_uint32(p, &i32)) || !TEST_str_eq(p->key, "i32") || !TEST_uint_eq(p->data_type, OSSL_PARAM_UNSIGNED_INTEGER) || !TEST_size_t_eq(p->data_size, sizeof(int32_t)) || !TEST_uint_eq((unsigned int)i32, 1532) /* Check unsigned int64 */ || !TEST_ptr(p = OSSL_PARAM_locate(params, "i64")) || !TEST_false(CRYPTO_secure_allocated(p->data)) || !TEST_str_eq(p->key, "i64") || !TEST_uint_eq(p->data_type, OSSL_PARAM_UNSIGNED_INTEGER) || !TEST_size_t_eq(p->data_size, sizeof(int64_t)) || !TEST_true(OSSL_PARAM_get_uint64(p, &i64)) || !TEST_ulong_eq((unsigned long)i64, 9999999) /* Check unsigned long int */ || !TEST_ptr(p = OSSL_PARAM_locate(params, "l")) || !TEST_false(CRYPTO_secure_allocated(p->data)) || !TEST_str_eq(p->key, "l") || !TEST_uint_eq(p->data_type, OSSL_PARAM_UNSIGNED_INTEGER) || !TEST_size_t_eq(p->data_size, sizeof(unsigned long int)) || !TEST_true(OSSL_PARAM_get_ulong(p, &l)) || !TEST_ulong_eq(l, 42) /* Check size_t */ || !TEST_ptr(p = OSSL_PARAM_locate(params, "st")) || !TEST_false(CRYPTO_secure_allocated(p->data)) || !TEST_str_eq(p->key, "st") || !TEST_uint_eq(p->data_type, OSSL_PARAM_UNSIGNED_INTEGER) || !TEST_size_t_eq(p->data_size, sizeof(size_t)) || !TEST_true(OSSL_PARAM_get_size_t(p, &st)) || !TEST_size_t_eq(st, 65537) /* Check octet string */ || !TEST_ptr(p = OSSL_PARAM_locate(params, "oct_s")) || !TEST_true(CRYPTO_secure_allocated(p->data)) || !TEST_str_eq(p->key, "oct_s") || !TEST_uint_eq(p->data_type, OSSL_PARAM_OCTET_STRING) || !TEST_mem_eq(p->data, p->data_size, data1, data1_size) /* Check octet pointer */ || !TEST_ptr(p = OSSL_PARAM_locate(params, "oct_p")) || !TEST_false(CRYPTO_secure_allocated(p->data)) || !TEST_true(CRYPTO_secure_allocated(*(void **)p->data)) || !TEST_str_eq(p->key, "oct_p") || !TEST_uint_eq(p->data_type, OSSL_PARAM_OCTET_PTR) || !TEST_mem_eq(*(void **)p->data, p->data_size, data2, data2_size) /* Check BN (zero BN becomes unsigned integer) */ || !TEST_ptr(p = OSSL_PARAM_locate(params, "zeronumber")) || !TEST_true(CRYPTO_secure_allocated(p->data)) || !TEST_str_eq(p->key, "zeronumber") || !TEST_uint_eq(p->data_type, OSSL_PARAM_UNSIGNED_INTEGER) || !TEST_true(OSSL_PARAM_get_BN(p, &zbn_res)) || !TEST_int_eq(BN_get_flags(pbn, BN_FLG_SECURE), BN_FLG_SECURE) || !TEST_BN_eq(zbn_res, zbn) /* Check BN (positive BN becomes unsigned integer) */ || !TEST_ptr(p = OSSL_PARAM_locate(params, "bignumber")) || !TEST_true(CRYPTO_secure_allocated(p->data)) || !TEST_str_eq(p->key, "bignumber") || !TEST_uint_eq(p->data_type, OSSL_PARAM_UNSIGNED_INTEGER) || !TEST_true(OSSL_PARAM_get_BN(p, &pbn_res)) || !TEST_int_eq(BN_get_flags(pbn, BN_FLG_SECURE), BN_FLG_SECURE) || !TEST_BN_eq(pbn_res, pbn) /* Check BN (negative BN becomes signed integer) */ || !TEST_ptr(p = OSSL_PARAM_locate(params, "negativebignumber")) || !TEST_true(CRYPTO_secure_allocated(p->data)) || !TEST_str_eq(p->key, "negativebignumber") || !TEST_uint_eq(p->data_type, OSSL_PARAM_INTEGER) || !TEST_true(OSSL_PARAM_get_BN(p, &nbn_res)) || !TEST_int_eq(BN_get_flags(nbn, BN_FLG_SECURE), BN_FLG_SECURE) || !TEST_BN_eq(nbn_res, nbn)) goto err; res = 1; err: OSSL_PARAM_free(p1); if (params != params_blt) OSSL_PARAM_free(params); OSSL_PARAM_free(params_blt); OSSL_PARAM_BLD_free(bld); OPENSSL_secure_free(data1); OPENSSL_secure_free(data2); BN_free(zbn); BN_free(zbn_res); BN_free(pbn); BN_free(pbn_res); BN_free(nbn); BN_free(nbn_res); return res; } static int builder_limit_test(void) { const int n = 100; char names[100][3]; OSSL_PARAM_BLD *bld = OSSL_PARAM_BLD_new(); OSSL_PARAM *params = NULL; int i, res = 0; if (!TEST_ptr(bld)) goto err; for (i = 0; i < n; i++) { names[i][0] = 'A' + (i / 26) - 1; names[i][1] = 'a' + (i % 26) - 1; names[i][2] = '\0'; if (!TEST_true(OSSL_PARAM_BLD_push_int(bld, names[i], 3 * i + 1))) goto err; } if (!TEST_ptr(params = OSSL_PARAM_BLD_to_param(bld))) goto err; /* Count the elements in the params array, expecting n */ for (i = 0; params[i].key != NULL; i++); if (!TEST_int_eq(i, n)) goto err; /* Verify that the build, cleared the builder structure */ OSSL_PARAM_free(params); params = NULL; if (!TEST_true(OSSL_PARAM_BLD_push_int(bld, "g", 2)) || !TEST_ptr(params = OSSL_PARAM_BLD_to_param(bld))) goto err; /* Count the elements in the params array, expecting 1 */ for (i = 0; params[i].key != NULL; i++); if (!TEST_int_eq(i, 1)) goto err; res = 1; err: OSSL_PARAM_free(params); OSSL_PARAM_BLD_free(bld); return res; } static int builder_merge_test(void) { static int data1[] = { 2, 3, 5, 7, 11, 15, 17 }; static unsigned char data2[] = { 2, 4, 6, 8, 10 }; OSSL_PARAM_BLD *bld = OSSL_PARAM_BLD_new(); OSSL_PARAM_BLD *bld2 = OSSL_PARAM_BLD_new(); OSSL_PARAM *params = NULL, *params_blt = NULL, *params2_blt = NULL, *p; unsigned int i; unsigned long int l; uint32_t i32; uint64_t i64; size_t st; BIGNUM *bn_priv = NULL, *bn_priv_res = NULL; BIGNUM *bn_pub = NULL, *bn_pub_res = NULL; int res = 0; if (!TEST_ptr(bld) || !TEST_true(OSSL_PARAM_BLD_push_uint(bld, "i", 6)) || !TEST_true(OSSL_PARAM_BLD_push_ulong(bld, "l", 42)) || !TEST_true(OSSL_PARAM_BLD_push_uint32(bld, "i32", 1532)) || !TEST_true(OSSL_PARAM_BLD_push_uint64(bld, "i64", 9999999)) || !TEST_true(OSSL_PARAM_BLD_push_size_t(bld, "st", 65537)) || !TEST_ptr(bn_priv = BN_secure_new()) || !TEST_true(BN_set_word(bn_priv, 1729)) || !TEST_true(OSSL_PARAM_BLD_push_BN(bld, "bignumber_priv", bn_priv)) || !TEST_ptr(params_blt = OSSL_PARAM_BLD_to_param(bld))) goto err; if (!TEST_ptr(bld2) || !TEST_true(OSSL_PARAM_BLD_push_octet_string(bld2, "oct_s", data1, sizeof(data1))) || !TEST_true(OSSL_PARAM_BLD_push_octet_ptr(bld2, "oct_p", data2, sizeof(data2))) || !TEST_true(OSSL_PARAM_BLD_push_uint32(bld2, "i32", 99)) || !TEST_ptr(bn_pub = BN_new()) || !TEST_true(BN_set_word(bn_pub, 0x42)) || !TEST_true(OSSL_PARAM_BLD_push_BN(bld2, "bignumber_pub", bn_pub)) || !TEST_ptr(params2_blt = OSSL_PARAM_BLD_to_param(bld2))) goto err; if (!TEST_ptr(params = OSSL_PARAM_merge(params_blt, params2_blt))) goto err; if (!TEST_ptr(p = OSSL_PARAM_locate(params, "i")) || !TEST_true(OSSL_PARAM_get_uint(p, &i)) || !TEST_str_eq(p->key, "i") || !TEST_uint_eq(p->data_type, OSSL_PARAM_UNSIGNED_INTEGER) || !TEST_size_t_eq(p->data_size, sizeof(int)) || !TEST_uint_eq(i, 6) /* Check unsigned int32 */ || !TEST_ptr(p = OSSL_PARAM_locate(params, "i32")) || !TEST_true(OSSL_PARAM_get_uint32(p, &i32)) || !TEST_str_eq(p->key, "i32") || !TEST_uint_eq(p->data_type, OSSL_PARAM_UNSIGNED_INTEGER) || !TEST_size_t_eq(p->data_size, sizeof(int32_t)) || !TEST_uint_eq((unsigned int)i32, 99) /* Check unsigned int64 */ || !TEST_ptr(p = OSSL_PARAM_locate(params, "i64")) || !TEST_str_eq(p->key, "i64") || !TEST_uint_eq(p->data_type, OSSL_PARAM_UNSIGNED_INTEGER) || !TEST_size_t_eq(p->data_size, sizeof(int64_t)) || !TEST_true(OSSL_PARAM_get_uint64(p, &i64)) || !TEST_ulong_eq((unsigned long)i64, 9999999) /* Check unsigned long int */ || !TEST_ptr(p = OSSL_PARAM_locate(params, "l")) || !TEST_str_eq(p->key, "l") || !TEST_uint_eq(p->data_type, OSSL_PARAM_UNSIGNED_INTEGER) || !TEST_size_t_eq(p->data_size, sizeof(unsigned long int)) || !TEST_true(OSSL_PARAM_get_ulong(p, &l)) || !TEST_ulong_eq(l, 42) /* Check size_t */ || !TEST_ptr(p = OSSL_PARAM_locate(params, "st")) || !TEST_str_eq(p->key, "st") || !TEST_uint_eq(p->data_type, OSSL_PARAM_UNSIGNED_INTEGER) || !TEST_size_t_eq(p->data_size, sizeof(size_t)) || !TEST_true(OSSL_PARAM_get_size_t(p, &st)) || !TEST_size_t_eq(st, 65537) /* Check octet string */ || !TEST_ptr(p = OSSL_PARAM_locate(params, "oct_s")) || !TEST_str_eq(p->key, "oct_s") || !TEST_uint_eq(p->data_type, OSSL_PARAM_OCTET_STRING) || !TEST_mem_eq(p->data, p->data_size, data1, sizeof(data1)) /* Check octet pointer */ || !TEST_ptr(p = OSSL_PARAM_locate(params, "oct_p")) || !TEST_str_eq(p->key, "oct_p") || !TEST_uint_eq(p->data_type, OSSL_PARAM_OCTET_PTR) || !TEST_mem_eq(*(void **)p->data, p->data_size, data2, sizeof(data2)) /* Check BN */ || !TEST_ptr(p = OSSL_PARAM_locate(params, "bignumber_pub")) || !TEST_str_eq(p->key, "bignumber_pub") || !TEST_uint_eq(p->data_type, OSSL_PARAM_UNSIGNED_INTEGER) || !TEST_true(OSSL_PARAM_get_BN(p, &bn_pub_res)) || !TEST_int_eq(BN_cmp(bn_pub_res, bn_pub), 0) || !TEST_ptr(p = OSSL_PARAM_locate(params, "bignumber_priv")) || !TEST_str_eq(p->key, "bignumber_priv") || !TEST_uint_eq(p->data_type, OSSL_PARAM_UNSIGNED_INTEGER) || !TEST_true(OSSL_PARAM_get_BN(p, &bn_priv_res)) || !TEST_int_eq(BN_cmp(bn_priv_res, bn_priv), 0)) goto err; res = 1; err: OSSL_PARAM_free(params); OSSL_PARAM_free(params_blt); OSSL_PARAM_free(params2_blt); OSSL_PARAM_BLD_free(bld); OSSL_PARAM_BLD_free(bld2); BN_free(bn_priv); BN_free(bn_priv_res); BN_free(bn_pub); BN_free(bn_pub_res); return res; } int setup_tests(void) { ADD_TEST(template_public_single_zero_test); ADD_ALL_TESTS(template_public_test, 5); /* Only run the secure memory testing if we have secure memory available */ if (CRYPTO_secure_malloc_init(1<<16, 16)) { ADD_TEST(template_private_single_zero_test); ADD_ALL_TESTS(template_private_test, 5); } ADD_TEST(builder_limit_test); ADD_TEST(builder_merge_test); return 1; }
22,450
38.806738
79
c
openssl
openssl-master/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; }
12,489
32.395722
80
c
openssl
openssl-master/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; }
23,362
33.922272
89
c
openssl
openssl-master/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; }
1,409
26.647059
77
c
openssl
openssl-master/test/pbetest.c
/* * Copyright 2021-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 "testutil.h" #include <openssl/evp.h> #include <openssl/x509.h> #include <openssl/rc4.h> #include <openssl/md5.h> #if !defined OPENSSL_NO_RC4 && !defined OPENSSL_NO_MD5 \ || !defined OPENSSL_NO_DES && !defined OPENSSL_NO_SHA1 static const char pbe_password[] = "MyVoiceIsMyPassport"; static unsigned char pbe_salt[] = { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, }; static const int pbe_iter = 1000; static unsigned char pbe_plaintext[] = { 0x57, 0x65, 0x20, 0x61, 0x72, 0x65, 0x20, 0x61, 0x6c, 0x6c, 0x20, 0x6d, 0x61, 0x64, 0x65, 0x20, 0x6f, 0x66, 0x20, 0x73, 0x74, 0x61, 0x72, 0x73, }; #endif /* Expected output generated using OpenSSL 1.1.1 */ #if !defined OPENSSL_NO_RC4 && !defined OPENSSL_NO_MD5 static const unsigned char pbe_ciphertext_rc4_md5[] = { 0x21, 0x90, 0xfa, 0xee, 0x95, 0x66, 0x59, 0x45, 0xfa, 0x1e, 0x9f, 0xe2, 0x25, 0xd2, 0xf9, 0x71, 0x94, 0xe4, 0x3d, 0xc9, 0x7c, 0xb0, 0x07, 0x23, }; #endif #if !defined OPENSSL_NO_DES && !defined OPENSSL_NO_SHA1 static const unsigned char pbe_ciphertext_des_sha1[] = { 0xce, 0x4b, 0xb0, 0x0a, 0x7b, 0x48, 0xd7, 0xe3, 0x9a, 0x9f, 0x46, 0xd6, 0x41, 0x42, 0x4b, 0x44, 0x36, 0x45, 0x5f, 0x60, 0x8f, 0x3c, 0xd0, 0x55, 0xd0, 0x8d, 0xa9, 0xab, 0x78, 0x5b, 0x63, 0xaf, }; #endif #if !defined OPENSSL_NO_RC4 && !defined OPENSSL_NO_MD5 \ || !defined OPENSSL_NO_DES && !defined OPENSSL_NO_SHA1 static int test_pkcs5_pbe(const EVP_CIPHER *cipher, const EVP_MD *md, const unsigned char *exp, const int exp_len) { int ret = 0; EVP_CIPHER_CTX *ctx; X509_ALGOR *algor = NULL; int i, outlen; unsigned char out[32]; ctx = EVP_CIPHER_CTX_new(); if (!TEST_ptr(ctx)) goto err; algor = X509_ALGOR_new(); if (!TEST_ptr(algor)) goto err; if (!TEST_true(PKCS5_pbe_set0_algor(algor, EVP_CIPHER_nid(cipher), pbe_iter, pbe_salt, sizeof(pbe_salt))) || !TEST_true(PKCS5_PBE_keyivgen(ctx, pbe_password, strlen(pbe_password), algor->parameter, cipher, md, 1)) || !TEST_true(EVP_CipherUpdate(ctx, out, &i, pbe_plaintext, sizeof(pbe_plaintext)))) goto err; outlen = i; if (!TEST_true(EVP_CipherFinal_ex(ctx, out + i, &i))) goto err; outlen += i; if (!TEST_mem_eq(out, outlen, exp, exp_len)) goto err; /* Decrypt */ if (!TEST_true(PKCS5_PBE_keyivgen(ctx, pbe_password, strlen(pbe_password), algor->parameter, cipher, md, 0)) || !TEST_true(EVP_CipherUpdate(ctx, out, &i, exp, exp_len))) goto err; outlen = i; if (!TEST_true(EVP_CipherFinal_ex(ctx, out + i, &i))) goto err; if (!TEST_mem_eq(out, outlen, pbe_plaintext, sizeof(pbe_plaintext))) goto err; ret = 1; err: EVP_CIPHER_CTX_free(ctx); X509_ALGOR_free(algor); return ret; } #endif #if !defined OPENSSL_NO_RC4 && !defined OPENSSL_NO_MD5 static int test_pkcs5_pbe_rc4_md5(void) { return test_pkcs5_pbe(EVP_rc4(), EVP_md5(), pbe_ciphertext_rc4_md5, sizeof(pbe_ciphertext_rc4_md5)); } #endif #if !defined OPENSSL_NO_DES && !defined OPENSSL_NO_SHA1 static int test_pkcs5_pbe_des_sha1(void) { return test_pkcs5_pbe(EVP_des_cbc(), EVP_sha1(), pbe_ciphertext_des_sha1, sizeof(pbe_ciphertext_des_sha1)); } #endif int setup_tests(void) { #if !defined OPENSSL_NO_RC4 && !defined OPENSSL_NO_MD5 ADD_TEST(test_pkcs5_pbe_rc4_md5); #endif #if !defined OPENSSL_NO_DES && !defined OPENSSL_NO_SHA1 ADD_TEST(test_pkcs5_pbe_des_sha1); #endif return 1; }
4,046
28.540146
111
c
openssl
openssl-master/test/pkcs12_api_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 <stdlib.h> #include "internal/nelem.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 OSSL_LIB_CTX *testctx = NULL; static OSSL_PROVIDER *nullprov = NULL; static int test_null_args(void) { return TEST_false(PKCS12_parse(NULL, NULL, NULL, NULL, NULL)); } static PKCS12 *PKCS12_load(const char *fpath) { BIO *bio = NULL; PKCS12 *p12 = NULL; bio = BIO_new_file(fpath, "rb"); if (!TEST_ptr(bio)) goto err; p12 = PKCS12_init_ex(NID_pkcs7_data, testctx, "provider=default"); if (!TEST_ptr(p12)) goto err; if (!TEST_true(p12 == d2i_PKCS12_bio(bio, &p12))) goto err; BIO_free(bio); return p12; err: BIO_free(bio); PKCS12_free(p12); return NULL; } static const char *in_file = NULL; static const char *in_pass = ""; static int has_key = 0; static int has_cert = 0; static int has_ca = 0; static int changepass(PKCS12 *p12, EVP_PKEY *key, X509 *cert, STACK_OF(X509) *ca) { int ret = 0; PKCS12 *p12new = NULL; EVP_PKEY *key2 = NULL; X509 *cert2 = NULL; STACK_OF(X509) *ca2 = NULL; BIO *bio = NULL; if (!TEST_true(PKCS12_newpass(p12, in_pass, "NEWPASS"))) goto err; if (!TEST_ptr(bio = BIO_new(BIO_s_mem()))) goto err; if (!TEST_true(i2d_PKCS12_bio(bio, p12))) goto err; if (!TEST_ptr(p12new = PKCS12_init_ex(NID_pkcs7_data, testctx, "provider=default"))) goto err; if (!TEST_ptr(d2i_PKCS12_bio(bio, &p12new))) goto err; if (!TEST_true(PKCS12_parse(p12new, "NEWPASS", &key2, &cert2, &ca2))) goto err; if (has_key) { if (!TEST_ptr(key2) || !TEST_int_eq(EVP_PKEY_eq(key, key2), 1)) goto err; } if (has_cert) { if (!TEST_ptr(cert2) || !TEST_int_eq(X509_cmp(cert, cert2), 0)) goto err; } ret = 1; err: BIO_free(bio); PKCS12_free(p12new); EVP_PKEY_free(key2); X509_free(cert2); OSSL_STACK_OF_X509_free(ca2); return ret; } static int pkcs12_parse_test(void) { int ret = 0; PKCS12 *p12 = NULL; EVP_PKEY *key = NULL; X509 *cert = NULL; STACK_OF(X509) *ca = NULL; if (in_file != NULL) { p12 = PKCS12_load(in_file); if (!TEST_ptr(p12)) goto err; if (!TEST_true(PKCS12_parse(p12, in_pass, &key, &cert, &ca))) goto err; if ((has_key && !TEST_ptr(key)) || (!has_key && !TEST_ptr_null(key))) goto err; if ((has_cert && !TEST_ptr(cert)) || (!has_cert && !TEST_ptr_null(cert))) goto err; if ((has_ca && !TEST_ptr(ca)) || (!has_ca && !TEST_ptr_null(ca))) goto err; if (has_key && !changepass(p12, key, cert, ca)) goto err; } ret = 1; err: PKCS12_free(p12); EVP_PKEY_free(key); X509_free(cert); OSSL_STACK_OF_X509_free(ca); return TEST_true(ret); } static int pkcs12_create_cb(PKCS12_SAFEBAG *bag, void *cbarg) { int cb_ret = *((int*)cbarg); return cb_ret; } static PKCS12 *pkcs12_create_ex2_setup(EVP_PKEY **key, X509 **cert, STACK_OF(X509) **ca) { PKCS12 *p12 = NULL; p12 = PKCS12_load("out6.p12"); if (!TEST_ptr(p12)) goto err; if (!TEST_true(PKCS12_parse(p12, "", key, cert, ca))) goto err; return p12; err: PKCS12_free(p12); return NULL; } static int pkcs12_create_ex2_test(int test) { int ret = 0, cb_ret = 0; PKCS12 *ptr = NULL, *p12 = NULL; EVP_PKEY *key = NULL; X509 *cert = NULL; STACK_OF(X509) *ca = NULL; p12 = pkcs12_create_ex2_setup(&key, &cert, &ca); if (!TEST_ptr(p12)) goto err; if (test == 0) { /* Confirm PKCS12_create_ex2 returns NULL */ ptr = PKCS12_create_ex2(NULL, NULL, NULL, NULL, NULL, NID_undef, NID_undef, 0, 0, 0, testctx, NULL, NULL, NULL); if (TEST_ptr(ptr)) goto err; /* Can't proceed without a valid cert at least */ if (!TEST_ptr(cert)) goto err; /* Specified call back called - return success */ cb_ret = 1; ptr = PKCS12_create_ex2(NULL, NULL, NULL, cert, NULL, NID_undef, NID_undef, 0, 0, 0, testctx, NULL, pkcs12_create_cb, (void*)&cb_ret); /* PKCS12 successfully created */ if (!TEST_ptr(ptr)) goto err; } else if (test == 1) { /* Specified call back called - return error*/ cb_ret = -1; ptr = PKCS12_create_ex2(NULL, NULL, NULL, cert, NULL, NID_undef, NID_undef, 0, 0, 0, testctx, NULL, pkcs12_create_cb, (void*)&cb_ret); /* PKCS12 not created */ if (TEST_ptr(ptr)) goto err; } else if (test == 2) { /* Specified call back called - return failure */ cb_ret = 0; ptr = PKCS12_create_ex2(NULL, NULL, NULL, cert, NULL, NID_undef, NID_undef, 0, 0, 0, testctx, NULL, pkcs12_create_cb, (void*)&cb_ret); /* PKCS12 successfully created */ if (!TEST_ptr(ptr)) goto err; } ret = 1; err: PKCS12_free(p12); PKCS12_free(ptr); EVP_PKEY_free(key); X509_free(cert); OSSL_STACK_OF_X509_free(ca); return TEST_true(ret); } typedef enum OPTION_choice { OPT_ERR = -1, OPT_EOF = 0, OPT_IN_FILE, OPT_IN_PASS, OPT_IN_HAS_KEY, OPT_IN_HAS_CERT, OPT_IN_HAS_CA, OPT_LEGACY, OPT_TEST_ENUM } OPTION_CHOICE; const OPTIONS *test_get_options(void) { static const OPTIONS options[] = { OPT_TEST_OPTIONS_DEFAULT_USAGE, { "in", OPT_IN_FILE, '<', "PKCS12 input file" }, { "pass", OPT_IN_PASS, 's', "PKCS12 input file password" }, { "has-key", OPT_IN_HAS_KEY, 'n', "Whether the input file does contain an user key" }, { "has-cert", OPT_IN_HAS_CERT, 'n', "Whether the input file does contain an user certificate" }, { "has-ca", OPT_IN_HAS_CA, 'n', "Whether the input file does contain other certificate" }, { "legacy", OPT_LEGACY, '-', "Test the legacy APIs" }, { NULL } }; return options; } int setup_tests(void) { OPTION_CHOICE o; while ((o = opt_next()) != OPT_EOF) { switch (o) { case OPT_IN_FILE: in_file = opt_arg(); break; case OPT_IN_PASS: in_pass = opt_arg(); break; case OPT_LEGACY: break; case OPT_IN_HAS_KEY: has_key = opt_int_arg(); break; case OPT_IN_HAS_CERT: has_cert = opt_int_arg(); break; case OPT_IN_HAS_CA: has_ca = opt_int_arg(); break; case OPT_TEST_CASES: break; default: return 0; } } if (!test_get_libctx(&testctx, &nullprov, NULL, NULL, NULL)) { OSSL_LIB_CTX_free(testctx); testctx = NULL; return 0; } ADD_TEST(test_null_args); ADD_TEST(pkcs12_parse_test); ADD_ALL_TESTS(pkcs12_create_ex2_test, 3); return 1; } void cleanup_tests(void) { OSSL_LIB_CTX_free(testctx); OSSL_PROVIDER_unload(nullprov); }
8,064
25.617162
106
c
openssl
openssl-master/test/pkey_meth_kdf_test.c
/* * Copyright 2017-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 */ /* Tests of the EVP_PKEY_CTX_set_* macro family */ #include <stdio.h> #include <string.h> #include <openssl/evp.h> #include <openssl/kdf.h> #include "testutil.h" static int test_kdf_tls1_prf(void) { int ret = 0; EVP_PKEY_CTX *pctx; unsigned char out[16]; size_t outlen = sizeof(out); if ((pctx = EVP_PKEY_CTX_new_id(EVP_PKEY_TLS1_PRF, NULL)) == NULL) { TEST_error("EVP_PKEY_TLS1_PRF"); goto err; } if (EVP_PKEY_derive_init(pctx) <= 0) { TEST_error("EVP_PKEY_derive_init"); goto err; } if (EVP_PKEY_CTX_set_tls1_prf_md(pctx, EVP_sha256()) <= 0) { TEST_error("EVP_PKEY_CTX_set_tls1_prf_md"); goto err; } if (EVP_PKEY_CTX_set1_tls1_prf_secret(pctx, (unsigned char *)"secret", 6) <= 0) { TEST_error("EVP_PKEY_CTX_set1_tls1_prf_secret"); goto err; } if (EVP_PKEY_CTX_add1_tls1_prf_seed(pctx, (unsigned char *)"seed", 4) <= 0) { TEST_error("EVP_PKEY_CTX_add1_tls1_prf_seed"); goto err; } if (EVP_PKEY_derive(pctx, out, &outlen) <= 0) { TEST_error("EVP_PKEY_derive"); goto err; } { const unsigned char expected[sizeof(out)] = { 0x8e, 0x4d, 0x93, 0x25, 0x30, 0xd7, 0x65, 0xa0, 0xaa, 0xe9, 0x74, 0xc3, 0x04, 0x73, 0x5e, 0xcc }; if (!TEST_mem_eq(out, sizeof(out), expected, sizeof(expected))) { goto err; } } ret = 1; err: EVP_PKEY_CTX_free(pctx); return ret; } static int test_kdf_hkdf(void) { int ret = 0; EVP_PKEY_CTX *pctx; unsigned char out[10]; size_t outlen = sizeof(out); if ((pctx = EVP_PKEY_CTX_new_id(EVP_PKEY_HKDF, NULL)) == NULL) { TEST_error("EVP_PKEY_HKDF"); goto err; } if (EVP_PKEY_derive_init(pctx) <= 0) { TEST_error("EVP_PKEY_derive_init"); goto err; } if (EVP_PKEY_CTX_set_hkdf_md(pctx, EVP_sha256()) <= 0) { TEST_error("EVP_PKEY_CTX_set_hkdf_md"); goto err; } if (EVP_PKEY_CTX_set1_hkdf_salt(pctx, (const unsigned char *)"salt", 4) <= 0) { TEST_error("EVP_PKEY_CTX_set1_hkdf_salt"); goto err; } if (EVP_PKEY_CTX_set1_hkdf_key(pctx, (const unsigned char *)"secret", 6) <= 0) { TEST_error("EVP_PKEY_CTX_set1_hkdf_key"); goto err; } if (EVP_PKEY_CTX_add1_hkdf_info(pctx, (const unsigned char *)"label", 5) <= 0) { TEST_error("EVP_PKEY_CTX_set1_hkdf_info"); goto err; } if (EVP_PKEY_derive(pctx, out, &outlen) <= 0) { TEST_error("EVP_PKEY_derive"); goto err; } { const unsigned char expected[sizeof(out)] = { 0x2a, 0xc4, 0x36, 0x9f, 0x52, 0x59, 0x96, 0xf8, 0xde, 0x13 }; if (!TEST_mem_eq(out, sizeof(out), expected, sizeof(expected))) { goto err; } } ret = 1; err: EVP_PKEY_CTX_free(pctx); return ret; } #ifndef OPENSSL_NO_SCRYPT static int test_kdf_scrypt(void) { int ret = 0; EVP_PKEY_CTX *pctx; unsigned char out[64]; size_t outlen = sizeof(out); if ((pctx = EVP_PKEY_CTX_new_id(EVP_PKEY_SCRYPT, NULL)) == NULL) { TEST_error("EVP_PKEY_SCRYPT"); goto err; } if (EVP_PKEY_derive_init(pctx) <= 0) { TEST_error("EVP_PKEY_derive_init"); goto err; } if (EVP_PKEY_CTX_set1_pbe_pass(pctx, "password", 8) <= 0) { TEST_error("EVP_PKEY_CTX_set1_pbe_pass"); goto err; } if (EVP_PKEY_CTX_set1_scrypt_salt(pctx, (unsigned char *)"NaCl", 4) <= 0) { TEST_error("EVP_PKEY_CTX_set1_scrypt_salt"); goto err; } if (EVP_PKEY_CTX_set_scrypt_N(pctx, 1024) <= 0) { TEST_error("EVP_PKEY_CTX_set_scrypt_N"); goto err; } if (EVP_PKEY_CTX_set_scrypt_r(pctx, 8) <= 0) { TEST_error("EVP_PKEY_CTX_set_scrypt_r"); goto err; } if (EVP_PKEY_CTX_set_scrypt_p(pctx, 16) <= 0) { TEST_error("EVP_PKEY_CTX_set_scrypt_p"); goto err; } if (EVP_PKEY_CTX_set_scrypt_maxmem_bytes(pctx, 16) <= 0) { TEST_error("EVP_PKEY_CTX_set_maxmem_bytes"); goto err; } if (EVP_PKEY_derive(pctx, out, &outlen) > 0) { TEST_error("EVP_PKEY_derive should have failed"); goto err; } if (EVP_PKEY_CTX_set_scrypt_maxmem_bytes(pctx, 10 * 1024 * 1024) <= 0) { TEST_error("EVP_PKEY_CTX_set_maxmem_bytes"); goto err; } if (EVP_PKEY_derive(pctx, out, &outlen) <= 0) { TEST_error("EVP_PKEY_derive"); goto err; } { const unsigned char expected[sizeof(out)] = { 0xfd, 0xba, 0xbe, 0x1c, 0x9d, 0x34, 0x72, 0x00, 0x78, 0x56, 0xe7, 0x19, 0x0d, 0x01, 0xe9, 0xfe, 0x7c, 0x6a, 0xd7, 0xcb, 0xc8, 0x23, 0x78, 0x30, 0xe7, 0x73, 0x76, 0x63, 0x4b, 0x37, 0x31, 0x62, 0x2e, 0xaf, 0x30, 0xd9, 0x2e, 0x22, 0xa3, 0x88, 0x6f, 0xf1, 0x09, 0x27, 0x9d, 0x98, 0x30, 0xda, 0xc7, 0x27, 0xaf, 0xb9, 0x4a, 0x83, 0xee, 0x6d, 0x83, 0x60, 0xcb, 0xdf, 0xa2, 0xcc, 0x06, 0x40 }; if (!TEST_mem_eq(out, sizeof(out), expected, sizeof(expected))) { goto err; } } ret = 1; err: EVP_PKEY_CTX_free(pctx); return ret; } #endif int setup_tests(void) { ADD_TEST(test_kdf_tls1_prf); ADD_TEST(test_kdf_hkdf); #ifndef OPENSSL_NO_SCRYPT ADD_TEST(test_kdf_scrypt); #endif return 1; }
5,907
27.819512
79
c
openssl
openssl-master/test/pkey_meth_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 EVP_PKEY method ordering */ /* We need to use some deprecated APIs */ #define OPENSSL_SUPPRESS_DEPRECATED #include <stdio.h> #include <string.h> #include <openssl/evp.h> #include "testutil.h" /* Test of EVP_PKEY_ASN1_METHOD ordering */ static int test_asn1_meths(void) { int i; int prev = -1; int good = 1; int pkey_id; const EVP_PKEY_ASN1_METHOD *ameth; for (i = 0; i < EVP_PKEY_asn1_get_count(); i++) { ameth = EVP_PKEY_asn1_get0(i); EVP_PKEY_asn1_get0_info(&pkey_id, NULL, NULL, NULL, NULL, ameth); if (pkey_id < prev) good = 0; prev = pkey_id; } if (!good) { TEST_error("EVP_PKEY_ASN1_METHOD table out of order"); for (i = 0; i < EVP_PKEY_asn1_get_count(); i++) { const char *info; ameth = EVP_PKEY_asn1_get0(i); EVP_PKEY_asn1_get0_info(&pkey_id, NULL, NULL, &info, NULL, ameth); if (info == NULL) info = "<NO NAME>"; TEST_note("%d : %s : %s", pkey_id, OBJ_nid2ln(pkey_id), info); } } return good; } #ifndef OPENSSL_NO_DEPRECATED_3_0 /* Test of EVP_PKEY_METHOD ordering */ static int test_pkey_meths(void) { size_t i; int prev = -1; int good = 1; int pkey_id; const EVP_PKEY_METHOD *pmeth; for (i = 0; i < EVP_PKEY_meth_get_count(); i++) { pmeth = EVP_PKEY_meth_get0(i); EVP_PKEY_meth_get0_info(&pkey_id, NULL, pmeth); if (pkey_id < prev) good = 0; prev = pkey_id; } if (!good) { TEST_error("EVP_PKEY_METHOD table out of order"); for (i = 0; i < EVP_PKEY_meth_get_count(); i++) { pmeth = EVP_PKEY_meth_get0(i); EVP_PKEY_meth_get0_info(&pkey_id, NULL, pmeth); TEST_note("%d : %s", pkey_id, OBJ_nid2ln(pkey_id)); } } return good; } #endif int setup_tests(void) { ADD_TEST(test_asn1_meths); #ifndef OPENSSL_NO_DEPRECATED_3_0 ADD_TEST(test_pkey_meths); #endif return 1; }
2,382
25.186813
78
c
openssl
openssl-master/test/priority_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 <stdio.h> #include <string.h> #include <openssl/opensslconf.h> #include <internal/priority_queue.h> #include <openssl/err.h> #include <openssl/crypto.h> #include "internal/nelem.h" #include "testutil.h" #define MAX_SAMPLES 500000 DEFINE_PRIORITY_QUEUE_OF(size_t); static size_t num_rec_freed; static int size_t_compare(const size_t *a, const size_t *b) { if (*a < *b) return -1; if (*a > *b) return 1; return 0; } static int qsort_size_t_compare(const void *a, const void *b) { return size_t_compare((size_t *)a, (size_t *)b); } static int qsort_size_t_compare_rev(const void *a, const void *b) { return size_t_compare((size_t *)b, (size_t *)a); } static void free_checker(ossl_unused size_t *p) { num_rec_freed++; } static int test_size_t_priority_queue_int(int reserve, int order, int count, int remove, int random, int popfree) { PRIORITY_QUEUE_OF(size_t) *pq = NULL; static size_t values[MAX_SAMPLES], sorted[MAX_SAMPLES], ref[MAX_SAMPLES]; size_t n; int i, res = 0; static const char *orders[3] = { "unordered", "ascending", "descending" }; TEST_info("testing count %d, %s, %s, values %s, remove %d, %sfree", count, orders[order], reserve ? "reserve" : "grow", random ? "random" : "deterministic", remove, popfree ? "pop " : ""); if (!TEST_size_t_le(count, MAX_SAMPLES)) return 0; memset(values, 0, sizeof(values)); memset(sorted, 0, sizeof(sorted)); memset(ref, 0, sizeof(ref)); for (i = 0; i < count; i++) values[i] = random ? test_random() : (size_t)(count - i); memcpy(sorted, values, sizeof(*sorted) * count); qsort(sorted, count, sizeof(*sorted), &qsort_size_t_compare); if (order == 1) memcpy(values, sorted, sizeof(*values) * count); else if (order == 2) qsort(values, count, sizeof(*values), &qsort_size_t_compare_rev); if (!TEST_ptr(pq = ossl_pqueue_size_t_new(&size_t_compare)) || !TEST_size_t_eq(ossl_pqueue_size_t_num(pq), 0)) goto err; if (reserve && !TEST_true(ossl_pqueue_size_t_reserve(pq, count))) goto err; for (i = 0; i < count; i++) if (!TEST_true(ossl_pqueue_size_t_push(pq, values + i, ref + i))) goto err; if (!TEST_size_t_eq(*ossl_pqueue_size_t_peek(pq), *sorted) || !TEST_size_t_eq(ossl_pqueue_size_t_num(pq), count)) goto err; if (remove) { while (remove-- > 0) { i = test_random() % count; if (values[i] != SIZE_MAX) { if (!TEST_ptr_eq(ossl_pqueue_size_t_remove(pq, ref[i]), values + i)) goto err; values[i] = SIZE_MAX; } } memcpy(sorted, values, sizeof(*sorted) * count); qsort(sorted, count, sizeof(*sorted), &qsort_size_t_compare); } for (i = 0; ossl_pqueue_size_t_peek(pq) != NULL; i++) if (!TEST_size_t_eq(*ossl_pqueue_size_t_peek(pq), sorted[i]) || !TEST_size_t_eq(*ossl_pqueue_size_t_pop(pq), sorted[i])) goto err; if (popfree) { num_rec_freed = 0; n = ossl_pqueue_size_t_num(pq); ossl_pqueue_size_t_pop_free(pq, &free_checker); pq = NULL; if (!TEST_size_t_eq(num_rec_freed, n)) goto err; } res = 1; err: ossl_pqueue_size_t_free(pq); return res; } static const int test_size_t_priority_counts[] = { 10, 11, 6, 5, 3, 1, 2, 7500 }; static int test_size_t_priority_queue(int n) { int reserve, order, count, remove, random, popfree; count = n % OSSL_NELEM(test_size_t_priority_counts); n /= OSSL_NELEM(test_size_t_priority_counts); order = n % 3; n /= 3; random = n % 2; n /= 2; reserve = n % 2; n /= 2; remove = n % 6; n /= 6; popfree = n % 2; count = test_size_t_priority_counts[count]; return test_size_t_priority_queue_int(reserve, order, count, remove, random, popfree); } static int test_large_priority_queue(void) { return test_size_t_priority_queue_int(0, 0, MAX_SAMPLES, MAX_SAMPLES / 100, 1, 1); } int setup_tests(void) { ADD_ALL_TESTS(test_size_t_priority_queue, OSSL_NELEM(test_size_t_priority_counts) /* count */ * 3 /* order */ * 2 /* random */ * 2 /* reserve */ * 6 /* remove */ * 2); /* pop & free */ ADD_TEST(test_large_priority_queue); return 1; }
5,206
29.273256
79
c
openssl
openssl-master/test/property_test.c
/* * Copyright 2019-2021 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 <stdarg.h> #include <openssl/evp.h> #include "testutil.h" #include "internal/nelem.h" #include "internal/property.h" #include "../crypto/property/property_local.h" /* * We make our OSSL_PROVIDER for testing purposes. All we really need is * a pointer. We know that as long as we don't try to use the method * cache flush functions, the provider pointer is merely a pointer being * passed around, and used as a tag of sorts. */ struct ossl_provider_st { int x; }; static int add_property_names(const char *n, ...) { va_list args; int res = 1; va_start(args, n); do { if (!TEST_int_ne(ossl_property_name(NULL, n, 1), 0)) res = 0; } while ((n = va_arg(args, const char *)) != NULL); va_end(args); return res; } static int up_ref(void *p) { return 1; } static void down_ref(void *p) { } static int test_property_string(void) { OSSL_LIB_CTX *ctx; OSSL_METHOD_STORE *store = NULL; int res = 0; OSSL_PROPERTY_IDX i, j; /*- * Use our own library context because we depend on ordering from a * pristine state. */ if (TEST_ptr(ctx = OSSL_LIB_CTX_new()) && TEST_ptr(store = ossl_method_store_new(ctx)) && TEST_int_eq(ossl_property_name(ctx, "fnord", 0), 0) && TEST_int_ne(ossl_property_name(ctx, "fnord", 1), 0) && TEST_int_ne(ossl_property_name(ctx, "name", 1), 0) /* Pre loaded names */ && TEST_str_eq(ossl_property_name_str(ctx, 1), "provider") && TEST_str_eq(ossl_property_name_str(ctx, 2), "version") && TEST_str_eq(ossl_property_name_str(ctx, 3), "fips") && TEST_str_eq(ossl_property_name_str(ctx, 4), "output") && TEST_str_eq(ossl_property_name_str(ctx, 5), "input") && TEST_str_eq(ossl_property_name_str(ctx, 6), "structure") /* The names we added */ && TEST_str_eq(ossl_property_name_str(ctx, 7), "fnord") && TEST_str_eq(ossl_property_name_str(ctx, 8), "name") /* Out of range */ && TEST_ptr_null(ossl_property_name_str(ctx, 0)) && TEST_ptr_null(ossl_property_name_str(ctx, 9)) /* Property value checks */ && TEST_int_eq(ossl_property_value(ctx, "fnord", 0), 0) && TEST_int_ne(i = ossl_property_value(ctx, "no", 0), 0) && TEST_int_ne(j = ossl_property_value(ctx, "yes", 0), 0) && TEST_int_ne(i, j) && TEST_int_eq(ossl_property_value(ctx, "yes", 1), j) && TEST_int_eq(ossl_property_value(ctx, "no", 1), i) && TEST_int_ne(i = ossl_property_value(ctx, "illuminati", 1), 0) && TEST_int_eq(j = ossl_property_value(ctx, "fnord", 1), i + 1) && TEST_int_eq(ossl_property_value(ctx, "fnord", 1), j) /* Pre loaded values */ && TEST_str_eq(ossl_property_value_str(ctx, 1), "yes") && TEST_str_eq(ossl_property_value_str(ctx, 2), "no") /* The value we added */ && TEST_str_eq(ossl_property_value_str(ctx, 3), "illuminati") && TEST_str_eq(ossl_property_value_str(ctx, 4), "fnord") /* Out of range */ && TEST_ptr_null(ossl_property_value_str(ctx, 0)) && TEST_ptr_null(ossl_property_value_str(ctx, 5)) /* Check name and values are distinct */ && TEST_int_eq(ossl_property_value(ctx, "cold", 0), 0) && TEST_int_ne(ossl_property_name(ctx, "fnord", 0), ossl_property_value(ctx, "fnord", 0))) res = 1; ossl_method_store_free(store); OSSL_LIB_CTX_free(ctx); return res; } static const struct { const char *defn; const char *query; int e; } parser_tests[] = { { "", "sky=blue", -1 }, { "", "sky!=blue", 1 }, { "groan", "", 0 }, { "cold=yes", "cold=yes", 1 }, { "cold=yes", "cold", 1 }, { "cold=yes", "cold!=no", 1 }, { "groan", "groan=yes", 1 }, { "groan", "groan=no", -1 }, { "groan", "groan!=yes", -1 }, { "cold=no", "cold", -1 }, { "cold=no", "?cold", 0 }, { "cold=no", "cold=no", 1 }, { "groan", "cold", -1 }, { "groan", "cold=no", 1 }, { "groan", "cold!=yes", 1 }, { "groan=blue", "groan=yellow", -1 }, { "groan=blue", "?groan=yellow", 0 }, { "groan=blue", "groan!=yellow", 1 }, { "groan=blue", "?groan!=yellow", 1 }, { "today=monday, tomorrow=3", "today!=2", 1 }, { "today=monday, tomorrow=3", "today!='monday'", -1 }, { "today=monday, tomorrow=3", "tomorrow=3", 1 }, { "n=0x3", "n=3", 1 }, { "n=0x3", "n=-3", -1 }, { "n=0x33", "n=51", 1 }, { "n=033", "n=27", 1 }, { "n=0", "n=00", 1 }, { "n=0x0", "n=0", 1 }, { "n=0, sky=blue", "?n=0, sky=blue", 2 }, { "n=1, sky=blue", "?n=0, sky=blue", 1 }, }; static int test_property_parse(int n) { OSSL_METHOD_STORE *store; OSSL_PROPERTY_LIST *p = NULL, *q = NULL; int r = 0; if (TEST_ptr(store = ossl_method_store_new(NULL)) && add_property_names("sky", "groan", "cold", "today", "tomorrow", "n", NULL) && TEST_ptr(p = ossl_parse_property(NULL, parser_tests[n].defn)) && TEST_ptr(q = ossl_parse_query(NULL, parser_tests[n].query, 0)) && TEST_int_eq(ossl_property_match_count(q, p), parser_tests[n].e)) r = 1; ossl_property_free(p); ossl_property_free(q); ossl_method_store_free(store); return r; } static int test_property_query_value_create(void) { OSSL_METHOD_STORE *store; OSSL_PROPERTY_LIST *p = NULL, *q = NULL, *o = NULL; int r = 0; /* The property value used here must not be used in other test cases */ if (TEST_ptr(store = ossl_method_store_new(NULL)) && add_property_names("wood", NULL) && TEST_ptr(p = ossl_parse_query(NULL, "wood=oak", 0)) /* undefined */ && TEST_ptr(q = ossl_parse_query(NULL, "wood=oak", 1)) /* creates */ && TEST_ptr(o = ossl_parse_query(NULL, "wood=oak", 0)) /* defined */ && TEST_int_eq(ossl_property_match_count(q, p), -1) && TEST_int_eq(ossl_property_match_count(q, o), 1)) r = 1; ossl_property_free(o); ossl_property_free(p); ossl_property_free(q); ossl_method_store_free(store); return r; } static const struct { int query; const char *ps; } parse_error_tests[] = { { 0, "n=1, n=1" }, /* duplicate name */ { 0, "n=1, a=hi, n=1" }, /* duplicate name */ { 1, "n=1, a=bye, ?n=0" }, /* duplicate name */ { 0, "a=abc,#@!, n=1" }, /* non-ASCII character located */ { 1, "a='Hello" }, /* Unterminated string */ { 0, "a=\"World" }, /* Unterminated string */ { 0, "a=_abd_" }, /* Unquoted string not starting with alphabetic */ { 1, "a=2, n=012345678" }, /* Bad octal digit */ { 0, "n=0x28FG, a=3" }, /* Bad hex digit */ { 0, "n=145d, a=2" }, /* Bad decimal digit */ { 1, "@='hello'" }, /* Invalid name */ { 1, "n0123456789012345678901234567890123456789" "0123456789012345678901234567890123456789" "0123456789012345678901234567890123456789" "0123456789012345678901234567890123456789=yes" }, /* Name too long */ { 0, ".n=3" }, /* Invalid name */ { 1, "fnord.fnord.=3" } /* Invalid name */ }; static int test_property_parse_error(int n) { OSSL_METHOD_STORE *store; OSSL_PROPERTY_LIST *p = NULL; int r = 0; const char *ps; if (!TEST_ptr(store = ossl_method_store_new(NULL)) || !add_property_names("a", "n", NULL)) goto err; ps = parse_error_tests[n].ps; if (parse_error_tests[n].query) { if (!TEST_ptr_null(p = ossl_parse_query(NULL, ps, 1))) goto err; } else if (!TEST_ptr_null(p = ossl_parse_property(NULL, ps))) { goto err; } r = 1; err: ossl_property_free(p); ossl_method_store_free(store); return r; } static const struct { const char *q_global; const char *q_local; const char *prop; } merge_tests[] = { { "", "colour=blue", "colour=blue" }, { "colour=blue", "", "colour=blue" }, { "colour=red", "colour=blue", "colour=blue" }, { "clouds=pink, urn=red", "urn=blue, colour=green", "urn=blue, colour=green, clouds=pink" }, { "pot=gold", "urn=blue", "pot=gold, urn=blue" }, { "night", "day", "day=yes, night=yes" }, { "day", "night", "day=yes, night=yes" }, { "", "", "" }, /* * The following four leave 'day' unspecified in the query, and will match * any definition */ { "day=yes", "-day", "day=no" }, { "day=yes", "-day", "day=yes" }, { "day=yes", "-day", "day=arglebargle" }, { "day=yes", "-day", "pot=sesquioxidizing" }, { "day, night", "-night, day", "day=yes, night=no" }, { "-day", "day=yes", "day=yes" }, }; static int test_property_merge(int n) { OSSL_METHOD_STORE *store; OSSL_PROPERTY_LIST *q_global = NULL, *q_local = NULL; OSSL_PROPERTY_LIST *q_combined = NULL, *prop = NULL; int r = 0; if (TEST_ptr(store = ossl_method_store_new(NULL)) && add_property_names("colour", "urn", "clouds", "pot", "day", "night", NULL) && TEST_ptr(prop = ossl_parse_property(NULL, merge_tests[n].prop)) && TEST_ptr(q_global = ossl_parse_query(NULL, merge_tests[n].q_global, 0)) && TEST_ptr(q_local = ossl_parse_query(NULL, merge_tests[n].q_local, 0)) && TEST_ptr(q_combined = ossl_property_merge(q_local, q_global)) && TEST_int_ge(ossl_property_match_count(q_combined, prop), 0)) r = 1; ossl_property_free(q_global); ossl_property_free(q_local); ossl_property_free(q_combined); ossl_property_free(prop); ossl_method_store_free(store); return r; } static int test_property_defn_cache(void) { OSSL_METHOD_STORE *store; OSSL_PROPERTY_LIST *red = NULL, *blue = NULL, *blue2 = NULL; int r; r = TEST_ptr(store = ossl_method_store_new(NULL)) && add_property_names("red", "blue", NULL) && TEST_ptr(red = ossl_parse_property(NULL, "red")) && TEST_ptr(blue = ossl_parse_property(NULL, "blue")) && TEST_ptr_ne(red, blue) && TEST_true(ossl_prop_defn_set(NULL, "red", &red)); if (!r) { ossl_property_free(red); red = NULL; ossl_property_free(blue); blue = NULL; } r = r && TEST_true(ossl_prop_defn_set(NULL, "blue", &blue)); if (!r) { ossl_property_free(blue); blue = NULL; } r = r && TEST_ptr_eq(ossl_prop_defn_get(NULL, "red"), red) && TEST_ptr_eq(ossl_prop_defn_get(NULL, "blue"), blue) && TEST_ptr(blue2 = ossl_parse_property(NULL, "blue")) && TEST_ptr_ne(blue2, blue) && TEST_true(ossl_prop_defn_set(NULL, "blue", &blue2)); if (!r) { ossl_property_free(blue2); blue2 = NULL; } r = r && TEST_ptr_eq(blue2, blue) && TEST_ptr_eq(ossl_prop_defn_get(NULL, "blue"), blue); ossl_method_store_free(store); return r; } static const struct { const char *defn; const char *query; int e; } definition_tests[] = { { "alpha", "alpha=yes", 1 }, { "alpha=no", "alpha", -1 }, { "alpha=1", "alpha=1", 1 }, { "alpha=2", "alpha=1",-1 }, { "alpha", "omega", -1 }, { "alpha", "?omega", 0 }, { "alpha", "?omega=1", 0 }, { "alpha", "?omega=no", 1 }, { "alpha", "?omega=yes", 0 }, { "alpha, omega", "?omega=yes", 1 }, { "alpha, omega", "?omega=no", 0 } }; static int test_definition_compares(int n) { OSSL_METHOD_STORE *store; OSSL_PROPERTY_LIST *d = NULL, *q = NULL; int r; r = TEST_ptr(store = ossl_method_store_new(NULL)) && add_property_names("alpha", "omega", NULL) && TEST_ptr(d = ossl_parse_property(NULL, definition_tests[n].defn)) && TEST_ptr(q = ossl_parse_query(NULL, definition_tests[n].query, 0)) && TEST_int_eq(ossl_property_match_count(q, d), definition_tests[n].e); ossl_property_free(d); ossl_property_free(q); ossl_method_store_free(store); return r; } static int test_register_deregister(void) { static const struct { int nid; const char *prop; char *impl; } impls[] = { { 6, "position=1", "a" }, { 6, "position=2", "b" }, { 6, "position=3", "c" }, { 6, "position=4", "d" }, }; size_t i; int ret = 0; OSSL_METHOD_STORE *store; OSSL_PROVIDER prov = { 1 }; if (!TEST_ptr(store = ossl_method_store_new(NULL)) || !add_property_names("position", NULL)) goto err; for (i = 0; i < OSSL_NELEM(impls); i++) if (!TEST_true(ossl_method_store_add(store, &prov, impls[i].nid, impls[i].prop, impls[i].impl, &up_ref, &down_ref))) { TEST_note("iteration %zd", i + 1); goto err; } /* Deregister in a different order to registration */ for (i = 0; i < OSSL_NELEM(impls); i++) { const size_t j = (1 + i * 3) % OSSL_NELEM(impls); int nid = impls[j].nid; void *impl = impls[j].impl; if (!TEST_true(ossl_method_store_remove(store, nid, impl)) || !TEST_false(ossl_method_store_remove(store, nid, impl))) { TEST_note("iteration %zd, position %zd", i + 1, j + 1); goto err; } } if (TEST_false(ossl_method_store_remove(store, impls[0].nid, impls[0].impl))) ret = 1; err: ossl_method_store_free(store); return ret; } static int test_property(void) { static OSSL_PROVIDER fake_provider1 = { 1 }; static OSSL_PROVIDER fake_provider2 = { 2 }; static const OSSL_PROVIDER *fake_prov1 = &fake_provider1; static const OSSL_PROVIDER *fake_prov2 = &fake_provider2; static const struct { const OSSL_PROVIDER **prov; int nid; const char *prop; char *impl; } impls[] = { { &fake_prov1, 1, "fast=no, colour=green", "a" }, { &fake_prov1, 1, "fast, colour=blue", "b" }, { &fake_prov1, 1, "", "-" }, { &fake_prov2, 9, "sky=blue, furry", "c" }, { &fake_prov2, 3, NULL, "d" }, { &fake_prov2, 6, "sky.colour=blue, sky=green, old.data", "e" }, }; static struct { const OSSL_PROVIDER **prov; int nid; const char *prop; char *expected; } queries[] = { { &fake_prov1, 1, "fast", "b" }, { &fake_prov1, 1, "fast=yes", "b" }, { &fake_prov1, 1, "fast=no, colour=green", "a" }, { &fake_prov1, 1, "colour=blue, fast", "b" }, { &fake_prov1, 1, "colour=blue", "b" }, { &fake_prov2, 9, "furry", "c" }, { &fake_prov2, 6, "sky.colour=blue", "e" }, { &fake_prov2, 6, "old.data", "e" }, { &fake_prov2, 9, "furry=yes, sky=blue", "c" }, { &fake_prov1, 1, "", "a" }, { &fake_prov2, 3, "", "d" }, }; OSSL_METHOD_STORE *store; size_t i; int ret = 0; void *result; if (!TEST_ptr(store = ossl_method_store_new(NULL)) || !add_property_names("fast", "colour", "sky", "furry", NULL)) goto err; for (i = 0; i < OSSL_NELEM(impls); i++) if (!TEST_true(ossl_method_store_add(store, *impls[i].prov, impls[i].nid, impls[i].prop, impls[i].impl, &up_ref, &down_ref))) { TEST_note("iteration %zd", i + 1); goto err; } /* * The first check of queries is with NULL given as provider. All * queries are expected to succeed. */ for (i = 0; i < OSSL_NELEM(queries); i++) { const OSSL_PROVIDER *nullprov = NULL; OSSL_PROPERTY_LIST *pq = NULL; if (!TEST_true(ossl_method_store_fetch(store, queries[i].nid, queries[i].prop, &nullprov, &result)) || !TEST_str_eq((char *)result, queries[i].expected)) { TEST_note("iteration %zd", i + 1); ossl_property_free(pq); goto err; } ossl_property_free(pq); } /* * The second check of queries is with &address1 given as provider. */ for (i = 0; i < OSSL_NELEM(queries); i++) { OSSL_PROPERTY_LIST *pq = NULL; result = NULL; if (queries[i].prov == &fake_prov1) { if (!TEST_true(ossl_method_store_fetch(store, queries[i].nid, queries[i].prop, &fake_prov1, &result)) || !TEST_ptr_eq(fake_prov1, &fake_provider1) || !TEST_str_eq((char *)result, queries[i].expected)) { TEST_note("iteration %zd", i + 1); ossl_property_free(pq); goto err; } } else { if (!TEST_false(ossl_method_store_fetch(store, queries[i].nid, queries[i].prop, &fake_prov1, &result)) || !TEST_ptr_eq(fake_prov1, &fake_provider1) || !TEST_ptr_null(result)) { TEST_note("iteration %zd", i + 1); ossl_property_free(pq); goto err; } } ossl_property_free(pq); } /* * The third check of queries is with &address2 given as provider. */ for (i = 0; i < OSSL_NELEM(queries); i++) { OSSL_PROPERTY_LIST *pq = NULL; result = NULL; if (queries[i].prov == &fake_prov2) { if (!TEST_true(ossl_method_store_fetch(store, queries[i].nid, queries[i].prop, &fake_prov2, &result)) || !TEST_ptr_eq(fake_prov2, &fake_provider2) || !TEST_str_eq((char *)result, queries[i].expected)) { TEST_note("iteration %zd", i + 1); ossl_property_free(pq); goto err; } } else { if (!TEST_false(ossl_method_store_fetch(store, queries[i].nid, queries[i].prop, &fake_prov2, &result)) || !TEST_ptr_eq(fake_prov2, &fake_provider2) || !TEST_ptr_null(result)) { TEST_note("iteration %zd", i + 1); ossl_property_free(pq); goto err; } } ossl_property_free(pq); } ret = 1; err: ossl_method_store_free(store); return ret; } static int test_query_cache_stochastic(void) { const int max = 10000, tail = 10; OSSL_METHOD_STORE *store; int i, res = 0; char buf[50]; void *result; int errors = 0; int v[10001]; OSSL_PROVIDER prov = { 1 }; if (!TEST_ptr(store = ossl_method_store_new(NULL)) || !add_property_names("n", NULL)) goto err; for (i = 1; i <= max; i++) { v[i] = 2 * i; BIO_snprintf(buf, sizeof(buf), "n=%d\n", i); if (!TEST_true(ossl_method_store_add(store, &prov, i, buf, "abc", &up_ref, &down_ref)) || !TEST_true(ossl_method_store_cache_set(store, &prov, i, buf, v + i, &up_ref, &down_ref)) || !TEST_true(ossl_method_store_cache_set(store, &prov, i, "n=1234", "miss", &up_ref, &down_ref))) { TEST_note("iteration %d", i); goto err; } } for (i = 1; i <= max; i++) { BIO_snprintf(buf, sizeof(buf), "n=%d\n", i); if (!ossl_method_store_cache_get(store, NULL, i, buf, &result) || result != v + i) errors++; } /* There is a tiny probability that this will fail when it shouldn't */ res = TEST_int_gt(errors, tail) && TEST_int_lt(errors, max - tail); err: ossl_method_store_free(store); return res; } static int test_fips_mode(void) { int ret = 0; OSSL_LIB_CTX *ctx = NULL; if (!TEST_ptr(ctx = OSSL_LIB_CTX_new())) goto err; ret = TEST_true(EVP_set_default_properties(ctx, "default=yes,fips=yes")) && TEST_true(EVP_default_properties_is_fips_enabled(ctx)) && TEST_true(EVP_set_default_properties(ctx, "fips=no,default=yes")) && TEST_false(EVP_default_properties_is_fips_enabled(ctx)) && TEST_true(EVP_set_default_properties(ctx, "fips=no")) && TEST_false(EVP_default_properties_is_fips_enabled(ctx)) && TEST_true(EVP_set_default_properties(ctx, "fips!=no")) && TEST_true(EVP_default_properties_is_fips_enabled(ctx)) && TEST_true(EVP_set_default_properties(ctx, "fips=no")) && TEST_false(EVP_default_properties_is_fips_enabled(ctx)) && TEST_true(EVP_set_default_properties(ctx, "fips=no,default=yes")) && TEST_true(EVP_default_properties_enable_fips(ctx, 1)) && TEST_true(EVP_default_properties_is_fips_enabled(ctx)) && TEST_true(EVP_default_properties_enable_fips(ctx, 0)) && TEST_false(EVP_default_properties_is_fips_enabled(ctx)); err: OSSL_LIB_CTX_free(ctx); return ret; } static struct { const char *in; const char *out; } to_string_tests[] = { { "fips=yes", "fips=yes" }, { "fips!=yes", "fips!=yes" }, { "fips = yes", "fips=yes" }, { "fips", "fips=yes" }, { "fips=no", "fips=no" }, { "-fips", "-fips" }, { "?fips=yes", "?fips=yes" }, { "fips=yes,provider=fips", "fips=yes,provider=fips" }, { "fips = yes , provider = fips", "fips=yes,provider=fips" }, { "fips=yes,provider!=fips", "fips=yes,provider!=fips" }, { "fips=yes,?provider=fips", "fips=yes,?provider=fips" }, { "fips=yes,-provider", "fips=yes,-provider" }, /* foo is an unknown internal name */ { "foo=yes,fips=yes", "fips=yes"}, { "", "" }, { "fips=3", "fips=3" }, { "fips=-3", "fips=-3" }, { NULL, "" } }; static int test_property_list_to_string(int i) { OSSL_PROPERTY_LIST *pl = NULL; int ret = 0; size_t bufsize; char *buf = NULL; if (to_string_tests[i].in != NULL && !TEST_ptr(pl = ossl_parse_query(NULL, to_string_tests[i].in, 1))) goto err; bufsize = ossl_property_list_to_string(NULL, pl, NULL, 0); if (!TEST_size_t_gt(bufsize, 0)) goto err; buf = OPENSSL_malloc(bufsize); if (!TEST_ptr(buf) || !TEST_size_t_eq(ossl_property_list_to_string(NULL, pl, buf, bufsize), bufsize) || !TEST_str_eq(to_string_tests[i].out, buf) || !TEST_size_t_eq(bufsize, strlen(to_string_tests[i].out) + 1)) goto err; ret = 1; err: OPENSSL_free(buf); ossl_property_free(pl); return ret; } int setup_tests(void) { ADD_TEST(test_property_string); ADD_TEST(test_property_query_value_create); ADD_ALL_TESTS(test_property_parse, OSSL_NELEM(parser_tests)); ADD_ALL_TESTS(test_property_parse_error, OSSL_NELEM(parse_error_tests)); ADD_ALL_TESTS(test_property_merge, OSSL_NELEM(merge_tests)); ADD_TEST(test_property_defn_cache); ADD_ALL_TESTS(test_definition_compares, OSSL_NELEM(definition_tests)); ADD_TEST(test_register_deregister); ADD_TEST(test_property); ADD_TEST(test_query_cache_stochastic); ADD_TEST(test_fips_mode); ADD_ALL_TESTS(test_property_list_to_string, OSSL_NELEM(to_string_tests)); return 1; }
24,577
34.313218
82
c
openssl
openssl-master/test/prov_config_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 <openssl/evp.h> #include "testutil.h" static char *configfile = NULL; /* * Test to make sure there are no leaks or failures from loading the config * file twice. */ static int test_double_config(void) { OSSL_LIB_CTX *ctx = OSSL_LIB_CTX_new(); int testresult = 0; EVP_MD *sha256 = NULL; if (!TEST_ptr(configfile)) return 0; if (!TEST_ptr(ctx)) return 0; if (!TEST_true(OSSL_LIB_CTX_load_config(ctx, configfile))) return 0; if (!TEST_true(OSSL_LIB_CTX_load_config(ctx, configfile))) return 0; /* Check we can actually fetch something */ sha256 = EVP_MD_fetch(ctx, "SHA2-256", NULL); if (!TEST_ptr(sha256)) goto err; testresult = 1; err: EVP_MD_free(sha256); OSSL_LIB_CTX_free(ctx); return testresult; } OPT_TEST_DECLARE_USAGE("configfile\n") int setup_tests(void) { if (!test_skip_common_options()) { TEST_error("Error parsing test options\n"); return 0; } if (!TEST_ptr(configfile = test_get_argument(0))) return 0; ADD_TEST(test_double_config); return 1; }
1,452
22.435484
75
c
openssl
openssl-master/test/provfetchtest.c
/* * Copyright 2021-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 <openssl/provider.h> #include <openssl/decoder.h> #include <openssl/encoder.h> #include <openssl/store.h> #include <openssl/rand.h> #include <openssl/core_names.h> #include "testutil.h" static int dummy_decoder_decode(void *ctx, OSSL_CORE_BIO *cin, int selection, OSSL_CALLBACK *object_cb, void *object_cbarg, OSSL_PASSPHRASE_CALLBACK *pw_cb, void *pw_cbarg) { return 0; } static const OSSL_DISPATCH dummy_decoder_functions[] = { { OSSL_FUNC_DECODER_DECODE, (void (*)(void))dummy_decoder_decode }, OSSL_DISPATCH_END }; static const OSSL_ALGORITHM dummy_decoders[] = { { "DUMMY", "provider=dummy,input=pem", dummy_decoder_functions }, { NULL, NULL, NULL } }; static int dummy_encoder_encode(void *ctx, OSSL_CORE_BIO *out, const void *obj_raw, const OSSL_PARAM obj_abstract[], int selection, OSSL_PASSPHRASE_CALLBACK *cb, void *cbarg) { return 0; } static const OSSL_DISPATCH dummy_encoder_functions[] = { { OSSL_FUNC_DECODER_DECODE, (void (*)(void))dummy_encoder_encode }, OSSL_DISPATCH_END }; static const OSSL_ALGORITHM dummy_encoders[] = { { "DUMMY", "provider=dummy,output=pem", dummy_encoder_functions }, { NULL, NULL, NULL } }; static void *dummy_store_open(void *provctx, const char *uri) { return NULL; } static int dummy_store_load(void *loaderctx, OSSL_CALLBACK *object_cb, void *object_cbarg, OSSL_PASSPHRASE_CALLBACK *pw_cb, void *pw_cbarg) { return 0; } static int dumm_store_eof(void *loaderctx) { return 0; } static int dummy_store_close(void *loaderctx) { return 0; } static const OSSL_DISPATCH dummy_store_functions[] = { { OSSL_FUNC_STORE_OPEN, (void (*)(void))dummy_store_open }, { OSSL_FUNC_STORE_LOAD, (void (*)(void))dummy_store_load }, { OSSL_FUNC_STORE_EOF, (void (*)(void))dumm_store_eof }, { OSSL_FUNC_STORE_CLOSE, (void (*)(void))dummy_store_close }, OSSL_DISPATCH_END }; static const OSSL_ALGORITHM dummy_store[] = { { "DUMMY", "provider=dummy", dummy_store_functions }, { NULL, NULL, NULL } }; static void *dummy_rand_newctx(void *provctx, void *parent, const OSSL_DISPATCH *parent_calls) { return provctx; } static void dummy_rand_freectx(void *vctx) { } static int dummy_rand_instantiate(void *vdrbg, unsigned int strength, int prediction_resistance, const unsigned char *pstr, size_t pstr_len, const OSSL_PARAM params[]) { return 1; } static int dummy_rand_uninstantiate(void *vdrbg) { return 1; } static int dummy_rand_generate(void *vctx, unsigned char *out, size_t outlen, unsigned int strength, int prediction_resistance, const unsigned char *addin, size_t addin_len) { size_t i; for (i = 0; i <outlen; i++) out[i] = (unsigned char)(i & 0xff); return 1; } static const OSSL_PARAM *dummy_rand_gettable_ctx_params(void *vctx, void *provctx) { static const OSSL_PARAM known_gettable_ctx_params[] = { OSSL_PARAM_size_t(OSSL_RAND_PARAM_MAX_REQUEST, NULL), OSSL_PARAM_END }; return known_gettable_ctx_params; } static int dummy_rand_get_ctx_params(void *vctx, OSSL_PARAM params[]) { OSSL_PARAM *p; p = OSSL_PARAM_locate(params, OSSL_RAND_PARAM_MAX_REQUEST); if (p != NULL && !OSSL_PARAM_set_size_t(p, INT_MAX)) return 0; return 1; } static int dummy_rand_enable_locking(void *vtest) { return 1; } static int dummy_rand_lock(void *vtest) { return 1; } static void dummy_rand_unlock(void *vtest) { } static const OSSL_DISPATCH dummy_rand_functions[] = { { OSSL_FUNC_RAND_NEWCTX, (void (*)(void))dummy_rand_newctx }, { OSSL_FUNC_RAND_FREECTX, (void (*)(void))dummy_rand_freectx }, { OSSL_FUNC_RAND_INSTANTIATE, (void (*)(void))dummy_rand_instantiate }, { OSSL_FUNC_RAND_UNINSTANTIATE, (void (*)(void))dummy_rand_uninstantiate }, { OSSL_FUNC_RAND_GENERATE, (void (*)(void))dummy_rand_generate }, { OSSL_FUNC_RAND_GETTABLE_CTX_PARAMS, (void(*)(void))dummy_rand_gettable_ctx_params }, { OSSL_FUNC_RAND_GET_CTX_PARAMS, (void(*)(void))dummy_rand_get_ctx_params }, { OSSL_FUNC_RAND_ENABLE_LOCKING, (void(*)(void))dummy_rand_enable_locking }, { OSSL_FUNC_RAND_LOCK, (void(*)(void))dummy_rand_lock }, { OSSL_FUNC_RAND_UNLOCK, (void(*)(void))dummy_rand_unlock }, OSSL_DISPATCH_END }; static const OSSL_ALGORITHM dummy_rand[] = { { "DUMMY", "provider=dummy", dummy_rand_functions }, { NULL, NULL, NULL } }; static const OSSL_ALGORITHM *dummy_query(void *provctx, int operation_id, int *no_cache) { *no_cache = 0; switch (operation_id) { case OSSL_OP_DECODER: return dummy_decoders; case OSSL_OP_ENCODER: return dummy_encoders; case OSSL_OP_STORE: return dummy_store; case OSSL_OP_RAND: return dummy_rand; } return NULL; } static const OSSL_DISPATCH dummy_dispatch_table[] = { { OSSL_FUNC_PROVIDER_QUERY_OPERATION, (void (*)(void))dummy_query }, { OSSL_FUNC_PROVIDER_TEARDOWN, (void (*)(void))OSSL_LIB_CTX_free }, OSSL_DISPATCH_END }; static int dummy_provider_init(const OSSL_CORE_HANDLE *handle, const OSSL_DISPATCH *in, const OSSL_DISPATCH **out, void **provctx) { OSSL_LIB_CTX *libctx = OSSL_LIB_CTX_new_child(handle, in); unsigned char buf[32]; *provctx = (void *)libctx; *out = dummy_dispatch_table; /* * Do some work using the child libctx, to make sure this is possible from * inside the init function. */ if (RAND_bytes_ex(libctx, buf, sizeof(buf), 0) <= 0) return 0; return 1; } /* * Try fetching and freeing various things. * Test 0: Decoder * Test 1: Encoder * Test 2: Store loader * Test 3: EVP_RAND * Test 4-7: As above, but additionally with a query string */ static int fetch_test(int tst) { OSSL_LIB_CTX *libctx = OSSL_LIB_CTX_new(); OSSL_PROVIDER *dummyprov = NULL; OSSL_PROVIDER *nullprov = NULL; OSSL_DECODER *decoder = NULL; OSSL_ENCODER *encoder = NULL; OSSL_STORE_LOADER *loader = NULL; int testresult = 0; unsigned char buf[32]; int query = tst > 3; if (!TEST_ptr(libctx)) goto err; if (!TEST_true(OSSL_PROVIDER_add_builtin(libctx, "dummy-prov", dummy_provider_init)) || !TEST_ptr(nullprov = OSSL_PROVIDER_load(libctx, "default")) || !TEST_ptr(dummyprov = OSSL_PROVIDER_load(libctx, "dummy-prov"))) goto err; switch (tst % 4) { case 0: decoder = OSSL_DECODER_fetch(libctx, "DUMMY", query ? "provider=dummy" : NULL); if (!TEST_ptr(decoder)) goto err; break; case 1: encoder = OSSL_ENCODER_fetch(libctx, "DUMMY", query ? "provider=dummy" : NULL); if (!TEST_ptr(encoder)) goto err; break; case 2: loader = OSSL_STORE_LOADER_fetch(libctx, "DUMMY", query ? "provider=dummy" : NULL); if (!TEST_ptr(loader)) goto err; break; case 3: if (!TEST_true(RAND_set_DRBG_type(libctx, "DUMMY", query ? "provider=dummy" : NULL, NULL, NULL)) || !TEST_int_ge(RAND_bytes_ex(libctx, buf, sizeof(buf), 0), 1)) goto err; break; default: goto err; } testresult = 1; err: OSSL_DECODER_free(decoder); OSSL_ENCODER_free(encoder); OSSL_STORE_LOADER_free(loader); OSSL_PROVIDER_unload(dummyprov); OSSL_PROVIDER_unload(nullprov); OSSL_LIB_CTX_free(libctx); return testresult; } int setup_tests(void) { ADD_ALL_TESTS(fetch_test, 8); return 1; }
8,638
27.989933
82
c
openssl
openssl-master/test/provider_default_search_path_test.c
/* * Copyright 2020-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 <stddef.h> #include <openssl/provider.h> #include "testutil.h" static int test_default_libctx(void) { OSSL_LIB_CTX *ctx = NULL; char *path = "./some/path"; const char *retrieved_path = NULL; int ok; ok = TEST_true(OSSL_PROVIDER_set_default_search_path(ctx, path)) && TEST_ptr(retrieved_path = OSSL_PROVIDER_get0_default_search_path(ctx)) && TEST_str_eq(path, retrieved_path); return ok; } static int test_explicit_libctx(void) { OSSL_LIB_CTX *ctx = NULL; char *def_libctx_path = "./some/path"; char *path = "./another/location"; const char *retrieved_defctx_path = NULL; const char *retrieved_path = NULL; int ok; /* Set search path for default context, then create a new context and set another path for it. Finally, get both paths and make sure they are still what we set and are separate. */ ok = TEST_true(OSSL_PROVIDER_set_default_search_path(NULL, def_libctx_path)) && TEST_ptr(ctx = OSSL_LIB_CTX_new()) && TEST_true(OSSL_PROVIDER_set_default_search_path(ctx, path)) && TEST_ptr(retrieved_defctx_path = OSSL_PROVIDER_get0_default_search_path(NULL)) && TEST_str_eq(def_libctx_path, retrieved_defctx_path) && TEST_ptr(retrieved_path = OSSL_PROVIDER_get0_default_search_path(ctx)) && TEST_str_eq(path, retrieved_path) && TEST_str_ne(retrieved_path, retrieved_defctx_path); OSSL_LIB_CTX_free(ctx); return ok; } int setup_tests(void) { ADD_TEST(test_default_libctx); ADD_TEST(test_explicit_libctx); return 1; }
1,943
31.4
89
c
openssl
openssl-master/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; }
1,417
23.448276
74
c
openssl
openssl-master/test/provider_internal_test.c
/* * Copyright 2019-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/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, 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, 0)) && test_provider(prov, expected_greeting1(name)); } 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 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); ADD_TEST(test_configured_provider); #endif ADD_TEST(test_cache_flushes); return 1; }
4,102
26.722973
81
c
openssl
openssl-master/test/provider_pkey_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 <stddef.h> #include <string.h> #include <openssl/provider.h> #include <openssl/params.h> #include <openssl/core_names.h> #include <openssl/evp.h> #include <openssl/store.h> #include "testutil.h" #include "fake_rsaprov.h" static OSSL_LIB_CTX *libctx = NULL; /* Fetch SIGNATURE method using a libctx and propq */ static int fetch_sig(OSSL_LIB_CTX *ctx, const char *alg, const char *propq, OSSL_PROVIDER *expected_prov) { OSSL_PROVIDER *prov; EVP_SIGNATURE *sig = EVP_SIGNATURE_fetch(ctx, "RSA", propq); int ret = 0; if (!TEST_ptr(sig)) return 0; if (!TEST_ptr(prov = EVP_SIGNATURE_get0_provider(sig))) goto end; if (!TEST_ptr_eq(prov, expected_prov)) { TEST_info("Fetched provider: %s, Expected provider: %s", OSSL_PROVIDER_get0_name(prov), OSSL_PROVIDER_get0_name(expected_prov)); goto end; } ret = 1; end: EVP_SIGNATURE_free(sig); return ret; } static int test_pkey_sig(void) { OSSL_PROVIDER *deflt = NULL; OSSL_PROVIDER *fake_rsa = NULL; int i, ret = 0; EVP_PKEY *pkey = NULL; EVP_PKEY_CTX *ctx = NULL; if (!TEST_ptr(fake_rsa = fake_rsa_start(libctx))) return 0; if (!TEST_ptr(deflt = OSSL_PROVIDER_load(libctx, "default"))) goto end; /* Do a direct fetch to see it works */ if (!TEST_true(fetch_sig(libctx, "RSA", "provider=fake-rsa", fake_rsa)) || !TEST_true(fetch_sig(libctx, "RSA", "?provider=fake-rsa", fake_rsa))) goto end; /* Construct a pkey using precise propq to use our provider */ if (!TEST_ptr(ctx = EVP_PKEY_CTX_new_from_name(libctx, "RSA", "provider=fake-rsa")) || !TEST_true(EVP_PKEY_fromdata_init(ctx)) || !TEST_true(EVP_PKEY_fromdata(ctx, &pkey, EVP_PKEY_KEYPAIR, NULL)) || !TEST_ptr(pkey)) goto end; EVP_PKEY_CTX_free(ctx); ctx = NULL; /* try exercising signature_init ops a few times */ for (i = 0; i < 3; i++) { size_t siglen; /* * Create a signing context for our pkey with optional propq. * The sign init should pick both keymgmt and signature from * fake-rsa as the key is not exportable. */ if (!TEST_ptr(ctx = EVP_PKEY_CTX_new_from_pkey(libctx, pkey, "?provider=default"))) goto end; /* * If this picks the wrong signature without realizing it * we can get a segfault or some internal error. At least watch * whether fake-rsa sign_init is is exercised by calling sign. */ if (!TEST_int_eq(EVP_PKEY_sign_init(ctx), 1)) goto end; if (!TEST_int_eq(EVP_PKEY_sign(ctx, NULL, &siglen, NULL, 0), 1) || !TEST_size_t_eq(siglen, 256)) goto end; EVP_PKEY_CTX_free(ctx); ctx = NULL; } ret = 1; end: fake_rsa_finish(fake_rsa); OSSL_PROVIDER_unload(deflt); EVP_PKEY_CTX_free(ctx); EVP_PKEY_free(pkey); return ret; } static int test_alternative_keygen_init(void) { EVP_PKEY_CTX *ctx = NULL; OSSL_PROVIDER *deflt = NULL; OSSL_PROVIDER *fake_rsa = NULL; const OSSL_PROVIDER *provider; const char *provname; int ret = 0; if (!TEST_ptr(deflt = OSSL_PROVIDER_load(libctx, "default"))) goto end; /* first try without the fake RSA provider loaded */ if (!TEST_ptr(ctx = EVP_PKEY_CTX_new_from_name(libctx, "RSA", NULL))) goto end; if (!TEST_int_gt(EVP_PKEY_keygen_init(ctx), 0)) goto end; if (!TEST_ptr(provider = EVP_PKEY_CTX_get0_provider(ctx))) goto end; if (!TEST_ptr(provname = OSSL_PROVIDER_get0_name(provider))) goto end; if (!TEST_str_eq(provname, "default")) goto end; EVP_PKEY_CTX_free(ctx); ctx = NULL; /* now load fake RSA and try again */ if (!TEST_ptr(fake_rsa = fake_rsa_start(libctx))) return 0; if (!TEST_ptr(ctx = EVP_PKEY_CTX_new_from_name(libctx, "RSA", "?provider=fake-rsa"))) goto end; if (!TEST_int_gt(EVP_PKEY_keygen_init(ctx), 0)) goto end; if (!TEST_ptr(provider = EVP_PKEY_CTX_get0_provider(ctx))) goto end; if (!TEST_ptr(provname = OSSL_PROVIDER_get0_name(provider))) goto end; if (!TEST_str_eq(provname, "fake-rsa")) goto end; ret = 1; end: fake_rsa_finish(fake_rsa); OSSL_PROVIDER_unload(deflt); EVP_PKEY_CTX_free(ctx); return ret; } static int test_pkey_eq(void) { OSSL_PROVIDER *deflt = NULL; OSSL_PROVIDER *fake_rsa = NULL; EVP_PKEY *pkey_fake = NULL; EVP_PKEY *pkey_dflt = NULL; EVP_PKEY_CTX *ctx = NULL; OSSL_PARAM *params = NULL; int ret = 0; if (!TEST_ptr(fake_rsa = fake_rsa_start(libctx))) return 0; if (!TEST_ptr(deflt = OSSL_PROVIDER_load(libctx, "default"))) goto end; /* Construct a public key for fake-rsa */ if (!TEST_ptr(params = fake_rsa_key_params(0)) || !TEST_ptr(ctx = EVP_PKEY_CTX_new_from_name(libctx, "RSA", "provider=fake-rsa")) || !TEST_true(EVP_PKEY_fromdata_init(ctx)) || !TEST_true(EVP_PKEY_fromdata(ctx, &pkey_fake, EVP_PKEY_PUBLIC_KEY, params)) || !TEST_ptr(pkey_fake)) goto end; EVP_PKEY_CTX_free(ctx); ctx = NULL; OSSL_PARAM_free(params); params = NULL; /* Construct a public key for default */ if (!TEST_ptr(params = fake_rsa_key_params(0)) || !TEST_ptr(ctx = EVP_PKEY_CTX_new_from_name(libctx, "RSA", "provider=default")) || !TEST_true(EVP_PKEY_fromdata_init(ctx)) || !TEST_true(EVP_PKEY_fromdata(ctx, &pkey_dflt, EVP_PKEY_PUBLIC_KEY, params)) || !TEST_ptr(pkey_dflt)) goto end; EVP_PKEY_CTX_free(ctx); ctx = NULL; OSSL_PARAM_free(params); params = NULL; /* now test for equality */ if (!TEST_int_eq(EVP_PKEY_eq(pkey_fake, pkey_dflt), 1)) goto end; ret = 1; end: fake_rsa_finish(fake_rsa); OSSL_PROVIDER_unload(deflt); EVP_PKEY_CTX_free(ctx); EVP_PKEY_free(pkey_fake); EVP_PKEY_free(pkey_dflt); OSSL_PARAM_free(params); return ret; } static int test_pkey_store(int idx) { OSSL_PROVIDER *deflt = NULL; OSSL_PROVIDER *fake_rsa = NULL; int ret = 0; EVP_PKEY *pkey = NULL; OSSL_STORE_LOADER *loader = NULL; OSSL_STORE_CTX *ctx = NULL; OSSL_STORE_INFO *info; const char *propq = idx == 0 ? "?provider=fake-rsa" : "?provider=default"; /* It's important to load the default provider first for this test */ if (!TEST_ptr(deflt = OSSL_PROVIDER_load(libctx, "default"))) goto end; if (!TEST_ptr(fake_rsa = fake_rsa_start(libctx))) goto end; if (!TEST_ptr(loader = OSSL_STORE_LOADER_fetch(libctx, "fake_rsa", propq))) goto end; OSSL_STORE_LOADER_free(loader); if (!TEST_ptr(ctx = OSSL_STORE_open_ex("fake_rsa:test", libctx, propq, NULL, NULL, NULL, NULL, NULL))) goto end; while (!OSSL_STORE_eof(ctx) && (info = OSSL_STORE_load(ctx)) != NULL && pkey == NULL) { if (OSSL_STORE_INFO_get_type(info) == OSSL_STORE_INFO_PKEY) pkey = OSSL_STORE_INFO_get1_PKEY(info); OSSL_STORE_INFO_free(info); info = NULL; } if (!TEST_ptr(pkey) || !TEST_int_eq(EVP_PKEY_is_a(pkey, "RSA"), 1)) goto end; ret = 1; end: fake_rsa_finish(fake_rsa); OSSL_PROVIDER_unload(deflt); OSSL_STORE_close(ctx); EVP_PKEY_free(pkey); return ret; } int setup_tests(void) { libctx = OSSL_LIB_CTX_new(); if (libctx == NULL) return 0; ADD_TEST(test_pkey_sig); ADD_TEST(test_alternative_keygen_init); ADD_TEST(test_pkey_eq); ADD_ALL_TESTS(test_pkey_store, 2); return 1; } void cleanup_tests(void) { OSSL_LIB_CTX_free(libctx); }
8,641
26.967638
80
c
openssl
openssl-master/test/provider_status_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 <string.h> #include <openssl/provider.h> #include <openssl/params.h> #include <openssl/core_names.h> #include <openssl/self_test.h> #include <openssl/evp.h> #include "testutil.h" typedef enum OPTION_choice { OPT_ERR = -1, OPT_EOF = 0, OPT_PROVIDER_NAME, OPT_CONFIG_FILE, OPT_TEST_ENUM } OPTION_CHOICE; struct self_test_arg { int count; }; static OSSL_LIB_CTX *libctx = NULL; static char *provider_name = 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, { "provider_name", OPT_PROVIDER_NAME, 's', "The name of the provider to load" }, { "config", OPT_CONFIG_FILE, '<', "The configuration file to use for the libctx" }, { NULL } }; return test_options; } static int self_test_events(const OSSL_PARAM params[], void *arg, const char *title, int corrupt) { struct self_test_arg *args = arg; const OSSL_PARAM *p = NULL; const char *phase = NULL, *type = NULL, *desc = NULL; int ret = 0; if (args->count == 0) BIO_printf(bio_out, "\n%s\n", title); args->count++; p = OSSL_PARAM_locate_const(params, OSSL_PROV_PARAM_SELF_TEST_PHASE); if (p == NULL || p->data_type != OSSL_PARAM_UTF8_STRING) goto err; phase = (const char *)p->data; p = OSSL_PARAM_locate_const(params, OSSL_PROV_PARAM_SELF_TEST_DESC); if (p == NULL || p->data_type != OSSL_PARAM_UTF8_STRING) goto err; desc = (const char *)p->data; p = OSSL_PARAM_locate_const(params, OSSL_PROV_PARAM_SELF_TEST_TYPE); if (p == NULL || p->data_type != OSSL_PARAM_UTF8_STRING) goto err; type = (const char *)p->data; if (strcmp(phase, OSSL_SELF_TEST_PHASE_START) == 0) BIO_printf(bio_out, "%s : (%s) : ", desc, type); else if (strcmp(phase, OSSL_SELF_TEST_PHASE_PASS) == 0 || strcmp(phase, OSSL_SELF_TEST_PHASE_FAIL) == 0) BIO_printf(bio_out, "%s\n", phase); /* * The self test code will internally corrupt the KAT test result if an * error is returned during the corrupt phase. */ if (corrupt && strcmp(phase, OSSL_SELF_TEST_PHASE_CORRUPT) == 0) goto err; ret = 1; err: return ret; } static int self_test_on_demand_fail(const OSSL_PARAM params[], void *arg) { return self_test_events(params, arg, "On Demand Failure", 1); } static int self_test_on_demand(const OSSL_PARAM params[], void *arg) { return self_test_events(params, arg, "On Demand", 0); } static int self_test_on_load(const OSSL_PARAM params[], void *arg) { return self_test_events(params, arg, "On Loading", 0); } static int get_provider_params(const OSSL_PROVIDER *prov) { int ret = 0; OSSL_PARAM params[5]; char *name, *version, *buildinfo; int status; const OSSL_PARAM *gettable, *p; if (!TEST_ptr(gettable = OSSL_PROVIDER_gettable_params(prov)) || !TEST_ptr(p = OSSL_PARAM_locate_const(gettable, OSSL_PROV_PARAM_NAME)) || !TEST_ptr(p = OSSL_PARAM_locate_const(gettable, OSSL_PROV_PARAM_VERSION)) || !TEST_ptr(p = OSSL_PARAM_locate_const(gettable, OSSL_PROV_PARAM_STATUS)) || !TEST_ptr(p = OSSL_PARAM_locate_const(gettable, OSSL_PROV_PARAM_BUILDINFO))) goto end; params[0] = OSSL_PARAM_construct_utf8_ptr(OSSL_PROV_PARAM_NAME, &name, 0); params[1] = OSSL_PARAM_construct_utf8_ptr(OSSL_PROV_PARAM_VERSION, &version, 0); params[2] = OSSL_PARAM_construct_int(OSSL_PROV_PARAM_STATUS, &status); params[3] = OSSL_PARAM_construct_utf8_ptr(OSSL_PROV_PARAM_BUILDINFO, &buildinfo, 0); params[4] = OSSL_PARAM_construct_end(); OSSL_PARAM_set_all_unmodified(params); if (!TEST_true(OSSL_PROVIDER_get_params(prov, params))) goto end; if (!TEST_true(OSSL_PARAM_modified(params + 0)) || !TEST_true(OSSL_PARAM_modified(params + 1)) || !TEST_true(OSSL_PARAM_modified(params + 2)) || !TEST_true(OSSL_PARAM_modified(params + 3)) || !TEST_true(status == 1)) goto end; ret = 1; end: return ret; } static int test_provider_status(void) { int ret = 0; unsigned int status = 0; OSSL_PROVIDER *prov = NULL; OSSL_PARAM params[2]; EVP_MD *fetch = NULL; if (!TEST_ptr(prov = OSSL_PROVIDER_load(libctx, provider_name))) goto err; if (!get_provider_params(prov)) goto err; /* Test that the provider status is ok */ params[0] = OSSL_PARAM_construct_uint(OSSL_PROV_PARAM_STATUS, &status); params[1] = OSSL_PARAM_construct_end(); if (!TEST_true(OSSL_PROVIDER_get_params(prov, params)) || !TEST_true(status == 1)) goto err; if (!TEST_ptr(fetch = EVP_MD_fetch(libctx, "SHA256", NULL))) goto err; EVP_MD_free(fetch); fetch = NULL; /* Test that the provider self test is ok */ self_test_args.count = 0; OSSL_SELF_TEST_set_callback(libctx, self_test_on_demand, &self_test_args); if (!TEST_true(OSSL_PROVIDER_self_test(prov))) goto err; /* Setup a callback that corrupts the self tests and causes status failures */ self_test_args.count = 0; OSSL_SELF_TEST_set_callback(libctx, self_test_on_demand_fail, &self_test_args); if (!TEST_false(OSSL_PROVIDER_self_test(prov))) goto err; if (!TEST_true(OSSL_PROVIDER_get_params(prov, params)) || !TEST_uint_eq(status, 0)) goto err; if (!TEST_ptr_null(fetch = EVP_MD_fetch(libctx, "SHA256", NULL))) goto err; ret = 1; err: EVP_MD_free(fetch); OSSL_PROVIDER_unload(prov); return ret; } static int test_provider_gettable_params(void) { OSSL_PROVIDER *prov; int ret; if (!TEST_ptr(prov = OSSL_PROVIDER_load(libctx, provider_name))) return 0; ret = get_provider_params(prov); OSSL_PROVIDER_unload(prov); 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_PROVIDER_NAME: provider_name = 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 (strcmp(provider_name, "fips") == 0) { self_test_args.count = 0; OSSL_SELF_TEST_set_callback(libctx, self_test_on_load, &self_test_args); if (!OSSL_LIB_CTX_load_config(libctx, config_file)) { opt_printf_stderr("Failed to load config\n"); return 0; } ADD_TEST(test_provider_status); } else { ADD_TEST(test_provider_gettable_params); } return 1; } void cleanup_tests(void) { OSSL_LIB_CTX_free(libctx); }
7,413
29.138211
87
c
openssl
openssl-master/test/provider_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 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 "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) }, { NULL, 0, NULL, 0, 0 } }; static unsigned int digestsuccess = 0; static OSSL_PARAM digest_check[] = { { "digest-check", OSSL_PARAM_UNSIGNED_INTEGER, &digestsuccess, sizeof(digestsuccess) }, { NULL, 0, NULL, 0, 0 } }; static unsigned int stopsuccess = 0; static OSSL_PARAM stop_property_mirror[] = { { "stop-property-mirror", OSSL_PARAM_UNSIGNED_INTEGER, &stopsuccess, sizeof(stopsuccess) }, { NULL, 0, NULL, 0, 0 } }; static int test_provider(OSSL_LIB_CTX **libctx, const char *name, OSSL_PROVIDER *legacy) { OSSL_PROVIDER *prov = NULL; const char *greeting = NULL; char expected_greeting[256]; int ok = 0; long err; int dolegacycheck = (legacy != NULL); OSSL_PROVIDER *deflt = NULL, *base = NULL; BIO_snprintf(expected_greeting, sizeof(expected_greeting), "Hello OpenSSL %.20s, greetings from %s!", OPENSSL_VERSION_STR, name); /* * 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(*libctx, "fips=yes"); /* * Check that it is possible to have a built-in provider mirrored in * a child lib ctx. */ if (!TEST_ptr(base = OSSL_PROVIDER_load(*libctx, "base"))) goto err; if (!TEST_ptr(prov = OSSL_PROVIDER_load(*libctx, name))) goto err; /* * Once the provider is loaded we clear the default properties and fetches * should start working again. */ EVP_set_default_properties(*libctx, ""); if (dolegacycheck) { if (!TEST_true(OSSL_PROVIDER_get_params(prov, digest_check)) || !TEST_true(digestsuccess)) goto err; /* * Check that a provider can prevent property mirroring if it sets its * own properties explicitly */ if (!TEST_true(OSSL_PROVIDER_get_params(prov, stop_property_mirror)) || !TEST_true(stopsuccess)) goto err; EVP_set_default_properties(*libctx, "fips=yes"); if (!TEST_true(OSSL_PROVIDER_get_params(prov, digest_check)) || !TEST_true(digestsuccess)) goto err; EVP_set_default_properties(*libctx, ""); } if (!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)) goto err; /* Make sure we got the error we were expecting */ err = ERR_peek_last_error(); if (!TEST_int_gt(err, 0) || !TEST_int_eq(ERR_GET_REASON(err), 1)) goto err; OSSL_PROVIDER_unload(legacy); legacy = NULL; if (dolegacycheck) { /* Legacy provider should also be unloaded from child libctx */ if (!TEST_true(OSSL_PROVIDER_get_params(prov, digest_check)) || !TEST_false(digestsuccess)) goto err; /* * Loading the legacy provider again should make it available again in * the child libctx. Loading and unloading the default provider should * have no impact on the child because the child loads it explicitly * before this point. */ legacy = OSSL_PROVIDER_load(*libctx, "legacy"); deflt = OSSL_PROVIDER_load(*libctx, "default"); if (!TEST_ptr(deflt) || !TEST_true(OSSL_PROVIDER_available(*libctx, "default"))) goto err; OSSL_PROVIDER_unload(deflt); deflt = NULL; if (!TEST_ptr(legacy) || !TEST_false(OSSL_PROVIDER_available(*libctx, "default")) || !TEST_true(OSSL_PROVIDER_get_params(prov, digest_check)) || !TEST_true(digestsuccess)) goto err; OSSL_PROVIDER_unload(legacy); legacy = NULL; } if (!TEST_true(OSSL_PROVIDER_unload(base))) goto err; base = NULL; if (!TEST_true(OSSL_PROVIDER_unload(prov))) goto err; prov = NULL; /* * We must free the libctx to force the provider to really be unloaded from * memory */ OSSL_LIB_CTX_free(*libctx); *libctx = NULL; /* We print out all the data to make sure it can still be accessed */ ERR_print_errors_fp(stderr); ok = 1; err: OSSL_PROVIDER_unload(base); OSSL_PROVIDER_unload(deflt); OSSL_PROVIDER_unload(legacy); legacy = NULL; OSSL_PROVIDER_unload(prov); OSSL_LIB_CTX_free(*libctx); *libctx = NULL; return ok; } static int test_builtin_provider(void) { OSSL_LIB_CTX *libctx = OSSL_LIB_CTX_new(); const char *name = "p_test_builtin"; int ok; ok = TEST_ptr(libctx) && TEST_true(OSSL_PROVIDER_add_builtin(libctx, name, PROVIDER_INIT_FUNCTION_NAME)) && test_provider(&libctx, name, NULL); OSSL_LIB_CTX_free(libctx); return ok; } /* Test relies on fetching the MD4 digest from the legacy provider */ #ifndef OPENSSL_NO_MD4 static int test_builtin_provider_with_child(void) { OSSL_LIB_CTX *libctx = OSSL_LIB_CTX_new(); const char *name = "p_test"; OSSL_PROVIDER *legacy; if (!TEST_ptr(libctx)) return 0; legacy = OSSL_PROVIDER_load(libctx, "legacy"); if (legacy == NULL) { /* * In this case we assume we've been built with "no-legacy" and skip * this test (there is no OPENSSL_NO_LEGACY) */ OSSL_LIB_CTX_free(libctx); return 1; } if (!TEST_true(OSSL_PROVIDER_add_builtin(libctx, name, PROVIDER_INIT_FUNCTION_NAME))) { OSSL_LIB_CTX_free(libctx); return 0; } /* test_provider will free libctx and unload legacy as part of the test */ return test_provider(&libctx, name, legacy); } #endif #ifndef NO_PROVIDER_MODULE static int test_loaded_provider(void) { OSSL_LIB_CTX *libctx = OSSL_LIB_CTX_new(); const char *name = "p_test"; if (!TEST_ptr(libctx)) return 0; /* test_provider will free libctx as part of the test */ return test_provider(&libctx, name, NULL); } #endif typedef enum OPTION_choice { OPT_ERR = -1, OPT_EOF = 0, OPT_LOADED, OPT_TEST_ENUM } OPTION_CHOICE; const OPTIONS *test_get_options(void) { static const OPTIONS test_options[] = { OPT_TEST_OPTIONS_DEFAULT_USAGE, { "loaded", OPT_LOADED, '-', "Run test with a loaded provider" }, { NULL } }; return test_options; } int setup_tests(void) { OPTION_CHOICE o; int loaded = 0; while ((o = opt_next()) != OPT_EOF) { switch (o) { case OPT_TEST_CASES: break; case OPT_LOADED: loaded = 1; break; default: return 0; } } if (!loaded) { ADD_TEST(test_builtin_provider); #ifndef OPENSSL_NO_MD4 ADD_TEST(test_builtin_provider_with_child); #endif } #ifndef NO_PROVIDER_MODULE else { ADD_TEST(test_loaded_provider); } #endif return 1; }
7,862
28.01476
79
c
openssl
openssl-master/test/punycode_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 <openssl/crypto.h> #include <string.h> #include "crypto/punycode.h" #include "internal/nelem.h" #include "internal/packet.h" #include "testutil.h" static const struct puny_test { unsigned int raw[50]; const char *encoded; } puny_cases[] = { { /* Test of 4 byte codepoint using smileyface emoji */ { 0x1F600 }, "e28h" }, /* Test cases from RFC 3492 */ { /* Arabic (Egyptian) */ { 0x0644, 0x064A, 0x0647, 0x0645, 0x0627, 0x0628, 0x062A, 0x0643, 0x0644, 0x0645, 0x0648, 0x0634, 0x0639, 0x0631, 0x0628, 0x064A, 0x061F }, "egbpdaj6bu4bxfgehfvwxn" }, { /* Chinese (simplified) */ { 0x4ED6, 0x4EEC, 0x4E3A, 0x4EC0, 0x4E48, 0x4E0D, 0x8BF4, 0x4E2D, 0x6587 }, "ihqwcrb4cv8a8dqg056pqjye" }, { /* Chinese (traditional) */ { 0x4ED6, 0x5011, 0x7232, 0x4EC0, 0x9EBD, 0x4E0D, 0x8AAA, 0x4E2D, 0x6587 }, "ihqwctvzc91f659drss3x8bo0yb" }, { /* Czech: Pro<ccaron>prost<ecaron>nemluv<iacute><ccaron>esky */ { 0x0050, 0x0072, 0x006F, 0x010D, 0x0070, 0x0072, 0x006F, 0x0073, 0x0074, 0x011B, 0x006E, 0x0065, 0x006D, 0x006C, 0x0075, 0x0076, 0x00ED, 0x010D, 0x0065, 0x0073, 0x006B, 0x0079 }, "Proprostnemluvesky-uyb24dma41a" }, { /* Hebrew */ { 0x05DC, 0x05DE, 0x05D4, 0x05D4, 0x05DD, 0x05E4, 0x05E9, 0x05D5, 0x05D8, 0x05DC, 0x05D0, 0x05DE, 0x05D3, 0x05D1, 0x05E8, 0x05D9, 0x05DD, 0x05E2, 0x05D1, 0x05E8, 0x05D9, 0x05EA }, "4dbcagdahymbxekheh6e0a7fei0b" }, { /* Hindi (Devanagari) */ { 0x092F, 0x0939, 0x0932, 0x094B, 0x0917, 0x0939, 0x093F, 0x0928, 0x094D, 0x0926, 0x0940, 0x0915, 0x094D, 0x092F, 0x094B, 0x0902, 0x0928, 0x0939, 0x0940, 0x0902, 0x092C, 0x094B, 0x0932, 0x0938, 0x0915, 0x0924, 0x0947, 0x0939, 0x0948, 0x0902 }, "i1baa7eci9glrd9b2ae1bj0hfcgg6iyaf8o0a1dig0cd" }, { /* Japanese (kanji and hiragana) */ { 0x306A, 0x305C, 0x307F, 0x3093, 0x306A, 0x65E5, 0x672C, 0x8A9E, 0x3092, 0x8A71, 0x3057, 0x3066, 0x304F, 0x308C, 0x306A, 0x3044, 0x306E, 0x304B }, "n8jok5ay5dzabd5bym9f0cm5685rrjetr6pdxa" }, { /* Korean (Hangul syllables) */ { 0xC138, 0xACC4, 0xC758, 0xBAA8, 0xB4E0, 0xC0AC, 0xB78C, 0xB4E4, 0xC774, 0xD55C, 0xAD6D, 0xC5B4, 0xB97C, 0xC774, 0xD574, 0xD55C, 0xB2E4, 0xBA74, 0xC5BC, 0xB9C8, 0xB098, 0xC88B, 0xC744, 0xAE4C }, "989aomsvi5e83db1d2a355cv1e0vak1dwrv93d5xbh15a0dt30a5jpsd879ccm6fea98c" }, { /* Russian (Cyrillic) */ { 0x043F, 0x043E, 0x0447, 0x0435, 0x043C, 0x0443, 0x0436, 0x0435, 0x043E, 0x043D, 0x0438, 0x043D, 0x0435, 0x0433, 0x043E, 0x0432, 0x043E, 0x0440, 0x044F, 0x0442, 0x043F, 0x043E, 0x0440, 0x0443, 0x0441, 0x0441, 0x043A, 0x0438 }, "b1abfaaepdrnnbgefbaDotcwatmq2g4l" }, { /* Spanish */ { 0x0050, 0x006F, 0x0072, 0x0071, 0x0075, 0x00E9, 0x006E, 0x006F, 0x0070, 0x0075, 0x0065, 0x0064, 0x0065, 0x006E, 0x0073, 0x0069, 0x006D, 0x0070, 0x006C, 0x0065, 0x006D, 0x0065, 0x006E, 0x0074, 0x0065, 0x0068, 0x0061, 0x0062, 0x006C, 0x0061, 0x0072, 0x0065, 0x006E, 0x0045, 0x0073, 0x0070, 0x0061, 0x00F1, 0x006F, 0x006C }, "PorqunopuedensimplementehablarenEspaol-fmd56a" }, { /* Vietnamese */ { 0x0054, 0x1EA1, 0x0069, 0x0073, 0x0061, 0x006F, 0x0068, 0x1ECD, 0x006B, 0x0068, 0x00F4, 0x006E, 0x0067, 0x0074, 0x0068, 0x1EC3, 0x0063, 0x0068, 0x1EC9, 0x006E, 0x00F3, 0x0069, 0x0074, 0x0069, 0x1EBF, 0x006E, 0x0067, 0x0056, 0x0069, 0x1EC7, 0x0074 }, "TisaohkhngthchnitingVit-kjcr8268qyxafd2f1b9g" }, { /* Japanese: 3<nen>B<gumi><kinpachi><sensei> */ { 0x0033, 0x5E74, 0x0042, 0x7D44, 0x91D1, 0x516B, 0x5148, 0x751F }, "3B-ww4c5e180e575a65lsy2b" }, { /* Japanese: <amuro><namie>-with-SUPER-MONKEYS */ { 0x5B89, 0x5BA4, 0x5948, 0x7F8E, 0x6075, 0x002D, 0x0077, 0x0069, 0x0074, 0x0068, 0x002D, 0x0053, 0x0055, 0x0050, 0x0045, 0x0052, 0x002D, 0x004D, 0x004F, 0x004E, 0x004B, 0x0045, 0x0059, 0x0053 }, "-with-SUPER-MONKEYS-pc58ag80a8qai00g7n9n" }, { /* Japanese: Hello-Another-Way-<sorezore><no><basho> */ { 0x0048, 0x0065, 0x006C, 0x006C, 0x006F, 0x002D, 0x0041, 0x006E, 0x006F, 0x0074, 0x0068, 0x0065, 0x0072, 0x002D, 0x0057, 0x0061, 0x0079, 0x002D, 0x305D, 0x308C, 0x305E, 0x308C, 0x306E, 0x5834, 0x6240 }, "Hello-Another-Way--fc4qua05auwb3674vfr0b" }, { /* Japanese: <hitotsu><yane><no><shita>2 */ { 0x3072, 0x3068, 0x3064, 0x5C4B, 0x6839, 0x306E, 0x4E0B, 0x0032 }, "2-u9tlzr9756bt3uc0v" }, { /* Japanese: Maji<de>Koi<suru>5<byou><mae> */ { 0x004D, 0x0061, 0x006A, 0x0069, 0x3067, 0x004B, 0x006F, 0x0069, 0x3059, 0x308B, 0x0035, 0x79D2, 0x524D }, "MajiKoi5-783gue6qz075azm5e" }, { /* Japanese: <pafii>de<runba> */ { 0x30D1, 0x30D5, 0x30A3, 0x30FC, 0x0064, 0x0065, 0x30EB, 0x30F3, 0x30D0 }, "de-jg4avhby1noc0d" }, { /* Japanese: <sono><supiido><de> */ { 0x305D, 0x306E, 0x30B9, 0x30D4, 0x30FC, 0x30C9, 0x3067 }, "d9juau41awczczp" }, { /* -> $1.00 <- */ { 0x002D, 0x003E, 0x0020, 0x0024, 0x0031, 0x002E, 0x0030, 0x0030, 0x0020, 0x003C, 0x002D }, "-> $1.00 <--" } }; static int test_punycode(int n) { const struct puny_test *tc = puny_cases + n; unsigned int buffer[50]; unsigned int bsize = OSSL_NELEM(buffer); size_t i; if (!TEST_true(ossl_punycode_decode(tc->encoded, strlen(tc->encoded), buffer, &bsize))) return 0; for (i = 0; i < OSSL_NELEM(tc->raw); i++) if (tc->raw[i] == 0) break; if (!TEST_mem_eq(buffer, bsize * sizeof(*buffer), tc->raw, i * sizeof(*tc->raw))) return 0; return 1; } static const struct bad_decode_test { size_t outlen; const char input[20]; } bad_decode_tests[] = { { 20, "xn--e-*" }, /* bad digit '*' */ { 10, "xn--e-999" }, /* loop > enc_len */ { 20, "xn--e-999999999" }, /* Too big */ { 20, {'x', 'n', '-', '-', (char)0x80, '-' } }, /* Not basic */ { 20, "xn--e-Oy65t" }, /* codepoint > 0x10FFFF */ }; static int test_a2ulabel_bad_decode(int tst) { char out[20]; return TEST_int_eq(ossl_a2ulabel(bad_decode_tests[tst].input, out, bad_decode_tests[tst].outlen), -1); } static int test_a2ulabel(void) { char out[50]; char in[530] = { 0 }; /* * The punycode being passed in and parsed is malformed but we're not * verifying that behaviour here. */ if (!TEST_int_eq(ossl_a2ulabel("xn--a.b.c", out, 1), 0) || !TEST_int_eq(ossl_a2ulabel("xn--a.b.c", out, 7), 1)) return 0; /* Test for an off by one on the buffer size works */ if (!TEST_int_eq(ossl_a2ulabel("xn--a.b.c", out, 6), 0) || !TEST_int_eq(ossl_a2ulabel("xn--a.b.c", out, 7), 1) || !TEST_str_eq(out,"\xc2\x80.b.c")) return 0; /* Test 4 byte smiley face */ if (!TEST_int_eq(ossl_a2ulabel("xn--e28h.com", out, 10), 1)) return 0; /* Test that we dont overflow the fixed internal buffer of 512 bytes when the starting bytes are copied */ strcpy(in, "xn--"); memset(in + 4, 'e', 513); memcpy(in + 517, "-3ya", 4); if (!TEST_int_eq(ossl_a2ulabel(in, out, 50), -1)) return 0; return 1; } static int test_puny_overrun(void) { static const unsigned int out[] = { 0x0033, 0x5E74, 0x0042, 0x7D44, 0x91D1, 0x516B, 0x5148, 0x751F }; static const char *in = "3B-ww4c5e180e575a65lsy2b"; unsigned int buf[OSSL_NELEM(out)]; unsigned int bsize = OSSL_NELEM(buf) - 1; if (!TEST_false(ossl_punycode_decode(in, strlen(in), buf, &bsize))) { if (TEST_mem_eq(buf, bsize * sizeof(*buf), out, sizeof(out))) TEST_error("CRITICAL: buffer overrun detected!"); return 0; } return 1; } static int test_dotted_overflow(void) { static const char string[] = "a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a"; const size_t num_reps = OSSL_NELEM(string) / 2; WPACKET p; BUF_MEM *in; char *out = NULL; size_t i; int res = 0; /* Create out input punycode string */ if (!TEST_ptr(in = BUF_MEM_new())) return 0; if (!TEST_true(WPACKET_init_len(&p, in, 0))) { BUF_MEM_free(in); return 0; } for (i = 0; i < num_reps; i++) { if (i > 1 && !TEST_true(WPACKET_put_bytes_u8(&p, '.'))) goto err; if (!TEST_true(WPACKET_memcpy(&p, "xn--a", sizeof("xn--a") - 1))) goto err; } if (!TEST_true(WPACKET_put_bytes_u8(&p, '\0'))) goto err; if (!TEST_ptr(out = OPENSSL_malloc(in->length))) goto err; /* Test the decode into an undersized buffer */ memset(out, 0x7f, in->length - 1); if (!TEST_int_le(ossl_a2ulabel(in->data, out, num_reps), 0) || !TEST_int_eq(out[num_reps], 0x7f)) goto err; /* Test the decode works into a full size buffer */ if (!TEST_int_gt(ossl_a2ulabel(in->data, out, in->length), 0) || !TEST_size_t_eq(strlen(out), num_reps * 3)) goto err; res = 1; err: WPACKET_cleanup(&p); BUF_MEM_free(in); OPENSSL_free(out); return res; } int setup_tests(void) { ADD_ALL_TESTS(test_punycode, OSSL_NELEM(puny_cases)); ADD_TEST(test_dotted_overflow); ADD_TEST(test_a2ulabel); ADD_TEST(test_puny_overrun); ADD_ALL_TESTS(test_a2ulabel_bad_decode, OSSL_NELEM(bad_decode_tests)); return 1; }
10,249
33.745763
110
c
openssl
openssl-master/test/quic_cc_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 */ /* For generating debug statistics during congestion controller development. */ /*#define GENERATE_LOG*/ #include "testutil.h" #include <openssl/ssl.h> #include "internal/quic_cc.h" #include "internal/priority_queue.h" /* * Time Simulation * =============== */ static OSSL_TIME fake_time = {0}; #define TIME_BASE (ossl_ticks2time(5 * OSSL_TIME_SECOND)) static OSSL_TIME fake_now(void *arg) { return fake_time; } static void step_time(uint32_t ms) { fake_time = ossl_time_add(fake_time, ossl_ms2time(ms)); } /* * Network Simulation * ================== * * This is a simple 'network simulator' which emulates a network with a certain * bandwidth and latency. Sending a packet into the network causes it to consume * some capacity of the network until the packet exits the network. Note that * the capacity is not known to the congestion controller as the entire point of * a congestion controller is to correctly estimate this capacity and this is * what we are testing. The network simulator does take care of informing the * congestion controller of ack/loss events automatically but the caller is * responsible for querying the congestion controller and choosing the size of * simulated transmitted packets. */ typedef struct net_pkt_st { /* * The time at which the packet was sent. */ OSSL_TIME tx_time; /* * The time at which the simulated packet arrives at the RX side (success) * or is dropped (!success). */ OSSL_TIME arrive_time; /* * The time at which the transmitting side makes a determination of * acknowledgement (if success) or loss (if !success). */ OSSL_TIME determination_time; /* * Current earliest time there is something to be done for this packet. * min(arrive_time, determination_time). */ OSSL_TIME next_time; /* 1 if the packet will be successfully delivered, 0 if it is to be lost. */ int success; /* 1 if we have already processed packet arrival. */ int arrived; /* Size of simulated packet in bytes. */ size_t size; /* pqueue internal index. */ size_t idx; } NET_PKT; DEFINE_PRIORITY_QUEUE_OF(NET_PKT); static int net_pkt_cmp(const NET_PKT *a, const NET_PKT *b) { return ossl_time_compare(a->next_time, b->next_time); } struct net_sim { const OSSL_CC_METHOD *ccm; OSSL_CC_DATA *cc; uint64_t capacity; /* bytes/s */ uint64_t latency; /* ms */ uint64_t spare_capacity; PRIORITY_QUEUE_OF(NET_PKT) *pkts; uint64_t total_acked, total_lost; /* bytes */ }; static int net_sim_init(struct net_sim *s, const OSSL_CC_METHOD *ccm, OSSL_CC_DATA *cc, uint64_t capacity, uint64_t latency) { s->ccm = ccm; s->cc = cc; s->capacity = capacity; s->latency = latency; s->spare_capacity = capacity; s->total_acked = 0; s->total_lost = 0; if (!TEST_ptr(s->pkts = ossl_pqueue_NET_PKT_new(net_pkt_cmp))) return 0; return 1; } static void do_free(NET_PKT *pkt) { OPENSSL_free(pkt); } static void net_sim_cleanup(struct net_sim *s) { ossl_pqueue_NET_PKT_pop_free(s->pkts, do_free); } static int net_sim_process(struct net_sim *s, size_t skip_forward); static int net_sim_send(struct net_sim *s, size_t sz) { NET_PKT *pkt = OPENSSL_zalloc(sizeof(*pkt)); int success; if (!TEST_ptr(pkt)) return 0; /* * Ensure we have processed any events which have come due as these might * increase our spare capacity. */ if (!TEST_true(net_sim_process(s, 0))) return 0; /* Do we have room for the packet in the network? */ success = (sz <= s->spare_capacity); pkt->tx_time = fake_time; pkt->success = success; if (success) { /* This packet will arrive successfully after |latency| time. */ pkt->arrive_time = ossl_time_add(pkt->tx_time, ossl_ms2time(s->latency)); /* Assume all received packets are acknowledged immediately. */ pkt->determination_time = ossl_time_add(pkt->arrive_time, ossl_ms2time(s->latency)); pkt->next_time = pkt->arrive_time; s->spare_capacity -= sz; } else { /* * In our network model, assume all packets are dropped due to a * bottleneck at the peer's NIC RX queue; thus dropping occurs after * |latency|. */ pkt->arrive_time = ossl_time_add(pkt->tx_time, ossl_ms2time(s->latency)); /* * It will take longer to detect loss than to detect acknowledgement. */ pkt->determination_time = ossl_time_add(pkt->tx_time, ossl_ms2time(3 * s->latency)); pkt->next_time = pkt->determination_time; } pkt->size = sz; if (!TEST_true(s->ccm->on_data_sent(s->cc, sz))) return 0; if (!TEST_true(ossl_pqueue_NET_PKT_push(s->pkts, pkt, &pkt->idx))) return 0; return 1; } static int net_sim_process_one(struct net_sim *s, int skip_forward) { NET_PKT *pkt = ossl_pqueue_NET_PKT_peek(s->pkts); if (pkt == NULL) return 3; /* Jump forward to the next significant point in time. */ if (skip_forward && ossl_time_compare(pkt->next_time, fake_time) > 0) fake_time = pkt->next_time; if (pkt->success && !pkt->arrived && ossl_time_compare(fake_time, pkt->arrive_time) >= 0) { /* Packet arrives */ s->spare_capacity += pkt->size; pkt->arrived = 1; ossl_pqueue_NET_PKT_pop(s->pkts); pkt->next_time = pkt->determination_time; if (!ossl_pqueue_NET_PKT_push(s->pkts, pkt, &pkt->idx)) return 0; return 1; } if (ossl_time_compare(fake_time, pkt->determination_time) < 0) return 2; if (!TEST_true(!pkt->success || pkt->arrived)) return 0; if (!pkt->success) { OSSL_CC_LOSS_INFO loss_info = {0}; loss_info.tx_time = pkt->tx_time; loss_info.tx_size = pkt->size; if (!TEST_true(s->ccm->on_data_lost(s->cc, &loss_info))) return 0; if (!TEST_true(s->ccm->on_data_lost_finished(s->cc, 0))) return 0; s->total_lost += pkt->size; ossl_pqueue_NET_PKT_pop(s->pkts); OPENSSL_free(pkt); } else { OSSL_CC_ACK_INFO ack_info = {0}; ack_info.tx_time = pkt->tx_time; ack_info.tx_size = pkt->size; if (!TEST_true(s->ccm->on_data_acked(s->cc, &ack_info))) return 0; s->total_acked += pkt->size; ossl_pqueue_NET_PKT_pop(s->pkts); OPENSSL_free(pkt); } return 1; } static int net_sim_process(struct net_sim *s, size_t skip_forward) { int rc; while ((rc = net_sim_process_one(s, skip_forward > 0 ? 1 : 0)) == 1) if (skip_forward > 0) --skip_forward; return rc; } /* * State Dumping Utilities * ======================= * * Utilities for outputting CC state information. */ #ifdef GENERATE_LOG static FILE *logfile; #endif static int dump_state(const OSSL_CC_METHOD *ccm, OSSL_CC_DATA *cc, struct net_sim *s) { #ifdef GENERATE_LOG uint64_t cwnd_size, cur_bytes, state; if (logfile == NULL) return 1; if (!TEST_true(ccm->get_option_uint(cc, OSSL_CC_OPTION_CUR_CWND_SIZE, &cwnd_size))) return 0; if (!TEST_true(ccm->get_option_uint(cc, OSSL_CC_OPTION_CUR_BYTES_IN_FLIGHT, &cur_bytes))) return 0; if (!TEST_true(ccm->get_option_uint(cc, OSSL_CC_OPTION_CUR_STATE, &state))) return 0; fprintf(logfile, "%10lu,%10lu,%10lu,%10lu,%10lu,%10lu,%10lu,%10lu,\"%c\"\n", ossl_time2ms(fake_time), ccm->get_tx_allowance(cc), cwnd_size, cur_bytes, s->total_acked, s->total_lost, s->capacity, s->spare_capacity, (char)state); #endif return 1; } /* * Simulation Test * =============== * * Simulator-based unit test in which we simulate a network with a certain * capacity. The average estimated channel capacity should not be too far from * the actual channel capacity. */ static int test_simulate(void) { int testresult = 0; int rc; int have_sim = 0; const OSSL_CC_METHOD *ccm = &ossl_cc_newreno_method; OSSL_CC_DATA *cc = NULL; size_t mdpl = 1472; uint64_t total_sent = 0, total_to_send, allowance; uint64_t actual_capacity = 16000; /* B/s - 128kb/s */ uint64_t cwnd_sample_sum = 0, cwnd_sample_count = 0; uint64_t diag_cur_bytes_in_flight = UINT64_MAX; uint64_t diag_cur_cwnd_size = UINT64_MAX; struct net_sim sim; OSSL_PARAM params[3], *p = params; fake_time = TIME_BASE; if (!TEST_ptr(cc = ccm->new(fake_now, NULL))) goto err; if (!TEST_true(net_sim_init(&sim, ccm, cc, actual_capacity, 100))) goto err; have_sim = 1; *p++ = OSSL_PARAM_construct_size_t(OSSL_CC_OPTION_MAX_DGRAM_PAYLOAD_LEN, &mdpl); *p++ = OSSL_PARAM_construct_end(); if (!TEST_true(ccm->set_input_params(cc, params))) goto err; p = params; *p++ = OSSL_PARAM_construct_uint64(OSSL_CC_OPTION_CUR_BYTES_IN_FLIGHT, &diag_cur_bytes_in_flight); *p++ = OSSL_PARAM_construct_uint64(OSSL_CC_OPTION_CUR_CWND_SIZE, &diag_cur_cwnd_size); *p++ = OSSL_PARAM_construct_end(); if (!TEST_true(ccm->bind_diagnostics(cc, params))) goto err; ccm->reset(cc); if (!TEST_uint64_t_ge(allowance = ccm->get_tx_allowance(cc), mdpl)) goto err; /* * Start generating traffic. Stop when we've sent 30 MiB. */ total_to_send = 30 * 1024 * 1024; while (total_sent < total_to_send) { /* * Assume we are bottlenecked by the network (which is the interesting * case for testing a congestion controller) and always fill our entire * TX allowance as and when it becomes available. */ for (;;) { uint64_t sz; dump_state(ccm, cc, &sim); allowance = ccm->get_tx_allowance(cc); sz = allowance > mdpl ? mdpl : allowance; if (sz > SIZE_MAX) sz = SIZE_MAX; /* * QUIC minimum packet sizes, etc. mean that in practice we will not * consume the allowance exactly, so only send above a certain size. */ if (sz < 30) break; step_time(7); if (!TEST_true(net_sim_send(&sim, (size_t)sz))) goto err; total_sent += sz; } /* Skip to next event. */ rc = net_sim_process(&sim, 1); if (!TEST_int_gt(rc, 0)) goto err; /* * If we are out of any events to handle at all we definitely should * have at least one MDPL's worth of allowance as nothing is in flight. */ if (rc == 3) { if (!TEST_uint64_t_eq(diag_cur_bytes_in_flight, 0)) goto err; if (!TEST_uint64_t_ge(ccm->get_tx_allowance(cc), mdpl)) goto err; } /* Update our average of the estimated channel capacity. */ { uint64_t v = 1; if (!TEST_uint64_t_ne(diag_cur_bytes_in_flight, UINT64_MAX) || !TEST_uint64_t_ne(diag_cur_cwnd_size, UINT64_MAX)) goto err; cwnd_sample_sum += v; ++cwnd_sample_count; } } /* * Ensure estimated channel capacity is not too far off from actual channel * capacity. */ { uint64_t estimated_capacity = cwnd_sample_sum / cwnd_sample_count; double error = ((double)estimated_capacity / (double)actual_capacity) - 1.0; TEST_info("est = %6llu kB/s, act=%6llu kB/s (error=%.02f%%)\n", (unsigned long long)estimated_capacity, (unsigned long long)actual_capacity, error * 100.0); /* Max 5% error */ if (!TEST_double_le(error, 0.05)) goto err; } testresult = 1; err: if (have_sim) net_sim_cleanup(&sim); if (cc != NULL) ccm->free(cc); #ifdef GENERATE_LOG if (logfile != NULL) fflush(logfile); #endif return testresult; } /* * Sanity Test * =========== * * Basic test of the congestion control APIs. */ static int test_sanity(void) { int testresult = 0; OSSL_CC_DATA *cc = NULL; const OSSL_CC_METHOD *ccm = &ossl_cc_newreno_method; OSSL_CC_LOSS_INFO loss_info = {0}; OSSL_CC_ACK_INFO ack_info = {0}; uint64_t allowance, allowance2; OSSL_PARAM params[3], *p = params; size_t mdpl = 1472, diag_mdpl = SIZE_MAX; uint64_t diag_cur_bytes_in_flight = UINT64_MAX; fake_time = TIME_BASE; if (!TEST_ptr(cc = ccm->new(fake_now, NULL))) goto err; /* Test configuration of options. */ *p++ = OSSL_PARAM_construct_size_t(OSSL_CC_OPTION_MAX_DGRAM_PAYLOAD_LEN, &mdpl); *p++ = OSSL_PARAM_construct_end(); if (!TEST_true(ccm->set_input_params(cc, params))) goto err; ccm->reset(cc); p = params; *p++ = OSSL_PARAM_construct_size_t(OSSL_CC_OPTION_MAX_DGRAM_PAYLOAD_LEN, &diag_mdpl); *p++ = OSSL_PARAM_construct_uint64(OSSL_CC_OPTION_CUR_BYTES_IN_FLIGHT, &diag_cur_bytes_in_flight); *p++ = OSSL_PARAM_construct_end(); if (!TEST_true(ccm->bind_diagnostics(cc, params)) || !TEST_size_t_eq(diag_mdpl, 1472)) goto err; if (!TEST_uint64_t_ge(allowance = ccm->get_tx_allowance(cc), 1472)) goto err; /* There is TX allowance so wakeup should be immediate */ if (!TEST_true(ossl_time_is_zero(ccm->get_wakeup_deadline(cc)))) goto err; /* No bytes should currently be in flight. */ if (!TEST_uint64_t_eq(diag_cur_bytes_in_flight, 0)) goto err; /* Tell the CC we have sent some data. */ if (!TEST_true(ccm->on_data_sent(cc, 1200))) goto err; /* Allowance should have decreased. */ if (!TEST_uint64_t_eq(ccm->get_tx_allowance(cc), allowance - 1200)) goto err; /* Acknowledge the data. */ ack_info.tx_time = fake_time; ack_info.tx_size = 1200; step_time(100); if (!TEST_true(ccm->on_data_acked(cc, &ack_info))) goto err; /* Allowance should have returned. */ if (!TEST_uint64_t_ge(allowance2 = ccm->get_tx_allowance(cc), allowance)) goto err; /* Test invalidation. */ if (!TEST_true(ccm->on_data_sent(cc, 1200))) goto err; /* Allowance should have decreased. */ if (!TEST_uint64_t_eq(ccm->get_tx_allowance(cc), allowance - 1200)) goto err; if (!TEST_true(ccm->on_data_invalidated(cc, 1200))) goto err; /* Allowance should have returned. */ if (!TEST_uint64_t_eq(ccm->get_tx_allowance(cc), allowance2)) goto err; /* Test loss. */ if (!TEST_uint64_t_ge(allowance = ccm->get_tx_allowance(cc), 1200 + 1300)) goto err; if (!TEST_true(ccm->on_data_sent(cc, 1200))) goto err; if (!TEST_true(ccm->on_data_sent(cc, 1300))) goto err; if (!TEST_uint64_t_eq(allowance2 = ccm->get_tx_allowance(cc), allowance - 1200 - 1300)) goto err; loss_info.tx_time = fake_time; loss_info.tx_size = 1200; step_time(100); if (!TEST_true(ccm->on_data_lost(cc, &loss_info))) goto err; loss_info.tx_size = 1300; if (!TEST_true(ccm->on_data_lost(cc, &loss_info))) goto err; if (!TEST_true(ccm->on_data_lost_finished(cc, 0))) goto err; /* Allowance should have changed due to the lost calls */ if (!TEST_uint64_t_ne(ccm->get_tx_allowance(cc), allowance2)) goto err; /* But it should not be as high as the original value */ if (!TEST_uint64_t_lt(ccm->get_tx_allowance(cc), allowance)) goto err; testresult = 1; err: if (cc != NULL) ccm->free(cc); return testresult; } int setup_tests(void) { #ifdef GENERATE_LOG logfile = fopen("quic_cc_stats.csv", "w"); fprintf(logfile, "\"Time\"," "\"TX Allowance\"," "\"CWND Size\"," "\"Bytes in Flight\"," "\"Total Acked\",\"Total Lost\"," "\"Capacity\",\"Spare Capacity\"," "\"State\"\n"); #endif ADD_TEST(test_simulate); ADD_TEST(test_sanity); return 1; }
17,400
26.797125
84
c
openssl
openssl-master/test/quic_cfq_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/packet.h" #include "internal/quic_cfq.h" #include "internal/quic_wire.h" #include "testutil.h" static const unsigned char ref_buf[] = { 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19 }; static const uint32_t ref_priority[] = { 90, 80, 70, 60, 95, 40, 94, 20, 10, 0 }; static const uint32_t ref_pn_space[] = { QUIC_PN_SPACE_INITIAL, QUIC_PN_SPACE_HANDSHAKE, QUIC_PN_SPACE_HANDSHAKE, QUIC_PN_SPACE_INITIAL, QUIC_PN_SPACE_INITIAL, QUIC_PN_SPACE_INITIAL, QUIC_PN_SPACE_INITIAL, QUIC_PN_SPACE_INITIAL, QUIC_PN_SPACE_APP, QUIC_PN_SPACE_APP, }; static const uint64_t ref_frame_type[] = { OSSL_QUIC_FRAME_TYPE_NEW_CONN_ID, OSSL_QUIC_FRAME_TYPE_NEW_CONN_ID, OSSL_QUIC_FRAME_TYPE_NEW_CONN_ID, OSSL_QUIC_FRAME_TYPE_NEW_CONN_ID, OSSL_QUIC_FRAME_TYPE_NEW_CONN_ID, OSSL_QUIC_FRAME_TYPE_NEW_CONN_ID, OSSL_QUIC_FRAME_TYPE_NEW_CONN_ID, OSSL_QUIC_FRAME_TYPE_NEW_CONN_ID, OSSL_QUIC_FRAME_TYPE_NEW_CONN_ID, OSSL_QUIC_FRAME_TYPE_RETIRE_CONN_ID, }; static const uint32_t expect[QUIC_PN_SPACE_NUM][11] = { { 4, 6, 0, 3, 5, 7, UINT32_MAX }, { 1, 2, UINT32_MAX }, { 8, 9, UINT32_MAX }, }; static QUIC_CFQ_ITEM *items[QUIC_PN_SPACE_NUM][10]; static unsigned char *g_free; static size_t g_free_len; static void free_cb(unsigned char *buf, size_t buf_len, void *arg) { g_free = buf; g_free_len = buf_len; } static int check(QUIC_CFQ *cfq) { int testresult = 0; QUIC_CFQ_ITEM *item; size_t i; uint32_t pn_space; for (pn_space = QUIC_PN_SPACE_INITIAL; pn_space < QUIC_PN_SPACE_NUM; ++pn_space) for (i = 0, item = ossl_quic_cfq_get_priority_head(cfq, pn_space);; ++i, item = ossl_quic_cfq_item_get_priority_next(item, pn_space)) { if (expect[pn_space][i] == UINT32_MAX) { if (!TEST_ptr_null(item)) goto err; break; } items[pn_space][i] = item; if (!TEST_ptr(item) || !TEST_ptr_eq(ossl_quic_cfq_item_get_encoded(item), ref_buf + expect[pn_space][i]) || !TEST_int_eq(ossl_quic_cfq_item_get_pn_space(item), pn_space) || !TEST_int_eq(ossl_quic_cfq_item_get_state(item), QUIC_CFQ_STATE_NEW)) goto err; } testresult = 1; err: return testresult; } static int test_cfq(void) { int testresult = 0; QUIC_CFQ *cfq = NULL; QUIC_CFQ_ITEM *item, *inext; size_t i; uint32_t pn_space; if (!TEST_ptr(cfq = ossl_quic_cfq_new())) goto err; g_free = NULL; g_free_len = 0; for (i = 0; i < OSSL_NELEM(ref_buf); ++i) { if (!TEST_ptr(item = ossl_quic_cfq_add_frame(cfq, ref_priority[i], ref_pn_space[i], ref_frame_type[i], ref_buf + i, 1, free_cb, NULL)) || !TEST_int_eq(ossl_quic_cfq_item_get_state(item), QUIC_CFQ_STATE_NEW) || !TEST_uint_eq(ossl_quic_cfq_item_get_pn_space(item), ref_pn_space[i]) || !TEST_uint64_t_eq(ossl_quic_cfq_item_get_frame_type(item), ref_frame_type[i]) || !TEST_ptr_eq(ossl_quic_cfq_item_get_encoded(item), ref_buf + i) || !TEST_size_t_eq(ossl_quic_cfq_item_get_encoded_len(item), 1)) goto err; } if (!check(cfq)) goto err; for (pn_space = QUIC_PN_SPACE_INITIAL; pn_space < QUIC_PN_SPACE_NUM; ++pn_space) for (item = ossl_quic_cfq_get_priority_head(cfq, pn_space); item != NULL; item = inext) { inext = ossl_quic_cfq_item_get_priority_next(item, pn_space); ossl_quic_cfq_mark_tx(cfq, item); } for (pn_space = QUIC_PN_SPACE_INITIAL; pn_space < QUIC_PN_SPACE_NUM; ++pn_space) if (!TEST_ptr_null(ossl_quic_cfq_get_priority_head(cfq, pn_space))) goto err; for (pn_space = QUIC_PN_SPACE_INITIAL; pn_space < QUIC_PN_SPACE_NUM; ++pn_space) for (i = 0; i < OSSL_NELEM(items[0]); ++i) if (items[pn_space][i] != NULL) ossl_quic_cfq_mark_lost(cfq, items[pn_space][i], UINT32_MAX); if (!check(cfq)) goto err; for (pn_space = QUIC_PN_SPACE_INITIAL; pn_space < QUIC_PN_SPACE_NUM; ++pn_space) for (i = 0; i < OSSL_NELEM(items[0]); ++i) if (items[pn_space][i] != NULL) ossl_quic_cfq_release(cfq, items[pn_space][i]); for (pn_space = QUIC_PN_SPACE_INITIAL; pn_space < QUIC_PN_SPACE_NUM; ++pn_space) if (!TEST_ptr_null(ossl_quic_cfq_get_priority_head(cfq, pn_space))) goto err; testresult = 1; err: ossl_quic_cfq_free(cfq); return testresult; } int setup_tests(void) { ADD_TEST(test_cfq); return 1; }
5,577
30.337079
84
c
openssl
openssl-master/test/quic_client_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 <stdio.h> #include <openssl/ssl.h> #include <openssl/quic.h> #include <openssl/bio.h> #include "internal/common.h" #include "internal/sockets.h" #include "internal/time.h" #include "testutil.h" static const char msg1[] = "GET LICENSE.txt\r\n"; static char msg2[16000]; static int is_want(SSL *s, int ret) { int ec = SSL_get_error(s, ret); return ec == SSL_ERROR_WANT_READ || ec == SSL_ERROR_WANT_WRITE; } static int test_quic_client(void) { int testresult = 0, ret; int c_fd = INVALID_SOCKET; BIO *c_net_bio = NULL, *c_net_bio_own = NULL; BIO_ADDR *s_addr_ = NULL; struct in_addr ina = {0}; SSL_CTX *c_ctx = NULL; SSL *c_ssl = NULL; short port = 4433; int c_connected = 0, c_write_done = 0, c_shutdown = 0; size_t l = 0, c_total_read = 0; OSSL_TIME start_time; unsigned char alpn[] = { 8, 'h', 't', 't', 'p', '/', '0', '.', '9' }; ina.s_addr = htonl(0x7f000001UL); /* Setup test client. */ c_fd = BIO_socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP, 0); if (!TEST_int_ne(c_fd, INVALID_SOCKET)) goto err; if (!TEST_true(BIO_socket_nbio(c_fd, 1))) goto err; if (!TEST_ptr(s_addr_ = BIO_ADDR_new())) goto err; if (!TEST_true(BIO_ADDR_rawmake(s_addr_, AF_INET, &ina, sizeof(ina), htons(port)))) goto err; if (!TEST_ptr(c_net_bio = c_net_bio_own = BIO_new_dgram(c_fd, 0))) goto err; if (!BIO_dgram_set_peer(c_net_bio, s_addr_)) goto err; if (!TEST_ptr(c_ctx = SSL_CTX_new(OSSL_QUIC_client_method()))) goto err; if (!TEST_ptr(c_ssl = SSL_new(c_ctx))) goto err; /* 0 is a success for SSL_set_alpn_protos() */ if (!TEST_false(SSL_set_alpn_protos(c_ssl, alpn, sizeof(alpn)))) goto err; /* Takes ownership of our reference to the BIO. */ SSL_set0_rbio(c_ssl, c_net_bio); /* Get another reference to be transferred in the SSL_set0_wbio call. */ if (!TEST_true(BIO_up_ref(c_net_bio))) { c_net_bio_own = NULL; /* SSL_free will free the first reference. */ goto err; } SSL_set0_wbio(c_ssl, c_net_bio); c_net_bio_own = NULL; if (!TEST_true(SSL_set_blocking_mode(c_ssl, 0))) goto err; start_time = ossl_time_now(); for (;;) { if (ossl_time_compare(ossl_time_subtract(ossl_time_now(), start_time), ossl_ms2time(3000)) >= 0) { TEST_error("timeout while attempting QUIC client test"); goto err; } if (!c_connected) { ret = SSL_connect(c_ssl); if (!TEST_true(ret == 1 || is_want(c_ssl, ret))) goto err; if (ret == 1) { c_connected = 1; TEST_info("Connected!"); } } if (c_connected && !c_write_done) { if (!TEST_int_eq(SSL_write(c_ssl, msg1, sizeof(msg1) - 1), (int)sizeof(msg1) - 1)) goto err; if (!TEST_true(SSL_stream_conclude(c_ssl, 0))) goto err; c_write_done = 1; } if (c_write_done && !c_shutdown && c_total_read < sizeof(msg2) - 1) { ret = SSL_read_ex(c_ssl, msg2 + c_total_read, sizeof(msg2) - 1 - c_total_read, &l); if (ret != 1) { if (SSL_get_error(c_ssl, ret) == SSL_ERROR_ZERO_RETURN) { c_shutdown = 1; TEST_info("Message: \n%s\n", msg2); } else if (!TEST_true(is_want(c_ssl, ret))) { goto err; } } else { c_total_read += l; if (!TEST_size_t_lt(c_total_read, sizeof(msg2) - 1)) goto err; } } if (c_shutdown) { ret = SSL_shutdown(c_ssl); if (ret == 1) break; } /* * This is inefficient because we spin until things work without * blocking but this is just a test. */ OSSL_sleep(0); SSL_handle_events(c_ssl); } testresult = 1; err: SSL_free(c_ssl); SSL_CTX_free(c_ctx); BIO_ADDR_free(s_addr_); BIO_free(c_net_bio_own); if (c_fd != INVALID_SOCKET) BIO_closesocket(c_fd); return testresult; } 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; } ADD_TEST(test_quic_client); return 1; }
4,958
27.016949
78
c
openssl
openssl-master/test/quic_fc_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/quic_fc.h" #include "internal/quic_error.h" #include "testutil.h" static int test_txfc(int is_stream) { int testresult = 0; QUIC_TXFC conn_txfc, stream_txfc, *txfc, *parent_txfc; if (!TEST_true(ossl_quic_txfc_init(&conn_txfc, 0))) goto err; if (is_stream && !TEST_true(ossl_quic_txfc_init(&stream_txfc, &conn_txfc))) goto err; txfc = is_stream ? &stream_txfc : &conn_txfc; parent_txfc = is_stream ? &conn_txfc : NULL; if (!TEST_true(ossl_quic_txfc_bump_cwm(txfc, 2000))) goto err; if (is_stream && !TEST_true(ossl_quic_txfc_bump_cwm(parent_txfc, 2000))) goto err; if (!TEST_uint64_t_eq(ossl_quic_txfc_get_swm(txfc), 0)) goto err; if (!TEST_uint64_t_eq(ossl_quic_txfc_get_cwm(txfc), 2000)) goto err; if (!TEST_uint64_t_eq(ossl_quic_txfc_get_credit_local(txfc), 2000)) goto err; if (is_stream && !TEST_uint64_t_eq(ossl_quic_txfc_get_credit(txfc), 2000)) goto err; if (!TEST_false(ossl_quic_txfc_has_become_blocked(txfc, 0))) goto err; if (!TEST_true(ossl_quic_txfc_consume_credit(txfc, 500))) goto err; if (!TEST_uint64_t_eq(ossl_quic_txfc_get_credit_local(txfc), 1500)) goto err; if (is_stream && !TEST_uint64_t_eq(ossl_quic_txfc_get_credit(txfc), 1500)) goto err; if (!TEST_false(ossl_quic_txfc_has_become_blocked(txfc, 0))) goto err; if (!TEST_uint64_t_eq(ossl_quic_txfc_get_swm(txfc), 500)) goto err; if (!TEST_true(ossl_quic_txfc_consume_credit(txfc, 100))) goto err; if (!TEST_uint64_t_eq(ossl_quic_txfc_get_swm(txfc), 600)) goto err; if (!TEST_uint64_t_eq(ossl_quic_txfc_get_credit_local(txfc), 1400)) goto err; if (is_stream && !TEST_uint64_t_eq(ossl_quic_txfc_get_credit(txfc), 1400)) goto err; if (!TEST_false(ossl_quic_txfc_has_become_blocked(txfc, 0))) goto err; if (!TEST_true(ossl_quic_txfc_consume_credit(txfc, 1400))) goto err; if (!TEST_uint64_t_eq(ossl_quic_txfc_get_credit_local(txfc), 0)) goto err; if (is_stream && !TEST_uint64_t_eq(ossl_quic_txfc_get_credit(txfc), 0)) goto err; if (!TEST_uint64_t_eq(ossl_quic_txfc_get_swm(txfc), 2000)) goto err; if (!TEST_true(ossl_quic_txfc_has_become_blocked(txfc, 0))) goto err; if (!TEST_true(ossl_quic_txfc_has_become_blocked(txfc, 0))) goto err; if (!TEST_true(ossl_quic_txfc_has_become_blocked(txfc, 1))) goto err; if (!TEST_false(ossl_quic_txfc_has_become_blocked(txfc, 0))) goto err; if (!TEST_false(ossl_quic_txfc_has_become_blocked(txfc, 0))) goto err; if (!TEST_false(ossl_quic_txfc_consume_credit(txfc, 1))) goto err; if (!TEST_uint64_t_eq(ossl_quic_txfc_get_cwm(txfc), 2000)) goto err; if (!TEST_uint64_t_eq(ossl_quic_txfc_get_swm(txfc), 2000)) goto err; if (!TEST_false(ossl_quic_txfc_bump_cwm(txfc, 2000))) goto err; if (!TEST_true(ossl_quic_txfc_bump_cwm(txfc, 2500))) goto err; if (is_stream && !TEST_true(ossl_quic_txfc_bump_cwm(parent_txfc, 2400))) goto err; if (!TEST_uint64_t_eq(ossl_quic_txfc_get_cwm(txfc), 2500)) goto err; if (!TEST_uint64_t_eq(ossl_quic_txfc_get_swm(txfc), 2000)) goto err; if (!TEST_uint64_t_eq(ossl_quic_txfc_get_credit_local(txfc), 500)) goto err; if (is_stream) ossl_quic_txfc_has_become_blocked(parent_txfc, 1); if (is_stream) { if (!TEST_true(ossl_quic_txfc_consume_credit(txfc, 399))) goto err; if (!TEST_false(ossl_quic_txfc_has_become_blocked(txfc, 0))) goto err; if (!TEST_uint64_t_eq(ossl_quic_txfc_get_credit(txfc), 1)) goto err; if (!TEST_true(ossl_quic_txfc_consume_credit(txfc, 1))) goto err; if (!TEST_true(ossl_quic_txfc_has_become_blocked(parent_txfc, 0))) goto err; if (!TEST_true(ossl_quic_txfc_has_become_blocked(parent_txfc, 1))) goto err; if (!TEST_false(ossl_quic_txfc_has_become_blocked(parent_txfc, 0))) goto err; } else { if (!TEST_true(ossl_quic_txfc_consume_credit(txfc, 499))) goto err; if (!TEST_false(ossl_quic_txfc_has_become_blocked(txfc, 0))) goto err; if (is_stream && !TEST_false(ossl_quic_txfc_has_become_blocked(parent_txfc, 0))) goto err; if (!TEST_true(ossl_quic_txfc_consume_credit(txfc, 1))) goto err; if (!TEST_true(ossl_quic_txfc_has_become_blocked(txfc, 0))) goto err; if (!TEST_true(ossl_quic_txfc_has_become_blocked(txfc, 1))) goto err; if (!TEST_false(ossl_quic_txfc_has_become_blocked(txfc, 0))) goto err; } testresult = 1; err: return testresult; } static OSSL_TIME cur_time; static OSSL_TIME fake_now(void *arg) { return cur_time; } #define RX_OPC_END 0 #define RX_OPC_INIT_CONN 1 /* arg0=initial window, arg1=max window */ #define RX_OPC_INIT_STREAM 2 /* arg0=initial window, arg1=max window */ #define RX_OPC_RX 3 /* arg0=end, arg1=is_fin */ #define RX_OPC_RETIRE 4 /* arg0=num_bytes, arg1=rtt in OSSL_TIME ticks, expect_fail */ #define RX_OPC_CHECK_CWM_CONN 5 /* arg0=expected */ #define RX_OPC_CHECK_CWM_STREAM 6 /* arg0=expected */ #define RX_OPC_CHECK_SWM_CONN 7 /* arg0=expected */ #define RX_OPC_CHECK_SWM_STREAM 8 /* arg0=expected */ #define RX_OPC_CHECK_RWM_CONN 9 /* arg0=expected */ #define RX_OPC_CHECK_RWM_STREAM 10 /* arg0=expected */ #define RX_OPC_CHECK_CHANGED_CONN 11 /* arg0=expected, arg1=clear */ #define RX_OPC_CHECK_CHANGED_STREAM 12 /* arg0=expected, arg1=clear */ #define RX_OPC_CHECK_ERROR_CONN 13 /* arg0=expected, arg1=clear */ #define RX_OPC_CHECK_ERROR_STREAM 14 /* arg0=expected, arg1=clear */ #define RX_OPC_STEP_TIME 15 /* arg0=OSSL_TIME ticks to advance */ #define RX_OPC_MSG 16 struct rx_test_op { unsigned char op; size_t stream_idx; uint64_t arg0, arg1; unsigned char expect_fail; const char *msg; }; #define RX_OP_END \ { RX_OPC_END } #define RX_OP_INIT_CONN(init_window_size, max_window_size) \ { RX_OPC_INIT_CONN, 0, (init_window_size), (max_window_size) }, #define RX_OP_INIT_STREAM(stream_idx, init_window_size, max_window_size) \ { RX_OPC_INIT_STREAM, (stream_idx), (init_window_size), (max_window_size) }, #define RX_OP_RX(stream_idx, end, is_fin) \ { RX_OPC_RX, (stream_idx), (end), (is_fin) }, #define RX_OP_RETIRE(stream_idx, num_bytes, rtt, expect_fail) \ { RX_OPC_RETIRE, (stream_idx), (num_bytes), (rtt), (expect_fail) }, #define RX_OP_CHECK_CWM_CONN(expected) \ { RX_OPC_CHECK_CWM_CONN, 0, (expected) }, #define RX_OP_CHECK_CWM_STREAM(stream_id, expected) \ { RX_OPC_CHECK_CWM_STREAM, (stream_id), (expected) }, #define RX_OP_CHECK_SWM_CONN(expected) \ { RX_OPC_CHECK_SWM_CONN, 0, (expected) }, #define RX_OP_CHECK_SWM_STREAM(stream_id, expected) \ { RX_OPC_CHECK_SWM_STREAM, (stream_id), (expected) }, #define RX_OP_CHECK_RWM_CONN(expected) \ { RX_OPC_CHECK_RWM_CONN, 0, (expected) }, #define RX_OP_CHECK_RWM_STREAM(stream_id, expected) \ { RX_OPC_CHECK_RWM_STREAM, (stream_id), (expected) }, #define RX_OP_CHECK_CHANGED_CONN(expected, clear) \ { RX_OPC_CHECK_CHANGED_CONN, 0, (expected), (clear) }, #define RX_OP_CHECK_CHANGED_STREAM(stream_id, expected, clear) \ { RX_OPC_CHECK_CHANGED_STREAM, (stream_id), (expected), (clear) }, #define RX_OP_CHECK_ERROR_CONN(expected, clear) \ { RX_OPC_CHECK_ERROR_CONN, 0, (expected), (clear) }, #define RX_OP_CHECK_ERROR_STREAM(stream_id, expected, clear) \ { RX_OPC_CHECK_ERROR_STREAM, (stream_id), (expected), (clear) }, #define RX_OP_STEP_TIME(t) \ { RX_OPC_STEP_TIME, 0, (t) }, #define RX_OP_MSG(msg) \ { RX_OPC_MSG, 0, 0, 0, 0, (msg) }, #define RX_OP_INIT(init_window_size, max_window_size) \ RX_OP_INIT_CONN(init_window_size, max_window_size) \ RX_OP_INIT_STREAM(0, init_window_size, max_window_size) #define RX_OP_CHECK_CWM(expected) \ RX_OP_CHECK_CWM_CONN(expected) \ RX_OP_CHECK_CWM_STREAM(0, expected) #define RX_OP_CHECK_SWM(expected) \ RX_OP_CHECK_SWM_CONN(expected) \ RX_OP_CHECK_SWM_STREAM(0, expected) #define RX_OP_CHECK_RWM(expected) \ RX_OP_CHECK_RWM_CONN(expected) \ RX_OP_CHECK_RWM_STREAM(0, expected) #define RX_OP_CHECK_CHANGED(expected, clear) \ RX_OP_CHECK_CHANGED_CONN(expected, clear) \ RX_OP_CHECK_CHANGED_STREAM(0, expected, clear) #define RX_OP_CHECK_ERROR(expected, clear) \ RX_OP_CHECK_ERROR_CONN(expected, clear) \ RX_OP_CHECK_ERROR_STREAM(0, expected, clear) #define INIT_WINDOW_SIZE (1 * 1024 * 1024) #define INIT_S_WINDOW_SIZE (384 * 1024) /* 1. Basic RXFC Tests (stream window == connection window) */ static const struct rx_test_op rx_script_1[] = { RX_OP_STEP_TIME(1000 * OSSL_TIME_MS) RX_OP_INIT(INIT_WINDOW_SIZE, 10 * INIT_WINDOW_SIZE) /* Check initial state. */ RX_OP_CHECK_CWM(INIT_WINDOW_SIZE) RX_OP_CHECK_ERROR(0, 0) RX_OP_CHECK_CHANGED(0, 0) /* We cannot retire what we have not received. */ RX_OP_RETIRE(0, 1, 0, 1) /* Zero bytes is a no-op and always valid. */ RX_OP_RETIRE(0, 0, 0, 0) /* Consume some window. */ RX_OP_RX(0, 50, 0) /* CWM has not changed. */ RX_OP_CHECK_CWM(INIT_WINDOW_SIZE) RX_OP_CHECK_SWM(50) /* RX, Partial retire */ RX_OP_RX(0, 60, 0) RX_OP_CHECK_SWM(60) RX_OP_RETIRE(0, 20, 50 * OSSL_TIME_MS, 0) RX_OP_CHECK_RWM(20) RX_OP_CHECK_SWM(60) RX_OP_CHECK_CWM(INIT_WINDOW_SIZE) RX_OP_CHECK_CHANGED(0, 0) RX_OP_CHECK_ERROR(0, 0) /* Fully retired */ RX_OP_RETIRE(0, 41, 0, 1) RX_OP_RETIRE(0, 40, 0, 0) RX_OP_CHECK_SWM(60) RX_OP_CHECK_RWM(60) RX_OP_CHECK_CWM(INIT_WINDOW_SIZE) RX_OP_CHECK_CHANGED(0, 0) RX_OP_CHECK_ERROR(0, 0) /* Exhaustion of window - we do not enlarge the window this epoch */ RX_OP_STEP_TIME(201 * OSSL_TIME_MS) RX_OP_RX(0, INIT_WINDOW_SIZE, 0) RX_OP_RETIRE(0, INIT_WINDOW_SIZE - 60, 50 * OSSL_TIME_MS, 0) RX_OP_CHECK_SWM(INIT_WINDOW_SIZE) RX_OP_CHECK_CHANGED(1, 0) RX_OP_CHECK_CHANGED(1, 1) RX_OP_CHECK_CHANGED(0, 0) RX_OP_CHECK_ERROR(0, 0) RX_OP_CHECK_CWM(INIT_WINDOW_SIZE * 2) /* Second epoch - we still do not enlarge the window this epoch */ RX_OP_RX(0, INIT_WINDOW_SIZE + 1, 0) RX_OP_STEP_TIME(201 * OSSL_TIME_MS) RX_OP_RX(0, INIT_WINDOW_SIZE * 2, 0) RX_OP_RETIRE(0, INIT_WINDOW_SIZE, 50 * OSSL_TIME_MS, 0) RX_OP_CHECK_SWM(INIT_WINDOW_SIZE * 2) RX_OP_CHECK_CHANGED(1, 0) RX_OP_CHECK_CHANGED(1, 1) RX_OP_CHECK_CHANGED(0, 0) RX_OP_CHECK_ERROR(0, 0) RX_OP_CHECK_CWM(INIT_WINDOW_SIZE * 3) /* Third epoch - we enlarge the window */ RX_OP_RX(0, INIT_WINDOW_SIZE * 2 + 1, 0) RX_OP_STEP_TIME(199 * OSSL_TIME_MS) RX_OP_RX(0, INIT_WINDOW_SIZE * 3, 0) RX_OP_RETIRE(0, INIT_WINDOW_SIZE, 50 * OSSL_TIME_MS, 0) RX_OP_CHECK_SWM(INIT_WINDOW_SIZE * 3) RX_OP_CHECK_CHANGED(1, 0) RX_OP_CHECK_CHANGED(1, 1) RX_OP_CHECK_CHANGED(0, 0) RX_OP_CHECK_ERROR(0, 0) RX_OP_CHECK_CWM(INIT_WINDOW_SIZE * 5) /* Fourth epoch - peer violates flow control */ RX_OP_RX(0, INIT_WINDOW_SIZE * 5 - 5, 0) RX_OP_STEP_TIME(250 * OSSL_TIME_MS) RX_OP_RX(0, INIT_WINDOW_SIZE * 5 + 1, 0) RX_OP_CHECK_SWM(INIT_WINDOW_SIZE * 5) RX_OP_CHECK_ERROR(QUIC_ERR_FLOW_CONTROL_ERROR, 0) RX_OP_CHECK_ERROR(QUIC_ERR_FLOW_CONTROL_ERROR, 1) RX_OP_CHECK_ERROR(0, 0) RX_OP_CHECK_CWM(INIT_WINDOW_SIZE * 5) /* * No window expansion due to flow control violation; window expansion is * triggered by retirement only. */ RX_OP_CHECK_CHANGED(0, 0) RX_OP_END }; /* 2. Interaction between connection and stream-level flow control */ static const struct rx_test_op rx_script_2[] = { RX_OP_STEP_TIME(1000 * OSSL_TIME_MS) RX_OP_INIT_CONN(INIT_WINDOW_SIZE, 10 * INIT_WINDOW_SIZE) RX_OP_INIT_STREAM(0, INIT_S_WINDOW_SIZE, 30 * INIT_S_WINDOW_SIZE) RX_OP_INIT_STREAM(1, INIT_S_WINDOW_SIZE, 30 * INIT_S_WINDOW_SIZE) RX_OP_RX(0, 10, 0) RX_OP_CHECK_CWM_CONN(INIT_WINDOW_SIZE) RX_OP_CHECK_CWM_STREAM(0, INIT_S_WINDOW_SIZE) RX_OP_CHECK_CWM_STREAM(1, INIT_S_WINDOW_SIZE) RX_OP_CHECK_SWM_CONN(10) RX_OP_CHECK_SWM_STREAM(0, 10) RX_OP_CHECK_SWM_STREAM(1, 0) RX_OP_CHECK_RWM_CONN(0) RX_OP_CHECK_RWM_STREAM(0, 0) RX_OP_CHECK_RWM_STREAM(1, 0) RX_OP_RX(1, 42, 0) RX_OP_RX(1, 42, 0) /* monotonic; equal or lower values ignored */ RX_OP_RX(1, 35, 0) RX_OP_CHECK_CWM_CONN(INIT_WINDOW_SIZE) RX_OP_CHECK_CWM_STREAM(0, INIT_S_WINDOW_SIZE) RX_OP_CHECK_CWM_STREAM(1, INIT_S_WINDOW_SIZE) RX_OP_CHECK_SWM_CONN(52) RX_OP_CHECK_SWM_STREAM(0, 10) RX_OP_CHECK_SWM_STREAM(1, 42) RX_OP_CHECK_RWM_CONN(0) RX_OP_CHECK_RWM_STREAM(0, 0) RX_OP_CHECK_RWM_STREAM(1, 0) RX_OP_RETIRE(0, 10, 50 * OSSL_TIME_MS, 0) RX_OP_CHECK_RWM_CONN(10) RX_OP_CHECK_RWM_STREAM(0, 10) RX_OP_CHECK_CWM_CONN(INIT_WINDOW_SIZE) RX_OP_CHECK_CWM_STREAM(0, INIT_S_WINDOW_SIZE) RX_OP_CHECK_CWM_STREAM(1, INIT_S_WINDOW_SIZE) RX_OP_RETIRE(1, 42, 50 * OSSL_TIME_MS, 0) RX_OP_CHECK_RWM_CONN(52) RX_OP_CHECK_RWM_STREAM(1, 42) RX_OP_CHECK_CWM_CONN(INIT_WINDOW_SIZE) RX_OP_CHECK_CWM_STREAM(0, INIT_S_WINDOW_SIZE) RX_OP_CHECK_CWM_STREAM(1, INIT_S_WINDOW_SIZE) RX_OP_CHECK_CHANGED_CONN(0, 0) /* FC limited by stream but not connection */ RX_OP_STEP_TIME(1000 * OSSL_TIME_MS) RX_OP_RX(0, INIT_S_WINDOW_SIZE, 0) RX_OP_CHECK_SWM_CONN(INIT_S_WINDOW_SIZE + 42) RX_OP_CHECK_SWM_STREAM(0, INIT_S_WINDOW_SIZE) RX_OP_CHECK_SWM_STREAM(1, 42) RX_OP_CHECK_CWM_CONN(INIT_WINDOW_SIZE) RX_OP_CHECK_CWM_STREAM(0, INIT_S_WINDOW_SIZE) /* We bump CWM when more than 1/4 of the window has been retired */ RX_OP_RETIRE(0, INIT_S_WINDOW_SIZE - 10, 50 * OSSL_TIME_MS, 0) RX_OP_CHECK_CWM_STREAM(0, INIT_S_WINDOW_SIZE * 2) RX_OP_CHECK_CHANGED_STREAM(0, 1, 0) RX_OP_CHECK_CHANGED_STREAM(0, 1, 1) RX_OP_CHECK_CHANGED_STREAM(0, 0, 0) /* * This is more than 1/4 of the connection window, so CWM will * be bumped here too. */ RX_OP_CHECK_CWM_CONN(INIT_S_WINDOW_SIZE + INIT_WINDOW_SIZE + 42) RX_OP_CHECK_RWM_CONN(INIT_S_WINDOW_SIZE + 42) RX_OP_CHECK_RWM_STREAM(0, INIT_S_WINDOW_SIZE) RX_OP_CHECK_RWM_STREAM(1, 42) RX_OP_CHECK_CHANGED_CONN(1, 0) RX_OP_CHECK_CHANGED_CONN(1, 1) RX_OP_CHECK_CHANGED_CONN(0, 0) RX_OP_CHECK_ERROR_CONN(0, 0) RX_OP_CHECK_ERROR_STREAM(0, 0, 0) RX_OP_CHECK_ERROR_STREAM(1, 0, 0) /* Test exceeding limit at stream level. */ RX_OP_RX(0, INIT_S_WINDOW_SIZE * 2 + 1, 0) RX_OP_CHECK_ERROR_STREAM(0, QUIC_ERR_FLOW_CONTROL_ERROR, 0) RX_OP_CHECK_ERROR_STREAM(0, QUIC_ERR_FLOW_CONTROL_ERROR, 1) RX_OP_CHECK_ERROR_STREAM(0, 0, 0) RX_OP_CHECK_ERROR_CONN(0, 0) /* doesn't affect conn */ /* Test exceeding limit at connection level. */ RX_OP_RX(0, INIT_WINDOW_SIZE * 2, 0) RX_OP_CHECK_ERROR_CONN(QUIC_ERR_FLOW_CONTROL_ERROR, 0) RX_OP_CHECK_ERROR_CONN(QUIC_ERR_FLOW_CONTROL_ERROR, 1) RX_OP_CHECK_ERROR_CONN(0, 0) RX_OP_END }; static const struct rx_test_op *rx_scripts[] = { rx_script_1, rx_script_2 }; static int run_rxfc_script(const struct rx_test_op *script) { #define MAX_STREAMS 3 int testresult = 0; const struct rx_test_op *op = script; QUIC_RXFC conn_rxfc, stream_rxfc[MAX_STREAMS]; char stream_init_done[MAX_STREAMS] = {0}; int conn_init_done = 0; cur_time = ossl_time_zero(); for (; op->op != RX_OPC_END; ++op) { switch (op->op) { case RX_OPC_INIT_CONN: if (!TEST_true(ossl_quic_rxfc_init(&conn_rxfc, 0, op->arg0, op->arg1, fake_now, NULL))) goto err; conn_init_done = 1; break; case RX_OPC_INIT_STREAM: if (!TEST_size_t_lt(op->stream_idx, OSSL_NELEM(stream_rxfc))) goto err; if (!TEST_true(ossl_quic_rxfc_init(&stream_rxfc[op->stream_idx], &conn_rxfc, op->arg0, op->arg1, fake_now, NULL))) goto err; stream_init_done[op->stream_idx] = 1; break; case RX_OPC_RX: if (!TEST_true(conn_init_done && op->stream_idx < OSSL_NELEM(stream_rxfc) && stream_init_done[op->stream_idx])) goto err; if (!TEST_true(ossl_quic_rxfc_on_rx_stream_frame(&stream_rxfc[op->stream_idx], op->arg0, (int)op->arg1))) goto err; break; case RX_OPC_RETIRE: if (!TEST_true(conn_init_done && op->stream_idx < OSSL_NELEM(stream_rxfc) && stream_init_done[op->stream_idx])) goto err; if (!TEST_int_eq(ossl_quic_rxfc_on_retire(&stream_rxfc[op->stream_idx], op->arg0, ossl_ticks2time(op->arg1)), !op->expect_fail)) goto err; break; case RX_OPC_CHECK_CWM_CONN: if (!TEST_true(conn_init_done)) goto err; if (!TEST_uint64_t_eq(ossl_quic_rxfc_get_cwm(&conn_rxfc), op->arg0)) goto err; break; case RX_OPC_CHECK_CWM_STREAM: if (!TEST_true(op->stream_idx < OSSL_NELEM(stream_rxfc) && stream_init_done[op->stream_idx])) goto err; if (!TEST_uint64_t_eq(ossl_quic_rxfc_get_cwm(&stream_rxfc[op->stream_idx]), op->arg0)) goto err; break; case RX_OPC_CHECK_SWM_CONN: if (!TEST_true(conn_init_done)) goto err; if (!TEST_uint64_t_eq(ossl_quic_rxfc_get_swm(&conn_rxfc), op->arg0)) goto err; break; case RX_OPC_CHECK_SWM_STREAM: if (!TEST_true(op->stream_idx < OSSL_NELEM(stream_rxfc) && stream_init_done[op->stream_idx])) goto err; if (!TEST_uint64_t_eq(ossl_quic_rxfc_get_swm(&stream_rxfc[op->stream_idx]), op->arg0)) goto err; break; case RX_OPC_CHECK_RWM_CONN: if (!TEST_true(conn_init_done)) goto err; if (!TEST_uint64_t_eq(ossl_quic_rxfc_get_rwm(&conn_rxfc), op->arg0)) goto err; break; case RX_OPC_CHECK_RWM_STREAM: if (!TEST_true(op->stream_idx < OSSL_NELEM(stream_rxfc) && stream_init_done[op->stream_idx])) goto err; if (!TEST_uint64_t_eq(ossl_quic_rxfc_get_rwm(&stream_rxfc[op->stream_idx]), op->arg0)) goto err; break; case RX_OPC_CHECK_CHANGED_CONN: if (!TEST_true(conn_init_done)) goto err; if (!TEST_int_eq(ossl_quic_rxfc_has_cwm_changed(&conn_rxfc, (int)op->arg1), (int)op->arg0)) goto err; break; case RX_OPC_CHECK_CHANGED_STREAM: if (!TEST_true(op->stream_idx < OSSL_NELEM(stream_rxfc) && stream_init_done[op->stream_idx])) goto err; if (!TEST_int_eq(ossl_quic_rxfc_has_cwm_changed(&stream_rxfc[op->stream_idx], (int)op->arg1), (int)op->arg0)) goto err; break; case RX_OPC_CHECK_ERROR_CONN: if (!TEST_true(conn_init_done)) goto err; if (!TEST_int_eq(ossl_quic_rxfc_get_error(&conn_rxfc, (int)op->arg1), (int)op->arg0)) goto err; break; case RX_OPC_CHECK_ERROR_STREAM: if (!TEST_true(op->stream_idx < OSSL_NELEM(stream_rxfc) && stream_init_done[op->stream_idx])) goto err; if (!TEST_int_eq(ossl_quic_rxfc_get_error(&stream_rxfc[op->stream_idx], (int)op->arg1), (int)op->arg0)) goto err; break; case RX_OPC_STEP_TIME: cur_time = ossl_time_add(cur_time, ossl_ticks2time(op->arg0)); break; case RX_OPC_MSG: fprintf(stderr, "# %s\n", op->msg); break; default: goto err; } } testresult = 1; err: return testresult; } static int test_rxfc(int idx) { return run_rxfc_script(rx_scripts[idx]); } int setup_tests(void) { ADD_ALL_TESTS(test_txfc, 2); ADD_ALL_TESTS(test_rxfc, OSSL_NELEM(rx_scripts)); return 1; }
22,827
35.063191
102
c
openssl
openssl-master/test/quic_fifd_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/packet.h" #include "internal/quic_txpim.h" #include "internal/quic_fifd.h" #include "testutil.h" static OSSL_TIME cur_time; static OSSL_TIME fake_now(void *arg) { return cur_time; } static void step_time(uint64_t ms) { cur_time = ossl_time_add(cur_time, ossl_ms2time(ms)); } static QUIC_SSTREAM *(*get_sstream_by_id_p)(uint64_t stream_id, uint32_t pn_space, void *arg); static QUIC_SSTREAM *get_sstream_by_id(uint64_t stream_id, uint32_t pn_space, void *arg) { return get_sstream_by_id_p(stream_id, pn_space, arg); } static void (*regen_frame_p)(uint64_t frame_type, uint64_t stream_id, QUIC_TXPIM_PKT *pkt, void *arg); static void regen_frame(uint64_t frame_type, uint64_t stream_id, QUIC_TXPIM_PKT *pkt, void *arg) { regen_frame_p(frame_type, stream_id, pkt, arg); } static void confirm_frame(uint64_t frame_type, uint64_t stream_id, QUIC_TXPIM_PKT *pkt, void *arg) {} static void sstream_updated(uint64_t stream_id, void *arg) {} typedef struct info_st { QUIC_FIFD fifd; OSSL_ACKM *ackm; QUIC_CFQ *cfq; QUIC_TXPIM *txpim; OSSL_STATM statm; OSSL_CC_DATA *ccdata; QUIC_SSTREAM *sstream[4]; } INFO; static INFO *cur_info; static int cb_fail; static int cfq_freed; /* ---------------------------------------------------------------------- * 1. Test that a submitted packet, on ack, acks all streams inside of it * Test that a submitted packet, on ack, calls the get by ID function * correctly * Test that a submitted packet, on ack, acks all fins inside it * Test that a submitted packet, on ack, releases the TXPIM packet */ static QUIC_SSTREAM *sstream_expect(uint64_t stream_id, uint32_t pn_space, void *arg) { if (stream_id == 42 || stream_id == 43) return cur_info->sstream[stream_id - 42]; cb_fail = 1; return NULL; } static uint64_t regen_frame_type[16]; static uint64_t regen_stream_id[16]; static size_t regen_count; static void regen_expect(uint64_t frame_type, uint64_t stream_id, QUIC_TXPIM_PKT *pkt, void *arg) { regen_frame_type[regen_count] = frame_type; regen_stream_id[regen_count] = stream_id; ++regen_count; } static const unsigned char placeholder_data[] = "placeholder"; static void cfq_free_cb_(unsigned char *buf, size_t buf_len, void *arg) { if (buf == placeholder_data && buf_len == sizeof(placeholder_data)) cfq_freed = 1; } #define TEST_KIND_ACK 0 #define TEST_KIND_LOSS 1 #define TEST_KIND_DISCARD 2 #define TEST_KIND_NUM 3 static int test_generic(INFO *info, int kind) { int testresult = 0; size_t i, consumed = 0; QUIC_TXPIM_PKT *pkt = NULL, *pkt2 = NULL; OSSL_QUIC_FRAME_STREAM hdr = {0}; OSSL_QTX_IOVEC iov[2]; size_t num_iov; QUIC_TXPIM_CHUNK chunk = {42, 0, 11, 0}; OSSL_QUIC_FRAME_ACK ack = {0}; OSSL_QUIC_ACK_RANGE ack_ranges[1] = {0}; QUIC_CFQ_ITEM *cfq_item = NULL; uint32_t pn_space = (kind == TEST_KIND_DISCARD) ? QUIC_PN_SPACE_HANDSHAKE : QUIC_PN_SPACE_APP; cur_time = ossl_seconds2time(1000); regen_count = 0; get_sstream_by_id_p = sstream_expect; regen_frame_p = regen_expect; if (!TEST_ptr(pkt = ossl_quic_txpim_pkt_alloc(info->txpim))) goto err; for (i = 0; i < 2; ++i) { num_iov = OSSL_NELEM(iov); if (!TEST_true(ossl_quic_sstream_append(info->sstream[i], (unsigned char *)"Test message", 12, &consumed)) || !TEST_size_t_eq(consumed, 12)) goto err; if (i == 1) ossl_quic_sstream_fin(info->sstream[i]); if (!TEST_true(ossl_quic_sstream_get_stream_frame(info->sstream[i], 0, &hdr, iov, &num_iov)) || !TEST_int_eq(hdr.is_fin, i == 1) || !TEST_uint64_t_eq(hdr.offset, 0) || !TEST_uint64_t_eq(hdr.len, 12) || !TEST_size_t_eq(ossl_quic_sstream_get_buffer_used(info->sstream[i]), 12) || !TEST_true(ossl_quic_sstream_mark_transmitted(info->sstream[i], hdr.offset, hdr.offset + hdr.len - 1))) goto err; if (i == 1 && !TEST_true(ossl_quic_sstream_mark_transmitted_fin(info->sstream[i], hdr.offset + hdr.len))) goto err; chunk.has_fin = hdr.is_fin; chunk.stream_id = 42 + i; if (!TEST_true(ossl_quic_txpim_pkt_append_chunk(pkt, &chunk))) goto err; } cfq_freed = 0; if (!TEST_ptr(cfq_item = ossl_quic_cfq_add_frame(info->cfq, 10, pn_space, OSSL_QUIC_FRAME_TYPE_NEW_CONN_ID, placeholder_data, sizeof(placeholder_data), cfq_free_cb_, NULL)) || !TEST_ptr_eq(cfq_item, ossl_quic_cfq_get_priority_head(info->cfq, pn_space))) goto err; ossl_quic_txpim_pkt_add_cfq_item(pkt, cfq_item); pkt->ackm_pkt.pkt_num = 0; pkt->ackm_pkt.pkt_space = pn_space; pkt->ackm_pkt.largest_acked = QUIC_PN_INVALID; pkt->ackm_pkt.num_bytes = 50; pkt->ackm_pkt.time = cur_time; pkt->ackm_pkt.is_inflight = 1; pkt->ackm_pkt.is_ack_eliciting = 1; if (kind == TEST_KIND_LOSS) { pkt->had_handshake_done_frame = 1; pkt->had_max_data_frame = 1; pkt->had_max_streams_bidi_frame = 1; pkt->had_max_streams_uni_frame = 1; pkt->had_ack_frame = 1; } ack_ranges[0].start = 0; ack_ranges[0].end = 0; ack.ack_ranges = ack_ranges; ack.num_ack_ranges = 1; if (!TEST_true(ossl_quic_fifd_pkt_commit(&info->fifd, pkt))) goto err; /* CFQ item should have been marked as transmitted */ if (!TEST_ptr_null(ossl_quic_cfq_get_priority_head(info->cfq, pn_space))) goto err; switch (kind) { case TEST_KIND_ACK: if (!TEST_true(ossl_ackm_on_rx_ack_frame(info->ackm, &ack, pn_space, cur_time))) goto err; for (i = 0; i < 2; ++i) if (!TEST_size_t_eq(ossl_quic_sstream_get_buffer_used(info->sstream[i]), 0)) goto err; /* This should fail, which proves the FIN was acked */ if (!TEST_false(ossl_quic_sstream_mark_lost_fin(info->sstream[1]))) goto err; /* CFQ item must have been released */ if (!TEST_true(cfq_freed)) goto err; /* No regen calls should have been made */ if (!TEST_size_t_eq(regen_count, 0)) goto err; break; case TEST_KIND_LOSS: /* Trigger loss detection via packet threshold. */ if (!TEST_ptr(pkt2 = ossl_quic_txpim_pkt_alloc(info->txpim))) goto err; step_time(10000); pkt2->ackm_pkt.pkt_num = 50; pkt2->ackm_pkt.pkt_space = pn_space; pkt2->ackm_pkt.largest_acked = QUIC_PN_INVALID; pkt2->ackm_pkt.num_bytes = 50; pkt2->ackm_pkt.time = cur_time; pkt2->ackm_pkt.is_inflight = 1; pkt2->ackm_pkt.is_ack_eliciting = 1; ack_ranges[0].start = 50; ack_ranges[0].end = 50; ack.ack_ranges = ack_ranges; ack.num_ack_ranges = 1; if (!TEST_true(ossl_quic_fifd_pkt_commit(&info->fifd, pkt2)) || !TEST_true(ossl_ackm_on_rx_ack_frame(info->ackm, &ack, pn_space, cur_time))) goto err; for (i = 0; i < 2; ++i) { num_iov = OSSL_NELEM(iov); /* * Stream data we sent must have been marked as lost; check by * ensuring it is returned again */ if (!TEST_true(ossl_quic_sstream_get_stream_frame(info->sstream[i], 0, &hdr, iov, &num_iov)) || !TEST_uint64_t_eq(hdr.offset, 0) || !TEST_uint64_t_eq(hdr.len, 12)) goto err; } /* FC frame should have regenerated for each stream */ if (!TEST_size_t_eq(regen_count, 7) || !TEST_uint64_t_eq(regen_stream_id[0], 42) || !TEST_uint64_t_eq(regen_frame_type[0], OSSL_QUIC_FRAME_TYPE_MAX_STREAM_DATA) || !TEST_uint64_t_eq(regen_stream_id[1], 43) || !TEST_uint64_t_eq(regen_frame_type[1], OSSL_QUIC_FRAME_TYPE_MAX_STREAM_DATA) || !TEST_uint64_t_eq(regen_frame_type[2], OSSL_QUIC_FRAME_TYPE_HANDSHAKE_DONE) || !TEST_uint64_t_eq(regen_stream_id[2], UINT64_MAX) || !TEST_uint64_t_eq(regen_frame_type[3], OSSL_QUIC_FRAME_TYPE_MAX_DATA) || !TEST_uint64_t_eq(regen_stream_id[3], UINT64_MAX) || !TEST_uint64_t_eq(regen_frame_type[4], OSSL_QUIC_FRAME_TYPE_MAX_STREAMS_BIDI) || !TEST_uint64_t_eq(regen_stream_id[4], UINT64_MAX) || !TEST_uint64_t_eq(regen_frame_type[5], OSSL_QUIC_FRAME_TYPE_MAX_STREAMS_UNI) || !TEST_uint64_t_eq(regen_stream_id[5], UINT64_MAX) || !TEST_uint64_t_eq(regen_frame_type[6], OSSL_QUIC_FRAME_TYPE_ACK_WITH_ECN) || !TEST_uint64_t_eq(regen_stream_id[6], UINT64_MAX)) goto err; /* CFQ item should have been marked as lost */ if (!TEST_ptr_eq(cfq_item, ossl_quic_cfq_get_priority_head(info->cfq, pn_space))) goto err; /* FIN should have been marked as lost */ num_iov = OSSL_NELEM(iov); if (!TEST_true(ossl_quic_sstream_get_stream_frame(info->sstream[1], 1, &hdr, iov, &num_iov)) || !TEST_true(hdr.is_fin) || !TEST_uint64_t_eq(hdr.len, 0)) goto err; break; case TEST_KIND_DISCARD: if (!TEST_true(ossl_ackm_on_pkt_space_discarded(info->ackm, pn_space))) goto err; /* CFQ item must have been released */ if (!TEST_true(cfq_freed)) goto err; break; default: goto err; } /* TXPIM must have been released */ if (!TEST_size_t_eq(ossl_quic_txpim_get_in_use(info->txpim), 0)) goto err; testresult = 1; err: return testresult; } static int test_fifd(int idx) { int testresult = 0; INFO info = {0}; size_t i; cur_info = &info; cb_fail = 0; if (!TEST_true(ossl_statm_init(&info.statm)) || !TEST_ptr(info.ccdata = ossl_cc_dummy_method.new(fake_now, NULL)) || !TEST_ptr(info.ackm = ossl_ackm_new(fake_now, NULL, &info.statm, &ossl_cc_dummy_method, info.ccdata)) || !TEST_true(ossl_ackm_on_handshake_confirmed(info.ackm)) || !TEST_ptr(info.cfq = ossl_quic_cfq_new()) || !TEST_ptr(info.txpim = ossl_quic_txpim_new()) || !TEST_true(ossl_quic_fifd_init(&info.fifd, info.cfq, info.ackm, info.txpim, get_sstream_by_id, NULL, regen_frame, NULL, confirm_frame, NULL, sstream_updated, NULL))) goto err; for (i = 0; i < OSSL_NELEM(info.sstream); ++i) if (!TEST_ptr(info.sstream[i] = ossl_quic_sstream_new(1024))) goto err; ossl_statm_update_rtt(&info.statm, ossl_time_zero(), ossl_ms2time(1)); if (!TEST_true(test_generic(&info, idx)) || !TEST_false(cb_fail)) goto err; testresult = 1; err: ossl_quic_fifd_cleanup(&info.fifd); ossl_quic_cfq_free(info.cfq); ossl_quic_txpim_free(info.txpim); ossl_ackm_free(info.ackm); ossl_statm_destroy(&info.statm); if (info.ccdata != NULL) ossl_cc_dummy_method.free(info.ccdata); for (i = 0; i < OSSL_NELEM(info.sstream); ++i) ossl_quic_sstream_free(info.sstream[i]); cur_info = NULL; return testresult; } int setup_tests(void) { ADD_ALL_TESTS(test_fifd, TEST_KIND_NUM); return 1; }
13,240
34.403743
95
c
openssl
openssl-master/test/quic_newcid_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 <string.h> #include <openssl/ssl.h> #include "helpers/quictestlib.h" #include "internal/quic_error.h" #include "testutil.h" static char *cert = NULL; static char *privkey = NULL; /* * Inject NEW_CONNECTION_ID frame */ static size_t ncid_injected; static int add_ncid_frame_cb(QTEST_FAULT *fault, QUIC_PKT_HDR *hdr, unsigned char *buf, size_t len, void *cbarg) { /* * We inject NEW_CONNECTION_ID frame to trigger change of the DCID. * The connection id length must be 8, otherwise the tserver won't be * able to receive packets with this new id. */ static unsigned char new_conn_id_frame[] = { 0x18, /* Type */ 0x01, /* Sequence Number */ 0x01, /* Retire Prior To */ 0x08, /* Connection ID Length */ 0x33, 0x44, 0x55, 0x66, 0xde, 0xad, 0xbe, 0xef, /* Connection ID */ 0xab, 0xcd, 0xef, 0x01, 0x12, 0x32, 0x23, 0x45, /* Stateless Reset Token */ 0x56, 0x06, 0x08, 0x89, 0xa1, 0xb2, 0xc3, 0xd4 }; /* We only ever add the unknown frame to one packet */ if (ncid_injected++) return 1; return qtest_fault_prepend_frame(fault, new_conn_id_frame, sizeof(new_conn_id_frame)); } static int test_ncid_frame(int fail) { int testresult = 0; SSL_CTX *cctx = SSL_CTX_new(OSSL_QUIC_client_method()); QUIC_TSERVER *qtserv = NULL; SSL *cssl = NULL; char *msg = "Hello World!"; size_t msglen = strlen(msg); unsigned char buf[80]; size_t byteswritten; size_t bytesread; QTEST_FAULT *fault = NULL; static const QUIC_CONN_ID conn_id = { 0x08, {0x33, 0x44, 0x55, 0x66, 0xde, 0xad, 0xbe, 0xef} }; ncid_injected = 0; if (!TEST_ptr(cctx)) goto err; if (!TEST_true(qtest_create_quic_objects(NULL, cctx, cert, privkey, 0, &qtserv, &cssl, &fault))) goto err; if (!TEST_true(qtest_create_quic_connection(qtserv, cssl))) goto err; if (!TEST_int_eq(SSL_write(cssl, msg, msglen), msglen)) goto err; ossl_quic_tserver_tick(qtserv); if (!TEST_true(ossl_quic_tserver_read(qtserv, 0, buf, sizeof(buf), &bytesread))) goto err; /* * We assume the entire message is read from the server in one go. In * theory this could get fragmented but its a small message so we assume * not. */ if (!TEST_mem_eq(msg, msglen, buf, bytesread)) goto err; /* * Write a message from the server to the client and add * a NEW_CONNECTION_ID frame. */ if (!TEST_true(qtest_fault_set_packet_plain_listener(fault, add_ncid_frame_cb, NULL))) goto err; if (!fail && !TEST_true(ossl_quic_tserver_set_new_local_cid(qtserv, &conn_id))) goto err; if (!TEST_true(ossl_quic_tserver_write(qtserv, 0, (unsigned char *)msg, msglen, &byteswritten))) goto err; if (!TEST_true(ncid_injected)) goto err; if (!TEST_size_t_eq(msglen, byteswritten)) goto err; ossl_quic_tserver_tick(qtserv); if (!TEST_true(SSL_handle_events(cssl))) goto err; if (!TEST_int_eq(SSL_read(cssl, buf, sizeof(buf)), msglen)) goto err; if (!TEST_mem_eq(msg, msglen, buf, bytesread)) goto err; if (!TEST_int_eq(SSL_write(cssl, msg, msglen), msglen)) goto err; ossl_quic_tserver_tick(qtserv); if (!TEST_true(ossl_quic_tserver_read(qtserv, 0, buf, sizeof(buf), &bytesread))) goto err; if (fail) { if (!TEST_size_t_eq(bytesread, 0)) goto err; } else { if (!TEST_mem_eq(msg, msglen, buf, bytesread)) goto err; } testresult = 1; err: qtest_fault_free(fault); SSL_free(cssl); ossl_quic_tserver_free(qtserv); SSL_CTX_free(cctx); return testresult; } OPT_TEST_DECLARE_USAGE("certsdir\n") int setup_tests(void) { char *certsdir = NULL; if (!test_skip_common_options()) { TEST_error("Error parsing test options\n"); return 0; } if (!TEST_ptr(certsdir = test_get_argument(0))) return 0; 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; ADD_ALL_TESTS(test_ncid_frame, 2); return 1; err: OPENSSL_free(cert); OPENSSL_free(privkey); return 0; } void cleanup_tests(void) { OPENSSL_free(cert); OPENSSL_free(privkey); }
5,290
27.446237
83
c
openssl
openssl-master/test/quic_record_test_util.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 */ #ifndef OSSL_RECORD_TEST_UTIL_H # define OSSL_RECORD_TEST_UTIL_H static int cmp_pkt_hdr(const QUIC_PKT_HDR *a, const QUIC_PKT_HDR *b, const unsigned char *b_data, size_t b_len, int cmp_data) { int ok = 1; if (b_data == NULL) { b_data = b->data; b_len = b->len; } if (!TEST_int_eq(a->type, b->type) || !TEST_int_eq(a->spin_bit, b->spin_bit) || !TEST_int_eq(a->key_phase, b->key_phase) || !TEST_int_eq(a->pn_len, b->pn_len) || !TEST_int_eq(a->partial, b->partial) || !TEST_int_eq(a->fixed, b->fixed) || !TEST_int_eq(a->unused, b->unused) || !TEST_int_eq(a->reserved, b->reserved) || !TEST_uint_eq(a->version, b->version) || !TEST_true(ossl_quic_conn_id_eq(&a->dst_conn_id, &b->dst_conn_id)) || !TEST_true(ossl_quic_conn_id_eq(&a->src_conn_id, &b->src_conn_id)) || !TEST_mem_eq(a->pn, sizeof(a->pn), b->pn, sizeof(b->pn)) || !TEST_size_t_eq(a->token_len, b->token_len) || !TEST_uint64_t_eq(a->len, b->len)) ok = 0; if (a->token_len > 0 && b->token_len > 0 && !TEST_mem_eq(a->token, a->token_len, b->token, b->token_len)) ok = 0; if ((a->token_len == 0 && !TEST_ptr_null(a->token)) || (b->token_len == 0 && !TEST_ptr_null(b->token))) ok = 0; if (cmp_data && !TEST_mem_eq(a->data, a->len, b_data, b_len)) ok = 0; return ok; } #endif
1,815
32.018182
77
h
openssl
openssl-master/test/quic_stream_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/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; /* 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; /* 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; 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, num_iov = 0, init_size = 8192, l; size_t consumed = 0, rd, expected = 0; 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; /* 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; } 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 < consumed; ++i) { if ((test_random() & 1) != 0) { *ref_dst_cur++ = *ref_src_cur; ++expected; } else if (!TEST_true(ossl_quic_sstream_mark_transmitted(sstream, i, 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; for (i = 0; i < num_iov; ++i) { if (!TEST_size_t_le(iov[i].buf_len + rd, expected)) goto err; memcpy(dst_cur, iov[i].buf, iov[i].buf_len); dst_cur += iov[i].buf_len; rd += iov[i].buf_len; } if (!TEST_uint64_t_eq(rd, hdr.len)) goto err; } 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; }
21,252
35.206133
90
c
openssl
openssl-master/test/quic_tserver_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 <openssl/ssl.h> #include <openssl/quic.h> #include <openssl/bio.h> #include "internal/common.h" #include "internal/sockets.h" #include "internal/quic_tserver.h" #include "internal/quic_thread_assist.h" #include "internal/quic_ssl.h" #include "internal/time.h" #include "testutil.h" static const char msg1[] = "The quick brown fox jumped over the lazy dogs."; static char msg2[1024], msg3[1024]; static OSSL_TIME fake_time; static CRYPTO_RWLOCK *fake_time_lock; static const char *certfile, *keyfile; static int is_want(SSL *s, int ret) { int ec = SSL_get_error(s, ret); return ec == SSL_ERROR_WANT_READ || ec == SSL_ERROR_WANT_WRITE; } static unsigned char scratch_buf[2048]; static OSSL_TIME fake_now(void *arg) { OSSL_TIME t; if (!CRYPTO_THREAD_read_lock(fake_time_lock)) return ossl_time_zero(); t = fake_time; CRYPTO_THREAD_unlock(fake_time_lock); return t; } static OSSL_TIME real_now(void *arg) { return ossl_time_now(); } static int do_test(int use_thread_assist, int use_fake_time, int use_inject) { int testresult = 0, ret; int s_fd = -1, c_fd = -1; BIO *s_net_bio = NULL, *s_net_bio_own = NULL; BIO *c_net_bio = NULL, *c_net_bio_own = NULL; BIO *c_pair_own = NULL, *s_pair_own = NULL; QUIC_TSERVER_ARGS tserver_args = {0}; QUIC_TSERVER *tserver = NULL; BIO_ADDR *s_addr_ = NULL; struct in_addr ina = {0}; union BIO_sock_info_u s_info = {0}; SSL_CTX *c_ctx = NULL; SSL *c_ssl = NULL; int c_connected = 0, c_write_done = 0, c_begin_read = 0, s_read_done = 0; int c_wait_eos = 0, c_done_eos = 0; int c_start_idle_test = 0, c_done_idle_test = 0; size_t l = 0, s_total_read = 0, s_total_written = 0, c_total_read = 0; size_t idle_units_done = 0; int s_begin_write = 0; OSSL_TIME start_time; unsigned char alpn[] = { 8, 'o', 's', 's', 'l', 't', 'e', 's', 't' }; OSSL_TIME (*now_cb)(void *arg) = use_fake_time ? fake_now : real_now; size_t limit_ms = 1000; #if defined(OPENSSL_NO_QUIC_THREAD_ASSIST) if (use_thread_assist) { TEST_skip("thread assisted mode not enabled"); return 1; } #endif ina.s_addr = htonl(0x7f000001UL); /* Setup test server. */ s_fd = BIO_socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP, 0); if (!TEST_int_ge(s_fd, 0)) goto err; if (!TEST_true(BIO_socket_nbio(s_fd, 1))) goto err; if (!TEST_ptr(s_addr_ = BIO_ADDR_new())) goto err; if (!TEST_true(BIO_ADDR_rawmake(s_addr_, AF_INET, &ina, sizeof(ina), 0))) goto err; if (!TEST_true(BIO_bind(s_fd, s_addr_, 0))) goto err; s_info.addr = s_addr_; if (!TEST_true(BIO_sock_info(s_fd, BIO_SOCK_INFO_ADDRESS, &s_info))) goto err; if (!TEST_int_gt(BIO_ADDR_rawport(s_addr_), 0)) goto err; if (!TEST_ptr(s_net_bio = s_net_bio_own = BIO_new_dgram(s_fd, 0))) goto err; if (!BIO_up_ref(s_net_bio)) goto err; fake_time = ossl_ms2time(1000); tserver_args.net_rbio = s_net_bio; tserver_args.net_wbio = s_net_bio; tserver_args.alpn = NULL; if (use_fake_time) tserver_args.now_cb = fake_now; if (!TEST_ptr(tserver = ossl_quic_tserver_new(&tserver_args, certfile, keyfile))) { BIO_free(s_net_bio); goto err; } s_net_bio_own = NULL; if (use_inject) { /* * In inject mode we create a dgram pair to feed to the QUIC client on * the read side. We don't feed anything to this, it is just a * placeholder to give the client something which never returns any * datagrams. */ if (!TEST_true(BIO_new_bio_dgram_pair(&c_pair_own, 5000, &s_pair_own, 5000))) goto err; } /* Setup test client. */ c_fd = BIO_socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP, 0); if (!TEST_int_ge(c_fd, 0)) goto err; if (!TEST_true(BIO_socket_nbio(c_fd, 1))) goto err; if (!TEST_ptr(c_net_bio = c_net_bio_own = BIO_new_dgram(c_fd, 0))) goto err; if (!BIO_dgram_set_peer(c_net_bio, s_addr_)) goto err; if (!TEST_ptr(c_ctx = SSL_CTX_new(use_thread_assist ? OSSL_QUIC_client_thread_method() : OSSL_QUIC_client_method()))) goto err; if (!TEST_ptr(c_ssl = SSL_new(c_ctx))) goto err; if (use_fake_time) if (!TEST_true(ossl_quic_conn_set_override_now_cb(c_ssl, fake_now, NULL))) goto err; /* 0 is a success for SSL_set_alpn_protos() */ if (!TEST_false(SSL_set_alpn_protos(c_ssl, alpn, sizeof(alpn)))) goto err; /* Takes ownership of our reference to the BIO. */ if (use_inject) { SSL_set0_rbio(c_ssl, c_pair_own); c_pair_own = NULL; } else { SSL_set0_rbio(c_ssl, c_net_bio); /* Get another reference to be transferred in the SSL_set0_wbio call. */ if (!TEST_true(BIO_up_ref(c_net_bio))) { c_net_bio_own = NULL; /* SSL_free will free the first reference. */ goto err; } } SSL_set0_wbio(c_ssl, c_net_bio); c_net_bio_own = NULL; if (!TEST_true(SSL_set_blocking_mode(c_ssl, 0))) goto err; start_time = now_cb(NULL); for (;;) { if (ossl_time_compare(ossl_time_subtract(now_cb(NULL), start_time), ossl_ms2time(limit_ms)) >= 0) { TEST_error("timeout while attempting QUIC server test"); goto err; } if (!c_start_idle_test) { ret = SSL_connect(c_ssl); if (!TEST_true(ret == 1 || is_want(c_ssl, ret))) goto err; if (ret == 1) c_connected = 1; } if (c_connected && !c_write_done) { if (!TEST_int_eq(SSL_write(c_ssl, msg1, sizeof(msg1) - 1), (int)sizeof(msg1) - 1)) goto err; if (!TEST_true(SSL_stream_conclude(c_ssl, 0))) goto err; c_write_done = 1; } if (c_connected && c_write_done && !s_read_done) { if (!ossl_quic_tserver_read(tserver, 0, (unsigned char *)msg2 + s_total_read, sizeof(msg2) - s_total_read, &l)) { if (!TEST_true(ossl_quic_tserver_has_read_ended(tserver, 0))) goto err; if (!TEST_mem_eq(msg1, sizeof(msg1) - 1, msg2, s_total_read)) goto err; s_begin_write = 1; s_read_done = 1; } else { s_total_read += l; if (!TEST_size_t_le(s_total_read, sizeof(msg1) - 1)) goto err; } } if (s_begin_write && s_total_written < sizeof(msg1) - 1) { if (!TEST_true(ossl_quic_tserver_write(tserver, 0, (unsigned char *)msg2 + s_total_written, sizeof(msg1) - 1 - s_total_written, &l))) goto err; s_total_written += l; if (s_total_written == sizeof(msg1) - 1) { ossl_quic_tserver_conclude(tserver, 0); c_begin_read = 1; } } if (c_begin_read && c_total_read < sizeof(msg1) - 1) { ret = SSL_read_ex(c_ssl, msg3 + c_total_read, sizeof(msg1) - 1 - c_total_read, &l); if (!TEST_true(ret == 1 || is_want(c_ssl, ret))) goto err; c_total_read += l; if (c_total_read == sizeof(msg1) - 1) { if (!TEST_mem_eq(msg1, sizeof(msg1) - 1, msg3, c_total_read)) goto err; c_wait_eos = 1; } } if (c_wait_eos && !c_done_eos) { unsigned char c; ret = SSL_read_ex(c_ssl, &c, sizeof(c), &l); if (!TEST_false(ret)) goto err; /* * Allow the implementation to take as long as it wants to finally * notice EOS. Account for varied timings in OS networking stacks. */ if (SSL_get_error(c_ssl, ret) != SSL_ERROR_WANT_READ) { if (!TEST_int_eq(SSL_get_error(c_ssl, ret), SSL_ERROR_ZERO_RETURN)) goto err; c_done_eos = 1; if (use_thread_assist && use_fake_time) { if (!TEST_true(ossl_quic_tserver_is_connected(tserver))) goto err; c_start_idle_test = 1; limit_ms = 120000; /* extend time limit */ } else { /* DONE */ break; } } } if (c_start_idle_test && !c_done_idle_test) { /* This is more than our default idle timeout of 30s. */ if (idle_units_done < 600) { if (!TEST_true(CRYPTO_THREAD_write_lock(fake_time_lock))) goto err; fake_time = ossl_time_add(fake_time, ossl_ms2time(100)); CRYPTO_THREAD_unlock(fake_time_lock); ++idle_units_done; ossl_quic_conn_force_assist_thread_wake(c_ssl); OSSL_sleep(1); /* Ensure CPU scheduling for test purposes */ } else { c_done_idle_test = 1; } } if (c_done_idle_test) { /* * If we have finished the fake idling duration, the connection * should still be healthy in TA mode. */ if (!TEST_true(ossl_quic_tserver_is_connected(tserver))) goto err; /* DONE */ break; } /* * This is inefficient because we spin until things work without * blocking but this is just a test. */ if (!c_start_idle_test || c_done_idle_test) { /* Inhibit manual ticking during idle test to test TA mode. */ SSL_handle_events(c_ssl); } ossl_quic_tserver_tick(tserver); if (use_inject) { BIO_MSG rmsg = {0}; size_t msgs_processed = 0; for (;;) { /* * Manually spoonfeed received datagrams from the real BIO_dgram * into QUIC via the injection interface, thereby testing the * injection interface. */ rmsg.data = scratch_buf; rmsg.data_len = sizeof(scratch_buf); if (!BIO_recvmmsg(c_net_bio, &rmsg, sizeof(rmsg), 1, 0, &msgs_processed) || msgs_processed == 0 || rmsg.data_len == 0) break; if (!TEST_true(SSL_inject_net_dgram(c_ssl, rmsg.data, rmsg.data_len, NULL, NULL))) goto err; } } } testresult = 1; err: SSL_free(c_ssl); SSL_CTX_free(c_ctx); ossl_quic_tserver_free(tserver); BIO_ADDR_free(s_addr_); BIO_free(s_net_bio_own); BIO_free(c_net_bio_own); BIO_free(c_pair_own); BIO_free(s_pair_own); if (s_fd >= 0) BIO_closesocket(s_fd); if (c_fd >= 0) BIO_closesocket(c_fd); return testresult; } static int test_tserver(int idx) { int thread_assisted, use_fake_time, use_inject; thread_assisted = idx % 2; idx /= 2; use_inject = idx % 2; idx /= 2; use_fake_time = idx % 2; if (use_fake_time && !thread_assisted) return 1; return do_test(thread_assisted, use_fake_time, use_inject); } 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(certfile = test_get_argument(0)) || !TEST_ptr(keyfile = test_get_argument(1))) return 0; if ((fake_time_lock = CRYPTO_THREAD_lock_new()) == NULL) return 0; ADD_ALL_TESTS(test_tserver, 2 * 2 * 2); return 1; }
12,761
29.313539
92
c
openssl
openssl-master/test/quic_txpim_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/packet.h" #include "internal/quic_txpim.h" #include "testutil.h" static int test_txpim(void) { int testresult = 0; QUIC_TXPIM *txpim; size_t i, j; QUIC_TXPIM_PKT *pkts[10] = {NULL}; QUIC_TXPIM_CHUNK chunks[3]; const QUIC_TXPIM_CHUNK *rchunks; if (!TEST_ptr(txpim = ossl_quic_txpim_new())) goto err; for (i = 0; i < OSSL_NELEM(pkts); ++i) { if (!TEST_ptr(pkts[i] = ossl_quic_txpim_pkt_alloc(txpim))) goto err; if (!TEST_size_t_eq(ossl_quic_txpim_pkt_get_num_chunks(pkts[i]), 0)) goto err; for (j = 0; j < OSSL_NELEM(chunks); ++j) { chunks[j].stream_id = 100 - j; chunks[j].start = 1000 * i + j * 10; chunks[j].end = chunks[j].start + 5; if (!TEST_true(ossl_quic_txpim_pkt_append_chunk(pkts[i], chunks + j))) goto err; } if (!TEST_size_t_eq(ossl_quic_txpim_pkt_get_num_chunks(pkts[i]), OSSL_NELEM(chunks))) goto err; rchunks = ossl_quic_txpim_pkt_get_chunks(pkts[i]); if (!TEST_uint64_t_eq(rchunks[0].stream_id, 98) || !TEST_uint64_t_eq(rchunks[1].stream_id, 99) || !TEST_uint64_t_eq(rchunks[2].stream_id, 100)) goto err; } testresult = 1; err: for (i = 0; i < OSSL_NELEM(pkts); ++i) if (txpim != NULL && pkts[i] != NULL) ossl_quic_txpim_pkt_release(txpim, pkts[i]); ossl_quic_txpim_free(txpim); return testresult; } int setup_tests(void) { ADD_TEST(test_txpim); return 1; }
1,953
27.735294
82
c
openssl
openssl-master/test/quicapitest.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/quic.h> #include "helpers/ssltestlib.h" #include "helpers/quictestlib.h" #include "testutil.h" #include "testutil/output.h" #include "../ssl/ssl_local.h" static OSSL_LIB_CTX *libctx = NULL; static OSSL_PROVIDER *defctxnull = NULL; static char *certsdir = NULL; static char *cert = NULL; static char *privkey = NULL; static char *datadir = NULL; static int is_fips = 0; /* The ssltrace test assumes some options are switched on/off */ #if !defined(OPENSSL_NO_SSL_TRACE) && !defined(OPENSSL_NO_EC) \ && defined(OPENSSL_NO_ZLIB) && defined(OPENSSL_NO_BROTLI) \ && defined(OPENSSL_NO_ZSTD) && !defined(OPENSSL_NO_ECX) \ && !defined(OPENSSL_NO_DH) # define DO_SSL_TRACE_TEST #endif /* * Test that we read what we've written. * Test 0: Non-blocking * Test 1: Blocking * Test 2: Blocking, introduce socket error, test error handling. */ static int test_quic_write_read(int idx) { SSL_CTX *cctx = SSL_CTX_new_ex(libctx, NULL, OSSL_QUIC_client_method()); SSL *clientquic = NULL; QUIC_TSERVER *qtserv = NULL; int j, ret = 0; unsigned char buf[20]; static char *msg = "A test message"; size_t msglen = strlen(msg); size_t numbytes = 0; int ssock = 0, csock = 0; uint64_t sid = UINT64_MAX; if (idx >= 1 && !qtest_supports_blocking()) return TEST_skip("Blocking tests not supported in this build"); if (!TEST_ptr(cctx) || !TEST_true(qtest_create_quic_objects(libctx, cctx, cert, privkey, idx >= 1 ? QTEST_FLAG_BLOCK : 0, &qtserv, &clientquic, NULL)) || !TEST_true(SSL_set_tlsext_host_name(clientquic, "localhost")) || !TEST_true(qtest_create_quic_connection(qtserv, clientquic))) goto end; if (idx >= 1) { if (!TEST_true(BIO_get_fd(ossl_quic_tserver_get0_rbio(qtserv), &ssock))) goto end; if (!TEST_int_gt(csock = SSL_get_rfd(clientquic), 0)) goto end; } sid = 0; /* client-initiated bidirectional stream */ for (j = 0; j < 2; j++) { /* Check that sending and receiving app data is ok */ if (!TEST_true(SSL_write_ex(clientquic, msg, msglen, &numbytes)) || !TEST_size_t_eq(numbytes, msglen)) goto end; if (idx >= 1) { do { if (!TEST_true(wait_until_sock_readable(ssock))) goto end; ossl_quic_tserver_tick(qtserv); if (!TEST_true(ossl_quic_tserver_read(qtserv, sid, buf, sizeof(buf), &numbytes))) goto end; } while (numbytes == 0); if (!TEST_mem_eq(buf, numbytes, msg, msglen)) goto end; } if (idx >= 2 && j > 0) /* Introduce permanent socket error */ BIO_closesocket(csock); ossl_quic_tserver_tick(qtserv); if (!TEST_true(ossl_quic_tserver_write(qtserv, sid, (unsigned char *)msg, msglen, &numbytes))) goto end; ossl_quic_tserver_tick(qtserv); SSL_handle_events(clientquic); if (idx >= 2 && j > 0) { if (!TEST_false(SSL_read_ex(clientquic, buf, 1, &numbytes)) || !TEST_int_eq(SSL_get_error(clientquic, 0), SSL_ERROR_SYSCALL) || !TEST_false(SSL_write_ex(clientquic, msg, msglen, &numbytes)) || !TEST_int_eq(SSL_get_error(clientquic, 0), SSL_ERROR_SYSCALL)) goto end; break; } /* * In blocking mode the SSL_read_ex call will block until the socket is * readable and has our data. In non-blocking mode we're doing everything * in memory, so it should be immediately available */ if (!TEST_true(SSL_read_ex(clientquic, buf, 1, &numbytes)) || !TEST_size_t_eq(numbytes, 1) || !TEST_true(SSL_has_pending(clientquic)) || !TEST_int_eq(SSL_pending(clientquic), msglen - 1) || !TEST_true(SSL_read_ex(clientquic, buf + 1, sizeof(buf) - 1, &numbytes)) || !TEST_mem_eq(buf, numbytes + 1, msg, msglen)) goto end; } if (!TEST_true(qtest_shutdown(qtserv, clientquic))) goto end; ret = 1; end: ossl_quic_tserver_free(qtserv); SSL_free(clientquic); SSL_CTX_free(cctx); return ret; } /* Test that a vanilla QUIC SSL object has the expected ciphersuites available */ static int test_ciphersuites(void) { SSL_CTX *ctx = SSL_CTX_new_ex(libctx, NULL, OSSL_QUIC_client_method()); SSL *ssl; int testresult = 0; const STACK_OF(SSL_CIPHER) *ciphers = NULL; const SSL_CIPHER *cipher; /* We expect this exact list of ciphersuites by default */ int cipherids[] = { TLS1_3_CK_AES_256_GCM_SHA384, #if !defined(OPENSSL_NO_CHACHA) && !defined(OPENSSL_NO_POLY1305) TLS1_3_CK_CHACHA20_POLY1305_SHA256, #endif TLS1_3_CK_AES_128_GCM_SHA256 }; size_t i, j; if (!TEST_ptr(ctx)) return 0; ssl = SSL_new(ctx); if (!TEST_ptr(ssl)) goto err; ciphers = SSL_get_ciphers(ssl); for (i = 0, j = 0; i < OSSL_NELEM(cipherids); i++) { if (cipherids[i] == TLS1_3_CK_CHACHA20_POLY1305_SHA256 && is_fips) continue; cipher = sk_SSL_CIPHER_value(ciphers, j++); if (!TEST_ptr(cipher)) goto err; if (!TEST_uint_eq(SSL_CIPHER_get_id(cipher), cipherids[i])) goto err; } /* We should have checked all the ciphers in the stack */ if (!TEST_int_eq(sk_SSL_CIPHER_num(ciphers), j)) goto err; testresult = 1; err: SSL_free(ssl); SSL_CTX_free(ctx); return testresult; } /* * Test that SSL_version, SSL_get_version, SSL_is_quic, SSL_is_tls and * SSL_is_dtls return the expected results for a QUIC connection. Compare with * test_version() in sslapitest.c which does the same thing for TLS/DTLS * connections. */ static int test_version(void) { SSL_CTX *cctx = SSL_CTX_new_ex(libctx, NULL, OSSL_QUIC_client_method()); SSL *clientquic = NULL; QUIC_TSERVER *qtserv = NULL; int testresult = 0; if (!TEST_ptr(cctx) || !TEST_true(qtest_create_quic_objects(libctx, cctx, cert, privkey, 0, &qtserv, &clientquic, NULL)) || !TEST_true(qtest_create_quic_connection(qtserv, clientquic))) goto err; if (!TEST_int_eq(SSL_version(clientquic), OSSL_QUIC1_VERSION) || !TEST_str_eq(SSL_get_version(clientquic), "QUICv1")) goto err; if (!TEST_true(SSL_is_quic(clientquic)) || !TEST_false(SSL_is_tls(clientquic)) || !TEST_false(SSL_is_dtls(clientquic))) goto err; testresult = 1; err: ossl_quic_tserver_free(qtserv); SSL_free(clientquic); SSL_CTX_free(cctx); return testresult; } #if defined(DO_SSL_TRACE_TEST) static void strip_line_ends(char *str) { size_t i; for (i = strlen(str); i > 0 && (str[i - 1] == '\n' || str[i - 1] == '\r'); i--); str[i] = '\0'; } static int compare_with_file(BIO *membio) { BIO *file = NULL; char buf1[512], buf2[512]; char *reffile; int ret = 0; size_t i; reffile = test_mk_file_path(datadir, "ssltraceref.txt"); if (!TEST_ptr(reffile)) goto err; file = BIO_new_file(reffile, "rb"); if (!TEST_ptr(file)) goto err; while (BIO_gets(file, buf1, sizeof(buf1)) > 0) { if (BIO_gets(membio, buf2, sizeof(buf2)) <= 0) { TEST_error("Failed reading mem data"); goto err; } strip_line_ends(buf1); strip_line_ends(buf2); if (strlen(buf1) != strlen(buf2)) { TEST_error("Actual and ref line data length mismatch"); TEST_info("%s", buf1); TEST_info("%s", buf2); goto err; } for (i = 0; i < strlen(buf1); i++) { /* '?' is a wild card character in the reference text */ if (buf1[i] == '?') buf2[i] = '?'; } if (!TEST_str_eq(buf1, buf2)) goto err; } if (!TEST_true(BIO_eof(file)) || !TEST_true(BIO_eof(membio))) goto err; ret = 1; err: OPENSSL_free(reffile); BIO_free(file); return ret; } /* * Tests that the SSL_trace() msg_callback works as expected with a QUIC * connection. This also provides testing of the msg_callback at the same time. */ static int test_ssl_trace(void) { SSL_CTX *cctx = SSL_CTX_new_ex(libctx, NULL, OSSL_QUIC_client_method()); SSL *clientquic = NULL; QUIC_TSERVER *qtserv = NULL; int testresult = 0; BIO *bio = BIO_new(BIO_s_mem()); /* * Ensure we only configure ciphersuites that are available with both the * default and fips providers to get the same output in both cases */ if (!TEST_true(SSL_CTX_set_ciphersuites(cctx, "TLS_AES_128_GCM_SHA256"))) goto err; if (!TEST_ptr(cctx) || !TEST_ptr(bio) || !TEST_true(qtest_create_quic_objects(libctx, cctx, cert, privkey, 0, &qtserv, &clientquic, NULL))) goto err; SSL_set_msg_callback(clientquic, SSL_trace); SSL_set_msg_callback_arg(clientquic, bio); if (!TEST_true(qtest_create_quic_connection(qtserv, clientquic))) goto err; if (!TEST_true(compare_with_file(bio))) goto err; testresult = 1; err: ossl_quic_tserver_free(qtserv); SSL_free(clientquic); SSL_CTX_free(cctx); BIO_free(bio); return testresult; } #endif static int ensure_valid_ciphers(const STACK_OF(SSL_CIPHER) *ciphers) { size_t i; /* Ensure ciphersuite list is suitably subsetted. */ for (i = 0; i < (size_t)sk_SSL_CIPHER_num(ciphers); ++i) { const SSL_CIPHER *cipher = sk_SSL_CIPHER_value(ciphers, i); switch (SSL_CIPHER_get_id(cipher)) { case TLS1_3_CK_AES_128_GCM_SHA256: case TLS1_3_CK_AES_256_GCM_SHA384: case TLS1_3_CK_CHACHA20_POLY1305_SHA256: break; default: TEST_error("forbidden cipher: %s", SSL_CIPHER_get_name(cipher)); return 0; } } return 1; } /* * Test that handshake-layer APIs which shouldn't work don't work with QUIC. */ static int test_quic_forbidden_apis_ctx(void) { int testresult = 0; SSL_CTX *ctx = NULL; if (!TEST_ptr(ctx = SSL_CTX_new_ex(libctx, NULL, OSSL_QUIC_client_method()))) goto err; #ifndef OPENSSL_NO_SRTP /* This function returns 0 on success and 1 on error, and should fail. */ if (!TEST_true(SSL_CTX_set_tlsext_use_srtp(ctx, "SRTP_AEAD_AES_128_GCM"))) goto err; #endif /* * List of ciphersuites we do and don't allow in QUIC. */ #define QUIC_CIPHERSUITES \ "TLS_AES_128_GCM_SHA256:" \ "TLS_AES_256_GCM_SHA384:" \ "TLS_CHACHA20_POLY1305_SHA256" #define NON_QUIC_CIPHERSUITES \ "TLS_AES_128_CCM_SHA256:" \ "TLS_AES_256_CCM_SHA384:" \ "TLS_AES_128_CCM_8_SHA256" /* Set TLSv1.3 ciphersuite list for the SSL_CTX. */ if (!TEST_true(SSL_CTX_set_ciphersuites(ctx, QUIC_CIPHERSUITES ":" NON_QUIC_CIPHERSUITES))) goto err; /* * Forbidden ciphersuites should show up in SSL_CTX accessors, they are only * filtered in SSL_get1_supported_ciphers, so we don't check for * non-inclusion here. */ testresult = 1; err: SSL_CTX_free(ctx); return testresult; } static int test_quic_forbidden_apis(void) { int testresult = 0; SSL_CTX *ctx = NULL; SSL *ssl = NULL; STACK_OF(SSL_CIPHER) *ciphers = NULL; if (!TEST_ptr(ctx = SSL_CTX_new_ex(libctx, NULL, OSSL_QUIC_client_method()))) goto err; if (!TEST_ptr(ssl = SSL_new(ctx))) goto err; #ifndef OPENSSL_NO_SRTP /* This function returns 0 on success and 1 on error, and should fail. */ if (!TEST_true(SSL_set_tlsext_use_srtp(ssl, "SRTP_AEAD_AES_128_GCM"))) goto err; #endif /* Set TLSv1.3 ciphersuite list for the SSL_CTX. */ if (!TEST_true(SSL_set_ciphersuites(ssl, QUIC_CIPHERSUITES ":" NON_QUIC_CIPHERSUITES))) goto err; /* Non-QUIC ciphersuites must not appear in supported ciphers list. */ if (!TEST_ptr(ciphers = SSL_get1_supported_ciphers(ssl)) || !TEST_true(ensure_valid_ciphers(ciphers))) goto err; testresult = 1; err: sk_SSL_CIPHER_free(ciphers); SSL_free(ssl); SSL_CTX_free(ctx); return testresult; } static int test_quic_forbidden_options(void) { int testresult = 0; SSL_CTX *ctx = NULL; SSL *ssl = NULL; char buf[16]; size_t len; if (!TEST_ptr(ctx = SSL_CTX_new_ex(libctx, NULL, OSSL_QUIC_client_method()))) goto err; /* QUIC options restrictions do not affect SSL_CTX */ SSL_CTX_set_options(ctx, UINT64_MAX); if (!TEST_uint64_t_eq(SSL_CTX_get_options(ctx), UINT64_MAX)) goto err; /* Set options on CTX which should not be inherited (tested below). */ SSL_CTX_set_read_ahead(ctx, 1); SSL_CTX_set_max_early_data(ctx, 1); SSL_CTX_set_recv_max_early_data(ctx, 1); SSL_CTX_set_quiet_shutdown(ctx, 1); if (!TEST_ptr(ssl = SSL_new(ctx))) goto err; /* Only permitted options get transferred to SSL object */ if (!TEST_uint64_t_eq(SSL_get_options(ssl), OSSL_QUIC_PERMITTED_OPTIONS)) goto err; /* Try again using SSL_set_options */ SSL_set_options(ssl, UINT64_MAX); if (!TEST_uint64_t_eq(SSL_get_options(ssl), OSSL_QUIC_PERMITTED_OPTIONS)) goto err; /* Clear everything */ SSL_clear_options(ssl, UINT64_MAX); if (!TEST_uint64_t_eq(SSL_get_options(ssl), 0)) goto err; /* Readahead */ if (!TEST_false(SSL_get_read_ahead(ssl))) goto err; SSL_set_read_ahead(ssl, 1); if (!TEST_false(SSL_get_read_ahead(ssl))) goto err; /* Block padding */ if (!TEST_true(SSL_set_block_padding(ssl, 0)) || !TEST_true(SSL_set_block_padding(ssl, 1)) || !TEST_false(SSL_set_block_padding(ssl, 2))) goto err; /* Max fragment length */ if (!TEST_true(SSL_set_tlsext_max_fragment_length(ssl, TLSEXT_max_fragment_length_DISABLED)) || !TEST_false(SSL_set_tlsext_max_fragment_length(ssl, TLSEXT_max_fragment_length_512))) goto err; /* Max early data */ if (!TEST_false(SSL_set_recv_max_early_data(ssl, 1)) || !TEST_false(SSL_set_max_early_data(ssl, 1))) goto err; /* Read/Write */ if (!TEST_false(SSL_read_early_data(ssl, buf, sizeof(buf), &len)) || !TEST_false(SSL_write_early_data(ssl, buf, sizeof(buf), &len))) goto err; /* Buffer Management */ if (!TEST_true(SSL_alloc_buffers(ssl)) || !TEST_false(SSL_free_buffers(ssl))) goto err; /* Pipelining */ if (!TEST_false(SSL_set_max_send_fragment(ssl, 2)) || !TEST_false(SSL_set_split_send_fragment(ssl, 2)) || !TEST_false(SSL_set_max_pipelines(ssl, 2))) goto err; /* HRR */ if (!TEST_false(SSL_stateless(ssl))) goto err; /* Quiet Shutdown */ if (!TEST_false(SSL_get_quiet_shutdown(ssl))) goto err; /* No duplication */ if (!TEST_ptr_null(SSL_dup(ssl))) goto err; /* No clear */ if (!TEST_false(SSL_clear(ssl))) goto err; testresult = 1; err: SSL_free(ssl); SSL_CTX_free(ctx); return testresult; } static int test_quic_set_fd(int idx) { int testresult = 0; SSL_CTX *ctx = NULL; SSL *ssl = NULL; int fd = -1, resfd = -1; BIO *bio = NULL; if (!TEST_ptr(ctx = SSL_CTX_new_ex(libctx, NULL, OSSL_QUIC_client_method()))) goto err; if (!TEST_ptr(ssl = SSL_new(ctx))) goto err; if (!TEST_int_ge(fd = BIO_socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP, 0), 0)) goto err; if (idx == 0) { if (!TEST_true(SSL_set_fd(ssl, fd))) goto err; if (!TEST_ptr(bio = SSL_get_rbio(ssl))) goto err; if (!TEST_ptr_eq(bio, SSL_get_wbio(ssl))) goto err; } else if (idx == 1) { if (!TEST_true(SSL_set_rfd(ssl, fd))) goto err; if (!TEST_ptr(bio = SSL_get_rbio(ssl))) goto err; if (!TEST_ptr_null(SSL_get_wbio(ssl))) goto err; } else { if (!TEST_true(SSL_set_wfd(ssl, fd))) goto err; if (!TEST_ptr(bio = SSL_get_wbio(ssl))) goto err; if (!TEST_ptr_null(SSL_get_rbio(ssl))) goto err; } if (!TEST_int_eq(BIO_method_type(bio), BIO_TYPE_DGRAM)) goto err; if (!TEST_true(BIO_get_fd(bio, &resfd)) || !TEST_int_eq(resfd, fd)) goto err; testresult = 1; err: SSL_free(ssl); SSL_CTX_free(ctx); if (fd >= 0) BIO_closesocket(fd); return testresult; } #define MAXLOOPS 1000 static int test_bio_ssl(void) { /* * We just use OSSL_QUIC_client_method() rather than * OSSL_QUIC_client_thread_method(). We will never leave the connection idle * so we will always be implicitly handling time events anyway via other * IO calls. */ SSL_CTX *cctx = SSL_CTX_new_ex(libctx, NULL, OSSL_QUIC_client_method()); SSL *clientquic = NULL, *stream = NULL; QUIC_TSERVER *qtserv = NULL; int testresult = 0; BIO *cbio = NULL, *strbio = NULL, *thisbio; const char *msg = "Hello world"; int abortctr = 0, err, clienterr = 0, servererr = 0, retc = 0, rets = 0; size_t written, readbytes, msglen; int sid = 0, i; unsigned char buf[80]; if (!TEST_ptr(cctx)) goto err; cbio = BIO_new_ssl(cctx, 1); if (!TEST_ptr(cbio)) goto err; /* * We must configure the ALPN/peer address etc so we get the SSL object in * order to pass it to qtest_create_quic_objects for configuration. */ if (!TEST_int_eq(BIO_get_ssl(cbio, &clientquic), 1)) goto err; if (!TEST_true(qtest_create_quic_objects(libctx, NULL, cert, privkey, 0, &qtserv, &clientquic, NULL))) goto err; msglen = strlen(msg); do { err = BIO_FLAGS_WRITE; while (!clienterr && !retc && err == BIO_FLAGS_WRITE) { retc = BIO_write_ex(cbio, msg, msglen, &written); if (!retc) { if (BIO_should_retry(cbio)) err = BIO_retry_type(cbio); else err = 0; } } if (!clienterr && retc <= 0 && err != BIO_FLAGS_READ) { TEST_info("BIO_write_ex() failed %d, %d", retc, err); TEST_openssl_errors(); clienterr = 1; } if (!servererr && rets <= 0) { ossl_quic_tserver_tick(qtserv); servererr = ossl_quic_tserver_is_term_any(qtserv); if (!servererr) rets = ossl_quic_tserver_is_handshake_confirmed(qtserv); } if (clienterr && servererr) goto err; if (++abortctr == MAXLOOPS) { TEST_info("No progress made"); goto err; } } while ((!retc && !clienterr) || (rets <= 0 && !servererr)); /* * 2 loops: The first using the default stream, and the second using a new * client initiated bidi stream. */ for (i = 0, thisbio = cbio; i < 2; i++) { if (!TEST_true(ossl_quic_tserver_read(qtserv, sid, buf, sizeof(buf), &readbytes)) || !TEST_mem_eq(msg, msglen, buf, readbytes)) goto err; if (!TEST_true(ossl_quic_tserver_write(qtserv, sid, (unsigned char *)msg, msglen, &written))) goto err; ossl_quic_tserver_tick(qtserv); if (!TEST_true(BIO_read_ex(thisbio, buf, sizeof(buf), &readbytes)) || !TEST_mem_eq(msg, msglen, buf, readbytes)) goto err; if (i == 1) break; /* * Now create a new stream and repeat. The bottom two bits of the stream * id represents whether the stream is bidi and whether it is client * initiated or not. For client initiated bidi they are both 0. So the * first client initiated bidi stream is 0 and the next one is 4. */ sid = 4; stream = SSL_new_stream(clientquic, 0); if (!TEST_ptr(stream)) goto err; thisbio = strbio = BIO_new(BIO_f_ssl()); if (!TEST_ptr(strbio)) goto err; if (!TEST_int_eq(BIO_set_ssl(thisbio, stream, BIO_CLOSE), 1)) goto err; stream = NULL; if (!TEST_true(BIO_write_ex(thisbio, msg, msglen, &written))) goto err; ossl_quic_tserver_tick(qtserv); } testresult = 1; err: BIO_free_all(cbio); BIO_free_all(strbio); SSL_free(stream); ossl_quic_tserver_free(qtserv); SSL_CTX_free(cctx); return testresult; } OPT_TEST_DECLARE_USAGE("provider config certsdir datadir\n") int setup_tests(void) { char *modulename; char *configfile; libctx = OSSL_LIB_CTX_new(); if (!TEST_ptr(libctx)) return 0; defctxnull = OSSL_PROVIDER_load(NULL, "null"); /* * Verify that the default and fips providers in the default libctx are not * available */ if (!TEST_false(OSSL_PROVIDER_available(NULL, "default")) || !TEST_false(OSSL_PROVIDER_available(NULL, "fips"))) goto err; if (!test_skip_common_options()) { TEST_error("Error parsing test options\n"); goto err; } if (!TEST_ptr(modulename = test_get_argument(0)) || !TEST_ptr(configfile = test_get_argument(1)) || !TEST_ptr(certsdir = test_get_argument(2)) || !TEST_ptr(datadir = test_get_argument(3))) goto err; if (!TEST_true(OSSL_LIB_CTX_load_config(libctx, configfile))) goto err; /* Check we have the expected provider available */ if (!TEST_true(OSSL_PROVIDER_available(libctx, modulename))) goto err; /* Check the default provider is not available */ if (strcmp(modulename, "default") != 0 && !TEST_false(OSSL_PROVIDER_available(libctx, "default"))) goto err; if (strcmp(modulename, "fips") == 0) is_fips = 1; 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; ADD_ALL_TESTS(test_quic_write_read, 3); ADD_TEST(test_ciphersuites); ADD_TEST(test_version); #if defined(DO_SSL_TRACE_TEST) ADD_TEST(test_ssl_trace); #endif ADD_TEST(test_quic_forbidden_apis_ctx); ADD_TEST(test_quic_forbidden_apis); ADD_TEST(test_quic_forbidden_options); ADD_ALL_TESTS(test_quic_set_fd, 3); ADD_TEST(test_bio_ssl); return 1; err: cleanup_tests(); return 0; } void cleanup_tests(void) { OPENSSL_free(cert); OPENSSL_free(privkey); OSSL_PROVIDER_unload(defctxnull); OSSL_LIB_CTX_free(libctx); }
24,276
28.498177
96
c
openssl
openssl-master/test/quicfaultstest.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 <openssl/ssl.h> #include "helpers/quictestlib.h" #include "internal/quic_error.h" #include "testutil.h" static char *cert = NULL; static char *privkey = NULL; /* * Basic test that just creates a connection and sends some data without any * faults injected. */ static int test_basic(void) { int testresult = 0; SSL_CTX *cctx = SSL_CTX_new(OSSL_QUIC_client_method()); QUIC_TSERVER *qtserv = NULL; SSL *cssl = NULL; char *msg = "Hello World!"; size_t msglen = strlen(msg); unsigned char buf[80]; size_t bytesread; if (!TEST_ptr(cctx)) goto err; if (!TEST_true(qtest_create_quic_objects(NULL, cctx, cert, privkey, 0, &qtserv, &cssl, NULL))) goto err; if (!TEST_true(qtest_create_quic_connection(qtserv, cssl))) goto err; if (!TEST_int_eq(SSL_write(cssl, msg, msglen), msglen)) goto err; ossl_quic_tserver_tick(qtserv); if (!TEST_true(ossl_quic_tserver_read(qtserv, 0, buf, sizeof(buf), &bytesread))) goto err; /* * We assume the entire message is read from the server in one go. In * theory this could get fragmented but its a small message so we assume * not. */ if (!TEST_mem_eq(msg, msglen, buf, bytesread)) goto err; testresult = 1; err: SSL_free(cssl); ossl_quic_tserver_free(qtserv); SSL_CTX_free(cctx); return testresult; } /* * Test that adding an unknown frame type is handled correctly */ static int add_unknown_frame_cb(QTEST_FAULT *fault, QUIC_PKT_HDR *hdr, unsigned char *buf, size_t len, void *cbarg) { static size_t done = 0; /* * There are no "reserved" frame types which are definitately safe for us * to use for testing purposes - but we just use the highest possible * value (8 byte length integer) and with no payload bytes */ unsigned char unknown_frame[] = { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff }; /* We only ever add the unknown frame to one packet */ if (done++) return 1; return qtest_fault_prepend_frame(fault, unknown_frame, sizeof(unknown_frame)); } static int test_unknown_frame(void) { int testresult = 0, ret; SSL_CTX *cctx = SSL_CTX_new(OSSL_QUIC_client_method()); QUIC_TSERVER *qtserv = NULL; SSL *cssl = NULL; char *msg = "Hello World!"; size_t msglen = strlen(msg); unsigned char buf[80]; size_t byteswritten; QTEST_FAULT *fault = NULL; uint64_t sid = UINT64_MAX; if (!TEST_ptr(cctx)) goto err; if (!TEST_true(qtest_create_quic_objects(NULL, cctx, cert, privkey, 0, &qtserv, &cssl, &fault))) goto err; if (!TEST_true(qtest_create_quic_connection(qtserv, cssl))) goto err; /* * Write a message from the server to the client and add an unknown frame * type */ if (!TEST_true(qtest_fault_set_packet_plain_listener(fault, add_unknown_frame_cb, NULL))) goto err; if (!TEST_true(ossl_quic_tserver_stream_new(qtserv, /*is_uni=*/0, &sid)) || !TEST_uint64_t_eq(sid, 1)) goto err; if (!TEST_true(ossl_quic_tserver_write(qtserv, sid, (unsigned char *)msg, msglen, &byteswritten))) goto err; if (!TEST_size_t_eq(msglen, byteswritten)) goto err; ossl_quic_tserver_tick(qtserv); if (!TEST_true(SSL_handle_events(cssl))) goto err; if (!TEST_int_le(ret = SSL_read(cssl, buf, sizeof(buf)), 0)) goto err; if (!TEST_int_eq(SSL_get_error(cssl, ret), SSL_ERROR_SSL)) goto err; #if 0 /* * TODO(QUIC): We should expect an error on the queue after this - but we * don't have it yet. * Note, just raising the error in the obvious place causes * SSL_handle_events() to succeed, but leave a spurious error on the stack. * We need to either allow SSL_handle_events() to fail, or somehow delay the * raising of the error until the SSL_read() call. */ if (!TEST_int_eq(ERR_GET_REASON(ERR_peek_error()), SSL_R_UNKNOWN_FRAME_TYPE_RECEIVED)) goto err; #endif if (!TEST_true(qtest_check_server_frame_encoding_err(qtserv))) goto err; testresult = 1; err: qtest_fault_free(fault); SSL_free(cssl); ossl_quic_tserver_free(qtserv); SSL_CTX_free(cctx); return testresult; } /* * Test that a server that fails to provide transport params cannot be * connected to. */ static int drop_transport_params_cb(QTEST_FAULT *fault, QTEST_ENCRYPTED_EXTENSIONS *ee, size_t eelen, void *encextcbarg) { if (!qtest_fault_delete_extension(fault, TLSEXT_TYPE_quic_transport_parameters, ee->extensions, &ee->extensionslen)) return 0; return 1; } static int test_no_transport_params(void) { int testresult = 0; SSL_CTX *cctx = SSL_CTX_new(OSSL_QUIC_client_method()); QUIC_TSERVER *qtserv = NULL; SSL *cssl = NULL; QTEST_FAULT *fault = NULL; if (!TEST_ptr(cctx)) goto err; if (!TEST_true(qtest_create_quic_objects(NULL, cctx, cert, privkey, 0, &qtserv, &cssl, &fault))) goto err; if (!TEST_true(qtest_fault_set_hand_enc_ext_listener(fault, drop_transport_params_cb, NULL))) goto err; /* * We expect the connection to fail because the server failed to provide * transport parameters */ if (!TEST_false(qtest_create_quic_connection(qtserv, cssl))) goto err; if (!TEST_true(qtest_check_server_protocol_err(qtserv))) goto err; testresult = 1; err: qtest_fault_free(fault); SSL_free(cssl); ossl_quic_tserver_free(qtserv); SSL_CTX_free(cctx); return testresult; } /* * Test that corrupted packets/datagrams are dropped and retransmitted */ static int docorrupt = 0; static int on_packet_cipher_cb(QTEST_FAULT *fault, QUIC_PKT_HDR *hdr, unsigned char *buf, size_t len, void *cbarg) { if (!docorrupt || len == 0) return 1; buf[(size_t)test_random() % len] ^= 0xff; docorrupt = 0; return 1; } static int on_datagram_cb(QTEST_FAULT *fault, BIO_MSG *m, size_t stride, void *cbarg) { if (!docorrupt || m->data_len == 0) return 1; if (!qtest_fault_resize_datagram(fault, m->data_len - 1)) return 1; docorrupt = 0; return 1; } /* * Test 1: Corrupt by flipping bits in an encrypted packet * Test 2: Corrupt by truncating an entire datagram */ static int test_corrupted_data(int idx) { QTEST_FAULT *fault = NULL; int testresult = 0; SSL_CTX *cctx = SSL_CTX_new(OSSL_QUIC_client_method()); QUIC_TSERVER *qtserv = NULL; SSL *cssl = NULL; char *msg = "Hello World!"; size_t msglen = strlen(msg); unsigned char buf[80]; size_t bytesread, byteswritten; uint64_t sid = UINT64_MAX; if (!TEST_ptr(cctx)) goto err; if (!TEST_true(qtest_create_quic_objects(NULL, cctx, cert, privkey, QTEST_FLAG_FAKE_TIME, &qtserv, &cssl, &fault))) goto err; if (idx == 0) { /* Listen for encrypted packets being sent */ if (!TEST_true(qtest_fault_set_packet_cipher_listener(fault, on_packet_cipher_cb, NULL))) goto err; } else { /* Listen for datagrams being sent */ if (!TEST_true(qtest_fault_set_datagram_listener(fault, on_datagram_cb, NULL))) goto err; } if (!TEST_true(qtest_create_quic_connection(qtserv, cssl))) goto err; /* Corrupt the next server packet*/ docorrupt = 1; if (!TEST_true(ossl_quic_tserver_stream_new(qtserv, /*is_uni=*/0, &sid)) || !TEST_uint64_t_eq(sid, 1)) goto err; /* * Send first 5 bytes of message. This will get corrupted and is treated as * "lost" */ if (!TEST_true(ossl_quic_tserver_write(qtserv, sid, (unsigned char *)msg, 5, &byteswritten))) goto err; if (!TEST_size_t_eq(byteswritten, 5)) goto err; /* * Introduce a small delay so that the above packet has time to be detected * as lost. Loss detection times are based on RTT which should be very * fast for us since there isn't really a network. The loss delay timer is * always at least 1ms though. We skip forward 100ms */ qtest_add_time(100); /* Send rest of message */ if (!TEST_true(ossl_quic_tserver_write(qtserv, sid, (unsigned char *)msg + 5, msglen - 5, &byteswritten))) goto err; if (!TEST_size_t_eq(byteswritten, msglen - 5)) goto err; /* * Receive the corrupted packet. This should get dropped and is effectively * "lost". We also process the second packet which should be decrypted * successfully. Therefore we ack the frames in it */ if (!TEST_true(SSL_handle_events(cssl))) goto err; /* * Process the ack. Detect that the first part of the message must have * been lost due to the time elapsed since it was sent and resend it */ ossl_quic_tserver_tick(qtserv); /* Receive and process the newly arrived message data resend */ if (!TEST_true(SSL_handle_events(cssl))) goto err; /* The whole message should now have arrived */ if (!TEST_true(SSL_read_ex(cssl, buf, sizeof(buf), &bytesread))) goto err; if (!TEST_mem_eq(msg, msglen, buf, bytesread)) goto err; /* * If the test was successful then we corrupted exactly one packet and * docorrupt was reset */ if (!TEST_false(docorrupt)) goto err; testresult = 1; err: qtest_fault_free(fault); SSL_free(cssl); ossl_quic_tserver_free(qtserv); SSL_CTX_free(cctx); return testresult; } OPT_TEST_DECLARE_USAGE("certsdir\n") int setup_tests(void) { char *certsdir = NULL; if (!test_skip_common_options()) { TEST_error("Error parsing test options\n"); return 0; } if (!TEST_ptr(certsdir = test_get_argument(0))) return 0; 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; ADD_TEST(test_basic); ADD_TEST(test_unknown_frame); ADD_TEST(test_no_transport_params); ADD_ALL_TESTS(test_corrupted_data, 2); return 1; err: OPENSSL_free(cert); OPENSSL_free(privkey); return 0; } void cleanup_tests(void) { OPENSSL_free(cert); OPENSSL_free(privkey); }
11,840
27.740291
85
c
openssl
openssl-master/test/rand_status_test.c
/* * Copyright 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 <openssl/rand.h> #include "testutil.h" /* * This needs to be in a test executable all by itself so that it can be * guaranteed to run before any generate calls have been made. */ static int test_rand_status(void) { return TEST_true(RAND_status()); } int setup_tests(void) { ADD_TEST(test_rand_status); return 1; }
673
23.071429
74
c
openssl
openssl-master/test/rand_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 <openssl/evp.h> #include <openssl/rand.h> #include <openssl/bio.h> #include <openssl/core_names.h> #include "testutil.h" static int test_rand(void) { EVP_RAND_CTX *privctx; OSSL_PARAM params[2], *p = params; unsigned char entropy1[] = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05 }; unsigned char entropy2[] = { 0xff, 0xfe, 0xfd }; unsigned char outbuf[3]; *p++ = OSSL_PARAM_construct_octet_string(OSSL_RAND_PARAM_TEST_ENTROPY, entropy1, sizeof(entropy1)); *p = OSSL_PARAM_construct_end(); if (!TEST_ptr(privctx = RAND_get0_private(NULL)) || !TEST_true(EVP_RAND_CTX_set_params(privctx, params)) || !TEST_int_gt(RAND_priv_bytes(outbuf, sizeof(outbuf)), 0) || !TEST_mem_eq(outbuf, sizeof(outbuf), entropy1, sizeof(outbuf)) || !TEST_int_le(RAND_priv_bytes(outbuf, sizeof(outbuf) + 1), 0) || !TEST_int_gt(RAND_priv_bytes(outbuf, sizeof(outbuf)), 0) || !TEST_mem_eq(outbuf, sizeof(outbuf), entropy1 + sizeof(outbuf), sizeof(outbuf))) return 0; *params = OSSL_PARAM_construct_octet_string(OSSL_RAND_PARAM_TEST_ENTROPY, entropy2, sizeof(entropy2)); if (!TEST_true(EVP_RAND_CTX_set_params(privctx, params)) || !TEST_int_gt(RAND_priv_bytes(outbuf, sizeof(outbuf)), 0) || !TEST_mem_eq(outbuf, sizeof(outbuf), entropy2, sizeof(outbuf))) return 0; return 1; } int setup_tests(void) { if (!TEST_true(RAND_set_DRBG_type(NULL, "TEST-RAND", NULL, NULL, NULL))) return 0; ADD_TEST(test_rand); return 1; }
2,023
36.481481
78
c
openssl
openssl-master/test/rc2test.c
/* * Copyright 1995-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 */ /* * RC2 low level APIs are deprecated for public use, but still ok for internal * use. */ #include "internal/deprecated.h" #include "internal/nelem.h" #include "testutil.h" #ifndef OPENSSL_NO_RC2 # include <openssl/rc2.h> static unsigned char RC2key[4][16] = { {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01}, {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, {0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F}, }; static unsigned char RC2plain[4][8] = { {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF}, {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, }; static unsigned char RC2cipher[4][8] = { {0x1C, 0x19, 0x8A, 0x83, 0x8D, 0xF0, 0x28, 0xB7}, {0x21, 0x82, 0x9C, 0x78, 0xA9, 0xF9, 0xC0, 0x74}, {0x13, 0xDB, 0x35, 0x17, 0xD3, 0x21, 0x86, 0x9E}, {0x50, 0xDC, 0x01, 0x62, 0xBD, 0x75, 0x7F, 0x31}, }; static int test_rc2(const int n) { int testresult = 1; RC2_KEY key; unsigned char buf[8], buf2[8]; RC2_set_key(&key, 16, &(RC2key[n][0]), 0 /* or 1024 */ ); RC2_ecb_encrypt(&RC2plain[n][0], buf, &key, RC2_ENCRYPT); if (!TEST_mem_eq(&RC2cipher[n][0], 8, buf, 8)) testresult = 0; RC2_ecb_encrypt(buf, buf2, &key, RC2_DECRYPT); if (!TEST_mem_eq(&RC2plain[n][0], 8, buf2, 8)) testresult = 0; return testresult; } #endif int setup_tests(void) { #ifndef OPENSSL_NO_RC2 ADD_ALL_TESTS(test_rc2, OSSL_NELEM(RC2key)); #endif return 1; }
2,151
27.693333
78
c
openssl
openssl-master/test/rc4test.c
/* * Copyright 1995-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 */ /* * RC4 and SHA-1 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" #ifndef OPENSSL_NO_RC4 # include <openssl/rc4.h> # include <openssl/sha.h> static unsigned char keys[6][30] = { {8, 0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef}, {8, 0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef}, {8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, {4, 0xef, 0x01, 0x23, 0x45}, {8, 0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef}, {4, 0xef, 0x01, 0x23, 0x45}, }; static unsigned char data_len[6] = { 8, 8, 8, 20, 28, 10 }; static unsigned char data[6][30] = { {0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef, 0xff}, {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff}, {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff}, {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff}, {0x12, 0x34, 0x56, 0x78, 0x9A, 0xBC, 0xDE, 0xF0, 0x12, 0x34, 0x56, 0x78, 0x9A, 0xBC, 0xDE, 0xF0, 0x12, 0x34, 0x56, 0x78, 0x9A, 0xBC, 0xDE, 0xF0, 0x12, 0x34, 0x56, 0x78, 0xff}, {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff}, }; static unsigned char output[6][30] = { {0x75, 0xb7, 0x87, 0x80, 0x99, 0xe0, 0xc5, 0x96, 0x00}, {0x74, 0x94, 0xc2, 0xe7, 0x10, 0x4b, 0x08, 0x79, 0x00}, {0xde, 0x18, 0x89, 0x41, 0xa3, 0x37, 0x5d, 0x3a, 0x00}, {0xd6, 0xa1, 0x41, 0xa7, 0xec, 0x3c, 0x38, 0xdf, 0xbd, 0x61, 0x5a, 0x11, 0x62, 0xe1, 0xc7, 0xba, 0x36, 0xb6, 0x78, 0x58, 0x00}, {0x66, 0xa0, 0x94, 0x9f, 0x8a, 0xf7, 0xd6, 0x89, 0x1f, 0x7f, 0x83, 0x2b, 0xa8, 0x33, 0xc0, 0x0c, 0x89, 0x2e, 0xbe, 0x30, 0x14, 0x3c, 0xe2, 0x87, 0x40, 0x01, 0x1e, 0xcf, 0x00}, {0xd6, 0xa1, 0x41, 0xa7, 0xec, 0x3c, 0x38, 0xdf, 0xbd, 0x61, 0x00}, }; static int test_rc4_encrypt(const int i) { unsigned char obuf[512]; RC4_KEY key; RC4_set_key(&key, keys[i][0], &(keys[i][1])); memset(obuf, 0, sizeof(obuf)); RC4(&key, data_len[i], &(data[i][0]), obuf); return TEST_mem_eq(obuf, data_len[i] + 1, output[i], data_len[i] + 1); } static int test_rc4_end_processing(const int i) { unsigned char obuf[512]; RC4_KEY key; RC4_set_key(&key, keys[3][0], &(keys[3][1])); memset(obuf, 0, sizeof(obuf)); RC4(&key, i, &(data[3][0]), obuf); if (!TEST_mem_eq(obuf, i, output[3], i)) return 0; return TEST_uchar_eq(obuf[i], 0); } static int test_rc4_multi_call(const int i) { unsigned char obuf[512]; RC4_KEY key; RC4_set_key(&key, keys[3][0], &(keys[3][1])); memset(obuf, 0, sizeof(obuf)); RC4(&key, i, &(data[3][0]), obuf); RC4(&key, data_len[3] - i, &(data[3][i]), &(obuf[i])); return TEST_mem_eq(obuf, data_len[3] + 1, output[3], data_len[3] + 1); } static int test_rc_bulk(void) { RC4_KEY key; unsigned char buf[513]; SHA_CTX c; unsigned char md[SHA_DIGEST_LENGTH]; int i; static unsigned char expected[] = { 0xa4, 0x7b, 0xcc, 0x00, 0x3d, 0xd0, 0xbd, 0xe1, 0xac, 0x5f, 0x12, 0x1e, 0x45, 0xbc, 0xfb, 0x1a, 0xa1, 0xf2, 0x7f, 0xc5 }; RC4_set_key(&key, keys[0][0], &(keys[3][1])); memset(buf, 0, sizeof(buf)); SHA1_Init(&c); for (i = 0; i < 2571; i++) { RC4(&key, sizeof(buf), buf, buf); SHA1_Update(&c, buf, sizeof(buf)); } SHA1_Final(md, &c); return TEST_mem_eq(md, sizeof(md), expected, sizeof(expected)); } #endif int setup_tests(void) { #ifndef OPENSSL_NO_RC4 ADD_ALL_TESTS(test_rc4_encrypt, OSSL_NELEM(data_len)); ADD_ALL_TESTS(test_rc4_end_processing, data_len[3]); ADD_ALL_TESTS(test_rc4_multi_call, data_len[3]); ADD_TEST(test_rc_bulk); #endif return 1; }
4,185
30.007407
79
c
openssl
openssl-master/test/rc5test.c
/* * Copyright 1995-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 */ /* * RC5 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" #ifndef OPENSSL_NO_RC5 # include <openssl/rc5.h> static unsigned char RC5key[5][16] = { {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, {0x91, 0x5f, 0x46, 0x19, 0xbe, 0x41, 0xb2, 0x51, 0x63, 0x55, 0xa5, 0x01, 0x10, 0xa9, 0xce, 0x91}, {0x78, 0x33, 0x48, 0xe7, 0x5a, 0xeb, 0x0f, 0x2f, 0xd7, 0xb1, 0x69, 0xbb, 0x8d, 0xc1, 0x67, 0x87}, {0xdc, 0x49, 0xdb, 0x13, 0x75, 0xa5, 0x58, 0x4f, 0x64, 0x85, 0xb4, 0x13, 0xb5, 0xf1, 0x2b, 0xaf}, {0x52, 0x69, 0xf1, 0x49, 0xd4, 0x1b, 0xa0, 0x15, 0x24, 0x97, 0x57, 0x4d, 0x7f, 0x15, 0x31, 0x25}, }; static unsigned char RC5plain[5][8] = { {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, {0x21, 0xA5, 0xDB, 0xEE, 0x15, 0x4B, 0x8F, 0x6D}, {0xF7, 0xC0, 0x13, 0xAC, 0x5B, 0x2B, 0x89, 0x52}, {0x2F, 0x42, 0xB3, 0xB7, 0x03, 0x69, 0xFC, 0x92}, {0x65, 0xC1, 0x78, 0xB2, 0x84, 0xD1, 0x97, 0xCC}, }; static unsigned char RC5cipher[5][8] = { {0x21, 0xA5, 0xDB, 0xEE, 0x15, 0x4B, 0x8F, 0x6D}, {0xF7, 0xC0, 0x13, 0xAC, 0x5B, 0x2B, 0x89, 0x52}, {0x2F, 0x42, 0xB3, 0xB7, 0x03, 0x69, 0xFC, 0x92}, {0x65, 0xC1, 0x78, 0xB2, 0x84, 0xD1, 0x97, 0xCC}, {0xEB, 0x44, 0xE4, 0x15, 0xDA, 0x31, 0x98, 0x24}, }; # define RC5_CBC_NUM 27 static unsigned char rc5_cbc_cipher[RC5_CBC_NUM][8] = { {0x7a, 0x7b, 0xba, 0x4d, 0x79, 0x11, 0x1d, 0x1e}, {0x79, 0x7b, 0xba, 0x4d, 0x78, 0x11, 0x1d, 0x1e}, {0x7a, 0x7b, 0xba, 0x4d, 0x79, 0x11, 0x1d, 0x1f}, {0x7a, 0x7b, 0xba, 0x4d, 0x79, 0x11, 0x1d, 0x1f}, {0x8b, 0x9d, 0xed, 0x91, 0xce, 0x77, 0x94, 0xa6}, {0x2f, 0x75, 0x9f, 0xe7, 0xad, 0x86, 0xa3, 0x78}, {0xdc, 0xa2, 0x69, 0x4b, 0xf4, 0x0e, 0x07, 0x88}, {0xdc, 0xa2, 0x69, 0x4b, 0xf4, 0x0e, 0x07, 0x88}, {0xdc, 0xfe, 0x09, 0x85, 0x77, 0xec, 0xa5, 0xff}, {0x96, 0x46, 0xfb, 0x77, 0x63, 0x8f, 0x9c, 0xa8}, {0xb2, 0xb3, 0x20, 0x9d, 0xb6, 0x59, 0x4d, 0xa4}, {0x54, 0x5f, 0x7f, 0x32, 0xa5, 0xfc, 0x38, 0x36}, {0x82, 0x85, 0xe7, 0xc1, 0xb5, 0xbc, 0x74, 0x02}, {0xfc, 0x58, 0x6f, 0x92, 0xf7, 0x08, 0x09, 0x34}, {0xcf, 0x27, 0x0e, 0xf9, 0x71, 0x7f, 0xf7, 0xc4}, {0xe4, 0x93, 0xf1, 0xc1, 0xbb, 0x4d, 0x6e, 0x8c}, {0x5c, 0x4c, 0x04, 0x1e, 0x0f, 0x21, 0x7a, 0xc3}, {0x92, 0x1f, 0x12, 0x48, 0x53, 0x73, 0xb4, 0xf7}, {0x5b, 0xa0, 0xca, 0x6b, 0xbe, 0x7f, 0x5f, 0xad}, {0xc5, 0x33, 0x77, 0x1c, 0xd0, 0x11, 0x0e, 0x63}, {0x29, 0x4d, 0xdb, 0x46, 0xb3, 0x27, 0x8d, 0x60}, {0xda, 0xd6, 0xbd, 0xa9, 0xdf, 0xe8, 0xf7, 0xe8}, {0x97, 0xe0, 0x78, 0x78, 0x37, 0xed, 0x31, 0x7f}, {0x78, 0x75, 0xdb, 0xf6, 0x73, 0x8c, 0x64, 0x78}, {0x8f, 0x34, 0xc3, 0xc6, 0x81, 0xc9, 0x96, 0x95}, {0x7c, 0xb3, 0xf1, 0xdf, 0x34, 0xf9, 0x48, 0x11}, {0x7f, 0xd1, 0xa0, 0x23, 0xa5, 0xbb, 0xa2, 0x17}, }; static unsigned char rc5_cbc_key[RC5_CBC_NUM][17] = { {1, 0x00}, {1, 0x00}, {1, 0x00}, {1, 0x00}, {1, 0x00}, {1, 0x11}, {1, 0x00}, {4, 0x00, 0x00, 0x00, 0x00}, {1, 0x00}, {1, 0x00}, {1, 0x00}, {1, 0x00}, {4, 0x01, 0x02, 0x03, 0x04}, {4, 0x01, 0x02, 0x03, 0x04}, {4, 0x01, 0x02, 0x03, 0x04}, {8, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08}, {8, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08}, {8, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08}, {8, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08}, {16, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x10, 0x20, 0x30, 0x40, 0x50, 0x60, 0x70, 0x80}, {16, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x10, 0x20, 0x30, 0x40, 0x50, 0x60, 0x70, 0x80}, {16, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x10, 0x20, 0x30, 0x40, 0x50, 0x60, 0x70, 0x80}, {5, 0x01, 0x02, 0x03, 0x04, 0x05}, {5, 0x01, 0x02, 0x03, 0x04, 0x05}, {5, 0x01, 0x02, 0x03, 0x04, 0x05}, {5, 0x01, 0x02, 0x03, 0x04, 0x05}, {5, 0x01, 0x02, 0x03, 0x04, 0x05}, }; static unsigned char rc5_cbc_plain[RC5_CBC_NUM][8] = { {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, {0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff}, {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01}, {0x10, 0x20, 0x30, 0x40, 0x50, 0x60, 0x70, 0x80}, {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, {0x10, 0x20, 0x30, 0x40, 0x50, 0x60, 0x70, 0x80}, {0x10, 0x20, 0x30, 0x40, 0x50, 0x60, 0x70, 0x80}, {0x10, 0x20, 0x30, 0x40, 0x50, 0x60, 0x70, 0x80}, {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}, {0x10, 0x20, 0x30, 0x40, 0x50, 0x60, 0x70, 0x80}, {0x10, 0x20, 0x30, 0x40, 0x50, 0x60, 0x70, 0x80}, {0x10, 0x20, 0x30, 0x40, 0x50, 0x60, 0x70, 0x80}, {0x10, 0x20, 0x30, 0x40, 0x50, 0x60, 0x70, 0x80}, {0x10, 0x20, 0x30, 0x40, 0x50, 0x60, 0x70, 0x80}, {0x10, 0x20, 0x30, 0x40, 0x50, 0x60, 0x70, 0x80}, {0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff}, {0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff}, {0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08}, {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, {0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x01}, }; static int rc5_cbc_rounds[RC5_CBC_NUM] = { 0, 0, 0, 0, 0, 1, 2, 2, 8, 8, 12, 16, 8, 12, 16, 12, 8, 12, 16, 8, 12, 16, 12, 8, 8, 8, 8, }; static unsigned char rc5_cbc_iv[RC5_CBC_NUM][8] = { {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01}, {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, {0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08}, {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, {0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08}, {0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08}, {0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08}, {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, {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}, {0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08}, {0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08}, {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, {0x78, 0x75, 0xdb, 0xf6, 0x73, 0x8c, 0x64, 0x78}, {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, {0x7c, 0xb3, 0xf1, 0xdf, 0x34, 0xf9, 0x48, 0x11}, }; static int test_rc5_ecb(int n) { int testresult = 1; RC5_32_KEY key; unsigned char buf[8], buf2[8]; if (!TEST_true(RC5_32_set_key(&key, 16, &RC5key[n][0], 12))) return 0; RC5_32_ecb_encrypt(&RC5plain[n][0], buf, &key, RC5_ENCRYPT); if (!TEST_mem_eq(&RC5cipher[n][0], sizeof(RC5cipher[0]), buf, sizeof(buf))) testresult = 0; RC5_32_ecb_encrypt(buf, buf2, &key, RC5_DECRYPT); if (!TEST_mem_eq(&RC5plain[n][0], sizeof(RC5cipher[0]), buf2, sizeof(buf2))) testresult = 0; return testresult; } static int test_rc5_cbc(int n) { int testresult = 1; int i; RC5_32_KEY key; unsigned char buf[8], buf2[8], ivb[8]; i = rc5_cbc_rounds[n]; if (i >= 8) { if (!TEST_true(RC5_32_set_key(&key, rc5_cbc_key[n][0], &rc5_cbc_key[n][1], i))) return 0; memcpy(ivb, &rc5_cbc_iv[n][0], 8); RC5_32_cbc_encrypt(&rc5_cbc_plain[n][0], buf, 8, &key, &ivb[0], RC5_ENCRYPT); if (!TEST_mem_eq(&rc5_cbc_cipher[n][0], sizeof(rc5_cbc_cipher[0]), buf, sizeof(buf))) testresult = 0; memcpy(ivb, &rc5_cbc_iv[n][0], 8); RC5_32_cbc_encrypt(buf, buf2, 8, &key, &ivb[0], RC5_DECRYPT); if (!TEST_mem_eq(&rc5_cbc_plain[n][0], sizeof(rc5_cbc_plain[0]), buf2, sizeof(buf2))) testresult = 0; } return testresult; } #endif int setup_tests(void) { #ifndef OPENSSL_NO_RC5 ADD_ALL_TESTS(test_rc5_ecb, OSSL_NELEM(RC5key)); ADD_ALL_TESTS(test_rc5_cbc, RC5_CBC_NUM); #endif return 1; }
9,285
37.057377
80
c
openssl
openssl-master/test/rdcpu_sanitytest.c
/* * Copyright 2018-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 <stdlib.h> #include <string.h> #include "testutil.h" #include "internal/cryptlib.h" #if (defined(__i386) || defined(__i386__) || defined(_M_IX86) || \ defined(__x86_64) || defined(__x86_64__) || \ defined(_M_AMD64) || defined (_M_X64)) && defined(OPENSSL_CPUID_OBJ) # define IS_X_86 1 size_t OPENSSL_ia32_rdrand_bytes(unsigned char *buf, size_t len); size_t OPENSSL_ia32_rdseed_bytes(unsigned char *buf, size_t len); #else # define IS_X_86 0 #endif #if defined(__aarch64__) && defined(OPENSSL_CPUID_OBJ) # define IS_AARCH_64 1 # include "arm_arch.h" size_t OPENSSL_rndr_bytes(unsigned char *buf, size_t len); size_t OPENSSL_rndrrs_bytes(unsigned char *buf, size_t len); #else # define IS_AARCH_64 0 #endif #if (IS_X_86 || IS_AARCH_64) static int sanity_check_bytes(size_t (*rng)(unsigned char *, size_t), int rounds, int min_failures, int max_retries, int max_zero_words) { int testresult = 0; unsigned char prior[31] = {0}, buf[31] = {0}, check[7]; int failures = 0, zero_words = 0; int i; for (i = 0; i < rounds; i++) { size_t generated = 0; int retry; for (retry = 0; retry < max_retries; retry++) { generated = rng(buf, sizeof(buf)); if (generated == sizeof(buf)) break; failures++; } /*- * Verify that we don't have too many unexpected runs of zeroes, * implying that we might be accidentally using the 32-bit RDRAND * instead of the 64-bit one on 64-bit systems. */ size_t j; for (j = 0; j < sizeof(buf) - 1; j++) { if (buf[j] == 0 && buf[j+1] == 0) { zero_words++; } } if (!TEST_int_eq(generated, sizeof(buf))) goto end; if (!TEST_false(!memcmp(prior, buf, sizeof(buf)))) goto end; /* Verify that the last 7 bytes of buf aren't all the same value */ unsigned char *tail = &buf[sizeof(buf) - sizeof(check)]; memset(check, tail[0], 7); if (!TEST_false(!memcmp(check, tail, sizeof(check)))) goto end; /* Save the result and make sure it's different next time */ memcpy(prior, buf, sizeof(buf)); } if (!TEST_int_le(zero_words, max_zero_words)) goto end; if (!TEST_int_ge(failures, min_failures)) goto end; testresult = 1; end: return testresult; } #endif #if IS_X_86 static int sanity_check_rdrand_bytes(void) { return sanity_check_bytes(OPENSSL_ia32_rdrand_bytes, 1000, 0, 10, 10); } static int sanity_check_rdseed_bytes(void) { /*- * RDSEED may take many retries to succeed; note that this is effectively * multiplied by the 8x retry loop in asm, and failure probabilities are * increased by the fact that we need either 4 or 8 samples depending on * the platform. */ return sanity_check_bytes(OPENSSL_ia32_rdseed_bytes, 1000, 1, 10000, 10); } #elif IS_AARCH_64 static int sanity_check_rndr_bytes(void) { return sanity_check_bytes(OPENSSL_rndr_bytes, 1000, 0, 10, 10); } static int sanity_check_rndrrs_bytes(void) { return sanity_check_bytes(OPENSSL_rndrrs_bytes, 1000, 0, 10000, 10); } #endif int setup_tests(void) { #if (IS_X_86 || IS_AARCH_64) OPENSSL_cpuid_setup(); # if IS_X_86 int have_rdseed = (OPENSSL_ia32cap_P[2] & (1 << 18)) != 0; int have_rdrand = (OPENSSL_ia32cap_P[1] & (1 << (62 - 32))) != 0; if (have_rdrand) { ADD_TEST(sanity_check_rdrand_bytes); } if (have_rdseed) { ADD_TEST(sanity_check_rdseed_bytes); } # elif IS_AARCH_64 int have_rndr_rndrrs = (OPENSSL_armcap_P & (1 << 8)) != 0; if (have_rndr_rndrrs) { ADD_TEST(sanity_check_rndr_bytes); ADD_TEST(sanity_check_rndrrs_bytes); } # endif #endif return 1; }
4,206
26.860927
77
c
openssl
openssl-master/test/recordlentest.c
/* * Copyright 2017-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 "helpers/ssltestlib.h" #include "testutil.h" static char *cert = NULL; static char *privkey = NULL; #define TEST_PLAINTEXT_OVERFLOW_OK 0 #define TEST_PLAINTEXT_OVERFLOW_NOT_OK 1 #define TEST_ENCRYPTED_OVERFLOW_TLS1_3_OK 2 #define TEST_ENCRYPTED_OVERFLOW_TLS1_3_NOT_OK 3 #define TEST_ENCRYPTED_OVERFLOW_TLS1_2_OK 4 #define TEST_ENCRYPTED_OVERFLOW_TLS1_2_NOT_OK 5 #define TOTAL_RECORD_OVERFLOW_TESTS 6 static int write_record(BIO *b, size_t len, int rectype, int recversion) { unsigned char header[SSL3_RT_HEADER_LENGTH]; size_t written; unsigned char buf[256]; memset(buf, 0, sizeof(buf)); header[0] = rectype; header[1] = (recversion >> 8) & 0xff; header[2] = recversion & 0xff; header[3] = (len >> 8) & 0xff; header[4] = len & 0xff; if (!BIO_write_ex(b, header, SSL3_RT_HEADER_LENGTH, &written) || written != SSL3_RT_HEADER_LENGTH) return 0; while (len > 0) { size_t outlen; if (len > sizeof(buf)) outlen = sizeof(buf); else outlen = len; if (!BIO_write_ex(b, buf, outlen, &written) || written != outlen) return 0; len -= outlen; } return 1; } static int fail_due_to_record_overflow(int enc) { long err = ERR_peek_error(); int reason; if (enc) reason = SSL_R_ENCRYPTED_LENGTH_TOO_LONG; else reason = SSL_R_DATA_LENGTH_TOO_LONG; if (ERR_GET_LIB(err) == ERR_LIB_SSL && ERR_GET_REASON(err) == reason) return 1; return 0; } static int test_record_overflow(int idx) { SSL_CTX *cctx = NULL, *sctx = NULL; SSL *clientssl = NULL, *serverssl = NULL; int testresult = 0; size_t len = 0; size_t written; int overf_expected; unsigned char buf; BIO *serverbio; int recversion; #ifdef OPENSSL_NO_TLS1_2 if (idx == TEST_ENCRYPTED_OVERFLOW_TLS1_2_OK || idx == TEST_ENCRYPTED_OVERFLOW_TLS1_2_NOT_OK) return 1; #endif #if defined(OPENSSL_NO_TLS1_3) \ || (defined(OPENSSL_NO_EC) && defined(OPENSSL_NO_DH)) if (idx == TEST_ENCRYPTED_OVERFLOW_TLS1_3_OK || idx == TEST_ENCRYPTED_OVERFLOW_TLS1_3_NOT_OK) return 1; #endif if (!TEST_true(create_ssl_ctx_pair(NULL, TLS_server_method(), TLS_client_method(), TLS1_VERSION, 0, &sctx, &cctx, cert, privkey))) goto end; if (idx == TEST_ENCRYPTED_OVERFLOW_TLS1_2_OK || idx == TEST_ENCRYPTED_OVERFLOW_TLS1_2_NOT_OK) { len = SSL3_RT_MAX_ENCRYPTED_LENGTH; #ifndef OPENSSL_NO_COMP len -= SSL3_RT_MAX_COMPRESSED_OVERHEAD; #endif SSL_CTX_set_max_proto_version(sctx, TLS1_2_VERSION); } else if (idx == TEST_ENCRYPTED_OVERFLOW_TLS1_3_OK || idx == TEST_ENCRYPTED_OVERFLOW_TLS1_3_NOT_OK) { len = SSL3_RT_MAX_TLS13_ENCRYPTED_LENGTH; } if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl, NULL, NULL))) goto end; serverbio = SSL_get_rbio(serverssl); if (idx == TEST_PLAINTEXT_OVERFLOW_OK || idx == TEST_PLAINTEXT_OVERFLOW_NOT_OK) { len = SSL3_RT_MAX_PLAIN_LENGTH; if (idx == TEST_PLAINTEXT_OVERFLOW_NOT_OK) len++; if (!TEST_true(write_record(serverbio, len, SSL3_RT_HANDSHAKE, TLS1_VERSION))) goto end; if (!TEST_int_le(SSL_accept(serverssl), 0)) goto end; overf_expected = (idx == TEST_PLAINTEXT_OVERFLOW_OK) ? 0 : 1; if (!TEST_int_eq(fail_due_to_record_overflow(0), overf_expected)) goto end; goto success; } if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE))) goto end; if (idx == TEST_ENCRYPTED_OVERFLOW_TLS1_2_NOT_OK || idx == TEST_ENCRYPTED_OVERFLOW_TLS1_3_NOT_OK) { overf_expected = 1; len++; } else { overf_expected = 0; } recversion = TLS1_2_VERSION; if (!TEST_true(write_record(serverbio, len, SSL3_RT_APPLICATION_DATA, recversion))) goto end; if (!TEST_false(SSL_read_ex(serverssl, &buf, sizeof(buf), &written))) goto end; if (!TEST_int_eq(fail_due_to_record_overflow(1), overf_expected)) goto end; success: testresult = 1; end: SSL_free(serverssl); SSL_free(clientssl); SSL_CTX_free(sctx); SSL_CTX_free(cctx); return testresult; } 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_record_overflow, TOTAL_RECORD_OVERFLOW_TESTS); return 1; } void cleanup_tests(void) { bio_s_mempacket_test_free(); }
5,506
25.863415
74
c
openssl
openssl-master/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; }
904
26.424242
75
c
openssl
openssl-master/test/rsa_mp_test.c
/* * Copyright 2017-2020 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 */ /* This aims to test the setting functions, including internal ones */ /* * RSA 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/crypto.h> #include <openssl/err.h> #include <openssl/rand.h> #include <openssl/bn.h> #include "testutil.h" #include <openssl/rsa.h> #include "crypto/rsa.h" #define NUM_EXTRA_PRIMES 1 DEFINE_STACK_OF(BIGNUM) /* C90 requires string should <= 509 bytes */ static const unsigned char n[] = "\x92\x60\xd0\x75\x0a\xe1\x17\xee\xe5\x5c\x3f\x3d\xea\xba\x74\x91" "\x75\x21\xa2\x62\xee\x76\x00\x7c\xdf\x8a\x56\x75\x5a\xd7\x3a\x15" "\x98\xa1\x40\x84\x10\xa0\x14\x34\xc3\xf5\xbc\x54\xa8\x8b\x57\xfa" "\x19\xfc\x43\x28\xda\xea\x07\x50\xa4\xc4\x4e\x88\xcf\xf3\xb2\x38" "\x26\x21\xb8\x0f\x67\x04\x64\x43\x3e\x43\x36\xe6\xd0\x03\xe8\xcd" "\x65\xbf\xf2\x11\xda\x14\x4b\x88\x29\x1c\x22\x59\xa0\x0a\x72\xb7" "\x11\xc1\x16\xef\x76\x86\xe8\xfe\xe3\x4e\x4d\x93\x3c\x86\x81\x87" "\xbd\xc2\x6f\x7b\xe0\x71\x49\x3c\x86\xf7\xa5\x94\x1c\x35\x10\x80" "\x6a\xd6\x7b\x0f\x94\xd8\x8f\x5c\xf5\xc0\x2a\x09\x28\x21\xd8\x62" "\x6e\x89\x32\xb6\x5c\x5b\xd8\xc9\x20\x49\xc2\x10\x93\x2b\x7a\xfa" "\x7a\xc5\x9c\x0e\x88\x6a\xe5\xc1\xed\xb0\x0d\x8c\xe2\xc5\x76\x33" "\xdb\x26\xbd\x66\x39\xbf\xf7\x3c\xee\x82\xbe\x92\x75\xc4\x02\xb4" "\xcf\x2a\x43\x88\xda\x8c\xf8\xc6\x4e\xef\xe1\xc5\xa0\xf5\xab\x80" "\x57\xc3\x9f\xa5\xc0\x58\x9c\x3e\x25\x3f\x09\x60\x33\x23\x00\xf9" "\x4b\xea\x44\x87\x7b\x58\x8e\x1e\xdb\xde\x97\xcf\x23\x60\x72\x7a" "\x09\xb7\x75\x26\x2d\x7e\xe5\x52\xb3\x31\x9b\x92\x66\xf0\x5a\x25"; static const unsigned char e[] = "\x01\x00\x01"; static const unsigned char d[] = "\x6a\x7d\xf2\xca\x63\xea\xd4\xdd\xa1\x91\xd6\x14\xb6\xb3\x85\xe0" "\xd9\x05\x6a\x3d\x6d\x5c\xfe\x07\xdb\x1d\xaa\xbe\xe0\x22\xdb\x08" "\x21\x2d\x97\x61\x3d\x33\x28\xe0\x26\x7c\x9d\xd2\x3d\x78\x7a\xbd" "\xe2\xaf\xcb\x30\x6a\xeb\x7d\xfc\xe6\x92\x46\xcc\x73\xf5\xc8\x7f" "\xdf\x06\x03\x01\x79\xa2\x11\x4b\x76\x7d\xb1\xf0\x83\xff\x84\x1c" "\x02\x5d\x7d\xc0\x0c\xd8\x24\x35\xb9\xa9\x0f\x69\x53\x69\xe9\x4d" "\xf2\x3d\x2c\xe4\x58\xbc\x3b\x32\x83\xad\x8b\xba\x2b\x8f\xa1\xba" "\x62\xe2\xdc\xe9\xac\xcf\xf3\x79\x9a\xae\x7c\x84\x00\x16\xf3\xba" "\x8e\x00\x48\xc0\xb6\xcc\x43\x39\xaf\x71\x61\x00\x3a\x5b\xeb\x86" "\x4a\x01\x64\xb2\xc1\xc9\x23\x7b\x64\xbc\x87\x55\x69\x94\x35\x1b" "\x27\x50\x6c\x33\xd4\xbc\xdf\xce\x0f\x9c\x49\x1a\x7d\x6b\x06\x28" "\xc7\xc8\x52\xbe\x4f\x0a\x9c\x31\x32\xb2\xed\x3a\x2c\x88\x81\xe9" "\xaa\xb0\x7e\x20\xe1\x7d\xeb\x07\x46\x91\xbe\x67\x77\x76\xa7\x8b" "\x5c\x50\x2e\x05\xd9\xbd\xde\x72\x12\x6b\x37\x38\x69\x5e\x2d\xd1" "\xa0\xa9\x8a\x14\x24\x7c\x65\xd8\xa7\xee\x79\x43\x2a\x09\x2c\xb0" "\x72\x1a\x12\xdf\x79\x8e\x44\xf7\xcf\xce\x0c\x49\x81\x47\xa9\xb1"; static const unsigned char p[] = "\x06\x77\xcd\xd5\x46\x9b\xc1\xd5\x58\x00\x81\xe2\xf3\x0a\x36\xb1" "\x6e\x29\x89\xd5\x2f\x31\x5f\x92\x22\x3b\x9b\x75\x30\x82\xfa\xc5" "\xf5\xde\x8a\x36\xdb\xc6\xe5\x8f\xef\x14\x37\xd6\x00\xf9\xab\x90" "\x9b\x5d\x57\x4c\xf5\x1f\x77\xc4\xbb\x8b\xdd\x9b\x67\x11\x45\xb2" "\x64\xe8\xac\xa8\x03\x0f\x16\x0d\x5d\x2d\x53\x07\x23\xfb\x62\x0d" "\xe6\x16\xd3\x23\xe8\xb3"; static const unsigned char q[] = "\x06\x66\x9a\x70\x53\xd6\x72\x74\xfd\xea\x45\xc3\xc0\x17\xae\xde" "\x79\x17\xae\x79\xde\xfc\x0e\xf7\xa4\x3a\x8c\x43\x8f\xc7\x8a\xa2" "\x2c\x51\xc4\xd0\x72\x89\x73\x5c\x61\xbe\xfd\x54\x3f\x92\x65\xde" "\x4d\x65\x71\x70\xf6\xf2\xe5\x98\xb9\x0f\xd1\x0b\xe6\x95\x09\x4a" "\x7a\xdf\xf3\x10\x16\xd0\x60\xfc\xa5\x10\x34\x97\x37\x6f\x0a\xd5" "\x5d\x8f\xd4\xc3\xa0\x5b"; static const unsigned char dmp1[] = "\x05\x7c\x9e\x1c\xbd\x90\x25\xe7\x40\x86\xf5\xa8\x3b\x7a\x3f\x99" "\x56\x95\x60\x3a\x7b\x95\x4b\xb8\xa0\xd7\xa5\xf1\xcc\xdc\x5f\xb5" "\x8c\xf4\x62\x95\x54\xed\x2e\x12\x62\xc2\xe8\xf6\xde\xce\xed\x8e" "\x77\x6d\xc0\x40\x25\x74\xb3\x5a\x2d\xaa\xe1\xac\x11\xcb\xe2\x2f" "\x0a\x51\x23\x1e\x47\xb2\x05\x88\x02\xb2\x0f\x4b\xf0\x67\x30\xf0" "\x0f\x6e\xef\x5f\xf7\xe7"; static const unsigned char dmq1[] = "\x01\xa5\x6b\xbc\xcd\xe3\x0e\x46\xc6\x72\xf5\x04\x56\x28\x01\x22" "\x58\x74\x5d\xbc\x1c\x3c\x29\x41\x49\x6c\x81\x5c\x72\xe2\xf7\xe5" "\xa3\x8e\x58\x16\xe0\x0e\x37\xac\x1f\xbb\x75\xfd\xaf\xe7\xdf\xe9" "\x1f\x70\xa2\x8f\x52\x03\xc0\x46\xd9\xf9\x96\x63\x00\x27\x7e\x5f" "\x38\x60\xd6\x6b\x61\xe2\xaf\xbe\xea\x58\xd3\x9d\xbc\x75\x03\x8d" "\x42\x65\xd6\x6b\x85\x97"; static const unsigned char iqmp[] = "\x03\xa1\x8b\x80\xe4\xd8\x87\x25\x17\x5d\xcc\x8d\xa9\x8a\x22\x2b" "\x6c\x15\x34\x6f\x80\xcc\x1c\x44\x04\x68\xbc\x03\xcd\x95\xbb\x69" "\x37\x61\x48\xb4\x23\x13\x08\x16\x54\x6a\xa1\x7c\xf5\xd4\x3a\xe1" "\x4f\xa4\x0c\xf5\xaf\x80\x85\x27\x06\x0d\x70\xc0\xc5\x19\x28\xfe" "\xee\x8e\x86\x21\x98\x8a\x37\xb7\xe5\x30\x25\x70\x93\x51\x2d\x49" "\x85\x56\xb3\x0c\x2b\x96"; static const unsigned char ex_prime[] = "\x03\x89\x22\xa0\xb7\x3a\x91\xcb\x5e\x0c\xfd\x73\xde\xa7\x38\xa9" "\x47\x43\xd6\x02\xbf\x2a\xb9\x3c\x48\xf3\x06\xd6\x58\x35\x50\x56" "\x16\x5c\x34\x9b\x61\x87\xc8\xaa\x0a\x5d\x8a\x0a\xcd\x9c\x41\xd9" "\x96\x24\xe0\xa9\x9b\x26\xb7\xa8\x08\xc9\xea\xdc\xa7\x15\xfb\x62" "\xa0\x2d\x90\xe6\xa7\x55\x6e\xc6\x6c\xff\xd6\x10\x6d\xfa\x2e\x04" "\x50\xec\x5c\x66\xe4\x05"; static const unsigned char ex_exponent[] = "\x02\x0a\xcd\xc3\x82\xd2\x03\xb0\x31\xac\xd3\x20\x80\x34\x9a\x57" "\xbc\x60\x04\x57\x25\xd0\x29\x9a\x16\x90\xb9\x1c\x49\x6a\xd1\xf2" "\x47\x8c\x0e\x9e\xc9\x20\xc2\xd8\xe4\x8f\xce\xd2\x1a\x9c\xec\xb4" "\x1f\x33\x41\xc8\xf5\x62\xd1\xa5\xef\x1d\xa1\xd8\xbd\x71\xc6\xf7" "\xda\x89\x37\x2e\xe2\xec\x47\xc5\xb8\xe3\xb4\xe3\x5c\x82\xaa\xdd" "\xb7\x58\x2e\xaf\x07\x79"; static const unsigned char ex_coefficient[] = "\x00\x9c\x09\x88\x9b\xc8\x57\x08\x69\x69\xab\x2d\x9e\x29\x1c\x3c" "\x6d\x59\x33\x12\x0d\x2b\x09\x2e\xaf\x01\x2c\x27\x01\xfc\xbd\x26" "\x13\xf9\x2d\x09\x22\x4e\x49\x11\x03\x82\x88\x87\xf4\x43\x1d\xac" "\xca\xec\x86\xf7\x23\xf1\x64\xf3\xf5\x81\xf0\x37\x36\xcf\x67\xff" "\x1a\xff\x7a\xc7\xf9\xf9\x67\x2d\xa0\x9d\x61\xf8\xf6\x47\x5c\x2f" "\xe7\x66\xe8\x3c\x3a\xe8"; static int key2048_key(RSA *key) { if (!TEST_int_eq(RSA_set0_key(key, BN_bin2bn(n, sizeof(n) - 1, NULL), BN_bin2bn(e, sizeof(e) - 1, NULL), BN_bin2bn(d, sizeof(d) - 1, NULL)), 1)) return 0; return RSA_size(key); } static int key2048p3_v1(RSA *key) { BIGNUM **pris = NULL, **exps = NULL, **coeffs = NULL; int rv = RSA_size(key); if (!TEST_int_eq(RSA_set0_factors(key, BN_bin2bn(p, sizeof(p) - 1, NULL), BN_bin2bn(q, sizeof(q) - 1, NULL)), 1)) goto err; if (!TEST_int_eq(RSA_set0_crt_params(key, BN_bin2bn(dmp1, sizeof(dmp1) - 1, NULL), BN_bin2bn(dmq1, sizeof(dmq1) - 1, NULL), BN_bin2bn(iqmp, sizeof(iqmp) - 1, NULL)), 1)) return 0; pris = OPENSSL_zalloc(sizeof(BIGNUM *)); exps = OPENSSL_zalloc(sizeof(BIGNUM *)); coeffs = OPENSSL_zalloc(sizeof(BIGNUM *)); if (!TEST_ptr(pris) || !TEST_ptr(exps) || !TEST_ptr(coeffs)) goto err; pris[0] = BN_bin2bn(ex_prime, sizeof(ex_prime) - 1, NULL); exps[0] = BN_bin2bn(ex_exponent, sizeof(ex_exponent) - 1, NULL); coeffs[0] = BN_bin2bn(ex_coefficient, sizeof(ex_coefficient) - 1, NULL); if (!TEST_ptr(pris[0]) || !TEST_ptr(exps[0]) || !TEST_ptr(coeffs[0])) goto err; if (!TEST_true(RSA_set0_multi_prime_params(key, pris, exps, coeffs, NUM_EXTRA_PRIMES))) goto err; ret: OPENSSL_free(pris); OPENSSL_free(exps); OPENSSL_free(coeffs); return rv; err: if (pris != NULL) BN_free(pris[0]); if (exps != NULL) BN_free(exps[0]); if (coeffs != NULL) BN_free(coeffs[0]); rv = 0; goto ret; } static int key2048p3_v2(RSA *key) { STACK_OF(BIGNUM) *primes = NULL, *exps = NULL, *coeffs = NULL; BIGNUM *num = NULL; int rv = RSA_size(key); if (!TEST_ptr(primes = sk_BIGNUM_new_null()) || !TEST_ptr(exps = sk_BIGNUM_new_null()) || !TEST_ptr(coeffs = sk_BIGNUM_new_null())) goto err; if (!TEST_ptr(num = BN_bin2bn(p, sizeof(p) - 1, NULL)) || !TEST_int_ne(sk_BIGNUM_push(primes, num), 0) || !TEST_ptr(num = BN_bin2bn(q, sizeof(q) - 1, NULL)) || !TEST_int_ne(sk_BIGNUM_push(primes, num), 0) || !TEST_ptr(num = BN_bin2bn(ex_prime, sizeof(ex_prime) - 1, NULL)) || !TEST_int_ne(sk_BIGNUM_push(primes, num), 0)) goto err; if (!TEST_ptr(num = BN_bin2bn(dmp1, sizeof(dmp1) - 1, NULL)) || !TEST_int_ne(sk_BIGNUM_push(exps, num), 0) || !TEST_ptr(num = BN_bin2bn(dmq1, sizeof(dmq1) - 1, NULL)) || !TEST_int_ne(sk_BIGNUM_push(exps, num), 0) || !TEST_ptr(num = BN_bin2bn(ex_exponent, sizeof(ex_exponent) - 1, NULL)) || !TEST_int_ne(sk_BIGNUM_push(exps, num), 0)) goto err; if (!TEST_ptr(num = BN_bin2bn(iqmp, sizeof(iqmp) - 1, NULL)) || !TEST_int_ne(sk_BIGNUM_push(coeffs, num), 0) || !TEST_ptr(num = BN_bin2bn(ex_coefficient, sizeof(ex_coefficient) - 1, NULL)) || !TEST_int_ne(sk_BIGNUM_push(coeffs, num), 0)) goto err; if (!TEST_true(ossl_rsa_set0_all_params(key, primes, exps, coeffs))) goto err; ret: sk_BIGNUM_free(primes); sk_BIGNUM_free(exps); sk_BIGNUM_free(coeffs); return rv; err: sk_BIGNUM_pop_free(primes, BN_free); sk_BIGNUM_pop_free(exps, BN_free); sk_BIGNUM_pop_free(coeffs, BN_free); primes = exps = coeffs = NULL; rv = 0; goto ret; } static int test_rsa_mp(int i) { int ret = 0; RSA *key; unsigned char ptext[256]; unsigned char ctext[256]; static unsigned char ptext_ex[] = "\x54\x85\x9b\x34\x2c\x49\xea\x2a"; int plen; int clen = 0; int num; static int (*param_set[])(RSA *) = { key2048p3_v1, key2048p3_v2, }; plen = sizeof(ptext_ex) - 1; key = RSA_new(); if (!TEST_ptr(key)) goto err; if (!TEST_int_eq((clen = key2048_key(key)), 256) || !TEST_int_eq((clen = param_set[i](key)), 256)) goto err; if (!TEST_true(RSA_check_key_ex(key, NULL))) goto err; num = RSA_public_encrypt(plen, ptext_ex, ctext, key, RSA_PKCS1_PADDING); if (!TEST_int_eq(num, clen)) goto err; num = RSA_private_decrypt(num, ctext, ptext, key, RSA_PKCS1_PADDING); if (!TEST_mem_eq(ptext, num, ptext_ex, plen)) goto err; ret = 1; err: RSA_free(key); return ret; } static int test_rsa_mp_gen_bad_input(void) { int ret = 0; RSA *rsa = NULL; BIGNUM *ebn = NULL; if (!TEST_ptr(rsa = RSA_new())) goto err; if (!TEST_ptr(ebn = BN_new())) goto err; if (!TEST_true(BN_set_word(ebn, 65537))) goto err; /* Test that a NULL exponent fails and does not segfault */ if (!TEST_int_eq(RSA_generate_multi_prime_key(rsa, 1024, 2, NULL, NULL), 0)) goto err; /* Test invalid bitsize fails */ if (!TEST_int_eq(RSA_generate_multi_prime_key(rsa, 500, 2, ebn, NULL), 0)) goto err; /* Test invalid prime count fails */ if (!TEST_int_eq(RSA_generate_multi_prime_key(rsa, 1024, 1, ebn, NULL), 0)) goto err; ret = 1; err: BN_free(ebn); RSA_free(rsa); return ret; } int setup_tests(void) { ADD_TEST(test_rsa_mp_gen_bad_input); ADD_ALL_TESTS(test_rsa_mp, 2); return 1; }
12,377
36.509091
87
c
openssl
openssl-master/test/rsa_sp800_56b_test.c
/* * Copyright 2018-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 */ /* * RSA 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 "internal/nelem.h" #include <openssl/crypto.h> #include <openssl/err.h> #include <openssl/rand.h> #include <openssl/bn.h> #include "testutil.h" #include "rsa_local.h" #include <openssl/rsa.h> /* taken from RSA2 cavs data */ static const unsigned char cav_e[] = { 0x01,0x00,0x01 }; static const unsigned char cav_p[] = { 0xcf,0x72,0x1b,0x9a,0xfd,0x0d,0x22,0x1a,0x74,0x50,0x97,0x22,0x76,0xd8,0xc0, 0xc2,0xfd,0x08,0x81,0x05,0xdd,0x18,0x21,0x99,0x96,0xd6,0x5c,0x79,0xe3,0x02, 0x81,0xd7,0x0e,0x3f,0x3b,0x34,0xda,0x61,0xc9,0x2d,0x84,0x86,0x62,0x1e,0x3d, 0x5d,0xbf,0x92,0x2e,0xcd,0x35,0x3d,0x6e,0xb9,0x59,0x16,0xc9,0x82,0x50,0x41, 0x30,0x45,0x67,0xaa,0xb7,0xbe,0xec,0xea,0x4b,0x9e,0xa0,0xc3,0x05,0xbc,0x4c, 0x01,0xa5,0x4b,0xbd,0xa4,0x20,0xb5,0x20,0xd5,0x59,0x6f,0x82,0x5c,0x8f,0x4f, 0xe0,0x3a,0x4e,0x7e,0xfe,0x44,0xf3,0x3c,0xc0,0x0e,0x14,0x2b,0x32,0xe6,0x28, 0x8b,0x63,0x87,0x00,0xc3,0x53,0x4a,0x5b,0x71,0x7a,0x5b,0x28,0x40,0xc4,0x18, 0xb6,0x77,0x0b,0xab,0x59,0xa4,0x96,0x7d }; static const unsigned char cav_q[] = { 0xfe,0xab,0xf2,0x7c,0x16,0x4a,0xf0,0x8d,0x31,0xc6,0x0a,0x82,0xe2,0xae,0xbb, 0x03,0x7e,0x7b,0x20,0x4e,0x64,0xb0,0x16,0xad,0x3c,0x01,0x1a,0xd3,0x54,0xbf, 0x2b,0xa4,0x02,0x9e,0xc3,0x0d,0x60,0x3d,0x1f,0xb9,0xc0,0x0d,0xe6,0x97,0x68, 0xbb,0x8c,0x81,0xd5,0xc1,0x54,0x96,0x0f,0x99,0xf0,0xa8,0xa2,0xf3,0xc6,0x8e, 0xec,0xbc,0x31,0x17,0x70,0x98,0x24,0xa3,0x36,0x51,0xa8,0x54,0xc4,0x44,0xdd, 0xf7,0x7e,0xda,0x47,0x4a,0x67,0x44,0x5d,0x4e,0x75,0xf0,0x4d,0x00,0x68,0xe1, 0x4a,0xec,0x1f,0x45,0xf9,0xe6,0xca,0x38,0x95,0x48,0x6f,0xdc,0x9d,0x1b,0xa3, 0x4b,0xfd,0x08,0x4b,0x54,0xcd,0xeb,0x3d,0xef,0x33,0x11,0x6e,0xce,0xe4,0x5d, 0xef,0xa9,0x58,0x5c,0x87,0x4d,0xc8,0xcf }; static const unsigned char cav_n[] = { 0xce,0x5e,0x8d,0x1a,0xa3,0x08,0x7a,0x2d,0xb4,0x49,0x48,0xf0,0x06,0xb6,0xfe, 0xba,0x2f,0x39,0x7c,0x7b,0xe0,0x5d,0x09,0x2d,0x57,0x4e,0x54,0x60,0x9c,0xe5, 0x08,0x4b,0xe1,0x1a,0x73,0xc1,0x5e,0x2f,0xb6,0x46,0xd7,0x81,0xca,0xbc,0x98, 0xd2,0xf9,0xef,0x1c,0x92,0x8c,0x8d,0x99,0x85,0x28,0x52,0xd6,0xd5,0xab,0x70, 0x7e,0x9e,0xa9,0x87,0x82,0xc8,0x95,0x64,0xeb,0xf0,0x6c,0x0f,0x3f,0xe9,0x02, 0x29,0x2e,0x6d,0xa1,0xec,0xbf,0xdc,0x23,0xdf,0x82,0x4f,0xab,0x39,0x8d,0xcc, 0xac,0x21,0x51,0x14,0xf8,0xef,0xec,0x73,0x80,0x86,0xa3,0xcf,0x8f,0xd5,0xcf, 0x22,0x1f,0xcc,0x23,0x2f,0xba,0xcb,0xf6,0x17,0xcd,0x3a,0x1f,0xd9,0x84,0xb9, 0x88,0xa7,0x78,0x0f,0xaa,0xc9,0x04,0x01,0x20,0x72,0x5d,0x2a,0xfe,0x5b,0xdd, 0x16,0x5a,0xed,0x83,0x02,0x96,0x39,0x46,0x37,0x30,0xc1,0x0d,0x87,0xc2,0xc8, 0x33,0x38,0xed,0x35,0x72,0xe5,0x29,0xf8,0x1f,0x23,0x60,0xe1,0x2a,0x5b,0x1d, 0x6b,0x53,0x3f,0x07,0xc4,0xd9,0xbb,0x04,0x0c,0x5c,0x3f,0x0b,0xc4,0xd4,0x61, 0x96,0x94,0xf1,0x0f,0x4a,0x49,0xac,0xde,0xd2,0xe8,0x42,0xb3,0x4a,0x0b,0x64, 0x7a,0x32,0x5f,0x2b,0x5b,0x0f,0x8b,0x8b,0xe0,0x33,0x23,0x34,0x64,0xf8,0xb5, 0x7f,0x69,0x60,0xb8,0x71,0xe9,0xff,0x92,0x42,0xb1,0xf7,0x23,0xa8,0xa7,0x92, 0x04,0x3d,0x6b,0xff,0xf7,0xab,0xbb,0x14,0x1f,0x4c,0x10,0x97,0xd5,0x6b,0x71, 0x12,0xfd,0x93,0xa0,0x4a,0x3b,0x75,0x72,0x40,0x96,0x1c,0x5f,0x40,0x40,0x57, 0x13 }; static const unsigned char cav_d[] = { 0x47,0x47,0x49,0x1d,0x66,0x2a,0x4b,0x68,0xf5,0xd8,0x4a,0x24,0xfd,0x6c,0xbf, 0x56,0xb7,0x70,0xf7,0x9a,0x21,0xc8,0x80,0x9e,0xf4,0x84,0xcd,0x88,0x01,0x28, 0xea,0x50,0xab,0x13,0x63,0xdf,0xea,0x14,0x38,0xb5,0x07,0x42,0x81,0x2f,0xda, 0xe9,0x24,0x02,0x7e,0xaf,0xef,0x74,0x09,0x0e,0x80,0xfa,0xfb,0xd1,0x19,0x41, 0xe5,0xba,0x0f,0x7c,0x0a,0xa4,0x15,0x55,0xa2,0x58,0x8c,0x3a,0x48,0x2c,0xc6, 0xde,0x4a,0x76,0xfb,0x72,0xb6,0x61,0xe6,0xd2,0x10,0x44,0x4c,0x33,0xb8,0xd2, 0x74,0xb1,0x9d,0x3b,0xcd,0x2f,0xb1,0x4f,0xc3,0x98,0xbd,0x83,0xb7,0x7e,0x75, 0xe8,0xa7,0x6a,0xee,0xcc,0x51,0x8c,0x99,0x17,0x67,0x7f,0x27,0xf9,0x0d,0x6a, 0xb7,0xd4,0x80,0x17,0x89,0x39,0x9c,0xf3,0xd7,0x0f,0xdf,0xb0,0x55,0x80,0x1d, 0xaf,0x57,0x2e,0xd0,0xf0,0x4f,0x42,0x69,0x55,0xbc,0x83,0xd6,0x97,0x83,0x7a, 0xe6,0xc6,0x30,0x6d,0x3d,0xb5,0x21,0xa7,0xc4,0x62,0x0a,0x20,0xce,0x5e,0x5a, 0x17,0x98,0xb3,0x6f,0x6b,0x9a,0xeb,0x6b,0xa3,0xc4,0x75,0xd8,0x2b,0xdc,0x5c, 0x6f,0xec,0x5d,0x49,0xac,0xa8,0xa4,0x2f,0xb8,0x8c,0x4f,0x2e,0x46,0x21,0xee, 0x72,0x6a,0x0e,0x22,0x80,0x71,0xc8,0x76,0x40,0x44,0x61,0x16,0xbf,0xa5,0xf8, 0x89,0xc7,0xe9,0x87,0xdf,0xbd,0x2e,0x4b,0x4e,0xc2,0x97,0x53,0xe9,0x49,0x1c, 0x05,0xb0,0x0b,0x9b,0x9f,0x21,0x19,0x41,0xe9,0xf5,0x61,0xd7,0x33,0x2e,0x2c, 0x94,0xb8,0xa8,0x9a,0x3a,0xcc,0x6a,0x24,0x8d,0x19,0x13,0xee,0xb9,0xb0,0x48, 0x61 }; /* helper function */ static BIGNUM *bn_load_new(const unsigned char *data, int sz) { BIGNUM *ret = BN_new(); if (ret != NULL) BN_bin2bn(data, sz, ret); return ret; } /* Check that small rsa exponents are allowed in non FIPS mode */ static int test_check_public_exponent(void) { int ret = 0; BIGNUM *e = NULL; ret = TEST_ptr(e = BN_new()) /* e is too small will fail */ && TEST_true(BN_set_word(e, 1)) && TEST_false(ossl_rsa_check_public_exponent(e)) /* e is even will fail */ && TEST_true(BN_set_word(e, 65536)) && TEST_false(ossl_rsa_check_public_exponent(e)) /* e is ok */ && TEST_true(BN_set_word(e, 3)) && TEST_true(ossl_rsa_check_public_exponent(e)) && TEST_true(BN_set_word(e, 17)) && TEST_true(ossl_rsa_check_public_exponent(e)) && TEST_true(BN_set_word(e, 65537)) && TEST_true(ossl_rsa_check_public_exponent(e)) /* e = 2^256 + 1 is ok */ && TEST_true(BN_lshift(e, BN_value_one(), 256)) && TEST_true(BN_add(e, e, BN_value_one())) && TEST_true(ossl_rsa_check_public_exponent(e)); BN_free(e); return ret; } static int test_check_prime_factor_range(void) { int ret = 0; BN_CTX *ctx = NULL; BIGNUM *p = NULL; BIGNUM *bn_p1 = NULL, *bn_p2 = NULL, *bn_p3 = NULL, *bn_p4 = NULL; /* Some range checks that are larger than 32 bits */ static const unsigned char p1[] = { 0x0B, 0x50, 0x4F, 0x33, 0x3F }; static const unsigned char p2[] = { 0x10, 0x00, 0x00, 0x00, 0x00 }; static const unsigned char p3[] = { 0x0B, 0x50, 0x4F, 0x33, 0x40 }; static const unsigned char p4[] = { 0x0F, 0xFF, 0xFF, 0xFF, 0xFF }; /* (√2)(2^(nbits/2 - 1) <= p <= 2^(nbits/2) - 1 * For 8 bits: 0xB.504F <= p <= 0xF * for 72 bits: 0xB504F333F. <= p <= 0xF_FFFF_FFFF */ ret = TEST_ptr(p = BN_new()) && TEST_ptr(bn_p1 = bn_load_new(p1, sizeof(p1))) && TEST_ptr(bn_p2 = bn_load_new(p2, sizeof(p2))) && TEST_ptr(bn_p3 = bn_load_new(p3, sizeof(p3))) && TEST_ptr(bn_p4 = bn_load_new(p4, sizeof(p4))) && TEST_ptr(ctx = BN_CTX_new()) && TEST_true(BN_set_word(p, 0xA)) && TEST_false(ossl_rsa_check_prime_factor_range(p, 8, ctx)) && TEST_true(BN_set_word(p, 0x10)) && TEST_false(ossl_rsa_check_prime_factor_range(p, 8, ctx)) && TEST_true(BN_set_word(p, 0xB)) && TEST_false(ossl_rsa_check_prime_factor_range(p, 8, ctx)) && TEST_true(BN_set_word(p, 0xC)) && TEST_true(ossl_rsa_check_prime_factor_range(p, 8, ctx)) && TEST_true(BN_set_word(p, 0xF)) && TEST_true(ossl_rsa_check_prime_factor_range(p, 8, ctx)) && TEST_false(ossl_rsa_check_prime_factor_range(bn_p1, 72, ctx)) && TEST_false(ossl_rsa_check_prime_factor_range(bn_p2, 72, ctx)) && TEST_true(ossl_rsa_check_prime_factor_range(bn_p3, 72, ctx)) && TEST_true(ossl_rsa_check_prime_factor_range(bn_p4, 72, ctx)); BN_free(bn_p4); BN_free(bn_p3); BN_free(bn_p2); BN_free(bn_p1); BN_free(p); BN_CTX_free(ctx); return ret; } static int test_check_prime_factor(void) { int ret = 0; BN_CTX *ctx = NULL; BIGNUM *p = NULL, *e = NULL; BIGNUM *bn_p1 = NULL, *bn_p2 = NULL, *bn_p3 = NULL; /* Some range checks that are larger than 32 bits */ static const unsigned char p1[] = { 0x0B, 0x50, 0x4f, 0x33, 0x73 }; static const unsigned char p2[] = { 0x0B, 0x50, 0x4f, 0x33, 0x75 }; static const unsigned char p3[] = { 0x0F, 0x50, 0x00, 0x03, 0x75 }; ret = TEST_ptr(p = BN_new()) && TEST_ptr(bn_p1 = bn_load_new(p1, sizeof(p1))) && TEST_ptr(bn_p2 = bn_load_new(p2, sizeof(p2))) && TEST_ptr(bn_p3 = bn_load_new(p3, sizeof(p3))) && TEST_ptr(e = BN_new()) && TEST_ptr(ctx = BN_CTX_new()) /* Fails the prime test */ && TEST_true(BN_set_word(e, 0x1)) && TEST_false(ossl_rsa_check_prime_factor(bn_p1, e, 72, ctx)) /* p is prime and in range and gcd(p-1, e) = 1 */ && TEST_true(ossl_rsa_check_prime_factor(bn_p2, e, 72, ctx)) /* gcd(p-1,e) = 1 test fails */ && TEST_true(BN_set_word(e, 0x2)) && TEST_false(ossl_rsa_check_prime_factor(p, e, 72, ctx)) /* p fails the range check */ && TEST_true(BN_set_word(e, 0x1)) && TEST_false(ossl_rsa_check_prime_factor(bn_p3, e, 72, ctx)); BN_free(bn_p3); BN_free(bn_p2); BN_free(bn_p1); BN_free(e); BN_free(p); BN_CTX_free(ctx); return ret; } /* This test uses legacy functions because they can take invalid numbers */ static int test_check_private_exponent(void) { int ret = 0; RSA *key = NULL; BN_CTX *ctx = NULL; BIGNUM *p = NULL, *q = NULL, *e = NULL, *d = NULL, *n = NULL; ret = TEST_ptr(key = RSA_new()) && TEST_ptr(ctx = BN_CTX_new()) && TEST_ptr(p = BN_new()) && TEST_ptr(q = BN_new()) /* lcm(15-1,17-1) = 14*16 / 2 = 112 */ && TEST_true(BN_set_word(p, 15)) && TEST_true(BN_set_word(q, 17)) && TEST_true(RSA_set0_factors(key, p, q)); if (!ret) { BN_free(p); BN_free(q); goto end; } ret = TEST_ptr(e = BN_new()) && TEST_ptr(d = BN_new()) && TEST_ptr(n = BN_new()) && TEST_true(BN_set_word(e, 5)) && TEST_true(BN_set_word(d, 157)) && TEST_true(BN_set_word(n, 15*17)) && TEST_true(RSA_set0_key(key, n, e, d)); if (!ret) { BN_free(e); BN_free(d); BN_free(n); goto end; } /* fails since d >= lcm(p-1, q-1) */ ret = TEST_false(ossl_rsa_check_private_exponent(key, 8, ctx)) && TEST_true(BN_set_word(d, 45)) /* d is correct size and 1 = e.d mod lcm(p-1, q-1) */ && TEST_true(ossl_rsa_check_private_exponent(key, 8, ctx)) /* d is too small compared to nbits */ && TEST_false(ossl_rsa_check_private_exponent(key, 16, ctx)) /* d is too small compared to nbits */ && TEST_true(BN_set_word(d, 16)) && TEST_false(ossl_rsa_check_private_exponent(key, 8, ctx)) /* fail if 1 != e.d mod lcm(p-1, q-1) */ && TEST_true(BN_set_word(d, 46)) && TEST_false(ossl_rsa_check_private_exponent(key, 8, ctx)); end: RSA_free(key); BN_CTX_free(ctx); return ret; } static int test_check_crt_components(void) { const int P = 15; const int Q = 17; const int E = 5; const int N = P*Q; const int DP = 3; const int DQ = 13; const int QINV = 8; int ret = 0; RSA *key = NULL; BN_CTX *ctx = NULL; BIGNUM *p = NULL, *q = NULL, *e = NULL; ret = TEST_ptr(key = RSA_new()) && TEST_ptr(ctx = BN_CTX_new()) && TEST_ptr(p = BN_new()) && TEST_ptr(q = BN_new()) && TEST_ptr(e = BN_new()) && TEST_true(BN_set_word(p, P)) && TEST_true(BN_set_word(q, Q)) && TEST_true(BN_set_word(e, E)) && TEST_true(RSA_set0_factors(key, p, q)); if (!ret) { BN_free(p); BN_free(q); goto end; } ret = TEST_int_eq(ossl_rsa_sp800_56b_derive_params_from_pq(key, 8, e, ctx), 1) && TEST_BN_eq_word(key->n, N) && TEST_BN_eq_word(key->dmp1, DP) && TEST_BN_eq_word(key->dmq1, DQ) && TEST_BN_eq_word(key->iqmp, QINV) && TEST_true(ossl_rsa_check_crt_components(key, ctx)) /* (a) 1 < dP < (p – 1). */ && TEST_true(BN_set_word(key->dmp1, 1)) && TEST_false(ossl_rsa_check_crt_components(key, ctx)) && TEST_true(BN_set_word(key->dmp1, P-1)) && TEST_false(ossl_rsa_check_crt_components(key, ctx)) && TEST_true(BN_set_word(key->dmp1, DP)) /* (b) 1 < dQ < (q - 1). */ && TEST_true(BN_set_word(key->dmq1, 1)) && TEST_false(ossl_rsa_check_crt_components(key, ctx)) && TEST_true(BN_set_word(key->dmq1, Q-1)) && TEST_false(ossl_rsa_check_crt_components(key, ctx)) && TEST_true(BN_set_word(key->dmq1, DQ)) /* (c) 1 < qInv < p */ && TEST_true(BN_set_word(key->iqmp, 1)) && TEST_false(ossl_rsa_check_crt_components(key, ctx)) && TEST_true(BN_set_word(key->iqmp, P)) && TEST_false(ossl_rsa_check_crt_components(key, ctx)) && TEST_true(BN_set_word(key->iqmp, QINV)) /* (d) 1 = (dP . e) mod (p - 1)*/ && TEST_true(BN_set_word(key->dmp1, DP+1)) && TEST_false(ossl_rsa_check_crt_components(key, ctx)) && TEST_true(BN_set_word(key->dmp1, DP)) /* (e) 1 = (dQ . e) mod (q - 1) */ && TEST_true(BN_set_word(key->dmq1, DQ-1)) && TEST_false(ossl_rsa_check_crt_components(key, ctx)) && TEST_true(BN_set_word(key->dmq1, DQ)) /* (f) 1 = (qInv . q) mod p */ && TEST_true(BN_set_word(key->iqmp, QINV+1)) && TEST_false(ossl_rsa_check_crt_components(key, ctx)) && TEST_true(BN_set_word(key->iqmp, QINV)) /* check defaults are still valid */ && TEST_true(ossl_rsa_check_crt_components(key, ctx)); end: BN_free(e); RSA_free(key); BN_CTX_free(ctx); return ret; } static const struct derive_from_pq_test { int p, q, e; } derive_from_pq_tests[] = { { 15, 17, 6 }, /* Mod_inverse failure */ { 0, 17, 5 }, /* d is too small */ }; static int test_derive_params_from_pq_fail(int tst) { int ret = 0; RSA *key = NULL; BN_CTX *ctx = NULL; BIGNUM *p = NULL, *q = NULL, *e = NULL; ret = TEST_ptr(key = RSA_new()) && TEST_ptr(ctx = BN_CTX_new()) && TEST_ptr(p = BN_new()) && TEST_ptr(q = BN_new()) && TEST_ptr(e = BN_new()) && TEST_true(BN_set_word(p, derive_from_pq_tests[tst].p)) && TEST_true(BN_set_word(q, derive_from_pq_tests[tst].q)) && TEST_true(BN_set_word(e, derive_from_pq_tests[tst].e)) && TEST_true(RSA_set0_factors(key, p, q)); if (!ret) { BN_free(p); BN_free(q); goto end; } ret = TEST_int_le(ossl_rsa_sp800_56b_derive_params_from_pq(key, 8, e, ctx), 0); end: BN_free(e); RSA_free(key); BN_CTX_free(ctx); return ret; } static int test_pq_diff(void) { int ret = 0; BIGNUM *tmp = NULL, *p = NULL, *q = NULL; ret = TEST_ptr(tmp = BN_new()) && TEST_ptr(p = BN_new()) && TEST_ptr(q = BN_new()) /* |1-(2+1)| > 2^1 */ && TEST_true(BN_set_word(p, 1)) && TEST_true(BN_set_word(q, 1+2)) && TEST_false(ossl_rsa_check_pminusq_diff(tmp, p, q, 202)) /* Check |p - q| > 2^(nbits/2 - 100) */ && TEST_true(BN_set_word(q, 1+3)) && TEST_true(ossl_rsa_check_pminusq_diff(tmp, p, q, 202)) && TEST_true(BN_set_word(p, 1+3)) && TEST_true(BN_set_word(q, 1)) && TEST_true(ossl_rsa_check_pminusq_diff(tmp, p, q, 202)); BN_free(p); BN_free(q); BN_free(tmp); return ret; } static int test_invalid_keypair(void) { int ret = 0; RSA *key = NULL; BN_CTX *ctx = NULL; BIGNUM *p = NULL, *q = NULL, *n = NULL, *e = NULL, *d = NULL; ret = TEST_ptr(key = RSA_new()) && TEST_ptr(ctx = BN_CTX_new()) /* NULL parameters */ && TEST_false(ossl_rsa_sp800_56b_check_keypair(key, NULL, -1, 2048)) /* load key */ && TEST_ptr(p = bn_load_new(cav_p, sizeof(cav_p))) && TEST_ptr(q = bn_load_new(cav_q, sizeof(cav_q))) && TEST_true(RSA_set0_factors(key, p, q)); if (!ret) { BN_free(p); BN_free(q); goto end; } ret = TEST_ptr(e = bn_load_new(cav_e, sizeof(cav_e))) && TEST_ptr(n = bn_load_new(cav_n, sizeof(cav_n))) && TEST_ptr(d = bn_load_new(cav_d, sizeof(cav_d))) && TEST_true(RSA_set0_key(key, n, e, d)); if (!ret) { BN_free(e); BN_free(n); BN_free(d); goto end; } /* bad strength/key size */ ret = TEST_false(ossl_rsa_sp800_56b_check_keypair(key, NULL, 100, 2048)) && TEST_false(ossl_rsa_sp800_56b_check_keypair(key, NULL, 112, 1024)) && TEST_false(ossl_rsa_sp800_56b_check_keypair(key, NULL, 128, 2048)) && TEST_false(ossl_rsa_sp800_56b_check_keypair(key, NULL, 140, 3072)) /* mismatching exponent */ && TEST_false(ossl_rsa_sp800_56b_check_keypair(key, BN_value_one(), -1, 2048)) /* bad exponent */ && TEST_true(BN_add_word(e, 1)) && TEST_false(ossl_rsa_sp800_56b_check_keypair(key, NULL, -1, 2048)) && TEST_true(BN_sub_word(e, 1)) /* mismatch between bits and modulus */ && TEST_false(ossl_rsa_sp800_56b_check_keypair(key, NULL, -1, 3072)) && TEST_true(ossl_rsa_sp800_56b_check_keypair(key, e, 112, 2048)) /* check n == pq failure */ && TEST_true(BN_add_word(n, 1)) && TEST_false(ossl_rsa_sp800_56b_check_keypair(key, NULL, -1, 2048)) && TEST_true(BN_sub_word(n, 1)) /* check p */ && TEST_true(BN_sub_word(p, 2)) && TEST_true(BN_mul(n, p, q, ctx)) && TEST_false(ossl_rsa_sp800_56b_check_keypair(key, NULL, -1, 2048)) && TEST_true(BN_add_word(p, 2)) && TEST_true(BN_mul(n, p, q, ctx)) /* check q */ && TEST_true(BN_sub_word(q, 2)) && TEST_true(BN_mul(n, p, q, ctx)) && TEST_false(ossl_rsa_sp800_56b_check_keypair(key, NULL, -1, 2048)) && TEST_true(BN_add_word(q, 2)) && TEST_true(BN_mul(n, p, q, ctx)); end: RSA_free(key); BN_CTX_free(ctx); return ret; } static int keygen_size[] = { 2048, 3072 }; static int test_sp80056b_keygen(int id) { RSA *key = NULL; int ret; int sz = keygen_size[id]; ret = TEST_ptr(key = RSA_new()) && TEST_true(ossl_rsa_sp800_56b_generate_key(key, sz, NULL, NULL)) && TEST_true(ossl_rsa_sp800_56b_check_public(key)) && TEST_true(ossl_rsa_sp800_56b_check_private(key)) && TEST_true(ossl_rsa_sp800_56b_check_keypair(key, NULL, -1, sz)); RSA_free(key); return ret; } static int test_check_private_key(void) { int ret = 0; BIGNUM *n = NULL, *d = NULL, *e = NULL; RSA *key = NULL; ret = TEST_ptr(key = RSA_new()) /* check NULL pointers fail */ && TEST_false(ossl_rsa_sp800_56b_check_private(key)) /* load private key */ && TEST_ptr(n = bn_load_new(cav_n, sizeof(cav_n))) && TEST_ptr(d = bn_load_new(cav_d, sizeof(cav_d))) && TEST_ptr(e = bn_load_new(cav_e, sizeof(cav_e))) && TEST_true(RSA_set0_key(key, n, e, d)); if (!ret) { BN_free(n); BN_free(e); BN_free(d); goto end; } /* check d is in range */ ret = TEST_true(ossl_rsa_sp800_56b_check_private(key)) /* check d is too low */ && TEST_true(BN_set_word(d, 0)) && TEST_false(ossl_rsa_sp800_56b_check_private(key)) /* check d is too high */ && TEST_ptr(BN_copy(d, n)) && TEST_false(ossl_rsa_sp800_56b_check_private(key)); end: RSA_free(key); return ret; } static int test_check_public_key(void) { int ret = 0; BIGNUM *n = NULL, *e = NULL; RSA *key = NULL; ret = TEST_ptr(key = RSA_new()) /* check NULL pointers fail */ && TEST_false(ossl_rsa_sp800_56b_check_public(key)) /* load public key */ && TEST_ptr(e = bn_load_new(cav_e, sizeof(cav_e))) && TEST_ptr(n = bn_load_new(cav_n, sizeof(cav_n))) && TEST_true(RSA_set0_key(key, n, e, NULL)); if (!ret) { BN_free(e); BN_free(n); goto end; } /* check public key is valid */ ret = TEST_true(ossl_rsa_sp800_56b_check_public(key)) /* check fail if n is even */ && TEST_true(BN_add_word(n, 1)) && TEST_false(ossl_rsa_sp800_56b_check_public(key)) && TEST_true(BN_sub_word(n, 1)) /* check fail if n is wrong number of bits */ && TEST_true(BN_lshift1(n, n)) && TEST_false(ossl_rsa_sp800_56b_check_public(key)) && TEST_true(BN_rshift1(n, n)) /* test odd exponent fails */ && TEST_true(BN_add_word(e, 1)) && TEST_false(ossl_rsa_sp800_56b_check_public(key)) && TEST_true(BN_sub_word(e, 1)) /* modulus fails composite check */ && TEST_true(BN_add_word(n, 2)) && TEST_false(ossl_rsa_sp800_56b_check_public(key)); end: RSA_free(key); return ret; } int setup_tests(void) { ADD_TEST(test_check_public_exponent); ADD_TEST(test_check_prime_factor_range); ADD_TEST(test_check_prime_factor); ADD_TEST(test_check_private_exponent); ADD_TEST(test_check_crt_components); ADD_ALL_TESTS(test_derive_params_from_pq_fail, (int)OSSL_NELEM(derive_from_pq_tests)); ADD_TEST(test_check_private_key); ADD_TEST(test_check_public_key); ADD_TEST(test_invalid_keypair); ADD_TEST(test_pq_diff); ADD_ALL_TESTS(test_sp80056b_keygen, (int)OSSL_NELEM(keygen_size)); return 1; }
22,531
37.319728
90
c
openssl
openssl-master/test/rsa_test.c
/* * Copyright 1999-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 */ /* test vectors from p1ovect1.txt */ /* * RSA 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 "internal/nelem.h" #include <openssl/crypto.h> #include <openssl/err.h> #include <openssl/rand.h> #include <openssl/bn.h> #include "testutil.h" #include <openssl/rsa.h> #define SetKey \ RSA_set0_key(key, \ BN_bin2bn(n, sizeof(n)-1, NULL), \ BN_bin2bn(e, sizeof(e)-1, NULL), \ BN_bin2bn(d, sizeof(d)-1, NULL)); \ RSA_set0_factors(key, \ BN_bin2bn(p, sizeof(p)-1, NULL), \ BN_bin2bn(q, sizeof(q)-1, NULL)); \ RSA_set0_crt_params(key, \ BN_bin2bn(dmp1, sizeof(dmp1)-1, NULL), \ BN_bin2bn(dmq1, sizeof(dmq1)-1, NULL), \ BN_bin2bn(iqmp, sizeof(iqmp)-1, NULL)); \ if (c != NULL) \ memcpy(c, ctext_ex, sizeof(ctext_ex) - 1); \ return sizeof(ctext_ex) - 1; static int key1(RSA *key, unsigned char *c) { static unsigned char 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 e[] = "\x11"; static unsigned char 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 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 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 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 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 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"; static unsigned char ctext_ex[] = "\x1b\x8f\x05\xf9\xca\x1a\x79\x52\x6e\x53\xf3\xcc\x51\x4f\xdb\x89" "\x2b\xfb\x91\x93\x23\x1e\x78\xb9\x92\xe6\x8d\x50\xa4\x80\xcb\x52" "\x33\x89\x5c\x74\x95\x8d\x5d\x02\xab\x8c\x0f\xd0\x40\xeb\x58\x44" "\xb0\x05\xc3\x9e\xd8\x27\x4a\x9d\xbf\xa8\x06\x71\x40\x94\x39\xd2"; SetKey; } static int key2(RSA *key, unsigned char *c) { static unsigned char n[] = "\x00\xA3\x07\x9A\x90\xDF\x0D\xFD\x72\xAC\x09\x0C\xCC\x2A\x78\xB8" "\x74\x13\x13\x3E\x40\x75\x9C\x98\xFA\xF8\x20\x4F\x35\x8A\x0B\x26" "\x3C\x67\x70\xE7\x83\xA9\x3B\x69\x71\xB7\x37\x79\xD2\x71\x7B\xE8" "\x34\x77\xCF"; static unsigned char e[] = "\x3"; static unsigned char d[] = "\x6C\xAF\xBC\x60\x94\xB3\xFE\x4C\x72\xB0\xB3\x32\xC6\xFB\x25\xA2" "\xB7\x62\x29\x80\x4E\x68\x65\xFC\xA4\x5A\x74\xDF\x0F\x8F\xB8\x41" "\x3B\x52\xC0\xD0\xE5\x3D\x9B\x59\x0F\xF1\x9B\xE7\x9F\x49\xDD\x21" "\xE5\xEB"; static unsigned char p[] = "\x00\xCF\x20\x35\x02\x8B\x9D\x86\x98\x40\xB4\x16\x66\xB4\x2E\x92" "\xEA\x0D\xA3\xB4\x32\x04\xB5\xCF\xCE\x91"; static unsigned char 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\x5F"; static unsigned char dmp1[] = "\x00\x8A\x15\x78\xAC\x5D\x13\xAF\x10\x2B\x22\xB9\x99\xCD\x74\x61" "\xF1\x5E\x6D\x22\xCC\x03\x23\xDF\xDF\x0B"; static unsigned char dmq1[] = "\x00\x86\x55\x21\x4A\xC5\x4D\x8D\x4E\xCD\x61\x77\xF1\xC7\x36\x90" "\xCE\x2A\x48\x2C\x8B\x05\x99\xCB\xE0\x3F"; static unsigned char iqmp[] = "\x00\x83\xEF\xEF\xB8\xA9\xA4\x0D\x1D\xB6\xED\x98\xAD\x84\xED\x13" "\x35\xDC\xC1\x08\xF3\x22\xD0\x57\xCF\x8D"; static unsigned char ctext_ex[] = "\x14\xbd\xdd\x28\xc9\x83\x35\x19\x23\x80\xe8\xe5\x49\xb1\x58\x2a" "\x8b\x40\xb4\x48\x6d\x03\xa6\xa5\x31\x1f\x1f\xd5\xf0\xa1\x80\xe4" "\x17\x53\x03\x29\xa9\x34\x90\x74\xb1\x52\x13\x54\x29\x08\x24\x52" "\x62\x51"; SetKey; } static int key3(RSA *key, unsigned char *c) { static unsigned char n[] = "\x00\xBB\xF8\x2F\x09\x06\x82\xCE\x9C\x23\x38\xAC\x2B\x9D\xA8\x71" "\xF7\x36\x8D\x07\xEE\xD4\x10\x43\xA4\x40\xD6\xB6\xF0\x74\x54\xF5" "\x1F\xB8\xDF\xBA\xAF\x03\x5C\x02\xAB\x61\xEA\x48\xCE\xEB\x6F\xCD" "\x48\x76\xED\x52\x0D\x60\xE1\xEC\x46\x19\x71\x9D\x8A\x5B\x8B\x80" "\x7F\xAF\xB8\xE0\xA3\xDF\xC7\x37\x72\x3E\xE6\xB4\xB7\xD9\x3A\x25" "\x84\xEE\x6A\x64\x9D\x06\x09\x53\x74\x88\x34\xB2\x45\x45\x98\x39" "\x4E\xE0\xAA\xB1\x2D\x7B\x61\xA5\x1F\x52\x7A\x9A\x41\xF6\xC1\x68" "\x7F\xE2\x53\x72\x98\xCA\x2A\x8F\x59\x46\xF8\xE5\xFD\x09\x1D\xBD" "\xCB"; static unsigned char e[] = "\x11"; static unsigned char d[] = "\x00\xA5\xDA\xFC\x53\x41\xFA\xF2\x89\xC4\xB9\x88\xDB\x30\xC1\xCD" "\xF8\x3F\x31\x25\x1E\x06\x68\xB4\x27\x84\x81\x38\x01\x57\x96\x41" "\xB2\x94\x10\xB3\xC7\x99\x8D\x6B\xC4\x65\x74\x5E\x5C\x39\x26\x69" "\xD6\x87\x0D\xA2\xC0\x82\xA9\x39\xE3\x7F\xDC\xB8\x2E\xC9\x3E\xDA" "\xC9\x7F\xF3\xAD\x59\x50\xAC\xCF\xBC\x11\x1C\x76\xF1\xA9\x52\x94" "\x44\xE5\x6A\xAF\x68\xC5\x6C\x09\x2C\xD3\x8D\xC3\xBE\xF5\xD2\x0A" "\x93\x99\x26\xED\x4F\x74\xA1\x3E\xDD\xFB\xE1\xA1\xCE\xCC\x48\x94" "\xAF\x94\x28\xC2\xB7\xB8\x88\x3F\xE4\x46\x3A\x4B\xC8\x5B\x1C\xB3" "\xC1"; static unsigned char p[] = "\x00\xEE\xCF\xAE\x81\xB1\xB9\xB3\xC9\x08\x81\x0B\x10\xA1\xB5\x60" "\x01\x99\xEB\x9F\x44\xAE\xF4\xFD\xA4\x93\xB8\x1A\x9E\x3D\x84\xF6" "\x32\x12\x4E\xF0\x23\x6E\x5D\x1E\x3B\x7E\x28\xFA\xE7\xAA\x04\x0A" "\x2D\x5B\x25\x21\x76\x45\x9D\x1F\x39\x75\x41\xBA\x2A\x58\xFB\x65" "\x99"; static unsigned char 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" "\x86\x98\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\x15" "\x03"; static unsigned char dmp1[] = "\x54\x49\x4C\xA6\x3E\xBA\x03\x37\xE4\xE2\x40\x23\xFC\xD6\x9A\x5A" "\xEB\x07\xDD\xDC\x01\x83\xA4\xD0\xAC\x9B\x54\xB0\x51\xF2\xB1\x3E" "\xD9\x49\x09\x75\xEA\xB7\x74\x14\xFF\x59\xC1\xF7\x69\x2E\x9A\x2E" "\x20\x2B\x38\xFC\x91\x0A\x47\x41\x74\xAD\xC9\x3C\x1F\x67\xC9\x81"; static unsigned char dmq1[] = "\x47\x1E\x02\x90\xFF\x0A\xF0\x75\x03\x51\xB7\xF8\x78\x86\x4C\xA9" "\x61\xAD\xBD\x3A\x8A\x7E\x99\x1C\x5C\x05\x56\xA9\x4C\x31\x46\xA7" "\xF9\x80\x3F\x8F\x6F\x8A\xE3\x42\xE9\x31\xFD\x8A\xE4\x7A\x22\x0D" "\x1B\x99\xA4\x95\x84\x98\x07\xFE\x39\xF9\x24\x5A\x98\x36\xDA\x3D"; static unsigned char iqmp[] = "\x00\xB0\x6C\x4F\xDA\xBB\x63\x01\x19\x8D\x26\x5B\xDB\xAE\x94\x23" "\xB3\x80\xF2\x71\xF7\x34\x53\x88\x50\x93\x07\x7F\xCD\x39\xE2\x11" "\x9F\xC9\x86\x32\x15\x4F\x58\x83\xB1\x67\xA9\x67\xBF\x40\x2B\x4E" "\x9E\x2E\x0F\x96\x56\xE6\x98\xEA\x36\x66\xED\xFB\x25\x79\x80\x39" "\xF7"; static unsigned char ctext_ex[] = "\xb8\x24\x6b\x56\xa6\xed\x58\x81\xae\xb5\x85\xd9\xa2\x5b\x2a\xd7" "\x90\xc4\x17\xe0\x80\x68\x1b\xf1\xac\x2b\xc3\xde\xb6\x9d\x8b\xce" "\xf0\xc4\x36\x6f\xec\x40\x0a\xf0\x52\xa7\x2e\x9b\x0e\xff\xb5\xb3" "\xf2\xf1\x92\xdb\xea\xca\x03\xc1\x27\x40\x05\x71\x13\xbf\x1f\x06" "\x69\xac\x22\xe9\xf3\xa7\x85\x2e\x3c\x15\xd9\x13\xca\xb0\xb8\x86" "\x3a\x95\xc9\x92\x94\xce\x86\x74\x21\x49\x54\x61\x03\x46\xf4\xd4" "\x74\xb2\x6f\x7c\x48\xb4\x2e\xe6\x8e\x1f\x57\x2a\x1f\xc4\x02\x6a" "\xc4\x56\xb4\xf5\x9f\x7b\x62\x1e\xa1\xb9\xd8\x8f\x64\x20\x2f\xb1"; SetKey; } static int rsa_setkey(RSA** key, unsigned char *ctext, int idx) { int clen = 0; *key = RSA_new(); if (*key != NULL) switch (idx) { case 0: clen = key1(*key, ctext); break; case 1: clen = key2(*key, ctext); break; case 2: clen = key3(*key, ctext); break; } return clen; } static int test_rsa_simple(int idx, int en_pad_type, int de_pad_type, int success, unsigned char *ctext_ex, int *clen, RSA **retkey) { int ret = 0; RSA *key; unsigned char ptext[256]; unsigned char ctext[256]; static unsigned char ptext_ex[] = "\x54\x85\x9b\x34\x2c\x49\xea\x2a"; int plen; int clentmp = 0; int num; plen = sizeof(ptext_ex) - 1; clentmp = rsa_setkey(&key, ctext_ex, idx); if (clen != NULL) *clen = clentmp; num = RSA_public_encrypt(plen, ptext_ex, ctext, key, en_pad_type); if (!TEST_int_eq(num, clentmp)) goto err; num = RSA_private_decrypt(num, ctext, ptext, key, de_pad_type); if (success) { if (!TEST_int_gt(num, 0) || !TEST_mem_eq(ptext, num, ptext_ex, plen)) goto err; } else { if (!TEST_int_lt(num, 0)) goto err; } ret = 1; if (retkey != NULL) { *retkey = key; key = NULL; } err: RSA_free(key); return ret; } static int test_rsa_pkcs1(int idx) { return test_rsa_simple(idx, RSA_PKCS1_PADDING, RSA_PKCS1_PADDING, 1, NULL, NULL, NULL); } static int test_rsa_oaep(int idx) { int ret = 0; RSA *key = NULL; unsigned char ptext[256]; static unsigned char ptext_ex[] = "\x54\x85\x9b\x34\x2c\x49\xea\x2a"; unsigned char ctext_ex[256]; int plen; int clen = 0; int num; int n; if (!test_rsa_simple(idx, RSA_PKCS1_OAEP_PADDING, RSA_PKCS1_OAEP_PADDING, 1, ctext_ex, &clen, &key)) goto err; plen = sizeof(ptext_ex) - 1; /* Different ciphertexts. Try decrypting ctext_ex */ num = RSA_private_decrypt(clen, ctext_ex, ptext, key, RSA_PKCS1_OAEP_PADDING); if (num <= 0 || !TEST_mem_eq(ptext, num, ptext_ex, plen)) goto err; /* Try decrypting corrupted ciphertexts. */ for (n = 0; n < clen; ++n) { ctext_ex[n] ^= 1; num = RSA_private_decrypt(clen, ctext_ex, ptext, key, RSA_PKCS1_OAEP_PADDING); if (!TEST_int_le(num, 0)) goto err; ctext_ex[n] ^= 1; } /* Test truncated ciphertexts, as well as negative length. */ for (n = -1; n < clen; ++n) { num = RSA_private_decrypt(n, ctext_ex, ptext, key, RSA_PKCS1_OAEP_PADDING); if (!TEST_int_le(num, 0)) goto err; } ret = 1; err: RSA_free(key); return ret; } static const struct { int bits; unsigned int r; } rsa_security_bits_cases[] = { /* NIST SP 800-56B rev 2 (draft) Appendix D Table 5 */ { 2048, 112 }, { 3072, 128 }, { 4096, 152 }, { 6144, 176 }, { 8192, 200 }, /* NIST FIPS 140-2 IG 7.5 */ { 7680, 192 }, { 15360, 256 }, /* Older values */ { 256, 40 }, { 512, 56 }, { 1024, 80 }, /* Some other values */ { 8888, 208 }, { 2468, 120 }, { 13456, 248 }, /* Edge points */ { 15359, 256 }, { 15361, 264 }, { 7679, 192 }, { 7681, 200 }, }; static int test_rsa_security_bit(int n) { static const unsigned char vals[8] = { 0x80, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40 }; RSA *key = RSA_new(); const int bits = rsa_security_bits_cases[n].bits; const int result = rsa_security_bits_cases[n].r; const int bytes = (bits + 7) / 8; int r = 0; unsigned char num[2000]; if (!TEST_ptr(key) || !TEST_int_le(bytes, (int)sizeof(num))) goto err; /* * It is necessary to set the RSA key in order to ask for the strength. * A BN of an appropriate size is created, in general it won't have the * properties necessary for RSA to function. This is okay here since * the RSA key is never used. */ memset(num, vals[bits % 8], bytes); /* * The 'e' parameter is set to the same value as 'n'. This saves having * an extra BN to hold a sensible value for 'e'. This is safe since the * RSA key is not used. The 'd' parameter can be NULL safely. */ if (TEST_true(RSA_set0_key(key, BN_bin2bn(num, bytes, NULL), BN_bin2bn(num, bytes, NULL), NULL)) && TEST_uint_eq(RSA_security_bits(key), result)) r = 1; err: RSA_free(key); return r; } static RSA *load_key(int priv) { RSA *rsa = NULL; BIGNUM *pn = NULL, *pe = NULL, *pd= NULL; /* RSA key extracted using > openssl genpkey -algorithm RSA -text */ static const unsigned char n[] = { 0x00, 0xbe, 0x24, 0x14, 0xf2, 0x39, 0xde, 0x19, 0xb3, 0xd7, 0x86, 0x1e, 0xf8, 0xd3, 0x97, 0x9f, 0x78, 0x28, 0x4c, 0xbf, 0xef, 0x03, 0x29, 0xc5, 0xeb, 0x97, 0x18, 0xdb, 0xa5, 0x17, 0x07, 0x57, 0x96, 0xe2, 0x45, 0x91, 0x2b, 0xd2, 0x9e, 0x28, 0x61, 0xa7, 0x8f, 0x39, 0xaa, 0xde, 0x94, 0x6d, 0x2b, 0x39, 0xde, 0xbe, 0xcf, 0xd7, 0x29, 0x16, 0x3a, 0x1a, 0x86, 0x2f, 0xff, 0x7a, 0x2f, 0x12, 0xc4, 0x8a, 0x32, 0x06, 0x6f, 0x40, 0x42, 0x37, 0xaa, 0x5f, 0xaf, 0x40, 0x77, 0xa5, 0x73, 0x09, 0xbf, 0xc5, 0x85, 0x79, 0xc0, 0x38, 0xd6, 0xb7, 0x2f, 0x77, 0xf0, 0x5a, 0xaf, 0xaf, 0xc3, 0x63, 0x4b, 0xea, 0xa2, 0x0c, 0x27, 0xcd, 0x7c, 0x77, 0xf4, 0x29, 0x5a, 0x69, 0xbd, 0xfe, 0x17, 0xb6, 0xc5, 0xd7, 0xc0, 0x40, 0xf9, 0x29, 0x46, 0x1f, 0xc0, 0x4b, 0xcf, 0x4e, 0x8f, 0x74, 0xd9, 0xc8, 0xd0, 0xde, 0x9c, 0x48, 0x57, 0xcc, 0x30, 0xbc, 0x06, 0x47, 0x4a, 0x8e, 0x40, 0x8a, 0xa1, 0x2a, 0x09, 0x8d, 0xe8, 0x41, 0x3d, 0x21, 0x52, 0xdc, 0x9c, 0xa9, 0x43, 0x63, 0x01, 0x44, 0xb3, 0xec, 0x22, 0x06, 0x29, 0xf6, 0xd8, 0xf6, 0x6b, 0xc3, 0x36, 0x25, 0xb0, 0x9b, 0xdb, 0x9a, 0x22, 0x51, 0x13, 0x42, 0xbd, 0x28, 0x0b, 0xd8, 0x5e, 0xac, 0xc7, 0x71, 0x6e, 0x78, 0xfc, 0xf4, 0x1d, 0x74, 0x9b, 0x1a, 0x19, 0x13, 0x56, 0x04, 0xb4, 0x33, 0x4e, 0xed, 0x54, 0x59, 0x7f, 0x71, 0x5d, 0x24, 0x18, 0x91, 0x51, 0x20, 0x39, 0x78, 0x4e, 0x33, 0x73, 0x96, 0xa8, 0x12, 0x2f, 0xff, 0x48, 0xc2, 0x11, 0x33, 0x95, 0xe5, 0xcc, 0x1a, 0xe2, 0x39, 0xd5, 0x57, 0x44, 0x51, 0x59, 0xd1, 0x35, 0x62, 0x16, 0x22, 0xf5, 0x52, 0x3d, 0xe0, 0x9b, 0x2d, 0x33, 0x34, 0x75, 0x13, 0x7d, 0x62, 0x70, 0x53, 0x31 }; static const unsigned char e[] = { 0x01, 0x00, 0x01 }; static const unsigned char d[] = { 0x0b, 0xd3, 0x07, 0x7a, 0xb0, 0x0c, 0xb2, 0xe3, 0x5d, 0x49, 0x7f, 0xe0, 0xf4, 0x5b, 0x21, 0x31, 0x96, 0x2b, 0x7e, 0x32, 0xdf, 0x5a, 0xec, 0x5e, 0x10, 0x14, 0x9d, 0x99, 0xaa, 0xd8, 0xc3, 0xfa, 0x9c, 0x0e, 0x0c, 0x96, 0xe9, 0xa3, 0x58, 0x62, 0x68, 0xca, 0xba, 0x50, 0xc9, 0x04, 0x58, 0xd4, 0xe3, 0xa5, 0x99, 0x8f, 0x08, 0x2b, 0xcb, 0xe0, 0x1f, 0x84, 0xc5, 0x64, 0xbd, 0x48, 0xe2, 0xc1, 0x56, 0x51, 0x01, 0xb7, 0x8e, 0xca, 0xe3, 0x66, 0x70, 0xea, 0x7f, 0x8f, 0x45, 0x3a, 0xa6, 0x02, 0x3f, 0x16, 0xc3, 0xad, 0x57, 0x97, 0x8a, 0x37, 0x2d, 0x6d, 0xb4, 0xfd, 0x08, 0x98, 0x95, 0x72, 0xeb, 0xd7, 0xa9, 0x9a, 0xfa, 0xcf, 0x55, 0x10, 0x19, 0xf7, 0x7f, 0x7c, 0x8f, 0x49, 0xf3, 0x1d, 0xc2, 0xf2, 0xd7, 0xb3, 0x8a, 0xfc, 0x9b, 0x76, 0x40, 0x5c, 0xa7, 0x2f, 0x7a, 0x8a, 0x3d, 0xdf, 0xbc, 0x52, 0x69, 0x99, 0xf8, 0x4b, 0x7a, 0xbf, 0x11, 0x5d, 0x31, 0x41, 0x5f, 0xa3, 0xb9, 0x74, 0xaf, 0xe4, 0x08, 0x19, 0x9f, 0x88, 0xca, 0xfb, 0x8e, 0xab, 0xa4, 0x00, 0x31, 0xc9, 0xf1, 0x77, 0xe9, 0xe3, 0xf1, 0x98, 0xd9, 0x04, 0x08, 0x0c, 0x38, 0x35, 0x4b, 0xcc, 0xab, 0x22, 0xdf, 0x84, 0xea, 0xe4, 0x2e, 0x57, 0xa5, 0xc1, 0x91, 0x0c, 0x34, 0x3b, 0x88, 0xbc, 0x14, 0xee, 0x6e, 0xe3, 0xf0, 0xe0, 0xdc, 0xae, 0xd6, 0x0c, 0x9b, 0xa0, 0x6d, 0xb6, 0x92, 0x6c, 0x7e, 0x05, 0x46, 0x02, 0xbc, 0x23, 0xbc, 0x65, 0xe6, 0x62, 0x04, 0x19, 0xe6, 0x98, 0x67, 0x2d, 0x15, 0x0a, 0xc4, 0xea, 0xb5, 0x62, 0xa0, 0x54, 0xed, 0x07, 0x45, 0x3e, 0x21, 0x93, 0x3e, 0x22, 0xd0, 0xc3, 0xca, 0x37, 0x3c, 0xea, 0x90, 0xdd, 0xa6, 0xb1, 0x6c, 0x76, 0xce, 0x5a, 0xe1, 0xc2, 0x80, 0x1f, 0x32, 0x21 }; if (!TEST_ptr(rsa = RSA_new())) return NULL; pn = BN_bin2bn(n, sizeof(n), NULL); pe = BN_bin2bn(e, sizeof(e), NULL); if (priv) pd = BN_bin2bn(d, sizeof(d), NULL); if (!TEST_false(pn == NULL || pe == NULL || (priv && pd == NULL) || !RSA_set0_key(rsa, pn, pe, pd))) { BN_free(pn); BN_free(pe); BN_free(pd); RSA_free(rsa); rsa = NULL; } return rsa; } static int test_rsa_saos(void) { int ret = 0; unsigned int siglen = 0; RSA *rsa_priv = NULL, *rsa_pub = NULL; static const unsigned char in[256] = { 0 }; unsigned char sig[256]; /* Maximum length allowed: The 3 relates to the octet byte 0x04 followed by a 2 byte length */ unsigned int inlen = sizeof(in) - RSA_PKCS1_PADDING_SIZE - 3; /* A generated signature when in[inlen]= { 1 }. */ static const unsigned char sig_mismatch[256] = { 0x5f, 0x64, 0xab, 0xd3, 0x86, 0xdf, 0x6e, 0x91, 0xa8, 0xdb, 0x9d, 0x36, 0x7a, 0x15, 0xe5, 0x75, 0xe4, 0x27, 0xdf, 0xeb, 0x8d, 0xaf, 0xb0, 0x60, 0xec, 0x36, 0x8b, 0x00, 0x36, 0xb4, 0x61, 0x38, 0xfe, 0xfa, 0x49, 0x55, 0xcf, 0xb7, 0xff, 0xeb, 0x25, 0xa5, 0x41, 0x1e, 0xaa, 0x74, 0x3d, 0x57, 0xed, 0x5c, 0x4a, 0x01, 0x9e, 0xb2, 0x50, 0xbc, 0x50, 0x15, 0xd5, 0x97, 0x93, 0x91, 0x97, 0xa3, 0xff, 0x67, 0x2a, 0xe9, 0x04, 0xdd, 0x31, 0x6f, 0x4b, 0x44, 0x4f, 0x04, 0xa0, 0x48, 0x6a, 0xc1, 0x8d, 0xc2, 0xf3, 0xf7, 0xc4, 0x8c, 0x29, 0xcb, 0x2c, 0x04, 0x8f, 0x30, 0x71, 0xbb, 0x5b, 0xf9, 0xf9, 0x1b, 0xe8, 0xf0, 0xe8, 0xd1, 0xcf, 0x73, 0xf6, 0x02, 0x45, 0x6f, 0x53, 0x25, 0x1e, 0x74, 0x94, 0x6e, 0xf4, 0x0d, 0x36, 0x6c, 0xa3, 0xae, 0x8f, 0x94, 0x05, 0xa9, 0xe9, 0x65, 0x26, 0x7f, 0x07, 0xc5, 0x7e, 0xab, 0xd9, 0xe9, 0x09, 0x2d, 0x19, 0x8c, 0x6a, 0xcc, 0xd5, 0x62, 0x04, 0xb4, 0x9b, 0xaf, 0x99, 0x6a, 0x7a, 0x7b, 0xef, 0x01, 0x9b, 0xc1, 0x46, 0x59, 0x88, 0xee, 0x8b, 0xd7, 0xe5, 0x35, 0xad, 0x4c, 0xb2, 0x0d, 0x93, 0xdd, 0x0e, 0x50, 0x36, 0x2b, 0x7b, 0x42, 0x9b, 0x59, 0x95, 0xe7, 0xe1, 0x36, 0x50, 0x87, 0x7c, 0xac, 0x47, 0x13, 0x9b, 0xa7, 0x36, 0xdf, 0x8a, 0xd7, 0xee, 0x7d, 0x2e, 0xa6, 0xbb, 0x31, 0x32, 0xed, 0x39, 0x77, 0xf2, 0x41, 0xf9, 0x2d, 0x29, 0xfc, 0x6d, 0x32, 0x8e, 0x35, 0x99, 0x38, 0x8b, 0xd9, 0xc6, 0x77, 0x09, 0xe3, 0xe3, 0x06, 0x98, 0xe1, 0x96, 0xe9, 0x23, 0x11, 0xeb, 0x09, 0xa2, 0x6b, 0x21, 0x52, 0x67, 0x94, 0x15, 0x72, 0x7e, 0xdd, 0x66, 0x1c, 0xe7, 0xdb, 0x0e, 0x71, 0x5d, 0x95, 0x9d, 0xf8, 0x8e, 0x65, 0x97, 0x2f, 0x1a, 0x86 }; /* The signature generated by RSA_private_encrypt of in[inlen] */ static const unsigned char no_octet_sig[256] = { 0x78, 0xaf, 0x3e, 0xd1, 0xbc, 0x99, 0xb3, 0x19, 0xa8, 0xaa, 0x64, 0x56, 0x60, 0x95, 0xa0, 0x81, 0xd8, 0xb4, 0xe1, 0x9c, 0xf8, 0x94, 0xfa, 0x31, 0xb5, 0xde, 0x90, 0x75, 0xa7, 0xdb, 0xd4, 0x7e, 0xda, 0x62, 0xde, 0x16, 0x78, 0x4f, 0x9b, 0xc2, 0xa4, 0xd4, 0x5c, 0x17, 0x4f, 0x2d, 0xf2, 0x84, 0x5b, 0x5d, 0x00, 0xa0, 0xcf, 0xda, 0x3f, 0xbc, 0x40, 0xb4, 0x4e, 0xcb, 0x18, 0xeb, 0x4b, 0x0f, 0xce, 0x95, 0x3a, 0x5a, 0x9c, 0x49, 0xb4, 0x63, 0xd4, 0xde, 0xfb, 0xe2, 0xa8, 0xf3, 0x97, 0x52, 0x36, 0x3e, 0xc0, 0xab, 0xc8, 0x1c, 0xef, 0xdd, 0xf4, 0x37, 0xbc, 0xf3, 0xc3, 0x67, 0xf6, 0xc0, 0x6e, 0x75, 0xa6, 0xf3, 0x7e, 0x37, 0x96, 0xf2, 0xbb, 0x25, 0x3a, 0xa0, 0xa8, 0x8e, 0xce, 0xa0, 0xce, 0x0f, 0x22, 0x2d, 0x9c, 0x30, 0x0d, 0x20, 0x36, 0xc6, 0x9d, 0x36, 0x5d, 0x5b, 0x3e, 0xbc, 0x7c, 0x55, 0x95, 0xb4, 0x69, 0x19, 0x27, 0xf6, 0x63, 0x78, 0x21, 0x2d, 0xcf, 0x51, 0xb0, 0x46, 0x44, 0x02, 0x29, 0x93, 0xa5, 0x1b, 0xda, 0x21, 0xb3, 0x74, 0xf6, 0x4e, 0xd0, 0xdb, 0x3d, 0x59, 0xfd, 0xd7, 0x88, 0xd0, 0x2f, 0x84, 0xf6, 0xb1, 0xaa, 0xce, 0x3e, 0xa0, 0xdc, 0x1a, 0xd0, 0xe3, 0x5f, 0x3c, 0xda, 0x96, 0xee, 0xce, 0xf9, 0x75, 0xcf, 0x8d, 0xf3, 0x03, 0x28, 0xa7, 0x39, 0xbd, 0x95, 0xaa, 0x73, 0xbe, 0xa5, 0x5f, 0x84, 0x33, 0x07, 0x49, 0xbf, 0x03, 0xf8, 0x4b, 0x46, 0xbf, 0x38, 0xd4, 0x9b, 0x14, 0xa7, 0x01, 0xb7, 0x1f, 0x12, 0x08, 0x01, 0xed, 0xcd, 0x34, 0xf5, 0xb4, 0x06, 0x47, 0xe0, 0x53, 0x1c, 0x7c, 0x3f, 0xb5, 0x30, 0x59, 0xbb, 0xe3, 0xd6, 0x7c, 0x41, 0xcc, 0xd2, 0x11, 0x73, 0x03, 0x77, 0x7f, 0x5f, 0xad, 0x4a, 0x54, 0xdf, 0x17, 0x94, 0x97, 0x5c, 0x16 }; if (!TEST_ptr(rsa_priv = load_key(1))) goto err; if (!TEST_ptr(rsa_pub = load_key(0))) goto err; if (!TEST_int_ge((int)sizeof(sig), RSA_size(rsa_priv))) goto err; /* Test that a generated signature can be verified */ if (!TEST_true(RSA_sign_ASN1_OCTET_STRING(0, in, inlen, sig, &siglen, rsa_priv))) goto err; if (!TEST_true(RSA_verify_ASN1_OCTET_STRING(0, in, inlen, sig, siglen, rsa_pub))) goto err; /* Test sign fails if the input is too large */ if (!TEST_false(RSA_sign_ASN1_OCTET_STRING(0, in, inlen + 1, sig, &siglen, rsa_priv))) goto err; /* Fail if there is no private signing key */ if (!TEST_false(RSA_sign_ASN1_OCTET_STRING(0, in, inlen, sig, &siglen, rsa_pub))) goto err; /* Fail if the signature is the wrong size */ if (!TEST_false(RSA_verify_ASN1_OCTET_STRING(0, in, inlen, sig, siglen - 1, rsa_pub))) goto err; /* Fail if the encrypted input is not octet encoded */ if (!TEST_false(RSA_verify_ASN1_OCTET_STRING(0, in, inlen, (unsigned char *)no_octet_sig, (unsigned int)sizeof(no_octet_sig), rsa_pub))) goto err; /* Fail if the signature does not match the input */ if (!TEST_false(RSA_verify_ASN1_OCTET_STRING(0, in, inlen, (unsigned char *)sig_mismatch, (unsigned int)sizeof(sig_mismatch), rsa_pub))) goto err; /* Fail if the signature is corrupt */ sig[0]++; if (!TEST_false(RSA_verify_ASN1_OCTET_STRING(0, in, inlen, sig, siglen, rsa_pub))) goto err; sig[0]--; ret = 1; err: RSA_free(rsa_priv); RSA_free(rsa_pub); return ret; } int setup_tests(void) { ADD_ALL_TESTS(test_rsa_pkcs1, 3); ADD_ALL_TESTS(test_rsa_oaep, 3); ADD_ALL_TESTS(test_rsa_security_bit, OSSL_NELEM(rsa_security_bits_cases)); ADD_TEST(test_rsa_saos); return 1; }
24,681
39.796694
98
c
openssl
openssl-master/test/rsa_x931_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/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); }
1,171
22.918367
74
c
openssl
openssl-master/test/safe_math_test.c
/* * Copyright 2021-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 <stdlib.h> /* * Uncomment this if the fallback non-builtin overflow checking is to * be tested. */ /*#define OPENSSL_NO_BUILTIN_OVERFLOW_CHECKING*/ #include "internal/nelem.h" #include "internal/safe_math.h" #include "testutil.h" /* Create the safe math instances we're interested in */ OSSL_SAFE_MATH_SIGNED(int, int) OSSL_SAFE_MATH_UNSIGNED(uint, unsigned int) OSSL_SAFE_MATH_UNSIGNED(size_t, size_t) static const struct { int a, b; int sum_err, sub_err, mul_err, div_err, mod_err, div_round_up_err; int neg_a_err, neg_b_err, abs_a_err, abs_b_err; } test_ints[] = { /* + - * / % /r -a -b |a||b| */ { 1, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { -1, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 1, -3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { -1, -3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 3, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { -3, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 2, -3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { -2, -3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { INT_MAX, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { INT_MAX, 2, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0 }, { INT_MAX, 4, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0 }, { INT_MAX - 3 , 4, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0 }, { INT_MIN, 1, 0, 1, 0, 0, 0, 0, 1, 0, 1, 0 }, { 1, INT_MIN, 0, 1, 0, 0, 0, 0, 0, 1, 0, 1 }, { INT_MIN, 2, 0, 1, 1, 0, 0, 0, 1, 0, 1, 0 }, { 2, INT_MIN, 0, 1, 1, 0, 0, 0, 0, 1, 0, 1 }, { INT_MIN, -1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 0 }, { INT_MAX, INT_MIN, 0, 1, 1, 0, 0, 0, 0, 1, 0, 1 }, { INT_MIN, INT_MAX, 0, 1, 1, 0, 0, 0, 1, 0, 1, 0 }, { 3, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0 }, }; static int test_int_ops(int n) { int err, r, s; const int a = test_ints[n].a, b = test_ints[n].b; err = 0; r = safe_add_int(a, b, &err); if (!TEST_int_eq(err, test_ints[n].sum_err) || (!err && !TEST_int_eq(r, a + b))) goto err; err = 0; r = safe_sub_int(a, b, &err); if (!TEST_int_eq(err, test_ints[n].sub_err) || (!err && !TEST_int_eq(r, a - b))) goto err; err = 0; r = safe_mul_int(a, b, &err); if (!TEST_int_eq(err, test_ints[n].mul_err) || (!err && !TEST_int_eq(r, a * b))) goto err; err = 0; r = safe_div_int(a, b, &err); if (!TEST_int_eq(err, test_ints[n].div_err) || (!err && !TEST_int_eq(r, a / b))) goto err; err = 0; r = safe_mod_int(a, b, &err); if (!TEST_int_eq(err, test_ints[n].mod_err) || (!err && !TEST_int_eq(r, a % b))) goto err; err = 0; r = safe_div_round_up_int(a, b, &err); if (!TEST_int_eq(err, test_ints[n].div_round_up_err)) goto err; s = safe_mod_int(a, b, &err); s = safe_add_int(safe_div_int(a, b, &err), s != 0, &err); if (!err && !TEST_int_eq(r, s)) goto err; err = 0; r = safe_neg_int(a, &err); if (!TEST_int_eq(err, test_ints[n].neg_a_err) || (!err && !TEST_int_eq(r, -a))) goto err; err = 0; r = safe_neg_int(b, &err); if (!TEST_int_eq(err, test_ints[n].neg_b_err) || (!err && !TEST_int_eq(r, -b))) goto err; err = 0; r = safe_abs_int(a, &err); if (!TEST_int_eq(err, test_ints[n].abs_a_err) || (!err && !TEST_int_eq(r, a < 0 ? -a : a))) goto err; err = 0; r = safe_abs_int(b, &err); if (!TEST_int_eq(err, test_ints[n].abs_b_err) || (!err && !TEST_int_eq(r, b < 0 ? -b : b))) goto err; return 1; err: TEST_info("a = %d b = %d r = %d err = %d", a, b, r, err); return 0; } static const struct { unsigned int a, b; int sum_err, sub_err, mul_err, div_err, mod_err, div_round_up_err; } test_uints[] = { /* + - * / % /r */ { 3, 1, 0, 0, 0, 0, 0, 0 }, { 1, 3, 0, 1, 0, 0, 0, 0 }, { UINT_MAX, 1, 1, 0, 0, 0, 0, 0 }, { UINT_MAX, 2, 1, 0, 1, 0, 0, 0 }, { UINT_MAX, 16, 1, 0, 1, 0, 0, 0 }, { UINT_MAX - 13, 16, 1, 0, 1, 0, 0, 0 }, { 1, UINT_MAX, 1, 1, 0, 0, 0, 0 }, { 2, UINT_MAX, 1, 1, 1, 0, 0, 0 }, { UINT_MAX, 0, 0, 0, 0, 1, 1, 1 }, }; static int test_uint_ops(int n) { int err; unsigned int r; const unsigned int a = test_uints[n].a, b = test_uints[n].b; err = 0; r = safe_add_uint(a, b, &err); if (!TEST_int_eq(err, test_uints[n].sum_err) || (!err && !TEST_uint_eq(r, a + b))) goto err; err = 0; r = safe_sub_uint(a, b, &err); if (!TEST_int_eq(err, test_uints[n].sub_err) || (!err && !TEST_uint_eq(r, a - b))) goto err; err = 0; r = safe_mul_uint(a, b, &err); if (!TEST_int_eq(err, test_uints[n].mul_err) || (!err && !TEST_uint_eq(r, a * b))) goto err; err = 0; r = safe_div_uint(a, b, &err); if (!TEST_int_eq(err, test_uints[n].div_err) || (!err && !TEST_uint_eq(r, a / b))) goto err; err = 0; r = safe_mod_uint(a, b, &err); if (!TEST_int_eq(err, test_uints[n].mod_err) || (!err && !TEST_uint_eq(r, a % b))) goto err; err = 0; r = safe_div_round_up_uint(a, b, &err); if (!TEST_int_eq(err, test_uints[n].div_round_up_err) || (!err && !TEST_uint_eq(r, a / b + (a % b != 0)))) goto err; err = 0; r = safe_neg_uint(a, &err); if (!TEST_int_eq(err, a != 0) || (!err && !TEST_uint_eq(r, 0))) goto err; err = 0; r = safe_neg_uint(b, &err); if (!TEST_int_eq(err, b != 0) || (!err && !TEST_uint_eq(r, 0))) goto err; err = 0; r = safe_abs_uint(a, &err); if (!TEST_int_eq(err, 0) || !TEST_uint_eq(r, a)) goto err; err = 0; r = safe_abs_uint(b, &err); if (!TEST_int_eq(err, 0) || !TEST_uint_eq(r, b)) goto err; return 1; err: TEST_info("a = %u b = %u r = %u err = %d", a, b, r, err); return 0; } static const struct { size_t a, b; int sum_err, sub_err, mul_err, div_err, mod_err, div_round_up_err; } test_size_ts[] = { { 3, 1, 0, 0, 0, 0, 0, 0 }, { 1, 3, 0, 1, 0, 0, 0, 0 }, { 36, 8, 0, 0, 0, 0, 0, 0 }, { SIZE_MAX, 1, 1, 0, 0, 0, 0, 0 }, { SIZE_MAX, 2, 1, 0, 1, 0, 0, 0 }, { SIZE_MAX, 8, 1, 0, 1, 0, 0, 0 }, { SIZE_MAX - 3, 8, 1, 0, 1, 0, 0, 0 }, { 1, SIZE_MAX, 1, 1, 0, 0, 0, 0 }, { 2, SIZE_MAX, 1, 1, 1, 0, 0, 0 }, { 11, 0, 0, 0, 0, 1, 1, 1 }, }; static int test_size_t_ops(int n) { int err; size_t r; const size_t a = test_size_ts[n].a, b = test_size_ts[n].b; err = 0; r = safe_add_size_t(a, b, &err); if (!TEST_int_eq(err, test_size_ts[n].sum_err) || (!err && !TEST_size_t_eq(r, a + b))) goto err; err = 0; r = safe_sub_size_t(a, b, &err); if (!TEST_int_eq(err, test_size_ts[n].sub_err) || (!err && !TEST_size_t_eq(r, a - b))) goto err; err = 0; r = safe_mul_size_t(a, b, &err); if (!TEST_int_eq(err, test_size_ts[n].mul_err) || (!err && !TEST_size_t_eq(r, a * b))) goto err; err = 0; r = safe_div_size_t(a, b, &err); if (!TEST_int_eq(err, test_size_ts[n].div_err) || (!err && !TEST_size_t_eq(r, a / b))) goto err; err = 0; r = safe_mod_size_t(a, b, &err); if (!TEST_int_eq(err, test_size_ts[n].mod_err) || (!err && !TEST_size_t_eq(r, a % b))) goto err; err = 0; r = safe_div_round_up_size_t(a, b, &err); if (!TEST_int_eq(err, test_size_ts[n].div_round_up_err) || (!err && !TEST_size_t_eq(r, a / b + (a % b != 0)))) goto err; err = 0; r = safe_neg_size_t(a, &err); if (!TEST_int_eq(err, a != 0) || (!err && !TEST_size_t_eq(r, 0))) goto err; err = 0; r = safe_neg_size_t(b, &err); if (!TEST_int_eq(err, b != 0) || (!err && !TEST_size_t_eq(r, 0))) goto err; err = 0; r = safe_abs_size_t(a, &err); if (!TEST_int_eq(err, 0) || !TEST_size_t_eq(r, a)) goto err; err = 0; r = safe_abs_size_t(b, &err); if (!TEST_int_eq(err, 0) || !TEST_size_t_eq(r, b)) goto err; return 1; err: TEST_info("a = %zu b = %zu r = %zu err = %d", a, b, r, err); return 0; } static const struct { int a, b, c; int err; } test_muldiv_ints[] = { { 3, 1, 2, 0 }, { 1, 3, 2, 0 }, { -3, 1, 2, 0 }, { 1, 3, -2, 0 }, { INT_MAX, INT_MAX, INT_MAX, 0 }, { INT_MIN, INT_MIN, INT_MAX, 1 }, { INT_MIN, INT_MIN, INT_MIN, 0 }, { INT_MAX, 2, 4, 0 }, { 8, INT_MAX, 4, 1 }, { INT_MAX, 8, 4, 1 }, { INT_MIN, 2, 4, 1 }, { 8, INT_MIN, 4, 1 }, { INT_MIN, 8, 4, 1 }, { 3, 4, 0, 1 }, }; static int test_int_muldiv(int n) { int err = 0; int r, real = 0; const int a = test_muldiv_ints[n].a; const int b = test_muldiv_ints[n].b; const int c = test_muldiv_ints[n].c; r = safe_muldiv_int(a, b, c, &err); if (c != 0) real = (int)((int64_t)a * (int64_t)b / (int64_t)c); if (!TEST_int_eq(err, test_muldiv_ints[n].err) || (!err && !TEST_int_eq(r, real))) { TEST_info("%d * %d / %d r = %d err = %d", a, b, c, r, err); return 0; } return 1; } static const struct { unsigned int a, b, c; int err; } test_muldiv_uints[] = { { 3, 1, 2, 0 }, { 1, 3, 2, 0 }, { UINT_MAX, UINT_MAX, UINT_MAX, 0 }, { UINT_MAX, 2, 4, 0 }, { 8, UINT_MAX, 4, 1 }, { UINT_MAX, 8, 4, 1 }, { 3, 4, 0, 1 }, }; static int test_uint_muldiv(int n) { int err = 0; unsigned int r, real = 0; const unsigned int a = test_muldiv_uints[n].a; const unsigned int b = test_muldiv_uints[n].b; const unsigned int c = test_muldiv_uints[n].c; r = safe_muldiv_uint(a, b, c, &err); if (c != 0) real = (unsigned int)((uint64_t)a * (uint64_t)b / (uint64_t)c); if (!TEST_int_eq(err, test_muldiv_uints[n].err) || (!err && !TEST_uint_eq(r, real))) { TEST_info("%u * %u / %u r = %u err = %d", a, b, c, r, err); return 0; } return 1; } int setup_tests(void) { ADD_ALL_TESTS(test_int_ops, OSSL_NELEM(test_ints)); ADD_ALL_TESTS(test_uint_ops, OSSL_NELEM(test_uints)); ADD_ALL_TESTS(test_size_t_ops, OSSL_NELEM(test_size_ts)); ADD_ALL_TESTS(test_int_muldiv, OSSL_NELEM(test_muldiv_ints)); ADD_ALL_TESTS(test_uint_muldiv, OSSL_NELEM(test_muldiv_uints)); return 1; }
11,531
29.91689
74
c
openssl
openssl-master/test/sanitytest.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 <string.h> #include <openssl/types.h> #include "testutil.h" #include "internal/numbers.h" #include "internal/time.h" static int test_sanity_null_zero(void) { char *p; char bytes[sizeof(p)]; /* Is NULL equivalent to all-bytes-zero? */ p = NULL; memset(bytes, 0, sizeof(bytes)); return TEST_mem_eq(&p, sizeof(p), bytes, sizeof(bytes)); } static int test_sanity_enum_size(void) { enum smallchoices { sa, sb, sc }; enum medchoices { ma, mb, mc, md, me, mf, mg, mh, mi, mj, mk, ml }; enum largechoices { a01, b01, c01, d01, e01, f01, g01, h01, i01, j01, a02, b02, c02, d02, e02, f02, g02, h02, i02, j02, a03, b03, c03, d03, e03, f03, g03, h03, i03, j03, a04, b04, c04, d04, e04, f04, g04, h04, i04, j04, a05, b05, c05, d05, e05, f05, g05, h05, i05, j05, a06, b06, c06, d06, e06, f06, g06, h06, i06, j06, a07, b07, c07, d07, e07, f07, g07, h07, i07, j07, a08, b08, c08, d08, e08, f08, g08, h08, i08, j08, a09, b09, c09, d09, e09, f09, g09, h09, i09, j09, a10, b10, c10, d10, e10, f10, g10, h10, i10, j10, xxx }; /* Enum size */ if (!TEST_size_t_eq(sizeof(enum smallchoices), sizeof(int)) || !TEST_size_t_eq(sizeof(enum medchoices), sizeof(int)) || !TEST_size_t_eq(sizeof(enum largechoices), sizeof(int))) return 0; return 1; } static int test_sanity_twos_complement(void) { /* Basic two's complement checks. */ if (!TEST_int_eq(~(-1), 0) || !TEST_long_eq(~(-1L), 0L)) return 0; return 1; } static int test_sanity_sign(void) { /* Check that values with sign bit 1 and value bits 0 are valid */ if (!TEST_int_eq(-(INT_MIN + 1), INT_MAX) || !TEST_long_eq(-(LONG_MIN + 1), LONG_MAX)) return 0; return 1; } static int test_sanity_unsigned_conversion(void) { /* Check that unsigned-to-signed conversions preserve bit patterns */ if (!TEST_int_eq((int)((unsigned int)INT_MAX + 1), INT_MIN) || !TEST_long_eq((long)((unsigned long)LONG_MAX + 1), LONG_MIN)) return 0; return 1; } static int test_sanity_range(void) { /* Verify some types are the correct size */ if (!TEST_size_t_eq(sizeof(int8_t), 1) || !TEST_size_t_eq(sizeof(uint8_t), 1) || !TEST_size_t_eq(sizeof(int16_t), 2) || !TEST_size_t_eq(sizeof(uint16_t), 2) || !TEST_size_t_eq(sizeof(int32_t), 4) || !TEST_size_t_eq(sizeof(uint32_t), 4) || !TEST_size_t_eq(sizeof(int64_t), 8) || !TEST_size_t_eq(sizeof(uint64_t), 8) #ifdef UINT128_MAX || !TEST_size_t_eq(sizeof(int128_t), 16) || !TEST_size_t_eq(sizeof(uint128_t), 16) #endif || !TEST_size_t_eq(sizeof(char), 1) || !TEST_size_t_eq(sizeof(unsigned char), 1)) return 0; /* We want our long longs to be at least 64 bits */ if (!TEST_size_t_ge(sizeof(long long int), 8) || !TEST_size_t_ge(sizeof(unsigned long long int), 8)) return 0; /* * Verify intmax_t. * Some platforms defined intmax_t to be 64 bits but still support * an int128_t, so this check is for at least 64 bits. */ if (!TEST_size_t_ge(sizeof(ossl_intmax_t), 8) || !TEST_size_t_ge(sizeof(ossl_uintmax_t), 8) || !TEST_size_t_ge(sizeof(ossl_uintmax_t), sizeof(size_t))) return 0; /* This isn't possible to check using the framework functions */ if (SIZE_MAX < INT_MAX) { TEST_error("int must not be wider than size_t"); return 0; } /* SIZE_MAX is always greater than 2*INT_MAX */ if (SIZE_MAX - INT_MAX <= INT_MAX) { TEST_error("SIZE_MAX must exceed 2*INT_MAX"); return 0; } return 1; } static int test_sanity_memcmp(void) { return CRYPTO_memcmp("ab", "cd", 2); } static int test_sanity_sleep(void) { OSSL_TIME start = ossl_time_now(); uint64_t seconds; /* * On any reasonable system this must sleep at least one second * but not more than 20. * Assuming there is no interruption. */ OSSL_sleep(1000); seconds = ossl_time2seconds(ossl_time_subtract(ossl_time_now(), start)); if (!TEST_uint64_t_ge(seconds, 1) || !TEST_uint64_t_le(seconds, 20)) return 0; return 1; } int setup_tests(void) { ADD_TEST(test_sanity_null_zero); ADD_TEST(test_sanity_enum_size); ADD_TEST(test_sanity_twos_complement); ADD_TEST(test_sanity_sign); ADD_TEST(test_sanity_unsigned_conversion); ADD_TEST(test_sanity_range); ADD_TEST(test_sanity_memcmp); ADD_TEST(test_sanity_sleep); return 1; }
5,018
29.603659
76
c
openssl
openssl-master/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; }
6,016
31.701087
80
c
openssl
openssl-master/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; }
7,601
27.260223
86
c
openssl
openssl-master/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; }
3,769
32.963964
80
c
openssl
openssl-master/test/shlibloadtest.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 <stdio.h> #include <string.h> #include <stdlib.h> #include <openssl/opensslv.h> #include <openssl/ssl.h> #include <openssl/types.h> #include "simpledynamic.h" typedef void DSO; typedef const SSL_METHOD * (*TLS_method_t)(void); typedef SSL_CTX * (*SSL_CTX_new_t)(const SSL_METHOD *meth); typedef void (*SSL_CTX_free_t)(SSL_CTX *); typedef int (*OPENSSL_init_crypto_t)(uint64_t, void *); typedef int (*OPENSSL_atexit_t)(void (*handler)(void)); typedef unsigned long (*ERR_get_error_t)(void); typedef unsigned long (*OPENSSL_version_major_t)(void); typedef unsigned long (*OPENSSL_version_minor_t)(void); typedef unsigned long (*OPENSSL_version_patch_t)(void); typedef DSO * (*DSO_dsobyaddr_t)(void (*addr)(void), int flags); typedef int (*DSO_free_t)(DSO *dso); typedef enum test_types_en { CRYPTO_FIRST, SSL_FIRST, JUST_CRYPTO, DSO_REFTEST, NO_ATEXIT } TEST_TYPE; static TEST_TYPE test_type; static const char *path_crypto; static const char *path_ssl; static const char *path_atexit; #ifdef SD_INIT static int atexit_handler_done = 0; static void atexit_handler(void) { FILE *atexit_file = fopen(path_atexit, "w"); if (atexit_file == NULL) return; fprintf(atexit_file, "atexit() run\n"); fclose(atexit_file); atexit_handler_done++; } static int test_lib(void) { SD ssllib = SD_INIT; SD cryptolib = SD_INIT; SSL_CTX *ctx; union { void (*func)(void); SD_SYM sym; } symbols[5]; TLS_method_t myTLS_method; SSL_CTX_new_t mySSL_CTX_new; SSL_CTX_free_t mySSL_CTX_free; ERR_get_error_t myERR_get_error; OPENSSL_version_major_t myOPENSSL_version_major; OPENSSL_version_minor_t myOPENSSL_version_minor; OPENSSL_version_patch_t myOPENSSL_version_patch; OPENSSL_atexit_t myOPENSSL_atexit; int result = 0; switch (test_type) { case JUST_CRYPTO: case DSO_REFTEST: case NO_ATEXIT: case CRYPTO_FIRST: if (!sd_load(path_crypto, &cryptolib, SD_SHLIB)) { fprintf(stderr, "Failed to load libcrypto\n"); goto end; } if (test_type != CRYPTO_FIRST) break; /* Fall through */ case SSL_FIRST: if (!sd_load(path_ssl, &ssllib, SD_SHLIB)) { fprintf(stderr, "Failed to load libssl\n"); goto end; } if (test_type != SSL_FIRST) break; if (!sd_load(path_crypto, &cryptolib, SD_SHLIB)) { fprintf(stderr, "Failed to load libcrypto\n"); goto end; } break; } if (test_type == NO_ATEXIT) { OPENSSL_init_crypto_t myOPENSSL_init_crypto; if (!sd_sym(cryptolib, "OPENSSL_init_crypto", &symbols[0].sym)) { fprintf(stderr, "Failed to load OPENSSL_init_crypto symbol\n"); goto end; } myOPENSSL_init_crypto = (OPENSSL_init_crypto_t)symbols[0].func; if (!myOPENSSL_init_crypto(OPENSSL_INIT_NO_ATEXIT, NULL)) { fprintf(stderr, "Failed to initialise libcrypto\n"); goto end; } } if (test_type != JUST_CRYPTO && test_type != DSO_REFTEST && test_type != NO_ATEXIT) { if (!sd_sym(ssllib, "TLS_method", &symbols[0].sym) || !sd_sym(ssllib, "SSL_CTX_new", &symbols[1].sym) || !sd_sym(ssllib, "SSL_CTX_free", &symbols[2].sym)) { fprintf(stderr, "Failed to load libssl symbols\n"); goto end; } myTLS_method = (TLS_method_t)symbols[0].func; mySSL_CTX_new = (SSL_CTX_new_t)symbols[1].func; mySSL_CTX_free = (SSL_CTX_free_t)symbols[2].func; ctx = mySSL_CTX_new(myTLS_method()); if (ctx == NULL) { fprintf(stderr, "Failed to create SSL_CTX\n"); goto end; } mySSL_CTX_free(ctx); } if (!sd_sym(cryptolib, "ERR_get_error", &symbols[0].sym) || !sd_sym(cryptolib, "OPENSSL_version_major", &symbols[1].sym) || !sd_sym(cryptolib, "OPENSSL_version_minor", &symbols[2].sym) || !sd_sym(cryptolib, "OPENSSL_version_patch", &symbols[3].sym) || !sd_sym(cryptolib, "OPENSSL_atexit", &symbols[4].sym)) { fprintf(stderr, "Failed to load libcrypto symbols\n"); goto end; } myERR_get_error = (ERR_get_error_t)symbols[0].func; if (myERR_get_error() != 0) { fprintf(stderr, "Unexpected ERR_get_error() response\n"); goto end; } /* Library and header version should be identical in this test */ myOPENSSL_version_major = (OPENSSL_version_major_t)symbols[1].func; myOPENSSL_version_minor = (OPENSSL_version_minor_t)symbols[2].func; myOPENSSL_version_patch = (OPENSSL_version_patch_t)symbols[3].func; if (myOPENSSL_version_major() != OPENSSL_VERSION_MAJOR || myOPENSSL_version_minor() != OPENSSL_VERSION_MINOR || myOPENSSL_version_patch() != OPENSSL_VERSION_PATCH) { fprintf(stderr, "Invalid library version number\n"); goto end; } myOPENSSL_atexit = (OPENSSL_atexit_t)symbols[4].func; if (!myOPENSSL_atexit(atexit_handler)) { fprintf(stderr, "Failed to register atexit handler\n"); goto end; } if (test_type == DSO_REFTEST) { # ifdef DSO_DLFCN DSO_dsobyaddr_t myDSO_dsobyaddr; DSO_free_t myDSO_free; /* * This is resembling the code used in ossl_init_base() and * OPENSSL_atexit() to block unloading the library after dlclose(). * We are not testing this on Windows, because it is done there in a * completely different way. Especially as a call to DSO_dsobyaddr() * will always return an error, because DSO_pathbyaddr() is not * implemented there. */ if (!sd_sym(cryptolib, "DSO_dsobyaddr", &symbols[0].sym) || !sd_sym(cryptolib, "DSO_free", &symbols[1].sym)) { fprintf(stderr, "Unable to load DSO symbols\n"); goto end; } myDSO_dsobyaddr = (DSO_dsobyaddr_t)symbols[0].func; myDSO_free = (DSO_free_t)symbols[1].func; { DSO *hndl; /* use known symbol from crypto module */ hndl = myDSO_dsobyaddr((void (*)(void))myERR_get_error, 0); if (hndl == NULL) { fprintf(stderr, "DSO_dsobyaddr() failed\n"); goto end; } myDSO_free(hndl); } # endif /* DSO_DLFCN */ } if (!sd_close(cryptolib)) { fprintf(stderr, "Failed to close libcrypto\n"); goto end; } cryptolib = SD_INIT; if (test_type == CRYPTO_FIRST || test_type == SSL_FIRST) { if (!sd_close(ssllib)) { fprintf(stderr, "Failed to close libssl\n"); goto end; } ssllib = SD_INIT; } # if defined(OPENSSL_NO_PINSHARED) \ && defined(__GLIBC__) \ && defined(__GLIBC_PREREQ) \ && defined(OPENSSL_SYS_LINUX) # if __GLIBC_PREREQ(2, 3) /* * If we didn't pin the so then we are hopefully on a platform that supports * running atexit() on so unload. If not we might crash. We know this is * true on linux since glibc 2.2.3 */ if (test_type != NO_ATEXIT && atexit_handler_done != 1) { fprintf(stderr, "atexit() handler did not run\n"); goto end; } # endif # endif result = 1; end: if (cryptolib != SD_INIT) sd_close(cryptolib); if (ssllib != SD_INIT) sd_close(ssllib); return result; } #endif /* * shlibloadtest should not use the normal test framework because we don't want * it to link against libcrypto (which the framework uses). The point of the * test is to check dynamic loading and unloading of libcrypto/libssl. */ int main(int argc, char *argv[]) { const char *p; if (argc != 5) { fprintf(stderr, "Incorrect number of arguments\n"); return 1; } p = argv[1]; if (strcmp(p, "-crypto_first") == 0) { test_type = CRYPTO_FIRST; } else if (strcmp(p, "-ssl_first") == 0) { test_type = SSL_FIRST; } else if (strcmp(p, "-just_crypto") == 0) { test_type = JUST_CRYPTO; } else if (strcmp(p, "-dso_ref") == 0) { test_type = DSO_REFTEST; } else if (strcmp(p, "-no_atexit") == 0) { test_type = NO_ATEXIT; } else { fprintf(stderr, "Unrecognised argument\n"); return 1; } path_crypto = argv[2]; path_ssl = argv[3]; path_atexit = argv[4]; if (path_crypto == NULL || path_ssl == NULL) { fprintf(stderr, "Invalid libcrypto/libssl path\n"); return 1; } #ifdef SD_INIT if (!test_lib()) return 1; #endif return 0; }
9,070
29.959044
80
c
openssl
openssl-master/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
1,692
20.43038
74
c
openssl
openssl-master/test/simpledynamic.h
/* * 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 */ #ifndef OSSL_TEST_SIMPLEDYNAMIC_H # define OSSL_TEST_SIMPLEDYNAMIC_H # include "crypto/dso_conf.h" # if defined(DSO_DLFCN) || defined(DSO_VMS) # include <dlfcn.h> # define SD_INIT NULL # ifdef DSO_VMS # define SD_SHLIB 0 # define SD_MODULE 0 # else # define SD_SHLIB (RTLD_GLOBAL|RTLD_LAZY) # define SD_MODULE (RTLD_LOCAL|RTLD_NOW) # endif typedef void *SD; typedef void *SD_SYM; # elif defined(DSO_WIN32) # include <windows.h> # define SD_INIT 0 # define SD_SHLIB 0 # define SD_MODULE 0 typedef HINSTANCE SD; typedef void *SD_SYM; # endif # if defined(DSO_DLFCN) || defined(DSO_WIN32) || defined(DSO_VMS) int sd_load(const char *filename, SD *sd, int type); int sd_sym(SD sd, const char *symname, SD_SYM *sym); int sd_close(SD lib); const char *sd_error(void); # endif #endif
1,178
21.673077
74
h
openssl
openssl-master/test/siphash_internal_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 */ /* Internal tests for the siphash module */ #include <stdio.h> #include <string.h> #include <openssl/bio.h> #include "testutil.h" #include "crypto/siphash.h" #include "internal/nelem.h" typedef struct { size_t size; unsigned char data[64]; } SIZED_DATA; typedef struct { int idx; SIZED_DATA expected; } TESTDATA; /********************************************************************** * * Test of siphash internal functions * ***/ /* From C reference: https://131002.net/siphash/ */ static TESTDATA tests[] = { { 0, { 8, { 0x31, 0x0e, 0x0e, 0xdd, 0x47, 0xdb, 0x6f, 0x72, } } }, { 1, { 8, { 0xfd, 0x67, 0xdc, 0x93, 0xc5, 0x39, 0xf8, 0x74, } } }, { 2, { 8, { 0x5a, 0x4f, 0xa9, 0xd9, 0x09, 0x80, 0x6c, 0x0d, } } }, { 3, { 8, { 0x2d, 0x7e, 0xfb, 0xd7, 0x96, 0x66, 0x67, 0x85, } } }, { 4, { 8, { 0xb7, 0x87, 0x71, 0x27, 0xe0, 0x94, 0x27, 0xcf, } } }, { 5, { 8, { 0x8d, 0xa6, 0x99, 0xcd, 0x64, 0x55, 0x76, 0x18, } } }, { 6, { 8, { 0xce, 0xe3, 0xfe, 0x58, 0x6e, 0x46, 0xc9, 0xcb, } } }, { 7, { 8, { 0x37, 0xd1, 0x01, 0x8b, 0xf5, 0x00, 0x02, 0xab, } } }, { 8, { 8, { 0x62, 0x24, 0x93, 0x9a, 0x79, 0xf5, 0xf5, 0x93, } } }, { 9, { 8, { 0xb0, 0xe4, 0xa9, 0x0b, 0xdf, 0x82, 0x00, 0x9e, } } }, { 10, { 8, { 0xf3, 0xb9, 0xdd, 0x94, 0xc5, 0xbb, 0x5d, 0x7a, } } }, { 11, { 8, { 0xa7, 0xad, 0x6b, 0x22, 0x46, 0x2f, 0xb3, 0xf4, } } }, { 12, { 8, { 0xfb, 0xe5, 0x0e, 0x86, 0xbc, 0x8f, 0x1e, 0x75, } } }, { 13, { 8, { 0x90, 0x3d, 0x84, 0xc0, 0x27, 0x56, 0xea, 0x14, } } }, { 14, { 8, { 0xee, 0xf2, 0x7a, 0x8e, 0x90, 0xca, 0x23, 0xf7, } } }, { 15, { 8, { 0xe5, 0x45, 0xbe, 0x49, 0x61, 0xca, 0x29, 0xa1, } } }, { 16, { 8, { 0xdb, 0x9b, 0xc2, 0x57, 0x7f, 0xcc, 0x2a, 0x3f, } } }, { 17, { 8, { 0x94, 0x47, 0xbe, 0x2c, 0xf5, 0xe9, 0x9a, 0x69, } } }, { 18, { 8, { 0x9c, 0xd3, 0x8d, 0x96, 0xf0, 0xb3, 0xc1, 0x4b, } } }, { 19, { 8, { 0xbd, 0x61, 0x79, 0xa7, 0x1d, 0xc9, 0x6d, 0xbb, } } }, { 20, { 8, { 0x98, 0xee, 0xa2, 0x1a, 0xf2, 0x5c, 0xd6, 0xbe, } } }, { 21, { 8, { 0xc7, 0x67, 0x3b, 0x2e, 0xb0, 0xcb, 0xf2, 0xd0, } } }, { 22, { 8, { 0x88, 0x3e, 0xa3, 0xe3, 0x95, 0x67, 0x53, 0x93, } } }, { 23, { 8, { 0xc8, 0xce, 0x5c, 0xcd, 0x8c, 0x03, 0x0c, 0xa8, } } }, { 24, { 8, { 0x94, 0xaf, 0x49, 0xf6, 0xc6, 0x50, 0xad, 0xb8, } } }, { 25, { 8, { 0xea, 0xb8, 0x85, 0x8a, 0xde, 0x92, 0xe1, 0xbc, } } }, { 26, { 8, { 0xf3, 0x15, 0xbb, 0x5b, 0xb8, 0x35, 0xd8, 0x17, } } }, { 27, { 8, { 0xad, 0xcf, 0x6b, 0x07, 0x63, 0x61, 0x2e, 0x2f, } } }, { 28, { 8, { 0xa5, 0xc9, 0x1d, 0xa7, 0xac, 0xaa, 0x4d, 0xde, } } }, { 29, { 8, { 0x71, 0x65, 0x95, 0x87, 0x66, 0x50, 0xa2, 0xa6, } } }, { 30, { 8, { 0x28, 0xef, 0x49, 0x5c, 0x53, 0xa3, 0x87, 0xad, } } }, { 31, { 8, { 0x42, 0xc3, 0x41, 0xd8, 0xfa, 0x92, 0xd8, 0x32, } } }, { 32, { 8, { 0xce, 0x7c, 0xf2, 0x72, 0x2f, 0x51, 0x27, 0x71, } } }, { 33, { 8, { 0xe3, 0x78, 0x59, 0xf9, 0x46, 0x23, 0xf3, 0xa7, } } }, { 34, { 8, { 0x38, 0x12, 0x05, 0xbb, 0x1a, 0xb0, 0xe0, 0x12, } } }, { 35, { 8, { 0xae, 0x97, 0xa1, 0x0f, 0xd4, 0x34, 0xe0, 0x15, } } }, { 36, { 8, { 0xb4, 0xa3, 0x15, 0x08, 0xbe, 0xff, 0x4d, 0x31, } } }, { 37, { 8, { 0x81, 0x39, 0x62, 0x29, 0xf0, 0x90, 0x79, 0x02, } } }, { 38, { 8, { 0x4d, 0x0c, 0xf4, 0x9e, 0xe5, 0xd4, 0xdc, 0xca, } } }, { 39, { 8, { 0x5c, 0x73, 0x33, 0x6a, 0x76, 0xd8, 0xbf, 0x9a, } } }, { 40, { 8, { 0xd0, 0xa7, 0x04, 0x53, 0x6b, 0xa9, 0x3e, 0x0e, } } }, { 41, { 8, { 0x92, 0x59, 0x58, 0xfc, 0xd6, 0x42, 0x0c, 0xad, } } }, { 42, { 8, { 0xa9, 0x15, 0xc2, 0x9b, 0xc8, 0x06, 0x73, 0x18, } } }, { 43, { 8, { 0x95, 0x2b, 0x79, 0xf3, 0xbc, 0x0a, 0xa6, 0xd4, } } }, { 44, { 8, { 0xf2, 0x1d, 0xf2, 0xe4, 0x1d, 0x45, 0x35, 0xf9, } } }, { 45, { 8, { 0x87, 0x57, 0x75, 0x19, 0x04, 0x8f, 0x53, 0xa9, } } }, { 46, { 8, { 0x10, 0xa5, 0x6c, 0xf5, 0xdf, 0xcd, 0x9a, 0xdb, } } }, { 47, { 8, { 0xeb, 0x75, 0x09, 0x5c, 0xcd, 0x98, 0x6c, 0xd0, } } }, { 48, { 8, { 0x51, 0xa9, 0xcb, 0x9e, 0xcb, 0xa3, 0x12, 0xe6, } } }, { 49, { 8, { 0x96, 0xaf, 0xad, 0xfc, 0x2c, 0xe6, 0x66, 0xc7, } } }, { 50, { 8, { 0x72, 0xfe, 0x52, 0x97, 0x5a, 0x43, 0x64, 0xee, } } }, { 51, { 8, { 0x5a, 0x16, 0x45, 0xb2, 0x76, 0xd5, 0x92, 0xa1, } } }, { 52, { 8, { 0xb2, 0x74, 0xcb, 0x8e, 0xbf, 0x87, 0x87, 0x0a, } } }, { 53, { 8, { 0x6f, 0x9b, 0xb4, 0x20, 0x3d, 0xe7, 0xb3, 0x81, } } }, { 54, { 8, { 0xea, 0xec, 0xb2, 0xa3, 0x0b, 0x22, 0xa8, 0x7f, } } }, { 55, { 8, { 0x99, 0x24, 0xa4, 0x3c, 0xc1, 0x31, 0x57, 0x24, } } }, { 56, { 8, { 0xbd, 0x83, 0x8d, 0x3a, 0xaf, 0xbf, 0x8d, 0xb7, } } }, { 57, { 8, { 0x0b, 0x1a, 0x2a, 0x32, 0x65, 0xd5, 0x1a, 0xea, } } }, { 58, { 8, { 0x13, 0x50, 0x79, 0xa3, 0x23, 0x1c, 0xe6, 0x60, } } }, { 59, { 8, { 0x93, 0x2b, 0x28, 0x46, 0xe4, 0xd7, 0x06, 0x66, } } }, { 60, { 8, { 0xe1, 0x91, 0x5f, 0x5c, 0xb1, 0xec, 0xa4, 0x6c, } } }, { 61, { 8, { 0xf3, 0x25, 0x96, 0x5c, 0xa1, 0x6d, 0x62, 0x9f, } } }, { 62, { 8, { 0x57, 0x5f, 0xf2, 0x8e, 0x60, 0x38, 0x1b, 0xe5, } } }, { 63, { 8, { 0x72, 0x45, 0x06, 0xeb, 0x4c, 0x32, 0x8a, 0x95, } } }, { 0, { 16, { 0xa3, 0x81, 0x7f, 0x04, 0xba, 0x25, 0xa8, 0xe6, 0x6d, 0xf6, 0x72, 0x14, 0xc7, 0x55, 0x02, 0x93, } } }, { 1, { 16, { 0xda, 0x87, 0xc1, 0xd8, 0x6b, 0x99, 0xaf, 0x44, 0x34, 0x76, 0x59, 0x11, 0x9b, 0x22, 0xfc, 0x45, } } }, { 2, { 16, { 0x81, 0x77, 0x22, 0x8d, 0xa4, 0xa4, 0x5d, 0xc7, 0xfc, 0xa3, 0x8b, 0xde, 0xf6, 0x0a, 0xff, 0xe4, } } }, { 3, { 16, { 0x9c, 0x70, 0xb6, 0x0c, 0x52, 0x67, 0xa9, 0x4e, 0x5f, 0x33, 0xb6, 0xb0, 0x29, 0x85, 0xed, 0x51, } } }, { 4, { 16, { 0xf8, 0x81, 0x64, 0xc1, 0x2d, 0x9c, 0x8f, 0xaf, 0x7d, 0x0f, 0x6e, 0x7c, 0x7b, 0xcd, 0x55, 0x79, } } }, { 5, { 16, { 0x13, 0x68, 0x87, 0x59, 0x80, 0x77, 0x6f, 0x88, 0x54, 0x52, 0x7a, 0x07, 0x69, 0x0e, 0x96, 0x27, } } }, { 6, { 16, { 0x14, 0xee, 0xca, 0x33, 0x8b, 0x20, 0x86, 0x13, 0x48, 0x5e, 0xa0, 0x30, 0x8f, 0xd7, 0xa1, 0x5e, } } }, { 7, { 16, { 0xa1, 0xf1, 0xeb, 0xbe, 0xd8, 0xdb, 0xc1, 0x53, 0xc0, 0xb8, 0x4a, 0xa6, 0x1f, 0xf0, 0x82, 0x39, } } }, { 8, { 16, { 0x3b, 0x62, 0xa9, 0xba, 0x62, 0x58, 0xf5, 0x61, 0x0f, 0x83, 0xe2, 0x64, 0xf3, 0x14, 0x97, 0xb4, } } }, { 9, { 16, { 0x26, 0x44, 0x99, 0x06, 0x0a, 0xd9, 0xba, 0xab, 0xc4, 0x7f, 0x8b, 0x02, 0xbb, 0x6d, 0x71, 0xed, } } }, { 10, { 16, { 0x00, 0x11, 0x0d, 0xc3, 0x78, 0x14, 0x69, 0x56, 0xc9, 0x54, 0x47, 0xd3, 0xf3, 0xd0, 0xfb, 0xba, } } }, { 11, { 16, { 0x01, 0x51, 0xc5, 0x68, 0x38, 0x6b, 0x66, 0x77, 0xa2, 0xb4, 0xdc, 0x6f, 0x81, 0xe5, 0xdc, 0x18, } } }, { 12, { 16, { 0xd6, 0x26, 0xb2, 0x66, 0x90, 0x5e, 0xf3, 0x58, 0x82, 0x63, 0x4d, 0xf6, 0x85, 0x32, 0xc1, 0x25, } } }, { 13, { 16, { 0x98, 0x69, 0xe2, 0x47, 0xe9, 0xc0, 0x8b, 0x10, 0xd0, 0x29, 0x93, 0x4f, 0xc4, 0xb9, 0x52, 0xf7, } } }, { 14, { 16, { 0x31, 0xfc, 0xef, 0xac, 0x66, 0xd7, 0xde, 0x9c, 0x7e, 0xc7, 0x48, 0x5f, 0xe4, 0x49, 0x49, 0x02, } } }, { 15, { 16, { 0x54, 0x93, 0xe9, 0x99, 0x33, 0xb0, 0xa8, 0x11, 0x7e, 0x08, 0xec, 0x0f, 0x97, 0xcf, 0xc3, 0xd9, } } }, { 16, { 16, { 0x6e, 0xe2, 0xa4, 0xca, 0x67, 0xb0, 0x54, 0xbb, 0xfd, 0x33, 0x15, 0xbf, 0x85, 0x23, 0x05, 0x77, } } }, { 17, { 16, { 0x47, 0x3d, 0x06, 0xe8, 0x73, 0x8d, 0xb8, 0x98, 0x54, 0xc0, 0x66, 0xc4, 0x7a, 0xe4, 0x77, 0x40, } } }, { 18, { 16, { 0xa4, 0x26, 0xe5, 0xe4, 0x23, 0xbf, 0x48, 0x85, 0x29, 0x4d, 0xa4, 0x81, 0xfe, 0xae, 0xf7, 0x23, } } }, { 19, { 16, { 0x78, 0x01, 0x77, 0x31, 0xcf, 0x65, 0xfa, 0xb0, 0x74, 0xd5, 0x20, 0x89, 0x52, 0x51, 0x2e, 0xb1, } } }, { 20, { 16, { 0x9e, 0x25, 0xfc, 0x83, 0x3f, 0x22, 0x90, 0x73, 0x3e, 0x93, 0x44, 0xa5, 0xe8, 0x38, 0x39, 0xeb, } } }, { 21, { 16, { 0x56, 0x8e, 0x49, 0x5a, 0xbe, 0x52, 0x5a, 0x21, 0x8a, 0x22, 0x14, 0xcd, 0x3e, 0x07, 0x1d, 0x12, } } }, { 22, { 16, { 0x4a, 0x29, 0xb5, 0x45, 0x52, 0xd1, 0x6b, 0x9a, 0x46, 0x9c, 0x10, 0x52, 0x8e, 0xff, 0x0a, 0xae, } } }, { 23, { 16, { 0xc9, 0xd1, 0x84, 0xdd, 0xd5, 0xa9, 0xf5, 0xe0, 0xcf, 0x8c, 0xe2, 0x9a, 0x9a, 0xbf, 0x69, 0x1c, } } }, { 24, { 16, { 0x2d, 0xb4, 0x79, 0xae, 0x78, 0xbd, 0x50, 0xd8, 0x88, 0x2a, 0x8a, 0x17, 0x8a, 0x61, 0x32, 0xad, } } }, { 25, { 16, { 0x8e, 0xce, 0x5f, 0x04, 0x2d, 0x5e, 0x44, 0x7b, 0x50, 0x51, 0xb9, 0xea, 0xcb, 0x8d, 0x8f, 0x6f, } } }, { 26, { 16, { 0x9c, 0x0b, 0x53, 0xb4, 0xb3, 0xc3, 0x07, 0xe8, 0x7e, 0xae, 0xe0, 0x86, 0x78, 0x14, 0x1f, 0x66, } } }, { 27, { 16, { 0xab, 0xf2, 0x48, 0xaf, 0x69, 0xa6, 0xea, 0xe4, 0xbf, 0xd3, 0xeb, 0x2f, 0x12, 0x9e, 0xeb, 0x94, } } }, { 28, { 16, { 0x06, 0x64, 0xda, 0x16, 0x68, 0x57, 0x4b, 0x88, 0xb9, 0x35, 0xf3, 0x02, 0x73, 0x58, 0xae, 0xf4, } } }, { 29, { 16, { 0xaa, 0x4b, 0x9d, 0xc4, 0xbf, 0x33, 0x7d, 0xe9, 0x0c, 0xd4, 0xfd, 0x3c, 0x46, 0x7c, 0x6a, 0xb7, } } }, { 30, { 16, { 0xea, 0x5c, 0x7f, 0x47, 0x1f, 0xaf, 0x6b, 0xde, 0x2b, 0x1a, 0xd7, 0xd4, 0x68, 0x6d, 0x22, 0x87, } } }, { 31, { 16, { 0x29, 0x39, 0xb0, 0x18, 0x32, 0x23, 0xfa, 0xfc, 0x17, 0x23, 0xde, 0x4f, 0x52, 0xc4, 0x3d, 0x35, } } }, { 32, { 16, { 0x7c, 0x39, 0x56, 0xca, 0x5e, 0xea, 0xfc, 0x3e, 0x36, 0x3e, 0x9d, 0x55, 0x65, 0x46, 0xeb, 0x68, } } }, { 33, { 16, { 0x77, 0xc6, 0x07, 0x71, 0x46, 0xf0, 0x1c, 0x32, 0xb6, 0xb6, 0x9d, 0x5f, 0x4e, 0xa9, 0xff, 0xcf, } } }, { 34, { 16, { 0x37, 0xa6, 0x98, 0x6c, 0xb8, 0x84, 0x7e, 0xdf, 0x09, 0x25, 0xf0, 0xf1, 0x30, 0x9b, 0x54, 0xde, } } }, { 35, { 16, { 0xa7, 0x05, 0xf0, 0xe6, 0x9d, 0xa9, 0xa8, 0xf9, 0x07, 0x24, 0x1a, 0x2e, 0x92, 0x3c, 0x8c, 0xc8, } } }, { 36, { 16, { 0x3d, 0xc4, 0x7d, 0x1f, 0x29, 0xc4, 0x48, 0x46, 0x1e, 0x9e, 0x76, 0xed, 0x90, 0x4f, 0x67, 0x11, } } }, { 37, { 16, { 0x0d, 0x62, 0xbf, 0x01, 0xe6, 0xfc, 0x0e, 0x1a, 0x0d, 0x3c, 0x47, 0x51, 0xc5, 0xd3, 0x69, 0x2b, } } }, { 38, { 16, { 0x8c, 0x03, 0x46, 0x8b, 0xca, 0x7c, 0x66, 0x9e, 0xe4, 0xfd, 0x5e, 0x08, 0x4b, 0xbe, 0xe7, 0xb5, } } }, { 39, { 16, { 0x52, 0x8a, 0x5b, 0xb9, 0x3b, 0xaf, 0x2c, 0x9c, 0x44, 0x73, 0xcc, 0xe5, 0xd0, 0xd2, 0x2b, 0xd9, } } }, { 40, { 16, { 0xdf, 0x6a, 0x30, 0x1e, 0x95, 0xc9, 0x5d, 0xad, 0x97, 0xae, 0x0c, 0xc8, 0xc6, 0x91, 0x3b, 0xd8, } } }, { 41, { 16, { 0x80, 0x11, 0x89, 0x90, 0x2c, 0x85, 0x7f, 0x39, 0xe7, 0x35, 0x91, 0x28, 0x5e, 0x70, 0xb6, 0xdb, } } }, { 42, { 16, { 0xe6, 0x17, 0x34, 0x6a, 0xc9, 0xc2, 0x31, 0xbb, 0x36, 0x50, 0xae, 0x34, 0xcc, 0xca, 0x0c, 0x5b, } } }, { 43, { 16, { 0x27, 0xd9, 0x34, 0x37, 0xef, 0xb7, 0x21, 0xaa, 0x40, 0x18, 0x21, 0xdc, 0xec, 0x5a, 0xdf, 0x89, } } }, { 44, { 16, { 0x89, 0x23, 0x7d, 0x9d, 0xed, 0x9c, 0x5e, 0x78, 0xd8, 0xb1, 0xc9, 0xb1, 0x66, 0xcc, 0x73, 0x42, } } }, { 45, { 16, { 0x4a, 0x6d, 0x80, 0x91, 0xbf, 0x5e, 0x7d, 0x65, 0x11, 0x89, 0xfa, 0x94, 0xa2, 0x50, 0xb1, 0x4c, } } }, { 46, { 16, { 0x0e, 0x33, 0xf9, 0x60, 0x55, 0xe7, 0xae, 0x89, 0x3f, 0xfc, 0x0e, 0x3d, 0xcf, 0x49, 0x29, 0x02, } } }, { 47, { 16, { 0xe6, 0x1c, 0x43, 0x2b, 0x72, 0x0b, 0x19, 0xd1, 0x8e, 0xc8, 0xd8, 0x4b, 0xdc, 0x63, 0x15, 0x1b, } } }, { 48, { 16, { 0xf7, 0xe5, 0xae, 0xf5, 0x49, 0xf7, 0x82, 0xcf, 0x37, 0x90, 0x55, 0xa6, 0x08, 0x26, 0x9b, 0x16, } } }, { 49, { 16, { 0x43, 0x8d, 0x03, 0x0f, 0xd0, 0xb7, 0xa5, 0x4f, 0xa8, 0x37, 0xf2, 0xad, 0x20, 0x1a, 0x64, 0x03, } } }, { 50, { 16, { 0xa5, 0x90, 0xd3, 0xee, 0x4f, 0xbf, 0x04, 0xe3, 0x24, 0x7e, 0x0d, 0x27, 0xf2, 0x86, 0x42, 0x3f, } } }, { 51, { 16, { 0x5f, 0xe2, 0xc1, 0xa1, 0x72, 0xfe, 0x93, 0xc4, 0xb1, 0x5c, 0xd3, 0x7c, 0xae, 0xf9, 0xf5, 0x38, } } }, { 52, { 16, { 0x2c, 0x97, 0x32, 0x5c, 0xbd, 0x06, 0xb3, 0x6e, 0xb2, 0x13, 0x3d, 0xd0, 0x8b, 0x3a, 0x01, 0x7c, } } }, { 53, { 16, { 0x92, 0xc8, 0x14, 0x22, 0x7a, 0x6b, 0xca, 0x94, 0x9f, 0xf0, 0x65, 0x9f, 0x00, 0x2a, 0xd3, 0x9e, } } }, { 54, { 16, { 0xdc, 0xe8, 0x50, 0x11, 0x0b, 0xd8, 0x32, 0x8c, 0xfb, 0xd5, 0x08, 0x41, 0xd6, 0x91, 0x1d, 0x87, } } }, { 55, { 16, { 0x67, 0xf1, 0x49, 0x84, 0xc7, 0xda, 0x79, 0x12, 0x48, 0xe3, 0x2b, 0xb5, 0x92, 0x25, 0x83, 0xda, } } }, { 56, { 16, { 0x19, 0x38, 0xf2, 0xcf, 0x72, 0xd5, 0x4e, 0xe9, 0x7e, 0x94, 0x16, 0x6f, 0xa9, 0x1d, 0x2a, 0x36, } } }, { 57, { 16, { 0x74, 0x48, 0x1e, 0x96, 0x46, 0xed, 0x49, 0xfe, 0x0f, 0x62, 0x24, 0x30, 0x16, 0x04, 0x69, 0x8e, } } }, { 58, { 16, { 0x57, 0xfc, 0xa5, 0xde, 0x98, 0xa9, 0xd6, 0xd8, 0x00, 0x64, 0x38, 0xd0, 0x58, 0x3d, 0x8a, 0x1d, } } }, { 59, { 16, { 0x9f, 0xec, 0xde, 0x1c, 0xef, 0xdc, 0x1c, 0xbe, 0xd4, 0x76, 0x36, 0x74, 0xd9, 0x57, 0x53, 0x59, } } }, { 60, { 16, { 0xe3, 0x04, 0x0c, 0x00, 0xeb, 0x28, 0xf1, 0x53, 0x66, 0xca, 0x73, 0xcb, 0xd8, 0x72, 0xe7, 0x40, } } }, { 61, { 16, { 0x76, 0x97, 0x00, 0x9a, 0x6a, 0x83, 0x1d, 0xfe, 0xcc, 0xa9, 0x1c, 0x59, 0x93, 0x67, 0x0f, 0x7a, } } }, { 62, { 16, { 0x58, 0x53, 0x54, 0x23, 0x21, 0xf5, 0x67, 0xa0, 0x05, 0xd5, 0x47, 0xa4, 0xf0, 0x47, 0x59, 0xbd, } } }, { 63, { 16, { 0x51, 0x50, 0xd1, 0x77, 0x2f, 0x50, 0x83, 0x4a, 0x50, 0x3e, 0x06, 0x9a, 0x97, 0x3f, 0xbd, 0x7c, } } } }; static int test_siphash(int idx) { SIPHASH siphash = { 0, }; TESTDATA test = tests[idx]; unsigned char key[SIPHASH_KEY_SIZE]; unsigned char in[64]; size_t inlen = test.idx; unsigned char *expected = test.expected.data; size_t expectedlen = test.expected.size; unsigned char out[SIPHASH_MAX_DIGEST_SIZE]; size_t i; if (expectedlen != SIPHASH_MIN_DIGEST_SIZE && expectedlen != SIPHASH_MAX_DIGEST_SIZE) { TEST_info("size %zu vs %d and %d", expectedlen, SIPHASH_MIN_DIGEST_SIZE, SIPHASH_MAX_DIGEST_SIZE); return 0; } if (!TEST_int_le(inlen, sizeof(in))) return 0; /* key and in data are 00 01 02 ... */ for (i = 0; i < sizeof(key); i++) key[i] = (unsigned char)i; for (i = 0; i < inlen; i++) in[i] = (unsigned char)i; if (!TEST_true(SipHash_set_hash_size(&siphash, expectedlen)) || !TEST_true(SipHash_Init(&siphash, key, 0, 0))) return 0; SipHash_Update(&siphash, in, inlen); if (!TEST_true(SipHash_Final(&siphash, out, expectedlen)) || !TEST_mem_eq(out, expectedlen, expected, expectedlen)) return 0; if (inlen > 16) { if (!TEST_true(SipHash_set_hash_size(&siphash, expectedlen)) || !TEST_true(SipHash_Init(&siphash, key, 0, 0))) return 0; SipHash_Update(&siphash, in, 1); SipHash_Update(&siphash, in+1, inlen-1); if (!TEST_true(SipHash_Final(&siphash, out, expectedlen))) return 0; if (!TEST_mem_eq(out, expectedlen, expected, expectedlen)) { TEST_info("SipHash test #%d/1+(N-1) failed.", idx); return 0; } } if (inlen > 32) { size_t half = inlen / 2; if (!TEST_true(SipHash_set_hash_size(&siphash, expectedlen)) || !TEST_true(SipHash_Init(&siphash, key, 0, 0))) return 0; SipHash_Update(&siphash, in, half); SipHash_Update(&siphash, in+half, inlen-half); if (!TEST_true(SipHash_Final(&siphash, out, expectedlen))) return 0; if (!TEST_mem_eq(out, expectedlen, expected, expectedlen)) { TEST_info("SipHash test #%d/2 failed.", idx); return 0; } for (half = 16; half < inlen; half += 16) { if (!TEST_true(SipHash_set_hash_size(&siphash, expectedlen)) || !TEST_true(SipHash_Init(&siphash, key, 0, 0))) return 0; SipHash_Update(&siphash, in, half); SipHash_Update(&siphash, in+half, inlen-half); if (!TEST_true(SipHash_Final(&siphash, out, expectedlen))) return 0; if (!TEST_mem_eq(out, expectedlen, expected, expectedlen)) { TEST_info("SipHash test #%d/%zu+%zu failed.", idx, half, inlen-half); return 0; } } } return 1; } static int test_siphash_basic(void) { SIPHASH siphash = { 0, }; unsigned char key[SIPHASH_KEY_SIZE]; unsigned char output[SIPHASH_MAX_DIGEST_SIZE]; /* Use invalid hash size */ return TEST_int_eq(SipHash_set_hash_size(&siphash, 4), 0) && TEST_false(SipHash_Final(&siphash, output, 0)) /* Use hash size = 8 */ && TEST_true(SipHash_set_hash_size(&siphash, 8)) && TEST_false(SipHash_Final(&siphash, output, 8)) && TEST_true(SipHash_Init(&siphash, key, 0, 0)) && TEST_true(SipHash_Final(&siphash, output, 8)) && TEST_int_eq(SipHash_Final(&siphash, output, 16), 0) /* Use hash size = 16 */ && TEST_true(SipHash_set_hash_size(&siphash, 16)) && TEST_true(SipHash_Init(&siphash, key, 0, 0)) && TEST_int_eq(SipHash_Final(&siphash, output, 8), 0) && TEST_true(SipHash_Final(&siphash, output, 16)) /* Use hash size = 0 (default = 16) */ && TEST_true(SipHash_set_hash_size(&siphash, 0)) && TEST_true(SipHash_Init(&siphash, key, 0, 0)) && TEST_int_eq(SipHash_Final(&siphash, output, 8), 0) && TEST_true(SipHash_Final(&siphash, output, 16)); } int setup_tests(void) { ADD_TEST(test_siphash_basic); ADD_ALL_TESTS(test_siphash, OSSL_NELEM(tests)); return 1; }
17,516
58.989726
120
c
openssl
openssl-master/test/sm2_internal_test.c
/* * Copyright 2017-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 */ /* * 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 <openssl/bio.h> #include <openssl/evp.h> #include <openssl/bn.h> #include <openssl/crypto.h> #include <openssl/err.h> #include <openssl/rand.h> #include "testutil.h" #ifndef OPENSSL_NO_SM2 # include "crypto/sm2.h" static fake_random_generate_cb get_faked_bytes; static OSSL_PROVIDER *fake_rand = NULL; static uint8_t *fake_rand_bytes = NULL; static size_t fake_rand_bytes_offset = 0; static size_t fake_rand_size = 0; static int get_faked_bytes(unsigned char *buf, size_t num, ossl_unused const char *name, ossl_unused EVP_RAND_CTX *ctx) { if (!TEST_ptr(fake_rand_bytes) || !TEST_size_t_gt(fake_rand_size, 0)) return 0; while (num-- > 0) { if (fake_rand_bytes_offset >= fake_rand_size) fake_rand_bytes_offset = 0; *buf++ = fake_rand_bytes[fake_rand_bytes_offset++]; } return 1; } static int start_fake_rand(const char *hex_bytes) { OPENSSL_free(fake_rand_bytes); fake_rand_bytes_offset = 0; fake_rand_size = strlen(hex_bytes) / 2; if (!TEST_ptr(fake_rand_bytes = OPENSSL_hexstr2buf(hex_bytes, NULL))) return 0; /* use own random function */ fake_rand_set_public_private_callbacks(NULL, get_faked_bytes); return 1; } static void restore_rand(void) { fake_rand_set_public_private_callbacks(NULL, NULL); OPENSSL_free(fake_rand_bytes); fake_rand_bytes = NULL; fake_rand_bytes_offset = 0; } static EC_GROUP *create_EC_group(const char *p_hex, const char *a_hex, const char *b_hex, const char *x_hex, const char *y_hex, const char *order_hex, const char *cof_hex) { BIGNUM *p = NULL; BIGNUM *a = NULL; BIGNUM *b = NULL; BIGNUM *g_x = NULL; BIGNUM *g_y = NULL; BIGNUM *order = NULL; BIGNUM *cof = NULL; EC_POINT *generator = NULL; EC_GROUP *group = NULL; int ok = 0; if (!TEST_true(BN_hex2bn(&p, p_hex)) || !TEST_true(BN_hex2bn(&a, a_hex)) || !TEST_true(BN_hex2bn(&b, b_hex))) goto done; group = EC_GROUP_new_curve_GFp(p, a, b, NULL); if (!TEST_ptr(group)) goto done; generator = EC_POINT_new(group); if (!TEST_ptr(generator)) goto done; if (!TEST_true(BN_hex2bn(&g_x, x_hex)) || !TEST_true(BN_hex2bn(&g_y, y_hex)) || !TEST_true(EC_POINT_set_affine_coordinates(group, generator, g_x, g_y, NULL))) goto done; if (!TEST_true(BN_hex2bn(&order, order_hex)) || !TEST_true(BN_hex2bn(&cof, cof_hex)) || !TEST_true(EC_GROUP_set_generator(group, generator, order, cof))) goto done; ok = 1; done: BN_free(p); BN_free(a); BN_free(b); BN_free(g_x); BN_free(g_y); EC_POINT_free(generator); BN_free(order); BN_free(cof); if (!ok) { EC_GROUP_free(group); group = NULL; } return group; } static int test_sm2_crypt(const EC_GROUP *group, const EVP_MD *digest, const char *privkey_hex, const char *message, const char *k_hex, const char *ctext_hex) { const size_t msg_len = strlen(message); BIGNUM *priv = NULL; EC_KEY *key = NULL; EC_POINT *pt = NULL; unsigned char *expected = OPENSSL_hexstr2buf(ctext_hex, NULL); size_t ctext_len = 0; size_t ptext_len = 0; uint8_t *ctext = NULL; uint8_t *recovered = NULL; size_t recovered_len = msg_len; int rc = 0; if (!TEST_ptr(expected) || !TEST_true(BN_hex2bn(&priv, privkey_hex))) goto done; key = EC_KEY_new(); if (!TEST_ptr(key) || !TEST_true(EC_KEY_set_group(key, group)) || !TEST_true(EC_KEY_set_private_key(key, priv))) goto done; pt = EC_POINT_new(group); if (!TEST_ptr(pt) || !TEST_true(EC_POINT_mul(group, pt, priv, NULL, NULL, NULL)) || !TEST_true(EC_KEY_set_public_key(key, pt)) || !TEST_true(ossl_sm2_ciphertext_size(key, digest, msg_len, &ctext_len))) goto done; ctext = OPENSSL_zalloc(ctext_len); if (!TEST_ptr(ctext)) goto done; start_fake_rand(k_hex); if (!TEST_true(ossl_sm2_encrypt(key, digest, (const uint8_t *)message, msg_len, ctext, &ctext_len))) { restore_rand(); goto done; } restore_rand(); if (!TEST_mem_eq(ctext, ctext_len, expected, ctext_len)) goto done; if (!TEST_true(ossl_sm2_plaintext_size(ctext, ctext_len, &ptext_len)) || !TEST_int_eq(ptext_len, msg_len)) goto done; recovered = OPENSSL_zalloc(ptext_len); if (!TEST_ptr(recovered) || !TEST_true(ossl_sm2_decrypt(key, digest, ctext, ctext_len, recovered, &recovered_len)) || !TEST_int_eq(recovered_len, msg_len) || !TEST_mem_eq(recovered, recovered_len, message, msg_len)) goto done; rc = 1; done: BN_free(priv); EC_POINT_free(pt); OPENSSL_free(ctext); OPENSSL_free(recovered); OPENSSL_free(expected); EC_KEY_free(key); return rc; } static int sm2_crypt_test(void) { int testresult = 0; EC_GROUP *gm_group = NULL; EC_GROUP *test_group = create_EC_group ("8542D69E4C044F18E8B92435BF6FF7DE457283915C45517D722EDB8B08F1DFC3", "787968B4FA32C3FD2417842E73BBFEFF2F3C848B6831D7E0EC65228B3937E498", "63E4C6D3B23B0C849CF84241484BFE48F61D59A5B16BA06E6E12D1DA27C5249A", "421DEBD61B62EAB6746434EBC3CC315E32220B3BADD50BDC4C4E6C147FEDD43D", "0680512BCBB42C07D47349D2153B70C4E5D7FDFCBFA36EA1A85841B9E46E09A2", "8542D69E4C044F18E8B92435BF6FF7DD297720630485628D5AE74EE7C32E79B7", "1"); if (!TEST_ptr(test_group)) goto done; if (!test_sm2_crypt( test_group, EVP_sm3(), "1649AB77A00637BD5E2EFE283FBF353534AA7F7CB89463F208DDBC2920BB0DA0", "encryption standard", "004C62EEFD6ECFC2B95B92FD6C3D9575148AFA17425546D49018E5388D49DD7B4F" "0092e8ff62146873c258557548500ab2df2a365e0609ab67640a1f6d57d7b17820" "008349312695a3e1d2f46905f39a766487f2432e95d6be0cb009fe8c69fd8825a7", "307B0220245C26FB68B1DDDDB12C4B6BF9F2B6D5FE60A383B0D18D1C4144ABF1" "7F6252E7022076CB9264C2A7E88E52B19903FDC47378F605E36811F5C07423A2" "4B84400F01B804209C3D7360C30156FAB7C80A0276712DA9D8094A634B766D3A" "285E07480653426D0413650053A89B41C418B0C3AAD00D886C00286467")) goto done; /* Same test as above except using SHA-256 instead of SM3 */ if (!test_sm2_crypt( test_group, EVP_sha256(), "1649AB77A00637BD5E2EFE283FBF353534AA7F7CB89463F208DDBC2920BB0DA0", "encryption standard", "004C62EEFD6ECFC2B95B92FD6C3D9575148AFA17425546D49018E5388D49DD7B4F" "003da18008784352192d70f22c26c243174a447ba272fec64163dd4742bae8bc98" "00df17605cf304e9dd1dfeb90c015e93b393a6f046792f790a6fa4228af67d9588", "307B0220245C26FB68B1DDDDB12C4B6BF9F2B6D5FE60A383B0D18D1C4144ABF17F" "6252E7022076CB9264C2A7E88E52B19903FDC47378F605E36811F5C07423A24B84" "400F01B80420BE89139D07853100EFA763F60CBE30099EA3DF7F8F364F9D10A5E9" "88E3C5AAFC0413229E6C9AEE2BB92CAD649FE2C035689785DA33")) goto done; /* From Annex C in both GM/T0003.5-2012 and GB/T 32918.5-2016.*/ gm_group = create_EC_group( "fffffffeffffffffffffffffffffffffffffffff00000000ffffffffffffffff", "fffffffeffffffffffffffffffffffffffffffff00000000fffffffffffffffc", "28e9fa9e9d9f5e344d5a9e4bcf6509a7f39789f515ab8f92ddbcbd414d940e93", "32c4ae2c1f1981195f9904466a39c9948fe30bbff2660be1715a4589334c74c7", "bc3736a2f4f6779c59bdcee36b692153d0a9877cc62a474002df32e52139f0a0", "fffffffeffffffffffffffffffffffff7203df6b21c6052b53bbf40939d54123", "1"); if (!TEST_ptr(gm_group)) goto done; if (!test_sm2_crypt( gm_group, EVP_sm3(), /* privkey (from which the encrypting public key is derived) */ "3945208F7B2144B13F36E38AC6D39F95889393692860B51A42FB81EF4DF7C5B8", /* plaintext message */ "encryption standard", /* ephemeral nonce k */ "59276E27D506861A16680F3AD9C02DCCEF3CC1FA3CDBE4CE6D54B80DEAC1BC21", /* * expected ciphertext, the field values are from GM/T 0003.5-2012 * (Annex C), but serialized following the ASN.1 format specified * in GM/T 0009-2012 (Sec. 7.2). */ "307C" /* SEQUENCE, 0x7c bytes */ "0220" /* INTEGER, 0x20 bytes */ "04EBFC718E8D1798620432268E77FEB6415E2EDE0E073C0F4F640ECD2E149A73" "0221" /* INTEGER, 0x21 bytes */ "00" /* leading 00 due to DER for pos. int with topmost bit set */ "E858F9D81E5430A57B36DAAB8F950A3C64E6EE6A63094D99283AFF767E124DF0" "0420" /* OCTET STRING, 0x20 bytes */ "59983C18F809E262923C53AEC295D30383B54E39D609D160AFCB1908D0BD8766" "0413" /* OCTET STRING, 0x13 bytes */ "21886CA989CA9C7D58087307CA93092D651EFA")) goto done; testresult = 1; done: EC_GROUP_free(test_group); EC_GROUP_free(gm_group); return testresult; } static int test_sm2_sign(const EC_GROUP *group, const char *userid, const char *privkey_hex, const char *message, const char *k_hex, const char *r_hex, const char *s_hex) { const size_t msg_len = strlen(message); int ok = 0; BIGNUM *priv = NULL; EC_POINT *pt = NULL; EC_KEY *key = NULL; ECDSA_SIG *sig = NULL; const BIGNUM *sig_r = NULL; const BIGNUM *sig_s = NULL; BIGNUM *r = NULL; BIGNUM *s = NULL; if (!TEST_true(BN_hex2bn(&priv, privkey_hex))) goto done; key = EC_KEY_new(); if (!TEST_ptr(key) || !TEST_true(EC_KEY_set_group(key, group)) || !TEST_true(EC_KEY_set_private_key(key, priv))) goto done; pt = EC_POINT_new(group); if (!TEST_ptr(pt) || !TEST_true(EC_POINT_mul(group, pt, priv, NULL, NULL, NULL)) || !TEST_true(EC_KEY_set_public_key(key, pt))) goto done; start_fake_rand(k_hex); sig = ossl_sm2_do_sign(key, EVP_sm3(), (const uint8_t *)userid, strlen(userid), (const uint8_t *)message, msg_len); if (!TEST_ptr(sig)) { restore_rand(); goto done; } restore_rand(); ECDSA_SIG_get0(sig, &sig_r, &sig_s); if (!TEST_true(BN_hex2bn(&r, r_hex)) || !TEST_true(BN_hex2bn(&s, s_hex)) || !TEST_BN_eq(r, sig_r) || !TEST_BN_eq(s, sig_s)) goto done; ok = ossl_sm2_do_verify(key, EVP_sm3(), sig, (const uint8_t *)userid, strlen(userid), (const uint8_t *)message, msg_len); /* We goto done whether this passes or fails */ TEST_true(ok); done: ECDSA_SIG_free(sig); EC_POINT_free(pt); EC_KEY_free(key); BN_free(priv); BN_free(r); BN_free(s); return ok; } static int sm2_sig_test(void) { int testresult = 0; EC_GROUP *gm_group = NULL; /* From draft-shen-sm2-ecdsa-02 */ EC_GROUP *test_group = create_EC_group ("8542D69E4C044F18E8B92435BF6FF7DE457283915C45517D722EDB8B08F1DFC3", "787968B4FA32C3FD2417842E73BBFEFF2F3C848B6831D7E0EC65228B3937E498", "63E4C6D3B23B0C849CF84241484BFE48F61D59A5B16BA06E6E12D1DA27C5249A", "421DEBD61B62EAB6746434EBC3CC315E32220B3BADD50BDC4C4E6C147FEDD43D", "0680512BCBB42C07D47349D2153B70C4E5D7FDFCBFA36EA1A85841B9E46E09A2", "8542D69E4C044F18E8B92435BF6FF7DD297720630485628D5AE74EE7C32E79B7", "1"); if (!TEST_ptr(test_group)) goto done; if (!TEST_true(test_sm2_sign( test_group, "[email protected]", "128B2FA8BD433C6C068C8D803DFF79792A519A55171B1B650C23661D15897263", "message digest", "006CB28D99385C175C94F94E934817663FC176D925DD72B727260DBAAE1FB2F96F" "007c47811054c6f99613a578eb8453706ccb96384fe7df5c171671e760bfa8be3a", "40F1EC59F793D9F49E09DCEF49130D4194F79FB1EED2CAA55BACDB49C4E755D1", "6FC6DAC32C5D5CF10C77DFB20F7C2EB667A457872FB09EC56327A67EC7DEEBE7"))) goto done; /* From Annex A in both GM/T0003.5-2012 and GB/T 32918.5-2016.*/ gm_group = create_EC_group( "fffffffeffffffffffffffffffffffffffffffff00000000ffffffffffffffff", "fffffffeffffffffffffffffffffffffffffffff00000000fffffffffffffffc", "28e9fa9e9d9f5e344d5a9e4bcf6509a7f39789f515ab8f92ddbcbd414d940e93", "32c4ae2c1f1981195f9904466a39c9948fe30bbff2660be1715a4589334c74c7", "bc3736a2f4f6779c59bdcee36b692153d0a9877cc62a474002df32e52139f0a0", "fffffffeffffffffffffffffffffffff7203df6b21c6052b53bbf40939d54123", "1"); if (!TEST_ptr(gm_group)) goto done; if (!TEST_true(test_sm2_sign( gm_group, /* the default ID specified in GM/T 0009-2012 (Sec. 10).*/ SM2_DEFAULT_USERID, /* privkey */ "3945208F7B2144B13F36E38AC6D39F95889393692860B51A42FB81EF4DF7C5B8", /* plaintext message */ "message digest", /* ephemeral nonce k */ "59276E27D506861A16680F3AD9C02DCCEF3CC1FA3CDBE4CE6D54B80DEAC1BC21", /* expected signature, the field values are from GM/T 0003.5-2012, Annex A. */ /* signature R, 0x20 bytes */ "F5A03B0648D2C4630EEAC513E1BB81A15944DA3827D5B74143AC7EACEEE720B3", /* signature S, 0x20 bytes */ "B1B6AA29DF212FD8763182BC0D421CA1BB9038FD1F7F42D4840B69C485BBC1AA"))) goto done; testresult = 1; done: EC_GROUP_free(test_group); EC_GROUP_free(gm_group); return testresult; } #endif int setup_tests(void) { #ifdef OPENSSL_NO_SM2 TEST_note("SM2 is disabled."); #else fake_rand = fake_rand_start(NULL); if (fake_rand == NULL) return 0; ADD_TEST(sm2_crypt_test); ADD_TEST(sm2_sig_test); #endif return 1; } void cleanup_tests(void) { #ifndef OPENSSL_NO_SM2 fake_rand_finish(fake_rand); #endif }
15,559
32.679654
93
c
openssl
openssl-master/test/sm3_internal_test.c
/* * Copyright 2021-2022 The OpenSSL Project Authors. All Rights Reserved. * Copyright 2021 UnionTech. 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 SM3 module. */ #include <string.h> #include <openssl/opensslconf.h> #include "testutil.h" #ifndef OPENSSL_NO_SM3 # include "internal/sm3.h" static int test_sm3(void) { static const unsigned char input1[] = { 0x61, 0x62, 0x63 }; /* * This test vector comes from Example 1 (A.1) of GM/T 0004-2012 */ static const unsigned char expected1[SM3_DIGEST_LENGTH] = { 0x66, 0xc7, 0xf0, 0xf4, 0x62, 0xee, 0xed, 0xd9, 0xd1, 0xf2, 0xd4, 0x6b, 0xdc, 0x10, 0xe4, 0xe2, 0x41, 0x67, 0xc4, 0x87, 0x5c, 0xf2, 0xf7, 0xa2, 0x29, 0x7d, 0xa0, 0x2b, 0x8f, 0x4b, 0xa8, 0xe0 }; static const unsigned char input2[] = { 0x61, 0x62, 0x63, 0x64, 0x61, 0x62, 0x63, 0x64, 0x61, 0x62, 0x63, 0x64, 0x61, 0x62, 0x63, 0x64, 0x61, 0x62, 0x63, 0x64, 0x61, 0x62, 0x63, 0x64, 0x61, 0x62, 0x63, 0x64, 0x61, 0x62, 0x63, 0x64, 0x61, 0x62, 0x63, 0x64, 0x61, 0x62, 0x63, 0x64, 0x61, 0x62, 0x63, 0x64, 0x61, 0x62, 0x63, 0x64, 0x61, 0x62, 0x63, 0x64, 0x61, 0x62, 0x63, 0x64, 0x61, 0x62, 0x63, 0x64, 0x61, 0x62, 0x63, 0x64 }; /* * This test vector comes from Example 2 (A.2) from GM/T 0004-2012 */ static const unsigned char expected2[SM3_DIGEST_LENGTH] = { 0xde, 0xbe, 0x9f, 0xf9, 0x22, 0x75, 0xb8, 0xa1, 0x38, 0x60, 0x48, 0x89, 0xc1, 0x8e, 0x5a, 0x4d, 0x6f, 0xdb, 0x70, 0xe5, 0x38, 0x7e, 0x57, 0x65, 0x29, 0x3d, 0xcb, 0xa3, 0x9c, 0x0c, 0x57, 0x32 }; SM3_CTX ctx1, ctx2; unsigned char md1[SM3_DIGEST_LENGTH], md2[SM3_DIGEST_LENGTH]; if (!TEST_true(ossl_sm3_init(&ctx1)) || !TEST_true(ossl_sm3_update(&ctx1, input1, sizeof(input1))) || !TEST_true(ossl_sm3_final(md1, &ctx1)) || !TEST_mem_eq(md1, SM3_DIGEST_LENGTH, expected1, SM3_DIGEST_LENGTH)) return 0; if (!TEST_true(ossl_sm3_init(&ctx2)) || !TEST_true(ossl_sm3_update(&ctx2, input2, sizeof(input2))) || !TEST_true(ossl_sm3_final(md2, &ctx2)) || !TEST_mem_eq(md2, SM3_DIGEST_LENGTH, expected2, SM3_DIGEST_LENGTH)) return 0; return 1; } #endif int setup_tests(void) { #ifndef OPENSSL_NO_SM3 ADD_TEST(test_sm3); #endif return 1; }
2,675
30.482353
82
c
openssl
openssl-master/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; }
2,342
25.931034
75
c
openssl
openssl-master/test/sparse_array_test.c
/* * Copyright 2019-2021 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 <stdio.h> #include <string.h> #include <limits.h> #include <openssl/crypto.h> #include "internal/nelem.h" #include "crypto/sparse_array.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_SPARSE_ARRAY_OF(char); static int test_sparse_array(void) { static const struct { ossl_uintmax_t n; char *v; } cases[] = { { 22, "a" }, { 0, "z" }, { 1, "b" }, { 290, "c" }, { INT_MAX, "m" }, { 6666666, "d" }, { (ossl_uintmax_t)-1, "H" }, { 99, "e" } }; SPARSE_ARRAY_OF(char) *sa; size_t i, j; int res = 0; if (!TEST_ptr(sa = ossl_sa_char_new()) || !TEST_ptr_null(ossl_sa_char_get(sa, 3)) || !TEST_ptr_null(ossl_sa_char_get(sa, 0)) || !TEST_ptr_null(ossl_sa_char_get(sa, UINT_MAX))) goto err; for (i = 0; i < OSSL_NELEM(cases); i++) { if (!TEST_true(ossl_sa_char_set(sa, cases[i].n, cases[i].v))) { TEST_note("iteration %zu", i + 1); goto err; } for (j = 0; j <= i; j++) if (!TEST_str_eq(ossl_sa_char_get(sa, cases[j].n), cases[j].v)) { TEST_note("iteration %zu / %zu", i + 1, j + 1); goto err; } } res = 1; err: ossl_sa_char_free(sa); return res; } static int test_sparse_array_num(void) { static const struct { size_t num; ossl_uintmax_t n; char *v; } cases[] = { { 1, 22, "a" }, { 2, 1021, "b" }, { 3, 3, "c" }, { 2, 22, NULL }, { 2, 3, "d" }, { 3, 22, "e" }, { 3, 666, NULL }, { 4, 666, "f" }, { 3, 3, NULL }, { 2, 22, NULL }, { 1, 666, NULL }, { 2, 64000, "g" }, { 1, 1021, NULL }, { 0, 64000, NULL }, { 1, 23, "h" }, { 0, 23, NULL } }; SPARSE_ARRAY_OF(char) *sa = NULL; size_t i; int res = 0; if (!TEST_size_t_eq(ossl_sa_char_num(NULL), 0) || !TEST_ptr(sa = ossl_sa_char_new()) || !TEST_size_t_eq(ossl_sa_char_num(sa), 0)) goto err; for (i = 0; i < OSSL_NELEM(cases); i++) if (!TEST_true(ossl_sa_char_set(sa, cases[i].n, cases[i].v)) || !TEST_size_t_eq(ossl_sa_char_num(sa), cases[i].num)) goto err; res = 1; err: ossl_sa_char_free(sa); return res; } struct index_cases_st { ossl_uintmax_t n; char *v; int del; }; struct doall_st { SPARSE_ARRAY_OF(char) *sa; size_t num_cases; const struct index_cases_st *cases; int res; int all; }; static void leaf_check_all(ossl_uintmax_t n, char *value, void *arg) { struct doall_st *doall_data = (struct doall_st *)arg; const struct index_cases_st *cases = doall_data->cases; size_t i; doall_data->res = 0; for (i = 0; i < doall_data->num_cases; i++) if ((doall_data->all || !cases[i].del) && n == cases[i].n && strcmp(value, cases[i].v) == 0) { doall_data->res = 1; return; } TEST_error("Index %ju with value %s not found", n, value); } static void leaf_delete(ossl_uintmax_t n, char *value, void *arg) { struct doall_st *doall_data = (struct doall_st *)arg; const struct index_cases_st *cases = doall_data->cases; size_t i; doall_data->res = 0; for (i = 0; i < doall_data->num_cases; i++) if (n == cases[i].n && strcmp(value, cases[i].v) == 0) { doall_data->res = 1; ossl_sa_char_set(doall_data->sa, n, NULL); return; } TEST_error("Index %ju with value %s not found", n, value); } static int test_sparse_array_doall(void) { static const struct index_cases_st cases[] = { { 22, "A", 1 }, { 1021, "b", 0 }, { 3, "c", 0 }, { INT_MAX, "d", 1 }, { (ossl_uintmax_t)-1, "H", 0 }, { (ossl_uintmax_t)-2, "i", 1 }, { 666666666, "s", 1 }, { 1234567890, "t", 0 }, }; struct doall_st doall_data; size_t i; SPARSE_ARRAY_OF(char) *sa = NULL; int res = 0; if (!TEST_ptr(sa = ossl_sa_char_new())) goto err; doall_data.num_cases = OSSL_NELEM(cases); doall_data.cases = cases; doall_data.all = 1; doall_data.sa = NULL; for (i = 0; i < OSSL_NELEM(cases); i++) if (!TEST_true(ossl_sa_char_set(sa, cases[i].n, cases[i].v))) { TEST_note("failed at iteration %zu", i + 1); goto err; } ossl_sa_char_doall_arg(sa, &leaf_check_all, &doall_data); if (doall_data.res == 0) { TEST_info("while checking all elements"); goto err; } doall_data.all = 0; doall_data.sa = sa; ossl_sa_char_doall_arg(sa, &leaf_delete, &doall_data); if (doall_data.res == 0) { TEST_info("while deleting selected elements"); goto err; } ossl_sa_char_doall_arg(sa, &leaf_check_all, &doall_data); if (doall_data.res == 0) { TEST_info("while checking for deleted elements"); goto err; } res = 1; err: ossl_sa_char_free(sa); return res; } int setup_tests(void) { ADD_TEST(test_sparse_array); ADD_TEST(test_sparse_array_num); ADD_TEST(test_sparse_array_doall); return 1; }
5,693
27.757576
78
c
openssl
openssl-master/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; }
8,294
28.310954
80
c
openssl
openssl-master/test/ssl_cert_table_internal_test.c
/* * Copyright 2017-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/ssl.h> #include "testutil.h" #include "internal/nelem.h" #include "../ssl/ssl_local.h" #include "../ssl/ssl_cert_table.h" #define test_cert_table(nid, amask, idx) \ do_test_cert_table(nid, amask, idx, #idx) static int do_test_cert_table(int nid, uint32_t amask, size_t idx, const char *idxname) { const SSL_CERT_LOOKUP *clu = &ssl_cert_info[idx]; if (clu->nid == nid && clu->amask == amask) return 1; TEST_error("Invalid table entry for certificate type %s, index %zu", idxname, idx); if (clu->nid != nid) TEST_note("Expected %s, got %s\n", OBJ_nid2sn(nid), OBJ_nid2sn(clu->nid)); if (clu->amask != amask) TEST_note("Expected auth mask 0x%x, got 0x%x\n", (unsigned int)amask, (unsigned int)clu->amask); return 0; } /* Sanity check of ssl_cert_table */ static int test_ssl_cert_table(void) { return TEST_size_t_eq(OSSL_NELEM(ssl_cert_info), SSL_PKEY_NUM) && test_cert_table(EVP_PKEY_RSA, SSL_aRSA, SSL_PKEY_RSA) && test_cert_table(EVP_PKEY_DSA, SSL_aDSS, SSL_PKEY_DSA_SIGN) && test_cert_table(EVP_PKEY_EC, SSL_aECDSA, SSL_PKEY_ECC) && test_cert_table(NID_id_GostR3410_2001, SSL_aGOST01, SSL_PKEY_GOST01) && test_cert_table(NID_id_GostR3410_2012_256, SSL_aGOST12, SSL_PKEY_GOST12_256) && test_cert_table(NID_id_GostR3410_2012_512, SSL_aGOST12, SSL_PKEY_GOST12_512) && test_cert_table(EVP_PKEY_ED25519, SSL_aECDSA, SSL_PKEY_ED25519) && test_cert_table(EVP_PKEY_ED448, SSL_aECDSA, SSL_PKEY_ED448); } int setup_tests(void) { ADD_TEST(test_ssl_cert_table); return 1; }
2,242
32.984848
77
c
openssl
openssl-master/test/ssl_ctx_test.c
/* * Copyright 2018-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 "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; }
5,558
38.425532
108
c
openssl
openssl-master/test/ssl_handshake_rtt_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 */ /* * We need access to the deprecated low level HMAC APIs for legacy purposes * when the deprecated calls are not hidden */ #ifndef OPENSSL_NO_DEPRECATED_3_0 # define OPENSSL_SUPPRESS_DEPRECATED #endif #include <stdio.h> #include <string.h> #include <openssl/opensslconf.h> #include <openssl/bio.h> #include <openssl/crypto.h> #include <openssl/ssl.h> #include <openssl/engine.h> #include "helpers/ssltestlib.h" #include "testutil.h" #include "testutil/output.h" #include "internal/ktls.h" #include "../ssl/ssl_local.h" #include "../ssl/statem/statem_local.h" static OSSL_LIB_CTX *libctx = NULL; static char *cert = NULL; static char *privkey = NULL; /* * Test 0: Clientside handshake RTT (TLSv1.2) * Test 1: Serverside handshake RTT (TLSv1.2) * Test 2: Clientside handshake RTT (TLSv1.3) * Test 3: Serverside handshake RTT (TLSv1.3) * Test 4: Clientside handshake RTT with Early Data (TLSv1.3) */ static int test_handshake_rtt(int tst) { SSL_CTX *cctx = NULL, *sctx = NULL; SSL *clientssl = NULL, *serverssl = NULL; int testresult = 0; SSL_CONNECTION *s = NULL; OSSL_STATEM *st = NULL; uint64_t rtt; #ifdef OPENSSL_NO_TLS1_2 if (tst <= 1) return 1; #endif #ifdef OSSL_NO_USABLE_TLS1_3 if (tst >= 2) return 1; #endif if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(), TLS_client_method(), TLS1_VERSION, (tst <= 1) ? TLS1_2_VERSION : TLS1_3_VERSION, &sctx, &cctx, cert, privkey)) || !TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl, NULL, NULL))) goto end; s = SSL_CONNECTION_FROM_SSL(tst % 2 == 0 ? clientssl : serverssl); if (!TEST_ptr(s) || !TEST_ptr(st = &s->statem)) return 0; /* implicitly set handshake rtt with a delay */ switch (tst) { case 0: st->hand_state = TLS_ST_CW_CLNT_HELLO; ossl_statem_client_write_transition(s); OSSL_sleep(1); st->hand_state = TLS_ST_CR_SRVR_DONE; ossl_statem_client_write_transition(s); break; case 1: st->hand_state = TLS_ST_SW_SRVR_DONE; ossl_statem_server_write_transition(s); OSSL_sleep(1); st->hand_state = TLS_ST_SR_FINISHED; ossl_statem_server_write_transition(s); break; case 2: st->hand_state = TLS_ST_CW_CLNT_HELLO; ossl_statem_client_write_transition(s); OSSL_sleep(1); st->hand_state = TLS_ST_CR_SRVR_DONE; ossl_statem_client_write_transition(s); break; case 3: st->hand_state = TLS_ST_SW_SRVR_DONE; ossl_statem_server_write_transition(s); OSSL_sleep(1); st->hand_state = TLS_ST_SR_FINISHED; ossl_statem_server_write_transition(s); break; case 4: st->hand_state = TLS_ST_EARLY_DATA; ossl_statem_client_write_transition(s); OSSL_sleep(1); st->hand_state = TLS_ST_CR_SRVR_DONE; ossl_statem_client_write_transition(s); break; } if (!TEST_int_gt(SSL_get_handshake_rtt(SSL_CONNECTION_GET_SSL(s), &rtt), 0)) goto end; /* 1 millisec is the absolute minimum it could be given the delay */ if (!TEST_uint64_t_ge(rtt, 1000)) goto end; testresult = 1; end: SSL_free(serverssl); SSL_free(clientssl); SSL_CTX_free(sctx); SSL_CTX_free(cctx); return testresult; } int setup_tests(void) { ADD_ALL_TESTS(test_handshake_rtt, 5); return 1; }
4,029
27.992806
80
c
openssl
openssl-master/test/ssl_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 <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); }
20,697
34.809689
83
c
openssl
openssl-master/test/ssl_test_ctx_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 */ /* * Ideally, CONF should offer standard parsing methods and cover them * in tests. But since we have no CONF tests, we use a custom test for now. */ #include <stdio.h> #include <string.h> #include "internal/nelem.h" #include "helpers/ssl_test_ctx.h" #include "testutil.h" #include <openssl/e_os2.h> #include <openssl/err.h> #include <openssl/conf.h> #include <openssl/ssl.h> static CONF *conf = NULL; typedef struct ssl_test_ctx_test_fixture { const char *test_case_name; const char *test_section; /* Expected parsed configuration. */ SSL_TEST_CTX *expected_ctx; } SSL_TEST_CTX_TEST_FIXTURE; static int clientconf_eq(SSL_TEST_CLIENT_CONF *conf1, SSL_TEST_CLIENT_CONF *conf2) { if (!TEST_int_eq(conf1->verify_callback, conf2->verify_callback) || !TEST_int_eq(conf1->servername, conf2->servername) || !TEST_str_eq(conf1->npn_protocols, conf2->npn_protocols) || !TEST_str_eq(conf1->alpn_protocols, conf2->alpn_protocols) || !TEST_int_eq(conf1->ct_validation, conf2->ct_validation) || !TEST_int_eq(conf1->max_fragment_len_mode, conf2->max_fragment_len_mode)) return 0; return 1; } static int serverconf_eq(SSL_TEST_SERVER_CONF *serv, SSL_TEST_SERVER_CONF *serv2) { if (!TEST_int_eq(serv->servername_callback, serv2->servername_callback) || !TEST_str_eq(serv->npn_protocols, serv2->npn_protocols) || !TEST_str_eq(serv->alpn_protocols, serv2->alpn_protocols) || !TEST_int_eq(serv->broken_session_ticket, serv2->broken_session_ticket) || !TEST_str_eq(serv->session_ticket_app_data, serv2->session_ticket_app_data) || !TEST_int_eq(serv->cert_status, serv2->cert_status)) return 0; return 1; } static int extraconf_eq(SSL_TEST_EXTRA_CONF *extra, SSL_TEST_EXTRA_CONF *extra2) { if (!TEST_true(clientconf_eq(&extra->client, &extra2->client)) || !TEST_true(serverconf_eq(&extra->server, &extra2->server)) || !TEST_true(serverconf_eq(&extra->server2, &extra2->server2))) return 0; return 1; } static int testctx_eq(SSL_TEST_CTX *ctx, SSL_TEST_CTX *ctx2) { if (!TEST_int_eq(ctx->method, ctx2->method) || !TEST_int_eq(ctx->handshake_mode, ctx2->handshake_mode) || !TEST_int_eq(ctx->app_data_size, ctx2->app_data_size) || !TEST_int_eq(ctx->max_fragment_size, ctx2->max_fragment_size) || !extraconf_eq(&ctx->extra, &ctx2->extra) || !extraconf_eq(&ctx->resume_extra, &ctx2->resume_extra) || !TEST_int_eq(ctx->expected_result, ctx2->expected_result) || !TEST_int_eq(ctx->expected_client_alert, ctx2->expected_client_alert) || !TEST_int_eq(ctx->expected_server_alert, ctx2->expected_server_alert) || !TEST_int_eq(ctx->expected_protocol, ctx2->expected_protocol) || !TEST_int_eq(ctx->expected_servername, ctx2->expected_servername) || !TEST_int_eq(ctx->session_ticket_expected, ctx2->session_ticket_expected) || !TEST_int_eq(ctx->compression_expected, ctx2->compression_expected) || !TEST_str_eq(ctx->expected_npn_protocol, ctx2->expected_npn_protocol) || !TEST_str_eq(ctx->expected_alpn_protocol, ctx2->expected_alpn_protocol) || !TEST_str_eq(ctx->expected_cipher, ctx2->expected_cipher) || !TEST_str_eq(ctx->expected_session_ticket_app_data, ctx2->expected_session_ticket_app_data) || !TEST_int_eq(ctx->resumption_expected, ctx2->resumption_expected) || !TEST_int_eq(ctx->session_id_expected, ctx2->session_id_expected)) return 0; return 1; } static SSL_TEST_CTX_TEST_FIXTURE *set_up(const char *const test_case_name) { SSL_TEST_CTX_TEST_FIXTURE *fixture; if (!TEST_ptr(fixture = OPENSSL_zalloc(sizeof(*fixture)))) return NULL; fixture->test_case_name = test_case_name; if (!TEST_ptr(fixture->expected_ctx = SSL_TEST_CTX_new(NULL))) { OPENSSL_free(fixture); return NULL; } return fixture; } static int execute_test(SSL_TEST_CTX_TEST_FIXTURE *fixture) { int success = 0; SSL_TEST_CTX *ctx; if (!TEST_ptr(ctx = SSL_TEST_CTX_create(conf, fixture->test_section, fixture->expected_ctx->libctx)) || !testctx_eq(ctx, fixture->expected_ctx)) goto err; success = 1; err: SSL_TEST_CTX_free(ctx); return success; } static void tear_down(SSL_TEST_CTX_TEST_FIXTURE *fixture) { SSL_TEST_CTX_free(fixture->expected_ctx); OPENSSL_free(fixture); } #define SETUP_SSL_TEST_CTX_TEST_FIXTURE() \ SETUP_TEST_FIXTURE(SSL_TEST_CTX_TEST_FIXTURE, set_up); #define EXECUTE_SSL_TEST_CTX_TEST() \ EXECUTE_TEST(execute_test, tear_down) static int test_empty_configuration(void) { SETUP_SSL_TEST_CTX_TEST_FIXTURE(); fixture->test_section = "ssltest_default"; fixture->expected_ctx->expected_result = SSL_TEST_SUCCESS; EXECUTE_SSL_TEST_CTX_TEST(); return result; } static int test_good_configuration(void) { SETUP_SSL_TEST_CTX_TEST_FIXTURE(); fixture->test_section = "ssltest_good"; fixture->expected_ctx->method = SSL_TEST_METHOD_DTLS; fixture->expected_ctx->handshake_mode = SSL_TEST_HANDSHAKE_RESUME; fixture->expected_ctx->app_data_size = 1024; fixture->expected_ctx->max_fragment_size = 2048; fixture->expected_ctx->expected_result = SSL_TEST_SERVER_FAIL; fixture->expected_ctx->expected_client_alert = SSL_AD_UNKNOWN_CA; fixture->expected_ctx->expected_server_alert = 0; /* No alert. */ fixture->expected_ctx->expected_protocol = TLS1_1_VERSION; fixture->expected_ctx->expected_servername = SSL_TEST_SERVERNAME_SERVER2; fixture->expected_ctx->session_ticket_expected = SSL_TEST_SESSION_TICKET_YES; fixture->expected_ctx->compression_expected = SSL_TEST_COMPRESSION_NO; fixture->expected_ctx->session_id_expected = SSL_TEST_SESSION_ID_IGNORE; fixture->expected_ctx->resumption_expected = 1; fixture->expected_ctx->extra.client.verify_callback = SSL_TEST_VERIFY_REJECT_ALL; fixture->expected_ctx->extra.client.servername = SSL_TEST_SERVERNAME_SERVER2; fixture->expected_ctx->extra.client.npn_protocols = OPENSSL_strdup("foo,bar"); if (!TEST_ptr(fixture->expected_ctx->extra.client.npn_protocols)) goto err; fixture->expected_ctx->extra.client.max_fragment_len_mode = 0; fixture->expected_ctx->extra.server.servername_callback = SSL_TEST_SERVERNAME_IGNORE_MISMATCH; fixture->expected_ctx->extra.server.broken_session_ticket = 1; fixture->expected_ctx->resume_extra.server2.alpn_protocols = OPENSSL_strdup("baz"); if (!TEST_ptr(fixture->expected_ctx->resume_extra.server2.alpn_protocols)) goto err; fixture->expected_ctx->resume_extra.client.ct_validation = SSL_TEST_CT_VALIDATION_STRICT; EXECUTE_SSL_TEST_CTX_TEST(); return result; err: tear_down(fixture); return 0; } static const char *bad_configurations[] = { "ssltest_unknown_option", "ssltest_wrong_section", "ssltest_unknown_expected_result", "ssltest_unknown_alert", "ssltest_unknown_protocol", "ssltest_unknown_verify_callback", "ssltest_unknown_servername", "ssltest_unknown_servername_callback", "ssltest_unknown_session_ticket_expected", "ssltest_unknown_compression_expected", "ssltest_unknown_session_id_expected", "ssltest_unknown_method", "ssltest_unknown_handshake_mode", "ssltest_unknown_resumption_expected", "ssltest_unknown_ct_validation", "ssltest_invalid_max_fragment_len", }; static int test_bad_configuration(int idx) { SSL_TEST_CTX *ctx; if (!TEST_ptr_null(ctx = SSL_TEST_CTX_create(conf, bad_configurations[idx], NULL))) { SSL_TEST_CTX_free(ctx); return 0; } return 1; } OPT_TEST_DECLARE_USAGE("conf_file\n") int setup_tests(void) { if (!test_skip_common_options()) { TEST_error("Error parsing test options\n"); return 0; } if (!TEST_ptr(conf = NCONF_new(NULL))) return 0; /* argument should point to test/ssl_test_ctx_test.cnf */ if (!TEST_int_gt(NCONF_load(conf, test_get_argument(0), NULL), 0)) return 0; ADD_TEST(test_empty_configuration); ADD_TEST(test_good_configuration); ADD_ALL_TESTS(test_bad_configuration, OSSL_NELEM(bad_configurations)); return 1; } void cleanup_tests(void) { NCONF_free(conf); }
9,353
34.298113
83
c
openssl
openssl-master/test/sslbuffertest.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 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/ssl.h> #include <openssl/bio.h> #include <openssl/err.h> /* We include internal headers so we can check if the buffers are allocated */ #include "../ssl/ssl_local.h" #include "../ssl/record/record_local.h" #include "internal/recordmethod.h" #include "../ssl/record/methods/recmethod_local.h" #include "internal/packet.h" #include "helpers/ssltestlib.h" #include "testutil.h" struct async_ctrs { unsigned int rctr; unsigned int wctr; }; static SSL_CTX *serverctx = NULL; static SSL_CTX *clientctx = NULL; #define MAX_ATTEMPTS 100 static int checkbuffers(SSL *s, int isalloced) { SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL(s); OSSL_RECORD_LAYER *rrl = sc->rlayer.rrl; OSSL_RECORD_LAYER *wrl = sc->rlayer.wrl; if (isalloced) return rrl->rbuf.buf != NULL && wrl->wbuf[0].buf != NULL; return rrl->rbuf.buf == NULL && wrl->wbuf[0].buf == NULL; } /* * There are 9 passes in the tests * 0 = control test * tests during writes * 1 = free buffers * 2 = + allocate buffers after free * 3 = + allocate buffers again * 4 = + free buffers after allocation * tests during reads * 5 = + free buffers * 6 = + free buffers again * 7 = + allocate buffers after free * 8 = + free buffers after allocation */ static int test_func(int test) { int result = 0; SSL *serverssl = NULL, *clientssl = NULL; int ret; size_t i, j; const char testdata[] = "Test data"; char buf[sizeof(testdata)]; if (!TEST_true(create_ssl_objects(serverctx, clientctx, &serverssl, &clientssl, NULL, NULL))) { TEST_error("Test %d failed: Create SSL objects failed\n", test); goto end; } if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE))) { TEST_error("Test %d failed: Create SSL connection failed\n", test); goto end; } /* * Send and receive some test data. Do the whole thing twice to ensure * we hit at least one async event in both reading and writing */ for (j = 0; j < 2; j++) { int len; /* * Write some test data. It should never take more than 2 attempts * (the first one might be a retryable fail). */ for (ret = -1, i = 0, len = 0; len != sizeof(testdata) && i < 2; i++) { /* test == 0 mean to free/allocate = control */ if (test >= 1 && (!TEST_true(SSL_free_buffers(clientssl)) || !TEST_true(checkbuffers(clientssl, 0)))) goto end; if (test >= 2 && (!TEST_true(SSL_alloc_buffers(clientssl)) || !TEST_true(checkbuffers(clientssl, 1)))) goto end; /* allocate a second time */ if (test >= 3 && (!TEST_true(SSL_alloc_buffers(clientssl)) || !TEST_true(checkbuffers(clientssl, 1)))) goto end; if (test >= 4 && (!TEST_true(SSL_free_buffers(clientssl)) || !TEST_true(checkbuffers(clientssl, 0)))) goto end; ret = SSL_write(clientssl, testdata + len, sizeof(testdata) - len); if (ret > 0) { len += ret; } else { int ssl_error = SSL_get_error(clientssl, ret); if (ssl_error == SSL_ERROR_SYSCALL || ssl_error == SSL_ERROR_SSL) { TEST_error("Test %d failed: Failed to write app data\n", test); goto end; } } } if (!TEST_size_t_eq(len, sizeof(testdata))) goto end; /* * Now read the test data. It may take more attempts here because * it could fail once for each byte read, including all overhead * bytes from the record header/padding etc. */ for (ret = -1, i = 0, len = 0; len != sizeof(testdata) && i < MAX_ATTEMPTS; i++) { if (test >= 5 && (!TEST_true(SSL_free_buffers(serverssl)) || !TEST_true(checkbuffers(serverssl, 0)))) goto end; /* free a second time */ if (test >= 6 && (!TEST_true(SSL_free_buffers(serverssl)) || !TEST_true(checkbuffers(serverssl, 0)))) goto end; if (test >= 7 && (!TEST_true(SSL_alloc_buffers(serverssl)) || !TEST_true(checkbuffers(serverssl, 1)))) goto end; if (test >= 8 && (!TEST_true(SSL_free_buffers(serverssl)) || !TEST_true(checkbuffers(serverssl, 0)))) goto end; ret = SSL_read(serverssl, buf + len, sizeof(buf) - len); if (ret > 0) { len += ret; } else { int ssl_error = SSL_get_error(serverssl, ret); if (ssl_error == SSL_ERROR_SYSCALL || ssl_error == SSL_ERROR_SSL) { TEST_error("Test %d failed: Failed to read app data\n", test); goto end; } } } if (!TEST_mem_eq(buf, len, testdata, sizeof(testdata))) goto end; } result = 1; end: if (!result) ERR_print_errors_fp(stderr); SSL_free(clientssl); SSL_free(serverssl); return result; } OPT_TEST_DECLARE_USAGE("certfile privkeyfile\n") int setup_tests(void) { char *cert, *pkey; if (!test_skip_common_options()) { TEST_error("Error parsing test options\n"); return 0; } if (!TEST_ptr(cert = test_get_argument(0)) || !TEST_ptr(pkey = test_get_argument(1))) return 0; if (!create_ssl_ctx_pair(NULL, TLS_server_method(), TLS_client_method(), TLS1_VERSION, 0, &serverctx, &clientctx, cert, pkey)) { TEST_error("Failed to create SSL_CTX pair\n"); return 0; } ADD_ALL_TESTS(test_func, 9); return 1; } void cleanup_tests(void) { SSL_CTX_free(clientctx); SSL_CTX_free(serverctx); }
6,596
30.564593
83
c
openssl
openssl-master/test/sslcorrupttest.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 <string.h> #include "helpers/ssltestlib.h" #include "testutil.h" static int docorrupt = 0; static void copy_flags(BIO *bio) { int flags; BIO *next = BIO_next(bio); flags = BIO_test_flags(next, BIO_FLAGS_SHOULD_RETRY | BIO_FLAGS_RWS); BIO_clear_flags(bio, BIO_FLAGS_SHOULD_RETRY | BIO_FLAGS_RWS); BIO_set_flags(bio, flags); } static int tls_corrupt_read(BIO *bio, char *out, int outl) { int ret; BIO *next = BIO_next(bio); ret = BIO_read(next, out, outl); copy_flags(bio); return ret; } static int tls_corrupt_write(BIO *bio, const char *in, int inl) { int ret; BIO *next = BIO_next(bio); char *copy; if (docorrupt) { if (!TEST_ptr(copy = OPENSSL_memdup(in, inl))) return 0; /* corrupt last bit of application data */ copy[inl-1] ^= 1; ret = BIO_write(next, copy, inl); OPENSSL_free(copy); } else { ret = BIO_write(next, in, inl); } copy_flags(bio); return ret; } static long tls_corrupt_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 = 0L; break; default: ret = BIO_ctrl(next, cmd, num, ptr); break; } return ret; } static int tls_corrupt_gets(BIO *bio, char *buf, int size) { /* We don't support this - not needed anyway */ return -1; } static int tls_corrupt_puts(BIO *bio, const char *str) { /* We don't support this - not needed anyway */ return -1; } static int tls_corrupt_new(BIO *bio) { BIO_set_init(bio, 1); return 1; } static int tls_corrupt_free(BIO *bio) { BIO_set_init(bio, 0); return 1; } #define BIO_TYPE_CUSTOM_FILTER (0x80 | BIO_TYPE_FILTER) static BIO_METHOD *method_tls_corrupt = NULL; /* Note: Not thread safe! */ static const BIO_METHOD *bio_f_tls_corrupt_filter(void) { if (method_tls_corrupt == NULL) { method_tls_corrupt = BIO_meth_new(BIO_TYPE_CUSTOM_FILTER, "TLS corrupt filter"); if (method_tls_corrupt == NULL || !BIO_meth_set_write(method_tls_corrupt, tls_corrupt_write) || !BIO_meth_set_read(method_tls_corrupt, tls_corrupt_read) || !BIO_meth_set_puts(method_tls_corrupt, tls_corrupt_puts) || !BIO_meth_set_gets(method_tls_corrupt, tls_corrupt_gets) || !BIO_meth_set_ctrl(method_tls_corrupt, tls_corrupt_ctrl) || !BIO_meth_set_create(method_tls_corrupt, tls_corrupt_new) || !BIO_meth_set_destroy(method_tls_corrupt, tls_corrupt_free)) return NULL; } return method_tls_corrupt; } static void bio_f_tls_corrupt_filter_free(void) { BIO_meth_free(method_tls_corrupt); } /* * The test is supposed to be executed with RSA key, customarily * with apps/server.pem used even in other tests. For this reason * |cipher_list| is initialized with RSA ciphers' names. This * naturally means that if test is to be re-purposed for other * type of key, then NID_auth_* filter below would need adjustment. */ static const char **cipher_list = NULL; static int setup_cipher_list(void) { SSL_CTX *ctx = NULL; SSL *ssl = NULL; STACK_OF(SSL_CIPHER) *sk_ciphers = NULL; int i, j, numciphers = 0; if (!TEST_ptr(ctx = SSL_CTX_new(TLS_server_method())) || !TEST_ptr(ssl = SSL_new(ctx)) || !TEST_ptr(sk_ciphers = SSL_get1_supported_ciphers(ssl))) goto err; /* * The |cipher_list| will be filled only with names of RSA ciphers, * so that some of the allocated space will be wasted, but the loss * is deemed acceptable... */ cipher_list = OPENSSL_malloc(sk_SSL_CIPHER_num(sk_ciphers) * sizeof(cipher_list[0])); if (!TEST_ptr(cipher_list)) goto err; for (j = 0, i = 0; i < sk_SSL_CIPHER_num(sk_ciphers); i++) { const SSL_CIPHER *cipher = sk_SSL_CIPHER_value(sk_ciphers, i); if (SSL_CIPHER_get_auth_nid(cipher) == NID_auth_rsa) cipher_list[j++] = SSL_CIPHER_get_name(cipher); } if (TEST_int_ne(j, 0)) numciphers = j; err: sk_SSL_CIPHER_free(sk_ciphers); SSL_free(ssl); SSL_CTX_free(ctx); return numciphers; } static char *cert = NULL; static char *privkey = NULL; static int test_ssl_corrupt(int testidx) { static unsigned char junk[16000] = { 0 }; SSL_CTX *sctx = NULL, *cctx = NULL; SSL *server = NULL, *client = NULL; BIO *c_to_s_fbio; int testresult = 0; STACK_OF(SSL_CIPHER) *ciphers; const SSL_CIPHER *currcipher; int err; docorrupt = 0; TEST_info("Starting #%d, %s", testidx, cipher_list[testidx]); if (!TEST_true(create_ssl_ctx_pair(NULL, TLS_server_method(), TLS_client_method(), TLS1_VERSION, 0, &sctx, &cctx, cert, privkey))) return 0; if (!TEST_true(SSL_CTX_set_dh_auto(sctx, 1)) || !TEST_true(SSL_CTX_set_cipher_list(cctx, cipher_list[testidx])) || !TEST_true(SSL_CTX_set_ciphersuites(cctx, "")) || !TEST_ptr(ciphers = SSL_CTX_get_ciphers(cctx)) || !TEST_int_eq(sk_SSL_CIPHER_num(ciphers), 1) || !TEST_ptr(currcipher = sk_SSL_CIPHER_value(ciphers, 0))) goto end; /* * No ciphers we are using are TLSv1.3 compatible so we should not attempt * to negotiate TLSv1.3 */ if (!TEST_true(SSL_CTX_set_max_proto_version(cctx, TLS1_2_VERSION))) goto end; if (!TEST_ptr(c_to_s_fbio = BIO_new(bio_f_tls_corrupt_filter()))) goto end; /* BIO is freed by create_ssl_connection on error */ if (!TEST_true(create_ssl_objects(sctx, cctx, &server, &client, NULL, c_to_s_fbio))) goto end; if (!TEST_true(create_ssl_connection(server, client, SSL_ERROR_NONE))) goto end; docorrupt = 1; if (!TEST_int_ge(SSL_write(client, junk, sizeof(junk)), 0)) goto end; if (!TEST_int_lt(SSL_read(server, junk, sizeof(junk)), 0)) goto end; do { err = ERR_get_error(); if (err == 0) { TEST_error("Decryption failed or bad record MAC not seen"); goto end; } } while (ERR_GET_REASON(err) != SSL_R_DECRYPTION_FAILED_OR_BAD_RECORD_MAC); testresult = 1; end: SSL_free(server); SSL_free(client); SSL_CTX_free(sctx); SSL_CTX_free(cctx); return testresult; } OPT_TEST_DECLARE_USAGE("certfile privkeyfile\n") int setup_tests(void) { int n; 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; n = setup_cipher_list(); if (n > 0) ADD_ALL_TESTS(test_ssl_corrupt, n); return 1; } void cleanup_tests(void) { bio_f_tls_corrupt_filter_free(); OPENSSL_free(cipher_list); }
7,511
25.733096
79
c
openssl
openssl-master/test/stack_test.c
/* * Copyright 2017-2021 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/safestack.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 typedef struct { int n; char c; } SS; typedef union { int n; char c; } SU; DEFINE_SPECIAL_STACK_OF(sint, int) DEFINE_SPECIAL_STACK_OF_CONST(uchar, unsigned char) DEFINE_STACK_OF(SS) DEFINE_STACK_OF_CONST(SU) static int int_compare(const int *const *a, const int *const *b) { if (**a < **b) return -1; if (**a > **b) return 1; return 0; } static int test_int_stack(int reserve) { static int v[] = { 1, 2, -4, 16, 999, 1, -173, 1, 9 }; static int notpresent = -1; const int n = OSSL_NELEM(v); static struct { int value; int unsorted; int sorted; int ex; } finds[] = { { 2, 1, 5, 5 }, { 9, 7, 6, 6 }, { -173, 5, 0, 0 }, { 999, 3, 8, 8 }, { 0, -1, -1, 1 } }; const int n_finds = OSSL_NELEM(finds); static struct { int value; int ex; } exfinds[] = { { 3, 5 }, { 1000, 8 }, { 20, 8 }, { -999, 0 }, { -5, 0 }, { 8, 5 } }; const int n_exfinds = OSSL_NELEM(exfinds); STACK_OF(sint) *s = sk_sint_new_null(); int i; int testresult = 0; if (!TEST_ptr(s) || (reserve > 0 && !TEST_true(sk_sint_reserve(s, 5 * reserve)))) goto end; /* Check push and num */ for (i = 0; i < n; i++) { if (!TEST_int_eq(sk_sint_num(s), i)) { TEST_info("int stack size %d", i); goto end; } sk_sint_push(s, v + i); } if (!TEST_int_eq(sk_sint_num(s), n)) goto end; /* check the values */ for (i = 0; i < n; i++) if (!TEST_ptr_eq(sk_sint_value(s, i), v + i)) { TEST_info("int value %d", i); goto end; } /* find unsorted -- the pointers are compared */ for (i = 0; i < n_finds; i++) { int *val = (finds[i].unsorted == -1) ? &notpresent : v + finds[i].unsorted; if (!TEST_int_eq(sk_sint_find(s, val), finds[i].unsorted)) { TEST_info("int unsorted find %d", i); goto end; } } /* find_ex unsorted */ for (i = 0; i < n_finds; i++) { int *val = (finds[i].unsorted == -1) ? &notpresent : v + finds[i].unsorted; if (!TEST_int_eq(sk_sint_find_ex(s, val), finds[i].unsorted)) { TEST_info("int unsorted find_ex %d", i); goto end; } } /* sorting */ if (!TEST_false(sk_sint_is_sorted(s))) goto end; (void)sk_sint_set_cmp_func(s, &int_compare); sk_sint_sort(s); if (!TEST_true(sk_sint_is_sorted(s))) goto end; /* find sorted -- the value is matched so we don't need to locate it */ for (i = 0; i < n_finds; i++) if (!TEST_int_eq(sk_sint_find(s, &finds[i].value), finds[i].sorted)) { TEST_info("int sorted find %d", i); goto end; } /* find_ex sorted */ for (i = 0; i < n_finds; i++) if (!TEST_int_eq(sk_sint_find_ex(s, &finds[i].value), finds[i].ex)) { TEST_info("int sorted find_ex present %d", i); goto end; } for (i = 0; i < n_exfinds; i++) if (!TEST_int_eq(sk_sint_find_ex(s, &exfinds[i].value), exfinds[i].ex)) { TEST_info("int sorted find_ex absent %d", i); goto end; } /* shift */ if (!TEST_ptr_eq(sk_sint_shift(s), v + 6)) goto end; testresult = 1; end: sk_sint_free(s); return testresult; } static int uchar_compare(const unsigned char *const *a, const unsigned char *const *b) { return **a - (signed int)**b; } static int test_uchar_stack(int reserve) { static const unsigned char v[] = { 1, 3, 7, 5, 255, 0 }; const int n = OSSL_NELEM(v); STACK_OF(uchar) *s = sk_uchar_new(&uchar_compare), *r = NULL; int i; int testresult = 0; if (!TEST_ptr(s) || (reserve > 0 && !TEST_true(sk_uchar_reserve(s, 5 * reserve)))) goto end; /* unshift and num */ for (i = 0; i < n; i++) { if (!TEST_int_eq(sk_uchar_num(s), i)) { TEST_info("uchar stack size %d", i); goto end; } sk_uchar_unshift(s, v + i); } if (!TEST_int_eq(sk_uchar_num(s), n)) goto end; /* dup */ r = sk_uchar_dup(NULL); if (sk_uchar_num(r) != 0) goto end; sk_uchar_free(r); r = sk_uchar_dup(s); if (!TEST_int_eq(sk_uchar_num(r), n)) goto end; sk_uchar_sort(r); /* pop */ for (i = 0; i < n; i++) if (!TEST_ptr_eq(sk_uchar_pop(s), v + i)) { TEST_info("uchar pop %d", i); goto end; } /* free -- we rely on the debug malloc to detect leakage here */ sk_uchar_free(s); s = NULL; /* dup again */ if (!TEST_int_eq(sk_uchar_num(r), n)) goto end; /* zero */ sk_uchar_zero(r); if (!TEST_int_eq(sk_uchar_num(r), 0)) goto end; /* insert */ sk_uchar_insert(r, v, 0); sk_uchar_insert(r, v + 2, -1); sk_uchar_insert(r, v + 1, 1); for (i = 0; i < 3; i++) if (!TEST_ptr_eq(sk_uchar_value(r, i), v + i)) { TEST_info("uchar insert %d", i); goto end; } /* delete */ if (!TEST_ptr_null(sk_uchar_delete(r, 12))) goto end; if (!TEST_ptr_eq(sk_uchar_delete(r, 1), v + 1)) goto end; /* set */ (void)sk_uchar_set(r, 1, v + 1); for (i = 0; i < 2; i++) if (!TEST_ptr_eq(sk_uchar_value(r, i), v + i)) { TEST_info("uchar set %d", i); goto end; } testresult = 1; end: sk_uchar_free(r); sk_uchar_free(s); return testresult; } static SS *SS_copy(const SS *p) { SS *q = OPENSSL_malloc(sizeof(*q)); if (q != NULL) memcpy(q, p, sizeof(*q)); return q; } static void SS_free(SS *p) { OPENSSL_free(p); } static int test_SS_stack(void) { STACK_OF(SS) *s = sk_SS_new_null(); STACK_OF(SS) *r = NULL; SS *v[10], *p; const int n = OSSL_NELEM(v); int i; int testresult = 0; /* allocate and push */ for (i = 0; i < n; i++) { v[i] = OPENSSL_malloc(sizeof(*v[i])); if (!TEST_ptr(v[i])) goto end; v[i]->n = i; v[i]->c = 'A' + i; if (!TEST_int_eq(sk_SS_num(s), i)) { TEST_info("SS stack size %d", i); goto end; } sk_SS_push(s, v[i]); } if (!TEST_int_eq(sk_SS_num(s), n)) goto end; /* deepcopy */ r = sk_SS_deep_copy(NULL, &SS_copy, &SS_free); if (sk_SS_num(r) != 0) goto end; sk_SS_free(r); r = sk_SS_deep_copy(s, &SS_copy, &SS_free); if (!TEST_ptr(r)) goto end; for (i = 0; i < n; i++) { p = sk_SS_value(r, i); if (!TEST_ptr_ne(p, v[i])) { TEST_info("SS deepcopy non-copy %d", i); goto end; } if (!TEST_int_eq(p->n, v[i]->n)) { TEST_info("test SS deepcopy int %d", i); goto end; } if (!TEST_char_eq(p->c, v[i]->c)) { TEST_info("SS deepcopy char %d", i); goto end; } } /* pop_free - we rely on the malloc debug to catch the leak */ sk_SS_pop_free(r, &SS_free); r = NULL; /* delete_ptr */ p = sk_SS_delete_ptr(s, v[3]); if (!TEST_ptr(p)) goto end; SS_free(p); if (!TEST_int_eq(sk_SS_num(s), n - 1)) goto end; for (i = 0; i < n-1; i++) if (!TEST_ptr_eq(sk_SS_value(s, i), v[i<3 ? i : 1+i])) { TEST_info("SS delete ptr item %d", i); goto end; } testresult = 1; end: sk_SS_pop_free(r, &SS_free); sk_SS_pop_free(s, &SS_free); return testresult; } static int test_SU_stack(void) { STACK_OF(SU) *s = sk_SU_new_null(); SU v[10]; const int n = OSSL_NELEM(v); int i; int testresult = 0; /* allocate and push */ for (i = 0; i < n; i++) { if ((i & 1) == 0) v[i].n = i; else v[i].c = 'A' + i; if (!TEST_int_eq(sk_SU_num(s), i)) { TEST_info("SU stack size %d", i); goto end; } sk_SU_push(s, v + i); } if (!TEST_int_eq(sk_SU_num(s), n)) goto end; /* check the pointers are correct */ for (i = 0; i < n; i++) if (!TEST_ptr_eq(sk_SU_value(s, i), v + i)) { TEST_info("SU pointer check %d", i); goto end; } testresult = 1; end: sk_SU_free(s); return testresult; } int setup_tests(void) { ADD_ALL_TESTS(test_int_stack, 4); ADD_ALL_TESTS(test_uchar_stack, 4); ADD_TEST(test_SS_stack); ADD_TEST(test_SU_stack); return 1; }
9,662
23.840617
81
c
openssl
openssl-master/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); }
1,175
22.058824
78
c
openssl
openssl-master/test/test_test.c
/* * Copyright 2017-2018 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/err.h> #include <openssl/crypto.h> #include <openssl/bn.h> #include "internal/nelem.h" #include "testutil.h" #define TEST(expected, test) test_case((expected), #test, (test)) static int test_case(int expected, const char *test, int result) { if (result != expected) { fprintf(stderr, "# FATAL: %s != %d\n", test, expected); return 0; } return 1; } static int test_int(void) { if (!TEST(1, TEST_int_eq(1, 1)) || !TEST(0, TEST_int_eq(1, -1)) || !TEST(1, TEST_int_ne(1, 2)) || !TEST(0, TEST_int_ne(3, 3)) || !TEST(1, TEST_int_lt(4, 9)) || !TEST(0, TEST_int_lt(9, 4)) || !TEST(1, TEST_int_le(4, 9)) || !TEST(1, TEST_int_le(5, 5)) || !TEST(0, TEST_int_le(9, 4)) || !TEST(1, TEST_int_gt(8, 5)) || !TEST(0, TEST_int_gt(5, 8)) || !TEST(1, TEST_int_ge(8, 5)) || !TEST(1, TEST_int_ge(6, 6)) || !TEST(0, TEST_int_ge(5, 8))) goto err; return 1; err: return 0; } static int test_uint(void) { if (!TEST(1, TEST_uint_eq(3u, 3u)) || !TEST(0, TEST_uint_eq(3u, 5u)) || !TEST(1, TEST_uint_ne(4u, 2u)) || !TEST(0, TEST_uint_ne(6u, 6u)) || !TEST(1, TEST_uint_lt(5u, 9u)) || !TEST(0, TEST_uint_lt(9u, 5u)) || !TEST(1, TEST_uint_le(5u, 9u)) || !TEST(1, TEST_uint_le(7u, 7u)) || !TEST(0, TEST_uint_le(9u, 5u)) || !TEST(1, TEST_uint_gt(11u, 1u)) || !TEST(0, TEST_uint_gt(1u, 11u)) || !TEST(1, TEST_uint_ge(11u, 1u)) || !TEST(1, TEST_uint_ge(6u, 6u)) || !TEST(0, TEST_uint_ge(1u, 11u))) goto err; return 1; err: return 0; } static int test_char(void) { if (!TEST(1, TEST_char_eq('a', 'a')) || !TEST(0, TEST_char_eq('a', 'A')) || !TEST(1, TEST_char_ne('a', 'c')) || !TEST(0, TEST_char_ne('e', 'e')) || !TEST(1, TEST_char_lt('i', 'x')) || !TEST(0, TEST_char_lt('x', 'i')) || !TEST(1, TEST_char_le('i', 'x')) || !TEST(1, TEST_char_le('n', 'n')) || !TEST(0, TEST_char_le('x', 'i')) || !TEST(1, TEST_char_gt('w', 'n')) || !TEST(0, TEST_char_gt('n', 'w')) || !TEST(1, TEST_char_ge('w', 'n')) || !TEST(1, TEST_char_ge('p', 'p')) || !TEST(0, TEST_char_ge('n', 'w'))) goto err; return 1; err: return 0; } static int test_uchar(void) { if (!TEST(1, TEST_uchar_eq(49, 49)) || !TEST(0, TEST_uchar_eq(49, 60)) || !TEST(1, TEST_uchar_ne(50, 2)) || !TEST(0, TEST_uchar_ne(66, 66)) || !TEST(1, TEST_uchar_lt(60, 80)) || !TEST(0, TEST_uchar_lt(80, 60)) || !TEST(1, TEST_uchar_le(60, 80)) || !TEST(1, TEST_uchar_le(78, 78)) || !TEST(0, TEST_uchar_le(80, 60)) || !TEST(1, TEST_uchar_gt(88, 37)) || !TEST(0, TEST_uchar_gt(37, 88)) || !TEST(1, TEST_uchar_ge(88, 37)) || !TEST(1, TEST_uchar_ge(66, 66)) || !TEST(0, TEST_uchar_ge(37, 88))) goto err; return 1; err: return 0; } static int test_long(void) { if (!TEST(1, TEST_long_eq(123l, 123l)) || !TEST(0, TEST_long_eq(123l, -123l)) || !TEST(1, TEST_long_ne(123l, 500l)) || !TEST(0, TEST_long_ne(1000l, 1000l)) || !TEST(1, TEST_long_lt(-8923l, 102934563l)) || !TEST(0, TEST_long_lt(102934563l, -8923l)) || !TEST(1, TEST_long_le(-8923l, 102934563l)) || !TEST(1, TEST_long_le(12345l, 12345l)) || !TEST(0, TEST_long_le(102934563l, -8923l)) || !TEST(1, TEST_long_gt(84325677l, 12345l)) || !TEST(0, TEST_long_gt(12345l, 84325677l)) || !TEST(1, TEST_long_ge(84325677l, 12345l)) || !TEST(1, TEST_long_ge(465869l, 465869l)) || !TEST(0, TEST_long_ge(12345l, 84325677l))) goto err; return 1; err: return 0; } static int test_ulong(void) { if (!TEST(1, TEST_ulong_eq(919ul, 919ul)) || !TEST(0, TEST_ulong_eq(919ul, 10234ul)) || !TEST(1, TEST_ulong_ne(8190ul, 66ul)) || !TEST(0, TEST_ulong_ne(10555ul, 10555ul)) || !TEST(1, TEST_ulong_lt(10234ul, 1000000ul)) || !TEST(0, TEST_ulong_lt(1000000ul, 10234ul)) || !TEST(1, TEST_ulong_le(10234ul, 1000000ul)) || !TEST(1, TEST_ulong_le(100000ul, 100000ul)) || !TEST(0, TEST_ulong_le(1000000ul, 10234ul)) || !TEST(1, TEST_ulong_gt(100000000ul, 22ul)) || !TEST(0, TEST_ulong_gt(22ul, 100000000ul)) || !TEST(1, TEST_ulong_ge(100000000ul, 22ul)) || !TEST(1, TEST_ulong_ge(10555ul, 10555ul)) || !TEST(0, TEST_ulong_ge(22ul, 100000000ul))) goto err; return 1; err: return 0; } static int test_size_t(void) { if (!TEST(1, TEST_size_t_eq((size_t)10, (size_t)10)) || !TEST(0, TEST_size_t_eq((size_t)10, (size_t)12)) || !TEST(1, TEST_size_t_ne((size_t)10, (size_t)12)) || !TEST(0, TEST_size_t_ne((size_t)24, (size_t)24)) || !TEST(1, TEST_size_t_lt((size_t)30, (size_t)88)) || !TEST(0, TEST_size_t_lt((size_t)88, (size_t)30)) || !TEST(1, TEST_size_t_le((size_t)30, (size_t)88)) || !TEST(1, TEST_size_t_le((size_t)33, (size_t)33)) || !TEST(0, TEST_size_t_le((size_t)88, (size_t)30)) || !TEST(1, TEST_size_t_gt((size_t)52, (size_t)33)) || !TEST(0, TEST_size_t_gt((size_t)33, (size_t)52)) || !TEST(1, TEST_size_t_ge((size_t)52, (size_t)33)) || !TEST(1, TEST_size_t_ge((size_t)38, (size_t)38)) || !TEST(0, TEST_size_t_ge((size_t)33, (size_t)52))) goto err; return 1; err: return 0; } static int test_time_t(void) { if (!TEST(1, TEST_time_t_eq((time_t)10, (time_t)10)) || !TEST(0, TEST_time_t_eq((time_t)10, (time_t)12)) || !TEST(1, TEST_time_t_ne((time_t)10, (time_t)12)) || !TEST(0, TEST_time_t_ne((time_t)24, (time_t)24)) || !TEST(1, TEST_time_t_lt((time_t)30, (time_t)88)) || !TEST(0, TEST_time_t_lt((time_t)88, (time_t)30)) || !TEST(1, TEST_time_t_le((time_t)30, (time_t)88)) || !TEST(1, TEST_time_t_le((time_t)33, (time_t)33)) || !TEST(0, TEST_time_t_le((time_t)88, (time_t)30)) || !TEST(1, TEST_time_t_gt((time_t)52, (time_t)33)) || !TEST(0, TEST_time_t_gt((time_t)33, (time_t)52)) || !TEST(1, TEST_time_t_ge((time_t)52, (time_t)33)) || !TEST(1, TEST_time_t_ge((time_t)38, (time_t)38)) || !TEST(0, TEST_time_t_ge((time_t)33, (time_t)52))) goto err; return 1; err: return 0; } static int test_pointer(void) { int x = 0; char y = 1; if (!TEST(1, TEST_ptr(&y)) || !TEST(0, TEST_ptr(NULL)) || !TEST(0, TEST_ptr_null(&y)) || !TEST(1, TEST_ptr_null(NULL)) || !TEST(1, TEST_ptr_eq(NULL, NULL)) || !TEST(0, TEST_ptr_eq(NULL, &y)) || !TEST(0, TEST_ptr_eq(&y, NULL)) || !TEST(0, TEST_ptr_eq(&y, &x)) || !TEST(1, TEST_ptr_eq(&x, &x)) || !TEST(0, TEST_ptr_ne(NULL, NULL)) || !TEST(1, TEST_ptr_ne(NULL, &y)) || !TEST(1, TEST_ptr_ne(&y, NULL)) || !TEST(1, TEST_ptr_ne(&y, &x)) || !TEST(0, TEST_ptr_ne(&x, &x))) goto err; return 1; err: return 0; } static int test_bool(void) { if (!TEST(0, TEST_true(0)) || !TEST(1, TEST_true(1)) || !TEST(1, TEST_false(0)) || !TEST(0, TEST_false(1))) goto err; return 1; err: return 0; } static int test_string(void) { static char buf[] = "abc"; if (!TEST(1, TEST_str_eq(NULL, NULL)) || !TEST(1, TEST_str_eq("abc", buf)) || !TEST(0, TEST_str_eq("abc", NULL)) || !TEST(0, TEST_str_eq("abc", "")) || !TEST(0, TEST_str_eq(NULL, buf)) || !TEST(0, TEST_str_ne(NULL, NULL)) || !TEST(0, TEST_str_eq("", NULL)) || !TEST(0, TEST_str_eq(NULL, "")) || !TEST(0, TEST_str_ne("", "")) || !TEST(0, TEST_str_eq("\1\2\3\4\5", "\1x\3\6\5")) || !TEST(0, TEST_str_ne("abc", buf)) || !TEST(1, TEST_str_ne("abc", NULL)) || !TEST(1, TEST_str_ne(NULL, buf)) || !TEST(0, TEST_str_eq("abcdef", "abcdefghijk"))) goto err; return 1; err: return 0; } static int test_memory(void) { static char buf[] = "xyz"; if (!TEST(1, TEST_mem_eq(NULL, 0, NULL, 0)) || !TEST(1, TEST_mem_eq(NULL, 1, NULL, 2)) || !TEST(0, TEST_mem_eq(NULL, 0, "xyz", 3)) || !TEST(0, TEST_mem_eq(NULL, 7, "abc", 3)) || !TEST(0, TEST_mem_ne(NULL, 0, NULL, 0)) || !TEST(0, TEST_mem_eq(NULL, 0, "", 0)) || !TEST(0, TEST_mem_eq("", 0, NULL, 0)) || !TEST(0, TEST_mem_ne("", 0, "", 0)) || !TEST(0, TEST_mem_eq("xyz", 3, NULL, 0)) || !TEST(0, TEST_mem_eq("xyz", 3, buf, sizeof(buf))) || !TEST(1, TEST_mem_eq("xyz", 4, buf, sizeof(buf)))) goto err; return 1; err: return 0; } static int test_memory_overflow(void) { /* Verify that the memory printing overflows without walking the stack */ const char *p = "1234567890123456789012345678901234567890123456789012"; const char *q = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; return TEST(0, TEST_mem_eq(p, strlen(p), q, strlen(q))); } static int test_bignum(void) { BIGNUM *a = NULL, *b = NULL, *c = NULL; int r = 0; if (!TEST(1, TEST_int_eq(BN_dec2bn(&a, "0"), 1)) || !TEST(1, TEST_BN_eq_word(a, 0)) || !TEST(0, TEST_BN_eq_word(a, 30)) || !TEST(1, TEST_BN_abs_eq_word(a, 0)) || !TEST(0, TEST_BN_eq_one(a)) || !TEST(1, TEST_BN_eq_zero(a)) || !TEST(0, TEST_BN_ne_zero(a)) || !TEST(1, TEST_BN_le_zero(a)) || !TEST(0, TEST_BN_lt_zero(a)) || !TEST(1, TEST_BN_ge_zero(a)) || !TEST(0, TEST_BN_gt_zero(a)) || !TEST(1, TEST_BN_even(a)) || !TEST(0, TEST_BN_odd(a)) || !TEST(1, TEST_BN_eq(b, c)) || !TEST(0, TEST_BN_eq(a, b)) || !TEST(0, TEST_BN_ne(NULL, c)) || !TEST(1, TEST_int_eq(BN_dec2bn(&b, "1"), 1)) || !TEST(1, TEST_BN_eq_word(b, 1)) || !TEST(1, TEST_BN_eq_one(b)) || !TEST(0, TEST_BN_abs_eq_word(b, 0)) || !TEST(1, TEST_BN_abs_eq_word(b, 1)) || !TEST(0, TEST_BN_eq_zero(b)) || !TEST(1, TEST_BN_ne_zero(b)) || !TEST(0, TEST_BN_le_zero(b)) || !TEST(0, TEST_BN_lt_zero(b)) || !TEST(1, TEST_BN_ge_zero(b)) || !TEST(1, TEST_BN_gt_zero(b)) || !TEST(0, TEST_BN_even(b)) || !TEST(1, TEST_BN_odd(b)) || !TEST(1, TEST_int_eq(BN_dec2bn(&c, "-334739439"), 10)) || !TEST(0, TEST_BN_eq_word(c, 334739439)) || !TEST(1, TEST_BN_abs_eq_word(c, 334739439)) || !TEST(0, TEST_BN_eq_zero(c)) || !TEST(1, TEST_BN_ne_zero(c)) || !TEST(1, TEST_BN_le_zero(c)) || !TEST(1, TEST_BN_lt_zero(c)) || !TEST(0, TEST_BN_ge_zero(c)) || !TEST(0, TEST_BN_gt_zero(c)) || !TEST(0, TEST_BN_even(c)) || !TEST(1, TEST_BN_odd(c)) || !TEST(1, TEST_BN_eq(a, a)) || !TEST(0, TEST_BN_ne(a, a)) || !TEST(0, TEST_BN_eq(a, b)) || !TEST(1, TEST_BN_ne(a, b)) || !TEST(0, TEST_BN_lt(a, c)) || !TEST(1, TEST_BN_lt(c, b)) || !TEST(0, TEST_BN_lt(b, c)) || !TEST(0, TEST_BN_le(a, c)) || !TEST(1, TEST_BN_le(c, b)) || !TEST(0, TEST_BN_le(b, c)) || !TEST(1, TEST_BN_gt(a, c)) || !TEST(0, TEST_BN_gt(c, b)) || !TEST(1, TEST_BN_gt(b, c)) || !TEST(1, TEST_BN_ge(a, c)) || !TEST(0, TEST_BN_ge(c, b)) || !TEST(1, TEST_BN_ge(b, c))) goto err; r = 1; err: BN_free(a); BN_free(b); BN_free(c); return r; } static int test_long_output(void) { const char *p = "1234567890123456789012345678901234567890123456789012"; const char *q = "1234567890klmnopqrs01234567890EFGHIJKLM0123456789XYZ"; const char *r = "1234567890123456789012345678901234567890123456789012" "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXY+" "12345678901234567890123ABC78901234567890123456789012"; const char *s = "1234567890123456789012345678901234567890123456789012" "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXY-" "1234567890123456789012345678901234567890123456789012" "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; return TEST(0, TEST_str_eq(p, q)) & TEST(0, TEST_str_eq(q, r)) & TEST(0, TEST_str_eq(r, s)) & TEST(0, TEST_mem_eq(r, strlen(r), s, strlen(s))); } static int test_long_bignum(void) { int r; BIGNUM *a = NULL, *b = NULL, *c = NULL, *d = NULL; const char as[] = "1234567890123456789012345678901234567890123456789012" "1234567890123456789012345678901234567890123456789012" "1234567890123456789012345678901234567890123456789012" "1234567890123456789012345678901234567890123456789012" "1234567890123456789012345678901234567890123456789012" "1234567890123456789012345678901234567890123456789012" "FFFFFF"; const char bs[] = "1234567890123456789012345678901234567890123456789012" "1234567890123456789012345678901234567890123456789013" "987657"; const char cs[] = "-" /* 64 characters plus sign */ "123456789012345678901234567890" "123456789012345678901234567890" "ABCD"; const char ds[] = "-" /* 63 characters plus sign */ "23456789A123456789B123456789C" "123456789D123456789E123456789F" "ABCD"; r = TEST_true(BN_hex2bn(&a, as)) && TEST_true(BN_hex2bn(&b, bs)) && TEST_true(BN_hex2bn(&c, cs)) && TEST_true(BN_hex2bn(&d, ds)) && (TEST(0, TEST_BN_eq(a, b)) & TEST(0, TEST_BN_eq(b, a)) & TEST(0, TEST_BN_eq(b, NULL)) & TEST(0, TEST_BN_eq(NULL, a)) & TEST(1, TEST_BN_ne(a, NULL)) & TEST(0, TEST_BN_eq(c, d))); BN_free(a); BN_free(b); BN_free(c); BN_free(d); return r; } static int test_messages(void) { TEST_info("This is an %s message.", "info"); TEST_error("This is an %s message.", "error"); return 1; } static int test_single_eval(void) { int i = 4; long l = -9000; char c = 'd'; unsigned char uc = 22; unsigned long ul = 500; size_t st = 1234; char buf[4] = { 0 }, *p = buf; /* int */ return TEST_int_eq(i++, 4) && TEST_int_eq(i, 5) && TEST_int_gt(++i, 5) && TEST_int_le(5, i++) && TEST_int_ne(--i, 5) && TEST_int_eq(12, i *= 2) /* Long */ && TEST_long_eq(l--, -9000L) && TEST_long_eq(++l, -9000L) && TEST_long_ne(-9000L, l /= 2) && TEST_long_lt(--l, -4500L) /* char */ && TEST_char_eq(++c, 'e') && TEST_char_eq('e', c--) && TEST_char_ne('d', --c) && TEST_char_le('b', --c) && TEST_char_lt(c++, 'c') /* unsigned char */ && TEST_uchar_eq(22, uc++) && TEST_uchar_eq(uc /= 2, 11) && TEST_ulong_eq(ul ^= 1, 501) && TEST_ulong_eq(502, ul ^= 3) && TEST_ulong_eq(ul = ul * 3 - 6, 1500) /* size_t */ && TEST_size_t_eq((--i, st++), 1234) && TEST_size_t_eq(st, 1235) && TEST_int_eq(11, i) /* pointers */ && TEST_ptr_eq(p++, buf) && TEST_ptr_eq(buf + 2, ++p) && TEST_ptr_eq(buf, p -= 2) && TEST_ptr(++p) && TEST_ptr_eq(p, buf + 1) && TEST_ptr_null(p = NULL) /* strings */ && TEST_str_eq(p = &("123456"[1]), "23456") && TEST_str_eq("3456", ++p) && TEST_str_ne(p++, "456") /* memory */ && TEST_mem_eq(--p, sizeof("3456"), "3456", sizeof("3456")) && TEST_mem_ne(p++, sizeof("456"), "456", sizeof("456")) && TEST_mem_eq(p--, sizeof("456"), "456", sizeof("456")); } static int test_output(void) { const char s[] = "1234567890123456789012345678901234567890123456789012" "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; test_output_string("test", s, sizeof(s) - 1); test_output_memory("test", (const unsigned char *)s, sizeof(s)); return 1; } static const char *bn_output_tests[] = { NULL, "0", "-12345678", "1234567890123456789012345678901234567890123456789012" "1234567890123456789012345678901234567890123456789013" "987657" }; static int test_bn_output(int n) { BIGNUM *b = NULL; if (bn_output_tests[n] != NULL && !TEST_true(BN_hex2bn(&b, bn_output_tests[n]))) return 0; test_output_bignum(bn_output_tests[n], b); BN_free(b); return 1; } static int test_skip_one(void) { return TEST_skip("skip test"); } static int test_skip_many(int n) { return TEST_skip("skip tests: %d", n); } static int test_skip_null(void) { /* * This is not a recommended way of skipping a test, a reason or * description should be included. */ return TEST_skip(NULL); } int setup_tests(void) { ADD_TEST(test_int); ADD_TEST(test_uint); ADD_TEST(test_char); ADD_TEST(test_uchar); ADD_TEST(test_long); ADD_TEST(test_ulong); ADD_TEST(test_size_t); ADD_TEST(test_time_t); ADD_TEST(test_pointer); ADD_TEST(test_bool); ADD_TEST(test_string); ADD_TEST(test_memory); ADD_TEST(test_memory_overflow); ADD_TEST(test_bignum); ADD_TEST(test_long_bignum); ADD_TEST(test_long_output); ADD_TEST(test_messages); ADD_TEST(test_single_eval); ADD_TEST(test_output); ADD_ALL_TESTS(test_bn_output, OSSL_NELEM(bn_output_tests)); ADD_TEST(test_skip_one); ADD_TEST(test_skip_null); ADD_ALL_TESTS(test_skip_many, 3); return 1; }
18,658
31.17069
77
c
openssl
openssl-master/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; }
8,699
27.618421
88
c
openssl
openssl-master/test/threadstest.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 */ /* * The test_multi_downgrade_shared_pkey function tests the thread safety of a * deprecated function. */ #ifndef OPENSSL_NO_DEPRECATED_3_0 # define OPENSSL_SUPPRESS_DEPRECATED #endif #if defined(_WIN32) # include <windows.h> #endif #include <string.h> #include <openssl/crypto.h> #include <openssl/rsa.h> #include <openssl/aes.h> #include <openssl/err.h> #include <openssl/rand.h> #include <openssl/pem.h> #include <openssl/evp.h> #include "internal/tsan_assist.h" #include "internal/nelem.h" #include "testutil.h" #include "threadstest.h" /* Limit the maximum number of threads */ #define MAXIMUM_THREADS 10 /* Limit the maximum number of providers loaded into a library context */ #define MAXIMUM_PROVIDERS 4 static int do_fips = 0; static char *privkey; static char *config_file = NULL; static int multidefault_run = 0; static const char *default_provider[] = { "default", NULL }; static const char *fips_provider[] = { "fips", NULL }; static const char *fips_and_default_providers[] = { "default", "fips", NULL }; static CRYPTO_RWLOCK *global_lock; #ifdef TSAN_REQUIRES_LOCKING static CRYPTO_RWLOCK *tsan_lock; #endif /* Grab a globally unique integer value, return 0 on failure */ static int get_new_uid(void) { /* * Start with a nice large number to avoid potential conflicts when * we generate a new OID. */ static TSAN_QUALIFIER int current_uid = 1 << (sizeof(int) * 8 - 2); #ifdef TSAN_REQUIRES_LOCKING int r; if (!TEST_true(CRYPTO_THREAD_write_lock(tsan_lock))) return 0; r = ++current_uid; if (!TEST_true(CRYPTO_THREAD_unlock(tsan_lock))) return 0; return r; #else return tsan_counter(&current_uid); #endif } static int test_lock(void) { CRYPTO_RWLOCK *lock = CRYPTO_THREAD_lock_new(); int res; res = TEST_true(CRYPTO_THREAD_read_lock(lock)) && TEST_true(CRYPTO_THREAD_unlock(lock)) && TEST_true(CRYPTO_THREAD_write_lock(lock)) && TEST_true(CRYPTO_THREAD_unlock(lock)); CRYPTO_THREAD_lock_free(lock); return res; } static CRYPTO_ONCE once_run = CRYPTO_ONCE_STATIC_INIT; static unsigned once_run_count = 0; static void once_do_run(void) { once_run_count++; } static void once_run_thread_cb(void) { CRYPTO_THREAD_run_once(&once_run, once_do_run); } static int test_once(void) { thread_t thread; if (!TEST_true(run_thread(&thread, once_run_thread_cb)) || !TEST_true(wait_for_thread(thread)) || !CRYPTO_THREAD_run_once(&once_run, once_do_run) || !TEST_int_eq(once_run_count, 1)) return 0; return 1; } static CRYPTO_THREAD_LOCAL thread_local_key; static unsigned destructor_run_count = 0; static int thread_local_thread_cb_ok = 0; static void thread_local_destructor(void *arg) { unsigned *count; if (arg == NULL) return; count = arg; (*count)++; } static void thread_local_thread_cb(void) { void *ptr; ptr = CRYPTO_THREAD_get_local(&thread_local_key); if (!TEST_ptr_null(ptr) || !TEST_true(CRYPTO_THREAD_set_local(&thread_local_key, &destructor_run_count))) return; ptr = CRYPTO_THREAD_get_local(&thread_local_key); if (!TEST_ptr_eq(ptr, &destructor_run_count)) return; thread_local_thread_cb_ok = 1; } static int test_thread_local(void) { thread_t thread; void *ptr = NULL; if (!TEST_true(CRYPTO_THREAD_init_local(&thread_local_key, thread_local_destructor))) return 0; ptr = CRYPTO_THREAD_get_local(&thread_local_key); if (!TEST_ptr_null(ptr) || !TEST_true(run_thread(&thread, thread_local_thread_cb)) || !TEST_true(wait_for_thread(thread)) || !TEST_int_eq(thread_local_thread_cb_ok, 1)) return 0; #if defined(OPENSSL_THREADS) && !defined(CRYPTO_TDEBUG) ptr = CRYPTO_THREAD_get_local(&thread_local_key); if (!TEST_ptr_null(ptr)) return 0; # if !defined(OPENSSL_SYS_WINDOWS) if (!TEST_int_eq(destructor_run_count, 1)) return 0; # endif #endif if (!TEST_true(CRYPTO_THREAD_cleanup_local(&thread_local_key))) return 0; return 1; } static int test_atomic(void) { int val = 0, ret = 0, testresult = 0; uint64_t val64 = 1, ret64 = 0; CRYPTO_RWLOCK *lock = CRYPTO_THREAD_lock_new(); if (!TEST_ptr(lock)) return 0; if (CRYPTO_atomic_add(&val, 1, &ret, NULL)) { /* This succeeds therefore we're on a platform with lockless atomics */ if (!TEST_int_eq(val, 1) || !TEST_int_eq(val, ret)) goto err; } else { /* This failed therefore we're on a platform without lockless atomics */ if (!TEST_int_eq(val, 0) || !TEST_int_eq(val, ret)) goto err; } val = 0; ret = 0; if (!TEST_true(CRYPTO_atomic_add(&val, 1, &ret, lock))) goto err; if (!TEST_int_eq(val, 1) || !TEST_int_eq(val, ret)) goto err; if (CRYPTO_atomic_or(&val64, 2, &ret64, NULL)) { /* This succeeds therefore we're on a platform with lockless atomics */ if (!TEST_uint_eq((unsigned int)val64, 3) || !TEST_uint_eq((unsigned int)val64, (unsigned int)ret64)) goto err; } else { /* This failed therefore we're on a platform without lockless atomics */ if (!TEST_uint_eq((unsigned int)val64, 1) || !TEST_int_eq((unsigned int)ret64, 0)) goto err; } val64 = 1; ret64 = 0; if (!TEST_true(CRYPTO_atomic_or(&val64, 2, &ret64, lock))) goto err; if (!TEST_uint_eq((unsigned int)val64, 3) || !TEST_uint_eq((unsigned int)val64, (unsigned int)ret64)) goto err; ret64 = 0; if (CRYPTO_atomic_load(&val64, &ret64, NULL)) { /* This succeeds therefore we're on a platform with lockless atomics */ if (!TEST_uint_eq((unsigned int)val64, 3) || !TEST_uint_eq((unsigned int)val64, (unsigned int)ret64)) goto err; } else { /* This failed therefore we're on a platform without lockless atomics */ if (!TEST_uint_eq((unsigned int)val64, 3) || !TEST_int_eq((unsigned int)ret64, 0)) goto err; } ret64 = 0; if (!TEST_true(CRYPTO_atomic_load(&val64, &ret64, lock))) goto err; if (!TEST_uint_eq((unsigned int)val64, 3) || !TEST_uint_eq((unsigned int)val64, (unsigned int)ret64)) goto err; testresult = 1; err: CRYPTO_THREAD_lock_free(lock); return testresult; } static OSSL_LIB_CTX *multi_libctx = NULL; static int multi_success; static OSSL_PROVIDER *multi_provider[MAXIMUM_PROVIDERS + 1]; static size_t multi_num_threads; static thread_t multi_threads[MAXIMUM_THREADS]; static void multi_intialise(void) { multi_success = 1; multi_libctx = NULL; multi_num_threads = 0; memset(multi_threads, 0, sizeof(multi_threads)); memset(multi_provider, 0, sizeof(multi_provider)); } static void multi_set_success(int ok) { if (CRYPTO_THREAD_write_lock(global_lock) == 0) { /* not synchronized, but better than not reporting failure */ multi_success = ok; return; } multi_success = ok; CRYPTO_THREAD_unlock(global_lock); } static void thead_teardown_libctx(void) { OSSL_PROVIDER **p; for (p = multi_provider; *p != NULL; p++) OSSL_PROVIDER_unload(*p); OSSL_LIB_CTX_free(multi_libctx); multi_intialise(); } static int thread_setup_libctx(int libctx, const char *providers[]) { size_t n; if (libctx && !TEST_true(test_get_libctx(&multi_libctx, NULL, config_file, NULL, NULL))) return 0; if (providers != NULL) for (n = 0; providers[n] != NULL; n++) if (!TEST_size_t_lt(n, MAXIMUM_PROVIDERS) || !TEST_ptr(multi_provider[n] = OSSL_PROVIDER_load(multi_libctx, providers[n]))) { thead_teardown_libctx(); return 0; } return 1; } static int teardown_threads(void) { size_t i; for (i = 0; i < multi_num_threads; i++) if (!TEST_true(wait_for_thread(multi_threads[i]))) return 0; return 1; } static int start_threads(size_t n, void (*thread_func)(void)) { size_t i; if (!TEST_size_t_le(multi_num_threads + n, MAXIMUM_THREADS)) return 0; for (i = 0 ; i < n; i++) if (!TEST_true(run_thread(multi_threads + multi_num_threads++, thread_func))) return 0; return 1; } /* Template multi-threaded test function */ static int thread_run_test(void (*main_func)(void), size_t num_threads, void (*thread_func)(void), int libctx, const char *providers[]) { int testresult = 0; multi_intialise(); if (!thread_setup_libctx(libctx, providers) || !start_threads(num_threads, thread_func)) goto err; if (main_func != NULL) main_func(); if (!teardown_threads() || !TEST_true(multi_success)) goto err; testresult = 1; err: thead_teardown_libctx(); return testresult; } static void thread_general_worker(void) { EVP_MD_CTX *mdctx = EVP_MD_CTX_new(); EVP_MD *md = EVP_MD_fetch(multi_libctx, "SHA2-256", NULL); EVP_CIPHER_CTX *cipherctx = EVP_CIPHER_CTX_new(); EVP_CIPHER *ciph = EVP_CIPHER_fetch(multi_libctx, "AES-128-CBC", NULL); const char *message = "Hello World"; size_t messlen = strlen(message); /* Should be big enough for encryption output too */ unsigned char out[EVP_MAX_MD_SIZE]; const unsigned char key[AES_BLOCK_SIZE] = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f }; const unsigned char iv[AES_BLOCK_SIZE] = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f }; unsigned int mdoutl; int ciphoutl; EVP_PKEY *pkey = NULL; int testresult = 0; int i, isfips; isfips = OSSL_PROVIDER_available(multi_libctx, "fips"); if (!TEST_ptr(mdctx) || !TEST_ptr(md) || !TEST_ptr(cipherctx) || !TEST_ptr(ciph)) goto err; /* Do some work */ for (i = 0; i < 5; i++) { if (!TEST_true(EVP_DigestInit_ex(mdctx, md, NULL)) || !TEST_true(EVP_DigestUpdate(mdctx, message, messlen)) || !TEST_true(EVP_DigestFinal(mdctx, out, &mdoutl))) goto err; } for (i = 0; i < 5; i++) { if (!TEST_true(EVP_EncryptInit_ex(cipherctx, ciph, NULL, key, iv)) || !TEST_true(EVP_EncryptUpdate(cipherctx, out, &ciphoutl, (unsigned char *)message, messlen)) || !TEST_true(EVP_EncryptFinal(cipherctx, out, &ciphoutl))) goto err; } /* * We want the test to run quickly - not securely. * Therefore we use an insecure bit length where we can (512). * In the FIPS module though we must use a longer length. */ pkey = EVP_PKEY_Q_keygen(multi_libctx, NULL, "RSA", isfips ? 2048 : 512); if (!TEST_ptr(pkey)) goto err; testresult = 1; err: EVP_MD_CTX_free(mdctx); EVP_MD_free(md); EVP_CIPHER_CTX_free(cipherctx); EVP_CIPHER_free(ciph); EVP_PKEY_free(pkey); if (!testresult) multi_set_success(0); } static void thread_multi_simple_fetch(void) { EVP_MD *md = EVP_MD_fetch(multi_libctx, "SHA2-256", NULL); if (md != NULL) EVP_MD_free(md); else multi_set_success(0); } static EVP_PKEY *shared_evp_pkey = NULL; static void thread_shared_evp_pkey(void) { char *msg = "Hello World"; unsigned char ctbuf[256]; unsigned char ptbuf[256]; size_t ptlen, ctlen = sizeof(ctbuf); EVP_PKEY_CTX *ctx = NULL; int success = 0; int i; for (i = 0; i < 1 + do_fips; i++) { if (i > 0) EVP_PKEY_CTX_free(ctx); ctx = EVP_PKEY_CTX_new_from_pkey(multi_libctx, shared_evp_pkey, i == 0 ? "provider=default" : "provider=fips"); if (!TEST_ptr(ctx)) goto err; if (!TEST_int_ge(EVP_PKEY_encrypt_init(ctx), 0) || !TEST_int_ge(EVP_PKEY_encrypt(ctx, ctbuf, &ctlen, (unsigned char *)msg, strlen(msg)), 0)) goto err; EVP_PKEY_CTX_free(ctx); ctx = EVP_PKEY_CTX_new_from_pkey(multi_libctx, shared_evp_pkey, NULL); if (!TEST_ptr(ctx)) goto err; ptlen = sizeof(ptbuf); if (!TEST_int_ge(EVP_PKEY_decrypt_init(ctx), 0) || !TEST_int_gt(EVP_PKEY_decrypt(ctx, ptbuf, &ptlen, ctbuf, ctlen), 0) || !TEST_mem_eq(msg, strlen(msg), ptbuf, ptlen)) goto err; } success = 1; err: EVP_PKEY_CTX_free(ctx); if (!success) multi_set_success(0); } static void thread_provider_load_unload(void) { OSSL_PROVIDER *deflt = OSSL_PROVIDER_load(multi_libctx, "default"); if (!TEST_ptr(deflt) || !TEST_true(OSSL_PROVIDER_available(multi_libctx, "default"))) multi_set_success(0); OSSL_PROVIDER_unload(deflt); } static int test_multi_general_worker_default_provider(void) { return thread_run_test(&thread_general_worker, 2, &thread_general_worker, 1, default_provider); } static int test_multi_general_worker_fips_provider(void) { if (!do_fips) return TEST_skip("FIPS not supported"); return thread_run_test(&thread_general_worker, 2, &thread_general_worker, 1, fips_provider); } static int test_multi_fetch_worker(void) { return thread_run_test(&thread_multi_simple_fetch, 2, &thread_multi_simple_fetch, 1, default_provider); } static int test_multi_shared_pkey_common(void (*worker)(void)) { int testresult = 0; multi_intialise(); if (!thread_setup_libctx(1, do_fips ? fips_and_default_providers : default_provider) || !TEST_ptr(shared_evp_pkey = load_pkey_pem(privkey, multi_libctx)) || !start_threads(1, &thread_shared_evp_pkey) || !start_threads(1, worker)) goto err; thread_shared_evp_pkey(); if (!teardown_threads() || !TEST_true(multi_success)) goto err; testresult = 1; err: EVP_PKEY_free(shared_evp_pkey); thead_teardown_libctx(); return testresult; } #ifndef OPENSSL_NO_DEPRECATED_3_0 static void thread_downgrade_shared_evp_pkey(void) { /* * This test is only relevant for deprecated functions that perform * downgrading */ if (EVP_PKEY_get0_RSA(shared_evp_pkey) == NULL) multi_set_success(0); } static int test_multi_downgrade_shared_pkey(void) { return test_multi_shared_pkey_common(&thread_downgrade_shared_evp_pkey); } #endif static int test_multi_shared_pkey(void) { return test_multi_shared_pkey_common(&thread_shared_evp_pkey); } static int test_multi_load_unload_provider(void) { EVP_MD *sha256 = NULL; OSSL_PROVIDER *prov = NULL; int testresult = 0; multi_intialise(); if (!thread_setup_libctx(1, NULL) || !TEST_ptr(prov = OSSL_PROVIDER_load(multi_libctx, "default")) || !TEST_ptr(sha256 = EVP_MD_fetch(multi_libctx, "SHA2-256", NULL)) || !TEST_true(OSSL_PROVIDER_unload(prov))) goto err; prov = NULL; if (!start_threads(2, &thread_provider_load_unload)) goto err; thread_provider_load_unload(); if (!teardown_threads() || !TEST_true(multi_success)) goto err; testresult = 1; err: OSSL_PROVIDER_unload(prov); EVP_MD_free(sha256); thead_teardown_libctx(); return testresult; } static char *multi_load_provider = "legacy"; /* * This test attempts to load several providers at the same time, and if * run with a thread sanitizer, should crash if the core provider code * doesn't synchronize well enough. */ static void test_multi_load_worker(void) { OSSL_PROVIDER *prov; if (!TEST_ptr(prov = OSSL_PROVIDER_load(multi_libctx, multi_load_provider)) || !TEST_true(OSSL_PROVIDER_unload(prov))) multi_set_success(0); } static int test_multi_default(void) { /* Avoid running this test twice */ if (multidefault_run) { TEST_skip("multi default test already run"); return 1; } multidefault_run = 1; return thread_run_test(&thread_multi_simple_fetch, 2, &thread_multi_simple_fetch, 0, default_provider); } static int test_multi_load(void) { int res = 1; OSSL_PROVIDER *prov; /* The multidefault test must run prior to this test */ if (!multidefault_run) { TEST_info("Running multi default test first"); res = test_multi_default(); } /* * We use the legacy provider in test_multi_load_worker because it uses a * child libctx that might hit more codepaths that might be sensitive to * threading issues. But in a no-legacy build that won't be loadable so * we use the default provider instead. */ prov = OSSL_PROVIDER_load(NULL, "legacy"); if (prov == NULL) { TEST_info("Cannot load legacy provider - assuming this is a no-legacy build"); multi_load_provider = "default"; } OSSL_PROVIDER_unload(prov); return thread_run_test(NULL, MAXIMUM_THREADS, &test_multi_load_worker, 0, NULL) && res; } static void test_obj_create_one(void) { char tids[12], oid[40], sn[30], ln[30]; int id = get_new_uid(); BIO_snprintf(tids, sizeof(tids), "%d", id); BIO_snprintf(oid, sizeof(oid), "1.3.6.1.4.1.16604.%s", tids); BIO_snprintf(sn, sizeof(sn), "short-name-%s", tids); BIO_snprintf(ln, sizeof(ln), "long-name-%s", tids); if (!TEST_int_ne(id, 0) || !TEST_true(id = OBJ_create(oid, sn, ln)) || !TEST_true(OBJ_add_sigid(id, NID_sha3_256, NID_rsa))) multi_set_success(0); } static int test_obj_add(void) { return thread_run_test(&test_obj_create_one, MAXIMUM_THREADS, &test_obj_create_one, 1, default_provider); } static void test_lib_ctx_load_config_worker(void) { if (!TEST_int_eq(OSSL_LIB_CTX_load_config(multi_libctx, config_file), 1)) multi_set_success(0); } static int test_lib_ctx_load_config(void) { return thread_run_test(&test_lib_ctx_load_config_worker, MAXIMUM_THREADS, &test_lib_ctx_load_config_worker, 1, default_provider); } #if !defined(OPENSSL_NO_DGRAM) && !defined(OPENSSL_NO_SOCK) static BIO *multi_bio1, *multi_bio2; static void test_bio_dgram_pair_worker(void) { ossl_unused int r; int ok = 0; uint8_t ch = 0; uint8_t scratch[64]; BIO_MSG msg = {0}; size_t num_processed = 0; if (!TEST_int_eq(RAND_bytes_ex(multi_libctx, &ch, 1, 64), 1)) goto err; msg.data = scratch; msg.data_len = sizeof(scratch); /* * We do not test for failure here as recvmmsg may fail if no sendmmsg * has been called yet. The purpose of this code is to exercise tsan. */ if (ch & 2) r = BIO_sendmmsg(ch & 1 ? multi_bio2 : multi_bio1, &msg, sizeof(BIO_MSG), 1, 0, &num_processed); else r = BIO_recvmmsg(ch & 1 ? multi_bio2 : multi_bio1, &msg, sizeof(BIO_MSG), 1, 0, &num_processed); ok = 1; err: if (ok == 0) multi_set_success(0); } static int test_bio_dgram_pair(void) { int r; BIO *bio1 = NULL, *bio2 = NULL; r = BIO_new_bio_dgram_pair(&bio1, 0, &bio2, 0); if (!TEST_int_eq(r, 1)) goto err; multi_bio1 = bio1; multi_bio2 = bio2; r = thread_run_test(&test_bio_dgram_pair_worker, MAXIMUM_THREADS, &test_bio_dgram_pair_worker, 1, default_provider); err: BIO_free(bio1); BIO_free(bio2); return r; } #endif static const char *pemdataraw[] = { "-----BEGIN RSA PRIVATE KEY-----\n", "MIIBOgIBAAJBAMFcGsaxxdgiuuGmCkVImy4h99CqT7jwY3pexPGcnUFtR2Fh36Bp\n", "oncwtkZ4cAgtvd4Qs8PkxUdp6p/DlUmObdkCAwEAAQJAUR44xX6zB3eaeyvTRzms\n", "kHADrPCmPWnr8dxsNwiDGHzrMKLN+i/HAam+97HxIKVWNDH2ba9Mf1SA8xu9dcHZ\n", "AQIhAOHPCLxbtQFVxlnhSyxYeb7O323c3QulPNn3bhOipElpAiEA2zZpBE8ZXVnL\n", "74QjG4zINlDfH+EOEtjJJ3RtaYDugvECIBtsQDxXytChsRgDQ1TcXdStXPcDppie\n", "dZhm8yhRTTBZAiAZjE/U9rsIDC0ebxIAZfn3iplWh84yGB3pgUI3J5WkoQIhAInE\n", "HTUY5WRj5riZtkyGnbm3DvF+1eMtO2lYV+OuLcfE\n", "-----END RSA PRIVATE KEY-----\n", NULL }; static void test_pem_read_one(void) { EVP_PKEY *key = NULL; BIO *pem = NULL; char *pemdata; size_t len; pemdata = glue_strings(pemdataraw, &len); if (pemdata == NULL) { multi_set_success(0); goto err; } pem = BIO_new_mem_buf(pemdata, len); if (pem == NULL) { multi_set_success(0); goto err; } key = PEM_read_bio_PrivateKey(pem, NULL, NULL, NULL); if (key == NULL) multi_set_success(0); err: EVP_PKEY_free(key); BIO_free(pem); OPENSSL_free(pemdata); } /* Test reading PEM files in multiple threads */ static int test_pem_read(void) { return thread_run_test(&test_pem_read_one, MAXIMUM_THREADS, &test_pem_read_one, 1, default_provider); } typedef enum OPTION_choice { OPT_ERR = -1, OPT_EOF = 0, OPT_FIPS, OPT_CONFIG_FILE, OPT_TEST_ENUM } OPTION_CHOICE; const OPTIONS *test_get_options(void) { static const OPTIONS options[] = { OPT_TEST_OPTIONS_DEFAULT_USAGE, { "fips", OPT_FIPS, '-', "Test the FIPS provider" }, { "config", OPT_CONFIG_FILE, '<', "The configuration file to use for the libctx" }, { NULL } }; return options; } int setup_tests(void) { OPTION_CHOICE o; char *datadir; while ((o = opt_next()) != OPT_EOF) { switch (o) { case OPT_FIPS: do_fips = 1; break; case OPT_CONFIG_FILE: config_file = opt_arg(); break; case OPT_TEST_CASES: break; default: return 0; } } if (!TEST_ptr(datadir = test_get_argument(0))) return 0; privkey = test_mk_file_path(datadir, "rsakey.pem"); if (!TEST_ptr(privkey)) return 0; if (!TEST_ptr(global_lock = CRYPTO_THREAD_lock_new())) return 0; #ifdef TSAN_REQUIRES_LOCKING if (!TEST_ptr(tsan_lock = CRYPTO_THREAD_lock_new())) return 0; #endif /* Keep first to validate auto creation of default library context */ ADD_TEST(test_multi_default); ADD_TEST(test_lock); ADD_TEST(test_once); ADD_TEST(test_thread_local); ADD_TEST(test_atomic); ADD_TEST(test_multi_load); ADD_TEST(test_multi_general_worker_default_provider); ADD_TEST(test_multi_general_worker_fips_provider); ADD_TEST(test_multi_fetch_worker); ADD_TEST(test_multi_shared_pkey); #ifndef OPENSSL_NO_DEPRECATED_3_0 ADD_TEST(test_multi_downgrade_shared_pkey); #endif ADD_TEST(test_multi_load_unload_provider); ADD_TEST(test_obj_add); ADD_TEST(test_lib_ctx_load_config); #if !defined(OPENSSL_NO_DGRAM) && !defined(OPENSSL_NO_SOCK) ADD_TEST(test_bio_dgram_pair); #endif ADD_TEST(test_pem_read); return 1; } void cleanup_tests(void) { OPENSSL_free(privkey); #ifdef TSAN_REQUIRES_LOCKING CRYPTO_THREAD_lock_free(tsan_lock); #endif CRYPTO_THREAD_lock_free(global_lock); }
24,422
26.690476
86
c
openssl
openssl-master/test/threadstest_fips.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 */ #if defined(_WIN32) # include <windows.h> #endif #include "testutil.h" #include "threadstest.h" static int success; static void thread_fips_rand_fetch(void) { EVP_MD *md; if (!TEST_true(md = EVP_MD_fetch(NULL, "SHA2-256", NULL))) success = 0; EVP_MD_free(md); } static int test_fips_rand_leak(void) { thread_t thread; success = 1; if (!TEST_true(run_thread(&thread, thread_fips_rand_fetch))) return 0; if (!TEST_true(wait_for_thread(thread))) return 0; return TEST_true(success); } int setup_tests(void) { /* * This test MUST be run first. Once the default library context is set * up, this test will always pass. */ ADD_TEST(test_fips_rand_leak); return 1; }
1,084
20.7
76
c
openssl
openssl-master/test/time_offset_test.c
/* * Copyright 2017-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 */ /* time_t/offset (+/-XXXX) tests for ASN1 and X509 */ #include <stdio.h> #include <string.h> #include <time.h> #include <openssl/asn1.h> #include <openssl/x509.h> #include "testutil.h" #include "internal/nelem.h" typedef struct { const char *data; int time_result; int type; } TESTDATA; /********************************************************************** * * Test driver * ***/ static TESTDATA tests[] = { { "20001201000000Z", 0, V_ASN1_GENERALIZEDTIME }, { "20001201010000+0100", 0, V_ASN1_GENERALIZEDTIME }, { "20001201050000+0500", 0, V_ASN1_GENERALIZEDTIME }, { "20001130230000-0100", 0, V_ASN1_GENERALIZEDTIME }, { "20001130190000-0500", 0, V_ASN1_GENERALIZEDTIME }, { "20001130190001-0500", 1, V_ASN1_GENERALIZEDTIME }, /* +1 second */ { "20001130185959-0500", -1, V_ASN1_GENERALIZEDTIME }, /* -1 second */ { "001201000000Z", 0, V_ASN1_UTCTIME }, { "001201010000+0100", 0, V_ASN1_UTCTIME }, { "001201050000+0500", 0, V_ASN1_UTCTIME }, { "001130230000-0100", 0, V_ASN1_UTCTIME }, { "001130190000-0500", 0, V_ASN1_UTCTIME }, { "001201000000-0000", 0, V_ASN1_UTCTIME }, { "001201000001-0000", 1, V_ASN1_UTCTIME }, /* +1 second */ { "001130235959-0000", -1, V_ASN1_UTCTIME }, /* -1 second */ { "20001201000000+0000", 0, V_ASN1_GENERALIZEDTIME }, { "20001201000000+0100", -1, V_ASN1_GENERALIZEDTIME }, { "001201000000+0100", -1, V_ASN1_UTCTIME }, { "20001201000000-0100", 1, V_ASN1_GENERALIZEDTIME }, { "001201000000-0100", 1, V_ASN1_UTCTIME }, { "20001201123400+1234", 0, V_ASN1_GENERALIZEDTIME }, { "20001130112600-1234", 0, V_ASN1_GENERALIZEDTIME }, }; static time_t the_time = 975628800; static ASN1_TIME the_asn1_time = { 15, V_ASN1_GENERALIZEDTIME, (unsigned char*)"20001201000000Z", 0 }; static int test_offset(int idx) { ASN1_TIME at; const TESTDATA *testdata = &tests[idx]; int ret = -2; int day, sec; at.data = (unsigned char*)testdata->data; at.length = strlen(testdata->data); at.type = testdata->type; at.flags = 0; if (!TEST_true(ASN1_TIME_diff(&day, &sec, &the_asn1_time, &at))) { TEST_info("ASN1_TIME_diff() failed for %s\n", at.data); return 0; } if (day > 0) ret = 1; else if (day < 0) ret = -1; else if (sec > 0) ret = 1; else if (sec < 0) ret = -1; else ret = 0; if (!TEST_int_eq(testdata->time_result, ret)) { TEST_info("ASN1_TIME_diff() test failed for %s day=%d sec=%d\n", at.data, day, sec); return 0; } ret = ASN1_TIME_cmp_time_t(&at, the_time); if (!TEST_int_eq(testdata->time_result, ret)) { TEST_info("ASN1_UTCTIME_cmp_time_t() test failed for %s\n", at.data); return 0; } return 1; } int setup_tests(void) { ADD_ALL_TESTS(test_offset, OSSL_NELEM(tests)); return 1; }
3,299
27.947368
92
c
openssl
openssl-master/test/timing_load_creds.c
/* * Copyright 2020-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 <stdlib.h> #include <openssl/e_os2.h> #ifdef OPENSSL_SYS_UNIX # include <sys/stat.h> # include <sys/resource.h> # include <openssl/pem.h> # include <openssl/x509.h> # include <openssl/err.h> # include <openssl/bio.h> # include "internal/e_os.h" # if defined(_POSIX_VERSION) && _POSIX_VERSION >= 200112L # ifndef timersub /* struct timeval * subtraction; a must be greater than or equal to b */ # define timersub(a, b, res) \ do { \ (res)->tv_sec = (a)->tv_sec - (b)->tv_sec; \ if ((a)->tv_usec < (b)->tv_usec) { \ (res)->tv_usec = (a)->tv_usec + 1000000 - (b)->tv_usec; \ --(res)->tv_sec; \ } else { \ (res)->tv_usec = (a)->tv_usec - (b)->tv_usec; \ } \ } while(0) # endif static char *prog; static void readx509(const char *contents, int size) { X509 *x = NULL; BIO *b = BIO_new_mem_buf(contents, size); if (b == NULL) { ERR_print_errors_fp(stderr); exit(EXIT_FAILURE); } PEM_read_bio_X509(b, &x, 0, NULL); if (x == NULL) { ERR_print_errors_fp(stderr); exit(EXIT_FAILURE); } X509_free(x); BIO_free(b); } static void readpkey(const char *contents, int size) { BIO *b = BIO_new_mem_buf(contents, size); EVP_PKEY *pkey; if (b == NULL) { ERR_print_errors_fp(stderr); exit(EXIT_FAILURE); } pkey = PEM_read_bio_PrivateKey(b, NULL, NULL, NULL); if (pkey == NULL) { ERR_print_errors_fp(stderr); exit(EXIT_FAILURE); } EVP_PKEY_free(pkey); BIO_free(b); } static void print_timeval(const char *what, struct timeval *tp) { printf("%s %d sec %d microsec\n", what, (int)tp->tv_sec, (int)tp->tv_usec); } static void usage(void) { fprintf(stderr, "Usage: %s [flags] pem-file\n", prog); fprintf(stderr, "Flags, with the default being '-wc':\n"); fprintf(stderr, " -c # Repeat count\n"); fprintf(stderr, " -d Debugging output (minimal)\n"); fprintf(stderr, " -w<T> What to load T is a single character:\n"); fprintf(stderr, " c for cert\n"); fprintf(stderr, " p for private key\n"); exit(EXIT_FAILURE); } # endif #endif int main(int ac, char **av) { #if defined(_POSIX_VERSION) && _POSIX_VERSION >= 200112L int i, debug = 0, count = 100, what = 'c'; struct stat sb; FILE *fp; char *contents; struct rusage start, end, elapsed; struct timeval e_start, e_end, e_elapsed; /* Parse JCL. */ prog = av[0]; while ((i = getopt(ac, av, "c:dw:")) != EOF) { switch (i) { default: usage(); break; case 'c': if ((count = atoi(optarg)) < 0) usage(); break; case 'd': debug = 1; break; case 'w': if (optarg[1] != '\0') usage(); switch (*optarg) { default: usage(); break; case 'c': case 'p': what = *optarg; break; } break; } } ac -= optind; av += optind; /* Read input file. */ if (av[0] == NULL) usage(); if (stat(av[0], &sb) < 0) { perror(av[0]); exit(EXIT_FAILURE); } contents = OPENSSL_malloc(sb.st_size + 1); if (contents == NULL) { perror("malloc"); exit(EXIT_FAILURE); } fp = fopen(av[0], "r"); if ((long)fread(contents, 1, sb.st_size, fp) != sb.st_size) { perror("fread"); exit(EXIT_FAILURE); } contents[sb.st_size] = '\0'; fclose(fp); if (debug) printf(">%s<\n", contents); /* Try to prep system cache, etc. */ for (i = 10; i > 0; i--) { switch (what) { case 'c': readx509(contents, (int)sb.st_size); break; case 'p': readpkey(contents, (int)sb.st_size); break; } } if (gettimeofday(&e_start, NULL) < 0) { perror("elapsed start"); exit(EXIT_FAILURE); } if (getrusage(RUSAGE_SELF, &start) < 0) { perror("start"); exit(EXIT_FAILURE); } for (i = count; i > 0; i--) { switch (what) { case 'c': readx509(contents, (int)sb.st_size); break; case 'p': readpkey(contents, (int)sb.st_size); break; } } if (getrusage(RUSAGE_SELF, &end) < 0) { perror("getrusage"); exit(EXIT_FAILURE); } if (gettimeofday(&e_end, NULL) < 0) { perror("gettimeofday"); exit(EXIT_FAILURE); } timersub(&end.ru_utime, &start.ru_stime, &elapsed.ru_stime); timersub(&end.ru_utime, &start.ru_utime, &elapsed.ru_utime); timersub(&e_end, &e_start, &e_elapsed); print_timeval("user ", &elapsed.ru_utime); print_timeval("sys ", &elapsed.ru_stime); if (debug) print_timeval("elapsed??", &e_elapsed); OPENSSL_free(contents); return EXIT_SUCCESS; #else fprintf(stderr, "This tool is not supported on this platform for lack of POSIX1.2001 support\n"); exit(EXIT_FAILURE); #endif }
5,895
26.296296
93
c
openssl
openssl-master/test/tls13ccstest.c
/* * Copyright 2017-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 <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); }
15,560
29.333333
81
c
openssl
openssl-master/test/tls13encryptiontest.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 <openssl/ssl.h> #include <openssl/evp.h> #include "../ssl/ssl_local.h" #include "../ssl/record/record_local.h" #include "internal/recordmethod.h" #include "../ssl/record/methods/recmethod_local.h" #include "internal/nelem.h" #include "testutil.h" /* * Based on the test vectors provided in: * https://tools.ietf.org/html/draft-ietf-tls-tls13-vectors-06 */ typedef struct { /* * We split these into 3 chunks in order to work around the 509 character * limit that the standard specifies for string literals */ const char *plaintext[3]; const char *ciphertext[3]; const char *key; const char *iv; const char *seq; } RECORD_DATA; /* * Note 1: The plaintext values given here have an additional "16" or "17" byte * added to the end when compared to the official vectors. The official vectors * do not include the inner content type, but we require it. * * Note 2: These are the vectors for the "Simple 1-RTT Handshake" */ static RECORD_DATA refdata[] = { { /* * Server: EncryptedExtensions, Certificate, CertificateVerify and * Finished */ { "080000240022000a00140012001d00170018001901000101010201030104001c" "00024001000000000b0001b9000001b50001b0308201ac30820115a003020102" "020102300d06092a864886f70d01010b0500300e310c300a0603550403130372" "7361301e170d3136303733303031323335395a170d3236303733303031323335" "395a300e310c300a0603550403130372736130819f300d06092a864886f70d01" "0101050003818d0030818902818100b4bb498f8279303d980836399b36c6988c" "0c68de55e1bdb826d3901a2461eafd2de49a91d015abbc9a95137ace6c1af19e", "aa6af98c7ced43120998e187a80ee0ccb0524b1b018c3e0b63264d449a6d38e2" "2a5fda430846748030530ef0461c8ca9d9efbfae8ea6d1d03e2bd193eff0ab9a" "8002c47428a6d35a8d88d79f7f1e3f0203010001a31a301830090603551d1304" "023000300b0603551d0f0404030205a0300d06092a864886f70d01010b050003" "81810085aad2a0e5b9276b908c65f73a7267170618a54c5f8a7b337d2df7a594" "365417f2eae8f8a58c8f8172f9319cf36b7fd6c55b80f21a03015156726096fd" "335e5e67f2dbf102702e608ccae6bec1fc63a42a99be5c3eb7107c3c54e9b9eb", "2bd5203b1c3b84e0a8b2f759409ba3eac9d91d402dcc0cc8f8961229ac9187b4" "2b4de100000f00008408040080754040d0ddab8cf0e2da2bc4995b868ad745c8" "e1564e33cde17880a42392cc624aeef6b67bb3f0ae71d9d54a2309731d87dc59" "f642d733be2eb27484ad8a8c8eb3516a7ac57f2625e2b5c0888a8541f4e734f7" "3d054761df1dd02f0e3e9a33cfa10b6e3eb4ebf7ac053b01fdabbddfc54133bc" "d24c8bbdceb223b2aa03452a2914000020ac86acbc9cd25a45b57ad5b64db15d" "4405cf8c80e314583ebf3283ef9a99310c16" }, { "f10b26d8fcaf67b5b828f712122216a1cd14187465b77637cbcd78539128bb93" "246dcca1af56f1eaa271666077455bc54965d85f05f9bd36d6996171eb536aff" "613eeddc42bad5a2d2227c4606f1215f980e7afaf56bd3b85a51be130003101a" "758d077b1c891d8e7a22947e5a229851fd42a9dd422608f868272abf92b3d43f" "b46ac420259346067f66322fd708885680f4b4433c29116f2dfa529e09bba53c" "7cd920121724809eaddcc84307ef46fc51a0b33d99d39db337fcd761ce0f2b02" "dc73dedb6fddb77c4f8099bde93d5bee08bcf2131f29a2a37ff07949e8f8bcdd", "3e8310b8bf8b3444c85aaf0d2aeb2d4f36fd14d5cb51fcebff418b3827136ab9" "529e9a3d3f35e4c0ae749ea2dbc94982a1281d3e6daab719aa4460889321a008" "bf10fa06ac0c61cc122cc90d5e22c0030c986ae84a33a0c47df174bcfbd50bf7" "8ffdf24051ab423db63d5815db2f830040f30521131c98c66f16c362addce2fb" "a0602cf0a7dddf22e8def7516cdfee95b4056cc9ad38c95352335421b5b1ffba" "df75e5212fdad7a75f52a2801486a1eec3539580bee0e4b337cda6085ac9eccd" "1a0f1a46cebfbb5cdfa3251ac28c3bc826148c6d8c1eb6a06f77f6ff632c6a83", "e283e8f9df7c6dbabf1c6ea40629a85b43ab0c73d34f9d5072832a104eda3f75" "f5d83da6e14822a18e14099d749eafd823ca2ac7542086501eca206ce7887920" "008573757ce2f230a890782b99cc682377beee812756d04f9025135fb599d746" "fefe7316c922ac265ca0d29021375adb63c1509c3e242dfb92b8dee891f7368c" "4058399b8db9075f2dcc8216194e503b6652d87d2cb41f99adfdcc5be5ec7e1e" "6326ac22d70bd3ba652827532d669aff005173597f8039c3ea4922d3ec757670" "222f6ac29b93e90d7ad3f6dd96328e429cfcfd5cca22707fe2d86ad1dcb0be75" "6e8e" }, "c66cb1aec519df44c91e10995511ac8b", "f7f6884c4981716c2d0d29a4", "0000000000000000" }, { /* Client: Finished */ { "14000020b9027a0204b972b52cdefa58950fa1580d68c9cb124dbe691a7178f2" "5c554b2316", "", "" }, { "9539b4ae2f87fd8e616b295628ea953d9e3858db274970d19813ec136cae7d96" "e0417775fcabd3d8858fdc60240912d218f5afb21c", "", "" }, "2679a43e1d76784034ea1797d5ad2649", "5482405290dd0d2f81c0d942", "0000000000000000" }, { /* Server: NewSessionTicket */ { "040000c90000001e2fd3992f02000000b2ff099f9676cdff8b0bf8825d000000" "007905a9d28efeef4a47c6f9b06a0cecdb0070d920b898997c75b79636943ed4" "2046a96142bd084a04acfa0c490f452d756dea02c0f927259f1f3231ac0d541a" "769129b740ce38090842b828c27fd729f59737ba98aa7b42e043c5da28f8dca8" "590b2df410d5134fd6c4cacad8b30370602afa35d265bf4d127976bb36dbda6a" "626f0270e20eebc73d6fcae2b1a0da122ee9042f76be56ebf41aa469c3d2c9da" "9197d80008002a00040000040016", "", "" }, { "3680c2b2109d25caa26c3b06eea9fdc5cb31613ba702176596da2e886bf6af93" "507bd68161ad9cb4780653842e1041ecbf0088a65ac4ef438419dd1d95ddd9bd" "2ad4484e7e167d0e6c008448ae58a0418713b6fc6c51e4bb23a537fb75a74f73" "de31fe6aa0bc522515f8b25f8955428b5de5ac06762cec22b0aa78c94385ef8e" "70fa24945b7c1f268510871689bbbbfaf2e7f4a19277024f95f1143ab12a31ec" "63adb128cb390711fd6d06a498df3e98615d8eb102e23353b480efcca5e8e026" "7a6d0fe2441f14c8c9664aefb2cfff6ae9e0442728b6a0940c1e824fda06", "", "" }, "a688ebb5ac826d6f42d45c0cc44b9b7d", "c1cad4425a438b5de714830a", "0000000000000000" }, { /* Client: Application Data */ { "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f" "202122232425262728292a2b2c2d2e2f303117", "", "" }, { "8c3497da00ae023e53c01b4324b665404c1b49e78fe2bf4d17f6348ae8340551" "e363a0cd05f2179c4fef5ad689b5cae0bae94adc63632e571fb79aa91544c639" "4d28a1", "", "" }, "88b96ad686c84be55ace18a59cce5c87", "b99dc58cd5ff5ab082fdad19", "0000000000000000" }, { /* Server: Application Data */ { "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f" "202122232425262728292a2b2c2d2e2f303117", "", "" }, { "f65f49fd2df6cd2347c3d30166e3cfddb6308a5906c076112c6a37ff1dbd406b" "5813c0abd734883017a6b2833186b13c14da5d75f33d8760789994e27d82043a" "b88d65", "", "" }, "a688ebb5ac826d6f42d45c0cc44b9b7d", "c1cad4425a438b5de714830a", "0000000000000001" }, { /* Client: CloseNotify */ { "010015", "", "" }, { "2c2148163d7938a35f6acf2a6606f8cbd1d9f2", "", "" }, "88b96ad686c84be55ace18a59cce5c87", "b99dc58cd5ff5ab082fdad19", "0000000000000001" }, { /* Server: CloseNotify */ { "010015", "", "" }, { "f8141ebdb5eda511e0bce639a56ff9ea825a21", "", "" }, "a688ebb5ac826d6f42d45c0cc44b9b7d", "c1cad4425a438b5de714830a", "0000000000000002" } }; /* * Same thing as OPENSSL_hexstr2buf() but enables us to pass the string in * 3 chunks */ static unsigned char *multihexstr2buf(const char *str[3], size_t *len) { size_t outer, inner, curr = 0; unsigned char *outbuf; size_t totlen = 0; /* Check lengths of all input strings are even */ for (outer = 0; outer < 3; outer++) { totlen += strlen(str[outer]); if ((totlen & 1) != 0) return NULL; } totlen /= 2; outbuf = OPENSSL_malloc(totlen); if (outbuf == NULL) return NULL; for (outer = 0; outer < 3; outer++) { for (inner = 0; str[outer][inner] != 0; inner += 2) { int hi, lo; hi = OPENSSL_hexchar2int(str[outer][inner]); lo = OPENSSL_hexchar2int(str[outer][inner + 1]); if (hi < 0 || lo < 0) { OPENSSL_free(outbuf); return NULL; } outbuf[curr++] = (hi << 4) | lo; } } *len = totlen; return outbuf; } static int load_record(TLS_RL_RECORD *rec, RECORD_DATA *recd, unsigned char **key, unsigned char *iv, size_t ivlen, unsigned char *seq) { unsigned char *pt = NULL, *sq = NULL, *ivtmp = NULL; size_t ptlen; *key = OPENSSL_hexstr2buf(recd->key, NULL); ivtmp = OPENSSL_hexstr2buf(recd->iv, NULL); sq = OPENSSL_hexstr2buf(recd->seq, NULL); pt = multihexstr2buf(recd->plaintext, &ptlen); if (*key == NULL || ivtmp == NULL || sq == NULL || pt == NULL) goto err; rec->data = rec->input = OPENSSL_malloc(ptlen + EVP_GCM_TLS_TAG_LEN); if (rec->data == NULL) goto err; rec->length = ptlen; memcpy(rec->data, pt, ptlen); OPENSSL_free(pt); memcpy(seq, sq, SEQ_NUM_SIZE); OPENSSL_free(sq); memcpy(iv, ivtmp, ivlen); OPENSSL_free(ivtmp); return 1; err: OPENSSL_free(*key); *key = NULL; OPENSSL_free(ivtmp); OPENSSL_free(sq); OPENSSL_free(pt); return 0; } static int test_record(TLS_RL_RECORD *rec, RECORD_DATA *recd, int enc) { int ret = 0; unsigned char *refd; size_t refdatalen = 0; if (enc) refd = multihexstr2buf(recd->ciphertext, &refdatalen); else refd = multihexstr2buf(recd->plaintext, &refdatalen); if (!TEST_ptr(refd)) { TEST_info("Failed to get reference data"); goto err; } if (!TEST_mem_eq(rec->data, rec->length, refd, refdatalen)) goto err; ret = 1; err: OPENSSL_free(refd); return ret; } #define TLS13_AES_128_GCM_SHA256_BYTES ((const unsigned char *)"\x13\x01") static int test_tls13_encryption(void) { TLS_RL_RECORD rec; unsigned char *key = NULL; const EVP_CIPHER *ciph = EVP_aes_128_gcm(); int ret = 0; size_t ivlen, ctr; unsigned char seqbuf[SEQ_NUM_SIZE]; unsigned char iv[EVP_MAX_IV_LENGTH]; OSSL_RECORD_LAYER *rrl = NULL, *wrl = NULL; /* * Encrypted TLSv1.3 records always have an outer content type of * application data, and a record version of TLSv1.2. */ rec.data = NULL; rec.type = SSL3_RT_APPLICATION_DATA; rec.rec_version = TLS1_2_VERSION; for (ctr = 0; ctr < OSSL_NELEM(refdata); ctr++) { /* Load the record */ ivlen = EVP_CIPHER_get_iv_length(ciph); if (!load_record(&rec, &refdata[ctr], &key, iv, ivlen, seqbuf)) { TEST_error("Failed loading key into EVP_CIPHER_CTX"); goto err; } /* Set up the write record layer */ if (!TEST_true(ossl_tls_record_method.new_record_layer( NULL, NULL, TLS1_3_VERSION, OSSL_RECORD_ROLE_SERVER, OSSL_RECORD_DIRECTION_WRITE, OSSL_RECORD_PROTECTION_LEVEL_APPLICATION, 0, NULL, 0, key, 16, iv, ivlen, NULL, 0, EVP_aes_128_gcm(), EVP_GCM_TLS_TAG_LEN, 0, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, &wrl))) goto err; memcpy(wrl->sequence, seqbuf, sizeof(seqbuf)); /* Encrypt it */ if (!TEST_size_t_eq(wrl->funcs->cipher(wrl, &rec, 1, 1, NULL, 0), 1)) { TEST_info("Failed to encrypt record %zu", ctr); goto err; } if (!TEST_true(test_record(&rec, &refdata[ctr], 1))) { TEST_info("Record %zu encryption test failed", ctr); goto err; } /* Set up the read record layer */ if (!TEST_true(ossl_tls_record_method.new_record_layer( NULL, NULL, TLS1_3_VERSION, OSSL_RECORD_ROLE_SERVER, OSSL_RECORD_DIRECTION_READ, OSSL_RECORD_PROTECTION_LEVEL_APPLICATION, 0, NULL, 0, key, 16, iv, ivlen, NULL, 0, EVP_aes_128_gcm(), EVP_GCM_TLS_TAG_LEN, 0, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, &rrl))) goto err; memcpy(rrl->sequence, seqbuf, sizeof(seqbuf)); /* Decrypt it */ if (!TEST_int_eq(rrl->funcs->cipher(rrl, &rec, 1, 0, NULL, 0), 1)) { TEST_info("Failed to decrypt record %zu", ctr); goto err; } if (!TEST_true(test_record(&rec, &refdata[ctr], 0))) { TEST_info("Record %zu decryption test failed", ctr); goto err; } ossl_tls_record_method.free(rrl); ossl_tls_record_method.free(wrl); rrl = wrl = NULL; OPENSSL_free(rec.data); OPENSSL_free(key); rec.data = NULL; key = NULL; } TEST_note("PASS: %zu records tested", ctr); ret = 1; err: ossl_tls_record_method.free(rrl); ossl_tls_record_method.free(wrl); OPENSSL_free(rec.data); OPENSSL_free(key); return ret; } int setup_tests(void) { ADD_TEST(test_tls13_encryption); return 1; }
14,376
34.498765
79
c
openssl
openssl-master/test/tls13secretstest.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 <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; }
12,451
29.004819
81
c
openssl
openssl-master/test/trace_api_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 <openssl/trace.h> #include "testutil.h" static int test_trace_categories(void) { int cat_num; for (cat_num = -1; cat_num <= OSSL_TRACE_CATEGORY_NUM + 1; ++cat_num) { const char *cat_name = OSSL_trace_get_category_name(cat_num); int is_cat_name_eq = 0; int ret_cat_num; int expected_ret; switch (cat_num) { #define CASE(name) \ case OSSL_TRACE_CATEGORY_##name: \ is_cat_name_eq = TEST_str_eq(cat_name, #name); \ break CASE(ALL); CASE(TRACE); CASE(INIT); CASE(TLS); CASE(TLS_CIPHER); CASE(CONF); CASE(ENGINE_TABLE); CASE(ENGINE_REF_COUNT); CASE(PKCS5V2); CASE(PKCS12_KEYGEN); CASE(PKCS12_DECRYPT); CASE(X509V3_POLICY); CASE(BN_CTX); CASE(CMP); CASE(STORE); CASE(DECODER); CASE(ENCODER); CASE(REF_COUNT); CASE(HTTP); #undef CASE default: is_cat_name_eq = TEST_ptr_null(cat_name); break; } if (!TEST_true(is_cat_name_eq)) return 0; ret_cat_num = OSSL_trace_get_category_num(cat_name); expected_ret = cat_name != NULL ? cat_num : -1; if (!TEST_int_eq(expected_ret, ret_cat_num)) return 0; } return 1; } #ifndef OPENSSL_NO_TRACE # define OSSL_START "xyz-" # define OSSL_HELLO "Hello World\n" /* OSSL_STR80 must have length OSSL_TRACE_STRING_MAX */ # define OSSL_STR80 "1234567890123456789012345678901234567890123456789012345678901234567890123456789\n" # define OSSL_STR81 (OSSL_STR80"x") # define OSSL_CTRL "A\xfe\nB" # define OSSL_MASKED "A \nB" # define OSSL_BYE "Good Bye Universe\n" # define OSSL_END "-abc" # define trace_string(text, full, str) \ OSSL_trace_string(trc_out, text, full, (unsigned char *)(str), strlen(str)) static int put_trace_output(void) { int res = 1; OSSL_TRACE_BEGIN(HTTP) { res = TEST_int_eq(BIO_printf(trc_out, OSSL_HELLO), strlen(OSSL_HELLO)) + TEST_int_eq(trace_string(0, 0, OSSL_STR80), strlen(OSSL_STR80)) + TEST_int_eq(trace_string(0, 0, OSSL_STR81), strlen(OSSL_STR80)) + TEST_int_eq(trace_string(1, 1, OSSL_CTRL), strlen(OSSL_CTRL)) + TEST_int_eq(trace_string(0, 1, OSSL_MASKED), strlen(OSSL_MASKED) + 1) /* newline added */ + TEST_int_eq(BIO_printf(trc_out, OSSL_BYE), strlen(OSSL_BYE)) == 6; /* not using '&&' but '+' to catch potentially multiple test failures */ } OSSL_TRACE_END(HTTP); return res; } static int test_trace_channel(void) { static const char expected[] = OSSL_START"\n" OSSL_HELLO OSSL_STR80 "[len 81 limited to 80]: "OSSL_STR80 OSSL_CTRL OSSL_MASKED"\n" OSSL_BYE OSSL_END"\n"; static const size_t expected_len = sizeof(expected) - 1; BIO *bio = NULL; char *p_buf = NULL; long len = 0; int ret = 0; bio = BIO_new(BIO_s_mem()); if (!TEST_ptr(bio)) goto end; if (!TEST_int_eq(OSSL_trace_set_channel(OSSL_TRACE_CATEGORY_HTTP, bio), 1)) { BIO_free(bio); goto end; } if (!TEST_true(OSSL_trace_enabled(OSSL_TRACE_CATEGORY_HTTP))) goto end; if (!TEST_int_eq(OSSL_trace_set_prefix(OSSL_TRACE_CATEGORY_HTTP, OSSL_START), 1)) goto end; if (!TEST_int_eq(OSSL_trace_set_suffix(OSSL_TRACE_CATEGORY_HTTP, OSSL_END), 1)) goto end; ret = put_trace_output(); len = BIO_get_mem_data(bio, &p_buf); if (!TEST_strn2_eq(p_buf, len, expected, expected_len)) ret = 0; ret = TEST_int_eq(OSSL_trace_set_channel(OSSL_TRACE_CATEGORY_HTTP, NULL), 1) && ret; end: return ret; } static int trace_cb_failure; static int trace_cb_called; static size_t trace_cb(const char *buffer, size_t count, int category, int cmd, void *data) { trace_cb_called = 1; if (!TEST_true(category == OSSL_TRACE_CATEGORY_TRACE)) trace_cb_failure = 1; return count; } static int test_trace_callback(void) { int ret = 0; if (!TEST_true(OSSL_trace_set_callback(OSSL_TRACE_CATEGORY_TRACE, trace_cb, NULL))) goto end; put_trace_output(); if (!TEST_false(trace_cb_failure) || !TEST_true(trace_cb_called)) goto end; ret = 1; end: return ret; } #endif OPT_TEST_DECLARE_USAGE("\n") int setup_tests(void) { if (!test_skip_common_options()) { TEST_error("Error parsing test options\n"); return 0; } ADD_TEST(test_trace_categories); #ifndef OPENSSL_NO_TRACE ADD_TEST(test_trace_channel); ADD_TEST(test_trace_callback); #endif return 1; } void cleanup_tests(void) { }
5,218
26.041451
103
c
openssl
openssl-master/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; }
2,259
22.789474
80
c
openssl
openssl-master/test/upcallstest.c
/* * Copyright 2021-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/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; }
5,604
32.562874
89
c
openssl
openssl-master/test/user_property_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 <openssl/core.h> #include <openssl/core_dispatch.h> #include <openssl/core_names.h> #include <openssl/provider.h> #include <openssl/crypto.h> #include <openssl/evp.h> #include "testutil.h" #define MYPROPERTIES "foo.bar=yes" static OSSL_FUNC_provider_query_operation_fn testprov_query; static OSSL_FUNC_digest_get_params_fn tmpmd_get_params; static OSSL_FUNC_digest_digest_fn tmpmd_digest; static int tmpmd_get_params(OSSL_PARAM params[]) { OSSL_PARAM *p = NULL; p = OSSL_PARAM_locate(params, OSSL_DIGEST_PARAM_BLOCK_SIZE); if (p != NULL && !OSSL_PARAM_set_size_t(p, 1)) return 0; p = OSSL_PARAM_locate(params, OSSL_DIGEST_PARAM_SIZE); if (p != NULL && !OSSL_PARAM_set_size_t(p, 1)) return 0; return 1; } static int tmpmd_digest(void *provctx, const unsigned char *in, size_t inl, unsigned char *out, size_t *outl, size_t outsz) { return 0; } static const OSSL_DISPATCH testprovmd_functions[] = { { OSSL_FUNC_DIGEST_GET_PARAMS, (void (*)(void))tmpmd_get_params }, { OSSL_FUNC_DIGEST_DIGEST, (void (*)(void))tmpmd_digest }, OSSL_DISPATCH_END }; static const OSSL_ALGORITHM testprov_digests[] = { { "testprovmd", MYPROPERTIES, testprovmd_functions }, { NULL, NULL, NULL } }; static const OSSL_ALGORITHM *testprov_query(void *provctx, int operation_id, int *no_cache) { *no_cache = 0; return operation_id == OSSL_OP_DIGEST ? testprov_digests : NULL; } static const OSSL_DISPATCH testprov_dispatch_table[] = { { OSSL_FUNC_PROVIDER_QUERY_OPERATION, (void (*)(void))testprov_query }, OSSL_DISPATCH_END }; static int testprov_provider_init(const OSSL_CORE_HANDLE *handle, const OSSL_DISPATCH *in, const OSSL_DISPATCH **out, void **provctx) { *provctx = (void *)handle; *out = testprov_dispatch_table; return 1; } enum { DEFAULT_PROPS_FIRST = 0, DEFAULT_PROPS_AFTER_LOAD, DEFAULT_PROPS_AFTER_FETCH, DEFAULT_PROPS_FINAL }; static int test_default_props_and_providers(int propsorder) { OSSL_LIB_CTX *libctx; OSSL_PROVIDER *testprov = NULL; EVP_MD *testprovmd = NULL; int res = 0; if (!TEST_ptr(libctx = OSSL_LIB_CTX_new()) || !TEST_true(OSSL_PROVIDER_add_builtin(libctx, "testprov", testprov_provider_init))) goto err; if (propsorder == DEFAULT_PROPS_FIRST && !TEST_true(EVP_set_default_properties(libctx, MYPROPERTIES))) goto err; if (!TEST_ptr(testprov = OSSL_PROVIDER_load(libctx, "testprov"))) goto err; if (propsorder == DEFAULT_PROPS_AFTER_LOAD && !TEST_true(EVP_set_default_properties(libctx, MYPROPERTIES))) goto err; if (!TEST_ptr(testprovmd = EVP_MD_fetch(libctx, "testprovmd", NULL))) goto err; if (propsorder == DEFAULT_PROPS_AFTER_FETCH) { if (!TEST_true(EVP_set_default_properties(libctx, MYPROPERTIES))) goto err; EVP_MD_free(testprovmd); if (!TEST_ptr(testprovmd = EVP_MD_fetch(libctx, "testprovmd", NULL))) goto err; } res = 1; err: EVP_MD_free(testprovmd); OSSL_PROVIDER_unload(testprov); OSSL_LIB_CTX_free(libctx); return res; } int setup_tests(void) { ADD_ALL_TESTS(test_default_props_and_providers, DEFAULT_PROPS_FINAL); return 1; }
3,866
28.075188
77
c
openssl
openssl-master/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; }
16,191
32.803758
95
c
openssl
openssl-master/test/v3nametest.c
/* * Copyright 2012-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 <openssl/e_os2.h> #include <openssl/x509.h> #include <openssl/x509v3.h> #include "internal/nelem.h" #include "testutil.h" static const char *const names[] = { "a", "b", ".", "*", "@", ".a", "a.", ".b", "b.", ".*", "*.", "*@", "@*", "a@", "@a", "b@", "..", "-example.com", "example-.com", "@@", "**", "*.com", "*com", "*.*.com", "*com", "com*", "*example.com", "*@example.com", "test@*.example.com", "example.com", "www.example.com", "test.www.example.com", "*.example.com", "*.www.example.com", "test.*.example.com", "www.*.com", ".www.example.com", "*www.example.com", "example.net", "xn--rger-koa.example.com", "*.xn--rger-koa.example.com", "www.xn--rger-koa.example.com", "*.good--example.com", "www.good--example.com", "*.xn--bar.com", "xn--foo.xn--bar.com", "a.example.com", "b.example.com", "[email protected]", "[email protected]", "[email protected]", NULL }; static const char *const exceptions[] = { "set CN: host: [*.example.com] matches [a.example.com]", "set CN: host: [*.example.com] matches [b.example.com]", "set CN: host: [*.example.com] matches [www.example.com]", "set CN: host: [*.example.com] matches [xn--rger-koa.example.com]", "set CN: host: [*.www.example.com] matches [test.www.example.com]", "set CN: host: [*.www.example.com] matches [.www.example.com]", "set CN: host: [*www.example.com] matches [www.example.com]", "set CN: host: [test.www.example.com] matches [.www.example.com]", "set CN: host: [*.xn--rger-koa.example.com] matches [www.xn--rger-koa.example.com]", "set CN: host: [*.xn--bar.com] matches [xn--foo.xn--bar.com]", "set CN: host: [*.good--example.com] matches [www.good--example.com]", "set CN: host-no-wildcards: [*.www.example.com] matches [.www.example.com]", "set CN: host-no-wildcards: [test.www.example.com] matches [.www.example.com]", "set emailAddress: email: [[email protected]] does not match [[email protected]]", "set emailAddress: email: [[email protected]] does not match [[email protected]]", "set emailAddress: email: [[email protected]] does not match [[email protected]]", "set emailAddress: email: [[email protected]] does not match [[email protected]]", "set dnsName: host: [*.example.com] matches [www.example.com]", "set dnsName: host: [*.example.com] matches [a.example.com]", "set dnsName: host: [*.example.com] matches [b.example.com]", "set dnsName: host: [*.example.com] matches [xn--rger-koa.example.com]", "set dnsName: host: [*.www.example.com] matches [test.www.example.com]", "set dnsName: host-no-wildcards: [*.www.example.com] matches [.www.example.com]", "set dnsName: host-no-wildcards: [test.www.example.com] matches [.www.example.com]", "set dnsName: host: [*.www.example.com] matches [.www.example.com]", "set dnsName: host: [*www.example.com] matches [www.example.com]", "set dnsName: host: [test.www.example.com] matches [.www.example.com]", "set dnsName: host: [*.xn--rger-koa.example.com] matches [www.xn--rger-koa.example.com]", "set dnsName: host: [*.xn--bar.com] matches [xn--foo.xn--bar.com]", "set dnsName: host: [*.good--example.com] matches [www.good--example.com]", "set rfc822Name: email: [[email protected]] does not match [[email protected]]", "set rfc822Name: email: [[email protected]] does not match [[email protected]]", "set rfc822Name: email: [[email protected]] does not match [[email protected]]", "set rfc822Name: email: [[email protected]] does not match [[email protected]]", NULL }; static int is_exception(const char *msg) { const char *const *p; for (p = exceptions; *p; ++p) if (strcmp(msg, *p) == 0) return 1; return 0; } static int set_cn(X509 *crt, ...) { int ret = 0; X509_NAME *n = NULL; va_list ap; va_start(ap, crt); n = X509_NAME_new(); if (n == NULL) goto out; while (1) { int nid; const char *name; nid = va_arg(ap, int); if (nid == 0) break; name = va_arg(ap, const char *); if (!X509_NAME_add_entry_by_NID(n, nid, MBSTRING_ASC, (unsigned char *)name, -1, -1, 1)) goto out; } if (!X509_set_subject_name(crt, n)) goto out; ret = 1; out: X509_NAME_free(n); va_end(ap); return ret; } /*- int X509_add_ext(X509 *x, X509_EXTENSION *ex, int loc); X509_EXTENSION *X509_EXTENSION_create_by_NID(X509_EXTENSION **ex, int nid, int crit, ASN1_OCTET_STRING *data); int X509_add_ext(X509 *x, X509_EXTENSION *ex, int loc); */ static int set_altname(X509 *crt, ...) { int ret = 0; GENERAL_NAMES *gens = NULL; GENERAL_NAME *gen = NULL; ASN1_IA5STRING *ia5 = NULL; va_list ap; va_start(ap, crt); gens = sk_GENERAL_NAME_new_null(); if (gens == NULL) goto out; while (1) { int type; const char *name; type = va_arg(ap, int); if (type == 0) break; name = va_arg(ap, const char *); gen = GENERAL_NAME_new(); if (gen == NULL) goto out; ia5 = ASN1_IA5STRING_new(); if (ia5 == NULL) goto out; if (!ASN1_STRING_set(ia5, name, -1)) goto out; switch (type) { case GEN_EMAIL: case GEN_DNS: GENERAL_NAME_set0_value(gen, type, ia5); ia5 = NULL; break; default: abort(); } sk_GENERAL_NAME_push(gens, gen); gen = NULL; } if (!X509_add1_ext_i2d(crt, NID_subject_alt_name, gens, 0, 0)) goto out; ret = 1; out: ASN1_IA5STRING_free(ia5); GENERAL_NAME_free(gen); GENERAL_NAMES_free(gens); va_end(ap); return ret; } static int set_cn1(X509 *crt, const char *name) { return set_cn(crt, NID_commonName, name, 0); } static int set_cn_and_email(X509 *crt, const char *name) { return set_cn(crt, NID_commonName, name, NID_pkcs9_emailAddress, "[email protected]", 0); } static int set_cn2(X509 *crt, const char *name) { return set_cn(crt, NID_commonName, "dummy value", NID_commonName, name, 0); } static int set_cn3(X509 *crt, const char *name) { return set_cn(crt, NID_commonName, name, NID_commonName, "dummy value", 0); } static int set_email1(X509 *crt, const char *name) { return set_cn(crt, NID_pkcs9_emailAddress, name, 0); } static int set_email2(X509 *crt, const char *name) { return set_cn(crt, NID_pkcs9_emailAddress, "[email protected]", NID_pkcs9_emailAddress, name, 0); } static int set_email3(X509 *crt, const char *name) { return set_cn(crt, NID_pkcs9_emailAddress, name, NID_pkcs9_emailAddress, "[email protected]", 0); } static int set_email_and_cn(X509 *crt, const char *name) { return set_cn(crt, NID_pkcs9_emailAddress, name, NID_commonName, "www.example.org", 0); } static int set_altname_dns(X509 *crt, const char *name) { return set_altname(crt, GEN_DNS, name, 0); } static int set_altname_email(X509 *crt, const char *name) { return set_altname(crt, GEN_EMAIL, name, 0); } struct set_name_fn { int (*fn) (X509 *, const char *); const char *name; int host; int email; }; static const struct set_name_fn name_fns[] = { {set_cn1, "set CN", 1, 0}, {set_cn2, "set CN", 1, 0}, {set_cn3, "set CN", 1, 0}, {set_cn_and_email, "set CN", 1, 0}, {set_email1, "set emailAddress", 0, 1}, {set_email2, "set emailAddress", 0, 1}, {set_email3, "set emailAddress", 0, 1}, {set_email_and_cn, "set emailAddress", 0, 1}, {set_altname_dns, "set dnsName", 1, 0}, {set_altname_email, "set rfc822Name", 0, 1}, }; static X509 *make_cert(void) { X509 *crt = NULL; if (!TEST_ptr(crt = X509_new())) return NULL; if (!TEST_true(X509_set_version(crt, X509_VERSION_3))) { X509_free(crt); return NULL; } return crt; } static int check_message(const struct set_name_fn *fn, const char *op, const char *nameincert, int match, const char *name) { char msg[1024]; if (match < 0) return 1; BIO_snprintf(msg, sizeof(msg), "%s: %s: [%s] %s [%s]", fn->name, op, nameincert, match ? "matches" : "does not match", name); if (is_exception(msg)) return 1; TEST_error("%s", msg); return 0; } static int run_cert(X509 *crt, const char *nameincert, const struct set_name_fn *fn) { const char *const *pname = names; int failed = 0; for (; *pname != NULL; ++pname) { int samename = OPENSSL_strcasecmp(nameincert, *pname) == 0; size_t namelen = strlen(*pname); char *name = OPENSSL_malloc(namelen + 1); int match, ret; if (!TEST_ptr(name)) return 0; memcpy(name, *pname, namelen + 1); match = -1; if (!TEST_int_ge(ret = X509_check_host(crt, name, namelen, 0, NULL), 0)) { failed = 1; } else if (fn->host) { if (ret == 1 && !samename) match = 1; if (ret == 0 && samename) match = 0; } else if (ret == 1) match = 1; if (!TEST_true(check_message(fn, "host", nameincert, match, *pname))) failed = 1; match = -1; if (!TEST_int_ge(ret = X509_check_host(crt, name, namelen, X509_CHECK_FLAG_NO_WILDCARDS, NULL), 0)) { failed = 1; } else if (fn->host) { if (ret == 1 && !samename) match = 1; if (ret == 0 && samename) match = 0; } else if (ret == 1) match = 1; if (!TEST_true(check_message(fn, "host-no-wildcards", nameincert, match, *pname))) failed = 1; match = -1; ret = X509_check_email(crt, name, namelen, 0); if (fn->email) { if (ret && !samename) match = 1; if (!ret && samename && strchr(nameincert, '@') != NULL) match = 0; } else if (ret) match = 1; if (!TEST_true(check_message(fn, "email", nameincert, match, *pname))) failed = 1; OPENSSL_free(name); } return failed == 0; } static int call_run_cert(int i) { int failed = 0; const struct set_name_fn *pfn = &name_fns[i]; X509 *crt; const char *const *pname; TEST_info("%s", pfn->name); for (pname = names; *pname != NULL; pname++) { if (!TEST_ptr(crt = make_cert()) || !TEST_true(pfn->fn(crt, *pname)) || !run_cert(crt, *pname, pfn)) failed = 1; X509_free(crt); } return failed == 0; } static struct gennamedata { const unsigned char der[22]; size_t derlen; } gennames[] = { { /* * [0] { * OBJECT_IDENTIFIER { 1.2.840.113554.4.1.72585.2.1 } * [0] { * SEQUENCE {} * } * } */ { 0xa0, 0x13, 0x06, 0x0d, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x12, 0x04, 0x01, 0x84, 0xb7, 0x09, 0x02, 0x01, 0xa0, 0x02, 0x30, 0x00 }, 21 }, { /* * [0] { * OBJECT_IDENTIFIER { 1.2.840.113554.4.1.72585.2.1 } * [0] { * [APPLICATION 0] {} * } * } */ { 0xa0, 0x13, 0x06, 0x0d, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x12, 0x04, 0x01, 0x84, 0xb7, 0x09, 0x02, 0x01, 0xa0, 0x02, 0x60, 0x00 }, 21 }, { /* * [0] { * OBJECT_IDENTIFIER { 1.2.840.113554.4.1.72585.2.1 } * [0] { * UTF8String { "a" } * } * } */ { 0xa0, 0x14, 0x06, 0x0d, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x12, 0x04, 0x01, 0x84, 0xb7, 0x09, 0x02, 0x01, 0xa0, 0x03, 0x0c, 0x01, 0x61 }, 22 }, { /* * [0] { * OBJECT_IDENTIFIER { 1.2.840.113554.4.1.72585.2.2 } * [0] { * UTF8String { "a" } * } * } */ { 0xa0, 0x14, 0x06, 0x0d, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x12, 0x04, 0x01, 0x84, 0xb7, 0x09, 0x02, 0x02, 0xa0, 0x03, 0x0c, 0x01, 0x61 }, 22 }, { /* * [0] { * OBJECT_IDENTIFIER { 1.2.840.113554.4.1.72585.2.1 } * [0] { * UTF8String { "b" } * } * } */ { 0xa0, 0x14, 0x06, 0x0d, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x12, 0x04, 0x01, 0x84, 0xb7, 0x09, 0x02, 0x01, 0xa0, 0x03, 0x0c, 0x01, 0x62 }, 22 }, { /* * [0] { * OBJECT_IDENTIFIER { 1.2.840.113554.4.1.72585.2.1 } * [0] { * BOOLEAN { TRUE } * } * } */ { 0xa0, 0x14, 0x06, 0x0d, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x12, 0x04, 0x01, 0x84, 0xb7, 0x09, 0x02, 0x01, 0xa0, 0x03, 0x01, 0x01, 0xff }, 22 }, { /* * [0] { * OBJECT_IDENTIFIER { 1.2.840.113554.4.1.72585.2.1 } * [0] { * BOOLEAN { FALSE } * } * } */ { 0xa0, 0x14, 0x06, 0x0d, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x12, 0x04, 0x01, 0x84, 0xb7, 0x09, 0x02, 0x01, 0xa0, 0x03, 0x01, 0x01, 0x00 }, 22 }, { /* [1 PRIMITIVE] { "a" } */ { 0x81, 0x01, 0x61 }, 3 }, { /* [1 PRIMITIVE] { "b" } */ { 0x81, 0x01, 0x62 }, 3 }, { /* [2 PRIMITIVE] { "a" } */ { 0x82, 0x01, 0x61 }, 3 }, { /* [2 PRIMITIVE] { "b" } */ { 0x82, 0x01, 0x62 }, 3 }, { /* * [4] { * SEQUENCE { * SET { * SEQUENCE { * # commonName * OBJECT_IDENTIFIER { 2.5.4.3 } * UTF8String { "a" } * } * } * } * } */ { 0xa4, 0x0e, 0x30, 0x0c, 0x31, 0x0a, 0x30, 0x08, 0x06, 0x03, 0x55, 0x04, 0x03, 0x0c, 0x01, 0x61 }, 16 }, { /* * [4] { * SEQUENCE { * SET { * SEQUENCE { * # commonName * OBJECT_IDENTIFIER { 2.5.4.3 } * UTF8String { "b" } * } * } * } * } */ { 0xa4, 0x0e, 0x30, 0x0c, 0x31, 0x0a, 0x30, 0x08, 0x06, 0x03, 0x55, 0x04, 0x03, 0x0c, 0x01, 0x62 }, 16 }, { /* * [5] { * [1] { * UTF8String { "a" } * } * } */ { 0xa5, 0x05, 0xa1, 0x03, 0x0c, 0x01, 0x61 }, 7 }, { /* * [5] { * [1] { * UTF8String { "b" } * } * } */ { 0xa5, 0x05, 0xa1, 0x03, 0x0c, 0x01, 0x62 }, 7 }, { /* * [5] { * [0] { * UTF8String {} * } * [1] { * UTF8String { "a" } * } * } */ { 0xa5, 0x09, 0xa0, 0x02, 0x0c, 0x00, 0xa1, 0x03, 0x0c, 0x01, 0x61 }, 11 }, { /* * [5] { * [0] { * UTF8String { "a" } * } * [1] { * UTF8String { "a" } * } * } */ { 0xa5, 0x0a, 0xa0, 0x03, 0x0c, 0x01, 0x61, 0xa1, 0x03, 0x0c, 0x01, 0x61 }, 12 }, { /* * [5] { * [0] { * UTF8String { "b" } * } * [1] { * UTF8String { "a" } * } * } */ { 0xa5, 0x0a, 0xa0, 0x03, 0x0c, 0x01, 0x62, 0xa1, 0x03, 0x0c, 0x01, 0x61 }, 12 }, { /* [6 PRIMITIVE] { "a" } */ { 0x86, 0x01, 0x61 }, 3 }, { /* [6 PRIMITIVE] { "b" } */ { 0x86, 0x01, 0x62 }, 3 }, { /* [7 PRIMITIVE] { `11111111` } */ { 0x87, 0x04, 0x11, 0x11, 0x11, 0x11 }, 6 }, { /* [7 PRIMITIVE] { `22222222`} */ { 0x87, 0x04, 0x22, 0x22, 0x22, 0x22 }, 6 }, { /* [7 PRIMITIVE] { `11111111111111111111111111111111` } */ { 0x87, 0x10, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11 }, 18 }, { /* [7 PRIMITIVE] { `22222222222222222222222222222222` } */ { 0x87, 0x10, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22 }, 18 }, { /* [8 PRIMITIVE] { 1.2.840.113554.4.1.72585.2.1 } */ { 0x88, 0x0d, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x12, 0x04, 0x01, 0x84, 0xb7, 0x09, 0x02, 0x01 }, 15 }, { /* [8 PRIMITIVE] { 1.2.840.113554.4.1.72585.2.2 } */ { 0x88, 0x0d, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x12, 0x04, 0x01, 0x84, 0xb7, 0x09, 0x02, 0x02 }, 15 }, { /* * Regression test for CVE-2023-0286. */ { 0xa3, 0x00 }, 2 } }; static int test_GENERAL_NAME_cmp(void) { size_t i, j; GENERAL_NAME **namesa = OPENSSL_malloc(sizeof(*namesa) * OSSL_NELEM(gennames)); GENERAL_NAME **namesb = OPENSSL_malloc(sizeof(*namesb) * OSSL_NELEM(gennames)); int testresult = 0; if (!TEST_ptr(namesa) || !TEST_ptr(namesb)) goto end; for (i = 0; i < OSSL_NELEM(gennames); i++) { const unsigned char *derp = gennames[i].der; /* * We create two versions of each GENERAL_NAME so that we ensure when * we compare them they are always different pointers. */ namesa[i] = d2i_GENERAL_NAME(NULL, &derp, gennames[i].derlen); derp = gennames[i].der; namesb[i] = d2i_GENERAL_NAME(NULL, &derp, gennames[i].derlen); if (!TEST_ptr(namesa[i]) || !TEST_ptr(namesb[i])) goto end; } /* Every name should be equal to itself and not equal to any others. */ for (i = 0; i < OSSL_NELEM(gennames); i++) { for (j = 0; j < OSSL_NELEM(gennames); j++) { if (i == j) { if (!TEST_int_eq(GENERAL_NAME_cmp(namesa[i], namesb[j]), 0)) goto end; } else { if (!TEST_int_ne(GENERAL_NAME_cmp(namesa[i], namesb[j]), 0)) goto end; } } } testresult = 1; end: for (i = 0; i < OSSL_NELEM(gennames); i++) { if (namesa != NULL) GENERAL_NAME_free(namesa[i]); if (namesb != NULL) GENERAL_NAME_free(namesb[i]); } OPENSSL_free(namesa); OPENSSL_free(namesb); return testresult; } int setup_tests(void) { ADD_ALL_TESTS(call_run_cert, OSSL_NELEM(name_fns)); ADD_TEST(test_GENERAL_NAME_cmp); return 1; }
20,251
27.245467
96
c
openssl
openssl-master/test/verify_extra_test.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 <stdio.h> #include <string.h> #include <openssl/crypto.h> #include <openssl/bio.h> #include <openssl/x509.h> #include <openssl/x509v3.h> #include <openssl/pem.h> #include <openssl/err.h> #include "testutil.h" static const char *certs_dir; static char *root_f = NULL; static char *roots_f = NULL; static char *untrusted_f = NULL; static char *bad_f = NULL; static char *req_f = NULL; static char *sroot_cert = NULL; static char *ca_cert = NULL; static char *ee_cert = NULL; #define load_cert_from_file(file) load_cert_pem(file, NULL) /*- * Test for CVE-2015-1793 (Alternate Chains Certificate Forgery) * * Chain is as follows: * * rootCA (self-signed) * | * interCA * | * subinterCA subinterCA (self-signed) * | | * leaf ------------------ * | * bad * * rootCA, interCA, subinterCA, subinterCA (ss) all have CA=TRUE * leaf and bad have CA=FALSE * * subinterCA and subinterCA (ss) have the same subject name and keys * * interCA (but not rootCA) and subinterCA (ss) are in the trusted store * (roots.pem) * leaf and subinterCA are in the untrusted list (untrusted.pem) * bad is the certificate being verified (bad.pem) * * Versions vulnerable to CVE-2015-1793 will fail to detect that leaf has * CA=FALSE, and will therefore incorrectly verify bad * */ static int test_alt_chains_cert_forgery(void) { int ret = 0; int i; X509 *x = NULL; STACK_OF(X509) *untrusted = NULL; X509_STORE_CTX *sctx = NULL; X509_STORE *store = NULL; X509_LOOKUP *lookup = NULL; store = X509_STORE_new(); if (store == NULL) goto err; lookup = X509_STORE_add_lookup(store, X509_LOOKUP_file()); if (lookup == NULL) goto err; if (!X509_LOOKUP_load_file(lookup, roots_f, X509_FILETYPE_PEM)) goto err; untrusted = load_certs_pem(untrusted_f); if ((x = load_cert_from_file(bad_f)) == NULL) goto err; sctx = X509_STORE_CTX_new(); if (sctx == NULL) goto err; if (!X509_STORE_CTX_init(sctx, store, x, untrusted)) goto err; i = X509_verify_cert(sctx); if (i == 0 && X509_STORE_CTX_get_error(sctx) == X509_V_ERR_INVALID_CA) { /* This is the result we were expecting: Test passed */ ret = 1; } err: X509_STORE_CTX_free(sctx); X509_free(x); OSSL_STACK_OF_X509_free(untrusted); X509_STORE_free(store); return ret; } static int test_distinguishing_id(void) { X509 *x = NULL; int ret = 0; ASN1_OCTET_STRING *v = NULL, *v2 = NULL; char *distid = "this is an ID"; x = load_cert_from_file(bad_f); if (x == NULL) goto err; v = ASN1_OCTET_STRING_new(); if (v == NULL) goto err; if (!ASN1_OCTET_STRING_set(v, (unsigned char *)distid, (int)strlen(distid))) { ASN1_OCTET_STRING_free(v); goto err; } X509_set0_distinguishing_id(x, v); v2 = X509_get0_distinguishing_id(x); if (!TEST_ptr(v2) || !TEST_int_eq(ASN1_OCTET_STRING_cmp(v, v2), 0)) goto err; ret = 1; err: X509_free(x); return ret; } static int test_req_distinguishing_id(void) { X509_REQ *x = NULL; BIO *bio = NULL; int ret = 0; ASN1_OCTET_STRING *v = NULL, *v2 = NULL; char *distid = "this is an ID"; bio = BIO_new_file(req_f, "r"); if (bio == NULL) goto err; x = PEM_read_bio_X509_REQ(bio, NULL, 0, NULL); if (x == NULL) goto err; v = ASN1_OCTET_STRING_new(); if (v == NULL) goto err; if (!ASN1_OCTET_STRING_set(v, (unsigned char *)distid, (int)strlen(distid))) { ASN1_OCTET_STRING_free(v); goto err; } X509_REQ_set0_distinguishing_id(x, v); v2 = X509_REQ_get0_distinguishing_id(x); if (!TEST_ptr(v2) || !TEST_int_eq(ASN1_OCTET_STRING_cmp(v, v2), 0)) goto err; ret = 1; err: X509_REQ_free(x); BIO_free(bio); return ret; } static int test_self_signed(const char *filename, int use_trusted, int expected) { X509 *cert = load_cert_from_file(filename); /* may result in NULL */ STACK_OF(X509) *trusted = sk_X509_new_null(); X509_STORE_CTX *ctx = X509_STORE_CTX_new(); int ret; ret = TEST_int_eq(X509_self_signed(cert, 1), expected); if (cert != NULL) { if (use_trusted) ret = ret && TEST_true(sk_X509_push(trusted, cert)); ret = ret && TEST_true(X509_STORE_CTX_init(ctx, NULL, cert, NULL)); X509_STORE_CTX_set0_trusted_stack(ctx, trusted); ret = ret && TEST_int_eq(X509_verify_cert(ctx), expected); } X509_STORE_CTX_free(ctx); sk_X509_free(trusted); X509_free(cert); return ret; } static int test_self_signed_good(void) { return test_self_signed(root_f, 1, 1); } static int test_self_signed_bad(void) { return test_self_signed(bad_f, 1, 0); } static int test_self_signed_error(void) { return test_self_signed("nonexistent file name", 1, -1); } static int test_store_ctx(void) { /* Verifying a cert where we have no trusted certs should fail */ return test_self_signed(bad_f, 0, 0); } static int do_test_purpose(int purpose, int expected) { X509 *eecert = load_cert_from_file(ee_cert); /* may result in NULL */ X509 *untrcert = load_cert_from_file(ca_cert); X509 *trcert = load_cert_from_file(sroot_cert); STACK_OF(X509) *trusted = sk_X509_new_null(); STACK_OF(X509) *untrusted = sk_X509_new_null(); X509_STORE_CTX *ctx = X509_STORE_CTX_new(); int testresult = 0; if (!TEST_ptr(eecert) || !TEST_ptr(untrcert) || !TEST_ptr(trcert) || !TEST_ptr(trusted) || !TEST_ptr(untrusted) || !TEST_ptr(ctx)) goto err; if (!TEST_true(sk_X509_push(trusted, trcert))) goto err; trcert = NULL; if (!TEST_true(sk_X509_push(untrusted, untrcert))) goto err; untrcert = NULL; if (!TEST_true(X509_STORE_CTX_init(ctx, NULL, eecert, untrusted))) goto err; if (!TEST_true(X509_STORE_CTX_set_purpose(ctx, purpose))) goto err; /* * X509_STORE_CTX_set0_trusted_stack() is bady named. Despite the set0 name * we are still responsible for freeing trusted after we have finished with * it. */ X509_STORE_CTX_set0_trusted_stack(ctx, trusted); if (!TEST_int_eq(X509_verify_cert(ctx), expected)) goto err; testresult = 1; err: OSSL_STACK_OF_X509_free(trusted); OSSL_STACK_OF_X509_free(untrusted); X509_STORE_CTX_free(ctx); X509_free(eecert); X509_free(untrcert); X509_free(trcert); return testresult; } static int test_purpose_ssl_client(void) { return do_test_purpose(X509_PURPOSE_SSL_CLIENT, 0); } static int test_purpose_ssl_server(void) { return do_test_purpose(X509_PURPOSE_SSL_SERVER, 1); } static int test_purpose_any(void) { return do_test_purpose(X509_PURPOSE_ANY, 1); } OPT_TEST_DECLARE_USAGE("certs-dir\n") int setup_tests(void) { if (!test_skip_common_options()) { TEST_error("Error parsing test options\n"); return 0; } if (!TEST_ptr(certs_dir = test_get_argument(0))) return 0; if (!TEST_ptr(root_f = test_mk_file_path(certs_dir, "rootCA.pem")) || !TEST_ptr(roots_f = test_mk_file_path(certs_dir, "roots.pem")) || !TEST_ptr(untrusted_f = test_mk_file_path(certs_dir, "untrusted.pem")) || !TEST_ptr(bad_f = test_mk_file_path(certs_dir, "bad.pem")) || !TEST_ptr(req_f = test_mk_file_path(certs_dir, "sm2-csr.pem")) || !TEST_ptr(sroot_cert = test_mk_file_path(certs_dir, "sroot-cert.pem")) || !TEST_ptr(ca_cert = test_mk_file_path(certs_dir, "ca-cert.pem")) || !TEST_ptr(ee_cert = test_mk_file_path(certs_dir, "ee-cert.pem"))) goto err; ADD_TEST(test_alt_chains_cert_forgery); ADD_TEST(test_store_ctx); ADD_TEST(test_distinguishing_id); ADD_TEST(test_req_distinguishing_id); ADD_TEST(test_self_signed_good); ADD_TEST(test_self_signed_bad); ADD_TEST(test_self_signed_error); ADD_TEST(test_purpose_ssl_client); ADD_TEST(test_purpose_ssl_server); ADD_TEST(test_purpose_any); return 1; err: cleanup_tests(); return 0; } void cleanup_tests(void) { OPENSSL_free(root_f); OPENSSL_free(roots_f); OPENSSL_free(untrusted_f); OPENSSL_free(bad_f); OPENSSL_free(req_f); OPENSSL_free(sroot_cert); OPENSSL_free(ca_cert); OPENSSL_free(ee_cert); }
8,921
25.087719
85
c
openssl
openssl-master/test/versions.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 */ #include <stdio.h> #include <openssl/opensslv.h> #include <openssl/crypto.h> /* A simple helper for the perl function OpenSSL::Test::openssl_versions */ int main(void) { printf("Build version: %s\n", OPENSSL_FULL_VERSION_STR); printf("Library version: %s\n", OpenSSL_version(OPENSSL_FULL_VERSION_STRING)); return 0; }
674
29.681818
75
c
openssl
openssl-master/test/x509_check_cert_pkey_test.c
/* * Copyright 2017-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 <openssl/pem.h> #include <openssl/x509.h> #include "testutil.h" /* * c: path of a cert in PEM format * k: path of a key in PEM format * t: API type, "cert" for X509_ and "req" for X509_REQ_ APIs. * e: expected, "ok" for success, "failed" for what should fail. */ static const char *c; static const char *k; static const char *t; static const char *e; static int test_x509_check_cert_pkey(void) { BIO *bio = NULL; X509 *x509 = NULL; X509_REQ *x509_req = NULL; EVP_PKEY *pkey = NULL; int ret = 0, type = 0, expected = 0, result = 0; /* * we check them first thus if fails we don't need to do * those PEM parsing operations. */ if (strcmp(t, "cert") == 0) { type = 1; } else if (strcmp(t, "req") == 0) { type = 2; } else { TEST_error("invalid 'type'"); goto failed; } if (strcmp(e, "ok") == 0) { expected = 1; } else if (strcmp(e, "failed") == 0) { expected = 0; } else { TEST_error("invalid 'expected'"); goto failed; } /* process private key */ if (!TEST_ptr(bio = BIO_new_file(k, "r"))) goto failed; if (!TEST_ptr(pkey = PEM_read_bio_PrivateKey(bio, NULL, NULL, NULL))) goto failed; BIO_free(bio); /* process cert or cert request, use the same local var */ if (!TEST_ptr(bio = BIO_new_file(c, "r"))) goto failed; switch (type) { case 1: x509 = PEM_read_bio_X509(bio, NULL, NULL, NULL); if (x509 == NULL) { TEST_error("read PEM x509 failed"); goto failed; } result = X509_check_private_key(x509, pkey); break; case 2: x509_req = PEM_read_bio_X509_REQ(bio, NULL, NULL, NULL); if (x509_req == NULL) { TEST_error("read PEM x509 req failed"); goto failed; } result = X509_REQ_check_private_key(x509_req, pkey); break; default: /* should never be here */ break; } if (!TEST_int_eq(result, expected)) { TEST_error("check private key: expected: %d, got: %d", expected, result); goto failed; } ret = 1; failed: BIO_free(bio); X509_free(x509); X509_REQ_free(x509_req); EVP_PKEY_free(pkey); return ret; } static const char *file; /* path of a cert/CRL/key file in PEM format */ static int expected; /* expected number of certs/CRLs/keys included */ static int test_PEM_X509_INFO_read_bio(void) { BIO *in; STACK_OF(X509_INFO) *sk; X509_INFO *it; int i, count = 0; if (!TEST_ptr((in = BIO_new_file(file, "r")))) return 0; sk = PEM_X509_INFO_read_bio(in, NULL, NULL, ""); BIO_free(in); for (i = 0; i < sk_X509_INFO_num(sk); i++) { it = sk_X509_INFO_value(sk, i); if (it->x509 != NULL) count++; if (it->crl != NULL) count++; if (it->x_pkey != NULL) count++; } sk_X509_INFO_pop_free(sk, X509_INFO_free); return TEST_int_eq(count, expected); } const OPTIONS *test_get_options(void) { enum { OPT_TEST_ENUM }; static const OPTIONS test_options[] = { OPT_TEST_OPTIONS_WITH_EXTRA_USAGE("cert key type expected\n" " or [options] file num\n"), { OPT_HELP_STR, 1, '-', "cert\tcertificate or CSR filename in PEM\n" }, { OPT_HELP_STR, 1, '-', "key\tprivate key filename in PEM\n" }, { OPT_HELP_STR, 1, '-', "type\t\tvalue must be 'cert' or 'req'\n" }, { OPT_HELP_STR, 1, '-', "expected\tthe expected return value, either 'ok' or 'failed'\n" }, { OPT_HELP_STR, 1, '-', "file\tPEM format file containing certs, keys, and/OR CRLs\n" }, { OPT_HELP_STR, 1, '-', "num\texpected number of credentials to be loaded from file\n" }, { NULL } }; return test_options; } int setup_tests(void) { if (!test_skip_common_options()) { TEST_error("Error parsing test options\n"); return 0; } if (test_get_argument_count() == 2) { const char *num; /* expected number of certs/CRLs/keys included */ if (!TEST_ptr(file = test_get_argument(0)) || !TEST_ptr(num = test_get_argument(1))) return 0; if (!TEST_int_eq(sscanf(num, "%d", &expected), 1)) return 0; ADD_TEST(test_PEM_X509_INFO_read_bio); return 1; } if (!TEST_ptr(c = test_get_argument(0)) || !TEST_ptr(k = test_get_argument(1)) || !TEST_ptr(t = test_get_argument(2)) || !TEST_ptr(e = test_get_argument(3))) { return 0; } ADD_TEST(test_x509_check_cert_pkey); return 1; }
5,111
27.087912
99
c
openssl
openssl-master/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; }
1,352
25.019231
78
c
openssl
openssl-master/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; }
3,025
26.261261
103
c
openssl
openssl-master/test/x509_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 <openssl/x509.h> #include "testutil.h" static EVP_PKEY *pubkey = NULL; static EVP_PKEY *privkey = NULL; static EVP_MD *signmd = NULL; /* EC key pair used for signing */ static const unsigned char privkeydata[] = { 0x30, 0x77, 0x02, 0x01, 0x01, 0x04, 0x20, 0x7d, 0x2b, 0xfe, 0x5c, 0xcb, 0xcb, 0x27, 0xd6, 0x28, 0xfe, 0x98, 0x34, 0x84, 0x4a, 0x13, 0x6f, 0x70, 0xc4, 0x1a, 0x0b, 0xfc, 0xde, 0xb0, 0xb2, 0x32, 0xb1, 0xdd, 0x4f, 0x0e, 0xbc, 0xdf, 0x89, 0xa0, 0x0a, 0x06, 0x08, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x03, 0x01, 0x07, 0xa1, 0x44, 0x03, 0x42, 0x00, 0x04, 0xbf, 0x82, 0xd9, 0xc9, 0x4b, 0x19, 0x43, 0x45, 0x6b, 0xd4, 0x50, 0x64, 0x9b, 0xd5, 0x8d, 0x5a, 0xd9, 0xdc, 0xc9, 0x24, 0x23, 0x7a, 0x3b, 0x48, 0x23, 0xe2, 0x2a, 0x24, 0xf2, 0x9c, 0x6f, 0x87, 0xd0, 0xc4, 0x0f, 0xcc, 0x7e, 0x7c, 0x8d, 0xfc, 0x08, 0x46, 0x37, 0x85, 0x4f, 0x5b, 0x3a, 0x0b, 0x97, 0xd7, 0x57, 0x2a, 0x5a, 0x6b, 0x7a, 0x0b, 0xe4, 0xe8, 0x9c, 0x4a, 0xbb, 0xbf, 0x09, 0x4d }; static const unsigned char pubkeydata[] = { 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, 0xbf, 0x82, 0xd9, 0xc9, 0x4b, 0x19, 0x43, 0x45, 0x6b, 0xd4, 0x50, 0x64, 0x9b, 0xd5, 0x8d, 0x5a, 0xd9, 0xdc, 0xc9, 0x24, 0x23, 0x7a, 0x3b, 0x48, 0x23, 0xe2, 0x2a, 0x24, 0xf2, 0x9c, 0x6f, 0x87, 0xd0, 0xc4, 0x0f, 0xcc, 0x7e, 0x7c, 0x8d, 0xfc, 0x08, 0x46, 0x37, 0x85, 0x4f, 0x5b, 0x3a, 0x0b, 0x97, 0xd7, 0x57, 0x2a, 0x5a, 0x6b, 0x7a, 0x0b, 0xe4, 0xe8, 0x9c, 0x4a, 0xbb, 0xbf, 0x09, 0x4d }; /* Self signed cert using ECDSA-SHA256 with the keypair listed above */ static const unsigned char certdata[] = { 0x30, 0x82, 0x01, 0x86, 0x30, 0x82, 0x01, 0x2d, 0x02, 0x14, 0x75, 0xd6, 0x04, 0xd2, 0x80, 0x61, 0xd3, 0x32, 0xbc, 0xae, 0x38, 0x58, 0xfe, 0x12, 0x42, 0x81, 0x7a, 0xdd, 0x0b, 0x99, 0x30, 0x0a, 0x06, 0x08, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x04, 0x03, 0x02, 0x30, 0x45, 0x31, 0x0b, 0x30, 0x09, 0x06, 0x03, 0x55, 0x04, 0x06, 0x13, 0x02, 0x41, 0x55, 0x31, 0x13, 0x30, 0x11, 0x06, 0x03, 0x55, 0x04, 0x08, 0x0c, 0x0a, 0x53, 0x6f, 0x6d, 0x65, 0x2d, 0x53, 0x74, 0x61, 0x74, 0x65, 0x31, 0x21, 0x30, 0x1f, 0x06, 0x03, 0x55, 0x04, 0x0a, 0x0c, 0x18, 0x49, 0x6e, 0x74, 0x65, 0x72, 0x6e, 0x65, 0x74, 0x20, 0x57, 0x69, 0x64, 0x67, 0x69, 0x74, 0x73, 0x20, 0x50, 0x74, 0x79, 0x20, 0x4c, 0x74, 0x64, 0x30, 0x20, 0x17, 0x0d, 0x32, 0x32, 0x31, 0x30, 0x31, 0x32, 0x30, 0x37, 0x32, 0x37, 0x35, 0x35, 0x5a, 0x18, 0x0f, 0x32, 0x30, 0x35, 0x30, 0x30, 0x32, 0x32, 0x37, 0x30, 0x37, 0x32, 0x37, 0x35, 0x35, 0x5a, 0x30, 0x45, 0x31, 0x0b, 0x30, 0x09, 0x06, 0x03, 0x55, 0x04, 0x06, 0x13, 0x02, 0x41, 0x55, 0x31, 0x13, 0x30, 0x11, 0x06, 0x03, 0x55, 0x04, 0x08, 0x0c, 0x0a, 0x53, 0x6f, 0x6d, 0x65, 0x2d, 0x53, 0x74, 0x61, 0x74, 0x65, 0x31, 0x21, 0x30, 0x1f, 0x06, 0x03, 0x55, 0x04, 0x0a, 0x0c, 0x18, 0x49, 0x6e, 0x74, 0x65, 0x72, 0x6e, 0x65, 0x74, 0x20, 0x57, 0x69, 0x64, 0x67, 0x69, 0x74, 0x73, 0x20, 0x50, 0x74, 0x79, 0x20, 0x4c, 0x74, 0x64, 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, 0xbf, 0x82, 0xd9, 0xc9, 0x4b, 0x19, 0x43, 0x45, 0x6b, 0xd4, 0x50, 0x64, 0x9b, 0xd5, 0x8d, 0x5a, 0xd9, 0xdc, 0xc9, 0x24, 0x23, 0x7a, 0x3b, 0x48, 0x23, 0xe2, 0x2a, 0x24, 0xf2, 0x9c, 0x6f, 0x87, 0xd0, 0xc4, 0x0f, 0xcc, 0x7e, 0x7c, 0x8d, 0xfc, 0x08, 0x46, 0x37, 0x85, 0x4f, 0x5b, 0x3a, 0x0b, 0x97, 0xd7, 0x57, 0x2a, 0x5a, 0x6b, 0x7a, 0x0b, 0xe4, 0xe8, 0x9c, 0x4a, 0xbb, 0xbf, 0x09, 0x4d, 0x30, 0x0a, 0x06, 0x08, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x04, 0x03, 0x02, 0x03, 0x47, 0x00, 0x30, 0x44, 0x02, 0x20, 0x5f, 0x45, 0x7f, 0xa4, 0x6a, 0x03, 0xfd, 0xe7, 0xf3, 0x42, 0x43, 0x38, 0x5b, 0x81, 0x08, 0x1a, 0x47, 0x8e, 0x59, 0x3a, 0x28, 0x5b, 0x97, 0x67, 0x47, 0x66, 0x2a, 0x16, 0xf5, 0xce, 0xf5, 0x92, 0x02, 0x20, 0x22, 0x0e, 0xab, 0x35, 0xdf, 0x49, 0xb1, 0x86, 0xa3, 0x3b, 0x26, 0xda, 0x7e, 0x8b, 0x44, 0x45, 0xc6, 0x46, 0x14, 0x04, 0x22, 0x2b, 0xe5, 0x2a, 0x62, 0x84, 0xc5, 0x94, 0xa0, 0x1b, 0xaa, 0xa9 }; /* Some simple CRL data */ static const unsigned char crldata[] = { 0x30, 0x81, 0x8B, 0x30, 0x31, 0x02, 0x01, 0x01, 0x30, 0x0C, 0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x04, 0x03, 0x02, 0x05, 0x00, 0x30, 0x0F, 0x31, 0x0D, 0x30, 0x0B, 0x06, 0x03, 0x55, 0x04, 0x03, 0x0C, 0x04, 0x54, 0x65, 0x73, 0x74, 0x17, 0x0D, 0x32, 0x32, 0x31, 0x30, 0x31, 0x32, 0x30, 0x35, 0x33, 0x34, 0x30, 0x31, 0x5A, 0x30, 0x0C, 0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x04, 0x03, 0x02, 0x05, 0x00, 0x03, 0x48, 0x00, 0x30, 0x45, 0x02, 0x20, 0x75, 0xAC, 0xA9, 0xB5, 0xFE, 0x63, 0x09, 0x8B, 0x57, 0x4F, 0xBB, 0xC6, 0x0C, 0xA9, 0x9A, 0x7C, 0x55, 0x89, 0xF9, 0x9C, 0x48, 0xE9, 0xF3, 0xED, 0xE5, 0xC2, 0x88, 0xCE, 0xEC, 0xB1, 0x51, 0xF1, 0x02, 0x21, 0x00, 0x8B, 0x93, 0xC5, 0xA6, 0x28, 0x48, 0x5A, 0x4E, 0x10, 0x52, 0x82, 0x12, 0x2F, 0xC4, 0x62, 0x2D, 0x3F, 0x5A, 0x62, 0x7F, 0x9D, 0x1B, 0x12, 0xC5, 0x36, 0x25, 0x73, 0x03, 0xF4, 0xDE, 0x62, 0x24 }; /* * Test for Regression discussed in PR #19388 * In order for this simple test to fail, it requires the digest used for * signing to be different from the alg within the loaded cert. */ static int test_x509_tbs_cache(void) { int ret; X509 *x = NULL; const unsigned char *p = certdata; ret = TEST_ptr(x = d2i_X509(NULL, &p, sizeof(certdata))) && TEST_int_gt(X509_sign(x, privkey, signmd), 0) && TEST_int_eq(X509_verify(x, pubkey), 1); X509_free(x); return ret; } /* * Test for Regression discussed in PR #19388 * In order for this simple test to fail, it requires the digest used for * signing to be different from the alg within the loaded cert. */ static int test_x509_crl_tbs_cache(void) { int ret; X509_CRL *crl = NULL; const unsigned char *p = crldata; ret = TEST_ptr(crl = d2i_X509_CRL(NULL, &p, sizeof(crldata))) && TEST_int_gt(X509_CRL_sign(crl, privkey, signmd), 0) && TEST_int_eq(X509_CRL_verify(crl, pubkey), 1); X509_CRL_free(crl); return ret; } int setup_tests(void) { const unsigned char *p; p = pubkeydata; pubkey = d2i_PUBKEY(NULL, &p, sizeof(pubkeydata)); p = privkeydata; privkey = d2i_PrivateKey(EVP_PKEY_EC, NULL, &p, sizeof(privkeydata)); if (pubkey == NULL || privkey == NULL) { BIO_printf(bio_err, "Failed to create keys\n"); return 0; } /* Note this digest is different from the certificate digest */ signmd = EVP_MD_fetch(NULL, "SHA384", NULL); if (signmd == NULL) { BIO_printf(bio_err, "Failed to fetch digest\n"); return 0; } ADD_TEST(test_x509_tbs_cache); ADD_TEST(test_x509_crl_tbs_cache); return 1; } void cleanup_tests(void) { EVP_MD_free(signmd); EVP_PKEY_free(pubkey); EVP_PKEY_free(privkey); }
7,310
47.74
99
c
openssl
openssl-master/test/x509_time_test.c
/* * Copyright 2017-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 */ /* Tests for X509 time functions */ #include <string.h> #include <time.h> #include <openssl/asn1.h> #include <openssl/x509.h> #include "testutil.h" #include "internal/nelem.h" typedef struct { const char *data; int type; time_t cmp_time; /* -1 if asn1_time <= cmp_time, 1 if asn1_time > cmp_time, 0 if error. */ int expected; } TESTDATA; typedef struct { const char *data; /* 0 for check-only mode, 1 for set-string mode */ int set_string; /* 0 for error, 1 if succeed */ int expected; /* * The following 2 fields are ignored if set_string field is set to '0' * (in check only mode). * * But they can still be ignored explicitly in set-string mode by: * setting -1 to expected_type and setting NULL to expected_string. * * It's useful in a case of set-string mode but the expected result * is a 'parsing error'. */ int expected_type; const char *expected_string; } TESTDATA_FORMAT; /* * Actually, the "loose" mode has been tested in * those time-compare-cases, so we may not test it again. */ static TESTDATA_FORMAT x509_format_tests[] = { /* GeneralizedTime */ { /* good format, check only */ "20170217180105Z", 0, 1, -1, NULL, }, { /* not leap year, check only */ "20170229180105Z", 0, 0, -1, NULL, }, { /* leap year, check only */ "20160229180105Z", 0, 1, -1, NULL, }, { /* SS is missing, check only */ "201702171801Z", 0, 0, -1, NULL, }, { /* fractional seconds, check only */ "20170217180105.001Z", 0, 0, -1, NULL, }, { /* timezone, check only */ "20170217180105+0800", 0, 0, -1, NULL, }, { /* SS is missing, set string */ "201702171801Z", 1, 0, -1, NULL, }, { /* fractional seconds, set string */ "20170217180105.001Z", 1, 0, -1, NULL, }, { /* timezone, set string */ "20170217180105+0800", 1, 0, -1, NULL, }, { /* good format, check returned 'turned' string */ "20170217180154Z", 1, 1, V_ASN1_UTCTIME, "170217180154Z", }, { /* good format, check returned string */ "20510217180154Z", 1, 1, V_ASN1_GENERALIZEDTIME, "20510217180154Z", }, { /* good format but out of UTC range, check returned string */ "19230419180154Z", 1, 1, V_ASN1_GENERALIZEDTIME, "19230419180154Z", }, /* UTC */ { /* SS is missing, check only */ "1702171801Z", 0, 0, -1, NULL, }, { /* not leap year, check only */ "050229180101Z", 0, 0, -1, NULL, }, { /* leap year, check only */ "040229180101Z", 0, 1, -1, NULL, }, { /* timezone, check only */ "170217180154+0800", 0, 0, -1, NULL, }, { /* SS is missing, set string */ "1702171801Z", 1, 0, -1, NULL, }, { /* timezone, set string */ "170217180154+0800", 1, 0, -1, NULL, }, { /* 2017, good format, check returned string */ "170217180154Z", 1, 1, V_ASN1_UTCTIME, "170217180154Z", }, { /* 1998, good format, check returned string */ "981223180154Z", 1, 1, V_ASN1_UTCTIME, "981223180154Z", }, }; static TESTDATA x509_cmp_tests[] = { { "20170217180154Z", V_ASN1_GENERALIZEDTIME, /* The same in seconds since epoch. */ 1487354514, -1, }, { "20170217180154Z", V_ASN1_GENERALIZEDTIME, /* One second more. */ 1487354515, -1, }, { "20170217180154Z", V_ASN1_GENERALIZEDTIME, /* One second less. */ 1487354513, 1, }, /* Same as UTC time. */ { "170217180154Z", V_ASN1_UTCTIME, /* The same in seconds since epoch. */ 1487354514, -1, }, { "170217180154Z", V_ASN1_UTCTIME, /* One second more. */ 1487354515, -1, }, { "170217180154Z", V_ASN1_UTCTIME, /* One second less. */ 1487354513, 1, }, /* UTCTime from the 20th century. */ { "990217180154Z", V_ASN1_UTCTIME, /* The same in seconds since epoch. */ 919274514, -1, }, { "990217180154Z", V_ASN1_UTCTIME, /* One second more. */ 919274515, -1, }, { "990217180154Z", V_ASN1_UTCTIME, /* One second less. */ 919274513, 1, }, /* Various invalid formats. */ { /* No trailing Z. */ "20170217180154", V_ASN1_GENERALIZEDTIME, 0, 0, }, { /* No trailing Z, UTCTime. */ "170217180154", V_ASN1_UTCTIME, 0, 0, }, { /* No seconds. */ "201702171801Z", V_ASN1_GENERALIZEDTIME, 0, 0, }, { /* No seconds, UTCTime. */ "1702171801Z", V_ASN1_UTCTIME, 0, 0, }, { /* Fractional seconds. */ "20170217180154.001Z", V_ASN1_GENERALIZEDTIME, 0, 0, }, { /* Fractional seconds, UTCTime. */ "170217180154.001Z", V_ASN1_UTCTIME, 0, 0, }, { /* Timezone offset. */ "20170217180154+0100", V_ASN1_GENERALIZEDTIME, 0, 0, }, { /* Timezone offset, UTCTime. */ "170217180154+0100", V_ASN1_UTCTIME, 0, 0, }, { /* Extra digits. */ "2017021718015400Z", V_ASN1_GENERALIZEDTIME, 0, 0, }, { /* Extra digits, UTCTime. */ "17021718015400Z", V_ASN1_UTCTIME, 0, 0, }, { /* Non-digits. */ "2017021718015aZ", V_ASN1_GENERALIZEDTIME, 0, 0, }, { /* Non-digits, UTCTime. */ "17021718015aZ", V_ASN1_UTCTIME, 0, 0, }, { /* Trailing garbage. */ "20170217180154Zlongtrailinggarbage", V_ASN1_GENERALIZEDTIME, 0, 0, }, { /* Trailing garbage, UTCTime. */ "170217180154Zlongtrailinggarbage", V_ASN1_UTCTIME, 0, 0, }, { /* Swapped type. */ "20170217180154Z", V_ASN1_UTCTIME, 0, 0, }, { /* Swapped type. */ "170217180154Z", V_ASN1_GENERALIZEDTIME, 0, 0, }, { /* Bad type. */ "20170217180154Z", V_ASN1_OCTET_STRING, 0, 0, }, }; static int test_x509_cmp_time(int idx) { ASN1_TIME t; int result; memset(&t, 0, sizeof(t)); t.type = x509_cmp_tests[idx].type; t.data = (unsigned char*)(x509_cmp_tests[idx].data); t.length = strlen(x509_cmp_tests[idx].data); t.flags = 0; result = X509_cmp_time(&t, &x509_cmp_tests[idx].cmp_time); if (!TEST_int_eq(result, x509_cmp_tests[idx].expected)) { TEST_info("test_x509_cmp_time(%d) failed: expected %d, got %d\n", idx, x509_cmp_tests[idx].expected, result); return 0; } return 1; } static int test_x509_cmp_time_current(void) { time_t now = time(NULL); /* Pick a day earlier and later, relative to any system clock. */ ASN1_TIME *asn1_before = NULL, *asn1_after = NULL; int cmp_result, failed = 0; asn1_before = ASN1_TIME_adj(NULL, now, -1, 0); asn1_after = ASN1_TIME_adj(NULL, now, 1, 0); cmp_result = X509_cmp_time(asn1_before, NULL); if (!TEST_int_eq(cmp_result, -1)) failed = 1; cmp_result = X509_cmp_time(asn1_after, NULL); if (!TEST_int_eq(cmp_result, 1)) failed = 1; ASN1_TIME_free(asn1_before); ASN1_TIME_free(asn1_after); return failed == 0; } static int test_X509_cmp_timeframe_vpm(const X509_VERIFY_PARAM *vpm, ASN1_TIME *asn1_before, ASN1_TIME *asn1_mid, ASN1_TIME *asn1_after) { int always_0 = vpm != NULL && (X509_VERIFY_PARAM_get_flags(vpm) & X509_V_FLAG_USE_CHECK_TIME) == 0 && (X509_VERIFY_PARAM_get_flags(vpm) & X509_V_FLAG_NO_CHECK_TIME) != 0; return asn1_before != NULL && asn1_mid != NULL && asn1_after != NULL && TEST_int_eq(X509_cmp_timeframe(vpm, asn1_before, asn1_after), 0) && TEST_int_eq(X509_cmp_timeframe(vpm, asn1_before, NULL), 0) && TEST_int_eq(X509_cmp_timeframe(vpm, NULL, asn1_after), 0) && TEST_int_eq(X509_cmp_timeframe(vpm, NULL, NULL), 0) && TEST_int_eq(X509_cmp_timeframe(vpm, asn1_after, asn1_after), always_0 ? 0 : -1) && TEST_int_eq(X509_cmp_timeframe(vpm, asn1_before, asn1_before), always_0 ? 0 : 1) && TEST_int_eq(X509_cmp_timeframe(vpm, asn1_after, asn1_before), always_0 ? 0 : 1); } static int test_X509_cmp_timeframe(void) { time_t now = time(NULL); ASN1_TIME *asn1_mid = ASN1_TIME_adj(NULL, now, 0, 0); /* Pick a day earlier and later, relative to any system clock. */ ASN1_TIME *asn1_before = ASN1_TIME_adj(NULL, now, -1, 0); ASN1_TIME *asn1_after = ASN1_TIME_adj(NULL, now, 1, 0); X509_VERIFY_PARAM *vpm = X509_VERIFY_PARAM_new(); int res = 0; if (vpm == NULL) goto finish; res = test_X509_cmp_timeframe_vpm(NULL, asn1_before, asn1_mid, asn1_after) && test_X509_cmp_timeframe_vpm(vpm, asn1_before, asn1_mid, asn1_after); X509_VERIFY_PARAM_set_time(vpm, now); res = res && test_X509_cmp_timeframe_vpm(vpm, asn1_before, asn1_mid, asn1_after) && X509_VERIFY_PARAM_set_flags(vpm, X509_V_FLAG_NO_CHECK_TIME) && test_X509_cmp_timeframe_vpm(vpm, asn1_before, asn1_mid, asn1_after); X509_VERIFY_PARAM_free(vpm); finish: ASN1_TIME_free(asn1_mid); ASN1_TIME_free(asn1_before); ASN1_TIME_free(asn1_after); return res; } static int test_x509_time(int idx) { ASN1_TIME *t = NULL; int result, rv = 0; if (x509_format_tests[idx].set_string) { /* set-string mode */ t = ASN1_TIME_new(); if (t == NULL) { TEST_info("test_x509_time(%d) failed: internal error\n", idx); return 0; } } result = ASN1_TIME_set_string_X509(t, x509_format_tests[idx].data); /* time string parsing result is always checked against what's expected */ if (!TEST_int_eq(result, x509_format_tests[idx].expected)) { TEST_info("test_x509_time(%d) failed: expected %d, got %d\n", idx, x509_format_tests[idx].expected, result); goto out; } /* if t is not NULL but expected_type is ignored(-1), it is an 'OK' case */ if (t != NULL && x509_format_tests[idx].expected_type != -1) { if (!TEST_int_eq(t->type, x509_format_tests[idx].expected_type)) { TEST_info("test_x509_time(%d) failed: expected_type %d, got %d\n", idx, x509_format_tests[idx].expected_type, t->type); goto out; } } /* if t is not NULL but expected_string is NULL, it is an 'OK' case too */ if (t != NULL && x509_format_tests[idx].expected_string) { if (!TEST_mem_eq((const char *)t->data, t->length, x509_format_tests[idx].expected_string, strlen(x509_format_tests[idx].expected_string))) { TEST_info("test_x509_time(%d) failed: expected_string %s, got %.*s\n", idx, x509_format_tests[idx].expected_string, t->length, t->data); goto out; } } rv = 1; out: if (t != NULL) ASN1_TIME_free(t); return rv; } static const struct { int y, m, d; int yd, wd; } day_of_week_tests[] = { /*YYYY MM DD DoY DoW */ { 1900, 1, 1, 0, 1 }, { 1900, 2, 28, 58, 3 }, { 1900, 3, 1, 59, 4 }, { 1900, 12, 31, 364, 1 }, { 1901, 1, 1, 0, 2 }, { 1970, 1, 1, 0, 4 }, { 1999, 1, 10, 9, 0 }, { 1999, 12, 31, 364, 5 }, { 2000, 1, 1, 0, 6 }, { 2000, 2, 28, 58, 1 }, { 2000, 2, 29, 59, 2 }, { 2000, 3, 1, 60, 3 }, { 2000, 12, 31, 365, 0 }, { 2001, 1, 1, 0, 1 }, { 2008, 1, 1, 0, 2 }, { 2008, 2, 28, 58, 4 }, { 2008, 2, 29, 59, 5 }, { 2008, 3, 1, 60, 6 }, { 2008, 12, 31, 365, 3 }, { 2009, 1, 1, 0, 4 }, { 2011, 1, 1, 0, 6 }, { 2011, 2, 28, 58, 1 }, { 2011, 3, 1, 59, 2 }, { 2011, 12, 31, 364, 6 }, { 2012, 1, 1, 0, 0 }, { 2019, 1, 2, 1, 3 }, { 2019, 2, 2, 32, 6 }, { 2019, 3, 2, 60, 6 }, { 2019, 4, 2, 91, 2 }, { 2019, 5, 2, 121, 4 }, { 2019, 6, 2, 152, 0 }, { 2019, 7, 2, 182, 2 }, { 2019, 8, 2, 213, 5 }, { 2019, 9, 2, 244, 1 }, { 2019, 10, 2, 274, 3 }, { 2019, 11, 2, 305, 6 }, { 2019, 12, 2, 335, 1 }, { 2020, 1, 2, 1, 4 }, { 2020, 2, 2, 32, 0 }, { 2020, 3, 2, 61, 1 }, { 2020, 4, 2, 92, 4 }, { 2020, 5, 2, 122, 6 }, { 2020, 6, 2, 153, 2 }, { 2020, 7, 2, 183, 4 }, { 2020, 8, 2, 214, 0 }, { 2020, 9, 2, 245, 3 }, { 2020, 10, 2, 275, 5 }, { 2020, 11, 2, 306, 1 }, { 2020, 12, 2, 336, 3 } }; static int test_days(int n) { char d[16]; ASN1_TIME *a = NULL; struct tm t; int r; BIO_snprintf(d, sizeof(d), "%04d%02d%02d050505Z", day_of_week_tests[n].y, day_of_week_tests[n].m, day_of_week_tests[n].d); if (!TEST_ptr(a = ASN1_TIME_new())) return 0; r = TEST_true(ASN1_TIME_set_string(a, d)) && TEST_true(ASN1_TIME_to_tm(a, &t)) && TEST_int_eq(t.tm_yday, day_of_week_tests[n].yd) && TEST_int_eq(t.tm_wday, day_of_week_tests[n].wd); ASN1_TIME_free(a); return r; } #define construct_asn1_time(s, t, e) \ { { sizeof(s) - 1, t, (unsigned char*)s, 0 }, e } static const struct { ASN1_TIME asn1; const char *readable; } x509_print_tests_rfc_822 [] = { /* Generalized Time */ construct_asn1_time("20170731222050Z", V_ASN1_GENERALIZEDTIME, "Jul 31 22:20:50 2017 GMT"), /* Generalized Time, no seconds */ construct_asn1_time("201707312220Z", V_ASN1_GENERALIZEDTIME, "Jul 31 22:20:00 2017 GMT"), /* Generalized Time, fractional seconds (3 digits) */ construct_asn1_time("20170731222050.123Z", V_ASN1_GENERALIZEDTIME, "Jul 31 22:20:50.123 2017 GMT"), /* Generalized Time, fractional seconds (1 digit) */ construct_asn1_time("20170731222050.1Z", V_ASN1_GENERALIZEDTIME, "Jul 31 22:20:50.1 2017 GMT"), /* Generalized Time, fractional seconds (0 digit) */ construct_asn1_time("20170731222050.Z", V_ASN1_GENERALIZEDTIME, "Bad time value"), /* UTC Time */ construct_asn1_time("170731222050Z", V_ASN1_UTCTIME, "Jul 31 22:20:50 2017 GMT"), /* UTC Time, no seconds */ construct_asn1_time("1707312220Z", V_ASN1_UTCTIME, "Jul 31 22:20:00 2017 GMT"), }; static const struct { ASN1_TIME asn1; const char *readable; } x509_print_tests_iso_8601 [] = { /* Generalized Time */ construct_asn1_time("20170731222050Z", V_ASN1_GENERALIZEDTIME, "2017-07-31 22:20:50Z"), /* Generalized Time, no seconds */ construct_asn1_time("201707312220Z", V_ASN1_GENERALIZEDTIME, "2017-07-31 22:20:00Z"), /* Generalized Time, fractional seconds (3 digits) */ construct_asn1_time("20170731222050.123Z", V_ASN1_GENERALIZEDTIME, "2017-07-31 22:20:50.123Z"), /* Generalized Time, fractional seconds (1 digit) */ construct_asn1_time("20170731222050.1Z", V_ASN1_GENERALIZEDTIME, "2017-07-31 22:20:50.1Z"), /* Generalized Time, fractional seconds (0 digit) */ construct_asn1_time("20170731222050.Z", V_ASN1_GENERALIZEDTIME, "Bad time value"), /* UTC Time */ construct_asn1_time("170731222050Z", V_ASN1_UTCTIME, "2017-07-31 22:20:50Z"), /* UTC Time, no seconds */ construct_asn1_time("1707312220Z", V_ASN1_UTCTIME, "2017-07-31 22:20:00Z"), }; static int test_x509_time_print_rfc_822(int idx) { BIO *m; int ret = 0, rv; char *pp; const char *readable; if (!TEST_ptr(m = BIO_new(BIO_s_mem()))) goto err; rv = ASN1_TIME_print_ex(m, &x509_print_tests_rfc_822[idx].asn1, ASN1_DTFLGS_RFC822); readable = x509_print_tests_rfc_822[idx].readable; if (rv == 0 && !TEST_str_eq(readable, "Bad time value")) { /* only if the test case intends to fail... */ goto err; } if (!TEST_int_ne(rv = BIO_get_mem_data(m, &pp), 0) || !TEST_int_eq(rv, (int)strlen(readable)) || !TEST_strn_eq(pp, readable, rv)) goto err; ret = 1; err: BIO_free(m); return ret; } static int test_x509_time_print_iso_8601(int idx) { BIO *m; int ret = 0, rv; char *pp; const char *readable; if (!TEST_ptr(m = BIO_new(BIO_s_mem()))) goto err; rv = ASN1_TIME_print_ex(m, &x509_print_tests_iso_8601[idx].asn1, ASN1_DTFLGS_ISO8601); readable = x509_print_tests_iso_8601[idx].readable; if (rv == 0 && !TEST_str_eq(readable, "Bad time value")) { /* only if the test case intends to fail... */ goto err; } if (!TEST_int_ne(rv = BIO_get_mem_data(m, &pp), 0) || !TEST_int_eq(rv, (int)strlen(readable)) || !TEST_strn_eq(pp, readable, rv)) goto err; ret = 1; err: BIO_free(m); return ret; } int setup_tests(void) { ADD_TEST(test_x509_cmp_time_current); ADD_TEST(test_X509_cmp_timeframe); ADD_ALL_TESTS(test_x509_cmp_time, OSSL_NELEM(x509_cmp_tests)); ADD_ALL_TESTS(test_x509_time, OSSL_NELEM(x509_format_tests)); ADD_ALL_TESTS(test_days, OSSL_NELEM(day_of_week_tests)); ADD_ALL_TESTS(test_x509_time_print_rfc_822, OSSL_NELEM(x509_print_tests_rfc_822)); ADD_ALL_TESTS(test_x509_time_print_iso_8601, OSSL_NELEM(x509_print_tests_iso_8601)); return 1; }
18,100
28.919008
90
c
openssl
openssl-master/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; }
5,313
27.569892
77
c
openssl
openssl-master/test/helpers/cmp_testlib.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 "cmp_testlib.h" #include <openssl/rsa.h> /* needed in case config no-deprecated */ OSSL_CMP_MSG *load_pkimsg(const char *file, OSSL_LIB_CTX *libctx) { OSSL_CMP_MSG *msg; (void)TEST_ptr((msg = OSSL_CMP_MSG_read(file, libctx, NULL))); return msg; } /* * Checks whether the syntax of msg conforms to ASN.1 */ int valid_asn1_encoding(const OSSL_CMP_MSG *msg) { return msg != NULL ? i2d_OSSL_CMP_MSG(msg, NULL) > 0 : 0; } /* * Compares two stacks of certificates in the order of their elements. * Returns 0 if sk1 and sk2 are equal and another value otherwise */ int STACK_OF_X509_cmp(const STACK_OF(X509) *sk1, const STACK_OF(X509) *sk2) { int i, res; X509 *a, *b; if (sk1 == sk2) return 0; if (sk1 == NULL) return -1; if (sk2 == NULL) return 1; if ((res = sk_X509_num(sk1) - sk_X509_num(sk2))) return res; for (i = 0; i < sk_X509_num(sk1); i++) { a = sk_X509_value(sk1, i); b = sk_X509_value(sk2, i); if (a != b) if ((res = X509_cmp(a, b)) != 0) return res; } return 0; } /* * Up refs and push a cert onto sk. * Returns the number of certificates on the stack on success * Returns -1 or 0 on error */ int STACK_OF_X509_push1(STACK_OF(X509) *sk, X509 *cert) { int res; if (sk == NULL || cert == NULL) return -1; if (!X509_up_ref(cert)) return -1; res = sk_X509_push(sk, cert); if (res <= 0) X509_free(cert); /* down-ref */ return res; } int print_to_bio_out(const char *func, const char *file, int line, OSSL_CMP_severity level, const char *msg) { return OSSL_CMP_print_to_bio(bio_out, func, file, line, level, msg); }
2,150
25.231707
75
c
openssl
openssl-master/test/helpers/cmp_testlib.h
/* * 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 */ #ifndef OSSL_TEST_CMP_TESTLIB_H # define OSSL_TEST_CMP_TESTLIB_H # include <openssl/cmp.h> # include <openssl/pem.h> # include <openssl/rand.h> # include "../../crypto/cmp/cmp_local.h" # include "../testutil.h" # ifndef OPENSSL_NO_CMP # define CMP_TEST_REFVALUE_LENGTH 15 /* arbitrary value */ OSSL_CMP_MSG *load_pkimsg(const char *file, OSSL_LIB_CTX *libctx); int valid_asn1_encoding(const OSSL_CMP_MSG *msg); int STACK_OF_X509_cmp(const STACK_OF(X509) *sk1, const STACK_OF(X509) *sk2); int STACK_OF_X509_push1(STACK_OF(X509) *sk, X509 *cert); int print_to_bio_out(const char *func, const char *file, int line, OSSL_CMP_severity level, const char *msg); # endif #endif /* OSSL_TEST_CMP_TESTLIB_H */
1,126
33.151515
76
h
openssl
openssl-master/test/helpers/handshake.h
/* * 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 */ #ifndef OSSL_TEST_HANDSHAKE_HELPER_H #define OSSL_TEST_HANDSHAKE_HELPER_H #include "ssl_test_ctx.h" typedef struct ctx_data_st { unsigned char *npn_protocols; size_t npn_protocols_len; unsigned char *alpn_protocols; size_t alpn_protocols_len; char *srp_user; char *srp_password; char *session_ticket_app_data; } CTX_DATA; typedef struct handshake_result { ssl_test_result_t result; /* These alerts are in the 2-byte format returned by the info_callback. */ /* (Latest) alert sent by the client; 0 if no alert. */ int client_alert_sent; /* Number of fatal or close_notify alerts sent. */ int client_num_fatal_alerts_sent; /* (Latest) alert received by the server; 0 if no alert. */ int client_alert_received; /* (Latest) alert sent by the server; 0 if no alert. */ int server_alert_sent; /* Number of fatal or close_notify alerts sent. */ int server_num_fatal_alerts_sent; /* (Latest) alert received by the client; 0 if no alert. */ int server_alert_received; /* Negotiated protocol. On success, these should always match. */ int server_protocol; int client_protocol; /* Server connection */ ssl_servername_t servername; /* Session ticket status */ ssl_session_ticket_t session_ticket; int compression; /* Was this called on the second context? */ int session_ticket_do_not_call; char *client_npn_negotiated; char *server_npn_negotiated; char *client_alpn_negotiated; char *server_alpn_negotiated; /* Was the handshake resumed? */ int client_resumed; int server_resumed; /* Temporary key type */ int tmp_key_type; /* server certificate key type */ int server_cert_type; /* server signing hash */ int server_sign_hash; /* server signature type */ int server_sign_type; /* server CA names */ STACK_OF(X509_NAME) *server_ca_names; /* client certificate key type */ int client_cert_type; /* client signing hash */ int client_sign_hash; /* client signature type */ int client_sign_type; /* Client CA names */ STACK_OF(X509_NAME) *client_ca_names; /* Session id status */ ssl_session_id_t session_id; char *cipher; /* session ticket application data */ char *result_session_ticket_app_data; } HANDSHAKE_RESULT; HANDSHAKE_RESULT *HANDSHAKE_RESULT_new(void); void HANDSHAKE_RESULT_free(HANDSHAKE_RESULT *result); /* Do a handshake and report some information about the result. */ HANDSHAKE_RESULT *do_handshake(SSL_CTX *server_ctx, SSL_CTX *server2_ctx, SSL_CTX *client_ctx, SSL_CTX *resume_server_ctx, SSL_CTX *resume_client_ctx, const SSL_TEST_CTX *test_ctx); int configure_handshake_ctx_for_srp(SSL_CTX *server_ctx, SSL_CTX *server2_ctx, SSL_CTX *client_ctx, const SSL_TEST_EXTRA_CONF *extra, CTX_DATA *server_ctx_data, CTX_DATA *server2_ctx_data, CTX_DATA *client_ctx_data); #endif /* OSSL_TEST_HANDSHAKE_HELPER_H */
3,574
35.111111
79
h