OpenVPN
ssl_verify_mbedtls.c
Go to the documentation of this file.
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-2025 OpenVPN Inc <sales@openvpn.net>
9 * Copyright (C) 2010-2021 Sentyron B.V. <openvpn@sentyron.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, see <https://www.gnu.org/licenses/>.
22 */
23
29#ifdef HAVE_CONFIG_H
30#include "config.h"
31#endif
32
33#include "syshead.h"
34
35#if defined(ENABLE_CRYPTO_MBEDTLS)
36
37#include "crypto_mbedtls.h"
38#include "mbedtls_compat.h"
39#include "ssl_verify.h"
40#include <mbedtls/asn1.h>
41#include <mbedtls/error.h>
42#include <mbedtls/bignum.h>
43#include <mbedtls/oid.h>
44#include <mbedtls/sha1.h>
45
46#define MAX_SUBJECT_LENGTH 256
47
48int
49verify_callback(void *session_obj, mbedtls_x509_crt *cert, int cert_depth, uint32_t *flags)
50{
51 struct tls_session *session = (struct tls_session *)session_obj;
52 struct gc_arena gc = gc_new();
53
54 ASSERT(cert);
56
57 session->verified = false;
58
59 /* Remember certificate hash */
62
63 if (session->opt->verify_hash_no_ca)
64 {
65 /*
66 * If we decide to verify the peer certificate based on the fingerprint
67 * we ignore wrong dates and the certificate not being trusted.
68 * Any other problem with the certificate (wrong key, bad cert,...)
69 * will still trigger an error.
70 * Clearing these flags relies on verify_cert will later rejecting a
71 * certificate that has no matching fingerprint.
72 */
75 *flags = *flags & ~flags_ignore;
76 }
77
78 /* did peer present cert which was signed by our root cert? */
79 if (*flags != 0)
80 {
81 int ret = 0;
82 char errstr[512] = { 0 };
83 char *subject = x509_get_subject(cert, &gc);
84 char *serial = backend_x509_get_serial(cert, &gc);
85
86 ret = mbedtls_x509_crt_verify_info(errstr, sizeof(errstr) - 1, "", *flags);
87 if (ret <= 0
88 && !snprintf(errstr, sizeof(errstr), "Could not retrieve error string, flags=%" PRIx32,
89 *flags))
90 {
91 errstr[0] = '\0';
92 }
93 else
94 {
96 }
97
98 if (subject)
99 {
100 msg(D_TLS_ERRORS, "VERIFY ERROR: depth=%d, subject=%s, serial=%s: %s", cert_depth,
101 subject, serial ? serial : "<not available>", errstr);
102 }
103 else
104 {
106 "VERIFY ERROR: depth=%d, (could not extract X509 "
107 "subject string from certificate): %s",
109 }
110
111 /* Leave flags set to non-zero to indicate that the cert is not ok */
112 }
113 else if (SUCCESS != verify_cert(session, cert, cert_depth))
114 {
116 }
117
118 gc_free(&gc);
119
120 /*
121 * PolarSSL/mbed TLS-1.2.0+ expects 0 on anything except fatal errors.
122 */
123 return 0;
124}
125
126#ifdef ENABLE_X509ALTUSERNAME
127#warning "X509 alt user name not yet supported for mbed TLS"
128#endif
129
131backend_x509_get_username(char *cn, size_t cn_len, char *x509_username_field, mbedtls_x509_crt *cert)
132{
133 mbedtls_x509_name *name;
134
135 ASSERT(cn != NULL);
136
137 name = &cert->subject;
138
139 /* Find common name */
140 while (name != NULL)
141 {
143 {
144 break;
145 }
146
147 name = name->next;
148 }
149
150 /* Not found, return an error if this is the peer's certificate */
151 if (name == NULL)
152 {
153 return FAILURE;
154 }
155
156 /* Found, extract CN */
157 if (cn_len > name->val.len)
158 {
159 memcpy(cn, name->val.p, name->val.len);
160 cn[name->val.len] = '\0';
161 }
162 else
163 {
164 memcpy(cn, name->val.p, cn_len);
165 cn[cn_len - 1] = '\0';
166 }
167
168 return SUCCESS;
169}
170
171char *
173{
174 char *buf = NULL;
175 size_t buflen = 0;
176 mbedtls_mpi serial_mpi = { 0 };
177
178 /* Transform asn1 integer serial into mbed TLS MPI */
180 if (!mbed_ok(mbedtls_mpi_read_binary(&serial_mpi, cert->serial.p, cert->serial.len)))
181 {
182 msg(M_WARN, "Failed to retrieve serial from certificate.");
183 goto end;
184 }
185
186 /* Determine decimal representation length, allocate buffer */
188 buf = gc_malloc(buflen, true, gc);
189
190 /* Write MPI serial as decimal string into buffer */
192 {
193 msg(M_WARN, "Failed to write serial to string.");
194 buf = NULL;
195 goto end;
196 }
197
198end:
200 return buf;
201}
202
203char *
205{
206 char *buf = NULL;
207 size_t len = cert->serial.len * 3 + 1;
208
209 buf = gc_malloc(len, true, gc);
210
211 if (mbedtls_x509_serial_gets(buf, len - 1, &cert->serial) < 0)
212 {
213 buf = NULL;
214 }
215
216 return buf;
217}
218
220backend_x509_write_pem(openvpn_x509_cert_t *cert, const char *filename)
221{
222 /* mbed TLS does not make it easy to write a certificate in PEM format.
223 * The only way is to directly access the DER encoded raw certificate
224 * and PEM encode it ourselves */
225
226 struct gc_arena gc = gc_new();
227 /* just do a very loose upper bound for the base64 based PEM encoding
228 * using 3 times the space for the base64 and 100 bytes for the
229 * headers and footer */
230 struct buffer pem = alloc_buf_gc(cert->raw.len * 3 + 100, &gc);
231
232 struct buffer der = {};
233 buf_set_read(&der, cert->raw.p, cert->raw.len);
234
235 if (!crypto_pem_encode("CERTIFICATE", &pem, &der, &gc))
236 {
237 goto err;
238 }
239
240 if (!buffer_write_file(filename, &pem))
241 {
242 goto err;
243 }
244
245 gc_free(&gc);
246 return SUCCESS;
247err:
248 msg(D_TLS_DEBUG_LOW, "Error writing X509 certificate to file %s", filename);
249 gc_free(&gc);
250 return FAILURE;
251}
252
253#if defined(__GNUC__) || defined(__clang__)
254#pragma GCC diagnostic push
255#pragma GCC diagnostic ignored "-Wconversion"
256#endif
257
258static struct buffer
260{
261 const size_t md_size = mbedtls_md_get_size(md_info);
263 mbedtls_md(md_info, cert->raw.p, cert->raw.len, BPTR(&fingerprint));
265 return fingerprint;
266}
267
268#if defined(__GNUC__) || defined(__clang__)
269#pragma GCC diagnostic pop
270#endif
271
272struct buffer
274{
275 return x509_get_fingerprint(mbedtls_md_info_from_type(MBEDTLS_MD_SHA1), cert, gc);
276}
277
278struct buffer
280{
281 return x509_get_fingerprint(mbedtls_md_info_from_type(MBEDTLS_MD_SHA256), cert, gc);
282}
283
284char *
285x509_get_subject(mbedtls_x509_crt *cert, struct gc_arena *gc)
286{
287 char tmp_subject[MAX_SUBJECT_LENGTH] = { 0 };
288 char *subject = NULL;
289
290 int ret = 0;
291
292 ret = mbedtls_x509_dn_gets(tmp_subject, MAX_SUBJECT_LENGTH - 1, &cert->subject);
293 if (ret > 0)
294 {
295 /* Allocate the required space for the subject */
296 subject = string_alloc(tmp_subject, gc);
297 }
298
299 return subject;
300}
301
302static void
303do_setenv_x509(struct env_set *es, const char *name, char *value, int depth)
304{
305 char *name_expand;
306 size_t name_expand_size;
307
308 string_mod(value, CC_ANY, CC_CRLF, '?');
309 msg(D_X509_ATTR, "X509 ATTRIBUTE name='%s' value='%s' depth=%d", name, value, depth);
310 name_expand_size = 64 + strlen(name);
311 name_expand = (char *)malloc(name_expand_size);
312 check_malloc_return(name_expand);
313 snprintf(name_expand, name_expand_size, "X509_%d_%s", depth, name);
314 setenv_str(es, name_expand, value);
315 free(name_expand);
316}
317
318static char *
319asn1_buf_to_c_string(const mbedtls_asn1_buf *orig, struct gc_arena *gc)
320{
321 size_t i;
322 char *val;
323
324 if (!(orig->tag == MBEDTLS_ASN1_UTF8_STRING || orig->tag == MBEDTLS_ASN1_PRINTABLE_STRING
325 || orig->tag == MBEDTLS_ASN1_IA5_STRING))
326 {
327 /* Only support C-string compatible types */
328 return string_alloc("ERROR: unsupported ASN.1 string type", gc);
329 }
330
331 for (i = 0; i < orig->len; ++i)
332 {
333 if (orig->p[i] == '\0')
334 {
335 return string_alloc("ERROR: embedded null value", gc);
336 }
337 }
338 val = gc_malloc(orig->len + 1, false, gc);
339 memcpy(val, orig->p, orig->len);
340 val[orig->len] = '\0';
341 return val;
342}
343
344static void
345do_setenv_name(struct env_set *es, const struct x509_track *xt, const mbedtls_x509_crt *cert,
346 int depth, struct gc_arena *gc)
347{
348 const mbedtls_x509_name *xn;
349 for (xn = &cert->subject; xn != NULL; xn = xn->next)
350 {
351 const char *xn_short_name = NULL;
352 if (0 == mbedtls_oid_get_attr_short_name(&xn->oid, &xn_short_name)
353 && 0 == strcmp(xt->name, xn_short_name))
354 {
355 char *val_str = asn1_buf_to_c_string(&xn->val, gc);
356 do_setenv_x509(es, xt->name, val_str, depth);
357 }
358 }
359}
360
361void
362x509_track_add(const struct x509_track **ll_head, const char *name, msglvl_t msglevel,
363 struct gc_arena *gc)
364{
365 struct x509_track *xt;
366 ALLOC_OBJ_CLEAR_GC(xt, struct x509_track, gc);
367 if (*name == '+')
368 {
369 xt->flags |= XT_FULL_CHAIN;
370 ++name;
371 }
372 xt->name = name;
373 xt->next = *ll_head;
374 *ll_head = xt;
375}
376
377void
378x509_setenv_track(const struct x509_track *xt, struct env_set *es, const int depth,
379 mbedtls_x509_crt *cert)
380{
381 struct gc_arena gc = gc_new();
382 while (xt)
383 {
384 if (depth == 0 || (xt->flags & XT_FULL_CHAIN))
385 {
386 if (0 == strcmp(xt->name, "SHA1") || 0 == strcmp(xt->name, "SHA256"))
387 {
388 /* Fingerprint is not part of X509 structure */
389 struct buffer cert_hash;
390 char *fingerprint;
391
392 if (0 == strcmp(xt->name, "SHA1"))
393 {
395 }
396 else
397 {
399 }
400
402 format_hex_ex(BPTR(&cert_hash), BLEN(&cert_hash), 0, 1 | FHE_CAPS, ":", &gc);
404 }
405 else
406 {
407 do_setenv_name(es, xt, cert, depth, &gc);
408 }
409 }
410 xt = xt->next;
411 }
412 gc_free(&gc);
413}
414
415/*
416 * Save X509 fields to environment, using the naming convention:
417 *
418 * X509_{cert_depth}_{name}={value}
419 */
420void
422{
423 int i;
424 unsigned char c;
425 const mbedtls_x509_name *name;
426 char s[128] = { 0 };
427
428 name = &cert->subject;
429
430 while (name != NULL)
431 {
432 char name_expand[64 + 8];
433 const char *shortname;
434
435 if (0 == mbedtls_oid_get_attr_short_name(&name->oid, &shortname))
436 {
437 snprintf(name_expand, sizeof(name_expand), "X509_%d_%s", cert_depth, shortname);
438 }
439 else
440 {
441 snprintf(name_expand, sizeof(name_expand), "X509_%d_\?\?", cert_depth);
442 }
443
444 for (i = 0; i < name->val.len; i++)
445 {
446 if (i >= (int)sizeof(s) - 1)
447 {
448 break;
449 }
450
451 c = name->val.p[i];
452 if (c < 32 || c == 127 || (c > 128 && c < 160))
453 {
454 s[i] = '?';
455 }
456 else
457 {
458 s[i] = c;
459 }
460 }
461 s[i] = '\0';
462
463 /* Check both strings, set environment variable */
465 string_mod((char *)s, CC_PRINT, CC_CRLF, '_');
466 setenv_str_incr(es, name_expand, (char *)s);
467
468 name = name->next;
469 }
470}
471
472/* Dummy function because Netscape certificate types are not supported in OpenVPN with mbedtls.
473 * Returns SUCCESS if usage is NS_CERT_CHECK_NONE, FAILURE otherwise. */
476{
478 {
479 return SUCCESS;
480 }
481
482 return FAILURE;
483}
484
486x509_verify_cert_ku(mbedtls_x509_crt *cert, const unsigned *const expected_ku, int expected_len)
487{
488 msg(D_HANDSHAKE, "Validating certificate key usage");
489
491 {
492 msg(D_TLS_ERRORS, "ERROR: Certificate does not have key usage extension");
493 return FAILURE;
494 }
495
497 {
498 /* Extension required, value checked by TLS library */
499 return SUCCESS;
500 }
501
503 for (size_t i = 0; SUCCESS != fFound && i < expected_len; i++)
504 {
506 {
507 fFound = SUCCESS;
508 }
509 }
510
511 if (fFound != SUCCESS)
512 {
513 msg(D_TLS_ERRORS, "ERROR: Certificate has invalid key usage, expected one of:");
514 for (size_t i = 0; i < expected_len && expected_ku[i]; i++)
515 {
516 msg(D_TLS_ERRORS, " * %04x", expected_ku[i]);
517 }
518 }
519
520 return fFound;
521}
522
524x509_verify_cert_eku(mbedtls_x509_crt *cert, const char *const expected_oid)
525{
527
529 {
530 msg(D_HANDSHAKE, "Certificate does not have extended key usage extension");
531 }
532 else
533 {
534 mbedtls_x509_sequence *oid_seq = &(cert->ext_key_usage);
535
536 msg(D_HANDSHAKE, "Validating certificate extended key usage");
537 while (oid_seq != NULL)
538 {
540 char oid_num_str[1024];
541 const char *oid_str;
542
544 {
545 msg(D_HANDSHAKE, "++ Certificate has EKU (str) %s, expects %s", oid_str,
548 {
549 fFound = SUCCESS;
550 break;
551 }
552 }
553
555 {
556 msg(D_HANDSHAKE, "++ Certificate has EKU (oid) %s, expects %s", oid_num_str,
559 {
560 fFound = SUCCESS;
561 break;
562 }
563 }
564 oid_seq = oid_seq->next;
565 }
566 }
567
568 return fFound;
569}
570
571bool
572tls_verify_crl_missing(const struct tls_options *opt)
573{
574 if (opt->crl_file && !(opt->ssl_flags & SSLF_CRL_VERIFY_DIR)
575 && (opt->ssl_ctx.crl == NULL || opt->ssl_ctx.crl->version == 0))
576 {
577 return true;
578 }
579 return false;
580}
581
582#endif /* #if defined(ENABLE_CRYPTO_MBEDTLS) */
bool buffer_write_file(const char *filename, const struct buffer *buf)
Write buffer contents to file.
Definition buffer.c:301
char * format_hex_ex(const uint8_t *data, int size, int maxoutput, unsigned int space_break_flags, const char *separator, struct gc_arena *gc)
Definition buffer.c:483
void chomp(char *str)
Definition buffer.c:614
void * gc_malloc(size_t size, bool clear, struct gc_arena *a)
Definition buffer.c:336
struct buffer alloc_buf_gc(size_t size, struct gc_arena *gc)
Definition buffer.c:89
bool string_mod(char *str, const unsigned int inclusive, const unsigned int exclusive, const char replace)
Modifies a string in place by replacing certain classes of characters of it with a specified characte...
Definition buffer.c:1041
char * string_alloc(const char *str, struct gc_arena *gc)
Definition buffer.c:649
#define CC_ANY
any character
Definition buffer.h:867
#define BPTR(buf)
Definition buffer.h:123
static bool buf_inc_len(struct buffer *buf, int inc)
Definition buffer.h:588
#define CC_CRLF
carriage return or newline
Definition buffer.h:904
static void buf_set_read(struct buffer *buf, const uint8_t *data, size_t size)
Definition buffer.h:348
#define ALLOC_OBJ_CLEAR_GC(dptr, type, gc)
Definition buffer.h:1079
#define BLEN(buf)
Definition buffer.h:126
static void check_malloc_return(void *p)
Definition buffer.h:1085
static void gc_free(struct gc_arena *a)
Definition buffer.h:1015
#define CC_PRINT
printable (>= 32, != 127)
Definition buffer.h:875
#define FHE_CAPS
Definition buffer.h:498
static struct gc_arena gc_new(void)
Definition buffer.h:1007
bool crypto_pem_encode(const char *name, struct buffer *dst, const struct buffer *src, struct gc_arena *gc)
Encode binary data as PEM.
Data Channel Cryptography mbed TLS-specific backend interface.
#define mbed_ok(errval)
Check errval and log on error.
void setenv_str(struct env_set *es, const char *name, const char *value)
Definition env_set.c:307
void setenv_str_incr(struct env_set *es, const char *name, const char *value)
Store the supplied name value pair in the env_set.
Definition env_set.c:329
#define D_TLS_DEBUG_LOW
Definition errlevel.h:76
#define D_X509_ATTR
Definition errlevel.h:102
#define D_HANDSHAKE
Definition errlevel.h:71
#define D_TLS_ERRORS
Definition errlevel.h:58
int verify_callback(void *session_obj, mbedtls_x509_crt *cert, int cert_depth, uint32_t *flags)
Verify that the remote OpenVPN peer's certificate allows setting up a VPN tunnel.
mbedtls compatibility stub.
static int mbedtls_x509_crt_has_ext_type(const mbedtls_x509_crt *ctx, int ext_type)
X509 openvpn_x509_cert_t
#define msg(flags,...)
Definition error.h:152
unsigned int msglvl_t
Definition error.h:77
#define ASSERT(x)
Definition error.h:219
#define M_WARN
Definition error.h:92
static void usage(void)
Definition options.c:4842
#define SSLF_CRL_VERIFY_DIR
Definition ssl_common.h:429
result_t verify_cert(struct tls_session *session, openvpn_x509_cert_t *cert, int cert_depth)
Definition ssl_verify.c:577
void cert_hash_remember(struct tls_session *session, const int error_depth, const struct buffer *cert_hash)
Definition ssl_verify.c:194
Control Channel Verification Module.
#define OPENVPN_KU_REQUIRED
Require keyUsage to be present in cert (0xFFFF is an invalid KU value)
Definition ssl_verify.h:257
#define XT_FULL_CHAIN
Definition ssl_verify.h:241
#define NS_CERT_CHECK_NONE
Do not perform Netscape certificate type verification.
Definition ssl_verify.h:250
struct buffer x509_get_sha256_fingerprint(openvpn_x509_cert_t *cert, struct gc_arena *gc)
Retrieve the certificate's SHA256 fingerprint.
void x509_setenv_track(const struct x509_track *xt, struct env_set *es, const int depth, openvpn_x509_cert_t *x509)
void x509_setenv(struct env_set *es, int cert_depth, openvpn_x509_cert_t *cert)
bool tls_verify_crl_missing(const struct tls_options *opt)
Return true iff a CRL is configured, but is not loaded.
result_t backend_x509_write_pem(openvpn_x509_cert_t *cert, const char *filename)
result_t x509_verify_ns_cert_type(openvpn_x509_cert_t *cert, const int usage)
char * backend_x509_get_serial_hex(openvpn_x509_cert_t *cert, struct gc_arena *gc)
result_t x509_verify_cert_ku(openvpn_x509_cert_t *x509, const unsigned *const expected_ku, int expected_len)
struct buffer x509_get_sha1_fingerprint(openvpn_x509_cert_t *cert, struct gc_arena *gc)
Retrieve the certificate's SHA1 fingerprint.
char * x509_get_subject(openvpn_x509_cert_t *cert, struct gc_arena *gc)
char * backend_x509_get_serial(openvpn_x509_cert_t *cert, struct gc_arena *gc)
result_t backend_x509_get_username(char *common_name, size_t cn_len, char *x509_username_field, openvpn_x509_cert_t *peer_cert)
void x509_track_add(const struct x509_track **ll_head, const char *name, msglvl_t msglevel, struct gc_arena *gc)
result_t
Result of verification function.
@ FAILURE
@ SUCCESS
result_t x509_verify_cert_eku(openvpn_x509_cert_t *x509, const char *const expected_oid)
static void do_setenv_x509(struct env_set *es, const char *name, char *value, int depth)
Wrapper structure for dynamically allocated memory.
Definition buffer.h:60
int len
Length in bytes of the actual content within the allocated memory.
Definition buffer.h:65
Structure containing the hash for a single certificate.
Definition ssl_verify.h:58
Garbage collection arena used to keep track of dynamically allocated memory.
Definition buffer.h:116
struct tls_root_ctx ssl_ctx
Definition ssl_common.h:309
unsigned int ssl_flags
Definition ssl_common.h:435
const char * crl_file
Definition ssl_common.h:354
mbedtls_x509_crl * crl
Certificate Revocation List.
Security parameter state of a single session within a VPN tunnel.
Definition ssl_common.h:490
unsigned int flags
Definition ssl_verify.h:242
const struct x509_track * next
Definition ssl_verify.h:239
const char * name
Definition ssl_verify.h:240
struct env_set * es
struct gc_arena gc
Definition test_ssl.c:131