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-2026 OpenVPN Inc <sales@openvpn.net>
9 * Copyright (C) 2010-2026 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 "ssl_verify.h"
39#include <mbedtls/asn1.h>
40#include <mbedtls/error.h>
41#include <mbedtls/bignum.h>
42#include <mbedtls/oid.h>
43#include <mbedtls/sha1.h>
44
45#define MAX_SUBJECT_LENGTH 256
46
47int
48verify_callback(void *session_obj, mbedtls_x509_crt *cert, int cert_depth, uint32_t *flags)
49{
50 struct tls_session *session = (struct tls_session *)session_obj;
51 struct gc_arena gc = gc_new();
52
53 ASSERT(cert);
55
56 session->verified = false;
57
58 /* Remember certificate hash */
61
62 if (session->opt->verify_hash_no_ca)
63 {
64 /*
65 * If we decide to verify the peer certificate based on the fingerprint
66 * we ignore wrong dates and the certificate not being trusted.
67 * Any other problem with the certificate (wrong key, bad cert,...)
68 * will still trigger an error.
69 * Clearing these flags relies on verify_cert will later rejecting a
70 * certificate that has no matching fingerprint.
71 */
74 *flags = *flags & ~flags_ignore;
75 }
76
77 /* did peer present cert which was signed by our root cert? */
78 if (*flags != 0)
79 {
80 int ret = 0;
81 char errstr[512] = { 0 };
82 char *subject = x509_get_subject(cert, &gc);
83 char *serial = backend_x509_get_serial(cert, &gc);
84
85 ret = mbedtls_x509_crt_verify_info(errstr, sizeof(errstr) - 1, "", *flags);
86 if (ret <= 0
87 && snprintf(errstr, sizeof(errstr), "Could not retrieve error string, flags=%" PRIx32,
88 *flags)
89 >= sizeof(errstr))
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/* not supported for mbedTLS yet */
127bool
129{
130 return false;
131}
132
134backend_x509_get_username(char *cn, size_t cn_len, char *x509_username_field, mbedtls_x509_crt *cert)
135{
136 mbedtls_x509_name *name;
137
138 ASSERT(cn != NULL);
139
140 name = &cert->subject;
141
142 /* Find common name */
143 while (name != NULL)
144 {
146 {
147 break;
148 }
149
150 name = name->next;
151 }
152
153 /* Not found, return an error if this is the peer's certificate */
154 if (name == NULL)
155 {
156 return FAILURE;
157 }
158
159 /* Found, extract CN */
160 if (cn_len > name->val.len)
161 {
162 memcpy(cn, name->val.p, name->val.len);
163 cn[name->val.len] = '\0';
164 }
165 else
166 {
167 memcpy(cn, name->val.p, cn_len);
168 cn[cn_len - 1] = '\0';
169 }
170
171 return SUCCESS;
172}
173
174char *
176{
177 char *buf = NULL;
178 size_t buflen = 0;
179 mbedtls_mpi serial_mpi = { 0 };
180
181 /* Transform asn1 integer serial into mbed TLS MPI */
183 if (!mbed_ok(mbedtls_mpi_read_binary(&serial_mpi, cert->serial.p, cert->serial.len)))
184 {
185 msg(M_WARN, "Failed to retrieve serial from certificate.");
186 goto end;
187 }
188
189 /* Determine decimal representation length, allocate buffer */
191 buf = gc_malloc(buflen, true, gc);
192
193 /* Write MPI serial as decimal string into buffer */
195 {
196 msg(M_WARN, "Failed to write serial to string.");
197 buf = NULL;
198 goto end;
199 }
200
201end:
203 return buf;
204}
205
206char *
208{
209 char *buf = NULL;
210 size_t len = cert->serial.len * 3 + 1;
211
212 buf = gc_malloc(len, true, gc);
213
214 if (mbedtls_x509_serial_gets(buf, len - 1, &cert->serial) < 0)
215 {
216 buf = NULL;
217 }
218
219 return buf;
220}
221
223backend_x509_write_pem(openvpn_x509_cert_t *cert, const char *filename)
224{
225 /* mbed TLS does not make it easy to write a certificate in PEM format.
226 * The only way is to directly access the DER encoded raw certificate
227 * and PEM encode it ourselves */
228
229 struct gc_arena gc = gc_new();
230 /* just do a very loose upper bound for the base64 based PEM encoding
231 * using 3 times the space for the base64 and 100 bytes for the
232 * headers and footer */
233 struct buffer pem = alloc_buf_gc(cert->raw.len * 3 + 100, &gc);
234
235 struct buffer der = { 0 };
236 buf_set_read(&der, cert->raw.p, cert->raw.len);
237
238 if (!crypto_pem_encode("CERTIFICATE", &pem, &der, &gc))
239 {
240 goto err;
241 }
242
243 if (!buffer_write_file(filename, &pem))
244 {
245 goto err;
246 }
247
248 gc_free(&gc);
249 return SUCCESS;
250err:
251 msg(D_TLS_DEBUG_LOW, "Error writing X509 certificate to file %s", filename);
252 gc_free(&gc);
253 return FAILURE;
254}
255
256#if defined(__GNUC__) || defined(__clang__)
257#pragma GCC diagnostic push
258#pragma GCC diagnostic ignored "-Wconversion"
259#endif
260
261static struct buffer
263{
264 const size_t md_size = mbedtls_md_get_size(md_info);
266 mbedtls_md(md_info, cert->raw.p, cert->raw.len, BPTR(&fingerprint));
268 return fingerprint;
269}
270
271#if defined(__GNUC__) || defined(__clang__)
272#pragma GCC diagnostic pop
273#endif
274
275struct buffer
277{
278 return x509_get_fingerprint(mbedtls_md_info_from_type(MBEDTLS_MD_SHA1), cert, gc);
279}
280
281struct buffer
283{
284 return x509_get_fingerprint(mbedtls_md_info_from_type(MBEDTLS_MD_SHA256), cert, gc);
285}
286
287char *
288x509_get_subject(mbedtls_x509_crt *cert, struct gc_arena *gc)
289{
290 char tmp_subject[MAX_SUBJECT_LENGTH] = { 0 };
291 char *subject = NULL;
292
293 int ret = 0;
294
295 ret = mbedtls_x509_dn_gets(tmp_subject, MAX_SUBJECT_LENGTH - 1, &cert->subject);
296 if (ret > 0)
297 {
298 /* Allocate the required space for the subject */
299 subject = string_alloc(tmp_subject, gc);
300 }
301
302 return subject;
303}
304
305static void
306do_setenv_x509(struct env_set *es, const char *name, char *value, int depth)
307{
308 char *name_expand;
309 size_t name_expand_size;
310
311 string_mod(value, CC_ANY, CC_CRLF, '?');
312 msg(D_X509_ATTR, "X509 ATTRIBUTE name='%s' value='%s' depth=%d", name, value, depth);
313 name_expand_size = 64 + strlen(name);
314 name_expand = (char *)malloc(name_expand_size);
315 check_malloc_return(name_expand);
316 snprintf(name_expand, name_expand_size, "X509_%d_%s", depth, name);
317 setenv_str(es, name_expand, value);
318 free(name_expand);
319}
320
321static char *
322asn1_buf_to_c_string(const mbedtls_asn1_buf *orig, struct gc_arena *gc)
323{
324 size_t i;
325 char *val;
326
327 if (!(orig->tag == MBEDTLS_ASN1_UTF8_STRING || orig->tag == MBEDTLS_ASN1_PRINTABLE_STRING
328 || orig->tag == MBEDTLS_ASN1_IA5_STRING))
329 {
330 /* Only support C-string compatible types */
331 return string_alloc("ERROR: unsupported ASN.1 string type", gc);
332 }
333
334 for (i = 0; i < orig->len; ++i)
335 {
336 if (orig->p[i] == '\0')
337 {
338 return string_alloc("ERROR: embedded null value", gc);
339 }
340 }
341 val = gc_malloc(orig->len + 1, false, gc);
342 memcpy(val, orig->p, orig->len);
343 val[orig->len] = '\0';
344 return val;
345}
346
347static void
348do_setenv_name(struct env_set *es, const struct x509_track *xt, const mbedtls_x509_crt *cert,
349 int depth, struct gc_arena *gc)
350{
351 const mbedtls_x509_name *xn;
352 for (xn = &cert->subject; xn != NULL; xn = xn->next)
353 {
354 const char *xn_short_name = NULL;
355 if (0 == mbedtls_oid_get_attr_short_name(&xn->oid, &xn_short_name)
356 && 0 == strcmp(xt->name, xn_short_name))
357 {
358 char *val_str = asn1_buf_to_c_string(&xn->val, gc);
359 do_setenv_x509(es, xt->name, val_str, depth);
360 }
361 }
362}
363
364void
365x509_track_add(const struct x509_track **ll_head, const char *name, msglvl_t msglevel,
366 struct gc_arena *gc)
367{
368 struct x509_track *xt;
369 ALLOC_OBJ_CLEAR_GC(xt, struct x509_track, gc);
370 if (*name == '+')
371 {
372 xt->flags |= XT_FULL_CHAIN;
373 ++name;
374 }
375 xt->name = name;
376 xt->next = *ll_head;
377 *ll_head = xt;
378}
379
380void
381x509_setenv_track(const struct x509_track *xt, struct env_set *es, const int depth,
382 mbedtls_x509_crt *cert)
383{
384 struct gc_arena gc = gc_new();
385 while (xt)
386 {
387 if (depth == 0 || (xt->flags & XT_FULL_CHAIN))
388 {
389 if (0 == strcmp(xt->name, "SHA1") || 0 == strcmp(xt->name, "SHA256"))
390 {
391 /* Fingerprint is not part of X509 structure */
392 struct buffer cert_hash;
393 char *fingerprint;
394
395 if (0 == strcmp(xt->name, "SHA1"))
396 {
398 }
399 else
400 {
402 }
403
405 format_hex_ex(BPTR(&cert_hash), BLEN(&cert_hash), 0, 1 | FHE_CAPS, ":", &gc);
407 }
408 else
409 {
410 do_setenv_name(es, xt, cert, depth, &gc);
411 }
412 }
413 xt = xt->next;
414 }
415 gc_free(&gc);
416}
417
418/*
419 * Save X509 fields to environment, using the naming convention:
420 *
421 * X509_{cert_depth}_{name}={value}
422 */
423void
425{
426 int i;
427 unsigned char c;
428 const mbedtls_x509_name *name;
429 char s[128] = { 0 };
430
431 name = &cert->subject;
432
433 while (name != NULL)
434 {
435 char name_expand[64 + 8];
436 const char *shortname;
437
438 if (0 == mbedtls_oid_get_attr_short_name(&name->oid, &shortname))
439 {
440 snprintf(name_expand, sizeof(name_expand), "X509_%d_%s", cert_depth, shortname);
441 }
442 else
443 {
444 snprintf(name_expand, sizeof(name_expand), "X509_%d_\?\?", cert_depth);
445 }
446
447 for (i = 0; i < name->val.len; i++)
448 {
449 if (i >= (int)sizeof(s) - 1)
450 {
451 break;
452 }
453
454 c = name->val.p[i];
455 if (c < 32 || c == 127 || (c > 128 && c < 160))
456 {
457 s[i] = '?';
458 }
459 else
460 {
461 s[i] = c;
462 }
463 }
464 s[i] = '\0';
465
466 /* Check both strings, set environment variable */
468 string_mod((char *)s, CC_PRINT, CC_CRLF, '_');
469 setenv_str_incr(es, name_expand, (char *)s);
470
471 name = name->next;
472 }
473}
474
475/* Dummy function because Netscape certificate types are not supported in OpenVPN with mbedtls.
476 * Returns SUCCESS if usage is NS_CERT_CHECK_NONE, FAILURE otherwise. */
479{
481 {
482 return SUCCESS;
483 }
484
485 return FAILURE;
486}
487
489x509_verify_cert_ku(mbedtls_x509_crt *cert, const unsigned int *const expected_ku, size_t expected_len)
490{
491 msg(D_HANDSHAKE, "Validating certificate key usage");
492
494 {
495 msg(D_TLS_ERRORS, "ERROR: Certificate does not have key usage extension");
496 return FAILURE;
497 }
498
500 {
501 /* Extension required, value checked by TLS library */
502 return SUCCESS;
503 }
504
506 for (size_t i = 0; SUCCESS != fFound && i < expected_len; i++)
507 {
509 {
510 fFound = SUCCESS;
511 }
512 }
513
514 if (fFound != SUCCESS)
515 {
516 msg(D_TLS_ERRORS, "ERROR: Certificate has invalid key usage, expected one of:");
517 for (size_t i = 0; i < expected_len && expected_ku[i]; i++)
518 {
519 msg(D_TLS_ERRORS, " * %04x", expected_ku[i]);
520 }
521 }
522
523 return fFound;
524}
525
527x509_verify_cert_eku(mbedtls_x509_crt *cert, const char *const expected_oid)
528{
530
532 {
533 msg(D_HANDSHAKE, "Certificate does not have extended key usage extension");
534 }
535 else
536 {
537 mbedtls_x509_sequence *oid_seq = &(cert->ext_key_usage);
538
539 msg(D_HANDSHAKE, "Validating certificate extended key usage");
540 while (oid_seq != NULL)
541 {
543 char oid_num_str[1024];
544 const char *oid_str;
545
547 {
548 msg(D_HANDSHAKE, "++ Certificate has EKU (str) %s, expects %s", oid_str,
551 {
552 fFound = SUCCESS;
553 break;
554 }
555 }
556
558 {
559 msg(D_HANDSHAKE, "++ Certificate has EKU (oid) %s, expects %s", oid_num_str,
562 {
563 fFound = SUCCESS;
564 break;
565 }
566 }
567 oid_seq = oid_seq->next;
568 }
569 }
570
571 return fFound;
572}
573
574bool
575tls_verify_crl_missing(const struct tls_options *opt)
576{
577 if (opt->crl_file && !(opt->ssl_flags & SSLF_CRL_VERIFY_DIR)
578 && (opt->ssl_ctx->crl == NULL || opt->ssl_ctx->crl->version == 0))
579 {
580 return true;
581 }
582 return false;
583}
584
585#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
void chomp(char *str)
Definition buffer.c:613
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
char * format_hex_ex(const uint8_t *data, size_t size, size_t maxoutput, unsigned int space_break_flags, const char *separator, struct gc_arena *gc)
Definition buffer.c:483
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:1045
char * string_alloc(const char *str, struct gc_arena *gc)
Definition buffer.c:648
#define CC_ANY
any character
Definition buffer.h:877
#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:914
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:1101
#define BLEN(buf)
Definition buffer.h:126
static void check_malloc_return(void *p)
Definition buffer.h:1107
static void gc_free(struct gc_arena *a)
Definition buffer.h:1025
#define CC_PRINT
printable (>= 32, != 127)
Definition buffer.h:885
#define FHE_CAPS
Definition buffer.h:498
static struct gc_arena gc_new(void)
Definition buffer.h:1017
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.
#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
void usage(void)
Definition options.c:4834
#define SSLF_CRL_VERIFY_DIR
Definition ssl_common.h:428
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.
bool x509_username_field_ext_supported(const char *extname)
Return true iff the supplied extension field is supported by the –x509-username-field option.
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)
struct buffer x509_get_sha1_fingerprint(openvpn_x509_cert_t *cert, struct gc_arena *gc)
Retrieve the certificate's SHA1 fingerprint.
result_t x509_verify_cert_ku(openvpn_x509_cert_t *x509, const unsigned *const expected_ku, size_t expected_len)
char * x509_get_subject(openvpn_x509_cert_t *cert, struct gc_arena *gc)
Definition test_pkcs11.c:68
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)
mbedtls_x509_crt openvpn_x509_cert_t
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
unsigned int ssl_flags
Definition ssl_common.h:434
struct tls_root_ctx * ssl_ctx
Definition ssl_common.h:311
const char * crl_file
Definition ssl_common.h:356
mbedtls_x509_crl * crl
Certificate Revocation List.
Security parameter state of a single session within a VPN tunnel.
Definition ssl_common.h:489
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