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 */
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 unsigned char cookie_secret[COOKIE_SECRET_LENGTH];
135 int cookie_initialized = 0;
137 int verify_callback(int ok, X509_STORE_CTX *ctx)
142 err_cert = X509_STORE_CTX_get_current_cert(ctx);
143 err = X509_STORE_CTX_get_error(ctx);
144 depth = X509_STORE_CTX_get_error_depth(ctx);
146 if (!verify_quiet || !ok) {
147 BIO_printf(bio_err, "depth=%d ", depth);
149 X509_NAME_print_ex(bio_err,
150 X509_get_subject_name(err_cert),
152 BIO_puts(bio_err, "\n");
154 BIO_puts(bio_err, "<no cert>\n");
157 BIO_printf(bio_err, "verify error:num=%d:%s\n", err,
158 X509_verify_cert_error_string(err));
159 if (verify_depth >= depth) {
160 if (!verify_return_error)
162 verify_error = X509_V_OK;
165 verify_error = X509_V_ERR_CERT_CHAIN_TOO_LONG;
169 case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT:
170 BIO_puts(bio_err, "issuer= ");
171 X509_NAME_print_ex(bio_err, X509_get_issuer_name(err_cert),
173 BIO_puts(bio_err, "\n");
175 case X509_V_ERR_CERT_NOT_YET_VALID:
176 case X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD:
177 BIO_printf(bio_err, "notBefore=");
178 ASN1_TIME_print(bio_err, X509_get_notBefore(err_cert));
179 BIO_printf(bio_err, "\n");
181 case X509_V_ERR_CERT_HAS_EXPIRED:
182 case X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD:
183 BIO_printf(bio_err, "notAfter=");
184 ASN1_TIME_print(bio_err, X509_get_notAfter(err_cert));
185 BIO_printf(bio_err, "\n");
187 case X509_V_ERR_NO_EXPLICIT_POLICY:
192 if (err == X509_V_OK && ok == 2 && !verify_quiet)
194 if (ok && !verify_quiet)
195 BIO_printf(bio_err, "verify return:%d\n", ok);
199 int set_cert_stuff(SSL_CTX *ctx, char *cert_file, char *key_file)
201 if (cert_file != NULL) {
202 if (SSL_CTX_use_certificate_file(ctx, cert_file,
203 SSL_FILETYPE_PEM) <= 0) {
204 BIO_printf(bio_err, "unable to get certificate from '%s'\n",
206 ERR_print_errors(bio_err);
209 if (key_file == NULL)
210 key_file = cert_file;
211 if (SSL_CTX_use_PrivateKey_file(ctx, key_file, SSL_FILETYPE_PEM) <= 0) {
212 BIO_printf(bio_err, "unable to get private key from '%s'\n",
214 ERR_print_errors(bio_err);
219 * If we are using DSA, we can copy the parameters from the private
224 * Now we know that a key and cert have been set against the SSL
227 if (!SSL_CTX_check_private_key(ctx)) {
229 "Private key does not match the certificate public key\n");
236 int set_cert_key_stuff(SSL_CTX *ctx, X509 *cert, EVP_PKEY *key,
237 STACK_OF(X509) *chain, int build_chain)
239 int chflags = chain ? SSL_BUILD_CHAIN_FLAG_CHECK : 0;
242 if (SSL_CTX_use_certificate(ctx, cert) <= 0) {
243 BIO_printf(bio_err, "error setting certificate\n");
244 ERR_print_errors(bio_err);
248 if (SSL_CTX_use_PrivateKey(ctx, key) <= 0) {
249 BIO_printf(bio_err, "error setting private key\n");
250 ERR_print_errors(bio_err);
255 * Now we know that a key and cert have been set against the SSL context
257 if (!SSL_CTX_check_private_key(ctx)) {
259 "Private key does not match the certificate public key\n");
262 if (chain && !SSL_CTX_set1_chain(ctx, chain)) {
263 BIO_printf(bio_err, "error setting certificate chain\n");
264 ERR_print_errors(bio_err);
267 if (build_chain && !SSL_CTX_build_cert_chain(ctx, chflags)) {
268 BIO_printf(bio_err, "error building certificate chain\n");
269 ERR_print_errors(bio_err);
275 static void ssl_print_client_cert_types(BIO *bio, SSL *s)
277 const unsigned char *p;
279 int cert_type_num = SSL_get0_certificate_types(s, &p);
282 BIO_puts(bio, "Client Certificate Types: ");
283 for (i = 0; i < cert_type_num; i++) {
284 unsigned char cert_type = p[i];
287 case TLS_CT_RSA_SIGN:
291 case TLS_CT_DSS_SIGN:
295 case TLS_CT_RSA_FIXED_DH:
296 cname = "RSA fixed DH";
299 case TLS_CT_DSS_FIXED_DH:
300 cname = "DSS fixed DH";
303 case TLS_CT_ECDSA_SIGN:
304 cname = "ECDSA sign";
307 case TLS_CT_RSA_FIXED_ECDH:
308 cname = "RSA fixed ECDH";
311 case TLS_CT_ECDSA_FIXED_ECDH:
312 cname = "ECDSA fixed ECDH";
315 case TLS_CT_GOST94_SIGN:
316 cname = "GOST94 Sign";
319 case TLS_CT_GOST01_SIGN:
320 cname = "GOST01 Sign";
331 BIO_puts(bio, cname);
333 BIO_printf(bio, "UNKNOWN (%d),", cert_type);
338 static int do_print_sigalgs(BIO *out, SSL *s, int shared)
341 client = SSL_is_server(s) ? 0 : 1;
343 nsig = SSL_get_shared_sigalgs(s, -1, NULL, NULL, NULL, NULL, NULL);
345 nsig = SSL_get_sigalgs(s, -1, NULL, NULL, NULL, NULL, NULL);
350 BIO_puts(out, "Shared ");
353 BIO_puts(out, "Requested ");
354 BIO_puts(out, "Signature Algorithms: ");
355 for (i = 0; i < nsig; i++) {
356 int hash_nid, sign_nid;
357 unsigned char rhash, rsign;
358 const char *sstr = NULL;
360 SSL_get_shared_sigalgs(s, i, &sign_nid, &hash_nid, NULL,
363 SSL_get_sigalgs(s, i, &sign_nid, &hash_nid, NULL, &rsign, &rhash);
366 if (sign_nid == EVP_PKEY_RSA)
368 else if (sign_nid == EVP_PKEY_DSA)
370 else if (sign_nid == EVP_PKEY_EC)
373 BIO_printf(out, "%s+", sstr);
375 BIO_printf(out, "0x%02X+", (int)rsign);
376 if (hash_nid != NID_undef)
377 BIO_printf(out, "%s", OBJ_nid2sn(hash_nid));
379 BIO_printf(out, "0x%02X", (int)rhash);
385 int ssl_print_sigalgs(BIO *out, SSL *s)
388 if (!SSL_is_server(s))
389 ssl_print_client_cert_types(out, s);
390 do_print_sigalgs(out, s, 0);
391 do_print_sigalgs(out, s, 1);
392 if (SSL_get_peer_signature_nid(s, &mdnid))
393 BIO_printf(out, "Peer signing digest: %s\n", OBJ_nid2sn(mdnid));
397 #ifndef OPENSSL_NO_EC
398 int ssl_print_point_formats(BIO *out, SSL *s)
401 const char *pformats;
402 nformats = SSL_get0_ec_point_formats(s, &pformats);
405 BIO_puts(out, "Supported Elliptic Curve Point Formats: ");
406 for (i = 0; i < nformats; i++, pformats++) {
410 case TLSEXT_ECPOINTFORMAT_uncompressed:
411 BIO_puts(out, "uncompressed");
414 case TLSEXT_ECPOINTFORMAT_ansiX962_compressed_prime:
415 BIO_puts(out, "ansiX962_compressed_prime");
418 case TLSEXT_ECPOINTFORMAT_ansiX962_compressed_char2:
419 BIO_puts(out, "ansiX962_compressed_char2");
423 BIO_printf(out, "unknown(%d)", (int)*pformats);
429 BIO_puts(out, "NONE");
434 int ssl_print_curves(BIO *out, SSL *s, int noshared)
436 int i, ncurves, *curves, nid;
439 ncurves = SSL_get1_curves(s, NULL);
442 curves = OPENSSL_malloc(ncurves * sizeof(int));
444 BIO_printf(out, "Out of memory\n");
447 SSL_get1_curves(s, curves);
449 BIO_puts(out, "Supported Elliptic Curves: ");
450 for (i = 0; i < ncurves; i++) {
454 /* If unrecognised print out hex version */
455 if (nid & TLSEXT_nid_unknown)
456 BIO_printf(out, "0x%04X", nid & 0xFFFF);
458 /* Use NIST name for curve if it exists */
459 cname = EC_curve_nid2nist(nid);
461 cname = OBJ_nid2sn(nid);
462 BIO_printf(out, "%s", cname);
466 BIO_puts(out, "NONE");
467 OPENSSL_free(curves);
472 BIO_puts(out, "\nShared Elliptic curves: ");
473 ncurves = SSL_get_shared_curve(s, -1);
474 for (i = 0; i < ncurves; i++) {
477 nid = SSL_get_shared_curve(s, i);
478 cname = EC_curve_nid2nist(nid);
480 cname = OBJ_nid2sn(nid);
481 BIO_printf(out, "%s", cname);
484 BIO_puts(out, "NONE");
489 int ssl_print_tmp_key(BIO *out, SSL *s)
492 if (!SSL_get_server_tmp_key(s, &key))
494 BIO_puts(out, "Server Temp Key: ");
495 switch (EVP_PKEY_id(key)) {
497 BIO_printf(out, "RSA, %d bits\n", EVP_PKEY_bits(key));
501 BIO_printf(out, "DH, %d bits\n", EVP_PKEY_bits(key));
503 #ifndef OPENSSL_NO_EC
506 EC_KEY *ec = EVP_PKEY_get1_EC_KEY(key);
509 nid = EC_GROUP_get_curve_name(EC_KEY_get0_group(ec));
511 cname = EC_curve_nid2nist(nid);
513 cname = OBJ_nid2sn(nid);
514 BIO_printf(out, "ECDH, %s, %d bits\n", cname, EVP_PKEY_bits(key));
522 long bio_dump_callback(BIO *bio, int cmd, const char *argp,
523 int argi, long argl, long ret)
527 out = (BIO *)BIO_get_callback_arg(bio);
531 if (cmd == (BIO_CB_READ | BIO_CB_RETURN)) {
532 BIO_printf(out, "read from %p [%p] (%lu bytes => %ld (0x%lX))\n",
533 (void *)bio, argp, (unsigned long)argi, ret, ret);
534 BIO_dump(out, argp, (int)ret);
536 } else if (cmd == (BIO_CB_WRITE | BIO_CB_RETURN)) {
537 BIO_printf(out, "write to %p [%p] (%lu bytes => %ld (0x%lX))\n",
538 (void *)bio, argp, (unsigned long)argi, ret, ret);
539 BIO_dump(out, argp, (int)ret);
544 void apps_ssl_info_callback(const SSL *s, int where, int ret)
549 w = where & ~SSL_ST_MASK;
551 if (w & SSL_ST_CONNECT)
553 else if (w & SSL_ST_ACCEPT)
558 if (where & SSL_CB_LOOP) {
559 BIO_printf(bio_err, "%s:%s\n", str, SSL_state_string_long(s));
560 } else if (where & SSL_CB_ALERT) {
561 str = (where & SSL_CB_READ) ? "read" : "write";
562 BIO_printf(bio_err, "SSL3 alert %s:%s:%s\n",
564 SSL_alert_type_string_long(ret),
565 SSL_alert_desc_string_long(ret));
566 } else if (where & SSL_CB_EXIT) {
568 BIO_printf(bio_err, "%s:failed in %s\n",
569 str, SSL_state_string_long(s));
571 BIO_printf(bio_err, "%s:error in %s\n",
572 str, SSL_state_string_long(s));
577 static const char *ssl_version_str(int version)
591 return "DTLS 1.0 (bad)";
597 void msg_cb(int write_p, int version, int content_type, const void *buf,
598 size_t len, SSL *ssl, void *arg)
601 const char *str_write_p, *str_version, *str_content_type =
602 "", *str_details1 = "", *str_details2 = "";
604 str_write_p = write_p ? ">>>" : "<<<";
606 str_version = ssl_version_str(version);
608 if (version == SSL3_VERSION ||
609 version == TLS1_VERSION ||
610 version == TLS1_1_VERSION ||
611 version == TLS1_2_VERSION ||
612 version == DTLS1_VERSION || version == DTLS1_BAD_VER) {
613 switch (content_type) {
615 str_content_type = "ChangeCipherSpec";
618 str_content_type = "Alert";
621 str_content_type = "Handshake";
625 if (content_type == 21) { /* Alert */
626 str_details1 = ", ???";
629 switch (((const unsigned char *)buf)[0]) {
631 str_details1 = ", warning";
634 str_details1 = ", fatal";
638 str_details2 = " ???";
639 switch (((const unsigned char *)buf)[1]) {
641 str_details2 = " close_notify";
644 str_details2 = " unexpected_message";
647 str_details2 = " bad_record_mac";
650 str_details2 = " decryption_failed";
653 str_details2 = " record_overflow";
656 str_details2 = " decompression_failure";
659 str_details2 = " handshake_failure";
662 str_details2 = " bad_certificate";
665 str_details2 = " unsupported_certificate";
668 str_details2 = " certificate_revoked";
671 str_details2 = " certificate_expired";
674 str_details2 = " certificate_unknown";
677 str_details2 = " illegal_parameter";
680 str_details2 = " unknown_ca";
683 str_details2 = " access_denied";
686 str_details2 = " decode_error";
689 str_details2 = " decrypt_error";
692 str_details2 = " export_restriction";
695 str_details2 = " protocol_version";
698 str_details2 = " insufficient_security";
701 str_details2 = " internal_error";
704 str_details2 = " user_canceled";
707 str_details2 = " no_renegotiation";
710 str_details2 = " unsupported_extension";
713 str_details2 = " certificate_unobtainable";
716 str_details2 = " unrecognized_name";
719 str_details2 = " bad_certificate_status_response";
722 str_details2 = " bad_certificate_hash_value";
725 str_details2 = " unknown_psk_identity";
731 if (content_type == 22) { /* Handshake */
732 str_details1 = "???";
735 switch (((const unsigned char *)buf)[0]) {
737 str_details1 = ", HelloRequest";
740 str_details1 = ", ClientHello";
743 str_details1 = ", ServerHello";
746 str_details1 = ", HelloVerifyRequest";
749 str_details1 = ", Certificate";
752 str_details1 = ", ServerKeyExchange";
755 str_details1 = ", CertificateRequest";
758 str_details1 = ", ServerHelloDone";
761 str_details1 = ", CertificateVerify";
764 str_details1 = ", ClientKeyExchange";
767 str_details1 = ", Finished";
772 #ifndef OPENSSL_NO_HEARTBEATS
773 if (content_type == 24) { /* Heartbeat */
774 str_details1 = ", Heartbeat";
777 switch (((const unsigned char *)buf)[0]) {
779 str_details1 = ", HeartbeatRequest";
782 str_details1 = ", HeartbeatResponse";
790 BIO_printf(bio, "%s %s%s [length %04lx]%s%s\n", str_write_p, str_version,
791 str_content_type, (unsigned long)len, str_details1,
797 BIO_printf(bio, " ");
799 for (i = 0; i < num; i++) {
800 if (i % 16 == 0 && i > 0)
801 BIO_printf(bio, "\n ");
802 BIO_printf(bio, " %02x", ((const unsigned char *)buf)[i]);
805 BIO_printf(bio, " ...");
806 BIO_printf(bio, "\n");
808 (void)BIO_flush(bio);
811 void tlsext_cb(SSL *s, int client_server, int type,
812 unsigned char *data, int len, void *arg)
818 case TLSEXT_TYPE_server_name:
819 extname = "server name";
822 case TLSEXT_TYPE_max_fragment_length:
823 extname = "max fragment length";
826 case TLSEXT_TYPE_client_certificate_url:
827 extname = "client certificate URL";
830 case TLSEXT_TYPE_trusted_ca_keys:
831 extname = "trusted CA keys";
834 case TLSEXT_TYPE_truncated_hmac:
835 extname = "truncated HMAC";
838 case TLSEXT_TYPE_status_request:
839 extname = "status request";
842 case TLSEXT_TYPE_user_mapping:
843 extname = "user mapping";
846 case TLSEXT_TYPE_client_authz:
847 extname = "client authz";
850 case TLSEXT_TYPE_server_authz:
851 extname = "server authz";
854 case TLSEXT_TYPE_cert_type:
855 extname = "cert type";
858 case TLSEXT_TYPE_elliptic_curves:
859 extname = "elliptic curves";
862 case TLSEXT_TYPE_ec_point_formats:
863 extname = "EC point formats";
866 case TLSEXT_TYPE_srp:
870 case TLSEXT_TYPE_signature_algorithms:
871 extname = "signature algorithms";
874 case TLSEXT_TYPE_use_srtp:
875 extname = "use SRTP";
878 case TLSEXT_TYPE_heartbeat:
879 extname = "heartbeat";
882 case TLSEXT_TYPE_session_ticket:
883 extname = "session ticket";
886 case TLSEXT_TYPE_renegotiate:
887 extname = "renegotiation info";
890 #ifdef TLSEXT_TYPE_next_proto_neg
891 case TLSEXT_TYPE_next_proto_neg:
892 extname = "next protocol";
895 #ifdef TLSEXT_TYPE_encrypt_then_mac
896 case TLSEXT_TYPE_encrypt_then_mac:
897 extname = "encrypt-then-mac";
900 case TLSEXT_TYPE_padding:
901 extname = "TLS padding";
910 BIO_printf(bio, "TLS %s extension \"%s\" (id=%d), len=%d\n",
911 client_server ? "server" : "client", extname, type, len);
912 BIO_dump(bio, (char *)data, len);
913 (void)BIO_flush(bio);
916 int generate_cookie_callback(SSL *ssl, unsigned char *cookie,
917 unsigned int *cookie_len)
919 unsigned char *buffer, result[EVP_MAX_MD_SIZE];
920 unsigned int length, resultlength;
923 struct sockaddr_in s4;
925 struct sockaddr_in6 s6;
929 /* Initialize a random secret */
930 if (!cookie_initialized) {
931 if (RAND_bytes(cookie_secret, COOKIE_SECRET_LENGTH) <= 0) {
932 BIO_printf(bio_err, "error setting random cookie secret\n");
935 cookie_initialized = 1;
938 /* Read peer information */
939 (void)BIO_dgram_get_peer(SSL_get_rbio(ssl), &peer);
941 /* Create buffer with peer's address and port */
943 switch (peer.sa.sa_family) {
945 length += sizeof(struct in_addr);
946 length += sizeof(peer.s4.sin_port);
950 length += sizeof(struct in6_addr);
951 length += sizeof(peer.s6.sin6_port);
958 buffer = OPENSSL_malloc(length);
960 if (buffer == NULL) {
961 BIO_printf(bio_err, "out of memory\n");
965 switch (peer.sa.sa_family) {
967 memcpy(buffer, &peer.s4.sin_port, sizeof(peer.s4.sin_port));
968 memcpy(buffer + sizeof(peer.s4.sin_port),
969 &peer.s4.sin_addr, sizeof(struct in_addr));
973 memcpy(buffer, &peer.s6.sin6_port, sizeof(peer.s6.sin6_port));
974 memcpy(buffer + sizeof(peer.s6.sin6_port),
975 &peer.s6.sin6_addr, sizeof(struct in6_addr));
983 /* Calculate HMAC of buffer using the secret */
984 HMAC(EVP_sha1(), cookie_secret, COOKIE_SECRET_LENGTH,
985 buffer, length, result, &resultlength);
986 OPENSSL_free(buffer);
988 memcpy(cookie, result, resultlength);
989 *cookie_len = resultlength;
994 int verify_cookie_callback(SSL *ssl, unsigned char *cookie,
995 unsigned int cookie_len)
997 unsigned char *buffer, result[EVP_MAX_MD_SIZE];
998 unsigned int length, resultlength;
1001 struct sockaddr_in s4;
1002 #if OPENSSL_USE_IPV6
1003 struct sockaddr_in6 s6;
1007 /* If secret isn't initialized yet, the cookie can't be valid */
1008 if (!cookie_initialized)
1011 /* Read peer information */
1012 (void)BIO_dgram_get_peer(SSL_get_rbio(ssl), &peer);
1014 /* Create buffer with peer's address and port */
1016 switch (peer.sa.sa_family) {
1018 length += sizeof(struct in_addr);
1019 length += sizeof(peer.s4.sin_port);
1021 #if OPENSSL_USE_IPV6
1023 length += sizeof(struct in6_addr);
1024 length += sizeof(peer.s6.sin6_port);
1031 buffer = OPENSSL_malloc(length);
1033 if (buffer == NULL) {
1034 BIO_printf(bio_err, "out of memory\n");
1038 switch (peer.sa.sa_family) {
1040 memcpy(buffer, &peer.s4.sin_port, sizeof(peer.s4.sin_port));
1041 memcpy(buffer + sizeof(peer.s4.sin_port),
1042 &peer.s4.sin_addr, sizeof(struct in_addr));
1044 #if OPENSSL_USE_IPV6
1046 memcpy(buffer, &peer.s6.sin6_port, sizeof(peer.s6.sin6_port));
1047 memcpy(buffer + sizeof(peer.s6.sin6_port),
1048 &peer.s6.sin6_addr, sizeof(struct in6_addr));
1056 /* Calculate HMAC of buffer using the secret */
1057 HMAC(EVP_sha1(), cookie_secret, COOKIE_SECRET_LENGTH,
1058 buffer, length, result, &resultlength);
1059 OPENSSL_free(buffer);
1061 if (cookie_len == resultlength
1062 && memcmp(result, cookie, resultlength) == 0)
1069 * Example of extended certificate handling. Where the standard support of
1070 * one certificate per algorithm is not sufficient an application can decide
1071 * which certificate(s) to use at runtime based on whatever criteria it deems
1075 /* Linked list of certificates, keys and chains */
1076 struct ssl_excert_st {
1078 const char *certfile;
1080 const char *keyfile;
1081 const char *chainfile;
1084 STACK_OF(X509) *chain;
1086 struct ssl_excert_st *next, *prev;
1089 struct chain_flags {
1094 struct chain_flags chain_flags_list[] = {
1095 {CERT_PKEY_VALID, "Overall Validity"},
1096 {CERT_PKEY_SIGN, "Sign with EE key"},
1097 {CERT_PKEY_EE_SIGNATURE, "EE signature"},
1098 {CERT_PKEY_CA_SIGNATURE, "CA signature"},
1099 {CERT_PKEY_EE_PARAM, "EE key parameters"},
1100 {CERT_PKEY_CA_PARAM, "CA key parameters"},
1101 {CERT_PKEY_EXPLICIT_SIGN, "Explicity sign with EE key"},
1102 {CERT_PKEY_ISSUER_NAME, "Issuer Name"},
1103 {CERT_PKEY_CERT_TYPE, "Certificate Type"},
1107 static void print_chain_flags(SSL *s, int flags)
1109 struct chain_flags *ctmp = chain_flags_list;
1111 while (ctmp->name) {
1112 BIO_printf(bio_err, "\t%s: %s\n", ctmp->name,
1113 flags & ctmp->flag ? "OK" : "NOT OK");
1116 BIO_printf(bio_err, "\tSuite B: ");
1117 if (SSL_set_cert_flags(s, 0) & SSL_CERT_FLAG_SUITEB_128_LOS)
1118 BIO_puts(bio_err, flags & CERT_PKEY_SUITEB ? "OK\n" : "NOT OK\n");
1120 BIO_printf(bio_err, "not tested\n");
1124 * Very basic selection callback: just use any certificate chain reported as
1125 * valid. More sophisticated could prioritise according to local policy.
1127 static int set_cert_cb(SSL *ssl, void *arg)
1130 SSL_EXCERT *exc = arg;
1131 #ifdef CERT_CB_TEST_RETRY
1132 static int retry_cnt;
1133 if (retry_cnt < 5) {
1135 fprintf(stderr, "Certificate callback retry test: count %d\n",
1140 SSL_certs_clear(ssl);
1146 * Go to end of list and traverse backwards since we prepend newer
1147 * entries this retains the original order.
1156 rv = SSL_check_chain(ssl, exc->cert, exc->key, exc->chain);
1157 BIO_printf(bio_err, "Checking cert chain %d:\nSubject: ", i);
1158 X509_NAME_print_ex(bio_err, X509_get_subject_name(exc->cert), 0,
1160 BIO_puts(bio_err, "\n");
1161 print_chain_flags(ssl, rv);
1162 if (rv & CERT_PKEY_VALID) {
1163 if (!SSL_use_certificate(ssl, exc->cert)
1164 || !SSL_use_PrivateKey(ssl, exc->key)) {
1168 * NB: we wouldn't normally do this as it is not efficient
1169 * building chains on each connection better to cache the chain
1172 if (exc->build_chain) {
1173 if (!SSL_build_cert_chain(ssl, 0))
1175 } else if (exc->chain)
1176 SSL_set1_chain(ssl, exc->chain);
1183 void ssl_ctx_set_excert(SSL_CTX *ctx, SSL_EXCERT *exc)
1185 SSL_CTX_set_cert_cb(ctx, set_cert_cb, exc);
1188 static int ssl_excert_prepend(SSL_EXCERT **pexc)
1191 exc = OPENSSL_malloc(sizeof(SSL_EXCERT));
1194 exc->certfile = NULL;
1195 exc->keyfile = NULL;
1196 exc->chainfile = NULL;
1201 exc->build_chain = 0;
1207 exc->certform = exc->next->certform;
1208 exc->keyform = exc->next->keyform;
1209 exc->next->prev = exc;
1211 exc->certform = FORMAT_PEM;
1212 exc->keyform = FORMAT_PEM;
1218 void ssl_excert_free(SSL_EXCERT *exc)
1223 X509_free(exc->cert);
1224 EVP_PKEY_free(exc->key);
1226 sk_X509_pop_free(exc->chain, X509_free);
1233 int load_excert(SSL_EXCERT **pexc)
1235 SSL_EXCERT *exc = *pexc;
1238 /* If nothing in list, free and set to NULL */
1239 if (!exc->certfile && !exc->next) {
1240 ssl_excert_free(exc);
1244 for (; exc; exc = exc->next) {
1245 if (!exc->certfile) {
1246 BIO_printf(bio_err, "Missing filename\n");
1249 exc->cert = load_cert(exc->certfile, exc->certform,
1250 NULL, NULL, "Server Certificate");
1254 exc->key = load_key(exc->keyfile, exc->keyform,
1255 0, NULL, NULL, "Server Key");
1257 exc->key = load_key(exc->certfile, exc->certform,
1258 0, NULL, NULL, "Server Key");
1262 if (exc->chainfile) {
1263 exc->chain = load_certs(exc->chainfile, FORMAT_PEM,
1264 NULL, NULL, "Server Chain");
1272 enum range { OPT_X_ENUM };
1274 int args_excert(int opt, SSL_EXCERT **pexc)
1276 SSL_EXCERT *exc = *pexc;
1278 assert(opt > OPT_X__FIRST);
1279 assert(opt < OPT_X__LAST);
1282 if (!ssl_excert_prepend(&exc)) {
1283 BIO_printf(bio_err, " %s: Error initialising xcert\n",
1290 switch ((enum range)opt) {
1295 if (exc->certfile && !ssl_excert_prepend(&exc)) {
1296 BIO_printf(bio_err, "%s: Error adding xcert\n", opt_getprog());
1299 exc->certfile = opt_arg();
1303 BIO_printf(bio_err, "%s: Key already specified\n", opt_getprog());
1306 exc->keyfile = opt_arg();
1309 if (exc->chainfile) {
1310 BIO_printf(bio_err, "%s: Chain already specified\n",
1314 exc->chainfile = opt_arg();
1316 case OPT_X_CHAIN_BUILD:
1317 exc->build_chain = 1;
1319 case OPT_X_CERTFORM:
1320 if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &exc->certform))
1324 if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &exc->keyform))
1331 ERR_print_errors(bio_err);
1333 ssl_excert_free(exc);
1338 static void print_raw_cipherlist(SSL *s)
1340 const unsigned char *rlist;
1341 static const unsigned char scsv_id[] = { 0, 0, 0xFF };
1342 size_t i, rlistlen, num;
1343 if (!SSL_is_server(s))
1345 num = SSL_get0_raw_cipherlist(s, NULL);
1346 rlistlen = SSL_get0_raw_cipherlist(s, &rlist);
1347 BIO_puts(bio_err, "Client cipher list: ");
1348 for (i = 0; i < rlistlen; i += num, rlist += num) {
1349 const SSL_CIPHER *c = SSL_CIPHER_find(s, rlist);
1351 BIO_puts(bio_err, ":");
1353 BIO_puts(bio_err, SSL_CIPHER_get_name(c));
1354 else if (!memcmp(rlist, scsv_id - num + 3, num))
1355 BIO_puts(bio_err, "SCSV");
1358 BIO_puts(bio_err, "0x");
1359 for (j = 0; j < num; j++)
1360 BIO_printf(bio_err, "%02X", rlist[j]);
1363 BIO_puts(bio_err, "\n");
1366 void print_ssl_summary(SSL *s)
1368 const SSL_CIPHER *c;
1370 /* const char *pnam = SSL_is_server(s) ? "client" : "server"; */
1372 BIO_printf(bio_err, "Protocol version: %s\n", SSL_get_version(s));
1373 print_raw_cipherlist(s);
1374 c = SSL_get_current_cipher(s);
1375 BIO_printf(bio_err, "Ciphersuite: %s\n", SSL_CIPHER_get_name(c));
1376 do_print_sigalgs(bio_err, s, 0);
1377 peer = SSL_get_peer_certificate(s);
1380 BIO_puts(bio_err, "Peer certificate: ");
1381 X509_NAME_print_ex(bio_err, X509_get_subject_name(peer),
1382 0, XN_FLAG_ONELINE);
1383 BIO_puts(bio_err, "\n");
1384 if (SSL_get_peer_signature_nid(s, &nid))
1385 BIO_printf(bio_err, "Hash used: %s\n", OBJ_nid2sn(nid));
1387 BIO_puts(bio_err, "No peer certificate\n");
1390 #ifndef OPENSSL_NO_EC
1391 ssl_print_point_formats(bio_err, s);
1392 if (SSL_is_server(s))
1393 ssl_print_curves(bio_err, s, 1);
1395 ssl_print_tmp_key(bio_err, s);
1397 if (!SSL_is_server(s))
1398 ssl_print_tmp_key(bio_err, s);
1402 int config_ctx(SSL_CONF_CTX *cctx, STACK_OF(OPENSSL_STRING) *str,
1403 SSL_CTX *ctx, int no_ecdhe, int no_jpake)
1407 SSL_CONF_CTX_set_ssl_ctx(cctx, ctx);
1408 for (i = 0; i < sk_OPENSSL_STRING_num(str); i += 2) {
1409 const char *flag = sk_OPENSSL_STRING_value(str, i);
1410 const char *arg = sk_OPENSSL_STRING_value(str, i + 1);
1411 /* If no_ecdhe or named curve already specified don't need a default. */
1412 if (!no_ecdhe && !strcmp(flag, "-named_curve"))
1414 #ifndef OPENSSL_NO_JPAKE
1415 if (!no_jpake && !strcmp(flag, "-cipher")) {
1416 BIO_puts(bio_err, "JPAKE sets cipher to PSK\n");
1420 if (SSL_CONF_cmd(cctx, flag, arg) <= 0) {
1422 BIO_printf(bio_err, "Error with command: \"%s %s\"\n",
1425 BIO_printf(bio_err, "Error with command: \"%s\"\n", flag);
1426 ERR_print_errors(bio_err);
1431 * This is a special case to keep existing s_server functionality: if we
1432 * don't have any curve specified *and* we haven't disabled ECDHE then
1436 if (SSL_CONF_cmd(cctx, "-named_curve", "P-256") <= 0) {
1437 BIO_puts(bio_err, "Error setting EC curve\n");
1438 ERR_print_errors(bio_err);
1442 #ifndef OPENSSL_NO_JPAKE
1444 if (SSL_CONF_cmd(cctx, "-cipher", "PSK") <= 0) {
1445 BIO_puts(bio_err, "Error setting cipher to PSK\n");
1446 ERR_print_errors(bio_err);
1451 if (!SSL_CONF_CTX_finish(cctx)) {
1452 BIO_puts(bio_err, "Error finishing context\n");
1453 ERR_print_errors(bio_err);
1459 static int add_crls_store(X509_STORE *st, STACK_OF(X509_CRL) *crls)
1463 for (i = 0; i < sk_X509_CRL_num(crls); i++) {
1464 crl = sk_X509_CRL_value(crls, i);
1465 X509_STORE_add_crl(st, crl);
1470 int ssl_ctx_add_crls(SSL_CTX *ctx, STACK_OF(X509_CRL) *crls, int crl_download)
1473 st = SSL_CTX_get_cert_store(ctx);
1474 add_crls_store(st, crls);
1476 store_setup_crl_download(st);
1480 int ssl_load_stores(SSL_CTX *ctx,
1481 const char *vfyCApath, const char *vfyCAfile,
1482 const char *chCApath, const char *chCAfile,
1483 STACK_OF(X509_CRL) *crls, int crl_download)
1485 X509_STORE *vfy = NULL, *ch = NULL;
1487 if (vfyCApath || vfyCAfile) {
1488 vfy = X509_STORE_new();
1489 if (!X509_STORE_load_locations(vfy, vfyCAfile, vfyCApath))
1491 add_crls_store(vfy, crls);
1492 SSL_CTX_set1_verify_cert_store(ctx, vfy);
1494 store_setup_crl_download(vfy);
1496 if (chCApath || chCAfile) {
1497 ch = X509_STORE_new();
1498 if (!X509_STORE_load_locations(ch, chCAfile, chCApath))
1500 SSL_CTX_set1_chain_cert_store(ctx, ch);
1505 X509_STORE_free(vfy);
1507 X509_STORE_free(ch);
1511 /* Verbose print out of security callback */
1516 int (*old_cb) (SSL *s, SSL_CTX *ctx, int op, int bits, int nid,
1517 void *other, void *ex);
1518 } security_debug_ex;
1520 static int security_callback_debug(SSL *s, SSL_CTX *ctx,
1521 int op, int bits, int nid,
1522 void *other, void *ex)
1524 security_debug_ex *sdb = ex;
1525 int rv, show_bits = 1, cert_md = 0;
1527 rv = sdb->old_cb(s, ctx, op, bits, nid, other, ex);
1528 if (rv == 1 && sdb->verbose < 2)
1530 BIO_puts(sdb->out, "Security callback: ");
1533 case SSL_SECOP_CIPHER_SUPPORTED:
1534 nm = "Supported Ciphersuite";
1536 case SSL_SECOP_CIPHER_SHARED:
1537 nm = "Shared Ciphersuite";
1539 case SSL_SECOP_CIPHER_CHECK:
1540 nm = "Check Ciphersuite";
1542 case SSL_SECOP_TICKET:
1543 BIO_puts(sdb->out, "Session ticket");
1547 case SSL_SECOP_COMPRESSION:
1548 BIO_puts(sdb->out, "SSL compression");
1552 #ifndef OPENSSL_NO_DH
1553 case SSL_SECOP_TMP_DH:
1554 nm = "Temp DH key bits";
1557 case SSL_SECOP_CURVE_SUPPORTED:
1558 nm = "Supported Curve";
1560 case SSL_SECOP_CURVE_SHARED:
1561 nm = "Shared Curve";
1563 case SSL_SECOP_CURVE_CHECK:
1566 case SSL_SECOP_VERSION:
1567 BIO_printf(sdb->out, "Version=%s", ssl_version_str(nid));
1571 case SSL_SECOP_SIGALG_SUPPORTED:
1572 nm = "Supported Signature Algorithm digest";
1574 case SSL_SECOP_SIGALG_SHARED:
1575 nm = "Shared Signature Algorithm digest";
1577 case SSL_SECOP_SIGALG_CHECK:
1578 nm = "Check Signature Algorithm digest";
1580 case SSL_SECOP_SIGALG_MASK:
1581 nm = "Signature Algorithm mask";
1583 case SSL_SECOP_EE_KEY:
1584 nm = "Certificate chain EE key";
1586 case SSL_SECOP_CA_KEY:
1587 nm = "Certificate chain CA key";
1589 case SSL_SECOP_CA_MD:
1591 nm = "Certificate chain CA digest";
1593 case SSL_SECOP_PEER_EE_KEY:
1594 nm = "Peer Chain EE key";
1596 case SSL_SECOP_PEER_CA_KEY:
1597 nm = "Peer Chain CA key";
1599 case SSL_SECOP_PEER_CA_MD:
1601 nm = "Peer chain CA digest";
1607 BIO_printf(sdb->out, "%s=", nm);
1609 switch (op & SSL_SECOP_OTHER_TYPE) {
1611 case SSL_SECOP_OTHER_CIPHER:
1612 BIO_puts(sdb->out, SSL_CIPHER_get_name(other));
1615 #ifndef OPENSSL_NO_EC
1616 case SSL_SECOP_OTHER_CURVE:
1619 cname = EC_curve_nid2nist(nid);
1621 cname = OBJ_nid2sn(nid);
1622 BIO_puts(sdb->out, cname);
1627 case SSL_SECOP_OTHER_DH:
1630 BIO_printf(sdb->out, "%d", BN_num_bits(dh->p));
1633 case SSL_SECOP_OTHER_CERT:
1636 int sig_nid = X509_get_signature_nid(other);
1637 BIO_puts(sdb->out, OBJ_nid2sn(sig_nid));
1639 EVP_PKEY *pkey = X509_get_pubkey(other);
1640 const char *algname = "";
1641 EVP_PKEY_asn1_get0_info(NULL, NULL, NULL, NULL,
1642 &algname, EVP_PKEY_get0_asn1(pkey));
1643 BIO_printf(sdb->out, "%s, bits=%d",
1644 algname, EVP_PKEY_bits(pkey));
1645 EVP_PKEY_free(pkey);
1649 case SSL_SECOP_OTHER_SIGALG:
1651 const unsigned char *salg = other;
1652 const char *sname = NULL;
1654 case TLSEXT_signature_anonymous:
1655 sname = "anonymous";
1657 case TLSEXT_signature_rsa:
1660 case TLSEXT_signature_dsa:
1663 case TLSEXT_signature_ecdsa:
1668 BIO_puts(sdb->out, OBJ_nid2sn(nid));
1670 BIO_printf(sdb->out, ", algorithm=%s", sname);
1672 BIO_printf(sdb->out, ", algid=%d", salg[1]);
1679 BIO_printf(sdb->out, ", security bits=%d", bits);
1680 BIO_printf(sdb->out, ": %s\n", rv ? "yes" : "no");
1684 void ssl_ctx_security_debug(SSL_CTX *ctx, int verbose)
1686 static security_debug_ex sdb;
1689 sdb.verbose = verbose;
1690 sdb.old_cb = SSL_CTX_get_security_callback(ctx);
1691 SSL_CTX_set_security_callback(ctx, security_callback_debug);
1692 SSL_CTX_set0_security_ex_data(ctx, &sdb);