file_path
stringlengths
19
75
code
stringlengths
279
1.37M
./openssl/test/helpers/pkcs12.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 <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 "pkcs12.h" /* from the same directory */ /* Set this to > 0 write test data to file */ static int write_files = 0; static int legacy = 0; static OSSL_LIB_CTX *test_ctx = NULL; static const char *test_propq = NULL; /* ------------------------------------------------------------------------- * Local function declarations */ static int add_attributes(PKCS12_SAFEBAG *bag, const PKCS12_ATTR *attrs); static void generate_p12(PKCS12_BUILDER *pb, const PKCS12_ENC *mac); static int write_p12(PKCS12 *p12, const char *outfile); static PKCS12 *from_bio_p12(BIO *bio, const PKCS12_ENC *mac); static PKCS12 *read_p12(const char *infile, const PKCS12_ENC *mac); static int check_p12_mac(PKCS12 *p12, const PKCS12_ENC *mac); static int check_asn1_string(const ASN1_TYPE *av, const char *txt); static int check_attrs(const STACK_OF(X509_ATTRIBUTE) *bag_attrs, const PKCS12_ATTR *attrs); /* -------------------------------------------------------------------------- * Global settings */ void PKCS12_helper_set_write_files(int enable) { write_files = enable; } void PKCS12_helper_set_legacy(int enable) { legacy = enable; } void PKCS12_helper_set_libctx(OSSL_LIB_CTX *libctx) { test_ctx = libctx; } void PKCS12_helper_set_propq(const char *propq) { test_propq = propq; } /* -------------------------------------------------------------------------- * Test data load functions */ static X509 *load_cert_asn1(const unsigned char *bytes, int len) { X509 *cert = NULL; cert = d2i_X509(NULL, &bytes, len); if (!TEST_ptr(cert)) goto err; err: return cert; } static EVP_PKEY *load_pkey_asn1(const unsigned char *bytes, int len) { EVP_PKEY *pkey = NULL; pkey = d2i_AutoPrivateKey(NULL, &bytes, len); if (!TEST_ptr(pkey)) goto err; err: return pkey; } /* ------------------------------------------------------------------------- * PKCS12 builder */ PKCS12_BUILDER *new_pkcs12_builder(const char *filename) { PKCS12_BUILDER *pb = OPENSSL_malloc(sizeof(PKCS12_BUILDER)); if (!TEST_ptr(pb)) return NULL; pb->filename = filename; pb->success = 1; return pb; } int end_pkcs12_builder(PKCS12_BUILDER *pb) { int result = pb->success; OPENSSL_free(pb); return result; } void start_pkcs12(PKCS12_BUILDER *pb) { pb->safes = NULL; } void end_pkcs12(PKCS12_BUILDER *pb) { if (!pb->success) return; generate_p12(pb, NULL); } void end_pkcs12_with_mac(PKCS12_BUILDER *pb, const PKCS12_ENC *mac) { if (!pb->success) return; generate_p12(pb, mac); } /* Generate the PKCS12 encoding and write to memory bio */ static void generate_p12(PKCS12_BUILDER *pb, const PKCS12_ENC *mac) { PKCS12 *p12; EVP_MD *md = NULL; if (!pb->success) return; pb->p12bio = BIO_new(BIO_s_mem()); if (!TEST_ptr(pb->p12bio)) { pb->success = 0; return; } if (legacy) p12 = PKCS12_add_safes(pb->safes, 0); else p12 = PKCS12_add_safes_ex(pb->safes, 0, test_ctx, test_propq); if (!TEST_ptr(p12)) { pb->success = 0; goto err; } sk_PKCS7_pop_free(pb->safes, PKCS7_free); if (mac != NULL) { if (legacy) md = (EVP_MD *)EVP_get_digestbynid(mac->nid); else md = EVP_MD_fetch(test_ctx, OBJ_nid2sn(mac->nid), test_propq); if (!TEST_true(PKCS12_set_mac(p12, mac->pass, strlen(mac->pass), NULL, 0, mac->iter, md))) { pb->success = 0; goto err; } } i2d_PKCS12_bio(pb->p12bio, p12); /* Can write to file here for debug */ if (write_files) write_p12(p12, pb->filename); err: if (!legacy && md != NULL) EVP_MD_free(md); PKCS12_free(p12); } static int write_p12(PKCS12 *p12, const char *outfile) { int ret = 0; BIO *out = BIO_new_file(outfile, "w"); if (out == NULL) goto err; if (!TEST_int_eq(i2d_PKCS12_bio(out, p12), 1)) goto err; ret = 1; err: BIO_free(out); return ret; } static PKCS12 *from_bio_p12(BIO *bio, const PKCS12_ENC *mac) { PKCS12 *p12 = NULL; /* Supply a p12 with library context/propq to the d2i decoder*/ if (!legacy) { p12 = PKCS12_init_ex(NID_pkcs7_data, test_ctx, test_propq); if (!TEST_ptr(p12)) goto err; } p12 = d2i_PKCS12_bio(bio, &p12); BIO_free(bio); if (!TEST_ptr(p12)) goto err; if (mac == NULL) { if (!TEST_false(PKCS12_mac_present(p12))) goto err; } else { if (!check_p12_mac(p12, mac)) goto err; } return p12; err: PKCS12_free(p12); return NULL; } /* For use with existing files */ static PKCS12 *read_p12(const char *infile, const PKCS12_ENC *mac) { PKCS12 *p12 = NULL; BIO *in = BIO_new_file(infile, "r"); if (in == NULL) goto err; p12 = d2i_PKCS12_bio(in, NULL); BIO_free(in); if (!TEST_ptr(p12)) goto err; if (mac == NULL) { if (!TEST_false(PKCS12_mac_present(p12))) goto err; } else { if (!check_p12_mac(p12, mac)) goto err; } return p12; err: PKCS12_free(p12); return NULL; } static int check_p12_mac(PKCS12 *p12, const PKCS12_ENC *mac) { return TEST_true(PKCS12_mac_present(p12)) && TEST_true(PKCS12_verify_mac(p12, mac->pass, strlen(mac->pass))); } /* ------------------------------------------------------------------------- * PKCS7 content info builder */ void start_contentinfo(PKCS12_BUILDER *pb) { pb->bags = NULL; } void end_contentinfo(PKCS12_BUILDER *pb) { if (pb->success && pb->bags != NULL) { if (!TEST_true(PKCS12_add_safe(&pb->safes, pb->bags, -1, 0, NULL))) pb->success = 0; } sk_PKCS12_SAFEBAG_pop_free(pb->bags, PKCS12_SAFEBAG_free); pb->bags = NULL; } void end_contentinfo_encrypted(PKCS12_BUILDER *pb, const PKCS12_ENC *enc) { if (pb->success && pb->bags != NULL) { if (legacy) { if (!TEST_true(PKCS12_add_safe(&pb->safes, pb->bags, enc->nid, enc->iter, enc->pass))) pb->success = 0; } else { if (!TEST_true(PKCS12_add_safe_ex(&pb->safes, pb->bags, enc->nid, enc->iter, enc->pass, test_ctx, test_propq))) pb->success = 0; } } sk_PKCS12_SAFEBAG_pop_free(pb->bags, PKCS12_SAFEBAG_free); pb->bags = NULL; } static STACK_OF(PKCS12_SAFEBAG) *decode_contentinfo(STACK_OF(PKCS7) *safes, int idx, const PKCS12_ENC *enc) { STACK_OF(PKCS12_SAFEBAG) *bags = NULL; int bagnid; PKCS7 *p7 = sk_PKCS7_value(safes, idx); if (!TEST_ptr(p7)) goto err; bagnid = OBJ_obj2nid(p7->type); if (enc) { if (!TEST_int_eq(bagnid, NID_pkcs7_encrypted)) goto err; bags = PKCS12_unpack_p7encdata(p7, enc->pass, strlen(enc->pass)); } else { if (!TEST_int_eq(bagnid, NID_pkcs7_data)) goto err; bags = PKCS12_unpack_p7data(p7); } if (!TEST_ptr(bags)) goto err; return bags; err: return NULL; } /* ------------------------------------------------------------------------- * PKCS12 safeBag/attribute builder */ static int add_attributes(PKCS12_SAFEBAG *bag, const PKCS12_ATTR *attr) { int ret = 0; int attr_nid; const PKCS12_ATTR *p_attr = attr; STACK_OF(X509_ATTRIBUTE)* attrs = NULL; X509_ATTRIBUTE *x509_attr = NULL; if (attr == NULL) return 1; while (p_attr->oid != NULL) { TEST_info("Adding attribute %s = %s", p_attr->oid, p_attr->value); attr_nid = OBJ_txt2nid(p_attr->oid); if (attr_nid == NID_friendlyName) { if (!TEST_true(PKCS12_add_friendlyname(bag, p_attr->value, -1))) goto err; } else if (attr_nid == NID_localKeyID) { if (!TEST_true(PKCS12_add_localkeyid(bag, (unsigned char *)p_attr->value, strlen(p_attr->value)))) goto err; } else if (attr_nid == NID_oracle_jdk_trustedkeyusage) { attrs = (STACK_OF(X509_ATTRIBUTE)*)PKCS12_SAFEBAG_get0_attrs(bag); x509_attr = X509_ATTRIBUTE_create(attr_nid, V_ASN1_OBJECT, OBJ_txt2obj(p_attr->value, 0)); X509at_add1_attr(&attrs, x509_attr); PKCS12_SAFEBAG_set0_attrs(bag, attrs); X509_ATTRIBUTE_free(x509_attr); } else { /* Custom attribute values limited to ASCII in these tests */ if (!TEST_true(PKCS12_add1_attr_by_txt(bag, p_attr->oid, MBSTRING_ASC, (unsigned char *)p_attr->value, strlen(p_attr->value)))) goto err; } p_attr++; } ret = 1; err: return ret; } void add_certbag(PKCS12_BUILDER *pb, const unsigned char *bytes, int len, const PKCS12_ATTR *attrs) { PKCS12_SAFEBAG *bag = NULL; X509 *cert = NULL; char *name; if (!pb->success) return; cert = load_cert_asn1(bytes, len); if (!TEST_ptr(cert)) { pb->success = 0; return; } name = X509_NAME_oneline(X509_get_subject_name(cert), NULL, 0); TEST_info("Adding certificate <%s>", name); OPENSSL_free(name); bag = PKCS12_add_cert(&pb->bags, cert); if (!TEST_ptr(bag)) { pb->success = 0; goto err; } if (!TEST_true(add_attributes(bag, attrs))) { pb->success = 0; goto err; } err: X509_free(cert); } void add_keybag(PKCS12_BUILDER *pb, const unsigned char *bytes, int len, const PKCS12_ATTR *attrs, const PKCS12_ENC *enc) { PKCS12_SAFEBAG *bag = NULL; EVP_PKEY *pkey = NULL; if (!pb->success) return; TEST_info("Adding key"); pkey = load_pkey_asn1(bytes, len); if (!TEST_ptr(pkey)) { pb->success = 0; return; } if (legacy) bag = PKCS12_add_key(&pb->bags, pkey, 0 /*keytype*/, enc->iter, enc->nid, enc->pass); else bag = PKCS12_add_key_ex(&pb->bags, pkey, 0 /*keytype*/, enc->iter, enc->nid, enc->pass, test_ctx, test_propq); if (!TEST_ptr(bag)) { pb->success = 0; goto err; } if (!add_attributes(bag, attrs)) pb->success = 0; err: EVP_PKEY_free(pkey); } void add_secretbag(PKCS12_BUILDER *pb, int secret_nid, const char *secret, const PKCS12_ATTR *attrs) { PKCS12_SAFEBAG *bag = NULL; if (!pb->success) return; TEST_info("Adding secret <%s>", secret); bag = PKCS12_add_secret(&pb->bags, secret_nid, (const unsigned char *)secret, strlen(secret)); if (!TEST_ptr(bag)) { pb->success = 0; return; } if (!add_attributes(bag, attrs)) pb->success = 0; } /* ------------------------------------------------------------------------- * PKCS12 structure checking */ static int check_asn1_string(const ASN1_TYPE *av, const char *txt) { int ret = 0; char *value = NULL; if (!TEST_ptr(av)) goto err; switch (av->type) { case V_ASN1_BMPSTRING: value = OPENSSL_uni2asc(av->value.bmpstring->data, av->value.bmpstring->length); if (!TEST_str_eq(txt, (char *)value)) goto err; break; case V_ASN1_UTF8STRING: if (!TEST_mem_eq(txt, strlen(txt), (char *)av->value.utf8string->data, av->value.utf8string->length)) goto err; break; case V_ASN1_OCTET_STRING: if (!TEST_mem_eq(txt, strlen(txt), (char *)av->value.octet_string->data, av->value.octet_string->length)) goto err; break; default: /* Tests do not support other attribute types currently */ goto err; } ret = 1; err: OPENSSL_free(value); return ret; } static int check_attrs(const STACK_OF(X509_ATTRIBUTE) *bag_attrs, const PKCS12_ATTR *attrs) { int ret = 0; X509_ATTRIBUTE *attr; ASN1_TYPE *av; int i, j; char attr_txt[100]; for (i = 0; i < sk_X509_ATTRIBUTE_num(bag_attrs); i++) { const PKCS12_ATTR *p_attr = attrs; ASN1_OBJECT *attr_obj; attr = sk_X509_ATTRIBUTE_value(bag_attrs, i); attr_obj = X509_ATTRIBUTE_get0_object(attr); OBJ_obj2txt(attr_txt, 100, attr_obj, 0); while (p_attr->oid != NULL) { /* Find a matching attribute type */ if (strcmp(p_attr->oid, attr_txt) == 0) { if (!TEST_int_eq(X509_ATTRIBUTE_count(attr), 1)) goto err; for (j = 0; j < X509_ATTRIBUTE_count(attr); j++) { av = X509_ATTRIBUTE_get0_type(attr, j); if (!TEST_true(check_asn1_string(av, p_attr->value))) goto err; } break; } p_attr++; } } ret = 1; err: return ret; } void check_certbag(PKCS12_BUILDER *pb, const unsigned char *bytes, int len, const PKCS12_ATTR *attrs) { X509 *x509 = NULL; X509 *ref_x509 = NULL; const PKCS12_SAFEBAG *bag; if (!pb->success) return; bag = sk_PKCS12_SAFEBAG_value(pb->bags, pb->bag_idx++); if (!TEST_ptr(bag)) { pb->success = 0; return; } if (!check_attrs(PKCS12_SAFEBAG_get0_attrs(bag), attrs) || !TEST_int_eq(PKCS12_SAFEBAG_get_nid(bag), NID_certBag) || !TEST_int_eq(PKCS12_SAFEBAG_get_bag_nid(bag), NID_x509Certificate)) { pb->success = 0; return; } x509 = PKCS12_SAFEBAG_get1_cert(bag); if (!TEST_ptr(x509)) { pb->success = 0; goto err; } ref_x509 = load_cert_asn1(bytes, len); if (!TEST_false(X509_cmp(x509, ref_x509))) pb->success = 0; err: X509_free(x509); X509_free(ref_x509); } void check_keybag(PKCS12_BUILDER *pb, const unsigned char *bytes, int len, const PKCS12_ATTR *attrs, const PKCS12_ENC *enc) { EVP_PKEY *pkey = NULL; EVP_PKEY *ref_pkey = NULL; PKCS8_PRIV_KEY_INFO *p8; const PKCS8_PRIV_KEY_INFO *p8c; const PKCS12_SAFEBAG *bag; if (!pb->success) return; bag = sk_PKCS12_SAFEBAG_value(pb->bags, pb->bag_idx++); if (!TEST_ptr(bag)) { pb->success = 0; return; } if (!check_attrs(PKCS12_SAFEBAG_get0_attrs(bag), attrs)) { pb->success = 0; return; } switch (PKCS12_SAFEBAG_get_nid(bag)) { case NID_keyBag: p8c = PKCS12_SAFEBAG_get0_p8inf(bag); if (!TEST_ptr(pkey = EVP_PKCS82PKEY(p8c))) { pb->success = 0; goto err; } break; case NID_pkcs8ShroudedKeyBag: if (legacy) p8 = PKCS12_decrypt_skey(bag, enc->pass, strlen(enc->pass)); else p8 = PKCS12_decrypt_skey_ex(bag, enc->pass, strlen(enc->pass), test_ctx, test_propq); if (!TEST_ptr(p8)) { pb->success = 0; goto err; } if (!TEST_ptr(pkey = EVP_PKCS82PKEY(p8))) { PKCS8_PRIV_KEY_INFO_free(p8); pb->success = 0; goto err; } PKCS8_PRIV_KEY_INFO_free(p8); break; default: pb->success = 0; goto err; } /* PKEY compare returns 1 for match */ ref_pkey = load_pkey_asn1(bytes, len); if (!TEST_true(EVP_PKEY_eq(pkey, ref_pkey))) pb->success = 0; err: EVP_PKEY_free(pkey); EVP_PKEY_free(ref_pkey); } void check_secretbag(PKCS12_BUILDER *pb, int secret_nid, const char *secret, const PKCS12_ATTR *attrs) { const PKCS12_SAFEBAG *bag; if (!pb->success) return; bag = sk_PKCS12_SAFEBAG_value(pb->bags, pb->bag_idx++); if (!TEST_ptr(bag)) { pb->success = 0; return; } if (!check_attrs(PKCS12_SAFEBAG_get0_attrs(bag), attrs) || !TEST_int_eq(PKCS12_SAFEBAG_get_nid(bag), NID_secretBag) || !TEST_int_eq(PKCS12_SAFEBAG_get_bag_nid(bag), secret_nid) || !TEST_true(check_asn1_string(PKCS12_SAFEBAG_get0_bag_obj(bag), secret))) pb->success = 0; } void start_check_pkcs12(PKCS12_BUILDER *pb) { PKCS12 *p12; if (!pb->success) return; p12 = from_bio_p12(pb->p12bio, NULL); if (!TEST_ptr(p12)) { pb->success = 0; return; } pb->safes = PKCS12_unpack_authsafes(p12); if (!TEST_ptr(pb->safes)) pb->success = 0; pb->safe_idx = 0; PKCS12_free(p12); } void start_check_pkcs12_with_mac(PKCS12_BUILDER *pb, const PKCS12_ENC *mac) { PKCS12 *p12; if (!pb->success) return; p12 = from_bio_p12(pb->p12bio, mac); if (!TEST_ptr(p12)) { pb->success = 0; return; } pb->safes = PKCS12_unpack_authsafes(p12); if (!TEST_ptr(pb->safes)) pb->success = 0; pb->safe_idx = 0; PKCS12_free(p12); } void start_check_pkcs12_file(PKCS12_BUILDER *pb) { PKCS12 *p12; if (!pb->success) return; p12 = read_p12(pb->filename, NULL); if (!TEST_ptr(p12)) { pb->success = 0; return; } pb->safes = PKCS12_unpack_authsafes(p12); if (!TEST_ptr(pb->safes)) pb->success = 0; pb->safe_idx = 0; PKCS12_free(p12); } void start_check_pkcs12_file_with_mac(PKCS12_BUILDER *pb, const PKCS12_ENC *mac) { PKCS12 *p12; if (!pb->success) return; p12 = read_p12(pb->filename, mac); if (!TEST_ptr(p12)) { pb->success = 0; return; } pb->safes = PKCS12_unpack_authsafes(p12); if (!TEST_ptr(pb->safes)) pb->success = 0; pb->safe_idx = 0; PKCS12_free(p12); } void end_check_pkcs12(PKCS12_BUILDER *pb) { if (!pb->success) return; sk_PKCS7_pop_free(pb->safes, PKCS7_free); } void start_check_contentinfo(PKCS12_BUILDER *pb) { if (!pb->success) return; pb->bag_idx = 0; pb->bags = decode_contentinfo(pb->safes, pb->safe_idx++, NULL); if (!TEST_ptr(pb->bags)) { pb->success = 0; return; } TEST_info("Decoding %d bags", sk_PKCS12_SAFEBAG_num(pb->bags)); } void start_check_contentinfo_encrypted(PKCS12_BUILDER *pb, const PKCS12_ENC *enc) { if (!pb->success) return; pb->bag_idx = 0; pb->bags = decode_contentinfo(pb->safes, pb->safe_idx++, enc); if (!TEST_ptr(pb->bags)) { pb->success = 0; return; } TEST_info("Decoding %d bags", sk_PKCS12_SAFEBAG_num(pb->bags)); } void end_check_contentinfo(PKCS12_BUILDER *pb) { if (!pb->success) return; if (!TEST_int_eq(sk_PKCS12_SAFEBAG_num(pb->bags), pb->bag_idx)) pb->success = 0; sk_PKCS12_SAFEBAG_pop_free(pb->bags, PKCS12_SAFEBAG_free); pb->bags = NULL; }
./openssl/test/helpers/ssl_test_ctx.h
/* * Copyright 2016-2023 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #ifndef OSSL_TEST_SSL_TEST_CTX_H #define OSSL_TEST_SSL_TEST_CTX_H #include <openssl/conf.h> #include <openssl/ssl.h> typedef enum { SSL_TEST_SUCCESS = 0, /* Default */ SSL_TEST_SERVER_FAIL, SSL_TEST_CLIENT_FAIL, SSL_TEST_INTERNAL_ERROR, /* Couldn't test resumption/renegotiation: original handshake failed. */ SSL_TEST_FIRST_HANDSHAKE_FAILED } ssl_test_result_t; typedef enum { SSL_TEST_VERIFY_NONE = 0, /* Default */ SSL_TEST_VERIFY_ACCEPT_ALL, SSL_TEST_VERIFY_RETRY_ONCE, SSL_TEST_VERIFY_REJECT_ALL } ssl_verify_callback_t; typedef enum { SSL_TEST_SERVERNAME_NONE = 0, /* Default */ SSL_TEST_SERVERNAME_SERVER1, SSL_TEST_SERVERNAME_SERVER2, SSL_TEST_SERVERNAME_INVALID } ssl_servername_t; typedef enum { SSL_TEST_SERVERNAME_CB_NONE = 0, /* Default */ SSL_TEST_SERVERNAME_IGNORE_MISMATCH, SSL_TEST_SERVERNAME_REJECT_MISMATCH, SSL_TEST_SERVERNAME_CLIENT_HELLO_IGNORE_MISMATCH, SSL_TEST_SERVERNAME_CLIENT_HELLO_REJECT_MISMATCH, SSL_TEST_SERVERNAME_CLIENT_HELLO_NO_V12 } ssl_servername_callback_t; typedef enum { SSL_TEST_SESSION_TICKET_IGNORE = 0, /* Default */ SSL_TEST_SESSION_TICKET_YES, SSL_TEST_SESSION_TICKET_NO, SSL_TEST_SESSION_TICKET_BROKEN /* Special test */ } ssl_session_ticket_t; typedef enum { SSL_TEST_COMPRESSION_NO = 0, /* Default */ SSL_TEST_COMPRESSION_YES } ssl_compression_t; typedef enum { SSL_TEST_SESSION_ID_IGNORE = 0, /* Default */ SSL_TEST_SESSION_ID_YES, SSL_TEST_SESSION_ID_NO } ssl_session_id_t; typedef enum { SSL_TEST_METHOD_TLS = 0, /* Default */ SSL_TEST_METHOD_DTLS, SSL_TEST_METHOD_QUIC } ssl_test_method_t; typedef enum { SSL_TEST_HANDSHAKE_SIMPLE = 0, /* Default */ SSL_TEST_HANDSHAKE_RESUME, SSL_TEST_HANDSHAKE_RENEG_SERVER, SSL_TEST_HANDSHAKE_RENEG_CLIENT, SSL_TEST_HANDSHAKE_KEY_UPDATE_SERVER, SSL_TEST_HANDSHAKE_KEY_UPDATE_CLIENT, SSL_TEST_HANDSHAKE_POST_HANDSHAKE_AUTH } ssl_handshake_mode_t; typedef enum { SSL_TEST_CT_VALIDATION_NONE = 0, /* Default */ SSL_TEST_CT_VALIDATION_PERMISSIVE, SSL_TEST_CT_VALIDATION_STRICT } ssl_ct_validation_t; typedef enum { SSL_TEST_CERT_STATUS_NONE = 0, /* Default */ SSL_TEST_CERT_STATUS_GOOD_RESPONSE, SSL_TEST_CERT_STATUS_BAD_RESPONSE } ssl_cert_status_t; /* * Server/client settings that aren't supported by the SSL CONF library, * such as callbacks. */ typedef struct { /* One of a number of predefined custom callbacks. */ ssl_verify_callback_t verify_callback; /* One of a number of predefined server names use by the client */ ssl_servername_t servername; /* Maximum Fragment Length extension mode */ int max_fragment_len_mode; /* Supported NPN and ALPN protocols. A comma-separated list. */ char *npn_protocols; char *alpn_protocols; ssl_ct_validation_t ct_validation; /* Ciphersuites to set on a renegotiation */ char *reneg_ciphers; char *srp_user; char *srp_password; /* PHA enabled */ int enable_pha; /* Do not send extms on renegotiation */ int no_extms_on_reneg; } SSL_TEST_CLIENT_CONF; typedef struct { /* SNI callback (server-side). */ ssl_servername_callback_t servername_callback; /* Supported NPN and ALPN protocols. A comma-separated list. */ char *npn_protocols; char *alpn_protocols; /* Whether to set a broken session ticket callback. */ int broken_session_ticket; /* Should we send a CertStatus message? */ ssl_cert_status_t cert_status; /* An SRP user known to the server. */ char *srp_user; char *srp_password; /* Forced PHA */ int force_pha; char *session_ticket_app_data; } SSL_TEST_SERVER_CONF; typedef struct { SSL_TEST_CLIENT_CONF client; SSL_TEST_SERVER_CONF server; SSL_TEST_SERVER_CONF server2; } SSL_TEST_EXTRA_CONF; typedef struct { /* * Global test configuration. Does not change between handshakes. */ /* Whether the server/client CTX should use DTLS or TLS. */ ssl_test_method_t method; /* Whether to test a resumed/renegotiated handshake. */ ssl_handshake_mode_t handshake_mode; /* * How much application data to exchange (default is 256 bytes). * Both peers will send |app_data_size| bytes interleaved. */ int app_data_size; /* Maximum send fragment size. */ int max_fragment_size; /* KeyUpdate type */ int key_update_type; /* * Extra server/client configurations. Per-handshake. */ /* First handshake. */ SSL_TEST_EXTRA_CONF extra; /* Resumed handshake. */ SSL_TEST_EXTRA_CONF resume_extra; /* * Test expectations. These apply to the LAST handshake. */ /* Defaults to SUCCESS. */ ssl_test_result_t expected_result; /* Alerts. 0 if no expectation. */ /* See ssl.h for alert codes. */ /* Alert sent by the client / received by the server. */ int expected_client_alert; /* Alert sent by the server / received by the client. */ int expected_server_alert; /* Negotiated protocol version. 0 if no expectation. */ /* See ssl.h for protocol versions. */ int expected_protocol; /* * The expected SNI context to use. * We test server-side that the server switched to the expected context. * Set by the callback upon success, so if the callback wasn't called or * terminated with an alert, the servername will match with * SSL_TEST_SERVERNAME_NONE. * Note: in the event that the servername was accepted, the client should * also receive an empty SNI extension back but we have no way of probing * client-side via the API that this was the case. */ ssl_servername_t expected_servername; ssl_session_ticket_t session_ticket_expected; int compression_expected; /* The expected NPN/ALPN protocol to negotiate. */ char *expected_npn_protocol; char *expected_alpn_protocol; /* Whether the second handshake is resumed or a full handshake (boolean). */ int resumption_expected; /* Expected temporary key type */ int expected_tmp_key_type; /* Expected server certificate key type */ int expected_server_cert_type; /* Expected server signing hash */ int expected_server_sign_hash; /* Expected server signature type */ int expected_server_sign_type; /* Expected server CA names */ STACK_OF(X509_NAME) *expected_server_ca_names; /* Expected client certificate key type */ int expected_client_cert_type; /* Expected client signing hash */ int expected_client_sign_hash; /* Expected client signature type */ int expected_client_sign_type; /* Expected CA names for client auth */ STACK_OF(X509_NAME) *expected_client_ca_names; /* Whether to use SCTP for the transport */ int use_sctp; /* Whether to pre-compress server certificates */ int compress_certificates; /* Enable SSL_MODE_DTLS_SCTP_LABEL_LENGTH_BUG on client side */ int enable_client_sctp_label_bug; /* Enable SSL_MODE_DTLS_SCTP_LABEL_LENGTH_BUG on server side */ int enable_server_sctp_label_bug; /* Whether to expect a session id from the server */ ssl_session_id_t session_id_expected; char *expected_cipher; /* Expected Session Ticket Application Data */ char *expected_session_ticket_app_data; OSSL_LIB_CTX *libctx; /* FIPS version string to check for compatibility */ char *fips_version; } SSL_TEST_CTX; const char *ssl_test_result_name(ssl_test_result_t result); const char *ssl_alert_name(int alert); const char *ssl_protocol_name(int protocol); const char *ssl_verify_callback_name(ssl_verify_callback_t verify_callback); const char *ssl_servername_name(ssl_servername_t server); const char *ssl_servername_callback_name(ssl_servername_callback_t servername_callback); const char *ssl_session_ticket_name(ssl_session_ticket_t server); const char *ssl_session_id_name(ssl_session_id_t server); const char *ssl_test_method_name(ssl_test_method_t method); const char *ssl_handshake_mode_name(ssl_handshake_mode_t mode); const char *ssl_ct_validation_name(ssl_ct_validation_t mode); const char *ssl_certstatus_name(ssl_cert_status_t cert_status); const char *ssl_max_fragment_len_name(int MFL_mode); /* * Load the test case context from |conf|. * See test/README.ssltest.md for details on the conf file format. */ SSL_TEST_CTX *SSL_TEST_CTX_create(const CONF *conf, const char *test_section, OSSL_LIB_CTX *libctx); SSL_TEST_CTX *SSL_TEST_CTX_new(OSSL_LIB_CTX *libctx); void SSL_TEST_CTX_free(SSL_TEST_CTX *ctx); #endif /* OSSL_TEST_SSL_TEST_CTX_H */
./openssl/test/helpers/quictestlib.c
/* * Copyright 2022-2023 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <assert.h> #include <openssl/configuration.h> #include <openssl/bio.h> #include "internal/e_os.h" /* For struct timeval */ #include "quictestlib.h" #include "ssltestlib.h" #include "../testutil.h" #if defined(OPENSSL_THREADS) && !defined(CRYPTO_TDEBUG) # include "../threadstest.h" #endif #include "internal/quic_ssl.h" #include "internal/quic_wire_pkt.h" #include "internal/quic_record_tx.h" #include "internal/quic_error.h" #include "internal/packet.h" #include "internal/tsan_assist.h" #define GROWTH_ALLOWANCE 1024 struct noise_args_data_st { BIO *cbio; BIO *sbio; BIO *tracebio; int flags; }; struct qtest_fault { QUIC_TSERVER *qtserv; /* Plain packet mutations */ /* Header for the plaintext packet */ QUIC_PKT_HDR pplainhdr; /* iovec for the plaintext packet data buffer */ OSSL_QTX_IOVEC pplainio; /* Allocated size of the plaintext packet data buffer */ size_t pplainbuf_alloc; qtest_fault_on_packet_plain_cb pplaincb; void *pplaincbarg; /* Handshake message mutations */ /* Handshake message buffer */ unsigned char *handbuf; /* Allocated size of the handshake message buffer */ size_t handbufalloc; /* Actual length of the handshake message */ size_t handbuflen; qtest_fault_on_handshake_cb handshakecb; void *handshakecbarg; qtest_fault_on_enc_ext_cb encextcb; void *encextcbarg; /* Cipher packet mutations */ qtest_fault_on_packet_cipher_cb pciphercb; void *pciphercbarg; /* Datagram mutations */ qtest_fault_on_datagram_cb datagramcb; void *datagramcbarg; /* The currently processed message */ BIO_MSG msg; /* Allocated size of msg data buffer */ size_t msgalloc; struct noise_args_data_st noiseargs; }; static void packet_plain_finish(void *arg); static void handshake_finish(void *arg); static OSSL_TIME qtest_get_time(void); static void qtest_reset_time(void); static int using_fake_time = 0; static OSSL_TIME fake_now; static CRYPTO_RWLOCK *fake_now_lock = NULL; static OSSL_TIME fake_now_cb(void *arg) { return qtest_get_time(); } static void noise_msg_callback(int write_p, int version, int content_type, const void *buf, size_t len, SSL *ssl, void *arg) { struct noise_args_data_st *noiseargs = (struct noise_args_data_st *)arg; if (content_type == SSL3_RT_QUIC_FRAME_FULL) { PACKET pkt; uint64_t frame_type; if (!PACKET_buf_init(&pkt, buf, len)) return; if (!ossl_quic_wire_peek_frame_header(&pkt, &frame_type, NULL)) return; if (frame_type == OSSL_QUIC_FRAME_TYPE_PING) { /* * If either endpoint issues a ping frame then we are in danger * of our noise being too much such that the connection itself * fails. We back off on the noise for a bit to avoid that. */ (void)BIO_ctrl(noiseargs->cbio, BIO_CTRL_NOISE_BACK_OFF, 0, NULL); (void)BIO_ctrl(noiseargs->sbio, BIO_CTRL_NOISE_BACK_OFF, 0, NULL); } } #ifndef OPENSSL_NO_SSL_TRACE if ((noiseargs->flags & QTEST_FLAG_CLIENT_TRACE) != 0 && !SSL_is_server(ssl)) SSL_trace(write_p, version, content_type, buf, len, ssl, noiseargs->tracebio); #endif } int qtest_create_quic_objects(OSSL_LIB_CTX *libctx, SSL_CTX *clientctx, SSL_CTX *serverctx, char *certfile, char *keyfile, int flags, QUIC_TSERVER **qtserv, SSL **cssl, QTEST_FAULT **fault, BIO **tracebio) { /* ALPN value as recognised by QUIC_TSERVER */ unsigned char alpn[] = { 8, 'o', 's', 's', 'l', 't', 'e', 's', 't' }; QUIC_TSERVER_ARGS tserver_args = {0}; BIO *cbio = NULL, *sbio = NULL, *fisbio = NULL; BIO_ADDR *peeraddr = NULL; struct in_addr ina = {0}; BIO *tmpbio = NULL; *qtserv = NULL; if (*cssl == NULL) { *cssl = SSL_new(clientctx); if (!TEST_ptr(*cssl)) return 0; } if (fault != NULL) { *fault = OPENSSL_zalloc(sizeof(**fault)); if (*fault == NULL) goto err; } #ifndef OPENSSL_NO_SSL_TRACE if ((flags & QTEST_FLAG_CLIENT_TRACE) != 0) { tmpbio = BIO_new_fp(stdout, BIO_NOCLOSE); if (!TEST_ptr(tmpbio)) goto err; SSL_set_msg_callback(*cssl, SSL_trace); SSL_set_msg_callback_arg(*cssl, tmpbio); } #endif if (tracebio != NULL) *tracebio = tmpbio; /* SSL_set_alpn_protos returns 0 for success! */ if (!TEST_false(SSL_set_alpn_protos(*cssl, alpn, sizeof(alpn)))) goto err; if (!TEST_ptr(peeraddr = BIO_ADDR_new())) goto err; if ((flags & QTEST_FLAG_BLOCK) != 0) { #if !defined(OPENSSL_NO_POSIX_IO) int cfd, sfd; /* * For blocking mode we need to create actual sockets rather than doing * everything in memory */ if (!TEST_true(create_test_sockets(&cfd, &sfd, SOCK_DGRAM, peeraddr))) goto err; cbio = BIO_new_dgram(cfd, 1); if (!TEST_ptr(cbio)) { close(cfd); close(sfd); goto err; } sbio = BIO_new_dgram(sfd, 1); if (!TEST_ptr(sbio)) { close(sfd); goto err; } #else goto err; #endif } else { if (!TEST_true(BIO_new_bio_dgram_pair(&cbio, 0, &sbio, 0))) goto err; if (!TEST_true(BIO_dgram_set_caps(cbio, BIO_DGRAM_CAP_HANDLES_DST_ADDR)) || !TEST_true(BIO_dgram_set_caps(sbio, BIO_DGRAM_CAP_HANDLES_DST_ADDR))) goto err; /* Dummy server address */ if (!TEST_true(BIO_ADDR_rawmake(peeraddr, AF_INET, &ina, sizeof(ina), htons(0)))) goto err; } if ((flags & QTEST_FLAG_PACKET_SPLIT) != 0) { BIO *pktsplitbio = BIO_new(bio_f_pkt_split_dgram_filter()); if (!TEST_ptr(pktsplitbio)) goto err; cbio = BIO_push(pktsplitbio, cbio); pktsplitbio = BIO_new(bio_f_pkt_split_dgram_filter()); if (!TEST_ptr(pktsplitbio)) goto err; sbio = BIO_push(pktsplitbio, sbio); } if ((flags & QTEST_FLAG_NOISE) != 0) { BIO *noisebio; /* * It is an error to not have a QTEST_FAULT object when introducing noise */ if (!TEST_ptr(fault)) goto err; noisebio = BIO_new(bio_f_noisy_dgram_filter()); if (!TEST_ptr(noisebio)) goto err; cbio = BIO_push(noisebio, cbio); noisebio = BIO_new(bio_f_noisy_dgram_filter()); if (!TEST_ptr(noisebio)) goto err; sbio = BIO_push(noisebio, sbio); /* * TODO(QUIC SERVER): * Currently the simplistic handler of the quic tserver cannot cope * with noise introduced in the first packet received from the * client. This needs to be removed once we have proper server side * handling. */ (void)BIO_ctrl(sbio, BIO_CTRL_NOISE_BACK_OFF, 0, NULL); (*fault)->noiseargs.cbio = cbio; (*fault)->noiseargs.sbio = sbio; (*fault)->noiseargs.tracebio = tmpbio; (*fault)->noiseargs.flags = flags; SSL_set_msg_callback(*cssl, noise_msg_callback); SSL_set_msg_callback_arg(*cssl, &(*fault)->noiseargs); } SSL_set_bio(*cssl, cbio, cbio); if (!TEST_true(SSL_set_blocking_mode(*cssl, (flags & QTEST_FLAG_BLOCK) != 0 ? 1 : 0))) goto err; if (!TEST_true(SSL_set1_initial_peer_addr(*cssl, peeraddr))) goto err; fisbio = BIO_new(qtest_get_bio_method()); if (!TEST_ptr(fisbio)) goto err; BIO_set_data(fisbio, fault == NULL ? NULL : *fault); if (!BIO_up_ref(sbio)) goto err; if (!TEST_ptr(BIO_push(fisbio, sbio))) { BIO_free(sbio); goto err; } tserver_args.libctx = libctx; tserver_args.net_rbio = sbio; tserver_args.net_wbio = fisbio; tserver_args.alpn = NULL; if (serverctx != NULL && !TEST_true(SSL_CTX_up_ref(serverctx))) goto err; tserver_args.ctx = serverctx; if (fake_now_lock == NULL) { fake_now_lock = CRYPTO_THREAD_lock_new(); if (fake_now_lock == NULL) goto err; } if ((flags & QTEST_FLAG_FAKE_TIME) != 0) { using_fake_time = 1; qtest_reset_time(); tserver_args.now_cb = fake_now_cb; (void)ossl_quic_conn_set_override_now_cb(*cssl, fake_now_cb, NULL); } else { using_fake_time = 0; } if (!TEST_ptr(*qtserv = ossl_quic_tserver_new(&tserver_args, certfile, keyfile))) goto err; /* Ownership of fisbio and sbio is now held by *qtserv */ sbio = NULL; fisbio = NULL; if ((flags & QTEST_FLAG_NOISE) != 0) ossl_quic_tserver_set_msg_callback(*qtserv, noise_msg_callback, &(*fault)->noiseargs); if (fault != NULL) (*fault)->qtserv = *qtserv; BIO_ADDR_free(peeraddr); return 1; err: SSL_CTX_free(tserver_args.ctx); BIO_ADDR_free(peeraddr); BIO_free_all(cbio); BIO_free_all(fisbio); BIO_free_all(sbio); SSL_free(*cssl); *cssl = NULL; ossl_quic_tserver_free(*qtserv); if (fault != NULL) OPENSSL_free(*fault); BIO_free(tmpbio); if (tracebio != NULL) *tracebio = NULL; return 0; } void qtest_add_time(uint64_t millis) { if (!CRYPTO_THREAD_write_lock(fake_now_lock)) return; fake_now = ossl_time_add(fake_now, ossl_ms2time(millis)); CRYPTO_THREAD_unlock(fake_now_lock); } static OSSL_TIME qtest_get_time(void) { OSSL_TIME ret; if (!CRYPTO_THREAD_read_lock(fake_now_lock)) return ossl_time_zero(); ret = fake_now; CRYPTO_THREAD_unlock(fake_now_lock); return ret; } static void qtest_reset_time(void) { if (!CRYPTO_THREAD_write_lock(fake_now_lock)) return; fake_now = ossl_time_zero(); CRYPTO_THREAD_unlock(fake_now_lock); /* zero time can have a special meaning, bump it */ qtest_add_time(1); } QTEST_FAULT *qtest_create_injector(QUIC_TSERVER *ts) { QTEST_FAULT *f; f = OPENSSL_zalloc(sizeof(*f)); if (f == NULL) return NULL; f->qtserv = ts; return f; } int qtest_supports_blocking(void) { #if !defined(OPENSSL_NO_POSIX_IO) && defined(OPENSSL_THREADS) && !defined(CRYPTO_TDEBUG) return 1; #else return 0; #endif } #define MAXLOOPS 1000 #if defined(OPENSSL_THREADS) && !defined(CRYPTO_TDEBUG) static int globserverret = 0; static TSAN_QUALIFIER int abortserverthread = 0; static QUIC_TSERVER *globtserv; static const thread_t thread_zero; static void run_server_thread(void) { /* * This will operate in a busy loop because the server does not block, * but should be acceptable because it is local and we expect this to be * fast */ globserverret = qtest_create_quic_connection(globtserv, NULL); } #endif int qtest_wait_for_timeout(SSL *s, QUIC_TSERVER *qtserv) { struct timeval tv; OSSL_TIME ctimeout, stimeout, mintimeout, now; int cinf; /* We don't need to wait in blocking mode */ if (s == NULL || SSL_get_blocking_mode(s)) return 1; /* Don't wait if either BIO has data waiting */ if (BIO_pending(SSL_get_rbio(s)) > 0 || BIO_pending(ossl_quic_tserver_get0_rbio(qtserv)) > 0) return 1; /* * Neither endpoint has data waiting to be read. We assume data transmission * is instantaneous due to using mem based BIOs, so there is no data "in * flight" and no more data will be sent by either endpoint until some time * based event has occurred. Therefore, wait for a timeout to occur. This * might happen if we are using the noisy BIO and datagrams have been lost. */ if (!SSL_get_event_timeout(s, &tv, &cinf)) return 0; if (using_fake_time) now = qtest_get_time(); else now = ossl_time_now(); ctimeout = cinf ? ossl_time_infinite() : ossl_time_from_timeval(tv); stimeout = ossl_time_subtract(ossl_quic_tserver_get_deadline(qtserv), now); mintimeout = ossl_time_min(ctimeout, stimeout); if (ossl_time_is_infinite(mintimeout)) return 0; if (using_fake_time) qtest_add_time(ossl_time2ms(mintimeout)); else OSSL_sleep(ossl_time2ms(mintimeout)); return 1; } int qtest_create_quic_connection_ex(QUIC_TSERVER *qtserv, SSL *clientssl, int wanterr) { int retc = -1, rets = 0, abortctr = 0, ret = 0; int clienterr = 0, servererr = 0; #if defined(OPENSSL_THREADS) && !defined(CRYPTO_TDEBUG) /* * Pointless initialisation to avoid bogus compiler warnings about using * t uninitialised */ thread_t t = thread_zero; if (clientssl != NULL) abortserverthread = 0; #endif if (!TEST_ptr(qtserv)) { goto err; } else if (clientssl == NULL) { retc = 1; } else if (SSL_get_blocking_mode(clientssl) > 0) { #if defined(OPENSSL_THREADS) && !defined(CRYPTO_TDEBUG) /* * clientssl is blocking. We will need a thread to complete the * connection */ globtserv = qtserv; if (!TEST_true(run_thread(&t, run_server_thread))) goto err; qtserv = NULL; rets = 1; #else TEST_error("No thread support in this build"); goto err; #endif } do { if (!clienterr && retc <= 0) { int err; retc = SSL_connect(clientssl); if (retc <= 0) { err = SSL_get_error(clientssl, retc); if (err == wanterr) { retc = 1; #if defined(OPENSSL_THREADS) && !defined(CRYPTO_TDEBUG) if (qtserv == NULL && rets > 0) tsan_store(&abortserverthread, 1); else #endif rets = 1; } else { if (err != SSL_ERROR_WANT_READ && err != SSL_ERROR_WANT_WRITE) { TEST_info("SSL_connect() failed %d, %d", retc, err); TEST_openssl_errors(); clienterr = 1; } } } } qtest_add_time(1); if (clientssl != NULL) SSL_handle_events(clientssl); if (qtserv != NULL) ossl_quic_tserver_tick(qtserv); if (!servererr && rets <= 0) { servererr = ossl_quic_tserver_is_term_any(qtserv); if (!servererr) rets = ossl_quic_tserver_is_handshake_confirmed(qtserv); } if (clienterr && servererr) goto err; if (clientssl != NULL && ++abortctr == MAXLOOPS) { TEST_info("No progress made"); goto err; } if ((retc <= 0 && !clienterr) || (rets <= 0 && !servererr)) { if (!qtest_wait_for_timeout(clientssl, qtserv)) goto err; } } while ((retc <= 0 && !clienterr) || (rets <= 0 && !servererr #if defined(OPENSSL_THREADS) && !defined(CRYPTO_TDEBUG) && !tsan_load(&abortserverthread) #endif )); if (qtserv == NULL && rets > 0) { #if defined(OPENSSL_THREADS) && !defined(CRYPTO_TDEBUG) if (!TEST_true(wait_for_thread(t)) || !TEST_true(globserverret)) goto err; #else TEST_error("Should not happen"); goto err; #endif } if (!clienterr && !servererr) ret = 1; err: return ret; } int qtest_create_quic_connection(QUIC_TSERVER *qtserv, SSL *clientssl) { return qtest_create_quic_connection_ex(qtserv, clientssl, SSL_ERROR_NONE); } #if defined(OPENSSL_THREADS) && !defined(CRYPTO_TDEBUG) static TSAN_QUALIFIER int shutdowndone; static void run_server_shutdown_thread(void) { /* * This will operate in a busy loop because the server does not block, * but should be acceptable because it is local and we expect this to be * fast */ do { ossl_quic_tserver_tick(globtserv); } while(!tsan_load(&shutdowndone)); } #endif int qtest_shutdown(QUIC_TSERVER *qtserv, SSL *clientssl) { int tickserver = 1; int ret = 0; #if defined(OPENSSL_THREADS) && !defined(CRYPTO_TDEBUG) /* * Pointless initialisation to avoid bogus compiler warnings about using * t uninitialised */ thread_t t = thread_zero; #endif if (SSL_get_blocking_mode(clientssl) > 0) { #if defined(OPENSSL_THREADS) && !defined(CRYPTO_TDEBUG) /* * clientssl is blocking. We will need a thread to complete the * connection */ globtserv = qtserv; shutdowndone = 0; if (!TEST_true(run_thread(&t, run_server_shutdown_thread))) return 0; tickserver = 0; #else TEST_error("No thread support in this build"); return 0; #endif } /* Busy loop in non-blocking mode. It should be quick because its local */ for (;;) { int rc = SSL_shutdown(clientssl); if (rc == 1) { ret = 1; break; } if (rc < 0) break; if (tickserver) ossl_quic_tserver_tick(qtserv); } #if defined(OPENSSL_THREADS) && !defined(CRYPTO_TDEBUG) tsan_store(&shutdowndone, 1); if (!tickserver) { if (!TEST_true(wait_for_thread(t))) ret = 0; } #endif return ret; } int qtest_check_server_transport_err(QUIC_TSERVER *qtserv, uint64_t code) { const QUIC_TERMINATE_CAUSE *cause; ossl_quic_tserver_tick(qtserv); /* * Check that the server has closed with the specified code from the client */ if (!TEST_true(ossl_quic_tserver_is_term_any(qtserv))) return 0; cause = ossl_quic_tserver_get_terminate_cause(qtserv); if (!TEST_ptr(cause) || !TEST_true(cause->remote) || !TEST_false(cause->app) || !TEST_uint64_t_eq(cause->error_code, code)) return 0; return 1; } int qtest_check_server_protocol_err(QUIC_TSERVER *qtserv) { return qtest_check_server_transport_err(qtserv, QUIC_ERR_PROTOCOL_VIOLATION); } int qtest_check_server_frame_encoding_err(QUIC_TSERVER *qtserv) { return qtest_check_server_transport_err(qtserv, QUIC_ERR_FRAME_ENCODING_ERROR); } void qtest_fault_free(QTEST_FAULT *fault) { if (fault == NULL) return; packet_plain_finish(fault); handshake_finish(fault); OPENSSL_free(fault); } static int packet_plain_mutate(const QUIC_PKT_HDR *hdrin, const OSSL_QTX_IOVEC *iovecin, size_t numin, QUIC_PKT_HDR **hdrout, const OSSL_QTX_IOVEC **iovecout, size_t *numout, void *arg) { QTEST_FAULT *fault = arg; size_t i, bufsz = 0; unsigned char *cur; /* Coalesce our data into a single buffer */ /* First calculate required buffer size */ for (i = 0; i < numin; i++) bufsz += iovecin[i].buf_len; fault->pplainio.buf_len = bufsz; /* Add an allowance for possible growth */ bufsz += GROWTH_ALLOWANCE; fault->pplainio.buf = cur = OPENSSL_malloc(bufsz); if (cur == NULL) { fault->pplainio.buf_len = 0; return 0; } fault->pplainbuf_alloc = bufsz; /* Copy in the data from the input buffers */ for (i = 0; i < numin; i++) { memcpy(cur, iovecin[i].buf, iovecin[i].buf_len); cur += iovecin[i].buf_len; } fault->pplainhdr = *hdrin; /* Cast below is safe because we allocated the buffer */ if (fault->pplaincb != NULL && !fault->pplaincb(fault, &fault->pplainhdr, (unsigned char *)fault->pplainio.buf, fault->pplainio.buf_len, fault->pplaincbarg)) return 0; *hdrout = &fault->pplainhdr; *iovecout = &fault->pplainio; *numout = 1; return 1; } static void packet_plain_finish(void *arg) { QTEST_FAULT *fault = arg; /* Cast below is safe because we allocated the buffer */ OPENSSL_free((unsigned char *)fault->pplainio.buf); fault->pplainio.buf_len = 0; fault->pplainbuf_alloc = 0; fault->pplainio.buf = NULL; } int qtest_fault_set_packet_plain_listener(QTEST_FAULT *fault, qtest_fault_on_packet_plain_cb pplaincb, void *pplaincbarg) { fault->pplaincb = pplaincb; fault->pplaincbarg = pplaincbarg; return ossl_quic_tserver_set_plain_packet_mutator(fault->qtserv, packet_plain_mutate, packet_plain_finish, fault); } /* To be called from a packet_plain_listener callback */ int qtest_fault_resize_plain_packet(QTEST_FAULT *fault, size_t newlen) { unsigned char *buf; size_t oldlen = fault->pplainio.buf_len; /* * Alloc'd size should always be non-zero, so if this fails we've been * incorrectly called */ if (fault->pplainbuf_alloc == 0) return 0; if (newlen > fault->pplainbuf_alloc) { /* This exceeds our growth allowance. Fail */ return 0; } /* Cast below is safe because we allocated the buffer */ buf = (unsigned char *)fault->pplainio.buf; if (newlen > oldlen) { /* Extend packet with 0 bytes */ memset(buf + oldlen, 0, newlen - oldlen); } /* else we're truncating or staying the same */ fault->pplainio.buf_len = newlen; fault->pplainhdr.len = newlen; return 1; } /* * Prepend frame data into a packet. To be called from a packet_plain_listener * callback */ int qtest_fault_prepend_frame(QTEST_FAULT *fault, const unsigned char *frame, size_t frame_len) { unsigned char *buf; size_t old_len; /* * Alloc'd size should always be non-zero, so if this fails we've been * incorrectly called */ if (fault->pplainbuf_alloc == 0) return 0; /* Cast below is safe because we allocated the buffer */ buf = (unsigned char *)fault->pplainio.buf; old_len = fault->pplainio.buf_len; /* Extend the size of the packet by the size of the new frame */ if (!TEST_true(qtest_fault_resize_plain_packet(fault, old_len + frame_len))) return 0; memmove(buf + frame_len, buf, old_len); memcpy(buf, frame, frame_len); return 1; } static int handshake_mutate(const unsigned char *msgin, size_t msginlen, unsigned char **msgout, size_t *msgoutlen, void *arg) { QTEST_FAULT *fault = arg; unsigned char *buf; unsigned long payloadlen; unsigned int msgtype; PACKET pkt; buf = OPENSSL_malloc(msginlen + GROWTH_ALLOWANCE); if (buf == NULL) return 0; fault->handbuf = buf; fault->handbuflen = msginlen; fault->handbufalloc = msginlen + GROWTH_ALLOWANCE; memcpy(buf, msgin, msginlen); if (!PACKET_buf_init(&pkt, buf, msginlen) || !PACKET_get_1(&pkt, &msgtype) || !PACKET_get_net_3(&pkt, &payloadlen) || PACKET_remaining(&pkt) != payloadlen) return 0; /* Parse specific message types */ switch (msgtype) { case SSL3_MT_ENCRYPTED_EXTENSIONS: { QTEST_ENCRYPTED_EXTENSIONS ee; if (fault->encextcb == NULL) break; /* * The EncryptedExtensions message is very simple. It just has an * extensions block in it and nothing else. */ ee.extensions = (unsigned char *)PACKET_data(&pkt); ee.extensionslen = payloadlen; if (!fault->encextcb(fault, &ee, payloadlen, fault->encextcbarg)) return 0; } default: /* No specific handlers for these message types yet */ break; } if (fault->handshakecb != NULL && !fault->handshakecb(fault, buf, fault->handbuflen, fault->handshakecbarg)) return 0; *msgout = buf; *msgoutlen = fault->handbuflen; return 1; } static void handshake_finish(void *arg) { QTEST_FAULT *fault = arg; OPENSSL_free(fault->handbuf); fault->handbuf = NULL; } int qtest_fault_set_handshake_listener(QTEST_FAULT *fault, qtest_fault_on_handshake_cb handshakecb, void *handshakecbarg) { fault->handshakecb = handshakecb; fault->handshakecbarg = handshakecbarg; return ossl_quic_tserver_set_handshake_mutator(fault->qtserv, handshake_mutate, handshake_finish, fault); } int qtest_fault_set_hand_enc_ext_listener(QTEST_FAULT *fault, qtest_fault_on_enc_ext_cb encextcb, void *encextcbarg) { fault->encextcb = encextcb; fault->encextcbarg = encextcbarg; return ossl_quic_tserver_set_handshake_mutator(fault->qtserv, handshake_mutate, handshake_finish, fault); } /* To be called from a handshake_listener callback */ int qtest_fault_resize_handshake(QTEST_FAULT *fault, size_t newlen) { unsigned char *buf; size_t oldlen = fault->handbuflen; /* * Alloc'd size should always be non-zero, so if this fails we've been * incorrectly called */ if (fault->handbufalloc == 0) return 0; if (newlen > fault->handbufalloc) { /* This exceeds our growth allowance. Fail */ return 0; } buf = (unsigned char *)fault->handbuf; if (newlen > oldlen) { /* Extend packet with 0 bytes */ memset(buf + oldlen, 0, newlen - oldlen); } /* else we're truncating or staying the same */ fault->handbuflen = newlen; return 1; } /* To be called from message specific listener callbacks */ int qtest_fault_resize_message(QTEST_FAULT *fault, size_t newlen) { /* First resize the underlying message */ if (!qtest_fault_resize_handshake(fault, newlen + SSL3_HM_HEADER_LENGTH)) return 0; /* Fixup the handshake message header */ fault->handbuf[1] = (unsigned char)((newlen >> 16) & 0xff); fault->handbuf[2] = (unsigned char)((newlen >> 8) & 0xff); fault->handbuf[3] = (unsigned char)((newlen ) & 0xff); return 1; } int qtest_fault_delete_extension(QTEST_FAULT *fault, unsigned int exttype, unsigned char *ext, size_t *extlen, BUF_MEM *old_ext) { PACKET pkt, sub, subext; WPACKET old_ext_wpkt; unsigned int type; const unsigned char *start, *end; size_t newlen, w; size_t msglen = fault->handbuflen; if (!PACKET_buf_init(&pkt, ext, *extlen)) return 0; /* Extension block starts with 2 bytes for extension block length */ if (!PACKET_as_length_prefixed_2(&pkt, &sub)) return 0; do { start = PACKET_data(&sub); if (!PACKET_get_net_2(&sub, &type) || !PACKET_get_length_prefixed_2(&sub, &subext)) return 0; } while (type != exttype); /* Found it */ end = PACKET_data(&sub); if (old_ext != NULL) { if (!WPACKET_init(&old_ext_wpkt, old_ext)) return 0; if (!WPACKET_memcpy(&old_ext_wpkt, PACKET_data(&subext), PACKET_remaining(&subext)) || !WPACKET_get_total_written(&old_ext_wpkt, &w)) { WPACKET_cleanup(&old_ext_wpkt); return 0; } WPACKET_finish(&old_ext_wpkt); old_ext->length = w; } /* * If we're not the last extension we need to move the rest earlier. The * cast below is safe because we own the underlying buffer and we're no * longer making PACKET calls. */ if (end < ext + *extlen) memmove((unsigned char *)start, end, end - start); /* * Calculate new extensions payload length = * Original length * - 2 extension block length bytes * - length of removed extension */ newlen = *extlen - 2 - (end - start); /* Fixup the length bytes for the extension block */ ext[0] = (unsigned char)((newlen >> 8) & 0xff); ext[1] = (unsigned char)((newlen ) & 0xff); /* * Length of the whole extension block is the new payload length plus the * 2 bytes for the length */ *extlen = newlen + 2; /* We can now resize the message */ if ((size_t)(end - start) + SSL3_HM_HEADER_LENGTH > msglen) return 0; /* Should not happen */ msglen -= (end - start) + SSL3_HM_HEADER_LENGTH; if (!qtest_fault_resize_message(fault, msglen)) return 0; return 1; } #define BIO_TYPE_CIPHER_PACKET_FILTER (0x80 | BIO_TYPE_FILTER) static BIO_METHOD *pcipherbiometh = NULL; # define BIO_MSG_N(array, stride, n) (*(BIO_MSG *)((char *)(array) + (n)*(stride))) static int pcipher_sendmmsg(BIO *b, BIO_MSG *msg, size_t stride, size_t num_msg, uint64_t flags, size_t *num_processed) { QTEST_FAULT *fault; BIO *next = BIO_next(b); ossl_ssize_t ret = 0; size_t i = 0, tmpnump; QUIC_PKT_HDR hdr; PACKET pkt; unsigned char *tmpdata; if (next == NULL) return 0; fault = BIO_get_data(b); if (fault == NULL || (fault->pciphercb == NULL && fault->datagramcb == NULL)) return BIO_sendmmsg(next, msg, stride, num_msg, flags, num_processed); if (num_msg == 0) { *num_processed = 0; return 1; } for (i = 0; i < num_msg; ++i) { fault->msg = BIO_MSG_N(msg, stride, i); /* Take a copy of the data so that callbacks can modify it */ tmpdata = OPENSSL_malloc(fault->msg.data_len + GROWTH_ALLOWANCE); if (tmpdata == NULL) return 0; memcpy(tmpdata, fault->msg.data, fault->msg.data_len); fault->msg.data = tmpdata; fault->msgalloc = fault->msg.data_len + GROWTH_ALLOWANCE; if (fault->pciphercb != NULL) { if (!PACKET_buf_init(&pkt, fault->msg.data, fault->msg.data_len)) return 0; do { if (!ossl_quic_wire_decode_pkt_hdr(&pkt, /* * TODO(QUIC SERVER): * Needs to be set to the actual short header CID length * when testing the server implementation. */ 0, 1, 0, &hdr, NULL)) goto out; /* * hdr.data is const - but its our buffer so casting away the * const is safe */ if (!fault->pciphercb(fault, &hdr, (unsigned char *)hdr.data, hdr.len, fault->pciphercbarg)) goto out; /* * At the moment modifications to hdr by the callback * are ignored. We might need to rewrite the QUIC header to * enable tests to change this. We also don't yet have a * mechanism for the callback to change the encrypted data * length. It's not clear if that's needed or not. */ } while (PACKET_remaining(&pkt) > 0); } if (fault->datagramcb != NULL && !fault->datagramcb(fault, &fault->msg, stride, fault->datagramcbarg)) goto out; if (!BIO_sendmmsg(next, &fault->msg, stride, 1, flags, &tmpnump)) { *num_processed = i; goto out; } OPENSSL_free(fault->msg.data); fault->msg.data = NULL; fault->msgalloc = 0; } *num_processed = i; out: ret = i > 0; OPENSSL_free(fault->msg.data); fault->msg.data = NULL; return ret; } static long pcipher_ctrl(BIO *b, int cmd, long larg, void *parg) { BIO *next = BIO_next(b); if (next == NULL) return -1; return BIO_ctrl(next, cmd, larg, parg); } BIO_METHOD *qtest_get_bio_method(void) { BIO_METHOD *tmp; if (pcipherbiometh != NULL) return pcipherbiometh; tmp = BIO_meth_new(BIO_TYPE_CIPHER_PACKET_FILTER, "Cipher Packet Filter"); if (!TEST_ptr(tmp)) return NULL; if (!TEST_true(BIO_meth_set_sendmmsg(tmp, pcipher_sendmmsg)) || !TEST_true(BIO_meth_set_ctrl(tmp, pcipher_ctrl))) goto err; pcipherbiometh = tmp; tmp = NULL; err: BIO_meth_free(tmp); return pcipherbiometh; } int qtest_fault_set_packet_cipher_listener(QTEST_FAULT *fault, qtest_fault_on_packet_cipher_cb pciphercb, void *pciphercbarg) { fault->pciphercb = pciphercb; fault->pciphercbarg = pciphercbarg; return 1; } int qtest_fault_set_datagram_listener(QTEST_FAULT *fault, qtest_fault_on_datagram_cb datagramcb, void *datagramcbarg) { fault->datagramcb = datagramcb; fault->datagramcbarg = datagramcbarg; return 1; } /* To be called from a datagram_listener callback */ int qtest_fault_resize_datagram(QTEST_FAULT *fault, size_t newlen) { if (newlen > fault->msgalloc) return 0; if (newlen > fault->msg.data_len) memset((unsigned char *)fault->msg.data + fault->msg.data_len, 0, newlen - fault->msg.data_len); fault->msg.data_len = newlen; return 1; } int bio_msg_copy(BIO_MSG *dst, BIO_MSG *src) { /* * Note it is assumed that the originally allocated data sizes for dst and * src are the same */ memcpy(dst->data, src->data, src->data_len); dst->data_len = src->data_len; dst->flags = src->flags; if (dst->local != NULL) { if (src->local != NULL) { if (!TEST_true(BIO_ADDR_copy(dst->local, src->local))) return 0; } else { BIO_ADDR_clear(dst->local); } } if (!TEST_true(BIO_ADDR_copy(dst->peer, src->peer))) return 0; return 1; }
./openssl/test/helpers/ssltestlib.c
/* * Copyright 2016-2023 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <string.h> #include "internal/e_os.h" #include "internal/nelem.h" #include "ssltestlib.h" #include "../testutil.h" #if (!defined(OPENSSL_NO_KTLS) || !defined(OPENSSL_NO_QUIC)) && !defined(OPENSSL_NO_POSIX_IO) && !defined(OPENSSL_NO_SOCK) # define OSSL_USE_SOCKETS 1 # include "internal/sockets.h" # include <openssl/bio.h> #endif static int tls_dump_new(BIO *bi); static int tls_dump_free(BIO *a); static int tls_dump_read(BIO *b, char *out, int outl); static int tls_dump_write(BIO *b, const char *in, int inl); static long tls_dump_ctrl(BIO *b, int cmd, long num, void *ptr); static int tls_dump_gets(BIO *bp, char *buf, int size); static int tls_dump_puts(BIO *bp, const char *str); /* Choose a sufficiently large type likely to be unused for this custom BIO */ #define BIO_TYPE_TLS_DUMP_FILTER (0x80 | BIO_TYPE_FILTER) #define BIO_TYPE_MEMPACKET_TEST 0x81 #define BIO_TYPE_ALWAYS_RETRY 0x82 #define BIO_TYPE_MAYBE_RETRY (0x83 | BIO_TYPE_FILTER) static BIO_METHOD *method_tls_dump = NULL; static BIO_METHOD *meth_mem = NULL; static BIO_METHOD *meth_always_retry = NULL; static BIO_METHOD *meth_maybe_retry = NULL; static int retry_err = -1; /* Note: Not thread safe! */ const BIO_METHOD *bio_f_tls_dump_filter(void) { if (method_tls_dump == NULL) { method_tls_dump = BIO_meth_new(BIO_TYPE_TLS_DUMP_FILTER, "TLS dump filter"); if (method_tls_dump == NULL || !BIO_meth_set_write(method_tls_dump, tls_dump_write) || !BIO_meth_set_read(method_tls_dump, tls_dump_read) || !BIO_meth_set_puts(method_tls_dump, tls_dump_puts) || !BIO_meth_set_gets(method_tls_dump, tls_dump_gets) || !BIO_meth_set_ctrl(method_tls_dump, tls_dump_ctrl) || !BIO_meth_set_create(method_tls_dump, tls_dump_new) || !BIO_meth_set_destroy(method_tls_dump, tls_dump_free)) return NULL; } return method_tls_dump; } void bio_f_tls_dump_filter_free(void) { BIO_meth_free(method_tls_dump); } static int tls_dump_new(BIO *bio) { BIO_set_init(bio, 1); return 1; } static int tls_dump_free(BIO *bio) { BIO_set_init(bio, 0); return 1; } 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); } #define RECORD_CONTENT_TYPE 0 #define RECORD_VERSION_HI 1 #define RECORD_VERSION_LO 2 #define RECORD_EPOCH_HI 3 #define RECORD_EPOCH_LO 4 #define RECORD_SEQUENCE_START 5 #define RECORD_SEQUENCE_END 10 #define RECORD_LEN_HI 11 #define RECORD_LEN_LO 12 #define MSG_TYPE 0 #define MSG_LEN_HI 1 #define MSG_LEN_MID 2 #define MSG_LEN_LO 3 #define MSG_SEQ_HI 4 #define MSG_SEQ_LO 5 #define MSG_FRAG_OFF_HI 6 #define MSG_FRAG_OFF_MID 7 #define MSG_FRAG_OFF_LO 8 #define MSG_FRAG_LEN_HI 9 #define MSG_FRAG_LEN_MID 10 #define MSG_FRAG_LEN_LO 11 static void dump_data(const char *data, int len) { int rem, i, content, reclen, msglen, fragoff, fraglen, epoch; unsigned char *rec; printf("---- START OF PACKET ----\n"); rem = len; rec = (unsigned char *)data; while (rem > 0) { if (rem != len) printf("*\n"); printf("*---- START OF RECORD ----\n"); if (rem < DTLS1_RT_HEADER_LENGTH) { printf("*---- RECORD TRUNCATED ----\n"); break; } content = rec[RECORD_CONTENT_TYPE]; printf("** Record Content-type: %d\n", content); printf("** Record Version: %02x%02x\n", rec[RECORD_VERSION_HI], rec[RECORD_VERSION_LO]); epoch = (rec[RECORD_EPOCH_HI] << 8) | rec[RECORD_EPOCH_LO]; printf("** Record Epoch: %d\n", epoch); printf("** Record Sequence: "); for (i = RECORD_SEQUENCE_START; i <= RECORD_SEQUENCE_END; i++) printf("%02x", rec[i]); reclen = (rec[RECORD_LEN_HI] << 8) | rec[RECORD_LEN_LO]; printf("\n** Record Length: %d\n", reclen); /* Now look at message */ rec += DTLS1_RT_HEADER_LENGTH; rem -= DTLS1_RT_HEADER_LENGTH; if (content == SSL3_RT_HANDSHAKE) { printf("**---- START OF HANDSHAKE MESSAGE FRAGMENT ----\n"); if (epoch > 0) { printf("**---- HANDSHAKE MESSAGE FRAGMENT ENCRYPTED ----\n"); } else if (rem < DTLS1_HM_HEADER_LENGTH || reclen < DTLS1_HM_HEADER_LENGTH) { printf("**---- HANDSHAKE MESSAGE FRAGMENT TRUNCATED ----\n"); } else { printf("*** Message Type: %d\n", rec[MSG_TYPE]); msglen = (rec[MSG_LEN_HI] << 16) | (rec[MSG_LEN_MID] << 8) | rec[MSG_LEN_LO]; printf("*** Message Length: %d\n", msglen); printf("*** Message sequence: %d\n", (rec[MSG_SEQ_HI] << 8) | rec[MSG_SEQ_LO]); fragoff = (rec[MSG_FRAG_OFF_HI] << 16) | (rec[MSG_FRAG_OFF_MID] << 8) | rec[MSG_FRAG_OFF_LO]; printf("*** Message Fragment offset: %d\n", fragoff); fraglen = (rec[MSG_FRAG_LEN_HI] << 16) | (rec[MSG_FRAG_LEN_MID] << 8) | rec[MSG_FRAG_LEN_LO]; printf("*** Message Fragment len: %d\n", fraglen); if (fragoff + fraglen > msglen) printf("***---- HANDSHAKE MESSAGE FRAGMENT INVALID ----\n"); else if (reclen < fraglen) printf("**---- HANDSHAKE MESSAGE FRAGMENT TRUNCATED ----\n"); else printf("**---- END OF HANDSHAKE MESSAGE FRAGMENT ----\n"); } } if (rem < reclen) { printf("*---- RECORD TRUNCATED ----\n"); rem = 0; } else { rec += reclen; rem -= reclen; printf("*---- END OF RECORD ----\n"); } } printf("---- END OF PACKET ----\n\n"); fflush(stdout); } static int tls_dump_read(BIO *bio, char *out, int outl) { int ret; BIO *next = BIO_next(bio); ret = BIO_read(next, out, outl); copy_flags(bio); if (ret > 0) { dump_data(out, ret); } return ret; } static int tls_dump_write(BIO *bio, const char *in, int inl) { int ret; BIO *next = BIO_next(bio); ret = BIO_write(next, in, inl); copy_flags(bio); return ret; } static long tls_dump_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_dump_gets(BIO *bio, char *buf, int size) { /* We don't support this - not needed anyway */ return -1; } static int tls_dump_puts(BIO *bio, const char *str) { return tls_dump_write(bio, str, strlen(str)); } struct mempacket_st { unsigned char *data; int len; unsigned int num; unsigned int type; }; static void mempacket_free(MEMPACKET *pkt) { if (pkt->data != NULL) OPENSSL_free(pkt->data); OPENSSL_free(pkt); } typedef struct mempacket_test_ctx_st { STACK_OF(MEMPACKET) *pkts; uint16_t epoch; unsigned int currrec; unsigned int currpkt; unsigned int lastpkt; unsigned int injected; unsigned int noinject; unsigned int dropepoch; int droprec; int duprec; } MEMPACKET_TEST_CTX; static int mempacket_test_new(BIO *bi); static int mempacket_test_free(BIO *a); static int mempacket_test_read(BIO *b, char *out, int outl); static int mempacket_test_write(BIO *b, const char *in, int inl); static long mempacket_test_ctrl(BIO *b, int cmd, long num, void *ptr); static int mempacket_test_gets(BIO *bp, char *buf, int size); static int mempacket_test_puts(BIO *bp, const char *str); const BIO_METHOD *bio_s_mempacket_test(void) { if (meth_mem == NULL) { if (!TEST_ptr(meth_mem = BIO_meth_new(BIO_TYPE_MEMPACKET_TEST, "Mem Packet Test")) || !TEST_true(BIO_meth_set_write(meth_mem, mempacket_test_write)) || !TEST_true(BIO_meth_set_read(meth_mem, mempacket_test_read)) || !TEST_true(BIO_meth_set_puts(meth_mem, mempacket_test_puts)) || !TEST_true(BIO_meth_set_gets(meth_mem, mempacket_test_gets)) || !TEST_true(BIO_meth_set_ctrl(meth_mem, mempacket_test_ctrl)) || !TEST_true(BIO_meth_set_create(meth_mem, mempacket_test_new)) || !TEST_true(BIO_meth_set_destroy(meth_mem, mempacket_test_free))) return NULL; } return meth_mem; } void bio_s_mempacket_test_free(void) { BIO_meth_free(meth_mem); } static int mempacket_test_new(BIO *bio) { MEMPACKET_TEST_CTX *ctx; if (!TEST_ptr(ctx = OPENSSL_zalloc(sizeof(*ctx)))) return 0; if (!TEST_ptr(ctx->pkts = sk_MEMPACKET_new_null())) { OPENSSL_free(ctx); return 0; } ctx->dropepoch = 0; ctx->droprec = -1; BIO_set_init(bio, 1); BIO_set_data(bio, ctx); return 1; } static int mempacket_test_free(BIO *bio) { MEMPACKET_TEST_CTX *ctx = BIO_get_data(bio); sk_MEMPACKET_pop_free(ctx->pkts, mempacket_free); OPENSSL_free(ctx); BIO_set_data(bio, NULL); BIO_set_init(bio, 0); return 1; } /* Record Header values */ #define EPOCH_HI 3 #define EPOCH_LO 4 #define RECORD_SEQUENCE 10 #define RECORD_LEN_HI 11 #define RECORD_LEN_LO 12 #define STANDARD_PACKET 0 static int mempacket_test_read(BIO *bio, char *out, int outl) { MEMPACKET_TEST_CTX *ctx = BIO_get_data(bio); MEMPACKET *thispkt; unsigned char *rec; int rem; unsigned int seq, offset, len, epoch; BIO_clear_retry_flags(bio); if ((thispkt = sk_MEMPACKET_value(ctx->pkts, 0)) == NULL || thispkt->num != ctx->currpkt) { /* Probably run out of data */ BIO_set_retry_read(bio); return -1; } (void)sk_MEMPACKET_shift(ctx->pkts); ctx->currpkt++; if (outl > thispkt->len) outl = thispkt->len; if (thispkt->type != INJECT_PACKET_IGNORE_REC_SEQ && (ctx->injected || ctx->droprec >= 0)) { /* * Overwrite the record sequence number. We strictly number them in * the order received. Since we are actually a reliable transport * we know that there won't be any re-ordering. We overwrite to deal * with any packets that have been injected */ for (rem = thispkt->len, rec = thispkt->data; rem > 0; rem -= len) { if (rem < DTLS1_RT_HEADER_LENGTH) return -1; epoch = (rec[EPOCH_HI] << 8) | rec[EPOCH_LO]; if (epoch != ctx->epoch) { ctx->epoch = epoch; ctx->currrec = 0; } seq = ctx->currrec; offset = 0; do { rec[RECORD_SEQUENCE - offset] = seq & 0xFF; seq >>= 8; offset++; } while (seq > 0); len = ((rec[RECORD_LEN_HI] << 8) | rec[RECORD_LEN_LO]) + DTLS1_RT_HEADER_LENGTH; if (rem < (int)len) return -1; if (ctx->droprec == (int)ctx->currrec && ctx->dropepoch == epoch) { if (rem > (int)len) memmove(rec, rec + len, rem - len); outl -= len; ctx->droprec = -1; if (outl == 0) BIO_set_retry_read(bio); } else { rec += len; } ctx->currrec++; } } memcpy(out, thispkt->data, outl); mempacket_free(thispkt); return outl; } /* * Look for records from different epochs in the last datagram and swap them * around */ int mempacket_swap_epoch(BIO *bio) { MEMPACKET_TEST_CTX *ctx = BIO_get_data(bio); MEMPACKET *thispkt; int rem, len, prevlen = 0, pktnum; unsigned char *rec, *prevrec = NULL, *tmp; unsigned int epoch; int numpkts = sk_MEMPACKET_num(ctx->pkts); if (numpkts <= 0) return 0; /* * If there are multiple packets we only look in the last one. This should * always be the one where any epoch change occurs. */ thispkt = sk_MEMPACKET_value(ctx->pkts, numpkts - 1); if (thispkt == NULL) return 0; for (rem = thispkt->len, rec = thispkt->data; rem > 0; rem -= len, rec += len) { if (rem < DTLS1_RT_HEADER_LENGTH) return 0; epoch = (rec[EPOCH_HI] << 8) | rec[EPOCH_LO]; len = ((rec[RECORD_LEN_HI] << 8) | rec[RECORD_LEN_LO]) + DTLS1_RT_HEADER_LENGTH; if (rem < len) return 0; /* Assumes the epoch change does not happen on the first record */ if (epoch != ctx->epoch) { if (prevrec == NULL) return 0; /* * We found 2 records with different epochs. Take a copy of the * earlier record */ tmp = OPENSSL_malloc(prevlen); if (tmp == NULL) return 0; memcpy(tmp, prevrec, prevlen); /* * Move everything from this record onwards, including any trailing * records, and overwrite the earlier record */ memmove(prevrec, rec, rem); thispkt->len -= prevlen; pktnum = thispkt->num; /* * Create a new packet for the earlier record that we took out and * add it to the end of the packet list. */ thispkt = OPENSSL_malloc(sizeof(*thispkt)); if (thispkt == NULL) { OPENSSL_free(tmp); return 0; } thispkt->type = INJECT_PACKET; thispkt->data = tmp; thispkt->len = prevlen; thispkt->num = pktnum + 1; if (sk_MEMPACKET_insert(ctx->pkts, thispkt, numpkts) <= 0) { OPENSSL_free(tmp); OPENSSL_free(thispkt); return 0; } return 1; } prevrec = rec; prevlen = len; } return 0; } /* Move packet from position s to position d in the list (d < s) */ int mempacket_move_packet(BIO *bio, int d, int s) { MEMPACKET_TEST_CTX *ctx = BIO_get_data(bio); MEMPACKET *thispkt; int numpkts = sk_MEMPACKET_num(ctx->pkts); int i; if (d >= s) return 0; /* We need at least s + 1 packets to be able to swap them */ if (numpkts <= s) return 0; /* Get the packet at position s */ thispkt = sk_MEMPACKET_value(ctx->pkts, s); if (thispkt == NULL) return 0; /* Remove and re-add it */ if (sk_MEMPACKET_delete(ctx->pkts, s) != thispkt) return 0; thispkt->num -= (s - d); if (sk_MEMPACKET_insert(ctx->pkts, thispkt, d) <= 0) return 0; /* Increment the packet numbers for moved packets */ for (i = d + 1; i <= s; i++) { thispkt = sk_MEMPACKET_value(ctx->pkts, i); thispkt->num++; } return 1; } int mempacket_test_inject(BIO *bio, const char *in, int inl, int pktnum, int type) { MEMPACKET_TEST_CTX *ctx = BIO_get_data(bio); MEMPACKET *thispkt = NULL, *looppkt, *nextpkt, *allpkts[3]; int i, duprec; const unsigned char *inu = (const unsigned char *)in; size_t len = ((inu[RECORD_LEN_HI] << 8) | inu[RECORD_LEN_LO]) + DTLS1_RT_HEADER_LENGTH; if (ctx == NULL) return -1; if ((size_t)inl < len) return -1; if ((size_t)inl == len) duprec = 0; else duprec = ctx->duprec > 0; /* We don't support arbitrary injection when duplicating records */ if (duprec && pktnum != -1) return -1; /* We only allow injection before we've started writing any data */ if (pktnum >= 0) { if (ctx->noinject) return -1; ctx->injected = 1; } else { ctx->noinject = 1; } for (i = 0; i < (duprec ? 3 : 1); i++) { if (!TEST_ptr(allpkts[i] = OPENSSL_malloc(sizeof(*thispkt)))) goto err; thispkt = allpkts[i]; if (!TEST_ptr(thispkt->data = OPENSSL_malloc(inl))) goto err; /* * If we are duplicating the packet, we duplicate it three times. The * first two times we drop the first record if there are more than one. * In this way we know that libssl will not be able to make progress * until it receives the last packet, and hence will be forced to * buffer these records. */ if (duprec && i != 2) { memcpy(thispkt->data, in + len, inl - len); thispkt->len = inl - len; } else { memcpy(thispkt->data, in, inl); thispkt->len = inl; } thispkt->num = (pktnum >= 0) ? (unsigned int)pktnum : ctx->lastpkt + i; thispkt->type = type; } for (i = 0; i < sk_MEMPACKET_num(ctx->pkts); i++) { if (!TEST_ptr(looppkt = sk_MEMPACKET_value(ctx->pkts, i))) goto err; /* Check if we found the right place to insert this packet */ if (looppkt->num > thispkt->num) { if (sk_MEMPACKET_insert(ctx->pkts, thispkt, i) == 0) goto err; /* If we're doing up front injection then we're done */ if (pktnum >= 0) return inl; /* * We need to do some accounting on lastpkt. We increment it first, * but it might now equal the value of injected packets, so we need * to skip over those */ ctx->lastpkt++; do { i++; nextpkt = sk_MEMPACKET_value(ctx->pkts, i); if (nextpkt != NULL && nextpkt->num == ctx->lastpkt) ctx->lastpkt++; else return inl; } while(1); } else if (looppkt->num == thispkt->num) { if (!ctx->noinject) { /* We injected two packets with the same packet number! */ goto err; } ctx->lastpkt++; thispkt->num++; } } /* * We didn't find any packets with a packet number equal to or greater than * this one, so we just add it onto the end */ for (i = 0; i < (duprec ? 3 : 1); i++) { thispkt = allpkts[i]; if (!sk_MEMPACKET_push(ctx->pkts, thispkt)) goto err; if (pktnum < 0) ctx->lastpkt++; } return inl; err: for (i = 0; i < (ctx->duprec > 0 ? 3 : 1); i++) mempacket_free(allpkts[i]); return -1; } static int mempacket_test_write(BIO *bio, const char *in, int inl) { return mempacket_test_inject(bio, in, inl, -1, STANDARD_PACKET); } static long mempacket_test_ctrl(BIO *bio, int cmd, long num, void *ptr) { long ret = 1; MEMPACKET_TEST_CTX *ctx = BIO_get_data(bio); MEMPACKET *thispkt; switch (cmd) { case BIO_CTRL_EOF: ret = (long)(sk_MEMPACKET_num(ctx->pkts) == 0); break; case BIO_CTRL_GET_CLOSE: ret = BIO_get_shutdown(bio); break; case BIO_CTRL_SET_CLOSE: BIO_set_shutdown(bio, (int)num); break; case BIO_CTRL_WPENDING: ret = 0L; break; case BIO_CTRL_PENDING: thispkt = sk_MEMPACKET_value(ctx->pkts, 0); if (thispkt == NULL) ret = 0; else ret = thispkt->len; break; case BIO_CTRL_FLUSH: ret = 1; break; case MEMPACKET_CTRL_SET_DROP_EPOCH: ctx->dropepoch = (unsigned int)num; break; case MEMPACKET_CTRL_SET_DROP_REC: ctx->droprec = (int)num; break; case MEMPACKET_CTRL_GET_DROP_REC: ret = ctx->droprec; break; case MEMPACKET_CTRL_SET_DUPLICATE_REC: ctx->duprec = (int)num; break; case BIO_CTRL_RESET: case BIO_CTRL_DUP: case BIO_CTRL_PUSH: case BIO_CTRL_POP: default: ret = 0; break; } return ret; } static int mempacket_test_gets(BIO *bio, char *buf, int size) { /* We don't support this - not needed anyway */ return -1; } static int mempacket_test_puts(BIO *bio, const char *str) { return mempacket_test_write(bio, str, strlen(str)); } static int always_retry_new(BIO *bi); static int always_retry_free(BIO *a); static int always_retry_read(BIO *b, char *out, int outl); static int always_retry_write(BIO *b, const char *in, int inl); static long always_retry_ctrl(BIO *b, int cmd, long num, void *ptr); static int always_retry_gets(BIO *bp, char *buf, int size); static int always_retry_puts(BIO *bp, const char *str); const BIO_METHOD *bio_s_always_retry(void) { if (meth_always_retry == NULL) { if (!TEST_ptr(meth_always_retry = BIO_meth_new(BIO_TYPE_ALWAYS_RETRY, "Always Retry")) || !TEST_true(BIO_meth_set_write(meth_always_retry, always_retry_write)) || !TEST_true(BIO_meth_set_read(meth_always_retry, always_retry_read)) || !TEST_true(BIO_meth_set_puts(meth_always_retry, always_retry_puts)) || !TEST_true(BIO_meth_set_gets(meth_always_retry, always_retry_gets)) || !TEST_true(BIO_meth_set_ctrl(meth_always_retry, always_retry_ctrl)) || !TEST_true(BIO_meth_set_create(meth_always_retry, always_retry_new)) || !TEST_true(BIO_meth_set_destroy(meth_always_retry, always_retry_free))) return NULL; } return meth_always_retry; } void bio_s_always_retry_free(void) { BIO_meth_free(meth_always_retry); } static int always_retry_new(BIO *bio) { BIO_set_init(bio, 1); return 1; } static int always_retry_free(BIO *bio) { BIO_set_data(bio, NULL); BIO_set_init(bio, 0); return 1; } void set_always_retry_err_val(int err) { retry_err = err; } static int always_retry_read(BIO *bio, char *out, int outl) { BIO_set_retry_read(bio); return retry_err; } static int always_retry_write(BIO *bio, const char *in, int inl) { BIO_set_retry_write(bio); return retry_err; } static long always_retry_ctrl(BIO *bio, int cmd, long num, void *ptr) { long ret = 1; switch (cmd) { case BIO_CTRL_FLUSH: BIO_set_retry_write(bio); /* fall through */ case BIO_CTRL_EOF: case BIO_CTRL_RESET: case BIO_CTRL_DUP: case BIO_CTRL_PUSH: case BIO_CTRL_POP: default: ret = 0; break; } return ret; } static int always_retry_gets(BIO *bio, char *buf, int size) { BIO_set_retry_read(bio); return retry_err; } static int always_retry_puts(BIO *bio, const char *str) { BIO_set_retry_write(bio); return retry_err; } struct maybe_retry_data_st { unsigned int retrycnt; }; static int maybe_retry_new(BIO *bi); static int maybe_retry_free(BIO *a); static int maybe_retry_write(BIO *b, const char *in, int inl); static long maybe_retry_ctrl(BIO *b, int cmd, long num, void *ptr); const BIO_METHOD *bio_s_maybe_retry(void) { if (meth_maybe_retry == NULL) { if (!TEST_ptr(meth_maybe_retry = BIO_meth_new(BIO_TYPE_MAYBE_RETRY, "Maybe Retry")) || !TEST_true(BIO_meth_set_write(meth_maybe_retry, maybe_retry_write)) || !TEST_true(BIO_meth_set_ctrl(meth_maybe_retry, maybe_retry_ctrl)) || !TEST_true(BIO_meth_set_create(meth_maybe_retry, maybe_retry_new)) || !TEST_true(BIO_meth_set_destroy(meth_maybe_retry, maybe_retry_free))) return NULL; } return meth_maybe_retry; } void bio_s_maybe_retry_free(void) { BIO_meth_free(meth_maybe_retry); } static int maybe_retry_new(BIO *bio) { struct maybe_retry_data_st *data = OPENSSL_zalloc(sizeof(*data)); if (data == NULL) return 0; BIO_set_data(bio, data); BIO_set_init(bio, 1); return 1; } static int maybe_retry_free(BIO *bio) { struct maybe_retry_data_st *data = BIO_get_data(bio); OPENSSL_free(data); BIO_set_data(bio, NULL); BIO_set_init(bio, 0); return 1; } static int maybe_retry_write(BIO *bio, const char *in, int inl) { struct maybe_retry_data_st *data = BIO_get_data(bio); if (data == NULL) return -1; if (data->retrycnt == 0) { BIO_set_retry_write(bio); return -1; } data->retrycnt--; return BIO_write(BIO_next(bio), in, inl); } static long maybe_retry_ctrl(BIO *bio, int cmd, long num, void *ptr) { struct maybe_retry_data_st *data = BIO_get_data(bio); if (data == NULL) return 0; switch (cmd) { case MAYBE_RETRY_CTRL_SET_RETRY_AFTER_CNT: data->retrycnt = num; return 1; case BIO_CTRL_FLUSH: if (data->retrycnt == 0) { BIO_set_retry_write(bio); return -1; } data->retrycnt--; /* fall through */ default: return BIO_ctrl(BIO_next(bio), cmd, num, ptr); } } int create_ssl_ctx_pair(OSSL_LIB_CTX *libctx, const SSL_METHOD *sm, const SSL_METHOD *cm, int min_proto_version, int max_proto_version, SSL_CTX **sctx, SSL_CTX **cctx, char *certfile, char *privkeyfile) { SSL_CTX *serverctx = NULL; SSL_CTX *clientctx = NULL; if (sctx != NULL) { if (*sctx != NULL) serverctx = *sctx; else if (!TEST_ptr(serverctx = SSL_CTX_new_ex(libctx, NULL, sm)) || !TEST_true(SSL_CTX_set_options(serverctx, SSL_OP_ALLOW_CLIENT_RENEGOTIATION))) goto err; } if (cctx != NULL) { if (*cctx != NULL) clientctx = *cctx; else if (!TEST_ptr(clientctx = SSL_CTX_new_ex(libctx, NULL, cm))) goto err; } #if !defined(OPENSSL_NO_TLS1_3) \ && defined(OPENSSL_NO_EC) \ && defined(OPENSSL_NO_DH) /* * There are no usable built-in TLSv1.3 groups if ec and dh are both * disabled */ if (max_proto_version == 0 && (sm == TLS_server_method() || cm == TLS_client_method())) max_proto_version = TLS1_2_VERSION; #endif if (serverctx != NULL && ((min_proto_version > 0 && !TEST_true(SSL_CTX_set_min_proto_version(serverctx, min_proto_version))) || (max_proto_version > 0 && !TEST_true(SSL_CTX_set_max_proto_version(serverctx, max_proto_version))))) goto err; if (clientctx != NULL && ((min_proto_version > 0 && !TEST_true(SSL_CTX_set_min_proto_version(clientctx, min_proto_version))) || (max_proto_version > 0 && !TEST_true(SSL_CTX_set_max_proto_version(clientctx, max_proto_version))))) goto err; if (serverctx != NULL && certfile != NULL && privkeyfile != NULL) { if (!TEST_int_eq(SSL_CTX_use_certificate_file(serverctx, certfile, SSL_FILETYPE_PEM), 1) || !TEST_int_eq(SSL_CTX_use_PrivateKey_file(serverctx, privkeyfile, SSL_FILETYPE_PEM), 1) || !TEST_int_eq(SSL_CTX_check_private_key(serverctx), 1)) goto err; } if (sctx != NULL) *sctx = serverctx; if (cctx != NULL) *cctx = clientctx; return 1; err: if (sctx != NULL && *sctx == NULL) SSL_CTX_free(serverctx); if (cctx != NULL && *cctx == NULL) SSL_CTX_free(clientctx); return 0; } #define MAXLOOPS 1000000 #if defined(OSSL_USE_SOCKETS) int wait_until_sock_readable(int sock) { fd_set readfds; struct timeval timeout; int width; width = sock + 1; FD_ZERO(&readfds); openssl_fdset(sock, &readfds); timeout.tv_sec = 10; /* give up after 10 seconds */ timeout.tv_usec = 0; select(width, &readfds, NULL, NULL, &timeout); return FD_ISSET(sock, &readfds); } int create_test_sockets(int *cfdp, int *sfdp, int socktype, BIO_ADDR *saddr) { struct sockaddr_in sin; const char *host = "127.0.0.1"; int cfd_connected = 0, ret = 0; socklen_t slen = sizeof(sin); int afd = -1, cfd = -1, sfd = -1; memset ((char *) &sin, 0, sizeof(sin)); sin.sin_family = AF_INET; sin.sin_addr.s_addr = inet_addr(host); afd = BIO_socket(AF_INET, socktype, socktype == SOCK_STREAM ? IPPROTO_TCP : IPPROTO_UDP, 0); if (afd == INVALID_SOCKET) return 0; if (bind(afd, (struct sockaddr*)&sin, sizeof(sin)) < 0) goto out; if (getsockname(afd, (struct sockaddr*)&sin, &slen) < 0) goto out; if (saddr != NULL && !BIO_ADDR_rawmake(saddr, sin.sin_family, &sin.sin_addr, sizeof(sin.sin_addr), sin.sin_port)) goto out; if (socktype == SOCK_STREAM && listen(afd, 1) < 0) goto out; cfd = BIO_socket(AF_INET, socktype, socktype == SOCK_STREAM ? IPPROTO_TCP : IPPROTO_UDP, 0); if (cfd == INVALID_SOCKET) goto out; if (!BIO_socket_nbio(afd, 1)) goto out; /* * If a DGRAM socket then we don't call "accept" or "connect" - so act like * we already called them. */ if (socktype == SOCK_DGRAM) { cfd_connected = 1; sfd = afd; afd = -1; } while (sfd == -1 || !cfd_connected) { sfd = accept(afd, NULL, 0); if (sfd == -1 && errno != EAGAIN) goto out; if (!cfd_connected && connect(cfd, (struct sockaddr*)&sin, sizeof(sin)) < 0) goto out; else cfd_connected = 1; } if (!BIO_socket_nbio(cfd, 1) || !BIO_socket_nbio(sfd, 1)) goto out; ret = 1; *cfdp = cfd; *sfdp = sfd; goto success; out: if (cfd != -1) close(cfd); if (sfd != -1) close(sfd); success: if (afd != -1) close(afd); return ret; } int create_ssl_objects2(SSL_CTX *serverctx, SSL_CTX *clientctx, SSL **sssl, SSL **cssl, int sfd, int cfd) { SSL *serverssl = NULL, *clientssl = NULL; BIO *s_to_c_bio = NULL, *c_to_s_bio = NULL; BIO_POLL_DESCRIPTOR rdesc = {0}, wdesc = {0}; if (*sssl != NULL) serverssl = *sssl; else if (!TEST_ptr(serverssl = SSL_new(serverctx))) goto error; if (*cssl != NULL) clientssl = *cssl; else if (!TEST_ptr(clientssl = SSL_new(clientctx))) goto error; if (!TEST_ptr(s_to_c_bio = BIO_new_socket(sfd, BIO_NOCLOSE)) || !TEST_ptr(c_to_s_bio = BIO_new_socket(cfd, BIO_NOCLOSE))) goto error; if (!TEST_false(SSL_get_rpoll_descriptor(clientssl, &rdesc) || !TEST_false(SSL_get_wpoll_descriptor(clientssl, &wdesc)))) goto error; SSL_set_bio(clientssl, c_to_s_bio, c_to_s_bio); SSL_set_bio(serverssl, s_to_c_bio, s_to_c_bio); if (!TEST_true(SSL_get_rpoll_descriptor(clientssl, &rdesc)) || !TEST_true(SSL_get_wpoll_descriptor(clientssl, &wdesc)) || !TEST_int_eq(rdesc.type, BIO_POLL_DESCRIPTOR_TYPE_SOCK_FD) || !TEST_int_eq(wdesc.type, BIO_POLL_DESCRIPTOR_TYPE_SOCK_FD) || !TEST_int_eq(rdesc.value.fd, cfd) || !TEST_int_eq(wdesc.value.fd, cfd)) goto error; if (!TEST_true(SSL_get_rpoll_descriptor(serverssl, &rdesc)) || !TEST_true(SSL_get_wpoll_descriptor(serverssl, &wdesc)) || !TEST_int_eq(rdesc.type, BIO_POLL_DESCRIPTOR_TYPE_SOCK_FD) || !TEST_int_eq(wdesc.type, BIO_POLL_DESCRIPTOR_TYPE_SOCK_FD) || !TEST_int_eq(rdesc.value.fd, sfd) || !TEST_int_eq(wdesc.value.fd, sfd)) goto error; *sssl = serverssl; *cssl = clientssl; return 1; error: SSL_free(serverssl); SSL_free(clientssl); BIO_free(s_to_c_bio); BIO_free(c_to_s_bio); return 0; } #else int wait_until_sock_readable(int sock) { return 0; } #endif /* defined(OSSL_USE_SOCKETS) */ /* * NOTE: Transfers control of the BIOs - this function will free them on error */ int create_ssl_objects(SSL_CTX *serverctx, SSL_CTX *clientctx, SSL **sssl, SSL **cssl, BIO *s_to_c_fbio, BIO *c_to_s_fbio) { SSL *serverssl = NULL, *clientssl = NULL; BIO *s_to_c_bio = NULL, *c_to_s_bio = NULL; if (*sssl != NULL) serverssl = *sssl; else if (!TEST_ptr(serverssl = SSL_new(serverctx))) goto error; if (*cssl != NULL) clientssl = *cssl; else if (!TEST_ptr(clientssl = SSL_new(clientctx))) goto error; if (SSL_is_dtls(clientssl)) { if (!TEST_ptr(s_to_c_bio = BIO_new(bio_s_mempacket_test())) || !TEST_ptr(c_to_s_bio = BIO_new(bio_s_mempacket_test()))) goto error; } else { if (!TEST_ptr(s_to_c_bio = BIO_new(BIO_s_mem())) || !TEST_ptr(c_to_s_bio = BIO_new(BIO_s_mem()))) goto error; } if (s_to_c_fbio != NULL && !TEST_ptr(s_to_c_bio = BIO_push(s_to_c_fbio, s_to_c_bio))) goto error; if (c_to_s_fbio != NULL && !TEST_ptr(c_to_s_bio = BIO_push(c_to_s_fbio, c_to_s_bio))) goto error; /* Set Non-blocking IO behaviour */ BIO_set_mem_eof_return(s_to_c_bio, -1); BIO_set_mem_eof_return(c_to_s_bio, -1); /* Up ref these as we are passing them to two SSL objects */ SSL_set_bio(serverssl, c_to_s_bio, s_to_c_bio); BIO_up_ref(s_to_c_bio); BIO_up_ref(c_to_s_bio); SSL_set_bio(clientssl, s_to_c_bio, c_to_s_bio); *sssl = serverssl; *cssl = clientssl; return 1; error: SSL_free(serverssl); SSL_free(clientssl); BIO_free(s_to_c_bio); BIO_free(c_to_s_bio); BIO_free(s_to_c_fbio); BIO_free(c_to_s_fbio); return 0; } /* * Create an SSL connection, but does not read any post-handshake * NewSessionTicket messages. * If |read| is set and we're using DTLS then we will attempt to SSL_read on * the connection once we've completed one half of it, to ensure any retransmits * get triggered. * We stop the connection attempt (and return a failure value) if either peer * has SSL_get_error() return the value in the |want| parameter. The connection * attempt could be restarted by a subsequent call to this function. */ int create_bare_ssl_connection(SSL *serverssl, SSL *clientssl, int want, int read, int listen) { int retc = -1, rets = -1, err, abortctr = 0, ret = 0; int clienterr = 0, servererr = 0; int isdtls = SSL_is_dtls(serverssl); #ifndef OPENSSL_NO_SOCK BIO_ADDR *peer = NULL; if (listen) { if (!isdtls) { TEST_error("DTLSv1_listen requested for non-DTLS object\n"); return 0; } peer = BIO_ADDR_new(); if (!TEST_ptr(peer)) return 0; } #else if (listen) { TEST_error("DTLSv1_listen requested in a no-sock build\n"); return 0; } #endif do { err = SSL_ERROR_WANT_WRITE; while (!clienterr && retc <= 0 && err == SSL_ERROR_WANT_WRITE) { retc = SSL_connect(clientssl); if (retc <= 0) err = SSL_get_error(clientssl, retc); } if (!clienterr && retc <= 0 && err != SSL_ERROR_WANT_READ) { TEST_info("SSL_connect() failed %d, %d", retc, err); if (want != SSL_ERROR_SSL) TEST_openssl_errors(); clienterr = 1; } if (want != SSL_ERROR_NONE && err == want) goto err; err = SSL_ERROR_WANT_WRITE; while (!servererr && rets <= 0 && err == SSL_ERROR_WANT_WRITE) { #ifndef OPENSSL_NO_SOCK if (listen) { rets = DTLSv1_listen(serverssl, peer); if (rets < 0) { err = SSL_ERROR_SSL; } else if (rets == 0) { err = SSL_ERROR_WANT_READ; } else { /* Success - stop listening and call SSL_accept from now on */ listen = 0; rets = 0; } } else #endif { rets = SSL_accept(serverssl); if (rets <= 0) err = SSL_get_error(serverssl, rets); } } if (!servererr && rets <= 0 && err != SSL_ERROR_WANT_READ && err != SSL_ERROR_WANT_X509_LOOKUP) { TEST_info("SSL_accept() failed %d, %d", rets, err); if (want != SSL_ERROR_SSL) TEST_openssl_errors(); servererr = 1; } if (want != SSL_ERROR_NONE && err == want) goto err; if (clienterr && servererr) goto err; if (isdtls && read) { unsigned char buf[20]; /* Trigger any retransmits that may be appropriate */ if (rets > 0 && retc <= 0) { if (SSL_read(serverssl, buf, sizeof(buf)) > 0) { /* We don't expect this to succeed! */ TEST_info("Unexpected SSL_read() success!"); goto err; } } if (retc > 0 && rets <= 0) { if (SSL_read(clientssl, buf, sizeof(buf)) > 0) { /* We don't expect this to succeed! */ TEST_info("Unexpected SSL_read() success!"); goto err; } } } if (++abortctr == MAXLOOPS) { TEST_info("No progress made"); goto err; } if (isdtls && abortctr <= 50 && (abortctr % 10) == 0) { /* * It looks like we're just spinning. Pause for a short period to * give the DTLS timer a chance to do something. We only do this for * the first few times to prevent hangs. */ OSSL_sleep(50); } } while (retc <=0 || rets <= 0); ret = 1; err: #ifndef OPENSSL_NO_SOCK BIO_ADDR_free(peer); #endif return ret; } /* * Create an SSL connection including any post handshake NewSessionTicket * messages. */ int create_ssl_connection(SSL *serverssl, SSL *clientssl, int want) { int i; unsigned char buf; size_t readbytes; if (!create_bare_ssl_connection(serverssl, clientssl, want, 1, 0)) return 0; /* * We attempt to read some data on the client side which we expect to fail. * This will ensure we have received the NewSessionTicket in TLSv1.3 where * appropriate. We do this twice because there are 2 NewSessionTickets. */ for (i = 0; i < 2; i++) { if (SSL_read_ex(clientssl, &buf, sizeof(buf), &readbytes) > 0) { if (!TEST_ulong_eq(readbytes, 0)) return 0; } else if (!TEST_int_eq(SSL_get_error(clientssl, 0), SSL_ERROR_WANT_READ)) { return 0; } } return 1; } void shutdown_ssl_connection(SSL *serverssl, SSL *clientssl) { SSL_shutdown(clientssl); SSL_shutdown(serverssl); SSL_free(serverssl); SSL_free(clientssl); } SSL_SESSION *create_a_psk(SSL *ssl, size_t mdsize) { const SSL_CIPHER *cipher = NULL; const unsigned char key[SHA384_DIGEST_LENGTH] = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f }; SSL_SESSION *sess = NULL; if (mdsize == SHA384_DIGEST_LENGTH) { cipher = SSL_CIPHER_find(ssl, TLS13_AES_256_GCM_SHA384_BYTES); } else if (mdsize == SHA256_DIGEST_LENGTH) { /* * Any ciphersuite using SHA256 will do - it will be compatible with * the actual ciphersuite selected as long as it too is based on SHA256 */ cipher = SSL_CIPHER_find(ssl, TLS13_AES_128_GCM_SHA256_BYTES); } else { /* Should not happen */ return NULL; } sess = SSL_SESSION_new(); if (!TEST_ptr(sess) || !TEST_ptr(cipher) || !TEST_true(SSL_SESSION_set1_master_key(sess, key, mdsize)) || !TEST_true(SSL_SESSION_set_cipher(sess, cipher)) || !TEST_true( SSL_SESSION_set_protocol_version(sess, TLS1_3_VERSION))) { SSL_SESSION_free(sess); return NULL; } return sess; } #define NUM_EXTRA_CERTS 40 int ssl_ctx_add_large_cert_chain(OSSL_LIB_CTX *libctx, SSL_CTX *sctx, const char *cert_file) { BIO *certbio = NULL; X509 *chaincert = NULL; int certlen; int ret = 0; int i; if (!TEST_ptr(certbio = BIO_new_file(cert_file, "r"))) goto end; if (!TEST_ptr(chaincert = X509_new_ex(libctx, NULL))) goto end; if (PEM_read_bio_X509(certbio, &chaincert, NULL, NULL) == NULL) goto end; BIO_free(certbio); certbio = NULL; /* * We assume the supplied certificate is big enough so that if we add * NUM_EXTRA_CERTS it will make the overall message large enough. The * default buffer size is requested to be 16k, but due to the way BUF_MEM * works, it ends up allocating a little over 21k (16 * 4/3). So, in this * test we need to have a message larger than that. */ certlen = i2d_X509(chaincert, NULL); OPENSSL_assert(certlen * NUM_EXTRA_CERTS > (SSL3_RT_MAX_PLAIN_LENGTH * 4) / 3); for (i = 0; i < NUM_EXTRA_CERTS; i++) { if (!X509_up_ref(chaincert)) goto end; if (!SSL_CTX_add_extra_chain_cert(sctx, chaincert)) { X509_free(chaincert); goto end; } } ret = 1; end: BIO_free(certbio); X509_free(chaincert); return ret; }
./openssl/test/helpers/handshake.c
/* * Copyright 2016-2022 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <string.h> #include <openssl/bio.h> #include <openssl/x509_vfy.h> #include <openssl/ssl.h> #include <openssl/core_names.h> #include "../../ssl/ssl_local.h" #include "internal/sockets.h" #include "internal/nelem.h" #include "handshake.h" #include "../testutil.h" #if !defined(OPENSSL_NO_SCTP) && !defined(OPENSSL_NO_SOCK) #include <netinet/sctp.h> #endif HANDSHAKE_RESULT *HANDSHAKE_RESULT_new(void) { HANDSHAKE_RESULT *ret; TEST_ptr(ret = OPENSSL_zalloc(sizeof(*ret))); return ret; } void HANDSHAKE_RESULT_free(HANDSHAKE_RESULT *result) { if (result == NULL) return; OPENSSL_free(result->client_npn_negotiated); OPENSSL_free(result->server_npn_negotiated); OPENSSL_free(result->client_alpn_negotiated); OPENSSL_free(result->server_alpn_negotiated); OPENSSL_free(result->result_session_ticket_app_data); sk_X509_NAME_pop_free(result->server_ca_names, X509_NAME_free); sk_X509_NAME_pop_free(result->client_ca_names, X509_NAME_free); OPENSSL_free(result->cipher); OPENSSL_free(result); } /* * Since there appears to be no way to extract the sent/received alert * from the SSL object directly, we use the info callback and stash * the result in ex_data. */ typedef struct handshake_ex_data_st { int alert_sent; int num_fatal_alerts_sent; int alert_received; int session_ticket_do_not_call; ssl_servername_t servername; } HANDSHAKE_EX_DATA; /* |ctx_data| itself is stack-allocated. */ static void ctx_data_free_data(CTX_DATA *ctx_data) { OPENSSL_free(ctx_data->npn_protocols); ctx_data->npn_protocols = NULL; OPENSSL_free(ctx_data->alpn_protocols); ctx_data->alpn_protocols = NULL; OPENSSL_free(ctx_data->srp_user); ctx_data->srp_user = NULL; OPENSSL_free(ctx_data->srp_password); ctx_data->srp_password = NULL; OPENSSL_free(ctx_data->session_ticket_app_data); ctx_data->session_ticket_app_data = NULL; } static int ex_data_idx; static void info_cb(const SSL *s, int where, int ret) { if (where & SSL_CB_ALERT) { HANDSHAKE_EX_DATA *ex_data = (HANDSHAKE_EX_DATA*)(SSL_get_ex_data(s, ex_data_idx)); if (where & SSL_CB_WRITE) { ex_data->alert_sent = ret; if (strcmp(SSL_alert_type_string(ret), "F") == 0 || strcmp(SSL_alert_desc_string(ret), "CN") == 0) ex_data->num_fatal_alerts_sent++; } else { ex_data->alert_received = ret; } } } /* Select the appropriate server CTX. * Returns SSL_TLSEXT_ERR_OK if a match was found. * If |ignore| is 1, returns SSL_TLSEXT_ERR_NOACK on mismatch. * Otherwise, returns SSL_TLSEXT_ERR_ALERT_FATAL on mismatch. * An empty SNI extension also returns SSL_TSLEXT_ERR_NOACK. */ static int select_server_ctx(SSL *s, void *arg, int ignore) { const char *servername = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name); HANDSHAKE_EX_DATA *ex_data = (HANDSHAKE_EX_DATA*)(SSL_get_ex_data(s, ex_data_idx)); if (servername == NULL) { ex_data->servername = SSL_TEST_SERVERNAME_SERVER1; return SSL_TLSEXT_ERR_NOACK; } if (strcmp(servername, "server2") == 0) { SSL_CTX *new_ctx = (SSL_CTX*)arg; SSL_set_SSL_CTX(s, new_ctx); /* * Copy over all the SSL_CTX options - reasonable behavior * allows testing of cases where the options between two * contexts differ/conflict */ SSL_clear_options(s, 0xFFFFFFFFL); SSL_set_options(s, SSL_CTX_get_options(new_ctx)); ex_data->servername = SSL_TEST_SERVERNAME_SERVER2; return SSL_TLSEXT_ERR_OK; } else if (strcmp(servername, "server1") == 0) { ex_data->servername = SSL_TEST_SERVERNAME_SERVER1; return SSL_TLSEXT_ERR_OK; } else if (ignore) { ex_data->servername = SSL_TEST_SERVERNAME_SERVER1; return SSL_TLSEXT_ERR_NOACK; } else { /* Don't set an explicit alert, to test library defaults. */ return SSL_TLSEXT_ERR_ALERT_FATAL; } } static int client_hello_select_server_ctx(SSL *s, void *arg, int ignore) { const char *servername; const unsigned char *p; size_t len, remaining; HANDSHAKE_EX_DATA *ex_data = (HANDSHAKE_EX_DATA*)(SSL_get_ex_data(s, ex_data_idx)); /* * The server_name extension was given too much extensibility when it * was written, so parsing the normal case is a bit complex. */ if (!SSL_client_hello_get0_ext(s, TLSEXT_TYPE_server_name, &p, &remaining) || remaining <= 2) return 0; /* Extract the length of the supplied list of names. */ len = (*(p++) << 8); len += *(p++); if (len + 2 != remaining) return 0; remaining = len; /* * The list in practice only has a single element, so we only consider * the first one. */ if (remaining == 0 || *p++ != TLSEXT_NAMETYPE_host_name) return 0; remaining--; /* Now we can finally pull out the byte array with the actual hostname. */ if (remaining <= 2) return 0; len = (*(p++) << 8); len += *(p++); if (len + 2 > remaining) return 0; remaining = len; servername = (const char *)p; if (len == strlen("server2") && HAS_PREFIX(servername, "server2")) { SSL_CTX *new_ctx = arg; SSL_set_SSL_CTX(s, new_ctx); /* * Copy over all the SSL_CTX options - reasonable behavior * allows testing of cases where the options between two * contexts differ/conflict */ SSL_clear_options(s, 0xFFFFFFFFL); SSL_set_options(s, SSL_CTX_get_options(new_ctx)); ex_data->servername = SSL_TEST_SERVERNAME_SERVER2; return 1; } else if (len == strlen("server1") && HAS_PREFIX(servername, "server1")) { ex_data->servername = SSL_TEST_SERVERNAME_SERVER1; return 1; } else if (ignore) { ex_data->servername = SSL_TEST_SERVERNAME_SERVER1; return 1; } return 0; } /* * (RFC 6066): * If the server understood the ClientHello extension but * does not recognize the server name, the server SHOULD take one of two * actions: either abort the handshake by sending a fatal-level * unrecognized_name(112) alert or continue the handshake. * * This behaviour is up to the application to configure; we test both * configurations to ensure the state machine propagates the result * correctly. */ static int servername_ignore_cb(SSL *s, int *ad, void *arg) { return select_server_ctx(s, arg, 1); } static int servername_reject_cb(SSL *s, int *ad, void *arg) { return select_server_ctx(s, arg, 0); } static int client_hello_ignore_cb(SSL *s, int *al, void *arg) { if (!client_hello_select_server_ctx(s, arg, 1)) { *al = SSL_AD_UNRECOGNIZED_NAME; return SSL_CLIENT_HELLO_ERROR; } return SSL_CLIENT_HELLO_SUCCESS; } static int client_hello_reject_cb(SSL *s, int *al, void *arg) { if (!client_hello_select_server_ctx(s, arg, 0)) { *al = SSL_AD_UNRECOGNIZED_NAME; return SSL_CLIENT_HELLO_ERROR; } return SSL_CLIENT_HELLO_SUCCESS; } static int client_hello_nov12_cb(SSL *s, int *al, void *arg) { int ret; unsigned int v; const unsigned char *p; v = SSL_client_hello_get0_legacy_version(s); if (v > TLS1_2_VERSION || v < SSL3_VERSION) { *al = SSL_AD_PROTOCOL_VERSION; return SSL_CLIENT_HELLO_ERROR; } (void)SSL_client_hello_get0_session_id(s, &p); if (p == NULL || SSL_client_hello_get0_random(s, &p) == 0 || SSL_client_hello_get0_ciphers(s, &p) == 0 || SSL_client_hello_get0_compression_methods(s, &p) == 0) { *al = SSL_AD_INTERNAL_ERROR; return SSL_CLIENT_HELLO_ERROR; } ret = client_hello_select_server_ctx(s, arg, 0); SSL_set_max_proto_version(s, TLS1_1_VERSION); if (!ret) { *al = SSL_AD_UNRECOGNIZED_NAME; return SSL_CLIENT_HELLO_ERROR; } return SSL_CLIENT_HELLO_SUCCESS; } static unsigned char dummy_ocsp_resp_good_val = 0xff; static unsigned char dummy_ocsp_resp_bad_val = 0xfe; static int server_ocsp_cb(SSL *s, void *arg) { unsigned char *resp; resp = OPENSSL_malloc(1); if (resp == NULL) return SSL_TLSEXT_ERR_ALERT_FATAL; /* * For the purposes of testing we just send back a dummy OCSP response */ *resp = *(unsigned char *)arg; if (!SSL_set_tlsext_status_ocsp_resp(s, resp, 1)) { OPENSSL_free(resp); return SSL_TLSEXT_ERR_ALERT_FATAL; } return SSL_TLSEXT_ERR_OK; } static int client_ocsp_cb(SSL *s, void *arg) { const unsigned char *resp; int len; len = SSL_get_tlsext_status_ocsp_resp(s, &resp); if (len != 1 || *resp != dummy_ocsp_resp_good_val) return 0; return 1; } static int verify_reject_cb(X509_STORE_CTX *ctx, void *arg) { X509_STORE_CTX_set_error(ctx, X509_V_ERR_APPLICATION_VERIFICATION); return 0; } static int n_retries = 0; static int verify_retry_cb(X509_STORE_CTX *ctx, void *arg) { int idx = SSL_get_ex_data_X509_STORE_CTX_idx(); SSL *ssl; /* this should not happen but check anyway */ if (idx < 0 || (ssl = X509_STORE_CTX_get_ex_data(ctx, idx)) == NULL) return 0; if (--n_retries < 0) return 1; return SSL_set_retry_verify(ssl); } static int verify_accept_cb(X509_STORE_CTX *ctx, void *arg) { return 1; } static int broken_session_ticket_cb(SSL *s, unsigned char *key_name, unsigned char *iv, EVP_CIPHER_CTX *ctx, EVP_MAC_CTX *hctx, int enc) { return 0; } static int do_not_call_session_ticket_cb(SSL *s, unsigned char *key_name, unsigned char *iv, EVP_CIPHER_CTX *ctx, EVP_MAC_CTX *hctx, int enc) { HANDSHAKE_EX_DATA *ex_data = (HANDSHAKE_EX_DATA*)(SSL_get_ex_data(s, ex_data_idx)); ex_data->session_ticket_do_not_call = 1; return 0; } /* Parse the comma-separated list into TLS format. */ static int parse_protos(const char *protos, unsigned char **out, size_t *outlen) { size_t len, i, prefix; len = strlen(protos); /* Should never have reuse. */ if (!TEST_ptr_null(*out) /* Test values are small, so we omit length limit checks. */ || !TEST_ptr(*out = OPENSSL_malloc(len + 1))) return 0; *outlen = len + 1; /* * foo => '3', 'f', 'o', 'o' * foo,bar => '3', 'f', 'o', 'o', '3', 'b', 'a', 'r' */ memcpy(*out + 1, protos, len); prefix = 0; i = prefix + 1; while (i <= len) { if ((*out)[i] == ',') { if (!TEST_int_gt(i - 1, prefix)) goto err; (*out)[prefix] = (unsigned char)(i - 1 - prefix); prefix = i; } i++; } if (!TEST_int_gt(len, prefix)) goto err; (*out)[prefix] = (unsigned char)(len - prefix); return 1; err: OPENSSL_free(*out); *out = NULL; return 0; } #ifndef OPENSSL_NO_NEXTPROTONEG /* * The client SHOULD select the first protocol advertised by the server that it * also supports. In the event that the client doesn't support any of server's * protocols, or the server doesn't advertise any, it SHOULD select the first * protocol that it supports. */ static int client_npn_cb(SSL *s, unsigned char **out, unsigned char *outlen, const unsigned char *in, unsigned int inlen, void *arg) { CTX_DATA *ctx_data = (CTX_DATA*)(arg); int ret; ret = SSL_select_next_proto(out, outlen, in, inlen, ctx_data->npn_protocols, ctx_data->npn_protocols_len); /* Accept both OPENSSL_NPN_NEGOTIATED and OPENSSL_NPN_NO_OVERLAP. */ return TEST_true(ret == OPENSSL_NPN_NEGOTIATED || ret == OPENSSL_NPN_NO_OVERLAP) ? SSL_TLSEXT_ERR_OK : SSL_TLSEXT_ERR_ALERT_FATAL; } static int server_npn_cb(SSL *s, const unsigned char **data, unsigned int *len, void *arg) { CTX_DATA *ctx_data = (CTX_DATA*)(arg); *data = ctx_data->npn_protocols; *len = ctx_data->npn_protocols_len; return SSL_TLSEXT_ERR_OK; } #endif /* * The server SHOULD select the most highly preferred protocol that it supports * and that is also advertised by the client. In the event that the server * supports no protocols that the client advertises, then the server SHALL * respond with a fatal "no_application_protocol" alert. */ static int server_alpn_cb(SSL *s, const unsigned char **out, unsigned char *outlen, const unsigned char *in, unsigned int inlen, void *arg) { CTX_DATA *ctx_data = (CTX_DATA*)(arg); int ret; /* SSL_select_next_proto isn't const-correct... */ unsigned char *tmp_out; /* * The result points either to |in| or to |ctx_data->alpn_protocols|. * The callback is allowed to point to |in| or to a long-lived buffer, * so we can return directly without storing a copy. */ ret = SSL_select_next_proto(&tmp_out, outlen, ctx_data->alpn_protocols, ctx_data->alpn_protocols_len, in, inlen); *out = tmp_out; /* Unlike NPN, we don't tolerate a mismatch. */ return ret == OPENSSL_NPN_NEGOTIATED ? SSL_TLSEXT_ERR_OK : SSL_TLSEXT_ERR_ALERT_FATAL; } static int generate_session_ticket_cb(SSL *s, void *arg) { CTX_DATA *server_ctx_data = arg; SSL_SESSION *ss = SSL_get_session(s); char *app_data = server_ctx_data->session_ticket_app_data; if (ss == NULL || app_data == NULL) return 0; return SSL_SESSION_set1_ticket_appdata(ss, app_data, strlen(app_data)); } static int decrypt_session_ticket_cb(SSL *s, SSL_SESSION *ss, const unsigned char *keyname, size_t keyname_len, SSL_TICKET_STATUS status, void *arg) { switch (status) { case SSL_TICKET_EMPTY: case SSL_TICKET_NO_DECRYPT: return SSL_TICKET_RETURN_IGNORE_RENEW; case SSL_TICKET_SUCCESS: return SSL_TICKET_RETURN_USE; case SSL_TICKET_SUCCESS_RENEW: return SSL_TICKET_RETURN_USE_RENEW; default: break; } return SSL_TICKET_RETURN_ABORT; } /* * Configure callbacks and other properties that can't be set directly * in the server/client CONF. */ static int configure_handshake_ctx(SSL_CTX *server_ctx, SSL_CTX *server2_ctx, SSL_CTX *client_ctx, const SSL_TEST_CTX *test, const SSL_TEST_EXTRA_CONF *extra, CTX_DATA *server_ctx_data, CTX_DATA *server2_ctx_data, CTX_DATA *client_ctx_data) { unsigned char *ticket_keys; size_t ticket_key_len; if (!TEST_int_eq(SSL_CTX_set_max_send_fragment(server_ctx, test->max_fragment_size), 1)) goto err; if (server2_ctx != NULL) { if (!TEST_int_eq(SSL_CTX_set_max_send_fragment(server2_ctx, test->max_fragment_size), 1)) goto err; } if (!TEST_int_eq(SSL_CTX_set_max_send_fragment(client_ctx, test->max_fragment_size), 1)) goto err; switch (extra->client.verify_callback) { case SSL_TEST_VERIFY_ACCEPT_ALL: SSL_CTX_set_cert_verify_callback(client_ctx, &verify_accept_cb, NULL); break; case SSL_TEST_VERIFY_RETRY_ONCE: n_retries = 1; SSL_CTX_set_cert_verify_callback(client_ctx, &verify_retry_cb, NULL); break; case SSL_TEST_VERIFY_REJECT_ALL: SSL_CTX_set_cert_verify_callback(client_ctx, &verify_reject_cb, NULL); break; case SSL_TEST_VERIFY_NONE: break; } switch (extra->client.max_fragment_len_mode) { case TLSEXT_max_fragment_length_512: case TLSEXT_max_fragment_length_1024: case TLSEXT_max_fragment_length_2048: case TLSEXT_max_fragment_length_4096: case TLSEXT_max_fragment_length_DISABLED: SSL_CTX_set_tlsext_max_fragment_length( client_ctx, extra->client.max_fragment_len_mode); break; } /* * Link the two contexts for SNI purposes. * Also do ClientHello callbacks here, as setting both ClientHello and SNI * is bad. */ switch (extra->server.servername_callback) { case SSL_TEST_SERVERNAME_IGNORE_MISMATCH: SSL_CTX_set_tlsext_servername_callback(server_ctx, servername_ignore_cb); SSL_CTX_set_tlsext_servername_arg(server_ctx, server2_ctx); break; case SSL_TEST_SERVERNAME_REJECT_MISMATCH: SSL_CTX_set_tlsext_servername_callback(server_ctx, servername_reject_cb); SSL_CTX_set_tlsext_servername_arg(server_ctx, server2_ctx); break; case SSL_TEST_SERVERNAME_CB_NONE: break; case SSL_TEST_SERVERNAME_CLIENT_HELLO_IGNORE_MISMATCH: SSL_CTX_set_client_hello_cb(server_ctx, client_hello_ignore_cb, server2_ctx); break; case SSL_TEST_SERVERNAME_CLIENT_HELLO_REJECT_MISMATCH: SSL_CTX_set_client_hello_cb(server_ctx, client_hello_reject_cb, server2_ctx); break; case SSL_TEST_SERVERNAME_CLIENT_HELLO_NO_V12: SSL_CTX_set_client_hello_cb(server_ctx, client_hello_nov12_cb, server2_ctx); } if (extra->server.cert_status != SSL_TEST_CERT_STATUS_NONE) { SSL_CTX_set_tlsext_status_type(client_ctx, TLSEXT_STATUSTYPE_ocsp); SSL_CTX_set_tlsext_status_cb(client_ctx, client_ocsp_cb); SSL_CTX_set_tlsext_status_arg(client_ctx, NULL); SSL_CTX_set_tlsext_status_cb(server_ctx, server_ocsp_cb); SSL_CTX_set_tlsext_status_arg(server_ctx, ((extra->server.cert_status == SSL_TEST_CERT_STATUS_GOOD_RESPONSE) ? &dummy_ocsp_resp_good_val : &dummy_ocsp_resp_bad_val)); } /* * The initial_ctx/session_ctx always handles the encrypt/decrypt of the * session ticket. This ticket_key callback is assigned to the second * session (assigned via SNI), and should never be invoked */ if (server2_ctx != NULL) SSL_CTX_set_tlsext_ticket_key_evp_cb(server2_ctx, do_not_call_session_ticket_cb); if (extra->server.broken_session_ticket) { SSL_CTX_set_tlsext_ticket_key_evp_cb(server_ctx, broken_session_ticket_cb); } #ifndef OPENSSL_NO_NEXTPROTONEG if (extra->server.npn_protocols != NULL) { if (!TEST_true(parse_protos(extra->server.npn_protocols, &server_ctx_data->npn_protocols, &server_ctx_data->npn_protocols_len))) goto err; SSL_CTX_set_npn_advertised_cb(server_ctx, server_npn_cb, server_ctx_data); } if (extra->server2.npn_protocols != NULL) { if (!TEST_true(parse_protos(extra->server2.npn_protocols, &server2_ctx_data->npn_protocols, &server2_ctx_data->npn_protocols_len)) || !TEST_ptr(server2_ctx)) goto err; SSL_CTX_set_npn_advertised_cb(server2_ctx, server_npn_cb, server2_ctx_data); } if (extra->client.npn_protocols != NULL) { if (!TEST_true(parse_protos(extra->client.npn_protocols, &client_ctx_data->npn_protocols, &client_ctx_data->npn_protocols_len))) goto err; SSL_CTX_set_next_proto_select_cb(client_ctx, client_npn_cb, client_ctx_data); } #endif if (extra->server.alpn_protocols != NULL) { if (!TEST_true(parse_protos(extra->server.alpn_protocols, &server_ctx_data->alpn_protocols, &server_ctx_data->alpn_protocols_len))) goto err; SSL_CTX_set_alpn_select_cb(server_ctx, server_alpn_cb, server_ctx_data); } if (extra->server2.alpn_protocols != NULL) { if (!TEST_ptr(server2_ctx) || !TEST_true(parse_protos(extra->server2.alpn_protocols, &server2_ctx_data->alpn_protocols, &server2_ctx_data->alpn_protocols_len ))) goto err; SSL_CTX_set_alpn_select_cb(server2_ctx, server_alpn_cb, server2_ctx_data); } if (extra->client.alpn_protocols != NULL) { unsigned char *alpn_protos = NULL; size_t alpn_protos_len = 0; if (!TEST_true(parse_protos(extra->client.alpn_protocols, &alpn_protos, &alpn_protos_len)) /* Reversed return value convention... */ || !TEST_int_eq(SSL_CTX_set_alpn_protos(client_ctx, alpn_protos, alpn_protos_len), 0)) goto err; OPENSSL_free(alpn_protos); } if (extra->server.session_ticket_app_data != NULL) { server_ctx_data->session_ticket_app_data = OPENSSL_strdup(extra->server.session_ticket_app_data); if (!TEST_ptr(server_ctx_data->session_ticket_app_data)) goto err; SSL_CTX_set_session_ticket_cb(server_ctx, generate_session_ticket_cb, decrypt_session_ticket_cb, server_ctx_data); } if (extra->server2.session_ticket_app_data != NULL) { if (!TEST_ptr(server2_ctx)) goto err; server2_ctx_data->session_ticket_app_data = OPENSSL_strdup(extra->server2.session_ticket_app_data); if (!TEST_ptr(server2_ctx_data->session_ticket_app_data)) goto err; SSL_CTX_set_session_ticket_cb(server2_ctx, NULL, decrypt_session_ticket_cb, server2_ctx_data); } /* * Use fixed session ticket keys so that we can decrypt a ticket created with * one CTX in another CTX. Don't address server2 for the moment. */ ticket_key_len = SSL_CTX_set_tlsext_ticket_keys(server_ctx, NULL, 0); if (!TEST_ptr(ticket_keys = OPENSSL_zalloc(ticket_key_len)) || !TEST_int_eq(SSL_CTX_set_tlsext_ticket_keys(server_ctx, ticket_keys, ticket_key_len), 1)) { OPENSSL_free(ticket_keys); goto err; } OPENSSL_free(ticket_keys); /* The default log list includes EC keys, so CT can't work without EC. */ #if !defined(OPENSSL_NO_CT) && !defined(OPENSSL_NO_EC) if (!TEST_true(SSL_CTX_set_default_ctlog_list_file(client_ctx))) goto err; switch (extra->client.ct_validation) { case SSL_TEST_CT_VALIDATION_PERMISSIVE: if (!TEST_true(SSL_CTX_enable_ct(client_ctx, SSL_CT_VALIDATION_PERMISSIVE))) goto err; break; case SSL_TEST_CT_VALIDATION_STRICT: if (!TEST_true(SSL_CTX_enable_ct(client_ctx, SSL_CT_VALIDATION_STRICT))) goto err; break; case SSL_TEST_CT_VALIDATION_NONE: break; } #endif #ifndef OPENSSL_NO_SRP if (!configure_handshake_ctx_for_srp(server_ctx, server2_ctx, client_ctx, extra, server_ctx_data, server2_ctx_data, client_ctx_data)) goto err; #endif /* !OPENSSL_NO_SRP */ #ifndef OPENSSL_NO_COMP_ALG if (test->compress_certificates) { if (!TEST_true(SSL_CTX_compress_certs(server_ctx, 0))) goto err; if (server2_ctx != NULL && !TEST_true(SSL_CTX_compress_certs(server2_ctx, 0))) goto err; } #endif return 1; err: return 0; } /* Configure per-SSL callbacks and other properties. */ static void configure_handshake_ssl(SSL *server, SSL *client, const SSL_TEST_EXTRA_CONF *extra) { if (extra->client.servername != SSL_TEST_SERVERNAME_NONE) SSL_set_tlsext_host_name(client, ssl_servername_name(extra->client.servername)); if (extra->client.enable_pha) SSL_set_post_handshake_auth(client, 1); } /* The status for each connection phase. */ typedef enum { PEER_SUCCESS, PEER_RETRY, PEER_ERROR, PEER_WAITING, PEER_TEST_FAILURE } peer_status_t; /* An SSL object and associated read-write buffers. */ typedef struct peer_st { SSL *ssl; /* Buffer lengths are int to match the SSL read/write API. */ unsigned char *write_buf; int write_buf_len; unsigned char *read_buf; int read_buf_len; int bytes_to_write; int bytes_to_read; peer_status_t status; } PEER; static int create_peer(PEER *peer, SSL_CTX *ctx) { static const int peer_buffer_size = 64 * 1024; SSL *ssl = NULL; unsigned char *read_buf = NULL, *write_buf = NULL; if (!TEST_ptr(ssl = SSL_new(ctx)) || !TEST_ptr(write_buf = OPENSSL_zalloc(peer_buffer_size)) || !TEST_ptr(read_buf = OPENSSL_zalloc(peer_buffer_size))) goto err; peer->ssl = ssl; peer->write_buf = write_buf; peer->read_buf = read_buf; peer->write_buf_len = peer->read_buf_len = peer_buffer_size; return 1; err: SSL_free(ssl); OPENSSL_free(write_buf); OPENSSL_free(read_buf); return 0; } static void peer_free_data(PEER *peer) { SSL_free(peer->ssl); OPENSSL_free(peer->write_buf); OPENSSL_free(peer->read_buf); } /* * Note that we could do the handshake transparently under an SSL_write, * but separating the steps is more helpful for debugging test failures. */ static void do_handshake_step(PEER *peer) { if (!TEST_int_eq(peer->status, PEER_RETRY)) { peer->status = PEER_TEST_FAILURE; } else { int ret = SSL_do_handshake(peer->ssl); if (ret == 1) { peer->status = PEER_SUCCESS; } else if (ret == 0) { peer->status = PEER_ERROR; } else { int error = SSL_get_error(peer->ssl, ret); /* Memory bios should never block with SSL_ERROR_WANT_WRITE. */ if (error != SSL_ERROR_WANT_READ && error != SSL_ERROR_WANT_RETRY_VERIFY) peer->status = PEER_ERROR; } } } /*- * Send/receive some application data. The read-write sequence is * Peer A: (R) W - first read will yield no data * Peer B: R W * ... * Peer A: R W * Peer B: R W * Peer A: R */ static void do_app_data_step(PEER *peer) { int ret = 1, write_bytes; if (!TEST_int_eq(peer->status, PEER_RETRY)) { peer->status = PEER_TEST_FAILURE; return; } /* We read everything available... */ while (ret > 0 && peer->bytes_to_read) { ret = SSL_read(peer->ssl, peer->read_buf, peer->read_buf_len); if (ret > 0) { if (!TEST_int_le(ret, peer->bytes_to_read)) { peer->status = PEER_TEST_FAILURE; return; } peer->bytes_to_read -= ret; } else if (ret == 0) { peer->status = PEER_ERROR; return; } else { int error = SSL_get_error(peer->ssl, ret); if (error != SSL_ERROR_WANT_READ) { peer->status = PEER_ERROR; return; } /* Else continue with write. */ } } /* ... but we only write one write-buffer-full of data. */ write_bytes = peer->bytes_to_write < peer->write_buf_len ? peer->bytes_to_write : peer->write_buf_len; if (write_bytes) { ret = SSL_write(peer->ssl, peer->write_buf, write_bytes); if (ret > 0) { /* SSL_write will only succeed with a complete write. */ if (!TEST_int_eq(ret, write_bytes)) { peer->status = PEER_TEST_FAILURE; return; } peer->bytes_to_write -= ret; } else { /* * We should perhaps check for SSL_ERROR_WANT_READ/WRITE here * but this doesn't yet occur with current app data sizes. */ peer->status = PEER_ERROR; return; } } /* * We could simply finish when there was nothing to read, and we have * nothing left to write. But keeping track of the expected number of bytes * to read gives us somewhat better guarantees that all data sent is in fact * received. */ if (peer->bytes_to_write == 0 && peer->bytes_to_read == 0) { peer->status = PEER_SUCCESS; } } static void do_reneg_setup_step(const SSL_TEST_CTX *test_ctx, PEER *peer) { int ret; char buf; if (peer->status == PEER_SUCCESS) { /* * We are a client that succeeded this step previously, but the server * wanted to retry. Probably there is a no_renegotiation warning alert * waiting for us. Attempt to continue the handshake. */ peer->status = PEER_RETRY; do_handshake_step(peer); return; } if (!TEST_int_eq(peer->status, PEER_RETRY) || !TEST_true(test_ctx->handshake_mode == SSL_TEST_HANDSHAKE_RENEG_SERVER || test_ctx->handshake_mode == SSL_TEST_HANDSHAKE_RENEG_CLIENT || test_ctx->handshake_mode == SSL_TEST_HANDSHAKE_KEY_UPDATE_SERVER || test_ctx->handshake_mode == SSL_TEST_HANDSHAKE_KEY_UPDATE_CLIENT || test_ctx->handshake_mode == SSL_TEST_HANDSHAKE_POST_HANDSHAKE_AUTH)) { peer->status = PEER_TEST_FAILURE; return; } /* Reset the count of the amount of app data we need to read/write */ peer->bytes_to_write = peer->bytes_to_read = test_ctx->app_data_size; /* Check if we are the peer that is going to initiate */ if ((test_ctx->handshake_mode == SSL_TEST_HANDSHAKE_RENEG_SERVER && SSL_is_server(peer->ssl)) || (test_ctx->handshake_mode == SSL_TEST_HANDSHAKE_RENEG_CLIENT && !SSL_is_server(peer->ssl))) { /* * If we already asked for a renegotiation then fall through to the * SSL_read() below. */ if (!SSL_renegotiate_pending(peer->ssl)) { /* * If we are the client we will always attempt to resume the * session. The server may or may not resume dependent on the * setting of SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION */ if (SSL_is_server(peer->ssl)) { ret = SSL_renegotiate(peer->ssl); } else { int full_reneg = 0; if (test_ctx->extra.client.no_extms_on_reneg) { SSL_set_options(peer->ssl, SSL_OP_NO_EXTENDED_MASTER_SECRET); full_reneg = 1; } if (test_ctx->extra.client.reneg_ciphers != NULL) { if (!SSL_set_cipher_list(peer->ssl, test_ctx->extra.client.reneg_ciphers)) { peer->status = PEER_ERROR; return; } full_reneg = 1; } if (full_reneg) ret = SSL_renegotiate(peer->ssl); else ret = SSL_renegotiate_abbreviated(peer->ssl); } if (!ret) { peer->status = PEER_ERROR; return; } do_handshake_step(peer); /* * If status is PEER_RETRY it means we're waiting on the peer to * continue the handshake. As far as setting up the renegotiation is * concerned that is a success. The next step will continue the * handshake to its conclusion. * * If status is PEER_SUCCESS then we are the server and we have * successfully sent the HelloRequest. We need to continue to wait * until the handshake arrives from the client. */ if (peer->status == PEER_RETRY) peer->status = PEER_SUCCESS; else if (peer->status == PEER_SUCCESS) peer->status = PEER_RETRY; return; } } else if (test_ctx->handshake_mode == SSL_TEST_HANDSHAKE_KEY_UPDATE_SERVER || test_ctx->handshake_mode == SSL_TEST_HANDSHAKE_KEY_UPDATE_CLIENT) { if (SSL_is_server(peer->ssl) != (test_ctx->handshake_mode == SSL_TEST_HANDSHAKE_KEY_UPDATE_SERVER)) { peer->status = PEER_SUCCESS; return; } ret = SSL_key_update(peer->ssl, test_ctx->key_update_type); if (!ret) { peer->status = PEER_ERROR; return; } do_handshake_step(peer); /* * This is a one step handshake. We shouldn't get anything other than * PEER_SUCCESS */ if (peer->status != PEER_SUCCESS) peer->status = PEER_ERROR; return; } else if (test_ctx->handshake_mode == SSL_TEST_HANDSHAKE_POST_HANDSHAKE_AUTH) { if (SSL_is_server(peer->ssl)) { SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL_ONLY(peer->ssl); if (sc == NULL) { peer->status = PEER_ERROR; return; } /* Make the server believe it's received the extension */ if (test_ctx->extra.server.force_pha) sc->post_handshake_auth = SSL_PHA_EXT_RECEIVED; ret = SSL_verify_client_post_handshake(peer->ssl); if (!ret) { peer->status = PEER_ERROR; return; } } do_handshake_step(peer); /* * This is a one step handshake. We shouldn't get anything other than * PEER_SUCCESS */ if (peer->status != PEER_SUCCESS) peer->status = PEER_ERROR; return; } /* * The SSL object is still expecting app data, even though it's going to * get a handshake message. We try to read, and it should fail - after which * we should be in a handshake */ ret = SSL_read(peer->ssl, &buf, sizeof(buf)); if (ret >= 0) { /* * We're not actually expecting data - we're expecting a reneg to * start */ peer->status = PEER_ERROR; return; } else { int error = SSL_get_error(peer->ssl, ret); if (error != SSL_ERROR_WANT_READ) { peer->status = PEER_ERROR; return; } /* If we're not in init yet then we're not done with setup yet */ if (!SSL_in_init(peer->ssl)) return; } peer->status = PEER_SUCCESS; } /* * RFC 5246 says: * * Note that as of TLS 1.1, * failure to properly close a connection no longer requires that a * session not be resumed. This is a change from TLS 1.0 to conform * with widespread implementation practice. * * However, * (a) OpenSSL requires that a connection be shutdown for all protocol versions. * (b) We test lower versions, too. * So we just implement shutdown. We do a full bidirectional shutdown so that we * can compare sent and received close_notify alerts and get some test coverage * for SSL_shutdown as a bonus. */ static void do_shutdown_step(PEER *peer) { int ret; if (!TEST_int_eq(peer->status, PEER_RETRY)) { peer->status = PEER_TEST_FAILURE; return; } ret = SSL_shutdown(peer->ssl); if (ret == 1) { peer->status = PEER_SUCCESS; } else if (ret < 0) { /* On 0, we retry. */ int error = SSL_get_error(peer->ssl, ret); if (error != SSL_ERROR_WANT_READ && error != SSL_ERROR_WANT_WRITE) peer->status = PEER_ERROR; } } typedef enum { HANDSHAKE, RENEG_APPLICATION_DATA, RENEG_SETUP, RENEG_HANDSHAKE, APPLICATION_DATA, SHUTDOWN, CONNECTION_DONE } connect_phase_t; static int renegotiate_op(const SSL_TEST_CTX *test_ctx) { switch (test_ctx->handshake_mode) { case SSL_TEST_HANDSHAKE_RENEG_SERVER: case SSL_TEST_HANDSHAKE_RENEG_CLIENT: return 1; default: return 0; } } static int post_handshake_op(const SSL_TEST_CTX *test_ctx) { switch (test_ctx->handshake_mode) { case SSL_TEST_HANDSHAKE_KEY_UPDATE_CLIENT: case SSL_TEST_HANDSHAKE_KEY_UPDATE_SERVER: case SSL_TEST_HANDSHAKE_POST_HANDSHAKE_AUTH: return 1; default: return 0; } } static connect_phase_t next_phase(const SSL_TEST_CTX *test_ctx, connect_phase_t phase) { switch (phase) { case HANDSHAKE: if (renegotiate_op(test_ctx) || post_handshake_op(test_ctx)) return RENEG_APPLICATION_DATA; return APPLICATION_DATA; case RENEG_APPLICATION_DATA: return RENEG_SETUP; case RENEG_SETUP: if (post_handshake_op(test_ctx)) return APPLICATION_DATA; return RENEG_HANDSHAKE; case RENEG_HANDSHAKE: return APPLICATION_DATA; case APPLICATION_DATA: return SHUTDOWN; case SHUTDOWN: return CONNECTION_DONE; case CONNECTION_DONE: TEST_error("Trying to progress after connection done"); break; } return -1; } static void do_connect_step(const SSL_TEST_CTX *test_ctx, PEER *peer, connect_phase_t phase) { switch (phase) { case HANDSHAKE: do_handshake_step(peer); break; case RENEG_APPLICATION_DATA: do_app_data_step(peer); break; case RENEG_SETUP: do_reneg_setup_step(test_ctx, peer); break; case RENEG_HANDSHAKE: do_handshake_step(peer); break; case APPLICATION_DATA: do_app_data_step(peer); break; case SHUTDOWN: do_shutdown_step(peer); break; case CONNECTION_DONE: TEST_error("Action after connection done"); break; } } typedef enum { /* Both parties succeeded. */ HANDSHAKE_SUCCESS, /* Client errored. */ CLIENT_ERROR, /* Server errored. */ SERVER_ERROR, /* Peers are in inconsistent state. */ INTERNAL_ERROR, /* One or both peers not done. */ HANDSHAKE_RETRY } handshake_status_t; /* * Determine the handshake outcome. * last_status: the status of the peer to have acted last. * previous_status: the status of the peer that didn't act last. * client_spoke_last: 1 if the client went last. */ static handshake_status_t handshake_status(peer_status_t last_status, peer_status_t previous_status, int client_spoke_last) { switch (last_status) { case PEER_TEST_FAILURE: return INTERNAL_ERROR; case PEER_WAITING: /* Shouldn't ever happen */ return INTERNAL_ERROR; case PEER_SUCCESS: switch (previous_status) { case PEER_TEST_FAILURE: return INTERNAL_ERROR; case PEER_SUCCESS: /* Both succeeded. */ return HANDSHAKE_SUCCESS; case PEER_WAITING: case PEER_RETRY: /* Let the first peer finish. */ return HANDSHAKE_RETRY; case PEER_ERROR: /* * Second peer succeeded despite the fact that the first peer * already errored. This shouldn't happen. */ return INTERNAL_ERROR; } break; case PEER_RETRY: return HANDSHAKE_RETRY; case PEER_ERROR: switch (previous_status) { case PEER_TEST_FAILURE: return INTERNAL_ERROR; case PEER_WAITING: /* The client failed immediately before sending the ClientHello */ return client_spoke_last ? CLIENT_ERROR : INTERNAL_ERROR; case PEER_SUCCESS: /* First peer succeeded but second peer errored. */ return client_spoke_last ? CLIENT_ERROR : SERVER_ERROR; case PEER_RETRY: /* We errored; let the peer finish. */ return HANDSHAKE_RETRY; case PEER_ERROR: /* Both peers errored. Return the one that errored first. */ return client_spoke_last ? SERVER_ERROR : CLIENT_ERROR; } } /* Control should never reach here. */ return INTERNAL_ERROR; } /* Convert unsigned char buf's that shouldn't contain any NUL-bytes to char. */ static char *dup_str(const unsigned char *in, size_t len) { char *ret = NULL; if (len == 0) return NULL; /* Assert that the string does not contain NUL-bytes. */ if (TEST_size_t_eq(OPENSSL_strnlen((const char*)(in), len), len)) TEST_ptr(ret = OPENSSL_strndup((const char*)(in), len)); return ret; } static int pkey_type(EVP_PKEY *pkey) { if (EVP_PKEY_is_a(pkey, "EC")) { char name[80]; size_t name_len; if (!EVP_PKEY_get_group_name(pkey, name, sizeof(name), &name_len)) return NID_undef; return OBJ_txt2nid(name); } return EVP_PKEY_get_id(pkey); } static int peer_pkey_type(SSL *s) { X509 *x = SSL_get0_peer_certificate(s); if (x != NULL) return pkey_type(X509_get0_pubkey(x)); return NID_undef; } #if !defined(OPENSSL_NO_SCTP) && !defined(OPENSSL_NO_SOCK) static int set_sock_as_sctp(int sock) { struct sctp_assocparams assocparams; struct sctp_rtoinfo rto_info; BIO *tmpbio; /* * To allow tests to fail fast (within a second or so), reduce the * retransmission timeouts and the number of retransmissions. */ memset(&rto_info, 0, sizeof(struct sctp_rtoinfo)); rto_info.srto_initial = 100; rto_info.srto_max = 200; rto_info.srto_min = 50; (void)setsockopt(sock, IPPROTO_SCTP, SCTP_RTOINFO, (const void *)&rto_info, sizeof(struct sctp_rtoinfo)); memset(&assocparams, 0, sizeof(struct sctp_assocparams)); assocparams.sasoc_asocmaxrxt = 2; (void)setsockopt(sock, IPPROTO_SCTP, SCTP_ASSOCINFO, (const void *)&assocparams, sizeof(struct sctp_assocparams)); /* * For SCTP we have to set various options on the socket prior to * connecting. This is done automatically by BIO_new_dgram_sctp(). * We don't actually need the created BIO though so we free it again * immediately. */ tmpbio = BIO_new_dgram_sctp(sock, BIO_NOCLOSE); if (tmpbio == NULL) return 0; BIO_free(tmpbio); return 1; } static int create_sctp_socks(int *ssock, int *csock) { BIO_ADDRINFO *res = NULL; const BIO_ADDRINFO *ai = NULL; int lsock = INVALID_SOCKET, asock = INVALID_SOCKET; int consock = INVALID_SOCKET; int ret = 0; int family = 0; if (BIO_sock_init() != 1) return 0; /* * Port is 4463. It could be anything. It will fail if it's already being * used for some other SCTP service. It seems unlikely though so we don't * worry about it here. */ if (!BIO_lookup_ex(NULL, "4463", BIO_LOOKUP_SERVER, family, SOCK_STREAM, IPPROTO_SCTP, &res)) return 0; for (ai = res; ai != NULL; ai = BIO_ADDRINFO_next(ai)) { family = BIO_ADDRINFO_family(ai); lsock = BIO_socket(family, SOCK_STREAM, IPPROTO_SCTP, 0); if (lsock == INVALID_SOCKET) { /* Maybe the kernel doesn't support the socket family, even if * BIO_lookup() added it in the returned result... */ continue; } if (!set_sock_as_sctp(lsock) || !BIO_listen(lsock, BIO_ADDRINFO_address(ai), BIO_SOCK_REUSEADDR)) { BIO_closesocket(lsock); lsock = INVALID_SOCKET; continue; } /* Success, don't try any more addresses */ break; } if (lsock == INVALID_SOCKET) goto err; BIO_ADDRINFO_free(res); res = NULL; if (!BIO_lookup_ex(NULL, "4463", BIO_LOOKUP_CLIENT, family, SOCK_STREAM, IPPROTO_SCTP, &res)) goto err; consock = BIO_socket(family, SOCK_STREAM, IPPROTO_SCTP, 0); if (consock == INVALID_SOCKET) goto err; if (!set_sock_as_sctp(consock) || !BIO_connect(consock, BIO_ADDRINFO_address(res), 0) || !BIO_socket_nbio(consock, 1)) goto err; asock = BIO_accept_ex(lsock, NULL, BIO_SOCK_NONBLOCK); if (asock == INVALID_SOCKET) goto err; *csock = consock; *ssock = asock; consock = asock = INVALID_SOCKET; ret = 1; err: BIO_ADDRINFO_free(res); if (consock != INVALID_SOCKET) BIO_closesocket(consock); if (lsock != INVALID_SOCKET) BIO_closesocket(lsock); if (asock != INVALID_SOCKET) BIO_closesocket(asock); return ret; } #endif /* * Note that |extra| points to the correct client/server configuration * within |test_ctx|. When configuring the handshake, general mode settings * are taken from |test_ctx|, and client/server-specific settings should be * taken from |extra|. * * The configuration code should never reach into |test_ctx->extra| or * |test_ctx->resume_extra| directly. * * (We could refactor test mode settings into a substructure. This would result * in cleaner argument passing but would complicate the test configuration * parsing.) */ static HANDSHAKE_RESULT *do_handshake_internal( SSL_CTX *server_ctx, SSL_CTX *server2_ctx, SSL_CTX *client_ctx, const SSL_TEST_CTX *test_ctx, const SSL_TEST_EXTRA_CONF *extra, SSL_SESSION *session_in, SSL_SESSION *serv_sess_in, SSL_SESSION **session_out, SSL_SESSION **serv_sess_out) { PEER server, client; BIO *client_to_server = NULL, *server_to_client = NULL; HANDSHAKE_EX_DATA server_ex_data, client_ex_data; CTX_DATA client_ctx_data, server_ctx_data, server2_ctx_data; HANDSHAKE_RESULT *ret = HANDSHAKE_RESULT_new(); int client_turn = 1, client_turn_count = 0, client_wait_count = 0; connect_phase_t phase = HANDSHAKE; handshake_status_t status = HANDSHAKE_RETRY; const unsigned char* tick = NULL; size_t tick_len = 0; const unsigned char* sess_id = NULL; unsigned int sess_id_len = 0; SSL_SESSION* sess = NULL; const unsigned char *proto = NULL; /* API dictates unsigned int rather than size_t. */ unsigned int proto_len = 0; EVP_PKEY *tmp_key; const STACK_OF(X509_NAME) *names; time_t start; const char* cipher; if (ret == NULL) return NULL; memset(&server_ctx_data, 0, sizeof(server_ctx_data)); memset(&server2_ctx_data, 0, sizeof(server2_ctx_data)); memset(&client_ctx_data, 0, sizeof(client_ctx_data)); memset(&server, 0, sizeof(server)); memset(&client, 0, sizeof(client)); memset(&server_ex_data, 0, sizeof(server_ex_data)); memset(&client_ex_data, 0, sizeof(client_ex_data)); if (!configure_handshake_ctx(server_ctx, server2_ctx, client_ctx, test_ctx, extra, &server_ctx_data, &server2_ctx_data, &client_ctx_data)) { TEST_note("configure_handshake_ctx"); HANDSHAKE_RESULT_free(ret); return NULL; } #if !defined(OPENSSL_NO_SCTP) && !defined(OPENSSL_NO_SOCK) if (test_ctx->enable_client_sctp_label_bug) SSL_CTX_set_mode(client_ctx, SSL_MODE_DTLS_SCTP_LABEL_LENGTH_BUG); if (test_ctx->enable_server_sctp_label_bug) SSL_CTX_set_mode(server_ctx, SSL_MODE_DTLS_SCTP_LABEL_LENGTH_BUG); #endif /* Setup SSL and buffers; additional configuration happens below. */ if (!create_peer(&server, server_ctx)) { TEST_note("creating server context"); goto err; } if (!create_peer(&client, client_ctx)) { TEST_note("creating client context"); goto err; } server.bytes_to_write = client.bytes_to_read = test_ctx->app_data_size; client.bytes_to_write = server.bytes_to_read = test_ctx->app_data_size; configure_handshake_ssl(server.ssl, client.ssl, extra); if (session_in != NULL) { SSL_SESSION_get_id(serv_sess_in, &sess_id_len); /* In case we're testing resumption without tickets. */ if ((sess_id_len > 0 && !TEST_true(SSL_CTX_add_session(server_ctx, serv_sess_in))) || !TEST_true(SSL_set_session(client.ssl, session_in))) goto err; sess_id_len = 0; } ret->result = SSL_TEST_INTERNAL_ERROR; if (test_ctx->use_sctp) { #if !defined(OPENSSL_NO_SCTP) && !defined(OPENSSL_NO_SOCK) int csock, ssock; if (create_sctp_socks(&ssock, &csock)) { client_to_server = BIO_new_dgram_sctp(csock, BIO_CLOSE); server_to_client = BIO_new_dgram_sctp(ssock, BIO_CLOSE); } #endif } else { client_to_server = BIO_new(BIO_s_mem()); server_to_client = BIO_new(BIO_s_mem()); } if (!TEST_ptr(client_to_server) || !TEST_ptr(server_to_client)) goto err; /* Non-blocking bio. */ BIO_set_nbio(client_to_server, 1); BIO_set_nbio(server_to_client, 1); SSL_set_connect_state(client.ssl); SSL_set_accept_state(server.ssl); /* The bios are now owned by the SSL object. */ if (test_ctx->use_sctp) { SSL_set_bio(client.ssl, client_to_server, client_to_server); SSL_set_bio(server.ssl, server_to_client, server_to_client); } else { SSL_set_bio(client.ssl, server_to_client, client_to_server); if (!TEST_int_gt(BIO_up_ref(server_to_client), 0) || !TEST_int_gt(BIO_up_ref(client_to_server), 0)) goto err; SSL_set_bio(server.ssl, client_to_server, server_to_client); } ex_data_idx = SSL_get_ex_new_index(0, "ex data", NULL, NULL, NULL); if (!TEST_int_ge(ex_data_idx, 0) || !TEST_int_eq(SSL_set_ex_data(server.ssl, ex_data_idx, &server_ex_data), 1) || !TEST_int_eq(SSL_set_ex_data(client.ssl, ex_data_idx, &client_ex_data), 1)) goto err; SSL_set_info_callback(server.ssl, &info_cb); SSL_set_info_callback(client.ssl, &info_cb); client.status = PEER_RETRY; server.status = PEER_WAITING; start = time(NULL); /* * Half-duplex handshake loop. * Client and server speak to each other synchronously in the same process. * We use non-blocking BIOs, so whenever one peer blocks for read, it * returns PEER_RETRY to indicate that it's the other peer's turn to write. * The handshake succeeds once both peers have succeeded. If one peer * errors out, we also let the other peer retry (and presumably fail). */ for (;;) { if (client_turn) { do_connect_step(test_ctx, &client, phase); status = handshake_status(client.status, server.status, 1 /* client went last */); if (server.status == PEER_WAITING) server.status = PEER_RETRY; } else { do_connect_step(test_ctx, &server, phase); status = handshake_status(server.status, client.status, 0 /* server went last */); } switch (status) { case HANDSHAKE_SUCCESS: client_turn_count = 0; phase = next_phase(test_ctx, phase); if (phase == CONNECTION_DONE) { ret->result = SSL_TEST_SUCCESS; goto err; } else { client.status = server.status = PEER_RETRY; /* * For now, client starts each phase. Since each phase is * started separately, we can later control this more * precisely, for example, to test client-initiated and * server-initiated shutdown. */ client_turn = 1; break; } case CLIENT_ERROR: ret->result = SSL_TEST_CLIENT_FAIL; goto err; case SERVER_ERROR: ret->result = SSL_TEST_SERVER_FAIL; goto err; case INTERNAL_ERROR: ret->result = SSL_TEST_INTERNAL_ERROR; goto err; case HANDSHAKE_RETRY: if (test_ctx->use_sctp) { if (time(NULL) - start > 3) { /* * We've waited for too long. Give up. */ ret->result = SSL_TEST_INTERNAL_ERROR; goto err; } /* * With "real" sockets we only swap to processing the peer * if they are expecting to retry. Otherwise we just retry the * same endpoint again. */ if ((client_turn && server.status == PEER_RETRY) || (!client_turn && client.status == PEER_RETRY)) client_turn ^= 1; } else { if (client_turn_count++ >= 2000) { /* * At this point, there's been so many PEER_RETRY in a row * that it's likely both sides are stuck waiting for a read. * It's time to give up. */ ret->result = SSL_TEST_INTERNAL_ERROR; goto err; } if (client_turn && server.status == PEER_SUCCESS) { /* * The server may finish before the client because the * client spends some turns processing NewSessionTickets. */ if (client_wait_count++ >= 2) { ret->result = SSL_TEST_INTERNAL_ERROR; goto err; } } else { /* Continue. */ client_turn ^= 1; } } break; } } err: ret->server_alert_sent = server_ex_data.alert_sent; ret->server_num_fatal_alerts_sent = server_ex_data.num_fatal_alerts_sent; ret->server_alert_received = client_ex_data.alert_received; ret->client_alert_sent = client_ex_data.alert_sent; ret->client_num_fatal_alerts_sent = client_ex_data.num_fatal_alerts_sent; ret->client_alert_received = server_ex_data.alert_received; ret->server_protocol = SSL_version(server.ssl); ret->client_protocol = SSL_version(client.ssl); ret->servername = server_ex_data.servername; if ((sess = SSL_get0_session(client.ssl)) != NULL) { SSL_SESSION_get0_ticket(sess, &tick, &tick_len); sess_id = SSL_SESSION_get_id(sess, &sess_id_len); } if (tick == NULL || tick_len == 0) ret->session_ticket = SSL_TEST_SESSION_TICKET_NO; else ret->session_ticket = SSL_TEST_SESSION_TICKET_YES; ret->compression = (SSL_get_current_compression(client.ssl) == NULL) ? SSL_TEST_COMPRESSION_NO : SSL_TEST_COMPRESSION_YES; if (sess_id == NULL || sess_id_len == 0) ret->session_id = SSL_TEST_SESSION_ID_NO; else ret->session_id = SSL_TEST_SESSION_ID_YES; ret->session_ticket_do_not_call = server_ex_data.session_ticket_do_not_call; if (extra->client.verify_callback == SSL_TEST_VERIFY_RETRY_ONCE && n_retries != -1) ret->result = SSL_TEST_SERVER_FAIL; #ifndef OPENSSL_NO_NEXTPROTONEG SSL_get0_next_proto_negotiated(client.ssl, &proto, &proto_len); ret->client_npn_negotiated = dup_str(proto, proto_len); SSL_get0_next_proto_negotiated(server.ssl, &proto, &proto_len); ret->server_npn_negotiated = dup_str(proto, proto_len); #endif SSL_get0_alpn_selected(client.ssl, &proto, &proto_len); ret->client_alpn_negotiated = dup_str(proto, proto_len); SSL_get0_alpn_selected(server.ssl, &proto, &proto_len); ret->server_alpn_negotiated = dup_str(proto, proto_len); if ((sess = SSL_get0_session(server.ssl)) != NULL) { SSL_SESSION_get0_ticket_appdata(sess, (void**)&tick, &tick_len); ret->result_session_ticket_app_data = OPENSSL_strndup((const char*)tick, tick_len); } ret->client_resumed = SSL_session_reused(client.ssl); ret->server_resumed = SSL_session_reused(server.ssl); cipher = SSL_CIPHER_get_name(SSL_get_current_cipher(client.ssl)); ret->cipher = dup_str((const unsigned char*)cipher, strlen(cipher)); if (session_out != NULL) *session_out = SSL_get1_session(client.ssl); if (serv_sess_out != NULL) { SSL_SESSION *tmp = SSL_get_session(server.ssl); /* * We create a fresh copy that is not in the server session ctx linked * list. */ if (tmp != NULL) *serv_sess_out = SSL_SESSION_dup(tmp); } if (SSL_get_peer_tmp_key(client.ssl, &tmp_key)) { ret->tmp_key_type = pkey_type(tmp_key); EVP_PKEY_free(tmp_key); } SSL_get_peer_signature_nid(client.ssl, &ret->server_sign_hash); SSL_get_peer_signature_nid(server.ssl, &ret->client_sign_hash); SSL_get_peer_signature_type_nid(client.ssl, &ret->server_sign_type); SSL_get_peer_signature_type_nid(server.ssl, &ret->client_sign_type); names = SSL_get0_peer_CA_list(client.ssl); if (names == NULL) ret->client_ca_names = NULL; else ret->client_ca_names = SSL_dup_CA_list(names); names = SSL_get0_peer_CA_list(server.ssl); if (names == NULL) ret->server_ca_names = NULL; else ret->server_ca_names = SSL_dup_CA_list(names); ret->server_cert_type = peer_pkey_type(client.ssl); ret->client_cert_type = peer_pkey_type(server.ssl); ctx_data_free_data(&server_ctx_data); ctx_data_free_data(&server2_ctx_data); ctx_data_free_data(&client_ctx_data); peer_free_data(&server); peer_free_data(&client); return ret; } 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) { HANDSHAKE_RESULT *result; SSL_SESSION *session = NULL, *serv_sess = NULL; result = do_handshake_internal(server_ctx, server2_ctx, client_ctx, test_ctx, &test_ctx->extra, NULL, NULL, &session, &serv_sess); if (result == NULL || test_ctx->handshake_mode != SSL_TEST_HANDSHAKE_RESUME || result->result == SSL_TEST_INTERNAL_ERROR) goto end; if (result->result != SSL_TEST_SUCCESS) { result->result = SSL_TEST_FIRST_HANDSHAKE_FAILED; goto end; } HANDSHAKE_RESULT_free(result); /* We don't support SNI on second handshake yet, so server2_ctx is NULL. */ result = do_handshake_internal(resume_server_ctx, NULL, resume_client_ctx, test_ctx, &test_ctx->resume_extra, session, serv_sess, NULL, NULL); end: SSL_SESSION_free(session); SSL_SESSION_free(serv_sess); return result; }
./openssl/test/helpers/pkcs12.h
/* * 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 <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" /* ------------------------------------------------------------------------- * PKCS#12 Test structures */ /* Holds a set of Attributes */ typedef struct pkcs12_attr { char *oid; char *value; } PKCS12_ATTR; /* Holds encryption parameters */ typedef struct pkcs12_enc { int nid; const char *pass; int iter; } PKCS12_ENC; /* Set of variables required for constructing the PKCS#12 structure */ typedef struct pkcs12_builder { const char *filename; int success; BIO *p12bio; STACK_OF(PKCS7) *safes; int safe_idx; STACK_OF(PKCS12_SAFEBAG) *bags; int bag_idx; } PKCS12_BUILDER; /* ------------------------------------------------------------------------- * PKCS#12 Test function declarations */ /* Global settings */ void PKCS12_helper_set_write_files(int enable); void PKCS12_helper_set_legacy(int enable); void PKCS12_helper_set_libctx(OSSL_LIB_CTX *libctx); void PKCS12_helper_set_propq(const char *propq); /* Allocate and initialise a PKCS#12 builder object */ PKCS12_BUILDER *new_pkcs12_builder(const char *filename); /* Finalise and free the PKCS#12 builder object, returning the success/fail flag */ int end_pkcs12_builder(PKCS12_BUILDER *pb); /* Encode/build functions */ void start_pkcs12(PKCS12_BUILDER *pb); void end_pkcs12(PKCS12_BUILDER *pb); void end_pkcs12_with_mac(PKCS12_BUILDER *pb, const PKCS12_ENC *mac); void start_contentinfo(PKCS12_BUILDER *pb); void end_contentinfo(PKCS12_BUILDER *pb); void end_contentinfo_encrypted(PKCS12_BUILDER *pb, const PKCS12_ENC *enc); void add_certbag(PKCS12_BUILDER *pb, const unsigned char *bytes, int len, const PKCS12_ATTR *attrs); void add_keybag(PKCS12_BUILDER *pb, const unsigned char *bytes, int len, const PKCS12_ATTR *attrs, const PKCS12_ENC *enc); void add_secretbag(PKCS12_BUILDER *pb, int secret_nid, const char *secret, const PKCS12_ATTR *attrs); void add_extra_attr(PKCS12_BUILDER *pb); /* Decode/check functions */ void start_check_pkcs12(PKCS12_BUILDER *pb); void start_check_pkcs12_with_mac(PKCS12_BUILDER *pb, const PKCS12_ENC *mac); void start_check_pkcs12_file(PKCS12_BUILDER *pb); void start_check_pkcs12_file_with_mac(PKCS12_BUILDER *pb, const PKCS12_ENC *mac); void end_check_pkcs12(PKCS12_BUILDER *pb); void start_check_contentinfo(PKCS12_BUILDER *pb); void start_check_contentinfo_encrypted(PKCS12_BUILDER *pb, const PKCS12_ENC *enc); void end_check_contentinfo(PKCS12_BUILDER *pb); void check_certbag(PKCS12_BUILDER *pb, const unsigned char *bytes, int len, const PKCS12_ATTR *attrs); void check_keybag(PKCS12_BUILDER *pb, const unsigned char *bytes, int len, const PKCS12_ATTR *attrs, const PKCS12_ENC *enc); void check_secretbag(PKCS12_BUILDER *pb, int secret_nid, const char *secret, const PKCS12_ATTR *attrs);
./openssl/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); }
./openssl/test/helpers/quictestlib.h
/* * Copyright 2022-2023 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <openssl/ssl.h> #include <internal/quic_tserver.h> /* Type to represent the Fault Injector */ typedef struct qtest_fault QTEST_FAULT; /* * Structure representing a parsed EncryptedExtension message. Listeners can * make changes to the contents of structure objects as required and the fault * injector will reconstruct the message to be sent on */ typedef struct qtest_fault_encrypted_extensions { /* EncryptedExtension messages just have an extensions block */ unsigned char *extensions; size_t extensionslen; } QTEST_ENCRYPTED_EXTENSIONS; /* Flags for use with qtest_create_quic_objects() */ /* Indicates whether we are using blocking mode or not */ #define QTEST_FLAG_BLOCK (1 << 0) /* Use fake time rather than real time */ #define QTEST_FLAG_FAKE_TIME (1 << 1) /* Introduce noise in the BIO */ #define QTEST_FLAG_NOISE (1 << 2) /* Split datagrams such that each datagram contains one packet */ #define QTEST_FLAG_PACKET_SPLIT (1 << 3) /* Turn on client side tracing */ #define QTEST_FLAG_CLIENT_TRACE (1 << 4) /* * Given an SSL_CTX for the client and filenames for the server certificate and * keyfile, create a server and client instances as well as a fault injector * instance. |flags| is the logical or of flags defined above, or 0 if none. */ int qtest_create_quic_objects(OSSL_LIB_CTX *libctx, SSL_CTX *clientctx, SSL_CTX *serverctx, char *certfile, char *keyfile, int flags, QUIC_TSERVER **qtserv, SSL **cssl, QTEST_FAULT **fault, BIO **tracebio); /* Where QTEST_FLAG_FAKE_TIME is used, add millis to the current time */ void qtest_add_time(uint64_t millis); QTEST_FAULT *qtest_create_injector(QUIC_TSERVER *ts); BIO_METHOD *qtest_get_bio_method(void); /* * Free up a Fault Injector instance */ void qtest_fault_free(QTEST_FAULT *fault); /* Returns 1 if the quictestlib supports blocking tests */ int qtest_supports_blocking(void); /* * Run the TLS handshake to create a QUIC connection between the client and * server. */ int qtest_create_quic_connection(QUIC_TSERVER *qtserv, SSL *clientssl); /* * Check if both client and server have no data to read and are waiting on a * timeout. If so, wait until the timeout has expired. */ int qtest_wait_for_timeout(SSL *s, QUIC_TSERVER *qtserv); /* * Same as qtest_create_quic_connection but will stop (successfully) if the * clientssl indicates SSL_ERROR_WANT_XXX as specified by |wanterr| */ int qtest_create_quic_connection_ex(QUIC_TSERVER *qtserv, SSL *clientssl, int wanterr); /* * Shutdown the client SSL object gracefully */ int qtest_shutdown(QUIC_TSERVER *qtserv, SSL *clientssl); /* * Confirm that the server has received the given transport error code. */ int qtest_check_server_transport_err(QUIC_TSERVER *qtserv, uint64_t code); /* * Confirm the server has received a protocol error. Equivalent to calling * qtest_check_server_transport_err with a code of QUIC_ERR_PROTOCOL_VIOLATION */ int qtest_check_server_protocol_err(QUIC_TSERVER *qtserv); /* * Confirm the server has received a frame encoding error. Equivalent to calling * qtest_check_server_transport_err with a code of QUIC_ERR_FRAME_ENCODING_ERROR */ int qtest_check_server_frame_encoding_err(QUIC_TSERVER *qtserv); /* * Enable tests to listen for pre-encryption QUIC packets being sent */ typedef int (*qtest_fault_on_packet_plain_cb)(QTEST_FAULT *fault, QUIC_PKT_HDR *hdr, unsigned char *buf, size_t len, void *cbarg); int qtest_fault_set_packet_plain_listener(QTEST_FAULT *fault, qtest_fault_on_packet_plain_cb pplaincb, void *pplaincbarg); /* * Helper function to be called from a packet_plain_listener callback if it * wants to resize the packet (either to add new data to it, or to truncate it). * The buf provided to packet_plain_listener is over allocated, so this just * changes the logical size and never changes the actual address of the buf. * This will fail if a large resize is attempted that exceeds the over * allocation. */ int qtest_fault_resize_plain_packet(QTEST_FAULT *fault, size_t newlen); /* * Prepend frame data into a packet. To be called from a packet_plain_listener * callback */ int qtest_fault_prepend_frame(QTEST_FAULT *fault, const unsigned char *frame, size_t frame_len); /* * The general handshake message listener is sent the entire handshake message * data block, including the handshake header itself */ typedef int (*qtest_fault_on_handshake_cb)(QTEST_FAULT *fault, unsigned char *msg, size_t msglen, void *handshakecbarg); int qtest_fault_set_handshake_listener(QTEST_FAULT *fault, qtest_fault_on_handshake_cb handshakecb, void *handshakecbarg); /* * Helper function to be called from a handshake_listener callback if it wants * to resize the handshake message (either to add new data to it, or to truncate * it). newlen must include the length of the handshake message header. The * handshake message buffer is over allocated, so this just changes the logical * size and never changes the actual address of the buf. * This will fail if a large resize is attempted that exceeds the over * allocation. */ int qtest_fault_resize_handshake(QTEST_FAULT *fault, size_t newlen); /* * Add listeners for specific types of frame here. E.g. we might * expect to see an "ACK" frame listener which will be passed pre-parsed ack * data that can be modified as required. */ /* * Handshake message specific listeners. Unlike the general handshake message * listener these messages are pre-parsed and supplied with message specific * data and exclude the handshake header */ typedef int (*qtest_fault_on_enc_ext_cb)(QTEST_FAULT *fault, QTEST_ENCRYPTED_EXTENSIONS *ee, size_t eelen, void *encextcbarg); int qtest_fault_set_hand_enc_ext_listener(QTEST_FAULT *fault, qtest_fault_on_enc_ext_cb encextcb, void *encextcbarg); /* Add listeners for other types of handshake message here */ /* * Helper function to be called from message specific listener callbacks. newlen * is the new length of the specific message excluding the handshake message * header. The buffers provided to the message specific listeners are over * allocated, so this just changes the logical size and never changes the actual * address of the buffer. This will fail if a large resize is attempted that * exceeds the over allocation. */ int qtest_fault_resize_message(QTEST_FAULT *fault, size_t newlen); /* * Helper function to delete an extension from an extension block. |exttype| is * the type of the extension to be deleted. |ext| points to the extension block. * On entry |*extlen| contains the length of the extension block. It is updated * with the new length on exit. If old_ext is non-NULL, the deleted extension * is appended to the given BUF_MEM. */ int qtest_fault_delete_extension(QTEST_FAULT *fault, unsigned int exttype, unsigned char *ext, size_t *extlen, BUF_MEM *old_ext); /* * Add additional helper functions for querying extensions here (e.g. * finding or adding them). We could also provide a "listener" API for listening * for specific extension types */ /* * Enable tests to listen for post-encryption QUIC packets being sent */ typedef int (*qtest_fault_on_packet_cipher_cb)(QTEST_FAULT *fault, /* The parsed packet header */ QUIC_PKT_HDR *hdr, /* The packet payload data */ unsigned char *buf, /* Length of the payload */ size_t len, void *cbarg); int qtest_fault_set_packet_cipher_listener(QTEST_FAULT *fault, qtest_fault_on_packet_cipher_cb pciphercb, void *picphercbarg); /* * Enable tests to listen for datagrams being sent */ typedef int (*qtest_fault_on_datagram_cb)(QTEST_FAULT *fault, BIO_MSG *m, size_t stride, void *cbarg); int qtest_fault_set_datagram_listener(QTEST_FAULT *fault, qtest_fault_on_datagram_cb datagramcb, void *datagramcbarg); /* * To be called from a datagram_listener callback. The datagram buffer is over * allocated, so this just changes the logical size and never changes the actual * address of the buffer. This will fail if a large resize is attempted that * exceeds the over allocation. */ int qtest_fault_resize_datagram(QTEST_FAULT *fault, size_t newlen); /* Copy a BIO_MSG */ int bio_msg_copy(BIO_MSG *dst, BIO_MSG *src); #define BIO_CTRL_NOISE_BACK_OFF 1001 /* BIO filter for simulating a noisy UDP socket */ const BIO_METHOD *bio_f_noisy_dgram_filter(void); /* Free the BIO filter method object */ void bio_f_noisy_dgram_filter_free(void); /* * BIO filter for splitting QUIC datagrams containing multiple packets into * individual datagrams. */ const BIO_METHOD *bio_f_pkt_split_dgram_filter(void); /* Free the BIO filter method object */ void bio_f_pkt_split_dgram_filter_free(void);
./openssl/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 */
./openssl/test/helpers/predefined_dhparams.h
/* * Copyright 1995-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/evp.h> #ifndef OPENSSL_NO_DH EVP_PKEY *get_dh512(OSSL_LIB_CTX *libctx); EVP_PKEY *get_dhx512(OSSL_LIB_CTX *libctx); EVP_PKEY *get_dh1024dsa(OSSL_LIB_CTX *libct); EVP_PKEY *get_dh2048(OSSL_LIB_CTX *libctx); EVP_PKEY *get_dh4096(OSSL_LIB_CTX *libctx); #endif
./openssl/util/quicserver.c
/* * Copyright 2023 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ /* * This is a temporary test server for QUIC. It will eventually be replaced * by s_server and removed once we have full QUIC server support. */ #include <stdio.h> #include <openssl/bio.h> #include <openssl/ssl.h> #include <openssl/err.h> #include "internal/e_os.h" #include "internal/sockets.h" #include "internal/quic_tserver.h" #include "internal/quic_stream_map.h" #include "internal/time.h" static BIO *bio_err = NULL; static void wait_for_activity(QUIC_TSERVER *qtserv) { fd_set readfds, writefds; fd_set *readfdsp = NULL, *writefdsp = NULL; struct timeval timeout, *timeoutp = NULL; int width; int sock; BIO *bio = ossl_quic_tserver_get0_rbio(qtserv); OSSL_TIME deadline; BIO_get_fd(bio, &sock); if (ossl_quic_tserver_get_net_read_desired(qtserv)) { readfdsp = &readfds; FD_ZERO(readfdsp); openssl_fdset(sock, readfdsp); } if (ossl_quic_tserver_get_net_write_desired(qtserv)) { writefdsp = &writefds; FD_ZERO(writefdsp); openssl_fdset(sock, writefdsp); } deadline = ossl_quic_tserver_get_deadline(qtserv); if (!ossl_time_is_infinite(deadline)) { timeout = ossl_time_to_timeval(ossl_time_subtract(deadline, ossl_time_now())); timeoutp = &timeout; } width = sock + 1; if (readfdsp == NULL && writefdsp == NULL && timeoutp == NULL) return; select(width, readfdsp, writefdsp, NULL, timeoutp); } /* Helper function to create a BIO connected to the server */ static BIO *create_dgram_bio(int family, const char *hostname, const char *port) { int sock = -1; BIO_ADDRINFO *res; const BIO_ADDRINFO *ai = NULL; BIO *bio; if (BIO_sock_init() != 1) return NULL; /* * Lookup IP address info for the server. */ if (!BIO_lookup_ex(hostname, port, BIO_LOOKUP_SERVER, family, SOCK_DGRAM, 0, &res)) return NULL; /* * Loop through all the possible addresses for the server and find one * we can create and start listening on */ for (ai = res; ai != NULL; ai = BIO_ADDRINFO_next(ai)) { /* Create the UDP socket */ sock = BIO_socket(BIO_ADDRINFO_family(ai), SOCK_DGRAM, 0, 0); if (sock == -1) continue; /* Start listening on the socket */ if (!BIO_listen(sock, BIO_ADDRINFO_address(ai), 0)) { BIO_closesocket(sock); continue; } /* Set to non-blocking mode */ if (!BIO_socket_nbio(sock, 1)) { BIO_closesocket(sock); continue; } break; /* stop searching if we found an addr */ } /* Free the address information resources we allocated earlier */ BIO_ADDRINFO_free(res); /* If we didn't bind any sockets, fail */ if (ai == NULL) return NULL; /* Create a BIO to wrap the socket */ bio = BIO_new(BIO_s_datagram()); if (bio == NULL) { BIO_closesocket(sock); return NULL; } /* * Associate the newly created BIO with the underlying socket. By * passing BIO_CLOSE here the socket will be automatically closed when * the BIO is freed. Alternatively you can use BIO_NOCLOSE, in which * case you must close the socket explicitly when it is no longer * needed. */ BIO_set_fd(bio, sock, BIO_CLOSE); return bio; } static void usage(void) { BIO_printf(bio_err, "quicserver [-6][-trace] hostname port certfile keyfile\n"); } int main(int argc, char *argv[]) { QUIC_TSERVER_ARGS tserver_args = {0}; QUIC_TSERVER *qtserv = NULL; int ipv6 = 0, trace = 0; int argnext = 1; BIO *bio = NULL; char *hostname, *port, *certfile, *keyfile; int ret = EXIT_FAILURE; unsigned char reqbuf[1024]; size_t numbytes, reqbytes = 0; const char reqterm[] = { '\r', '\n', '\r', '\n' }; const char *response[] = { "HTTP/1.0 200 ok\r\nContent-type: text/html\r\n\r\n<!DOCTYPE html>\n<html>\n<body>Hello world</body>\n</html>\n", "HTTP/1.0 200 ok\r\nContent-type: text/html\r\n\r\n<!DOCTYPE html>\n<html>\n<body>Hello again</body>\n</html>\n", "HTTP/1.0 200 ok\r\nContent-type: text/html\r\n\r\n<!DOCTYPE html>\n<html>\n<body>Another response</body>\n</html>\n", "HTTP/1.0 200 ok\r\nContent-type: text/html\r\n\r\n<!DOCTYPE html>\n<html>\n<body>A message</body>\n</html>\n", }; unsigned char alpn[] = { 8, 'h', 't', 't', 'p', '/', '1', '.', '0' }; int first = 1; uint64_t streamid; size_t respnum = 0; bio_err = BIO_new_fp(stderr, BIO_NOCLOSE | BIO_FP_TEXT); if (argc == 0 || bio_err == NULL) goto end2; while (argnext < argc) { if (argv[argnext][0] != '-') break; if (strcmp(argv[argnext], "-6") == 0) { ipv6 = 1; } else if(strcmp(argv[argnext], "-trace") == 0) { trace = 1; } else { BIO_printf(bio_err, "Unrecognised argument %s\n", argv[argnext]); usage(); goto end2; } argnext++; } if (argc - argnext != 4) { usage(); goto end2; } hostname = argv[argnext++]; port = argv[argnext++]; certfile = argv[argnext++]; keyfile = argv[argnext++]; bio = create_dgram_bio(ipv6 ? AF_INET6 : AF_INET, hostname, port); if (bio == NULL || !BIO_up_ref(bio)) { BIO_printf(bio_err, "Unable to create server socket\n"); goto end2; } tserver_args.libctx = NULL; tserver_args.net_rbio = bio; tserver_args.net_wbio = bio; tserver_args.alpn = alpn; tserver_args.alpnlen = sizeof(alpn); tserver_args.ctx = NULL; qtserv = ossl_quic_tserver_new(&tserver_args, certfile, keyfile); if (qtserv == NULL) { BIO_printf(bio_err, "Failed to create the QUIC_TSERVER\n"); goto end; } BIO_printf(bio_err, "Starting quicserver\n"); BIO_printf(bio_err, "Note that this utility will be removed in a future OpenSSL version.\n"); BIO_printf(bio_err, "For test purposes only. Not for use in a production environment.\n"); /* Ownership of the BIO is passed to qtserv */ bio = NULL; if (trace) #ifndef OPENSSL_NO_SSL_TRACE ossl_quic_tserver_set_msg_callback(qtserv, SSL_trace, bio_err); #else BIO_printf(bio_err, "Warning: -trace specified but no SSL tracing support present\n"); #endif /* Wait for handshake to complete */ ossl_quic_tserver_tick(qtserv); while(!ossl_quic_tserver_is_handshake_confirmed(qtserv)) { wait_for_activity(qtserv); ossl_quic_tserver_tick(qtserv); if (ossl_quic_tserver_is_terminated(qtserv)) { BIO_printf(bio_err, "Failed waiting for handshake completion\n"); ret = EXIT_FAILURE; goto end; } } for (;; respnum++) { if (respnum >= OSSL_NELEM(response)) goto end; /* Wait for an incoming stream */ do { streamid = ossl_quic_tserver_pop_incoming_stream(qtserv); if (streamid == UINT64_MAX) wait_for_activity(qtserv); ossl_quic_tserver_tick(qtserv); if (ossl_quic_tserver_is_terminated(qtserv)) { /* Assume we finished everything the clients wants from us */ ret = EXIT_SUCCESS; goto end; } } while(streamid == UINT64_MAX); /* Read the request */ do { if (first) first = 0; else wait_for_activity(qtserv); ossl_quic_tserver_tick(qtserv); if (ossl_quic_tserver_is_terminated(qtserv)) { BIO_printf(bio_err, "Failed reading request\n"); ret = EXIT_FAILURE; goto end; } if (ossl_quic_tserver_read(qtserv, streamid, reqbuf + reqbytes, sizeof(reqbuf) - reqbytes, &numbytes)) { if (numbytes > 0) fwrite(reqbuf + reqbytes, 1, numbytes, stdout); reqbytes += numbytes; } } while (reqbytes < sizeof(reqterm) || memcmp(reqbuf + reqbytes - sizeof(reqterm), reqterm, sizeof(reqterm)) != 0); if ((streamid & QUIC_STREAM_DIR_UNI) != 0) { /* * Incoming stream was uni-directional. Create a server initiated * uni-directional stream for the response. */ if (!ossl_quic_tserver_stream_new(qtserv, 1, &streamid)) { BIO_printf(bio_err, "Failed creating response stream\n"); goto end; } } /* Send the response */ ossl_quic_tserver_tick(qtserv); if (!ossl_quic_tserver_write(qtserv, streamid, (unsigned char *)response[respnum], strlen(response[respnum]), &numbytes)) goto end; if (!ossl_quic_tserver_conclude(qtserv, streamid)) goto end; } end: /* Free twice because we did an up-ref */ BIO_free(bio); end2: BIO_free(bio); ossl_quic_tserver_free(qtserv); BIO_free(bio_err); return ret; }
./openssl/util/check-format-test-positives.c
/* * Copyright 2007-2022 The OpenSSL Project Authors. All Rights Reserved. * Copyright Siemens AG 2015-2022 * * 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 demonstrates/tests cases where check-format.pl should report issues. * Some of the reports are due to sanity checks for proper nesting of comment * delimiters and parenthesis-like symbols, e.g., on unexpected/unclosed braces. */ /* * The '@'s after '*' are used for self-tests: they mark lines containing * a single flaw that should be reported. Normally it should be reported * while handling the given line, but in case of delayed checks there is a * following digit indicating the number of reports expected for this line. */ /* For each of the following set of lines the tool should complain once */ /*@ tab character: */ /*@ intra-line carriage return character: */ /*@ non-printable ASCII character:  */ /*@ non-ASCII character: ä */ /*@ whitespace at EOL: */ // /*@ end-of-line comment style not allowed (for C90 compatibility) */ /*@0 intra-line comment indent off by 1, reported unless sloppy-cmt */ /*X */ /*@2 missing spc or '*' after comment start reported unless sloppy-spc */ /* X*/ /*@ missing space before comment end , reported unless sloppy-spc */ /*@ comment starting delimiter: /* inside intra-line comment */ /*@0 *@ above multi-line comment start indent off by 1, reported unless sloppy-cmt; this comment line is too long *@ multi-line comment indent further off by 1 relative to comment start *@ multi-line comment ending with text on last line */ /*@2 multi-line comment starting with text on first line *@ comment starting delimiter: /* inside multi-line comment *@ multi-line comment indent off by -1 *X*@ no spc after leading '*' in multi-line comment, reported unless sloppy-spc *@0 more than two spaces after . in comment, no more reported *@0 more than two spaces after ? in comment, no more reported *@0 more than two spaces after ! in comment, no more reported */ /*@ multi-line comment end indent off by -1 (relative to comment start) */ */ /*@ unexpected comment ending delimiter outside comment */ /*- '-' for formatted comment not allowed in intra-line comment */ /*@ comment line is 4 columns tooooooooooooooooo wide, reported unless sloppy-len */ /*@ comment line is 5 columns toooooooooooooooooooooooooooooooooooooooooooooo wide */ #if ~0 /*@ '#if' with constant condition */ #endif /*@ indent of preproc. directive off by 1 (must be 0) */ #define X (1 + 1) /*@0 extra space in body, reported unless sloppy-spc */ #define Y 1 /*@ extra space before body, reported unless sloppy-spc */ \ #define Z /*@2 preprocessor directive within multi-line directive */ typedef struct { /*@0 extra space in code, reported unless sloppy-spc */ enum { /*@1 extra space in intra-line comment, no more reported */ w = 0 /*@ hanging expr indent off by 1, or 3 for lines after '{' */ && 1, /*@ hanging expr indent off by 3, or -1 for leading '&&' */ x = 1, /*@ hanging expr indent off by -1 */ y,z /*@ no space after ',', reported unless sloppy-spc */ } e_member ; /*@ space before ';', reported unless sloppy-spc */ int v[1; /*@ unclosed bracket in type declaration */ union { /*@ statement/type declaration indent off by -1 */ struct{} s; /*@ no space before '{', reported unless sloppy-spc */ }u_member; /*@ no space after '}', reported unless sloppy-spc */ } s_type; /*@ statement/type declaration indent off by 4 */ int* somefunc(); /*@ no space before '*' in type decl, r unless sloppy-spc */ void main(int n) { /*@ opening brace at end of function definition header */ for (; ; ) ; /*@ space before ')', reported unless sloppy-spc */ for ( ; x; y) ; /*@2 space after '(' and before ';', unless sloppy-spc */ for (;;n++) { /*@ missing space after ';', reported unless sloppy-spc */ return; /*@0 (1-line) single statement in braces */ }} /*@2 code after '}' outside expr */ } /*@ unexpected closing brace (too many '}') outside expr */ ) /*@ unexpected closing paren outside expr */ #endif /*@ unexpected #endif */ int f (int a, /*@ space after fn before '(', reported unless sloppy-spc */ int b, /*@ hanging expr indent off by -1 */ long I) /*@ single-letter name 'I' */ { int x; /*@ code after '{' opening a block */ int xx = 1) + /*@ unexpected closing parenthesis */ 0L < /*@ constant on LHS of comparison operator */ a] - /*@ unexpected closing bracket */ 3: * /*@ unexpected ':' (without preceding '?') within expr */ 4}; /*@ unexpected closing brace within expression */ char y[] = { /*@0 unclosed brace within initializer/enum expression */ 1* 1, /*@ no space etc. before '*', reported unless sloppy-spc */ 2, /*@ hanging expr indent (for lines after '{') off by 1 */ (xx /*@0 unclosed parenthesis in expression */ ? y /*@0 unclosed '? (conditional expression) */ [0; /*@4 unclosed bracket in expression */ /*@ blank line within local decls */ s_type s; /*@2 local variable declaration indent off by -1 */ t_type t; /*@ local variable declaration indent again off by -1 */ /* */ /*@0 missing blank line after local decls */ somefunc(a, /*@2 statement indent off by -1 */ "aligned" /*@ expr indent off by -2 accepted if sloppy-hang */ "right" , b, /*@ expr indent off by -1 */ b, /*@ expr indent as on line above, accepted if sloppy-hang */ b, /*@ expr indent off -8 but @ extra indent accepted if sloppy-hang */ "again aligned" /*@ expr indent off by -9 (left of stmt indent, */ "right", abc == /*@ .. so reported also with sloppy-hang; this line is too long */ 456 # define MAC(A) (A) /*@ nesting indent of preprocessor directive off by 1 */ ? 1 /*@ hanging expr indent off by 1 */ : 2); /*@ hanging expr indent off by 2, or 1 for leading ':' */ if(a /*@ missing space after 'if', reported unless sloppy-spc */ /*@0 intra-line comment indent off by -1 (not: by 3 due to '&&') */ && ! 0 /*@2 space after '!', reported unless sloppy-spc */ || b == /*@ hanging expr indent off by 2, or -2 for leading '||' */ (x<<= 1) + /*@ missing space before '<<=' reported unless sloppy-spc */ (xx+= 2) + /*@ missing space before '+=', reported unless sloppy-spc */ (a^ 1) + /*@ missing space before '^', reported unless sloppy-spc */ (y *=z) + /*@ missing space after '*=' reported unless sloppy-spc */ a %2 / /*@ missing space after '%', reported unless sloppy-spc */ 1 +/* */ /*@ no space before comment, reported unless sloppy-spc */ /* */+ /*@ no space after comment, reported unless sloppy-spc */ s. e_member) /*@ space after '.', reported unless sloppy-spc */ xx = a + b /*@ extra single-statement indent off by 1 */ + 0; /*@ two times extra single-statement indent off by 3 */ if (a ++) /*@ space before postfix '++', reported unless sloppy-spc */ { /*@ {' not on same line as preceding 'if' */ c; /*@0 single stmt in braces, reported on 1-stmt */ } else /*@ missing '{' on same line after '} else' */ { /*@ statement indent off by 2 */ d; /*@0 single stmt in braces, reported on 1-stmt */ } /*@ statement indent off by 6 */ if (1) f(a, /*@ (non-brace) code after end of 'if' condition */ b); else /*@ (non-brace) code before 'else' */ do f(c, c); /*@ (non-brace) code after 'do' */ while ( 2); /*@ space after '(', reported unless sloppy-spc */ b; c; /*@ more than one statement per line */ outer: /*@ outer label special indent off by 1 */ do{ /*@ missing space before '{', reported unless sloppy-spc */ inner: /*@ inner label normal indent off by 1 */ f (3, /*@ space after fn before '(', reported unless sloppy-spc */ 4); /*@0 false negative: should report single stmt in braces */ } /*@0 'while' not on same line as preceding '}' */ while (a+ 0); /*@2 missing space before '+', reported unless sloppy-spc */ switch (b ) { /*@ space before ')', reported unless sloppy-spc */ case 1: /*@ 'case' special statement indent off by -1 */ case(2): /*@ missing space after 'case', reported unless sloppy-spc */ default: ; /*@ code after 'default:' */ } /*@ statement indent off by -4 */ return( /*@ missing space after 'return', reported unless sloppy-spc */ x); } /*@ code before block-level '}' */ /* Here the tool should stop complaining apart from the below issues at EOF */ void f_looong_body() { ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; /*@ 2 essentially blank lines before, if !sloppy-spc */ } /*@ function body length > 200 lines */ #if X /*@0 unclosed #if */ struct t { /*@0 unclosed brace at decl/block level */ enum { /*@0 unclosed brace at enum/expression level */ v = (1 /*@0 unclosed parenthesis */ etyp /*@0 blank line follows just before EOF, if !sloppy-spc: */
./openssl/util/check-format-test-negatives.c
/* * Copyright 2007-2022 The OpenSSL Project Authors. All Rights Reserved. * Copyright Siemens AG 2015-2022 * * 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 */ /* * A collection of test cases where check-format.pl should not report issues. * There are some known false positives, though, which are marked below. */ #include <errno.h> /* should not report whitespace nits within <...> */ #define F \ void f() \ { \ int i; \ int j; \ \ return; \ } /* allow extra SPC in single-line comment */ /* * allow extra SPC in regular multi-line comment */ /*- * allow extra SPC in format-tagged multi-line comment */ /** allow extra '*' in comment opening */ /*! allow extra '!' in comment opening */ /* ** allow "**" as first non-space chars of a line within multi-line comment */ int f(void) /* * trailing multi-line comment */ { typedef int INT; void v; short b; char c; signed s; unsigned u; int i; long l; float f; double d; enum {} enu; struct {} stru; union {} un; auto a; extern e; static int stat; const int con; volatile int vola; register int reg; OSSL_x y, *p = params; int params[]; OSSL_PARAM * (* params []) [MAX + 1]; XY *(* fn)(int a, char b); /* * multi-line comment should not disturb detection of local decls */ BIO1 ***b; /* intra-line comment should not disturb detection of local decls */ unsigned k; /* intra-line comment should not disturb detection of end of local decls */ { int x; /* just decls in block */ } if (p != (unsigned char *) &(ctx->tmp[0])) { i -= (p - (unsigned char *) /* do not confuse with var decl */ &(ctx->tmp[0])); } { ctx->buf_off = 0; /* do not confuse with var decl */ return 0; } { ctx->buf_len = EVP_EncodeBlock((unsigned char *)ctx->buf, (unsigned char *)ctx->tmp, /* no decl */ ctx->tmp_len); } { EVP_EncodeFinal(ctx->base64, (unsigned char *)ctx->buf, &(ctx->len)); /* no decl */ /* push out the bytes */ goto again; } { f(1, (unsigned long)2); /* no decl */ x; } { char *pass_str = get_passwd(opt_srv_secret, "x"); if (pass_str != NULL) { cleanse(opt_srv_secret); res = OSSL_CMP_CTX_set1_secretValue(ctx, (unsigned char *)pass_str, strlen(pass_str)); clear_free(pass_str); } } } int g(void) { if (ctx == NULL) { /* non-leading end-of-line comment */ if (/* comment after '(' */ pem_name != NULL /* comment before ')' */) /* entire-line comment indent usually like for the following line */ return NULL; /* hanging indent also for this line after comment */ /* leading comment has same indentation as normal code */ stmt; /* entire-line comment may have same indent as normal code */ } for (i = 0; i < n; i++) for (; i < n; i++) for (i = 0; ; i++) for (i = 0;; i++) for (i = 0; i < n; ) for (i = 0; i < n;) ; for (i = 0; ; ) for (i = 0; ;) for (i = 0;; ) for (i = 0;;) for (; i < n; ) for (; j < n;) for (; ; i++) for (;; i++) ; for (;;) /* the only variant allowed in case of "empty" for (...) */ ; for (;;) ; /* should not trigger: space before ';' */ lab: ; /* should not trigger: space before ';' */ #if X if (1) /* bad style: just part of control structure depends on #if */ #else if (2) /*@ resulting false positive */ #endif c; /*@ resulting false positive */ if (1) if (2) c; else e; else f; do do 2; while (1); while (2); if (1) f(a, b); do 1; while (2); /*@ more than one stmt just to construct case */ if (1) f(a, b); else do 1; while (2); if (1) f(a, b); else do /*@ (non-brace) code before 'do' just to construct case */ 1; while (2); f1234(a, b); do /*@ (non-brace) code before 'do' just to construct case */ 1; while (2); if (1) f(a, b); do /*@ (non-brace) code before 'do' just to construct case */ 1; while (2); if (1) f(a, b); else do f(c, c); /*@ (non-brace) code after 'do' just to construct case */ while (2); if (1) f(a, b); else return; if (1) f(a, b); else /*@ (non-brace) code before 'else' just to construct case */ do 1; while (2); if (1) { /*@ brace after 'if' not on same line just to construct case */ c; d; } /* this comment is correctly indented if it refers to the following line */ d; if (1) { 2; } else /*@ no brace after 'else' just to construct case */ 3; do { } while (x); if (1) { 2; } else { 3; } if (4) 5; else 6; if (1) { if (2) { case MAC_TYPE_MAC: { EVP_MAC_CTX *new_mac_ctx; if (ctx->pkey == NULL) return 0; } break; default: /* This should be dead code */ return 0; } } if (expr_line1 == expr_line2 && expr_line3) { c1; } else { c; d; } if (expr_line1 == expr_line2 && expr_line3) hanging_stmt; } #define m \ do { /* should not be confused with function header followed by '{' */ \ } while (0) /* should not trigger: constant on LHS of comparison or assignment operator */ X509 *x509 = NULL; int y = a + 1 < b; int ret, was_NULL = *certs == NULL; /* should not trigger: missing space before ... */ float z = 1e-6 * (-1) * b[+6] * 1e+1 * (a)->f * (long)+1 - (tmstart.tv_sec + tmstart.tv_nsec * 1e-9); struct st = {-1, 0}; int x = (y <<= 1) + (z <= 5.0); const OPTIONS passwd_options[] = { {"aixmd5", OPT_AIXMD5, '-', "AIX MD5-based password algorithm"}, #if !defined(OPENSSL_NO_DES) && !defined(OPENSSL_NO_DEPRECATED_3_0) {"crypt", OPT_CRYPT, '-', "Standard Unix password algorithm (default)"}, #endif OPT_R_OPTIONS, {NULL} }; typedef * d(int) x; typedef (int) x; typedef (int)*() x; typedef *int * x; typedef OSSL_CMP_MSG *(*cmp_srv_process_cb_t) (OSSL_CMP_SRV_CTX *ctx, OSSL_CMP_MSG *msg) xx; #define IF(cond) if (cond) _Pragma("GCC diagnostic push") _Pragma("GCC diagnostic pop") #define CB_ERR_IF(cond, ctx, cert, depth, err) \ if ((cond) && ((depth) < 0 || verify_cb_cert(ctx, cert, depth, err) == 0)) \ return err static int verify_cb_crl(X509_STORE_CTX *ctx, int err) { ctx->error = err; return ctx->verify_cb(0, ctx); } #ifdef CMP_FALLBACK_EST # define CMP_FALLBACK_CERT_FILE "cert.pem" #endif #define X509_OBJECT_get0_X509(obj) \ ((obj) == NULL || (obj)->type != X509_LU_X509 ? NULL : (obj)->data.x509) #define X509_STORE_CTX_set_current_cert(ctx, x) { (ctx)->current_cert = (x); } #define X509_STORE_set_ex_data(ctx, idx, data) \ CRYPTO_set_ex_data(&(ctx)->ex_data, (idx), (data)) typedef int (*X509_STORE_CTX_check_revocation_fn)(X509_STORE_CTX *ctx); #define X509_STORE_CTX_set_error_depth(ctx, depth) \ { (ctx)->error_depth = (depth); } #define EVP_PKEY_up_ref(x) ((x)->references++) /* should not report missing blank line: */ DECLARE_STACK_OF(OPENSSL_CSTRING) bool UTIL_iterate_dir(int (*fn)(const char *file, void *arg), void *arg, const char *path, bool recursive); size_t UTIL_url_encode( size_t *size_needed ); size_t UTIL_url_encode(const char *source, char *destination, size_t destination_len, size_t *size_needed); #error well. oops. int f() { c; if (1) { c; } c; if (1) if (2) { /*@ brace after 'if' not on same line just to construct case */ c; } e; const usign = { 0xDF, { dd }, dd }; const unsign = { 0xDF, { dd }, dd }; } const unsigned char trans_id[OSSL_CMP_TRANSACTIONID_LENGTH] = { 0xDF, }; const unsigned char trans_id[OSSL_CMP_TRANSACTIONID_LENGTH] = { 0xDF, }; typedef int a; typedef struct { int a; } b; typedef enum { w = 0 } e_type; typedef struct { enum { w = 0 } e_type; enum { w = 0 } e_type; } e; struct s_type { enum e_type { w = 0 }; }; struct s_type { enum e_type { w = 0 }; enum e2_type { w = 0 }; }; #define X 1 + 1 #define Y /* .. */ 2 + 2 #define Z 3 + 3 * (*a++) static varref cmp_vars[] = { /* comment. comment? comment! */ {&opt_config}, {&opt_section}, {&opt_server}, {&opt_proxy}, {&opt_path}, }; #define SWITCH(x) \ switch (x) { \ case 0: \ break; \ default: \ break; \ } #define DEFINE_SET_GET_BASE_TEST(PREFIX, SETN, GETN, DUP, FIELD, TYPE, ERR, \ DEFAULT, NEW, FREE) \ static int execute_CTX_##SETN##_##GETN##_##FIELD( \ TEST_FIXTURE *fixture) \ { \ CTX *ctx = fixture->ctx; \ int (*set_fn)(CTX *ctx, TYPE) = \ (int (*)(CTX *ctx, TYPE))PREFIX##_##SETN##_##FIELD; \ /* comment */ \ } union un var; /* struct/union/enum in variable type */ struct provider_store_st *f() /* struct/union/enum in function return type */ { } static void f(struct pem_pass_data *data) /* struct/union/enum in arg list */ { } static void *fun(void) { if (pem_name != NULL) /* comment */ return NULL; label0: label1: /* allow special indent 1 for label at outermost level in body */ do { label2: size_t available_len, data_len; const char *curr = txt, *next = txt; char *tmp; { label3: } } while (1); char *intraline_string_with_comment_delimiters_and_dbl_space = "1 /*1"; char *multiline_string_with_comment_delimiters_and_dbl_space = "1 /*1\ 2222222\'22222222222222222\"222222222" "33333 /*3333333333" "44 /*44444444444\ 55555555555555\ 6666"; } ASN1_CHOICE(OSSL_CRMF_POPO) = { ASN1_IMP(OSSL_CRMF_POPO, value.raVerified, ASN1_NULL, 0), ASN1_EXP(OSSL_CRMF_POPO, value.keyAgreement, OSSL_CRMF_POPOPRIVKEY, 3) } ASN1_CHOICE_END(OSSL_CRMF_POPO) IMPLEMENT_ASN1_FUNCTIONS(OSSL_CRMF_POPO) ASN1_ADB(OSSL_CRMF_ATTRIBUTETYPEANDVALUE) = { ADB_ENTRY(NID_id_regCtrl_regToken, ASN1_SIMPLE(OSSL_CRMF_ATTRIBUTETYPEANDVALUE, value.regToken, ASN1_UTF8STRING)), } ASN1_ADB_END(OSSL_CRMF_ATTRIBUTETYPEANDVALUE, 0, type, 0, &attributetypeandvalue_default_tt, NULL); ASN1_ITEM_TEMPLATE(OSSL_CRMF_MSGS) = ASN1_EX_TEMPLATE_TYPE(ASN1_TFLG_SEQUENCE_OF, 0, OSSL_CRMF_MSGS, OSSL_CRMF_MSG) ASN1_ITEM_TEMPLATE_END(OSSL_CRMF_MSGS) void f_looong_body_200() { /* function body length up to 200 lines accepted */ ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; } void f_looong_body_201() { /* function body length > 200 lines, but LONG BODY marker present */ ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; }
./openssl/doc/designs/ddd/ddd-05-mem-nonblocking.c
#include <sys/poll.h> #include <openssl/ssl.h> /* * Demo 5: Client — Client Uses Memory BIO — Nonblocking * ===================================================== * * This is an example of (part of) an application which uses libssl in an * asynchronous, nonblocking fashion. The application passes memory BIOs to * OpenSSL, meaning that it controls both when data is read/written from an SSL * object on the decrypted side but also when encrypted data from the network is * shunted to/from OpenSSL. In this way OpenSSL is used as a pure state machine * which does not make its own network I/O calls. OpenSSL never sees or creates * any file descriptor for a network socket. The functions below show all * interactions with libssl the application makes, and would hypothetically be * linked into a larger application. */ typedef struct app_conn_st { SSL *ssl; BIO *ssl_bio, *net_bio; int rx_need_tx, tx_need_rx; } APP_CONN; /* * The application is initializing and wants an SSL_CTX which it will use for * some number of outgoing connections, which it creates in subsequent calls to * new_conn. The application may also call this function multiple times to * create multiple SSL_CTX. */ SSL_CTX *create_ssl_ctx(void) { SSL_CTX *ctx; #ifdef USE_QUIC ctx = SSL_CTX_new(OSSL_QUIC_client_method()); #else ctx = SSL_CTX_new(TLS_client_method()); #endif if (ctx == NULL) return NULL; /* Enable trust chain verification. */ SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, NULL); /* Load default root CA store. */ if (SSL_CTX_set_default_verify_paths(ctx) == 0) { SSL_CTX_free(ctx); return NULL; } return ctx; } /* * The application wants to create a new outgoing connection using a given * SSL_CTX. * * hostname is a string like "openssl.org" used for certificate validation. */ APP_CONN *new_conn(SSL_CTX *ctx, const char *bare_hostname) { BIO *ssl_bio, *internal_bio, *net_bio; APP_CONN *conn; SSL *ssl; #ifdef USE_QUIC static const unsigned char alpn[] = {5, 'd', 'u', 'm', 'm', 'y'}; #endif conn = calloc(1, sizeof(APP_CONN)); if (conn == NULL) return NULL; ssl = conn->ssl = SSL_new(ctx); if (ssl == NULL) { free(conn); return NULL; } SSL_set_connect_state(ssl); /* cannot fail */ #ifdef USE_QUIC if (BIO_new_bio_dgram_pair(&internal_bio, 0, &net_bio, 0) <= 0) { #else if (BIO_new_bio_pair(&internal_bio, 0, &net_bio, 0) <= 0) { #endif SSL_free(ssl); free(conn); return NULL; } SSL_set_bio(ssl, internal_bio, internal_bio); if (SSL_set1_host(ssl, bare_hostname) <= 0) { SSL_free(ssl); free(conn); return NULL; } if (SSL_set_tlsext_host_name(ssl, bare_hostname) <= 0) { SSL_free(ssl); free(conn); return NULL; } ssl_bio = BIO_new(BIO_f_ssl()); if (ssl_bio == NULL) { SSL_free(ssl); free(conn); return NULL; } if (BIO_set_ssl(ssl_bio, ssl, BIO_CLOSE) <= 0) { SSL_free(ssl); BIO_free(ssl_bio); return NULL; } #ifdef USE_QUIC /* Configure ALPN, which is required for QUIC. */ if (SSL_set_alpn_protos(ssl, alpn, sizeof(alpn))) { /* Note: SSL_set_alpn_protos returns 1 for failure. */ SSL_free(ssl); BIO_free(ssl_bio); return NULL; } #endif conn->ssl_bio = ssl_bio; conn->net_bio = net_bio; return conn; } /* * Non-blocking transmission. * * Returns -1 on error. Returns -2 if the function would block (corresponds to * EWOULDBLOCK). */ int tx(APP_CONN *conn, const void *buf, int buf_len) { int rc, l; l = BIO_write(conn->ssl_bio, buf, buf_len); if (l <= 0) { rc = SSL_get_error(conn->ssl, l); switch (rc) { case SSL_ERROR_WANT_READ: conn->tx_need_rx = 1; case SSL_ERROR_WANT_CONNECT: case SSL_ERROR_WANT_WRITE: return -2; default: return -1; } } else { conn->tx_need_rx = 0; } return l; } /* * Non-blocking reception. * * Returns -1 on error. Returns -2 if the function would block (corresponds to * EWOULDBLOCK). */ int rx(APP_CONN *conn, void *buf, int buf_len) { int rc, l; l = BIO_read(conn->ssl_bio, buf, buf_len); if (l <= 0) { rc = SSL_get_error(conn->ssl, l); switch (rc) { case SSL_ERROR_WANT_WRITE: conn->rx_need_tx = 1; case SSL_ERROR_WANT_READ: return -2; default: return -1; } } else { conn->rx_need_tx = 0; } return l; } /* * Called to get data which has been enqueued for transmission to the network * by OpenSSL. For QUIC, this always outputs a single datagram. * * IMPORTANT (QUIC): If buf_len is inadequate to hold the datagram, it is truncated * (similar to read(2)). A buffer size of at least 1472 must be used by default * to guarantee this does not occur. */ int read_net_tx(APP_CONN *conn, void *buf, int buf_len) { return BIO_read(conn->net_bio, buf, buf_len); } /* * Called to feed data which has been received from the network to OpenSSL. * * QUIC: buf must contain the entirety of a single datagram. It will be consumed * entirely (return value == buf_len) or not at all. */ int write_net_rx(APP_CONN *conn, const void *buf, int buf_len) { return BIO_write(conn->net_bio, buf, buf_len); } /* * Determine how much data can be written to the network RX BIO. */ size_t net_rx_space(APP_CONN *conn) { return BIO_ctrl_get_write_guarantee(conn->net_bio); } /* * Determine how much data is currently queued for transmission in the network * TX BIO. */ size_t net_tx_avail(APP_CONN *conn) { return BIO_ctrl_pending(conn->net_bio); } /* * These functions returns zero or more of: * * POLLIN: The SSL state machine is interested in socket readability events. * * POLLOUT: The SSL state machine is interested in socket writeability events. * * POLLERR: The SSL state machine is interested in socket error events. * * get_conn_pending_tx returns events which may cause SSL_write to make * progress and get_conn_pending_rx returns events which may cause SSL_read * to make progress. */ int get_conn_pending_tx(APP_CONN *conn) { #ifdef USE_QUIC return (SSL_net_read_desired(conn->ssl) ? POLLIN : 0) | (SSL_net_write_desired(conn->ssl) ? POLLOUT : 0) | POLLERR; #else return (conn->tx_need_rx ? POLLIN : 0) | POLLOUT | POLLERR; #endif } int get_conn_pending_rx(APP_CONN *conn) { #ifdef USE_QUIC return get_conn_pending_tx(conn); #else return (conn->rx_need_tx ? POLLOUT : 0) | POLLIN | POLLERR; #endif } /* * The application wants to close the connection and free bookkeeping * structures. */ void teardown(APP_CONN *conn) { BIO_free_all(conn->ssl_bio); BIO_free_all(conn->net_bio); free(conn); } /* * The application is shutting down and wants to free a previously * created SSL_CTX. */ void teardown_ctx(SSL_CTX *ctx) { SSL_CTX_free(ctx); } /* * ============================================================================ * Example driver for the above code. This is just to demonstrate that the code * works and is not intended to be representative of a real application. */ #include <sys/types.h> #include <sys/socket.h> #include <sys/signal.h> #include <netdb.h> #include <unistd.h> #include <fcntl.h> #include <errno.h> static int pump(APP_CONN *conn, int fd, int events, int timeout) { int l, l2; char buf[2048]; /* QUIC: would need to be changed if < 1472 */ size_t wspace; struct pollfd pfd = {0}; pfd.fd = fd; pfd.events = (events & (POLLIN | POLLERR)); if (net_rx_space(conn) == 0) pfd.events &= ~POLLIN; if (net_tx_avail(conn) > 0) pfd.events |= POLLOUT; if ((pfd.events & (POLLIN|POLLOUT)) == 0) return 1; if (poll(&pfd, 1, timeout) == 0) return -1; if (pfd.revents & POLLIN) { while ((wspace = net_rx_space(conn)) > 0) { l = read(fd, buf, wspace > sizeof(buf) ? sizeof(buf) : wspace); if (l <= 0) { switch (errno) { case EAGAIN: goto stop; default: if (l == 0) /* EOF */ goto stop; fprintf(stderr, "error on read: %d\n", errno); return -1; } break; } l2 = write_net_rx(conn, buf, l); if (l2 < l) fprintf(stderr, "short write %d %d\n", l2, l); } stop:; } if (pfd.revents & POLLOUT) { for (;;) { l = read_net_tx(conn, buf, sizeof(buf)); if (l <= 0) break; l2 = write(fd, buf, l); if (l2 < l) fprintf(stderr, "short read %d %d\n", l2, l); } } return 1; } int main(int argc, char **argv) { int rc, fd = -1, res = 1; static char tx_msg[300]; const char *tx_p = tx_msg; char rx_buf[2048]; int l, tx_len; int timeout = 2000 /* ms */; APP_CONN *conn = NULL; struct addrinfo hints = {0}, *result = NULL; SSL_CTX *ctx = NULL; if (argc < 3) { fprintf(stderr, "usage: %s host port\n", argv[0]); goto fail; } tx_len = snprintf(tx_msg, sizeof(tx_msg), "GET / HTTP/1.0\r\nHost: %s\r\n\r\n", argv[1]); ctx = create_ssl_ctx(); if (ctx == NULL) { fprintf(stderr, "cannot create SSL context\n"); goto fail; } hints.ai_family = AF_INET; hints.ai_socktype = SOCK_STREAM; hints.ai_flags = AI_PASSIVE; rc = getaddrinfo(argv[1], argv[2], &hints, &result); if (rc < 0) { fprintf(stderr, "cannot resolve\n"); goto fail; } signal(SIGPIPE, SIG_IGN); #ifdef USE_QUIC fd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); #else fd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); #endif if (fd < 0) { fprintf(stderr, "cannot create socket\n"); goto fail; } rc = connect(fd, result->ai_addr, result->ai_addrlen); if (rc < 0) { fprintf(stderr, "cannot connect\n"); goto fail; } rc = fcntl(fd, F_SETFL, O_NONBLOCK); if (rc < 0) { fprintf(stderr, "cannot make socket nonblocking\n"); goto fail; } conn = new_conn(ctx, argv[1]); if (conn == NULL) { fprintf(stderr, "cannot establish connection\n"); goto fail; } /* TX */ while (tx_len != 0) { l = tx(conn, tx_p, tx_len); if (l > 0) { tx_p += l; tx_len -= l; } else if (l == -1) { fprintf(stderr, "tx error\n"); } else if (l == -2) { if (pump(conn, fd, get_conn_pending_tx(conn), timeout) != 1) { fprintf(stderr, "pump error\n"); goto fail; } } } /* RX */ for (;;) { l = rx(conn, rx_buf, sizeof(rx_buf)); if (l > 0) { fwrite(rx_buf, 1, l, stdout); } else if (l == -1) { break; } else if (l == -2) { if (pump(conn, fd, get_conn_pending_rx(conn), timeout) != 1) { fprintf(stderr, "pump error\n"); goto fail; } } } res = 0; fail: if (conn != NULL) teardown(conn); if (ctx != NULL) teardown_ctx(ctx); if (result != NULL) freeaddrinfo(result); return res; }
./openssl/doc/designs/ddd/ddd-06-mem-uv.c
#include <sys/poll.h> #include <openssl/ssl.h> #include <uv.h> #include <assert.h> #ifdef USE_QUIC # include <sys/time.h> #endif typedef struct app_conn_st APP_CONN; typedef struct upper_write_op_st UPPER_WRITE_OP; typedef struct lower_write_op_st LOWER_WRITE_OP; typedef void (app_connect_cb)(APP_CONN *conn, int status, void *arg); typedef void (app_write_cb)(APP_CONN *conn, int status, void *arg); typedef void (app_read_cb)(APP_CONN *conn, void *buf, size_t buf_len, void *arg); #ifdef USE_QUIC static void set_timer(APP_CONN *conn); #else static void tcp_connect_done(uv_connect_t *tcp_connect, int status); #endif static void net_connect_fail_close_done(uv_handle_t *handle); static int handshake_ssl(APP_CONN *conn); static void flush_write_buf(APP_CONN *conn); static void set_rx(APP_CONN *conn); static int try_write(APP_CONN *conn, UPPER_WRITE_OP *op); static void handle_pending_writes(APP_CONN *conn); static int write_deferred(APP_CONN *conn, const void *buf, size_t buf_len, app_write_cb *cb, void *arg); static void teardown_continued(uv_handle_t *handle); static int setup_ssl(APP_CONN *conn, const char *hostname); #ifdef USE_QUIC static inline int timeval_to_ms(const struct timeval *t) { return t->tv_sec*1000 + t->tv_usec/1000; } #endif /* * Structure to track an application-level write request. Only created * if SSL_write does not accept the data immediately, typically because * it is in WANT_READ. */ struct upper_write_op_st { struct upper_write_op_st *prev, *next; const uint8_t *buf; size_t buf_len, written; APP_CONN *conn; app_write_cb *cb; void *cb_arg; }; /* * Structure to track a network-level write request. */ struct lower_write_op_st { #ifdef USE_QUIC uv_udp_send_t w; #else uv_write_t w; #endif uv_buf_t b; uint8_t *buf; APP_CONN *conn; }; /* * Application connection object. */ struct app_conn_st { SSL_CTX *ctx; SSL *ssl; BIO *net_bio; #ifdef USE_QUIC uv_udp_t udp; uv_timer_t timer; #else uv_stream_t *stream; uv_tcp_t tcp; uv_connect_t tcp_connect; #endif app_connect_cb *app_connect_cb; /* called once handshake is done */ void *app_connect_arg; app_read_cb *app_read_cb; /* application's on-RX callback */ void *app_read_arg; const char *hostname; char init_handshake, done_handshake, closed; char *teardown_done; UPPER_WRITE_OP *pending_upper_write_head, *pending_upper_write_tail; }; /* * The application is initializing and wants an SSL_CTX which it will use for * some number of outgoing connections, which it creates in subsequent calls to * new_conn. The application may also call this function multiple times to * create multiple SSL_CTX. */ SSL_CTX *create_ssl_ctx(void) { SSL_CTX *ctx; #ifdef USE_QUIC ctx = SSL_CTX_new(OSSL_QUIC_client_method()); #else ctx = SSL_CTX_new(TLS_client_method()); #endif if (ctx == NULL) return NULL; /* Enable trust chain verification. */ SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, NULL); /* Load default root CA store. */ if (SSL_CTX_set_default_verify_paths(ctx) == 0) { SSL_CTX_free(ctx); return NULL; } return ctx; } /* * The application wants to create a new outgoing connection using a given * SSL_CTX. An outgoing TCP connection is started and the callback is called * asynchronously when the TLS handshake is complete. * * hostname is a string like "openssl.org" used for certificate validation. */ APP_CONN *new_conn(SSL_CTX *ctx, const char *hostname, struct sockaddr *sa, socklen_t sa_len, app_connect_cb *cb, void *arg) { int rc; APP_CONN *conn = NULL; conn = calloc(1, sizeof(APP_CONN)); if (!conn) return NULL; #ifdef USE_QUIC uv_udp_init(uv_default_loop(), &conn->udp); conn->udp.data = conn; uv_timer_init(uv_default_loop(), &conn->timer); conn->timer.data = conn; #else uv_tcp_init(uv_default_loop(), &conn->tcp); conn->tcp.data = conn; conn->stream = (uv_stream_t *)&conn->tcp; #endif conn->app_connect_cb = cb; conn->app_connect_arg = arg; #ifdef USE_QUIC rc = uv_udp_connect(&conn->udp, sa); #else conn->tcp_connect.data = conn; rc = uv_tcp_connect(&conn->tcp_connect, &conn->tcp, sa, tcp_connect_done); #endif if (rc < 0) { #ifdef USE_QUIC uv_close((uv_handle_t *)&conn->udp, net_connect_fail_close_done); #else uv_close((uv_handle_t *)&conn->tcp, net_connect_fail_close_done); #endif return NULL; } conn->ctx = ctx; conn->hostname = hostname; #ifdef USE_QUIC rc = setup_ssl(conn, hostname); if (rc < 0) { uv_close((uv_handle_t *)&conn->udp, net_connect_fail_close_done); return NULL; } #endif return conn; } /* * The application wants to start reading from the SSL stream. * The callback is called whenever data is available. */ int app_read_start(APP_CONN *conn, app_read_cb *cb, void *arg) { conn->app_read_cb = cb; conn->app_read_arg = arg; set_rx(conn); return 0; } /* * The application wants to write. The callback is called once the * write is complete. The callback should free the buffer. */ int app_write(APP_CONN *conn, const void *buf, size_t buf_len, app_write_cb *cb, void *arg) { write_deferred(conn, buf, buf_len, cb, arg); handle_pending_writes(conn); return buf_len; } /* * The application wants to close the connection and free bookkeeping * structures. */ void teardown(APP_CONN *conn) { char teardown_done = 0; if (conn == NULL) return; BIO_free_all(conn->net_bio); SSL_free(conn->ssl); #ifndef USE_QUIC uv_cancel((uv_req_t *)&conn->tcp_connect); #endif conn->teardown_done = &teardown_done; #ifdef USE_QUIC uv_close((uv_handle_t *)&conn->udp, teardown_continued); uv_close((uv_handle_t *)&conn->timer, teardown_continued); #else uv_close((uv_handle_t *)conn->stream, teardown_continued); #endif /* Just wait synchronously until teardown completes. */ #ifdef USE_QUIC while (teardown_done < 2) #else while (!teardown_done) #endif uv_run(uv_default_loop(), UV_RUN_DEFAULT); } /* * The application is shutting down and wants to free a previously * created SSL_CTX. */ void teardown_ctx(SSL_CTX *ctx) { SSL_CTX_free(ctx); } /* * ============================================================================ * Internal implementation functions. */ static void enqueue_upper_write_op(APP_CONN *conn, UPPER_WRITE_OP *op) { op->prev = conn->pending_upper_write_tail; if (op->prev) op->prev->next = op; conn->pending_upper_write_tail = op; if (conn->pending_upper_write_head == NULL) conn->pending_upper_write_head = op; } static void dequeue_upper_write_op(APP_CONN *conn) { if (conn->pending_upper_write_head == NULL) return; if (conn->pending_upper_write_head->next == NULL) { conn->pending_upper_write_head = NULL; conn->pending_upper_write_tail = NULL; } else { conn->pending_upper_write_head = conn->pending_upper_write_head->next; conn->pending_upper_write_head->prev = NULL; } } static void net_read_alloc(uv_handle_t *handle, size_t suggested_size, uv_buf_t *buf) { #ifdef USE_QUIC if (suggested_size < 1472) suggested_size = 1472; #endif buf->base = malloc(suggested_size); buf->len = suggested_size; } static void on_rx_push(APP_CONN *conn) { int srd, rc; int buf_len = 4096; do { if (!conn->app_read_cb) return; void *buf = malloc(buf_len); if (!buf) return; srd = SSL_read(conn->ssl, buf, buf_len); flush_write_buf(conn); if (srd <= 0) { rc = SSL_get_error(conn->ssl, srd); if (rc == SSL_ERROR_WANT_READ) { free(buf); return; } } conn->app_read_cb(conn, buf, srd, conn->app_read_arg); } while (srd == buf_len); } static void net_error(APP_CONN *conn) { conn->closed = 1; set_rx(conn); if (conn->app_read_cb) conn->app_read_cb(conn, NULL, 0, conn->app_read_arg); } static void handle_pending_writes(APP_CONN *conn) { int rc; if (conn->pending_upper_write_head == NULL) return; do { UPPER_WRITE_OP *op = conn->pending_upper_write_head; rc = try_write(conn, op); if (rc <= 0) break; dequeue_upper_write_op(conn); free(op); } while (conn->pending_upper_write_head != NULL); set_rx(conn); } #ifdef USE_QUIC static void net_read_done(uv_udp_t *stream, ssize_t nr, const uv_buf_t *buf, const struct sockaddr *addr, unsigned int flags) #else static void net_read_done(uv_stream_t *stream, ssize_t nr, const uv_buf_t *buf) #endif { int rc; APP_CONN *conn = (APP_CONN *)stream->data; if (nr < 0) { free(buf->base); net_error(conn); return; } if (nr > 0) { int wr = BIO_write(conn->net_bio, buf->base, nr); assert(wr == nr); } free(buf->base); if (!conn->done_handshake) { rc = handshake_ssl(conn); if (rc < 0) { fprintf(stderr, "handshake error: %d\n", rc); return; } if (!conn->done_handshake) return; } handle_pending_writes(conn); on_rx_push(conn); } static void set_rx(APP_CONN *conn) { #ifdef USE_QUIC if (!conn->closed) uv_udp_recv_start(&conn->udp, net_read_alloc, net_read_done); else uv_udp_recv_stop(&conn->udp); #else if (!conn->closed && (conn->app_read_cb || (!conn->done_handshake && conn->init_handshake) || conn->pending_upper_write_head != NULL)) uv_read_start(conn->stream, net_read_alloc, net_read_done); else uv_read_stop(conn->stream); #endif } #ifdef USE_QUIC static void net_write_done(uv_udp_send_t *req, int status) #else static void net_write_done(uv_write_t *req, int status) #endif { LOWER_WRITE_OP *op = (LOWER_WRITE_OP *)req->data; APP_CONN *conn = op->conn; if (status < 0) { fprintf(stderr, "UV write failed %d\n", status); return; } free(op->buf); free(op); flush_write_buf(conn); } static void flush_write_buf(APP_CONN *conn) { int rc, rd; LOWER_WRITE_OP *op; uint8_t *buf; buf = malloc(4096); if (!buf) return; rd = BIO_read(conn->net_bio, buf, 4096); if (rd <= 0) { free(buf); return; } op = calloc(1, sizeof(LOWER_WRITE_OP)); if (!op) return; op->buf = buf; op->conn = conn; op->w.data = op; op->b.base = (char *)buf; op->b.len = rd; #ifdef USE_QUIC rc = uv_udp_send(&op->w, &conn->udp, &op->b, 1, NULL, net_write_done); #else rc = uv_write(&op->w, conn->stream, &op->b, 1, net_write_done); #endif if (rc < 0) { free(buf); free(op); fprintf(stderr, "UV write failed\n"); return; } } static void handshake_done_ssl(APP_CONN *conn) { #ifdef USE_QUIC set_timer(conn); #endif conn->app_connect_cb(conn, 0, conn->app_connect_arg); } static int handshake_ssl(APP_CONN *conn) { int rc, rcx; conn->init_handshake = 1; rc = SSL_do_handshake(conn->ssl); if (rc > 0) { conn->done_handshake = 1; handshake_done_ssl(conn); set_rx(conn); return 0; } flush_write_buf(conn); rcx = SSL_get_error(conn->ssl, rc); if (rcx == SSL_ERROR_WANT_READ) { set_rx(conn); return 0; } fprintf(stderr, "Handshake error: %d\n", rcx); return -rcx; } static int setup_ssl(APP_CONN *conn, const char *hostname) { BIO *internal_bio = NULL, *net_bio = NULL; SSL *ssl = NULL; #ifdef USE_QUIC static const unsigned char alpn[] = {5, 'd', 'u', 'm', 'm', 'y'}; #endif ssl = SSL_new(conn->ctx); if (!ssl) return -1; SSL_set_connect_state(ssl); #ifdef USE_QUIC if (BIO_new_bio_dgram_pair(&internal_bio, 0, &net_bio, 0) <= 0) { SSL_free(ssl); return -1; } #else if (BIO_new_bio_pair(&internal_bio, 0, &net_bio, 0) <= 0) { SSL_free(ssl); return -1; } #endif SSL_set_bio(ssl, internal_bio, internal_bio); if (SSL_set1_host(ssl, hostname) <= 0) { SSL_free(ssl); return -1; } if (SSL_set_tlsext_host_name(ssl, hostname) <= 0) { SSL_free(ssl); return -1; } #ifdef USE_QUIC /* Configure ALPN, which is required for QUIC. */ if (SSL_set_alpn_protos(ssl, alpn, sizeof(alpn))) { /* Note: SSL_set_alpn_protos returns 1 for failure. */ SSL_free(ssl); return -1; } #endif conn->net_bio = net_bio; conn->ssl = ssl; return handshake_ssl(conn); } #ifndef USE_QUIC static void tcp_connect_done(uv_connect_t *tcp_connect, int status) { int rc; APP_CONN *conn = (APP_CONN *)tcp_connect->data; if (status < 0) { uv_stop(uv_default_loop()); return; } rc = setup_ssl(conn, conn->hostname); if (rc < 0) { fprintf(stderr, "cannot init SSL\n"); uv_stop(uv_default_loop()); return; } } #endif static void net_connect_fail_close_done(uv_handle_t *handle) { APP_CONN *conn = (APP_CONN *)handle->data; free(conn); } #ifdef USE_QUIC static void timer_done(uv_timer_t *timer) { APP_CONN *conn = (APP_CONN *)timer->data; SSL_handle_events(conn->ssl); handle_pending_writes(conn); flush_write_buf(conn); set_rx(conn); set_timer(conn); /* repeat timer */ } static void set_timer(APP_CONN *conn) { struct timeval tv; int ms, is_infinite; if (!SSL_get_event_timeout(conn->ssl, &tv, &is_infinite)) return; ms = is_infinite ? -1 : timeval_to_ms(&tv); if (ms > 0) uv_timer_start(&conn->timer, timer_done, ms, 0); } #endif static int try_write(APP_CONN *conn, UPPER_WRITE_OP *op) { int rc, rcx; size_t written = op->written; while (written < op->buf_len) { rc = SSL_write(conn->ssl, op->buf + written, op->buf_len - written); if (rc <= 0) { rcx = SSL_get_error(conn->ssl, rc); if (rcx == SSL_ERROR_WANT_READ) { op->written = written; return 0; } else { if (op->cb != NULL) op->cb(conn, -rcx, op->cb_arg); return 1; /* op should be freed */ } } written += rc; } if (op->cb != NULL) op->cb(conn, 0, op->cb_arg); flush_write_buf(conn); return 1; /* op should be freed */ } static int write_deferred(APP_CONN *conn, const void *buf, size_t buf_len, app_write_cb *cb, void *arg) { UPPER_WRITE_OP *op = calloc(1, sizeof(UPPER_WRITE_OP)); if (!op) return -1; op->buf = buf; op->buf_len = buf_len; op->conn = conn; op->cb = cb; op->cb_arg = arg; enqueue_upper_write_op(conn, op); set_rx(conn); flush_write_buf(conn); return buf_len; } static void teardown_continued(uv_handle_t *handle) { APP_CONN *conn = (APP_CONN *)handle->data; UPPER_WRITE_OP *op, *next_op; char *teardown_done = conn->teardown_done; #ifdef USE_QUIC if (++*teardown_done < 2) return; #endif for (op=conn->pending_upper_write_head; op; op=next_op) { next_op = op->next; free(op); } free(conn); #ifndef USE_QUIC *teardown_done = 1; #endif } /* * ============================================================================ * Example driver for the above code. This is just to demonstrate that the code * works and is not intended to be representative of a real application. */ static void post_read(APP_CONN *conn, void *buf, size_t buf_len, void *arg) { if (!buf_len) { free(buf); uv_stop(uv_default_loop()); return; } fwrite(buf, 1, buf_len, stdout); free(buf); } static void post_write_get(APP_CONN *conn, int status, void *arg) { if (status < 0) { fprintf(stderr, "write failed: %d\n", status); return; } app_read_start(conn, post_read, NULL); } char tx_msg[300]; int mlen; static void post_connect(APP_CONN *conn, int status, void *arg) { int wr; if (status < 0) { fprintf(stderr, "failed to connect: %d\n", status); uv_stop(uv_default_loop()); return; } wr = app_write(conn, tx_msg, mlen, post_write_get, NULL); if (wr < mlen) { fprintf(stderr, "error writing request"); return; } } int main(int argc, char **argv) { int rc = 1; SSL_CTX *ctx = NULL; APP_CONN *conn = NULL; struct addrinfo hints = {0}, *result = NULL; if (argc < 3) { fprintf(stderr, "usage: %s host port\n", argv[0]); goto fail; } mlen = snprintf(tx_msg, sizeof(tx_msg), "GET / HTTP/1.0\r\nHost: %s\r\n\r\n", argv[1]); ctx = create_ssl_ctx(); if (!ctx) goto fail; hints.ai_family = AF_INET; hints.ai_socktype = SOCK_STREAM; hints.ai_flags = AI_PASSIVE; rc = getaddrinfo(argv[1], argv[2], &hints, &result); if (rc < 0) { fprintf(stderr, "cannot resolve\n"); goto fail; } conn = new_conn(ctx, argv[1], result->ai_addr, result->ai_addrlen, post_connect, NULL); if (!conn) goto fail; uv_run(uv_default_loop(), UV_RUN_DEFAULT); rc = 0; fail: teardown(conn); freeaddrinfo(result); uv_loop_close(uv_default_loop()); teardown_ctx(ctx); }
./openssl/doc/designs/ddd/ddd-02-conn-nonblocking.c
#include <sys/poll.h> #include <openssl/ssl.h> /* * Demo 2: Client — Managed Connection — Nonblocking * ============================================================== * * This is an example of (part of) an application which uses libssl in an * asynchronous, nonblocking fashion. The functions show all interactions with * libssl the application makes, and would hypothetically be linked into a * larger application. * * In this example, libssl still makes syscalls directly using an fd, which is * configured in nonblocking mode. As such, the application can still be * abstracted from the details of what that fd is (is it a TCP socket? is it a * UDP socket?); this code passes the application an fd and the application * simply calls back into this code when poll()/etc. indicates it is ready. */ typedef struct app_conn_st { SSL *ssl; BIO *ssl_bio; int rx_need_tx, tx_need_rx; } APP_CONN; /* * The application is initializing and wants an SSL_CTX which it will use for * some number of outgoing connections, which it creates in subsequent calls to * new_conn. The application may also call this function multiple times to * create multiple SSL_CTX. */ SSL_CTX *create_ssl_ctx(void) { SSL_CTX *ctx; #ifdef USE_QUIC ctx = SSL_CTX_new(OSSL_QUIC_client_method()); #else ctx = SSL_CTX_new(TLS_client_method()); #endif if (ctx == NULL) return NULL; /* Enable trust chain verification. */ SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, NULL); /* Load default root CA store. */ if (SSL_CTX_set_default_verify_paths(ctx) == 0) { SSL_CTX_free(ctx); return NULL; } return ctx; } /* * The application wants to create a new outgoing connection using a given * SSL_CTX. * * hostname is a string like "openssl.org:443" or "[::1]:443". */ APP_CONN *new_conn(SSL_CTX *ctx, const char *hostname) { APP_CONN *conn; BIO *out, *buf; SSL *ssl = NULL; const char *bare_hostname; #ifdef USE_QUIC static const unsigned char alpn[] = {5, 'd', 'u', 'm', 'm', 'y'}; #endif conn = calloc(1, sizeof(APP_CONN)); if (conn == NULL) return NULL; out = BIO_new_ssl_connect(ctx); if (out == NULL) { free(conn); return NULL; } if (BIO_get_ssl(out, &ssl) == 0) { BIO_free_all(out); free(conn); return NULL; } /* * NOTE: QUIC cannot operate with a buffering BIO between the QUIC SSL * object in the network. In this case, the call to BIO_push() is not * supported by the QUIC SSL object and will be ignored, thus this code * works without removing this line. However, the buffering BIO is not * actually used as a result and should be removed when adapting code to use * QUIC. * * Setting a buffer as the underlying BIO on the QUIC SSL object using * SSL_set_bio() will not work, though BIO_s_dgram_pair is available for * buffering the input and output to the QUIC SSL object on the network side * if desired. */ buf = BIO_new(BIO_f_buffer()); if (buf == NULL) { BIO_free_all(out); free(conn); return NULL; } BIO_push(out, buf); if (BIO_set_conn_hostname(out, hostname) == 0) { BIO_free_all(out); free(conn); return NULL; } /* Returns the parsed hostname extracted from the hostname:port string. */ bare_hostname = BIO_get_conn_hostname(out); if (bare_hostname == NULL) { BIO_free_all(out); free(conn); return NULL; } /* Tell the SSL object the hostname to check certificates against. */ if (SSL_set1_host(ssl, bare_hostname) <= 0) { BIO_free_all(out); free(conn); return NULL; } #ifdef USE_QUIC /* Configure ALPN, which is required for QUIC. */ if (SSL_set_alpn_protos(ssl, alpn, sizeof(alpn))) { /* Note: SSL_set_alpn_protos returns 1 for failure. */ BIO_free_all(out); return NULL; } #endif /* Make the BIO nonblocking. */ BIO_set_nbio(out, 1); conn->ssl_bio = out; return conn; } /* * Non-blocking transmission. * * Returns -1 on error. Returns -2 if the function would block (corresponds to * EWOULDBLOCK). */ int tx(APP_CONN *conn, const void *buf, int buf_len) { int l; conn->tx_need_rx = 0; l = BIO_write(conn->ssl_bio, buf, buf_len); if (l <= 0) { if (BIO_should_retry(conn->ssl_bio)) { conn->tx_need_rx = BIO_should_read(conn->ssl_bio); return -2; } else { return -1; } } return l; } /* * Non-blocking reception. * * Returns -1 on error. Returns -2 if the function would block (corresponds to * EWOULDBLOCK). */ int rx(APP_CONN *conn, void *buf, int buf_len) { int l; conn->rx_need_tx = 0; l = BIO_read(conn->ssl_bio, buf, buf_len); if (l <= 0) { if (BIO_should_retry(conn->ssl_bio)) { conn->rx_need_tx = BIO_should_write(conn->ssl_bio); return -2; } else { return -1; } } return l; } /* * The application wants to know a fd it can poll on to determine when the * SSL state machine needs to be pumped. */ int get_conn_fd(APP_CONN *conn) { #ifdef USE_QUIC BIO_POLL_DESCRIPTOR d; if (!BIO_get_rpoll_descriptor(conn->ssl_bio, &d)) return -1; return d.value.fd; #else return BIO_get_fd(conn->ssl_bio, NULL); #endif } /* * These functions returns zero or more of: * * POLLIN: The SSL state machine is interested in socket readability events. * * POLLOUT: The SSL state machine is interested in socket writeability events. * * POLLERR: The SSL state machine is interested in socket error events. * * get_conn_pending_tx returns events which may cause SSL_write to make * progress and get_conn_pending_rx returns events which may cause SSL_read * to make progress. */ int get_conn_pending_tx(APP_CONN *conn) { #ifdef USE_QUIC return (SSL_net_read_desired(conn->ssl) ? POLLIN : 0) | (SSL_net_write_desired(conn->ssl) ? POLLOUT : 0) | POLLERR; #else return (conn->tx_need_rx ? POLLIN : 0) | POLLOUT | POLLERR; #endif } int get_conn_pending_rx(APP_CONN *conn) { #ifdef USE_QUIC return get_conn_pending_tx(conn); #else return (conn->rx_need_tx ? POLLOUT : 0) | POLLIN | POLLERR; #endif } #ifdef USE_QUIC /* * Returns the number of milliseconds after which some call to libssl must be * made. Any call (BIO_read/BIO_write/BIO_pump) will do. Returns -1 if * there is no need for such a call. This may change after the next call * to libssl. */ static inline int timeval_to_ms(const struct timeval *t); int get_conn_pump_timeout(APP_CONN *conn) { struct timeval tv; int is_infinite; if (!SSL_get_event_timeout(conn->ssl, &tv, &is_infinite)) return -1; return is_infinite ? -1 : timeval_to_ms(&tv); } /* * Called to advance internals of libssl state machines without having to * perform an application-level read/write. */ void pump(APP_CONN *conn) { SSL_handle_events(conn->ssl); } #endif /* * The application wants to close the connection and free bookkeeping * structures. */ void teardown(APP_CONN *conn) { BIO_free_all(conn->ssl_bio); free(conn); } /* * The application is shutting down and wants to free a previously * created SSL_CTX. */ void teardown_ctx(SSL_CTX *ctx) { SSL_CTX_free(ctx); } /* * ============================================================================ * Example driver for the above code. This is just to demonstrate that the code * works and is not intended to be representative of a real application. */ #include <sys/time.h> static inline void ms_to_timeval(struct timeval *t, int ms) { t->tv_sec = ms < 0 ? -1 : ms/1000; t->tv_usec = ms < 0 ? 0 : (ms%1000)*1000; } static inline int timeval_to_ms(const struct timeval *t) { return t->tv_sec*1000 + t->tv_usec/1000; } int main(int argc, char **argv) { static char tx_msg[384], host_port[300]; const char *tx_p = tx_msg; char rx_buf[2048]; int res = 1, l, tx_len; #ifdef USE_QUIC struct timeval timeout; #else int timeout = 2000 /* ms */; #endif APP_CONN *conn = NULL; SSL_CTX *ctx = NULL; #ifdef USE_QUIC ms_to_timeval(&timeout, 2000); #endif if (argc < 3) { fprintf(stderr, "usage: %s host port\n", argv[0]); goto fail; } snprintf(host_port, sizeof(host_port), "%s:%s", argv[1], argv[2]); tx_len = snprintf(tx_msg, sizeof(tx_msg), "GET / HTTP/1.0\r\nHost: %s\r\n\r\n", argv[1]); ctx = create_ssl_ctx(); if (ctx == NULL) { fprintf(stderr, "cannot create SSL context\n"); goto fail; } conn = new_conn(ctx, host_port); if (conn == NULL) { fprintf(stderr, "cannot establish connection\n"); goto fail; } /* TX */ while (tx_len != 0) { l = tx(conn, tx_p, tx_len); if (l > 0) { tx_p += l; tx_len -= l; } else if (l == -1) { fprintf(stderr, "tx error\n"); } else if (l == -2) { #ifdef USE_QUIC struct timeval start, now, deadline, t; #endif struct pollfd pfd = {0}; #ifdef USE_QUIC ms_to_timeval(&t, get_conn_pump_timeout(conn)); if (t.tv_sec < 0 || timercmp(&t, &timeout, >)) t = timeout; gettimeofday(&start, NULL); timeradd(&start, &timeout, &deadline); #endif pfd.fd = get_conn_fd(conn); pfd.events = get_conn_pending_tx(conn); #ifdef USE_QUIC if (poll(&pfd, 1, timeval_to_ms(&t)) == 0) #else if (poll(&pfd, 1, timeout) == 0) #endif { #ifdef USE_QUIC pump(conn); gettimeofday(&now, NULL); if (timercmp(&now, &deadline, >=)) #endif { fprintf(stderr, "tx timeout\n"); goto fail; } } } } /* RX */ for (;;) { l = rx(conn, rx_buf, sizeof(rx_buf)); if (l > 0) { fwrite(rx_buf, 1, l, stdout); } else if (l == -1) { break; } else if (l == -2) { #ifdef USE_QUIC struct timeval start, now, deadline, t; #endif struct pollfd pfd = {0}; #ifdef USE_QUIC ms_to_timeval(&t, get_conn_pump_timeout(conn)); if (t.tv_sec < 0 || timercmp(&t, &timeout, >)) t = timeout; gettimeofday(&start, NULL); timeradd(&start, &timeout, &deadline); #endif pfd.fd = get_conn_fd(conn); pfd.events = get_conn_pending_rx(conn); #ifdef USE_QUIC if (poll(&pfd, 1, timeval_to_ms(&t)) == 0) #else if (poll(&pfd, 1, timeout) == 0) #endif { #ifdef USE_QUIC pump(conn); gettimeofday(&now, NULL); if (timercmp(&now, &deadline, >=)) #endif { fprintf(stderr, "rx timeout\n"); goto fail; } } } } res = 0; fail: if (conn != NULL) teardown(conn); if (ctx != NULL) teardown_ctx(ctx); return res; }
./openssl/doc/designs/ddd/ddd-03-fd-blocking.c
#include <openssl/ssl.h> /* * Demo 3: Client — Client Creates FD — Blocking * ============================================= * * This is an example of (part of) an application which uses libssl in a simple, * synchronous, blocking fashion. The client is responsible for creating the * socket and passing it to libssl. The functions show all interactions with * libssl the application makes, and would hypothetically be linked into a * larger application. */ /* * The application is initializing and wants an SSL_CTX which it will use for * some number of outgoing connections, which it creates in subsequent calls to * new_conn. The application may also call this function multiple times to * create multiple SSL_CTX. */ SSL_CTX *create_ssl_ctx(void) { SSL_CTX *ctx; #ifdef USE_QUIC ctx = SSL_CTX_new(OSSL_QUIC_client_method()); #else ctx = SSL_CTX_new(TLS_client_method()); #endif if (ctx == NULL) return NULL; /* Enable trust chain verification. */ SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, NULL); /* Load default root CA store. */ if (SSL_CTX_set_default_verify_paths(ctx) == 0) { SSL_CTX_free(ctx); return NULL; } return ctx; } /* * The application wants to create a new outgoing connection using a given * SSL_CTX. * * hostname is a string like "openssl.org" used for certificate validation. */ SSL *new_conn(SSL_CTX *ctx, int fd, const char *bare_hostname) { SSL *ssl; #ifdef USE_QUIC static const unsigned char alpn[] = {5, 'd', 'u', 'm', 'm', 'y'}; #endif ssl = SSL_new(ctx); if (ssl == NULL) return NULL; SSL_set_connect_state(ssl); /* cannot fail */ if (SSL_set_fd(ssl, fd) <= 0) { SSL_free(ssl); return NULL; } if (SSL_set1_host(ssl, bare_hostname) <= 0) { SSL_free(ssl); return NULL; } if (SSL_set_tlsext_host_name(ssl, bare_hostname) <= 0) { SSL_free(ssl); return NULL; } #ifdef USE_QUIC /* Configure ALPN, which is required for QUIC. */ if (SSL_set_alpn_protos(ssl, alpn, sizeof(alpn))) { /* Note: SSL_set_alpn_protos returns 1 for failure. */ SSL_free(ssl); return NULL; } #endif return ssl; } /* * The application wants to send some block of data to the peer. * This is a blocking call. */ int tx(SSL *ssl, const void *buf, int buf_len) { return SSL_write(ssl, buf, buf_len); } /* * The application wants to receive some block of data from * the peer. This is a blocking call. */ int rx(SSL *ssl, void *buf, int buf_len) { return SSL_read(ssl, buf, buf_len); } /* * The application wants to close the connection and free bookkeeping * structures. */ void teardown(SSL *ssl) { SSL_free(ssl); } /* * The application is shutting down and wants to free a previously * created SSL_CTX. */ void teardown_ctx(SSL_CTX *ctx) { SSL_CTX_free(ctx); } /* * ============================================================================ * Example driver for the above code. This is just to demonstrate that the code * works and is not intended to be representative of a real application. */ #include <sys/types.h> #include <sys/socket.h> #include <sys/signal.h> #include <netdb.h> #include <unistd.h> int main(int argc, char **argv) { int rc, fd = -1, l, mlen, res = 1; static char msg[300]; struct addrinfo hints = {0}, *result = NULL; SSL *ssl = NULL; SSL_CTX *ctx = NULL; char buf[2048]; if (argc < 3) { fprintf(stderr, "usage: %s host port\n", argv[0]); goto fail; } mlen = snprintf(msg, sizeof(msg), "GET / HTTP/1.0\r\nHost: %s\r\n\r\n", argv[1]); ctx = create_ssl_ctx(); if (ctx == NULL) { fprintf(stderr, "cannot create context\n"); goto fail; } hints.ai_family = AF_INET; hints.ai_socktype = SOCK_STREAM; hints.ai_flags = AI_PASSIVE; rc = getaddrinfo(argv[1], argv[2], &hints, &result); if (rc < 0) { fprintf(stderr, "cannot resolve\n"); goto fail; } signal(SIGPIPE, SIG_IGN); #ifdef USE_QUIC fd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); #else fd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); #endif if (fd < 0) { fprintf(stderr, "cannot create socket\n"); goto fail; } rc = connect(fd, result->ai_addr, result->ai_addrlen); if (rc < 0) { fprintf(stderr, "cannot connect\n"); goto fail; } ssl = new_conn(ctx, fd, argv[1]); if (ssl == NULL) { fprintf(stderr, "cannot create connection\n"); goto fail; } l = tx(ssl, msg, mlen); if (l < mlen) { fprintf(stderr, "tx error\n"); goto fail; } for (;;) { l = rx(ssl, buf, sizeof(buf)); if (l <= 0) break; fwrite(buf, 1, l, stdout); } res = 0; fail: if (ssl != NULL) teardown(ssl); if (ctx != NULL) teardown_ctx(ctx); if (fd >= 0) close(fd); if (result != NULL) freeaddrinfo(result); return res; }
./openssl/doc/designs/ddd/ddd-02-conn-nonblocking-threads.c
#include <sys/poll.h> #include <openssl/ssl.h> /* * Demo 2: Client — Managed Connection — Nonblocking * ============================================================== * * This is an example of (part of) an application which uses libssl in an * asynchronous, nonblocking fashion. The functions show all interactions with * libssl the application makes, and would hypothetically be linked into a * larger application. * * In this example, libssl still makes syscalls directly using an fd, which is * configured in nonblocking mode. As such, the application can still be * abstracted from the details of what that fd is (is it a TCP socket? is it a * UDP socket?); this code passes the application an fd and the application * simply calls back into this code when poll()/etc. indicates it is ready. */ typedef struct app_conn_st { SSL *ssl; BIO *ssl_bio; int rx_need_tx, tx_need_rx; } APP_CONN; /* * The application is initializing and wants an SSL_CTX which it will use for * some number of outgoing connections, which it creates in subsequent calls to * new_conn. The application may also call this function multiple times to * create multiple SSL_CTX. */ SSL_CTX *create_ssl_ctx(void) { SSL_CTX *ctx; #ifdef USE_QUIC ctx = SSL_CTX_new(OSSL_QUIC_client_thread_method()); #else ctx = SSL_CTX_new(TLS_client_method()); #endif if (ctx == NULL) return NULL; /* Enable trust chain verification. */ SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, NULL); /* Load default root CA store. */ if (SSL_CTX_set_default_verify_paths(ctx) == 0) { SSL_CTX_free(ctx); return NULL; } return ctx; } /* * The application wants to create a new outgoing connection using a given * SSL_CTX. * * hostname is a string like "openssl.org:443" or "[::1]:443". */ APP_CONN *new_conn(SSL_CTX *ctx, const char *hostname) { APP_CONN *conn; BIO *out, *buf; SSL *ssl = NULL; const char *bare_hostname; #ifdef USE_QUIC static const unsigned char alpn[] = {5, 'd', 'u', 'm', 'm', 'y'}; #endif conn = calloc(1, sizeof(APP_CONN)); if (conn == NULL) return NULL; out = BIO_new_ssl_connect(ctx); if (out == NULL) { free(conn); return NULL; } if (BIO_get_ssl(out, &ssl) == 0) { BIO_free_all(out); free(conn); return NULL; } buf = BIO_new(BIO_f_buffer()); if (buf == NULL) { BIO_free_all(out); free(conn); return NULL; } BIO_push(out, buf); if (BIO_set_conn_hostname(out, hostname) == 0) { BIO_free_all(out); free(conn); return NULL; } /* Returns the parsed hostname extracted from the hostname:port string. */ bare_hostname = BIO_get_conn_hostname(out); if (bare_hostname == NULL) { BIO_free_all(out); free(conn); return NULL; } /* Tell the SSL object the hostname to check certificates against. */ if (SSL_set1_host(ssl, bare_hostname) <= 0) { BIO_free_all(out); free(conn); return NULL; } #ifdef USE_QUIC /* Configure ALPN, which is required for QUIC. */ if (SSL_set_alpn_protos(ssl, alpn, sizeof(alpn))) { /* Note: SSL_set_alpn_protos returns 1 for failure. */ BIO_free_all(out); free(conn); return NULL; } #endif /* Make the BIO nonblocking. */ BIO_set_nbio(out, 1); conn->ssl_bio = out; return conn; } /* * Non-blocking transmission. * * Returns -1 on error. Returns -2 if the function would block (corresponds to * EWOULDBLOCK). */ int tx(APP_CONN *conn, const void *buf, int buf_len) { int l; conn->tx_need_rx = 0; l = BIO_write(conn->ssl_bio, buf, buf_len); if (l <= 0) { if (BIO_should_retry(conn->ssl_bio)) { conn->tx_need_rx = BIO_should_read(conn->ssl_bio); return -2; } else { return -1; } } return l; } /* * Non-blocking reception. * * Returns -1 on error. Returns -2 if the function would block (corresponds to * EWOULDBLOCK). */ int rx(APP_CONN *conn, void *buf, int buf_len) { int l; conn->rx_need_tx = 0; l = BIO_read(conn->ssl_bio, buf, buf_len); if (l <= 0) { if (BIO_should_retry(conn->ssl_bio)) { conn->rx_need_tx = BIO_should_write(conn->ssl_bio); return -2; } else { return -1; } } return l; } /* * The application wants to know a fd it can poll on to determine when the * SSL state machine needs to be pumped. */ int get_conn_fd(APP_CONN *conn) { #ifdef USE_QUIC BIO_POLL_DESCRIPTOR d; if (!BIO_get_rpoll_descriptor(conn->ssl_bio, &d)) return -1; return d.value.fd; #else return BIO_get_fd(conn->ssl_bio, NULL); #endif } /* * These functions returns zero or more of: * * POLLIN: The SSL state machine is interested in socket readability events. * * POLLOUT: The SSL state machine is interested in socket writeability events. * * POLLERR: The SSL state machine is interested in socket error events. * * get_conn_pending_tx returns events which may cause SSL_write to make * progress and get_conn_pending_rx returns events which may cause SSL_read * to make progress. */ int get_conn_pending_tx(APP_CONN *conn) { #ifdef USE_QUIC return (SSL_net_read_desired(conn->ssl) ? POLLIN : 0) | (SSL_net_write_desired(conn->ssl) ? POLLOUT : 0) | POLLERR; #else return (conn->tx_need_rx ? POLLIN : 0) | POLLOUT | POLLERR; #endif } int get_conn_pending_rx(APP_CONN *conn) { #ifdef USE_QUIC return get_conn_pending_tx(conn); #else return (conn->rx_need_tx ? POLLOUT : 0) | POLLIN | POLLERR; #endif } /* * The application wants to close the connection and free bookkeeping * structures. */ void teardown(APP_CONN *conn) { BIO_free_all(conn->ssl_bio); free(conn); } /* * The application is shutting down and wants to free a previously * created SSL_CTX. */ void teardown_ctx(SSL_CTX *ctx) { SSL_CTX_free(ctx); } /* * ============================================================================ * Example driver for the above code. This is just to demonstrate that the code * works and is not intended to be representative of a real application. */ int main(int argc, char **argv) { static char tx_msg[384], host_port[300]; const char *tx_p = tx_msg; char rx_buf[2048]; int res = 1, l, tx_len; int timeout = 2000 /* ms */; APP_CONN *conn = NULL; SSL_CTX *ctx = NULL; if (argc < 3) { fprintf(stderr, "usage: %s host port\n", argv[0]); goto fail; } snprintf(host_port, sizeof(host_port), "%s:%s", argv[1], argv[2]); tx_len = snprintf(tx_msg, sizeof(tx_msg), "GET / HTTP/1.0\r\nHost: %s\r\n\r\n", argv[1]); ctx = create_ssl_ctx(); if (ctx == NULL) { fprintf(stderr, "cannot create SSL context\n"); goto fail; } conn = new_conn(ctx, host_port); if (conn == NULL) { fprintf(stderr, "cannot establish connection\n"); goto fail; } /* TX */ while (tx_len != 0) { l = tx(conn, tx_p, tx_len); if (l > 0) { tx_p += l; tx_len -= l; } else if (l == -1) { fprintf(stderr, "tx error\n"); } else if (l == -2) { struct pollfd pfd = {0}; pfd.fd = get_conn_fd(conn); pfd.events = get_conn_pending_tx(conn); if (poll(&pfd, 1, timeout) == 0) { fprintf(stderr, "tx timeout\n"); goto fail; } } } /* RX */ for (;;) { l = rx(conn, rx_buf, sizeof(rx_buf)); if (l > 0) { fwrite(rx_buf, 1, l, stdout); } else if (l == -1) { break; } else if (l == -2) { struct pollfd pfd = {0}; pfd.fd = get_conn_fd(conn); pfd.events = get_conn_pending_rx(conn); if (poll(&pfd, 1, timeout) == 0) { fprintf(stderr, "rx timeout\n"); goto fail; } } } res = 0; fail: if (conn != NULL) teardown(conn); if (ctx != NULL) teardown_ctx(ctx); return res; }
./openssl/doc/designs/ddd/ddd-04-fd-nonblocking.c
#include <sys/poll.h> #include <openssl/ssl.h> /* * Demo 4: Client — Client Creates FD — Nonblocking * ================================================ * * This is an example of (part of) an application which uses libssl in an * asynchronous, nonblocking fashion. The client is responsible for creating the * socket and passing it to libssl. The functions show all interactions with * libssl the application makes, and would hypothetically be linked into a * larger application. */ typedef struct app_conn_st { SSL *ssl; int fd; int rx_need_tx, tx_need_rx; } APP_CONN; /* * The application is initializing and wants an SSL_CTX which it will use for * some number of outgoing connections, which it creates in subsequent calls to * new_conn. The application may also call this function multiple times to * create multiple SSL_CTX. */ SSL_CTX *create_ssl_ctx(void) { SSL_CTX *ctx; #ifdef USE_QUIC ctx = SSL_CTX_new(OSSL_QUIC_client_method()); #else ctx = SSL_CTX_new(TLS_client_method()); #endif if (ctx == NULL) return NULL; /* Enable trust chain verification. */ SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, NULL); /* Load default root CA store. */ if (SSL_CTX_set_default_verify_paths(ctx) == 0) { SSL_CTX_free(ctx); return NULL; } return ctx; } /* * The application wants to create a new outgoing connection using a given * SSL_CTX. * * hostname is a string like "openssl.org" used for certificate validation. */ APP_CONN *new_conn(SSL_CTX *ctx, int fd, const char *bare_hostname) { APP_CONN *conn; SSL *ssl; #ifdef USE_QUIC static const unsigned char alpn[] = {5, 'd', 'u', 'm', 'm', 'y'}; #endif conn = calloc(1, sizeof(APP_CONN)); if (conn == NULL) return NULL; ssl = conn->ssl = SSL_new(ctx); if (ssl == NULL) { free(conn); return NULL; } SSL_set_connect_state(ssl); /* cannot fail */ if (SSL_set_fd(ssl, fd) <= 0) { SSL_free(ssl); free(conn); return NULL; } if (SSL_set1_host(ssl, bare_hostname) <= 0) { SSL_free(ssl); free(conn); return NULL; } if (SSL_set_tlsext_host_name(ssl, bare_hostname) <= 0) { SSL_free(ssl); free(conn); return NULL; } #ifdef USE_QUIC /* Configure ALPN, which is required for QUIC. */ if (SSL_set_alpn_protos(ssl, alpn, sizeof(alpn))) { /* Note: SSL_set_alpn_protos returns 1 for failure. */ SSL_free(ssl); free(conn); return NULL; } #endif conn->fd = fd; return conn; } /* * Non-blocking transmission. * * Returns -1 on error. Returns -2 if the function would block (corresponds to * EWOULDBLOCK). */ int tx(APP_CONN *conn, const void *buf, int buf_len) { int rc, l; conn->tx_need_rx = 0; l = SSL_write(conn->ssl, buf, buf_len); if (l <= 0) { rc = SSL_get_error(conn->ssl, l); switch (rc) { case SSL_ERROR_WANT_READ: conn->tx_need_rx = 1; case SSL_ERROR_WANT_CONNECT: case SSL_ERROR_WANT_WRITE: return -2; default: return -1; } } return l; } /* * Non-blocking reception. * * Returns -1 on error. Returns -2 if the function would block (corresponds to * EWOULDBLOCK). */ int rx(APP_CONN *conn, void *buf, int buf_len) { int rc, l; conn->rx_need_tx = 0; l = SSL_read(conn->ssl, buf, buf_len); if (l <= 0) { rc = SSL_get_error(conn->ssl, l); switch (rc) { case SSL_ERROR_WANT_WRITE: conn->rx_need_tx = 1; case SSL_ERROR_WANT_READ: return -2; default: return -1; } } return l; } /* * The application wants to know a fd it can poll on to determine when the * SSL state machine needs to be pumped. * * If the fd returned has: * * POLLIN: SSL_read *may* return data; * if application does not want to read yet, it should call pump(). * * POLLOUT: SSL_write *may* accept data * * POLLERR: An application should call pump() if it is not likely to call * SSL_read or SSL_write soon. * */ int get_conn_fd(APP_CONN *conn) { return conn->fd; } /* * These functions returns zero or more of: * * POLLIN: The SSL state machine is interested in socket readability events. * * POLLOUT: The SSL state machine is interested in socket writeability events. * * POLLERR: The SSL state machine is interested in socket error events. * * get_conn_pending_tx returns events which may cause SSL_write to make * progress and get_conn_pending_rx returns events which may cause SSL_read * to make progress. */ int get_conn_pending_tx(APP_CONN *conn) { #ifdef USE_QUIC return (SSL_net_read_desired(conn->ssl) ? POLLIN : 0) | (SSL_net_write_desired(conn->ssl) ? POLLOUT : 0) | POLLERR; #else return (conn->tx_need_rx ? POLLIN : 0) | POLLOUT | POLLERR; #endif } int get_conn_pending_rx(APP_CONN *conn) { return get_conn_pending_tx(conn); } #ifdef USE_QUIC /* * Returns the number of milliseconds after which some call to libssl must be * made. Any call (SSL_read/SSL_write/SSL_pump) will do. Returns -1 if there is * no need for such a call. This may change after the next call * to libssl. */ static inline int timeval_to_ms(const struct timeval *t); int get_conn_pump_timeout(APP_CONN *conn) { struct timeval tv; int is_infinite; if (!SSL_get_event_timeout(conn->ssl, &tv, &is_infinite)) return -1; return is_infinite ? -1 : timeval_to_ms(&tv); } /* * Called to advance internals of libssl state machines without having to * perform an application-level read/write. */ void pump(APP_CONN *conn) { SSL_handle_events(conn->ssl); } #endif /* * The application wants to close the connection and free bookkeeping * structures. */ void teardown(APP_CONN *conn) { SSL_shutdown(conn->ssl); SSL_free(conn->ssl); free(conn); } /* * The application is shutting down and wants to free a previously * created SSL_CTX. */ void teardown_ctx(SSL_CTX *ctx) { SSL_CTX_free(ctx); } /* * ============================================================================ * Example driver for the above code. This is just to demonstrate that the code * works and is not intended to be representative of a real application. */ #include <sys/types.h> #include <sys/socket.h> #include <sys/signal.h> #ifdef USE_QUIC # include <sys/time.h> #endif #include <netdb.h> #include <unistd.h> #include <fcntl.h> #ifdef USE_QUIC static inline void ms_to_timeval(struct timeval *t, int ms) { t->tv_sec = ms < 0 ? -1 : ms/1000; t->tv_usec = ms < 0 ? 0 : (ms%1000)*1000; } static inline int timeval_to_ms(const struct timeval *t) { return t->tv_sec*1000 + t->tv_usec/1000; } #endif int main(int argc, char **argv) { int rc, fd = -1, res = 1; static char tx_msg[300]; const char *tx_p = tx_msg; char rx_buf[2048]; int l, tx_len; #ifdef USE_QUIC struct timeval timeout; #else int timeout = 2000 /* ms */; #endif APP_CONN *conn = NULL; struct addrinfo hints = {0}, *result = NULL; SSL_CTX *ctx = NULL; #ifdef USE_QUIC ms_to_timeval(&timeout, 2000); #endif if (argc < 3) { fprintf(stderr, "usage: %s host port\n", argv[0]); goto fail; } tx_len = snprintf(tx_msg, sizeof(tx_msg), "GET / HTTP/1.0\r\nHost: %s\r\n\r\n", argv[1]); ctx = create_ssl_ctx(); if (ctx == NULL) { fprintf(stderr, "cannot create SSL context\n"); goto fail; } hints.ai_family = AF_INET; hints.ai_socktype = SOCK_STREAM; hints.ai_flags = AI_PASSIVE; rc = getaddrinfo(argv[1], argv[2], &hints, &result); if (rc < 0) { fprintf(stderr, "cannot resolve\n"); goto fail; } signal(SIGPIPE, SIG_IGN); #ifdef USE_QUIC fd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); #else fd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); #endif if (fd < 0) { fprintf(stderr, "cannot create socket\n"); goto fail; } rc = connect(fd, result->ai_addr, result->ai_addrlen); if (rc < 0) { fprintf(stderr, "cannot connect\n"); goto fail; } rc = fcntl(fd, F_SETFL, O_NONBLOCK); if (rc < 0) { fprintf(stderr, "cannot make socket nonblocking\n"); goto fail; } conn = new_conn(ctx, fd, argv[1]); if (conn == NULL) { fprintf(stderr, "cannot establish connection\n"); goto fail; } /* TX */ while (tx_len != 0) { l = tx(conn, tx_p, tx_len); if (l > 0) { tx_p += l; tx_len -= l; } else if (l == -1) { fprintf(stderr, "tx error\n"); goto fail; } else if (l == -2) { #ifdef USE_QUIC struct timeval start, now, deadline, t; #endif struct pollfd pfd = {0}; #ifdef USE_QUIC ms_to_timeval(&t, get_conn_pump_timeout(conn)); if (t.tv_sec < 0 || timercmp(&t, &timeout, >)) t = timeout; gettimeofday(&start, NULL); timeradd(&start, &timeout, &deadline); #endif pfd.fd = get_conn_fd(conn); pfd.events = get_conn_pending_tx(conn); #ifdef USE_QUIC if (poll(&pfd, 1, timeval_to_ms(&t)) == 0) #else if (poll(&pfd, 1, timeout) == 0) #endif { #ifdef USE_QUIC pump(conn); gettimeofday(&now, NULL); if (timercmp(&now, &deadline, >=)) #endif { fprintf(stderr, "tx timeout\n"); goto fail; } } } } /* RX */ for (;;) { l = rx(conn, rx_buf, sizeof(rx_buf)); if (l > 0) { fwrite(rx_buf, 1, l, stdout); } else if (l == -1) { break; } else if (l == -2) { #ifdef USE_QUIC struct timeval start, now, deadline, t; #endif struct pollfd pfd = {0}; #ifdef USE_QUIC ms_to_timeval(&t, get_conn_pump_timeout(conn)); if (t.tv_sec < 0 || timercmp(&t, &timeout, >)) t = timeout; gettimeofday(&start, NULL); timeradd(&start, &timeout, &deadline); #endif pfd.fd = get_conn_fd(conn); pfd.events = get_conn_pending_rx(conn); #ifdef USE_QUIC if (poll(&pfd, 1, timeval_to_ms(&t)) == 0) #else if (poll(&pfd, 1, timeout) == 0) #endif { #ifdef USE_QUIC pump(conn); gettimeofday(&now, NULL); if (timercmp(&now, &deadline, >=)) #endif { fprintf(stderr, "rx timeout\n"); goto fail; } } } } res = 0; fail: if (conn != NULL) teardown(conn); if (ctx != NULL) teardown_ctx(ctx); if (result != NULL) freeaddrinfo(result); return res; }
./openssl/doc/designs/ddd/ddd-01-conn-blocking.c
#include <openssl/ssl.h> /* * Demo 1: Client — Managed Connection — Blocking * ============================================== * * This is an example of (part of) an application which uses libssl in a simple, * synchronous, blocking fashion. The functions show all interactions with * libssl the application makes, and would hypothetically be linked into a * larger application. */ /* * The application is initializing and wants an SSL_CTX which it will use for * some number of outgoing connections, which it creates in subsequent calls to * new_conn. The application may also call this function multiple times to * create multiple SSL_CTX. */ SSL_CTX *create_ssl_ctx(void) { SSL_CTX *ctx; #ifdef USE_QUIC ctx = SSL_CTX_new(OSSL_QUIC_client_method()); #else ctx = SSL_CTX_new(TLS_client_method()); #endif if (ctx == NULL) return NULL; /* Enable trust chain verification. */ SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, NULL); /* Load default root CA store. */ if (SSL_CTX_set_default_verify_paths(ctx) == 0) { SSL_CTX_free(ctx); return NULL; } return ctx; } /* * The application wants to create a new outgoing connection using a given * SSL_CTX. * * hostname is a string like "openssl.org:443" or "[::1]:443". */ BIO *new_conn(SSL_CTX *ctx, const char *hostname) { BIO *out; SSL *ssl = NULL; const char *bare_hostname; #ifdef USE_QUIC static const unsigned char alpn[] = {5, 'd', 'u', 'm', 'm', 'y'}; #endif out = BIO_new_ssl_connect(ctx); if (out == NULL) return NULL; if (BIO_get_ssl(out, &ssl) == 0) { BIO_free_all(out); return NULL; } if (BIO_set_conn_hostname(out, hostname) == 0) { BIO_free_all(out); return NULL; } /* Returns the parsed hostname extracted from the hostname:port string. */ bare_hostname = BIO_get_conn_hostname(out); if (bare_hostname == NULL) { BIO_free_all(out); return NULL; } /* Tell the SSL object the hostname to check certificates against. */ if (SSL_set1_host(ssl, bare_hostname) <= 0) { BIO_free_all(out); return NULL; } #ifdef USE_QUIC /* Configure ALPN, which is required for QUIC. */ if (SSL_set_alpn_protos(ssl, alpn, sizeof(alpn))) { /* Note: SSL_set_alpn_protos returns 1 for failure. */ BIO_free_all(out); return NULL; } #endif return out; } /* * The application wants to send some block of data to the peer. * This is a blocking call. */ int tx(BIO *bio, const void *buf, int buf_len) { return BIO_write(bio, buf, buf_len); } /* * The application wants to receive some block of data from * the peer. This is a blocking call. */ int rx(BIO *bio, void *buf, int buf_len) { return BIO_read(bio, buf, buf_len); } /* * The application wants to close the connection and free bookkeeping * structures. */ void teardown(BIO *bio) { BIO_free_all(bio); } /* * The application is shutting down and wants to free a previously * created SSL_CTX. */ void teardown_ctx(SSL_CTX *ctx) { SSL_CTX_free(ctx); } /* * ============================================================================ * Example driver for the above code. This is just to demonstrate that the code * works and is not intended to be representative of a real application. */ int main(int argc, char **argv) { static char msg[384], host_port[300]; SSL_CTX *ctx = NULL; BIO *b = NULL; char buf[2048]; int l, mlen, res = 1; if (argc < 3) { fprintf(stderr, "usage: %s host port\n", argv[0]); goto fail; } snprintf(host_port, sizeof(host_port), "%s:%s", argv[1], argv[2]); mlen = snprintf(msg, sizeof(msg), "GET / HTTP/1.0\r\nHost: %s\r\n\r\n", argv[1]); ctx = create_ssl_ctx(); if (ctx == NULL) { fprintf(stderr, "could not create context\n"); goto fail; } b = new_conn(ctx, host_port); if (b == NULL) { fprintf(stderr, "could not create connection\n"); goto fail; } l = tx(b, msg, mlen); if (l < mlen) { fprintf(stderr, "tx error\n"); goto fail; } for (;;) { l = rx(b, buf, sizeof(buf)); if (l <= 0) break; fwrite(buf, 1, l, stdout); } res = 0; fail: if (b != NULL) teardown(b); if (ctx != NULL) teardown_ctx(ctx); return res; }
./openssl/apps/kdf.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 <string.h> #include "apps.h" #include "progs.h" #include <openssl/bio.h> #include <openssl/err.h> #include <openssl/evp.h> #include <openssl/kdf.h> #include <openssl/params.h> typedef enum OPTION_choice { OPT_COMMON, OPT_KDFOPT, OPT_BIN, OPT_KEYLEN, OPT_OUT, OPT_CIPHER, OPT_DIGEST, OPT_MAC, OPT_PROV_ENUM } OPTION_CHOICE; const OPTIONS kdf_options[] = { {OPT_HELP_STR, 1, '-', "Usage: %s [options] kdf_name\n"}, OPT_SECTION("General"), {"help", OPT_HELP, '-', "Display this summary"}, {"kdfopt", OPT_KDFOPT, 's', "KDF algorithm control parameters in n:v form"}, {"cipher", OPT_CIPHER, 's', "Cipher"}, {"digest", OPT_DIGEST, 's', "Digest"}, {"mac", OPT_MAC, 's', "MAC"}, {OPT_MORE_STR, 1, '-', "See 'Supported Controls' in the EVP_KDF_ docs\n"}, {"keylen", OPT_KEYLEN, 's', "The size of the output derived key"}, OPT_SECTION("Output"), {"out", OPT_OUT, '>', "Output to filename rather than stdout"}, {"binary", OPT_BIN, '-', "Output in binary format (default is hexadecimal)"}, OPT_PROV_OPTIONS, OPT_PARAMETERS(), {"kdf_name", 0, 0, "Name of the KDF algorithm"}, {NULL} }; static char *alloc_kdf_algorithm_name(STACK_OF(OPENSSL_STRING) **optp, const char *name, const char *arg) { size_t len = strlen(name) + strlen(arg) + 2; char *res; if (*optp == NULL) *optp = sk_OPENSSL_STRING_new_null(); if (*optp == NULL) return NULL; res = app_malloc(len, "algorithm name"); BIO_snprintf(res, len, "%s:%s", name, arg); if (sk_OPENSSL_STRING_push(*optp, res)) return res; OPENSSL_free(res); return NULL; } int kdf_main(int argc, char **argv) { int ret = 1, out_bin = 0; OPTION_CHOICE o; STACK_OF(OPENSSL_STRING) *opts = NULL; char *prog, *hexout = NULL; const char *outfile = NULL; unsigned char *dkm_bytes = NULL; size_t dkm_len = 0; BIO *out = NULL; EVP_KDF *kdf = NULL; EVP_KDF_CTX *ctx = NULL; char *digest = NULL, *cipher = NULL, *mac = NULL; prog = opt_init(argc, argv, kdf_options); while ((o = opt_next()) != OPT_EOF) { switch (o) { default: opthelp: BIO_printf(bio_err, "%s: Use -help for summary.\n", prog); goto err; case OPT_HELP: opt_help(kdf_options); ret = 0; goto err; case OPT_BIN: out_bin = 1; break; case OPT_KEYLEN: dkm_len = (size_t)atoi(opt_arg()); break; case OPT_OUT: outfile = opt_arg(); break; case OPT_KDFOPT: if (opts == NULL) opts = sk_OPENSSL_STRING_new_null(); if (opts == NULL || !sk_OPENSSL_STRING_push(opts, opt_arg())) goto opthelp; break; case OPT_CIPHER: OPENSSL_free(cipher); cipher = alloc_kdf_algorithm_name(&opts, "cipher", opt_arg()); if (cipher == NULL) goto opthelp; break; case OPT_DIGEST: OPENSSL_free(digest); digest = alloc_kdf_algorithm_name(&opts, "digest", opt_arg()); if (digest == NULL) goto opthelp; break; case OPT_MAC: OPENSSL_free(mac); mac = alloc_kdf_algorithm_name(&opts, "mac", opt_arg()); if (mac == NULL) goto opthelp; break; case OPT_PROV_CASES: if (!opt_provider(o)) goto err; break; } } /* One argument, the KDF name. */ argc = opt_num_rest(); argv = opt_rest(); if (argc != 1) goto opthelp; if ((kdf = EVP_KDF_fetch(app_get0_libctx(), argv[0], app_get0_propq())) == NULL) { BIO_printf(bio_err, "Invalid KDF name %s\n", argv[0]); goto opthelp; } ctx = EVP_KDF_CTX_new(kdf); if (ctx == NULL) goto err; if (opts != NULL) { int ok = 1; OSSL_PARAM *params = app_params_new_from_opts(opts, EVP_KDF_settable_ctx_params(kdf)); if (params == NULL) goto err; if (!EVP_KDF_CTX_set_params(ctx, params)) { BIO_printf(bio_err, "KDF parameter error\n"); ERR_print_errors(bio_err); ok = 0; } app_params_free(params); if (!ok) goto err; } out = bio_open_default(outfile, 'w', out_bin ? FORMAT_BINARY : FORMAT_TEXT); if (out == NULL) goto err; if (dkm_len <= 0) { BIO_printf(bio_err, "Invalid derived key length.\n"); goto err; } dkm_bytes = app_malloc(dkm_len, "out buffer"); if (dkm_bytes == NULL) goto err; if (!EVP_KDF_derive(ctx, dkm_bytes, dkm_len, NULL)) { BIO_printf(bio_err, "EVP_KDF_derive failed\n"); goto err; } if (out_bin) { BIO_write(out, dkm_bytes, dkm_len); } else { hexout = OPENSSL_buf2hexstr(dkm_bytes, dkm_len); if (hexout == NULL) { BIO_printf(bio_err, "Memory allocation failure\n"); goto err; } BIO_printf(out, "%s\n\n", hexout); } ret = 0; err: if (ret != 0) ERR_print_errors(bio_err); OPENSSL_clear_free(dkm_bytes, dkm_len); sk_OPENSSL_STRING_free(opts); EVP_KDF_free(kdf); EVP_KDF_CTX_free(ctx); BIO_free(out); OPENSSL_free(hexout); OPENSSL_free(cipher); OPENSSL_free(digest); OPENSSL_free(mac); return ret; }
./openssl/apps/openssl.c
/* * Copyright 1995-2023 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <stdio.h> #include <stdlib.h> #include "internal/common.h" #include <openssl/bio.h> #include <openssl/crypto.h> #include <openssl/trace.h> #include <openssl/lhash.h> #include <openssl/conf.h> #include <openssl/x509.h> #include <openssl/pem.h> #include <openssl/ssl.h> #ifndef OPENSSL_NO_ENGINE # include <openssl/engine.h> #endif #include <openssl/err.h> /* Needed to get the other O_xxx flags. */ #ifdef OPENSSL_SYS_VMS # include <unixio.h> #endif #include "apps.h" #include "progs.h" /* * The LHASH callbacks ("hash" & "cmp") have been replaced by functions with * the base prototypes (we cast each variable inside the function to the * required type of "FUNCTION*"). This removes the necessity for * macro-generated wrapper functions. */ static LHASH_OF(FUNCTION) *prog_init(void); static int do_cmd(LHASH_OF(FUNCTION) *prog, int argc, char *argv[]); char *default_config_file = NULL; BIO *bio_in = NULL; BIO *bio_out = NULL; BIO *bio_err = NULL; static void warn_deprecated(const FUNCTION *fp) { if (fp->deprecated_version != NULL) BIO_printf(bio_err, "The command %s was deprecated in version %s.", fp->name, fp->deprecated_version); else BIO_printf(bio_err, "The command %s is deprecated.", fp->name); if (strcmp(fp->deprecated_alternative, DEPRECATED_NO_ALTERNATIVE) != 0) BIO_printf(bio_err, " Use '%s' instead.", fp->deprecated_alternative); BIO_printf(bio_err, "\n"); } static int apps_startup(void) { const char *use_libctx = NULL; #ifdef SIGPIPE signal(SIGPIPE, SIG_IGN); #endif /* Set non-default library initialisation settings */ if (!OPENSSL_init_ssl(OPENSSL_INIT_ENGINE_ALL_BUILTIN | OPENSSL_INIT_LOAD_CONFIG, NULL)) return 0; (void)setup_ui_method(); (void)setup_engine_loader(); /* * NOTE: This is an undocumented feature required for testing only. * There are no guarantees that it will exist in future builds. */ use_libctx = getenv("OPENSSL_TEST_LIBCTX"); if (use_libctx != NULL) { /* Set this to "1" to create a global libctx */ if (strcmp(use_libctx, "1") == 0) { if (app_create_libctx() == NULL) return 0; } } return 1; } static void apps_shutdown(void) { app_providers_cleanup(); OSSL_LIB_CTX_free(app_get0_libctx()); destroy_engine_loader(); destroy_ui_method(); } #ifndef OPENSSL_NO_TRACE typedef struct tracedata_st { BIO *bio; unsigned int ingroup:1; } tracedata; static size_t internal_trace_cb(const char *buf, size_t cnt, int category, int cmd, void *vdata) { int ret = 0; tracedata *trace_data = vdata; char buffer[256], *hex; CRYPTO_THREAD_ID tid; switch (cmd) { case OSSL_TRACE_CTRL_BEGIN: if (trace_data->ingroup) { BIO_printf(bio_err, "ERROR: tracing already started\n"); return 0; } trace_data->ingroup = 1; tid = CRYPTO_THREAD_get_current_id(); hex = OPENSSL_buf2hexstr((const unsigned char *)&tid, sizeof(tid)); BIO_snprintf(buffer, sizeof(buffer), "TRACE[%s]:%s: ", hex == NULL ? "<null>" : hex, OSSL_trace_get_category_name(category)); OPENSSL_free(hex); BIO_set_prefix(trace_data->bio, buffer); break; case OSSL_TRACE_CTRL_WRITE: if (!trace_data->ingroup) { BIO_printf(bio_err, "ERROR: writing when tracing not started\n"); return 0; } ret = BIO_write(trace_data->bio, buf, cnt); break; case OSSL_TRACE_CTRL_END: if (!trace_data->ingroup) { BIO_printf(bio_err, "ERROR: finishing when tracing not started\n"); return 0; } trace_data->ingroup = 0; BIO_set_prefix(trace_data->bio, NULL); break; } return ret < 0 ? 0 : ret; } DEFINE_STACK_OF(tracedata) static STACK_OF(tracedata) *trace_data_stack; static void tracedata_free(tracedata *data) { BIO_free_all(data->bio); OPENSSL_free(data); } static void cleanup_trace(void) { sk_tracedata_pop_free(trace_data_stack, tracedata_free); } static void setup_trace_category(int category) { BIO *channel; tracedata *trace_data; BIO *bio = NULL; if (OSSL_trace_enabled(category)) return; bio = BIO_new(BIO_f_prefix()); channel = BIO_push(bio, dup_bio_err(FORMAT_TEXT)); trace_data = OPENSSL_zalloc(sizeof(*trace_data)); if (trace_data == NULL || bio == NULL || (trace_data->bio = channel) == NULL || OSSL_trace_set_callback(category, internal_trace_cb, trace_data) == 0 || sk_tracedata_push(trace_data_stack, trace_data) == 0) { fprintf(stderr, "warning: unable to setup trace callback for category '%s'.\n", OSSL_trace_get_category_name(category)); OSSL_trace_set_callback(category, NULL, NULL); BIO_free_all(channel); } } static void setup_trace(const char *str) { char *val; /* * We add this handler as early as possible to ensure it's executed * as late as possible, i.e. after the TRACE code has done its cleanup * (which happens last in OPENSSL_cleanup). */ atexit(cleanup_trace); trace_data_stack = sk_tracedata_new_null(); val = OPENSSL_strdup(str); if (val != NULL) { char *valp = val; char *item; for (valp = val; (item = strtok(valp, ",")) != NULL; valp = NULL) { int category = OSSL_trace_get_category_num(item); if (category == OSSL_TRACE_CATEGORY_ALL) { while (++category < OSSL_TRACE_CATEGORY_NUM) setup_trace_category(category); break; } else if (category > 0) { setup_trace_category(category); } else { fprintf(stderr, "warning: unknown trace category: '%s'.\n", item); } } } OPENSSL_free(val); } #endif /* OPENSSL_NO_TRACE */ static char *help_argv[] = { "help", NULL }; static char *version_argv[] = { "version", NULL }; int main(int argc, char *argv[]) { FUNCTION f, *fp; LHASH_OF(FUNCTION) *prog = NULL; char *pname; const char *fname; ARGS arg; int global_help = 0; int global_version = 0; int ret = 0; arg.argv = NULL; arg.size = 0; /* Set up some of the environment. */ bio_in = dup_bio_in(FORMAT_TEXT); bio_out = dup_bio_out(FORMAT_TEXT); bio_err = dup_bio_err(FORMAT_TEXT); #if defined(OPENSSL_SYS_VMS) && defined(__DECC) argv = copy_argv(&argc, argv); #elif defined(_WIN32) /* Replace argv[] with UTF-8 encoded strings. */ win32_utf8argv(&argc, &argv); #endif #ifndef OPENSSL_NO_TRACE setup_trace(getenv("OPENSSL_TRACE")); #endif if ((fname = "apps_startup", !apps_startup()) || (fname = "prog_init", (prog = prog_init()) == NULL)) { BIO_printf(bio_err, "FATAL: Startup failure (dev note: %s()) for %s\n", fname, argv[0]); ERR_print_errors(bio_err); ret = 1; goto end; } pname = opt_progname(argv[0]); default_config_file = CONF_get1_default_config_file(); if (default_config_file == NULL) app_bail_out("%s: could not get default config file\n", pname); /* first check the program name */ f.name = pname; fp = lh_FUNCTION_retrieve(prog, &f); if (fp == NULL) { /* We assume we've been called as 'openssl ...' */ global_help = argc > 1 && (strcmp(argv[1], "-help") == 0 || strcmp(argv[1], "--help") == 0 || strcmp(argv[1], "-h") == 0 || strcmp(argv[1], "--h") == 0); global_version = argc > 1 && (strcmp(argv[1], "-version") == 0 || strcmp(argv[1], "--version") == 0 || strcmp(argv[1], "-v") == 0 || strcmp(argv[1], "--v") == 0); argc--; argv++; opt_appname(argc == 1 || global_help ? "help" : global_version ? "version" : argv[0]); } else { argv[0] = pname; } /* * If there's no command, assume "help". If there's an override for help * or version run those, otherwise run the command given. */ ret = (argc == 0) || global_help ? do_cmd(prog, 1, help_argv) : global_version ? do_cmd(prog, 1, version_argv) : do_cmd(prog, argc, argv); end: OPENSSL_free(default_config_file); lh_FUNCTION_free(prog); OPENSSL_free(arg.argv); if (!app_RAND_write()) ret = EXIT_FAILURE; BIO_free(bio_in); BIO_free_all(bio_out); apps_shutdown(); BIO_free_all(bio_err); EXIT(ret); } typedef enum HELP_CHOICE { OPT_hERR = -1, OPT_hEOF = 0, OPT_hHELP } HELP_CHOICE; const OPTIONS help_options[] = { {OPT_HELP_STR, 1, '-', "Usage: help [options] [command]\n"}, OPT_SECTION("General"), {"help", OPT_hHELP, '-', "Display this summary"}, OPT_PARAMETERS(), {"command", 0, 0, "Name of command to display help (optional)"}, {NULL} }; int help_main(int argc, char **argv) { FUNCTION *fp; int i, nl; FUNC_TYPE tp; char *prog; HELP_CHOICE o; DISPLAY_COLUMNS dc; char *new_argv[3]; prog = opt_init(argc, argv, help_options); while ((o = opt_next()) != OPT_hEOF) { switch (o) { case OPT_hERR: case OPT_hEOF: BIO_printf(bio_err, "%s: Use -help for summary.\n", prog); return 1; case OPT_hHELP: opt_help(help_options); return 0; } } /* One optional argument, the command to get help for. */ if (opt_num_rest() == 1) { new_argv[0] = opt_rest()[0]; new_argv[1] = "--help"; new_argv[2] = NULL; return do_cmd(prog_init(), 2, new_argv); } if (!opt_check_rest_arg(NULL)) { BIO_printf(bio_err, "Usage: %s\n", prog); return 1; } calculate_columns(functions, &dc); BIO_printf(bio_err, "%s:\n\nStandard commands", prog); i = 0; tp = FT_none; for (fp = functions; fp->name != NULL; fp++) { nl = 0; if (i++ % dc.columns == 0) { BIO_printf(bio_err, "\n"); nl = 1; } if (fp->type != tp) { tp = fp->type; if (!nl) BIO_printf(bio_err, "\n"); if (tp == FT_md) { i = 1; BIO_printf(bio_err, "\nMessage Digest commands (see the `dgst' command for more details)\n"); } else if (tp == FT_cipher) { i = 1; BIO_printf(bio_err, "\nCipher commands (see the `enc' command for more details)\n"); } } BIO_printf(bio_err, "%-*s", dc.width, fp->name); } BIO_printf(bio_err, "\n\n"); return 0; } static int do_cmd(LHASH_OF(FUNCTION) *prog, int argc, char *argv[]) { FUNCTION f, *fp; if (argc <= 0 || argv[0] == NULL) return 0; memset(&f, 0, sizeof(f)); f.name = argv[0]; fp = lh_FUNCTION_retrieve(prog, &f); if (fp == NULL) { if (EVP_get_digestbyname(argv[0])) { f.type = FT_md; f.func = dgst_main; fp = &f; } else if (EVP_get_cipherbyname(argv[0])) { f.type = FT_cipher; f.func = enc_main; fp = &f; } } if (fp != NULL) { if (fp->deprecated_alternative != NULL) warn_deprecated(fp); return fp->func(argc, argv); } f.name = argv[0]; if (CHECK_AND_SKIP_PREFIX(f.name, "no-")) { /* * User is asking if foo is unsupported, by trying to "run" the * no-foo command. Strange. */ if (lh_FUNCTION_retrieve(prog, &f) == NULL) { BIO_printf(bio_out, "%s\n", argv[0]); return 0; } BIO_printf(bio_out, "%s\n", argv[0] + 3); return 1; } BIO_printf(bio_err, "Invalid command '%s'; type \"help\" for a list.\n", argv[0]); return 1; } static int function_cmp(const FUNCTION *a, const FUNCTION *b) { return strncmp(a->name, b->name, 8); } static unsigned long function_hash(const FUNCTION *a) { return OPENSSL_LH_strhash(a->name); } static int SortFnByName(const void *_f1, const void *_f2) { const FUNCTION *f1 = _f1; const FUNCTION *f2 = _f2; if (f1->type != f2->type) return f1->type - f2->type; return strcmp(f1->name, f2->name); } static LHASH_OF(FUNCTION) *prog_init(void) { static LHASH_OF(FUNCTION) *ret = NULL; static int prog_inited = 0; FUNCTION *f; size_t i; if (prog_inited) return ret; prog_inited = 1; /* Sort alphabetically within category. For nicer help displays. */ for (i = 0, f = functions; f->name != NULL; ++f, ++i) ; qsort(functions, i, sizeof(*functions), SortFnByName); if ((ret = lh_FUNCTION_new(function_hash, function_cmp)) == NULL) return NULL; for (f = functions; f->name != NULL; f++) (void)lh_FUNCTION_insert(ret, f); return ret; }
./openssl/apps/engine.c
/* * Copyright 2000-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 */ /* We need to use some engine deprecated APIs */ #define OPENSSL_SUPPRESS_DEPRECATED #include <openssl/opensslconf.h> #include "apps.h" #include "progs.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #include <openssl/err.h> #include <openssl/engine.h> #include <openssl/ssl.h> #include <openssl/store.h> typedef enum OPTION_choice { OPT_COMMON, OPT_C, OPT_T, OPT_TT, OPT_PRE, OPT_POST, OPT_V = 100, OPT_VV, OPT_VVV, OPT_VVVV } OPTION_CHOICE; const OPTIONS engine_options[] = { {OPT_HELP_STR, 1, '-', "Usage: %s [options] engine...\n"}, OPT_SECTION("General"), {"help", OPT_HELP, '-', "Display this summary"}, {"t", OPT_T, '-', "Check that specified engine is available"}, {"pre", OPT_PRE, 's', "Run command against the ENGINE before loading it"}, {"post", OPT_POST, 's', "Run command against the ENGINE after loading it"}, OPT_SECTION("Output"), {"v", OPT_V, '-', "List 'control commands' For each specified engine"}, {"vv", OPT_VV, '-', "Also display each command's description"}, {"vvv", OPT_VVV, '-', "Also add the input flags for each command"}, {"vvvv", OPT_VVVV, '-', "Also show internal input flags"}, {"c", OPT_C, '-', "List the capabilities of specified engine"}, {"tt", OPT_TT, '-', "Display error trace for unavailable engines"}, {OPT_MORE_STR, OPT_EOF, 1, "Commands are like \"SO_PATH:/lib/libdriver.so\""}, OPT_PARAMETERS(), {"engine", 0, 0, "ID of engine(s) to load"}, {NULL} }; static int append_buf(char **buf, int *size, const char *s) { const int expand = 256; int len = strlen(s) + 1; char *p = *buf; if (p == NULL) { *size = ((len + expand - 1) / expand) * expand; p = *buf = app_malloc(*size, "engine buffer"); } else { const int blen = strlen(p); if (blen > 0) len += 2 + blen; if (len > *size) { *size = ((len + expand - 1) / expand) * expand; p = OPENSSL_realloc(p, *size); if (p == NULL) { OPENSSL_free(*buf); *buf = NULL; return 0; } *buf = p; } if (blen > 0) { p += blen; *p++ = ','; *p++ = ' '; } } strcpy(p, s); return 1; } static int util_flags(BIO *out, unsigned int flags, const char *indent) { int started = 0, err = 0; /* Indent before displaying input flags */ BIO_printf(out, "%s%s(input flags): ", indent, indent); if (flags == 0) { BIO_printf(out, "<no flags>\n"); return 1; } /* * If the object is internal, mark it in a way that shows instead of * having it part of all the other flags, even if it really is. */ if (flags & ENGINE_CMD_FLAG_INTERNAL) { BIO_printf(out, "[Internal] "); } if (flags & ENGINE_CMD_FLAG_NUMERIC) { BIO_printf(out, "NUMERIC"); started = 1; } /* * Now we check that no combinations of the mutually exclusive NUMERIC, * STRING, and NO_INPUT flags have been used. Future flags that can be * OR'd together with these would need to added after these to preserve * the testing logic. */ if (flags & ENGINE_CMD_FLAG_STRING) { if (started) { BIO_printf(out, "|"); err = 1; } BIO_printf(out, "STRING"); started = 1; } if (flags & ENGINE_CMD_FLAG_NO_INPUT) { if (started) { BIO_printf(out, "|"); err = 1; } BIO_printf(out, "NO_INPUT"); started = 1; } /* Check for unknown flags */ flags = flags & ~ENGINE_CMD_FLAG_NUMERIC & ~ENGINE_CMD_FLAG_STRING & ~ENGINE_CMD_FLAG_NO_INPUT & ~ENGINE_CMD_FLAG_INTERNAL; if (flags) { if (started) BIO_printf(out, "|"); BIO_printf(out, "<0x%04X>", flags); } if (err) BIO_printf(out, " <illegal flags!>"); BIO_printf(out, "\n"); return 1; } static int util_verbose(ENGINE *e, int verbose, BIO *out, const char *indent) { static const int line_wrap = 78; int num; int ret = 0; char *name = NULL; char *desc = NULL; int flags; int xpos = 0; STACK_OF(OPENSSL_STRING) *cmds = NULL; if (!ENGINE_ctrl(e, ENGINE_CTRL_HAS_CTRL_FUNCTION, 0, NULL, NULL) || ((num = ENGINE_ctrl(e, ENGINE_CTRL_GET_FIRST_CMD_TYPE, 0, NULL, NULL)) <= 0)) { return 1; } cmds = sk_OPENSSL_STRING_new_null(); if (cmds == NULL) goto err; do { int len; /* Get the command input flags */ if ((flags = ENGINE_ctrl(e, ENGINE_CTRL_GET_CMD_FLAGS, num, NULL, NULL)) < 0) goto err; if (!(flags & ENGINE_CMD_FLAG_INTERNAL) || verbose >= 4) { /* Get the command name */ if ((len = ENGINE_ctrl(e, ENGINE_CTRL_GET_NAME_LEN_FROM_CMD, num, NULL, NULL)) <= 0) goto err; name = app_malloc(len + 1, "name buffer"); if (ENGINE_ctrl(e, ENGINE_CTRL_GET_NAME_FROM_CMD, num, name, NULL) <= 0) goto err; /* Get the command description */ if ((len = ENGINE_ctrl(e, ENGINE_CTRL_GET_DESC_LEN_FROM_CMD, num, NULL, NULL)) < 0) goto err; if (len > 0) { desc = app_malloc(len + 1, "description buffer"); if (ENGINE_ctrl(e, ENGINE_CTRL_GET_DESC_FROM_CMD, num, desc, NULL) <= 0) goto err; } /* Now decide on the output */ if (xpos == 0) /* Do an indent */ xpos = BIO_puts(out, indent); else /* Otherwise prepend a ", " */ xpos += BIO_printf(out, ", "); if (verbose == 1) { /* * We're just listing names, comma-delimited */ if ((xpos > (int)strlen(indent)) && (xpos + (int)strlen(name) > line_wrap)) { BIO_printf(out, "\n"); xpos = BIO_puts(out, indent); } xpos += BIO_printf(out, "%s", name); } else { /* We're listing names plus descriptions */ BIO_printf(out, "%s: %s\n", name, (desc == NULL) ? "<no description>" : desc); /* ... and sometimes input flags */ if ((verbose >= 3) && !util_flags(out, flags, indent)) goto err; xpos = 0; } } OPENSSL_free(name); name = NULL; OPENSSL_free(desc); desc = NULL; /* Move to the next command */ num = ENGINE_ctrl(e, ENGINE_CTRL_GET_NEXT_CMD_TYPE, num, NULL, NULL); } while (num > 0); if (xpos > 0) BIO_printf(out, "\n"); ret = 1; err: sk_OPENSSL_STRING_free(cmds); OPENSSL_free(name); OPENSSL_free(desc); return ret; } static void util_do_cmds(ENGINE *e, STACK_OF(OPENSSL_STRING) *cmds, BIO *out, const char *indent) { int loop, res, num = sk_OPENSSL_STRING_num(cmds); if (num < 0) { BIO_printf(out, "[Error]: internal stack error\n"); return; } for (loop = 0; loop < num; loop++) { char buf[256]; const char *cmd, *arg; cmd = sk_OPENSSL_STRING_value(cmds, loop); res = 1; /* assume success */ /* Check if this command has no ":arg" */ if ((arg = strstr(cmd, ":")) == NULL) { if (!ENGINE_ctrl_cmd_string(e, cmd, NULL, 0)) res = 0; } else { if ((int)(arg - cmd) > 254) { BIO_printf(out, "[Error]: command name too long\n"); return; } memcpy(buf, cmd, (int)(arg - cmd)); buf[arg - cmd] = '\0'; arg++; /* Move past the ":" */ /* Call the command with the argument */ if (!ENGINE_ctrl_cmd_string(e, buf, arg, 0)) res = 0; } if (res) { BIO_printf(out, "[Success]: %s\n", cmd); } else { BIO_printf(out, "[Failure]: %s\n", cmd); ERR_print_errors(out); } } } struct util_store_cap_data { ENGINE *engine; char **cap_buf; int *cap_size; int ok; }; static void util_store_cap(const OSSL_STORE_LOADER *loader, void *arg) { struct util_store_cap_data *ctx = arg; if (OSSL_STORE_LOADER_get0_engine(loader) == ctx->engine) { char buf[256]; BIO_snprintf(buf, sizeof(buf), "STORE(%s)", OSSL_STORE_LOADER_get0_scheme(loader)); if (!append_buf(ctx->cap_buf, ctx->cap_size, buf)) ctx->ok = 0; } } int engine_main(int argc, char **argv) { int ret = 1, i; int verbose = 0, list_cap = 0, test_avail = 0, test_avail_noise = 0; ENGINE *e; STACK_OF(OPENSSL_CSTRING) *engines = sk_OPENSSL_CSTRING_new_null(); STACK_OF(OPENSSL_STRING) *pre_cmds = sk_OPENSSL_STRING_new_null(); STACK_OF(OPENSSL_STRING) *post_cmds = sk_OPENSSL_STRING_new_null(); BIO *out; const char *indent = " "; OPTION_CHOICE o; char *prog; char *argv1; out = dup_bio_out(FORMAT_TEXT); if (engines == NULL || pre_cmds == NULL || post_cmds == NULL) goto end; /* Remember the original command name, parse/skip any leading engine * names, and then setup to parse the rest of the line as flags. */ prog = argv[0]; while ((argv1 = argv[1]) != NULL && *argv1 != '-') { sk_OPENSSL_CSTRING_push(engines, argv1); argc--; argv++; } argv[0] = prog; opt_init(argc, argv, engine_options); while ((o = opt_next()) != OPT_EOF) { switch (o) { case OPT_EOF: case OPT_ERR: BIO_printf(bio_err, "%s: Use -help for summary.\n", prog); goto end; case OPT_HELP: opt_help(engine_options); ret = 0; goto end; case OPT_VVVV: case OPT_VVV: case OPT_VV: case OPT_V: /* Convert to an integer from one to four. */ i = (int)(o - OPT_V) + 1; if (verbose < i) verbose = i; break; case OPT_C: list_cap = 1; break; case OPT_TT: test_avail_noise++; /* fall through */ case OPT_T: test_avail++; break; case OPT_PRE: sk_OPENSSL_STRING_push(pre_cmds, opt_arg()); break; case OPT_POST: sk_OPENSSL_STRING_push(post_cmds, opt_arg()); break; } } /* Any remaining arguments are engine names. */ argc = opt_num_rest(); argv = opt_rest(); for ( ; *argv; argv++) { if (**argv == '-') { BIO_printf(bio_err, "%s: Cannot mix flags and engine names.\n", prog); BIO_printf(bio_err, "%s: Use -help for summary.\n", prog); goto end; } sk_OPENSSL_CSTRING_push(engines, *argv); } if (sk_OPENSSL_CSTRING_num(engines) == 0) { for (e = ENGINE_get_first(); e != NULL; e = ENGINE_get_next(e)) { sk_OPENSSL_CSTRING_push(engines, ENGINE_get_id(e)); } } ret = 0; for (i = 0; i < sk_OPENSSL_CSTRING_num(engines); i++) { const char *id = sk_OPENSSL_CSTRING_value(engines, i); if ((e = ENGINE_by_id(id)) != NULL) { const char *name = ENGINE_get_name(e); /* * Do "id" first, then "name". Easier to auto-parse. */ BIO_printf(out, "(%s) %s\n", id, name); util_do_cmds(e, pre_cmds, out, indent); if (strcmp(ENGINE_get_id(e), id) != 0) { BIO_printf(out, "Loaded: (%s) %s\n", ENGINE_get_id(e), ENGINE_get_name(e)); } if (list_cap) { int cap_size = 256; char *cap_buf = NULL; int k, n; const int *nids; ENGINE_CIPHERS_PTR fn_c; ENGINE_DIGESTS_PTR fn_d; ENGINE_PKEY_METHS_PTR fn_pk; if (ENGINE_get_RSA(e) != NULL && !append_buf(&cap_buf, &cap_size, "RSA")) goto end; if (ENGINE_get_DSA(e) != NULL && !append_buf(&cap_buf, &cap_size, "DSA")) goto end; if (ENGINE_get_DH(e) != NULL && !append_buf(&cap_buf, &cap_size, "DH")) goto end; if (ENGINE_get_RAND(e) != NULL && !append_buf(&cap_buf, &cap_size, "RAND")) goto end; fn_c = ENGINE_get_ciphers(e); if (fn_c == NULL) goto skip_ciphers; n = fn_c(e, NULL, &nids, 0); for (k = 0; k < n; ++k) if (!append_buf(&cap_buf, &cap_size, OBJ_nid2sn(nids[k]))) goto end; skip_ciphers: fn_d = ENGINE_get_digests(e); if (fn_d == NULL) goto skip_digests; n = fn_d(e, NULL, &nids, 0); for (k = 0; k < n; ++k) if (!append_buf(&cap_buf, &cap_size, OBJ_nid2sn(nids[k]))) goto end; skip_digests: fn_pk = ENGINE_get_pkey_meths(e); if (fn_pk == NULL) goto skip_pmeths; n = fn_pk(e, NULL, &nids, 0); for (k = 0; k < n; ++k) if (!append_buf(&cap_buf, &cap_size, OBJ_nid2sn(nids[k]))) goto end; skip_pmeths: { struct util_store_cap_data store_ctx; store_ctx.engine = e; store_ctx.cap_buf = &cap_buf; store_ctx.cap_size = &cap_size; store_ctx.ok = 1; OSSL_STORE_do_all_loaders(util_store_cap, &store_ctx); if (!store_ctx.ok) goto end; } if (cap_buf != NULL && (*cap_buf != '\0')) BIO_printf(out, " [%s]\n", cap_buf); OPENSSL_free(cap_buf); } if (test_avail) { BIO_printf(out, "%s", indent); if (ENGINE_init(e)) { BIO_printf(out, "[ available ]\n"); util_do_cmds(e, post_cmds, out, indent); ENGINE_finish(e); } else { BIO_printf(out, "[ unavailable ]\n"); if (test_avail_noise) ERR_print_errors_fp(stdout); ERR_clear_error(); } } if ((verbose > 0) && !util_verbose(e, verbose, out, indent)) goto end; ENGINE_free(e); } else { ERR_print_errors(bio_err); /* because exit codes above 127 have special meaning on Unix */ if (++ret > 127) ret = 127; } } end: ERR_print_errors(bio_err); sk_OPENSSL_CSTRING_free(engines); sk_OPENSSL_STRING_free(pre_cmds); sk_OPENSSL_STRING_free(post_cmds); BIO_free_all(out); return ret; }
./openssl/apps/prime.c
/* * Copyright 2004-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 "apps.h" #include "progs.h" #include <openssl/bn.h> typedef enum OPTION_choice { OPT_COMMON, OPT_HEX, OPT_GENERATE, OPT_BITS, OPT_SAFE, OPT_CHECKS, OPT_PROV_ENUM } OPTION_CHOICE; static int check_num(const char *s, const int is_hex) { int i; /* * It would make sense to use ossl_isxdigit and ossl_isdigit here, * but ossl_ctype_check is a local symbol in libcrypto.so. */ if (is_hex) { for (i = 0; ('0' <= s[i] && s[i] <= '9') || ('A' <= s[i] && s[i] <= 'F') || ('a' <= s[i] && s[i] <= 'f'); i++); } else { for (i = 0; '0' <= s[i] && s[i] <= '9'; i++); } return s[i] == 0; } const OPTIONS prime_options[] = { {OPT_HELP_STR, 1, '-', "Usage: %s [options] [number...]\n"}, OPT_SECTION("General"), {"help", OPT_HELP, '-', "Display this summary"}, {"bits", OPT_BITS, 'p', "Size of number in bits"}, {"checks", OPT_CHECKS, 'p', "Number of checks"}, OPT_SECTION("Output"), {"hex", OPT_HEX, '-', "Hex output"}, {"generate", OPT_GENERATE, '-', "Generate a prime"}, {"safe", OPT_SAFE, '-', "When used with -generate, generate a safe prime"}, OPT_PROV_OPTIONS, OPT_PARAMETERS(), {"number", 0, 0, "Number(s) to check for primality if not generating"}, {NULL} }; int prime_main(int argc, char **argv) { BIGNUM *bn = NULL; int hex = 0, generate = 0, bits = 0, safe = 0, ret = 1; char *prog; OPTION_CHOICE o; prog = opt_init(argc, argv, prime_options); while ((o = opt_next()) != OPT_EOF) { switch (o) { case OPT_EOF: case OPT_ERR: opthelp: BIO_printf(bio_err, "%s: Use -help for summary.\n", prog); goto end; case OPT_HELP: opt_help(prime_options); ret = 0; goto end; case OPT_HEX: hex = 1; break; case OPT_GENERATE: generate = 1; break; case OPT_BITS: bits = atoi(opt_arg()); break; case OPT_SAFE: safe = 1; break; case OPT_CHECKS: /* ignore parameter and argument */ opt_arg(); break; case OPT_PROV_CASES: if (!opt_provider(o)) goto end; break; } } /* Optional arguments are numbers to check. */ if (generate && !opt_check_rest_arg(NULL)) goto opthelp; argc = opt_num_rest(); argv = opt_rest(); if (!generate && argc == 0) { BIO_printf(bio_err, "Missing number (s) to check\n"); goto opthelp; } if (generate) { char *s; if (!bits) { BIO_printf(bio_err, "Specify the number of bits.\n"); goto end; } bn = BN_new(); if (bn == NULL) { BIO_printf(bio_err, "Out of memory.\n"); goto end; } if (!BN_generate_prime_ex(bn, bits, safe, NULL, NULL, NULL)) { BIO_printf(bio_err, "Failed to generate prime.\n"); goto end; } s = hex ? BN_bn2hex(bn) : BN_bn2dec(bn); if (s == NULL) { BIO_printf(bio_err, "Out of memory.\n"); goto end; } BIO_printf(bio_out, "%s\n", s); OPENSSL_free(s); } else { for ( ; *argv; argv++) { int r = check_num(argv[0], hex); if (r) r = hex ? BN_hex2bn(&bn, argv[0]) : BN_dec2bn(&bn, argv[0]); if (!r) { BIO_printf(bio_err, "Failed to process value (%s)\n", argv[0]); goto end; } BN_print(bio_out, bn); BIO_printf(bio_out, " (%s) %s prime\n", argv[0], BN_check_prime(bn, NULL, NULL) ? "is" : "is not"); } } ret = 0; end: BN_free(bn); return ret; }
./openssl/apps/dgst.c
/* * Copyright 1995-2023 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <stdio.h> #include <string.h> #include <stdlib.h> #include "apps.h" #include "progs.h" #include <openssl/bio.h> #include <openssl/err.h> #include <openssl/evp.h> #include <openssl/objects.h> #include <openssl/x509.h> #include <openssl/pem.h> #include <openssl/hmac.h> #include <ctype.h> #undef BUFSIZE #define BUFSIZE 1024*8 int do_fp(BIO *out, unsigned char *buf, BIO *bp, int sep, int binout, int xoflen, EVP_PKEY *key, unsigned char *sigin, int siglen, const char *sig_name, const char *md_name, const char *file); static void show_digests(const OBJ_NAME *name, void *bio_); struct doall_dgst_digests { BIO *bio; int n; }; typedef enum OPTION_choice { OPT_COMMON, OPT_LIST, OPT_C, OPT_R, OPT_OUT, OPT_SIGN, OPT_PASSIN, OPT_VERIFY, OPT_PRVERIFY, OPT_SIGNATURE, OPT_KEYFORM, OPT_ENGINE, OPT_ENGINE_IMPL, OPT_HEX, OPT_BINARY, OPT_DEBUG, OPT_FIPS_FINGERPRINT, OPT_HMAC, OPT_MAC, OPT_SIGOPT, OPT_MACOPT, OPT_XOFLEN, OPT_DIGEST, OPT_R_ENUM, OPT_PROV_ENUM } OPTION_CHOICE; const OPTIONS dgst_options[] = { {OPT_HELP_STR, 1, '-', "Usage: %s [options] [file...]\n"}, OPT_SECTION("General"), {"help", OPT_HELP, '-', "Display this summary"}, {"list", OPT_LIST, '-', "List digests"}, #ifndef OPENSSL_NO_ENGINE {"engine", OPT_ENGINE, 's', "Use engine e, possibly a hardware device"}, {"engine_impl", OPT_ENGINE_IMPL, '-', "Also use engine given by -engine for digest operations"}, #endif {"passin", OPT_PASSIN, 's', "Input file pass phrase source"}, OPT_SECTION("Output"), {"c", OPT_C, '-', "Print the digest with separating colons"}, {"r", OPT_R, '-', "Print the digest in coreutils format"}, {"out", OPT_OUT, '>', "Output to filename rather than stdout"}, {"keyform", OPT_KEYFORM, 'f', "Key file format (ENGINE, other values ignored)"}, {"hex", OPT_HEX, '-', "Print as hex dump"}, {"binary", OPT_BINARY, '-', "Print in binary form"}, {"xoflen", OPT_XOFLEN, 'p', "Output length for XOF algorithms. To obtain the maximum security strength set this to 32 (or greater) for SHAKE128, and 64 (or greater) for SHAKE256"}, {"d", OPT_DEBUG, '-', "Print debug info"}, {"debug", OPT_DEBUG, '-', "Print debug info"}, OPT_SECTION("Signing"), {"sign", OPT_SIGN, 's', "Sign digest using private key"}, {"verify", OPT_VERIFY, 's', "Verify a signature using public key"}, {"prverify", OPT_PRVERIFY, 's', "Verify a signature using private key"}, {"sigopt", OPT_SIGOPT, 's', "Signature parameter in n:v form"}, {"signature", OPT_SIGNATURE, '<', "File with signature to verify"}, {"hmac", OPT_HMAC, 's', "Create hashed MAC with key"}, {"mac", OPT_MAC, 's', "Create MAC (not necessarily HMAC)"}, {"macopt", OPT_MACOPT, 's', "MAC algorithm parameters in n:v form or key"}, {"", OPT_DIGEST, '-', "Any supported digest"}, {"fips-fingerprint", OPT_FIPS_FINGERPRINT, '-', "Compute HMAC with the key used in OpenSSL-FIPS fingerprint"}, OPT_R_OPTIONS, OPT_PROV_OPTIONS, OPT_PARAMETERS(), {"file", 0, 0, "Files to digest (optional; default is stdin)"}, {NULL} }; int dgst_main(int argc, char **argv) { BIO *in = NULL, *inp, *bmd = NULL, *out = NULL; ENGINE *e = NULL, *impl = NULL; EVP_PKEY *sigkey = NULL; STACK_OF(OPENSSL_STRING) *sigopts = NULL, *macopts = NULL; char *hmac_key = NULL; char *mac_name = NULL, *digestname = NULL; char *passinarg = NULL, *passin = NULL; EVP_MD *md = NULL; const char *outfile = NULL, *keyfile = NULL, *prog = NULL; const char *sigfile = NULL; const char *md_name = NULL; OPTION_CHOICE o; int separator = 0, debug = 0, keyform = FORMAT_UNDEF, siglen = 0; int i, ret = EXIT_FAILURE, out_bin = -1, want_pub = 0, do_verify = 0; int xoflen = 0; unsigned char *buf = NULL, *sigbuf = NULL; int engine_impl = 0; struct doall_dgst_digests dec; buf = app_malloc(BUFSIZE, "I/O buffer"); md = (EVP_MD *)EVP_get_digestbyname(argv[0]); if (md != NULL) digestname = argv[0]; opt_set_unknown_name("digest"); prog = opt_init(argc, argv, dgst_options); while ((o = opt_next()) != OPT_EOF) { switch (o) { case OPT_EOF: case OPT_ERR: opthelp: BIO_printf(bio_err, "%s: Use -help for summary.\n", prog); goto end; case OPT_HELP: opt_help(dgst_options); ret = EXIT_SUCCESS; goto end; case OPT_LIST: BIO_printf(bio_out, "Supported digests:\n"); dec.bio = bio_out; dec.n = 0; OBJ_NAME_do_all_sorted(OBJ_NAME_TYPE_MD_METH, show_digests, &dec); BIO_printf(bio_out, "\n"); ret = EXIT_SUCCESS; goto end; case OPT_C: separator = 1; break; case OPT_R: separator = 2; break; case OPT_R_CASES: if (!opt_rand(o)) goto end; break; case OPT_OUT: outfile = opt_arg(); break; case OPT_SIGN: keyfile = opt_arg(); break; case OPT_PASSIN: passinarg = opt_arg(); break; case OPT_VERIFY: keyfile = opt_arg(); want_pub = do_verify = 1; break; case OPT_PRVERIFY: keyfile = opt_arg(); do_verify = 1; break; case OPT_SIGNATURE: sigfile = opt_arg(); break; case OPT_KEYFORM: if (!opt_format(opt_arg(), OPT_FMT_ANY, &keyform)) goto opthelp; break; case OPT_ENGINE: e = setup_engine(opt_arg(), 0); break; case OPT_ENGINE_IMPL: engine_impl = 1; break; case OPT_HEX: out_bin = 0; break; case OPT_BINARY: out_bin = 1; break; case OPT_XOFLEN: xoflen = atoi(opt_arg()); break; case OPT_DEBUG: debug = 1; break; case OPT_FIPS_FINGERPRINT: hmac_key = "etaonrishdlcupfm"; break; case OPT_HMAC: hmac_key = opt_arg(); break; case OPT_MAC: mac_name = opt_arg(); break; case OPT_SIGOPT: if (!sigopts) sigopts = sk_OPENSSL_STRING_new_null(); if (!sigopts || !sk_OPENSSL_STRING_push(sigopts, opt_arg())) goto opthelp; break; case OPT_MACOPT: if (!macopts) macopts = sk_OPENSSL_STRING_new_null(); if (!macopts || !sk_OPENSSL_STRING_push(macopts, opt_arg())) goto opthelp; break; case OPT_DIGEST: digestname = opt_unknown(); break; case OPT_PROV_CASES: if (!opt_provider(o)) goto end; break; } } /* Remaining args are files to digest. */ argc = opt_num_rest(); argv = opt_rest(); if (keyfile != NULL && argc > 1) { BIO_printf(bio_err, "%s: Can only sign or verify one file.\n", prog); goto end; } if (!app_RAND_load()) goto end; if (digestname != NULL) { if (!opt_md(digestname, &md)) goto opthelp; } if (do_verify && sigfile == NULL) { BIO_printf(bio_err, "No signature to verify: use the -signature option\n"); goto end; } if (engine_impl) impl = e; in = BIO_new(BIO_s_file()); bmd = BIO_new(BIO_f_md()); if (in == NULL || bmd == NULL) goto end; if (debug) { BIO_set_callback_ex(in, BIO_debug_callback_ex); /* needed for windows 3.1 */ BIO_set_callback_arg(in, (char *)bio_err); } if (!app_passwd(passinarg, NULL, &passin, NULL)) { BIO_printf(bio_err, "Error getting password\n"); goto end; } if (out_bin == -1) { if (keyfile != NULL) out_bin = 1; else out_bin = 0; } out = bio_open_default(outfile, 'w', out_bin ? FORMAT_BINARY : FORMAT_TEXT); if (out == NULL) goto end; if ((!(mac_name == NULL) + !(keyfile == NULL) + !(hmac_key == NULL)) > 1) { BIO_printf(bio_err, "MAC and signing key cannot both be specified\n"); goto end; } if (keyfile != NULL) { int type; if (want_pub) sigkey = load_pubkey(keyfile, keyform, 0, NULL, e, "public key"); else sigkey = load_key(keyfile, keyform, 0, passin, e, "private key"); if (sigkey == NULL) { /* * load_[pub]key() has already printed an appropriate message */ goto end; } type = EVP_PKEY_get_id(sigkey); if (type == EVP_PKEY_ED25519 || type == EVP_PKEY_ED448) { /* * We implement PureEdDSA for these which doesn't have a separate * digest, and only supports one shot. */ BIO_printf(bio_err, "Key type not supported for this operation\n"); goto end; } } if (mac_name != NULL) { EVP_PKEY_CTX *mac_ctx = NULL; if (!init_gen_str(&mac_ctx, mac_name, impl, 0, NULL, NULL)) goto end; if (macopts != NULL) { for (i = 0; i < sk_OPENSSL_STRING_num(macopts); i++) { char *macopt = sk_OPENSSL_STRING_value(macopts, i); if (pkey_ctrl_string(mac_ctx, macopt) <= 0) { EVP_PKEY_CTX_free(mac_ctx); BIO_printf(bio_err, "MAC parameter error \"%s\"\n", macopt); goto end; } } } sigkey = app_keygen(mac_ctx, mac_name, 0, 0 /* not verbose */); /* Verbose output would make external-tests gost-engine fail */ EVP_PKEY_CTX_free(mac_ctx); if (sigkey == NULL) goto end; } if (hmac_key != NULL) { if (md == NULL) { md = (EVP_MD *)EVP_sha256(); digestname = SN_sha256; } sigkey = EVP_PKEY_new_raw_private_key(EVP_PKEY_HMAC, impl, (unsigned char *)hmac_key, strlen(hmac_key)); if (sigkey == NULL) goto end; } if (sigkey != NULL) { EVP_MD_CTX *mctx = NULL; EVP_PKEY_CTX *pctx = NULL; int res; if (BIO_get_md_ctx(bmd, &mctx) <= 0) { BIO_printf(bio_err, "Error getting context\n"); goto end; } if (do_verify) if (impl == NULL) res = EVP_DigestVerifyInit_ex(mctx, &pctx, digestname, app_get0_libctx(), app_get0_propq(), sigkey, NULL); else res = EVP_DigestVerifyInit(mctx, &pctx, md, impl, sigkey); else if (impl == NULL) res = EVP_DigestSignInit_ex(mctx, &pctx, digestname, app_get0_libctx(), app_get0_propq(), sigkey, NULL); else res = EVP_DigestSignInit(mctx, &pctx, md, impl, sigkey); if (res == 0) { BIO_printf(bio_err, "Error setting context\n"); goto end; } if (sigopts != NULL) { for (i = 0; i < sk_OPENSSL_STRING_num(sigopts); i++) { char *sigopt = sk_OPENSSL_STRING_value(sigopts, i); if (pkey_ctrl_string(pctx, sigopt) <= 0) { BIO_printf(bio_err, "Signature parameter error \"%s\"\n", sigopt); goto end; } } } } /* we use md as a filter, reading from 'in' */ else { EVP_MD_CTX *mctx = NULL; if (BIO_get_md_ctx(bmd, &mctx) <= 0) { BIO_printf(bio_err, "Error getting context\n"); goto end; } if (md == NULL) md = (EVP_MD *)EVP_sha256(); if (!EVP_DigestInit_ex(mctx, md, impl)) { BIO_printf(bio_err, "Error setting digest\n"); goto end; } } if (sigfile != NULL && sigkey != NULL) { BIO *sigbio = BIO_new_file(sigfile, "rb"); if (sigbio == NULL) { BIO_printf(bio_err, "Error opening signature file %s\n", sigfile); goto end; } siglen = EVP_PKEY_get_size(sigkey); sigbuf = app_malloc(siglen, "signature buffer"); siglen = BIO_read(sigbio, sigbuf, siglen); BIO_free(sigbio); if (siglen <= 0) { BIO_printf(bio_err, "Error reading signature file %s\n", sigfile); goto end; } } inp = BIO_push(bmd, in); if (md == NULL) { EVP_MD_CTX *tctx; BIO_get_md_ctx(bmd, &tctx); md = EVP_MD_CTX_get1_md(tctx); } if (md != NULL) md_name = EVP_MD_get0_name(md); if (xoflen > 0) { if (!(EVP_MD_get_flags(md) & EVP_MD_FLAG_XOF)) { BIO_printf(bio_err, "Length can only be specified for XOF\n"); goto end; } /* * Signing using XOF is not supported by any algorithms currently since * each algorithm only calls EVP_DigestFinal_ex() in their sign_final * and verify_final methods. */ if (sigkey != NULL) { BIO_printf(bio_err, "Signing key cannot be specified for XOF\n"); goto end; } } if (argc == 0) { BIO_set_fp(in, stdin, BIO_NOCLOSE); ret = do_fp(out, buf, inp, separator, out_bin, xoflen, sigkey, sigbuf, siglen, NULL, md_name, "stdin"); } else { const char *sig_name = NULL; if (out_bin == 0) { if (sigkey != NULL) sig_name = EVP_PKEY_get0_type_name(sigkey); } ret = EXIT_SUCCESS; for (i = 0; i < argc; i++) { if (BIO_read_filename(in, argv[i]) <= 0) { perror(argv[i]); ret = EXIT_FAILURE; continue; } else { if (do_fp(out, buf, inp, separator, out_bin, xoflen, sigkey, sigbuf, siglen, sig_name, md_name, argv[i])) ret = EXIT_FAILURE; } (void)BIO_reset(bmd); } } end: if (ret != EXIT_SUCCESS) ERR_print_errors(bio_err); OPENSSL_clear_free(buf, BUFSIZE); BIO_free(in); OPENSSL_free(passin); BIO_free_all(out); EVP_MD_free(md); EVP_PKEY_free(sigkey); sk_OPENSSL_STRING_free(sigopts); sk_OPENSSL_STRING_free(macopts); OPENSSL_free(sigbuf); BIO_free(bmd); release_engine(e); return ret; } static void show_digests(const OBJ_NAME *name, void *arg) { struct doall_dgst_digests *dec = (struct doall_dgst_digests *)arg; const EVP_MD *md = NULL; /* Filter out signed digests (a.k.a signature algorithms) */ if (strstr(name->name, "rsa") != NULL || strstr(name->name, "RSA") != NULL) return; if (!islower((unsigned char)*name->name)) return; /* Filter out message digests that we cannot use */ md = EVP_MD_fetch(app_get0_libctx(), name->name, app_get0_propq()); if (md == NULL) { md = EVP_get_digestbyname(name->name); if (md == NULL) return; } BIO_printf(dec->bio, "-%-25s", name->name); if (++dec->n == 3) { BIO_printf(dec->bio, "\n"); dec->n = 0; } else { BIO_printf(dec->bio, " "); } } /* * The newline_escape_filename function performs newline escaping for any * filename that contains a newline. This function also takes a pointer * to backslash. The backslash pointer is a flag to indicating whether a newline * is present in the filename. If a newline is present, the backslash flag is * set and the output format will contain a backslash at the beginning of the * digest output. This output format is to replicate the output format found * in the '*sum' checksum programs. This aims to preserve backward * compatibility. */ static const char *newline_escape_filename(const char *file, int *backslash) { size_t i, e = 0, length = strlen(file), newline_count = 0, mem_len = 0; char *file_cpy = NULL; for (i = 0; i < length; i++) if (file[i] == '\n') newline_count++; mem_len = length + newline_count + 1; file_cpy = app_malloc(mem_len, file); i = 0; while (e < length) { const char c = file[e]; if (c == '\n') { file_cpy[i++] = '\\'; file_cpy[i++] = 'n'; *backslash = 1; } else { file_cpy[i++] = c; } e++; } file_cpy[i] = '\0'; return (const char*)file_cpy; } int do_fp(BIO *out, unsigned char *buf, BIO *bp, int sep, int binout, int xoflen, EVP_PKEY *key, unsigned char *sigin, int siglen, const char *sig_name, const char *md_name, const char *file) { size_t len = BUFSIZE; int i, backslash = 0, ret = EXIT_FAILURE; unsigned char *allocated_buf = NULL; while (BIO_pending(bp) || !BIO_eof(bp)) { i = BIO_read(bp, (char *)buf, BUFSIZE); if (i < 0) { BIO_printf(bio_err, "Read error in %s\n", file); goto end; } if (i == 0) break; } if (sigin != NULL) { EVP_MD_CTX *ctx; BIO_get_md_ctx(bp, &ctx); i = EVP_DigestVerifyFinal(ctx, sigin, (unsigned int)siglen); if (i > 0) { BIO_printf(out, "Verified OK\n"); } else if (i == 0) { BIO_printf(out, "Verification failure\n"); goto end; } else { BIO_printf(bio_err, "Error verifying data\n"); goto end; } ret = EXIT_SUCCESS; goto end; } if (key != NULL) { EVP_MD_CTX *ctx; size_t tmplen; BIO_get_md_ctx(bp, &ctx); if (!EVP_DigestSignFinal(ctx, NULL, &tmplen)) { BIO_printf(bio_err, "Error getting maximum length of signed data\n"); goto end; } if (tmplen > BUFSIZE) { len = tmplen; allocated_buf = app_malloc(len, "Signature buffer"); buf = allocated_buf; } if (!EVP_DigestSignFinal(ctx, buf, &len)) { BIO_printf(bio_err, "Error signing data\n"); goto end; } } else if (xoflen > 0) { EVP_MD_CTX *ctx; len = xoflen; if (len > BUFSIZE) { allocated_buf = app_malloc(len, "Digest buffer"); buf = allocated_buf; } BIO_get_md_ctx(bp, &ctx); if (!EVP_DigestFinalXOF(ctx, buf, len)) { BIO_printf(bio_err, "Error Digesting Data\n"); goto end; } } else { len = BIO_gets(bp, (char *)buf, BUFSIZE); if ((int)len < 0) goto end; } if (binout) { BIO_write(out, buf, len); } else if (sep == 2) { file = newline_escape_filename(file, &backslash); if (backslash == 1) BIO_puts(out, "\\"); for (i = 0; i < (int)len; i++) BIO_printf(out, "%02x", buf[i]); BIO_printf(out, " *%s\n", file); OPENSSL_free((char *)file); } else { if (sig_name != NULL) { BIO_puts(out, sig_name); if (md_name != NULL) BIO_printf(out, "-%s", md_name); BIO_printf(out, "(%s)= ", file); } else if (md_name != NULL) { BIO_printf(out, "%s(%s)= ", md_name, file); } else { BIO_printf(out, "(%s)= ", file); } for (i = 0; i < (int)len; i++) { if (sep && (i != 0)) BIO_printf(out, ":"); BIO_printf(out, "%02x", buf[i]); } BIO_printf(out, "\n"); } ret = EXIT_SUCCESS; end: if (allocated_buf != NULL) OPENSSL_clear_free(allocated_buf, len); return ret; }
./openssl/apps/fipsinstall.c
/* * Copyright 2019-2023 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <openssl/evp.h> #include <openssl/err.h> #include <openssl/provider.h> #include <openssl/params.h> #include <openssl/fips_names.h> #include <openssl/core_names.h> #include <openssl/self_test.h> #include <openssl/fipskey.h> #include "apps.h" #include "progs.h" #define BUFSIZE 4096 /* Configuration file values */ #define VERSION_KEY "version" #define VERSION_VAL "1" #define INSTALL_STATUS_VAL "INSTALL_SELF_TEST_KATS_RUN" static OSSL_CALLBACK self_test_events; static char *self_test_corrupt_desc = NULL; static char *self_test_corrupt_type = NULL; static int self_test_log = 1; static int quiet = 0; typedef enum OPTION_choice { OPT_COMMON, OPT_IN, OPT_OUT, OPT_MODULE, OPT_PEDANTIC, OPT_PROV_NAME, OPT_SECTION_NAME, OPT_MAC_NAME, OPT_MACOPT, OPT_VERIFY, OPT_NO_LOG, OPT_CORRUPT_DESC, OPT_CORRUPT_TYPE, OPT_QUIET, OPT_CONFIG, OPT_NO_CONDITIONAL_ERRORS, OPT_NO_SECURITY_CHECKS, OPT_TLS_PRF_EMS_CHECK, OPT_DISALLOW_DRGB_TRUNC_DIGEST, OPT_SELF_TEST_ONLOAD, OPT_SELF_TEST_ONINSTALL } OPTION_CHOICE; const OPTIONS fipsinstall_options[] = { OPT_SECTION("General"), {"help", OPT_HELP, '-', "Display this summary"}, {"pedantic", OPT_PEDANTIC, '-', "Set options for strict FIPS compliance"}, {"verify", OPT_VERIFY, '-', "Verify a config file instead of generating one"}, {"module", OPT_MODULE, '<', "File name of the provider module"}, {"provider_name", OPT_PROV_NAME, 's', "FIPS provider name"}, {"section_name", OPT_SECTION_NAME, 's', "FIPS Provider config section name (optional)"}, {"no_conditional_errors", OPT_NO_CONDITIONAL_ERRORS, '-', "Disable the ability of the fips module to enter an error state if" " any conditional self tests fail"}, {"no_security_checks", OPT_NO_SECURITY_CHECKS, '-', "Disable the run-time FIPS security checks in the module"}, {"self_test_onload", OPT_SELF_TEST_ONLOAD, '-', "Forces self tests to always run on module load"}, {"self_test_oninstall", OPT_SELF_TEST_ONINSTALL, '-', "Forces self tests to run once on module installation"}, {"ems_check", OPT_TLS_PRF_EMS_CHECK, '-', "Enable the run-time FIPS check for EMS during TLS1_PRF"}, {"no_drbg_truncated_digests", OPT_DISALLOW_DRGB_TRUNC_DIGEST, '-', "Disallow truncated digests with Hash and HMAC DRBGs"}, OPT_SECTION("Input"), {"in", OPT_IN, '<', "Input config file, used when verifying"}, OPT_SECTION("Output"), {"out", OPT_OUT, '>', "Output config file, used when generating"}, {"mac_name", OPT_MAC_NAME, 's', "MAC name"}, {"macopt", OPT_MACOPT, 's', "MAC algorithm parameters in n:v form."}, {OPT_MORE_STR, 0, 0, "See 'PARAMETER NAMES' in the EVP_MAC_ docs"}, {"noout", OPT_NO_LOG, '-', "Disable logging of self test events"}, {"corrupt_desc", OPT_CORRUPT_DESC, 's', "Corrupt a self test by description"}, {"corrupt_type", OPT_CORRUPT_TYPE, 's', "Corrupt a self test by type"}, {"config", OPT_CONFIG, '<', "The parent config to verify"}, {"quiet", OPT_QUIET, '-', "No messages, just exit status"}, {NULL} }; typedef struct { unsigned int self_test_onload : 1; unsigned int conditional_errors : 1; unsigned int security_checks : 1; unsigned int tls_prf_ems_check : 1; unsigned int drgb_no_trunc_dgst : 1; } FIPS_OPTS; /* Pedantic FIPS compliance */ static const FIPS_OPTS pedantic_opts = { 1, /* self_test_onload */ 1, /* conditional_errors */ 1, /* security_checks */ 1, /* tls_prf_ems_check */ 1, /* drgb_no_trunc_dgst */ }; /* Default FIPS settings for backward compatibility */ static FIPS_OPTS fips_opts = { 1, /* self_test_onload */ 1, /* conditional_errors */ 1, /* security_checks */ 0, /* tls_prf_ems_check */ 0, /* drgb_no_trunc_dgst */ }; static int check_non_pedantic_fips(int pedantic, const char *name) { if (pedantic) { BIO_printf(bio_err, "Cannot specify -%s after -pedantic\n", name); return 0; } return 1; } static int do_mac(EVP_MAC_CTX *ctx, unsigned char *tmp, BIO *in, unsigned char *out, size_t *out_len) { int ret = 0; int i; size_t outsz = *out_len; if (!EVP_MAC_init(ctx, NULL, 0, NULL)) goto err; if (EVP_MAC_CTX_get_mac_size(ctx) > outsz) goto end; while ((i = BIO_read(in, (char *)tmp, BUFSIZE)) != 0) { if (i < 0 || !EVP_MAC_update(ctx, tmp, i)) goto err; } end: if (!EVP_MAC_final(ctx, out, out_len, outsz)) goto err; ret = 1; err: return ret; } static int load_fips_prov_and_run_self_test(const char *prov_name) { int ret = 0; OSSL_PROVIDER *prov = NULL; OSSL_PARAM params[4], *p = params; char *name = "", *vers = "", *build = ""; prov = OSSL_PROVIDER_load(NULL, prov_name); if (prov == NULL) { BIO_printf(bio_err, "Failed to load FIPS module\n"); goto end; } if (!quiet) { *p++ = OSSL_PARAM_construct_utf8_ptr(OSSL_PROV_PARAM_NAME, &name, sizeof(name)); *p++ = OSSL_PARAM_construct_utf8_ptr(OSSL_PROV_PARAM_VERSION, &vers, sizeof(vers)); *p++ = OSSL_PARAM_construct_utf8_ptr(OSSL_PROV_PARAM_BUILDINFO, &build, sizeof(build)); *p = OSSL_PARAM_construct_end(); if (!OSSL_PROVIDER_get_params(prov, params)) { BIO_printf(bio_err, "Failed to query FIPS module parameters\n"); goto end; } if (OSSL_PARAM_modified(params)) BIO_printf(bio_err, "\t%-10s\t%s\n", "name:", name); if (OSSL_PARAM_modified(params + 1)) BIO_printf(bio_err, "\t%-10s\t%s\n", "version:", vers); if (OSSL_PARAM_modified(params + 2)) BIO_printf(bio_err, "\t%-10s\t%s\n", "build:", build); } ret = 1; end: OSSL_PROVIDER_unload(prov); return ret; } static int print_mac(BIO *bio, const char *label, const unsigned char *mac, size_t len) { int ret; char *hexstr = NULL; hexstr = OPENSSL_buf2hexstr(mac, (long)len); if (hexstr == NULL) return 0; ret = BIO_printf(bio, "%s = %s\n", label, hexstr); OPENSSL_free(hexstr); return ret; } static int write_config_header(BIO *out, const char *prov_name, const char *section) { return BIO_printf(out, "openssl_conf = openssl_init\n\n") && BIO_printf(out, "[openssl_init]\n") && BIO_printf(out, "providers = provider_section\n\n") && BIO_printf(out, "[provider_section]\n") && BIO_printf(out, "%s = %s\n\n", prov_name, section); } /* * Outputs a fips related config file that contains entries for the fips * module checksum, installation indicator checksum and the options * conditional_errors and security_checks. * * Returns 1 if the config file is written otherwise it returns 0 on error. */ static int write_config_fips_section(BIO *out, const char *section, unsigned char *module_mac, size_t module_mac_len, const FIPS_OPTS *opts, unsigned char *install_mac, size_t install_mac_len) { int ret = 0; if (BIO_printf(out, "[%s]\n", section) <= 0 || BIO_printf(out, "activate = 1\n") <= 0 || BIO_printf(out, "%s = %s\n", OSSL_PROV_FIPS_PARAM_INSTALL_VERSION, VERSION_VAL) <= 0 || BIO_printf(out, "%s = %s\n", OSSL_PROV_FIPS_PARAM_CONDITIONAL_ERRORS, opts->conditional_errors ? "1" : "0") <= 0 || BIO_printf(out, "%s = %s\n", OSSL_PROV_FIPS_PARAM_SECURITY_CHECKS, opts->security_checks ? "1" : "0") <= 0 || BIO_printf(out, "%s = %s\n", OSSL_PROV_FIPS_PARAM_TLS1_PRF_EMS_CHECK, opts->tls_prf_ems_check ? "1" : "0") <= 0 || BIO_printf(out, "%s = %s\n", OSSL_PROV_PARAM_DRBG_TRUNC_DIGEST, opts->drgb_no_trunc_dgst ? "1" : "0") <= 0 || !print_mac(out, OSSL_PROV_FIPS_PARAM_MODULE_MAC, module_mac, module_mac_len)) goto end; if (install_mac != NULL && install_mac_len > 0) { if (!print_mac(out, OSSL_PROV_FIPS_PARAM_INSTALL_MAC, install_mac, install_mac_len) || BIO_printf(out, "%s = %s\n", OSSL_PROV_FIPS_PARAM_INSTALL_STATUS, INSTALL_STATUS_VAL) <= 0) goto end; } ret = 1; end: return ret; } static CONF *generate_config_and_load(const char *prov_name, const char *section, unsigned char *module_mac, size_t module_mac_len, const FIPS_OPTS *opts) { BIO *mem_bio = NULL; CONF *conf = NULL; mem_bio = BIO_new(BIO_s_mem()); if (mem_bio == NULL) return 0; if (!write_config_header(mem_bio, prov_name, section) || !write_config_fips_section(mem_bio, section, module_mac, module_mac_len, opts, NULL, 0)) goto end; conf = app_load_config_bio(mem_bio, NULL); if (conf == NULL) goto end; if (CONF_modules_load(conf, NULL, 0) <= 0) goto end; BIO_free(mem_bio); return conf; end: NCONF_free(conf); BIO_free(mem_bio); return NULL; } static void free_config_and_unload(CONF *conf) { if (conf != NULL) { NCONF_free(conf); CONF_modules_unload(1); } } static int verify_module_load(const char *parent_config_file) { return OSSL_LIB_CTX_load_config(NULL, parent_config_file); } /* * Returns 1 if the config file entries match the passed in module_mac and * install_mac values, otherwise it returns 0. */ static int verify_config(const char *infile, const char *section, unsigned char *module_mac, size_t module_mac_len, unsigned char *install_mac, size_t install_mac_len) { int ret = 0; char *s = NULL; unsigned char *buf1 = NULL, *buf2 = NULL; long len; CONF *conf = NULL; /* read in the existing values and check they match the saved values */ conf = app_load_config(infile); if (conf == NULL) goto end; s = NCONF_get_string(conf, section, OSSL_PROV_FIPS_PARAM_INSTALL_VERSION); if (s == NULL || strcmp(s, VERSION_VAL) != 0) { BIO_printf(bio_err, "version not found\n"); goto end; } s = NCONF_get_string(conf, section, OSSL_PROV_FIPS_PARAM_MODULE_MAC); if (s == NULL) { BIO_printf(bio_err, "Module integrity MAC not found\n"); goto end; } buf1 = OPENSSL_hexstr2buf(s, &len); if (buf1 == NULL || (size_t)len != module_mac_len || memcmp(module_mac, buf1, module_mac_len) != 0) { BIO_printf(bio_err, "Module integrity mismatch\n"); goto end; } if (install_mac != NULL && install_mac_len > 0) { s = NCONF_get_string(conf, section, OSSL_PROV_FIPS_PARAM_INSTALL_STATUS); if (s == NULL || strcmp(s, INSTALL_STATUS_VAL) != 0) { BIO_printf(bio_err, "install status not found\n"); goto end; } s = NCONF_get_string(conf, section, OSSL_PROV_FIPS_PARAM_INSTALL_MAC); if (s == NULL) { BIO_printf(bio_err, "Install indicator MAC not found\n"); goto end; } buf2 = OPENSSL_hexstr2buf(s, &len); if (buf2 == NULL || (size_t)len != install_mac_len || memcmp(install_mac, buf2, install_mac_len) != 0) { BIO_printf(bio_err, "Install indicator status mismatch\n"); goto end; } } ret = 1; end: OPENSSL_free(buf1); OPENSSL_free(buf2); NCONF_free(conf); return ret; } int fipsinstall_main(int argc, char **argv) { int ret = 1, verify = 0, gotkey = 0, gotdigest = 0, pedantic = 0; const char *section_name = "fips_sect"; const char *mac_name = "HMAC"; const char *prov_name = "fips"; BIO *module_bio = NULL, *mem_bio = NULL, *fout = NULL; char *in_fname = NULL, *out_fname = NULL, *prog; char *module_fname = NULL, *parent_config = NULL, *module_path = NULL; const char *tail; EVP_MAC_CTX *ctx = NULL, *ctx2 = NULL; STACK_OF(OPENSSL_STRING) *opts = NULL; OPTION_CHOICE o; unsigned char *read_buffer = NULL; unsigned char module_mac[EVP_MAX_MD_SIZE]; size_t module_mac_len = EVP_MAX_MD_SIZE; unsigned char install_mac[EVP_MAX_MD_SIZE]; size_t install_mac_len = EVP_MAX_MD_SIZE; EVP_MAC *mac = NULL; CONF *conf = NULL; if ((opts = sk_OPENSSL_STRING_new_null()) == NULL) goto end; prog = opt_init(argc, argv, fipsinstall_options); while ((o = opt_next()) != OPT_EOF) { switch (o) { case OPT_EOF: case OPT_ERR: opthelp: BIO_printf(bio_err, "%s: Use -help for summary.\n", prog); goto cleanup; case OPT_HELP: opt_help(fipsinstall_options); ret = 0; goto end; case OPT_IN: in_fname = opt_arg(); break; case OPT_OUT: out_fname = opt_arg(); break; case OPT_PEDANTIC: fips_opts = pedantic_opts; pedantic = 1; break; case OPT_NO_CONDITIONAL_ERRORS: if (!check_non_pedantic_fips(pedantic, "no_conditional_errors")) goto end; fips_opts.conditional_errors = 0; break; case OPT_NO_SECURITY_CHECKS: if (!check_non_pedantic_fips(pedantic, "no_security_checks")) goto end; fips_opts.security_checks = 0; break; case OPT_TLS_PRF_EMS_CHECK: fips_opts.tls_prf_ems_check = 1; break; case OPT_DISALLOW_DRGB_TRUNC_DIGEST: fips_opts.drgb_no_trunc_dgst = 1; break; case OPT_QUIET: quiet = 1; /* FALLTHROUGH */ case OPT_NO_LOG: self_test_log = 0; break; case OPT_CORRUPT_DESC: self_test_corrupt_desc = opt_arg(); break; case OPT_CORRUPT_TYPE: self_test_corrupt_type = opt_arg(); break; case OPT_PROV_NAME: prov_name = opt_arg(); break; case OPT_MODULE: module_fname = opt_arg(); break; case OPT_SECTION_NAME: section_name = opt_arg(); break; case OPT_MAC_NAME: mac_name = opt_arg(); break; case OPT_CONFIG: parent_config = opt_arg(); break; case OPT_MACOPT: if (!sk_OPENSSL_STRING_push(opts, opt_arg())) goto opthelp; if (HAS_PREFIX(opt_arg(), "hexkey:")) gotkey = 1; else if (HAS_PREFIX(opt_arg(), "digest:")) gotdigest = 1; break; case OPT_VERIFY: verify = 1; break; case OPT_SELF_TEST_ONLOAD: fips_opts.self_test_onload = 1; break; case OPT_SELF_TEST_ONINSTALL: if (!check_non_pedantic_fips(pedantic, "self_test_oninstall")) goto end; fips_opts.self_test_onload = 0; break; } } /* No extra arguments. */ if (!opt_check_rest_arg(NULL)) goto opthelp; if (verify && in_fname == NULL) { BIO_printf(bio_err, "Missing -in option for -verify\n"); goto opthelp; } if (parent_config != NULL) { /* Test that a parent config can load the module */ if (verify_module_load(parent_config)) { ret = OSSL_PROVIDER_available(NULL, prov_name) ? 0 : 1; if (!quiet) { BIO_printf(bio_err, "FIPS provider is %s\n", ret == 0 ? "available" : " not available"); } } goto end; } if (module_fname == NULL) goto opthelp; tail = opt_path_end(module_fname); if (tail != NULL) { module_path = OPENSSL_strdup(module_fname); if (module_path == NULL) goto end; module_path[tail - module_fname] = '\0'; if (!OSSL_PROVIDER_set_default_search_path(NULL, module_path)) goto end; } if (self_test_log || self_test_corrupt_desc != NULL || self_test_corrupt_type != NULL) OSSL_SELF_TEST_set_callback(NULL, self_test_events, NULL); /* Use the default FIPS HMAC digest and key if not specified. */ if (!gotdigest && !sk_OPENSSL_STRING_push(opts, "digest:SHA256")) goto end; if (!gotkey && !sk_OPENSSL_STRING_push(opts, "hexkey:" FIPS_KEY_STRING)) goto end; module_bio = bio_open_default(module_fname, 'r', FORMAT_BINARY); if (module_bio == NULL) { BIO_printf(bio_err, "Failed to open module file\n"); goto end; } read_buffer = app_malloc(BUFSIZE, "I/O buffer"); if (read_buffer == NULL) goto end; mac = EVP_MAC_fetch(app_get0_libctx(), mac_name, app_get0_propq()); if (mac == NULL) { BIO_printf(bio_err, "Unable to get MAC of type %s\n", mac_name); goto end; } ctx = EVP_MAC_CTX_new(mac); if (ctx == NULL) { BIO_printf(bio_err, "Unable to create MAC CTX for module check\n"); goto end; } if (opts != NULL) { int ok = 1; OSSL_PARAM *params = app_params_new_from_opts(opts, EVP_MAC_settable_ctx_params(mac)); if (params == NULL) goto end; if (!EVP_MAC_CTX_set_params(ctx, params)) { BIO_printf(bio_err, "MAC parameter error\n"); ERR_print_errors(bio_err); ok = 0; } app_params_free(params); if (!ok) goto end; } ctx2 = EVP_MAC_CTX_dup(ctx); if (ctx2 == NULL) { BIO_printf(bio_err, "Unable to create MAC CTX for install indicator\n"); goto end; } if (!do_mac(ctx, read_buffer, module_bio, module_mac, &module_mac_len)) goto end; if (fips_opts.self_test_onload == 0) { mem_bio = BIO_new_mem_buf((const void *)INSTALL_STATUS_VAL, strlen(INSTALL_STATUS_VAL)); if (mem_bio == NULL) { BIO_printf(bio_err, "Unable to create memory BIO\n"); goto end; } if (!do_mac(ctx2, read_buffer, mem_bio, install_mac, &install_mac_len)) goto end; } else { install_mac_len = 0; } if (verify) { if (!verify_config(in_fname, section_name, module_mac, module_mac_len, install_mac, install_mac_len)) goto end; if (!quiet) BIO_printf(bio_err, "VERIFY PASSED\n"); } else { conf = generate_config_and_load(prov_name, section_name, module_mac, module_mac_len, &fips_opts); if (conf == NULL) goto end; if (!load_fips_prov_and_run_self_test(prov_name)) goto end; fout = out_fname == NULL ? dup_bio_out(FORMAT_TEXT) : bio_open_default(out_fname, 'w', FORMAT_TEXT); if (fout == NULL) { BIO_printf(bio_err, "Failed to open file\n"); goto end; } if (!write_config_fips_section(fout, section_name, module_mac, module_mac_len, &fips_opts, install_mac, install_mac_len)) goto end; if (!quiet) BIO_printf(bio_err, "INSTALL PASSED\n"); } ret = 0; end: if (ret == 1) { if (!quiet) BIO_printf(bio_err, "%s FAILED\n", verify ? "VERIFY" : "INSTALL"); ERR_print_errors(bio_err); } cleanup: OPENSSL_free(module_path); BIO_free(fout); BIO_free(mem_bio); BIO_free(module_bio); sk_OPENSSL_STRING_free(opts); EVP_MAC_free(mac); EVP_MAC_CTX_free(ctx2); EVP_MAC_CTX_free(ctx); OPENSSL_free(read_buffer); free_config_and_unload(conf); return ret; } static int self_test_events(const OSSL_PARAM params[], void *arg) { const OSSL_PARAM *p = NULL; const char *phase = NULL, *type = NULL, *desc = NULL; int ret = 0; 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 (self_test_log) { if (strcmp(phase, OSSL_SELF_TEST_PHASE_START) == 0) BIO_printf(bio_err, "%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_err, "%s\n", phase); } /* * The self test code will internally corrupt the KAT test result if an * error is returned during the corrupt phase. */ if (strcmp(phase, OSSL_SELF_TEST_PHASE_CORRUPT) == 0 && (self_test_corrupt_desc != NULL || self_test_corrupt_type != NULL)) { if (self_test_corrupt_desc != NULL && strcmp(self_test_corrupt_desc, desc) != 0) goto end; if (self_test_corrupt_type != NULL && strcmp(self_test_corrupt_type, type) != 0) goto end; BIO_printf(bio_err, "%s ", phase); goto err; } end: ret = 1; err: return ret; }
./openssl/apps/mac.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 */ #include <string.h> #include "apps.h" #include "progs.h" #include <openssl/bio.h> #include <openssl/err.h> #include <openssl/evp.h> #include <openssl/params.h> #include <openssl/core_names.h> #undef BUFSIZE #define BUFSIZE 1024*8 typedef enum OPTION_choice { OPT_COMMON, OPT_MACOPT, OPT_BIN, OPT_IN, OPT_OUT, OPT_CIPHER, OPT_DIGEST, OPT_PROV_ENUM } OPTION_CHOICE; const OPTIONS mac_options[] = { {OPT_HELP_STR, 1, '-', "Usage: %s [options] mac_name\n"}, OPT_SECTION("General"), {"help", OPT_HELP, '-', "Display this summary"}, {"macopt", OPT_MACOPT, 's', "MAC algorithm parameters in n:v form"}, {"cipher", OPT_CIPHER, 's', "Cipher"}, {"digest", OPT_DIGEST, 's', "Digest"}, {OPT_MORE_STR, 1, '-', "See 'PARAMETER NAMES' in the EVP_MAC_ docs"}, OPT_SECTION("Input"), {"in", OPT_IN, '<', "Input file to MAC (default is stdin)"}, OPT_SECTION("Output"), {"out", OPT_OUT, '>', "Output to filename rather than stdout"}, {"binary", OPT_BIN, '-', "Output in binary format (default is hexadecimal)"}, OPT_PROV_OPTIONS, OPT_PARAMETERS(), {"mac_name", 0, 0, "MAC algorithm"}, {NULL} }; static char *alloc_mac_algorithm_name(STACK_OF(OPENSSL_STRING) **optp, const char *name, const char *arg) { size_t len = strlen(name) + strlen(arg) + 2; char *res; if (*optp == NULL) *optp = sk_OPENSSL_STRING_new_null(); if (*optp == NULL) return NULL; res = app_malloc(len, "algorithm name"); BIO_snprintf(res, len, "%s:%s", name, arg); if (sk_OPENSSL_STRING_push(*optp, res)) return res; OPENSSL_free(res); return NULL; } int mac_main(int argc, char **argv) { int ret = 1; char *prog; EVP_MAC *mac = NULL; OPTION_CHOICE o; EVP_MAC_CTX *ctx = NULL; STACK_OF(OPENSSL_STRING) *opts = NULL; unsigned char *buf = NULL; size_t len; int i; BIO *in = NULL, *out = NULL; const char *outfile = NULL; const char *infile = NULL; int out_bin = 0; int inform = FORMAT_BINARY; char *digest = NULL, *cipher = NULL; OSSL_PARAM *params = NULL; prog = opt_init(argc, argv, mac_options); buf = app_malloc(BUFSIZE, "I/O buffer"); while ((o = opt_next()) != OPT_EOF) { switch (o) { default: opthelp: BIO_printf(bio_err, "%s: Use -help for summary.\n", prog); goto err; case OPT_HELP: opt_help(mac_options); ret = 0; goto err; case OPT_BIN: out_bin = 1; break; case OPT_IN: infile = opt_arg(); break; case OPT_OUT: outfile = opt_arg(); break; case OPT_MACOPT: if (opts == NULL) opts = sk_OPENSSL_STRING_new_null(); if (opts == NULL || !sk_OPENSSL_STRING_push(opts, opt_arg())) goto opthelp; break; case OPT_CIPHER: OPENSSL_free(cipher); cipher = alloc_mac_algorithm_name(&opts, "cipher", opt_arg()); if (cipher == NULL) goto opthelp; break; case OPT_DIGEST: OPENSSL_free(digest); digest = alloc_mac_algorithm_name(&opts, "digest", opt_arg()); if (digest == NULL) goto opthelp; break; case OPT_PROV_CASES: if (!opt_provider(o)) goto err; break; } } /* One argument, the MAC name. */ if (!opt_check_rest_arg("MAC name")) goto opthelp; argv = opt_rest(); mac = EVP_MAC_fetch(app_get0_libctx(), argv[0], app_get0_propq()); if (mac == NULL) { BIO_printf(bio_err, "Invalid MAC name %s\n", argv[0]); goto opthelp; } ctx = EVP_MAC_CTX_new(mac); if (ctx == NULL) goto err; if (opts != NULL) { int ok = 1; params = app_params_new_from_opts(opts, EVP_MAC_settable_ctx_params(mac)); if (params == NULL) goto err; if (!EVP_MAC_CTX_set_params(ctx, params)) { BIO_printf(bio_err, "MAC parameter error\n"); ERR_print_errors(bio_err); ok = 0; } app_params_free(params); if (!ok) goto err; } in = bio_open_default(infile, 'r', inform); if (in == NULL) goto err; out = bio_open_default(outfile, 'w', out_bin ? FORMAT_BINARY : FORMAT_TEXT); if (out == NULL) goto err; if (!EVP_MAC_init(ctx, NULL, 0, NULL)) { BIO_printf(bio_err, "EVP_MAC_Init failed\n"); goto err; } while (BIO_pending(in) || !BIO_eof(in)) { i = BIO_read(in, (char *)buf, BUFSIZE); if (i < 0) { BIO_printf(bio_err, "Read Error in '%s'\n", infile); ERR_print_errors(bio_err); goto err; } if (i == 0) break; if (!EVP_MAC_update(ctx, buf, i)) { BIO_printf(bio_err, "EVP_MAC_update failed\n"); goto err; } } if (!EVP_MAC_final(ctx, NULL, &len, 0)) { BIO_printf(bio_err, "EVP_MAC_final failed\n"); goto err; } if (len > BUFSIZE) { BIO_printf(bio_err, "output len is too large\n"); goto err; } if (!EVP_MAC_final(ctx, buf, &len, BUFSIZE)) { BIO_printf(bio_err, "EVP_MAC_final failed\n"); goto err; } if (out_bin) { BIO_write(out, buf, len); } else { for (i = 0; i < (int)len; ++i) BIO_printf(out, "%02X", buf[i]); if (outfile == NULL) BIO_printf(out, "\n"); } ret = 0; err: if (ret != 0) ERR_print_errors(bio_err); OPENSSL_clear_free(buf, BUFSIZE); OPENSSL_free(cipher); OPENSSL_free(digest); sk_OPENSSL_STRING_free(opts); BIO_free(in); BIO_free(out); EVP_MAC_CTX_free(ctx); EVP_MAC_free(mac); return ret; }
./openssl/apps/version.c
/* * Copyright 1995-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 <stdlib.h> #include <string.h> #include "apps.h" #include "progs.h" #include <openssl/evp.h> #include <openssl/crypto.h> #include <openssl/bn.h> typedef enum OPTION_choice { OPT_COMMON, OPT_B, OPT_D, OPT_E, OPT_M, OPT_F, OPT_O, OPT_P, OPT_V, OPT_A, OPT_R, OPT_C } OPTION_CHOICE; const OPTIONS version_options[] = { OPT_SECTION("General"), {"help", OPT_HELP, '-', "Display this summary"}, OPT_SECTION("Output"), {"a", OPT_A, '-', "Show all data"}, {"b", OPT_B, '-', "Show build date"}, {"d", OPT_D, '-', "Show configuration directory"}, {"e", OPT_E, '-', "Show engines directory"}, {"m", OPT_M, '-', "Show modules directory"}, {"f", OPT_F, '-', "Show compiler flags used"}, {"o", OPT_O, '-', "Show some internal datatype options"}, {"p", OPT_P, '-', "Show target build platform"}, {"r", OPT_R, '-', "Show random seeding options"}, {"v", OPT_V, '-', "Show library version"}, {"c", OPT_C, '-', "Show CPU settings info"}, {NULL} }; int version_main(int argc, char **argv) { int ret = 1, dirty = 0, seed = 0; int cflags = 0, version = 0, date = 0, options = 0, platform = 0, dir = 0; int engdir = 0, moddir = 0, cpuinfo = 0; char *prog; OPTION_CHOICE o; prog = opt_init(argc, argv, version_options); while ((o = opt_next()) != OPT_EOF) { switch (o) { case OPT_EOF: case OPT_ERR: opthelp: BIO_printf(bio_err, "%s: Use -help for summary.\n", prog); goto end; case OPT_HELP: opt_help(version_options); ret = 0; goto end; case OPT_B: dirty = date = 1; break; case OPT_D: dirty = dir = 1; break; case OPT_E: dirty = engdir = 1; break; case OPT_M: dirty = moddir = 1; break; case OPT_F: dirty = cflags = 1; break; case OPT_O: dirty = options = 1; break; case OPT_P: dirty = platform = 1; break; case OPT_R: dirty = seed = 1; break; case OPT_V: dirty = version = 1; break; case OPT_C: dirty = cpuinfo = 1; break; case OPT_A: seed = options = cflags = version = date = platform = dir = engdir = moddir = cpuinfo = 1; break; } } /* No extra arguments. */ if (!opt_check_rest_arg(NULL)) goto opthelp; if (!dirty) version = 1; if (version) printf("%s (Library: %s)\n", OPENSSL_VERSION_TEXT, OpenSSL_version(OPENSSL_VERSION)); if (date) printf("%s\n", OpenSSL_version(OPENSSL_BUILT_ON)); if (platform) printf("%s\n", OpenSSL_version(OPENSSL_PLATFORM)); if (options) { printf("options: "); printf(" %s", BN_options()); printf("\n"); } if (cflags) printf("%s\n", OpenSSL_version(OPENSSL_CFLAGS)); if (dir) printf("%s\n", OpenSSL_version(OPENSSL_DIR)); if (engdir) printf("%s\n", OpenSSL_version(OPENSSL_ENGINES_DIR)); if (moddir) printf("%s\n", OpenSSL_version(OPENSSL_MODULES_DIR)); if (seed) { const char *src = OPENSSL_info(OPENSSL_INFO_SEED_SOURCE); printf("Seeding source: %s\n", src ? src : "N/A"); } if (cpuinfo) printf("%s\n", OpenSSL_version(OPENSSL_CPU_INFO)); ret = 0; end: return ret; } #if defined(__TANDEM) && defined(OPENSSL_VPROC) /* * Define a VPROC function for the openssl program. * This is used by platform version identification tools. * Do not inline this procedure or make it static. */ # define OPENSSL_VPROC_STRING_(x) x##_OPENSSL # define OPENSSL_VPROC_STRING(x) OPENSSL_VPROC_STRING_(x) # define OPENSSL_VPROC_FUNC OPENSSL_VPROC_STRING(OPENSSL_VPROC) void OPENSSL_VPROC_FUNC(void) {} #endif
./openssl/apps/nseq.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 */ #include <stdio.h> #include <string.h> #include "apps.h" #include "progs.h" #include <openssl/pem.h> #include <openssl/err.h> typedef enum OPTION_choice { OPT_COMMON, OPT_TOSEQ, OPT_IN, OPT_OUT, OPT_PROV_ENUM } OPTION_CHOICE; const OPTIONS nseq_options[] = { OPT_SECTION("General"), {"help", OPT_HELP, '-', "Display this summary"}, OPT_SECTION("Input"), {"in", OPT_IN, '<', "Input file"}, OPT_SECTION("Output"), {"toseq", OPT_TOSEQ, '-', "Output NS Sequence file"}, {"out", OPT_OUT, '>', "Output file"}, OPT_PROV_OPTIONS, {NULL} }; int nseq_main(int argc, char **argv) { BIO *in = NULL, *out = NULL; X509 *x509 = NULL; NETSCAPE_CERT_SEQUENCE *seq = NULL; OPTION_CHOICE o; int toseq = 0, ret = 1, i; char *infile = NULL, *outfile = NULL, *prog; prog = opt_init(argc, argv, nseq_options); while ((o = opt_next()) != OPT_EOF) { switch (o) { case OPT_EOF: case OPT_ERR: opthelp: BIO_printf(bio_err, "%s: Use -help for summary.\n", prog); goto end; case OPT_HELP: ret = 0; opt_help(nseq_options); goto end; case OPT_TOSEQ: toseq = 1; break; case OPT_IN: infile = opt_arg(); break; case OPT_OUT: outfile = opt_arg(); break; case OPT_PROV_CASES: if (!opt_provider(o)) goto end; break; } } /* No extra arguments. */ if (!opt_check_rest_arg(NULL)) goto opthelp; in = bio_open_default(infile, 'r', FORMAT_PEM); if (in == NULL) goto end; out = bio_open_default(outfile, 'w', FORMAT_PEM); if (out == NULL) goto end; if (toseq) { seq = NETSCAPE_CERT_SEQUENCE_new(); if (seq == NULL) goto end; seq->certs = sk_X509_new_null(); if (seq->certs == NULL) goto end; while ((x509 = PEM_read_bio_X509(in, NULL, NULL, NULL))) { if (!sk_X509_push(seq->certs, x509)) goto end; } if (!sk_X509_num(seq->certs)) { BIO_printf(bio_err, "%s: Error reading certs file %s\n", prog, infile); ERR_print_errors(bio_err); goto end; } PEM_write_bio_NETSCAPE_CERT_SEQUENCE(out, seq); ret = 0; goto end; } seq = PEM_read_bio_NETSCAPE_CERT_SEQUENCE(in, NULL, NULL, NULL); if (seq == NULL) { BIO_printf(bio_err, "%s: Error reading sequence file %s\n", prog, infile); ERR_print_errors(bio_err); goto end; } for (i = 0; i < sk_X509_num(seq->certs); i++) { x509 = sk_X509_value(seq->certs, i); dump_cert_text(out, x509); PEM_write_bio_X509(out, x509); } ret = 0; end: BIO_free(in); BIO_free_all(out); NETSCAPE_CERT_SEQUENCE_free(seq); return ret; }
./openssl/apps/pkey.c
/* * Copyright 2006-2023 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <stdio.h> #include <string.h> #include "apps.h" #include "progs.h" #include "ec_common.h" #include <openssl/pem.h> #include <openssl/err.h> #include <openssl/evp.h> #include <openssl/core_names.h> typedef enum OPTION_choice { OPT_COMMON, OPT_INFORM, OPT_OUTFORM, OPT_PASSIN, OPT_PASSOUT, OPT_ENGINE, OPT_IN, OPT_OUT, OPT_PUBIN, OPT_PUBOUT, OPT_TEXT_PUB, OPT_TEXT, OPT_NOOUT, OPT_CIPHER, OPT_TRADITIONAL, OPT_CHECK, OPT_PUB_CHECK, OPT_EC_PARAM_ENC, OPT_EC_CONV_FORM, OPT_PROV_ENUM } OPTION_CHOICE; const OPTIONS pkey_options[] = { OPT_SECTION("General"), {"help", OPT_HELP, '-', "Display this summary"}, #ifndef OPENSSL_NO_ENGINE {"engine", OPT_ENGINE, 's', "Use engine, possibly a hardware device"}, #endif OPT_PROV_OPTIONS, {"check", OPT_CHECK, '-', "Check key consistency"}, {"pubcheck", OPT_PUB_CHECK, '-', "Check public key consistency"}, OPT_SECTION("Input"), {"in", OPT_IN, 's', "Input key"}, {"inform", OPT_INFORM, 'f', "Key input format (ENGINE, other values ignored)"}, {"passin", OPT_PASSIN, 's', "Key input pass phrase source"}, {"pubin", OPT_PUBIN, '-', "Read only public components from key input"}, OPT_SECTION("Output"), {"out", OPT_OUT, '>', "Output file for encoded and/or text output"}, {"outform", OPT_OUTFORM, 'F', "Output encoding format (DER or PEM)"}, {"", OPT_CIPHER, '-', "Any supported cipher to be used for encryption"}, {"passout", OPT_PASSOUT, 's', "Output PEM file pass phrase source"}, {"traditional", OPT_TRADITIONAL, '-', "Use traditional format for private key PEM output"}, {"pubout", OPT_PUBOUT, '-', "Restrict encoded output to public components"}, {"noout", OPT_NOOUT, '-', "Do not output the key in encoded form"}, {"text", OPT_TEXT, '-', "Output key components in plaintext"}, {"text_pub", OPT_TEXT_PUB, '-', "Output only public key components in text form"}, {"ec_conv_form", OPT_EC_CONV_FORM, 's', "Specifies the EC point conversion form in the encoding"}, {"ec_param_enc", OPT_EC_PARAM_ENC, 's', "Specifies the way the EC parameters are encoded"}, {NULL} }; int pkey_main(int argc, char **argv) { BIO *out = NULL; ENGINE *e = NULL; EVP_PKEY *pkey = NULL; EVP_PKEY_CTX *ctx = NULL; EVP_CIPHER *cipher = NULL; char *infile = NULL, *outfile = NULL, *passin = NULL, *passout = NULL; char *passinarg = NULL, *passoutarg = NULL, *ciphername = NULL, *prog; OPTION_CHOICE o; int informat = FORMAT_UNDEF, outformat = FORMAT_PEM; int pubin = 0, pubout = 0, text_pub = 0, text = 0, noout = 0, ret = 1; int private = 0, traditional = 0, check = 0, pub_check = 0; #ifndef OPENSSL_NO_EC char *asn1_encoding = NULL; char *point_format = NULL; #endif opt_set_unknown_name("cipher"); prog = opt_init(argc, argv, pkey_options); while ((o = opt_next()) != OPT_EOF) { switch (o) { case OPT_EOF: case OPT_ERR: opthelp: BIO_printf(bio_err, "%s: Use -help for summary.\n", prog); goto end; case OPT_HELP: opt_help(pkey_options); ret = 0; goto end; case OPT_INFORM: if (!opt_format(opt_arg(), OPT_FMT_ANY, &informat)) goto opthelp; break; case OPT_OUTFORM: if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &outformat)) goto opthelp; break; case OPT_PASSIN: passinarg = opt_arg(); break; case OPT_PASSOUT: passoutarg = opt_arg(); break; case OPT_ENGINE: e = setup_engine(opt_arg(), 0); break; case OPT_IN: infile = opt_arg(); break; case OPT_OUT: outfile = opt_arg(); break; case OPT_PUBIN: pubin = pubout = 1; break; case OPT_PUBOUT: pubout = 1; break; case OPT_TEXT_PUB: text_pub = 1; break; case OPT_TEXT: text = 1; break; case OPT_NOOUT: noout = 1; break; case OPT_TRADITIONAL: traditional = 1; break; case OPT_CHECK: check = 1; break; case OPT_PUB_CHECK: pub_check = 1; break; case OPT_CIPHER: ciphername = opt_unknown(); break; case OPT_EC_CONV_FORM: #ifdef OPENSSL_NO_EC goto opthelp; #else point_format = opt_arg(); if (!opt_string(point_format, point_format_options)) goto opthelp; break; #endif case OPT_EC_PARAM_ENC: #ifdef OPENSSL_NO_EC goto opthelp; #else asn1_encoding = opt_arg(); if (!opt_string(asn1_encoding, asn1_encoding_options)) goto opthelp; break; #endif case OPT_PROV_CASES: if (!opt_provider(o)) goto end; break; } } /* No extra arguments. */ if (!opt_check_rest_arg(NULL)) goto opthelp; if (text && text_pub) BIO_printf(bio_err, "Warning: The -text option is ignored with -text_pub\n"); if (traditional && (noout || outformat != FORMAT_PEM)) BIO_printf(bio_err, "Warning: The -traditional is ignored since there is no PEM output\n"); /* -pubout and -text is the same as -text_pub */ if (!text_pub && pubout && text) { text = 0; text_pub = 1; } private = (!noout && !pubout) || (text && !text_pub); if (!opt_cipher(ciphername, &cipher)) goto opthelp; if (cipher == NULL) { if (passoutarg != NULL) BIO_printf(bio_err, "Warning: The -passout option is ignored without a cipher option\n"); } else { if (noout || outformat != FORMAT_PEM) { BIO_printf(bio_err, "Error: Cipher options are supported only for PEM output\n"); goto end; } } if (!app_passwd(passinarg, passoutarg, &passin, &passout)) { BIO_printf(bio_err, "Error getting passwords\n"); goto end; } out = bio_open_owner(outfile, outformat, private); if (out == NULL) goto end; if (pubin) pkey = load_pubkey(infile, informat, 1, passin, e, "Public Key"); else pkey = load_key(infile, informat, 1, passin, e, "key"); if (pkey == NULL) goto end; #ifndef OPENSSL_NO_EC if (asn1_encoding != NULL || point_format != NULL) { OSSL_PARAM params[3], *p = params; if (!EVP_PKEY_is_a(pkey, "EC")) goto end; if (asn1_encoding != NULL) *p++ = OSSL_PARAM_construct_utf8_string(OSSL_PKEY_PARAM_EC_ENCODING, asn1_encoding, 0); if (point_format != NULL) *p++ = OSSL_PARAM_construct_utf8_string( OSSL_PKEY_PARAM_EC_POINT_CONVERSION_FORMAT, point_format, 0); *p = OSSL_PARAM_construct_end(); if (EVP_PKEY_set_params(pkey, params) <= 0) goto end; } #endif if (check || pub_check) { int r; ctx = EVP_PKEY_CTX_new(pkey, e); if (ctx == NULL) { ERR_print_errors(bio_err); goto end; } if (check && !pubin) r = EVP_PKEY_check(ctx); else r = EVP_PKEY_public_check(ctx); if (r == 1) { BIO_printf(out, "Key is valid\n"); } else { /* * Note: at least for RSA keys if this function returns * -1, there will be no error reasons. */ BIO_printf(bio_err, "Key is invalid\n"); ERR_print_errors(bio_err); goto end; } } if (!noout) { if (outformat == FORMAT_PEM) { if (pubout) { if (!PEM_write_bio_PUBKEY(out, pkey)) goto end; } else { assert(private); if (traditional) { if (!PEM_write_bio_PrivateKey_traditional(out, pkey, cipher, NULL, 0, NULL, passout)) goto end; } else { if (!PEM_write_bio_PrivateKey(out, pkey, cipher, NULL, 0, NULL, passout)) goto end; } } } else if (outformat == FORMAT_ASN1) { if (text || text_pub) { BIO_printf(bio_err, "Error: Text output cannot be combined with DER output\n"); goto end; } if (pubout) { if (!i2d_PUBKEY_bio(out, pkey)) goto end; } else { assert(private); if (!i2d_PrivateKey_bio(out, pkey)) goto end; } } else { BIO_printf(bio_err, "Bad format specified for key\n"); goto end; } } if (text_pub) { if (EVP_PKEY_print_public(out, pkey, 0, NULL) <= 0) goto end; } else if (text) { assert(private); if (EVP_PKEY_print_private(out, pkey, 0, NULL) <= 0) goto end; } ret = 0; end: if (ret != 0) ERR_print_errors(bio_err); EVP_PKEY_CTX_free(ctx); EVP_PKEY_free(pkey); EVP_CIPHER_free(cipher); release_engine(e); BIO_free_all(out); OPENSSL_free(passin); OPENSSL_free(passout); return ret; }
./openssl/apps/pkcs8.c
/* * Copyright 1999-2023 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include "apps.h" #include "progs.h" #include <openssl/pem.h> #include <openssl/err.h> #include <openssl/evp.h> #include <openssl/pkcs12.h> #define STR(a) XSTR(a) #define XSTR(a) #a typedef enum OPTION_choice { OPT_COMMON, OPT_INFORM, OPT_OUTFORM, OPT_ENGINE, OPT_IN, OPT_OUT, OPT_TOPK8, OPT_NOITER, OPT_NOCRYPT, #ifndef OPENSSL_NO_SCRYPT OPT_SCRYPT, OPT_SCRYPT_N, OPT_SCRYPT_R, OPT_SCRYPT_P, #endif OPT_V2, OPT_V1, OPT_V2PRF, OPT_ITER, OPT_PASSIN, OPT_PASSOUT, OPT_TRADITIONAL, OPT_SALTLEN, OPT_R_ENUM, OPT_PROV_ENUM } OPTION_CHOICE; const OPTIONS pkcs8_options[] = { OPT_SECTION("General"), {"help", OPT_HELP, '-', "Display this summary"}, #ifndef OPENSSL_NO_ENGINE {"engine", OPT_ENGINE, 's', "Use engine, possibly a hardware device"}, #endif {"v1", OPT_V1, 's', "Use PKCS#5 v1.5 and cipher"}, {"v2", OPT_V2, 's', "Use PKCS#5 v2.0 and cipher"}, {"v2prf", OPT_V2PRF, 's', "Set the PRF algorithm to use with PKCS#5 v2.0"}, OPT_SECTION("Input"), {"in", OPT_IN, '<', "Input file"}, {"inform", OPT_INFORM, 'F', "Input format (DER or PEM)"}, {"passin", OPT_PASSIN, 's', "Input file pass phrase source"}, {"nocrypt", OPT_NOCRYPT, '-', "Use or expect unencrypted private key"}, OPT_SECTION("Output"), {"out", OPT_OUT, '>', "Output file"}, {"outform", OPT_OUTFORM, 'F', "Output format (DER or PEM)"}, {"topk8", OPT_TOPK8, '-', "Output PKCS8 file"}, {"passout", OPT_PASSOUT, 's', "Output file pass phrase source"}, {"traditional", OPT_TRADITIONAL, '-', "use traditional format private key"}, {"iter", OPT_ITER, 'p', "Specify the iteration count"}, {"noiter", OPT_NOITER, '-', "Use 1 as iteration count"}, {"saltlen", OPT_SALTLEN, 'p', "Specify the salt length (in bytes)"}, {OPT_MORE_STR, 0, 0, "Default: 8 (For PBE1) or 16 (for PBE2)"}, #ifndef OPENSSL_NO_SCRYPT OPT_SECTION("Scrypt"), {"scrypt", OPT_SCRYPT, '-', "Use scrypt algorithm"}, {"scrypt_N", OPT_SCRYPT_N, 's', "Set scrypt N parameter"}, {"scrypt_r", OPT_SCRYPT_R, 's', "Set scrypt r parameter"}, {"scrypt_p", OPT_SCRYPT_P, 's', "Set scrypt p parameter"}, #endif OPT_R_OPTIONS, OPT_PROV_OPTIONS, {NULL} }; int pkcs8_main(int argc, char **argv) { BIO *in = NULL, *out = NULL; ENGINE *e = NULL; EVP_PKEY *pkey = NULL; PKCS8_PRIV_KEY_INFO *p8inf = NULL; X509_SIG *p8 = NULL; EVP_CIPHER *cipher = NULL; char *infile = NULL, *outfile = NULL, *ciphername = NULL; char *passinarg = NULL, *passoutarg = NULL, *prog; #ifndef OPENSSL_NO_UI_CONSOLE char pass[APP_PASS_LEN]; #endif char *passin = NULL, *passout = NULL, *p8pass = NULL; OPTION_CHOICE o; int nocrypt = 0, ret = 1, iter = PKCS12_DEFAULT_ITER; int informat = FORMAT_UNDEF, outformat = FORMAT_PEM, topk8 = 0, pbe_nid = -1; int private = 0, traditional = 0; #ifndef OPENSSL_NO_SCRYPT long scrypt_N = 0, scrypt_r = 0, scrypt_p = 0; #endif int saltlen = 0; /* A value of zero chooses the default */ prog = opt_init(argc, argv, pkcs8_options); while ((o = opt_next()) != OPT_EOF) { switch (o) { case OPT_EOF: case OPT_ERR: opthelp: BIO_printf(bio_err, "%s: Use -help for summary.\n", prog); goto end; case OPT_HELP: opt_help(pkcs8_options); ret = 0; goto end; case OPT_INFORM: if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &informat)) goto opthelp; break; case OPT_IN: infile = opt_arg(); break; case OPT_OUTFORM: if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &outformat)) goto opthelp; break; case OPT_OUT: outfile = opt_arg(); break; case OPT_TOPK8: topk8 = 1; break; case OPT_NOITER: iter = 1; break; case OPT_NOCRYPT: nocrypt = 1; break; case OPT_R_CASES: if (!opt_rand(o)) goto end; break; case OPT_PROV_CASES: if (!opt_provider(o)) goto end; break; case OPT_TRADITIONAL: traditional = 1; break; case OPT_V2: ciphername = opt_arg(); break; case OPT_V1: pbe_nid = OBJ_txt2nid(opt_arg()); if (pbe_nid == NID_undef) { BIO_printf(bio_err, "%s: Unknown PBE algorithm %s\n", prog, opt_arg()); goto opthelp; } break; case OPT_V2PRF: pbe_nid = OBJ_txt2nid(opt_arg()); if (!EVP_PBE_find(EVP_PBE_TYPE_PRF, pbe_nid, NULL, NULL, 0)) { BIO_printf(bio_err, "%s: Unknown PRF algorithm %s\n", prog, opt_arg()); goto opthelp; } if (cipher == NULL) cipher = (EVP_CIPHER *)EVP_aes_256_cbc(); break; case OPT_ITER: iter = opt_int_arg(); break; case OPT_PASSIN: passinarg = opt_arg(); break; case OPT_PASSOUT: passoutarg = opt_arg(); break; case OPT_ENGINE: e = setup_engine(opt_arg(), 0); break; #ifndef OPENSSL_NO_SCRYPT case OPT_SCRYPT: scrypt_N = 16384; scrypt_r = 8; scrypt_p = 1; if (cipher == NULL) cipher = (EVP_CIPHER *)EVP_aes_256_cbc(); break; case OPT_SCRYPT_N: if (!opt_long(opt_arg(), &scrypt_N) || scrypt_N <= 0) goto opthelp; break; case OPT_SCRYPT_R: if (!opt_long(opt_arg(), &scrypt_r) || scrypt_r <= 0) goto opthelp; break; case OPT_SCRYPT_P: if (!opt_long(opt_arg(), &scrypt_p) || scrypt_p <= 0) goto opthelp; break; #endif case OPT_SALTLEN: if (!opt_int(opt_arg(), &saltlen)) goto opthelp; break; } } /* No extra arguments. */ if (!opt_check_rest_arg(NULL)) goto opthelp; private = 1; if (!app_RAND_load()) goto end; if (ciphername != NULL) { if (!opt_cipher(ciphername, &cipher)) goto opthelp; } if (!app_passwd(passinarg, passoutarg, &passin, &passout)) { BIO_printf(bio_err, "Error getting passwords\n"); goto end; } if ((pbe_nid == -1) && cipher == NULL) cipher = (EVP_CIPHER *)EVP_aes_256_cbc(); in = bio_open_default(infile, 'r', informat == FORMAT_UNDEF ? FORMAT_PEM : informat); if (in == NULL) goto end; out = bio_open_owner(outfile, outformat, private); if (out == NULL) goto end; if (topk8) { pkey = load_key(infile, informat, 1, passin, e, "key"); if (pkey == NULL) goto end; if ((p8inf = EVP_PKEY2PKCS8(pkey)) == NULL) { BIO_printf(bio_err, "Error converting key\n"); ERR_print_errors(bio_err); goto end; } if (nocrypt) { assert(private); if (outformat == FORMAT_PEM) { PEM_write_bio_PKCS8_PRIV_KEY_INFO(out, p8inf); } else if (outformat == FORMAT_ASN1) { i2d_PKCS8_PRIV_KEY_INFO_bio(out, p8inf); } else { BIO_printf(bio_err, "Bad format specified for key\n"); goto end; } } else { X509_ALGOR *pbe; if (cipher) { #ifndef OPENSSL_NO_SCRYPT if (scrypt_N && scrypt_r && scrypt_p) pbe = PKCS5_pbe2_set_scrypt(cipher, NULL, saltlen, NULL, scrypt_N, scrypt_r, scrypt_p); else #endif pbe = PKCS5_pbe2_set_iv(cipher, iter, NULL, saltlen, NULL, pbe_nid); } else { pbe = PKCS5_pbe_set(pbe_nid, iter, NULL, saltlen); } if (pbe == NULL) { BIO_printf(bio_err, "Error setting PBE algorithm\n"); ERR_print_errors(bio_err); goto end; } if (passout != NULL) { p8pass = passout; } else if (1) { /* To avoid bit rot */ #ifndef OPENSSL_NO_UI_CONSOLE p8pass = pass; if (EVP_read_pw_string (pass, sizeof(pass), "Enter Encryption Password:", 1)) { X509_ALGOR_free(pbe); goto end; } } else { #endif BIO_printf(bio_err, "Password required\n"); goto end; } p8 = PKCS8_set0_pbe(p8pass, strlen(p8pass), p8inf, pbe); if (p8 == NULL) { X509_ALGOR_free(pbe); BIO_printf(bio_err, "Error encrypting key\n"); ERR_print_errors(bio_err); goto end; } assert(private); if (outformat == FORMAT_PEM) PEM_write_bio_PKCS8(out, p8); else if (outformat == FORMAT_ASN1) i2d_PKCS8_bio(out, p8); else { BIO_printf(bio_err, "Bad format specified for key\n"); goto end; } } ret = 0; goto end; } if (nocrypt) { if (informat == FORMAT_PEM || informat == FORMAT_UNDEF) { p8inf = PEM_read_bio_PKCS8_PRIV_KEY_INFO(in, NULL, NULL, NULL); } else if (informat == FORMAT_ASN1) { p8inf = d2i_PKCS8_PRIV_KEY_INFO_bio(in, NULL); } else { BIO_printf(bio_err, "Bad format specified for key\n"); goto end; } } else { if (informat == FORMAT_PEM || informat == FORMAT_UNDEF) { p8 = PEM_read_bio_PKCS8(in, NULL, NULL, NULL); } else if (informat == FORMAT_ASN1) { p8 = d2i_PKCS8_bio(in, NULL); } else { BIO_printf(bio_err, "Bad format specified for key\n"); goto end; } if (p8 == NULL) { BIO_printf(bio_err, "Error reading key\n"); ERR_print_errors(bio_err); goto end; } if (passin != NULL) { p8pass = passin; } else if (1) { #ifndef OPENSSL_NO_UI_CONSOLE p8pass = pass; if (EVP_read_pw_string(pass, sizeof(pass), "Enter Password:", 0)) { BIO_printf(bio_err, "Can't read Password\n"); goto end; } } else { #endif BIO_printf(bio_err, "Password required\n"); goto end; } p8inf = PKCS8_decrypt(p8, p8pass, strlen(p8pass)); } if (p8inf == NULL) { BIO_printf(bio_err, "Error decrypting key\n"); ERR_print_errors(bio_err); goto end; } if ((pkey = EVP_PKCS82PKEY(p8inf)) == NULL) { BIO_printf(bio_err, "Error converting key\n"); ERR_print_errors(bio_err); goto end; } assert(private); if (outformat == FORMAT_PEM) { if (traditional) PEM_write_bio_PrivateKey_traditional(out, pkey, NULL, NULL, 0, NULL, passout); else PEM_write_bio_PrivateKey(out, pkey, NULL, NULL, 0, NULL, passout); } else if (outformat == FORMAT_ASN1) { i2d_PrivateKey_bio(out, pkey); } else { BIO_printf(bio_err, "Bad format specified for key\n"); goto end; } ret = 0; end: X509_SIG_free(p8); PKCS8_PRIV_KEY_INFO_free(p8inf); EVP_PKEY_free(pkey); EVP_CIPHER_free(cipher); release_engine(e); BIO_free_all(out); BIO_free(in); OPENSSL_free(passin); OPENSSL_free(passout); return ret; }
./openssl/apps/errstr.c
/* * Copyright 1995-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 <stdlib.h> #include <string.h> #include "apps.h" #include "progs.h" #include <openssl/bio.h> #include <openssl/err.h> #include <openssl/ssl.h> typedef enum OPTION_choice { OPT_ERR = -1, OPT_EOF = 0, OPT_HELP } OPTION_CHOICE; const OPTIONS errstr_options[] = { {OPT_HELP_STR, 1, '-', "Usage: %s [options] errnum...\n"}, OPT_SECTION("General"), {"help", OPT_HELP, '-', "Display this summary"}, OPT_PARAMETERS(), {"errnum", 0, 0, "Error number(s) to decode"}, {NULL} }; int errstr_main(int argc, char **argv) { OPTION_CHOICE o; char buf[256], *prog; int ret = 1; unsigned long l; prog = opt_init(argc, argv, errstr_options); while ((o = opt_next()) != OPT_EOF) { switch (o) { case OPT_EOF: case OPT_ERR: BIO_printf(bio_err, "%s: Use -help for summary.\n", prog); goto end; case OPT_HELP: opt_help(errstr_options); ret = 0; goto end; } } /* * We're not really an SSL application so this won't auto-init, but * we're still interested in SSL error strings */ OPENSSL_init_ssl(OPENSSL_INIT_LOAD_SSL_STRINGS | OPENSSL_INIT_LOAD_CRYPTO_STRINGS, NULL); /* All remaining arg are error code. */ ret = 0; for (argv = opt_rest(); *argv != NULL; argv++) { if (sscanf(*argv, "%lx", &l) <= 0) { ret++; } else { ERR_error_string_n(l, buf, sizeof(buf)); BIO_printf(bio_out, "%s\n", buf); } } end: return ret; }
./openssl/apps/ocsp.c
/* * Copyright 2001-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/opensslconf.h> #ifdef OPENSSL_SYS_VMS /* So fd_set and friends get properly defined on OpenVMS */ # define _XOPEN_SOURCE_EXTENDED #endif #include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> #include <ctype.h> /* Needs to be included before the openssl headers */ #include "apps.h" #include "http_server.h" #include "progs.h" #include "internal/sockets.h" #include <openssl/e_os2.h> #include <openssl/crypto.h> #include <openssl/err.h> #include <openssl/ssl.h> #include <openssl/evp.h> #include <openssl/bn.h> #include <openssl/x509v3.h> #if defined(__TANDEM) # if defined(OPENSSL_TANDEM_FLOSS) # include <floss.h(floss_fork)> # endif #endif #if defined(OPENSSL_SYS_VXWORKS) /* not supported */ int setpgid(pid_t pid, pid_t pgid) { errno = ENOSYS; return 0; } /* not supported */ pid_t fork(void) { errno = ENOSYS; return (pid_t) -1; } #endif /* Maximum leeway in validity period: default 5 minutes */ #define MAX_VALIDITY_PERIOD (5 * 60) static int add_ocsp_cert(OCSP_REQUEST **req, X509 *cert, const EVP_MD *cert_id_md, X509 *issuer, STACK_OF(OCSP_CERTID) *ids); static int add_ocsp_serial(OCSP_REQUEST **req, char *serial, const EVP_MD *cert_id_md, X509 *issuer, STACK_OF(OCSP_CERTID) *ids); static int print_ocsp_summary(BIO *out, OCSP_BASICRESP *bs, OCSP_REQUEST *req, STACK_OF(OPENSSL_STRING) *names, STACK_OF(OCSP_CERTID) *ids, long nsec, long maxage); static void make_ocsp_response(BIO *err, OCSP_RESPONSE **resp, OCSP_REQUEST *req, CA_DB *db, STACK_OF(X509) *ca, X509 *rcert, EVP_PKEY *rkey, const EVP_MD *md, STACK_OF(OPENSSL_STRING) *sigopts, STACK_OF(X509) *rother, unsigned long flags, int nmin, int ndays, int badsig, const EVP_MD *resp_md); static char **lookup_serial(CA_DB *db, ASN1_INTEGER *ser); static int do_responder(OCSP_REQUEST **preq, BIO **pcbio, BIO *acbio, int timeout); static int send_ocsp_response(BIO *cbio, const OCSP_RESPONSE *resp); static char *prog; #ifdef HTTP_DAEMON static int index_changed(CA_DB *); #endif typedef enum OPTION_choice { OPT_COMMON, OPT_OUTFILE, OPT_TIMEOUT, OPT_URL, OPT_HOST, OPT_PORT, #ifndef OPENSSL_NO_SOCK OPT_PROXY, OPT_NO_PROXY, #endif OPT_IGNORE_ERR, OPT_NOVERIFY, OPT_NONCE, OPT_NO_NONCE, OPT_RESP_NO_CERTS, OPT_RESP_KEY_ID, OPT_NO_CERTS, OPT_NO_SIGNATURE_VERIFY, OPT_NO_CERT_VERIFY, OPT_NO_CHAIN, OPT_NO_CERT_CHECKS, OPT_NO_EXPLICIT, OPT_TRUST_OTHER, OPT_NO_INTERN, OPT_BADSIG, OPT_TEXT, OPT_REQ_TEXT, OPT_RESP_TEXT, OPT_REQIN, OPT_RESPIN, OPT_SIGNER, OPT_VAFILE, OPT_SIGN_OTHER, OPT_VERIFY_OTHER, OPT_CAFILE, OPT_CAPATH, OPT_CASTORE, OPT_NOCAFILE, OPT_NOCAPATH, OPT_NOCASTORE, OPT_VALIDITY_PERIOD, OPT_STATUS_AGE, OPT_SIGNKEY, OPT_REQOUT, OPT_RESPOUT, OPT_PATH, OPT_ISSUER, OPT_CERT, OPT_SERIAL, OPT_INDEX, OPT_CA, OPT_NMIN, OPT_REQUEST, OPT_NDAYS, OPT_RSIGNER, OPT_RKEY, OPT_ROTHER, OPT_RMD, OPT_RSIGOPT, OPT_HEADER, OPT_PASSIN, OPT_RCID, OPT_V_ENUM, OPT_MD, OPT_MULTI, OPT_PROV_ENUM } OPTION_CHOICE; const OPTIONS ocsp_options[] = { OPT_SECTION("General"), {"help", OPT_HELP, '-', "Display this summary"}, {"ignore_err", OPT_IGNORE_ERR, '-', "Ignore error on OCSP request or response and continue running"}, {"CAfile", OPT_CAFILE, '<', "Trusted certificates file"}, {"CApath", OPT_CAPATH, '<', "Trusted certificates directory"}, {"CAstore", OPT_CASTORE, ':', "Trusted certificates store URI"}, {"no-CAfile", OPT_NOCAFILE, '-', "Do not load the default certificates file"}, {"no-CApath", OPT_NOCAPATH, '-', "Do not load certificates from the default certificates directory"}, {"no-CAstore", OPT_NOCASTORE, '-', "Do not load certificates from the default certificates store"}, OPT_SECTION("Responder"), {"timeout", OPT_TIMEOUT, 'p', "Connection timeout (in seconds) to the OCSP responder"}, {"resp_no_certs", OPT_RESP_NO_CERTS, '-', "Don't include any certificates in response"}, #ifdef HTTP_DAEMON {"multi", OPT_MULTI, 'p', "run multiple responder processes"}, #endif {"no_certs", OPT_NO_CERTS, '-', "Don't include any certificates in signed request"}, {"badsig", OPT_BADSIG, '-', "Corrupt last byte of loaded OCSP response signature (for test)"}, {"CA", OPT_CA, '<', "CA certificates"}, {"nmin", OPT_NMIN, 'p', "Number of minutes before next update"}, {"nrequest", OPT_REQUEST, 'p', "Number of requests to accept (default unlimited)"}, {"reqin", OPT_REQIN, 's', "File with the DER-encoded request"}, {"signer", OPT_SIGNER, '<', "Certificate to sign OCSP request with"}, {"sign_other", OPT_SIGN_OTHER, '<', "Additional certificates to include in signed request"}, {"index", OPT_INDEX, '<', "Certificate status index file"}, {"ndays", OPT_NDAYS, 'p', "Number of days before next update"}, {"rsigner", OPT_RSIGNER, '<', "Responder certificate to sign responses with"}, {"rkey", OPT_RKEY, '<', "Responder key to sign responses with"}, {"passin", OPT_PASSIN, 's', "Responder key pass phrase source"}, {"rother", OPT_ROTHER, '<', "Other certificates to include in response"}, {"rmd", OPT_RMD, 's', "Digest Algorithm to use in signature of OCSP response"}, {"rsigopt", OPT_RSIGOPT, 's', "OCSP response signature parameter in n:v form"}, {"header", OPT_HEADER, 's', "key=value header to add"}, {"rcid", OPT_RCID, 's', "Use specified algorithm for cert id in response"}, {"", OPT_MD, '-', "Any supported digest algorithm (sha1,sha256, ... )"}, OPT_SECTION("Client"), {"url", OPT_URL, 's', "Responder URL"}, {"host", OPT_HOST, 's', "TCP/IP hostname:port to connect to"}, {"port", OPT_PORT, 'N', "Port to run responder on"}, {"path", OPT_PATH, 's', "Path to use in OCSP request"}, #ifndef OPENSSL_NO_SOCK {"proxy", OPT_PROXY, 's', "[http[s]://]host[:port][/path] of HTTP(S) proxy to use; path is ignored"}, {"no_proxy", OPT_NO_PROXY, 's', "List of addresses of servers not to use HTTP(S) proxy for"}, {OPT_MORE_STR, 0, 0, "Default from environment variable 'no_proxy', else 'NO_PROXY', else none"}, #endif {"out", OPT_OUTFILE, '>', "Output filename"}, {"noverify", OPT_NOVERIFY, '-', "Don't verify response at all"}, {"nonce", OPT_NONCE, '-', "Add OCSP nonce to request"}, {"no_nonce", OPT_NO_NONCE, '-', "Don't add OCSP nonce to request"}, {"no_signature_verify", OPT_NO_SIGNATURE_VERIFY, '-', "Don't check signature on response"}, {"resp_key_id", OPT_RESP_KEY_ID, '-', "Identify response by signing certificate key ID"}, {"no_cert_verify", OPT_NO_CERT_VERIFY, '-', "Don't check signing certificate"}, {"text", OPT_TEXT, '-', "Print text form of request and response"}, {"req_text", OPT_REQ_TEXT, '-', "Print text form of request"}, {"resp_text", OPT_RESP_TEXT, '-', "Print text form of response"}, {"no_chain", OPT_NO_CHAIN, '-', "Don't chain verify response"}, {"no_cert_checks", OPT_NO_CERT_CHECKS, '-', "Don't do additional checks on signing certificate"}, {"no_explicit", OPT_NO_EXPLICIT, '-', "Do not explicitly check the chain, just verify the root"}, {"trust_other", OPT_TRUST_OTHER, '-', "Don't verify additional certificates"}, {"no_intern", OPT_NO_INTERN, '-', "Don't search certificates contained in response for signer"}, {"respin", OPT_RESPIN, 's', "File with the DER-encoded response"}, {"VAfile", OPT_VAFILE, '<', "Validator certificates file"}, {"verify_other", OPT_VERIFY_OTHER, '<', "Additional certificates to search for signer"}, {"cert", OPT_CERT, '<', "Certificate to check; may be given multiple times"}, {"serial", OPT_SERIAL, 's', "Serial number to check; may be given multiple times"}, {"validity_period", OPT_VALIDITY_PERIOD, 'u', "Maximum validity discrepancy in seconds"}, {"signkey", OPT_SIGNKEY, 's', "Private key to sign OCSP request with"}, {"reqout", OPT_REQOUT, 's', "Output file for the DER-encoded request"}, {"respout", OPT_RESPOUT, 's', "Output file for the DER-encoded response"}, {"issuer", OPT_ISSUER, '<', "Issuer certificate"}, {"status_age", OPT_STATUS_AGE, 'p', "Maximum status age in seconds"}, OPT_V_OPTIONS, OPT_PROV_OPTIONS, {NULL} }; int ocsp_main(int argc, char **argv) { BIO *acbio = NULL, *cbio = NULL, *derbio = NULL, *out = NULL; EVP_MD *cert_id_md = NULL, *rsign_md = NULL; STACK_OF(OPENSSL_STRING) *rsign_sigopts = NULL; int trailing_md = 0; CA_DB *rdb = NULL; EVP_PKEY *key = NULL, *rkey = NULL; OCSP_BASICRESP *bs = NULL; OCSP_REQUEST *req = NULL; OCSP_RESPONSE *resp = NULL; STACK_OF(CONF_VALUE) *headers = NULL; STACK_OF(OCSP_CERTID) *ids = NULL; STACK_OF(OPENSSL_STRING) *reqnames = NULL; STACK_OF(X509) *sign_other = NULL, *verify_other = NULL, *rother = NULL; STACK_OF(X509) *issuers = NULL; X509 *issuer = NULL, *cert = NULL; STACK_OF(X509) *rca_certs = NULL; EVP_MD *resp_certid_md = NULL; X509 *signer = NULL, *rsigner = NULL; X509_STORE *store = NULL; X509_VERIFY_PARAM *vpm = NULL; const char *CAfile = NULL, *CApath = NULL, *CAstore = NULL; char *header, *value, *respdigname = NULL; char *host = NULL, *port = NULL, *path = "/", *outfile = NULL; #ifndef OPENSSL_NO_SOCK char *opt_proxy = NULL; char *opt_no_proxy = NULL; #endif char *rca_filename = NULL, *reqin = NULL, *respin = NULL; char *reqout = NULL, *respout = NULL, *ridx_filename = NULL; char *rsignfile = NULL, *rkeyfile = NULL; char *passinarg = NULL, *passin = NULL; char *sign_certfile = NULL, *verify_certfile = NULL, *rcertfile = NULL; char *signfile = NULL, *keyfile = NULL; char *thost = NULL, *tport = NULL, *tpath = NULL; int noCAfile = 0, noCApath = 0, noCAstore = 0; int accept_count = -1, add_nonce = 1, noverify = 0, use_ssl = -1; int vpmtouched = 0, badsig = 0, i, ignore_err = 0, nmin = 0, ndays = -1; int req_text = 0, resp_text = 0, res, ret = 1; int req_timeout = -1; long nsec = MAX_VALIDITY_PERIOD, maxage = -1; unsigned long sign_flags = 0, verify_flags = 0, rflags = 0; OPTION_CHOICE o; if ((reqnames = sk_OPENSSL_STRING_new_null()) == NULL || (ids = sk_OCSP_CERTID_new_null()) == NULL || (vpm = X509_VERIFY_PARAM_new()) == NULL) goto end; opt_set_unknown_name("digest"); prog = opt_init(argc, argv, ocsp_options); while ((o = opt_next()) != OPT_EOF) { switch (o) { case OPT_EOF: case OPT_ERR: opthelp: BIO_printf(bio_err, "%s: Use -help for summary.\n", prog); goto end; case OPT_HELP: ret = 0; opt_help(ocsp_options); goto end; case OPT_OUTFILE: outfile = opt_arg(); break; case OPT_TIMEOUT: #ifndef OPENSSL_NO_SOCK req_timeout = atoi(opt_arg()); #endif break; case OPT_URL: OPENSSL_free(thost); OPENSSL_free(tport); OPENSSL_free(tpath); thost = tport = tpath = NULL; if (!OSSL_HTTP_parse_url(opt_arg(), &use_ssl, NULL /* userinfo */, &host, &port, NULL /* port_num */, &path, NULL /* qry */, NULL /* frag */)) { BIO_printf(bio_err, "%s Error parsing -url argument\n", prog); goto end; } thost = host; tport = port; tpath = path; break; case OPT_HOST: host = opt_arg(); break; case OPT_PORT: port = opt_arg(); break; case OPT_PATH: path = opt_arg(); break; #ifndef OPENSSL_NO_SOCK case OPT_PROXY: opt_proxy = opt_arg(); break; case OPT_NO_PROXY: opt_no_proxy = opt_arg(); break; #endif case OPT_IGNORE_ERR: ignore_err = 1; break; case OPT_NOVERIFY: noverify = 1; break; case OPT_NONCE: add_nonce = 2; break; case OPT_NO_NONCE: add_nonce = 0; break; case OPT_RESP_NO_CERTS: rflags |= OCSP_NOCERTS; break; case OPT_RESP_KEY_ID: rflags |= OCSP_RESPID_KEY; break; case OPT_NO_CERTS: sign_flags |= OCSP_NOCERTS; break; case OPT_NO_SIGNATURE_VERIFY: verify_flags |= OCSP_NOSIGS; break; case OPT_NO_CERT_VERIFY: verify_flags |= OCSP_NOVERIFY; break; case OPT_NO_CHAIN: verify_flags |= OCSP_NOCHAIN; break; case OPT_NO_CERT_CHECKS: verify_flags |= OCSP_NOCHECKS; break; case OPT_NO_EXPLICIT: verify_flags |= OCSP_NOEXPLICIT; break; case OPT_TRUST_OTHER: verify_flags |= OCSP_TRUSTOTHER; break; case OPT_NO_INTERN: verify_flags |= OCSP_NOINTERN; break; case OPT_BADSIG: badsig = 1; break; case OPT_TEXT: req_text = resp_text = 1; break; case OPT_REQ_TEXT: req_text = 1; break; case OPT_RESP_TEXT: resp_text = 1; break; case OPT_REQIN: reqin = opt_arg(); break; case OPT_RESPIN: respin = opt_arg(); break; case OPT_SIGNER: signfile = opt_arg(); break; case OPT_VAFILE: verify_certfile = opt_arg(); verify_flags |= OCSP_TRUSTOTHER; break; case OPT_SIGN_OTHER: sign_certfile = opt_arg(); break; case OPT_VERIFY_OTHER: verify_certfile = opt_arg(); break; case OPT_CAFILE: CAfile = opt_arg(); break; case OPT_CAPATH: CApath = opt_arg(); break; case OPT_CASTORE: CAstore = opt_arg(); break; case OPT_NOCAFILE: noCAfile = 1; break; case OPT_NOCAPATH: noCApath = 1; break; case OPT_NOCASTORE: noCAstore = 1; break; case OPT_V_CASES: if (!opt_verify(o, vpm)) goto end; vpmtouched++; break; case OPT_VALIDITY_PERIOD: opt_long(opt_arg(), &nsec); break; case OPT_STATUS_AGE: opt_long(opt_arg(), &maxage); break; case OPT_SIGNKEY: keyfile = opt_arg(); break; case OPT_REQOUT: reqout = opt_arg(); break; case OPT_RESPOUT: respout = opt_arg(); break; case OPT_ISSUER: issuer = load_cert(opt_arg(), FORMAT_UNDEF, "issuer certificate"); if (issuer == NULL) goto end; if (issuers == NULL) { if ((issuers = sk_X509_new_null()) == NULL) goto end; } if (!sk_X509_push(issuers, issuer)) goto end; break; case OPT_CERT: reset_unknown(); X509_free(cert); cert = load_cert(opt_arg(), FORMAT_UNDEF, "certificate"); if (cert == NULL) goto end; if (cert_id_md == NULL) cert_id_md = (EVP_MD *)EVP_sha1(); if (!add_ocsp_cert(&req, cert, cert_id_md, issuer, ids)) goto end; if (!sk_OPENSSL_STRING_push(reqnames, opt_arg())) goto end; trailing_md = 0; break; case OPT_SERIAL: reset_unknown(); if (cert_id_md == NULL) cert_id_md = (EVP_MD *)EVP_sha1(); if (!add_ocsp_serial(&req, opt_arg(), cert_id_md, issuer, ids)) goto end; if (!sk_OPENSSL_STRING_push(reqnames, opt_arg())) goto end; trailing_md = 0; break; case OPT_INDEX: ridx_filename = opt_arg(); break; case OPT_CA: rca_filename = opt_arg(); break; case OPT_NMIN: nmin = opt_int_arg(); if (ndays == -1) ndays = 0; break; case OPT_REQUEST: accept_count = opt_int_arg(); break; case OPT_NDAYS: ndays = atoi(opt_arg()); break; case OPT_RSIGNER: rsignfile = opt_arg(); break; case OPT_RKEY: rkeyfile = opt_arg(); break; case OPT_PASSIN: passinarg = opt_arg(); break; case OPT_ROTHER: rcertfile = opt_arg(); break; case OPT_RMD: /* Response MessageDigest */ respdigname = opt_arg(); break; case OPT_RSIGOPT: if (rsign_sigopts == NULL) rsign_sigopts = sk_OPENSSL_STRING_new_null(); if (rsign_sigopts == NULL || !sk_OPENSSL_STRING_push(rsign_sigopts, opt_arg())) goto end; break; case OPT_HEADER: header = opt_arg(); value = strchr(header, '='); if (value == NULL) { BIO_printf(bio_err, "Missing = in header key=value\n"); goto opthelp; } *value++ = '\0'; if (!X509V3_add_value(header, value, &headers)) goto end; break; case OPT_RCID: if (!opt_md(opt_arg(), &resp_certid_md)) goto opthelp; break; case OPT_MD: if (trailing_md) { BIO_printf(bio_err, "%s: Digest must be before -cert or -serial\n", prog); goto opthelp; } if (!opt_md(opt_unknown(), &cert_id_md)) goto opthelp; trailing_md = 1; break; case OPT_MULTI: #ifdef HTTP_DAEMON n_responders = atoi(opt_arg()); #endif break; case OPT_PROV_CASES: if (!opt_provider(o)) goto end; break; } } /* No extra arguments. */ if (!opt_check_rest_arg(NULL)) goto opthelp; if (trailing_md) { BIO_printf(bio_err, "%s: Digest must be before -cert or -serial\n", prog); goto opthelp; } if (respdigname != NULL) { if (!opt_md(respdigname, &rsign_md)) goto end; } /* Have we anything to do? */ if (req == NULL && reqin == NULL && respin == NULL && !(port != NULL && ridx_filename != NULL)) goto opthelp; out = bio_open_default(outfile, 'w', FORMAT_TEXT); if (out == NULL) goto end; if (req == NULL && (add_nonce != 2)) add_nonce = 0; if (req == NULL && reqin != NULL) { derbio = bio_open_default(reqin, 'r', FORMAT_ASN1); if (derbio == NULL) goto end; req = d2i_OCSP_REQUEST_bio(derbio, NULL); BIO_free(derbio); if (req == NULL) { BIO_printf(bio_err, "Error reading OCSP request\n"); goto end; } } if (req == NULL && port != NULL) { #ifndef OPENSSL_NO_SOCK acbio = http_server_init(prog, port, -1); if (acbio == NULL) goto end; #else BIO_printf(bio_err, "Cannot act as server - sockets not supported\n"); goto end; #endif } if (rsignfile != NULL) { if (rkeyfile == NULL) rkeyfile = rsignfile; rsigner = load_cert(rsignfile, FORMAT_UNDEF, "responder certificate"); if (rsigner == NULL) { BIO_printf(bio_err, "Error loading responder certificate\n"); goto end; } if (!load_certs(rca_filename, 0, &rca_certs, NULL, "CA certificates")) goto end; if (rcertfile != NULL) { if (!load_certs(rcertfile, 0, &rother, NULL, "responder other certificates")) goto end; } if (!app_passwd(passinarg, NULL, &passin, NULL)) { BIO_printf(bio_err, "Error getting password\n"); goto end; } rkey = load_key(rkeyfile, FORMAT_UNDEF, 0, passin, NULL, "responder private key"); if (rkey == NULL) goto end; } if (ridx_filename != NULL && (rkey == NULL || rsigner == NULL || rca_certs == NULL)) { BIO_printf(bio_err, "Responder mode requires certificate, key, and CA.\n"); goto end; } if (ridx_filename != NULL) { rdb = load_index(ridx_filename, NULL); if (rdb == NULL || index_index(rdb) <= 0) { BIO_printf(bio_err, "Problem with index file: %s (could not load/parse file)\n", ridx_filename); ret = 1; goto end; } } #ifdef HTTP_DAEMON if (n_responders != 0 && acbio != NULL) spawn_loop(prog); if (acbio != NULL && req_timeout > 0) signal(SIGALRM, socket_timeout); #endif if (acbio != NULL) trace_log_message(-1, prog, LOG_INFO, "waiting for OCSP client connections..."); redo_accept: if (acbio != NULL) { #ifdef HTTP_DAEMON if (index_changed(rdb)) { CA_DB *newrdb = load_index(ridx_filename, NULL); if (newrdb != NULL && index_index(newrdb) > 0) { free_index(rdb); rdb = newrdb; } else { free_index(newrdb); trace_log_message(-1, prog, LOG_ERR, "error reloading updated index: %s", ridx_filename); } } #endif req = NULL; res = do_responder(&req, &cbio, acbio, req_timeout); if (res == 0) goto redo_accept; if (req == NULL) { if (res == 1) { resp = OCSP_response_create(OCSP_RESPONSE_STATUS_MALFORMEDREQUEST, NULL); send_ocsp_response(cbio, resp); } goto done_resp; } } if (req == NULL && (signfile != NULL || reqout != NULL || host != NULL || add_nonce || ridx_filename != NULL)) { BIO_printf(bio_err, "Need an OCSP request for this operation!\n"); goto end; } if (req != NULL && add_nonce) { if (!OCSP_request_add1_nonce(req, NULL, -1)) goto end; } if (signfile != NULL) { if (keyfile == NULL) keyfile = signfile; signer = load_cert(signfile, FORMAT_UNDEF, "signer certificate"); if (signer == NULL) { BIO_printf(bio_err, "Error loading signer certificate\n"); goto end; } if (sign_certfile != NULL) { if (!load_certs(sign_certfile, 0, &sign_other, NULL, "signer certificates")) goto end; } key = load_key(keyfile, FORMAT_UNDEF, 0, NULL, NULL, "signer private key"); if (key == NULL) goto end; if (!OCSP_request_sign(req, signer, key, NULL, sign_other, sign_flags)) { BIO_printf(bio_err, "Error signing OCSP request\n"); goto end; } } if (req_text && req != NULL) OCSP_REQUEST_print(out, req, 0); if (reqout != NULL) { derbio = bio_open_default(reqout, 'w', FORMAT_ASN1); if (derbio == NULL) goto end; i2d_OCSP_REQUEST_bio(derbio, req); BIO_free(derbio); } if (rdb != NULL) { make_ocsp_response(bio_err, &resp, req, rdb, rca_certs, rsigner, rkey, rsign_md, rsign_sigopts, rother, rflags, nmin, ndays, badsig, resp_certid_md); if (resp == NULL) goto end; if (cbio != NULL) send_ocsp_response(cbio, resp); } else if (host != NULL) { #ifndef OPENSSL_NO_SOCK resp = process_responder(req, host, port, path, opt_proxy, opt_no_proxy, use_ssl, headers, req_timeout); if (resp == NULL) goto end; #else BIO_printf(bio_err, "Error creating connect BIO - sockets not supported\n"); goto end; #endif } else if (respin != NULL) { derbio = bio_open_default(respin, 'r', FORMAT_ASN1); if (derbio == NULL) goto end; resp = d2i_OCSP_RESPONSE_bio(derbio, NULL); BIO_free(derbio); if (resp == NULL) { BIO_printf(bio_err, "Error reading OCSP response\n"); goto end; } } else { ret = 0; goto end; } done_resp: if (respout != NULL) { derbio = bio_open_default(respout, 'w', FORMAT_ASN1); if (derbio == NULL) goto end; i2d_OCSP_RESPONSE_bio(derbio, resp); BIO_free(derbio); } i = OCSP_response_status(resp); if (i != OCSP_RESPONSE_STATUS_SUCCESSFUL) { BIO_printf(out, "Responder Error: %s (%d)\n", OCSP_response_status_str(i), i); if (!ignore_err) goto end; } if (resp_text) OCSP_RESPONSE_print(out, resp, 0); /* If running as responder don't verify our own response */ if (cbio != NULL) { /* If not unlimited, see if we took all we should. */ if (accept_count != -1 && --accept_count <= 0) { ret = 0; goto end; } BIO_free_all(cbio); cbio = NULL; OCSP_REQUEST_free(req); req = NULL; OCSP_RESPONSE_free(resp); resp = NULL; goto redo_accept; } if (ridx_filename != NULL) { ret = 0; goto end; } if (store == NULL) { store = setup_verify(CAfile, noCAfile, CApath, noCApath, CAstore, noCAstore); if (!store) goto end; } if (vpmtouched) X509_STORE_set1_param(store, vpm); if (verify_certfile != NULL) { if (!load_certs(verify_certfile, 0, &verify_other, NULL, "validator certificates")) goto end; } bs = OCSP_response_get1_basic(resp); if (bs == NULL) { BIO_printf(bio_err, "Error parsing response\n"); goto end; } ret = 0; if (!noverify) { if (req != NULL && ((i = OCSP_check_nonce(req, bs)) <= 0)) { if (i == -1) BIO_printf(bio_err, "WARNING: no nonce in response\n"); else { BIO_printf(bio_err, "Nonce Verify error\n"); ret = 1; goto end; } } i = OCSP_basic_verify(bs, verify_other, store, verify_flags); if (i <= 0 && issuers) { i = OCSP_basic_verify(bs, issuers, store, OCSP_TRUSTOTHER); if (i > 0) ERR_clear_error(); } if (i <= 0) { BIO_printf(bio_err, "Response Verify Failure\n"); ERR_print_errors(bio_err); ret = 1; } else { BIO_printf(bio_err, "Response verify OK\n"); } } if (!print_ocsp_summary(out, bs, req, reqnames, ids, nsec, maxage)) ret = 1; end: ERR_print_errors(bio_err); X509_free(signer); X509_STORE_free(store); X509_VERIFY_PARAM_free(vpm); sk_OPENSSL_STRING_free(rsign_sigopts); EVP_PKEY_free(key); EVP_PKEY_free(rkey); EVP_MD_free(cert_id_md); EVP_MD_free(rsign_md); EVP_MD_free(resp_certid_md); X509_free(cert); OSSL_STACK_OF_X509_free(issuers); X509_free(rsigner); OSSL_STACK_OF_X509_free(rca_certs); free_index(rdb); BIO_free_all(cbio); BIO_free_all(acbio); BIO_free_all(out); OCSP_REQUEST_free(req); OCSP_RESPONSE_free(resp); OCSP_BASICRESP_free(bs); sk_OPENSSL_STRING_free(reqnames); sk_OCSP_CERTID_free(ids); OSSL_STACK_OF_X509_free(sign_other); OSSL_STACK_OF_X509_free(verify_other); sk_CONF_VALUE_pop_free(headers, X509V3_conf_free); OPENSSL_free(thost); OPENSSL_free(tport); OPENSSL_free(tpath); return ret; } #ifdef HTTP_DAEMON static int index_changed(CA_DB *rdb) { struct stat sb; if (rdb != NULL && stat(rdb->dbfname, &sb) != -1) { if (rdb->dbst.st_mtime != sb.st_mtime || rdb->dbst.st_ctime != sb.st_ctime || rdb->dbst.st_ino != sb.st_ino || rdb->dbst.st_dev != sb.st_dev) { syslog(LOG_INFO, "index file changed, reloading"); return 1; } } return 0; } #endif static int add_ocsp_cert(OCSP_REQUEST **req, X509 *cert, const EVP_MD *cert_id_md, X509 *issuer, STACK_OF(OCSP_CERTID) *ids) { OCSP_CERTID *id; if (issuer == NULL) { BIO_printf(bio_err, "No issuer certificate specified\n"); return 0; } if (*req == NULL) *req = OCSP_REQUEST_new(); if (*req == NULL) goto err; id = OCSP_cert_to_id(cert_id_md, cert, issuer); if (id == NULL || !sk_OCSP_CERTID_push(ids, id)) goto err; if (!OCSP_request_add0_id(*req, id)) goto err; return 1; err: BIO_printf(bio_err, "Error Creating OCSP request\n"); return 0; } static int add_ocsp_serial(OCSP_REQUEST **req, char *serial, const EVP_MD *cert_id_md, X509 *issuer, STACK_OF(OCSP_CERTID) *ids) { OCSP_CERTID *id; const X509_NAME *iname; ASN1_BIT_STRING *ikey; ASN1_INTEGER *sno; if (issuer == NULL) { BIO_printf(bio_err, "No issuer certificate specified\n"); return 0; } if (*req == NULL) *req = OCSP_REQUEST_new(); if (*req == NULL) goto err; iname = X509_get_subject_name(issuer); ikey = X509_get0_pubkey_bitstr(issuer); sno = s2i_ASN1_INTEGER(NULL, serial); if (sno == NULL) { BIO_printf(bio_err, "Error converting serial number %s\n", serial); return 0; } id = OCSP_cert_id_new(cert_id_md, iname, ikey, sno); ASN1_INTEGER_free(sno); if (id == NULL || !sk_OCSP_CERTID_push(ids, id)) goto err; if (!OCSP_request_add0_id(*req, id)) goto err; return 1; err: BIO_printf(bio_err, "Error Creating OCSP request\n"); return 0; } static int print_ocsp_summary(BIO *out, OCSP_BASICRESP *bs, OCSP_REQUEST *req, STACK_OF(OPENSSL_STRING) *names, STACK_OF(OCSP_CERTID) *ids, long nsec, long maxage) { OCSP_CERTID *id; const char *name; int i, status, reason; ASN1_GENERALIZEDTIME *rev, *thisupd, *nextupd; int ret = 1; if (req == NULL || !sk_OPENSSL_STRING_num(names)) return 1; if (bs == NULL || !sk_OCSP_CERTID_num(ids)) return 0; for (i = 0; i < sk_OCSP_CERTID_num(ids); i++) { id = sk_OCSP_CERTID_value(ids, i); name = sk_OPENSSL_STRING_value(names, i); BIO_printf(out, "%s: ", name); if (!OCSP_resp_find_status(bs, id, &status, &reason, &rev, &thisupd, &nextupd)) { BIO_puts(out, "ERROR: No Status found.\n"); ret = 0; continue; } /* * Check validity: if invalid write to output BIO so we know which * response this refers to. */ if (!OCSP_check_validity(thisupd, nextupd, nsec, maxage)) { BIO_puts(out, "WARNING: Status times invalid.\n"); ERR_print_errors(out); } BIO_printf(out, "%s\n", OCSP_cert_status_str(status)); BIO_puts(out, "\tThis Update: "); ASN1_GENERALIZEDTIME_print(out, thisupd); BIO_puts(out, "\n"); if (nextupd) { BIO_puts(out, "\tNext Update: "); ASN1_GENERALIZEDTIME_print(out, nextupd); BIO_puts(out, "\n"); } if (status != V_OCSP_CERTSTATUS_REVOKED) continue; if (reason != -1) BIO_printf(out, "\tReason: %s\n", OCSP_crl_reason_str(reason)); BIO_puts(out, "\tRevocation Time: "); ASN1_GENERALIZEDTIME_print(out, rev); BIO_puts(out, "\n"); } return ret; } static void make_ocsp_response(BIO *err, OCSP_RESPONSE **resp, OCSP_REQUEST *req, CA_DB *db, STACK_OF(X509) *ca, X509 *rcert, EVP_PKEY *rkey, const EVP_MD *rmd, STACK_OF(OPENSSL_STRING) *sigopts, STACK_OF(X509) *rother, unsigned long flags, int nmin, int ndays, int badsig, const EVP_MD *resp_md) { ASN1_TIME *thisupd = NULL, *nextupd = NULL; OCSP_CERTID *cid; OCSP_BASICRESP *bs = NULL; int i, id_count; EVP_MD_CTX *mctx = NULL; EVP_PKEY_CTX *pkctx = NULL; id_count = OCSP_request_onereq_count(req); if (id_count <= 0) { *resp = OCSP_response_create(OCSP_RESPONSE_STATUS_MALFORMEDREQUEST, NULL); goto end; } bs = OCSP_BASICRESP_new(); thisupd = X509_gmtime_adj(NULL, 0); if (ndays != -1) nextupd = X509_time_adj_ex(NULL, ndays, nmin * 60, NULL); /* Examine each certificate id in the request */ for (i = 0; i < id_count; i++) { OCSP_ONEREQ *one; ASN1_INTEGER *serial; char **inf; int jj; int found = 0; ASN1_OBJECT *cert_id_md_oid; const EVP_MD *cert_id_md; OCSP_CERTID *cid_resp_md = NULL; one = OCSP_request_onereq_get0(req, i); cid = OCSP_onereq_get0_id(one); OCSP_id_get0_info(NULL, &cert_id_md_oid, NULL, NULL, cid); cert_id_md = EVP_get_digestbyobj(cert_id_md_oid); if (cert_id_md == NULL) { *resp = OCSP_response_create(OCSP_RESPONSE_STATUS_INTERNALERROR, NULL); goto end; } for (jj = 0; jj < sk_X509_num(ca) && !found; jj++) { X509 *ca_cert = sk_X509_value(ca, jj); OCSP_CERTID *ca_id = OCSP_cert_to_id(cert_id_md, NULL, ca_cert); if (OCSP_id_issuer_cmp(ca_id, cid) == 0) { found = 1; if (resp_md != NULL) cid_resp_md = OCSP_cert_to_id(resp_md, NULL, ca_cert); } OCSP_CERTID_free(ca_id); } OCSP_id_get0_info(NULL, NULL, NULL, &serial, cid); inf = lookup_serial(db, serial); /* at this point, we can have cid be an alias of cid_resp_md */ cid = (cid_resp_md != NULL) ? cid_resp_md : cid; if (!found) { OCSP_basic_add1_status(bs, cid, V_OCSP_CERTSTATUS_UNKNOWN, 0, NULL, thisupd, nextupd); continue; } if (inf == NULL) { OCSP_basic_add1_status(bs, cid, V_OCSP_CERTSTATUS_UNKNOWN, 0, NULL, thisupd, nextupd); } else if (inf[DB_type][0] == DB_TYPE_VAL) { OCSP_basic_add1_status(bs, cid, V_OCSP_CERTSTATUS_GOOD, 0, NULL, thisupd, nextupd); } else if (inf[DB_type][0] == DB_TYPE_REV) { ASN1_OBJECT *inst = NULL; ASN1_TIME *revtm = NULL; ASN1_GENERALIZEDTIME *invtm = NULL; OCSP_SINGLERESP *single; int reason = -1; unpack_revinfo(&revtm, &reason, &inst, &invtm, inf[DB_rev_date]); single = OCSP_basic_add1_status(bs, cid, V_OCSP_CERTSTATUS_REVOKED, reason, revtm, thisupd, nextupd); if (single == NULL) { *resp = OCSP_response_create(OCSP_RESPONSE_STATUS_INTERNALERROR, NULL); goto end; } if (invtm != NULL) OCSP_SINGLERESP_add1_ext_i2d(single, NID_invalidity_date, invtm, 0, 0); else if (inst != NULL) OCSP_SINGLERESP_add1_ext_i2d(single, NID_hold_instruction_code, inst, 0, 0); ASN1_OBJECT_free(inst); ASN1_TIME_free(revtm); ASN1_GENERALIZEDTIME_free(invtm); } OCSP_CERTID_free(cid_resp_md); } OCSP_copy_nonce(bs, req); mctx = EVP_MD_CTX_new(); if (mctx == NULL || !EVP_DigestSignInit(mctx, &pkctx, rmd, NULL, rkey)) { *resp = OCSP_response_create(OCSP_RESPONSE_STATUS_INTERNALERROR, NULL); goto end; } for (i = 0; i < sk_OPENSSL_STRING_num(sigopts); i++) { char *sigopt = sk_OPENSSL_STRING_value(sigopts, i); if (pkey_ctrl_string(pkctx, sigopt) <= 0) { BIO_printf(err, "parameter error \"%s\"\n", sigopt); ERR_print_errors(bio_err); *resp = OCSP_response_create(OCSP_RESPONSE_STATUS_INTERNALERROR, NULL); goto end; } } if (!OCSP_basic_sign_ctx(bs, rcert, mctx, rother, flags)) { *resp = OCSP_response_create(OCSP_RESPONSE_STATUS_INTERNALERROR, bs); goto end; } if (badsig) { const ASN1_OCTET_STRING *sig = OCSP_resp_get0_signature(bs); corrupt_signature(sig); } *resp = OCSP_response_create(OCSP_RESPONSE_STATUS_SUCCESSFUL, bs); end: EVP_MD_CTX_free(mctx); ASN1_TIME_free(thisupd); ASN1_TIME_free(nextupd); OCSP_BASICRESP_free(bs); } static char **lookup_serial(CA_DB *db, ASN1_INTEGER *ser) { int i; BIGNUM *bn = NULL; char *itmp, *row[DB_NUMBER], **rrow; for (i = 0; i < DB_NUMBER; i++) row[i] = NULL; bn = ASN1_INTEGER_to_BN(ser, NULL); OPENSSL_assert(bn); /* FIXME: should report an error at this * point and abort */ if (BN_is_zero(bn)) { itmp = OPENSSL_strdup("00"); OPENSSL_assert(itmp); } else { itmp = BN_bn2hex(bn); } row[DB_serial] = itmp; BN_free(bn); rrow = TXT_DB_get_by_index(db->db, DB_serial, row); OPENSSL_free(itmp); return rrow; } static int do_responder(OCSP_REQUEST **preq, BIO **pcbio, BIO *acbio, int timeout) { #ifndef OPENSSL_NO_SOCK return http_server_get_asn1_req(ASN1_ITEM_rptr(OCSP_REQUEST), (ASN1_VALUE **)preq, NULL, pcbio, acbio, NULL /* found_keep_alive */, prog, 1 /* accept_get */, timeout); #else BIO_printf(bio_err, "Error getting OCSP request - sockets not supported\n"); *preq = NULL; return 0; #endif } static int send_ocsp_response(BIO *cbio, const OCSP_RESPONSE *resp) { #ifndef OPENSSL_NO_SOCK return http_server_send_asn1_resp(prog, cbio, 0 /* no keep-alive */, "application/ocsp-response", ASN1_ITEM_rptr(OCSP_RESPONSE), (const ASN1_VALUE *)resp); #else BIO_printf(bio_err, "Error sending OCSP response - sockets not supported\n"); return 0; #endif } #ifndef OPENSSL_NO_SOCK OCSP_RESPONSE *process_responder(OCSP_REQUEST *req, const char *host, const char *port, const char *path, const char *proxy, const char *no_proxy, int use_ssl, STACK_OF(CONF_VALUE) *headers, int req_timeout) { SSL_CTX *ctx = NULL; OCSP_RESPONSE *resp = NULL; if (use_ssl == 1) { ctx = SSL_CTX_new(TLS_client_method()); if (ctx == NULL) { BIO_printf(bio_err, "Error creating SSL context.\n"); goto end; } } resp = (OCSP_RESPONSE *) app_http_post_asn1(host, port, path, proxy, no_proxy, ctx, headers, "application/ocsp-request", (ASN1_VALUE *)req, ASN1_ITEM_rptr(OCSP_REQUEST), "application/ocsp-response", req_timeout, ASN1_ITEM_rptr(OCSP_RESPONSE)); if (resp == NULL) BIO_printf(bio_err, "Error querying OCSP responder\n"); end: SSL_CTX_free(ctx); return resp; } #endif
./openssl/apps/genrsa.c
/* * Copyright 1995-2023 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <openssl/opensslconf.h> #include <stdio.h> #include <string.h> #include <sys/types.h> #include <sys/stat.h> #include "apps.h" #include "progs.h" #include <openssl/bio.h> #include <openssl/err.h> #include <openssl/bn.h> #include <openssl/rsa.h> #include <openssl/evp.h> #include <openssl/x509.h> #include <openssl/pem.h> #include <openssl/rand.h> #define DEFBITS 2048 #define DEFPRIMES 2 static int verbose = 0; typedef enum OPTION_choice { OPT_COMMON, #ifndef OPENSSL_NO_DEPRECATED_3_0 OPT_3, #endif OPT_F4, OPT_ENGINE, OPT_OUT, OPT_PASSOUT, OPT_CIPHER, OPT_PRIMES, OPT_VERBOSE, OPT_QUIET, OPT_R_ENUM, OPT_PROV_ENUM, OPT_TRADITIONAL } OPTION_CHOICE; const OPTIONS genrsa_options[] = { {OPT_HELP_STR, 1, '-', "Usage: %s [options] numbits\n"}, OPT_SECTION("General"), {"help", OPT_HELP, '-', "Display this summary"}, #ifndef OPENSSL_NO_ENGINE {"engine", OPT_ENGINE, 's', "Use engine, possibly a hardware device"}, #endif OPT_SECTION("Input"), #ifndef OPENSSL_NO_DEPRECATED_3_0 {"3", OPT_3, '-', "(deprecated) Use 3 for the E value"}, #endif {"F4", OPT_F4, '-', "Use the Fermat number F4 (0x10001) for the E value"}, {"f4", OPT_F4, '-', "Use the Fermat number F4 (0x10001) for the E value"}, OPT_SECTION("Output"), {"out", OPT_OUT, '>', "Output the key to specified file"}, {"passout", OPT_PASSOUT, 's', "Output file pass phrase source"}, {"primes", OPT_PRIMES, 'p', "Specify number of primes"}, {"verbose", OPT_VERBOSE, '-', "Verbose output"}, {"quiet", OPT_QUIET, '-', "Terse output"}, {"traditional", OPT_TRADITIONAL, '-', "Use traditional format for private keys"}, {"", OPT_CIPHER, '-', "Encrypt the output with any supported cipher"}, OPT_R_OPTIONS, OPT_PROV_OPTIONS, OPT_PARAMETERS(), {"numbits", 0, 0, "Size of key in bits"}, {NULL} }; int genrsa_main(int argc, char **argv) { BN_GENCB *cb = BN_GENCB_new(); ENGINE *eng = NULL; BIGNUM *bn = BN_new(); BIO *out = NULL; EVP_PKEY *pkey = NULL; EVP_PKEY_CTX *ctx = NULL; EVP_CIPHER *enc = NULL; int ret = 1, num = DEFBITS, private = 0, primes = DEFPRIMES; unsigned long f4 = RSA_F4; char *outfile = NULL, *passoutarg = NULL, *passout = NULL; char *prog, *hexe, *dece, *ciphername = NULL; OPTION_CHOICE o; int traditional = 0; if (bn == NULL || cb == NULL) goto end; opt_set_unknown_name("cipher"); prog = opt_init(argc, argv, genrsa_options); while ((o = opt_next()) != OPT_EOF) { switch (o) { case OPT_EOF: case OPT_ERR: opthelp: BIO_printf(bio_err, "%s: Use -help for summary.\n", prog); goto end; case OPT_HELP: ret = 0; opt_help(genrsa_options); goto end; #ifndef OPENSSL_NO_DEPRECATED_3_0 case OPT_3: f4 = RSA_3; break; #endif case OPT_F4: f4 = RSA_F4; break; case OPT_OUT: outfile = opt_arg(); break; case OPT_ENGINE: eng = setup_engine(opt_arg(), 0); break; case OPT_R_CASES: if (!opt_rand(o)) goto end; break; case OPT_PROV_CASES: if (!opt_provider(o)) goto end; break; case OPT_PASSOUT: passoutarg = opt_arg(); break; case OPT_CIPHER: ciphername = opt_unknown(); break; case OPT_PRIMES: primes = opt_int_arg(); break; case OPT_VERBOSE: verbose = 1; break; case OPT_QUIET: verbose = 0; break; case OPT_TRADITIONAL: traditional = 1; break; } } /* One optional argument, the bitsize. */ argc = opt_num_rest(); argv = opt_rest(); if (argc == 1) { if (!opt_int(argv[0], &num) || num <= 0) goto end; if (num > OPENSSL_RSA_MAX_MODULUS_BITS) BIO_printf(bio_err, "Warning: It is not recommended to use more than %d bit for RSA keys.\n" " Your key size is %d! Larger key size may behave not as expected.\n", OPENSSL_RSA_MAX_MODULUS_BITS, num); } else if (!opt_check_rest_arg(NULL)) { goto opthelp; } if (!app_RAND_load()) goto end; private = 1; if (!opt_cipher(ciphername, &enc)) goto end; if (!app_passwd(NULL, passoutarg, NULL, &passout)) { BIO_printf(bio_err, "Error getting password\n"); goto end; } out = bio_open_owner(outfile, FORMAT_PEM, private); if (out == NULL) goto end; if (!init_gen_str(&ctx, "RSA", eng, 0, app_get0_libctx(), app_get0_propq())) goto end; if (verbose) EVP_PKEY_CTX_set_cb(ctx, progress_cb); EVP_PKEY_CTX_set_app_data(ctx, bio_err); if (EVP_PKEY_CTX_set_rsa_keygen_bits(ctx, num) <= 0) { BIO_printf(bio_err, "Error setting RSA length\n"); goto end; } if (!BN_set_word(bn, f4)) { BIO_printf(bio_err, "Error allocating RSA public exponent\n"); goto end; } if (EVP_PKEY_CTX_set1_rsa_keygen_pubexp(ctx, bn) <= 0) { BIO_printf(bio_err, "Error setting RSA public exponent\n"); goto end; } if (EVP_PKEY_CTX_set_rsa_keygen_primes(ctx, primes) <= 0) { BIO_printf(bio_err, "Error setting number of primes\n"); goto end; } pkey = app_keygen(ctx, "RSA", num, verbose); if (pkey == NULL) goto end; if (verbose) { BIGNUM *e = NULL; /* Every RSA key has an 'e' */ EVP_PKEY_get_bn_param(pkey, "e", &e); if (e == NULL) { BIO_printf(bio_err, "Error cannot access RSA e\n"); goto end; } hexe = BN_bn2hex(e); dece = BN_bn2dec(e); if (hexe && dece) { BIO_printf(bio_err, "e is %s (0x%s)\n", dece, hexe); } OPENSSL_free(hexe); OPENSSL_free(dece); BN_free(e); } if (traditional) { if (!PEM_write_bio_PrivateKey_traditional(out, pkey, enc, NULL, 0, NULL, passout)) goto end; } else { if (!PEM_write_bio_PrivateKey(out, pkey, enc, NULL, 0, NULL, passout)) goto end; } ret = 0; end: BN_free(bn); BN_GENCB_free(cb); EVP_PKEY_CTX_free(ctx); EVP_PKEY_free(pkey); EVP_CIPHER_free(enc); BIO_free_all(out); release_engine(eng); OPENSSL_free(passout); if (ret != 0) ERR_print_errors(bio_err); return ret; }
./openssl/apps/pkeyutl.c
/* * Copyright 2006-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 "apps.h" #include "progs.h" #include <string.h> #include <openssl/err.h> #include <openssl/pem.h> #include <openssl/evp.h> #include <sys/stat.h> #define KEY_NONE 0 #define KEY_PRIVKEY 1 #define KEY_PUBKEY 2 #define KEY_CERT 3 static EVP_PKEY_CTX *init_ctx(const char *kdfalg, int *pkeysize, const char *keyfile, int keyform, int key_type, char *passinarg, int pkey_op, ENGINE *e, const int impl, int rawin, EVP_PKEY **ppkey, EVP_MD_CTX *mctx, const char *digestname, OSSL_LIB_CTX *libctx, const char *propq); static int setup_peer(EVP_PKEY_CTX *ctx, int peerform, const char *file, ENGINE *e); static int do_keyop(EVP_PKEY_CTX *ctx, int pkey_op, unsigned char *out, size_t *poutlen, const unsigned char *in, size_t inlen); static int do_raw_keyop(int pkey_op, EVP_MD_CTX *mctx, EVP_PKEY *pkey, BIO *in, int filesize, unsigned char *sig, int siglen, unsigned char **out, size_t *poutlen); typedef enum OPTION_choice { OPT_COMMON, OPT_ENGINE, OPT_ENGINE_IMPL, OPT_IN, OPT_OUT, OPT_PUBIN, OPT_CERTIN, OPT_ASN1PARSE, OPT_HEXDUMP, OPT_SIGN, OPT_VERIFY, OPT_VERIFYRECOVER, OPT_REV, OPT_ENCRYPT, OPT_DECRYPT, OPT_DERIVE, OPT_SIGFILE, OPT_INKEY, OPT_PEERKEY, OPT_PASSIN, OPT_PEERFORM, OPT_KEYFORM, OPT_PKEYOPT, OPT_PKEYOPT_PASSIN, OPT_KDF, OPT_KDFLEN, OPT_R_ENUM, OPT_PROV_ENUM, OPT_CONFIG, OPT_RAWIN, OPT_DIGEST } OPTION_CHOICE; const OPTIONS pkeyutl_options[] = { OPT_SECTION("General"), {"help", OPT_HELP, '-', "Display this summary"}, #ifndef OPENSSL_NO_ENGINE {"engine", OPT_ENGINE, 's', "Use engine, possibly a hardware device"}, {"engine_impl", OPT_ENGINE_IMPL, '-', "Also use engine given by -engine for crypto operations"}, #endif {"sign", OPT_SIGN, '-', "Sign input data with private key"}, {"verify", OPT_VERIFY, '-', "Verify with public key"}, {"encrypt", OPT_ENCRYPT, '-', "Encrypt input data with public key"}, {"decrypt", OPT_DECRYPT, '-', "Decrypt input data with private key"}, {"derive", OPT_DERIVE, '-', "Derive shared secret"}, OPT_CONFIG_OPTION, OPT_SECTION("Input"), {"in", OPT_IN, '<', "Input file - default stdin"}, {"rawin", OPT_RAWIN, '-', "Indicate the input data is in raw form"}, {"inkey", OPT_INKEY, 's', "Input key, by default private key"}, {"pubin", OPT_PUBIN, '-', "Input key is a public key"}, {"passin", OPT_PASSIN, 's', "Input file pass phrase source"}, {"peerkey", OPT_PEERKEY, 's', "Peer key file used in key derivation"}, {"peerform", OPT_PEERFORM, 'E', "Peer key format (DER/PEM/P12/ENGINE)"}, {"certin", OPT_CERTIN, '-', "Input is a cert with a public key"}, {"rev", OPT_REV, '-', "Reverse the order of the input buffer"}, {"sigfile", OPT_SIGFILE, '<', "Signature file (verify operation only)"}, {"keyform", OPT_KEYFORM, 'E', "Private key format (ENGINE, other values ignored)"}, OPT_SECTION("Output"), {"out", OPT_OUT, '>', "Output file - default stdout"}, {"asn1parse", OPT_ASN1PARSE, '-', "asn1parse the output data"}, {"hexdump", OPT_HEXDUMP, '-', "Hex dump output"}, {"verifyrecover", OPT_VERIFYRECOVER, '-', "Verify with public key, recover original data"}, OPT_SECTION("Signing/Derivation"), {"digest", OPT_DIGEST, 's', "Specify the digest algorithm when signing the raw input data"}, {"pkeyopt", OPT_PKEYOPT, 's', "Public key options as opt:value"}, {"pkeyopt_passin", OPT_PKEYOPT_PASSIN, 's', "Public key option that is read as a passphrase argument opt:passphrase"}, {"kdf", OPT_KDF, 's', "Use KDF algorithm"}, {"kdflen", OPT_KDFLEN, 'p', "KDF algorithm output length"}, OPT_R_OPTIONS, OPT_PROV_OPTIONS, {NULL} }; int pkeyutl_main(int argc, char **argv) { CONF *conf = NULL; BIO *in = NULL, *out = NULL; ENGINE *e = NULL; EVP_PKEY_CTX *ctx = NULL; EVP_PKEY *pkey = NULL; char *infile = NULL, *outfile = NULL, *sigfile = NULL, *passinarg = NULL; char hexdump = 0, asn1parse = 0, rev = 0, *prog; unsigned char *buf_in = NULL, *buf_out = NULL, *sig = NULL; OPTION_CHOICE o; int buf_inlen = 0, siglen = -1; int keyform = FORMAT_UNDEF, peerform = FORMAT_UNDEF; int keysize = -1, pkey_op = EVP_PKEY_OP_SIGN, key_type = KEY_PRIVKEY; int engine_impl = 0; int ret = 1, rv = -1; size_t buf_outlen; const char *inkey = NULL; const char *peerkey = NULL; const char *kdfalg = NULL, *digestname = NULL; int kdflen = 0; STACK_OF(OPENSSL_STRING) *pkeyopts = NULL; STACK_OF(OPENSSL_STRING) *pkeyopts_passin = NULL; int rawin = 0; EVP_MD_CTX *mctx = NULL; EVP_MD *md = NULL; int filesize = -1; OSSL_LIB_CTX *libctx = app_get0_libctx(); prog = opt_init(argc, argv, pkeyutl_options); while ((o = opt_next()) != OPT_EOF) { switch (o) { case OPT_EOF: case OPT_ERR: opthelp: BIO_printf(bio_err, "%s: Use -help for summary.\n", prog); goto end; case OPT_HELP: opt_help(pkeyutl_options); ret = 0; goto end; case OPT_IN: infile = opt_arg(); break; case OPT_OUT: outfile = opt_arg(); break; case OPT_SIGFILE: sigfile = opt_arg(); break; case OPT_ENGINE_IMPL: engine_impl = 1; break; case OPT_INKEY: inkey = opt_arg(); break; case OPT_PEERKEY: peerkey = opt_arg(); break; case OPT_PASSIN: passinarg = opt_arg(); break; case OPT_PEERFORM: if (!opt_format(opt_arg(), OPT_FMT_ANY, &peerform)) goto opthelp; break; case OPT_KEYFORM: if (!opt_format(opt_arg(), OPT_FMT_ANY, &keyform)) goto opthelp; break; case OPT_R_CASES: if (!opt_rand(o)) goto end; break; case OPT_CONFIG: conf = app_load_config_modules(opt_arg()); if (conf == NULL) goto end; break; case OPT_PROV_CASES: if (!opt_provider(o)) goto end; break; case OPT_ENGINE: e = setup_engine(opt_arg(), 0); break; case OPT_PUBIN: key_type = KEY_PUBKEY; break; case OPT_CERTIN: key_type = KEY_CERT; break; case OPT_ASN1PARSE: asn1parse = 1; break; case OPT_HEXDUMP: hexdump = 1; break; case OPT_SIGN: pkey_op = EVP_PKEY_OP_SIGN; break; case OPT_VERIFY: pkey_op = EVP_PKEY_OP_VERIFY; break; case OPT_VERIFYRECOVER: pkey_op = EVP_PKEY_OP_VERIFYRECOVER; break; case OPT_ENCRYPT: pkey_op = EVP_PKEY_OP_ENCRYPT; break; case OPT_DECRYPT: pkey_op = EVP_PKEY_OP_DECRYPT; break; case OPT_DERIVE: pkey_op = EVP_PKEY_OP_DERIVE; break; case OPT_KDF: pkey_op = EVP_PKEY_OP_DERIVE; key_type = KEY_NONE; kdfalg = opt_arg(); break; case OPT_KDFLEN: kdflen = atoi(opt_arg()); break; case OPT_REV: rev = 1; break; case OPT_PKEYOPT: if ((pkeyopts == NULL && (pkeyopts = sk_OPENSSL_STRING_new_null()) == NULL) || sk_OPENSSL_STRING_push(pkeyopts, opt_arg()) == 0) { BIO_puts(bio_err, "out of memory\n"); goto end; } break; case OPT_PKEYOPT_PASSIN: if ((pkeyopts_passin == NULL && (pkeyopts_passin = sk_OPENSSL_STRING_new_null()) == NULL) || sk_OPENSSL_STRING_push(pkeyopts_passin, opt_arg()) == 0) { BIO_puts(bio_err, "out of memory\n"); goto end; } break; case OPT_RAWIN: rawin = 1; break; case OPT_DIGEST: digestname = opt_arg(); break; } } /* No extra arguments. */ if (!opt_check_rest_arg(NULL)) goto opthelp; if (!app_RAND_load()) goto end; if (rawin && pkey_op != EVP_PKEY_OP_SIGN && pkey_op != EVP_PKEY_OP_VERIFY) { BIO_printf(bio_err, "%s: -rawin can only be used with -sign or -verify\n", prog); goto opthelp; } if (digestname != NULL && !rawin) { BIO_printf(bio_err, "%s: -digest can only be used with -rawin\n", prog); goto opthelp; } if (rawin && rev) { BIO_printf(bio_err, "%s: -rev cannot be used with raw input\n", prog); goto opthelp; } if (kdfalg != NULL) { if (kdflen == 0) { BIO_printf(bio_err, "%s: no KDF length given (-kdflen parameter).\n", prog); goto opthelp; } } else if (inkey == NULL) { BIO_printf(bio_err, "%s: no private key given (-inkey parameter).\n", prog); goto opthelp; } else if (peerkey != NULL && pkey_op != EVP_PKEY_OP_DERIVE) { BIO_printf(bio_err, "%s: no peer key given (-peerkey parameter).\n", prog); goto opthelp; } if (rawin) { if ((mctx = EVP_MD_CTX_new()) == NULL) { BIO_printf(bio_err, "Error: out of memory\n"); goto end; } } ctx = init_ctx(kdfalg, &keysize, inkey, keyform, key_type, passinarg, pkey_op, e, engine_impl, rawin, &pkey, mctx, digestname, libctx, app_get0_propq()); if (ctx == NULL) { BIO_printf(bio_err, "%s: Error initializing context\n", prog); goto end; } if (peerkey != NULL && !setup_peer(ctx, peerform, peerkey, e)) { BIO_printf(bio_err, "%s: Error setting up peer key\n", prog); goto end; } if (pkeyopts != NULL) { int num = sk_OPENSSL_STRING_num(pkeyopts); int i; for (i = 0; i < num; ++i) { const char *opt = sk_OPENSSL_STRING_value(pkeyopts, i); if (pkey_ctrl_string(ctx, opt) <= 0) { BIO_printf(bio_err, "%s: Can't set parameter \"%s\":\n", prog, opt); goto end; } } } if (pkeyopts_passin != NULL) { int num = sk_OPENSSL_STRING_num(pkeyopts_passin); int i; for (i = 0; i < num; i++) { char *opt = sk_OPENSSL_STRING_value(pkeyopts_passin, i); char *passin = strchr(opt, ':'); char *passwd; if (passin == NULL) { /* Get password interactively */ char passwd_buf[4096]; int r; BIO_snprintf(passwd_buf, sizeof(passwd_buf), "Enter %s: ", opt); r = EVP_read_pw_string(passwd_buf, sizeof(passwd_buf) - 1, passwd_buf, 0); if (r < 0) { if (r == -2) BIO_puts(bio_err, "user abort\n"); else BIO_puts(bio_err, "entry failed\n"); goto end; } passwd = OPENSSL_strdup(passwd_buf); if (passwd == NULL) { BIO_puts(bio_err, "out of memory\n"); goto end; } } else { /* Get password as a passin argument: First split option name * and passphrase argument into two strings */ *passin = 0; passin++; if (app_passwd(passin, NULL, &passwd, NULL) == 0) { BIO_printf(bio_err, "failed to get '%s'\n", opt); goto end; } } if (EVP_PKEY_CTX_ctrl_str(ctx, opt, passwd) <= 0) { BIO_printf(bio_err, "%s: Can't set parameter \"%s\":\n", prog, opt); goto end; } OPENSSL_free(passwd); } } if (sigfile != NULL && (pkey_op != EVP_PKEY_OP_VERIFY)) { BIO_printf(bio_err, "%s: Signature file specified for non verify\n", prog); goto end; } if (sigfile == NULL && (pkey_op == EVP_PKEY_OP_VERIFY)) { BIO_printf(bio_err, "%s: No signature file specified for verify\n", prog); goto end; } if (pkey_op != EVP_PKEY_OP_DERIVE) { in = bio_open_default(infile, 'r', FORMAT_BINARY); if (infile != NULL) { struct stat st; if (stat(infile, &st) == 0 && st.st_size <= INT_MAX) filesize = (int)st.st_size; } if (in == NULL) goto end; } out = bio_open_default(outfile, 'w', FORMAT_BINARY); if (out == NULL) goto end; if (sigfile != NULL) { BIO *sigbio = BIO_new_file(sigfile, "rb"); if (sigbio == NULL) { BIO_printf(bio_err, "Can't open signature file %s\n", sigfile); goto end; } siglen = bio_to_mem(&sig, keysize * 10, sigbio); BIO_free(sigbio); if (siglen < 0) { BIO_printf(bio_err, "Error reading signature data\n"); goto end; } } /* Raw input data is handled elsewhere */ if (in != NULL && !rawin) { /* Read the input data */ buf_inlen = bio_to_mem(&buf_in, -1, in); if (buf_inlen < 0) { BIO_printf(bio_err, "Error reading input Data\n"); goto end; } if (rev) { size_t i; unsigned char ctmp; size_t l = (size_t)buf_inlen; for (i = 0; i < l / 2; i++) { ctmp = buf_in[i]; buf_in[i] = buf_in[l - 1 - i]; buf_in[l - 1 - i] = ctmp; } } } /* Sanity check the input if the input is not raw */ if (!rawin && buf_inlen > EVP_MAX_MD_SIZE && (pkey_op == EVP_PKEY_OP_SIGN || pkey_op == EVP_PKEY_OP_VERIFY)) { BIO_printf(bio_err, "Error: The input data looks too long to be a hash\n"); goto end; } if (pkey_op == EVP_PKEY_OP_VERIFY) { if (rawin) { rv = do_raw_keyop(pkey_op, mctx, pkey, in, filesize, sig, siglen, NULL, 0); } else { rv = EVP_PKEY_verify(ctx, sig, (size_t)siglen, buf_in, (size_t)buf_inlen); } if (rv == 1) { BIO_puts(out, "Signature Verified Successfully\n"); ret = 0; } else { BIO_puts(out, "Signature Verification Failure\n"); } goto end; } if (rawin) { /* rawin allocates the buffer in do_raw_keyop() */ rv = do_raw_keyop(pkey_op, mctx, pkey, in, filesize, NULL, 0, &buf_out, (size_t *)&buf_outlen); } else { if (kdflen != 0) { buf_outlen = kdflen; rv = 1; } else { rv = do_keyop(ctx, pkey_op, NULL, (size_t *)&buf_outlen, buf_in, (size_t)buf_inlen); } if (rv > 0 && buf_outlen != 0) { buf_out = app_malloc(buf_outlen, "buffer output"); rv = do_keyop(ctx, pkey_op, buf_out, (size_t *)&buf_outlen, buf_in, (size_t)buf_inlen); } } if (rv <= 0) { if (pkey_op != EVP_PKEY_OP_DERIVE) { BIO_puts(bio_err, "Public Key operation error\n"); } else { BIO_puts(bio_err, "Key derivation failed\n"); } goto end; } ret = 0; if (asn1parse) { if (!ASN1_parse_dump(out, buf_out, buf_outlen, 1, -1)) ERR_print_errors(bio_err); /* but still return success */ } else if (hexdump) { BIO_dump(out, (char *)buf_out, buf_outlen); } else { BIO_write(out, buf_out, buf_outlen); } end: if (ret != 0) ERR_print_errors(bio_err); EVP_MD_CTX_free(mctx); EVP_PKEY_CTX_free(ctx); EVP_MD_free(md); release_engine(e); BIO_free(in); BIO_free_all(out); OPENSSL_free(buf_in); OPENSSL_free(buf_out); OPENSSL_free(sig); sk_OPENSSL_STRING_free(pkeyopts); sk_OPENSSL_STRING_free(pkeyopts_passin); NCONF_free(conf); return ret; } static EVP_PKEY_CTX *init_ctx(const char *kdfalg, int *pkeysize, const char *keyfile, int keyform, int key_type, char *passinarg, int pkey_op, ENGINE *e, const int engine_impl, int rawin, EVP_PKEY **ppkey, EVP_MD_CTX *mctx, const char *digestname, OSSL_LIB_CTX *libctx, const char *propq) { EVP_PKEY *pkey = NULL; EVP_PKEY_CTX *ctx = NULL; ENGINE *impl = NULL; char *passin = NULL; int rv = -1; X509 *x; if (((pkey_op == EVP_PKEY_OP_SIGN) || (pkey_op == EVP_PKEY_OP_DECRYPT) || (pkey_op == EVP_PKEY_OP_DERIVE)) && (key_type != KEY_PRIVKEY && kdfalg == NULL)) { BIO_printf(bio_err, "A private key is needed for this operation\n"); goto end; } if (!app_passwd(passinarg, NULL, &passin, NULL)) { BIO_printf(bio_err, "Error getting password\n"); goto end; } switch (key_type) { case KEY_PRIVKEY: pkey = load_key(keyfile, keyform, 0, passin, e, "private key"); break; case KEY_PUBKEY: pkey = load_pubkey(keyfile, keyform, 0, NULL, e, "public key"); break; case KEY_CERT: x = load_cert(keyfile, keyform, "Certificate"); if (x) { pkey = X509_get_pubkey(x); X509_free(x); } break; case KEY_NONE: break; } #ifndef OPENSSL_NO_ENGINE if (engine_impl) impl = e; #endif if (kdfalg != NULL) { int kdfnid = OBJ_sn2nid(kdfalg); if (kdfnid == NID_undef) { kdfnid = OBJ_ln2nid(kdfalg); if (kdfnid == NID_undef) { BIO_printf(bio_err, "The given KDF \"%s\" is unknown.\n", kdfalg); goto end; } } if (impl != NULL) ctx = EVP_PKEY_CTX_new_id(kdfnid, impl); else ctx = EVP_PKEY_CTX_new_from_name(libctx, kdfalg, propq); } else { if (pkey == NULL) goto end; *pkeysize = EVP_PKEY_get_size(pkey); if (impl != NULL) ctx = EVP_PKEY_CTX_new(pkey, impl); else ctx = EVP_PKEY_CTX_new_from_pkey(libctx, pkey, propq); if (ppkey != NULL) *ppkey = pkey; EVP_PKEY_free(pkey); } if (ctx == NULL) goto end; if (rawin) { EVP_MD_CTX_set_pkey_ctx(mctx, ctx); switch (pkey_op) { case EVP_PKEY_OP_SIGN: rv = EVP_DigestSignInit_ex(mctx, NULL, digestname, libctx, propq, pkey, NULL); break; case EVP_PKEY_OP_VERIFY: rv = EVP_DigestVerifyInit_ex(mctx, NULL, digestname, libctx, propq, pkey, NULL); break; } } else { switch (pkey_op) { case EVP_PKEY_OP_SIGN: rv = EVP_PKEY_sign_init(ctx); break; case EVP_PKEY_OP_VERIFY: rv = EVP_PKEY_verify_init(ctx); break; case EVP_PKEY_OP_VERIFYRECOVER: rv = EVP_PKEY_verify_recover_init(ctx); break; case EVP_PKEY_OP_ENCRYPT: rv = EVP_PKEY_encrypt_init(ctx); break; case EVP_PKEY_OP_DECRYPT: rv = EVP_PKEY_decrypt_init(ctx); break; case EVP_PKEY_OP_DERIVE: rv = EVP_PKEY_derive_init(ctx); break; } } if (rv <= 0) { EVP_PKEY_CTX_free(ctx); ctx = NULL; } end: OPENSSL_free(passin); return ctx; } static int setup_peer(EVP_PKEY_CTX *ctx, int peerform, const char *file, ENGINE *e) { EVP_PKEY *peer = NULL; ENGINE *engine = NULL; int ret; if (peerform == FORMAT_ENGINE) engine = e; peer = load_pubkey(file, peerform, 0, NULL, engine, "peer key"); if (peer == NULL) { BIO_printf(bio_err, "Error reading peer key %s\n", file); return 0; } ret = EVP_PKEY_derive_set_peer(ctx, peer) > 0; EVP_PKEY_free(peer); return ret; } static int do_keyop(EVP_PKEY_CTX *ctx, int pkey_op, unsigned char *out, size_t *poutlen, const unsigned char *in, size_t inlen) { int rv = 0; switch (pkey_op) { case EVP_PKEY_OP_VERIFYRECOVER: rv = EVP_PKEY_verify_recover(ctx, out, poutlen, in, inlen); break; case EVP_PKEY_OP_SIGN: rv = EVP_PKEY_sign(ctx, out, poutlen, in, inlen); break; case EVP_PKEY_OP_ENCRYPT: rv = EVP_PKEY_encrypt(ctx, out, poutlen, in, inlen); break; case EVP_PKEY_OP_DECRYPT: rv = EVP_PKEY_decrypt(ctx, out, poutlen, in, inlen); break; case EVP_PKEY_OP_DERIVE: rv = EVP_PKEY_derive(ctx, out, poutlen); break; } return rv; } #define TBUF_MAXSIZE 2048 static int do_raw_keyop(int pkey_op, EVP_MD_CTX *mctx, EVP_PKEY *pkey, BIO *in, int filesize, unsigned char *sig, int siglen, unsigned char **out, size_t *poutlen) { int rv = 0; unsigned char tbuf[TBUF_MAXSIZE]; unsigned char *mbuf = NULL; int buf_len = 0; /* Some algorithms only support oneshot digests */ if (EVP_PKEY_get_id(pkey) == EVP_PKEY_ED25519 || EVP_PKEY_get_id(pkey) == EVP_PKEY_ED448) { if (filesize < 0) { BIO_printf(bio_err, "Error: unable to determine file size for oneshot operation\n"); goto end; } mbuf = app_malloc(filesize, "oneshot sign/verify buffer"); switch (pkey_op) { case EVP_PKEY_OP_VERIFY: buf_len = BIO_read(in, mbuf, filesize); if (buf_len != filesize) { BIO_printf(bio_err, "Error reading raw input data\n"); goto end; } rv = EVP_DigestVerify(mctx, sig, (size_t)siglen, mbuf, buf_len); break; case EVP_PKEY_OP_SIGN: buf_len = BIO_read(in, mbuf, filesize); if (buf_len != filesize) { BIO_printf(bio_err, "Error reading raw input data\n"); goto end; } rv = EVP_DigestSign(mctx, NULL, poutlen, mbuf, buf_len); if (rv == 1 && out != NULL) { *out = app_malloc(*poutlen, "buffer output"); rv = EVP_DigestSign(mctx, *out, poutlen, mbuf, buf_len); } break; } goto end; } switch (pkey_op) { case EVP_PKEY_OP_VERIFY: for (;;) { buf_len = BIO_read(in, tbuf, TBUF_MAXSIZE); if (buf_len == 0) break; if (buf_len < 0) { BIO_printf(bio_err, "Error reading raw input data\n"); goto end; } rv = EVP_DigestVerifyUpdate(mctx, tbuf, (size_t)buf_len); if (rv != 1) { BIO_printf(bio_err, "Error verifying raw input data\n"); goto end; } } rv = EVP_DigestVerifyFinal(mctx, sig, (size_t)siglen); break; case EVP_PKEY_OP_SIGN: for (;;) { buf_len = BIO_read(in, tbuf, TBUF_MAXSIZE); if (buf_len == 0) break; if (buf_len < 0) { BIO_printf(bio_err, "Error reading raw input data\n"); goto end; } rv = EVP_DigestSignUpdate(mctx, tbuf, (size_t)buf_len); if (rv != 1) { BIO_printf(bio_err, "Error signing raw input data\n"); goto end; } } rv = EVP_DigestSignFinal(mctx, NULL, poutlen); if (rv == 1 && out != NULL) { *out = app_malloc(*poutlen, "buffer output"); rv = EVP_DigestSignFinal(mctx, *out, poutlen); } break; } end: OPENSSL_free(mbuf); return rv; }
./openssl/apps/ca.c
/* * Copyright 1995-2023 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #include <sys/types.h> #include <openssl/conf.h> #include <openssl/bio.h> #include <openssl/err.h> #include <openssl/bn.h> #include <openssl/txt_db.h> #include <openssl/evp.h> #include <openssl/x509.h> #include <openssl/x509v3.h> #include <openssl/objects.h> #include <openssl/ocsp.h> #include <openssl/pem.h> #ifndef W_OK # ifdef OPENSSL_SYS_VMS # include <unistd.h> # elif !defined(OPENSSL_SYS_VXWORKS) && !defined(OPENSSL_SYS_WINDOWS) && !defined(OPENSSL_SYS_TANDEM) # include <sys/file.h> # endif #endif #include "apps.h" #include "progs.h" #ifndef W_OK # define F_OK 0 # define W_OK 2 # define R_OK 4 #endif #ifndef PATH_MAX # define PATH_MAX 4096 #endif #define BASE_SECTION "ca" #define ENV_DEFAULT_CA "default_ca" #define STRING_MASK "string_mask" #define UTF8_IN "utf8" #define ENV_NEW_CERTS_DIR "new_certs_dir" #define ENV_CERTIFICATE "certificate" #define ENV_SERIAL "serial" #define ENV_RAND_SERIAL "rand_serial" #define ENV_CRLNUMBER "crlnumber" #define ENV_PRIVATE_KEY "private_key" #define ENV_DEFAULT_DAYS "default_days" #define ENV_DEFAULT_STARTDATE "default_startdate" #define ENV_DEFAULT_ENDDATE "default_enddate" #define ENV_DEFAULT_CRL_DAYS "default_crl_days" #define ENV_DEFAULT_CRL_HOURS "default_crl_hours" #define ENV_DEFAULT_MD "default_md" #define ENV_DEFAULT_EMAIL_DN "email_in_dn" #define ENV_PRESERVE "preserve" #define ENV_POLICY "policy" #define ENV_EXTENSIONS "x509_extensions" #define ENV_CRLEXT "crl_extensions" #define ENV_MSIE_HACK "msie_hack" #define ENV_NAMEOPT "name_opt" #define ENV_CERTOPT "cert_opt" #define ENV_EXTCOPY "copy_extensions" #define ENV_UNIQUE_SUBJECT "unique_subject" #define ENV_DATABASE "database" /* Additional revocation information types */ typedef enum { REV_VALID = -1, /* Valid (not-revoked) status */ REV_NONE = 0, /* No additional information */ REV_CRL_REASON = 1, /* Value is CRL reason code */ REV_HOLD = 2, /* Value is hold instruction */ REV_KEY_COMPROMISE = 3, /* Value is cert key compromise time */ REV_CA_COMPROMISE = 4 /* Value is CA key compromise time */ } REVINFO_TYPE; static char *lookup_conf(const CONF *conf, const char *group, const char *tag); static int certify(X509 **xret, const char *infile, int informat, EVP_PKEY *pkey, X509 *x509, const char *dgst, STACK_OF(OPENSSL_STRING) *sigopts, STACK_OF(OPENSSL_STRING) *vfyopts, STACK_OF(CONF_VALUE) *policy, CA_DB *db, BIGNUM *serial, const char *subj, unsigned long chtype, int multirdn, int email_dn, const char *startdate, const char *enddate, long days, int batch, const char *ext_sect, CONF *conf, int verbose, unsigned long certopt, unsigned long nameopt, int default_op, int ext_copy, int selfsign, unsigned long dateopt); static int certify_cert(X509 **xret, const char *infile, int certformat, const char *passin, EVP_PKEY *pkey, X509 *x509, const char *dgst, STACK_OF(OPENSSL_STRING) *sigopts, STACK_OF(OPENSSL_STRING) *vfyopts, STACK_OF(CONF_VALUE) *policy, CA_DB *db, BIGNUM *serial, const char *subj, unsigned long chtype, int multirdn, int email_dn, const char *startdate, const char *enddate, long days, int batch, const char *ext_sect, CONF *conf, int verbose, unsigned long certopt, unsigned long nameopt, int default_op, int ext_copy, unsigned long dateopt); static int certify_spkac(X509 **xret, const char *infile, EVP_PKEY *pkey, X509 *x509, const char *dgst, STACK_OF(OPENSSL_STRING) *sigopts, STACK_OF(CONF_VALUE) *policy, CA_DB *db, BIGNUM *serial, const char *subj, unsigned long chtype, int multirdn, int email_dn, const char *startdate, const char *enddate, long days, const char *ext_sect, CONF *conf, int verbose, unsigned long certopt, unsigned long nameopt, int default_op, int ext_copy, unsigned long dateopt); static int do_body(X509 **xret, EVP_PKEY *pkey, X509 *x509, const char *dgst, STACK_OF(OPENSSL_STRING) *sigopts, STACK_OF(CONF_VALUE) *policy, CA_DB *db, BIGNUM *serial, const char *subj, unsigned long chtype, int multirdn, int email_dn, const char *startdate, const char *enddate, long days, int batch, int verbose, X509_REQ *req, const char *ext_sect, CONF *conf, unsigned long certopt, unsigned long nameopt, int default_op, int ext_copy, int selfsign, unsigned long dateopt); static int get_certificate_status(const char *ser_status, CA_DB *db); static int check_time_format(const char *str); static int do_revoke(X509 *x509, CA_DB *db, REVINFO_TYPE rev_type, const char *extval); static char *make_revocation_str(REVINFO_TYPE rev_type, const char *rev_arg); static int make_revoked(X509_REVOKED *rev, const char *str); static int old_entry_print(const ASN1_OBJECT *obj, const ASN1_STRING *str); static void write_new_certificate(BIO *bp, X509 *x, int output_der, int notext); static CONF *extfile_conf = NULL; static int preserve = 0; static int msie_hack = 0; typedef enum OPTION_choice { OPT_COMMON, OPT_ENGINE, OPT_VERBOSE, OPT_CONFIG, OPT_NAME, OPT_SUBJ, OPT_UTF8, OPT_CREATE_SERIAL, OPT_MULTIVALUE_RDN, OPT_STARTDATE, OPT_ENDDATE, OPT_DAYS, OPT_MD, OPT_POLICY, OPT_KEYFILE, OPT_KEYFORM, OPT_PASSIN, OPT_KEY, OPT_CERT, OPT_CERTFORM, OPT_SELFSIGN, OPT_IN, OPT_INFORM, OPT_OUT, OPT_DATEOPT, OPT_OUTDIR, OPT_VFYOPT, OPT_SIGOPT, OPT_NOTEXT, OPT_BATCH, OPT_PRESERVEDN, OPT_NOEMAILDN, OPT_GENCRL, OPT_MSIE_HACK, OPT_CRL_LASTUPDATE, OPT_CRL_NEXTUPDATE, OPT_CRLDAYS, OPT_CRLHOURS, OPT_CRLSEC, OPT_INFILES, OPT_SS_CERT, OPT_SPKAC, OPT_REVOKE, OPT_VALID, OPT_EXTENSIONS, OPT_EXTFILE, OPT_STATUS, OPT_UPDATEDB, OPT_CRLEXTS, OPT_RAND_SERIAL, OPT_QUIET, OPT_R_ENUM, OPT_PROV_ENUM, /* Do not change the order here; see related case statements below */ OPT_CRL_REASON, OPT_CRL_HOLD, OPT_CRL_COMPROMISE, OPT_CRL_CA_COMPROMISE } OPTION_CHOICE; const OPTIONS ca_options[] = { {OPT_HELP_STR, 1, '-', "Usage: %s [options] [certreq...]\n"}, OPT_SECTION("General"), {"help", OPT_HELP, '-', "Display this summary"}, {"verbose", OPT_VERBOSE, '-', "Verbose output during processing"}, {"quiet", OPT_QUIET, '-', "Terse output during processing"}, {"outdir", OPT_OUTDIR, '/', "Where to put output cert"}, {"in", OPT_IN, '<', "The input cert request(s)"}, {"inform", OPT_INFORM, 'F', "CSR input format to use (PEM or DER; by default try PEM first)"}, {"infiles", OPT_INFILES, '-', "The last argument, requests to process"}, {"out", OPT_OUT, '>', "Where to put the output file(s)"}, {"dateopt", OPT_DATEOPT, 's', "Datetime format used for printing. (rfc_822/iso_8601). Default is rfc_822."}, {"notext", OPT_NOTEXT, '-', "Do not print the generated certificate"}, {"batch", OPT_BATCH, '-', "Don't ask questions"}, {"msie_hack", OPT_MSIE_HACK, '-', "msie modifications to handle all Universal Strings"}, {"ss_cert", OPT_SS_CERT, '<', "File contains a self signed cert to sign"}, {"spkac", OPT_SPKAC, '<', "File contains DN and signed public key and challenge"}, #ifndef OPENSSL_NO_ENGINE {"engine", OPT_ENGINE, 's', "Use engine, possibly a hardware device"}, #endif OPT_SECTION("Configuration"), {"config", OPT_CONFIG, 's', "A config file"}, {"name", OPT_NAME, 's', "The particular CA definition to use"}, {"section", OPT_NAME, 's', "An alias for -name"}, {"policy", OPT_POLICY, 's', "The CA 'policy' to support"}, OPT_SECTION("Certificate"), {"subj", OPT_SUBJ, 's', "Use arg instead of request's subject"}, {"utf8", OPT_UTF8, '-', "Input characters are UTF8; default ASCII"}, {"create_serial", OPT_CREATE_SERIAL, '-', "If reading serial fails, create a new random serial"}, {"rand_serial", OPT_RAND_SERIAL, '-', "Always create a random serial; do not store it"}, {"multivalue-rdn", OPT_MULTIVALUE_RDN, '-', "Deprecated; multi-valued RDNs support is always on."}, {"startdate", OPT_STARTDATE, 's', "Cert notBefore, YYMMDDHHMMSSZ"}, {"enddate", OPT_ENDDATE, 's', "YYMMDDHHMMSSZ cert notAfter (overrides -days)"}, {"days", OPT_DAYS, 'p', "Number of days to certify the cert for"}, {"extensions", OPT_EXTENSIONS, 's', "Extension section (override value in config file)"}, {"extfile", OPT_EXTFILE, '<', "Configuration file with X509v3 extensions to add"}, {"preserveDN", OPT_PRESERVEDN, '-', "Don't re-order the DN"}, {"noemailDN", OPT_NOEMAILDN, '-', "Don't add the EMAIL field to the DN"}, OPT_SECTION("Signing"), {"md", OPT_MD, 's', "Digest to use, such as sha256"}, {"keyfile", OPT_KEYFILE, 's', "The CA private key"}, {"keyform", OPT_KEYFORM, 'f', "Private key file format (ENGINE, other values ignored)"}, {"passin", OPT_PASSIN, 's', "Key and cert input file pass phrase source"}, {"key", OPT_KEY, 's', "Key to decrypt the private key or cert files if encrypted. Better use -passin"}, {"cert", OPT_CERT, '<', "The CA cert"}, {"certform", OPT_CERTFORM, 'F', "Certificate input format (DER/PEM/P12); has no effect"}, {"selfsign", OPT_SELFSIGN, '-', "Sign a cert with the key associated with it"}, {"sigopt", OPT_SIGOPT, 's', "Signature parameter in n:v form"}, {"vfyopt", OPT_VFYOPT, 's', "Verification parameter in n:v form"}, OPT_SECTION("Revocation"), {"gencrl", OPT_GENCRL, '-', "Generate a new CRL"}, {"valid", OPT_VALID, 's', "Add a Valid(not-revoked) DB entry about a cert (given in file)"}, {"status", OPT_STATUS, 's', "Shows cert status given the serial number"}, {"updatedb", OPT_UPDATEDB, '-', "Updates db for expired cert"}, {"crlexts", OPT_CRLEXTS, 's', "CRL extension section (override value in config file)"}, {"crl_reason", OPT_CRL_REASON, 's', "revocation reason"}, {"crl_hold", OPT_CRL_HOLD, 's', "the hold instruction, an OID. Sets revocation reason to certificateHold"}, {"crl_compromise", OPT_CRL_COMPROMISE, 's', "sets compromise time to val and the revocation reason to keyCompromise"}, {"crl_CA_compromise", OPT_CRL_CA_COMPROMISE, 's', "sets compromise time to val and the revocation reason to CACompromise"}, {"crl_lastupdate", OPT_CRL_LASTUPDATE, 's', "Sets the CRL lastUpdate time to val (YYMMDDHHMMSSZ or YYYYMMDDHHMMSSZ)"}, {"crl_nextupdate", OPT_CRL_NEXTUPDATE, 's', "Sets the CRL nextUpdate time to val (YYMMDDHHMMSSZ or YYYYMMDDHHMMSSZ)"}, {"crldays", OPT_CRLDAYS, 'p', "Days until the next CRL is due"}, {"crlhours", OPT_CRLHOURS, 'p', "Hours until the next CRL is due"}, {"crlsec", OPT_CRLSEC, 'p', "Seconds until the next CRL is due"}, {"revoke", OPT_REVOKE, '<', "Revoke a cert (given in file)"}, OPT_R_OPTIONS, OPT_PROV_OPTIONS, OPT_PARAMETERS(), {"certreq", 0, 0, "Certificate requests to be signed (optional)"}, {NULL} }; int ca_main(int argc, char **argv) { CONF *conf = NULL; ENGINE *e = NULL; BIGNUM *crlnumber = NULL, *serial = NULL; EVP_PKEY *pkey = NULL; BIO *in = NULL, *out = NULL, *Sout = NULL; ASN1_INTEGER *tmpser; CA_DB *db = NULL; DB_ATTR db_attr; STACK_OF(CONF_VALUE) *attribs = NULL; STACK_OF(OPENSSL_STRING) *sigopts = NULL, *vfyopts = NULL; STACK_OF(X509) *cert_sk = NULL; X509_CRL *crl = NULL; char *configfile = default_config_file, *section = NULL; char def_dgst[80] = ""; char *dgst = NULL, *policy = NULL, *keyfile = NULL; char *certfile = NULL, *crl_ext = NULL, *crlnumberfile = NULL; int certformat = FORMAT_UNDEF, informat = FORMAT_UNDEF; unsigned long dateopt = ASN1_DTFLGS_RFC822; const char *infile = NULL, *spkac_file = NULL, *ss_cert_file = NULL; const char *extensions = NULL, *extfile = NULL, *passinarg = NULL; char *passin = NULL; char *outdir = NULL, *outfile = NULL, *rev_arg = NULL, *ser_status = NULL; const char *serialfile = NULL, *subj = NULL; char *prog, *startdate = NULL, *enddate = NULL; char *dbfile = NULL, *f; char new_cert[PATH_MAX]; char tmp[10 + 1] = "\0"; char *const *pp; const char *p; size_t outdirlen = 0; int create_ser = 0, free_passin = 0, total = 0, total_done = 0; int batch = 0, default_op = 1, doupdatedb = 0, ext_copy = EXT_COPY_NONE; int keyformat = FORMAT_UNDEF, multirdn = 1, notext = 0, output_der = 0; int ret = 1, email_dn = 1, req = 0, verbose = 0, gencrl = 0, dorevoke = 0; int rand_ser = 0, i, j, selfsign = 0, def_ret; char *crl_lastupdate = NULL, *crl_nextupdate = NULL; long crldays = 0, crlhours = 0, crlsec = 0, days = 0; unsigned long chtype = MBSTRING_ASC, certopt = 0; X509 *x509 = NULL, *x509p = NULL, *x = NULL; REVINFO_TYPE rev_type = REV_NONE; X509_REVOKED *r = NULL; OPTION_CHOICE o; prog = opt_init(argc, argv, ca_options); while ((o = opt_next()) != OPT_EOF) { switch (o) { case OPT_EOF: case OPT_ERR: opthelp: BIO_printf(bio_err, "%s: Use -help for summary.\n", prog); goto end; case OPT_HELP: opt_help(ca_options); ret = 0; goto end; case OPT_IN: req = 1; infile = opt_arg(); break; case OPT_INFORM: if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &informat)) goto opthelp; break; case OPT_OUT: outfile = opt_arg(); break; case OPT_DATEOPT: if (!set_dateopt(&dateopt, opt_arg())) goto opthelp; break; case OPT_VERBOSE: verbose = 1; break; case OPT_QUIET: verbose = 0; break; case OPT_CONFIG: configfile = opt_arg(); break; case OPT_NAME: section = opt_arg(); break; case OPT_SUBJ: subj = opt_arg(); /* preserve=1; */ break; case OPT_UTF8: chtype = MBSTRING_UTF8; break; case OPT_RAND_SERIAL: rand_ser = 1; break; case OPT_CREATE_SERIAL: create_ser = 1; break; case OPT_MULTIVALUE_RDN: /* obsolete */ break; case OPT_STARTDATE: startdate = opt_arg(); break; case OPT_ENDDATE: enddate = opt_arg(); break; case OPT_DAYS: days = atoi(opt_arg()); break; case OPT_MD: dgst = opt_arg(); break; case OPT_POLICY: policy = opt_arg(); break; case OPT_KEYFILE: keyfile = opt_arg(); break; case OPT_KEYFORM: if (!opt_format(opt_arg(), OPT_FMT_ANY, &keyformat)) goto opthelp; break; case OPT_PASSIN: passinarg = opt_arg(); break; case OPT_R_CASES: if (!opt_rand(o)) goto end; break; case OPT_PROV_CASES: if (!opt_provider(o)) goto end; break; case OPT_KEY: passin = opt_arg(); break; case OPT_CERT: certfile = opt_arg(); break; case OPT_CERTFORM: if (!opt_format(opt_arg(), OPT_FMT_ANY, &certformat)) goto opthelp; break; case OPT_SELFSIGN: selfsign = 1; break; case OPT_OUTDIR: outdir = opt_arg(); break; case OPT_SIGOPT: if (sigopts == NULL) sigopts = sk_OPENSSL_STRING_new_null(); if (sigopts == NULL || !sk_OPENSSL_STRING_push(sigopts, opt_arg())) goto end; break; case OPT_VFYOPT: if (vfyopts == NULL) vfyopts = sk_OPENSSL_STRING_new_null(); if (vfyopts == NULL || !sk_OPENSSL_STRING_push(vfyopts, opt_arg())) goto end; break; case OPT_NOTEXT: notext = 1; break; case OPT_BATCH: batch = 1; break; case OPT_PRESERVEDN: preserve = 1; break; case OPT_NOEMAILDN: email_dn = 0; break; case OPT_GENCRL: gencrl = 1; break; case OPT_MSIE_HACK: msie_hack = 1; break; case OPT_CRL_LASTUPDATE: crl_lastupdate = opt_arg(); break; case OPT_CRL_NEXTUPDATE: crl_nextupdate = opt_arg(); break; case OPT_CRLDAYS: crldays = atol(opt_arg()); break; case OPT_CRLHOURS: crlhours = atol(opt_arg()); break; case OPT_CRLSEC: crlsec = atol(opt_arg()); break; case OPT_INFILES: req = 1; goto end_of_options; case OPT_SS_CERT: ss_cert_file = opt_arg(); req = 1; break; case OPT_SPKAC: spkac_file = opt_arg(); req = 1; break; case OPT_REVOKE: infile = opt_arg(); dorevoke = 1; break; case OPT_VALID: infile = opt_arg(); dorevoke = 2; break; case OPT_EXTENSIONS: extensions = opt_arg(); break; case OPT_EXTFILE: extfile = opt_arg(); break; case OPT_STATUS: ser_status = opt_arg(); break; case OPT_UPDATEDB: doupdatedb = 1; break; case OPT_CRLEXTS: crl_ext = opt_arg(); break; case OPT_CRL_REASON: /* := REV_CRL_REASON */ case OPT_CRL_HOLD: case OPT_CRL_COMPROMISE: case OPT_CRL_CA_COMPROMISE: rev_arg = opt_arg(); rev_type = (o - OPT_CRL_REASON) + REV_CRL_REASON; break; case OPT_ENGINE: e = setup_engine(opt_arg(), 0); break; } } end_of_options: /* Remaining args are files to certify. */ argc = opt_num_rest(); argv = opt_rest(); if ((conf = app_load_config_verbose(configfile, 1)) == NULL) goto end; if (configfile != default_config_file && !app_load_modules(conf)) goto end; /* Lets get the config section we are using */ if (section == NULL && (section = lookup_conf(conf, BASE_SECTION, ENV_DEFAULT_CA)) == NULL) goto end; p = app_conf_try_string(conf, NULL, "oid_file"); if (p != NULL) { BIO *oid_bio = BIO_new_file(p, "r"); if (oid_bio == NULL) { ERR_clear_error(); } else { OBJ_create_objects(oid_bio); BIO_free(oid_bio); } } if (!add_oid_section(conf)) goto end; app_RAND_load_conf(conf, BASE_SECTION); if (!app_RAND_load()) goto end; f = app_conf_try_string(conf, section, STRING_MASK); if (f != NULL && !ASN1_STRING_set_default_mask_asc(f)) { BIO_printf(bio_err, "Invalid global string mask setting %s\n", f); goto end; } if (chtype != MBSTRING_UTF8) { f = app_conf_try_string(conf, section, UTF8_IN); if (f != NULL && strcmp(f, "yes") == 0) chtype = MBSTRING_UTF8; } db_attr.unique_subject = 1; p = app_conf_try_string(conf, section, ENV_UNIQUE_SUBJECT); if (p != NULL) db_attr.unique_subject = parse_yesno(p, 1); /*****************************************************************/ /* report status of cert with serial number given on command line */ if (ser_status) { dbfile = lookup_conf(conf, section, ENV_DATABASE); if (dbfile == NULL) goto end; db = load_index(dbfile, &db_attr); if (db == NULL) { BIO_printf(bio_err, "Problem with index file: %s (could not load/parse file)\n", dbfile); goto end; } if (index_index(db) <= 0) goto end; if (get_certificate_status(ser_status, db) != 1) BIO_printf(bio_err, "Error verifying serial %s!\n", ser_status); goto end; } /*****************************************************************/ /* we definitely need a private key, so let's get it */ if (keyfile == NULL && (keyfile = lookup_conf(conf, section, ENV_PRIVATE_KEY)) == NULL) goto end; if (passin == NULL) { free_passin = 1; if (!app_passwd(passinarg, NULL, &passin, NULL)) { BIO_printf(bio_err, "Error getting password\n"); goto end; } } pkey = load_key(keyfile, keyformat, 0, passin, e, "CA private key"); cleanse(passin); if (pkey == NULL) /* load_key() has already printed an appropriate message */ goto end; /*****************************************************************/ /* we need a certificate */ if (!selfsign || spkac_file || ss_cert_file || gencrl) { if (certfile == NULL && (certfile = lookup_conf(conf, section, ENV_CERTIFICATE)) == NULL) goto end; x509 = load_cert_pass(certfile, certformat, 1, passin, "CA certificate"); if (x509 == NULL) goto end; if (!X509_check_private_key(x509, pkey)) { BIO_printf(bio_err, "CA certificate and CA private key do not match\n"); goto end; } } if (!selfsign) x509p = x509; f = app_conf_try_string(conf, BASE_SECTION, ENV_PRESERVE); if (f != NULL && (*f == 'y' || *f == 'Y')) preserve = 1; f = app_conf_try_string(conf, BASE_SECTION, ENV_MSIE_HACK); if (f != NULL && (*f == 'y' || *f == 'Y')) msie_hack = 1; f = app_conf_try_string(conf, section, ENV_NAMEOPT); if (f != NULL) { if (!set_nameopt(f)) { BIO_printf(bio_err, "Invalid name options: \"%s\"\n", f); goto end; } default_op = 0; } f = app_conf_try_string(conf, section, ENV_CERTOPT); if (f != NULL) { if (!set_cert_ex(&certopt, f)) { BIO_printf(bio_err, "Invalid certificate options: \"%s\"\n", f); goto end; } default_op = 0; } f = app_conf_try_string(conf, section, ENV_EXTCOPY); if (f != NULL) { if (!set_ext_copy(&ext_copy, f)) { BIO_printf(bio_err, "Invalid extension copy option: \"%s\"\n", f); goto end; } } /*****************************************************************/ /* lookup where to write new certificates */ if ((outdir == NULL) && (req)) { outdir = NCONF_get_string(conf, section, ENV_NEW_CERTS_DIR); if (outdir == NULL) { BIO_printf(bio_err, "there needs to be defined a directory for new certificate to be placed in\n"); goto end; } #ifndef OPENSSL_SYS_VMS /* * outdir is a directory spec, but access() for VMS demands a * filename. We could use the DEC C routine to convert the * directory syntax to Unix, and give that to app_isdir, * but for now the fopen will catch the error if it's not a * directory */ if (app_isdir(outdir) <= 0) { BIO_printf(bio_err, "%s: %s is not a directory\n", prog, outdir); perror(outdir); goto end; } #endif } /*****************************************************************/ /* we need to load the database file */ dbfile = lookup_conf(conf, section, ENV_DATABASE); if (dbfile == NULL) goto end; db = load_index(dbfile, &db_attr); if (db == NULL) { BIO_printf(bio_err, "Problem with index file: %s (could not load/parse file)\n", dbfile); goto end; } /* Lets check some fields */ for (i = 0; i < sk_OPENSSL_PSTRING_num(db->db->data); i++) { pp = sk_OPENSSL_PSTRING_value(db->db->data, i); if ((pp[DB_type][0] != DB_TYPE_REV) && (pp[DB_rev_date][0] != '\0')) { BIO_printf(bio_err, "entry %d: not revoked yet, but has a revocation date\n", i + 1); goto end; } if ((pp[DB_type][0] == DB_TYPE_REV) && !make_revoked(NULL, pp[DB_rev_date])) { BIO_printf(bio_err, " in entry %d\n", i + 1); goto end; } if (!check_time_format((char *)pp[DB_exp_date])) { BIO_printf(bio_err, "entry %d: invalid expiry date\n", i + 1); goto end; } p = pp[DB_serial]; j = strlen(p); if (*p == '-') { p++; j--; } if ((j & 1) || (j < 2)) { BIO_printf(bio_err, "entry %d: bad serial number length (%d)\n", i + 1, j); goto end; } for ( ; *p; p++) { if (!isxdigit(_UC(*p))) { BIO_printf(bio_err, "entry %d: bad char 0%o '%c' in serial number\n", i + 1, *p, *p); goto end; } } } if (verbose) { TXT_DB_write(bio_out, db->db); BIO_printf(bio_err, "%d entries loaded from the database\n", sk_OPENSSL_PSTRING_num(db->db->data)); BIO_printf(bio_err, "generating index\n"); } if (index_index(db) <= 0) goto end; /*****************************************************************/ /* Update the db file for expired certificates */ if (doupdatedb) { if (verbose) BIO_printf(bio_err, "Updating %s ...\n", dbfile); i = do_updatedb(db, NULL); if (i == -1) { BIO_printf(bio_err, "Malloc failure\n"); goto end; } else if (i == 0) { if (verbose) BIO_printf(bio_err, "No entries found to mark expired\n"); } else { if (!save_index(dbfile, "new", db)) goto end; if (!rotate_index(dbfile, "new", "old")) goto end; if (verbose) BIO_printf(bio_err, "Done. %d entries marked as expired\n", i); } } /*****************************************************************/ /* Read extensions config file */ if (extfile) { if ((extfile_conf = app_load_config(extfile)) == NULL) { ret = 1; goto end; } if (verbose) BIO_printf(bio_err, "Successfully loaded extensions file %s\n", extfile); /* We can have sections in the ext file */ if (extensions == NULL) { extensions = app_conf_try_string(extfile_conf, "default", "extensions"); if (extensions == NULL) extensions = "default"; } } /*****************************************************************/ if (req || gencrl) { if (spkac_file != NULL && outfile != NULL) { output_der = 1; batch = 1; } } def_ret = EVP_PKEY_get_default_digest_name(pkey, def_dgst, sizeof(def_dgst)); /* * EVP_PKEY_get_default_digest_name() returns 2 if the digest is * mandatory for this algorithm. * * That call may give back the name "UNDEF", which has these meanings: * * when def_ret == 2: the user MUST leave the digest unspecified * when def_ret == 1: the user MAY leave the digest unspecified */ if (def_ret == 2 && strcmp(def_dgst, "UNDEF") == 0) { dgst = NULL; } else if (dgst == NULL && (dgst = lookup_conf(conf, section, ENV_DEFAULT_MD)) == NULL && strcmp(def_dgst, "UNDEF") != 0) { goto end; } else { if (strcmp(dgst, "default") == 0 || strcmp(def_dgst, "UNDEF") == 0) { if (def_ret <= 0) { BIO_puts(bio_err, "no default digest\n"); goto end; } dgst = def_dgst; } } if (req) { if (email_dn == 1) { char *tmp_email_dn = NULL; tmp_email_dn = app_conf_try_string(conf, section, ENV_DEFAULT_EMAIL_DN); if (tmp_email_dn != NULL && strcmp(tmp_email_dn, "no") == 0) email_dn = 0; } if (verbose) BIO_printf(bio_err, "message digest is %s\n", dgst); if (policy == NULL && (policy = lookup_conf(conf, section, ENV_POLICY)) == NULL) goto end; if (verbose) BIO_printf(bio_err, "policy is %s\n", policy); if (app_conf_try_string(conf, section, ENV_RAND_SERIAL) != NULL) { rand_ser = 1; } else { serialfile = lookup_conf(conf, section, ENV_SERIAL); if (serialfile == NULL) goto end; } if (extfile_conf != NULL) { /* Check syntax of extfile */ X509V3_CTX ctx; X509V3_set_ctx_test(&ctx); X509V3_set_nconf(&ctx, extfile_conf); if (!X509V3_EXT_add_nconf(extfile_conf, &ctx, extensions, NULL)) { BIO_printf(bio_err, "Error checking certificate extensions from extfile section %s\n", extensions); ret = 1; goto end; } } else { /* * no '-extfile' option, so we look for extensions in the main * configuration file */ if (extensions == NULL) extensions = app_conf_try_string(conf, section, ENV_EXTENSIONS); if (extensions != NULL) { /* Check syntax of config file section */ X509V3_CTX ctx; X509V3_set_ctx_test(&ctx); X509V3_set_nconf(&ctx, conf); if (!X509V3_EXT_add_nconf(conf, &ctx, extensions, NULL)) { BIO_printf(bio_err, "Error checking certificate extension config section %s\n", extensions); ret = 1; goto end; } } } if (startdate == NULL) startdate = app_conf_try_string(conf, section, ENV_DEFAULT_STARTDATE); if (startdate != NULL && !ASN1_TIME_set_string_X509(NULL, startdate)) { BIO_printf(bio_err, "start date is invalid, it should be YYMMDDHHMMSSZ or YYYYMMDDHHMMSSZ\n"); goto end; } if (startdate == NULL) startdate = "today"; if (enddate == NULL) enddate = app_conf_try_string(conf, section, ENV_DEFAULT_ENDDATE); if (enddate != NULL && !ASN1_TIME_set_string_X509(NULL, enddate)) { BIO_printf(bio_err, "end date is invalid, it should be YYMMDDHHMMSSZ or YYYYMMDDHHMMSSZ\n"); goto end; } if (days == 0) { if (!app_conf_try_number(conf, section, ENV_DEFAULT_DAYS, &days)) days = 0; } if (enddate == NULL && days == 0) { BIO_printf(bio_err, "cannot lookup how many days to certify for\n"); goto end; } if (rand_ser) { if ((serial = BN_new()) == NULL || !rand_serial(serial, NULL)) { BIO_printf(bio_err, "error generating serial number\n"); goto end; } } else { serial = load_serial(serialfile, NULL, create_ser, NULL); if (serial == NULL) { BIO_printf(bio_err, "error while loading serial number\n"); goto end; } if (verbose) { if (BN_is_zero(serial)) { BIO_printf(bio_err, "next serial number is 00\n"); } else { if ((f = BN_bn2hex(serial)) == NULL) goto end; BIO_printf(bio_err, "next serial number is %s\n", f); OPENSSL_free(f); } } } if ((attribs = NCONF_get_section(conf, policy)) == NULL) { BIO_printf(bio_err, "unable to find 'section' for %s\n", policy); goto end; } if ((cert_sk = sk_X509_new_null()) == NULL) { BIO_printf(bio_err, "Memory allocation failure\n"); goto end; } if (spkac_file != NULL) { total++; j = certify_spkac(&x, spkac_file, pkey, x509, dgst, sigopts, attribs, db, serial, subj, chtype, multirdn, email_dn, startdate, enddate, days, extensions, conf, verbose, certopt, get_nameopt(), default_op, ext_copy, dateopt); if (j < 0) goto end; if (j > 0) { total_done++; BIO_printf(bio_err, "\n"); if (!BN_add_word(serial, 1)) goto end; if (!sk_X509_push(cert_sk, x)) { BIO_printf(bio_err, "Memory allocation failure\n"); goto end; } } } if (ss_cert_file != NULL) { total++; j = certify_cert(&x, ss_cert_file, certformat, passin, pkey, x509, dgst, sigopts, vfyopts, attribs, db, serial, subj, chtype, multirdn, email_dn, startdate, enddate, days, batch, extensions, conf, verbose, certopt, get_nameopt(), default_op, ext_copy, dateopt); if (j < 0) goto end; if (j > 0) { total_done++; BIO_printf(bio_err, "\n"); if (!BN_add_word(serial, 1)) goto end; if (!sk_X509_push(cert_sk, x)) { BIO_printf(bio_err, "Memory allocation failure\n"); goto end; } } } if (infile != NULL) { total++; j = certify(&x, infile, informat, pkey, x509p, dgst, sigopts, vfyopts, attribs, db, serial, subj, chtype, multirdn, email_dn, startdate, enddate, days, batch, extensions, conf, verbose, certopt, get_nameopt(), default_op, ext_copy, selfsign, dateopt); if (j < 0) goto end; if (j > 0) { total_done++; BIO_printf(bio_err, "\n"); if (!BN_add_word(serial, 1)) goto end; if (!sk_X509_push(cert_sk, x)) { BIO_printf(bio_err, "Memory allocation failure\n"); goto end; } } } for (i = 0; i < argc; i++) { total++; j = certify(&x, argv[i], informat, pkey, x509p, dgst, sigopts, vfyopts, attribs, db, serial, subj, chtype, multirdn, email_dn, startdate, enddate, days, batch, extensions, conf, verbose, certopt, get_nameopt(), default_op, ext_copy, selfsign, dateopt); if (j < 0) goto end; if (j > 0) { total_done++; BIO_printf(bio_err, "\n"); if (!BN_add_word(serial, 1)) { X509_free(x); goto end; } if (!sk_X509_push(cert_sk, x)) { BIO_printf(bio_err, "Memory allocation failure\n"); X509_free(x); goto end; } } } /* * we have a stack of newly certified certificates and a database * and serial number that need updating */ if (sk_X509_num(cert_sk) > 0) { if (!batch) { BIO_printf(bio_err, "\n%d out of %d certificate requests certified, commit? [y/n]", total_done, total); (void)BIO_flush(bio_err); tmp[0] = '\0'; if (fgets(tmp, sizeof(tmp), stdin) == NULL) { BIO_printf(bio_err, "CERTIFICATION CANCELED: I/O error\n"); ret = 0; goto end; } if (tmp[0] != 'y' && tmp[0] != 'Y') { BIO_printf(bio_err, "CERTIFICATION CANCELED\n"); ret = 0; goto end; } } BIO_printf(bio_err, "Write out database with %d new entries\n", sk_X509_num(cert_sk)); if (serialfile != NULL && !save_serial(serialfile, "new", serial, NULL)) goto end; if (!save_index(dbfile, "new", db)) goto end; } outdirlen = OPENSSL_strlcpy(new_cert, outdir, sizeof(new_cert)); #ifndef OPENSSL_SYS_VMS outdirlen = OPENSSL_strlcat(new_cert, "/", sizeof(new_cert)); #endif if (verbose) BIO_printf(bio_err, "writing new certificates\n"); for (i = 0; i < sk_X509_num(cert_sk); i++) { BIO *Cout = NULL; X509 *xi = sk_X509_value(cert_sk, i); const ASN1_INTEGER *serialNumber = X509_get0_serialNumber(xi); const unsigned char *psn = ASN1_STRING_get0_data(serialNumber); const int snl = ASN1_STRING_length(serialNumber); const int filen_len = 2 * (snl > 0 ? snl : 1) + sizeof(".pem"); char *n = new_cert + outdirlen; if (outdirlen + filen_len > PATH_MAX) { BIO_printf(bio_err, "certificate file name too long\n"); goto end; } if (snl > 0) { static const char HEX_DIGITS[] = "0123456789ABCDEF"; for (j = 0; j < snl; j++, psn++) { *n++ = HEX_DIGITS[*psn >> 4]; *n++ = HEX_DIGITS[*psn & 0x0F]; } } else { *(n++) = '0'; *(n++) = '0'; } *(n++) = '.'; *(n++) = 'p'; *(n++) = 'e'; *(n++) = 'm'; *n = '\0'; /* closing new_cert */ if (verbose) BIO_printf(bio_err, "writing %s\n", new_cert); Sout = bio_open_default(outfile, 'w', output_der ? FORMAT_ASN1 : FORMAT_TEXT); if (Sout == NULL) goto end; Cout = BIO_new_file(new_cert, "w"); if (Cout == NULL) { perror(new_cert); goto end; } write_new_certificate(Cout, xi, 0, notext); write_new_certificate(Sout, xi, output_der, notext); BIO_free_all(Cout); BIO_free_all(Sout); Sout = NULL; } if (sk_X509_num(cert_sk)) { /* Rename the database and the serial file */ if (serialfile != NULL && !rotate_serial(serialfile, "new", "old")) goto end; if (!rotate_index(dbfile, "new", "old")) goto end; BIO_printf(bio_err, "Database updated\n"); } } /*****************************************************************/ if (gencrl) { int crl_v2 = 0; if (crl_ext == NULL) crl_ext = app_conf_try_string(conf, section, ENV_CRLEXT); if (crl_ext != NULL) { /* Check syntax of file */ X509V3_CTX ctx; X509V3_set_ctx_test(&ctx); X509V3_set_nconf(&ctx, conf); if (!X509V3_EXT_add_nconf(conf, &ctx, crl_ext, NULL)) { BIO_printf(bio_err, "Error checking CRL extension section %s\n", crl_ext); ret = 1; goto end; } } crlnumberfile = app_conf_try_string(conf, section, ENV_CRLNUMBER); if (crlnumberfile != NULL) { if ((crlnumber = load_serial(crlnumberfile, NULL, 0, NULL)) == NULL) { BIO_printf(bio_err, "error while loading CRL number\n"); goto end; } } if (!crldays && !crlhours && !crlsec) { if (!app_conf_try_number(conf, section, ENV_DEFAULT_CRL_DAYS, &crldays)) crldays = 0; if (!app_conf_try_number(conf, section, ENV_DEFAULT_CRL_HOURS, &crlhours)) crlhours = 0; } if ((crl_nextupdate == NULL) && (crldays == 0) && (crlhours == 0) && (crlsec == 0)) { BIO_printf(bio_err, "cannot lookup how long until the next CRL is issued\n"); goto end; } if (verbose) BIO_printf(bio_err, "making CRL\n"); if ((crl = X509_CRL_new_ex(app_get0_libctx(), app_get0_propq())) == NULL) goto end; if (!X509_CRL_set_issuer_name(crl, X509_get_subject_name(x509))) goto end; if (!set_crl_lastupdate(crl, crl_lastupdate)) { BIO_puts(bio_err, "error setting CRL lastUpdate\n"); ret = 1; goto end; } if (!set_crl_nextupdate(crl, crl_nextupdate, crldays, crlhours, crlsec)) { BIO_puts(bio_err, "error setting CRL nextUpdate\n"); ret = 1; goto end; } for (i = 0; i < sk_OPENSSL_PSTRING_num(db->db->data); i++) { pp = sk_OPENSSL_PSTRING_value(db->db->data, i); if (pp[DB_type][0] == DB_TYPE_REV) { if ((r = X509_REVOKED_new()) == NULL) goto end; j = make_revoked(r, pp[DB_rev_date]); if (!j) goto end; if (j == 2) crl_v2 = 1; if (!BN_hex2bn(&serial, pp[DB_serial])) goto end; tmpser = BN_to_ASN1_INTEGER(serial, NULL); BN_free(serial); serial = NULL; if (!tmpser) goto end; X509_REVOKED_set_serialNumber(r, tmpser); ASN1_INTEGER_free(tmpser); X509_CRL_add0_revoked(crl, r); } } /* * sort the data so it will be written in serial number order */ X509_CRL_sort(crl); /* we now have a CRL */ if (verbose) BIO_printf(bio_err, "signing CRL\n"); /* Add any extensions asked for */ if (crl_ext != NULL || crlnumberfile != NULL) { X509V3_CTX crlctx; X509V3_set_ctx(&crlctx, x509, NULL, NULL, crl, 0); X509V3_set_nconf(&crlctx, conf); if (crl_ext != NULL) if (!X509V3_EXT_CRL_add_nconf(conf, &crlctx, crl_ext, crl)) { BIO_printf(bio_err, "Error adding CRL extensions from section %s\n", crl_ext); goto end; } if (crlnumberfile != NULL) { tmpser = BN_to_ASN1_INTEGER(crlnumber, NULL); if (!tmpser) goto end; X509_CRL_add1_ext_i2d(crl, NID_crl_number, tmpser, 0, 0); ASN1_INTEGER_free(tmpser); crl_v2 = 1; if (!BN_add_word(crlnumber, 1)) goto end; } } if (crl_ext != NULL || crl_v2) { if (!X509_CRL_set_version(crl, X509_CRL_VERSION_2)) goto end; } /* we have a CRL number that need updating */ if (crlnumberfile != NULL && !save_serial(crlnumberfile, "new", crlnumber, NULL)) goto end; BN_free(crlnumber); crlnumber = NULL; if (!do_X509_CRL_sign(crl, pkey, dgst, sigopts)) goto end; Sout = bio_open_default(outfile, 'w', output_der ? FORMAT_ASN1 : FORMAT_TEXT); if (Sout == NULL) goto end; PEM_write_bio_X509_CRL(Sout, crl); /* Rename the crlnumber file */ if (crlnumberfile != NULL && !rotate_serial(crlnumberfile, "new", "old")) goto end; } /*****************************************************************/ if (dorevoke) { if (infile == NULL) { BIO_printf(bio_err, "no input files\n"); goto end; } else { X509 *revcert; revcert = load_cert_pass(infile, informat, 1, passin, "certificate to be revoked"); if (revcert == NULL) goto end; if (dorevoke == 2) rev_type = REV_VALID; j = do_revoke(revcert, db, rev_type, rev_arg); if (j <= 0) goto end; X509_free(revcert); if (!save_index(dbfile, "new", db)) goto end; if (!rotate_index(dbfile, "new", "old")) goto end; BIO_printf(bio_err, "Database updated\n"); } } ret = 0; end: if (ret) ERR_print_errors(bio_err); BIO_free_all(Sout); BIO_free_all(out); BIO_free_all(in); OSSL_STACK_OF_X509_free(cert_sk); cleanse(passin); if (free_passin) OPENSSL_free(passin); BN_free(serial); BN_free(crlnumber); free_index(db); sk_OPENSSL_STRING_free(sigopts); sk_OPENSSL_STRING_free(vfyopts); EVP_PKEY_free(pkey); X509_free(x509); X509_CRL_free(crl); NCONF_free(conf); NCONF_free(extfile_conf); release_engine(e); return ret; } static char *lookup_conf(const CONF *conf, const char *section, const char *tag) { char *entry = NCONF_get_string(conf, section, tag); if (entry == NULL) BIO_printf(bio_err, "variable lookup failed for %s::%s\n", section, tag); return entry; } static int certify(X509 **xret, const char *infile, int informat, EVP_PKEY *pkey, X509 *x509, const char *dgst, STACK_OF(OPENSSL_STRING) *sigopts, STACK_OF(OPENSSL_STRING) *vfyopts, STACK_OF(CONF_VALUE) *policy, CA_DB *db, BIGNUM *serial, const char *subj, unsigned long chtype, int multirdn, int email_dn, const char *startdate, const char *enddate, long days, int batch, const char *ext_sect, CONF *lconf, int verbose, unsigned long certopt, unsigned long nameopt, int default_op, int ext_copy, int selfsign, unsigned long dateopt) { X509_REQ *req = NULL; EVP_PKEY *pktmp = NULL; int ok = -1, i; req = load_csr_autofmt(infile, informat, vfyopts, "certificate request"); if (req == NULL) goto end; if ((pktmp = X509_REQ_get0_pubkey(req)) == NULL) { BIO_printf(bio_err, "Error unpacking public key\n"); goto end; } if (verbose) X509_REQ_print_ex(bio_err, req, nameopt, X509_FLAG_COMPAT); BIO_printf(bio_err, "Check that the request matches the signature\n"); ok = 0; if (selfsign && !X509_REQ_check_private_key(req, pkey)) { BIO_printf(bio_err, "Certificate request and CA private key do not match\n"); goto end; } i = do_X509_REQ_verify(req, pktmp, vfyopts); if (i < 0) { BIO_printf(bio_err, "Signature verification problems...\n"); goto end; } if (i == 0) { BIO_printf(bio_err, "Signature did not match the certificate request\n"); goto end; } BIO_printf(bio_err, "Signature ok\n"); ok = do_body(xret, pkey, x509, dgst, sigopts, policy, db, serial, subj, chtype, multirdn, email_dn, startdate, enddate, days, batch, verbose, req, ext_sect, lconf, certopt, nameopt, default_op, ext_copy, selfsign, dateopt); end: ERR_print_errors(bio_err); X509_REQ_free(req); return ok; } static int certify_cert(X509 **xret, const char *infile, int certformat, const char *passin, EVP_PKEY *pkey, X509 *x509, const char *dgst, STACK_OF(OPENSSL_STRING) *sigopts, STACK_OF(OPENSSL_STRING) *vfyopts, STACK_OF(CONF_VALUE) *policy, CA_DB *db, BIGNUM *serial, const char *subj, unsigned long chtype, int multirdn, int email_dn, const char *startdate, const char *enddate, long days, int batch, const char *ext_sect, CONF *lconf, int verbose, unsigned long certopt, unsigned long nameopt, int default_op, int ext_copy, unsigned long dateopt) { X509 *template_cert = NULL; X509_REQ *rreq = NULL; EVP_PKEY *pktmp = NULL; int ok = -1, i; if ((template_cert = load_cert_pass(infile, certformat, 1, passin, "template certificate")) == NULL) goto end; if (verbose) X509_print(bio_err, template_cert); BIO_printf(bio_err, "Check that the request matches the signature\n"); if ((pktmp = X509_get0_pubkey(template_cert)) == NULL) { BIO_printf(bio_err, "error unpacking public key\n"); goto end; } i = do_X509_verify(template_cert, pktmp, vfyopts); if (i < 0) { ok = 0; BIO_printf(bio_err, "Signature verification problems....\n"); goto end; } if (i == 0) { ok = 0; BIO_printf(bio_err, "Signature did not match the certificate\n"); goto end; } else { BIO_printf(bio_err, "Signature ok\n"); } if ((rreq = X509_to_X509_REQ(template_cert, NULL, NULL)) == NULL) goto end; ok = do_body(xret, pkey, x509, dgst, sigopts, policy, db, serial, subj, chtype, multirdn, email_dn, startdate, enddate, days, batch, verbose, rreq, ext_sect, lconf, certopt, nameopt, default_op, ext_copy, 0, dateopt); end: X509_REQ_free(rreq); X509_free(template_cert); return ok; } static int do_body(X509 **xret, EVP_PKEY *pkey, X509 *x509, const char *dgst, STACK_OF(OPENSSL_STRING) *sigopts, STACK_OF(CONF_VALUE) *policy, CA_DB *db, BIGNUM *serial, const char *subj, unsigned long chtype, int multirdn, int email_dn, const char *startdate, const char *enddate, long days, int batch, int verbose, X509_REQ *req, const char *ext_sect, CONF *lconf, unsigned long certopt, unsigned long nameopt, int default_op, int ext_copy, int selfsign, unsigned long dateopt) { const X509_NAME *name = NULL; X509_NAME *CAname = NULL, *subject = NULL; const ASN1_TIME *tm; ASN1_STRING *str, *str2; ASN1_OBJECT *obj; X509 *ret = NULL; X509_NAME_ENTRY *ne, *tne; EVP_PKEY *pktmp; int ok = -1, i, j, last, nid; const char *p; CONF_VALUE *cv; OPENSSL_STRING row[DB_NUMBER]; OPENSSL_STRING *irow = NULL; OPENSSL_STRING *rrow = NULL; char buf[25]; X509V3_CTX ext_ctx; for (i = 0; i < DB_NUMBER; i++) row[i] = NULL; if (subj) { X509_NAME *n = parse_name(subj, chtype, multirdn, "subject"); if (!n) goto end; X509_REQ_set_subject_name(req, n); X509_NAME_free(n); } if (default_op) BIO_printf(bio_err, "The Subject's Distinguished Name is as follows\n"); name = X509_REQ_get_subject_name(req); for (i = 0; i < X509_NAME_entry_count(name); i++) { ne = X509_NAME_get_entry(name, i); str = X509_NAME_ENTRY_get_data(ne); obj = X509_NAME_ENTRY_get_object(ne); nid = OBJ_obj2nid(obj); if (msie_hack) { /* assume all type should be strings */ if (str->type == V_ASN1_UNIVERSALSTRING) ASN1_UNIVERSALSTRING_to_string(str); if (str->type == V_ASN1_IA5STRING && nid != NID_pkcs9_emailAddress) str->type = V_ASN1_T61STRING; if (nid == NID_pkcs9_emailAddress && str->type == V_ASN1_PRINTABLESTRING) str->type = V_ASN1_IA5STRING; } /* If no EMAIL is wanted in the subject */ if (nid == NID_pkcs9_emailAddress && !email_dn) continue; /* check some things */ if (nid == NID_pkcs9_emailAddress && str->type != V_ASN1_IA5STRING) { BIO_printf(bio_err, "\nemailAddress type needs to be of type IA5STRING\n"); goto end; } if (str->type != V_ASN1_BMPSTRING && str->type != V_ASN1_UTF8STRING) { j = ASN1_PRINTABLE_type(str->data, str->length); if ((j == V_ASN1_T61STRING && str->type != V_ASN1_T61STRING) || (j == V_ASN1_IA5STRING && str->type == V_ASN1_PRINTABLESTRING)) { BIO_printf(bio_err, "\nThe string contains characters that are illegal for the ASN.1 type\n"); goto end; } } if (default_op) old_entry_print(obj, str); } /* Ok, now we check the 'policy' stuff. */ if ((subject = X509_NAME_new()) == NULL) { BIO_printf(bio_err, "Memory allocation failure\n"); goto end; } /* take a copy of the issuer name before we mess with it. */ if (selfsign) CAname = X509_NAME_dup(name); else CAname = X509_NAME_dup(X509_get_subject_name(x509)); if (CAname == NULL) goto end; str = str2 = NULL; for (i = 0; i < sk_CONF_VALUE_num(policy); i++) { cv = sk_CONF_VALUE_value(policy, i); /* get the object id */ if ((j = OBJ_txt2nid(cv->name)) == NID_undef) { BIO_printf(bio_err, "%s:unknown object type in 'policy' configuration\n", cv->name); goto end; } obj = OBJ_nid2obj(j); last = -1; for (;;) { X509_NAME_ENTRY *push = NULL; /* lookup the object in the supplied name list */ j = X509_NAME_get_index_by_OBJ(name, obj, last); if (j < 0) { if (last != -1) break; tne = NULL; } else { tne = X509_NAME_get_entry(name, j); } last = j; /* depending on the 'policy', decide what to do. */ if (strcmp(cv->value, "optional") == 0) { if (tne != NULL) push = tne; } else if (strcmp(cv->value, "supplied") == 0) { if (tne == NULL) { BIO_printf(bio_err, "The %s field needed to be supplied and was missing\n", cv->name); goto end; } else { push = tne; } } else if (strcmp(cv->value, "match") == 0) { int last2; if (tne == NULL) { BIO_printf(bio_err, "The mandatory %s field was missing\n", cv->name); goto end; } last2 = -1; again2: j = X509_NAME_get_index_by_OBJ(CAname, obj, last2); if ((j < 0) && (last2 == -1)) { BIO_printf(bio_err, "The %s field does not exist in the CA certificate,\n" "the 'policy' is misconfigured\n", cv->name); goto end; } if (j >= 0) { push = X509_NAME_get_entry(CAname, j); str = X509_NAME_ENTRY_get_data(tne); str2 = X509_NAME_ENTRY_get_data(push); last2 = j; if (ASN1_STRING_cmp(str, str2) != 0) goto again2; } if (j < 0) { BIO_printf(bio_err, "The %s field is different between\n" "CA certificate (%s) and the request (%s)\n", cv->name, ((str2 == NULL) ? "NULL" : (char *)str2->data), ((str == NULL) ? "NULL" : (char *)str->data)); goto end; } } else { BIO_printf(bio_err, "%s:invalid type in 'policy' configuration\n", cv->value); goto end; } if (push != NULL) { if (!X509_NAME_add_entry(subject, push, -1, 0)) { BIO_printf(bio_err, "Memory allocation failure\n"); goto end; } } if (j < 0) break; } } if (preserve) { X509_NAME_free(subject); /* subject=X509_NAME_dup(X509_REQ_get_subject_name(req)); */ subject = X509_NAME_dup(name); if (subject == NULL) goto end; } /* We are now totally happy, lets make and sign the certificate */ if (verbose) BIO_printf(bio_err, "Everything appears to be ok, creating and signing the certificate\n"); if ((ret = X509_new_ex(app_get0_libctx(), app_get0_propq())) == NULL) goto end; if (BN_to_ASN1_INTEGER(serial, X509_get_serialNumber(ret)) == NULL) goto end; if (selfsign) { if (!X509_set_issuer_name(ret, subject)) goto end; } else { if (!X509_set_issuer_name(ret, X509_get_subject_name(x509))) goto end; } if (!set_cert_times(ret, startdate, enddate, days)) goto end; if (enddate != NULL) { int tdays; if (!ASN1_TIME_diff(&tdays, NULL, NULL, X509_get0_notAfter(ret))) goto end; days = tdays; } if (!X509_set_subject_name(ret, subject)) goto end; pktmp = X509_REQ_get0_pubkey(req); i = X509_set_pubkey(ret, pktmp); if (!i) goto end; /* Initialize the context structure */ X509V3_set_ctx(&ext_ctx, selfsign ? ret : x509, ret, NULL /* no need to give req, needed info is in ret */, NULL, X509V3_CTX_REPLACE); /* prepare fallback for AKID, but only if issuer cert equals subject cert */ if (selfsign) { if (!X509V3_set_issuer_pkey(&ext_ctx, pkey)) goto end; if (!cert_matches_key(ret, pkey)) BIO_printf(bio_err, "Warning: Signature key and public key of cert do not match\n"); } /* Lets add the extensions, if there are any */ if (ext_sect) { if (extfile_conf != NULL) { if (verbose) BIO_printf(bio_err, "Extra configuration file found\n"); /* Use the extfile_conf configuration db LHASH */ X509V3_set_nconf(&ext_ctx, extfile_conf); /* Adds exts contained in the configuration file */ if (!X509V3_EXT_add_nconf(extfile_conf, &ext_ctx, ext_sect, ret)) { BIO_printf(bio_err, "Error adding certificate extensions from extfile section %s\n", ext_sect); goto end; } if (verbose) BIO_printf(bio_err, "Successfully added extensions from file.\n"); } else if (ext_sect) { /* We found extensions to be set from config file */ X509V3_set_nconf(&ext_ctx, lconf); if (!X509V3_EXT_add_nconf(lconf, &ext_ctx, ext_sect, ret)) { BIO_printf(bio_err, "Error adding certificate extensions from config section %s\n", ext_sect); goto end; } if (verbose) BIO_printf(bio_err, "Successfully added extensions from config\n"); } } /* Copy extensions from request (if any) */ if (!copy_extensions(ret, req, ext_copy)) { BIO_printf(bio_err, "ERROR: adding extensions from request\n"); goto end; } if (verbose) BIO_printf(bio_err, "The subject name appears to be ok, checking database for clashes\n"); /* Build the correct Subject if no e-mail is wanted in the subject. */ if (!email_dn) { X509_NAME_ENTRY *tmpne; X509_NAME *dn_subject; /* * Its best to dup the subject DN and then delete any email addresses * because this retains its structure. */ if ((dn_subject = X509_NAME_dup(subject)) == NULL) { BIO_printf(bio_err, "Memory allocation failure\n"); goto end; } i = -1; while ((i = X509_NAME_get_index_by_NID(dn_subject, NID_pkcs9_emailAddress, i)) >= 0) { tmpne = X509_NAME_delete_entry(dn_subject, i--); X509_NAME_ENTRY_free(tmpne); } if (!X509_set_subject_name(ret, dn_subject)) { X509_NAME_free(dn_subject); goto end; } X509_NAME_free(dn_subject); } row[DB_name] = X509_NAME_oneline(X509_get_subject_name(ret), NULL, 0); if (row[DB_name] == NULL) { BIO_printf(bio_err, "Memory allocation failure\n"); goto end; } if (BN_is_zero(serial)) row[DB_serial] = OPENSSL_strdup("00"); else row[DB_serial] = BN_bn2hex(serial); if (row[DB_serial] == NULL) { BIO_printf(bio_err, "Memory allocation failure\n"); goto end; } if (row[DB_name][0] == '\0') { /* * An empty subject! We'll use the serial number instead. If * unique_subject is in use then we don't want different entries with * empty subjects matching each other. */ OPENSSL_free(row[DB_name]); row[DB_name] = OPENSSL_strdup(row[DB_serial]); if (row[DB_name] == NULL) { BIO_printf(bio_err, "Memory allocation failure\n"); goto end; } } if (db->attributes.unique_subject) { OPENSSL_STRING *crow = row; rrow = TXT_DB_get_by_index(db->db, DB_name, crow); if (rrow != NULL) { BIO_printf(bio_err, "ERROR:There is already a certificate for %s\n", row[DB_name]); } } if (rrow == NULL) { rrow = TXT_DB_get_by_index(db->db, DB_serial, row); if (rrow != NULL) { BIO_printf(bio_err, "ERROR:Serial number %s has already been issued,\n", row[DB_serial]); BIO_printf(bio_err, " check the database/serial_file for corruption\n"); } } if (rrow != NULL) { BIO_printf(bio_err, "The matching entry has the following details\n"); if (rrow[DB_type][0] == DB_TYPE_EXP) p = "Expired"; else if (rrow[DB_type][0] == DB_TYPE_REV) p = "Revoked"; else if (rrow[DB_type][0] == DB_TYPE_VAL) p = "Valid"; else p = "\ninvalid type, Database error\n"; BIO_printf(bio_err, "Type :%s\n", p); if (rrow[DB_type][0] == DB_TYPE_REV) { p = rrow[DB_exp_date]; if (p == NULL) p = "undef"; BIO_printf(bio_err, "Was revoked on:%s\n", p); } p = rrow[DB_exp_date]; if (p == NULL) p = "undef"; BIO_printf(bio_err, "Expires on :%s\n", p); p = rrow[DB_serial]; if (p == NULL) p = "undef"; BIO_printf(bio_err, "Serial Number :%s\n", p); p = rrow[DB_file]; if (p == NULL) p = "undef"; BIO_printf(bio_err, "File name :%s\n", p); p = rrow[DB_name]; if (p == NULL) p = "undef"; BIO_printf(bio_err, "Subject Name :%s\n", p); ok = -1; /* This is now a 'bad' error. */ goto end; } if (!default_op) { BIO_printf(bio_err, "Certificate Details:\n"); /* * Never print signature details because signature not present */ certopt |= X509_FLAG_NO_SIGDUMP | X509_FLAG_NO_SIGNAME; X509_print_ex(bio_err, ret, nameopt, certopt); } BIO_printf(bio_err, "Certificate is to be certified until "); ASN1_TIME_print_ex(bio_err, X509_get0_notAfter(ret), dateopt); if (days) BIO_printf(bio_err, " (%ld days)", days); BIO_printf(bio_err, "\n"); if (!batch) { BIO_printf(bio_err, "Sign the certificate? [y/n]:"); (void)BIO_flush(bio_err); buf[0] = '\0'; if (fgets(buf, sizeof(buf), stdin) == NULL) { BIO_printf(bio_err, "CERTIFICATE WILL NOT BE CERTIFIED: I/O error\n"); ok = 0; goto end; } if (!(buf[0] == 'y' || buf[0] == 'Y')) { BIO_printf(bio_err, "CERTIFICATE WILL NOT BE CERTIFIED\n"); ok = 0; goto end; } } pktmp = X509_get0_pubkey(ret); if (EVP_PKEY_missing_parameters(pktmp) && !EVP_PKEY_missing_parameters(pkey)) EVP_PKEY_copy_parameters(pktmp, pkey); if (!do_X509_sign(ret, 0, pkey, dgst, sigopts, &ext_ctx)) goto end; /* We now just add it to the database as DB_TYPE_VAL('V') */ row[DB_type] = OPENSSL_strdup("V"); tm = X509_get0_notAfter(ret); row[DB_exp_date] = app_malloc(tm->length + 1, "row expdate"); memcpy(row[DB_exp_date], tm->data, tm->length); row[DB_exp_date][tm->length] = '\0'; row[DB_rev_date] = NULL; row[DB_file] = OPENSSL_strdup("unknown"); if ((row[DB_type] == NULL) || (row[DB_file] == NULL) || (row[DB_name] == NULL)) { BIO_printf(bio_err, "Memory allocation failure\n"); goto end; } irow = app_malloc(sizeof(*irow) * (DB_NUMBER + 1), "row space"); for (i = 0; i < DB_NUMBER; i++) irow[i] = row[i]; irow[DB_NUMBER] = NULL; if (!TXT_DB_insert(db->db, irow)) { BIO_printf(bio_err, "failed to update database\n"); BIO_printf(bio_err, "TXT_DB error number %ld\n", db->db->error); goto end; } irow = NULL; ok = 1; end: if (ok != 1) { for (i = 0; i < DB_NUMBER; i++) OPENSSL_free(row[i]); } OPENSSL_free(irow); X509_NAME_free(CAname); X509_NAME_free(subject); if (ok <= 0) X509_free(ret); else *xret = ret; return ok; } static void write_new_certificate(BIO *bp, X509 *x, int output_der, int notext) { if (output_der) { (void)i2d_X509_bio(bp, x); return; } if (!notext) X509_print(bp, x); PEM_write_bio_X509(bp, x); } static int certify_spkac(X509 **xret, const char *infile, EVP_PKEY *pkey, X509 *x509, const char *dgst, STACK_OF(OPENSSL_STRING) *sigopts, STACK_OF(CONF_VALUE) *policy, CA_DB *db, BIGNUM *serial, const char *subj, unsigned long chtype, int multirdn, int email_dn, const char *startdate, const char *enddate, long days, const char *ext_sect, CONF *lconf, int verbose, unsigned long certopt, unsigned long nameopt, int default_op, int ext_copy, unsigned long dateopt) { STACK_OF(CONF_VALUE) *sk = NULL; LHASH_OF(CONF_VALUE) *parms = NULL; X509_REQ *req = NULL; CONF_VALUE *cv = NULL; NETSCAPE_SPKI *spki = NULL; char *type, *buf; EVP_PKEY *pktmp = NULL; X509_NAME *n = NULL; X509_NAME_ENTRY *ne = NULL; int ok = -1, i, j; long errline; int nid; /* * Load input file into a hash table. (This is just an easy * way to read and parse the file, then put it into a convenient * STACK format). */ parms = CONF_load(NULL, infile, &errline); if (parms == NULL) { BIO_printf(bio_err, "error on line %ld of %s\n", errline, infile); goto end; } sk = CONF_get_section(parms, "default"); if (sk_CONF_VALUE_num(sk) == 0) { BIO_printf(bio_err, "no name/value pairs found in %s\n", infile); goto end; } /* * Now create a dummy X509 request structure. We don't actually * have an X509 request, but we have many of the components * (a public key, various DN components). The idea is that we * put these components into the right X509 request structure * and we can use the same code as if you had a real X509 request. */ req = X509_REQ_new(); if (req == NULL) goto end; /* * Build up the subject name set. */ n = X509_REQ_get_subject_name(req); for (i = 0;; i++) { if (sk_CONF_VALUE_num(sk) <= i) break; cv = sk_CONF_VALUE_value(sk, i); type = cv->name; /* * Skip past any leading X. X: X, etc to allow for multiple instances */ for (buf = cv->name; *buf; buf++) if ((*buf == ':') || (*buf == ',') || (*buf == '.')) { buf++; if (*buf) type = buf; break; } buf = cv->value; if ((nid = OBJ_txt2nid(type)) == NID_undef) { if (strcmp(type, "SPKAC") == 0) { spki = NETSCAPE_SPKI_b64_decode(cv->value, -1); if (spki == NULL) { BIO_printf(bio_err, "unable to load Netscape SPKAC structure\n"); goto end; } } continue; } if (!X509_NAME_add_entry_by_NID(n, nid, chtype, (unsigned char *)buf, -1, -1, 0)) goto end; } if (spki == NULL) { BIO_printf(bio_err, "Netscape SPKAC structure not found in %s\n", infile); goto end; } /* * Now extract the key from the SPKI structure. */ BIO_printf(bio_err, "Check that the SPKAC request matches the signature\n"); if ((pktmp = NETSCAPE_SPKI_get_pubkey(spki)) == NULL) { BIO_printf(bio_err, "error unpacking SPKAC public key\n"); goto end; } j = NETSCAPE_SPKI_verify(spki, pktmp); if (j <= 0) { EVP_PKEY_free(pktmp); BIO_printf(bio_err, "signature verification failed on SPKAC public key\n"); goto end; } BIO_printf(bio_err, "Signature ok\n"); X509_REQ_set_pubkey(req, pktmp); EVP_PKEY_free(pktmp); ok = do_body(xret, pkey, x509, dgst, sigopts, policy, db, serial, subj, chtype, multirdn, email_dn, startdate, enddate, days, 1, verbose, req, ext_sect, lconf, certopt, nameopt, default_op, ext_copy, 0, dateopt); end: X509_REQ_free(req); CONF_free(parms); NETSCAPE_SPKI_free(spki); X509_NAME_ENTRY_free(ne); return ok; } static int check_time_format(const char *str) { return ASN1_TIME_set_string(NULL, str); } static int do_revoke(X509 *x509, CA_DB *db, REVINFO_TYPE rev_type, const char *value) { const ASN1_TIME *tm = NULL; char *row[DB_NUMBER], **rrow, **irow; char *rev_str = NULL; BIGNUM *bn = NULL; int ok = -1, i; for (i = 0; i < DB_NUMBER; i++) row[i] = NULL; row[DB_name] = X509_NAME_oneline(X509_get_subject_name(x509), NULL, 0); bn = ASN1_INTEGER_to_BN(X509_get0_serialNumber(x509), NULL); if (!bn) goto end; if (BN_is_zero(bn)) row[DB_serial] = OPENSSL_strdup("00"); else row[DB_serial] = BN_bn2hex(bn); BN_free(bn); if (row[DB_name] != NULL && row[DB_name][0] == '\0') { /* Entries with empty Subjects actually use the serial number instead */ OPENSSL_free(row[DB_name]); row[DB_name] = OPENSSL_strdup(row[DB_serial]); } if ((row[DB_name] == NULL) || (row[DB_serial] == NULL)) { BIO_printf(bio_err, "Memory allocation failure\n"); goto end; } /* * We have to lookup by serial number because name lookup skips revoked * certs */ rrow = TXT_DB_get_by_index(db->db, DB_serial, row); if (rrow == NULL) { BIO_printf(bio_err, "Adding Entry with serial number %s to DB for %s\n", row[DB_serial], row[DB_name]); /* We now just add it to the database as DB_TYPE_REV('V') */ row[DB_type] = OPENSSL_strdup("V"); tm = X509_get0_notAfter(x509); row[DB_exp_date] = app_malloc(tm->length + 1, "row exp_data"); memcpy(row[DB_exp_date], tm->data, tm->length); row[DB_exp_date][tm->length] = '\0'; row[DB_rev_date] = NULL; row[DB_file] = OPENSSL_strdup("unknown"); if (row[DB_type] == NULL || row[DB_file] == NULL) { BIO_printf(bio_err, "Memory allocation failure\n"); goto end; } irow = app_malloc(sizeof(*irow) * (DB_NUMBER + 1), "row ptr"); for (i = 0; i < DB_NUMBER; i++) irow[i] = row[i]; irow[DB_NUMBER] = NULL; if (!TXT_DB_insert(db->db, irow)) { BIO_printf(bio_err, "failed to update database\n"); BIO_printf(bio_err, "TXT_DB error number %ld\n", db->db->error); OPENSSL_free(irow); goto end; } for (i = 0; i < DB_NUMBER; i++) row[i] = NULL; /* Revoke Certificate */ if (rev_type == REV_VALID) ok = 1; else /* Retry revocation after DB insertion */ ok = do_revoke(x509, db, rev_type, value); goto end; } else if (index_name_cmp_noconst(row, rrow)) { BIO_printf(bio_err, "ERROR:name does not match %s\n", row[DB_name]); goto end; } else if (rev_type == REV_VALID) { BIO_printf(bio_err, "ERROR:Already present, serial number %s\n", row[DB_serial]); goto end; } else if (rrow[DB_type][0] == DB_TYPE_REV) { BIO_printf(bio_err, "ERROR:Already revoked, serial number %s\n", row[DB_serial]); goto end; } else { BIO_printf(bio_err, "Revoking Certificate %s.\n", rrow[DB_serial]); rev_str = make_revocation_str(rev_type, value); if (!rev_str) { BIO_printf(bio_err, "Error in revocation arguments\n"); goto end; } rrow[DB_type][0] = DB_TYPE_REV; rrow[DB_type][1] = '\0'; rrow[DB_rev_date] = rev_str; } ok = 1; end: for (i = 0; i < DB_NUMBER; i++) OPENSSL_free(row[i]); return ok; } static int get_certificate_status(const char *serial, CA_DB *db) { char *row[DB_NUMBER], **rrow; int ok = -1, i; size_t serial_len = strlen(serial); /* Free Resources */ for (i = 0; i < DB_NUMBER; i++) row[i] = NULL; /* Malloc needed char spaces */ row[DB_serial] = app_malloc(serial_len + 2, "row serial#"); if (serial_len % 2) { /* * Set the first char to 0 */ row[DB_serial][0] = '0'; /* Copy String from serial to row[DB_serial] */ memcpy(row[DB_serial] + 1, serial, serial_len); row[DB_serial][serial_len + 1] = '\0'; } else { /* Copy String from serial to row[DB_serial] */ memcpy(row[DB_serial], serial, serial_len); row[DB_serial][serial_len] = '\0'; } /* Make it Upper Case */ make_uppercase(row[DB_serial]); ok = 1; /* Search for the certificate */ rrow = TXT_DB_get_by_index(db->db, DB_serial, row); if (rrow == NULL) { BIO_printf(bio_err, "Serial %s not present in db.\n", row[DB_serial]); ok = -1; goto end; } else if (rrow[DB_type][0] == DB_TYPE_VAL) { BIO_printf(bio_err, "%s=Valid (%c)\n", row[DB_serial], rrow[DB_type][0]); goto end; } else if (rrow[DB_type][0] == DB_TYPE_REV) { BIO_printf(bio_err, "%s=Revoked (%c)\n", row[DB_serial], rrow[DB_type][0]); goto end; } else if (rrow[DB_type][0] == DB_TYPE_EXP) { BIO_printf(bio_err, "%s=Expired (%c)\n", row[DB_serial], rrow[DB_type][0]); goto end; } else if (rrow[DB_type][0] == DB_TYPE_SUSP) { BIO_printf(bio_err, "%s=Suspended (%c)\n", row[DB_serial], rrow[DB_type][0]); goto end; } else { BIO_printf(bio_err, "%s=Unknown (%c).\n", row[DB_serial], rrow[DB_type][0]); ok = -1; } end: for (i = 0; i < DB_NUMBER; i++) { OPENSSL_free(row[i]); } return ok; } int do_updatedb(CA_DB *db, time_t *now) { ASN1_TIME *a_tm = NULL; int i, cnt = 0; char **rrow; a_tm = ASN1_TIME_new(); if (a_tm == NULL) return -1; /* get actual time */ if (X509_time_adj(a_tm, 0, now) == NULL) { ASN1_TIME_free(a_tm); return -1; } for (i = 0; i < sk_OPENSSL_PSTRING_num(db->db->data); i++) { rrow = sk_OPENSSL_PSTRING_value(db->db->data, i); if (rrow[DB_type][0] == DB_TYPE_VAL) { /* ignore entries that are not valid */ ASN1_TIME *exp_date = NULL; exp_date = ASN1_TIME_new(); if (exp_date == NULL) { ASN1_TIME_free(a_tm); return -1; } if (!ASN1_TIME_set_string(exp_date, rrow[DB_exp_date])) { ASN1_TIME_free(a_tm); ASN1_TIME_free(exp_date); return -1; } if (ASN1_TIME_compare(exp_date, a_tm) <= 0) { rrow[DB_type][0] = DB_TYPE_EXP; rrow[DB_type][1] = '\0'; cnt++; BIO_printf(bio_err, "%s=Expired\n", rrow[DB_serial]); } ASN1_TIME_free(exp_date); } } ASN1_TIME_free(a_tm); return cnt; } static const char *crl_reasons[] = { /* CRL reason strings */ "unspecified", "keyCompromise", "CACompromise", "affiliationChanged", "superseded", "cessationOfOperation", "certificateHold", "removeFromCRL", /* Additional pseudo reasons */ "holdInstruction", "keyTime", "CAkeyTime" }; #define NUM_REASONS OSSL_NELEM(crl_reasons) /* * Given revocation information convert to a DB string. The format of the * string is: revtime[,reason,extra]. Where 'revtime' is the revocation time * (the current time). 'reason' is the optional CRL reason and 'extra' is any * additional argument */ static char *make_revocation_str(REVINFO_TYPE rev_type, const char *rev_arg) { char *str; const char *reason = NULL, *other = NULL; ASN1_OBJECT *otmp; ASN1_UTCTIME *revtm = NULL; int i; switch (rev_type) { case REV_NONE: case REV_VALID: break; case REV_CRL_REASON: for (i = 0; i < 8; i++) { if (OPENSSL_strcasecmp(rev_arg, crl_reasons[i]) == 0) { reason = crl_reasons[i]; break; } } if (reason == NULL) { BIO_printf(bio_err, "Unknown CRL reason %s\n", rev_arg); return NULL; } break; case REV_HOLD: /* Argument is an OID */ otmp = OBJ_txt2obj(rev_arg, 0); ASN1_OBJECT_free(otmp); if (otmp == NULL) { BIO_printf(bio_err, "Invalid object identifier %s\n", rev_arg); return NULL; } reason = "holdInstruction"; other = rev_arg; break; case REV_KEY_COMPROMISE: case REV_CA_COMPROMISE: /* Argument is the key compromise time */ if (!ASN1_GENERALIZEDTIME_set_string(NULL, rev_arg)) { BIO_printf(bio_err, "Invalid time format %s. Need YYYYMMDDHHMMSSZ\n", rev_arg); return NULL; } other = rev_arg; if (rev_type == REV_KEY_COMPROMISE) reason = "keyTime"; else reason = "CAkeyTime"; break; } revtm = X509_gmtime_adj(NULL, 0); if (!revtm) return NULL; i = revtm->length + 1; if (reason) i += strlen(reason) + 1; if (other) i += strlen(other) + 1; str = app_malloc(i, "revocation reason"); OPENSSL_strlcpy(str, (char *)revtm->data, i); if (reason) { OPENSSL_strlcat(str, ",", i); OPENSSL_strlcat(str, reason, i); } if (other) { OPENSSL_strlcat(str, ",", i); OPENSSL_strlcat(str, other, i); } ASN1_UTCTIME_free(revtm); return str; } /*- * Convert revocation field to X509_REVOKED entry * return code: * 0 error * 1 OK * 2 OK and some extensions added (i.e. V2 CRL) */ static int make_revoked(X509_REVOKED *rev, const char *str) { char *tmp = NULL; int reason_code = -1; int i, ret = 0; ASN1_OBJECT *hold = NULL; ASN1_GENERALIZEDTIME *comp_time = NULL; ASN1_ENUMERATED *rtmp = NULL; ASN1_TIME *revDate = NULL; i = unpack_revinfo(&revDate, &reason_code, &hold, &comp_time, str); if (i == 0) goto end; if (rev && !X509_REVOKED_set_revocationDate(rev, revDate)) goto end; if (rev && (reason_code != OCSP_REVOKED_STATUS_NOSTATUS)) { rtmp = ASN1_ENUMERATED_new(); if (rtmp == NULL || !ASN1_ENUMERATED_set(rtmp, reason_code)) goto end; if (X509_REVOKED_add1_ext_i2d(rev, NID_crl_reason, rtmp, 0, 0) <= 0) goto end; } if (rev && comp_time) { if (X509_REVOKED_add1_ext_i2d (rev, NID_invalidity_date, comp_time, 0, 0) <= 0) goto end; } if (rev && hold) { if (X509_REVOKED_add1_ext_i2d (rev, NID_hold_instruction_code, hold, 0, 0) <= 0) goto end; } if (reason_code != OCSP_REVOKED_STATUS_NOSTATUS) ret = 2; else ret = 1; end: OPENSSL_free(tmp); ASN1_OBJECT_free(hold); ASN1_GENERALIZEDTIME_free(comp_time); ASN1_ENUMERATED_free(rtmp); ASN1_TIME_free(revDate); return ret; } static int old_entry_print(const ASN1_OBJECT *obj, const ASN1_STRING *str) { char buf[25], *pbuf; const char *p; int j; j = i2a_ASN1_OBJECT(bio_err, obj); pbuf = buf; for (j = 22 - j; j > 0; j--) *(pbuf++) = ' '; *(pbuf++) = ':'; *(pbuf++) = '\0'; BIO_puts(bio_err, buf); if (str->type == V_ASN1_PRINTABLESTRING) BIO_printf(bio_err, "PRINTABLE:'"); else if (str->type == V_ASN1_T61STRING) BIO_printf(bio_err, "T61STRING:'"); else if (str->type == V_ASN1_IA5STRING) BIO_printf(bio_err, "IA5STRING:'"); else if (str->type == V_ASN1_UNIVERSALSTRING) BIO_printf(bio_err, "UNIVERSALSTRING:'"); else BIO_printf(bio_err, "ASN.1 %2d:'", str->type); p = (const char *)str->data; for (j = str->length; j > 0; j--) { if ((*p >= ' ') && (*p <= '~')) BIO_printf(bio_err, "%c", *p); else if (*p & 0x80) BIO_printf(bio_err, "\\0x%02X", *p); else if ((unsigned char)*p == 0xf7) BIO_printf(bio_err, "^?"); else BIO_printf(bio_err, "^%c", *p + '@'); p++; } BIO_printf(bio_err, "'\n"); return 1; } int unpack_revinfo(ASN1_TIME **prevtm, int *preason, ASN1_OBJECT **phold, ASN1_GENERALIZEDTIME **pinvtm, const char *str) { char *tmp; char *rtime_str, *reason_str = NULL, *arg_str = NULL, *p; int reason_code = -1; int ret = 0; unsigned int i; ASN1_OBJECT *hold = NULL; ASN1_GENERALIZEDTIME *comp_time = NULL; tmp = OPENSSL_strdup(str); if (!tmp) { BIO_printf(bio_err, "memory allocation failure\n"); goto end; } p = strchr(tmp, ','); rtime_str = tmp; if (p) { *p = '\0'; p++; reason_str = p; p = strchr(p, ','); if (p) { *p = '\0'; arg_str = p + 1; } } if (prevtm) { *prevtm = ASN1_UTCTIME_new(); if (*prevtm == NULL) { BIO_printf(bio_err, "memory allocation failure\n"); goto end; } if (!ASN1_UTCTIME_set_string(*prevtm, rtime_str)) { BIO_printf(bio_err, "invalid revocation date %s\n", rtime_str); goto end; } } if (reason_str) { for (i = 0; i < NUM_REASONS; i++) { if (OPENSSL_strcasecmp(reason_str, crl_reasons[i]) == 0) { reason_code = i; break; } } if (reason_code == OCSP_REVOKED_STATUS_NOSTATUS) { BIO_printf(bio_err, "invalid reason code %s\n", reason_str); goto end; } if (reason_code == 7) { reason_code = OCSP_REVOKED_STATUS_REMOVEFROMCRL; } else if (reason_code == 8) { /* Hold instruction */ if (!arg_str) { BIO_printf(bio_err, "missing hold instruction\n"); goto end; } reason_code = OCSP_REVOKED_STATUS_CERTIFICATEHOLD; hold = OBJ_txt2obj(arg_str, 0); if (!hold) { BIO_printf(bio_err, "invalid object identifier %s\n", arg_str); goto end; } if (phold) *phold = hold; else ASN1_OBJECT_free(hold); } else if ((reason_code == 9) || (reason_code == 10)) { if (!arg_str) { BIO_printf(bio_err, "missing compromised time\n"); goto end; } comp_time = ASN1_GENERALIZEDTIME_new(); if (comp_time == NULL) { BIO_printf(bio_err, "memory allocation failure\n"); goto end; } if (!ASN1_GENERALIZEDTIME_set_string(comp_time, arg_str)) { BIO_printf(bio_err, "invalid compromised time %s\n", arg_str); goto end; } if (reason_code == 9) reason_code = OCSP_REVOKED_STATUS_KEYCOMPROMISE; else reason_code = OCSP_REVOKED_STATUS_CACOMPROMISE; } } if (preason) *preason = reason_code; if (pinvtm) { *pinvtm = comp_time; comp_time = NULL; } ret = 1; end: OPENSSL_free(tmp); ASN1_GENERALIZEDTIME_free(comp_time); return ret; }
./openssl/apps/timeouts.h
/* * Copyright 1999-2016 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #ifndef OSSL_APPS_TIMEOUTS_H # define OSSL_APPS_TIMEOUTS_H /* numbers in us */ # define DGRAM_RCV_TIMEOUT 250000 # define DGRAM_SND_TIMEOUT 250000 #endif /* ! OSSL_APPS_TIMEOUTS_H */
./openssl/apps/pkcs12.c
/* * Copyright 1999-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/opensslconf.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include "apps.h" #include "progs.h" #include <openssl/asn1.h> #include <openssl/crypto.h> #include <openssl/err.h> #include <openssl/pem.h> #include <openssl/pkcs12.h> #include <openssl/provider.h> #include <openssl/kdf.h> #include <openssl/rand.h> #define NOKEYS 0x1 #define NOCERTS 0x2 #define INFO 0x4 #define CLCERTS 0x8 #define CACERTS 0x10 #define PASSWD_BUF_SIZE 2048 #define WARN_EXPORT(opt) \ BIO_printf(bio_err, "Warning: -%s option ignored with -export\n", opt); #define WARN_NO_EXPORT(opt) \ BIO_printf(bio_err, "Warning: -%s option ignored without -export\n", opt); static int get_cert_chain(X509 *cert, X509_STORE *store, STACK_OF(X509) *untrusted_certs, STACK_OF(X509) **chain); int dump_certs_keys_p12(BIO *out, const PKCS12 *p12, const char *pass, int passlen, int options, char *pempass, const EVP_CIPHER *enc); int dump_certs_pkeys_bags(BIO *out, const STACK_OF(PKCS12_SAFEBAG) *bags, const char *pass, int passlen, int options, char *pempass, const EVP_CIPHER *enc); int dump_certs_pkeys_bag(BIO *out, const PKCS12_SAFEBAG *bags, const char *pass, int passlen, int options, char *pempass, const EVP_CIPHER *enc); void print_attribute(BIO *out, const ASN1_TYPE *av); int print_attribs(BIO *out, const STACK_OF(X509_ATTRIBUTE) *attrlst, const char *name); void hex_prin(BIO *out, unsigned char *buf, int len); static int alg_print(const X509_ALGOR *alg); int cert_load(BIO *in, STACK_OF(X509) *sk); static int set_pbe(int *ppbe, const char *str); static int jdk_trust(PKCS12_SAFEBAG *bag, void *cbarg); typedef enum OPTION_choice { OPT_COMMON, OPT_CIPHER, OPT_NOKEYS, OPT_KEYEX, OPT_KEYSIG, OPT_NOCERTS, OPT_CLCERTS, OPT_CACERTS, OPT_NOOUT, OPT_INFO, OPT_CHAIN, OPT_TWOPASS, OPT_NOMACVER, #ifndef OPENSSL_NO_DES OPT_DESCERT, #endif OPT_EXPORT, OPT_ITER, OPT_NOITER, OPT_MACITER, OPT_NOMACITER, OPT_MACSALTLEN, OPT_NOMAC, OPT_LMK, OPT_NODES, OPT_NOENC, OPT_MACALG, OPT_CERTPBE, OPT_KEYPBE, OPT_INKEY, OPT_CERTFILE, OPT_UNTRUSTED, OPT_PASSCERTS, OPT_NAME, OPT_CSP, OPT_CANAME, OPT_IN, OPT_OUT, OPT_PASSIN, OPT_PASSOUT, OPT_PASSWORD, OPT_CAPATH, OPT_CAFILE, OPT_CASTORE, OPT_NOCAPATH, OPT_NOCAFILE, OPT_NOCASTORE, OPT_ENGINE, OPT_R_ENUM, OPT_PROV_ENUM, OPT_JDKTRUST, #ifndef OPENSSL_NO_DES OPT_LEGACY_ALG #endif } OPTION_CHOICE; const OPTIONS pkcs12_options[] = { OPT_SECTION("General"), {"help", OPT_HELP, '-', "Display this summary"}, {"in", OPT_IN, '<', "Input file"}, {"out", OPT_OUT, '>', "Output file"}, {"passin", OPT_PASSIN, 's', "Input file pass phrase source"}, {"passout", OPT_PASSOUT, 's', "Output file pass phrase source"}, {"password", OPT_PASSWORD, 's', "Set PKCS#12 import/export password source"}, {"twopass", OPT_TWOPASS, '-', "Separate MAC, encryption passwords"}, {"nokeys", OPT_NOKEYS, '-', "Don't output private keys"}, {"nocerts", OPT_NOCERTS, '-', "Don't output certificates"}, {"noout", OPT_NOOUT, '-', "Don't output anything, just verify PKCS#12 input"}, #ifndef OPENSSL_NO_DES {"legacy", OPT_LEGACY_ALG, '-', # ifdef OPENSSL_NO_RC2 "Use legacy encryption algorithm 3DES_CBC for keys and certs" # else "Use legacy encryption: 3DES_CBC for keys, RC2_CBC for certs" # endif }, #endif #ifndef OPENSSL_NO_ENGINE {"engine", OPT_ENGINE, 's', "Use engine, possibly a hardware device"}, #endif OPT_PROV_OPTIONS, OPT_R_OPTIONS, OPT_SECTION("PKCS#12 import (parsing PKCS#12)"), {"info", OPT_INFO, '-', "Print info about PKCS#12 structure"}, {"nomacver", OPT_NOMACVER, '-', "Don't verify integrity MAC"}, {"clcerts", OPT_CLCERTS, '-', "Only output client certificates"}, {"cacerts", OPT_CACERTS, '-', "Only output CA certificates"}, {"", OPT_CIPHER, '-', "Any supported cipher for output encryption"}, {"noenc", OPT_NOENC, '-', "Don't encrypt private keys"}, {"nodes", OPT_NODES, '-', "Don't encrypt private keys; deprecated"}, OPT_SECTION("PKCS#12 output (export)"), {"export", OPT_EXPORT, '-', "Create PKCS12 file"}, {"inkey", OPT_INKEY, 's', "Private key, else read from -in input file"}, {"certfile", OPT_CERTFILE, '<', "Extra certificates for PKCS12 output"}, {"passcerts", OPT_PASSCERTS, 's', "Certificate file pass phrase source"}, {"chain", OPT_CHAIN, '-', "Build and add certificate chain for EE cert,"}, {OPT_MORE_STR, 0, 0, "which is the 1st cert from -in matching the private key (if given)"}, {"untrusted", OPT_UNTRUSTED, '<', "Untrusted certificates for chain building"}, {"CAfile", OPT_CAFILE, '<', "PEM-format file of CA's"}, {"CApath", OPT_CAPATH, '/', "PEM-format directory of CA's"}, {"CAstore", OPT_CASTORE, ':', "URI to store of CA's"}, {"no-CAfile", OPT_NOCAFILE, '-', "Do not load the default certificates file"}, {"no-CApath", OPT_NOCAPATH, '-', "Do not load certificates from the default certificates directory"}, {"no-CAstore", OPT_NOCASTORE, '-', "Do not load certificates from the default certificates store"}, {"name", OPT_NAME, 's', "Use name as friendly name"}, {"caname", OPT_CANAME, 's', "Use name as CA friendly name (can be repeated)"}, {"CSP", OPT_CSP, 's', "Microsoft CSP name"}, {"LMK", OPT_LMK, '-', "Add local machine keyset attribute to private key"}, {"keyex", OPT_KEYEX, '-', "Set key type to MS key exchange"}, {"keysig", OPT_KEYSIG, '-', "Set key type to MS key signature"}, {"keypbe", OPT_KEYPBE, 's', "Private key PBE algorithm (default AES-256 CBC)"}, {"certpbe", OPT_CERTPBE, 's', "Certificate PBE algorithm (default PBES2 with PBKDF2 and AES-256 CBC)"}, #ifndef OPENSSL_NO_DES {"descert", OPT_DESCERT, '-', "Encrypt output with 3DES (default PBES2 with PBKDF2 and AES-256 CBC)"}, #endif {"macalg", OPT_MACALG, 's', "Digest algorithm to use in MAC (default SHA256)"}, {"iter", OPT_ITER, 'p', "Specify the iteration count for encryption and MAC"}, {"noiter", OPT_NOITER, '-', "Don't use encryption iteration"}, {"nomaciter", OPT_NOMACITER, '-', "Don't use MAC iteration)"}, {"maciter", OPT_MACITER, '-', "Unused, kept for backwards compatibility"}, {"macsaltlen", OPT_MACSALTLEN, 'p', "Specify the salt len for MAC"}, {"nomac", OPT_NOMAC, '-', "Don't generate MAC"}, {"jdktrust", OPT_JDKTRUST, 's', "Mark certificate in PKCS#12 store as trusted for JDK compatibility"}, {NULL} }; int pkcs12_main(int argc, char **argv) { char *infile = NULL, *outfile = NULL, *keyname = NULL, *certfile = NULL; char *untrusted = NULL, *ciphername = NULL, *enc_name = NULL; char *passcertsarg = NULL, *passcerts = NULL; char *name = NULL, *csp_name = NULL; char pass[PASSWD_BUF_SIZE] = "", macpass[PASSWD_BUF_SIZE] = ""; int export_pkcs12 = 0, options = 0, chain = 0, twopass = 0, keytype = 0; char *jdktrust = NULL; #ifndef OPENSSL_NO_DES int use_legacy = 0; #endif /* use library defaults for the iter, maciter, cert, and key PBE */ int iter = 0, maciter = 0; int macsaltlen = PKCS12_SALT_LEN; int cert_pbe = NID_undef; int key_pbe = NID_undef; int ret = 1, macver = 1, add_lmk = 0, private = 0; int noprompt = 0; char *passinarg = NULL, *passoutarg = NULL, *passarg = NULL; char *passin = NULL, *passout = NULL, *macalg = NULL; char *cpass = NULL, *mpass = NULL, *badpass = NULL; const char *CApath = NULL, *CAfile = NULL, *CAstore = NULL, *prog; int noCApath = 0, noCAfile = 0, noCAstore = 0; ENGINE *e = NULL; BIO *in = NULL, *out = NULL; PKCS12 *p12 = NULL; STACK_OF(OPENSSL_STRING) *canames = NULL; EVP_CIPHER *default_enc = (EVP_CIPHER *)EVP_aes_256_cbc(); EVP_CIPHER *enc = (EVP_CIPHER *)default_enc; OPTION_CHOICE o; opt_set_unknown_name("cipher"); prog = opt_init(argc, argv, pkcs12_options); while ((o = opt_next()) != OPT_EOF) { switch (o) { case OPT_EOF: case OPT_ERR: opthelp: BIO_printf(bio_err, "%s: Use -help for summary.\n", prog); goto end; case OPT_HELP: opt_help(pkcs12_options); ret = 0; goto end; case OPT_NOKEYS: options |= NOKEYS; break; case OPT_KEYEX: keytype = KEY_EX; break; case OPT_KEYSIG: keytype = KEY_SIG; break; case OPT_NOCERTS: options |= NOCERTS; break; case OPT_CLCERTS: options |= CLCERTS; break; case OPT_CACERTS: options |= CACERTS; break; case OPT_NOOUT: options |= (NOKEYS | NOCERTS); break; case OPT_JDKTRUST: jdktrust = opt_arg(); /* Adding jdk trust implies nokeys */ options |= NOKEYS; break; case OPT_INFO: options |= INFO; break; case OPT_CHAIN: chain = 1; break; case OPT_TWOPASS: twopass = 1; break; case OPT_NOMACVER: macver = 0; break; #ifndef OPENSSL_NO_DES case OPT_DESCERT: cert_pbe = NID_pbe_WithSHA1And3_Key_TripleDES_CBC; break; #endif case OPT_EXPORT: export_pkcs12 = 1; break; case OPT_NODES: case OPT_NOENC: /* * |enc_name| stores the name of the option used so it * can be printed if an error message is output. */ enc_name = opt_flag() + 1; enc = NULL; ciphername = NULL; break; case OPT_CIPHER: enc_name = ciphername = opt_unknown(); break; case OPT_ITER: maciter = iter = opt_int_arg(); break; case OPT_NOITER: iter = 1; break; case OPT_MACITER: /* no-op */ break; case OPT_NOMACITER: maciter = 1; break; case OPT_MACSALTLEN: macsaltlen = opt_int_arg(); break; case OPT_NOMAC: cert_pbe = -1; maciter = -1; break; case OPT_MACALG: macalg = opt_arg(); break; case OPT_CERTPBE: if (!set_pbe(&cert_pbe, opt_arg())) goto opthelp; break; case OPT_KEYPBE: if (!set_pbe(&key_pbe, opt_arg())) goto opthelp; break; case OPT_R_CASES: if (!opt_rand(o)) goto end; break; case OPT_INKEY: keyname = opt_arg(); break; case OPT_CERTFILE: certfile = opt_arg(); break; case OPT_UNTRUSTED: untrusted = opt_arg(); break; case OPT_PASSCERTS: passcertsarg = opt_arg(); break; case OPT_NAME: name = opt_arg(); break; case OPT_LMK: add_lmk = 1; break; case OPT_CSP: csp_name = opt_arg(); break; case OPT_CANAME: if (canames == NULL && (canames = sk_OPENSSL_STRING_new_null()) == NULL) goto end; sk_OPENSSL_STRING_push(canames, opt_arg()); break; case OPT_IN: infile = opt_arg(); break; case OPT_OUT: outfile = opt_arg(); break; case OPT_PASSIN: passinarg = opt_arg(); break; case OPT_PASSOUT: passoutarg = opt_arg(); break; case OPT_PASSWORD: passarg = opt_arg(); break; case OPT_CAPATH: CApath = opt_arg(); break; case OPT_CASTORE: CAstore = opt_arg(); break; case OPT_CAFILE: CAfile = opt_arg(); break; case OPT_NOCAPATH: noCApath = 1; break; case OPT_NOCASTORE: noCAstore = 1; break; case OPT_NOCAFILE: noCAfile = 1; break; case OPT_ENGINE: e = setup_engine(opt_arg(), 0); break; #ifndef OPENSSL_NO_DES case OPT_LEGACY_ALG: use_legacy = 1; break; #endif case OPT_PROV_CASES: if (!opt_provider(o)) goto end; break; } } /* No extra arguments. */ if (!opt_check_rest_arg(NULL)) goto opthelp; if (!app_RAND_load()) goto end; if (!opt_cipher_any(ciphername, &enc)) goto opthelp; if (export_pkcs12) { if ((options & INFO) != 0) WARN_EXPORT("info"); if (macver == 0) WARN_EXPORT("nomacver"); if ((options & CLCERTS) != 0) WARN_EXPORT("clcerts"); if ((options & CACERTS) != 0) WARN_EXPORT("cacerts"); if (enc != default_enc) BIO_printf(bio_err, "Warning: output encryption option -%s ignored with -export\n", enc_name); } else { if (keyname != NULL) WARN_NO_EXPORT("inkey"); if (certfile != NULL) WARN_NO_EXPORT("certfile"); if (passcertsarg != NULL) WARN_NO_EXPORT("passcerts"); if (chain) WARN_NO_EXPORT("chain"); if (untrusted != NULL) WARN_NO_EXPORT("untrusted"); if (CAfile != NULL) WARN_NO_EXPORT("CAfile"); if (CApath != NULL) WARN_NO_EXPORT("CApath"); if (CAstore != NULL) WARN_NO_EXPORT("CAstore"); if (noCAfile) WARN_NO_EXPORT("no-CAfile"); if (noCApath) WARN_NO_EXPORT("no-CApath"); if (noCAstore) WARN_NO_EXPORT("no-CAstore"); if (name != NULL) WARN_NO_EXPORT("name"); if (canames != NULL) WARN_NO_EXPORT("caname"); if (csp_name != NULL) WARN_NO_EXPORT("CSP"); if (add_lmk) WARN_NO_EXPORT("LMK"); if (keytype == KEY_EX) WARN_NO_EXPORT("keyex"); if (keytype == KEY_SIG) WARN_NO_EXPORT("keysig"); if (key_pbe != NID_undef) WARN_NO_EXPORT("keypbe"); if (cert_pbe != NID_undef && cert_pbe != -1) WARN_NO_EXPORT("certpbe and -descert"); if (macalg != NULL) WARN_NO_EXPORT("macalg"); if (iter != 0) WARN_NO_EXPORT("iter and -noiter"); if (maciter == 1) WARN_NO_EXPORT("nomaciter"); if (cert_pbe == -1 && maciter == -1) WARN_NO_EXPORT("nomac"); if (macsaltlen != PKCS12_SALT_LEN) WARN_NO_EXPORT("macsaltlen"); } #ifndef OPENSSL_NO_DES if (use_legacy) { /* load the legacy provider if not loaded already*/ if (!OSSL_PROVIDER_available(app_get0_libctx(), "legacy")) { if (!app_provider_load(app_get0_libctx(), "legacy")) goto end; /* load the default provider explicitly */ if (!app_provider_load(app_get0_libctx(), "default")) goto end; } if (cert_pbe == NID_undef) { /* Adapt default algorithm */ # ifndef OPENSSL_NO_RC2 cert_pbe = NID_pbe_WithSHA1And40BitRC2_CBC; # else cert_pbe = NID_pbe_WithSHA1And3_Key_TripleDES_CBC; # endif } if (key_pbe == NID_undef) key_pbe = NID_pbe_WithSHA1And3_Key_TripleDES_CBC; if (enc == default_enc) enc = (EVP_CIPHER *)EVP_des_ede3_cbc(); if (macalg == NULL) macalg = "sha1"; } #endif private = 1; if (!app_passwd(passcertsarg, NULL, &passcerts, NULL)) { BIO_printf(bio_err, "Error getting certificate file password\n"); goto end; } if (passarg != NULL) { if (export_pkcs12) passoutarg = passarg; else passinarg = passarg; } if (!app_passwd(passinarg, passoutarg, &passin, &passout)) { BIO_printf(bio_err, "Error getting passwords\n"); goto end; } if (cpass == NULL) { if (export_pkcs12) cpass = passout; else cpass = passin; } if (cpass != NULL) { mpass = cpass; noprompt = 1; if (twopass) { if (export_pkcs12) BIO_printf(bio_err, "Option -twopass cannot be used with -passout or -password\n"); else BIO_printf(bio_err, "Option -twopass cannot be used with -passin or -password\n"); goto end; } } else { cpass = pass; mpass = macpass; } if (twopass) { /* To avoid bit rot */ if (1) { #ifndef OPENSSL_NO_UI_CONSOLE if (EVP_read_pw_string( macpass, sizeof(macpass), "Enter MAC Password:", export_pkcs12)) { BIO_printf(bio_err, "Can't read Password\n"); goto end; } } else { #endif BIO_printf(bio_err, "Unsupported option -twopass\n"); goto end; } } if (export_pkcs12) { EVP_PKEY *key = NULL; X509 *ee_cert = NULL, *x = NULL; STACK_OF(X509) *certs = NULL; STACK_OF(X509) *untrusted_certs = NULL; EVP_MD *macmd = NULL; unsigned char *catmp = NULL; int i; ASN1_OBJECT *obj = NULL; if ((options & (NOCERTS | NOKEYS)) == (NOCERTS | NOKEYS)) { BIO_printf(bio_err, "Nothing to export due to -noout or -nocerts and -nokeys\n"); goto export_end; } if ((options & NOCERTS) != 0) { chain = 0; BIO_printf(bio_err, "Warning: -chain option ignored with -nocerts\n"); } if (!(options & NOKEYS)) { key = load_key(keyname ? keyname : infile, FORMAT_PEM, 1, passin, e, keyname ? "private key from -inkey file" : "private key from -in file"); if (key == NULL) goto export_end; } /* Load all certs in input file */ if (!(options & NOCERTS)) { if (!load_certs(infile, 1, &certs, passin, "certificates from -in file")) goto export_end; if (sk_X509_num(certs) < 1) { BIO_printf(bio_err, "No certificate in -in file %s\n", infile); goto export_end; } if (key != NULL) { /* Look for matching private key */ for (i = 0; i < sk_X509_num(certs); i++) { x = sk_X509_value(certs, i); if (cert_matches_key(x, key)) { ee_cert = x; /* Zero keyid and alias */ X509_keyid_set1(ee_cert, NULL, 0); X509_alias_set1(ee_cert, NULL, 0); /* Remove from list */ (void)sk_X509_delete(certs, i); break; } } if (ee_cert == NULL) { BIO_printf(bio_err, "No cert in -in file '%s' matches private key\n", infile); goto export_end; } } } /* Load any untrusted certificates for chain building */ if (untrusted != NULL) { if (!load_certs(untrusted, 0, &untrusted_certs, passcerts, "untrusted certificates")) goto export_end; } /* If chaining get chain from end entity cert */ if (chain) { int vret; STACK_OF(X509) *chain2; X509_STORE *store; X509 *ee_cert_tmp = ee_cert; /* Assume the first cert if we haven't got anything else */ if (ee_cert_tmp == NULL && certs != NULL) ee_cert_tmp = sk_X509_value(certs, 0); if (ee_cert_tmp == NULL) { BIO_printf(bio_err, "No end entity certificate to check with -chain\n"); goto export_end; } if ((store = setup_verify(CAfile, noCAfile, CApath, noCApath, CAstore, noCAstore)) == NULL) goto export_end; vret = get_cert_chain(ee_cert_tmp, store, untrusted_certs, &chain2); X509_STORE_free(store); if (vret == X509_V_OK) { int add_certs; /* Remove from chain2 the first (end entity) certificate */ X509_free(sk_X509_shift(chain2)); /* Add the remaining certs (except for duplicates) */ add_certs = X509_add_certs(certs, chain2, X509_ADD_FLAG_UP_REF | X509_ADD_FLAG_NO_DUP); OSSL_STACK_OF_X509_free(chain2); if (!add_certs) goto export_end; } else { if (vret != X509_V_ERR_UNSPECIFIED) BIO_printf(bio_err, "Error getting chain: %s\n", X509_verify_cert_error_string(vret)); goto export_end; } } /* Add any extra certificates asked for */ if (certfile != NULL) { if (!load_certs(certfile, 0, &certs, passcerts, "extra certificates from -certfile")) goto export_end; } /* Add any CA names */ for (i = 0; i < sk_OPENSSL_STRING_num(canames); i++) { catmp = (unsigned char *)sk_OPENSSL_STRING_value(canames, i); X509_alias_set1(sk_X509_value(certs, i), catmp, -1); } if (csp_name != NULL && key != NULL) EVP_PKEY_add1_attr_by_NID(key, NID_ms_csp_name, MBSTRING_ASC, (unsigned char *)csp_name, -1); if (add_lmk && key != NULL) EVP_PKEY_add1_attr_by_NID(key, NID_LocalKeySet, 0, NULL, -1); if (!noprompt && !(enc == NULL && maciter == -1)) { /* To avoid bit rot */ if (1) { #ifndef OPENSSL_NO_UI_CONSOLE if (EVP_read_pw_string(pass, sizeof(pass), "Enter Export Password:", 1)) { BIO_printf(bio_err, "Can't read Password\n"); goto export_end; } } else { #endif BIO_printf(bio_err, "Password required\n"); goto export_end; } } if (!twopass) OPENSSL_strlcpy(macpass, pass, sizeof(macpass)); if (jdktrust != NULL) { obj = OBJ_txt2obj(jdktrust, 0); } p12 = PKCS12_create_ex2(cpass, name, key, ee_cert, certs, key_pbe, cert_pbe, iter, -1, keytype, app_get0_libctx(), app_get0_propq(), jdk_trust, (void*)obj); if (p12 == NULL) { BIO_printf(bio_err, "Error creating PKCS12 structure for %s\n", outfile); goto export_end; } if (macalg != NULL) { if (!opt_md(macalg, &macmd)) goto opthelp; } if (maciter != -1) { if (!PKCS12_set_mac(p12, mpass, -1, NULL, macsaltlen, maciter, macmd)) { BIO_printf(bio_err, "Error creating PKCS12 MAC; no PKCS12KDF support?\n"); BIO_printf(bio_err, "Use -nomac if MAC not required and PKCS12KDF support not available.\n"); goto export_end; } } assert(private); out = bio_open_owner(outfile, FORMAT_PKCS12, private); if (out == NULL) goto end; i2d_PKCS12_bio(out, p12); ret = 0; export_end: EVP_PKEY_free(key); EVP_MD_free(macmd); OSSL_STACK_OF_X509_free(certs); OSSL_STACK_OF_X509_free(untrusted_certs); X509_free(ee_cert); ASN1_OBJECT_free(obj); ERR_print_errors(bio_err); goto end; } in = bio_open_default(infile, 'r', FORMAT_PKCS12); if (in == NULL) goto end; out = bio_open_owner(outfile, FORMAT_PEM, private); if (out == NULL) goto end; p12 = PKCS12_init_ex(NID_pkcs7_data, app_get0_libctx(), app_get0_propq()); if (p12 == NULL) { ERR_print_errors(bio_err); goto end; } if ((p12 = d2i_PKCS12_bio(in, &p12)) == NULL) { ERR_print_errors(bio_err); goto end; } if (!noprompt) { if (1) { #ifndef OPENSSL_NO_UI_CONSOLE if (EVP_read_pw_string(pass, sizeof(pass), "Enter Import Password:", 0)) { BIO_printf(bio_err, "Can't read Password\n"); goto end; } } else { #endif BIO_printf(bio_err, "Password required\n"); goto end; } } if (!twopass) OPENSSL_strlcpy(macpass, pass, sizeof(macpass)); if ((options & INFO) && PKCS12_mac_present(p12)) { const ASN1_INTEGER *tmaciter; const X509_ALGOR *macalgid; const ASN1_OBJECT *macobj; const ASN1_OCTET_STRING *tmac; const ASN1_OCTET_STRING *tsalt; PKCS12_get0_mac(&tmac, &macalgid, &tsalt, &tmaciter, p12); /* current hash algorithms do not use parameters so extract just name, in future alg_print() may be needed */ X509_ALGOR_get0(&macobj, NULL, NULL, macalgid); BIO_puts(bio_err, "MAC: "); i2a_ASN1_OBJECT(bio_err, macobj); BIO_printf(bio_err, ", Iteration %ld\n", tmaciter != NULL ? ASN1_INTEGER_get(tmaciter) : 1L); BIO_printf(bio_err, "MAC length: %ld, salt length: %ld\n", tmac != NULL ? ASN1_STRING_length(tmac) : 0L, tsalt != NULL ? ASN1_STRING_length(tsalt) : 0L); } if (macver) { EVP_KDF *pkcs12kdf; pkcs12kdf = EVP_KDF_fetch(app_get0_libctx(), "PKCS12KDF", app_get0_propq()); if (pkcs12kdf == NULL) { BIO_printf(bio_err, "Error verifying PKCS12 MAC; no PKCS12KDF support.\n"); BIO_printf(bio_err, "Use -nomacver if MAC verification is not required.\n"); goto end; } EVP_KDF_free(pkcs12kdf); /* If we enter empty password try no password first */ if (!mpass[0] && PKCS12_verify_mac(p12, NULL, 0)) { /* If mac and crypto pass the same set it to NULL too */ if (!twopass) cpass = NULL; } else if (!PKCS12_verify_mac(p12, mpass, -1)) { /* * May be UTF8 from previous version of OpenSSL: * convert to a UTF8 form which will translate * to the same Unicode password. */ unsigned char *utmp; int utmplen; unsigned long err = ERR_peek_error(); if (ERR_GET_LIB(err) == ERR_LIB_PKCS12 && ERR_GET_REASON(err) == PKCS12_R_MAC_ABSENT) { BIO_printf(bio_err, "Warning: MAC is absent!\n"); goto dump; } utmp = OPENSSL_asc2uni(mpass, -1, NULL, &utmplen); if (utmp == NULL) goto end; badpass = OPENSSL_uni2utf8(utmp, utmplen); OPENSSL_free(utmp); if (!PKCS12_verify_mac(p12, badpass, -1)) { BIO_printf(bio_err, "Mac verify error: invalid password?\n"); ERR_print_errors(bio_err); goto end; } else { BIO_printf(bio_err, "Warning: using broken algorithm\n"); if (!twopass) cpass = badpass; } } } dump: assert(private); if (!dump_certs_keys_p12(out, p12, cpass, -1, options, passout, enc)) { BIO_printf(bio_err, "Error outputting keys and certificates\n"); ERR_print_errors(bio_err); goto end; } ret = 0; end: PKCS12_free(p12); release_engine(e); BIO_free(in); BIO_free_all(out); sk_OPENSSL_STRING_free(canames); OPENSSL_free(badpass); OPENSSL_free(passcerts); OPENSSL_free(passin); OPENSSL_free(passout); return ret; } static int jdk_trust(PKCS12_SAFEBAG *bag, void *cbarg) { STACK_OF(X509_ATTRIBUTE) *attrs = NULL; X509_ATTRIBUTE *attr = NULL; /* Nothing to do */ if (cbarg == NULL) return 1; /* Get the current attrs */ attrs = (STACK_OF(X509_ATTRIBUTE)*)PKCS12_SAFEBAG_get0_attrs(bag); /* Create a new attr for the JDK Trusted Usage and add it */ attr = X509_ATTRIBUTE_create(NID_oracle_jdk_trustedkeyusage, V_ASN1_OBJECT, (ASN1_OBJECT*)cbarg); /* Add the new attr, if attrs is NULL, it'll be initialised */ X509at_add1_attr(&attrs, attr); /* Set the bag attrs */ PKCS12_SAFEBAG_set0_attrs(bag, attrs); X509_ATTRIBUTE_free(attr); return 1; } int dump_certs_keys_p12(BIO *out, const PKCS12 *p12, const char *pass, int passlen, int options, char *pempass, const EVP_CIPHER *enc) { STACK_OF(PKCS7) *asafes = NULL; int i, bagnid; int ret = 0; PKCS7 *p7; if ((asafes = PKCS12_unpack_authsafes(p12)) == NULL) return 0; for (i = 0; i < sk_PKCS7_num(asafes); i++) { STACK_OF(PKCS12_SAFEBAG) *bags; p7 = sk_PKCS7_value(asafes, i); bagnid = OBJ_obj2nid(p7->type); if (bagnid == NID_pkcs7_data) { bags = PKCS12_unpack_p7data(p7); if (options & INFO) BIO_printf(bio_err, "PKCS7 Data\n"); } else if (bagnid == NID_pkcs7_encrypted) { if (options & INFO) { BIO_printf(bio_err, "PKCS7 Encrypted data: "); alg_print(p7->d.encrypted->enc_data->algorithm); } bags = PKCS12_unpack_p7encdata(p7, pass, passlen); } else { continue; } if (bags == NULL) goto err; if (!dump_certs_pkeys_bags(out, bags, pass, passlen, options, pempass, enc)) { sk_PKCS12_SAFEBAG_pop_free(bags, PKCS12_SAFEBAG_free); goto err; } sk_PKCS12_SAFEBAG_pop_free(bags, PKCS12_SAFEBAG_free); } ret = 1; err: sk_PKCS7_pop_free(asafes, PKCS7_free); return ret; } int dump_certs_pkeys_bags(BIO *out, const STACK_OF(PKCS12_SAFEBAG) *bags, const char *pass, int passlen, int options, char *pempass, const EVP_CIPHER *enc) { int i; for (i = 0; i < sk_PKCS12_SAFEBAG_num(bags); i++) { if (!dump_certs_pkeys_bag(out, sk_PKCS12_SAFEBAG_value(bags, i), pass, passlen, options, pempass, enc)) return 0; } return 1; } int dump_certs_pkeys_bag(BIO *out, const PKCS12_SAFEBAG *bag, const char *pass, int passlen, int options, char *pempass, const EVP_CIPHER *enc) { EVP_PKEY *pkey; PKCS8_PRIV_KEY_INFO *p8; const PKCS8_PRIV_KEY_INFO *p8c; X509 *x509; const STACK_OF(X509_ATTRIBUTE) *attrs; int ret = 0; attrs = PKCS12_SAFEBAG_get0_attrs(bag); switch (PKCS12_SAFEBAG_get_nid(bag)) { case NID_keyBag: if (options & INFO) BIO_printf(bio_err, "Key bag\n"); if (options & NOKEYS) return 1; print_attribs(out, attrs, "Bag Attributes"); p8c = PKCS12_SAFEBAG_get0_p8inf(bag); if ((pkey = EVP_PKCS82PKEY(p8c)) == NULL) return 0; print_attribs(out, PKCS8_pkey_get0_attrs(p8c), "Key Attributes"); ret = PEM_write_bio_PrivateKey(out, pkey, enc, NULL, 0, NULL, pempass); EVP_PKEY_free(pkey); break; case NID_pkcs8ShroudedKeyBag: if (options & INFO) { const X509_SIG *tp8; const X509_ALGOR *tp8alg; BIO_printf(bio_err, "Shrouded Keybag: "); tp8 = PKCS12_SAFEBAG_get0_pkcs8(bag); X509_SIG_get0(tp8, &tp8alg, NULL); alg_print(tp8alg); } if (options & NOKEYS) return 1; print_attribs(out, attrs, "Bag Attributes"); if ((p8 = PKCS12_decrypt_skey(bag, pass, passlen)) == NULL) return 0; if ((pkey = EVP_PKCS82PKEY(p8)) == NULL) { PKCS8_PRIV_KEY_INFO_free(p8); return 0; } print_attribs(out, PKCS8_pkey_get0_attrs(p8), "Key Attributes"); PKCS8_PRIV_KEY_INFO_free(p8); ret = PEM_write_bio_PrivateKey(out, pkey, enc, NULL, 0, NULL, pempass); EVP_PKEY_free(pkey); break; case NID_certBag: if (options & INFO) BIO_printf(bio_err, "Certificate bag\n"); if (options & NOCERTS) return 1; if (PKCS12_SAFEBAG_get0_attr(bag, NID_localKeyID)) { if (options & CACERTS) return 1; } else if (options & CLCERTS) return 1; print_attribs(out, attrs, "Bag Attributes"); if (PKCS12_SAFEBAG_get_bag_nid(bag) != NID_x509Certificate) return 1; if ((x509 = PKCS12_SAFEBAG_get1_cert(bag)) == NULL) return 0; dump_cert_text(out, x509); ret = PEM_write_bio_X509(out, x509); X509_free(x509); break; case NID_secretBag: if (options & INFO) BIO_printf(bio_err, "Secret bag\n"); print_attribs(out, attrs, "Bag Attributes"); BIO_printf(bio_err, "Bag Type: "); i2a_ASN1_OBJECT(bio_err, PKCS12_SAFEBAG_get0_bag_type(bag)); BIO_printf(bio_err, "\nBag Value: "); print_attribute(out, PKCS12_SAFEBAG_get0_bag_obj(bag)); return 1; case NID_safeContentsBag: if (options & INFO) BIO_printf(bio_err, "Safe Contents bag\n"); print_attribs(out, attrs, "Bag Attributes"); return dump_certs_pkeys_bags(out, PKCS12_SAFEBAG_get0_safes(bag), pass, passlen, options, pempass, enc); default: BIO_printf(bio_err, "Warning unsupported bag type: "); i2a_ASN1_OBJECT(bio_err, PKCS12_SAFEBAG_get0_type(bag)); BIO_printf(bio_err, "\n"); return 1; } return ret; } /* Given a single certificate return a verified chain or NULL if error */ static int get_cert_chain(X509 *cert, X509_STORE *store, STACK_OF(X509) *untrusted_certs, STACK_OF(X509) **chain) { X509_STORE_CTX *store_ctx = NULL; STACK_OF(X509) *chn = NULL; int i = 0; store_ctx = X509_STORE_CTX_new_ex(app_get0_libctx(), app_get0_propq()); if (store_ctx == NULL) { i = X509_V_ERR_UNSPECIFIED; goto end; } if (!X509_STORE_CTX_init(store_ctx, store, cert, untrusted_certs)) { i = X509_V_ERR_UNSPECIFIED; goto end; } if (X509_verify_cert(store_ctx) > 0) chn = X509_STORE_CTX_get1_chain(store_ctx); else if ((i = X509_STORE_CTX_get_error(store_ctx)) == 0) i = X509_V_ERR_UNSPECIFIED; end: X509_STORE_CTX_free(store_ctx); *chain = chn; return i; } static int alg_print(const X509_ALGOR *alg) { int pbenid, aparamtype; const ASN1_OBJECT *aoid; const void *aparam; PBEPARAM *pbe = NULL; X509_ALGOR_get0(&aoid, &aparamtype, &aparam, alg); pbenid = OBJ_obj2nid(aoid); BIO_printf(bio_err, "%s", OBJ_nid2ln(pbenid)); /* * If PBE algorithm is PBES2 decode algorithm parameters * for additional details. */ if (pbenid == NID_pbes2) { PBE2PARAM *pbe2 = NULL; int encnid; if (aparamtype == V_ASN1_SEQUENCE) pbe2 = ASN1_item_unpack(aparam, ASN1_ITEM_rptr(PBE2PARAM)); if (pbe2 == NULL) { BIO_puts(bio_err, ", <unsupported parameters>"); goto done; } X509_ALGOR_get0(&aoid, &aparamtype, &aparam, pbe2->keyfunc); pbenid = OBJ_obj2nid(aoid); X509_ALGOR_get0(&aoid, NULL, NULL, pbe2->encryption); encnid = OBJ_obj2nid(aoid); BIO_printf(bio_err, ", %s, %s", OBJ_nid2ln(pbenid), OBJ_nid2sn(encnid)); /* If KDF is PBKDF2 decode parameters */ if (pbenid == NID_id_pbkdf2) { PBKDF2PARAM *kdf = NULL; int prfnid; if (aparamtype == V_ASN1_SEQUENCE) kdf = ASN1_item_unpack(aparam, ASN1_ITEM_rptr(PBKDF2PARAM)); if (kdf == NULL) { BIO_puts(bio_err, ", <unsupported parameters>"); goto done; } if (kdf->prf == NULL) { prfnid = NID_hmacWithSHA1; } else { X509_ALGOR_get0(&aoid, NULL, NULL, kdf->prf); prfnid = OBJ_obj2nid(aoid); } BIO_printf(bio_err, ", Iteration %ld, PRF %s", ASN1_INTEGER_get(kdf->iter), OBJ_nid2sn(prfnid)); PBKDF2PARAM_free(kdf); #ifndef OPENSSL_NO_SCRYPT } else if (pbenid == NID_id_scrypt) { SCRYPT_PARAMS *kdf = NULL; if (aparamtype == V_ASN1_SEQUENCE) kdf = ASN1_item_unpack(aparam, ASN1_ITEM_rptr(SCRYPT_PARAMS)); if (kdf == NULL) { BIO_puts(bio_err, ", <unsupported parameters>"); goto done; } BIO_printf(bio_err, ", Salt length: %d, Cost(N): %ld, " "Block size(r): %ld, Parallelism(p): %ld", ASN1_STRING_length(kdf->salt), ASN1_INTEGER_get(kdf->costParameter), ASN1_INTEGER_get(kdf->blockSize), ASN1_INTEGER_get(kdf->parallelizationParameter)); SCRYPT_PARAMS_free(kdf); #endif } PBE2PARAM_free(pbe2); } else { if (aparamtype == V_ASN1_SEQUENCE) pbe = ASN1_item_unpack(aparam, ASN1_ITEM_rptr(PBEPARAM)); if (pbe == NULL) { BIO_puts(bio_err, ", <unsupported parameters>"); goto done; } BIO_printf(bio_err, ", Iteration %ld", ASN1_INTEGER_get(pbe->iter)); PBEPARAM_free(pbe); } done: BIO_puts(bio_err, "\n"); return 1; } /* Load all certificates from a given file */ int cert_load(BIO *in, STACK_OF(X509) *sk) { int ret = 0; X509 *cert; while ((cert = PEM_read_bio_X509(in, NULL, NULL, NULL))) { ret = 1; if (!sk_X509_push(sk, cert)) return 0; } if (ret) ERR_clear_error(); return ret; } /* Generalised x509 attribute value print */ void print_attribute(BIO *out, const ASN1_TYPE *av) { char *value; const char *ln; char objbuf[80]; switch (av->type) { case V_ASN1_BMPSTRING: value = OPENSSL_uni2asc(av->value.bmpstring->data, av->value.bmpstring->length); BIO_printf(out, "%s\n", value); OPENSSL_free(value); break; case V_ASN1_UTF8STRING: BIO_printf(out, "%.*s\n", av->value.utf8string->length, av->value.utf8string->data); break; case V_ASN1_OCTET_STRING: hex_prin(out, av->value.octet_string->data, av->value.octet_string->length); BIO_printf(out, "\n"); break; case V_ASN1_BIT_STRING: hex_prin(out, av->value.bit_string->data, av->value.bit_string->length); BIO_printf(out, "\n"); break; case V_ASN1_OBJECT: ln = OBJ_nid2ln(OBJ_obj2nid(av->value.object)); if (!ln) ln = ""; OBJ_obj2txt(objbuf, sizeof(objbuf), av->value.object, 1); BIO_printf(out, "%s (%s)", ln, objbuf); BIO_printf(out, "\n"); break; default: BIO_printf(out, "<Unsupported tag %d>\n", av->type); break; } } /* Generalised attribute print: handle PKCS#8 and bag attributes */ int print_attribs(BIO *out, const STACK_OF(X509_ATTRIBUTE) *attrlst, const char *name) { X509_ATTRIBUTE *attr; ASN1_TYPE *av; int i, j, attr_nid; if (!attrlst) { BIO_printf(out, "%s: <No Attributes>\n", name); return 1; } if (!sk_X509_ATTRIBUTE_num(attrlst)) { BIO_printf(out, "%s: <Empty Attributes>\n", name); return 1; } BIO_printf(out, "%s\n", name); for (i = 0; i < sk_X509_ATTRIBUTE_num(attrlst); i++) { ASN1_OBJECT *attr_obj; attr = sk_X509_ATTRIBUTE_value(attrlst, i); attr_obj = X509_ATTRIBUTE_get0_object(attr); attr_nid = OBJ_obj2nid(attr_obj); BIO_printf(out, " "); if (attr_nid == NID_undef) { i2a_ASN1_OBJECT(out, attr_obj); BIO_printf(out, ": "); } else { BIO_printf(out, "%s: ", OBJ_nid2ln(attr_nid)); } if (X509_ATTRIBUTE_count(attr)) { for (j = 0; j < X509_ATTRIBUTE_count(attr); j++) { av = X509_ATTRIBUTE_get0_type(attr, j); print_attribute(out, av); } } else { BIO_printf(out, "<No Values>\n"); } } return 1; } void hex_prin(BIO *out, unsigned char *buf, int len) { int i; for (i = 0; i < len; i++) BIO_printf(out, "%02X ", buf[i]); } static int set_pbe(int *ppbe, const char *str) { if (!str) return 0; if (strcmp(str, "NONE") == 0) { *ppbe = -1; return 1; } *ppbe = OBJ_txt2nid(str); if (*ppbe == NID_undef) { BIO_printf(bio_err, "Unknown PBE algorithm %s\n", str); return 0; } return 1; }
./openssl/apps/ts.c
/* * Copyright 2006-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/opensslconf.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include "apps.h" #include "progs.h" #include <openssl/bio.h> #include <openssl/err.h> #include <openssl/pem.h> #include <openssl/rand.h> #include <openssl/ts.h> #include <openssl/bn.h> /* Request nonce length, in bits (must be a multiple of 8). */ #define NONCE_LENGTH 64 /* Name of config entry that defines the OID file. */ #define ENV_OID_FILE "oid_file" /* Is |EXACTLY_ONE| of three pointers set? */ #define EXACTLY_ONE(a, b, c) \ (( a && !b && !c) || \ ( b && !a && !c) || \ ( c && !a && !b)) static ASN1_OBJECT *txt2obj(const char *oid); static CONF *load_config_file(const char *configfile); /* Query related functions. */ static int query_command(const char *data, const char *digest, const EVP_MD *md, const char *policy, int no_nonce, int cert, const char *in, const char *out, int text); static TS_REQ *create_query(BIO *data_bio, const char *digest, const EVP_MD *md, const char *policy, int no_nonce, int cert); static int create_digest(BIO *input, const char *digest, const EVP_MD *md, unsigned char **md_value); static ASN1_INTEGER *create_nonce(int bits); /* Reply related functions. */ static int reply_command(CONF *conf, const char *section, const char *engine, const char *queryfile, const char *passin, const char *inkey, const EVP_MD *md, const char *signer, const char *chain, const char *policy, const char *in, int token_in, const char *out, int token_out, int text); static TS_RESP *read_PKCS7(BIO *in_bio); static TS_RESP *create_response(CONF *conf, const char *section, const char *engine, const char *queryfile, const char *passin, const char *inkey, const EVP_MD *md, const char *signer, const char *chain, const char *policy); static ASN1_INTEGER *serial_cb(TS_RESP_CTX *ctx, void *data); static ASN1_INTEGER *next_serial(const char *serialfile); static int save_ts_serial(const char *serialfile, ASN1_INTEGER *serial); /* Verify related functions. */ static int verify_command(const char *data, const char *digest, const char *queryfile, const char *in, int token_in, const char *CApath, const char *CAfile, const char *CAstore, char *untrusted, X509_VERIFY_PARAM *vpm); static TS_VERIFY_CTX *create_verify_ctx(const char *data, const char *digest, const char *queryfile, const char *CApath, const char *CAfile, const char *CAstore, char *untrusted, X509_VERIFY_PARAM *vpm); static X509_STORE *create_cert_store(const char *CApath, const char *CAfile, const char *CAstore, X509_VERIFY_PARAM *vpm); static int verify_cb(int ok, X509_STORE_CTX *ctx); typedef enum OPTION_choice { OPT_COMMON, OPT_ENGINE, OPT_CONFIG, OPT_SECTION, OPT_QUERY, OPT_DATA, OPT_DIGEST, OPT_TSPOLICY, OPT_NO_NONCE, OPT_CERT, OPT_IN, OPT_TOKEN_IN, OPT_OUT, OPT_TOKEN_OUT, OPT_TEXT, OPT_REPLY, OPT_QUERYFILE, OPT_PASSIN, OPT_INKEY, OPT_SIGNER, OPT_CHAIN, OPT_VERIFY, OPT_CAPATH, OPT_CAFILE, OPT_CASTORE, OPT_UNTRUSTED, OPT_MD, OPT_V_ENUM, OPT_R_ENUM, OPT_PROV_ENUM } OPTION_CHOICE; const OPTIONS ts_options[] = { OPT_SECTION("General"), {"help", OPT_HELP, '-', "Display this summary"}, {"config", OPT_CONFIG, '<', "Configuration file"}, {"section", OPT_SECTION, 's', "Section to use within config file"}, #ifndef OPENSSL_NO_ENGINE {"engine", OPT_ENGINE, 's', "Use engine, possibly a hardware device"}, #endif {"inkey", OPT_INKEY, 's', "File with private key for reply"}, {"signer", OPT_SIGNER, 's', "Signer certificate file"}, {"chain", OPT_CHAIN, '<', "File with signer CA chain"}, {"CAfile", OPT_CAFILE, '<', "File with trusted CA certs"}, {"CApath", OPT_CAPATH, '/', "Path to trusted CA files"}, {"CAstore", OPT_CASTORE, ':', "URI to trusted CA store"}, {"untrusted", OPT_UNTRUSTED, '<', "Extra untrusted certs"}, {"token_in", OPT_TOKEN_IN, '-', "Input is a PKCS#7 file"}, {"token_out", OPT_TOKEN_OUT, '-', "Output is a PKCS#7 file"}, {"passin", OPT_PASSIN, 's', "Input file pass phrase source"}, {"", OPT_MD, '-', "Any supported digest"}, OPT_SECTION("Query"), {"query", OPT_QUERY, '-', "Generate a TS query"}, {"data", OPT_DATA, '<', "File to hash"}, {"digest", OPT_DIGEST, 's', "Digest (as a hex string)"}, {"queryfile", OPT_QUERYFILE, '<', "File containing a TS query"}, {"cert", OPT_CERT, '-', "Put cert request into query"}, {"in", OPT_IN, '<', "Input file"}, OPT_SECTION("Verify"), {"verify", OPT_VERIFY, '-', "Verify a TS response"}, {"reply", OPT_REPLY, '-', "Generate a TS reply"}, {"tspolicy", OPT_TSPOLICY, 's', "Policy OID to use"}, {"no_nonce", OPT_NO_NONCE, '-', "Do not include a nonce"}, {"out", OPT_OUT, '>', "Output file"}, {"text", OPT_TEXT, '-', "Output text (not DER)"}, OPT_R_OPTIONS, OPT_V_OPTIONS, OPT_PROV_OPTIONS, {NULL} }; /* * This command is so complex, special help is needed. */ static char* opt_helplist[] = { "", "Typical uses:", " openssl ts -query [-rand file...] [-config file] [-data file]", " [-digest hexstring] [-tspolicy oid] [-no_nonce] [-cert]", " [-in file] [-out file] [-text]", "", " openssl ts -reply [-config file] [-section tsa_section]", " [-queryfile file] [-passin password]", " [-signer tsa_cert.pem] [-inkey private_key.pem]", " [-chain certs_file.pem] [-tspolicy oid]", " [-in file] [-token_in] [-out file] [-token_out]", #ifndef OPENSSL_NO_ENGINE " [-text] [-engine id]", #else " [-text]", #endif "", " openssl ts -verify -CApath dir -CAfile root-cert.pem -CAstore uri", " -untrusted extra-certs.pem [-data file] [-digest hexstring]", " [-queryfile request.tsq] -in response.tsr [-token_in] ...", NULL, }; int ts_main(int argc, char **argv) { CONF *conf = NULL; const char *CAfile = NULL, *prog; char *untrusted = NULL; const char *configfile = default_config_file, *engine = NULL; const char *section = NULL, *digestname = NULL; char **helpp; char *password = NULL; char *data = NULL, *digest = NULL, *policy = NULL; char *in = NULL, *out = NULL, *queryfile = NULL, *passin = NULL; char *inkey = NULL, *signer = NULL, *chain = NULL, *CApath = NULL; char *CAstore = NULL; EVP_MD *md = NULL; OPTION_CHOICE o, mode = OPT_ERR; int ret = 1, no_nonce = 0, cert = 0, text = 0; int vpmtouched = 0; X509_VERIFY_PARAM *vpm = NULL; /* Input is ContentInfo instead of TimeStampResp. */ int token_in = 0; /* Output is ContentInfo instead of TimeStampResp. */ int token_out = 0; if ((vpm = X509_VERIFY_PARAM_new()) == NULL) goto end; opt_set_unknown_name("digest"); prog = opt_init(argc, argv, ts_options); while ((o = opt_next()) != OPT_EOF) { switch (o) { case OPT_EOF: case OPT_ERR: opthelp: BIO_printf(bio_err, "%s: Use -help for summary.\n", prog); goto end; case OPT_HELP: opt_help(ts_options); for (helpp = opt_helplist; *helpp; ++helpp) BIO_printf(bio_err, "%s\n", *helpp); ret = 0; goto end; case OPT_CONFIG: configfile = opt_arg(); break; case OPT_SECTION: section = opt_arg(); break; case OPT_QUERY: case OPT_REPLY: case OPT_VERIFY: if (mode != OPT_ERR) { BIO_printf(bio_err, "%s: Must give only one of -query, -reply, or -verify\n", prog); goto opthelp; } mode = o; break; case OPT_DATA: data = opt_arg(); break; case OPT_DIGEST: digest = opt_arg(); break; case OPT_R_CASES: if (!opt_rand(o)) goto end; break; case OPT_PROV_CASES: if (!opt_provider(o)) goto end; break; case OPT_TSPOLICY: policy = opt_arg(); break; case OPT_NO_NONCE: no_nonce = 1; break; case OPT_CERT: cert = 1; break; case OPT_IN: in = opt_arg(); break; case OPT_TOKEN_IN: token_in = 1; break; case OPT_OUT: out = opt_arg(); break; case OPT_TOKEN_OUT: token_out = 1; break; case OPT_TEXT: text = 1; break; case OPT_QUERYFILE: queryfile = opt_arg(); break; case OPT_PASSIN: passin = opt_arg(); break; case OPT_INKEY: inkey = opt_arg(); break; case OPT_SIGNER: signer = opt_arg(); break; case OPT_CHAIN: chain = opt_arg(); break; case OPT_CAPATH: CApath = opt_arg(); break; case OPT_CAFILE: CAfile = opt_arg(); break; case OPT_CASTORE: CAstore = opt_arg(); break; case OPT_UNTRUSTED: untrusted = opt_arg(); break; case OPT_ENGINE: engine = opt_arg(); break; case OPT_MD: digestname = opt_unknown(); break; case OPT_V_CASES: if (!opt_verify(o, vpm)) goto end; vpmtouched++; break; } } /* No extra arguments. */ if (!opt_check_rest_arg(NULL)) goto opthelp; if (mode == OPT_ERR) { BIO_printf(bio_err, "%s: Must give one of -query, -reply, or -verify\n", prog); goto opthelp; } if (!app_RAND_load()) goto end; if (!opt_md(digestname, &md)) goto opthelp; if (mode == OPT_REPLY && passin && !app_passwd(passin, NULL, &password, NULL)) { BIO_printf(bio_err, "Error getting password.\n"); goto end; } if ((conf = load_config_file(configfile)) == NULL) goto end; if (configfile != default_config_file && !app_load_modules(conf)) goto end; /* Check parameter consistency and execute the appropriate function. */ if (mode == OPT_QUERY) { if (vpmtouched) goto opthelp; if ((data != NULL) && (digest != NULL)) goto opthelp; ret = !query_command(data, digest, md, policy, no_nonce, cert, in, out, text); } else if (mode == OPT_REPLY) { if (vpmtouched) goto opthelp; if ((in != NULL) && (queryfile != NULL)) goto opthelp; if (in == NULL) { if ((conf == NULL) || (token_in != 0)) goto opthelp; } ret = !reply_command(conf, section, engine, queryfile, password, inkey, md, signer, chain, policy, in, token_in, out, token_out, text); } else if (mode == OPT_VERIFY) { if ((in == NULL) || !EXACTLY_ONE(queryfile, data, digest)) goto opthelp; ret = !verify_command(data, digest, queryfile, in, token_in, CApath, CAfile, CAstore, untrusted, vpmtouched ? vpm : NULL); } else { goto opthelp; } end: X509_VERIFY_PARAM_free(vpm); EVP_MD_free(md); NCONF_free(conf); OPENSSL_free(password); return ret; } /* * Configuration file-related function definitions. */ static ASN1_OBJECT *txt2obj(const char *oid) { ASN1_OBJECT *oid_obj = NULL; if ((oid_obj = OBJ_txt2obj(oid, 0)) == NULL) BIO_printf(bio_err, "cannot convert %s to OID\n", oid); return oid_obj; } static CONF *load_config_file(const char *configfile) { CONF *conf = app_load_config(configfile); if (conf != NULL) { const char *p; BIO_printf(bio_err, "Using configuration from %s\n", configfile); p = app_conf_try_string(conf, NULL, ENV_OID_FILE); if (p != NULL) { BIO *oid_bio = BIO_new_file(p, "r"); if (!oid_bio) ERR_print_errors(bio_err); else { OBJ_create_objects(oid_bio); BIO_free_all(oid_bio); } } if (!add_oid_section(conf)) ERR_print_errors(bio_err); } return conf; } /* * Query-related method definitions. */ static int query_command(const char *data, const char *digest, const EVP_MD *md, const char *policy, int no_nonce, int cert, const char *in, const char *out, int text) { int ret = 0; TS_REQ *query = NULL; BIO *in_bio = NULL; BIO *data_bio = NULL; BIO *out_bio = NULL; /* Build query object. */ if (in != NULL) { if ((in_bio = bio_open_default(in, 'r', FORMAT_ASN1)) == NULL) goto end; query = d2i_TS_REQ_bio(in_bio, NULL); } else { if (digest == NULL && (data_bio = bio_open_default(data, 'r', FORMAT_ASN1)) == NULL) goto end; query = create_query(data_bio, digest, md, policy, no_nonce, cert); } if (query == NULL) goto end; if (text) { if ((out_bio = bio_open_default(out, 'w', FORMAT_TEXT)) == NULL) goto end; if (!TS_REQ_print_bio(out_bio, query)) goto end; } else { if ((out_bio = bio_open_default(out, 'w', FORMAT_ASN1)) == NULL) goto end; if (!i2d_TS_REQ_bio(out_bio, query)) goto end; } ret = 1; end: ERR_print_errors(bio_err); BIO_free_all(in_bio); BIO_free_all(data_bio); BIO_free_all(out_bio); TS_REQ_free(query); return ret; } static TS_REQ *create_query(BIO *data_bio, const char *digest, const EVP_MD *md, const char *policy, int no_nonce, int cert) { int ret = 0; TS_REQ *ts_req = NULL; int len; TS_MSG_IMPRINT *msg_imprint = NULL; X509_ALGOR *algo = NULL; unsigned char *data = NULL; ASN1_OBJECT *policy_obj = NULL; ASN1_INTEGER *nonce_asn1 = NULL; if (md == NULL && (md = EVP_get_digestbyname("sha256")) == NULL) goto err; if ((ts_req = TS_REQ_new()) == NULL) goto err; if (!TS_REQ_set_version(ts_req, 1)) goto err; if ((msg_imprint = TS_MSG_IMPRINT_new()) == NULL) goto err; if ((algo = X509_ALGOR_new()) == NULL) goto err; if ((algo->algorithm = OBJ_nid2obj(EVP_MD_get_type(md))) == NULL) goto err; if ((algo->parameter = ASN1_TYPE_new()) == NULL) goto err; algo->parameter->type = V_ASN1_NULL; if (!TS_MSG_IMPRINT_set_algo(msg_imprint, algo)) goto err; if ((len = create_digest(data_bio, digest, md, &data)) == 0) goto err; if (!TS_MSG_IMPRINT_set_msg(msg_imprint, data, len)) goto err; if (!TS_REQ_set_msg_imprint(ts_req, msg_imprint)) goto err; if (policy && (policy_obj = txt2obj(policy)) == NULL) goto err; if (policy_obj && !TS_REQ_set_policy_id(ts_req, policy_obj)) goto err; /* Setting nonce if requested. */ if (!no_nonce && (nonce_asn1 = create_nonce(NONCE_LENGTH)) == NULL) goto err; if (nonce_asn1 && !TS_REQ_set_nonce(ts_req, nonce_asn1)) goto err; if (!TS_REQ_set_cert_req(ts_req, cert)) goto err; ret = 1; err: if (!ret) { TS_REQ_free(ts_req); ts_req = NULL; BIO_printf(bio_err, "could not create query\n"); ERR_print_errors(bio_err); } TS_MSG_IMPRINT_free(msg_imprint); X509_ALGOR_free(algo); OPENSSL_free(data); ASN1_OBJECT_free(policy_obj); ASN1_INTEGER_free(nonce_asn1); return ts_req; } static int create_digest(BIO *input, const char *digest, const EVP_MD *md, unsigned char **md_value) { int md_value_len; int rv = 0; EVP_MD_CTX *md_ctx = NULL; md_value_len = EVP_MD_get_size(md); if (md_value_len < 0) return 0; if (input != NULL) { unsigned char buffer[4096]; int length; md_ctx = EVP_MD_CTX_new(); if (md_ctx == NULL) return 0; *md_value = app_malloc(md_value_len, "digest buffer"); if (!EVP_DigestInit(md_ctx, md)) goto err; while ((length = BIO_read(input, buffer, sizeof(buffer))) > 0) { if (!EVP_DigestUpdate(md_ctx, buffer, length)) goto err; } if (!EVP_DigestFinal(md_ctx, *md_value, NULL)) goto err; md_value_len = EVP_MD_get_size(md); } else { long digest_len; *md_value = OPENSSL_hexstr2buf(digest, &digest_len); if (*md_value == NULL || md_value_len != digest_len) { OPENSSL_free(*md_value); *md_value = NULL; BIO_printf(bio_err, "bad digest, %d bytes " "must be specified\n", md_value_len); return 0; } } rv = md_value_len; err: EVP_MD_CTX_free(md_ctx); return rv; } static ASN1_INTEGER *create_nonce(int bits) { unsigned char buf[20]; ASN1_INTEGER *nonce = NULL; int len = (bits - 1) / 8 + 1; int i; if (len > (int)sizeof(buf)) goto err; if (RAND_bytes(buf, len) <= 0) goto err; /* Find the first non-zero byte and creating ASN1_INTEGER object. */ for (i = 0; i < len && !buf[i]; ++i) continue; if ((nonce = ASN1_INTEGER_new()) == NULL) goto err; OPENSSL_free(nonce->data); nonce->length = len - i; nonce->data = app_malloc(nonce->length + 1, "nonce buffer"); memcpy(nonce->data, buf + i, nonce->length); return nonce; err: BIO_printf(bio_err, "could not create nonce\n"); ASN1_INTEGER_free(nonce); return NULL; } /* * Reply-related method definitions. */ static int reply_command(CONF *conf, const char *section, const char *engine, const char *queryfile, const char *passin, const char *inkey, const EVP_MD *md, const char *signer, const char *chain, const char *policy, const char *in, int token_in, const char *out, int token_out, int text) { int ret = 0; TS_RESP *response = NULL; BIO *in_bio = NULL; BIO *query_bio = NULL; BIO *inkey_bio = NULL; BIO *signer_bio = NULL; BIO *out_bio = NULL; if (in != NULL) { if ((in_bio = BIO_new_file(in, "rb")) == NULL) goto end; if (token_in) { response = read_PKCS7(in_bio); } else { response = d2i_TS_RESP_bio(in_bio, NULL); } } else { response = create_response(conf, section, engine, queryfile, passin, inkey, md, signer, chain, policy); if (response != NULL) BIO_printf(bio_err, "Response has been generated.\n"); else BIO_printf(bio_err, "Response is not generated.\n"); } if (response == NULL) goto end; /* Write response. */ if (text) { if ((out_bio = bio_open_default(out, 'w', FORMAT_TEXT)) == NULL) goto end; if (token_out) { TS_TST_INFO *tst_info = TS_RESP_get_tst_info(response); if (!TS_TST_INFO_print_bio(out_bio, tst_info)) goto end; } else { if (!TS_RESP_print_bio(out_bio, response)) goto end; } } else { if ((out_bio = bio_open_default(out, 'w', FORMAT_ASN1)) == NULL) goto end; if (token_out) { PKCS7 *token = TS_RESP_get_token(response); if (!i2d_PKCS7_bio(out_bio, token)) goto end; } else { if (!i2d_TS_RESP_bio(out_bio, response)) goto end; } } ret = 1; end: ERR_print_errors(bio_err); BIO_free_all(in_bio); BIO_free_all(query_bio); BIO_free_all(inkey_bio); BIO_free_all(signer_bio); BIO_free_all(out_bio); TS_RESP_free(response); return ret; } /* Reads a PKCS7 token and adds default 'granted' status info to it. */ static TS_RESP *read_PKCS7(BIO *in_bio) { int ret = 0; PKCS7 *token = NULL; TS_TST_INFO *tst_info = NULL; TS_RESP *resp = NULL; TS_STATUS_INFO *si = NULL; if ((token = d2i_PKCS7_bio(in_bio, NULL)) == NULL) goto end; if ((tst_info = PKCS7_to_TS_TST_INFO(token)) == NULL) goto end; if ((resp = TS_RESP_new()) == NULL) goto end; if ((si = TS_STATUS_INFO_new()) == NULL) goto end; if (!TS_STATUS_INFO_set_status(si, TS_STATUS_GRANTED)) goto end; if (!TS_RESP_set_status_info(resp, si)) goto end; TS_RESP_set_tst_info(resp, token, tst_info); token = NULL; /* Ownership is lost. */ tst_info = NULL; /* Ownership is lost. */ ret = 1; end: PKCS7_free(token); TS_TST_INFO_free(tst_info); if (!ret) { TS_RESP_free(resp); resp = NULL; } TS_STATUS_INFO_free(si); return resp; } static TS_RESP *create_response(CONF *conf, const char *section, const char *engine, const char *queryfile, const char *passin, const char *inkey, const EVP_MD *md, const char *signer, const char *chain, const char *policy) { int ret = 0; TS_RESP *response = NULL; BIO *query_bio = NULL; TS_RESP_CTX *resp_ctx = NULL; if ((query_bio = BIO_new_file(queryfile, "rb")) == NULL) goto end; if ((section = TS_CONF_get_tsa_section(conf, section)) == NULL) goto end; if ((resp_ctx = TS_RESP_CTX_new()) == NULL) goto end; if (!TS_CONF_set_serial(conf, section, serial_cb, resp_ctx)) goto end; #ifndef OPENSSL_NO_ENGINE if (!TS_CONF_set_crypto_device(conf, section, engine)) goto end; #endif if (!TS_CONF_set_signer_cert(conf, section, signer, resp_ctx)) goto end; if (!TS_CONF_set_certs(conf, section, chain, resp_ctx)) goto end; if (!TS_CONF_set_signer_key(conf, section, inkey, passin, resp_ctx)) goto end; if (md) { if (!TS_RESP_CTX_set_signer_digest(resp_ctx, md)) goto end; } else if (!TS_CONF_set_signer_digest(conf, section, NULL, resp_ctx)) { goto end; } if (!TS_CONF_set_ess_cert_id_digest(conf, section, resp_ctx)) goto end; if (!TS_CONF_set_def_policy(conf, section, policy, resp_ctx)) goto end; if (!TS_CONF_set_policies(conf, section, resp_ctx)) goto end; if (!TS_CONF_set_digests(conf, section, resp_ctx)) goto end; if (!TS_CONF_set_accuracy(conf, section, resp_ctx)) goto end; if (!TS_CONF_set_clock_precision_digits(conf, section, resp_ctx)) goto end; if (!TS_CONF_set_ordering(conf, section, resp_ctx)) goto end; if (!TS_CONF_set_tsa_name(conf, section, resp_ctx)) goto end; if (!TS_CONF_set_ess_cert_id_chain(conf, section, resp_ctx)) goto end; if ((response = TS_RESP_create_response(resp_ctx, query_bio)) == NULL) goto end; ret = 1; end: if (!ret) { TS_RESP_free(response); response = NULL; } TS_RESP_CTX_free(resp_ctx); BIO_free_all(query_bio); return response; } static ASN1_INTEGER *serial_cb(TS_RESP_CTX *ctx, void *data) { const char *serial_file = (const char *)data; ASN1_INTEGER *serial = next_serial(serial_file); if (serial == NULL) { TS_RESP_CTX_set_status_info(ctx, TS_STATUS_REJECTION, "Error during serial number " "generation."); TS_RESP_CTX_add_failure_info(ctx, TS_INFO_ADD_INFO_NOT_AVAILABLE); } else { save_ts_serial(serial_file, serial); } return serial; } static ASN1_INTEGER *next_serial(const char *serialfile) { int ret = 0; BIO *in = NULL; ASN1_INTEGER *serial = NULL; BIGNUM *bn = NULL; if ((serial = ASN1_INTEGER_new()) == NULL) goto err; if ((in = BIO_new_file(serialfile, "r")) == NULL) { ERR_clear_error(); BIO_printf(bio_err, "Warning: could not open file %s for " "reading, using serial number: 1\n", serialfile); if (!ASN1_INTEGER_set(serial, 1)) goto err; } else { char buf[1024]; if (!a2i_ASN1_INTEGER(in, serial, buf, sizeof(buf))) { BIO_printf(bio_err, "unable to load number from %s\n", serialfile); goto err; } if ((bn = ASN1_INTEGER_to_BN(serial, NULL)) == NULL) goto err; ASN1_INTEGER_free(serial); serial = NULL; if (!BN_add_word(bn, 1)) goto err; if ((serial = BN_to_ASN1_INTEGER(bn, NULL)) == NULL) goto err; } ret = 1; err: if (!ret) { ASN1_INTEGER_free(serial); serial = NULL; } BIO_free_all(in); BN_free(bn); return serial; } static int save_ts_serial(const char *serialfile, ASN1_INTEGER *serial) { int ret = 0; BIO *out = NULL; if ((out = BIO_new_file(serialfile, "w")) == NULL) goto err; if (i2a_ASN1_INTEGER(out, serial) <= 0) goto err; if (BIO_puts(out, "\n") <= 0) goto err; ret = 1; err: if (!ret) BIO_printf(bio_err, "could not save serial number to %s\n", serialfile); BIO_free_all(out); return ret; } /* * Verify-related method definitions. */ static int verify_command(const char *data, const char *digest, const char *queryfile, const char *in, int token_in, const char *CApath, const char *CAfile, const char *CAstore, char *untrusted, X509_VERIFY_PARAM *vpm) { BIO *in_bio = NULL; PKCS7 *token = NULL; TS_RESP *response = NULL; TS_VERIFY_CTX *verify_ctx = NULL; int ret = 0; if ((in_bio = BIO_new_file(in, "rb")) == NULL) goto end; if (token_in) { if ((token = d2i_PKCS7_bio(in_bio, NULL)) == NULL) goto end; } else { if ((response = d2i_TS_RESP_bio(in_bio, NULL)) == NULL) goto end; } if ((verify_ctx = create_verify_ctx(data, digest, queryfile, CApath, CAfile, CAstore, untrusted, vpm)) == NULL) goto end; ret = token_in ? TS_RESP_verify_token(verify_ctx, token) : TS_RESP_verify_response(verify_ctx, response); end: printf("Verification: "); if (ret) printf("OK\n"); else { printf("FAILED\n"); ERR_print_errors(bio_err); } BIO_free_all(in_bio); PKCS7_free(token); TS_RESP_free(response); TS_VERIFY_CTX_free(verify_ctx); return ret; } static TS_VERIFY_CTX *create_verify_ctx(const char *data, const char *digest, const char *queryfile, const char *CApath, const char *CAfile, const char *CAstore, char *untrusted, X509_VERIFY_PARAM *vpm) { TS_VERIFY_CTX *ctx = NULL; STACK_OF(X509) *certs; BIO *input = NULL; TS_REQ *request = NULL; int ret = 0; int f = 0; if (data != NULL || digest != NULL) { if ((ctx = TS_VERIFY_CTX_new()) == NULL) goto err; f = TS_VFY_VERSION | TS_VFY_SIGNER; if (data != NULL) { BIO *out = NULL; f |= TS_VFY_DATA; if ((out = BIO_new_file(data, "rb")) == NULL) goto err; if (TS_VERIFY_CTX_set_data(ctx, out) == NULL) { BIO_free_all(out); goto err; } } else if (digest != NULL) { long imprint_len; unsigned char *hexstr = OPENSSL_hexstr2buf(digest, &imprint_len); f |= TS_VFY_IMPRINT; if (TS_VERIFY_CTX_set_imprint(ctx, hexstr, imprint_len) == NULL) { BIO_printf(bio_err, "invalid digest string\n"); goto err; } } } else if (queryfile != NULL) { if ((input = BIO_new_file(queryfile, "rb")) == NULL) goto err; if ((request = d2i_TS_REQ_bio(input, NULL)) == NULL) goto err; if ((ctx = TS_REQ_to_TS_VERIFY_CTX(request, NULL)) == NULL) goto err; } else { return NULL; } /* Add the signature verification flag and arguments. */ TS_VERIFY_CTX_add_flags(ctx, f | TS_VFY_SIGNATURE); /* Initialising the X509_STORE object. */ if (TS_VERIFY_CTX_set_store(ctx, create_cert_store(CApath, CAfile, CAstore, vpm)) == NULL) goto err; /* Loading any extra untrusted certificates. */ if (untrusted != NULL) { certs = load_certs_multifile(untrusted, NULL, "extra untrusted certs", vpm); if (certs == NULL || TS_VERIFY_CTX_set_certs(ctx, certs) == NULL) goto err; } ret = 1; err: if (!ret) { TS_VERIFY_CTX_free(ctx); ctx = NULL; } BIO_free_all(input); TS_REQ_free(request); return ctx; } static X509_STORE *create_cert_store(const char *CApath, const char *CAfile, const char *CAstore, X509_VERIFY_PARAM *vpm) { X509_STORE *cert_ctx = NULL; X509_LOOKUP *lookup = NULL; OSSL_LIB_CTX *libctx = app_get0_libctx(); const char *propq = app_get0_propq(); cert_ctx = X509_STORE_new(); if (cert_ctx == NULL) { BIO_printf(bio_err, "memory allocation failure\n"); return NULL; } X509_STORE_set_verify_cb(cert_ctx, verify_cb); if (CApath != NULL) { lookup = X509_STORE_add_lookup(cert_ctx, X509_LOOKUP_hash_dir()); if (lookup == NULL) { BIO_printf(bio_err, "memory allocation failure\n"); goto err; } if (X509_LOOKUP_add_dir(lookup, CApath, X509_FILETYPE_PEM) <= 0) { BIO_printf(bio_err, "Error loading directory %s\n", CApath); goto err; } } if (CAfile != NULL) { lookup = X509_STORE_add_lookup(cert_ctx, X509_LOOKUP_file()); if (lookup == NULL) { BIO_printf(bio_err, "memory allocation failure\n"); goto err; } if (X509_LOOKUP_load_file_ex(lookup, CAfile, X509_FILETYPE_PEM, libctx, propq) <= 0) { BIO_printf(bio_err, "Error loading file %s\n", CAfile); goto err; } } if (CAstore != NULL) { lookup = X509_STORE_add_lookup(cert_ctx, X509_LOOKUP_store()); if (lookup == NULL) { BIO_printf(bio_err, "memory allocation failure\n"); goto err; } if (X509_LOOKUP_load_store_ex(lookup, CAstore, libctx, propq) <= 0) { BIO_printf(bio_err, "Error loading store URI %s\n", CAstore); goto err; } } if (vpm != NULL) X509_STORE_set1_param(cert_ctx, vpm); return cert_ctx; err: X509_STORE_free(cert_ctx); return NULL; } static int verify_cb(int ok, X509_STORE_CTX *ctx) { return ok; }
./openssl/apps/genpkey.c
/* * Copyright 2006-2023 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <stdio.h> #include <string.h> #include "apps.h" #include "progs.h" #include <openssl/pem.h> #include <openssl/err.h> #include <openssl/evp.h> static int verbose = 1; static int init_keygen_file(EVP_PKEY_CTX **pctx, const char *file, ENGINE *e, OSSL_LIB_CTX *libctx, const char *propq); typedef enum OPTION_choice { OPT_COMMON, OPT_ENGINE, OPT_OUTFORM, OPT_OUT, OPT_PASS, OPT_PARAMFILE, OPT_ALGORITHM, OPT_PKEYOPT, OPT_GENPARAM, OPT_TEXT, OPT_CIPHER, OPT_VERBOSE, OPT_QUIET, OPT_CONFIG, OPT_OUTPUBKEY, OPT_PROV_ENUM, OPT_R_ENUM } OPTION_CHOICE; const OPTIONS genpkey_options[] = { OPT_SECTION("General"), {"help", OPT_HELP, '-', "Display this summary"}, #ifndef OPENSSL_NO_ENGINE {"engine", OPT_ENGINE, 's', "Use engine, possibly a hardware device"}, #endif {"paramfile", OPT_PARAMFILE, '<', "Parameters file"}, {"algorithm", OPT_ALGORITHM, 's', "The public key algorithm"}, {"verbose", OPT_VERBOSE, '-', "Output status while generating keys"}, {"quiet", OPT_QUIET, '-', "Do not output status while generating keys"}, {"pkeyopt", OPT_PKEYOPT, 's', "Set the public key algorithm option as opt:value"}, OPT_CONFIG_OPTION, OPT_SECTION("Output"), {"out", OPT_OUT, '>', "Output (private key) file"}, {"outpubkey", OPT_OUTPUBKEY, '>', "Output public key file"}, {"outform", OPT_OUTFORM, 'F', "output format (DER or PEM)"}, {"pass", OPT_PASS, 's', "Output file pass phrase source"}, {"genparam", OPT_GENPARAM, '-', "Generate parameters, not key"}, {"text", OPT_TEXT, '-', "Print the private key in text"}, {"", OPT_CIPHER, '-', "Cipher to use to encrypt the key"}, OPT_PROV_OPTIONS, OPT_R_OPTIONS, /* This is deliberately last. */ {OPT_HELP_STR, 1, 1, "Order of options may be important! See the documentation.\n"}, {NULL} }; static const char *param_datatype_2name(unsigned int type, int *ishex) { *ishex = 0; switch (type) { case OSSL_PARAM_INTEGER: return "int"; case OSSL_PARAM_UNSIGNED_INTEGER: return "uint"; case OSSL_PARAM_REAL: return "float"; case OSSL_PARAM_OCTET_STRING: *ishex = 1; return "string"; case OSSL_PARAM_UTF8_STRING: return "string"; default: return NULL; } } static void show_gen_pkeyopt(const char *algname, OSSL_LIB_CTX *libctx, const char *propq) { EVP_PKEY_CTX *ctx = NULL; const OSSL_PARAM *params; int i, ishex = 0; if (algname == NULL) return; ctx = EVP_PKEY_CTX_new_from_name(libctx, algname, propq); if (ctx == NULL) return; if (EVP_PKEY_keygen_init(ctx) <= 0) goto cleanup; params = EVP_PKEY_CTX_settable_params(ctx); if (params == NULL) goto cleanup; BIO_printf(bio_err, "\nThe possible -pkeyopt arguments are:\n"); for (i = 0; params[i].key != NULL; ++i) { const char *name = param_datatype_2name(params[i].data_type, &ishex); if (name != NULL) BIO_printf(bio_err, " %s%s:%s\n", ishex ? "hex" : "", params[i].key, name); } cleanup: EVP_PKEY_CTX_free(ctx); } int genpkey_main(int argc, char **argv) { CONF *conf = NULL; BIO *in = NULL, *out = NULL, *outpubkey = NULL; ENGINE *e = NULL; EVP_PKEY *pkey = NULL; EVP_PKEY_CTX *ctx = NULL; char *outfile = NULL, *passarg = NULL, *pass = NULL, *prog, *p; char *outpubkeyfile = NULL; const char *ciphername = NULL, *paramfile = NULL, *algname = NULL; EVP_CIPHER *cipher = NULL; OPTION_CHOICE o; int outformat = FORMAT_PEM, text = 0, ret = 1, rv, do_param = 0; int private = 0, i; OSSL_LIB_CTX *libctx = app_get0_libctx(); STACK_OF(OPENSSL_STRING) *keyopt = NULL; opt_set_unknown_name("cipher"); prog = opt_init(argc, argv, genpkey_options); keyopt = sk_OPENSSL_STRING_new_null(); if (keyopt == NULL) goto end; while ((o = opt_next()) != OPT_EOF) { switch (o) { case OPT_EOF: case OPT_ERR: opthelp: BIO_printf(bio_err, "%s: Use -help for summary.\n", prog); goto end; case OPT_HELP: ret = 0; opt_help(genpkey_options); show_gen_pkeyopt(algname, libctx, app_get0_propq()); goto end; case OPT_OUTFORM: if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &outformat)) goto opthelp; break; case OPT_OUT: outfile = opt_arg(); break; case OPT_OUTPUBKEY: outpubkeyfile = opt_arg(); break; case OPT_PASS: passarg = opt_arg(); break; case OPT_ENGINE: e = setup_engine(opt_arg(), 0); break; case OPT_PARAMFILE: if (do_param == 1) goto opthelp; paramfile = opt_arg(); break; case OPT_ALGORITHM: algname = opt_arg(); break; case OPT_PKEYOPT: if (!sk_OPENSSL_STRING_push(keyopt, opt_arg())) goto end; break; case OPT_QUIET: verbose = 0; break; case OPT_VERBOSE: verbose = 1; break; case OPT_GENPARAM: do_param = 1; break; case OPT_TEXT: text = 1; break; case OPT_CIPHER: ciphername = opt_unknown(); break; case OPT_CONFIG: conf = app_load_config_modules(opt_arg()); if (conf == NULL) goto end; break; case OPT_PROV_CASES: if (!opt_provider(o)) goto end; break; case OPT_R_CASES: if (!opt_rand(o)) goto end; break; } } /* No extra arguments. */ if (!opt_check_rest_arg(NULL)) goto opthelp; if (!app_RAND_load()) goto end; /* Fetch cipher, etc. */ if (paramfile != NULL) { if (!init_keygen_file(&ctx, paramfile, e, libctx, app_get0_propq())) goto end; } if (algname != NULL) { if (!init_gen_str(&ctx, algname, e, do_param, libctx, app_get0_propq())) goto end; } if (ctx == NULL) goto opthelp; for (i = 0; i < sk_OPENSSL_STRING_num(keyopt); i++) { p = sk_OPENSSL_STRING_value(keyopt, i); if (pkey_ctrl_string(ctx, p) <= 0) { BIO_printf(bio_err, "%s: Error setting %s parameter:\n", prog, p); ERR_print_errors(bio_err); goto end; } } if (!opt_cipher(ciphername, &cipher)) goto opthelp; if (ciphername != NULL && do_param == 1) { BIO_printf(bio_err, "Cannot use cipher with -genparam option\n"); goto opthelp; } private = do_param ? 0 : 1; if (!app_passwd(passarg, NULL, &pass, NULL)) { BIO_puts(bio_err, "Error getting password\n"); goto end; } out = bio_open_owner(outfile, outformat, private); if (out == NULL) goto end; if (outpubkeyfile != NULL) { outpubkey = bio_open_owner(outpubkeyfile, outformat, private); if (outpubkey == NULL) goto end; } if (verbose) EVP_PKEY_CTX_set_cb(ctx, progress_cb); EVP_PKEY_CTX_set_app_data(ctx, bio_err); pkey = do_param ? app_paramgen(ctx, algname) : app_keygen(ctx, algname, 0, 0 /* not verbose */); if (pkey == NULL) goto end; if (do_param) { rv = PEM_write_bio_Parameters(out, pkey); } else if (outformat == FORMAT_PEM) { assert(private); rv = PEM_write_bio_PrivateKey(out, pkey, cipher, NULL, 0, NULL, pass); if (rv > 0 && outpubkey != NULL) rv = PEM_write_bio_PUBKEY(outpubkey, pkey); } else if (outformat == FORMAT_ASN1) { assert(private); rv = i2d_PrivateKey_bio(out, pkey); if (rv > 0 && outpubkey != NULL) rv = i2d_PUBKEY_bio(outpubkey, pkey); } else { BIO_printf(bio_err, "Bad format specified for key\n"); goto end; } ret = 0; if (rv <= 0) { BIO_puts(bio_err, "Error writing key(s)\n"); ret = 1; } if (text) { if (do_param) rv = EVP_PKEY_print_params(out, pkey, 0, NULL); else rv = EVP_PKEY_print_private(out, pkey, 0, NULL); if (rv <= 0) { BIO_puts(bio_err, "Error printing key\n"); ret = 1; } } end: sk_OPENSSL_STRING_free(keyopt); if (ret != 0) ERR_print_errors(bio_err); EVP_PKEY_free(pkey); EVP_PKEY_CTX_free(ctx); EVP_CIPHER_free(cipher); BIO_free_all(out); BIO_free_all(outpubkey); BIO_free(in); release_engine(e); OPENSSL_free(pass); NCONF_free(conf); return ret; } static int init_keygen_file(EVP_PKEY_CTX **pctx, const char *file, ENGINE *e, OSSL_LIB_CTX *libctx, const char *propq) { BIO *pbio; EVP_PKEY *pkey = NULL; EVP_PKEY_CTX *ctx = NULL; if (*pctx) { BIO_puts(bio_err, "Parameters already set!\n"); return 0; } pbio = BIO_new_file(file, "r"); if (pbio == NULL) { BIO_printf(bio_err, "Can't open parameter file %s\n", file); return 0; } pkey = PEM_read_bio_Parameters_ex(pbio, NULL, libctx, propq); BIO_free(pbio); if (pkey == NULL) { BIO_printf(bio_err, "Error reading parameter file %s\n", file); return 0; } if (e != NULL) ctx = EVP_PKEY_CTX_new(pkey, e); else ctx = EVP_PKEY_CTX_new_from_pkey(libctx, pkey, propq); if (ctx == NULL) goto err; if (EVP_PKEY_keygen_init(ctx) <= 0) goto err; EVP_PKEY_free(pkey); *pctx = ctx; return 1; err: BIO_puts(bio_err, "Error initializing context\n"); ERR_print_errors(bio_err); EVP_PKEY_CTX_free(ctx); EVP_PKEY_free(pkey); return 0; } int init_gen_str(EVP_PKEY_CTX **pctx, const char *algname, ENGINE *e, int do_param, OSSL_LIB_CTX *libctx, const char *propq) { EVP_PKEY_CTX *ctx = NULL; int pkey_id; if (*pctx) { BIO_puts(bio_err, "Algorithm already set!\n"); return 0; } pkey_id = get_legacy_pkey_id(libctx, algname, e); if (pkey_id != NID_undef) ctx = EVP_PKEY_CTX_new_id(pkey_id, e); else ctx = EVP_PKEY_CTX_new_from_name(libctx, algname, propq); if (ctx == NULL) goto err; if (do_param) { if (EVP_PKEY_paramgen_init(ctx) <= 0) goto err; } else { if (EVP_PKEY_keygen_init(ctx) <= 0) goto err; } *pctx = ctx; return 1; err: BIO_printf(bio_err, "Error initializing %s context\n", algname); ERR_print_errors(bio_err); EVP_PKEY_CTX_free(ctx); return 0; }
./openssl/apps/s_client.c
/* * Copyright 1995-2023 The OpenSSL Project Authors. All Rights Reserved. * Copyright 2005 Nokia. 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/e_os.h" #include <ctype.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <errno.h> #include <openssl/e_os2.h> #include "internal/nelem.h" #ifndef OPENSSL_NO_SOCK /* * With IPv6, it looks like Digital has mixed up the proper order of * recursive header file inclusion, resulting in the compiler complaining * that u_int isn't defined, but only if _POSIX_C_SOURCE is defined, which is * needed to have fileno() declared correctly... So let's define u_int */ #if defined(OPENSSL_SYS_VMS_DECC) && !defined(__U_INT) # define __U_INT typedef unsigned int u_int; #endif #include "apps.h" #include "progs.h" #include <openssl/x509.h> #include <openssl/ssl.h> #include <openssl/err.h> #include <openssl/pem.h> #include <openssl/rand.h> #include <openssl/ocsp.h> #include <openssl/bn.h> #include <openssl/trace.h> #include <openssl/async.h> #ifndef OPENSSL_NO_CT # include <openssl/ct.h> #endif #include "s_apps.h" #include "timeouts.h" #include "internal/sockets.h" #if defined(__has_feature) # if __has_feature(memory_sanitizer) # include <sanitizer/msan_interface.h> # endif #endif #undef BUFSIZZ #define BUFSIZZ 1024*8 #define S_CLIENT_IRC_READ_TIMEOUT 8 #define USER_DATA_MODE_NONE 0 #define USER_DATA_MODE_BASIC 1 #define USER_DATA_MODE_ADVANCED 2 #define USER_DATA_PROCESS_BAD_ARGUMENT 0 #define USER_DATA_PROCESS_SHUT 1 #define USER_DATA_PROCESS_RESTART 2 #define USER_DATA_PROCESS_NO_DATA 3 #define USER_DATA_PROCESS_CONTINUE 4 struct user_data_st { /* SSL connection we are processing commands for */ SSL *con; /* Buffer where we are storing data supplied by the user */ char *buf; /* Allocated size of the buffer */ size_t bufmax; /* Amount of the buffer actually used */ size_t buflen; /* Current location in the buffer where we will read from next*/ size_t bufoff; /* The mode we are using for processing commands */ int mode; /* Whether FIN has ben sent on the stream */ int isfin; }; static void user_data_init(struct user_data_st *user_data, SSL *con, char *buf, size_t bufmax, int mode); static int user_data_add(struct user_data_st *user_data, size_t i); static int user_data_process(struct user_data_st *user_data, size_t *len, size_t *off); static int user_data_has_data(struct user_data_st *user_data); static char *prog; static int c_debug = 0; static int c_showcerts = 0; static char *keymatexportlabel = NULL; static int keymatexportlen = 20; static BIO *bio_c_out = NULL; static int c_quiet = 0; static char *sess_out = NULL; static SSL_SESSION *psksess = NULL; static void print_stuff(BIO *berr, SSL *con, int full); #ifndef OPENSSL_NO_OCSP static int ocsp_resp_cb(SSL *s, void *arg); #endif static int ldap_ExtendedResponse_parse(const char *buf, long rem); static int is_dNS_name(const char *host); static const unsigned char cert_type_rpk[] = { TLSEXT_cert_type_rpk, TLSEXT_cert_type_x509 }; static int enable_server_rpk = 0; static int saved_errno; static void save_errno(void) { saved_errno = errno; errno = 0; } static int restore_errno(void) { int ret = errno; errno = saved_errno; return ret; } /* Default PSK identity and key */ static char *psk_identity = "Client_identity"; #ifndef OPENSSL_NO_PSK static unsigned int psk_client_cb(SSL *ssl, const char *hint, char *identity, unsigned int max_identity_len, unsigned char *psk, unsigned int max_psk_len) { int ret; long key_len; unsigned char *key; if (c_debug) BIO_printf(bio_c_out, "psk_client_cb\n"); if (!hint) { /* no ServerKeyExchange message */ if (c_debug) BIO_printf(bio_c_out, "NULL received PSK identity hint, continuing anyway\n"); } else if (c_debug) { BIO_printf(bio_c_out, "Received PSK identity hint '%s'\n", hint); } /* * lookup PSK identity and PSK key based on the given identity hint here */ ret = BIO_snprintf(identity, max_identity_len, "%s", psk_identity); if (ret < 0 || (unsigned int)ret > max_identity_len) goto out_err; if (c_debug) BIO_printf(bio_c_out, "created identity '%s' len=%d\n", identity, ret); /* convert the PSK key to binary */ key = OPENSSL_hexstr2buf(psk_key, &key_len); if (key == NULL) { BIO_printf(bio_err, "Could not convert PSK key '%s' to buffer\n", psk_key); return 0; } if (max_psk_len > INT_MAX || key_len > (long)max_psk_len) { BIO_printf(bio_err, "psk buffer of callback is too small (%d) for key (%ld)\n", max_psk_len, key_len); OPENSSL_free(key); return 0; } memcpy(psk, key, key_len); OPENSSL_free(key); if (c_debug) BIO_printf(bio_c_out, "created PSK len=%ld\n", key_len); return key_len; out_err: if (c_debug) BIO_printf(bio_err, "Error in PSK client callback\n"); return 0; } #endif const unsigned char tls13_aes128gcmsha256_id[] = { 0x13, 0x01 }; const unsigned char tls13_aes256gcmsha384_id[] = { 0x13, 0x02 }; static int psk_use_session_cb(SSL *s, const EVP_MD *md, const unsigned char **id, size_t *idlen, SSL_SESSION **sess) { SSL_SESSION *usesess = NULL; const SSL_CIPHER *cipher = NULL; if (psksess != NULL) { SSL_SESSION_up_ref(psksess); usesess = psksess; } else { long key_len; unsigned char *key = OPENSSL_hexstr2buf(psk_key, &key_len); if (key == NULL) { BIO_printf(bio_err, "Could not convert PSK key '%s' to buffer\n", psk_key); return 0; } /* We default to SHA-256 */ cipher = SSL_CIPHER_find(s, tls13_aes128gcmsha256_id); if (cipher == NULL) { BIO_printf(bio_err, "Error finding suitable ciphersuite\n"); OPENSSL_free(key); return 0; } usesess = SSL_SESSION_new(); if (usesess == NULL || !SSL_SESSION_set1_master_key(usesess, key, key_len) || !SSL_SESSION_set_cipher(usesess, cipher) || !SSL_SESSION_set_protocol_version(usesess, TLS1_3_VERSION)) { OPENSSL_free(key); goto err; } OPENSSL_free(key); } cipher = SSL_SESSION_get0_cipher(usesess); if (cipher == NULL) goto err; if (md != NULL && SSL_CIPHER_get_handshake_digest(cipher) != md) { /* PSK not usable, ignore it */ *id = NULL; *idlen = 0; *sess = NULL; SSL_SESSION_free(usesess); } else { *sess = usesess; *id = (unsigned char *)psk_identity; *idlen = strlen(psk_identity); } return 1; err: SSL_SESSION_free(usesess); return 0; } /* This is a context that we pass to callbacks */ typedef struct tlsextctx_st { BIO *biodebug; int ack; } tlsextctx; static int ssl_servername_cb(SSL *s, int *ad, void *arg) { tlsextctx *p = (tlsextctx *) arg; const char *hn = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name); if (SSL_get_servername_type(s) != -1) p->ack = !SSL_session_reused(s) && hn != NULL; else BIO_printf(bio_err, "Can't use SSL_get_servername\n"); return SSL_TLSEXT_ERR_OK; } #ifndef OPENSSL_NO_NEXTPROTONEG /* This the context that we pass to next_proto_cb */ typedef struct tlsextnextprotoctx_st { unsigned char *data; size_t len; int status; } tlsextnextprotoctx; static tlsextnextprotoctx next_proto; static int next_proto_cb(SSL *s, unsigned char **out, unsigned char *outlen, const unsigned char *in, unsigned int inlen, void *arg) { tlsextnextprotoctx *ctx = arg; if (!c_quiet) { /* We can assume that |in| is syntactically valid. */ unsigned i; BIO_printf(bio_c_out, "Protocols advertised by server: "); for (i = 0; i < inlen;) { if (i) BIO_write(bio_c_out, ", ", 2); BIO_write(bio_c_out, &in[i + 1], in[i]); i += in[i] + 1; } BIO_write(bio_c_out, "\n", 1); } ctx->status = SSL_select_next_proto(out, outlen, in, inlen, ctx->data, ctx->len); return SSL_TLSEXT_ERR_OK; } #endif /* ndef OPENSSL_NO_NEXTPROTONEG */ static int serverinfo_cli_parse_cb(SSL *s, unsigned int ext_type, const unsigned char *in, size_t inlen, int *al, void *arg) { char pem_name[100]; unsigned char ext_buf[4 + 65536]; /* Reconstruct the type/len fields prior to extension data */ inlen &= 0xffff; /* for formal memcmpy correctness */ ext_buf[0] = (unsigned char)(ext_type >> 8); ext_buf[1] = (unsigned char)(ext_type); ext_buf[2] = (unsigned char)(inlen >> 8); ext_buf[3] = (unsigned char)(inlen); memcpy(ext_buf + 4, in, inlen); BIO_snprintf(pem_name, sizeof(pem_name), "SERVERINFO FOR EXTENSION %d", ext_type); PEM_write_bio(bio_c_out, pem_name, "", ext_buf, 4 + inlen); return 1; } /* * Hex decoder that tolerates optional whitespace. Returns number of bytes * produced, advances inptr to end of input string. */ static ossl_ssize_t hexdecode(const char **inptr, void *result) { unsigned char **out = (unsigned char **)result; const char *in = *inptr; unsigned char *ret = app_malloc(strlen(in) / 2, "hexdecode"); unsigned char *cp = ret; uint8_t byte; int nibble = 0; if (ret == NULL) return -1; for (byte = 0; *in; ++in) { int x; if (isspace(_UC(*in))) continue; x = OPENSSL_hexchar2int(*in); if (x < 0) { OPENSSL_free(ret); return 0; } byte |= (char)x; if ((nibble ^= 1) == 0) { *cp++ = byte; byte = 0; } else { byte <<= 4; } } if (nibble != 0) { OPENSSL_free(ret); return 0; } *inptr = in; return cp - (*out = ret); } /* * Decode unsigned 0..255, returns 1 on success, <= 0 on failure. Advances * inptr to next field skipping leading whitespace. */ static ossl_ssize_t checked_uint8(const char **inptr, void *out) { uint8_t *result = (uint8_t *)out; const char *in = *inptr; char *endp; long v; int e; save_errno(); v = strtol(in, &endp, 10); e = restore_errno(); if (((v == LONG_MIN || v == LONG_MAX) && e == ERANGE) || endp == in || !isspace(_UC(*endp)) || v != (*result = (uint8_t) v)) { return -1; } for (in = endp; isspace(_UC(*in)); ++in) continue; *inptr = in; return 1; } struct tlsa_field { void *var; const char *name; ossl_ssize_t (*parser)(const char **, void *); }; static int tlsa_import_rr(SSL *con, const char *rrdata) { /* Not necessary to re-init these values; the "parsers" do that. */ static uint8_t usage; static uint8_t selector; static uint8_t mtype; static unsigned char *data; static struct tlsa_field tlsa_fields[] = { { &usage, "usage", checked_uint8 }, { &selector, "selector", checked_uint8 }, { &mtype, "mtype", checked_uint8 }, { &data, "data", hexdecode }, { NULL, } }; struct tlsa_field *f; int ret; const char *cp = rrdata; ossl_ssize_t len = 0; for (f = tlsa_fields; f->var; ++f) { /* Returns number of bytes produced, advances cp to next field */ if ((len = f->parser(&cp, f->var)) <= 0) { BIO_printf(bio_err, "%s: warning: bad TLSA %s field in: %s\n", prog, f->name, rrdata); return 0; } } /* The data field is last, so len is its length */ ret = SSL_dane_tlsa_add(con, usage, selector, mtype, data, len); OPENSSL_free(data); if (ret == 0) { ERR_print_errors(bio_err); BIO_printf(bio_err, "%s: warning: unusable TLSA rrdata: %s\n", prog, rrdata); return 0; } if (ret < 0) { ERR_print_errors(bio_err); BIO_printf(bio_err, "%s: warning: error loading TLSA rrdata: %s\n", prog, rrdata); return 0; } return ret; } static int tlsa_import_rrset(SSL *con, STACK_OF(OPENSSL_STRING) *rrset) { int num = sk_OPENSSL_STRING_num(rrset); int count = 0; int i; for (i = 0; i < num; ++i) { char *rrdata = sk_OPENSSL_STRING_value(rrset, i); if (tlsa_import_rr(con, rrdata) > 0) ++count; } return count > 0; } typedef enum OPTION_choice { OPT_COMMON, OPT_4, OPT_6, OPT_HOST, OPT_PORT, OPT_CONNECT, OPT_BIND, OPT_UNIX, OPT_XMPPHOST, OPT_VERIFY, OPT_NAMEOPT, OPT_CERT, OPT_CRL, OPT_CRL_DOWNLOAD, OPT_SESS_OUT, OPT_SESS_IN, OPT_CERTFORM, OPT_CRLFORM, OPT_VERIFY_RET_ERROR, OPT_VERIFY_QUIET, OPT_BRIEF, OPT_PREXIT, OPT_NO_INTERACTIVE, OPT_CRLF, OPT_QUIET, OPT_NBIO, OPT_SSL_CLIENT_ENGINE, OPT_IGN_EOF, OPT_NO_IGN_EOF, OPT_DEBUG, OPT_TLSEXTDEBUG, OPT_STATUS, OPT_WDEBUG, OPT_MSG, OPT_MSGFILE, OPT_ENGINE, OPT_TRACE, OPT_SECURITY_DEBUG, OPT_SECURITY_DEBUG_VERBOSE, OPT_SHOWCERTS, OPT_NBIO_TEST, OPT_STATE, OPT_PSK_IDENTITY, OPT_PSK, OPT_PSK_SESS, #ifndef OPENSSL_NO_SRP OPT_SRPUSER, OPT_SRPPASS, OPT_SRP_STRENGTH, OPT_SRP_LATEUSER, OPT_SRP_MOREGROUPS, #endif OPT_SSL3, OPT_SSL_CONFIG, OPT_TLS1_3, OPT_TLS1_2, OPT_TLS1_1, OPT_TLS1, OPT_DTLS, OPT_DTLS1, OPT_DTLS1_2, OPT_QUIC, OPT_SCTP, OPT_TIMEOUT, OPT_MTU, OPT_KEYFORM, OPT_PASS, OPT_CERT_CHAIN, OPT_KEY, OPT_RECONNECT, OPT_BUILD_CHAIN, OPT_NEXTPROTONEG, OPT_ALPN, OPT_CAPATH, OPT_NOCAPATH, OPT_CHAINCAPATH, OPT_VERIFYCAPATH, OPT_CAFILE, OPT_NOCAFILE, OPT_CHAINCAFILE, OPT_VERIFYCAFILE, OPT_CASTORE, OPT_NOCASTORE, OPT_CHAINCASTORE, OPT_VERIFYCASTORE, OPT_SERVERINFO, OPT_STARTTLS, OPT_SERVERNAME, OPT_NOSERVERNAME, OPT_ASYNC, OPT_USE_SRTP, OPT_KEYMATEXPORT, OPT_KEYMATEXPORTLEN, OPT_PROTOHOST, OPT_MAXFRAGLEN, OPT_MAX_SEND_FRAG, OPT_SPLIT_SEND_FRAG, OPT_MAX_PIPELINES, OPT_READ_BUF, OPT_KEYLOG_FILE, OPT_EARLY_DATA, OPT_REQCAFILE, OPT_TFO, OPT_V_ENUM, OPT_X_ENUM, OPT_S_ENUM, OPT_IGNORE_UNEXPECTED_EOF, OPT_FALLBACKSCSV, OPT_NOCMDS, OPT_ADV, OPT_PROXY, OPT_PROXY_USER, OPT_PROXY_PASS, OPT_DANE_TLSA_DOMAIN, #ifndef OPENSSL_NO_CT OPT_CT, OPT_NOCT, OPT_CTLOG_FILE, #endif OPT_DANE_TLSA_RRDATA, OPT_DANE_EE_NO_NAME, OPT_ENABLE_PHA, OPT_ENABLE_SERVER_RPK, OPT_ENABLE_CLIENT_RPK, OPT_SCTP_LABEL_BUG, OPT_KTLS, OPT_R_ENUM, OPT_PROV_ENUM } OPTION_CHOICE; const OPTIONS s_client_options[] = { {OPT_HELP_STR, 1, '-', "Usage: %s [options] [host:port]\n"}, OPT_SECTION("General"), {"help", OPT_HELP, '-', "Display this summary"}, #ifndef OPENSSL_NO_ENGINE {"engine", OPT_ENGINE, 's', "Use engine, possibly a hardware device"}, {"ssl_client_engine", OPT_SSL_CLIENT_ENGINE, 's', "Specify engine to be used for client certificate operations"}, #endif {"ssl_config", OPT_SSL_CONFIG, 's', "Use specified section for SSL_CTX configuration"}, #ifndef OPENSSL_NO_CT {"ct", OPT_CT, '-', "Request and parse SCTs (also enables OCSP stapling)"}, {"noct", OPT_NOCT, '-', "Do not request or parse SCTs (default)"}, {"ctlogfile", OPT_CTLOG_FILE, '<', "CT log list CONF file"}, #endif OPT_SECTION("Network"), {"host", OPT_HOST, 's', "Use -connect instead"}, {"port", OPT_PORT, 'p', "Use -connect instead"}, {"connect", OPT_CONNECT, 's', "TCP/IP where to connect; default: " PORT ")"}, {"bind", OPT_BIND, 's', "bind local address for connection"}, {"proxy", OPT_PROXY, 's', "Connect to via specified proxy to the real server"}, {"proxy_user", OPT_PROXY_USER, 's', "UserID for proxy authentication"}, {"proxy_pass", OPT_PROXY_PASS, 's', "Proxy authentication password source"}, #ifdef AF_UNIX {"unix", OPT_UNIX, 's', "Connect over the specified Unix-domain socket"}, #endif {"4", OPT_4, '-', "Use IPv4 only"}, #ifdef AF_INET6 {"6", OPT_6, '-', "Use IPv6 only"}, #endif {"maxfraglen", OPT_MAXFRAGLEN, 'p', "Enable Maximum Fragment Length Negotiation (len values: 512, 1024, 2048 and 4096)"}, {"max_send_frag", OPT_MAX_SEND_FRAG, 'p', "Maximum Size of send frames "}, {"split_send_frag", OPT_SPLIT_SEND_FRAG, 'p', "Size used to split data for encrypt pipelines"}, {"max_pipelines", OPT_MAX_PIPELINES, 'p', "Maximum number of encrypt/decrypt pipelines to be used"}, {"read_buf", OPT_READ_BUF, 'p', "Default read buffer size to be used for connections"}, {"fallback_scsv", OPT_FALLBACKSCSV, '-', "Send the fallback SCSV"}, OPT_SECTION("Identity"), {"cert", OPT_CERT, '<', "Client certificate file to use"}, {"certform", OPT_CERTFORM, 'F', "Client certificate file format (PEM/DER/P12); has no effect"}, {"cert_chain", OPT_CERT_CHAIN, '<', "Client certificate chain file (in PEM format)"}, {"build_chain", OPT_BUILD_CHAIN, '-', "Build client certificate chain"}, {"key", OPT_KEY, 's', "Private key file to use; default: -cert file"}, {"keyform", OPT_KEYFORM, 'E', "Key format (ENGINE, other values ignored)"}, {"pass", OPT_PASS, 's', "Private key and cert file pass phrase source"}, {"verify", OPT_VERIFY, 'p', "Turn on peer certificate verification"}, {"nameopt", OPT_NAMEOPT, 's', "Certificate subject/issuer name printing options"}, {"CApath", OPT_CAPATH, '/', "PEM format directory of CA's"}, {"CAfile", OPT_CAFILE, '<', "PEM format file of CA's"}, {"CAstore", OPT_CASTORE, ':', "URI to store of CA's"}, {"no-CAfile", OPT_NOCAFILE, '-', "Do not load the default certificates file"}, {"no-CApath", OPT_NOCAPATH, '-', "Do not load certificates from the default certificates directory"}, {"no-CAstore", OPT_NOCASTORE, '-', "Do not load certificates from the default certificates store"}, {"requestCAfile", OPT_REQCAFILE, '<', "PEM format file of CA names to send to the server"}, #if defined(TCP_FASTOPEN) && !defined(OPENSSL_NO_TFO) {"tfo", OPT_TFO, '-', "Connect using TCP Fast Open"}, #endif {"dane_tlsa_domain", OPT_DANE_TLSA_DOMAIN, 's', "DANE TLSA base domain"}, {"dane_tlsa_rrdata", OPT_DANE_TLSA_RRDATA, 's', "DANE TLSA rrdata presentation form"}, {"dane_ee_no_namechecks", OPT_DANE_EE_NO_NAME, '-', "Disable name checks when matching DANE-EE(3) TLSA records"}, {"psk_identity", OPT_PSK_IDENTITY, 's', "PSK identity"}, {"psk", OPT_PSK, 's', "PSK in hex (without 0x)"}, {"psk_session", OPT_PSK_SESS, '<', "File to read PSK SSL session from"}, {"name", OPT_PROTOHOST, 's', "Hostname to use for \"-starttls lmtp\", \"-starttls smtp\" or \"-starttls xmpp[-server]\""}, OPT_SECTION("Session"), {"reconnect", OPT_RECONNECT, '-', "Drop and re-make the connection with the same Session-ID"}, {"sess_out", OPT_SESS_OUT, '>', "File to write SSL session to"}, {"sess_in", OPT_SESS_IN, '<', "File to read SSL session from"}, OPT_SECTION("Input/Output"), {"crlf", OPT_CRLF, '-', "Convert LF from terminal into CRLF"}, {"quiet", OPT_QUIET, '-', "No s_client output"}, {"ign_eof", OPT_IGN_EOF, '-', "Ignore input eof (default when -quiet)"}, {"no_ign_eof", OPT_NO_IGN_EOF, '-', "Don't ignore input eof"}, {"starttls", OPT_STARTTLS, 's', "Use the appropriate STARTTLS command before starting TLS"}, {"xmpphost", OPT_XMPPHOST, 's', "Alias of -name option for \"-starttls xmpp[-server]\""}, {"brief", OPT_BRIEF, '-', "Restrict output to brief summary of connection parameters"}, {"prexit", OPT_PREXIT, '-', "Print session information when the program exits"}, {"no-interactive", OPT_NO_INTERACTIVE, '-', "Don't run the client in the interactive mode"}, OPT_SECTION("Debug"), {"showcerts", OPT_SHOWCERTS, '-', "Show all certificates sent by the server"}, {"debug", OPT_DEBUG, '-', "Extra output"}, {"msg", OPT_MSG, '-', "Show protocol messages"}, {"msgfile", OPT_MSGFILE, '>', "File to send output of -msg or -trace, instead of stdout"}, {"nbio_test", OPT_NBIO_TEST, '-', "More ssl protocol testing"}, {"state", OPT_STATE, '-', "Print the ssl states"}, {"keymatexport", OPT_KEYMATEXPORT, 's', "Export keying material using label"}, {"keymatexportlen", OPT_KEYMATEXPORTLEN, 'p', "Export len bytes of keying material; default 20"}, {"security_debug", OPT_SECURITY_DEBUG, '-', "Enable security debug messages"}, {"security_debug_verbose", OPT_SECURITY_DEBUG_VERBOSE, '-', "Output more security debug output"}, #ifndef OPENSSL_NO_SSL_TRACE {"trace", OPT_TRACE, '-', "Show trace output of protocol messages"}, #endif #ifdef WATT32 {"wdebug", OPT_WDEBUG, '-', "WATT-32 tcp debugging"}, #endif {"keylogfile", OPT_KEYLOG_FILE, '>', "Write TLS secrets to file"}, {"nocommands", OPT_NOCMDS, '-', "Do not use interactive command letters"}, {"adv", OPT_ADV, '-', "Advanced command mode"}, {"servername", OPT_SERVERNAME, 's', "Set TLS extension servername (SNI) in ClientHello (default)"}, {"noservername", OPT_NOSERVERNAME, '-', "Do not send the server name (SNI) extension in the ClientHello"}, {"tlsextdebug", OPT_TLSEXTDEBUG, '-', "Hex dump of all TLS extensions received"}, {"ignore_unexpected_eof", OPT_IGNORE_UNEXPECTED_EOF, '-', "Do not treat lack of close_notify from a peer as an error"}, #ifndef OPENSSL_NO_OCSP {"status", OPT_STATUS, '-', "Request certificate status from server"}, #endif {"serverinfo", OPT_SERVERINFO, 's', "types Send empty ClientHello extensions (comma-separated numbers)"}, {"alpn", OPT_ALPN, 's', "Enable ALPN extension, considering named protocols supported (comma-separated list)"}, {"async", OPT_ASYNC, '-', "Support asynchronous operation"}, {"nbio", OPT_NBIO, '-', "Use non-blocking IO"}, OPT_SECTION("Protocol and version"), #ifndef OPENSSL_NO_SSL3 {"ssl3", OPT_SSL3, '-', "Just use SSLv3"}, #endif #ifndef OPENSSL_NO_TLS1 {"tls1", OPT_TLS1, '-', "Just use TLSv1"}, #endif #ifndef OPENSSL_NO_TLS1_1 {"tls1_1", OPT_TLS1_1, '-', "Just use TLSv1.1"}, #endif #ifndef OPENSSL_NO_TLS1_2 {"tls1_2", OPT_TLS1_2, '-', "Just use TLSv1.2"}, #endif #ifndef OPENSSL_NO_TLS1_3 {"tls1_3", OPT_TLS1_3, '-', "Just use TLSv1.3"}, #endif #ifndef OPENSSL_NO_DTLS {"dtls", OPT_DTLS, '-', "Use any version of DTLS"}, {"quic", OPT_QUIC, '-', "Use QUIC"}, {"timeout", OPT_TIMEOUT, '-', "Enable send/receive timeout on DTLS connections"}, {"mtu", OPT_MTU, 'p', "Set the link layer MTU"}, #endif #ifndef OPENSSL_NO_DTLS1 {"dtls1", OPT_DTLS1, '-', "Just use DTLSv1"}, #endif #ifndef OPENSSL_NO_DTLS1_2 {"dtls1_2", OPT_DTLS1_2, '-', "Just use DTLSv1.2"}, #endif #ifndef OPENSSL_NO_SCTP {"sctp", OPT_SCTP, '-', "Use SCTP"}, {"sctp_label_bug", OPT_SCTP_LABEL_BUG, '-', "Enable SCTP label length bug"}, #endif #ifndef OPENSSL_NO_NEXTPROTONEG {"nextprotoneg", OPT_NEXTPROTONEG, 's', "Enable NPN extension, considering named protocols supported (comma-separated list)"}, #endif {"early_data", OPT_EARLY_DATA, '<', "File to send as early data"}, {"enable_pha", OPT_ENABLE_PHA, '-', "Enable post-handshake-authentication"}, {"enable_server_rpk", OPT_ENABLE_SERVER_RPK, '-', "Enable raw public keys (RFC7250) from the server"}, {"enable_client_rpk", OPT_ENABLE_CLIENT_RPK, '-', "Enable raw public keys (RFC7250) from the client"}, #ifndef OPENSSL_NO_SRTP {"use_srtp", OPT_USE_SRTP, 's', "Offer SRTP key management with a colon-separated profile list"}, #endif #ifndef OPENSSL_NO_SRP {"srpuser", OPT_SRPUSER, 's', "(deprecated) SRP authentication for 'user'"}, {"srppass", OPT_SRPPASS, 's', "(deprecated) Password for 'user'"}, {"srp_lateuser", OPT_SRP_LATEUSER, '-', "(deprecated) SRP username into second ClientHello message"}, {"srp_moregroups", OPT_SRP_MOREGROUPS, '-', "(deprecated) Tolerate other than the known g N values."}, {"srp_strength", OPT_SRP_STRENGTH, 'p', "(deprecated) Minimal length in bits for N"}, #endif #ifndef OPENSSL_NO_KTLS {"ktls", OPT_KTLS, '-', "Enable Kernel TLS for sending and receiving"}, #endif OPT_R_OPTIONS, OPT_S_OPTIONS, OPT_V_OPTIONS, {"CRL", OPT_CRL, '<', "CRL file to use"}, {"crl_download", OPT_CRL_DOWNLOAD, '-', "Download CRL from distribution points"}, {"CRLform", OPT_CRLFORM, 'F', "CRL format (PEM or DER); default PEM"}, {"verify_return_error", OPT_VERIFY_RET_ERROR, '-', "Close connection on verification error"}, {"verify_quiet", OPT_VERIFY_QUIET, '-', "Restrict verify output to errors"}, {"chainCAfile", OPT_CHAINCAFILE, '<', "CA file for certificate chain (PEM format)"}, {"chainCApath", OPT_CHAINCAPATH, '/', "Use dir as certificate store path to build CA certificate chain"}, {"chainCAstore", OPT_CHAINCASTORE, ':', "CA store URI for certificate chain"}, {"verifyCAfile", OPT_VERIFYCAFILE, '<', "CA file for certificate verification (PEM format)"}, {"verifyCApath", OPT_VERIFYCAPATH, '/', "Use dir as certificate store path to verify CA certificate"}, {"verifyCAstore", OPT_VERIFYCASTORE, ':', "CA store URI for certificate verification"}, OPT_X_OPTIONS, OPT_PROV_OPTIONS, OPT_PARAMETERS(), {"host:port", 0, 0, "Where to connect; same as -connect option"}, {NULL} }; typedef enum PROTOCOL_choice { PROTO_OFF, PROTO_SMTP, PROTO_POP3, PROTO_IMAP, PROTO_FTP, PROTO_TELNET, PROTO_XMPP, PROTO_XMPP_SERVER, PROTO_IRC, PROTO_MYSQL, PROTO_POSTGRES, PROTO_LMTP, PROTO_NNTP, PROTO_SIEVE, PROTO_LDAP } PROTOCOL_CHOICE; static const OPT_PAIR services[] = { {"smtp", PROTO_SMTP}, {"pop3", PROTO_POP3}, {"imap", PROTO_IMAP}, {"ftp", PROTO_FTP}, {"xmpp", PROTO_XMPP}, {"xmpp-server", PROTO_XMPP_SERVER}, {"telnet", PROTO_TELNET}, {"irc", PROTO_IRC}, {"mysql", PROTO_MYSQL}, {"postgres", PROTO_POSTGRES}, {"lmtp", PROTO_LMTP}, {"nntp", PROTO_NNTP}, {"sieve", PROTO_SIEVE}, {"ldap", PROTO_LDAP}, {NULL, 0} }; #define IS_INET_FLAG(o) \ (o == OPT_4 || o == OPT_6 || o == OPT_HOST || o == OPT_PORT || o == OPT_CONNECT) #define IS_UNIX_FLAG(o) (o == OPT_UNIX) #define IS_PROT_FLAG(o) \ (o == OPT_SSL3 || o == OPT_TLS1 || o == OPT_TLS1_1 || o == OPT_TLS1_2 \ || o == OPT_TLS1_3 || o == OPT_DTLS || o == OPT_DTLS1 || o == OPT_DTLS1_2 \ || o == OPT_QUIC) /* Free |*dest| and optionally set it to a copy of |source|. */ static void freeandcopy(char **dest, const char *source) { OPENSSL_free(*dest); *dest = NULL; if (source != NULL) *dest = OPENSSL_strdup(source); } static int new_session_cb(SSL *s, SSL_SESSION *sess) { if (sess_out != NULL) { BIO *stmp = BIO_new_file(sess_out, "w"); if (stmp == NULL) { BIO_printf(bio_err, "Error writing session file %s\n", sess_out); } else { PEM_write_bio_SSL_SESSION(stmp, sess); BIO_free(stmp); } } /* * Session data gets dumped on connection for TLSv1.2 and below, and on * arrival of the NewSessionTicket for TLSv1.3. */ if (SSL_version(s) == TLS1_3_VERSION) { BIO_printf(bio_c_out, "---\nPost-Handshake New Session Ticket arrived:\n"); SSL_SESSION_print(bio_c_out, sess); BIO_printf(bio_c_out, "---\n"); } /* * We always return a "fail" response so that the session gets freed again * because we haven't used the reference. */ return 0; } int s_client_main(int argc, char **argv) { BIO *sbio; EVP_PKEY *key = NULL; SSL *con = NULL; SSL_CTX *ctx = NULL; STACK_OF(X509) *chain = NULL; X509 *cert = NULL; X509_VERIFY_PARAM *vpm = NULL; SSL_EXCERT *exc = NULL; SSL_CONF_CTX *cctx = NULL; STACK_OF(OPENSSL_STRING) *ssl_args = NULL; char *dane_tlsa_domain = NULL; STACK_OF(OPENSSL_STRING) *dane_tlsa_rrset = NULL; int dane_ee_no_name = 0; STACK_OF(X509_CRL) *crls = NULL; const SSL_METHOD *meth = TLS_client_method(); const char *CApath = NULL, *CAfile = NULL, *CAstore = NULL; char *cbuf = NULL, *sbuf = NULL, *mbuf = NULL; char *proxystr = NULL, *proxyuser = NULL; char *proxypassarg = NULL, *proxypass = NULL; char *connectstr = NULL, *bindstr = NULL; char *cert_file = NULL, *key_file = NULL, *chain_file = NULL; char *chCApath = NULL, *chCAfile = NULL, *chCAstore = NULL, *host = NULL; char *thost = NULL, *tport = NULL; char *port = NULL; char *bindhost = NULL, *bindport = NULL; char *passarg = NULL, *pass = NULL; char *vfyCApath = NULL, *vfyCAfile = NULL, *vfyCAstore = NULL; char *ReqCAfile = NULL; char *sess_in = NULL, *crl_file = NULL, *p; const char *protohost = NULL; struct timeval timeout, *timeoutp; fd_set readfds, writefds; int noCApath = 0, noCAfile = 0, noCAstore = 0; int build_chain = 0, cert_format = FORMAT_UNDEF; size_t cbuf_len, cbuf_off; int key_format = FORMAT_UNDEF, crlf = 0, full_log = 1, mbuf_len = 0; int prexit = 0; int nointeractive = 0; int sdebug = 0; int reconnect = 0, verify = SSL_VERIFY_NONE, vpmtouched = 0; int ret = 1, in_init = 1, i, nbio_test = 0, sock = -1, k, width, state = 0; int sbuf_len, sbuf_off, cmdmode = USER_DATA_MODE_BASIC; int socket_family = AF_UNSPEC, socket_type = SOCK_STREAM, protocol = 0; int starttls_proto = PROTO_OFF, crl_format = FORMAT_UNDEF, crl_download = 0; int write_tty, read_tty, write_ssl, read_ssl, tty_on, ssl_pending; int first_loop; #if !defined(OPENSSL_SYS_WINDOWS) && !defined(OPENSSL_SYS_MSDOS) int at_eof = 0; #endif int read_buf_len = 0; int fallback_scsv = 0; OPTION_CHOICE o; #ifndef OPENSSL_NO_DTLS int enable_timeouts = 0; long socket_mtu = 0; #endif #ifndef OPENSSL_NO_ENGINE ENGINE *ssl_client_engine = NULL; #endif ENGINE *e = NULL; #if defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_MSDOS) struct timeval tv; #endif const char *servername = NULL; char *sname_alloc = NULL; int noservername = 0; const char *alpn_in = NULL; tlsextctx tlsextcbp = { NULL, 0 }; const char *ssl_config = NULL; #define MAX_SI_TYPES 100 unsigned short serverinfo_types[MAX_SI_TYPES]; int serverinfo_count = 0, start = 0, len; #ifndef OPENSSL_NO_NEXTPROTONEG const char *next_proto_neg_in = NULL; #endif #ifndef OPENSSL_NO_SRP char *srppass = NULL; int srp_lateuser = 0; SRP_ARG srp_arg = { NULL, NULL, 0, 0, 0, 1024 }; #endif #ifndef OPENSSL_NO_SRTP char *srtp_profiles = NULL; #endif #ifndef OPENSSL_NO_CT char *ctlog_file = NULL; int ct_validation = 0; #endif int min_version = 0, max_version = 0, prot_opt = 0, no_prot_opt = 0; int async = 0; unsigned int max_send_fragment = 0; unsigned int split_send_fragment = 0, max_pipelines = 0; enum { use_inet, use_unix, use_unknown } connect_type = use_unknown; int count4or6 = 0; uint8_t maxfraglen = 0; int c_nbio = 0, c_msg = 0, c_ign_eof = 0, c_brief = 0; int c_tlsextdebug = 0; #ifndef OPENSSL_NO_OCSP int c_status_req = 0; #endif BIO *bio_c_msg = NULL; const char *keylog_file = NULL, *early_data_file = NULL; int isdtls = 0, isquic = 0; char *psksessf = NULL; int enable_pha = 0; int enable_client_rpk = 0; #ifndef OPENSSL_NO_SCTP int sctp_label_bug = 0; #endif int ignore_unexpected_eof = 0; #ifndef OPENSSL_NO_KTLS int enable_ktls = 0; #endif int tfo = 0; int is_infinite; BIO_ADDR *peer_addr = NULL; struct user_data_st user_data; FD_ZERO(&readfds); FD_ZERO(&writefds); /* Known false-positive of MemorySanitizer. */ #if defined(__has_feature) # if __has_feature(memory_sanitizer) __msan_unpoison(&readfds, sizeof(readfds)); __msan_unpoison(&writefds, sizeof(writefds)); # endif #endif c_quiet = 0; c_debug = 0; c_showcerts = 0; c_nbio = 0; port = OPENSSL_strdup(PORT); vpm = X509_VERIFY_PARAM_new(); cctx = SSL_CONF_CTX_new(); if (port == NULL || vpm == NULL || cctx == NULL) { BIO_printf(bio_err, "%s: out of memory\n", opt_getprog()); goto end; } cbuf = app_malloc(BUFSIZZ, "cbuf"); sbuf = app_malloc(BUFSIZZ, "sbuf"); mbuf = app_malloc(BUFSIZZ, "mbuf"); SSL_CONF_CTX_set_flags(cctx, SSL_CONF_FLAG_CLIENT | SSL_CONF_FLAG_CMDLINE); prog = opt_init(argc, argv, s_client_options); while ((o = opt_next()) != OPT_EOF) { /* Check for intermixing flags. */ if (connect_type == use_unix && IS_INET_FLAG(o)) { BIO_printf(bio_err, "%s: Intermixed protocol flags (unix and internet domains)\n", prog); goto end; } if (connect_type == use_inet && IS_UNIX_FLAG(o)) { BIO_printf(bio_err, "%s: Intermixed protocol flags (internet and unix domains)\n", prog); goto end; } if (IS_PROT_FLAG(o) && ++prot_opt > 1) { BIO_printf(bio_err, "Cannot supply multiple protocol flags\n"); goto end; } if (IS_NO_PROT_FLAG(o)) no_prot_opt++; if (prot_opt == 1 && no_prot_opt) { BIO_printf(bio_err, "Cannot supply both a protocol flag and '-no_<prot>'\n"); goto end; } switch (o) { case OPT_EOF: case OPT_ERR: opthelp: BIO_printf(bio_err, "%s: Use -help for summary.\n", prog); goto end; case OPT_HELP: opt_help(s_client_options); ret = 0; goto end; case OPT_4: connect_type = use_inet; socket_family = AF_INET; count4or6++; break; #ifdef AF_INET6 case OPT_6: connect_type = use_inet; socket_family = AF_INET6; count4or6++; break; #endif case OPT_HOST: connect_type = use_inet; freeandcopy(&host, opt_arg()); break; case OPT_PORT: connect_type = use_inet; freeandcopy(&port, opt_arg()); break; case OPT_CONNECT: connect_type = use_inet; freeandcopy(&connectstr, opt_arg()); break; case OPT_BIND: freeandcopy(&bindstr, opt_arg()); break; case OPT_PROXY: proxystr = opt_arg(); break; case OPT_PROXY_USER: proxyuser = opt_arg(); break; case OPT_PROXY_PASS: proxypassarg = opt_arg(); break; #ifdef AF_UNIX case OPT_UNIX: connect_type = use_unix; socket_family = AF_UNIX; freeandcopy(&host, opt_arg()); break; #endif case OPT_XMPPHOST: /* fall through, since this is an alias */ case OPT_PROTOHOST: protohost = opt_arg(); break; case OPT_VERIFY: verify = SSL_VERIFY_PEER; verify_args.depth = atoi(opt_arg()); if (!c_quiet) BIO_printf(bio_err, "verify depth is %d\n", verify_args.depth); break; case OPT_CERT: cert_file = opt_arg(); break; case OPT_NAMEOPT: if (!set_nameopt(opt_arg())) goto end; break; case OPT_CRL: crl_file = opt_arg(); break; case OPT_CRL_DOWNLOAD: crl_download = 1; break; case OPT_SESS_OUT: sess_out = opt_arg(); break; case OPT_SESS_IN: sess_in = opt_arg(); break; case OPT_CERTFORM: if (!opt_format(opt_arg(), OPT_FMT_ANY, &cert_format)) goto opthelp; break; case OPT_CRLFORM: if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &crl_format)) goto opthelp; break; case OPT_VERIFY_RET_ERROR: verify = SSL_VERIFY_PEER; verify_args.return_error = 1; break; case OPT_VERIFY_QUIET: verify_args.quiet = 1; break; case OPT_BRIEF: c_brief = verify_args.quiet = c_quiet = 1; break; case OPT_S_CASES: if (ssl_args == NULL) ssl_args = sk_OPENSSL_STRING_new_null(); if (ssl_args == NULL || !sk_OPENSSL_STRING_push(ssl_args, opt_flag()) || !sk_OPENSSL_STRING_push(ssl_args, opt_arg())) { BIO_printf(bio_err, "%s: Memory allocation failure\n", prog); goto end; } break; case OPT_V_CASES: if (!opt_verify(o, vpm)) goto end; vpmtouched++; break; case OPT_X_CASES: if (!args_excert(o, &exc)) goto end; break; case OPT_IGNORE_UNEXPECTED_EOF: ignore_unexpected_eof = 1; break; case OPT_PREXIT: prexit = 1; break; case OPT_NO_INTERACTIVE: nointeractive = 1; break; case OPT_CRLF: crlf = 1; break; case OPT_QUIET: c_quiet = c_ign_eof = 1; break; case OPT_NBIO: c_nbio = 1; break; case OPT_NOCMDS: cmdmode = USER_DATA_MODE_NONE; break; case OPT_ADV: cmdmode = USER_DATA_MODE_ADVANCED; break; case OPT_ENGINE: e = setup_engine(opt_arg(), 1); break; case OPT_SSL_CLIENT_ENGINE: #ifndef OPENSSL_NO_ENGINE ssl_client_engine = setup_engine(opt_arg(), 0); if (ssl_client_engine == NULL) { BIO_printf(bio_err, "Error getting client auth engine\n"); goto opthelp; } #endif break; case OPT_R_CASES: if (!opt_rand(o)) goto end; break; case OPT_PROV_CASES: if (!opt_provider(o)) goto end; break; case OPT_IGN_EOF: c_ign_eof = 1; break; case OPT_NO_IGN_EOF: c_ign_eof = 0; break; case OPT_DEBUG: c_debug = 1; break; case OPT_TLSEXTDEBUG: c_tlsextdebug = 1; break; case OPT_STATUS: #ifndef OPENSSL_NO_OCSP c_status_req = 1; #endif break; case OPT_WDEBUG: #ifdef WATT32 dbug_init(); #endif break; case OPT_MSG: c_msg = 1; break; case OPT_MSGFILE: bio_c_msg = BIO_new_file(opt_arg(), "w"); if (bio_c_msg == NULL) { BIO_printf(bio_err, "Error writing file %s\n", opt_arg()); goto end; } break; case OPT_TRACE: #ifndef OPENSSL_NO_SSL_TRACE c_msg = 2; #endif break; case OPT_SECURITY_DEBUG: sdebug = 1; break; case OPT_SECURITY_DEBUG_VERBOSE: sdebug = 2; break; case OPT_SHOWCERTS: c_showcerts = 1; break; case OPT_NBIO_TEST: nbio_test = 1; break; case OPT_STATE: state = 1; break; case OPT_PSK_IDENTITY: psk_identity = opt_arg(); break; case OPT_PSK: for (p = psk_key = opt_arg(); *p; p++) { if (isxdigit(_UC(*p))) continue; BIO_printf(bio_err, "Not a hex number '%s'\n", psk_key); goto end; } break; case OPT_PSK_SESS: psksessf = opt_arg(); break; #ifndef OPENSSL_NO_SRP case OPT_SRPUSER: srp_arg.srplogin = opt_arg(); if (min_version < TLS1_VERSION) min_version = TLS1_VERSION; break; case OPT_SRPPASS: srppass = opt_arg(); if (min_version < TLS1_VERSION) min_version = TLS1_VERSION; break; case OPT_SRP_STRENGTH: srp_arg.strength = atoi(opt_arg()); BIO_printf(bio_err, "SRP minimal length for N is %d\n", srp_arg.strength); if (min_version < TLS1_VERSION) min_version = TLS1_VERSION; break; case OPT_SRP_LATEUSER: srp_lateuser = 1; if (min_version < TLS1_VERSION) min_version = TLS1_VERSION; break; case OPT_SRP_MOREGROUPS: srp_arg.amp = 1; if (min_version < TLS1_VERSION) min_version = TLS1_VERSION; break; #endif case OPT_SSL_CONFIG: ssl_config = opt_arg(); break; case OPT_SSL3: min_version = SSL3_VERSION; max_version = SSL3_VERSION; socket_type = SOCK_STREAM; #ifndef OPENSSL_NO_DTLS isdtls = 0; #endif isquic = 0; break; case OPT_TLS1_3: min_version = TLS1_3_VERSION; max_version = TLS1_3_VERSION; socket_type = SOCK_STREAM; #ifndef OPENSSL_NO_DTLS isdtls = 0; #endif isquic = 0; break; case OPT_TLS1_2: min_version = TLS1_2_VERSION; max_version = TLS1_2_VERSION; socket_type = SOCK_STREAM; #ifndef OPENSSL_NO_DTLS isdtls = 0; #endif isquic = 0; break; case OPT_TLS1_1: min_version = TLS1_1_VERSION; max_version = TLS1_1_VERSION; socket_type = SOCK_STREAM; #ifndef OPENSSL_NO_DTLS isdtls = 0; #endif isquic = 0; break; case OPT_TLS1: min_version = TLS1_VERSION; max_version = TLS1_VERSION; socket_type = SOCK_STREAM; #ifndef OPENSSL_NO_DTLS isdtls = 0; #endif isquic = 0; break; case OPT_DTLS: #ifndef OPENSSL_NO_DTLS meth = DTLS_client_method(); socket_type = SOCK_DGRAM; isdtls = 1; isquic = 0; #endif break; case OPT_DTLS1: #ifndef OPENSSL_NO_DTLS1 meth = DTLS_client_method(); min_version = DTLS1_VERSION; max_version = DTLS1_VERSION; socket_type = SOCK_DGRAM; isdtls = 1; isquic = 0; #endif break; case OPT_DTLS1_2: #ifndef OPENSSL_NO_DTLS1_2 meth = DTLS_client_method(); min_version = DTLS1_2_VERSION; max_version = DTLS1_2_VERSION; socket_type = SOCK_DGRAM; isdtls = 1; isquic = 0; #endif break; case OPT_QUIC: #ifndef OPENSSL_NO_QUIC meth = OSSL_QUIC_client_method(); min_version = 0; max_version = 0; socket_type = SOCK_DGRAM; # ifndef OPENSSL_NO_DTLS isdtls = 0; # endif isquic = 1; #endif break; case OPT_SCTP: #ifndef OPENSSL_NO_SCTP protocol = IPPROTO_SCTP; #endif break; case OPT_SCTP_LABEL_BUG: #ifndef OPENSSL_NO_SCTP sctp_label_bug = 1; #endif break; case OPT_TIMEOUT: #ifndef OPENSSL_NO_DTLS enable_timeouts = 1; #endif break; case OPT_MTU: #ifndef OPENSSL_NO_DTLS socket_mtu = atol(opt_arg()); #endif break; case OPT_FALLBACKSCSV: fallback_scsv = 1; break; case OPT_KEYFORM: if (!opt_format(opt_arg(), OPT_FMT_ANY, &key_format)) goto opthelp; break; case OPT_PASS: passarg = opt_arg(); break; case OPT_CERT_CHAIN: chain_file = opt_arg(); break; case OPT_KEY: key_file = opt_arg(); break; case OPT_RECONNECT: reconnect = 5; break; case OPT_CAPATH: CApath = opt_arg(); break; case OPT_NOCAPATH: noCApath = 1; break; case OPT_CHAINCAPATH: chCApath = opt_arg(); break; case OPT_VERIFYCAPATH: vfyCApath = opt_arg(); break; case OPT_BUILD_CHAIN: build_chain = 1; break; case OPT_REQCAFILE: ReqCAfile = opt_arg(); break; case OPT_CAFILE: CAfile = opt_arg(); break; case OPT_NOCAFILE: noCAfile = 1; break; #ifndef OPENSSL_NO_CT case OPT_NOCT: ct_validation = 0; break; case OPT_CT: ct_validation = 1; break; case OPT_CTLOG_FILE: ctlog_file = opt_arg(); break; #endif case OPT_CHAINCAFILE: chCAfile = opt_arg(); break; case OPT_VERIFYCAFILE: vfyCAfile = opt_arg(); break; case OPT_CASTORE: CAstore = opt_arg(); break; case OPT_NOCASTORE: noCAstore = 1; break; case OPT_CHAINCASTORE: chCAstore = opt_arg(); break; case OPT_VERIFYCASTORE: vfyCAstore = opt_arg(); break; case OPT_DANE_TLSA_DOMAIN: dane_tlsa_domain = opt_arg(); break; case OPT_DANE_TLSA_RRDATA: if (dane_tlsa_rrset == NULL) dane_tlsa_rrset = sk_OPENSSL_STRING_new_null(); if (dane_tlsa_rrset == NULL || !sk_OPENSSL_STRING_push(dane_tlsa_rrset, opt_arg())) { BIO_printf(bio_err, "%s: Memory allocation failure\n", prog); goto end; } break; case OPT_DANE_EE_NO_NAME: dane_ee_no_name = 1; break; case OPT_NEXTPROTONEG: #ifndef OPENSSL_NO_NEXTPROTONEG next_proto_neg_in = opt_arg(); #endif break; case OPT_ALPN: alpn_in = opt_arg(); break; case OPT_SERVERINFO: p = opt_arg(); len = strlen(p); for (start = 0, i = 0; i <= len; ++i) { if (i == len || p[i] == ',') { serverinfo_types[serverinfo_count] = atoi(p + start); if (++serverinfo_count == MAX_SI_TYPES) break; start = i + 1; } } break; case OPT_STARTTLS: if (!opt_pair(opt_arg(), services, &starttls_proto)) goto end; break; case OPT_TFO: tfo = 1; break; case OPT_SERVERNAME: servername = opt_arg(); break; case OPT_NOSERVERNAME: noservername = 1; break; case OPT_USE_SRTP: #ifndef OPENSSL_NO_SRTP srtp_profiles = opt_arg(); #endif break; case OPT_KEYMATEXPORT: keymatexportlabel = opt_arg(); break; case OPT_KEYMATEXPORTLEN: keymatexportlen = atoi(opt_arg()); break; case OPT_ASYNC: async = 1; break; case OPT_MAXFRAGLEN: len = atoi(opt_arg()); switch (len) { case 512: maxfraglen = TLSEXT_max_fragment_length_512; break; case 1024: maxfraglen = TLSEXT_max_fragment_length_1024; break; case 2048: maxfraglen = TLSEXT_max_fragment_length_2048; break; case 4096: maxfraglen = TLSEXT_max_fragment_length_4096; break; default: BIO_printf(bio_err, "%s: Max Fragment Len %u is out of permitted values", prog, len); goto opthelp; } break; case OPT_MAX_SEND_FRAG: max_send_fragment = atoi(opt_arg()); break; case OPT_SPLIT_SEND_FRAG: split_send_fragment = atoi(opt_arg()); break; case OPT_MAX_PIPELINES: max_pipelines = atoi(opt_arg()); break; case OPT_READ_BUF: read_buf_len = atoi(opt_arg()); break; case OPT_KEYLOG_FILE: keylog_file = opt_arg(); break; case OPT_EARLY_DATA: early_data_file = opt_arg(); break; case OPT_ENABLE_PHA: enable_pha = 1; break; case OPT_KTLS: #ifndef OPENSSL_NO_KTLS enable_ktls = 1; #endif break; case OPT_ENABLE_SERVER_RPK: enable_server_rpk = 1; break; case OPT_ENABLE_CLIENT_RPK: enable_client_rpk = 1; break; } } /* Optional argument is connect string if -connect not used. */ if (opt_num_rest() == 1) { /* Don't allow -connect and a separate argument. */ if (connectstr != NULL) { BIO_printf(bio_err, "%s: cannot provide both -connect option and target parameter\n", prog); goto opthelp; } connect_type = use_inet; freeandcopy(&connectstr, *opt_rest()); } else if (!opt_check_rest_arg(NULL)) { goto opthelp; } if (!app_RAND_load()) goto end; if (c_ign_eof) cmdmode = USER_DATA_MODE_NONE; if (count4or6 >= 2) { BIO_printf(bio_err, "%s: Can't use both -4 and -6\n", prog); goto opthelp; } if (noservername) { if (servername != NULL) { BIO_printf(bio_err, "%s: Can't use -servername and -noservername together\n", prog); goto opthelp; } if (dane_tlsa_domain != NULL) { BIO_printf(bio_err, "%s: Can't use -dane_tlsa_domain and -noservername together\n", prog); goto opthelp; } } #ifndef OPENSSL_NO_NEXTPROTONEG if (min_version == TLS1_3_VERSION && next_proto_neg_in != NULL) { BIO_printf(bio_err, "Cannot supply -nextprotoneg with TLSv1.3\n"); goto opthelp; } #endif if (connectstr != NULL) { int res; char *tmp_host = host, *tmp_port = port; res = BIO_parse_hostserv(connectstr, &host, &port, BIO_PARSE_PRIO_HOST); if (tmp_host != host) OPENSSL_free(tmp_host); if (tmp_port != port) OPENSSL_free(tmp_port); if (!res) { BIO_printf(bio_err, "%s: -connect argument or target parameter malformed or ambiguous\n", prog); goto end; } } if (proxystr != NULL) { #ifndef OPENSSL_NO_HTTP int res; char *tmp_host = host, *tmp_port = port; if (host == NULL || port == NULL) { BIO_printf(bio_err, "%s: -proxy requires use of -connect or target parameter\n", prog); goto opthelp; } if (servername == NULL && !noservername) { servername = sname_alloc = OPENSSL_strdup(host); if (sname_alloc == NULL) { BIO_printf(bio_err, "%s: out of memory\n", prog); goto end; } } /* Retain the original target host:port for use in the HTTP proxy connect string */ thost = OPENSSL_strdup(host); tport = OPENSSL_strdup(port); if (thost == NULL || tport == NULL) { BIO_printf(bio_err, "%s: out of memory\n", prog); goto end; } res = BIO_parse_hostserv(proxystr, &host, &port, BIO_PARSE_PRIO_HOST); if (tmp_host != host) OPENSSL_free(tmp_host); if (tmp_port != port) OPENSSL_free(tmp_port); if (!res) { BIO_printf(bio_err, "%s: -proxy argument malformed or ambiguous\n", prog); goto end; } #else BIO_printf(bio_err, "%s: -proxy not supported in no-http build\n", prog); goto end; #endif } if (bindstr != NULL) { int res; res = BIO_parse_hostserv(bindstr, &bindhost, &bindport, BIO_PARSE_PRIO_HOST); if (!res) { BIO_printf(bio_err, "%s: -bind argument parameter malformed or ambiguous\n", prog); goto end; } } #ifdef AF_UNIX if (socket_family == AF_UNIX && socket_type != SOCK_STREAM) { BIO_printf(bio_err, "Can't use unix sockets and datagrams together\n"); goto end; } #endif #ifndef OPENSSL_NO_SCTP if (protocol == IPPROTO_SCTP) { if (socket_type != SOCK_DGRAM) { BIO_printf(bio_err, "Can't use -sctp without DTLS\n"); goto end; } /* SCTP is unusual. It uses DTLS over a SOCK_STREAM protocol */ socket_type = SOCK_STREAM; } #endif #if !defined(OPENSSL_NO_NEXTPROTONEG) next_proto.status = -1; if (next_proto_neg_in) { next_proto.data = next_protos_parse(&next_proto.len, next_proto_neg_in); if (next_proto.data == NULL) { BIO_printf(bio_err, "Error parsing -nextprotoneg argument\n"); goto end; } } else next_proto.data = NULL; #endif if (!app_passwd(passarg, NULL, &pass, NULL)) { BIO_printf(bio_err, "Error getting private key password\n"); goto end; } if (!app_passwd(proxypassarg, NULL, &proxypass, NULL)) { BIO_printf(bio_err, "Error getting proxy password\n"); goto end; } if (proxypass != NULL && proxyuser == NULL) { BIO_printf(bio_err, "Error: Must specify proxy_user with proxy_pass\n"); goto end; } if (key_file == NULL) key_file = cert_file; if (key_file != NULL) { key = load_key(key_file, key_format, 0, pass, e, "client certificate private key"); if (key == NULL) goto end; } if (cert_file != NULL) { cert = load_cert_pass(cert_file, cert_format, 1, pass, "client certificate"); if (cert == NULL) goto end; } if (chain_file != NULL) { if (!load_certs(chain_file, 0, &chain, pass, "client certificate chain")) goto end; } if (crl_file != NULL) { X509_CRL *crl; crl = load_crl(crl_file, crl_format, 0, "CRL"); if (crl == NULL) goto end; crls = sk_X509_CRL_new_null(); if (crls == NULL || !sk_X509_CRL_push(crls, crl)) { BIO_puts(bio_err, "Error adding CRL\n"); ERR_print_errors(bio_err); X509_CRL_free(crl); goto end; } } if (!load_excert(&exc)) goto end; if (bio_c_out == NULL) { if (c_quiet && !c_debug) { bio_c_out = BIO_new(BIO_s_null()); if (c_msg && bio_c_msg == NULL) { bio_c_msg = dup_bio_out(FORMAT_TEXT); if (bio_c_msg == NULL) { BIO_printf(bio_err, "Out of memory\n"); goto end; } } } else { bio_c_out = dup_bio_out(FORMAT_TEXT); } if (bio_c_out == NULL) { BIO_printf(bio_err, "Unable to create BIO\n"); goto end; } } #ifndef OPENSSL_NO_SRP if (!app_passwd(srppass, NULL, &srp_arg.srppassin, NULL)) { BIO_printf(bio_err, "Error getting password\n"); goto end; } #endif ctx = SSL_CTX_new_ex(app_get0_libctx(), app_get0_propq(), meth); if (ctx == NULL) { ERR_print_errors(bio_err); goto end; } SSL_CTX_clear_mode(ctx, SSL_MODE_AUTO_RETRY); if (sdebug) ssl_ctx_security_debug(ctx, sdebug); if (!config_ctx(cctx, ssl_args, ctx)) goto end; if (ssl_config != NULL) { if (SSL_CTX_config(ctx, ssl_config) == 0) { BIO_printf(bio_err, "Error using configuration \"%s\"\n", ssl_config); ERR_print_errors(bio_err); goto end; } } #ifndef OPENSSL_NO_SCTP if (protocol == IPPROTO_SCTP && sctp_label_bug == 1) SSL_CTX_set_mode(ctx, SSL_MODE_DTLS_SCTP_LABEL_LENGTH_BUG); #endif if (min_version != 0 && SSL_CTX_set_min_proto_version(ctx, min_version) == 0) goto end; if (max_version != 0 && SSL_CTX_set_max_proto_version(ctx, max_version) == 0) goto end; if (ignore_unexpected_eof) SSL_CTX_set_options(ctx, SSL_OP_IGNORE_UNEXPECTED_EOF); #ifndef OPENSSL_NO_KTLS if (enable_ktls) SSL_CTX_set_options(ctx, SSL_OP_ENABLE_KTLS); #endif if (vpmtouched && !SSL_CTX_set1_param(ctx, vpm)) { BIO_printf(bio_err, "Error setting verify params\n"); ERR_print_errors(bio_err); goto end; } if (async) { SSL_CTX_set_mode(ctx, SSL_MODE_ASYNC); } if (max_send_fragment > 0 && !SSL_CTX_set_max_send_fragment(ctx, max_send_fragment)) { BIO_printf(bio_err, "%s: Max send fragment size %u is out of permitted range\n", prog, max_send_fragment); goto end; } if (split_send_fragment > 0 && !SSL_CTX_set_split_send_fragment(ctx, split_send_fragment)) { BIO_printf(bio_err, "%s: Split send fragment size %u is out of permitted range\n", prog, split_send_fragment); goto end; } if (max_pipelines > 0 && !SSL_CTX_set_max_pipelines(ctx, max_pipelines)) { BIO_printf(bio_err, "%s: Max pipelines %u is out of permitted range\n", prog, max_pipelines); goto end; } if (read_buf_len > 0) { SSL_CTX_set_default_read_buffer_len(ctx, read_buf_len); } if (maxfraglen > 0 && !SSL_CTX_set_tlsext_max_fragment_length(ctx, maxfraglen)) { BIO_printf(bio_err, "%s: Max Fragment Length code %u is out of permitted values" "\n", prog, maxfraglen); goto end; } if (!ssl_load_stores(ctx, vfyCApath, vfyCAfile, vfyCAstore, chCApath, chCAfile, chCAstore, crls, crl_download)) { BIO_printf(bio_err, "Error loading store locations\n"); ERR_print_errors(bio_err); goto end; } if (ReqCAfile != NULL) { STACK_OF(X509_NAME) *nm = sk_X509_NAME_new_null(); if (nm == NULL || !SSL_add_file_cert_subjects_to_stack(nm, ReqCAfile)) { sk_X509_NAME_pop_free(nm, X509_NAME_free); BIO_printf(bio_err, "Error loading CA names\n"); ERR_print_errors(bio_err); goto end; } SSL_CTX_set0_CA_list(ctx, nm); } #ifndef OPENSSL_NO_ENGINE if (ssl_client_engine) { if (!SSL_CTX_set_client_cert_engine(ctx, ssl_client_engine)) { BIO_puts(bio_err, "Error setting client auth engine\n"); ERR_print_errors(bio_err); release_engine(ssl_client_engine); goto end; } release_engine(ssl_client_engine); } #endif #ifndef OPENSSL_NO_PSK if (psk_key != NULL) { if (c_debug) BIO_printf(bio_c_out, "PSK key given, setting client callback\n"); SSL_CTX_set_psk_client_callback(ctx, psk_client_cb); } #endif if (psksessf != NULL) { BIO *stmp = BIO_new_file(psksessf, "r"); if (stmp == NULL) { BIO_printf(bio_err, "Can't open PSK session file %s\n", psksessf); ERR_print_errors(bio_err); goto end; } psksess = PEM_read_bio_SSL_SESSION(stmp, NULL, 0, NULL); BIO_free(stmp); if (psksess == NULL) { BIO_printf(bio_err, "Can't read PSK session file %s\n", psksessf); ERR_print_errors(bio_err); goto end; } } if (psk_key != NULL || psksess != NULL) SSL_CTX_set_psk_use_session_callback(ctx, psk_use_session_cb); #ifndef OPENSSL_NO_SRTP if (srtp_profiles != NULL) { /* Returns 0 on success! */ if (SSL_CTX_set_tlsext_use_srtp(ctx, srtp_profiles) != 0) { BIO_printf(bio_err, "Error setting SRTP profile\n"); ERR_print_errors(bio_err); goto end; } } #endif if (exc != NULL) ssl_ctx_set_excert(ctx, exc); #if !defined(OPENSSL_NO_NEXTPROTONEG) if (next_proto.data != NULL) SSL_CTX_set_next_proto_select_cb(ctx, next_proto_cb, &next_proto); #endif if (alpn_in) { size_t alpn_len; unsigned char *alpn = next_protos_parse(&alpn_len, alpn_in); if (alpn == NULL) { BIO_printf(bio_err, "Error parsing -alpn argument\n"); goto end; } /* Returns 0 on success! */ if (SSL_CTX_set_alpn_protos(ctx, alpn, alpn_len) != 0) { BIO_printf(bio_err, "Error setting ALPN\n"); goto end; } OPENSSL_free(alpn); } for (i = 0; i < serverinfo_count; i++) { if (!SSL_CTX_add_client_custom_ext(ctx, serverinfo_types[i], NULL, NULL, NULL, serverinfo_cli_parse_cb, NULL)) { BIO_printf(bio_err, "Warning: Unable to add custom extension %u, skipping\n", serverinfo_types[i]); } } if (state) SSL_CTX_set_info_callback(ctx, apps_ssl_info_callback); #ifndef OPENSSL_NO_CT /* Enable SCT processing, without early connection termination */ if (ct_validation && !SSL_CTX_enable_ct(ctx, SSL_CT_VALIDATION_PERMISSIVE)) { ERR_print_errors(bio_err); goto end; } if (!ctx_set_ctlog_list_file(ctx, ctlog_file)) { if (ct_validation) { ERR_print_errors(bio_err); goto end; } /* * If CT validation is not enabled, the log list isn't needed so don't * show errors or abort. We try to load it regardless because then we * can show the names of the logs any SCTs came from (SCTs may be seen * even with validation disabled). */ ERR_clear_error(); } #endif SSL_CTX_set_verify(ctx, verify, verify_callback); if (!ctx_set_verify_locations(ctx, CAfile, noCAfile, CApath, noCApath, CAstore, noCAstore)) { ERR_print_errors(bio_err); goto end; } ssl_ctx_add_crls(ctx, crls, crl_download); if (!set_cert_key_stuff(ctx, cert, key, chain, build_chain)) goto end; if (!noservername) { tlsextcbp.biodebug = bio_err; SSL_CTX_set_tlsext_servername_callback(ctx, ssl_servername_cb); SSL_CTX_set_tlsext_servername_arg(ctx, &tlsextcbp); } #ifndef OPENSSL_NO_SRP if (srp_arg.srplogin != NULL && !set_up_srp_arg(ctx, &srp_arg, srp_lateuser, c_msg, c_debug)) goto end; # endif if (dane_tlsa_domain != NULL) { if (SSL_CTX_dane_enable(ctx) <= 0) { BIO_printf(bio_err, "%s: Error enabling DANE TLSA authentication.\n", prog); ERR_print_errors(bio_err); goto end; } } /* * In TLSv1.3 NewSessionTicket messages arrive after the handshake and can * come at any time. Therefore, we use a callback to write out the session * when we know about it. This approach works for < TLSv1.3 as well. */ SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_CLIENT | SSL_SESS_CACHE_NO_INTERNAL_STORE); SSL_CTX_sess_set_new_cb(ctx, new_session_cb); if (set_keylog_file(ctx, keylog_file)) goto end; con = SSL_new(ctx); if (con == NULL) goto end; if (enable_pha) SSL_set_post_handshake_auth(con, 1); if (enable_client_rpk) if (!SSL_set1_client_cert_type(con, cert_type_rpk, sizeof(cert_type_rpk))) { BIO_printf(bio_err, "Error setting client certificate types\n"); goto end; } if (enable_server_rpk) { if (!SSL_set1_server_cert_type(con, cert_type_rpk, sizeof(cert_type_rpk))) { BIO_printf(bio_err, "Error setting server certificate types\n"); goto end; } } if (sess_in != NULL) { SSL_SESSION *sess; BIO *stmp = BIO_new_file(sess_in, "r"); if (stmp == NULL) { BIO_printf(bio_err, "Can't open session file %s\n", sess_in); ERR_print_errors(bio_err); goto end; } sess = PEM_read_bio_SSL_SESSION(stmp, NULL, 0, NULL); BIO_free(stmp); if (sess == NULL) { BIO_printf(bio_err, "Can't open session file %s\n", sess_in); ERR_print_errors(bio_err); goto end; } if (!SSL_set_session(con, sess)) { BIO_printf(bio_err, "Can't set session\n"); ERR_print_errors(bio_err); goto end; } SSL_SESSION_free(sess); } if (fallback_scsv) SSL_set_mode(con, SSL_MODE_SEND_FALLBACK_SCSV); if (!noservername && (servername != NULL || dane_tlsa_domain == NULL)) { if (servername == NULL) { if (host == NULL || is_dNS_name(host)) servername = (host == NULL) ? "localhost" : host; } if (servername != NULL && !SSL_set_tlsext_host_name(con, servername)) { BIO_printf(bio_err, "Unable to set TLS servername extension.\n"); ERR_print_errors(bio_err); goto end; } } if (dane_tlsa_domain != NULL) { if (SSL_dane_enable(con, dane_tlsa_domain) <= 0) { BIO_printf(bio_err, "%s: Error enabling DANE TLSA " "authentication.\n", prog); ERR_print_errors(bio_err); goto end; } if (dane_tlsa_rrset == NULL) { BIO_printf(bio_err, "%s: DANE TLSA authentication requires at " "least one -dane_tlsa_rrdata option.\n", prog); goto end; } if (tlsa_import_rrset(con, dane_tlsa_rrset) <= 0) { BIO_printf(bio_err, "%s: Failed to import any TLSA " "records.\n", prog); goto end; } if (dane_ee_no_name) SSL_dane_set_flags(con, DANE_FLAG_NO_DANE_EE_NAMECHECKS); } else if (dane_tlsa_rrset != NULL) { BIO_printf(bio_err, "%s: DANE TLSA authentication requires the " "-dane_tlsa_domain option.\n", prog); goto end; } #ifndef OPENSSL_NO_DTLS if (isdtls && tfo) { BIO_printf(bio_err, "%s: DTLS does not support the -tfo option\n", prog); goto end; } #endif #ifndef OPENSSL_NO_QUIC if (isquic && tfo) { BIO_printf(bio_err, "%s: QUIC does not support the -tfo option\n", prog); goto end; } if (isquic && alpn_in == NULL) { BIO_printf(bio_err, "%s: QUIC requires ALPN to be specified (e.g. \"h3\" for HTTP/3) via the -alpn option\n", prog); goto end; } #endif if (tfo) BIO_printf(bio_c_out, "Connecting via TFO\n"); re_start: if (init_client(&sock, host, port, bindhost, bindport, socket_family, socket_type, protocol, tfo, !isquic, &peer_addr) == 0) { BIO_printf(bio_err, "connect:errno=%d\n", get_last_socket_error()); BIO_closesocket(sock); goto end; } BIO_printf(bio_c_out, "CONNECTED(%08X)\n", sock); /* * QUIC always uses a non-blocking socket - and we have to switch on * non-blocking mode at the SSL level */ if (c_nbio || isquic) { if (!BIO_socket_nbio(sock, 1)) { ERR_print_errors(bio_err); goto end; } if (c_nbio) { if (isquic && !SSL_set_blocking_mode(con, 0)) goto end; BIO_printf(bio_c_out, "Turned on non blocking io\n"); } } #ifndef OPENSSL_NO_DTLS if (isdtls) { union BIO_sock_info_u peer_info; #ifndef OPENSSL_NO_SCTP if (protocol == IPPROTO_SCTP) sbio = BIO_new_dgram_sctp(sock, BIO_NOCLOSE); else #endif sbio = BIO_new_dgram(sock, BIO_NOCLOSE); if (sbio == NULL || (peer_info.addr = BIO_ADDR_new()) == NULL) { BIO_printf(bio_err, "memory allocation failure\n"); BIO_free(sbio); BIO_closesocket(sock); goto end; } if (!BIO_sock_info(sock, BIO_SOCK_INFO_ADDRESS, &peer_info)) { BIO_printf(bio_err, "getsockname:errno=%d\n", get_last_socket_error()); BIO_free(sbio); BIO_ADDR_free(peer_info.addr); BIO_closesocket(sock); goto end; } (void)BIO_ctrl_set_connected(sbio, peer_info.addr); BIO_ADDR_free(peer_info.addr); peer_info.addr = NULL; if (enable_timeouts) { timeout.tv_sec = 0; timeout.tv_usec = DGRAM_RCV_TIMEOUT; BIO_ctrl(sbio, BIO_CTRL_DGRAM_SET_RECV_TIMEOUT, 0, &timeout); timeout.tv_sec = 0; timeout.tv_usec = DGRAM_SND_TIMEOUT; BIO_ctrl(sbio, BIO_CTRL_DGRAM_SET_SEND_TIMEOUT, 0, &timeout); } if (socket_mtu) { if (socket_mtu < DTLS_get_link_min_mtu(con)) { BIO_printf(bio_err, "MTU too small. Must be at least %ld\n", DTLS_get_link_min_mtu(con)); BIO_free(sbio); goto shut; } SSL_set_options(con, SSL_OP_NO_QUERY_MTU); if (!DTLS_set_link_mtu(con, socket_mtu)) { BIO_printf(bio_err, "Failed to set MTU\n"); BIO_free(sbio); goto shut; } } else { /* want to do MTU discovery */ BIO_ctrl(sbio, BIO_CTRL_DGRAM_MTU_DISCOVER, 0, NULL); } } else #endif /* OPENSSL_NO_DTLS */ #ifndef OPENSSL_NO_QUIC if (isquic) { sbio = BIO_new_dgram(sock, BIO_NOCLOSE); if (!SSL_set1_initial_peer_addr(con, peer_addr)) { BIO_printf(bio_err, "Failed to set the initial peer address\n"); goto shut; } } else #endif sbio = BIO_new_socket(sock, BIO_NOCLOSE); if (sbio == NULL) { BIO_printf(bio_err, "Unable to create BIO\n"); ERR_print_errors(bio_err); BIO_closesocket(sock); goto end; } /* Now that we're using a BIO... */ if (tfo) { (void)BIO_set_conn_address(sbio, peer_addr); (void)BIO_set_tfo(sbio, 1); } if (nbio_test) { BIO *test; test = BIO_new(BIO_f_nbio_test()); if (test == NULL) { BIO_printf(bio_err, "Unable to create BIO\n"); BIO_free(sbio); goto shut; } sbio = BIO_push(test, sbio); } if (c_debug) { BIO_set_callback_ex(sbio, bio_dump_callback); BIO_set_callback_arg(sbio, (char *)bio_c_out); } if (c_msg) { #ifndef OPENSSL_NO_SSL_TRACE if (c_msg == 2) SSL_set_msg_callback(con, SSL_trace); else #endif SSL_set_msg_callback(con, msg_cb); SSL_set_msg_callback_arg(con, bio_c_msg ? bio_c_msg : bio_c_out); } if (c_tlsextdebug) { SSL_set_tlsext_debug_callback(con, tlsext_cb); SSL_set_tlsext_debug_arg(con, bio_c_out); } #ifndef OPENSSL_NO_OCSP if (c_status_req) { SSL_set_tlsext_status_type(con, TLSEXT_STATUSTYPE_ocsp); SSL_CTX_set_tlsext_status_cb(ctx, ocsp_resp_cb); SSL_CTX_set_tlsext_status_arg(ctx, bio_c_out); } #endif SSL_set_bio(con, sbio, sbio); SSL_set_connect_state(con); /* ok, lets connect */ if (fileno_stdin() > SSL_get_fd(con)) width = fileno_stdin() + 1; else width = SSL_get_fd(con) + 1; read_tty = 1; write_tty = 0; tty_on = 0; read_ssl = 1; write_ssl = 1; first_loop = 1; cbuf_len = 0; cbuf_off = 0; sbuf_len = 0; sbuf_off = 0; #ifndef OPENSSL_NO_HTTP if (proxystr != NULL) { /* Here we must use the connect string target host & port */ if (!OSSL_HTTP_proxy_connect(sbio, thost, tport, proxyuser, proxypass, 0 /* no timeout */, bio_err, prog)) goto shut; } #endif switch ((PROTOCOL_CHOICE) starttls_proto) { case PROTO_OFF: break; case PROTO_LMTP: case PROTO_SMTP: { /* * This is an ugly hack that does a lot of assumptions. We do * have to handle multi-line responses which may come in a single * packet or not. We therefore have to use BIO_gets() which does * need a buffering BIO. So during the initial chitchat we do * push a buffering BIO into the chain that is removed again * later on to not disturb the rest of the s_client operation. */ int foundit = 0; BIO *fbio = BIO_new(BIO_f_buffer()); if (fbio == NULL) { BIO_printf(bio_err, "Unable to create BIO\n"); goto shut; } BIO_push(fbio, sbio); /* Wait for multi-line response to end from LMTP or SMTP */ do { mbuf_len = BIO_gets(fbio, mbuf, BUFSIZZ); } while (mbuf_len > 3 && mbuf[3] == '-'); if (protohost == NULL) protohost = "mail.example.com"; if (starttls_proto == (int)PROTO_LMTP) BIO_printf(fbio, "LHLO %s\r\n", protohost); else BIO_printf(fbio, "EHLO %s\r\n", protohost); (void)BIO_flush(fbio); /* * Wait for multi-line response to end LHLO LMTP or EHLO SMTP * response. */ do { mbuf_len = BIO_gets(fbio, mbuf, BUFSIZZ); if (strstr(mbuf, "STARTTLS")) foundit = 1; } while (mbuf_len > 3 && mbuf[3] == '-'); (void)BIO_flush(fbio); BIO_pop(fbio); BIO_free(fbio); if (!foundit) BIO_printf(bio_err, "Didn't find STARTTLS in server response," " trying anyway...\n"); BIO_printf(sbio, "STARTTLS\r\n"); BIO_read(sbio, sbuf, BUFSIZZ); } break; case PROTO_POP3: { BIO_read(sbio, mbuf, BUFSIZZ); BIO_printf(sbio, "STLS\r\n"); mbuf_len = BIO_read(sbio, sbuf, BUFSIZZ); if (mbuf_len < 0) { BIO_printf(bio_err, "BIO_read failed\n"); goto end; } } break; case PROTO_IMAP: { int foundit = 0; BIO *fbio = BIO_new(BIO_f_buffer()); if (fbio == NULL) { BIO_printf(bio_err, "Unable to create BIO\n"); goto shut; } BIO_push(fbio, sbio); BIO_gets(fbio, mbuf, BUFSIZZ); /* STARTTLS command requires CAPABILITY... */ BIO_printf(fbio, ". CAPABILITY\r\n"); (void)BIO_flush(fbio); /* wait for multi-line CAPABILITY response */ do { mbuf_len = BIO_gets(fbio, mbuf, BUFSIZZ); if (strstr(mbuf, "STARTTLS")) foundit = 1; } while (mbuf_len > 3 && mbuf[0] != '.'); (void)BIO_flush(fbio); BIO_pop(fbio); BIO_free(fbio); if (!foundit) BIO_printf(bio_err, "Didn't find STARTTLS in server response," " trying anyway...\n"); BIO_printf(sbio, ". STARTTLS\r\n"); BIO_read(sbio, sbuf, BUFSIZZ); } break; case PROTO_FTP: { BIO *fbio = BIO_new(BIO_f_buffer()); if (fbio == NULL) { BIO_printf(bio_err, "Unable to create BIO\n"); goto shut; } BIO_push(fbio, sbio); /* wait for multi-line response to end from FTP */ do { mbuf_len = BIO_gets(fbio, mbuf, BUFSIZZ); } while (mbuf_len > 3 && (!isdigit((unsigned char)mbuf[0]) || !isdigit((unsigned char)mbuf[1]) || !isdigit((unsigned char)mbuf[2]) || mbuf[3] != ' ')); (void)BIO_flush(fbio); BIO_pop(fbio); BIO_free(fbio); BIO_printf(sbio, "AUTH TLS\r\n"); BIO_read(sbio, sbuf, BUFSIZZ); } break; case PROTO_XMPP: case PROTO_XMPP_SERVER: { int seen = 0; BIO_printf(sbio, "<stream:stream " "xmlns:stream='http://etherx.jabber.org/streams' " "xmlns='jabber:%s' to='%s' version='1.0'>", starttls_proto == PROTO_XMPP ? "client" : "server", protohost ? protohost : host); seen = BIO_read(sbio, mbuf, BUFSIZZ); if (seen < 0) { BIO_printf(bio_err, "BIO_read failed\n"); goto end; } mbuf[seen] = '\0'; while (!strstr (mbuf, "<starttls xmlns='urn:ietf:params:xml:ns:xmpp-tls'") && !strstr(mbuf, "<starttls xmlns=\"urn:ietf:params:xml:ns:xmpp-tls\"")) { seen = BIO_read(sbio, mbuf, BUFSIZZ); if (seen <= 0) goto shut; mbuf[seen] = '\0'; } BIO_printf(sbio, "<starttls xmlns='urn:ietf:params:xml:ns:xmpp-tls'/>"); seen = BIO_read(sbio, sbuf, BUFSIZZ); if (seen < 0) { BIO_printf(bio_err, "BIO_read failed\n"); goto shut; } sbuf[seen] = '\0'; if (!strstr(sbuf, "<proceed")) goto shut; mbuf[0] = '\0'; } break; case PROTO_TELNET: { static const unsigned char tls_do[] = { /* IAC DO START_TLS */ 255, 253, 46 }; static const unsigned char tls_will[] = { /* IAC WILL START_TLS */ 255, 251, 46 }; static const unsigned char tls_follows[] = { /* IAC SB START_TLS FOLLOWS IAC SE */ 255, 250, 46, 1, 255, 240 }; int bytes; /* Telnet server should demand we issue START_TLS */ bytes = BIO_read(sbio, mbuf, BUFSIZZ); if (bytes != 3 || memcmp(mbuf, tls_do, 3) != 0) goto shut; /* Agree to issue START_TLS and send the FOLLOWS sub-command */ BIO_write(sbio, tls_will, 3); BIO_write(sbio, tls_follows, 6); (void)BIO_flush(sbio); /* Telnet server also sent the FOLLOWS sub-command */ bytes = BIO_read(sbio, mbuf, BUFSIZZ); if (bytes != 6 || memcmp(mbuf, tls_follows, 6) != 0) goto shut; } break; case PROTO_IRC: { int numeric; BIO *fbio = BIO_new(BIO_f_buffer()); if (fbio == NULL) { BIO_printf(bio_err, "Unable to create BIO\n"); goto end; } BIO_push(fbio, sbio); BIO_printf(fbio, "STARTTLS\r\n"); (void)BIO_flush(fbio); width = SSL_get_fd(con) + 1; do { numeric = 0; FD_ZERO(&readfds); openssl_fdset(SSL_get_fd(con), &readfds); timeout.tv_sec = S_CLIENT_IRC_READ_TIMEOUT; timeout.tv_usec = 0; /* * If the IRCd doesn't respond within * S_CLIENT_IRC_READ_TIMEOUT seconds, assume * it doesn't support STARTTLS. Many IRCds * will not give _any_ sort of response to a * STARTTLS command when it's not supported. */ if (!BIO_get_buffer_num_lines(fbio) && !BIO_pending(fbio) && !BIO_pending(sbio) && select(width, (void *)&readfds, NULL, NULL, &timeout) < 1) { BIO_printf(bio_err, "Timeout waiting for response (%d seconds).\n", S_CLIENT_IRC_READ_TIMEOUT); break; } mbuf_len = BIO_gets(fbio, mbuf, BUFSIZZ); if (mbuf_len < 1 || sscanf(mbuf, "%*s %d", &numeric) != 1) break; /* :example.net 451 STARTTLS :You have not registered */ /* :example.net 421 STARTTLS :Unknown command */ if ((numeric == 451 || numeric == 421) && strstr(mbuf, "STARTTLS") != NULL) { BIO_printf(bio_err, "STARTTLS not supported: %s", mbuf); break; } if (numeric == 691) { BIO_printf(bio_err, "STARTTLS negotiation failed: "); ERR_print_errors(bio_err); break; } } while (numeric != 670); (void)BIO_flush(fbio); BIO_pop(fbio); BIO_free(fbio); if (numeric != 670) { BIO_printf(bio_err, "Server does not support STARTTLS.\n"); ret = 1; goto shut; } } break; case PROTO_MYSQL: { /* SSL request packet */ static const unsigned char ssl_req[] = { /* payload_length, sequence_id */ 0x20, 0x00, 0x00, 0x01, /* payload */ /* capability flags, CLIENT_SSL always set */ 0x85, 0xae, 0x7f, 0x00, /* max-packet size */ 0x00, 0x00, 0x00, 0x01, /* character set */ 0x21, /* string[23] reserved (all [0]) */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; int bytes = 0; int ssl_flg = 0x800; int pos; const unsigned char *packet = (const unsigned char *)sbuf; /* Receiving Initial Handshake packet. */ bytes = BIO_read(sbio, (void *)packet, BUFSIZZ); if (bytes < 0) { BIO_printf(bio_err, "BIO_read failed\n"); goto shut; /* Packet length[3], Packet number[1] + minimum payload[17] */ } else if (bytes < 21) { BIO_printf(bio_err, "MySQL packet too short.\n"); goto shut; } else if (bytes != (4 + packet[0] + (packet[1] << 8) + (packet[2] << 16))) { BIO_printf(bio_err, "MySQL packet length does not match.\n"); goto shut; /* protocol version[1] */ } else if (packet[4] != 0xA) { BIO_printf(bio_err, "Only MySQL protocol version 10 is supported.\n"); goto shut; } pos = 5; /* server version[string+NULL] */ for (;;) { if (pos >= bytes) { BIO_printf(bio_err, "Cannot confirm server version. "); goto shut; } else if (packet[pos++] == '\0') { break; } } /* make sure we have at least 15 bytes left in the packet */ if (pos + 15 > bytes) { BIO_printf(bio_err, "MySQL server handshake packet is broken.\n"); goto shut; } pos += 12; /* skip over conn id[4] + SALT[8] */ if (packet[pos++] != '\0') { /* verify filler */ BIO_printf(bio_err, "MySQL packet is broken.\n"); goto shut; } /* capability flags[2] */ if (!((packet[pos] + (packet[pos + 1] << 8)) & ssl_flg)) { BIO_printf(bio_err, "MySQL server does not support SSL.\n"); goto shut; } /* Sending SSL Handshake packet. */ BIO_write(sbio, ssl_req, sizeof(ssl_req)); (void)BIO_flush(sbio); } break; case PROTO_POSTGRES: { static const unsigned char ssl_request[] = { /* Length SSLRequest */ 0, 0, 0, 8, 4, 210, 22, 47 }; int bytes; /* Send SSLRequest packet */ BIO_write(sbio, ssl_request, 8); (void)BIO_flush(sbio); /* Reply will be a single S if SSL is enabled */ bytes = BIO_read(sbio, sbuf, BUFSIZZ); if (bytes != 1 || sbuf[0] != 'S') goto shut; } break; case PROTO_NNTP: { int foundit = 0; BIO *fbio = BIO_new(BIO_f_buffer()); if (fbio == NULL) { BIO_printf(bio_err, "Unable to create BIO\n"); goto end; } BIO_push(fbio, sbio); BIO_gets(fbio, mbuf, BUFSIZZ); /* STARTTLS command requires CAPABILITIES... */ BIO_printf(fbio, "CAPABILITIES\r\n"); (void)BIO_flush(fbio); BIO_gets(fbio, mbuf, BUFSIZZ); /* no point in trying to parse the CAPABILITIES response if there is none */ if (strstr(mbuf, "101") != NULL) { /* wait for multi-line CAPABILITIES response */ do { mbuf_len = BIO_gets(fbio, mbuf, BUFSIZZ); if (strstr(mbuf, "STARTTLS")) foundit = 1; } while (mbuf_len > 1 && mbuf[0] != '.'); } (void)BIO_flush(fbio); BIO_pop(fbio); BIO_free(fbio); if (!foundit) BIO_printf(bio_err, "Didn't find STARTTLS in server response," " trying anyway...\n"); BIO_printf(sbio, "STARTTLS\r\n"); mbuf_len = BIO_read(sbio, mbuf, BUFSIZZ); if (mbuf_len < 0) { BIO_printf(bio_err, "BIO_read failed\n"); goto end; } mbuf[mbuf_len] = '\0'; if (strstr(mbuf, "382") == NULL) { BIO_printf(bio_err, "STARTTLS failed: %s", mbuf); goto shut; } } break; case PROTO_SIEVE: { int foundit = 0; BIO *fbio = BIO_new(BIO_f_buffer()); if (fbio == NULL) { BIO_printf(bio_err, "Unable to create BIO\n"); goto end; } BIO_push(fbio, sbio); /* wait for multi-line response to end from Sieve */ do { mbuf_len = BIO_gets(fbio, mbuf, BUFSIZZ); /* * According to RFC 5804 § 1.7, capability * is case-insensitive, make it uppercase */ if (mbuf_len > 1 && mbuf[0] == '"') { make_uppercase(mbuf); if (HAS_PREFIX(mbuf, "\"STARTTLS\"")) foundit = 1; } } while (mbuf_len > 1 && mbuf[0] == '"'); (void)BIO_flush(fbio); BIO_pop(fbio); BIO_free(fbio); if (!foundit) BIO_printf(bio_err, "Didn't find STARTTLS in server response," " trying anyway...\n"); BIO_printf(sbio, "STARTTLS\r\n"); mbuf_len = BIO_read(sbio, mbuf, BUFSIZZ); if (mbuf_len < 0) { BIO_printf(bio_err, "BIO_read failed\n"); goto end; } mbuf[mbuf_len] = '\0'; if (mbuf_len < 2) { BIO_printf(bio_err, "STARTTLS failed: %s", mbuf); goto shut; } /* * According to RFC 5804 § 2.2, response codes are case- * insensitive, make it uppercase but preserve the response. */ strncpy(sbuf, mbuf, 2); make_uppercase(sbuf); if (!HAS_PREFIX(sbuf, "OK")) { BIO_printf(bio_err, "STARTTLS not supported: %s", mbuf); goto shut; } } break; case PROTO_LDAP: { /* StartTLS Operation according to RFC 4511 */ static char ldap_tls_genconf[] = "asn1=SEQUENCE:LDAPMessage\n" "[LDAPMessage]\n" "messageID=INTEGER:1\n" "extendedReq=EXPLICIT:23A,IMPLICIT:0C," "FORMAT:ASCII,OCT:1.3.6.1.4.1.1466.20037\n"; long errline = -1; char *genstr = NULL; int result = -1; ASN1_TYPE *atyp = NULL; BIO *ldapbio = BIO_new(BIO_s_mem()); CONF *cnf = NCONF_new(NULL); if (ldapbio == NULL || cnf == NULL) { BIO_free(ldapbio); NCONF_free(cnf); goto end; } BIO_puts(ldapbio, ldap_tls_genconf); if (NCONF_load_bio(cnf, ldapbio, &errline) <= 0) { BIO_free(ldapbio); NCONF_free(cnf); if (errline <= 0) { BIO_printf(bio_err, "NCONF_load_bio failed\n"); goto end; } else { BIO_printf(bio_err, "Error on line %ld\n", errline); goto end; } } BIO_free(ldapbio); genstr = NCONF_get_string(cnf, "default", "asn1"); if (genstr == NULL) { NCONF_free(cnf); BIO_printf(bio_err, "NCONF_get_string failed\n"); goto end; } atyp = ASN1_generate_nconf(genstr, cnf); if (atyp == NULL) { NCONF_free(cnf); BIO_printf(bio_err, "ASN1_generate_nconf failed\n"); goto end; } NCONF_free(cnf); /* Send SSLRequest packet */ BIO_write(sbio, atyp->value.sequence->data, atyp->value.sequence->length); (void)BIO_flush(sbio); ASN1_TYPE_free(atyp); mbuf_len = BIO_read(sbio, mbuf, BUFSIZZ); if (mbuf_len < 0) { BIO_printf(bio_err, "BIO_read failed\n"); goto end; } result = ldap_ExtendedResponse_parse(mbuf, mbuf_len); if (result < 0) { BIO_printf(bio_err, "ldap_ExtendedResponse_parse failed\n"); goto shut; } else if (result > 0) { BIO_printf(bio_err, "STARTTLS failed, LDAP Result Code: %i\n", result); goto shut; } mbuf_len = 0; } break; } if (early_data_file != NULL && ((SSL_get0_session(con) != NULL && SSL_SESSION_get_max_early_data(SSL_get0_session(con)) > 0) || (psksess != NULL && SSL_SESSION_get_max_early_data(psksess) > 0))) { BIO *edfile = BIO_new_file(early_data_file, "r"); size_t readbytes, writtenbytes; int finish = 0; if (edfile == NULL) { BIO_printf(bio_err, "Cannot open early data file\n"); goto shut; } while (!finish) { if (!BIO_read_ex(edfile, cbuf, BUFSIZZ, &readbytes)) finish = 1; while (!SSL_write_early_data(con, cbuf, readbytes, &writtenbytes)) { switch (SSL_get_error(con, 0)) { case SSL_ERROR_WANT_WRITE: case SSL_ERROR_WANT_ASYNC: case SSL_ERROR_WANT_READ: /* Just keep trying - busy waiting */ continue; default: BIO_printf(bio_err, "Error writing early data\n"); BIO_free(edfile); ERR_print_errors(bio_err); goto shut; } } } BIO_free(edfile); } user_data_init(&user_data, con, cbuf, BUFSIZZ, cmdmode); for (;;) { FD_ZERO(&readfds); FD_ZERO(&writefds); if ((isdtls || isquic) && SSL_get_event_timeout(con, &timeout, &is_infinite) && !is_infinite) timeoutp = &timeout; else timeoutp = NULL; if (!SSL_is_init_finished(con) && SSL_total_renegotiations(con) == 0 && SSL_get_key_update_type(con) == SSL_KEY_UPDATE_NONE) { in_init = 1; tty_on = 0; } else { tty_on = 1; if (in_init) { in_init = 0; if (c_brief) { BIO_puts(bio_err, "CONNECTION ESTABLISHED\n"); print_ssl_summary(con); } print_stuff(bio_c_out, con, full_log); if (full_log > 0) full_log--; if (starttls_proto) { BIO_write(bio_err, mbuf, mbuf_len); /* We don't need to know any more */ if (!reconnect) starttls_proto = PROTO_OFF; } if (reconnect) { reconnect--; BIO_printf(bio_c_out, "drop connection and then reconnect\n"); do_ssl_shutdown(con); SSL_set_connect_state(con); BIO_closesocket(SSL_get_fd(con)); goto re_start; } } } if (!write_ssl) { do { switch (user_data_process(&user_data, &cbuf_len, &cbuf_off)) { default: BIO_printf(bio_err, "ERROR\n"); /* fall through */ case USER_DATA_PROCESS_SHUT: ret = 0; goto shut; case USER_DATA_PROCESS_RESTART: goto re_start; case USER_DATA_PROCESS_NO_DATA: break; case USER_DATA_PROCESS_CONTINUE: write_ssl = 1; break; } } while (!write_ssl && cbuf_len == 0 && user_data_has_data(&user_data)); if (cbuf_len > 0) { read_tty = 0; timeout.tv_sec = 0; timeout.tv_usec = 0; } else { read_tty = 1; } } ssl_pending = read_ssl && SSL_has_pending(con); if (!ssl_pending) { #if !defined(OPENSSL_SYS_WINDOWS) && !defined(OPENSSL_SYS_MSDOS) if (tty_on) { /* * Note that select() returns when read _would not block_, * and EOF satisfies that. To avoid a CPU-hogging loop, * set the flag so we exit. */ if (read_tty && !at_eof) openssl_fdset(fileno_stdin(), &readfds); #if !defined(OPENSSL_SYS_VMS) if (write_tty) openssl_fdset(fileno_stdout(), &writefds); #endif } /* * Note that for QUIC we never actually check FD_ISSET() for the * underlying network fds. We just rely on select waking up when * they become readable/writeable and then SSL_handle_events() doing * the right thing. */ if ((!isquic && read_ssl) || (isquic && SSL_net_read_desired(con))) openssl_fdset(SSL_get_fd(con), &readfds); if ((!isquic && write_ssl) || (isquic && (first_loop || SSL_net_write_desired(con)))) openssl_fdset(SSL_get_fd(con), &writefds); #else if (!tty_on || !write_tty) { if ((!isquic && read_ssl) || (isquic && SSL_net_read_desired(con))) openssl_fdset(SSL_get_fd(con), &readfds); if ((!isquic && write_ssl) || (isquic && (first_loop || SSL_net_write_desired(con)))) openssl_fdset(SSL_get_fd(con), &writefds); } #endif /* * Note: under VMS with SOCKETSHR the second parameter is * currently of type (int *) whereas under other systems it is * (void *) if you don't have a cast it will choke the compiler: * if you do have a cast then you can either go for (int *) or * (void *). */ #if defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_MSDOS) /* * Under Windows/DOS we make the assumption that we can always * write to the tty: therefore, if we need to write to the tty we * just fall through. Otherwise we timeout the select every * second and see if there are any keypresses. Note: this is a * hack, in a proper Windows application we wouldn't do this. */ i = 0; if (!write_tty) { if (read_tty) { tv.tv_sec = 1; tv.tv_usec = 0; i = select(width, (void *)&readfds, (void *)&writefds, NULL, &tv); if (!i && (!has_stdin_waiting() || !read_tty)) continue; } else i = select(width, (void *)&readfds, (void *)&writefds, NULL, timeoutp); } #else i = select(width, (void *)&readfds, (void *)&writefds, NULL, timeoutp); #endif if (i < 0) { BIO_printf(bio_err, "bad select %d\n", get_last_socket_error()); goto shut; } } if (timeoutp != NULL) { SSL_handle_events(con); if (isdtls && !FD_ISSET(SSL_get_fd(con), &readfds) && !FD_ISSET(SSL_get_fd(con), &writefds)) BIO_printf(bio_err, "TIMEOUT occurred\n"); } if (!ssl_pending && ((!isquic && FD_ISSET(SSL_get_fd(con), &writefds)) || (isquic && (cbuf_len > 0 || first_loop)))) { k = SSL_write(con, &(cbuf[cbuf_off]), (unsigned int)cbuf_len); switch (SSL_get_error(con, k)) { case SSL_ERROR_NONE: cbuf_off += k; cbuf_len -= k; if (k <= 0) goto end; /* we have done a write(con,NULL,0); */ if (cbuf_len == 0) { read_tty = 1; write_ssl = 0; } else { /* if (cbuf_len > 0) */ read_tty = 0; write_ssl = 1; } break; case SSL_ERROR_WANT_WRITE: BIO_printf(bio_c_out, "write W BLOCK\n"); write_ssl = 1; read_tty = 0; break; case SSL_ERROR_WANT_ASYNC: BIO_printf(bio_c_out, "write A BLOCK\n"); wait_for_async(con); write_ssl = 1; read_tty = 0; break; case SSL_ERROR_WANT_READ: BIO_printf(bio_c_out, "write R BLOCK\n"); write_tty = 0; read_ssl = 1; write_ssl = 0; break; case SSL_ERROR_WANT_X509_LOOKUP: BIO_printf(bio_c_out, "write X BLOCK\n"); break; case SSL_ERROR_ZERO_RETURN: if (cbuf_len != 0) { BIO_printf(bio_c_out, "shutdown\n"); ret = 0; goto shut; } else { read_tty = 1; write_ssl = 0; break; } case SSL_ERROR_SYSCALL: if ((k != 0) || (cbuf_len != 0)) { int sockerr = get_last_socket_error(); if (!tfo || sockerr != EISCONN) { BIO_printf(bio_err, "write:errno=%d\n", sockerr); goto shut; } } else { read_tty = 1; write_ssl = 0; } break; case SSL_ERROR_WANT_ASYNC_JOB: /* This shouldn't ever happen in s_client - treat as an error */ case SSL_ERROR_SSL: ERR_print_errors(bio_err); goto shut; } } #if defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_MSDOS) || defined(OPENSSL_SYS_VMS) /* Assume Windows/DOS/BeOS can always write */ else if (!ssl_pending && write_tty) #else else if (!ssl_pending && FD_ISSET(fileno_stdout(), &writefds)) #endif { #ifdef CHARSET_EBCDIC ascii2ebcdic(&(sbuf[sbuf_off]), &(sbuf[sbuf_off]), sbuf_len); #endif i = raw_write_stdout(&(sbuf[sbuf_off]), sbuf_len); if (i <= 0) { BIO_printf(bio_c_out, "DONE\n"); ret = 0; goto shut; } sbuf_len -= i; sbuf_off += i; if (sbuf_len <= 0) { read_ssl = 1; write_tty = 0; } } else if (ssl_pending || (!isquic && FD_ISSET(SSL_get_fd(con), &readfds))) { #ifdef RENEG { static int iiii; if (++iiii == 52) { SSL_renegotiate(con); iiii = 0; } } #endif k = SSL_read(con, sbuf, 1024 /* BUFSIZZ */ ); switch (SSL_get_error(con, k)) { case SSL_ERROR_NONE: if (k <= 0) goto end; sbuf_off = 0; sbuf_len = k; read_ssl = 0; write_tty = 1; break; case SSL_ERROR_WANT_ASYNC: BIO_printf(bio_c_out, "read A BLOCK\n"); wait_for_async(con); write_tty = 0; read_ssl = 1; if ((read_tty == 0) && (write_ssl == 0)) write_ssl = 1; break; case SSL_ERROR_WANT_WRITE: BIO_printf(bio_c_out, "read W BLOCK\n"); write_ssl = 1; read_tty = 0; break; case SSL_ERROR_WANT_READ: BIO_printf(bio_c_out, "read R BLOCK\n"); write_tty = 0; read_ssl = 1; if ((read_tty == 0) && (write_ssl == 0)) write_ssl = 1; break; case SSL_ERROR_WANT_X509_LOOKUP: BIO_printf(bio_c_out, "read X BLOCK\n"); break; case SSL_ERROR_SYSCALL: ret = get_last_socket_error(); if (c_brief) BIO_puts(bio_err, "CONNECTION CLOSED BY SERVER\n"); else BIO_printf(bio_err, "read:errno=%d\n", ret); goto shut; case SSL_ERROR_ZERO_RETURN: BIO_printf(bio_c_out, "closed\n"); ret = 0; goto shut; case SSL_ERROR_WANT_ASYNC_JOB: /* This shouldn't ever happen in s_client. Treat as an error */ case SSL_ERROR_SSL: ERR_print_errors(bio_err); goto shut; } } /* don't wait for client input in the non-interactive mode */ else if (nointeractive) { ret = 0; goto shut; } /* OPENSSL_SYS_MSDOS includes OPENSSL_SYS_WINDOWS */ #if defined(OPENSSL_SYS_MSDOS) else if (has_stdin_waiting()) #else else if (FD_ISSET(fileno_stdin(), &readfds)) #endif { if (crlf) { int j, lf_num; i = raw_read_stdin(cbuf, BUFSIZZ / 2); lf_num = 0; /* both loops are skipped when i <= 0 */ for (j = 0; j < i; j++) if (cbuf[j] == '\n') lf_num++; for (j = i - 1; j >= 0; j--) { cbuf[j + lf_num] = cbuf[j]; if (cbuf[j] == '\n') { lf_num--; i++; cbuf[j + lf_num] = '\r'; } } assert(lf_num == 0); } else i = raw_read_stdin(cbuf, BUFSIZZ); #if !defined(OPENSSL_SYS_WINDOWS) && !defined(OPENSSL_SYS_MSDOS) if (i == 0) at_eof = 1; #endif if (!c_ign_eof && i <= 0) { BIO_printf(bio_err, "DONE\n"); ret = 0; goto shut; } if (i > 0 && !user_data_add(&user_data, i)) { ret = 0; goto shut; } read_tty = 0; } first_loop = 0; } shut: if (in_init) print_stuff(bio_c_out, con, full_log); do_ssl_shutdown(con); /* * If we ended with an alert being sent, but still with data in the * network buffer to be read, then calling BIO_closesocket() will * result in a TCP-RST being sent. On some platforms (notably * Windows) then this will result in the peer immediately abandoning * the connection including any buffered alert data before it has * had a chance to be read. Shutting down the sending side first, * and then closing the socket sends TCP-FIN first followed by * TCP-RST. This seems to allow the peer to read the alert data. */ shutdown(SSL_get_fd(con), 1); /* SHUT_WR */ /* * We just said we have nothing else to say, but it doesn't mean that * the other side has nothing. It's even recommended to consume incoming * data. [In testing context this ensures that alerts are passed on...] */ timeout.tv_sec = 0; timeout.tv_usec = 500000; /* some extreme round-trip */ do { FD_ZERO(&readfds); openssl_fdset(sock, &readfds); } while (select(sock + 1, &readfds, NULL, NULL, &timeout) > 0 && BIO_read(sbio, sbuf, BUFSIZZ) > 0); BIO_closesocket(SSL_get_fd(con)); end: if (con != NULL) { if (prexit != 0) print_stuff(bio_c_out, con, 1); SSL_free(con); } SSL_SESSION_free(psksess); #if !defined(OPENSSL_NO_NEXTPROTONEG) OPENSSL_free(next_proto.data); #endif SSL_CTX_free(ctx); set_keylog_file(NULL, NULL); X509_free(cert); sk_X509_CRL_pop_free(crls, X509_CRL_free); EVP_PKEY_free(key); OSSL_STACK_OF_X509_free(chain); OPENSSL_free(pass); #ifndef OPENSSL_NO_SRP OPENSSL_free(srp_arg.srppassin); #endif OPENSSL_free(sname_alloc); BIO_ADDR_free(peer_addr); OPENSSL_free(connectstr); OPENSSL_free(bindstr); OPENSSL_free(bindhost); OPENSSL_free(bindport); OPENSSL_free(host); OPENSSL_free(port); OPENSSL_free(thost); OPENSSL_free(tport); X509_VERIFY_PARAM_free(vpm); ssl_excert_free(exc); sk_OPENSSL_STRING_free(ssl_args); sk_OPENSSL_STRING_free(dane_tlsa_rrset); SSL_CONF_CTX_free(cctx); OPENSSL_clear_free(cbuf, BUFSIZZ); OPENSSL_clear_free(sbuf, BUFSIZZ); OPENSSL_clear_free(mbuf, BUFSIZZ); clear_free(proxypass); release_engine(e); BIO_free(bio_c_out); bio_c_out = NULL; BIO_free(bio_c_msg); bio_c_msg = NULL; return ret; } static void print_stuff(BIO *bio, SSL *s, int full) { X509 *peer = NULL; STACK_OF(X509) *sk; const SSL_CIPHER *c; EVP_PKEY *public_key; int i, istls13 = (SSL_version(s) == TLS1_3_VERSION); long verify_result; #ifndef OPENSSL_NO_COMP const COMP_METHOD *comp, *expansion; #endif unsigned char *exportedkeymat; #ifndef OPENSSL_NO_CT const SSL_CTX *ctx = SSL_get_SSL_CTX(s); #endif if (full) { int got_a_chain = 0; sk = SSL_get_peer_cert_chain(s); if (sk != NULL) { got_a_chain = 1; BIO_printf(bio, "---\nCertificate chain\n"); for (i = 0; i < sk_X509_num(sk); i++) { BIO_printf(bio, "%2d s:", i); X509_NAME_print_ex(bio, X509_get_subject_name(sk_X509_value(sk, i)), 0, get_nameopt()); BIO_puts(bio, "\n"); BIO_printf(bio, " i:"); X509_NAME_print_ex(bio, X509_get_issuer_name(sk_X509_value(sk, i)), 0, get_nameopt()); BIO_puts(bio, "\n"); public_key = X509_get_pubkey(sk_X509_value(sk, i)); if (public_key != NULL) { BIO_printf(bio, " a:PKEY: %s, %d (bit); sigalg: %s\n", OBJ_nid2sn(EVP_PKEY_get_base_id(public_key)), EVP_PKEY_get_bits(public_key), OBJ_nid2sn(X509_get_signature_nid(sk_X509_value(sk, i)))); EVP_PKEY_free(public_key); } BIO_printf(bio, " v:NotBefore: "); ASN1_TIME_print(bio, X509_get0_notBefore(sk_X509_value(sk, i))); BIO_printf(bio, "; NotAfter: "); ASN1_TIME_print(bio, X509_get0_notAfter(sk_X509_value(sk, i))); BIO_puts(bio, "\n"); if (c_showcerts) PEM_write_bio_X509(bio, sk_X509_value(sk, i)); } } BIO_printf(bio, "---\n"); peer = SSL_get0_peer_certificate(s); if (peer != NULL) { BIO_printf(bio, "Server certificate\n"); /* Redundant if we showed the whole chain */ if (!(c_showcerts && got_a_chain)) PEM_write_bio_X509(bio, peer); dump_cert_text(bio, peer); } else { BIO_printf(bio, "no peer certificate available\n"); } /* Only display RPK information if configured */ if (SSL_get_negotiated_client_cert_type(s) == TLSEXT_cert_type_rpk) BIO_printf(bio, "Client-to-server raw public key negotiated\n"); if (SSL_get_negotiated_server_cert_type(s) == TLSEXT_cert_type_rpk) BIO_printf(bio, "Server-to-client raw public key negotiated\n"); if (enable_server_rpk) { EVP_PKEY *peer_rpk = SSL_get0_peer_rpk(s); if (peer_rpk != NULL) { BIO_printf(bio, "Server raw public key\n"); EVP_PKEY_print_public(bio, peer_rpk, 2, NULL); } else { BIO_printf(bio, "no peer rpk available\n"); } } print_ca_names(bio, s); ssl_print_sigalgs(bio, s); ssl_print_tmp_key(bio, s); #ifndef OPENSSL_NO_CT /* * When the SSL session is anonymous, or resumed via an abbreviated * handshake, no SCTs are provided as part of the handshake. While in * a resumed session SCTs may be present in the session's certificate, * no callbacks are invoked to revalidate these, and in any case that * set of SCTs may be incomplete. Thus it makes little sense to * attempt to display SCTs from a resumed session's certificate, and of * course none are associated with an anonymous peer. */ if (peer != NULL && !SSL_session_reused(s) && SSL_ct_is_enabled(s)) { const STACK_OF(SCT) *scts = SSL_get0_peer_scts(s); int sct_count = scts != NULL ? sk_SCT_num(scts) : 0; BIO_printf(bio, "---\nSCTs present (%i)\n", sct_count); if (sct_count > 0) { const CTLOG_STORE *log_store = SSL_CTX_get0_ctlog_store(ctx); BIO_printf(bio, "---\n"); for (i = 0; i < sct_count; ++i) { SCT *sct = sk_SCT_value(scts, i); BIO_printf(bio, "SCT validation status: %s\n", SCT_validation_status_string(sct)); SCT_print(sct, bio, 0, log_store); if (i < sct_count - 1) BIO_printf(bio, "\n---\n"); } BIO_printf(bio, "\n"); } } #endif BIO_printf(bio, "---\nSSL handshake has read %ju bytes " "and written %ju bytes\n", BIO_number_read(SSL_get_rbio(s)), BIO_number_written(SSL_get_wbio(s))); } print_verify_detail(s, bio); BIO_printf(bio, (SSL_session_reused(s) ? "---\nReused, " : "---\nNew, ")); c = SSL_get_current_cipher(s); BIO_printf(bio, "%s, Cipher is %s\n", SSL_CIPHER_get_version(c), SSL_CIPHER_get_name(c)); if (peer != NULL) { EVP_PKEY *pktmp; pktmp = X509_get0_pubkey(peer); BIO_printf(bio, "Server public key is %d bit\n", EVP_PKEY_get_bits(pktmp)); } ssl_print_secure_renegotiation_notes(bio, s); #ifndef OPENSSL_NO_COMP comp = SSL_get_current_compression(s); expansion = SSL_get_current_expansion(s); BIO_printf(bio, "Compression: %s\n", comp ? SSL_COMP_get_name(comp) : "NONE"); BIO_printf(bio, "Expansion: %s\n", expansion ? SSL_COMP_get_name(expansion) : "NONE"); #endif #ifndef OPENSSL_NO_KTLS if (BIO_get_ktls_send(SSL_get_wbio(s))) BIO_printf(bio_err, "Using Kernel TLS for sending\n"); if (BIO_get_ktls_recv(SSL_get_rbio(s))) BIO_printf(bio_err, "Using Kernel TLS for receiving\n"); #endif if (OSSL_TRACE_ENABLED(TLS)) { /* Print out local port of connection: useful for debugging */ int sock; union BIO_sock_info_u info; sock = SSL_get_fd(s); if ((info.addr = BIO_ADDR_new()) != NULL && BIO_sock_info(sock, BIO_SOCK_INFO_ADDRESS, &info)) { BIO_printf(bio_c_out, "LOCAL PORT is %u\n", ntohs(BIO_ADDR_rawport(info.addr))); } BIO_ADDR_free(info.addr); } #if !defined(OPENSSL_NO_NEXTPROTONEG) if (next_proto.status != -1) { const unsigned char *proto; unsigned int proto_len; SSL_get0_next_proto_negotiated(s, &proto, &proto_len); BIO_printf(bio, "Next protocol: (%d) ", next_proto.status); BIO_write(bio, proto, proto_len); BIO_write(bio, "\n", 1); } #endif { const unsigned char *proto; unsigned int proto_len; SSL_get0_alpn_selected(s, &proto, &proto_len); if (proto_len > 0) { BIO_printf(bio, "ALPN protocol: "); BIO_write(bio, proto, proto_len); BIO_write(bio, "\n", 1); } else BIO_printf(bio, "No ALPN negotiated\n"); } #ifndef OPENSSL_NO_SRTP { SRTP_PROTECTION_PROFILE *srtp_profile = SSL_get_selected_srtp_profile(s); if (srtp_profile) BIO_printf(bio, "SRTP Extension negotiated, profile=%s\n", srtp_profile->name); } #endif if (istls13) { switch (SSL_get_early_data_status(s)) { case SSL_EARLY_DATA_NOT_SENT: BIO_printf(bio, "Early data was not sent\n"); break; case SSL_EARLY_DATA_REJECTED: BIO_printf(bio, "Early data was rejected\n"); break; case SSL_EARLY_DATA_ACCEPTED: BIO_printf(bio, "Early data was accepted\n"); break; } /* * We also print the verify results when we dump session information, * but in TLSv1.3 we may not get that right away (or at all) depending * on when we get a NewSessionTicket. Therefore, we print it now as well. */ verify_result = SSL_get_verify_result(s); BIO_printf(bio, "Verify return code: %ld (%s)\n", verify_result, X509_verify_cert_error_string(verify_result)); } else { /* In TLSv1.3 we do this on arrival of a NewSessionTicket */ SSL_SESSION_print(bio, SSL_get_session(s)); } if (SSL_get_session(s) != NULL && keymatexportlabel != NULL) { BIO_printf(bio, "Keying material exporter:\n"); BIO_printf(bio, " Label: '%s'\n", keymatexportlabel); BIO_printf(bio, " Length: %i bytes\n", keymatexportlen); exportedkeymat = app_malloc(keymatexportlen, "export key"); if (SSL_export_keying_material(s, exportedkeymat, keymatexportlen, keymatexportlabel, strlen(keymatexportlabel), NULL, 0, 0) <= 0) { BIO_printf(bio, " Error\n"); } else { BIO_printf(bio, " Keying material: "); for (i = 0; i < keymatexportlen; i++) BIO_printf(bio, "%02X", exportedkeymat[i]); BIO_printf(bio, "\n"); } OPENSSL_free(exportedkeymat); } BIO_printf(bio, "---\n"); /* flush, or debugging output gets mixed with http response */ (void)BIO_flush(bio); } # ifndef OPENSSL_NO_OCSP static int ocsp_resp_cb(SSL *s, void *arg) { const unsigned char *p; int len; OCSP_RESPONSE *rsp; len = SSL_get_tlsext_status_ocsp_resp(s, &p); BIO_puts(arg, "OCSP response: "); if (p == NULL) { BIO_puts(arg, "no response sent\n"); return 1; } rsp = d2i_OCSP_RESPONSE(NULL, &p, len); if (rsp == NULL) { BIO_puts(arg, "response parse error\n"); BIO_dump_indent(arg, (char *)p, len, 4); return 0; } BIO_puts(arg, "\n======================================\n"); OCSP_RESPONSE_print(arg, rsp, 0); BIO_puts(arg, "======================================\n"); OCSP_RESPONSE_free(rsp); return 1; } # endif static int ldap_ExtendedResponse_parse(const char *buf, long rem) { const unsigned char *cur, *end; long len; int tag, xclass, inf, ret = -1; cur = (const unsigned char *)buf; end = cur + rem; /* * From RFC 4511: * * LDAPMessage ::= SEQUENCE { * messageID MessageID, * protocolOp CHOICE { * ... * extendedResp ExtendedResponse, * ... }, * controls [0] Controls OPTIONAL } * * ExtendedResponse ::= [APPLICATION 24] SEQUENCE { * COMPONENTS OF LDAPResult, * responseName [10] LDAPOID OPTIONAL, * responseValue [11] OCTET STRING OPTIONAL } * * LDAPResult ::= SEQUENCE { * resultCode ENUMERATED { * success (0), * ... * other (80), * ... }, * matchedDN LDAPDN, * diagnosticMessage LDAPString, * referral [3] Referral OPTIONAL } */ /* pull SEQUENCE */ inf = ASN1_get_object(&cur, &len, &tag, &xclass, rem); if (inf != V_ASN1_CONSTRUCTED || tag != V_ASN1_SEQUENCE || (rem = end - cur, len > rem)) { BIO_printf(bio_err, "Unexpected LDAP response\n"); goto end; } rem = len; /* ensure that we don't overstep the SEQUENCE */ /* pull MessageID */ inf = ASN1_get_object(&cur, &len, &tag, &xclass, rem); if (inf != V_ASN1_UNIVERSAL || tag != V_ASN1_INTEGER || (rem = end - cur, len > rem)) { BIO_printf(bio_err, "No MessageID\n"); goto end; } cur += len; /* shall we check for MessageId match or just skip? */ /* pull [APPLICATION 24] */ rem = end - cur; inf = ASN1_get_object(&cur, &len, &tag, &xclass, rem); if (inf != V_ASN1_CONSTRUCTED || xclass != V_ASN1_APPLICATION || tag != 24) { BIO_printf(bio_err, "Not ExtendedResponse\n"); goto end; } /* pull resultCode */ rem = end - cur; inf = ASN1_get_object(&cur, &len, &tag, &xclass, rem); if (inf != V_ASN1_UNIVERSAL || tag != V_ASN1_ENUMERATED || len == 0 || (rem = end - cur, len > rem)) { BIO_printf(bio_err, "Not LDAPResult\n"); goto end; } /* len should always be one, but just in case... */ for (ret = 0, inf = 0; inf < len; inf++) { ret <<= 8; ret |= cur[inf]; } /* There is more data, but we don't care... */ end: return ret; } /* * Host dNS Name verifier: used for checking that the hostname is in dNS format * before setting it as SNI */ static int is_dNS_name(const char *host) { const size_t MAX_LABEL_LENGTH = 63; size_t i; int isdnsname = 0; size_t length = strlen(host); size_t label_length = 0; int all_numeric = 1; /* * Deviation from strict DNS name syntax, also check names with '_' * Check DNS name syntax, any '-' or '.' must be internal, * and on either side of each '.' we can't have a '-' or '.'. * * If the name has just one label, we don't consider it a DNS name. */ for (i = 0; i < length && label_length < MAX_LABEL_LENGTH; ++i) { char c = host[i]; if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_') { label_length += 1; all_numeric = 0; continue; } if (c >= '0' && c <= '9') { label_length += 1; continue; } /* Dot and hyphen cannot be first or last. */ if (i > 0 && i < length - 1) { if (c == '-') { label_length += 1; continue; } /* * Next to a dot the preceding and following characters must not be * another dot or a hyphen. Otherwise, record that the name is * plausible, since it has two or more labels. */ if (c == '.' && host[i + 1] != '.' && host[i - 1] != '-' && host[i + 1] != '-') { label_length = 0; isdnsname = 1; continue; } } isdnsname = 0; break; } /* dNS name must not be all numeric and labels must be shorter than 64 characters. */ isdnsname &= !all_numeric && !(label_length == MAX_LABEL_LENGTH); return isdnsname; } static void user_data_init(struct user_data_st *user_data, SSL *con, char *buf, size_t bufmax, int mode) { user_data->con = con; user_data->buf = buf; user_data->bufmax = bufmax; user_data->buflen = 0; user_data->bufoff = 0; user_data->mode = mode; user_data->isfin = 0; } static int user_data_add(struct user_data_st *user_data, size_t i) { if (user_data->buflen != 0 || i > user_data->bufmax) return 0; user_data->buflen = i; user_data->bufoff = 0; return 1; } #define USER_COMMAND_HELP 0 #define USER_COMMAND_QUIT 1 #define USER_COMMAND_RECONNECT 2 #define USER_COMMAND_RENEGOTIATE 3 #define USER_COMMAND_KEY_UPDATE 4 #define USER_COMMAND_FIN 5 static int user_data_execute(struct user_data_st *user_data, int cmd, char *arg) { switch (cmd) { case USER_COMMAND_HELP: /* This only ever occurs in advanced mode, so just emit advanced help */ BIO_printf(bio_err, "Enter text to send to the peer followed by <enter>\n"); BIO_printf(bio_err, "To issue a command insert {cmd} or {cmd:arg} anywhere in the text\n"); BIO_printf(bio_err, "Entering {{ will send { to the peer\n"); BIO_printf(bio_err, "The following commands are available\n"); BIO_printf(bio_err, " {help}: Get this help text\n"); BIO_printf(bio_err, " {quit}: Close the connection to the peer\n"); BIO_printf(bio_err, " {reconnect}: Reconnect to the peer\n"); if (SSL_is_quic(user_data->con)) { BIO_printf(bio_err, " {fin}: Send FIN on the stream. No further writing is possible\n"); } else if(SSL_version(user_data->con) == TLS1_3_VERSION) { BIO_printf(bio_err, " {keyup:req|noreq}: Send a Key Update message\n"); BIO_printf(bio_err, " Arguments:\n"); BIO_printf(bio_err, " req = peer update requested (default)\n"); BIO_printf(bio_err, " noreq = peer update not requested\n"); } else { BIO_printf(bio_err, " {reneg}: Attempt to renegotiate\n"); } BIO_printf(bio_err, "\n"); return USER_DATA_PROCESS_NO_DATA; case USER_COMMAND_QUIT: BIO_printf(bio_err, "DONE\n"); return USER_DATA_PROCESS_SHUT; case USER_COMMAND_RECONNECT: BIO_printf(bio_err, "RECONNECTING\n"); do_ssl_shutdown(user_data->con); SSL_set_connect_state(user_data->con); BIO_closesocket(SSL_get_fd(user_data->con)); return USER_DATA_PROCESS_RESTART; case USER_COMMAND_RENEGOTIATE: BIO_printf(bio_err, "RENEGOTIATING\n"); if (!SSL_renegotiate(user_data->con)) break; return USER_DATA_PROCESS_CONTINUE; case USER_COMMAND_KEY_UPDATE: { int updatetype; if (OPENSSL_strcasecmp(arg, "req") == 0) updatetype = SSL_KEY_UPDATE_REQUESTED; else if (OPENSSL_strcasecmp(arg, "noreq") == 0) updatetype = SSL_KEY_UPDATE_NOT_REQUESTED; else return USER_DATA_PROCESS_BAD_ARGUMENT; BIO_printf(bio_err, "KEYUPDATE\n"); if (!SSL_key_update(user_data->con, updatetype)) break; return USER_DATA_PROCESS_CONTINUE; } case USER_COMMAND_FIN: if (!SSL_stream_conclude(user_data->con, 0)) break; user_data->isfin = 1; return USER_DATA_PROCESS_NO_DATA; default: break; } BIO_printf(bio_err, "ERROR\n"); ERR_print_errors(bio_err); return USER_DATA_PROCESS_SHUT; } static int user_data_process(struct user_data_st *user_data, size_t *len, size_t *off) { char *buf_start = user_data->buf + user_data->bufoff; size_t outlen = user_data->buflen; if (user_data->buflen == 0) { *len = 0; *off = 0; return USER_DATA_PROCESS_NO_DATA; } if (user_data->mode == USER_DATA_MODE_BASIC) { switch (buf_start[0]) { case 'Q': user_data->buflen = user_data->bufoff = *len = *off = 0; return user_data_execute(user_data, USER_COMMAND_QUIT, NULL); case 'C': user_data->buflen = user_data->bufoff = *len = *off = 0; return user_data_execute(user_data, USER_COMMAND_RECONNECT, NULL); case 'R': user_data->buflen = user_data->bufoff = *len = *off = 0; return user_data_execute(user_data, USER_COMMAND_RENEGOTIATE, NULL); case 'K': case 'k': user_data->buflen = user_data->bufoff = *len = *off = 0; return user_data_execute(user_data, USER_COMMAND_KEY_UPDATE, buf_start[0] == 'K' ? "req" : "noreq"); default: break; } } else if (user_data->mode == USER_DATA_MODE_ADVANCED) { char *cmd_start = buf_start; cmd_start[outlen] = '\0'; for (;;) { cmd_start = strchr(cmd_start, '{'); if (cmd_start == buf_start && *(cmd_start + 1) == '{') { /* The "{" is escaped, so skip it */ cmd_start += 2; buf_start++; user_data->bufoff++; user_data->buflen--; outlen--; continue; } break; } if (cmd_start == buf_start) { /* Command detected */ char *cmd_end = strchr(cmd_start, '}'); char *arg_start; int cmd = -1, ret = USER_DATA_PROCESS_NO_DATA; size_t oldoff; if (cmd_end == NULL) { /* Malformed command */ cmd_start[outlen - 1] = '\0'; BIO_printf(bio_err, "ERROR PROCESSING COMMAND. REST OF LINE IGNORED: %s\n", cmd_start); user_data->buflen = user_data->bufoff = *len = *off = 0; return USER_DATA_PROCESS_NO_DATA; } *cmd_end = '\0'; arg_start = strchr(cmd_start, ':'); if (arg_start != NULL) { *arg_start = '\0'; arg_start++; } /* Skip over the { */ cmd_start++; /* * Now we have cmd_start pointing to a NUL terminated string for * the command, and arg_start either being NULL or pointing to a * NUL terminated string for the argument. */ if (OPENSSL_strcasecmp(cmd_start, "help") == 0) { cmd = USER_COMMAND_HELP; } else if (OPENSSL_strcasecmp(cmd_start, "quit") == 0) { cmd = USER_COMMAND_QUIT; } else if (OPENSSL_strcasecmp(cmd_start, "reconnect") == 0) { cmd = USER_COMMAND_RECONNECT; } else if(SSL_is_quic(user_data->con)) { if (OPENSSL_strcasecmp(cmd_start, "fin") == 0) cmd = USER_COMMAND_FIN; } if (SSL_version(user_data->con) == TLS1_3_VERSION) { if (OPENSSL_strcasecmp(cmd_start, "keyup") == 0) { cmd = USER_COMMAND_KEY_UPDATE; if (arg_start == NULL) arg_start = "req"; } } else { /* (D)TLSv1.2 or below */ if (OPENSSL_strcasecmp(cmd_start, "reneg") == 0) cmd = USER_COMMAND_RENEGOTIATE; } if (cmd == -1) { BIO_printf(bio_err, "UNRECOGNISED COMMAND (IGNORED): %s\n", cmd_start); } else { ret = user_data_execute(user_data, cmd, arg_start); if (ret == USER_DATA_PROCESS_BAD_ARGUMENT) { BIO_printf(bio_err, "BAD ARGUMENT (COMMAND IGNORED): %s\n", arg_start); ret = USER_DATA_PROCESS_NO_DATA; } } oldoff = user_data->bufoff; user_data->bufoff = (cmd_end - user_data->buf) + 1; user_data->buflen -= user_data->bufoff - oldoff; if (user_data->buf + 1 == cmd_start && user_data->buflen == 1 && user_data->buf[user_data->bufoff] == '\n') { /* * This command was the only thing on the whole line. We * suppress the final `\n` */ user_data->bufoff = 0; user_data->buflen = 0; } *len = *off = 0; return ret; } else if (cmd_start != NULL) { /* * There is a command on this line, but its not at the start. Output * the start of the line, and we'll process the command next time * we call this function */ outlen = cmd_start - buf_start; } } if (user_data->isfin) { user_data->buflen = user_data->bufoff = *len = *off = 0; return USER_DATA_PROCESS_NO_DATA; } #ifdef CHARSET_EBCDIC ebcdic2ascii(buf_start, buf_start, outlen); #endif *len = outlen; *off = user_data->bufoff; user_data->buflen -= outlen; if (user_data->buflen == 0) user_data->bufoff = 0; else user_data->bufoff += outlen; return USER_DATA_PROCESS_CONTINUE; } static int user_data_has_data(struct user_data_st *user_data) { return user_data->buflen > 0; } #endif /* OPENSSL_NO_SOCK */
./openssl/apps/smime.c
/* * Copyright 1999-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 */ /* S/MIME utility function */ #include <stdio.h> #include <string.h> #include "apps.h" #include "progs.h" #include <openssl/crypto.h> #include <openssl/pem.h> #include <openssl/err.h> #include <openssl/x509_vfy.h> #include <openssl/x509v3.h> static int save_certs(char *signerfile, STACK_OF(X509) *signers); static int smime_cb(int ok, X509_STORE_CTX *ctx); #define SMIME_OP 0x10 #define SMIME_IP 0x20 #define SMIME_SIGNERS 0x40 #define SMIME_ENCRYPT (1 | SMIME_OP) #define SMIME_DECRYPT (2 | SMIME_IP) #define SMIME_SIGN (3 | SMIME_OP | SMIME_SIGNERS) #define SMIME_RESIGN (6 | SMIME_IP | SMIME_OP | SMIME_SIGNERS) #define SMIME_VERIFY (4 | SMIME_IP) #define SMIME_PK7OUT (5 | SMIME_IP | SMIME_OP) typedef enum OPTION_choice { OPT_COMMON, OPT_ENCRYPT, OPT_DECRYPT, OPT_SIGN, OPT_RESIGN, OPT_VERIFY, OPT_PK7OUT, OPT_TEXT, OPT_NOINTERN, OPT_NOVERIFY, OPT_NOCHAIN, OPT_NOCERTS, OPT_NOATTR, OPT_NODETACH, OPT_NOSMIMECAP, OPT_BINARY, OPT_NOSIGS, OPT_STREAM, OPT_INDEF, OPT_NOINDEF, OPT_CRLFEOL, OPT_ENGINE, OPT_PASSIN, OPT_TO, OPT_FROM, OPT_SUBJECT, OPT_SIGNER, OPT_RECIP, OPT_MD, OPT_CIPHER, OPT_INKEY, OPT_KEYFORM, OPT_CERTFILE, OPT_CAFILE, OPT_CAPATH, OPT_CASTORE, OPT_NOCAFILE, OPT_NOCAPATH, OPT_NOCASTORE, OPT_R_ENUM, OPT_PROV_ENUM, OPT_CONFIG, OPT_V_ENUM, OPT_IN, OPT_INFORM, OPT_OUT, OPT_OUTFORM, OPT_CONTENT } OPTION_CHOICE; const OPTIONS smime_options[] = { {OPT_HELP_STR, 1, '-', "Usage: %s [options] [cert...]\n"}, OPT_SECTION("General"), {"help", OPT_HELP, '-', "Display this summary"}, {"in", OPT_IN, '<', "Input file"}, {"inform", OPT_INFORM, 'c', "Input format SMIME (default), PEM or DER"}, {"out", OPT_OUT, '>', "Output file"}, {"outform", OPT_OUTFORM, 'c', "Output format SMIME (default), PEM or DER"}, {"inkey", OPT_INKEY, 's', "Input private key (if not signer or recipient)"}, {"keyform", OPT_KEYFORM, 'f', "Input private key format (ENGINE, other values ignored)"}, #ifndef OPENSSL_NO_ENGINE {"engine", OPT_ENGINE, 's', "Use engine, possibly a hardware device"}, #endif {"stream", OPT_STREAM, '-', "Enable CMS streaming" }, {"indef", OPT_INDEF, '-', "Same as -stream" }, {"noindef", OPT_NOINDEF, '-', "Disable CMS streaming"}, OPT_CONFIG_OPTION, OPT_SECTION("Action"), {"encrypt", OPT_ENCRYPT, '-', "Encrypt message"}, {"decrypt", OPT_DECRYPT, '-', "Decrypt encrypted message"}, {"sign", OPT_SIGN, '-', "Sign message"}, {"resign", OPT_RESIGN, '-', "Resign a signed message"}, {"verify", OPT_VERIFY, '-', "Verify signed message"}, {"pk7out", OPT_PK7OUT, '-', "Output PKCS#7 structure"}, OPT_SECTION("Signing/Encryption"), {"passin", OPT_PASSIN, 's', "Input file pass phrase source"}, {"md", OPT_MD, 's', "Digest algorithm to use when signing or resigning"}, {"", OPT_CIPHER, '-', "Any supported cipher"}, {"nointern", OPT_NOINTERN, '-', "Don't search certificates in message for signer"}, {"nodetach", OPT_NODETACH, '-', "Use opaque signing"}, {"noattr", OPT_NOATTR, '-', "Don't include any signed attributes"}, {"binary", OPT_BINARY, '-', "Don't translate message to text"}, {"signer", OPT_SIGNER, 's', "Signer certificate file"}, {"content", OPT_CONTENT, '<', "Supply or override content for detached signature"}, {"nocerts", OPT_NOCERTS, '-', "Don't include signers certificate when signing"}, OPT_SECTION("Verification/Decryption"), {"nosigs", OPT_NOSIGS, '-', "Don't verify message signature"}, {"noverify", OPT_NOVERIFY, '-', "Don't verify signers certificate"}, {"certfile", OPT_CERTFILE, '<', "Other certificates file"}, {"recip", OPT_RECIP, '<', "Recipient certificate file for decryption"}, OPT_SECTION("Email"), {"to", OPT_TO, 's', "To address"}, {"from", OPT_FROM, 's', "From address"}, {"subject", OPT_SUBJECT, 's', "Subject"}, {"text", OPT_TEXT, '-', "Include or delete text MIME headers"}, {"nosmimecap", OPT_NOSMIMECAP, '-', "Omit the SMIMECapabilities attribute"}, OPT_SECTION("Certificate chain"), {"CApath", OPT_CAPATH, '/', "Trusted certificates directory"}, {"CAfile", OPT_CAFILE, '<', "Trusted certificates file"}, {"CAstore", OPT_CASTORE, ':', "Trusted certificates store URI"}, {"no-CAfile", OPT_NOCAFILE, '-', "Do not load the default certificates file"}, {"no-CApath", OPT_NOCAPATH, '-', "Do not load certificates from the default certificates directory"}, {"no-CAstore", OPT_NOCASTORE, '-', "Do not load certificates from the default certificates store"}, {"nochain", OPT_NOCHAIN, '-', "set PKCS7_NOCHAIN so certificates contained in the message are not used as untrusted CAs" }, {"crlfeol", OPT_CRLFEOL, '-', "Use CRLF as EOL termination instead of CR only"}, OPT_R_OPTIONS, OPT_V_OPTIONS, OPT_PROV_OPTIONS, OPT_PARAMETERS(), {"cert", 0, 0, "Recipient certs, used when encrypting"}, {NULL} }; static const char *operation_name(int operation) { switch (operation) { case SMIME_ENCRYPT: return "encrypt"; case SMIME_DECRYPT: return "decrypt"; case SMIME_SIGN: return "sign"; case SMIME_RESIGN: return "resign"; case SMIME_VERIFY: return "verify"; case SMIME_PK7OUT: return "pk7out"; default: return "(invalid operation)"; } } #define SET_OPERATION(op) \ ((operation != 0 && (operation != (op))) \ ? 0 * BIO_printf(bio_err, "%s: Cannot use -%s together with -%s\n", \ prog, operation_name(op), operation_name(operation)) \ : (operation = (op))) int smime_main(int argc, char **argv) { CONF *conf = NULL; BIO *in = NULL, *out = NULL, *indata = NULL; EVP_PKEY *key = NULL; PKCS7 *p7 = NULL; STACK_OF(OPENSSL_STRING) *sksigners = NULL, *skkeys = NULL; STACK_OF(X509) *encerts = NULL, *other = NULL; X509 *cert = NULL, *recip = NULL, *signer = NULL; X509_STORE *store = NULL; X509_VERIFY_PARAM *vpm = NULL; EVP_CIPHER *cipher = NULL; EVP_MD *sign_md = NULL; const char *CAfile = NULL, *CApath = NULL, *CAstore = NULL, *prog = NULL; char *certfile = NULL, *keyfile = NULL, *contfile = NULL; char *infile = NULL, *outfile = NULL, *signerfile = NULL, *recipfile = NULL; char *passinarg = NULL, *passin = NULL, *to = NULL, *from = NULL; char *subject = NULL, *digestname = NULL, *ciphername = NULL; OPTION_CHOICE o; int noCApath = 0, noCAfile = 0, noCAstore = 0; int flags = PKCS7_DETACHED, operation = 0, ret = 0, indef = 0; int informat = FORMAT_SMIME, outformat = FORMAT_SMIME, keyform = FORMAT_UNDEF; int vpmtouched = 0, rv = 0; ENGINE *e = NULL; const char *mime_eol = "\n"; OSSL_LIB_CTX *libctx = app_get0_libctx(); if ((vpm = X509_VERIFY_PARAM_new()) == NULL) return 1; opt_set_unknown_name("cipher"); prog = opt_init(argc, argv, smime_options); while ((o = opt_next()) != OPT_EOF) { switch (o) { case OPT_EOF: case OPT_ERR: opthelp: BIO_printf(bio_err, "%s: Use -help for summary.\n", prog); goto end; case OPT_HELP: opt_help(smime_options); ret = 0; goto end; case OPT_INFORM: if (!opt_format(opt_arg(), OPT_FMT_PDS, &informat)) goto opthelp; break; case OPT_IN: infile = opt_arg(); break; case OPT_OUTFORM: if (!opt_format(opt_arg(), OPT_FMT_PDS, &outformat)) goto opthelp; break; case OPT_OUT: outfile = opt_arg(); break; case OPT_ENCRYPT: if (!SET_OPERATION(SMIME_ENCRYPT)) goto end; break; case OPT_DECRYPT: if (!SET_OPERATION(SMIME_DECRYPT)) goto end; break; case OPT_SIGN: if (!SET_OPERATION(SMIME_SIGN)) goto end; break; case OPT_RESIGN: if (!SET_OPERATION(SMIME_RESIGN)) goto end; break; case OPT_VERIFY: if (!SET_OPERATION(SMIME_VERIFY)) goto end; break; case OPT_PK7OUT: if (!SET_OPERATION(SMIME_PK7OUT)) goto end; break; case OPT_TEXT: flags |= PKCS7_TEXT; break; case OPT_NOINTERN: flags |= PKCS7_NOINTERN; break; case OPT_NOVERIFY: flags |= PKCS7_NOVERIFY; break; case OPT_NOCHAIN: flags |= PKCS7_NOCHAIN; break; case OPT_NOCERTS: flags |= PKCS7_NOCERTS; break; case OPT_NOATTR: flags |= PKCS7_NOATTR; break; case OPT_NODETACH: flags &= ~PKCS7_DETACHED; break; case OPT_NOSMIMECAP: flags |= PKCS7_NOSMIMECAP; break; case OPT_BINARY: flags |= PKCS7_BINARY; break; case OPT_NOSIGS: flags |= PKCS7_NOSIGS; break; case OPT_STREAM: case OPT_INDEF: indef = 1; break; case OPT_NOINDEF: indef = 0; break; case OPT_CRLFEOL: flags |= PKCS7_CRLFEOL; mime_eol = "\r\n"; break; case OPT_R_CASES: if (!opt_rand(o)) goto end; break; case OPT_PROV_CASES: if (!opt_provider(o)) goto end; break; case OPT_CONFIG: conf = app_load_config_modules(opt_arg()); if (conf == NULL) goto end; break; case OPT_ENGINE: e = setup_engine(opt_arg(), 0); break; case OPT_PASSIN: passinarg = opt_arg(); break; case OPT_TO: to = opt_arg(); break; case OPT_FROM: from = opt_arg(); break; case OPT_SUBJECT: subject = opt_arg(); break; case OPT_SIGNER: /* If previous -signer argument add signer to list */ if (signerfile != NULL) { if (sksigners == NULL && (sksigners = sk_OPENSSL_STRING_new_null()) == NULL) goto end; sk_OPENSSL_STRING_push(sksigners, signerfile); if (keyfile == NULL) keyfile = signerfile; if (skkeys == NULL && (skkeys = sk_OPENSSL_STRING_new_null()) == NULL) goto end; sk_OPENSSL_STRING_push(skkeys, keyfile); keyfile = NULL; } signerfile = opt_arg(); break; case OPT_RECIP: recipfile = opt_arg(); break; case OPT_MD: digestname = opt_arg(); break; case OPT_CIPHER: ciphername = opt_unknown(); break; case OPT_INKEY: /* If previous -inkey argument add signer to list */ if (keyfile != NULL) { if (signerfile == NULL) { BIO_printf(bio_err, "%s: Must have -signer before -inkey\n", prog); goto opthelp; } if (sksigners == NULL && (sksigners = sk_OPENSSL_STRING_new_null()) == NULL) goto end; sk_OPENSSL_STRING_push(sksigners, signerfile); signerfile = NULL; if (skkeys == NULL && (skkeys = sk_OPENSSL_STRING_new_null()) == NULL) goto end; sk_OPENSSL_STRING_push(skkeys, keyfile); } keyfile = opt_arg(); break; case OPT_KEYFORM: if (!opt_format(opt_arg(), OPT_FMT_ANY, &keyform)) goto opthelp; break; case OPT_CERTFILE: certfile = opt_arg(); break; case OPT_CAFILE: CAfile = opt_arg(); break; case OPT_CAPATH: CApath = opt_arg(); break; case OPT_CASTORE: CAstore = opt_arg(); break; case OPT_NOCAFILE: noCAfile = 1; break; case OPT_NOCAPATH: noCApath = 1; break; case OPT_NOCASTORE: noCAstore = 1; break; case OPT_CONTENT: contfile = opt_arg(); break; case OPT_V_CASES: if (!opt_verify(o, vpm)) goto opthelp; vpmtouched++; break; } } /* Extra arguments are files with recipient keys. */ argc = opt_num_rest(); argv = opt_rest(); if (!app_RAND_load()) goto end; if (digestname != NULL) { if (!opt_md(digestname, &sign_md)) goto opthelp; } if (!opt_cipher_any(ciphername, &cipher)) goto opthelp; if (!(operation & SMIME_SIGNERS) && (skkeys != NULL || sksigners != NULL)) { BIO_puts(bio_err, "Multiple signers or keys not allowed\n"); goto opthelp; } if (!operation) { BIO_puts(bio_err, "No operation (-encrypt|-sign|...) specified\n"); goto opthelp; } if (operation & SMIME_SIGNERS) { /* Check to see if any final signer needs to be appended */ if (keyfile && !signerfile) { BIO_puts(bio_err, "Illegal -inkey without -signer\n"); goto opthelp; } if (signerfile != NULL) { if (sksigners == NULL && (sksigners = sk_OPENSSL_STRING_new_null()) == NULL) goto end; sk_OPENSSL_STRING_push(sksigners, signerfile); if (!skkeys && (skkeys = sk_OPENSSL_STRING_new_null()) == NULL) goto end; if (!keyfile) keyfile = signerfile; sk_OPENSSL_STRING_push(skkeys, keyfile); } if (sksigners == NULL) { BIO_printf(bio_err, "No signer certificate specified\n"); goto opthelp; } signerfile = NULL; keyfile = NULL; } else if (operation == SMIME_DECRYPT) { if (recipfile == NULL && keyfile == NULL) { BIO_printf(bio_err, "No recipient certificate or key specified\n"); goto opthelp; } } else if (operation == SMIME_ENCRYPT) { if (argc == 0) { BIO_printf(bio_err, "No recipient(s) certificate(s) specified\n"); goto opthelp; } } if (!app_passwd(passinarg, NULL, &passin, NULL)) { BIO_printf(bio_err, "Error getting password\n"); goto end; } ret = 2; if (!(operation & SMIME_SIGNERS)) flags &= ~PKCS7_DETACHED; if (!(operation & SMIME_OP)) { if (flags & PKCS7_BINARY) outformat = FORMAT_BINARY; } if (!(operation & SMIME_IP)) { if (flags & PKCS7_BINARY) informat = FORMAT_BINARY; } if (operation == SMIME_ENCRYPT) { if (cipher == NULL) { #ifndef OPENSSL_NO_DES cipher = (EVP_CIPHER *)EVP_des_ede3_cbc(); #else BIO_printf(bio_err, "No cipher selected\n"); goto end; #endif } encerts = sk_X509_new_null(); if (encerts == NULL) goto end; while (*argv != NULL) { cert = load_cert(*argv, FORMAT_UNDEF, "recipient certificate file"); if (cert == NULL) goto end; if (!sk_X509_push(encerts, cert)) goto end; cert = NULL; argv++; } } if (certfile != NULL) { if (!load_certs(certfile, 0, &other, NULL, "certificates")) { ERR_print_errors(bio_err); goto end; } } if (recipfile != NULL && (operation == SMIME_DECRYPT)) { if ((recip = load_cert(recipfile, FORMAT_UNDEF, "recipient certificate file")) == NULL) { ERR_print_errors(bio_err); goto end; } } if (operation == SMIME_DECRYPT) { if (keyfile == NULL) keyfile = recipfile; } else if (operation == SMIME_SIGN) { if (keyfile == NULL) keyfile = signerfile; } else { keyfile = NULL; } if (keyfile != NULL) { key = load_key(keyfile, keyform, 0, passin, e, "signing key"); if (key == NULL) goto end; } in = bio_open_default(infile, 'r', informat); if (in == NULL) goto end; if (operation & SMIME_IP) { PKCS7 *p7_in = NULL; p7 = PKCS7_new_ex(libctx, app_get0_propq()); if (p7 == NULL) { BIO_printf(bio_err, "Error allocating PKCS7 object\n"); goto end; } if (informat == FORMAT_SMIME) { p7_in = SMIME_read_PKCS7_ex(in, &indata, &p7); } else if (informat == FORMAT_PEM) { p7_in = PEM_read_bio_PKCS7(in, &p7, NULL, NULL); } else if (informat == FORMAT_ASN1) { p7_in = d2i_PKCS7_bio(in, &p7); } else { BIO_printf(bio_err, "Bad input format for PKCS#7 file\n"); goto end; } if (p7_in == NULL) { BIO_printf(bio_err, "Error reading S/MIME message\n"); goto end; } if (contfile != NULL) { BIO_free(indata); if ((indata = BIO_new_file(contfile, "rb")) == NULL) { BIO_printf(bio_err, "Can't read content file %s\n", contfile); goto end; } } } out = bio_open_default(outfile, 'w', outformat); if (out == NULL) goto end; if (operation == SMIME_VERIFY) { if ((store = setup_verify(CAfile, noCAfile, CApath, noCApath, CAstore, noCAstore)) == NULL) goto end; X509_STORE_set_verify_cb(store, smime_cb); if (vpmtouched) X509_STORE_set1_param(store, vpm); } ret = 3; if (operation == SMIME_ENCRYPT) { if (indef) flags |= PKCS7_STREAM; p7 = PKCS7_encrypt_ex(encerts, in, cipher, flags, libctx, app_get0_propq()); } else if (operation & SMIME_SIGNERS) { int i; /* * If detached data content we only enable streaming if S/MIME output * format. */ if (operation == SMIME_SIGN) { if (flags & PKCS7_DETACHED) { if (outformat == FORMAT_SMIME) flags |= PKCS7_STREAM; } else if (indef) { flags |= PKCS7_STREAM; } flags |= PKCS7_PARTIAL; p7 = PKCS7_sign_ex(NULL, NULL, other, in, flags, libctx, app_get0_propq()); if (p7 == NULL) goto end; if (flags & PKCS7_NOCERTS) { for (i = 0; i < sk_X509_num(other); i++) { X509 *x = sk_X509_value(other, i); PKCS7_add_certificate(p7, x); } } } else { flags |= PKCS7_REUSE_DIGEST; } for (i = 0; i < sk_OPENSSL_STRING_num(sksigners); i++) { signerfile = sk_OPENSSL_STRING_value(sksigners, i); keyfile = sk_OPENSSL_STRING_value(skkeys, i); signer = load_cert(signerfile, FORMAT_UNDEF, "signer certificate"); if (signer == NULL) goto end; key = load_key(keyfile, keyform, 0, passin, e, "signing key"); if (key == NULL) goto end; if (!PKCS7_sign_add_signer(p7, signer, key, sign_md, flags)) goto end; X509_free(signer); signer = NULL; EVP_PKEY_free(key); key = NULL; } /* If not streaming or resigning finalize structure */ if ((operation == SMIME_SIGN) && !(flags & PKCS7_STREAM)) { if (!PKCS7_final(p7, in, flags)) goto end; } } if (p7 == NULL) { BIO_printf(bio_err, "Error creating PKCS#7 structure\n"); goto end; } ret = 4; if (operation == SMIME_DECRYPT) { if (!PKCS7_decrypt(p7, key, recip, out, flags)) { BIO_printf(bio_err, "Error decrypting PKCS#7 structure\n"); goto end; } } else if (operation == SMIME_VERIFY) { STACK_OF(X509) *signers; if (PKCS7_verify(p7, other, store, indata, out, flags)) BIO_printf(bio_err, "Verification successful\n"); else { BIO_printf(bio_err, "Verification failure\n"); goto end; } signers = PKCS7_get0_signers(p7, other, flags); if (!save_certs(signerfile, signers)) { BIO_printf(bio_err, "Error writing signers to %s\n", signerfile); ret = 5; goto end; } sk_X509_free(signers); } else if (operation == SMIME_PK7OUT) { PEM_write_bio_PKCS7(out, p7); } else { if (to) BIO_printf(out, "To: %s%s", to, mime_eol); if (from) BIO_printf(out, "From: %s%s", from, mime_eol); if (subject) BIO_printf(out, "Subject: %s%s", subject, mime_eol); if (outformat == FORMAT_SMIME) { if (operation == SMIME_RESIGN) rv = SMIME_write_PKCS7(out, p7, indata, flags); else rv = SMIME_write_PKCS7(out, p7, in, flags); } else if (outformat == FORMAT_PEM) { rv = PEM_write_bio_PKCS7_stream(out, p7, in, flags); } else if (outformat == FORMAT_ASN1) { rv = i2d_PKCS7_bio_stream(out, p7, in, flags); } else { BIO_printf(bio_err, "Bad output format for PKCS#7 file\n"); goto end; } if (rv == 0) { BIO_printf(bio_err, "Error writing output\n"); ret = 3; goto end; } } ret = 0; end: if (ret) ERR_print_errors(bio_err); OSSL_STACK_OF_X509_free(encerts); OSSL_STACK_OF_X509_free(other); X509_VERIFY_PARAM_free(vpm); sk_OPENSSL_STRING_free(sksigners); sk_OPENSSL_STRING_free(skkeys); X509_STORE_free(store); X509_free(cert); X509_free(recip); X509_free(signer); EVP_PKEY_free(key); EVP_MD_free(sign_md); EVP_CIPHER_free(cipher); PKCS7_free(p7); release_engine(e); BIO_free(in); BIO_free(indata); BIO_free_all(out); OPENSSL_free(passin); NCONF_free(conf); return ret; } static int save_certs(char *signerfile, STACK_OF(X509) *signers) { int i; BIO *tmp; if (signerfile == NULL) return 1; tmp = BIO_new_file(signerfile, "w"); if (tmp == NULL) return 0; for (i = 0; i < sk_X509_num(signers); i++) PEM_write_bio_X509(tmp, sk_X509_value(signers, i)); BIO_free(tmp); return 1; } /* Minimal callback just to output policy info (if any) */ static int smime_cb(int ok, X509_STORE_CTX *ctx) { int error; error = X509_STORE_CTX_get_error(ctx); if ((error != X509_V_ERR_NO_EXPLICIT_POLICY) && ((error != X509_V_OK) || (ok != 2))) return ok; policies_print(ctx); return ok; }
./openssl/apps/verify.c
/* * Copyright 1995-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 "apps.h" #include "progs.h" #include <openssl/bio.h> #include <openssl/err.h> #include <openssl/x509.h> #include <openssl/x509v3.h> #include <openssl/pem.h> static int cb(int ok, X509_STORE_CTX *ctx); static int check(X509_STORE *ctx, const char *file, STACK_OF(X509) *uchain, STACK_OF(X509) *tchain, STACK_OF(X509_CRL) *crls, int show_chain, STACK_OF(OPENSSL_STRING) *opts); static int v_verbose = 0, vflags = 0; typedef enum OPTION_choice { OPT_COMMON, OPT_ENGINE, OPT_CAPATH, OPT_CAFILE, OPT_CASTORE, OPT_NOCAPATH, OPT_NOCAFILE, OPT_NOCASTORE, OPT_UNTRUSTED, OPT_TRUSTED, OPT_CRLFILE, OPT_CRL_DOWNLOAD, OPT_SHOW_CHAIN, OPT_V_ENUM, OPT_NAMEOPT, OPT_VFYOPT, OPT_VERBOSE, OPT_PROV_ENUM } OPTION_CHOICE; const OPTIONS verify_options[] = { {OPT_HELP_STR, 1, '-', "Usage: %s [options] [cert...]\n"}, OPT_SECTION("General"), {"help", OPT_HELP, '-', "Display this summary"}, #ifndef OPENSSL_NO_ENGINE {"engine", OPT_ENGINE, 's', "Use engine, possibly a hardware device"}, #endif {"verbose", OPT_VERBOSE, '-', "Print extra information about the operations being performed."}, {"nameopt", OPT_NAMEOPT, 's', "Certificate subject/issuer name printing options"}, OPT_SECTION("Certificate chain"), {"trusted", OPT_TRUSTED, '<', "A file of trusted certificates"}, {"CAfile", OPT_CAFILE, '<', "A file of trusted certificates"}, {"CApath", OPT_CAPATH, '/', "A directory of files with trusted certificates"}, {"CAstore", OPT_CASTORE, ':', "URI to a store of trusted certificates"}, {"no-CAfile", OPT_NOCAFILE, '-', "Do not load the default trusted certificates file"}, {"no-CApath", OPT_NOCAPATH, '-', "Do not load trusted certificates from the default directory"}, {"no-CAstore", OPT_NOCASTORE, '-', "Do not load trusted certificates from the default certificates store"}, {"untrusted", OPT_UNTRUSTED, '<', "A file of untrusted certificates"}, {"CRLfile", OPT_CRLFILE, '<', "File containing one or more CRL's (in PEM format) to load"}, {"crl_download", OPT_CRL_DOWNLOAD, '-', "Try downloading CRL information for certificates via their CDP entries"}, {"show_chain", OPT_SHOW_CHAIN, '-', "Display information about the certificate chain"}, OPT_V_OPTIONS, {"vfyopt", OPT_VFYOPT, 's', "Verification parameter in n:v form"}, OPT_PROV_OPTIONS, OPT_PARAMETERS(), {"cert", 0, 0, "Certificate(s) to verify (optional; stdin used otherwise)"}, {NULL} }; int verify_main(int argc, char **argv) { ENGINE *e = NULL; STACK_OF(X509) *untrusted = NULL, *trusted = NULL; STACK_OF(X509_CRL) *crls = NULL; STACK_OF(OPENSSL_STRING) *vfyopts = NULL; X509_STORE *store = NULL; X509_VERIFY_PARAM *vpm = NULL; const char *prog, *CApath = NULL, *CAfile = NULL, *CAstore = NULL; int noCApath = 0, noCAfile = 0, noCAstore = 0; int vpmtouched = 0, crl_download = 0, show_chain = 0, i = 0, ret = 1; OPTION_CHOICE o; if ((vpm = X509_VERIFY_PARAM_new()) == NULL) goto end; prog = opt_init(argc, argv, verify_options); while ((o = opt_next()) != OPT_EOF) { switch (o) { case OPT_EOF: case OPT_ERR: opthelp: BIO_printf(bio_err, "%s: Use -help for summary.\n", prog); goto end; case OPT_HELP: opt_help(verify_options); BIO_printf(bio_err, "\nRecognized certificate chain purposes:\n"); for (i = 0; i < X509_PURPOSE_get_count(); i++) { X509_PURPOSE *ptmp = X509_PURPOSE_get0(i); BIO_printf(bio_err, " %-15s %s\n", X509_PURPOSE_get0_sname(ptmp), X509_PURPOSE_get0_name(ptmp)); } BIO_printf(bio_err, "Recognized certificate policy names:\n"); for (i = 0; i < X509_VERIFY_PARAM_get_count(); i++) { const X509_VERIFY_PARAM *vptmp = X509_VERIFY_PARAM_get0(i); BIO_printf(bio_err, " %s\n", X509_VERIFY_PARAM_get0_name(vptmp)); } ret = 0; goto end; case OPT_V_CASES: if (!opt_verify(o, vpm)) goto end; vpmtouched++; break; case OPT_CAPATH: CApath = opt_arg(); break; case OPT_CAFILE: CAfile = opt_arg(); break; case OPT_CASTORE: CAstore = opt_arg(); break; case OPT_NOCAPATH: noCApath = 1; break; case OPT_NOCAFILE: noCAfile = 1; break; case OPT_NOCASTORE: noCAstore = 1; break; case OPT_UNTRUSTED: /* Zero or more times */ if (!load_certs(opt_arg(), 0, &untrusted, NULL, "untrusted certificates")) goto end; break; case OPT_TRUSTED: /* Zero or more times */ noCAfile = 1; noCApath = 1; noCAstore = 1; if (!load_certs(opt_arg(), 0, &trusted, NULL, "trusted certificates")) goto end; break; case OPT_CRLFILE: /* Zero or more times */ if (!load_crls(opt_arg(), &crls, NULL, "other CRLs")) goto end; break; case OPT_CRL_DOWNLOAD: crl_download = 1; break; case OPT_ENGINE: if ((e = setup_engine(opt_arg(), 0)) == NULL) { /* Failure message already displayed */ goto end; } break; case OPT_SHOW_CHAIN: show_chain = 1; break; case OPT_NAMEOPT: if (!set_nameopt(opt_arg())) goto end; break; case OPT_VFYOPT: if (!vfyopts) vfyopts = sk_OPENSSL_STRING_new_null(); if (!vfyopts || !sk_OPENSSL_STRING_push(vfyopts, opt_arg())) goto opthelp; break; case OPT_VERBOSE: v_verbose = 1; break; case OPT_PROV_CASES: if (!opt_provider(o)) goto end; break; } } /* Extra arguments are certificates to verify. */ argc = opt_num_rest(); argv = opt_rest(); if (trusted != NULL && (CAfile != NULL || CApath != NULL || CAstore != NULL)) { BIO_printf(bio_err, "%s: Cannot use -trusted with -CAfile, -CApath or -CAstore\n", prog); goto end; } if ((store = setup_verify(CAfile, noCAfile, CApath, noCApath, CAstore, noCAstore)) == NULL) goto end; X509_STORE_set_verify_cb(store, cb); if (vpmtouched) X509_STORE_set1_param(store, vpm); ERR_clear_error(); if (crl_download) store_setup_crl_download(store); ret = 0; if (argc < 1) { if (check(store, NULL, untrusted, trusted, crls, show_chain, vfyopts) != 1) ret = -1; } else { for (i = 0; i < argc; i++) if (check(store, argv[i], untrusted, trusted, crls, show_chain, vfyopts) != 1) ret = -1; } end: X509_VERIFY_PARAM_free(vpm); X509_STORE_free(store); OSSL_STACK_OF_X509_free(untrusted); OSSL_STACK_OF_X509_free(trusted); sk_X509_CRL_pop_free(crls, X509_CRL_free); sk_OPENSSL_STRING_free(vfyopts); release_engine(e); return (ret < 0 ? 2 : ret); } static int check(X509_STORE *ctx, const char *file, STACK_OF(X509) *uchain, STACK_OF(X509) *tchain, STACK_OF(X509_CRL) *crls, int show_chain, STACK_OF(OPENSSL_STRING) *opts) { X509 *x = NULL; int i = 0, ret = 0; X509_STORE_CTX *csc; STACK_OF(X509) *chain = NULL; int num_untrusted; x = load_cert(file, FORMAT_UNDEF, "certificate file"); if (x == NULL) goto end; if (opts != NULL) { for (i = 0; i < sk_OPENSSL_STRING_num(opts); i++) { char *opt = sk_OPENSSL_STRING_value(opts, i); if (x509_ctrl_string(x, opt) <= 0) { BIO_printf(bio_err, "parameter error \"%s\"\n", opt); ERR_print_errors(bio_err); X509_free(x); return 0; } } } csc = X509_STORE_CTX_new(); if (csc == NULL) { BIO_printf(bio_err, "error %s: X.509 store context allocation failed\n", (file == NULL) ? "stdin" : file); goto end; } X509_STORE_set_flags(ctx, vflags); if (!X509_STORE_CTX_init(csc, ctx, x, uchain)) { X509_STORE_CTX_free(csc); BIO_printf(bio_err, "error %s: X.509 store context initialization failed\n", (file == NULL) ? "stdin" : file); goto end; } if (tchain != NULL) X509_STORE_CTX_set0_trusted_stack(csc, tchain); if (crls != NULL) X509_STORE_CTX_set0_crls(csc, crls); i = X509_verify_cert(csc); if (i > 0 && X509_STORE_CTX_get_error(csc) == X509_V_OK) { BIO_printf(bio_out, "%s: OK\n", (file == NULL) ? "stdin" : file); ret = 1; if (show_chain) { int j; chain = X509_STORE_CTX_get1_chain(csc); num_untrusted = X509_STORE_CTX_get_num_untrusted(csc); BIO_printf(bio_out, "Chain:\n"); for (j = 0; j < sk_X509_num(chain); j++) { X509 *cert = sk_X509_value(chain, j); BIO_printf(bio_out, "depth=%d: ", j); X509_NAME_print_ex_fp(stdout, X509_get_subject_name(cert), 0, get_nameopt()); if (j < num_untrusted) BIO_printf(bio_out, " (untrusted)"); BIO_printf(bio_out, "\n"); } OSSL_STACK_OF_X509_free(chain); } } else { BIO_printf(bio_err, "error %s: verification failed\n", (file == NULL) ? "stdin" : file); } X509_STORE_CTX_free(csc); end: if (i <= 0) ERR_print_errors(bio_err); X509_free(x); return ret; } static int cb(int ok, X509_STORE_CTX *ctx) { int cert_error = X509_STORE_CTX_get_error(ctx); X509 *current_cert = X509_STORE_CTX_get_current_cert(ctx); if (!ok) { if (current_cert != NULL) { X509_NAME_print_ex(bio_err, X509_get_subject_name(current_cert), 0, get_nameopt()); BIO_printf(bio_err, "\n"); } BIO_printf(bio_err, "%serror %d at %d depth lookup: %s\n", X509_STORE_CTX_get0_parent_ctx(ctx) ? "[CRL path] " : "", cert_error, X509_STORE_CTX_get_error_depth(ctx), X509_verify_cert_error_string(cert_error)); /* * Pretend that some errors are ok, so they don't stop further * processing of the certificate chain. Setting ok = 1 does this. * After X509_verify_cert() is done, we verify that there were * no actual errors, even if the returned value was positive. */ switch (cert_error) { case X509_V_ERR_NO_EXPLICIT_POLICY: policies_print(ctx); /* fall through */ case X509_V_ERR_CERT_HAS_EXPIRED: /* Continue even if the leaf is a self-signed cert */ case X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT: /* Continue after extension errors too */ case X509_V_ERR_INVALID_CA: case X509_V_ERR_INVALID_NON_CA: case X509_V_ERR_PATH_LENGTH_EXCEEDED: case X509_V_ERR_CRL_HAS_EXPIRED: case X509_V_ERR_CRL_NOT_YET_VALID: case X509_V_ERR_UNHANDLED_CRITICAL_EXTENSION: /* errors due to strict conformance checking (-x509_strict) */ case X509_V_ERR_INVALID_PURPOSE: case X509_V_ERR_PATHLEN_INVALID_FOR_NON_CA: case X509_V_ERR_PATHLEN_WITHOUT_KU_KEY_CERT_SIGN: case X509_V_ERR_CA_BCONS_NOT_CRITICAL: case X509_V_ERR_CA_CERT_MISSING_KEY_USAGE: case X509_V_ERR_KU_KEY_CERT_SIGN_INVALID_FOR_NON_CA: case X509_V_ERR_ISSUER_NAME_EMPTY: case X509_V_ERR_SUBJECT_NAME_EMPTY: case X509_V_ERR_EMPTY_SUBJECT_SAN_NOT_CRITICAL: case X509_V_ERR_EMPTY_SUBJECT_ALT_NAME: case X509_V_ERR_SIGNATURE_ALGORITHM_INCONSISTENCY: case X509_V_ERR_AUTHORITY_KEY_IDENTIFIER_CRITICAL: case X509_V_ERR_SUBJECT_KEY_IDENTIFIER_CRITICAL: case X509_V_ERR_MISSING_AUTHORITY_KEY_IDENTIFIER: case X509_V_ERR_MISSING_SUBJECT_KEY_IDENTIFIER: case X509_V_ERR_EXTENSIONS_REQUIRE_VERSION_3: ok = 1; } return ok; } if (cert_error == X509_V_OK && ok == 2) policies_print(ctx); if (!v_verbose) ERR_clear_error(); return ok; }
./openssl/apps/sess_id.c
/* * Copyright 1995-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 <stdlib.h> #include <string.h> #include "apps.h" #include "progs.h" #include <openssl/bio.h> #include <openssl/err.h> #include <openssl/x509.h> #include <openssl/pem.h> #include <openssl/ssl.h> typedef enum OPTION_choice { OPT_COMMON, OPT_INFORM, OPT_OUTFORM, OPT_IN, OPT_OUT, OPT_TEXT, OPT_CERT, OPT_NOOUT, OPT_CONTEXT } OPTION_CHOICE; const OPTIONS sess_id_options[] = { OPT_SECTION("General"), {"help", OPT_HELP, '-', "Display this summary"}, {"context", OPT_CONTEXT, 's', "Set the session ID context"}, OPT_SECTION("Input"), {"in", OPT_IN, 's', "Input file - default stdin"}, {"inform", OPT_INFORM, 'F', "Input format - default PEM (DER or PEM)"}, OPT_SECTION("Output"), {"out", OPT_OUT, '>', "Output file - default stdout"}, {"outform", OPT_OUTFORM, 'f', "Output format - default PEM (PEM, DER or NSS)"}, {"text", OPT_TEXT, '-', "Print ssl session id details"}, {"cert", OPT_CERT, '-', "Output certificate "}, {"noout", OPT_NOOUT, '-', "Don't output the encoded session info"}, {NULL} }; static SSL_SESSION *load_sess_id(char *file, int format); int sess_id_main(int argc, char **argv) { SSL_SESSION *x = NULL; X509 *peer = NULL; BIO *out = NULL; char *infile = NULL, *outfile = NULL, *context = NULL, *prog; int informat = FORMAT_PEM, outformat = FORMAT_PEM; int cert = 0, noout = 0, text = 0, ret = 1, i, num = 0; OPTION_CHOICE o; prog = opt_init(argc, argv, sess_id_options); while ((o = opt_next()) != OPT_EOF) { switch (o) { case OPT_EOF: case OPT_ERR: opthelp: BIO_printf(bio_err, "%s: Use -help for summary.\n", prog); goto end; case OPT_HELP: opt_help(sess_id_options); ret = 0; goto end; case OPT_INFORM: if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &informat)) goto opthelp; break; case OPT_OUTFORM: if (!opt_format(opt_arg(), OPT_FMT_PEMDER | OPT_FMT_NSS, &outformat)) goto opthelp; break; case OPT_IN: infile = opt_arg(); break; case OPT_OUT: outfile = opt_arg(); break; case OPT_TEXT: text = ++num; break; case OPT_CERT: cert = ++num; break; case OPT_NOOUT: noout = ++num; break; case OPT_CONTEXT: context = opt_arg(); break; } } /* No extra arguments. */ if (!opt_check_rest_arg(NULL)) goto opthelp; x = load_sess_id(infile, informat); if (x == NULL) { goto end; } peer = SSL_SESSION_get0_peer(x); if (context != NULL) { size_t ctx_len = strlen(context); if (ctx_len > SSL_MAX_SID_CTX_LENGTH) { BIO_printf(bio_err, "Context too long\n"); goto end; } if (!SSL_SESSION_set1_id_context(x, (unsigned char *)context, ctx_len)) { BIO_printf(bio_err, "Error setting id context\n"); goto end; } } if (!noout || text) { out = bio_open_default(outfile, 'w', outformat); if (out == NULL) goto end; } if (text) { SSL_SESSION_print(out, x); if (cert) { if (peer == NULL) BIO_puts(out, "No certificate present\n"); else X509_print(out, peer); } } if (!noout && !cert) { if (outformat == FORMAT_ASN1) { i = i2d_SSL_SESSION_bio(out, x); } else if (outformat == FORMAT_PEM) { i = PEM_write_bio_SSL_SESSION(out, x); } else if (outformat == FORMAT_NSS) { i = SSL_SESSION_print_keylog(out, x); } else { BIO_printf(bio_err, "bad output format specified for outfile\n"); goto end; } if (!i) { BIO_printf(bio_err, "unable to write SSL_SESSION\n"); goto end; } } else if (!noout && (peer != NULL)) { /* just print the certificate */ if (outformat == FORMAT_ASN1) { i = (int)i2d_X509_bio(out, peer); } else if (outformat == FORMAT_PEM) { i = PEM_write_bio_X509(out, peer); } else { BIO_printf(bio_err, "bad output format specified for outfile\n"); goto end; } if (!i) { BIO_printf(bio_err, "unable to write X509\n"); goto end; } } ret = 0; end: BIO_free_all(out); SSL_SESSION_free(x); return ret; } static SSL_SESSION *load_sess_id(char *infile, int format) { SSL_SESSION *x = NULL; BIO *in = NULL; in = bio_open_default(infile, 'r', format); if (in == NULL) goto end; if (format == FORMAT_ASN1) x = d2i_SSL_SESSION_bio(in, NULL); else x = PEM_read_bio_SSL_SESSION(in, NULL, NULL, NULL); if (x == NULL) { BIO_printf(bio_err, "unable to load SSL_SESSION\n"); ERR_print_errors(bio_err); goto end; } end: BIO_free(in); return x; }
./openssl/apps/spkac.c
/* * Copyright 1999-2023 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> #include "apps.h" #include "progs.h" #include <openssl/bio.h> #include <openssl/conf.h> #include <openssl/err.h> #include <openssl/evp.h> #include <openssl/x509.h> #include <openssl/pem.h> typedef enum OPTION_choice { OPT_COMMON, OPT_NOOUT, OPT_PUBKEY, OPT_VERIFY, OPT_IN, OPT_OUT, OPT_ENGINE, OPT_KEY, OPT_CHALLENGE, OPT_PASSIN, OPT_SPKAC, OPT_SPKSECT, OPT_KEYFORM, OPT_DIGEST, OPT_PROV_ENUM } OPTION_CHOICE; const OPTIONS spkac_options[] = { OPT_SECTION("General"), {"help", OPT_HELP, '-', "Display this summary"}, {"spksect", OPT_SPKSECT, 's', "Specify the name of an SPKAC-dedicated section of configuration"}, #ifndef OPENSSL_NO_ENGINE {"engine", OPT_ENGINE, 's', "Use engine, possibly a hardware device"}, #endif OPT_SECTION("Input"), {"in", OPT_IN, '<', "Input file"}, {"key", OPT_KEY, '<', "Create SPKAC using private key"}, {"keyform", OPT_KEYFORM, 'f', "Private key file format (ENGINE, other values ignored)"}, {"passin", OPT_PASSIN, 's', "Input file pass phrase source"}, {"challenge", OPT_CHALLENGE, 's', "Challenge string"}, {"spkac", OPT_SPKAC, 's', "Alternative SPKAC name"}, OPT_SECTION("Output"), {"digest", OPT_DIGEST, 's', "Sign new SPKAC with the specified digest (default: MD5)" }, {"out", OPT_OUT, '>', "Output file"}, {"noout", OPT_NOOUT, '-', "Don't print SPKAC"}, {"pubkey", OPT_PUBKEY, '-', "Output public key"}, {"verify", OPT_VERIFY, '-', "Verify SPKAC signature"}, OPT_PROV_OPTIONS, {NULL} }; int spkac_main(int argc, char **argv) { BIO *out = NULL; CONF *conf = NULL; ENGINE *e = NULL; EVP_PKEY *pkey = NULL; NETSCAPE_SPKI *spki = NULL; char *challenge = NULL, *keyfile = NULL; char *infile = NULL, *outfile = NULL, *passinarg = NULL, *passin = NULL; char *spkstr = NULL, *prog; const char *spkac = "SPKAC", *spksect = "default"; const char *digest = "MD5"; EVP_MD *md = NULL; int i, ret = 1, verify = 0, noout = 0, pubkey = 0; int keyformat = FORMAT_UNDEF; OPTION_CHOICE o; prog = opt_init(argc, argv, spkac_options); while ((o = opt_next()) != OPT_EOF) { switch (o) { case OPT_EOF: case OPT_ERR: opthelp: BIO_printf(bio_err, "%s: Use -help for summary.\n", prog); goto end; case OPT_HELP: opt_help(spkac_options); ret = 0; goto end; case OPT_IN: infile = opt_arg(); break; case OPT_OUT: outfile = opt_arg(); break; case OPT_NOOUT: noout = 1; break; case OPT_PUBKEY: pubkey = 1; break; case OPT_VERIFY: verify = 1; break; case OPT_PASSIN: passinarg = opt_arg(); break; case OPT_KEY: keyfile = opt_arg(); break; case OPT_KEYFORM: if (!opt_format(opt_arg(), OPT_FMT_ANY, &keyformat)) goto opthelp; break; case OPT_CHALLENGE: challenge = opt_arg(); break; case OPT_SPKAC: spkac = opt_arg(); break; case OPT_SPKSECT: spksect = opt_arg(); break; case OPT_DIGEST: digest = opt_arg(); break; case OPT_ENGINE: e = setup_engine(opt_arg(), 0); break; case OPT_PROV_CASES: if (!opt_provider(o)) goto end; break; } } /* No extra arguments. */ if (!opt_check_rest_arg(NULL)) goto opthelp; if (!app_passwd(passinarg, NULL, &passin, NULL)) { BIO_printf(bio_err, "Error getting password\n"); goto end; } if (keyfile != NULL) { if (!opt_md(digest, &md)) goto end; pkey = load_key(strcmp(keyfile, "-") ? keyfile : NULL, keyformat, 1, passin, e, "private key"); if (pkey == NULL) goto end; spki = NETSCAPE_SPKI_new(); if (spki == NULL) goto end; if (challenge != NULL && !ASN1_STRING_set(spki->spkac->challenge, challenge, (int)strlen(challenge))) goto end; if (!NETSCAPE_SPKI_set_pubkey(spki, pkey)) { BIO_printf(bio_err, "Error setting public key\n"); goto end; } i = NETSCAPE_SPKI_sign(spki, pkey, md); if (i <= 0) { BIO_printf(bio_err, "Error signing SPKAC\n"); goto end; } spkstr = NETSCAPE_SPKI_b64_encode(spki); if (spkstr == NULL) goto end; out = bio_open_default(outfile, 'w', FORMAT_TEXT); if (out == NULL) { OPENSSL_free(spkstr); goto end; } BIO_printf(out, "SPKAC=%s\n", spkstr); OPENSSL_free(spkstr); ret = 0; goto end; } if ((conf = app_load_config(infile)) == NULL) goto end; spkstr = NCONF_get_string(conf, spksect, spkac); if (spkstr == NULL) { BIO_printf(bio_err, "Can't find SPKAC called \"%s\"\n", spkac); ERR_print_errors(bio_err); goto end; } spki = NETSCAPE_SPKI_b64_decode(spkstr, -1); if (spki == NULL) { BIO_printf(bio_err, "Error loading SPKAC\n"); ERR_print_errors(bio_err); goto end; } out = bio_open_default(outfile, 'w', FORMAT_TEXT); if (out == NULL) goto end; if (!noout) NETSCAPE_SPKI_print(out, spki); pkey = NETSCAPE_SPKI_get_pubkey(spki); if (verify) { i = NETSCAPE_SPKI_verify(spki, pkey); if (i > 0) { BIO_printf(bio_err, "Signature OK\n"); } else { BIO_printf(bio_err, "Signature Failure\n"); ERR_print_errors(bio_err); goto end; } } if (pubkey) PEM_write_bio_PUBKEY(out, pkey); ret = 0; end: EVP_MD_free(md); NCONF_free(conf); NETSCAPE_SPKI_free(spki); BIO_free_all(out); EVP_PKEY_free(pkey); release_engine(e); OPENSSL_free(passin); return ret; }
./openssl/apps/speed.c
/* * Copyright 1995-2023 The OpenSSL Project Authors. All Rights Reserved. * Copyright (c) 2002, Oracle and/or its affiliates. All rights reserved * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #undef SECONDS #define SECONDS 3 #define PKEY_SECONDS 10 #define RSA_SECONDS PKEY_SECONDS #define DSA_SECONDS PKEY_SECONDS #define ECDSA_SECONDS PKEY_SECONDS #define ECDH_SECONDS PKEY_SECONDS #define EdDSA_SECONDS PKEY_SECONDS #define SM2_SECONDS PKEY_SECONDS #define FFDH_SECONDS PKEY_SECONDS #define KEM_SECONDS PKEY_SECONDS #define SIG_SECONDS PKEY_SECONDS #define MAX_ALGNAME_SUFFIX 100 /* We need to use some deprecated APIs */ #define OPENSSL_SUPPRESS_DEPRECATED #include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #include "apps.h" #include "progs.h" #include "internal/nelem.h" #include "internal/numbers.h" #include <openssl/crypto.h> #include <openssl/rand.h> #include <openssl/err.h> #include <openssl/evp.h> #include <openssl/objects.h> #include <openssl/core_names.h> #include <openssl/async.h> #include <openssl/provider.h> #if !defined(OPENSSL_SYS_MSDOS) # include <unistd.h> #endif #if defined(__TANDEM) # if defined(OPENSSL_TANDEM_FLOSS) # include <floss.h(floss_fork)> # endif #endif #if defined(_WIN32) # include <windows.h> /* * While VirtualLock is available under the app partition (e.g. UWP), * the headers do not define the API. Define it ourselves instead. */ WINBASEAPI BOOL WINAPI VirtualLock( _In_ LPVOID lpAddress, _In_ SIZE_T dwSize ); #endif #if defined(OPENSSL_SYS_LINUX) # include <sys/mman.h> #endif #include <openssl/bn.h> #include <openssl/rsa.h> #include "./testrsa.h" #ifndef OPENSSL_NO_DH # include <openssl/dh.h> #endif #include <openssl/x509.h> #include <openssl/dsa.h> #include "./testdsa.h" #include <openssl/modes.h> #ifndef HAVE_FORK # if defined(OPENSSL_SYS_VMS) || defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_VXWORKS) # define HAVE_FORK 0 # else # define HAVE_FORK 1 # include <sys/wait.h> # endif #endif #if HAVE_FORK # undef NO_FORK #else # define NO_FORK #endif #define MAX_MISALIGNMENT 63 #define MAX_ECDH_SIZE 256 #define MISALIGN 64 #define MAX_FFDH_SIZE 1024 #ifndef RSA_DEFAULT_PRIME_NUM # define RSA_DEFAULT_PRIME_NUM 2 #endif typedef struct openssl_speed_sec_st { int sym; int rsa; int dsa; int ecdsa; int ecdh; int eddsa; int sm2; int ffdh; int kem; int sig; } openssl_speed_sec_t; static volatile int run = 0; static int mr = 0; /* machine-readeable output format to merge fork results */ static int usertime = 1; static double Time_F(int s); static void print_message(const char *s, int length, int tm); static void pkey_print_message(const char *str, const char *str2, unsigned int bits, int sec); static void kskey_print_message(const char *str, const char *str2, int tm); static void print_result(int alg, int run_no, int count, double time_used); #ifndef NO_FORK static int do_multi(int multi, int size_num); #endif static int domlock = 0; static const int lengths_list[] = { 16, 64, 256, 1024, 8 * 1024, 16 * 1024 }; #define SIZE_NUM OSSL_NELEM(lengths_list) static const int *lengths = lengths_list; static const int aead_lengths_list[] = { 2, 31, 136, 1024, 8 * 1024, 16 * 1024 }; #define START 0 #define STOP 1 #ifdef SIGALRM static void alarmed(ossl_unused int sig) { signal(SIGALRM, alarmed); run = 0; } static double Time_F(int s) { double ret = app_tminterval(s, usertime); if (s == STOP) alarm(0); return ret; } #elif defined(_WIN32) # define SIGALRM -1 static unsigned int lapse; static volatile unsigned int schlock; static void alarm_win32(unsigned int secs) { lapse = secs * 1000; } # define alarm alarm_win32 static DWORD WINAPI sleepy(VOID * arg) { schlock = 1; Sleep(lapse); run = 0; return 0; } static double Time_F(int s) { double ret; static HANDLE thr; if (s == START) { schlock = 0; thr = CreateThread(NULL, 4096, sleepy, NULL, 0, NULL); if (thr == NULL) { DWORD err = GetLastError(); BIO_printf(bio_err, "unable to CreateThread (%lu)", err); ExitProcess(err); } while (!schlock) Sleep(0); /* scheduler spinlock */ ret = app_tminterval(s, usertime); } else { ret = app_tminterval(s, usertime); if (run) TerminateThread(thr, 0); CloseHandle(thr); } return ret; } #else # error "SIGALRM not defined and the platform is not Windows" #endif static void multiblock_speed(const EVP_CIPHER *evp_cipher, int lengths_single, const openssl_speed_sec_t *seconds); static int opt_found(const char *name, unsigned int *result, const OPT_PAIR pairs[], unsigned int nbelem) { unsigned int idx; for (idx = 0; idx < nbelem; ++idx, pairs++) if (strcmp(name, pairs->name) == 0) { *result = pairs->retval; return 1; } return 0; } #define opt_found(value, pairs, result)\ opt_found(value, result, pairs, OSSL_NELEM(pairs)) typedef enum OPTION_choice { OPT_COMMON, OPT_ELAPSED, OPT_EVP, OPT_HMAC, OPT_DECRYPT, OPT_ENGINE, OPT_MULTI, OPT_MR, OPT_MB, OPT_MISALIGN, OPT_ASYNCJOBS, OPT_R_ENUM, OPT_PROV_ENUM, OPT_CONFIG, OPT_PRIMES, OPT_SECONDS, OPT_BYTES, OPT_AEAD, OPT_CMAC, OPT_MLOCK, OPT_KEM, OPT_SIG } OPTION_CHOICE; const OPTIONS speed_options[] = { {OPT_HELP_STR, 1, '-', "Usage: %s [options] [algorithm...]\n" "All +int options consider prefix '0' as base-8 input, " "prefix '0x'/'0X' as base-16 input.\n" }, OPT_SECTION("General"), {"help", OPT_HELP, '-', "Display this summary"}, {"mb", OPT_MB, '-', "Enable (tls1>=1) multi-block mode on EVP-named cipher"}, {"mr", OPT_MR, '-', "Produce machine readable output"}, #ifndef NO_FORK {"multi", OPT_MULTI, 'p', "Run benchmarks in parallel"}, #endif #ifndef OPENSSL_NO_ASYNC {"async_jobs", OPT_ASYNCJOBS, 'p', "Enable async mode and start specified number of jobs"}, #endif #ifndef OPENSSL_NO_ENGINE {"engine", OPT_ENGINE, 's', "Use engine, possibly a hardware device"}, #endif {"primes", OPT_PRIMES, 'p', "Specify number of primes (for RSA only)"}, {"mlock", OPT_MLOCK, '-', "Lock memory for better result determinism"}, OPT_CONFIG_OPTION, OPT_SECTION("Selection"), {"evp", OPT_EVP, 's', "Use EVP-named cipher or digest"}, {"hmac", OPT_HMAC, 's', "HMAC using EVP-named digest"}, {"cmac", OPT_CMAC, 's', "CMAC using EVP-named cipher"}, {"decrypt", OPT_DECRYPT, '-', "Time decryption instead of encryption (only EVP)"}, {"aead", OPT_AEAD, '-', "Benchmark EVP-named AEAD cipher in TLS-like sequence"}, {"kem-algorithms", OPT_KEM, '-', "Benchmark KEM algorithms"}, {"signature-algorithms", OPT_SIG, '-', "Benchmark signature algorithms"}, OPT_SECTION("Timing"), {"elapsed", OPT_ELAPSED, '-', "Use wall-clock time instead of CPU user time as divisor"}, {"seconds", OPT_SECONDS, 'p', "Run benchmarks for specified amount of seconds"}, {"bytes", OPT_BYTES, 'p', "Run [non-PKI] benchmarks on custom-sized buffer"}, {"misalign", OPT_MISALIGN, 'p', "Use specified offset to mis-align buffers"}, OPT_R_OPTIONS, OPT_PROV_OPTIONS, OPT_PARAMETERS(), {"algorithm", 0, 0, "Algorithm(s) to test (optional; otherwise tests all)"}, {NULL} }; enum { D_MD2, D_MDC2, D_MD4, D_MD5, D_SHA1, D_RMD160, D_SHA256, D_SHA512, D_WHIRLPOOL, D_HMAC, D_CBC_DES, D_EDE3_DES, D_RC4, D_CBC_IDEA, D_CBC_SEED, D_CBC_RC2, D_CBC_RC5, D_CBC_BF, D_CBC_CAST, D_CBC_128_AES, D_CBC_192_AES, D_CBC_256_AES, D_CBC_128_CML, D_CBC_192_CML, D_CBC_256_CML, D_EVP, D_GHASH, D_RAND, D_EVP_CMAC, D_KMAC128, D_KMAC256, ALGOR_NUM }; /* name of algorithms to test. MUST BE KEEP IN SYNC with above enum ! */ static const char *names[ALGOR_NUM] = { "md2", "mdc2", "md4", "md5", "sha1", "rmd160", "sha256", "sha512", "whirlpool", "hmac(sha256)", "des-cbc", "des-ede3", "rc4", "idea-cbc", "seed-cbc", "rc2-cbc", "rc5-cbc", "blowfish", "cast-cbc", "aes-128-cbc", "aes-192-cbc", "aes-256-cbc", "camellia-128-cbc", "camellia-192-cbc", "camellia-256-cbc", "evp", "ghash", "rand", "cmac", "kmac128", "kmac256" }; /* list of configured algorithm (remaining), with some few alias */ static const OPT_PAIR doit_choices[] = { {"md2", D_MD2}, {"mdc2", D_MDC2}, {"md4", D_MD4}, {"md5", D_MD5}, {"hmac", D_HMAC}, {"sha1", D_SHA1}, {"sha256", D_SHA256}, {"sha512", D_SHA512}, {"whirlpool", D_WHIRLPOOL}, {"ripemd", D_RMD160}, {"rmd160", D_RMD160}, {"ripemd160", D_RMD160}, {"rc4", D_RC4}, {"des-cbc", D_CBC_DES}, {"des-ede3", D_EDE3_DES}, {"aes-128-cbc", D_CBC_128_AES}, {"aes-192-cbc", D_CBC_192_AES}, {"aes-256-cbc", D_CBC_256_AES}, {"camellia-128-cbc", D_CBC_128_CML}, {"camellia-192-cbc", D_CBC_192_CML}, {"camellia-256-cbc", D_CBC_256_CML}, {"rc2-cbc", D_CBC_RC2}, {"rc2", D_CBC_RC2}, {"rc5-cbc", D_CBC_RC5}, {"rc5", D_CBC_RC5}, {"idea-cbc", D_CBC_IDEA}, {"idea", D_CBC_IDEA}, {"seed-cbc", D_CBC_SEED}, {"seed", D_CBC_SEED}, {"bf-cbc", D_CBC_BF}, {"blowfish", D_CBC_BF}, {"bf", D_CBC_BF}, {"cast-cbc", D_CBC_CAST}, {"cast", D_CBC_CAST}, {"cast5", D_CBC_CAST}, {"ghash", D_GHASH}, {"rand", D_RAND}, {"kmac128", D_KMAC128}, {"kmac256", D_KMAC256}, }; static double results[ALGOR_NUM][SIZE_NUM]; enum { R_DSA_1024, R_DSA_2048, DSA_NUM }; static const OPT_PAIR dsa_choices[DSA_NUM] = { {"dsa1024", R_DSA_1024}, {"dsa2048", R_DSA_2048} }; static double dsa_results[DSA_NUM][2]; /* 2 ops: sign then verify */ enum { R_RSA_512, R_RSA_1024, R_RSA_2048, R_RSA_3072, R_RSA_4096, R_RSA_7680, R_RSA_15360, RSA_NUM }; static const OPT_PAIR rsa_choices[RSA_NUM] = { {"rsa512", R_RSA_512}, {"rsa1024", R_RSA_1024}, {"rsa2048", R_RSA_2048}, {"rsa3072", R_RSA_3072}, {"rsa4096", R_RSA_4096}, {"rsa7680", R_RSA_7680}, {"rsa15360", R_RSA_15360} }; static double rsa_results[RSA_NUM][4]; /* 4 ops: sign, verify, encrypt, decrypt */ #ifndef OPENSSL_NO_DH enum ff_params_t { R_FFDH_2048, R_FFDH_3072, R_FFDH_4096, R_FFDH_6144, R_FFDH_8192, FFDH_NUM }; static const OPT_PAIR ffdh_choices[FFDH_NUM] = { {"ffdh2048", R_FFDH_2048}, {"ffdh3072", R_FFDH_3072}, {"ffdh4096", R_FFDH_4096}, {"ffdh6144", R_FFDH_6144}, {"ffdh8192", R_FFDH_8192}, }; static double ffdh_results[FFDH_NUM][1]; /* 1 op: derivation */ #endif /* OPENSSL_NO_DH */ enum ec_curves_t { R_EC_P160, R_EC_P192, R_EC_P224, R_EC_P256, R_EC_P384, R_EC_P521, #ifndef OPENSSL_NO_EC2M R_EC_K163, R_EC_K233, R_EC_K283, R_EC_K409, R_EC_K571, R_EC_B163, R_EC_B233, R_EC_B283, R_EC_B409, R_EC_B571, #endif R_EC_BRP256R1, R_EC_BRP256T1, R_EC_BRP384R1, R_EC_BRP384T1, R_EC_BRP512R1, R_EC_BRP512T1, ECDSA_NUM }; /* list of ecdsa curves */ static const OPT_PAIR ecdsa_choices[ECDSA_NUM] = { {"ecdsap160", R_EC_P160}, {"ecdsap192", R_EC_P192}, {"ecdsap224", R_EC_P224}, {"ecdsap256", R_EC_P256}, {"ecdsap384", R_EC_P384}, {"ecdsap521", R_EC_P521}, #ifndef OPENSSL_NO_EC2M {"ecdsak163", R_EC_K163}, {"ecdsak233", R_EC_K233}, {"ecdsak283", R_EC_K283}, {"ecdsak409", R_EC_K409}, {"ecdsak571", R_EC_K571}, {"ecdsab163", R_EC_B163}, {"ecdsab233", R_EC_B233}, {"ecdsab283", R_EC_B283}, {"ecdsab409", R_EC_B409}, {"ecdsab571", R_EC_B571}, #endif {"ecdsabrp256r1", R_EC_BRP256R1}, {"ecdsabrp256t1", R_EC_BRP256T1}, {"ecdsabrp384r1", R_EC_BRP384R1}, {"ecdsabrp384t1", R_EC_BRP384T1}, {"ecdsabrp512r1", R_EC_BRP512R1}, {"ecdsabrp512t1", R_EC_BRP512T1} }; enum { #ifndef OPENSSL_NO_ECX R_EC_X25519 = ECDSA_NUM, R_EC_X448, EC_NUM #else EC_NUM = ECDSA_NUM #endif }; /* list of ecdh curves, extension of |ecdsa_choices| list above */ static const OPT_PAIR ecdh_choices[EC_NUM] = { {"ecdhp160", R_EC_P160}, {"ecdhp192", R_EC_P192}, {"ecdhp224", R_EC_P224}, {"ecdhp256", R_EC_P256}, {"ecdhp384", R_EC_P384}, {"ecdhp521", R_EC_P521}, #ifndef OPENSSL_NO_EC2M {"ecdhk163", R_EC_K163}, {"ecdhk233", R_EC_K233}, {"ecdhk283", R_EC_K283}, {"ecdhk409", R_EC_K409}, {"ecdhk571", R_EC_K571}, {"ecdhb163", R_EC_B163}, {"ecdhb233", R_EC_B233}, {"ecdhb283", R_EC_B283}, {"ecdhb409", R_EC_B409}, {"ecdhb571", R_EC_B571}, #endif {"ecdhbrp256r1", R_EC_BRP256R1}, {"ecdhbrp256t1", R_EC_BRP256T1}, {"ecdhbrp384r1", R_EC_BRP384R1}, {"ecdhbrp384t1", R_EC_BRP384T1}, {"ecdhbrp512r1", R_EC_BRP512R1}, {"ecdhbrp512t1", R_EC_BRP512T1}, #ifndef OPENSSL_NO_ECX {"ecdhx25519", R_EC_X25519}, {"ecdhx448", R_EC_X448} #endif }; static double ecdh_results[EC_NUM][1]; /* 1 op: derivation */ static double ecdsa_results[ECDSA_NUM][2]; /* 2 ops: sign then verify */ #ifndef OPENSSL_NO_ECX enum { R_EC_Ed25519, R_EC_Ed448, EdDSA_NUM }; static const OPT_PAIR eddsa_choices[EdDSA_NUM] = { {"ed25519", R_EC_Ed25519}, {"ed448", R_EC_Ed448} }; static double eddsa_results[EdDSA_NUM][2]; /* 2 ops: sign then verify */ #endif /* OPENSSL_NO_ECX */ #ifndef OPENSSL_NO_SM2 enum { R_EC_CURVESM2, SM2_NUM }; static const OPT_PAIR sm2_choices[SM2_NUM] = { {"curveSM2", R_EC_CURVESM2} }; # define SM2_ID "TLSv1.3+GM+Cipher+Suite" # define SM2_ID_LEN sizeof("TLSv1.3+GM+Cipher+Suite") - 1 static double sm2_results[SM2_NUM][2]; /* 2 ops: sign then verify */ #endif /* OPENSSL_NO_SM2 */ #define MAX_KEM_NUM 111 static size_t kems_algs_len = 0; static char *kems_algname[MAX_KEM_NUM] = { NULL }; static double kems_results[MAX_KEM_NUM][3]; /* keygen, encaps, decaps */ #define MAX_SIG_NUM 111 static size_t sigs_algs_len = 0; static char *sigs_algname[MAX_SIG_NUM] = { NULL }; static double sigs_results[MAX_SIG_NUM][3]; /* keygen, sign, verify */ #define COND(unused_cond) (run && count < INT_MAX) #define COUNT(d) (count) typedef struct loopargs_st { ASYNC_JOB *inprogress_job; ASYNC_WAIT_CTX *wait_ctx; unsigned char *buf; unsigned char *buf2; unsigned char *buf_malloc; unsigned char *buf2_malloc; unsigned char *key; size_t buflen; size_t sigsize; size_t encsize; EVP_PKEY_CTX *rsa_sign_ctx[RSA_NUM]; EVP_PKEY_CTX *rsa_verify_ctx[RSA_NUM]; EVP_PKEY_CTX *rsa_encrypt_ctx[RSA_NUM]; EVP_PKEY_CTX *rsa_decrypt_ctx[RSA_NUM]; EVP_PKEY_CTX *dsa_sign_ctx[DSA_NUM]; EVP_PKEY_CTX *dsa_verify_ctx[DSA_NUM]; EVP_PKEY_CTX *ecdsa_sign_ctx[ECDSA_NUM]; EVP_PKEY_CTX *ecdsa_verify_ctx[ECDSA_NUM]; EVP_PKEY_CTX *ecdh_ctx[EC_NUM]; #ifndef OPENSSL_NO_ECX EVP_MD_CTX *eddsa_ctx[EdDSA_NUM]; EVP_MD_CTX *eddsa_ctx2[EdDSA_NUM]; #endif /* OPENSSL_NO_ECX */ #ifndef OPENSSL_NO_SM2 EVP_MD_CTX *sm2_ctx[SM2_NUM]; EVP_MD_CTX *sm2_vfy_ctx[SM2_NUM]; EVP_PKEY *sm2_pkey[SM2_NUM]; #endif unsigned char *secret_a; unsigned char *secret_b; size_t outlen[EC_NUM]; #ifndef OPENSSL_NO_DH EVP_PKEY_CTX *ffdh_ctx[FFDH_NUM]; unsigned char *secret_ff_a; unsigned char *secret_ff_b; #endif EVP_CIPHER_CTX *ctx; EVP_MAC_CTX *mctx; EVP_PKEY_CTX *kem_gen_ctx[MAX_KEM_NUM]; EVP_PKEY_CTX *kem_encaps_ctx[MAX_KEM_NUM]; EVP_PKEY_CTX *kem_decaps_ctx[MAX_KEM_NUM]; size_t kem_out_len[MAX_KEM_NUM]; size_t kem_secret_len[MAX_KEM_NUM]; unsigned char *kem_out[MAX_KEM_NUM]; unsigned char *kem_send_secret[MAX_KEM_NUM]; unsigned char *kem_rcv_secret[MAX_KEM_NUM]; EVP_PKEY_CTX *sig_gen_ctx[MAX_KEM_NUM]; EVP_PKEY_CTX *sig_sign_ctx[MAX_KEM_NUM]; EVP_PKEY_CTX *sig_verify_ctx[MAX_KEM_NUM]; size_t sig_max_sig_len[MAX_KEM_NUM]; size_t sig_act_sig_len[MAX_KEM_NUM]; unsigned char *sig_sig[MAX_KEM_NUM]; } loopargs_t; static int run_benchmark(int async_jobs, int (*loop_function) (void *), loopargs_t *loopargs); static unsigned int testnum; static char *evp_mac_mdname = "sha256"; static char *evp_hmac_name = NULL; static const char *evp_md_name = NULL; static char *evp_mac_ciphername = "aes-128-cbc"; static char *evp_cmac_name = NULL; static int have_md(const char *name) { int ret = 0; EVP_MD *md = NULL; if (opt_md_silent(name, &md)) { EVP_MD_CTX *ctx = EVP_MD_CTX_new(); if (ctx != NULL && EVP_DigestInit(ctx, md) > 0) ret = 1; EVP_MD_CTX_free(ctx); EVP_MD_free(md); } return ret; } static int have_cipher(const char *name) { int ret = 0; EVP_CIPHER *cipher = NULL; if (opt_cipher_silent(name, &cipher)) { EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new(); if (ctx != NULL && EVP_CipherInit_ex(ctx, cipher, NULL, NULL, NULL, 1) > 0) ret = 1; EVP_CIPHER_CTX_free(ctx); EVP_CIPHER_free(cipher); } return ret; } static int EVP_Digest_loop(const char *mdname, ossl_unused int algindex, void *args) { loopargs_t *tempargs = *(loopargs_t **) args; unsigned char *buf = tempargs->buf; unsigned char digest[EVP_MAX_MD_SIZE]; int count; EVP_MD *md = NULL; if (!opt_md_silent(mdname, &md)) return -1; for (count = 0; COND(c[algindex][testnum]); count++) { if (!EVP_Digest(buf, (size_t)lengths[testnum], digest, NULL, md, NULL)) { count = -1; break; } } EVP_MD_free(md); return count; } static int EVP_Digest_md_loop(void *args) { return EVP_Digest_loop(evp_md_name, D_EVP, args); } static int EVP_Digest_MD2_loop(void *args) { return EVP_Digest_loop("md2", D_MD2, args); } static int EVP_Digest_MDC2_loop(void *args) { return EVP_Digest_loop("mdc2", D_MDC2, args); } static int EVP_Digest_MD4_loop(void *args) { return EVP_Digest_loop("md4", D_MD4, args); } static int MD5_loop(void *args) { return EVP_Digest_loop("md5", D_MD5, args); } static int mac_setup(const char *name, EVP_MAC **mac, OSSL_PARAM params[], loopargs_t *loopargs, unsigned int loopargs_len) { unsigned int i; *mac = EVP_MAC_fetch(app_get0_libctx(), name, app_get0_propq()); if (*mac == NULL) return 0; for (i = 0; i < loopargs_len; i++) { loopargs[i].mctx = EVP_MAC_CTX_new(*mac); if (loopargs[i].mctx == NULL) return 0; if (!EVP_MAC_CTX_set_params(loopargs[i].mctx, params)) return 0; } return 1; } static void mac_teardown(EVP_MAC **mac, loopargs_t *loopargs, unsigned int loopargs_len) { unsigned int i; for (i = 0; i < loopargs_len; i++) EVP_MAC_CTX_free(loopargs[i].mctx); EVP_MAC_free(*mac); *mac = NULL; return; } static int EVP_MAC_loop(ossl_unused int algindex, void *args) { loopargs_t *tempargs = *(loopargs_t **) args; unsigned char *buf = tempargs->buf; EVP_MAC_CTX *mctx = tempargs->mctx; unsigned char mac[EVP_MAX_MD_SIZE]; int count; for (count = 0; COND(c[algindex][testnum]); count++) { size_t outl; if (!EVP_MAC_init(mctx, NULL, 0, NULL) || !EVP_MAC_update(mctx, buf, lengths[testnum]) || !EVP_MAC_final(mctx, mac, &outl, sizeof(mac))) return -1; } return count; } static int HMAC_loop(void *args) { return EVP_MAC_loop(D_HMAC, args); } static int CMAC_loop(void *args) { return EVP_MAC_loop(D_EVP_CMAC, args); } static int KMAC128_loop(void *args) { return EVP_MAC_loop(D_KMAC128, args); } static int KMAC256_loop(void *args) { return EVP_MAC_loop(D_KMAC256, args); } static int SHA1_loop(void *args) { return EVP_Digest_loop("sha1", D_SHA1, args); } static int SHA256_loop(void *args) { return EVP_Digest_loop("sha256", D_SHA256, args); } static int SHA512_loop(void *args) { return EVP_Digest_loop("sha512", D_SHA512, args); } static int WHIRLPOOL_loop(void *args) { return EVP_Digest_loop("whirlpool", D_WHIRLPOOL, args); } static int EVP_Digest_RMD160_loop(void *args) { return EVP_Digest_loop("ripemd160", D_RMD160, args); } static int algindex; static int EVP_Cipher_loop(void *args) { loopargs_t *tempargs = *(loopargs_t **) args; unsigned char *buf = tempargs->buf; int count; if (tempargs->ctx == NULL) return -1; for (count = 0; COND(c[algindex][testnum]); count++) if (EVP_Cipher(tempargs->ctx, buf, buf, (size_t)lengths[testnum]) <= 0) return -1; return count; } static int GHASH_loop(void *args) { loopargs_t *tempargs = *(loopargs_t **) args; unsigned char *buf = tempargs->buf; EVP_MAC_CTX *mctx = tempargs->mctx; int count; /* just do the update in the loop to be comparable with 1.1.1 */ for (count = 0; COND(c[D_GHASH][testnum]); count++) { if (!EVP_MAC_update(mctx, buf, lengths[testnum])) return -1; } return count; } #define MAX_BLOCK_SIZE 128 static unsigned char iv[2 * MAX_BLOCK_SIZE / 8]; static EVP_CIPHER_CTX *init_evp_cipher_ctx(const char *ciphername, const unsigned char *key, int keylen) { EVP_CIPHER_CTX *ctx = NULL; EVP_CIPHER *cipher = NULL; if (!opt_cipher_silent(ciphername, &cipher)) return NULL; if ((ctx = EVP_CIPHER_CTX_new()) == NULL) goto end; if (!EVP_CipherInit_ex(ctx, cipher, NULL, NULL, NULL, 1)) { EVP_CIPHER_CTX_free(ctx); ctx = NULL; goto end; } if (EVP_CIPHER_CTX_set_key_length(ctx, keylen) <= 0) { EVP_CIPHER_CTX_free(ctx); ctx = NULL; goto end; } if (!EVP_CipherInit_ex(ctx, NULL, NULL, key, iv, 1)) { EVP_CIPHER_CTX_free(ctx); ctx = NULL; goto end; } end: EVP_CIPHER_free(cipher); return ctx; } static int RAND_bytes_loop(void *args) { loopargs_t *tempargs = *(loopargs_t **) args; unsigned char *buf = tempargs->buf; int count; for (count = 0; COND(c[D_RAND][testnum]); count++) RAND_bytes(buf, lengths[testnum]); return count; } static int decrypt = 0; static int EVP_Update_loop(void *args) { loopargs_t *tempargs = *(loopargs_t **) args; unsigned char *buf = tempargs->buf; EVP_CIPHER_CTX *ctx = tempargs->ctx; int outl, count, rc; if (decrypt) { for (count = 0; COND(c[D_EVP][testnum]); count++) { rc = EVP_DecryptUpdate(ctx, buf, &outl, buf, lengths[testnum]); if (rc != 1) { /* reset iv in case of counter overflow */ rc = EVP_CipherInit_ex(ctx, NULL, NULL, NULL, iv, -1); } } } else { for (count = 0; COND(c[D_EVP][testnum]); count++) { rc = EVP_EncryptUpdate(ctx, buf, &outl, buf, lengths[testnum]); if (rc != 1) { /* reset iv in case of counter overflow */ rc = EVP_CipherInit_ex(ctx, NULL, NULL, NULL, iv, -1); } } } if (decrypt) rc = EVP_DecryptFinal_ex(ctx, buf, &outl); else rc = EVP_EncryptFinal_ex(ctx, buf, &outl); if (rc == 0) BIO_printf(bio_err, "Error finalizing cipher loop\n"); return count; } /* * CCM does not support streaming. For the purpose of performance measurement, * each message is encrypted using the same (key,iv)-pair. Do not use this * code in your application. */ static int EVP_Update_loop_ccm(void *args) { loopargs_t *tempargs = *(loopargs_t **) args; unsigned char *buf = tempargs->buf; EVP_CIPHER_CTX *ctx = tempargs->ctx; int outl, count, realcount = 0, final; unsigned char tag[12]; if (decrypt) { for (count = 0; COND(c[D_EVP][testnum]); count++) { if (EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_SET_TAG, sizeof(tag), tag) > 0 /* reset iv */ && EVP_DecryptInit_ex(ctx, NULL, NULL, NULL, iv) > 0 /* counter is reset on every update */ && EVP_DecryptUpdate(ctx, buf, &outl, buf, lengths[testnum]) > 0) realcount++; } } else { for (count = 0; COND(c[D_EVP][testnum]); count++) { /* restore iv length field */ if (EVP_EncryptUpdate(ctx, NULL, &outl, NULL, lengths[testnum]) > 0 /* counter is reset on every update */ && EVP_EncryptUpdate(ctx, buf, &outl, buf, lengths[testnum]) > 0) realcount++; } } if (decrypt) final = EVP_DecryptFinal_ex(ctx, buf, &outl); else final = EVP_EncryptFinal_ex(ctx, buf, &outl); if (final == 0) BIO_printf(bio_err, "Error finalizing ccm loop\n"); return realcount; } /* * To make AEAD benchmarking more relevant perform TLS-like operations, * 13-byte AAD followed by payload. But don't use TLS-formatted AAD, as * payload length is not actually limited by 16KB... */ static int EVP_Update_loop_aead(void *args) { loopargs_t *tempargs = *(loopargs_t **) args; unsigned char *buf = tempargs->buf; EVP_CIPHER_CTX *ctx = tempargs->ctx; int outl, count, realcount = 0; unsigned char aad[13] = { 0xcc }; unsigned char faketag[16] = { 0xcc }; if (decrypt) { for (count = 0; COND(c[D_EVP][testnum]); count++) { if (EVP_DecryptInit_ex(ctx, NULL, NULL, NULL, iv) > 0 && EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_SET_TAG, sizeof(faketag), faketag) > 0 && EVP_DecryptUpdate(ctx, NULL, &outl, aad, sizeof(aad)) > 0 && EVP_DecryptUpdate(ctx, buf, &outl, buf, lengths[testnum]) > 0 && EVP_DecryptFinal_ex(ctx, buf + outl, &outl) >0) realcount++; } } else { for (count = 0; COND(c[D_EVP][testnum]); count++) { if (EVP_EncryptInit_ex(ctx, NULL, NULL, NULL, iv) > 0 && EVP_EncryptUpdate(ctx, NULL, &outl, aad, sizeof(aad)) > 0 && EVP_EncryptUpdate(ctx, buf, &outl, buf, lengths[testnum]) > 0 && EVP_EncryptFinal_ex(ctx, buf + outl, &outl) > 0) realcount++; } } return realcount; } static int RSA_sign_loop(void *args) { loopargs_t *tempargs = *(loopargs_t **) args; unsigned char *buf = tempargs->buf; unsigned char *buf2 = tempargs->buf2; size_t *rsa_num = &tempargs->sigsize; EVP_PKEY_CTX **rsa_sign_ctx = tempargs->rsa_sign_ctx; int ret, count; for (count = 0; COND(rsa_c[testnum][0]); count++) { *rsa_num = tempargs->buflen; ret = EVP_PKEY_sign(rsa_sign_ctx[testnum], buf2, rsa_num, buf, 36); if (ret <= 0) { BIO_printf(bio_err, "RSA sign failure\n"); ERR_print_errors(bio_err); count = -1; break; } } return count; } static int RSA_verify_loop(void *args) { loopargs_t *tempargs = *(loopargs_t **) args; unsigned char *buf = tempargs->buf; unsigned char *buf2 = tempargs->buf2; size_t rsa_num = tempargs->sigsize; EVP_PKEY_CTX **rsa_verify_ctx = tempargs->rsa_verify_ctx; int ret, count; for (count = 0; COND(rsa_c[testnum][1]); count++) { ret = EVP_PKEY_verify(rsa_verify_ctx[testnum], buf2, rsa_num, buf, 36); if (ret <= 0) { BIO_printf(bio_err, "RSA verify failure\n"); ERR_print_errors(bio_err); count = -1; break; } } return count; } static int RSA_encrypt_loop(void *args) { loopargs_t *tempargs = *(loopargs_t **) args; unsigned char *buf = tempargs->buf; unsigned char *buf2 = tempargs->buf2; size_t *rsa_num = &tempargs->encsize; EVP_PKEY_CTX **rsa_encrypt_ctx = tempargs->rsa_encrypt_ctx; int ret, count; for (count = 0; COND(rsa_c[testnum][2]); count++) { *rsa_num = tempargs->buflen; ret = EVP_PKEY_encrypt(rsa_encrypt_ctx[testnum], buf2, rsa_num, buf, 36); if (ret <= 0) { BIO_printf(bio_err, "RSA encrypt failure\n"); ERR_print_errors(bio_err); count = -1; break; } } return count; } static int RSA_decrypt_loop(void *args) { loopargs_t *tempargs = *(loopargs_t **) args; unsigned char *buf = tempargs->buf; unsigned char *buf2 = tempargs->buf2; size_t rsa_num; EVP_PKEY_CTX **rsa_decrypt_ctx = tempargs->rsa_decrypt_ctx; int ret, count; for (count = 0; COND(rsa_c[testnum][3]); count++) { rsa_num = tempargs->buflen; ret = EVP_PKEY_decrypt(rsa_decrypt_ctx[testnum], buf, &rsa_num, buf2, tempargs->encsize); if (ret <= 0) { BIO_printf(bio_err, "RSA decrypt failure\n"); ERR_print_errors(bio_err); count = -1; break; } } return count; } #ifndef OPENSSL_NO_DH static int FFDH_derive_key_loop(void *args) { loopargs_t *tempargs = *(loopargs_t **) args; EVP_PKEY_CTX *ffdh_ctx = tempargs->ffdh_ctx[testnum]; unsigned char *derived_secret = tempargs->secret_ff_a; int count; for (count = 0; COND(ffdh_c[testnum][0]); count++) { /* outlen can be overwritten with a too small value (no padding used) */ size_t outlen = MAX_FFDH_SIZE; EVP_PKEY_derive(ffdh_ctx, derived_secret, &outlen); } return count; } #endif /* OPENSSL_NO_DH */ static int DSA_sign_loop(void *args) { loopargs_t *tempargs = *(loopargs_t **) args; unsigned char *buf = tempargs->buf; unsigned char *buf2 = tempargs->buf2; size_t *dsa_num = &tempargs->sigsize; EVP_PKEY_CTX **dsa_sign_ctx = tempargs->dsa_sign_ctx; int ret, count; for (count = 0; COND(dsa_c[testnum][0]); count++) { *dsa_num = tempargs->buflen; ret = EVP_PKEY_sign(dsa_sign_ctx[testnum], buf2, dsa_num, buf, 20); if (ret <= 0) { BIO_printf(bio_err, "DSA sign failure\n"); ERR_print_errors(bio_err); count = -1; break; } } return count; } static int DSA_verify_loop(void *args) { loopargs_t *tempargs = *(loopargs_t **) args; unsigned char *buf = tempargs->buf; unsigned char *buf2 = tempargs->buf2; size_t dsa_num = tempargs->sigsize; EVP_PKEY_CTX **dsa_verify_ctx = tempargs->dsa_verify_ctx; int ret, count; for (count = 0; COND(dsa_c[testnum][1]); count++) { ret = EVP_PKEY_verify(dsa_verify_ctx[testnum], buf2, dsa_num, buf, 20); if (ret <= 0) { BIO_printf(bio_err, "DSA verify failure\n"); ERR_print_errors(bio_err); count = -1; break; } } return count; } static int ECDSA_sign_loop(void *args) { loopargs_t *tempargs = *(loopargs_t **) args; unsigned char *buf = tempargs->buf; unsigned char *buf2 = tempargs->buf2; size_t *ecdsa_num = &tempargs->sigsize; EVP_PKEY_CTX **ecdsa_sign_ctx = tempargs->ecdsa_sign_ctx; int ret, count; for (count = 0; COND(ecdsa_c[testnum][0]); count++) { *ecdsa_num = tempargs->buflen; ret = EVP_PKEY_sign(ecdsa_sign_ctx[testnum], buf2, ecdsa_num, buf, 20); if (ret <= 0) { BIO_printf(bio_err, "ECDSA sign failure\n"); ERR_print_errors(bio_err); count = -1; break; } } return count; } static int ECDSA_verify_loop(void *args) { loopargs_t *tempargs = *(loopargs_t **) args; unsigned char *buf = tempargs->buf; unsigned char *buf2 = tempargs->buf2; size_t ecdsa_num = tempargs->sigsize; EVP_PKEY_CTX **ecdsa_verify_ctx = tempargs->ecdsa_verify_ctx; int ret, count; for (count = 0; COND(ecdsa_c[testnum][1]); count++) { ret = EVP_PKEY_verify(ecdsa_verify_ctx[testnum], buf2, ecdsa_num, buf, 20); if (ret <= 0) { BIO_printf(bio_err, "ECDSA verify failure\n"); ERR_print_errors(bio_err); count = -1; break; } } return count; } /* ******************************************************************** */ static int ECDH_EVP_derive_key_loop(void *args) { loopargs_t *tempargs = *(loopargs_t **) args; EVP_PKEY_CTX *ctx = tempargs->ecdh_ctx[testnum]; unsigned char *derived_secret = tempargs->secret_a; int count; size_t *outlen = &(tempargs->outlen[testnum]); for (count = 0; COND(ecdh_c[testnum][0]); count++) EVP_PKEY_derive(ctx, derived_secret, outlen); return count; } #ifndef OPENSSL_NO_ECX static int EdDSA_sign_loop(void *args) { loopargs_t *tempargs = *(loopargs_t **) args; unsigned char *buf = tempargs->buf; EVP_MD_CTX **edctx = tempargs->eddsa_ctx; unsigned char *eddsasig = tempargs->buf2; size_t *eddsasigsize = &tempargs->sigsize; int ret, count; for (count = 0; COND(eddsa_c[testnum][0]); count++) { ret = EVP_DigestSignInit(edctx[testnum], NULL, NULL, NULL, NULL); if (ret == 0) { BIO_printf(bio_err, "EdDSA sign init failure\n"); ERR_print_errors(bio_err); count = -1; break; } ret = EVP_DigestSign(edctx[testnum], eddsasig, eddsasigsize, buf, 20); if (ret == 0) { BIO_printf(bio_err, "EdDSA sign failure\n"); ERR_print_errors(bio_err); count = -1; break; } } return count; } static int EdDSA_verify_loop(void *args) { loopargs_t *tempargs = *(loopargs_t **) args; unsigned char *buf = tempargs->buf; EVP_MD_CTX **edctx = tempargs->eddsa_ctx2; unsigned char *eddsasig = tempargs->buf2; size_t eddsasigsize = tempargs->sigsize; int ret, count; for (count = 0; COND(eddsa_c[testnum][1]); count++) { ret = EVP_DigestVerifyInit(edctx[testnum], NULL, NULL, NULL, NULL); if (ret == 0) { BIO_printf(bio_err, "EdDSA verify init failure\n"); ERR_print_errors(bio_err); count = -1; break; } ret = EVP_DigestVerify(edctx[testnum], eddsasig, eddsasigsize, buf, 20); if (ret != 1) { BIO_printf(bio_err, "EdDSA verify failure\n"); ERR_print_errors(bio_err); count = -1; break; } } return count; } #endif /* OPENSSL_NO_ECX */ #ifndef OPENSSL_NO_SM2 static int SM2_sign_loop(void *args) { loopargs_t *tempargs = *(loopargs_t **) args; unsigned char *buf = tempargs->buf; EVP_MD_CTX **sm2ctx = tempargs->sm2_ctx; unsigned char *sm2sig = tempargs->buf2; size_t sm2sigsize; int ret, count; EVP_PKEY **sm2_pkey = tempargs->sm2_pkey; const size_t max_size = EVP_PKEY_get_size(sm2_pkey[testnum]); for (count = 0; COND(sm2_c[testnum][0]); count++) { sm2sigsize = max_size; if (!EVP_DigestSignInit(sm2ctx[testnum], NULL, EVP_sm3(), NULL, sm2_pkey[testnum])) { BIO_printf(bio_err, "SM2 init sign failure\n"); ERR_print_errors(bio_err); count = -1; break; } ret = EVP_DigestSign(sm2ctx[testnum], sm2sig, &sm2sigsize, buf, 20); if (ret == 0) { BIO_printf(bio_err, "SM2 sign failure\n"); ERR_print_errors(bio_err); count = -1; break; } /* update the latest returned size and always use the fixed buffer size */ tempargs->sigsize = sm2sigsize; } return count; } static int SM2_verify_loop(void *args) { loopargs_t *tempargs = *(loopargs_t **) args; unsigned char *buf = tempargs->buf; EVP_MD_CTX **sm2ctx = tempargs->sm2_vfy_ctx; unsigned char *sm2sig = tempargs->buf2; size_t sm2sigsize = tempargs->sigsize; int ret, count; EVP_PKEY **sm2_pkey = tempargs->sm2_pkey; for (count = 0; COND(sm2_c[testnum][1]); count++) { if (!EVP_DigestVerifyInit(sm2ctx[testnum], NULL, EVP_sm3(), NULL, sm2_pkey[testnum])) { BIO_printf(bio_err, "SM2 verify init failure\n"); ERR_print_errors(bio_err); count = -1; break; } ret = EVP_DigestVerify(sm2ctx[testnum], sm2sig, sm2sigsize, buf, 20); if (ret != 1) { BIO_printf(bio_err, "SM2 verify failure\n"); ERR_print_errors(bio_err); count = -1; break; } } return count; } #endif /* OPENSSL_NO_SM2 */ static int KEM_keygen_loop(void *args) { loopargs_t *tempargs = *(loopargs_t **) args; EVP_PKEY_CTX *ctx = tempargs->kem_gen_ctx[testnum]; EVP_PKEY *pkey = NULL; int count; for (count = 0; COND(kems_c[testnum][0]); count++) { if (EVP_PKEY_keygen(ctx, &pkey) <= 0) return -1; /* * runtime defined to quite some degree by randomness, * so performance overhead of _free doesn't impact * results significantly. In any case this test is * meant to permit relative algorithm performance * comparison. */ EVP_PKEY_free(pkey); pkey = NULL; } return count; } static int KEM_encaps_loop(void *args) { loopargs_t *tempargs = *(loopargs_t **) args; EVP_PKEY_CTX *ctx = tempargs->kem_encaps_ctx[testnum]; size_t out_len = tempargs->kem_out_len[testnum]; size_t secret_len = tempargs->kem_secret_len[testnum]; unsigned char *out = tempargs->kem_out[testnum]; unsigned char *secret = tempargs->kem_send_secret[testnum]; int count; for (count = 0; COND(kems_c[testnum][1]); count++) { if (EVP_PKEY_encapsulate(ctx, out, &out_len, secret, &secret_len) <= 0) return -1; } return count; } static int KEM_decaps_loop(void *args) { loopargs_t *tempargs = *(loopargs_t **) args; EVP_PKEY_CTX *ctx = tempargs->kem_decaps_ctx[testnum]; size_t out_len = tempargs->kem_out_len[testnum]; size_t secret_len = tempargs->kem_secret_len[testnum]; unsigned char *out = tempargs->kem_out[testnum]; unsigned char *secret = tempargs->kem_send_secret[testnum]; int count; for (count = 0; COND(kems_c[testnum][2]); count++) { if (EVP_PKEY_decapsulate(ctx, secret, &secret_len, out, out_len) <= 0) return -1; } return count; } static int SIG_keygen_loop(void *args) { loopargs_t *tempargs = *(loopargs_t **) args; EVP_PKEY_CTX *ctx = tempargs->sig_gen_ctx[testnum]; EVP_PKEY *pkey = NULL; int count; for (count = 0; COND(kems_c[testnum][0]); count++) { EVP_PKEY_keygen(ctx, &pkey); /* TBD: How much does free influence runtime? */ EVP_PKEY_free(pkey); pkey = NULL; } return count; } static int SIG_sign_loop(void *args) { loopargs_t *tempargs = *(loopargs_t **) args; EVP_PKEY_CTX *ctx = tempargs->sig_sign_ctx[testnum]; /* be sure to not change stored sig: */ unsigned char *sig = app_malloc(tempargs->sig_max_sig_len[testnum], "sig sign loop"); unsigned char md[SHA256_DIGEST_LENGTH] = { 0 }; size_t md_len = SHA256_DIGEST_LENGTH; int count; for (count = 0; COND(kems_c[testnum][1]); count++) { size_t sig_len = tempargs->sig_max_sig_len[testnum]; int ret = EVP_PKEY_sign(ctx, sig, &sig_len, md, md_len); if (ret <= 0) { BIO_printf(bio_err, "SIG sign failure at count %d\n", count); ERR_print_errors(bio_err); count = -1; break; } } OPENSSL_free(sig); return count; } static int SIG_verify_loop(void *args) { loopargs_t *tempargs = *(loopargs_t **) args; EVP_PKEY_CTX *ctx = tempargs->sig_verify_ctx[testnum]; size_t sig_len = tempargs->sig_act_sig_len[testnum]; unsigned char *sig = tempargs->sig_sig[testnum]; unsigned char md[SHA256_DIGEST_LENGTH] = { 0 }; size_t md_len = SHA256_DIGEST_LENGTH; int count; for (count = 0; COND(kems_c[testnum][2]); count++) { int ret = EVP_PKEY_verify(ctx, sig, sig_len, md, md_len); if (ret <= 0) { BIO_printf(bio_err, "SIG verify failure at count %d\n", count); ERR_print_errors(bio_err); count = -1; break; } } return count; } static int run_benchmark(int async_jobs, int (*loop_function) (void *), loopargs_t *loopargs) { int job_op_count = 0; int total_op_count = 0; int num_inprogress = 0; int error = 0, i = 0, ret = 0; OSSL_ASYNC_FD job_fd = 0; size_t num_job_fds = 0; if (async_jobs == 0) { return loop_function((void *)&loopargs); } for (i = 0; i < async_jobs && !error; i++) { loopargs_t *looparg_item = loopargs + i; /* Copy pointer content (looparg_t item address) into async context */ ret = ASYNC_start_job(&loopargs[i].inprogress_job, loopargs[i].wait_ctx, &job_op_count, loop_function, (void *)&looparg_item, sizeof(looparg_item)); switch (ret) { case ASYNC_PAUSE: ++num_inprogress; break; case ASYNC_FINISH: if (job_op_count == -1) { error = 1; } else { total_op_count += job_op_count; } break; case ASYNC_NO_JOBS: case ASYNC_ERR: BIO_printf(bio_err, "Failure in the job\n"); ERR_print_errors(bio_err); error = 1; break; } } while (num_inprogress > 0) { #if defined(OPENSSL_SYS_WINDOWS) DWORD avail = 0; #elif defined(OPENSSL_SYS_UNIX) int select_result = 0; OSSL_ASYNC_FD max_fd = 0; fd_set waitfdset; FD_ZERO(&waitfdset); for (i = 0; i < async_jobs && num_inprogress > 0; i++) { if (loopargs[i].inprogress_job == NULL) continue; if (!ASYNC_WAIT_CTX_get_all_fds (loopargs[i].wait_ctx, NULL, &num_job_fds) || num_job_fds > 1) { BIO_printf(bio_err, "Too many fds in ASYNC_WAIT_CTX\n"); ERR_print_errors(bio_err); error = 1; break; } ASYNC_WAIT_CTX_get_all_fds(loopargs[i].wait_ctx, &job_fd, &num_job_fds); FD_SET(job_fd, &waitfdset); if (job_fd > max_fd) max_fd = job_fd; } if (max_fd >= (OSSL_ASYNC_FD)FD_SETSIZE) { BIO_printf(bio_err, "Error: max_fd (%d) must be smaller than FD_SETSIZE (%d). " "Decrease the value of async_jobs\n", max_fd, FD_SETSIZE); ERR_print_errors(bio_err); error = 1; break; } select_result = select(max_fd + 1, &waitfdset, NULL, NULL, NULL); if (select_result == -1 && errno == EINTR) continue; if (select_result == -1) { BIO_printf(bio_err, "Failure in the select\n"); ERR_print_errors(bio_err); error = 1; break; } if (select_result == 0) continue; #endif for (i = 0; i < async_jobs; i++) { if (loopargs[i].inprogress_job == NULL) continue; if (!ASYNC_WAIT_CTX_get_all_fds (loopargs[i].wait_ctx, NULL, &num_job_fds) || num_job_fds > 1) { BIO_printf(bio_err, "Too many fds in ASYNC_WAIT_CTX\n"); ERR_print_errors(bio_err); error = 1; break; } ASYNC_WAIT_CTX_get_all_fds(loopargs[i].wait_ctx, &job_fd, &num_job_fds); #if defined(OPENSSL_SYS_UNIX) if (num_job_fds == 1 && !FD_ISSET(job_fd, &waitfdset)) continue; #elif defined(OPENSSL_SYS_WINDOWS) if (num_job_fds == 1 && !PeekNamedPipe(job_fd, NULL, 0, NULL, &avail, NULL) && avail > 0) continue; #endif ret = ASYNC_start_job(&loopargs[i].inprogress_job, loopargs[i].wait_ctx, &job_op_count, loop_function, (void *)(loopargs + i), sizeof(loopargs_t)); switch (ret) { case ASYNC_PAUSE: break; case ASYNC_FINISH: if (job_op_count == -1) { error = 1; } else { total_op_count += job_op_count; } --num_inprogress; loopargs[i].inprogress_job = NULL; break; case ASYNC_NO_JOBS: case ASYNC_ERR: --num_inprogress; loopargs[i].inprogress_job = NULL; BIO_printf(bio_err, "Failure in the job\n"); ERR_print_errors(bio_err); error = 1; break; } } } return error ? -1 : total_op_count; } typedef struct ec_curve_st { const char *name; unsigned int nid; unsigned int bits; size_t sigsize; /* only used for EdDSA curves */ } EC_CURVE; static EVP_PKEY *get_ecdsa(const EC_CURVE *curve) { EVP_PKEY_CTX *kctx = NULL; EVP_PKEY *key = NULL; /* Ensure that the error queue is empty */ if (ERR_peek_error()) { BIO_printf(bio_err, "WARNING: the error queue contains previous unhandled errors.\n"); ERR_print_errors(bio_err); } /* * Let's try to create a ctx directly from the NID: this works for * curves like Curve25519 that are not implemented through the low * level EC interface. * If this fails we try creating a EVP_PKEY_EC generic param ctx, * then we set the curve by NID before deriving the actual keygen * ctx for that specific curve. */ kctx = EVP_PKEY_CTX_new_id(curve->nid, NULL); if (kctx == NULL) { EVP_PKEY_CTX *pctx = NULL; EVP_PKEY *params = NULL; /* * If we reach this code EVP_PKEY_CTX_new_id() failed and a * "int_ctx_new:unsupported algorithm" error was added to the * error queue. * We remove it from the error queue as we are handling it. */ unsigned long error = ERR_peek_error(); if (error == ERR_peek_last_error() /* oldest and latest errors match */ /* check that the error origin matches */ && ERR_GET_LIB(error) == ERR_LIB_EVP && (ERR_GET_REASON(error) == EVP_R_UNSUPPORTED_ALGORITHM || ERR_GET_REASON(error) == ERR_R_UNSUPPORTED)) ERR_get_error(); /* pop error from queue */ if (ERR_peek_error()) { BIO_printf(bio_err, "Unhandled error in the error queue during EC key setup.\n"); ERR_print_errors(bio_err); return NULL; } /* Create the context for parameter generation */ if ((pctx = EVP_PKEY_CTX_new_from_name(NULL, "EC", NULL)) == NULL || EVP_PKEY_paramgen_init(pctx) <= 0 || EVP_PKEY_CTX_set_ec_paramgen_curve_nid(pctx, curve->nid) <= 0 || EVP_PKEY_paramgen(pctx, &params) <= 0) { BIO_printf(bio_err, "EC params init failure.\n"); ERR_print_errors(bio_err); EVP_PKEY_CTX_free(pctx); return NULL; } EVP_PKEY_CTX_free(pctx); /* Create the context for the key generation */ kctx = EVP_PKEY_CTX_new(params, NULL); EVP_PKEY_free(params); } if (kctx == NULL || EVP_PKEY_keygen_init(kctx) <= 0 || EVP_PKEY_keygen(kctx, &key) <= 0) { BIO_printf(bio_err, "EC key generation failure.\n"); ERR_print_errors(bio_err); key = NULL; } EVP_PKEY_CTX_free(kctx); return key; } #define stop_it(do_it, test_num)\ memset(do_it + test_num, 0, OSSL_NELEM(do_it) - test_num); /* Checks to see if algorithms are fetchable */ #define IS_FETCHABLE(type, TYPE) \ static int is_ ## type ## _fetchable(const TYPE *alg) \ { \ TYPE *impl; \ const char *propq = app_get0_propq(); \ OSSL_LIB_CTX *libctx = app_get0_libctx(); \ const char *name = TYPE ## _get0_name(alg); \ \ ERR_set_mark(); \ impl = TYPE ## _fetch(libctx, name, propq); \ ERR_pop_to_mark(); \ if (impl == NULL) \ return 0; \ TYPE ## _free(impl); \ return 1; \ } IS_FETCHABLE(signature, EVP_SIGNATURE) IS_FETCHABLE(kem, EVP_KEM) DEFINE_STACK_OF(EVP_KEM) static int kems_cmp(const EVP_KEM * const *a, const EVP_KEM * const *b) { return strcmp(OSSL_PROVIDER_get0_name(EVP_KEM_get0_provider(*a)), OSSL_PROVIDER_get0_name(EVP_KEM_get0_provider(*b))); } static void collect_kem(EVP_KEM *kem, void *stack) { STACK_OF(EVP_KEM) *kem_stack = stack; if (is_kem_fetchable(kem) && sk_EVP_KEM_push(kem_stack, kem) > 0) { EVP_KEM_up_ref(kem); } } static int kem_locate(const char *algo, unsigned int *idx) { unsigned int i; for (i = 0; i < kems_algs_len; i++) { if (strcmp(kems_algname[i], algo) == 0) { *idx = i; return 1; } } return 0; } DEFINE_STACK_OF(EVP_SIGNATURE) static int signatures_cmp(const EVP_SIGNATURE * const *a, const EVP_SIGNATURE * const *b) { return strcmp(OSSL_PROVIDER_get0_name(EVP_SIGNATURE_get0_provider(*a)), OSSL_PROVIDER_get0_name(EVP_SIGNATURE_get0_provider(*b))); } static void collect_signatures(EVP_SIGNATURE *sig, void *stack) { STACK_OF(EVP_SIGNATURE) *sig_stack = stack; if (is_signature_fetchable(sig) && sk_EVP_SIGNATURE_push(sig_stack, sig) > 0) EVP_SIGNATURE_up_ref(sig); } static int sig_locate(const char *algo, unsigned int *idx) { unsigned int i; for (i = 0; i < sigs_algs_len; i++) { if (strcmp(sigs_algname[i], algo) == 0) { *idx = i; return 1; } } return 0; } static int get_max(const uint8_t doit[], size_t algs_len) { size_t i = 0; int maxcnt = 0; for (i = 0; i < algs_len; i++) if (maxcnt < doit[i]) maxcnt = doit[i]; return maxcnt; } int speed_main(int argc, char **argv) { CONF *conf = NULL; ENGINE *e = NULL; loopargs_t *loopargs = NULL; const char *prog; const char *engine_id = NULL; EVP_CIPHER *evp_cipher = NULL; EVP_MAC *mac = NULL; double d = 0.0; OPTION_CHOICE o; int async_init = 0, multiblock = 0, pr_header = 0; uint8_t doit[ALGOR_NUM] = { 0 }; int ret = 1, misalign = 0, lengths_single = 0, aead = 0; STACK_OF(EVP_KEM) *kem_stack = NULL; STACK_OF(EVP_SIGNATURE) *sig_stack = NULL; long count = 0; unsigned int size_num = SIZE_NUM; unsigned int i, k, loopargs_len = 0, async_jobs = 0; unsigned int idx; int keylen; int buflen; size_t declen; BIGNUM *bn = NULL; EVP_PKEY_CTX *genctx = NULL; #ifndef NO_FORK int multi = 0; #endif long op_count = 1; openssl_speed_sec_t seconds = { SECONDS, RSA_SECONDS, DSA_SECONDS, ECDSA_SECONDS, ECDH_SECONDS, EdDSA_SECONDS, SM2_SECONDS, FFDH_SECONDS, KEM_SECONDS, SIG_SECONDS }; static const unsigned char key32[32] = { 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34, 0x56 }; static const unsigned char deskey[] = { 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, /* key1 */ 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, /* key2 */ 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34 /* key3 */ }; static const struct { const unsigned char *data; unsigned int length; unsigned int bits; } rsa_keys[] = { { test512, sizeof(test512), 512 }, { test1024, sizeof(test1024), 1024 }, { test2048, sizeof(test2048), 2048 }, { test3072, sizeof(test3072), 3072 }, { test4096, sizeof(test4096), 4096 }, { test7680, sizeof(test7680), 7680 }, { test15360, sizeof(test15360), 15360 } }; uint8_t rsa_doit[RSA_NUM] = { 0 }; int primes = RSA_DEFAULT_PRIME_NUM; #ifndef OPENSSL_NO_DH typedef struct ffdh_params_st { const char *name; unsigned int nid; unsigned int bits; } FFDH_PARAMS; static const FFDH_PARAMS ffdh_params[FFDH_NUM] = { {"ffdh2048", NID_ffdhe2048, 2048}, {"ffdh3072", NID_ffdhe3072, 3072}, {"ffdh4096", NID_ffdhe4096, 4096}, {"ffdh6144", NID_ffdhe6144, 6144}, {"ffdh8192", NID_ffdhe8192, 8192} }; uint8_t ffdh_doit[FFDH_NUM] = { 0 }; #endif /* OPENSSL_NO_DH */ static const unsigned int dsa_bits[DSA_NUM] = { 1024, 2048 }; uint8_t dsa_doit[DSA_NUM] = { 0 }; /* * We only test over the following curves as they are representative, To * add tests over more curves, simply add the curve NID and curve name to * the following arrays and increase the |ecdh_choices| and |ecdsa_choices| * lists accordingly. */ static const EC_CURVE ec_curves[EC_NUM] = { /* Prime Curves */ {"secp160r1", NID_secp160r1, 160}, {"nistp192", NID_X9_62_prime192v1, 192}, {"nistp224", NID_secp224r1, 224}, {"nistp256", NID_X9_62_prime256v1, 256}, {"nistp384", NID_secp384r1, 384}, {"nistp521", NID_secp521r1, 521}, #ifndef OPENSSL_NO_EC2M /* Binary Curves */ {"nistk163", NID_sect163k1, 163}, {"nistk233", NID_sect233k1, 233}, {"nistk283", NID_sect283k1, 283}, {"nistk409", NID_sect409k1, 409}, {"nistk571", NID_sect571k1, 571}, {"nistb163", NID_sect163r2, 163}, {"nistb233", NID_sect233r1, 233}, {"nistb283", NID_sect283r1, 283}, {"nistb409", NID_sect409r1, 409}, {"nistb571", NID_sect571r1, 571}, #endif {"brainpoolP256r1", NID_brainpoolP256r1, 256}, {"brainpoolP256t1", NID_brainpoolP256t1, 256}, {"brainpoolP384r1", NID_brainpoolP384r1, 384}, {"brainpoolP384t1", NID_brainpoolP384t1, 384}, {"brainpoolP512r1", NID_brainpoolP512r1, 512}, {"brainpoolP512t1", NID_brainpoolP512t1, 512}, #ifndef OPENSSL_NO_ECX /* Other and ECDH only ones */ {"X25519", NID_X25519, 253}, {"X448", NID_X448, 448} #endif }; #ifndef OPENSSL_NO_ECX static const EC_CURVE ed_curves[EdDSA_NUM] = { /* EdDSA */ {"Ed25519", NID_ED25519, 253, 64}, {"Ed448", NID_ED448, 456, 114} }; #endif /* OPENSSL_NO_ECX */ #ifndef OPENSSL_NO_SM2 static const EC_CURVE sm2_curves[SM2_NUM] = { /* SM2 */ {"CurveSM2", NID_sm2, 256} }; uint8_t sm2_doit[SM2_NUM] = { 0 }; #endif uint8_t ecdsa_doit[ECDSA_NUM] = { 0 }; uint8_t ecdh_doit[EC_NUM] = { 0 }; #ifndef OPENSSL_NO_ECX uint8_t eddsa_doit[EdDSA_NUM] = { 0 }; #endif /* OPENSSL_NO_ECX */ uint8_t kems_doit[MAX_KEM_NUM] = { 0 }; uint8_t sigs_doit[MAX_SIG_NUM] = { 0 }; uint8_t do_kems = 0; uint8_t do_sigs = 0; /* checks declared curves against choices list. */ #ifndef OPENSSL_NO_ECX OPENSSL_assert(ed_curves[EdDSA_NUM - 1].nid == NID_ED448); OPENSSL_assert(strcmp(eddsa_choices[EdDSA_NUM - 1].name, "ed448") == 0); OPENSSL_assert(ec_curves[EC_NUM - 1].nid == NID_X448); OPENSSL_assert(strcmp(ecdh_choices[EC_NUM - 1].name, "ecdhx448") == 0); OPENSSL_assert(ec_curves[ECDSA_NUM - 1].nid == NID_brainpoolP512t1); OPENSSL_assert(strcmp(ecdsa_choices[ECDSA_NUM - 1].name, "ecdsabrp512t1") == 0); #endif /* OPENSSL_NO_ECX */ #ifndef OPENSSL_NO_SM2 OPENSSL_assert(sm2_curves[SM2_NUM - 1].nid == NID_sm2); OPENSSL_assert(strcmp(sm2_choices[SM2_NUM - 1].name, "curveSM2") == 0); #endif prog = opt_init(argc, argv, speed_options); while ((o = opt_next()) != OPT_EOF) { switch (o) { case OPT_EOF: case OPT_ERR: opterr: BIO_printf(bio_err, "%s: Use -help for summary.\n", prog); goto end; case OPT_HELP: opt_help(speed_options); ret = 0; goto end; case OPT_ELAPSED: usertime = 0; break; case OPT_EVP: if (doit[D_EVP]) { BIO_printf(bio_err, "%s: -evp option cannot be used more than once\n", prog); goto opterr; } ERR_set_mark(); if (!opt_cipher_silent(opt_arg(), &evp_cipher)) { if (have_md(opt_arg())) evp_md_name = opt_arg(); } if (evp_cipher == NULL && evp_md_name == NULL) { ERR_clear_last_mark(); BIO_printf(bio_err, "%s: %s is an unknown cipher or digest\n", prog, opt_arg()); goto end; } ERR_pop_to_mark(); doit[D_EVP] = 1; break; case OPT_HMAC: if (!have_md(opt_arg())) { BIO_printf(bio_err, "%s: %s is an unknown digest\n", prog, opt_arg()); goto end; } evp_mac_mdname = opt_arg(); doit[D_HMAC] = 1; break; case OPT_CMAC: if (!have_cipher(opt_arg())) { BIO_printf(bio_err, "%s: %s is an unknown cipher\n", prog, opt_arg()); goto end; } evp_mac_ciphername = opt_arg(); doit[D_EVP_CMAC] = 1; break; case OPT_DECRYPT: decrypt = 1; break; case OPT_ENGINE: /* * In a forked execution, an engine might need to be * initialised by each child process, not by the parent. * So store the name here and run setup_engine() later on. */ engine_id = opt_arg(); break; case OPT_MULTI: #ifndef NO_FORK multi = opt_int_arg(); if ((size_t)multi >= SIZE_MAX / sizeof(int)) { BIO_printf(bio_err, "%s: multi argument too large\n", prog); return 0; } #endif break; case OPT_ASYNCJOBS: #ifndef OPENSSL_NO_ASYNC async_jobs = opt_int_arg(); if (!ASYNC_is_capable()) { BIO_printf(bio_err, "%s: async_jobs specified but async not supported\n", prog); goto opterr; } if (async_jobs > 99999) { BIO_printf(bio_err, "%s: too many async_jobs\n", prog); goto opterr; } #endif break; case OPT_MISALIGN: misalign = opt_int_arg(); if (misalign > MISALIGN) { BIO_printf(bio_err, "%s: Maximum offset is %d\n", prog, MISALIGN); goto opterr; } break; case OPT_MR: mr = 1; break; case OPT_MB: multiblock = 1; #ifdef OPENSSL_NO_MULTIBLOCK BIO_printf(bio_err, "%s: -mb specified but multi-block support is disabled\n", prog); goto end; #endif break; case OPT_R_CASES: if (!opt_rand(o)) goto end; break; case OPT_PROV_CASES: if (!opt_provider(o)) goto end; break; case OPT_CONFIG: conf = app_load_config_modules(opt_arg()); if (conf == NULL) goto end; break; case OPT_PRIMES: primes = opt_int_arg(); break; case OPT_SECONDS: seconds.sym = seconds.rsa = seconds.dsa = seconds.ecdsa = seconds.ecdh = seconds.eddsa = seconds.sm2 = seconds.ffdh = seconds.kem = seconds.sig = opt_int_arg(); break; case OPT_BYTES: lengths_single = opt_int_arg(); lengths = &lengths_single; size_num = 1; break; case OPT_AEAD: aead = 1; break; case OPT_KEM: do_kems = 1; break; case OPT_SIG: do_sigs = 1; break; case OPT_MLOCK: domlock = 1; #if !defined(_WIN32) && !defined(OPENSSL_SYS_LINUX) BIO_printf(bio_err, "%s: -mlock not supported on this platform\n", prog); goto end; #endif break; } } /* find all KEMs currently available */ kem_stack = sk_EVP_KEM_new(kems_cmp); EVP_KEM_do_all_provided(app_get0_libctx(), collect_kem, kem_stack); kems_algs_len = 0; for (idx = 0; idx < (unsigned int)sk_EVP_KEM_num(kem_stack); idx++) { EVP_KEM *kem = sk_EVP_KEM_value(kem_stack, idx); if (strcmp(EVP_KEM_get0_name(kem), "RSA") == 0) { if (kems_algs_len + OSSL_NELEM(rsa_choices) >= MAX_KEM_NUM) { BIO_printf(bio_err, "Too many KEMs registered. Change MAX_KEM_NUM.\n"); goto end; } for (i = 0; i < OSSL_NELEM(rsa_choices); i++) { kems_doit[kems_algs_len] = 1; kems_algname[kems_algs_len++] = OPENSSL_strdup(rsa_choices[i].name); } } else if (strcmp(EVP_KEM_get0_name(kem), "EC") == 0) { if (kems_algs_len + 3 >= MAX_KEM_NUM) { BIO_printf(bio_err, "Too many KEMs registered. Change MAX_KEM_NUM.\n"); goto end; } kems_doit[kems_algs_len] = 1; kems_algname[kems_algs_len++] = OPENSSL_strdup("ECP-256"); kems_doit[kems_algs_len] = 1; kems_algname[kems_algs_len++] = OPENSSL_strdup("ECP-384"); kems_doit[kems_algs_len] = 1; kems_algname[kems_algs_len++] = OPENSSL_strdup("ECP-521"); } else { if (kems_algs_len + 1 >= MAX_KEM_NUM) { BIO_printf(bio_err, "Too many KEMs registered. Change MAX_KEM_NUM.\n"); goto end; } kems_doit[kems_algs_len] = 1; kems_algname[kems_algs_len++] = OPENSSL_strdup(EVP_KEM_get0_name(kem)); } } sk_EVP_KEM_pop_free(kem_stack, EVP_KEM_free); kem_stack = NULL; /* find all SIGNATUREs currently available */ sig_stack = sk_EVP_SIGNATURE_new(signatures_cmp); EVP_SIGNATURE_do_all_provided(app_get0_libctx(), collect_signatures, sig_stack); sigs_algs_len = 0; for (idx = 0; idx < (unsigned int)sk_EVP_SIGNATURE_num(sig_stack); idx++) { EVP_SIGNATURE *s = sk_EVP_SIGNATURE_value(sig_stack, idx); const char *sig_name = EVP_SIGNATURE_get0_name(s); if (strcmp(sig_name, "RSA") == 0) { if (sigs_algs_len + OSSL_NELEM(rsa_choices) >= MAX_SIG_NUM) { BIO_printf(bio_err, "Too many signatures registered. Change MAX_SIG_NUM.\n"); goto end; } for (i = 0; i < OSSL_NELEM(rsa_choices); i++) { sigs_doit[sigs_algs_len] = 1; sigs_algname[sigs_algs_len++] = OPENSSL_strdup(rsa_choices[i].name); } } else if (strcmp(sig_name, "DSA") == 0) { if (sigs_algs_len + DSA_NUM >= MAX_SIG_NUM) { BIO_printf(bio_err, "Too many signatures registered. Change MAX_SIG_NUM.\n"); goto end; } for (i = 0; i < DSA_NUM; i++) { sigs_doit[sigs_algs_len] = 1; sigs_algname[sigs_algs_len++] = OPENSSL_strdup(dsa_choices[i].name); } } /* skipping these algs as tested elsewhere - and b/o setup is a pain */ else if (strcmp(sig_name, "ED25519") && strcmp(sig_name, "ED448") && strcmp(sig_name, "ECDSA") && strcmp(sig_name, "HMAC") && strcmp(sig_name, "SIPHASH") && strcmp(sig_name, "POLY1305") && strcmp(sig_name, "CMAC") && strcmp(sig_name, "SM2")) { /* skip alg */ if (sigs_algs_len + 1 >= MAX_SIG_NUM) { BIO_printf(bio_err, "Too many signatures registered. Change MAX_SIG_NUM.\n"); goto end; } /* activate this provider algorithm */ sigs_doit[sigs_algs_len] = 1; sigs_algname[sigs_algs_len++] = OPENSSL_strdup(sig_name); } } sk_EVP_SIGNATURE_pop_free(sig_stack, EVP_SIGNATURE_free); sig_stack = NULL; /* Remaining arguments are algorithms. */ argc = opt_num_rest(); argv = opt_rest(); if (!app_RAND_load()) goto end; for (; *argv; argv++) { const char *algo = *argv; int algo_found = 0; if (opt_found(algo, doit_choices, &i)) { doit[i] = 1; algo_found = 1; } if (strcmp(algo, "des") == 0) { doit[D_CBC_DES] = doit[D_EDE3_DES] = 1; algo_found = 1; } if (strcmp(algo, "sha") == 0) { doit[D_SHA1] = doit[D_SHA256] = doit[D_SHA512] = 1; algo_found = 1; } #ifndef OPENSSL_NO_DEPRECATED_3_0 if (strcmp(algo, "openssl") == 0) /* just for compatibility */ algo_found = 1; #endif if (HAS_PREFIX(algo, "rsa")) { if (algo[sizeof("rsa") - 1] == '\0') { memset(rsa_doit, 1, sizeof(rsa_doit)); algo_found = 1; } if (opt_found(algo, rsa_choices, &i)) { rsa_doit[i] = 1; algo_found = 1; } } #ifndef OPENSSL_NO_DH if (HAS_PREFIX(algo, "ffdh")) { if (algo[sizeof("ffdh") - 1] == '\0') { memset(ffdh_doit, 1, sizeof(ffdh_doit)); algo_found = 1; } if (opt_found(algo, ffdh_choices, &i)) { ffdh_doit[i] = 2; algo_found = 1; } } #endif if (HAS_PREFIX(algo, "dsa")) { if (algo[sizeof("dsa") - 1] == '\0') { memset(dsa_doit, 1, sizeof(dsa_doit)); algo_found = 1; } if (opt_found(algo, dsa_choices, &i)) { dsa_doit[i] = 2; algo_found = 1; } } if (strcmp(algo, "aes") == 0) { doit[D_CBC_128_AES] = doit[D_CBC_192_AES] = doit[D_CBC_256_AES] = 1; algo_found = 1; } if (strcmp(algo, "camellia") == 0) { doit[D_CBC_128_CML] = doit[D_CBC_192_CML] = doit[D_CBC_256_CML] = 1; algo_found = 1; } if (HAS_PREFIX(algo, "ecdsa")) { if (algo[sizeof("ecdsa") - 1] == '\0') { memset(ecdsa_doit, 1, sizeof(ecdsa_doit)); algo_found = 1; } if (opt_found(algo, ecdsa_choices, &i)) { ecdsa_doit[i] = 2; algo_found = 1; } } if (HAS_PREFIX(algo, "ecdh")) { if (algo[sizeof("ecdh") - 1] == '\0') { memset(ecdh_doit, 1, sizeof(ecdh_doit)); algo_found = 1; } if (opt_found(algo, ecdh_choices, &i)) { ecdh_doit[i] = 2; algo_found = 1; } } #ifndef OPENSSL_NO_ECX if (strcmp(algo, "eddsa") == 0) { memset(eddsa_doit, 1, sizeof(eddsa_doit)); algo_found = 1; } if (opt_found(algo, eddsa_choices, &i)) { eddsa_doit[i] = 2; algo_found = 1; } #endif /* OPENSSL_NO_ECX */ #ifndef OPENSSL_NO_SM2 if (strcmp(algo, "sm2") == 0) { memset(sm2_doit, 1, sizeof(sm2_doit)); algo_found = 1; } if (opt_found(algo, sm2_choices, &i)) { sm2_doit[i] = 2; algo_found = 1; } #endif if (kem_locate(algo, &idx)) { kems_doit[idx]++; do_kems = 1; algo_found = 1; } if (sig_locate(algo, &idx)) { sigs_doit[idx]++; do_sigs = 1; algo_found = 1; } if (strcmp(algo, "kmac") == 0) { doit[D_KMAC128] = doit[D_KMAC256] = 1; algo_found = 1; } if (strcmp(algo, "cmac") == 0) { doit[D_EVP_CMAC] = 1; algo_found = 1; } if (!algo_found) { BIO_printf(bio_err, "%s: Unknown algorithm %s\n", prog, algo); goto end; } } /* Sanity checks */ if (aead) { if (evp_cipher == NULL) { BIO_printf(bio_err, "-aead can be used only with an AEAD cipher\n"); goto end; } else if (!(EVP_CIPHER_get_flags(evp_cipher) & EVP_CIPH_FLAG_AEAD_CIPHER)) { BIO_printf(bio_err, "%s is not an AEAD cipher\n", EVP_CIPHER_get0_name(evp_cipher)); goto end; } } if (kems_algs_len > 0) { int maxcnt = get_max(kems_doit, kems_algs_len); if (maxcnt > 1) { /* some algs explicitly selected */ for (i = 0; i < kems_algs_len; i++) { /* disable the rest */ kems_doit[i]--; } } } if (sigs_algs_len > 0) { int maxcnt = get_max(sigs_doit, sigs_algs_len); if (maxcnt > 1) { /* some algs explicitly selected */ for (i = 0; i < sigs_algs_len; i++) { /* disable the rest */ sigs_doit[i]--; } } } if (multiblock) { if (evp_cipher == NULL) { BIO_printf(bio_err, "-mb can be used only with a multi-block" " capable cipher\n"); goto end; } else if (!(EVP_CIPHER_get_flags(evp_cipher) & EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK)) { BIO_printf(bio_err, "%s is not a multi-block capable\n", EVP_CIPHER_get0_name(evp_cipher)); goto end; } else if (async_jobs > 0) { BIO_printf(bio_err, "Async mode is not supported with -mb"); goto end; } } /* Initialize the job pool if async mode is enabled */ if (async_jobs > 0) { async_init = ASYNC_init_thread(async_jobs, async_jobs); if (!async_init) { BIO_printf(bio_err, "Error creating the ASYNC job pool\n"); goto end; } } loopargs_len = (async_jobs == 0 ? 1 : async_jobs); loopargs = app_malloc(loopargs_len * sizeof(loopargs_t), "array of loopargs"); memset(loopargs, 0, loopargs_len * sizeof(loopargs_t)); buflen = lengths[size_num - 1]; if (buflen < 36) /* size of random vector in RSA benchmark */ buflen = 36; if (INT_MAX - (MAX_MISALIGNMENT + 1) < buflen) { BIO_printf(bio_err, "Error: buffer size too large\n"); goto end; } buflen += MAX_MISALIGNMENT + 1; for (i = 0; i < loopargs_len; i++) { if (async_jobs > 0) { loopargs[i].wait_ctx = ASYNC_WAIT_CTX_new(); if (loopargs[i].wait_ctx == NULL) { BIO_printf(bio_err, "Error creating the ASYNC_WAIT_CTX\n"); goto end; } } loopargs[i].buf_malloc = app_malloc(buflen, "input buffer"); loopargs[i].buf2_malloc = app_malloc(buflen, "input buffer"); /* Align the start of buffers on a 64 byte boundary */ loopargs[i].buf = loopargs[i].buf_malloc + misalign; loopargs[i].buf2 = loopargs[i].buf2_malloc + misalign; loopargs[i].buflen = buflen - misalign; loopargs[i].sigsize = buflen - misalign; loopargs[i].secret_a = app_malloc(MAX_ECDH_SIZE, "ECDH secret a"); loopargs[i].secret_b = app_malloc(MAX_ECDH_SIZE, "ECDH secret b"); #ifndef OPENSSL_NO_DH loopargs[i].secret_ff_a = app_malloc(MAX_FFDH_SIZE, "FFDH secret a"); loopargs[i].secret_ff_b = app_malloc(MAX_FFDH_SIZE, "FFDH secret b"); #endif } #ifndef NO_FORK if (multi && do_multi(multi, size_num)) goto show_res; #endif for (i = 0; i < loopargs_len; ++i) { if (domlock) { #if defined(_WIN32) (void)VirtualLock(loopargs[i].buf_malloc, buflen); (void)VirtualLock(loopargs[i].buf2_malloc, buflen); #elif defined(OPENSSL_SYS_LINUX) (void)mlock(loopargs[i].buf_malloc, buflen); (void)mlock(loopargs[i].buf_malloc, buflen); #endif } memset(loopargs[i].buf_malloc, 0, buflen); memset(loopargs[i].buf2_malloc, 0, buflen); } /* Initialize the engine after the fork */ e = setup_engine(engine_id, 0); /* No parameters; turn on everything. */ if (argc == 0 && !doit[D_EVP] && !doit[D_HMAC] && !doit[D_EVP_CMAC] && !do_kems && !do_sigs) { memset(doit, 1, sizeof(doit)); doit[D_EVP] = doit[D_EVP_CMAC] = 0; ERR_set_mark(); for (i = D_MD2; i <= D_WHIRLPOOL; i++) { if (!have_md(names[i])) doit[i] = 0; } for (i = D_CBC_DES; i <= D_CBC_256_CML; i++) { if (!have_cipher(names[i])) doit[i] = 0; } if ((mac = EVP_MAC_fetch(app_get0_libctx(), "GMAC", app_get0_propq())) != NULL) { EVP_MAC_free(mac); mac = NULL; } else { doit[D_GHASH] = 0; } if ((mac = EVP_MAC_fetch(app_get0_libctx(), "HMAC", app_get0_propq())) != NULL) { EVP_MAC_free(mac); mac = NULL; } else { doit[D_HMAC] = 0; } ERR_pop_to_mark(); memset(rsa_doit, 1, sizeof(rsa_doit)); #ifndef OPENSSL_NO_DH memset(ffdh_doit, 1, sizeof(ffdh_doit)); #endif memset(dsa_doit, 1, sizeof(dsa_doit)); #ifndef OPENSSL_NO_ECX memset(ecdsa_doit, 1, sizeof(ecdsa_doit)); memset(ecdh_doit, 1, sizeof(ecdh_doit)); memset(eddsa_doit, 1, sizeof(eddsa_doit)); #endif /* OPENSSL_NO_ECX */ #ifndef OPENSSL_NO_SM2 memset(sm2_doit, 1, sizeof(sm2_doit)); #endif memset(kems_doit, 1, sizeof(kems_doit)); do_kems = 1; memset(sigs_doit, 1, sizeof(sigs_doit)); do_sigs = 1; } for (i = 0; i < ALGOR_NUM; i++) if (doit[i]) pr_header++; if (usertime == 0 && !mr) BIO_printf(bio_err, "You have chosen to measure elapsed time " "instead of user CPU time.\n"); #if SIGALRM > 0 signal(SIGALRM, alarmed); #endif if (doit[D_MD2]) { for (testnum = 0; testnum < size_num; testnum++) { print_message(names[D_MD2], lengths[testnum], seconds.sym); Time_F(START); count = run_benchmark(async_jobs, EVP_Digest_MD2_loop, loopargs); d = Time_F(STOP); print_result(D_MD2, testnum, count, d); if (count < 0) break; } } if (doit[D_MDC2]) { for (testnum = 0; testnum < size_num; testnum++) { print_message(names[D_MDC2], lengths[testnum], seconds.sym); Time_F(START); count = run_benchmark(async_jobs, EVP_Digest_MDC2_loop, loopargs); d = Time_F(STOP); print_result(D_MDC2, testnum, count, d); if (count < 0) break; } } if (doit[D_MD4]) { for (testnum = 0; testnum < size_num; testnum++) { print_message(names[D_MD4], lengths[testnum], seconds.sym); Time_F(START); count = run_benchmark(async_jobs, EVP_Digest_MD4_loop, loopargs); d = Time_F(STOP); print_result(D_MD4, testnum, count, d); if (count < 0) break; } } if (doit[D_MD5]) { for (testnum = 0; testnum < size_num; testnum++) { print_message(names[D_MD5], lengths[testnum], seconds.sym); Time_F(START); count = run_benchmark(async_jobs, MD5_loop, loopargs); d = Time_F(STOP); print_result(D_MD5, testnum, count, d); if (count < 0) break; } } if (doit[D_SHA1]) { for (testnum = 0; testnum < size_num; testnum++) { print_message(names[D_SHA1], lengths[testnum], seconds.sym); Time_F(START); count = run_benchmark(async_jobs, SHA1_loop, loopargs); d = Time_F(STOP); print_result(D_SHA1, testnum, count, d); if (count < 0) break; } } if (doit[D_SHA256]) { for (testnum = 0; testnum < size_num; testnum++) { print_message(names[D_SHA256], lengths[testnum], seconds.sym); Time_F(START); count = run_benchmark(async_jobs, SHA256_loop, loopargs); d = Time_F(STOP); print_result(D_SHA256, testnum, count, d); if (count < 0) break; } } if (doit[D_SHA512]) { for (testnum = 0; testnum < size_num; testnum++) { print_message(names[D_SHA512], lengths[testnum], seconds.sym); Time_F(START); count = run_benchmark(async_jobs, SHA512_loop, loopargs); d = Time_F(STOP); print_result(D_SHA512, testnum, count, d); if (count < 0) break; } } if (doit[D_WHIRLPOOL]) { for (testnum = 0; testnum < size_num; testnum++) { print_message(names[D_WHIRLPOOL], lengths[testnum], seconds.sym); Time_F(START); count = run_benchmark(async_jobs, WHIRLPOOL_loop, loopargs); d = Time_F(STOP); print_result(D_WHIRLPOOL, testnum, count, d); if (count < 0) break; } } if (doit[D_RMD160]) { for (testnum = 0; testnum < size_num; testnum++) { print_message(names[D_RMD160], lengths[testnum], seconds.sym); Time_F(START); count = run_benchmark(async_jobs, EVP_Digest_RMD160_loop, loopargs); d = Time_F(STOP); print_result(D_RMD160, testnum, count, d); if (count < 0) break; } } if (doit[D_HMAC]) { static const char hmac_key[] = "This is a key..."; int len = strlen(hmac_key); OSSL_PARAM params[3]; if (evp_mac_mdname == NULL) goto end; evp_hmac_name = app_malloc(sizeof("hmac()") + strlen(evp_mac_mdname), "HMAC name"); sprintf(evp_hmac_name, "hmac(%s)", evp_mac_mdname); names[D_HMAC] = evp_hmac_name; params[0] = OSSL_PARAM_construct_utf8_string(OSSL_MAC_PARAM_DIGEST, evp_mac_mdname, 0); params[1] = OSSL_PARAM_construct_octet_string(OSSL_MAC_PARAM_KEY, (char *)hmac_key, len); params[2] = OSSL_PARAM_construct_end(); if (mac_setup("HMAC", &mac, params, loopargs, loopargs_len) < 1) goto end; for (testnum = 0; testnum < size_num; testnum++) { print_message(names[D_HMAC], lengths[testnum], seconds.sym); Time_F(START); count = run_benchmark(async_jobs, HMAC_loop, loopargs); d = Time_F(STOP); print_result(D_HMAC, testnum, count, d); if (count < 0) break; } mac_teardown(&mac, loopargs, loopargs_len); } if (doit[D_CBC_DES]) { int st = 1; for (i = 0; st && i < loopargs_len; i++) { loopargs[i].ctx = init_evp_cipher_ctx("des-cbc", deskey, sizeof(deskey) / 3); st = loopargs[i].ctx != NULL; } algindex = D_CBC_DES; for (testnum = 0; st && testnum < size_num; testnum++) { print_message(names[D_CBC_DES], lengths[testnum], seconds.sym); Time_F(START); count = run_benchmark(async_jobs, EVP_Cipher_loop, loopargs); d = Time_F(STOP); print_result(D_CBC_DES, testnum, count, d); } for (i = 0; i < loopargs_len; i++) EVP_CIPHER_CTX_free(loopargs[i].ctx); } if (doit[D_EDE3_DES]) { int st = 1; for (i = 0; st && i < loopargs_len; i++) { loopargs[i].ctx = init_evp_cipher_ctx("des-ede3-cbc", deskey, sizeof(deskey)); st = loopargs[i].ctx != NULL; } algindex = D_EDE3_DES; for (testnum = 0; st && testnum < size_num; testnum++) { print_message(names[D_EDE3_DES], lengths[testnum], seconds.sym); Time_F(START); count = run_benchmark(async_jobs, EVP_Cipher_loop, loopargs); d = Time_F(STOP); print_result(D_EDE3_DES, testnum, count, d); } for (i = 0; i < loopargs_len; i++) EVP_CIPHER_CTX_free(loopargs[i].ctx); } for (k = 0; k < 3; k++) { algindex = D_CBC_128_AES + k; if (doit[algindex]) { int st = 1; keylen = 16 + k * 8; for (i = 0; st && i < loopargs_len; i++) { loopargs[i].ctx = init_evp_cipher_ctx(names[algindex], key32, keylen); st = loopargs[i].ctx != NULL; } for (testnum = 0; st && testnum < size_num; testnum++) { print_message(names[algindex], lengths[testnum], seconds.sym); Time_F(START); count = run_benchmark(async_jobs, EVP_Cipher_loop, loopargs); d = Time_F(STOP); print_result(algindex, testnum, count, d); } for (i = 0; i < loopargs_len; i++) EVP_CIPHER_CTX_free(loopargs[i].ctx); } } for (k = 0; k < 3; k++) { algindex = D_CBC_128_CML + k; if (doit[algindex]) { int st = 1; keylen = 16 + k * 8; for (i = 0; st && i < loopargs_len; i++) { loopargs[i].ctx = init_evp_cipher_ctx(names[algindex], key32, keylen); st = loopargs[i].ctx != NULL; } for (testnum = 0; st && testnum < size_num; testnum++) { print_message(names[algindex], lengths[testnum], seconds.sym); Time_F(START); count = run_benchmark(async_jobs, EVP_Cipher_loop, loopargs); d = Time_F(STOP); print_result(algindex, testnum, count, d); } for (i = 0; i < loopargs_len; i++) EVP_CIPHER_CTX_free(loopargs[i].ctx); } } for (algindex = D_RC4; algindex <= D_CBC_CAST; algindex++) { if (doit[algindex]) { int st = 1; keylen = 16; for (i = 0; st && i < loopargs_len; i++) { loopargs[i].ctx = init_evp_cipher_ctx(names[algindex], key32, keylen); st = loopargs[i].ctx != NULL; } for (testnum = 0; st && testnum < size_num; testnum++) { print_message(names[algindex], lengths[testnum], seconds.sym); Time_F(START); count = run_benchmark(async_jobs, EVP_Cipher_loop, loopargs); d = Time_F(STOP); print_result(algindex, testnum, count, d); } for (i = 0; i < loopargs_len; i++) EVP_CIPHER_CTX_free(loopargs[i].ctx); } } if (doit[D_GHASH]) { static const char gmac_iv[] = "0123456789ab"; OSSL_PARAM params[4]; params[0] = OSSL_PARAM_construct_utf8_string(OSSL_ALG_PARAM_CIPHER, "aes-128-gcm", 0); params[1] = OSSL_PARAM_construct_octet_string(OSSL_MAC_PARAM_IV, (char *)gmac_iv, sizeof(gmac_iv) - 1); params[2] = OSSL_PARAM_construct_octet_string(OSSL_MAC_PARAM_KEY, (void *)key32, 16); params[3] = OSSL_PARAM_construct_end(); if (mac_setup("GMAC", &mac, params, loopargs, loopargs_len) < 1) goto end; /* b/c of the definition of GHASH_loop(), init() calls are needed here */ for (i = 0; i < loopargs_len; i++) { if (!EVP_MAC_init(loopargs[i].mctx, NULL, 0, NULL)) goto end; } for (testnum = 0; testnum < size_num; testnum++) { print_message(names[D_GHASH], lengths[testnum], seconds.sym); Time_F(START); count = run_benchmark(async_jobs, GHASH_loop, loopargs); d = Time_F(STOP); print_result(D_GHASH, testnum, count, d); if (count < 0) break; } mac_teardown(&mac, loopargs, loopargs_len); } if (doit[D_RAND]) { for (testnum = 0; testnum < size_num; testnum++) { print_message(names[D_RAND], lengths[testnum], seconds.sym); Time_F(START); count = run_benchmark(async_jobs, RAND_bytes_loop, loopargs); d = Time_F(STOP); print_result(D_RAND, testnum, count, d); } } if (doit[D_EVP]) { if (evp_cipher != NULL) { int (*loopfunc) (void *) = EVP_Update_loop; if (multiblock && (EVP_CIPHER_get_flags(evp_cipher) & EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK)) { multiblock_speed(evp_cipher, lengths_single, &seconds); ret = 0; goto end; } names[D_EVP] = EVP_CIPHER_get0_name(evp_cipher); if (EVP_CIPHER_get_mode(evp_cipher) == EVP_CIPH_CCM_MODE) { loopfunc = EVP_Update_loop_ccm; } else if (aead && (EVP_CIPHER_get_flags(evp_cipher) & EVP_CIPH_FLAG_AEAD_CIPHER)) { loopfunc = EVP_Update_loop_aead; if (lengths == lengths_list) { lengths = aead_lengths_list; size_num = OSSL_NELEM(aead_lengths_list); } } for (testnum = 0; testnum < size_num; testnum++) { print_message(names[D_EVP], lengths[testnum], seconds.sym); for (k = 0; k < loopargs_len; k++) { loopargs[k].ctx = EVP_CIPHER_CTX_new(); if (loopargs[k].ctx == NULL) { BIO_printf(bio_err, "\nEVP_CIPHER_CTX_new failure\n"); exit(1); } if (!EVP_CipherInit_ex(loopargs[k].ctx, evp_cipher, NULL, NULL, iv, decrypt ? 0 : 1)) { BIO_printf(bio_err, "\nEVP_CipherInit_ex failure\n"); ERR_print_errors(bio_err); exit(1); } EVP_CIPHER_CTX_set_padding(loopargs[k].ctx, 0); keylen = EVP_CIPHER_CTX_get_key_length(loopargs[k].ctx); loopargs[k].key = app_malloc(keylen, "evp_cipher key"); EVP_CIPHER_CTX_rand_key(loopargs[k].ctx, loopargs[k].key); if (!EVP_CipherInit_ex(loopargs[k].ctx, NULL, NULL, loopargs[k].key, NULL, -1)) { BIO_printf(bio_err, "\nEVP_CipherInit_ex failure\n"); ERR_print_errors(bio_err); exit(1); } OPENSSL_clear_free(loopargs[k].key, keylen); /* GCM-SIV/SIV mode only allows for a single Update operation */ if (EVP_CIPHER_get_mode(evp_cipher) == EVP_CIPH_SIV_MODE || EVP_CIPHER_get_mode(evp_cipher) == EVP_CIPH_GCM_SIV_MODE) (void)EVP_CIPHER_CTX_ctrl(loopargs[k].ctx, EVP_CTRL_SET_SPEED, 1, NULL); } Time_F(START); count = run_benchmark(async_jobs, loopfunc, loopargs); d = Time_F(STOP); for (k = 0; k < loopargs_len; k++) EVP_CIPHER_CTX_free(loopargs[k].ctx); print_result(D_EVP, testnum, count, d); } } else if (evp_md_name != NULL) { names[D_EVP] = evp_md_name; for (testnum = 0; testnum < size_num; testnum++) { print_message(names[D_EVP], lengths[testnum], seconds.sym); Time_F(START); count = run_benchmark(async_jobs, EVP_Digest_md_loop, loopargs); d = Time_F(STOP); print_result(D_EVP, testnum, count, d); if (count < 0) break; } } } if (doit[D_EVP_CMAC]) { OSSL_PARAM params[3]; EVP_CIPHER *cipher = NULL; if (!opt_cipher(evp_mac_ciphername, &cipher)) goto end; keylen = EVP_CIPHER_get_key_length(cipher); EVP_CIPHER_free(cipher); if (keylen <= 0 || keylen > (int)sizeof(key32)) { BIO_printf(bio_err, "\nRequested CMAC cipher with unsupported key length.\n"); goto end; } evp_cmac_name = app_malloc(sizeof("cmac()") + strlen(evp_mac_ciphername), "CMAC name"); sprintf(evp_cmac_name, "cmac(%s)", evp_mac_ciphername); names[D_EVP_CMAC] = evp_cmac_name; params[0] = OSSL_PARAM_construct_utf8_string(OSSL_ALG_PARAM_CIPHER, evp_mac_ciphername, 0); params[1] = OSSL_PARAM_construct_octet_string(OSSL_MAC_PARAM_KEY, (char *)key32, keylen); params[2] = OSSL_PARAM_construct_end(); if (mac_setup("CMAC", &mac, params, loopargs, loopargs_len) < 1) goto end; for (testnum = 0; testnum < size_num; testnum++) { print_message(names[D_EVP_CMAC], lengths[testnum], seconds.sym); Time_F(START); count = run_benchmark(async_jobs, CMAC_loop, loopargs); d = Time_F(STOP); print_result(D_EVP_CMAC, testnum, count, d); if (count < 0) break; } mac_teardown(&mac, loopargs, loopargs_len); } if (doit[D_KMAC128]) { OSSL_PARAM params[2]; params[0] = OSSL_PARAM_construct_octet_string(OSSL_MAC_PARAM_KEY, (void *)key32, 16); params[1] = OSSL_PARAM_construct_end(); if (mac_setup("KMAC-128", &mac, params, loopargs, loopargs_len) < 1) goto end; for (testnum = 0; testnum < size_num; testnum++) { print_message(names[D_KMAC128], lengths[testnum], seconds.sym); Time_F(START); count = run_benchmark(async_jobs, KMAC128_loop, loopargs); d = Time_F(STOP); print_result(D_KMAC128, testnum, count, d); if (count < 0) break; } mac_teardown(&mac, loopargs, loopargs_len); } if (doit[D_KMAC256]) { OSSL_PARAM params[2]; params[0] = OSSL_PARAM_construct_octet_string(OSSL_MAC_PARAM_KEY, (void *)key32, 32); params[1] = OSSL_PARAM_construct_end(); if (mac_setup("KMAC-256", &mac, params, loopargs, loopargs_len) < 1) goto end; for (testnum = 0; testnum < size_num; testnum++) { print_message(names[D_KMAC256], lengths[testnum], seconds.sym); Time_F(START); count = run_benchmark(async_jobs, KMAC256_loop, loopargs); d = Time_F(STOP); print_result(D_KMAC256, testnum, count, d); if (count < 0) break; } mac_teardown(&mac, loopargs, loopargs_len); } for (i = 0; i < loopargs_len; i++) if (RAND_bytes(loopargs[i].buf, 36) <= 0) goto end; for (testnum = 0; testnum < RSA_NUM; testnum++) { EVP_PKEY *rsa_key = NULL; int st = 0; if (!rsa_doit[testnum]) continue; if (primes > RSA_DEFAULT_PRIME_NUM) { /* we haven't set keys yet, generate multi-prime RSA keys */ bn = BN_new(); st = bn != NULL && BN_set_word(bn, RSA_F4) && init_gen_str(&genctx, "RSA", NULL, 0, NULL, NULL) && EVP_PKEY_CTX_set_rsa_keygen_bits(genctx, rsa_keys[testnum].bits) > 0 && EVP_PKEY_CTX_set1_rsa_keygen_pubexp(genctx, bn) > 0 && EVP_PKEY_CTX_set_rsa_keygen_primes(genctx, primes) > 0 && EVP_PKEY_keygen(genctx, &rsa_key); BN_free(bn); bn = NULL; EVP_PKEY_CTX_free(genctx); genctx = NULL; } else { const unsigned char *p = rsa_keys[testnum].data; st = (rsa_key = d2i_PrivateKey(EVP_PKEY_RSA, NULL, &p, rsa_keys[testnum].length)) != NULL; } for (i = 0; st && i < loopargs_len; i++) { loopargs[i].rsa_sign_ctx[testnum] = EVP_PKEY_CTX_new(rsa_key, NULL); loopargs[i].sigsize = loopargs[i].buflen; if (loopargs[i].rsa_sign_ctx[testnum] == NULL || EVP_PKEY_sign_init(loopargs[i].rsa_sign_ctx[testnum]) <= 0 || EVP_PKEY_sign(loopargs[i].rsa_sign_ctx[testnum], loopargs[i].buf2, &loopargs[i].sigsize, loopargs[i].buf, 36) <= 0) st = 0; } if (!st) { BIO_printf(bio_err, "RSA sign setup failure. No RSA sign will be done.\n"); ERR_print_errors(bio_err); op_count = 1; } else { pkey_print_message("private", "rsa sign", rsa_keys[testnum].bits, seconds.rsa); /* RSA_blinding_on(rsa_key[testnum],NULL); */ Time_F(START); count = run_benchmark(async_jobs, RSA_sign_loop, loopargs); d = Time_F(STOP); BIO_printf(bio_err, mr ? "+R1:%ld:%d:%.2f\n" : "%ld %u bits private RSA sign ops in %.2fs\n", count, rsa_keys[testnum].bits, d); rsa_results[testnum][0] = (double)count / d; op_count = count; } for (i = 0; st && i < loopargs_len; i++) { loopargs[i].rsa_verify_ctx[testnum] = EVP_PKEY_CTX_new(rsa_key, NULL); if (loopargs[i].rsa_verify_ctx[testnum] == NULL || EVP_PKEY_verify_init(loopargs[i].rsa_verify_ctx[testnum]) <= 0 || EVP_PKEY_verify(loopargs[i].rsa_verify_ctx[testnum], loopargs[i].buf2, loopargs[i].sigsize, loopargs[i].buf, 36) <= 0) st = 0; } if (!st) { BIO_printf(bio_err, "RSA verify setup failure. No RSA verify will be done.\n"); ERR_print_errors(bio_err); rsa_doit[testnum] = 0; } else { pkey_print_message("public", "rsa verify", rsa_keys[testnum].bits, seconds.rsa); Time_F(START); count = run_benchmark(async_jobs, RSA_verify_loop, loopargs); d = Time_F(STOP); BIO_printf(bio_err, mr ? "+R2:%ld:%d:%.2f\n" : "%ld %u bits public RSA verify ops in %.2fs\n", count, rsa_keys[testnum].bits, d); rsa_results[testnum][1] = (double)count / d; } for (i = 0; st && i < loopargs_len; i++) { loopargs[i].rsa_encrypt_ctx[testnum] = EVP_PKEY_CTX_new(rsa_key, NULL); loopargs[i].encsize = loopargs[i].buflen; if (loopargs[i].rsa_encrypt_ctx[testnum] == NULL || EVP_PKEY_encrypt_init(loopargs[i].rsa_encrypt_ctx[testnum]) <= 0 || EVP_PKEY_encrypt(loopargs[i].rsa_encrypt_ctx[testnum], loopargs[i].buf2, &loopargs[i].encsize, loopargs[i].buf, 36) <= 0) st = 0; } if (!st) { BIO_printf(bio_err, "RSA encrypt setup failure. No RSA encrypt will be done.\n"); ERR_print_errors(bio_err); op_count = 1; } else { pkey_print_message("private", "rsa encrypt", rsa_keys[testnum].bits, seconds.rsa); /* RSA_blinding_on(rsa_key[testnum],NULL); */ Time_F(START); count = run_benchmark(async_jobs, RSA_encrypt_loop, loopargs); d = Time_F(STOP); BIO_printf(bio_err, mr ? "+R3:%ld:%d:%.2f\n" : "%ld %u bits public RSA encrypt ops in %.2fs\n", count, rsa_keys[testnum].bits, d); rsa_results[testnum][2] = (double)count / d; op_count = count; } for (i = 0; st && i < loopargs_len; i++) { loopargs[i].rsa_decrypt_ctx[testnum] = EVP_PKEY_CTX_new(rsa_key, NULL); declen = loopargs[i].buflen; if (loopargs[i].rsa_decrypt_ctx[testnum] == NULL || EVP_PKEY_decrypt_init(loopargs[i].rsa_decrypt_ctx[testnum]) <= 0 || EVP_PKEY_decrypt(loopargs[i].rsa_decrypt_ctx[testnum], loopargs[i].buf, &declen, loopargs[i].buf2, loopargs[i].encsize) <= 0) st = 0; } if (!st) { BIO_printf(bio_err, "RSA decrypt setup failure. No RSA decrypt will be done.\n"); ERR_print_errors(bio_err); op_count = 1; } else { pkey_print_message("private", "rsa decrypt", rsa_keys[testnum].bits, seconds.rsa); /* RSA_blinding_on(rsa_key[testnum],NULL); */ Time_F(START); count = run_benchmark(async_jobs, RSA_decrypt_loop, loopargs); d = Time_F(STOP); BIO_printf(bio_err, mr ? "+R4:%ld:%d:%.2f\n" : "%ld %u bits private RSA decrypt ops in %.2fs\n", count, rsa_keys[testnum].bits, d); rsa_results[testnum][3] = (double)count / d; op_count = count; } if (op_count <= 1) { /* if longer than 10s, don't do any more */ stop_it(rsa_doit, testnum); } EVP_PKEY_free(rsa_key); } for (testnum = 0; testnum < DSA_NUM; testnum++) { EVP_PKEY *dsa_key = NULL; int st; if (!dsa_doit[testnum]) continue; st = (dsa_key = get_dsa(dsa_bits[testnum])) != NULL; for (i = 0; st && i < loopargs_len; i++) { loopargs[i].dsa_sign_ctx[testnum] = EVP_PKEY_CTX_new(dsa_key, NULL); loopargs[i].sigsize = loopargs[i].buflen; if (loopargs[i].dsa_sign_ctx[testnum] == NULL || EVP_PKEY_sign_init(loopargs[i].dsa_sign_ctx[testnum]) <= 0 || EVP_PKEY_sign(loopargs[i].dsa_sign_ctx[testnum], loopargs[i].buf2, &loopargs[i].sigsize, loopargs[i].buf, 20) <= 0) st = 0; } if (!st) { BIO_printf(bio_err, "DSA sign setup failure. No DSA sign will be done.\n"); ERR_print_errors(bio_err); op_count = 1; } else { pkey_print_message("sign", "dsa", dsa_bits[testnum], seconds.dsa); Time_F(START); count = run_benchmark(async_jobs, DSA_sign_loop, loopargs); d = Time_F(STOP); BIO_printf(bio_err, mr ? "+R5:%ld:%u:%.2f\n" : "%ld %u bits DSA sign ops in %.2fs\n", count, dsa_bits[testnum], d); dsa_results[testnum][0] = (double)count / d; op_count = count; } for (i = 0; st && i < loopargs_len; i++) { loopargs[i].dsa_verify_ctx[testnum] = EVP_PKEY_CTX_new(dsa_key, NULL); if (loopargs[i].dsa_verify_ctx[testnum] == NULL || EVP_PKEY_verify_init(loopargs[i].dsa_verify_ctx[testnum]) <= 0 || EVP_PKEY_verify(loopargs[i].dsa_verify_ctx[testnum], loopargs[i].buf2, loopargs[i].sigsize, loopargs[i].buf, 36) <= 0) st = 0; } if (!st) { BIO_printf(bio_err, "DSA verify setup failure. No DSA verify will be done.\n"); ERR_print_errors(bio_err); dsa_doit[testnum] = 0; } else { pkey_print_message("verify", "dsa", dsa_bits[testnum], seconds.dsa); Time_F(START); count = run_benchmark(async_jobs, DSA_verify_loop, loopargs); d = Time_F(STOP); BIO_printf(bio_err, mr ? "+R6:%ld:%u:%.2f\n" : "%ld %u bits DSA verify ops in %.2fs\n", count, dsa_bits[testnum], d); dsa_results[testnum][1] = (double)count / d; } if (op_count <= 1) { /* if longer than 10s, don't do any more */ stop_it(dsa_doit, testnum); } EVP_PKEY_free(dsa_key); } for (testnum = 0; testnum < ECDSA_NUM; testnum++) { EVP_PKEY *ecdsa_key = NULL; int st; if (!ecdsa_doit[testnum]) continue; st = (ecdsa_key = get_ecdsa(&ec_curves[testnum])) != NULL; for (i = 0; st && i < loopargs_len; i++) { loopargs[i].ecdsa_sign_ctx[testnum] = EVP_PKEY_CTX_new(ecdsa_key, NULL); loopargs[i].sigsize = loopargs[i].buflen; if (loopargs[i].ecdsa_sign_ctx[testnum] == NULL || EVP_PKEY_sign_init(loopargs[i].ecdsa_sign_ctx[testnum]) <= 0 || EVP_PKEY_sign(loopargs[i].ecdsa_sign_ctx[testnum], loopargs[i].buf2, &loopargs[i].sigsize, loopargs[i].buf, 20) <= 0) st = 0; } if (!st) { BIO_printf(bio_err, "ECDSA sign setup failure. No ECDSA sign will be done.\n"); ERR_print_errors(bio_err); op_count = 1; } else { pkey_print_message("sign", "ecdsa", ec_curves[testnum].bits, seconds.ecdsa); Time_F(START); count = run_benchmark(async_jobs, ECDSA_sign_loop, loopargs); d = Time_F(STOP); BIO_printf(bio_err, mr ? "+R7:%ld:%u:%.2f\n" : "%ld %u bits ECDSA sign ops in %.2fs\n", count, ec_curves[testnum].bits, d); ecdsa_results[testnum][0] = (double)count / d; op_count = count; } for (i = 0; st && i < loopargs_len; i++) { loopargs[i].ecdsa_verify_ctx[testnum] = EVP_PKEY_CTX_new(ecdsa_key, NULL); if (loopargs[i].ecdsa_verify_ctx[testnum] == NULL || EVP_PKEY_verify_init(loopargs[i].ecdsa_verify_ctx[testnum]) <= 0 || EVP_PKEY_verify(loopargs[i].ecdsa_verify_ctx[testnum], loopargs[i].buf2, loopargs[i].sigsize, loopargs[i].buf, 20) <= 0) st = 0; } if (!st) { BIO_printf(bio_err, "ECDSA verify setup failure. No ECDSA verify will be done.\n"); ERR_print_errors(bio_err); ecdsa_doit[testnum] = 0; } else { pkey_print_message("verify", "ecdsa", ec_curves[testnum].bits, seconds.ecdsa); Time_F(START); count = run_benchmark(async_jobs, ECDSA_verify_loop, loopargs); d = Time_F(STOP); BIO_printf(bio_err, mr ? "+R8:%ld:%u:%.2f\n" : "%ld %u bits ECDSA verify ops in %.2fs\n", count, ec_curves[testnum].bits, d); ecdsa_results[testnum][1] = (double)count / d; } if (op_count <= 1) { /* if longer than 10s, don't do any more */ stop_it(ecdsa_doit, testnum); } } for (testnum = 0; testnum < EC_NUM; testnum++) { int ecdh_checks = 1; if (!ecdh_doit[testnum]) continue; for (i = 0; i < loopargs_len; i++) { EVP_PKEY_CTX *test_ctx = NULL; EVP_PKEY_CTX *ctx = NULL; EVP_PKEY *key_A = NULL; EVP_PKEY *key_B = NULL; size_t outlen; size_t test_outlen; if ((key_A = get_ecdsa(&ec_curves[testnum])) == NULL /* generate secret key A */ || (key_B = get_ecdsa(&ec_curves[testnum])) == NULL /* generate secret key B */ || (ctx = EVP_PKEY_CTX_new(key_A, NULL)) == NULL /* derivation ctx from skeyA */ || EVP_PKEY_derive_init(ctx) <= 0 /* init derivation ctx */ || EVP_PKEY_derive_set_peer(ctx, key_B) <= 0 /* set peer pubkey in ctx */ || EVP_PKEY_derive(ctx, NULL, &outlen) <= 0 /* determine max length */ || outlen == 0 /* ensure outlen is a valid size */ || outlen > MAX_ECDH_SIZE /* avoid buffer overflow */) { ecdh_checks = 0; BIO_printf(bio_err, "ECDH key generation failure.\n"); ERR_print_errors(bio_err); op_count = 1; break; } /* * Here we perform a test run, comparing the output of a*B and b*A; * we try this here and assume that further EVP_PKEY_derive calls * never fail, so we can skip checks in the actually benchmarked * code, for maximum performance. */ if ((test_ctx = EVP_PKEY_CTX_new(key_B, NULL)) == NULL /* test ctx from skeyB */ || EVP_PKEY_derive_init(test_ctx) <= 0 /* init derivation test_ctx */ || EVP_PKEY_derive_set_peer(test_ctx, key_A) <= 0 /* set peer pubkey in test_ctx */ || EVP_PKEY_derive(test_ctx, NULL, &test_outlen) <= 0 /* determine max length */ || EVP_PKEY_derive(ctx, loopargs[i].secret_a, &outlen) <= 0 /* compute a*B */ || EVP_PKEY_derive(test_ctx, loopargs[i].secret_b, &test_outlen) <= 0 /* compute b*A */ || test_outlen != outlen /* compare output length */) { ecdh_checks = 0; BIO_printf(bio_err, "ECDH computation failure.\n"); ERR_print_errors(bio_err); op_count = 1; break; } /* Compare the computation results: CRYPTO_memcmp() returns 0 if equal */ if (CRYPTO_memcmp(loopargs[i].secret_a, loopargs[i].secret_b, outlen)) { ecdh_checks = 0; BIO_printf(bio_err, "ECDH computations don't match.\n"); ERR_print_errors(bio_err); op_count = 1; break; } loopargs[i].ecdh_ctx[testnum] = ctx; loopargs[i].outlen[testnum] = outlen; EVP_PKEY_free(key_A); EVP_PKEY_free(key_B); EVP_PKEY_CTX_free(test_ctx); test_ctx = NULL; } if (ecdh_checks != 0) { pkey_print_message("", "ecdh", ec_curves[testnum].bits, seconds.ecdh); Time_F(START); count = run_benchmark(async_jobs, ECDH_EVP_derive_key_loop, loopargs); d = Time_F(STOP); BIO_printf(bio_err, mr ? "+R9:%ld:%d:%.2f\n" : "%ld %u-bits ECDH ops in %.2fs\n", count, ec_curves[testnum].bits, d); ecdh_results[testnum][0] = (double)count / d; op_count = count; } if (op_count <= 1) { /* if longer than 10s, don't do any more */ stop_it(ecdh_doit, testnum); } } #ifndef OPENSSL_NO_ECX for (testnum = 0; testnum < EdDSA_NUM; testnum++) { int st = 1; EVP_PKEY *ed_pkey = NULL; EVP_PKEY_CTX *ed_pctx = NULL; if (!eddsa_doit[testnum]) continue; /* Ignore Curve */ for (i = 0; i < loopargs_len; i++) { loopargs[i].eddsa_ctx[testnum] = EVP_MD_CTX_new(); if (loopargs[i].eddsa_ctx[testnum] == NULL) { st = 0; break; } loopargs[i].eddsa_ctx2[testnum] = EVP_MD_CTX_new(); if (loopargs[i].eddsa_ctx2[testnum] == NULL) { st = 0; break; } if ((ed_pctx = EVP_PKEY_CTX_new_id(ed_curves[testnum].nid, NULL)) == NULL || EVP_PKEY_keygen_init(ed_pctx) <= 0 || EVP_PKEY_keygen(ed_pctx, &ed_pkey) <= 0) { st = 0; EVP_PKEY_CTX_free(ed_pctx); break; } EVP_PKEY_CTX_free(ed_pctx); if (!EVP_DigestSignInit(loopargs[i].eddsa_ctx[testnum], NULL, NULL, NULL, ed_pkey)) { st = 0; EVP_PKEY_free(ed_pkey); break; } if (!EVP_DigestVerifyInit(loopargs[i].eddsa_ctx2[testnum], NULL, NULL, NULL, ed_pkey)) { st = 0; EVP_PKEY_free(ed_pkey); break; } EVP_PKEY_free(ed_pkey); ed_pkey = NULL; } if (st == 0) { BIO_printf(bio_err, "EdDSA failure.\n"); ERR_print_errors(bio_err); op_count = 1; } else { for (i = 0; i < loopargs_len; i++) { /* Perform EdDSA signature test */ loopargs[i].sigsize = ed_curves[testnum].sigsize; st = EVP_DigestSign(loopargs[i].eddsa_ctx[testnum], loopargs[i].buf2, &loopargs[i].sigsize, loopargs[i].buf, 20); if (st == 0) break; } if (st == 0) { BIO_printf(bio_err, "EdDSA sign failure. No EdDSA sign will be done.\n"); ERR_print_errors(bio_err); op_count = 1; } else { pkey_print_message("sign", ed_curves[testnum].name, ed_curves[testnum].bits, seconds.eddsa); Time_F(START); count = run_benchmark(async_jobs, EdDSA_sign_loop, loopargs); d = Time_F(STOP); BIO_printf(bio_err, mr ? "+R10:%ld:%u:%s:%.2f\n" : "%ld %u bits %s sign ops in %.2fs \n", count, ed_curves[testnum].bits, ed_curves[testnum].name, d); eddsa_results[testnum][0] = (double)count / d; op_count = count; } /* Perform EdDSA verification test */ for (i = 0; i < loopargs_len; i++) { st = EVP_DigestVerify(loopargs[i].eddsa_ctx2[testnum], loopargs[i].buf2, loopargs[i].sigsize, loopargs[i].buf, 20); if (st != 1) break; } if (st != 1) { BIO_printf(bio_err, "EdDSA verify failure. No EdDSA verify will be done.\n"); ERR_print_errors(bio_err); eddsa_doit[testnum] = 0; } else { pkey_print_message("verify", ed_curves[testnum].name, ed_curves[testnum].bits, seconds.eddsa); Time_F(START); count = run_benchmark(async_jobs, EdDSA_verify_loop, loopargs); d = Time_F(STOP); BIO_printf(bio_err, mr ? "+R11:%ld:%u:%s:%.2f\n" : "%ld %u bits %s verify ops in %.2fs\n", count, ed_curves[testnum].bits, ed_curves[testnum].name, d); eddsa_results[testnum][1] = (double)count / d; } if (op_count <= 1) { /* if longer than 10s, don't do any more */ stop_it(eddsa_doit, testnum); } } } #endif /* OPENSSL_NO_ECX */ #ifndef OPENSSL_NO_SM2 for (testnum = 0; testnum < SM2_NUM; testnum++) { int st = 1; EVP_PKEY *sm2_pkey = NULL; if (!sm2_doit[testnum]) continue; /* Ignore Curve */ /* Init signing and verification */ for (i = 0; i < loopargs_len; i++) { EVP_PKEY_CTX *sm2_pctx = NULL; EVP_PKEY_CTX *sm2_vfy_pctx = NULL; EVP_PKEY_CTX *pctx = NULL; st = 0; loopargs[i].sm2_ctx[testnum] = EVP_MD_CTX_new(); loopargs[i].sm2_vfy_ctx[testnum] = EVP_MD_CTX_new(); if (loopargs[i].sm2_ctx[testnum] == NULL || loopargs[i].sm2_vfy_ctx[testnum] == NULL) break; sm2_pkey = NULL; st = !((pctx = EVP_PKEY_CTX_new_id(EVP_PKEY_SM2, NULL)) == NULL || EVP_PKEY_keygen_init(pctx) <= 0 || EVP_PKEY_CTX_set_ec_paramgen_curve_nid(pctx, sm2_curves[testnum].nid) <= 0 || EVP_PKEY_keygen(pctx, &sm2_pkey) <= 0); EVP_PKEY_CTX_free(pctx); if (st == 0) break; st = 0; /* set back to zero */ /* attach it sooner to rely on main final cleanup */ loopargs[i].sm2_pkey[testnum] = sm2_pkey; loopargs[i].sigsize = EVP_PKEY_get_size(sm2_pkey); sm2_pctx = EVP_PKEY_CTX_new(sm2_pkey, NULL); sm2_vfy_pctx = EVP_PKEY_CTX_new(sm2_pkey, NULL); if (sm2_pctx == NULL || sm2_vfy_pctx == NULL) { EVP_PKEY_CTX_free(sm2_vfy_pctx); break; } /* attach them directly to respective ctx */ EVP_MD_CTX_set_pkey_ctx(loopargs[i].sm2_ctx[testnum], sm2_pctx); EVP_MD_CTX_set_pkey_ctx(loopargs[i].sm2_vfy_ctx[testnum], sm2_vfy_pctx); /* * No need to allow user to set an explicit ID here, just use * the one defined in the 'draft-yang-tls-tl13-sm-suites' I-D. */ if (EVP_PKEY_CTX_set1_id(sm2_pctx, SM2_ID, SM2_ID_LEN) != 1 || EVP_PKEY_CTX_set1_id(sm2_vfy_pctx, SM2_ID, SM2_ID_LEN) != 1) break; if (!EVP_DigestSignInit(loopargs[i].sm2_ctx[testnum], NULL, EVP_sm3(), NULL, sm2_pkey)) break; if (!EVP_DigestVerifyInit(loopargs[i].sm2_vfy_ctx[testnum], NULL, EVP_sm3(), NULL, sm2_pkey)) break; st = 1; /* mark loop as succeeded */ } if (st == 0) { BIO_printf(bio_err, "SM2 init failure.\n"); ERR_print_errors(bio_err); op_count = 1; } else { for (i = 0; i < loopargs_len; i++) { /* Perform SM2 signature test */ st = EVP_DigestSign(loopargs[i].sm2_ctx[testnum], loopargs[i].buf2, &loopargs[i].sigsize, loopargs[i].buf, 20); if (st == 0) break; } if (st == 0) { BIO_printf(bio_err, "SM2 sign failure. No SM2 sign will be done.\n"); ERR_print_errors(bio_err); op_count = 1; } else { pkey_print_message("sign", sm2_curves[testnum].name, sm2_curves[testnum].bits, seconds.sm2); Time_F(START); count = run_benchmark(async_jobs, SM2_sign_loop, loopargs); d = Time_F(STOP); BIO_printf(bio_err, mr ? "+R12:%ld:%u:%s:%.2f\n" : "%ld %u bits %s sign ops in %.2fs \n", count, sm2_curves[testnum].bits, sm2_curves[testnum].name, d); sm2_results[testnum][0] = (double)count / d; op_count = count; } /* Perform SM2 verification test */ for (i = 0; i < loopargs_len; i++) { st = EVP_DigestVerify(loopargs[i].sm2_vfy_ctx[testnum], loopargs[i].buf2, loopargs[i].sigsize, loopargs[i].buf, 20); if (st != 1) break; } if (st != 1) { BIO_printf(bio_err, "SM2 verify failure. No SM2 verify will be done.\n"); ERR_print_errors(bio_err); sm2_doit[testnum] = 0; } else { pkey_print_message("verify", sm2_curves[testnum].name, sm2_curves[testnum].bits, seconds.sm2); Time_F(START); count = run_benchmark(async_jobs, SM2_verify_loop, loopargs); d = Time_F(STOP); BIO_printf(bio_err, mr ? "+R13:%ld:%u:%s:%.2f\n" : "%ld %u bits %s verify ops in %.2fs\n", count, sm2_curves[testnum].bits, sm2_curves[testnum].name, d); sm2_results[testnum][1] = (double)count / d; } if (op_count <= 1) { /* if longer than 10s, don't do any more */ for (testnum++; testnum < SM2_NUM; testnum++) sm2_doit[testnum] = 0; } } } #endif /* OPENSSL_NO_SM2 */ #ifndef OPENSSL_NO_DH for (testnum = 0; testnum < FFDH_NUM; testnum++) { int ffdh_checks = 1; if (!ffdh_doit[testnum]) continue; for (i = 0; i < loopargs_len; i++) { EVP_PKEY *pkey_A = NULL; EVP_PKEY *pkey_B = NULL; EVP_PKEY_CTX *ffdh_ctx = NULL; EVP_PKEY_CTX *test_ctx = NULL; size_t secret_size; size_t test_out; /* Ensure that the error queue is empty */ if (ERR_peek_error()) { BIO_printf(bio_err, "WARNING: the error queue contains previous unhandled errors.\n"); ERR_print_errors(bio_err); } pkey_A = EVP_PKEY_new(); if (!pkey_A) { BIO_printf(bio_err, "Error while initialising EVP_PKEY (out of memory?).\n"); ERR_print_errors(bio_err); op_count = 1; ffdh_checks = 0; break; } pkey_B = EVP_PKEY_new(); if (!pkey_B) { BIO_printf(bio_err, "Error while initialising EVP_PKEY (out of memory?).\n"); ERR_print_errors(bio_err); op_count = 1; ffdh_checks = 0; break; } ffdh_ctx = EVP_PKEY_CTX_new_id(EVP_PKEY_DH, NULL); if (!ffdh_ctx) { BIO_printf(bio_err, "Error while allocating EVP_PKEY_CTX.\n"); ERR_print_errors(bio_err); op_count = 1; ffdh_checks = 0; break; } if (EVP_PKEY_keygen_init(ffdh_ctx) <= 0) { BIO_printf(bio_err, "Error while initialising EVP_PKEY_CTX.\n"); ERR_print_errors(bio_err); op_count = 1; ffdh_checks = 0; break; } if (EVP_PKEY_CTX_set_dh_nid(ffdh_ctx, ffdh_params[testnum].nid) <= 0) { BIO_printf(bio_err, "Error setting DH key size for keygen.\n"); ERR_print_errors(bio_err); op_count = 1; ffdh_checks = 0; break; } if (EVP_PKEY_keygen(ffdh_ctx, &pkey_A) <= 0 || EVP_PKEY_keygen(ffdh_ctx, &pkey_B) <= 0) { BIO_printf(bio_err, "FFDH key generation failure.\n"); ERR_print_errors(bio_err); op_count = 1; ffdh_checks = 0; break; } EVP_PKEY_CTX_free(ffdh_ctx); /* * check if the derivation works correctly both ways so that * we know if future derive calls will fail, and we can skip * error checking in benchmarked code */ ffdh_ctx = EVP_PKEY_CTX_new(pkey_A, NULL); if (ffdh_ctx == NULL) { BIO_printf(bio_err, "Error while allocating EVP_PKEY_CTX.\n"); ERR_print_errors(bio_err); op_count = 1; ffdh_checks = 0; break; } if (EVP_PKEY_derive_init(ffdh_ctx) <= 0) { BIO_printf(bio_err, "FFDH derivation context init failure.\n"); ERR_print_errors(bio_err); op_count = 1; ffdh_checks = 0; break; } if (EVP_PKEY_derive_set_peer(ffdh_ctx, pkey_B) <= 0) { BIO_printf(bio_err, "Assigning peer key for derivation failed.\n"); ERR_print_errors(bio_err); op_count = 1; ffdh_checks = 0; break; } if (EVP_PKEY_derive(ffdh_ctx, NULL, &secret_size) <= 0) { BIO_printf(bio_err, "Checking size of shared secret failed.\n"); ERR_print_errors(bio_err); op_count = 1; ffdh_checks = 0; break; } if (secret_size > MAX_FFDH_SIZE) { BIO_printf(bio_err, "Assertion failure: shared secret too large.\n"); op_count = 1; ffdh_checks = 0; break; } if (EVP_PKEY_derive(ffdh_ctx, loopargs[i].secret_ff_a, &secret_size) <= 0) { BIO_printf(bio_err, "Shared secret derive failure.\n"); ERR_print_errors(bio_err); op_count = 1; ffdh_checks = 0; break; } /* Now check from side B */ test_ctx = EVP_PKEY_CTX_new(pkey_B, NULL); if (!test_ctx) { BIO_printf(bio_err, "Error while allocating EVP_PKEY_CTX.\n"); ERR_print_errors(bio_err); op_count = 1; ffdh_checks = 0; break; } if (EVP_PKEY_derive_init(test_ctx) <= 0 || EVP_PKEY_derive_set_peer(test_ctx, pkey_A) <= 0 || EVP_PKEY_derive(test_ctx, NULL, &test_out) <= 0 || EVP_PKEY_derive(test_ctx, loopargs[i].secret_ff_b, &test_out) <= 0 || test_out != secret_size) { BIO_printf(bio_err, "FFDH computation failure.\n"); op_count = 1; ffdh_checks = 0; break; } /* compare the computed secrets */ if (CRYPTO_memcmp(loopargs[i].secret_ff_a, loopargs[i].secret_ff_b, secret_size)) { BIO_printf(bio_err, "FFDH computations don't match.\n"); ERR_print_errors(bio_err); op_count = 1; ffdh_checks = 0; break; } loopargs[i].ffdh_ctx[testnum] = ffdh_ctx; EVP_PKEY_free(pkey_A); pkey_A = NULL; EVP_PKEY_free(pkey_B); pkey_B = NULL; EVP_PKEY_CTX_free(test_ctx); test_ctx = NULL; } if (ffdh_checks != 0) { pkey_print_message("", "ffdh", ffdh_params[testnum].bits, seconds.ffdh); Time_F(START); count = run_benchmark(async_jobs, FFDH_derive_key_loop, loopargs); d = Time_F(STOP); BIO_printf(bio_err, mr ? "+R14:%ld:%d:%.2f\n" : "%ld %u-bits FFDH ops in %.2fs\n", count, ffdh_params[testnum].bits, d); ffdh_results[testnum][0] = (double)count / d; op_count = count; } if (op_count <= 1) { /* if longer than 10s, don't do any more */ stop_it(ffdh_doit, testnum); } } #endif /* OPENSSL_NO_DH */ for (testnum = 0; testnum < kems_algs_len; testnum++) { int kem_checks = 1; const char *kem_name = kems_algname[testnum]; if (!kems_doit[testnum] || !do_kems) continue; for (i = 0; i < loopargs_len; i++) { EVP_PKEY *pkey = NULL; EVP_PKEY_CTX *kem_gen_ctx = NULL; EVP_PKEY_CTX *kem_encaps_ctx = NULL; EVP_PKEY_CTX *kem_decaps_ctx = NULL; size_t send_secret_len, out_len; size_t rcv_secret_len; unsigned char *out = NULL, *send_secret = NULL, *rcv_secret; unsigned int bits; char *name; char sfx[MAX_ALGNAME_SUFFIX]; OSSL_PARAM params[] = { OSSL_PARAM_END, OSSL_PARAM_END }; int use_params = 0; enum kem_type_t { KEM_RSA = 1, KEM_EC, KEM_X25519, KEM_X448 } kem_type; /* no string after rsa<bitcnt> permitted: */ if (strlen(kem_name) < MAX_ALGNAME_SUFFIX + 4 /* rsa+digit */ && sscanf(kem_name, "rsa%u%s", &bits, sfx) == 1) kem_type = KEM_RSA; else if (strncmp(kem_name, "EC", 2) == 0) kem_type = KEM_EC; else if (strcmp(kem_name, "X25519") == 0) kem_type = KEM_X25519; else if (strcmp(kem_name, "X448") == 0) kem_type = KEM_X448; else kem_type = 0; if (ERR_peek_error()) { BIO_printf(bio_err, "WARNING: the error queue contains previous unhandled errors.\n"); ERR_print_errors(bio_err); } if (kem_type == KEM_RSA) { params[0] = OSSL_PARAM_construct_uint(OSSL_PKEY_PARAM_RSA_BITS, &bits); use_params = 1; } else if (kem_type == KEM_EC) { name = (char *)(kem_name + 2); params[0] = OSSL_PARAM_construct_utf8_string(OSSL_PKEY_PARAM_GROUP_NAME, name, 0); use_params = 1; } kem_gen_ctx = EVP_PKEY_CTX_new_from_name(app_get0_libctx(), (kem_type == KEM_RSA) ? "RSA": (kem_type == KEM_EC) ? "EC": kem_name, app_get0_propq()); if ((!kem_gen_ctx || EVP_PKEY_keygen_init(kem_gen_ctx) <= 0) || (use_params && EVP_PKEY_CTX_set_params(kem_gen_ctx, params) <= 0)) { BIO_printf(bio_err, "Error initializing keygen ctx for %s.\n", kem_name); goto kem_err_break; } if (EVP_PKEY_keygen(kem_gen_ctx, &pkey) <= 0) { BIO_printf(bio_err, "Error while generating KEM EVP_PKEY.\n"); goto kem_err_break; } /* Now prepare encaps data structs */ kem_encaps_ctx = EVP_PKEY_CTX_new_from_pkey(app_get0_libctx(), pkey, app_get0_propq()); if (kem_encaps_ctx == NULL || EVP_PKEY_encapsulate_init(kem_encaps_ctx, NULL) <= 0 || (kem_type == KEM_RSA && EVP_PKEY_CTX_set_kem_op(kem_encaps_ctx, "RSASVE") <= 0) || ((kem_type == KEM_EC || kem_type == KEM_X25519 || kem_type == KEM_X448) && EVP_PKEY_CTX_set_kem_op(kem_encaps_ctx, "DHKEM") <= 0) || EVP_PKEY_encapsulate(kem_encaps_ctx, NULL, &out_len, NULL, &send_secret_len) <= 0) { BIO_printf(bio_err, "Error while initializing encaps data structs for %s.\n", kem_name); goto kem_err_break; } out = app_malloc(out_len, "encaps result"); send_secret = app_malloc(send_secret_len, "encaps secret"); if (out == NULL || send_secret == NULL) { BIO_printf(bio_err, "MemAlloc error in encaps for %s.\n", kem_name); goto kem_err_break; } if (EVP_PKEY_encapsulate(kem_encaps_ctx, out, &out_len, send_secret, &send_secret_len) <= 0) { BIO_printf(bio_err, "Encaps error for %s.\n", kem_name); goto kem_err_break; } /* Now prepare decaps data structs */ kem_decaps_ctx = EVP_PKEY_CTX_new_from_pkey(app_get0_libctx(), pkey, app_get0_propq()); if (kem_decaps_ctx == NULL || EVP_PKEY_decapsulate_init(kem_decaps_ctx, NULL) <= 0 || (kem_type == KEM_RSA && EVP_PKEY_CTX_set_kem_op(kem_decaps_ctx, "RSASVE") <= 0) || ((kem_type == KEM_EC || kem_type == KEM_X25519 || kem_type == KEM_X448) && EVP_PKEY_CTX_set_kem_op(kem_decaps_ctx, "DHKEM") <= 0) || EVP_PKEY_decapsulate(kem_decaps_ctx, NULL, &rcv_secret_len, out, out_len) <= 0) { BIO_printf(bio_err, "Error while initializing decaps data structs for %s.\n", kem_name); goto kem_err_break; } rcv_secret = app_malloc(rcv_secret_len, "KEM decaps secret"); if (rcv_secret == NULL) { BIO_printf(bio_err, "MemAlloc failure in decaps for %s.\n", kem_name); goto kem_err_break; } if (EVP_PKEY_decapsulate(kem_decaps_ctx, rcv_secret, &rcv_secret_len, out, out_len) <= 0 || rcv_secret_len != send_secret_len || memcmp(send_secret, rcv_secret, send_secret_len)) { BIO_printf(bio_err, "Decaps error for %s.\n", kem_name); goto kem_err_break; } loopargs[i].kem_gen_ctx[testnum] = kem_gen_ctx; loopargs[i].kem_encaps_ctx[testnum] = kem_encaps_ctx; loopargs[i].kem_decaps_ctx[testnum] = kem_decaps_ctx; loopargs[i].kem_out_len[testnum] = out_len; loopargs[i].kem_secret_len[testnum] = send_secret_len; loopargs[i].kem_out[testnum] = out; loopargs[i].kem_send_secret[testnum] = send_secret; loopargs[i].kem_rcv_secret[testnum] = rcv_secret; EVP_PKEY_free(pkey); pkey = NULL; continue; kem_err_break: ERR_print_errors(bio_err); EVP_PKEY_free(pkey); op_count = 1; kem_checks = 0; break; } if (kem_checks != 0) { kskey_print_message(kem_name, "keygen", seconds.kem); Time_F(START); count = run_benchmark(async_jobs, KEM_keygen_loop, loopargs); d = Time_F(STOP); BIO_printf(bio_err, mr ? "+R15:%ld:%s:%.2f\n" : "%ld %s KEM keygen ops in %.2fs\n", count, kem_name, d); kems_results[testnum][0] = (double)count / d; op_count = count; kskey_print_message(kem_name, "encaps", seconds.kem); Time_F(START); count = run_benchmark(async_jobs, KEM_encaps_loop, loopargs); d = Time_F(STOP); BIO_printf(bio_err, mr ? "+R16:%ld:%s:%.2f\n" : "%ld %s KEM encaps ops in %.2fs\n", count, kem_name, d); kems_results[testnum][1] = (double)count / d; op_count = count; kskey_print_message(kem_name, "decaps", seconds.kem); Time_F(START); count = run_benchmark(async_jobs, KEM_decaps_loop, loopargs); d = Time_F(STOP); BIO_printf(bio_err, mr ? "+R17:%ld:%s:%.2f\n" : "%ld %s KEM decaps ops in %.2fs\n", count, kem_name, d); kems_results[testnum][2] = (double)count / d; op_count = count; } if (op_count <= 1) { /* if longer than 10s, don't do any more */ stop_it(kems_doit, testnum); } } for (testnum = 0; testnum < sigs_algs_len; testnum++) { int sig_checks = 1; const char *sig_name = sigs_algname[testnum]; if (!sigs_doit[testnum] || !do_sigs) continue; for (i = 0; i < loopargs_len; i++) { EVP_PKEY *pkey = NULL; EVP_PKEY_CTX *ctx_params = NULL; EVP_PKEY* pkey_params = NULL; EVP_PKEY_CTX *sig_gen_ctx = NULL; EVP_PKEY_CTX *sig_sign_ctx = NULL; EVP_PKEY_CTX *sig_verify_ctx = NULL; unsigned char md[SHA256_DIGEST_LENGTH]; unsigned char *sig; char sfx[MAX_ALGNAME_SUFFIX]; size_t md_len = SHA256_DIGEST_LENGTH; size_t max_sig_len, sig_len; unsigned int bits; OSSL_PARAM params[] = { OSSL_PARAM_END, OSSL_PARAM_END }; int use_params = 0; /* only sign little data to avoid measuring digest performance */ memset(md, 0, SHA256_DIGEST_LENGTH); if (ERR_peek_error()) { BIO_printf(bio_err, "WARNING: the error queue contains previous unhandled errors.\n"); ERR_print_errors(bio_err); } /* no string after rsa<bitcnt> permitted: */ if (strlen(sig_name) < MAX_ALGNAME_SUFFIX + 4 /* rsa+digit */ && sscanf(sig_name, "rsa%u%s", &bits, sfx) == 1) { params[0] = OSSL_PARAM_construct_uint(OSSL_PKEY_PARAM_RSA_BITS, &bits); use_params = 1; } if (strncmp(sig_name, "dsa", 3) == 0) { ctx_params = EVP_PKEY_CTX_new_id(EVP_PKEY_DSA, NULL); if (ctx_params == NULL || EVP_PKEY_paramgen_init(ctx_params) <= 0 || EVP_PKEY_CTX_set_dsa_paramgen_bits(ctx_params, atoi(sig_name + 3)) <= 0 || EVP_PKEY_paramgen(ctx_params, &pkey_params) <= 0 || (sig_gen_ctx = EVP_PKEY_CTX_new(pkey_params, NULL)) == NULL || EVP_PKEY_keygen_init(sig_gen_ctx) <= 0) { BIO_printf(bio_err, "Error initializing classic keygen ctx for %s.\n", sig_name); goto sig_err_break; } } if (sig_gen_ctx == NULL) sig_gen_ctx = EVP_PKEY_CTX_new_from_name(app_get0_libctx(), use_params == 1 ? "RSA" : sig_name, app_get0_propq()); if (!sig_gen_ctx || EVP_PKEY_keygen_init(sig_gen_ctx) <= 0 || (use_params && EVP_PKEY_CTX_set_params(sig_gen_ctx, params) <= 0)) { BIO_printf(bio_err, "Error initializing keygen ctx for %s.\n", sig_name); goto sig_err_break; } if (EVP_PKEY_keygen(sig_gen_ctx, &pkey) <= 0) { BIO_printf(bio_err, "Error while generating signature EVP_PKEY for %s.\n", sig_name); goto sig_err_break; } /* Now prepare signature data structs */ sig_sign_ctx = EVP_PKEY_CTX_new_from_pkey(app_get0_libctx(), pkey, app_get0_propq()); if (sig_sign_ctx == NULL || EVP_PKEY_sign_init(sig_sign_ctx) <= 0 || (use_params == 1 && (EVP_PKEY_CTX_set_rsa_padding(sig_sign_ctx, RSA_PKCS1_PADDING) <= 0)) || EVP_PKEY_sign(sig_sign_ctx, NULL, &max_sig_len, md, md_len) <= 0) { BIO_printf(bio_err, "Error while initializing signing data structs for %s.\n", sig_name); goto sig_err_break; } sig = app_malloc(sig_len = max_sig_len, "signature buffer"); if (sig == NULL) { BIO_printf(bio_err, "MemAlloc error in sign for %s.\n", sig_name); goto sig_err_break; } if (EVP_PKEY_sign(sig_sign_ctx, sig, &sig_len, md, md_len) <= 0) { BIO_printf(bio_err, "Signing error for %s.\n", sig_name); goto sig_err_break; } /* Now prepare verify data structs */ memset(md, 0, SHA256_DIGEST_LENGTH); sig_verify_ctx = EVP_PKEY_CTX_new_from_pkey(app_get0_libctx(), pkey, app_get0_propq()); if (sig_verify_ctx == NULL || EVP_PKEY_verify_init(sig_verify_ctx) <= 0 || (use_params == 1 && (EVP_PKEY_CTX_set_rsa_padding(sig_verify_ctx, RSA_PKCS1_PADDING) <= 0))) { BIO_printf(bio_err, "Error while initializing verify data structs for %s.\n", sig_name); goto sig_err_break; } if (EVP_PKEY_verify(sig_verify_ctx, sig, sig_len, md, md_len) <= 0) { BIO_printf(bio_err, "Verify error for %s.\n", sig_name); goto sig_err_break; } if (EVP_PKEY_verify(sig_verify_ctx, sig, sig_len, md, md_len) <= 0) { BIO_printf(bio_err, "Verify 2 error for %s.\n", sig_name); goto sig_err_break; } loopargs[i].sig_gen_ctx[testnum] = sig_gen_ctx; loopargs[i].sig_sign_ctx[testnum] = sig_sign_ctx; loopargs[i].sig_verify_ctx[testnum] = sig_verify_ctx; loopargs[i].sig_max_sig_len[testnum] = max_sig_len; loopargs[i].sig_act_sig_len[testnum] = sig_len; loopargs[i].sig_sig[testnum] = sig; EVP_PKEY_free(pkey); pkey = NULL; continue; sig_err_break: ERR_print_errors(bio_err); EVP_PKEY_free(pkey); op_count = 1; sig_checks = 0; break; } if (sig_checks != 0) { kskey_print_message(sig_name, "keygen", seconds.sig); Time_F(START); count = run_benchmark(async_jobs, SIG_keygen_loop, loopargs); d = Time_F(STOP); BIO_printf(bio_err, mr ? "+R18:%ld:%s:%.2f\n" : "%ld %s signature keygen ops in %.2fs\n", count, sig_name, d); sigs_results[testnum][0] = (double)count / d; op_count = count; kskey_print_message(sig_name, "signs", seconds.sig); Time_F(START); count = run_benchmark(async_jobs, SIG_sign_loop, loopargs); d = Time_F(STOP); BIO_printf(bio_err, mr ? "+R19:%ld:%s:%.2f\n" : "%ld %s signature sign ops in %.2fs\n", count, sig_name, d); sigs_results[testnum][1] = (double)count / d; op_count = count; kskey_print_message(sig_name, "verify", seconds.sig); Time_F(START); count = run_benchmark(async_jobs, SIG_verify_loop, loopargs); d = Time_F(STOP); BIO_printf(bio_err, mr ? "+R20:%ld:%s:%.2f\n" : "%ld %s signature verify ops in %.2fs\n", count, sig_name, d); sigs_results[testnum][2] = (double)count / d; op_count = count; } if (op_count <= 1) stop_it(sigs_doit, testnum); } #ifndef NO_FORK show_res: #endif if (!mr) { printf("version: %s\n", OpenSSL_version(OPENSSL_FULL_VERSION_STRING)); printf("%s\n", OpenSSL_version(OPENSSL_BUILT_ON)); printf("options: %s\n", BN_options()); printf("%s\n", OpenSSL_version(OPENSSL_CFLAGS)); printf("%s\n", OpenSSL_version(OPENSSL_CPU_INFO)); } if (pr_header) { if (mr) { printf("+H"); } else { printf("The 'numbers' are in 1000s of bytes per second processed.\n"); printf("type "); } for (testnum = 0; testnum < size_num; testnum++) printf(mr ? ":%d" : "%7d bytes", lengths[testnum]); printf("\n"); } for (k = 0; k < ALGOR_NUM; k++) { const char *alg_name = names[k]; if (!doit[k]) continue; if (k == D_EVP) { if (evp_cipher == NULL) alg_name = evp_md_name; else if ((alg_name = EVP_CIPHER_get0_name(evp_cipher)) == NULL) app_bail_out("failed to get name of cipher '%s'\n", evp_cipher); } if (mr) printf("+F:%u:%s", k, alg_name); else printf("%-13s", alg_name); for (testnum = 0; testnum < size_num; testnum++) { if (results[k][testnum] > 10000 && !mr) printf(" %11.2fk", results[k][testnum] / 1e3); else printf(mr ? ":%.2f" : " %11.2f ", results[k][testnum]); } printf("\n"); } testnum = 1; for (k = 0; k < RSA_NUM; k++) { if (!rsa_doit[k]) continue; if (testnum && !mr) { printf("%19ssign verify encrypt decrypt sign/s verify/s encr./s decr./s\n", " "); testnum = 0; } if (mr) printf("+F2:%u:%u:%f:%f:%f:%f\n", k, rsa_keys[k].bits, rsa_results[k][0], rsa_results[k][1], rsa_results[k][2], rsa_results[k][3]); else printf("rsa %5u bits %8.6fs %8.6fs %8.6fs %8.6fs %8.1f %8.1f %8.1f %8.1f\n", rsa_keys[k].bits, 1.0 / rsa_results[k][0], 1.0 / rsa_results[k][1], 1.0 / rsa_results[k][2], 1.0 / rsa_results[k][3], rsa_results[k][0], rsa_results[k][1], rsa_results[k][2], rsa_results[k][3]); } testnum = 1; for (k = 0; k < DSA_NUM; k++) { if (!dsa_doit[k]) continue; if (testnum && !mr) { printf("%18ssign verify sign/s verify/s\n", " "); testnum = 0; } if (mr) printf("+F3:%u:%u:%f:%f\n", k, dsa_bits[k], dsa_results[k][0], dsa_results[k][1]); else printf("dsa %4u bits %8.6fs %8.6fs %8.1f %8.1f\n", dsa_bits[k], 1.0 / dsa_results[k][0], 1.0 / dsa_results[k][1], dsa_results[k][0], dsa_results[k][1]); } testnum = 1; for (k = 0; k < OSSL_NELEM(ecdsa_doit); k++) { if (!ecdsa_doit[k]) continue; if (testnum && !mr) { printf("%30ssign verify sign/s verify/s\n", " "); testnum = 0; } if (mr) printf("+F4:%u:%u:%f:%f\n", k, ec_curves[k].bits, ecdsa_results[k][0], ecdsa_results[k][1]); else printf("%4u bits ecdsa (%s) %8.4fs %8.4fs %8.1f %8.1f\n", ec_curves[k].bits, ec_curves[k].name, 1.0 / ecdsa_results[k][0], 1.0 / ecdsa_results[k][1], ecdsa_results[k][0], ecdsa_results[k][1]); } testnum = 1; for (k = 0; k < EC_NUM; k++) { if (!ecdh_doit[k]) continue; if (testnum && !mr) { printf("%30sop op/s\n", " "); testnum = 0; } if (mr) printf("+F5:%u:%u:%f:%f\n", k, ec_curves[k].bits, ecdh_results[k][0], 1.0 / ecdh_results[k][0]); else printf("%4u bits ecdh (%s) %8.4fs %8.1f\n", ec_curves[k].bits, ec_curves[k].name, 1.0 / ecdh_results[k][0], ecdh_results[k][0]); } #ifndef OPENSSL_NO_ECX testnum = 1; for (k = 0; k < OSSL_NELEM(eddsa_doit); k++) { if (!eddsa_doit[k]) continue; if (testnum && !mr) { printf("%30ssign verify sign/s verify/s\n", " "); testnum = 0; } if (mr) printf("+F6:%u:%u:%s:%f:%f\n", k, ed_curves[k].bits, ed_curves[k].name, eddsa_results[k][0], eddsa_results[k][1]); else printf("%4u bits EdDSA (%s) %8.4fs %8.4fs %8.1f %8.1f\n", ed_curves[k].bits, ed_curves[k].name, 1.0 / eddsa_results[k][0], 1.0 / eddsa_results[k][1], eddsa_results[k][0], eddsa_results[k][1]); } #endif /* OPENSSL_NO_ECX */ #ifndef OPENSSL_NO_SM2 testnum = 1; for (k = 0; k < OSSL_NELEM(sm2_doit); k++) { if (!sm2_doit[k]) continue; if (testnum && !mr) { printf("%30ssign verify sign/s verify/s\n", " "); testnum = 0; } if (mr) printf("+F7:%u:%u:%s:%f:%f\n", k, sm2_curves[k].bits, sm2_curves[k].name, sm2_results[k][0], sm2_results[k][1]); else printf("%4u bits SM2 (%s) %8.4fs %8.4fs %8.1f %8.1f\n", sm2_curves[k].bits, sm2_curves[k].name, 1.0 / sm2_results[k][0], 1.0 / sm2_results[k][1], sm2_results[k][0], sm2_results[k][1]); } #endif #ifndef OPENSSL_NO_DH testnum = 1; for (k = 0; k < FFDH_NUM; k++) { if (!ffdh_doit[k]) continue; if (testnum && !mr) { printf("%23sop op/s\n", " "); testnum = 0; } if (mr) printf("+F8:%u:%u:%f:%f\n", k, ffdh_params[k].bits, ffdh_results[k][0], 1.0 / ffdh_results[k][0]); else printf("%4u bits ffdh %8.4fs %8.1f\n", ffdh_params[k].bits, 1.0 / ffdh_results[k][0], ffdh_results[k][0]); } #endif /* OPENSSL_NO_DH */ testnum = 1; for (k = 0; k < kems_algs_len; k++) { const char *kem_name = kems_algname[k]; if (!kems_doit[k] || !do_kems) continue; if (testnum && !mr) { printf("%31skeygen encaps decaps keygens/s encaps/s decaps/s\n", " "); testnum = 0; } if (mr) printf("+F9:%u:%f:%f:%f\n", k, kems_results[k][0], kems_results[k][1], kems_results[k][2]); else printf("%27s %8.6fs %8.6fs %8.6fs %9.1f %9.1f %9.1f\n", kem_name, 1.0 / kems_results[k][0], 1.0 / kems_results[k][1], 1.0 / kems_results[k][2], kems_results[k][0], kems_results[k][1], kems_results[k][2]); } ret = 0; testnum = 1; for (k = 0; k < sigs_algs_len; k++) { const char *sig_name = sigs_algname[k]; if (!sigs_doit[k] || !do_sigs) continue; if (testnum && !mr) { printf("%31skeygen signs verify keygens/s sign/s verify/s\n", " "); testnum = 0; } if (mr) printf("+F10:%u:%f:%f:%f\n", k, sigs_results[k][0], sigs_results[k][1], sigs_results[k][2]); else printf("%27s %8.6fs %8.6fs %8.6fs %9.1f %9.1f %9.1f\n", sig_name, 1.0 / sigs_results[k][0], 1.0 / sigs_results[k][1], 1.0 / sigs_results[k][2], sigs_results[k][0], sigs_results[k][1], sigs_results[k][2]); } ret = 0; end: ERR_print_errors(bio_err); for (i = 0; i < loopargs_len; i++) { OPENSSL_free(loopargs[i].buf_malloc); OPENSSL_free(loopargs[i].buf2_malloc); BN_free(bn); EVP_PKEY_CTX_free(genctx); for (k = 0; k < RSA_NUM; k++) { EVP_PKEY_CTX_free(loopargs[i].rsa_sign_ctx[k]); EVP_PKEY_CTX_free(loopargs[i].rsa_verify_ctx[k]); EVP_PKEY_CTX_free(loopargs[i].rsa_encrypt_ctx[k]); EVP_PKEY_CTX_free(loopargs[i].rsa_decrypt_ctx[k]); } #ifndef OPENSSL_NO_DH OPENSSL_free(loopargs[i].secret_ff_a); OPENSSL_free(loopargs[i].secret_ff_b); for (k = 0; k < FFDH_NUM; k++) EVP_PKEY_CTX_free(loopargs[i].ffdh_ctx[k]); #endif for (k = 0; k < DSA_NUM; k++) { EVP_PKEY_CTX_free(loopargs[i].dsa_sign_ctx[k]); EVP_PKEY_CTX_free(loopargs[i].dsa_verify_ctx[k]); } for (k = 0; k < ECDSA_NUM; k++) { EVP_PKEY_CTX_free(loopargs[i].ecdsa_sign_ctx[k]); EVP_PKEY_CTX_free(loopargs[i].ecdsa_verify_ctx[k]); } for (k = 0; k < EC_NUM; k++) EVP_PKEY_CTX_free(loopargs[i].ecdh_ctx[k]); #ifndef OPENSSL_NO_ECX for (k = 0; k < EdDSA_NUM; k++) { EVP_MD_CTX_free(loopargs[i].eddsa_ctx[k]); EVP_MD_CTX_free(loopargs[i].eddsa_ctx2[k]); } #endif /* OPENSSL_NO_ECX */ #ifndef OPENSSL_NO_SM2 for (k = 0; k < SM2_NUM; k++) { EVP_PKEY_CTX *pctx = NULL; /* free signing ctx */ if (loopargs[i].sm2_ctx[k] != NULL && (pctx = EVP_MD_CTX_get_pkey_ctx(loopargs[i].sm2_ctx[k])) != NULL) EVP_PKEY_CTX_free(pctx); EVP_MD_CTX_free(loopargs[i].sm2_ctx[k]); /* free verification ctx */ if (loopargs[i].sm2_vfy_ctx[k] != NULL && (pctx = EVP_MD_CTX_get_pkey_ctx(loopargs[i].sm2_vfy_ctx[k])) != NULL) EVP_PKEY_CTX_free(pctx); EVP_MD_CTX_free(loopargs[i].sm2_vfy_ctx[k]); /* free pkey */ EVP_PKEY_free(loopargs[i].sm2_pkey[k]); } #endif for (k = 0; k < kems_algs_len; k++) { EVP_PKEY_CTX_free(loopargs[i].kem_gen_ctx[k]); EVP_PKEY_CTX_free(loopargs[i].kem_encaps_ctx[k]); EVP_PKEY_CTX_free(loopargs[i].kem_decaps_ctx[k]); OPENSSL_free(loopargs[i].kem_out[k]); OPENSSL_free(loopargs[i].kem_send_secret[k]); OPENSSL_free(loopargs[i].kem_rcv_secret[k]); } for (k = 0; k < sigs_algs_len; k++) { EVP_PKEY_CTX_free(loopargs[i].sig_gen_ctx[k]); EVP_PKEY_CTX_free(loopargs[i].sig_sign_ctx[k]); EVP_PKEY_CTX_free(loopargs[i].sig_verify_ctx[k]); OPENSSL_free(loopargs[i].sig_sig[k]); } OPENSSL_free(loopargs[i].secret_a); OPENSSL_free(loopargs[i].secret_b); } OPENSSL_free(evp_hmac_name); OPENSSL_free(evp_cmac_name); for (k = 0; k < kems_algs_len; k++) OPENSSL_free(kems_algname[k]); if (kem_stack != NULL) sk_EVP_KEM_pop_free(kem_stack, EVP_KEM_free); for (k = 0; k < sigs_algs_len; k++) OPENSSL_free(sigs_algname[k]); if (sig_stack != NULL) sk_EVP_SIGNATURE_pop_free(sig_stack, EVP_SIGNATURE_free); if (async_jobs > 0) { for (i = 0; i < loopargs_len; i++) ASYNC_WAIT_CTX_free(loopargs[i].wait_ctx); } if (async_init) { ASYNC_cleanup_thread(); } OPENSSL_free(loopargs); release_engine(e); EVP_CIPHER_free(evp_cipher); EVP_MAC_free(mac); NCONF_free(conf); return ret; } static void print_message(const char *s, int length, int tm) { BIO_printf(bio_err, mr ? "+DT:%s:%d:%d\n" : "Doing %s ops for %ds on %d size blocks: ", s, tm, length); (void)BIO_flush(bio_err); run = 1; alarm(tm); } static void pkey_print_message(const char *str, const char *str2, unsigned int bits, int tm) { BIO_printf(bio_err, mr ? "+DTP:%d:%s:%s:%d\n" : "Doing %u bits %s %s ops for %ds: ", bits, str, str2, tm); (void)BIO_flush(bio_err); run = 1; alarm(tm); } static void kskey_print_message(const char *str, const char *str2, int tm) { BIO_printf(bio_err, mr ? "+DTP:%s:%s:%d\n" : "Doing %s %s ops for %ds: ", str, str2, tm); (void)BIO_flush(bio_err); run = 1; alarm(tm); } static void print_result(int alg, int run_no, int count, double time_used) { if (count == -1) { BIO_printf(bio_err, "%s error!\n", names[alg]); ERR_print_errors(bio_err); return; } BIO_printf(bio_err, mr ? "+R:%d:%s:%f\n" : "%d %s ops in %.2fs\n", count, names[alg], time_used); results[alg][run_no] = ((double)count) / time_used * lengths[run_no]; } #ifndef NO_FORK static char *sstrsep(char **string, const char *delim) { char isdelim[256]; char *token = *string; memset(isdelim, 0, sizeof(isdelim)); isdelim[0] = 1; while (*delim) { isdelim[(unsigned char)(*delim)] = 1; delim++; } while (!isdelim[(unsigned char)(**string)]) (*string)++; if (**string) { **string = 0; (*string)++; } return token; } static int strtoint(const char *str, const int min_val, const int upper_val, int *res) { char *end = NULL; long int val = 0; errno = 0; val = strtol(str, &end, 10); if (errno == 0 && end != str && *end == 0 && min_val <= val && val < upper_val) { *res = (int)val; return 1; } else { return 0; } } static int do_multi(int multi, int size_num) { int n; int fd[2]; int *fds; int status; static char sep[] = ":"; fds = app_malloc(sizeof(*fds) * multi, "fd buffer for do_multi"); for (n = 0; n < multi; ++n) { if (pipe(fd) == -1) { BIO_printf(bio_err, "pipe failure\n"); exit(1); } fflush(stdout); (void)BIO_flush(bio_err); if (fork()) { close(fd[1]); fds[n] = fd[0]; } else { close(fd[0]); close(1); if (dup(fd[1]) == -1) { BIO_printf(bio_err, "dup failed\n"); exit(1); } close(fd[1]); mr = 1; usertime = 0; OPENSSL_free(fds); return 0; } printf("Forked child %d\n", n); } /* for now, assume the pipe is long enough to take all the output */ for (n = 0; n < multi; ++n) { FILE *f; char buf[1024]; char *p; char *tk; int k; double d; if ((f = fdopen(fds[n], "r")) == NULL) { BIO_printf(bio_err, "fdopen failure with 0x%x\n", errno); OPENSSL_free(fds); return 1; } while (fgets(buf, sizeof(buf), f)) { p = strchr(buf, '\n'); if (p) *p = '\0'; if (buf[0] != '+') { BIO_printf(bio_err, "Don't understand line '%s' from child %d\n", buf, n); continue; } printf("Got: %s from %d\n", buf, n); p = buf; if (CHECK_AND_SKIP_PREFIX(p, "+F:")) { int alg; int j; if (strtoint(sstrsep(&p, sep), 0, ALGOR_NUM, &alg)) { sstrsep(&p, sep); for (j = 0; j < size_num; ++j) results[alg][j] += atof(sstrsep(&p, sep)); } } else if (CHECK_AND_SKIP_PREFIX(p, "+F2:")) { tk = sstrsep(&p, sep); if (strtoint(tk, 0, OSSL_NELEM(rsa_results), &k)) { sstrsep(&p, sep); d = atof(sstrsep(&p, sep)); rsa_results[k][0] += d; d = atof(sstrsep(&p, sep)); rsa_results[k][1] += d; d = atof(sstrsep(&p, sep)); rsa_results[k][2] += d; d = atof(sstrsep(&p, sep)); rsa_results[k][3] += d; } } else if (CHECK_AND_SKIP_PREFIX(p, "+F3:")) { tk = sstrsep(&p, sep); if (strtoint(tk, 0, OSSL_NELEM(dsa_results), &k)) { sstrsep(&p, sep); d = atof(sstrsep(&p, sep)); dsa_results[k][0] += d; d = atof(sstrsep(&p, sep)); dsa_results[k][1] += d; } } else if (CHECK_AND_SKIP_PREFIX(p, "+F4:")) { tk = sstrsep(&p, sep); if (strtoint(tk, 0, OSSL_NELEM(ecdsa_results), &k)) { sstrsep(&p, sep); d = atof(sstrsep(&p, sep)); ecdsa_results[k][0] += d; d = atof(sstrsep(&p, sep)); ecdsa_results[k][1] += d; } } else if (CHECK_AND_SKIP_PREFIX(p, "+F5:")) { tk = sstrsep(&p, sep); if (strtoint(tk, 0, OSSL_NELEM(ecdh_results), &k)) { sstrsep(&p, sep); d = atof(sstrsep(&p, sep)); ecdh_results[k][0] += d; } # ifndef OPENSSL_NO_ECX } else if (CHECK_AND_SKIP_PREFIX(p, "+F6:")) { tk = sstrsep(&p, sep); if (strtoint(tk, 0, OSSL_NELEM(eddsa_results), &k)) { sstrsep(&p, sep); sstrsep(&p, sep); d = atof(sstrsep(&p, sep)); eddsa_results[k][0] += d; d = atof(sstrsep(&p, sep)); eddsa_results[k][1] += d; } # endif /* OPENSSL_NO_ECX */ # ifndef OPENSSL_NO_SM2 } else if (CHECK_AND_SKIP_PREFIX(p, "+F7:")) { tk = sstrsep(&p, sep); if (strtoint(tk, 0, OSSL_NELEM(sm2_results), &k)) { sstrsep(&p, sep); sstrsep(&p, sep); d = atof(sstrsep(&p, sep)); sm2_results[k][0] += d; d = atof(sstrsep(&p, sep)); sm2_results[k][1] += d; } # endif /* OPENSSL_NO_SM2 */ # ifndef OPENSSL_NO_DH } else if (CHECK_AND_SKIP_PREFIX(p, "+F8:")) { tk = sstrsep(&p, sep); if (strtoint(tk, 0, OSSL_NELEM(ffdh_results), &k)) { sstrsep(&p, sep); d = atof(sstrsep(&p, sep)); ffdh_results[k][0] += d; } # endif /* OPENSSL_NO_DH */ } else if (CHECK_AND_SKIP_PREFIX(p, "+F9:")) { tk = sstrsep(&p, sep); if (strtoint(tk, 0, OSSL_NELEM(kems_results), &k)) { d = atof(sstrsep(&p, sep)); kems_results[k][0] += d; d = atof(sstrsep(&p, sep)); kems_results[k][1] += d; d = atof(sstrsep(&p, sep)); kems_results[k][2] += d; } } else if (CHECK_AND_SKIP_PREFIX(p, "+F10:")) { tk = sstrsep(&p, sep); if (strtoint(tk, 0, OSSL_NELEM(sigs_results), &k)) { d = atof(sstrsep(&p, sep)); sigs_results[k][0] += d; d = atof(sstrsep(&p, sep)); sigs_results[k][1] += d; d = atof(sstrsep(&p, sep)); sigs_results[k][2] += d; } } else if (!HAS_PREFIX(buf, "+H:")) { BIO_printf(bio_err, "Unknown type '%s' from child %d\n", buf, n); } } fclose(f); } OPENSSL_free(fds); for (n = 0; n < multi; ++n) { while (wait(&status) == -1) if (errno != EINTR) { BIO_printf(bio_err, "Waitng for child failed with 0x%x\n", errno); return 1; } if (WIFEXITED(status) && WEXITSTATUS(status)) { BIO_printf(bio_err, "Child exited with %d\n", WEXITSTATUS(status)); } else if (WIFSIGNALED(status)) { BIO_printf(bio_err, "Child terminated by signal %d\n", WTERMSIG(status)); } } return 1; } #endif static void multiblock_speed(const EVP_CIPHER *evp_cipher, int lengths_single, const openssl_speed_sec_t *seconds) { static const int mblengths_list[] = { 8 * 1024, 2 * 8 * 1024, 4 * 8 * 1024, 8 * 8 * 1024, 8 * 16 * 1024 }; const int *mblengths = mblengths_list; int j, count, keylen, num = OSSL_NELEM(mblengths_list), ciph_success = 1; const char *alg_name; unsigned char *inp = NULL, *out = NULL, *key, no_key[32], no_iv[16]; EVP_CIPHER_CTX *ctx = NULL; double d = 0.0; if (lengths_single) { mblengths = &lengths_single; num = 1; } inp = app_malloc(mblengths[num - 1], "multiblock input buffer"); out = app_malloc(mblengths[num - 1] + 1024, "multiblock output buffer"); if ((ctx = EVP_CIPHER_CTX_new()) == NULL) app_bail_out("failed to allocate cipher context\n"); if (!EVP_EncryptInit_ex(ctx, evp_cipher, NULL, NULL, no_iv)) app_bail_out("failed to initialise cipher context\n"); if ((keylen = EVP_CIPHER_CTX_get_key_length(ctx)) < 0) { BIO_printf(bio_err, "Impossible negative key length: %d\n", keylen); goto err; } key = app_malloc(keylen, "evp_cipher key"); if (EVP_CIPHER_CTX_rand_key(ctx, key) <= 0) app_bail_out("failed to generate random cipher key\n"); if (!EVP_EncryptInit_ex(ctx, NULL, NULL, key, NULL)) app_bail_out("failed to set cipher key\n"); OPENSSL_clear_free(key, keylen); if (EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_SET_MAC_KEY, sizeof(no_key), no_key) <= 0) app_bail_out("failed to set AEAD key\n"); if ((alg_name = EVP_CIPHER_get0_name(evp_cipher)) == NULL) app_bail_out("failed to get cipher name\n"); for (j = 0; j < num; j++) { print_message(alg_name, mblengths[j], seconds->sym); Time_F(START); for (count = 0; run && count < INT_MAX; count++) { unsigned char aad[EVP_AEAD_TLS1_AAD_LEN]; EVP_CTRL_TLS1_1_MULTIBLOCK_PARAM mb_param; size_t len = mblengths[j]; int packlen; memset(aad, 0, 8); /* avoid uninitialized values */ aad[8] = 23; /* SSL3_RT_APPLICATION_DATA */ aad[9] = 3; /* version */ aad[10] = 2; aad[11] = 0; /* length */ aad[12] = 0; mb_param.out = NULL; mb_param.inp = aad; mb_param.len = len; mb_param.interleave = 8; packlen = EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_TLS1_1_MULTIBLOCK_AAD, sizeof(mb_param), &mb_param); if (packlen > 0) { mb_param.out = out; mb_param.inp = inp; mb_param.len = len; (void)EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_TLS1_1_MULTIBLOCK_ENCRYPT, sizeof(mb_param), &mb_param); } else { int pad; if (RAND_bytes(inp, 16) <= 0) app_bail_out("error setting random bytes\n"); len += 16; aad[11] = (unsigned char)(len >> 8); aad[12] = (unsigned char)(len); pad = EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_TLS1_AAD, EVP_AEAD_TLS1_AAD_LEN, aad); ciph_success = EVP_Cipher(ctx, out, inp, len + pad); } } d = Time_F(STOP); BIO_printf(bio_err, mr ? "+R:%d:%s:%f\n" : "%d %s ops in %.2fs\n", count, "evp", d); if ((ciph_success <= 0) && (mr == 0)) BIO_printf(bio_err, "Error performing cipher op\n"); results[D_EVP][j] = ((double)count) / d * mblengths[j]; } if (mr) { fprintf(stdout, "+H"); for (j = 0; j < num; j++) fprintf(stdout, ":%d", mblengths[j]); fprintf(stdout, "\n"); fprintf(stdout, "+F:%d:%s", D_EVP, alg_name); for (j = 0; j < num; j++) fprintf(stdout, ":%.2f", results[D_EVP][j]); fprintf(stdout, "\n"); } else { fprintf(stdout, "The 'numbers' are in 1000s of bytes per second processed.\n"); fprintf(stdout, "type "); for (j = 0; j < num; j++) fprintf(stdout, "%7d bytes", mblengths[j]); fprintf(stdout, "\n"); fprintf(stdout, "%-24s", alg_name); for (j = 0; j < num; j++) { if (results[D_EVP][j] > 10000) fprintf(stdout, " %11.2fk", results[D_EVP][j] / 1e3); else fprintf(stdout, " %11.2f ", results[D_EVP][j]); } fprintf(stdout, "\n"); } err: OPENSSL_free(inp); OPENSSL_free(out); EVP_CIPHER_CTX_free(ctx); }
./openssl/apps/s_time.c
/* * Copyright 1995-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 <stdlib.h> #include <string.h> #include <openssl/opensslconf.h> #ifndef OPENSSL_NO_SOCK #include "apps.h" #include "progs.h" #include <openssl/x509.h> #include <openssl/ssl.h> #include <openssl/pem.h> #include "s_apps.h" #include <openssl/err.h> #include "internal/sockets.h" #if !defined(OPENSSL_SYS_MSDOS) # include <unistd.h> #endif #define SSL_CONNECT_NAME "localhost:4433" #define SECONDS 30 #define SECONDSSTR "30" static SSL *doConnection(SSL *scon, const char *host, SSL_CTX *ctx); /* * Define a HTTP get command globally. * Also define the size of the command, this is two bytes less than * the size of the string because the %s is replaced by the URL. */ static const char fmt_http_get_cmd[] = "GET %s HTTP/1.0\r\n\r\n"; static const size_t fmt_http_get_cmd_size = sizeof(fmt_http_get_cmd) - 2; typedef enum OPTION_choice { OPT_COMMON, OPT_CONNECT, OPT_CIPHER, OPT_CIPHERSUITES, OPT_CERT, OPT_NAMEOPT, OPT_KEY, OPT_CAPATH, OPT_CAFILE, OPT_CASTORE, OPT_NOCAPATH, OPT_NOCAFILE, OPT_NOCASTORE, OPT_NEW, OPT_REUSE, OPT_BUGS, OPT_VERIFY, OPT_TIME, OPT_SSL3, OPT_WWW, OPT_TLS1, OPT_TLS1_1, OPT_TLS1_2, OPT_TLS1_3, OPT_PROV_ENUM } OPTION_CHOICE; const OPTIONS s_time_options[] = { OPT_SECTION("General"), {"help", OPT_HELP, '-', "Display this summary"}, OPT_SECTION("Connection"), {"connect", OPT_CONNECT, 's', "Where to connect as post:port (default is " SSL_CONNECT_NAME ")"}, {"new", OPT_NEW, '-', "Just time new connections"}, {"reuse", OPT_REUSE, '-', "Just time connection reuse"}, {"bugs", OPT_BUGS, '-', "Turn on SSL bug compatibility"}, {"cipher", OPT_CIPHER, 's', "TLSv1.2 and below cipher list to be used"}, {"ciphersuites", OPT_CIPHERSUITES, 's', "Specify TLSv1.3 ciphersuites to be used"}, #ifndef OPENSSL_NO_SSL3 {"ssl3", OPT_SSL3, '-', "Just use SSLv3"}, #endif #ifndef OPENSSL_NO_TLS1 {"tls1", OPT_TLS1, '-', "Just use TLSv1.0"}, #endif #ifndef OPENSSL_NO_TLS1_1 {"tls1_1", OPT_TLS1_1, '-', "Just use TLSv1.1"}, #endif #ifndef OPENSSL_NO_TLS1_2 {"tls1_2", OPT_TLS1_2, '-', "Just use TLSv1.2"}, #endif #ifndef OPENSSL_NO_TLS1_3 {"tls1_3", OPT_TLS1_3, '-', "Just use TLSv1.3"}, #endif {"verify", OPT_VERIFY, 'p', "Turn on peer certificate verification, set depth"}, {"time", OPT_TIME, 'p', "Seconds to collect data, default " SECONDSSTR}, {"www", OPT_WWW, 's', "Fetch specified page from the site"}, OPT_SECTION("Certificate"), {"nameopt", OPT_NAMEOPT, 's', "Certificate subject/issuer name printing options"}, {"cert", OPT_CERT, '<', "Cert file to use, PEM format assumed"}, {"key", OPT_KEY, '<', "File with key, PEM; default is -cert file"}, {"cafile", OPT_CAFILE, '<', "PEM format file of CA's"}, {"CAfile", OPT_CAFILE, '<', "PEM format file of CA's"}, {"CApath", OPT_CAPATH, '/', "PEM format directory of CA's"}, {"CAstore", OPT_CASTORE, ':', "URI to store of CA's"}, {"no-CAfile", OPT_NOCAFILE, '-', "Do not load the default certificates file"}, {"no-CApath", OPT_NOCAPATH, '-', "Do not load certificates from the default certificates directory"}, {"no-CAstore", OPT_NOCASTORE, '-', "Do not load certificates from the default certificates store URI"}, OPT_PROV_OPTIONS, {NULL} }; #define START 0 #define STOP 1 static double tm_Time_F(int s) { return app_tminterval(s, 1); } int s_time_main(int argc, char **argv) { char buf[1024 * 8]; SSL *scon = NULL; SSL_CTX *ctx = NULL; const SSL_METHOD *meth = NULL; char *CApath = NULL, *CAfile = NULL, *CAstore = NULL; char *cipher = NULL, *ciphersuites = NULL; char *www_path = NULL; char *host = SSL_CONNECT_NAME, *certfile = NULL, *keyfile = NULL, *prog; double totalTime = 0.0; int noCApath = 0, noCAfile = 0, noCAstore = 0; int maxtime = SECONDS, nConn = 0, perform = 3, ret = 1, i, st_bugs = 0; long bytes_read = 0, finishtime = 0; OPTION_CHOICE o; int min_version = 0, max_version = 0, ver, buf_len, fd; size_t buf_size; meth = TLS_client_method(); prog = opt_init(argc, argv, s_time_options); while ((o = opt_next()) != OPT_EOF) { switch (o) { case OPT_EOF: case OPT_ERR: opthelp: BIO_printf(bio_err, "%s: Use -help for summary.\n", prog); goto end; case OPT_HELP: opt_help(s_time_options); ret = 0; goto end; case OPT_CONNECT: host = opt_arg(); break; case OPT_REUSE: perform = 2; break; case OPT_NEW: perform = 1; break; case OPT_VERIFY: verify_args.depth = opt_int_arg(); BIO_printf(bio_err, "%s: verify depth is %d\n", prog, verify_args.depth); break; case OPT_CERT: certfile = opt_arg(); break; case OPT_NAMEOPT: if (!set_nameopt(opt_arg())) goto end; break; case OPT_KEY: keyfile = opt_arg(); break; case OPT_CAPATH: CApath = opt_arg(); break; case OPT_CAFILE: CAfile = opt_arg(); break; case OPT_NOCAPATH: noCApath = 1; break; case OPT_NOCAFILE: noCAfile = 1; break; case OPT_CASTORE: CAstore = opt_arg(); break; case OPT_NOCASTORE: noCAstore = 1; break; case OPT_CIPHER: cipher = opt_arg(); break; case OPT_CIPHERSUITES: ciphersuites = opt_arg(); break; case OPT_BUGS: st_bugs = 1; break; case OPT_TIME: maxtime = opt_int_arg(); break; case OPT_WWW: www_path = opt_arg(); buf_size = strlen(www_path) + fmt_http_get_cmd_size; if (buf_size > sizeof(buf)) { BIO_printf(bio_err, "%s: -www option is too long\n", prog); goto end; } break; case OPT_SSL3: min_version = SSL3_VERSION; max_version = SSL3_VERSION; break; case OPT_TLS1: min_version = TLS1_VERSION; max_version = TLS1_VERSION; break; case OPT_TLS1_1: min_version = TLS1_1_VERSION; max_version = TLS1_1_VERSION; break; case OPT_TLS1_2: min_version = TLS1_2_VERSION; max_version = TLS1_2_VERSION; break; case OPT_TLS1_3: min_version = TLS1_3_VERSION; max_version = TLS1_3_VERSION; break; case OPT_PROV_CASES: if (!opt_provider(o)) goto end; break; } } /* No extra arguments. */ if (!opt_check_rest_arg(NULL)) goto opthelp; if (cipher == NULL) cipher = getenv("SSL_CIPHER"); if ((ctx = SSL_CTX_new(meth)) == NULL) goto end; SSL_CTX_set_quiet_shutdown(ctx, 1); if (SSL_CTX_set_min_proto_version(ctx, min_version) == 0) goto end; if (SSL_CTX_set_max_proto_version(ctx, max_version) == 0) goto end; if (st_bugs) SSL_CTX_set_options(ctx, SSL_OP_ALL); if (cipher != NULL && !SSL_CTX_set_cipher_list(ctx, cipher)) goto end; if (ciphersuites != NULL && !SSL_CTX_set_ciphersuites(ctx, ciphersuites)) goto end; if (!set_cert_stuff(ctx, certfile, keyfile)) goto end; if (!ctx_set_verify_locations(ctx, CAfile, noCAfile, CApath, noCApath, CAstore, noCAstore)) { ERR_print_errors(bio_err); goto end; } if (!(perform & 1)) goto next; printf("Collecting connection statistics for %d seconds\n", maxtime); /* Loop and time how long it takes to make connections */ bytes_read = 0; finishtime = (long)time(NULL) + maxtime; tm_Time_F(START); for (;;) { if (finishtime < (long)time(NULL)) break; if ((scon = doConnection(NULL, host, ctx)) == NULL) goto end; if (www_path != NULL) { buf_len = BIO_snprintf(buf, sizeof(buf), fmt_http_get_cmd, www_path); if (buf_len <= 0 || SSL_write(scon, buf, buf_len) <= 0) goto end; while ((i = SSL_read(scon, buf, sizeof(buf))) > 0) bytes_read += i; } SSL_set_shutdown(scon, SSL_SENT_SHUTDOWN | SSL_RECEIVED_SHUTDOWN); BIO_closesocket(SSL_get_fd(scon)); nConn += 1; if (SSL_session_reused(scon)) { ver = 'r'; } else { ver = SSL_version(scon); if (ver == TLS1_VERSION) ver = 't'; else if (ver == SSL3_VERSION) ver = '3'; else ver = '*'; } fputc(ver, stdout); fflush(stdout); SSL_free(scon); scon = NULL; } totalTime += tm_Time_F(STOP); /* Add the time for this iteration */ printf ("\n\n%d connections in %.2fs; %.2f connections/user sec, bytes read %ld\n", nConn, totalTime, ((double)nConn / totalTime), bytes_read); printf ("%d connections in %ld real seconds, %ld bytes read per connection\n", nConn, (long)time(NULL) - finishtime + maxtime, nConn > 0 ? bytes_read / nConn : 0l); /* * Now loop and time connections using the same session id over and over */ next: if (!(perform & 2)) goto end; printf("\n\nNow timing with session id reuse.\n"); /* Get an SSL object so we can reuse the session id */ if ((scon = doConnection(NULL, host, ctx)) == NULL) { BIO_printf(bio_err, "Unable to get connection\n"); goto end; } if (www_path != NULL) { buf_len = BIO_snprintf(buf, sizeof(buf), fmt_http_get_cmd, www_path); if (buf_len <= 0 || SSL_write(scon, buf, buf_len) <= 0) goto end; while (SSL_read(scon, buf, sizeof(buf)) > 0) continue; } SSL_set_shutdown(scon, SSL_SENT_SHUTDOWN | SSL_RECEIVED_SHUTDOWN); if ((fd = SSL_get_fd(scon)) >= 0) BIO_closesocket(fd); nConn = 0; totalTime = 0.0; finishtime = (long)time(NULL) + maxtime; printf("starting\n"); bytes_read = 0; tm_Time_F(START); for (;;) { if (finishtime < (long)time(NULL)) break; if ((doConnection(scon, host, ctx)) == NULL) goto end; if (www_path != NULL) { buf_len = BIO_snprintf(buf, sizeof(buf), fmt_http_get_cmd, www_path); if (buf_len <= 0 || SSL_write(scon, buf, buf_len) <= 0) goto end; while ((i = SSL_read(scon, buf, sizeof(buf))) > 0) bytes_read += i; } SSL_set_shutdown(scon, SSL_SENT_SHUTDOWN | SSL_RECEIVED_SHUTDOWN); if ((fd = SSL_get_fd(scon)) >= 0) BIO_closesocket(fd); nConn += 1; if (SSL_session_reused(scon)) { ver = 'r'; } else { ver = SSL_version(scon); if (ver == TLS1_VERSION) ver = 't'; else if (ver == SSL3_VERSION) ver = '3'; else ver = '*'; } fputc(ver, stdout); fflush(stdout); } totalTime += tm_Time_F(STOP); /* Add the time for this iteration */ printf ("\n\n%d connections in %.2fs; %.2f connections/user sec, bytes read %ld\n", nConn, totalTime, ((double)nConn / totalTime), bytes_read); if (nConn > 0) printf ("%d connections in %ld real seconds, %ld bytes read per connection\n", nConn, (long)time(NULL) - finishtime + maxtime, bytes_read / nConn); else printf("0 connections in %ld real seconds\n", (long)time(NULL) - finishtime + maxtime); ret = 0; end: SSL_free(scon); SSL_CTX_free(ctx); return ret; } /*- * doConnection - make a connection */ static SSL *doConnection(SSL *scon, const char *host, SSL_CTX *ctx) { BIO *conn; SSL *serverCon; int i; if ((conn = BIO_new(BIO_s_connect())) == NULL) return NULL; if (BIO_set_conn_hostname(conn, host) <= 0 || BIO_set_conn_mode(conn, BIO_SOCK_NODELAY) <= 0) { BIO_free(conn); return NULL; } if (scon == NULL) { serverCon = SSL_new(ctx); if (serverCon == NULL) { BIO_free(conn); return NULL; } } else { serverCon = scon; SSL_set_connect_state(serverCon); } SSL_set_bio(serverCon, conn, conn); /* ok, lets connect */ i = SSL_connect(serverCon); if (i <= 0) { BIO_printf(bio_err, "ERROR\n"); if (verify_args.error != X509_V_OK) BIO_printf(bio_err, "verify error:%s\n", X509_verify_cert_error_string(verify_args.error)); else ERR_print_errors(bio_err); if (scon == NULL) SSL_free(serverCon); return NULL; } #if defined(SOL_SOCKET) && defined(SO_LINGER) { struct linger no_linger; int fd; no_linger.l_onoff = 1; no_linger.l_linger = 0; fd = SSL_get_fd(serverCon); if (fd >= 0) (void)setsockopt(fd, SOL_SOCKET, SO_LINGER, (char*)&no_linger, sizeof(no_linger)); } #endif return serverCon; } #endif /* OPENSSL_NO_SOCK */
./openssl/apps/testrsa.h
/* * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ static unsigned char test512[] = { 0x30, 0x82, 0x01, 0x3a, 0x02, 0x01, 0x00, 0x02, 0x41, 0x00, 0xd6, 0x33, 0xb9, 0xc8, 0xfb, 0x4f, 0x3c, 0x7d, 0xc0, 0x01, 0x86, 0xd0, 0xe7, 0xa0, 0x55, 0xf2, 0x95, 0x93, 0xcc, 0x4f, 0xb7, 0x5b, 0x67, 0x5b, 0x94, 0x68, 0xc9, 0x34, 0x15, 0xde, 0xa5, 0x2e, 0x1c, 0x33, 0xc2, 0x6e, 0xfc, 0x34, 0x5e, 0x71, 0x13, 0xb7, 0xd6, 0xee, 0xd8, 0xa5, 0x65, 0x05, 0x72, 0x87, 0xa8, 0xb0, 0x77, 0xfe, 0x57, 0xf5, 0xfc, 0x5f, 0x55, 0x83, 0x87, 0xdd, 0x57, 0x49, 0x02, 0x03, 0x01, 0x00, 0x01, 0x02, 0x41, 0x00, 0xa7, 0xf7, 0x91, 0xc5, 0x0f, 0x84, 0x57, 0xdc, 0x07, 0xf7, 0x6a, 0x7f, 0x60, 0x52, 0xb3, 0x72, 0xf1, 0x66, 0x1f, 0x7d, 0x97, 0x3b, 0x9e, 0xb6, 0x0a, 0x8f, 0x8c, 0xcf, 0x42, 0x23, 0x00, 0x04, 0xd4, 0x28, 0x0e, 0x1c, 0x90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 0xef, 0x51, 0xf1, 0xab, 0x6d, 0xfb, 0x4b, 0x14, 0xe9, 0x4b, 0x52, 0xb5, 0x82, 0x2c, }; static unsigned char test1024[] = { 0x30, 0x82, 0x02, 0x5c, 0x02, 0x01, 0x00, 0x02, 0x81, 0x81, 0x00, 0xdc, 0x98, 0x43, 0xe8, 0x3d, 0x43, 0x5b, 0xe4, 0x05, 0xcd, 0xd0, 0xa9, 0x3e, 0xcb, 0x83, 0x75, 0xf6, 0xb5, 0xa5, 0x9f, 0x6b, 0xe9, 0x34, 0x41, 0x29, 0x18, 0xfa, 0x6a, 0x55, 0x4d, 0x70, 0xfc, 0xec, 0xae, 0x87, 0x38, 0x0a, 0x20, 0xa9, 0xc0, 0x45, 0x77, 0x6e, 0x57, 0x60, 0x57, 0xf4, 0xed, 0x96, 0x22, 0xcb, 0x8f, 0xe1, 0x33, 0x3a, 0x17, 0x1f, 0xed, 0x37, 0xa5, 0x6f, 0xeb, 0xa6, 0xbc, 0x12, 0x80, 0x1d, 0x53, 0xbd, 0x70, 0xeb, 0x21, 0x76, 0x3e, 0xc9, 0x2f, 0x1a, 0x45, 0x24, 0x82, 0xff, 0xcd, 0x59, 0x32, 0x06, 0x2e, 0x12, 0x3b, 0x23, 0x78, 0xed, 0x12, 0x3d, 0xe0, 0x8d, 0xf9, 0x67, 0x4f, 0x37, 0x4e, 0x47, 0x02, 0x4c, 0x2d, 0xc0, 0x4f, 0x1f, 0xb3, 0x94, 0xe1, 0x41, 0x2e, 0x2d, 0x90, 0x10, 0xfc, 0x82, 0x91, 0x8b, 0x0f, 0x22, 0xd4, 0xf2, 0xfc, 0x2c, 0xab, 0x53, 0x55, 0x02, 0x03, 0x01, 0x00, 0x01, 0x02, 0x81, 0x80, 0x2b, 0xcc, 0x3f, 0x8f, 0x58, 0xba, 0x8b, 0x00, 0x16, 0xf6, 0xea, 0x3a, 0xf0, 0x30, 0xd0, 0x05, 0x17, 0xda, 0xb0, 0xeb, 0x9a, 0x2d, 0x4f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b7, 0x1b, 0xe7, 0x87, 0x02, 0x40, 0x78, 0xda, 0x5d, 0x07, 0x51, 0x0c, 0x16, 0x7a, 0x9f, 0x29, 0x20, 0x84, 0x0d, 0x42, 0xfa, 0xd7, 0x00, 0xd8, 0x77, 0x7e, 0xb0, 0xb0, 0x6b, 0xd6, 0x5b, 0x53, 0xb8, 0x9b, 0x7a, 0xcd, 0xc7, 0x2b, 0xb8, 0x6a, 0x63, 0xa9, 0xfb, 0x6f, 0xa4, 0x72, 0xbf, 0x4c, 0x5d, 0x00, 0x14, 0xba, 0xfa, 0x59, 0x88, 0xed, 0xe4, 0xe0, 0x8c, 0xa2, 0xec, 0x14, 0x7e, 0x2d, 0xe2, 0xf0, 0x46, 0x49, 0x95, 0x45, }; static unsigned char test2048[] = { 0x30, 0x82, 0x04, 0xa3, 0x02, 0x01, 0x00, 0x02, 0x82, 0x01, 0x01, 0x00, 0xc0, 0xc0, 0xce, 0x3e, 0x3c, 0x53, 0x67, 0x3f, 0x4f, 0xc5, 0x2f, 0xa4, 0xc2, 0x5a, 0x2f, 0x58, 0xfd, 0x27, 0x52, 0x6a, 0xe8, 0xcf, 0x4a, 0x73, 0x47, 0x8d, 0x25, 0x0f, 0x5f, 0x03, 0x26, 0x78, 0xef, 0xf0, 0x22, 0x12, 0xd3, 0xde, 0x47, 0xb2, 0x1c, 0x0b, 0x38, 0x63, 0x1a, 0x6c, 0x85, 0x7a, 0x80, 0xc6, 0x8f, 0xa0, 0x41, 0xaf, 0x62, 0xc4, 0x67, 0x32, 0x88, 0xf8, 0xa6, 0x9c, 0xf5, 0x23, 0x1d, 0xe4, 0xac, 0x3f, 0x29, 0xf9, 0xec, 0xe1, 0x8b, 0x26, 0x03, 0x2c, 0xb2, 0xab, 0xf3, 0x7d, 0xb5, 0xca, 0x49, 0xc0, 0x8f, 0x1c, 0xdf, 0x33, 0x3a, 0x60, 0xda, 0x3c, 0xb0, 0x16, 0xf8, 0xa9, 0x12, 0x8f, 0x64, 0xac, 0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0x2b, 0x31, 0xc2, 0x36, 0xcd, 0x60, 0xbf, 0x9d, 0x2d, 0x74, 0x32, 0xe8, 0x9c, 0x93, 0x6e, 0xbb, 0x91, 0x7b, 0xfd, 0xd9, 0x02, 0x81, 0x81, 0x00, 0xa2, 0x71, 0x25, 0x38, 0xeb, 0x2a, 0xe9, 0x37, 0xcd, 0xfe, 0x44, 0xce, 0x90, 0x3f, 0x52, 0x87, 0x84, 0x52, 0x1b, 0xae, 0x8d, 0x22, 0x94, 0xce, 0x38, 0xe6, 0x04, 0x88, 0x76, 0x85, 0x9a, 0xd3, 0x14, 0x09, 0xe5, 0x69, 0x9a, 0xff, 0x58, 0x92, 0x02, 0x6a, 0x7d, 0x7c, 0x1e, 0x2c, 0xfd, 0xa8, 0xca, 0x32, 0x14, 0x4f, 0x0d, 0x84, 0x0d, 0x37, 0x43, 0xbf, 0xe4, 0x5d, 0x12, 0xc8, 0x24, 0x91, 0x27, 0x8d, 0x46, 0xd9, 0x54, 0x53, 0xe7, 0x62, 0x71, 0xa8, 0x2b, 0x71, 0x41, 0x8d, 0x75, 0xf8, 0x3a, 0xa0, 0x61, 0x29, 0x46, 0xa6, 0xe5, 0x82, 0xfa, 0x3a, 0xd9, 0x08, 0xfa, 0xfc, 0x63, 0xfd, 0x6b, 0x30, 0xbc, 0xf4, 0x4e, 0x9e, 0x8c, 0x25, 0x0c, 0xb6, 0x55, 0xe7, 0x3c, 0xd4, 0x4e, 0x0b, 0xfd, 0x8b, 0xc3, 0x0e, 0x1d, 0x9c, 0x44, 0x57, 0x8f, 0x1f, 0x86, 0xf7, 0xd5, 0x1b, 0xe4, 0x95, }; static unsigned char test3072[] = { 0x30, 0x82, 0x06, 0xe3, 0x02, 0x01, 0x00, 0x02, 0x82, 0x01, 0x81, 0x00, 0xbc, 0x3b, 0x23, 0xc0, 0x33, 0xa7, 0x8b, 0xaa, 0xca, 0xa3, 0x8c, 0x94, 0xf2, 0x4c, 0x52, 0x08, 0x85, 0x80, 0xfc,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 0x43, 0x0d, 0x0c, 0x67, 0x9e, 0xab, 0xe6, 0x8d, 0xb6, 0x2d, 0x41, 0xca, 0x43, 0xd8, 0xcb, 0x30, 0xfb, 0x3b, 0x40, 0x0d, 0x10, 0x9b, 0xb1, 0x55, 0x93, 0x73, 0x8b, 0x60, 0xef, 0xc0, 0xee, 0xc0, 0xa6, 0x7a, 0x79, 0x90, 0xfd, 0x4c, 0x25, 0xd4, 0x4f, 0x67, 0xbe, 0xf7, 0x86, 0x3c, 0x5d, 0x2b, 0x7d, 0x97, 0x3d, 0xa2, 0x91, 0xa5, 0x06, 0x69, 0xf6, 0x7a, 0xb8, 0x77, 0xe6, 0x70, 0xa9, 0xd8, 0x86, 0x4b, 0xa6, 0xcf, 0x67, 0x1d, 0x33, 0xcf, 0xfe, 0x3e }; static unsigned char test4096[] = { 0x30, 0x82, 0x09, 0x29, 0x02, 0x01, 0x00, 0x02, 0x82, 0x02, 0x01, 0x00, 0xc0, 0x71, 0xac, 0x1a, 0x13, 0x88, 0x82, 0x43, 0x3b, 0x51, 0x57, 0x71, 0x8d, 0xb6, 0x2b, 0x82, 0x65, 0x21, 0x53, 0x5f, 0x28, 0x29, 0x4f, 0x8d, 0x7c, 0x8a, 0xb9, 0x44, 0xb3, 0x28, 0x41, 0x4f, 0xd3, 0xfa, 0x6a, 0xf8, 0xb9, 0x28, 0x50, 0x39, 0x67, 0x53, 0x2c, 0x3c, 0xd7, 0xcb, 0x96, 0x41, 0x40, 0x32, 0xbb, 0xeb, 0x70, 0xae, 0x1f, 0xb0, 0x65, 0xf7, 0x3a, 0xd9, 0x22, 0xfd, 0x10, 0xae, 0xbd, 0x02, 0xe2, 0xdd, 0xf3, 0xc2, 0x79, 0x3c, 0xc6, 0xfc, 0x75, 0xbb, 0xaf, 0x4e, 0x3a, 0x36, 0xc2, 0x4f, 0xea, 0x25, 0xdf, 0x13, 0x16, 0x4b, 0x20, 0xfe, 0x4b, 0x69, 0x16, 0xc4, 0x7f, 0x1a, 0x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ed, 0xb9, 0x26, 0xab, 0x2e, 0xdb, 0xeb, 0x8f, 0xff, 0xdb, 0xb0, 0xc6, 0x55, 0xaf, 0xf8, 0x2a, 0x91, 0x9d, 0x50, 0x44, 0x21, 0x17, }; static unsigned char test7680[] = { 0x30, 0x82, 0x11, 0x09, 0x02, 0x01, 0x00, 0x02, 0x82, 0x03, 0xc1, 0x00, 0xe3, 0x27, 0x46, 0x99, 0xb5, 0x17, 0xab, 0xfa, 0x65, 0x05, 0x7a, 0x06, 0x81, 0x14, 0xce, 0x43, 0x21, 0x49, 0x0f, 0x08, 0xf1, 0x70, 0xb4, 0xc1, 0x10, 0xd1, 0x87, 0xf8, 0x29, 0x91, 0x36, 0x66, 0x2d, 0xbe, 0x7b, 0x1d, 0xa2, 0x0b, 0x20, 0x38, 0xd9, 0x8e, 0x78, 0x27, 0xcf, 0xb5, 0x45, 0x58, 0x3d, 0xf4, 0xda, 0xf0, 0xdc, 0x21, 0x17, 0x52, 0xcd, 0x68, 0xe2, 0x81, 0xac, 0x88, 0x61, 0x10, 0xbc, 0xb0, 0x7f, 0xe4, 0xf3, 0x78, 0xb7, 0x28, 0x6c, 0x5f, 0x5c, 0xc2, 0x8d, 0x3d, 0xb0, 0x87, 0x41, 0x15, 0x2e, 0x09, 0x5f, 0xea, 0x06, 0x7f, 0xe9, 0x35, 0x18, 0x90, 0x50, 0xad, 0xf6, 0xb9, 0xfd, 0x33, 0x02, 0x1a, 0x99, 0x9e, 0xa5, 0x7d, 0x2c, 0x3b, 0x24, 0xe7, 0x31, 0x35, 0x73, 0x9a, 0xb0, 0xfe, 0x03, 0xfc, 0xc6, 0x98, 0x78, 0xd9, 0x66, 0x95, 0xa5, 0x12, 0xbc, 0x1e, 0x82, 0xbc, 0xf1, 0xc5, 0x31, 0xcd, 0xa6, 0xb1, 0x0c, 0x02, 0xbf, 0x7f, 0xb7, 0xaf, 0x5f, 0xd6, 0xed, 0xf7, 0xc1, 0x59, 0x86, 0x3a, 0x35, 0x95, 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 0x3d, 0x16, 0x64, 0xed, 0xf5, 0xe8, 0xdf, 0x99, 0xa4, 0xfb, 0xad, 0x79, 0x88, 0xd5, 0x8c, 0x62, 0x33, 0x9e, 0x35, 0xa6, 0x7f, 0x9d, 0xb6, 0x1a, 0x40, 0x6d, 0xc3, 0x89, 0x5d, 0x7b, 0xe2, 0xc8, 0xd3, 0x16, 0x13, 0x07, 0x9a, 0x38, 0x22, 0x33, 0x03, 0xac, 0x70, 0x3e, 0xce, 0x32, 0x56, 0x0b, 0x58, 0x56, 0xb8, 0xe9, 0xd8, 0x42, 0x35, 0x6c, 0xb9, 0x02, 0xb3, 0x64, 0xeb, 0xaa, 0x09, 0x3f, 0xac, 0x66, 0x08, 0xb4, 0x5f, 0x3e, 0xb4, 0xec, 0x39, 0xb1, 0x99, 0xe4, 0x5d, 0x1d, 0x32, 0x14, 0xc1, 0x48, 0x8f, 0x6c, 0x65, 0x87, 0x34, 0x50, 0xa4, 0xf4, 0x9b, 0x5b, 0x2e, 0xb5, 0x79, 0x0d, 0x11, 0x62, 0xa4, 0x35, 0x9c, 0x6f, 0x92, 0xd0, 0x68, 0x07, 0xdd, 0x69, 0x85, 0x48, 0xe3, 0x5d, 0x10, 0x34, 0xaf, 0xea, 0x41, 0x72, 0x5a, 0x71, 0x00, 0xf8, 0xe6, 0x47, 0x7f, 0xa0, 0x6f, 0x91, 0x96, 0x40, 0x00, 0x40, 0x70, 0xfb, 0x63, 0xcf, 0xc9, 0x36, 0x04, 0x1c, 0x3b, 0x11, 0x08, 0x29, 0x81, 0x9f }; static unsigned char test15360[] = { 0x30, 0x82, 0x21, 0xe8, 0x02, 0x01, 0x00, 0x02, 0x82, 0x07, 0x81, 0x00, 0xad, 0x3f, 0xaa, 0xdc, 0x8c, 0x85, 0xcb, 0x60, 0xd2, 0xf5, 0x30, 0xa1, 0x0f, 0x26, 0xec, 0xdf, 0xfc, 0x91, 0x39, 0xbd, 0x3e, 0x8f, 0x99, 0x64, 0x1e, 0x51, 0x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, 0xd3, 0xfc, 0xe4, 0xe0, 0xec, 0x44, 0x0b, 0x1c, 0x05, 0x39, 0xa4, 0x13, 0x87, 0x29, 0x11, 0x9d, 0xea, 0xe9, 0x64, 0xa9, 0x1c, 0x76, 0x3a, 0x65, 0x0b, 0xfd, 0xed, 0x77, 0x46, 0x4f, 0xcd, 0x0b, 0x63, 0xc4, 0x83, 0x0b, 0x56, 0x79, 0xd3, 0x67, 0x01, 0x11, 0x02, 0xd9, 0x50, 0xd8, 0x23, 0xf4, 0xb6, 0x02, 0x4c, 0xae, 0xb5, 0xc9, 0x68, 0x1b, 0x87, 0x33, 0xbb, 0xdc, 0x64, 0x0e, 0x32, 0x34, 0xb2, 0x25, 0xaa, 0x76, 0xdd, 0x7e, 0xc3, 0x46, 0x51, 0x1c, 0xc1, 0xd0, 0x05, 0x09, 0x6c, 0x27, 0xd3, 0xcf, 0x33, 0x7a, 0xb9, 0x26, 0x24, 0x23, 0x4a, 0x93, 0x9f, 0x4b, 0x96, 0xc7, 0xe2, 0xb2, 0x51, 0x42, 0x4d, 0x5d, 0xd9, 0x73, 0x75, 0xce, 0x23, 0x28, 0x56, 0x5e, 0xe7, 0x96, 0x58, 0x04, 0xfd, 0x33, 0x93, 0x08, 0x41, 0x62, 0x02, 0x7e, 0xc9, 0xc6, 0x55, 0x64, 0x19, 0xda, 0x39, 0xb8, 0x5d, 0x09, 0x47, 0xf3, 0xdd, 0x77, 0xee, 0xea, 0x35, 0x73, 0x95, 0xdb, 0x18, 0x4d, 0xd1, 0xfe, 0xee, 0x40, 0x31, 0x2a, 0x22, 0x91, 0x69, 0xd6, 0xed, 0x9c, 0x54, 0x14, 0x73, 0x61, 0x61, 0xe7, 0x1d, 0x34, 0x96, 0x47, 0xff, 0x28, 0x7a, 0x48, 0xa3, 0xf4, 0xcd, 0x64, 0x23, 0xe2, 0x52, 0x2f, 0x20, 0x8f, 0x04, 0xb3, 0xdc, 0xf0, 0x29, 0x67, 0x88, 0x76, 0x79, 0xdb,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0x99, 0x08, 0xe4, 0xcc, 0xce, 0xdf, 0x71, 0x65, 0x8a, 0x6d, 0x62, 0xde, 0x76, 0x1d, 0x6d, 0x6b, 0x78, 0x22, 0x32, 0x63, 0xdd, 0x53, 0x7d, 0xec, 0xed, 0x9d, 0x82, 0xa9, 0x2c, 0x5c, 0x8a, 0x17, 0xdd, 0x85, 0xf9, 0xd2, 0xac, 0x6e, 0x98, 0x60, 0x2e, 0x08, 0xd4, 0x06, 0x76, 0xf4, 0x97, 0xca, 0xb1, 0x72, 0x50, 0x5b, 0x83, 0xea, 0xbb, 0x39, 0x0f, 0x18, 0xb3, 0xb8, 0x03, 0xee, 0x7c, 0x84, 0xa9, 0x69, 0xcd, 0x1d, 0xbd, 0xe2, 0xb7, 0xce, 0xe2, 0x6f, 0x03, 0x49, 0x52, 0x67, 0xa0, 0x1b, 0x23, 0x43, 0x92, 0x2c, 0x7c, 0x3b, 0x65, 0xe8, 0x61, 0x99, 0xde, 0xb5, 0xf1, 0x63, 0x73, 0x92, 0x6c, 0x70, 0x8b, 0x83, 0x10, 0xb4, 0x06, 0x2c, 0x99, 0x12, 0x73, 0xec, 0x87, 0x92, 0x09, 0x67, 0x96, 0xd6, 0x9c, 0x9f, 0x35, 0x48, 0x48, 0x3b, 0x44, 0x00, 0x73, 0x1c, 0x59, 0xeb, 0x81, 0x7b, 0xd1, 0xda, 0x76, 0xcf, 0xc2, 0x4d, 0xf1, 0xa2, 0x5b, 0x2f, 0x5f, 0x91, 0x29, 0x6e, 0x08, 0x37, 0xd6, 0xaa, 0xd2, 0xf8, 0x4f, 0x5e, 0x00, 0x16, 0x52 };
./openssl/apps/passwd.c
/* * Copyright 2000-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 "apps.h" #include "progs.h" #include <openssl/bio.h> #include <openssl/err.h> #include <openssl/evp.h> #include <openssl/rand.h> #if !defined(OPENSSL_NO_DES) && !defined(OPENSSL_NO_DEPRECATED_3_0) # include <openssl/des.h> #endif #include <openssl/md5.h> #include <openssl/sha.h> static const unsigned char cov_2char[64] = { /* from crypto/des/fcrypt.c */ 0x2E, 0x2F, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4A, 0x4B, 0x4C, 0x4D, 0x4E, 0x4F, 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5A, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6A, 0x6B, 0x6C, 0x6D, 0x6E, 0x6F, 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7A }; static const char ascii_dollar[] = { 0x24, 0x00 }; typedef enum { passwd_unset = 0, passwd_md5, passwd_apr1, passwd_sha256, passwd_sha512, passwd_aixmd5 } passwd_modes; static int do_passwd(int passed_salt, char **salt_p, char **salt_malloc_p, char *passwd, BIO *out, int quiet, int table, int reverse, size_t pw_maxlen, passwd_modes mode); typedef enum OPTION_choice { OPT_COMMON, OPT_IN, OPT_NOVERIFY, OPT_QUIET, OPT_TABLE, OPT_REVERSE, OPT_APR1, OPT_1, OPT_5, OPT_6, OPT_AIXMD5, OPT_SALT, OPT_STDIN, OPT_R_ENUM, OPT_PROV_ENUM } OPTION_CHOICE; const OPTIONS passwd_options[] = { {OPT_HELP_STR, 1, '-', "Usage: %s [options] [password]\n"}, OPT_SECTION("General"), {"help", OPT_HELP, '-', "Display this summary"}, OPT_SECTION("Input"), {"in", OPT_IN, '<', "Read passwords from file"}, {"noverify", OPT_NOVERIFY, '-', "Never verify when reading password from terminal"}, {"stdin", OPT_STDIN, '-', "Read passwords from stdin"}, OPT_SECTION("Output"), {"quiet", OPT_QUIET, '-', "No warnings"}, {"table", OPT_TABLE, '-', "Format output as table"}, {"reverse", OPT_REVERSE, '-', "Switch table columns"}, OPT_SECTION("Cryptographic"), {"salt", OPT_SALT, 's', "Use provided salt"}, {"6", OPT_6, '-', "SHA512-based password algorithm"}, {"5", OPT_5, '-', "SHA256-based password algorithm"}, {"apr1", OPT_APR1, '-', "MD5-based password algorithm, Apache variant"}, {"1", OPT_1, '-', "MD5-based password algorithm"}, {"aixmd5", OPT_AIXMD5, '-', "AIX MD5-based password algorithm"}, OPT_R_OPTIONS, OPT_PROV_OPTIONS, OPT_PARAMETERS(), {"password", 0, 0, "Password text to digest (optional)"}, {NULL} }; int passwd_main(int argc, char **argv) { BIO *in = NULL; char *infile = NULL, *salt = NULL, *passwd = NULL, **passwds = NULL; char *salt_malloc = NULL, *passwd_malloc = NULL, *prog; OPTION_CHOICE o; int in_stdin = 0, pw_source_defined = 0; #ifndef OPENSSL_NO_UI_CONSOLE int in_noverify = 0; #endif int passed_salt = 0, quiet = 0, table = 0, reverse = 0; int ret = 1; passwd_modes mode = passwd_unset; size_t passwd_malloc_size = 0; size_t pw_maxlen = 256; /* arbitrary limit, should be enough for most * passwords */ prog = opt_init(argc, argv, passwd_options); while ((o = opt_next()) != OPT_EOF) { switch (o) { case OPT_EOF: case OPT_ERR: opthelp: BIO_printf(bio_err, "%s: Use -help for summary.\n", prog); goto end; case OPT_HELP: opt_help(passwd_options); ret = 0; goto end; case OPT_IN: if (pw_source_defined) goto opthelp; infile = opt_arg(); pw_source_defined = 1; break; case OPT_NOVERIFY: #ifndef OPENSSL_NO_UI_CONSOLE in_noverify = 1; #endif break; case OPT_QUIET: quiet = 1; break; case OPT_TABLE: table = 1; break; case OPT_REVERSE: reverse = 1; break; case OPT_1: if (mode != passwd_unset) goto opthelp; mode = passwd_md5; break; case OPT_5: if (mode != passwd_unset) goto opthelp; mode = passwd_sha256; break; case OPT_6: if (mode != passwd_unset) goto opthelp; mode = passwd_sha512; break; case OPT_APR1: if (mode != passwd_unset) goto opthelp; mode = passwd_apr1; break; case OPT_AIXMD5: if (mode != passwd_unset) goto opthelp; mode = passwd_aixmd5; break; case OPT_SALT: passed_salt = 1; salt = opt_arg(); break; case OPT_STDIN: if (pw_source_defined) goto opthelp; in_stdin = 1; pw_source_defined = 1; break; case OPT_R_CASES: if (!opt_rand(o)) goto end; break; case OPT_PROV_CASES: if (!opt_provider(o)) goto end; break; } } /* All remaining arguments are the password text */ argc = opt_num_rest(); argv = opt_rest(); if (*argv != NULL) { if (pw_source_defined) goto opthelp; pw_source_defined = 1; passwds = argv; } if (!app_RAND_load()) goto end; if (mode == passwd_unset) { /* use default */ mode = passwd_md5; } if (infile != NULL && in_stdin) { BIO_printf(bio_err, "%s: Can't combine -in and -stdin\n", prog); goto end; } if (infile != NULL || in_stdin) { /* * If in_stdin is true, we know that infile is NULL, and that * bio_open_default() will give us back an alias for stdin. */ in = bio_open_default(infile, 'r', FORMAT_TEXT); if (in == NULL) goto end; } if (passwds == NULL) { /* no passwords on the command line */ passwd_malloc_size = pw_maxlen + 2; /* longer than necessary so that we can warn about truncation */ passwd = passwd_malloc = app_malloc(passwd_malloc_size, "password buffer"); } if ((in == NULL) && (passwds == NULL)) { /* * we use the following method to make sure what * in the 'else' section is always compiled, to * avoid rot of not-frequently-used code. */ if (1) { #ifndef OPENSSL_NO_UI_CONSOLE /* build a null-terminated list */ static char *passwds_static[2] = { NULL, NULL }; passwds = passwds_static; if (in == NULL) { if (EVP_read_pw_string (passwd_malloc, passwd_malloc_size, "Password: ", !(passed_salt || in_noverify)) != 0) goto end; } passwds[0] = passwd_malloc; } else { #endif BIO_printf(bio_err, "password required\n"); goto end; } } if (in == NULL) { assert(passwds != NULL); assert(*passwds != NULL); do { /* loop over list of passwords */ passwd = *passwds++; if (!do_passwd(passed_salt, &salt, &salt_malloc, passwd, bio_out, quiet, table, reverse, pw_maxlen, mode)) goto end; } while (*passwds != NULL); } else { /* in != NULL */ int done; assert(passwd != NULL); do { int r = BIO_gets(in, passwd, pw_maxlen + 1); if (r > 0) { char *c = (strchr(passwd, '\n')); if (c != NULL) { *c = 0; /* truncate at newline */ } else { /* ignore rest of line */ char trash[BUFSIZ]; do r = BIO_gets(in, trash, sizeof(trash)); while ((r > 0) && (!strchr(trash, '\n'))); } if (!do_passwd (passed_salt, &salt, &salt_malloc, passwd, bio_out, quiet, table, reverse, pw_maxlen, mode)) goto end; } done = (r <= 0); } while (!done); } ret = 0; end: #if 0 ERR_print_errors(bio_err); #endif OPENSSL_free(salt_malloc); OPENSSL_free(passwd_malloc); BIO_free(in); return ret; } /* * MD5-based password algorithm (should probably be available as a library * function; then the static buffer would not be acceptable). For magic * string "1", this should be compatible to the MD5-based BSD password * algorithm. For 'magic' string "apr1", this is compatible to the MD5-based * Apache password algorithm. (Apparently, the Apache password algorithm is * identical except that the 'magic' string was changed -- the laziest * application of the NIH principle I've ever encountered.) */ static char *md5crypt(const char *passwd, const char *magic, const char *salt) { /* "$apr1$..salt..$.......md5hash..........\0" */ static char out_buf[6 + 9 + 24 + 2]; unsigned char buf[MD5_DIGEST_LENGTH]; char ascii_magic[5]; /* "apr1" plus '\0' */ char ascii_salt[9]; /* Max 8 chars plus '\0' */ char *ascii_passwd = NULL; char *salt_out; int n; unsigned int i; EVP_MD_CTX *md = NULL, *md2 = NULL; size_t passwd_len, salt_len, magic_len; passwd_len = strlen(passwd); out_buf[0] = 0; magic_len = strlen(magic); OPENSSL_strlcpy(ascii_magic, magic, sizeof(ascii_magic)); #ifdef CHARSET_EBCDIC if ((magic[0] & 0x80) != 0) /* High bit is 1 in EBCDIC alnums */ ebcdic2ascii(ascii_magic, ascii_magic, magic_len); #endif /* The salt gets truncated to 8 chars */ OPENSSL_strlcpy(ascii_salt, salt, sizeof(ascii_salt)); salt_len = strlen(ascii_salt); #ifdef CHARSET_EBCDIC ebcdic2ascii(ascii_salt, ascii_salt, salt_len); #endif #ifdef CHARSET_EBCDIC ascii_passwd = OPENSSL_strdup(passwd); if (ascii_passwd == NULL) return NULL; ebcdic2ascii(ascii_passwd, ascii_passwd, passwd_len); passwd = ascii_passwd; #endif if (magic_len > 0) { OPENSSL_strlcat(out_buf, ascii_dollar, sizeof(out_buf)); if (magic_len > 4) /* assert it's "1" or "apr1" */ goto err; OPENSSL_strlcat(out_buf, ascii_magic, sizeof(out_buf)); OPENSSL_strlcat(out_buf, ascii_dollar, sizeof(out_buf)); } OPENSSL_strlcat(out_buf, ascii_salt, sizeof(out_buf)); if (strlen(out_buf) > 6 + 8) /* assert "$apr1$..salt.." */ goto err; salt_out = out_buf; if (magic_len > 0) salt_out += 2 + magic_len; if (salt_len > 8) goto err; md = EVP_MD_CTX_new(); if (md == NULL || !EVP_DigestInit_ex(md, EVP_md5(), NULL) || !EVP_DigestUpdate(md, passwd, passwd_len)) goto err; if (magic_len > 0) if (!EVP_DigestUpdate(md, ascii_dollar, 1) || !EVP_DigestUpdate(md, ascii_magic, magic_len) || !EVP_DigestUpdate(md, ascii_dollar, 1)) goto err; if (!EVP_DigestUpdate(md, ascii_salt, salt_len)) goto err; md2 = EVP_MD_CTX_new(); if (md2 == NULL || !EVP_DigestInit_ex(md2, EVP_md5(), NULL) || !EVP_DigestUpdate(md2, passwd, passwd_len) || !EVP_DigestUpdate(md2, ascii_salt, salt_len) || !EVP_DigestUpdate(md2, passwd, passwd_len) || !EVP_DigestFinal_ex(md2, buf, NULL)) goto err; for (i = passwd_len; i > sizeof(buf); i -= sizeof(buf)) { if (!EVP_DigestUpdate(md, buf, sizeof(buf))) goto err; } if (!EVP_DigestUpdate(md, buf, i)) goto err; n = passwd_len; while (n) { if (!EVP_DigestUpdate(md, (n & 1) ? "\0" : passwd, 1)) goto err; n >>= 1; } if (!EVP_DigestFinal_ex(md, buf, NULL)) goto err; for (i = 0; i < 1000; i++) { if (!EVP_DigestInit_ex(md2, EVP_md5(), NULL)) goto err; if (!EVP_DigestUpdate(md2, (i & 1) ? (const unsigned char *)passwd : buf, (i & 1) ? passwd_len : sizeof(buf))) goto err; if (i % 3) { if (!EVP_DigestUpdate(md2, ascii_salt, salt_len)) goto err; } if (i % 7) { if (!EVP_DigestUpdate(md2, passwd, passwd_len)) goto err; } if (!EVP_DigestUpdate(md2, (i & 1) ? buf : (const unsigned char *)passwd, (i & 1) ? sizeof(buf) : passwd_len)) goto err; if (!EVP_DigestFinal_ex(md2, buf, NULL)) goto err; } EVP_MD_CTX_free(md2); EVP_MD_CTX_free(md); md2 = NULL; md = NULL; { /* transform buf into output string */ unsigned char buf_perm[sizeof(buf)]; int dest, source; char *output; /* silly output permutation */ for (dest = 0, source = 0; dest < 14; dest++, source = (source + 6) % 17) buf_perm[dest] = buf[source]; buf_perm[14] = buf[5]; buf_perm[15] = buf[11]; # ifndef PEDANTIC /* Unfortunately, this generates a "no * effect" warning */ assert(16 == sizeof(buf_perm)); # endif output = salt_out + salt_len; assert(output == out_buf + strlen(out_buf)); *output++ = ascii_dollar[0]; for (i = 0; i < 15; i += 3) { *output++ = cov_2char[buf_perm[i + 2] & 0x3f]; *output++ = cov_2char[((buf_perm[i + 1] & 0xf) << 2) | (buf_perm[i + 2] >> 6)]; *output++ = cov_2char[((buf_perm[i] & 3) << 4) | (buf_perm[i + 1] >> 4)]; *output++ = cov_2char[buf_perm[i] >> 2]; } assert(i == 15); *output++ = cov_2char[buf_perm[i] & 0x3f]; *output++ = cov_2char[buf_perm[i] >> 6]; *output = 0; assert(strlen(out_buf) < sizeof(out_buf)); #ifdef CHARSET_EBCDIC ascii2ebcdic(out_buf, out_buf, strlen(out_buf)); #endif } return out_buf; err: OPENSSL_free(ascii_passwd); EVP_MD_CTX_free(md2); EVP_MD_CTX_free(md); return NULL; } /* * SHA based password algorithm, describe by Ulrich Drepper here: * https://www.akkadia.org/drepper/SHA-crypt.txt * (note that it's in the public domain) */ static char *shacrypt(const char *passwd, const char *magic, const char *salt) { /* Prefix for optional rounds specification. */ static const char rounds_prefix[] = "rounds="; /* Maximum salt string length. */ # define SALT_LEN_MAX 16 /* Default number of rounds if not explicitly specified. */ # define ROUNDS_DEFAULT 5000 /* Minimum number of rounds. */ # define ROUNDS_MIN 1000 /* Maximum number of rounds. */ # define ROUNDS_MAX 999999999 /* "$6$rounds=<N>$......salt......$...shahash(up to 86 chars)...\0" */ static char out_buf[3 + 17 + 17 + 86 + 1]; unsigned char buf[SHA512_DIGEST_LENGTH]; unsigned char temp_buf[SHA512_DIGEST_LENGTH]; size_t buf_size = 0; char ascii_magic[2]; char ascii_salt[17]; /* Max 16 chars plus '\0' */ char *ascii_passwd = NULL; size_t n; EVP_MD_CTX *md = NULL, *md2 = NULL; const EVP_MD *sha = NULL; size_t passwd_len, salt_len, magic_len; unsigned int rounds = ROUNDS_DEFAULT; /* Default */ char rounds_custom = 0; char *p_bytes = NULL; char *s_bytes = NULL; char *cp = NULL; passwd_len = strlen(passwd); magic_len = strlen(magic); /* assert it's "5" or "6" */ if (magic_len != 1) return NULL; switch (magic[0]) { case '5': sha = EVP_sha256(); buf_size = 32; break; case '6': sha = EVP_sha512(); buf_size = 64; break; default: return NULL; } if (strncmp(salt, rounds_prefix, sizeof(rounds_prefix) - 1) == 0) { const char *num = salt + sizeof(rounds_prefix) - 1; char *endp; unsigned long int srounds = strtoul (num, &endp, 10); if (*endp == '$') { salt = endp + 1; if (srounds > ROUNDS_MAX) rounds = ROUNDS_MAX; else if (srounds < ROUNDS_MIN) rounds = ROUNDS_MIN; else rounds = (unsigned int)srounds; rounds_custom = 1; } else { return NULL; } } OPENSSL_strlcpy(ascii_magic, magic, sizeof(ascii_magic)); #ifdef CHARSET_EBCDIC if ((magic[0] & 0x80) != 0) /* High bit is 1 in EBCDIC alnums */ ebcdic2ascii(ascii_magic, ascii_magic, magic_len); #endif /* The salt gets truncated to 16 chars */ OPENSSL_strlcpy(ascii_salt, salt, sizeof(ascii_salt)); salt_len = strlen(ascii_salt); #ifdef CHARSET_EBCDIC ebcdic2ascii(ascii_salt, ascii_salt, salt_len); #endif #ifdef CHARSET_EBCDIC ascii_passwd = OPENSSL_strdup(passwd); if (ascii_passwd == NULL) return NULL; ebcdic2ascii(ascii_passwd, ascii_passwd, passwd_len); passwd = ascii_passwd; #endif out_buf[0] = 0; OPENSSL_strlcat(out_buf, ascii_dollar, sizeof(out_buf)); OPENSSL_strlcat(out_buf, ascii_magic, sizeof(out_buf)); OPENSSL_strlcat(out_buf, ascii_dollar, sizeof(out_buf)); if (rounds_custom) { char tmp_buf[80]; /* "rounds=999999999" */ sprintf(tmp_buf, "rounds=%u", rounds); #ifdef CHARSET_EBCDIC /* In case we're really on a ASCII based platform and just pretend */ if (tmp_buf[0] != 0x72) /* ASCII 'r' */ ebcdic2ascii(tmp_buf, tmp_buf, strlen(tmp_buf)); #endif OPENSSL_strlcat(out_buf, tmp_buf, sizeof(out_buf)); OPENSSL_strlcat(out_buf, ascii_dollar, sizeof(out_buf)); } OPENSSL_strlcat(out_buf, ascii_salt, sizeof(out_buf)); /* assert "$5$rounds=999999999$......salt......" */ if (strlen(out_buf) > 3 + 17 * rounds_custom + salt_len) goto err; md = EVP_MD_CTX_new(); if (md == NULL || !EVP_DigestInit_ex(md, sha, NULL) || !EVP_DigestUpdate(md, passwd, passwd_len) || !EVP_DigestUpdate(md, ascii_salt, salt_len)) goto err; md2 = EVP_MD_CTX_new(); if (md2 == NULL || !EVP_DigestInit_ex(md2, sha, NULL) || !EVP_DigestUpdate(md2, passwd, passwd_len) || !EVP_DigestUpdate(md2, ascii_salt, salt_len) || !EVP_DigestUpdate(md2, passwd, passwd_len) || !EVP_DigestFinal_ex(md2, buf, NULL)) goto err; for (n = passwd_len; n > buf_size; n -= buf_size) { if (!EVP_DigestUpdate(md, buf, buf_size)) goto err; } if (!EVP_DigestUpdate(md, buf, n)) goto err; n = passwd_len; while (n) { if (!EVP_DigestUpdate(md, (n & 1) ? buf : (const unsigned char *)passwd, (n & 1) ? buf_size : passwd_len)) goto err; n >>= 1; } if (!EVP_DigestFinal_ex(md, buf, NULL)) goto err; /* P sequence */ if (!EVP_DigestInit_ex(md2, sha, NULL)) goto err; for (n = passwd_len; n > 0; n--) if (!EVP_DigestUpdate(md2, passwd, passwd_len)) goto err; if (!EVP_DigestFinal_ex(md2, temp_buf, NULL)) goto err; if ((p_bytes = OPENSSL_zalloc(passwd_len)) == NULL) goto err; for (cp = p_bytes, n = passwd_len; n > buf_size; n -= buf_size, cp += buf_size) memcpy(cp, temp_buf, buf_size); memcpy(cp, temp_buf, n); /* S sequence */ if (!EVP_DigestInit_ex(md2, sha, NULL)) goto err; for (n = 16 + buf[0]; n > 0; n--) if (!EVP_DigestUpdate(md2, ascii_salt, salt_len)) goto err; if (!EVP_DigestFinal_ex(md2, temp_buf, NULL)) goto err; if ((s_bytes = OPENSSL_zalloc(salt_len)) == NULL) goto err; for (cp = s_bytes, n = salt_len; n > buf_size; n -= buf_size, cp += buf_size) memcpy(cp, temp_buf, buf_size); memcpy(cp, temp_buf, n); for (n = 0; n < rounds; n++) { if (!EVP_DigestInit_ex(md2, sha, NULL)) goto err; if (!EVP_DigestUpdate(md2, (n & 1) ? (const unsigned char *)p_bytes : buf, (n & 1) ? passwd_len : buf_size)) goto err; if (n % 3) { if (!EVP_DigestUpdate(md2, s_bytes, salt_len)) goto err; } if (n % 7) { if (!EVP_DigestUpdate(md2, p_bytes, passwd_len)) goto err; } if (!EVP_DigestUpdate(md2, (n & 1) ? buf : (const unsigned char *)p_bytes, (n & 1) ? buf_size : passwd_len)) goto err; if (!EVP_DigestFinal_ex(md2, buf, NULL)) goto err; } EVP_MD_CTX_free(md2); EVP_MD_CTX_free(md); md2 = NULL; md = NULL; OPENSSL_free(p_bytes); OPENSSL_free(s_bytes); p_bytes = NULL; s_bytes = NULL; cp = out_buf + strlen(out_buf); *cp++ = ascii_dollar[0]; # define b64_from_24bit(B2, B1, B0, N) \ do { \ unsigned int w = ((B2) << 16) | ((B1) << 8) | (B0); \ int i = (N); \ while (i-- > 0) \ { \ *cp++ = cov_2char[w & 0x3f]; \ w >>= 6; \ } \ } while (0) switch (magic[0]) { case '5': b64_from_24bit (buf[0], buf[10], buf[20], 4); b64_from_24bit (buf[21], buf[1], buf[11], 4); b64_from_24bit (buf[12], buf[22], buf[2], 4); b64_from_24bit (buf[3], buf[13], buf[23], 4); b64_from_24bit (buf[24], buf[4], buf[14], 4); b64_from_24bit (buf[15], buf[25], buf[5], 4); b64_from_24bit (buf[6], buf[16], buf[26], 4); b64_from_24bit (buf[27], buf[7], buf[17], 4); b64_from_24bit (buf[18], buf[28], buf[8], 4); b64_from_24bit (buf[9], buf[19], buf[29], 4); b64_from_24bit (0, buf[31], buf[30], 3); break; case '6': b64_from_24bit (buf[0], buf[21], buf[42], 4); b64_from_24bit (buf[22], buf[43], buf[1], 4); b64_from_24bit (buf[44], buf[2], buf[23], 4); b64_from_24bit (buf[3], buf[24], buf[45], 4); b64_from_24bit (buf[25], buf[46], buf[4], 4); b64_from_24bit (buf[47], buf[5], buf[26], 4); b64_from_24bit (buf[6], buf[27], buf[48], 4); b64_from_24bit (buf[28], buf[49], buf[7], 4); b64_from_24bit (buf[50], buf[8], buf[29], 4); b64_from_24bit (buf[9], buf[30], buf[51], 4); b64_from_24bit (buf[31], buf[52], buf[10], 4); b64_from_24bit (buf[53], buf[11], buf[32], 4); b64_from_24bit (buf[12], buf[33], buf[54], 4); b64_from_24bit (buf[34], buf[55], buf[13], 4); b64_from_24bit (buf[56], buf[14], buf[35], 4); b64_from_24bit (buf[15], buf[36], buf[57], 4); b64_from_24bit (buf[37], buf[58], buf[16], 4); b64_from_24bit (buf[59], buf[17], buf[38], 4); b64_from_24bit (buf[18], buf[39], buf[60], 4); b64_from_24bit (buf[40], buf[61], buf[19], 4); b64_from_24bit (buf[62], buf[20], buf[41], 4); b64_from_24bit (0, 0, buf[63], 2); break; default: goto err; } *cp = '\0'; #ifdef CHARSET_EBCDIC ascii2ebcdic(out_buf, out_buf, strlen(out_buf)); #endif return out_buf; err: EVP_MD_CTX_free(md2); EVP_MD_CTX_free(md); OPENSSL_free(p_bytes); OPENSSL_free(s_bytes); OPENSSL_free(ascii_passwd); return NULL; } static int do_passwd(int passed_salt, char **salt_p, char **salt_malloc_p, char *passwd, BIO *out, int quiet, int table, int reverse, size_t pw_maxlen, passwd_modes mode) { char *hash = NULL; assert(salt_p != NULL); assert(salt_malloc_p != NULL); /* first make sure we have a salt */ if (!passed_salt) { size_t saltlen = 0; size_t i; if (mode == passwd_md5 || mode == passwd_apr1 || mode == passwd_aixmd5) saltlen = 8; if (mode == passwd_sha256 || mode == passwd_sha512) saltlen = 16; assert(saltlen != 0); if (*salt_malloc_p == NULL) *salt_p = *salt_malloc_p = app_malloc(saltlen + 1, "salt buffer"); if (RAND_bytes((unsigned char *)*salt_p, saltlen) <= 0) goto end; for (i = 0; i < saltlen; i++) (*salt_p)[i] = cov_2char[(*salt_p)[i] & 0x3f]; /* 6 bits */ (*salt_p)[i] = 0; # ifdef CHARSET_EBCDIC /* The password encryption function will convert back to ASCII */ ascii2ebcdic(*salt_p, *salt_p, saltlen); # endif } assert(*salt_p != NULL); /* truncate password if necessary */ if ((strlen(passwd) > pw_maxlen)) { if (!quiet) /* * XXX: really we should know how to print a size_t, not cast it */ BIO_printf(bio_err, "Warning: truncating password to %u characters\n", (unsigned)pw_maxlen); passwd[pw_maxlen] = 0; } assert(strlen(passwd) <= pw_maxlen); /* now compute password hash */ if (mode == passwd_md5 || mode == passwd_apr1) hash = md5crypt(passwd, (mode == passwd_md5 ? "1" : "apr1"), *salt_p); if (mode == passwd_aixmd5) hash = md5crypt(passwd, "", *salt_p); if (mode == passwd_sha256 || mode == passwd_sha512) hash = shacrypt(passwd, (mode == passwd_sha256 ? "5" : "6"), *salt_p); assert(hash != NULL); if (table && !reverse) BIO_printf(out, "%s\t%s\n", passwd, hash); else if (table && reverse) BIO_printf(out, "%s\t%s\n", hash, passwd); else BIO_printf(out, "%s\n", hash); return 1; end: return 0; }
./openssl/apps/ecparam.c
/* * Copyright 2002-2022 The OpenSSL Project Authors. All Rights Reserved. * Copyright (c) 2002, Oracle and/or its affiliates. All rights reserved * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <string.h> #include <openssl/opensslconf.h> #include <openssl/evp.h> #include <openssl/encoder.h> #include <openssl/decoder.h> #include <openssl/core_names.h> #include <openssl/core_dispatch.h> #include <openssl/params.h> #include <openssl/err.h> #include "apps.h" #include "progs.h" #include "ec_common.h" typedef enum OPTION_choice { OPT_COMMON, OPT_INFORM, OPT_OUTFORM, OPT_IN, OPT_OUT, OPT_TEXT, OPT_CHECK, OPT_LIST_CURVES, OPT_NO_SEED, OPT_NOOUT, OPT_NAME, OPT_CONV_FORM, OPT_PARAM_ENC, OPT_GENKEY, OPT_ENGINE, OPT_CHECK_NAMED, OPT_R_ENUM, OPT_PROV_ENUM } OPTION_CHOICE; const OPTIONS ecparam_options[] = { OPT_SECTION("General"), {"help", OPT_HELP, '-', "Display this summary"}, {"list_curves", OPT_LIST_CURVES, '-', "Prints a list of all curve 'short names'"}, #ifndef OPENSSL_NO_ENGINE {"engine", OPT_ENGINE, 's', "Use engine, possibly a hardware device"}, #endif {"genkey", OPT_GENKEY, '-', "Generate ec key"}, {"in", OPT_IN, '<', "Input file - default stdin"}, {"inform", OPT_INFORM, 'F', "Input format - default PEM (DER or PEM)"}, {"out", OPT_OUT, '>', "Output file - default stdout"}, {"outform", OPT_OUTFORM, 'F', "Output format - default PEM"}, OPT_SECTION("Output"), {"text", OPT_TEXT, '-', "Print the ec parameters in text form"}, {"noout", OPT_NOOUT, '-', "Do not print the ec parameter"}, {"param_enc", OPT_PARAM_ENC, 's', "Specifies the way the ec parameters are encoded"}, OPT_SECTION("Parameter"), {"check", OPT_CHECK, '-', "Validate the ec parameters"}, {"check_named", OPT_CHECK_NAMED, '-', "Check that named EC curve parameters have not been modified"}, {"no_seed", OPT_NO_SEED, '-', "If 'explicit' parameters are chosen do not use the seed"}, {"name", OPT_NAME, 's', "Use the ec parameters with specified 'short name'"}, {"conv_form", OPT_CONV_FORM, 's', "Specifies the point conversion form "}, OPT_R_OPTIONS, OPT_PROV_OPTIONS, {NULL} }; static int list_builtin_curves(BIO *out) { int ret = 0; EC_builtin_curve *curves = NULL; size_t n, crv_len = EC_get_builtin_curves(NULL, 0); curves = app_malloc((int)sizeof(*curves) * crv_len, "list curves"); if (!EC_get_builtin_curves(curves, crv_len)) goto end; for (n = 0; n < crv_len; n++) { const char *comment = curves[n].comment; const char *sname = OBJ_nid2sn(curves[n].nid); if (comment == NULL) comment = "CURVE DESCRIPTION NOT AVAILABLE"; if (sname == NULL) sname = ""; BIO_printf(out, " %-10s: ", sname); BIO_printf(out, "%s\n", comment); } ret = 1; end: OPENSSL_free(curves); return ret; } int ecparam_main(int argc, char **argv) { EVP_PKEY_CTX *gctx_params = NULL, *gctx_key = NULL, *pctx = NULL; EVP_PKEY *params_key = NULL, *key = NULL; OSSL_ENCODER_CTX *ectx_key = NULL, *ectx_params = NULL; OSSL_DECODER_CTX *dctx_params = NULL; ENGINE *e = NULL; BIO *out = NULL; char *curve_name = NULL; char *asn1_encoding = NULL; char *point_format = NULL; char *infile = NULL, *outfile = NULL, *prog; OPTION_CHOICE o; int informat = FORMAT_PEM, outformat = FORMAT_PEM, noout = 0; int ret = 1, private = 0; int no_seed = 0, check = 0, check_named = 0, text = 0, genkey = 0; int list_curves = 0; prog = opt_init(argc, argv, ecparam_options); while ((o = opt_next()) != OPT_EOF) { switch (o) { case OPT_EOF: case OPT_ERR: opthelp: BIO_printf(bio_err, "%s: Use -help for summary.\n", prog); goto end; case OPT_HELP: opt_help(ecparam_options); ret = 0; goto end; case OPT_INFORM: if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &informat)) goto opthelp; break; case OPT_IN: infile = opt_arg(); break; case OPT_OUTFORM: if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &outformat)) goto opthelp; break; case OPT_OUT: outfile = opt_arg(); break; case OPT_TEXT: text = 1; break; case OPT_CHECK: check = 1; break; case OPT_CHECK_NAMED: check_named = 1; break; case OPT_LIST_CURVES: list_curves = 1; break; case OPT_NO_SEED: no_seed = 1; break; case OPT_NOOUT: noout = 1; break; case OPT_NAME: curve_name = opt_arg(); break; case OPT_CONV_FORM: point_format = opt_arg(); if (!opt_string(point_format, point_format_options)) goto opthelp; break; case OPT_PARAM_ENC: asn1_encoding = opt_arg(); if (!opt_string(asn1_encoding, asn1_encoding_options)) goto opthelp; break; case OPT_GENKEY: genkey = 1; break; case OPT_R_CASES: if (!opt_rand(o)) goto end; break; case OPT_PROV_CASES: if (!opt_provider(o)) goto end; break; case OPT_ENGINE: e = setup_engine(opt_arg(), 0); break; } } /* No extra args. */ if (!opt_check_rest_arg(NULL)) goto opthelp; if (!app_RAND_load()) goto end; private = genkey ? 1 : 0; out = bio_open_owner(outfile, outformat, private); if (out == NULL) goto end; if (list_curves) { if (list_builtin_curves(out)) ret = 0; goto end; } if (curve_name != NULL) { OSSL_PARAM params[4]; OSSL_PARAM *p = params; if (strcmp(curve_name, "secp192r1") == 0) { BIO_printf(bio_err, "using curve name prime192v1 instead of secp192r1\n"); curve_name = SN_X9_62_prime192v1; } else if (strcmp(curve_name, "secp256r1") == 0) { BIO_printf(bio_err, "using curve name prime256v1 instead of secp256r1\n"); curve_name = SN_X9_62_prime256v1; } *p++ = OSSL_PARAM_construct_utf8_string(OSSL_PKEY_PARAM_GROUP_NAME, curve_name, 0); if (asn1_encoding != NULL) *p++ = OSSL_PARAM_construct_utf8_string(OSSL_PKEY_PARAM_EC_ENCODING, asn1_encoding, 0); if (point_format != NULL) *p++ = OSSL_PARAM_construct_utf8_string( OSSL_PKEY_PARAM_EC_POINT_CONVERSION_FORMAT, point_format, 0); *p = OSSL_PARAM_construct_end(); if (OPENSSL_strcasecmp(curve_name, "SM2") == 0) gctx_params = EVP_PKEY_CTX_new_from_name(app_get0_libctx(), "sm2", app_get0_propq()); else gctx_params = EVP_PKEY_CTX_new_from_name(app_get0_libctx(), "ec", app_get0_propq()); if (gctx_params == NULL || EVP_PKEY_keygen_init(gctx_params) <= 0 || EVP_PKEY_CTX_set_params(gctx_params, params) <= 0 || EVP_PKEY_keygen(gctx_params, &params_key) <= 0) { BIO_printf(bio_err, "unable to generate key\n"); goto end; } } else { params_key = load_keyparams_suppress(infile, informat, 1, "EC", "EC parameters", 1); if (params_key == NULL) params_key = load_keyparams_suppress(infile, informat, 1, "SM2", "SM2 parameters", 1); if (params_key == NULL) { BIO_printf(bio_err, "Unable to load parameters from %s\n", infile); goto end; } if (point_format && !EVP_PKEY_set_utf8_string_param( params_key, OSSL_PKEY_PARAM_EC_POINT_CONVERSION_FORMAT, point_format)) { BIO_printf(bio_err, "unable to set point conversion format\n"); goto end; } if (asn1_encoding != NULL && !EVP_PKEY_set_utf8_string_param( params_key, OSSL_PKEY_PARAM_EC_ENCODING, asn1_encoding)) { BIO_printf(bio_err, "unable to set asn1 encoding format\n"); goto end; } } if (no_seed && !EVP_PKEY_set_octet_string_param(params_key, OSSL_PKEY_PARAM_EC_SEED, NULL, 0)) { BIO_printf(bio_err, "unable to clear seed\n"); goto end; } if (text && !EVP_PKEY_print_params(out, params_key, 0, NULL)) { BIO_printf(bio_err, "unable to print params\n"); goto end; } if (check || check_named) { BIO_printf(bio_err, "checking elliptic curve parameters: "); if (check_named && !EVP_PKEY_set_utf8_string_param(params_key, OSSL_PKEY_PARAM_EC_GROUP_CHECK_TYPE, OSSL_PKEY_EC_GROUP_CHECK_NAMED)) { BIO_printf(bio_err, "unable to set check_type\n"); goto end; } pctx = EVP_PKEY_CTX_new_from_pkey(app_get0_libctx(), params_key, app_get0_propq()); if (pctx == NULL || EVP_PKEY_param_check(pctx) <= 0) { BIO_printf(bio_err, "failed\n"); goto end; } BIO_printf(bio_err, "ok\n"); } if (outformat == FORMAT_ASN1 && genkey) noout = 1; if (!noout) { ectx_params = OSSL_ENCODER_CTX_new_for_pkey( params_key, OSSL_KEYMGMT_SELECT_DOMAIN_PARAMETERS, outformat == FORMAT_ASN1 ? "DER" : "PEM", NULL, NULL); if (!OSSL_ENCODER_to_bio(ectx_params, out)) { BIO_printf(bio_err, "unable to write elliptic curve parameters\n"); goto end; } } if (genkey) { /* * NOTE: EC keygen does not normally need to pass in the param_key * for named curves. This can be achieved using: * gctx = EVP_PKEY_CTX_new_from_name(NULL, "EC", NULL); * EVP_PKEY_keygen_init(gctx); * EVP_PKEY_CTX_set_group_name(gctx, curvename); * EVP_PKEY_keygen(gctx, &key) <= 0) */ gctx_key = EVP_PKEY_CTX_new_from_pkey(app_get0_libctx(), params_key, app_get0_propq()); if (EVP_PKEY_keygen_init(gctx_key) <= 0 || EVP_PKEY_keygen(gctx_key, &key) <= 0) { BIO_printf(bio_err, "unable to generate key\n"); goto end; } assert(private); ectx_key = OSSL_ENCODER_CTX_new_for_pkey( key, OSSL_KEYMGMT_SELECT_ALL, outformat == FORMAT_ASN1 ? "DER" : "PEM", NULL, NULL); if (!OSSL_ENCODER_to_bio(ectx_key, out)) { BIO_printf(bio_err, "unable to write elliptic " "curve parameters\n"); goto end; } } ret = 0; end: if (ret != 0) ERR_print_errors(bio_err); release_engine(e); EVP_PKEY_free(params_key); EVP_PKEY_free(key); EVP_PKEY_CTX_free(pctx); EVP_PKEY_CTX_free(gctx_params); EVP_PKEY_CTX_free(gctx_key); OSSL_DECODER_CTX_free(dctx_params); OSSL_ENCODER_CTX_free(ectx_params); OSSL_ENCODER_CTX_free(ectx_key); BIO_free_all(out); return ret; }
./openssl/apps/testdsa.h
/* * Copyright 1998-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/param_build.h> /* used by speed.c */ EVP_PKEY *get_dsa(int); static unsigned char dsa512_priv[] = { 0x65, 0xe5, 0xc7, 0x38, 0x60, 0x24, 0xb5, 0x89, 0xd4, 0x9c, 0xeb, 0x4c, 0x9c, 0x1d, 0x7a, 0x22, 0xbd, 0xd1, 0xc2, 0xd2, }; static unsigned char dsa512_pub[] = { 0x00, 0x95, 0xa7, 0x0d, 0xec, 0x93, 0x68, 0xba, 0x5f, 0xf7, 0x5f, 0x07, 0xf2, 0x3b, 0xad, 0x6b, 0x01, 0xdc, 0xbe, 0xec, 0xde, 0x04, 0x7a, 0x3a, 0x27, 0xb3, 0xec, 0x49, 0xfd, 0x08, 0x43, 0x3d, 0x7e, 0xa8, 0x2c, 0x5e, 0x7b, 0xbb, 0xfc, 0xf4, 0x6e, 0xeb, 0x6c, 0xb0, 0x6e, 0xf8, 0x02, 0x12, 0x8c, 0x38, 0x5d, 0x83, 0x56, 0x7d, 0xee, 0x53, 0x05, 0x3e, 0x24, 0x84, 0xbe, 0xba, 0x0a, 0x6b, 0xc8, }; static unsigned char dsa512_p[] = { 0x9D, 0x1B, 0x69, 0x8E, 0x26, 0xDB, 0xF2, 0x2B, 0x11, 0x70, 0x19, 0x86, 0xF6, 0x19, 0xC8, 0xF8, 0x19, 0xF2, 0x18, 0x53, 0x94, 0x46, 0x06, 0xD0, 0x62, 0x50, 0x33, 0x4B, 0x02, 0x3C, 0x52, 0x30, 0x03, 0x8B, 0x3B, 0xF9, 0x5F, 0xD1, 0x24, 0x06, 0x4F, 0x7B, 0x4C, 0xBA, 0xAA, 0x40, 0x9B, 0xFD, 0x96, 0xE4, 0x37, 0x33, 0xBB, 0x2D, 0x5A, 0xD7, 0x5A, 0x11, 0x40, 0x66, 0xA2, 0x76, 0x7D, 0x31, }; static unsigned char dsa512_q[] = { 0xFB, 0x53, 0xEF, 0x50, 0xB4, 0x40, 0x92, 0x31, 0x56, 0x86, 0x53, 0x7A, 0xE8, 0x8B, 0x22, 0x9A, 0x49, 0xFB, 0x71, 0x8F, }; static unsigned char dsa512_g[] = { 0x83, 0x3E, 0x88, 0xE5, 0xC5, 0x89, 0x73, 0xCE, 0x3B, 0x6C, 0x01, 0x49, 0xBF, 0xB3, 0xC7, 0x9F, 0x0A, 0xEA, 0x44, 0x91, 0xE5, 0x30, 0xAA, 0xD9, 0xBE, 0x5B, 0x5F, 0xB7, 0x10, 0xD7, 0x89, 0xB7, 0x8E, 0x74, 0xFB, 0xCF, 0x29, 0x1E, 0xEB, 0xA8, 0x2C, 0x54, 0x51, 0xB8, 0x10, 0xDE, 0xA0, 0xCE, 0x2F, 0xCC, 0x24, 0x6B, 0x90, 0x77, 0xDE, 0xA2, 0x68, 0xA6, 0x52, 0x12, 0xA2, 0x03, 0x9D, 0x20, }; static unsigned char dsa1024_priv[] = { 0x7d, 0x21, 0xda, 0xbb, 0x62, 0x15, 0x47, 0x36, 0x07, 0x67, 0x12, 0xe8, 0x8c, 0xaa, 0x1c, 0xcd, 0x38, 0x12, 0x61, 0x18, }; static unsigned char dsa1024_pub[] = { 0x3c, 0x4e, 0x9c, 0x2a, 0x7f, 0x16, 0xc1, 0x25, 0xeb, 0xac, 0x78, 0x63, 0x90, 0x14, 0x8c, 0x8b, 0xf4, 0x68, 0x43, 0x3c, 0x2d, 0xee, 0x65, 0x50, 0x7d, 0x9c, 0x8f, 0x8c, 0x8a, 0x51, 0xd6, 0x11, 0x2b, 0x99, 0xaf, 0x1e, 0x90, 0x97, 0xb5, 0xd3, 0xa6, 0x20, 0x25, 0xd6, 0xfe, 0x43, 0x02, 0xd5, 0x91, 0x7d, 0xa7, 0x8c, 0xdb, 0xc9, 0x85, 0xa3, 0x36, 0x48, 0xf7, 0x68, 0xaa, 0x60, 0xb1, 0xf7, 0x05, 0x68, 0x3a, 0xa3, 0x3f, 0xd3, 0x19, 0x82, 0xd8, 0x82, 0x7a, 0x77, 0xfb, 0xef, 0xf4, 0x15, 0x0a, 0xeb, 0x06, 0x04, 0x7f, 0x53, 0x07, 0x0c, 0xbc, 0xcb, 0x2d, 0x83, 0xdb, 0x3e, 0xd1, 0x28, 0xa5, 0xa1, 0x31, 0xe0, 0x67, 0xfa, 0x50, 0xde, 0x9b, 0x07, 0x83, 0x7e, 0x2c, 0x0b, 0xc3, 0x13, 0x50, 0x61, 0xe5, 0xad, 0xbd, 0x36, 0xb8, 0x97, 0x4e, 0x40, 0x7d, 0xe8, 0x83, 0x0d, 0xbc, 0x4b }; static unsigned char dsa1024_p[] = { 0xA7, 0x3F, 0x6E, 0x85, 0xBF, 0x41, 0x6A, 0x29, 0x7D, 0xF0, 0x9F, 0x47, 0x19, 0x30, 0x90, 0x9A, 0x09, 0x1D, 0xDA, 0x6A, 0x33, 0x1E, 0xC5, 0x3D, 0x86, 0x96, 0xB3, 0x15, 0xE0, 0x53, 0x2E, 0x8F, 0xE0, 0x59, 0x82, 0x73, 0x90, 0x3E, 0x75, 0x31, 0x99, 0x47, 0x7A, 0x52, 0xFB, 0x85, 0xE4, 0xD9, 0xA6, 0x7B, 0x38, 0x9B, 0x68, 0x8A, 0x84, 0x9B, 0x87, 0xC6, 0x1E, 0xB5, 0x7E, 0x86, 0x4B, 0x53, 0x5B, 0x59, 0xCF, 0x71, 0x65, 0x19, 0x88, 0x6E, 0xCE, 0x66, 0xAE, 0x6B, 0x88, 0x36, 0xFB, 0xEC, 0x28, 0xDC, 0xC2, 0xD7, 0xA5, 0xBB, 0xE5, 0x2C, 0x39, 0x26, 0x4B, 0xDA, 0x9A, 0x70, 0x18, 0x95, 0x37, 0x95, 0x10, 0x56, 0x23, 0xF6, 0x15, 0xED, 0xBA, 0x04, 0x5E, 0xDE, 0x39, 0x4F, 0xFD, 0xB7, 0x43, 0x1F, 0xB5, 0xA4, 0x65, 0x6F, 0xCD, 0x80, 0x11, 0xE4, 0x70, 0x95, 0x5B, 0x50, 0xCD, 0x49, }; static unsigned char dsa1024_q[] = { 0xF7, 0x07, 0x31, 0xED, 0xFA, 0x6C, 0x06, 0x03, 0xD5, 0x85, 0x8A, 0x1C, 0xAC, 0x9C, 0x65, 0xE7, 0x50, 0x66, 0x65, 0x6F, }; static unsigned char dsa1024_g[] = { 0x4D, 0xDF, 0x4C, 0x03, 0xA6, 0x91, 0x8A, 0xF5, 0x19, 0x6F, 0x50, 0x46, 0x25, 0x99, 0xE5, 0x68, 0x6F, 0x30, 0xE3, 0x69, 0xE1, 0xE5, 0xB3, 0x5D, 0x98, 0xBB, 0x28, 0x86, 0x48, 0xFC, 0xDE, 0x99, 0x04, 0x3F, 0x5F, 0x88, 0x0C, 0x9C, 0x73, 0x24, 0x0D, 0x20, 0x5D, 0xB9, 0x2A, 0x9A, 0x3F, 0x18, 0x96, 0x27, 0xE4, 0x62, 0x87, 0xC1, 0x7B, 0x74, 0x62, 0x53, 0xFC, 0x61, 0x27, 0xA8, 0x7A, 0x91, 0x09, 0x9D, 0xB6, 0xF1, 0x4D, 0x9C, 0x54, 0x0F, 0x58, 0x06, 0xEE, 0x49, 0x74, 0x07, 0xCE, 0x55, 0x7E, 0x23, 0xCE, 0x16, 0xF6, 0xCA, 0xDC, 0x5A, 0x61, 0x01, 0x7E, 0xC9, 0x71, 0xB5, 0x4D, 0xF6, 0xDC, 0x34, 0x29, 0x87, 0x68, 0xF6, 0x5E, 0x20, 0x93, 0xB3, 0xDB, 0xF5, 0xE4, 0x09, 0x6C, 0x41, 0x17, 0x95, 0x92, 0xEB, 0x01, 0xB5, 0x73, 0xA5, 0x6A, 0x7E, 0xD8, 0x32, 0xED, 0x0E, 0x02, 0xB8, }; static unsigned char dsa2048_priv[] = { 0x32, 0x67, 0x92, 0xf6, 0xc4, 0xe2, 0xe2, 0xe8, 0xa0, 0x8b, 0x6b, 0x45, 0x0c, 0x8a, 0x76, 0xb0, 0xee, 0xcf, 0x91, 0xa7, }; static unsigned char dsa2048_pub[] = { 0x17, 0x8f, 0xa8, 0x11, 0x84, 0x92, 0xec, 0x83, 0x47, 0xc7, 0x6a, 0xb0, 0x92, 0xaf, 0x5a, 0x20, 0x37, 0xa3, 0x64, 0x79, 0xd2, 0xd0, 0x3d, 0xcd, 0xe0, 0x61, 0x88, 0x88, 0x21, 0xcc, 0x74, 0x5d, 0xce, 0x4c, 0x51, 0x47, 0xf0, 0xc5, 0x5c, 0x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 0x1A, 0x8F, 0x0D, 0x38, 0xBB, 0x21, 0x5D, 0x18, 0xFC, 0x0F, 0x46, 0xF7, 0xA3, 0xB0, 0x1D, 0x23, 0xC3, 0xD2, 0xC7, 0x72, 0x51, 0x18, 0xDF, 0x46, 0x95, 0x79, 0xD9, 0xBD, 0xB5, 0x19, 0x02, 0x2C, 0x87, 0xDC, 0xE7, 0x57, 0x82, 0x7E, 0xF1, 0x8B, 0x06, 0x3D, 0x00, 0xA5, 0x7B, 0x6B, 0x26, 0x27, 0x91, 0x0F, 0x6A, 0x77, 0xE4, 0xD5, 0x04, 0xE4, 0x12, 0x2C, 0x42, 0xFF, 0xD2, 0x88, 0xBB, 0xD3, 0x92, 0xA0, 0xF9, 0xC8, 0x51, 0x64, 0x14, 0x5C, 0xD8, 0xF9, 0x6C, 0x47, 0x82, 0xB4, 0x1C, 0x7F, 0x09, 0xB8, 0xF0, 0x25, 0x83, 0x1D, 0x3F, 0x3F, 0x05, 0xB3, 0x21, 0x0A, 0x5D, 0xA7, 0xD8, 0x54, 0xC3, 0x65, 0x7D, 0xC3, 0xB0, 0x1D, 0xBF, 0xAE, 0xF8, 0x68, 0xCF, 0x9B, }; static unsigned char dsa2048_q[] = { 0x97, 0xE7, 0x33, 0x4D, 0xD3, 0x94, 0x3E, 0x0B, 0xDB, 0x62, 0x74, 0xC6, 0xA1, 0x08, 0xDD, 0x19, 0xA3, 0x75, 0x17, 0x1B, }; static unsigned char dsa2048_g[] = { 0x2C, 0x78, 0x16, 0x59, 0x34, 0x63, 0xF4, 0xF3, 0x92, 0xFC, 0xB5, 0xA5, 0x4F, 0x13, 0xDE, 0x2F, 0x1C, 0xA4, 0x3C, 0xAE, 0xAD, 0x38, 0x3F, 0x7E, 0x90, 0xBF, 0x96, 0xA6, 0xAE, 0x25, 0x90, 0x72, 0xF5, 0x8E, 0x80, 0x0C, 0x39, 0x1C, 0xD9, 0xEC, 0xBA, 0x90, 0x5B, 0x3A, 0xE8, 0x58, 0x6C, 0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xE7, 0xFD, 0xD2, 0xAD, 0x9F, 0x36, 0xC1, 0xA0, 0x29, 0x99, 0xD1, 0x96, 0x70, 0x59, 0x06, 0x78, 0x35, 0xBD, 0x65, 0x55, 0x52, 0x9E, 0xF8, 0xB2, 0xE5, 0x38, }; typedef struct testdsa_st { unsigned char *priv; unsigned char *pub; unsigned char *p; unsigned char *g; unsigned char *q; int priv_l; int pub_l; int p_l; int g_l; int q_l; } testdsa; #define set_dsa_ptr(st, bits) \ do { \ st.priv = dsa##bits##_priv; \ st.pub = dsa##bits##_pub; \ st.p = dsa##bits##_p; \ st.g = dsa##bits##_g; \ st.q = dsa##bits##_q; \ st.priv_l = sizeof(dsa##bits##_priv); \ st.pub_l = sizeof(dsa##bits##_pub); \ st.p_l = sizeof(dsa##bits##_p); \ st.g_l = sizeof(dsa##bits##_g); \ st.q_l = sizeof(dsa##bits##_q); \ } while (0) EVP_PKEY *get_dsa(int dsa_bits) { EVP_PKEY *pkey = NULL; BIGNUM *priv_key, *pub_key, *p, *q, *g; EVP_PKEY_CTX *pctx; testdsa dsa_t; OSSL_PARAM_BLD *tmpl = NULL; OSSL_PARAM *params = NULL; switch (dsa_bits) { case 512: set_dsa_ptr(dsa_t, 512); break; case 1024: set_dsa_ptr(dsa_t, 1024); break; case 2048: set_dsa_ptr(dsa_t, 2048); break; default: return NULL; } if ((pctx = EVP_PKEY_CTX_new_from_name(NULL, "DSA", NULL)) == NULL) return NULL; priv_key = BN_bin2bn(dsa_t.priv, dsa_t.priv_l, NULL); pub_key = BN_bin2bn(dsa_t.pub, dsa_t.pub_l, NULL); p = BN_bin2bn(dsa_t.p, dsa_t.p_l, NULL); q = BN_bin2bn(dsa_t.q, dsa_t.q_l, NULL); g = BN_bin2bn(dsa_t.g, dsa_t.g_l, NULL); if (priv_key == NULL || pub_key == NULL || p == NULL || q == NULL || g == NULL) { goto err; } if ((tmpl = OSSL_PARAM_BLD_new()) == NULL || !OSSL_PARAM_BLD_push_BN(tmpl, OSSL_PKEY_PARAM_FFC_P, p) || !OSSL_PARAM_BLD_push_BN(tmpl, OSSL_PKEY_PARAM_FFC_Q, q) || !OSSL_PARAM_BLD_push_BN(tmpl, OSSL_PKEY_PARAM_FFC_G, g) || !OSSL_PARAM_BLD_push_BN(tmpl, OSSL_PKEY_PARAM_PRIV_KEY, priv_key) || !OSSL_PARAM_BLD_push_BN(tmpl, OSSL_PKEY_PARAM_PUB_KEY, pub_key) || (params = OSSL_PARAM_BLD_to_param(tmpl)) == NULL) goto err; if (EVP_PKEY_fromdata_init(pctx) <= 0 || EVP_PKEY_fromdata(pctx, &pkey, EVP_PKEY_KEYPAIR, params) <= 0) pkey = NULL; err: OSSL_PARAM_free(params); OSSL_PARAM_BLD_free(tmpl); BN_free(priv_key); BN_free(pub_key); BN_free(p); BN_free(q); BN_free(g); EVP_PKEY_CTX_free(pctx); return pkey; }
./openssl/apps/storeutl.c
/* * Copyright 2016-2022 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <openssl/opensslconf.h> #include "apps.h" #include "progs.h" #include <openssl/err.h> #include <openssl/pem.h> #include <openssl/store.h> #include <openssl/x509v3.h> /* s2i_ASN1_INTEGER */ static int process(const char *uri, const UI_METHOD *uimeth, PW_CB_DATA *uidata, int expected, int criterion, OSSL_STORE_SEARCH *search, int text, int noout, int recursive, int indent, BIO *out, const char *prog, OSSL_LIB_CTX *libctx); typedef enum OPTION_choice { OPT_COMMON, OPT_ENGINE, OPT_OUT, OPT_PASSIN, OPT_NOOUT, OPT_TEXT, OPT_RECURSIVE, OPT_SEARCHFOR_CERTS, OPT_SEARCHFOR_KEYS, OPT_SEARCHFOR_CRLS, OPT_CRITERION_SUBJECT, OPT_CRITERION_ISSUER, OPT_CRITERION_SERIAL, OPT_CRITERION_FINGERPRINT, OPT_CRITERION_ALIAS, OPT_MD, OPT_PROV_ENUM } OPTION_CHOICE; const OPTIONS storeutl_options[] = { {OPT_HELP_STR, 1, '-', "Usage: %s [options] uri\n"}, OPT_SECTION("General"), {"help", OPT_HELP, '-', "Display this summary"}, {"", OPT_MD, '-', "Any supported digest"}, #ifndef OPENSSL_NO_ENGINE {"engine", OPT_ENGINE, 's', "Use engine, possibly a hardware device"}, #endif OPT_SECTION("Search"), {"certs", OPT_SEARCHFOR_CERTS, '-', "Search for certificates only"}, {"keys", OPT_SEARCHFOR_KEYS, '-', "Search for keys only"}, {"crls", OPT_SEARCHFOR_CRLS, '-', "Search for CRLs only"}, {"subject", OPT_CRITERION_SUBJECT, 's', "Search by subject"}, {"issuer", OPT_CRITERION_ISSUER, 's', "Search by issuer and serial, issuer name"}, {"serial", OPT_CRITERION_SERIAL, 's', "Search by issuer and serial, serial number"}, {"fingerprint", OPT_CRITERION_FINGERPRINT, 's', "Search by public key fingerprint, given in hex"}, {"alias", OPT_CRITERION_ALIAS, 's', "Search by alias"}, {"r", OPT_RECURSIVE, '-', "Recurse through names"}, OPT_SECTION("Input"), {"passin", OPT_PASSIN, 's', "Input file pass phrase source"}, OPT_SECTION("Output"), {"out", OPT_OUT, '>', "Output file - default stdout"}, {"text", OPT_TEXT, '-', "Print a text form of the objects"}, {"noout", OPT_NOOUT, '-', "No PEM output, just status"}, OPT_PROV_OPTIONS, OPT_PARAMETERS(), {"uri", 0, 0, "URI of the store object"}, {NULL} }; int storeutl_main(int argc, char *argv[]) { int ret = 1, noout = 0, text = 0, recursive = 0; char *outfile = NULL, *passin = NULL, *passinarg = NULL; BIO *out = NULL; ENGINE *e = NULL; OPTION_CHOICE o; char *prog; PW_CB_DATA pw_cb_data; int expected = 0; int criterion = 0; X509_NAME *subject = NULL, *issuer = NULL; ASN1_INTEGER *serial = NULL; unsigned char *fingerprint = NULL; size_t fingerprintlen = 0; char *alias = NULL, *digestname = NULL; OSSL_STORE_SEARCH *search = NULL; EVP_MD *digest = NULL; OSSL_LIB_CTX *libctx = app_get0_libctx(); opt_set_unknown_name("digest"); prog = opt_init(argc, argv, storeutl_options); while ((o = opt_next()) != OPT_EOF) { switch (o) { case OPT_EOF: case OPT_ERR: opthelp: BIO_printf(bio_err, "%s: Use -help for summary.\n", prog); goto end; case OPT_HELP: opt_help(storeutl_options); ret = 0; goto end; case OPT_OUT: outfile = opt_arg(); break; case OPT_PASSIN: passinarg = opt_arg(); break; case OPT_NOOUT: noout = 1; break; case OPT_TEXT: text = 1; break; case OPT_RECURSIVE: recursive = 1; break; case OPT_SEARCHFOR_CERTS: case OPT_SEARCHFOR_KEYS: case OPT_SEARCHFOR_CRLS: if (expected != 0) { BIO_printf(bio_err, "%s: only one search type can be given.\n", prog); goto end; } { static const struct { enum OPTION_choice choice; int type; } map[] = { {OPT_SEARCHFOR_CERTS, OSSL_STORE_INFO_CERT}, {OPT_SEARCHFOR_KEYS, OSSL_STORE_INFO_PKEY}, {OPT_SEARCHFOR_CRLS, OSSL_STORE_INFO_CRL}, }; size_t i; for (i = 0; i < OSSL_NELEM(map); i++) { if (o == map[i].choice) { expected = map[i].type; break; } } /* * If expected wasn't set at this point, it means the map * isn't synchronised with the possible options leading here. */ OPENSSL_assert(expected != 0); } break; case OPT_CRITERION_SUBJECT: if (criterion != 0) { BIO_printf(bio_err, "%s: criterion already given.\n", prog); goto end; } criterion = OSSL_STORE_SEARCH_BY_NAME; if (subject != NULL) { BIO_printf(bio_err, "%s: subject already given.\n", prog); goto end; } subject = parse_name(opt_arg(), MBSTRING_UTF8, 1, "subject"); if (subject == NULL) goto end; break; case OPT_CRITERION_ISSUER: if (criterion != 0 && criterion != OSSL_STORE_SEARCH_BY_ISSUER_SERIAL) { BIO_printf(bio_err, "%s: criterion already given.\n", prog); goto end; } criterion = OSSL_STORE_SEARCH_BY_ISSUER_SERIAL; if (issuer != NULL) { BIO_printf(bio_err, "%s: issuer already given.\n", prog); goto end; } issuer = parse_name(opt_arg(), MBSTRING_UTF8, 1, "issuer"); if (issuer == NULL) goto end; break; case OPT_CRITERION_SERIAL: if (criterion != 0 && criterion != OSSL_STORE_SEARCH_BY_ISSUER_SERIAL) { BIO_printf(bio_err, "%s: criterion already given.\n", prog); goto end; } criterion = OSSL_STORE_SEARCH_BY_ISSUER_SERIAL; if (serial != NULL) { BIO_printf(bio_err, "%s: serial number already given.\n", prog); goto end; } if ((serial = s2i_ASN1_INTEGER(NULL, opt_arg())) == NULL) { BIO_printf(bio_err, "%s: can't parse serial number argument.\n", prog); goto end; } break; case OPT_CRITERION_FINGERPRINT: if (criterion != 0 || (criterion == OSSL_STORE_SEARCH_BY_KEY_FINGERPRINT && fingerprint != NULL)) { BIO_printf(bio_err, "%s: criterion already given.\n", prog); goto end; } criterion = OSSL_STORE_SEARCH_BY_KEY_FINGERPRINT; if (fingerprint != NULL) { BIO_printf(bio_err, "%s: fingerprint already given.\n", prog); goto end; } { long tmplen = 0; if ((fingerprint = OPENSSL_hexstr2buf(opt_arg(), &tmplen)) == NULL) { BIO_printf(bio_err, "%s: can't parse fingerprint argument.\n", prog); goto end; } fingerprintlen = (size_t)tmplen; } break; case OPT_CRITERION_ALIAS: if (criterion != 0) { BIO_printf(bio_err, "%s: criterion already given.\n", prog); goto end; } criterion = OSSL_STORE_SEARCH_BY_ALIAS; if (alias != NULL) { BIO_printf(bio_err, "%s: alias already given.\n", prog); goto end; } if ((alias = OPENSSL_strdup(opt_arg())) == NULL) { BIO_printf(bio_err, "%s: can't parse alias argument.\n", prog); goto end; } break; case OPT_ENGINE: e = setup_engine(opt_arg(), 0); break; case OPT_MD: digestname = opt_unknown(); break; case OPT_PROV_CASES: if (!opt_provider(o)) goto end; break; } } /* One argument, the URI */ if (!opt_check_rest_arg("URI")) goto opthelp; argv = opt_rest(); if (!opt_md(digestname, &digest)) goto opthelp; if (criterion != 0) { switch (criterion) { case OSSL_STORE_SEARCH_BY_NAME: if ((search = OSSL_STORE_SEARCH_by_name(subject)) == NULL) { ERR_print_errors(bio_err); goto end; } break; case OSSL_STORE_SEARCH_BY_ISSUER_SERIAL: if (issuer == NULL || serial == NULL) { BIO_printf(bio_err, "%s: both -issuer and -serial must be given.\n", prog); goto end; } if ((search = OSSL_STORE_SEARCH_by_issuer_serial(issuer, serial)) == NULL) { ERR_print_errors(bio_err); goto end; } break; case OSSL_STORE_SEARCH_BY_KEY_FINGERPRINT: if ((search = OSSL_STORE_SEARCH_by_key_fingerprint(digest, fingerprint, fingerprintlen)) == NULL) { ERR_print_errors(bio_err); goto end; } break; case OSSL_STORE_SEARCH_BY_ALIAS: if ((search = OSSL_STORE_SEARCH_by_alias(alias)) == NULL) { ERR_print_errors(bio_err); goto end; } break; } } if (!app_passwd(passinarg, NULL, &passin, NULL)) { BIO_printf(bio_err, "Error getting passwords\n"); goto end; } pw_cb_data.password = passin; pw_cb_data.prompt_info = argv[0]; out = bio_open_default(outfile, 'w', FORMAT_TEXT); if (out == NULL) goto end; ret = process(argv[0], get_ui_method(), &pw_cb_data, expected, criterion, search, text, noout, recursive, 0, out, prog, libctx); end: EVP_MD_free(digest); OPENSSL_free(fingerprint); OPENSSL_free(alias); ASN1_INTEGER_free(serial); X509_NAME_free(subject); X509_NAME_free(issuer); OSSL_STORE_SEARCH_free(search); BIO_free_all(out); OPENSSL_free(passin); release_engine(e); return ret; } static int indent_printf(int indent, BIO *bio, const char *format, ...) { va_list args; int ret; va_start(args, format); ret = BIO_printf(bio, "%*s", indent, "") + BIO_vprintf(bio, format, args); va_end(args); return ret; } static int process(const char *uri, const UI_METHOD *uimeth, PW_CB_DATA *uidata, int expected, int criterion, OSSL_STORE_SEARCH *search, int text, int noout, int recursive, int indent, BIO *out, const char *prog, OSSL_LIB_CTX *libctx) { OSSL_STORE_CTX *store_ctx = NULL; int ret = 1, items = 0; if ((store_ctx = OSSL_STORE_open_ex(uri, libctx, app_get0_propq(), uimeth, uidata, NULL, NULL, NULL)) == NULL) { BIO_printf(bio_err, "Couldn't open file or uri %s\n", uri); ERR_print_errors(bio_err); return ret; } if (expected != 0) { if (!OSSL_STORE_expect(store_ctx, expected)) { ERR_print_errors(bio_err); goto end2; } } if (criterion != 0) { if (!OSSL_STORE_supports_search(store_ctx, criterion)) { BIO_printf(bio_err, "%s: the store scheme doesn't support the given search criteria.\n", prog); goto end2; } if (!OSSL_STORE_find(store_ctx, search)) { ERR_print_errors(bio_err); goto end2; } } /* From here on, we count errors, and we'll return the count at the end */ ret = 0; for (;;) { OSSL_STORE_INFO *info = OSSL_STORE_load(store_ctx); int type = info == NULL ? 0 : OSSL_STORE_INFO_get_type(info); const char *infostr = info == NULL ? NULL : OSSL_STORE_INFO_type_string(type); if (info == NULL) { if (OSSL_STORE_error(store_ctx)) { if (recursive) ERR_clear_error(); else ERR_print_errors(bio_err); if (OSSL_STORE_eof(store_ctx)) break; ret++; continue; } if (OSSL_STORE_eof(store_ctx)) break; BIO_printf(bio_err, "ERROR: OSSL_STORE_load() returned NULL without " "eof or error indications\n"); BIO_printf(bio_err, " This is an error in the loader\n"); ERR_print_errors(bio_err); ret++; break; } if (type == OSSL_STORE_INFO_NAME) { const char *name = OSSL_STORE_INFO_get0_NAME(info); const char *desc = OSSL_STORE_INFO_get0_NAME_description(info); indent_printf(indent, bio_out, "%d: %s: %s\n", items, infostr, name); if (desc != NULL) indent_printf(indent, bio_out, "%s\n", desc); } else { indent_printf(indent, bio_out, "%d: %s\n", items, infostr); } /* * Unfortunately, PEM_X509_INFO_write_bio() is sorely lacking in * functionality, so we must figure out how exactly to write things * ourselves... */ switch (type) { case OSSL_STORE_INFO_NAME: if (recursive) { const char *suburi = OSSL_STORE_INFO_get0_NAME(info); ret += process(suburi, uimeth, uidata, expected, criterion, search, text, noout, recursive, indent + 2, out, prog, libctx); } break; case OSSL_STORE_INFO_PARAMS: if (text) EVP_PKEY_print_params(out, OSSL_STORE_INFO_get0_PARAMS(info), 0, NULL); if (!noout) PEM_write_bio_Parameters(out, OSSL_STORE_INFO_get0_PARAMS(info)); break; case OSSL_STORE_INFO_PUBKEY: if (text) EVP_PKEY_print_public(out, OSSL_STORE_INFO_get0_PUBKEY(info), 0, NULL); if (!noout) PEM_write_bio_PUBKEY(out, OSSL_STORE_INFO_get0_PUBKEY(info)); break; case OSSL_STORE_INFO_PKEY: if (text) EVP_PKEY_print_private(out, OSSL_STORE_INFO_get0_PKEY(info), 0, NULL); if (!noout) PEM_write_bio_PrivateKey(out, OSSL_STORE_INFO_get0_PKEY(info), NULL, NULL, 0, NULL, NULL); break; case OSSL_STORE_INFO_CERT: if (text) X509_print(out, OSSL_STORE_INFO_get0_CERT(info)); if (!noout) PEM_write_bio_X509(out, OSSL_STORE_INFO_get0_CERT(info)); break; case OSSL_STORE_INFO_CRL: if (text) X509_CRL_print(out, OSSL_STORE_INFO_get0_CRL(info)); if (!noout) PEM_write_bio_X509_CRL(out, OSSL_STORE_INFO_get0_CRL(info)); break; default: BIO_printf(bio_err, "!!! Unknown code\n"); ret++; break; } items++; OSSL_STORE_INFO_free(info); } indent_printf(indent, out, "Total found: %d\n", items); end2: if (!OSSL_STORE_close(store_ctx)) { ERR_print_errors(bio_err); ret++; } return ret; }
./openssl/apps/pkcs7.c
/* * Copyright 1995-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 <time.h> #include "apps.h" #include "progs.h" #include <openssl/err.h> #include <openssl/objects.h> #include <openssl/evp.h> #include <openssl/x509.h> #include <openssl/pkcs7.h> #include <openssl/pem.h> typedef enum OPTION_choice { OPT_COMMON, OPT_INFORM, OPT_OUTFORM, OPT_IN, OPT_OUT, OPT_NOOUT, OPT_TEXT, OPT_PRINT, OPT_PRINT_CERTS, OPT_QUIET, OPT_ENGINE, OPT_PROV_ENUM } OPTION_CHOICE; const OPTIONS pkcs7_options[] = { OPT_SECTION("General"), {"help", OPT_HELP, '-', "Display this summary"}, #ifndef OPENSSL_NO_ENGINE {"engine", OPT_ENGINE, 's', "Use engine, possibly a hardware device"}, #endif OPT_SECTION("Input"), {"in", OPT_IN, '<', "Input file"}, {"inform", OPT_INFORM, 'F', "Input format - DER or PEM"}, OPT_SECTION("Output"), {"outform", OPT_OUTFORM, 'F', "Output format - DER or PEM"}, {"out", OPT_OUT, '>', "Output file"}, {"noout", OPT_NOOUT, '-', "Don't output encoded data"}, {"text", OPT_TEXT, '-', "Print full details of certificates"}, {"print", OPT_PRINT, '-', "Print out all fields of the PKCS7 structure"}, {"print_certs", OPT_PRINT_CERTS, '-', "Print_certs print any certs or crl in the input"}, {"quiet", OPT_QUIET, '-', "When used with -print_certs, it produces a cleaner output"}, OPT_PROV_OPTIONS, {NULL} }; int pkcs7_main(int argc, char **argv) { ENGINE *e = NULL; PKCS7 *p7 = NULL, *p7i; BIO *in = NULL, *out = NULL; int informat = FORMAT_PEM, outformat = FORMAT_PEM; char *infile = NULL, *outfile = NULL, *prog; int i, print_certs = 0, text = 0, noout = 0, p7_print = 0, quiet = 0, ret = 1; OPTION_CHOICE o; OSSL_LIB_CTX *libctx = app_get0_libctx(); prog = opt_init(argc, argv, pkcs7_options); while ((o = opt_next()) != OPT_EOF) { switch (o) { case OPT_EOF: case OPT_ERR: opthelp: BIO_printf(bio_err, "%s: Use -help for summary.\n", prog); goto end; case OPT_HELP: opt_help(pkcs7_options); ret = 0; goto end; case OPT_INFORM: if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &informat)) goto opthelp; break; case OPT_OUTFORM: if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &outformat)) goto opthelp; break; case OPT_IN: infile = opt_arg(); break; case OPT_OUT: outfile = opt_arg(); break; case OPT_NOOUT: noout = 1; break; case OPT_TEXT: text = 1; break; case OPT_PRINT: p7_print = 1; break; case OPT_PRINT_CERTS: print_certs = 1; break; case OPT_QUIET: quiet = 1; break; case OPT_ENGINE: e = setup_engine(opt_arg(), 0); break; case OPT_PROV_CASES: if (!opt_provider(o)) goto end; break; } } /* No extra arguments. */ if (!opt_check_rest_arg(NULL)) goto opthelp; in = bio_open_default(infile, 'r', informat); if (in == NULL) goto end; p7 = PKCS7_new_ex(libctx, app_get0_propq()); if (p7 == NULL) { BIO_printf(bio_err, "unable to allocate PKCS7 object\n"); ERR_print_errors(bio_err); goto end; } if (informat == FORMAT_ASN1) p7i = d2i_PKCS7_bio(in, &p7); else p7i = PEM_read_bio_PKCS7(in, &p7, NULL, NULL); if (p7i == NULL) { BIO_printf(bio_err, "unable to load PKCS7 object\n"); ERR_print_errors(bio_err); goto end; } out = bio_open_default(outfile, 'w', outformat); if (out == NULL) goto end; if (p7_print) PKCS7_print_ctx(out, p7, 0, NULL); if (print_certs) { STACK_OF(X509) *certs = NULL; STACK_OF(X509_CRL) *crls = NULL; i = OBJ_obj2nid(p7->type); switch (i) { case NID_pkcs7_signed: if (p7->d.sign != NULL) { certs = p7->d.sign->cert; crls = p7->d.sign->crl; } break; case NID_pkcs7_signedAndEnveloped: if (p7->d.signed_and_enveloped != NULL) { certs = p7->d.signed_and_enveloped->cert; crls = p7->d.signed_and_enveloped->crl; } break; default: break; } if (certs != NULL) { X509 *x; for (i = 0; i < sk_X509_num(certs); i++) { x = sk_X509_value(certs, i); if (text) X509_print(out, x); else if (!quiet) dump_cert_text(out, x); if (!noout) PEM_write_bio_X509(out, x); BIO_puts(out, "\n"); } } if (crls != NULL) { X509_CRL *crl; for (i = 0; i < sk_X509_CRL_num(crls); i++) { crl = sk_X509_CRL_value(crls, i); X509_CRL_print_ex(out, crl, get_nameopt()); if (!noout) PEM_write_bio_X509_CRL(out, crl); BIO_puts(out, "\n"); } } ret = 0; goto end; } if (!noout) { if (outformat == FORMAT_ASN1) i = i2d_PKCS7_bio(out, p7); else i = PEM_write_bio_PKCS7(out, p7); if (!i) { BIO_printf(bio_err, "unable to write pkcs7 object\n"); ERR_print_errors(bio_err); goto end; } } ret = 0; end: PKCS7_free(p7); release_engine(e); BIO_free(in); BIO_free_all(out); return ret; }
./openssl/apps/vms_decc_init.c
/* * Copyright 2010-2016 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #if defined( __VMS) && !defined( OPENSSL_NO_DECC_INIT) && \ defined( __DECC) && !defined( __VAX) && (__CRTL_VER >= 70301000) # define USE_DECC_INIT 1 #endif #ifdef USE_DECC_INIT /* * ---------------------------------------------------------------------- * decc_init() On non-VAX systems, uses LIB$INITIALIZE to set a collection * of C RTL features without using the DECC$* logical name method. * ---------------------------------------------------------------------- */ # include <stdio.h> # include <stdlib.h> # include <unixlib.h> /* Global storage. */ /* Flag to sense if decc_init() was called. */ int decc_init_done = -1; /* Structure to hold a DECC$* feature name and its desired value. */ typedef struct { char *name; int value; } decc_feat_t; /* * Array of DECC$* feature names and their desired values. Note: * DECC$ARGV_PARSE_STYLE is the urgent one. */ decc_feat_t decc_feat_array[] = { /* Preserve command-line case with SET PROCESS/PARSE_STYLE=EXTENDED */ {"DECC$ARGV_PARSE_STYLE", 1}, /* Preserve case for file names on ODS5 disks. */ {"DECC$EFS_CASE_PRESERVE", 1}, /* * Enable multiple dots (and most characters) in ODS5 file names, while * preserving VMS-ness of ";version". */ {"DECC$EFS_CHARSET", 1}, /* List terminator. */ {(char *)NULL, 0} }; /* LIB$INITIALIZE initialization function. */ static void decc_init(void) { char *openssl_debug_decc_init; int verbose = 0; int feat_index; int feat_value; int feat_value_max; int feat_value_min; int i; int sts; /* Get debug option. */ openssl_debug_decc_init = getenv("OPENSSL_DEBUG_DECC_INIT"); if (openssl_debug_decc_init != NULL) { verbose = strtol(openssl_debug_decc_init, NULL, 10); if (verbose <= 0) { verbose = 1; } } /* Set the global flag to indicate that LIB$INITIALIZE worked. */ decc_init_done = 1; /* Loop through all items in the decc_feat_array[]. */ for (i = 0; decc_feat_array[i].name != NULL; i++) { /* Get the feature index. */ feat_index = decc$feature_get_index(decc_feat_array[i].name); if (feat_index >= 0) { /* Valid item. Collect its properties. */ feat_value = decc$feature_get_value(feat_index, 1); feat_value_min = decc$feature_get_value(feat_index, 2); feat_value_max = decc$feature_get_value(feat_index, 3); /* Check the validity of our desired value. */ if ((decc_feat_array[i].value >= feat_value_min) && (decc_feat_array[i].value <= feat_value_max)) { /* Valid value. Set it if necessary. */ if (feat_value != decc_feat_array[i].value) { sts = decc$feature_set_value(feat_index, 1, decc_feat_array[i].value); if (verbose > 1) { fprintf(stderr, " %s = %d, sts = %d.\n", decc_feat_array[i].name, decc_feat_array[i].value, sts); } } } else { /* Invalid DECC feature value. */ fprintf(stderr, " INVALID DECC$FEATURE VALUE, %d: %d <= %s <= %d.\n", feat_value, feat_value_min, decc_feat_array[i].name, feat_value_max); } } else { /* Invalid DECC feature name. */ fprintf(stderr, " UNKNOWN DECC$FEATURE: %s.\n", decc_feat_array[i].name); } } if (verbose > 0) { fprintf(stderr, " DECC_INIT complete.\n"); } } /* Get "decc_init()" into a valid, loaded LIB$INITIALIZE PSECT. */ # pragma nostandard /* * Establish the LIB$INITIALIZE PSECTs, with proper alignment and other * attributes. Note that "nopic" is significant only on VAX. */ # pragma extern_model save # if __INITIAL_POINTER_SIZE == 64 # define PSECT_ALIGN 3 # else # define PSECT_ALIGN 2 # endif # pragma extern_model strict_refdef "LIB$INITIALIZ" PSECT_ALIGN, nopic, nowrt const int spare[8] = { 0 }; # pragma extern_model strict_refdef "LIB$INITIALIZE" PSECT_ALIGN, nopic, nowrt void (*const x_decc_init) () = decc_init; # pragma extern_model restore /* Fake reference to ensure loading the LIB$INITIALIZE PSECT. */ # pragma extern_model save int LIB$INITIALIZE(void); # pragma extern_model strict_refdef int dmy_lib$initialize = (int)LIB$INITIALIZE; # pragma extern_model restore # pragma standard #else /* def USE_DECC_INIT */ /* Dummy code to avoid a %CC-W-EMPTYFILE complaint. */ int decc_init_dummy(void); #endif /* def USE_DECC_INIT */
./openssl/apps/x509.c
/* * Copyright 1995-2023 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include "apps.h" #include "progs.h" #include <openssl/bio.h> #include <openssl/asn1.h> #include <openssl/err.h> #include <openssl/bn.h> #include <openssl/evp.h> #include <openssl/x509.h> #include <openssl/x509v3.h> #include <openssl/objects.h> #include <openssl/pem.h> #include <openssl/rsa.h> #ifndef OPENSSL_NO_DSA # include <openssl/dsa.h> #endif #undef POSTFIX #define POSTFIX ".srl" #define DEFAULT_DAYS 30 /* default cert validity period in days */ #define UNSET_DAYS -2 /* -1 is used for testing expiration checks */ #define EXT_COPY_UNSET -1 static int callb(int ok, X509_STORE_CTX *ctx); static ASN1_INTEGER *x509_load_serial(const char *CAfile, const char *serialfile, int create); static int purpose_print(BIO *bio, X509 *cert, X509_PURPOSE *pt); static int print_x509v3_exts(BIO *bio, X509 *x, const char *ext_names); typedef enum OPTION_choice { OPT_COMMON, OPT_INFORM, OPT_OUTFORM, OPT_KEYFORM, OPT_REQ, OPT_CAFORM, OPT_CAKEYFORM, OPT_VFYOPT, OPT_SIGOPT, OPT_DAYS, OPT_PASSIN, OPT_EXTFILE, OPT_EXTENSIONS, OPT_IN, OPT_OUT, OPT_KEY, OPT_SIGNKEY, OPT_CA, OPT_CAKEY, OPT_CASERIAL, OPT_SET_SERIAL, OPT_NEW, OPT_FORCE_PUBKEY, OPT_ISSU, OPT_SUBJ, OPT_ADDTRUST, OPT_ADDREJECT, OPT_SETALIAS, OPT_CERTOPT, OPT_DATEOPT, OPT_NAMEOPT, OPT_EMAIL, OPT_OCSP_URI, OPT_SERIAL, OPT_NEXT_SERIAL, OPT_MODULUS, OPT_PUBKEY, OPT_X509TOREQ, OPT_TEXT, OPT_HASH, OPT_ISSUER_HASH, OPT_SUBJECT, OPT_ISSUER, OPT_FINGERPRINT, OPT_DATES, OPT_PURPOSE, OPT_STARTDATE, OPT_ENDDATE, OPT_CHECKEND, OPT_CHECKHOST, OPT_CHECKEMAIL, OPT_CHECKIP, OPT_NOOUT, OPT_TRUSTOUT, OPT_CLRTRUST, OPT_CLRREJECT, OPT_ALIAS, OPT_CACREATESERIAL, OPT_CLREXT, OPT_OCSPID, OPT_SUBJECT_HASH_OLD, OPT_ISSUER_HASH_OLD, OPT_COPY_EXTENSIONS, OPT_BADSIG, OPT_MD, OPT_ENGINE, OPT_NOCERT, OPT_PRESERVE_DATES, OPT_R_ENUM, OPT_PROV_ENUM, OPT_EXT } OPTION_CHOICE; const OPTIONS x509_options[] = { OPT_SECTION("General"), {"help", OPT_HELP, '-', "Display this summary"}, {"in", OPT_IN, '<', "Certificate input, or CSR input file with -req (default stdin)"}, {"passin", OPT_PASSIN, 's', "Private key and cert file pass-phrase source"}, {"new", OPT_NEW, '-', "Generate a certificate from scratch"}, {"x509toreq", OPT_X509TOREQ, '-', "Output a certification request (rather than a certificate)"}, {"req", OPT_REQ, '-', "Input is a CSR file (rather than a certificate)"}, {"copy_extensions", OPT_COPY_EXTENSIONS, 's', "copy extensions when converting from CSR to x509 or vice versa"}, {"inform", OPT_INFORM, 'f', "CSR input format to use (PEM or DER; by default try PEM first)"}, {"vfyopt", OPT_VFYOPT, 's', "CSR verification parameter in n:v form"}, {"key", OPT_KEY, 's', "Key for signing, and to include unless using -force_pubkey"}, {"signkey", OPT_SIGNKEY, 's', "Same as -key"}, {"keyform", OPT_KEYFORM, 'E', "Key input format (ENGINE, other values ignored)"}, {"out", OPT_OUT, '>', "Output file - default stdout"}, {"outform", OPT_OUTFORM, 'f', "Output format (DER or PEM) - default PEM"}, {"nocert", OPT_NOCERT, '-', "No cert output (except for requested printing)"}, {"noout", OPT_NOOUT, '-', "No output (except for requested printing)"}, OPT_SECTION("Certificate printing"), {"text", OPT_TEXT, '-', "Print the certificate in text form"}, {"dateopt", OPT_DATEOPT, 's', "Datetime format used for printing. (rfc_822/iso_8601). Default is rfc_822."}, {"certopt", OPT_CERTOPT, 's', "Various certificate text printing options"}, {"fingerprint", OPT_FINGERPRINT, '-', "Print the certificate fingerprint"}, {"alias", OPT_ALIAS, '-', "Print certificate alias"}, {"serial", OPT_SERIAL, '-', "Print serial number value"}, {"startdate", OPT_STARTDATE, '-', "Print the notBefore field"}, {"enddate", OPT_ENDDATE, '-', "Print the notAfter field"}, {"dates", OPT_DATES, '-', "Print both notBefore and notAfter fields"}, {"subject", OPT_SUBJECT, '-', "Print subject DN"}, {"issuer", OPT_ISSUER, '-', "Print issuer DN"}, {"nameopt", OPT_NAMEOPT, 's', "Certificate subject/issuer name printing options"}, {"email", OPT_EMAIL, '-', "Print email address(es)"}, {"hash", OPT_HASH, '-', "Synonym for -subject_hash (for backward compat)"}, {"subject_hash", OPT_HASH, '-', "Print subject hash value"}, #ifndef OPENSSL_NO_MD5 {"subject_hash_old", OPT_SUBJECT_HASH_OLD, '-', "Print old-style (MD5) subject hash value"}, #endif {"issuer_hash", OPT_ISSUER_HASH, '-', "Print issuer hash value"}, #ifndef OPENSSL_NO_MD5 {"issuer_hash_old", OPT_ISSUER_HASH_OLD, '-', "Print old-style (MD5) issuer hash value"}, #endif {"ext", OPT_EXT, 's', "Restrict which X.509 extensions to print and/or copy"}, {"ocspid", OPT_OCSPID, '-', "Print OCSP hash values for the subject name and public key"}, {"ocsp_uri", OPT_OCSP_URI, '-', "Print OCSP Responder URL(s)"}, {"purpose", OPT_PURPOSE, '-', "Print out certificate purposes"}, {"pubkey", OPT_PUBKEY, '-', "Print the public key in PEM format"}, {"modulus", OPT_MODULUS, '-', "Print the RSA key modulus"}, OPT_SECTION("Certificate checking"), {"checkend", OPT_CHECKEND, 'M', "Check whether cert expires in the next arg seconds"}, {OPT_MORE_STR, 1, 1, "Exit 1 (failure) if so, 0 if not"}, {"checkhost", OPT_CHECKHOST, 's', "Check certificate matches host"}, {"checkemail", OPT_CHECKEMAIL, 's', "Check certificate matches email"}, {"checkip", OPT_CHECKIP, 's', "Check certificate matches ipaddr"}, OPT_SECTION("Certificate output"), {"set_serial", OPT_SET_SERIAL, 's', "Serial number to use, overrides -CAserial"}, {"next_serial", OPT_NEXT_SERIAL, '-', "Increment current certificate serial number"}, {"days", OPT_DAYS, 'n', "Number of days until newly generated certificate expires - default 30"}, {"preserve_dates", OPT_PRESERVE_DATES, '-', "Preserve existing validity dates"}, {"set_issuer", OPT_ISSU, 's', "Set or override certificate issuer"}, {"set_subject", OPT_SUBJ, 's', "Set or override certificate subject (and issuer)"}, {"subj", OPT_SUBJ, 's', "Alias for -set_subject"}, {"force_pubkey", OPT_FORCE_PUBKEY, '<', "Key to be placed in new certificate or certificate request"}, {"clrext", OPT_CLREXT, '-', "Do not take over any extensions from the source certificate or request"}, {"extfile", OPT_EXTFILE, '<', "Config file with X509V3 extensions to add"}, {"extensions", OPT_EXTENSIONS, 's', "Section of extfile to use - default: unnamed section"}, {"sigopt", OPT_SIGOPT, 's', "Signature parameter, in n:v form"}, {"badsig", OPT_BADSIG, '-', "Corrupt last byte of certificate signature (for test)"}, {"", OPT_MD, '-', "Any supported digest, used for signing and printing"}, OPT_SECTION("Micro-CA"), {"CA", OPT_CA, '<', "Use the given CA certificate, conflicts with -key"}, {"CAform", OPT_CAFORM, 'F', "CA cert format (PEM/DER/P12); has no effect"}, {"CAkey", OPT_CAKEY, 's', "The corresponding CA key; default is -CA arg"}, {"CAkeyform", OPT_CAKEYFORM, 'E', "CA key format (ENGINE, other values ignored)"}, {"CAserial", OPT_CASERIAL, 's', "File that keeps track of CA-generated serial number"}, {"CAcreateserial", OPT_CACREATESERIAL, '-', "Create CA serial number file if it does not exist"}, OPT_SECTION("Certificate trust output"), {"trustout", OPT_TRUSTOUT, '-', "Mark certificate PEM output as trusted"}, {"setalias", OPT_SETALIAS, 's', "Set certificate alias (nickname)"}, {"clrtrust", OPT_CLRTRUST, '-', "Clear all trusted purposes"}, {"addtrust", OPT_ADDTRUST, 's', "Trust certificate for a given purpose"}, {"clrreject", OPT_CLRREJECT, '-', "Clears all the prohibited or rejected uses of the certificate"}, {"addreject", OPT_ADDREJECT, 's', "Reject certificate for a given purpose"}, OPT_R_OPTIONS, #ifndef OPENSSL_NO_ENGINE {"engine", OPT_ENGINE, 's', "Use engine, possibly a hardware device"}, #endif OPT_PROV_OPTIONS, {NULL} }; static void warn_copying(ASN1_OBJECT *excluded, const char *names) { const char *sn = OBJ_nid2sn(OBJ_obj2nid(excluded)); if (names != NULL && strstr(names, sn) != NULL) BIO_printf(bio_err, "Warning: -ext should not specify copying %s extension to CSR; ignoring this\n", sn); } static X509_REQ *x509_to_req(X509 *cert, int ext_copy, const char *names) { const STACK_OF(X509_EXTENSION) *cert_exts = X509_get0_extensions(cert); int i, n = sk_X509_EXTENSION_num(cert_exts /* may be NULL */); ASN1_OBJECT *skid = OBJ_nid2obj(NID_subject_key_identifier); ASN1_OBJECT *akid = OBJ_nid2obj(NID_authority_key_identifier); STACK_OF(X509_EXTENSION) *exts; X509_REQ *req = X509_to_X509_REQ(cert, NULL, NULL); if (req == NULL) return NULL; /* * Filter out SKID and AKID extensions, which make no sense in a CSR. * If names is not NULL, copy only those extensions listed there. */ warn_copying(skid, names); warn_copying(akid, names); if ((exts = sk_X509_EXTENSION_new_reserve(NULL, n)) == NULL) goto err; for (i = 0; i < n; i++) { X509_EXTENSION *ex = sk_X509_EXTENSION_value(cert_exts, i); ASN1_OBJECT *obj = X509_EXTENSION_get_object(ex); if (OBJ_cmp(obj, skid) != 0 && OBJ_cmp(obj, akid) != 0 && !sk_X509_EXTENSION_push(exts, ex)) goto err; } if (sk_X509_EXTENSION_num(exts) > 0) { if (ext_copy != EXT_COPY_UNSET && ext_copy != EXT_COPY_NONE && !X509_REQ_add_extensions(req, exts)) { BIO_printf(bio_err, "Error copying extensions from certificate\n"); goto err; } } sk_X509_EXTENSION_free(exts); return req; err: sk_X509_EXTENSION_free(exts); X509_REQ_free(req); return NULL; } static int self_signed(X509_STORE *ctx, X509 *cert) { X509_STORE_CTX *xsc = X509_STORE_CTX_new(); int ret = 0; if (xsc == NULL || !X509_STORE_CTX_init(xsc, ctx, cert, NULL)) { BIO_printf(bio_err, "Error initialising X509 store\n"); } else { X509_STORE_CTX_set_flags(xsc, X509_V_FLAG_CHECK_SS_SIGNATURE); ret = X509_verify_cert(xsc) > 0; } X509_STORE_CTX_free(xsc); return ret; } int x509_main(int argc, char **argv) { ASN1_INTEGER *sno = NULL; ASN1_OBJECT *objtmp = NULL; BIO *out = NULL; CONF *extconf = NULL; int ext_copy = EXT_COPY_UNSET; X509V3_CTX ext_ctx; EVP_PKEY *privkey = NULL, *CAkey = NULL, *pubkey = NULL; EVP_PKEY *pkey; int newcert = 0; char *issu = NULL, *subj = NULL, *digest = NULL; X509_NAME *fissu = NULL, *fsubj = NULL; const unsigned long chtype = MBSTRING_ASC; const int multirdn = 1; STACK_OF(ASN1_OBJECT) *trust = NULL, *reject = NULL; STACK_OF(OPENSSL_STRING) *sigopts = NULL, *vfyopts = NULL; X509 *x = NULL, *xca = NULL, *issuer_cert; X509_REQ *req = NULL, *rq = NULL; X509_STORE *ctx = NULL; char *CAkeyfile = NULL, *CAserial = NULL, *pubkeyfile = NULL, *alias = NULL; char *checkhost = NULL, *checkemail = NULL, *checkip = NULL; char *ext_names = NULL; char *extsect = NULL, *extfile = NULL, *passin = NULL, *passinarg = NULL; char *infile = NULL, *outfile = NULL, *privkeyfile = NULL, *CAfile = NULL; char *prog; int days = UNSET_DAYS; /* not explicitly set */ int x509toreq = 0, modulus = 0, print_pubkey = 0, pprint = 0; int CAformat = FORMAT_UNDEF, CAkeyformat = FORMAT_UNDEF; unsigned long dateopt = ASN1_DTFLGS_RFC822; int fingerprint = 0, reqfile = 0, checkend = 0; int informat = FORMAT_UNDEF, outformat = FORMAT_PEM, keyformat = FORMAT_UNDEF; int next_serial = 0, subject_hash = 0, issuer_hash = 0, ocspid = 0; int noout = 0, CA_createserial = 0, email = 0; int ocsp_uri = 0, trustout = 0, clrtrust = 0, clrreject = 0, aliasout = 0; int ret = 1, i, j, num = 0, badsig = 0, clrext = 0, nocert = 0; int text = 0, serial = 0, subject = 0, issuer = 0, startdate = 0, ext = 0; int enddate = 0; time_t checkoffset = 0; unsigned long certflag = 0; int preserve_dates = 0; OPTION_CHOICE o; ENGINE *e = NULL; #ifndef OPENSSL_NO_MD5 int subject_hash_old = 0, issuer_hash_old = 0; #endif ctx = X509_STORE_new(); if (ctx == NULL) goto err; X509_STORE_set_verify_cb(ctx, callb); opt_set_unknown_name("digest"); prog = opt_init(argc, argv, x509_options); while ((o = opt_next()) != OPT_EOF) { switch (o) { case OPT_EOF: case OPT_ERR: opthelp: BIO_printf(bio_err, "%s: Use -help for summary.\n", prog); goto err; case OPT_HELP: opt_help(x509_options); ret = 0; goto end; case OPT_INFORM: if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &informat)) goto opthelp; break; case OPT_IN: infile = opt_arg(); break; case OPT_OUTFORM: if (!opt_format(opt_arg(), OPT_FMT_ANY, &outformat)) goto opthelp; break; case OPT_KEYFORM: if (!opt_format(opt_arg(), OPT_FMT_ANY, &keyformat)) goto opthelp; break; case OPT_CAFORM: if (!opt_format(opt_arg(), OPT_FMT_ANY, &CAformat)) goto opthelp; break; case OPT_CAKEYFORM: if (!opt_format(opt_arg(), OPT_FMT_ANY, &CAkeyformat)) goto opthelp; break; case OPT_OUT: outfile = opt_arg(); break; case OPT_REQ: reqfile = 1; break; case OPT_DATEOPT: if (!set_dateopt(&dateopt, opt_arg())) { BIO_printf(bio_err, "Invalid date format: %s\n", opt_arg()); goto err; } break; case OPT_COPY_EXTENSIONS: if (!set_ext_copy(&ext_copy, opt_arg())) { BIO_printf(bio_err, "Invalid extension copy option: %s\n", opt_arg()); goto err; } break; case OPT_SIGOPT: if (!sigopts) sigopts = sk_OPENSSL_STRING_new_null(); if (!sigopts || !sk_OPENSSL_STRING_push(sigopts, opt_arg())) goto opthelp; break; case OPT_VFYOPT: if (!vfyopts) vfyopts = sk_OPENSSL_STRING_new_null(); if (!vfyopts || !sk_OPENSSL_STRING_push(vfyopts, opt_arg())) goto opthelp; break; case OPT_DAYS: days = atoi(opt_arg()); if (days < -1) { BIO_printf(bio_err, "%s: -days parameter arg must be >= -1\n", prog); goto err; } break; case OPT_PASSIN: passinarg = opt_arg(); break; case OPT_EXTFILE: extfile = opt_arg(); break; case OPT_R_CASES: if (!opt_rand(o)) goto end; break; case OPT_PROV_CASES: if (!opt_provider(o)) goto end; break; case OPT_EXTENSIONS: extsect = opt_arg(); break; case OPT_KEY: case OPT_SIGNKEY: privkeyfile = opt_arg(); break; case OPT_CA: CAfile = opt_arg(); break; case OPT_CAKEY: CAkeyfile = opt_arg(); break; case OPT_CASERIAL: CAserial = opt_arg(); break; case OPT_SET_SERIAL: if (sno != NULL) { BIO_printf(bio_err, "Serial number supplied twice\n"); goto opthelp; } if ((sno = s2i_ASN1_INTEGER(NULL, opt_arg())) == NULL) goto opthelp; break; case OPT_NEW: newcert = 1; break; case OPT_FORCE_PUBKEY: pubkeyfile = opt_arg(); break; case OPT_ISSU: issu = opt_arg(); break; case OPT_SUBJ: subj = opt_arg(); break; case OPT_ADDTRUST: if (trust == NULL && (trust = sk_ASN1_OBJECT_new_null()) == NULL) goto end; if ((objtmp = OBJ_txt2obj(opt_arg(), 0)) == NULL) { BIO_printf(bio_err, "%s: Invalid trust object value %s\n", prog, opt_arg()); goto opthelp; } sk_ASN1_OBJECT_push(trust, objtmp); trustout = 1; break; case OPT_ADDREJECT: if (reject == NULL && (reject = sk_ASN1_OBJECT_new_null()) == NULL) goto end; if ((objtmp = OBJ_txt2obj(opt_arg(), 0)) == NULL) { BIO_printf(bio_err, "%s: Invalid reject object value %s\n", prog, opt_arg()); goto opthelp; } sk_ASN1_OBJECT_push(reject, objtmp); trustout = 1; break; case OPT_SETALIAS: alias = opt_arg(); trustout = 1; break; case OPT_CERTOPT: if (!set_cert_ex(&certflag, opt_arg())) goto opthelp; break; case OPT_NAMEOPT: if (!set_nameopt(opt_arg())) goto opthelp; break; case OPT_ENGINE: e = setup_engine(opt_arg(), 0); break; case OPT_EMAIL: email = ++num; break; case OPT_OCSP_URI: ocsp_uri = ++num; break; case OPT_SERIAL: serial = ++num; break; case OPT_NEXT_SERIAL: next_serial = ++num; break; case OPT_MODULUS: modulus = ++num; break; case OPT_PUBKEY: print_pubkey = ++num; break; case OPT_X509TOREQ: x509toreq = 1; break; case OPT_TEXT: text = ++num; break; case OPT_SUBJECT: subject = ++num; break; case OPT_ISSUER: issuer = ++num; break; case OPT_FINGERPRINT: fingerprint = ++num; break; case OPT_HASH: subject_hash = ++num; break; case OPT_ISSUER_HASH: issuer_hash = ++num; break; case OPT_PURPOSE: pprint = ++num; break; case OPT_STARTDATE: startdate = ++num; break; case OPT_ENDDATE: enddate = ++num; break; case OPT_NOOUT: noout = ++num; break; case OPT_EXT: ext = ++num; ext_names = opt_arg(); break; case OPT_NOCERT: nocert = 1; break; case OPT_TRUSTOUT: trustout = 1; break; case OPT_CLRTRUST: clrtrust = ++num; break; case OPT_CLRREJECT: clrreject = ++num; break; case OPT_ALIAS: aliasout = ++num; break; case OPT_CACREATESERIAL: CA_createserial = 1; break; case OPT_CLREXT: clrext = 1; break; case OPT_OCSPID: ocspid = ++num; break; case OPT_BADSIG: badsig = 1; break; #ifndef OPENSSL_NO_MD5 case OPT_SUBJECT_HASH_OLD: subject_hash_old = ++num; break; case OPT_ISSUER_HASH_OLD: issuer_hash_old = ++num; break; #else case OPT_SUBJECT_HASH_OLD: case OPT_ISSUER_HASH_OLD: break; #endif case OPT_DATES: startdate = ++num; enddate = ++num; break; case OPT_CHECKEND: checkend = 1; { ossl_intmax_t temp = 0; if (!opt_intmax(opt_arg(), &temp)) goto opthelp; checkoffset = (time_t)temp; if ((ossl_intmax_t)checkoffset != temp) { BIO_printf(bio_err, "%s: Checkend time out of range %s\n", prog, opt_arg()); goto opthelp; } } break; case OPT_CHECKHOST: checkhost = opt_arg(); break; case OPT_CHECKEMAIL: checkemail = opt_arg(); break; case OPT_CHECKIP: checkip = opt_arg(); break; case OPT_PRESERVE_DATES: preserve_dates = 1; break; case OPT_MD: digest = opt_unknown(); break; } } /* No extra arguments. */ if (!opt_check_rest_arg(NULL)) goto opthelp; if (!app_RAND_load()) goto end; if (!opt_check_md(digest)) goto opthelp; if (preserve_dates && days != UNSET_DAYS) { BIO_printf(bio_err, "Cannot use -preserve_dates with -days option\n"); goto err; } if (days == UNSET_DAYS) days = DEFAULT_DAYS; if (!app_passwd(passinarg, NULL, &passin, NULL)) { BIO_printf(bio_err, "Error getting password\n"); goto err; } if (!X509_STORE_set_default_paths_ex(ctx, app_get0_libctx(), app_get0_propq())) goto end; if (newcert && infile != NULL) { BIO_printf(bio_err, "The -in option cannot be used with -new\n"); goto err; } if (newcert && reqfile) { BIO_printf(bio_err, "The -req option cannot be used with -new\n"); goto err; } if (privkeyfile != NULL) { privkey = load_key(privkeyfile, keyformat, 0, passin, e, "private key"); if (privkey == NULL) goto end; } if (pubkeyfile != NULL) { if ((pubkey = load_pubkey(pubkeyfile, keyformat, 0, NULL, e, "explicitly set public key")) == NULL) goto end; } if (newcert) { if (subj == NULL) { BIO_printf(bio_err, "The -new option requires a subject to be set using -subj\n"); goto err; } if (privkeyfile == NULL && pubkeyfile == NULL) { BIO_printf(bio_err, "The -new option requires using the -key or -force_pubkey option\n"); goto err; } } if (issu != NULL && (fissu = parse_name(issu, chtype, multirdn, "issuer")) == NULL) goto end; if (subj != NULL && (fsubj = parse_name(subj, chtype, multirdn, "subject")) == NULL) goto end; if (CAkeyfile == NULL) CAkeyfile = CAfile; if (CAfile != NULL) { if (privkeyfile != NULL) { BIO_printf(bio_err, "Cannot use both -key/-signkey and -CA option\n"); goto err; } } else { #define WARN_NO_CA(opt) BIO_printf(bio_err, \ "Warning: ignoring " opt " option since -CA option is not given\n"); if (CAkeyfile != NULL) WARN_NO_CA("-CAkey"); if (CAkeyformat != FORMAT_UNDEF) WARN_NO_CA("-CAkeyform"); if (CAformat != FORMAT_UNDEF) WARN_NO_CA("-CAform"); if (CAserial != NULL) WARN_NO_CA("-CAserial"); if (CA_createserial) WARN_NO_CA("-CAcreateserial"); } if (extfile == NULL) { if (extsect != NULL) BIO_printf(bio_err, "Warning: ignoring -extensions option without -extfile\n"); } else { X509V3_CTX ctx2; if ((extconf = app_load_config(extfile)) == NULL) goto end; if (extsect == NULL) { extsect = app_conf_try_string(extconf, "default", "extensions"); if (extsect == NULL) extsect = "default"; } X509V3_set_ctx_test(&ctx2); X509V3_set_nconf(&ctx2, extconf); if (!X509V3_EXT_add_nconf(extconf, &ctx2, extsect, NULL)) { BIO_printf(bio_err, "Error checking extension section %s\n", extsect); goto err; } } if (reqfile) { if (infile == NULL) BIO_printf(bio_err, "Warning: Reading cert request from stdin since no -in option is given\n"); req = load_csr_autofmt(infile, informat, vfyopts, "certificate request input"); if (req == NULL) goto end; if ((pkey = X509_REQ_get0_pubkey(req)) == NULL) { BIO_printf(bio_err, "Error unpacking public key from CSR\n"); goto err; } i = do_X509_REQ_verify(req, pkey, vfyopts); if (i <= 0) { BIO_printf(bio_err, i < 0 ? "Error while verifying certificate request self-signature\n" : "Certificate request self-signature did not match the contents\n"); goto err; } BIO_printf(bio_err, "Certificate request self-signature ok\n"); print_name(bio_err, "subject=", X509_REQ_get_subject_name(req)); } else if (!x509toreq && ext_copy != EXT_COPY_UNSET) { BIO_printf(bio_err, "Warning: ignoring -copy_extensions since neither -x509toreq nor -req is given\n"); } if (reqfile || newcert) { if (preserve_dates) BIO_printf(bio_err, "Warning: ignoring -preserve_dates option with -req or -new\n"); preserve_dates = 0; if (privkeyfile == NULL && CAkeyfile == NULL) { BIO_printf(bio_err, "We need a private key to sign with, use -key or -CAkey or -CA with private key\n"); goto err; } if ((x = X509_new_ex(app_get0_libctx(), app_get0_propq())) == NULL) goto end; if (CAfile == NULL && sno == NULL) { sno = ASN1_INTEGER_new(); if (sno == NULL || !rand_serial(NULL, sno)) goto end; } if (req != NULL && ext_copy != EXT_COPY_UNSET) { if (clrext && ext_copy != EXT_COPY_NONE) { BIO_printf(bio_err, "Must not use -clrext together with -copy_extensions\n"); goto err; } else if (!copy_extensions(x, req, ext_copy)) { BIO_printf(bio_err, "Error copying extensions from request\n"); goto err; } } } else { if (infile == NULL) BIO_printf(bio_err, "Warning: Reading certificate from stdin since no -in or -new option is given\n"); x = load_cert_pass(infile, informat, 1, passin, "certificate"); if (x == NULL) goto end; } if ((fsubj != NULL || req != NULL) && !X509_set_subject_name(x, fsubj != NULL ? fsubj : X509_REQ_get_subject_name(req))) goto end; if ((pubkey != NULL || privkey != NULL || req != NULL) && !X509_set_pubkey(x, pubkey != NULL ? pubkey : privkey != NULL ? privkey : X509_REQ_get0_pubkey(req))) goto end; if (CAfile != NULL) { xca = load_cert_pass(CAfile, CAformat, 1, passin, "CA certificate"); if (xca == NULL) goto end; } out = bio_open_default(outfile, 'w', outformat); if (out == NULL) goto end; if (alias) X509_alias_set1(x, (unsigned char *)alias, -1); if (clrtrust) X509_trust_clear(x); if (clrreject) X509_reject_clear(x); if (trust != NULL) { for (i = 0; i < sk_ASN1_OBJECT_num(trust); i++) X509_add1_trust_object(x, sk_ASN1_OBJECT_value(trust, i)); } if (reject != NULL) { for (i = 0; i < sk_ASN1_OBJECT_num(reject); i++) X509_add1_reject_object(x, sk_ASN1_OBJECT_value(reject, i)); } if (clrext && ext_names != NULL) BIO_printf(bio_err, "Warning: Ignoring -ext since -clrext is given\n"); for (i = X509_get_ext_count(x) - 1; i >= 0; i--) { X509_EXTENSION *ex = X509_get_ext(x, i); const char *sn = OBJ_nid2sn(OBJ_obj2nid(X509_EXTENSION_get_object(ex))); if (clrext || (ext_names != NULL && strstr(ext_names, sn) == NULL)) X509_EXTENSION_free(X509_delete_ext(x, i)); } issuer_cert = x; if (CAfile != NULL) { issuer_cert = xca; if (sno == NULL) sno = x509_load_serial(CAfile, CAserial, CA_createserial); if (sno == NULL) goto end; if (!x509toreq && !reqfile && !newcert && !self_signed(ctx, x)) goto end; } else { if (privkey != NULL && !cert_matches_key(x, privkey)) BIO_printf(bio_err, "Warning: Signature key and public key of cert do not match\n"); } if (sno != NULL && !X509_set_serialNumber(x, sno)) goto end; if (reqfile || newcert || privkey != NULL || CAfile != NULL) { if (!preserve_dates && !set_cert_times(x, NULL, NULL, days)) goto end; if (fissu != NULL) { if (!X509_set_issuer_name(x, fissu)) goto end; } else { if (!X509_set_issuer_name(x, X509_get_subject_name(issuer_cert))) goto end; } } X509V3_set_ctx(&ext_ctx, issuer_cert, x, NULL, NULL, X509V3_CTX_REPLACE); /* prepare fallback for AKID, but only if issuer cert equals subject cert */ if (CAfile == NULL) { if (!X509V3_set_issuer_pkey(&ext_ctx, privkey)) goto end; } if (extconf != NULL && !x509toreq) { X509V3_set_nconf(&ext_ctx, extconf); if (!X509V3_EXT_add_nconf(extconf, &ext_ctx, extsect, x)) { BIO_printf(bio_err, "Error adding extensions from section %s\n", extsect); goto err; } } /* At this point the contents of the certificate x have been finished. */ pkey = X509_get0_pubkey(x); if ((print_pubkey != 0 || modulus != 0) && pkey == NULL) { BIO_printf(bio_err, "Error getting public key\n"); goto err; } if (x509toreq) { /* also works in conjunction with -req */ if (privkey == NULL) { BIO_printf(bio_err, "Must specify request signing key using -key\n"); goto err; } if (clrext && ext_copy != EXT_COPY_NONE) { BIO_printf(bio_err, "Must not use -clrext together with -copy_extensions\n"); goto err; } if ((rq = x509_to_req(x, ext_copy, ext_names)) == NULL) goto end; if (extconf != NULL) { X509V3_set_nconf(&ext_ctx, extconf); if (!X509V3_EXT_REQ_add_nconf(extconf, &ext_ctx, extsect, rq)) { BIO_printf(bio_err, "Error adding request extensions from section %s\n", extsect); goto err; } } if (!do_X509_REQ_sign(rq, privkey, digest, sigopts)) goto end; if (!noout) { if (outformat == FORMAT_ASN1) { X509_REQ_print_ex(out, rq, get_nameopt(), X509_FLAG_COMPAT); i = i2d_X509_bio(out, x); } else { i = PEM_write_bio_X509_REQ(out, rq); } if (!i) { BIO_printf(bio_err, "Unable to write certificate request\n"); goto err; } } noout = 1; } else if (CAfile != NULL) { if ((CAkey = load_key(CAkeyfile, CAkeyformat, 0, passin, e, "CA private key")) == NULL) goto end; if (!X509_check_private_key(xca, CAkey)) { BIO_printf(bio_err, "CA certificate and CA private key do not match\n"); goto err; } if (!do_X509_sign(x, 0, CAkey, digest, sigopts, &ext_ctx)) goto end; } else if (privkey != NULL) { if (!do_X509_sign(x, 0, privkey, digest, sigopts, &ext_ctx)) goto end; } if (badsig) { const ASN1_BIT_STRING *signature; X509_get0_signature(&signature, NULL, x); corrupt_signature(signature); } /* Process print options in the given order, as indicated by index i */ for (i = 1; i <= num; i++) { if (i == issuer) { print_name(out, "issuer=", X509_get_issuer_name(x)); } else if (i == subject) { print_name(out, "subject=", X509_get_subject_name(x)); } else if (i == serial) { BIO_printf(out, "serial="); i2a_ASN1_INTEGER(out, X509_get0_serialNumber(x)); BIO_printf(out, "\n"); } else if (i == next_serial) { ASN1_INTEGER *ser; BIGNUM *bnser = ASN1_INTEGER_to_BN(X509_get0_serialNumber(x), NULL); if (bnser == NULL) goto end; if (!BN_add_word(bnser, 1) || (ser = BN_to_ASN1_INTEGER(bnser, NULL)) == NULL) { BN_free(bnser); goto end; } BN_free(bnser); i2a_ASN1_INTEGER(out, ser); ASN1_INTEGER_free(ser); BIO_puts(out, "\n"); } else if (i == email || i == ocsp_uri) { STACK_OF(OPENSSL_STRING) *emlst = i == email ? X509_get1_email(x) : X509_get1_ocsp(x); for (j = 0; j < sk_OPENSSL_STRING_num(emlst); j++) BIO_printf(out, "%s\n", sk_OPENSSL_STRING_value(emlst, j)); X509_email_free(emlst); } else if (i == aliasout) { unsigned char *alstr = X509_alias_get0(x, NULL); if (alstr) BIO_printf(out, "%s\n", alstr); else BIO_puts(out, "<No Alias>\n"); } else if (i == subject_hash) { BIO_printf(out, "%08lx\n", X509_subject_name_hash(x)); #ifndef OPENSSL_NO_MD5 } else if (i == subject_hash_old) { BIO_printf(out, "%08lx\n", X509_subject_name_hash_old(x)); #endif } else if (i == issuer_hash) { BIO_printf(out, "%08lx\n", X509_issuer_name_hash(x)); #ifndef OPENSSL_NO_MD5 } else if (i == issuer_hash_old) { BIO_printf(out, "%08lx\n", X509_issuer_name_hash_old(x)); #endif } else if (i == pprint) { BIO_printf(out, "Certificate purposes:\n"); for (j = 0; j < X509_PURPOSE_get_count(); j++) purpose_print(out, x, X509_PURPOSE_get0(j)); } else if (i == modulus) { BIO_printf(out, "Modulus="); if (EVP_PKEY_is_a(pkey, "RSA") || EVP_PKEY_is_a(pkey, "RSA-PSS")) { BIGNUM *n = NULL; /* Every RSA key has an 'n' */ EVP_PKEY_get_bn_param(pkey, "n", &n); BN_print(out, n); BN_free(n); } else if (EVP_PKEY_is_a(pkey, "DSA")) { BIGNUM *dsapub = NULL; /* Every DSA key has a 'pub' */ EVP_PKEY_get_bn_param(pkey, "pub", &dsapub); BN_print(out, dsapub); BN_free(dsapub); } else { BIO_printf(out, "No modulus for this public key type"); } BIO_printf(out, "\n"); } else if (i == print_pubkey) { PEM_write_bio_PUBKEY(out, pkey); } else if (i == text) { X509_print_ex(out, x, get_nameopt(), certflag); } else if (i == startdate) { BIO_puts(out, "notBefore="); ASN1_TIME_print_ex(out, X509_get0_notBefore(x), dateopt); BIO_puts(out, "\n"); } else if (i == enddate) { BIO_puts(out, "notAfter="); ASN1_TIME_print_ex(out, X509_get0_notAfter(x), dateopt); BIO_puts(out, "\n"); } else if (i == fingerprint) { unsigned int n; unsigned char md[EVP_MAX_MD_SIZE]; const char *fdigname = digest; EVP_MD *fdig; int digres; if (fdigname == NULL) fdigname = "SHA1"; if ((fdig = EVP_MD_fetch(app_get0_libctx(), fdigname, app_get0_propq())) == NULL) { BIO_printf(bio_err, "Unknown digest\n"); goto err; } digres = X509_digest(x, fdig, md, &n); EVP_MD_free(fdig); if (!digres) { BIO_printf(bio_err, "Out of memory\n"); goto err; } BIO_printf(out, "%s Fingerprint=", fdigname); for (j = 0; j < (int)n; j++) BIO_printf(out, "%02X%c", md[j], (j + 1 == (int)n) ? '\n' : ':'); } else if (i == ocspid) { X509_ocspid_print(out, x); } else if (i == ext) { print_x509v3_exts(out, x, ext_names); } } if (checkend) { time_t tcheck = time(NULL) + checkoffset; ret = X509_cmp_time(X509_get0_notAfter(x), &tcheck) < 0; if (ret) BIO_printf(out, "Certificate will expire\n"); else BIO_printf(out, "Certificate will not expire\n"); goto end; } if (!check_cert_attributes(out, x, checkhost, checkemail, checkip, 1)) goto err; if (noout || nocert) { ret = 0; goto end; } if (outformat == FORMAT_ASN1) { i = i2d_X509_bio(out, x); } else if (outformat == FORMAT_PEM) { if (trustout) i = PEM_write_bio_X509_AUX(out, x); else i = PEM_write_bio_X509(out, x); } else { BIO_printf(bio_err, "Bad output format specified for outfile\n"); goto err; } if (!i) { BIO_printf(bio_err, "Unable to write certificate\n"); goto err; } ret = 0; goto end; err: ERR_print_errors(bio_err); end: NCONF_free(extconf); BIO_free_all(out); X509_STORE_free(ctx); X509_NAME_free(fissu); X509_NAME_free(fsubj); X509_REQ_free(req); X509_free(x); X509_free(xca); EVP_PKEY_free(privkey); EVP_PKEY_free(CAkey); EVP_PKEY_free(pubkey); sk_OPENSSL_STRING_free(sigopts); sk_OPENSSL_STRING_free(vfyopts); X509_REQ_free(rq); ASN1_INTEGER_free(sno); sk_ASN1_OBJECT_pop_free(trust, ASN1_OBJECT_free); sk_ASN1_OBJECT_pop_free(reject, ASN1_OBJECT_free); release_engine(e); clear_free(passin); return ret; } static ASN1_INTEGER *x509_load_serial(const char *CAfile, const char *serialfile, int create) { char *buf = NULL; ASN1_INTEGER *bs = NULL; BIGNUM *serial = NULL; int defaultfile = 0, file_exists; if (serialfile == NULL) { const char *p = strrchr(CAfile, '.'); size_t len = p != NULL ? (size_t)(p - CAfile) : strlen(CAfile); buf = app_malloc(len + sizeof(POSTFIX), "serial# buffer"); memcpy(buf, CAfile, len); memcpy(buf + len, POSTFIX, sizeof(POSTFIX)); serialfile = buf; defaultfile = 1; } serial = load_serial(serialfile, &file_exists, create || defaultfile, NULL); if (serial == NULL) goto end; if (!BN_add_word(serial, 1)) { BIO_printf(bio_err, "Serial number increment failure\n"); goto end; } if (file_exists || create) save_serial(serialfile, NULL, serial, &bs); else bs = BN_to_ASN1_INTEGER(serial, NULL); end: OPENSSL_free(buf); BN_free(serial); return bs; } static int callb(int ok, X509_STORE_CTX *ctx) { int err; X509 *err_cert; /* * It is ok to use a self-signed certificate. This case will catch both * the initial ok == 0 and the final ok == 1 calls to this function. */ err = X509_STORE_CTX_get_error(ctx); if (err == X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT) return 1; if (!ok) { err_cert = X509_STORE_CTX_get_current_cert(ctx); print_name(bio_err, "subject=", X509_get_subject_name(err_cert)); BIO_printf(bio_err, "Error with certificate - error %d at depth %d\n%s\n", err, X509_STORE_CTX_get_error_depth(ctx), X509_verify_cert_error_string(err)); return 1; } return 1; } static int purpose_print(BIO *bio, X509 *cert, X509_PURPOSE *pt) { int id, i, idret; const char *pname; id = X509_PURPOSE_get_id(pt); pname = X509_PURPOSE_get0_name(pt); for (i = 0; i < 2; i++) { idret = X509_check_purpose(cert, id, i); BIO_printf(bio, "%s%s : ", pname, i ? " CA" : ""); if (idret == 1) BIO_printf(bio, "Yes\n"); else if (idret == 0) BIO_printf(bio, "No\n"); else BIO_printf(bio, "Yes (WARNING code=%d)\n", idret); } return 1; } static int parse_ext_names(char *names, const char **result) { char *p, *q; int cnt = 0, len = 0; p = q = names; len = strlen(names); while (q - names <= len) { if (*q != ',' && *q != '\0') { q++; continue; } if (p != q) { /* found */ if (result != NULL) { result[cnt] = p; *q = '\0'; } cnt++; } p = ++q; } return cnt; } static int print_x509v3_exts(BIO *bio, X509 *x, const char *ext_names) { const STACK_OF(X509_EXTENSION) *exts = NULL; STACK_OF(X509_EXTENSION) *exts2 = NULL; X509_EXTENSION *ext = NULL; ASN1_OBJECT *obj; int i, j, ret = 0, num, nn = 0; const char *sn, **names = NULL; char *tmp_ext_names = NULL; exts = X509_get0_extensions(x); if ((num = sk_X509_EXTENSION_num(exts)) <= 0) { BIO_printf(bio_err, "No extensions in certificate\n"); ret = 1; goto end; } /* parse comma separated ext name string */ if ((tmp_ext_names = OPENSSL_strdup(ext_names)) == NULL) goto end; if ((nn = parse_ext_names(tmp_ext_names, NULL)) == 0) { BIO_printf(bio, "Invalid extension names: %s\n", ext_names); goto end; } if ((names = OPENSSL_malloc(sizeof(char *) * nn)) == NULL) goto end; parse_ext_names(tmp_ext_names, names); for (i = 0; i < num; i++) { ext = sk_X509_EXTENSION_value(exts, i); /* check if this ext is what we want */ obj = X509_EXTENSION_get_object(ext); sn = OBJ_nid2sn(OBJ_obj2nid(obj)); if (sn == NULL || strcmp(sn, "UNDEF") == 0) continue; for (j = 0; j < nn; j++) { if (strcmp(sn, names[j]) == 0) { /* push the extension into a new stack */ if (exts2 == NULL && (exts2 = sk_X509_EXTENSION_new_null()) == NULL) goto end; if (!sk_X509_EXTENSION_push(exts2, ext)) goto end; } } } if (!sk_X509_EXTENSION_num(exts2)) { BIO_printf(bio, "No extensions matched with %s\n", ext_names); ret = 1; goto end; } ret = X509V3_extensions_print(bio, NULL, exts2, 0, 0); end: sk_X509_EXTENSION_free(exts2); OPENSSL_free(names); OPENSSL_free(tmp_ext_names); return ret; }
./openssl/apps/gendsa.c
/* * Copyright 1995-2023 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <openssl/opensslconf.h> #include <stdio.h> #include <string.h> #include <sys/types.h> #include <sys/stat.h> #include "apps.h" #include "progs.h" #include <openssl/bio.h> #include <openssl/err.h> #include <openssl/bn.h> #include <openssl/dsa.h> #include <openssl/x509.h> #include <openssl/pem.h> typedef enum OPTION_choice { OPT_COMMON, OPT_OUT, OPT_PASSOUT, OPT_ENGINE, OPT_CIPHER, OPT_VERBOSE, OPT_QUIET, OPT_R_ENUM, OPT_PROV_ENUM } OPTION_CHOICE; const OPTIONS gendsa_options[] = { {OPT_HELP_STR, 1, '-', "Usage: %s [options] dsaparam-file\n"}, OPT_SECTION("General"), {"help", OPT_HELP, '-', "Display this summary"}, #ifndef OPENSSL_NO_ENGINE {"engine", OPT_ENGINE, 's', "Use engine, possibly a hardware device"}, #endif OPT_SECTION("Output"), {"out", OPT_OUT, '>', "Output the key to the specified file"}, {"passout", OPT_PASSOUT, 's', "Output file pass phrase source"}, OPT_R_OPTIONS, OPT_PROV_OPTIONS, {"", OPT_CIPHER, '-', "Encrypt the output with any supported cipher"}, {"verbose", OPT_VERBOSE, '-', "Verbose output"}, {"quiet", OPT_QUIET, '-', "Terse output"}, OPT_PARAMETERS(), {"dsaparam-file", 0, 0, "File containing DSA parameters"}, {NULL} }; int gendsa_main(int argc, char **argv) { ENGINE *e = NULL; BIO *out = NULL, *in = NULL; EVP_PKEY *pkey = NULL; EVP_PKEY_CTX *ctx = NULL; EVP_CIPHER *enc = NULL; char *dsaparams = NULL, *ciphername = NULL; char *outfile = NULL, *passoutarg = NULL, *passout = NULL, *prog; OPTION_CHOICE o; int ret = 1, private = 0, verbose = 0, nbits; opt_set_unknown_name("cipher"); prog = opt_init(argc, argv, gendsa_options); while ((o = opt_next()) != OPT_EOF) { switch (o) { case OPT_EOF: case OPT_ERR: opthelp: BIO_printf(bio_err, "%s: Use -help for summary.\n", prog); goto end; case OPT_HELP: ret = 0; opt_help(gendsa_options); goto end; case OPT_OUT: outfile = opt_arg(); break; case OPT_PASSOUT: passoutarg = opt_arg(); break; case OPT_ENGINE: e = setup_engine(opt_arg(), 0); break; case OPT_R_CASES: if (!opt_rand(o)) goto end; break; case OPT_PROV_CASES: if (!opt_provider(o)) goto end; break; case OPT_CIPHER: ciphername = opt_unknown(); break; case OPT_VERBOSE: verbose = 1; break; case OPT_QUIET: verbose = 0; break; } } /* One argument, the params file. */ if (!opt_check_rest_arg("params file")) goto opthelp; argv = opt_rest(); dsaparams = argv[0]; if (!app_RAND_load()) goto end; if (!opt_cipher(ciphername, &enc)) goto end; private = 1; if (!app_passwd(NULL, passoutarg, NULL, &passout)) { BIO_printf(bio_err, "Error getting password\n"); goto end; } pkey = load_keyparams(dsaparams, FORMAT_UNDEF, 1, "DSA", "DSA parameters"); out = bio_open_owner(outfile, FORMAT_PEM, private); if (out == NULL) goto end2; nbits = EVP_PKEY_get_bits(pkey); if (nbits > OPENSSL_DSA_MAX_MODULUS_BITS) BIO_printf(bio_err, "Warning: It is not recommended to use more than %d bit for DSA keys.\n" " Your key size is %d! Larger key size may behave not as expected.\n", OPENSSL_DSA_MAX_MODULUS_BITS, EVP_PKEY_get_bits(pkey)); ctx = EVP_PKEY_CTX_new_from_pkey(app_get0_libctx(), pkey, app_get0_propq()); if (ctx == NULL) { BIO_printf(bio_err, "unable to create PKEY context\n"); goto end; } EVP_PKEY_free(pkey); pkey = NULL; if (EVP_PKEY_keygen_init(ctx) <= 0) { BIO_printf(bio_err, "unable to set up for key generation\n"); goto end; } pkey = app_keygen(ctx, "DSA", nbits, verbose); if (pkey == NULL) goto end; assert(private); if (!PEM_write_bio_PrivateKey(out, pkey, enc, NULL, 0, NULL, passout)) { BIO_printf(bio_err, "unable to output generated key\n"); goto end; } ret = 0; end: if (ret != 0) ERR_print_errors(bio_err); end2: BIO_free(in); BIO_free_all(out); EVP_PKEY_free(pkey); EVP_PKEY_CTX_free(ctx); EVP_CIPHER_free(enc); release_engine(e); OPENSSL_free(passout); return ret; }
./openssl/apps/dsaparam.c
/* * Copyright 1995-2023 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <openssl/opensslconf.h> #include <stdio.h> #include <stdlib.h> #include <time.h> #include <string.h> #include "apps.h" #include "progs.h" #include <openssl/bio.h> #include <openssl/err.h> #include <openssl/bn.h> #include <openssl/dsa.h> #include <openssl/x509.h> #include <openssl/pem.h> static int verbose = 0; typedef enum OPTION_choice { OPT_COMMON, OPT_INFORM, OPT_OUTFORM, OPT_IN, OPT_OUT, OPT_TEXT, OPT_NOOUT, OPT_GENKEY, OPT_ENGINE, OPT_VERBOSE, OPT_QUIET, OPT_R_ENUM, OPT_PROV_ENUM } OPTION_CHOICE; const OPTIONS dsaparam_options[] = { {OPT_HELP_STR, 1, '-', "Usage: %s [options] [numbits] [numqbits]\n"}, OPT_SECTION("General"), {"help", OPT_HELP, '-', "Display this summary"}, #ifndef OPENSSL_NO_ENGINE {"engine", OPT_ENGINE, 's', "Use engine e, possibly a hardware device"}, #endif OPT_SECTION("Input"), {"in", OPT_IN, '<', "Input file"}, {"inform", OPT_INFORM, 'F', "Input format - DER or PEM"}, OPT_SECTION("Output"), {"out", OPT_OUT, '>', "Output file"}, {"outform", OPT_OUTFORM, 'F', "Output format - DER or PEM"}, {"text", OPT_TEXT, '-', "Print as text"}, {"noout", OPT_NOOUT, '-', "No output"}, {"verbose", OPT_VERBOSE, '-', "Verbose output"}, {"quiet", OPT_QUIET, '-', "Terse output"}, {"genkey", OPT_GENKEY, '-', "Generate a DSA key"}, OPT_R_OPTIONS, OPT_PROV_OPTIONS, OPT_PARAMETERS(), {"numbits", 0, 0, "Number of bits if generating parameters or key (optional)"}, {"numqbits", 0, 0, "Number of bits in the subprime parameter q if generating parameters or key (optional)"}, {NULL} }; int dsaparam_main(int argc, char **argv) { ENGINE *e = NULL; BIO *out = NULL; EVP_PKEY *params = NULL, *pkey = NULL; EVP_PKEY_CTX *ctx = NULL; int numbits = -1, numqbits = -1, num = 0, genkey = 0; int informat = FORMAT_UNDEF, outformat = FORMAT_PEM, noout = 0; int ret = 1, i, text = 0, private = 0; char *infile = NULL, *outfile = NULL, *prog; OPTION_CHOICE o; prog = opt_init(argc, argv, dsaparam_options); while ((o = opt_next()) != OPT_EOF) { switch (o) { case OPT_EOF: case OPT_ERR: opthelp: BIO_printf(bio_err, "%s: Use -help for summary.\n", prog); goto end; case OPT_HELP: opt_help(dsaparam_options); ret = 0; goto end; case OPT_INFORM: if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &informat)) goto opthelp; break; case OPT_IN: infile = opt_arg(); break; case OPT_OUTFORM: if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &outformat)) goto opthelp; break; case OPT_OUT: outfile = opt_arg(); break; case OPT_ENGINE: e = setup_engine(opt_arg(), 0); break; case OPT_TEXT: text = 1; break; case OPT_GENKEY: genkey = 1; break; case OPT_R_CASES: if (!opt_rand(o)) goto end; break; case OPT_PROV_CASES: if (!opt_provider(o)) goto end; break; case OPT_NOOUT: noout = 1; break; case OPT_VERBOSE: verbose = 1; break; case OPT_QUIET: verbose = 0; break; } } /* Optional args are bitsize and q bitsize. */ argc = opt_num_rest(); argv = opt_rest(); if (argc == 2) { if (!opt_int(argv[0], &num) || num < 0) goto opthelp; if (!opt_int(argv[1], &numqbits) || numqbits < 0) goto opthelp; } else if (argc == 1) { if (!opt_int(argv[0], &num) || num < 0) goto opthelp; } else if (!opt_check_rest_arg(NULL)) { goto opthelp; } if (!app_RAND_load()) goto end; /* generate a key */ numbits = num; private = genkey ? 1 : 0; out = bio_open_owner(outfile, outformat, private); if (out == NULL) goto end; ctx = EVP_PKEY_CTX_new_from_name(app_get0_libctx(), "DSA", app_get0_propq()); if (ctx == NULL) { BIO_printf(bio_err, "Error, DSA parameter generation context allocation failed\n"); goto end; } if (numbits > 0) { if (numbits > OPENSSL_DSA_MAX_MODULUS_BITS) BIO_printf(bio_err, "Warning: It is not recommended to use more than %d bit for DSA keys.\n" " Your key size is %d! Larger key size may behave not as expected.\n", OPENSSL_DSA_MAX_MODULUS_BITS, numbits); EVP_PKEY_CTX_set_app_data(ctx, bio_err); if (verbose) { EVP_PKEY_CTX_set_cb(ctx, progress_cb); BIO_printf(bio_err, "Generating DSA parameters, %d bit long prime\n", num); BIO_printf(bio_err, "This could take some time\n"); } if (EVP_PKEY_paramgen_init(ctx) <= 0) { BIO_printf(bio_err, "Error, DSA key generation paramgen init failed\n"); goto end; } if (EVP_PKEY_CTX_set_dsa_paramgen_bits(ctx, num) <= 0) { BIO_printf(bio_err, "Error, DSA key generation setting bit length failed\n"); goto end; } if (numqbits > 0) { if (EVP_PKEY_CTX_set_dsa_paramgen_q_bits(ctx, numqbits) <= 0) { BIO_printf(bio_err, "Error, DSA key generation setting subprime bit length failed\n"); goto end; } } params = app_paramgen(ctx, "DSA"); } else { params = load_keyparams(infile, informat, 1, "DSA", "DSA parameters"); } if (params == NULL) { /* Error message should already have been displayed */ goto end; } if (text) { EVP_PKEY_print_params(out, params, 0, NULL); } if (outformat == FORMAT_ASN1 && genkey) noout = 1; if (!noout) { if (outformat == FORMAT_ASN1) i = i2d_KeyParams_bio(out, params); else i = PEM_write_bio_Parameters(out, params); if (!i) { BIO_printf(bio_err, "Error, unable to write DSA parameters\n"); goto end; } } if (genkey) { EVP_PKEY_CTX_free(ctx); ctx = EVP_PKEY_CTX_new_from_pkey(app_get0_libctx(), params, app_get0_propq()); if (ctx == NULL) { BIO_printf(bio_err, "Error, DSA key generation context allocation failed\n"); goto end; } if (EVP_PKEY_keygen_init(ctx) <= 0) { BIO_printf(bio_err, "Error, unable to initialise for key generation\n"); goto end; } pkey = app_keygen(ctx, "DSA", numbits, verbose); if (pkey == NULL) goto end; assert(private); if (outformat == FORMAT_ASN1) i = i2d_PrivateKey_bio(out, pkey); else i = PEM_write_bio_PrivateKey(out, pkey, NULL, NULL, 0, NULL, NULL); } ret = 0; end: if (ret != 0) ERR_print_errors(bio_err); BIO_free_all(out); EVP_PKEY_CTX_free(ctx); EVP_PKEY_free(pkey); EVP_PKEY_free(params); release_engine(e); return ret; }
./openssl/apps/list.c
/* * Copyright 1995-2023 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ /* We need to use some deprecated APIs */ #define OPENSSL_SUPPRESS_DEPRECATED #include <string.h> #include <openssl/evp.h> #include <openssl/err.h> #include <openssl/provider.h> #include <openssl/safestack.h> #include <openssl/kdf.h> #include <openssl/encoder.h> #include <openssl/decoder.h> #include <openssl/store.h> #include <openssl/core_names.h> #include <openssl/rand.h> #include "apps.h" #include "app_params.h" #include "progs.h" #include "opt.h" #include "names.h" static int verbose = 0; static const char *select_name = NULL; /* Checks to see if algorithms are fetchable */ #define IS_FETCHABLE(type, TYPE) \ static int is_ ## type ## _fetchable(const TYPE *alg) \ { \ TYPE *impl; \ const char *propq = app_get0_propq(); \ OSSL_LIB_CTX *libctx = app_get0_libctx(); \ const char *name = TYPE ## _get0_name(alg); \ \ ERR_set_mark(); \ impl = TYPE ## _fetch(libctx, name, propq); \ ERR_pop_to_mark(); \ if (impl == NULL) \ return 0; \ TYPE ## _free(impl); \ return 1; \ } IS_FETCHABLE(cipher, EVP_CIPHER) IS_FETCHABLE(digest, EVP_MD) IS_FETCHABLE(mac, EVP_MAC) IS_FETCHABLE(kdf, EVP_KDF) IS_FETCHABLE(rand, EVP_RAND) IS_FETCHABLE(keymgmt, EVP_KEYMGMT) IS_FETCHABLE(signature, EVP_SIGNATURE) IS_FETCHABLE(kem, EVP_KEM) IS_FETCHABLE(asym_cipher, EVP_ASYM_CIPHER) IS_FETCHABLE(keyexch, EVP_KEYEXCH) IS_FETCHABLE(decoder, OSSL_DECODER) IS_FETCHABLE(encoder, OSSL_ENCODER) #ifndef OPENSSL_NO_DEPRECATED_3_0 static int include_legacy(void) { return app_get0_propq() == NULL; } static void legacy_cipher_fn(const EVP_CIPHER *c, const char *from, const char *to, void *arg) { if (select_name != NULL && (c == NULL || OPENSSL_strcasecmp(select_name, EVP_CIPHER_get0_name(c)) != 0)) return; if (c != NULL) { BIO_printf(arg, " %s\n", EVP_CIPHER_get0_name(c)); } else { if (from == NULL) from = "<undefined>"; if (to == NULL) to = "<undefined>"; BIO_printf(arg, " %s => %s\n", from, to); } } #endif DEFINE_STACK_OF(EVP_CIPHER) static int cipher_cmp(const EVP_CIPHER * const *a, const EVP_CIPHER * const *b) { return strcmp(OSSL_PROVIDER_get0_name(EVP_CIPHER_get0_provider(*a)), OSSL_PROVIDER_get0_name(EVP_CIPHER_get0_provider(*b))); } static void collect_ciphers(EVP_CIPHER *cipher, void *stack) { STACK_OF(EVP_CIPHER) *cipher_stack = stack; if (is_cipher_fetchable(cipher) && sk_EVP_CIPHER_push(cipher_stack, cipher) > 0) EVP_CIPHER_up_ref(cipher); } static void list_ciphers(const char *prefix) { STACK_OF(EVP_CIPHER) *ciphers = sk_EVP_CIPHER_new(cipher_cmp); int i; if (ciphers == NULL) { BIO_printf(bio_err, "ERROR: Memory allocation\n"); return; } #ifndef OPENSSL_NO_DEPRECATED_3_0 if (include_legacy()) { BIO_printf(bio_out, "%sLegacy:\n", prefix); EVP_CIPHER_do_all_sorted(legacy_cipher_fn, bio_out); } #endif BIO_printf(bio_out, "%sProvided:\n", prefix); EVP_CIPHER_do_all_provided(app_get0_libctx(), collect_ciphers, ciphers); sk_EVP_CIPHER_sort(ciphers); for (i = 0; i < sk_EVP_CIPHER_num(ciphers); i++) { const EVP_CIPHER *c = sk_EVP_CIPHER_value(ciphers, i); STACK_OF(OPENSSL_CSTRING) *names = NULL; if (select_name != NULL && !EVP_CIPHER_is_a(c, select_name)) continue; names = sk_OPENSSL_CSTRING_new(name_cmp); if (names != NULL && EVP_CIPHER_names_do_all(c, collect_names, names)) { BIO_printf(bio_out, " "); print_names(bio_out, names); BIO_printf(bio_out, " @ %s\n", OSSL_PROVIDER_get0_name(EVP_CIPHER_get0_provider(c))); if (verbose) { const char *desc = EVP_CIPHER_get0_description(c); if (desc != NULL) BIO_printf(bio_out, " description: %s\n", desc); print_param_types("retrievable algorithm parameters", EVP_CIPHER_gettable_params(c), 4); print_param_types("retrievable operation parameters", EVP_CIPHER_gettable_ctx_params(c), 4); print_param_types("settable operation parameters", EVP_CIPHER_settable_ctx_params(c), 4); } } sk_OPENSSL_CSTRING_free(names); } sk_EVP_CIPHER_pop_free(ciphers, EVP_CIPHER_free); } #ifndef OPENSSL_NO_DEPRECATED_3_0 static void legacy_md_fn(const EVP_MD *m, const char *from, const char *to, void *arg) { if (m != NULL) { BIO_printf(arg, " %s\n", EVP_MD_get0_name(m)); } else { if (from == NULL) from = "<undefined>"; if (to == NULL) to = "<undefined>"; BIO_printf((BIO *)arg, " %s => %s\n", from, to); } } #endif DEFINE_STACK_OF(EVP_MD) static int md_cmp(const EVP_MD * const *a, const EVP_MD * const *b) { return strcmp(OSSL_PROVIDER_get0_name(EVP_MD_get0_provider(*a)), OSSL_PROVIDER_get0_name(EVP_MD_get0_provider(*b))); } static void collect_digests(EVP_MD *digest, void *stack) { STACK_OF(EVP_MD) *digest_stack = stack; if (is_digest_fetchable(digest) && sk_EVP_MD_push(digest_stack, digest) > 0) EVP_MD_up_ref(digest); } static void list_digests(const char *prefix) { STACK_OF(EVP_MD) *digests = sk_EVP_MD_new(md_cmp); int i; if (digests == NULL) { BIO_printf(bio_err, "ERROR: Memory allocation\n"); return; } #ifndef OPENSSL_NO_DEPRECATED_3_0 if (include_legacy()) { BIO_printf(bio_out, "%sLegacy:\n", prefix); EVP_MD_do_all_sorted(legacy_md_fn, bio_out); } #endif BIO_printf(bio_out, "%sProvided:\n", prefix); EVP_MD_do_all_provided(app_get0_libctx(), collect_digests, digests); sk_EVP_MD_sort(digests); for (i = 0; i < sk_EVP_MD_num(digests); i++) { const EVP_MD *m = sk_EVP_MD_value(digests, i); STACK_OF(OPENSSL_CSTRING) *names = NULL; if (select_name != NULL && !EVP_MD_is_a(m, select_name)) continue; names = sk_OPENSSL_CSTRING_new(name_cmp); if (names != NULL && EVP_MD_names_do_all(m, collect_names, names)) { BIO_printf(bio_out, " "); print_names(bio_out, names); BIO_printf(bio_out, " @ %s\n", OSSL_PROVIDER_get0_name(EVP_MD_get0_provider(m))); if (verbose) { const char *desc = EVP_MD_get0_description(m); if (desc != NULL) BIO_printf(bio_out, " description: %s\n", desc); print_param_types("retrievable algorithm parameters", EVP_MD_gettable_params(m), 4); print_param_types("retrievable operation parameters", EVP_MD_gettable_ctx_params(m), 4); print_param_types("settable operation parameters", EVP_MD_settable_ctx_params(m), 4); } } sk_OPENSSL_CSTRING_free(names); } sk_EVP_MD_pop_free(digests, EVP_MD_free); } DEFINE_STACK_OF(EVP_MAC) static int mac_cmp(const EVP_MAC * const *a, const EVP_MAC * const *b) { return strcmp(OSSL_PROVIDER_get0_name(EVP_MAC_get0_provider(*a)), OSSL_PROVIDER_get0_name(EVP_MAC_get0_provider(*b))); } static void collect_macs(EVP_MAC *mac, void *stack) { STACK_OF(EVP_MAC) *mac_stack = stack; if (is_mac_fetchable(mac) && sk_EVP_MAC_push(mac_stack, mac) > 0) EVP_MAC_up_ref(mac); } static void list_macs(void) { STACK_OF(EVP_MAC) *macs = sk_EVP_MAC_new(mac_cmp); int i; if (macs == NULL) { BIO_printf(bio_err, "ERROR: Memory allocation\n"); return; } BIO_printf(bio_out, "Provided MACs:\n"); EVP_MAC_do_all_provided(app_get0_libctx(), collect_macs, macs); sk_EVP_MAC_sort(macs); for (i = 0; i < sk_EVP_MAC_num(macs); i++) { const EVP_MAC *m = sk_EVP_MAC_value(macs, i); STACK_OF(OPENSSL_CSTRING) *names = NULL; if (select_name != NULL && !EVP_MAC_is_a(m, select_name)) continue; names = sk_OPENSSL_CSTRING_new(name_cmp); if (names != NULL && EVP_MAC_names_do_all(m, collect_names, names)) { BIO_printf(bio_out, " "); print_names(bio_out, names); BIO_printf(bio_out, " @ %s\n", OSSL_PROVIDER_get0_name(EVP_MAC_get0_provider(m))); if (verbose) { const char *desc = EVP_MAC_get0_description(m); if (desc != NULL) BIO_printf(bio_out, " description: %s\n", desc); print_param_types("retrievable algorithm parameters", EVP_MAC_gettable_params(m), 4); print_param_types("retrievable operation parameters", EVP_MAC_gettable_ctx_params(m), 4); print_param_types("settable operation parameters", EVP_MAC_settable_ctx_params(m), 4); } } sk_OPENSSL_CSTRING_free(names); } sk_EVP_MAC_pop_free(macs, EVP_MAC_free); } /* * KDFs and PRFs */ DEFINE_STACK_OF(EVP_KDF) static int kdf_cmp(const EVP_KDF * const *a, const EVP_KDF * const *b) { return strcmp(OSSL_PROVIDER_get0_name(EVP_KDF_get0_provider(*a)), OSSL_PROVIDER_get0_name(EVP_KDF_get0_provider(*b))); } static void collect_kdfs(EVP_KDF *kdf, void *stack) { STACK_OF(EVP_KDF) *kdf_stack = stack; if (is_kdf_fetchable(kdf) && sk_EVP_KDF_push(kdf_stack, kdf) > 0) EVP_KDF_up_ref(kdf); } static void list_kdfs(void) { STACK_OF(EVP_KDF) *kdfs = sk_EVP_KDF_new(kdf_cmp); int i; if (kdfs == NULL) { BIO_printf(bio_err, "ERROR: Memory allocation\n"); return; } BIO_printf(bio_out, "Provided KDFs and PDFs:\n"); EVP_KDF_do_all_provided(app_get0_libctx(), collect_kdfs, kdfs); sk_EVP_KDF_sort(kdfs); for (i = 0; i < sk_EVP_KDF_num(kdfs); i++) { const EVP_KDF *k = sk_EVP_KDF_value(kdfs, i); STACK_OF(OPENSSL_CSTRING) *names = NULL; if (select_name != NULL && !EVP_KDF_is_a(k, select_name)) continue; names = sk_OPENSSL_CSTRING_new(name_cmp); if (names != NULL && EVP_KDF_names_do_all(k, collect_names, names)) { BIO_printf(bio_out, " "); print_names(bio_out, names); BIO_printf(bio_out, " @ %s\n", OSSL_PROVIDER_get0_name(EVP_KDF_get0_provider(k))); if (verbose) { const char *desc = EVP_KDF_get0_description(k); if (desc != NULL) BIO_printf(bio_out, " description: %s\n", desc); print_param_types("retrievable algorithm parameters", EVP_KDF_gettable_params(k), 4); print_param_types("retrievable operation parameters", EVP_KDF_gettable_ctx_params(k), 4); print_param_types("settable operation parameters", EVP_KDF_settable_ctx_params(k), 4); } } sk_OPENSSL_CSTRING_free(names); } sk_EVP_KDF_pop_free(kdfs, EVP_KDF_free); } /* * RANDs */ DEFINE_STACK_OF(EVP_RAND) static int rand_cmp(const EVP_RAND * const *a, const EVP_RAND * const *b) { int ret = OPENSSL_strcasecmp(EVP_RAND_get0_name(*a), EVP_RAND_get0_name(*b)); if (ret == 0) ret = strcmp(OSSL_PROVIDER_get0_name(EVP_RAND_get0_provider(*a)), OSSL_PROVIDER_get0_name(EVP_RAND_get0_provider(*b))); return ret; } static void collect_rands(EVP_RAND *rand, void *stack) { STACK_OF(EVP_RAND) *rand_stack = stack; if (is_rand_fetchable(rand) && sk_EVP_RAND_push(rand_stack, rand) > 0) EVP_RAND_up_ref(rand); } static void list_random_generators(void) { STACK_OF(EVP_RAND) *rands = sk_EVP_RAND_new(rand_cmp); int i; if (rands == NULL) { BIO_printf(bio_err, "ERROR: Memory allocation\n"); return; } BIO_printf(bio_out, "Provided RNGs and seed sources:\n"); EVP_RAND_do_all_provided(app_get0_libctx(), collect_rands, rands); sk_EVP_RAND_sort(rands); for (i = 0; i < sk_EVP_RAND_num(rands); i++) { const EVP_RAND *m = sk_EVP_RAND_value(rands, i); if (select_name != NULL && OPENSSL_strcasecmp(EVP_RAND_get0_name(m), select_name) != 0) continue; BIO_printf(bio_out, " %s", EVP_RAND_get0_name(m)); BIO_printf(bio_out, " @ %s\n", OSSL_PROVIDER_get0_name(EVP_RAND_get0_provider(m))); if (verbose) { const char *desc = EVP_RAND_get0_description(m); if (desc != NULL) BIO_printf(bio_out, " description: %s\n", desc); print_param_types("retrievable algorithm parameters", EVP_RAND_gettable_params(m), 4); print_param_types("retrievable operation parameters", EVP_RAND_gettable_ctx_params(m), 4); print_param_types("settable operation parameters", EVP_RAND_settable_ctx_params(m), 4); } } sk_EVP_RAND_pop_free(rands, EVP_RAND_free); } static void display_random(const char *name, EVP_RAND_CTX *drbg) { EVP_RAND *rand; uint64_t u; const char *p; const OSSL_PARAM *gettables; OSSL_PARAM params[2] = { OSSL_PARAM_END, OSSL_PARAM_END }; unsigned char buf[1000]; BIO_printf(bio_out, "%s:\n", name); if (drbg != NULL) { rand = EVP_RAND_CTX_get0_rand(drbg); BIO_printf(bio_out, " %s", EVP_RAND_get0_name(rand)); BIO_printf(bio_out, " @ %s\n", OSSL_PROVIDER_get0_name(EVP_RAND_get0_provider(rand))); switch (EVP_RAND_get_state(drbg)) { case EVP_RAND_STATE_UNINITIALISED: p = "uninitialised"; break; case EVP_RAND_STATE_READY: p = "ready"; break; case EVP_RAND_STATE_ERROR: p = "error"; break; default: p = "unknown"; break; } BIO_printf(bio_out, " state = %s\n", p); gettables = EVP_RAND_gettable_ctx_params(rand); if (gettables != NULL) for (; gettables->key != NULL; gettables++) { /* State has been dealt with already, so ignore */ if (OPENSSL_strcasecmp(gettables->key, OSSL_RAND_PARAM_STATE) == 0) continue; /* Outside of verbose mode, we skip non-string values */ if (gettables->data_type != OSSL_PARAM_UTF8_STRING && gettables->data_type != OSSL_PARAM_UTF8_PTR && !verbose) continue; params->key = gettables->key; params->data_type = gettables->data_type; if (gettables->data_type == OSSL_PARAM_UNSIGNED_INTEGER || gettables->data_type == OSSL_PARAM_INTEGER) { params->data = &u; params->data_size = sizeof(u); } else { params->data = buf; params->data_size = sizeof(buf); } params->return_size = 0; if (EVP_RAND_CTX_get_params(drbg, params)) print_param_value(params, 2); } } } static void list_random_instances(void) { display_random("primary", RAND_get0_primary(NULL)); display_random("public", RAND_get0_public(NULL)); display_random("private", RAND_get0_private(NULL)); } /* * Encoders */ DEFINE_STACK_OF(OSSL_ENCODER) static int encoder_cmp(const OSSL_ENCODER * const *a, const OSSL_ENCODER * const *b) { return strcmp(OSSL_PROVIDER_get0_name(OSSL_ENCODER_get0_provider(*a)), OSSL_PROVIDER_get0_name(OSSL_ENCODER_get0_provider(*b))); } static void collect_encoders(OSSL_ENCODER *encoder, void *stack) { STACK_OF(OSSL_ENCODER) *encoder_stack = stack; if (is_encoder_fetchable(encoder) && sk_OSSL_ENCODER_push(encoder_stack, encoder) > 0) OSSL_ENCODER_up_ref(encoder); } static void list_encoders(void) { STACK_OF(OSSL_ENCODER) *encoders; int i; encoders = sk_OSSL_ENCODER_new(encoder_cmp); if (encoders == NULL) { BIO_printf(bio_err, "ERROR: Memory allocation\n"); return; } BIO_printf(bio_out, "Provided ENCODERs:\n"); OSSL_ENCODER_do_all_provided(app_get0_libctx(), collect_encoders, encoders); sk_OSSL_ENCODER_sort(encoders); for (i = 0; i < sk_OSSL_ENCODER_num(encoders); i++) { OSSL_ENCODER *k = sk_OSSL_ENCODER_value(encoders, i); STACK_OF(OPENSSL_CSTRING) *names = NULL; if (select_name != NULL && !OSSL_ENCODER_is_a(k, select_name)) continue; names = sk_OPENSSL_CSTRING_new(name_cmp); if (names != NULL && OSSL_ENCODER_names_do_all(k, collect_names, names)) { BIO_printf(bio_out, " "); print_names(bio_out, names); BIO_printf(bio_out, " @ %s (%s)\n", OSSL_PROVIDER_get0_name(OSSL_ENCODER_get0_provider(k)), OSSL_ENCODER_get0_properties(k)); if (verbose) { const char *desc = OSSL_ENCODER_get0_description(k); if (desc != NULL) BIO_printf(bio_out, " description: %s\n", desc); print_param_types("settable operation parameters", OSSL_ENCODER_settable_ctx_params(k), 4); } } sk_OPENSSL_CSTRING_free(names); } sk_OSSL_ENCODER_pop_free(encoders, OSSL_ENCODER_free); } /* * Decoders */ DEFINE_STACK_OF(OSSL_DECODER) static int decoder_cmp(const OSSL_DECODER * const *a, const OSSL_DECODER * const *b) { return strcmp(OSSL_PROVIDER_get0_name(OSSL_DECODER_get0_provider(*a)), OSSL_PROVIDER_get0_name(OSSL_DECODER_get0_provider(*b))); } static void collect_decoders(OSSL_DECODER *decoder, void *stack) { STACK_OF(OSSL_DECODER) *decoder_stack = stack; if (is_decoder_fetchable(decoder) && sk_OSSL_DECODER_push(decoder_stack, decoder) > 0) OSSL_DECODER_up_ref(decoder); } static void list_decoders(void) { STACK_OF(OSSL_DECODER) *decoders; int i; decoders = sk_OSSL_DECODER_new(decoder_cmp); if (decoders == NULL) { BIO_printf(bio_err, "ERROR: Memory allocation\n"); return; } BIO_printf(bio_out, "Provided DECODERs:\n"); OSSL_DECODER_do_all_provided(app_get0_libctx(), collect_decoders, decoders); sk_OSSL_DECODER_sort(decoders); for (i = 0; i < sk_OSSL_DECODER_num(decoders); i++) { OSSL_DECODER *k = sk_OSSL_DECODER_value(decoders, i); STACK_OF(OPENSSL_CSTRING) *names = NULL; if (select_name != NULL && !OSSL_DECODER_is_a(k, select_name)) continue; names = sk_OPENSSL_CSTRING_new(name_cmp); if (names != NULL && OSSL_DECODER_names_do_all(k, collect_names, names)) { BIO_printf(bio_out, " "); print_names(bio_out, names); BIO_printf(bio_out, " @ %s (%s)\n", OSSL_PROVIDER_get0_name(OSSL_DECODER_get0_provider(k)), OSSL_DECODER_get0_properties(k)); if (verbose) { const char *desc = OSSL_DECODER_get0_description(k); if (desc != NULL) BIO_printf(bio_out, " description: %s\n", desc); print_param_types("settable operation parameters", OSSL_DECODER_settable_ctx_params(k), 4); } } sk_OPENSSL_CSTRING_free(names); } sk_OSSL_DECODER_pop_free(decoders, OSSL_DECODER_free); } DEFINE_STACK_OF(EVP_KEYMGMT) static int keymanager_cmp(const EVP_KEYMGMT * const *a, const EVP_KEYMGMT * const *b) { return strcmp(OSSL_PROVIDER_get0_name(EVP_KEYMGMT_get0_provider(*a)), OSSL_PROVIDER_get0_name(EVP_KEYMGMT_get0_provider(*b))); } static void collect_keymanagers(EVP_KEYMGMT *km, void *stack) { STACK_OF(EVP_KEYMGMT) *km_stack = stack; if (is_keymgmt_fetchable(km) && sk_EVP_KEYMGMT_push(km_stack, km) > 0) EVP_KEYMGMT_up_ref(km); } static void list_keymanagers(void) { int i; STACK_OF(EVP_KEYMGMT) *km_stack = sk_EVP_KEYMGMT_new(keymanager_cmp); EVP_KEYMGMT_do_all_provided(app_get0_libctx(), collect_keymanagers, km_stack); sk_EVP_KEYMGMT_sort(km_stack); for (i = 0; i < sk_EVP_KEYMGMT_num(km_stack); i++) { EVP_KEYMGMT *k = sk_EVP_KEYMGMT_value(km_stack, i); STACK_OF(OPENSSL_CSTRING) *names = NULL; if (select_name != NULL && !EVP_KEYMGMT_is_a(k, select_name)) continue; names = sk_OPENSSL_CSTRING_new(name_cmp); if (names != NULL && EVP_KEYMGMT_names_do_all(k, collect_names, names)) { const char *desc = EVP_KEYMGMT_get0_description(k); BIO_printf(bio_out, " Name: "); if (desc != NULL) BIO_printf(bio_out, "%s", desc); else BIO_printf(bio_out, "%s", sk_OPENSSL_CSTRING_value(names, 0)); BIO_printf(bio_out, "\n"); BIO_printf(bio_out, " Type: Provider Algorithm\n"); BIO_printf(bio_out, " IDs: "); print_names(bio_out, names); BIO_printf(bio_out, " @ %s\n", OSSL_PROVIDER_get0_name(EVP_KEYMGMT_get0_provider(k))); if (verbose) { print_param_types("settable key generation parameters", EVP_KEYMGMT_gen_settable_params(k), 4); print_param_types("settable operation parameters", EVP_KEYMGMT_settable_params(k), 4); print_param_types("retrievable operation parameters", EVP_KEYMGMT_gettable_params(k), 4); } } sk_OPENSSL_CSTRING_free(names); } sk_EVP_KEYMGMT_pop_free(km_stack, EVP_KEYMGMT_free); } DEFINE_STACK_OF(EVP_SIGNATURE) static int signature_cmp(const EVP_SIGNATURE * const *a, const EVP_SIGNATURE * const *b) { return strcmp(OSSL_PROVIDER_get0_name(EVP_SIGNATURE_get0_provider(*a)), OSSL_PROVIDER_get0_name(EVP_SIGNATURE_get0_provider(*b))); } static void collect_signatures(EVP_SIGNATURE *sig, void *stack) { STACK_OF(EVP_SIGNATURE) *sig_stack = stack; if (is_signature_fetchable(sig) && sk_EVP_SIGNATURE_push(sig_stack, sig) > 0) EVP_SIGNATURE_up_ref(sig); } static void list_signatures(void) { int i, count = 0; STACK_OF(EVP_SIGNATURE) *sig_stack = sk_EVP_SIGNATURE_new(signature_cmp); EVP_SIGNATURE_do_all_provided(app_get0_libctx(), collect_signatures, sig_stack); sk_EVP_SIGNATURE_sort(sig_stack); for (i = 0; i < sk_EVP_SIGNATURE_num(sig_stack); i++) { EVP_SIGNATURE *k = sk_EVP_SIGNATURE_value(sig_stack, i); STACK_OF(OPENSSL_CSTRING) *names = NULL; if (select_name != NULL && !EVP_SIGNATURE_is_a(k, select_name)) continue; names = sk_OPENSSL_CSTRING_new(name_cmp); if (names != NULL && EVP_SIGNATURE_names_do_all(k, collect_names, names)) { count++; BIO_printf(bio_out, " "); print_names(bio_out, names); BIO_printf(bio_out, " @ %s\n", OSSL_PROVIDER_get0_name(EVP_SIGNATURE_get0_provider(k))); if (verbose) { const char *desc = EVP_SIGNATURE_get0_description(k); if (desc != NULL) BIO_printf(bio_out, " description: %s\n", desc); print_param_types("settable operation parameters", EVP_SIGNATURE_settable_ctx_params(k), 4); print_param_types("retrievable operation parameters", EVP_SIGNATURE_gettable_ctx_params(k), 4); } } sk_OPENSSL_CSTRING_free(names); } sk_EVP_SIGNATURE_pop_free(sig_stack, EVP_SIGNATURE_free); if (count == 0) BIO_printf(bio_out, " -\n"); } DEFINE_STACK_OF(EVP_KEM) static int kem_cmp(const EVP_KEM * const *a, const EVP_KEM * const *b) { return strcmp(OSSL_PROVIDER_get0_name(EVP_KEM_get0_provider(*a)), OSSL_PROVIDER_get0_name(EVP_KEM_get0_provider(*b))); } static void collect_kem(EVP_KEM *kem, void *stack) { STACK_OF(EVP_KEM) *kem_stack = stack; if (is_kem_fetchable(kem) && sk_EVP_KEM_push(kem_stack, kem) > 0) EVP_KEM_up_ref(kem); } static void list_kems(void) { int i, count = 0; STACK_OF(EVP_KEM) *kem_stack = sk_EVP_KEM_new(kem_cmp); EVP_KEM_do_all_provided(app_get0_libctx(), collect_kem, kem_stack); sk_EVP_KEM_sort(kem_stack); for (i = 0; i < sk_EVP_KEM_num(kem_stack); i++) { EVP_KEM *k = sk_EVP_KEM_value(kem_stack, i); STACK_OF(OPENSSL_CSTRING) *names = NULL; if (select_name != NULL && !EVP_KEM_is_a(k, select_name)) continue; names = sk_OPENSSL_CSTRING_new(name_cmp); if (names != NULL && EVP_KEM_names_do_all(k, collect_names, names)) { count++; BIO_printf(bio_out, " "); print_names(bio_out, names); BIO_printf(bio_out, " @ %s\n", OSSL_PROVIDER_get0_name(EVP_KEM_get0_provider(k))); if (verbose) { const char *desc = EVP_KEM_get0_description(k); if (desc != NULL) BIO_printf(bio_out, " description: %s\n", desc); print_param_types("settable operation parameters", EVP_KEM_settable_ctx_params(k), 4); print_param_types("retrievable operation parameters", EVP_KEM_gettable_ctx_params(k), 4); } } sk_OPENSSL_CSTRING_free(names); } sk_EVP_KEM_pop_free(kem_stack, EVP_KEM_free); if (count == 0) BIO_printf(bio_out, " -\n"); } DEFINE_STACK_OF(EVP_ASYM_CIPHER) static int asymcipher_cmp(const EVP_ASYM_CIPHER * const *a, const EVP_ASYM_CIPHER * const *b) { return strcmp(OSSL_PROVIDER_get0_name(EVP_ASYM_CIPHER_get0_provider(*a)), OSSL_PROVIDER_get0_name(EVP_ASYM_CIPHER_get0_provider(*b))); } static void collect_asymciph(EVP_ASYM_CIPHER *asym_cipher, void *stack) { STACK_OF(EVP_ASYM_CIPHER) *asym_cipher_stack = stack; if (is_asym_cipher_fetchable(asym_cipher) && sk_EVP_ASYM_CIPHER_push(asym_cipher_stack, asym_cipher) > 0) EVP_ASYM_CIPHER_up_ref(asym_cipher); } static void list_asymciphers(void) { int i, count = 0; STACK_OF(EVP_ASYM_CIPHER) *asymciph_stack = sk_EVP_ASYM_CIPHER_new(asymcipher_cmp); EVP_ASYM_CIPHER_do_all_provided(app_get0_libctx(), collect_asymciph, asymciph_stack); sk_EVP_ASYM_CIPHER_sort(asymciph_stack); for (i = 0; i < sk_EVP_ASYM_CIPHER_num(asymciph_stack); i++) { EVP_ASYM_CIPHER *k = sk_EVP_ASYM_CIPHER_value(asymciph_stack, i); STACK_OF(OPENSSL_CSTRING) *names = NULL; if (select_name != NULL && !EVP_ASYM_CIPHER_is_a(k, select_name)) continue; names = sk_OPENSSL_CSTRING_new(name_cmp); if (names != NULL && EVP_ASYM_CIPHER_names_do_all(k, collect_names, names)) { count++; BIO_printf(bio_out, " "); print_names(bio_out, names); BIO_printf(bio_out, " @ %s\n", OSSL_PROVIDER_get0_name(EVP_ASYM_CIPHER_get0_provider(k))); if (verbose) { const char *desc = EVP_ASYM_CIPHER_get0_description(k); if (desc != NULL) BIO_printf(bio_out, " description: %s\n", desc); print_param_types("settable operation parameters", EVP_ASYM_CIPHER_settable_ctx_params(k), 4); print_param_types("retrievable operation parameters", EVP_ASYM_CIPHER_gettable_ctx_params(k), 4); } } sk_OPENSSL_CSTRING_free(names); } sk_EVP_ASYM_CIPHER_pop_free(asymciph_stack, EVP_ASYM_CIPHER_free); if (count == 0) BIO_printf(bio_out, " -\n"); } DEFINE_STACK_OF(EVP_KEYEXCH) static int kex_cmp(const EVP_KEYEXCH * const *a, const EVP_KEYEXCH * const *b) { return strcmp(OSSL_PROVIDER_get0_name(EVP_KEYEXCH_get0_provider(*a)), OSSL_PROVIDER_get0_name(EVP_KEYEXCH_get0_provider(*b))); } static void collect_kex(EVP_KEYEXCH *kex, void *stack) { STACK_OF(EVP_KEYEXCH) *kex_stack = stack; if (is_keyexch_fetchable(kex) && sk_EVP_KEYEXCH_push(kex_stack, kex) > 0) EVP_KEYEXCH_up_ref(kex); } static void list_keyexchanges(void) { int i, count = 0; STACK_OF(EVP_KEYEXCH) *kex_stack = sk_EVP_KEYEXCH_new(kex_cmp); EVP_KEYEXCH_do_all_provided(app_get0_libctx(), collect_kex, kex_stack); sk_EVP_KEYEXCH_sort(kex_stack); for (i = 0; i < sk_EVP_KEYEXCH_num(kex_stack); i++) { EVP_KEYEXCH *k = sk_EVP_KEYEXCH_value(kex_stack, i); STACK_OF(OPENSSL_CSTRING) *names = NULL; if (select_name != NULL && !EVP_KEYEXCH_is_a(k, select_name)) continue; names = sk_OPENSSL_CSTRING_new(name_cmp); if (names != NULL && EVP_KEYEXCH_names_do_all(k, collect_names, names)) { count++; BIO_printf(bio_out, " "); print_names(bio_out, names); BIO_printf(bio_out, " @ %s\n", OSSL_PROVIDER_get0_name(EVP_KEYEXCH_get0_provider(k))); if (verbose) { const char *desc = EVP_KEYEXCH_get0_description(k); if (desc != NULL) BIO_printf(bio_out, " description: %s\n", desc); print_param_types("settable operation parameters", EVP_KEYEXCH_settable_ctx_params(k), 4); print_param_types("retrievable operation parameters", EVP_KEYEXCH_gettable_ctx_params(k), 4); } } sk_OPENSSL_CSTRING_free(names); } sk_EVP_KEYEXCH_pop_free(kex_stack, EVP_KEYEXCH_free); if (count == 0) BIO_printf(bio_out, " -\n"); } static void list_objects(void) { int max_nid = OBJ_new_nid(0); int i; char *oid_buf = NULL; int oid_size = 0; /* Skip 0, since that's NID_undef */ for (i = 1; i < max_nid; i++) { const ASN1_OBJECT *obj = OBJ_nid2obj(i); const char *sn = OBJ_nid2sn(i); const char *ln = OBJ_nid2ln(i); int n = 0; /* * If one of the retrieved objects somehow generated an error, * we ignore it. The check for NID_undef below will detect the * error and simply skip to the next NID. */ ERR_clear_error(); if (OBJ_obj2nid(obj) == NID_undef) continue; if ((n = OBJ_obj2txt(NULL, 0, obj, 1)) == 0) { BIO_printf(bio_out, "# None-OID object: %s, %s\n", sn, ln); continue; } if (n < 0) break; /* Error */ if (n > oid_size) { oid_buf = OPENSSL_realloc(oid_buf, n + 1); if (oid_buf == NULL) { BIO_printf(bio_err, "ERROR: Memory allocation\n"); break; /* Error */ } oid_size = n + 1; } if (OBJ_obj2txt(oid_buf, oid_size, obj, 1) < 0) break; /* Error */ if (ln == NULL || strcmp(sn, ln) == 0) BIO_printf(bio_out, "%s = %s\n", sn, oid_buf); else BIO_printf(bio_out, "%s = %s, %s\n", sn, ln, oid_buf); } OPENSSL_free(oid_buf); } static void list_options_for_command(const char *command) { const FUNCTION *fp; const OPTIONS *o; for (fp = functions; fp->name != NULL; fp++) if (strcmp(fp->name, command) == 0) break; if (fp->name == NULL) { BIO_printf(bio_err, "Invalid command '%s'; type \"help\" for a list.\n", command); return; } if ((o = fp->help) == NULL) return; for ( ; o->name != NULL; o++) { char c = o->valtype; if (o->name == OPT_PARAM_STR) break; if (o->name == OPT_HELP_STR || o->name == OPT_MORE_STR || o->name == OPT_SECTION_STR || o->name[0] == '\0') continue; BIO_printf(bio_out, "%s %c\n", o->name, c == '\0' ? '-' : c); } /* Always output the -- marker since it is sometimes documented. */ BIO_printf(bio_out, "- -\n"); } static int is_md_available(const char *name) { EVP_MD *md; const char *propq = app_get0_propq(); /* Look through providers' digests */ ERR_set_mark(); md = EVP_MD_fetch(app_get0_libctx(), name, propq); ERR_pop_to_mark(); if (md != NULL) { EVP_MD_free(md); return 1; } return propq != NULL || get_digest_from_engine(name) == NULL ? 0 : 1; } static int is_cipher_available(const char *name) { EVP_CIPHER *cipher; const char *propq = app_get0_propq(); /* Look through providers' ciphers */ ERR_set_mark(); cipher = EVP_CIPHER_fetch(app_get0_libctx(), name, propq); ERR_pop_to_mark(); if (cipher != NULL) { EVP_CIPHER_free(cipher); return 1; } return propq != NULL || get_cipher_from_engine(name) == NULL ? 0 : 1; } static void list_type(FUNC_TYPE ft, int one) { FUNCTION *fp; int i = 0; DISPLAY_COLUMNS dc; memset(&dc, 0, sizeof(dc)); if (!one) calculate_columns(functions, &dc); for (fp = functions; fp->name != NULL; fp++) { if (fp->type != ft) continue; switch (ft) { case FT_cipher: if (!is_cipher_available(fp->name)) continue; break; case FT_md: if (!is_md_available(fp->name)) continue; break; default: break; } if (one) { BIO_printf(bio_out, "%s\n", fp->name); } else { if (i % dc.columns == 0 && i > 0) BIO_printf(bio_out, "\n"); BIO_printf(bio_out, "%-*s", dc.width, fp->name); i++; } } if (!one) BIO_printf(bio_out, "\n\n"); } static void list_pkey(void) { #ifndef OPENSSL_NO_DEPRECATED_3_0 int i; if (select_name == NULL && include_legacy()) { BIO_printf(bio_out, "Legacy:\n"); for (i = 0; i < EVP_PKEY_asn1_get_count(); i++) { const EVP_PKEY_ASN1_METHOD *ameth; int pkey_id, pkey_base_id, pkey_flags; const char *pinfo, *pem_str; ameth = EVP_PKEY_asn1_get0(i); EVP_PKEY_asn1_get0_info(&pkey_id, &pkey_base_id, &pkey_flags, &pinfo, &pem_str, ameth); if (pkey_flags & ASN1_PKEY_ALIAS) { BIO_printf(bio_out, " Name: %s\n", OBJ_nid2ln(pkey_id)); BIO_printf(bio_out, "\tAlias for: %s\n", OBJ_nid2ln(pkey_base_id)); } else { BIO_printf(bio_out, " Name: %s\n", pinfo); BIO_printf(bio_out, "\tType: %s Algorithm\n", pkey_flags & ASN1_PKEY_DYNAMIC ? "External" : "Builtin"); BIO_printf(bio_out, "\tOID: %s\n", OBJ_nid2ln(pkey_id)); if (pem_str == NULL) pem_str = "(none)"; BIO_printf(bio_out, "\tPEM string: %s\n", pem_str); } } } #endif BIO_printf(bio_out, "Provided:\n"); BIO_printf(bio_out, " Key Managers:\n"); list_keymanagers(); } static void list_pkey_meth(void) { #ifndef OPENSSL_NO_DEPRECATED_3_0 size_t i; size_t meth_count = EVP_PKEY_meth_get_count(); if (select_name == NULL && include_legacy()) { BIO_printf(bio_out, "Legacy:\n"); for (i = 0; i < meth_count; i++) { const EVP_PKEY_METHOD *pmeth = EVP_PKEY_meth_get0(i); int pkey_id, pkey_flags; EVP_PKEY_meth_get0_info(&pkey_id, &pkey_flags, pmeth); BIO_printf(bio_out, " %s\n", OBJ_nid2ln(pkey_id)); BIO_printf(bio_out, "\tType: %s Algorithm\n", pkey_flags & ASN1_PKEY_DYNAMIC ? "External" : "Builtin"); } } #endif BIO_printf(bio_out, "Provided:\n"); BIO_printf(bio_out, " Encryption:\n"); list_asymciphers(); BIO_printf(bio_out, " Key Exchange:\n"); list_keyexchanges(); BIO_printf(bio_out, " Signatures:\n"); list_signatures(); BIO_printf(bio_out, " Key encapsulation:\n"); list_kems(); } DEFINE_STACK_OF(OSSL_STORE_LOADER) static int store_cmp(const OSSL_STORE_LOADER * const *a, const OSSL_STORE_LOADER * const *b) { return strcmp(OSSL_PROVIDER_get0_name(OSSL_STORE_LOADER_get0_provider(*a)), OSSL_PROVIDER_get0_name(OSSL_STORE_LOADER_get0_provider(*b))); } static void collect_store_loaders(OSSL_STORE_LOADER *store, void *stack) { STACK_OF(OSSL_STORE_LOADER) *store_stack = stack; if (sk_OSSL_STORE_LOADER_push(store_stack, store) > 0) OSSL_STORE_LOADER_up_ref(store); } static void list_store_loaders(void) { STACK_OF(OSSL_STORE_LOADER) *stores = sk_OSSL_STORE_LOADER_new(store_cmp); int i; if (stores == NULL) { BIO_printf(bio_err, "ERROR: Memory allocation\n"); return; } BIO_printf(bio_out, "Provided STORE LOADERs:\n"); OSSL_STORE_LOADER_do_all_provided(app_get0_libctx(), collect_store_loaders, stores); sk_OSSL_STORE_LOADER_sort(stores); for (i = 0; i < sk_OSSL_STORE_LOADER_num(stores); i++) { const OSSL_STORE_LOADER *m = sk_OSSL_STORE_LOADER_value(stores, i); STACK_OF(OPENSSL_CSTRING) *names = NULL; if (select_name != NULL && !OSSL_STORE_LOADER_is_a(m, select_name)) continue; names = sk_OPENSSL_CSTRING_new(name_cmp); if (names != NULL && OSSL_STORE_LOADER_names_do_all(m, collect_names, names)) { BIO_printf(bio_out, " "); print_names(bio_out, names); BIO_printf(bio_out, " @ %s\n", OSSL_PROVIDER_get0_name(OSSL_STORE_LOADER_get0_provider(m))); } sk_OPENSSL_CSTRING_free(names); } sk_OSSL_STORE_LOADER_pop_free(stores, OSSL_STORE_LOADER_free); } DEFINE_STACK_OF(OSSL_PROVIDER) static int provider_cmp(const OSSL_PROVIDER * const *a, const OSSL_PROVIDER * const *b) { return strcmp(OSSL_PROVIDER_get0_name(*a), OSSL_PROVIDER_get0_name(*b)); } static int collect_providers(OSSL_PROVIDER *provider, void *stack) { STACK_OF(OSSL_PROVIDER) *provider_stack = stack; /* * If OK - result is the index of inserted data * Error - result is -1 or 0 */ return sk_OSSL_PROVIDER_push(provider_stack, provider) > 0 ? 1 : 0; } static void list_provider_info(void) { STACK_OF(OSSL_PROVIDER) *providers = sk_OSSL_PROVIDER_new(provider_cmp); OSSL_PARAM params[5]; char *name, *version, *buildinfo; int status; int i; if (providers == NULL) { BIO_printf(bio_err, "ERROR: Memory allocation\n"); return; } if (OSSL_PROVIDER_do_all(NULL, &collect_providers, providers) != 1) { BIO_printf(bio_err, "ERROR: Memory allocation\n"); return; } BIO_printf(bio_out, "Providers:\n"); sk_OSSL_PROVIDER_sort(providers); for (i = 0; i < sk_OSSL_PROVIDER_num(providers); i++) { const OSSL_PROVIDER *prov = sk_OSSL_PROVIDER_value(providers, i); const char *provname = OSSL_PROVIDER_get0_name(prov); BIO_printf(bio_out, " %s\n", provname); /* Query the "known" information parameters, the order matches below */ 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 (!OSSL_PROVIDER_get_params(prov, params)) { BIO_printf(bio_err, "WARNING: Unable to query provider parameters for %s\n", provname); } else { /* Print out the provider information, the params order matches above */ if (OSSL_PARAM_modified(params)) BIO_printf(bio_out, " name: %s\n", name); if (OSSL_PARAM_modified(params + 1)) BIO_printf(bio_out, " version: %s\n", version); if (OSSL_PARAM_modified(params + 2)) BIO_printf(bio_out, " status: %sactive\n", status ? "" : "in"); if (verbose) { if (OSSL_PARAM_modified(params + 3)) BIO_printf(bio_out, " build info: %s\n", buildinfo); print_param_types("gettable provider parameters", OSSL_PROVIDER_gettable_params(prov), 4); } } } sk_OSSL_PROVIDER_free(providers); } #ifndef OPENSSL_NO_DEPRECATED_3_0 static void list_engines(void) { # ifndef OPENSSL_NO_ENGINE ENGINE *e; BIO_puts(bio_out, "Engines:\n"); e = ENGINE_get_first(); while (e) { BIO_printf(bio_out, "%s\n", ENGINE_get_id(e)); e = ENGINE_get_next(e); } # else BIO_puts(bio_out, "Engine support is disabled.\n"); # endif } #endif static void list_disabled(void) { BIO_puts(bio_out, "Disabled algorithms:\n"); #ifdef OPENSSL_NO_ARGON2 BIO_puts(bio_out, "ARGON2\n"); #endif #ifdef OPENSSL_NO_ARIA BIO_puts(bio_out, "ARIA\n"); #endif #ifdef OPENSSL_NO_BF BIO_puts(bio_out, "BF\n"); #endif #ifdef OPENSSL_NO_BLAKE2 BIO_puts(bio_out, "BLAKE2\n"); #endif #ifdef OPENSSL_NO_CAMELLIA BIO_puts(bio_out, "CAMELLIA\n"); #endif #ifdef OPENSSL_NO_CAST BIO_puts(bio_out, "CAST\n"); #endif #ifdef OPENSSL_NO_CMAC BIO_puts(bio_out, "CMAC\n"); #endif #ifdef OPENSSL_NO_CMS BIO_puts(bio_out, "CMS\n"); #endif #ifdef OPENSSL_NO_COMP BIO_puts(bio_out, "COMP\n"); #endif #ifdef OPENSSL_NO_DES BIO_puts(bio_out, "DES\n"); #endif #ifdef OPENSSL_NO_DGRAM BIO_puts(bio_out, "DGRAM\n"); #endif #ifdef OPENSSL_NO_DH BIO_puts(bio_out, "DH\n"); #endif #ifdef OPENSSL_NO_DSA BIO_puts(bio_out, "DSA\n"); #endif #if defined(OPENSSL_NO_DTLS) BIO_puts(bio_out, "DTLS\n"); #endif #if defined(OPENSSL_NO_DTLS1) BIO_puts(bio_out, "DTLS1\n"); #endif #if defined(OPENSSL_NO_DTLS1_2) BIO_puts(bio_out, "DTLS1_2\n"); #endif #ifdef OPENSSL_NO_EC BIO_puts(bio_out, "EC\n"); #endif #ifdef OPENSSL_NO_ECX BIO_puts(bio_out, "ECX\n"); #endif #ifdef OPENSSL_NO_EC2M BIO_puts(bio_out, "EC2M\n"); #endif #if defined(OPENSSL_NO_ENGINE) && !defined(OPENSSL_NO_DEPRECATED_3_0) BIO_puts(bio_out, "ENGINE\n"); #endif #ifdef OPENSSL_NO_GOST BIO_puts(bio_out, "GOST\n"); #endif #ifdef OPENSSL_NO_IDEA BIO_puts(bio_out, "IDEA\n"); #endif #ifdef OPENSSL_NO_MD2 BIO_puts(bio_out, "MD2\n"); #endif #ifdef OPENSSL_NO_MD4 BIO_puts(bio_out, "MD4\n"); #endif #ifdef OPENSSL_NO_MD5 BIO_puts(bio_out, "MD5\n"); #endif #ifdef OPENSSL_NO_MDC2 BIO_puts(bio_out, "MDC2\n"); #endif #ifdef OPENSSL_NO_OCB BIO_puts(bio_out, "OCB\n"); #endif #ifdef OPENSSL_NO_OCSP BIO_puts(bio_out, "OCSP\n"); #endif #ifdef OPENSSL_NO_PSK BIO_puts(bio_out, "PSK\n"); #endif #ifdef OPENSSL_NO_RC2 BIO_puts(bio_out, "RC2\n"); #endif #ifdef OPENSSL_NO_RC4 BIO_puts(bio_out, "RC4\n"); #endif #ifdef OPENSSL_NO_RC5 BIO_puts(bio_out, "RC5\n"); #endif #ifdef OPENSSL_NO_RMD160 BIO_puts(bio_out, "RMD160\n"); #endif #ifdef OPENSSL_NO_SCRYPT BIO_puts(bio_out, "SCRYPT\n"); #endif #ifdef OPENSSL_NO_SCTP BIO_puts(bio_out, "SCTP\n"); #endif #ifdef OPENSSL_NO_SEED BIO_puts(bio_out, "SEED\n"); #endif #ifdef OPENSSL_NO_SM2 BIO_puts(bio_out, "SM2\n"); #endif #ifdef OPENSSL_NO_SM3 BIO_puts(bio_out, "SM3\n"); #endif #ifdef OPENSSL_NO_SM4 BIO_puts(bio_out, "SM4\n"); #endif #ifdef OPENSSL_NO_SOCK BIO_puts(bio_out, "SOCK\n"); #endif #ifdef OPENSSL_NO_SRP BIO_puts(bio_out, "SRP\n"); #endif #ifdef OPENSSL_NO_SRTP BIO_puts(bio_out, "SRTP\n"); #endif #ifdef OPENSSL_NO_SSL3 BIO_puts(bio_out, "SSL3\n"); #endif #ifdef OPENSSL_NO_TLS1 BIO_puts(bio_out, "TLS1\n"); #endif #ifdef OPENSSL_NO_TLS1_1 BIO_puts(bio_out, "TLS1_1\n"); #endif #ifdef OPENSSL_NO_TLS1_2 BIO_puts(bio_out, "TLS1_2\n"); #endif #ifdef OPENSSL_NO_WHIRLPOOL BIO_puts(bio_out, "WHIRLPOOL\n"); #endif #ifdef OPENSSL_NO_ZLIB BIO_puts(bio_out, "ZLIB\n"); #endif #ifdef OPENSSL_NO_BROTLI BIO_puts(bio_out, "BROTLI\n"); #endif #ifdef OPENSSL_NO_ZSTD BIO_puts(bio_out, "ZSTD\n"); #endif } /* Unified enum for help and list commands. */ typedef enum HELPLIST_CHOICE { OPT_COMMON, OPT_ONE, OPT_VERBOSE, OPT_ALL_ARGORITHMS, OPT_COMMANDS, OPT_DIGEST_COMMANDS, OPT_MAC_ALGORITHMS, OPT_OPTIONS, OPT_DIGEST_ALGORITHMS, OPT_CIPHER_COMMANDS, OPT_CIPHER_ALGORITHMS, OPT_PK_ALGORITHMS, OPT_PK_METHOD, OPT_DISABLED, OPT_KDF_ALGORITHMS, OPT_RANDOM_INSTANCES, OPT_RANDOM_GENERATORS, OPT_ENCODERS, OPT_DECODERS, OPT_KEYMANAGERS, OPT_KEYEXCHANGE_ALGORITHMS, OPT_KEM_ALGORITHMS, OPT_SIGNATURE_ALGORITHMS, OPT_ASYM_CIPHER_ALGORITHMS, OPT_STORE_LOADERS, OPT_PROVIDER_INFO, OPT_OBJECTS, OPT_SELECT_NAME, #ifndef OPENSSL_NO_DEPRECATED_3_0 OPT_ENGINES, #endif OPT_PROV_ENUM } HELPLIST_CHOICE; const OPTIONS list_options[] = { OPT_SECTION("General"), {"help", OPT_HELP, '-', "Display this summary"}, OPT_SECTION("Output"), {"1", OPT_ONE, '-', "List in one column"}, {"verbose", OPT_VERBOSE, '-', "Verbose listing"}, {"select", OPT_SELECT_NAME, 's', "Select a single algorithm"}, {"commands", OPT_COMMANDS, '-', "List of standard commands"}, {"standard-commands", OPT_COMMANDS, '-', "List of standard commands"}, {"all-algorithms", OPT_ALL_ARGORITHMS, '-', "List of all algorithms"}, #ifndef OPENSSL_NO_DEPRECATED_3_0 {"digest-commands", OPT_DIGEST_COMMANDS, '-', "List of message digest commands (deprecated)"}, #endif {"digest-algorithms", OPT_DIGEST_ALGORITHMS, '-', "List of message digest algorithms"}, {"kdf-algorithms", OPT_KDF_ALGORITHMS, '-', "List of key derivation and pseudo random function algorithms"}, {"random-instances", OPT_RANDOM_INSTANCES, '-', "List the primary, public and private random number generator details"}, {"random-generators", OPT_RANDOM_GENERATORS, '-', "List of random number generators"}, {"mac-algorithms", OPT_MAC_ALGORITHMS, '-', "List of message authentication code algorithms"}, #ifndef OPENSSL_NO_DEPRECATED_3_0 {"cipher-commands", OPT_CIPHER_COMMANDS, '-', "List of cipher commands (deprecated)"}, #endif {"cipher-algorithms", OPT_CIPHER_ALGORITHMS, '-', "List of symmetric cipher algorithms"}, {"encoders", OPT_ENCODERS, '-', "List of encoding methods" }, {"decoders", OPT_DECODERS, '-', "List of decoding methods" }, {"key-managers", OPT_KEYMANAGERS, '-', "List of key managers" }, {"key-exchange-algorithms", OPT_KEYEXCHANGE_ALGORITHMS, '-', "List of key exchange algorithms" }, {"kem-algorithms", OPT_KEM_ALGORITHMS, '-', "List of key encapsulation mechanism algorithms" }, {"signature-algorithms", OPT_SIGNATURE_ALGORITHMS, '-', "List of signature algorithms" }, {"asymcipher-algorithms", OPT_ASYM_CIPHER_ALGORITHMS, '-', "List of asymmetric cipher algorithms" }, {"public-key-algorithms", OPT_PK_ALGORITHMS, '-', "List of public key algorithms"}, {"public-key-methods", OPT_PK_METHOD, '-', "List of public key methods"}, {"store-loaders", OPT_STORE_LOADERS, '-', "List of store loaders"}, {"providers", OPT_PROVIDER_INFO, '-', "List of provider information"}, #ifndef OPENSSL_NO_DEPRECATED_3_0 {"engines", OPT_ENGINES, '-', "List of loaded engines"}, #endif {"disabled", OPT_DISABLED, '-', "List of disabled features"}, {"options", OPT_OPTIONS, 's', "List options for specified command"}, {"objects", OPT_OBJECTS, '-', "List built in objects (OID<->name mappings)"}, OPT_PROV_OPTIONS, {NULL} }; int list_main(int argc, char **argv) { char *prog; HELPLIST_CHOICE o; int one = 0, done = 0; int print_newline = 0; struct { unsigned int commands:1; unsigned int all_algorithms:1; unsigned int random_instances:1; unsigned int random_generators:1; unsigned int digest_commands:1; unsigned int digest_algorithms:1; unsigned int kdf_algorithms:1; unsigned int mac_algorithms:1; unsigned int cipher_commands:1; unsigned int cipher_algorithms:1; unsigned int encoder_algorithms:1; unsigned int decoder_algorithms:1; unsigned int keymanager_algorithms:1; unsigned int signature_algorithms:1; unsigned int keyexchange_algorithms:1; unsigned int kem_algorithms:1; unsigned int asym_cipher_algorithms:1; unsigned int pk_algorithms:1; unsigned int pk_method:1; unsigned int store_loaders:1; unsigned int provider_info:1; #ifndef OPENSSL_NO_DEPRECATED_3_0 unsigned int engines:1; #endif unsigned int disabled:1; unsigned int objects:1; unsigned int options:1; } todo = { 0, }; verbose = 0; /* Clear a possible previous call */ prog = opt_init(argc, argv, list_options); while ((o = opt_next()) != OPT_EOF) { switch (o) { case OPT_EOF: /* Never hit, but suppresses warning */ case OPT_ERR: opthelp: BIO_printf(bio_err, "%s: Use -help for summary.\n", prog); return 1; case OPT_HELP: opt_help(list_options); return 0; case OPT_ONE: one = 1; break; case OPT_ALL_ARGORITHMS: todo.all_algorithms = 1; break; case OPT_COMMANDS: todo.commands = 1; break; case OPT_DIGEST_COMMANDS: todo.digest_commands = 1; break; case OPT_DIGEST_ALGORITHMS: todo.digest_algorithms = 1; break; case OPT_KDF_ALGORITHMS: todo.kdf_algorithms = 1; break; case OPT_RANDOM_INSTANCES: todo.random_instances = 1; break; case OPT_RANDOM_GENERATORS: todo.random_generators = 1; break; case OPT_MAC_ALGORITHMS: todo.mac_algorithms = 1; break; case OPT_CIPHER_COMMANDS: todo.cipher_commands = 1; break; case OPT_CIPHER_ALGORITHMS: todo.cipher_algorithms = 1; break; case OPT_ENCODERS: todo.encoder_algorithms = 1; break; case OPT_DECODERS: todo.decoder_algorithms = 1; break; case OPT_KEYMANAGERS: todo.keymanager_algorithms = 1; break; case OPT_SIGNATURE_ALGORITHMS: todo.signature_algorithms = 1; break; case OPT_KEYEXCHANGE_ALGORITHMS: todo.keyexchange_algorithms = 1; break; case OPT_KEM_ALGORITHMS: todo.kem_algorithms = 1; break; case OPT_ASYM_CIPHER_ALGORITHMS: todo.asym_cipher_algorithms = 1; break; case OPT_PK_ALGORITHMS: todo.pk_algorithms = 1; break; case OPT_PK_METHOD: todo.pk_method = 1; break; case OPT_STORE_LOADERS: todo.store_loaders = 1; break; case OPT_PROVIDER_INFO: todo.provider_info = 1; break; #ifndef OPENSSL_NO_DEPRECATED_3_0 case OPT_ENGINES: todo.engines = 1; break; #endif case OPT_DISABLED: todo.disabled = 1; break; case OPT_OBJECTS: todo.objects = 1; break; case OPT_OPTIONS: list_options_for_command(opt_arg()); break; case OPT_VERBOSE: verbose = 1; break; case OPT_SELECT_NAME: select_name = opt_arg(); break; case OPT_PROV_CASES: if (!opt_provider(o)) return 1; break; } done = 1; } /* No extra arguments. */ if (!opt_check_rest_arg(NULL)) goto opthelp; #define MAYBE_ADD_NL(cmd) \ do { \ if (print_newline++) { \ BIO_printf(bio_out, "\n"); \ } \ cmd; \ } while(0) if (todo.commands) MAYBE_ADD_NL(list_type(FT_general, one)); if (todo.all_algorithms) { MAYBE_ADD_NL({}); BIO_printf(bio_out, "Digests:\n"); list_digests(" "); BIO_printf(bio_out, "\nSymmetric Ciphers:\n"); list_ciphers(" "); BIO_printf(bio_out, "\n"); list_kdfs(); BIO_printf(bio_out, "\n"); list_macs(); BIO_printf(bio_out, "\nProvided Asymmetric Encryption:\n"); list_asymciphers(); BIO_printf(bio_out, "\nProvided Key Exchange:\n"); list_keyexchanges(); BIO_printf(bio_out, "\nProvided Signatures:\n"); list_signatures(); BIO_printf(bio_out, "\nProvided Key encapsulation:\n"); list_kems(); BIO_printf(bio_out, "\nProvided Key managers:\n"); list_keymanagers(); BIO_printf(bio_out, "\n"); list_encoders(); BIO_printf(bio_out, "\n"); list_decoders(); BIO_printf(bio_out, "\n"); list_store_loaders(); } if (todo.random_instances) MAYBE_ADD_NL(list_random_instances()); if (todo.random_generators) MAYBE_ADD_NL(list_random_generators()); if (todo.digest_commands) MAYBE_ADD_NL(list_type(FT_md, one)); if (todo.digest_algorithms) MAYBE_ADD_NL(list_digests("")); if (todo.kdf_algorithms) MAYBE_ADD_NL(list_kdfs()); if (todo.mac_algorithms) MAYBE_ADD_NL(list_macs()); if (todo.cipher_commands) MAYBE_ADD_NL(list_type(FT_cipher, one)); if (todo.cipher_algorithms) MAYBE_ADD_NL(list_ciphers("")); if (todo.encoder_algorithms) MAYBE_ADD_NL(list_encoders()); if (todo.decoder_algorithms) MAYBE_ADD_NL(list_decoders()); if (todo.keymanager_algorithms) MAYBE_ADD_NL(list_keymanagers()); if (todo.signature_algorithms) MAYBE_ADD_NL(list_signatures()); if (todo.asym_cipher_algorithms) MAYBE_ADD_NL(list_asymciphers()); if (todo.keyexchange_algorithms) MAYBE_ADD_NL(list_keyexchanges()); if (todo.kem_algorithms) MAYBE_ADD_NL(list_kems()); if (todo.pk_algorithms) MAYBE_ADD_NL(list_pkey()); if (todo.pk_method) MAYBE_ADD_NL(list_pkey_meth()); if (todo.store_loaders) MAYBE_ADD_NL(list_store_loaders()); if (todo.provider_info) MAYBE_ADD_NL(list_provider_info()); #ifndef OPENSSL_NO_DEPRECATED_3_0 if (todo.engines) MAYBE_ADD_NL(list_engines()); #endif if (todo.disabled) MAYBE_ADD_NL(list_disabled()); if (todo.objects) MAYBE_ADD_NL(list_objects()); #undef MAYBE_ADD_NL if (!done) goto opthelp; return 0; }
./openssl/apps/rehash.c
/* * Copyright 2015-2023 The OpenSSL Project Authors. All Rights Reserved. * Copyright (c) 2013-2014 Timo Teräs <timo.teras@gmail.com> * * 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 "apps.h" #include "progs.h" #if defined(OPENSSL_SYS_UNIX) || defined(__APPLE__) || \ (defined(__VMS) && defined(__DECC) && __CRTL_VER >= 80300000) # include <unistd.h> # include <stdio.h> # include <limits.h> # include <errno.h> # include <string.h> # include <ctype.h> # include <sys/stat.h> /* * Make sure that the processing of symbol names is treated the same as when * libcrypto is built. This is done automatically for public headers (see * include/openssl/__DECC_INCLUDE_PROLOGUE.H and __DECC_INCLUDE_EPILOGUE.H), * but not for internal headers. */ # ifdef __VMS # pragma names save # pragma names as_is,shortened # endif # include "internal/o_dir.h" # ifdef __VMS # pragma names restore # endif # include <openssl/evp.h> # include <openssl/pem.h> # include <openssl/x509.h> # ifndef PATH_MAX # define PATH_MAX 4096 # endif # define MAX_COLLISIONS 256 # if defined(OPENSSL_SYS_VXWORKS) /* * VxWorks has no symbolic links */ # define lstat(path, buf) stat(path, buf) int symlink(const char *target, const char *linkpath) { errno = ENOSYS; return -1; } ssize_t readlink(const char *pathname, char *buf, size_t bufsiz) { errno = ENOSYS; return -1; } # endif typedef struct hentry_st { struct hentry_st *next; char *filename; unsigned short old_id; unsigned char need_symlink; unsigned char digest[EVP_MAX_MD_SIZE]; } HENTRY; typedef struct bucket_st { struct bucket_st *next; HENTRY *first_entry, *last_entry; unsigned int hash; unsigned short type; unsigned short num_needed; } BUCKET; enum Type { /* Keep in sync with |suffixes|, below. */ TYPE_CERT=0, TYPE_CRL=1 }; enum Hash { HASH_OLD, HASH_NEW, HASH_BOTH }; static int evpmdsize; static const EVP_MD *evpmd; static int remove_links = 1; static int verbose = 0; static BUCKET *hash_table[257]; static const char *suffixes[] = { "", "r" }; static const char *extensions[] = { "pem", "crt", "cer", "crl" }; static void bit_set(unsigned char *set, unsigned int bit) { set[bit >> 3] |= 1 << (bit & 0x7); } static int bit_isset(unsigned char *set, unsigned int bit) { return set[bit >> 3] & (1 << (bit & 0x7)); } /* * Process an entry; return number of errors. */ static int add_entry(enum Type type, unsigned int hash, const char *filename, const unsigned char *digest, int need_symlink, unsigned short old_id) { static BUCKET nilbucket; static HENTRY nilhentry; BUCKET *bp; HENTRY *ep, *found = NULL; unsigned int ndx = (type + hash) % OSSL_NELEM(hash_table); for (bp = hash_table[ndx]; bp; bp = bp->next) if (bp->type == type && bp->hash == hash) break; if (bp == NULL) { bp = app_malloc(sizeof(*bp), "hash bucket"); *bp = nilbucket; bp->next = hash_table[ndx]; bp->type = type; bp->hash = hash; hash_table[ndx] = bp; } for (ep = bp->first_entry; ep; ep = ep->next) { if (digest && memcmp(digest, ep->digest, evpmdsize) == 0) { BIO_printf(bio_err, "%s: warning: skipping duplicate %s in %s\n", opt_getprog(), type == TYPE_CERT ? "certificate" : "CRL", filename); return 0; } if (strcmp(filename, ep->filename) == 0) { found = ep; if (digest == NULL) break; } } ep = found; if (ep == NULL) { if (bp->num_needed >= MAX_COLLISIONS) { BIO_printf(bio_err, "%s: error: hash table overflow for %s\n", opt_getprog(), filename); return 1; } ep = app_malloc(sizeof(*ep), "collision bucket"); *ep = nilhentry; ep->old_id = ~0; ep->filename = OPENSSL_strdup(filename); if (ep->filename == NULL) { OPENSSL_free(ep); ep = NULL; BIO_printf(bio_err, "out of memory\n"); return 1; } if (bp->last_entry) bp->last_entry->next = ep; if (bp->first_entry == NULL) bp->first_entry = ep; bp->last_entry = ep; } if (old_id < ep->old_id) ep->old_id = old_id; if (need_symlink && !ep->need_symlink) { ep->need_symlink = 1; bp->num_needed++; memcpy(ep->digest, digest, evpmdsize); } return 0; } /* * Check if a symlink goes to the right spot; return 0 if okay. * This can be -1 if bad filename, or an error count. */ static int handle_symlink(const char *filename, const char *fullpath) { unsigned int hash = 0; int i, type, id; unsigned char ch; char linktarget[PATH_MAX], *endptr; ossl_ssize_t n; for (i = 0; i < 8; i++) { ch = filename[i]; if (!isxdigit(ch)) return -1; hash <<= 4; hash += OPENSSL_hexchar2int(ch); } if (filename[i++] != '.') return -1; for (type = OSSL_NELEM(suffixes) - 1; type > 0; type--) if (OPENSSL_strncasecmp(&filename[i], suffixes[type], strlen(suffixes[type])) == 0) break; i += strlen(suffixes[type]); id = strtoul(&filename[i], &endptr, 10); if (*endptr != '\0') return -1; n = readlink(fullpath, linktarget, sizeof(linktarget)); if (n < 0 || n >= (int)sizeof(linktarget)) return -1; linktarget[n] = 0; return add_entry(type, hash, linktarget, NULL, 0, id); } /* * process a file, return number of errors. */ static int do_file(const char *filename, const char *fullpath, enum Hash h) { STACK_OF (X509_INFO) *inf = NULL; X509_INFO *x; const X509_NAME *name = NULL; BIO *b; const char *ext; unsigned char digest[EVP_MAX_MD_SIZE]; int type, errs = 0; size_t i; /* Does it end with a recognized extension? */ if ((ext = strrchr(filename, '.')) == NULL) goto end; for (i = 0; i < OSSL_NELEM(extensions); i++) { if (OPENSSL_strcasecmp(extensions[i], ext + 1) == 0) break; } if (i >= OSSL_NELEM(extensions)) goto end; /* Does it have X.509 data in it? */ if ((b = BIO_new_file(fullpath, "r")) == NULL) { BIO_printf(bio_err, "%s: error: skipping %s, cannot open file\n", opt_getprog(), filename); errs++; goto end; } inf = PEM_X509_INFO_read_bio(b, NULL, NULL, NULL); BIO_free(b); if (inf == NULL) goto end; if (sk_X509_INFO_num(inf) != 1) { BIO_printf(bio_err, "%s: warning: skipping %s," "it does not contain exactly one certificate or CRL\n", opt_getprog(), filename); /* This is not an error. */ goto end; } x = sk_X509_INFO_value(inf, 0); if (x->x509 != NULL) { type = TYPE_CERT; name = X509_get_subject_name(x->x509); if (!X509_digest(x->x509, evpmd, digest, NULL)) { BIO_printf(bio_err, "out of memory\n"); ++errs; goto end; } } else if (x->crl != NULL) { type = TYPE_CRL; name = X509_CRL_get_issuer(x->crl); if (!X509_CRL_digest(x->crl, evpmd, digest, NULL)) { BIO_printf(bio_err, "out of memory\n"); ++errs; goto end; } } else { ++errs; goto end; } if (name != NULL) { if (h == HASH_NEW || h == HASH_BOTH) { int ok; unsigned long hash_value = X509_NAME_hash_ex(name, app_get0_libctx(), app_get0_propq(), &ok); if (ok) { errs += add_entry(type, hash_value, filename, digest, 1, ~0); } else { BIO_printf(bio_err, "%s: error calculating SHA1 hash value\n", opt_getprog()); errs++; } } if ((h == HASH_OLD) || (h == HASH_BOTH)) errs += add_entry(type, X509_NAME_hash_old(name), filename, digest, 1, ~0); } end: sk_X509_INFO_pop_free(inf, X509_INFO_free); return errs; } static void str_free(char *s) { OPENSSL_free(s); } static int ends_with_dirsep(const char *path) { if (*path != '\0') path += strlen(path) - 1; # if defined __VMS if (*path == ']' || *path == '>' || *path == ':') return 1; # elif defined _WIN32 if (*path == '\\') return 1; # endif return *path == '/'; } static int sk_strcmp(const char * const *a, const char * const *b) { return strcmp(*a, *b); } /* * Process a directory; return number of errors found. */ static int do_dir(const char *dirname, enum Hash h) { BUCKET *bp, *nextbp; HENTRY *ep, *nextep; OPENSSL_DIR_CTX *d = NULL; struct stat st; unsigned char idmask[MAX_COLLISIONS / 8]; int n, numfiles, nextid, dirlen, buflen, errs = 0; size_t i, fname_max_len = 20; /* maximum length of "%08x.r%d" */ const char *pathsep = ""; const char *filename; char *buf = NULL, *copy = NULL; STACK_OF(OPENSSL_STRING) *files = NULL; if (app_access(dirname, W_OK) < 0) { BIO_printf(bio_err, "Skipping %s, can't write\n", dirname); return 1; } dirlen = strlen(dirname); if (dirlen != 0 && !ends_with_dirsep(dirname)) { pathsep = "/"; dirlen++; } if (verbose) BIO_printf(bio_out, "Doing %s\n", dirname); if ((files = sk_OPENSSL_STRING_new(sk_strcmp)) == NULL) { BIO_printf(bio_err, "Skipping %s, out of memory\n", dirname); errs = 1; goto err; } while ((filename = OPENSSL_DIR_read(&d, dirname)) != NULL) { size_t fname_len = strlen(filename); if ((copy = OPENSSL_strdup(filename)) == NULL || sk_OPENSSL_STRING_push(files, copy) == 0) { OPENSSL_free(copy); OPENSSL_DIR_end(&d); BIO_puts(bio_err, "out of memory\n"); errs = 1; goto err; } if (fname_len > fname_max_len) fname_max_len = fname_len; } OPENSSL_DIR_end(&d); sk_OPENSSL_STRING_sort(files); buflen = dirlen + fname_max_len + 1; buf = app_malloc(buflen, "filename buffer"); numfiles = sk_OPENSSL_STRING_num(files); for (n = 0; n < numfiles; ++n) { filename = sk_OPENSSL_STRING_value(files, n); if (BIO_snprintf(buf, buflen, "%s%s%s", dirname, pathsep, filename) >= buflen) continue; if (lstat(buf, &st) < 0) continue; if (S_ISLNK(st.st_mode) && handle_symlink(filename, buf) == 0) continue; errs += do_file(filename, buf, h); } for (i = 0; i < OSSL_NELEM(hash_table); i++) { for (bp = hash_table[i]; bp; bp = nextbp) { nextbp = bp->next; nextid = 0; memset(idmask, 0, (bp->num_needed + 7) / 8); for (ep = bp->first_entry; ep; ep = ep->next) if (ep->old_id < bp->num_needed) bit_set(idmask, ep->old_id); for (ep = bp->first_entry; ep; ep = nextep) { nextep = ep->next; if (ep->old_id < bp->num_needed) { /* Link exists, and is used as-is */ BIO_snprintf(buf, buflen, "%08x.%s%d", bp->hash, suffixes[bp->type], ep->old_id); if (verbose) BIO_printf(bio_out, "link %s -> %s\n", ep->filename, buf); } else if (ep->need_symlink) { /* New link needed (it may replace something) */ while (bit_isset(idmask, nextid)) nextid++; BIO_snprintf(buf, buflen, "%s%s%08x.%s%d", dirname, pathsep, bp->hash, suffixes[bp->type], nextid); if (verbose) BIO_printf(bio_out, "link %s -> %s\n", ep->filename, &buf[dirlen]); if (unlink(buf) < 0 && errno != ENOENT) { BIO_printf(bio_err, "%s: Can't unlink %s, %s\n", opt_getprog(), buf, strerror(errno)); errs++; } if (symlink(ep->filename, buf) < 0) { BIO_printf(bio_err, "%s: Can't symlink %s, %s\n", opt_getprog(), ep->filename, strerror(errno)); errs++; } bit_set(idmask, nextid); } else if (remove_links) { /* Link to be deleted */ BIO_snprintf(buf, buflen, "%s%s%08x.%s%d", dirname, pathsep, bp->hash, suffixes[bp->type], ep->old_id); if (verbose) BIO_printf(bio_out, "unlink %s\n", &buf[dirlen]); if (unlink(buf) < 0 && errno != ENOENT) { BIO_printf(bio_err, "%s: Can't unlink %s, %s\n", opt_getprog(), buf, strerror(errno)); errs++; } } OPENSSL_free(ep->filename); OPENSSL_free(ep); } OPENSSL_free(bp); } hash_table[i] = NULL; } err: sk_OPENSSL_STRING_pop_free(files, str_free); OPENSSL_free(buf); return errs; } typedef enum OPTION_choice { OPT_COMMON, OPT_COMPAT, OPT_OLD, OPT_N, OPT_VERBOSE, OPT_PROV_ENUM } OPTION_CHOICE; const OPTIONS rehash_options[] = { {OPT_HELP_STR, 1, '-', "Usage: %s [options] [directory...]\n"}, OPT_SECTION("General"), {"help", OPT_HELP, '-', "Display this summary"}, {"h", OPT_HELP, '-', "Display this summary"}, {"compat", OPT_COMPAT, '-', "Create both new- and old-style hash links"}, {"old", OPT_OLD, '-', "Use old-style hash to generate links"}, {"n", OPT_N, '-', "Do not remove existing links"}, OPT_SECTION("Output"), {"v", OPT_VERBOSE, '-', "Verbose output"}, OPT_PROV_OPTIONS, OPT_PARAMETERS(), {"directory", 0, 0, "One or more directories to process (optional)"}, {NULL} }; int rehash_main(int argc, char **argv) { const char *env, *prog; char *e, *m; int errs = 0; OPTION_CHOICE o; enum Hash h = HASH_NEW; prog = opt_init(argc, argv, rehash_options); while ((o = opt_next()) != OPT_EOF) { switch (o) { case OPT_EOF: case OPT_ERR: BIO_printf(bio_err, "%s: Use -help for summary.\n", prog); goto end; case OPT_HELP: opt_help(rehash_options); goto end; case OPT_COMPAT: h = HASH_BOTH; break; case OPT_OLD: h = HASH_OLD; break; case OPT_N: remove_links = 0; break; case OPT_VERBOSE: verbose = 1; break; case OPT_PROV_CASES: if (!opt_provider(o)) goto end; break; } } /* Optional arguments are directories to scan. */ argc = opt_num_rest(); argv = opt_rest(); evpmd = EVP_sha1(); evpmdsize = EVP_MD_get_size(evpmd); if (*argv != NULL) { while (*argv != NULL) errs += do_dir(*argv++, h); } else if ((env = getenv(X509_get_default_cert_dir_env())) != NULL) { char lsc[2] = { LIST_SEPARATOR_CHAR, '\0' }; m = OPENSSL_strdup(env); for (e = strtok(m, lsc); e != NULL; e = strtok(NULL, lsc)) errs += do_dir(e, h); OPENSSL_free(m); } else { errs += do_dir(X509_get_default_cert_dir(), h); } end: return errs; } #else const OPTIONS rehash_options[] = { {NULL} }; int rehash_main(int argc, char **argv) { BIO_printf(bio_err, "Not available; use c_rehash script\n"); return 1; } #endif /* defined(OPENSSL_SYS_UNIX) || defined(__APPLE__) */
./openssl/apps/rsautl.c
/* * Copyright 2000-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/opensslconf.h> #include "apps.h" #include "progs.h" #include <string.h> #include <openssl/err.h> #include <openssl/pem.h> #include <openssl/rsa.h> #define RSA_SIGN 1 #define RSA_VERIFY 2 #define RSA_ENCRYPT 3 #define RSA_DECRYPT 4 #define KEY_PRIVKEY 1 #define KEY_PUBKEY 2 #define KEY_CERT 3 typedef enum OPTION_choice { OPT_COMMON, OPT_ENGINE, OPT_IN, OPT_OUT, OPT_ASN1PARSE, OPT_HEXDUMP, OPT_RSA_RAW, OPT_OAEP, OPT_PKCS, OPT_X931, OPT_SIGN, OPT_VERIFY, OPT_REV, OPT_ENCRYPT, OPT_DECRYPT, OPT_PUBIN, OPT_CERTIN, OPT_INKEY, OPT_PASSIN, OPT_KEYFORM, OPT_R_ENUM, OPT_PROV_ENUM } OPTION_CHOICE; const OPTIONS rsautl_options[] = { OPT_SECTION("General"), {"help", OPT_HELP, '-', "Display this summary"}, {"sign", OPT_SIGN, '-', "Sign with private key"}, {"verify", OPT_VERIFY, '-', "Verify with public key"}, {"encrypt", OPT_ENCRYPT, '-', "Encrypt with public key"}, {"decrypt", OPT_DECRYPT, '-', "Decrypt with private key"}, #ifndef OPENSSL_NO_ENGINE {"engine", OPT_ENGINE, 's', "Use engine, possibly a hardware device"}, #endif OPT_SECTION("Input"), {"in", OPT_IN, '<', "Input file"}, {"inkey", OPT_INKEY, 's', "Input key, by default an RSA private key"}, {"keyform", OPT_KEYFORM, 'E', "Private key format (ENGINE, other values ignored)"}, {"pubin", OPT_PUBIN, '-', "Input key is an RSA public pkey"}, {"certin", OPT_CERTIN, '-', "Input is a cert carrying an RSA public key"}, {"rev", OPT_REV, '-', "Reverse the order of the input buffer"}, {"passin", OPT_PASSIN, 's', "Input file pass phrase source"}, OPT_SECTION("Output"), {"out", OPT_OUT, '>', "Output file"}, {"raw", OPT_RSA_RAW, '-', "Use no padding"}, {"pkcs", OPT_PKCS, '-', "Use PKCS#1 v1.5 padding (default)"}, {"x931", OPT_X931, '-', "Use ANSI X9.31 padding"}, {"oaep", OPT_OAEP, '-', "Use PKCS#1 OAEP"}, {"asn1parse", OPT_ASN1PARSE, '-', "Run output through asn1parse; useful with -verify"}, {"hexdump", OPT_HEXDUMP, '-', "Hex dump output"}, OPT_R_OPTIONS, OPT_PROV_OPTIONS, {NULL} }; int rsautl_main(int argc, char **argv) { BIO *in = NULL, *out = NULL; ENGINE *e = NULL; EVP_PKEY *pkey = NULL; EVP_PKEY_CTX *ctx = NULL; X509 *x; char *infile = NULL, *outfile = NULL, *keyfile = NULL; char *passinarg = NULL, *passin = NULL, *prog; char rsa_mode = RSA_VERIFY, key_type = KEY_PRIVKEY; unsigned char *rsa_in = NULL, *rsa_out = NULL, pad = RSA_PKCS1_PADDING; size_t rsa_inlen, rsa_outlen = 0; int keyformat = FORMAT_UNDEF, keysize, ret = 1, rv; int hexdump = 0, asn1parse = 0, need_priv = 0, rev = 0; OPTION_CHOICE o; prog = opt_init(argc, argv, rsautl_options); while ((o = opt_next()) != OPT_EOF) { switch (o) { case OPT_EOF: case OPT_ERR: opthelp: BIO_printf(bio_err, "%s: Use -help for summary.\n", prog); goto end; case OPT_HELP: opt_help(rsautl_options); ret = 0; goto end; case OPT_KEYFORM: if (!opt_format(opt_arg(), OPT_FMT_ANY, &keyformat)) goto opthelp; break; case OPT_IN: infile = opt_arg(); break; case OPT_OUT: outfile = opt_arg(); break; case OPT_ENGINE: e = setup_engine(opt_arg(), 0); break; case OPT_ASN1PARSE: asn1parse = 1; break; case OPT_HEXDUMP: hexdump = 1; break; case OPT_RSA_RAW: pad = RSA_NO_PADDING; break; case OPT_OAEP: pad = RSA_PKCS1_OAEP_PADDING; break; case OPT_PKCS: pad = RSA_PKCS1_PADDING; break; case OPT_X931: pad = RSA_X931_PADDING; break; case OPT_SIGN: rsa_mode = RSA_SIGN; need_priv = 1; break; case OPT_VERIFY: rsa_mode = RSA_VERIFY; break; case OPT_REV: rev = 1; break; case OPT_ENCRYPT: rsa_mode = RSA_ENCRYPT; break; case OPT_DECRYPT: rsa_mode = RSA_DECRYPT; need_priv = 1; break; case OPT_PUBIN: key_type = KEY_PUBKEY; break; case OPT_CERTIN: key_type = KEY_CERT; break; case OPT_INKEY: keyfile = opt_arg(); break; case OPT_PASSIN: passinarg = opt_arg(); break; case OPT_R_CASES: if (!opt_rand(o)) goto end; break; case OPT_PROV_CASES: if (!opt_provider(o)) goto end; break; } } /* No extra arguments. */ if (!opt_check_rest_arg(NULL)) goto opthelp; if (!app_RAND_load()) goto end; if (need_priv && (key_type != KEY_PRIVKEY)) { BIO_printf(bio_err, "A private key is needed for this operation\n"); goto end; } if (!app_passwd(passinarg, NULL, &passin, NULL)) { BIO_printf(bio_err, "Error getting password\n"); goto end; } switch (key_type) { case KEY_PRIVKEY: pkey = load_key(keyfile, keyformat, 0, passin, e, "private key"); break; case KEY_PUBKEY: pkey = load_pubkey(keyfile, keyformat, 0, NULL, e, "public key"); break; case KEY_CERT: x = load_cert(keyfile, FORMAT_UNDEF, "Certificate"); if (x) { pkey = X509_get_pubkey(x); X509_free(x); } break; } if (pkey == NULL) return 1; in = bio_open_default(infile, 'r', FORMAT_BINARY); if (in == NULL) goto end; out = bio_open_default(outfile, 'w', FORMAT_BINARY); if (out == NULL) goto end; keysize = EVP_PKEY_get_size(pkey); rsa_in = app_malloc(keysize * 2, "hold rsa key"); rsa_out = app_malloc(keysize, "output rsa key"); rsa_outlen = keysize; /* Read the input data */ rv = BIO_read(in, rsa_in, keysize * 2); if (rv < 0) { BIO_printf(bio_err, "Error reading input Data\n"); goto end; } rsa_inlen = rv; if (rev) { size_t i; unsigned char ctmp; for (i = 0; i < rsa_inlen / 2; i++) { ctmp = rsa_in[i]; rsa_in[i] = rsa_in[rsa_inlen - 1 - i]; rsa_in[rsa_inlen - 1 - i] = ctmp; } } if ((ctx = EVP_PKEY_CTX_new_from_pkey(NULL, pkey, NULL)) == NULL) goto end; switch (rsa_mode) { case RSA_VERIFY: rv = EVP_PKEY_verify_recover_init(ctx) > 0 && EVP_PKEY_CTX_set_rsa_padding(ctx, pad) > 0 && EVP_PKEY_verify_recover(ctx, rsa_out, &rsa_outlen, rsa_in, rsa_inlen) > 0; break; case RSA_SIGN: rv = EVP_PKEY_sign_init(ctx) > 0 && EVP_PKEY_CTX_set_rsa_padding(ctx, pad) > 0 && EVP_PKEY_sign(ctx, rsa_out, &rsa_outlen, rsa_in, rsa_inlen) > 0; break; case RSA_ENCRYPT: rv = EVP_PKEY_encrypt_init(ctx) > 0 && EVP_PKEY_CTX_set_rsa_padding(ctx, pad) > 0 && EVP_PKEY_encrypt(ctx, rsa_out, &rsa_outlen, rsa_in, rsa_inlen) > 0; break; case RSA_DECRYPT: rv = EVP_PKEY_decrypt_init(ctx) > 0 && EVP_PKEY_CTX_set_rsa_padding(ctx, pad) > 0 && EVP_PKEY_decrypt(ctx, rsa_out, &rsa_outlen, rsa_in, rsa_inlen) > 0; break; } if (!rv) { BIO_printf(bio_err, "RSA operation error\n"); ERR_print_errors(bio_err); goto end; } ret = 0; if (asn1parse) { if (!ASN1_parse_dump(out, rsa_out, rsa_outlen, 1, -1)) { ERR_print_errors(bio_err); } } else if (hexdump) { BIO_dump(out, (char *)rsa_out, rsa_outlen); } else { BIO_write(out, rsa_out, rsa_outlen); } end: EVP_PKEY_CTX_free(ctx); EVP_PKEY_free(pkey); release_engine(e); BIO_free(in); BIO_free_all(out); OPENSSL_free(rsa_in); OPENSSL_free(rsa_out); OPENSSL_free(passin); return ret; }
./openssl/apps/crl2pkcs7.c
/* * Copyright 1995-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 <sys/types.h> #include "apps.h" #include "progs.h" #include <openssl/err.h> #include <openssl/evp.h> #include <openssl/x509.h> #include <openssl/pkcs7.h> #include <openssl/pem.h> #include <openssl/objects.h> static int add_certs_from_file(STACK_OF(X509) *stack, char *certfile); typedef enum OPTION_choice { OPT_COMMON, OPT_INFORM, OPT_OUTFORM, OPT_IN, OPT_OUT, OPT_NOCRL, OPT_CERTFILE, OPT_PROV_ENUM } OPTION_CHOICE; const OPTIONS crl2pkcs7_options[] = { OPT_SECTION("General"), {"help", OPT_HELP, '-', "Display this summary"}, OPT_SECTION("Input"), {"in", OPT_IN, '<', "Input file"}, {"inform", OPT_INFORM, 'F', "Input format - DER or PEM"}, {"nocrl", OPT_NOCRL, '-', "No crl to load, just certs from '-certfile'"}, {"certfile", OPT_CERTFILE, '<', "File of chain of certs to a trusted CA; can be repeated"}, OPT_SECTION("Output"), {"out", OPT_OUT, '>', "Output file"}, {"outform", OPT_OUTFORM, 'F', "Output format - DER or PEM"}, OPT_PROV_OPTIONS, {NULL} }; int crl2pkcs7_main(int argc, char **argv) { BIO *in = NULL, *out = NULL; PKCS7 *p7 = NULL; PKCS7_SIGNED *p7s = NULL; STACK_OF(OPENSSL_STRING) *certflst = NULL; STACK_OF(X509) *cert_stack = NULL; STACK_OF(X509_CRL) *crl_stack = NULL; X509_CRL *crl = NULL; char *infile = NULL, *outfile = NULL, *prog, *certfile; int i = 0, informat = FORMAT_PEM, outformat = FORMAT_PEM, ret = 1, nocrl = 0; OPTION_CHOICE o; prog = opt_init(argc, argv, crl2pkcs7_options); while ((o = opt_next()) != OPT_EOF) { switch (o) { case OPT_EOF: case OPT_ERR: opthelp: BIO_printf(bio_err, "%s: Use -help for summary.\n", prog); goto end; case OPT_HELP: opt_help(crl2pkcs7_options); ret = 0; goto end; case OPT_INFORM: if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &informat)) goto opthelp; break; case OPT_OUTFORM: if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &outformat)) goto opthelp; break; case OPT_IN: infile = opt_arg(); break; case OPT_OUT: outfile = opt_arg(); break; case OPT_NOCRL: nocrl = 1; break; case OPT_CERTFILE: if ((certflst == NULL) && (certflst = sk_OPENSSL_STRING_new_null()) == NULL) goto end; if (!sk_OPENSSL_STRING_push(certflst, opt_arg())) goto end; break; case OPT_PROV_CASES: if (!opt_provider(o)) goto end; break; } } /* No remaining args. */ if (!opt_check_rest_arg(NULL)) goto opthelp; if (!nocrl) { in = bio_open_default(infile, 'r', informat); if (in == NULL) goto end; if (informat == FORMAT_ASN1) crl = d2i_X509_CRL_bio(in, NULL); else if (informat == FORMAT_PEM) crl = PEM_read_bio_X509_CRL(in, NULL, NULL, NULL); if (crl == NULL) { BIO_printf(bio_err, "unable to load CRL\n"); ERR_print_errors(bio_err); goto end; } } if ((p7 = PKCS7_new()) == NULL) goto end; if ((p7s = PKCS7_SIGNED_new()) == NULL) goto end; p7->type = OBJ_nid2obj(NID_pkcs7_signed); p7->d.sign = p7s; p7s->contents->type = OBJ_nid2obj(NID_pkcs7_data); if (!ASN1_INTEGER_set(p7s->version, 1)) goto end; if (crl != NULL) { if ((crl_stack = sk_X509_CRL_new_null()) == NULL) goto end; p7s->crl = crl_stack; sk_X509_CRL_push(crl_stack, crl); crl = NULL; /* now part of p7 for OPENSSL_freeing */ } if (certflst != NULL) { if ((cert_stack = sk_X509_new_null()) == NULL) goto end; p7s->cert = cert_stack; for (i = 0; i < sk_OPENSSL_STRING_num(certflst); i++) { certfile = sk_OPENSSL_STRING_value(certflst, i); if (add_certs_from_file(cert_stack, certfile) < 0) { BIO_printf(bio_err, "error loading certificates\n"); ERR_print_errors(bio_err); goto end; } } } out = bio_open_default(outfile, 'w', outformat); if (out == NULL) goto end; if (outformat == FORMAT_ASN1) i = i2d_PKCS7_bio(out, p7); else if (outformat == FORMAT_PEM) i = PEM_write_bio_PKCS7(out, p7); if (!i) { BIO_printf(bio_err, "unable to write pkcs7 object\n"); ERR_print_errors(bio_err); goto end; } ret = 0; end: sk_OPENSSL_STRING_free(certflst); BIO_free(in); BIO_free_all(out); PKCS7_free(p7); X509_CRL_free(crl); return ret; } /*- *---------------------------------------------------------------------- * int add_certs_from_file * * Read a list of certificates to be checked from a file. * * Results: * number of certs added if successful, -1 if not. *---------------------------------------------------------------------- */ static int add_certs_from_file(STACK_OF(X509) *stack, char *certfile) { BIO *in = NULL; int count = 0; int ret = -1; STACK_OF(X509_INFO) *sk = NULL; X509_INFO *xi; in = BIO_new_file(certfile, "r"); if (in == NULL) { BIO_printf(bio_err, "error opening the file, %s\n", certfile); goto end; } /* This loads from a file, a stack of x509/crl/pkey sets */ sk = PEM_X509_INFO_read_bio(in, NULL, NULL, NULL); if (sk == NULL) { BIO_printf(bio_err, "error reading the file, %s\n", certfile); goto end; } /* scan over it and pull out the CRL's */ while (sk_X509_INFO_num(sk)) { xi = sk_X509_INFO_shift(sk); if (xi->x509 != NULL) { sk_X509_push(stack, xi->x509); xi->x509 = NULL; count++; } X509_INFO_free(xi); } ret = count; end: /* never need to OPENSSL_free x */ BIO_free(in); sk_X509_INFO_free(sk); return ret; }
./openssl/apps/s_server.c
/* * Copyright 1995-2023 The OpenSSL Project Authors. All Rights Reserved. * Copyright (c) 2002, Oracle and/or its affiliates. All rights reserved * Copyright 2005 Nokia. All rights reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <ctype.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #if defined(_WIN32) /* Included before async.h to avoid some warnings */ # include <windows.h> #endif #include <openssl/e_os2.h> #include <openssl/async.h> #include <openssl/ssl.h> #include <openssl/decoder.h> #ifndef OPENSSL_NO_SOCK /* * With IPv6, it looks like Digital has mixed up the proper order of * recursive header file inclusion, resulting in the compiler complaining * that u_int isn't defined, but only if _POSIX_C_SOURCE is defined, which is * needed to have fileno() declared correctly... So let's define u_int */ #if defined(OPENSSL_SYS_VMS_DECC) && !defined(__U_INT) # define __U_INT typedef unsigned int u_int; #endif #include <openssl/bn.h> #include "apps.h" #include "progs.h" #include <openssl/err.h> #include <openssl/pem.h> #include <openssl/x509.h> #include <openssl/rand.h> #include <openssl/ocsp.h> #ifndef OPENSSL_NO_DH # include <openssl/dh.h> #endif #include <openssl/rsa.h> #include "s_apps.h" #include "timeouts.h" #ifdef CHARSET_EBCDIC #include <openssl/ebcdic.h> #endif #include "internal/sockets.h" static int not_resumable_sess_cb(SSL *s, int is_forward_secure); static int sv_body(int s, int stype, int prot, unsigned char *context); static int www_body(int s, int stype, int prot, unsigned char *context); static int rev_body(int s, int stype, int prot, unsigned char *context); static void close_accept_socket(void); static int init_ssl_connection(SSL *s); static void print_stats(BIO *bp, SSL_CTX *ctx); static int generate_session_id(SSL *ssl, unsigned char *id, unsigned int *id_len); static void init_session_cache_ctx(SSL_CTX *sctx); static void free_sessions(void); static void print_connection_info(SSL *con); static const int bufsize = 16 * 1024; static int accept_socket = -1; #define TEST_CERT "server.pem" #define TEST_CERT2 "server2.pem" static int s_nbio = 0; static int s_nbio_test = 0; static int s_crlf = 0; static SSL_CTX *ctx = NULL; static SSL_CTX *ctx2 = NULL; static int www = 0; static BIO *bio_s_out = NULL; static BIO *bio_s_msg = NULL; static int s_debug = 0; static int s_tlsextdebug = 0; static int s_msg = 0; static int s_quiet = 0; static int s_ign_eof = 0; static int s_brief = 0; static char *keymatexportlabel = NULL; static int keymatexportlen = 20; static int async = 0; static int use_sendfile = 0; static int use_zc_sendfile = 0; static const char *session_id_prefix = NULL; static const unsigned char cert_type_rpk[] = { TLSEXT_cert_type_rpk, TLSEXT_cert_type_x509 }; static int enable_client_rpk = 0; #ifndef OPENSSL_NO_DTLS static int enable_timeouts = 0; static long socket_mtu; #endif /* * We define this but make it always be 0 in no-dtls builds to simplify the * code. */ static int dtlslisten = 0; static int stateless = 0; static int early_data = 0; static SSL_SESSION *psksess = NULL; static char *psk_identity = "Client_identity"; char *psk_key = NULL; /* by default PSK is not used */ static char http_server_binmode = 0; /* for now: 0/1 = default/binary */ #ifndef OPENSSL_NO_PSK static unsigned int psk_server_cb(SSL *ssl, const char *identity, unsigned char *psk, unsigned int max_psk_len) { long key_len = 0; unsigned char *key; if (s_debug) BIO_printf(bio_s_out, "psk_server_cb\n"); if (!SSL_is_dtls(ssl) && SSL_version(ssl) >= TLS1_3_VERSION) { /* * This callback is designed for use in (D)TLSv1.2 (or below). It is * possible to use a single callback for all protocol versions - but it * is preferred to use a dedicated callback for TLSv1.3. For TLSv1.3 we * have psk_find_session_cb. */ return 0; } if (identity == NULL) { BIO_printf(bio_err, "Error: client did not send PSK identity\n"); goto out_err; } if (s_debug) BIO_printf(bio_s_out, "identity_len=%d identity=%s\n", (int)strlen(identity), identity); /* here we could lookup the given identity e.g. from a database */ if (strcmp(identity, psk_identity) != 0) { BIO_printf(bio_s_out, "PSK warning: client identity not what we expected" " (got '%s' expected '%s')\n", identity, psk_identity); } else { if (s_debug) BIO_printf(bio_s_out, "PSK client identity found\n"); } /* convert the PSK key to binary */ key = OPENSSL_hexstr2buf(psk_key, &key_len); if (key == NULL) { BIO_printf(bio_err, "Could not convert PSK key '%s' to buffer\n", psk_key); return 0; } if (key_len > (int)max_psk_len) { BIO_printf(bio_err, "psk buffer of callback is too small (%d) for key (%ld)\n", max_psk_len, key_len); OPENSSL_free(key); return 0; } memcpy(psk, key, key_len); OPENSSL_free(key); if (s_debug) BIO_printf(bio_s_out, "fetched PSK len=%ld\n", key_len); return key_len; out_err: if (s_debug) BIO_printf(bio_err, "Error in PSK server callback\n"); (void)BIO_flush(bio_err); (void)BIO_flush(bio_s_out); return 0; } #endif static int psk_find_session_cb(SSL *ssl, const unsigned char *identity, size_t identity_len, SSL_SESSION **sess) { SSL_SESSION *tmpsess = NULL; unsigned char *key; long key_len; const SSL_CIPHER *cipher = NULL; if (strlen(psk_identity) != identity_len || memcmp(psk_identity, identity, identity_len) != 0) { *sess = NULL; return 1; } if (psksess != NULL) { SSL_SESSION_up_ref(psksess); *sess = psksess; return 1; } key = OPENSSL_hexstr2buf(psk_key, &key_len); if (key == NULL) { BIO_printf(bio_err, "Could not convert PSK key '%s' to buffer\n", psk_key); return 0; } /* We default to SHA256 */ cipher = SSL_CIPHER_find(ssl, tls13_aes128gcmsha256_id); if (cipher == NULL) { BIO_printf(bio_err, "Error finding suitable ciphersuite\n"); OPENSSL_free(key); return 0; } tmpsess = SSL_SESSION_new(); if (tmpsess == NULL || !SSL_SESSION_set1_master_key(tmpsess, key, key_len) || !SSL_SESSION_set_cipher(tmpsess, cipher) || !SSL_SESSION_set_protocol_version(tmpsess, SSL_version(ssl))) { OPENSSL_free(key); SSL_SESSION_free(tmpsess); return 0; } OPENSSL_free(key); *sess = tmpsess; return 1; } #ifndef OPENSSL_NO_SRP static srpsrvparm srp_callback_parm; #endif static int local_argc = 0; static char **local_argv; #ifdef CHARSET_EBCDIC static int ebcdic_new(BIO *bi); static int ebcdic_free(BIO *a); static int ebcdic_read(BIO *b, char *out, int outl); static int ebcdic_write(BIO *b, const char *in, int inl); static long ebcdic_ctrl(BIO *b, int cmd, long num, void *ptr); static int ebcdic_gets(BIO *bp, char *buf, int size); static int ebcdic_puts(BIO *bp, const char *str); # define BIO_TYPE_EBCDIC_FILTER (18|0x0200) static BIO_METHOD *methods_ebcdic = NULL; /* This struct is "unwarranted chumminess with the compiler." */ typedef struct { size_t alloced; char buff[1]; } EBCDIC_OUTBUFF; static const BIO_METHOD *BIO_f_ebcdic_filter(void) { if (methods_ebcdic == NULL) { methods_ebcdic = BIO_meth_new(BIO_TYPE_EBCDIC_FILTER, "EBCDIC/ASCII filter"); if (methods_ebcdic == NULL || !BIO_meth_set_write(methods_ebcdic, ebcdic_write) || !BIO_meth_set_read(methods_ebcdic, ebcdic_read) || !BIO_meth_set_puts(methods_ebcdic, ebcdic_puts) || !BIO_meth_set_gets(methods_ebcdic, ebcdic_gets) || !BIO_meth_set_ctrl(methods_ebcdic, ebcdic_ctrl) || !BIO_meth_set_create(methods_ebcdic, ebcdic_new) || !BIO_meth_set_destroy(methods_ebcdic, ebcdic_free)) return NULL; } return methods_ebcdic; } static int ebcdic_new(BIO *bi) { EBCDIC_OUTBUFF *wbuf; wbuf = app_malloc(sizeof(*wbuf) + 1024, "ebcdic wbuf"); wbuf->alloced = 1024; wbuf->buff[0] = '\0'; BIO_set_data(bi, wbuf); BIO_set_init(bi, 1); return 1; } static int ebcdic_free(BIO *a) { EBCDIC_OUTBUFF *wbuf; if (a == NULL) return 0; wbuf = BIO_get_data(a); OPENSSL_free(wbuf); BIO_set_data(a, NULL); BIO_set_init(a, 0); return 1; } static int ebcdic_read(BIO *b, char *out, int outl) { int ret = 0; BIO *next = BIO_next(b); if (out == NULL || outl == 0) return 0; if (next == NULL) return 0; ret = BIO_read(next, out, outl); if (ret > 0) ascii2ebcdic(out, out, ret); return ret; } static int ebcdic_write(BIO *b, const char *in, int inl) { EBCDIC_OUTBUFF *wbuf; BIO *next = BIO_next(b); int ret = 0; int num; if ((in == NULL) || (inl <= 0)) return 0; if (next == NULL) return 0; wbuf = (EBCDIC_OUTBUFF *) BIO_get_data(b); if (inl > (num = wbuf->alloced)) { num = num + num; /* double the size */ if (num < inl) num = inl; OPENSSL_free(wbuf); wbuf = app_malloc(sizeof(*wbuf) + num, "grow ebcdic wbuf"); wbuf->alloced = num; wbuf->buff[0] = '\0'; BIO_set_data(b, wbuf); } ebcdic2ascii(wbuf->buff, in, inl); ret = BIO_write(next, wbuf->buff, inl); return ret; } static long ebcdic_ctrl(BIO *b, int cmd, long num, void *ptr) { long ret; BIO *next = BIO_next(b); 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 ebcdic_gets(BIO *bp, char *buf, int size) { int i, ret = 0; BIO *next = BIO_next(bp); if (next == NULL) return 0; /* return(BIO_gets(bp->next_bio,buf,size));*/ for (i = 0; i < size - 1; ++i) { ret = ebcdic_read(bp, &buf[i], 1); if (ret <= 0) break; else if (buf[i] == '\n') { ++i; break; } } if (i < size) buf[i] = '\0'; return (ret < 0 && i == 0) ? ret : i; } static int ebcdic_puts(BIO *bp, const char *str) { if (BIO_next(bp) == NULL) return 0; return ebcdic_write(bp, str, strlen(str)); } #endif /* This is a context that we pass to callbacks */ typedef struct tlsextctx_st { char *servername; BIO *biodebug; int extension_error; } tlsextctx; static int ssl_servername_cb(SSL *s, int *ad, void *arg) { tlsextctx *p = (tlsextctx *) arg; const char *servername = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name); if (servername != NULL && p->biodebug != NULL) { const char *cp = servername; unsigned char uc; BIO_printf(p->biodebug, "Hostname in TLS extension: \""); while ((uc = *cp++) != 0) BIO_printf(p->biodebug, (((uc) & ~127) == 0) && isprint(uc) ? "%c" : "\\x%02x", uc); BIO_printf(p->biodebug, "\"\n"); } if (p->servername == NULL) return SSL_TLSEXT_ERR_NOACK; if (servername != NULL) { if (OPENSSL_strcasecmp(servername, p->servername)) return p->extension_error; if (ctx2 != NULL) { BIO_printf(p->biodebug, "Switching server context.\n"); SSL_set_SSL_CTX(s, ctx2); } } return SSL_TLSEXT_ERR_OK; } /* Structure passed to cert status callback */ typedef struct tlsextstatusctx_st { int timeout; /* File to load OCSP Response from (or NULL if no file) */ char *respin; /* Default responder to use */ char *host, *path, *port; char *proxy, *no_proxy; int use_ssl; int verbose; } tlsextstatusctx; static tlsextstatusctx tlscstatp = { -1 }; #ifndef OPENSSL_NO_OCSP /* * Helper function to get an OCSP_RESPONSE from a responder. This is a * simplified version. It examines certificates each time and makes one OCSP * responder query for each request. A full version would store details such as * the OCSP certificate IDs and minimise the number of OCSP responses by caching * them until they were considered "expired". */ static int get_ocsp_resp_from_responder(SSL *s, tlsextstatusctx *srctx, OCSP_RESPONSE **resp) { char *host = NULL, *port = NULL, *path = NULL; char *proxy = NULL, *no_proxy = NULL; int use_ssl; STACK_OF(OPENSSL_STRING) *aia = NULL; X509 *x = NULL; X509_STORE_CTX *inctx = NULL; X509_OBJECT *obj; OCSP_REQUEST *req = NULL; OCSP_CERTID *id = NULL; STACK_OF(X509_EXTENSION) *exts; int ret = SSL_TLSEXT_ERR_NOACK; int i; /* Build up OCSP query from server certificate */ x = SSL_get_certificate(s); aia = X509_get1_ocsp(x); if (aia != NULL) { if (!OSSL_HTTP_parse_url(sk_OPENSSL_STRING_value(aia, 0), &use_ssl, NULL, &host, &port, NULL, &path, NULL, NULL)) { BIO_puts(bio_err, "cert_status: can't parse AIA URL\n"); goto err; } if (srctx->verbose) BIO_printf(bio_err, "cert_status: AIA URL: %s\n", sk_OPENSSL_STRING_value(aia, 0)); } else { if (srctx->host == NULL) { BIO_puts(bio_err, "cert_status: no AIA and no default responder URL\n"); goto done; } host = srctx->host; path = srctx->path; port = srctx->port; use_ssl = srctx->use_ssl; } proxy = srctx->proxy; no_proxy = srctx->no_proxy; inctx = X509_STORE_CTX_new(); if (inctx == NULL) goto err; if (!X509_STORE_CTX_init(inctx, SSL_CTX_get_cert_store(SSL_get_SSL_CTX(s)), NULL, NULL)) goto err; obj = X509_STORE_CTX_get_obj_by_subject(inctx, X509_LU_X509, X509_get_issuer_name(x)); if (obj == NULL) { BIO_puts(bio_err, "cert_status: Can't retrieve issuer certificate.\n"); goto done; } id = OCSP_cert_to_id(NULL, x, X509_OBJECT_get0_X509(obj)); X509_OBJECT_free(obj); if (id == NULL) goto err; req = OCSP_REQUEST_new(); if (req == NULL) goto err; if (!OCSP_request_add0_id(req, id)) goto err; id = NULL; /* Add any extensions to the request */ SSL_get_tlsext_status_exts(s, &exts); for (i = 0; i < sk_X509_EXTENSION_num(exts); i++) { X509_EXTENSION *ext = sk_X509_EXTENSION_value(exts, i); if (!OCSP_REQUEST_add_ext(req, ext, -1)) goto err; } *resp = process_responder(req, host, port, path, proxy, no_proxy, use_ssl, NULL /* headers */, srctx->timeout); if (*resp == NULL) { BIO_puts(bio_err, "cert_status: error querying responder\n"); goto done; } ret = SSL_TLSEXT_ERR_OK; goto done; err: ret = SSL_TLSEXT_ERR_ALERT_FATAL; done: /* * If we parsed aia we need to free; otherwise they were copied and we * don't */ if (aia != NULL) { OPENSSL_free(host); OPENSSL_free(path); OPENSSL_free(port); X509_email_free(aia); } OCSP_CERTID_free(id); OCSP_REQUEST_free(req); X509_STORE_CTX_free(inctx); return ret; } /* * Certificate Status callback. This is called when a client includes a * certificate status request extension. The response is either obtained from a * file, or from an OCSP responder. */ static int cert_status_cb(SSL *s, void *arg) { tlsextstatusctx *srctx = arg; OCSP_RESPONSE *resp = NULL; unsigned char *rspder = NULL; int rspderlen; int ret = SSL_TLSEXT_ERR_ALERT_FATAL; if (srctx->verbose) BIO_puts(bio_err, "cert_status: callback called\n"); if (srctx->respin != NULL) { BIO *derbio = bio_open_default(srctx->respin, 'r', FORMAT_ASN1); if (derbio == NULL) { BIO_puts(bio_err, "cert_status: Cannot open OCSP response file\n"); goto err; } resp = d2i_OCSP_RESPONSE_bio(derbio, NULL); BIO_free(derbio); if (resp == NULL) { BIO_puts(bio_err, "cert_status: Error reading OCSP response\n"); goto err; } } else { ret = get_ocsp_resp_from_responder(s, srctx, &resp); if (ret != SSL_TLSEXT_ERR_OK) goto err; } rspderlen = i2d_OCSP_RESPONSE(resp, &rspder); if (rspderlen <= 0) goto err; SSL_set_tlsext_status_ocsp_resp(s, rspder, rspderlen); if (srctx->verbose) { BIO_puts(bio_err, "cert_status: ocsp response sent:\n"); OCSP_RESPONSE_print(bio_err, resp, 2); } ret = SSL_TLSEXT_ERR_OK; err: if (ret != SSL_TLSEXT_ERR_OK) ERR_print_errors(bio_err); OCSP_RESPONSE_free(resp); return ret; } #endif #ifndef OPENSSL_NO_NEXTPROTONEG /* This is the context that we pass to next_proto_cb */ typedef struct tlsextnextprotoctx_st { unsigned char *data; size_t len; } tlsextnextprotoctx; static int next_proto_cb(SSL *s, const unsigned char **data, unsigned int *len, void *arg) { tlsextnextprotoctx *next_proto = arg; *data = next_proto->data; *len = next_proto->len; return SSL_TLSEXT_ERR_OK; } #endif /* ndef OPENSSL_NO_NEXTPROTONEG */ /* This the context that we pass to alpn_cb */ typedef struct tlsextalpnctx_st { unsigned char *data; size_t len; } tlsextalpnctx; static int alpn_cb(SSL *s, const unsigned char **out, unsigned char *outlen, const unsigned char *in, unsigned int inlen, void *arg) { tlsextalpnctx *alpn_ctx = arg; if (!s_quiet) { /* We can assume that |in| is syntactically valid. */ unsigned int i; BIO_printf(bio_s_out, "ALPN protocols advertised by the client: "); for (i = 0; i < inlen;) { if (i) BIO_write(bio_s_out, ", ", 2); BIO_write(bio_s_out, &in[i + 1], in[i]); i += in[i] + 1; } BIO_write(bio_s_out, "\n", 1); } if (SSL_select_next_proto ((unsigned char **)out, outlen, alpn_ctx->data, alpn_ctx->len, in, inlen) != OPENSSL_NPN_NEGOTIATED) { return SSL_TLSEXT_ERR_ALERT_FATAL; } if (!s_quiet) { BIO_printf(bio_s_out, "ALPN protocols selected: "); BIO_write(bio_s_out, *out, *outlen); BIO_write(bio_s_out, "\n", 1); } return SSL_TLSEXT_ERR_OK; } static int not_resumable_sess_cb(SSL *s, int is_forward_secure) { /* disable resumption for sessions with forward secure ciphers */ return is_forward_secure; } typedef enum OPTION_choice { OPT_COMMON, OPT_ENGINE, OPT_4, OPT_6, OPT_ACCEPT, OPT_PORT, OPT_UNIX, OPT_UNLINK, OPT_NACCEPT, OPT_VERIFY, OPT_NAMEOPT, OPT_UPPER_V_VERIFY, OPT_CONTEXT, OPT_CERT, OPT_CRL, OPT_CRL_DOWNLOAD, OPT_SERVERINFO, OPT_CERTFORM, OPT_KEY, OPT_KEYFORM, OPT_PASS, OPT_CERT_CHAIN, OPT_DHPARAM, OPT_DCERTFORM, OPT_DCERT, OPT_DKEYFORM, OPT_DPASS, OPT_DKEY, OPT_DCERT_CHAIN, OPT_NOCERT, OPT_CAPATH, OPT_NOCAPATH, OPT_CHAINCAPATH, OPT_VERIFYCAPATH, OPT_NO_CACHE, OPT_EXT_CACHE, OPT_CRLFORM, OPT_VERIFY_RET_ERROR, OPT_VERIFY_QUIET, OPT_BUILD_CHAIN, OPT_CAFILE, OPT_NOCAFILE, OPT_CHAINCAFILE, OPT_VERIFYCAFILE, OPT_CASTORE, OPT_NOCASTORE, OPT_CHAINCASTORE, OPT_VERIFYCASTORE, OPT_NBIO, OPT_NBIO_TEST, OPT_IGN_EOF, OPT_NO_IGN_EOF, OPT_DEBUG, OPT_TLSEXTDEBUG, OPT_STATUS, OPT_STATUS_VERBOSE, OPT_STATUS_TIMEOUT, OPT_PROXY, OPT_NO_PROXY, OPT_STATUS_URL, OPT_STATUS_FILE, OPT_MSG, OPT_MSGFILE, OPT_TRACE, OPT_SECURITY_DEBUG, OPT_SECURITY_DEBUG_VERBOSE, OPT_STATE, OPT_CRLF, OPT_QUIET, OPT_BRIEF, OPT_NO_DHE, OPT_NO_RESUME_EPHEMERAL, OPT_PSK_IDENTITY, OPT_PSK_HINT, OPT_PSK, OPT_PSK_SESS, OPT_SRPVFILE, OPT_SRPUSERSEED, OPT_REV, OPT_WWW, OPT_UPPER_WWW, OPT_HTTP, OPT_ASYNC, OPT_SSL_CONFIG, OPT_MAX_SEND_FRAG, OPT_SPLIT_SEND_FRAG, OPT_MAX_PIPELINES, OPT_READ_BUF, OPT_SSL3, OPT_TLS1_3, OPT_TLS1_2, OPT_TLS1_1, OPT_TLS1, OPT_DTLS, OPT_DTLS1, OPT_DTLS1_2, OPT_SCTP, OPT_TIMEOUT, OPT_MTU, OPT_LISTEN, OPT_STATELESS, OPT_ID_PREFIX, OPT_SERVERNAME, OPT_SERVERNAME_FATAL, OPT_CERT2, OPT_KEY2, OPT_NEXTPROTONEG, OPT_ALPN, OPT_SENDFILE, OPT_SRTP_PROFILES, OPT_KEYMATEXPORT, OPT_KEYMATEXPORTLEN, OPT_KEYLOG_FILE, OPT_MAX_EARLY, OPT_RECV_MAX_EARLY, OPT_EARLY_DATA, OPT_S_NUM_TICKETS, OPT_ANTI_REPLAY, OPT_NO_ANTI_REPLAY, OPT_SCTP_LABEL_BUG, OPT_HTTP_SERVER_BINMODE, OPT_NOCANAMES, OPT_IGNORE_UNEXPECTED_EOF, OPT_KTLS, OPT_USE_ZC_SENDFILE, OPT_TFO, OPT_CERT_COMP, OPT_ENABLE_SERVER_RPK, OPT_ENABLE_CLIENT_RPK, OPT_R_ENUM, OPT_S_ENUM, OPT_V_ENUM, OPT_X_ENUM, OPT_PROV_ENUM } OPTION_CHOICE; const OPTIONS s_server_options[] = { OPT_SECTION("General"), {"help", OPT_HELP, '-', "Display this summary"}, {"ssl_config", OPT_SSL_CONFIG, 's', "Configure SSL_CTX using the given configuration value"}, #ifndef OPENSSL_NO_SSL_TRACE {"trace", OPT_TRACE, '-', "trace protocol messages"}, #endif #ifndef OPENSSL_NO_ENGINE {"engine", OPT_ENGINE, 's', "Use engine, possibly a hardware device"}, #endif OPT_SECTION("Network"), {"port", OPT_PORT, 'p', "TCP/IP port to listen on for connections (default is " PORT ")"}, {"accept", OPT_ACCEPT, 's', "TCP/IP optional host and port to listen on for connections (default is *:" PORT ")"}, #ifdef AF_UNIX {"unix", OPT_UNIX, 's', "Unix domain socket to accept on"}, {"unlink", OPT_UNLINK, '-', "For -unix, unlink existing socket first"}, #endif {"4", OPT_4, '-', "Use IPv4 only"}, {"6", OPT_6, '-', "Use IPv6 only"}, #if defined(TCP_FASTOPEN) && !defined(OPENSSL_NO_TFO) {"tfo", OPT_TFO, '-', "Listen for TCP Fast Open connections"}, #endif OPT_SECTION("Identity"), {"context", OPT_CONTEXT, 's', "Set session ID context"}, {"CAfile", OPT_CAFILE, '<', "PEM format file of CA's"}, {"CApath", OPT_CAPATH, '/', "PEM format directory of CA's"}, {"CAstore", OPT_CASTORE, ':', "URI to store of CA's"}, {"no-CAfile", OPT_NOCAFILE, '-', "Do not load the default certificates file"}, {"no-CApath", OPT_NOCAPATH, '-', "Do not load certificates from the default certificates directory"}, {"no-CAstore", OPT_NOCASTORE, '-', "Do not load certificates from the default certificates store URI"}, {"nocert", OPT_NOCERT, '-', "Don't use any certificates (Anon-DH)"}, {"verify", OPT_VERIFY, 'n', "Turn on peer certificate verification"}, {"Verify", OPT_UPPER_V_VERIFY, 'n', "Turn on peer certificate verification, must have a cert"}, {"nameopt", OPT_NAMEOPT, 's', "Certificate subject/issuer name printing options"}, {"cert", OPT_CERT, '<', "Server certificate file to use; default " TEST_CERT}, {"cert2", OPT_CERT2, '<', "Certificate file to use for servername; default " TEST_CERT2}, {"certform", OPT_CERTFORM, 'F', "Server certificate file format (PEM/DER/P12); has no effect"}, {"cert_chain", OPT_CERT_CHAIN, '<', "Server certificate chain file in PEM format"}, {"build_chain", OPT_BUILD_CHAIN, '-', "Build server certificate chain"}, {"serverinfo", OPT_SERVERINFO, 's', "PEM serverinfo file for certificate"}, {"key", OPT_KEY, 's', "Private key file to use; default is -cert file or else" TEST_CERT}, {"key2", OPT_KEY2, '<', "-Private Key file to use for servername if not in -cert2"}, {"keyform", OPT_KEYFORM, 'f', "Key format (ENGINE, other values ignored)"}, {"pass", OPT_PASS, 's', "Private key and cert file pass phrase source"}, {"dcert", OPT_DCERT, '<', "Second server certificate file to use (usually for DSA)"}, {"dcertform", OPT_DCERTFORM, 'F', "Second server certificate file format (PEM/DER/P12); has no effect"}, {"dcert_chain", OPT_DCERT_CHAIN, '<', "second server certificate chain file in PEM format"}, {"dkey", OPT_DKEY, '<', "Second private key file to use (usually for DSA)"}, {"dkeyform", OPT_DKEYFORM, 'f', "Second key file format (ENGINE, other values ignored)"}, {"dpass", OPT_DPASS, 's', "Second private key and cert file pass phrase source"}, {"dhparam", OPT_DHPARAM, '<', "DH parameters file to use"}, {"servername", OPT_SERVERNAME, 's', "Servername for HostName TLS extension"}, {"servername_fatal", OPT_SERVERNAME_FATAL, '-', "On servername mismatch send fatal alert (default warning alert)"}, {"nbio_test", OPT_NBIO_TEST, '-', "Test with the non-blocking test bio"}, {"crlf", OPT_CRLF, '-', "Convert LF from terminal into CRLF"}, {"quiet", OPT_QUIET, '-', "No server output"}, {"no_resume_ephemeral", OPT_NO_RESUME_EPHEMERAL, '-', "Disable caching and tickets if ephemeral (EC)DH is used"}, {"www", OPT_WWW, '-', "Respond to a 'GET /' with a status page"}, {"WWW", OPT_UPPER_WWW, '-', "Respond to a 'GET with the file ./path"}, {"ignore_unexpected_eof", OPT_IGNORE_UNEXPECTED_EOF, '-', "Do not treat lack of close_notify from a peer as an error"}, {"tlsextdebug", OPT_TLSEXTDEBUG, '-', "Hex dump of all TLS extensions received"}, {"HTTP", OPT_HTTP, '-', "Like -WWW but ./path includes HTTP headers"}, {"id_prefix", OPT_ID_PREFIX, 's', "Generate SSL/TLS session IDs prefixed by arg"}, {"keymatexport", OPT_KEYMATEXPORT, 's', "Export keying material using label"}, {"keymatexportlen", OPT_KEYMATEXPORTLEN, 'p', "Export len bytes of keying material; default 20"}, {"CRL", OPT_CRL, '<', "CRL file to use"}, {"CRLform", OPT_CRLFORM, 'F', "CRL file format (PEM or DER); default PEM"}, {"crl_download", OPT_CRL_DOWNLOAD, '-', "Download CRLs from distribution points in certificate CDP entries"}, {"chainCAfile", OPT_CHAINCAFILE, '<', "CA file for certificate chain (PEM format)"}, {"chainCApath", OPT_CHAINCAPATH, '/', "use dir as certificate store path to build CA certificate chain"}, {"chainCAstore", OPT_CHAINCASTORE, ':', "use URI as certificate store to build CA certificate chain"}, {"verifyCAfile", OPT_VERIFYCAFILE, '<', "CA file for certificate verification (PEM format)"}, {"verifyCApath", OPT_VERIFYCAPATH, '/', "use dir as certificate store path to verify CA certificate"}, {"verifyCAstore", OPT_VERIFYCASTORE, ':', "use URI as certificate store to verify CA certificate"}, {"no_cache", OPT_NO_CACHE, '-', "Disable session cache"}, {"ext_cache", OPT_EXT_CACHE, '-', "Disable internal cache, set up and use external cache"}, {"verify_return_error", OPT_VERIFY_RET_ERROR, '-', "Close connection on verification error"}, {"verify_quiet", OPT_VERIFY_QUIET, '-', "No verify output except verify errors"}, {"ign_eof", OPT_IGN_EOF, '-', "Ignore input EOF (default when -quiet)"}, {"no_ign_eof", OPT_NO_IGN_EOF, '-', "Do not ignore input EOF"}, #ifndef OPENSSL_NO_COMP_ALG {"cert_comp", OPT_CERT_COMP, '-', "Pre-compress server certificates"}, #endif #ifndef OPENSSL_NO_OCSP OPT_SECTION("OCSP"), {"status", OPT_STATUS, '-', "Request certificate status from server"}, {"status_verbose", OPT_STATUS_VERBOSE, '-', "Print more output in certificate status callback"}, {"status_timeout", OPT_STATUS_TIMEOUT, 'n', "Status request responder timeout"}, {"status_url", OPT_STATUS_URL, 's', "Status request fallback URL"}, {"proxy", OPT_PROXY, 's', "[http[s]://]host[:port][/path] of HTTP(S) proxy to use; path is ignored"}, {"no_proxy", OPT_NO_PROXY, 's', "List of addresses of servers not to use HTTP(S) proxy for"}, {OPT_MORE_STR, 0, 0, "Default from environment variable 'no_proxy', else 'NO_PROXY', else none"}, {"status_file", OPT_STATUS_FILE, '<', "File containing DER encoded OCSP Response"}, #endif OPT_SECTION("Debug"), {"security_debug", OPT_SECURITY_DEBUG, '-', "Print output from SSL/TLS security framework"}, {"security_debug_verbose", OPT_SECURITY_DEBUG_VERBOSE, '-', "Print more output from SSL/TLS security framework"}, {"brief", OPT_BRIEF, '-', "Restrict output to brief summary of connection parameters"}, {"rev", OPT_REV, '-', "act as an echo server that sends back received text reversed"}, {"debug", OPT_DEBUG, '-', "Print more output"}, {"msg", OPT_MSG, '-', "Show protocol messages"}, {"msgfile", OPT_MSGFILE, '>', "File to send output of -msg or -trace, instead of stdout"}, {"state", OPT_STATE, '-', "Print the SSL states"}, {"async", OPT_ASYNC, '-', "Operate in asynchronous mode"}, {"max_pipelines", OPT_MAX_PIPELINES, 'p', "Maximum number of encrypt/decrypt pipelines to be used"}, {"naccept", OPT_NACCEPT, 'p', "Terminate after #num connections"}, {"keylogfile", OPT_KEYLOG_FILE, '>', "Write TLS secrets to file"}, OPT_SECTION("Network"), {"nbio", OPT_NBIO, '-', "Use non-blocking IO"}, {"timeout", OPT_TIMEOUT, '-', "Enable timeouts"}, {"mtu", OPT_MTU, 'p', "Set link-layer MTU"}, {"read_buf", OPT_READ_BUF, 'p', "Default read buffer size to be used for connections"}, {"split_send_frag", OPT_SPLIT_SEND_FRAG, 'p', "Size used to split data for encrypt pipelines"}, {"max_send_frag", OPT_MAX_SEND_FRAG, 'p', "Maximum Size of send frames "}, OPT_SECTION("Server identity"), {"psk_identity", OPT_PSK_IDENTITY, 's', "PSK identity to expect"}, #ifndef OPENSSL_NO_PSK {"psk_hint", OPT_PSK_HINT, 's', "PSK identity hint to use"}, #endif {"psk", OPT_PSK, 's', "PSK in hex (without 0x)"}, {"psk_session", OPT_PSK_SESS, '<', "File to read PSK SSL session from"}, #ifndef OPENSSL_NO_SRP {"srpvfile", OPT_SRPVFILE, '<', "(deprecated) The verifier file for SRP"}, {"srpuserseed", OPT_SRPUSERSEED, 's', "(deprecated) A seed string for a default user salt"}, #endif OPT_SECTION("Protocol and version"), {"max_early_data", OPT_MAX_EARLY, 'n', "The maximum number of bytes of early data as advertised in tickets"}, {"recv_max_early_data", OPT_RECV_MAX_EARLY, 'n', "The maximum number of bytes of early data (hard limit)"}, {"early_data", OPT_EARLY_DATA, '-', "Attempt to read early data"}, {"num_tickets", OPT_S_NUM_TICKETS, 'n', "The number of TLSv1.3 session tickets that a server will automatically issue" }, {"anti_replay", OPT_ANTI_REPLAY, '-', "Switch on anti-replay protection (default)"}, {"no_anti_replay", OPT_NO_ANTI_REPLAY, '-', "Switch off anti-replay protection"}, {"http_server_binmode", OPT_HTTP_SERVER_BINMODE, '-', "opening files in binary mode when acting as http server (-WWW and -HTTP)"}, {"no_ca_names", OPT_NOCANAMES, '-', "Disable TLS Extension CA Names"}, {"stateless", OPT_STATELESS, '-', "Require TLSv1.3 cookies"}, #ifndef OPENSSL_NO_SSL3 {"ssl3", OPT_SSL3, '-', "Just talk SSLv3"}, #endif #ifndef OPENSSL_NO_TLS1 {"tls1", OPT_TLS1, '-', "Just talk TLSv1"}, #endif #ifndef OPENSSL_NO_TLS1_1 {"tls1_1", OPT_TLS1_1, '-', "Just talk TLSv1.1"}, #endif #ifndef OPENSSL_NO_TLS1_2 {"tls1_2", OPT_TLS1_2, '-', "just talk TLSv1.2"}, #endif #ifndef OPENSSL_NO_TLS1_3 {"tls1_3", OPT_TLS1_3, '-', "just talk TLSv1.3"}, #endif #ifndef OPENSSL_NO_DTLS {"dtls", OPT_DTLS, '-', "Use any DTLS version"}, {"listen", OPT_LISTEN, '-', "Listen for a DTLS ClientHello with a cookie and then connect"}, #endif #ifndef OPENSSL_NO_DTLS1 {"dtls1", OPT_DTLS1, '-', "Just talk DTLSv1"}, #endif #ifndef OPENSSL_NO_DTLS1_2 {"dtls1_2", OPT_DTLS1_2, '-', "Just talk DTLSv1.2"}, #endif #ifndef OPENSSL_NO_SCTP {"sctp", OPT_SCTP, '-', "Use SCTP"}, {"sctp_label_bug", OPT_SCTP_LABEL_BUG, '-', "Enable SCTP label length bug"}, #endif #ifndef OPENSSL_NO_SRTP {"use_srtp", OPT_SRTP_PROFILES, 's', "Offer SRTP key management with a colon-separated profile list"}, #endif {"no_dhe", OPT_NO_DHE, '-', "Disable ephemeral DH"}, #ifndef OPENSSL_NO_NEXTPROTONEG {"nextprotoneg", OPT_NEXTPROTONEG, 's', "Set the advertised protocols for the NPN extension (comma-separated list)"}, #endif {"alpn", OPT_ALPN, 's', "Set the advertised protocols for the ALPN extension (comma-separated list)"}, #ifndef OPENSSL_NO_KTLS {"ktls", OPT_KTLS, '-', "Enable Kernel TLS for sending and receiving"}, {"sendfile", OPT_SENDFILE, '-', "Use sendfile to response file with -WWW"}, {"zerocopy_sendfile", OPT_USE_ZC_SENDFILE, '-', "Use zerocopy mode of KTLS sendfile"}, #endif {"enable_server_rpk", OPT_ENABLE_SERVER_RPK, '-', "Enable raw public keys (RFC7250) from the server"}, {"enable_client_rpk", OPT_ENABLE_CLIENT_RPK, '-', "Enable raw public keys (RFC7250) from the client"}, OPT_R_OPTIONS, OPT_S_OPTIONS, OPT_V_OPTIONS, OPT_X_OPTIONS, OPT_PROV_OPTIONS, {NULL} }; #define IS_PROT_FLAG(o) \ (o == OPT_SSL3 || o == OPT_TLS1 || o == OPT_TLS1_1 || o == OPT_TLS1_2 \ || o == OPT_TLS1_3 || o == OPT_DTLS || o == OPT_DTLS1 || o == OPT_DTLS1_2) int s_server_main(int argc, char *argv[]) { ENGINE *engine = NULL; EVP_PKEY *s_key = NULL, *s_dkey = NULL; SSL_CONF_CTX *cctx = NULL; const SSL_METHOD *meth = TLS_server_method(); SSL_EXCERT *exc = NULL; STACK_OF(OPENSSL_STRING) *ssl_args = NULL; STACK_OF(X509) *s_chain = NULL, *s_dchain = NULL; STACK_OF(X509_CRL) *crls = NULL; X509 *s_cert = NULL, *s_dcert = NULL; X509_VERIFY_PARAM *vpm = NULL; const char *CApath = NULL, *CAfile = NULL, *CAstore = NULL; const char *chCApath = NULL, *chCAfile = NULL, *chCAstore = NULL; char *dpassarg = NULL, *dpass = NULL; char *passarg = NULL, *pass = NULL; char *vfyCApath = NULL, *vfyCAfile = NULL, *vfyCAstore = NULL; char *crl_file = NULL, *prog; #ifdef AF_UNIX int unlink_unix_path = 0; #endif do_server_cb server_cb; int vpmtouched = 0, build_chain = 0, no_cache = 0, ext_cache = 0; char *dhfile = NULL; int no_dhe = 0; int nocert = 0, ret = 1; int noCApath = 0, noCAfile = 0, noCAstore = 0; int s_cert_format = FORMAT_UNDEF, s_key_format = FORMAT_UNDEF; int s_dcert_format = FORMAT_UNDEF, s_dkey_format = FORMAT_UNDEF; int rev = 0, naccept = -1, sdebug = 0; int socket_family = AF_UNSPEC, socket_type = SOCK_STREAM, protocol = 0; int state = 0, crl_format = FORMAT_UNDEF, crl_download = 0; char *host = NULL; char *port = NULL; unsigned char *context = NULL; OPTION_CHOICE o; EVP_PKEY *s_key2 = NULL; X509 *s_cert2 = NULL; tlsextctx tlsextcbp = { NULL, NULL, SSL_TLSEXT_ERR_ALERT_WARNING }; const char *ssl_config = NULL; int read_buf_len = 0; #ifndef OPENSSL_NO_NEXTPROTONEG const char *next_proto_neg_in = NULL; tlsextnextprotoctx next_proto = { NULL, 0 }; #endif const char *alpn_in = NULL; tlsextalpnctx alpn_ctx = { NULL, 0 }; #ifndef OPENSSL_NO_PSK /* by default do not send a PSK identity hint */ char *psk_identity_hint = NULL; #endif char *p; #ifndef OPENSSL_NO_SRP char *srpuserseed = NULL; char *srp_verifier_file = NULL; #endif #ifndef OPENSSL_NO_SRTP char *srtp_profiles = NULL; #endif int min_version = 0, max_version = 0, prot_opt = 0, no_prot_opt = 0; int s_server_verify = SSL_VERIFY_NONE; int s_server_session_id_context = 1; /* anything will do */ const char *s_cert_file = TEST_CERT, *s_key_file = NULL, *s_chain_file = NULL; const char *s_cert_file2 = TEST_CERT2, *s_key_file2 = NULL; char *s_dcert_file = NULL, *s_dkey_file = NULL, *s_dchain_file = NULL; #ifndef OPENSSL_NO_OCSP int s_tlsextstatus = 0; #endif int no_resume_ephemeral = 0; unsigned int max_send_fragment = 0; unsigned int split_send_fragment = 0, max_pipelines = 0; const char *s_serverinfo_file = NULL; const char *keylog_file = NULL; int max_early_data = -1, recv_max_early_data = -1; char *psksessf = NULL; int no_ca_names = 0; #ifndef OPENSSL_NO_SCTP int sctp_label_bug = 0; #endif int ignore_unexpected_eof = 0; #ifndef OPENSSL_NO_KTLS int enable_ktls = 0; #endif int tfo = 0; int cert_comp = 0; int enable_server_rpk = 0; /* Init of few remaining global variables */ local_argc = argc; local_argv = argv; ctx = ctx2 = NULL; s_nbio = s_nbio_test = 0; www = 0; bio_s_out = NULL; s_debug = 0; s_msg = 0; s_quiet = 0; s_brief = 0; async = 0; use_sendfile = 0; use_zc_sendfile = 0; port = OPENSSL_strdup(PORT); cctx = SSL_CONF_CTX_new(); vpm = X509_VERIFY_PARAM_new(); if (port == NULL || cctx == NULL || vpm == NULL) goto end; SSL_CONF_CTX_set_flags(cctx, SSL_CONF_FLAG_SERVER | SSL_CONF_FLAG_CMDLINE); prog = opt_init(argc, argv, s_server_options); while ((o = opt_next()) != OPT_EOF) { if (IS_PROT_FLAG(o) && ++prot_opt > 1) { BIO_printf(bio_err, "Cannot supply multiple protocol flags\n"); goto end; } if (IS_NO_PROT_FLAG(o)) no_prot_opt++; if (prot_opt == 1 && no_prot_opt) { BIO_printf(bio_err, "Cannot supply both a protocol flag and '-no_<prot>'\n"); goto end; } switch (o) { case OPT_EOF: case OPT_ERR: opthelp: BIO_printf(bio_err, "%s: Use -help for summary.\n", prog); goto end; case OPT_HELP: opt_help(s_server_options); ret = 0; goto end; case OPT_4: #ifdef AF_UNIX if (socket_family == AF_UNIX) { OPENSSL_free(host); host = NULL; OPENSSL_free(port); port = NULL; } #endif socket_family = AF_INET; break; case OPT_6: if (1) { #ifdef AF_INET6 #ifdef AF_UNIX if (socket_family == AF_UNIX) { OPENSSL_free(host); host = NULL; OPENSSL_free(port); port = NULL; } #endif socket_family = AF_INET6; } else { #endif BIO_printf(bio_err, "%s: IPv6 domain sockets unsupported\n", prog); goto end; } break; case OPT_PORT: #ifdef AF_UNIX if (socket_family == AF_UNIX) { socket_family = AF_UNSPEC; } #endif OPENSSL_free(port); port = NULL; OPENSSL_free(host); host = NULL; if (BIO_parse_hostserv(opt_arg(), NULL, &port, BIO_PARSE_PRIO_SERV) < 1) { BIO_printf(bio_err, "%s: -port argument malformed or ambiguous\n", port); goto end; } break; case OPT_ACCEPT: #ifdef AF_UNIX if (socket_family == AF_UNIX) { socket_family = AF_UNSPEC; } #endif OPENSSL_free(port); port = NULL; OPENSSL_free(host); host = NULL; if (BIO_parse_hostserv(opt_arg(), &host, &port, BIO_PARSE_PRIO_SERV) < 1) { BIO_printf(bio_err, "%s: -accept argument malformed or ambiguous\n", port); goto end; } break; #ifdef AF_UNIX case OPT_UNIX: socket_family = AF_UNIX; OPENSSL_free(host); host = OPENSSL_strdup(opt_arg()); if (host == NULL) goto end; OPENSSL_free(port); port = NULL; break; case OPT_UNLINK: unlink_unix_path = 1; break; #endif case OPT_NACCEPT: naccept = atol(opt_arg()); break; case OPT_VERIFY: s_server_verify = SSL_VERIFY_PEER | SSL_VERIFY_CLIENT_ONCE; verify_args.depth = atoi(opt_arg()); if (!s_quiet) BIO_printf(bio_err, "verify depth is %d\n", verify_args.depth); break; case OPT_UPPER_V_VERIFY: s_server_verify = SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT | SSL_VERIFY_CLIENT_ONCE; verify_args.depth = atoi(opt_arg()); if (!s_quiet) BIO_printf(bio_err, "verify depth is %d, must return a certificate\n", verify_args.depth); break; case OPT_CONTEXT: context = (unsigned char *)opt_arg(); break; case OPT_CERT: s_cert_file = opt_arg(); break; case OPT_NAMEOPT: if (!set_nameopt(opt_arg())) goto end; break; case OPT_CRL: crl_file = opt_arg(); break; case OPT_CRL_DOWNLOAD: crl_download = 1; break; case OPT_SERVERINFO: s_serverinfo_file = opt_arg(); break; case OPT_CERTFORM: if (!opt_format(opt_arg(), OPT_FMT_ANY, &s_cert_format)) goto opthelp; break; case OPT_KEY: s_key_file = opt_arg(); break; case OPT_KEYFORM: if (!opt_format(opt_arg(), OPT_FMT_ANY, &s_key_format)) goto opthelp; break; case OPT_PASS: passarg = opt_arg(); break; case OPT_CERT_CHAIN: s_chain_file = opt_arg(); break; case OPT_DHPARAM: dhfile = opt_arg(); break; case OPT_DCERTFORM: if (!opt_format(opt_arg(), OPT_FMT_ANY, &s_dcert_format)) goto opthelp; break; case OPT_DCERT: s_dcert_file = opt_arg(); break; case OPT_DKEYFORM: if (!opt_format(opt_arg(), OPT_FMT_ANY, &s_dkey_format)) goto opthelp; break; case OPT_DPASS: dpassarg = opt_arg(); break; case OPT_DKEY: s_dkey_file = opt_arg(); break; case OPT_DCERT_CHAIN: s_dchain_file = opt_arg(); break; case OPT_NOCERT: nocert = 1; break; case OPT_CAPATH: CApath = opt_arg(); break; case OPT_NOCAPATH: noCApath = 1; break; case OPT_CHAINCAPATH: chCApath = opt_arg(); break; case OPT_VERIFYCAPATH: vfyCApath = opt_arg(); break; case OPT_CASTORE: CAstore = opt_arg(); break; case OPT_NOCASTORE: noCAstore = 1; break; case OPT_CHAINCASTORE: chCAstore = opt_arg(); break; case OPT_VERIFYCASTORE: vfyCAstore = opt_arg(); break; case OPT_NO_CACHE: no_cache = 1; break; case OPT_EXT_CACHE: ext_cache = 1; break; case OPT_CRLFORM: if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &crl_format)) goto opthelp; break; case OPT_S_CASES: case OPT_S_NUM_TICKETS: case OPT_ANTI_REPLAY: case OPT_NO_ANTI_REPLAY: if (ssl_args == NULL) ssl_args = sk_OPENSSL_STRING_new_null(); if (ssl_args == NULL || !sk_OPENSSL_STRING_push(ssl_args, opt_flag()) || !sk_OPENSSL_STRING_push(ssl_args, opt_arg())) { BIO_printf(bio_err, "%s: Memory allocation failure\n", prog); goto end; } break; case OPT_V_CASES: if (!opt_verify(o, vpm)) goto end; vpmtouched++; break; case OPT_X_CASES: if (!args_excert(o, &exc)) goto end; break; case OPT_VERIFY_RET_ERROR: verify_args.return_error = 1; break; case OPT_VERIFY_QUIET: verify_args.quiet = 1; break; case OPT_BUILD_CHAIN: build_chain = 1; break; case OPT_CAFILE: CAfile = opt_arg(); break; case OPT_NOCAFILE: noCAfile = 1; break; case OPT_CHAINCAFILE: chCAfile = opt_arg(); break; case OPT_VERIFYCAFILE: vfyCAfile = opt_arg(); break; case OPT_NBIO: s_nbio = 1; break; case OPT_NBIO_TEST: s_nbio = s_nbio_test = 1; break; case OPT_IGN_EOF: s_ign_eof = 1; break; case OPT_NO_IGN_EOF: s_ign_eof = 0; break; case OPT_DEBUG: s_debug = 1; break; case OPT_TLSEXTDEBUG: s_tlsextdebug = 1; break; case OPT_STATUS: #ifndef OPENSSL_NO_OCSP s_tlsextstatus = 1; #endif break; case OPT_STATUS_VERBOSE: #ifndef OPENSSL_NO_OCSP s_tlsextstatus = tlscstatp.verbose = 1; #endif break; case OPT_STATUS_TIMEOUT: #ifndef OPENSSL_NO_OCSP s_tlsextstatus = 1; tlscstatp.timeout = atoi(opt_arg()); #endif break; case OPT_PROXY: #ifndef OPENSSL_NO_OCSP tlscstatp.proxy = opt_arg(); #endif break; case OPT_NO_PROXY: #ifndef OPENSSL_NO_OCSP tlscstatp.no_proxy = opt_arg(); #endif break; case OPT_STATUS_URL: #ifndef OPENSSL_NO_OCSP s_tlsextstatus = 1; if (!OSSL_HTTP_parse_url(opt_arg(), &tlscstatp.use_ssl, NULL, &tlscstatp.host, &tlscstatp.port, NULL, &tlscstatp.path, NULL, NULL)) { BIO_printf(bio_err, "Error parsing -status_url argument\n"); goto end; } #endif break; case OPT_STATUS_FILE: #ifndef OPENSSL_NO_OCSP s_tlsextstatus = 1; tlscstatp.respin = opt_arg(); #endif break; case OPT_MSG: s_msg = 1; break; case OPT_MSGFILE: bio_s_msg = BIO_new_file(opt_arg(), "w"); if (bio_s_msg == NULL) { BIO_printf(bio_err, "Error writing file %s\n", opt_arg()); goto end; } break; case OPT_TRACE: #ifndef OPENSSL_NO_SSL_TRACE s_msg = 2; #endif break; case OPT_SECURITY_DEBUG: sdebug = 1; break; case OPT_SECURITY_DEBUG_VERBOSE: sdebug = 2; break; case OPT_STATE: state = 1; break; case OPT_CRLF: s_crlf = 1; break; case OPT_QUIET: s_quiet = 1; break; case OPT_BRIEF: s_quiet = s_brief = verify_args.quiet = 1; break; case OPT_NO_DHE: no_dhe = 1; break; case OPT_NO_RESUME_EPHEMERAL: no_resume_ephemeral = 1; break; case OPT_PSK_IDENTITY: psk_identity = opt_arg(); break; case OPT_PSK_HINT: #ifndef OPENSSL_NO_PSK psk_identity_hint = opt_arg(); #endif break; case OPT_PSK: for (p = psk_key = opt_arg(); *p; p++) { if (isxdigit(_UC(*p))) continue; BIO_printf(bio_err, "Not a hex number '%s'\n", psk_key); goto end; } break; case OPT_PSK_SESS: psksessf = opt_arg(); break; case OPT_SRPVFILE: #ifndef OPENSSL_NO_SRP srp_verifier_file = opt_arg(); if (min_version < TLS1_VERSION) min_version = TLS1_VERSION; #endif break; case OPT_SRPUSERSEED: #ifndef OPENSSL_NO_SRP srpuserseed = opt_arg(); if (min_version < TLS1_VERSION) min_version = TLS1_VERSION; #endif break; case OPT_REV: rev = 1; break; case OPT_WWW: www = 1; break; case OPT_UPPER_WWW: www = 2; break; case OPT_HTTP: www = 3; break; case OPT_SSL_CONFIG: ssl_config = opt_arg(); break; case OPT_SSL3: min_version = SSL3_VERSION; max_version = SSL3_VERSION; break; case OPT_TLS1_3: min_version = TLS1_3_VERSION; max_version = TLS1_3_VERSION; break; case OPT_TLS1_2: min_version = TLS1_2_VERSION; max_version = TLS1_2_VERSION; break; case OPT_TLS1_1: min_version = TLS1_1_VERSION; max_version = TLS1_1_VERSION; break; case OPT_TLS1: min_version = TLS1_VERSION; max_version = TLS1_VERSION; break; case OPT_DTLS: #ifndef OPENSSL_NO_DTLS meth = DTLS_server_method(); socket_type = SOCK_DGRAM; #endif break; case OPT_DTLS1: #ifndef OPENSSL_NO_DTLS meth = DTLS_server_method(); min_version = DTLS1_VERSION; max_version = DTLS1_VERSION; socket_type = SOCK_DGRAM; #endif break; case OPT_DTLS1_2: #ifndef OPENSSL_NO_DTLS meth = DTLS_server_method(); min_version = DTLS1_2_VERSION; max_version = DTLS1_2_VERSION; socket_type = SOCK_DGRAM; #endif break; case OPT_SCTP: #ifndef OPENSSL_NO_SCTP protocol = IPPROTO_SCTP; #endif break; case OPT_SCTP_LABEL_BUG: #ifndef OPENSSL_NO_SCTP sctp_label_bug = 1; #endif break; case OPT_TIMEOUT: #ifndef OPENSSL_NO_DTLS enable_timeouts = 1; #endif break; case OPT_MTU: #ifndef OPENSSL_NO_DTLS socket_mtu = atol(opt_arg()); #endif break; case OPT_LISTEN: #ifndef OPENSSL_NO_DTLS dtlslisten = 1; #endif break; case OPT_STATELESS: stateless = 1; break; case OPT_ID_PREFIX: session_id_prefix = opt_arg(); break; case OPT_ENGINE: #ifndef OPENSSL_NO_ENGINE engine = setup_engine(opt_arg(), s_debug); #endif break; case OPT_R_CASES: if (!opt_rand(o)) goto end; break; case OPT_PROV_CASES: if (!opt_provider(o)) goto end; break; case OPT_SERVERNAME: tlsextcbp.servername = opt_arg(); break; case OPT_SERVERNAME_FATAL: tlsextcbp.extension_error = SSL_TLSEXT_ERR_ALERT_FATAL; break; case OPT_CERT2: s_cert_file2 = opt_arg(); break; case OPT_KEY2: s_key_file2 = opt_arg(); break; case OPT_NEXTPROTONEG: # ifndef OPENSSL_NO_NEXTPROTONEG next_proto_neg_in = opt_arg(); #endif break; case OPT_ALPN: alpn_in = opt_arg(); break; case OPT_SRTP_PROFILES: #ifndef OPENSSL_NO_SRTP srtp_profiles = opt_arg(); #endif break; case OPT_KEYMATEXPORT: keymatexportlabel = opt_arg(); break; case OPT_KEYMATEXPORTLEN: keymatexportlen = atoi(opt_arg()); break; case OPT_ASYNC: async = 1; break; case OPT_MAX_SEND_FRAG: max_send_fragment = atoi(opt_arg()); break; case OPT_SPLIT_SEND_FRAG: split_send_fragment = atoi(opt_arg()); break; case OPT_MAX_PIPELINES: max_pipelines = atoi(opt_arg()); break; case OPT_READ_BUF: read_buf_len = atoi(opt_arg()); break; case OPT_KEYLOG_FILE: keylog_file = opt_arg(); break; case OPT_MAX_EARLY: max_early_data = atoi(opt_arg()); if (max_early_data < 0) { BIO_printf(bio_err, "Invalid value for max_early_data\n"); goto end; } break; case OPT_RECV_MAX_EARLY: recv_max_early_data = atoi(opt_arg()); if (recv_max_early_data < 0) { BIO_printf(bio_err, "Invalid value for recv_max_early_data\n"); goto end; } break; case OPT_EARLY_DATA: early_data = 1; if (max_early_data == -1) max_early_data = SSL3_RT_MAX_PLAIN_LENGTH; break; case OPT_HTTP_SERVER_BINMODE: http_server_binmode = 1; break; case OPT_NOCANAMES: no_ca_names = 1; break; case OPT_KTLS: #ifndef OPENSSL_NO_KTLS enable_ktls = 1; #endif break; case OPT_SENDFILE: #ifndef OPENSSL_NO_KTLS use_sendfile = 1; #endif break; case OPT_USE_ZC_SENDFILE: #ifndef OPENSSL_NO_KTLS use_zc_sendfile = 1; #endif break; case OPT_IGNORE_UNEXPECTED_EOF: ignore_unexpected_eof = 1; break; case OPT_TFO: tfo = 1; break; case OPT_CERT_COMP: cert_comp = 1; break; case OPT_ENABLE_SERVER_RPK: enable_server_rpk = 1; break; case OPT_ENABLE_CLIENT_RPK: enable_client_rpk = 1; break; } } /* No extra arguments. */ if (!opt_check_rest_arg(NULL)) goto opthelp; if (!app_RAND_load()) goto end; #ifndef OPENSSL_NO_NEXTPROTONEG if (min_version == TLS1_3_VERSION && next_proto_neg_in != NULL) { BIO_printf(bio_err, "Cannot supply -nextprotoneg with TLSv1.3\n"); goto opthelp; } #endif #ifndef OPENSSL_NO_DTLS if (www && socket_type == SOCK_DGRAM) { BIO_printf(bio_err, "Can't use -HTTP, -www or -WWW with DTLS\n"); goto end; } if (dtlslisten && socket_type != SOCK_DGRAM) { BIO_printf(bio_err, "Can only use -listen with DTLS\n"); goto end; } if (rev && socket_type == SOCK_DGRAM) { BIO_printf(bio_err, "Can't use -rev with DTLS\n"); goto end; } #endif if (tfo && socket_type != SOCK_STREAM) { BIO_printf(bio_err, "Can only use -tfo with TLS\n"); goto end; } if (stateless && socket_type != SOCK_STREAM) { BIO_printf(bio_err, "Can only use --stateless with TLS\n"); goto end; } #ifdef AF_UNIX if (socket_family == AF_UNIX && socket_type != SOCK_STREAM) { BIO_printf(bio_err, "Can't use unix sockets and datagrams together\n"); goto end; } #endif if (early_data && (www > 0 || rev)) { BIO_printf(bio_err, "Can't use -early_data in combination with -www, -WWW, -HTTP, or -rev\n"); goto end; } #ifndef OPENSSL_NO_SCTP if (protocol == IPPROTO_SCTP) { if (socket_type != SOCK_DGRAM) { BIO_printf(bio_err, "Can't use -sctp without DTLS\n"); goto end; } /* SCTP is unusual. It uses DTLS over a SOCK_STREAM protocol */ socket_type = SOCK_STREAM; } #endif #ifndef OPENSSL_NO_KTLS if (use_zc_sendfile && !use_sendfile) { BIO_printf(bio_out, "Warning: -zerocopy_sendfile depends on -sendfile, enabling -sendfile now.\n"); use_sendfile = 1; } if (use_sendfile && enable_ktls == 0) { BIO_printf(bio_out, "Warning: -sendfile depends on -ktls, enabling -ktls now.\n"); enable_ktls = 1; } if (use_sendfile && www <= 1) { BIO_printf(bio_err, "Can't use -sendfile without -WWW or -HTTP\n"); goto end; } #endif if (!app_passwd(passarg, dpassarg, &pass, &dpass)) { BIO_printf(bio_err, "Error getting password\n"); goto end; } if (s_key_file == NULL) s_key_file = s_cert_file; if (s_key_file2 == NULL) s_key_file2 = s_cert_file2; if (!load_excert(&exc)) goto end; if (nocert == 0) { s_key = load_key(s_key_file, s_key_format, 0, pass, engine, "server certificate private key"); if (s_key == NULL) goto end; s_cert = load_cert_pass(s_cert_file, s_cert_format, 1, pass, "server certificate"); if (s_cert == NULL) goto end; if (s_chain_file != NULL) { if (!load_certs(s_chain_file, 0, &s_chain, NULL, "server certificate chain")) goto end; } if (tlsextcbp.servername != NULL) { s_key2 = load_key(s_key_file2, s_key_format, 0, pass, engine, "second server certificate private key"); if (s_key2 == NULL) goto end; s_cert2 = load_cert_pass(s_cert_file2, s_cert_format, 1, pass, "second server certificate"); if (s_cert2 == NULL) goto end; } } #if !defined(OPENSSL_NO_NEXTPROTONEG) if (next_proto_neg_in) { next_proto.data = next_protos_parse(&next_proto.len, next_proto_neg_in); if (next_proto.data == NULL) goto end; } #endif alpn_ctx.data = NULL; if (alpn_in) { alpn_ctx.data = next_protos_parse(&alpn_ctx.len, alpn_in); if (alpn_ctx.data == NULL) goto end; } if (crl_file != NULL) { X509_CRL *crl; crl = load_crl(crl_file, crl_format, 0, "CRL"); if (crl == NULL) goto end; crls = sk_X509_CRL_new_null(); if (crls == NULL || !sk_X509_CRL_push(crls, crl)) { BIO_puts(bio_err, "Error adding CRL\n"); ERR_print_errors(bio_err); X509_CRL_free(crl); goto end; } } if (s_dcert_file != NULL) { if (s_dkey_file == NULL) s_dkey_file = s_dcert_file; s_dkey = load_key(s_dkey_file, s_dkey_format, 0, dpass, engine, "second certificate private key"); if (s_dkey == NULL) goto end; s_dcert = load_cert_pass(s_dcert_file, s_dcert_format, 1, dpass, "second server certificate"); if (s_dcert == NULL) { ERR_print_errors(bio_err); goto end; } if (s_dchain_file != NULL) { if (!load_certs(s_dchain_file, 0, &s_dchain, NULL, "second server certificate chain")) goto end; } } if (bio_s_out == NULL) { if (s_quiet && !s_debug) { bio_s_out = BIO_new(BIO_s_null()); if (s_msg && bio_s_msg == NULL) { bio_s_msg = dup_bio_out(FORMAT_TEXT); if (bio_s_msg == NULL) { BIO_printf(bio_err, "Out of memory\n"); goto end; } } } else { bio_s_out = dup_bio_out(FORMAT_TEXT); } } if (bio_s_out == NULL) goto end; if (nocert) { s_cert_file = NULL; s_key_file = NULL; s_dcert_file = NULL; s_dkey_file = NULL; s_cert_file2 = NULL; s_key_file2 = NULL; } ctx = SSL_CTX_new_ex(app_get0_libctx(), app_get0_propq(), meth); if (ctx == NULL) { ERR_print_errors(bio_err); goto end; } SSL_CTX_clear_mode(ctx, SSL_MODE_AUTO_RETRY); if (sdebug) ssl_ctx_security_debug(ctx, sdebug); if (!config_ctx(cctx, ssl_args, ctx)) goto end; if (ssl_config) { if (SSL_CTX_config(ctx, ssl_config) == 0) { BIO_printf(bio_err, "Error using configuration \"%s\"\n", ssl_config); ERR_print_errors(bio_err); goto end; } } #ifndef OPENSSL_NO_SCTP if (protocol == IPPROTO_SCTP && sctp_label_bug == 1) SSL_CTX_set_mode(ctx, SSL_MODE_DTLS_SCTP_LABEL_LENGTH_BUG); #endif if (min_version != 0 && SSL_CTX_set_min_proto_version(ctx, min_version) == 0) goto end; if (max_version != 0 && SSL_CTX_set_max_proto_version(ctx, max_version) == 0) goto end; if (session_id_prefix) { if (strlen(session_id_prefix) >= 32) BIO_printf(bio_err, "warning: id_prefix is too long, only one new session will be possible\n"); if (!SSL_CTX_set_generate_session_id(ctx, generate_session_id)) { BIO_printf(bio_err, "error setting 'id_prefix'\n"); ERR_print_errors(bio_err); goto end; } BIO_printf(bio_err, "id_prefix '%s' set.\n", session_id_prefix); } if (exc != NULL) ssl_ctx_set_excert(ctx, exc); if (state) SSL_CTX_set_info_callback(ctx, apps_ssl_info_callback); if (no_cache) SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_OFF); else if (ext_cache) init_session_cache_ctx(ctx); else SSL_CTX_sess_set_cache_size(ctx, 128); if (async) { SSL_CTX_set_mode(ctx, SSL_MODE_ASYNC); } if (no_ca_names) { SSL_CTX_set_options(ctx, SSL_OP_DISABLE_TLSEXT_CA_NAMES); } if (ignore_unexpected_eof) SSL_CTX_set_options(ctx, SSL_OP_IGNORE_UNEXPECTED_EOF); #ifndef OPENSSL_NO_KTLS if (enable_ktls) SSL_CTX_set_options(ctx, SSL_OP_ENABLE_KTLS); if (use_zc_sendfile) SSL_CTX_set_options(ctx, SSL_OP_ENABLE_KTLS_TX_ZEROCOPY_SENDFILE); #endif if (max_send_fragment > 0 && !SSL_CTX_set_max_send_fragment(ctx, max_send_fragment)) { BIO_printf(bio_err, "%s: Max send fragment size %u is out of permitted range\n", prog, max_send_fragment); goto end; } if (split_send_fragment > 0 && !SSL_CTX_set_split_send_fragment(ctx, split_send_fragment)) { BIO_printf(bio_err, "%s: Split send fragment size %u is out of permitted range\n", prog, split_send_fragment); goto end; } if (max_pipelines > 0 && !SSL_CTX_set_max_pipelines(ctx, max_pipelines)) { BIO_printf(bio_err, "%s: Max pipelines %u is out of permitted range\n", prog, max_pipelines); goto end; } if (read_buf_len > 0) { SSL_CTX_set_default_read_buffer_len(ctx, read_buf_len); } #ifndef OPENSSL_NO_SRTP if (srtp_profiles != NULL) { /* Returns 0 on success! */ if (SSL_CTX_set_tlsext_use_srtp(ctx, srtp_profiles) != 0) { BIO_printf(bio_err, "Error setting SRTP profile\n"); ERR_print_errors(bio_err); goto end; } } #endif if (!ctx_set_verify_locations(ctx, CAfile, noCAfile, CApath, noCApath, CAstore, noCAstore)) { ERR_print_errors(bio_err); goto end; } if (vpmtouched && !SSL_CTX_set1_param(ctx, vpm)) { BIO_printf(bio_err, "Error setting verify params\n"); ERR_print_errors(bio_err); goto end; } ssl_ctx_add_crls(ctx, crls, 0); if (!ssl_load_stores(ctx, vfyCApath, vfyCAfile, vfyCAstore, chCApath, chCAfile, chCAstore, crls, crl_download)) { BIO_printf(bio_err, "Error loading store locations\n"); ERR_print_errors(bio_err); goto end; } if (s_cert2) { ctx2 = SSL_CTX_new_ex(app_get0_libctx(), app_get0_propq(), meth); if (ctx2 == NULL) { ERR_print_errors(bio_err); goto end; } } if (ctx2 != NULL) { BIO_printf(bio_s_out, "Setting secondary ctx parameters\n"); if (sdebug) ssl_ctx_security_debug(ctx2, sdebug); if (session_id_prefix) { if (strlen(session_id_prefix) >= 32) BIO_printf(bio_err, "warning: id_prefix is too long, only one new session will be possible\n"); if (!SSL_CTX_set_generate_session_id(ctx2, generate_session_id)) { BIO_printf(bio_err, "error setting 'id_prefix'\n"); ERR_print_errors(bio_err); goto end; } BIO_printf(bio_err, "id_prefix '%s' set.\n", session_id_prefix); } if (exc != NULL) ssl_ctx_set_excert(ctx2, exc); if (state) SSL_CTX_set_info_callback(ctx2, apps_ssl_info_callback); if (no_cache) SSL_CTX_set_session_cache_mode(ctx2, SSL_SESS_CACHE_OFF); else if (ext_cache) init_session_cache_ctx(ctx2); else SSL_CTX_sess_set_cache_size(ctx2, 128); if (async) SSL_CTX_set_mode(ctx2, SSL_MODE_ASYNC); if (!ctx_set_verify_locations(ctx2, CAfile, noCAfile, CApath, noCApath, CAstore, noCAstore)) { ERR_print_errors(bio_err); goto end; } if (vpmtouched && !SSL_CTX_set1_param(ctx2, vpm)) { BIO_printf(bio_err, "Error setting verify params\n"); ERR_print_errors(bio_err); goto end; } ssl_ctx_add_crls(ctx2, crls, 0); if (!config_ctx(cctx, ssl_args, ctx2)) goto end; } #ifndef OPENSSL_NO_NEXTPROTONEG if (next_proto.data) SSL_CTX_set_next_protos_advertised_cb(ctx, next_proto_cb, &next_proto); #endif if (alpn_ctx.data) SSL_CTX_set_alpn_select_cb(ctx, alpn_cb, &alpn_ctx); if (!no_dhe) { EVP_PKEY *dhpkey = NULL; if (dhfile != NULL) dhpkey = load_keyparams(dhfile, FORMAT_UNDEF, 0, "DH", "DH parameters"); else if (s_cert_file != NULL) dhpkey = load_keyparams_suppress(s_cert_file, FORMAT_UNDEF, 0, "DH", "DH parameters", 1); if (dhpkey != NULL) { BIO_printf(bio_s_out, "Setting temp DH parameters\n"); } else { BIO_printf(bio_s_out, "Using default temp DH parameters\n"); } (void)BIO_flush(bio_s_out); if (dhpkey == NULL) { SSL_CTX_set_dh_auto(ctx, 1); } else { /* * We need 2 references: one for use by ctx and one for use by * ctx2 */ if (!EVP_PKEY_up_ref(dhpkey)) { EVP_PKEY_free(dhpkey); goto end; } if (!SSL_CTX_set0_tmp_dh_pkey(ctx, dhpkey)) { BIO_puts(bio_err, "Error setting temp DH parameters\n"); ERR_print_errors(bio_err); /* Free 2 references */ EVP_PKEY_free(dhpkey); EVP_PKEY_free(dhpkey); goto end; } } if (ctx2 != NULL) { if (dhfile != NULL) { EVP_PKEY *dhpkey2 = load_keyparams_suppress(s_cert_file2, FORMAT_UNDEF, 0, "DH", "DH parameters", 1); if (dhpkey2 != NULL) { BIO_printf(bio_s_out, "Setting temp DH parameters\n"); (void)BIO_flush(bio_s_out); EVP_PKEY_free(dhpkey); dhpkey = dhpkey2; } } if (dhpkey == NULL) { SSL_CTX_set_dh_auto(ctx2, 1); } else if (!SSL_CTX_set0_tmp_dh_pkey(ctx2, dhpkey)) { BIO_puts(bio_err, "Error setting temp DH parameters\n"); ERR_print_errors(bio_err); EVP_PKEY_free(dhpkey); goto end; } dhpkey = NULL; } EVP_PKEY_free(dhpkey); } if (!set_cert_key_stuff(ctx, s_cert, s_key, s_chain, build_chain)) goto end; if (s_serverinfo_file != NULL && !SSL_CTX_use_serverinfo_file(ctx, s_serverinfo_file)) { ERR_print_errors(bio_err); goto end; } if (ctx2 != NULL && !set_cert_key_stuff(ctx2, s_cert2, s_key2, NULL, build_chain)) goto end; if (s_dcert != NULL) { if (!set_cert_key_stuff(ctx, s_dcert, s_dkey, s_dchain, build_chain)) goto end; } if (no_resume_ephemeral) { SSL_CTX_set_not_resumable_session_callback(ctx, not_resumable_sess_cb); if (ctx2 != NULL) SSL_CTX_set_not_resumable_session_callback(ctx2, not_resumable_sess_cb); } #ifndef OPENSSL_NO_PSK if (psk_key != NULL) { if (s_debug) BIO_printf(bio_s_out, "PSK key given, setting server callback\n"); SSL_CTX_set_psk_server_callback(ctx, psk_server_cb); } if (psk_identity_hint != NULL) { if (min_version == TLS1_3_VERSION) { BIO_printf(bio_s_out, "PSK warning: there is NO identity hint in TLSv1.3\n"); } else { if (!SSL_CTX_use_psk_identity_hint(ctx, psk_identity_hint)) { BIO_printf(bio_err, "error setting PSK identity hint to context\n"); ERR_print_errors(bio_err); goto end; } } } #endif if (psksessf != NULL) { BIO *stmp = BIO_new_file(psksessf, "r"); if (stmp == NULL) { BIO_printf(bio_err, "Can't open PSK session file %s\n", psksessf); ERR_print_errors(bio_err); goto end; } psksess = PEM_read_bio_SSL_SESSION(stmp, NULL, 0, NULL); BIO_free(stmp); if (psksess == NULL) { BIO_printf(bio_err, "Can't read PSK session file %s\n", psksessf); ERR_print_errors(bio_err); goto end; } } if (psk_key != NULL || psksess != NULL) SSL_CTX_set_psk_find_session_callback(ctx, psk_find_session_cb); SSL_CTX_set_verify(ctx, s_server_verify, verify_callback); if (!SSL_CTX_set_session_id_context(ctx, (void *)&s_server_session_id_context, sizeof(s_server_session_id_context))) { BIO_printf(bio_err, "error setting session id context\n"); ERR_print_errors(bio_err); goto end; } /* Set DTLS cookie generation and verification callbacks */ SSL_CTX_set_cookie_generate_cb(ctx, generate_cookie_callback); SSL_CTX_set_cookie_verify_cb(ctx, verify_cookie_callback); /* Set TLS1.3 cookie generation and verification callbacks */ SSL_CTX_set_stateless_cookie_generate_cb(ctx, generate_stateless_cookie_callback); SSL_CTX_set_stateless_cookie_verify_cb(ctx, verify_stateless_cookie_callback); if (ctx2 != NULL) { SSL_CTX_set_verify(ctx2, s_server_verify, verify_callback); if (!SSL_CTX_set_session_id_context(ctx2, (void *)&s_server_session_id_context, sizeof(s_server_session_id_context))) { BIO_printf(bio_err, "error setting session id context\n"); ERR_print_errors(bio_err); goto end; } tlsextcbp.biodebug = bio_s_out; SSL_CTX_set_tlsext_servername_callback(ctx2, ssl_servername_cb); SSL_CTX_set_tlsext_servername_arg(ctx2, &tlsextcbp); SSL_CTX_set_tlsext_servername_callback(ctx, ssl_servername_cb); SSL_CTX_set_tlsext_servername_arg(ctx, &tlsextcbp); } #ifndef OPENSSL_NO_SRP if (srp_verifier_file != NULL) { if (!set_up_srp_verifier_file(ctx, &srp_callback_parm, srpuserseed, srp_verifier_file)) goto end; } else #endif if (CAfile != NULL) { SSL_CTX_set_client_CA_list(ctx, SSL_load_client_CA_file(CAfile)); if (ctx2) SSL_CTX_set_client_CA_list(ctx2, SSL_load_client_CA_file(CAfile)); } #ifndef OPENSSL_NO_OCSP if (s_tlsextstatus) { SSL_CTX_set_tlsext_status_cb(ctx, cert_status_cb); SSL_CTX_set_tlsext_status_arg(ctx, &tlscstatp); if (ctx2) { SSL_CTX_set_tlsext_status_cb(ctx2, cert_status_cb); SSL_CTX_set_tlsext_status_arg(ctx2, &tlscstatp); } } #endif if (set_keylog_file(ctx, keylog_file)) goto end; if (max_early_data >= 0) SSL_CTX_set_max_early_data(ctx, max_early_data); if (recv_max_early_data >= 0) SSL_CTX_set_recv_max_early_data(ctx, recv_max_early_data); if (cert_comp) { BIO_printf(bio_s_out, "Compressing certificates\n"); if (!SSL_CTX_compress_certs(ctx, 0)) BIO_printf(bio_s_out, "Error compressing certs on ctx\n"); if (ctx2 != NULL && !SSL_CTX_compress_certs(ctx2, 0)) BIO_printf(bio_s_out, "Error compressing certs on ctx2\n"); } if (enable_server_rpk) if (!SSL_CTX_set1_server_cert_type(ctx, cert_type_rpk, sizeof(cert_type_rpk))) { BIO_printf(bio_s_out, "Error setting server certificate types\n"); goto end; } if (enable_client_rpk) if (!SSL_CTX_set1_client_cert_type(ctx, cert_type_rpk, sizeof(cert_type_rpk))) { BIO_printf(bio_s_out, "Error setting server certificate types\n"); goto end; } if (rev) server_cb = rev_body; else if (www) server_cb = www_body; else server_cb = sv_body; #ifdef AF_UNIX if (socket_family == AF_UNIX && unlink_unix_path) unlink(host); #endif if (tfo) BIO_printf(bio_s_out, "Listening for TFO\n"); do_server(&accept_socket, host, port, socket_family, socket_type, protocol, server_cb, context, naccept, bio_s_out, tfo); print_stats(bio_s_out, ctx); ret = 0; end: SSL_CTX_free(ctx); SSL_SESSION_free(psksess); set_keylog_file(NULL, NULL); X509_free(s_cert); sk_X509_CRL_pop_free(crls, X509_CRL_free); X509_free(s_dcert); EVP_PKEY_free(s_key); EVP_PKEY_free(s_dkey); OSSL_STACK_OF_X509_free(s_chain); OSSL_STACK_OF_X509_free(s_dchain); OPENSSL_free(pass); OPENSSL_free(dpass); OPENSSL_free(host); OPENSSL_free(port); X509_VERIFY_PARAM_free(vpm); free_sessions(); OPENSSL_free(tlscstatp.host); OPENSSL_free(tlscstatp.port); OPENSSL_free(tlscstatp.path); SSL_CTX_free(ctx2); X509_free(s_cert2); EVP_PKEY_free(s_key2); #ifndef OPENSSL_NO_NEXTPROTONEG OPENSSL_free(next_proto.data); #endif OPENSSL_free(alpn_ctx.data); ssl_excert_free(exc); sk_OPENSSL_STRING_free(ssl_args); SSL_CONF_CTX_free(cctx); release_engine(engine); BIO_free(bio_s_out); bio_s_out = NULL; BIO_free(bio_s_msg); bio_s_msg = NULL; #ifdef CHARSET_EBCDIC BIO_meth_free(methods_ebcdic); #endif return ret; } static void print_stats(BIO *bio, SSL_CTX *ssl_ctx) { BIO_printf(bio, "%4ld items in the session cache\n", SSL_CTX_sess_number(ssl_ctx)); BIO_printf(bio, "%4ld client connects (SSL_connect())\n", SSL_CTX_sess_connect(ssl_ctx)); BIO_printf(bio, "%4ld client renegotiates (SSL_connect())\n", SSL_CTX_sess_connect_renegotiate(ssl_ctx)); BIO_printf(bio, "%4ld client connects that finished\n", SSL_CTX_sess_connect_good(ssl_ctx)); BIO_printf(bio, "%4ld server accepts (SSL_accept())\n", SSL_CTX_sess_accept(ssl_ctx)); BIO_printf(bio, "%4ld server renegotiates (SSL_accept())\n", SSL_CTX_sess_accept_renegotiate(ssl_ctx)); BIO_printf(bio, "%4ld server accepts that finished\n", SSL_CTX_sess_accept_good(ssl_ctx)); BIO_printf(bio, "%4ld session cache hits\n", SSL_CTX_sess_hits(ssl_ctx)); BIO_printf(bio, "%4ld session cache misses\n", SSL_CTX_sess_misses(ssl_ctx)); BIO_printf(bio, "%4ld session cache timeouts\n", SSL_CTX_sess_timeouts(ssl_ctx)); BIO_printf(bio, "%4ld callback cache hits\n", SSL_CTX_sess_cb_hits(ssl_ctx)); BIO_printf(bio, "%4ld cache full overflows (%ld allowed)\n", SSL_CTX_sess_cache_full(ssl_ctx), SSL_CTX_sess_get_cache_size(ssl_ctx)); } static long int count_reads_callback(BIO *bio, int cmd, const char *argp, size_t len, int argi, long argl, int ret, size_t *processed) { unsigned int *p_counter = (unsigned int *)BIO_get_callback_arg(bio); switch (cmd) { case BIO_CB_READ: /* No break here */ case BIO_CB_GETS: if (p_counter != NULL) ++*p_counter; break; default: break; } if (s_debug) { BIO_set_callback_arg(bio, (char *)bio_s_out); ret = (int)bio_dump_callback(bio, cmd, argp, len, argi, argl, ret, processed); BIO_set_callback_arg(bio, (char *)p_counter); } return ret; } static int sv_body(int s, int stype, int prot, unsigned char *context) { char *buf = NULL; fd_set readfds; int ret = 1, width; int k; unsigned long l; SSL *con = NULL; BIO *sbio; struct timeval timeout; #if !(defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_MSDOS)) struct timeval *timeoutp; #endif #ifndef OPENSSL_NO_DTLS # ifndef OPENSSL_NO_SCTP int isdtls = (stype == SOCK_DGRAM || prot == IPPROTO_SCTP); # else int isdtls = (stype == SOCK_DGRAM); # endif #endif buf = app_malloc(bufsize, "server buffer"); if (s_nbio) { if (!BIO_socket_nbio(s, 1)) ERR_print_errors(bio_err); else if (!s_quiet) BIO_printf(bio_err, "Turned on non blocking io\n"); } con = SSL_new(ctx); if (con == NULL) { ret = -1; goto err; } if (s_tlsextdebug) { SSL_set_tlsext_debug_callback(con, tlsext_cb); SSL_set_tlsext_debug_arg(con, bio_s_out); } if (context != NULL && !SSL_set_session_id_context(con, context, strlen((char *)context))) { BIO_printf(bio_err, "Error setting session id context\n"); ret = -1; goto err; } if (!SSL_clear(con)) { BIO_printf(bio_err, "Error clearing SSL connection\n"); ret = -1; goto err; } #ifndef OPENSSL_NO_DTLS if (isdtls) { # ifndef OPENSSL_NO_SCTP if (prot == IPPROTO_SCTP) sbio = BIO_new_dgram_sctp(s, BIO_NOCLOSE); else # endif sbio = BIO_new_dgram(s, BIO_NOCLOSE); if (sbio == NULL) { BIO_printf(bio_err, "Unable to create BIO\n"); ERR_print_errors(bio_err); goto err; } if (enable_timeouts) { timeout.tv_sec = 0; timeout.tv_usec = DGRAM_RCV_TIMEOUT; BIO_ctrl(sbio, BIO_CTRL_DGRAM_SET_RECV_TIMEOUT, 0, &timeout); timeout.tv_sec = 0; timeout.tv_usec = DGRAM_SND_TIMEOUT; BIO_ctrl(sbio, BIO_CTRL_DGRAM_SET_SEND_TIMEOUT, 0, &timeout); } if (socket_mtu) { if (socket_mtu < DTLS_get_link_min_mtu(con)) { BIO_printf(bio_err, "MTU too small. Must be at least %ld\n", DTLS_get_link_min_mtu(con)); ret = -1; BIO_free(sbio); goto err; } SSL_set_options(con, SSL_OP_NO_QUERY_MTU); if (!DTLS_set_link_mtu(con, socket_mtu)) { BIO_printf(bio_err, "Failed to set MTU\n"); ret = -1; BIO_free(sbio); goto err; } } else /* want to do MTU discovery */ BIO_ctrl(sbio, BIO_CTRL_DGRAM_MTU_DISCOVER, 0, NULL); # ifndef OPENSSL_NO_SCTP if (prot != IPPROTO_SCTP) # endif /* Turn on cookie exchange. Not necessary for SCTP */ SSL_set_options(con, SSL_OP_COOKIE_EXCHANGE); } else #endif sbio = BIO_new_socket(s, BIO_NOCLOSE); if (sbio == NULL) { BIO_printf(bio_err, "Unable to create BIO\n"); ERR_print_errors(bio_err); goto err; } if (s_nbio_test) { BIO *test; test = BIO_new(BIO_f_nbio_test()); if (test == NULL) { BIO_printf(bio_err, "Unable to create BIO\n"); ret = -1; BIO_free(sbio); goto err; } sbio = BIO_push(test, sbio); } SSL_set_bio(con, sbio, sbio); SSL_set_accept_state(con); /* SSL_set_fd(con,s); */ BIO_set_callback_ex(SSL_get_rbio(con), count_reads_callback); if (s_msg) { #ifndef OPENSSL_NO_SSL_TRACE if (s_msg == 2) SSL_set_msg_callback(con, SSL_trace); else #endif SSL_set_msg_callback(con, msg_cb); SSL_set_msg_callback_arg(con, bio_s_msg ? bio_s_msg : bio_s_out); } if (s_tlsextdebug) { SSL_set_tlsext_debug_callback(con, tlsext_cb); SSL_set_tlsext_debug_arg(con, bio_s_out); } if (early_data) { int write_header = 1, edret = SSL_READ_EARLY_DATA_ERROR; size_t readbytes; while (edret != SSL_READ_EARLY_DATA_FINISH) { for (;;) { edret = SSL_read_early_data(con, buf, bufsize, &readbytes); if (edret != SSL_READ_EARLY_DATA_ERROR) break; switch (SSL_get_error(con, 0)) { case SSL_ERROR_WANT_WRITE: case SSL_ERROR_WANT_ASYNC: case SSL_ERROR_WANT_READ: /* Just keep trying - busy waiting */ continue; default: BIO_printf(bio_err, "Error reading early data\n"); ERR_print_errors(bio_err); goto err; } } if (readbytes > 0) { if (write_header) { BIO_printf(bio_s_out, "Early data received:\n"); write_header = 0; } raw_write_stdout(buf, (unsigned int)readbytes); (void)BIO_flush(bio_s_out); } } if (write_header) { if (SSL_get_early_data_status(con) == SSL_EARLY_DATA_NOT_SENT) BIO_printf(bio_s_out, "No early data received\n"); else BIO_printf(bio_s_out, "Early data was rejected\n"); } else { BIO_printf(bio_s_out, "\nEnd of early data\n"); } if (SSL_is_init_finished(con)) print_connection_info(con); } if (fileno_stdin() > s) width = fileno_stdin() + 1; else width = s + 1; for (;;) { int i; int read_from_terminal; int read_from_sslcon; read_from_terminal = 0; read_from_sslcon = SSL_has_pending(con) || (async && SSL_waiting_for_async(con)); if (!read_from_sslcon) { FD_ZERO(&readfds); #if !defined(OPENSSL_SYS_WINDOWS) && !defined(OPENSSL_SYS_MSDOS) openssl_fdset(fileno_stdin(), &readfds); #endif openssl_fdset(s, &readfds); /* * Note: under VMS with SOCKETSHR the second parameter is * currently of type (int *) whereas under other systems it is * (void *) if you don't have a cast it will choke the compiler: * if you do have a cast then you can either go for (int *) or * (void *). */ #if defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_MSDOS) /* * Under DOS (non-djgpp) and Windows we can't select on stdin: * only on sockets. As a workaround we timeout the select every * second and check for any keypress. In a proper Windows * application we wouldn't do this because it is inefficient. */ timeout.tv_sec = 1; timeout.tv_usec = 0; i = select(width, (void *)&readfds, NULL, NULL, &timeout); if (has_stdin_waiting()) read_from_terminal = 1; if ((i < 0) || (!i && !read_from_terminal)) continue; #else if (SSL_is_dtls(con) && DTLSv1_get_timeout(con, &timeout)) timeoutp = &timeout; else timeoutp = NULL; i = select(width, (void *)&readfds, NULL, NULL, timeoutp); if ((SSL_is_dtls(con)) && DTLSv1_handle_timeout(con) > 0) BIO_printf(bio_err, "TIMEOUT occurred\n"); if (i <= 0) continue; if (FD_ISSET(fileno_stdin(), &readfds)) read_from_terminal = 1; #endif if (FD_ISSET(s, &readfds)) read_from_sslcon = 1; } if (read_from_terminal) { if (s_crlf) { int j, lf_num; i = raw_read_stdin(buf, bufsize / 2); lf_num = 0; /* both loops are skipped when i <= 0 */ for (j = 0; j < i; j++) if (buf[j] == '\n') lf_num++; for (j = i - 1; j >= 0; j--) { buf[j + lf_num] = buf[j]; if (buf[j] == '\n') { lf_num--; i++; buf[j + lf_num] = '\r'; } } assert(lf_num == 0); } else { i = raw_read_stdin(buf, bufsize); } if (!s_quiet && !s_brief) { if ((i <= 0) || (buf[0] == 'Q')) { BIO_printf(bio_s_out, "DONE\n"); (void)BIO_flush(bio_s_out); BIO_closesocket(s); close_accept_socket(); ret = -11; goto err; } if ((i <= 0) || (buf[0] == 'q')) { BIO_printf(bio_s_out, "DONE\n"); (void)BIO_flush(bio_s_out); if (SSL_version(con) != DTLS1_VERSION) BIO_closesocket(s); /* * close_accept_socket(); ret= -11; */ goto err; } if ((buf[0] == 'r') && ((buf[1] == '\n') || (buf[1] == '\r'))) { SSL_renegotiate(con); i = SSL_do_handshake(con); printf("SSL_do_handshake -> %d\n", i); continue; } if ((buf[0] == 'R') && ((buf[1] == '\n') || (buf[1] == '\r'))) { SSL_set_verify(con, SSL_VERIFY_PEER | SSL_VERIFY_CLIENT_ONCE, NULL); SSL_renegotiate(con); i = SSL_do_handshake(con); printf("SSL_do_handshake -> %d\n", i); continue; } if ((buf[0] == 'K' || buf[0] == 'k') && ((buf[1] == '\n') || (buf[1] == '\r'))) { SSL_key_update(con, buf[0] == 'K' ? SSL_KEY_UPDATE_REQUESTED : SSL_KEY_UPDATE_NOT_REQUESTED); i = SSL_do_handshake(con); printf("SSL_do_handshake -> %d\n", i); continue; } if (buf[0] == 'c' && ((buf[1] == '\n') || (buf[1] == '\r'))) { SSL_set_verify(con, SSL_VERIFY_PEER, NULL); i = SSL_verify_client_post_handshake(con); if (i == 0) { printf("Failed to initiate request\n"); ERR_print_errors(bio_err); } else { i = SSL_do_handshake(con); printf("SSL_do_handshake -> %d\n", i); } continue; } if (buf[0] == 'P') { static const char str[] = "Lets print some clear text\n"; BIO_write(SSL_get_wbio(con), str, sizeof(str) -1); } if (buf[0] == 'S') { print_stats(bio_s_out, SSL_get_SSL_CTX(con)); } } #ifdef CHARSET_EBCDIC ebcdic2ascii(buf, buf, i); #endif l = k = 0; for (;;) { /* should do a select for the write */ #ifdef RENEG static count = 0; if (++count == 100) { count = 0; SSL_renegotiate(con); } #endif k = SSL_write(con, &(buf[l]), (unsigned int)i); #ifndef OPENSSL_NO_SRP while (SSL_get_error(con, k) == SSL_ERROR_WANT_X509_LOOKUP) { BIO_printf(bio_s_out, "LOOKUP renego during write\n"); lookup_srp_user(&srp_callback_parm, bio_s_out); k = SSL_write(con, &(buf[l]), (unsigned int)i); } #endif switch (SSL_get_error(con, k)) { case SSL_ERROR_NONE: break; case SSL_ERROR_WANT_ASYNC: BIO_printf(bio_s_out, "Write BLOCK (Async)\n"); (void)BIO_flush(bio_s_out); wait_for_async(con); break; case SSL_ERROR_WANT_WRITE: case SSL_ERROR_WANT_READ: case SSL_ERROR_WANT_X509_LOOKUP: BIO_printf(bio_s_out, "Write BLOCK\n"); (void)BIO_flush(bio_s_out); break; case SSL_ERROR_WANT_ASYNC_JOB: /* * This shouldn't ever happen in s_server. Treat as an error */ case SSL_ERROR_SYSCALL: case SSL_ERROR_SSL: BIO_printf(bio_s_out, "ERROR\n"); (void)BIO_flush(bio_s_out); ERR_print_errors(bio_err); ret = 1; goto err; /* break; */ case SSL_ERROR_ZERO_RETURN: BIO_printf(bio_s_out, "DONE\n"); (void)BIO_flush(bio_s_out); ret = 1; goto err; } if (k > 0) { l += k; i -= k; } if (i <= 0) break; } } if (read_from_sslcon) { /* * init_ssl_connection handles all async events itself so if we're * waiting for async then we shouldn't go back into * init_ssl_connection */ if ((!async || !SSL_waiting_for_async(con)) && !SSL_is_init_finished(con)) { /* * Count number of reads during init_ssl_connection. * It helps us to distinguish configuration errors from errors * caused by a client. */ unsigned int read_counter = 0; BIO_set_callback_arg(SSL_get_rbio(con), (char *)&read_counter); i = init_ssl_connection(con); BIO_set_callback_arg(SSL_get_rbio(con), NULL); /* * If initialization fails without reads, then * there was a fatal error in configuration. */ if (i <= 0 && read_counter == 0) { ret = -1; goto err; } if (i < 0) { ret = 0; goto err; } else if (i == 0) { ret = 1; goto err; } } else { again: i = SSL_read(con, (char *)buf, bufsize); #ifndef OPENSSL_NO_SRP while (SSL_get_error(con, i) == SSL_ERROR_WANT_X509_LOOKUP) { BIO_printf(bio_s_out, "LOOKUP renego during read\n"); lookup_srp_user(&srp_callback_parm, bio_s_out); i = SSL_read(con, (char *)buf, bufsize); } #endif switch (SSL_get_error(con, i)) { case SSL_ERROR_NONE: #ifdef CHARSET_EBCDIC ascii2ebcdic(buf, buf, i); #endif raw_write_stdout(buf, (unsigned int)i); (void)BIO_flush(bio_s_out); if (SSL_has_pending(con)) goto again; break; case SSL_ERROR_WANT_ASYNC: BIO_printf(bio_s_out, "Read BLOCK (Async)\n"); (void)BIO_flush(bio_s_out); wait_for_async(con); break; case SSL_ERROR_WANT_WRITE: case SSL_ERROR_WANT_READ: BIO_printf(bio_s_out, "Read BLOCK\n"); (void)BIO_flush(bio_s_out); break; case SSL_ERROR_WANT_ASYNC_JOB: /* * This shouldn't ever happen in s_server. Treat as an error */ case SSL_ERROR_SYSCALL: case SSL_ERROR_SSL: BIO_printf(bio_s_out, "ERROR\n"); (void)BIO_flush(bio_s_out); ERR_print_errors(bio_err); ret = 1; goto err; case SSL_ERROR_ZERO_RETURN: BIO_printf(bio_s_out, "DONE\n"); (void)BIO_flush(bio_s_out); ret = 1; goto err; } } } } err: if (con != NULL) { BIO_printf(bio_s_out, "shutting down SSL\n"); do_ssl_shutdown(con); SSL_free(con); } BIO_printf(bio_s_out, "CONNECTION CLOSED\n"); OPENSSL_clear_free(buf, bufsize); return ret; } static void close_accept_socket(void) { BIO_printf(bio_err, "shutdown accept socket\n"); if (accept_socket >= 0) { BIO_closesocket(accept_socket); } } static int is_retryable(SSL *con, int i) { int err = SSL_get_error(con, i); /* If it's not a fatal error, it must be retryable */ return (err != SSL_ERROR_SSL) && (err != SSL_ERROR_SYSCALL) && (err != SSL_ERROR_ZERO_RETURN); } static int init_ssl_connection(SSL *con) { int i; long verify_err; int retry = 0; if (dtlslisten || stateless) { BIO_ADDR *client = NULL; if (dtlslisten) { if ((client = BIO_ADDR_new()) == NULL) { BIO_printf(bio_err, "ERROR - memory\n"); return 0; } i = DTLSv1_listen(con, client); } else { i = SSL_stateless(con); } if (i > 0) { BIO *wbio; int fd = -1; if (dtlslisten) { wbio = SSL_get_wbio(con); if (wbio) { BIO_get_fd(wbio, &fd); } if (!wbio || BIO_connect(fd, client, 0) == 0) { BIO_printf(bio_err, "ERROR - unable to connect\n"); BIO_ADDR_free(client); return 0; } (void)BIO_ctrl_set_connected(wbio, client); BIO_ADDR_free(client); dtlslisten = 0; } else { stateless = 0; } i = SSL_accept(con); } else { BIO_ADDR_free(client); } } else { do { i = SSL_accept(con); if (i <= 0) retry = is_retryable(con, i); #ifdef CERT_CB_TEST_RETRY { while (i <= 0 && SSL_get_error(con, i) == SSL_ERROR_WANT_X509_LOOKUP && SSL_get_state(con) == TLS_ST_SR_CLNT_HELLO) { BIO_printf(bio_err, "LOOKUP from certificate callback during accept\n"); i = SSL_accept(con); if (i <= 0) retry = is_retryable(con, i); } } #endif #ifndef OPENSSL_NO_SRP while (i <= 0 && SSL_get_error(con, i) == SSL_ERROR_WANT_X509_LOOKUP) { BIO_printf(bio_s_out, "LOOKUP during accept %s\n", srp_callback_parm.login); lookup_srp_user(&srp_callback_parm, bio_s_out); i = SSL_accept(con); if (i <= 0) retry = is_retryable(con, i); } #endif } while (i < 0 && SSL_waiting_for_async(con)); } if (i <= 0) { if (((dtlslisten || stateless) && i == 0) || (!dtlslisten && !stateless && retry)) { BIO_printf(bio_s_out, "DELAY\n"); return 1; } BIO_printf(bio_err, "ERROR\n"); verify_err = SSL_get_verify_result(con); if (verify_err != X509_V_OK) { BIO_printf(bio_err, "verify error:%s\n", X509_verify_cert_error_string(verify_err)); } /* Always print any error messages */ ERR_print_errors(bio_err); return 0; } print_connection_info(con); return 1; } static void print_connection_info(SSL *con) { const char *str; X509 *peer; char buf[BUFSIZ]; #if !defined(OPENSSL_NO_NEXTPROTONEG) const unsigned char *next_proto_neg; unsigned next_proto_neg_len; #endif unsigned char *exportedkeymat; int i; if (s_brief) print_ssl_summary(con); PEM_write_bio_SSL_SESSION(bio_s_out, SSL_get_session(con)); peer = SSL_get0_peer_certificate(con); if (peer != NULL) { BIO_printf(bio_s_out, "Client certificate\n"); PEM_write_bio_X509(bio_s_out, peer); dump_cert_text(bio_s_out, peer); peer = NULL; } /* Only display RPK information if configured */ if (SSL_get_negotiated_server_cert_type(con) == TLSEXT_cert_type_rpk) BIO_printf(bio_s_out, "Server-to-client raw public key negotiated\n"); if (SSL_get_negotiated_client_cert_type(con) == TLSEXT_cert_type_rpk) BIO_printf(bio_s_out, "Client-to-server raw public key negotiated\n"); if (enable_client_rpk) { EVP_PKEY *client_rpk = SSL_get0_peer_rpk(con); if (client_rpk != NULL) { BIO_printf(bio_s_out, "Client raw public key\n"); EVP_PKEY_print_public(bio_s_out, client_rpk, 2, NULL); } } if (SSL_get_shared_ciphers(con, buf, sizeof(buf)) != NULL) BIO_printf(bio_s_out, "Shared ciphers:%s\n", buf); str = SSL_CIPHER_get_name(SSL_get_current_cipher(con)); ssl_print_sigalgs(bio_s_out, con); #ifndef OPENSSL_NO_EC ssl_print_point_formats(bio_s_out, con); ssl_print_groups(bio_s_out, con, 0); #endif print_ca_names(bio_s_out, con); BIO_printf(bio_s_out, "CIPHER is %s\n", (str != NULL) ? str : "(NONE)"); #if !defined(OPENSSL_NO_NEXTPROTONEG) SSL_get0_next_proto_negotiated(con, &next_proto_neg, &next_proto_neg_len); if (next_proto_neg) { BIO_printf(bio_s_out, "NEXTPROTO is "); BIO_write(bio_s_out, next_proto_neg, next_proto_neg_len); BIO_printf(bio_s_out, "\n"); } #endif #ifndef OPENSSL_NO_SRTP { SRTP_PROTECTION_PROFILE *srtp_profile = SSL_get_selected_srtp_profile(con); if (srtp_profile) BIO_printf(bio_s_out, "SRTP Extension negotiated, profile=%s\n", srtp_profile->name); } #endif if (SSL_session_reused(con)) BIO_printf(bio_s_out, "Reused session-id\n"); ssl_print_secure_renegotiation_notes(bio_s_out, con); if ((SSL_get_options(con) & SSL_OP_NO_RENEGOTIATION)) BIO_printf(bio_s_out, "Renegotiation is DISABLED\n"); if (keymatexportlabel != NULL) { BIO_printf(bio_s_out, "Keying material exporter:\n"); BIO_printf(bio_s_out, " Label: '%s'\n", keymatexportlabel); BIO_printf(bio_s_out, " Length: %i bytes\n", keymatexportlen); exportedkeymat = app_malloc(keymatexportlen, "export key"); if (SSL_export_keying_material(con, exportedkeymat, keymatexportlen, keymatexportlabel, strlen(keymatexportlabel), NULL, 0, 0) <= 0) { BIO_printf(bio_s_out, " Error\n"); } else { BIO_printf(bio_s_out, " Keying material: "); for (i = 0; i < keymatexportlen; i++) BIO_printf(bio_s_out, "%02X", exportedkeymat[i]); BIO_printf(bio_s_out, "\n"); } OPENSSL_free(exportedkeymat); } #ifndef OPENSSL_NO_KTLS if (BIO_get_ktls_send(SSL_get_wbio(con))) BIO_printf(bio_err, "Using Kernel TLS for sending\n"); if (BIO_get_ktls_recv(SSL_get_rbio(con))) BIO_printf(bio_err, "Using Kernel TLS for receiving\n"); #endif (void)BIO_flush(bio_s_out); } static int www_body(int s, int stype, int prot, unsigned char *context) { char *buf = NULL, *p; int ret = 1; int i, j, k, dot; SSL *con; const SSL_CIPHER *c; BIO *io, *ssl_bio, *sbio; #ifdef RENEG int total_bytes = 0; #endif int width; #ifndef OPENSSL_NO_KTLS int use_sendfile_for_req = use_sendfile; #endif fd_set readfds; const char *opmode; #ifdef CHARSET_EBCDIC BIO *filter; #endif /* Set width for a select call if needed */ width = s + 1; /* as we use BIO_gets(), and it always null terminates data, we need * to allocate 1 byte longer buffer to fit the full 2^14 byte record */ p = buf = app_malloc(bufsize + 1, "server www buffer"); io = BIO_new(BIO_f_buffer()); ssl_bio = BIO_new(BIO_f_ssl()); if ((io == NULL) || (ssl_bio == NULL)) goto err; if (s_nbio) { if (!BIO_socket_nbio(s, 1)) ERR_print_errors(bio_err); else if (!s_quiet) BIO_printf(bio_err, "Turned on non blocking io\n"); } /* lets make the output buffer a reasonable size */ if (BIO_set_write_buffer_size(io, bufsize) <= 0) goto err; if ((con = SSL_new(ctx)) == NULL) goto err; if (s_tlsextdebug) { SSL_set_tlsext_debug_callback(con, tlsext_cb); SSL_set_tlsext_debug_arg(con, bio_s_out); } if (context != NULL && !SSL_set_session_id_context(con, context, strlen((char *)context))) { SSL_free(con); goto err; } sbio = BIO_new_socket(s, BIO_NOCLOSE); if (sbio == NULL) { SSL_free(con); goto err; } if (s_nbio_test) { BIO *test; test = BIO_new(BIO_f_nbio_test()); if (test == NULL) { SSL_free(con); BIO_free(sbio); goto err; } sbio = BIO_push(test, sbio); } SSL_set_bio(con, sbio, sbio); SSL_set_accept_state(con); /* No need to free |con| after this. Done by BIO_free(ssl_bio) */ BIO_set_ssl(ssl_bio, con, BIO_CLOSE); BIO_push(io, ssl_bio); ssl_bio = NULL; #ifdef CHARSET_EBCDIC filter = BIO_new(BIO_f_ebcdic_filter()); if (filter == NULL) goto err; io = BIO_push(filter, io); #endif if (s_debug) { BIO_set_callback_ex(SSL_get_rbio(con), bio_dump_callback); BIO_set_callback_arg(SSL_get_rbio(con), (char *)bio_s_out); } if (s_msg) { #ifndef OPENSSL_NO_SSL_TRACE if (s_msg == 2) SSL_set_msg_callback(con, SSL_trace); else #endif SSL_set_msg_callback(con, msg_cb); SSL_set_msg_callback_arg(con, bio_s_msg ? bio_s_msg : bio_s_out); } for (;;) { i = BIO_gets(io, buf, bufsize + 1); if (i < 0) { /* error */ if (!BIO_should_retry(io) && !SSL_waiting_for_async(con)) { if (!s_quiet) ERR_print_errors(bio_err); goto err; } else { BIO_printf(bio_s_out, "read R BLOCK\n"); #ifndef OPENSSL_NO_SRP if (BIO_should_io_special(io) && BIO_get_retry_reason(io) == BIO_RR_SSL_X509_LOOKUP) { BIO_printf(bio_s_out, "LOOKUP renego during read\n"); lookup_srp_user(&srp_callback_parm, bio_s_out); continue; } #endif OSSL_sleep(1000); continue; } } else if (i == 0) { /* end of input */ ret = 1; goto end; } /* else we have data */ if ((www == 1 && HAS_PREFIX(buf, "GET ")) || (www == 2 && HAS_PREFIX(buf, "GET /stats "))) { X509 *peer = NULL; STACK_OF(SSL_CIPHER) *sk; static const char *space = " "; if (www == 1 && HAS_PREFIX(buf, "GET /reneg")) { if (HAS_PREFIX(buf, "GET /renegcert")) SSL_set_verify(con, SSL_VERIFY_PEER | SSL_VERIFY_CLIENT_ONCE, NULL); i = SSL_renegotiate(con); BIO_printf(bio_s_out, "SSL_renegotiate -> %d\n", i); /* Send the HelloRequest */ i = SSL_do_handshake(con); if (i <= 0) { BIO_printf(bio_s_out, "SSL_do_handshake() Retval %d\n", SSL_get_error(con, i)); ERR_print_errors(bio_err); goto err; } /* Wait for a ClientHello to come back */ FD_ZERO(&readfds); openssl_fdset(s, &readfds); i = select(width, (void *)&readfds, NULL, NULL, NULL); if (i <= 0 || !FD_ISSET(s, &readfds)) { BIO_printf(bio_s_out, "Error waiting for client response\n"); ERR_print_errors(bio_err); goto err; } /* * We're not actually expecting any data here and we ignore * any that is sent. This is just to force the handshake that * we're expecting to come from the client. If they haven't * sent one there's not much we can do. */ BIO_gets(io, buf, bufsize + 1); } BIO_puts(io, "HTTP/1.0 200 ok\r\nContent-type: text/html\r\n\r\n"); BIO_puts(io, "<HTML><BODY BGCOLOR=\"#ffffff\">\n"); BIO_puts(io, "<pre>\n"); /* BIO_puts(io, OpenSSL_version(OPENSSL_VERSION)); */ BIO_puts(io, "\n"); for (i = 0; i < local_argc; i++) { const char *myp; for (myp = local_argv[i]; *myp; myp++) switch (*myp) { case '<': BIO_puts(io, "&lt;"); break; case '>': BIO_puts(io, "&gt;"); break; case '&': BIO_puts(io, "&amp;"); break; default: BIO_write(io, myp, 1); break; } BIO_write(io, " ", 1); } BIO_puts(io, "\n"); ssl_print_secure_renegotiation_notes(io, con); /* * The following is evil and should not really be done */ BIO_printf(io, "Ciphers supported in s_server binary\n"); sk = SSL_get_ciphers(con); j = sk_SSL_CIPHER_num(sk); for (i = 0; i < j; i++) { c = sk_SSL_CIPHER_value(sk, i); BIO_printf(io, "%-11s:%-25s ", SSL_CIPHER_get_version(c), SSL_CIPHER_get_name(c)); if ((((i + 1) % 2) == 0) && (i + 1 != j)) BIO_puts(io, "\n"); } BIO_puts(io, "\n"); p = SSL_get_shared_ciphers(con, buf, bufsize); if (p != NULL) { BIO_printf(io, "---\nCiphers common between both SSL end points:\n"); j = i = 0; while (*p) { if (*p == ':') { BIO_write(io, space, 26 - j); i++; j = 0; BIO_write(io, ((i % 3) ? " " : "\n"), 1); } else { BIO_write(io, p, 1); j++; } p++; } BIO_puts(io, "\n"); } ssl_print_sigalgs(io, con); #ifndef OPENSSL_NO_EC ssl_print_groups(io, con, 0); #endif print_ca_names(io, con); BIO_printf(io, (SSL_session_reused(con) ? "---\nReused, " : "---\nNew, ")); c = SSL_get_current_cipher(con); BIO_printf(io, "%s, Cipher is %s\n", SSL_CIPHER_get_version(c), SSL_CIPHER_get_name(c)); SSL_SESSION_print(io, SSL_get_session(con)); BIO_printf(io, "---\n"); print_stats(io, SSL_get_SSL_CTX(con)); BIO_printf(io, "---\n"); peer = SSL_get0_peer_certificate(con); if (peer != NULL) { BIO_printf(io, "Client certificate\n"); X509_print(io, peer); PEM_write_bio_X509(io, peer); peer = NULL; } else { BIO_puts(io, "no client certificate available\n"); } BIO_puts(io, "</pre></BODY></HTML>\r\n\r\n"); break; } else if ((www == 2 || www == 3) && CHECK_AND_SKIP_PREFIX(p, "GET /")) { BIO *file; char *e; static const char *text = "HTTP/1.0 200 ok\r\nContent-type: text/plain\r\n\r\n"; dot = 1; for (e = p; *e != '\0'; e++) { if (e[0] == ' ') break; if (e[0] == ':') { /* Windows drive. We treat this the same way as ".." */ dot = -1; break; } switch (dot) { case 1: dot = (e[0] == '.') ? 2 : 0; break; case 2: dot = (e[0] == '.') ? 3 : 0; break; case 3: dot = (e[0] == '/' || e[0] == '\\') ? -1 : 0; break; } if (dot == 0) dot = (e[0] == '/' || e[0] == '\\') ? 1 : 0; } dot = (dot == 3) || (dot == -1); /* filename contains ".." * component */ if (*e == '\0') { BIO_puts(io, text); BIO_printf(io, "'%s' is an invalid file name\r\n", p); break; } *e = '\0'; if (dot) { BIO_puts(io, text); BIO_printf(io, "'%s' contains '..' or ':'\r\n", p); break; } if (*p == '/' || *p == '\\') { BIO_puts(io, text); BIO_printf(io, "'%s' is an invalid path\r\n", p); break; } /* if a directory, do the index thang */ if (app_isdir(p) > 0) { BIO_puts(io, text); BIO_printf(io, "'%s' is a directory\r\n", p); break; } opmode = (http_server_binmode == 1) ? "rb" : "r"; if ((file = BIO_new_file(p, opmode)) == NULL) { BIO_puts(io, text); BIO_printf(io, "Error opening '%s' mode='%s'\r\n", p, opmode); ERR_print_errors(io); break; } if (!s_quiet) BIO_printf(bio_err, "FILE:%s\n", p); if (www == 2) { i = strlen(p); if (((i > 5) && (strcmp(&(p[i - 5]), ".html") == 0)) || ((i > 4) && (strcmp(&(p[i - 4]), ".php") == 0)) || ((i > 4) && (strcmp(&(p[i - 4]), ".htm") == 0))) BIO_puts(io, "HTTP/1.0 200 ok\r\nContent-type: text/html\r\n\r\n"); else BIO_puts(io, "HTTP/1.0 200 ok\r\nContent-type: text/plain\r\n\r\n"); } /* send the file */ #ifndef OPENSSL_NO_KTLS if (use_sendfile_for_req && !BIO_get_ktls_send(SSL_get_wbio(con))) { BIO_printf(bio_err, "Warning: sendfile requested but KTLS is not available\n"); use_sendfile_for_req = 0; } if (use_sendfile_for_req) { FILE *fp = NULL; int fd; struct stat st; off_t offset = 0; size_t filesize; BIO_get_fp(file, &fp); fd = fileno(fp); if (fstat(fd, &st) < 0) { BIO_printf(io, "Error fstat '%s'\r\n", p); ERR_print_errors(io); goto write_error; } filesize = st.st_size; if (((int)BIO_flush(io)) < 0) goto write_error; for (;;) { i = SSL_sendfile(con, fd, offset, filesize, 0); if (i < 0) { BIO_printf(io, "Error SSL_sendfile '%s'\r\n", p); ERR_print_errors(io); break; } else { offset += i; filesize -= i; } if (filesize <= 0) { if (!s_quiet) BIO_printf(bio_err, "KTLS SENDFILE '%s' OK\n", p); break; } } } else #endif { for (;;) { i = BIO_read(file, buf, bufsize); if (i <= 0) break; #ifdef RENEG total_bytes += i; BIO_printf(bio_err, "%d\n", i); if (total_bytes > 3 * 1024) { total_bytes = 0; BIO_printf(bio_err, "RENEGOTIATE\n"); SSL_renegotiate(con); } #endif for (j = 0; j < i;) { #ifdef RENEG static count = 0; if (++count == 13) SSL_renegotiate(con); #endif k = BIO_write(io, &(buf[j]), i - j); if (k <= 0) { if (!BIO_should_retry(io) && !SSL_waiting_for_async(con)) { goto write_error; } else { BIO_printf(bio_s_out, "rwrite W BLOCK\n"); } } else { j += k; } } } } write_error: BIO_free(file); break; } } for (;;) { i = (int)BIO_flush(io); if (i <= 0) { if (!BIO_should_retry(io)) break; } else break; } end: /* make sure we reuse sessions */ do_ssl_shutdown(con); err: OPENSSL_free(buf); BIO_free(ssl_bio); BIO_free_all(io); return ret; } static int rev_body(int s, int stype, int prot, unsigned char *context) { char *buf = NULL; int i; int ret = 1; SSL *con; BIO *io, *ssl_bio, *sbio; #ifdef CHARSET_EBCDIC BIO *filter; #endif /* as we use BIO_gets(), and it always null terminates data, we need * to allocate 1 byte longer buffer to fit the full 2^14 byte record */ buf = app_malloc(bufsize + 1, "server rev buffer"); io = BIO_new(BIO_f_buffer()); ssl_bio = BIO_new(BIO_f_ssl()); if ((io == NULL) || (ssl_bio == NULL)) goto err; /* lets make the output buffer a reasonable size */ if (BIO_set_write_buffer_size(io, bufsize) <= 0) goto err; if ((con = SSL_new(ctx)) == NULL) goto err; if (s_tlsextdebug) { SSL_set_tlsext_debug_callback(con, tlsext_cb); SSL_set_tlsext_debug_arg(con, bio_s_out); } if (context != NULL && !SSL_set_session_id_context(con, context, strlen((char *)context))) { SSL_free(con); ERR_print_errors(bio_err); goto err; } sbio = BIO_new_socket(s, BIO_NOCLOSE); if (sbio == NULL) { SSL_free(con); ERR_print_errors(bio_err); goto err; } SSL_set_bio(con, sbio, sbio); SSL_set_accept_state(con); /* No need to free |con| after this. Done by BIO_free(ssl_bio) */ BIO_set_ssl(ssl_bio, con, BIO_CLOSE); BIO_push(io, ssl_bio); ssl_bio = NULL; #ifdef CHARSET_EBCDIC filter = BIO_new(BIO_f_ebcdic_filter()); if (filter == NULL) goto err; io = BIO_push(filter, io); #endif if (s_debug) { BIO_set_callback_ex(SSL_get_rbio(con), bio_dump_callback); BIO_set_callback_arg(SSL_get_rbio(con), (char *)bio_s_out); } if (s_msg) { #ifndef OPENSSL_NO_SSL_TRACE if (s_msg == 2) SSL_set_msg_callback(con, SSL_trace); else #endif SSL_set_msg_callback(con, msg_cb); SSL_set_msg_callback_arg(con, bio_s_msg ? bio_s_msg : bio_s_out); } for (;;) { i = BIO_do_handshake(io); if (i > 0) break; if (!BIO_should_retry(io)) { BIO_puts(bio_err, "CONNECTION FAILURE\n"); ERR_print_errors(bio_err); goto end; } #ifndef OPENSSL_NO_SRP if (BIO_should_io_special(io) && BIO_get_retry_reason(io) == BIO_RR_SSL_X509_LOOKUP) { BIO_printf(bio_s_out, "LOOKUP renego during accept\n"); lookup_srp_user(&srp_callback_parm, bio_s_out); continue; } #endif } BIO_printf(bio_err, "CONNECTION ESTABLISHED\n"); print_ssl_summary(con); for (;;) { i = BIO_gets(io, buf, bufsize + 1); if (i < 0) { /* error */ if (!BIO_should_retry(io)) { if (!s_quiet) ERR_print_errors(bio_err); goto err; } else { BIO_printf(bio_s_out, "read R BLOCK\n"); #ifndef OPENSSL_NO_SRP if (BIO_should_io_special(io) && BIO_get_retry_reason(io) == BIO_RR_SSL_X509_LOOKUP) { BIO_printf(bio_s_out, "LOOKUP renego during read\n"); lookup_srp_user(&srp_callback_parm, bio_s_out); continue; } #endif OSSL_sleep(1000); continue; } } else if (i == 0) { /* end of input */ ret = 1; BIO_printf(bio_err, "CONNECTION CLOSED\n"); goto end; } else { char *p = buf + i - 1; while (i && (*p == '\n' || *p == '\r')) { p--; i--; } if (!s_ign_eof && i == 5 && HAS_PREFIX(buf, "CLOSE")) { ret = 1; BIO_printf(bio_err, "CONNECTION CLOSED\n"); goto end; } BUF_reverse((unsigned char *)buf, NULL, i); buf[i] = '\n'; BIO_write(io, buf, i + 1); for (;;) { i = BIO_flush(io); if (i > 0) break; if (!BIO_should_retry(io)) goto end; } } } end: /* make sure we reuse sessions */ do_ssl_shutdown(con); err: OPENSSL_free(buf); BIO_free(ssl_bio); BIO_free_all(io); return ret; } #define MAX_SESSION_ID_ATTEMPTS 10 static int generate_session_id(SSL *ssl, unsigned char *id, unsigned int *id_len) { unsigned int count = 0; unsigned int session_id_prefix_len = strlen(session_id_prefix); do { if (RAND_bytes(id, *id_len) <= 0) return 0; /* * Prefix the session_id with the required prefix. NB: If our prefix * is too long, clip it - but there will be worse effects anyway, eg. * the server could only possibly create 1 session ID (ie. the * prefix!) so all future session negotiations will fail due to * conflicts. */ memcpy(id, session_id_prefix, (session_id_prefix_len < *id_len) ? session_id_prefix_len : *id_len); } while (SSL_has_matching_session_id(ssl, id, *id_len) && (++count < MAX_SESSION_ID_ATTEMPTS)); if (count >= MAX_SESSION_ID_ATTEMPTS) return 0; return 1; } /* * By default s_server uses an in-memory cache which caches SSL_SESSION * structures without any serialization. This hides some bugs which only * become apparent in deployed servers. By implementing a basic external * session cache some issues can be debugged using s_server. */ typedef struct simple_ssl_session_st { unsigned char *id; unsigned int idlen; unsigned char *der; int derlen; struct simple_ssl_session_st *next; } simple_ssl_session; static simple_ssl_session *first = NULL; static int add_session(SSL *ssl, SSL_SESSION *session) { simple_ssl_session *sess = app_malloc(sizeof(*sess), "get session"); unsigned char *p; SSL_SESSION_get_id(session, &sess->idlen); sess->derlen = i2d_SSL_SESSION(session, NULL); if (sess->derlen < 0) { BIO_printf(bio_err, "Error encoding session\n"); OPENSSL_free(sess); return 0; } sess->id = OPENSSL_memdup(SSL_SESSION_get_id(session, NULL), sess->idlen); sess->der = app_malloc(sess->derlen, "get session buffer"); if (!sess->id) { BIO_printf(bio_err, "Out of memory adding to external cache\n"); OPENSSL_free(sess->id); OPENSSL_free(sess->der); OPENSSL_free(sess); return 0; } p = sess->der; /* Assume it still works. */ if (i2d_SSL_SESSION(session, &p) != sess->derlen) { BIO_printf(bio_err, "Unexpected session encoding length\n"); OPENSSL_free(sess->id); OPENSSL_free(sess->der); OPENSSL_free(sess); return 0; } sess->next = first; first = sess; BIO_printf(bio_err, "New session added to external cache\n"); return 0; } static SSL_SESSION *get_session(SSL *ssl, const unsigned char *id, int idlen, int *do_copy) { simple_ssl_session *sess; *do_copy = 0; for (sess = first; sess; sess = sess->next) { if (idlen == (int)sess->idlen && !memcmp(sess->id, id, idlen)) { const unsigned char *p = sess->der; BIO_printf(bio_err, "Lookup session: cache hit\n"); return d2i_SSL_SESSION_ex(NULL, &p, sess->derlen, app_get0_libctx(), app_get0_propq()); } } BIO_printf(bio_err, "Lookup session: cache miss\n"); return NULL; } static void del_session(SSL_CTX *sctx, SSL_SESSION *session) { simple_ssl_session *sess, *prev = NULL; const unsigned char *id; unsigned int idlen; id = SSL_SESSION_get_id(session, &idlen); for (sess = first; sess; sess = sess->next) { if (idlen == sess->idlen && !memcmp(sess->id, id, idlen)) { if (prev) prev->next = sess->next; else first = sess->next; OPENSSL_free(sess->id); OPENSSL_free(sess->der); OPENSSL_free(sess); return; } prev = sess; } } static void init_session_cache_ctx(SSL_CTX *sctx) { SSL_CTX_set_session_cache_mode(sctx, SSL_SESS_CACHE_NO_INTERNAL | SSL_SESS_CACHE_SERVER); SSL_CTX_sess_set_new_cb(sctx, add_session); SSL_CTX_sess_set_get_cb(sctx, get_session); SSL_CTX_sess_set_remove_cb(sctx, del_session); } static void free_sessions(void) { simple_ssl_session *sess, *tsess; for (sess = first; sess;) { OPENSSL_free(sess->id); OPENSSL_free(sess->der); tsess = sess; sess = sess->next; OPENSSL_free(tsess); } first = NULL; } #endif /* OPENSSL_NO_SOCK */
./openssl/apps/rand.c
/* * Copyright 1998-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 "apps.h" #include "progs.h" #include <ctype.h> #include <stdio.h> #include <string.h> #include <openssl/bio.h> #include <openssl/err.h> #include <openssl/rand.h> typedef enum OPTION_choice { OPT_COMMON, OPT_OUT, OPT_ENGINE, OPT_BASE64, OPT_HEX, OPT_R_ENUM, OPT_PROV_ENUM } OPTION_CHOICE; const OPTIONS rand_options[] = { {OPT_HELP_STR, 1, '-', "Usage: %s [options] num[K|M|G|T]\n"}, OPT_SECTION("General"), {"help", OPT_HELP, '-', "Display this summary"}, #ifndef OPENSSL_NO_ENGINE {"engine", OPT_ENGINE, 's', "Use engine, possibly a hardware device"}, #endif OPT_SECTION("Output"), {"out", OPT_OUT, '>', "Output file"}, {"base64", OPT_BASE64, '-', "Base64 encode output"}, {"hex", OPT_HEX, '-', "Hex encode output"}, OPT_R_OPTIONS, OPT_PROV_OPTIONS, OPT_PARAMETERS(), {"num", 0, 0, "Number of bytes to generate"}, {NULL} }; int rand_main(int argc, char **argv) { ENGINE *e = NULL; BIO *out = NULL; char *outfile = NULL, *prog; OPTION_CHOICE o; int format = FORMAT_BINARY, r, i, ret = 1; size_t buflen = (1 << 16); /* max rand chunk size is 2^16 bytes */ long num = -1; uint64_t scaled_num = 0; uint8_t *buf = NULL; prog = opt_init(argc, argv, rand_options); while ((o = opt_next()) != OPT_EOF) { switch (o) { case OPT_EOF: case OPT_ERR: opthelp: BIO_printf(bio_err, "%s: Use -help for summary.\n", prog); goto end; case OPT_HELP: opt_help(rand_options); ret = 0; goto end; case OPT_OUT: outfile = opt_arg(); break; case OPT_ENGINE: e = setup_engine(opt_arg(), 0); break; case OPT_R_CASES: if (!opt_rand(o)) goto end; break; case OPT_BASE64: format = FORMAT_BASE64; break; case OPT_HEX: format = FORMAT_TEXT; break; case OPT_PROV_CASES: if (!opt_provider(o)) goto end; break; } } /* Optional argument is number of bytes to generate. */ argc = opt_num_rest(); argv = opt_rest(); if (argc == 1) { int factoridx = 0; int shift = 0; /* * special case for requesting the max allowed * number of random bytes to be generated */ if (!strcmp(argv[0], "max")) { /* * 2^61 bytes is the limit of random output * per drbg instantiation */ scaled_num = UINT64_MAX >> 3; } else { /* * iterate over the value and check to see if there are * any non-numerical chars * A non digit suffix indicates we need to shift the * number of requested bytes by a factor of: * K = 1024^1 (1 << (10 * 1)) * M = 1024^2 (1 << (10 * 2)) * G = 1024^3 (1 << (10 * 3)) * T = 1024^4 (1 << (10 * 4)) * which can be achieved by bit-shifting the number */ while (argv[0][factoridx]) { if (!isdigit((int)(argv[0][factoridx]))) { switch(argv[0][factoridx]) { case 'K': shift = 10; break; case 'M': shift = 20; break; case 'G': shift = 30; break; case 'T': shift = 40; break; default: BIO_printf(bio_err, "Invalid size suffix %s\n", &argv[0][factoridx]); goto opthelp; } break; } factoridx++; } if (shift != 0 && strlen(&argv[0][factoridx]) != 1) { BIO_printf(bio_err, "Invalid size suffix %s\n", &argv[0][factoridx]); goto opthelp; } } /* Remove the suffix from the arg so that opt_long works */ if (shift != 0) argv[0][factoridx] = '\0'; if ((scaled_num == 0) && (!opt_long(argv[0], &num) || num <= 0)) goto opthelp; if (shift != 0) { /* check for overflow */ if ((UINT64_MAX >> shift) < (size_t)num) { BIO_printf(bio_err, "%lu bytes with suffix overflows\n", num); goto opthelp; } scaled_num = num << shift; if (scaled_num > (UINT64_MAX >> 3)) { BIO_printf(bio_err, "Request exceeds max allowed output\n"); goto opthelp; } } else { if (scaled_num == 0) scaled_num = num; } } else if (!opt_check_rest_arg(NULL)) { goto opthelp; } if (!app_RAND_load()) goto end; out = bio_open_default(outfile, 'w', format); if (out == NULL) goto end; if (format == FORMAT_BASE64) { BIO *b64 = BIO_new(BIO_f_base64()); if (b64 == NULL) goto end; out = BIO_push(b64, out); } buf = app_malloc(buflen, "buffer for output file"); while (scaled_num > 0) { int chunk; chunk = scaled_num > buflen ? (int)buflen : (int)scaled_num; r = RAND_bytes(buf, chunk); if (r <= 0) goto end; if (format != FORMAT_TEXT) { if (BIO_write(out, buf, chunk) != chunk) goto end; } else { for (i = 0; i < chunk; i++) if (BIO_printf(out, "%02x", buf[i]) != 2) goto end; } scaled_num -= chunk; } if (format == FORMAT_TEXT) BIO_puts(out, "\n"); if (BIO_flush(out) <= 0) goto end; ret = 0; end: if (ret != 0) ERR_print_errors(bio_err); OPENSSL_free(buf); release_engine(e); BIO_free_all(out); return ret; }
./openssl/apps/dhparam.c
/* * Copyright 1995-2023 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <openssl/opensslconf.h> #include <stdio.h> #include <stdlib.h> #include <time.h> #include <string.h> #include "apps.h" #include "progs.h" #include <openssl/bio.h> #include <openssl/err.h> #include <openssl/bn.h> #include <openssl/dsa.h> #include <openssl/dh.h> #include <openssl/x509.h> #include <openssl/pem.h> #include <openssl/core_names.h> #include <openssl/core_dispatch.h> #include <openssl/param_build.h> #include <openssl/encoder.h> #include <openssl/decoder.h> #define DEFBITS 2048 static EVP_PKEY *dsa_to_dh(EVP_PKEY *dh); static int verbose = 1; typedef enum OPTION_choice { OPT_COMMON, OPT_INFORM, OPT_OUTFORM, OPT_IN, OPT_OUT, OPT_ENGINE, OPT_CHECK, OPT_TEXT, OPT_NOOUT, OPT_DSAPARAM, OPT_2, OPT_3, OPT_5, OPT_VERBOSE, OPT_QUIET, OPT_R_ENUM, OPT_PROV_ENUM } OPTION_CHOICE; const OPTIONS dhparam_options[] = { {OPT_HELP_STR, 1, '-', "Usage: %s [options] [numbits]\n"}, OPT_SECTION("General"), {"help", OPT_HELP, '-', "Display this summary"}, {"check", OPT_CHECK, '-', "Check the DH parameters"}, #if !defined(OPENSSL_NO_DSA) || !defined(OPENSSL_NO_DEPRECATED_3_0) {"dsaparam", OPT_DSAPARAM, '-', "Read or generate DSA parameters, convert to DH"}, #endif #ifndef OPENSSL_NO_ENGINE {"engine", OPT_ENGINE, 's', "Use engine e, possibly a hardware device"}, #endif OPT_SECTION("Input"), {"in", OPT_IN, '<', "Input file"}, {"inform", OPT_INFORM, 'F', "Input format, DER or PEM"}, OPT_SECTION("Output"), {"out", OPT_OUT, '>', "Output file"}, {"outform", OPT_OUTFORM, 'F', "Output format, DER or PEM"}, {"text", OPT_TEXT, '-', "Print a text form of the DH parameters"}, {"noout", OPT_NOOUT, '-', "Don't output any DH parameters"}, {"2", OPT_2, '-', "Generate parameters using 2 as the generator value"}, {"3", OPT_3, '-', "Generate parameters using 3 as the generator value"}, {"5", OPT_5, '-', "Generate parameters using 5 as the generator value"}, {"verbose", OPT_VERBOSE, '-', "Verbose output"}, {"quiet", OPT_QUIET, '-', "Terse output"}, OPT_R_OPTIONS, OPT_PROV_OPTIONS, OPT_PARAMETERS(), {"numbits", 0, 0, "Number of bits if generating parameters (optional)"}, {NULL} }; int dhparam_main(int argc, char **argv) { BIO *in = NULL, *out = NULL; EVP_PKEY *pkey = NULL, *tmppkey = NULL; EVP_PKEY_CTX *ctx = NULL; char *infile = NULL, *outfile = NULL, *prog; ENGINE *e = NULL; int dsaparam = 0; int text = 0, ret = 1, num = 0, g = 0; int informat = FORMAT_PEM, outformat = FORMAT_PEM, check = 0, noout = 0; OPTION_CHOICE o; prog = opt_init(argc, argv, dhparam_options); while ((o = opt_next()) != OPT_EOF) { switch (o) { case OPT_EOF: case OPT_ERR: opthelp: BIO_printf(bio_err, "%s: Use -help for summary.\n", prog); goto end; case OPT_HELP: opt_help(dhparam_options); ret = 0; goto end; case OPT_INFORM: if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &informat)) goto opthelp; break; case OPT_OUTFORM: if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &outformat)) goto opthelp; break; case OPT_IN: infile = opt_arg(); break; case OPT_OUT: outfile = opt_arg(); break; case OPT_ENGINE: e = setup_engine(opt_arg(), 0); break; case OPT_CHECK: check = 1; break; case OPT_TEXT: text = 1; break; case OPT_DSAPARAM: dsaparam = 1; break; case OPT_2: g = 2; break; case OPT_3: g = 3; break; case OPT_5: g = 5; break; case OPT_NOOUT: noout = 1; break; case OPT_VERBOSE: verbose = 1; break; case OPT_QUIET: verbose = 0; break; case OPT_R_CASES: if (!opt_rand(o)) goto end; break; case OPT_PROV_CASES: if (!opt_provider(o)) goto end; break; } } /* One optional argument, bitsize to generate. */ argc = opt_num_rest(); argv = opt_rest(); if (argc == 1) { if (!opt_int(argv[0], &num) || num <= 0) goto opthelp; } else if (!opt_check_rest_arg(NULL)) { goto opthelp; } if (!app_RAND_load()) goto end; if (g && !num) num = DEFBITS; if (dsaparam && g) { BIO_printf(bio_err, "Error, generator may not be chosen for DSA parameters\n"); goto end; } out = bio_open_default(outfile, 'w', outformat); if (out == NULL) goto end; /* DH parameters */ if (num && !g) g = 2; if (num) { const char *alg = dsaparam ? "DSA" : "DH"; if (infile != NULL) { BIO_printf(bio_err, "Warning, input file %s ignored\n", infile); } ctx = EVP_PKEY_CTX_new_from_name(app_get0_libctx(), alg, app_get0_propq()); if (ctx == NULL) { BIO_printf(bio_err, "Error, %s param generation context allocation failed\n", alg); goto end; } EVP_PKEY_CTX_set_app_data(ctx, bio_err); if (verbose) { EVP_PKEY_CTX_set_cb(ctx, progress_cb); BIO_printf(bio_err, "Generating %s parameters, %d bit long %sprime\n", alg, num, dsaparam ? "" : "safe "); } if (EVP_PKEY_paramgen_init(ctx) <= 0) { BIO_printf(bio_err, "Error, unable to initialise %s parameters\n", alg); goto end; } if (dsaparam) { if (EVP_PKEY_CTX_set_dsa_paramgen_bits(ctx, num) <= 0) { BIO_printf(bio_err, "Error, unable to set DSA prime length\n"); goto end; } } else { if (EVP_PKEY_CTX_set_dh_paramgen_prime_len(ctx, num) <= 0) { BIO_printf(bio_err, "Error, unable to set DH prime length\n"); goto end; } if (EVP_PKEY_CTX_set_dh_paramgen_generator(ctx, g) <= 0) { BIO_printf(bio_err, "Error, unable to set generator\n"); goto end; } } tmppkey = app_paramgen(ctx, alg); if (tmppkey == NULL) goto end; EVP_PKEY_CTX_free(ctx); ctx = NULL; if (dsaparam) { pkey = dsa_to_dh(tmppkey); if (pkey == NULL) goto end; EVP_PKEY_free(tmppkey); } else { pkey = tmppkey; } tmppkey = NULL; } else { OSSL_DECODER_CTX *decoderctx = NULL; const char *keytype = "DH"; int done; in = bio_open_default(infile, 'r', informat); if (in == NULL) goto end; do { /* * We assume we're done unless we explicitly want to retry and set * this to 0 below. */ done = 1; /* * We set NULL for the keytype to allow any key type. We don't know * if we're going to get DH or DHX (or DSA in the event of dsaparam). * We check that we got one of those key types afterwards. */ decoderctx = OSSL_DECODER_CTX_new_for_pkey(&tmppkey, (informat == FORMAT_ASN1) ? "DER" : "PEM", NULL, (informat == FORMAT_ASN1) ? keytype : NULL, OSSL_KEYMGMT_SELECT_DOMAIN_PARAMETERS, NULL, NULL); if (decoderctx != NULL && !OSSL_DECODER_from_bio(decoderctx, in) && informat == FORMAT_ASN1 && strcmp(keytype, "DH") == 0) { /* * When reading DER we explicitly state the expected keytype * because, unlike PEM, there is no header to declare what * the contents of the DER file are. The decoders just try * and guess. Unfortunately with DHX key types they may guess * wrong and think we have a DSA keytype. Therefore, we try * both DH and DHX sequentially. */ keytype = "DHX"; /* * BIO_reset() returns 0 for success for file BIOs only!!! * This won't work for stdin (and never has done) */ if (BIO_reset(in) == 0) done = 0; } OSSL_DECODER_CTX_free(decoderctx); } while (!done); if (tmppkey == NULL) { BIO_printf(bio_err, "Error, unable to load parameters\n"); goto end; } if (dsaparam) { if (!EVP_PKEY_is_a(tmppkey, "DSA")) { BIO_printf(bio_err, "Error, unable to load DSA parameters\n"); goto end; } pkey = dsa_to_dh(tmppkey); if (pkey == NULL) goto end; } else { if (!EVP_PKEY_is_a(tmppkey, "DH") && !EVP_PKEY_is_a(tmppkey, "DHX")) { BIO_printf(bio_err, "Error, unable to load DH parameters\n"); goto end; } pkey = tmppkey; tmppkey = NULL; } } if (text) EVP_PKEY_print_params(out, pkey, 4, NULL); if (check) { ctx = EVP_PKEY_CTX_new_from_pkey(app_get0_libctx(), pkey, app_get0_propq()); if (ctx == NULL) { BIO_printf(bio_err, "Error, failed to check DH parameters\n"); goto end; } if (EVP_PKEY_param_check(ctx) <= 0) { BIO_printf(bio_err, "Error, invalid parameters generated\n"); goto end; } BIO_printf(bio_err, "DH parameters appear to be ok.\n"); } if (!noout) { OSSL_ENCODER_CTX *ectx = OSSL_ENCODER_CTX_new_for_pkey(pkey, OSSL_KEYMGMT_SELECT_DOMAIN_PARAMETERS, outformat == FORMAT_ASN1 ? "DER" : "PEM", NULL, NULL); if (ectx == NULL || !OSSL_ENCODER_to_bio(ectx, out)) { OSSL_ENCODER_CTX_free(ectx); BIO_printf(bio_err, "Error, unable to write DH parameters\n"); goto end; } OSSL_ENCODER_CTX_free(ectx); } ret = 0; end: if (ret != 0) ERR_print_errors(bio_err); BIO_free(in); BIO_free_all(out); EVP_PKEY_free(pkey); EVP_PKEY_free(tmppkey); EVP_PKEY_CTX_free(ctx); release_engine(e); return ret; } /* * Historically we had the low-level call DSA_dup_DH() to do this. * That is now deprecated with no replacement. Since we still need to do this * for backwards compatibility reasons, we do it "manually". */ static EVP_PKEY *dsa_to_dh(EVP_PKEY *dh) { OSSL_PARAM_BLD *tmpl = NULL; OSSL_PARAM *params = NULL; BIGNUM *bn_p = NULL, *bn_q = NULL, *bn_g = NULL; EVP_PKEY_CTX *ctx = NULL; EVP_PKEY *pkey = NULL; if (!EVP_PKEY_get_bn_param(dh, OSSL_PKEY_PARAM_FFC_P, &bn_p) || !EVP_PKEY_get_bn_param(dh, OSSL_PKEY_PARAM_FFC_Q, &bn_q) || !EVP_PKEY_get_bn_param(dh, OSSL_PKEY_PARAM_FFC_G, &bn_g)) { BIO_printf(bio_err, "Error, failed to set DH parameters\n"); goto err; } if ((tmpl = OSSL_PARAM_BLD_new()) == NULL || !OSSL_PARAM_BLD_push_BN(tmpl, OSSL_PKEY_PARAM_FFC_P, bn_p) || !OSSL_PARAM_BLD_push_BN(tmpl, OSSL_PKEY_PARAM_FFC_Q, bn_q) || !OSSL_PARAM_BLD_push_BN(tmpl, OSSL_PKEY_PARAM_FFC_G, bn_g) || (params = OSSL_PARAM_BLD_to_param(tmpl)) == NULL) { BIO_printf(bio_err, "Error, failed to set DH parameters\n"); goto err; } ctx = EVP_PKEY_CTX_new_from_name(app_get0_libctx(), "DHX", app_get0_propq()); if (ctx == NULL || EVP_PKEY_fromdata_init(ctx) <= 0 || EVP_PKEY_fromdata(ctx, &pkey, EVP_PKEY_KEY_PARAMETERS, params) <= 0) { BIO_printf(bio_err, "Error, failed to set DH parameters\n"); goto err; } err: EVP_PKEY_CTX_free(ctx); OSSL_PARAM_free(params); OSSL_PARAM_BLD_free(tmpl); BN_free(bn_p); BN_free(bn_q); BN_free(bn_g); return pkey; }
./openssl/apps/dsa.c
/* * Copyright 1995-2023 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <openssl/opensslconf.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> #include "apps.h" #include "progs.h" #include <openssl/bio.h> #include <openssl/err.h> #include <openssl/dsa.h> #include <openssl/evp.h> #include <openssl/x509.h> #include <openssl/pem.h> #include <openssl/bn.h> #include <openssl/encoder.h> #include <openssl/core_names.h> #include <openssl/core_dispatch.h> #ifndef OPENSSL_NO_RC4 # define DEFAULT_PVK_ENCR_STRENGTH 2 #else # define DEFAULT_PVK_ENCR_STRENGTH 0 #endif typedef enum OPTION_choice { OPT_COMMON, OPT_INFORM, OPT_OUTFORM, OPT_IN, OPT_OUT, OPT_ENGINE, /* Do not change the order here; see case statements below */ OPT_PVK_NONE, OPT_PVK_WEAK, OPT_PVK_STRONG, OPT_NOOUT, OPT_TEXT, OPT_MODULUS, OPT_PUBIN, OPT_PUBOUT, OPT_CIPHER, OPT_PASSIN, OPT_PASSOUT, OPT_PROV_ENUM } OPTION_CHOICE; const OPTIONS dsa_options[] = { OPT_SECTION("General"), {"help", OPT_HELP, '-', "Display this summary"}, {"", OPT_CIPHER, '-', "Any supported cipher"}, #ifndef OPENSSL_NO_RC4 {"pvk-strong", OPT_PVK_STRONG, '-', "Enable 'Strong' PVK encoding level (default)"}, {"pvk-weak", OPT_PVK_WEAK, '-', "Enable 'Weak' PVK encoding level"}, {"pvk-none", OPT_PVK_NONE, '-', "Don't enforce PVK encoding"}, #endif #ifndef OPENSSL_NO_ENGINE {"engine", OPT_ENGINE, 's', "Use engine e, possibly a hardware device"}, #endif OPT_SECTION("Input"), {"in", OPT_IN, 's', "Input key"}, {"inform", OPT_INFORM, 'f', "Input format (DER/PEM/PVK); has no effect"}, {"pubin", OPT_PUBIN, '-', "Expect a public key in input file"}, {"passin", OPT_PASSIN, 's', "Input file pass phrase source"}, OPT_SECTION("Output"), {"out", OPT_OUT, '>', "Output file"}, {"outform", OPT_OUTFORM, 'f', "Output format, DER PEM PVK"}, {"noout", OPT_NOOUT, '-', "Don't print key out"}, {"text", OPT_TEXT, '-', "Print the key in text"}, {"modulus", OPT_MODULUS, '-', "Print the DSA public value"}, {"pubout", OPT_PUBOUT, '-', "Output public key, not private"}, {"passout", OPT_PASSOUT, 's', "Output file pass phrase source"}, OPT_PROV_OPTIONS, {NULL} }; int dsa_main(int argc, char **argv) { BIO *out = NULL; ENGINE *e = NULL; EVP_PKEY *pkey = NULL; EVP_CIPHER *enc = NULL; char *infile = NULL, *outfile = NULL, *prog; char *passin = NULL, *passout = NULL, *passinarg = NULL, *passoutarg = NULL; OPTION_CHOICE o; int informat = FORMAT_UNDEF, outformat = FORMAT_PEM, text = 0, noout = 0; int modulus = 0, pubin = 0, pubout = 0, ret = 1; int pvk_encr = DEFAULT_PVK_ENCR_STRENGTH; int private = 0; const char *output_type = NULL, *ciphername = NULL; const char *output_structure = NULL; int selection = 0; OSSL_ENCODER_CTX *ectx = NULL; opt_set_unknown_name("cipher"); prog = opt_init(argc, argv, dsa_options); while ((o = opt_next()) != OPT_EOF) { switch (o) { case OPT_EOF: case OPT_ERR: opthelp: ret = 0; BIO_printf(bio_err, "%s: Use -help for summary.\n", prog); goto end; case OPT_HELP: opt_help(dsa_options); ret = 0; goto end; case OPT_INFORM: if (!opt_format(opt_arg(), OPT_FMT_ANY, &informat)) goto opthelp; break; case OPT_IN: infile = opt_arg(); break; case OPT_OUTFORM: if (!opt_format(opt_arg(), OPT_FMT_ANY, &outformat)) goto opthelp; break; case OPT_OUT: outfile = opt_arg(); break; case OPT_ENGINE: e = setup_engine(opt_arg(), 0); break; case OPT_PASSIN: passinarg = opt_arg(); break; case OPT_PASSOUT: passoutarg = opt_arg(); break; case OPT_PVK_STRONG: /* pvk_encr:= 2 */ case OPT_PVK_WEAK: /* pvk_encr:= 1 */ case OPT_PVK_NONE: /* pvk_encr:= 0 */ #ifndef OPENSSL_NO_RC4 pvk_encr = (o - OPT_PVK_NONE); #endif break; case OPT_NOOUT: noout = 1; break; case OPT_TEXT: text = 1; break; case OPT_MODULUS: modulus = 1; break; case OPT_PUBIN: pubin = 1; break; case OPT_PUBOUT: pubout = 1; break; case OPT_CIPHER: ciphername = opt_unknown(); break; case OPT_PROV_CASES: if (!opt_provider(o)) goto end; break; } } /* No extra args. */ if (!opt_check_rest_arg(NULL)) goto opthelp; if (!opt_cipher(ciphername, &enc)) goto end; private = !pubin && (!pubout || text); if (!app_passwd(passinarg, passoutarg, &passin, &passout)) { BIO_printf(bio_err, "Error getting passwords\n"); goto end; } BIO_printf(bio_err, "read DSA key\n"); if (pubin) pkey = load_pubkey(infile, informat, 1, passin, e, "public key"); else pkey = load_key(infile, informat, 1, passin, e, "private key"); if (pkey == NULL) { BIO_printf(bio_err, "unable to load Key\n"); ERR_print_errors(bio_err); goto end; } if (!EVP_PKEY_is_a(pkey, "DSA")) { BIO_printf(bio_err, "Not a DSA key\n"); goto end; } out = bio_open_owner(outfile, outformat, private); if (out == NULL) goto end; if (text) { assert(pubin || private); if ((pubin && EVP_PKEY_print_public(out, pkey, 0, NULL) <= 0) || (!pubin && EVP_PKEY_print_private(out, pkey, 0, NULL) <= 0)) { perror(outfile); ERR_print_errors(bio_err); goto end; } } if (modulus) { BIGNUM *pub_key = NULL; if (!EVP_PKEY_get_bn_param(pkey, "pub", &pub_key)) { ERR_print_errors(bio_err); goto end; } BIO_printf(out, "Public Key="); BN_print(out, pub_key); BIO_printf(out, "\n"); BN_free(pub_key); } if (noout) { ret = 0; goto end; } BIO_printf(bio_err, "writing DSA key\n"); if (outformat == FORMAT_ASN1) { output_type = "DER"; } else if (outformat == FORMAT_PEM) { output_type = "PEM"; } else if (outformat == FORMAT_MSBLOB) { output_type = "MSBLOB"; } else if (outformat == FORMAT_PVK) { if (pubin) { BIO_printf(bio_err, "PVK form impossible with public key input\n"); goto end; } output_type = "PVK"; } else { BIO_printf(bio_err, "bad output format specified for outfile\n"); goto end; } if (outformat == FORMAT_ASN1 || outformat == FORMAT_PEM) { if (pubout || pubin) output_structure = "SubjectPublicKeyInfo"; else output_structure = "type-specific"; } /* Select what you want in the output */ if (pubout || pubin) { selection = OSSL_KEYMGMT_SELECT_PUBLIC_KEY; } else { assert(private); selection = (OSSL_KEYMGMT_SELECT_KEYPAIR | OSSL_KEYMGMT_SELECT_ALL_PARAMETERS); } /* Perform the encoding */ ectx = OSSL_ENCODER_CTX_new_for_pkey(pkey, selection, output_type, output_structure, NULL); if (OSSL_ENCODER_CTX_get_num_encoders(ectx) == 0) { BIO_printf(bio_err, "%s format not supported\n", output_type); goto end; } /* Passphrase setup */ if (enc != NULL) OSSL_ENCODER_CTX_set_cipher(ectx, EVP_CIPHER_get0_name(enc), NULL); /* Default passphrase prompter */ if (enc != NULL || outformat == FORMAT_PVK) { OSSL_ENCODER_CTX_set_passphrase_ui(ectx, get_ui_method(), NULL); if (passout != NULL) /* When passout given, override the passphrase prompter */ OSSL_ENCODER_CTX_set_passphrase(ectx, (const unsigned char *)passout, strlen(passout)); } /* PVK requires a bit more */ if (outformat == FORMAT_PVK) { OSSL_PARAM params[2] = { OSSL_PARAM_END, OSSL_PARAM_END }; params[0] = OSSL_PARAM_construct_int("encrypt-level", &pvk_encr); if (!OSSL_ENCODER_CTX_set_params(ectx, params)) { BIO_printf(bio_err, "invalid PVK encryption level\n"); goto end; } } if (!OSSL_ENCODER_to_bio(ectx, out)) { BIO_printf(bio_err, "unable to write key\n"); goto end; } ret = 0; end: if (ret != 0) ERR_print_errors(bio_err); OSSL_ENCODER_CTX_free(ectx); BIO_free_all(out); EVP_PKEY_free(pkey); EVP_CIPHER_free(enc); release_engine(e); OPENSSL_free(passin); OPENSSL_free(passout); return ret; }
./openssl/apps/ec.c
/* * Copyright 2002-2023 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <string.h> #include <openssl/opensslconf.h> #include <openssl/evp.h> #include <openssl/encoder.h> #include <openssl/decoder.h> #include <openssl/core_names.h> #include <openssl/core_dispatch.h> #include <openssl/params.h> #include <openssl/err.h> #include "apps.h" #include "progs.h" #include "ec_common.h" typedef enum OPTION_choice { OPT_COMMON, OPT_INFORM, OPT_OUTFORM, OPT_ENGINE, OPT_IN, OPT_OUT, OPT_NOOUT, OPT_TEXT, OPT_PARAM_OUT, OPT_PUBIN, OPT_PUBOUT, OPT_PASSIN, OPT_PASSOUT, OPT_PARAM_ENC, OPT_CONV_FORM, OPT_CIPHER, OPT_NO_PUBLIC, OPT_CHECK, OPT_PROV_ENUM } OPTION_CHOICE; const OPTIONS ec_options[] = { OPT_SECTION("General"), {"help", OPT_HELP, '-', "Display this summary"}, #ifndef OPENSSL_NO_ENGINE {"engine", OPT_ENGINE, 's', "Use engine, possibly a hardware device"}, #endif OPT_SECTION("Input"), {"in", OPT_IN, 's', "Input file"}, {"inform", OPT_INFORM, 'f', "Input format (DER/PEM/P12/ENGINE)"}, {"pubin", OPT_PUBIN, '-', "Expect a public key in input file"}, {"passin", OPT_PASSIN, 's', "Input file pass phrase source"}, {"check", OPT_CHECK, '-', "check key consistency"}, {"", OPT_CIPHER, '-', "Any supported cipher"}, {"param_enc", OPT_PARAM_ENC, 's', "Specifies the way the ec parameters are encoded"}, {"conv_form", OPT_CONV_FORM, 's', "Specifies the point conversion form "}, OPT_SECTION("Output"), {"out", OPT_OUT, '>', "Output file"}, {"outform", OPT_OUTFORM, 'F', "Output format - DER or PEM"}, {"noout", OPT_NOOUT, '-', "Don't print key out"}, {"text", OPT_TEXT, '-', "Print the key"}, {"param_out", OPT_PARAM_OUT, '-', "Print the elliptic curve parameters"}, {"pubout", OPT_PUBOUT, '-', "Output public key, not private"}, {"no_public", OPT_NO_PUBLIC, '-', "exclude public key from private key"}, {"passout", OPT_PASSOUT, 's', "Output file pass phrase source"}, OPT_PROV_OPTIONS, {NULL} }; int ec_main(int argc, char **argv) { OSSL_ENCODER_CTX *ectx = NULL; OSSL_DECODER_CTX *dctx = NULL; EVP_PKEY_CTX *pctx = NULL; EVP_PKEY *eckey = NULL; BIO *out = NULL; ENGINE *e = NULL; EVP_CIPHER *enc = NULL; char *infile = NULL, *outfile = NULL, *ciphername = NULL, *prog; char *passin = NULL, *passout = NULL, *passinarg = NULL, *passoutarg = NULL; OPTION_CHOICE o; int informat = FORMAT_UNDEF, outformat = FORMAT_PEM, text = 0, noout = 0; int pubin = 0, pubout = 0, param_out = 0, ret = 1, private = 0; int check = 0; char *asn1_encoding = NULL; char *point_format = NULL; int no_public = 0; opt_set_unknown_name("cipher"); prog = opt_init(argc, argv, ec_options); while ((o = opt_next()) != OPT_EOF) { switch (o) { case OPT_EOF: case OPT_ERR: opthelp: BIO_printf(bio_err, "%s: Use -help for summary.\n", prog); goto end; case OPT_HELP: opt_help(ec_options); ret = 0; goto end; case OPT_INFORM: if (!opt_format(opt_arg(), OPT_FMT_ANY, &informat)) goto opthelp; break; case OPT_IN: infile = opt_arg(); break; case OPT_OUTFORM: if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &outformat)) goto opthelp; break; case OPT_OUT: outfile = opt_arg(); break; case OPT_NOOUT: noout = 1; break; case OPT_TEXT: text = 1; break; case OPT_PARAM_OUT: param_out = 1; break; case OPT_PUBIN: pubin = 1; break; case OPT_PUBOUT: pubout = 1; break; case OPT_PASSIN: passinarg = opt_arg(); break; case OPT_PASSOUT: passoutarg = opt_arg(); break; case OPT_ENGINE: e = setup_engine(opt_arg(), 0); break; case OPT_CIPHER: ciphername = opt_unknown(); break; case OPT_CONV_FORM: point_format = opt_arg(); if (!opt_string(point_format, point_format_options)) goto opthelp; break; case OPT_PARAM_ENC: asn1_encoding = opt_arg(); if (!opt_string(asn1_encoding, asn1_encoding_options)) goto opthelp; break; case OPT_NO_PUBLIC: no_public = 1; break; case OPT_CHECK: check = 1; break; case OPT_PROV_CASES: if (!opt_provider(o)) goto end; break; } } /* No extra arguments. */ if (!opt_check_rest_arg(NULL)) goto opthelp; if (!opt_cipher(ciphername, &enc)) goto opthelp; private = !pubin && (text || (!param_out && !pubout)); if (!app_passwd(passinarg, passoutarg, &passin, &passout)) { BIO_printf(bio_err, "Error getting passwords\n"); goto end; } BIO_printf(bio_err, "read EC key\n"); if (pubin) eckey = load_pubkey(infile, informat, 1, passin, e, "public key"); else eckey = load_key(infile, informat, 1, passin, e, "private key"); if (eckey == NULL) { BIO_printf(bio_err, "unable to load Key\n"); goto end; } out = bio_open_owner(outfile, outformat, private); if (out == NULL) goto end; if (point_format && !EVP_PKEY_set_utf8_string_param( eckey, OSSL_PKEY_PARAM_EC_POINT_CONVERSION_FORMAT, point_format)) { BIO_printf(bio_err, "unable to set point conversion format\n"); goto end; } if (asn1_encoding != NULL && !EVP_PKEY_set_utf8_string_param( eckey, OSSL_PKEY_PARAM_EC_ENCODING, asn1_encoding)) { BIO_printf(bio_err, "unable to set asn1 encoding format\n"); goto end; } if (no_public) { if (!EVP_PKEY_set_int_param(eckey, OSSL_PKEY_PARAM_EC_INCLUDE_PUBLIC, 0)) { BIO_printf(bio_err, "unable to disable public key encoding\n"); goto end; } } else { if (!EVP_PKEY_set_int_param(eckey, OSSL_PKEY_PARAM_EC_INCLUDE_PUBLIC, 1)) { BIO_printf(bio_err, "unable to enable public key encoding\n"); goto end; } } if (text) { assert(pubin || private); if ((pubin && EVP_PKEY_print_public(out, eckey, 0, NULL) <= 0) || (!pubin && EVP_PKEY_print_private(out, eckey, 0, NULL) <= 0)) { BIO_printf(bio_err, "unable to print EC key\n"); goto end; } } if (check) { pctx = EVP_PKEY_CTX_new_from_pkey(NULL, eckey, NULL); if (pctx == NULL) { BIO_printf(bio_err, "unable to check EC key\n"); goto end; } if (EVP_PKEY_check(pctx) <= 0) BIO_printf(bio_err, "EC Key Invalid!\n"); else BIO_printf(bio_err, "EC Key valid.\n"); ERR_print_errors(bio_err); } if (!noout) { int selection; const char *output_type = outformat == FORMAT_ASN1 ? "DER" : "PEM"; const char *output_structure = "type-specific"; BIO_printf(bio_err, "writing EC key\n"); if (param_out) { selection = OSSL_KEYMGMT_SELECT_DOMAIN_PARAMETERS; } else if (pubin || pubout) { selection = OSSL_KEYMGMT_SELECT_DOMAIN_PARAMETERS | OSSL_KEYMGMT_SELECT_PUBLIC_KEY; output_structure = "SubjectPublicKeyInfo"; } else { selection = OSSL_KEYMGMT_SELECT_ALL; assert(private); } ectx = OSSL_ENCODER_CTX_new_for_pkey(eckey, selection, output_type, output_structure, NULL); if (enc != NULL) { OSSL_ENCODER_CTX_set_cipher(ectx, EVP_CIPHER_get0_name(enc), NULL); /* Default passphrase prompter */ OSSL_ENCODER_CTX_set_passphrase_ui(ectx, get_ui_method(), NULL); if (passout != NULL) /* When passout given, override the passphrase prompter */ OSSL_ENCODER_CTX_set_passphrase(ectx, (const unsigned char *)passout, strlen(passout)); } if (!OSSL_ENCODER_to_bio(ectx, out)) { BIO_printf(bio_err, "unable to write EC key\n"); goto end; } } ret = 0; end: if (ret != 0) ERR_print_errors(bio_err); BIO_free_all(out); EVP_PKEY_free(eckey); EVP_CIPHER_free(enc); OSSL_ENCODER_CTX_free(ectx); OSSL_DECODER_CTX_free(dctx); EVP_PKEY_CTX_free(pctx); release_engine(e); if (passin != NULL) OPENSSL_clear_free(passin, strlen(passin)); if (passout != NULL) OPENSSL_clear_free(passout, strlen(passout)); return ret; }
./openssl/apps/srp.c
/* * Copyright 2004-2021 The OpenSSL Project Authors. All Rights Reserved. * Copyright (c) 2004, EdelKey Project. 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 * * Originally written by Christophe Renou and Peter Sylvester, * for the EdelKey project. */ /* SRP is deprecated, so we're going to have to use some deprecated APIs */ #define OPENSSL_SUPPRESS_DEPRECATED #include <openssl/opensslconf.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <openssl/conf.h> #include <openssl/bio.h> #include <openssl/err.h> #include <openssl/txt_db.h> #include <openssl/buffer.h> #include <openssl/srp.h> #include "apps.h" #include "progs.h" #define BASE_SECTION "srp" #define CONFIG_FILE "openssl.cnf" #define ENV_DATABASE "srpvfile" #define ENV_DEFAULT_SRP "default_srp" static int get_index(CA_DB *db, char *id, char type) { char **pp; int i; if (id == NULL) return -1; if (type == DB_SRP_INDEX) { for (i = 0; i < sk_OPENSSL_PSTRING_num(db->db->data); i++) { pp = sk_OPENSSL_PSTRING_value(db->db->data, i); if (pp[DB_srptype][0] == DB_SRP_INDEX && strcmp(id, pp[DB_srpid]) == 0) return i; } } else { for (i = 0; i < sk_OPENSSL_PSTRING_num(db->db->data); i++) { pp = sk_OPENSSL_PSTRING_value(db->db->data, i); if (pp[DB_srptype][0] != DB_SRP_INDEX && strcmp(id, pp[DB_srpid]) == 0) return i; } } return -1; } static void print_entry(CA_DB *db, int indx, int verbose, char *s) { if (indx >= 0 && verbose) { int j; char **pp = sk_OPENSSL_PSTRING_value(db->db->data, indx); BIO_printf(bio_err, "%s \"%s\"\n", s, pp[DB_srpid]); for (j = 0; j < DB_NUMBER; j++) { BIO_printf(bio_err, " %d = \"%s\"\n", j, pp[j]); } } } static void print_index(CA_DB *db, int indexindex, int verbose) { print_entry(db, indexindex, verbose, "g N entry"); } static void print_user(CA_DB *db, int userindex, int verbose) { if (verbose > 0) { char **pp = sk_OPENSSL_PSTRING_value(db->db->data, userindex); if (pp[DB_srptype][0] != 'I') { print_entry(db, userindex, verbose, "User entry"); print_entry(db, get_index(db, pp[DB_srpgN], 'I'), verbose, "g N entry"); } } } static int update_index(CA_DB *db, char **row) { char **irow; int i; irow = app_malloc(sizeof(*irow) * (DB_NUMBER + 1), "row pointers"); for (i = 0; i < DB_NUMBER; i++) irow[i] = row[i]; irow[DB_NUMBER] = NULL; if (!TXT_DB_insert(db->db, irow)) { BIO_printf(bio_err, "failed to update srpvfile\n"); BIO_printf(bio_err, "TXT_DB error number %ld\n", db->db->error); OPENSSL_free(irow); return 0; } return 1; } static char *lookup_conf(const CONF *conf, const char *section, const char *tag) { char *entry = NCONF_get_string(conf, section, tag); if (entry == NULL) BIO_printf(bio_err, "variable lookup failed for %s::%s\n", section, tag); return entry; } static char *srp_verify_user(const char *user, const char *srp_verifier, char *srp_usersalt, const char *g, const char *N, const char *passin, int verbose) { char password[1025]; PW_CB_DATA cb_tmp; char *verifier = NULL; char *gNid = NULL; int len; cb_tmp.prompt_info = user; cb_tmp.password = passin; len = password_callback(password, sizeof(password)-1, 0, &cb_tmp); if (len > 0) { password[len] = 0; if (verbose) BIO_printf(bio_err, "Validating\n user=\"%s\"\n srp_verifier=\"%s\"\n srp_usersalt=\"%s\"\n g=\"%s\"\n N=\"%s\"\n", user, srp_verifier, srp_usersalt, g, N); if (verbose > 1) BIO_printf(bio_err, "Pass %s\n", password); OPENSSL_assert(srp_usersalt != NULL); if ((gNid = SRP_create_verifier(user, password, &srp_usersalt, &verifier, N, g)) == NULL) { BIO_printf(bio_err, "Internal error validating SRP verifier\n"); } else { if (strcmp(verifier, srp_verifier)) gNid = NULL; OPENSSL_free(verifier); } OPENSSL_cleanse(password, len); } return gNid; } static char *srp_create_user(char *user, char **srp_verifier, char **srp_usersalt, char *g, char *N, char *passout, int verbose) { char password[1025]; PW_CB_DATA cb_tmp; char *gNid = NULL; char *salt = NULL; int len; cb_tmp.prompt_info = user; cb_tmp.password = passout; len = password_callback(password, sizeof(password)-1, 1, &cb_tmp); if (len > 0) { password[len] = 0; if (verbose) BIO_printf(bio_err, "Creating\n user=\"%s\"\n g=\"%s\"\n N=\"%s\"\n", user, g, N); if ((gNid = SRP_create_verifier(user, password, &salt, srp_verifier, N, g)) == NULL) { BIO_printf(bio_err, "Internal error creating SRP verifier\n"); } else { *srp_usersalt = salt; } OPENSSL_cleanse(password, len); if (verbose > 1) BIO_printf(bio_err, "gNid=%s salt =\"%s\"\n verifier =\"%s\"\n", gNid, salt, *srp_verifier); } return gNid; } typedef enum OPTION_choice { OPT_COMMON, OPT_VERBOSE, OPT_CONFIG, OPT_NAME, OPT_SRPVFILE, OPT_ADD, OPT_DELETE, OPT_MODIFY, OPT_LIST, OPT_GN, OPT_USERINFO, OPT_PASSIN, OPT_PASSOUT, OPT_ENGINE, OPT_R_ENUM, OPT_PROV_ENUM } OPTION_CHOICE; const OPTIONS srp_options[] = { {OPT_HELP_STR, 1, '-', "Usage: %s [options] [user...]\n"}, OPT_SECTION("General"), {"help", OPT_HELP, '-', "Display this summary"}, {"verbose", OPT_VERBOSE, '-', "Talk a lot while doing things"}, {"config", OPT_CONFIG, '<', "A config file"}, {"name", OPT_NAME, 's', "The particular srp definition to use"}, #ifndef OPENSSL_NO_ENGINE {"engine", OPT_ENGINE, 's', "Use engine, possibly a hardware device"}, #endif OPT_SECTION("Action"), {"add", OPT_ADD, '-', "Add a user and SRP verifier"}, {"modify", OPT_MODIFY, '-', "Modify the SRP verifier of an existing user"}, {"delete", OPT_DELETE, '-', "Delete user from verifier file"}, {"list", OPT_LIST, '-', "List users"}, OPT_SECTION("Configuration"), {"srpvfile", OPT_SRPVFILE, '<', "The srp verifier file name"}, {"gn", OPT_GN, 's', "Set g and N values to be used for new verifier"}, {"userinfo", OPT_USERINFO, 's', "Additional info to be set for user"}, {"passin", OPT_PASSIN, 's', "Input file pass phrase source"}, {"passout", OPT_PASSOUT, 's', "Output file pass phrase source"}, OPT_R_OPTIONS, OPT_PROV_OPTIONS, OPT_PARAMETERS(), {"user", 0, 0, "Username(s) to process (optional)"}, {NULL} }; int srp_main(int argc, char **argv) { ENGINE *e = NULL; CA_DB *db = NULL; CONF *conf = NULL; int gNindex = -1, maxgN = -1, ret = 1, errors = 0, verbose = 0, i; int doupdatedb = 0, mode = OPT_ERR; char *user = NULL, *passinarg = NULL, *passoutarg = NULL; char *passin = NULL, *passout = NULL, *gN = NULL, *userinfo = NULL; char *section = NULL; char **gNrow = NULL, *configfile = NULL; char *srpvfile = NULL, **pp, *prog; OPTION_CHOICE o; prog = opt_init(argc, argv, srp_options); while ((o = opt_next()) != OPT_EOF) { switch (o) { case OPT_EOF: case OPT_ERR: opthelp: BIO_printf(bio_err, "%s: Use -help for summary.\n", prog); goto end; case OPT_HELP: opt_help(srp_options); ret = 0; goto end; case OPT_VERBOSE: verbose++; break; case OPT_CONFIG: configfile = opt_arg(); break; case OPT_NAME: section = opt_arg(); break; case OPT_SRPVFILE: srpvfile = opt_arg(); break; case OPT_ADD: case OPT_DELETE: case OPT_MODIFY: case OPT_LIST: if (mode != OPT_ERR) { BIO_printf(bio_err, "%s: Only one of -add/-delete/-modify/-list\n", prog); goto opthelp; } mode = o; break; case OPT_GN: gN = opt_arg(); break; case OPT_USERINFO: userinfo = opt_arg(); break; case OPT_PASSIN: passinarg = opt_arg(); break; case OPT_PASSOUT: passoutarg = opt_arg(); break; case OPT_ENGINE: e = setup_engine(opt_arg(), 0); break; case OPT_R_CASES: if (!opt_rand(o)) goto end; break; case OPT_PROV_CASES: if (!opt_provider(o)) goto end; break; } } /* Optional parameters are usernames. */ argc = opt_num_rest(); argv = opt_rest(); if (!app_RAND_load()) goto end; if (srpvfile != NULL && configfile != NULL) { BIO_printf(bio_err, "-srpvfile and -configfile cannot be specified together.\n"); goto end; } if (mode == OPT_ERR) { BIO_printf(bio_err, "Exactly one of the options -add, -delete, -modify -list must be specified.\n"); goto opthelp; } if (mode == OPT_DELETE || mode == OPT_MODIFY || mode == OPT_ADD) { if (argc == 0) { BIO_printf(bio_err, "Need at least one user.\n"); goto opthelp; } user = *argv++; } if ((passinarg != NULL || passoutarg != NULL) && argc != 1) { BIO_printf(bio_err, "-passin, -passout arguments only valid with one user.\n"); goto opthelp; } if (!app_passwd(passinarg, passoutarg, &passin, &passout)) { BIO_printf(bio_err, "Error getting passwords\n"); goto end; } if (srpvfile == NULL) { if (configfile == NULL) configfile = default_config_file; conf = app_load_config_verbose(configfile, verbose); if (conf == NULL) goto end; if (configfile != default_config_file && !app_load_modules(conf)) goto end; /* Lets get the config section we are using */ if (section == NULL) { if (verbose) BIO_printf(bio_err, "trying to read " ENV_DEFAULT_SRP " in " BASE_SECTION "\n"); section = lookup_conf(conf, BASE_SECTION, ENV_DEFAULT_SRP); if (section == NULL) goto end; } app_RAND_load_conf(conf, BASE_SECTION); if (verbose) BIO_printf(bio_err, "trying to read " ENV_DATABASE " in section \"%s\"\n", section); srpvfile = lookup_conf(conf, section, ENV_DATABASE); if (srpvfile == NULL) goto end; } if (verbose) BIO_printf(bio_err, "Trying to read SRP verifier file \"%s\"\n", srpvfile); db = load_index(srpvfile, NULL); if (db == NULL) { BIO_printf(bio_err, "Problem with index file: %s (could not load/parse file)\n", srpvfile); goto end; } /* Lets check some fields */ for (i = 0; i < sk_OPENSSL_PSTRING_num(db->db->data); i++) { pp = sk_OPENSSL_PSTRING_value(db->db->data, i); if (pp[DB_srptype][0] == DB_SRP_INDEX) { maxgN = i; if ((gNindex < 0) && (gN != NULL) && strcmp(gN, pp[DB_srpid]) == 0) gNindex = i; print_index(db, i, verbose > 1); } } if (verbose) BIO_printf(bio_err, "Database initialised\n"); if (gNindex >= 0) { gNrow = sk_OPENSSL_PSTRING_value(db->db->data, gNindex); print_entry(db, gNindex, verbose > 1, "Default g and N"); } else if (maxgN > 0 && !SRP_get_default_gN(gN)) { BIO_printf(bio_err, "No g and N value for index \"%s\"\n", gN); goto end; } else { if (verbose) BIO_printf(bio_err, "Database has no g N information.\n"); gNrow = NULL; } if (verbose > 1) BIO_printf(bio_err, "Starting user processing\n"); while (mode == OPT_LIST || user != NULL) { int userindex = -1; if (user != NULL && verbose > 1) BIO_printf(bio_err, "Processing user \"%s\"\n", user); if ((userindex = get_index(db, user, 'U')) >= 0) print_user(db, userindex, (verbose > 0) || mode == OPT_LIST); if (mode == OPT_LIST) { if (user == NULL) { BIO_printf(bio_err, "List all users\n"); for (i = 0; i < sk_OPENSSL_PSTRING_num(db->db->data); i++) print_user(db, i, 1); } else if (userindex < 0) { BIO_printf(bio_err, "user \"%s\" does not exist, ignored. t\n", user); errors++; } } else if (mode == OPT_ADD) { if (userindex >= 0) { /* reactivation of a new user */ char **row = sk_OPENSSL_PSTRING_value(db->db->data, userindex); BIO_printf(bio_err, "user \"%s\" reactivated.\n", user); row[DB_srptype][0] = 'V'; doupdatedb = 1; } else { char *row[DB_NUMBER]; char *gNid; row[DB_srpverifier] = NULL; row[DB_srpsalt] = NULL; row[DB_srpinfo] = NULL; if (! (gNid = srp_create_user(user, &(row[DB_srpverifier]), &(row[DB_srpsalt]), gNrow ? gNrow[DB_srpsalt] : gN, gNrow ? gNrow[DB_srpverifier] : NULL, passout, verbose))) { BIO_printf(bio_err, "Cannot create srp verifier for user \"%s\", operation abandoned .\n", user); errors++; goto end; } row[DB_srpid] = OPENSSL_strdup(user); row[DB_srptype] = OPENSSL_strdup("v"); row[DB_srpgN] = OPENSSL_strdup(gNid); if ((row[DB_srpid] == NULL) || (row[DB_srpgN] == NULL) || (row[DB_srptype] == NULL) || (row[DB_srpverifier] == NULL) || (row[DB_srpsalt] == NULL) || (userinfo && ((row[DB_srpinfo] = OPENSSL_strdup(userinfo)) == NULL)) || !update_index(db, row)) { OPENSSL_free(row[DB_srpid]); OPENSSL_free(row[DB_srpgN]); OPENSSL_free(row[DB_srpinfo]); OPENSSL_free(row[DB_srptype]); OPENSSL_free(row[DB_srpverifier]); OPENSSL_free(row[DB_srpsalt]); goto end; } doupdatedb = 1; } } else if (mode == OPT_MODIFY) { if (userindex < 0) { BIO_printf(bio_err, "user \"%s\" does not exist, operation ignored.\n", user); errors++; } else { char **row = sk_OPENSSL_PSTRING_value(db->db->data, userindex); char type = row[DB_srptype][0]; if (type == 'v') { BIO_printf(bio_err, "user \"%s\" already updated, operation ignored.\n", user); errors++; } else { char *gNid; if (row[DB_srptype][0] == 'V') { int user_gN; char **irow = NULL; if (verbose) BIO_printf(bio_err, "Verifying password for user \"%s\"\n", user); if ((user_gN = get_index(db, row[DB_srpgN], DB_SRP_INDEX)) >= 0) irow = sk_OPENSSL_PSTRING_value(db->db->data, userindex); if (!srp_verify_user (user, row[DB_srpverifier], row[DB_srpsalt], irow ? irow[DB_srpsalt] : row[DB_srpgN], irow ? irow[DB_srpverifier] : NULL, passin, verbose)) { BIO_printf(bio_err, "Invalid password for user \"%s\", operation abandoned.\n", user); errors++; goto end; } } if (verbose) BIO_printf(bio_err, "Password for user \"%s\" ok.\n", user); if (! (gNid = srp_create_user(user, &(row[DB_srpverifier]), &(row[DB_srpsalt]), gNrow ? gNrow[DB_srpsalt] : NULL, gNrow ? gNrow[DB_srpverifier] : NULL, passout, verbose))) { BIO_printf(bio_err, "Cannot create srp verifier for user \"%s\", operation abandoned.\n", user); errors++; goto end; } row[DB_srptype][0] = 'v'; row[DB_srpgN] = OPENSSL_strdup(gNid); if (row[DB_srpid] == NULL || row[DB_srpgN] == NULL || row[DB_srptype] == NULL || row[DB_srpverifier] == NULL || row[DB_srpsalt] == NULL || (userinfo && ((row[DB_srpinfo] = OPENSSL_strdup(userinfo)) == NULL))) goto end; doupdatedb = 1; } } } else if (mode == OPT_DELETE) { if (userindex < 0) { BIO_printf(bio_err, "user \"%s\" does not exist, operation ignored. t\n", user); errors++; } else { char **xpp = sk_OPENSSL_PSTRING_value(db->db->data, userindex); BIO_printf(bio_err, "user \"%s\" revoked. t\n", user); xpp[DB_srptype][0] = 'R'; doupdatedb = 1; } } user = *argv++; if (user == NULL) { /* no more processing in any mode if no users left */ break; } } if (verbose) BIO_printf(bio_err, "User procession done.\n"); if (doupdatedb) { /* Lets check some fields */ for (i = 0; i < sk_OPENSSL_PSTRING_num(db->db->data); i++) { pp = sk_OPENSSL_PSTRING_value(db->db->data, i); if (pp[DB_srptype][0] == 'v') { pp[DB_srptype][0] = 'V'; print_user(db, i, verbose); } } if (verbose) BIO_printf(bio_err, "Trying to update srpvfile.\n"); if (!save_index(srpvfile, "new", db)) goto end; if (verbose) BIO_printf(bio_err, "Temporary srpvfile created.\n"); if (!rotate_index(srpvfile, "new", "old")) goto end; if (verbose) BIO_printf(bio_err, "srpvfile updated.\n"); } ret = (errors != 0); end: if (errors != 0) if (verbose) BIO_printf(bio_err, "User errors %d.\n", errors); if (verbose) BIO_printf(bio_err, "SRP terminating with code %d.\n", ret); OPENSSL_free(passin); OPENSSL_free(passout); if (ret) ERR_print_errors(bio_err); NCONF_free(conf); free_index(db); release_engine(e); return ret; }
./openssl/apps/enc.c
/* * Copyright 1995-2023 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <limits.h> #include "apps.h" #include "progs.h" #include <openssl/bio.h> #include <openssl/err.h> #include <openssl/evp.h> #include <openssl/objects.h> #include <openssl/x509.h> #include <openssl/rand.h> #include <openssl/pem.h> #ifndef OPENSSL_NO_COMP # include <openssl/comp.h> #endif #include <ctype.h> #undef SIZE #undef BSIZE #define SIZE (512) #define BSIZE (8*1024) #define PBKDF2_ITER_DEFAULT 10000 #define STR(a) XSTR(a) #define XSTR(a) #a static int set_hex(const char *in, unsigned char *out, int size); static void show_ciphers(const OBJ_NAME *name, void *bio_); struct doall_enc_ciphers { BIO *bio; int n; }; typedef enum OPTION_choice { OPT_COMMON, OPT_LIST, OPT_E, OPT_IN, OPT_OUT, OPT_PASS, OPT_ENGINE, OPT_D, OPT_P, OPT_V, OPT_NOPAD, OPT_SALT, OPT_NOSALT, OPT_DEBUG, OPT_UPPER_P, OPT_UPPER_A, OPT_A, OPT_Z, OPT_BUFSIZE, OPT_K, OPT_KFILE, OPT_UPPER_K, OPT_NONE, OPT_UPPER_S, OPT_IV, OPT_MD, OPT_ITER, OPT_PBKDF2, OPT_CIPHER, OPT_SALTLEN, OPT_R_ENUM, OPT_PROV_ENUM } OPTION_CHOICE; const OPTIONS enc_options[] = { OPT_SECTION("General"), {"help", OPT_HELP, '-', "Display this summary"}, {"list", OPT_LIST, '-', "List ciphers"}, #ifndef OPENSSL_NO_DEPRECATED_3_0 {"ciphers", OPT_LIST, '-', "Alias for -list"}, #endif {"e", OPT_E, '-', "Encrypt"}, {"d", OPT_D, '-', "Decrypt"}, {"p", OPT_P, '-', "Print the iv/key"}, {"P", OPT_UPPER_P, '-', "Print the iv/key and exit"}, #ifndef OPENSSL_NO_ENGINE {"engine", OPT_ENGINE, 's', "Use engine, possibly a hardware device"}, #endif OPT_SECTION("Input"), {"in", OPT_IN, '<', "Input file"}, {"k", OPT_K, 's', "Passphrase"}, {"kfile", OPT_KFILE, '<', "Read passphrase from file"}, OPT_SECTION("Output"), {"out", OPT_OUT, '>', "Output file"}, {"pass", OPT_PASS, 's', "Passphrase source"}, {"v", OPT_V, '-', "Verbose output"}, {"a", OPT_A, '-', "Base64 encode/decode, depending on encryption flag"}, {"base64", OPT_A, '-', "Same as option -a"}, {"A", OPT_UPPER_A, '-', "Used with -[base64|a] to specify base64 buffer as a single line"}, OPT_SECTION("Encryption"), {"nopad", OPT_NOPAD, '-', "Disable standard block padding"}, {"salt", OPT_SALT, '-', "Use salt in the KDF (default)"}, {"nosalt", OPT_NOSALT, '-', "Do not use salt in the KDF"}, {"debug", OPT_DEBUG, '-', "Print debug info"}, {"bufsize", OPT_BUFSIZE, 's', "Buffer size"}, {"K", OPT_UPPER_K, 's', "Raw key, in hex"}, {"S", OPT_UPPER_S, 's', "Salt, in hex"}, {"iv", OPT_IV, 's', "IV in hex"}, {"md", OPT_MD, 's', "Use specified digest to create a key from the passphrase"}, {"iter", OPT_ITER, 'p', "Specify the iteration count and force the use of PBKDF2"}, {OPT_MORE_STR, 0, 0, "Default: " STR(PBKDF2_ITER_DEFAULT)}, {"pbkdf2", OPT_PBKDF2, '-', "Use password-based key derivation function 2 (PBKDF2)"}, {OPT_MORE_STR, 0, 0, "Use -iter to change the iteration count from " STR(PBKDF2_ITER_DEFAULT)}, {"none", OPT_NONE, '-', "Don't encrypt"}, {"saltlen", OPT_SALTLEN, 'p', "Specify the PBKDF2 salt length (in bytes)"}, {OPT_MORE_STR, 0, 0, "Default: 16"}, #ifndef OPENSSL_NO_ZLIB {"z", OPT_Z, '-', "Compress or decompress encrypted data using zlib"}, #endif {"", OPT_CIPHER, '-', "Any supported cipher"}, OPT_R_OPTIONS, OPT_PROV_OPTIONS, {NULL} }; int enc_main(int argc, char **argv) { static char buf[128]; static const char magic[] = "Salted__"; ENGINE *e = NULL; BIO *in = NULL, *out = NULL, *b64 = NULL, *benc = NULL, *rbio = NULL, *wbio = NULL; EVP_CIPHER_CTX *ctx = NULL; EVP_CIPHER *cipher = NULL; EVP_MD *dgst = NULL; const char *digestname = NULL; char *hkey = NULL, *hiv = NULL, *hsalt = NULL, *p; char *infile = NULL, *outfile = NULL, *prog; char *str = NULL, *passarg = NULL, *pass = NULL, *strbuf = NULL; const char *ciphername = NULL; char mbuf[sizeof(magic) - 1]; OPTION_CHOICE o; int bsize = BSIZE, verbose = 0, debug = 0, olb64 = 0, nosalt = 0; int enc = 1, printkey = 0, i, k; int base64 = 0, informat = FORMAT_BINARY, outformat = FORMAT_BINARY; int ret = 1, inl, nopad = 0; unsigned char key[EVP_MAX_KEY_LENGTH], iv[EVP_MAX_IV_LENGTH]; unsigned char *buff = NULL, salt[EVP_MAX_IV_LENGTH]; int saltlen = 0; int pbkdf2 = 0; int iter = 0; long n; int streamable = 1; int wrap = 0; struct doall_enc_ciphers dec; #ifndef OPENSSL_NO_ZLIB int do_zlib = 0; BIO *bzl = NULL; #endif int do_brotli = 0; BIO *bbrot = NULL; int do_zstd = 0; BIO *bzstd = NULL; /* first check the command name */ if (strcmp(argv[0], "base64") == 0) base64 = 1; #ifndef OPENSSL_NO_ZLIB else if (strcmp(argv[0], "zlib") == 0) do_zlib = 1; #endif #ifndef OPENSSL_NO_BROTLI else if (strcmp(argv[0], "brotli") == 0) do_brotli = 1; #endif #ifndef OPENSSL_NO_ZSTD else if (strcmp(argv[0], "zstd") == 0) do_zstd = 1; #endif else if (strcmp(argv[0], "enc") != 0) ciphername = argv[0]; opt_set_unknown_name("cipher"); prog = opt_init(argc, argv, enc_options); while ((o = opt_next()) != OPT_EOF) { switch (o) { case OPT_EOF: case OPT_ERR: opthelp: BIO_printf(bio_err, "%s: Use -help for summary.\n", prog); goto end; case OPT_HELP: opt_help(enc_options); ret = 0; goto end; case OPT_LIST: BIO_printf(bio_out, "Supported ciphers:\n"); dec.bio = bio_out; dec.n = 0; OBJ_NAME_do_all_sorted(OBJ_NAME_TYPE_CIPHER_METH, show_ciphers, &dec); BIO_printf(bio_out, "\n"); ret = 0; goto end; case OPT_E: enc = 1; break; case OPT_IN: infile = opt_arg(); break; case OPT_OUT: outfile = opt_arg(); break; case OPT_PASS: passarg = opt_arg(); break; case OPT_ENGINE: e = setup_engine(opt_arg(), 0); break; case OPT_D: enc = 0; break; case OPT_P: printkey = 1; break; case OPT_V: verbose = 1; break; case OPT_NOPAD: nopad = 1; break; case OPT_SALT: nosalt = 0; break; case OPT_NOSALT: nosalt = 1; break; case OPT_DEBUG: debug = 1; break; case OPT_UPPER_P: printkey = 2; break; case OPT_UPPER_A: olb64 = 1; break; case OPT_A: base64 = 1; break; case OPT_Z: #ifndef OPENSSL_NO_ZLIB do_zlib = 1; #endif break; case OPT_BUFSIZE: p = opt_arg(); i = (int)strlen(p) - 1; k = i >= 1 && p[i] == 'k'; if (k) p[i] = '\0'; if (!opt_long(opt_arg(), &n) || n < 0 || (k && n >= LONG_MAX / 1024)) goto opthelp; if (k) n *= 1024; bsize = (int)n; break; case OPT_K: str = opt_arg(); break; case OPT_KFILE: in = bio_open_default(opt_arg(), 'r', FORMAT_TEXT); if (in == NULL) goto opthelp; i = BIO_gets(in, buf, sizeof(buf)); BIO_free(in); in = NULL; if (i <= 0) { BIO_printf(bio_err, "%s Can't read key from %s\n", prog, opt_arg()); goto opthelp; } while (--i > 0 && (buf[i] == '\r' || buf[i] == '\n')) buf[i] = '\0'; if (i <= 0) { BIO_printf(bio_err, "%s: zero length password\n", prog); goto opthelp; } str = buf; break; case OPT_UPPER_K: hkey = opt_arg(); break; case OPT_UPPER_S: hsalt = opt_arg(); break; case OPT_IV: hiv = opt_arg(); break; case OPT_MD: digestname = opt_arg(); break; case OPT_CIPHER: ciphername = opt_unknown(); break; case OPT_ITER: iter = opt_int_arg(); pbkdf2 = 1; break; case OPT_SALTLEN: if (!opt_int(opt_arg(), &saltlen)) goto opthelp; if (saltlen > (int)sizeof(salt)) saltlen = (int)sizeof(salt); break; case OPT_PBKDF2: pbkdf2 = 1; if (iter == 0) /* do not overwrite a chosen value */ iter = PBKDF2_ITER_DEFAULT; break; case OPT_NONE: cipher = NULL; break; case OPT_R_CASES: if (!opt_rand(o)) goto end; break; case OPT_PROV_CASES: if (!opt_provider(o)) goto end; break; } } /* No extra arguments. */ if (!opt_check_rest_arg(NULL)) goto opthelp; if (!app_RAND_load()) goto end; if (saltlen == 0 || pbkdf2 == 0) saltlen = PKCS5_SALT_LEN; /* Get the cipher name, either from progname (if set) or flag. */ if (!opt_cipher(ciphername, &cipher)) goto opthelp; if (cipher && (EVP_CIPHER_mode(cipher) == EVP_CIPH_WRAP_MODE)) { wrap = 1; streamable = 0; } if (digestname != NULL) { if (!opt_md(digestname, &dgst)) goto opthelp; } if (dgst == NULL) dgst = (EVP_MD *)EVP_sha256(); if (iter == 0) iter = 1; /* It must be large enough for a base64 encoded line */ if (base64 && bsize < 80) bsize = 80; if (verbose) BIO_printf(bio_err, "bufsize=%d\n", bsize); #ifndef OPENSSL_NO_ZLIB if (do_zlib) base64 = 0; #endif if (do_brotli) base64 = 0; if (do_zstd) base64 = 0; if (base64) { if (enc) outformat = FORMAT_BASE64; else informat = FORMAT_BASE64; } strbuf = app_malloc(SIZE, "strbuf"); buff = app_malloc(EVP_ENCODE_LENGTH(bsize), "evp buffer"); if (infile == NULL) { if (!streamable && printkey != 2) { /* if just print key and exit, it's ok */ BIO_printf(bio_err, "Unstreamable cipher mode\n"); goto end; } in = dup_bio_in(informat); } else { in = bio_open_default(infile, 'r', informat); } if (in == NULL) goto end; if (str == NULL && passarg != NULL) { if (!app_passwd(passarg, NULL, &pass, NULL)) { BIO_printf(bio_err, "Error getting password\n"); goto end; } str = pass; } if ((str == NULL) && (cipher != NULL) && (hkey == NULL)) { if (1) { #ifndef OPENSSL_NO_UI_CONSOLE for (;;) { char prompt[200]; BIO_snprintf(prompt, sizeof(prompt), "enter %s %s password:", EVP_CIPHER_get0_name(cipher), (enc) ? "encryption" : "decryption"); strbuf[0] = '\0'; i = EVP_read_pw_string((char *)strbuf, SIZE, prompt, enc); if (i == 0) { if (strbuf[0] == '\0') { ret = 1; goto end; } str = strbuf; break; } if (i < 0) { BIO_printf(bio_err, "bad password read\n"); goto end; } } } else { #endif BIO_printf(bio_err, "password required\n"); goto end; } } out = bio_open_default(outfile, 'w', outformat); if (out == NULL) goto end; if (debug) { BIO_set_callback_ex(in, BIO_debug_callback_ex); BIO_set_callback_ex(out, BIO_debug_callback_ex); BIO_set_callback_arg(in, (char *)bio_err); BIO_set_callback_arg(out, (char *)bio_err); } rbio = in; wbio = out; #ifndef OPENSSL_NO_COMP # ifndef OPENSSL_NO_ZLIB if (do_zlib) { if ((bzl = BIO_new(BIO_f_zlib())) == NULL) goto end; if (debug) { BIO_set_callback_ex(bzl, BIO_debug_callback_ex); BIO_set_callback_arg(bzl, (char *)bio_err); } if (enc) wbio = BIO_push(bzl, wbio); else rbio = BIO_push(bzl, rbio); } # endif if (do_brotli) { if ((bbrot = BIO_new(BIO_f_brotli())) == NULL) goto end; if (debug) { BIO_set_callback_ex(bbrot, BIO_debug_callback_ex); BIO_set_callback_arg(bbrot, (char *)bio_err); } if (enc) wbio = BIO_push(bbrot, wbio); else rbio = BIO_push(bbrot, rbio); } if (do_zstd) { if ((bzstd = BIO_new(BIO_f_zstd())) == NULL) goto end; if (debug) { BIO_set_callback_ex(bzstd, BIO_debug_callback_ex); BIO_set_callback_arg(bzstd, (char *)bio_err); } if (enc) wbio = BIO_push(bzstd, wbio); else rbio = BIO_push(bzstd, rbio); } #endif if (base64) { if ((b64 = BIO_new(BIO_f_base64())) == NULL) goto end; if (debug) { BIO_set_callback_ex(b64, BIO_debug_callback_ex); BIO_set_callback_arg(b64, (char *)bio_err); } if (olb64) BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL); if (enc) wbio = BIO_push(b64, wbio); else rbio = BIO_push(b64, rbio); } if (cipher != NULL) { if (str != NULL) { /* a passphrase is available */ /* * Salt handling: if encrypting generate a salt if not supplied, * and write to output BIO. If decrypting use salt from input BIO * if not given with args */ unsigned char *sptr; size_t str_len = strlen(str); if (nosalt) { sptr = NULL; } else { if (hsalt != NULL && !set_hex(hsalt, salt, saltlen)) { BIO_printf(bio_err, "invalid hex salt value\n"); goto end; } if (enc) { /* encryption */ if (hsalt == NULL) { if (RAND_bytes(salt, saltlen) <= 0) { BIO_printf(bio_err, "RAND_bytes failed\n"); goto end; } /* * If -P option then don't bother writing. * If salt is given, shouldn't either ? */ if ((printkey != 2) && (BIO_write(wbio, magic, sizeof(magic) - 1) != sizeof(magic) - 1 || BIO_write(wbio, (char *)salt, saltlen) != saltlen)) { BIO_printf(bio_err, "error writing output file\n"); goto end; } } } else { /* decryption */ if (hsalt == NULL) { if (BIO_read(rbio, mbuf, sizeof(mbuf)) != sizeof(mbuf)) { BIO_printf(bio_err, "error reading input file\n"); goto end; } if (memcmp(mbuf, magic, sizeof(mbuf)) == 0) { /* file IS salted */ if (BIO_read(rbio, salt, saltlen) != saltlen) { BIO_printf(bio_err, "error reading input file\n"); goto end; } } else { /* file is NOT salted, NO salt available */ BIO_printf(bio_err, "bad magic number\n"); goto end; } } } sptr = salt; } if (pbkdf2 == 1) { /* * derive key and default iv * concatenated into a temporary buffer */ unsigned char tmpkeyiv[EVP_MAX_KEY_LENGTH + EVP_MAX_IV_LENGTH]; int iklen = EVP_CIPHER_get_key_length(cipher); int ivlen = EVP_CIPHER_get_iv_length(cipher); /* not needed if HASH_UPDATE() is fixed : */ int islen = (sptr != NULL ? saltlen : 0); if (!PKCS5_PBKDF2_HMAC(str, str_len, sptr, islen, iter, dgst, iklen+ivlen, tmpkeyiv)) { BIO_printf(bio_err, "PKCS5_PBKDF2_HMAC failed\n"); goto end; } /* split and move data back to global buffer */ memcpy(key, tmpkeyiv, iklen); memcpy(iv, tmpkeyiv+iklen, ivlen); } else { BIO_printf(bio_err, "*** WARNING : " "deprecated key derivation used.\n" "Using -iter or -pbkdf2 would be better.\n"); if (!EVP_BytesToKey(cipher, dgst, sptr, (unsigned char *)str, str_len, 1, key, iv)) { BIO_printf(bio_err, "EVP_BytesToKey failed\n"); goto end; } } /* * zero the complete buffer or the string passed from the command * line. */ if (str == strbuf) OPENSSL_cleanse(str, SIZE); else OPENSSL_cleanse(str, str_len); } if (hiv != NULL) { int siz = EVP_CIPHER_get_iv_length(cipher); if (siz == 0) { BIO_printf(bio_err, "warning: iv not used by this cipher\n"); } else if (!set_hex(hiv, iv, siz)) { BIO_printf(bio_err, "invalid hex iv value\n"); goto end; } } if ((hiv == NULL) && (str == NULL) && EVP_CIPHER_get_iv_length(cipher) != 0 && wrap == 0) { /* * No IV was explicitly set and no IV was generated. * Hence the IV is undefined, making correct decryption impossible. */ BIO_printf(bio_err, "iv undefined\n"); goto end; } if (hkey != NULL) { if (!set_hex(hkey, key, EVP_CIPHER_get_key_length(cipher))) { BIO_printf(bio_err, "invalid hex key value\n"); goto end; } /* wiping secret data as we no longer need it */ cleanse(hkey); } if ((benc = BIO_new(BIO_f_cipher())) == NULL) goto end; /* * Since we may be changing parameters work on the encryption context * rather than calling BIO_set_cipher(). */ BIO_get_cipher_ctx(benc, &ctx); if (wrap == 1) EVP_CIPHER_CTX_set_flags(ctx, EVP_CIPHER_CTX_FLAG_WRAP_ALLOW); if (!EVP_CipherInit_ex(ctx, cipher, e, NULL, NULL, enc)) { BIO_printf(bio_err, "Error setting cipher %s\n", EVP_CIPHER_get0_name(cipher)); ERR_print_errors(bio_err); goto end; } if (nopad) EVP_CIPHER_CTX_set_padding(ctx, 0); if (!EVP_CipherInit_ex(ctx, NULL, NULL, key, (hiv == NULL && wrap == 1 ? NULL : iv), enc)) { BIO_printf(bio_err, "Error setting cipher %s\n", EVP_CIPHER_get0_name(cipher)); ERR_print_errors(bio_err); goto end; } if (debug) { BIO_set_callback_ex(benc, BIO_debug_callback_ex); BIO_set_callback_arg(benc, (char *)bio_err); } if (printkey) { if (!nosalt) { printf("salt="); for (i = 0; i < (int)saltlen; i++) printf("%02X", salt[i]); printf("\n"); } if (EVP_CIPHER_get_key_length(cipher) > 0) { printf("key="); for (i = 0; i < EVP_CIPHER_get_key_length(cipher); i++) printf("%02X", key[i]); printf("\n"); } if (EVP_CIPHER_get_iv_length(cipher) > 0) { printf("iv ="); for (i = 0; i < EVP_CIPHER_get_iv_length(cipher); i++) printf("%02X", iv[i]); printf("\n"); } if (printkey == 2) { ret = 0; goto end; } } } /* Only encrypt/decrypt as we write the file */ if (benc != NULL) wbio = BIO_push(benc, wbio); while (BIO_pending(rbio) || !BIO_eof(rbio)) { inl = BIO_read(rbio, (char *)buff, bsize); if (inl <= 0) break; if (!streamable && !BIO_eof(rbio)) { /* do not output data */ BIO_printf(bio_err, "Unstreamable cipher mode\n"); goto end; } if (BIO_write(wbio, (char *)buff, inl) != inl) { BIO_printf(bio_err, "error writing output file\n"); goto end; } if (!streamable) break; } if (!BIO_flush(wbio)) { if (enc) BIO_printf(bio_err, "bad encrypt\n"); else BIO_printf(bio_err, "bad decrypt\n"); goto end; } ret = 0; if (verbose) { BIO_printf(bio_err, "bytes read : %8ju\n", BIO_number_read(in)); BIO_printf(bio_err, "bytes written: %8ju\n", BIO_number_written(out)); } end: ERR_print_errors(bio_err); OPENSSL_free(strbuf); OPENSSL_free(buff); BIO_free(in); BIO_free_all(out); BIO_free(benc); BIO_free(b64); EVP_MD_free(dgst); EVP_CIPHER_free(cipher); #ifndef OPENSSL_NO_ZLIB BIO_free(bzl); #endif BIO_free(bbrot); BIO_free(bzstd); release_engine(e); OPENSSL_free(pass); return ret; } static void show_ciphers(const OBJ_NAME *name, void *arg) { struct doall_enc_ciphers *dec = (struct doall_enc_ciphers *)arg; const EVP_CIPHER *cipher; if (!islower((unsigned char)*name->name)) return; /* Filter out ciphers that we cannot use */ cipher = EVP_get_cipherbyname(name->name); if (cipher == NULL || (EVP_CIPHER_get_flags(cipher) & EVP_CIPH_FLAG_AEAD_CIPHER) != 0 || EVP_CIPHER_get_mode(cipher) == EVP_CIPH_XTS_MODE) return; BIO_printf(dec->bio, "-%-25s", name->name); if (++dec->n == 3) { BIO_printf(dec->bio, "\n"); dec->n = 0; } else BIO_printf(dec->bio, " "); } static int set_hex(const char *in, unsigned char *out, int size) { int i, n; unsigned char j; i = size * 2; n = strlen(in); if (n > i) { BIO_printf(bio_err, "hex string is too long, ignoring excess\n"); n = i; /* ignore exceeding part */ } else if (n < i) { BIO_printf(bio_err, "hex string is too short, padding with zero bytes to length\n"); } memset(out, 0, size); for (i = 0; i < n; i++) { j = (unsigned char)*in++; if (!isxdigit(j)) { BIO_printf(bio_err, "non-hex digit\n"); return 0; } j = (unsigned char)OPENSSL_hexchar2int(j); if (i & 1) out[i / 2] |= j; else out[i / 2] = (j << 4); } return 1; }
./openssl/apps/ciphers.c
/* * Copyright 1995-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 "apps.h" #include "progs.h" #include <openssl/err.h> #include <openssl/ssl.h> #include "s_apps.h" typedef enum OPTION_choice { OPT_COMMON, OPT_STDNAME, OPT_CONVERT, OPT_SSL3, OPT_TLS1, OPT_TLS1_1, OPT_TLS1_2, OPT_TLS1_3, OPT_PSK, OPT_SRP, OPT_CIPHERSUITES, OPT_V, OPT_UPPER_V, OPT_S, OPT_PROV_ENUM } OPTION_CHOICE; const OPTIONS ciphers_options[] = { {OPT_HELP_STR, 1, '-', "Usage: %s [options] [cipher]\n"}, OPT_SECTION("General"), {"help", OPT_HELP, '-', "Display this summary"}, OPT_SECTION("Output"), {"v", OPT_V, '-', "Verbose listing of the SSL/TLS ciphers"}, {"V", OPT_UPPER_V, '-', "Even more verbose"}, {"stdname", OPT_STDNAME, '-', "Show standard cipher names"}, {"convert", OPT_CONVERT, 's', "Convert standard name into OpenSSL name"}, OPT_SECTION("Cipher specification"), {"s", OPT_S, '-', "Only supported ciphers"}, #ifndef OPENSSL_NO_SSL3 {"ssl3", OPT_SSL3, '-', "Ciphers compatible with SSL3"}, #endif #ifndef OPENSSL_NO_TLS1 {"tls1", OPT_TLS1, '-', "Ciphers compatible with TLS1"}, #endif #ifndef OPENSSL_NO_TLS1_1 {"tls1_1", OPT_TLS1_1, '-', "Ciphers compatible with TLS1.1"}, #endif #ifndef OPENSSL_NO_TLS1_2 {"tls1_2", OPT_TLS1_2, '-', "Ciphers compatible with TLS1.2"}, #endif #ifndef OPENSSL_NO_TLS1_3 {"tls1_3", OPT_TLS1_3, '-', "Ciphers compatible with TLS1.3"}, #endif #ifndef OPENSSL_NO_PSK {"psk", OPT_PSK, '-', "Include ciphersuites requiring PSK"}, #endif #ifndef OPENSSL_NO_SRP {"srp", OPT_SRP, '-', "(deprecated) Include ciphersuites requiring SRP"}, #endif {"ciphersuites", OPT_CIPHERSUITES, 's', "Configure the TLSv1.3 ciphersuites to use"}, OPT_PROV_OPTIONS, OPT_PARAMETERS(), {"cipher", 0, 0, "Cipher string to decode (optional)"}, {NULL} }; #ifndef OPENSSL_NO_PSK static unsigned int dummy_psk(SSL *ssl, const char *hint, char *identity, unsigned int max_identity_len, unsigned char *psk, unsigned int max_psk_len) { return 0; } #endif int ciphers_main(int argc, char **argv) { SSL_CTX *ctx = NULL; SSL *ssl = NULL; STACK_OF(SSL_CIPHER) *sk = NULL; const SSL_METHOD *meth = TLS_server_method(); int ret = 1, i, verbose = 0, Verbose = 0, use_supported = 0; int stdname = 0; #ifndef OPENSSL_NO_PSK int psk = 0; #endif #ifndef OPENSSL_NO_SRP int srp = 0; #endif const char *p; char *ciphers = NULL, *prog, *convert = NULL, *ciphersuites = NULL; char buf[512]; OPTION_CHOICE o; int min_version = 0, max_version = 0; prog = opt_init(argc, argv, ciphers_options); while ((o = opt_next()) != OPT_EOF) { switch (o) { case OPT_EOF: case OPT_ERR: opthelp: BIO_printf(bio_err, "%s: Use -help for summary.\n", prog); goto end; case OPT_HELP: opt_help(ciphers_options); ret = 0; goto end; case OPT_V: verbose = 1; break; case OPT_UPPER_V: verbose = Verbose = 1; break; case OPT_S: use_supported = 1; break; case OPT_STDNAME: stdname = verbose = 1; break; case OPT_CONVERT: convert = opt_arg(); break; case OPT_SSL3: min_version = SSL3_VERSION; max_version = SSL3_VERSION; break; case OPT_TLS1: min_version = TLS1_VERSION; max_version = TLS1_VERSION; break; case OPT_TLS1_1: min_version = TLS1_1_VERSION; max_version = TLS1_1_VERSION; break; case OPT_TLS1_2: min_version = TLS1_2_VERSION; max_version = TLS1_2_VERSION; break; case OPT_TLS1_3: min_version = TLS1_3_VERSION; max_version = TLS1_3_VERSION; break; case OPT_PSK: #ifndef OPENSSL_NO_PSK psk = 1; #endif break; case OPT_SRP: #ifndef OPENSSL_NO_SRP srp = 1; #endif break; case OPT_CIPHERSUITES: ciphersuites = opt_arg(); break; case OPT_PROV_CASES: if (!opt_provider(o)) goto end; break; } } /* Optional arg is cipher name. */ argv = opt_rest(); if (opt_num_rest() == 1) ciphers = argv[0]; else if (!opt_check_rest_arg(NULL)) goto opthelp; if (convert != NULL) { BIO_printf(bio_out, "OpenSSL cipher name: %s\n", OPENSSL_cipher_name(convert)); ret = 0; goto end; } ctx = SSL_CTX_new_ex(app_get0_libctx(), app_get0_propq(), meth); if (ctx == NULL) goto err; if (SSL_CTX_set_min_proto_version(ctx, min_version) == 0) goto err; if (SSL_CTX_set_max_proto_version(ctx, max_version) == 0) goto err; #ifndef OPENSSL_NO_PSK if (psk) SSL_CTX_set_psk_client_callback(ctx, dummy_psk); #endif #ifndef OPENSSL_NO_SRP if (srp) set_up_dummy_srp(ctx); #endif if (ciphersuites != NULL && !SSL_CTX_set_ciphersuites(ctx, ciphersuites)) { BIO_printf(bio_err, "Error setting TLSv1.3 ciphersuites\n"); goto err; } if (ciphers != NULL) { if (!SSL_CTX_set_cipher_list(ctx, ciphers)) { BIO_printf(bio_err, "Error in cipher list\n"); goto err; } } ssl = SSL_new(ctx); if (ssl == NULL) goto err; if (use_supported) sk = SSL_get1_supported_ciphers(ssl); else sk = SSL_get_ciphers(ssl); if (!verbose) { for (i = 0; i < sk_SSL_CIPHER_num(sk); i++) { const SSL_CIPHER *c = sk_SSL_CIPHER_value(sk, i); if (!ossl_assert(c != NULL)) continue; p = SSL_CIPHER_get_name(c); if (p == NULL) break; if (i != 0) BIO_printf(bio_out, ":"); BIO_printf(bio_out, "%s", p); } BIO_printf(bio_out, "\n"); } else { for (i = 0; i < sk_SSL_CIPHER_num(sk); i++) { const SSL_CIPHER *c; c = sk_SSL_CIPHER_value(sk, i); if (!ossl_assert(c != NULL)) continue; if (Verbose) { unsigned long id = SSL_CIPHER_get_id(c); int id0 = (int)(id >> 24); int id1 = (int)((id >> 16) & 0xffL); int id2 = (int)((id >> 8) & 0xffL); int id3 = (int)(id & 0xffL); if ((id & 0xff000000L) == 0x03000000L) BIO_printf(bio_out, " 0x%02X,0x%02X - ", id2, id3); /* SSL3 * cipher */ else BIO_printf(bio_out, "0x%02X,0x%02X,0x%02X,0x%02X - ", id0, id1, id2, id3); /* whatever */ } if (stdname) { const char *nm = SSL_CIPHER_standard_name(c); if (nm == NULL) nm = "UNKNOWN"; BIO_printf(bio_out, "%-45s - ", nm); } BIO_puts(bio_out, SSL_CIPHER_description(c, buf, sizeof(buf))); } } ret = 0; goto end; err: ERR_print_errors(bio_err); end: if (use_supported) sk_SSL_CIPHER_free(sk); SSL_CTX_free(ctx); SSL_free(ssl); return ret; }
./openssl/apps/info.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/crypto.h> #include "apps.h" #include "progs.h" typedef enum OPTION_choice { OPT_COMMON, OPT_CONFIGDIR, OPT_ENGINESDIR, OPT_MODULESDIR, OPT_DSOEXT, OPT_DIRNAMESEP, OPT_LISTSEP, OPT_SEEDS, OPT_CPUSETTINGS } OPTION_CHOICE; const OPTIONS info_options[] = { OPT_SECTION("General"), {"help", OPT_HELP, '-', "Display this summary"}, OPT_SECTION("Output"), {"configdir", OPT_CONFIGDIR, '-', "Default configuration file directory"}, {"enginesdir", OPT_ENGINESDIR, '-', "Default engine module directory"}, {"modulesdir", OPT_MODULESDIR, '-', "Default module directory (other than engine modules)"}, {"dsoext", OPT_DSOEXT, '-', "Configured extension for modules"}, {"dirnamesep", OPT_DIRNAMESEP, '-', "Directory-filename separator"}, {"listsep", OPT_LISTSEP, '-', "List separator character"}, {"seeds", OPT_SEEDS, '-', "Seed sources"}, {"cpusettings", OPT_CPUSETTINGS, '-', "CPU settings info"}, {NULL} }; int info_main(int argc, char **argv) { int ret = 1, dirty = 0, type = 0; char *prog; OPTION_CHOICE o; prog = opt_init(argc, argv, info_options); while ((o = opt_next()) != OPT_EOF) { switch (o) { default: opthelp: BIO_printf(bio_err, "%s: Use -help for summary.\n", prog); goto end; case OPT_HELP: opt_help(info_options); ret = 0; goto end; case OPT_CONFIGDIR: type = OPENSSL_INFO_CONFIG_DIR; dirty++; break; case OPT_ENGINESDIR: type = OPENSSL_INFO_ENGINES_DIR; dirty++; break; case OPT_MODULESDIR: type = OPENSSL_INFO_MODULES_DIR; dirty++; break; case OPT_DSOEXT: type = OPENSSL_INFO_DSO_EXTENSION; dirty++; break; case OPT_DIRNAMESEP: type = OPENSSL_INFO_DIR_FILENAME_SEPARATOR; dirty++; break; case OPT_LISTSEP: type = OPENSSL_INFO_LIST_SEPARATOR; dirty++; break; case OPT_SEEDS: type = OPENSSL_INFO_SEED_SOURCE; dirty++; break; case OPT_CPUSETTINGS: type = OPENSSL_INFO_CPU_SETTINGS; dirty++; break; } } if (!opt_check_rest_arg(NULL)) goto opthelp; if (dirty > 1) { BIO_printf(bio_err, "%s: Only one item allowed\n", prog); goto opthelp; } if (dirty == 0) { BIO_printf(bio_err, "%s: No items chosen\n", prog); goto opthelp; } BIO_printf(bio_out, "%s\n", OPENSSL_info(type)); ret = 0; end: return ret; }
./openssl/apps/asn1parse.c
/* * Copyright 1995-2023 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include "apps.h" #include "progs.h" #include <openssl/err.h> #include <openssl/evp.h> #include <openssl/x509.h> #include <openssl/pem.h> #include <openssl/asn1t.h> typedef enum OPTION_choice { OPT_COMMON, OPT_INFORM, OPT_IN, OPT_OUT, OPT_INDENT, OPT_NOOUT, OPT_OID, OPT_OFFSET, OPT_LENGTH, OPT_DUMP, OPT_DLIMIT, OPT_STRPARSE, OPT_GENSTR, OPT_GENCONF, OPT_STRICTPEM, OPT_ITEM } OPTION_CHOICE; const OPTIONS asn1parse_options[] = { OPT_SECTION("General"), {"help", OPT_HELP, '-', "Display this summary"}, {"oid", OPT_OID, '<', "file of extra oid definitions"}, OPT_SECTION("I/O"), {"inform", OPT_INFORM, 'A', "input format - one of DER PEM B64"}, {"in", OPT_IN, '<', "input file"}, {"out", OPT_OUT, '>', "output file (output format is always DER)"}, {"noout", OPT_NOOUT, 0, "do not produce any output"}, {"offset", OPT_OFFSET, 'p', "offset into file"}, {"length", OPT_LENGTH, 'p', "length of section in file"}, {"strparse", OPT_STRPARSE, 'p', "offset; a series of these can be used to 'dig'"}, {"genstr", OPT_GENSTR, 's', "string to generate ASN1 structure from"}, {OPT_MORE_STR, 0, 0, "into multiple ASN1 blob wrappings"}, {"genconf", OPT_GENCONF, 's', "file to generate ASN1 structure from"}, {"strictpem", OPT_STRICTPEM, 0, "equivalent to '-inform pem' (obsolete)"}, {"item", OPT_ITEM, 's', "item to parse and print"}, {OPT_MORE_STR, 0, 0, "(-inform will be ignored)"}, OPT_SECTION("Formatting"), {"i", OPT_INDENT, 0, "indents the output"}, {"dump", OPT_DUMP, 0, "unknown data in hex form"}, {"dlimit", OPT_DLIMIT, 'p', "dump the first arg bytes of unknown data in hex form"}, {NULL} }; static int do_generate(char *genstr, const char *genconf, BUF_MEM *buf); int asn1parse_main(int argc, char **argv) { ASN1_TYPE *at = NULL; BIO *in = NULL, *b64 = NULL, *derout = NULL; BUF_MEM *buf = NULL; STACK_OF(OPENSSL_STRING) *osk = NULL; char *genstr = NULL, *genconf = NULL; char *infile = NULL, *oidfile = NULL, *derfile = NULL; unsigned char *str = NULL; char *name = NULL, *header = NULL, *prog; const unsigned char *ctmpbuf; int indent = 0, noout = 0, dump = 0, informat = FORMAT_PEM; int offset = 0, ret = 1, i, j; long num, tmplen; unsigned char *tmpbuf; unsigned int length = 0; OPTION_CHOICE o; const ASN1_ITEM *it = NULL; prog = opt_init(argc, argv, asn1parse_options); if ((osk = sk_OPENSSL_STRING_new_null()) == NULL) { BIO_printf(bio_err, "%s: Memory allocation failure\n", prog); goto end; } while ((o = opt_next()) != OPT_EOF) { switch (o) { case OPT_EOF: case OPT_ERR: opthelp: BIO_printf(bio_err, "%s: Use -help for summary.\n", prog); goto end; case OPT_HELP: opt_help(asn1parse_options); ret = 0; goto end; case OPT_INFORM: if (!opt_format(opt_arg(), OPT_FMT_ASN1, &informat)) goto opthelp; break; case OPT_IN: infile = opt_arg(); break; case OPT_OUT: derfile = opt_arg(); break; case OPT_INDENT: indent = 1; break; case OPT_NOOUT: noout = 1; break; case OPT_OID: oidfile = opt_arg(); break; case OPT_OFFSET: offset = strtol(opt_arg(), NULL, 0); break; case OPT_LENGTH: length = strtol(opt_arg(), NULL, 0); break; case OPT_DUMP: dump = -1; break; case OPT_DLIMIT: dump = strtol(opt_arg(), NULL, 0); break; case OPT_STRPARSE: sk_OPENSSL_STRING_push(osk, opt_arg()); break; case OPT_GENSTR: genstr = opt_arg(); break; case OPT_GENCONF: genconf = opt_arg(); break; case OPT_STRICTPEM: /* accepted for backward compatibility */ informat = FORMAT_PEM; break; case OPT_ITEM: it = ASN1_ITEM_lookup(opt_arg()); if (it == NULL) { size_t tmp; BIO_printf(bio_err, "Unknown item name %s\n", opt_arg()); BIO_puts(bio_err, "Supported types:\n"); for (tmp = 0;; tmp++) { it = ASN1_ITEM_get(tmp); if (it == NULL) break; BIO_printf(bio_err, " %s\n", it->sname); } goto end; } break; } } /* No extra args. */ if (!opt_check_rest_arg(NULL)) goto opthelp; if (oidfile != NULL) { in = bio_open_default(oidfile, 'r', FORMAT_TEXT); if (in == NULL) goto end; OBJ_create_objects(in); BIO_free(in); } if ((in = bio_open_default(infile, 'r', informat)) == NULL) goto end; if (derfile && (derout = bio_open_default(derfile, 'w', FORMAT_ASN1)) == NULL) goto end; if ((buf = BUF_MEM_new()) == NULL) goto end; if (genconf == NULL && genstr == NULL && informat == FORMAT_PEM) { if (PEM_read_bio(in, &name, &header, &str, &num) != 1) { BIO_printf(bio_err, "Error reading PEM file\n"); ERR_print_errors(bio_err); goto end; } buf->data = (char *)str; buf->length = buf->max = num; } else { if (!BUF_MEM_grow(buf, BUFSIZ * 8)) goto end; /* Pre-allocate :-) */ if (genstr || genconf) { num = do_generate(genstr, genconf, buf); if (num < 0) { ERR_print_errors(bio_err); goto end; } } else { if (informat == FORMAT_BASE64) { BIO *tmp; if ((b64 = BIO_new(BIO_f_base64())) == NULL) goto end; BIO_push(b64, in); tmp = in; in = b64; b64 = tmp; } num = 0; for (;;) { if (!BUF_MEM_grow(buf, num + BUFSIZ)) goto end; i = BIO_read(in, &(buf->data[num]), BUFSIZ); if (i <= 0) break; num += i; } } str = (unsigned char *)buf->data; } /* If any structs to parse go through in sequence */ if (sk_OPENSSL_STRING_num(osk)) { tmpbuf = str; tmplen = num; for (i = 0; i < sk_OPENSSL_STRING_num(osk); i++) { ASN1_TYPE *atmp; int typ; j = strtol(sk_OPENSSL_STRING_value(osk, i), NULL, 0); if (j <= 0 || j >= tmplen) { BIO_printf(bio_err, "'%s' is out of range\n", sk_OPENSSL_STRING_value(osk, i)); continue; } tmpbuf += j; tmplen -= j; atmp = at; ctmpbuf = tmpbuf; at = d2i_ASN1_TYPE(NULL, &ctmpbuf, tmplen); ASN1_TYPE_free(atmp); if (!at) { BIO_printf(bio_err, "Error parsing structure\n"); ERR_print_errors(bio_err); goto end; } typ = ASN1_TYPE_get(at); if ((typ == V_ASN1_OBJECT) || (typ == V_ASN1_BOOLEAN) || (typ == V_ASN1_NULL)) { BIO_printf(bio_err, "Can't parse %s type\n", ASN1_tag2str(typ)); ERR_print_errors(bio_err); goto end; } /* hmm... this is a little evil but it works */ tmpbuf = at->value.asn1_string->data; tmplen = at->value.asn1_string->length; } str = tmpbuf; num = tmplen; } if (offset < 0 || offset >= num) { BIO_printf(bio_err, "Error: offset out of range\n"); goto end; } num -= offset; if (length == 0 || length > (unsigned int)num) length = (unsigned int)num; if (derout != NULL) { if (BIO_write(derout, str + offset, length) != (int)length) { BIO_printf(bio_err, "Error writing output\n"); ERR_print_errors(bio_err); goto end; } } if (!noout) { const unsigned char *p = str + offset; if (it != NULL) { ASN1_VALUE *value = ASN1_item_d2i(NULL, &p, length, it); if (value == NULL) { BIO_printf(bio_err, "Error parsing item %s\n", it->sname); ERR_print_errors(bio_err); goto end; } ASN1_item_print(bio_out, value, 0, it, NULL); ASN1_item_free(value, it); } else { if (!ASN1_parse_dump(bio_out, p, length, indent, dump)) { ERR_print_errors(bio_err); goto end; } } } ret = 0; end: BIO_free(derout); BIO_free(in); BIO_free(b64); if (ret != 0) ERR_print_errors(bio_err); BUF_MEM_free(buf); OPENSSL_free(name); OPENSSL_free(header); ASN1_TYPE_free(at); sk_OPENSSL_STRING_free(osk); return ret; } static int do_generate(char *genstr, const char *genconf, BUF_MEM *buf) { CONF *cnf = NULL; int len; unsigned char *p; ASN1_TYPE *atyp = NULL; if (genconf != NULL) { if ((cnf = app_load_config(genconf)) == NULL) goto err; if (genstr == NULL) genstr = NCONF_get_string(cnf, "default", "asn1"); if (genstr == NULL) { BIO_printf(bio_err, "Can't find 'asn1' in '%s'\n", genconf); goto err; } } atyp = ASN1_generate_nconf(genstr, cnf); NCONF_free(cnf); cnf = NULL; if (atyp == NULL) return -1; len = i2d_ASN1_TYPE(atyp, NULL); if (len <= 0) goto err; if (!BUF_MEM_grow(buf, len)) goto err; p = (unsigned char *)buf->data; i2d_ASN1_TYPE(atyp, &p); ASN1_TYPE_free(atyp); return len; err: NCONF_free(cnf); ASN1_TYPE_free(atyp); return -1; }
./openssl/apps/crl.c
/* * Copyright 1995-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 "apps.h" #include "progs.h" #include <openssl/bio.h> #include <openssl/err.h> #include <openssl/x509.h> #include <openssl/x509v3.h> #include <openssl/pem.h> typedef enum OPTION_choice { OPT_COMMON, OPT_INFORM, OPT_IN, OPT_OUTFORM, OPT_OUT, OPT_KEYFORM, OPT_KEY, OPT_ISSUER, OPT_LASTUPDATE, OPT_NEXTUPDATE, OPT_FINGERPRINT, OPT_CRLNUMBER, OPT_BADSIG, OPT_GENDELTA, OPT_CAPATH, OPT_CAFILE, OPT_CASTORE, OPT_NOCAPATH, OPT_NOCAFILE, OPT_NOCASTORE, OPT_VERIFY, OPT_DATEOPT, OPT_TEXT, OPT_HASH, OPT_HASH_OLD, OPT_NOOUT, OPT_NAMEOPT, OPT_MD, OPT_PROV_ENUM } OPTION_CHOICE; const OPTIONS crl_options[] = { OPT_SECTION("General"), {"help", OPT_HELP, '-', "Display this summary"}, {"verify", OPT_VERIFY, '-', "Verify CRL signature"}, OPT_SECTION("Input"), {"in", OPT_IN, '<', "Input file - default stdin"}, {"inform", OPT_INFORM, 'F', "CRL input format (DER or PEM); has no effect"}, {"key", OPT_KEY, '<', "CRL signing Private key to use"}, {"keyform", OPT_KEYFORM, 'F', "Private key file format (DER/PEM/P12); has no effect"}, OPT_SECTION("Output"), {"out", OPT_OUT, '>', "output file - default stdout"}, {"outform", OPT_OUTFORM, 'F', "Output format - default PEM"}, {"dateopt", OPT_DATEOPT, 's', "Datetime format used for printing. (rfc_822/iso_8601). Default is rfc_822."}, {"text", OPT_TEXT, '-', "Print out a text format version"}, {"hash", OPT_HASH, '-', "Print hash value"}, #ifndef OPENSSL_NO_MD5 {"hash_old", OPT_HASH_OLD, '-', "Print old-style (MD5) hash value"}, #endif {"nameopt", OPT_NAMEOPT, 's', "Certificate subject/issuer name printing options"}, {"", OPT_MD, '-', "Any supported digest"}, OPT_SECTION("CRL"), {"issuer", OPT_ISSUER, '-', "Print issuer DN"}, {"lastupdate", OPT_LASTUPDATE, '-', "Set lastUpdate field"}, {"nextupdate", OPT_NEXTUPDATE, '-', "Set nextUpdate field"}, {"noout", OPT_NOOUT, '-', "No CRL output"}, {"fingerprint", OPT_FINGERPRINT, '-', "Print the crl fingerprint"}, {"crlnumber", OPT_CRLNUMBER, '-', "Print CRL number"}, {"badsig", OPT_BADSIG, '-', "Corrupt last byte of loaded CRL signature (for test)" }, {"gendelta", OPT_GENDELTA, '<', "Other CRL to compare/diff to the Input one"}, OPT_SECTION("Certificate"), {"CApath", OPT_CAPATH, '/', "Verify CRL using certificates in dir"}, {"CAfile", OPT_CAFILE, '<', "Verify CRL using certificates in file name"}, {"CAstore", OPT_CASTORE, ':', "Verify CRL using certificates in store URI"}, {"no-CAfile", OPT_NOCAFILE, '-', "Do not load the default certificates file"}, {"no-CApath", OPT_NOCAPATH, '-', "Do not load certificates from the default certificates directory"}, {"no-CAstore", OPT_NOCASTORE, '-', "Do not load certificates from the default certificates store"}, OPT_PROV_OPTIONS, {NULL} }; int crl_main(int argc, char **argv) { X509_CRL *x = NULL; BIO *out = NULL; X509_STORE *store = NULL; X509_STORE_CTX *ctx = NULL; X509_LOOKUP *lookup = NULL; X509_OBJECT *xobj = NULL; EVP_PKEY *pkey; EVP_MD *digest = (EVP_MD *)EVP_sha1(); char *infile = NULL, *outfile = NULL, *crldiff = NULL, *keyfile = NULL; char *digestname = NULL; const char *CAfile = NULL, *CApath = NULL, *CAstore = NULL, *prog; OPTION_CHOICE o; int hash = 0, issuer = 0, lastupdate = 0, nextupdate = 0, noout = 0; int informat = FORMAT_UNDEF, outformat = FORMAT_PEM, keyformat = FORMAT_UNDEF; int ret = 1, num = 0, badsig = 0, fingerprint = 0, crlnumber = 0; int text = 0, do_ver = 0, noCAfile = 0, noCApath = 0, noCAstore = 0; unsigned long dateopt = ASN1_DTFLGS_RFC822; int i; #ifndef OPENSSL_NO_MD5 int hash_old = 0; #endif opt_set_unknown_name("digest"); prog = opt_init(argc, argv, crl_options); while ((o = opt_next()) != OPT_EOF) { switch (o) { case OPT_EOF: case OPT_ERR: opthelp: BIO_printf(bio_err, "%s: Use -help for summary.\n", prog); goto end; case OPT_HELP: opt_help(crl_options); ret = 0; goto end; case OPT_INFORM: if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &informat)) goto opthelp; break; case OPT_IN: infile = opt_arg(); break; case OPT_OUTFORM: if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &outformat)) goto opthelp; break; case OPT_OUT: outfile = opt_arg(); break; case OPT_KEYFORM: if (!opt_format(opt_arg(), OPT_FMT_ANY, &keyformat)) goto opthelp; break; case OPT_KEY: keyfile = opt_arg(); break; case OPT_GENDELTA: crldiff = opt_arg(); break; case OPT_CAPATH: CApath = opt_arg(); do_ver = 1; break; case OPT_CAFILE: CAfile = opt_arg(); do_ver = 1; break; case OPT_CASTORE: CAstore = opt_arg(); do_ver = 1; break; case OPT_NOCAPATH: noCApath = 1; break; case OPT_NOCAFILE: noCAfile = 1; break; case OPT_NOCASTORE: noCAstore = 1; break; case OPT_HASH_OLD: #ifndef OPENSSL_NO_MD5 hash_old = ++num; #endif break; case OPT_VERIFY: do_ver = 1; break; case OPT_DATEOPT: if (!set_dateopt(&dateopt, opt_arg())) goto opthelp; break; case OPT_TEXT: text = 1; break; case OPT_HASH: hash = ++num; break; case OPT_ISSUER: issuer = ++num; break; case OPT_LASTUPDATE: lastupdate = ++num; break; case OPT_NEXTUPDATE: nextupdate = ++num; break; case OPT_NOOUT: noout = 1; break; case OPT_FINGERPRINT: fingerprint = ++num; break; case OPT_CRLNUMBER: crlnumber = ++num; break; case OPT_BADSIG: badsig = 1; break; case OPT_NAMEOPT: if (!set_nameopt(opt_arg())) goto opthelp; break; case OPT_MD: digestname = opt_unknown(); break; case OPT_PROV_CASES: if (!opt_provider(o)) goto end; break; } } /* No remaining args. */ if (!opt_check_rest_arg(NULL)) goto opthelp; if (!opt_md(digestname, &digest)) goto opthelp; x = load_crl(infile, informat, 1, "CRL"); if (x == NULL) goto end; if (do_ver) { if ((store = setup_verify(CAfile, noCAfile, CApath, noCApath, CAstore, noCAstore)) == NULL) goto end; lookup = X509_STORE_add_lookup(store, X509_LOOKUP_file()); if (lookup == NULL) goto end; ctx = X509_STORE_CTX_new(); if (ctx == NULL || !X509_STORE_CTX_init(ctx, store, NULL, NULL)) { BIO_printf(bio_err, "Error initialising X509 store\n"); goto end; } xobj = X509_STORE_CTX_get_obj_by_subject(ctx, X509_LU_X509, X509_CRL_get_issuer(x)); if (xobj == NULL) { BIO_printf(bio_err, "Error getting CRL issuer certificate\n"); goto end; } pkey = X509_get_pubkey(X509_OBJECT_get0_X509(xobj)); X509_OBJECT_free(xobj); if (pkey == NULL) { BIO_printf(bio_err, "Error getting CRL issuer public key\n"); goto end; } i = X509_CRL_verify(x, pkey); EVP_PKEY_free(pkey); if (i < 0) goto end; if (i == 0) BIO_printf(bio_err, "verify failure\n"); else BIO_printf(bio_err, "verify OK\n"); } if (crldiff != NULL) { X509_CRL *newcrl, *delta; if (!keyfile) { BIO_puts(bio_err, "Missing CRL signing key\n"); goto end; } newcrl = load_crl(crldiff, informat, 0, "other CRL"); if (!newcrl) goto end; pkey = load_key(keyfile, keyformat, 0, NULL, NULL, "CRL signing key"); if (pkey == NULL) { X509_CRL_free(newcrl); goto end; } delta = X509_CRL_diff(x, newcrl, pkey, digest, 0); X509_CRL_free(newcrl); EVP_PKEY_free(pkey); if (delta) { X509_CRL_free(x); x = delta; } else { BIO_puts(bio_err, "Error creating delta CRL\n"); goto end; } } if (badsig) { const ASN1_BIT_STRING *sig; X509_CRL_get0_signature(x, &sig, NULL); corrupt_signature(sig); } if (num) { for (i = 1; i <= num; i++) { if (issuer == i) { print_name(bio_out, "issuer=", X509_CRL_get_issuer(x)); } if (crlnumber == i) { ASN1_INTEGER *crlnum; crlnum = X509_CRL_get_ext_d2i(x, NID_crl_number, NULL, NULL); BIO_printf(bio_out, "crlNumber="); if (crlnum) { BIO_puts(bio_out, "0x"); i2a_ASN1_INTEGER(bio_out, crlnum); ASN1_INTEGER_free(crlnum); } else { BIO_puts(bio_out, "<NONE>"); } BIO_printf(bio_out, "\n"); } if (hash == i) { int ok; unsigned long hash_value = X509_NAME_hash_ex(X509_CRL_get_issuer(x), app_get0_libctx(), app_get0_propq(), &ok); if (num > 1) BIO_printf(bio_out, "issuer name hash="); if (ok) { BIO_printf(bio_out, "%08lx\n", hash_value); } else { BIO_puts(bio_out, "<ERROR>"); goto end; } } #ifndef OPENSSL_NO_MD5 if (hash_old == i) { if (num > 1) BIO_printf(bio_out, "issuer name old hash="); BIO_printf(bio_out, "%08lx\n", X509_NAME_hash_old(X509_CRL_get_issuer(x))); } #endif if (lastupdate == i) { BIO_printf(bio_out, "lastUpdate="); ASN1_TIME_print_ex(bio_out, X509_CRL_get0_lastUpdate(x), dateopt); BIO_printf(bio_out, "\n"); } if (nextupdate == i) { BIO_printf(bio_out, "nextUpdate="); if (X509_CRL_get0_nextUpdate(x)) ASN1_TIME_print_ex(bio_out, X509_CRL_get0_nextUpdate(x), dateopt); else BIO_printf(bio_out, "NONE"); BIO_printf(bio_out, "\n"); } if (fingerprint == i) { int j; unsigned int n; unsigned char md[EVP_MAX_MD_SIZE]; if (!X509_CRL_digest(x, digest, md, &n)) { BIO_printf(bio_err, "out of memory\n"); goto end; } BIO_printf(bio_out, "%s Fingerprint=", EVP_MD_get0_name(digest)); for (j = 0; j < (int)n; j++) { BIO_printf(bio_out, "%02X%c", md[j], (j + 1 == (int)n) ? '\n' : ':'); } } } } out = bio_open_default(outfile, 'w', outformat); if (out == NULL) goto end; if (text) X509_CRL_print_ex(out, x, get_nameopt()); if (noout) { ret = 0; goto end; } if (outformat == FORMAT_ASN1) i = (int)i2d_X509_CRL_bio(out, x); else i = PEM_write_bio_X509_CRL(out, x); if (!i) { BIO_printf(bio_err, "unable to write CRL\n"); goto end; } ret = 0; end: if (ret != 0) ERR_print_errors(bio_err); BIO_free_all(out); EVP_MD_free(digest); X509_CRL_free(x); X509_STORE_CTX_free(ctx); X509_STORE_free(store); return ret; }
./openssl/apps/cms.c
/* * Copyright 2008-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 */ /* CMS utility function */ #include <stdio.h> #include <string.h> #include "apps.h" #include "progs.h" #include <openssl/crypto.h> #include <openssl/pem.h> #include <openssl/err.h> #include <openssl/x509_vfy.h> #include <openssl/x509v3.h> #include <openssl/cms.h> static int save_certs(char *signerfile, STACK_OF(X509) *signers); static int cms_cb(int ok, X509_STORE_CTX *ctx); static void receipt_request_print(CMS_ContentInfo *cms); static CMS_ReceiptRequest *make_receipt_request(STACK_OF(OPENSSL_STRING) *rr_to, int rr_allorfirst, STACK_OF(OPENSSL_STRING) *rr_from); static int cms_set_pkey_param(EVP_PKEY_CTX *pctx, STACK_OF(OPENSSL_STRING) *param); #define SMIME_OP 0x100 #define SMIME_IP 0x200 #define SMIME_SIGNERS 0x400 #define SMIME_ENCRYPT (1 | SMIME_OP) #define SMIME_DECRYPT (2 | SMIME_IP) #define SMIME_SIGN (3 | SMIME_OP | SMIME_SIGNERS) #define SMIME_VERIFY (4 | SMIME_IP) #define SMIME_RESIGN (5 | SMIME_IP | SMIME_OP | SMIME_SIGNERS) #define SMIME_SIGN_RECEIPT (6 | SMIME_IP | SMIME_OP) #define SMIME_VERIFY_RECEIPT (7 | SMIME_IP) #define SMIME_DIGEST_CREATE (8 | SMIME_OP) #define SMIME_DIGEST_VERIFY (9 | SMIME_IP) #define SMIME_COMPRESS (10 | SMIME_OP) #define SMIME_UNCOMPRESS (11 | SMIME_IP) #define SMIME_ENCRYPTED_ENCRYPT (12 | SMIME_OP) #define SMIME_ENCRYPTED_DECRYPT (13 | SMIME_IP) #define SMIME_DATA_CREATE (14 | SMIME_OP) #define SMIME_DATA_OUT (15 | SMIME_IP) #define SMIME_CMSOUT (16 | SMIME_IP | SMIME_OP) static int verify_err = 0; typedef struct cms_key_param_st cms_key_param; struct cms_key_param_st { int idx; STACK_OF(OPENSSL_STRING) *param; cms_key_param *next; }; typedef enum OPTION_choice { OPT_COMMON, OPT_INFORM, OPT_OUTFORM, OPT_IN, OPT_OUT, OPT_ENCRYPT, OPT_DECRYPT, OPT_SIGN, OPT_CADES, OPT_SIGN_RECEIPT, OPT_RESIGN, OPT_VERIFY, OPT_VERIFY_RETCODE, OPT_VERIFY_RECEIPT, OPT_CMSOUT, OPT_DATA_OUT, OPT_DATA_CREATE, OPT_DIGEST_VERIFY, OPT_DIGEST, OPT_DIGEST_CREATE, OPT_COMPRESS, OPT_UNCOMPRESS, OPT_ED_DECRYPT, OPT_ED_ENCRYPT, OPT_DEBUG_DECRYPT, OPT_TEXT, OPT_ASCIICRLF, OPT_NOINTERN, OPT_NOVERIFY, OPT_NOCERTS, OPT_NOATTR, OPT_NODETACH, OPT_NOSMIMECAP, OPT_BINARY, OPT_KEYID, OPT_NOSIGS, OPT_NO_CONTENT_VERIFY, OPT_NO_ATTR_VERIFY, OPT_INDEF, OPT_NOINDEF, OPT_CRLFEOL, OPT_NOOUT, OPT_RR_PRINT, OPT_RR_ALL, OPT_RR_FIRST, OPT_RCTFORM, OPT_CERTFILE, OPT_CAFILE, OPT_CAPATH, OPT_CASTORE, OPT_NOCAPATH, OPT_NOCAFILE, OPT_NOCASTORE, OPT_CONTENT, OPT_PRINT, OPT_NAMEOPT, OPT_SECRETKEY, OPT_SECRETKEYID, OPT_PWRI_PASSWORD, OPT_ECONTENT_TYPE, OPT_PASSIN, OPT_TO, OPT_FROM, OPT_SUBJECT, OPT_SIGNER, OPT_RECIP, OPT_CERTSOUT, OPT_MD, OPT_INKEY, OPT_KEYFORM, OPT_KEYOPT, OPT_RR_FROM, OPT_RR_TO, OPT_AES128_WRAP, OPT_AES192_WRAP, OPT_AES256_WRAP, OPT_3DES_WRAP, OPT_WRAP, OPT_ENGINE, OPT_R_ENUM, OPT_PROV_ENUM, OPT_CONFIG, OPT_V_ENUM, OPT_CIPHER, OPT_ORIGINATOR } OPTION_CHOICE; const OPTIONS cms_options[] = { {OPT_HELP_STR, 1, '-', "Usage: %s [options] [cert...]\n"}, {"help", OPT_HELP, '-', "Display this summary"}, OPT_SECTION("General"), {"in", OPT_IN, '<', "Input file"}, {"out", OPT_OUT, '>', "Output file"}, OPT_CONFIG_OPTION, OPT_SECTION("Operation"), {"encrypt", OPT_ENCRYPT, '-', "Encrypt message"}, {"decrypt", OPT_DECRYPT, '-', "Decrypt encrypted message"}, {"sign", OPT_SIGN, '-', "Sign message"}, {"verify", OPT_VERIFY, '-', "Verify signed message"}, {"resign", OPT_RESIGN, '-', "Resign a signed message"}, {"sign_receipt", OPT_SIGN_RECEIPT, '-', "Generate a signed receipt for a message"}, {"verify_receipt", OPT_VERIFY_RECEIPT, '<', "Verify receipts; exit if receipt signatures do not verify"}, {"digest", OPT_DIGEST, 's', "Sign a pre-computed digest in hex notation"}, {"digest_create", OPT_DIGEST_CREATE, '-', "Create a CMS \"DigestedData\" object"}, {"digest_verify", OPT_DIGEST_VERIFY, '-', "Verify a CMS \"DigestedData\" object and output it"}, {"compress", OPT_COMPRESS, '-', "Create a CMS \"CompressedData\" object"}, {"uncompress", OPT_UNCOMPRESS, '-', "Uncompress a CMS \"CompressedData\" object"}, {"EncryptedData_encrypt", OPT_ED_ENCRYPT, '-', "Create CMS \"EncryptedData\" object using symmetric key"}, {"EncryptedData_decrypt", OPT_ED_DECRYPT, '-', "Decrypt CMS \"EncryptedData\" object using symmetric key"}, {"data_create", OPT_DATA_CREATE, '-', "Create a CMS \"Data\" object"}, {"data_out", OPT_DATA_OUT, '-', "Copy CMS \"Data\" object to output"}, {"cmsout", OPT_CMSOUT, '-', "Output CMS structure"}, OPT_SECTION("File format"), {"inform", OPT_INFORM, 'c', "Input format SMIME (default), PEM or DER"}, {"outform", OPT_OUTFORM, 'c', "Output format SMIME (default), PEM or DER"}, {"rctform", OPT_RCTFORM, 'F', "Receipt file format"}, {"stream", OPT_INDEF, '-', "Enable CMS streaming"}, {"indef", OPT_INDEF, '-', "Same as -stream"}, {"noindef", OPT_NOINDEF, '-', "Disable CMS streaming"}, {"binary", OPT_BINARY, '-', "Treat input as binary: do not translate to canonical form"}, {"crlfeol", OPT_CRLFEOL, '-', "Use CRLF as EOL termination instead of CR only" }, {"asciicrlf", OPT_ASCIICRLF, '-', "Perform CRLF canonicalisation when signing"}, OPT_SECTION("Keys and passwords"), {"pwri_password", OPT_PWRI_PASSWORD, 's', "Specific password for recipient"}, {"secretkey", OPT_SECRETKEY, 's', "Use specified hex-encoded key to decrypt/encrypt recipients or content"}, {"secretkeyid", OPT_SECRETKEYID, 's', "Identity of the -secretkey for CMS \"KEKRecipientInfo\" object"}, {"inkey", OPT_INKEY, 's', "Input private key (if not signer or recipient)"}, {"passin", OPT_PASSIN, 's', "Input file pass phrase source"}, {"keyopt", OPT_KEYOPT, 's', "Set public key parameters as n:v pairs"}, {"keyform", OPT_KEYFORM, 'f', "Input private key format (ENGINE, other values ignored)"}, #ifndef OPENSSL_NO_ENGINE {"engine", OPT_ENGINE, 's', "Use engine e, possibly a hardware device"}, #endif OPT_PROV_OPTIONS, OPT_R_OPTIONS, OPT_SECTION("Encryption and decryption"), {"originator", OPT_ORIGINATOR, 's', "Originator certificate file"}, {"recip", OPT_RECIP, '<', "Recipient cert file"}, {"cert...", OPT_PARAM, '.', "Recipient certs (optional; used only when encrypting)"}, {"", OPT_CIPHER, '-', "The encryption algorithm to use (any supported cipher)"}, {"wrap", OPT_WRAP, 's', "Key wrap algorithm to use when encrypting with key agreement"}, {"aes128-wrap", OPT_AES128_WRAP, '-', "Use AES128 to wrap key"}, {"aes192-wrap", OPT_AES192_WRAP, '-', "Use AES192 to wrap key"}, {"aes256-wrap", OPT_AES256_WRAP, '-', "Use AES256 to wrap key"}, {"des3-wrap", OPT_3DES_WRAP, '-', "Use 3DES-EDE to wrap key"}, {"debug_decrypt", OPT_DEBUG_DECRYPT, '-', "Disable MMA protection, return error if no recipient found (see doc)"}, OPT_SECTION("Signing"), {"md", OPT_MD, 's', "Digest algorithm to use"}, {"signer", OPT_SIGNER, 's', "Signer certificate input file"}, {"certfile", OPT_CERTFILE, '<', "Other certificates file"}, {"cades", OPT_CADES, '-', "Include signingCertificate attribute (CAdES-BES)"}, {"nodetach", OPT_NODETACH, '-', "Use opaque signing"}, {"nocerts", OPT_NOCERTS, '-', "Don't include signer's certificate when signing"}, {"noattr", OPT_NOATTR, '-', "Don't include any signed attributes"}, {"nosmimecap", OPT_NOSMIMECAP, '-', "Omit the SMIMECapabilities attribute"}, {"receipt_request_all", OPT_RR_ALL, '-', "When signing, create a receipt request for all recipients"}, {"receipt_request_first", OPT_RR_FIRST, '-', "When signing, create a receipt request for first recipient"}, {"receipt_request_from", OPT_RR_FROM, 's', "Create signed receipt request with specified email address"}, {"receipt_request_to", OPT_RR_TO, 's', "Create signed receipt targeted to specified address"}, OPT_SECTION("Verification"), {"signer", OPT_DUP, 's', "Signer certificate(s) output file"}, {"content", OPT_CONTENT, '<', "Supply or override content for detached signature"}, {"no_content_verify", OPT_NO_CONTENT_VERIFY, '-', "Do not verify signed content signatures"}, {"no_attr_verify", OPT_NO_ATTR_VERIFY, '-', "Do not verify signed attribute signatures"}, {"nosigs", OPT_NOSIGS, '-', "Don't verify message signature"}, {"noverify", OPT_NOVERIFY, '-', "Don't verify signers certificate"}, {"nointern", OPT_NOINTERN, '-', "Don't search certificates in message for signer"}, {"cades", OPT_DUP, '-', "Check signingCertificate (CAdES-BES)"}, {"verify_retcode", OPT_VERIFY_RETCODE, '-', "Exit non-zero on verification failure"}, {"CAfile", OPT_CAFILE, '<', "Trusted certificates file"}, {"CApath", OPT_CAPATH, '/', "Trusted certificates directory"}, {"CAstore", OPT_CASTORE, ':', "Trusted certificates store URI"}, {"no-CAfile", OPT_NOCAFILE, '-', "Do not load the default certificates file"}, {"no-CApath", OPT_NOCAPATH, '-', "Do not load certificates from the default certificates directory"}, {"no-CAstore", OPT_NOCASTORE, '-', "Do not load certificates from the default certificates store"}, OPT_SECTION("Output"), {"keyid", OPT_KEYID, '-', "Use subject key identifier"}, {"econtent_type", OPT_ECONTENT_TYPE, 's', "OID for external content"}, {"text", OPT_TEXT, '-', "Include or delete text MIME headers"}, {"certsout", OPT_CERTSOUT, '>', "Certificate output file"}, {"to", OPT_TO, 's', "To address"}, {"from", OPT_FROM, 's', "From address"}, {"subject", OPT_SUBJECT, 's', "Subject"}, OPT_SECTION("Printing"), {"noout", OPT_NOOUT, '-', "For the -cmsout operation do not output the parsed CMS structure"}, {"print", OPT_PRINT, '-', "For the -cmsout operation print out all fields of the CMS structure"}, {"nameopt", OPT_NAMEOPT, 's', "For the -print option specifies various strings printing options"}, {"receipt_request_print", OPT_RR_PRINT, '-', "Print CMS Receipt Request" }, OPT_V_OPTIONS, {NULL} }; static CMS_ContentInfo *load_content_info(int informat, BIO *in, int flags, BIO **indata, const char *name) { CMS_ContentInfo *ret, *ci; ret = CMS_ContentInfo_new_ex(app_get0_libctx(), app_get0_propq()); if (ret == NULL) { BIO_printf(bio_err, "Error allocating CMS_contentinfo\n"); return NULL; } switch (informat) { case FORMAT_SMIME: ci = SMIME_read_CMS_ex(in, flags, indata, &ret); break; case FORMAT_PEM: ci = PEM_read_bio_CMS(in, &ret, NULL, NULL); break; case FORMAT_ASN1: ci = d2i_CMS_bio(in, &ret); break; default: BIO_printf(bio_err, "Bad input format for %s\n", name); goto err; } if (ci == NULL) { BIO_printf(bio_err, "Error reading %s Content Info\n", name); goto err; } return ret; err: CMS_ContentInfo_free(ret); return NULL; } int cms_main(int argc, char **argv) { CONF *conf = NULL; ASN1_OBJECT *econtent_type = NULL; BIO *in = NULL, *out = NULL, *indata = NULL, *rctin = NULL; CMS_ContentInfo *cms = NULL, *rcms = NULL; CMS_ReceiptRequest *rr = NULL; ENGINE *e = NULL; EVP_PKEY *key = NULL; EVP_CIPHER *cipher = NULL, *wrap_cipher = NULL; EVP_MD *sign_md = NULL; STACK_OF(OPENSSL_STRING) *rr_to = NULL, *rr_from = NULL; STACK_OF(OPENSSL_STRING) *sksigners = NULL, *skkeys = NULL; STACK_OF(X509) *encerts = sk_X509_new_null(), *other = NULL; X509 *cert = NULL, *recip = NULL, *signer = NULL, *originator = NULL; X509_STORE *store = NULL; X509_VERIFY_PARAM *vpm = X509_VERIFY_PARAM_new(); char *certfile = NULL, *keyfile = NULL, *contfile = NULL; const char *CAfile = NULL, *CApath = NULL, *CAstore = NULL; char *certsoutfile = NULL, *digestname = NULL, *wrapname = NULL; int noCAfile = 0, noCApath = 0, noCAstore = 0; char *digesthex = NULL; unsigned char *digestbin = NULL; long digestlen = 0; char *infile = NULL, *outfile = NULL, *rctfile = NULL; char *passinarg = NULL, *passin = NULL, *signerfile = NULL; char *originatorfile = NULL, *recipfile = NULL, *ciphername = NULL; char *to = NULL, *from = NULL, *subject = NULL, *prog; cms_key_param *key_first = NULL, *key_param = NULL; int flags = CMS_DETACHED, binary_files = 0; int noout = 0, print = 0, keyidx = -1, vpmtouched = 0; int informat = FORMAT_SMIME, outformat = FORMAT_SMIME; int operation = 0, ret = 1, rr_print = 0, rr_allorfirst = -1; int verify_retcode = 0, rctformat = FORMAT_SMIME, keyform = FORMAT_UNDEF; size_t secret_keylen = 0, secret_keyidlen = 0; unsigned char *pwri_pass = NULL, *pwri_tmp = NULL; unsigned char *secret_key = NULL, *secret_keyid = NULL; long ltmp; const char *mime_eol = "\n"; OPTION_CHOICE o; OSSL_LIB_CTX *libctx = app_get0_libctx(); if (encerts == NULL || vpm == NULL) goto end; opt_set_unknown_name("cipher"); prog = opt_init(argc, argv, cms_options); while ((o = opt_next()) != OPT_EOF) { switch (o) { case OPT_EOF: case OPT_ERR: opthelp: BIO_printf(bio_err, "%s: Use -help for summary.\n", prog); goto end; case OPT_HELP: opt_help(cms_options); ret = 0; goto end; case OPT_INFORM: if (!opt_format(opt_arg(), OPT_FMT_PDS, &informat)) goto opthelp; break; case OPT_OUTFORM: if (!opt_format(opt_arg(), OPT_FMT_PDS, &outformat)) goto opthelp; break; case OPT_OUT: outfile = opt_arg(); break; case OPT_ENCRYPT: operation = SMIME_ENCRYPT; break; case OPT_DECRYPT: operation = SMIME_DECRYPT; break; case OPT_SIGN: operation = SMIME_SIGN; break; case OPT_VERIFY: operation = SMIME_VERIFY; break; case OPT_RESIGN: operation = SMIME_RESIGN; break; case OPT_SIGN_RECEIPT: operation = SMIME_SIGN_RECEIPT; break; case OPT_VERIFY_RECEIPT: operation = SMIME_VERIFY_RECEIPT; rctfile = opt_arg(); break; case OPT_VERIFY_RETCODE: verify_retcode = 1; break; case OPT_DIGEST_CREATE: operation = SMIME_DIGEST_CREATE; break; case OPT_DIGEST: digesthex = opt_arg(); break; case OPT_DIGEST_VERIFY: operation = SMIME_DIGEST_VERIFY; break; case OPT_COMPRESS: operation = SMIME_COMPRESS; break; case OPT_UNCOMPRESS: operation = SMIME_UNCOMPRESS; break; case OPT_ED_ENCRYPT: operation = SMIME_ENCRYPTED_ENCRYPT; break; case OPT_ED_DECRYPT: operation = SMIME_ENCRYPTED_DECRYPT; break; case OPT_DATA_CREATE: operation = SMIME_DATA_CREATE; break; case OPT_DATA_OUT: operation = SMIME_DATA_OUT; break; case OPT_CMSOUT: operation = SMIME_CMSOUT; break; case OPT_DEBUG_DECRYPT: flags |= CMS_DEBUG_DECRYPT; break; case OPT_TEXT: flags |= CMS_TEXT; break; case OPT_ASCIICRLF: flags |= CMS_ASCIICRLF; break; case OPT_NOINTERN: flags |= CMS_NOINTERN; break; case OPT_NOVERIFY: flags |= CMS_NO_SIGNER_CERT_VERIFY; break; case OPT_NOCERTS: flags |= CMS_NOCERTS; break; case OPT_NOATTR: flags |= CMS_NOATTR; break; case OPT_NODETACH: flags &= ~CMS_DETACHED; break; case OPT_NOSMIMECAP: flags |= CMS_NOSMIMECAP; break; case OPT_BINARY: flags |= CMS_BINARY; break; case OPT_CADES: flags |= CMS_CADES; break; case OPT_KEYID: flags |= CMS_USE_KEYID; break; case OPT_NOSIGS: flags |= CMS_NOSIGS; break; case OPT_NO_CONTENT_VERIFY: flags |= CMS_NO_CONTENT_VERIFY; break; case OPT_NO_ATTR_VERIFY: flags |= CMS_NO_ATTR_VERIFY; break; case OPT_INDEF: flags |= CMS_STREAM; break; case OPT_NOINDEF: flags &= ~CMS_STREAM; break; case OPT_CRLFEOL: mime_eol = "\r\n"; flags |= CMS_CRLFEOL; break; case OPT_NOOUT: noout = 1; break; case OPT_RR_PRINT: rr_print = 1; break; case OPT_RR_ALL: rr_allorfirst = 0; break; case OPT_RR_FIRST: rr_allorfirst = 1; break; case OPT_RCTFORM: if (!opt_format(opt_arg(), OPT_FMT_PEMDER | OPT_FMT_SMIME, &rctformat)) goto opthelp; break; case OPT_CERTFILE: certfile = opt_arg(); break; case OPT_CAFILE: CAfile = opt_arg(); break; case OPT_CAPATH: CApath = opt_arg(); break; case OPT_CASTORE: CAstore = opt_arg(); break; case OPT_NOCAFILE: noCAfile = 1; break; case OPT_NOCAPATH: noCApath = 1; break; case OPT_NOCASTORE: noCAstore = 1; break; case OPT_IN: infile = opt_arg(); break; case OPT_CONTENT: contfile = opt_arg(); break; case OPT_RR_FROM: if (rr_from == NULL && (rr_from = sk_OPENSSL_STRING_new_null()) == NULL) goto end; sk_OPENSSL_STRING_push(rr_from, opt_arg()); break; case OPT_RR_TO: if (rr_to == NULL && (rr_to = sk_OPENSSL_STRING_new_null()) == NULL) goto end; sk_OPENSSL_STRING_push(rr_to, opt_arg()); break; case OPT_PRINT: noout = print = 1; break; case OPT_NAMEOPT: if (!set_nameopt(opt_arg())) goto opthelp; break; case OPT_SECRETKEY: if (secret_key != NULL) { BIO_printf(bio_err, "Invalid key (supplied twice) %s\n", opt_arg()); goto opthelp; } secret_key = OPENSSL_hexstr2buf(opt_arg(), &ltmp); if (secret_key == NULL) { BIO_printf(bio_err, "Invalid key %s\n", opt_arg()); goto end; } secret_keylen = (size_t)ltmp; break; case OPT_SECRETKEYID: if (secret_keyid != NULL) { BIO_printf(bio_err, "Invalid id (supplied twice) %s\n", opt_arg()); goto opthelp; } secret_keyid = OPENSSL_hexstr2buf(opt_arg(), &ltmp); if (secret_keyid == NULL) { BIO_printf(bio_err, "Invalid id %s\n", opt_arg()); goto opthelp; } secret_keyidlen = (size_t)ltmp; break; case OPT_PWRI_PASSWORD: pwri_pass = (unsigned char *)opt_arg(); break; case OPT_ECONTENT_TYPE: if (econtent_type != NULL) { BIO_printf(bio_err, "Invalid OID (supplied twice) %s\n", opt_arg()); goto opthelp; } econtent_type = OBJ_txt2obj(opt_arg(), 0); if (econtent_type == NULL) { BIO_printf(bio_err, "Invalid OID %s\n", opt_arg()); goto opthelp; } break; case OPT_ENGINE: e = setup_engine(opt_arg(), 0); break; case OPT_PASSIN: passinarg = opt_arg(); break; case OPT_TO: to = opt_arg(); break; case OPT_FROM: from = opt_arg(); break; case OPT_SUBJECT: subject = opt_arg(); break; case OPT_CERTSOUT: certsoutfile = opt_arg(); break; case OPT_MD: digestname = opt_arg(); break; case OPT_SIGNER: /* If previous -signer argument add signer to list */ if (signerfile != NULL) { if (sksigners == NULL && (sksigners = sk_OPENSSL_STRING_new_null()) == NULL) goto end; sk_OPENSSL_STRING_push(sksigners, signerfile); if (keyfile == NULL) keyfile = signerfile; if (skkeys == NULL && (skkeys = sk_OPENSSL_STRING_new_null()) == NULL) goto end; sk_OPENSSL_STRING_push(skkeys, keyfile); keyfile = NULL; } signerfile = opt_arg(); break; case OPT_ORIGINATOR: originatorfile = opt_arg(); break; case OPT_INKEY: /* If previous -inkey argument add signer to list */ if (keyfile != NULL) { if (signerfile == NULL) { BIO_puts(bio_err, "Illegal -inkey without -signer\n"); goto end; } if (sksigners == NULL && (sksigners = sk_OPENSSL_STRING_new_null()) == NULL) goto end; sk_OPENSSL_STRING_push(sksigners, signerfile); signerfile = NULL; if (skkeys == NULL && (skkeys = sk_OPENSSL_STRING_new_null()) == NULL) goto end; sk_OPENSSL_STRING_push(skkeys, keyfile); } keyfile = opt_arg(); break; case OPT_KEYFORM: if (!opt_format(opt_arg(), OPT_FMT_ANY, &keyform)) goto opthelp; break; case OPT_RECIP: if (operation == SMIME_ENCRYPT) { cert = load_cert(opt_arg(), FORMAT_UNDEF, "recipient certificate file"); if (cert == NULL) goto end; if (!sk_X509_push(encerts, cert)) goto end; cert = NULL; } else { recipfile = opt_arg(); } break; case OPT_CIPHER: ciphername = opt_unknown(); break; case OPT_KEYOPT: keyidx = -1; if (operation == SMIME_ENCRYPT) { if (sk_X509_num(encerts) > 0) keyidx += sk_X509_num(encerts); } else { if (keyfile != NULL || signerfile != NULL) keyidx++; if (skkeys != NULL) keyidx += sk_OPENSSL_STRING_num(skkeys); } if (keyidx < 0) { BIO_printf(bio_err, "No key specified\n"); goto opthelp; } if (key_param == NULL || key_param->idx != keyidx) { cms_key_param *nparam; nparam = app_malloc(sizeof(*nparam), "key param buffer"); if ((nparam->param = sk_OPENSSL_STRING_new_null()) == NULL) { OPENSSL_free(nparam); goto end; } nparam->idx = keyidx; nparam->next = NULL; if (key_first == NULL) key_first = nparam; else key_param->next = nparam; key_param = nparam; } sk_OPENSSL_STRING_push(key_param->param, opt_arg()); break; case OPT_V_CASES: if (!opt_verify(o, vpm)) goto end; vpmtouched++; break; case OPT_R_CASES: if (!opt_rand(o)) goto end; break; case OPT_PROV_CASES: if (!opt_provider(o)) goto end; break; case OPT_CONFIG: conf = app_load_config_modules(opt_arg()); if (conf == NULL) goto end; break; case OPT_WRAP: wrapname = opt_arg(); break; case OPT_AES128_WRAP: case OPT_AES192_WRAP: case OPT_AES256_WRAP: case OPT_3DES_WRAP: wrapname = opt_flag() + 1; break; } } if (!app_RAND_load()) goto end; if (digestname != NULL) { if (!opt_md(digestname, &sign_md)) goto end; } if (!opt_cipher_any(ciphername, &cipher)) goto end; if (wrapname != NULL) { if (!opt_cipher_any(wrapname, &wrap_cipher)) goto end; } /* Remaining args are files to process. */ argc = opt_num_rest(); argv = opt_rest(); if ((rr_allorfirst != -1 || rr_from != NULL) && rr_to == NULL) { BIO_puts(bio_err, "No Signed Receipts Recipients\n"); goto opthelp; } if (!(operation & SMIME_SIGNERS) && (rr_to != NULL || rr_from != NULL)) { BIO_puts(bio_err, "Signed receipts only allowed with -sign\n"); goto opthelp; } if (!(operation & SMIME_SIGNERS) && (skkeys != NULL || sksigners != NULL)) { BIO_puts(bio_err, "Multiple signers or keys not allowed\n"); goto opthelp; } if ((flags & CMS_CADES) != 0) { if ((flags & CMS_NOATTR) != 0) { BIO_puts(bio_err, "Incompatible options: " "CAdES requires signed attributes\n"); goto opthelp; } if (operation == SMIME_VERIFY && (flags & (CMS_NO_SIGNER_CERT_VERIFY | CMS_NO_ATTR_VERIFY)) != 0) { BIO_puts(bio_err, "Incompatible options: CAdES validation requires" " certs and signed attributes validations\n"); goto opthelp; } } if (operation & SMIME_SIGNERS) { if (keyfile != NULL && signerfile == NULL) { BIO_puts(bio_err, "Illegal -inkey without -signer\n"); goto opthelp; } /* Check to see if any final signer needs to be appended */ if (signerfile != NULL) { if (sksigners == NULL && (sksigners = sk_OPENSSL_STRING_new_null()) == NULL) goto end; sk_OPENSSL_STRING_push(sksigners, signerfile); if (skkeys == NULL && (skkeys = sk_OPENSSL_STRING_new_null()) == NULL) goto end; if (keyfile == NULL) keyfile = signerfile; sk_OPENSSL_STRING_push(skkeys, keyfile); } if (sksigners == NULL) { BIO_printf(bio_err, "No signer certificate specified\n"); goto opthelp; } signerfile = NULL; keyfile = NULL; } else if (operation == SMIME_DECRYPT) { if (recipfile == NULL && keyfile == NULL && secret_key == NULL && pwri_pass == NULL) { BIO_printf(bio_err, "No recipient certificate or key specified\n"); goto opthelp; } } else if (operation == SMIME_ENCRYPT) { if (*argv == NULL && secret_key == NULL && pwri_pass == NULL && sk_X509_num(encerts) <= 0) { BIO_printf(bio_err, "No recipient(s) certificate(s) specified\n"); goto opthelp; } } else if (!operation) { BIO_printf(bio_err, "No operation option (-encrypt|-decrypt|-sign|-verify|...) specified.\n"); goto opthelp; } if (!app_passwd(passinarg, NULL, &passin, NULL)) { BIO_printf(bio_err, "Error getting password\n"); goto end; } ret = 2; if ((operation & SMIME_SIGNERS) == 0) { if ((flags & CMS_DETACHED) == 0) BIO_printf(bio_err, "Warning: -nodetach option is ignored for non-signing operation\n"); flags &= ~CMS_DETACHED; } if ((operation & SMIME_IP) == 0 && contfile != NULL) BIO_printf(bio_err, "Warning: -contfile option is ignored for the given operation\n"); if (operation != SMIME_ENCRYPT && *argv != NULL) BIO_printf(bio_err, "Warning: recipient certificate file parameters ignored for operation other than -encrypt\n"); if ((flags & CMS_BINARY) != 0) { if (!(operation & SMIME_OP)) outformat = FORMAT_BINARY; if (!(operation & SMIME_IP)) informat = FORMAT_BINARY; if ((operation & SMIME_SIGNERS) != 0 && (flags & CMS_DETACHED) != 0) binary_files = 1; if ((operation & SMIME_IP) != 0 && contfile == NULL) binary_files = 1; } if (operation == SMIME_ENCRYPT) { if (!cipher) { #ifndef OPENSSL_NO_DES cipher = (EVP_CIPHER *)EVP_des_ede3_cbc(); #else BIO_printf(bio_err, "No cipher selected\n"); goto end; #endif } if (secret_key && !secret_keyid) { BIO_printf(bio_err, "No secret key id\n"); goto end; } for (; *argv != NULL; argv++) { cert = load_cert(*argv, FORMAT_UNDEF, "recipient certificate file"); if (cert == NULL) goto end; if (!sk_X509_push(encerts, cert)) goto end; cert = NULL; } } if (certfile != NULL) { if (!load_certs(certfile, 0, &other, NULL, "certificate file")) { ERR_print_errors(bio_err); goto end; } } if (recipfile != NULL && (operation == SMIME_DECRYPT)) { if ((recip = load_cert(recipfile, FORMAT_UNDEF, "recipient certificate file")) == NULL) { ERR_print_errors(bio_err); goto end; } } if (originatorfile != NULL) { if ((originator = load_cert(originatorfile, FORMAT_UNDEF, "originator certificate file")) == NULL) { ERR_print_errors(bio_err); goto end; } } if (operation == SMIME_SIGN_RECEIPT) { if ((signer = load_cert(signerfile, FORMAT_UNDEF, "receipt signer certificate file")) == NULL) { ERR_print_errors(bio_err); goto end; } } if ((operation == SMIME_DECRYPT) || (operation == SMIME_ENCRYPT)) { if (keyfile == NULL) keyfile = recipfile; } else if ((operation == SMIME_SIGN) || (operation == SMIME_SIGN_RECEIPT)) { if (keyfile == NULL) keyfile = signerfile; } else { keyfile = NULL; } if (keyfile != NULL) { key = load_key(keyfile, keyform, 0, passin, e, "signing key"); if (key == NULL) goto end; } if (digesthex != NULL) { if (operation != SMIME_SIGN) { BIO_printf(bio_err, "Cannot use -digest for non-signing operation\n"); goto end; } if (infile != NULL || (flags & CMS_DETACHED) == 0 || (flags & CMS_STREAM) != 0) { BIO_printf(bio_err, "Cannot use -digest when -in, -nodetach or streaming is used\n"); goto end; } digestbin = OPENSSL_hexstr2buf(digesthex, &digestlen); if (digestbin == NULL) { BIO_printf(bio_err, "Invalid hex value after -digest\n"); goto end; } } else { in = bio_open_default(infile, 'r', binary_files ? FORMAT_BINARY : informat); if (in == NULL) goto end; } if (operation & SMIME_IP) { cms = load_content_info(informat, in, flags, &indata, "SMIME"); if (cms == NULL) goto end; if (contfile != NULL) { BIO_free(indata); if ((indata = BIO_new_file(contfile, "rb")) == NULL) { BIO_printf(bio_err, "Can't read content file %s\n", contfile); goto end; } } if (certsoutfile != NULL) { STACK_OF(X509) *allcerts; allcerts = CMS_get1_certs(cms); if (!save_certs(certsoutfile, allcerts)) { BIO_printf(bio_err, "Error writing certs to %s\n", certsoutfile); ret = 5; goto end; } OSSL_STACK_OF_X509_free(allcerts); } } if (rctfile != NULL) { char *rctmode = (rctformat == FORMAT_ASN1) ? "rb" : "r"; if ((rctin = BIO_new_file(rctfile, rctmode)) == NULL) { BIO_printf(bio_err, "Can't open receipt file %s\n", rctfile); goto end; } rcms = load_content_info(rctformat, rctin, 0, NULL, "receipt"); if (rcms == NULL) goto end; } out = bio_open_default(outfile, 'w', binary_files ? FORMAT_BINARY : outformat); if (out == NULL) goto end; if ((operation == SMIME_VERIFY) || (operation == SMIME_VERIFY_RECEIPT)) { if ((store = setup_verify(CAfile, noCAfile, CApath, noCApath, CAstore, noCAstore)) == NULL) goto end; X509_STORE_set_verify_cb(store, cms_cb); if (vpmtouched) X509_STORE_set1_param(store, vpm); } ret = 3; if (operation == SMIME_DATA_CREATE) { cms = CMS_data_create_ex(in, flags, libctx, app_get0_propq()); } else if (operation == SMIME_DIGEST_CREATE) { cms = CMS_digest_create_ex(in, sign_md, flags, libctx, app_get0_propq()); } else if (operation == SMIME_COMPRESS) { cms = CMS_compress(in, -1, flags); } else if (operation == SMIME_ENCRYPT) { int i; flags |= CMS_PARTIAL; cms = CMS_encrypt_ex(NULL, in, cipher, flags, libctx, app_get0_propq()); if (cms == NULL) goto end; for (i = 0; i < sk_X509_num(encerts); i++) { CMS_RecipientInfo *ri; cms_key_param *kparam; int tflags = flags | CMS_KEY_PARAM; /* This flag enforces allocating the EVP_PKEY_CTX for the recipient here */ EVP_PKEY_CTX *pctx; X509 *x = sk_X509_value(encerts, i); int res; for (kparam = key_first; kparam; kparam = kparam->next) { if (kparam->idx == i) { break; } } ri = CMS_add1_recipient(cms, x, key, originator, tflags); if (ri == NULL) goto end; pctx = CMS_RecipientInfo_get0_pkey_ctx(ri); if (kparam != NULL) { if (!cms_set_pkey_param(pctx, kparam->param)) goto end; } res = EVP_PKEY_CTX_ctrl(pctx, -1, -1, EVP_PKEY_CTRL_CIPHER, EVP_CIPHER_get_nid(cipher), NULL); if (res <= 0 && res != -2) goto end; if (CMS_RecipientInfo_type(ri) == CMS_RECIPINFO_AGREE && wrap_cipher != NULL) { EVP_CIPHER_CTX *wctx; wctx = CMS_RecipientInfo_kari_get0_ctx(ri); if (EVP_EncryptInit_ex(wctx, wrap_cipher, NULL, NULL, NULL) != 1) goto end; } } if (secret_key != NULL) { if (!CMS_add0_recipient_key(cms, NID_undef, secret_key, secret_keylen, secret_keyid, secret_keyidlen, NULL, NULL, NULL)) goto end; /* NULL these because call absorbs them */ secret_key = NULL; secret_keyid = NULL; } if (pwri_pass != NULL) { pwri_tmp = (unsigned char *)OPENSSL_strdup((char *)pwri_pass); if (pwri_tmp == NULL) goto end; if (CMS_add0_recipient_password(cms, -1, NID_undef, NID_undef, pwri_tmp, -1, NULL) == NULL) goto end; pwri_tmp = NULL; } if (!(flags & CMS_STREAM)) { if (!CMS_final(cms, in, NULL, flags)) goto end; } } else if (operation == SMIME_ENCRYPTED_ENCRYPT) { cms = CMS_EncryptedData_encrypt_ex(in, cipher, secret_key, secret_keylen, flags, libctx, app_get0_propq()); } else if (operation == SMIME_SIGN_RECEIPT) { CMS_ContentInfo *srcms = NULL; STACK_OF(CMS_SignerInfo) *sis; CMS_SignerInfo *si; sis = CMS_get0_SignerInfos(cms); if (sis == NULL) goto end; si = sk_CMS_SignerInfo_value(sis, 0); srcms = CMS_sign_receipt(si, signer, key, other, flags); if (srcms == NULL) goto end; CMS_ContentInfo_free(cms); cms = srcms; } else if (operation & SMIME_SIGNERS) { int i; /* * If detached data content and not signing pre-computed digest, we * enable streaming if S/MIME output format. */ if (operation == SMIME_SIGN) { if ((flags & CMS_DETACHED) != 0 && digestbin == NULL) { if (outformat == FORMAT_SMIME) flags |= CMS_STREAM; } flags |= CMS_PARTIAL; cms = CMS_sign_ex(NULL, NULL, other, in, flags, libctx, app_get0_propq()); if (cms == NULL) goto end; if (econtent_type != NULL) CMS_set1_eContentType(cms, econtent_type); if (rr_to != NULL && ((rr = make_receipt_request(rr_to, rr_allorfirst, rr_from)) == NULL)) { BIO_puts(bio_err, "Signed Receipt Request Creation Error\n"); goto end; } } else { flags |= CMS_REUSE_DIGEST; } for (i = 0; i < sk_OPENSSL_STRING_num(sksigners); i++) { CMS_SignerInfo *si; cms_key_param *kparam; int tflags = flags; signerfile = sk_OPENSSL_STRING_value(sksigners, i); keyfile = sk_OPENSSL_STRING_value(skkeys, i); signer = load_cert(signerfile, FORMAT_UNDEF, "signer certificate"); if (signer == NULL) { ret = 2; goto end; } key = load_key(keyfile, keyform, 0, passin, e, "signing key"); if (key == NULL) { ret = 2; goto end; } for (kparam = key_first; kparam; kparam = kparam->next) { if (kparam->idx == i) { tflags |= CMS_KEY_PARAM; break; } } si = CMS_add1_signer(cms, signer, key, sign_md, tflags); if (si == NULL) goto end; if (kparam != NULL) { EVP_PKEY_CTX *pctx; pctx = CMS_SignerInfo_get0_pkey_ctx(si); if (!cms_set_pkey_param(pctx, kparam->param)) goto end; } if (rr != NULL && !CMS_add1_ReceiptRequest(si, rr)) goto end; X509_free(signer); signer = NULL; EVP_PKEY_free(key); key = NULL; } /* If not streaming or resigning finalize structure */ if (operation == SMIME_SIGN && digestbin != NULL && (flags & CMS_STREAM) == 0) { /* Use pre-computed digest instead of content */ if (!CMS_final_digest(cms, digestbin, digestlen, NULL, flags)) goto end; } else if (operation == SMIME_SIGN && (flags & CMS_STREAM) == 0) { if (!CMS_final(cms, in, NULL, flags)) goto end; } } if (cms == NULL) { BIO_printf(bio_err, "Error creating CMS structure\n"); goto end; } ret = 4; if (operation == SMIME_DECRYPT) { if (flags & CMS_DEBUG_DECRYPT) CMS_decrypt(cms, NULL, NULL, NULL, NULL, flags); if (secret_key != NULL) { if (!CMS_decrypt_set1_key(cms, secret_key, secret_keylen, secret_keyid, secret_keyidlen)) { BIO_puts(bio_err, "Error decrypting CMS using secret key\n"); goto end; } } if (key != NULL) { if (!CMS_decrypt_set1_pkey_and_peer(cms, key, recip, originator)) { BIO_puts(bio_err, "Error decrypting CMS using private key\n"); goto end; } } if (pwri_pass != NULL) { if (!CMS_decrypt_set1_password(cms, pwri_pass, -1)) { BIO_puts(bio_err, "Error decrypting CMS using password\n"); goto end; } } if (!CMS_decrypt(cms, NULL, NULL, indata, out, flags)) { BIO_printf(bio_err, "Error decrypting CMS structure\n"); goto end; } } else if (operation == SMIME_DATA_OUT) { if (!CMS_data(cms, out, flags)) goto end; } else if (operation == SMIME_UNCOMPRESS) { if (!CMS_uncompress(cms, indata, out, flags)) goto end; } else if (operation == SMIME_DIGEST_VERIFY) { if (CMS_digest_verify(cms, indata, out, flags) > 0) { BIO_printf(bio_err, "Verification successful\n"); } else { BIO_printf(bio_err, "Verification failure\n"); goto end; } } else if (operation == SMIME_ENCRYPTED_DECRYPT) { if (!CMS_EncryptedData_decrypt(cms, secret_key, secret_keylen, indata, out, flags)) goto end; } else if (operation == SMIME_VERIFY) { if (CMS_verify(cms, other, store, indata, out, flags) > 0) { BIO_printf(bio_err, "%s Verification successful\n", (flags & CMS_CADES) != 0 ? "CAdES" : "CMS"); } else { BIO_printf(bio_err, "%s Verification failure\n", (flags & CMS_CADES) != 0 ? "CAdES" : "CMS"); if (verify_retcode) ret = verify_err + 32; goto end; } if (signerfile != NULL) { STACK_OF(X509) *signers = CMS_get0_signers(cms); if (!save_certs(signerfile, signers)) { BIO_printf(bio_err, "Error writing signers to %s\n", signerfile); ret = 5; goto end; } sk_X509_free(signers); } if (rr_print) receipt_request_print(cms); } else if (operation == SMIME_VERIFY_RECEIPT) { if (CMS_verify_receipt(rcms, cms, other, store, flags) > 0) { BIO_printf(bio_err, "Verification successful\n"); } else { BIO_printf(bio_err, "Verification failure\n"); goto end; } } else { if (noout) { if (print) { ASN1_PCTX *pctx = NULL; if (get_nameopt() != XN_FLAG_ONELINE) { pctx = ASN1_PCTX_new(); if (pctx != NULL) { /* Print anyway if malloc failed */ ASN1_PCTX_set_flags(pctx, ASN1_PCTX_FLAGS_SHOW_ABSENT); ASN1_PCTX_set_str_flags(pctx, get_nameopt()); ASN1_PCTX_set_nm_flags(pctx, get_nameopt()); } } CMS_ContentInfo_print_ctx(out, cms, 0, pctx); ASN1_PCTX_free(pctx); } } else if (outformat == FORMAT_SMIME) { if (to) BIO_printf(out, "To: %s%s", to, mime_eol); if (from) BIO_printf(out, "From: %s%s", from, mime_eol); if (subject) BIO_printf(out, "Subject: %s%s", subject, mime_eol); if (operation == SMIME_RESIGN) ret = SMIME_write_CMS(out, cms, indata, flags); else ret = SMIME_write_CMS(out, cms, in, flags); } else if (outformat == FORMAT_PEM) { ret = PEM_write_bio_CMS_stream(out, cms, in, flags); } else if (outformat == FORMAT_ASN1) { ret = i2d_CMS_bio_stream(out, cms, in, flags); } else { BIO_printf(bio_err, "Bad output format for CMS file\n"); goto end; } if (ret <= 0) { ret = 6; goto end; } } ret = 0; end: if (ret) ERR_print_errors(bio_err); OSSL_STACK_OF_X509_free(encerts); OSSL_STACK_OF_X509_free(other); X509_VERIFY_PARAM_free(vpm); sk_OPENSSL_STRING_free(sksigners); sk_OPENSSL_STRING_free(skkeys); OPENSSL_free(secret_key); OPENSSL_free(secret_keyid); OPENSSL_free(pwri_tmp); ASN1_OBJECT_free(econtent_type); CMS_ReceiptRequest_free(rr); sk_OPENSSL_STRING_free(rr_to); sk_OPENSSL_STRING_free(rr_from); for (key_param = key_first; key_param;) { cms_key_param *tparam; sk_OPENSSL_STRING_free(key_param->param); tparam = key_param->next; OPENSSL_free(key_param); key_param = tparam; } X509_STORE_free(store); X509_free(cert); X509_free(recip); X509_free(signer); EVP_PKEY_free(key); EVP_CIPHER_free(cipher); EVP_CIPHER_free(wrap_cipher); EVP_MD_free(sign_md); CMS_ContentInfo_free(cms); CMS_ContentInfo_free(rcms); release_engine(e); BIO_free(rctin); BIO_free(in); BIO_free(indata); BIO_free_all(out); OPENSSL_free(digestbin); OPENSSL_free(passin); NCONF_free(conf); return ret; } static int save_certs(char *signerfile, STACK_OF(X509) *signers) { int i; BIO *tmp; if (signerfile == NULL) return 1; tmp = BIO_new_file(signerfile, "w"); if (tmp == NULL) return 0; for (i = 0; i < sk_X509_num(signers); i++) PEM_write_bio_X509(tmp, sk_X509_value(signers, i)); BIO_free(tmp); return 1; } /* Minimal callback just to output policy info (if any) */ static int cms_cb(int ok, X509_STORE_CTX *ctx) { int error; error = X509_STORE_CTX_get_error(ctx); verify_err = error; if ((error != X509_V_ERR_NO_EXPLICIT_POLICY) && ((error != X509_V_OK) || (ok != 2))) return ok; policies_print(ctx); return ok; } static void gnames_stack_print(STACK_OF(GENERAL_NAMES) *gns) { STACK_OF(GENERAL_NAME) *gens; GENERAL_NAME *gen; int i, j; for (i = 0; i < sk_GENERAL_NAMES_num(gns); i++) { gens = sk_GENERAL_NAMES_value(gns, i); for (j = 0; j < sk_GENERAL_NAME_num(gens); j++) { gen = sk_GENERAL_NAME_value(gens, j); BIO_puts(bio_err, " "); GENERAL_NAME_print(bio_err, gen); BIO_puts(bio_err, "\n"); } } return; } static void receipt_request_print(CMS_ContentInfo *cms) { STACK_OF(CMS_SignerInfo) *sis; CMS_SignerInfo *si; CMS_ReceiptRequest *rr; int allorfirst; STACK_OF(GENERAL_NAMES) *rto, *rlist; ASN1_STRING *scid; int i, rv; sis = CMS_get0_SignerInfos(cms); for (i = 0; i < sk_CMS_SignerInfo_num(sis); i++) { si = sk_CMS_SignerInfo_value(sis, i); rv = CMS_get1_ReceiptRequest(si, &rr); BIO_printf(bio_err, "Signer %d:\n", i + 1); if (rv == 0) { BIO_puts(bio_err, " No Receipt Request\n"); } else if (rv < 0) { BIO_puts(bio_err, " Receipt Request Parse Error\n"); ERR_print_errors(bio_err); } else { const char *id; int idlen; CMS_ReceiptRequest_get0_values(rr, &scid, &allorfirst, &rlist, &rto); BIO_puts(bio_err, " Signed Content ID:\n"); idlen = ASN1_STRING_length(scid); id = (const char *)ASN1_STRING_get0_data(scid); BIO_dump_indent(bio_err, id, idlen, 4); BIO_puts(bio_err, " Receipts From"); if (rlist != NULL) { BIO_puts(bio_err, " List:\n"); gnames_stack_print(rlist); } else if (allorfirst == 1) { BIO_puts(bio_err, ": First Tier\n"); } else if (allorfirst == 0) { BIO_puts(bio_err, ": All\n"); } else { BIO_printf(bio_err, " Unknown (%d)\n", allorfirst); } BIO_puts(bio_err, " Receipts To:\n"); gnames_stack_print(rto); } CMS_ReceiptRequest_free(rr); } } static STACK_OF(GENERAL_NAMES) *make_names_stack(STACK_OF(OPENSSL_STRING) *ns) { int i; STACK_OF(GENERAL_NAMES) *ret; GENERAL_NAMES *gens = NULL; GENERAL_NAME *gen = NULL; ret = sk_GENERAL_NAMES_new_null(); if (ret == NULL) goto err; for (i = 0; i < sk_OPENSSL_STRING_num(ns); i++) { char *str = sk_OPENSSL_STRING_value(ns, i); gen = a2i_GENERAL_NAME(NULL, NULL, NULL, GEN_EMAIL, str, 0); if (gen == NULL) goto err; gens = GENERAL_NAMES_new(); if (gens == NULL) goto err; if (!sk_GENERAL_NAME_push(gens, gen)) goto err; gen = NULL; if (!sk_GENERAL_NAMES_push(ret, gens)) goto err; gens = NULL; } return ret; err: sk_GENERAL_NAMES_pop_free(ret, GENERAL_NAMES_free); GENERAL_NAMES_free(gens); GENERAL_NAME_free(gen); return NULL; } static CMS_ReceiptRequest *make_receipt_request(STACK_OF(OPENSSL_STRING) *rr_to, int rr_allorfirst, STACK_OF(OPENSSL_STRING) *rr_from) { STACK_OF(GENERAL_NAMES) *rct_to = NULL, *rct_from = NULL; CMS_ReceiptRequest *rr; rct_to = make_names_stack(rr_to); if (rct_to == NULL) goto err; if (rr_from != NULL) { rct_from = make_names_stack(rr_from); if (rct_from == NULL) goto err; } else { rct_from = NULL; } rr = CMS_ReceiptRequest_create0_ex(NULL, -1, rr_allorfirst, rct_from, rct_to, app_get0_libctx()); if (rr == NULL) goto err; return rr; err: sk_GENERAL_NAMES_pop_free(rct_to, GENERAL_NAMES_free); sk_GENERAL_NAMES_pop_free(rct_from, GENERAL_NAMES_free); return NULL; } static int cms_set_pkey_param(EVP_PKEY_CTX *pctx, STACK_OF(OPENSSL_STRING) *param) { char *keyopt; int i; if (sk_OPENSSL_STRING_num(param) <= 0) return 1; for (i = 0; i < sk_OPENSSL_STRING_num(param); i++) { keyopt = sk_OPENSSL_STRING_value(param, i); if (pkey_ctrl_string(pctx, keyopt) <= 0) { BIO_printf(bio_err, "parameter error \"%s\"\n", keyopt); ERR_print_errors(bio_err); return 0; } } return 1; }
./openssl/apps/req.c
/* * Copyright 1995-2023 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <stdio.h> #include <stdlib.h> #include <time.h> #include <string.h> #include <ctype.h> #include "apps.h" #include "progs.h" #include <openssl/core_names.h> #include <openssl/bio.h> #include <openssl/evp.h> #include <openssl/conf.h> #include <openssl/err.h> #include <openssl/asn1.h> #include <openssl/x509.h> #include <openssl/x509v3.h> #include <openssl/objects.h> #include <openssl/pem.h> #include <openssl/bn.h> #include <openssl/lhash.h> #include <openssl/rsa.h> #ifndef OPENSSL_NO_DSA # include <openssl/dsa.h> #endif #define BITS "default_bits" #define KEYFILE "default_keyfile" #define PROMPT "prompt" #define DISTINGUISHED_NAME "distinguished_name" #define ATTRIBUTES "attributes" #define V3_EXTENSIONS "x509_extensions" #define REQ_EXTENSIONS "req_extensions" #define STRING_MASK "string_mask" #define UTF8_IN "utf8" #define DEFAULT_KEY_LENGTH 2048 #define MIN_KEY_LENGTH 512 #define DEFAULT_DAYS 30 /* default cert validity period in days */ #define UNSET_DAYS -2 /* -1 may be used for testing expiration checks */ #define EXT_COPY_UNSET -1 static int make_REQ(X509_REQ *req, EVP_PKEY *pkey, X509_NAME *fsubj, int mutlirdn, int attribs, unsigned long chtype); static int prompt_info(X509_REQ *req, STACK_OF(CONF_VALUE) *dn_sk, const char *dn_sect, STACK_OF(CONF_VALUE) *attr_sk, const char *attr_sect, int attribs, unsigned long chtype); static int auto_info(X509_REQ *req, STACK_OF(CONF_VALUE) *sk, STACK_OF(CONF_VALUE) *attr, int attribs, unsigned long chtype); static int add_attribute_object(X509_REQ *req, char *text, const char *def, char *value, int nid, int n_min, int n_max, unsigned long chtype); static int add_DN_object(X509_NAME *n, char *text, const char *def, char *value, int nid, int n_min, int n_max, unsigned long chtype, int mval); static int build_data(char *text, const char *def, char *value, int n_min, int n_max, char *buf, const int buf_size, const char *desc1, const char *desc2); static int req_check_len(int len, int n_min, int n_max); static int check_end(const char *str, const char *end); static int join(char buf[], size_t buf_size, const char *name, const char *tail, const char *desc); static EVP_PKEY_CTX *set_keygen_ctx(const char *gstr, char **pkeytype, long *pkeylen, ENGINE *keygen_engine); static const char *section = "req"; static CONF *req_conf = NULL; static CONF *addext_conf = NULL; static int batch = 0; typedef enum OPTION_choice { OPT_COMMON, OPT_INFORM, OPT_OUTFORM, OPT_ENGINE, OPT_KEYGEN_ENGINE, OPT_KEY, OPT_PUBKEY, OPT_NEW, OPT_CONFIG, OPT_KEYFORM, OPT_IN, OPT_OUT, OPT_KEYOUT, OPT_PASSIN, OPT_PASSOUT, OPT_NEWKEY, OPT_PKEYOPT, OPT_SIGOPT, OPT_VFYOPT, OPT_BATCH, OPT_NEWHDR, OPT_MODULUS, OPT_VERIFY, OPT_NOENC, OPT_NODES, OPT_NOOUT, OPT_VERBOSE, OPT_UTF8, OPT_NAMEOPT, OPT_REQOPT, OPT_SUBJ, OPT_SUBJECT, OPT_TEXT, OPT_X509, OPT_X509V1, OPT_CA, OPT_CAKEY, OPT_MULTIVALUE_RDN, OPT_DAYS, OPT_SET_SERIAL, OPT_COPY_EXTENSIONS, OPT_EXTENSIONS, OPT_REQEXTS, OPT_ADDEXT, OPT_PRECERT, OPT_MD, OPT_SECTION, OPT_QUIET, OPT_R_ENUM, OPT_PROV_ENUM } OPTION_CHOICE; const OPTIONS req_options[] = { OPT_SECTION("General"), {"help", OPT_HELP, '-', "Display this summary"}, #ifndef OPENSSL_NO_ENGINE {"engine", OPT_ENGINE, 's', "Use engine, possibly a hardware device"}, {"keygen_engine", OPT_KEYGEN_ENGINE, 's', "Specify engine to be used for key generation operations"}, #endif {"in", OPT_IN, '<', "X.509 request input file (default stdin)"}, {"inform", OPT_INFORM, 'F', "CSR input format to use (PEM or DER; by default try PEM first)"}, {"verify", OPT_VERIFY, '-', "Verify self-signature on the request"}, OPT_SECTION("Certificate"), {"new", OPT_NEW, '-', "New request"}, {"config", OPT_CONFIG, '<', "Request template file"}, {"section", OPT_SECTION, 's', "Config section to use (default \"req\")"}, {"utf8", OPT_UTF8, '-', "Input characters are UTF8 (default ASCII)"}, {"nameopt", OPT_NAMEOPT, 's', "Certificate subject/issuer name printing options"}, {"reqopt", OPT_REQOPT, 's', "Various request text options"}, {"text", OPT_TEXT, '-', "Text form of request"}, {"x509", OPT_X509, '-', "Output an X.509 certificate structure instead of a cert request"}, {"x509v1", OPT_X509V1, '-', "Request cert generation with X.509 version 1"}, {"CA", OPT_CA, '<', "Issuer cert to use for signing a cert, implies -x509"}, {"CAkey", OPT_CAKEY, 's', "Issuer private key to use with -CA; default is -CA arg"}, {OPT_MORE_STR, 1, 1, "(Required by some CA's)"}, {"subj", OPT_SUBJ, 's', "Set or modify subject of request or cert"}, {"subject", OPT_SUBJECT, '-', "Print the subject of the output request or cert"}, {"multivalue-rdn", OPT_MULTIVALUE_RDN, '-', "Deprecated; multi-valued RDNs support is always on."}, {"days", OPT_DAYS, 'p', "Number of days cert is valid for"}, {"set_serial", OPT_SET_SERIAL, 's', "Serial number to use"}, {"copy_extensions", OPT_COPY_EXTENSIONS, 's', "copy extensions from request when using -x509"}, {"extensions", OPT_EXTENSIONS, 's', "Cert or request extension section (override value in config file)"}, {"reqexts", OPT_REQEXTS, 's', "An alias for -extensions"}, {"addext", OPT_ADDEXT, 's', "Additional cert extension key=value pair (may be given more than once)"}, {"precert", OPT_PRECERT, '-', "Add a poison extension to generated cert (implies -new)"}, OPT_SECTION("Keys and Signing"), {"key", OPT_KEY, 's', "Key for signing, and to include unless -in given"}, {"keyform", OPT_KEYFORM, 'f', "Key file format (ENGINE, other values ignored)"}, {"pubkey", OPT_PUBKEY, '-', "Output public key"}, {"keyout", OPT_KEYOUT, '>', "File to write private key to"}, {"passin", OPT_PASSIN, 's', "Private key and certificate password source"}, {"passout", OPT_PASSOUT, 's', "Output file pass phrase source"}, {"newkey", OPT_NEWKEY, 's', "Generate new key with [<alg>:]<nbits> or <alg>[:<file>] or param:<file>"}, {"pkeyopt", OPT_PKEYOPT, 's', "Public key options as opt:value"}, {"sigopt", OPT_SIGOPT, 's', "Signature parameter in n:v form"}, {"vfyopt", OPT_VFYOPT, 's', "Verification parameter in n:v form"}, {"", OPT_MD, '-', "Any supported digest"}, OPT_SECTION("Output"), {"out", OPT_OUT, '>', "Output file"}, {"outform", OPT_OUTFORM, 'F', "Output format - DER or PEM"}, {"batch", OPT_BATCH, '-', "Do not ask anything during request generation"}, {"verbose", OPT_VERBOSE, '-', "Verbose output"}, {"quiet", OPT_QUIET, '-', "Terse output"}, {"noenc", OPT_NOENC, '-', "Don't encrypt private keys"}, {"nodes", OPT_NODES, '-', "Don't encrypt private keys; deprecated"}, {"noout", OPT_NOOUT, '-', "Do not output REQ"}, {"newhdr", OPT_NEWHDR, '-', "Output \"NEW\" in the header lines"}, {"modulus", OPT_MODULUS, '-', "RSA modulus"}, OPT_R_OPTIONS, OPT_PROV_OPTIONS, {NULL} }; /* * An LHASH of strings, where each string is an extension name. */ static unsigned long ext_name_hash(const OPENSSL_STRING *a) { return OPENSSL_LH_strhash((const char *)a); } static int ext_name_cmp(const OPENSSL_STRING *a, const OPENSSL_STRING *b) { return strcmp((const char *)a, (const char *)b); } static void exts_cleanup(OPENSSL_STRING *x) { OPENSSL_free((char *)x); } /* * Is the |kv| key already duplicated? * Return 0 if unique, -1 on runtime error, -2 on syntax error; 1 if found. */ static int duplicated(LHASH_OF(OPENSSL_STRING) *addexts, char *kv) { char *p; size_t off; /* Check syntax. */ /* Skip leading whitespace, make a copy. */ while (isspace(_UC(*kv))) kv++; if ((p = strchr(kv, '=')) == NULL) { BIO_printf(bio_err, "Parse error on -addext: missing '='\n"); return -2; } off = p - kv; if ((kv = OPENSSL_strdup(kv)) == NULL) return -1; /* Skip trailing space before the equal sign. */ for (p = kv + off; p > kv; --p) if (!isspace(_UC(p[-1]))) break; if (p == kv) { BIO_printf(bio_err, "Parse error on -addext: missing key\n"); OPENSSL_free(kv); return -2; } *p = '\0'; /* Finally have a clean "key"; see if it's there [by attempt to add it]. */ p = (char *)lh_OPENSSL_STRING_insert(addexts, (OPENSSL_STRING *)kv); if (p != NULL) { BIO_printf(bio_err, "Duplicate extension name: %s\n", kv); OPENSSL_free(p); return 1; } else if (lh_OPENSSL_STRING_error(addexts)) { OPENSSL_free(kv); return -1; } return 0; } int req_main(int argc, char **argv) { ASN1_INTEGER *serial = NULL; BIO *out = NULL; ENGINE *e = NULL, *gen_eng = NULL; EVP_PKEY *pkey = NULL, *CAkey = NULL; EVP_PKEY_CTX *genctx = NULL; STACK_OF(OPENSSL_STRING) *pkeyopts = NULL, *sigopts = NULL, *vfyopts = NULL; LHASH_OF(OPENSSL_STRING) *addexts = NULL; X509 *new_x509 = NULL, *CAcert = NULL; X509_REQ *req = NULL; EVP_CIPHER *cipher = NULL; int ext_copy = EXT_COPY_UNSET; BIO *addext_bio = NULL; char *extsect = NULL; const char *infile = NULL, *CAfile = NULL, *CAkeyfile = NULL; char *outfile = NULL, *keyfile = NULL, *digest = NULL; char *keyalgstr = NULL, *p, *prog, *passargin = NULL, *passargout = NULL; char *passin = NULL, *passout = NULL; char *nofree_passin = NULL, *nofree_passout = NULL; char *subj = NULL; X509_NAME *fsubj = NULL; char *template = default_config_file, *keyout = NULL; const char *keyalg = NULL; OPTION_CHOICE o; int days = UNSET_DAYS; int ret = 1, gen_x509 = 0, i = 0, newreq = 0, verbose = 0, progress = 1; int informat = FORMAT_UNDEF, outformat = FORMAT_PEM, keyform = FORMAT_UNDEF; int modulus = 0, multirdn = 1, verify = 0, noout = 0, text = 0; int noenc = 0, newhdr = 0, subject = 0, pubkey = 0, precert = 0, x509v1 = 0; long newkey_len = -1; unsigned long chtype = MBSTRING_ASC, reqflag = 0; #ifndef OPENSSL_NO_DES cipher = (EVP_CIPHER *)EVP_des_ede3_cbc(); #endif opt_set_unknown_name("digest"); prog = opt_init(argc, argv, req_options); while ((o = opt_next()) != OPT_EOF) { switch (o) { case OPT_EOF: case OPT_ERR: opthelp: BIO_printf(bio_err, "%s: Use -help for summary.\n", prog); goto end; case OPT_HELP: opt_help(req_options); ret = 0; goto end; case OPT_INFORM: if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &informat)) goto opthelp; break; case OPT_OUTFORM: if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &outformat)) goto opthelp; break; case OPT_ENGINE: e = setup_engine(opt_arg(), 0); break; case OPT_KEYGEN_ENGINE: #ifndef OPENSSL_NO_ENGINE gen_eng = setup_engine(opt_arg(), 0); if (gen_eng == NULL) { BIO_printf(bio_err, "Can't find keygen engine %s\n", *argv); goto opthelp; } #endif break; case OPT_KEY: keyfile = opt_arg(); break; case OPT_PUBKEY: pubkey = 1; break; case OPT_NEW: newreq = 1; break; case OPT_CONFIG: template = opt_arg(); break; case OPT_SECTION: section = opt_arg(); break; case OPT_KEYFORM: if (!opt_format(opt_arg(), OPT_FMT_ANY, &keyform)) goto opthelp; break; case OPT_IN: infile = opt_arg(); break; case OPT_OUT: outfile = opt_arg(); break; case OPT_KEYOUT: keyout = opt_arg(); break; case OPT_PASSIN: passargin = opt_arg(); break; case OPT_PASSOUT: passargout = opt_arg(); break; case OPT_R_CASES: if (!opt_rand(o)) goto end; break; case OPT_PROV_CASES: if (!opt_provider(o)) goto end; break; case OPT_NEWKEY: keyalg = opt_arg(); newreq = 1; break; case OPT_PKEYOPT: if (pkeyopts == NULL) pkeyopts = sk_OPENSSL_STRING_new_null(); if (pkeyopts == NULL || !sk_OPENSSL_STRING_push(pkeyopts, opt_arg())) goto opthelp; break; case OPT_SIGOPT: if (!sigopts) sigopts = sk_OPENSSL_STRING_new_null(); if (!sigopts || !sk_OPENSSL_STRING_push(sigopts, opt_arg())) goto opthelp; break; case OPT_VFYOPT: if (!vfyopts) vfyopts = sk_OPENSSL_STRING_new_null(); if (!vfyopts || !sk_OPENSSL_STRING_push(vfyopts, opt_arg())) goto opthelp; break; case OPT_BATCH: batch = 1; break; case OPT_NEWHDR: newhdr = 1; break; case OPT_MODULUS: modulus = 1; break; case OPT_VERIFY: verify = 1; break; case OPT_NODES: case OPT_NOENC: noenc = 1; break; case OPT_NOOUT: noout = 1; break; case OPT_VERBOSE: verbose = 1; progress = 1; break; case OPT_QUIET: verbose = 0; progress = 0; break; case OPT_UTF8: chtype = MBSTRING_UTF8; break; case OPT_NAMEOPT: if (!set_nameopt(opt_arg())) goto opthelp; break; case OPT_REQOPT: if (!set_cert_ex(&reqflag, opt_arg())) goto opthelp; break; case OPT_TEXT: text = 1; break; case OPT_X509V1: x509v1 = 1; /* fall thru */ case OPT_X509: gen_x509 = 1; break; case OPT_CA: CAfile = opt_arg(); gen_x509 = 1; break; case OPT_CAKEY: CAkeyfile = opt_arg(); break; case OPT_DAYS: days = atoi(opt_arg()); if (days < -1) { BIO_printf(bio_err, "%s: -days parameter arg must be >= -1\n", prog); goto end; } break; case OPT_SET_SERIAL: if (serial != NULL) { BIO_printf(bio_err, "Serial number supplied twice\n"); goto opthelp; } serial = s2i_ASN1_INTEGER(NULL, opt_arg()); if (serial == NULL) goto opthelp; break; case OPT_SUBJECT: subject = 1; break; case OPT_SUBJ: subj = opt_arg(); break; case OPT_MULTIVALUE_RDN: /* obsolete */ break; case OPT_COPY_EXTENSIONS: if (!set_ext_copy(&ext_copy, opt_arg())) { BIO_printf(bio_err, "Invalid extension copy option: \"%s\"\n", opt_arg()); goto end; } break; case OPT_EXTENSIONS: case OPT_REQEXTS: extsect = opt_arg(); break; case OPT_ADDEXT: p = opt_arg(); if (addexts == NULL) { addexts = lh_OPENSSL_STRING_new(ext_name_hash, ext_name_cmp); addext_bio = BIO_new(BIO_s_mem()); if (addexts == NULL || addext_bio == NULL) goto end; } i = duplicated(addexts, p); if (i == 1) goto opthelp; if (i == -1) BIO_printf(bio_err, "Internal error handling -addext %s\n", p); if (i < 0 || BIO_printf(addext_bio, "%s\n", p) < 0) goto end; break; case OPT_PRECERT: newreq = precert = 1; break; case OPT_MD: digest = opt_unknown(); break; } } /* No extra arguments. */ if (!opt_check_rest_arg(NULL)) goto opthelp; if (!app_RAND_load()) goto end; if (!gen_x509) { if (days != UNSET_DAYS) BIO_printf(bio_err, "Ignoring -days without -x509; not generating a certificate\n"); if (ext_copy == EXT_COPY_NONE) BIO_printf(bio_err, "Ignoring -copy_extensions 'none' when -x509 is not given\n"); } if (infile == NULL) { if (gen_x509) newreq = 1; else if (!newreq) BIO_printf(bio_err, "Warning: Will read cert request from stdin since no -in option is given\n"); } if (!app_passwd(passargin, passargout, &passin, &passout)) { BIO_printf(bio_err, "Error getting passwords\n"); goto end; } if ((req_conf = app_load_config_verbose(template, verbose)) == NULL) goto end; if (addext_bio != NULL) { if (verbose) BIO_printf(bio_err, "Using additional configuration from -addext options\n"); if ((addext_conf = app_load_config_bio(addext_bio, NULL)) == NULL) goto end; } if (template != default_config_file && !app_load_modules(req_conf)) goto end; if (req_conf != NULL) { p = app_conf_try_string(req_conf, NULL, "oid_file"); if (p != NULL) { BIO *oid_bio = BIO_new_file(p, "r"); if (oid_bio == NULL) { if (verbose) BIO_printf(bio_err, "Problems opening '%s' for extra OIDs\n", p); } else { OBJ_create_objects(oid_bio); BIO_free(oid_bio); } } } if (!add_oid_section(req_conf)) goto end; /* Check that any specified digest is fetchable */ if (digest != NULL) { if (!opt_check_md(digest)) goto opthelp; } else { /* No digest specified, default to configuration */ p = app_conf_try_string(req_conf, section, "default_md"); if (p != NULL) digest = p; } if (extsect == NULL) extsect = app_conf_try_string(req_conf, section, gen_x509 ? V3_EXTENSIONS : REQ_EXTENSIONS); if (extsect != NULL) { /* Check syntax of extension section in config file */ X509V3_CTX ctx; X509V3_set_ctx_test(&ctx); X509V3_set_nconf(&ctx, req_conf); if (!X509V3_EXT_add_nconf(req_conf, &ctx, extsect, NULL)) { BIO_printf(bio_err, "Error checking %s extension section %s\n", gen_x509 ? "x509" : "request", extsect); goto end; } } if (addext_conf != NULL) { /* Check syntax of command line extensions */ X509V3_CTX ctx; X509V3_set_ctx_test(&ctx); X509V3_set_nconf(&ctx, addext_conf); if (!X509V3_EXT_add_nconf(addext_conf, &ctx, "default", NULL)) { BIO_printf(bio_err, "Error checking extensions defined using -addext\n"); goto end; } } if (passin == NULL) passin = nofree_passin = app_conf_try_string(req_conf, section, "input_password"); if (passout == NULL) passout = nofree_passout = app_conf_try_string(req_conf, section, "output_password"); p = app_conf_try_string(req_conf, section, STRING_MASK); if (p != NULL && !ASN1_STRING_set_default_mask_asc(p)) { BIO_printf(bio_err, "Invalid global string mask setting %s\n", p); goto end; } if (chtype != MBSTRING_UTF8) { p = app_conf_try_string(req_conf, section, UTF8_IN); if (p != NULL && strcmp(p, "yes") == 0) chtype = MBSTRING_UTF8; } if (keyfile != NULL) { pkey = load_key(keyfile, keyform, 0, passin, e, "private key"); if (pkey == NULL) goto end; app_RAND_load_conf(req_conf, section); } if (keyalg != NULL && pkey != NULL) { BIO_printf(bio_err, "Warning: Not generating key via given -newkey option since -key is given\n"); /* Better throw an error in this case */ } if (newreq && pkey == NULL) { app_RAND_load_conf(req_conf, section); if (!app_conf_try_number(req_conf, section, BITS, &newkey_len)) newkey_len = DEFAULT_KEY_LENGTH; genctx = set_keygen_ctx(keyalg, &keyalgstr, &newkey_len, gen_eng); if (genctx == NULL) goto end; if (newkey_len < MIN_KEY_LENGTH && (EVP_PKEY_CTX_is_a(genctx, "RSA") || EVP_PKEY_CTX_is_a(genctx, "RSA-PSS") || EVP_PKEY_CTX_is_a(genctx, "DSA"))) { BIO_printf(bio_err, "Private key length too short, needs to be at least %d bits, not %ld.\n", MIN_KEY_LENGTH, newkey_len); goto end; } if (newkey_len > OPENSSL_RSA_MAX_MODULUS_BITS && (EVP_PKEY_CTX_is_a(genctx, "RSA") || EVP_PKEY_CTX_is_a(genctx, "RSA-PSS"))) BIO_printf(bio_err, "Warning: It is not recommended to use more than %d bit for RSA keys.\n" " Your key size is %ld! Larger key size may behave not as expected.\n", OPENSSL_RSA_MAX_MODULUS_BITS, newkey_len); #ifndef OPENSSL_NO_DSA if (EVP_PKEY_CTX_is_a(genctx, "DSA") && newkey_len > OPENSSL_DSA_MAX_MODULUS_BITS) BIO_printf(bio_err, "Warning: It is not recommended to use more than %d bit for DSA keys.\n" " Your key size is %ld! Larger key size may behave not as expected.\n", OPENSSL_DSA_MAX_MODULUS_BITS, newkey_len); #endif if (pkeyopts != NULL) { char *genopt; for (i = 0; i < sk_OPENSSL_STRING_num(pkeyopts); i++) { genopt = sk_OPENSSL_STRING_value(pkeyopts, i); if (pkey_ctrl_string(genctx, genopt) <= 0) { BIO_printf(bio_err, "Key parameter error \"%s\"\n", genopt); goto end; } } } EVP_PKEY_CTX_set_app_data(genctx, bio_err); if (progress) EVP_PKEY_CTX_set_cb(genctx, progress_cb); pkey = app_keygen(genctx, keyalgstr, newkey_len, verbose); if (pkey == NULL) goto end; EVP_PKEY_CTX_free(genctx); genctx = NULL; } if (keyout == NULL && keyfile == NULL) keyout = app_conf_try_string(req_conf, section, KEYFILE); if (pkey != NULL && (keyfile == NULL || keyout != NULL)) { if (verbose) { BIO_printf(bio_err, "Writing private key to "); if (keyout == NULL) BIO_printf(bio_err, "stdout\n"); else BIO_printf(bio_err, "'%s'\n", keyout); } out = bio_open_owner(keyout, outformat, newreq); if (out == NULL) goto end; p = app_conf_try_string(req_conf, section, "encrypt_rsa_key"); if (p == NULL) p = app_conf_try_string(req_conf, section, "encrypt_key"); if (p != NULL && strcmp(p, "no") == 0) cipher = NULL; if (noenc) cipher = NULL; i = 0; loop: if (!PEM_write_bio_PrivateKey(out, pkey, cipher, NULL, 0, NULL, passout)) { if ((ERR_GET_REASON(ERR_peek_error()) == PEM_R_PROBLEMS_GETTING_PASSWORD) && (i < 3)) { ERR_clear_error(); i++; goto loop; } goto end; } BIO_free(out); out = NULL; BIO_printf(bio_err, "-----\n"); } /* * subj is expected to be in the format /type0=value0/type1=value1/type2=... * where characters may be escaped by \ */ if (subj != NULL && (fsubj = parse_name(subj, chtype, multirdn, "subject")) == NULL) goto end; if (!newreq) { if (keyfile != NULL) BIO_printf(bio_err, "Warning: Not placing -key in cert or request since request is used\n"); req = load_csr_autofmt(infile /* if NULL, reads from stdin */, informat, vfyopts, "X509 request"); if (req == NULL) goto end; } else if (infile != NULL) { BIO_printf(bio_err, "Warning: Ignoring -in option since -new or -newkey or -precert is given\n"); /* Better throw an error in this case, as done in the x509 app */ } if (CAkeyfile == NULL) CAkeyfile = CAfile; if (CAkeyfile != NULL) { if (CAfile == NULL) { BIO_printf(bio_err, "Warning: Ignoring -CAkey option since no -CA option is given\n"); } else { if ((CAkey = load_key(CAkeyfile, FORMAT_UNDEF, 0, passin, e, CAkeyfile != CAfile ? "issuer private key from -CAkey arg" : "issuer private key from -CA arg")) == NULL) goto end; } } if (CAfile != NULL) { if ((CAcert = load_cert_pass(CAfile, FORMAT_UNDEF, 1, passin, "issuer cert from -CA arg")) == NULL) goto end; if (!X509_check_private_key(CAcert, CAkey)) { BIO_printf(bio_err, "Issuer CA certificate and key do not match\n"); goto end; } } if (newreq || gen_x509) { if (CAcert == NULL && pkey == NULL) { BIO_printf(bio_err, "Must provide a signature key using -key or" " provide -CA / -CAkey\n"); goto end; } if (req == NULL) { req = X509_REQ_new_ex(app_get0_libctx(), app_get0_propq()); if (req == NULL) { goto end; } if (!make_REQ(req, pkey, fsubj, multirdn, !gen_x509, chtype)) { BIO_printf(bio_err, "Error making certificate request\n"); goto end; } /* Note that -x509 can take over -key and -subj option values. */ } if (gen_x509) { EVP_PKEY *pub_key = X509_REQ_get0_pubkey(req); EVP_PKEY *issuer_key = CAcert != NULL ? CAkey : pkey; X509V3_CTX ext_ctx; X509_NAME *issuer = CAcert != NULL ? X509_get_subject_name(CAcert) : X509_REQ_get_subject_name(req); X509_NAME *n_subj = fsubj != NULL ? fsubj : X509_REQ_get_subject_name(req); if (CAcert != NULL && keyfile != NULL) BIO_printf(bio_err, "Warning: Not using -key or -newkey for signing since -CA option is given\n"); if ((new_x509 = X509_new_ex(app_get0_libctx(), app_get0_propq())) == NULL) goto end; if (serial != NULL) { if (!X509_set_serialNumber(new_x509, serial)) goto end; } else { if (!rand_serial(NULL, X509_get_serialNumber(new_x509))) goto end; } if (!X509_set_issuer_name(new_x509, issuer)) goto end; if (days == UNSET_DAYS) { days = DEFAULT_DAYS; } if (!set_cert_times(new_x509, NULL, NULL, days)) goto end; if (!X509_set_subject_name(new_x509, n_subj)) goto end; if (!pub_key || !X509_set_pubkey(new_x509, pub_key)) goto end; if (ext_copy == EXT_COPY_UNSET) { if (infile != NULL) BIO_printf(bio_err, "Warning: No -copy_extensions given; ignoring any extensions in the request\n"); } else if (!copy_extensions(new_x509, req, ext_copy)) { BIO_printf(bio_err, "Error copying extensions from request\n"); goto end; } /* Set up V3 context struct */ X509V3_set_ctx(&ext_ctx, CAcert != NULL ? CAcert : new_x509, new_x509, NULL, NULL, X509V3_CTX_REPLACE); /* prepare fallback for AKID, but only if issuer cert == new_x509 */ if (CAcert == NULL) { if (!X509V3_set_issuer_pkey(&ext_ctx, issuer_key)) goto end; if (!cert_matches_key(new_x509, issuer_key)) BIO_printf(bio_err, "Warning: Signature key and public key of cert do not match\n"); } X509V3_set_nconf(&ext_ctx, req_conf); /* Add extensions */ if (extsect != NULL && !X509V3_EXT_add_nconf(req_conf, &ext_ctx, extsect, new_x509)) { BIO_printf(bio_err, "Error adding x509 extensions from section %s\n", extsect); goto end; } if (addext_conf != NULL && !X509V3_EXT_add_nconf(addext_conf, &ext_ctx, "default", new_x509)) { BIO_printf(bio_err, "Error adding x509 extensions defined via -addext\n"); goto end; } /* If a pre-cert was requested, we need to add a poison extension */ if (precert) { if (X509_add1_ext_i2d(new_x509, NID_ct_precert_poison, NULL, 1, 0) != 1) { BIO_printf(bio_err, "Error adding poison extension\n"); goto end; } } i = do_X509_sign(new_x509, x509v1, issuer_key, digest, sigopts, &ext_ctx); if (!i) goto end; } else { X509V3_CTX ext_ctx; if (precert) { BIO_printf(bio_err, "Warning: Ignoring -precert flag since no cert is produced\n"); } /* Set up V3 context struct */ X509V3_set_ctx(&ext_ctx, NULL, NULL, req, NULL, X509V3_CTX_REPLACE); X509V3_set_nconf(&ext_ctx, req_conf); /* Add extensions */ if (extsect != NULL && !X509V3_EXT_REQ_add_nconf(req_conf, &ext_ctx, extsect, req)) { BIO_printf(bio_err, "Error adding request extensions from section %s\n", extsect); goto end; } if (addext_conf != NULL && !X509V3_EXT_REQ_add_nconf(addext_conf, &ext_ctx, "default", req)) { BIO_printf(bio_err, "Error adding request extensions defined via -addext\n"); goto end; } i = do_X509_REQ_sign(req, pkey, digest, sigopts); if (!i) goto end; } } if (subj != NULL && !newreq && !gen_x509) { if (verbose) { BIO_printf(out, "Modifying subject of certificate request\n"); print_name(out, "Old subject=", X509_REQ_get_subject_name(req)); } if (!X509_REQ_set_subject_name(req, fsubj)) { BIO_printf(bio_err, "Error modifying subject of certificate request\n"); goto end; } if (verbose) { print_name(out, "New subject=", X509_REQ_get_subject_name(req)); } } if (verify) { EVP_PKEY *tpubkey = pkey; if (tpubkey == NULL) { tpubkey = X509_REQ_get0_pubkey(req); if (tpubkey == NULL) goto end; } i = do_X509_REQ_verify(req, tpubkey, vfyopts); if (i < 0) goto end; if (i == 0) BIO_printf(bio_err, "Certificate request self-signature verify failure\n"); else /* i > 0 */ BIO_printf(bio_out, "Certificate request self-signature verify OK\n"); } if (noout && !text && !modulus && !subject && !pubkey) { ret = 0; goto end; } out = bio_open_default(outfile, keyout != NULL && outfile != NULL && strcmp(keyout, outfile) == 0 ? 'a' : 'w', outformat); if (out == NULL) goto end; if (pubkey) { EVP_PKEY *tpubkey = X509_REQ_get0_pubkey(req); if (tpubkey == NULL) { BIO_printf(bio_err, "Error getting public key\n"); goto end; } PEM_write_bio_PUBKEY(out, tpubkey); } if (text) { if (gen_x509) ret = X509_print_ex(out, new_x509, get_nameopt(), reqflag); else ret = X509_REQ_print_ex(out, req, get_nameopt(), reqflag); if (ret == 0) { if (gen_x509) BIO_printf(bio_err, "Error printing certificate\n"); else BIO_printf(bio_err, "Error printing certificate request\n"); goto end; } } if (subject) { print_name(out, "subject=", gen_x509 ? X509_get_subject_name(new_x509) : X509_REQ_get_subject_name(req)); } if (modulus) { EVP_PKEY *tpubkey; if (gen_x509) tpubkey = X509_get0_pubkey(new_x509); else tpubkey = X509_REQ_get0_pubkey(req); if (tpubkey == NULL) { BIO_puts(bio_err, "Modulus is unavailable\n"); goto end; } BIO_puts(out, "Modulus="); if (EVP_PKEY_is_a(tpubkey, "RSA") || EVP_PKEY_is_a(tpubkey, "RSA-PSS")) { BIGNUM *n = NULL; if (!EVP_PKEY_get_bn_param(tpubkey, "n", &n)) goto end; BN_print(out, n); BN_free(n); } else { BIO_puts(out, "Wrong Algorithm type"); } BIO_puts(out, "\n"); } if (!noout && !gen_x509) { if (outformat == FORMAT_ASN1) i = i2d_X509_REQ_bio(out, req); else if (newhdr) i = PEM_write_bio_X509_REQ_NEW(out, req); else i = PEM_write_bio_X509_REQ(out, req); if (!i) { BIO_printf(bio_err, "Unable to write certificate request\n"); goto end; } } if (!noout && gen_x509 && new_x509 != NULL) { if (outformat == FORMAT_ASN1) i = i2d_X509_bio(out, new_x509); else i = PEM_write_bio_X509(out, new_x509); if (!i) { BIO_printf(bio_err, "Unable to write X509 certificate\n"); goto end; } } ret = 0; end: if (ret) { ERR_print_errors(bio_err); } NCONF_free(req_conf); NCONF_free(addext_conf); BIO_free(addext_bio); BIO_free_all(out); EVP_PKEY_free(pkey); EVP_PKEY_CTX_free(genctx); sk_OPENSSL_STRING_free(pkeyopts); sk_OPENSSL_STRING_free(sigopts); sk_OPENSSL_STRING_free(vfyopts); lh_OPENSSL_STRING_doall(addexts, exts_cleanup); lh_OPENSSL_STRING_free(addexts); #ifndef OPENSSL_NO_ENGINE release_engine(gen_eng); #endif OPENSSL_free(keyalgstr); X509_REQ_free(req); X509_NAME_free(fsubj); X509_free(new_x509); X509_free(CAcert); EVP_PKEY_free(CAkey); ASN1_INTEGER_free(serial); release_engine(e); if (passin != nofree_passin) OPENSSL_free(passin); if (passout != nofree_passout) OPENSSL_free(passout); return ret; } static int make_REQ(X509_REQ *req, EVP_PKEY *pkey, X509_NAME *fsubj, int multirdn, int attribs, unsigned long chtype) { int ret = 0, i; char no_prompt = 0; STACK_OF(CONF_VALUE) *dn_sk = NULL, *attr_sk = NULL; char *tmp, *dn_sect, *attr_sect; tmp = app_conf_try_string(req_conf, section, PROMPT); if (tmp != NULL && strcmp(tmp, "no") == 0) no_prompt = 1; dn_sect = app_conf_try_string(req_conf, section, DISTINGUISHED_NAME); if (dn_sect != NULL) { dn_sk = NCONF_get_section(req_conf, dn_sect); if (dn_sk == NULL) { BIO_printf(bio_err, "Unable to get '%s' section\n", dn_sect); goto err; } } attr_sect = app_conf_try_string(req_conf, section, ATTRIBUTES); if (attr_sect != NULL) { attr_sk = NCONF_get_section(req_conf, attr_sect); if (attr_sk == NULL) { BIO_printf(bio_err, "Unable to get '%s' section\n", attr_sect); goto err; } } /* so far there is only version 1 */ if (!X509_REQ_set_version(req, X509_REQ_VERSION_1)) goto err; if (fsubj != NULL) i = X509_REQ_set_subject_name(req, fsubj); else if (no_prompt) i = auto_info(req, dn_sk, attr_sk, attribs, chtype); else i = prompt_info(req, dn_sk, dn_sect, attr_sk, attr_sect, attribs, chtype); if (!i) goto err; if (!X509_REQ_set_pubkey(req, pkey)) goto err; ret = 1; err: return ret; } static int prompt_info(X509_REQ *req, STACK_OF(CONF_VALUE) *dn_sk, const char *dn_sect, STACK_OF(CONF_VALUE) *attr_sk, const char *attr_sect, int attribs, unsigned long chtype) { int i; char *p, *q; char buf[100]; int nid, mval; long n_min, n_max; char *type, *value; const char *def; CONF_VALUE *v; X509_NAME *subj = X509_REQ_get_subject_name(req); if (!batch) { BIO_printf(bio_err, "You are about to be asked to enter information that will be incorporated\n"); BIO_printf(bio_err, "into your certificate request.\n"); BIO_printf(bio_err, "What you are about to enter is what is called a Distinguished Name or a DN.\n"); BIO_printf(bio_err, "There are quite a few fields but you can leave some blank\n"); BIO_printf(bio_err, "For some fields there will be a default value,\n"); BIO_printf(bio_err, "If you enter '.', the field will be left blank.\n"); BIO_printf(bio_err, "-----\n"); } if (sk_CONF_VALUE_num(dn_sk)) { i = -1; start: for (;;) { i++; if (sk_CONF_VALUE_num(dn_sk) <= i) break; v = sk_CONF_VALUE_value(dn_sk, i); p = q = NULL; type = v->name; if (!check_end(type, "_min") || !check_end(type, "_max") || !check_end(type, "_default") || !check_end(type, "_value")) continue; /* * Skip past any leading X. X: X, etc to allow for multiple * instances */ for (p = v->name; *p; p++) if ((*p == ':') || (*p == ',') || (*p == '.')) { p++; if (*p) type = p; break; } if (*type == '+') { mval = -1; type++; } else { mval = 0; } /* If OBJ not recognised ignore it */ if ((nid = OBJ_txt2nid(type)) == NID_undef) goto start; if (!join(buf, sizeof(buf), v->name, "_default", "Name")) return 0; if ((def = app_conf_try_string(req_conf, dn_sect, buf)) == NULL) def = ""; if (!join(buf, sizeof(buf), v->name, "_value", "Name")) return 0; if ((value = app_conf_try_string(req_conf, dn_sect, buf)) == NULL) value = NULL; if (!join(buf, sizeof(buf), v->name, "_min", "Name")) return 0; if (!app_conf_try_number(req_conf, dn_sect, buf, &n_min)) n_min = -1; if (!join(buf, sizeof(buf), v->name, "_max", "Name")) return 0; if (!app_conf_try_number(req_conf, dn_sect, buf, &n_max)) n_max = -1; if (!add_DN_object(subj, v->value, def, value, nid, n_min, n_max, chtype, mval)) return 0; } if (X509_NAME_entry_count(subj) == 0) { BIO_printf(bio_err, "Error: No objects specified in config file\n"); return 0; } if (attribs) { if ((attr_sk != NULL) && (sk_CONF_VALUE_num(attr_sk) > 0) && (!batch)) { BIO_printf(bio_err, "\nPlease enter the following 'extra' attributes\n"); BIO_printf(bio_err, "to be sent with your certificate request\n"); } i = -1; start2: for (;;) { i++; if ((attr_sk == NULL) || (sk_CONF_VALUE_num(attr_sk) <= i)) break; v = sk_CONF_VALUE_value(attr_sk, i); type = v->name; if ((nid = OBJ_txt2nid(type)) == NID_undef) goto start2; if (!join(buf, sizeof(buf), type, "_default", "Name")) return 0; def = app_conf_try_string(req_conf, attr_sect, buf); if (def == NULL) def = ""; if (!join(buf, sizeof(buf), type, "_value", "Name")) return 0; value = app_conf_try_string(req_conf, attr_sect, buf); if (!join(buf, sizeof(buf), type, "_min", "Name")) return 0; if (!app_conf_try_number(req_conf, attr_sect, buf, &n_min)) n_min = -1; if (!join(buf, sizeof(buf), type, "_max", "Name")) return 0; if (!app_conf_try_number(req_conf, attr_sect, buf, &n_max)) n_max = -1; if (!add_attribute_object(req, v->value, def, value, nid, n_min, n_max, chtype)) return 0; } } } else { BIO_printf(bio_err, "No template, please set one up.\n"); return 0; } return 1; } static int auto_info(X509_REQ *req, STACK_OF(CONF_VALUE) *dn_sk, STACK_OF(CONF_VALUE) *attr_sk, int attribs, unsigned long chtype) { int i, spec_char, plus_char; char *p, *q; char *type; CONF_VALUE *v; X509_NAME *subj; subj = X509_REQ_get_subject_name(req); for (i = 0; i < sk_CONF_VALUE_num(dn_sk); i++) { int mval; v = sk_CONF_VALUE_value(dn_sk, i); p = q = NULL; type = v->name; /* * Skip past any leading X. X: X, etc to allow for multiple instances */ for (p = v->name; *p; p++) { #ifndef CHARSET_EBCDIC spec_char = (*p == ':' || *p == ',' || *p == '.'); #else spec_char = (*p == os_toascii[':'] || *p == os_toascii[','] || *p == os_toascii['.']); #endif if (spec_char) { p++; if (*p) type = p; break; } } #ifndef CHARSET_EBCDIC plus_char = (*type == '+'); #else plus_char = (*type == os_toascii['+']); #endif if (plus_char) { type++; mval = -1; } else { mval = 0; } if (!X509_NAME_add_entry_by_txt(subj, type, chtype, (unsigned char *)v->value, -1, -1, mval)) return 0; } if (!X509_NAME_entry_count(subj)) { BIO_printf(bio_err, "Error: No objects specified in config file\n"); return 0; } if (attribs) { for (i = 0; i < sk_CONF_VALUE_num(attr_sk); i++) { v = sk_CONF_VALUE_value(attr_sk, i); if (!X509_REQ_add1_attr_by_txt(req, v->name, chtype, (unsigned char *)v->value, -1)) return 0; } } return 1; } static int add_DN_object(X509_NAME *n, char *text, const char *def, char *value, int nid, int n_min, int n_max, unsigned long chtype, int mval) { int ret = 0; char buf[1024]; ret = build_data(text, def, value, n_min, n_max, buf, sizeof(buf), "DN value", "DN default"); if ((ret == 0) || (ret == 1)) return ret; ret = 1; if (!X509_NAME_add_entry_by_NID(n, nid, chtype, (unsigned char *)buf, -1, -1, mval)) ret = 0; return ret; } static int add_attribute_object(X509_REQ *req, char *text, const char *def, char *value, int nid, int n_min, int n_max, unsigned long chtype) { int ret = 0; char buf[1024]; ret = build_data(text, def, value, n_min, n_max, buf, sizeof(buf), "Attribute value", "Attribute default"); if ((ret == 0) || (ret == 1)) return ret; ret = 1; if (!X509_REQ_add1_attr_by_NID(req, nid, chtype, (unsigned char *)buf, -1)) { BIO_printf(bio_err, "Error adding attribute\n"); ret = 0; } return ret; } static int build_data(char *text, const char *def, char *value, int n_min, int n_max, char *buf, const int buf_size, const char *desc1, const char *desc2) { int i; start: if (!batch) BIO_printf(bio_err, "%s [%s]:", text, def); (void)BIO_flush(bio_err); if (value != NULL) { if (!join(buf, buf_size, value, "\n", desc1)) return 0; BIO_printf(bio_err, "%s\n", value); } else { buf[0] = '\0'; if (!batch) { if (!fgets(buf, buf_size, stdin)) return 0; } else { buf[0] = '\n'; buf[1] = '\0'; } } if (buf[0] == '\0') return 0; if (buf[0] == '\n') { if ((def == NULL) || (def[0] == '\0')) return 1; if (!join(buf, buf_size, def, "\n", desc2)) return 0; } else if ((buf[0] == '.') && (buf[1] == '\n')) { return 1; } i = strlen(buf); if (buf[i - 1] != '\n') { BIO_printf(bio_err, "Missing newline at end of input\n"); return 0; } buf[--i] = '\0'; #ifdef CHARSET_EBCDIC ebcdic2ascii(buf, buf, i); #endif if (!req_check_len(i, n_min, n_max)) { if (batch || value) return 0; goto start; } return 2; } static int req_check_len(int len, int n_min, int n_max) { if (n_min > 0 && len < n_min) { BIO_printf(bio_err, "String too short, must be at least %d bytes long\n", n_min); return 0; } if (n_max >= 0 && len > n_max) { BIO_printf(bio_err, "String too long, must be at most %d bytes long\n", n_max); return 0; } return 1; } /* Check if the end of a string matches 'end' */ static int check_end(const char *str, const char *end) { size_t elen, slen; const char *tmp; elen = strlen(end); slen = strlen(str); if (elen > slen) return 1; tmp = str + slen - elen; return strcmp(tmp, end); } /* * Merge the two strings together into the result buffer checking for * overflow and producing an error message if there is. */ static int join(char buf[], size_t buf_size, const char *name, const char *tail, const char *desc) { const size_t name_len = strlen(name), tail_len = strlen(tail); if (name_len + tail_len + 1 > buf_size) { BIO_printf(bio_err, "%s '%s' too long\n", desc, name); return 0; } memcpy(buf, name, name_len); memcpy(buf + name_len, tail, tail_len + 1); return 1; } static EVP_PKEY_CTX *set_keygen_ctx(const char *gstr, char **pkeytype, long *pkeylen, ENGINE *keygen_engine) { EVP_PKEY_CTX *gctx = NULL; EVP_PKEY *param = NULL; long keylen = -1; BIO *pbio = NULL; const char *keytype = NULL; size_t keytypelen = 0; int expect_paramfile = 0; const char *paramfile = NULL; /* Treat the first part of gstr, and only that */ if (gstr == NULL) { /* * Special case: when no string given, default to RSA and the * key length given by |*pkeylen|. */ keytype = "RSA"; keylen = *pkeylen; } else if (gstr[0] >= '0' && gstr[0] <= '9') { /* Special case: only keylength given from string, so default to RSA */ keytype = "RSA"; /* The second part treatment will do the rest */ } else { const char *p = strchr(gstr, ':'); int len; if (p != NULL) len = p - gstr; else len = strlen(gstr); if (strncmp(gstr, "param", len) == 0) { expect_paramfile = 1; if (p == NULL) { BIO_printf(bio_err, "Parameter file requested but no path given: %s\n", gstr); return NULL; } } else { keytype = gstr; keytypelen = len; } if (p != NULL) gstr = gstr + len + 1; else gstr = NULL; } /* Treat the second part of gstr, if there is one */ if (gstr != NULL) { /* If the second part starts with a digit, we assume it's a size */ if (!expect_paramfile && gstr[0] >= '0' && gstr[0] <= '9') keylen = atol(gstr); else paramfile = gstr; } if (paramfile != NULL) { pbio = BIO_new_file(paramfile, "r"); if (pbio == NULL) { BIO_printf(bio_err, "Cannot open parameter file %s\n", paramfile); return NULL; } param = PEM_read_bio_Parameters(pbio, NULL); if (param == NULL) { X509 *x; (void)BIO_reset(pbio); x = PEM_read_bio_X509(pbio, NULL, NULL, NULL); if (x != NULL) { param = X509_get_pubkey(x); X509_free(x); } } BIO_free(pbio); if (param == NULL) { BIO_printf(bio_err, "Error reading parameter file %s\n", paramfile); return NULL; } if (keytype == NULL) { keytype = EVP_PKEY_get0_type_name(param); if (keytype == NULL) { EVP_PKEY_free(param); BIO_puts(bio_err, "Unable to determine key type\n"); return NULL; } } } if (keytypelen > 0) *pkeytype = OPENSSL_strndup(keytype, keytypelen); else *pkeytype = OPENSSL_strdup(keytype); if (*pkeytype == NULL) { BIO_printf(bio_err, "Out of memory\n"); EVP_PKEY_free(param); return NULL; } if (keylen >= 0) *pkeylen = keylen; if (param != NULL) { if (!EVP_PKEY_is_a(param, *pkeytype)) { BIO_printf(bio_err, "Key type does not match parameters\n"); EVP_PKEY_free(param); return NULL; } if (keygen_engine != NULL) gctx = EVP_PKEY_CTX_new(param, keygen_engine); else gctx = EVP_PKEY_CTX_new_from_pkey(app_get0_libctx(), param, app_get0_propq()); *pkeylen = EVP_PKEY_get_bits(param); EVP_PKEY_free(param); } else { if (keygen_engine != NULL) { int pkey_id = get_legacy_pkey_id(app_get0_libctx(), *pkeytype, keygen_engine); if (pkey_id != NID_undef) gctx = EVP_PKEY_CTX_new_id(pkey_id, keygen_engine); } else { gctx = EVP_PKEY_CTX_new_from_name(app_get0_libctx(), *pkeytype, app_get0_propq()); } } if (gctx == NULL) { BIO_puts(bio_err, "Error allocating keygen context\n"); return NULL; } if (EVP_PKEY_keygen_init(gctx) <= 0) { BIO_puts(bio_err, "Error initializing keygen context\n"); EVP_PKEY_CTX_free(gctx); return NULL; } if (keylen == -1 && (EVP_PKEY_CTX_is_a(gctx, "RSA") || EVP_PKEY_CTX_is_a(gctx, "RSA-PSS"))) keylen = *pkeylen; if (keylen != -1) { OSSL_PARAM params[] = { OSSL_PARAM_END, OSSL_PARAM_END }; size_t bits = keylen; params[0] = OSSL_PARAM_construct_size_t(OSSL_PKEY_PARAM_BITS, &bits); if (EVP_PKEY_CTX_set_params(gctx, params) <= 0) { BIO_puts(bio_err, "Error setting keysize\n"); EVP_PKEY_CTX_free(gctx); return NULL; } } return gctx; }
./openssl/apps/cmp.c
/* * Copyright 2007-2023 The OpenSSL Project Authors. All Rights Reserved. * Copyright Nokia 2007-2019 * Copyright Siemens AG 2015-2019 * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ /* This app is disabled when OPENSSL_NO_CMP is defined. */ #include <string.h> #include <ctype.h> #include "apps.h" #include "http_server.h" #include "s_apps.h" #include "progs.h" #include "cmp_mock_srv.h" /* tweaks needed due to missing unistd.h on Windows */ #if defined(_WIN32) && !defined(__BORLANDC__) # define access _access #endif #ifndef F_OK # define F_OK 0 #endif #include <openssl/ui.h> #include <openssl/pkcs12.h> #include <openssl/ssl.h> /* explicit #includes not strictly needed since implied by the above: */ #include <stdlib.h> #include <openssl/cmp.h> #include <openssl/cmp_util.h> #include <openssl/crmf.h> #include <openssl/crypto.h> #include <openssl/err.h> #include <openssl/store.h> #include <openssl/objects.h> #include <openssl/x509.h> static char *prog; static char *opt_config = NULL; #define CMP_SECTION "cmp" #define SECTION_NAME_MAX 40 /* max length of section name */ #define DEFAULT_SECTION "default" static char *opt_section = CMP_SECTION; static int opt_verbosity = OSSL_CMP_LOG_INFO; static int read_config(void); static CONF *conf = NULL; /* OpenSSL config file context structure */ static OSSL_CMP_CTX *cmp_ctx = NULL; /* the client-side CMP context */ /* the type of cmp command we want to send */ typedef enum { CMP_IR, CMP_KUR, CMP_CR, CMP_P10CR, CMP_RR, CMP_GENM } cmp_cmd_t; /* message transfer */ #if !defined(OPENSSL_NO_SOCK) && !defined(OPENSSL_NO_HTTP) static char *opt_server = NULL; static char *opt_proxy = NULL; static char *opt_no_proxy = NULL; #endif static char *opt_recipient = NULL; static char *opt_path = NULL; static int opt_keep_alive = 1; static int opt_msg_timeout = -1; static int opt_total_timeout = -1; /* server authentication */ static char *opt_trusted = NULL; static char *opt_untrusted = NULL; static char *opt_srvcert = NULL; static char *opt_expect_sender = NULL; static int opt_ignore_keyusage = 0; static int opt_unprotected_errors = 0; static int opt_no_cache_extracerts = 0; static char *opt_srvcertout = NULL; static char *opt_extracertsout = NULL; static char *opt_cacertsout = NULL; static char *opt_oldwithold = NULL; static char *opt_newwithnew = NULL; static char *opt_newwithold = NULL; static char *opt_oldwithnew = NULL; /* client authentication */ static char *opt_ref = NULL; static char *opt_secret = NULL; static char *opt_cert = NULL; static char *opt_own_trusted = NULL; static char *opt_key = NULL; static char *opt_keypass = NULL; static char *opt_digest = NULL; static char *opt_mac = NULL; static char *opt_extracerts = NULL; static int opt_unprotected_requests = 0; /* generic message */ static char *opt_cmd_s = NULL; static int opt_cmd = -1; static char *opt_geninfo = NULL; static char *opt_infotype_s = NULL; static int opt_infotype = NID_undef; static char *opt_profile = NULL; /* certificate enrollment */ static char *opt_newkey = NULL; static char *opt_newkeypass = NULL; static char *opt_subject = NULL; static int opt_days = 0; static char *opt_reqexts = NULL; static char *opt_sans = NULL; static int opt_san_nodefault = 0; static char *opt_policies = NULL; static char *opt_policy_oids = NULL; static int opt_policy_oids_critical = 0; static int opt_popo = OSSL_CRMF_POPO_NONE - 1; static char *opt_csr = NULL; static char *opt_out_trusted = NULL; static int opt_implicit_confirm = 0; static int opt_disable_confirm = 0; static char *opt_certout = NULL; static char *opt_chainout = NULL; /* certificate enrollment and revocation */ static char *opt_oldcert = NULL; static char *opt_issuer = NULL; static char *opt_serial = NULL; static int opt_revreason = CRL_REASON_NONE; /* credentials format */ static char *opt_certform_s = "PEM"; static int opt_certform = FORMAT_PEM; static char *opt_keyform_s = NULL; static int opt_keyform = FORMAT_UNDEF; static char *opt_otherpass = NULL; static char *opt_engine = NULL; #if !defined(OPENSSL_NO_SOCK) && !defined(OPENSSL_NO_HTTP) /* TLS connection */ static int opt_tls_used = 0; static char *opt_tls_cert = NULL; static char *opt_tls_key = NULL; static char *opt_tls_keypass = NULL; static char *opt_tls_extra = NULL; static char *opt_tls_trusted = NULL; static char *opt_tls_host = NULL; #endif /* client-side debugging */ static int opt_batch = 0; static int opt_repeat = 1; static char *opt_reqin = NULL; static int opt_reqin_new_tid = 0; static char *opt_reqout = NULL; static char *opt_rspin = NULL; static int rspin_in_use = 0; static char *opt_rspout = NULL; static int opt_use_mock_srv = 0; /* mock server */ #if !defined(OPENSSL_NO_SOCK) && !defined(OPENSSL_NO_HTTP) static char *opt_port = NULL; static int opt_max_msgs = 0; #endif static char *opt_srv_ref = NULL; static char *opt_srv_secret = NULL; static char *opt_srv_cert = NULL; static char *opt_srv_key = NULL; static char *opt_srv_keypass = NULL; static char *opt_srv_trusted = NULL; static char *opt_srv_untrusted = NULL; static char *opt_ref_cert = NULL; static char *opt_rsp_cert = NULL; static char *opt_rsp_extracerts = NULL; static char *opt_rsp_capubs = NULL; static char *opt_rsp_newwithnew = NULL; static char *opt_rsp_newwithold = NULL; static char *opt_rsp_oldwithnew = NULL; static int opt_poll_count = 0; static int opt_check_after = 1; static int opt_grant_implicitconf = 0; static int opt_pkistatus = OSSL_CMP_PKISTATUS_accepted; static int opt_failure = INT_MIN; static int opt_failurebits = 0; static char *opt_statusstring = NULL; static int opt_send_error = 0; static int opt_send_unprotected = 0; static int opt_send_unprot_err = 0; static int opt_accept_unprotected = 0; static int opt_accept_unprot_err = 0; static int opt_accept_raverified = 0; static X509_VERIFY_PARAM *vpm = NULL; typedef enum OPTION_choice { OPT_COMMON, OPT_CONFIG, OPT_SECTION, OPT_VERBOSITY, OPT_CMD, OPT_INFOTYPE, OPT_PROFILE, OPT_GENINFO, OPT_NEWKEY, OPT_NEWKEYPASS, OPT_SUBJECT, OPT_DAYS, OPT_REQEXTS, OPT_SANS, OPT_SAN_NODEFAULT, OPT_POLICIES, OPT_POLICY_OIDS, OPT_POLICY_OIDS_CRITICAL, OPT_POPO, OPT_CSR, OPT_OUT_TRUSTED, OPT_IMPLICIT_CONFIRM, OPT_DISABLE_CONFIRM, OPT_CERTOUT, OPT_CHAINOUT, OPT_OLDCERT, OPT_ISSUER, OPT_SERIAL, OPT_REVREASON, #if !defined(OPENSSL_NO_SOCK) && !defined(OPENSSL_NO_HTTP) OPT_SERVER, OPT_PROXY, OPT_NO_PROXY, #endif OPT_RECIPIENT, OPT_PATH, OPT_KEEP_ALIVE, OPT_MSG_TIMEOUT, OPT_TOTAL_TIMEOUT, OPT_TRUSTED, OPT_UNTRUSTED, OPT_SRVCERT, OPT_EXPECT_SENDER, OPT_IGNORE_KEYUSAGE, OPT_UNPROTECTED_ERRORS, OPT_NO_CACHE_EXTRACERTS, OPT_SRVCERTOUT, OPT_EXTRACERTSOUT, OPT_CACERTSOUT, OPT_OLDWITHOLD, OPT_NEWWITHNEW, OPT_NEWWITHOLD, OPT_OLDWITHNEW, OPT_REF, OPT_SECRET, OPT_CERT, OPT_OWN_TRUSTED, OPT_KEY, OPT_KEYPASS, OPT_DIGEST, OPT_MAC, OPT_EXTRACERTS, OPT_UNPROTECTED_REQUESTS, OPT_CERTFORM, OPT_KEYFORM, OPT_OTHERPASS, #ifndef OPENSSL_NO_ENGINE OPT_ENGINE, #endif OPT_PROV_ENUM, OPT_R_ENUM, #if !defined(OPENSSL_NO_SOCK) && !defined(OPENSSL_NO_HTTP) OPT_TLS_USED, OPT_TLS_CERT, OPT_TLS_KEY, OPT_TLS_KEYPASS, OPT_TLS_EXTRA, OPT_TLS_TRUSTED, OPT_TLS_HOST, #endif OPT_BATCH, OPT_REPEAT, OPT_REQIN, OPT_REQIN_NEW_TID, OPT_REQOUT, OPT_RSPIN, OPT_RSPOUT, OPT_USE_MOCK_SRV, #if !defined(OPENSSL_NO_SOCK) && !defined(OPENSSL_NO_HTTP) OPT_PORT, OPT_MAX_MSGS, #endif OPT_SRV_REF, OPT_SRV_SECRET, OPT_SRV_CERT, OPT_SRV_KEY, OPT_SRV_KEYPASS, OPT_SRV_TRUSTED, OPT_SRV_UNTRUSTED, OPT_REF_CERT, OPT_RSP_CERT, OPT_RSP_EXTRACERTS, OPT_RSP_CAPUBS, OPT_RSP_NEWWITHNEW, OPT_RSP_NEWWITHOLD, OPT_RSP_OLDWITHNEW, OPT_POLL_COUNT, OPT_CHECK_AFTER, OPT_GRANT_IMPLICITCONF, OPT_PKISTATUS, OPT_FAILURE, OPT_FAILUREBITS, OPT_STATUSSTRING, OPT_SEND_ERROR, OPT_SEND_UNPROTECTED, OPT_SEND_UNPROT_ERR, OPT_ACCEPT_UNPROTECTED, OPT_ACCEPT_UNPROT_ERR, OPT_ACCEPT_RAVERIFIED, OPT_V_ENUM } OPTION_CHOICE; const OPTIONS cmp_options[] = { /* entries must be in the same order as enumerated above!! */ {"help", OPT_HELP, '-', "Display this summary"}, {"config", OPT_CONFIG, 's', "Configuration file to use. \"\" = none. Default from env variable OPENSSL_CONF"}, {"section", OPT_SECTION, 's', "Section(s) in config file to get options from. \"\" = 'default'. Default 'cmp'"}, {"verbosity", OPT_VERBOSITY, 'N', "Log level; 3=ERR, 4=WARN, 6=INFO, 7=DEBUG, 8=TRACE. Default 6 = INFO"}, OPT_SECTION("Generic message"), {"cmd", OPT_CMD, 's', "CMP request to send: ir/cr/kur/p10cr/rr/genm"}, {"infotype", OPT_INFOTYPE, 's', "InfoType name for requesting specific info in genm, with specific support"}, {OPT_MORE_STR, 0, 0, "for 'caCerts' and 'rootCaCert'"}, {"profile", OPT_PROFILE, 's', "Certificate profile name to place in generalInfo field of request PKIHeader"}, {"geninfo", OPT_GENINFO, 's', "Comma-separated list of OID and value to place in generalInfo PKIHeader"}, {OPT_MORE_STR, 0, 0, "of form <OID>:int:<n> or <OID>:str:<s>, e.g. \'1.2.3.4:int:56789, id-kp:str:name'"}, OPT_SECTION("Certificate enrollment"), {"newkey", OPT_NEWKEY, 's', "Private or public key for the requested cert. Default: CSR key or client key"}, {"newkeypass", OPT_NEWKEYPASS, 's', "New private key pass phrase source"}, {"subject", OPT_SUBJECT, 's', "Distinguished Name (DN) of subject to use in the requested cert template"}, {OPT_MORE_STR, 0, 0, "For kur, default is subject of -csr arg or reference cert (see -oldcert)"}, {OPT_MORE_STR, 0, 0, "this default is used for ir and cr only if no Subject Alt Names are set"}, {"days", OPT_DAYS, 'N', "Requested validity time of the new certificate in number of days"}, {"reqexts", OPT_REQEXTS, 's', "Name of config file section defining certificate request extensions."}, {OPT_MORE_STR, 0, 0, "Augments or replaces any extensions contained CSR given with -csr"}, {"sans", OPT_SANS, 's', "Subject Alt Names (IPADDR/DNS/URI) to add as (critical) cert req extension"}, {"san_nodefault", OPT_SAN_NODEFAULT, '-', "Do not take default SANs from reference certificate (see -oldcert)"}, {"policies", OPT_POLICIES, 's', "Name of config file section defining policies certificate request extension"}, {"policy_oids", OPT_POLICY_OIDS, 's', "Policy OID(s) to add as policies certificate request extension"}, {"policy_oids_critical", OPT_POLICY_OIDS_CRITICAL, '-', "Flag the policy OID(s) given with -policy_oids as critical"}, {"popo", OPT_POPO, 'n', "Proof-of-Possession (POPO) method to use for ir/cr/kur where"}, {OPT_MORE_STR, 0, 0, "-1 = NONE, 0 = RAVERIFIED, 1 = SIGNATURE (default), 2 = KEYENC"}, {"csr", OPT_CSR, 's', "PKCS#10 CSR file in PEM or DER format to convert or to use in p10cr"}, {"out_trusted", OPT_OUT_TRUSTED, 's', "Certificates to trust when verifying newly enrolled certificates"}, {"implicit_confirm", OPT_IMPLICIT_CONFIRM, '-', "Request implicit confirmation of newly enrolled certificates"}, {"disable_confirm", OPT_DISABLE_CONFIRM, '-', "Do not confirm newly enrolled certificate w/o requesting implicit"}, {OPT_MORE_STR, 0, 0, "confirmation. WARNING: This leads to behavior violating RFC 4210"}, {"certout", OPT_CERTOUT, 's', "File to save newly enrolled certificate"}, {"chainout", OPT_CHAINOUT, 's', "File to save the chain of newly enrolled certificate"}, OPT_SECTION("Certificate enrollment and revocation"), {"oldcert", OPT_OLDCERT, 's', "Certificate to be updated (defaulting to -cert) or to be revoked in rr;"}, {OPT_MORE_STR, 0, 0, "also used as reference (defaulting to -cert) for subject DN and SANs."}, {OPT_MORE_STR, 0, 0, "Issuer is used as recipient unless -recipient, -srvcert, or -issuer given"}, {"issuer", OPT_ISSUER, 's', "DN of the issuer to place in the certificate template of ir/cr/kur/rr;"}, {OPT_MORE_STR, 0, 0, "also used as recipient if neither -recipient nor -srvcert are given"}, {"serial", OPT_SERIAL, 's', "Serial number of certificate to be revoked in revocation request (rr)"}, {"revreason", OPT_REVREASON, 'n', "Reason code to include in revocation request (rr); possible values:"}, {OPT_MORE_STR, 0, 0, "0..6, 8..10 (see RFC5280, 5.3.1) or -1. Default -1 = none included"}, OPT_SECTION("Message transfer"), #if defined(OPENSSL_NO_SOCK) || defined(OPENSSL_NO_HTTP) {OPT_MORE_STR, 0, 0, "NOTE: -server, -proxy, and -no_proxy not supported due to no-sock/no-http build"}, #else {"server", OPT_SERVER, 's', "[http[s]://]address[:port][/path] of CMP server. Default port 80 or 443."}, {OPT_MORE_STR, 0, 0, "address may be a DNS name or an IP address; path can be overridden by -path"}, {"proxy", OPT_PROXY, 's', "[http[s]://]address[:port][/path] of HTTP(S) proxy to use; path is ignored"}, {"no_proxy", OPT_NO_PROXY, 's', "List of addresses of servers not to use HTTP(S) proxy for"}, {OPT_MORE_STR, 0, 0, "Default from environment variable 'no_proxy', else 'NO_PROXY', else none"}, #endif {"recipient", OPT_RECIPIENT, 's', "DN of CA. Default: subject of -srvcert, -issuer, issuer of -oldcert or -cert"}, {"path", OPT_PATH, 's', "HTTP path (aka CMP alias) at the CMP server. Default from -server, else \"/\""}, {"keep_alive", OPT_KEEP_ALIVE, 'N', "Persistent HTTP connections. 0: no, 1 (the default): request, 2: require"}, {"msg_timeout", OPT_MSG_TIMEOUT, 'N', "Number of seconds allowed per CMP message round trip, or 0 for infinite"}, {"total_timeout", OPT_TOTAL_TIMEOUT, 'N', "Overall time an enrollment incl. polling may take. Default 0 = infinite"}, OPT_SECTION("Server authentication"), {"trusted", OPT_TRUSTED, 's', "Certificates to use as trust anchors when verifying signed CMP responses"}, {OPT_MORE_STR, 0, 0, "unless -srvcert is given"}, {"untrusted", OPT_UNTRUSTED, 's', "Intermediate CA certs for chain construction for CMP/TLS/enrolled certs"}, {"srvcert", OPT_SRVCERT, 's', "Server cert to pin and trust directly when verifying signed CMP responses"}, {"expect_sender", OPT_EXPECT_SENDER, 's', "DN of expected sender of responses. Defaults to subject of -srvcert, if any"}, {"ignore_keyusage", OPT_IGNORE_KEYUSAGE, '-', "Ignore CMP signer cert key usage, else 'digitalSignature' must be allowed"}, {"unprotected_errors", OPT_UNPROTECTED_ERRORS, '-', "Accept missing or invalid protection of regular error messages and negative"}, {OPT_MORE_STR, 0, 0, "certificate responses (ip/cp/kup), revocation responses (rp), and PKIConf"}, {OPT_MORE_STR, 0, 0, "WARNING: This setting leads to behavior allowing violation of RFC 4210"}, {"no_cache_extracerts", OPT_NO_CACHE_EXTRACERTS, '-', "Do not keep certificates received in the extraCerts CMP message field"}, { "srvcertout", OPT_SRVCERTOUT, 's', "File to save the server cert used and validated for CMP response protection"}, {"extracertsout", OPT_EXTRACERTSOUT, 's', "File to save extra certificates received in the extraCerts field"}, {"cacertsout", OPT_CACERTSOUT, 's', "File to save CA certs received in caPubs field or genp with id-it-caCerts"}, { "oldwithold", OPT_OLDWITHOLD, 's', "Root CA certificate to request update for in genm of type rootCaCert"}, { "newwithnew", OPT_NEWWITHNEW, 's', "File to save NewWithNew cert received in genp of type rootCaKeyUpdate"}, { "newwithold", OPT_NEWWITHOLD, 's', "File to save NewWithOld cert received in genp of type rootCaKeyUpdate"}, { "oldwithnew", OPT_OLDWITHNEW, 's', "File to save OldWithNew cert received in genp of type rootCaKeyUpdate"}, OPT_SECTION("Client authentication"), {"ref", OPT_REF, 's', "Reference value to use as senderKID in case no -cert is given"}, {"secret", OPT_SECRET, 's', "Prefer PBM (over signatures) for protecting msgs with given password source"}, {"cert", OPT_CERT, 's', "Client's CMP signer certificate; its public key must match the -key argument"}, {OPT_MORE_STR, 0, 0, "This also used as default reference for subject DN and SANs."}, {OPT_MORE_STR, 0, 0, "Any further certs included are appended to the untrusted certs"}, {"own_trusted", OPT_OWN_TRUSTED, 's', "Optional certs to verify chain building for own CMP signer cert"}, {"key", OPT_KEY, 's', "CMP signer private key, not used when -secret given"}, {"keypass", OPT_KEYPASS, 's', "Client private key (and cert and old cert) pass phrase source"}, {"digest", OPT_DIGEST, 's', "Digest to use in message protection and POPO signatures. Default \"sha256\""}, {"mac", OPT_MAC, 's', "MAC algorithm to use in PBM-based message protection. Default \"hmac-sha1\""}, {"extracerts", OPT_EXTRACERTS, 's', "Certificates to append in extraCerts field of outgoing messages."}, {OPT_MORE_STR, 0, 0, "This can be used as the default CMP signer cert chain to include"}, {"unprotected_requests", OPT_UNPROTECTED_REQUESTS, '-', "Send request messages without CMP-level protection"}, OPT_SECTION("Credentials format"), {"certform", OPT_CERTFORM, 's', "Format (PEM or DER) to use when saving a certificate to a file. Default PEM"}, {"keyform", OPT_KEYFORM, 's', "Format of the key input (ENGINE, other values ignored)"}, {"otherpass", OPT_OTHERPASS, 's', "Pass phrase source potentially needed for loading certificates of others"}, #ifndef OPENSSL_NO_ENGINE {"engine", OPT_ENGINE, 's', "Use crypto engine with given identifier, possibly a hardware device."}, {OPT_MORE_STR, 0, 0, "Engines may also be defined in OpenSSL config file engine section."}, #endif OPT_PROV_OPTIONS, OPT_R_OPTIONS, OPT_SECTION("TLS connection"), #if defined(OPENSSL_NO_SOCK) || defined(OPENSSL_NO_HTTP) {OPT_MORE_STR, 0, 0, "NOTE: -tls_used and all other TLS options not supported due to no-sock/no-http build"}, #else {"tls_used", OPT_TLS_USED, '-', "Enable using TLS (also when other TLS options are not set)"}, {"tls_cert", OPT_TLS_CERT, 's', "Client's TLS certificate. May include chain to be provided to TLS server"}, {"tls_key", OPT_TLS_KEY, 's', "Private key for the client's TLS certificate"}, {"tls_keypass", OPT_TLS_KEYPASS, 's', "Pass phrase source for the client's private TLS key (and TLS cert)"}, {"tls_extra", OPT_TLS_EXTRA, 's', "Extra certificates to provide to TLS server during TLS handshake"}, {"tls_trusted", OPT_TLS_TRUSTED, 's', "Trusted certificates to use for verifying the TLS server certificate;"}, {OPT_MORE_STR, 0, 0, "this implies hostname validation"}, {"tls_host", OPT_TLS_HOST, 's', "Address to be checked (rather than -server) during TLS hostname validation"}, #endif OPT_SECTION("Client-side debugging"), {"batch", OPT_BATCH, '-', "Do not interactively prompt for input when a password is required etc."}, {"repeat", OPT_REPEAT, 'p', "Invoke the transaction the given positive number of times. Default 1"}, {"reqin", OPT_REQIN, 's', "Take sequence of CMP requests to send to server from file(s)"}, {"reqin_new_tid", OPT_REQIN_NEW_TID, '-', "Use fresh transactionID for CMP requests read from -reqin"}, {"reqout", OPT_REQOUT, 's', "Save sequence of CMP requests created by the client to file(s)"}, {"rspin", OPT_RSPIN, 's', "Process sequence of CMP responses provided in file(s), skipping server"}, {"rspout", OPT_RSPOUT, 's', "Save sequence of actually used CMP responses to file(s)"}, {"use_mock_srv", OPT_USE_MOCK_SRV, '-', "Use internal mock server at API level, bypassing socket-based HTTP"}, OPT_SECTION("Mock server"), #if defined(OPENSSL_NO_SOCK) || defined(OPENSSL_NO_HTTP) {OPT_MORE_STR, 0, 0, "NOTE: -port and -max_msgs not supported due to no-sock/no-http build"}, #else {"port", OPT_PORT, 's', "Act as HTTP-based mock server listening on given port"}, {"max_msgs", OPT_MAX_MSGS, 'N', "max number of messages handled by HTTP mock server. Default: 0 = unlimited"}, #endif {"srv_ref", OPT_SRV_REF, 's', "Reference value to use as senderKID of server in case no -srv_cert is given"}, {"srv_secret", OPT_SRV_SECRET, 's', "Password source for server authentication with a pre-shared key (secret)"}, {"srv_cert", OPT_SRV_CERT, 's', "Certificate of the server"}, {"srv_key", OPT_SRV_KEY, 's', "Private key used by the server for signing messages"}, {"srv_keypass", OPT_SRV_KEYPASS, 's', "Server private key (and cert) pass phrase source"}, {"srv_trusted", OPT_SRV_TRUSTED, 's', "Trusted certificates for client authentication"}, {"srv_untrusted", OPT_SRV_UNTRUSTED, 's', "Intermediate certs that may be useful for verifying CMP protection"}, {"ref_cert", OPT_RSP_CERT, 's', "Certificate to be expected for rr and any oldCertID in kur messages"}, {"rsp_cert", OPT_RSP_CERT, 's', "Certificate to be returned as mock enrollment result"}, {"rsp_extracerts", OPT_RSP_EXTRACERTS, 's', "Extra certificates to be included in mock certification responses"}, {"rsp_capubs", OPT_RSP_CAPUBS, 's', "CA certificates to be included in mock ip response"}, {"rsp_newwithnew", OPT_RSP_NEWWITHNEW, 's', "New root CA certificate to include in genp of type rootCaKeyUpdate"}, {"rsp_newwithold", OPT_RSP_NEWWITHOLD, 's', "NewWithOld transition cert to include in genp of type rootCaKeyUpdate"}, {"rsp_oldwithnew", OPT_RSP_OLDWITHNEW, 's', "OldWithNew transition cert to include in genp of type rootCaKeyUpdate"}, {"poll_count", OPT_POLL_COUNT, 'N', "Number of times the client must poll before receiving a certificate"}, {"check_after", OPT_CHECK_AFTER, 'N', "The check_after value (time to wait) to include in poll response"}, {"grant_implicitconf", OPT_GRANT_IMPLICITCONF, '-', "Grant implicit confirmation of newly enrolled certificate"}, {"pkistatus", OPT_PKISTATUS, 'N', "PKIStatus to be included in server response. Possible values: 0..6"}, {"failure", OPT_FAILURE, 'N', "A single failure info bit number to include in server response, 0..26"}, {"failurebits", OPT_FAILUREBITS, 'N', "Number representing failure bits to include in server response, 0..2^27 - 1"}, {"statusstring", OPT_STATUSSTRING, 's', "Status string to be included in server response"}, {"send_error", OPT_SEND_ERROR, '-', "Force server to reply with error message"}, {"send_unprotected", OPT_SEND_UNPROTECTED, '-', "Send response messages without CMP-level protection"}, {"send_unprot_err", OPT_SEND_UNPROT_ERR, '-', "In case of negative responses, server shall send unprotected error messages,"}, {OPT_MORE_STR, 0, 0, "certificate responses (ip/cp/kup), and revocation responses (rp)."}, {OPT_MORE_STR, 0, 0, "WARNING: This setting leads to behavior violating RFC 4210"}, {"accept_unprotected", OPT_ACCEPT_UNPROTECTED, '-', "Accept missing or invalid protection of requests"}, {"accept_unprot_err", OPT_ACCEPT_UNPROT_ERR, '-', "Accept unprotected error messages from client"}, {"accept_raverified", OPT_ACCEPT_RAVERIFIED, '-', "Accept RAVERIFIED as proof-of-possession (POPO)"}, OPT_V_OPTIONS, {NULL} }; typedef union { char **txt; int *num; long *num_long; } varref; static varref cmp_vars[] = { /* must be in same order as enumerated above! */ {&opt_config}, {&opt_section}, {(char **)&opt_verbosity}, {&opt_cmd_s}, {&opt_infotype_s}, {&opt_profile}, {&opt_geninfo}, {&opt_newkey}, {&opt_newkeypass}, {&opt_subject}, {(char **)&opt_days}, {&opt_reqexts}, {&opt_sans}, {(char **)&opt_san_nodefault}, {&opt_policies}, {&opt_policy_oids}, {(char **)&opt_policy_oids_critical}, {(char **)&opt_popo}, {&opt_csr}, {&opt_out_trusted}, {(char **)&opt_implicit_confirm}, {(char **)&opt_disable_confirm}, {&opt_certout}, {&opt_chainout}, {&opt_oldcert}, {&opt_issuer}, {&opt_serial}, {(char **)&opt_revreason}, #if !defined(OPENSSL_NO_SOCK) && !defined(OPENSSL_NO_HTTP) {&opt_server}, {&opt_proxy}, {&opt_no_proxy}, #endif {&opt_recipient}, {&opt_path}, {(char **)&opt_keep_alive}, {(char **)&opt_msg_timeout}, {(char **)&opt_total_timeout}, {&opt_trusted}, {&opt_untrusted}, {&opt_srvcert}, {&opt_expect_sender}, {(char **)&opt_ignore_keyusage}, {(char **)&opt_unprotected_errors}, {(char **)&opt_no_cache_extracerts}, {&opt_srvcertout}, {&opt_extracertsout}, {&opt_cacertsout}, {&opt_oldwithold}, {&opt_newwithnew}, {&opt_newwithold}, {&opt_oldwithnew}, {&opt_ref}, {&opt_secret}, {&opt_cert}, {&opt_own_trusted}, {&opt_key}, {&opt_keypass}, {&opt_digest}, {&opt_mac}, {&opt_extracerts}, {(char **)&opt_unprotected_requests}, {&opt_certform_s}, {&opt_keyform_s}, {&opt_otherpass}, #ifndef OPENSSL_NO_ENGINE {&opt_engine}, #endif #if !defined(OPENSSL_NO_SOCK) && !defined(OPENSSL_NO_HTTP) {(char **)&opt_tls_used}, {&opt_tls_cert}, {&opt_tls_key}, {&opt_tls_keypass}, {&opt_tls_extra}, {&opt_tls_trusted}, {&opt_tls_host}, #endif {(char **)&opt_batch}, {(char **)&opt_repeat}, {&opt_reqin}, {(char **)&opt_reqin_new_tid}, {&opt_reqout}, {&opt_rspin}, {&opt_rspout}, {(char **)&opt_use_mock_srv}, #if !defined(OPENSSL_NO_SOCK) && !defined(OPENSSL_NO_HTTP) {&opt_port}, {(char **)&opt_max_msgs}, #endif {&opt_srv_ref}, {&opt_srv_secret}, {&opt_srv_cert}, {&opt_srv_key}, {&opt_srv_keypass}, {&opt_srv_trusted}, {&opt_srv_untrusted}, {&opt_ref_cert}, {&opt_rsp_cert}, {&opt_rsp_extracerts}, {&opt_rsp_capubs}, {&opt_rsp_newwithnew}, {&opt_rsp_newwithold}, {&opt_rsp_oldwithnew}, {(char **)&opt_poll_count}, {(char **)&opt_check_after}, {(char **)&opt_grant_implicitconf}, {(char **)&opt_pkistatus}, {(char **)&opt_failure}, {(char **)&opt_failurebits}, {&opt_statusstring}, {(char **)&opt_send_error}, {(char **)&opt_send_unprotected}, {(char **)&opt_send_unprot_err}, {(char **)&opt_accept_unprotected}, {(char **)&opt_accept_unprot_err}, {(char **)&opt_accept_raverified}, {NULL} }; #define FUNC (strcmp(OPENSSL_FUNC, "(unknown function)") == 0 \ ? "CMP" : OPENSSL_FUNC) #define CMP_print(bio, level, prefix, msg, a1, a2, a3) \ ((void)(level > opt_verbosity ? 0 : \ (BIO_printf(bio, "%s:%s:%d:CMP %s: " msg "\n", \ FUNC, OPENSSL_FILE, OPENSSL_LINE, prefix, a1, a2, a3)))) #define CMP_DEBUG(m, a1, a2, a3) \ CMP_print(bio_out, OSSL_CMP_LOG_DEBUG, "debug", m, a1, a2, a3) #define CMP_debug(msg) CMP_DEBUG(msg"%s%s%s", "", "", "") #define CMP_debug1(msg, a1) CMP_DEBUG(msg"%s%s", a1, "", "") #define CMP_debug2(msg, a1, a2) CMP_DEBUG(msg"%s", a1, a2, "") #define CMP_debug3(msg, a1, a2, a3) CMP_DEBUG(msg, a1, a2, a3) #define CMP_INFO(msg, a1, a2, a3) \ CMP_print(bio_out, OSSL_CMP_LOG_INFO, "info", msg, a1, a2, a3) #define CMP_info(msg) CMP_INFO(msg"%s%s%s", "", "", "") #define CMP_info1(msg, a1) CMP_INFO(msg"%s%s", a1, "", "") #define CMP_info2(msg, a1, a2) CMP_INFO(msg"%s", a1, a2, "") #define CMP_info3(msg, a1, a2, a3) CMP_INFO(msg, a1, a2, a3) #define CMP_WARN(m, a1, a2, a3) \ CMP_print(bio_out, OSSL_CMP_LOG_WARNING, "warning", m, a1, a2, a3) #define CMP_warn(msg) CMP_WARN(msg"%s%s%s", "", "", "") #define CMP_warn1(msg, a1) CMP_WARN(msg"%s%s", a1, "", "") #define CMP_warn2(msg, a1, a2) CMP_WARN(msg"%s", a1, a2, "") #define CMP_warn3(msg, a1, a2, a3) CMP_WARN(msg, a1, a2, a3) #define CMP_ERR(msg, a1, a2, a3) \ CMP_print(bio_err, OSSL_CMP_LOG_ERR, "error", msg, a1, a2, a3) #define CMP_err(msg) CMP_ERR(msg"%s%s%s", "", "", "") #define CMP_err1(msg, a1) CMP_ERR(msg"%s%s", a1, "", "") #define CMP_err2(msg, a1, a2) CMP_ERR(msg"%s", a1, a2, "") #define CMP_err3(msg, a1, a2, a3) CMP_ERR(msg, a1, a2, a3) static 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); } static int print_to_bio_err(const char *func, const char *file, int line, OSSL_CMP_severity level, const char *msg) { return OSSL_CMP_print_to_bio(bio_err, func, file, line, level, msg); } static int set_verbosity(int level) { if (level < OSSL_CMP_LOG_EMERG || level > OSSL_CMP_LOG_MAX) { CMP_err1("Logging verbosity level %d out of range (0 .. 8)", level); return 0; } opt_verbosity = level; return 1; } static EVP_PKEY *load_key_pwd(const char *uri, int format, const char *pass, ENGINE *eng, const char *desc) { char *pass_string = get_passwd(pass, desc); EVP_PKEY *pkey = load_key(uri, format, 0, pass_string, eng, desc); clear_free(pass_string); return pkey; } static X509 *load_cert_pwd(const char *uri, const char *pass, const char *desc) { X509 *cert; char *pass_string = get_passwd(pass, desc); cert = load_cert_pass(uri, FORMAT_UNDEF, 0, pass_string, desc); clear_free(pass_string); return cert; } /* set expected hostname/IP addr and clears the email addr in the given ts */ static int truststore_set_host_etc(X509_STORE *ts, const char *host) { X509_VERIFY_PARAM *ts_vpm = X509_STORE_get0_param(ts); /* first clear any hostnames, IP, and email addresses */ if (!X509_VERIFY_PARAM_set1_host(ts_vpm, NULL, 0) || !X509_VERIFY_PARAM_set1_ip(ts_vpm, NULL, 0) || !X509_VERIFY_PARAM_set1_email(ts_vpm, NULL, 0)) return 0; X509_VERIFY_PARAM_set_hostflags(ts_vpm, X509_CHECK_FLAG_ALWAYS_CHECK_SUBJECT | X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS); return (host != NULL && X509_VERIFY_PARAM_set1_ip_asc(ts_vpm, host)) || X509_VERIFY_PARAM_set1_host(ts_vpm, host, 0); } /* write OSSL_CMP_MSG DER-encoded to the specified file name item */ static int write_PKIMESSAGE(const OSSL_CMP_MSG *msg, char **filenames) { char *file; if (msg == NULL || filenames == NULL) { CMP_err("NULL arg to write_PKIMESSAGE"); return 0; } if (*filenames == NULL) { CMP_err("not enough file names provided for writing PKIMessage"); return 0; } file = *filenames; *filenames = next_item(file); if (OSSL_CMP_MSG_write(file, msg) < 0) { CMP_err1("cannot write PKIMessage to file '%s'", file); return 0; } return 1; } /* read DER-encoded OSSL_CMP_MSG from the specified file name item */ static OSSL_CMP_MSG *read_PKIMESSAGE(const char *desc, char **filenames) { char *file; OSSL_CMP_MSG *ret; if (filenames == NULL || desc == NULL) { CMP_err("NULL arg to read_PKIMESSAGE"); return NULL; } if (*filenames == NULL) { CMP_err("not enough file names provided for reading PKIMessage"); return NULL; } file = *filenames; *filenames = next_item(file); ret = OSSL_CMP_MSG_read(file, app_get0_libctx(), app_get0_propq()); if (ret == NULL) CMP_err1("cannot read PKIMessage from file '%s'", file); else CMP_info2("%s %s", desc, file); return ret; } /*- * Sends the PKIMessage req and on success place the response in *res * basically like OSSL_CMP_MSG_http_perform(), but in addition allows * to dump the sequence of requests and responses to files and/or * to take the sequence of requests and responses from files. */ static OSSL_CMP_MSG *read_write_req_resp(OSSL_CMP_CTX *ctx, const OSSL_CMP_MSG *req) { OSSL_CMP_MSG *req_new = NULL; OSSL_CMP_MSG *res = NULL; OSSL_CMP_PKIHEADER *hdr; const char *prev_opt_rspin = opt_rspin; if (opt_reqout != NULL && !write_PKIMESSAGE(req, &opt_reqout)) goto err; if (opt_reqin != NULL && opt_rspin == NULL) { if ((req_new = read_PKIMESSAGE("actually sending", &opt_reqin)) == NULL) goto err; /*- * The transaction ID in req_new read from opt_reqin may not be fresh. * In this case the server may complain "Transaction id already in use." * The following workaround unfortunately requires re-protection. */ if (opt_reqin_new_tid && !OSSL_CMP_MSG_update_transactionID(ctx, req_new)) goto err; /* * Except for first request, need to satisfy recipNonce check by server. * Unfortunately requires re-protection if protection is required. */ if (!OSSL_CMP_MSG_update_recipNonce(ctx, req_new)) goto err; } if (opt_rspin != NULL) { res = read_PKIMESSAGE("actually using", &opt_rspin); } else { const OSSL_CMP_MSG *actual_req = req_new != NULL ? req_new : req; if (opt_use_mock_srv) { if (rspin_in_use) CMP_warn("too few -rspin filename arguments; resorting to using mock server"); res = OSSL_CMP_CTX_server_perform(ctx, actual_req); } else { #if !defined(OPENSSL_NO_SOCK) && !defined(OPENSSL_NO_HTTP) if (opt_server == NULL) { CMP_err("missing -server or -use_mock_srv option, or too few -rspin filename arguments"); goto err; } if (rspin_in_use) CMP_warn("too few -rspin filename arguments; resorting to contacting server"); res = OSSL_CMP_MSG_http_perform(ctx, actual_req); #else CMP_err("-server not supported on no-sock/no-http build; missing -use_mock_srv option or too few -rspin filename arguments"); #endif } rspin_in_use = 0; } if (res == NULL) goto err; if (req_new != NULL || prev_opt_rspin != NULL) { /* need to satisfy nonce and transactionID checks by client */ ASN1_OCTET_STRING *nonce; ASN1_OCTET_STRING *tid; hdr = OSSL_CMP_MSG_get0_header(res); nonce = OSSL_CMP_HDR_get0_recipNonce(hdr); tid = OSSL_CMP_HDR_get0_transactionID(hdr); if (!OSSL_CMP_CTX_set1_senderNonce(ctx, nonce) || !OSSL_CMP_CTX_set1_transactionID(ctx, tid)) { OSSL_CMP_MSG_free(res); res = NULL; goto err; } } if (opt_rspout != NULL && !write_PKIMESSAGE(res, &opt_rspout)) { OSSL_CMP_MSG_free(res); res = NULL; } err: OSSL_CMP_MSG_free(req_new); return res; } static int set_name(const char *str, int (*set_fn) (OSSL_CMP_CTX *ctx, const X509_NAME *name), OSSL_CMP_CTX *ctx, const char *desc) { if (str != NULL) { X509_NAME *n = parse_name(str, MBSTRING_ASC, 1, desc); if (n == NULL) return 0; if (!(*set_fn) (ctx, n)) { X509_NAME_free(n); CMP_err("out of memory"); return 0; } X509_NAME_free(n); } return 1; } static int set_gennames(OSSL_CMP_CTX *ctx, char *names, const char *desc) { char *next; for (; names != NULL; names = next) { GENERAL_NAME *n; next = next_item(names); if (strcmp(names, "critical") == 0) { (void)OSSL_CMP_CTX_set_option(ctx, OSSL_CMP_OPT_SUBJECTALTNAME_CRITICAL, 1); continue; } /* try IP address first, then email/URI/domain name */ (void)ERR_set_mark(); n = a2i_GENERAL_NAME(NULL, NULL, NULL, GEN_IPADD, names, 0); if (n == NULL) n = a2i_GENERAL_NAME(NULL, NULL, NULL, strchr(names, '@') != NULL ? GEN_EMAIL : strchr(names, ':') != NULL ? GEN_URI : GEN_DNS, names, 0); (void)ERR_pop_to_mark(); if (n == NULL) { CMP_err2("bad syntax of %s '%s'", desc, names); return 0; } if (!OSSL_CMP_CTX_push1_subjectAltName(ctx, n)) { GENERAL_NAME_free(n); CMP_err("out of memory"); return 0; } GENERAL_NAME_free(n); } return 1; } static X509_STORE *load_trusted(char *input, int for_new_cert, const char *desc) { X509_STORE *ts = load_certstore(input, opt_otherpass, desc, vpm); if (ts == NULL) return NULL; X509_STORE_set_verify_cb(ts, X509_STORE_CTX_print_verify_cb); /* copy vpm to store */ if (X509_STORE_set1_param(ts, vpm /* may be NULL */) && (for_new_cert || truststore_set_host_etc(ts, NULL))) return ts; BIO_printf(bio_err, "error setting verification parameters for %s\n", desc); OSSL_CMP_CTX_print_errors(cmp_ctx); X509_STORE_free(ts); return NULL; } typedef int (*add_X509_fn_t)(void *ctx, const X509 *cert); static int setup_cert(void *ctx, const char *file, const char *pass, const char *desc, add_X509_fn_t set1_fn) { X509 *cert; int ok; if (file == NULL) return 1; if ((cert = load_cert_pwd(file, pass, desc)) == NULL) return 0; ok = (*set1_fn)(ctx, cert); X509_free(cert); return ok; } typedef int (*add_X509_stack_fn_t)(void *ctx, const STACK_OF(X509) *certs); static int setup_certs(char *files, const char *desc, void *ctx, add_X509_stack_fn_t set1_fn) { STACK_OF(X509) *certs; int ok; if (files == NULL) return 1; if ((certs = load_certs_multifile(files, opt_otherpass, desc, vpm)) == NULL) return 0; ok = (*set1_fn)(ctx, certs); OSSL_STACK_OF_X509_free(certs); return ok; } /* * parse and transform some options, checking their syntax. * Returns 1 on success, 0 on error */ static int transform_opts(void) { if (opt_cmd_s != NULL) { if (!strcmp(opt_cmd_s, "ir")) { opt_cmd = CMP_IR; } else if (!strcmp(opt_cmd_s, "kur")) { opt_cmd = CMP_KUR; } else if (!strcmp(opt_cmd_s, "cr")) { opt_cmd = CMP_CR; } else if (!strcmp(opt_cmd_s, "p10cr")) { opt_cmd = CMP_P10CR; } else if (!strcmp(opt_cmd_s, "rr")) { opt_cmd = CMP_RR; } else if (!strcmp(opt_cmd_s, "genm")) { opt_cmd = CMP_GENM; } else { CMP_err1("unknown cmp command '%s'", opt_cmd_s); return 0; } } else { CMP_err("no cmp command to execute"); return 0; } #ifndef OPENSSL_NO_ENGINE # define FORMAT_OPTIONS (OPT_FMT_PEMDER | OPT_FMT_PKCS12 | OPT_FMT_ENGINE) #else # define FORMAT_OPTIONS (OPT_FMT_PEMDER | OPT_FMT_PKCS12) #endif if (opt_keyform_s != NULL && !opt_format(opt_keyform_s, FORMAT_OPTIONS, &opt_keyform)) { CMP_err("unknown option given for key loading format"); return 0; } #undef FORMAT_OPTIONS if (opt_certform_s != NULL && !opt_format(opt_certform_s, OPT_FMT_PEMDER, &opt_certform)) { CMP_err("unknown option given for certificate storing format"); return 0; } return 1; } static OSSL_CMP_SRV_CTX *setup_srv_ctx(ENGINE *engine) { OSSL_CMP_CTX *ctx; /* extra CMP (client) ctx partly used by server */ OSSL_CMP_SRV_CTX *srv_ctx = ossl_cmp_mock_srv_new(app_get0_libctx(), app_get0_propq()); if (srv_ctx == NULL) return NULL; ctx = OSSL_CMP_SRV_CTX_get0_cmp_ctx(srv_ctx); if (opt_srv_ref == NULL) { if (opt_srv_cert == NULL) { /* opt_srv_cert should determine the sender */ CMP_err("must give -srv_ref for mock server if no -srv_cert given"); goto err; } } else { if (!OSSL_CMP_CTX_set1_referenceValue(ctx, (unsigned char *)opt_srv_ref, strlen(opt_srv_ref))) goto err; } if (opt_srv_secret != NULL) { int res; char *pass_str = get_passwd(opt_srv_secret, "PBMAC secret of mock server"); if (pass_str != NULL) { cleanse(opt_srv_secret); res = OSSL_CMP_CTX_set1_secretValue(ctx, (unsigned char *)pass_str, strlen(pass_str)); clear_free(pass_str); if (res == 0) goto err; } } else if (opt_srv_cert == NULL) { CMP_err("server credentials (-srv_secret or -srv_cert) must be given if -use_mock_srv or -port is used"); goto err; } else { CMP_warn("server will not be able to handle PBM-protected requests since -srv_secret is not given"); } if (opt_srv_secret == NULL && ((opt_srv_cert == NULL) != (opt_srv_key == NULL))) { CMP_err("must give both -srv_cert and -srv_key options or neither"); goto err; } if (!setup_cert(ctx, opt_srv_cert, opt_srv_keypass, "signer certificate of the mock server", (add_X509_fn_t)OSSL_CMP_CTX_set1_cert)) goto err; if (opt_srv_key != NULL) { EVP_PKEY *pkey = load_key_pwd(opt_srv_key, opt_keyform, opt_srv_keypass, engine, "private key for mock server cert"); if (pkey == NULL || !OSSL_CMP_CTX_set1_pkey(ctx, pkey)) { EVP_PKEY_free(pkey); goto err; } EVP_PKEY_free(pkey); } cleanse(opt_srv_keypass); if (opt_srv_trusted != NULL) { X509_STORE *ts = load_trusted(opt_srv_trusted, 0, "certs trusted by mock server"); if (ts == NULL || !OSSL_CMP_CTX_set0_trusted(ctx, ts)) { X509_STORE_free(ts); goto err; } } else { CMP_warn("mock server will not be able to handle signature-protected requests since -srv_trusted is not given"); } if (!setup_certs(opt_srv_untrusted, "untrusted certificates for mock server", ctx, (add_X509_stack_fn_t)OSSL_CMP_CTX_set1_untrusted)) goto err; if (!setup_cert(srv_ctx, opt_ref_cert, opt_otherpass, "reference cert to be expected by the mock server", (add_X509_fn_t)ossl_cmp_mock_srv_set1_refCert)) goto err; if (opt_rsp_cert == NULL) { CMP_warn("no -rsp_cert given for mock server"); } else { if (!setup_cert(srv_ctx, opt_rsp_cert, opt_keypass, "cert the mock server returns on certificate requests", (add_X509_fn_t)ossl_cmp_mock_srv_set1_certOut)) goto err; } if (!setup_certs(opt_rsp_extracerts, "CMP extra certificates for mock server", srv_ctx, (add_X509_stack_fn_t)ossl_cmp_mock_srv_set1_chainOut)) goto err; if (!setup_certs(opt_rsp_capubs, "caPubs for mock server", srv_ctx, (add_X509_stack_fn_t)ossl_cmp_mock_srv_set1_caPubsOut)) goto err; if (!setup_cert(srv_ctx, opt_rsp_newwithnew, opt_otherpass, "NewWithNew cert the mock server returns in rootCaKeyUpdate", (add_X509_fn_t)ossl_cmp_mock_srv_set1_newWithNew) || !setup_cert(srv_ctx, opt_rsp_newwithold, opt_otherpass, "NewWithOld cert the mock server returns in rootCaKeyUpdate", (add_X509_fn_t)ossl_cmp_mock_srv_set1_newWithOld) || !setup_cert(srv_ctx, opt_rsp_oldwithnew, opt_otherpass, "OldWithNew cert the mock server returns in rootCaKeyUpdate", (add_X509_fn_t)ossl_cmp_mock_srv_set1_oldWithNew)) goto err; (void)ossl_cmp_mock_srv_set_pollCount(srv_ctx, opt_poll_count); (void)ossl_cmp_mock_srv_set_checkAfterTime(srv_ctx, opt_check_after); if (opt_grant_implicitconf) (void)OSSL_CMP_SRV_CTX_set_grant_implicit_confirm(srv_ctx, 1); if (opt_failure != INT_MIN) { /* option has been set explicitly */ if (opt_failure < 0 || OSSL_CMP_PKIFAILUREINFO_MAX < opt_failure) { CMP_err1("-failure out of range, should be >= 0 and <= %d", OSSL_CMP_PKIFAILUREINFO_MAX); goto err; } if (opt_failurebits != 0) CMP_warn("-failurebits overrides -failure"); else opt_failurebits = 1 << opt_failure; } if ((unsigned)opt_failurebits > OSSL_CMP_PKIFAILUREINFO_MAX_BIT_PATTERN) { CMP_err("-failurebits out of range"); goto err; } if (!ossl_cmp_mock_srv_set_statusInfo(srv_ctx, opt_pkistatus, opt_failurebits, opt_statusstring)) goto err; if (opt_send_error) (void)ossl_cmp_mock_srv_set_sendError(srv_ctx, 1); if (opt_send_unprotected) (void)OSSL_CMP_CTX_set_option(ctx, OSSL_CMP_OPT_UNPROTECTED_SEND, 1); if (opt_send_unprot_err) (void)OSSL_CMP_SRV_CTX_set_send_unprotected_errors(srv_ctx, 1); if (opt_accept_unprotected) (void)OSSL_CMP_SRV_CTX_set_accept_unprotected(srv_ctx, 1); if (opt_accept_unprot_err) (void)OSSL_CMP_CTX_set_option(ctx, OSSL_CMP_OPT_UNPROTECTED_ERRORS, 1); if (opt_accept_raverified) (void)OSSL_CMP_SRV_CTX_set_accept_raverified(srv_ctx, 1); return srv_ctx; err: ossl_cmp_mock_srv_free(srv_ctx); return NULL; } /* * set up verification aspects of OSSL_CMP_CTX w.r.t. opts from config file/CLI. * Returns pointer on success, NULL on error */ static int setup_verification_ctx(OSSL_CMP_CTX *ctx) { if (!setup_certs(opt_untrusted, "untrusted certificates", ctx, (add_X509_stack_fn_t)OSSL_CMP_CTX_set1_untrusted)) return 0; if (opt_srvcert != NULL || opt_trusted != NULL) { if (opt_srvcert != NULL) { if (opt_trusted != NULL) { CMP_warn("-trusted option is ignored since -srvcert option is present"); opt_trusted = NULL; } if (opt_recipient != NULL) { CMP_warn("-recipient option is ignored since -srvcert option is present"); opt_recipient = NULL; } if (!setup_cert(ctx, opt_srvcert, opt_otherpass, "directly trusted CMP server certificate", (add_X509_fn_t)OSSL_CMP_CTX_set1_srvCert)) return 0; } if (opt_trusted != NULL) { X509_STORE *ts; /* * the 0 arg below clears any expected host/ip/email address; * opt_expect_sender is used instead */ ts = load_trusted(opt_trusted, 0, "certs trusted by client"); if (ts == NULL || !OSSL_CMP_CTX_set0_trusted(ctx, ts)) { X509_STORE_free(ts); return 0; } } } if (opt_unprotected_errors) (void)OSSL_CMP_CTX_set_option(ctx, OSSL_CMP_OPT_UNPROTECTED_ERRORS, 1); if (opt_out_trusted != NULL) { /* for use in OSSL_CMP_certConf_cb() */ X509_VERIFY_PARAM *out_vpm = NULL; X509_STORE *out_trusted = load_trusted(opt_out_trusted, 1, "trusted certs for verifying newly enrolled cert"); if (out_trusted == NULL) return 0; /* ignore any -attime here, new certs are current anyway */ out_vpm = X509_STORE_get0_param(out_trusted); X509_VERIFY_PARAM_clear_flags(out_vpm, X509_V_FLAG_USE_CHECK_TIME); (void)OSSL_CMP_CTX_set_certConf_cb_arg(ctx, out_trusted); } if (opt_disable_confirm) (void)OSSL_CMP_CTX_set_option(ctx, OSSL_CMP_OPT_DISABLE_CONFIRM, 1); if (opt_implicit_confirm) (void)OSSL_CMP_CTX_set_option(ctx, OSSL_CMP_OPT_IMPLICIT_CONFIRM, 1); return 1; } #if !defined(OPENSSL_NO_SOCK) && !defined(OPENSSL_NO_HTTP) /* * set up ssl_ctx for the OSSL_CMP_CTX based on options from config file/CLI. * Returns pointer on success, NULL on error */ static SSL_CTX *setup_ssl_ctx(OSSL_CMP_CTX *ctx, const char *host, ENGINE *engine) { STACK_OF(X509) *untrusted = OSSL_CMP_CTX_get0_untrusted(ctx); EVP_PKEY *pkey = NULL; X509_STORE *trust_store = NULL; SSL_CTX *ssl_ctx; int i; ssl_ctx = SSL_CTX_new(TLS_client_method()); if (ssl_ctx == NULL) return NULL; if (opt_tls_trusted != NULL) { trust_store = load_trusted(opt_tls_trusted, 0, "trusted TLS certs"); if (trust_store == NULL) goto err; SSL_CTX_set_cert_store(ssl_ctx, trust_store); SSL_CTX_set_verify(ssl_ctx, SSL_VERIFY_PEER, NULL); } else { CMP_warn("-tls_used given without -tls_trusted; will not authenticate the TLS server"); } if (opt_tls_cert != NULL && opt_tls_key != NULL) { X509 *cert; STACK_OF(X509) *certs = NULL; int ok; if (!load_cert_certs(opt_tls_cert, &cert, &certs, 0, opt_tls_keypass, "TLS client certificate (optionally with chain)", vpm)) /* need opt_tls_keypass if opt_tls_cert is encrypted PKCS#12 file */ goto err; ok = SSL_CTX_use_certificate(ssl_ctx, cert) > 0; X509_free(cert); /* * Any further certs and any untrusted certs are used for constructing * the chain to be provided with the TLS client cert to the TLS server. */ if (!ok || !SSL_CTX_set0_chain(ssl_ctx, certs)) { CMP_err1("unable to use client TLS certificate file '%s'", opt_tls_cert); OSSL_STACK_OF_X509_free(certs); goto err; } for (i = 0; i < sk_X509_num(untrusted); i++) { cert = sk_X509_value(untrusted, i); if (!SSL_CTX_add1_chain_cert(ssl_ctx, cert)) { CMP_err("could not add untrusted cert to TLS client cert chain"); goto err; } } { X509_VERIFY_PARAM *tls_vpm = NULL; unsigned long bak_flags = 0; /* compiler warns without init */ if (trust_store != NULL) { tls_vpm = X509_STORE_get0_param(trust_store); bak_flags = X509_VERIFY_PARAM_get_flags(tls_vpm); /* disable any cert status/revocation checking etc. */ X509_VERIFY_PARAM_clear_flags(tls_vpm, ~(X509_V_FLAG_USE_CHECK_TIME | X509_V_FLAG_NO_CHECK_TIME | X509_V_FLAG_PARTIAL_CHAIN | X509_V_FLAG_POLICY_CHECK)); } CMP_debug("trying to build cert chain for own TLS cert"); if (SSL_CTX_build_cert_chain(ssl_ctx, SSL_BUILD_CHAIN_FLAG_UNTRUSTED | SSL_BUILD_CHAIN_FLAG_NO_ROOT)) { CMP_debug("success building cert chain for own TLS cert"); } else { OSSL_CMP_CTX_print_errors(ctx); CMP_warn("could not build cert chain for own TLS cert"); } if (trust_store != NULL) X509_VERIFY_PARAM_set_flags(tls_vpm, bak_flags); } /* If present we append to the list also the certs from opt_tls_extra */ if (opt_tls_extra != NULL) { STACK_OF(X509) *tls_extra = load_certs_multifile(opt_tls_extra, opt_otherpass, "extra certificates for TLS", vpm); int res = 1; if (tls_extra == NULL) goto err; for (i = 0; i < sk_X509_num(tls_extra); i++) { cert = sk_X509_value(tls_extra, i); if (res != 0) res = SSL_CTX_add_extra_chain_cert(ssl_ctx, cert); if (res == 0) X509_free(cert); } sk_X509_free(tls_extra); if (res == 0) { BIO_printf(bio_err, "error: unable to add TLS extra certs\n"); goto err; } } pkey = load_key_pwd(opt_tls_key, opt_keyform, opt_tls_keypass, engine, "TLS client private key"); cleanse(opt_tls_keypass); if (pkey == NULL) goto err; /* * verify the key matches the cert, * not using SSL_CTX_check_private_key(ssl_ctx) * because it gives poor and sometimes misleading diagnostics */ if (!X509_check_private_key(SSL_CTX_get0_certificate(ssl_ctx), pkey)) { CMP_err2("TLS private key '%s' does not match the TLS certificate '%s'\n", opt_tls_key, opt_tls_cert); EVP_PKEY_free(pkey); pkey = NULL; /* otherwise, for some reason double free! */ goto err; } if (SSL_CTX_use_PrivateKey(ssl_ctx, pkey) <= 0) { CMP_err1("unable to use TLS client private key '%s'", opt_tls_key); EVP_PKEY_free(pkey); pkey = NULL; /* otherwise, for some reason double free! */ goto err; } EVP_PKEY_free(pkey); /* we do not need the handle any more */ } else { CMP_warn("-tls_used given without -tls_key; cannot authenticate to the TLS server"); } if (trust_store != NULL) { /* * Enable and parameterize server hostname/IP address check. * If we did this before checking our own TLS cert * the expected hostname would mislead the check. */ if (!truststore_set_host_etc(trust_store, opt_tls_host != NULL ? opt_tls_host : host)) goto err; } return ssl_ctx; err: SSL_CTX_free(ssl_ctx); return NULL; } #endif /* OPENSSL_NO_SOCK */ /* * set up protection aspects of OSSL_CMP_CTX based on options from config * file/CLI while parsing options and checking their consistency. * Returns 1 on success, 0 on error */ static int setup_protection_ctx(OSSL_CMP_CTX *ctx, ENGINE *engine) { if (!opt_unprotected_requests && opt_secret == NULL && opt_key == NULL) { CMP_err("must give -key or -secret unless -unprotected_requests is used"); return 0; } if (opt_ref == NULL && opt_cert == NULL && opt_subject == NULL) { /* cert or subject should determine the sender */ CMP_err("must give -ref if no -cert and no -subject given"); return 0; } if (opt_secret == NULL && ((opt_cert == NULL) != (opt_key == NULL))) { CMP_err("must give both -cert and -key options or neither"); return 0; } if (opt_secret != NULL) { char *pass_string = get_passwd(opt_secret, "PBMAC"); int res; if (pass_string != NULL) { cleanse(opt_secret); res = OSSL_CMP_CTX_set1_secretValue(ctx, (unsigned char *)pass_string, strlen(pass_string)); clear_free(pass_string); if (res == 0) return 0; } if (opt_cert != NULL || opt_key != NULL) CMP_warn("-cert and -key not used for protection since -secret is given"); } if (opt_ref != NULL && !OSSL_CMP_CTX_set1_referenceValue(ctx, (unsigned char *)opt_ref, strlen(opt_ref))) return 0; if (opt_key != NULL) { EVP_PKEY *pkey = load_key_pwd(opt_key, opt_keyform, opt_keypass, engine, "private key for CMP client certificate"); if (pkey == NULL || !OSSL_CMP_CTX_set1_pkey(ctx, pkey)) { EVP_PKEY_free(pkey); return 0; } EVP_PKEY_free(pkey); } if (opt_secret == NULL && opt_srvcert == NULL && opt_trusted == NULL) CMP_warn("will not authenticate server due to missing -secret, -trusted, or -srvcert"); if (opt_cert != NULL) { X509 *cert; STACK_OF(X509) *certs = NULL; X509_STORE *own_trusted = NULL; int ok; if (!load_cert_certs(opt_cert, &cert, &certs, 0, opt_keypass, "CMP client certificate (optionally with chain)", vpm)) /* opt_keypass is needed if opt_cert is an encrypted PKCS#12 file */ return 0; ok = OSSL_CMP_CTX_set1_cert(ctx, cert); X509_free(cert); if (!ok) { CMP_err("out of memory"); } else { if (opt_own_trusted != NULL) { own_trusted = load_trusted(opt_own_trusted, 0, "trusted certs for verifying own CMP signer cert"); ok = own_trusted != NULL; } ok = ok && OSSL_CMP_CTX_build_cert_chain(ctx, own_trusted, certs); } X509_STORE_free(own_trusted); OSSL_STACK_OF_X509_free(certs); if (!ok) return 0; } else if (opt_own_trusted != NULL) { CMP_warn("-own_trusted option is ignored without -cert"); } if (!setup_certs(opt_extracerts, "extra certificates for CMP", ctx, (add_X509_stack_fn_t)OSSL_CMP_CTX_set1_extraCertsOut)) return 0; cleanse(opt_otherpass); if (opt_unprotected_requests) (void)OSSL_CMP_CTX_set_option(ctx, OSSL_CMP_OPT_UNPROTECTED_SEND, 1); if (opt_digest != NULL) { int digest = OBJ_ln2nid(opt_digest); if (digest == NID_undef) { CMP_err1("digest algorithm name not recognized: '%s'", opt_digest); return 0; } if (!OSSL_CMP_CTX_set_option(ctx, OSSL_CMP_OPT_DIGEST_ALGNID, digest) || !OSSL_CMP_CTX_set_option(ctx, OSSL_CMP_OPT_OWF_ALGNID, digest)) { CMP_err1("digest algorithm name not supported: '%s'", opt_digest); return 0; } } if (opt_mac != NULL) { int mac = OBJ_ln2nid(opt_mac); if (mac == NID_undef) { CMP_err1("MAC algorithm name not recognized: '%s'", opt_mac); return 0; } (void)OSSL_CMP_CTX_set_option(ctx, OSSL_CMP_OPT_MAC_ALGNID, mac); } return 1; } /* * Set up IR/CR/P10CR/KUR/CertConf/RR/GENM specific parts of the OSSL_CMP_CTX * based on options from CLI and/or config file. * Returns 1 on success, 0 on error */ static int setup_request_ctx(OSSL_CMP_CTX *ctx, ENGINE *engine) { X509_REQ *csr = NULL; X509_EXTENSIONS *exts = NULL; X509V3_CTX ext_ctx; if (opt_subject == NULL && opt_csr == NULL && opt_oldcert == NULL && opt_cert == NULL && opt_cmd != CMP_RR && opt_cmd != CMP_GENM) CMP_warn("no -subject given; no -csr or -oldcert or -cert available for fallback"); if (!set_name(opt_issuer, OSSL_CMP_CTX_set1_issuer, ctx, "issuer")) return 0; if (opt_cmd == CMP_IR || opt_cmd == CMP_CR || opt_cmd == CMP_KUR) { if (opt_newkey == NULL && opt_key == NULL && opt_csr == NULL && opt_oldcert == NULL) { CMP_err("missing -newkey (or -key) to be certified and no -csr, -oldcert, or -cert given for fallback public key"); return 0; } if (opt_newkey == NULL && opt_popo != OSSL_CRMF_POPO_NONE && opt_popo != OSSL_CRMF_POPO_RAVERIFIED) { if (opt_csr != NULL) { CMP_err1("no -newkey option given with private key for POPO, -csr option only provides public key%s", opt_key == NULL ? "" : ", and -key option superseded by -csr"); return 0; } if (opt_key == NULL) { CMP_err("missing -newkey (or -key) option for POPO"); return 0; } } if (opt_certout == NULL) { CMP_err("-certout not given, nowhere to save newly enrolled certificate"); return 0; } if (!set_name(opt_subject, OSSL_CMP_CTX_set1_subjectName, ctx, "subject")) return 0; } else { const char *msg = "option is ignored for commands other than 'ir', 'cr', and 'kur'"; if (opt_subject != NULL) { if (opt_ref == NULL && opt_cert == NULL) { /* will use subject as sender unless oldcert subject is used */ if (!set_name(opt_subject, OSSL_CMP_CTX_set1_subjectName, ctx, "subject")) return 0; } else { CMP_warn1("-subject %s since sender is taken from -ref or -cert", msg); } } if (opt_issuer != NULL && opt_cmd != CMP_RR) CMP_warn1("-issuer %s and 'rr'", msg); if (opt_reqexts != NULL) CMP_warn1("-reqexts %s", msg); if (opt_san_nodefault) CMP_warn1("-san_nodefault %s", msg); if (opt_sans != NULL) CMP_warn1("-sans %s", msg); if (opt_policies != NULL) CMP_warn1("-policies %s", msg); if (opt_policy_oids != NULL) CMP_warn1("-policy_oids %s", msg); if (opt_cmd != CMP_P10CR) { if (opt_implicit_confirm) CMP_warn1("-implicit_confirm %s, and 'p10cr'", msg); if (opt_disable_confirm) CMP_warn1("-disable_confirm %s, and 'p10cr'", msg); if (opt_certout != NULL) CMP_warn1("-certout %s, and 'p10cr'", msg); if (opt_chainout != NULL) CMP_warn1("-chainout %s, and 'p10cr'", msg); } } if (opt_cmd == CMP_KUR) { char *ref_cert = opt_oldcert != NULL ? opt_oldcert : opt_cert; if (ref_cert == NULL && opt_csr == NULL) { CMP_err("missing -oldcert for certificate to be updated and no -csr given"); return 0; } if (opt_subject != NULL) CMP_warn2("given -subject '%s' overrides the subject of '%s' for KUR", opt_subject, ref_cert != NULL ? ref_cert : opt_csr); } if (opt_cmd == CMP_RR) { if (opt_issuer == NULL && opt_serial == NULL) { if (opt_oldcert == NULL && opt_csr == NULL) { CMP_err("missing -oldcert or -issuer and -serial for certificate to be revoked and no -csr given"); return 0; } if (opt_oldcert != NULL && opt_csr != NULL) CMP_warn("ignoring -csr since certificate to be revoked is given"); } else { #define OSSL_CMP_RR_MSG "since -issuer and -serial is given for command 'rr'" if (opt_issuer == NULL || opt_serial == NULL) { CMP_err("Must give both -issuer and -serial options or neither"); return 0; } if (opt_oldcert != NULL) CMP_warn("Ignoring -oldcert " OSSL_CMP_RR_MSG); if (opt_csr != NULL) CMP_warn("Ignoring -csr " OSSL_CMP_RR_MSG); } if (opt_serial != NULL) { ASN1_INTEGER *sno; if ((sno = s2i_ASN1_INTEGER(NULL, opt_serial)) == NULL) { CMP_err1("cannot read serial number: '%s'", opt_serial); return 0; } if (!OSSL_CMP_CTX_set1_serialNumber(ctx, sno)) { ASN1_INTEGER_free(sno); CMP_err("out of memory"); return 0; } ASN1_INTEGER_free(sno); } if (opt_revreason > CRL_REASON_NONE) (void)OSSL_CMP_CTX_set_option(ctx, OSSL_CMP_OPT_REVOCATION_REASON, opt_revreason); } else { if (opt_serial != NULL) CMP_warn("Ignoring -serial for command other than 'rr'"); } if (opt_cmd == CMP_P10CR && opt_csr == NULL) { CMP_err("missing PKCS#10 CSR for p10cr"); return 0; } if (opt_recipient == NULL && opt_srvcert == NULL && opt_issuer == NULL && opt_oldcert == NULL && opt_cert == NULL) CMP_warn("missing -recipient, -srvcert, -issuer, -oldcert or -cert; recipient will be set to \"NULL-DN\""); if (opt_cmd == CMP_P10CR || opt_cmd == CMP_RR || opt_cmd == CMP_GENM) { const char *msg = "option is ignored for 'p10cr', 'rr', and 'genm' commands"; if (opt_newkeypass != NULL) CMP_warn1("-newkeypass %s", msg); if (opt_newkey != NULL) CMP_warn1("-newkey %s", msg); if (opt_days != 0) CMP_warn1("-days %s", msg); if (opt_popo != OSSL_CRMF_POPO_NONE - 1) CMP_warn1("-popo %s", msg); if (opt_out_trusted != NULL) CMP_warn1("-out_trusted %s", msg); } else if (opt_newkey != NULL) { const char *file = opt_newkey; const int format = opt_keyform; const char *pass = opt_newkeypass; const char *desc = "new private key for cert to be enrolled"; EVP_PKEY *pkey; int priv = 1; BIO *bio_bak = bio_err; bio_err = NULL; /* suppress diagnostics on first try loading key */ pkey = load_key_pwd(file, format, pass, engine, desc); bio_err = bio_bak; if (pkey == NULL) { ERR_clear_error(); desc = opt_csr == NULL ? "fallback public key for cert to be enrolled" : "public key for checking cert resulting from p10cr"; pkey = load_pubkey(file, format, 0, pass, engine, desc); priv = 0; } cleanse(opt_newkeypass); if (pkey == NULL || !OSSL_CMP_CTX_set0_newPkey(ctx, priv, pkey)) { EVP_PKEY_free(pkey); return 0; } } if (opt_days > 0 && !OSSL_CMP_CTX_set_option(ctx, OSSL_CMP_OPT_VALIDITY_DAYS, opt_days)) { CMP_err("could not set requested cert validity period"); return 0; } if (opt_policies != NULL && opt_policy_oids != NULL) { CMP_err("cannot have policies both via -policies and via -policy_oids"); return 0; } if (opt_csr != NULL) { if (opt_cmd == CMP_GENM) { CMP_warn("-csr option is ignored for 'genm' command"); } else { csr = load_csr_autofmt(opt_csr, FORMAT_UNDEF, NULL, "PKCS#10 CSR"); if (csr == NULL) return 0; if (!OSSL_CMP_CTX_set1_p10CSR(ctx, csr)) goto oom; } } if (opt_reqexts != NULL || opt_policies != NULL) { if ((exts = sk_X509_EXTENSION_new_null()) == NULL) goto oom; X509V3_set_ctx(&ext_ctx, NULL, NULL, csr, NULL, X509V3_CTX_REPLACE); X509V3_set_nconf(&ext_ctx, conf); if (opt_reqexts != NULL && !X509V3_EXT_add_nconf_sk(conf, &ext_ctx, opt_reqexts, &exts)) { CMP_err1("cannot load certificate request extension section '%s'", opt_reqexts); goto exts_err; } if (opt_policies != NULL && !X509V3_EXT_add_nconf_sk(conf, &ext_ctx, opt_policies, &exts)) { CMP_err1("cannot load policy cert request extension section '%s'", opt_policies); goto exts_err; } OSSL_CMP_CTX_set0_reqExtensions(ctx, exts); } X509_REQ_free(csr); /* After here, must not goto oom/exts_err */ if (OSSL_CMP_CTX_reqExtensions_have_SAN(ctx) && opt_sans != NULL) { CMP_err("cannot have Subject Alternative Names both via -reqexts and via -sans"); return 0; } if (!set_gennames(ctx, opt_sans, "Subject Alternative Name")) return 0; if (opt_san_nodefault) { if (opt_sans != NULL) CMP_warn("-opt_san_nodefault has no effect when -sans is used"); (void)OSSL_CMP_CTX_set_option(ctx, OSSL_CMP_OPT_SUBJECTALTNAME_NODEFAULT, 1); } if (opt_policy_oids_critical) { if (opt_policy_oids == NULL) CMP_warn("-opt_policy_oids_critical has no effect unless -policy_oids is given"); (void)OSSL_CMP_CTX_set_option(ctx, OSSL_CMP_OPT_POLICIES_CRITICAL, 1); } while (opt_policy_oids != NULL) { ASN1_OBJECT *policy; POLICYINFO *pinfo; char *next = next_item(opt_policy_oids); if ((policy = OBJ_txt2obj(opt_policy_oids, 1)) == 0) { CMP_err1("Invalid -policy_oids arg '%s'", opt_policy_oids); return 0; } if (OBJ_obj2nid(policy) == NID_undef) CMP_warn1("Unknown -policy_oids arg: %.40s", opt_policy_oids); if ((pinfo = POLICYINFO_new()) == NULL) { ASN1_OBJECT_free(policy); return 0; } pinfo->policyid = policy; if (!OSSL_CMP_CTX_push0_policy(ctx, pinfo)) { CMP_err1("cannot add policy with OID '%s'", opt_policy_oids); POLICYINFO_free(pinfo); return 0; } opt_policy_oids = next; } if (opt_popo >= OSSL_CRMF_POPO_NONE) (void)OSSL_CMP_CTX_set_option(ctx, OSSL_CMP_OPT_POPO_METHOD, opt_popo); if (opt_oldcert != NULL) { if (opt_cmd == CMP_GENM) { CMP_warn("-oldcert option is ignored for 'genm' command"); } else { if (!setup_cert(ctx, opt_oldcert, opt_keypass, /* needed if opt_oldcert is encrypted PKCS12 file */ opt_cmd == CMP_KUR ? "certificate to be updated" : opt_cmd == CMP_RR ? "certificate to be revoked" : "reference certificate (oldcert)", (add_X509_fn_t)OSSL_CMP_CTX_set1_oldCert)) return 0; } } cleanse(opt_keypass); return 1; oom: CMP_err("out of memory"); exts_err: sk_X509_EXTENSION_pop_free(exts, X509_EXTENSION_free); X509_REQ_free(csr); return 0; } static int add_certProfile(OSSL_CMP_CTX *ctx, const char *name) { OSSL_CMP_ITAV *itav = NULL; STACK_OF(ASN1_UTF8STRING) *sk; ASN1_UTF8STRING *utf8string; if (ctx == NULL || name == NULL) return 0; if ((sk = sk_ASN1_UTF8STRING_new_reserve(NULL, 1)) == NULL) return 0; if ((utf8string = ASN1_UTF8STRING_new()) == NULL) goto err; if (!ASN1_STRING_set(utf8string, name, (int)strlen(name))) { ASN1_STRING_free(utf8string); goto err; } /* Due to sk_ASN1_UTF8STRING_new_reserve(NULL, 1), this surely succeeds: */ (void)sk_ASN1_UTF8STRING_push(sk, utf8string); if ((itav = OSSL_CMP_ITAV_new0_certProfile(sk)) == NULL) goto err; if (OSSL_CMP_CTX_push0_geninfo_ITAV(ctx, itav)) return 1; OSSL_CMP_ITAV_free(itav); return 0; err: sk_ASN1_UTF8STRING_pop_free(sk, ASN1_UTF8STRING_free); return 0; } static int handle_opt_geninfo(OSSL_CMP_CTX *ctx) { ASN1_OBJECT *obj = NULL; ASN1_TYPE *type = NULL; long value; ASN1_INTEGER *aint = NULL; ASN1_UTF8STRING *text = NULL; OSSL_CMP_ITAV *itav; char *ptr = opt_geninfo, *oid, *end; do { while (isspace(_UC(*ptr))) ptr++; oid = ptr; if ((ptr = strchr(oid, ':')) == NULL) { CMP_err1("Missing ':' in -geninfo arg %.40s", oid); return 0; } *ptr++ = '\0'; if ((obj = OBJ_txt2obj(oid, 0)) == NULL) { CMP_err1("Invalid OID in -geninfo arg %.40s", oid); return 0; } if (OBJ_obj2nid(obj) == NID_undef) CMP_warn1("Unknown OID in -geninfo arg: %.40s", oid); if ((type = ASN1_TYPE_new()) == NULL) goto oom; if (CHECK_AND_SKIP_CASE_PREFIX(ptr, "int:")) { value = strtol(ptr, &end, 10); if (end == ptr) { CMP_err1("Cannot parse int in -geninfo arg %.40s", ptr); goto err; } ptr = end; if (*ptr != '\0') { if (*ptr != ',') { CMP_err1("Missing ',' or end of -geninfo arg after int at %.40s", ptr); goto err; } ptr++; } if ((aint = ASN1_INTEGER_new()) == NULL || !ASN1_INTEGER_set(aint, value)) goto oom; ASN1_TYPE_set(type, V_ASN1_INTEGER, aint); aint = NULL; } else if (CHECK_AND_SKIP_CASE_PREFIX(ptr, "str:")) { end = strchr(ptr, ','); if (end == NULL) end = ptr + strlen(ptr); else *end++ = '\0'; if ((text = ASN1_UTF8STRING_new()) == NULL || !ASN1_STRING_set(text, ptr, -1)) goto oom; ptr = end; ASN1_TYPE_set(type, V_ASN1_UTF8STRING, text); text = NULL; } else { CMP_err1("Missing 'int:' or 'str:' in -geninfo arg %.40s", ptr); goto err; } if ((itav = OSSL_CMP_ITAV_create(obj, type)) == NULL) { CMP_err("Unable to create 'OSSL_CMP_ITAV' structure"); goto err; } obj = NULL; type = NULL; if (!OSSL_CMP_CTX_push0_geninfo_ITAV(ctx, itav)) { CMP_err("Failed to add ITAV for geninfo of the PKI message header"); OSSL_CMP_ITAV_free(itav); return 0; } } while (*ptr != '\0'); return 1; oom: CMP_err("out of memory"); err: ASN1_OBJECT_free(obj); ASN1_TYPE_free(type); ASN1_INTEGER_free(aint); ASN1_UTF8STRING_free(text); return 0; } /* * set up the client-side OSSL_CMP_CTX based on options from config file/CLI * while parsing options and checking their consistency. * Prints reason for error to bio_err. * Returns 1 on success, 0 on error */ static int setup_client_ctx(OSSL_CMP_CTX *ctx, ENGINE *engine) { int ret = 0; char *host = NULL, *port = NULL, *path = NULL, *used_path = opt_path; #if !defined(OPENSSL_NO_SOCK) && !defined(OPENSSL_NO_HTTP) int portnum, use_ssl; static char server_port[32] = { '\0' }; const char *proxy_host = NULL; #endif char server_buf[200] = "mock server"; char proxy_buf[200] = ""; if (!opt_use_mock_srv && opt_rspin == NULL) { /* note: -port is not given */ #if !defined(OPENSSL_NO_SOCK) && !defined(OPENSSL_NO_HTTP) if (opt_server == NULL) { CMP_err("missing -server or -use_mock_srv or -rspin option"); goto err; } #else CMP_err("missing -use_mock_srv or -rspin option; -server option is not supported due to no-sock build"); goto err; #endif } #if !defined(OPENSSL_NO_SOCK) && !defined(OPENSSL_NO_HTTP) if (opt_server == NULL) { if (opt_proxy != NULL) CMP_warn("ignoring -proxy option since -server is not given"); if (opt_no_proxy != NULL) CMP_warn("ignoring -no_proxy option since -server is not given"); goto set_path; } if (!OSSL_HTTP_parse_url(opt_server, &use_ssl, NULL /* user */, &host, &port, &portnum, &path, NULL /* q */, NULL /* frag */)) { CMP_err1("cannot parse -server URL: %s", opt_server); goto err; } if (use_ssl && !opt_tls_used) { CMP_warn("assuming -tls_used since -server URL indicates HTTPS"); opt_tls_used = 1; } if (!OSSL_CMP_CTX_set_option(ctx, OSSL_CMP_OPT_USE_TLS, opt_tls_used)) goto err; BIO_snprintf(server_port, sizeof(server_port), "%s", port); if (opt_path == NULL) used_path = path; if (!OSSL_CMP_CTX_set1_server(ctx, host) || !OSSL_CMP_CTX_set_serverPort(ctx, portnum)) goto oom; if (opt_proxy != NULL && !OSSL_CMP_CTX_set1_proxy(ctx, opt_proxy)) goto oom; if (opt_no_proxy != NULL && !OSSL_CMP_CTX_set1_no_proxy(ctx, opt_no_proxy)) goto oom; (void)BIO_snprintf(server_buf, sizeof(server_buf), "http%s://%s:%s/%s", opt_tls_used ? "s" : "", host, port, *used_path == '/' ? used_path + 1 : used_path); proxy_host = OSSL_HTTP_adapt_proxy(opt_proxy, opt_no_proxy, host, use_ssl); if (proxy_host != NULL) (void)BIO_snprintf(proxy_buf, sizeof(proxy_buf), " via %s", proxy_host); set_path: #endif if (!OSSL_CMP_CTX_set1_serverPath(ctx, used_path)) goto oom; if (!transform_opts()) goto err; if (opt_infotype_s == NULL) { if (opt_cmd == CMP_GENM) CMP_warn("no -infotype option given for genm"); } else if (opt_cmd != CMP_GENM) { CMP_warn("-infotype option is ignored for commands other than 'genm'"); } else { char id_buf[100] = "id-it-"; strncat(id_buf, opt_infotype_s, sizeof(id_buf) - strlen(id_buf) - 1); if ((opt_infotype = OBJ_sn2nid(id_buf)) == NID_undef) { CMP_err("unknown OID name in -infotype option"); goto err; } } if (opt_cmd != CMP_GENM || opt_infotype != NID_id_it_rootCaCert) { const char *msg = "option is ignored unless -cmd 'genm' and -infotype rootCaCert is given"; if (opt_oldwithold != NULL) CMP_warn1("-oldwithold %s", msg); if (opt_newwithnew != NULL) CMP_warn1("-newwithnew %s", msg); if (opt_newwithold != NULL) CMP_warn1("-newwithold %s", msg); if (opt_oldwithnew != NULL) CMP_warn1("-oldwithnew %s", msg); } if (!setup_verification_ctx(ctx)) goto err; if (opt_keep_alive != 1) (void)OSSL_CMP_CTX_set_option(ctx, OSSL_CMP_OPT_KEEP_ALIVE, opt_keep_alive); if (opt_total_timeout > 0 && opt_msg_timeout > 0 && opt_total_timeout < opt_msg_timeout) { CMP_err2("-total_timeout argument = %d must not be < %d (-msg_timeout)", opt_total_timeout, opt_msg_timeout); goto err; } if (opt_msg_timeout >= 0) /* must do this before setup_ssl_ctx() */ (void)OSSL_CMP_CTX_set_option(ctx, OSSL_CMP_OPT_MSG_TIMEOUT, opt_msg_timeout); if (opt_total_timeout >= 0) (void)OSSL_CMP_CTX_set_option(ctx, OSSL_CMP_OPT_TOTAL_TIMEOUT, opt_total_timeout); if (opt_rspin != NULL) { rspin_in_use = 1; if (opt_reqin != NULL) CMP_warn("-reqin is ignored since -rspin is present"); } if (opt_reqin_new_tid && opt_reqin == NULL) CMP_warn("-reqin_new_tid is ignored since -reqin is not present"); if (opt_reqin != NULL || opt_reqout != NULL || opt_rspin != NULL || opt_rspout != NULL || opt_use_mock_srv) (void)OSSL_CMP_CTX_set_transfer_cb(ctx, read_write_req_resp); #if !defined(OPENSSL_NO_SOCK) && !defined(OPENSSL_NO_HTTP) if (opt_tls_used) { APP_HTTP_TLS_INFO *info; if (opt_tls_cert != NULL || opt_tls_key != NULL || opt_tls_keypass != NULL) { if (opt_tls_key == NULL) { CMP_err("missing -tls_key option"); goto err; } else if (opt_tls_cert == NULL) { CMP_err("missing -tls_cert option"); goto err; } } if ((info = OPENSSL_zalloc(sizeof(*info))) == NULL) goto err; APP_HTTP_TLS_INFO_free(OSSL_CMP_CTX_get_http_cb_arg(ctx)); (void)OSSL_CMP_CTX_set_http_cb_arg(ctx, info); info->ssl_ctx = setup_ssl_ctx(ctx, host, engine); info->server = host; host = NULL; /* prevent deallocation */ if ((info->port = OPENSSL_strdup(server_port)) == NULL) goto err; /* workaround for callback design flaw, see #17088: */ info->use_proxy = proxy_host != NULL; info->timeout = OSSL_CMP_CTX_get_option(ctx, OSSL_CMP_OPT_MSG_TIMEOUT); if (info->ssl_ctx == NULL) goto err; (void)OSSL_CMP_CTX_set_http_cb(ctx, app_http_tls_cb); } #endif if (!setup_protection_ctx(ctx, engine)) goto err; if (!setup_request_ctx(ctx, engine)) goto err; if (!set_name(opt_recipient, OSSL_CMP_CTX_set1_recipient, ctx, "recipient") || !set_name(opt_expect_sender, OSSL_CMP_CTX_set1_expected_sender, ctx, "expected sender")) goto err; if (opt_geninfo != NULL && !handle_opt_geninfo(ctx)) goto err; if (opt_profile != NULL && !add_certProfile(ctx, opt_profile)) goto err; /* not printing earlier, to minimize confusion in case setup fails before */ if (opt_rspin != NULL) CMP_info2("will contact %s%s " "only if -rspin argument gives too few filenames", server_buf, proxy_buf); else CMP_info2("will contact %s%s", server_buf, proxy_buf); ret = 1; err: OPENSSL_free(host); OPENSSL_free(port); OPENSSL_free(path); return ret; oom: CMP_err("out of memory"); goto err; } /* * write out the given certificate to the output specified by bio. * Depending on options use either PEM or DER format. * Returns 1 on success, 0 on error */ static int write_cert(BIO *bio, X509 *cert) { if ((opt_certform == FORMAT_PEM && PEM_write_bio_X509(bio, cert)) || (opt_certform == FORMAT_ASN1 && i2d_X509_bio(bio, cert))) return 1; if (opt_certform != FORMAT_PEM && opt_certform != FORMAT_ASN1) BIO_printf(bio_err, "error: unsupported type '%s' for writing certificates\n", opt_certform_s); return 0; } /* * If file != NULL writes out a stack of certs to the given file. * If certs is NULL, the file is emptied. * Frees the certs if present. * Depending on options use either PEM or DER format, * where DER does not make much sense for writing more than one cert! * Returns number of written certificates on success, -1 on error. */ static int save_free_certs(STACK_OF(X509) *certs, const char *file, const char *desc) { BIO *bio = NULL; int i; int n = sk_X509_num(certs /* may be NULL */); if (n < 0) n = 0; if (file == NULL) goto end; if (certs != NULL) CMP_info3("received %d %s certificate(s), saving to file '%s'", n, desc, file); if (n > 1 && opt_certform != FORMAT_PEM) CMP_warn("saving more than one certificate in non-PEM format"); if ((bio = BIO_new(BIO_s_file())) == NULL || !BIO_write_filename(bio, (char *)file)) { CMP_err3("could not open file '%s' for %s %s certificate(s)", file, certs == NULL ? "deleting" : "writing", desc); n = -1; goto end; } for (i = 0; i < n; i++) { if (!write_cert(bio, sk_X509_value(certs, i))) { CMP_err2("cannot write %s certificate to file '%s'", desc, file); n = -1; goto end; } } end: BIO_free(bio); OSSL_STACK_OF_X509_free(certs); return n; } static int delete_file(const char *file, const char *desc) { if (file == NULL) return 1; if (unlink(file) != 0 && errno != ENOENT) { CMP_err2("Failed to delete %s, which should be done to indicate there is no %s", file, desc); return 0; } return 1; } static int save_cert_or_delete(X509 *cert, const char *file, const char *desc) { if (file == NULL) return 1; if (cert == NULL) { char desc_cert[80]; BIO_snprintf(desc_cert, sizeof(desc_cert), "%s certificate", desc); return delete_file(file, desc_cert); } else { STACK_OF(X509) *certs = sk_X509_new_null(); if (!X509_add_cert(certs, cert, X509_ADD_FLAG_UP_REF)) { sk_X509_free(certs); return 0; } return save_free_certs(certs, file, desc) >= 0; } } static int print_itavs(const STACK_OF(OSSL_CMP_ITAV) *itavs) { int i, ret = 1; int n = sk_OSSL_CMP_ITAV_num(itavs); if (n <= 0) { /* also in case itavs == NULL */ CMP_info("genp does not contain any ITAV"); return ret; } for (i = 1; i <= n; i++) { OSSL_CMP_ITAV *itav = sk_OSSL_CMP_ITAV_value(itavs, i - 1); ASN1_OBJECT *type = OSSL_CMP_ITAV_get0_type(itav); char name[80]; if (itav == NULL) { CMP_err1("could not get ITAV #%d from genp", i); ret = 0; continue; } if (i2t_ASN1_OBJECT(name, sizeof(name), type) <= 0) { CMP_err1("error parsing type of ITAV #%d from genp", i); ret = 0; } else { CMP_info2("ITAV #%d from genp infoType=%s", i, name); } } return ret; } static char opt_item[SECTION_NAME_MAX + 1]; /* get previous name from a comma or space-separated list of names */ static const char *prev_item(const char *opt, const char *end) { const char *beg; size_t len; if (end == opt) return NULL; beg = end; while (beg > opt) { --beg; if (beg[0] == ',' || isspace(_UC(beg[0]))) { ++beg; break; } } len = end - beg; if (len > SECTION_NAME_MAX) { CMP_warn3("using only first %d characters of section name starting with \"%.*s\"", SECTION_NAME_MAX, SECTION_NAME_MAX, beg); len = SECTION_NAME_MAX; } memcpy(opt_item, beg, len); opt_item[len] = '\0'; while (beg > opt) { --beg; if (beg[0] != ',' && !isspace(_UC(beg[0]))) { ++beg; break; } } return beg; } /* get str value for name from a comma-separated hierarchy of config sections */ static char *conf_get_string(const CONF *src_conf, const char *groups, const char *name) { char *res = NULL; const char *end = groups + strlen(groups); while ((end = prev_item(groups, end)) != NULL) { if ((res = app_conf_try_string(src_conf, opt_item, name)) != NULL) return res; } return res; } /* get long val for name from a comma-separated hierarchy of config sections */ static int conf_get_number_e(const CONF *conf_, const char *groups, const char *name, long *result) { char *str = conf_get_string(conf_, groups, name); char *tailptr; long res; if (str == NULL || *str == '\0') return 0; res = strtol(str, &tailptr, 10); if (res == LONG_MIN || res == LONG_MAX || *tailptr != '\0') return 0; *result = res; return 1; } /* * use the command line option table to read values from the CMP section * of openssl.cnf. Defaults are taken from the config file, they can be * overwritten on the command line. */ static int read_config(void) { unsigned int i; long num = 0; char *txt = NULL; const OPTIONS *opt; int start_opt = OPT_VERBOSITY - OPT_HELP; int start_idx = OPT_VERBOSITY - 2; /* * starting with offset OPT_VERBOSITY because OPT_CONFIG and OPT_SECTION * would not make sense within the config file. */ int n_options = OSSL_NELEM(cmp_options) - 1; for (opt = &cmp_options[start_opt], i = start_idx; opt->name != NULL; i++, opt++) if (!strcmp(opt->name, OPT_SECTION_STR) || !strcmp(opt->name, OPT_MORE_STR)) n_options--; OPENSSL_assert(OSSL_NELEM(cmp_vars) == n_options + OPT_PROV__FIRST + 1 - OPT_PROV__LAST + OPT_R__FIRST + 1 - OPT_R__LAST + OPT_V__FIRST + 1 - OPT_V__LAST); for (opt = &cmp_options[start_opt], i = start_idx; opt->name != NULL; i++, opt++) { int provider_option = (OPT_PROV__FIRST <= opt->retval && opt->retval < OPT_PROV__LAST); int rand_state_option = (OPT_R__FIRST <= opt->retval && opt->retval < OPT_R__LAST); int verification_option = (OPT_V__FIRST <= opt->retval && opt->retval < OPT_V__LAST); if (strcmp(opt->name, OPT_SECTION_STR) == 0 || strcmp(opt->name, OPT_MORE_STR) == 0) { i--; continue; } if (provider_option || rand_state_option || verification_option) i--; switch (opt->valtype) { case '-': case 'p': case 'n': case 'N': case 'l': if (!conf_get_number_e(conf, opt_section, opt->name, &num)) { ERR_clear_error(); continue; /* option not provided */ } if (opt->valtype == 'p' && num <= 0) { opt_printf_stderr("Non-positive number \"%ld\" for config option -%s\n", num, opt->name); return -1; } if (opt->valtype == 'N' && num < 0) { opt_printf_stderr("Negative number \"%ld\" for config option -%s\n", num, opt->name); return -1; } break; case 's': case '>': case 'M': txt = conf_get_string(conf, opt_section, opt->name); if (txt == NULL) { ERR_clear_error(); continue; /* option not provided */ } break; default: CMP_err2("internal: unsupported type '%c' for option '%s'", opt->valtype, opt->name); return 0; break; } if (provider_option || verification_option) { int conf_argc = 1; char *conf_argv[3]; char arg1[82]; BIO_snprintf(arg1, 81, "-%s", (char *)opt->name); conf_argv[0] = prog; conf_argv[1] = arg1; if (opt->valtype == '-') { if (num != 0) conf_argc = 2; } else { conf_argc = 3; conf_argv[2] = conf_get_string(conf, opt_section, opt->name); /* not NULL */ } if (conf_argc > 1) { (void)opt_init(conf_argc, conf_argv, cmp_options); if (provider_option ? !opt_provider(opt_next()) : !opt_verify(opt_next(), vpm)) { CMP_err2("for option '%s' in config file section '%s'", opt->name, opt_section); return 0; } } } else { switch (opt->valtype) { case '-': case 'p': case 'n': case 'N': if (num < INT_MIN || INT_MAX < num) { BIO_printf(bio_err, "integer value out of range for option '%s'\n", opt->name); return 0; } *cmp_vars[i].num = (int)num; break; case 'l': *cmp_vars[i].num_long = num; break; default: if (txt != NULL && txt[0] == '\0') txt = NULL; /* reset option on empty string input */ *cmp_vars[i].txt = txt; break; } } } return 1; } static char *opt_str(void) { char *arg = opt_arg(); if (arg[0] == '\0') { CMP_warn1("%s option argument is empty string, resetting option", opt_flag()); arg = NULL; } else if (arg[0] == '-') { CMP_warn1("%s option argument starts with hyphen", opt_flag()); } return arg; } /* returns 1 on success, 0 on error, -1 on -help (i.e., stop with success) */ static int get_opts(int argc, char **argv) { OPTION_CHOICE o; prog = opt_init(argc, argv, cmp_options); while ((o = opt_next()) != OPT_EOF) { switch (o) { case OPT_EOF: case OPT_ERR: opthelp: BIO_printf(bio_err, "%s: Use -help for summary.\n", prog); return 0; case OPT_HELP: opt_help(cmp_options); return -1; case OPT_CONFIG: /* has already been handled */ case OPT_SECTION: /* has already been handled */ break; case OPT_VERBOSITY: if (!set_verbosity(opt_int_arg())) goto opthelp; break; #if !defined(OPENSSL_NO_SOCK) && !defined(OPENSSL_NO_HTTP) case OPT_SERVER: opt_server = opt_str(); break; case OPT_PROXY: opt_proxy = opt_str(); break; case OPT_NO_PROXY: opt_no_proxy = opt_str(); break; #endif case OPT_RECIPIENT: opt_recipient = opt_str(); break; case OPT_PATH: opt_path = opt_str(); break; case OPT_KEEP_ALIVE: opt_keep_alive = opt_int_arg(); if (opt_keep_alive > 2) { CMP_err("-keep_alive argument must be 0, 1, or 2"); goto opthelp; } break; case OPT_MSG_TIMEOUT: opt_msg_timeout = opt_int_arg(); break; case OPT_TOTAL_TIMEOUT: opt_total_timeout = opt_int_arg(); break; #if !defined(OPENSSL_NO_SOCK) && !defined(OPENSSL_NO_HTTP) case OPT_TLS_USED: opt_tls_used = 1; break; case OPT_TLS_CERT: opt_tls_cert = opt_str(); break; case OPT_TLS_KEY: opt_tls_key = opt_str(); break; case OPT_TLS_KEYPASS: opt_tls_keypass = opt_str(); break; case OPT_TLS_EXTRA: opt_tls_extra = opt_str(); break; case OPT_TLS_TRUSTED: opt_tls_trusted = opt_str(); break; case OPT_TLS_HOST: opt_tls_host = opt_str(); break; #endif case OPT_REF: opt_ref = opt_str(); break; case OPT_SECRET: opt_secret = opt_str(); break; case OPT_CERT: opt_cert = opt_str(); break; case OPT_OWN_TRUSTED: opt_own_trusted = opt_str(); break; case OPT_KEY: opt_key = opt_str(); break; case OPT_KEYPASS: opt_keypass = opt_str(); break; case OPT_DIGEST: opt_digest = opt_str(); break; case OPT_MAC: opt_mac = opt_str(); break; case OPT_EXTRACERTS: opt_extracerts = opt_str(); break; case OPT_UNPROTECTED_REQUESTS: opt_unprotected_requests = 1; break; case OPT_TRUSTED: opt_trusted = opt_str(); break; case OPT_UNTRUSTED: opt_untrusted = opt_str(); break; case OPT_SRVCERT: opt_srvcert = opt_str(); break; case OPT_EXPECT_SENDER: opt_expect_sender = opt_str(); break; case OPT_IGNORE_KEYUSAGE: opt_ignore_keyusage = 1; break; case OPT_UNPROTECTED_ERRORS: opt_unprotected_errors = 1; break; case OPT_NO_CACHE_EXTRACERTS: opt_no_cache_extracerts = 1; break; case OPT_SRVCERTOUT: opt_srvcertout = opt_str(); break; case OPT_EXTRACERTSOUT: opt_extracertsout = opt_str(); break; case OPT_CACERTSOUT: opt_cacertsout = opt_str(); break; case OPT_OLDWITHOLD: opt_oldwithold = opt_str(); break; case OPT_NEWWITHNEW: opt_newwithnew = opt_str(); break; case OPT_NEWWITHOLD: opt_newwithold = opt_str(); break; case OPT_OLDWITHNEW: opt_oldwithnew = opt_str(); break; case OPT_V_CASES: if (!opt_verify(o, vpm)) goto opthelp; break; case OPT_CMD: opt_cmd_s = opt_str(); break; case OPT_INFOTYPE: opt_infotype_s = opt_str(); break; case OPT_PROFILE: opt_profile = opt_str(); break; case OPT_GENINFO: opt_geninfo = opt_str(); break; case OPT_NEWKEY: opt_newkey = opt_str(); break; case OPT_NEWKEYPASS: opt_newkeypass = opt_str(); break; case OPT_SUBJECT: opt_subject = opt_str(); break; case OPT_DAYS: opt_days = opt_int_arg(); break; case OPT_REQEXTS: opt_reqexts = opt_str(); break; case OPT_SANS: opt_sans = opt_str(); break; case OPT_SAN_NODEFAULT: opt_san_nodefault = 1; break; case OPT_POLICIES: opt_policies = opt_str(); break; case OPT_POLICY_OIDS: opt_policy_oids = opt_str(); break; case OPT_POLICY_OIDS_CRITICAL: opt_policy_oids_critical = 1; break; case OPT_POPO: opt_popo = opt_int_arg(); if (opt_popo < OSSL_CRMF_POPO_NONE || opt_popo > OSSL_CRMF_POPO_KEYENC) { CMP_err("invalid popo spec. Valid values are -1 .. 2"); goto opthelp; } break; case OPT_CSR: opt_csr = opt_str(); break; case OPT_OUT_TRUSTED: opt_out_trusted = opt_str(); break; case OPT_IMPLICIT_CONFIRM: opt_implicit_confirm = 1; break; case OPT_DISABLE_CONFIRM: opt_disable_confirm = 1; break; case OPT_CERTOUT: opt_certout = opt_str(); break; case OPT_CHAINOUT: opt_chainout = opt_str(); break; case OPT_OLDCERT: opt_oldcert = opt_str(); break; case OPT_REVREASON: opt_revreason = opt_int_arg(); if (opt_revreason < CRL_REASON_NONE || opt_revreason > CRL_REASON_AA_COMPROMISE || opt_revreason == 7) { CMP_err("invalid revreason. Valid values are -1 .. 6, 8 .. 10"); goto opthelp; } break; case OPT_ISSUER: opt_issuer = opt_str(); break; case OPT_SERIAL: opt_serial = opt_str(); break; case OPT_CERTFORM: opt_certform_s = opt_str(); break; case OPT_KEYFORM: opt_keyform_s = opt_str(); break; case OPT_OTHERPASS: opt_otherpass = opt_str(); break; #ifndef OPENSSL_NO_ENGINE case OPT_ENGINE: opt_engine = opt_str(); break; #endif case OPT_PROV_CASES: if (!opt_provider(o)) goto opthelp; break; case OPT_R_CASES: if (!opt_rand(o)) goto opthelp; break; case OPT_BATCH: opt_batch = 1; break; case OPT_REPEAT: opt_repeat = opt_int_arg(); break; case OPT_REQIN: opt_reqin = opt_str(); break; case OPT_REQIN_NEW_TID: opt_reqin_new_tid = 1; break; case OPT_REQOUT: opt_reqout = opt_str(); break; case OPT_RSPIN: opt_rspin = opt_str(); break; case OPT_RSPOUT: opt_rspout = opt_str(); break; case OPT_USE_MOCK_SRV: opt_use_mock_srv = 1; break; #if !defined(OPENSSL_NO_SOCK) && !defined(OPENSSL_NO_HTTP) case OPT_PORT: opt_port = opt_str(); break; case OPT_MAX_MSGS: opt_max_msgs = opt_int_arg(); break; #endif case OPT_SRV_REF: opt_srv_ref = opt_str(); break; case OPT_SRV_SECRET: opt_srv_secret = opt_str(); break; case OPT_SRV_CERT: opt_srv_cert = opt_str(); break; case OPT_SRV_KEY: opt_srv_key = opt_str(); break; case OPT_SRV_KEYPASS: opt_srv_keypass = opt_str(); break; case OPT_SRV_TRUSTED: opt_srv_trusted = opt_str(); break; case OPT_SRV_UNTRUSTED: opt_srv_untrusted = opt_str(); break; case OPT_REF_CERT: opt_ref_cert = opt_str(); break; case OPT_RSP_CERT: opt_rsp_cert = opt_str(); break; case OPT_RSP_EXTRACERTS: opt_rsp_extracerts = opt_str(); break; case OPT_RSP_CAPUBS: opt_rsp_capubs = opt_str(); break; case OPT_RSP_NEWWITHNEW: opt_rsp_newwithnew = opt_str(); break; case OPT_RSP_NEWWITHOLD: opt_rsp_newwithold = opt_str(); break; case OPT_RSP_OLDWITHNEW: opt_rsp_oldwithnew = opt_str(); break; case OPT_POLL_COUNT: opt_poll_count = opt_int_arg(); break; case OPT_CHECK_AFTER: opt_check_after = opt_int_arg(); break; case OPT_GRANT_IMPLICITCONF: opt_grant_implicitconf = 1; break; case OPT_PKISTATUS: opt_pkistatus = opt_int_arg(); break; case OPT_FAILURE: opt_failure = opt_int_arg(); break; case OPT_FAILUREBITS: opt_failurebits = opt_int_arg(); break; case OPT_STATUSSTRING: opt_statusstring = opt_str(); break; case OPT_SEND_ERROR: opt_send_error = 1; break; case OPT_SEND_UNPROTECTED: opt_send_unprotected = 1; break; case OPT_SEND_UNPROT_ERR: opt_send_unprot_err = 1; break; case OPT_ACCEPT_UNPROTECTED: opt_accept_unprotected = 1; break; case OPT_ACCEPT_UNPROT_ERR: opt_accept_unprot_err = 1; break; case OPT_ACCEPT_RAVERIFIED: opt_accept_raverified = 1; break; } } /* No extra args. */ if (!opt_check_rest_arg(NULL)) goto opthelp; return 1; } #if !defined(OPENSSL_NO_SOCK) && !defined(OPENSSL_NO_HTTP) static int cmp_server(OSSL_CMP_CTX *srv_cmp_ctx) { BIO *acbio; BIO *cbio = NULL; int keep_alive = 0; int msgs = 0; int retry = 1; int ret = 1; if ((acbio = http_server_init(prog, opt_port, opt_verbosity)) == NULL) return 0; while (opt_max_msgs <= 0 || msgs < opt_max_msgs) { char *path = NULL; OSSL_CMP_MSG *req = NULL; OSSL_CMP_MSG *resp = NULL; ret = http_server_get_asn1_req(ASN1_ITEM_rptr(OSSL_CMP_MSG), (ASN1_VALUE **)&req, &path, &cbio, acbio, &keep_alive, prog, 0, 0); if (ret == 0) { /* no request yet */ if (retry) { OSSL_sleep(1000); retry = 0; continue; } ret = 0; goto next; } if (ret++ == -1) /* fatal error */ break; ret = 0; msgs++; if (req != NULL) { if (strcmp(path, "") != 0 && strcmp(path, "pkix/") != 0) { (void)http_server_send_status(prog, cbio, 404, "Not Found"); CMP_err1("expecting empty path or 'pkix/' but got '%s'", path); OPENSSL_free(path); OSSL_CMP_MSG_free(req); goto next; } OPENSSL_free(path); resp = OSSL_CMP_CTX_server_perform(cmp_ctx, req); OSSL_CMP_MSG_free(req); if (resp == NULL) { (void)http_server_send_status(prog, cbio, 500, "Internal Server Error"); break; /* treated as fatal error */ } ret = http_server_send_asn1_resp(prog, cbio, keep_alive, "application/pkixcmp", ASN1_ITEM_rptr(OSSL_CMP_MSG), (const ASN1_VALUE *)resp); OSSL_CMP_MSG_free(resp); if (!ret) break; /* treated as fatal error */ } next: if (!ret) { /* on transmission error, cancel CMP transaction */ (void)OSSL_CMP_CTX_set1_transactionID(srv_cmp_ctx, NULL); (void)OSSL_CMP_CTX_set1_senderNonce(srv_cmp_ctx, NULL); } if (!ret || !keep_alive || OSSL_CMP_CTX_get_status(srv_cmp_ctx) != OSSL_CMP_PKISTATUS_trans /* transaction closed by OSSL_CMP_CTX_server_perform() */) { BIO_free_all(cbio); cbio = NULL; } } BIO_free_all(cbio); BIO_free_all(acbio); return ret; } #endif static void print_status(void) { /* print PKIStatusInfo */ int status = OSSL_CMP_CTX_get_status(cmp_ctx); char *buf = app_malloc(OSSL_CMP_PKISI_BUFLEN, "PKIStatusInfo buf"); const char *string = OSSL_CMP_CTX_snprint_PKIStatus(cmp_ctx, buf, OSSL_CMP_PKISI_BUFLEN); const char *from = "", *server = ""; #if !defined(OPENSSL_NO_SOCK) && !defined(OPENSSL_NO_HTTP) if (opt_server != NULL) { from = " from "; server = opt_server; } #endif CMP_print(bio_err, status == OSSL_CMP_PKISTATUS_accepted ? OSSL_CMP_LOG_INFO : status == OSSL_CMP_PKISTATUS_rejection || status == OSSL_CMP_PKISTATUS_waiting ? OSSL_CMP_LOG_ERR : OSSL_CMP_LOG_WARNING, status == OSSL_CMP_PKISTATUS_accepted ? "info" : status == OSSL_CMP_PKISTATUS_rejection ? "server error" : status == OSSL_CMP_PKISTATUS_waiting ? "internal error" : "warning", "received%s%s %s", from, server, string != NULL ? string : "<unknown PKIStatus>"); OPENSSL_free(buf); } static int do_genm(OSSL_CMP_CTX *ctx) { if (opt_infotype == NID_id_it_caCerts) { STACK_OF(X509) *cacerts = NULL; if (opt_cacertsout == NULL) { CMP_err("Missing -cacertsout option for -infotype caCerts"); return 0; } if (!OSSL_CMP_get1_caCerts(ctx, &cacerts)) return 0; /* could check authorization of sender/origin at this point */ if (cacerts == NULL) { CMP_warn("no CA certificates provided by server"); } else if (save_free_certs(cacerts, opt_cacertsout, "CA") < 0) { CMP_err1("Failed to store CA certificates from genp in %s", opt_cacertsout); return 0; } return 1; } else if (opt_infotype == NID_id_it_rootCaCert) { X509 *oldwithold = NULL; X509 *newwithnew = NULL; X509 *newwithold = NULL; X509 *oldwithnew = NULL; int res = 0; if (opt_newwithnew == NULL) { CMP_err("Missing -newwithnew option for -infotype rootCaCert"); return 0; } if (opt_oldwithold == NULL) { CMP_warn("No -oldwithold given, will use all certs given with -trusted as trust anchors for verifying the newWithNew cert"); } else { oldwithold = load_cert_pwd(opt_oldwithold, opt_otherpass, "OldWithOld cert for genm with -infotype rootCaCert"); if (oldwithold == NULL) goto end_upd; } if (!OSSL_CMP_get1_rootCaKeyUpdate(ctx, oldwithold, &newwithnew, &newwithold, &oldwithnew)) goto end_upd; /* At this point might check authorization of response sender/origin */ if (newwithnew == NULL) CMP_info("no root CA certificate update available"); else if (oldwithold == NULL && oldwithnew != NULL) CMP_warn("oldWithNew certificate received in genp for verifying oldWithOld, but oldWithOld was not provided"); if (save_cert_or_delete(newwithnew, opt_newwithnew, "NewWithNew cert from genp") && save_cert_or_delete(newwithold, opt_newwithold, "NewWithOld cert from genp") && save_cert_or_delete(oldwithnew, opt_oldwithnew, "OldWithNew cert from genp")) res = 1; X509_free(newwithnew); X509_free(newwithold); X509_free(oldwithnew); end_upd: X509_free(oldwithold); return res; } else { OSSL_CMP_ITAV *req; STACK_OF(OSSL_CMP_ITAV) *itavs; if (opt_infotype != NID_undef) { CMP_warn1("No specific support for -infotype %s available", opt_infotype_s); req = OSSL_CMP_ITAV_create(OBJ_nid2obj(opt_infotype), NULL); if (req == NULL || !OSSL_CMP_CTX_push0_genm_ITAV(ctx, req)) { CMP_err1("Failed to create genm for -infotype %s", opt_infotype_s); return 0; } } if ((itavs = OSSL_CMP_exec_GENM_ses(ctx)) != NULL) { int res = print_itavs(itavs); sk_OSSL_CMP_ITAV_pop_free(itavs, OSSL_CMP_ITAV_free); return res; } if (OSSL_CMP_CTX_get_status(ctx) != OSSL_CMP_PKISTATUS_request) CMP_err("Did not receive response on genm or genp is not valid"); return 0; } } int cmp_main(int argc, char **argv) { char *configfile = NULL; int i; X509 *newcert = NULL; ENGINE *engine = NULL; OSSL_CMP_CTX *srv_cmp_ctx = NULL; int ret = 0; /* default: failure */ prog = opt_appname(argv[0]); if (argc <= 1) { opt_help(cmp_options); goto err; } /* * handle options -config, -section, and -verbosity upfront * to take effect for other options */ for (i = 1; i < argc - 1; i++) { if (*argv[i] == '-') { if (!strcmp(argv[i] + 1, cmp_options[OPT_CONFIG - OPT_HELP].name)) opt_config = argv[++i]; else if (!strcmp(argv[i] + 1, cmp_options[OPT_SECTION - OPT_HELP].name)) opt_section = argv[++i]; else if (strcmp(argv[i] + 1, cmp_options[OPT_VERBOSITY - OPT_HELP].name) == 0 && !set_verbosity(atoi(argv[++i]))) goto err; } } if (opt_section[0] == '\0') /* empty string */ opt_section = DEFAULT_SECTION; vpm = X509_VERIFY_PARAM_new(); if (vpm == NULL) { CMP_err("out of memory"); goto err; } /* read default values for options from config file */ configfile = opt_config != NULL ? opt_config : default_config_file; if (configfile != NULL && configfile[0] != '\0' /* non-empty string */ && (configfile != default_config_file || access(configfile, F_OK) != -1)) { CMP_info2("using section(s) '%s' of OpenSSL configuration file '%s'", opt_section, configfile); conf = app_load_config(configfile); if (conf == NULL) { goto err; } else { if (strcmp(opt_section, CMP_SECTION) == 0) { /* default */ if (!NCONF_get_section(conf, opt_section)) CMP_info2("no [%s] section found in config file '%s';" " will thus use just [default] and unnamed section if present", opt_section, configfile); } else { const char *end = opt_section + strlen(opt_section); while ((end = prev_item(opt_section, end)) != NULL) { if (!NCONF_get_section(conf, opt_item)) { CMP_err2("no [%s] section found in config file '%s'", opt_item, configfile); goto err; } } } ret = read_config(); if (!set_verbosity(opt_verbosity)) /* just for checking range */ ret = -1; if (ret <= 0) { if (ret == -1) BIO_printf(bio_err, "Use -help for summary.\n"); goto err; } } } (void)BIO_flush(bio_err); /* prevent interference with opt_help() */ cmp_ctx = OSSL_CMP_CTX_new(app_get0_libctx(), app_get0_propq()); if (cmp_ctx == NULL) goto err; ret = get_opts(argc, argv); if (ret <= 0) goto err; ret = 0; if (!app_RAND_load()) goto err; if (opt_batch) set_base_ui_method(UI_null()); if (opt_engine != NULL) { engine = setup_engine_methods(opt_engine, 0 /* not: ENGINE_METHOD_ALL */, 0); if (engine == NULL) { CMP_err1("cannot load engine %s", opt_engine); goto err; } } OSSL_CMP_CTX_set_log_verbosity(cmp_ctx, opt_verbosity); if (!OSSL_CMP_CTX_set_log_cb(cmp_ctx, print_to_bio_out)) { CMP_err1("cannot set up error reporting and logging for %s", prog); goto err; } #if !defined(OPENSSL_NO_SOCK) && !defined(OPENSSL_NO_HTTP) if (opt_tls_cert == NULL && opt_tls_key == NULL && opt_tls_keypass == NULL && opt_tls_extra == NULL && opt_tls_trusted == NULL && opt_tls_host == NULL) { if (opt_tls_used) CMP_warn("-tls_used given without any other TLS options"); } else if (!opt_tls_used) { CMP_warn("ignoring TLS options(s) since -tls_used is not given"); } if (opt_port != NULL) { if (opt_tls_used) { CMP_err("-tls_used option not supported with -port option"); goto err; } if (opt_server != NULL || opt_use_mock_srv) { CMP_err("The -port option excludes -server and -use_mock_srv"); goto err; } if (opt_reqin != NULL || opt_reqout != NULL) { CMP_err("The -port option does not support -reqin and -reqout"); goto err; } if (opt_rspin != NULL || opt_rspout != NULL) { CMP_err("The -port option does not support -rspin and -rspout"); goto err; } } if (opt_server != NULL && opt_use_mock_srv) { CMP_err("cannot use both -server and -use_mock_srv options"); goto err; } #endif if (opt_ignore_keyusage) (void)OSSL_CMP_CTX_set_option(cmp_ctx, OSSL_CMP_OPT_IGNORE_KEYUSAGE, 1); if (opt_no_cache_extracerts) (void)OSSL_CMP_CTX_set_option(cmp_ctx, OSSL_CMP_OPT_NO_CACHE_EXTRACERTS, 1); if (opt_use_mock_srv #if !defined(OPENSSL_NO_SOCK) && !defined(OPENSSL_NO_HTTP) || opt_port != NULL #endif ) { OSSL_CMP_SRV_CTX *srv_ctx; if ((srv_ctx = setup_srv_ctx(engine)) == NULL) goto err; srv_cmp_ctx = OSSL_CMP_SRV_CTX_get0_cmp_ctx(srv_ctx); OSSL_CMP_CTX_set_transfer_cb_arg(cmp_ctx, srv_ctx); if (!OSSL_CMP_CTX_set_log_cb(srv_cmp_ctx, print_to_bio_err)) { CMP_err1("cannot set up error reporting and logging for %s", prog); goto err; } OSSL_CMP_CTX_set_log_verbosity(srv_cmp_ctx, opt_verbosity); } #if !defined(OPENSSL_NO_SOCK) && !defined(OPENSSL_NO_HTTP) if (opt_tls_used && (opt_use_mock_srv || opt_server == NULL)) { CMP_warn("ignoring -tls_used option since -use_mock_srv is given or -server is not given"); opt_tls_used = 0; } if (opt_port != NULL) { /* act as very basic CMP HTTP server */ ret = cmp_server(srv_cmp_ctx); goto err; } /* act as CMP client, possibly using internal mock server */ if (opt_rspin != NULL) { if (opt_server != NULL) CMP_warn("-server option is not used if enough filenames given for -rspin"); if (opt_use_mock_srv) CMP_warn("-use_mock_srv option is not used if enough filenames given for -rspin"); } #endif if (!setup_client_ctx(cmp_ctx, engine)) { CMP_err("cannot set up CMP context"); goto err; } for (i = 0; i < opt_repeat; i++) { /* everything is ready, now connect and perform the command! */ switch (opt_cmd) { case CMP_IR: newcert = OSSL_CMP_exec_IR_ses(cmp_ctx); if (newcert != NULL) ret = 1; break; case CMP_KUR: newcert = OSSL_CMP_exec_KUR_ses(cmp_ctx); if (newcert != NULL) ret = 1; break; case CMP_CR: newcert = OSSL_CMP_exec_CR_ses(cmp_ctx); if (newcert != NULL) ret = 1; break; case CMP_P10CR: newcert = OSSL_CMP_exec_P10CR_ses(cmp_ctx); if (newcert != NULL) ret = 1; break; case CMP_RR: ret = OSSL_CMP_exec_RR_ses(cmp_ctx); break; case CMP_GENM: ret = do_genm(cmp_ctx); default: break; } if (OSSL_CMP_CTX_get_status(cmp_ctx) < OSSL_CMP_PKISTATUS_accepted) { ret = 0; goto err; /* we got no response, maybe even did not send request */ } print_status(); if (!save_cert_or_delete(OSSL_CMP_CTX_get0_validatedSrvCert(cmp_ctx), opt_srvcertout, "validated server")) ret = 0; if (!ret) goto err; ret = 0; if (save_free_certs(OSSL_CMP_CTX_get1_extraCertsIn(cmp_ctx), opt_extracertsout, "extra") < 0) goto err; if (newcert != NULL && (opt_cmd == CMP_IR || opt_cmd == CMP_CR || opt_cmd == CMP_KUR || opt_cmd == CMP_P10CR)) if (!save_cert_or_delete(newcert, opt_certout, "newly enrolled") || save_free_certs(OSSL_CMP_CTX_get1_newChain(cmp_ctx), opt_chainout, "chain") < 0 || save_free_certs(OSSL_CMP_CTX_get1_caPubs(cmp_ctx), opt_cacertsout, "CA") < 0) goto err; if (!OSSL_CMP_CTX_reinit(cmp_ctx)) goto err; } ret = 1; err: /* in case we ended up here on error without proper cleaning */ cleanse(opt_keypass); cleanse(opt_newkeypass); cleanse(opt_otherpass); #if !defined(OPENSSL_NO_SOCK) && !defined(OPENSSL_NO_HTTP) cleanse(opt_tls_keypass); #endif cleanse(opt_secret); cleanse(opt_srv_keypass); cleanse(opt_srv_secret); if (ret != 1) OSSL_CMP_CTX_print_errors(cmp_ctx); if (cmp_ctx != NULL) { #if !defined(OPENSSL_NO_SOCK) && !defined(OPENSSL_NO_HTTP) APP_HTTP_TLS_INFO *info = OSSL_CMP_CTX_get_http_cb_arg(cmp_ctx); (void)OSSL_CMP_CTX_set_http_cb_arg(cmp_ctx, NULL); #endif ossl_cmp_mock_srv_free(OSSL_CMP_CTX_get_transfer_cb_arg(cmp_ctx)); X509_STORE_free(OSSL_CMP_CTX_get_certConf_cb_arg(cmp_ctx)); /* cannot free info already here, as it may be used indirectly by: */ OSSL_CMP_CTX_free(cmp_ctx); #if !defined(OPENSSL_NO_SOCK) && !defined(OPENSSL_NO_HTTP) if (info != NULL) { OPENSSL_free((char *)info->server); OPENSSL_free((char *)info->port); APP_HTTP_TLS_INFO_free(info); } #endif } X509_VERIFY_PARAM_free(vpm); release_engine(engine); NCONF_free(conf); /* must not do as long as opt_... variables are used */ OSSL_CMP_log_close(); return ret == 0 ? EXIT_FAILURE : EXIT_SUCCESS; /* ret == -1 for -help */ }
./openssl/apps/pkeyparam.c
/* * Copyright 2006-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 "apps.h" #include "progs.h" #include <openssl/pem.h> #include <openssl/err.h> #include <openssl/evp.h> typedef enum OPTION_choice { OPT_COMMON, OPT_IN, OPT_OUT, OPT_TEXT, OPT_NOOUT, OPT_ENGINE, OPT_CHECK, OPT_PROV_ENUM } OPTION_CHOICE; const OPTIONS pkeyparam_options[] = { OPT_SECTION("General"), {"help", OPT_HELP, '-', "Display this summary"}, #ifndef OPENSSL_NO_ENGINE {"engine", OPT_ENGINE, 's', "Use engine, possibly a hardware device"}, #endif {"check", OPT_CHECK, '-', "Check key param consistency"}, OPT_SECTION("Input"), {"in", OPT_IN, '<', "Input file"}, OPT_SECTION("Output"), {"out", OPT_OUT, '>', "Output file"}, {"text", OPT_TEXT, '-', "Print parameters as text"}, {"noout", OPT_NOOUT, '-', "Don't output encoded parameters"}, OPT_PROV_OPTIONS, {NULL} }; int pkeyparam_main(int argc, char **argv) { ENGINE *e = NULL; BIO *in = NULL, *out = NULL; EVP_PKEY *pkey = NULL; EVP_PKEY_CTX *ctx = NULL; int text = 0, noout = 0, ret = EXIT_FAILURE, check = 0, r; OPTION_CHOICE o; char *infile = NULL, *outfile = NULL, *prog; prog = opt_init(argc, argv, pkeyparam_options); while ((o = opt_next()) != OPT_EOF) { switch (o) { case OPT_EOF: case OPT_ERR: opthelp: BIO_printf(bio_err, "%s: Use -help for summary.\n", prog); goto end; case OPT_HELP: opt_help(pkeyparam_options); ret = 0; goto end; case OPT_IN: infile = opt_arg(); break; case OPT_OUT: outfile = opt_arg(); break; case OPT_ENGINE: e = setup_engine(opt_arg(), 0); break; case OPT_TEXT: text = 1; break; case OPT_NOOUT: noout = 1; break; case OPT_CHECK: check = 1; break; case OPT_PROV_CASES: if (!opt_provider(o)) goto end; break; } } /* No extra arguments. */ if (!opt_check_rest_arg(NULL)) goto opthelp; in = bio_open_default(infile, 'r', FORMAT_PEM); if (in == NULL) goto end; out = bio_open_default(outfile, 'w', FORMAT_PEM); if (out == NULL) goto end; pkey = PEM_read_bio_Parameters_ex(in, NULL, app_get0_libctx(), app_get0_propq()); if (pkey == NULL) { BIO_printf(bio_err, "Error reading parameters\n"); ERR_print_errors(bio_err); goto end; } if (check) { if (e == NULL) ctx = EVP_PKEY_CTX_new_from_pkey(app_get0_libctx(), pkey, app_get0_propq()); else ctx = EVP_PKEY_CTX_new(pkey, e); if (ctx == NULL) { ERR_print_errors(bio_err); goto end; } r = EVP_PKEY_param_check(ctx); if (r == 1) { BIO_printf(out, "Parameters are valid\n"); } else { /* * Note: at least for RSA keys if this function returns * -1, there will be no error reasons. */ BIO_printf(bio_err, "Parameters are invalid\n"); ERR_print_errors(bio_err); goto end; } } if (!noout) PEM_write_bio_Parameters(out, pkey); if (text) EVP_PKEY_print_params(out, pkey, 0, NULL); ret = EXIT_SUCCESS; end: EVP_PKEY_CTX_free(ctx); EVP_PKEY_free(pkey); release_engine(e); BIO_free_all(out); BIO_free(in); return ret; }
./openssl/apps/rsa.c
/* * Copyright 1995-2023 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ /* Necessary for legacy RSA public key export */ #define OPENSSL_SUPPRESS_DEPRECATED #include <openssl/opensslconf.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> #include "apps.h" #include "progs.h" #include <openssl/bio.h> #include <openssl/err.h> #include <openssl/rsa.h> #include <openssl/evp.h> #include <openssl/x509.h> #include <openssl/pem.h> #include <openssl/bn.h> #include <openssl/encoder.h> /* * This include is to get OSSL_KEYMGMT_SELECT_*, which feels a bit * much just for those macros... they might serve better as EVP macros. */ #include <openssl/core_dispatch.h> #ifndef OPENSSL_NO_RC4 # define DEFAULT_PVK_ENCR_STRENGTH 2 #else # define DEFAULT_PVK_ENCR_STRENGTH 0 #endif typedef enum OPTION_choice { OPT_COMMON, OPT_INFORM, OPT_OUTFORM, OPT_ENGINE, OPT_IN, OPT_OUT, OPT_PUBIN, OPT_PUBOUT, OPT_PASSOUT, OPT_PASSIN, OPT_RSAPUBKEY_IN, OPT_RSAPUBKEY_OUT, /* Do not change the order here; see case statements below */ OPT_PVK_NONE, OPT_PVK_WEAK, OPT_PVK_STRONG, OPT_NOOUT, OPT_TEXT, OPT_MODULUS, OPT_CHECK, OPT_CIPHER, OPT_PROV_ENUM, OPT_TRADITIONAL } OPTION_CHOICE; const OPTIONS rsa_options[] = { OPT_SECTION("General"), {"help", OPT_HELP, '-', "Display this summary"}, {"check", OPT_CHECK, '-', "Verify key consistency"}, {"", OPT_CIPHER, '-', "Any supported cipher"}, #ifndef OPENSSL_NO_ENGINE {"engine", OPT_ENGINE, 's', "Use engine, possibly a hardware device"}, #endif OPT_SECTION("Input"), {"in", OPT_IN, 's', "Input file"}, {"inform", OPT_INFORM, 'f', "Input format (DER/PEM/P12/ENGINE)"}, {"pubin", OPT_PUBIN, '-', "Expect a public key in input file"}, {"RSAPublicKey_in", OPT_RSAPUBKEY_IN, '-', "Input is an RSAPublicKey"}, {"passin", OPT_PASSIN, 's', "Input file pass phrase source"}, OPT_SECTION("Output"), {"out", OPT_OUT, '>', "Output file"}, {"outform", OPT_OUTFORM, 'f', "Output format, one of DER PEM PVK"}, {"pubout", OPT_PUBOUT, '-', "Output a public key"}, {"RSAPublicKey_out", OPT_RSAPUBKEY_OUT, '-', "Output is an RSAPublicKey"}, {"passout", OPT_PASSOUT, 's', "Output file pass phrase source"}, {"noout", OPT_NOOUT, '-', "Don't print key out"}, {"text", OPT_TEXT, '-', "Print the key in text"}, {"modulus", OPT_MODULUS, '-', "Print the RSA key modulus"}, {"traditional", OPT_TRADITIONAL, '-', "Use traditional format for private keys"}, #ifndef OPENSSL_NO_RC4 OPT_SECTION("PVK"), {"pvk-strong", OPT_PVK_STRONG, '-', "Enable 'Strong' PVK encoding level (default)"}, {"pvk-weak", OPT_PVK_WEAK, '-', "Enable 'Weak' PVK encoding level"}, {"pvk-none", OPT_PVK_NONE, '-', "Don't enforce PVK encoding"}, #endif OPT_PROV_OPTIONS, {NULL} }; static int try_legacy_encoding(EVP_PKEY *pkey, int outformat, int pubout, BIO *out) { int ret = 0; #ifndef OPENSSL_NO_DEPRECATED_3_0 const RSA *rsa = EVP_PKEY_get0_RSA(pkey); if (rsa == NULL) return 0; if (outformat == FORMAT_ASN1) { if (pubout == 2) ret = i2d_RSAPublicKey_bio(out, rsa) > 0; else ret = i2d_RSA_PUBKEY_bio(out, rsa) > 0; } else if (outformat == FORMAT_PEM) { if (pubout == 2) ret = PEM_write_bio_RSAPublicKey(out, rsa) > 0; else ret = PEM_write_bio_RSA_PUBKEY(out, rsa) > 0; # ifndef OPENSSL_NO_DSA } else if (outformat == FORMAT_MSBLOB || outformat == FORMAT_PVK) { ret = i2b_PublicKey_bio(out, pkey) > 0; # endif } #endif return ret; } int rsa_main(int argc, char **argv) { ENGINE *e = NULL; BIO *out = NULL; EVP_PKEY *pkey = NULL; EVP_PKEY_CTX *pctx; EVP_CIPHER *enc = NULL; char *infile = NULL, *outfile = NULL, *ciphername = NULL, *prog; char *passin = NULL, *passout = NULL, *passinarg = NULL, *passoutarg = NULL; int private = 0; int informat = FORMAT_UNDEF, outformat = FORMAT_PEM, text = 0, check = 0; int noout = 0, modulus = 0, pubin = 0, pubout = 0, ret = 1; int pvk_encr = DEFAULT_PVK_ENCR_STRENGTH; OPTION_CHOICE o; int traditional = 0; const char *output_type = NULL; const char *output_structure = NULL; int selection = 0; OSSL_ENCODER_CTX *ectx = NULL; opt_set_unknown_name("cipher"); prog = opt_init(argc, argv, rsa_options); while ((o = opt_next()) != OPT_EOF) { switch (o) { case OPT_EOF: case OPT_ERR: opthelp: BIO_printf(bio_err, "%s: Use -help for summary.\n", prog); goto end; case OPT_HELP: opt_help(rsa_options); ret = 0; goto end; case OPT_INFORM: if (!opt_format(opt_arg(), OPT_FMT_ANY, &informat)) goto opthelp; break; case OPT_IN: infile = opt_arg(); break; case OPT_OUTFORM: if (!opt_format(opt_arg(), OPT_FMT_ANY, &outformat)) goto opthelp; break; case OPT_OUT: outfile = opt_arg(); break; case OPT_PASSIN: passinarg = opt_arg(); break; case OPT_PASSOUT: passoutarg = opt_arg(); break; case OPT_ENGINE: e = setup_engine(opt_arg(), 0); break; case OPT_PUBIN: pubin = 1; break; case OPT_PUBOUT: pubout = 1; break; case OPT_RSAPUBKEY_IN: pubin = 2; break; case OPT_RSAPUBKEY_OUT: pubout = 2; break; case OPT_PVK_STRONG: /* pvk_encr:= 2 */ case OPT_PVK_WEAK: /* pvk_encr:= 1 */ case OPT_PVK_NONE: /* pvk_encr:= 0 */ pvk_encr = (o - OPT_PVK_NONE); break; case OPT_NOOUT: noout = 1; break; case OPT_TEXT: text = 1; break; case OPT_MODULUS: modulus = 1; break; case OPT_CHECK: check = 1; break; case OPT_CIPHER: ciphername = opt_unknown(); break; case OPT_PROV_CASES: if (!opt_provider(o)) goto end; break; case OPT_TRADITIONAL: traditional = 1; break; } } /* No extra arguments. */ if (!opt_check_rest_arg(NULL)) goto opthelp; if (!opt_cipher(ciphername, &enc)) goto opthelp; private = (text && !pubin) || (!pubout && !noout); if (!app_passwd(passinarg, passoutarg, &passin, &passout)) { BIO_printf(bio_err, "Error getting passwords\n"); goto end; } if (check && pubin) { BIO_printf(bio_err, "Only private keys can be checked\n"); goto end; } if (pubin) { int tmpformat = FORMAT_UNDEF; if (pubin == 2) { if (informat == FORMAT_PEM) tmpformat = FORMAT_PEMRSA; else if (informat == FORMAT_ASN1) tmpformat = FORMAT_ASN1RSA; } else { tmpformat = informat; } pkey = load_pubkey(infile, tmpformat, 1, passin, e, "public key"); } else { pkey = load_key(infile, informat, 1, passin, e, "private key"); } if (pkey == NULL) { ERR_print_errors(bio_err); goto end; } if (!EVP_PKEY_is_a(pkey, "RSA") && !EVP_PKEY_is_a(pkey, "RSA-PSS")) { BIO_printf(bio_err, "Not an RSA key\n"); goto end; } out = bio_open_owner(outfile, outformat, private); if (out == NULL) goto end; if (text) { assert(pubin || private); if ((pubin && EVP_PKEY_print_public(out, pkey, 0, NULL) <= 0) || (!pubin && EVP_PKEY_print_private(out, pkey, 0, NULL) <= 0)) { perror(outfile); ERR_print_errors(bio_err); goto end; } } if (modulus) { BIGNUM *n = NULL; /* Every RSA key has an 'n' */ EVP_PKEY_get_bn_param(pkey, "n", &n); BIO_printf(out, "Modulus="); BN_print(out, n); BIO_printf(out, "\n"); BN_free(n); } if (check) { int r; pctx = EVP_PKEY_CTX_new_from_pkey(NULL, pkey, NULL); if (pctx == NULL) { BIO_printf(bio_err, "RSA unable to create PKEY context\n"); ERR_print_errors(bio_err); goto end; } r = EVP_PKEY_check(pctx); EVP_PKEY_CTX_free(pctx); if (r == 1) { BIO_printf(out, "RSA key ok\n"); } else if (r == 0) { BIO_printf(bio_err, "RSA key not ok\n"); ERR_print_errors(bio_err); } else if (r < 0) { ERR_print_errors(bio_err); goto end; } } if (noout) { ret = 0; goto end; } BIO_printf(bio_err, "writing RSA key\n"); /* Choose output type for the format */ if (outformat == FORMAT_ASN1) { output_type = "DER"; } else if (outformat == FORMAT_PEM) { output_type = "PEM"; } else if (outformat == FORMAT_MSBLOB) { output_type = "MSBLOB"; } else if (outformat == FORMAT_PVK) { if (pubin) { BIO_printf(bio_err, "PVK form impossible with public key input\n"); goto end; } output_type = "PVK"; } else { BIO_printf(bio_err, "bad output format specified for outfile\n"); goto end; } /* Select what you want in the output */ if (pubout || pubin) { selection = OSSL_KEYMGMT_SELECT_PUBLIC_KEY; } else { assert(private); selection = (OSSL_KEYMGMT_SELECT_KEYPAIR | OSSL_KEYMGMT_SELECT_ALL_PARAMETERS); } /* For DER based output, select the desired output structure */ if (outformat == FORMAT_ASN1 || outformat == FORMAT_PEM) { if (pubout || pubin) { if (pubout == 2) output_structure = "pkcs1"; /* "type-specific" would work too */ else output_structure = "SubjectPublicKeyInfo"; } else { assert(private); if (traditional) output_structure = "pkcs1"; /* "type-specific" would work too */ else output_structure = "PrivateKeyInfo"; } } /* Now, perform the encoding */ ectx = OSSL_ENCODER_CTX_new_for_pkey(pkey, selection, output_type, output_structure, NULL); if (OSSL_ENCODER_CTX_get_num_encoders(ectx) == 0) { if ((!pubout && !pubin) || !try_legacy_encoding(pkey, outformat, pubout, out)) BIO_printf(bio_err, "%s format not supported\n", output_type); else ret = 0; goto end; } /* Passphrase setup */ if (enc != NULL) OSSL_ENCODER_CTX_set_cipher(ectx, EVP_CIPHER_get0_name(enc), NULL); /* Default passphrase prompter */ if (enc != NULL || outformat == FORMAT_PVK) { OSSL_ENCODER_CTX_set_passphrase_ui(ectx, get_ui_method(), NULL); if (passout != NULL) /* When passout given, override the passphrase prompter */ OSSL_ENCODER_CTX_set_passphrase(ectx, (const unsigned char *)passout, strlen(passout)); } /* PVK is a bit special... */ if (outformat == FORMAT_PVK) { OSSL_PARAM params[2] = { OSSL_PARAM_END, OSSL_PARAM_END }; params[0] = OSSL_PARAM_construct_int("encrypt-level", &pvk_encr); if (!OSSL_ENCODER_CTX_set_params(ectx, params)) { BIO_printf(bio_err, "invalid PVK encryption level\n"); goto end; } } if (!OSSL_ENCODER_to_bio(ectx, out)) { BIO_printf(bio_err, "unable to write key\n"); ERR_print_errors(bio_err); goto end; } ret = 0; end: OSSL_ENCODER_CTX_free(ectx); release_engine(e); BIO_free_all(out); EVP_PKEY_free(pkey); EVP_CIPHER_free(enc); OPENSSL_free(passin); OPENSSL_free(passout); return ret; }
./openssl/apps/include/names.h
/* * Copyright 2019 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <openssl/safestack.h> /* Standard comparing function for names */ int name_cmp(const char * const *a, const char * const *b); /* collect_names is meant to be used with EVP_{type}_doall_names */ void collect_names(const char *name, void *vdata); /* Sorts and prints a stack of names to |out| */ void print_names(BIO *out, STACK_OF(OPENSSL_CSTRING) *names);
./openssl/apps/include/cmp_mock_srv.h
/* * Copyright 2018-2023 The OpenSSL Project Authors. All Rights Reserved. * Copyright Siemens AG 2018-2020 * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #ifndef OSSL_APPS_CMP_MOCK_SRV_H # define OSSL_APPS_CMP_MOCK_SRV_H # include <openssl/opensslconf.h> # ifndef OPENSSL_NO_CMP # include <openssl/cmp.h> OSSL_CMP_SRV_CTX *ossl_cmp_mock_srv_new(OSSL_LIB_CTX *libctx, const char *propq); void ossl_cmp_mock_srv_free(OSSL_CMP_SRV_CTX *srv_ctx); int ossl_cmp_mock_srv_set1_refCert(OSSL_CMP_SRV_CTX *srv_ctx, X509 *cert); int ossl_cmp_mock_srv_set1_certOut(OSSL_CMP_SRV_CTX *srv_ctx, X509 *cert); int ossl_cmp_mock_srv_set1_chainOut(OSSL_CMP_SRV_CTX *srv_ctx, STACK_OF(X509) *chain); int ossl_cmp_mock_srv_set1_caPubsOut(OSSL_CMP_SRV_CTX *srv_ctx, STACK_OF(X509) *caPubs); int ossl_cmp_mock_srv_set1_newWithNew(OSSL_CMP_SRV_CTX *srv_ctx, X509 *cert); int ossl_cmp_mock_srv_set1_newWithOld(OSSL_CMP_SRV_CTX *srv_ctx, X509 *cert); int ossl_cmp_mock_srv_set1_oldWithNew(OSSL_CMP_SRV_CTX *srv_ctx, X509 *cert); int ossl_cmp_mock_srv_set_statusInfo(OSSL_CMP_SRV_CTX *srv_ctx, int status, int fail_info, const char *text); int ossl_cmp_mock_srv_set_sendError(OSSL_CMP_SRV_CTX *srv_ctx, int bodytype); int ossl_cmp_mock_srv_set_pollCount(OSSL_CMP_SRV_CTX *srv_ctx, int count); int ossl_cmp_mock_srv_set_checkAfterTime(OSSL_CMP_SRV_CTX *srv_ctx, int sec); # endif /* !defined(OPENSSL_NO_CMP) */ #endif /* !defined(OSSL_APPS_CMP_MOCK_SRV_H) */
./openssl/apps/include/app_params.h
/* * Copyright 2019-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/core.h> int print_param_types(const char *thing, const OSSL_PARAM *pdefs, int indent); void print_param_value(const OSSL_PARAM *p, int indent);
./openssl/apps/include/opt.h
/* * Copyright 2018-2023 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #ifndef OSSL_APPS_OPT_H #define OSSL_APPS_OPT_H #include <sys/types.h> #include <openssl/e_os2.h> #include <openssl/types.h> #include <stdarg.h> #define OPT_COMMON OPT_ERR = -1, OPT_EOF = 0, OPT_HELP /* * Common verification options. */ # define OPT_V_ENUM \ OPT_V__FIRST=2000, \ OPT_V_POLICY, OPT_V_PURPOSE, OPT_V_VERIFY_NAME, OPT_V_VERIFY_DEPTH, \ OPT_V_ATTIME, OPT_V_VERIFY_HOSTNAME, OPT_V_VERIFY_EMAIL, \ OPT_V_VERIFY_IP, OPT_V_IGNORE_CRITICAL, OPT_V_ISSUER_CHECKS, \ OPT_V_CRL_CHECK, OPT_V_CRL_CHECK_ALL, OPT_V_POLICY_CHECK, \ OPT_V_EXPLICIT_POLICY, OPT_V_INHIBIT_ANY, OPT_V_INHIBIT_MAP, \ OPT_V_X509_STRICT, OPT_V_EXTENDED_CRL, OPT_V_USE_DELTAS, \ OPT_V_POLICY_PRINT, OPT_V_CHECK_SS_SIG, OPT_V_TRUSTED_FIRST, \ OPT_V_SUITEB_128_ONLY, OPT_V_SUITEB_128, OPT_V_SUITEB_192, \ OPT_V_PARTIAL_CHAIN, OPT_V_NO_ALT_CHAINS, OPT_V_NO_CHECK_TIME, \ OPT_V_VERIFY_AUTH_LEVEL, OPT_V_ALLOW_PROXY_CERTS, \ OPT_V__LAST # define OPT_V_OPTIONS \ OPT_SECTION("Validation"), \ { "policy", OPT_V_POLICY, 's', "adds policy to the acceptable policy set"}, \ { "purpose", OPT_V_PURPOSE, 's', \ "certificate chain purpose"}, \ { "verify_name", OPT_V_VERIFY_NAME, 's', "verification policy name"}, \ { "verify_depth", OPT_V_VERIFY_DEPTH, 'n', \ "chain depth limit" }, \ { "auth_level", OPT_V_VERIFY_AUTH_LEVEL, 'n', \ "chain authentication security level" }, \ { "attime", OPT_V_ATTIME, 'M', "verification epoch time" }, \ { "verify_hostname", OPT_V_VERIFY_HOSTNAME, 's', \ "expected peer hostname" }, \ { "verify_email", OPT_V_VERIFY_EMAIL, 's', \ "expected peer email" }, \ { "verify_ip", OPT_V_VERIFY_IP, 's', \ "expected peer IP address" }, \ { "ignore_critical", OPT_V_IGNORE_CRITICAL, '-', \ "permit unhandled critical extensions"}, \ { "issuer_checks", OPT_V_ISSUER_CHECKS, '-', "(deprecated)"}, \ { "crl_check", OPT_V_CRL_CHECK, '-', "check leaf certificate revocation" }, \ { "crl_check_all", OPT_V_CRL_CHECK_ALL, '-', "check full chain revocation" }, \ { "policy_check", OPT_V_POLICY_CHECK, '-', "perform rfc5280 policy checks"}, \ { "explicit_policy", OPT_V_EXPLICIT_POLICY, '-', \ "set policy variable require-explicit-policy"}, \ { "inhibit_any", OPT_V_INHIBIT_ANY, '-', \ "set policy variable inhibit-any-policy"}, \ { "inhibit_map", OPT_V_INHIBIT_MAP, '-', \ "set policy variable inhibit-policy-mapping"}, \ { "x509_strict", OPT_V_X509_STRICT, '-', \ "disable certificate compatibility work-arounds"}, \ { "extended_crl", OPT_V_EXTENDED_CRL, '-', \ "enable extended CRL features"}, \ { "use_deltas", OPT_V_USE_DELTAS, '-', \ "use delta CRLs"}, \ { "policy_print", OPT_V_POLICY_PRINT, '-', \ "print policy processing diagnostics"}, \ { "check_ss_sig", OPT_V_CHECK_SS_SIG, '-', \ "check root CA self-signatures"}, \ { "trusted_first", OPT_V_TRUSTED_FIRST, '-', \ "search trust store first (default)" }, \ { "suiteB_128_only", OPT_V_SUITEB_128_ONLY, '-', "Suite B 128-bit-only mode"}, \ { "suiteB_128", OPT_V_SUITEB_128, '-', \ "Suite B 128-bit mode allowing 192-bit algorithms"}, \ { "suiteB_192", OPT_V_SUITEB_192, '-', "Suite B 192-bit-only mode" }, \ { "partial_chain", OPT_V_PARTIAL_CHAIN, '-', \ "accept chains anchored by intermediate trust-store CAs"}, \ { "no_alt_chains", OPT_V_NO_ALT_CHAINS, '-', "(deprecated)" }, \ { "no_check_time", OPT_V_NO_CHECK_TIME, '-', "ignore certificate validity time" }, \ { "allow_proxy_certs", OPT_V_ALLOW_PROXY_CERTS, '-', "allow the use of proxy certificates" } # define OPT_V_CASES \ OPT_V__FIRST: case OPT_V__LAST: break; \ case OPT_V_POLICY: \ case OPT_V_PURPOSE: \ case OPT_V_VERIFY_NAME: \ case OPT_V_VERIFY_DEPTH: \ case OPT_V_VERIFY_AUTH_LEVEL: \ case OPT_V_ATTIME: \ case OPT_V_VERIFY_HOSTNAME: \ case OPT_V_VERIFY_EMAIL: \ case OPT_V_VERIFY_IP: \ case OPT_V_IGNORE_CRITICAL: \ case OPT_V_ISSUER_CHECKS: \ case OPT_V_CRL_CHECK: \ case OPT_V_CRL_CHECK_ALL: \ case OPT_V_POLICY_CHECK: \ case OPT_V_EXPLICIT_POLICY: \ case OPT_V_INHIBIT_ANY: \ case OPT_V_INHIBIT_MAP: \ case OPT_V_X509_STRICT: \ case OPT_V_EXTENDED_CRL: \ case OPT_V_USE_DELTAS: \ case OPT_V_POLICY_PRINT: \ case OPT_V_CHECK_SS_SIG: \ case OPT_V_TRUSTED_FIRST: \ case OPT_V_SUITEB_128_ONLY: \ case OPT_V_SUITEB_128: \ case OPT_V_SUITEB_192: \ case OPT_V_PARTIAL_CHAIN: \ case OPT_V_NO_ALT_CHAINS: \ case OPT_V_NO_CHECK_TIME: \ case OPT_V_ALLOW_PROXY_CERTS /* * Common "extended validation" options. */ # define OPT_X_ENUM \ OPT_X__FIRST=1000, \ OPT_X_KEY, OPT_X_CERT, OPT_X_CHAIN, OPT_X_CHAIN_BUILD, \ OPT_X_CERTFORM, OPT_X_KEYFORM, \ OPT_X__LAST # define OPT_X_OPTIONS \ OPT_SECTION("Extended certificate"), \ { "xkey", OPT_X_KEY, '<', "key for Extended certificates"}, \ { "xcert", OPT_X_CERT, '<', "cert for Extended certificates"}, \ { "xchain", OPT_X_CHAIN, '<', "chain for Extended certificates"}, \ { "xchain_build", OPT_X_CHAIN_BUILD, '-', \ "build certificate chain for the extended certificates"}, \ { "xcertform", OPT_X_CERTFORM, 'F', \ "format of Extended certificate (PEM/DER/P12); has no effect" }, \ { "xkeyform", OPT_X_KEYFORM, 'F', \ "format of Extended certificate's key (DER/PEM/P12); has no effect"} # define OPT_X_CASES \ OPT_X__FIRST: case OPT_X__LAST: break; \ case OPT_X_KEY: \ case OPT_X_CERT: \ case OPT_X_CHAIN: \ case OPT_X_CHAIN_BUILD: \ case OPT_X_CERTFORM: \ case OPT_X_KEYFORM /* * Common SSL options. * Any changes here must be coordinated with ../ssl/ssl_conf.c */ # define OPT_S_ENUM \ OPT_S__FIRST=3000, \ OPT_S_NOSSL3, OPT_S_NOTLS1, OPT_S_NOTLS1_1, OPT_S_NOTLS1_2, \ OPT_S_NOTLS1_3, OPT_S_BUGS, OPT_S_NO_COMP, OPT_S_NOTICKET, \ OPT_S_SERVERPREF, OPT_S_LEGACYRENEG, OPT_S_CLIENTRENEG, \ OPT_S_LEGACYCONN, \ OPT_S_ONRESUMP, OPT_S_NOLEGACYCONN, \ OPT_S_ALLOW_NO_DHE_KEX, OPT_S_PREFER_NO_DHE_KEX, \ OPT_S_PRIORITIZE_CHACHA, \ OPT_S_STRICT, OPT_S_SIGALGS, OPT_S_CLIENTSIGALGS, OPT_S_GROUPS, \ OPT_S_CURVES, OPT_S_NAMEDCURVE, OPT_S_CIPHER, OPT_S_CIPHERSUITES, \ OPT_S_RECORD_PADDING, OPT_S_DEBUGBROKE, OPT_S_COMP, \ OPT_S_MINPROTO, OPT_S_MAXPROTO, \ OPT_S_NO_RENEGOTIATION, OPT_S_NO_MIDDLEBOX, OPT_S_NO_ETM, \ OPT_S_NO_EMS, \ OPT_S_NO_TX_CERT_COMP, \ OPT_S_NO_RX_CERT_COMP, \ OPT_S__LAST # define OPT_S_OPTIONS \ OPT_SECTION("TLS/SSL"), \ {"no_ssl3", OPT_S_NOSSL3, '-',"Just disable SSLv3" }, \ {"no_tls1", OPT_S_NOTLS1, '-', "Just disable TLSv1"}, \ {"no_tls1_1", OPT_S_NOTLS1_1, '-', "Just disable TLSv1.1" }, \ {"no_tls1_2", OPT_S_NOTLS1_2, '-', "Just disable TLSv1.2"}, \ {"no_tls1_3", OPT_S_NOTLS1_3, '-', "Just disable TLSv1.3"}, \ {"bugs", OPT_S_BUGS, '-', "Turn on SSL bug compatibility"}, \ {"no_comp", OPT_S_NO_COMP, '-', "Disable SSL/TLS compression (default)" }, \ {"comp", OPT_S_COMP, '-', "Use SSL/TLS-level compression" }, \ {"no_tx_cert_comp", OPT_S_NO_TX_CERT_COMP, '-', "Disable sending TLSv1.3 compressed certificates" }, \ {"no_rx_cert_comp", OPT_S_NO_RX_CERT_COMP, '-', "Disable receiving TLSv1.3 compressed certificates" }, \ {"no_ticket", OPT_S_NOTICKET, '-', \ "Disable use of TLS session tickets"}, \ {"serverpref", OPT_S_SERVERPREF, '-', "Use server's cipher preferences"}, \ {"legacy_renegotiation", OPT_S_LEGACYRENEG, '-', \ "Enable use of legacy renegotiation (dangerous)"}, \ {"client_renegotiation", OPT_S_CLIENTRENEG, '-', \ "Allow client-initiated renegotiation" }, \ {"no_renegotiation", OPT_S_NO_RENEGOTIATION, '-', \ "Disable all renegotiation."}, \ {"legacy_server_connect", OPT_S_LEGACYCONN, '-', \ "Allow initial connection to servers that don't support RI"}, \ {"no_resumption_on_reneg", OPT_S_ONRESUMP, '-', \ "Disallow session resumption on renegotiation"}, \ {"no_legacy_server_connect", OPT_S_NOLEGACYCONN, '-', \ "Disallow initial connection to servers that don't support RI"}, \ {"allow_no_dhe_kex", OPT_S_ALLOW_NO_DHE_KEX, '-', \ "In TLSv1.3 allow non-(ec)dhe based key exchange on resumption"}, \ {"prefer_no_dhe_kex", OPT_S_PREFER_NO_DHE_KEX, '-', \ "In TLSv1.3 prefer non-(ec)dhe over (ec)dhe-based key exchange on resumption"}, \ {"prioritize_chacha", OPT_S_PRIORITIZE_CHACHA, '-', \ "Prioritize ChaCha ciphers when preferred by clients"}, \ {"strict", OPT_S_STRICT, '-', \ "Enforce strict certificate checks as per TLS standard"}, \ {"sigalgs", OPT_S_SIGALGS, 's', \ "Signature algorithms to support (colon-separated list)" }, \ {"client_sigalgs", OPT_S_CLIENTSIGALGS, 's', \ "Signature algorithms to support for client certificate" \ " authentication (colon-separated list)" }, \ {"groups", OPT_S_GROUPS, 's', \ "Groups to advertise (colon-separated list)" }, \ {"curves", OPT_S_CURVES, 's', \ "Groups to advertise (colon-separated list)" }, \ {"named_curve", OPT_S_NAMEDCURVE, 's', \ "Elliptic curve used for ECDHE (server-side only)" }, \ {"cipher", OPT_S_CIPHER, 's', "Specify TLSv1.2 and below cipher list to be used"}, \ {"ciphersuites", OPT_S_CIPHERSUITES, 's', "Specify TLSv1.3 ciphersuites to be used"}, \ {"min_protocol", OPT_S_MINPROTO, 's', "Specify the minimum protocol version to be used"}, \ {"max_protocol", OPT_S_MAXPROTO, 's', "Specify the maximum protocol version to be used"}, \ {"record_padding", OPT_S_RECORD_PADDING, 's', \ "Block size to pad TLS 1.3 records to."}, \ {"debug_broken_protocol", OPT_S_DEBUGBROKE, '-', \ "Perform all sorts of protocol violations for testing purposes"}, \ {"no_middlebox", OPT_S_NO_MIDDLEBOX, '-', \ "Disable TLSv1.3 middlebox compat mode" }, \ {"no_etm", OPT_S_NO_ETM, '-', \ "Disable Encrypt-then-Mac extension"}, \ {"no_ems", OPT_S_NO_EMS, '-', \ "Disable Extended master secret extension"} # define OPT_S_CASES \ OPT_S__FIRST: case OPT_S__LAST: break; \ case OPT_S_NOSSL3: \ case OPT_S_NOTLS1: \ case OPT_S_NOTLS1_1: \ case OPT_S_NOTLS1_2: \ case OPT_S_NOTLS1_3: \ case OPT_S_BUGS: \ case OPT_S_NO_COMP: \ case OPT_S_COMP: \ case OPT_S_NO_TX_CERT_COMP: \ case OPT_S_NO_RX_CERT_COMP: \ case OPT_S_NOTICKET: \ case OPT_S_SERVERPREF: \ case OPT_S_LEGACYRENEG: \ case OPT_S_CLIENTRENEG: \ case OPT_S_LEGACYCONN: \ case OPT_S_ONRESUMP: \ case OPT_S_NOLEGACYCONN: \ case OPT_S_ALLOW_NO_DHE_KEX: \ case OPT_S_PREFER_NO_DHE_KEX: \ case OPT_S_PRIORITIZE_CHACHA: \ case OPT_S_STRICT: \ case OPT_S_SIGALGS: \ case OPT_S_CLIENTSIGALGS: \ case OPT_S_GROUPS: \ case OPT_S_CURVES: \ case OPT_S_NAMEDCURVE: \ case OPT_S_CIPHER: \ case OPT_S_CIPHERSUITES: \ case OPT_S_RECORD_PADDING: \ case OPT_S_NO_RENEGOTIATION: \ case OPT_S_MINPROTO: \ case OPT_S_MAXPROTO: \ case OPT_S_DEBUGBROKE: \ case OPT_S_NO_MIDDLEBOX: \ case OPT_S_NO_ETM: \ case OPT_S_NO_EMS #define IS_NO_PROT_FLAG(o) \ (o == OPT_S_NOSSL3 || o == OPT_S_NOTLS1 || o == OPT_S_NOTLS1_1 \ || o == OPT_S_NOTLS1_2 || o == OPT_S_NOTLS1_3) /* * Random state options. */ # define OPT_R_ENUM \ OPT_R__FIRST=1500, OPT_R_RAND, OPT_R_WRITERAND, OPT_R__LAST # define OPT_R_OPTIONS \ OPT_SECTION("Random state"), \ {"rand", OPT_R_RAND, 's', "Load the given file(s) into the random number generator"}, \ {"writerand", OPT_R_WRITERAND, '>', "Write random data to the specified file"} # define OPT_R_CASES \ OPT_R__FIRST: case OPT_R__LAST: break; \ case OPT_R_RAND: case OPT_R_WRITERAND /* * Provider options. */ # define OPT_PROV_ENUM \ OPT_PROV__FIRST=1600, \ OPT_PROV_PROVIDER, OPT_PROV_PROVIDER_PATH, OPT_PROV_PROPQUERY, \ OPT_PROV__LAST # define OPT_CONFIG_OPTION \ { "config", OPT_CONFIG, '<', "Load a configuration file (this may load modules)" } # define OPT_PROV_OPTIONS \ OPT_SECTION("Provider"), \ { "provider-path", OPT_PROV_PROVIDER_PATH, 's', "Provider load path (must be before 'provider' argument if required)" }, \ { "provider", OPT_PROV_PROVIDER, 's', "Provider to load (can be specified multiple times)" }, \ { "propquery", OPT_PROV_PROPQUERY, 's', "Property query used when fetching algorithms" } # define OPT_PROV_CASES \ OPT_PROV__FIRST: case OPT_PROV__LAST: break; \ case OPT_PROV_PROVIDER: \ case OPT_PROV_PROVIDER_PATH: \ case OPT_PROV_PROPQUERY /* * Option parsing. */ extern const char OPT_HELP_STR[]; extern const char OPT_MORE_STR[]; extern const char OPT_SECTION_STR[]; extern const char OPT_PARAM_STR[]; typedef struct options_st { const char *name; int retval; /*- * value type: * * '-' no value (also the value zero) * 'n' number (type 'int') * 'p' positive number (type 'int') * 'u' unsigned number (type 'unsigned long') * 'l' number (type 'unsigned long') * 'M' number (type 'intmax_t') * 'U' unsigned number (type 'uintmax_t') * 's' string * '<' input file * '>' output file * '/' directory * 'f' any format [OPT_FMT_ANY] * 'F' der/pem format [OPT_FMT_PEMDER] * 'A' any ASN1, der/pem/b64 format [OPT_FMT_ASN1] * 'E' der/pem/engine format [OPT_FMT_PDE] * 'c' pem/der/smime format [OPT_FMT_PDS] * * The 'l', 'n' and 'u' value types include the values zero, * the 'p' value type does not. */ int valtype; const char *helpstr; } OPTIONS; /* Special retval values: */ #define OPT_PARAM 0 /* same as OPT_EOF usually defined in apps */ #define OPT_DUP -2 /* marks duplicate occurrence of option in help output */ /* * A string/int pairing; widely use for option value lookup, hence the * name OPT_PAIR. But that name is misleading in s_cb.c, so we also use * the "generic" name STRINT_PAIR. */ typedef struct string_int_pair_st { const char *name; int retval; } OPT_PAIR, STRINT_PAIR; /* Flags to pass into opt_format; see FORMAT_xxx, below. */ # define OPT_FMT_PEM (1L << 1) # define OPT_FMT_DER (1L << 2) # define OPT_FMT_B64 (1L << 3) # define OPT_FMT_PKCS12 (1L << 4) # define OPT_FMT_SMIME (1L << 5) # define OPT_FMT_ENGINE (1L << 6) # define OPT_FMT_MSBLOB (1L << 7) # define OPT_FMT_NSS (1L << 8) # define OPT_FMT_TEXT (1L << 9) # define OPT_FMT_HTTP (1L << 10) # define OPT_FMT_PVK (1L << 11) # define OPT_FMT_PEMDER (OPT_FMT_PEM | OPT_FMT_DER) # define OPT_FMT_ASN1 (OPT_FMT_PEM | OPT_FMT_DER | OPT_FMT_B64) # define OPT_FMT_PDE (OPT_FMT_PEMDER | OPT_FMT_ENGINE) # define OPT_FMT_PDS (OPT_FMT_PEMDER | OPT_FMT_SMIME) # define OPT_FMT_ANY ( \ OPT_FMT_PEM | OPT_FMT_DER | OPT_FMT_B64 | \ OPT_FMT_PKCS12 | OPT_FMT_SMIME | \ OPT_FMT_ENGINE | OPT_FMT_MSBLOB | OPT_FMT_NSS | \ OPT_FMT_TEXT | OPT_FMT_HTTP | OPT_FMT_PVK) /* Divide options into sections when displaying usage */ #define OPT_SECTION(sec) { OPT_SECTION_STR, 1, '-', sec " options:\n" } #define OPT_PARAMETERS() { OPT_PARAM_STR, 1, '-', "Parameters:\n" } const char *opt_path_end(const char *filename); char *opt_init(int ac, char **av, const OPTIONS *o); char *opt_progname(const char *argv0); char *opt_appname(const char *argv0); char *opt_getprog(void); void opt_help(const OPTIONS *list); void opt_begin(void); int opt_next(void); char *opt_flag(void); char *opt_arg(void); char *opt_unknown(void); void reset_unknown(void); int opt_cipher(const char *name, EVP_CIPHER **cipherp); int opt_cipher_any(const char *name, EVP_CIPHER **cipherp); int opt_cipher_silent(const char *name, EVP_CIPHER **cipherp); int opt_check_md(const char *name); int opt_md(const char *name, EVP_MD **mdp); int opt_md_silent(const char *name, EVP_MD **mdp); int opt_int(const char *arg, int *result); void opt_set_unknown_name(const char *name); int opt_int_arg(void); int opt_long(const char *arg, long *result); int opt_ulong(const char *arg, unsigned long *result); int opt_intmax(const char *arg, ossl_intmax_t *result); int opt_uintmax(const char *arg, ossl_uintmax_t *result); int opt_isdir(const char *name); int opt_format(const char *s, unsigned long flags, int *result); void print_format_error(int format, unsigned long flags); int opt_printf_stderr(const char *fmt, ...); int opt_string(const char *name, const char **options); int opt_pair(const char *arg, const OPT_PAIR *pairs, int *result); int opt_verify(int i, X509_VERIFY_PARAM *vpm); int opt_rand(int i); int opt_provider(int i); int opt_provider_option_given(void); char **opt_rest(void); int opt_num_rest(void); int opt_check_rest_arg(const char *expected); /* Returns non-zero if legacy paths are still available */ int opt_legacy_okay(void); #endif /* OSSL_APPS_OPT_H */
./openssl/apps/include/fmt.h
/* * 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 */ /* * Options are shared by apps (see apps.h) and the test system * (see test/testutil.h'). * In order to remove the dependency between apps and options, the following * shared fields have been moved into this file. */ #ifndef OSSL_APPS_FMT_H #define OSSL_APPS_FMT_H /* * On some platforms, it's important to distinguish between text and binary * files. On some, there might even be specific file formats for different * contents. The FORMAT_xxx macros are meant to express an intent with the * file being read or created. */ # define B_FORMAT_TEXT 0x8000 # define FORMAT_UNDEF 0 # define FORMAT_TEXT (1 | B_FORMAT_TEXT) /* Generic text */ # define FORMAT_BINARY 2 /* Generic binary */ # define FORMAT_BASE64 (3 | B_FORMAT_TEXT) /* Base64 */ # define FORMAT_ASN1 4 /* ASN.1/DER */ # define FORMAT_PEM (5 | B_FORMAT_TEXT) # define FORMAT_PKCS12 6 # define FORMAT_SMIME (7 | B_FORMAT_TEXT) # define FORMAT_ENGINE 8 /* Not really a file format */ # define FORMAT_PEMRSA (9 | B_FORMAT_TEXT) /* PEM RSAPublicKey format */ # define FORMAT_ASN1RSA 10 /* DER RSAPublicKey format */ # define FORMAT_MSBLOB 11 /* MS Key blob format */ # define FORMAT_PVK 12 /* MS PVK file format */ # define FORMAT_HTTP 13 /* Download using HTTP */ # define FORMAT_NSS 14 /* NSS keylog format */ int FMT_istext(int format); #endif /* OSSL_APPS_FMT_H_ */
./openssl/apps/include/ec_common.h
/* * 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 */ #ifndef OPENSSL_NO_EC static const char *point_format_options[] = { "uncompressed", "compressed", "hybrid", NULL }; static const char *asn1_encoding_options[] = { "named_curve", "explicit", NULL }; #endif
./openssl/apps/include/app_libctx.h
/* * Copyright 2021 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #ifndef OSSL_APPS_LIBCTX_H # define OSSL_APPS_LIBCTX_H # include <openssl/types.h> OSSL_LIB_CTX *app_create_libctx(void); OSSL_LIB_CTX *app_get0_libctx(void); int app_set_propq(const char *arg); const char *app_get0_propq(void); #endif
./openssl/apps/include/vms_term_sock.h
/* * Copyright 2016 The OpenSSL Project Authors. All Rights Reserved. * Copyright 2016 VMS Software, 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 */ #ifndef OSSL_APPS_VMS_TERM_SOCK_H # define OSSL_APPS_VMS_TERM_SOCK_H /* ** Terminal Socket Function Codes */ # define TERM_SOCK_CREATE 1 # define TERM_SOCK_DELETE 2 /* ** Terminal Socket Status Codes */ # define TERM_SOCK_FAILURE 0 # define TERM_SOCK_SUCCESS 1 /* ** Terminal Socket Prototype */ int TerminalSocket (int FunctionCode, int *ReturnSocket); #endif
./openssl/apps/include/log.h
/* * Copyright 1995-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_APPS_LOG_H # define OSSL_APPS_LOG_H # include <openssl/bio.h> # if !defined(OPENSSL_SYS_VMS) && !defined(OPENSSL_SYS_WINDOWS) \ && !defined(OPENSSL_NO_SOCK) && !defined(OPENSSL_NO_POSIX_IO) # include <syslog.h> # else # define LOG_EMERG 0 # define LOG_ALERT 1 # define LOG_CRIT 2 # define LOG_ERR 3 # define LOG_WARNING 4 # define LOG_NOTICE 5 # define LOG_INFO 6 # define LOG_DEBUG 7 # endif # undef LOG_TRACE # define LOG_TRACE (LOG_DEBUG + 1) int log_set_verbosity(const char *prog, int level); int log_get_verbosity(void); /*- * Output a message using the trace API with the given category * if the category is >= 0 and tracing is enabled. * Log the message to syslog if multi-threaded HTTP_DAEMON, else to bio_err * if the verbosity is sufficient for the given level of severity. * Yet cannot do both types of output in strict ANSI mode. * category: trace category as defined in trace.h, or -1 * prog: the name of the current app, or NULL * level: the severity of the message, e.g., LOG_ERR * fmt: message format, which should not include a trailing newline * ...: potential extra parameters like with printf() * returns nothing */ void trace_log_message(int category, const char *prog, int level, const char *fmt, ...); #endif /* OSSL_APPS_LOG_H */
./openssl/apps/include/engine_loader.h
/* * 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 */ #ifndef HEADER_ENGINE_LOADER_H # define HEADER_ENGINE_LOADER_H # include <openssl/store.h> /* this is a private URI scheme */ # define ENGINE_SCHEME "org.openssl.engine" # define ENGINE_SCHEME_COLON ENGINE_SCHEME ":" int setup_engine_loader(void); void destroy_engine_loader(void); #endif
./openssl/apps/include/function.h
/* * Copyright 2019-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 */ #ifndef OSSL_APPS_FUNCTION_H # define OSSL_APPS_FUNCTION_H # include <openssl/lhash.h> # include "opt.h" #define DEPRECATED_NO_ALTERNATIVE "unknown" typedef enum FUNC_TYPE { FT_none, FT_general, FT_md, FT_cipher, FT_pkey, FT_md_alg, FT_cipher_alg } FUNC_TYPE; typedef struct function_st { FUNC_TYPE type; const char *name; int (*func)(int argc, char *argv[]); const OPTIONS *help; const char *deprecated_alternative; const char *deprecated_version; } FUNCTION; DEFINE_LHASH_OF_EX(FUNCTION); /* Structure to hold the number of columns to be displayed and the * field width used to display them. */ typedef struct { int columns; int width; } DISPLAY_COLUMNS; void calculate_columns(FUNCTION *functions, DISPLAY_COLUMNS *dc); #endif
./openssl/apps/include/http_server.h
/* * Copyright 1995-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_HTTP_SERVER_H # define OSSL_HTTP_SERVER_H # include "apps.h" # include "log.h" # ifndef HAVE_FORK # if defined(OPENSSL_SYS_VMS) || defined(OPENSSL_SYS_WINDOWS) # define HAVE_FORK 0 # else # define HAVE_FORK 1 # endif # endif # if HAVE_FORK # undef NO_FORK # else # define NO_FORK # endif # if !defined(NO_FORK) && !defined(OPENSSL_NO_SOCK) \ && !defined(OPENSSL_NO_POSIX_IO) # define HTTP_DAEMON # include <sys/types.h> # include <sys/wait.h> # include <signal.h> # define MAXERRLEN 1000 /* limit error text sent to syslog to 1000 bytes */ # endif # ifndef OPENSSL_NO_SOCK /*- * Initialize an HTTP server, setting up its listening BIO * prog: the name of the current app * port: the port to listen on * verbosity: the level of verbosity to use, or -1 for default: LOG_INFO * returns a BIO for accepting requests, NULL on error */ BIO *http_server_init(const char *prog, const char *port, int verbosity); /*- * Accept an ASN.1-formatted HTTP request * it: the expected request ASN.1 type * preq: pointer to variable where to place the parsed request * ppath: pointer to variable where to place the request path, or NULL * pcbio: pointer to variable where to place the BIO for sending the response to * acbio: the listening bio (typically as returned by http_server_init_bio()) * found_keep_alive: for returning flag if client requests persistent connection * prog: the name of the current app, for diagnostics only * accept_get: whether to accept GET requests (in addition to POST requests) * timeout: connection timeout (in seconds), or 0 for none/infinite * returns 0 in case caller should retry, then *preq == *ppath == *pcbio == NULL * returns -1 on fatal error; also then holds *preq == *ppath == *pcbio == NULL * returns 1 otherwise. In this case it is guaranteed that *pcbio != NULL while * *ppath == NULL and *preq == NULL if and only if the request is invalid, * On return value 1 the caller is responsible for sending an HTTP response, * using http_server_send_asn1_resp() or http_server_send_status(). * The caller must free any non-NULL *preq, *ppath, and *pcbio pointers. */ int http_server_get_asn1_req(const ASN1_ITEM *it, ASN1_VALUE **preq, char **ppath, BIO **pcbio, BIO *acbio, int *found_keep_alive, const char *prog, int accept_get, int timeout); /*- * Send an ASN.1-formatted HTTP response * prog: the name of the current app, for diagnostics only * cbio: destination BIO (typically as returned by http_server_get_asn1_req()) * note: cbio should not do an encoding that changes the output length * keep_alive: grant persistent connection * content_type: string identifying the type of the response * it: the response ASN.1 type * resp: the response to send * returns 1 on success, 0 on failure */ int http_server_send_asn1_resp(const char *prog, BIO *cbio, int keep_alive, const char *content_type, const ASN1_ITEM *it, const ASN1_VALUE *resp); /*- * Send a trivial HTTP response, typically to report an error or OK * prog: the name of the current app, for diagnostics only * cbio: destination BIO (typically as returned by http_server_get_asn1_req()) * status: the status code to send * reason: the corresponding human-readable string * returns 1 on success, 0 on failure */ int http_server_send_status(const char *prog, BIO *cbio, int status, const char *reason); # endif # ifdef HTTP_DAEMON extern int n_responders; extern int acfd; void socket_timeout(int signum); void spawn_loop(const char *prog); # endif #endif
./openssl/apps/include/platform.h
/* * Copyright 2019 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #ifndef OSSL_APPS_PLATFORM_H # define OSSL_APPS_PLATFORM_H # include <openssl/e_os2.h> # if defined(OPENSSL_SYS_VMS) && defined(__DECC) /* * VMS C only for now, implemented in vms_decc_init.c * If other C compilers forget to terminate argv with NULL, this function * can be re-used. */ char **copy_argv(int *argc, char *argv[]); # endif # ifdef _WIN32 /* * Win32-specific argv initialization that splits OS-supplied UNICODE * command line string to array of UTF8-encoded strings. */ void win32_utf8argv(int *argc, char **argv[]); # endif #endif
./openssl/apps/include/apps.h
/* * Copyright 1995-2023 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #ifndef OSSL_APPS_H # define OSSL_APPS_H # include "internal/e_os.h" /* struct timeval for DTLS */ # include "internal/common.h" /* for HAS_PREFIX */ # include "internal/nelem.h" # include "internal/sockets.h" /* for openssl_fdset() */ # include <assert.h> # include <stdarg.h> # include <sys/types.h> # ifndef OPENSSL_NO_POSIX_IO # include <sys/stat.h> # include <fcntl.h> # endif # include <openssl/e_os2.h> # include <openssl/types.h> # include <openssl/bio.h> # include <openssl/x509.h> # include <openssl/conf.h> # include <openssl/txt_db.h> # include <openssl/engine.h> # include <openssl/ocsp.h> # include <openssl/http.h> # include <signal.h> # include "apps_ui.h" # include "opt.h" # include "fmt.h" # include "platform.h" # include "engine_loader.h" # include "app_libctx.h" /* * quick macro when you need to pass an unsigned char instead of a char. * this is true for some implementations of the is*() functions, for * example. */ # define _UC(c) ((unsigned char)(c)) void app_RAND_load_conf(CONF *c, const char *section); int app_RAND_write(void); int app_RAND_load(void); extern char *default_config_file; /* may be "" */ extern BIO *bio_in; extern BIO *bio_out; extern BIO *bio_err; extern const unsigned char tls13_aes128gcmsha256_id[]; extern const unsigned char tls13_aes256gcmsha384_id[]; extern BIO_ADDR *ourpeer; BIO *dup_bio_in(int format); BIO *dup_bio_out(int format); BIO *dup_bio_err(int format); BIO *bio_open_owner(const char *filename, int format, int private); BIO *bio_open_default(const char *filename, char mode, int format); BIO *bio_open_default_quiet(const char *filename, char mode, int format); char *app_conf_try_string(const CONF *cnf, const char *group, const char *name); int app_conf_try_number(const CONF *conf, const char *group, const char *name, long *result); CONF *app_load_config_bio(BIO *in, const char *filename); # define app_load_config(filename) app_load_config_internal(filename, 0) # define app_load_config_quiet(filename) app_load_config_internal(filename, 1) CONF *app_load_config_internal(const char *filename, int quiet); CONF *app_load_config_verbose(const char *filename, int verbose); int app_load_modules(const CONF *config); CONF *app_load_config_modules(const char *configfile); void unbuffer(FILE *fp); void wait_for_async(SSL *s); # if defined(OPENSSL_SYS_MSDOS) int has_stdin_waiting(void); # endif void corrupt_signature(const ASN1_STRING *signature); int set_cert_times(X509 *x, const char *startdate, const char *enddate, int days); int set_crl_lastupdate(X509_CRL *crl, const char *lastupdate); int set_crl_nextupdate(X509_CRL *crl, const char *nextupdate, long days, long hours, long secs); typedef struct args_st { int size; int argc; char **argv; } ARGS; /* We need both wrap and the "real" function because libcrypto uses both. */ int wrap_password_callback(char *buf, int bufsiz, int verify, void *cb_data); /* progress callback for dsaparam, dhparam, req, genpkey, etc. */ int progress_cb(EVP_PKEY_CTX *ctx); int chopup_args(ARGS *arg, char *buf); void dump_cert_text(BIO *out, X509 *x); void print_name(BIO *out, const char *title, const X509_NAME *nm); void print_bignum_var(BIO *, const BIGNUM *, const char *, int, unsigned char *); void print_array(BIO *, const char *, int, const unsigned char *); int set_nameopt(const char *arg); unsigned long get_nameopt(void); int set_dateopt(unsigned long *dateopt, const char *arg); int set_cert_ex(unsigned long *flags, const char *arg); int set_name_ex(unsigned long *flags, const char *arg); int set_ext_copy(int *copy_type, const char *arg); int copy_extensions(X509 *x, X509_REQ *req, int copy_type); char *get_passwd(const char *pass, const char *desc); int app_passwd(const char *arg1, const char *arg2, char **pass1, char **pass2); int add_oid_section(CONF *conf); X509_REQ *load_csr(const char *file, int format, const char *desc); X509_REQ *load_csr_autofmt(const char *infile, int format, STACK_OF(OPENSSL_STRING) *vfyopts, const char *desc); X509 *load_cert_pass(const char *uri, int format, int maybe_stdin, const char *pass, const char *desc); # define load_cert(uri, format, desc) load_cert_pass(uri, format, 1, NULL, desc) X509_CRL *load_crl(const char *uri, int format, int maybe_stdin, const char *desc); void cleanse(char *str); void clear_free(char *str); EVP_PKEY *load_key(const char *uri, int format, int maybe_stdin, const char *pass, ENGINE *e, const char *desc); /* first try reading public key, on failure resort to loading private key */ EVP_PKEY *load_pubkey(const char *uri, int format, int maybe_stdin, const char *pass, ENGINE *e, const char *desc); EVP_PKEY *load_keyparams(const char *uri, int format, int maybe_stdin, const char *keytype, const char *desc); EVP_PKEY *load_keyparams_suppress(const char *uri, int format, int maybe_stdin, const char *keytype, const char *desc, int suppress_decode_errors); char *next_item(char *opt); /* in list separated by comma and/or space */ int load_cert_certs(const char *uri, X509 **pcert, STACK_OF(X509) **pcerts, int exclude_http, const char *pass, const char *desc, X509_VERIFY_PARAM *vpm); STACK_OF(X509) *load_certs_multifile(char *files, const char *pass, const char *desc, X509_VERIFY_PARAM *vpm); X509_STORE *load_certstore(char *input, const char *pass, const char *desc, X509_VERIFY_PARAM *vpm); int load_certs(const char *uri, int maybe_stdin, STACK_OF(X509) **certs, const char *pass, const char *desc); int load_crls(const char *uri, STACK_OF(X509_CRL) **crls, const char *pass, const char *desc); int load_key_certs_crls(const char *uri, int format, int maybe_stdin, const char *pass, const char *desc, int quiet, EVP_PKEY **ppkey, EVP_PKEY **ppubkey, EVP_PKEY **pparams, X509 **pcert, STACK_OF(X509) **pcerts, X509_CRL **pcrl, STACK_OF(X509_CRL) **pcrls); X509_STORE *setup_verify(const char *CAfile, int noCAfile, const char *CApath, int noCApath, const char *CAstore, int noCAstore); __owur int ctx_set_verify_locations(SSL_CTX *ctx, const char *CAfile, int noCAfile, const char *CApath, int noCApath, const char *CAstore, int noCAstore); # ifndef OPENSSL_NO_CT /* * Sets the file to load the Certificate Transparency log list from. * If path is NULL, loads from the default file path. * Returns 1 on success, 0 otherwise. */ __owur int ctx_set_ctlog_list_file(SSL_CTX *ctx, const char *path); # endif ENGINE *setup_engine_methods(const char *id, unsigned int methods, int debug); # define setup_engine(e, debug) setup_engine_methods(e, (unsigned int)-1, debug) void release_engine(ENGINE *e); int init_engine(ENGINE *e); int finish_engine(ENGINE *e); char *make_engine_uri(ENGINE *e, const char *key_id, const char *desc); int get_legacy_pkey_id(OSSL_LIB_CTX *libctx, const char *algname, ENGINE *e); const EVP_MD *get_digest_from_engine(const char *name); const EVP_CIPHER *get_cipher_from_engine(const char *name); # ifndef OPENSSL_NO_OCSP OCSP_RESPONSE *process_responder(OCSP_REQUEST *req, const char *host, const char *port, const char *path, const char *proxy, const char *no_proxy, int use_ssl, STACK_OF(CONF_VALUE) *headers, int req_timeout); # endif /* Functions defined in ca.c and also used in ocsp.c */ int unpack_revinfo(ASN1_TIME **prevtm, int *preason, ASN1_OBJECT **phold, ASN1_GENERALIZEDTIME **pinvtm, const char *str); # define DB_type 0 # define DB_exp_date 1 # define DB_rev_date 2 # define DB_serial 3 /* index - unique */ # define DB_file 4 # define DB_name 5 /* index - unique when active and not disabled */ # define DB_NUMBER 6 # define DB_TYPE_REV 'R' /* Revoked */ # define DB_TYPE_EXP 'E' /* Expired */ # define DB_TYPE_VAL 'V' /* Valid ; inserted with: ca ... -valid */ # define DB_TYPE_SUSP 'S' /* Suspended */ typedef struct db_attr_st { int unique_subject; } DB_ATTR; typedef struct ca_db_st { DB_ATTR attributes; TXT_DB *db; char *dbfname; # ifndef OPENSSL_NO_POSIX_IO struct stat dbst; # endif } CA_DB; extern int do_updatedb(CA_DB *db, time_t *now); void app_bail_out(char *fmt, ...); void *app_malloc(size_t sz, const char *what); /* load_serial, save_serial, and rotate_serial are also used for CRL numbers */ BIGNUM *load_serial(const char *serialfile, int *exists, int create, ASN1_INTEGER **retai); int save_serial(const char *serialfile, const char *suffix, const BIGNUM *serial, ASN1_INTEGER **retai); int rotate_serial(const char *serialfile, const char *new_suffix, const char *old_suffix); int rand_serial(BIGNUM *b, ASN1_INTEGER *ai); CA_DB *load_index(const char *dbfile, DB_ATTR *dbattr); int index_index(CA_DB *db); int save_index(const char *dbfile, const char *suffix, CA_DB *db); int rotate_index(const char *dbfile, const char *new_suffix, const char *old_suffix); void free_index(CA_DB *db); # define index_name_cmp_noconst(a, b) \ index_name_cmp((const OPENSSL_CSTRING *)CHECKED_PTR_OF(OPENSSL_STRING, a), \ (const OPENSSL_CSTRING *)CHECKED_PTR_OF(OPENSSL_STRING, b)) int index_name_cmp(const OPENSSL_CSTRING *a, const OPENSSL_CSTRING *b); int parse_yesno(const char *str, int def); X509_NAME *parse_name(const char *str, int chtype, int multirdn, const char *desc); void policies_print(X509_STORE_CTX *ctx); int bio_to_mem(unsigned char **out, int maxlen, BIO *in); int pkey_ctrl_string(EVP_PKEY_CTX *ctx, const char *value); int x509_ctrl_string(X509 *x, const char *value); int x509_req_ctrl_string(X509_REQ *x, const char *value); int init_gen_str(EVP_PKEY_CTX **pctx, const char *algname, ENGINE *e, int do_param, OSSL_LIB_CTX *libctx, const char *propq); int cert_matches_key(const X509 *cert, const EVP_PKEY *pkey); int do_X509_sign(X509 *x, int force_v1, EVP_PKEY *pkey, const char *md, STACK_OF(OPENSSL_STRING) *sigopts, X509V3_CTX *ext_ctx); int do_X509_verify(X509 *x, EVP_PKEY *pkey, STACK_OF(OPENSSL_STRING) *vfyopts); int do_X509_REQ_sign(X509_REQ *x, EVP_PKEY *pkey, const char *md, STACK_OF(OPENSSL_STRING) *sigopts); int do_X509_REQ_verify(X509_REQ *x, EVP_PKEY *pkey, STACK_OF(OPENSSL_STRING) *vfyopts); int do_X509_CRL_sign(X509_CRL *x, EVP_PKEY *pkey, const char *md, STACK_OF(OPENSSL_STRING) *sigopts); extern char *psk_key; unsigned char *next_protos_parse(size_t *outlen, const char *in); int check_cert_attributes(BIO *bio, X509 *x, const char *checkhost, const char *checkemail, const char *checkip, int print); void store_setup_crl_download(X509_STORE *st); typedef struct app_http_tls_info_st { const char *server; const char *port; int use_proxy; long timeout; SSL_CTX *ssl_ctx; } APP_HTTP_TLS_INFO; BIO *app_http_tls_cb(BIO *hbio, /* APP_HTTP_TLS_INFO */ void *arg, int connect, int detail); void APP_HTTP_TLS_INFO_free(APP_HTTP_TLS_INFO *info); # ifndef OPENSSL_NO_SOCK ASN1_VALUE *app_http_get_asn1(const char *url, const char *proxy, const char *no_proxy, SSL_CTX *ssl_ctx, const STACK_OF(CONF_VALUE) *headers, long timeout, const char *expected_content_type, const ASN1_ITEM *it); ASN1_VALUE *app_http_post_asn1(const char *host, const char *port, const char *path, const char *proxy, const char *no_proxy, SSL_CTX *ctx, const STACK_OF(CONF_VALUE) *headers, const char *content_type, ASN1_VALUE *req, const ASN1_ITEM *req_it, const char *expected_content_type, long timeout, const ASN1_ITEM *rsp_it); # endif # define EXT_COPY_NONE 0 # define EXT_COPY_ADD 1 # define EXT_COPY_ALL 2 # define NETSCAPE_CERT_HDR "certificate" # define APP_PASS_LEN 1024 /* * IETF RFC 5280 says serial number must be <= 20 bytes. Use 159 bits * so that the first bit will never be one, so that the DER encoding * rules won't force a leading octet. */ # define SERIAL_RAND_BITS 159 int app_isdir(const char *); int app_access(const char *, int flag); int fileno_stdin(void); int fileno_stdout(void); int raw_read_stdin(void *, int); int raw_write_stdout(const void *, int); # define TM_START 0 # define TM_STOP 1 double app_tminterval(int stop, int usertime); void make_uppercase(char *string); typedef struct verify_options_st { int depth; int quiet; int error; int return_error; } VERIFY_CB_ARGS; extern VERIFY_CB_ARGS verify_args; OSSL_PARAM *app_params_new_from_opts(STACK_OF(OPENSSL_STRING) *opts, const OSSL_PARAM *paramdefs); void app_params_free(OSSL_PARAM *params); int app_provider_load(OSSL_LIB_CTX *libctx, const char *provider_name); void app_providers_cleanup(void); EVP_PKEY *app_keygen(EVP_PKEY_CTX *ctx, const char *alg, int bits, int verbose); EVP_PKEY *app_paramgen(EVP_PKEY_CTX *ctx, const char *alg); #endif
./openssl/apps/include/apps_ui.h
/* * 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 */ #ifndef OSSL_APPS_UI_H # define OSSL_APPS_UI_H # define PW_MIN_LENGTH 4 typedef struct pw_cb_data { const void *password; const char *prompt_info; } PW_CB_DATA; int password_callback(char *buf, int bufsiz, int verify, PW_CB_DATA *cb_data); int setup_ui_method(void); void destroy_ui_method(void); int set_base_ui_method(const UI_METHOD *ui_method); const UI_METHOD *get_ui_method(void); extern BIO *bio_err; #endif
./openssl/apps/include/s_apps.h
/* * Copyright 1995-2023 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <openssl/opensslconf.h> #include <openssl/ssl.h> #include <openssl/srp.h> #define PORT "4433" #define PROTOCOL "tcp" #define SSL_VERSION_ALLOWS_RENEGOTIATION(s) \ (SSL_is_dtls(s) || (SSL_version(s) < TLS1_3_VERSION)) typedef int (*do_server_cb)(int s, int stype, int prot, unsigned char *context); void get_sock_info_address(int asock, char **hostname, char **service); int report_server_accept(BIO *out, int asock, int with_address, int with_pid); int do_server(int *accept_sock, const char *host, const char *port, int family, int type, int protocol, do_server_cb cb, unsigned char *context, int naccept, BIO *bio_s_out, int tfo); int verify_callback(int ok, X509_STORE_CTX *ctx); int set_cert_stuff(SSL_CTX *ctx, char *cert_file, char *key_file); int set_cert_key_stuff(SSL_CTX *ctx, X509 *cert, EVP_PKEY *key, STACK_OF(X509) *chain, int build_chain); int ssl_print_sigalgs(BIO *out, SSL *s); int ssl_print_point_formats(BIO *out, SSL *s); int ssl_print_groups(BIO *out, SSL *s, int noshared); int ssl_print_tmp_key(BIO *out, SSL *s); int init_client(int *sock, const char *host, const char *port, const char *bindhost, const char *bindport, int family, int type, int protocol, int tfo, int doconn, BIO_ADDR **ba_ret); int should_retry(int i); void do_ssl_shutdown(SSL *ssl); long bio_dump_callback(BIO *bio, int cmd, const char *argp, size_t len, int argi, long argl, int ret, size_t *processed); void apps_ssl_info_callback(const SSL *s, int where, int ret); void msg_cb(int write_p, int version, int content_type, const void *buf, size_t len, SSL *ssl, void *arg); void tlsext_cb(SSL *s, int client_server, int type, const unsigned char *data, int len, void *arg); int generate_cookie_callback(SSL *ssl, unsigned char *cookie, unsigned int *cookie_len); int verify_cookie_callback(SSL *ssl, const unsigned char *cookie, unsigned int cookie_len); #ifdef __VMS /* 31 char symbol name limit */ # define generate_stateless_cookie_callback generate_stateless_cookie_cb # define verify_stateless_cookie_callback verify_stateless_cookie_cb #endif int generate_stateless_cookie_callback(SSL *ssl, unsigned char *cookie, size_t *cookie_len); int verify_stateless_cookie_callback(SSL *ssl, const unsigned char *cookie, size_t cookie_len); typedef struct ssl_excert_st SSL_EXCERT; void ssl_ctx_set_excert(SSL_CTX *ctx, SSL_EXCERT *exc); void ssl_excert_free(SSL_EXCERT *exc); int args_excert(int option, SSL_EXCERT **pexc); int load_excert(SSL_EXCERT **pexc); void print_verify_detail(SSL *s, BIO *bio); void print_ssl_summary(SSL *s); int config_ctx(SSL_CONF_CTX *cctx, STACK_OF(OPENSSL_STRING) *str, SSL_CTX *ctx); int ssl_ctx_add_crls(SSL_CTX *ctx, STACK_OF(X509_CRL) *crls, int crl_download); int ssl_load_stores(SSL_CTX *ctx, const char *vfyCApath, const char *vfyCAfile, const char *vfyCAstore, const char *chCApath, const char *chCAfile, const char *chCAstore, STACK_OF(X509_CRL) *crls, int crl_download); void ssl_ctx_security_debug(SSL_CTX *ctx, int verbose); int set_keylog_file(SSL_CTX *ctx, const char *keylog_file); void print_ca_names(BIO *bio, SSL *s); void ssl_print_secure_renegotiation_notes(BIO *bio, SSL *s); #ifndef OPENSSL_NO_SRP /* The client side SRP context that we pass to all SRP related callbacks */ typedef struct srp_arg_st { char *srppassin; char *srplogin; int msg; /* copy from c_msg */ int debug; /* copy from c_debug */ int amp; /* allow more groups */ int strength; /* minimal size for N */ } SRP_ARG; int set_up_srp_arg(SSL_CTX *ctx, SRP_ARG *srp_arg, int srp_lateuser, int c_msg, int c_debug); void set_up_dummy_srp(SSL_CTX *ctx); /* The server side SRP context that we pass to all SRP related callbacks */ typedef struct srpsrvparm_st { char *login; SRP_VBASE *vb; SRP_user_pwd *user; } srpsrvparm; int set_up_srp_verifier_file(SSL_CTX *ctx, srpsrvparm *srp_callback_parm, char *srpuserseed, char *srp_verifier_file); void lookup_srp_user(srpsrvparm *srp_callback_parm, BIO *bio_s_out); #endif /* OPENSSL_NO_SRP */
./openssl/apps/lib/apps_opt_printf.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 "opt.h" #include <openssl/ui.h> #include "apps_ui.h" /* This function is defined here due to visibility of bio_err */ int opt_printf_stderr(const char *fmt, ...) { va_list ap; int ret; va_start(ap, fmt); ret = BIO_vprintf(bio_err, fmt, ap); va_end(ap); return ret; }
./openssl/apps/lib/tlssrp_depr.c
/* * Copyright 1995-2023 The OpenSSL Project Authors. All Rights Reserved. * Copyright 2005 Nokia. 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 file is to enable backwards compatibility for the SRP features of * s_client, s_server and ciphers. All of those features are deprecated and will * eventually disappear. In the meantime, to continue to support them, we * need to access deprecated SRP APIs. */ #define OPENSSL_SUPPRESS_DEPRECATED #include <openssl/bn.h> #include <openssl/bio.h> #include <openssl/ssl.h> #include <openssl/srp.h> #include "apps_ui.h" #include "apps.h" #include "s_apps.h" static int srp_Verify_N_and_g(const BIGNUM *N, const BIGNUM *g) { BN_CTX *bn_ctx = BN_CTX_new(); BIGNUM *p = BN_new(); BIGNUM *r = BN_new(); int ret = g != NULL && N != NULL && bn_ctx != NULL && BN_is_odd(N) && BN_check_prime(N, bn_ctx, NULL) == 1 && p != NULL && BN_rshift1(p, N) && /* p = (N-1)/2 */ BN_check_prime(p, bn_ctx, NULL) == 1 && r != NULL && /* verify g^((N-1)/2) == -1 (mod N) */ BN_mod_exp(r, g, p, N, bn_ctx) && BN_add_word(r, 1) && BN_cmp(r, N) == 0; BN_free(r); BN_free(p); BN_CTX_free(bn_ctx); return ret; } /*- * This callback is used here for two purposes: * - extended debugging * - making some primality tests for unknown groups * The callback is only called for a non default group. * * An application does not need the call back at all if * only the standard groups are used. In real life situations, * client and server already share well known groups, * thus there is no need to verify them. * Furthermore, in case that a server actually proposes a group that * is not one of those defined in RFC 5054, it is more appropriate * to add the group to a static list and then compare since * primality tests are rather cpu consuming. */ static int ssl_srp_verify_param_cb(SSL *s, void *arg) { SRP_ARG *srp_arg = (SRP_ARG *)arg; BIGNUM *N = NULL, *g = NULL; if (((N = SSL_get_srp_N(s)) == NULL) || ((g = SSL_get_srp_g(s)) == NULL)) return 0; if (srp_arg->debug || srp_arg->msg || srp_arg->amp == 1) { BIO_printf(bio_err, "SRP parameters:\n"); BIO_printf(bio_err, "\tN="); BN_print(bio_err, N); BIO_printf(bio_err, "\n\tg="); BN_print(bio_err, g); BIO_printf(bio_err, "\n"); } if (SRP_check_known_gN_param(g, N)) return 1; if (srp_arg->amp == 1) { if (srp_arg->debug) BIO_printf(bio_err, "SRP param N and g are not known params, going to check deeper.\n"); /* * The srp_moregroups is a real debugging feature. Implementers * should rather add the value to the known ones. The minimal size * has already been tested. */ if (BN_num_bits(g) <= BN_BITS && srp_Verify_N_and_g(N, g)) return 1; } BIO_printf(bio_err, "SRP param N and g rejected.\n"); return 0; } #define PWD_STRLEN 1024 static char *ssl_give_srp_client_pwd_cb(SSL *s, void *arg) { SRP_ARG *srp_arg = (SRP_ARG *)arg; char *pass = app_malloc(PWD_STRLEN + 1, "SRP password buffer"); PW_CB_DATA cb_tmp; int l; cb_tmp.password = (char *)srp_arg->srppassin; cb_tmp.prompt_info = "SRP user"; if ((l = password_callback(pass, PWD_STRLEN, 0, &cb_tmp)) < 0) { BIO_printf(bio_err, "Can't read Password\n"); OPENSSL_free(pass); return NULL; } *(pass + l) = '\0'; return pass; } int set_up_srp_arg(SSL_CTX *ctx, SRP_ARG *srp_arg, int srp_lateuser, int c_msg, int c_debug) { if (!srp_lateuser && !SSL_CTX_set_srp_username(ctx, srp_arg->srplogin)) { BIO_printf(bio_err, "Unable to set SRP username\n"); return 0; } srp_arg->msg = c_msg; srp_arg->debug = c_debug; SSL_CTX_set_srp_cb_arg(ctx, &srp_arg); SSL_CTX_set_srp_client_pwd_callback(ctx, ssl_give_srp_client_pwd_cb); SSL_CTX_set_srp_strength(ctx, srp_arg->strength); if (c_msg || c_debug || srp_arg->amp == 0) SSL_CTX_set_srp_verify_param_callback(ctx, ssl_srp_verify_param_cb); return 1; } static char *dummy_srp(SSL *ssl, void *arg) { return ""; } void set_up_dummy_srp(SSL_CTX *ctx) { SSL_CTX_set_srp_client_pwd_callback(ctx, dummy_srp); } /* * This callback pretends to require some asynchronous logic in order to * obtain a verifier. When the callback is called for a new connection we * return with a negative value. This will provoke the accept etc to return * with an LOOKUP_X509. The main logic of the reinvokes the suspended call * (which would normally occur after a worker has finished) and we set the * user parameters. */ static int ssl_srp_server_param_cb(SSL *s, int *ad, void *arg) { srpsrvparm *p = (srpsrvparm *) arg; int ret = SSL3_AL_FATAL; if (p->login == NULL && p->user == NULL) { p->login = SSL_get_srp_username(s); BIO_printf(bio_err, "SRP username = \"%s\"\n", p->login); return -1; } if (p->user == NULL) { BIO_printf(bio_err, "User %s doesn't exist\n", p->login); goto err; } if (SSL_set_srp_server_param (s, p->user->N, p->user->g, p->user->s, p->user->v, p->user->info) < 0) { *ad = SSL_AD_INTERNAL_ERROR; goto err; } BIO_printf(bio_err, "SRP parameters set: username = \"%s\" info=\"%s\" \n", p->login, p->user->info); ret = SSL_ERROR_NONE; err: SRP_user_pwd_free(p->user); p->user = NULL; p->login = NULL; return ret; } int set_up_srp_verifier_file(SSL_CTX *ctx, srpsrvparm *srp_callback_parm, char *srpuserseed, char *srp_verifier_file) { int ret; srp_callback_parm->vb = SRP_VBASE_new(srpuserseed); srp_callback_parm->user = NULL; srp_callback_parm->login = NULL; if (srp_callback_parm->vb == NULL) { BIO_printf(bio_err, "Failed to initialize SRP verifier file \n"); return 0; } if ((ret = SRP_VBASE_init(srp_callback_parm->vb, srp_verifier_file)) != SRP_NO_ERROR) { BIO_printf(bio_err, "Cannot initialize SRP verifier file \"%s\":ret=%d\n", srp_verifier_file, ret); return 0; } SSL_CTX_set_verify(ctx, SSL_VERIFY_NONE, verify_callback); SSL_CTX_set_srp_cb_arg(ctx, &srp_callback_parm); SSL_CTX_set_srp_username_callback(ctx, ssl_srp_server_param_cb); return 1; } void lookup_srp_user(srpsrvparm *srp_callback_parm, BIO *bio_s_out) { SRP_user_pwd_free(srp_callback_parm->user); srp_callback_parm->user = SRP_VBASE_get1_by_user(srp_callback_parm->vb, srp_callback_parm->login); if (srp_callback_parm->user != NULL) BIO_printf(bio_s_out, "LOOKUP done %s\n", srp_callback_parm->user->info); else BIO_printf(bio_s_out, "LOOKUP not successful\n"); }
./openssl/apps/lib/cmp_mock_srv.c
/* * Copyright 2018-2023 The OpenSSL Project Authors. All Rights Reserved. * Copyright Siemens AG 2018-2020 * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or atf * https://www.openssl.org/source/license.html */ #include "apps.h" #include "cmp_mock_srv.h" #include <openssl/cmp.h> #include <openssl/err.h> #include <openssl/cmperr.h> /* the context for the CMP mock server */ typedef struct { X509 *refCert; /* cert to expect for oldCertID in kur/rr msg */ X509 *certOut; /* certificate to be returned in cp/ip/kup msg */ STACK_OF(X509) *chainOut; /* chain of certOut to add to extraCerts field */ STACK_OF(X509) *caPubsOut; /* used in caPubs of ip and in caCerts of genp */ X509 *newWithNew; /* to return in newWithNew of rootKeyUpdate */ X509 *newWithOld; /* to return in newWithOld of rootKeyUpdate */ X509 *oldWithNew; /* to return in oldWithNew of rootKeyUpdate */ OSSL_CMP_PKISI *statusOut; /* status for ip/cp/kup/rp msg unless polling */ int sendError; /* send error response on given request type */ OSSL_CMP_MSG *req; /* original request message during polling */ int pollCount; /* number of polls before actual cert response */ int curr_pollCount; /* number of polls so far for current request */ int checkAfterTime; /* time the client should wait between polling */ } mock_srv_ctx; static void mock_srv_ctx_free(mock_srv_ctx *ctx) { if (ctx == NULL) return; OSSL_CMP_PKISI_free(ctx->statusOut); X509_free(ctx->refCert); X509_free(ctx->certOut); OSSL_STACK_OF_X509_free(ctx->chainOut); OSSL_STACK_OF_X509_free(ctx->caPubsOut); OSSL_CMP_MSG_free(ctx->req); OPENSSL_free(ctx); } static mock_srv_ctx *mock_srv_ctx_new(void) { mock_srv_ctx *ctx = OPENSSL_zalloc(sizeof(mock_srv_ctx)); if (ctx == NULL) goto err; if ((ctx->statusOut = OSSL_CMP_PKISI_new()) == NULL) goto err; ctx->sendError = -1; /* all other elements are initialized to 0 or NULL, respectively */ return ctx; err: mock_srv_ctx_free(ctx); return NULL; } #define DEFINE_OSSL_SET1_CERT(FIELD) \ int ossl_cmp_mock_srv_set1_##FIELD(OSSL_CMP_SRV_CTX *srv_ctx, \ X509 *cert) \ { \ mock_srv_ctx *ctx = OSSL_CMP_SRV_CTX_get0_custom_ctx(srv_ctx); \ \ if (ctx == NULL) { \ ERR_raise(ERR_LIB_CMP, CMP_R_NULL_ARGUMENT); \ return 0; \ } \ if (cert == NULL || X509_up_ref(cert)) { \ X509_free(ctx->FIELD); \ ctx->FIELD = cert; \ return 1; \ } \ return 0; \ } DEFINE_OSSL_SET1_CERT(refCert) DEFINE_OSSL_SET1_CERT(certOut) int ossl_cmp_mock_srv_set1_chainOut(OSSL_CMP_SRV_CTX *srv_ctx, STACK_OF(X509) *chain) { mock_srv_ctx *ctx = OSSL_CMP_SRV_CTX_get0_custom_ctx(srv_ctx); STACK_OF(X509) *chain_copy = NULL; if (ctx == NULL) { ERR_raise(ERR_LIB_CMP, CMP_R_NULL_ARGUMENT); return 0; } if (chain != NULL && (chain_copy = X509_chain_up_ref(chain)) == NULL) return 0; OSSL_STACK_OF_X509_free(ctx->chainOut); ctx->chainOut = chain_copy; return 1; } int ossl_cmp_mock_srv_set1_caPubsOut(OSSL_CMP_SRV_CTX *srv_ctx, STACK_OF(X509) *caPubs) { mock_srv_ctx *ctx = OSSL_CMP_SRV_CTX_get0_custom_ctx(srv_ctx); STACK_OF(X509) *caPubs_copy = NULL; if (ctx == NULL) { ERR_raise(ERR_LIB_CMP, CMP_R_NULL_ARGUMENT); return 0; } if (caPubs != NULL && (caPubs_copy = X509_chain_up_ref(caPubs)) == NULL) return 0; OSSL_STACK_OF_X509_free(ctx->caPubsOut); ctx->caPubsOut = caPubs_copy; return 1; } DEFINE_OSSL_SET1_CERT(newWithNew) DEFINE_OSSL_SET1_CERT(newWithOld) DEFINE_OSSL_SET1_CERT(oldWithNew) int ossl_cmp_mock_srv_set_statusInfo(OSSL_CMP_SRV_CTX *srv_ctx, int status, int fail_info, const char *text) { mock_srv_ctx *ctx = OSSL_CMP_SRV_CTX_get0_custom_ctx(srv_ctx); OSSL_CMP_PKISI *si; if (ctx == NULL) { ERR_raise(ERR_LIB_CMP, CMP_R_NULL_ARGUMENT); return 0; } if ((si = OSSL_CMP_STATUSINFO_new(status, fail_info, text)) == NULL) return 0; OSSL_CMP_PKISI_free(ctx->statusOut); ctx->statusOut = si; return 1; } int ossl_cmp_mock_srv_set_sendError(OSSL_CMP_SRV_CTX *srv_ctx, int bodytype) { mock_srv_ctx *ctx = OSSL_CMP_SRV_CTX_get0_custom_ctx(srv_ctx); if (ctx == NULL) { ERR_raise(ERR_LIB_CMP, CMP_R_NULL_ARGUMENT); return 0; } /* might check bodytype, but this would require exporting all body types */ ctx->sendError = bodytype; return 1; } int ossl_cmp_mock_srv_set_pollCount(OSSL_CMP_SRV_CTX *srv_ctx, int count) { mock_srv_ctx *ctx = OSSL_CMP_SRV_CTX_get0_custom_ctx(srv_ctx); if (ctx == NULL) { ERR_raise(ERR_LIB_CMP, CMP_R_NULL_ARGUMENT); return 0; } if (count < 0) { ERR_raise(ERR_LIB_CMP, CMP_R_INVALID_ARGS); return 0; } ctx->pollCount = count; return 1; } int ossl_cmp_mock_srv_set_checkAfterTime(OSSL_CMP_SRV_CTX *srv_ctx, int sec) { mock_srv_ctx *ctx = OSSL_CMP_SRV_CTX_get0_custom_ctx(srv_ctx); if (ctx == NULL) { ERR_raise(ERR_LIB_CMP, CMP_R_NULL_ARGUMENT); return 0; } ctx->checkAfterTime = sec; return 1; } /* determine whether to delay response to (non-polling) request */ static int delayed_delivery(OSSL_CMP_SRV_CTX *srv_ctx, const OSSL_CMP_MSG *req) { mock_srv_ctx *ctx = OSSL_CMP_SRV_CTX_get0_custom_ctx(srv_ctx); int req_type = OSSL_CMP_MSG_get_bodytype(req); if (ctx == NULL || req == NULL) { ERR_raise(ERR_LIB_CMP, CMP_R_NULL_ARGUMENT); return -1; } /* * For ir/cr/p10cr/kur delayed delivery is handled separately in * process_cert_request */ if (req_type == OSSL_CMP_IR || req_type == OSSL_CMP_CR || req_type == OSSL_CMP_P10CR || req_type == OSSL_CMP_KUR /* Client may use error to abort the ongoing polling */ || req_type == OSSL_CMP_ERROR) return 0; if (ctx->pollCount > 0 && ctx->curr_pollCount == 0) { /* start polling */ if ((ctx->req = OSSL_CMP_MSG_dup(req)) == NULL) return -1; return 1; } return 0; } /* check for matching reference cert components, as far as given */ static int refcert_cmp(const X509 *refcert, const X509_NAME *issuer, const ASN1_INTEGER *serial) { const X509_NAME *ref_issuer; const ASN1_INTEGER *ref_serial; if (refcert == NULL) return 1; ref_issuer = X509_get_issuer_name(refcert); ref_serial = X509_get0_serialNumber(refcert); return (ref_issuer == NULL || X509_NAME_cmp(issuer, ref_issuer) == 0) && (ref_serial == NULL || ASN1_INTEGER_cmp(serial, ref_serial) == 0); } /* reset the state that belongs to a transaction */ static int clean_transaction(OSSL_CMP_SRV_CTX *srv_ctx, ossl_unused const ASN1_OCTET_STRING *id) { mock_srv_ctx *ctx = OSSL_CMP_SRV_CTX_get0_custom_ctx(srv_ctx); if (ctx == NULL) { ERR_raise(ERR_LIB_CMP, CMP_R_NULL_ARGUMENT); return 0; } ctx->curr_pollCount = 0; OSSL_CMP_MSG_free(ctx->req); ctx->req = NULL; return 1; } static OSSL_CMP_PKISI *process_cert_request(OSSL_CMP_SRV_CTX *srv_ctx, const OSSL_CMP_MSG *cert_req, ossl_unused int certReqId, const OSSL_CRMF_MSG *crm, const X509_REQ *p10cr, X509 **certOut, STACK_OF(X509) **chainOut, STACK_OF(X509) **caPubs) { mock_srv_ctx *ctx = OSSL_CMP_SRV_CTX_get0_custom_ctx(srv_ctx); int bodytype; OSSL_CMP_PKISI *si = NULL; if (ctx == NULL || cert_req == NULL || certOut == NULL || chainOut == NULL || caPubs == NULL) { ERR_raise(ERR_LIB_CMP, CMP_R_NULL_ARGUMENT); return NULL; } bodytype = OSSL_CMP_MSG_get_bodytype(cert_req); if (ctx->sendError == 1 || ctx->sendError == bodytype) { ERR_raise(ERR_LIB_CMP, CMP_R_ERROR_PROCESSING_MESSAGE); return NULL; } *certOut = NULL; *chainOut = NULL; *caPubs = NULL; if (ctx->pollCount > 0 && ctx->curr_pollCount == 0) { /* start polling */ if ((ctx->req = OSSL_CMP_MSG_dup(cert_req)) == NULL) return NULL; return OSSL_CMP_STATUSINFO_new(OSSL_CMP_PKISTATUS_waiting, 0, NULL); } if (ctx->curr_pollCount >= ctx->pollCount) /* give final response after polling */ ctx->curr_pollCount = 0; /* accept cert profile for cr messages only with the configured name */ if (OSSL_CMP_MSG_get_bodytype(cert_req) == OSSL_CMP_CR) { STACK_OF(OSSL_CMP_ITAV) *itavs = OSSL_CMP_HDR_get0_geninfo_ITAVs(OSSL_CMP_MSG_get0_header(cert_req)); int i; for (i = 0; i < sk_OSSL_CMP_ITAV_num(itavs); i++) { OSSL_CMP_ITAV *itav = sk_OSSL_CMP_ITAV_value(itavs, i); ASN1_OBJECT *obj = OSSL_CMP_ITAV_get0_type(itav); STACK_OF(ASN1_UTF8STRING) *strs; ASN1_UTF8STRING *str; const char *data; if (OBJ_obj2nid(obj) == NID_id_it_certProfile) { if (!OSSL_CMP_ITAV_get0_certProfile(itav, &strs)) return NULL; if (sk_ASN1_UTF8STRING_num(strs) < 1) { ERR_raise(ERR_LIB_CMP, CMP_R_UNEXPECTED_CERTPROFILE); return NULL; } str = sk_ASN1_UTF8STRING_value(strs, 0); if (str == NULL || (data = (const char *)ASN1_STRING_get0_data(str)) == NULL) { ERR_raise(ERR_LIB_CMP, ERR_R_PASSED_INVALID_ARGUMENT); return NULL; } if (strcmp(data, "profile1") != 0) { ERR_raise(ERR_LIB_CMP, CMP_R_UNEXPECTED_CERTPROFILE); return NULL; } break; } } } /* accept cert update request only for the reference cert, if given */ if (bodytype == OSSL_CMP_KUR && crm != NULL /* thus not p10cr */ && ctx->refCert != NULL) { const OSSL_CRMF_CERTID *cid = OSSL_CRMF_MSG_get0_regCtrl_oldCertID(crm); if (cid == NULL) { ERR_raise(ERR_LIB_CMP, CMP_R_MISSING_CERTID); return NULL; } if (!refcert_cmp(ctx->refCert, OSSL_CRMF_CERTID_get0_issuer(cid), OSSL_CRMF_CERTID_get0_serialNumber(cid))) { ERR_raise(ERR_LIB_CMP, CMP_R_WRONG_CERTID); return NULL; } } if (ctx->certOut != NULL && (*certOut = X509_dup(ctx->certOut)) == NULL) /* Should return a cert produced from request template, see FR #16054 */ goto err; if (ctx->chainOut != NULL && (*chainOut = X509_chain_up_ref(ctx->chainOut)) == NULL) goto err; if (ctx->caPubsOut != NULL /* OSSL_CMP_PKIBODY_IP not visible here */ && (*caPubs = X509_chain_up_ref(ctx->caPubsOut)) == NULL) goto err; if (ctx->statusOut != NULL && (si = OSSL_CMP_PKISI_dup(ctx->statusOut)) == NULL) goto err; return si; err: X509_free(*certOut); *certOut = NULL; OSSL_STACK_OF_X509_free(*chainOut); *chainOut = NULL; OSSL_STACK_OF_X509_free(*caPubs); *caPubs = NULL; return NULL; } static OSSL_CMP_PKISI *process_rr(OSSL_CMP_SRV_CTX *srv_ctx, const OSSL_CMP_MSG *rr, const X509_NAME *issuer, const ASN1_INTEGER *serial) { mock_srv_ctx *ctx = OSSL_CMP_SRV_CTX_get0_custom_ctx(srv_ctx); if (ctx == NULL || rr == NULL) { ERR_raise(ERR_LIB_CMP, CMP_R_NULL_ARGUMENT); return NULL; } if (ctx->sendError == 1 || ctx->sendError == OSSL_CMP_MSG_get_bodytype(rr)) { ERR_raise(ERR_LIB_CMP, CMP_R_ERROR_PROCESSING_MESSAGE); return NULL; } /* allow any RR derived from CSR which does not include issuer and serial */ if ((issuer != NULL || serial != NULL) /* accept revocation only for the reference cert, if given */ && !refcert_cmp(ctx->refCert, issuer, serial)) { ERR_raise_data(ERR_LIB_CMP, CMP_R_REQUEST_NOT_ACCEPTED, "wrong certificate to revoke"); return NULL; } return OSSL_CMP_PKISI_dup(ctx->statusOut); } static OSSL_CMP_ITAV *process_genm_itav(mock_srv_ctx *ctx, int req_nid, const OSSL_CMP_ITAV *req) { OSSL_CMP_ITAV *rsp; switch (req_nid) { case NID_id_it_caCerts: rsp = OSSL_CMP_ITAV_new_caCerts(ctx->caPubsOut); break; case NID_id_it_rootCaCert: rsp = OSSL_CMP_ITAV_new_rootCaKeyUpdate(ctx->newWithNew, ctx->newWithOld, ctx->oldWithNew); break; default: rsp = OSSL_CMP_ITAV_dup(req); } return rsp; } static int process_genm(OSSL_CMP_SRV_CTX *srv_ctx, const OSSL_CMP_MSG *genm, const STACK_OF(OSSL_CMP_ITAV) *in, STACK_OF(OSSL_CMP_ITAV) **out) { mock_srv_ctx *ctx = OSSL_CMP_SRV_CTX_get0_custom_ctx(srv_ctx); if (ctx == NULL || genm == NULL || in == NULL || out == NULL) { ERR_raise(ERR_LIB_CMP, CMP_R_NULL_ARGUMENT); return 0; } if (ctx->sendError == 1 || ctx->sendError == OSSL_CMP_MSG_get_bodytype(genm) || sk_OSSL_CMP_ITAV_num(in) > 1) { ERR_raise(ERR_LIB_CMP, CMP_R_ERROR_PROCESSING_MESSAGE); return 0; } if (sk_OSSL_CMP_ITAV_num(in) == 1) { OSSL_CMP_ITAV *req = sk_OSSL_CMP_ITAV_value(in, 0), *rsp; ASN1_OBJECT *obj = OSSL_CMP_ITAV_get0_type(req); if ((*out = sk_OSSL_CMP_ITAV_new_reserve(NULL, 1)) == NULL) return 0; rsp = process_genm_itav(ctx, OBJ_obj2nid(obj), req); if (rsp != NULL && sk_OSSL_CMP_ITAV_push(*out, rsp)) return 1; sk_OSSL_CMP_ITAV_free(*out); return 0; } *out = sk_OSSL_CMP_ITAV_deep_copy(in, OSSL_CMP_ITAV_dup, OSSL_CMP_ITAV_free); return *out != NULL; } static void process_error(OSSL_CMP_SRV_CTX *srv_ctx, const OSSL_CMP_MSG *error, const OSSL_CMP_PKISI *statusInfo, const ASN1_INTEGER *errorCode, const OSSL_CMP_PKIFREETEXT *errorDetails) { mock_srv_ctx *ctx = OSSL_CMP_SRV_CTX_get0_custom_ctx(srv_ctx); char buf[OSSL_CMP_PKISI_BUFLEN]; char *sibuf; int i; if (ctx == NULL || error == NULL) { ERR_raise(ERR_LIB_CMP, CMP_R_NULL_ARGUMENT); return; } BIO_printf(bio_err, "mock server received error:\n"); if (statusInfo == NULL) { BIO_printf(bio_err, "pkiStatusInfo absent\n"); } else { sibuf = OSSL_CMP_snprint_PKIStatusInfo(statusInfo, buf, sizeof(buf)); BIO_printf(bio_err, "pkiStatusInfo: %s\n", sibuf != NULL ? sibuf: "<invalid>"); } if (errorCode == NULL) BIO_printf(bio_err, "errorCode absent\n"); else BIO_printf(bio_err, "errorCode: %ld\n", ASN1_INTEGER_get(errorCode)); if (sk_ASN1_UTF8STRING_num(errorDetails) <= 0) { BIO_printf(bio_err, "errorDetails absent\n"); } else { BIO_printf(bio_err, "errorDetails: "); for (i = 0; i < sk_ASN1_UTF8STRING_num(errorDetails); i++) { if (i > 0) BIO_printf(bio_err, ", "); ASN1_STRING_print_ex(bio_err, sk_ASN1_UTF8STRING_value(errorDetails, i), ASN1_STRFLGS_ESC_QUOTE); } BIO_printf(bio_err, "\n"); } } static int process_certConf(OSSL_CMP_SRV_CTX *srv_ctx, const OSSL_CMP_MSG *certConf, ossl_unused int certReqId, const ASN1_OCTET_STRING *certHash, const OSSL_CMP_PKISI *si) { mock_srv_ctx *ctx = OSSL_CMP_SRV_CTX_get0_custom_ctx(srv_ctx); ASN1_OCTET_STRING *digest; if (ctx == NULL || certConf == NULL || certHash == NULL) { ERR_raise(ERR_LIB_CMP, CMP_R_NULL_ARGUMENT); return 0; } if (ctx->sendError == 1 || ctx->sendError == OSSL_CMP_MSG_get_bodytype(certConf) || ctx->certOut == NULL) { ERR_raise(ERR_LIB_CMP, CMP_R_ERROR_PROCESSING_MESSAGE); return 0; } if ((digest = X509_digest_sig(ctx->certOut, NULL, NULL)) == NULL) return 0; if (ASN1_OCTET_STRING_cmp(certHash, digest) != 0) { ASN1_OCTET_STRING_free(digest); ERR_raise(ERR_LIB_CMP, CMP_R_CERTHASH_UNMATCHED); return 0; } ASN1_OCTET_STRING_free(digest); return 1; } /* return 0 on failure, 1 on success, setting *req or otherwise *check_after */ static int process_pollReq(OSSL_CMP_SRV_CTX *srv_ctx, const OSSL_CMP_MSG *pollReq, ossl_unused int certReqId, OSSL_CMP_MSG **req, int64_t *check_after) { mock_srv_ctx *ctx = OSSL_CMP_SRV_CTX_get0_custom_ctx(srv_ctx); if (req != NULL) *req = NULL; if (ctx == NULL || pollReq == NULL || req == NULL || check_after == NULL) { ERR_raise(ERR_LIB_CMP, CMP_R_NULL_ARGUMENT); return 0; } if (ctx->sendError == 1 || ctx->sendError == OSSL_CMP_MSG_get_bodytype(pollReq)) { ERR_raise(ERR_LIB_CMP, CMP_R_ERROR_PROCESSING_MESSAGE); return 0; } if (ctx->req == NULL) { /* not currently in polling mode */ ERR_raise(ERR_LIB_CMP, CMP_R_UNEXPECTED_POLLREQ); return 0; } if (++ctx->curr_pollCount >= ctx->pollCount) { /* end polling */ *req = ctx->req; ctx->req = NULL; *check_after = 0; } else { *check_after = ctx->checkAfterTime; } return 1; } OSSL_CMP_SRV_CTX *ossl_cmp_mock_srv_new(OSSL_LIB_CTX *libctx, const char *propq) { OSSL_CMP_SRV_CTX *srv_ctx = OSSL_CMP_SRV_CTX_new(libctx, propq); mock_srv_ctx *ctx = mock_srv_ctx_new(); if (srv_ctx != NULL && ctx != NULL && OSSL_CMP_SRV_CTX_init(srv_ctx, ctx, process_cert_request, process_rr, process_genm, process_error, process_certConf, process_pollReq) && OSSL_CMP_SRV_CTX_init_trans(srv_ctx, delayed_delivery, clean_transaction)) return srv_ctx; mock_srv_ctx_free(ctx); OSSL_CMP_SRV_CTX_free(srv_ctx); return NULL; } void ossl_cmp_mock_srv_free(OSSL_CMP_SRV_CTX *srv_ctx) { if (srv_ctx != NULL) mock_srv_ctx_free(OSSL_CMP_SRV_CTX_get0_custom_ctx(srv_ctx)); OSSL_CMP_SRV_CTX_free(srv_ctx); }
./openssl/apps/lib/engine.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 */ /* * Here is a set of wrappers for the ENGINE API, which are no-ops when the * ENGINE API is disabled / removed. * We need to suppress deprecation warnings to make this work. */ #define OPENSSL_SUPPRESS_DEPRECATED #include <string.h> /* strcmp */ #include <openssl/types.h> /* Ensure we have the ENGINE type, regardless */ #include <openssl/err.h> #ifndef OPENSSL_NO_ENGINE # include <openssl/engine.h> #endif #include "apps.h" #ifndef OPENSSL_NO_ENGINE /* Try to load an engine in a shareable library */ static ENGINE *try_load_engine(const char *engine) { ENGINE *e = NULL; if ((e = ENGINE_by_id("dynamic")) != NULL) { if (!ENGINE_ctrl_cmd_string(e, "SO_PATH", engine, 0) || !ENGINE_ctrl_cmd_string(e, "LOAD", NULL, 0)) { ENGINE_free(e); e = NULL; } } return e; } #endif ENGINE *setup_engine_methods(const char *id, unsigned int methods, int debug) { ENGINE *e = NULL; #ifndef OPENSSL_NO_ENGINE if (id != NULL) { if (strcmp(id, "auto") == 0) { BIO_printf(bio_err, "Enabling auto ENGINE support\n"); ENGINE_register_all_complete(); return NULL; } if ((e = ENGINE_by_id(id)) == NULL && (e = try_load_engine(id)) == NULL) { BIO_printf(bio_err, "Invalid engine \"%s\"\n", id); ERR_print_errors(bio_err); return NULL; } if (debug) (void)ENGINE_ctrl(e, ENGINE_CTRL_SET_LOGSTREAM, 0, bio_err, 0); if (!ENGINE_ctrl_cmd(e, "SET_USER_INTERFACE", 0, (void *)get_ui_method(), 0, 1) || !ENGINE_set_default(e, methods)) { BIO_printf(bio_err, "Cannot use engine \"%s\"\n", ENGINE_get_id(e)); ERR_print_errors(bio_err); ENGINE_free(e); return NULL; } BIO_printf(bio_err, "Engine \"%s\" set.\n", ENGINE_get_id(e)); } #endif return e; } void release_engine(ENGINE *e) { #ifndef OPENSSL_NO_ENGINE /* Free our "structural" reference. */ ENGINE_free(e); #endif } int init_engine(ENGINE *e) { int rv = 1; #ifndef OPENSSL_NO_ENGINE rv = ENGINE_init(e); #endif return rv; } int finish_engine(ENGINE *e) { int rv = 1; #ifndef OPENSSL_NO_ENGINE rv = ENGINE_finish(e); #endif return rv; } char *make_engine_uri(ENGINE *e, const char *key_id, const char *desc) { char *new_uri = NULL; #ifndef OPENSSL_NO_ENGINE if (e == NULL) { BIO_printf(bio_err, "No engine specified for loading %s\n", desc); } else if (key_id == NULL) { BIO_printf(bio_err, "No engine key id specified for loading %s\n", desc); } else { const char *engineid = ENGINE_get_id(e); size_t uri_sz = sizeof(ENGINE_SCHEME_COLON) - 1 + strlen(engineid) + 1 /* : */ + strlen(key_id) + 1 /* \0 */ ; new_uri = OPENSSL_malloc(uri_sz); if (new_uri != NULL) { OPENSSL_strlcpy(new_uri, ENGINE_SCHEME_COLON, uri_sz); OPENSSL_strlcat(new_uri, engineid, uri_sz); OPENSSL_strlcat(new_uri, ":", uri_sz); OPENSSL_strlcat(new_uri, key_id, uri_sz); } } #else BIO_printf(bio_err, "Engines not supported for loading %s\n", desc); #endif return new_uri; } int get_legacy_pkey_id(OSSL_LIB_CTX *libctx, const char *algname, ENGINE *e) { const EVP_PKEY_ASN1_METHOD *ameth; ENGINE *tmpeng = NULL; int pkey_id = NID_undef; ERR_set_mark(); ameth = EVP_PKEY_asn1_find_str(&tmpeng, algname, -1); #if !defined(OPENSSL_NO_ENGINE) ENGINE_finish(tmpeng); if (ameth == NULL && e != NULL) ameth = ENGINE_get_pkey_asn1_meth_str(e, algname, -1); else #endif /* We're only interested if it comes from an ENGINE */ if (tmpeng == NULL) ameth = NULL; ERR_pop_to_mark(); if (ameth == NULL) return NID_undef; EVP_PKEY_asn1_get0_info(&pkey_id, NULL, NULL, NULL, NULL, ameth); return pkey_id; } const EVP_MD *get_digest_from_engine(const char *name) { #ifndef OPENSSL_NO_ENGINE ENGINE *eng; eng = ENGINE_get_digest_engine(OBJ_sn2nid(name)); if (eng != NULL) { ENGINE_finish(eng); return EVP_get_digestbyname(name); } #endif return NULL; } const EVP_CIPHER *get_cipher_from_engine(const char *name) { #ifndef OPENSSL_NO_ENGINE ENGINE *eng; eng = ENGINE_get_cipher_engine(OBJ_sn2nid(name)); if (eng != NULL) { ENGINE_finish(eng); return EVP_get_cipherbyname(name); } #endif return NULL; }
./openssl/apps/lib/engine_loader.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 */ /* * Here is an STORE loader for ENGINE backed keys. It relies on deprecated * functions, and therefore need to have deprecation warnings suppressed. * This file is not compiled at all in a '--api=3 no-deprecated' configuration. */ #define OPENSSL_SUPPRESS_DEPRECATED #include "apps.h" #ifndef OPENSSL_NO_ENGINE # include <stdarg.h> # include <string.h> # include <openssl/engine.h> # include <openssl/store.h> /* * Support for legacy private engine keys via the 'org.openssl.engine:' scheme * * org.openssl.engine:{engineid}:{keyid} * * Note: we ONLY support ENGINE_load_private_key() and ENGINE_load_public_key() * Note 2: This scheme has a precedent in code in PKIX-SSH. for exactly * this sort of purpose. */ /* Local definition of OSSL_STORE_LOADER_CTX */ struct ossl_store_loader_ctx_st { ENGINE *e; /* Structural reference */ char *keyid; int expected; int loaded; /* 0 = key not loaded yet, 1 = key loaded */ }; static OSSL_STORE_LOADER_CTX *OSSL_STORE_LOADER_CTX_new(ENGINE *e, char *keyid) { OSSL_STORE_LOADER_CTX *ctx = OPENSSL_zalloc(sizeof(*ctx)); if (ctx != NULL) { ctx->e = e; ctx->keyid = keyid; } return ctx; } static void OSSL_STORE_LOADER_CTX_free(OSSL_STORE_LOADER_CTX *ctx) { if (ctx != NULL) { ENGINE_free(ctx->e); OPENSSL_free(ctx->keyid); OPENSSL_free(ctx); } } static OSSL_STORE_LOADER_CTX *engine_open(const OSSL_STORE_LOADER *loader, const char *uri, const UI_METHOD *ui_method, void *ui_data) { const char *p = uri, *q; ENGINE *e = NULL; char *keyid = NULL; OSSL_STORE_LOADER_CTX *ctx = NULL; if (!CHECK_AND_SKIP_CASE_PREFIX(p, ENGINE_SCHEME_COLON)) return NULL; /* Look for engine ID */ q = strchr(p, ':'); if (q != NULL /* There is both an engine ID and a key ID */ && p[0] != ':' /* The engine ID is at least one character */ && q[1] != '\0') { /* The key ID is at least one character */ char engineid[256]; size_t engineid_l = q - p; strncpy(engineid, p, engineid_l); engineid[engineid_l] = '\0'; e = ENGINE_by_id(engineid); keyid = OPENSSL_strdup(q + 1); } if (e != NULL && keyid != NULL) ctx = OSSL_STORE_LOADER_CTX_new(e, keyid); if (ctx == NULL) { OPENSSL_free(keyid); ENGINE_free(e); } return ctx; } static int engine_expect(OSSL_STORE_LOADER_CTX *ctx, int expected) { if (expected == 0 || expected == OSSL_STORE_INFO_PUBKEY || expected == OSSL_STORE_INFO_PKEY) { ctx->expected = expected; return 1; } return 0; } static OSSL_STORE_INFO *engine_load(OSSL_STORE_LOADER_CTX *ctx, const UI_METHOD *ui_method, void *ui_data) { EVP_PKEY *pkey = NULL, *pubkey = NULL; OSSL_STORE_INFO *info = NULL; if (ctx->loaded == 0) { if (ENGINE_init(ctx->e)) { if (ctx->expected == 0 || ctx->expected == OSSL_STORE_INFO_PKEY) pkey = ENGINE_load_private_key(ctx->e, ctx->keyid, (UI_METHOD *)ui_method, ui_data); if ((pkey == NULL && ctx->expected == 0) || ctx->expected == OSSL_STORE_INFO_PUBKEY) pubkey = ENGINE_load_public_key(ctx->e, ctx->keyid, (UI_METHOD *)ui_method, ui_data); ENGINE_finish(ctx->e); } } ctx->loaded = 1; if (pubkey != NULL) info = OSSL_STORE_INFO_new_PUBKEY(pubkey); else if (pkey != NULL) info = OSSL_STORE_INFO_new_PKEY(pkey); if (info == NULL) { EVP_PKEY_free(pkey); EVP_PKEY_free(pubkey); } return info; } static int engine_eof(OSSL_STORE_LOADER_CTX *ctx) { return ctx->loaded != 0; } static int engine_error(OSSL_STORE_LOADER_CTX *ctx) { return 0; } static int engine_close(OSSL_STORE_LOADER_CTX *ctx) { OSSL_STORE_LOADER_CTX_free(ctx); return 1; } int setup_engine_loader(void) { OSSL_STORE_LOADER *loader = NULL; if ((loader = OSSL_STORE_LOADER_new(NULL, ENGINE_SCHEME)) == NULL || !OSSL_STORE_LOADER_set_open(loader, engine_open) || !OSSL_STORE_LOADER_set_expect(loader, engine_expect) || !OSSL_STORE_LOADER_set_load(loader, engine_load) || !OSSL_STORE_LOADER_set_eof(loader, engine_eof) || !OSSL_STORE_LOADER_set_error(loader, engine_error) || !OSSL_STORE_LOADER_set_close(loader, engine_close) || !OSSL_STORE_register_loader(loader)) { OSSL_STORE_LOADER_free(loader); loader = NULL; } return loader != NULL; } void destroy_engine_loader(void) { OSSL_STORE_LOADER *loader = OSSL_STORE_unregister_loader(ENGINE_SCHEME); OSSL_STORE_LOADER_free(loader); } #else /* !OPENSSL_NO_ENGINE */ int setup_engine_loader(void) { return 0; } void destroy_engine_loader(void) { } #endif
./openssl/apps/lib/vms_decc_argv.c
/* * Copyright 2015-2021 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <stdlib.h> #include <openssl/crypto.h> #include "platform.h" /* for copy_argv() */ char **newargv = NULL; static void cleanup_argv(void) { OPENSSL_free(newargv); newargv = NULL; } char **copy_argv(int *argc, char *argv[]) { /*- * The note below is for historical purpose. On VMS now we always * copy argv "safely." * * 2011-03-22 SMS. * If we have 32-bit pointers everywhere, then we're safe, and * we bypass this mess, as on non-VMS systems. * Problem 1: Compaq/HP C before V7.3 always used 32-bit * pointers for argv[]. * Fix 1: For a 32-bit argv[], when we're using 64-bit pointers * everywhere else, we always allocate and use a 64-bit * duplicate of argv[]. * Problem 2: Compaq/HP C V7.3 (Alpha, IA64) before ECO1 failed * to NULL-terminate a 64-bit argv[]. (As this was written, the * compiler ECO was available only on IA64.) * Fix 2: Unless advised not to (VMS_TRUST_ARGV), we test a * 64-bit argv[argc] for NULL, and, if necessary, use a * (properly) NULL-terminated (64-bit) duplicate of argv[]. * The same code is used in either case to duplicate argv[]. * Some of these decisions could be handled in preprocessing, * but the code tends to get even uglier, and the penalty for * deciding at compile- or run-time is tiny. */ int i, count = *argc; char **p = newargv; cleanup_argv(); /* * We purposefully use OPENSSL_malloc() rather than app_malloc() here, * to avoid symbol name clashes in test programs that would otherwise * get them when linking with all of libapps.a. * See comment in test/build.info. */ newargv = OPENSSL_malloc(sizeof(*newargv) * (count + 1)); if (newargv == NULL) return NULL; /* Register automatic cleanup on first use */ if (p == NULL) OPENSSL_atexit(cleanup_argv); for (i = 0; i < count; i++) newargv[i] = argv[i]; newargv[i] = NULL; *argc = i; return newargv; }
./openssl/apps/lib/names.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 <string.h> #include <openssl/bio.h> #include <openssl/safestack.h> #include "names.h" #include "internal/e_os.h" int name_cmp(const char * const *a, const char * const *b) { return OPENSSL_strcasecmp(*a, *b); } void collect_names(const char *name, void *vdata) { STACK_OF(OPENSSL_CSTRING) *names = vdata; sk_OPENSSL_CSTRING_push(names, name); } void print_names(BIO *out, STACK_OF(OPENSSL_CSTRING) *names) { int i = sk_OPENSSL_CSTRING_num(names); int j; sk_OPENSSL_CSTRING_sort(names); if (i > 1) BIO_printf(out, "{ "); for (j = 0; j < i; j++) { const char *name = sk_OPENSSL_CSTRING_value(names, j); if (j > 0) BIO_printf(out, ", "); BIO_printf(out, "%s", name); } if (i > 1) BIO_printf(out, " }"); }