1 /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
4 * This package is an SSL implementation written
5 * by Eric Young (eay@cryptsoft.com).
6 * The implementation was written so as to conform with Netscapes SSL.
8 * This library is free for commercial and non-commercial use as long as
9 * the following conditions are aheared to. The following conditions
10 * apply to all code found in this distribution, be it the RC4, RSA,
11 * lhash, DES, etc., code; not just the SSL code. The SSL documentation
12 * included with this distribution is covered by the same copyright terms
13 * except that the holder is Tim Hudson (tjh@cryptsoft.com).
15 * Copyright remains Eric Young's, and as such any Copyright notices in
16 * the code are not to be removed.
17 * If this package is used in a product, Eric Young should be given attribution
18 * as the author of the parts of the library used.
19 * This can be in the form of a textual message at program startup or
20 * in documentation (online or textual) provided with the package.
22 * Redistribution and use in source and binary forms, with or without
23 * modification, are permitted provided that the following conditions
25 * 1. Redistributions of source code must retain the copyright
26 * notice, this list of conditions and the following disclaimer.
27 * 2. Redistributions in binary form must reproduce the above copyright
28 * notice, this list of conditions and the following disclaimer in the
29 * documentation and/or other materials provided with the distribution.
30 * 3. All advertising materials mentioning features or use of this software
31 * must display the following acknowledgement:
32 * "This product includes cryptographic software written by
33 * Eric Young (eay@cryptsoft.com)"
34 * The word 'cryptographic' can be left out if the rouines from the library
35 * being used are not cryptographic related :-).
36 * 4. If you include any Windows specific code (or a derivative thereof) from
37 * the apps directory (application code) you must include an acknowledgement:
38 * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
40 * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
41 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
42 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
43 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
44 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
45 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
46 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
47 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
48 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
49 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
52 * The licence and distribution terms for any publically available version or
53 * derivative of this code cannot be changed. i.e. this code cannot simply be
54 * copied and put under another distribution licence
55 * [including the GNU Public Licence.]
57 /* ====================================================================
58 * Copyright (c) 1998-2006 The OpenSSL Project. All rights reserved.
60 * Redistribution and use in source and binary forms, with or without
61 * modification, are permitted provided that the following conditions
64 * 1. Redistributions of source code must retain the above copyright
65 * notice, this list of conditions and the following disclaimer.
67 * 2. Redistributions in binary form must reproduce the above copyright
68 * notice, this list of conditions and the following disclaimer in
69 * the documentation and/or other materials provided with the
72 * 3. All advertising materials mentioning features or use of this
73 * software must display the following acknowledgment:
74 * "This product includes software developed by the OpenSSL Project
75 * for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
77 * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
78 * endorse or promote products derived from this software without
79 * prior written permission. For written permission, please contact
80 * openssl-core@openssl.org.
82 * 5. Products derived from this software may not be called "OpenSSL"
83 * nor may "OpenSSL" appear in their names without prior written
84 * permission of the OpenSSL Project.
86 * 6. Redistributions of any form whatsoever must retain the following
88 * "This product includes software developed by the OpenSSL Project
89 * for use in the OpenSSL Toolkit (http://www.openssl.org/)"
91 * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
92 * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
93 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
94 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR
95 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
96 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
97 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
98 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
99 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
100 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
101 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
102 * OF THE POSSIBILITY OF SUCH DAMAGE.
103 * ====================================================================
105 * This product includes cryptographic software written by Eric Young
106 * (eay@cryptsoft.com). This product includes software written by Tim
107 * Hudson (tjh@cryptsoft.com).
111 /* callback functions used by s_client, s_server, and s_time */
114 #include <string.h> /* for memcpy() and strcmp() */
118 #include <openssl/err.h>
119 #include <openssl/rand.h>
120 #include <openssl/x509.h>
121 #include <openssl/ssl.h>
122 #include <openssl/bn.h>
123 #ifndef OPENSSL_NO_DH
124 # include <openssl/dh.h>
128 #define COOKIE_SECRET_LENGTH 16
130 int verify_depth = 0;
131 int verify_quiet = 0;
132 int verify_error = X509_V_OK;
133 int verify_return_error = 0;
134 #ifndef OPENSSL_NO_SOCK
135 static unsigned char cookie_secret[COOKIE_SECRET_LENGTH];
136 static int cookie_initialized = 0;
139 static const char *lookup(int val, const STRINT_PAIR* list, const char* def)
141 for ( ; list->name; ++list)
142 if (list->retval == val)
147 int verify_callback(int ok, X509_STORE_CTX *ctx)
152 err_cert = X509_STORE_CTX_get_current_cert(ctx);
153 err = X509_STORE_CTX_get_error(ctx);
154 depth = X509_STORE_CTX_get_error_depth(ctx);
156 if (!verify_quiet || !ok) {
157 BIO_printf(bio_err, "depth=%d ", depth);
159 X509_NAME_print_ex(bio_err,
160 X509_get_subject_name(err_cert),
162 BIO_puts(bio_err, "\n");
164 BIO_puts(bio_err, "<no cert>\n");
167 BIO_printf(bio_err, "verify error:num=%d:%s\n", err,
168 X509_verify_cert_error_string(err));
169 if (verify_depth >= depth) {
170 if (!verify_return_error)
175 verify_error = X509_V_ERR_CERT_CHAIN_TOO_LONG;
179 case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT:
180 BIO_puts(bio_err, "issuer= ");
181 X509_NAME_print_ex(bio_err, X509_get_issuer_name(err_cert),
183 BIO_puts(bio_err, "\n");
185 case X509_V_ERR_CERT_NOT_YET_VALID:
186 case X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD:
187 BIO_printf(bio_err, "notBefore=");
188 ASN1_TIME_print(bio_err, X509_get_notBefore(err_cert));
189 BIO_printf(bio_err, "\n");
191 case X509_V_ERR_CERT_HAS_EXPIRED:
192 case X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD:
193 BIO_printf(bio_err, "notAfter=");
194 ASN1_TIME_print(bio_err, X509_get_notAfter(err_cert));
195 BIO_printf(bio_err, "\n");
197 case X509_V_ERR_NO_EXPLICIT_POLICY:
202 if (err == X509_V_OK && ok == 2 && !verify_quiet)
204 if (ok && !verify_quiet)
205 BIO_printf(bio_err, "verify return:%d\n", ok);
209 int set_cert_stuff(SSL_CTX *ctx, char *cert_file, char *key_file)
211 if (cert_file != NULL) {
212 if (SSL_CTX_use_certificate_file(ctx, cert_file,
213 SSL_FILETYPE_PEM) <= 0) {
214 BIO_printf(bio_err, "unable to get certificate from '%s'\n",
216 ERR_print_errors(bio_err);
219 if (key_file == NULL)
220 key_file = cert_file;
221 if (SSL_CTX_use_PrivateKey_file(ctx, key_file, SSL_FILETYPE_PEM) <= 0) {
222 BIO_printf(bio_err, "unable to get private key from '%s'\n",
224 ERR_print_errors(bio_err);
229 * If we are using DSA, we can copy the parameters from the private
234 * Now we know that a key and cert have been set against the SSL
237 if (!SSL_CTX_check_private_key(ctx)) {
239 "Private key does not match the certificate public key\n");
246 int set_cert_key_stuff(SSL_CTX *ctx, X509 *cert, EVP_PKEY *key,
247 STACK_OF(X509) *chain, int build_chain)
249 int chflags = chain ? SSL_BUILD_CHAIN_FLAG_CHECK : 0;
252 if (SSL_CTX_use_certificate(ctx, cert) <= 0) {
253 BIO_printf(bio_err, "error setting certificate\n");
254 ERR_print_errors(bio_err);
258 if (SSL_CTX_use_PrivateKey(ctx, key) <= 0) {
259 BIO_printf(bio_err, "error setting private key\n");
260 ERR_print_errors(bio_err);
265 * Now we know that a key and cert have been set against the SSL context
267 if (!SSL_CTX_check_private_key(ctx)) {
269 "Private key does not match the certificate public key\n");
272 if (chain && !SSL_CTX_set1_chain(ctx, chain)) {
273 BIO_printf(bio_err, "error setting certificate chain\n");
274 ERR_print_errors(bio_err);
277 if (build_chain && !SSL_CTX_build_cert_chain(ctx, chflags)) {
278 BIO_printf(bio_err, "error building certificate chain\n");
279 ERR_print_errors(bio_err);
285 static STRINT_PAIR cert_type_list[] = {
286 {"RSA sign", TLS_CT_RSA_SIGN},
287 {"DSA sign", TLS_CT_DSS_SIGN},
288 {"RSA fixed DH", TLS_CT_RSA_FIXED_DH},
289 {"DSS fixed DH", TLS_CT_DSS_FIXED_DH},
290 {"ECDSA sign", TLS_CT_ECDSA_SIGN},
291 {"RSA fixed ECDH", TLS_CT_RSA_FIXED_ECDH},
292 {"ECDSA fixed ECDH", TLS_CT_ECDSA_FIXED_ECDH},
293 {"GOST01 Sign", TLS_CT_GOST01_SIGN},
297 static void ssl_print_client_cert_types(BIO *bio, SSL *s)
299 const unsigned char *p;
301 int cert_type_num = SSL_get0_certificate_types(s, &p);
304 BIO_puts(bio, "Client Certificate Types: ");
305 for (i = 0; i < cert_type_num; i++) {
306 unsigned char cert_type = p[i];
307 const char *cname = lookup((int)cert_type, cert_type_list, NULL);
312 BIO_puts(bio, cname);
314 BIO_printf(bio, "UNKNOWN (%d),", cert_type);
319 static int do_print_sigalgs(BIO *out, SSL *s, int shared)
322 client = SSL_is_server(s) ? 0 : 1;
324 nsig = SSL_get_shared_sigalgs(s, -1, NULL, NULL, NULL, NULL, NULL);
326 nsig = SSL_get_sigalgs(s, -1, NULL, NULL, NULL, NULL, NULL);
331 BIO_puts(out, "Shared ");
334 BIO_puts(out, "Requested ");
335 BIO_puts(out, "Signature Algorithms: ");
336 for (i = 0; i < nsig; i++) {
337 int hash_nid, sign_nid;
338 unsigned char rhash, rsign;
339 const char *sstr = NULL;
341 SSL_get_shared_sigalgs(s, i, &sign_nid, &hash_nid, NULL,
344 SSL_get_sigalgs(s, i, &sign_nid, &hash_nid, NULL, &rsign, &rhash);
347 if (sign_nid == EVP_PKEY_RSA)
349 else if (sign_nid == EVP_PKEY_DSA)
351 else if (sign_nid == EVP_PKEY_EC)
354 BIO_printf(out, "%s+", sstr);
356 BIO_printf(out, "0x%02X+", (int)rsign);
357 if (hash_nid != NID_undef)
358 BIO_printf(out, "%s", OBJ_nid2sn(hash_nid));
360 BIO_printf(out, "0x%02X", (int)rhash);
366 int ssl_print_sigalgs(BIO *out, SSL *s)
369 if (!SSL_is_server(s))
370 ssl_print_client_cert_types(out, s);
371 do_print_sigalgs(out, s, 0);
372 do_print_sigalgs(out, s, 1);
373 if (SSL_get_peer_signature_nid(s, &mdnid))
374 BIO_printf(out, "Peer signing digest: %s\n", OBJ_nid2sn(mdnid));
378 #ifndef OPENSSL_NO_EC
379 int ssl_print_point_formats(BIO *out, SSL *s)
382 const char *pformats;
383 nformats = SSL_get0_ec_point_formats(s, &pformats);
386 BIO_puts(out, "Supported Elliptic Curve Point Formats: ");
387 for (i = 0; i < nformats; i++, pformats++) {
391 case TLSEXT_ECPOINTFORMAT_uncompressed:
392 BIO_puts(out, "uncompressed");
395 case TLSEXT_ECPOINTFORMAT_ansiX962_compressed_prime:
396 BIO_puts(out, "ansiX962_compressed_prime");
399 case TLSEXT_ECPOINTFORMAT_ansiX962_compressed_char2:
400 BIO_puts(out, "ansiX962_compressed_char2");
404 BIO_printf(out, "unknown(%d)", (int)*pformats);
413 int ssl_print_curves(BIO *out, SSL *s, int noshared)
415 int i, ncurves, *curves, nid;
418 ncurves = SSL_get1_curves(s, NULL);
421 curves = app_malloc(ncurves * sizeof(int), "curves to print");
422 SSL_get1_curves(s, curves);
424 BIO_puts(out, "Supported Elliptic Curves: ");
425 for (i = 0; i < ncurves; i++) {
429 /* If unrecognised print out hex version */
430 if (nid & TLSEXT_nid_unknown)
431 BIO_printf(out, "0x%04X", nid & 0xFFFF);
433 /* Use NIST name for curve if it exists */
434 cname = EC_curve_nid2nist(nid);
436 cname = OBJ_nid2sn(nid);
437 BIO_printf(out, "%s", cname);
440 OPENSSL_free(curves);
445 BIO_puts(out, "\nShared Elliptic curves: ");
446 ncurves = SSL_get_shared_curve(s, -1);
447 for (i = 0; i < ncurves; i++) {
450 nid = SSL_get_shared_curve(s, i);
451 cname = EC_curve_nid2nist(nid);
453 cname = OBJ_nid2sn(nid);
454 BIO_printf(out, "%s", cname);
457 BIO_puts(out, "NONE");
462 int ssl_print_tmp_key(BIO *out, SSL *s)
465 if (!SSL_get_server_tmp_key(s, &key))
467 BIO_puts(out, "Server Temp Key: ");
468 switch (EVP_PKEY_id(key)) {
470 BIO_printf(out, "RSA, %d bits\n", EVP_PKEY_bits(key));
474 BIO_printf(out, "DH, %d bits\n", EVP_PKEY_bits(key));
476 #ifndef OPENSSL_NO_EC
479 EC_KEY *ec = EVP_PKEY_get1_EC_KEY(key);
482 nid = EC_GROUP_get_curve_name(EC_KEY_get0_group(ec));
484 cname = EC_curve_nid2nist(nid);
486 cname = OBJ_nid2sn(nid);
487 BIO_printf(out, "ECDH, %s, %d bits\n", cname, EVP_PKEY_bits(key));
495 long bio_dump_callback(BIO *bio, int cmd, const char *argp,
496 int argi, long argl, long ret)
500 out = (BIO *)BIO_get_callback_arg(bio);
504 if (cmd == (BIO_CB_READ | BIO_CB_RETURN)) {
505 BIO_printf(out, "read from %p [%p] (%lu bytes => %ld (0x%lX))\n",
506 (void *)bio, (void *)argp, (unsigned long)argi, ret, ret);
507 BIO_dump(out, argp, (int)ret);
509 } else if (cmd == (BIO_CB_WRITE | BIO_CB_RETURN)) {
510 BIO_printf(out, "write to %p [%p] (%lu bytes => %ld (0x%lX))\n",
511 (void *)bio, (void *)argp, (unsigned long)argi, ret, ret);
512 BIO_dump(out, argp, (int)ret);
517 void apps_ssl_info_callback(const SSL *s, int where, int ret)
522 w = where & ~SSL_ST_MASK;
524 if (w & SSL_ST_CONNECT)
526 else if (w & SSL_ST_ACCEPT)
531 if (where & SSL_CB_LOOP) {
532 BIO_printf(bio_err, "%s:%s\n", str, SSL_state_string_long(s));
533 } else if (where & SSL_CB_ALERT) {
534 str = (where & SSL_CB_READ) ? "read" : "write";
535 BIO_printf(bio_err, "SSL3 alert %s:%s:%s\n",
537 SSL_alert_type_string_long(ret),
538 SSL_alert_desc_string_long(ret));
539 } else if (where & SSL_CB_EXIT) {
541 BIO_printf(bio_err, "%s:failed in %s\n",
542 str, SSL_state_string_long(s));
544 BIO_printf(bio_err, "%s:error in %s\n",
545 str, SSL_state_string_long(s));
550 static STRINT_PAIR ssl_versions[] = {
551 {"SSL 3.0", SSL3_VERSION},
552 {"TLS 1.0", TLS1_VERSION},
553 {"TLS 1.1", TLS1_1_VERSION},
554 {"TLS 1.2", TLS1_2_VERSION},
555 {"DTLS 1.0", DTLS1_VERSION},
556 {"DTLS 1.0 (bad)", DTLS1_BAD_VER},
559 static STRINT_PAIR alert_types[] = {
560 {" close_notify", 0},
561 {" unexpected_message", 10},
562 {" bad_record_mac", 20},
563 {" decryption_failed", 21},
564 {" record_overflow", 22},
565 {" decompression_failure", 30},
566 {" handshake_failure", 40},
567 {" bad_certificate", 42},
568 {" unsupported_certificate", 43},
569 {" certificate_revoked", 44},
570 {" certificate_expired", 45},
571 {" certificate_unknown", 46},
572 {" illegal_parameter", 47},
574 {" access_denied", 49},
575 {" decode_error", 50},
576 {" decrypt_error", 51},
577 {" export_restriction", 60},
578 {" protocol_version", 70},
579 {" insufficient_security", 71},
580 {" internal_error", 80},
581 {" user_canceled", 90},
582 {" no_renegotiation", 100},
583 {" unsupported_extension", 110},
584 {" certificate_unobtainable", 111},
585 {" unrecognized_name", 112},
586 {" bad_certificate_status_response", 113},
587 {" bad_certificate_hash_value", 114},
588 {" unknown_psk_identity", 115},
592 static STRINT_PAIR handshakes[] = {
593 {", HelloRequest", 0},
594 {", ClientHello", 1},
595 {", ServerHello", 2},
596 {", HelloVerifyRequest", 3},
597 {", NewSessionTicket", 4},
598 {", Certificate", 11},
599 {", ServerKeyExchange", 12},
600 {", CertificateRequest", 13},
601 {", ServerHelloDone", 14},
602 {", CertificateVerify", 15},
603 {", ClientKeyExchange", 16},
605 {", CertificateUrl", 21},
606 {", CertificateStatus", 22},
607 {", SupplementalData", 23},
611 void msg_cb(int write_p, int version, int content_type, const void *buf,
612 size_t len, SSL *ssl, void *arg)
615 const char *str_write_p = write_p ? ">>>" : "<<<";
616 const char *str_version = lookup(version, ssl_versions, "???");
617 const char *str_content_type = "", *str_details1 = "", *str_details2 = "";
618 const unsigned char* bp = buf;
620 if (version == SSL3_VERSION ||
621 version == TLS1_VERSION ||
622 version == TLS1_1_VERSION ||
623 version == TLS1_2_VERSION ||
624 version == DTLS1_VERSION || version == DTLS1_BAD_VER) {
625 switch (content_type) {
627 str_content_type = "ChangeCipherSpec";
630 str_content_type = "Alert";
631 str_details1 = ", ???";
635 str_details1 = ", warning";
638 str_details1 = ", fatal";
641 str_details2 = lookup((int)bp[1], alert_types, " ???");
645 str_content_type = "Handshake";
646 str_details1 = "???";
648 str_details1 = lookup((int)bp[0], handshakes, "???");
651 str_content_type = "ApplicationData";
653 #ifndef OPENSSL_NO_HEARTBEATS
655 str_details1 = ", Heartbeat";
660 str_details1 = ", HeartbeatRequest";
663 str_details1 = ", HeartbeatResponse";
672 BIO_printf(bio, "%s %s%s [length %04lx]%s%s\n", str_write_p, str_version,
673 str_content_type, (unsigned long)len, str_details1,
679 BIO_printf(bio, " ");
681 for (i = 0; i < num; i++) {
682 if (i % 16 == 0 && i > 0)
683 BIO_printf(bio, "\n ");
684 BIO_printf(bio, " %02x", ((const unsigned char *)buf)[i]);
687 BIO_printf(bio, " ...");
688 BIO_printf(bio, "\n");
690 (void)BIO_flush(bio);
693 static STRINT_PAIR tlsext_types[] = {
694 {"server name", TLSEXT_TYPE_server_name},
695 {"max fragment length", TLSEXT_TYPE_max_fragment_length},
696 {"client certificate URL", TLSEXT_TYPE_client_certificate_url},
697 {"trusted CA keys", TLSEXT_TYPE_trusted_ca_keys},
698 {"truncated HMAC", TLSEXT_TYPE_truncated_hmac},
699 {"status request", TLSEXT_TYPE_status_request},
700 {"user mapping", TLSEXT_TYPE_user_mapping},
701 {"client authz", TLSEXT_TYPE_client_authz},
702 {"server authz", TLSEXT_TYPE_server_authz},
703 {"cert type", TLSEXT_TYPE_cert_type},
704 {"elliptic curves", TLSEXT_TYPE_elliptic_curves},
705 {"EC point formats", TLSEXT_TYPE_ec_point_formats},
706 {"SRP", TLSEXT_TYPE_srp},
707 {"signature algorithms", TLSEXT_TYPE_signature_algorithms},
708 {"use SRTP", TLSEXT_TYPE_use_srtp},
709 {"heartbeat", TLSEXT_TYPE_heartbeat},
710 {"session ticket", TLSEXT_TYPE_session_ticket},
711 {"renegotiation info", TLSEXT_TYPE_renegotiate},
712 {"signed certificate timestamps", TLSEXT_TYPE_signed_certificate_timestamp},
713 {"TLS padding", TLSEXT_TYPE_padding},
714 #ifdef TLSEXT_TYPE_next_proto_neg
715 {"next protocol", TLSEXT_TYPE_next_proto_neg},
717 #ifdef TLSEXT_TYPE_encrypt_then_mac
718 {"encrypt-then-mac", TLSEXT_TYPE_encrypt_then_mac},
720 #ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
721 {"application layer protocol negotiation",
722 TLSEXT_TYPE_application_layer_protocol_negotiation},
724 #ifdef TLSEXT_TYPE_extended_master_secret
725 {"extended master secret", TLSEXT_TYPE_extended_master_secret},
730 void tlsext_cb(SSL *s, int client_server, int type,
731 const unsigned char *data, int len, void *arg)
734 const char *extname = lookup(type, tlsext_types, "unknown");
736 BIO_printf(bio, "TLS %s extension \"%s\" (id=%d), len=%d\n",
737 client_server ? "server" : "client", extname, type, len);
738 BIO_dump(bio, (const char *)data, len);
739 (void)BIO_flush(bio);
742 #ifndef OPENSSL_NO_SOCK
743 int generate_cookie_callback(SSL *ssl, unsigned char *cookie,
744 unsigned int *cookie_len)
746 unsigned char *buffer;
749 BIO_ADDR *peer = NULL;
751 /* Initialize a random secret */
752 if (!cookie_initialized) {
753 if (RAND_bytes(cookie_secret, COOKIE_SECRET_LENGTH) <= 0) {
754 BIO_printf(bio_err, "error setting random cookie secret\n");
757 cookie_initialized = 1;
760 peer = BIO_ADDR_new();
762 BIO_printf(bio_err, "memory full\n");
766 /* Read peer information */
767 (void)BIO_dgram_get_peer(SSL_get_rbio(ssl), peer);
769 /* Create buffer with peer's address and port */
770 BIO_ADDR_rawaddress(peer, NULL, &length);
771 OPENSSL_assert(length != 0);
772 port = BIO_ADDR_rawport(peer);
773 length += sizeof(port);
774 buffer = app_malloc(length, "cookie generate buffer");
776 memcpy(buffer, &port, sizeof(port));
777 BIO_ADDR_rawaddress(peer, buffer + sizeof(port), NULL);
779 /* Calculate HMAC of buffer using the secret */
780 HMAC(EVP_sha1(), cookie_secret, COOKIE_SECRET_LENGTH,
781 buffer, length, cookie, cookie_len);
783 OPENSSL_free(buffer);
789 int verify_cookie_callback(SSL *ssl, const unsigned char *cookie,
790 unsigned int cookie_len)
792 unsigned char result[EVP_MAX_MD_SIZE];
793 unsigned int resultlength;
795 /* Note: we check cookie_initialized because if it's not,
796 * it cannot be valid */
797 if (cookie_initialized
798 && generate_cookie_callback(ssl, result, &resultlength)
799 && cookie_len == resultlength
800 && memcmp(result, cookie, resultlength) == 0)
808 * Example of extended certificate handling. Where the standard support of
809 * one certificate per algorithm is not sufficient an application can decide
810 * which certificate(s) to use at runtime based on whatever criteria it deems
814 /* Linked list of certificates, keys and chains */
815 struct ssl_excert_st {
817 const char *certfile;
820 const char *chainfile;
823 STACK_OF(X509) *chain;
825 struct ssl_excert_st *next, *prev;
828 static STRINT_PAIR chain_flags[] = {
829 {"Overall Validity", CERT_PKEY_VALID},
830 {"Sign with EE key", CERT_PKEY_SIGN},
831 {"EE signature", CERT_PKEY_EE_SIGNATURE},
832 {"CA signature", CERT_PKEY_CA_SIGNATURE},
833 {"EE key parameters", CERT_PKEY_EE_PARAM},
834 {"CA key parameters", CERT_PKEY_CA_PARAM},
835 {"Explicitly sign with EE key", CERT_PKEY_EXPLICIT_SIGN},
836 {"Issuer Name", CERT_PKEY_ISSUER_NAME},
837 {"Certificate Type", CERT_PKEY_CERT_TYPE},
841 static void print_chain_flags(SSL *s, int flags)
845 for (pp = chain_flags; pp->name; ++pp)
846 BIO_printf(bio_err, "\t%s: %s\n",
848 (flags & pp->retval) ? "OK" : "NOT OK");
849 BIO_printf(bio_err, "\tSuite B: ");
850 if (SSL_set_cert_flags(s, 0) & SSL_CERT_FLAG_SUITEB_128_LOS)
851 BIO_puts(bio_err, flags & CERT_PKEY_SUITEB ? "OK\n" : "NOT OK\n");
853 BIO_printf(bio_err, "not tested\n");
857 * Very basic selection callback: just use any certificate chain reported as
858 * valid. More sophisticated could prioritise according to local policy.
860 static int set_cert_cb(SSL *ssl, void *arg)
863 SSL_EXCERT *exc = arg;
864 #ifdef CERT_CB_TEST_RETRY
865 static int retry_cnt;
869 "Certificate callback retry test: count %d\n",
874 SSL_certs_clear(ssl);
880 * Go to end of list and traverse backwards since we prepend newer
881 * entries this retains the original order.
890 rv = SSL_check_chain(ssl, exc->cert, exc->key, exc->chain);
891 BIO_printf(bio_err, "Checking cert chain %d:\nSubject: ", i);
892 X509_NAME_print_ex(bio_err, X509_get_subject_name(exc->cert), 0,
894 BIO_puts(bio_err, "\n");
895 print_chain_flags(ssl, rv);
896 if (rv & CERT_PKEY_VALID) {
897 if (!SSL_use_certificate(ssl, exc->cert)
898 || !SSL_use_PrivateKey(ssl, exc->key)) {
902 * NB: we wouldn't normally do this as it is not efficient
903 * building chains on each connection better to cache the chain
906 if (exc->build_chain) {
907 if (!SSL_build_cert_chain(ssl, 0))
909 } else if (exc->chain)
910 SSL_set1_chain(ssl, exc->chain);
917 void ssl_ctx_set_excert(SSL_CTX *ctx, SSL_EXCERT *exc)
919 SSL_CTX_set_cert_cb(ctx, set_cert_cb, exc);
922 static int ssl_excert_prepend(SSL_EXCERT **pexc)
924 SSL_EXCERT *exc = app_malloc(sizeof(*exc), "prepend cert");
926 memset(exc, 0, sizeof(*exc));
932 exc->certform = exc->next->certform;
933 exc->keyform = exc->next->keyform;
934 exc->next->prev = exc;
936 exc->certform = FORMAT_PEM;
937 exc->keyform = FORMAT_PEM;
943 void ssl_excert_free(SSL_EXCERT *exc)
950 X509_free(exc->cert);
951 EVP_PKEY_free(exc->key);
952 sk_X509_pop_free(exc->chain, X509_free);
959 int load_excert(SSL_EXCERT **pexc)
961 SSL_EXCERT *exc = *pexc;
964 /* If nothing in list, free and set to NULL */
965 if (!exc->certfile && !exc->next) {
966 ssl_excert_free(exc);
970 for (; exc; exc = exc->next) {
971 if (!exc->certfile) {
972 BIO_printf(bio_err, "Missing filename\n");
975 exc->cert = load_cert(exc->certfile, exc->certform,
976 "Server Certificate");
980 exc->key = load_key(exc->keyfile, exc->keyform,
981 0, NULL, NULL, "Server Key");
983 exc->key = load_key(exc->certfile, exc->certform,
984 0, NULL, NULL, "Server Key");
988 if (exc->chainfile) {
989 if (!load_certs(exc->chainfile, &exc->chain, FORMAT_PEM, NULL,
997 enum range { OPT_X_ENUM };
999 int args_excert(int opt, SSL_EXCERT **pexc)
1001 SSL_EXCERT *exc = *pexc;
1003 assert(opt > OPT_X__FIRST);
1004 assert(opt < OPT_X__LAST);
1007 if (!ssl_excert_prepend(&exc)) {
1008 BIO_printf(bio_err, " %s: Error initialising xcert\n",
1015 switch ((enum range)opt) {
1020 if (exc->certfile && !ssl_excert_prepend(&exc)) {
1021 BIO_printf(bio_err, "%s: Error adding xcert\n", opt_getprog());
1024 exc->certfile = opt_arg();
1028 BIO_printf(bio_err, "%s: Key already specified\n", opt_getprog());
1031 exc->keyfile = opt_arg();
1034 if (exc->chainfile) {
1035 BIO_printf(bio_err, "%s: Chain already specified\n",
1039 exc->chainfile = opt_arg();
1041 case OPT_X_CHAIN_BUILD:
1042 exc->build_chain = 1;
1044 case OPT_X_CERTFORM:
1045 if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &exc->certform))
1049 if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &exc->keyform))
1056 ERR_print_errors(bio_err);
1057 ssl_excert_free(exc);
1062 static void print_raw_cipherlist(SSL *s)
1064 const unsigned char *rlist;
1065 static const unsigned char scsv_id[] = { 0, 0xFF };
1066 size_t i, rlistlen, num;
1067 if (!SSL_is_server(s))
1069 num = SSL_get0_raw_cipherlist(s, NULL);
1070 OPENSSL_assert(num == 2);
1071 rlistlen = SSL_get0_raw_cipherlist(s, &rlist);
1072 BIO_puts(bio_err, "Client cipher list: ");
1073 for (i = 0; i < rlistlen; i += num, rlist += num) {
1074 const SSL_CIPHER *c = SSL_CIPHER_find(s, rlist);
1076 BIO_puts(bio_err, ":");
1078 BIO_puts(bio_err, SSL_CIPHER_get_name(c));
1079 else if (!memcmp(rlist, scsv_id, num))
1080 BIO_puts(bio_err, "SCSV");
1083 BIO_puts(bio_err, "0x");
1084 for (j = 0; j < num; j++)
1085 BIO_printf(bio_err, "%02X", rlist[j]);
1088 BIO_puts(bio_err, "\n");
1092 * Hex encoder for TLSA RRdata, not ':' delimited.
1094 static char *hexencode(const unsigned char *data, size_t len)
1096 static const char *hex = "0123456789abcdef";
1099 size_t outlen = 2 * len + 1;
1100 int ilen = (int) outlen;
1102 if (outlen < len || ilen < 0 || outlen != (size_t)ilen) {
1103 BIO_printf(bio_err, "%s: %" PRIu64 "-byte buffer too large to hexencode\n",
1104 opt_getprog(), (uint64_t)len);
1107 cp = out = app_malloc(ilen, "TLSA hex data buffer");
1110 *cp++ = hex[(*data >> 4) & 0x0f];
1111 *cp++ = hex[*data++ & 0x0f];
1117 void print_verify_detail(SSL *s, BIO *bio)
1121 long verify_err = SSL_get_verify_result(s);
1123 if (verify_err == X509_V_OK) {
1124 const char *peername = SSL_get0_peername(s);
1126 BIO_printf(bio, "Verification: OK\n");
1127 if (peername != NULL)
1128 BIO_printf(bio, "Verified peername: %s\n", peername);
1130 const char *reason = X509_verify_cert_error_string(verify_err);
1132 BIO_printf(bio, "Verification error: %s\n", reason);
1135 if ((mdpth = SSL_get0_dane_authority(s, NULL, &mspki)) >= 0) {
1136 uint8_t usage, selector, mtype;
1137 const unsigned char *data = NULL;
1141 mdpth = SSL_get0_dane_tlsa(s, &usage, &selector, &mtype, &data, &dlen);
1144 * The TLSA data field can be quite long when it is a certificate,
1145 * public key or even a SHA2-512 digest. Because the initial octets of
1146 * ASN.1 certificates and public keys contain mostly boilerplate OIDs
1147 * and lengths, we show the last 12 bytes of the data instead, as these
1148 * are more likely to distinguish distinct TLSA records.
1150 #define TLSA_TAIL_SIZE 12
1151 if (dlen > TLSA_TAIL_SIZE)
1152 hexdata = hexencode(data + dlen - TLSA_TAIL_SIZE, TLSA_TAIL_SIZE);
1154 hexdata = hexencode(data, dlen);
1155 BIO_printf(bio, "DANE TLSA %d %d %d %s%s %s at depth %d\n",
1156 usage, selector, mtype,
1157 (dlen > TLSA_TAIL_SIZE) ? "..." : "", hexdata,
1158 (mspki != NULL) ? "signed the certificate" :
1159 mdpth ? "matched TA certificate" : "matched EE certificate",
1161 OPENSSL_free(hexdata);
1165 void print_ssl_summary(SSL *s)
1167 const SSL_CIPHER *c;
1169 /* const char *pnam = SSL_is_server(s) ? "client" : "server"; */
1171 BIO_printf(bio_err, "Protocol version: %s\n", SSL_get_version(s));
1172 print_raw_cipherlist(s);
1173 c = SSL_get_current_cipher(s);
1174 BIO_printf(bio_err, "Ciphersuite: %s\n", SSL_CIPHER_get_name(c));
1175 do_print_sigalgs(bio_err, s, 0);
1176 peer = SSL_get_peer_certificate(s);
1180 BIO_puts(bio_err, "Peer certificate: ");
1181 X509_NAME_print_ex(bio_err, X509_get_subject_name(peer),
1182 0, XN_FLAG_ONELINE);
1183 BIO_puts(bio_err, "\n");
1184 if (SSL_get_peer_signature_nid(s, &nid))
1185 BIO_printf(bio_err, "Hash used: %s\n", OBJ_nid2sn(nid));
1186 print_verify_detail(s, bio_err);
1188 BIO_puts(bio_err, "No peer certificate\n");
1190 #ifndef OPENSSL_NO_EC
1191 ssl_print_point_formats(bio_err, s);
1192 if (SSL_is_server(s))
1193 ssl_print_curves(bio_err, s, 1);
1195 ssl_print_tmp_key(bio_err, s);
1197 if (!SSL_is_server(s))
1198 ssl_print_tmp_key(bio_err, s);
1202 int config_ctx(SSL_CONF_CTX *cctx, STACK_OF(OPENSSL_STRING) *str,
1207 SSL_CONF_CTX_set_ssl_ctx(cctx, ctx);
1208 for (i = 0; i < sk_OPENSSL_STRING_num(str); i += 2) {
1209 const char *flag = sk_OPENSSL_STRING_value(str, i);
1210 const char *arg = sk_OPENSSL_STRING_value(str, i + 1);
1211 if (SSL_CONF_cmd(cctx, flag, arg) <= 0) {
1213 BIO_printf(bio_err, "Error with command: \"%s %s\"\n",
1216 BIO_printf(bio_err, "Error with command: \"%s\"\n", flag);
1217 ERR_print_errors(bio_err);
1221 if (!SSL_CONF_CTX_finish(cctx)) {
1222 BIO_puts(bio_err, "Error finishing context\n");
1223 ERR_print_errors(bio_err);
1229 static int add_crls_store(X509_STORE *st, STACK_OF(X509_CRL) *crls)
1233 for (i = 0; i < sk_X509_CRL_num(crls); i++) {
1234 crl = sk_X509_CRL_value(crls, i);
1235 X509_STORE_add_crl(st, crl);
1240 int ssl_ctx_add_crls(SSL_CTX *ctx, STACK_OF(X509_CRL) *crls, int crl_download)
1243 st = SSL_CTX_get_cert_store(ctx);
1244 add_crls_store(st, crls);
1246 store_setup_crl_download(st);
1250 int ssl_load_stores(SSL_CTX *ctx,
1251 const char *vfyCApath, const char *vfyCAfile,
1252 const char *chCApath, const char *chCAfile,
1253 STACK_OF(X509_CRL) *crls, int crl_download)
1255 X509_STORE *vfy = NULL, *ch = NULL;
1257 if (vfyCApath != NULL || vfyCAfile != NULL) {
1258 vfy = X509_STORE_new();
1261 if (!X509_STORE_load_locations(vfy, vfyCAfile, vfyCApath))
1263 add_crls_store(vfy, crls);
1264 SSL_CTX_set1_verify_cert_store(ctx, vfy);
1266 store_setup_crl_download(vfy);
1268 if (chCApath != NULL || chCAfile != NULL) {
1269 ch = X509_STORE_new();
1272 if (!X509_STORE_load_locations(ch, chCAfile, chCApath))
1274 SSL_CTX_set1_chain_cert_store(ctx, ch);
1278 X509_STORE_free(vfy);
1279 X509_STORE_free(ch);
1283 /* Verbose print out of security callback */
1288 int (*old_cb) (const SSL *s, const SSL_CTX *ctx, int op, int bits, int nid,
1289 void *other, void *ex);
1290 } security_debug_ex;
1292 static STRINT_PAIR callback_types[] = {
1293 {"Supported Ciphersuite", SSL_SECOP_CIPHER_SUPPORTED},
1294 {"Shared Ciphersuite", SSL_SECOP_CIPHER_SHARED},
1295 {"Check Ciphersuite", SSL_SECOP_CIPHER_CHECK},
1296 #ifndef OPENSSL_NO_DH
1297 {"Temp DH key bits", SSL_SECOP_TMP_DH},
1299 {"Supported Curve", SSL_SECOP_CURVE_SUPPORTED},
1300 {"Shared Curve", SSL_SECOP_CURVE_SHARED},
1301 {"Check Curve", SSL_SECOP_CURVE_CHECK},
1302 {"Supported Signature Algorithm digest", SSL_SECOP_SIGALG_SUPPORTED},
1303 {"Shared Signature Algorithm digest", SSL_SECOP_SIGALG_SHARED},
1304 {"Check Signature Algorithm digest", SSL_SECOP_SIGALG_CHECK},
1305 {"Signature Algorithm mask", SSL_SECOP_SIGALG_MASK},
1306 {"Certificate chain EE key", SSL_SECOP_EE_KEY},
1307 {"Certificate chain CA key", SSL_SECOP_CA_KEY},
1308 {"Peer Chain EE key", SSL_SECOP_PEER_EE_KEY},
1309 {"Peer Chain CA key", SSL_SECOP_PEER_CA_KEY},
1310 {"Certificate chain CA digest", SSL_SECOP_CA_MD},
1311 {"Peer chain CA digest", SSL_SECOP_PEER_CA_MD},
1312 {"SSL compression", SSL_SECOP_COMPRESSION},
1313 {"Session ticket", SSL_SECOP_TICKET},
1317 static int security_callback_debug(const SSL *s, const SSL_CTX *ctx,
1318 int op, int bits, int nid,
1319 void *other, void *ex)
1321 security_debug_ex *sdb = ex;
1322 int rv, show_bits = 1, cert_md = 0;
1324 rv = sdb->old_cb(s, ctx, op, bits, nid, other, ex);
1325 if (rv == 1 && sdb->verbose < 2)
1327 BIO_puts(sdb->out, "Security callback: ");
1329 nm = lookup(op, callback_types, NULL);
1331 case SSL_SECOP_TICKET:
1332 case SSL_SECOP_COMPRESSION:
1336 case SSL_SECOP_VERSION:
1337 BIO_printf(sdb->out, "Version=%s", lookup(nid, ssl_versions, "???"));
1341 case SSL_SECOP_CA_MD:
1342 case SSL_SECOP_PEER_CA_MD:
1347 BIO_printf(sdb->out, "%s=", nm);
1349 switch (op & SSL_SECOP_OTHER_TYPE) {
1351 case SSL_SECOP_OTHER_CIPHER:
1352 BIO_puts(sdb->out, SSL_CIPHER_get_name(other));
1355 #ifndef OPENSSL_NO_EC
1356 case SSL_SECOP_OTHER_CURVE:
1359 cname = EC_curve_nid2nist(nid);
1361 cname = OBJ_nid2sn(nid);
1362 BIO_puts(sdb->out, cname);
1366 #ifndef OPENSSL_NO_DH
1367 case SSL_SECOP_OTHER_DH:
1370 BIO_printf(sdb->out, "%d", DH_bits(dh));
1374 case SSL_SECOP_OTHER_CERT:
1377 int sig_nid = X509_get_signature_nid(other);
1378 BIO_puts(sdb->out, OBJ_nid2sn(sig_nid));
1380 EVP_PKEY *pkey = X509_get0_pubkey(other);
1381 const char *algname = "";
1382 EVP_PKEY_asn1_get0_info(NULL, NULL, NULL, NULL,
1383 &algname, EVP_PKEY_get0_asn1(pkey));
1384 BIO_printf(sdb->out, "%s, bits=%d",
1385 algname, EVP_PKEY_bits(pkey));
1389 case SSL_SECOP_OTHER_SIGALG:
1391 const unsigned char *salg = other;
1392 const char *sname = NULL;
1394 case TLSEXT_signature_anonymous:
1395 sname = "anonymous";
1397 case TLSEXT_signature_rsa:
1400 case TLSEXT_signature_dsa:
1403 case TLSEXT_signature_ecdsa:
1408 BIO_puts(sdb->out, OBJ_nid2sn(nid));
1410 BIO_printf(sdb->out, ", algorithm=%s", sname);
1412 BIO_printf(sdb->out, ", algid=%d", salg[1]);
1419 BIO_printf(sdb->out, ", security bits=%d", bits);
1420 BIO_printf(sdb->out, ": %s\n", rv ? "yes" : "no");
1424 void ssl_ctx_security_debug(SSL_CTX *ctx, int verbose)
1426 static security_debug_ex sdb;
1429 sdb.verbose = verbose;
1430 sdb.old_cb = SSL_CTX_get_security_callback(ctx);
1431 SSL_CTX_set_security_callback(ctx, security_callback_debug);
1432 SSL_CTX_set0_security_ex_data(ctx, &sdb);