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
28
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
39#include "ssl_verify.h"
40#include <mbedtls/asn1.h>
41#include <mbedtls/error.h>
42#include <mbedtls/oid.h>
43
44#define MAX_SUBJECT_LENGTH 256
45
46int
47verify_callback(void *session_obj, mbedtls_x509_crt *cert, int cert_depth, uint32_t *flags)
48{
49 struct tls_session *session = (struct tls_session *)session_obj;
50 struct gc_arena gc = gc_new();
51
52 ASSERT(cert);
54
55 session->verified = false;
56
57 /* Remember certificate hash */
58 struct buffer cert_fingerprint = x509_get_sha256_fingerprint(cert, &gc);
59 cert_hash_remember(session, cert_depth, &cert_fingerprint);
60
61 if (session->opt->verify_hash_no_ca)
62 {
63 /*
64 * If we decide to verify the peer certificate based on the fingerprint
65 * we ignore wrong dates and the certificate not being trusted.
66 * Any other problem with the certificate (wrong key, bad cert,...)
67 * will still trigger an error.
68 * Clearing these flags relies on verify_cert will later rejecting a
69 * certificate that has no matching fingerprint.
70 */
71 uint32_t flags_ignore = MBEDTLS_X509_BADCERT_NOT_TRUSTED | MBEDTLS_X509_BADCERT_EXPIRED
72 | MBEDTLS_X509_BADCERT_FUTURE;
73 *flags = *flags & ~flags_ignore;
74 }
75
76 /* did peer present cert which was signed by our root cert? */
77 if (*flags != 0)
78 {
79 int ret = 0;
80 char errstr[512] = { 0 };
81 char *subject = x509_get_subject(cert, &gc);
82 char *serial = backend_x509_get_serial(cert, &gc);
83
84 ret = mbedtls_x509_crt_verify_info(errstr, sizeof(errstr) - 1, "", *flags);
85 if (ret <= 0
86 && !checked_snprintf(errstr, sizeof(errstr), "Could not retrieve error string, flags=%" PRIx32, *flags))
87 {
88 errstr[0] = '\0';
89 }
90 else
91 {
92 chomp(errstr);
93 }
94
95 if (subject)
96 {
97 msg(D_TLS_ERRORS, "VERIFY ERROR: depth=%d, subject=%s, serial=%s: %s", cert_depth,
98 subject, serial ? serial : "<not available>", errstr);
99 }
100 else
101 {
103 "VERIFY ERROR: depth=%d, (could not extract X509 "
104 "subject string from certificate): %s",
105 cert_depth, errstr);
106 }
107
108 /* Leave flags set to non-zero to indicate that the cert is not ok */
109 }
110 else if (SUCCESS != verify_cert(session, cert, cert_depth))
111 {
112 *flags |= MBEDTLS_X509_BADCERT_OTHER;
113 }
114
115 gc_free(&gc);
116
117 /*
118 * PolarSSL/mbed TLS-1.2.0+ expects 0 on anything except fatal errors.
119 */
120 return 0;
121}
122
123/* not supported for mbedTLS yet */
124bool
125x509_username_field_ext_supported(const char *fieldname)
126{
127 return false;
128}
129
130static const char *
131fieldname_to_oid(const char *fieldname)
132{
133 if (strcmp(fieldname, "C") == 0)
134 {
135 return MBEDTLS_OID_AT_COUNTRY;
136 }
137 else if (strcmp(fieldname, "ST") == 0)
138 {
139 return MBEDTLS_OID_AT_STATE;
140 }
141 else if (strcmp(fieldname, "LOCALITY") == 0)
142 {
143 return MBEDTLS_OID_AT_LOCALITY;
144 }
145 else if (strcmp(fieldname, "O") == 0)
146 {
147 return MBEDTLS_OID_AT_ORGANIZATION;
148 }
149 else if (strcmp(fieldname, "OU") == 0)
150 {
151 return MBEDTLS_OID_AT_ORG_UNIT;
152 }
153 else if (strcmp(fieldname, "CN") == 0)
154 {
155 return MBEDTLS_OID_AT_CN;
156 }
157 else if (strcmp(fieldname, "GN") == 0)
158 {
159 return MBEDTLS_OID_AT_GIVEN_NAME;
160 }
161 else if (strcmp(fieldname, "SN") == 0)
162 {
163 return MBEDTLS_OID_AT_SUR_NAME;
164 }
165 else if (strcmp(fieldname, "initials") == 0)
166 {
167 return MBEDTLS_OID_AT_INITIALS;
168 }
169 else if (strcmp(fieldname, "pseudonym") == 0)
170 {
171 return MBEDTLS_OID_AT_PSEUDONYM;
172 }
173 else if (strcmp(fieldname, "title") == 0)
174 {
175 return MBEDTLS_OID_AT_TITLE;
176 }
177 else if (strcmp(fieldname, "generationQualifier") == 0)
178 {
179 return MBEDTLS_OID_AT_GENERATION_QUALIFIER;
180 }
181 else if (strcmp(fieldname, "postalAddress") == 0)
182 {
183 return MBEDTLS_OID_AT_POSTAL_ADDRESS;
184 }
185 else if (strcmp(fieldname, "postalCode") == 0)
186 {
187 return MBEDTLS_OID_AT_POSTAL_CODE;
188 }
189 else if (strcmp(fieldname, "emailAddress") == 0)
190 {
191 return MBEDTLS_OID_PKCS9_EMAIL;
192 }
193 else if (strcmp(fieldname, "uid") == 0)
194 {
195 return MBEDTLS_OID_AT_UNIQUE_IDENTIFIER;
196 }
197 else if (strcmp(fieldname, "dnQualifier") == 0)
198 {
199 return MBEDTLS_OID_AT_DN_QUALIFIER;
200 }
201 else
202 {
203 return NULL;
204 }
205}
206
207static bool
208asn1_buf_is_cstr_compatible(const mbedtls_asn1_buf *asn1_buf)
209{
210 if (!(asn1_buf->tag == MBEDTLS_ASN1_UTF8_STRING || asn1_buf->tag == MBEDTLS_ASN1_PRINTABLE_STRING
211 || asn1_buf->tag == MBEDTLS_ASN1_IA5_STRING))
212 {
213 return false;
214 }
215 for (size_t i = 0; i < asn1_buf->len; i++)
216 {
217 if (asn1_buf->p[i] == '\0')
218 {
219 return false;
220 }
221 }
222 return true;
223}
224
225#if defined(__GNUC__) || defined(__clang__)
226#pragma GCC diagnostic push
227#pragma GCC diagnostic ignored "-Wsign-conversion"
228#endif
229
231backend_x509_get_username(char *cn, size_t cn_len, char *x509_username_field, mbedtls_x509_crt *cert)
232{
233 ASSERT(cn != NULL && cn_len > 0 && cert != NULL);
234
235 if (x509_username_field == NULL)
236 {
237 goto fail;
238 }
239
240 if (strcmp(x509_username_field, "serialNumber") == 0)
241 {
242 if (cn_len < 2)
243 {
244 goto fail;
245 }
246 cn[0] = '0';
247 cn[1] = 'x';
248 size_t cn_index = 2;
249 bool leading_zeros = true;
250 for (size_t i = 0; i < cert->serial.len; i++)
251 {
252 uint8_t serial_byte = cert->serial.p[i];
253 if (leading_zeros && serial_byte == 0)
254 {
255 continue;
256 }
257 leading_zeros = false;
258 if (cn_index > cn_len - 3)
259 {
260 goto fail;
261 }
262 snprintf(&cn[cn_index], cn_len - cn_index, "%02X", serial_byte);
263 cn_index += 2;
264 }
265 return SUCCESS;
266 }
267
268 const char *field_oid = fieldname_to_oid(x509_username_field);
269 if (field_oid == NULL)
270 {
271 goto fail;
272 }
273
274 /* Find field_oid in the subject name. */
275 mbedtls_x509_name *name = NULL;
276 mbedtls_x509_name *next = &cert->subject;
277 while (next != NULL)
278 {
279 if (strlen(field_oid) == next->oid.len
280 && 0 == memcmp(next->oid.p, field_oid, next->oid.len))
281 {
282 name = next;
283 }
284
285 next = next->next;
286 }
287
288 /* Not found, return an error if this is the peer's certificate */
289 if (name == NULL)
290 {
291 goto fail;
292 }
293
294 if (!asn1_buf_is_cstr_compatible(&name->val))
295 {
296 goto fail;
297 }
298
299 /* Check that we have room in the buffer, including the terminating '/0' byte. */
300 if (cn_len <= name->val.len)
301 {
302 goto fail;
303 }
304
305 memcpy(cn, name->val.p, name->val.len);
306 cn[name->val.len] = '\0';
307
308 return SUCCESS;
309
310fail:
311 cn[0] = '\0';
312 return FAILURE;
313}
314
315/* Mbed TLS 4 has no function to print the certificate serial number and does
316 * not expose the bignum functions anymore. So in order to write the serial
317 * number as a decimal string, we implement bignum % 10 and bignum / 10. */
318static char
319bignum_mod_10(const uint8_t *bignum, size_t bignum_length)
320{
321 int result = 0;
322 for (size_t i = 0; i < bignum_length; i++)
323 {
324 result = (result * 256) % 10;
325 result = (result + bignum[i]) % 10;
326 }
327 return (char)result;
328}
329
330/* Divide bignum by 10 rounded down, in place. */
331static void
332bignum_div_10(uint8_t *bignum, size_t *bignum_length)
333{
334 /*
335 * Some intuition for the algorithm below:
336 *
337 * We want to calculate
338 *
339 * (bignum[0] * 256^n + bignum[1] * 256^(n-1) + ... + bignum[n]) / 10.
340 *
341 * Let remainder = bignum[0] % 10 and carry = remainder * 256.
342 * Then we can write the above as
343 *
344 * (bignum[0] / 10) * 256^n
345 * + ((carry + bignum[1]) * 256^(n-1) + ... + bignum[n]) / 10.
346 *
347 * So now we have the first byte of our result. The second byte will be
348 * (carry + bignum[1]) / 10. Note that this fits into one byte because
349 * 0 <= remainder < 10. We calculate the next remainder and carry as
350 * remainder = (carry + bignum[1]) % 10 and carry = remainder * 256 and
351 * move on to the next byte until we are done.
352 */
353 size_t new_length = 0;
354 int carry = 0;
355 for (size_t i = 0; i < *bignum_length; i++)
356 {
357 uint8_t next_byte = (uint8_t)((bignum[i] + carry) / 10);
358 int remainder = (bignum[i] + carry) % 10;
359 carry = remainder * 256;
360
361 /* Write the byte unless it's a leading zero. */
362 if (new_length != 0 || next_byte != 0)
363 {
364 bignum[new_length++] = next_byte;
365 }
366 }
367 *bignum_length = new_length;
368}
369
370/* Write the decimal representation of bignum to out, if enough space is available.
371 * Returns the number of bytes needed in out, or 0 on error. To calculate the
372 * necessary buffer size, the function can be called with out = NULL. */
373static size_t
374write_bignum(char *out, size_t out_size, const uint8_t *bignum, size_t bignum_length)
375{
376 if (bignum_length == 0)
377 {
378 /* We want out to be "0". */
379 if (out != NULL)
380 {
381 if (out_size >= 2)
382 {
383 out[0] = '0';
384 out[1] = '\0';
385 }
386 else if (out_size > 0)
387 {
388 out[0] = '\0';
389 }
390 }
391 return 2;
392 }
393
394 uint8_t *bignum_copy = malloc(bignum_length);
395 if (bignum_copy == NULL)
396 {
397 return 0;
398 }
399 memcpy(bignum_copy, bignum, bignum_length);
400
401 size_t bytes_needed = 0;
402 size_t bytes_written = 0;
403 while (bignum_length > 0)
404 {
405 /* We're writing the digits in reverse order. We put them in the right order later. */
406 char digit = bignum_mod_10(bignum_copy, bignum_length);
407 if (out != NULL && bytes_written < out_size - 1)
408 {
409 out[bytes_written++] = '0' + (char)digit;
410 }
411 bytes_needed += 1;
412 bignum_div_10(bignum_copy, &bignum_length);
413 }
414
415 if (out != NULL)
416 {
417 if (bytes_written == bytes_needed)
418 {
419 /* We had space for all digits. Now reverse them. */
420 for (size_t i = 0; i < bytes_written / 2; i++)
421 {
422 char tmp = out[i];
423 out[i] = out[bytes_written - 1 - i];
424 out[bytes_written - 1 - i] = tmp;
425 }
426 out[bytes_written] = '\0';
427 }
428 else if (out_size > 0)
429 {
430 out[0] = '\0';
431 }
432 }
433 bytes_needed += 1;
434
435 free(bignum_copy);
436 return bytes_needed;
437}
438
439char *
440backend_x509_get_serial(mbedtls_x509_crt *cert, struct gc_arena *gc)
441{
442 char *buf = NULL;
443 size_t buflen = 0;
444
445 buflen = write_bignum(NULL, 0, cert->serial.p, cert->serial.len);
446 if (buflen == 0)
447 {
448 msg(M_WARN, "Failed to write serial to string.");
449 return NULL;
450 }
451 buf = gc_malloc(buflen, true, gc);
452 if (write_bignum(buf, buflen, cert->serial.p, cert->serial.len) != buflen)
453 {
454 msg(M_WARN, "Failed to write serial to string.");
455 return NULL;
456 }
457 return buf;
458}
459
460char *
461backend_x509_get_serial_hex(mbedtls_x509_crt *cert, struct gc_arena *gc)
462{
463 char *buf = NULL;
464 size_t len = cert->serial.len * 3 + 1;
465
466 buf = gc_malloc(len, true, gc);
467
468 if (mbedtls_x509_serial_gets(buf, len - 1, &cert->serial) < 0)
469 {
470 buf = NULL;
471 }
472
473 return buf;
474}
475
477backend_x509_write_pem(openvpn_x509_cert_t *cert, const char *filename)
478{
479 /* mbed TLS does not make it easy to write a certificate in PEM format.
480 * The only way is to directly access the DER encoded raw certificate
481 * and PEM encode it ourselves */
482
483 struct gc_arena gc = gc_new();
484 /* just do a very loose upper bound for the base64 based PEM encoding
485 * using 3 times the space for the base64 and 100 bytes for the
486 * headers and footer */
487 struct buffer pem = alloc_buf_gc(cert->raw.len * 3 + 100, &gc);
488
489 struct buffer der = { 0 };
490 buf_set_read(&der, cert->raw.p, cert->raw.len);
491
492 if (!crypto_pem_encode("CERTIFICATE", &pem, &der, &gc))
493 {
494 goto err;
495 }
496
497 if (!buffer_write_file(filename, &pem))
498 {
499 goto err;
500 }
501
502 gc_free(&gc);
503 return SUCCESS;
504err:
505 msg(D_TLS_DEBUG_LOW, "Error writing X509 certificate to file %s", filename);
506 gc_free(&gc);
507 return FAILURE;
508}
509
510static struct buffer
511x509_get_fingerprint(const mbedtls_md_info_t *md_info, mbedtls_x509_crt *cert, struct gc_arena *gc)
512{
513 const size_t md_size = mbedtls_md_get_size(md_info);
514 struct buffer fingerprint = alloc_buf_gc(md_size, gc);
515 mbedtls_md(md_info, cert->raw.p, cert->raw.len, BPTR(&fingerprint));
516 ASSERT(buf_inc_len(&fingerprint, (int)md_size));
517 return fingerprint;
518}
519
520struct buffer
521x509_get_sha1_fingerprint(mbedtls_x509_crt *cert, struct gc_arena *gc)
522{
523 return x509_get_fingerprint(mbedtls_md_info_from_type(MBEDTLS_MD_SHA1), cert, gc);
524}
525
526struct buffer
527x509_get_sha256_fingerprint(mbedtls_x509_crt *cert, struct gc_arena *gc)
528{
529 return x509_get_fingerprint(mbedtls_md_info_from_type(MBEDTLS_MD_SHA256), cert, gc);
530}
531
532char *
533x509_get_subject(mbedtls_x509_crt *cert, struct gc_arena *gc)
534{
535 char tmp_subject[MAX_SUBJECT_LENGTH] = { 0 };
536 char *subject = NULL;
537
538 int ret = 0;
539
540 ret = mbedtls_x509_dn_gets(tmp_subject, MAX_SUBJECT_LENGTH - 1, &cert->subject);
541 if (ret > 0)
542 {
543 /* Allocate the required space for the subject */
544 subject = string_alloc(tmp_subject, gc);
545 }
546
547 return subject;
548}
549
550static void
551do_setenv_x509(struct env_set *es, const char *name, char *value, int depth)
552{
553 char *name_expand;
554 size_t name_expand_size;
555
556 string_mod(value, CC_ANY, CC_CRLF, '?');
557 msg(D_X509_ATTR, "X509 ATTRIBUTE name='%s' value='%s' depth=%d", name, value, depth);
558 name_expand_size = 64 + strlen(name);
559 name_expand = (char *)malloc(name_expand_size);
560 check_malloc_return(name_expand);
561 snprintf(name_expand, name_expand_size, "X509_%d_%s", depth, name);
562 setenv_str(es, name_expand, value);
563 free(name_expand);
564}
565
566static char *
567asn1_buf_to_c_string(const mbedtls_asn1_buf *orig, struct gc_arena *gc)
568{
569 char *val;
570
571 if (!asn1_buf_is_cstr_compatible(orig))
572 {
573 return string_alloc("ERROR: Unsupported string type or embedded null bytes.", gc);
574 }
575 val = gc_malloc(orig->len + 1, false, gc);
576 memcpy(val, orig->p, orig->len);
577 val[orig->len] = '\0';
578 return val;
579}
580
581static inline int
582oid_get_attr_short_name(const mbedtls_asn1_buf *oid, const char **desc)
583{
584 /* The relevant OIDs all have equal length. */
585 if (oid->tag != MBEDTLS_ASN1_OID || oid->len != strlen(MBEDTLS_OID_AT_CN))
586 {
587 *desc = NULL;
588 return -1;
589 }
590
591 if (memcmp(oid->p, MBEDTLS_OID_AT_CN, oid->len) == 0)
592 {
593 *desc = "CN";
594 }
595 else if (memcmp(oid->p, MBEDTLS_OID_AT_SUR_NAME, oid->len) == 0)
596 {
597 *desc = "SN";
598 }
599 else if (memcmp(oid->p, MBEDTLS_OID_AT_SERIAL_NUMBER, oid->len) == 0)
600 {
601 *desc = "serialNumber";
602 }
603 else if (memcmp(oid->p, MBEDTLS_OID_AT_COUNTRY, oid->len) == 0)
604 {
605 *desc = "C";
606 }
607 else if (memcmp(oid->p, MBEDTLS_OID_AT_LOCALITY, oid->len) == 0)
608 {
609 *desc = "L";
610 }
611 else if (memcmp(oid->p, MBEDTLS_OID_AT_STATE, oid->len) == 0)
612 {
613 *desc = "ST";
614 }
615 else if (memcmp(oid->p, MBEDTLS_OID_AT_ORGANIZATION, oid->len) == 0)
616 {
617 *desc = "O";
618 }
619 else if (memcmp(oid->p, MBEDTLS_OID_AT_ORG_UNIT, oid->len) == 0)
620 {
621 *desc = "OU";
622 }
623 else if (memcmp(oid->p, MBEDTLS_OID_AT_TITLE, oid->len) == 0)
624 {
625 *desc = "title";
626 }
627 else if (memcmp(oid->p, MBEDTLS_OID_AT_POSTAL_ADDRESS, oid->len) == 0)
628 {
629 *desc = "postalAddress";
630 }
631 else if (memcmp(oid->p, MBEDTLS_OID_AT_POSTAL_CODE, oid->len) == 0)
632 {
633 *desc = "postalCode";
634 }
635 else if (memcmp(oid->p, MBEDTLS_OID_AT_GIVEN_NAME, oid->len) == 0)
636 {
637 *desc = "GN";
638 }
639 else if (memcmp(oid->p, MBEDTLS_OID_AT_INITIALS, oid->len) == 0)
640 {
641 *desc = "initials";
642 }
643 else if (memcmp(oid->p, MBEDTLS_OID_AT_GENERATION_QUALIFIER, oid->len) == 0)
644 {
645 *desc = "generationQualifier";
646 }
647 else if (memcmp(oid->p, MBEDTLS_OID_AT_UNIQUE_IDENTIFIER, oid->len) == 0)
648 {
649 *desc = "uniqueIdentifier";
650 }
651 else if (memcmp(oid->p, MBEDTLS_OID_AT_DN_QUALIFIER, oid->len) == 0)
652 {
653 *desc = "dnQualifier";
654 }
655 else if (memcmp(oid->p, MBEDTLS_OID_AT_PSEUDONYM, oid->len) == 0)
656 {
657 *desc = "pseudonym";
658 }
659 else
660 {
661 *desc = NULL;
662 return -1;
663 }
664 return 0;
665}
666
667static void
668do_setenv_name(struct env_set *es, const struct x509_track *xt, const mbedtls_x509_crt *cert,
669 int depth, struct gc_arena *gc)
670{
671 const mbedtls_x509_name *xn;
672 for (xn = &cert->subject; xn != NULL; xn = xn->next)
673 {
674 const char *xn_short_name = NULL;
675 if (0 == oid_get_attr_short_name(&xn->oid, &xn_short_name)
676 && 0 == strcmp(xt->name, xn_short_name))
677 {
678 char *val_str = asn1_buf_to_c_string(&xn->val, gc);
679 do_setenv_x509(es, xt->name, val_str, depth);
680 }
681 }
682}
683
684void
685x509_track_add(const struct x509_track **ll_head, const char *name, msglvl_t msglevel,
686 struct gc_arena *gc)
687{
688 struct x509_track *xt;
689 ALLOC_OBJ_CLEAR_GC(xt, struct x509_track, gc);
690 if (*name == '+')
691 {
692 xt->flags |= XT_FULL_CHAIN;
693 ++name;
694 }
695 xt->name = name;
696 xt->next = *ll_head;
697 *ll_head = xt;
698}
699
700void
701x509_setenv_track(const struct x509_track *xt, struct env_set *es, const int depth,
702 mbedtls_x509_crt *cert)
703{
704 struct gc_arena gc = gc_new();
705 while (xt)
706 {
707 if (depth == 0 || (xt->flags & XT_FULL_CHAIN))
708 {
709 if (0 == strcmp(xt->name, "SHA1") || 0 == strcmp(xt->name, "SHA256"))
710 {
711 /* Fingerprint is not part of X509 structure */
712 struct buffer cert_hash;
713 char *fingerprint;
714
715 if (0 == strcmp(xt->name, "SHA1"))
716 {
718 }
719 else
720 {
722 }
723
724 fingerprint =
725 format_hex_ex(BPTR(&cert_hash), BLEN(&cert_hash), 0, 1 | FHE_CAPS, ":", &gc);
726 do_setenv_x509(es, xt->name, fingerprint, depth);
727 }
728 else
729 {
730 do_setenv_name(es, xt, cert, depth, &gc);
731 }
732 }
733 xt = xt->next;
734 }
735 gc_free(&gc);
736}
737
738/*
739 * Save X509 fields to environment, using the naming convention:
740 *
741 * X509_{cert_depth}_{name}={value}
742 */
743void
744x509_setenv(struct env_set *es, int cert_depth, mbedtls_x509_crt *cert)
745{
746 const mbedtls_x509_name *name;
747 char s[128] = { 0 };
748
749 name = &cert->subject;
750
751 while (name != NULL)
752 {
753 char name_expand[64 + 8];
754 const char *shortname;
755
756 if (0 == oid_get_attr_short_name(&name->oid, &shortname))
757 {
758 snprintf(name_expand, sizeof(name_expand), "X509_%d_%s", cert_depth, shortname);
759 }
760 else
761 {
762 snprintf(name_expand, sizeof(name_expand), "X509_%d_\?\?", cert_depth);
763 }
764
765 size_t i;
766 for (i = 0; i < name->val.len; i++)
767 {
768 if (i >= sizeof(s) - 1)
769 {
770 break;
771 }
772
773 const unsigned char c = name->val.p[i];
774 if (c < 32 || c == 127 || (c > 128 && c < 160))
775 {
776 s[i] = '?';
777 }
778 else
779 {
780 s[i] = c;
781 }
782 }
783 s[i] = '\0';
784
785 /* Check both strings, set environment variable */
786 string_mod(name_expand, CC_PRINT, CC_CRLF, '_');
787 string_mod((char *)s, CC_PRINT, CC_CRLF, '_');
788 setenv_str_incr(es, name_expand, (char *)s);
789
790 name = name->next;
791 }
792}
793
794#if defined(__GNUC__) || defined(__clang__)
795#pragma GCC diagnostic pop
796#endif
797
798/* Dummy function because Netscape certificate types are not supported in OpenVPN with mbedtls.
799 * Returns SUCCESS if usage is NS_CERT_CHECK_NONE, FAILURE otherwise. */
801x509_verify_ns_cert_type(mbedtls_x509_crt *cert, const int cert_type)
802{
803 if (cert_type == NS_CERT_CHECK_NONE)
804 {
805 return SUCCESS;
806 }
807
808 return FAILURE;
809}
810
812x509_verify_cert_ku(mbedtls_x509_crt *cert, const unsigned int *const expected_ku, size_t expected_len)
813{
814 msg(D_HANDSHAKE, "Validating certificate key usage");
815
816 if (!mbedtls_x509_crt_has_ext_type(cert, MBEDTLS_X509_EXT_KEY_USAGE))
817 {
818 msg(D_TLS_ERRORS, "ERROR: Certificate does not have key usage extension");
819 return FAILURE;
820 }
821
822 if (expected_ku[0] == OPENVPN_KU_REQUIRED)
823 {
824 /* Extension required, value checked by TLS library */
825 return SUCCESS;
826 }
827
828 result_t fFound = FAILURE;
829 for (size_t i = 0; SUCCESS != fFound && i < expected_len; i++)
830 {
831 if (expected_ku[i] != 0 && 0 == mbedtls_x509_crt_check_key_usage(cert, expected_ku[i]))
832 {
833 fFound = SUCCESS;
834 }
835 }
836
837 if (fFound != SUCCESS)
838 {
839 msg(D_TLS_ERRORS, "ERROR: Certificate has invalid key usage, expected one of:");
840 for (size_t i = 0; i < expected_len && expected_ku[i]; i++)
841 {
842 msg(D_TLS_ERRORS, " * %04x", expected_ku[i]);
843 }
844 }
845
846 return fFound;
847}
848
849static inline int
850oid_get_extended_key_usage(const mbedtls_asn1_buf *oid, const char **desc)
851{
852 /* The relevant OIDs all have equal length. */
853 if (oid->tag != MBEDTLS_ASN1_OID || oid->len != strlen(MBEDTLS_OID_SERVER_AUTH))
854 {
855 *desc = NULL;
856 return -1;
857 }
858
859 if (memcmp(oid->p, MBEDTLS_OID_SERVER_AUTH, oid->len) == 0)
860 {
861 *desc = "TLS Web Server Authentication";
862 }
863 else if (memcmp(oid->p, MBEDTLS_OID_CLIENT_AUTH, oid->len) == 0)
864 {
865 *desc = "TLS Web Client Authentication";
866 }
867 else if (memcmp(oid->p, MBEDTLS_OID_CODE_SIGNING, oid->len) == 0)
868 {
869 *desc = "Code Signing";
870 }
871 else if (memcmp(oid->p, MBEDTLS_OID_EMAIL_PROTECTION, oid->len) == 0)
872 {
873 *desc = "E-mail Protection";
874 }
875 else if (memcmp(oid->p, MBEDTLS_OID_TIME_STAMPING, oid->len) == 0)
876 {
877 *desc = "Time Stamping";
878 }
879 else if (memcmp(oid->p, MBEDTLS_OID_OCSP_SIGNING, oid->len) == 0)
880 {
881 *desc = "OCSP Signing";
882 }
883 else
884 {
885 *desc = NULL;
886 return -1;
887 }
888
889 return 0;
890}
891
893x509_verify_cert_eku(mbedtls_x509_crt *cert, const char *const expected_oid)
894{
895 result_t fFound = FAILURE;
896
897 if (!mbedtls_x509_crt_has_ext_type(cert, MBEDTLS_X509_EXT_EXTENDED_KEY_USAGE))
898 {
899 msg(D_HANDSHAKE, "Certificate does not have extended key usage extension");
900 }
901 else
902 {
903 mbedtls_x509_sequence *oid_seq = &(cert->ext_key_usage);
904
905 msg(D_HANDSHAKE, "Validating certificate extended key usage");
906 while (oid_seq != NULL)
907 {
908 mbedtls_x509_buf *oid = &oid_seq->buf;
909 char oid_num_str[1024];
910 const char *oid_str;
911
912 if (0 == oid_get_extended_key_usage(oid, &oid_str))
913 {
914 msg(D_HANDSHAKE, "++ Certificate has EKU (str) %s, expects %s", oid_str,
915 expected_oid);
916 if (!strcmp(expected_oid, oid_str))
917 {
918 fFound = SUCCESS;
919 break;
920 }
921 }
922
923 if (0 < mbedtls_oid_get_numeric_string(oid_num_str, sizeof(oid_num_str), oid))
924 {
925 msg(D_HANDSHAKE, "++ Certificate has EKU (oid) %s, expects %s", oid_num_str,
926 expected_oid);
927 if (!strcmp(expected_oid, oid_num_str))
928 {
929 fFound = SUCCESS;
930 break;
931 }
932 }
933 oid_seq = oid_seq->next;
934 }
935 }
936
937 return fFound;
938}
939
940bool
941tls_verify_crl_missing(const struct tls_options *opt)
942{
943 if (opt->crl_file && !(opt->ssl_flags & SSLF_CRL_VERIFY_DIR)
944 && (opt->ssl_ctx->crl == NULL || opt->ssl_ctx->crl->version == 0))
945 {
946 return true;
947 }
948 return false;
949}
950
951#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:285
void chomp(char *str)
Remove trailing newline and carriage-return characters from a string.
Definition buffer.c:596
void * gc_malloc(size_t size, bool clear, struct gc_arena *a)
Allocate memory and, optionally, zero it.
Definition buffer.c:321
struct buffer alloc_buf_gc(size_t size, struct gc_arena *gc)
Allocate a buffer of the given size under garbage collection.
Definition buffer.c:77
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)
Format a binary buffer as a hex string.
Definition buffer.c:460
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:1021
bool checked_snprintf(char *str, size_t size, const char *format,...)
Like snprintf() but returns an boolean.
Definition buffer.c:1150
char * string_alloc(const char *str, struct gc_arena *gc)
Duplicate a string, allocating memory under garbage collection.
Definition buffer.c:618
#define CC_ANY
any character
Definition buffer.h:1686
#define BPTR(buf)
Return a pointer to the start of the buffer content.
Definition buffer.h:139
static bool buf_inc_len(struct buffer *buf, int inc)
Increase or decrease the length of a buffer.
Definition buffer.h:1119
#define CC_CRLF
carriage return or newline
Definition buffer.h:1723
static void buf_set_read(struct buffer *buf, const uint8_t *data, size_t size)
Initialise a buffer with an externally provided read-only memory region.
Definition buffer.h:687
#define ALLOC_OBJ_CLEAR_GC(dptr, type, gc)
Allocate and zero-initialise a garbage-collected object of the given type.
Definition buffer.h:2132
#define BLEN(buf)
Return the length of the buffer content in bytes.
Definition buffer.h:151
static void check_malloc_return(void *p)
Abort if a memory allocation returned NULL.
Definition buffer.h:2144
static void gc_free(struct gc_arena *a)
Free all allocations in a garbage collection arena.
Definition buffer.h:1974
#define CC_PRINT
printable (>= 32, != 127)
Definition buffer.h:1694
#define FHE_CAPS
Flag for format_hex_ex(): output hex digits in upper case.
Definition buffer.h:927
static struct gc_arena gc_new(void)
Allocate and return a new, empty garbage collection arena.
Definition buffer.h:1958
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 backend interface using the TF-PSA-Crypto library part of Mbed TLS 4.
void setenv_str(struct env_set *es, const char *name, const char *value)
Definition env_set.c:305
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:327
#define D_TLS_DEBUG_LOW
Definition errlevel.h:75
#define D_X509_ATTR
Definition errlevel.h:100
#define D_HANDSHAKE
Definition errlevel.h:70
#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:221
#define M_WARN
Definition error.h:92
#define SSLF_CRL_VERIFY_DIR
Definition ssl_common.h:433
result_t verify_cert(struct tls_session *session, openvpn_x509_cert_t *cert, int cert_depth)
Definition ssl_verify.c:591
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 cert_type)
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:70
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:71
int len
Length in bytes of the actual content within the allocated memory.
Definition buffer.h:76
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:127
unsigned int ssl_flags
Definition ssl_common.h:439
struct tls_root_ctx * ssl_ctx
Definition ssl_common.h:310
const char * crl_file
Definition ssl_common.h:360
mbedtls_x509_crl * crl
Certificate Revocation List.
Definition ssl_mbedtls.h:92
Security parameter state of a single session within a VPN tunnel.
Definition ssl_common.h:497
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 gc_arena gc
Definition test_ssl.c:138