1 /*
2  *  OpenVPN -- An application to securely tunnel IP networks
3  *             over a single TCP/UDP port, with support for SSL/TLS-based
4  *             session authentication and key exchange,
5  *             packet encryption, packet authentication, and
6  *             packet compression.
7  *
8  *  Copyright (C) 2002-2018 OpenVPN Inc <sales@openvpn.net>
9  *  Copyright (C) 2010-2018 Fox Crypto B.V. <openvpn@fox-it.com>
10  *
11  *  This program is free software; you can redistribute it and/or modify
12  *  it under the terms of the GNU General Public License version 2
13  *  as published by the Free Software Foundation.
14  *
15  *  This program is distributed in the hope that it will be useful,
16  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
17  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18  *  GNU General Public License for more details.
19  *
20  *  You should have received a copy of the GNU General Public License along
21  *  with this program; if not, write to the Free Software Foundation, Inc.,
22  *  51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
23  */
24 
25 /**
26  * @file Control Channel OpenSSL Backend
27  */
28 
29 #ifdef HAVE_CONFIG_H
30 #include "config.h"
31 #elif defined(_MSC_VER)
32 #include "config-msvc.h"
33 #endif
34 
35 #include "syshead.h"
36 
37 #if defined(ENABLE_CRYPTO_OPENSSL)
38 
39 #include "errlevel.h"
40 #include "buffer.h"
41 #include "misc.h"
42 #include "manage.h"
43 #include "memdbg.h"
44 #include "ssl_backend.h"
45 #include "ssl_common.h"
46 #include "base64.h"
47 #include "openssl_compat.h"
48 
49 #ifdef ENABLE_CRYPTOAPI
50 #include "cryptoapi.h"
51 #endif
52 
53 #include "ssl_verify_openssl.h"
54 
55 #include <openssl/bn.h>
56 #include <openssl/crypto.h>
57 #include <openssl/dh.h>
58 #include <openssl/dsa.h>
59 #include <openssl/err.h>
60 #include <openssl/pkcs12.h>
61 #include <openssl/rsa.h>
62 #include <openssl/x509.h>
63 #include <openssl/ssl.h>
64 #ifndef OPENSSL_NO_EC
65 #include <openssl/ec.h>
66 #endif
67 
68 /*
69  * Allocate space in SSL objects in which to store a struct tls_session
70  * pointer back to parent.
71  *
72  */
73 
74 int mydata_index; /* GLOBAL */
75 
76 void
tls_init_lib(void)77 tls_init_lib(void)
78 {
79 #if OPENSSL_VERSION_NUMBER < 0x10100000L
80     SSL_library_init();
81 #ifndef ENABLE_SMALL
82     SSL_load_error_strings();
83 #endif
84     OpenSSL_add_all_algorithms();
85 #endif
86     mydata_index = SSL_get_ex_new_index(0, "struct session *", NULL, NULL, NULL);
87     ASSERT(mydata_index >= 0);
88 }
89 
90 void
tls_free_lib(void)91 tls_free_lib(void)
92 {
93 #if OPENSSL_VERSION_NUMBER < 0x10100000L
94     EVP_cleanup();
95 #ifndef ENABLE_SMALL
96     ERR_free_strings();
97 #endif
98 #endif
99 }
100 
101 void
tls_clear_error(void)102 tls_clear_error(void)
103 {
104     ERR_clear_error();
105 }
106 
107 void
tls_ctx_server_new(struct tls_root_ctx * ctx)108 tls_ctx_server_new(struct tls_root_ctx *ctx)
109 {
110     ASSERT(NULL != ctx);
111 
112     ctx->ctx = SSL_CTX_new(SSLv23_server_method());
113 
114     if (ctx->ctx == NULL)
115     {
116         crypto_msg(M_FATAL, "SSL_CTX_new SSLv23_server_method");
117     }
118     if (ERR_peek_error() != 0)
119     {
120         crypto_msg(M_WARN, "Warning: TLS server context initialisation "
121                    "has warnings.");
122     }
123 }
124 
125 void
tls_ctx_client_new(struct tls_root_ctx * ctx)126 tls_ctx_client_new(struct tls_root_ctx *ctx)
127 {
128     ASSERT(NULL != ctx);
129 
130     ctx->ctx = SSL_CTX_new(SSLv23_client_method());
131 
132     if (ctx->ctx == NULL)
133     {
134         crypto_msg(M_FATAL, "SSL_CTX_new SSLv23_client_method");
135     }
136     if (ERR_peek_error() != 0)
137     {
138         crypto_msg(M_WARN, "Warning: TLS client context initialisation "
139                    "has warnings.");
140     }
141 }
142 
143 void
tls_ctx_free(struct tls_root_ctx * ctx)144 tls_ctx_free(struct tls_root_ctx *ctx)
145 {
146     ASSERT(NULL != ctx);
147     SSL_CTX_free(ctx->ctx);
148     ctx->ctx = NULL;
149 }
150 
151 bool
tls_ctx_initialised(struct tls_root_ctx * ctx)152 tls_ctx_initialised(struct tls_root_ctx *ctx)
153 {
154     ASSERT(NULL != ctx);
155     return NULL != ctx->ctx;
156 }
157 
158 bool
key_state_export_keying_material(struct tls_session * session,const char * label,size_t label_size,void * ekm,size_t ekm_size)159 key_state_export_keying_material(struct tls_session *session,
160                                  const char* label, size_t label_size,
161                                  void *ekm, size_t ekm_size)
162 
163 {
164     SSL* ssl = session->key[KS_PRIMARY].ks_ssl.ssl;
165 
166     if (SSL_export_keying_material(ssl, ekm, ekm_size, label,
167                                    label_size, NULL, 0, 0) == 1)
168     {
169         return true;
170     }
171     else
172     {
173         secure_memzero(ekm, ekm_size);
174         return false;
175     }
176 }
177 
178 /*
179  * Print debugging information on SSL/TLS session negotiation.
180  */
181 
182 #ifndef INFO_CALLBACK_SSL_CONST
183 #define INFO_CALLBACK_SSL_CONST const
184 #endif
185 static void
info_callback(INFO_CALLBACK_SSL_CONST SSL * s,int where,int ret)186 info_callback(INFO_CALLBACK_SSL_CONST SSL *s, int where, int ret)
187 {
188     if (where & SSL_CB_LOOP)
189     {
190         dmsg(D_HANDSHAKE_VERBOSE, "SSL state (%s): %s",
191              where & SSL_ST_CONNECT ? "connect" :
192              where &SSL_ST_ACCEPT ? "accept" :
193              "undefined", SSL_state_string_long(s));
194     }
195     else if (where & SSL_CB_ALERT)
196     {
197         dmsg(D_HANDSHAKE_VERBOSE, "SSL alert (%s): %s: %s",
198              where & SSL_CB_READ ? "read" : "write",
199              SSL_alert_type_string_long(ret),
200              SSL_alert_desc_string_long(ret));
201     }
202 }
203 
204 /*
205  * Return maximum TLS version supported by local OpenSSL library.
206  * Assume that presence of SSL_OP_NO_TLSvX macro indicates that
207  * TLSvX is supported.
208  */
209 int
tls_version_max(void)210 tls_version_max(void)
211 {
212 #if defined(TLS1_3_VERSION)
213     /* If this is defined we can safely assume TLS 1.3 support */
214     return TLS_VER_1_3;
215 #elif OPENSSL_VERSION_NUMBER >= 0x10100000L
216     /*
217      * If TLS_VER_1_3 is not defined, we were compiled against a version that
218      * did not support TLS 1.3.
219      *
220      * However, the library we are *linked* against might be OpenSSL 1.1.1
221      * and therefore supports TLS 1.3. This needs to be checked at runtime
222      * since we can be compiled against 1.1.0 and then the library can be
223      * upgraded to 1.1.1.
224      * We only need to check this for OpenSSL versions that can be
225      * upgraded to 1.1.1 without recompile (>= 1.1.0)
226      */
227     if (OpenSSL_version_num() >= 0x1010100fL)
228     {
229         return TLS_VER_1_3;
230     }
231     else
232     {
233         return TLS_VER_1_2;
234     }
235 #elif defined(TLS1_2_VERSION) || defined(SSL_OP_NO_TLSv1_2)
236     return TLS_VER_1_2;
237 #elif defined(TLS1_1_VERSION) || defined(SSL_OP_NO_TLSv1_1)
238     return TLS_VER_1_1;
239 #else  /* if defined(TLS1_3_VERSION) */
240     return TLS_VER_1_0;
241 #endif
242 }
243 
244 /** Convert internal version number to openssl version number */
245 static int
openssl_tls_version(int ver)246 openssl_tls_version(int ver)
247 {
248     if (ver == TLS_VER_1_0)
249     {
250         return TLS1_VERSION;
251     }
252     else if (ver == TLS_VER_1_1)
253     {
254         return TLS1_1_VERSION;
255     }
256     else if (ver == TLS_VER_1_2)
257     {
258         return TLS1_2_VERSION;
259     }
260     else if (ver == TLS_VER_1_3)
261     {
262         /*
263          * Supporting the library upgraded to TLS1.3 without recompile
264          * is enough to support here with a simple constant that the same
265          * as in the TLS 1.3, so spec it is very unlikely that OpenSSL
266          * will change this constant
267          */
268 #ifndef TLS1_3_VERSION
269         /*
270          * We do not want to define TLS_VER_1_3 if not defined
271          * since other parts of the code use the existance of this macro
272          * as proxy for TLS 1.3 support
273          */
274         return 0x0304;
275 #else
276         return TLS1_3_VERSION;
277 #endif
278     }
279     return 0;
280 }
281 
282 static bool
tls_ctx_set_tls_versions(struct tls_root_ctx * ctx,unsigned int ssl_flags)283 tls_ctx_set_tls_versions(struct tls_root_ctx *ctx, unsigned int ssl_flags)
284 {
285     int tls_ver_min = openssl_tls_version(
286         (ssl_flags >> SSLF_TLS_VERSION_MIN_SHIFT) & SSLF_TLS_VERSION_MIN_MASK);
287     int tls_ver_max = openssl_tls_version(
288         (ssl_flags >> SSLF_TLS_VERSION_MAX_SHIFT) & SSLF_TLS_VERSION_MAX_MASK);
289 
290     if (!tls_ver_min)
291     {
292         /* Enforce at least TLS 1.0 */
293         int cur_min = SSL_CTX_get_min_proto_version(ctx->ctx);
294         tls_ver_min = cur_min < TLS1_VERSION ? TLS1_VERSION : cur_min;
295     }
296 
297     if (!SSL_CTX_set_min_proto_version(ctx->ctx, tls_ver_min))
298     {
299         msg(D_TLS_ERRORS, "%s: failed to set minimum TLS version", __func__);
300         return false;
301     }
302 
303     if (tls_ver_max && !SSL_CTX_set_max_proto_version(ctx->ctx, tls_ver_max))
304     {
305         msg(D_TLS_ERRORS, "%s: failed to set maximum TLS version", __func__);
306         return false;
307     }
308 
309     return true;
310 }
311 
312 bool
tls_ctx_set_options(struct tls_root_ctx * ctx,unsigned int ssl_flags)313 tls_ctx_set_options(struct tls_root_ctx *ctx, unsigned int ssl_flags)
314 {
315     ASSERT(NULL != ctx);
316 
317     /* process SSL options */
318     long sslopt = SSL_OP_SINGLE_DH_USE | SSL_OP_NO_TICKET;
319 #ifdef SSL_OP_CIPHER_SERVER_PREFERENCE
320     sslopt |= SSL_OP_CIPHER_SERVER_PREFERENCE;
321 #endif
322     sslopt |= SSL_OP_NO_COMPRESSION;
323     /* Disable TLS renegotiations. OpenVPN's renegotiation creates new SSL
324      * session and does not depend on this feature. And TLS renegotiations have
325      * been problematic in the past */
326 #ifdef SSL_OP_NO_RENEGOTIATION
327     sslopt |= SSL_OP_NO_RENEGOTIATION;
328 #endif
329 
330     SSL_CTX_set_options(ctx->ctx, sslopt);
331 
332     if (!tls_ctx_set_tls_versions(ctx, ssl_flags))
333     {
334         return false;
335     }
336 
337 #ifdef SSL_MODE_RELEASE_BUFFERS
338     SSL_CTX_set_mode(ctx->ctx, SSL_MODE_RELEASE_BUFFERS);
339 #endif
340     SSL_CTX_set_session_cache_mode(ctx->ctx, SSL_SESS_CACHE_OFF);
341     SSL_CTX_set_default_passwd_cb(ctx->ctx, pem_password_callback);
342 
343     /* Require peer certificate verification */
344     int verify_flags = SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
345     if (ssl_flags & SSLF_CLIENT_CERT_NOT_REQUIRED)
346     {
347         verify_flags = 0;
348     }
349     else if (ssl_flags & SSLF_CLIENT_CERT_OPTIONAL)
350     {
351         verify_flags = SSL_VERIFY_PEER;
352     }
353     SSL_CTX_set_verify(ctx->ctx, verify_flags, verify_callback);
354 
355     SSL_CTX_set_info_callback(ctx->ctx, info_callback);
356 
357     return true;
358 }
359 
360 void
convert_tls_list_to_openssl(char * openssl_ciphers,size_t len,const char * ciphers)361 convert_tls_list_to_openssl(char *openssl_ciphers, size_t len,const char *ciphers)
362 {
363     /* Parse supplied cipher list and pass on to OpenSSL */
364     size_t begin_of_cipher, end_of_cipher;
365 
366     const char *current_cipher;
367     size_t current_cipher_len;
368 
369     const tls_cipher_name_pair *cipher_pair;
370 
371     size_t openssl_ciphers_len = 0;
372     openssl_ciphers[0] = '\0';
373 
374     /* Translate IANA cipher suite names to OpenSSL names */
375     begin_of_cipher = end_of_cipher = 0;
376     for (; begin_of_cipher < strlen(ciphers); begin_of_cipher = end_of_cipher)
377     {
378         end_of_cipher += strcspn(&ciphers[begin_of_cipher], ":");
379         cipher_pair = tls_get_cipher_name_pair(&ciphers[begin_of_cipher], end_of_cipher - begin_of_cipher);
380 
381         if (NULL == cipher_pair)
382         {
383             /* No translation found, use original */
384             current_cipher = &ciphers[begin_of_cipher];
385             current_cipher_len = end_of_cipher - begin_of_cipher;
386 
387             /* Issue warning on missing translation */
388             /* %.*s format specifier expects length of type int, so guarantee */
389             /* that length is small enough and cast to int. */
390             msg(D_LOW, "No valid translation found for TLS cipher '%.*s'",
391                 constrain_int(current_cipher_len, 0, 256), current_cipher);
392         }
393         else
394         {
395             /* Use OpenSSL name */
396             current_cipher = cipher_pair->openssl_name;
397             current_cipher_len = strlen(current_cipher);
398 
399             if (end_of_cipher - begin_of_cipher == current_cipher_len
400                 && 0 != memcmp(&ciphers[begin_of_cipher], cipher_pair->iana_name,
401                                end_of_cipher - begin_of_cipher))
402             {
403                 /* Non-IANA name used, show warning */
404                 msg(M_WARN, "Deprecated TLS cipher name '%s', please use IANA name '%s'", cipher_pair->openssl_name, cipher_pair->iana_name);
405             }
406         }
407 
408         /* Make sure new cipher name fits in cipher string */
409         if ((SIZE_MAX - openssl_ciphers_len) < current_cipher_len
410             || (len - 1) < (openssl_ciphers_len + current_cipher_len))
411         {
412             msg(M_FATAL,
413                 "Failed to set restricted TLS cipher list, too long (>%d).",
414                 (int)(len - 1));
415         }
416 
417         /* Concatenate cipher name to OpenSSL cipher string */
418         memcpy(&openssl_ciphers[openssl_ciphers_len], current_cipher, current_cipher_len);
419         openssl_ciphers_len += current_cipher_len;
420         openssl_ciphers[openssl_ciphers_len] = ':';
421         openssl_ciphers_len++;
422 
423         end_of_cipher++;
424     }
425 
426     if (openssl_ciphers_len > 0)
427     {
428         openssl_ciphers[openssl_ciphers_len-1] = '\0';
429     }
430 }
431 
432 void
tls_ctx_restrict_ciphers(struct tls_root_ctx * ctx,const char * ciphers)433 tls_ctx_restrict_ciphers(struct tls_root_ctx *ctx, const char *ciphers)
434 {
435     if (ciphers == NULL)
436     {
437         /* Use sane default TLS cipher list */
438         if (!SSL_CTX_set_cipher_list(ctx->ctx,
439                                      /* Use openssl's default list as a basis */
440                                      "DEFAULT"
441                                      /* Disable export ciphers and openssl's 'low' and 'medium' ciphers */
442                                      ":!EXP:!LOW:!MEDIUM"
443                                      /* Disable static (EC)DH keys (no forward secrecy) */
444                                      ":!kDH:!kECDH"
445                                      /* Disable DSA private keys */
446                                      ":!DSS"
447                                      /* Disable unsupported TLS modes */
448                                      ":!PSK:!SRP:!kRSA"))
449         {
450             crypto_msg(M_FATAL, "Failed to set default TLS cipher list.");
451         }
452         return;
453     }
454 
455     char openssl_ciphers[4096];
456     convert_tls_list_to_openssl(openssl_ciphers, sizeof(openssl_ciphers), ciphers);
457 
458     ASSERT(NULL != ctx);
459 
460     /* Set OpenSSL cipher list */
461     if (!SSL_CTX_set_cipher_list(ctx->ctx, openssl_ciphers))
462     {
463         crypto_msg(M_FATAL, "Failed to set restricted TLS cipher list: %s", openssl_ciphers);
464     }
465 }
466 
467 void
convert_tls13_list_to_openssl(char * openssl_ciphers,size_t len,const char * ciphers)468 convert_tls13_list_to_openssl(char *openssl_ciphers, size_t len,
469                               const char *ciphers)
470 {
471     /*
472      * OpenSSL (and official IANA) cipher names have _ in them. We
473      * historically used names with - in them. Silently convert names
474      * with - to names with _ to support both
475      */
476     if (strlen(ciphers) >= (len - 1))
477     {
478         msg(M_FATAL,
479             "Failed to set restricted TLS 1.3 cipher list, too long (>%d).",
480             (int) (len - 1));
481     }
482 
483     strncpy(openssl_ciphers, ciphers, len);
484 
485     for (size_t i = 0; i < strlen(openssl_ciphers); i++)
486     {
487         if (openssl_ciphers[i] == '-')
488         {
489             openssl_ciphers[i] = '_';
490         }
491     }
492 }
493 
494 void
tls_ctx_restrict_ciphers_tls13(struct tls_root_ctx * ctx,const char * ciphers)495 tls_ctx_restrict_ciphers_tls13(struct tls_root_ctx *ctx, const char *ciphers)
496 {
497     if (ciphers == NULL)
498     {
499         /* default cipher list of OpenSSL 1.1.1 is sane, do not set own
500          * default as we do with tls-cipher */
501         return;
502     }
503 
504 #if !defined(TLS1_3_VERSION)
505     crypto_msg(M_WARN, "Not compiled with OpenSSL 1.1.1 or higher. "
506                "Ignoring TLS 1.3 only tls-ciphersuites '%s' setting.",
507                ciphers);
508 #else
509     ASSERT(NULL != ctx);
510 
511     char openssl_ciphers[4096];
512     convert_tls13_list_to_openssl(openssl_ciphers, sizeof(openssl_ciphers),
513                                   ciphers);
514 
515     if (!SSL_CTX_set_ciphersuites(ctx->ctx, openssl_ciphers))
516     {
517         crypto_msg(M_FATAL, "Failed to set restricted TLS 1.3 cipher list: %s",
518                    openssl_ciphers);
519     }
520 #endif
521 }
522 
523 void
tls_ctx_set_cert_profile(struct tls_root_ctx * ctx,const char * profile)524 tls_ctx_set_cert_profile(struct tls_root_ctx *ctx, const char *profile)
525 {
526 #ifdef HAVE_SSL_CTX_SET_SECURITY_LEVEL
527     /* OpenSSL does not have certificate profiles, but a complex set of
528      * callbacks that we could try to implement to achieve something similar.
529      * For now, use OpenSSL's security levels to achieve similar (but not equal)
530      * behaviour. */
531     if (!profile || 0 == strcmp(profile, "legacy"))
532     {
533         SSL_CTX_set_security_level(ctx->ctx, 1);
534     }
535     else if (0 == strcmp(profile, "preferred"))
536     {
537         SSL_CTX_set_security_level(ctx->ctx, 2);
538     }
539     else if (0 == strcmp(profile, "suiteb"))
540     {
541         SSL_CTX_set_security_level(ctx->ctx, 3);
542         SSL_CTX_set_cipher_list(ctx->ctx, "SUITEB128");
543     }
544     else
545     {
546         msg(M_FATAL, "ERROR: Invalid cert profile: %s", profile);
547     }
548 #else  /* ifdef HAVE_SSL_CTX_SET_SECURITY_LEVEL */
549     if (profile)
550     {
551         msg(M_WARN, "WARNING: OpenSSL 1.0.2 does not support --tls-cert-profile"
552             ", ignoring user-set profile: '%s'", profile);
553     }
554 #endif /* ifdef HAVE_SSL_CTX_SET_SECURITY_LEVEL */
555 }
556 
557 void
tls_ctx_set_tls_groups(struct tls_root_ctx * ctx,const char * groups)558 tls_ctx_set_tls_groups(struct tls_root_ctx *ctx, const char *groups)
559 {
560     ASSERT(ctx);
561     struct gc_arena gc = gc_new();
562     /* This method could be as easy as
563      *  SSL_CTX_set1_groups_list(ctx->ctx, groups)
564      * but OpenSSL does not like the name secp256r1 for prime256v1
565      * This is one of the important curves.
566      * To support the same name for OpenSSL and mbedTLS, we do
567      * this dance.
568      */
569 
570     int groups_count = get_num_elements(groups, ':');
571 
572     int *glist;
573     /* Allocate an array for them */
574     ALLOC_ARRAY_CLEAR_GC(glist, int, groups_count, &gc);
575 
576     /* Parse allowed ciphers, getting IDs */
577     int glistlen = 0;
578     char *tmp_groups = string_alloc(groups, &gc);
579 
580     const char *token;
581     while ((token = strsep(&tmp_groups, ":")))
582     {
583         if (streq(token, "secp256r1"))
584         {
585             token = "prime256v1";
586         }
587         int nid = OBJ_sn2nid(token);
588 
589         if (nid == 0)
590         {
591             msg(M_WARN, "Warning unknown curve/group specified: %s", token);
592         }
593         else
594         {
595             glist[glistlen] = nid;
596             glistlen++;
597         }
598     }
599 
600     if (!SSL_CTX_set1_groups(ctx->ctx, glist, glistlen))
601     {
602         crypto_msg(M_FATAL, "Failed to set allowed TLS group list: %s",
603                    groups);
604     }
605     gc_free(&gc);
606 }
607 
608 void
tls_ctx_check_cert_time(const struct tls_root_ctx * ctx)609 tls_ctx_check_cert_time(const struct tls_root_ctx *ctx)
610 {
611     int ret;
612     const X509 *cert;
613 
614     ASSERT(ctx);
615 
616     cert = SSL_CTX_get0_certificate(ctx->ctx);
617 
618     if (cert == NULL)
619     {
620         return; /* Nothing to check if there is no certificate */
621     }
622 
623     ret = X509_cmp_time(X509_get0_notBefore(cert), NULL);
624     if (ret == 0)
625     {
626         msg(D_TLS_DEBUG_MED, "Failed to read certificate notBefore field.");
627     }
628     if (ret > 0)
629     {
630         msg(M_WARN, "WARNING: Your certificate is not yet valid!");
631     }
632 
633     ret = X509_cmp_time(X509_get0_notAfter(cert), NULL);
634     if (ret == 0)
635     {
636         msg(D_TLS_DEBUG_MED, "Failed to read certificate notAfter field.");
637     }
638     if (ret < 0)
639     {
640         msg(M_WARN, "WARNING: Your certificate has expired!");
641     }
642 }
643 
644 void
tls_ctx_load_dh_params(struct tls_root_ctx * ctx,const char * dh_file,bool dh_file_inline)645 tls_ctx_load_dh_params(struct tls_root_ctx *ctx, const char *dh_file,
646                        bool dh_file_inline)
647 {
648     DH *dh;
649     BIO *bio;
650 
651     ASSERT(NULL != ctx);
652 
653     if (dh_file_inline)
654     {
655         if (!(bio = BIO_new_mem_buf((char *)dh_file, -1)))
656         {
657             crypto_msg(M_FATAL, "Cannot open memory BIO for inline DH parameters");
658         }
659     }
660     else
661     {
662         /* Get Diffie Hellman Parameters */
663         if (!(bio = BIO_new_file(dh_file, "r")))
664         {
665             crypto_msg(M_FATAL, "Cannot open %s for DH parameters", dh_file);
666         }
667     }
668 
669     dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
670     BIO_free(bio);
671 
672     if (!dh)
673     {
674         crypto_msg(M_FATAL, "Cannot load DH parameters from %s",
675                    print_key_filename(dh_file, dh_file_inline));
676     }
677     if (!SSL_CTX_set_tmp_dh(ctx->ctx, dh))
678     {
679         crypto_msg(M_FATAL, "SSL_CTX_set_tmp_dh");
680     }
681 
682     msg(D_TLS_DEBUG_LOW, "Diffie-Hellman initialized with %d bit key",
683         8 * DH_size(dh));
684 
685     DH_free(dh);
686 }
687 
688 void
tls_ctx_load_ecdh_params(struct tls_root_ctx * ctx,const char * curve_name)689 tls_ctx_load_ecdh_params(struct tls_root_ctx *ctx, const char *curve_name
690                          )
691 {
692 #ifndef OPENSSL_NO_EC
693     int nid = NID_undef;
694     EC_KEY *ecdh = NULL;
695     const char *sname = NULL;
696 
697     /* Generate a new ECDH key for each SSL session (for non-ephemeral ECDH) */
698     SSL_CTX_set_options(ctx->ctx, SSL_OP_SINGLE_ECDH_USE);
699 
700     if (curve_name != NULL)
701     {
702         /* Use user supplied curve if given */
703         msg(D_TLS_DEBUG, "Using user specified ECDH curve (%s)", curve_name);
704         nid = OBJ_sn2nid(curve_name);
705     }
706     else
707     {
708 #if OPENSSL_VERSION_NUMBER < 0x10100000L
709 
710         /* OpenSSL 1.0.2 and newer can automatically handle ECDH parameter
711          * loading */
712         SSL_CTX_set_ecdh_auto(ctx->ctx, 1);
713 
714         /* OpenSSL 1.1.0 and newer have always ecdh auto loading enabled,
715          * so do nothing */
716 #endif
717         return;
718     }
719 
720     /* Translate NID back to name , just for kicks */
721     sname = OBJ_nid2sn(nid);
722     if (sname == NULL)
723     {
724         sname = "(Unknown)";
725     }
726 
727     /* Create new EC key and set as ECDH key */
728     if (NID_undef == nid || NULL == (ecdh = EC_KEY_new_by_curve_name(nid)))
729     {
730         /* Creating key failed, fall back on sane default */
731         ecdh = EC_KEY_new_by_curve_name(NID_secp384r1);
732         const char *source = (NULL == curve_name) ?
733                              "extract curve from certificate" : "use supplied curve";
734         msg(D_TLS_DEBUG_LOW,
735             "Failed to %s (%s), using secp384r1 instead.", source, sname);
736         sname = OBJ_nid2sn(NID_secp384r1);
737     }
738 
739     if (!SSL_CTX_set_tmp_ecdh(ctx->ctx, ecdh))
740     {
741         crypto_msg(M_FATAL, "SSL_CTX_set_tmp_ecdh: cannot add curve");
742     }
743 
744     msg(D_TLS_DEBUG_LOW, "ECDH curve %s added", sname);
745 
746     EC_KEY_free(ecdh);
747 #else  /* ifndef OPENSSL_NO_EC */
748     msg(D_LOW, "Your OpenSSL library was built without elliptic curve support."
749         " Skipping ECDH parameter loading.");
750 #endif /* OPENSSL_NO_EC */
751 }
752 
753 int
tls_ctx_load_pkcs12(struct tls_root_ctx * ctx,const char * pkcs12_file,bool pkcs12_file_inline,bool load_ca_file)754 tls_ctx_load_pkcs12(struct tls_root_ctx *ctx, const char *pkcs12_file,
755                     bool pkcs12_file_inline, bool load_ca_file)
756 {
757     FILE *fp;
758     EVP_PKEY *pkey;
759     X509 *cert;
760     STACK_OF(X509) *ca = NULL;
761     PKCS12 *p12;
762     int i;
763     char password[256];
764 
765     ASSERT(NULL != ctx);
766 
767     if (pkcs12_file_inline)
768     {
769         BIO *b64 = BIO_new(BIO_f_base64());
770         BIO *bio = BIO_new_mem_buf((void *) pkcs12_file,
771                                    (int) strlen(pkcs12_file));
772         ASSERT(b64 && bio);
773         BIO_push(b64, bio);
774         p12 = d2i_PKCS12_bio(b64, NULL);
775         if (!p12)
776         {
777             crypto_msg(M_FATAL, "Error reading inline PKCS#12 file");
778         }
779         BIO_free(b64);
780         BIO_free(bio);
781     }
782     else
783     {
784         /* Load the PKCS #12 file */
785         if (!(fp = platform_fopen(pkcs12_file, "rb")))
786         {
787             crypto_msg(M_FATAL, "Error opening file %s", pkcs12_file);
788         }
789         p12 = d2i_PKCS12_fp(fp, NULL);
790         fclose(fp);
791         if (!p12)
792         {
793             crypto_msg(M_FATAL, "Error reading PKCS#12 file %s", pkcs12_file);
794         }
795     }
796 
797     /* Parse the PKCS #12 file */
798     if (!PKCS12_parse(p12, "", &pkey, &cert, &ca))
799     {
800         pem_password_callback(password, sizeof(password) - 1, 0, NULL);
801         /* Reparse the PKCS #12 file with password */
802         ca = NULL;
803         if (!PKCS12_parse(p12, password, &pkey, &cert, &ca))
804         {
805 #ifdef ENABLE_MANAGEMENT
806             if (management && (ERR_GET_REASON(ERR_peek_error()) == PKCS12_R_MAC_VERIFY_FAILURE))
807             {
808                 management_auth_failure(management, UP_TYPE_PRIVATE_KEY, NULL);
809             }
810 #endif
811             PKCS12_free(p12);
812             return 1;
813         }
814     }
815     PKCS12_free(p12);
816 
817     /* Load Certificate */
818     if (!SSL_CTX_use_certificate(ctx->ctx, cert))
819     {
820         crypto_msg(M_FATAL, "Cannot use certificate");
821     }
822 
823     /* Load Private Key */
824     if (!SSL_CTX_use_PrivateKey(ctx->ctx, pkey))
825     {
826         crypto_msg(M_FATAL, "Cannot use private key");
827     }
828 
829     /* Check Private Key */
830     if (!SSL_CTX_check_private_key(ctx->ctx))
831     {
832         crypto_msg(M_FATAL, "Private key does not match the certificate");
833     }
834 
835     /* Set Certificate Verification chain */
836     if (load_ca_file)
837     {
838         /* Add CAs from PKCS12 to the cert store and mark them as trusted.
839          * They're also used to fill in the chain of intermediate certs as
840          * necessary.
841          */
842         if (ca && sk_X509_num(ca))
843         {
844             for (i = 0; i < sk_X509_num(ca); i++)
845             {
846                 X509_STORE *cert_store = SSL_CTX_get_cert_store(ctx->ctx);
847                 if (!X509_STORE_add_cert(cert_store,sk_X509_value(ca, i)))
848                 {
849                     crypto_msg(M_FATAL,"Cannot add certificate to certificate chain (X509_STORE_add_cert)");
850                 }
851                 if (!SSL_CTX_add_client_CA(ctx->ctx, sk_X509_value(ca, i)))
852                 {
853                     crypto_msg(M_FATAL,"Cannot add certificate to client CA list (SSL_CTX_add_client_CA)");
854                 }
855             }
856         }
857     }
858     else
859     {
860         /* If trusted CA certs were loaded from a PEM file, and we ignore the
861          * ones in PKCS12, do load PKCS12-provided certs to the client extra
862          * certs chain just in case they include intermediate CAs needed to
863          * prove my identity to the other end. This does not make them trusted.
864          */
865         if (ca && sk_X509_num(ca))
866         {
867             for (i = 0; i < sk_X509_num(ca); i++)
868             {
869                 if (!SSL_CTX_add_extra_chain_cert(ctx->ctx,sk_X509_value(ca, i)))
870                 {
871                     crypto_msg(M_FATAL, "Cannot add extra certificate to chain (SSL_CTX_add_extra_chain_cert)");
872                 }
873             }
874         }
875     }
876     return 0;
877 }
878 
879 #ifdef ENABLE_CRYPTOAPI
880 void
tls_ctx_load_cryptoapi(struct tls_root_ctx * ctx,const char * cryptoapi_cert)881 tls_ctx_load_cryptoapi(struct tls_root_ctx *ctx, const char *cryptoapi_cert)
882 {
883     ASSERT(NULL != ctx);
884 
885     /* Load Certificate and Private Key */
886     if (!SSL_CTX_use_CryptoAPI_certificate(ctx->ctx, cryptoapi_cert))
887     {
888         crypto_msg(M_FATAL, "Cannot load certificate \"%s\" from Microsoft Certificate Store", cryptoapi_cert);
889     }
890 }
891 #endif /* ENABLE_CRYPTOAPI */
892 
893 static void
tls_ctx_add_extra_certs(struct tls_root_ctx * ctx,BIO * bio,bool optional)894 tls_ctx_add_extra_certs(struct tls_root_ctx *ctx, BIO *bio, bool optional)
895 {
896     X509 *cert;
897     while (true)
898     {
899         cert = NULL;
900         if (!PEM_read_bio_X509(bio, &cert, NULL, NULL))
901         {
902             /*  a PEM_R_NO_START_LINE "Error" indicates that no certificate
903              *  is found in the buffer.  If loading more certificates is
904              *  optional, break without raising an error
905              */
906             if (optional
907                 && ERR_GET_REASON(ERR_peek_error()) == PEM_R_NO_START_LINE)
908             {
909                 /* remove that error from error stack */
910                 (void)ERR_get_error();
911                 break;
912             }
913 
914             /* Otherwise, bail out with error */
915             crypto_msg(M_FATAL, "Error reading extra certificate");
916         }
917         /* takes ownership of cert like a set1 method */
918         if (SSL_CTX_add_extra_chain_cert(ctx->ctx, cert) != 1)
919         {
920             crypto_msg(M_FATAL, "Error adding extra certificate");
921         }
922         /* We loaded at least one certificate, so loading more is optional */
923         optional = true;
924     }
925 }
926 
927 void
tls_ctx_load_cert_file(struct tls_root_ctx * ctx,const char * cert_file,bool cert_file_inline)928 tls_ctx_load_cert_file(struct tls_root_ctx *ctx, const char *cert_file,
929                        bool cert_file_inline)
930 {
931     BIO *in = NULL;
932     X509 *x = NULL;
933     int ret = 0;
934 
935     ASSERT(NULL != ctx);
936 
937     if (cert_file_inline)
938     {
939         in = BIO_new_mem_buf((char *) cert_file, -1);
940     }
941     else
942     {
943         in = BIO_new_file(cert_file, "r");
944     }
945 
946     if (in == NULL)
947     {
948         SSLerr(SSL_F_SSL_CTX_USE_CERTIFICATE_FILE, ERR_R_SYS_LIB);
949         goto end;
950     }
951 
952     x = PEM_read_bio_X509(in, NULL,
953                           SSL_CTX_get_default_passwd_cb(ctx->ctx),
954                           SSL_CTX_get_default_passwd_cb_userdata(ctx->ctx));
955     if (x == NULL)
956     {
957         SSLerr(SSL_F_SSL_CTX_USE_CERTIFICATE_FILE, ERR_R_PEM_LIB);
958         goto end;
959     }
960 
961     ret = SSL_CTX_use_certificate(ctx->ctx, x);
962     if (ret)
963     {
964         tls_ctx_add_extra_certs(ctx, in, true);
965     }
966 
967 end:
968     if (!ret)
969     {
970         if (cert_file_inline)
971         {
972             crypto_msg(M_FATAL, "Cannot load inline certificate file");
973         }
974         else
975         {
976             crypto_msg(M_FATAL, "Cannot load certificate file %s", cert_file);
977         }
978     }
979     else
980     {
981         crypto_print_openssl_errors(M_DEBUG);
982     }
983 
984     BIO_free(in);
985     X509_free(x);
986 }
987 
988 int
tls_ctx_load_priv_file(struct tls_root_ctx * ctx,const char * priv_key_file,bool priv_key_file_inline)989 tls_ctx_load_priv_file(struct tls_root_ctx *ctx, const char *priv_key_file,
990                        bool priv_key_file_inline)
991 {
992     SSL_CTX *ssl_ctx = NULL;
993     BIO *in = NULL;
994     EVP_PKEY *pkey = NULL;
995     int ret = 1;
996 
997     ASSERT(NULL != ctx);
998 
999     ssl_ctx = ctx->ctx;
1000 
1001     if (priv_key_file_inline)
1002     {
1003         in = BIO_new_mem_buf((char *) priv_key_file, -1);
1004     }
1005     else
1006     {
1007         in = BIO_new_file(priv_key_file, "r");
1008     }
1009 
1010     if (!in)
1011     {
1012         goto end;
1013     }
1014 
1015     pkey = PEM_read_bio_PrivateKey(in, NULL,
1016                                    SSL_CTX_get_default_passwd_cb(ctx->ctx),
1017                                    SSL_CTX_get_default_passwd_cb_userdata(ctx->ctx));
1018     if (!pkey)
1019     {
1020         pkey = engine_load_key(priv_key_file, ctx->ctx);
1021     }
1022 
1023     if (!pkey || !SSL_CTX_use_PrivateKey(ssl_ctx, pkey))
1024     {
1025 #ifdef ENABLE_MANAGEMENT
1026         if (management && (ERR_GET_REASON(ERR_peek_error()) == EVP_R_BAD_DECRYPT))
1027         {
1028             management_auth_failure(management, UP_TYPE_PRIVATE_KEY, NULL);
1029         }
1030 #endif
1031         crypto_msg(M_WARN, "Cannot load private key file %s",
1032                    print_key_filename(priv_key_file, priv_key_file_inline));
1033         goto end;
1034     }
1035 
1036     /* Check Private Key */
1037     if (!SSL_CTX_check_private_key(ssl_ctx))
1038     {
1039         crypto_msg(M_FATAL, "Private key does not match the certificate");
1040     }
1041     ret = 0;
1042 
1043 end:
1044     EVP_PKEY_free(pkey);
1045     BIO_free(in);
1046     return ret;
1047 }
1048 
1049 void
backend_tls_ctx_reload_crl(struct tls_root_ctx * ssl_ctx,const char * crl_file,bool crl_inline)1050 backend_tls_ctx_reload_crl(struct tls_root_ctx *ssl_ctx, const char *crl_file,
1051                            bool crl_inline)
1052 {
1053     BIO *in = NULL;
1054 
1055     X509_STORE *store = SSL_CTX_get_cert_store(ssl_ctx->ctx);
1056     if (!store)
1057     {
1058         crypto_msg(M_FATAL, "Cannot get certificate store");
1059     }
1060 
1061     /* Always start with a cleared CRL list, for that we
1062      * we need to manually find the CRL object from the stack
1063      * and remove it */
1064     STACK_OF(X509_OBJECT) *objs = X509_STORE_get0_objects(store);
1065     for (int i = 0; i < sk_X509_OBJECT_num(objs); i++)
1066     {
1067         X509_OBJECT *obj = sk_X509_OBJECT_value(objs, i);
1068         ASSERT(obj);
1069         if (X509_OBJECT_get_type(obj) == X509_LU_CRL)
1070         {
1071             sk_X509_OBJECT_delete(objs, i);
1072             X509_OBJECT_free(obj);
1073         }
1074     }
1075 
1076     X509_STORE_set_flags(store, X509_V_FLAG_CRL_CHECK | X509_V_FLAG_CRL_CHECK_ALL);
1077 
1078     if (crl_inline)
1079     {
1080         in = BIO_new_mem_buf((char *) crl_file, -1);
1081     }
1082     else
1083     {
1084         in = BIO_new_file(crl_file, "r");
1085     }
1086 
1087     if (in == NULL)
1088     {
1089         msg(M_WARN, "CRL: cannot read: %s",
1090             print_key_filename(crl_file, crl_inline));
1091         goto end;
1092     }
1093 
1094     int num_crls_loaded = 0;
1095     while (true)
1096     {
1097         X509_CRL *crl = PEM_read_bio_X509_CRL(in, NULL, NULL, NULL);
1098         if (crl == NULL)
1099         {
1100             /*
1101              * PEM_R_NO_START_LINE can be considered equivalent to EOF.
1102              */
1103             bool eof = ERR_GET_REASON(ERR_peek_error()) == PEM_R_NO_START_LINE;
1104             /* but warn if no CRLs have been loaded */
1105             if (num_crls_loaded > 0 && eof)
1106             {
1107                 /* remove that error from error stack */
1108                 (void)ERR_get_error();
1109                 break;
1110             }
1111 
1112             crypto_msg(M_WARN, "CRL: cannot read CRL from file %s",
1113                        print_key_filename(crl_file, crl_inline));
1114             break;
1115         }
1116 
1117         if (!X509_STORE_add_crl(store, crl))
1118         {
1119             X509_CRL_free(crl);
1120             crypto_msg(M_WARN, "CRL: cannot add %s to store",
1121                        print_key_filename(crl_file, crl_inline));
1122             break;
1123         }
1124         X509_CRL_free(crl);
1125         num_crls_loaded++;
1126     }
1127     msg(M_INFO, "CRL: loaded %d CRLs from file %s", num_crls_loaded, crl_file);
1128 end:
1129     BIO_free(in);
1130 }
1131 
1132 
1133 #ifdef ENABLE_MANAGEMENT
1134 
1135 /* encrypt */
1136 static int
rsa_pub_enc(int flen,const unsigned char * from,unsigned char * to,RSA * rsa,int padding)1137 rsa_pub_enc(int flen, const unsigned char *from, unsigned char *to, RSA *rsa, int padding)
1138 {
1139     ASSERT(0);
1140     return -1;
1141 }
1142 
1143 /* verify arbitrary data */
1144 static int
rsa_pub_dec(int flen,const unsigned char * from,unsigned char * to,RSA * rsa,int padding)1145 rsa_pub_dec(int flen, const unsigned char *from, unsigned char *to, RSA *rsa, int padding)
1146 {
1147     ASSERT(0);
1148     return -1;
1149 }
1150 
1151 /* decrypt */
1152 static int
rsa_priv_dec(int flen,const unsigned char * from,unsigned char * to,RSA * rsa,int padding)1153 rsa_priv_dec(int flen, const unsigned char *from, unsigned char *to, RSA *rsa, int padding)
1154 {
1155     ASSERT(0);
1156     return -1;
1157 }
1158 
1159 /* called at RSA_free */
1160 static int
openvpn_extkey_rsa_finish(RSA * rsa)1161 openvpn_extkey_rsa_finish(RSA *rsa)
1162 {
1163     /* meth was allocated in tls_ctx_use_management_external_key() ; since
1164      * this function is called when the parent RSA object is destroyed,
1165      * it is no longer used after this point so kill it. */
1166     const RSA_METHOD *meth = RSA_get_method(rsa);
1167     RSA_meth_free((RSA_METHOD *)meth);
1168     return 1;
1169 }
1170 
1171 /*
1172  * Convert OpenSSL's constant to the strings used in the management
1173  * interface query
1174  */
1175 const char *
get_rsa_padding_name(const int padding)1176 get_rsa_padding_name(const int padding)
1177 {
1178     switch (padding)
1179     {
1180         case RSA_PKCS1_PADDING:
1181             return "RSA_PKCS1_PADDING";
1182 
1183         case RSA_NO_PADDING:
1184             return "RSA_NO_PADDING";
1185 
1186         default:
1187             return "UNKNOWN";
1188     }
1189 }
1190 
1191 /**
1192  * Pass the input hash in 'dgst' to management and get the signature back.
1193  *
1194  * @param dgst          hash to be signed
1195  * @param dgstlen       len of data in dgst
1196  * @param sig           On successful return signature is in sig.
1197  * @param siglen        length of buffer sig
1198  * @param algorithm     padding/hashing algorithm for the signature
1199  *
1200  * @return              signature length or -1 on error.
1201  */
1202 static int
get_sig_from_man(const unsigned char * dgst,unsigned int dgstlen,unsigned char * sig,unsigned int siglen,const char * algorithm)1203 get_sig_from_man(const unsigned char *dgst, unsigned int dgstlen,
1204                  unsigned char *sig, unsigned int siglen,
1205                  const char *algorithm)
1206 {
1207     char *in_b64 = NULL;
1208     char *out_b64 = NULL;
1209     int len = -1;
1210 
1211     int bencret = openvpn_base64_encode(dgst, dgstlen, &in_b64);
1212 
1213     if (management && bencret > 0)
1214     {
1215         out_b64 = management_query_pk_sig(management, in_b64, algorithm);
1216 
1217     }
1218     if (out_b64)
1219     {
1220         len = openvpn_base64_decode(out_b64, sig, siglen);
1221     }
1222 
1223     free(in_b64);
1224     free(out_b64);
1225     return len;
1226 }
1227 
1228 /* sign arbitrary data */
1229 static int
rsa_priv_enc(int flen,const unsigned char * from,unsigned char * to,RSA * rsa,int padding)1230 rsa_priv_enc(int flen, const unsigned char *from, unsigned char *to, RSA *rsa,
1231              int padding)
1232 {
1233     unsigned int len = RSA_size(rsa);
1234     int ret = -1;
1235 
1236     if (padding != RSA_PKCS1_PADDING && padding != RSA_NO_PADDING)
1237     {
1238         RSAerr(RSA_F_RSA_OSSL_PRIVATE_ENCRYPT, RSA_R_UNKNOWN_PADDING_TYPE);
1239         return -1;
1240     }
1241 
1242     ret = get_sig_from_man(from, flen, to, len, get_rsa_padding_name(padding));
1243 
1244     return (ret == len) ? ret : -1;
1245 }
1246 
1247 static int
tls_ctx_use_external_rsa_key(struct tls_root_ctx * ctx,EVP_PKEY * pkey)1248 tls_ctx_use_external_rsa_key(struct tls_root_ctx *ctx, EVP_PKEY *pkey)
1249 {
1250     RSA *rsa = NULL;
1251     RSA_METHOD *rsa_meth;
1252 
1253     ASSERT(NULL != ctx);
1254 
1255     const RSA *pub_rsa = EVP_PKEY_get0_RSA(pkey);
1256     ASSERT(NULL != pub_rsa);
1257 
1258     /* allocate custom RSA method object */
1259     rsa_meth = RSA_meth_new("OpenVPN external private key RSA Method",
1260                             RSA_METHOD_FLAG_NO_CHECK);
1261     check_malloc_return(rsa_meth);
1262     RSA_meth_set_pub_enc(rsa_meth, rsa_pub_enc);
1263     RSA_meth_set_pub_dec(rsa_meth, rsa_pub_dec);
1264     RSA_meth_set_priv_enc(rsa_meth, rsa_priv_enc);
1265     RSA_meth_set_priv_dec(rsa_meth, rsa_priv_dec);
1266     RSA_meth_set_init(rsa_meth, NULL);
1267     RSA_meth_set_finish(rsa_meth, openvpn_extkey_rsa_finish);
1268     RSA_meth_set0_app_data(rsa_meth, NULL);
1269 
1270     /* allocate RSA object */
1271     rsa = RSA_new();
1272     if (rsa == NULL)
1273     {
1274         SSLerr(SSL_F_SSL_USE_PRIVATEKEY, ERR_R_MALLOC_FAILURE);
1275         goto err;
1276     }
1277 
1278     /* initialize RSA object */
1279     const BIGNUM *n = NULL;
1280     const BIGNUM *e = NULL;
1281     RSA_get0_key(pub_rsa, &n, &e, NULL);
1282     RSA_set0_key(rsa, BN_dup(n), BN_dup(e), NULL);
1283     RSA_set_flags(rsa, RSA_flags(rsa) | RSA_FLAG_EXT_PKEY);
1284     if (!RSA_set_method(rsa, rsa_meth))
1285     {
1286         RSA_meth_free(rsa_meth);
1287         goto err;
1288     }
1289     /* from this point rsa_meth will get freed with rsa */
1290 
1291     /* bind our custom RSA object to ssl_ctx */
1292     if (!SSL_CTX_use_RSAPrivateKey(ctx->ctx, rsa))
1293     {
1294         goto err;
1295     }
1296 
1297     RSA_free(rsa); /* doesn't necessarily free, just decrements refcount */
1298     return 1;
1299 
1300 err:
1301     if (rsa)
1302     {
1303         RSA_free(rsa);
1304     }
1305     else if (rsa_meth)
1306     {
1307         RSA_meth_free(rsa_meth);
1308     }
1309     return 0;
1310 }
1311 
1312 #if OPENSSL_VERSION_NUMBER > 0x10100000L && !defined(OPENSSL_NO_EC)
1313 
1314 /* called when EC_KEY is destroyed */
1315 static void
openvpn_extkey_ec_finish(EC_KEY * ec)1316 openvpn_extkey_ec_finish(EC_KEY *ec)
1317 {
1318     /* release the method structure */
1319     const EC_KEY_METHOD *ec_meth = EC_KEY_get_method(ec);
1320     EC_KEY_METHOD_free((EC_KEY_METHOD *) ec_meth);
1321 }
1322 
1323 /* EC_KEY_METHOD callback: sign().
1324  * Sign the hash using EC key and return DER encoded signature in sig,
1325  * its length in siglen. Return value is 1 on success, 0 on error.
1326  */
1327 static int
ecdsa_sign(int type,const unsigned char * dgst,int dgstlen,unsigned char * sig,unsigned int * siglen,const BIGNUM * kinv,const BIGNUM * r,EC_KEY * ec)1328 ecdsa_sign(int type, const unsigned char *dgst, int dgstlen, unsigned char *sig,
1329            unsigned int *siglen, const BIGNUM *kinv, const BIGNUM *r, EC_KEY *ec)
1330 {
1331     int capacity = ECDSA_size(ec);
1332     /*
1333      * ECDSA does not seem to have proper constants for paddings since
1334      * there are only signatures without padding at the moment, use
1335      * a generic ECDSA for the moment
1336      */
1337     int len = get_sig_from_man(dgst, dgstlen, sig, capacity, "ECDSA");
1338 
1339     if (len > 0)
1340     {
1341         *siglen = len;
1342         return 1;
1343     }
1344     return 0;
1345 }
1346 
1347 /* EC_KEY_METHOD callback: sign_setup(). We do no precomputations */
1348 static int
ecdsa_sign_setup(EC_KEY * ec,BN_CTX * ctx_in,BIGNUM ** kinvp,BIGNUM ** rp)1349 ecdsa_sign_setup(EC_KEY *ec, BN_CTX *ctx_in, BIGNUM **kinvp, BIGNUM **rp)
1350 {
1351     return 1;
1352 }
1353 
1354 /* EC_KEY_METHOD callback: sign_sig().
1355  * Sign the hash and return the result as a newly allocated ECDS_SIG
1356  * struct or NULL on error.
1357  */
1358 static ECDSA_SIG *
ecdsa_sign_sig(const unsigned char * dgst,int dgstlen,const BIGNUM * in_kinv,const BIGNUM * in_r,EC_KEY * ec)1359 ecdsa_sign_sig(const unsigned char *dgst, int dgstlen, const BIGNUM *in_kinv,
1360                const BIGNUM *in_r, EC_KEY *ec)
1361 {
1362     ECDSA_SIG *ecsig = NULL;
1363     unsigned int len = ECDSA_size(ec);
1364     struct gc_arena gc = gc_new();
1365 
1366     unsigned char *buf = gc_malloc(len, false, &gc);
1367     if (ecdsa_sign(0, dgst, dgstlen, buf, &len, NULL, NULL, ec) != 1)
1368     {
1369         goto out;
1370     }
1371     /* const char ** should be avoided: not up to us, so we cast our way through */
1372     ecsig = d2i_ECDSA_SIG(NULL, (const unsigned char **)&buf, len);
1373 
1374 out:
1375     gc_free(&gc);
1376     return ecsig;
1377 }
1378 
1379 static int
tls_ctx_use_external_ec_key(struct tls_root_ctx * ctx,EVP_PKEY * pkey)1380 tls_ctx_use_external_ec_key(struct tls_root_ctx *ctx, EVP_PKEY *pkey)
1381 {
1382     EC_KEY *ec = NULL;
1383     EVP_PKEY *privkey = NULL;
1384     EC_KEY_METHOD *ec_method;
1385 
1386     ASSERT(ctx);
1387 
1388     ec_method = EC_KEY_METHOD_new(EC_KEY_OpenSSL());
1389     if (!ec_method)
1390     {
1391         goto err;
1392     }
1393 
1394     /* Among init methods, we only need the finish method */
1395     EC_KEY_METHOD_set_init(ec_method, NULL, openvpn_extkey_ec_finish, NULL, NULL, NULL, NULL);
1396     EC_KEY_METHOD_set_sign(ec_method, ecdsa_sign, ecdsa_sign_setup, ecdsa_sign_sig);
1397 
1398     ec = EC_KEY_dup(EVP_PKEY_get0_EC_KEY(pkey));
1399     if (!ec)
1400     {
1401         EC_KEY_METHOD_free(ec_method);
1402         goto err;
1403     }
1404     if (!EC_KEY_set_method(ec, ec_method))
1405     {
1406         EC_KEY_METHOD_free(ec_method);
1407         goto err;
1408     }
1409     /* from this point ec_method will get freed when ec is freed */
1410 
1411     privkey = EVP_PKEY_new();
1412     if (!EVP_PKEY_assign_EC_KEY(privkey, ec))
1413     {
1414         goto err;
1415     }
1416     /* from this point ec will get freed when privkey is freed */
1417 
1418     if (!SSL_CTX_use_PrivateKey(ctx->ctx, privkey))
1419     {
1420         ec = NULL; /* avoid double freeing it below */
1421         goto err;
1422     }
1423 
1424     EVP_PKEY_free(privkey); /* this will down ref privkey and ec */
1425     return 1;
1426 
1427 err:
1428     /* Reach here only when ec and privkey can be independenly freed */
1429     EVP_PKEY_free(privkey);
1430     EC_KEY_free(ec);
1431     return 0;
1432 }
1433 #endif /* OPENSSL_VERSION_NUMBER > 1.1.0 dev && !defined(OPENSSL_NO_EC) */
1434 
1435 int
tls_ctx_use_management_external_key(struct tls_root_ctx * ctx)1436 tls_ctx_use_management_external_key(struct tls_root_ctx *ctx)
1437 {
1438     int ret = 1;
1439 
1440     ASSERT(NULL != ctx);
1441 
1442     X509 *cert = SSL_CTX_get0_certificate(ctx->ctx);
1443 
1444     ASSERT(NULL != cert);
1445 
1446     /* get the public key */
1447     EVP_PKEY *pkey = X509_get0_pubkey(cert);
1448     ASSERT(pkey); /* NULL before SSL_CTX_use_certificate() is called */
1449 
1450     if (EVP_PKEY_id(pkey) == EVP_PKEY_RSA)
1451     {
1452         if (!tls_ctx_use_external_rsa_key(ctx, pkey))
1453         {
1454             goto cleanup;
1455         }
1456     }
1457 #if (OPENSSL_VERSION_NUMBER > 0x10100000L) && !defined(OPENSSL_NO_EC)
1458     else if (EVP_PKEY_id(pkey) == EVP_PKEY_EC)
1459     {
1460         if (!tls_ctx_use_external_ec_key(ctx, pkey))
1461         {
1462             goto cleanup;
1463         }
1464     }
1465     else
1466     {
1467         crypto_msg(M_WARN, "management-external-key requires an RSA or EC certificate");
1468         goto cleanup;
1469     }
1470 #else  /* OPENSSL_VERSION_NUMBER > 1.1.0 dev && !defined(OPENSSL_NO_EC) */
1471     else
1472     {
1473         crypto_msg(M_WARN, "management-external-key requires an RSA certificate");
1474         goto cleanup;
1475     }
1476 #endif /* OPENSSL_VERSION_NUMBER > 1.1.0 dev && !defined(OPENSSL_NO_EC) */
1477 
1478     ret = 0;
1479 cleanup:
1480     if (ret)
1481     {
1482         crypto_msg(M_FATAL, "Cannot enable SSL external private key capability");
1483     }
1484     return ret;
1485 }
1486 
1487 #endif /* ifdef ENABLE_MANAGEMENT */
1488 
1489 static int
sk_x509_name_cmp(const X509_NAME * const * a,const X509_NAME * const * b)1490 sk_x509_name_cmp(const X509_NAME *const *a, const X509_NAME *const *b)
1491 {
1492     return X509_NAME_cmp(*a, *b);
1493 }
1494 
1495 void
tls_ctx_load_ca(struct tls_root_ctx * ctx,const char * ca_file,bool ca_file_inline,const char * ca_path,bool tls_server)1496 tls_ctx_load_ca(struct tls_root_ctx *ctx, const char *ca_file,
1497                 bool ca_file_inline, const char *ca_path, bool tls_server)
1498 {
1499     STACK_OF(X509_INFO) *info_stack = NULL;
1500     STACK_OF(X509_NAME) *cert_names = NULL;
1501     X509_LOOKUP *lookup = NULL;
1502     X509_STORE *store = NULL;
1503     X509_NAME *xn = NULL;
1504     BIO *in = NULL;
1505     int i, added = 0, prev = 0;
1506 
1507     ASSERT(NULL != ctx);
1508 
1509     store = SSL_CTX_get_cert_store(ctx->ctx);
1510     if (!store)
1511     {
1512         crypto_msg(M_FATAL, "Cannot get certificate store");
1513     }
1514 
1515     /* Try to add certificates and CRLs from ca_file */
1516     if (ca_file)
1517     {
1518         if (ca_file_inline)
1519         {
1520             in = BIO_new_mem_buf((char *)ca_file, -1);
1521         }
1522         else
1523         {
1524             in = BIO_new_file(ca_file, "r");
1525         }
1526 
1527         if (in)
1528         {
1529             info_stack = PEM_X509_INFO_read_bio(in, NULL, NULL, NULL);
1530         }
1531 
1532         if (info_stack)
1533         {
1534             for (i = 0; i < sk_X509_INFO_num(info_stack); i++)
1535             {
1536                 X509_INFO *info = sk_X509_INFO_value(info_stack, i);
1537                 if (info->crl)
1538                 {
1539                     X509_STORE_add_crl(store, info->crl);
1540                 }
1541 
1542                 if (tls_server && !info->x509)
1543                 {
1544                     crypto_msg(M_FATAL, "X509 name was missing in TLS mode");
1545                 }
1546 
1547                 if (info->x509)
1548                 {
1549                     X509_STORE_add_cert(store, info->x509);
1550                     added++;
1551 
1552                     if (!tls_server)
1553                     {
1554                         continue;
1555                     }
1556 
1557                     /* Use names of CAs as a client CA list */
1558                     if (cert_names == NULL)
1559                     {
1560                         cert_names = sk_X509_NAME_new(sk_x509_name_cmp);
1561                         if (!cert_names)
1562                         {
1563                             continue;
1564                         }
1565                     }
1566 
1567                     xn = X509_get_subject_name(info->x509);
1568                     if (!xn)
1569                     {
1570                         continue;
1571                     }
1572 
1573                     /* Don't add duplicate CA names */
1574                     if (sk_X509_NAME_find(cert_names, xn) == -1)
1575                     {
1576                         xn = X509_NAME_dup(xn);
1577                         if (!xn)
1578                         {
1579                             continue;
1580                         }
1581                         sk_X509_NAME_push(cert_names, xn);
1582                     }
1583                 }
1584 
1585                 if (tls_server)
1586                 {
1587                     int cnum = sk_X509_NAME_num(cert_names);
1588                     if (cnum != (prev + 1))
1589                     {
1590                         crypto_msg(M_WARN,
1591                                    "Cannot load CA certificate file %s (entry %d did not validate)",
1592                                    print_key_filename(ca_file, ca_file_inline),
1593                                    added);
1594                     }
1595                     prev = cnum;
1596                 }
1597             }
1598             sk_X509_INFO_pop_free(info_stack, X509_INFO_free);
1599         }
1600 
1601         if (tls_server)
1602         {
1603             SSL_CTX_set_client_CA_list(ctx->ctx, cert_names);
1604         }
1605 
1606         if (!added)
1607         {
1608             crypto_msg(M_FATAL,
1609                        "Cannot load CA certificate file %s (no entries were read)",
1610                        print_key_filename(ca_file, ca_file_inline));
1611         }
1612 
1613         if (tls_server)
1614         {
1615             int cnum = sk_X509_NAME_num(cert_names);
1616             if (cnum != added)
1617             {
1618                 crypto_msg(M_FATAL, "Cannot load CA certificate file %s (only %d "
1619                            "of %d entries were valid X509 names)",
1620                            print_key_filename(ca_file, ca_file_inline), cnum,
1621                            added);
1622             }
1623         }
1624 
1625         BIO_free(in);
1626     }
1627 
1628     /* Set a store for certs (CA & CRL) with a lookup on the "capath" hash directory */
1629     if (ca_path)
1630     {
1631         lookup = X509_STORE_add_lookup(store, X509_LOOKUP_hash_dir());
1632         if (lookup && X509_LOOKUP_add_dir(lookup, ca_path, X509_FILETYPE_PEM))
1633         {
1634             msg(M_WARN, "WARNING: experimental option --capath %s", ca_path);
1635         }
1636         else
1637         {
1638             crypto_msg(M_FATAL, "Cannot add lookup at --capath %s", ca_path);
1639         }
1640         X509_STORE_set_flags(store, X509_V_FLAG_CRL_CHECK | X509_V_FLAG_CRL_CHECK_ALL);
1641     }
1642 }
1643 
1644 void
tls_ctx_load_extra_certs(struct tls_root_ctx * ctx,const char * extra_certs_file,bool extra_certs_file_inline)1645 tls_ctx_load_extra_certs(struct tls_root_ctx *ctx, const char *extra_certs_file,
1646                          bool extra_certs_file_inline)
1647 {
1648     BIO *in;
1649     if (extra_certs_file_inline)
1650     {
1651         in = BIO_new_mem_buf((char *)extra_certs_file, -1);
1652     }
1653     else
1654     {
1655         in = BIO_new_file(extra_certs_file, "r");
1656     }
1657 
1658     if (in == NULL)
1659     {
1660         crypto_msg(M_FATAL, "Cannot load extra-certs file: %s",
1661                    print_key_filename(extra_certs_file,
1662                                       extra_certs_file_inline));
1663 
1664     }
1665     else
1666     {
1667         tls_ctx_add_extra_certs(ctx, in, false);
1668     }
1669 
1670     BIO_free(in);
1671 }
1672 
1673 /* **************************************
1674  *
1675  * Key-state specific functions
1676  *
1677  ***************************************/
1678 /*
1679  *
1680  * BIO functions
1681  *
1682  */
1683 
1684 #ifdef BIO_DEBUG
1685 
1686 #warning BIO_DEBUG defined
1687 
1688 static FILE *biofp;                            /* GLOBAL */
1689 static bool biofp_toggle;                      /* GLOBAL */
1690 static time_t biofp_last_open;                 /* GLOBAL */
1691 static const int biofp_reopen_interval = 600;  /* GLOBAL */
1692 
1693 static void
close_biofp(void)1694 close_biofp(void)
1695 {
1696     if (biofp)
1697     {
1698         ASSERT(!fclose(biofp));
1699         biofp = NULL;
1700     }
1701 }
1702 
1703 static void
open_biofp(void)1704 open_biofp(void)
1705 {
1706     const time_t current = time(NULL);
1707     const pid_t pid = getpid();
1708 
1709     if (biofp_last_open + biofp_reopen_interval < current)
1710     {
1711         close_biofp();
1712     }
1713     if (!biofp)
1714     {
1715         char fn[256];
1716         openvpn_snprintf(fn, sizeof(fn), "bio/%d-%d.log", pid, biofp_toggle);
1717         biofp = fopen(fn, "w");
1718         ASSERT(biofp);
1719         biofp_last_open = time(NULL);
1720         biofp_toggle ^= 1;
1721     }
1722 }
1723 
1724 static void
bio_debug_data(const char * mode,BIO * bio,const uint8_t * buf,int len,const char * desc)1725 bio_debug_data(const char *mode, BIO *bio, const uint8_t *buf, int len, const char *desc)
1726 {
1727     struct gc_arena gc = gc_new();
1728     if (len > 0)
1729     {
1730         open_biofp();
1731         fprintf(biofp, "BIO_%s %s time=%" PRIi64 " bio=" ptr_format " len=%d data=%s\n",
1732                 mode, desc, (int64_t)time(NULL), (ptr_type)bio, len, format_hex(buf, len, 0, &gc));
1733         fflush(biofp);
1734     }
1735     gc_free(&gc);
1736 }
1737 
1738 static void
bio_debug_oc(const char * mode,BIO * bio)1739 bio_debug_oc(const char *mode, BIO *bio)
1740 {
1741     open_biofp();
1742     fprintf(biofp, "BIO %s time=%" PRIi64 " bio=" ptr_format "\n",
1743             mode, (int64_t)time(NULL), (ptr_type)bio);
1744     fflush(biofp);
1745 }
1746 
1747 #endif /* ifdef BIO_DEBUG */
1748 
1749 /*
1750  * Write to an OpenSSL BIO in non-blocking mode.
1751  */
1752 static int
bio_write(BIO * bio,const uint8_t * data,int size,const char * desc)1753 bio_write(BIO *bio, const uint8_t *data, int size, const char *desc)
1754 {
1755     int i;
1756     int ret = 0;
1757     ASSERT(size >= 0);
1758     if (size)
1759     {
1760         /*
1761          * Free the L_TLS lock prior to calling BIO routines
1762          * so that foreground thread can still call
1763          * tls_pre_decrypt or tls_pre_encrypt,
1764          * allowing tunnel packet forwarding to continue.
1765          */
1766 #ifdef BIO_DEBUG
1767         bio_debug_data("write", bio, data, size, desc);
1768 #endif
1769         i = BIO_write(bio, data, size);
1770 
1771         if (i < 0)
1772         {
1773             if (BIO_should_retry(bio))
1774             {
1775             }
1776             else
1777             {
1778                 crypto_msg(D_TLS_ERRORS, "TLS ERROR: BIO write %s error", desc);
1779                 ret = -1;
1780                 ERR_clear_error();
1781             }
1782         }
1783         else if (i != size)
1784         {
1785             crypto_msg(D_TLS_ERRORS, "TLS ERROR: BIO write %s incomplete %d/%d",
1786                        desc, i, size);
1787             ret = -1;
1788             ERR_clear_error();
1789         }
1790         else
1791         {                       /* successful write */
1792             dmsg(D_HANDSHAKE_VERBOSE, "BIO write %s %d bytes", desc, i);
1793             ret = 1;
1794         }
1795     }
1796     return ret;
1797 }
1798 
1799 /*
1800  * Inline functions for reading from and writing
1801  * to BIOs.
1802  */
1803 
1804 static void
bio_write_post(const int status,struct buffer * buf)1805 bio_write_post(const int status, struct buffer *buf)
1806 {
1807     if (status == 1) /* success status return from bio_write? */
1808     {
1809         memset(BPTR(buf), 0, BLEN(buf));  /* erase data just written */
1810         buf->len = 0;
1811     }
1812 }
1813 
1814 /*
1815  * Read from an OpenSSL BIO in non-blocking mode.
1816  */
1817 static int
bio_read(BIO * bio,struct buffer * buf,int maxlen,const char * desc)1818 bio_read(BIO *bio, struct buffer *buf, int maxlen, const char *desc)
1819 {
1820     int i;
1821     int ret = 0;
1822     ASSERT(buf->len >= 0);
1823     if (buf->len)
1824     {
1825     }
1826     else
1827     {
1828         int len = buf_forward_capacity(buf);
1829         if (maxlen < len)
1830         {
1831             len = maxlen;
1832         }
1833 
1834         /*
1835          * BIO_read brackets most of the serious RSA
1836          * key negotiation number crunching.
1837          */
1838         i = BIO_read(bio, BPTR(buf), len);
1839 
1840         VALGRIND_MAKE_READABLE((void *) &i, sizeof(i));
1841 
1842 #ifdef BIO_DEBUG
1843         bio_debug_data("read", bio, BPTR(buf), i, desc);
1844 #endif
1845         if (i < 0)
1846         {
1847             if (BIO_should_retry(bio))
1848             {
1849             }
1850             else
1851             {
1852                 crypto_msg(D_TLS_ERRORS, "TLS_ERROR: BIO read %s error", desc);
1853                 buf->len = 0;
1854                 ret = -1;
1855                 ERR_clear_error();
1856             }
1857         }
1858         else if (!i)
1859         {
1860             buf->len = 0;
1861         }
1862         else
1863         {                       /* successful read */
1864             dmsg(D_HANDSHAKE_VERBOSE, "BIO read %s %d bytes", desc, i);
1865             buf->len = i;
1866             ret = 1;
1867             VALGRIND_MAKE_READABLE((void *) BPTR(buf), BLEN(buf));
1868         }
1869     }
1870     return ret;
1871 }
1872 
1873 void
key_state_ssl_init(struct key_state_ssl * ks_ssl,const struct tls_root_ctx * ssl_ctx,bool is_server,struct tls_session * session)1874 key_state_ssl_init(struct key_state_ssl *ks_ssl, const struct tls_root_ctx *ssl_ctx, bool is_server, struct tls_session *session)
1875 {
1876     ASSERT(NULL != ssl_ctx);
1877     ASSERT(ks_ssl);
1878     CLEAR(*ks_ssl);
1879 
1880     ks_ssl->ssl = SSL_new(ssl_ctx->ctx);
1881     if (!ks_ssl->ssl)
1882     {
1883         crypto_msg(M_FATAL, "SSL_new failed");
1884     }
1885 
1886     /* put session * in ssl object so we can access it
1887      * from verify callback*/
1888     SSL_set_ex_data(ks_ssl->ssl, mydata_index, session);
1889 
1890     ASSERT((ks_ssl->ssl_bio = BIO_new(BIO_f_ssl())));
1891     ASSERT((ks_ssl->ct_in = BIO_new(BIO_s_mem())));
1892     ASSERT((ks_ssl->ct_out = BIO_new(BIO_s_mem())));
1893 
1894 #ifdef BIO_DEBUG
1895     bio_debug_oc("open ssl_bio", ks_ssl->ssl_bio);
1896     bio_debug_oc("open ct_in", ks_ssl->ct_in);
1897     bio_debug_oc("open ct_out", ks_ssl->ct_out);
1898 #endif
1899 
1900     if (is_server)
1901     {
1902         SSL_set_accept_state(ks_ssl->ssl);
1903     }
1904     else
1905     {
1906         SSL_set_connect_state(ks_ssl->ssl);
1907     }
1908 
1909     SSL_set_bio(ks_ssl->ssl, ks_ssl->ct_in, ks_ssl->ct_out);
1910     BIO_set_ssl(ks_ssl->ssl_bio, ks_ssl->ssl, BIO_NOCLOSE);
1911 }
1912 
1913 void
key_state_ssl_free(struct key_state_ssl * ks_ssl)1914 key_state_ssl_free(struct key_state_ssl *ks_ssl)
1915 {
1916     if (ks_ssl->ssl)
1917     {
1918 #ifdef BIO_DEBUG
1919         bio_debug_oc("close ssl_bio", ks_ssl->ssl_bio);
1920         bio_debug_oc("close ct_in", ks_ssl->ct_in);
1921         bio_debug_oc("close ct_out", ks_ssl->ct_out);
1922 #endif
1923         BIO_free_all(ks_ssl->ssl_bio);
1924         SSL_free(ks_ssl->ssl);
1925     }
1926 }
1927 
1928 int
key_state_write_plaintext(struct key_state_ssl * ks_ssl,struct buffer * buf)1929 key_state_write_plaintext(struct key_state_ssl *ks_ssl, struct buffer *buf)
1930 {
1931     int ret = 0;
1932     perf_push(PERF_BIO_WRITE_PLAINTEXT);
1933 
1934 #ifdef ENABLE_CRYPTO_OPENSSL
1935     ASSERT(NULL != ks_ssl);
1936 
1937     ret = bio_write(ks_ssl->ssl_bio, BPTR(buf), BLEN(buf),
1938                     "tls_write_plaintext");
1939     bio_write_post(ret, buf);
1940 #endif /* ENABLE_CRYPTO_OPENSSL */
1941 
1942     perf_pop();
1943     return ret;
1944 }
1945 
1946 int
key_state_write_plaintext_const(struct key_state_ssl * ks_ssl,const uint8_t * data,int len)1947 key_state_write_plaintext_const(struct key_state_ssl *ks_ssl, const uint8_t *data, int len)
1948 {
1949     int ret = 0;
1950     perf_push(PERF_BIO_WRITE_PLAINTEXT);
1951 
1952     ASSERT(NULL != ks_ssl);
1953 
1954     ret = bio_write(ks_ssl->ssl_bio, data, len, "tls_write_plaintext_const");
1955 
1956     perf_pop();
1957     return ret;
1958 }
1959 
1960 int
key_state_read_ciphertext(struct key_state_ssl * ks_ssl,struct buffer * buf,int maxlen)1961 key_state_read_ciphertext(struct key_state_ssl *ks_ssl, struct buffer *buf,
1962                           int maxlen)
1963 {
1964     int ret = 0;
1965     perf_push(PERF_BIO_READ_CIPHERTEXT);
1966 
1967     ASSERT(NULL != ks_ssl);
1968 
1969     ret = bio_read(ks_ssl->ct_out, buf, maxlen, "tls_read_ciphertext");
1970 
1971     perf_pop();
1972     return ret;
1973 }
1974 
1975 int
key_state_write_ciphertext(struct key_state_ssl * ks_ssl,struct buffer * buf)1976 key_state_write_ciphertext(struct key_state_ssl *ks_ssl, struct buffer *buf)
1977 {
1978     int ret = 0;
1979     perf_push(PERF_BIO_WRITE_CIPHERTEXT);
1980 
1981     ASSERT(NULL != ks_ssl);
1982 
1983     ret = bio_write(ks_ssl->ct_in, BPTR(buf), BLEN(buf), "tls_write_ciphertext");
1984     bio_write_post(ret, buf);
1985 
1986     perf_pop();
1987     return ret;
1988 }
1989 
1990 int
key_state_read_plaintext(struct key_state_ssl * ks_ssl,struct buffer * buf,int maxlen)1991 key_state_read_plaintext(struct key_state_ssl *ks_ssl, struct buffer *buf,
1992                          int maxlen)
1993 {
1994     int ret = 0;
1995     perf_push(PERF_BIO_READ_PLAINTEXT);
1996 
1997     ASSERT(NULL != ks_ssl);
1998 
1999     ret = bio_read(ks_ssl->ssl_bio, buf, maxlen, "tls_read_plaintext");
2000 
2001     perf_pop();
2002     return ret;
2003 }
2004 
2005 /**
2006  * Print human readable information about the certifcate into buf
2007  * @param cert      the certificate being used
2008  * @param buf       output buffer
2009  * @param buflen    output buffer length
2010  */
2011 static void
print_cert_details(X509 * cert,char * buf,size_t buflen)2012 print_cert_details(X509 *cert, char *buf, size_t buflen)
2013 {
2014     const char *curve = "";
2015     const char *type = "(error getting type)";
2016     EVP_PKEY *pkey = X509_get_pubkey(cert);
2017 
2018     if (pkey == NULL)
2019     {
2020         buf[0] = 0;
2021         return;
2022     }
2023 
2024     int typeid = EVP_PKEY_id(pkey);
2025 
2026 #ifndef OPENSSL_NO_EC
2027     if (typeid == EVP_PKEY_EC && EVP_PKEY_get0_EC_KEY(pkey) != NULL)
2028     {
2029         const EC_KEY *ec = EVP_PKEY_get0_EC_KEY(pkey);
2030         const EC_GROUP *group = EC_KEY_get0_group(ec);
2031 
2032         int nid = EC_GROUP_get_curve_name(group);
2033         if (nid == 0 || (curve = OBJ_nid2sn(nid)) == NULL)
2034         {
2035             curve = "(error getting curve name)";
2036         }
2037     }
2038 #endif
2039     if (EVP_PKEY_id(pkey) != 0)
2040     {
2041         int typeid = EVP_PKEY_id(pkey);
2042         type = OBJ_nid2sn(typeid);
2043 
2044         /* OpenSSL reports rsaEncryption, dsaEncryption and
2045         * id-ecPublicKey, map these values to nicer ones */
2046         if (typeid == EVP_PKEY_RSA)
2047         {
2048             type = "RSA";
2049         }
2050         else if (typeid == EVP_PKEY_DSA)
2051         {
2052             type = "DSA";
2053         }
2054         else if (typeid == EVP_PKEY_EC)
2055         {
2056             /* EC gets the curve appended after the type */
2057             type = "EC, curve ";
2058         }
2059         else if (type == NULL)
2060         {
2061             type = "unknown type";
2062         }
2063     }
2064 
2065     char sig[128] = { 0 };
2066     int signature_nid = X509_get_signature_nid(cert);
2067     if (signature_nid != 0)
2068     {
2069         openvpn_snprintf(sig, sizeof(sig), ", signature: %s",
2070                          OBJ_nid2sn(signature_nid));
2071     }
2072 
2073     openvpn_snprintf(buf, buflen, ", peer certificate: %d bit %s%s%s",
2074                      EVP_PKEY_bits(pkey), type, curve, sig);
2075 
2076     EVP_PKEY_free(pkey);
2077 }
2078 
2079 /* **************************************
2080  *
2081  * Information functions
2082  *
2083  * Print information for the end user.
2084  *
2085  ***************************************/
2086 void
print_details(struct key_state_ssl * ks_ssl,const char * prefix)2087 print_details(struct key_state_ssl *ks_ssl, const char *prefix)
2088 {
2089     const SSL_CIPHER *ciph;
2090     char s1[256];
2091     char s2[256];
2092 
2093     s1[0] = s2[0] = 0;
2094     ciph = SSL_get_current_cipher(ks_ssl->ssl);
2095     openvpn_snprintf(s1, sizeof(s1), "%s %s, cipher %s %s",
2096                      prefix,
2097                      SSL_get_version(ks_ssl->ssl),
2098                      SSL_CIPHER_get_version(ciph),
2099                      SSL_CIPHER_get_name(ciph));
2100     X509 *cert = SSL_get_peer_certificate(ks_ssl->ssl);
2101 
2102     if (cert)
2103     {
2104         print_cert_details(cert, s2, sizeof(s2));
2105         X509_free(cert);
2106     }
2107     msg(D_HANDSHAKE, "%s%s", s1, s2);
2108 }
2109 
2110 void
show_available_tls_ciphers_list(const char * cipher_list,const char * tls_cert_profile,bool tls13)2111 show_available_tls_ciphers_list(const char *cipher_list,
2112                                 const char *tls_cert_profile,
2113                                 bool tls13)
2114 {
2115     struct tls_root_ctx tls_ctx;
2116 
2117     tls_ctx.ctx = SSL_CTX_new(SSLv23_method());
2118     if (!tls_ctx.ctx)
2119     {
2120         crypto_msg(M_FATAL, "Cannot create SSL_CTX object");
2121     }
2122 
2123 #if defined(TLS1_3_VERSION)
2124     if (tls13)
2125     {
2126         SSL_CTX_set_min_proto_version(tls_ctx.ctx,
2127                                       openssl_tls_version(TLS_VER_1_3));
2128         tls_ctx_restrict_ciphers_tls13(&tls_ctx, cipher_list);
2129     }
2130     else
2131 #endif
2132     {
2133         SSL_CTX_set_max_proto_version(tls_ctx.ctx, TLS1_2_VERSION);
2134         tls_ctx_restrict_ciphers(&tls_ctx, cipher_list);
2135     }
2136 
2137     tls_ctx_set_cert_profile(&tls_ctx, tls_cert_profile);
2138 
2139     SSL *ssl = SSL_new(tls_ctx.ctx);
2140     if (!ssl)
2141     {
2142         crypto_msg(M_FATAL, "Cannot create SSL object");
2143     }
2144 
2145 #if OPENSSL_VERSION_NUMBER < 0x1010000fL
2146     STACK_OF(SSL_CIPHER) *sk = SSL_get_ciphers(ssl);
2147 #else
2148     STACK_OF(SSL_CIPHER) *sk = SSL_get1_supported_ciphers(ssl);
2149 #endif
2150     for (int i = 0; i < sk_SSL_CIPHER_num(sk); i++)
2151     {
2152         const SSL_CIPHER *c = sk_SSL_CIPHER_value(sk, i);
2153 
2154         const char *cipher_name = SSL_CIPHER_get_name(c);
2155 
2156         const tls_cipher_name_pair *pair =
2157             tls_get_cipher_name_pair(cipher_name, strlen(cipher_name));
2158 
2159         if (tls13)
2160         {
2161             printf("%s\n", cipher_name);
2162         }
2163         else if (NULL == pair)
2164         {
2165             /* No translation found, print warning */
2166             printf("%s (No IANA name known to OpenVPN, use OpenSSL name.)\n",
2167                    cipher_name);
2168         }
2169         else
2170         {
2171             printf("%s\n", pair->iana_name);
2172         }
2173     }
2174 #if (OPENSSL_VERSION_NUMBER >= 0x1010000fL)
2175     sk_SSL_CIPHER_free(sk);
2176 #endif
2177     SSL_free(ssl);
2178     SSL_CTX_free(tls_ctx.ctx);
2179 }
2180 
2181 /*
2182  * Show the Elliptic curves that are available for us to use
2183  * in the OpenSSL library.
2184  */
2185 void
show_available_curves(void)2186 show_available_curves(void)
2187 {
2188     printf("Consider using openssl 'ecparam -list_curves' as\n"
2189            "alternative to running this command.\n");
2190 #ifndef OPENSSL_NO_EC
2191     EC_builtin_curve *curves = NULL;
2192     size_t crv_len = 0;
2193     size_t n = 0;
2194 
2195     crv_len = EC_get_builtin_curves(NULL, 0);
2196     ALLOC_ARRAY(curves, EC_builtin_curve, crv_len);
2197     if (EC_get_builtin_curves(curves, crv_len))
2198     {
2199         printf("\nAvailable Elliptic curves/groups:\n");
2200         for (n = 0; n < crv_len; n++)
2201         {
2202             const char *sname;
2203             sname   = OBJ_nid2sn(curves[n].nid);
2204             if (sname == NULL)
2205             {
2206                 sname = "";
2207             }
2208 
2209             printf("%s\n", sname);
2210         }
2211     }
2212     else
2213     {
2214         crypto_msg(M_FATAL, "Cannot get list of builtin curves");
2215     }
2216     free(curves);
2217 #else  /* ifndef OPENSSL_NO_EC */
2218     msg(M_WARN, "Your OpenSSL library was built without elliptic curve support. "
2219         "No curves available.");
2220 #endif /* ifndef OPENSSL_NO_EC */
2221 }
2222 
2223 void
get_highest_preference_tls_cipher(char * buf,int size)2224 get_highest_preference_tls_cipher(char *buf, int size)
2225 {
2226     SSL_CTX *ctx;
2227     SSL *ssl;
2228     const char *cipher_name;
2229 
2230     ctx = SSL_CTX_new(SSLv23_method());
2231     if (!ctx)
2232     {
2233         crypto_msg(M_FATAL, "Cannot create SSL_CTX object");
2234     }
2235     ssl = SSL_new(ctx);
2236     if (!ssl)
2237     {
2238         crypto_msg(M_FATAL, "Cannot create SSL object");
2239     }
2240 
2241     cipher_name = SSL_get_cipher_list(ssl, 0);
2242     strncpynt(buf, cipher_name, size);
2243 
2244     SSL_free(ssl);
2245     SSL_CTX_free(ctx);
2246 }
2247 
2248 const char *
get_ssl_library_version(void)2249 get_ssl_library_version(void)
2250 {
2251     return OpenSSL_version(OPENSSL_VERSION);
2252 }
2253 
2254 #endif /* defined(ENABLE_CRYPTO_OPENSSL) */
2255