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 */
115 #include <string.h> /* for memcpy() and strcmp() */
119 #include <openssl/err.h>
120 #include <openssl/rand.h>
121 #include <openssl/x509.h>
122 #include <openssl/ssl.h>
123 #include <openssl/bn.h>
124 #ifndef OPENSSL_NO_DH
125 # include <openssl/dh.h>
129 #define COOKIE_SECRET_LENGTH 16
131 int verify_depth = 0;
132 int verify_quiet = 0;
133 int verify_error = X509_V_OK;
134 int verify_return_error = 0;
135 unsigned char cookie_secret[COOKIE_SECRET_LENGTH];
136 int cookie_initialized = 0;
138 int verify_callback(int ok, X509_STORE_CTX *ctx)
143 err_cert = X509_STORE_CTX_get_current_cert(ctx);
144 err = X509_STORE_CTX_get_error(ctx);
145 depth = X509_STORE_CTX_get_error_depth(ctx);
147 if (!verify_quiet || !ok) {
148 BIO_printf(bio_err, "depth=%d ", depth);
150 X509_NAME_print_ex(bio_err,
151 X509_get_subject_name(err_cert),
153 BIO_puts(bio_err, "\n");
155 BIO_puts(bio_err, "<no cert>\n");
158 BIO_printf(bio_err, "verify error:num=%d:%s\n", err,
159 X509_verify_cert_error_string(err));
160 if (verify_depth >= depth) {
161 if (!verify_return_error)
163 verify_error = X509_V_OK;
166 verify_error = X509_V_ERR_CERT_CHAIN_TOO_LONG;
170 case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT:
171 BIO_puts(bio_err, "issuer= ");
172 X509_NAME_print_ex(bio_err, X509_get_issuer_name(err_cert),
174 BIO_puts(bio_err, "\n");
176 case X509_V_ERR_CERT_NOT_YET_VALID:
177 case X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD:
178 BIO_printf(bio_err, "notBefore=");
179 ASN1_TIME_print(bio_err, X509_get_notBefore(err_cert));
180 BIO_printf(bio_err, "\n");
182 case X509_V_ERR_CERT_HAS_EXPIRED:
183 case X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD:
184 BIO_printf(bio_err, "notAfter=");
185 ASN1_TIME_print(bio_err, X509_get_notAfter(err_cert));
186 BIO_printf(bio_err, "\n");
188 case X509_V_ERR_NO_EXPLICIT_POLICY:
193 if (err == X509_V_OK && ok == 2 && !verify_quiet)
195 if (ok && !verify_quiet)
196 BIO_printf(bio_err, "verify return:%d\n", ok);
200 int set_cert_stuff(SSL_CTX *ctx, char *cert_file, char *key_file)
202 if (cert_file != NULL) {
203 if (SSL_CTX_use_certificate_file(ctx, cert_file,
204 SSL_FILETYPE_PEM) <= 0) {
205 BIO_printf(bio_err, "unable to get certificate from '%s'\n",
207 ERR_print_errors(bio_err);
210 if (key_file == NULL)
211 key_file = cert_file;
212 if (SSL_CTX_use_PrivateKey_file(ctx, key_file, SSL_FILETYPE_PEM) <= 0) {
213 BIO_printf(bio_err, "unable to get private key from '%s'\n",
215 ERR_print_errors(bio_err);
220 * If we are using DSA, we can copy the parameters from the private
225 * Now we know that a key and cert have been set against the SSL
228 if (!SSL_CTX_check_private_key(ctx)) {
230 "Private key does not match the certificate public key\n");
237 int set_cert_key_stuff(SSL_CTX *ctx, X509 *cert, EVP_PKEY *key,
238 STACK_OF(X509) *chain, int build_chain)
240 int chflags = chain ? SSL_BUILD_CHAIN_FLAG_CHECK : 0;
243 if (SSL_CTX_use_certificate(ctx, cert) <= 0) {
244 BIO_printf(bio_err, "error setting certificate\n");
245 ERR_print_errors(bio_err);
249 if (SSL_CTX_use_PrivateKey(ctx, key) <= 0) {
250 BIO_printf(bio_err, "error setting private key\n");
251 ERR_print_errors(bio_err);
256 * Now we know that a key and cert have been set against the SSL context
258 if (!SSL_CTX_check_private_key(ctx)) {
260 "Private key does not match the certificate public key\n");
263 if (chain && !SSL_CTX_set1_chain(ctx, chain)) {
264 BIO_printf(bio_err, "error setting certificate chain\n");
265 ERR_print_errors(bio_err);
268 if (build_chain && !SSL_CTX_build_cert_chain(ctx, chflags)) {
269 BIO_printf(bio_err, "error building certificate chain\n");
270 ERR_print_errors(bio_err);
276 static void ssl_print_client_cert_types(BIO *bio, SSL *s)
278 const unsigned char *p;
280 int cert_type_num = SSL_get0_certificate_types(s, &p);
283 BIO_puts(bio, "Client Certificate Types: ");
284 for (i = 0; i < cert_type_num; i++) {
285 unsigned char cert_type = p[i];
288 case TLS_CT_RSA_SIGN:
292 case TLS_CT_DSS_SIGN:
296 case TLS_CT_RSA_FIXED_DH:
297 cname = "RSA fixed DH";
300 case TLS_CT_DSS_FIXED_DH:
301 cname = "DSS fixed DH";
304 case TLS_CT_ECDSA_SIGN:
305 cname = "ECDSA sign";
308 case TLS_CT_RSA_FIXED_ECDH:
309 cname = "RSA fixed ECDH";
312 case TLS_CT_ECDSA_FIXED_ECDH:
313 cname = "ECDSA fixed ECDH";
316 case TLS_CT_GOST94_SIGN:
317 cname = "GOST94 Sign";
320 case TLS_CT_GOST01_SIGN:
321 cname = "GOST01 Sign";
332 BIO_puts(bio, cname);
334 BIO_printf(bio, "UNKNOWN (%d),", cert_type);
339 static int do_print_sigalgs(BIO *out, SSL *s, int shared)
342 client = SSL_is_server(s) ? 0 : 1;
344 nsig = SSL_get_shared_sigalgs(s, -1, NULL, NULL, NULL, NULL, NULL);
346 nsig = SSL_get_sigalgs(s, -1, NULL, NULL, NULL, NULL, NULL);
351 BIO_puts(out, "Shared ");
354 BIO_puts(out, "Requested ");
355 BIO_puts(out, "Signature Algorithms: ");
356 for (i = 0; i < nsig; i++) {
357 int hash_nid, sign_nid;
358 unsigned char rhash, rsign;
359 const char *sstr = NULL;
361 SSL_get_shared_sigalgs(s, i, &sign_nid, &hash_nid, NULL,
364 SSL_get_sigalgs(s, i, &sign_nid, &hash_nid, NULL, &rsign, &rhash);
367 if (sign_nid == EVP_PKEY_RSA)
369 else if (sign_nid == EVP_PKEY_DSA)
371 else if (sign_nid == EVP_PKEY_EC)
374 BIO_printf(out, "%s+", sstr);
376 BIO_printf(out, "0x%02X+", (int)rsign);
377 if (hash_nid != NID_undef)
378 BIO_printf(out, "%s", OBJ_nid2sn(hash_nid));
380 BIO_printf(out, "0x%02X", (int)rhash);
386 int ssl_print_sigalgs(BIO *out, SSL *s)
389 if (!SSL_is_server(s))
390 ssl_print_client_cert_types(out, s);
391 do_print_sigalgs(out, s, 0);
392 do_print_sigalgs(out, s, 1);
393 if (SSL_get_peer_signature_nid(s, &mdnid))
394 BIO_printf(out, "Peer signing digest: %s\n", OBJ_nid2sn(mdnid));
398 #ifndef OPENSSL_NO_EC
399 int ssl_print_point_formats(BIO *out, SSL *s)
402 const char *pformats;
403 nformats = SSL_get0_ec_point_formats(s, &pformats);
406 BIO_puts(out, "Supported Elliptic Curve Point Formats: ");
407 for (i = 0; i < nformats; i++, pformats++) {
411 case TLSEXT_ECPOINTFORMAT_uncompressed:
412 BIO_puts(out, "uncompressed");
415 case TLSEXT_ECPOINTFORMAT_ansiX962_compressed_prime:
416 BIO_puts(out, "ansiX962_compressed_prime");
419 case TLSEXT_ECPOINTFORMAT_ansiX962_compressed_char2:
420 BIO_puts(out, "ansiX962_compressed_char2");
424 BIO_printf(out, "unknown(%d)", (int)*pformats);
430 BIO_puts(out, "NONE");
435 int ssl_print_curves(BIO *out, SSL *s, int noshared)
437 int i, ncurves, *curves, nid;
440 ncurves = SSL_get1_curves(s, NULL);
443 curves = app_malloc(ncurves * sizeof(int), "curves to print");
444 SSL_get1_curves(s, curves);
446 BIO_puts(out, "Supported Elliptic Curves: ");
447 for (i = 0; i < ncurves; i++) {
451 /* If unrecognised print out hex version */
452 if (nid & TLSEXT_nid_unknown)
453 BIO_printf(out, "0x%04X", nid & 0xFFFF);
455 /* Use NIST name for curve if it exists */
456 cname = EC_curve_nid2nist(nid);
458 cname = OBJ_nid2sn(nid);
459 BIO_printf(out, "%s", cname);
463 BIO_puts(out, "NONE");
464 OPENSSL_free(curves);
469 BIO_puts(out, "\nShared Elliptic curves: ");
470 ncurves = SSL_get_shared_curve(s, -1);
471 for (i = 0; i < ncurves; i++) {
474 nid = SSL_get_shared_curve(s, i);
475 cname = EC_curve_nid2nist(nid);
477 cname = OBJ_nid2sn(nid);
478 BIO_printf(out, "%s", cname);
481 BIO_puts(out, "NONE");
486 int ssl_print_tmp_key(BIO *out, SSL *s)
489 if (!SSL_get_server_tmp_key(s, &key))
491 BIO_puts(out, "Server Temp Key: ");
492 switch (EVP_PKEY_id(key)) {
494 BIO_printf(out, "RSA, %d bits\n", EVP_PKEY_bits(key));
498 BIO_printf(out, "DH, %d bits\n", EVP_PKEY_bits(key));
500 #ifndef OPENSSL_NO_EC
503 EC_KEY *ec = EVP_PKEY_get1_EC_KEY(key);
506 nid = EC_GROUP_get_curve_name(EC_KEY_get0_group(ec));
508 cname = EC_curve_nid2nist(nid);
510 cname = OBJ_nid2sn(nid);
511 BIO_printf(out, "ECDH, %s, %d bits\n", cname, EVP_PKEY_bits(key));
519 long bio_dump_callback(BIO *bio, int cmd, const char *argp,
520 int argi, long argl, long ret)
524 out = (BIO *)BIO_get_callback_arg(bio);
528 if (cmd == (BIO_CB_READ | BIO_CB_RETURN)) {
529 BIO_printf(out, "read from %p [%p] (%lu bytes => %ld (0x%lX))\n",
530 (void *)bio, argp, (unsigned long)argi, ret, ret);
531 BIO_dump(out, argp, (int)ret);
533 } else if (cmd == (BIO_CB_WRITE | BIO_CB_RETURN)) {
534 BIO_printf(out, "write to %p [%p] (%lu bytes => %ld (0x%lX))\n",
535 (void *)bio, argp, (unsigned long)argi, ret, ret);
536 BIO_dump(out, argp, (int)ret);
541 void apps_ssl_info_callback(const SSL *s, int where, int ret)
546 w = where & ~SSL_ST_MASK;
548 if (w & SSL_ST_CONNECT)
550 else if (w & SSL_ST_ACCEPT)
555 if (where & SSL_CB_LOOP) {
556 BIO_printf(bio_err, "%s:%s\n", str, SSL_state_string_long(s));
557 } else if (where & SSL_CB_ALERT) {
558 str = (where & SSL_CB_READ) ? "read" : "write";
559 BIO_printf(bio_err, "SSL3 alert %s:%s:%s\n",
561 SSL_alert_type_string_long(ret),
562 SSL_alert_desc_string_long(ret));
563 } else if (where & SSL_CB_EXIT) {
565 BIO_printf(bio_err, "%s:failed in %s\n",
566 str, SSL_state_string_long(s));
568 BIO_printf(bio_err, "%s:error in %s\n",
569 str, SSL_state_string_long(s));
574 static const char *ssl_version_str(int version)
588 return "DTLS 1.0 (bad)";
594 void msg_cb(int write_p, int version, int content_type, const void *buf,
595 size_t len, SSL *ssl, void *arg)
598 const char *str_write_p, *str_version, *str_content_type =
599 "", *str_details1 = "", *str_details2 = "";
601 str_write_p = write_p ? ">>>" : "<<<";
603 str_version = ssl_version_str(version);
605 if (version == SSL3_VERSION ||
606 version == TLS1_VERSION ||
607 version == TLS1_1_VERSION ||
608 version == TLS1_2_VERSION ||
609 version == DTLS1_VERSION || version == DTLS1_BAD_VER) {
610 switch (content_type) {
612 str_content_type = "ChangeCipherSpec";
615 str_content_type = "Alert";
618 str_content_type = "Handshake";
622 if (content_type == 21) { /* Alert */
623 str_details1 = ", ???";
626 switch (((const unsigned char *)buf)[0]) {
628 str_details1 = ", warning";
631 str_details1 = ", fatal";
635 str_details2 = " ???";
636 switch (((const unsigned char *)buf)[1]) {
638 str_details2 = " close_notify";
641 str_details2 = " unexpected_message";
644 str_details2 = " bad_record_mac";
647 str_details2 = " decryption_failed";
650 str_details2 = " record_overflow";
653 str_details2 = " decompression_failure";
656 str_details2 = " handshake_failure";
659 str_details2 = " bad_certificate";
662 str_details2 = " unsupported_certificate";
665 str_details2 = " certificate_revoked";
668 str_details2 = " certificate_expired";
671 str_details2 = " certificate_unknown";
674 str_details2 = " illegal_parameter";
677 str_details2 = " unknown_ca";
680 str_details2 = " access_denied";
683 str_details2 = " decode_error";
686 str_details2 = " decrypt_error";
689 str_details2 = " export_restriction";
692 str_details2 = " protocol_version";
695 str_details2 = " insufficient_security";
698 str_details2 = " internal_error";
701 str_details2 = " user_canceled";
704 str_details2 = " no_renegotiation";
707 str_details2 = " unsupported_extension";
710 str_details2 = " certificate_unobtainable";
713 str_details2 = " unrecognized_name";
716 str_details2 = " bad_certificate_status_response";
719 str_details2 = " bad_certificate_hash_value";
722 str_details2 = " unknown_psk_identity";
728 if (content_type == 22) { /* Handshake */
729 str_details1 = "???";
732 switch (((const unsigned char *)buf)[0]) {
734 str_details1 = ", HelloRequest";
737 str_details1 = ", ClientHello";
740 str_details1 = ", ServerHello";
743 str_details1 = ", HelloVerifyRequest";
746 str_details1 = ", Certificate";
749 str_details1 = ", ServerKeyExchange";
752 str_details1 = ", CertificateRequest";
755 str_details1 = ", ServerHelloDone";
758 str_details1 = ", CertificateVerify";
761 str_details1 = ", ClientKeyExchange";
764 str_details1 = ", Finished";
769 #ifndef OPENSSL_NO_HEARTBEATS
770 if (content_type == 24) { /* Heartbeat */
771 str_details1 = ", Heartbeat";
774 switch (((const unsigned char *)buf)[0]) {
776 str_details1 = ", HeartbeatRequest";
779 str_details1 = ", HeartbeatResponse";
787 BIO_printf(bio, "%s %s%s [length %04lx]%s%s\n", str_write_p, str_version,
788 str_content_type, (unsigned long)len, str_details1,
794 BIO_printf(bio, " ");
796 for (i = 0; i < num; i++) {
797 if (i % 16 == 0 && i > 0)
798 BIO_printf(bio, "\n ");
799 BIO_printf(bio, " %02x", ((const unsigned char *)buf)[i]);
802 BIO_printf(bio, " ...");
803 BIO_printf(bio, "\n");
805 (void)BIO_flush(bio);
808 void tlsext_cb(SSL *s, int client_server, int type,
809 unsigned char *data, int len, void *arg)
815 case TLSEXT_TYPE_server_name:
816 extname = "server name";
819 case TLSEXT_TYPE_max_fragment_length:
820 extname = "max fragment length";
823 case TLSEXT_TYPE_client_certificate_url:
824 extname = "client certificate URL";
827 case TLSEXT_TYPE_trusted_ca_keys:
828 extname = "trusted CA keys";
831 case TLSEXT_TYPE_truncated_hmac:
832 extname = "truncated HMAC";
835 case TLSEXT_TYPE_status_request:
836 extname = "status request";
839 case TLSEXT_TYPE_user_mapping:
840 extname = "user mapping";
843 case TLSEXT_TYPE_client_authz:
844 extname = "client authz";
847 case TLSEXT_TYPE_server_authz:
848 extname = "server authz";
851 case TLSEXT_TYPE_cert_type:
852 extname = "cert type";
855 case TLSEXT_TYPE_elliptic_curves:
856 extname = "elliptic curves";
859 case TLSEXT_TYPE_ec_point_formats:
860 extname = "EC point formats";
863 case TLSEXT_TYPE_srp:
867 case TLSEXT_TYPE_signature_algorithms:
868 extname = "signature algorithms";
871 case TLSEXT_TYPE_use_srtp:
872 extname = "use SRTP";
875 case TLSEXT_TYPE_heartbeat:
876 extname = "heartbeat";
879 case TLSEXT_TYPE_session_ticket:
880 extname = "session ticket";
883 case TLSEXT_TYPE_renegotiate:
884 extname = "renegotiation info";
887 #ifdef TLSEXT_TYPE_next_proto_neg
888 case TLSEXT_TYPE_next_proto_neg:
889 extname = "next protocol";
892 #ifdef TLSEXT_TYPE_encrypt_then_mac
893 case TLSEXT_TYPE_encrypt_then_mac:
894 extname = "encrypt-then-mac";
897 case TLSEXT_TYPE_padding:
898 extname = "TLS padding";
907 BIO_printf(bio, "TLS %s extension \"%s\" (id=%d), len=%d\n",
908 client_server ? "server" : "client", extname, type, len);
909 BIO_dump(bio, (char *)data, len);
910 (void)BIO_flush(bio);
913 int generate_cookie_callback(SSL *ssl, unsigned char *cookie,
914 unsigned int *cookie_len)
916 unsigned char *buffer, result[EVP_MAX_MD_SIZE];
917 unsigned int length, resultlength;
920 struct sockaddr_in s4;
922 struct sockaddr_in6 s6;
926 /* Initialize a random secret */
927 if (!cookie_initialized) {
928 if (RAND_bytes(cookie_secret, COOKIE_SECRET_LENGTH) <= 0) {
929 BIO_printf(bio_err, "error setting random cookie secret\n");
932 cookie_initialized = 1;
935 /* Read peer information */
936 (void)BIO_dgram_get_peer(SSL_get_rbio(ssl), &peer);
938 /* Create buffer with peer's address and port */
940 switch (peer.sa.sa_family) {
942 length += sizeof(struct in_addr);
943 length += sizeof(peer.s4.sin_port);
947 length += sizeof(struct in6_addr);
948 length += sizeof(peer.s6.sin6_port);
955 buffer = app_malloc(length, "cookie generate buffer");
957 switch (peer.sa.sa_family) {
959 memcpy(buffer, &peer.s4.sin_port, sizeof(peer.s4.sin_port));
960 memcpy(buffer + sizeof(peer.s4.sin_port),
961 &peer.s4.sin_addr, sizeof(struct in_addr));
965 memcpy(buffer, &peer.s6.sin6_port, sizeof(peer.s6.sin6_port));
966 memcpy(buffer + sizeof(peer.s6.sin6_port),
967 &peer.s6.sin6_addr, sizeof(struct in6_addr));
975 /* Calculate HMAC of buffer using the secret */
976 HMAC(EVP_sha1(), cookie_secret, COOKIE_SECRET_LENGTH,
977 buffer, length, result, &resultlength);
978 OPENSSL_free(buffer);
980 memcpy(cookie, result, resultlength);
981 *cookie_len = resultlength;
986 int verify_cookie_callback(SSL *ssl, unsigned char *cookie,
987 unsigned int cookie_len)
989 unsigned char *buffer, result[EVP_MAX_MD_SIZE];
990 unsigned int length, resultlength;
993 struct sockaddr_in s4;
995 struct sockaddr_in6 s6;
999 /* If secret isn't initialized yet, the cookie can't be valid */
1000 if (!cookie_initialized)
1003 /* Read peer information */
1004 (void)BIO_dgram_get_peer(SSL_get_rbio(ssl), &peer);
1006 /* Create buffer with peer's address and port */
1008 switch (peer.sa.sa_family) {
1010 length += sizeof(struct in_addr);
1011 length += sizeof(peer.s4.sin_port);
1013 #if OPENSSL_USE_IPV6
1015 length += sizeof(struct in6_addr);
1016 length += sizeof(peer.s6.sin6_port);
1023 buffer = app_malloc(length, "cookie verify buffer");
1025 switch (peer.sa.sa_family) {
1027 memcpy(buffer, &peer.s4.sin_port, sizeof(peer.s4.sin_port));
1028 memcpy(buffer + sizeof(peer.s4.sin_port),
1029 &peer.s4.sin_addr, sizeof(struct in_addr));
1031 #if OPENSSL_USE_IPV6
1033 memcpy(buffer, &peer.s6.sin6_port, sizeof(peer.s6.sin6_port));
1034 memcpy(buffer + sizeof(peer.s6.sin6_port),
1035 &peer.s6.sin6_addr, sizeof(struct in6_addr));
1043 /* Calculate HMAC of buffer using the secret */
1044 HMAC(EVP_sha1(), cookie_secret, COOKIE_SECRET_LENGTH,
1045 buffer, length, result, &resultlength);
1046 OPENSSL_free(buffer);
1048 if (cookie_len == resultlength
1049 && memcmp(result, cookie, resultlength) == 0)
1056 * Example of extended certificate handling. Where the standard support of
1057 * one certificate per algorithm is not sufficient an application can decide
1058 * which certificate(s) to use at runtime based on whatever criteria it deems
1062 /* Linked list of certificates, keys and chains */
1063 struct ssl_excert_st {
1065 const char *certfile;
1067 const char *keyfile;
1068 const char *chainfile;
1071 STACK_OF(X509) *chain;
1073 struct ssl_excert_st *next, *prev;
1076 struct chain_flags {
1081 struct chain_flags chain_flags_list[] = {
1082 {CERT_PKEY_VALID, "Overall Validity"},
1083 {CERT_PKEY_SIGN, "Sign with EE key"},
1084 {CERT_PKEY_EE_SIGNATURE, "EE signature"},
1085 {CERT_PKEY_CA_SIGNATURE, "CA signature"},
1086 {CERT_PKEY_EE_PARAM, "EE key parameters"},
1087 {CERT_PKEY_CA_PARAM, "CA key parameters"},
1088 {CERT_PKEY_EXPLICIT_SIGN, "Explicity sign with EE key"},
1089 {CERT_PKEY_ISSUER_NAME, "Issuer Name"},
1090 {CERT_PKEY_CERT_TYPE, "Certificate Type"},
1094 static void print_chain_flags(SSL *s, int flags)
1096 struct chain_flags *ctmp = chain_flags_list;
1098 while (ctmp->name) {
1099 BIO_printf(bio_err, "\t%s: %s\n", ctmp->name,
1100 flags & ctmp->flag ? "OK" : "NOT OK");
1103 BIO_printf(bio_err, "\tSuite B: ");
1104 if (SSL_set_cert_flags(s, 0) & SSL_CERT_FLAG_SUITEB_128_LOS)
1105 BIO_puts(bio_err, flags & CERT_PKEY_SUITEB ? "OK\n" : "NOT OK\n");
1107 BIO_printf(bio_err, "not tested\n");
1111 * Very basic selection callback: just use any certificate chain reported as
1112 * valid. More sophisticated could prioritise according to local policy.
1114 static int set_cert_cb(SSL *ssl, void *arg)
1117 SSL_EXCERT *exc = arg;
1118 #ifdef CERT_CB_TEST_RETRY
1119 static int retry_cnt;
1120 if (retry_cnt < 5) {
1122 fprintf(stderr, "Certificate callback retry test: count %d\n",
1127 SSL_certs_clear(ssl);
1133 * Go to end of list and traverse backwards since we prepend newer
1134 * entries this retains the original order.
1143 rv = SSL_check_chain(ssl, exc->cert, exc->key, exc->chain);
1144 BIO_printf(bio_err, "Checking cert chain %d:\nSubject: ", i);
1145 X509_NAME_print_ex(bio_err, X509_get_subject_name(exc->cert), 0,
1147 BIO_puts(bio_err, "\n");
1148 print_chain_flags(ssl, rv);
1149 if (rv & CERT_PKEY_VALID) {
1150 if (!SSL_use_certificate(ssl, exc->cert)
1151 || !SSL_use_PrivateKey(ssl, exc->key)) {
1155 * NB: we wouldn't normally do this as it is not efficient
1156 * building chains on each connection better to cache the chain
1159 if (exc->build_chain) {
1160 if (!SSL_build_cert_chain(ssl, 0))
1162 } else if (exc->chain)
1163 SSL_set1_chain(ssl, exc->chain);
1170 void ssl_ctx_set_excert(SSL_CTX *ctx, SSL_EXCERT *exc)
1172 SSL_CTX_set_cert_cb(ctx, set_cert_cb, exc);
1175 static int ssl_excert_prepend(SSL_EXCERT **pexc)
1177 SSL_EXCERT *exc = app_malloc(sizeof(*exc), "prepend cert");
1179 exc->certfile = NULL;
1180 exc->keyfile = NULL;
1181 exc->chainfile = NULL;
1186 exc->build_chain = 0;
1192 exc->certform = exc->next->certform;
1193 exc->keyform = exc->next->keyform;
1194 exc->next->prev = exc;
1196 exc->certform = FORMAT_PEM;
1197 exc->keyform = FORMAT_PEM;
1203 void ssl_excert_free(SSL_EXCERT *exc)
1210 X509_free(exc->cert);
1211 EVP_PKEY_free(exc->key);
1212 sk_X509_pop_free(exc->chain, X509_free);
1219 int load_excert(SSL_EXCERT **pexc)
1221 SSL_EXCERT *exc = *pexc;
1224 /* If nothing in list, free and set to NULL */
1225 if (!exc->certfile && !exc->next) {
1226 ssl_excert_free(exc);
1230 for (; exc; exc = exc->next) {
1231 if (!exc->certfile) {
1232 BIO_printf(bio_err, "Missing filename\n");
1235 exc->cert = load_cert(exc->certfile, exc->certform,
1236 NULL, NULL, "Server Certificate");
1240 exc->key = load_key(exc->keyfile, exc->keyform,
1241 0, NULL, NULL, "Server Key");
1243 exc->key = load_key(exc->certfile, exc->certform,
1244 0, NULL, NULL, "Server Key");
1248 if (exc->chainfile) {
1249 exc->chain = load_certs(exc->chainfile, FORMAT_PEM,
1250 NULL, NULL, "Server Chain");
1258 enum range { OPT_X_ENUM };
1260 int args_excert(int opt, SSL_EXCERT **pexc)
1262 SSL_EXCERT *exc = *pexc;
1264 assert(opt > OPT_X__FIRST);
1265 assert(opt < OPT_X__LAST);
1268 if (!ssl_excert_prepend(&exc)) {
1269 BIO_printf(bio_err, " %s: Error initialising xcert\n",
1276 switch ((enum range)opt) {
1281 if (exc->certfile && !ssl_excert_prepend(&exc)) {
1282 BIO_printf(bio_err, "%s: Error adding xcert\n", opt_getprog());
1285 exc->certfile = opt_arg();
1289 BIO_printf(bio_err, "%s: Key already specified\n", opt_getprog());
1292 exc->keyfile = opt_arg();
1295 if (exc->chainfile) {
1296 BIO_printf(bio_err, "%s: Chain already specified\n",
1300 exc->chainfile = opt_arg();
1302 case OPT_X_CHAIN_BUILD:
1303 exc->build_chain = 1;
1305 case OPT_X_CERTFORM:
1306 if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &exc->certform))
1310 if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &exc->keyform))
1317 ERR_print_errors(bio_err);
1318 ssl_excert_free(exc);
1323 static void print_raw_cipherlist(SSL *s)
1325 const unsigned char *rlist;
1326 static const unsigned char scsv_id[] = { 0, 0, 0xFF };
1327 size_t i, rlistlen, num;
1328 if (!SSL_is_server(s))
1330 num = SSL_get0_raw_cipherlist(s, NULL);
1331 rlistlen = SSL_get0_raw_cipherlist(s, &rlist);
1332 BIO_puts(bio_err, "Client cipher list: ");
1333 for (i = 0; i < rlistlen; i += num, rlist += num) {
1334 const SSL_CIPHER *c = SSL_CIPHER_find(s, rlist);
1336 BIO_puts(bio_err, ":");
1338 BIO_puts(bio_err, SSL_CIPHER_get_name(c));
1339 else if (!memcmp(rlist, scsv_id - num + 3, num))
1340 BIO_puts(bio_err, "SCSV");
1343 BIO_puts(bio_err, "0x");
1344 for (j = 0; j < num; j++)
1345 BIO_printf(bio_err, "%02X", rlist[j]);
1348 BIO_puts(bio_err, "\n");
1351 void print_ssl_summary(SSL *s)
1353 const SSL_CIPHER *c;
1355 /* const char *pnam = SSL_is_server(s) ? "client" : "server"; */
1357 BIO_printf(bio_err, "Protocol version: %s\n", SSL_get_version(s));
1358 print_raw_cipherlist(s);
1359 c = SSL_get_current_cipher(s);
1360 BIO_printf(bio_err, "Ciphersuite: %s\n", SSL_CIPHER_get_name(c));
1361 do_print_sigalgs(bio_err, s, 0);
1362 peer = SSL_get_peer_certificate(s);
1365 BIO_puts(bio_err, "Peer certificate: ");
1366 X509_NAME_print_ex(bio_err, X509_get_subject_name(peer),
1367 0, XN_FLAG_ONELINE);
1368 BIO_puts(bio_err, "\n");
1369 if (SSL_get_peer_signature_nid(s, &nid))
1370 BIO_printf(bio_err, "Hash used: %s\n", OBJ_nid2sn(nid));
1372 BIO_puts(bio_err, "No peer certificate\n");
1374 #ifndef OPENSSL_NO_EC
1375 ssl_print_point_formats(bio_err, s);
1376 if (SSL_is_server(s))
1377 ssl_print_curves(bio_err, s, 1);
1379 ssl_print_tmp_key(bio_err, s);
1381 if (!SSL_is_server(s))
1382 ssl_print_tmp_key(bio_err, s);
1386 int config_ctx(SSL_CONF_CTX *cctx, STACK_OF(OPENSSL_STRING) *str,
1387 SSL_CTX *ctx, int no_ecdhe, int no_jpake)
1391 SSL_CONF_CTX_set_ssl_ctx(cctx, ctx);
1392 for (i = 0; i < sk_OPENSSL_STRING_num(str); i += 2) {
1393 const char *flag = sk_OPENSSL_STRING_value(str, i);
1394 const char *arg = sk_OPENSSL_STRING_value(str, i + 1);
1395 /* If no_ecdhe or named curve already specified don't need a default. */
1396 if (!no_ecdhe && strcmp(flag, "-named_curve") == 0)
1398 #ifndef OPENSSL_NO_JPAKE
1399 if (!no_jpake && (strcmp(flag, "-cipher") == 0)) {
1400 BIO_puts(bio_err, "JPAKE sets cipher to PSK\n");
1404 if (SSL_CONF_cmd(cctx, flag, arg) <= 0) {
1406 BIO_printf(bio_err, "Error with command: \"%s %s\"\n",
1409 BIO_printf(bio_err, "Error with command: \"%s\"\n", flag);
1410 ERR_print_errors(bio_err);
1415 * This is a special case to keep existing s_server functionality: if we
1416 * don't have any curve specified *and* we haven't disabled ECDHE then
1420 if (SSL_CONF_cmd(cctx, "-named_curve", "P-256") <= 0) {
1421 BIO_puts(bio_err, "Error setting EC curve\n");
1422 ERR_print_errors(bio_err);
1426 #ifndef OPENSSL_NO_JPAKE
1428 if (SSL_CONF_cmd(cctx, "-cipher", "PSK") <= 0) {
1429 BIO_puts(bio_err, "Error setting cipher to PSK\n");
1430 ERR_print_errors(bio_err);
1435 if (!SSL_CONF_CTX_finish(cctx)) {
1436 BIO_puts(bio_err, "Error finishing context\n");
1437 ERR_print_errors(bio_err);
1443 static int add_crls_store(X509_STORE *st, STACK_OF(X509_CRL) *crls)
1447 for (i = 0; i < sk_X509_CRL_num(crls); i++) {
1448 crl = sk_X509_CRL_value(crls, i);
1449 X509_STORE_add_crl(st, crl);
1454 int ssl_ctx_add_crls(SSL_CTX *ctx, STACK_OF(X509_CRL) *crls, int crl_download)
1457 st = SSL_CTX_get_cert_store(ctx);
1458 add_crls_store(st, crls);
1460 store_setup_crl_download(st);
1464 int ssl_load_stores(SSL_CTX *ctx,
1465 const char *vfyCApath, const char *vfyCAfile,
1466 const char *chCApath, const char *chCAfile,
1467 STACK_OF(X509_CRL) *crls, int crl_download)
1469 X509_STORE *vfy = NULL, *ch = NULL;
1471 if (vfyCApath || vfyCAfile) {
1472 vfy = X509_STORE_new();
1473 if (!X509_STORE_load_locations(vfy, vfyCAfile, vfyCApath))
1475 add_crls_store(vfy, crls);
1476 SSL_CTX_set1_verify_cert_store(ctx, vfy);
1478 store_setup_crl_download(vfy);
1480 if (chCApath || chCAfile) {
1481 ch = X509_STORE_new();
1482 if (!X509_STORE_load_locations(ch, chCAfile, chCApath))
1484 SSL_CTX_set1_chain_cert_store(ctx, ch);
1488 X509_STORE_free(vfy);
1489 X509_STORE_free(ch);
1493 /* Verbose print out of security callback */
1498 int (*old_cb) (SSL *s, SSL_CTX *ctx, int op, int bits, int nid,
1499 void *other, void *ex);
1500 } security_debug_ex;
1502 static int security_callback_debug(SSL *s, SSL_CTX *ctx,
1503 int op, int bits, int nid,
1504 void *other, void *ex)
1506 security_debug_ex *sdb = ex;
1507 int rv, show_bits = 1, cert_md = 0;
1509 rv = sdb->old_cb(s, ctx, op, bits, nid, other, ex);
1510 if (rv == 1 && sdb->verbose < 2)
1512 BIO_puts(sdb->out, "Security callback: ");
1515 case SSL_SECOP_CIPHER_SUPPORTED:
1516 nm = "Supported Ciphersuite";
1518 case SSL_SECOP_CIPHER_SHARED:
1519 nm = "Shared Ciphersuite";
1521 case SSL_SECOP_CIPHER_CHECK:
1522 nm = "Check Ciphersuite";
1524 case SSL_SECOP_TICKET:
1525 BIO_puts(sdb->out, "Session ticket");
1529 case SSL_SECOP_COMPRESSION:
1530 BIO_puts(sdb->out, "SSL compression");
1534 #ifndef OPENSSL_NO_DH
1535 case SSL_SECOP_TMP_DH:
1536 nm = "Temp DH key bits";
1539 case SSL_SECOP_CURVE_SUPPORTED:
1540 nm = "Supported Curve";
1542 case SSL_SECOP_CURVE_SHARED:
1543 nm = "Shared Curve";
1545 case SSL_SECOP_CURVE_CHECK:
1548 case SSL_SECOP_VERSION:
1549 BIO_printf(sdb->out, "Version=%s", ssl_version_str(nid));
1553 case SSL_SECOP_SIGALG_SUPPORTED:
1554 nm = "Supported Signature Algorithm digest";
1556 case SSL_SECOP_SIGALG_SHARED:
1557 nm = "Shared Signature Algorithm digest";
1559 case SSL_SECOP_SIGALG_CHECK:
1560 nm = "Check Signature Algorithm digest";
1562 case SSL_SECOP_SIGALG_MASK:
1563 nm = "Signature Algorithm mask";
1565 case SSL_SECOP_EE_KEY:
1566 nm = "Certificate chain EE key";
1568 case SSL_SECOP_CA_KEY:
1569 nm = "Certificate chain CA key";
1571 case SSL_SECOP_CA_MD:
1573 nm = "Certificate chain CA digest";
1575 case SSL_SECOP_PEER_EE_KEY:
1576 nm = "Peer Chain EE key";
1578 case SSL_SECOP_PEER_CA_KEY:
1579 nm = "Peer Chain CA key";
1581 case SSL_SECOP_PEER_CA_MD:
1583 nm = "Peer chain CA digest";
1589 BIO_printf(sdb->out, "%s=", nm);
1591 switch (op & SSL_SECOP_OTHER_TYPE) {
1593 case SSL_SECOP_OTHER_CIPHER:
1594 BIO_puts(sdb->out, SSL_CIPHER_get_name(other));
1597 #ifndef OPENSSL_NO_EC
1598 case SSL_SECOP_OTHER_CURVE:
1601 cname = EC_curve_nid2nist(nid);
1603 cname = OBJ_nid2sn(nid);
1604 BIO_puts(sdb->out, cname);
1609 case SSL_SECOP_OTHER_DH:
1612 BIO_printf(sdb->out, "%d", BN_num_bits(dh->p));
1615 case SSL_SECOP_OTHER_CERT:
1618 int sig_nid = X509_get_signature_nid(other);
1619 BIO_puts(sdb->out, OBJ_nid2sn(sig_nid));
1621 EVP_PKEY *pkey = X509_get_pubkey(other);
1622 const char *algname = "";
1623 EVP_PKEY_asn1_get0_info(NULL, NULL, NULL, NULL,
1624 &algname, EVP_PKEY_get0_asn1(pkey));
1625 BIO_printf(sdb->out, "%s, bits=%d",
1626 algname, EVP_PKEY_bits(pkey));
1627 EVP_PKEY_free(pkey);
1631 case SSL_SECOP_OTHER_SIGALG:
1633 const unsigned char *salg = other;
1634 const char *sname = NULL;
1636 case TLSEXT_signature_anonymous:
1637 sname = "anonymous";
1639 case TLSEXT_signature_rsa:
1642 case TLSEXT_signature_dsa:
1645 case TLSEXT_signature_ecdsa:
1650 BIO_puts(sdb->out, OBJ_nid2sn(nid));
1652 BIO_printf(sdb->out, ", algorithm=%s", sname);
1654 BIO_printf(sdb->out, ", algid=%d", salg[1]);
1661 BIO_printf(sdb->out, ", security bits=%d", bits);
1662 BIO_printf(sdb->out, ": %s\n", rv ? "yes" : "no");
1666 void ssl_ctx_security_debug(SSL_CTX *ctx, int verbose)
1668 static security_debug_ex sdb;
1671 sdb.verbose = verbose;
1672 sdb.old_cb = SSL_CTX_get_security_callback(ctx);
1673 SSL_CTX_set_security_callback(ctx, security_callback_debug);
1674 SSL_CTX_set0_security_ex_data(ctx, &sdb);