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 Fox Crypto B.V. <openvpn@foxcrypto.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, int 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
253static struct buffer
255{
256 const size_t md_size = mbedtls_md_get_size(md_info);
258 mbedtls_md(md_info, cert->raw.p, cert->raw.len, BPTR(&fingerprint));
260 return fingerprint;
261}
262
263struct buffer
265{
266 return x509_get_fingerprint(mbedtls_md_info_from_type(MBEDTLS_MD_SHA1), cert, gc);
267}
268
269struct buffer
271{
272 return x509_get_fingerprint(mbedtls_md_info_from_type(MBEDTLS_MD_SHA256), cert, gc);
273}
274
275char *
276x509_get_subject(mbedtls_x509_crt *cert, struct gc_arena *gc)
277{
278 char tmp_subject[MAX_SUBJECT_LENGTH] = { 0 };
279 char *subject = NULL;
280
281 int ret = 0;
282
283 ret = mbedtls_x509_dn_gets(tmp_subject, MAX_SUBJECT_LENGTH - 1, &cert->subject);
284 if (ret > 0)
285 {
286 /* Allocate the required space for the subject */
287 subject = string_alloc(tmp_subject, gc);
288 }
289
290 return subject;
291}
292
293static void
294do_setenv_x509(struct env_set *es, const char *name, char *value, int depth)
295{
296 char *name_expand;
297 size_t name_expand_size;
298
299 string_mod(value, CC_ANY, CC_CRLF, '?');
300 msg(D_X509_ATTR, "X509 ATTRIBUTE name='%s' value='%s' depth=%d", name, value, depth);
301 name_expand_size = 64 + strlen(name);
302 name_expand = (char *)malloc(name_expand_size);
303 check_malloc_return(name_expand);
304 snprintf(name_expand, name_expand_size, "X509_%d_%s", depth, name);
305 setenv_str(es, name_expand, value);
306 free(name_expand);
307}
308
309static char *
310asn1_buf_to_c_string(const mbedtls_asn1_buf *orig, struct gc_arena *gc)
311{
312 size_t i;
313 char *val;
314
315 if (!(orig->tag == MBEDTLS_ASN1_UTF8_STRING || orig->tag == MBEDTLS_ASN1_PRINTABLE_STRING
316 || orig->tag == MBEDTLS_ASN1_IA5_STRING))
317 {
318 /* Only support C-string compatible types */
319 return string_alloc("ERROR: unsupported ASN.1 string type", gc);
320 }
321
322 for (i = 0; i < orig->len; ++i)
323 {
324 if (orig->p[i] == '\0')
325 {
326 return string_alloc("ERROR: embedded null value", gc);
327 }
328 }
329 val = gc_malloc(orig->len + 1, false, gc);
330 memcpy(val, orig->p, orig->len);
331 val[orig->len] = '\0';
332 return val;
333}
334
335static void
336do_setenv_name(struct env_set *es, const struct x509_track *xt, const mbedtls_x509_crt *cert,
337 int depth, struct gc_arena *gc)
338{
339 const mbedtls_x509_name *xn;
340 for (xn = &cert->subject; xn != NULL; xn = xn->next)
341 {
342 const char *xn_short_name = NULL;
343 if (0 == mbedtls_oid_get_attr_short_name(&xn->oid, &xn_short_name)
344 && 0 == strcmp(xt->name, xn_short_name))
345 {
346 char *val_str = asn1_buf_to_c_string(&xn->val, gc);
347 do_setenv_x509(es, xt->name, val_str, depth);
348 }
349 }
350}
351
352void
353x509_track_add(const struct x509_track **ll_head, const char *name, int msglevel,
354 struct gc_arena *gc)
355{
356 struct x509_track *xt;
357 ALLOC_OBJ_CLEAR_GC(xt, struct x509_track, gc);
358 if (*name == '+')
359 {
360 xt->flags |= XT_FULL_CHAIN;
361 ++name;
362 }
363 xt->name = name;
364 xt->next = *ll_head;
365 *ll_head = xt;
366}
367
368void
369x509_setenv_track(const struct x509_track *xt, struct env_set *es, const int depth,
370 mbedtls_x509_crt *cert)
371{
372 struct gc_arena gc = gc_new();
373 while (xt)
374 {
375 if (depth == 0 || (xt->flags & XT_FULL_CHAIN))
376 {
377 if (0 == strcmp(xt->name, "SHA1") || 0 == strcmp(xt->name, "SHA256"))
378 {
379 /* Fingerprint is not part of X509 structure */
380 struct buffer cert_hash;
381 char *fingerprint;
382
383 if (0 == strcmp(xt->name, "SHA1"))
384 {
386 }
387 else
388 {
390 }
391
393 format_hex_ex(BPTR(&cert_hash), BLEN(&cert_hash), 0, 1 | FHE_CAPS, ":", &gc);
395 }
396 else
397 {
398 do_setenv_name(es, xt, cert, depth, &gc);
399 }
400 }
401 xt = xt->next;
402 }
403 gc_free(&gc);
404}
405
406/*
407 * Save X509 fields to environment, using the naming convention:
408 *
409 * X509_{cert_depth}_{name}={value}
410 */
411void
413{
414 int i;
415 unsigned char c;
416 const mbedtls_x509_name *name;
417 char s[128] = { 0 };
418
419 name = &cert->subject;
420
421 while (name != NULL)
422 {
423 char name_expand[64 + 8];
424 const char *shortname;
425
426 if (0 == mbedtls_oid_get_attr_short_name(&name->oid, &shortname))
427 {
428 snprintf(name_expand, sizeof(name_expand), "X509_%d_%s", cert_depth, shortname);
429 }
430 else
431 {
432 snprintf(name_expand, sizeof(name_expand), "X509_%d_\?\?", cert_depth);
433 }
434
435 for (i = 0; i < name->val.len; i++)
436 {
437 if (i >= (int)sizeof(s) - 1)
438 {
439 break;
440 }
441
442 c = name->val.p[i];
443 if (c < 32 || c == 127 || (c > 128 && c < 160))
444 {
445 s[i] = '?';
446 }
447 else
448 {
449 s[i] = c;
450 }
451 }
452 s[i] = '\0';
453
454 /* Check both strings, set environment variable */
456 string_mod((char *)s, CC_PRINT, CC_CRLF, '_');
457 setenv_str_incr(es, name_expand, (char *)s);
458
459 name = name->next;
460 }
461}
462
463/* Dummy function because Netscape certificate types are not supported in OpenVPN with mbedtls.
464 * Returns SUCCESS if usage is NS_CERT_CHECK_NONE, FAILURE otherwise. */
467{
469 {
470 return SUCCESS;
471 }
472
473 return FAILURE;
474}
475
477x509_verify_cert_ku(mbedtls_x509_crt *cert, const unsigned *const expected_ku, int expected_len)
478{
479 msg(D_HANDSHAKE, "Validating certificate key usage");
480
482 {
483 msg(D_TLS_ERRORS, "ERROR: Certificate does not have key usage extension");
484 return FAILURE;
485 }
486
488 {
489 /* Extension required, value checked by TLS library */
490 return SUCCESS;
491 }
492
494 for (size_t i = 0; SUCCESS != fFound && i < expected_len; i++)
495 {
497 {
498 fFound = SUCCESS;
499 }
500 }
501
502 if (fFound != SUCCESS)
503 {
504 msg(D_TLS_ERRORS, "ERROR: Certificate has invalid key usage, expected one of:");
505 for (size_t i = 0; i < expected_len && expected_ku[i]; i++)
506 {
507 msg(D_TLS_ERRORS, " * %04x", expected_ku[i]);
508 }
509 }
510
511 return fFound;
512}
513
515x509_verify_cert_eku(mbedtls_x509_crt *cert, const char *const expected_oid)
516{
518
520 {
521 msg(D_HANDSHAKE, "Certificate does not have extended key usage extension");
522 }
523 else
524 {
525 mbedtls_x509_sequence *oid_seq = &(cert->ext_key_usage);
526
527 msg(D_HANDSHAKE, "Validating certificate extended key usage");
528 while (oid_seq != NULL)
529 {
531 char oid_num_str[1024];
532 const char *oid_str;
533
535 {
536 msg(D_HANDSHAKE, "++ Certificate has EKU (str) %s, expects %s", oid_str,
539 {
540 fFound = SUCCESS;
541 break;
542 }
543 }
544
546 {
547 msg(D_HANDSHAKE, "++ Certificate has EKU (oid) %s, expects %s", oid_num_str,
550 {
551 fFound = SUCCESS;
552 break;
553 }
554 }
555 oid_seq = oid_seq->next;
556 }
557 }
558
559 return fFound;
560}
561
562bool
563tls_verify_crl_missing(const struct tls_options *opt)
564{
565 if (opt->crl_file && !(opt->ssl_flags & SSLF_CRL_VERIFY_DIR)
566 && (opt->ssl_ctx.crl == NULL || opt->ssl_ctx.crl->version == 0))
567 {
568 return true;
569 }
570 return false;
571}
572
573#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)
#define msg(flags,...)
Definition error.h:150
#define ASSERT(x)
Definition error.h:217
#define M_WARN
Definition error.h:90
static void usage(void)
Definition options.c:4833
#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)
result_t backend_x509_get_username(char *common_name, int cn_len, char *x509_username_field, openvpn_x509_cert_t *peer_cert)
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)
Definition test_pkcs11.c:68
char * backend_x509_get_serial(openvpn_x509_cert_t *cert, struct gc_arena *gc)
void x509_track_add(const struct x509_track **ll_head, const char *name, int 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
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:154