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 static unsigned char cookie_secret[COOKIE_SECRET_LENGTH];
135 static int cookie_initialized = 0;
137 static const char *lookup(int val, const STRINT_PAIR* list, const char* def)
139 for ( ; list->name; ++list)
140 if (list->retval == val)
145 int verify_callback(int ok, X509_STORE_CTX *ctx)
150 err_cert = X509_STORE_CTX_get_current_cert(ctx);
151 err = X509_STORE_CTX_get_error(ctx);
152 depth = X509_STORE_CTX_get_error_depth(ctx);
154 if (!verify_quiet || !ok) {
155 BIO_printf(bio_err, "depth=%d ", depth);
157 X509_NAME_print_ex(bio_err,
158 X509_get_subject_name(err_cert),
160 BIO_puts(bio_err, "\n");
162 BIO_puts(bio_err, "<no cert>\n");
165 BIO_printf(bio_err, "verify error:num=%d:%s\n", err,
166 X509_verify_cert_error_string(err));
167 if (verify_depth >= depth) {
168 if (!verify_return_error)
170 verify_error = X509_V_OK;
173 verify_error = X509_V_ERR_CERT_CHAIN_TOO_LONG;
177 case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT:
178 BIO_puts(bio_err, "issuer= ");
179 X509_NAME_print_ex(bio_err, X509_get_issuer_name(err_cert),
181 BIO_puts(bio_err, "\n");
183 case X509_V_ERR_CERT_NOT_YET_VALID:
184 case X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD:
185 BIO_printf(bio_err, "notBefore=");
186 ASN1_TIME_print(bio_err, X509_get_notBefore(err_cert));
187 BIO_printf(bio_err, "\n");
189 case X509_V_ERR_CERT_HAS_EXPIRED:
190 case X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD:
191 BIO_printf(bio_err, "notAfter=");
192 ASN1_TIME_print(bio_err, X509_get_notAfter(err_cert));
193 BIO_printf(bio_err, "\n");
195 case X509_V_ERR_NO_EXPLICIT_POLICY:
200 if (err == X509_V_OK && ok == 2 && !verify_quiet)
202 if (ok && !verify_quiet)
203 BIO_printf(bio_err, "verify return:%d\n", ok);
207 int set_cert_stuff(SSL_CTX *ctx, char *cert_file, char *key_file)
209 if (cert_file != NULL) {
210 if (SSL_CTX_use_certificate_file(ctx, cert_file,
211 SSL_FILETYPE_PEM) <= 0) {
212 BIO_printf(bio_err, "unable to get certificate from '%s'\n",
214 ERR_print_errors(bio_err);
217 if (key_file == NULL)
218 key_file = cert_file;
219 if (SSL_CTX_use_PrivateKey_file(ctx, key_file, SSL_FILETYPE_PEM) <= 0) {
220 BIO_printf(bio_err, "unable to get private key from '%s'\n",
222 ERR_print_errors(bio_err);
227 * If we are using DSA, we can copy the parameters from the private
232 * Now we know that a key and cert have been set against the SSL
235 if (!SSL_CTX_check_private_key(ctx)) {
237 "Private key does not match the certificate public key\n");
244 int set_cert_key_stuff(SSL_CTX *ctx, X509 *cert, EVP_PKEY *key,
245 STACK_OF(X509) *chain, int build_chain)
247 int chflags = chain ? SSL_BUILD_CHAIN_FLAG_CHECK : 0;
250 if (SSL_CTX_use_certificate(ctx, cert) <= 0) {
251 BIO_printf(bio_err, "error setting certificate\n");
252 ERR_print_errors(bio_err);
256 if (SSL_CTX_use_PrivateKey(ctx, key) <= 0) {
257 BIO_printf(bio_err, "error setting private key\n");
258 ERR_print_errors(bio_err);
263 * Now we know that a key and cert have been set against the SSL context
265 if (!SSL_CTX_check_private_key(ctx)) {
267 "Private key does not match the certificate public key\n");
270 if (chain && !SSL_CTX_set1_chain(ctx, chain)) {
271 BIO_printf(bio_err, "error setting certificate chain\n");
272 ERR_print_errors(bio_err);
275 if (build_chain && !SSL_CTX_build_cert_chain(ctx, chflags)) {
276 BIO_printf(bio_err, "error building certificate chain\n");
277 ERR_print_errors(bio_err);
283 static STRINT_PAIR cert_type_list[] = {
284 {"RSA sign", TLS_CT_RSA_SIGN},
285 {"DSA sign", TLS_CT_DSS_SIGN},
286 {"RSA fixed DH", TLS_CT_RSA_FIXED_DH},
287 {"DSS fixed DH", TLS_CT_DSS_FIXED_DH},
288 {"ECDSA sign", TLS_CT_ECDSA_SIGN},
289 {"RSA fixed ECDH", TLS_CT_RSA_FIXED_ECDH},
290 {"ECDSA fixed ECDH", TLS_CT_ECDSA_FIXED_ECDH},
291 {"GOST01 Sign", TLS_CT_GOST01_SIGN},
295 static void ssl_print_client_cert_types(BIO *bio, SSL *s)
297 const unsigned char *p;
299 int cert_type_num = SSL_get0_certificate_types(s, &p);
302 BIO_puts(bio, "Client Certificate Types: ");
303 for (i = 0; i < cert_type_num; i++) {
304 unsigned char cert_type = p[i];
305 const char *cname = lookup((int)cert_type, cert_type_list, NULL);
310 BIO_puts(bio, cname);
312 BIO_printf(bio, "UNKNOWN (%d),", cert_type);
317 static int do_print_sigalgs(BIO *out, SSL *s, int shared)
320 client = SSL_is_server(s) ? 0 : 1;
322 nsig = SSL_get_shared_sigalgs(s, -1, NULL, NULL, NULL, NULL, NULL);
324 nsig = SSL_get_sigalgs(s, -1, NULL, NULL, NULL, NULL, NULL);
329 BIO_puts(out, "Shared ");
332 BIO_puts(out, "Requested ");
333 BIO_puts(out, "Signature Algorithms: ");
334 for (i = 0; i < nsig; i++) {
335 int hash_nid, sign_nid;
336 unsigned char rhash, rsign;
337 const char *sstr = NULL;
339 SSL_get_shared_sigalgs(s, i, &sign_nid, &hash_nid, NULL,
342 SSL_get_sigalgs(s, i, &sign_nid, &hash_nid, NULL, &rsign, &rhash);
345 if (sign_nid == EVP_PKEY_RSA)
347 else if (sign_nid == EVP_PKEY_DSA)
349 else if (sign_nid == EVP_PKEY_EC)
352 BIO_printf(out, "%s+", sstr);
354 BIO_printf(out, "0x%02X+", (int)rsign);
355 if (hash_nid != NID_undef)
356 BIO_printf(out, "%s", OBJ_nid2sn(hash_nid));
358 BIO_printf(out, "0x%02X", (int)rhash);
364 int ssl_print_sigalgs(BIO *out, SSL *s)
367 if (!SSL_is_server(s))
368 ssl_print_client_cert_types(out, s);
369 do_print_sigalgs(out, s, 0);
370 do_print_sigalgs(out, s, 1);
371 if (SSL_get_peer_signature_nid(s, &mdnid))
372 BIO_printf(out, "Peer signing digest: %s\n", OBJ_nid2sn(mdnid));
376 #ifndef OPENSSL_NO_EC
377 int ssl_print_point_formats(BIO *out, SSL *s)
380 const char *pformats;
381 nformats = SSL_get0_ec_point_formats(s, &pformats);
384 BIO_puts(out, "Supported Elliptic Curve Point Formats: ");
385 for (i = 0; i < nformats; i++, pformats++) {
389 case TLSEXT_ECPOINTFORMAT_uncompressed:
390 BIO_puts(out, "uncompressed");
393 case TLSEXT_ECPOINTFORMAT_ansiX962_compressed_prime:
394 BIO_puts(out, "ansiX962_compressed_prime");
397 case TLSEXT_ECPOINTFORMAT_ansiX962_compressed_char2:
398 BIO_puts(out, "ansiX962_compressed_char2");
402 BIO_printf(out, "unknown(%d)", (int)*pformats);
408 BIO_puts(out, "NONE");
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);
441 BIO_puts(out, "NONE");
442 OPENSSL_free(curves);
447 BIO_puts(out, "\nShared Elliptic curves: ");
448 ncurves = SSL_get_shared_curve(s, -1);
449 for (i = 0; i < ncurves; i++) {
452 nid = SSL_get_shared_curve(s, i);
453 cname = EC_curve_nid2nist(nid);
455 cname = OBJ_nid2sn(nid);
456 BIO_printf(out, "%s", cname);
459 BIO_puts(out, "NONE");
464 int ssl_print_tmp_key(BIO *out, SSL *s)
467 if (!SSL_get_server_tmp_key(s, &key))
469 BIO_puts(out, "Server Temp Key: ");
470 switch (EVP_PKEY_id(key)) {
472 BIO_printf(out, "RSA, %d bits\n", EVP_PKEY_bits(key));
476 BIO_printf(out, "DH, %d bits\n", EVP_PKEY_bits(key));
478 #ifndef OPENSSL_NO_EC
481 EC_KEY *ec = EVP_PKEY_get1_EC_KEY(key);
484 nid = EC_GROUP_get_curve_name(EC_KEY_get0_group(ec));
486 cname = EC_curve_nid2nist(nid);
488 cname = OBJ_nid2sn(nid);
489 BIO_printf(out, "ECDH, %s, %d bits\n", cname, EVP_PKEY_bits(key));
497 long bio_dump_callback(BIO *bio, int cmd, const char *argp,
498 int argi, long argl, long ret)
502 out = (BIO *)BIO_get_callback_arg(bio);
506 if (cmd == (BIO_CB_READ | BIO_CB_RETURN)) {
507 BIO_printf(out, "read from %p [%p] (%lu bytes => %ld (0x%lX))\n",
508 (void *)bio, argp, (unsigned long)argi, ret, ret);
509 BIO_dump(out, argp, (int)ret);
511 } else if (cmd == (BIO_CB_WRITE | BIO_CB_RETURN)) {
512 BIO_printf(out, "write to %p [%p] (%lu bytes => %ld (0x%lX))\n",
513 (void *)bio, argp, (unsigned long)argi, ret, ret);
514 BIO_dump(out, argp, (int)ret);
519 void apps_ssl_info_callback(const SSL *s, int where, int ret)
524 w = where & ~SSL_ST_MASK;
526 if (w & SSL_ST_CONNECT)
528 else if (w & SSL_ST_ACCEPT)
533 if (where & SSL_CB_LOOP) {
534 BIO_printf(bio_err, "%s:%s\n", str, SSL_state_string_long(s));
535 } else if (where & SSL_CB_ALERT) {
536 str = (where & SSL_CB_READ) ? "read" : "write";
537 BIO_printf(bio_err, "SSL3 alert %s:%s:%s\n",
539 SSL_alert_type_string_long(ret),
540 SSL_alert_desc_string_long(ret));
541 } else if (where & SSL_CB_EXIT) {
543 BIO_printf(bio_err, "%s:failed in %s\n",
544 str, SSL_state_string_long(s));
546 BIO_printf(bio_err, "%s:error in %s\n",
547 str, SSL_state_string_long(s));
552 static STRINT_PAIR ssl_versions[] = {
553 {"SSL 3.0", SSL3_VERSION},
554 {"TLS 1.0", TLS1_VERSION},
555 {"TLS 1.1", TLS1_1_VERSION},
556 {"TLS 1.2", TLS1_2_VERSION},
557 {"DTLS 1.0", DTLS1_VERSION},
558 {"DTLS 1.0 (bad)", DTLS1_BAD_VER},
561 static STRINT_PAIR alert_types[] = {
562 {" close_notify", 0},
563 {" unexpected_message", 10},
564 {" bad_record_mac", 20},
565 {" decryption_failed", 21},
566 {" record_overflow", 22},
567 {" decompression_failure", 30},
568 {" handshake_failure", 40},
569 {" bad_certificate", 42},
570 {" unsupported_certificate", 43},
571 {" certificate_revoked", 44},
572 {" certificate_expired", 45},
573 {" certificate_unknown", 46},
574 {" illegal_parameter", 47},
576 {" access_denied", 49},
577 {" decode_error", 50},
578 {" decrypt_error", 51},
579 {" export_restriction", 60},
580 {" protocol_version", 70},
581 {" insufficient_security", 71},
582 {" internal_error", 80},
583 {" user_canceled", 90},
584 {" no_renegotiation", 100},
585 {" unsupported_extension", 110},
586 {" certificate_unobtainable", 111},
587 {" unrecognized_name", 112},
588 {" bad_certificate_status_response", 113},
589 {" bad_certificate_hash_value", 114},
590 {" unknown_psk_identity", 115},
594 static STRINT_PAIR handshakes[] = {
595 {", HelloRequest", 0},
596 {", ClientHello", 1},
597 {", ServerHello", 2},
598 {", HelloVerifyRequest", 3},
599 {", Certificate", 11},
600 {", ServerKeyExchange", 12},
601 {", CertificateRequest", 13},
602 {", ServerHelloDone", 14},
603 {", CertificateVerify", 15},
604 {", ClientKeyExchange", 16},
609 void msg_cb(int write_p, int version, int content_type, const void *buf,
610 size_t len, SSL *ssl, void *arg)
613 const char *str_write_p = write_p ? ">>>" : "<<<";
614 const char *str_version = lookup(version, ssl_versions, "???");
615 const char *str_content_type = "", *str_details1 = "", *str_details2 = "";
616 const unsigned char* bp = buf;
618 if (version == SSL3_VERSION ||
619 version == TLS1_VERSION ||
620 version == TLS1_1_VERSION ||
621 version == TLS1_2_VERSION ||
622 version == DTLS1_VERSION || version == DTLS1_BAD_VER) {
623 switch (content_type) {
625 str_content_type = "ChangeCipherSpec";
628 str_content_type = "Alert";
629 str_details1 = ", ???";
633 str_details1 = ", warning";
636 str_details1 = ", fatal";
639 str_details2 = lookup((int)bp[1], alert_types, " ???");
643 str_content_type = "Handshake";
644 str_details1 = "???";
646 str_details1 = lookup((int)bp[0], handshakes, "???");
648 #ifndef OPENSSL_NO_HEARTBEATS
650 str_details1 = ", Heartbeat";
655 str_details1 = ", HeartbeatRequest";
658 str_details1 = ", HeartbeatResponse";
667 BIO_printf(bio, "%s %s%s [length %04lx]%s%s\n", str_write_p, str_version,
668 str_content_type, (unsigned long)len, str_details1,
674 BIO_printf(bio, " ");
676 for (i = 0; i < num; i++) {
677 if (i % 16 == 0 && i > 0)
678 BIO_printf(bio, "\n ");
679 BIO_printf(bio, " %02x", ((const unsigned char *)buf)[i]);
682 BIO_printf(bio, " ...");
683 BIO_printf(bio, "\n");
685 (void)BIO_flush(bio);
688 static STRINT_PAIR tlsext_types[] = {
689 {"server name", TLSEXT_TYPE_server_name},
690 {"max fragment length", TLSEXT_TYPE_max_fragment_length},
691 {"client certificate URL", TLSEXT_TYPE_client_certificate_url},
692 {"trusted CA keys", TLSEXT_TYPE_trusted_ca_keys},
693 {"truncated HMAC", TLSEXT_TYPE_truncated_hmac},
694 {"status request", TLSEXT_TYPE_status_request},
695 {"user mapping", TLSEXT_TYPE_user_mapping},
696 {"client authz", TLSEXT_TYPE_client_authz},
697 {"server authz", TLSEXT_TYPE_server_authz},
698 {"cert type", TLSEXT_TYPE_cert_type},
699 {"elliptic curves", TLSEXT_TYPE_elliptic_curves},
700 {"EC point formats", TLSEXT_TYPE_ec_point_formats},
701 {"SRP", TLSEXT_TYPE_srp},
702 {"signature algorithms", TLSEXT_TYPE_signature_algorithms},
703 {"use SRTP", TLSEXT_TYPE_use_srtp},
704 {"heartbeat", TLSEXT_TYPE_heartbeat},
705 {"session ticket", TLSEXT_TYPE_session_ticket},
706 {"renegotiation info", TLSEXT_TYPE_renegotiate},
707 {"TLS padding", TLSEXT_TYPE_padding},
708 #ifdef TLSEXT_TYPE_next_proto_neg
709 {"next protocol", TLSEXT_TYPE_next_proto_neg},
711 #ifdef TLSEXT_TYPE_encrypt_then_mac
712 {"encrypt-then-mac", TLSEXT_TYPE_encrypt_then_mac},
714 #ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
715 {"application layer protocol negotiation",
716 TLSEXT_TYPE_application_layer_protocol_negotiation},
721 void tlsext_cb(SSL *s, int client_server, int type,
722 unsigned char *data, int len, void *arg)
725 const char *extname = lookup(type, tlsext_types, "unknown");
727 BIO_printf(bio, "TLS %s extension \"%s\" (id=%d), len=%d\n",
728 client_server ? "server" : "client", extname, type, len);
729 BIO_dump(bio, (char *)data, len);
730 (void)BIO_flush(bio);
733 int generate_cookie_callback(SSL *ssl, unsigned char *cookie,
734 unsigned int *cookie_len)
736 unsigned char *buffer, result[EVP_MAX_MD_SIZE];
737 unsigned int length, resultlength;
740 struct sockaddr_in s4;
742 struct sockaddr_in6 s6;
746 /* Initialize a random secret */
747 if (!cookie_initialized) {
748 if (RAND_bytes(cookie_secret, COOKIE_SECRET_LENGTH) <= 0) {
749 BIO_printf(bio_err, "error setting random cookie secret\n");
752 cookie_initialized = 1;
755 /* Read peer information */
756 (void)BIO_dgram_get_peer(SSL_get_rbio(ssl), &peer);
758 /* Create buffer with peer's address and port */
760 switch (peer.sa.sa_family) {
762 length += sizeof(struct in_addr);
763 length += sizeof(peer.s4.sin_port);
767 length += sizeof(struct in6_addr);
768 length += sizeof(peer.s6.sin6_port);
775 buffer = app_malloc(length, "cookie generate buffer");
777 switch (peer.sa.sa_family) {
779 memcpy(buffer, &peer.s4.sin_port, sizeof(peer.s4.sin_port));
780 memcpy(buffer + sizeof(peer.s4.sin_port),
781 &peer.s4.sin_addr, sizeof(struct in_addr));
785 memcpy(buffer, &peer.s6.sin6_port, sizeof(peer.s6.sin6_port));
786 memcpy(buffer + sizeof(peer.s6.sin6_port),
787 &peer.s6.sin6_addr, sizeof(struct in6_addr));
795 /* Calculate HMAC of buffer using the secret */
796 HMAC(EVP_sha1(), cookie_secret, COOKIE_SECRET_LENGTH,
797 buffer, length, result, &resultlength);
798 OPENSSL_free(buffer);
800 memcpy(cookie, result, resultlength);
801 *cookie_len = resultlength;
806 int verify_cookie_callback(SSL *ssl, unsigned char *cookie,
807 unsigned int cookie_len)
809 unsigned char *buffer, result[EVP_MAX_MD_SIZE];
810 unsigned int length, resultlength;
813 struct sockaddr_in s4;
815 struct sockaddr_in6 s6;
819 /* If secret isn't initialized yet, the cookie can't be valid */
820 if (!cookie_initialized)
823 /* Read peer information */
824 (void)BIO_dgram_get_peer(SSL_get_rbio(ssl), &peer);
826 /* Create buffer with peer's address and port */
828 switch (peer.sa.sa_family) {
830 length += sizeof(struct in_addr);
831 length += sizeof(peer.s4.sin_port);
835 length += sizeof(struct in6_addr);
836 length += sizeof(peer.s6.sin6_port);
843 buffer = app_malloc(length, "cookie verify buffer");
845 switch (peer.sa.sa_family) {
847 memcpy(buffer, &peer.s4.sin_port, sizeof(peer.s4.sin_port));
848 memcpy(buffer + sizeof(peer.s4.sin_port),
849 &peer.s4.sin_addr, sizeof(struct in_addr));
853 memcpy(buffer, &peer.s6.sin6_port, sizeof(peer.s6.sin6_port));
854 memcpy(buffer + sizeof(peer.s6.sin6_port),
855 &peer.s6.sin6_addr, sizeof(struct in6_addr));
863 /* Calculate HMAC of buffer using the secret */
864 HMAC(EVP_sha1(), cookie_secret, COOKIE_SECRET_LENGTH,
865 buffer, length, result, &resultlength);
866 OPENSSL_free(buffer);
868 if (cookie_len == resultlength
869 && memcmp(result, cookie, resultlength) == 0)
876 * Example of extended certificate handling. Where the standard support of
877 * one certificate per algorithm is not sufficient an application can decide
878 * which certificate(s) to use at runtime based on whatever criteria it deems
882 /* Linked list of certificates, keys and chains */
883 struct ssl_excert_st {
885 const char *certfile;
888 const char *chainfile;
891 STACK_OF(X509) *chain;
893 struct ssl_excert_st *next, *prev;
896 static STRINT_PAIR chain_flags[] = {
897 {"Overall Validity", CERT_PKEY_VALID},
898 {"Sign with EE key", CERT_PKEY_SIGN},
899 {"EE signature", CERT_PKEY_EE_SIGNATURE},
900 {"CA signature", CERT_PKEY_CA_SIGNATURE},
901 {"EE key parameters", CERT_PKEY_EE_PARAM},
902 {"CA key parameters", CERT_PKEY_CA_PARAM},
903 {"Explicity sign with EE key", CERT_PKEY_EXPLICIT_SIGN},
904 {"Issuer Name", CERT_PKEY_ISSUER_NAME},
905 {"Certificate Type", CERT_PKEY_CERT_TYPE},
909 static void print_chain_flags(SSL *s, int flags)
913 for (pp = chain_flags; pp->name; ++pp)
914 BIO_printf(bio_err, "\t%s: %s\n",
916 (flags & pp->retval) ? "OK" : "NOT OK");
917 BIO_printf(bio_err, "\tSuite B: ");
918 if (SSL_set_cert_flags(s, 0) & SSL_CERT_FLAG_SUITEB_128_LOS)
919 BIO_puts(bio_err, flags & CERT_PKEY_SUITEB ? "OK\n" : "NOT OK\n");
921 BIO_printf(bio_err, "not tested\n");
925 * Very basic selection callback: just use any certificate chain reported as
926 * valid. More sophisticated could prioritise according to local policy.
928 static int set_cert_cb(SSL *ssl, void *arg)
931 SSL_EXCERT *exc = arg;
932 #ifdef CERT_CB_TEST_RETRY
933 static int retry_cnt;
937 "Certificate callback retry test: count %d\n",
942 SSL_certs_clear(ssl);
948 * Go to end of list and traverse backwards since we prepend newer
949 * entries this retains the original order.
958 rv = SSL_check_chain(ssl, exc->cert, exc->key, exc->chain);
959 BIO_printf(bio_err, "Checking cert chain %d:\nSubject: ", i);
960 X509_NAME_print_ex(bio_err, X509_get_subject_name(exc->cert), 0,
962 BIO_puts(bio_err, "\n");
963 print_chain_flags(ssl, rv);
964 if (rv & CERT_PKEY_VALID) {
965 if (!SSL_use_certificate(ssl, exc->cert)
966 || !SSL_use_PrivateKey(ssl, exc->key)) {
970 * NB: we wouldn't normally do this as it is not efficient
971 * building chains on each connection better to cache the chain
974 if (exc->build_chain) {
975 if (!SSL_build_cert_chain(ssl, 0))
977 } else if (exc->chain)
978 SSL_set1_chain(ssl, exc->chain);
985 void ssl_ctx_set_excert(SSL_CTX *ctx, SSL_EXCERT *exc)
987 SSL_CTX_set_cert_cb(ctx, set_cert_cb, exc);
990 static int ssl_excert_prepend(SSL_EXCERT **pexc)
992 SSL_EXCERT *exc = app_malloc(sizeof(*exc), "prepend cert");
994 memset(exc, 0, sizeof(*exc));
1000 exc->certform = exc->next->certform;
1001 exc->keyform = exc->next->keyform;
1002 exc->next->prev = exc;
1004 exc->certform = FORMAT_PEM;
1005 exc->keyform = FORMAT_PEM;
1011 void ssl_excert_free(SSL_EXCERT *exc)
1018 X509_free(exc->cert);
1019 EVP_PKEY_free(exc->key);
1020 sk_X509_pop_free(exc->chain, X509_free);
1027 int load_excert(SSL_EXCERT **pexc)
1029 SSL_EXCERT *exc = *pexc;
1032 /* If nothing in list, free and set to NULL */
1033 if (!exc->certfile && !exc->next) {
1034 ssl_excert_free(exc);
1038 for (; exc; exc = exc->next) {
1039 if (!exc->certfile) {
1040 BIO_printf(bio_err, "Missing filename\n");
1043 exc->cert = load_cert(exc->certfile, exc->certform,
1044 NULL, NULL, "Server Certificate");
1048 exc->key = load_key(exc->keyfile, exc->keyform,
1049 0, NULL, NULL, "Server Key");
1051 exc->key = load_key(exc->certfile, exc->certform,
1052 0, NULL, NULL, "Server Key");
1056 if (exc->chainfile) {
1057 exc->chain = load_certs(exc->chainfile, FORMAT_PEM,
1058 NULL, NULL, "Server Chain");
1066 enum range { OPT_X_ENUM };
1068 int args_excert(int opt, SSL_EXCERT **pexc)
1070 SSL_EXCERT *exc = *pexc;
1072 assert(opt > OPT_X__FIRST);
1073 assert(opt < OPT_X__LAST);
1076 if (!ssl_excert_prepend(&exc)) {
1077 BIO_printf(bio_err, " %s: Error initialising xcert\n",
1084 switch ((enum range)opt) {
1089 if (exc->certfile && !ssl_excert_prepend(&exc)) {
1090 BIO_printf(bio_err, "%s: Error adding xcert\n", opt_getprog());
1093 exc->certfile = opt_arg();
1097 BIO_printf(bio_err, "%s: Key already specified\n", opt_getprog());
1100 exc->keyfile = opt_arg();
1103 if (exc->chainfile) {
1104 BIO_printf(bio_err, "%s: Chain already specified\n",
1108 exc->chainfile = opt_arg();
1110 case OPT_X_CHAIN_BUILD:
1111 exc->build_chain = 1;
1113 case OPT_X_CERTFORM:
1114 if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &exc->certform))
1118 if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &exc->keyform))
1125 ERR_print_errors(bio_err);
1126 ssl_excert_free(exc);
1131 static void print_raw_cipherlist(SSL *s)
1133 const unsigned char *rlist;
1134 static const unsigned char scsv_id[] = { 0, 0, 0xFF };
1135 size_t i, rlistlen, num;
1136 if (!SSL_is_server(s))
1138 num = SSL_get0_raw_cipherlist(s, NULL);
1139 rlistlen = SSL_get0_raw_cipherlist(s, &rlist);
1140 BIO_puts(bio_err, "Client cipher list: ");
1141 for (i = 0; i < rlistlen; i += num, rlist += num) {
1142 const SSL_CIPHER *c = SSL_CIPHER_find(s, rlist);
1144 BIO_puts(bio_err, ":");
1146 BIO_puts(bio_err, SSL_CIPHER_get_name(c));
1147 else if (!memcmp(rlist, scsv_id - num + 3, num))
1148 BIO_puts(bio_err, "SCSV");
1151 BIO_puts(bio_err, "0x");
1152 for (j = 0; j < num; j++)
1153 BIO_printf(bio_err, "%02X", rlist[j]);
1156 BIO_puts(bio_err, "\n");
1159 void print_ssl_summary(SSL *s)
1161 const SSL_CIPHER *c;
1163 /* const char *pnam = SSL_is_server(s) ? "client" : "server"; */
1165 BIO_printf(bio_err, "Protocol version: %s\n", SSL_get_version(s));
1166 print_raw_cipherlist(s);
1167 c = SSL_get_current_cipher(s);
1168 BIO_printf(bio_err, "Ciphersuite: %s\n", SSL_CIPHER_get_name(c));
1169 do_print_sigalgs(bio_err, s, 0);
1170 peer = SSL_get_peer_certificate(s);
1173 BIO_puts(bio_err, "Peer certificate: ");
1174 X509_NAME_print_ex(bio_err, X509_get_subject_name(peer),
1175 0, XN_FLAG_ONELINE);
1176 BIO_puts(bio_err, "\n");
1177 if (SSL_get_peer_signature_nid(s, &nid))
1178 BIO_printf(bio_err, "Hash used: %s\n", OBJ_nid2sn(nid));
1180 BIO_puts(bio_err, "No peer certificate\n");
1182 #ifndef OPENSSL_NO_EC
1183 ssl_print_point_formats(bio_err, s);
1184 if (SSL_is_server(s))
1185 ssl_print_curves(bio_err, s, 1);
1187 ssl_print_tmp_key(bio_err, s);
1189 if (!SSL_is_server(s))
1190 ssl_print_tmp_key(bio_err, s);
1194 int config_ctx(SSL_CONF_CTX *cctx, STACK_OF(OPENSSL_STRING) *str,
1195 SSL_CTX *ctx, int no_ecdhe, int no_jpake)
1199 SSL_CONF_CTX_set_ssl_ctx(cctx, ctx);
1200 for (i = 0; i < sk_OPENSSL_STRING_num(str); i += 2) {
1201 const char *flag = sk_OPENSSL_STRING_value(str, i);
1202 const char *arg = sk_OPENSSL_STRING_value(str, i + 1);
1203 /* If no_ecdhe or named curve already specified don't need a default. */
1204 if (!no_ecdhe && strcmp(flag, "-named_curve") == 0)
1206 #ifndef OPENSSL_NO_JPAKE
1207 if (!no_jpake && (strcmp(flag, "-cipher") == 0)) {
1208 BIO_puts(bio_err, "JPAKE sets cipher to PSK\n");
1212 if (SSL_CONF_cmd(cctx, flag, arg) <= 0) {
1214 BIO_printf(bio_err, "Error with command: \"%s %s\"\n",
1217 BIO_printf(bio_err, "Error with command: \"%s\"\n", flag);
1218 ERR_print_errors(bio_err);
1223 * This is a special case to keep existing s_server functionality: if we
1224 * don't have any curve specified *and* we haven't disabled ECDHE then
1228 if (SSL_CONF_cmd(cctx, "-named_curve", "P-256") <= 0) {
1229 BIO_puts(bio_err, "Error setting EC curve\n");
1230 ERR_print_errors(bio_err);
1234 #ifndef OPENSSL_NO_JPAKE
1236 if (SSL_CONF_cmd(cctx, "-cipher", "PSK") <= 0) {
1237 BIO_puts(bio_err, "Error setting cipher to PSK\n");
1238 ERR_print_errors(bio_err);
1243 if (!SSL_CONF_CTX_finish(cctx)) {
1244 BIO_puts(bio_err, "Error finishing context\n");
1245 ERR_print_errors(bio_err);
1251 static int add_crls_store(X509_STORE *st, STACK_OF(X509_CRL) *crls)
1255 for (i = 0; i < sk_X509_CRL_num(crls); i++) {
1256 crl = sk_X509_CRL_value(crls, i);
1257 X509_STORE_add_crl(st, crl);
1262 int ssl_ctx_add_crls(SSL_CTX *ctx, STACK_OF(X509_CRL) *crls, int crl_download)
1265 st = SSL_CTX_get_cert_store(ctx);
1266 add_crls_store(st, crls);
1268 store_setup_crl_download(st);
1272 int ssl_load_stores(SSL_CTX *ctx,
1273 const char *vfyCApath, const char *vfyCAfile,
1274 const char *chCApath, const char *chCAfile,
1275 STACK_OF(X509_CRL) *crls, int crl_download)
1277 X509_STORE *vfy = NULL, *ch = NULL;
1279 if (vfyCApath || vfyCAfile) {
1280 vfy = X509_STORE_new();
1281 if (!X509_STORE_load_locations(vfy, vfyCAfile, vfyCApath))
1283 add_crls_store(vfy, crls);
1284 SSL_CTX_set1_verify_cert_store(ctx, vfy);
1286 store_setup_crl_download(vfy);
1288 if (chCApath || chCAfile) {
1289 ch = X509_STORE_new();
1290 if (!X509_STORE_load_locations(ch, chCAfile, chCApath))
1292 SSL_CTX_set1_chain_cert_store(ctx, ch);
1296 X509_STORE_free(vfy);
1297 X509_STORE_free(ch);
1301 /* Verbose print out of security callback */
1306 int (*old_cb) (SSL *s, SSL_CTX *ctx, int op, int bits, int nid,
1307 void *other, void *ex);
1308 } security_debug_ex;
1310 static STRINT_PAIR callback_types[] = {
1311 {"Supported Ciphersuite", SSL_SECOP_CIPHER_SUPPORTED},
1312 {"Shared Ciphersuite", SSL_SECOP_CIPHER_SHARED},
1313 {"Check Ciphersuite", SSL_SECOP_CIPHER_CHECK},
1314 #ifndef OPENSSL_NO_DH
1315 {"Temp DH key bits", SSL_SECOP_TMP_DH},
1317 {"Supported Curve", SSL_SECOP_CURVE_SUPPORTED},
1318 {"Shared Curve", SSL_SECOP_CURVE_SHARED},
1319 {"Check Curve", SSL_SECOP_CURVE_CHECK},
1320 {"Supported Signature Algorithm digest", SSL_SECOP_SIGALG_SUPPORTED},
1321 {"Shared Signature Algorithm digest", SSL_SECOP_SIGALG_SHARED},
1322 {"Check Signature Algorithm digest", SSL_SECOP_SIGALG_CHECK},
1323 {"Signature Algorithm mask", SSL_SECOP_SIGALG_MASK},
1324 {"Certificate chain EE key", SSL_SECOP_EE_KEY},
1325 {"Certificate chain CA key", SSL_SECOP_CA_KEY},
1326 {"Peer Chain EE key", SSL_SECOP_PEER_EE_KEY},
1327 {"Peer Chain CA key", SSL_SECOP_PEER_CA_KEY},
1328 {"Certificate chain CA digest", SSL_SECOP_CA_MD},
1329 {"Peer chain CA digest", SSL_SECOP_PEER_CA_MD},
1330 {"SSL compression", SSL_SECOP_COMPRESSION},
1331 {"Session ticket", SSL_SECOP_TICKET},
1335 static int security_callback_debug(SSL *s, SSL_CTX *ctx,
1336 int op, int bits, int nid,
1337 void *other, void *ex)
1339 security_debug_ex *sdb = ex;
1340 int rv, show_bits = 1, cert_md = 0;
1342 rv = sdb->old_cb(s, ctx, op, bits, nid, other, ex);
1343 if (rv == 1 && sdb->verbose < 2)
1345 BIO_puts(sdb->out, "Security callback: ");
1347 nm = lookup(op, callback_types, NULL);
1349 case SSL_SECOP_TICKET:
1350 case SSL_SECOP_COMPRESSION:
1354 case SSL_SECOP_VERSION:
1355 BIO_printf(sdb->out, "Version=%s", lookup(nid, ssl_versions, "???"));
1359 case SSL_SECOP_CA_MD:
1360 case SSL_SECOP_PEER_CA_MD:
1365 BIO_printf(sdb->out, "%s=", nm);
1367 switch (op & SSL_SECOP_OTHER_TYPE) {
1369 case SSL_SECOP_OTHER_CIPHER:
1370 BIO_puts(sdb->out, SSL_CIPHER_get_name(other));
1373 #ifndef OPENSSL_NO_EC
1374 case SSL_SECOP_OTHER_CURVE:
1377 cname = EC_curve_nid2nist(nid);
1379 cname = OBJ_nid2sn(nid);
1380 BIO_puts(sdb->out, cname);
1385 case SSL_SECOP_OTHER_DH:
1388 BIO_printf(sdb->out, "%d", BN_num_bits(dh->p));
1391 case SSL_SECOP_OTHER_CERT:
1394 int sig_nid = X509_get_signature_nid(other);
1395 BIO_puts(sdb->out, OBJ_nid2sn(sig_nid));
1397 EVP_PKEY *pkey = X509_get_pubkey(other);
1398 const char *algname = "";
1399 EVP_PKEY_asn1_get0_info(NULL, NULL, NULL, NULL,
1400 &algname, EVP_PKEY_get0_asn1(pkey));
1401 BIO_printf(sdb->out, "%s, bits=%d",
1402 algname, EVP_PKEY_bits(pkey));
1403 EVP_PKEY_free(pkey);
1407 case SSL_SECOP_OTHER_SIGALG:
1409 const unsigned char *salg = other;
1410 const char *sname = NULL;
1412 case TLSEXT_signature_anonymous:
1413 sname = "anonymous";
1415 case TLSEXT_signature_rsa:
1418 case TLSEXT_signature_dsa:
1421 case TLSEXT_signature_ecdsa:
1426 BIO_puts(sdb->out, OBJ_nid2sn(nid));
1428 BIO_printf(sdb->out, ", algorithm=%s", sname);
1430 BIO_printf(sdb->out, ", algid=%d", salg[1]);
1437 BIO_printf(sdb->out, ", security bits=%d", bits);
1438 BIO_printf(sdb->out, ": %s\n", rv ? "yes" : "no");
1442 void ssl_ctx_security_debug(SSL_CTX *ctx, int verbose)
1444 static security_debug_ex sdb;
1447 sdb.verbose = verbose;
1448 sdb.old_cb = SSL_CTX_get_security_callback(ctx);
1449 SSL_CTX_set_security_callback(ctx, security_callback_debug);
1450 SSL_CTX_set0_security_ex_data(ctx, &sdb);