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  *  Copyright (C) 2006-2010, Brainspark B.V.
11  *
12  *  This program is free software; you can redistribute it and/or modify
13  *  it under the terms of the GNU General Public License version 2
14  *  as published by the Free Software Foundation.
15  *
16  *  This program is distributed in the hope that it will be useful,
17  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
18  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19  *  GNU General Public License for more details.
20  *
21  *  You should have received a copy of the GNU General Public License along
22  *  with this program; if not, write to the Free Software Foundation, Inc.,
23  *  51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
24  */
25 
26 /**
27  * @file Control Channel mbed TLS Backend
28  */
29 
30 #ifdef HAVE_CONFIG_H
31 #include "config.h"
32 #elif defined(_MSC_VER)
33 #include "config-msvc.h"
34 #endif
35 
36 #include "syshead.h"
37 
38 #if defined(ENABLE_CRYPTO_MBEDTLS)
39 
40 #include "errlevel.h"
41 #include "ssl_backend.h"
42 #include "base64.h"
43 #include "buffer.h"
44 #include "misc.h"
45 #include "manage.h"
46 #include "pkcs11_backend.h"
47 #include "ssl_common.h"
48 
49 #include <mbedtls/havege.h>
50 
51 #include "ssl_verify_mbedtls.h"
52 #include <mbedtls/debug.h>
53 #include <mbedtls/error.h>
54 #include <mbedtls/version.h>
55 
56 #if MBEDTLS_VERSION_NUMBER >= 0x02040000
57     #include <mbedtls/net_sockets.h>
58 #else
59     #include <mbedtls/net.h>
60 #endif
61 
62 #include <mbedtls/oid.h>
63 #include <mbedtls/pem.h>
64 
65 static const mbedtls_x509_crt_profile openvpn_x509_crt_profile_legacy =
66 {
67     /* Hashes from SHA-1 and above */
68     MBEDTLS_X509_ID_FLAG( MBEDTLS_MD_SHA1 )
69     |MBEDTLS_X509_ID_FLAG( MBEDTLS_MD_RIPEMD160 )
70     |MBEDTLS_X509_ID_FLAG( MBEDTLS_MD_SHA224 )
71     |MBEDTLS_X509_ID_FLAG( MBEDTLS_MD_SHA256 )
72     |MBEDTLS_X509_ID_FLAG( MBEDTLS_MD_SHA384 )
73     |MBEDTLS_X509_ID_FLAG( MBEDTLS_MD_SHA512 ),
74     0xFFFFFFF, /* Any PK alg    */
75     0xFFFFFFF, /* Any curve     */
76     1024,      /* RSA-1024 and larger */
77 };
78 
79 static const mbedtls_x509_crt_profile openvpn_x509_crt_profile_preferred =
80 {
81     /* SHA-2 and above */
82     MBEDTLS_X509_ID_FLAG( MBEDTLS_MD_SHA224 )
83     |MBEDTLS_X509_ID_FLAG( MBEDTLS_MD_SHA256 )
84     |MBEDTLS_X509_ID_FLAG( MBEDTLS_MD_SHA384 )
85     |MBEDTLS_X509_ID_FLAG( MBEDTLS_MD_SHA512 ),
86     0xFFFFFFF, /* Any PK alg    */
87     0xFFFFFFF, /* Any curve     */
88     2048,      /* RSA-2048 and larger */
89 };
90 
91 #define openvpn_x509_crt_profile_suiteb mbedtls_x509_crt_profile_suiteb;
92 
93 void
tls_init_lib(void)94 tls_init_lib(void)
95 {
96 }
97 
98 void
tls_free_lib(void)99 tls_free_lib(void)
100 {
101 }
102 
103 void
tls_clear_error(void)104 tls_clear_error(void)
105 {
106 }
107 
108 void
tls_ctx_server_new(struct tls_root_ctx * ctx)109 tls_ctx_server_new(struct tls_root_ctx *ctx)
110 {
111     ASSERT(NULL != ctx);
112     CLEAR(*ctx);
113 
114     ALLOC_OBJ_CLEAR(ctx->dhm_ctx, mbedtls_dhm_context);
115 
116     ALLOC_OBJ_CLEAR(ctx->ca_chain, mbedtls_x509_crt);
117 
118     ctx->endpoint = MBEDTLS_SSL_IS_SERVER;
119     ctx->initialised = true;
120 }
121 
122 void
tls_ctx_client_new(struct tls_root_ctx * ctx)123 tls_ctx_client_new(struct tls_root_ctx *ctx)
124 {
125     ASSERT(NULL != ctx);
126     CLEAR(*ctx);
127 
128     ALLOC_OBJ_CLEAR(ctx->dhm_ctx, mbedtls_dhm_context);
129     ALLOC_OBJ_CLEAR(ctx->ca_chain, mbedtls_x509_crt);
130 
131     ctx->endpoint = MBEDTLS_SSL_IS_CLIENT;
132     ctx->initialised = true;
133 }
134 
135 void
tls_ctx_free(struct tls_root_ctx * ctx)136 tls_ctx_free(struct tls_root_ctx *ctx)
137 {
138     if (ctx)
139     {
140         mbedtls_pk_free(ctx->priv_key);
141         free(ctx->priv_key);
142 
143         mbedtls_x509_crt_free(ctx->ca_chain);
144         free(ctx->ca_chain);
145 
146         mbedtls_x509_crt_free(ctx->crt_chain);
147         free(ctx->crt_chain);
148 
149         mbedtls_dhm_free(ctx->dhm_ctx);
150         free(ctx->dhm_ctx);
151 
152         mbedtls_x509_crl_free(ctx->crl);
153         free(ctx->crl);
154 
155 #if defined(ENABLE_PKCS11)
156         pkcs11h_certificate_freeCertificate(ctx->pkcs11_cert);
157 #endif
158 
159         free(ctx->allowed_ciphers);
160 
161         free(ctx->groups);
162 
163         CLEAR(*ctx);
164 
165         ctx->initialised = false;
166     }
167 }
168 
169 bool
tls_ctx_initialised(struct tls_root_ctx * ctx)170 tls_ctx_initialised(struct tls_root_ctx *ctx)
171 {
172     ASSERT(NULL != ctx);
173     return ctx->initialised;
174 }
175 
176 #ifdef HAVE_EXPORT_KEYING_MATERIAL
177 int
mbedtls_ssl_export_keys_cb(void * p_expkey,const unsigned char * ms,const unsigned char * kb,size_t maclen,size_t keylen,size_t ivlen,const unsigned char client_random[32],const unsigned char server_random[32],mbedtls_tls_prf_types tls_prf_type)178 mbedtls_ssl_export_keys_cb(void *p_expkey, const unsigned char *ms,
179                            const unsigned char *kb, size_t maclen,
180                            size_t keylen, size_t ivlen,
181                            const unsigned char client_random[32],
182                            const unsigned char server_random[32],
183                            mbedtls_tls_prf_types tls_prf_type)
184 {
185     struct tls_session *session = p_expkey;
186     struct key_state_ssl *ks_ssl = &session->key[KS_PRIMARY].ks_ssl;
187     struct tls_key_cache *cache = &ks_ssl->tls_key_cache;
188 
189     static_assert(sizeof(ks_ssl->ctx->session->master)
190                     == sizeof(cache->master_secret), "master size mismatch");
191 
192     memcpy(cache->client_server_random, client_random, 32);
193     memcpy(cache->client_server_random + 32, server_random, 32);
194     memcpy(cache->master_secret, ms, sizeof(cache->master_secret));
195     cache->tls_prf_type = tls_prf_type;
196 
197     return true;
198 }
199 
200 bool
key_state_export_keying_material(struct tls_session * session,const char * label,size_t label_size,void * ekm,size_t ekm_size)201 key_state_export_keying_material(struct tls_session *session,
202                                  const char* label, size_t label_size,
203                                  void *ekm, size_t ekm_size)
204 {
205     ASSERT(strlen(label) == label_size);
206 
207     struct tls_key_cache *cache = &session->key[KS_PRIMARY].ks_ssl.tls_key_cache;
208 
209     /* If the type is NONE, we either have no cached secrets or
210      * there is no PRF, in both cases we cannot generate key material */
211     if (cache->tls_prf_type == MBEDTLS_SSL_TLS_PRF_NONE)
212     {
213         return false;
214     }
215 
216     int ret = mbedtls_ssl_tls_prf(cache->tls_prf_type, cache->master_secret,
217                                   sizeof(cache->master_secret),
218                                   label, cache->client_server_random,
219                                   sizeof(cache->client_server_random),
220                                   ekm, ekm_size);
221 
222     if (mbed_ok(ret))
223     {
224         return true;
225     }
226     else
227     {
228         secure_memzero(ekm, session->opt->ekm_size);
229         return  false;
230     }
231 }
232 #else
233 bool
key_state_export_keying_material(struct tls_session * session,const char * label,size_t label_size,void * ekm,size_t ekm_size)234 key_state_export_keying_material(struct tls_session *session,
235                                  const char* label, size_t label_size,
236                                  void *ekm, size_t ekm_size)
237 {
238     /* Dummy function to avoid ifdefs in the common code */
239     return false;
240 }
241 #endif /* HAVE_EXPORT_KEYING_MATERIAL */
242 
243 bool
tls_ctx_set_options(struct tls_root_ctx * ctx,unsigned int ssl_flags)244 tls_ctx_set_options(struct tls_root_ctx *ctx, unsigned int ssl_flags)
245 {
246     return true;
247 }
248 
249 static const char *
tls_translate_cipher_name(const char * cipher_name)250 tls_translate_cipher_name(const char *cipher_name)
251 {
252     const tls_cipher_name_pair *pair = tls_get_cipher_name_pair(cipher_name, strlen(cipher_name));
253 
254     if (NULL == pair)
255     {
256         /* No translation found, return original */
257         return cipher_name;
258     }
259 
260     if (0 != strcmp(cipher_name, pair->iana_name))
261     {
262         /* Deprecated name found, notify user */
263         msg(M_WARN, "Deprecated cipher suite name '%s', please use IANA name '%s'", pair->openssl_name, pair->iana_name);
264     }
265 
266     return pair->iana_name;
267 }
268 
269 void
tls_ctx_restrict_ciphers_tls13(struct tls_root_ctx * ctx,const char * ciphers)270 tls_ctx_restrict_ciphers_tls13(struct tls_root_ctx *ctx, const char *ciphers)
271 {
272     if (ciphers == NULL)
273     {
274         /* Nothing to do, return without warning message */
275         return;
276     }
277 
278     msg(M_WARN, "mbed TLS does not support setting tls-ciphersuites. "
279         "Ignoring TLS 1.3 cipher list: %s", ciphers);
280 }
281 
282 void
tls_ctx_restrict_ciphers(struct tls_root_ctx * ctx,const char * ciphers)283 tls_ctx_restrict_ciphers(struct tls_root_ctx *ctx, const char *ciphers)
284 {
285     char *tmp_ciphers, *tmp_ciphers_orig, *token;
286 
287     if (NULL == ciphers)
288     {
289         return; /* Nothing to do */
290     }
291 
292     ASSERT(NULL != ctx);
293 
294     /* Get number of ciphers */
295     int cipher_count = get_num_elements(ciphers, ':');
296 
297     /* Allocate an array for them */
298     ALLOC_ARRAY_CLEAR(ctx->allowed_ciphers, int, cipher_count+1)
299 
300     /* Parse allowed ciphers, getting IDs */
301     int i = 0;
302     tmp_ciphers_orig = tmp_ciphers = string_alloc(ciphers, NULL);
303 
304     token = strtok(tmp_ciphers, ":");
305     while (token)
306     {
307         ctx->allowed_ciphers[i] = mbedtls_ssl_get_ciphersuite_id(
308             tls_translate_cipher_name(token));
309         if (0 != ctx->allowed_ciphers[i])
310         {
311             i++;
312         }
313         token = strtok(NULL, ":");
314     }
315     free(tmp_ciphers_orig);
316 }
317 
318 void
tls_ctx_set_cert_profile(struct tls_root_ctx * ctx,const char * profile)319 tls_ctx_set_cert_profile(struct tls_root_ctx *ctx, const char *profile)
320 {
321     if (!profile || 0 == strcmp(profile, "legacy"))
322     {
323         ctx->cert_profile = openvpn_x509_crt_profile_legacy;
324     }
325     else if (0 == strcmp(profile, "preferred"))
326     {
327         ctx->cert_profile = openvpn_x509_crt_profile_preferred;
328     }
329     else if (0 == strcmp(profile, "suiteb"))
330     {
331         ctx->cert_profile = openvpn_x509_crt_profile_suiteb;
332     }
333     else
334     {
335         msg(M_FATAL, "ERROR: Invalid cert profile: %s", profile);
336     }
337 }
338 
339 void
tls_ctx_set_tls_groups(struct tls_root_ctx * ctx,const char * groups)340 tls_ctx_set_tls_groups(struct tls_root_ctx *ctx, const char *groups)
341 {
342     ASSERT(ctx);
343     struct gc_arena gc = gc_new();
344 
345     /* Get number of groups and allocate an array in ctx */
346     int groups_count = get_num_elements(groups, ':');
347     ALLOC_ARRAY_CLEAR(ctx->groups, mbedtls_ecp_group_id, groups_count + 1)
348 
349     /* Parse allowed ciphers, getting IDs */
350     int i = 0;
351     char *tmp_groups = string_alloc(groups, &gc);
352 
353     const char *token;
354     while ((token = strsep(&tmp_groups, ":")))
355     {
356         const mbedtls_ecp_curve_info *ci =
357             mbedtls_ecp_curve_info_from_name(token);
358         if (!ci)
359         {
360             msg(M_WARN, "Warning unknown curve/group specified: %s", token);
361         }
362         else
363         {
364             ctx->groups[i] = ci->grp_id;
365             i++;
366         }
367     }
368     ctx->groups[i] = MBEDTLS_ECP_DP_NONE;
369 
370     gc_free(&gc);
371 }
372 
373 
374 void
tls_ctx_check_cert_time(const struct tls_root_ctx * ctx)375 tls_ctx_check_cert_time(const struct tls_root_ctx *ctx)
376 {
377     ASSERT(ctx);
378     if (ctx->crt_chain == NULL)
379     {
380         return; /* Nothing to check if there is no certificate */
381     }
382 
383     if (mbedtls_x509_time_is_future(&ctx->crt_chain->valid_from))
384     {
385         msg(M_WARN, "WARNING: Your certificate is not yet valid!");
386     }
387 
388     if (mbedtls_x509_time_is_past(&ctx->crt_chain->valid_to))
389     {
390         msg(M_WARN, "WARNING: Your certificate has expired!");
391     }
392 }
393 
394 void
tls_ctx_load_dh_params(struct tls_root_ctx * ctx,const char * dh_file,bool dh_inline)395 tls_ctx_load_dh_params(struct tls_root_ctx *ctx, const char *dh_file,
396                        bool dh_inline)
397 {
398     if (dh_inline)
399     {
400         if (!mbed_ok(mbedtls_dhm_parse_dhm(ctx->dhm_ctx,
401                                            (const unsigned char *) dh_file,
402                                            strlen(dh_file) + 1)))
403         {
404             msg(M_FATAL, "Cannot read inline DH parameters");
405         }
406     }
407     else
408     {
409         if (!mbed_ok(mbedtls_dhm_parse_dhmfile(ctx->dhm_ctx, dh_file)))
410         {
411             msg(M_FATAL, "Cannot read DH parameters from file %s", dh_file);
412         }
413     }
414 
415     msg(D_TLS_DEBUG_LOW, "Diffie-Hellman initialized with " counter_format " bit key",
416         (counter_type) 8 * mbedtls_mpi_size(&ctx->dhm_ctx->P));
417 }
418 
419 void
tls_ctx_load_ecdh_params(struct tls_root_ctx * ctx,const char * curve_name)420 tls_ctx_load_ecdh_params(struct tls_root_ctx *ctx, const char *curve_name
421                          )
422 {
423     if (NULL != curve_name)
424     {
425         msg(M_WARN, "WARNING: mbed TLS builds do not support specifying an ECDH "
426             "curve, using default curves.");
427     }
428 }
429 
430 int
tls_ctx_load_pkcs12(struct tls_root_ctx * ctx,const char * pkcs12_file,bool pkcs12_file_inline,bool load_ca_file)431 tls_ctx_load_pkcs12(struct tls_root_ctx *ctx, const char *pkcs12_file,
432                     bool pkcs12_file_inline, bool load_ca_file)
433 {
434     msg(M_FATAL, "PKCS #12 files not yet supported for mbed TLS.");
435     return 0;
436 }
437 
438 #ifdef ENABLE_CRYPTOAPI
439 void
tls_ctx_load_cryptoapi(struct tls_root_ctx * ctx,const char * cryptoapi_cert)440 tls_ctx_load_cryptoapi(struct tls_root_ctx *ctx, const char *cryptoapi_cert)
441 {
442     msg(M_FATAL, "Windows CryptoAPI not yet supported for mbed TLS.");
443 }
444 #endif /* _WIN32 */
445 
446 void
tls_ctx_load_cert_file(struct tls_root_ctx * ctx,const char * cert_file,bool cert_inline)447 tls_ctx_load_cert_file(struct tls_root_ctx *ctx, const char *cert_file,
448                        bool cert_inline)
449 {
450     ASSERT(NULL != ctx);
451 
452     if (!ctx->crt_chain)
453     {
454         ALLOC_OBJ_CLEAR(ctx->crt_chain, mbedtls_x509_crt);
455     }
456 
457     if (cert_inline)
458     {
459         if (!mbed_ok(mbedtls_x509_crt_parse(ctx->crt_chain,
460                                             (const unsigned char *)cert_file,
461                                             strlen(cert_file) + 1)))
462         {
463             msg(M_FATAL, "Cannot load inline certificate file");
464         }
465     }
466     else
467     {
468         if (!mbed_ok(mbedtls_x509_crt_parse_file(ctx->crt_chain, cert_file)))
469         {
470             msg(M_FATAL, "Cannot load certificate file %s", cert_file);
471         }
472     }
473 }
474 
475 int
tls_ctx_load_priv_file(struct tls_root_ctx * ctx,const char * priv_key_file,bool priv_key_inline)476 tls_ctx_load_priv_file(struct tls_root_ctx *ctx, const char *priv_key_file,
477                        bool priv_key_inline)
478 {
479     int status;
480     ASSERT(NULL != ctx);
481 
482     if (!ctx->priv_key)
483     {
484         ALLOC_OBJ_CLEAR(ctx->priv_key, mbedtls_pk_context);
485     }
486 
487     if (priv_key_inline)
488     {
489         status = mbedtls_pk_parse_key(ctx->priv_key,
490                                       (const unsigned char *) priv_key_file,
491                                       strlen(priv_key_file) + 1, NULL, 0);
492 
493         if (MBEDTLS_ERR_PK_PASSWORD_REQUIRED == status)
494         {
495             char passbuf[512] = {0};
496             pem_password_callback(passbuf, 512, 0, NULL);
497             status = mbedtls_pk_parse_key(ctx->priv_key,
498                                           (const unsigned char *) priv_key_file,
499                                           strlen(priv_key_file) + 1,
500                                           (unsigned char *) passbuf,
501                                           strlen(passbuf));
502         }
503     }
504     else
505     {
506         status = mbedtls_pk_parse_keyfile(ctx->priv_key, priv_key_file, NULL);
507         if (MBEDTLS_ERR_PK_PASSWORD_REQUIRED == status)
508         {
509             char passbuf[512] = {0};
510             pem_password_callback(passbuf, 512, 0, NULL);
511             status = mbedtls_pk_parse_keyfile(ctx->priv_key, priv_key_file, passbuf);
512         }
513     }
514     if (!mbed_ok(status))
515     {
516 #ifdef ENABLE_MANAGEMENT
517         if (management && (MBEDTLS_ERR_PK_PASSWORD_MISMATCH == status))
518         {
519             management_auth_failure(management, UP_TYPE_PRIVATE_KEY, NULL);
520         }
521 #endif
522         msg(M_WARN, "Cannot load private key file %s",
523             print_key_filename(priv_key_file, priv_key_inline));
524         return 1;
525     }
526 
527     if (!mbed_ok(mbedtls_pk_check_pair(&ctx->crt_chain->pk, ctx->priv_key)))
528     {
529         msg(M_WARN, "Private key does not match the certificate");
530         return 1;
531     }
532 
533     return 0;
534 }
535 
536 /**
537  * external_pkcs1_sign implements a mbed TLS rsa_sign_func callback, that uses
538  * the management interface to request an RSA signature for the supplied hash.
539  *
540  * @param ctx_voidptr   Management external key context.
541  * @param f_rng         (Unused)
542  * @param p_rng         (Unused)
543  * @param mode          RSA mode (should be RSA_PRIVATE).
544  * @param md_alg        Message digest ('hash') algorithm type.
545  * @param hashlen       Length of hash (overridden by length specified by md_alg
546  *                      if md_alg != MBEDTLS_MD_NONE).
547  * @param hash          The digest ('hash') to sign. Should have a size
548  *                      matching the length of md_alg (if != MBEDTLS_MD_NONE),
549  *                      or hashlen otherwise.
550  * @param sig           Buffer that returns the signature. Should be at least of
551  *                      size ctx->signature_length.
552  *
553  * @return 0 on success, non-zero mbed TLS error code on failure.
554  */
555 static inline int
external_pkcs1_sign(void * ctx_voidptr,int (* f_rng)(void *,unsigned char *,size_t),void * p_rng,int mode,mbedtls_md_type_t md_alg,unsigned int hashlen,const unsigned char * hash,unsigned char * sig)556 external_pkcs1_sign( void *ctx_voidptr,
557                      int (*f_rng)(void *, unsigned char *, size_t), void *p_rng, int mode,
558                      mbedtls_md_type_t md_alg, unsigned int hashlen, const unsigned char *hash,
559                      unsigned char *sig )
560 {
561     struct external_context *const ctx = ctx_voidptr;
562     int rv;
563     uint8_t *to_sign = NULL;
564     size_t asn_len = 0, oid_size = 0;
565     const char *oid = NULL;
566 
567     if (NULL == ctx)
568     {
569         return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
570     }
571 
572     if (MBEDTLS_RSA_PRIVATE != mode)
573     {
574         return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
575     }
576 
577     /*
578      * Support a wide range of hashes. TLSv1.1 and before only need SIG_RSA_RAW,
579      * but TLSv1.2 needs the full suite of hashes.
580      *
581      * This code has been taken from mbed TLS pkcs11_sign(), under the GPLv2.0+.
582      */
583     if (md_alg != MBEDTLS_MD_NONE)
584     {
585         const mbedtls_md_info_t *md_info = mbedtls_md_info_from_type( md_alg );
586         if (md_info == NULL)
587         {
588             return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
589         }
590 
591         if (!mbed_ok(mbedtls_oid_get_oid_by_md( md_alg, &oid, &oid_size )))
592         {
593             return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
594         }
595 
596         hashlen = mbedtls_md_get_size( md_info );
597         asn_len = 10 + oid_size;
598     }
599 
600     if ((SIZE_MAX - hashlen) < asn_len
601         || ctx->signature_length < (asn_len + hashlen))
602     {
603         return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
604     }
605 
606     ALLOC_ARRAY_CLEAR(to_sign, uint8_t, asn_len + hashlen);
607     uint8_t *p = to_sign;
608     if (md_alg != MBEDTLS_MD_NONE)
609     {
610         /*
611          * DigestInfo ::= SEQUENCE {
612          *   digestAlgorithm DigestAlgorithmIdentifier,
613          *   digest Digest }
614          *
615          * DigestAlgorithmIdentifier ::= AlgorithmIdentifier
616          *
617          * Digest ::= OCTET STRING
618          */
619         *p++ = MBEDTLS_ASN1_SEQUENCE | MBEDTLS_ASN1_CONSTRUCTED;
620         *p++ = (unsigned char) ( 0x08 + oid_size + hashlen );
621         *p++ = MBEDTLS_ASN1_SEQUENCE | MBEDTLS_ASN1_CONSTRUCTED;
622         *p++ = (unsigned char) ( 0x04 + oid_size );
623         *p++ = MBEDTLS_ASN1_OID;
624         *p++ = oid_size & 0xFF;
625         memcpy( p, oid, oid_size );
626         p += oid_size;
627         *p++ = MBEDTLS_ASN1_NULL;
628         *p++ = 0x00;
629         *p++ = MBEDTLS_ASN1_OCTET_STRING;
630         *p++ = hashlen;
631 
632         /* Double-check ASN length */
633         ASSERT(asn_len == p - to_sign);
634     }
635 
636     /* Copy the hash to be signed */
637     memcpy(p, hash, hashlen);
638 
639     /* Call external signature function */
640     if (!ctx->sign(ctx->sign_ctx, to_sign, asn_len + hashlen, sig,
641                    ctx->signature_length))
642     {
643         rv = MBEDTLS_ERR_RSA_PRIVATE_FAILED;
644         goto done;
645     }
646 
647     rv = 0;
648 
649 done:
650     free(to_sign);
651     return rv;
652 }
653 
654 static inline size_t
external_key_len(void * vctx)655 external_key_len(void *vctx)
656 {
657     struct external_context *const ctx = vctx;
658 
659     return ctx->signature_length;
660 }
661 
662 int
tls_ctx_use_external_signing_func(struct tls_root_ctx * ctx,external_sign_func sign_func,void * sign_ctx)663 tls_ctx_use_external_signing_func(struct tls_root_ctx *ctx,
664                                   external_sign_func sign_func, void *sign_ctx)
665 {
666     ASSERT(NULL != ctx);
667 
668     if (ctx->crt_chain == NULL)
669     {
670         msg(M_WARN, "ERROR: external key requires a certificate.");
671         return 1;
672     }
673 
674     if (mbedtls_pk_get_type(&ctx->crt_chain->pk) != MBEDTLS_PK_RSA)
675     {
676         msg(M_WARN, "ERROR: external key with mbed TLS requires a "
677             "certificate with an RSA key.");
678         return 1;
679     }
680 
681     ctx->external_key.signature_length = mbedtls_pk_get_len(&ctx->crt_chain->pk);
682     ctx->external_key.sign = sign_func;
683     ctx->external_key.sign_ctx = sign_ctx;
684 
685     ALLOC_OBJ_CLEAR(ctx->priv_key, mbedtls_pk_context);
686     if (!mbed_ok(mbedtls_pk_setup_rsa_alt(ctx->priv_key, &ctx->external_key,
687                                           NULL, external_pkcs1_sign, external_key_len)))
688     {
689         return 1;
690     }
691 
692     return 0;
693 }
694 
695 #ifdef ENABLE_MANAGEMENT
696 /** Query the management interface for a signature, see external_sign_func. */
697 static bool
management_sign_func(void * sign_ctx,const void * src,size_t src_len,void * dst,size_t dst_len)698 management_sign_func(void *sign_ctx, const void *src, size_t src_len,
699                      void *dst, size_t dst_len)
700 {
701     bool ret = false;
702     char *src_b64 = NULL;
703     char *dst_b64 = NULL;
704 
705     if (!management || (openvpn_base64_encode(src, src_len, &src_b64) <= 0))
706     {
707         goto cleanup;
708     }
709 
710     /*
711      * We only support RSA external keys and PKCS1 signatures at the moment
712      * in mbed TLS, so the signature parameter is hardcoded to this encoding
713      */
714     if (!(dst_b64 = management_query_pk_sig(management, src_b64,
715                                             "RSA_PKCS1_PADDING")))
716     {
717         goto cleanup;
718     }
719 
720     if (openvpn_base64_decode(dst_b64, dst, dst_len) != dst_len)
721     {
722         goto cleanup;
723     }
724 
725     ret = true;
726 cleanup:
727     free(src_b64);
728     free(dst_b64);
729 
730     return ret;
731 }
732 
733 int
tls_ctx_use_management_external_key(struct tls_root_ctx * ctx)734 tls_ctx_use_management_external_key(struct tls_root_ctx *ctx)
735 {
736     return tls_ctx_use_external_signing_func(ctx, management_sign_func, NULL);
737 }
738 
739 #endif /* ifdef ENABLE_MANAGEMENT */
740 
741 void
tls_ctx_load_ca(struct tls_root_ctx * ctx,const char * ca_file,bool ca_inline,const char * ca_path,bool tls_server)742 tls_ctx_load_ca(struct tls_root_ctx *ctx, const char *ca_file,
743                 bool ca_inline, const char *ca_path, bool tls_server)
744 {
745     if (ca_path)
746     {
747         msg(M_FATAL, "ERROR: mbed TLS cannot handle the capath directive");
748     }
749 
750     if (ca_file && ca_inline)
751     {
752         if (!mbed_ok(mbedtls_x509_crt_parse(ctx->ca_chain,
753                                             (const unsigned char *) ca_file,
754                                             strlen(ca_file) + 1)))
755         {
756             msg(M_FATAL, "Cannot load inline CA certificates");
757         }
758     }
759     else
760     {
761         /* Load CA file for verifying peer supplied certificate */
762         if (!mbed_ok(mbedtls_x509_crt_parse_file(ctx->ca_chain, ca_file)))
763         {
764             msg(M_FATAL, "Cannot load CA certificate file %s", ca_file);
765         }
766     }
767 }
768 
769 void
tls_ctx_load_extra_certs(struct tls_root_ctx * ctx,const char * extra_certs_file,bool extra_certs_inline)770 tls_ctx_load_extra_certs(struct tls_root_ctx *ctx, const char *extra_certs_file,
771                          bool extra_certs_inline)
772 {
773     ASSERT(NULL != ctx);
774 
775     if (!ctx->crt_chain)
776     {
777         ALLOC_OBJ_CLEAR(ctx->crt_chain, mbedtls_x509_crt);
778     }
779 
780     if (extra_certs_inline)
781     {
782         if (!mbed_ok(mbedtls_x509_crt_parse(ctx->crt_chain,
783                                             (const unsigned char *) extra_certs_file,
784                                             strlen(extra_certs_file) + 1)))
785         {
786             msg(M_FATAL, "Cannot load inline extra-certs file");
787         }
788     }
789     else
790     {
791         if (!mbed_ok(mbedtls_x509_crt_parse_file(ctx->crt_chain, extra_certs_file)))
792         {
793             msg(M_FATAL, "Cannot load extra-certs file: %s", extra_certs_file);
794         }
795     }
796 }
797 
798 /* **************************************
799  *
800  * Key-state specific functions
801  *
802  ***************************************/
803 
804 /*
805  * "Endless buffer"
806  */
807 
808 static inline void
buf_free_entry(buffer_entry * entry)809 buf_free_entry(buffer_entry *entry)
810 {
811     if (NULL != entry)
812     {
813         free(entry->data);
814         free(entry);
815     }
816 }
817 
818 static void
buf_free_entries(endless_buffer * buf)819 buf_free_entries(endless_buffer *buf)
820 {
821     while (buf->first_block)
822     {
823         buffer_entry *cur_block = buf->first_block;
824         buf->first_block = cur_block->next_block;
825         buf_free_entry(cur_block);
826     }
827     buf->last_block = NULL;
828 }
829 
830 static int
endless_buf_read(endless_buffer * in,unsigned char * out,size_t out_len)831 endless_buf_read( endless_buffer *in, unsigned char *out, size_t out_len )
832 {
833     size_t read_len = 0;
834 
835     if (in->first_block == NULL)
836     {
837         return MBEDTLS_ERR_SSL_WANT_READ;
838     }
839 
840     while (in->first_block != NULL && read_len < out_len)
841     {
842         int block_len = in->first_block->length - in->data_start;
843         if (block_len <= out_len - read_len)
844         {
845             buffer_entry *cur_entry = in->first_block;
846             memcpy(out + read_len, cur_entry->data + in->data_start,
847                    block_len);
848 
849             read_len += block_len;
850 
851             in->first_block = cur_entry->next_block;
852             in->data_start = 0;
853 
854             if (in->first_block == NULL)
855             {
856                 in->last_block = NULL;
857             }
858 
859             buf_free_entry(cur_entry);
860         }
861         else
862         {
863             memcpy(out + read_len, in->first_block->data + in->data_start,
864                    out_len - read_len);
865             in->data_start += out_len - read_len;
866             read_len = out_len;
867         }
868     }
869 
870     return read_len;
871 }
872 
873 static int
endless_buf_write(endless_buffer * out,const unsigned char * in,size_t len)874 endless_buf_write( endless_buffer *out, const unsigned char *in, size_t len )
875 {
876     buffer_entry *new_block = malloc(sizeof(buffer_entry));
877     if (NULL == new_block)
878     {
879         return MBEDTLS_ERR_NET_SEND_FAILED;
880     }
881 
882     new_block->data = malloc(len);
883     if (NULL == new_block->data)
884     {
885         free(new_block);
886         return MBEDTLS_ERR_NET_SEND_FAILED;
887     }
888 
889     new_block->length = len;
890     new_block->next_block = NULL;
891 
892     memcpy(new_block->data, in, len);
893 
894     if (NULL == out->first_block)
895     {
896         out->first_block = new_block;
897     }
898 
899     if (NULL != out->last_block)
900     {
901         out->last_block->next_block = new_block;
902     }
903 
904     out->last_block = new_block;
905 
906     return len;
907 }
908 
909 static int
ssl_bio_read(void * ctx,unsigned char * out,size_t out_len)910 ssl_bio_read( void *ctx, unsigned char *out, size_t out_len)
911 {
912     bio_ctx *my_ctx = (bio_ctx *) ctx;
913     return endless_buf_read(&my_ctx->in, out, out_len);
914 }
915 
916 static int
ssl_bio_write(void * ctx,const unsigned char * in,size_t in_len)917 ssl_bio_write( void *ctx, const unsigned char *in, size_t in_len)
918 {
919     bio_ctx *my_ctx = (bio_ctx *) ctx;
920     return endless_buf_write(&my_ctx->out, in, in_len);
921 }
922 
923 static void
my_debug(void * ctx,int level,const char * file,int line,const char * str)924 my_debug( void *ctx, int level, const char *file, int line,
925           const char *str )
926 {
927     int my_loglevel = (level < 3) ? D_TLS_DEBUG_MED : D_TLS_DEBUG;
928     msg(my_loglevel, "mbed TLS msg (%s:%d): %s", file, line, str);
929 }
930 
931 /*
932  * Further personalise the RNG using a hash of the public key
933  */
934 void
tls_ctx_personalise_random(struct tls_root_ctx * ctx)935 tls_ctx_personalise_random(struct tls_root_ctx *ctx)
936 {
937     static char old_sha256_hash[32] = {0};
938     unsigned char sha256_hash[32] = {0};
939     mbedtls_ctr_drbg_context *cd_ctx = rand_ctx_get();
940 
941     if (NULL != ctx->crt_chain)
942     {
943         const md_kt_t *sha256_kt = md_kt_get("SHA256");
944         mbedtls_x509_crt *cert = ctx->crt_chain;
945 
946         if (!md_full(sha256_kt, cert->tbs.p, cert->tbs.len, sha256_hash))
947         {
948             msg(M_WARN, "WARNING: failed to personalise random");
949         }
950 
951         if (0 != memcmp(old_sha256_hash, sha256_hash, sizeof(sha256_hash)))
952         {
953             mbedtls_ctr_drbg_update(cd_ctx, sha256_hash, 32);
954             memcpy(old_sha256_hash, sha256_hash, sizeof(old_sha256_hash));
955         }
956     }
957 }
958 
959 int
tls_version_max(void)960 tls_version_max(void)
961 {
962 #if defined(MBEDTLS_SSL_MAJOR_VERSION_3) && defined(MBEDTLS_SSL_MINOR_VERSION_3)
963     return TLS_VER_1_2;
964 #elif defined(MBEDTLS_SSL_MAJOR_VERSION_3) && defined(MBEDTLS_SSL_MINOR_VERSION_2)
965     return TLS_VER_1_1;
966 #else
967     return TLS_VER_1_0;
968 #endif
969 }
970 
971 /**
972  * Convert an OpenVPN tls-version variable to mbed TLS format (i.e. a major and
973  * minor ssl version number).
974  *
975  * @param tls_ver       The tls-version variable to convert.
976  * @param major         Returns the TLS major version in mbed TLS format.
977  *                      Must be a valid pointer.
978  * @param minor         Returns the TLS minor version in mbed TLS format.
979  *                      Must be a valid pointer.
980  */
981 static void
tls_version_to_major_minor(int tls_ver,int * major,int * minor)982 tls_version_to_major_minor(int tls_ver, int *major, int *minor)
983 {
984     ASSERT(major);
985     ASSERT(minor);
986 
987     switch (tls_ver)
988     {
989         case TLS_VER_1_0:
990             *major = MBEDTLS_SSL_MAJOR_VERSION_3;
991             *minor = MBEDTLS_SSL_MINOR_VERSION_1;
992             break;
993 
994         case TLS_VER_1_1:
995             *major = MBEDTLS_SSL_MAJOR_VERSION_3;
996             *minor = MBEDTLS_SSL_MINOR_VERSION_2;
997             break;
998 
999         case TLS_VER_1_2:
1000             *major = MBEDTLS_SSL_MAJOR_VERSION_3;
1001             *minor = MBEDTLS_SSL_MINOR_VERSION_3;
1002             break;
1003 
1004         default:
1005             msg(M_FATAL, "%s: invalid TLS version %d", __func__, tls_ver);
1006             break;
1007     }
1008 }
1009 
1010 void
backend_tls_ctx_reload_crl(struct tls_root_ctx * ctx,const char * crl_file,bool crl_inline)1011 backend_tls_ctx_reload_crl(struct tls_root_ctx *ctx, const char *crl_file,
1012                            bool crl_inline)
1013 {
1014     ASSERT(crl_file);
1015 
1016     if (ctx->crl == NULL)
1017     {
1018         ALLOC_OBJ_CLEAR(ctx->crl, mbedtls_x509_crl);
1019     }
1020     mbedtls_x509_crl_free(ctx->crl);
1021 
1022     if (crl_inline)
1023     {
1024         if (!mbed_ok(mbedtls_x509_crl_parse(ctx->crl,
1025                                             (const unsigned char *)crl_file,
1026                                             strlen(crl_file) + 1)))
1027         {
1028             msg(M_WARN, "CRL: cannot parse inline CRL");
1029             goto err;
1030         }
1031     }
1032     else
1033     {
1034         if (!mbed_ok(mbedtls_x509_crl_parse_file(ctx->crl, crl_file)))
1035         {
1036             msg(M_WARN, "CRL: cannot read CRL from file %s", crl_file);
1037             goto err;
1038         }
1039     }
1040     return;
1041 
1042 err:
1043     mbedtls_x509_crl_free(ctx->crl);
1044 }
1045 
1046 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)1047 key_state_ssl_init(struct key_state_ssl *ks_ssl,
1048                    const struct tls_root_ctx *ssl_ctx, bool is_server,
1049                    struct tls_session *session)
1050 {
1051     ASSERT(NULL != ssl_ctx);
1052     ASSERT(ks_ssl);
1053     CLEAR(*ks_ssl);
1054 
1055     /* Initialise SSL config */
1056     ALLOC_OBJ_CLEAR(ks_ssl->ssl_config, mbedtls_ssl_config);
1057     mbedtls_ssl_config_init(ks_ssl->ssl_config);
1058     mbedtls_ssl_config_defaults(ks_ssl->ssl_config, ssl_ctx->endpoint,
1059                                 MBEDTLS_SSL_TRANSPORT_STREAM, MBEDTLS_SSL_PRESET_DEFAULT);
1060 #ifdef MBEDTLS_DEBUG_C
1061     /* We only want to have mbed TLS generate debug level logging when we would
1062      * also display it.
1063      * In fact mbed TLS 2.25.0 crashes generating debug log if Curve25591 is
1064      * selected for DH (https://github.com/ARMmbed/mbedtls/issues/4208) */
1065     if (session->opt->ssl_flags & SSLF_TLS_DEBUG_ENABLED)
1066     {
1067         mbedtls_debug_set_threshold(3);
1068     }
1069     else
1070     {
1071         mbedtls_debug_set_threshold(2);
1072     }
1073 #endif
1074     mbedtls_ssl_conf_dbg(ks_ssl->ssl_config, my_debug, NULL);
1075     mbedtls_ssl_conf_rng(ks_ssl->ssl_config, mbedtls_ctr_drbg_random,
1076                          rand_ctx_get());
1077 
1078     mbedtls_ssl_conf_cert_profile(ks_ssl->ssl_config, &ssl_ctx->cert_profile);
1079 
1080     if (ssl_ctx->allowed_ciphers)
1081     {
1082         mbedtls_ssl_conf_ciphersuites(ks_ssl->ssl_config, ssl_ctx->allowed_ciphers);
1083     }
1084 
1085     if (ssl_ctx->groups)
1086     {
1087         mbedtls_ssl_conf_curves(ks_ssl->ssl_config, ssl_ctx->groups);
1088     }
1089 
1090     /* Disable TLS renegotiations if the mbedtls library supports that feature.
1091      * OpenVPN's renegotiation creates new SSL sessions and does not depend on
1092      * this feature and TLS renegotiations have been problematic in the past. */
1093 #if defined(MBEDTLS_SSL_RENEGOTIATION)
1094     mbedtls_ssl_conf_renegotiation(ks_ssl->ssl_config, MBEDTLS_SSL_RENEGOTIATION_DISABLED);
1095 #endif /* MBEDTLS_SSL_RENEGOTIATION */
1096 
1097     /* Disable record splitting (for now).  OpenVPN assumes records are sent
1098      * unfragmented, and changing that will require thorough review and
1099      * testing.  Since OpenVPN is not susceptible to BEAST, we can just
1100      * disable record splitting as a quick fix. */
1101 #if defined(MBEDTLS_SSL_CBC_RECORD_SPLITTING)
1102     mbedtls_ssl_conf_cbc_record_splitting(ks_ssl->ssl_config,
1103                                           MBEDTLS_SSL_CBC_RECORD_SPLITTING_DISABLED);
1104 #endif /* MBEDTLS_SSL_CBC_RECORD_SPLITTING */
1105 
1106     /* Initialise authentication information */
1107     if (is_server)
1108     {
1109         mbed_ok(mbedtls_ssl_conf_dh_param_ctx(ks_ssl->ssl_config,
1110                                               ssl_ctx->dhm_ctx));
1111     }
1112 
1113     mbed_ok(mbedtls_ssl_conf_own_cert(ks_ssl->ssl_config, ssl_ctx->crt_chain,
1114                                       ssl_ctx->priv_key));
1115 
1116     /* Initialise SSL verification */
1117     if (session->opt->ssl_flags & SSLF_CLIENT_CERT_OPTIONAL)
1118     {
1119         mbedtls_ssl_conf_authmode(ks_ssl->ssl_config, MBEDTLS_SSL_VERIFY_OPTIONAL);
1120     }
1121     else if (!(session->opt->ssl_flags & SSLF_CLIENT_CERT_NOT_REQUIRED))
1122     {
1123         mbedtls_ssl_conf_authmode(ks_ssl->ssl_config, MBEDTLS_SSL_VERIFY_REQUIRED);
1124     }
1125     mbedtls_ssl_conf_verify(ks_ssl->ssl_config, verify_callback, session);
1126 
1127     /* TODO: mbed TLS does not currently support sending the CA chain to the client */
1128     mbedtls_ssl_conf_ca_chain(ks_ssl->ssl_config, ssl_ctx->ca_chain, ssl_ctx->crl);
1129 
1130     /* Initialize minimum TLS version */
1131     {
1132         const int tls_version_min =
1133             (session->opt->ssl_flags >> SSLF_TLS_VERSION_MIN_SHIFT)
1134             &SSLF_TLS_VERSION_MIN_MASK;
1135 
1136         /* default to TLS 1.0 */
1137         int major = MBEDTLS_SSL_MAJOR_VERSION_3;
1138         int minor = MBEDTLS_SSL_MINOR_VERSION_1;
1139 
1140         if (tls_version_min > TLS_VER_UNSPEC)
1141         {
1142             tls_version_to_major_minor(tls_version_min, &major, &minor);
1143         }
1144 
1145         mbedtls_ssl_conf_min_version(ks_ssl->ssl_config, major, minor);
1146     }
1147 
1148     /* Initialize maximum TLS version */
1149     {
1150         const int tls_version_max =
1151             (session->opt->ssl_flags >> SSLF_TLS_VERSION_MAX_SHIFT)
1152             &SSLF_TLS_VERSION_MAX_MASK;
1153 
1154         if (tls_version_max > TLS_VER_UNSPEC)
1155         {
1156             int major, minor;
1157             tls_version_to_major_minor(tls_version_max, &major, &minor);
1158             mbedtls_ssl_conf_max_version(ks_ssl->ssl_config, major, minor);
1159         }
1160     }
1161 
1162 #ifdef HAVE_EXPORT_KEYING_MATERIAL
1163     /* Initialize keying material exporter */
1164     mbedtls_ssl_conf_export_keys_ext_cb(ks_ssl->ssl_config,
1165                                         mbedtls_ssl_export_keys_cb, session);
1166 #endif
1167 
1168     /* Initialise SSL context */
1169     ALLOC_OBJ_CLEAR(ks_ssl->ctx, mbedtls_ssl_context);
1170     mbedtls_ssl_init(ks_ssl->ctx);
1171     mbedtls_ssl_setup(ks_ssl->ctx, ks_ssl->ssl_config);
1172 
1173     /* Initialise BIOs */
1174     ALLOC_OBJ_CLEAR(ks_ssl->bio_ctx, bio_ctx);
1175     mbedtls_ssl_set_bio(ks_ssl->ctx, ks_ssl->bio_ctx, ssl_bio_write,
1176                         ssl_bio_read, NULL);
1177 }
1178 
1179 void
key_state_ssl_free(struct key_state_ssl * ks_ssl)1180 key_state_ssl_free(struct key_state_ssl *ks_ssl)
1181 {
1182     if (ks_ssl)
1183     {
1184         CLEAR(ks_ssl->tls_key_cache);
1185 
1186         if (ks_ssl->ctx)
1187         {
1188             mbedtls_ssl_free(ks_ssl->ctx);
1189             free(ks_ssl->ctx);
1190         }
1191         if (ks_ssl->ssl_config)
1192         {
1193             mbedtls_ssl_config_free(ks_ssl->ssl_config);
1194             free(ks_ssl->ssl_config);
1195         }
1196         if (ks_ssl->bio_ctx)
1197         {
1198             buf_free_entries(&ks_ssl->bio_ctx->in);
1199             buf_free_entries(&ks_ssl->bio_ctx->out);
1200             free(ks_ssl->bio_ctx);
1201         }
1202         CLEAR(*ks_ssl);
1203     }
1204 }
1205 
1206 int
key_state_write_plaintext(struct key_state_ssl * ks,struct buffer * buf)1207 key_state_write_plaintext(struct key_state_ssl *ks, struct buffer *buf)
1208 {
1209     int retval = 0;
1210 
1211     ASSERT(buf);
1212 
1213     retval = key_state_write_plaintext_const(ks, BPTR(buf), BLEN(buf));
1214 
1215     if (1 == retval)
1216     {
1217         memset(BPTR(buf), 0, BLEN(buf));  /* erase data just written */
1218         buf->len = 0;
1219     }
1220 
1221     return retval;
1222 }
1223 
1224 int
key_state_write_plaintext_const(struct key_state_ssl * ks,const uint8_t * data,int len)1225 key_state_write_plaintext_const(struct key_state_ssl *ks, const uint8_t *data, int len)
1226 {
1227     int retval = 0;
1228     perf_push(PERF_BIO_WRITE_PLAINTEXT);
1229 
1230     ASSERT(NULL != ks);
1231     ASSERT(len >= 0);
1232 
1233     if (0 == len)
1234     {
1235         perf_pop();
1236         return 0;
1237     }
1238 
1239     ASSERT(data);
1240 
1241     retval = mbedtls_ssl_write(ks->ctx, data, len);
1242 
1243     if (retval < 0)
1244     {
1245         perf_pop();
1246         if (MBEDTLS_ERR_SSL_WANT_WRITE == retval || MBEDTLS_ERR_SSL_WANT_READ == retval)
1247         {
1248             return 0;
1249         }
1250         mbed_log_err(D_TLS_ERRORS, retval,
1251                      "TLS ERROR: write tls_write_plaintext_const error");
1252         return -1;
1253     }
1254 
1255     if (retval != len)
1256     {
1257         msg(D_TLS_ERRORS,
1258             "TLS ERROR: write tls_write_plaintext_const incomplete %d/%d",
1259             retval, len);
1260         perf_pop();
1261         return -1;
1262     }
1263 
1264     /* successful write */
1265     dmsg(D_HANDSHAKE_VERBOSE, "write tls_write_plaintext_const %d bytes", retval);
1266 
1267     perf_pop();
1268     return 1;
1269 }
1270 
1271 int
key_state_read_ciphertext(struct key_state_ssl * ks,struct buffer * buf,int maxlen)1272 key_state_read_ciphertext(struct key_state_ssl *ks, struct buffer *buf,
1273                           int maxlen)
1274 {
1275     int retval = 0;
1276     int len = 0;
1277 
1278     perf_push(PERF_BIO_READ_CIPHERTEXT);
1279 
1280     ASSERT(NULL != ks);
1281     ASSERT(buf);
1282     ASSERT(buf->len >= 0);
1283 
1284     if (buf->len)
1285     {
1286         perf_pop();
1287         return 0;
1288     }
1289 
1290     len = buf_forward_capacity(buf);
1291     if (maxlen < len)
1292     {
1293         len = maxlen;
1294     }
1295 
1296     retval = endless_buf_read(&ks->bio_ctx->out, BPTR(buf), len);
1297 
1298     /* Error during read, check for retry error */
1299     if (retval < 0)
1300     {
1301         perf_pop();
1302         if (MBEDTLS_ERR_SSL_WANT_WRITE == retval || MBEDTLS_ERR_SSL_WANT_READ == retval)
1303         {
1304             return 0;
1305         }
1306         mbed_log_err(D_TLS_ERRORS, retval, "TLS_ERROR: read tls_read_ciphertext error");
1307         buf->len = 0;
1308         return -1;
1309     }
1310     /* Nothing read, try again */
1311     if (0 == retval)
1312     {
1313         buf->len = 0;
1314         perf_pop();
1315         return 0;
1316     }
1317 
1318     /* successful read */
1319     dmsg(D_HANDSHAKE_VERBOSE, "read tls_read_ciphertext %d bytes", retval);
1320     buf->len = retval;
1321     perf_pop();
1322     return 1;
1323 }
1324 
1325 int
key_state_write_ciphertext(struct key_state_ssl * ks,struct buffer * buf)1326 key_state_write_ciphertext(struct key_state_ssl *ks, struct buffer *buf)
1327 {
1328     int retval = 0;
1329     perf_push(PERF_BIO_WRITE_CIPHERTEXT);
1330 
1331     ASSERT(NULL != ks);
1332     ASSERT(buf);
1333     ASSERT(buf->len >= 0);
1334 
1335     if (0 == buf->len)
1336     {
1337         perf_pop();
1338         return 0;
1339     }
1340 
1341     retval = endless_buf_write(&ks->bio_ctx->in, BPTR(buf), buf->len);
1342 
1343     if (retval < 0)
1344     {
1345         perf_pop();
1346 
1347         if (MBEDTLS_ERR_SSL_WANT_WRITE == retval || MBEDTLS_ERR_SSL_WANT_READ == retval)
1348         {
1349             return 0;
1350         }
1351         mbed_log_err(D_TLS_ERRORS, retval,
1352                      "TLS ERROR: write tls_write_ciphertext error");
1353         return -1;
1354     }
1355 
1356     if (retval != buf->len)
1357     {
1358         msg(D_TLS_ERRORS, "TLS ERROR: write tls_write_ciphertext incomplete %d/%d",
1359             retval, buf->len);
1360         perf_pop();
1361         return -1;
1362     }
1363 
1364     /* successful write */
1365     dmsg(D_HANDSHAKE_VERBOSE, "write tls_write_ciphertext %d bytes", retval);
1366 
1367     memset(BPTR(buf), 0, BLEN(buf));  /* erase data just written */
1368     buf->len = 0;
1369 
1370     perf_pop();
1371     return 1;
1372 }
1373 
1374 int
key_state_read_plaintext(struct key_state_ssl * ks,struct buffer * buf,int maxlen)1375 key_state_read_plaintext(struct key_state_ssl *ks, struct buffer *buf,
1376                          int maxlen)
1377 {
1378     int retval = 0;
1379     int len = 0;
1380 
1381     perf_push(PERF_BIO_READ_PLAINTEXT);
1382 
1383     ASSERT(NULL != ks);
1384     ASSERT(buf);
1385     ASSERT(buf->len >= 0);
1386 
1387     if (buf->len)
1388     {
1389         perf_pop();
1390         return 0;
1391     }
1392 
1393     len = buf_forward_capacity(buf);
1394     if (maxlen < len)
1395     {
1396         len = maxlen;
1397     }
1398 
1399     retval = mbedtls_ssl_read(ks->ctx, BPTR(buf), len);
1400 
1401     /* Error during read, check for retry error */
1402     if (retval < 0)
1403     {
1404         if (MBEDTLS_ERR_SSL_WANT_WRITE == retval || MBEDTLS_ERR_SSL_WANT_READ == retval)
1405         {
1406             return 0;
1407         }
1408         mbed_log_err(D_TLS_ERRORS, retval, "TLS_ERROR: read tls_read_plaintext error");
1409         buf->len = 0;
1410         perf_pop();
1411         return -1;
1412     }
1413     /* Nothing read, try again */
1414     if (0 == retval)
1415     {
1416         buf->len = 0;
1417         perf_pop();
1418         return 0;
1419     }
1420 
1421     /* successful read */
1422     dmsg(D_HANDSHAKE_VERBOSE, "read tls_read_plaintext %d bytes", retval);
1423     buf->len = retval;
1424 
1425     perf_pop();
1426     return 1;
1427 }
1428 
1429 /* **************************************
1430  *
1431  * Information functions
1432  *
1433  * Print information for the end user.
1434  *
1435  ***************************************/
1436 void
print_details(struct key_state_ssl * ks_ssl,const char * prefix)1437 print_details(struct key_state_ssl *ks_ssl, const char *prefix)
1438 {
1439     const mbedtls_x509_crt *cert;
1440     char s1[256];
1441     char s2[256];
1442 
1443     s1[0] = s2[0] = 0;
1444     openvpn_snprintf(s1, sizeof(s1), "%s %s, cipher %s",
1445                      prefix,
1446                      mbedtls_ssl_get_version(ks_ssl->ctx),
1447                      mbedtls_ssl_get_ciphersuite(ks_ssl->ctx));
1448 
1449     cert = mbedtls_ssl_get_peer_cert(ks_ssl->ctx);
1450     if (cert != NULL)
1451     {
1452         openvpn_snprintf(s2, sizeof(s2), ", %u bit key",
1453                          (unsigned int) mbedtls_pk_get_bitlen(&cert->pk));
1454     }
1455 
1456     msg(D_HANDSHAKE, "%s%s", s1, s2);
1457 }
1458 
1459 void
show_available_tls_ciphers_list(const char * cipher_list,const char * tls_cert_profile,bool tls13)1460 show_available_tls_ciphers_list(const char *cipher_list,
1461                                 const char *tls_cert_profile,
1462                                 bool tls13)
1463 {
1464     if (tls13)
1465     {
1466         /* mbed TLS has no TLS 1.3 support currently */
1467         return;
1468     }
1469     struct tls_root_ctx tls_ctx;
1470     const int *ciphers = mbedtls_ssl_list_ciphersuites();
1471 
1472     tls_ctx_server_new(&tls_ctx);
1473     tls_ctx_set_cert_profile(&tls_ctx, tls_cert_profile);
1474     tls_ctx_restrict_ciphers(&tls_ctx, cipher_list);
1475 
1476     if (tls_ctx.allowed_ciphers)
1477     {
1478         ciphers = tls_ctx.allowed_ciphers;
1479     }
1480 
1481     while (*ciphers != 0)
1482     {
1483         printf("%s\n", mbedtls_ssl_get_ciphersuite_name(*ciphers));
1484         ciphers++;
1485     }
1486     tls_ctx_free(&tls_ctx);
1487 }
1488 
1489 void
show_available_curves(void)1490 show_available_curves(void)
1491 {
1492     const mbedtls_ecp_curve_info *pcurve = mbedtls_ecp_curve_list();
1493 
1494     if (NULL == pcurve)
1495     {
1496         msg(M_FATAL, "Cannot retrieve curve list from mbed TLS");
1497     }
1498 
1499     /* Print curve list */
1500     printf("Available Elliptic curves, listed in order of preference:\n\n");
1501     while (MBEDTLS_ECP_DP_NONE != pcurve->grp_id)
1502     {
1503         printf("%s\n", pcurve->name);
1504         pcurve++;
1505     }
1506 }
1507 
1508 void
get_highest_preference_tls_cipher(char * buf,int size)1509 get_highest_preference_tls_cipher(char *buf, int size)
1510 {
1511     const char *cipher_name;
1512     const int *ciphers = mbedtls_ssl_list_ciphersuites();
1513     if (*ciphers == 0)
1514     {
1515         msg(M_FATAL, "Cannot retrieve list of supported SSL ciphers.");
1516     }
1517 
1518     cipher_name = mbedtls_ssl_get_ciphersuite_name(*ciphers);
1519     strncpynt(buf, cipher_name, size);
1520 }
1521 
1522 const char *
get_ssl_library_version(void)1523 get_ssl_library_version(void)
1524 {
1525     static char mbedtls_version[30];
1526     unsigned int pv = mbedtls_version_get_number();
1527     sprintf( mbedtls_version, "mbed TLS %d.%d.%d",
1528              (pv>>24)&0xff, (pv>>16)&0xff, (pv>>8)&0xff );
1529     return mbedtls_version;
1530 }
1531 
1532 #endif /* defined(ENABLE_CRYPTO_MBEDTLS) */
1533