f7207c9208e14886edac37434c0d98a443df733a
[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_error=X509_V_OK;
129 int verify_return_error=0;
130 unsigned char cookie_secret[COOKIE_SECRET_LENGTH];
131 int cookie_initialized=0;
132
133 int MS_CALLBACK verify_callback(int ok, X509_STORE_CTX *ctx)
134         {
135         X509 *err_cert;
136         int err,depth;
137
138         err_cert=X509_STORE_CTX_get_current_cert(ctx);
139         err=    X509_STORE_CTX_get_error(ctx);
140         depth=  X509_STORE_CTX_get_error_depth(ctx);
141
142         BIO_printf(bio_err,"depth=%d ",depth);
143         if (err_cert)
144                 {
145                 X509_NAME_print_ex(bio_err, X509_get_subject_name(err_cert),
146                                         0, XN_FLAG_ONELINE);
147                 BIO_puts(bio_err, "\n");
148                 }
149         else
150                 BIO_puts(bio_err, "<no cert>\n");
151         if (!ok)
152                 {
153                 BIO_printf(bio_err,"verify error:num=%d:%s\n",err,
154                         X509_verify_cert_error_string(err));
155                 if (verify_depth >= depth)
156                         {
157                         if (!verify_return_error)
158                                 ok=1;
159                         verify_error=X509_V_OK;
160                         }
161                 else
162                         {
163                         ok=0;
164                         verify_error=X509_V_ERR_CERT_CHAIN_TOO_LONG;
165                         }
166                 }
167         switch (err)
168                 {
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),
172                                         0, XN_FLAG_ONELINE);
173                 BIO_puts(bio_err, "\n");
174                 break;
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");
180                 break;
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");
186                 break;
187         case X509_V_ERR_NO_EXPLICIT_POLICY:
188                 policies_print(bio_err, ctx);
189                 break;
190                 }
191         if (err == X509_V_OK && ok == 2)
192                 policies_print(bio_err, ctx);
193
194         BIO_printf(bio_err,"verify return:%d\n",ok);
195         return(ok);
196         }
197
198 int set_cert_stuff(SSL_CTX *ctx, char *cert_file, char *key_file)
199         {
200         if (cert_file != NULL)
201                 {
202                 /*
203                 SSL *ssl;
204                 X509 *x509;
205                 */
206
207                 if (SSL_CTX_use_certificate_file(ctx,cert_file,
208                         SSL_FILETYPE_PEM) <= 0)
209                         {
210                         BIO_printf(bio_err,"unable to get certificate from '%s'\n",cert_file);
211                         ERR_print_errors(bio_err);
212                         return(0);
213                         }
214                 if (key_file == NULL) key_file=cert_file;
215                 if (SSL_CTX_use_PrivateKey_file(ctx,key_file,
216                         SSL_FILETYPE_PEM) <= 0)
217                         {
218                         BIO_printf(bio_err,"unable to get private key from '%s'\n",key_file);
219                         ERR_print_errors(bio_err);
220                         return(0);
221                         }
222
223                 /*
224                 In theory this is no longer needed 
225                 ssl=SSL_new(ctx);
226                 x509=SSL_get_certificate(ssl);
227
228                 if (x509 != NULL) {
229                         EVP_PKEY *pktmp;
230                         pktmp = X509_get_pubkey(x509);
231                         EVP_PKEY_copy_parameters(pktmp,
232                                                 SSL_get_privatekey(ssl));
233                         EVP_PKEY_free(pktmp);
234                 }
235                 SSL_free(ssl);
236                 */
237
238                 /* If we are using DSA, we can copy the parameters from
239                  * the private key */
240
241
242                 /* Now we know that a key and cert have been set against
243                  * the SSL context */
244                 if (!SSL_CTX_check_private_key(ctx))
245                         {
246                         BIO_printf(bio_err,"Private key does not match the certificate public key\n");
247                         return(0);
248                         }
249                 }
250         return(1);
251         }
252
253 int set_cert_key_stuff(SSL_CTX *ctx, X509 *cert, EVP_PKEY *key,
254                        STACK_OF(X509) *chain, int build_chain)
255         {
256         if (cert == NULL)
257                 return 1;
258         if (SSL_CTX_use_certificate(ctx,cert) <= 0)
259                 {
260                 BIO_printf(bio_err,"error setting certificate\n");
261                 ERR_print_errors(bio_err);
262                 return 0;
263                 }
264
265         if (SSL_CTX_use_PrivateKey(ctx,key) <= 0)
266                 {
267                 BIO_printf(bio_err,"error setting private key\n");
268                 ERR_print_errors(bio_err);
269                 return 0;
270                 }
271                  
272         /* Now we know that a key and cert have been set against
273          * the SSL context */
274         if (!SSL_CTX_check_private_key(ctx))
275                 {
276                 BIO_printf(bio_err,"Private key does not match the certificate public key\n");
277                 return 0;
278                 }
279         if (chain && !SSL_CTX_set1_chain(ctx, chain))
280                 {
281                 BIO_printf(bio_err,"error setting certificate chain\n");
282                 ERR_print_errors(bio_err);
283                 return 0;
284                 }
285         if (!chain && build_chain && !SSL_CTX_build_cert_chain(ctx, 0))
286                 {
287                 BIO_printf(bio_err,"error building certificate chain\n");
288                 ERR_print_errors(bio_err);
289                 return 0;
290                 }
291                 
292         return 1;
293         }
294
295 static void ssl_print_client_cert_types(BIO *bio, SSL *s)
296         {
297         const unsigned char *p;
298         int i;
299         int cert_type_num = SSL_get0_certificate_types(s, &p);
300         if (!cert_type_num)
301                 return;
302         BIO_puts(bio, "Client Certificate Types: ");
303         for (i = 0; i < cert_type_num; i++)
304                 {
305                 unsigned char cert_type = p[i];
306                 char *cname;
307                 switch(cert_type)
308                         {
309                 case TLS_CT_RSA_SIGN:
310                         cname = "RSA sign";
311                         break;
312
313                 case TLS_CT_DSS_SIGN:
314                         cname = "DSA sign";
315                         break;
316
317                 case TLS_CT_RSA_FIXED_DH:
318                         cname = "RSA fixed DH";
319                         break;
320
321                 case TLS_CT_DSS_FIXED_DH:
322                         cname = "DSS fixed DH";
323                         break;
324
325                 case TLS_CT_ECDSA_SIGN:
326                         cname = "ECDSA sign";
327                         break;
328
329                 case TLS_CT_RSA_FIXED_ECDH:
330                         cname = "RSA fixed ECDH";
331                         break;
332
333                 case TLS_CT_ECDSA_FIXED_ECDH:
334                         cname = "ECDSA fixed ECDH";
335                         break;
336
337                 case TLS_CT_GOST94_SIGN:
338                         cname = "GOST94 Sign";
339                         break;
340
341                 case TLS_CT_GOST01_SIGN:
342                         cname = "GOST01 Sign";
343                         break;
344
345                 default:
346                          cname = NULL;
347                         }
348
349                 if (i)
350                         BIO_puts(bio, ", ");
351
352                 if (cname)
353                         BIO_puts(bio, cname);
354                 else
355                         BIO_printf(bio, "UNKNOWN (%d),", cert_type);
356                 }
357         BIO_puts(bio, "\n");
358         }
359
360 static int do_print_sigalgs(BIO *out, SSL *s, int shared)
361         {
362         int i, nsig, client;
363         client = SSL_is_server(s) ? 0 : 1;
364         if (shared)
365                 nsig = SSL_get_shared_sigalgs(s, -1, NULL, NULL, NULL,
366                                                         NULL, NULL);
367         else
368                 nsig = SSL_get_sigalgs(s, -1, NULL, NULL, NULL, NULL, NULL);
369         if (nsig == 0)
370                 return 1;
371
372         if (shared)
373                 BIO_puts(out, "Shared ");
374
375         if (client)
376                 BIO_puts(out, "Requested ");
377         BIO_puts(out, "Signature Algorithms: ");
378         for (i = 0; i < nsig; i++)
379                 {
380                 int hash_nid, sign_nid;
381                 unsigned char rhash, rsign;
382                 const char *sstr = NULL;
383                 if (shared)
384                         SSL_get_shared_sigalgs(s, i, &sign_nid, &hash_nid, NULL,
385                                                         &rsign, &rhash);
386                 else
387                         SSL_get_sigalgs(s, i, &sign_nid, &hash_nid, NULL,
388                                                         &rsign, &rhash);
389                 if (i)
390                         BIO_puts(out, ":");
391                 if (sign_nid == EVP_PKEY_RSA)
392                         sstr = "RSA";
393                 else if(sign_nid == EVP_PKEY_DSA)
394                         sstr = "DSA";
395                 else if(sign_nid == EVP_PKEY_EC)
396                         sstr = "ECDSA";
397                 if (sstr)
398                         BIO_printf(out,"%s+", sstr);
399                 else
400                         BIO_printf(out,"0x%02X+", (int)rsign);
401                 if (hash_nid != NID_undef)
402                         BIO_printf(out, "%s", OBJ_nid2sn(hash_nid));
403                 else
404                         BIO_printf(out,"0x%02X", (int)rhash);
405                 }
406         BIO_puts(out, "\n");
407         return 1;
408         }
409
410 int ssl_print_sigalgs(BIO *out, SSL *s)
411         {
412         if (!SSL_is_server(s))
413                 ssl_print_client_cert_types(out, s);
414         do_print_sigalgs(out, s, 0);
415         do_print_sigalgs(out, s, 1);
416         return 1;
417         }
418
419 int ssl_print_curves(BIO *out, SSL *s)
420         {
421         int i, ncurves, *curves, nid;
422         const char *cname;
423         ncurves = SSL_get1_curves(s, NULL);
424         if (ncurves <= 0)
425                 return 1;
426         curves = OPENSSL_malloc(ncurves * sizeof(int));
427         SSL_get1_curves(s, curves);
428
429         BIO_puts(out, "Supported Elliptic Curves: ");
430         for (i = 0; i < ncurves; i++)
431                 {
432                 if (i)
433                         BIO_puts(out, ":");
434                 nid = curves[i];
435                 /* If unrecognised print out hex version */
436                 if (nid & TLSEXT_nid_unknown)
437                         BIO_printf(out, "0x%04X", nid & 0xFFFF);
438                 else
439                         {
440                         /* Use NIST name for curve if it exists */
441                         cname = EC_curve_nid2nist(nid);
442                         if (!cname)
443                                 cname = OBJ_nid2sn(nid);
444                         BIO_printf(out, "%s", cname);
445                         }
446                 }
447         BIO_puts(out, "\nShared Elliptic curves: ");
448         OPENSSL_free(curves);
449         ncurves = SSL_get_shared_curve(s, -1);
450         for (i = 0; i < ncurves; i++)
451                 {
452                 if (i)
453                         BIO_puts(out, ":");
454                 nid = SSL_get_shared_curve(s, i);
455                 cname = EC_curve_nid2nist(nid);
456                 if (!cname)
457                         cname = OBJ_nid2sn(nid);
458                 BIO_printf(out, "%s", cname);
459                 }
460         if (ncurves == 0)
461                 BIO_puts(out, "NONE");
462         BIO_puts(out, "\n");
463         return 1;
464         }
465
466
467 long MS_CALLBACK bio_dump_callback(BIO *bio, int cmd, const char *argp,
468                                    int argi, long argl, long ret)
469         {
470         BIO *out;
471
472         out=(BIO *)BIO_get_callback_arg(bio);
473         if (out == NULL) return(ret);
474
475         if (cmd == (BIO_CB_READ|BIO_CB_RETURN))
476                 {
477                 BIO_printf(out,"read from %p [%p] (%lu bytes => %ld (0x%lX))\n",
478                         (void *)bio,argp,(unsigned long)argi,ret,ret);
479                 BIO_dump(out,argp,(int)ret);
480                 return(ret);
481                 }
482         else if (cmd == (BIO_CB_WRITE|BIO_CB_RETURN))
483                 {
484                 BIO_printf(out,"write to %p [%p] (%lu bytes => %ld (0x%lX))\n",
485                         (void *)bio,argp,(unsigned long)argi,ret,ret);
486                 BIO_dump(out,argp,(int)ret);
487                 }
488         return(ret);
489         }
490
491 void MS_CALLBACK apps_ssl_info_callback(const SSL *s, int where, int ret)
492         {
493         const char *str;
494         int w;
495
496         w=where& ~SSL_ST_MASK;
497
498         if (w & SSL_ST_CONNECT) str="SSL_connect";
499         else if (w & SSL_ST_ACCEPT) str="SSL_accept";
500         else str="undefined";
501
502         if (where & SSL_CB_LOOP)
503                 {
504                 BIO_printf(bio_err,"%s:%s\n",str,SSL_state_string_long(s));
505                 }
506         else if (where & SSL_CB_ALERT)
507                 {
508                 str=(where & SSL_CB_READ)?"read":"write";
509                 BIO_printf(bio_err,"SSL3 alert %s:%s:%s\n",
510                         str,
511                         SSL_alert_type_string_long(ret),
512                         SSL_alert_desc_string_long(ret));
513                 }
514         else if (where & SSL_CB_EXIT)
515                 {
516                 if (ret == 0)
517                         BIO_printf(bio_err,"%s:failed in %s\n",
518                                 str,SSL_state_string_long(s));
519                 else if (ret < 0)
520                         {
521                         BIO_printf(bio_err,"%s:error in %s\n",
522                                 str,SSL_state_string_long(s));
523                         }
524                 }
525         }
526
527
528 void MS_CALLBACK msg_cb(int write_p, int version, int content_type, const void *buf, size_t len, SSL *ssl, void *arg)
529         {
530         BIO *bio = arg;
531         const char *str_write_p, *str_version, *str_content_type = "", *str_details1 = "", *str_details2= "";
532         
533         str_write_p = write_p ? ">>>" : "<<<";
534
535         switch (version)
536                 {
537         case SSL2_VERSION:
538                 str_version = "SSL 2.0";
539                 break;
540         case SSL3_VERSION:
541                 str_version = "SSL 3.0 ";
542                 break;
543         case TLS1_VERSION:
544                 str_version = "TLS 1.0 ";
545                 break;
546         case TLS1_1_VERSION:
547                 str_version = "TLS 1.1 ";
548                 break;
549         case TLS1_2_VERSION:
550                 str_version = "TLS 1.2 ";
551                 break;
552         case DTLS1_VERSION:
553                 str_version = "DTLS 1.0 ";
554                 break;
555         case DTLS1_BAD_VER:
556                 str_version = "DTLS 1.0 (bad) ";
557                 break;
558         default:
559                 str_version = "???";
560                 }
561
562         if (version == SSL2_VERSION)
563                 {
564                 str_details1 = "???";
565
566                 if (len > 0)
567                         {
568                         switch (((const unsigned char*)buf)[0])
569                                 {
570                                 case 0:
571                                         str_details1 = ", ERROR:";
572                                         str_details2 = " ???";
573                                         if (len >= 3)
574                                                 {
575                                                 unsigned err = (((const unsigned char*)buf)[1]<<8) + ((const unsigned char*)buf)[2];
576                                                 
577                                                 switch (err)
578                                                         {
579                                                 case 0x0001:
580                                                         str_details2 = " NO-CIPHER-ERROR";
581                                                         break;
582                                                 case 0x0002:
583                                                         str_details2 = " NO-CERTIFICATE-ERROR";
584                                                         break;
585                                                 case 0x0004:
586                                                         str_details2 = " BAD-CERTIFICATE-ERROR";
587                                                         break;
588                                                 case 0x0006:
589                                                         str_details2 = " UNSUPPORTED-CERTIFICATE-TYPE-ERROR";
590                                                         break;
591                                                         }
592                                                 }
593
594                                         break;
595                                 case 1:
596                                         str_details1 = ", CLIENT-HELLO";
597                                         break;
598                                 case 2:
599                                         str_details1 = ", CLIENT-MASTER-KEY";
600                                         break;
601                                 case 3:
602                                         str_details1 = ", CLIENT-FINISHED";
603                                         break;
604                                 case 4:
605                                         str_details1 = ", SERVER-HELLO";
606                                         break;
607                                 case 5:
608                                         str_details1 = ", SERVER-VERIFY";
609                                         break;
610                                 case 6:
611                                         str_details1 = ", SERVER-FINISHED";
612                                         break;
613                                 case 7:
614                                         str_details1 = ", REQUEST-CERTIFICATE";
615                                         break;
616                                 case 8:
617                                         str_details1 = ", CLIENT-CERTIFICATE";
618                                         break;
619                                 }
620                         }
621                 }
622
623         if (version == SSL3_VERSION ||
624             version == TLS1_VERSION ||
625             version == DTLS1_VERSION ||
626             version == DTLS1_BAD_VER)
627                 {
628                 switch (content_type)
629                         {
630                 case 20:
631                         str_content_type = "ChangeCipherSpec";
632                         break;
633                 case 21:
634                         str_content_type = "Alert";
635                         break;
636                 case 22:
637                         str_content_type = "Handshake";
638                         break;
639                         }
640
641                 if (content_type == 21) /* Alert */
642                         {
643                         str_details1 = ", ???";
644                         
645                         if (len == 2)
646                                 {
647                                 switch (((const unsigned char*)buf)[0])
648                                         {
649                                 case 1:
650                                         str_details1 = ", warning";
651                                         break;
652                                 case 2:
653                                         str_details1 = ", fatal";
654                                         break;
655                                         }
656
657                                 str_details2 = " ???";
658                                 switch (((const unsigned char*)buf)[1])
659                                         {
660                                 case 0:
661                                         str_details2 = " close_notify";
662                                         break;
663                                 case 10:
664                                         str_details2 = " unexpected_message";
665                                         break;
666                                 case 20:
667                                         str_details2 = " bad_record_mac";
668                                         break;
669                                 case 21:
670                                         str_details2 = " decryption_failed";
671                                         break;
672                                 case 22:
673                                         str_details2 = " record_overflow";
674                                         break;
675                                 case 30:
676                                         str_details2 = " decompression_failure";
677                                         break;
678                                 case 40:
679                                         str_details2 = " handshake_failure";
680                                         break;
681                                 case 42:
682                                         str_details2 = " bad_certificate";
683                                         break;
684                                 case 43:
685                                         str_details2 = " unsupported_certificate";
686                                         break;
687                                 case 44:
688                                         str_details2 = " certificate_revoked";
689                                         break;
690                                 case 45:
691                                         str_details2 = " certificate_expired";
692                                         break;
693                                 case 46:
694                                         str_details2 = " certificate_unknown";
695                                         break;
696                                 case 47:
697                                         str_details2 = " illegal_parameter";
698                                         break;
699                                 case 48:
700                                         str_details2 = " unknown_ca";
701                                         break;
702                                 case 49:
703                                         str_details2 = " access_denied";
704                                         break;
705                                 case 50:
706                                         str_details2 = " decode_error";
707                                         break;
708                                 case 51:
709                                         str_details2 = " decrypt_error";
710                                         break;
711                                 case 60:
712                                         str_details2 = " export_restriction";
713                                         break;
714                                 case 70:
715                                         str_details2 = " protocol_version";
716                                         break;
717                                 case 71:
718                                         str_details2 = " insufficient_security";
719                                         break;
720                                 case 80:
721                                         str_details2 = " internal_error";
722                                         break;
723                                 case 90:
724                                         str_details2 = " user_canceled";
725                                         break;
726                                 case 100:
727                                         str_details2 = " no_renegotiation";
728                                         break;
729                                 case 110:
730                                         str_details2 = " unsupported_extension";
731                                         break;
732                                 case 111:
733                                         str_details2 = " certificate_unobtainable";
734                                         break;
735                                 case 112:
736                                         str_details2 = " unrecognized_name";
737                                         break;
738                                 case 113:
739                                         str_details2 = " bad_certificate_status_response";
740                                         break;
741                                 case 114:
742                                         str_details2 = " bad_certificate_hash_value";
743                                         break;
744                                 case 115:
745                                         str_details2 = " unknown_psk_identity";
746                                         break;
747                                         }
748                                 }
749                         }
750                 
751                 if (content_type == 22) /* Handshake */
752                         {
753                         str_details1 = "???";
754
755                         if (len > 0)
756                                 {
757                                 switch (((const unsigned char*)buf)[0])
758                                         {
759                                 case 0:
760                                         str_details1 = ", HelloRequest";
761                                         break;
762                                 case 1:
763                                         str_details1 = ", ClientHello";
764                                         break;
765                                 case 2:
766                                         str_details1 = ", ServerHello";
767                                         break;
768                                 case 3:
769                                         str_details1 = ", HelloVerifyRequest";
770                                         break;
771                                 case 11:
772                                         str_details1 = ", Certificate";
773                                         break;
774                                 case 12:
775                                         str_details1 = ", ServerKeyExchange";
776                                         break;
777                                 case 13:
778                                         str_details1 = ", CertificateRequest";
779                                         break;
780                                 case 14:
781                                         str_details1 = ", ServerHelloDone";
782                                         break;
783                                 case 15:
784                                         str_details1 = ", CertificateVerify";
785                                         break;
786                                 case 16:
787                                         str_details1 = ", ClientKeyExchange";
788                                         break;
789                                 case 20:
790                                         str_details1 = ", Finished";
791                                         break;
792                                         }
793                                 }
794                         }
795
796 #ifndef OPENSSL_NO_HEARTBEATS
797                 if (content_type == 24) /* Heartbeat */
798                         {
799                         str_details1 = ", Heartbeat";
800                         
801                         if (len > 0)
802                                 {
803                                 switch (((const unsigned char*)buf)[0])
804                                         {
805                                 case 1:
806                                         str_details1 = ", HeartbeatRequest";
807                                         break;
808                                 case 2:
809                                         str_details1 = ", HeartbeatResponse";
810                                         break;
811                                         }
812                                 }
813                         }
814 #endif
815                 }
816
817         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);
818
819         if (len > 0)
820                 {
821                 size_t num, i;
822                 
823                 BIO_printf(bio, "   ");
824                 num = len;
825 #if 0
826                 if (num > 16)
827                         num = 16;
828 #endif
829                 for (i = 0; i < num; i++)
830                         {
831                         if (i % 16 == 0 && i > 0)
832                                 BIO_printf(bio, "\n   ");
833                         BIO_printf(bio, " %02x", ((const unsigned char*)buf)[i]);
834                         }
835                 if (i < len)
836                         BIO_printf(bio, " ...");
837                 BIO_printf(bio, "\n");
838                 }
839         (void)BIO_flush(bio);
840         }
841
842 void MS_CALLBACK tlsext_cb(SSL *s, int client_server, int type,
843                                         unsigned char *data, int len,
844                                         void *arg)
845         {
846         BIO *bio = arg;
847         char *extname;
848
849         switch(type)
850                 {
851                 case TLSEXT_TYPE_server_name:
852                 extname = "server name";
853                 break;
854
855                 case TLSEXT_TYPE_max_fragment_length:
856                 extname = "max fragment length";
857                 break;
858
859                 case TLSEXT_TYPE_client_certificate_url:
860                 extname = "client certificate URL";
861                 break;
862
863                 case TLSEXT_TYPE_trusted_ca_keys:
864                 extname = "trusted CA keys";
865                 break;
866
867                 case TLSEXT_TYPE_truncated_hmac:
868                 extname = "truncated HMAC";
869                 break;
870
871                 case TLSEXT_TYPE_status_request:
872                 extname = "status request";
873                 break;
874
875                 case TLSEXT_TYPE_user_mapping:
876                 extname = "user mapping";
877                 break;
878
879                 case TLSEXT_TYPE_client_authz:
880                 extname = "client authz";
881                 break;
882
883                 case TLSEXT_TYPE_server_authz:
884                 extname = "server authz";
885                 break;
886
887                 case TLSEXT_TYPE_cert_type:
888                 extname = "cert type";
889                 break;
890
891                 case TLSEXT_TYPE_elliptic_curves:
892                 extname = "elliptic curves";
893                 break;
894
895                 case TLSEXT_TYPE_ec_point_formats:
896                 extname = "EC point formats";
897                 break;
898
899                 case TLSEXT_TYPE_srp:
900                 extname = "SRP";
901                 break;
902
903                 case TLSEXT_TYPE_signature_algorithms:
904                 extname = "signature algorithms";
905                 break;
906
907                 case TLSEXT_TYPE_use_srtp:
908                 extname = "use SRTP";
909                 break;
910
911                 case TLSEXT_TYPE_heartbeat:
912                 extname = "heartbeat";
913                 break;
914
915                 case TLSEXT_TYPE_session_ticket:
916                 extname = "session ticket";
917                 break;
918
919                 case TLSEXT_TYPE_renegotiate: 
920                 extname = "renegotiation info";
921                 break;
922
923 #ifdef TLSEXT_TYPE_opaque_prf_input
924                 case TLSEXT_TYPE_opaque_prf_input:
925                 extname = "opaque PRF input";
926                 break;
927 #endif
928 #ifdef TLSEXT_TYPE_next_proto_neg
929                 case TLSEXT_TYPE_next_proto_neg:
930                 extname = "next protocol";
931                 break;
932 #endif
933
934                 default:
935                 extname = "unknown";
936                 break;
937
938                 }
939         
940         BIO_printf(bio, "TLS %s extension \"%s\" (id=%d), len=%d\n",
941                         client_server ? "server": "client",
942                         extname, type, len);
943         BIO_dump(bio, (char *)data, len);
944         (void)BIO_flush(bio);
945         }
946
947 int MS_CALLBACK generate_cookie_callback(SSL *ssl, unsigned char *cookie, unsigned int *cookie_len)
948         {
949         unsigned char *buffer, result[EVP_MAX_MD_SIZE];
950         unsigned int length, resultlength;
951         union {
952                 struct sockaddr sa;
953                 struct sockaddr_in s4;
954 #if OPENSSL_USE_IPV6
955                 struct sockaddr_in6 s6;
956 #endif
957         } peer;
958
959         /* Initialize a random secret */
960         if (!cookie_initialized)
961                 {
962                 if (!RAND_bytes(cookie_secret, COOKIE_SECRET_LENGTH))
963                         {
964                         BIO_printf(bio_err,"error setting random cookie secret\n");
965                         return 0;
966                         }
967                 cookie_initialized = 1;
968                 }
969
970         /* Read peer information */
971         (void)BIO_dgram_get_peer(SSL_get_rbio(ssl), &peer);
972
973         /* Create buffer with peer's address and port */
974         length = 0;
975         switch (peer.sa.sa_family)
976                 {
977         case AF_INET:
978                 length += sizeof(struct in_addr);
979                 length += sizeof(peer.s4.sin_port);
980                 break;
981 #if OPENSSL_USE_IPV6
982         case AF_INET6:
983                 length += sizeof(struct in6_addr);
984                 length += sizeof(peer.s6.sin6_port);
985                 break;
986 #endif
987         default:
988                 OPENSSL_assert(0);
989                 break;
990                 }
991         buffer = OPENSSL_malloc(length);
992
993         if (buffer == NULL)
994                 {
995                 BIO_printf(bio_err,"out of memory\n");
996                 return 0;
997                 }
998
999         switch (peer.sa.sa_family)
1000                 {
1001         case AF_INET:
1002                 memcpy(buffer,
1003                        &peer.s4.sin_port,
1004                        sizeof(peer.s4.sin_port));
1005                 memcpy(buffer + sizeof(peer.s4.sin_port),
1006                        &peer.s4.sin_addr,
1007                        sizeof(struct in_addr));
1008                 break;
1009 #if OPENSSL_USE_IPV6
1010         case AF_INET6:
1011                 memcpy(buffer,
1012                        &peer.s6.sin6_port,
1013                        sizeof(peer.s6.sin6_port));
1014                 memcpy(buffer + sizeof(peer.s6.sin6_port),
1015                        &peer.s6.sin6_addr,
1016                        sizeof(struct in6_addr));
1017                 break;
1018 #endif
1019         default:
1020                 OPENSSL_assert(0);
1021                 break;
1022                 }
1023
1024         /* Calculate HMAC of buffer using the secret */
1025         HMAC(EVP_sha1(), cookie_secret, COOKIE_SECRET_LENGTH,
1026              buffer, length, result, &resultlength);
1027         OPENSSL_free(buffer);
1028
1029         memcpy(cookie, result, resultlength);
1030         *cookie_len = resultlength;
1031
1032         return 1;
1033         }
1034
1035 int MS_CALLBACK verify_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         /* If secret isn't initialized yet, the cookie can't be valid */
1048         if (!cookie_initialized)
1049                 return 0;
1050
1051         /* Read peer information */
1052         (void)BIO_dgram_get_peer(SSL_get_rbio(ssl), &peer);
1053
1054         /* Create buffer with peer's address and port */
1055         length = 0;
1056         switch (peer.sa.sa_family)
1057                 {
1058         case AF_INET:
1059                 length += sizeof(struct in_addr);
1060                 length += sizeof(peer.s4.sin_port);
1061                 break;
1062 #if OPENSSL_USE_IPV6
1063         case AF_INET6:
1064                 length += sizeof(struct in6_addr);
1065                 length += sizeof(peer.s6.sin6_port);
1066                 break;
1067 #endif
1068         default:
1069                 OPENSSL_assert(0);
1070                 break;
1071                 }
1072         buffer = OPENSSL_malloc(length);
1073         
1074         if (buffer == NULL)
1075                 {
1076                 BIO_printf(bio_err,"out of memory\n");
1077                 return 0;
1078                 }
1079
1080         switch (peer.sa.sa_family)
1081                 {
1082         case AF_INET:
1083                 memcpy(buffer,
1084                        &peer.s4.sin_port,
1085                        sizeof(peer.s4.sin_port));
1086                 memcpy(buffer + sizeof(peer.s4.sin_port),
1087                        &peer.s4.sin_addr,
1088                        sizeof(struct in_addr));
1089                 break;
1090 #if OPENSSL_USE_IPV6
1091         case AF_INET6:
1092                 memcpy(buffer,
1093                        &peer.s6.sin6_port,
1094                        sizeof(peer.s6.sin6_port));
1095                 memcpy(buffer + sizeof(peer.s6.sin6_port),
1096                        &peer.s6.sin6_addr,
1097                        sizeof(struct in6_addr));
1098                 break;
1099 #endif
1100         default:
1101                 OPENSSL_assert(0);
1102                 break;
1103                 }
1104
1105         /* Calculate HMAC of buffer using the secret */
1106         HMAC(EVP_sha1(), cookie_secret, COOKIE_SECRET_LENGTH,
1107              buffer, length, result, &resultlength);
1108         OPENSSL_free(buffer);
1109
1110         if (cookie_len == resultlength && memcmp(result, cookie, resultlength) == 0)
1111                 return 1;
1112
1113         return 0;
1114         }
1115
1116 /* Example of extended certificate handling. Where the standard support
1117  * of one certificate per algorithm is not sufficient an application
1118  * can decide which certificate(s) to use at runtime based on whatever
1119  * criteria it deems appropriate.
1120  */
1121
1122 /* Linked list of certificates, keys and chains */
1123 struct  ssl_excert_st
1124         {
1125         int certform;
1126         const char *certfile;
1127         int keyform;
1128         const char *keyfile;
1129         const char *chainfile;
1130         X509 *cert;
1131         EVP_PKEY *key;
1132         STACK_OF(X509) *chain;
1133         int build_chain;
1134         struct ssl_excert_st *next, *prev;
1135         };
1136
1137 struct chain_flags
1138         {
1139         int flag;
1140         const char *name;
1141         };
1142
1143 struct chain_flags chain_flags_list[] =
1144         {
1145                 {CERT_PKEY_VALID, "Overall Validity"},
1146                 {CERT_PKEY_SIGN,  "Sign with EE key"},
1147                 {CERT_PKEY_EE_SIGNATURE, "EE signature"},
1148                 {CERT_PKEY_CA_SIGNATURE, "CA signature"},
1149                 {CERT_PKEY_EE_PARAM, "EE key parameters"},
1150                 {CERT_PKEY_CA_PARAM, "CA key parameters"},
1151                 {CERT_PKEY_EXPLICIT_SIGN,  "Explicity sign with EE key"},
1152                 {CERT_PKEY_ISSUER_NAME,  "Issuer Name"},
1153                 {CERT_PKEY_CERT_TYPE,  "Certificate Type"},
1154                 {0, NULL}
1155         };
1156
1157
1158 static void print_chain_flags(BIO *out, int flags)
1159         {
1160         struct chain_flags *ctmp = chain_flags_list;
1161         while(ctmp->name)
1162                 {
1163                 BIO_printf(out, "\t%s: %s\n", ctmp->name,
1164                                 flags & ctmp->flag ? "OK" : "NOT OK");
1165                 ctmp++;
1166                 }
1167         }
1168
1169 /* Very basic selection callback: just use any certificate chain
1170  * reported as valid. More sophisticated could prioritise according
1171  * to local policy.
1172  */
1173 static int set_cert_cb(SSL *ssl, void *arg)
1174         {
1175         int i, rv;
1176         SSL_EXCERT *exc = arg;
1177         SSL_certs_clear(ssl);
1178
1179         if (!exc)
1180                 return 1;
1181
1182         /* Go to end of list and traverse backwards since we prepend
1183          * newer entries this retains the original order.
1184          */
1185         while (exc->next)
1186                 exc = exc->next;
1187
1188         i = 0;  
1189
1190         while(exc)
1191                 {
1192                 i++;
1193                 rv = SSL_check_chain(ssl, exc->cert, exc->key, exc->chain);
1194                 BIO_printf(bio_err, "Checking cert chain %d:\nSubject: ", i);
1195                 X509_NAME_print_ex(bio_err, X509_get_subject_name(exc->cert), 0,
1196                                                         XN_FLAG_ONELINE);
1197                 BIO_puts(bio_err, "\n");
1198                 
1199                 print_chain_flags(bio_err, rv);
1200                 if (rv & CERT_PKEY_VALID)
1201                         {
1202                         SSL_use_certificate(ssl, exc->cert);
1203                         SSL_use_PrivateKey(ssl, exc->key);
1204                         /* NB: we wouldn't normally do this as it is
1205                          * not efficient building chains on each connection
1206                          * better to cache the chain in advance.
1207                          */
1208                         if (exc->build_chain)
1209                                 {
1210                                 if (!SSL_build_cert_chain(ssl, 0))
1211                                         return 0;
1212                                 }
1213                         else if (exc->chain)
1214                                 SSL_set1_chain(ssl, exc->chain);
1215                         }
1216                 exc = exc->prev;
1217                 }
1218         return 1;
1219         }
1220
1221 void ssl_ctx_set_excert(SSL_CTX *ctx, SSL_EXCERT *exc)
1222         {
1223         SSL_CTX_set_cert_cb(ctx, set_cert_cb, exc);
1224         }
1225
1226 static int ssl_excert_prepend(SSL_EXCERT **pexc)
1227         {
1228         SSL_EXCERT *exc;
1229         exc = OPENSSL_malloc(sizeof(SSL_EXCERT));
1230         if (!exc)
1231                 return 0;
1232         exc->certfile = NULL;
1233         exc->keyfile = NULL;
1234         exc->chainfile = NULL;
1235         exc->cert = NULL;
1236         exc->key = NULL;
1237         exc->chain = NULL;
1238         exc->prev = NULL;
1239         exc->build_chain = 0;
1240
1241         exc->next = *pexc;
1242         *pexc = exc;
1243                         
1244         if (exc->next)
1245                 {
1246                 exc->certform = exc->next->certform;
1247                 exc->keyform = exc->next->keyform;
1248                 exc->next->prev = exc;
1249                 }
1250         else
1251                 {
1252                 exc->certform = FORMAT_PEM;
1253                 exc->keyform = FORMAT_PEM;
1254                 }
1255         return 1;
1256
1257         }
1258
1259 void ssl_excert_free(SSL_EXCERT *exc)
1260         {
1261         SSL_EXCERT *curr;
1262         while (exc)
1263                 {
1264                 if (exc->cert)
1265                         X509_free(exc->cert);
1266                 if (exc->key)
1267                         EVP_PKEY_free(exc->key);
1268                 if (exc->chain)
1269                         sk_X509_pop_free(exc->chain, X509_free);
1270                 curr = exc;
1271                 exc = exc->next;
1272                 OPENSSL_free(curr);
1273                 }
1274         }
1275
1276 int load_excert(SSL_EXCERT **pexc, BIO *err)
1277         {
1278         SSL_EXCERT *exc = *pexc;
1279         if (!exc)
1280                 return 1;
1281         /* If nothing in list, free and set to NULL */
1282         if (!exc->certfile && !exc->next)
1283                 {
1284                 ssl_excert_free(exc);
1285                 *pexc = NULL;
1286                 return 1;
1287                 }
1288         for(; exc; exc=exc->next)
1289                 {
1290                 if (!exc->certfile)
1291                         {
1292                         BIO_printf(err, "Missing filename\n");
1293                         return 0;
1294                         }
1295                 exc->cert = load_cert(err, exc->certfile, exc->certform,
1296                                         NULL, NULL, "Server Certificate");
1297                 if (!exc->cert)
1298                         return 0;
1299                 if (exc->keyfile)
1300                         exc->keyfile = exc->certfile;
1301                 exc->key = load_key(err, exc->certfile, exc->certform, 0,
1302                                         NULL, NULL, "Server Certificate");
1303                 if (!exc->key)
1304                         return 0;
1305                 if (exc->chainfile)
1306                         {
1307                         exc->chain = load_certs(err,
1308                                                 exc->chainfile, FORMAT_PEM,
1309                                                 NULL, NULL,
1310                                                 "Server Chain");
1311                         if (!exc->chainfile)
1312                                 return 0;
1313                         }
1314                 }
1315         return 1;
1316         }
1317                 
1318
1319 int args_excert(char ***pargs, int *pargc,
1320                         int *badarg, BIO *err, SSL_EXCERT **pexc)
1321         {
1322         char *arg = **pargs, *argn = (*pargs)[1];
1323         SSL_EXCERT *exc = *pexc;
1324         int narg = 2;
1325         if (!exc)
1326                 {
1327                 if (ssl_excert_prepend(&exc))
1328                         *pexc = exc;
1329                 else
1330                         {
1331                         BIO_printf(err, "Error initialising xcert\n");
1332                         *badarg = 1;
1333                         goto err;
1334                         }
1335                 }
1336         if (strcmp(arg, "-xcert") == 0)
1337                 {
1338                 if (!argn)
1339                         {
1340                         *badarg = 1;
1341                         return 1;
1342                         }
1343                 if (exc->certfile && !ssl_excert_prepend(&exc))
1344                         {
1345                         BIO_printf(err, "Error adding xcert\n");
1346                         *badarg = 1;
1347                         goto err;
1348                         }
1349                 exc->certfile = argn;
1350                 }
1351         else if (strcmp(arg,"-xkey") == 0)
1352                 {
1353                 if (!argn)
1354                         {
1355                         *badarg = 1;
1356                         return 1;
1357                         }
1358                 if (exc->keyfile)
1359                         {
1360                         BIO_printf(err, "Key already specified\n");
1361                         *badarg = 1;
1362                         return 1;
1363                         }
1364                 exc->keyfile = argn;
1365                 }
1366         else if (strcmp(arg,"-xchain") == 0)
1367                 {
1368                 if (!argn)
1369                         {
1370                         *badarg = 1;
1371                         return 1;
1372                         }
1373                 if (exc->chainfile)
1374                         {
1375                         BIO_printf(err, "Chain already specified\n");
1376                         *badarg = 1;
1377                         return 1;
1378                         }
1379                 exc->chainfile = argn;
1380                 }
1381         else if (strcmp(arg,"-xchain_build") == 0)
1382                 {
1383                 narg = 1;
1384                 exc->build_chain = 1;
1385                 }
1386         else if (strcmp(arg,"-xcertform") == 0)
1387                 {
1388                 if (!argn)
1389                         {
1390                         *badarg = 1;
1391                         goto err;
1392                         }
1393                 exc->certform = str2fmt(argn);
1394                 }
1395         else if (strcmp(arg,"-xkeyform") == 0)
1396                 {
1397                 if (!argn)
1398                         {
1399                         *badarg = 1;
1400                         goto err;
1401                         }
1402                 exc->keyform = str2fmt(argn);
1403                 }
1404         else
1405                 return 0;
1406
1407         (*pargs) += narg;
1408
1409         if (pargc)
1410                 *pargc -= narg;
1411
1412         *pexc = exc;
1413
1414         return 1;
1415
1416         err:
1417         ERR_print_errors(err);
1418         ssl_excert_free(exc);
1419         *pexc = NULL;
1420         return 1;
1421         }
1422