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