Optimize session cache flushing
[openssl.git] / ssl / ssl_rsa.c
1 /*
2  * Copyright 1995-2021 The OpenSSL Project Authors. All Rights Reserved.
3  *
4  * Licensed under the Apache License 2.0 (the "License").  You may not use
5  * this file except in compliance with the License.  You can obtain a copy
6  * in the file LICENSE in the source distribution or at
7  * https://www.openssl.org/source/license.html
8  */
9
10 #include <stdio.h>
11 #include "ssl_local.h"
12 #include "internal/packet.h"
13 #include <openssl/bio.h>
14 #include <openssl/objects.h>
15 #include <openssl/evp.h>
16 #include <openssl/x509.h>
17 #include <openssl/x509v3.h>
18 #include <openssl/pem.h>
19
20 static int ssl_set_cert(CERT *c, X509 *x509);
21 static int ssl_set_pkey(CERT *c, EVP_PKEY *pkey);
22
23 #define  SYNTHV1CONTEXT     (SSL_EXT_TLS1_2_AND_BELOW_ONLY \
24                              | SSL_EXT_CLIENT_HELLO \
25                              | SSL_EXT_TLS1_2_SERVER_HELLO \
26                              | SSL_EXT_IGNORE_ON_RESUMPTION)
27
28 int SSL_use_certificate(SSL *ssl, X509 *x)
29 {
30     int rv;
31     if (x == NULL) {
32         ERR_raise(ERR_LIB_SSL, ERR_R_PASSED_NULL_PARAMETER);
33         return 0;
34     }
35
36     rv = ssl_security_cert(ssl, NULL, x, 0, 1);
37     if (rv != 1) {
38         ERR_raise(ERR_LIB_SSL, rv);
39         return 0;
40     }
41
42     return ssl_set_cert(ssl->cert, x);
43 }
44
45 int SSL_use_certificate_file(SSL *ssl, const char *file, int type)
46 {
47     int j;
48     BIO *in;
49     int ret = 0;
50     X509 *cert = NULL, *x = NULL;
51
52     in = BIO_new(BIO_s_file());
53     if (in == NULL) {
54         ERR_raise(ERR_LIB_SSL, ERR_R_BUF_LIB);
55         goto end;
56     }
57
58     if (BIO_read_filename(in, file) <= 0) {
59         ERR_raise(ERR_LIB_SSL, ERR_R_SYS_LIB);
60         goto end;
61     }
62
63     if (type != SSL_FILETYPE_ASN1 && type != SSL_FILETYPE_PEM) {
64         ERR_raise(ERR_LIB_SSL, SSL_R_BAD_SSL_FILETYPE);
65         goto end;
66     }
67     x = X509_new_ex(ssl->ctx->libctx, ssl->ctx->propq);
68     if (x == NULL) {
69         ERR_raise(ERR_LIB_SSL, ERR_R_MALLOC_FAILURE);
70         goto end;
71     }
72     if (type == SSL_FILETYPE_ASN1) {
73         j = ERR_R_ASN1_LIB;
74         cert = d2i_X509_bio(in, &x);
75     } else if (type == SSL_FILETYPE_PEM) {
76         j = ERR_R_PEM_LIB;
77         cert = PEM_read_bio_X509(in, &x, ssl->default_passwd_callback,
78                                  ssl->default_passwd_callback_userdata);
79     } else {
80         ERR_raise(ERR_LIB_SSL, SSL_R_BAD_SSL_FILETYPE);
81         goto end;
82     }
83
84     if (cert == NULL) {
85         ERR_raise(ERR_LIB_SSL, j);
86         goto end;
87     }
88
89     ret = SSL_use_certificate(ssl, x);
90  end:
91     X509_free(x);
92     BIO_free(in);
93     return ret;
94 }
95
96 int SSL_use_certificate_ASN1(SSL *ssl, const unsigned char *d, int len)
97 {
98     X509 *x;
99     int ret;
100
101     x = X509_new_ex(ssl->ctx->libctx, ssl->ctx->propq);
102     if (x == NULL) {
103         ERR_raise(ERR_LIB_SSL, ERR_R_MALLOC_FAILURE);
104         return 0;
105     }
106
107     if (d2i_X509(&x, &d, (long)len)== NULL) {
108         X509_free(x);
109         ERR_raise(ERR_LIB_SSL, ERR_R_ASN1_LIB);
110         return 0;
111     }
112
113     ret = SSL_use_certificate(ssl, x);
114     X509_free(x);
115     return ret;
116 }
117
118 static int ssl_set_pkey(CERT *c, EVP_PKEY *pkey)
119 {
120     size_t i;
121
122     if (ssl_cert_lookup_by_pkey(pkey, &i) == NULL) {
123         ERR_raise(ERR_LIB_SSL, SSL_R_UNKNOWN_CERTIFICATE_TYPE);
124         return 0;
125     }
126
127     if (c->pkeys[i].x509 != NULL
128             && !X509_check_private_key(c->pkeys[i].x509, pkey))
129         return 0;
130
131     EVP_PKEY_free(c->pkeys[i].privatekey);
132     EVP_PKEY_up_ref(pkey);
133     c->pkeys[i].privatekey = pkey;
134     c->key = &c->pkeys[i];
135     return 1;
136 }
137
138 int SSL_use_PrivateKey(SSL *ssl, EVP_PKEY *pkey)
139 {
140     int ret;
141
142     if (pkey == NULL) {
143         ERR_raise(ERR_LIB_SSL, ERR_R_PASSED_NULL_PARAMETER);
144         return 0;
145     }
146     ret = ssl_set_pkey(ssl->cert, pkey);
147     return ret;
148 }
149
150 int SSL_use_PrivateKey_file(SSL *ssl, const char *file, int type)
151 {
152     int j, ret = 0;
153     BIO *in;
154     EVP_PKEY *pkey = NULL;
155
156     in = BIO_new(BIO_s_file());
157     if (in == NULL) {
158         ERR_raise(ERR_LIB_SSL, ERR_R_BUF_LIB);
159         goto end;
160     }
161
162     if (BIO_read_filename(in, file) <= 0) {
163         ERR_raise(ERR_LIB_SSL, ERR_R_SYS_LIB);
164         goto end;
165     }
166     if (type == SSL_FILETYPE_PEM) {
167         j = ERR_R_PEM_LIB;
168         pkey = PEM_read_bio_PrivateKey_ex(in, NULL,
169                                           ssl->default_passwd_callback,
170                                           ssl->default_passwd_callback_userdata,
171                                           ssl->ctx->libctx,
172                                           ssl->ctx->propq);
173     } else if (type == SSL_FILETYPE_ASN1) {
174         j = ERR_R_ASN1_LIB;
175         pkey = d2i_PrivateKey_ex_bio(in, NULL, ssl->ctx->libctx,
176                                      ssl->ctx->propq);
177     } else {
178         ERR_raise(ERR_LIB_SSL, SSL_R_BAD_SSL_FILETYPE);
179         goto end;
180     }
181     if (pkey == NULL) {
182         ERR_raise(ERR_LIB_SSL, j);
183         goto end;
184     }
185     ret = SSL_use_PrivateKey(ssl, pkey);
186     EVP_PKEY_free(pkey);
187  end:
188     BIO_free(in);
189     return ret;
190 }
191
192 int SSL_use_PrivateKey_ASN1(int type, SSL *ssl, const unsigned char *d,
193                             long len)
194 {
195     int ret;
196     const unsigned char *p;
197     EVP_PKEY *pkey;
198
199     p = d;
200     if ((pkey = d2i_PrivateKey_ex(type, NULL, &p, (long)len, ssl->ctx->libctx,
201                                   ssl->ctx->propq)) == NULL) {
202         ERR_raise(ERR_LIB_SSL, ERR_R_ASN1_LIB);
203         return 0;
204     }
205
206     ret = SSL_use_PrivateKey(ssl, pkey);
207     EVP_PKEY_free(pkey);
208     return ret;
209 }
210
211 int SSL_CTX_use_certificate(SSL_CTX *ctx, X509 *x)
212 {
213     int rv;
214     if (x == NULL) {
215         ERR_raise(ERR_LIB_SSL, ERR_R_PASSED_NULL_PARAMETER);
216         return 0;
217     }
218
219     rv = ssl_security_cert(NULL, ctx, x, 0, 1);
220     if (rv != 1) {
221         ERR_raise(ERR_LIB_SSL, rv);
222         return 0;
223     }
224     return ssl_set_cert(ctx->cert, x);
225 }
226
227 static int ssl_set_cert(CERT *c, X509 *x)
228 {
229     EVP_PKEY *pkey;
230     size_t i;
231
232     pkey = X509_get0_pubkey(x);
233     if (pkey == NULL) {
234         ERR_raise(ERR_LIB_SSL, SSL_R_X509_LIB);
235         return 0;
236     }
237
238     if (ssl_cert_lookup_by_pkey(pkey, &i) == NULL) {
239         ERR_raise(ERR_LIB_SSL, SSL_R_UNKNOWN_CERTIFICATE_TYPE);
240         return 0;
241     }
242
243     if (i == SSL_PKEY_ECC && !EVP_PKEY_can_sign(pkey)) {
244         ERR_raise(ERR_LIB_SSL, SSL_R_ECC_CERT_NOT_FOR_SIGNING);
245         return 0;
246     }
247
248     if (c->pkeys[i].privatekey != NULL) {
249         /*
250          * The return code from EVP_PKEY_copy_parameters is deliberately
251          * ignored. Some EVP_PKEY types cannot do this.
252          */
253         EVP_PKEY_copy_parameters(pkey, c->pkeys[i].privatekey);
254         ERR_clear_error();
255
256         if (!X509_check_private_key(x, c->pkeys[i].privatekey)) {
257             /*
258              * don't fail for a cert/key mismatch, just free current private
259              * key (when switching to a different cert & key, first this
260              * function should be used, then ssl_set_pkey
261              */
262             EVP_PKEY_free(c->pkeys[i].privatekey);
263             c->pkeys[i].privatekey = NULL;
264             /* clear error queue */
265             ERR_clear_error();
266         }
267     }
268
269     X509_free(c->pkeys[i].x509);
270     X509_up_ref(x);
271     c->pkeys[i].x509 = x;
272     c->key = &(c->pkeys[i]);
273
274     return 1;
275 }
276
277 int SSL_CTX_use_certificate_file(SSL_CTX *ctx, const char *file, int type)
278 {
279     int j = SSL_R_BAD_VALUE;
280     BIO *in;
281     int ret = 0;
282     X509 *x = NULL, *cert = NULL;
283
284     in = BIO_new(BIO_s_file());
285     if (in == NULL) {
286         ERR_raise(ERR_LIB_SSL, ERR_R_BUF_LIB);
287         goto end;
288     }
289
290     if (BIO_read_filename(in, file) <= 0) {
291         ERR_raise(ERR_LIB_SSL, ERR_R_SYS_LIB);
292         goto end;
293     }
294     if (type != SSL_FILETYPE_ASN1 && type != SSL_FILETYPE_PEM) {
295         ERR_raise(ERR_LIB_SSL, SSL_R_BAD_SSL_FILETYPE);
296         goto end;
297     }
298     x = X509_new_ex(ctx->libctx, ctx->propq);
299     if (x == NULL) {
300         ERR_raise(ERR_LIB_SSL, ERR_R_MALLOC_FAILURE);
301         goto end;
302     }
303     if (type == SSL_FILETYPE_ASN1) {
304         j = ERR_R_ASN1_LIB;
305         cert = d2i_X509_bio(in, &x);
306     } else if (type == SSL_FILETYPE_PEM) {
307         j = ERR_R_PEM_LIB;
308         cert = PEM_read_bio_X509(in, &x, ctx->default_passwd_callback,
309                                  ctx->default_passwd_callback_userdata);
310     }
311     if (cert == NULL) {
312         ERR_raise(ERR_LIB_SSL, j);
313         goto end;
314     }
315
316     ret = SSL_CTX_use_certificate(ctx, x);
317  end:
318     X509_free(x);
319     BIO_free(in);
320     return ret;
321 }
322
323 int SSL_CTX_use_certificate_ASN1(SSL_CTX *ctx, int len, const unsigned char *d)
324 {
325     X509 *x;
326     int ret;
327
328     x = X509_new_ex(ctx->libctx, ctx->propq);
329     if (x == NULL) {
330         ERR_raise(ERR_LIB_SSL, ERR_R_MALLOC_FAILURE);
331         return 0;
332     }
333
334     if (d2i_X509(&x, &d, (long)len) == NULL) {
335         X509_free(x);
336         ERR_raise(ERR_LIB_SSL, ERR_R_ASN1_LIB);
337         return 0;
338     }
339
340     ret = SSL_CTX_use_certificate(ctx, x);
341     X509_free(x);
342     return ret;
343 }
344
345 int SSL_CTX_use_PrivateKey(SSL_CTX *ctx, EVP_PKEY *pkey)
346 {
347     if (pkey == NULL) {
348         ERR_raise(ERR_LIB_SSL, ERR_R_PASSED_NULL_PARAMETER);
349         return 0;
350     }
351     return ssl_set_pkey(ctx->cert, pkey);
352 }
353
354 int SSL_CTX_use_PrivateKey_file(SSL_CTX *ctx, const char *file, int type)
355 {
356     int j, ret = 0;
357     BIO *in;
358     EVP_PKEY *pkey = NULL;
359
360     in = BIO_new(BIO_s_file());
361     if (in == NULL) {
362         ERR_raise(ERR_LIB_SSL, ERR_R_BUF_LIB);
363         goto end;
364     }
365
366     if (BIO_read_filename(in, file) <= 0) {
367         ERR_raise(ERR_LIB_SSL, ERR_R_SYS_LIB);
368         goto end;
369     }
370     if (type == SSL_FILETYPE_PEM) {
371         j = ERR_R_PEM_LIB;
372         pkey = PEM_read_bio_PrivateKey_ex(in, NULL,
373                                        ctx->default_passwd_callback,
374                                        ctx->default_passwd_callback_userdata,
375                                        ctx->libctx, ctx->propq);
376     } else if (type == SSL_FILETYPE_ASN1) {
377         j = ERR_R_ASN1_LIB;
378         pkey = d2i_PrivateKey_ex_bio(in, NULL, ctx->libctx, ctx->propq);
379     } else {
380         ERR_raise(ERR_LIB_SSL, SSL_R_BAD_SSL_FILETYPE);
381         goto end;
382     }
383     if (pkey == NULL) {
384         ERR_raise(ERR_LIB_SSL, j);
385         goto end;
386     }
387     ret = SSL_CTX_use_PrivateKey(ctx, pkey);
388     EVP_PKEY_free(pkey);
389  end:
390     BIO_free(in);
391     return ret;
392 }
393
394 int SSL_CTX_use_PrivateKey_ASN1(int type, SSL_CTX *ctx,
395                                 const unsigned char *d, long len)
396 {
397     int ret;
398     const unsigned char *p;
399     EVP_PKEY *pkey;
400
401     p = d;
402     if ((pkey = d2i_PrivateKey_ex(type, NULL, &p, (long)len, ctx->libctx,
403                                   ctx->propq)) == NULL) {
404         ERR_raise(ERR_LIB_SSL, ERR_R_ASN1_LIB);
405         return 0;
406     }
407
408     ret = SSL_CTX_use_PrivateKey(ctx, pkey);
409     EVP_PKEY_free(pkey);
410     return ret;
411 }
412
413 /*
414  * Read a file that contains our certificate in "PEM" format, possibly
415  * followed by a sequence of CA certificates that should be sent to the peer
416  * in the Certificate message.
417  */
418 static int use_certificate_chain_file(SSL_CTX *ctx, SSL *ssl, const char *file)
419 {
420     BIO *in;
421     int ret = 0;
422     X509 *x = NULL;
423     pem_password_cb *passwd_callback;
424     void *passwd_callback_userdata;
425     SSL_CTX *real_ctx = (ssl == NULL) ? ctx : ssl->ctx;
426
427     if (ctx == NULL && ssl == NULL)
428         return 0;
429
430     ERR_clear_error();          /* clear error stack for
431                                  * SSL_CTX_use_certificate() */
432
433     if (ctx != NULL) {
434         passwd_callback = ctx->default_passwd_callback;
435         passwd_callback_userdata = ctx->default_passwd_callback_userdata;
436     } else {
437         passwd_callback = ssl->default_passwd_callback;
438         passwd_callback_userdata = ssl->default_passwd_callback_userdata;
439     }
440
441     in = BIO_new(BIO_s_file());
442     if (in == NULL) {
443         ERR_raise(ERR_LIB_SSL, ERR_R_BUF_LIB);
444         goto end;
445     }
446
447     if (BIO_read_filename(in, file) <= 0) {
448         ERR_raise(ERR_LIB_SSL, ERR_R_SYS_LIB);
449         goto end;
450     }
451
452     x = X509_new_ex(real_ctx->libctx, real_ctx->propq);
453     if (x == NULL) {
454         ERR_raise(ERR_LIB_SSL, ERR_R_MALLOC_FAILURE);
455         goto end;
456     }
457     if (PEM_read_bio_X509_AUX(in, &x, passwd_callback,
458                               passwd_callback_userdata) == NULL) {
459         ERR_raise(ERR_LIB_SSL, ERR_R_PEM_LIB);
460         goto end;
461     }
462
463     if (ctx)
464         ret = SSL_CTX_use_certificate(ctx, x);
465     else
466         ret = SSL_use_certificate(ssl, x);
467
468     if (ERR_peek_error() != 0)
469         ret = 0;                /* Key/certificate mismatch doesn't imply
470                                  * ret==0 ... */
471     if (ret) {
472         /*
473          * If we could set up our certificate, now proceed to the CA
474          * certificates.
475          */
476         X509 *ca;
477         int r;
478         unsigned long err;
479
480         if (ctx)
481             r = SSL_CTX_clear_chain_certs(ctx);
482         else
483             r = SSL_clear_chain_certs(ssl);
484
485         if (r == 0) {
486             ret = 0;
487             goto end;
488         }
489
490         while (1) {
491             ca = X509_new_ex(real_ctx->libctx, real_ctx->propq);
492             if (ca == NULL) {
493                 ERR_raise(ERR_LIB_SSL, ERR_R_MALLOC_FAILURE);
494                 goto end;
495             }
496             if (PEM_read_bio_X509(in, &ca, passwd_callback,
497                                   passwd_callback_userdata) != NULL) {
498                 if (ctx)
499                     r = SSL_CTX_add0_chain_cert(ctx, ca);
500                 else
501                     r = SSL_add0_chain_cert(ssl, ca);
502                 /*
503                  * Note that we must not free ca if it was successfully added to
504                  * the chain (while we must free the main certificate, since its
505                  * reference count is increased by SSL_CTX_use_certificate).
506                  */
507                 if (!r) {
508                     X509_free(ca);
509                     ret = 0;
510                     goto end;
511                 }
512             } else {
513                 X509_free(ca);
514                 break;
515             }
516         }
517         /* When the while loop ends, it's usually just EOF. */
518         err = ERR_peek_last_error();
519         if (ERR_GET_LIB(err) == ERR_LIB_PEM
520             && ERR_GET_REASON(err) == PEM_R_NO_START_LINE)
521             ERR_clear_error();
522         else
523             ret = 0;            /* some real error */
524     }
525
526  end:
527     X509_free(x);
528     BIO_free(in);
529     return ret;
530 }
531
532 int SSL_CTX_use_certificate_chain_file(SSL_CTX *ctx, const char *file)
533 {
534     return use_certificate_chain_file(ctx, NULL, file);
535 }
536
537 int SSL_use_certificate_chain_file(SSL *ssl, const char *file)
538 {
539     return use_certificate_chain_file(NULL, ssl, file);
540 }
541
542 static int serverinfo_find_extension(const unsigned char *serverinfo,
543                                      size_t serverinfo_length,
544                                      unsigned int extension_type,
545                                      const unsigned char **extension_data,
546                                      size_t *extension_length)
547 {
548     PACKET pkt, data;
549
550     *extension_data = NULL;
551     *extension_length = 0;
552     if (serverinfo == NULL || serverinfo_length == 0)
553         return -1;
554
555     if (!PACKET_buf_init(&pkt, serverinfo, serverinfo_length))
556         return -1;
557
558     for (;;) {
559         unsigned int type = 0;
560         unsigned long context = 0;
561
562         /* end of serverinfo */
563         if (PACKET_remaining(&pkt) == 0)
564             return 0;           /* Extension not found */
565
566         if (!PACKET_get_net_4(&pkt, &context)
567                 || !PACKET_get_net_2(&pkt, &type)
568                 || !PACKET_get_length_prefixed_2(&pkt, &data))
569             return -1;
570
571         if (type == extension_type) {
572             *extension_data = PACKET_data(&data);
573             *extension_length = PACKET_remaining(&data);;
574             return 1;           /* Success */
575         }
576     }
577     /* Unreachable */
578 }
579
580 static int serverinfoex_srv_parse_cb(SSL *s, unsigned int ext_type,
581                                      unsigned int context,
582                                      const unsigned char *in,
583                                      size_t inlen, X509 *x, size_t chainidx,
584                                      int *al, void *arg)
585 {
586
587     if (inlen != 0) {
588         *al = SSL_AD_DECODE_ERROR;
589         return 0;
590     }
591
592     return 1;
593 }
594
595 static int serverinfo_srv_parse_cb(SSL *s, unsigned int ext_type,
596                                    const unsigned char *in,
597                                    size_t inlen, int *al, void *arg)
598 {
599     return serverinfoex_srv_parse_cb(s, ext_type, 0, in, inlen, NULL, 0, al,
600                                      arg);
601 }
602
603 static int serverinfoex_srv_add_cb(SSL *s, unsigned int ext_type,
604                                    unsigned int context,
605                                    const unsigned char **out,
606                                    size_t *outlen, X509 *x, size_t chainidx,
607                                    int *al, void *arg)
608 {
609     const unsigned char *serverinfo = NULL;
610     size_t serverinfo_length = 0;
611
612     /* We only support extensions for the first Certificate */
613     if ((context & SSL_EXT_TLS1_3_CERTIFICATE) != 0 && chainidx > 0)
614         return 0;
615
616     /* Is there serverinfo data for the chosen server cert? */
617     if ((ssl_get_server_cert_serverinfo(s, &serverinfo,
618                                         &serverinfo_length)) != 0) {
619         /* Find the relevant extension from the serverinfo */
620         int retval = serverinfo_find_extension(serverinfo, serverinfo_length,
621                                                ext_type, out, outlen);
622         if (retval == -1) {
623             *al = SSL_AD_INTERNAL_ERROR;
624             return -1;          /* Error */
625         }
626         if (retval == 0)
627             return 0;           /* No extension found, don't send extension */
628         return 1;               /* Send extension */
629     }
630     return 0;                   /* No serverinfo data found, don't send
631                                  * extension */
632 }
633
634 static int serverinfo_srv_add_cb(SSL *s, unsigned int ext_type,
635                                  const unsigned char **out, size_t *outlen,
636                                  int *al, void *arg)
637 {
638     return serverinfoex_srv_add_cb(s, ext_type, 0, out, outlen, NULL, 0, al,
639                                    arg);
640 }
641
642 /*
643  * With a NULL context, this function just checks that the serverinfo data
644  * parses correctly.  With a non-NULL context, it registers callbacks for
645  * the included extensions.
646  */
647 static int serverinfo_process_buffer(unsigned int version,
648                                      const unsigned char *serverinfo,
649                                      size_t serverinfo_length, SSL_CTX *ctx)
650 {
651     PACKET pkt;
652
653     if (serverinfo == NULL || serverinfo_length == 0)
654         return 0;
655
656     if (version != SSL_SERVERINFOV1 && version != SSL_SERVERINFOV2)
657         return 0;
658
659     if (!PACKET_buf_init(&pkt, serverinfo, serverinfo_length))
660         return 0;
661
662     while (PACKET_remaining(&pkt)) {
663         unsigned long context = 0;
664         unsigned int ext_type = 0;
665         PACKET data;
666
667         if ((version == SSL_SERVERINFOV2 && !PACKET_get_net_4(&pkt, &context))
668                 || !PACKET_get_net_2(&pkt, &ext_type)
669                 || !PACKET_get_length_prefixed_2(&pkt, &data))
670             return 0;
671
672         if (ctx == NULL)
673             continue;
674
675         /*
676          * The old style custom extensions API could be set separately for
677          * server/client, i.e. you could set one custom extension for a client,
678          * and *for the same extension in the same SSL_CTX* you could set a
679          * custom extension for the server as well. It seems quite weird to be
680          * setting a custom extension for both client and server in a single
681          * SSL_CTX - but theoretically possible. This isn't possible in the
682          * new API. Therefore, if we have V1 serverinfo we use the old API. We
683          * also use the old API even if we have V2 serverinfo but the context
684          * looks like an old style <= TLSv1.2 extension.
685          */
686         if (version == SSL_SERVERINFOV1 || context == SYNTHV1CONTEXT) {
687             if (!SSL_CTX_add_server_custom_ext(ctx, ext_type,
688                                                serverinfo_srv_add_cb,
689                                                NULL, NULL,
690                                                serverinfo_srv_parse_cb,
691                                                NULL))
692                 return 0;
693         } else {
694             if (!SSL_CTX_add_custom_ext(ctx, ext_type, context,
695                                         serverinfoex_srv_add_cb,
696                                         NULL, NULL,
697                                         serverinfoex_srv_parse_cb,
698                                         NULL))
699                 return 0;
700         }
701     }
702
703     return 1;
704 }
705
706 int SSL_CTX_use_serverinfo_ex(SSL_CTX *ctx, unsigned int version,
707                               const unsigned char *serverinfo,
708                               size_t serverinfo_length)
709 {
710     unsigned char *new_serverinfo;
711
712     if (ctx == NULL || serverinfo == NULL || serverinfo_length == 0) {
713         ERR_raise(ERR_LIB_SSL, ERR_R_PASSED_NULL_PARAMETER);
714         return 0;
715     }
716     if (!serverinfo_process_buffer(version, serverinfo, serverinfo_length,
717                                    NULL)) {
718         ERR_raise(ERR_LIB_SSL, SSL_R_INVALID_SERVERINFO_DATA);
719         return 0;
720     }
721     if (ctx->cert->key == NULL) {
722         ERR_raise(ERR_LIB_SSL, ERR_R_INTERNAL_ERROR);
723         return 0;
724     }
725     new_serverinfo = OPENSSL_realloc(ctx->cert->key->serverinfo,
726                                      serverinfo_length);
727     if (new_serverinfo == NULL) {
728         ERR_raise(ERR_LIB_SSL, ERR_R_MALLOC_FAILURE);
729         return 0;
730     }
731     ctx->cert->key->serverinfo = new_serverinfo;
732     memcpy(ctx->cert->key->serverinfo, serverinfo, serverinfo_length);
733     ctx->cert->key->serverinfo_length = serverinfo_length;
734
735     /*
736      * Now that the serverinfo is validated and stored, go ahead and
737      * register callbacks.
738      */
739     if (!serverinfo_process_buffer(version, serverinfo, serverinfo_length,
740                                    ctx)) {
741         ERR_raise(ERR_LIB_SSL, SSL_R_INVALID_SERVERINFO_DATA);
742         return 0;
743     }
744     return 1;
745 }
746
747 int SSL_CTX_use_serverinfo(SSL_CTX *ctx, const unsigned char *serverinfo,
748                            size_t serverinfo_length)
749 {
750     return SSL_CTX_use_serverinfo_ex(ctx, SSL_SERVERINFOV1, serverinfo,
751                                      serverinfo_length);
752 }
753
754 int SSL_CTX_use_serverinfo_file(SSL_CTX *ctx, const char *file)
755 {
756     unsigned char *serverinfo = NULL;
757     unsigned char *tmp;
758     size_t serverinfo_length = 0;
759     unsigned char *extension = 0;
760     long extension_length = 0;
761     char *name = NULL;
762     char *header = NULL;
763     static const char namePrefix1[] = "SERVERINFO FOR ";
764     static const char namePrefix2[] = "SERVERINFOV2 FOR ";
765     unsigned int name_len;
766     int ret = 0;
767     BIO *bin = NULL;
768     size_t num_extensions = 0, contextoff = 0;
769
770     if (ctx == NULL || file == NULL) {
771         ERR_raise(ERR_LIB_SSL, ERR_R_PASSED_NULL_PARAMETER);
772         goto end;
773     }
774
775     bin = BIO_new(BIO_s_file());
776     if (bin == NULL) {
777         ERR_raise(ERR_LIB_SSL, ERR_R_BUF_LIB);
778         goto end;
779     }
780     if (BIO_read_filename(bin, file) <= 0) {
781         ERR_raise(ERR_LIB_SSL, ERR_R_SYS_LIB);
782         goto end;
783     }
784
785     for (num_extensions = 0;; num_extensions++) {
786         unsigned int version;
787
788         if (PEM_read_bio(bin, &name, &header, &extension, &extension_length)
789             == 0) {
790             /*
791              * There must be at least one extension in this file
792              */
793             if (num_extensions == 0) {
794                 ERR_raise(ERR_LIB_SSL, SSL_R_NO_PEM_EXTENSIONS);
795                 goto end;
796             } else              /* End of file, we're done */
797                 break;
798         }
799         /* Check that PEM name starts with "BEGIN SERVERINFO FOR " */
800         name_len = strlen(name);
801         if (name_len < sizeof(namePrefix1) - 1) {
802             ERR_raise(ERR_LIB_SSL, SSL_R_PEM_NAME_TOO_SHORT);
803             goto end;
804         }
805         if (strncmp(name, namePrefix1, sizeof(namePrefix1) - 1) == 0) {
806             version = SSL_SERVERINFOV1;
807         } else {
808             if (name_len < sizeof(namePrefix2) - 1) {
809                 ERR_raise(ERR_LIB_SSL, SSL_R_PEM_NAME_TOO_SHORT);
810                 goto end;
811             }
812             if (strncmp(name, namePrefix2, sizeof(namePrefix2) - 1) != 0) {
813                 ERR_raise(ERR_LIB_SSL, SSL_R_PEM_NAME_BAD_PREFIX);
814                 goto end;
815             }
816             version = SSL_SERVERINFOV2;
817         }
818         /*
819          * Check that the decoded PEM data is plausible (valid length field)
820          */
821         if (version == SSL_SERVERINFOV1) {
822             /* 4 byte header: 2 bytes type, 2 bytes len */
823             if (extension_length < 4
824                     || (extension[2] << 8) + extension[3]
825                        != extension_length - 4) {
826                 ERR_raise(ERR_LIB_SSL, SSL_R_BAD_DATA);
827                 goto end;
828             }
829             /*
830              * File does not have a context value so we must take account of
831              * this later.
832              */
833             contextoff = 4;
834         } else {
835             /* 8 byte header: 4 bytes context, 2 bytes type, 2 bytes len */
836             if (extension_length < 8
837                     || (extension[6] << 8) + extension[7]
838                        != extension_length - 8) {
839                 ERR_raise(ERR_LIB_SSL, SSL_R_BAD_DATA);
840                 goto end;
841             }
842         }
843         /* Append the decoded extension to the serverinfo buffer */
844         tmp = OPENSSL_realloc(serverinfo, serverinfo_length + extension_length
845                                           + contextoff);
846         if (tmp == NULL) {
847             ERR_raise(ERR_LIB_SSL, ERR_R_MALLOC_FAILURE);
848             goto end;
849         }
850         serverinfo = tmp;
851         if (contextoff > 0) {
852             unsigned char *sinfo = serverinfo + serverinfo_length;
853
854             /* We know this only uses the last 2 bytes */
855             sinfo[0] = 0;
856             sinfo[1] = 0;
857             sinfo[2] = (SYNTHV1CONTEXT >> 8) & 0xff;
858             sinfo[3] = SYNTHV1CONTEXT & 0xff;
859         }
860         memcpy(serverinfo + serverinfo_length + contextoff,
861                extension, extension_length);
862         serverinfo_length += extension_length + contextoff;
863
864         OPENSSL_free(name);
865         name = NULL;
866         OPENSSL_free(header);
867         header = NULL;
868         OPENSSL_free(extension);
869         extension = NULL;
870     }
871
872     ret = SSL_CTX_use_serverinfo_ex(ctx, SSL_SERVERINFOV2, serverinfo,
873                                     serverinfo_length);
874  end:
875     /* SSL_CTX_use_serverinfo makes a local copy of the serverinfo. */
876     OPENSSL_free(name);
877     OPENSSL_free(header);
878     OPENSSL_free(extension);
879     OPENSSL_free(serverinfo);
880     BIO_free(bin);
881     return ret;
882 }
883
884 static int ssl_set_cert_and_key(SSL *ssl, SSL_CTX *ctx, X509 *x509, EVP_PKEY *privatekey,
885                                 STACK_OF(X509) *chain, int override)
886 {
887     int ret = 0;
888     size_t i;
889     int j;
890     int rv;
891     CERT *c = ssl != NULL ? ssl->cert : ctx->cert;
892     STACK_OF(X509) *dup_chain = NULL;
893     EVP_PKEY *pubkey = NULL;
894
895     /* Do all security checks before anything else */
896     rv = ssl_security_cert(ssl, ctx, x509, 0, 1);
897     if (rv != 1) {
898         ERR_raise(ERR_LIB_SSL, rv);
899         goto out;
900     }
901     for (j = 0; j < sk_X509_num(chain); j++) {
902         rv = ssl_security_cert(ssl, ctx, sk_X509_value(chain, j), 0, 0);
903         if (rv != 1) {
904             ERR_raise(ERR_LIB_SSL, rv);
905             goto out;
906         }
907     }
908
909     pubkey = X509_get_pubkey(x509); /* bumps reference */
910     if (pubkey == NULL)
911         goto out;
912     if (privatekey == NULL) {
913         privatekey = pubkey;
914     } else {
915         /* For RSA, which has no parameters, missing returns 0 */
916         if (EVP_PKEY_missing_parameters(privatekey)) {
917             if (EVP_PKEY_missing_parameters(pubkey)) {
918                 /* nobody has parameters? - error */
919                 ERR_raise(ERR_LIB_SSL, SSL_R_MISSING_PARAMETERS);
920                 goto out;
921             } else {
922                 /* copy to privatekey from pubkey */
923                 EVP_PKEY_copy_parameters(privatekey, pubkey);
924             }
925         } else if (EVP_PKEY_missing_parameters(pubkey)) {
926             /* copy to pubkey from privatekey */
927             EVP_PKEY_copy_parameters(pubkey, privatekey);
928         } /* else both have parameters */
929
930         /* check that key <-> cert match */
931         if (EVP_PKEY_eq(pubkey, privatekey) != 1) {
932             ERR_raise(ERR_LIB_SSL, SSL_R_PRIVATE_KEY_MISMATCH);
933             goto out;
934         }
935     }
936     if (ssl_cert_lookup_by_pkey(pubkey, &i) == NULL) {
937         ERR_raise(ERR_LIB_SSL, SSL_R_UNKNOWN_CERTIFICATE_TYPE);
938         goto out;
939     }
940
941     if (!override && (c->pkeys[i].x509 != NULL
942                       || c->pkeys[i].privatekey != NULL
943                       || c->pkeys[i].chain != NULL)) {
944         /* No override, and something already there */
945         ERR_raise(ERR_LIB_SSL, SSL_R_NOT_REPLACING_CERTIFICATE);
946         goto out;
947     }
948
949     if (chain != NULL) {
950         dup_chain = X509_chain_up_ref(chain);
951         if  (dup_chain == NULL) {
952             ERR_raise(ERR_LIB_SSL, ERR_R_MALLOC_FAILURE);
953             goto out;
954         }
955     }
956
957     sk_X509_pop_free(c->pkeys[i].chain, X509_free);
958     c->pkeys[i].chain = dup_chain;
959
960     X509_free(c->pkeys[i].x509);
961     X509_up_ref(x509);
962     c->pkeys[i].x509 = x509;
963
964     EVP_PKEY_free(c->pkeys[i].privatekey);
965     EVP_PKEY_up_ref(privatekey);
966     c->pkeys[i].privatekey = privatekey;
967
968     c->key = &(c->pkeys[i]);
969
970     ret = 1;
971  out:
972     EVP_PKEY_free(pubkey);
973     return ret;
974 }
975
976 int SSL_use_cert_and_key(SSL *ssl, X509 *x509, EVP_PKEY *privatekey,
977                          STACK_OF(X509) *chain, int override)
978 {
979     return ssl_set_cert_and_key(ssl, NULL, x509, privatekey, chain, override);
980 }
981
982 int SSL_CTX_use_cert_and_key(SSL_CTX *ctx, X509 *x509, EVP_PKEY *privatekey,
983                              STACK_OF(X509) *chain, int override)
984 {
985     return ssl_set_cert_and_key(NULL, ctx, x509, privatekey, chain, override);
986 }