New option to add CRLs for s_client and s_server.
[openssl.git] / apps / s_cb.c
1 /* apps/s_cb.c - callback functions used by s_client, s_server, and s_time */
2 /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
3  * All rights reserved.
4  *
5  * This package is an SSL implementation written
6  * by Eric Young (eay@cryptsoft.com).
7  * The implementation was written so as to conform with Netscapes SSL.
8  * 
9  * This library is free for commercial and non-commercial use as long as
10  * the following conditions are aheared to.  The following conditions
11  * apply to all code found in this distribution, be it the RC4, RSA,
12  * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
13  * included with this distribution is covered by the same copyright terms
14  * except that the holder is Tim Hudson (tjh@cryptsoft.com).
15  * 
16  * Copyright remains Eric Young's, and as such any Copyright notices in
17  * the code are not to be removed.
18  * If this package is used in a product, Eric Young should be given attribution
19  * as the author of the parts of the library used.
20  * This can be in the form of a textual message at program startup or
21  * in documentation (online or textual) provided with the package.
22  * 
23  * Redistribution and use in source and binary forms, with or without
24  * modification, are permitted provided that the following conditions
25  * are met:
26  * 1. Redistributions of source code must retain the copyright
27  *    notice, this list of conditions and the following disclaimer.
28  * 2. Redistributions in binary form must reproduce the above copyright
29  *    notice, this list of conditions and the following disclaimer in the
30  *    documentation and/or other materials provided with the distribution.
31  * 3. All advertising materials mentioning features or use of this software
32  *    must display the following acknowledgement:
33  *    "This product includes cryptographic software written by
34  *     Eric Young (eay@cryptsoft.com)"
35  *    The word 'cryptographic' can be left out if the rouines from the library
36  *    being used are not cryptographic related :-).
37  * 4. If you include any Windows specific code (or a derivative thereof) from 
38  *    the apps directory (application code) you must include an acknowledgement:
39  *    "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
40  * 
41  * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
42  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
43  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
44  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
45  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
46  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
47  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
48  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
49  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
50  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
51  * SUCH DAMAGE.
52  * 
53  * The licence and distribution terms for any publically available version or
54  * derivative of this code cannot be changed.  i.e. this code cannot simply be
55  * copied and put under another distribution licence
56  * [including the GNU Public Licence.]
57  */
58 /* ====================================================================
59  * Copyright (c) 1998-2006 The OpenSSL Project.  All rights reserved.
60  *
61  * Redistribution and use in source and binary forms, with or without
62  * modification, are permitted provided that the following conditions
63  * are met:
64  *
65  * 1. Redistributions of source code must retain the above copyright
66  *    notice, this list of conditions and the following disclaimer. 
67  *
68  * 2. Redistributions in binary form must reproduce the above copyright
69  *    notice, this list of conditions and the following disclaimer in
70  *    the documentation and/or other materials provided with the
71  *    distribution.
72  *
73  * 3. All advertising materials mentioning features or use of this
74  *    software must display the following acknowledgment:
75  *    "This product includes software developed by the OpenSSL Project
76  *    for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
77  *
78  * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
79  *    endorse or promote products derived from this software without
80  *    prior written permission. For written permission, please contact
81  *    openssl-core@openssl.org.
82  *
83  * 5. Products derived from this software may not be called "OpenSSL"
84  *    nor may "OpenSSL" appear in their names without prior written
85  *    permission of the OpenSSL Project.
86  *
87  * 6. Redistributions of any form whatsoever must retain the following
88  *    acknowledgment:
89  *    "This product includes software developed by the OpenSSL Project
90  *    for use in the OpenSSL Toolkit (http://www.openssl.org/)"
91  *
92  * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
93  * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
94  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
95  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
96  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
97  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
98  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
99  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
100  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
101  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
102  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
103  * OF THE POSSIBILITY OF SUCH DAMAGE.
104  * ====================================================================
105  *
106  * This product includes cryptographic software written by Eric Young
107  * (eay@cryptsoft.com).  This product includes software written by Tim
108  * Hudson (tjh@cryptsoft.com).
109  *
110  */
111
112 #include <stdio.h>
113 #include <stdlib.h>
114 #define USE_SOCKETS
115 #define NON_MAIN
116 #include "apps.h"
117 #undef NON_MAIN
118 #undef USE_SOCKETS
119 #include <openssl/err.h>
120 #include <openssl/rand.h>
121 #include <openssl/x509.h>
122 #include <openssl/ssl.h>
123 #include "s_apps.h"
124
125 #define COOKIE_SECRET_LENGTH    16
126
127 int verify_depth=0;
128 int verify_quiet=0;
129 int verify_error=X509_V_OK;
130 int verify_return_error=0;
131 unsigned char cookie_secret[COOKIE_SECRET_LENGTH];
132 int cookie_initialized=0;
133
134 int MS_CALLBACK verify_callback(int ok, X509_STORE_CTX *ctx)
135         {
136         X509 *err_cert;
137         int err,depth;
138
139         err_cert=X509_STORE_CTX_get_current_cert(ctx);
140         err=    X509_STORE_CTX_get_error(ctx);
141         depth=  X509_STORE_CTX_get_error_depth(ctx);
142
143         if (!verify_quiet || !ok)
144                 {
145                 BIO_printf(bio_err,"depth=%d ",depth);
146                 if (err_cert)
147                         {
148                         X509_NAME_print_ex(bio_err,
149                                         X509_get_subject_name(err_cert),
150                                         0, XN_FLAG_ONELINE);
151                         BIO_puts(bio_err, "\n");
152                         }
153                 else
154                         BIO_puts(bio_err, "<no cert>\n");
155                 }
156         if (!ok)
157                 {
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                         {
162                         if (!verify_return_error)
163                                 ok=1;
164                         verify_error=X509_V_OK;
165                         }
166                 else
167                         {
168                         ok=0;
169                         verify_error=X509_V_ERR_CERT_CHAIN_TOO_LONG;
170                         }
171                 }
172         switch (err)
173                 {
174         case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT:
175                 BIO_puts(bio_err,"issuer= ");
176                 X509_NAME_print_ex(bio_err, X509_get_issuer_name(err_cert),
177                                         0, XN_FLAG_ONELINE);
178                 BIO_puts(bio_err, "\n");
179                 break;
180         case X509_V_ERR_CERT_NOT_YET_VALID:
181         case X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD:
182                 BIO_printf(bio_err,"notBefore=");
183                 ASN1_TIME_print(bio_err,X509_get_notBefore(err_cert));
184                 BIO_printf(bio_err,"\n");
185                 break;
186         case X509_V_ERR_CERT_HAS_EXPIRED:
187         case X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD:
188                 BIO_printf(bio_err,"notAfter=");
189                 ASN1_TIME_print(bio_err,X509_get_notAfter(err_cert));
190                 BIO_printf(bio_err,"\n");
191                 break;
192         case X509_V_ERR_NO_EXPLICIT_POLICY:
193                 policies_print(bio_err, ctx);
194                 break;
195                 }
196         if (err == X509_V_OK && ok == 2 && !verify_quiet)
197                 policies_print(bio_err, ctx);
198         if (ok && !verify_quiet)
199                 BIO_printf(bio_err,"verify return:%d\n",ok);
200         return(ok);
201         }
202
203 int set_cert_stuff(SSL_CTX *ctx, char *cert_file, char *key_file)
204         {
205         if (cert_file != NULL)
206                 {
207                 /*
208                 SSL *ssl;
209                 X509 *x509;
210                 */
211
212                 if (SSL_CTX_use_certificate_file(ctx,cert_file,
213                         SSL_FILETYPE_PEM) <= 0)
214                         {
215                         BIO_printf(bio_err,"unable to get certificate from '%s'\n",cert_file);
216                         ERR_print_errors(bio_err);
217                         return(0);
218                         }
219                 if (key_file == NULL) key_file=cert_file;
220                 if (SSL_CTX_use_PrivateKey_file(ctx,key_file,
221                         SSL_FILETYPE_PEM) <= 0)
222                         {
223                         BIO_printf(bio_err,"unable to get private key from '%s'\n",key_file);
224                         ERR_print_errors(bio_err);
225                         return(0);
226                         }
227
228                 /*
229                 In theory this is no longer needed 
230                 ssl=SSL_new(ctx);
231                 x509=SSL_get_certificate(ssl);
232
233                 if (x509 != NULL) {
234                         EVP_PKEY *pktmp;
235                         pktmp = X509_get_pubkey(x509);
236                         EVP_PKEY_copy_parameters(pktmp,
237                                                 SSL_get_privatekey(ssl));
238                         EVP_PKEY_free(pktmp);
239                 }
240                 SSL_free(ssl);
241                 */
242
243                 /* If we are using DSA, we can copy the parameters from
244                  * the private key */
245
246
247                 /* Now we know that a key and cert have been set against
248                  * the SSL context */
249                 if (!SSL_CTX_check_private_key(ctx))
250                         {
251                         BIO_printf(bio_err,"Private key does not match the certificate public key\n");
252                         return(0);
253                         }
254                 }
255         return(1);
256         }
257
258 int set_cert_key_stuff(SSL_CTX *ctx, X509 *cert, EVP_PKEY *key,
259                        STACK_OF(X509) *chain, int build_chain)
260         {
261         if (cert == NULL)
262                 return 1;
263         if (SSL_CTX_use_certificate(ctx,cert) <= 0)
264                 {
265                 BIO_printf(bio_err,"error setting certificate\n");
266                 ERR_print_errors(bio_err);
267                 return 0;
268                 }
269
270         if (SSL_CTX_use_PrivateKey(ctx,key) <= 0)
271                 {
272                 BIO_printf(bio_err,"error setting private key\n");
273                 ERR_print_errors(bio_err);
274                 return 0;
275                 }
276                  
277         /* Now we know that a key and cert have been set against
278          * the SSL context */
279         if (!SSL_CTX_check_private_key(ctx))
280                 {
281                 BIO_printf(bio_err,"Private key does not match the certificate public key\n");
282                 return 0;
283                 }
284         if (chain && !SSL_CTX_set1_chain(ctx, chain))
285                 {
286                 BIO_printf(bio_err,"error setting certificate chain\n");
287                 ERR_print_errors(bio_err);
288                 return 0;
289                 }
290         if (!chain && build_chain && !SSL_CTX_build_cert_chain(ctx, 0))
291                 {
292                 BIO_printf(bio_err,"error building certificate chain\n");
293                 ERR_print_errors(bio_err);
294                 return 0;
295                 }
296         return 1;
297         }
298
299 static void ssl_print_client_cert_types(BIO *bio, SSL *s)
300         {
301         const unsigned char *p;
302         int i;
303         int cert_type_num = SSL_get0_certificate_types(s, &p);
304         if (!cert_type_num)
305                 return;
306         BIO_puts(bio, "Client Certificate Types: ");
307         for (i = 0; i < cert_type_num; i++)
308                 {
309                 unsigned char cert_type = p[i];
310                 char *cname;
311                 switch(cert_type)
312                         {
313                 case TLS_CT_RSA_SIGN:
314                         cname = "RSA sign";
315                         break;
316
317                 case TLS_CT_DSS_SIGN:
318                         cname = "DSA sign";
319                         break;
320
321                 case TLS_CT_RSA_FIXED_DH:
322                         cname = "RSA fixed DH";
323                         break;
324
325                 case TLS_CT_DSS_FIXED_DH:
326                         cname = "DSS fixed DH";
327                         break;
328
329                 case TLS_CT_ECDSA_SIGN:
330                         cname = "ECDSA sign";
331                         break;
332
333                 case TLS_CT_RSA_FIXED_ECDH:
334                         cname = "RSA fixed ECDH";
335                         break;
336
337                 case TLS_CT_ECDSA_FIXED_ECDH:
338                         cname = "ECDSA fixed ECDH";
339                         break;
340
341                 case TLS_CT_GOST94_SIGN:
342                         cname = "GOST94 Sign";
343                         break;
344
345                 case TLS_CT_GOST01_SIGN:
346                         cname = "GOST01 Sign";
347                         break;
348
349                 default:
350                          cname = NULL;
351                         }
352
353                 if (i)
354                         BIO_puts(bio, ", ");
355
356                 if (cname)
357                         BIO_puts(bio, cname);
358                 else
359                         BIO_printf(bio, "UNKNOWN (%d),", cert_type);
360                 }
361         BIO_puts(bio, "\n");
362         }
363
364 static int do_print_sigalgs(BIO *out, SSL *s, int shared)
365         {
366         int i, nsig, client;
367         client = SSL_is_server(s) ? 0 : 1;
368         if (shared)
369                 nsig = SSL_get_shared_sigalgs(s, -1, NULL, NULL, NULL,
370                                                         NULL, NULL);
371         else
372                 nsig = SSL_get_sigalgs(s, -1, NULL, NULL, NULL, NULL, NULL);
373         if (nsig == 0)
374                 return 1;
375
376         if (shared)
377                 BIO_puts(out, "Shared ");
378
379         if (client)
380                 BIO_puts(out, "Requested ");
381         BIO_puts(out, "Signature Algorithms: ");
382         for (i = 0; i < nsig; i++)
383                 {
384                 int hash_nid, sign_nid;
385                 unsigned char rhash, rsign;
386                 const char *sstr = NULL;
387                 if (shared)
388                         SSL_get_shared_sigalgs(s, i, &sign_nid, &hash_nid, NULL,
389                                                         &rsign, &rhash);
390                 else
391                         SSL_get_sigalgs(s, i, &sign_nid, &hash_nid, NULL,
392                                                         &rsign, &rhash);
393                 if (i)
394                         BIO_puts(out, ":");
395                 if (sign_nid == EVP_PKEY_RSA)
396                         sstr = "RSA";
397                 else if(sign_nid == EVP_PKEY_DSA)
398                         sstr = "DSA";
399                 else if(sign_nid == EVP_PKEY_EC)
400                         sstr = "ECDSA";
401                 if (sstr)
402                         BIO_printf(out,"%s+", sstr);
403                 else
404                         BIO_printf(out,"0x%02X+", (int)rsign);
405                 if (hash_nid != NID_undef)
406                         BIO_printf(out, "%s", OBJ_nid2sn(hash_nid));
407                 else
408                         BIO_printf(out,"0x%02X", (int)rhash);
409                 }
410         BIO_puts(out, "\n");
411         return 1;
412         }
413
414 int ssl_print_sigalgs(BIO *out, SSL *s)
415         {
416         int mdnid;
417         if (!SSL_is_server(s))
418                 ssl_print_client_cert_types(out, s);
419         do_print_sigalgs(out, s, 0);
420         do_print_sigalgs(out, s, 1);
421         if (SSL_get_peer_signature_nid(s, &mdnid))
422                 BIO_printf(out, "Peer signing digest: %s\n", OBJ_nid2sn(mdnid));
423         return 1;
424         }
425
426 int ssl_print_point_formats(BIO *out, SSL *s)
427         {
428         int i, nformats;
429         const char *pformats;
430         nformats = SSL_get0_ec_point_formats(s, &pformats);
431         if (nformats <= 0)
432                 return 1;
433         BIO_puts(out, "Supported Elliptic Curve Point Formats: ");
434         for (i = 0; i < nformats; i++, pformats++)
435                 {
436                 if (i)
437                         BIO_puts(out, ":");
438                 switch(*pformats)
439                         {
440                 case TLSEXT_ECPOINTFORMAT_uncompressed:
441                         BIO_puts(out, "uncompressed");
442                         break;
443
444                 case TLSEXT_ECPOINTFORMAT_ansiX962_compressed_prime:
445                         BIO_puts(out, "ansiX962_compressed_prime");
446                         break;
447
448                 case TLSEXT_ECPOINTFORMAT_ansiX962_compressed_char2:
449                         BIO_puts(out, "ansiX962_compressed_char2");
450                         break;
451
452                 default:
453                         BIO_printf(out, "unknown(%d)", (int)*pformats);
454                         break;
455
456                         }
457                 }
458         if (nformats <= 0)
459                 BIO_puts(out, "NONE");
460         BIO_puts(out, "\n");
461         return 1;
462         }
463
464 int ssl_print_curves(BIO *out, SSL *s, int noshared)
465         {
466         int i, ncurves, *curves, nid;
467         const char *cname;
468         ncurves = SSL_get1_curves(s, NULL);
469         if (ncurves <= 0)
470                 return 1;
471         curves = OPENSSL_malloc(ncurves * sizeof(int));
472         SSL_get1_curves(s, curves);
473
474         BIO_puts(out, "Supported Elliptic Curves: ");
475         for (i = 0; i < ncurves; i++)
476                 {
477                 if (i)
478                         BIO_puts(out, ":");
479                 nid = curves[i];
480                 /* If unrecognised print out hex version */
481                 if (nid & TLSEXT_nid_unknown)
482                         BIO_printf(out, "0x%04X", nid & 0xFFFF);
483                 else
484                         {
485                         /* Use NIST name for curve if it exists */
486                         cname = EC_curve_nid2nist(nid);
487                         if (!cname)
488                                 cname = OBJ_nid2sn(nid);
489                         BIO_printf(out, "%s", cname);
490                         }
491                 }
492         if (ncurves == 0)
493                 BIO_puts(out, "NONE");
494         OPENSSL_free(curves);
495         if (noshared)
496                 {
497                 BIO_puts(out, "\n");
498                 return 1;
499                 }
500         BIO_puts(out, "\nShared Elliptic curves: ");
501         ncurves = SSL_get_shared_curve(s, -1);
502         for (i = 0; i < ncurves; i++)
503                 {
504                 if (i)
505                         BIO_puts(out, ":");
506                 nid = SSL_get_shared_curve(s, i);
507                 cname = EC_curve_nid2nist(nid);
508                 if (!cname)
509                         cname = OBJ_nid2sn(nid);
510                 BIO_printf(out, "%s", cname);
511                 }
512         if (ncurves == 0)
513                 BIO_puts(out, "NONE");
514         BIO_puts(out, "\n");
515         return 1;
516         }
517
518 int ssl_print_tmp_key(BIO *out, SSL *s)
519         {
520         EVP_PKEY *key;
521         if (!SSL_get_server_tmp_key(s, &key))
522                 return 1;
523         BIO_puts(out, "Server Temp Key: ");
524         switch (EVP_PKEY_id(key))
525                 {
526         case EVP_PKEY_RSA:
527                 BIO_printf(out, "RSA, %d bits\n", EVP_PKEY_bits(key));
528                 break;
529
530         case EVP_PKEY_DH:
531                 BIO_printf(out, "DH, %d bits\n", EVP_PKEY_bits(key));
532                 break;
533
534         case EVP_PKEY_EC:
535                         {
536                         EC_KEY *ec = EVP_PKEY_get1_EC_KEY(key);
537                         int nid;
538                         const char *cname;
539                         nid = EC_GROUP_get_curve_name(EC_KEY_get0_group(ec));
540                         EC_KEY_free(ec);
541                         cname = EC_curve_nid2nist(nid);
542                         if (!cname)
543                                 cname = OBJ_nid2sn(nid);
544                         BIO_printf(out, "ECDH, %s, %d bits\n",
545                                                 cname, EVP_PKEY_bits(key));
546                         }
547                 }
548         EVP_PKEY_free(key);
549         return 1;
550         }
551                 
552
553 long MS_CALLBACK bio_dump_callback(BIO *bio, int cmd, const char *argp,
554                                    int argi, long argl, long ret)
555         {
556         BIO *out;
557
558         out=(BIO *)BIO_get_callback_arg(bio);
559         if (out == NULL) return(ret);
560
561         if (cmd == (BIO_CB_READ|BIO_CB_RETURN))
562                 {
563                 BIO_printf(out,"read from %p [%p] (%lu bytes => %ld (0x%lX))\n",
564                         (void *)bio,argp,(unsigned long)argi,ret,ret);
565                 BIO_dump(out,argp,(int)ret);
566                 return(ret);
567                 }
568         else if (cmd == (BIO_CB_WRITE|BIO_CB_RETURN))
569                 {
570                 BIO_printf(out,"write to %p [%p] (%lu bytes => %ld (0x%lX))\n",
571                         (void *)bio,argp,(unsigned long)argi,ret,ret);
572                 BIO_dump(out,argp,(int)ret);
573                 }
574         return(ret);
575         }
576
577 void MS_CALLBACK apps_ssl_info_callback(const SSL *s, int where, int ret)
578         {
579         const char *str;
580         int w;
581
582         w=where& ~SSL_ST_MASK;
583
584         if (w & SSL_ST_CONNECT) str="SSL_connect";
585         else if (w & SSL_ST_ACCEPT) str="SSL_accept";
586         else str="undefined";
587
588         if (where & SSL_CB_LOOP)
589                 {
590                 BIO_printf(bio_err,"%s:%s\n",str,SSL_state_string_long(s));
591                 }
592         else if (where & SSL_CB_ALERT)
593                 {
594                 str=(where & SSL_CB_READ)?"read":"write";
595                 BIO_printf(bio_err,"SSL3 alert %s:%s:%s\n",
596                         str,
597                         SSL_alert_type_string_long(ret),
598                         SSL_alert_desc_string_long(ret));
599                 }
600         else if (where & SSL_CB_EXIT)
601                 {
602                 if (ret == 0)
603                         BIO_printf(bio_err,"%s:failed in %s\n",
604                                 str,SSL_state_string_long(s));
605                 else if (ret < 0)
606                         {
607                         BIO_printf(bio_err,"%s:error in %s\n",
608                                 str,SSL_state_string_long(s));
609                         }
610                 }
611         }
612
613
614 void MS_CALLBACK msg_cb(int write_p, int version, int content_type, const void *buf, size_t len, SSL *ssl, void *arg)
615         {
616         BIO *bio = arg;
617         const char *str_write_p, *str_version, *str_content_type = "", *str_details1 = "", *str_details2= "";
618         
619         str_write_p = write_p ? ">>>" : "<<<";
620
621         switch (version)
622                 {
623         case SSL2_VERSION:
624                 str_version = "SSL 2.0";
625                 break;
626         case SSL3_VERSION:
627                 str_version = "SSL 3.0 ";
628                 break;
629         case TLS1_VERSION:
630                 str_version = "TLS 1.0 ";
631                 break;
632         case TLS1_1_VERSION:
633                 str_version = "TLS 1.1 ";
634                 break;
635         case TLS1_2_VERSION:
636                 str_version = "TLS 1.2 ";
637                 break;
638         case DTLS1_VERSION:
639                 str_version = "DTLS 1.0 ";
640                 break;
641         case DTLS1_BAD_VER:
642                 str_version = "DTLS 1.0 (bad) ";
643                 break;
644         default:
645                 str_version = "???";
646                 }
647
648         if (version == SSL2_VERSION)
649                 {
650                 str_details1 = "???";
651
652                 if (len > 0)
653                         {
654                         switch (((const unsigned char*)buf)[0])
655                                 {
656                                 case 0:
657                                         str_details1 = ", ERROR:";
658                                         str_details2 = " ???";
659                                         if (len >= 3)
660                                                 {
661                                                 unsigned err = (((const unsigned char*)buf)[1]<<8) + ((const unsigned char*)buf)[2];
662                                                 
663                                                 switch (err)
664                                                         {
665                                                 case 0x0001:
666                                                         str_details2 = " NO-CIPHER-ERROR";
667                                                         break;
668                                                 case 0x0002:
669                                                         str_details2 = " NO-CERTIFICATE-ERROR";
670                                                         break;
671                                                 case 0x0004:
672                                                         str_details2 = " BAD-CERTIFICATE-ERROR";
673                                                         break;
674                                                 case 0x0006:
675                                                         str_details2 = " UNSUPPORTED-CERTIFICATE-TYPE-ERROR";
676                                                         break;
677                                                         }
678                                                 }
679
680                                         break;
681                                 case 1:
682                                         str_details1 = ", CLIENT-HELLO";
683                                         break;
684                                 case 2:
685                                         str_details1 = ", CLIENT-MASTER-KEY";
686                                         break;
687                                 case 3:
688                                         str_details1 = ", CLIENT-FINISHED";
689                                         break;
690                                 case 4:
691                                         str_details1 = ", SERVER-HELLO";
692                                         break;
693                                 case 5:
694                                         str_details1 = ", SERVER-VERIFY";
695                                         break;
696                                 case 6:
697                                         str_details1 = ", SERVER-FINISHED";
698                                         break;
699                                 case 7:
700                                         str_details1 = ", REQUEST-CERTIFICATE";
701                                         break;
702                                 case 8:
703                                         str_details1 = ", CLIENT-CERTIFICATE";
704                                         break;
705                                 }
706                         }
707                 }
708
709         if (version == SSL3_VERSION ||
710             version == TLS1_VERSION ||
711             version == TLS1_1_VERSION ||
712             version == TLS1_2_VERSION ||
713             version == DTLS1_VERSION ||
714             version == DTLS1_BAD_VER)
715                 {
716                 switch (content_type)
717                         {
718                 case 20:
719                         str_content_type = "ChangeCipherSpec";
720                         break;
721                 case 21:
722                         str_content_type = "Alert";
723                         break;
724                 case 22:
725                         str_content_type = "Handshake";
726                         break;
727                         }
728
729                 if (content_type == 21) /* Alert */
730                         {
731                         str_details1 = ", ???";
732                         
733                         if (len == 2)
734                                 {
735                                 switch (((const unsigned char*)buf)[0])
736                                         {
737                                 case 1:
738                                         str_details1 = ", warning";
739                                         break;
740                                 case 2:
741                                         str_details1 = ", fatal";
742                                         break;
743                                         }
744
745                                 str_details2 = " ???";
746                                 switch (((const unsigned char*)buf)[1])
747                                         {
748                                 case 0:
749                                         str_details2 = " close_notify";
750                                         break;
751                                 case 10:
752                                         str_details2 = " unexpected_message";
753                                         break;
754                                 case 20:
755                                         str_details2 = " bad_record_mac";
756                                         break;
757                                 case 21:
758                                         str_details2 = " decryption_failed";
759                                         break;
760                                 case 22:
761                                         str_details2 = " record_overflow";
762                                         break;
763                                 case 30:
764                                         str_details2 = " decompression_failure";
765                                         break;
766                                 case 40:
767                                         str_details2 = " handshake_failure";
768                                         break;
769                                 case 42:
770                                         str_details2 = " bad_certificate";
771                                         break;
772                                 case 43:
773                                         str_details2 = " unsupported_certificate";
774                                         break;
775                                 case 44:
776                                         str_details2 = " certificate_revoked";
777                                         break;
778                                 case 45:
779                                         str_details2 = " certificate_expired";
780                                         break;
781                                 case 46:
782                                         str_details2 = " certificate_unknown";
783                                         break;
784                                 case 47:
785                                         str_details2 = " illegal_parameter";
786                                         break;
787                                 case 48:
788                                         str_details2 = " unknown_ca";
789                                         break;
790                                 case 49:
791                                         str_details2 = " access_denied";
792                                         break;
793                                 case 50:
794                                         str_details2 = " decode_error";
795                                         break;
796                                 case 51:
797                                         str_details2 = " decrypt_error";
798                                         break;
799                                 case 60:
800                                         str_details2 = " export_restriction";
801                                         break;
802                                 case 70:
803                                         str_details2 = " protocol_version";
804                                         break;
805                                 case 71:
806                                         str_details2 = " insufficient_security";
807                                         break;
808                                 case 80:
809                                         str_details2 = " internal_error";
810                                         break;
811                                 case 90:
812                                         str_details2 = " user_canceled";
813                                         break;
814                                 case 100:
815                                         str_details2 = " no_renegotiation";
816                                         break;
817                                 case 110:
818                                         str_details2 = " unsupported_extension";
819                                         break;
820                                 case 111:
821                                         str_details2 = " certificate_unobtainable";
822                                         break;
823                                 case 112:
824                                         str_details2 = " unrecognized_name";
825                                         break;
826                                 case 113:
827                                         str_details2 = " bad_certificate_status_response";
828                                         break;
829                                 case 114:
830                                         str_details2 = " bad_certificate_hash_value";
831                                         break;
832                                 case 115:
833                                         str_details2 = " unknown_psk_identity";
834                                         break;
835                                         }
836                                 }
837                         }
838                 
839                 if (content_type == 22) /* Handshake */
840                         {
841                         str_details1 = "???";
842
843                         if (len > 0)
844                                 {
845                                 switch (((const unsigned char*)buf)[0])
846                                         {
847                                 case 0:
848                                         str_details1 = ", HelloRequest";
849                                         break;
850                                 case 1:
851                                         str_details1 = ", ClientHello";
852                                         break;
853                                 case 2:
854                                         str_details1 = ", ServerHello";
855                                         break;
856                                 case 3:
857                                         str_details1 = ", HelloVerifyRequest";
858                                         break;
859                                 case 11:
860                                         str_details1 = ", Certificate";
861                                         break;
862                                 case 12:
863                                         str_details1 = ", ServerKeyExchange";
864                                         break;
865                                 case 13:
866                                         str_details1 = ", CertificateRequest";
867                                         break;
868                                 case 14:
869                                         str_details1 = ", ServerHelloDone";
870                                         break;
871                                 case 15:
872                                         str_details1 = ", CertificateVerify";
873                                         break;
874                                 case 16:
875                                         str_details1 = ", ClientKeyExchange";
876                                         break;
877                                 case 20:
878                                         str_details1 = ", Finished";
879                                         break;
880                                         }
881                                 }
882                         }
883
884 #ifndef OPENSSL_NO_HEARTBEATS
885                 if (content_type == 24) /* Heartbeat */
886                         {
887                         str_details1 = ", Heartbeat";
888                         
889                         if (len > 0)
890                                 {
891                                 switch (((const unsigned char*)buf)[0])
892                                         {
893                                 case 1:
894                                         str_details1 = ", HeartbeatRequest";
895                                         break;
896                                 case 2:
897                                         str_details1 = ", HeartbeatResponse";
898                                         break;
899                                         }
900                                 }
901                         }
902 #endif
903                 }
904
905         BIO_printf(bio, "%s %s%s [length %04lx]%s%s\n", str_write_p, str_version, str_content_type, (unsigned long)len, str_details1, str_details2);
906
907         if (len > 0)
908                 {
909                 size_t num, i;
910                 
911                 BIO_printf(bio, "   ");
912                 num = len;
913 #if 0
914                 if (num > 16)
915                         num = 16;
916 #endif
917                 for (i = 0; i < num; i++)
918                         {
919                         if (i % 16 == 0 && i > 0)
920                                 BIO_printf(bio, "\n   ");
921                         BIO_printf(bio, " %02x", ((const unsigned char*)buf)[i]);
922                         }
923                 if (i < len)
924                         BIO_printf(bio, " ...");
925                 BIO_printf(bio, "\n");
926                 }
927         (void)BIO_flush(bio);
928         }
929
930 void MS_CALLBACK tlsext_cb(SSL *s, int client_server, int type,
931                                         unsigned char *data, int len,
932                                         void *arg)
933         {
934         BIO *bio = arg;
935         char *extname;
936
937         switch(type)
938                 {
939                 case TLSEXT_TYPE_server_name:
940                 extname = "server name";
941                 break;
942
943                 case TLSEXT_TYPE_max_fragment_length:
944                 extname = "max fragment length";
945                 break;
946
947                 case TLSEXT_TYPE_client_certificate_url:
948                 extname = "client certificate URL";
949                 break;
950
951                 case TLSEXT_TYPE_trusted_ca_keys:
952                 extname = "trusted CA keys";
953                 break;
954
955                 case TLSEXT_TYPE_truncated_hmac:
956                 extname = "truncated HMAC";
957                 break;
958
959                 case TLSEXT_TYPE_status_request:
960                 extname = "status request";
961                 break;
962
963                 case TLSEXT_TYPE_user_mapping:
964                 extname = "user mapping";
965                 break;
966
967                 case TLSEXT_TYPE_client_authz:
968                 extname = "client authz";
969                 break;
970
971                 case TLSEXT_TYPE_server_authz:
972                 extname = "server authz";
973                 break;
974
975                 case TLSEXT_TYPE_cert_type:
976                 extname = "cert type";
977                 break;
978
979                 case TLSEXT_TYPE_elliptic_curves:
980                 extname = "elliptic curves";
981                 break;
982
983                 case TLSEXT_TYPE_ec_point_formats:
984                 extname = "EC point formats";
985                 break;
986
987                 case TLSEXT_TYPE_srp:
988                 extname = "SRP";
989                 break;
990
991                 case TLSEXT_TYPE_signature_algorithms:
992                 extname = "signature algorithms";
993                 break;
994
995                 case TLSEXT_TYPE_use_srtp:
996                 extname = "use SRTP";
997                 break;
998
999                 case TLSEXT_TYPE_heartbeat:
1000                 extname = "heartbeat";
1001                 break;
1002
1003                 case TLSEXT_TYPE_session_ticket:
1004                 extname = "session ticket";
1005                 break;
1006
1007                 case TLSEXT_TYPE_renegotiate: 
1008                 extname = "renegotiation info";
1009                 break;
1010
1011 #ifdef TLSEXT_TYPE_opaque_prf_input
1012                 case TLSEXT_TYPE_opaque_prf_input:
1013                 extname = "opaque PRF input";
1014                 break;
1015 #endif
1016 #ifdef TLSEXT_TYPE_next_proto_neg
1017                 case TLSEXT_TYPE_next_proto_neg:
1018                 extname = "next protocol";
1019                 break;
1020 #endif
1021
1022                 default:
1023                 extname = "unknown";
1024                 break;
1025
1026                 }
1027         
1028         BIO_printf(bio, "TLS %s extension \"%s\" (id=%d), len=%d\n",
1029                         client_server ? "server": "client",
1030                         extname, type, len);
1031         BIO_dump(bio, (char *)data, len);
1032         (void)BIO_flush(bio);
1033         }
1034
1035 int MS_CALLBACK generate_cookie_callback(SSL *ssl, unsigned char *cookie, unsigned int *cookie_len)
1036         {
1037         unsigned char *buffer, result[EVP_MAX_MD_SIZE];
1038         unsigned int length, resultlength;
1039         union {
1040                 struct sockaddr sa;
1041                 struct sockaddr_in s4;
1042 #if OPENSSL_USE_IPV6
1043                 struct sockaddr_in6 s6;
1044 #endif
1045         } peer;
1046
1047         /* Initialize a random secret */
1048         if (!cookie_initialized)
1049                 {
1050                 if (!RAND_bytes(cookie_secret, COOKIE_SECRET_LENGTH))
1051                         {
1052                         BIO_printf(bio_err,"error setting random cookie secret\n");
1053                         return 0;
1054                         }
1055                 cookie_initialized = 1;
1056                 }
1057
1058         /* Read peer information */
1059         (void)BIO_dgram_get_peer(SSL_get_rbio(ssl), &peer);
1060
1061         /* Create buffer with peer's address and port */
1062         length = 0;
1063         switch (peer.sa.sa_family)
1064                 {
1065         case AF_INET:
1066                 length += sizeof(struct in_addr);
1067                 length += sizeof(peer.s4.sin_port);
1068                 break;
1069 #if OPENSSL_USE_IPV6
1070         case AF_INET6:
1071                 length += sizeof(struct in6_addr);
1072                 length += sizeof(peer.s6.sin6_port);
1073                 break;
1074 #endif
1075         default:
1076                 OPENSSL_assert(0);
1077                 break;
1078                 }
1079         buffer = OPENSSL_malloc(length);
1080
1081         if (buffer == NULL)
1082                 {
1083                 BIO_printf(bio_err,"out of memory\n");
1084                 return 0;
1085                 }
1086
1087         switch (peer.sa.sa_family)
1088                 {
1089         case AF_INET:
1090                 memcpy(buffer,
1091                        &peer.s4.sin_port,
1092                        sizeof(peer.s4.sin_port));
1093                 memcpy(buffer + sizeof(peer.s4.sin_port),
1094                        &peer.s4.sin_addr,
1095                        sizeof(struct in_addr));
1096                 break;
1097 #if OPENSSL_USE_IPV6
1098         case AF_INET6:
1099                 memcpy(buffer,
1100                        &peer.s6.sin6_port,
1101                        sizeof(peer.s6.sin6_port));
1102                 memcpy(buffer + sizeof(peer.s6.sin6_port),
1103                        &peer.s6.sin6_addr,
1104                        sizeof(struct in6_addr));
1105                 break;
1106 #endif
1107         default:
1108                 OPENSSL_assert(0);
1109                 break;
1110                 }
1111
1112         /* Calculate HMAC of buffer using the secret */
1113         HMAC(EVP_sha1(), cookie_secret, COOKIE_SECRET_LENGTH,
1114              buffer, length, result, &resultlength);
1115         OPENSSL_free(buffer);
1116
1117         memcpy(cookie, result, resultlength);
1118         *cookie_len = resultlength;
1119
1120         return 1;
1121         }
1122
1123 int MS_CALLBACK verify_cookie_callback(SSL *ssl, unsigned char *cookie, unsigned int cookie_len)
1124         {
1125         unsigned char *buffer, result[EVP_MAX_MD_SIZE];
1126         unsigned int length, resultlength;
1127         union {
1128                 struct sockaddr sa;
1129                 struct sockaddr_in s4;
1130 #if OPENSSL_USE_IPV6
1131                 struct sockaddr_in6 s6;
1132 #endif
1133         } peer;
1134
1135         /* If secret isn't initialized yet, the cookie can't be valid */
1136         if (!cookie_initialized)
1137                 return 0;
1138
1139         /* Read peer information */
1140         (void)BIO_dgram_get_peer(SSL_get_rbio(ssl), &peer);
1141
1142         /* Create buffer with peer's address and port */
1143         length = 0;
1144         switch (peer.sa.sa_family)
1145                 {
1146         case AF_INET:
1147                 length += sizeof(struct in_addr);
1148                 length += sizeof(peer.s4.sin_port);
1149                 break;
1150 #if OPENSSL_USE_IPV6
1151         case AF_INET6:
1152                 length += sizeof(struct in6_addr);
1153                 length += sizeof(peer.s6.sin6_port);
1154                 break;
1155 #endif
1156         default:
1157                 OPENSSL_assert(0);
1158                 break;
1159                 }
1160         buffer = OPENSSL_malloc(length);
1161         
1162         if (buffer == NULL)
1163                 {
1164                 BIO_printf(bio_err,"out of memory\n");
1165                 return 0;
1166                 }
1167
1168         switch (peer.sa.sa_family)
1169                 {
1170         case AF_INET:
1171                 memcpy(buffer,
1172                        &peer.s4.sin_port,
1173                        sizeof(peer.s4.sin_port));
1174                 memcpy(buffer + sizeof(peer.s4.sin_port),
1175                        &peer.s4.sin_addr,
1176                        sizeof(struct in_addr));
1177                 break;
1178 #if OPENSSL_USE_IPV6
1179         case AF_INET6:
1180                 memcpy(buffer,
1181                        &peer.s6.sin6_port,
1182                        sizeof(peer.s6.sin6_port));
1183                 memcpy(buffer + sizeof(peer.s6.sin6_port),
1184                        &peer.s6.sin6_addr,
1185                        sizeof(struct in6_addr));
1186                 break;
1187 #endif
1188         default:
1189                 OPENSSL_assert(0);
1190                 break;
1191                 }
1192
1193         /* Calculate HMAC of buffer using the secret */
1194         HMAC(EVP_sha1(), cookie_secret, COOKIE_SECRET_LENGTH,
1195              buffer, length, result, &resultlength);
1196         OPENSSL_free(buffer);
1197
1198         if (cookie_len == resultlength && memcmp(result, cookie, resultlength) == 0)
1199                 return 1;
1200
1201         return 0;
1202         }
1203
1204 /* Example of extended certificate handling. Where the standard support
1205  * of one certificate per algorithm is not sufficient an application
1206  * can decide which certificate(s) to use at runtime based on whatever
1207  * criteria it deems appropriate.
1208  */
1209
1210 /* Linked list of certificates, keys and chains */
1211 struct  ssl_excert_st
1212         {
1213         int certform;
1214         const char *certfile;
1215         int keyform;
1216         const char *keyfile;
1217         const char *chainfile;
1218         X509 *cert;
1219         EVP_PKEY *key;
1220         STACK_OF(X509) *chain;
1221         int build_chain;
1222         struct ssl_excert_st *next, *prev;
1223         };
1224
1225 struct chain_flags
1226         {
1227         int flag;
1228         const char *name;
1229         };
1230
1231 struct chain_flags chain_flags_list[] =
1232         {
1233                 {CERT_PKEY_VALID, "Overall Validity"},
1234                 {CERT_PKEY_SIGN,  "Sign with EE key"},
1235                 {CERT_PKEY_EE_SIGNATURE, "EE signature"},
1236                 {CERT_PKEY_CA_SIGNATURE, "CA signature"},
1237                 {CERT_PKEY_EE_PARAM, "EE key parameters"},
1238                 {CERT_PKEY_CA_PARAM, "CA key parameters"},
1239                 {CERT_PKEY_EXPLICIT_SIGN,  "Explicity sign with EE key"},
1240                 {CERT_PKEY_ISSUER_NAME,  "Issuer Name"},
1241                 {CERT_PKEY_CERT_TYPE,  "Certificate Type"},
1242                 {0, NULL}
1243         };
1244
1245
1246 static void print_chain_flags(BIO *out, int flags)
1247         {
1248         struct chain_flags *ctmp = chain_flags_list;
1249         while(ctmp->name)
1250                 {
1251                 BIO_printf(out, "\t%s: %s\n", ctmp->name,
1252                                 flags & ctmp->flag ? "OK" : "NOT OK");
1253                 ctmp++;
1254                 }
1255         }
1256
1257 /* Very basic selection callback: just use any certificate chain
1258  * reported as valid. More sophisticated could prioritise according
1259  * to local policy.
1260  */
1261 static int set_cert_cb(SSL *ssl, void *arg)
1262         {
1263         int i, rv;
1264         SSL_EXCERT *exc = arg;
1265         SSL_certs_clear(ssl);
1266
1267         if (!exc)
1268                 return 1;
1269
1270         /* Go to end of list and traverse backwards since we prepend
1271          * newer entries this retains the original order.
1272          */
1273         while (exc->next)
1274                 exc = exc->next;
1275
1276         i = 0;  
1277
1278         while(exc)
1279                 {
1280                 i++;
1281                 rv = SSL_check_chain(ssl, exc->cert, exc->key, exc->chain);
1282                 BIO_printf(bio_err, "Checking cert chain %d:\nSubject: ", i);
1283                 X509_NAME_print_ex(bio_err, X509_get_subject_name(exc->cert), 0,
1284                                                         XN_FLAG_ONELINE);
1285                 BIO_puts(bio_err, "\n");
1286                 
1287                 print_chain_flags(bio_err, rv);
1288                 if (rv & CERT_PKEY_VALID)
1289                         {
1290                         SSL_use_certificate(ssl, exc->cert);
1291                         SSL_use_PrivateKey(ssl, exc->key);
1292                         /* NB: we wouldn't normally do this as it is
1293                          * not efficient building chains on each connection
1294                          * better to cache the chain in advance.
1295                          */
1296                         if (exc->build_chain)
1297                                 {
1298                                 if (!SSL_build_cert_chain(ssl, 0))
1299                                         return 0;
1300                                 }
1301                         else if (exc->chain)
1302                                 SSL_set1_chain(ssl, exc->chain);
1303                         }
1304                 exc = exc->prev;
1305                 }
1306         return 1;
1307         }
1308
1309 void ssl_ctx_set_excert(SSL_CTX *ctx, SSL_EXCERT *exc)
1310         {
1311         SSL_CTX_set_cert_cb(ctx, set_cert_cb, exc);
1312         }
1313
1314 static int ssl_excert_prepend(SSL_EXCERT **pexc)
1315         {
1316         SSL_EXCERT *exc;
1317         exc = OPENSSL_malloc(sizeof(SSL_EXCERT));
1318         if (!exc)
1319                 return 0;
1320         exc->certfile = NULL;
1321         exc->keyfile = NULL;
1322         exc->chainfile = NULL;
1323         exc->cert = NULL;
1324         exc->key = NULL;
1325         exc->chain = NULL;
1326         exc->prev = NULL;
1327         exc->build_chain = 0;
1328
1329         exc->next = *pexc;
1330         *pexc = exc;
1331                         
1332         if (exc->next)
1333                 {
1334                 exc->certform = exc->next->certform;
1335                 exc->keyform = exc->next->keyform;
1336                 exc->next->prev = exc;
1337                 }
1338         else
1339                 {
1340                 exc->certform = FORMAT_PEM;
1341                 exc->keyform = FORMAT_PEM;
1342                 }
1343         return 1;
1344
1345         }
1346
1347 void ssl_excert_free(SSL_EXCERT *exc)
1348         {
1349         SSL_EXCERT *curr;
1350         while (exc)
1351                 {
1352                 if (exc->cert)
1353                         X509_free(exc->cert);
1354                 if (exc->key)
1355                         EVP_PKEY_free(exc->key);
1356                 if (exc->chain)
1357                         sk_X509_pop_free(exc->chain, X509_free);
1358                 curr = exc;
1359                 exc = exc->next;
1360                 OPENSSL_free(curr);
1361                 }
1362         }
1363
1364 int load_excert(SSL_EXCERT **pexc, BIO *err)
1365         {
1366         SSL_EXCERT *exc = *pexc;
1367         if (!exc)
1368                 return 1;
1369         /* If nothing in list, free and set to NULL */
1370         if (!exc->certfile && !exc->next)
1371                 {
1372                 ssl_excert_free(exc);
1373                 *pexc = NULL;
1374                 return 1;
1375                 }
1376         for(; exc; exc=exc->next)
1377                 {
1378                 if (!exc->certfile)
1379                         {
1380                         BIO_printf(err, "Missing filename\n");
1381                         return 0;
1382                         }
1383                 exc->cert = load_cert(err, exc->certfile, exc->certform,
1384                                         NULL, NULL, "Server Certificate");
1385                 if (!exc->cert)
1386                         return 0;
1387                 if (exc->keyfile)
1388                         exc->keyfile = exc->certfile;
1389                 exc->key = load_key(err, exc->certfile, exc->certform, 0,
1390                                         NULL, NULL, "Server Certificate");
1391                 if (!exc->key)
1392                         return 0;
1393                 if (exc->chainfile)
1394                         {
1395                         exc->chain = load_certs(err,
1396                                                 exc->chainfile, FORMAT_PEM,
1397                                                 NULL, NULL,
1398                                                 "Server Chain");
1399                         if (!exc->chainfile)
1400                                 return 0;
1401                         }
1402                 }
1403         return 1;
1404         }
1405                 
1406
1407 int args_excert(char ***pargs, int *pargc,
1408                         int *badarg, BIO *err, SSL_EXCERT **pexc)
1409         {
1410         char *arg = **pargs, *argn = (*pargs)[1];
1411         SSL_EXCERT *exc = *pexc;
1412         int narg = 2;
1413         if (!exc)
1414                 {
1415                 if (ssl_excert_prepend(&exc))
1416                         *pexc = exc;
1417                 else
1418                         {
1419                         BIO_printf(err, "Error initialising xcert\n");
1420                         *badarg = 1;
1421                         goto err;
1422                         }
1423                 }
1424         if (strcmp(arg, "-xcert") == 0)
1425                 {
1426                 if (!argn)
1427                         {
1428                         *badarg = 1;
1429                         return 1;
1430                         }
1431                 if (exc->certfile && !ssl_excert_prepend(&exc))
1432                         {
1433                         BIO_printf(err, "Error adding xcert\n");
1434                         *badarg = 1;
1435                         goto err;
1436                         }
1437                 exc->certfile = argn;
1438                 }
1439         else if (strcmp(arg,"-xkey") == 0)
1440                 {
1441                 if (!argn)
1442                         {
1443                         *badarg = 1;
1444                         return 1;
1445                         }
1446                 if (exc->keyfile)
1447                         {
1448                         BIO_printf(err, "Key already specified\n");
1449                         *badarg = 1;
1450                         return 1;
1451                         }
1452                 exc->keyfile = argn;
1453                 }
1454         else if (strcmp(arg,"-xchain") == 0)
1455                 {
1456                 if (!argn)
1457                         {
1458                         *badarg = 1;
1459                         return 1;
1460                         }
1461                 if (exc->chainfile)
1462                         {
1463                         BIO_printf(err, "Chain already specified\n");
1464                         *badarg = 1;
1465                         return 1;
1466                         }
1467                 exc->chainfile = argn;
1468                 }
1469         else if (strcmp(arg,"-xchain_build") == 0)
1470                 {
1471                 narg = 1;
1472                 exc->build_chain = 1;
1473                 }
1474         else if (strcmp(arg,"-xcertform") == 0)
1475                 {
1476                 if (!argn)
1477                         {
1478                         *badarg = 1;
1479                         goto err;
1480                         }
1481                 exc->certform = str2fmt(argn);
1482                 }
1483         else if (strcmp(arg,"-xkeyform") == 0)
1484                 {
1485                 if (!argn)
1486                         {
1487                         *badarg = 1;
1488                         goto err;
1489                         }
1490                 exc->keyform = str2fmt(argn);
1491                 }
1492         else
1493                 return 0;
1494
1495         (*pargs) += narg;
1496
1497         if (pargc)
1498                 *pargc -= narg;
1499
1500         *pexc = exc;
1501
1502         return 1;
1503
1504         err:
1505         ERR_print_errors(err);
1506         ssl_excert_free(exc);
1507         *pexc = NULL;
1508         return 1;
1509         }
1510
1511 static void print_raw_cipherlist(BIO *bio, SSL *s)
1512         {
1513         const unsigned char *rlist;
1514         static const unsigned char scsv_id[] = {0, 0, 0xFF};
1515         size_t i, rlistlen, num;
1516         if (!SSL_is_server(s))
1517                 return;
1518         num = SSL_get0_raw_cipherlist(s, NULL);
1519         rlistlen = SSL_get0_raw_cipherlist(s, &rlist);
1520         BIO_puts(bio, "Client cipher list: ");
1521         for (i = 0; i < rlistlen; i += num, rlist += num)
1522                 {
1523                 const SSL_CIPHER *c = SSL_CIPHER_find(s, rlist);
1524                 if (i)
1525                         BIO_puts(bio, ":");
1526                 if (c)
1527                         BIO_puts(bio, SSL_CIPHER_get_name(c));
1528                 else if (!memcmp(rlist, scsv_id - num + 3, num))
1529                         BIO_puts(bio, "SCSV");
1530                 else
1531                         {
1532                         size_t j;
1533                         BIO_puts(bio, "0x");
1534                         for (j = 0; j < num; j++)
1535                                 BIO_printf(bio, "%02X", rlist[j]);
1536                         }
1537                 }
1538         BIO_puts(bio, "\n");
1539         }
1540         
1541
1542 void print_ssl_summary(BIO *bio, SSL *s)
1543         {
1544         const SSL_CIPHER *c;
1545         X509 *peer;
1546         /*const char *pnam = SSL_is_server(s) ? "client" : "server";*/
1547         BIO_printf(bio, "Protocol version: %s\n", SSL_get_version(s));
1548         print_raw_cipherlist(bio, s);
1549         c = SSL_get_current_cipher(s);
1550         BIO_printf(bio,"Ciphersuite: %s\n", SSL_CIPHER_get_name(c));
1551         do_print_sigalgs(bio, s, 0);
1552         peer = SSL_get_peer_certificate(s);
1553         if (peer)
1554                 {
1555                 int nid;
1556                 BIO_puts(bio, "Peer certificate: ");
1557                 X509_NAME_print_ex(bio, X509_get_subject_name(peer),
1558                                         0, XN_FLAG_ONELINE);
1559                 BIO_puts(bio, "\n");
1560                 if (SSL_get_peer_signature_nid(s, &nid))
1561                         BIO_printf(bio, "Hash used: %s\n", OBJ_nid2sn(nid));
1562                 }
1563         else
1564                 BIO_puts(bio, "No peer certificate\n");
1565         if (peer)
1566                 X509_free(peer);
1567         ssl_print_point_formats(bio, s);
1568         if (SSL_is_server(s))
1569                 ssl_print_curves(bio, s, 1);
1570         else
1571                 ssl_print_tmp_key(bio, s);
1572         }
1573
1574 void print_ssl_cert_checks(BIO *bio, SSL *s,
1575                                 const unsigned char *checkhost,
1576                                 const unsigned char *checkemail,
1577                                 const char *checkip)
1578         {
1579         X509 *peer;
1580         peer = SSL_get_peer_certificate(s);
1581         if (peer)
1582                 {
1583                 print_cert_checks(bio, peer, checkhost, checkemail, checkip);
1584                 X509_free(peer);
1585                 }
1586         }
1587
1588 int args_ssl(char ***pargs, int *pargc, SSL_CONF_CTX *cctx,
1589                         int *badarg, BIO *err, STACK_OF(OPENSSL_STRING) **pstr)
1590         {
1591         char *arg = **pargs, *argn = (*pargs)[1];
1592         int rv;
1593
1594         /* Attempt to run SSL configuration command */
1595         rv = SSL_CONF_cmd_argv(cctx, pargc, pargs);
1596         /* If parameter not recognised just return */
1597         if (rv == 0)
1598                 return 0;
1599         /* see if missing argument error */
1600         if (rv == -3)
1601                 {
1602                 BIO_printf(err, "%s needs an argument\n", arg);
1603                 *badarg = 1;
1604                 goto end;
1605                 }
1606         /* Check for some other error */
1607         if (rv < 0)
1608                 {
1609                 BIO_printf(err, "Error with command: \"%s %s\"\n",
1610                                                 arg, argn ? argn : "");
1611                 *badarg = 1;
1612                 goto end;
1613                 }
1614         /* Store command and argument */
1615         /* If only one argument processed store value as NULL */
1616         if (rv == 1)
1617                 argn = NULL;
1618         if (!*pstr)
1619                 *pstr = sk_OPENSSL_STRING_new_null();
1620         if (!*pstr || !sk_OPENSSL_STRING_push(*pstr, arg) ||
1621                                 !sk_OPENSSL_STRING_push(*pstr, argn))
1622                 {
1623                 BIO_puts(err, "Memory allocation failure\n");
1624                 goto end;
1625                 }
1626
1627         end:
1628         if (*badarg)
1629                 ERR_print_errors(err);
1630
1631         return 1;
1632         }
1633
1634 int args_ssl_call(SSL_CTX *ctx, BIO *err, SSL_CONF_CTX *cctx,
1635                                 STACK_OF(OPENSSL_STRING) *str, int no_ecdhe)
1636         {
1637         int i;
1638         SSL_CONF_CTX_set_ssl_ctx(cctx, ctx);
1639         for (i = 0; i < sk_OPENSSL_STRING_num(str); i+= 2)
1640                 {
1641                 const char *param = sk_OPENSSL_STRING_value(str, i);
1642                 const char *value = sk_OPENSSL_STRING_value(str, i + 1);
1643                 /* If no_ecdhe or named curve already specified don't need
1644                  * a default.
1645                  */
1646                 if (!no_ecdhe && !strcmp(param, "-named_curve"))
1647                         no_ecdhe = 1;
1648                 if (SSL_CONF_cmd(cctx, param, value) <= 0)
1649                         {
1650                         BIO_printf(err, "Error with command: \"%s %s\"\n",
1651                                                 param, value ? value : "");
1652                         ERR_print_errors(err);
1653                         return 0;
1654                         }
1655                 }
1656         /* This is a special case to keep existing s_server functionality:
1657          * if we don't have any curve specified *and* we haven't disabled
1658          * ECDHE then use P-256.
1659          */
1660         if (!no_ecdhe)
1661                 {
1662                 if (SSL_CONF_cmd(cctx, "-named_curve", "P-256") <= 0)
1663                         {
1664                         BIO_puts(err, "Error setting EC curve\n");
1665                         ERR_print_errors(err);
1666                         return 0;
1667                         }
1668                 }
1669         return 1;
1670         }
1671
1672 static int add_crls_store(X509_STORE *st, STACK_OF(X509_CRL) *crls)
1673         {
1674         X509_CRL *crl;
1675         int i;
1676         if (crls)
1677                 {
1678                 for (i = 0; i < sk_X509_CRL_num(crls); i++)
1679                         {
1680                         crl = sk_X509_CRL_value(crls, i);
1681                         X509_STORE_add_crl(st, crl);
1682                         }
1683                 }
1684         return 1;
1685         }
1686
1687 int ssl_ctx_add_crls(SSL_CTX *ctx, STACK_OF(X509_CRL) *crls)
1688         {
1689         X509_STORE *st;
1690         if (crls)
1691                 {
1692                 st = SSL_CTX_get_cert_store(ctx);
1693                 add_crls_store(st, crls);
1694                 }
1695         return 1;
1696         }
1697
1698 int ssl_load_stores(SSL_CTX *ctx,
1699                         const char *vfyCApath, const char *vfyCAfile,
1700                         const char *chCApath, const char *chCAfile,
1701                         STACK_OF(X509_CRL) *crls)
1702         {
1703         X509_STORE *vfy = NULL, *ch = NULL;
1704         int rv = 0;
1705         if (vfyCApath || vfyCAfile)
1706                 {
1707                 vfy = X509_STORE_new();
1708                 if (!X509_STORE_load_locations(vfy, vfyCAfile, vfyCApath))
1709                         goto err;
1710                 add_crls_store(vfy, crls);
1711                 SSL_CTX_set1_verify_cert_store(ctx, vfy);
1712                 }
1713         if (chCApath || chCAfile)
1714                 {
1715                 ch = X509_STORE_new();
1716                 if (!X509_STORE_load_locations(ch, chCAfile, chCApath))
1717                         goto err;
1718                 SSL_CTX_set1_chain_cert_store(ctx, ch);
1719                 }
1720         rv = 1;
1721         err:
1722         if (vfy)
1723                 X509_STORE_free(vfy);
1724         if (ch)
1725                 X509_STORE_free(ch);
1726         return rv;
1727         }