OpenVPN
test_ssl.c
Go to the documentation of this file.
1/*
2 * OpenVPN -- An application to securely tunnel IP networks
3 * over a single 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) 2023-2026 OpenVPN Inc <sales@openvpn.net>
9 *
10 * This program is free software; you can redistribute it and/or modify
11 * it under the terms of the GNU General Public License version 2
12 * as published by the Free Software Foundation.
13 *
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
18 *
19 * You should have received a copy of the GNU General Public License along
20 * with this program; if not, see <https://www.gnu.org/licenses/>.
21 */
22
23#ifdef HAVE_CONFIG_H
24#include "config.h"
25#endif
26
27#include "syshead.h"
28
29#include <stdio.h>
30#include <stdlib.h>
31#include <stdarg.h>
32#include <string.h>
33#include <setjmp.h>
34#include <cmocka.h>
35
36#include "crypto.h"
37#include "crypto_epoch.h"
38#include "options.h"
39#include "ssl_backend.h"
40#include "options_util.h"
41
42#include "mock_msg.h"
43#include "mss.h"
44#include "ssl_verify_backend.h"
45#include "win32.h"
46#include "test_common.h"
47#include "ssl.h"
48#include "buffer.h"
49#include "cert_data.h"
50#include "packet_id.h"
51#include "ssl_util.h"
52#include "ssl_verify.h"
53#include "openvpn.h"
54
55#include "test_acc.h"
56
57/* Mock function to be allowed to include win32.c which is required for
58 * getting the temp directory */
59#ifdef _WIN32
60struct signal_info siginfo_static; /* GLOBAL */
61
62const char *
63strerror_win32(DWORD errnum, struct gc_arena *gc)
64{
65 ASSERT(false);
66}
67
68void
69throw_signal(const int signum)
70{
71 ASSERT(false);
72}
73#endif
74
75#if defined(ENABLE_CRYPTO_OPENSSL) && (OPENSSL_VERSION_NUMBER > 0x30000000L)
76#define HAVE_OPENSSL_STORE
77#endif
78
79/* stubs for some unused functions instead of pulling in too many dependencies */
80bool
81get_user_pass_cr(struct user_pass *up, const char *auth_file, const char *prefix,
82 const unsigned int flags, const char *auth_challenge)
83{
84 return false;
85}
86void
87purge_user_pass(struct user_pass *up, bool force)
88{
89 return;
90}
91void
95
96/* Define a dummy dco cipher option to avoid linking against all the DCO
97 * units */
98#if defined(ENABLE_DCO)
99const char *
101{
102 return "AES-192-GCM:AES-128-CBC:AES-256-GCM:AES-128-GCM:CHACHA20-POLY1305";
103}
104#endif
105
106/* generated using
107 * openssl req -x509 -newkey ec -pkeyopt ec_paramgen_curve:secp384r1 -keyout - \
108 * -noenc -sha256 -days 3650 -subj '/CN=ovpn-test-secp384r1' -nodes \
109 * -addext 'subjectAltName=DNS:unittest.example.com' \
110 * -addext 'extendedKeyUsage=clientAuth'
111 */
112static const char *const unittest_cert =
113 "-----BEGIN CERTIFICATE-----\n"
114 "MIICBjCCAYygAwIBAgIUFoXgpP4beykV7tpgrjHQTWPGi4cwCgYIKoZIzj0EAwIw\n"
115 "HjEcMBoGA1UEAwwTb3Zwbi10ZXN0LXNlY3AzODRyMTAeFw0yNTA5MDgxMzExNTBa\n"
116 "Fw0zNTA5MDYxMzExNTBaMB4xHDAaBgNVBAMME292cG4tdGVzdC1zZWNwMzg0cjEw\n"
117 "djAQBgcqhkjOPQIBBgUrgQQAIgNiAAQVDmf+TZB3rW6zqWFox606u/PhA93ysX/h\n"
118 "1s2xyq9+QGzIdE/hks6p/Yzyu7RLOUjxvO0J45RHcYmo67DlvSOi496T3zrgvp1H\n"
119 "KfHD5ohMyvzw0+e8lmjJqJjn+PegMkOjgYowgYcwHQYDVR0OBBYEFCH1eYnaV8fh\n"
120 "E3Bv7lyrlYu24eoVMB8GA1UdIwQYMBaAFCH1eYnaV8fhE3Bv7lyrlYu24eoVMA8G\n"
121 "A1UdEwEB/wQFMAMBAf8wHwYDVR0RBBgwFoIUdW5pdHRlc3QuZXhhbXBsZS5jb20w\n"
122 "EwYDVR0lBAwwCgYIKwYBBQUHAwIwCgYIKoZIzj0EAwIDaAAwZQIxAL7q7jcwTOuq\n"
123 "5sp0Beq81Vnznd3gsDZYNs1OYRWH33xergDVKlBb6kCwus0dhghtVAIwIgT4ytkY\n"
124 "oAPx8LB3oP8ubEu1ue6V9jZln/cCiLyXDDtaiJOZHtDqHGfHqvc6rAok\n"
125 "-----END CERTIFICATE-----\n";
126
127static const char *const unittest_key =
128 "-----BEGIN PRIVATE KEY-----\n"
129 "MIG2AgEAMBAGByqGSM49AgEGBSuBBAAiBIGeMIGbAgEBBDAXBC7tpa9UepoMVZlM\n"
130 "OxUubkECGK7aWFebxDc3UPoEQemEPMOCdkWBSU/t7Mm4R66hZANiAAQVDmf+TZB3\n"
131 "rW6zqWFox606u/PhA93ysX/h1s2xyq9+QGzIdE/hks6p/Yzyu7RLOUjxvO0J45RH\n"
132 "cYmo67DlvSOi496T3zrgvp1HKfHD5ohMyvzw0+e8lmjJqJjn+PegMkM=\n"
133 "-----END PRIVATE KEY-----\n";
134
135
136static struct
137{
138 struct gc_arena gc;
139 const char *certfile;
140 const char *keyfile;
142
143static int
144init(void **state)
145{
146 (void)state;
147 global_state.gc = gc_new();
150
151 int certfd = open(global_state.certfile, O_RDWR);
152 int keyfd = open(global_state.keyfile, O_RDWR);
153 if (certfd < 0 || keyfd < 0)
154 {
155 fail_msg("make tmpfile for certificate or key data failed (error = %d)", errno);
156 }
157 /* Awkward casts required for MinGW with -O0 only */
158 assert_int_equal(write(certfd, unittest_cert, (unsigned int)strlen(unittest_cert)),
159 strlen(unittest_cert));
160 assert_int_equal(write(keyfd, unittest_key, (unsigned int)strlen(unittest_key)),
161 strlen(unittest_key));
162 close(certfd);
163 close(keyfd);
164 return 0;
165}
166
167static int
168cleanup(void **state)
169{
170 (void)state;
171 unlink(global_state.certfile);
172 unlink(global_state.keyfile);
174 return 0;
175}
176
177static void
179{
180 struct gc_arena gc = gc_new();
181
182 struct tls_root_ctx ctx = { 0 };
185
186 openvpn_x509_cert_t *cert = NULL;
187
188 /* we do not have methods to fetch certificates from ssl contexts, use
189 * internal TLS library methods for the unit test */
190#ifdef ENABLE_CRYPTO_OPENSSL
191 cert = SSL_CTX_get0_certificate(ctx.ctx);
192#elif defined(ENABLE_CRYPTO_MBEDTLS)
193 cert = ctx.crt_chain;
194#endif
195
196 const char *tmpfile = platform_create_temp_file(platform_get_tmp_dir(), "ut_pem", &gc);
197 backend_x509_write_pem(cert, tmpfile);
198
199 struct buffer exported_pem = buffer_read_from_file(tmpfile, &gc);
200 assert_string_equal(BSTR(&exported_pem), unittest_cert);
201
202 tls_ctx_free(&ctx);
203 unlink(tmpfile);
204 gc_free(&gc);
205}
206
207static void
209{
210 (void)state;
211 struct tls_root_ctx ctx = { 0 };
212
213 /* test loading of inlined cert and key.
214 * loading the key also checks that it matches the loaded certificate
215 */
218 assert_int_equal(tls_ctx_load_priv_file(&ctx, unittest_key, true), 0);
220
221 /* test loading of cert and key from file */
223 tls_ctx_load_cert_file(&ctx, global_state.certfile, false);
224 assert_int_equal(tls_ctx_load_priv_file(&ctx, global_state.keyfile, false), 0);
226}
227
228/* test loading cert and key using file:/path URI */
229static void
231{
232 (void)state;
233
234#if !defined(HAVE_OPENSSL_STORE)
235 skip();
236#else /* HAVE_OPENSSL_STORE */
237
238 struct tls_root_ctx ctx = { 0 };
239 const char *certfile = global_state.certfile;
240 const char *keyfile = global_state.keyfile;
241 struct gc_arena *gc = &global_state.gc;
242
243 struct buffer certuri = alloc_buf_gc(6 + strlen(certfile) + 1, gc); /* 6 bytes for "file:/" */
244 struct buffer keyuri = alloc_buf_gc(6 + strlen(keyfile) + 1, gc); /* 6 bytes for "file:/" */
245
246 /* Windows temp file path starts with drive letter -- add a leading slash for URI */
247#ifdef _WIN32
248 const char *lead = "/";
249#else
250 const char *lead = "";
251#endif /* _WIN32 */
252 assert_true(buf_printf(&certuri, "file:%s%s", lead, certfile));
253 assert_true(buf_printf(&keyuri, "file:%s%s", lead, keyfile));
254
255 /* On Windows replace any '\' in path by '/' required for URI */
256#ifdef _WIN32
257 string_mod(BSTR(&certuri), CC_ANY, CC_BACKSLASH, '/');
258 string_mod(BSTR(&keyuri), CC_ANY, CC_BACKSLASH, '/');
259#endif /* _WIN32 */
260
261 tls_ctx_new(&ctx);
262 tls_ctx_load_cert_file(&ctx, BSTR(&certuri), false);
263 assert_int_equal(tls_ctx_load_priv_file(&ctx, BSTR(&keyuri), false), 0);
264 tls_ctx_free(&ctx);
265#endif /* HAVE_OPENSSL_STORE */
266}
267
268#if defined(__GNUC__) || defined(__clang__)
269#pragma GCC diagnostic push
270#pragma GCC diagnostic ignored "-Wsign-conversion"
271#endif
272
273static void
275{
276 int overhead = 0;
277
278 /* tls-auth and tls-crypt */
279 overhead += 128;
280
281 /* TCP length field and opcode */
282 overhead += 3;
283
284 /* ACK array and remote SESSION ID (part of the ACK array) */
285 overhead += ACK_SIZE(RELIABLE_ACK_SIZE);
286
287 /* Previous OpenVPN version calculated the maximum size and buffer of a
288 * control frame depending on the overhead of the data channel frame
289 * overhead and limited its maximum size to 1250. Since control frames
290 * also need to fit into data channel buffer we have the same
291 * default of 1500 + 100 as data channel buffers have. Increasing
292 * control channel mtu beyond this limit also increases the data channel
293 * buffers */
294 int tls_mtu = 1500;
295 frame->buf.payload_size = tls_mtu + 100;
296
297 frame->buf.headroom = overhead;
298 frame->buf.tailroom = overhead;
299
300 frame->tun_mtu = tls_mtu;
301}
302
303static void
305{
306 struct gc_arena gc = gc_new();
307
308 /* initialise frame for the test */
309 struct frame frame;
311
312 struct buffer src = alloc_buf_gc(frame.buf.payload_size, &gc);
313 struct buffer work = alloc_buf_gc(BUF_SIZE(&frame), &gc);
314 struct buffer encrypt_workspace = alloc_buf_gc(BUF_SIZE(&frame), &gc);
315 struct buffer decrypt_workspace = alloc_buf_gc(BUF_SIZE(&frame), &gc);
316
317 /* init work */
319
320 update_time();
321
322 /* Test encryption, decryption for all packet sizes */
323 for (int i = 1; i <= frame.buf.payload_size; ++i)
324 {
325 /* msg(M_INFO, "TESTING ENCRYPT/DECRYPT of packet length=%d", i); */
326
327 /*
328 * Load src with random data.
329 */
330 ASSERT(buf_init(&src, 0));
331 ASSERT(i <= src.capacity);
332 src.len = i;
333 prng_bytes(BPTR(&src), BLEN(&src));
334
335 /* copy source to input buf */
336 struct buffer buf = work;
337 void *buf_p = buf_write_alloc(&buf, BLENZ(&src));
338 ASSERT(buf_p);
339 memcpy(buf_p, BPTR(&src), BLENZ(&src));
340
341 /* initialize work buffer with buf.headroom bytes of prepend capacity */
342 ASSERT(buf_init(&encrypt_workspace, frame.buf.headroom));
343
344 /* encrypt */
345 openvpn_encrypt(&buf, encrypt_workspace, co);
346
347 /* decrypt */
348 openvpn_decrypt(&buf, decrypt_workspace, co, &frame, BPTR(&buf));
349
350 /* compare */
351 assert_int_equal(buf.len, src.len);
352 assert_memory_equal(BPTR(&src), BPTR(&buf), i);
353 }
354 gc_free(&gc);
355}
356
357static void
359{
360 struct frame frame;
362
363 struct gc_arena gc = gc_new();
364 struct buffer encrypt_workspace = alloc_buf_gc(BUF_SIZE(&frame), &gc);
365 struct buffer decrypt_workspace = alloc_buf_gc(BUF_SIZE(&frame), &gc);
366 struct buffer work = alloc_buf_gc(BUF_SIZE(&frame), &gc);
367 struct buffer src = alloc_buf_gc(frame.buf.payload_size, &gc);
368 void *buf_p;
369
371
372 /*
373 * Load src with random data.
374 */
375 ASSERT(buf_init(&src, 0));
376 ASSERT(len <= src.capacity);
377 src.len = len;
378 prng_bytes(BPTR(&src), BLEN(&src));
379
380 /* copy source to input buf */
381 struct buffer buf = work;
382 buf_p = buf_write_alloc(&buf, BLENZ(&src));
383 ASSERT(buf_p);
384 memcpy(buf_p, BPTR(&src), BLENZ(&src));
385
386 ASSERT(buf_init(&encrypt_workspace, frame.buf.headroom));
387 openvpn_encrypt(&buf, encrypt_workspace, co);
388
389 /* decrypt */
390 openvpn_decrypt(&buf, decrypt_workspace, co, &frame, BPTR(&buf));
391
392 /* compare */
393 assert_int_equal(buf.len, src.len);
394 assert_memory_equal(BPTR(&src), BPTR(&buf), len);
395
396 gc_free(&gc);
397}
398
399
400static void
401check_aead_limits(struct crypto_options *co, bool chachapoly)
402{
403 /* Check that we correctly react when we have a nearing AEAD limits */
404
405 /* manually increase the send counter to be past
406 * the GCM usage limit */
407 co->key_ctx_bi.encrypt.plaintext_blocks = 0x1ull << 40;
408
409
410 bool epoch = (co->flags & CO_EPOCH_DATA_KEY_FORMAT);
411
412 int expected_epoch = epoch ? 4 : 0;
413
414 /* Ensure that we are still on the initial key (our init_crypto_options
415 * unit test method iterates the initial key to 4) or that it is 0 when
416 * epoch is not in use
417 */
418 assert_int_equal(co->key_ctx_bi.encrypt.epoch, expected_epoch);
419
420 encrypt_one_packet(co, 1000);
421
422 /* either epoch key has been updated or warning is enabled */
423 if (epoch && !chachapoly)
424 {
425 expected_epoch++;
426 }
427
428 assert_int_equal(co->key_ctx_bi.encrypt.epoch, expected_epoch);
429
430 if (!epoch)
431 {
432 /* Check always against the GCM usage limit here to see if that
433 * check works */
434 assert_true(
436 return;
437 }
438
439 /* Move to the end of the epoch data key send PID range, ChachaPoly
440 * should now also move to a new epoch data key */
442
443 encrypt_one_packet(co, 1000);
444 encrypt_one_packet(co, 1000);
445
446 expected_epoch++;
447 assert_int_equal(co->key_ctx_bi.encrypt.epoch, expected_epoch);
448}
449
450
451static struct crypto_options
452init_crypto_options(const char *cipher, const char *auth, bool epoch, struct key2 *statickey)
453{
454 struct key2 key2 = { .n = 2 };
455
456 if (statickey)
457 {
458 /* Use chosen static key instead of random key when defined */
459 key2 = *statickey;
460 }
461 else
462 {
463 prng_bytes(key2.keys[0].cipher, sizeof(key2.keys[0].cipher));
464 prng_bytes(key2.keys[0].hmac, sizeof(key2.keys[0].hmac));
465 prng_bytes(key2.keys[1].cipher, sizeof(key2.keys[1].cipher));
466 prng_bytes(key2.keys[1].hmac, sizeof(key2.keys)[1].hmac);
467 }
468
469 struct crypto_options co = { 0 };
470
471 struct key_type kt = create_kt(cipher, auth, "ssl-test");
472
473 if (epoch)
474 {
475 struct epoch_key e1 = { .epoch = 1, .epoch_key = { 0 } };
476 memcpy(e1.epoch_key, key2.keys[0].cipher, sizeof(e1.epoch_key));
478 epoch_init_key_ctx(&co, &kt, &e1, &e1, 5);
479
480 /* Do a little of dancing for the epoch_send_key_iterate to test
481 * that this works too */
485 }
486 else
487 {
488 init_key_ctx_bi(&co.key_ctx_bi, &key2, KEY_DIRECTION_BIDIRECTIONAL, &kt, "unit-test-ssl");
489 }
490 packet_id_init(&co.packet_id, 5, 5, "UNITTEST", 0);
491 return co;
492}
493
494static void
501
502/* This adds a few more methods than strictly necessary but this allows
503 * us to see which exact test was run from the backtrace of the test
504 * when it fails */
505static void
507{
508 bool ischacha = !strcmp(cipher, "ChaCha20-Poly1305");
509
510 struct crypto_options co = init_crypto_options(cipher, "none", true, NULL);
512 check_aead_limits(&co, ischacha);
514}
515
516static void
517run_data_channel_with_cipher(const char *cipher, const char *auth)
518{
519 bool ischacha = !strcmp(cipher, "ChaCha20-Poly1305");
520 struct crypto_options co = init_crypto_options(cipher, auth, false, NULL);
522 check_aead_limits(&co, ischacha);
524}
525
526
527static void
529{
530 run_data_channel_with_cipher("AES-128-GCM", "none");
531}
532
533static void
538
539static void
541{
542 run_data_channel_with_cipher("AES-192-GCM", "none");
543}
544
545static void
550
551static void
553{
554 run_data_channel_with_cipher("AES-256-GCM", "none");
555}
556
557static void
562
563static void
565{
566 run_data_channel_with_cipher("AES-128-CBC", "SHA256");
567}
568
569static void
571{
572 run_data_channel_with_cipher("AES-192-CBC", "SHA256");
573}
574
575static void
577{
578 run_data_channel_with_cipher("AES-256-CBC", "SHA256");
579}
580
581static void
583{
584 if (!cipher_valid("ChaCha20-Poly1305"))
585 {
586 skip();
587 return;
588 }
589
590 run_data_channel_with_cipher("ChaCha20-Poly1305", "none");
591}
592
593static void
595{
596 if (!cipher_valid("ChaCha20-Poly1305"))
597 {
598 skip();
599 return;
600 }
601
602 run_data_channel_with_cipher_epoch("ChaCha20-Poly1305");
603}
604
605static void
607{
608 if (!cipher_valid("BF-CBC"))
609 {
610 skip();
611 return;
612 }
613 run_data_channel_with_cipher("BF-CBC", "SHA1");
614}
615
616
617static struct key2
619{
620 struct key2 key2 = { .n = 2 };
621
622 const uint8_t key[] = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', '0', '1', '2',
623 '3', '4', '5', '6', '7', 'A', 'B', 'C', 'D', 'E', 'F',
624 'G', 'H', 'j', 'k', 'u', 'c', 'h', 'e', 'n', 'l' };
625
626 static_assert(sizeof(key) == 32, "Size of key should be 32 bytes");
627
628 /* copy the key a few times to ensure to have the size we need for
629 * Statickey but XOR it to not repeat it */
630 uint8_t keydata[sizeof(key2.keys)];
631
632 for (size_t i = 0; i < sizeof(key2.keys); i++)
633 {
634 keydata[i] = (uint8_t)(key[i % sizeof(key)] ^ i);
635 }
636
637 ASSERT(memcpy(key2.keys[0].cipher, keydata, sizeof(key2.keys[0].cipher)));
638 ASSERT(memcpy(key2.keys[0].hmac, keydata + 64, sizeof(key2.keys[0].hmac)));
639 ASSERT(memcpy(key2.keys[1].cipher, keydata + 128, sizeof(key2.keys[1].cipher)));
640 ASSERT(memcpy(key2.keys[1].hmac, keydata + 192, sizeof(key2.keys)[1].hmac));
641
642 return key2;
643}
644
645static void
647{
648 struct key2 key2 = create_key();
649
650 struct crypto_options co = init_crypto_options("AES-256-GCM", "none", epoch, &key2);
651
652 struct gc_arena gc = gc_new();
653
654 /* initialise frame for the test */
655 struct frame frame;
657
658 struct buffer src = alloc_buf_gc(frame.buf.payload_size, &gc);
659 struct buffer work = alloc_buf_gc(BUF_SIZE(&frame), &gc);
660 struct buffer encrypt_workspace = alloc_buf_gc(BUF_SIZE(&frame), &gc);
661 struct buffer decrypt_workspace = alloc_buf_gc(BUF_SIZE(&frame), &gc);
662 void *buf_p;
663
664 /* init work */
666
667 now = 0;
668
669 /*
670 * Load src with known data.
671 */
672 ASSERT(buf_init(&src, 0));
673 const char *plaintext = "The quick little fox jumps over the bureaucratic hurdles";
674
675 ASSERT(buf_write(&src, plaintext, strlen(plaintext)));
676
677 /* copy source to input buf */
678 struct buffer buf = work;
679 buf_p = buf_write_alloc(&buf, BLENZ(&src));
680 ASSERT(buf_p);
681 memcpy(buf_p, BPTR(&src), BLENZ(&src));
682
683 /* initialize work buffer with buf.headroom bytes of prepend capacity */
684 ASSERT(buf_init(&encrypt_workspace, frame.buf.headroom));
685
686 /* add packet opcode and peer id */
687 buf_write_u8(&encrypt_workspace, 7);
688 buf_write_u8(&encrypt_workspace, 0);
689 buf_write_u8(&encrypt_workspace, 0);
690 buf_write_u8(&encrypt_workspace, 23);
691
692 /* encrypt */
693 openvpn_encrypt(&buf, encrypt_workspace, &co);
694
695 /* separate buffer in authenticated data and encrypted data */
696 const uint8_t *ad_start = BPTR(&buf);
697 buf_advance(&buf, 4);
698
699 if (epoch)
700 {
701 uint8_t packetid1[8] = { 0, 0x04, 0, 0, 0, 0, 0, 1 };
702 assert_memory_equal(BPTR(&buf), packetid1, 8);
703 }
704 else
705 {
706 uint8_t packetid1[4] = { 0, 0, 0, 1 };
707 assert_memory_equal(BPTR(&buf), packetid1, 4);
708 }
709
710 if (epoch)
711 {
712 uint8_t *tag_location = BEND(&buf) - OPENVPN_AEAD_TAG_LENGTH;
713 const uint8_t exp_tag_epoch[16] = { 0x0f, 0xff, 0xf5, 0x91, 0x3d, 0x39, 0xd7, 0x5b,
714 0x18, 0x57, 0x3b, 0x57, 0x48, 0x58, 0x9a, 0x7d };
715
716 assert_memory_equal(tag_location, exp_tag_epoch, OPENVPN_AEAD_TAG_LENGTH);
717 }
718 else
719 {
720 uint8_t *tag_location = BPTR(&buf) + 4;
721 const uint8_t exp_tag_noepoch[16] = { 0x1f, 0xdd, 0x90, 0x8f, 0x0e, 0x9d, 0xc2, 0x5e,
722 0x79, 0xd8, 0x32, 0x02, 0x0d, 0x58, 0xe7, 0x3f };
723 assert_memory_equal(tag_location, exp_tag_noepoch, OPENVPN_AEAD_TAG_LENGTH);
724 }
725
726 /* Check some bytes at the beginning of the encrypted part */
727 if (epoch)
728 {
729 const uint8_t bytesat14[6] = { 0x36, 0xaa, 0xb4, 0xd4, 0x9c, 0xe6 };
730 assert_memory_equal(BPTR(&buf) + 14, bytesat14, sizeof(bytesat14));
731 }
732 else
733 {
734 const uint8_t bytesat30[6] = { 0xa8, 0x2e, 0x6b, 0x17, 0x06, 0xd9 };
735 assert_memory_equal(BPTR(&buf) + 30, bytesat30, sizeof(bytesat30));
736 }
737
738 /* decrypt */
739 openvpn_decrypt(&buf, decrypt_workspace, &co, &frame, ad_start);
740
741 /* compare */
742 assert_int_equal(buf.len, strlen(plaintext));
743 assert_memory_equal(BPTR(&buf), plaintext, strlen(plaintext));
744
746 gc_free(&gc);
747}
748
749static void
754
755static void
760
761#if defined(ENABLE_CRYPTO_MBEDTLS)
762static openvpn_x509_cert_t *
763get_certificate(const char *cert_str)
764{
765 mbedtls_x509_crt *cert;
766 ALLOC_OBJ_CLEAR(cert, mbedtls_x509_crt);
767 int ret = mbedtls_x509_crt_parse(cert, (const unsigned char *)cert_str,
768 strlen(cert_str) + 1);
769
770 assert_int_equal(ret, 0);
771 return cert;
772}
773
774static void
776{
777 mbedtls_x509_crt_free(cert);
778 free(cert);
779}
780#else
781static openvpn_x509_cert_t *
782get_certificate(const char *cert_str)
783{
784 BIO *in = BIO_new_mem_buf((char *)cert_str, -1);
785 assert_non_null(in);
786 X509 *cert = PEM_read_bio_X509(in, NULL, NULL, NULL);
787 assert_non_null(cert);
788 BIO_free(in);
789 return cert;
790}
791
792static void
794{
795 X509_free(cert);
796}
797#endif
798
799/* Generated with:
800 * openssl req -x509 -newkey ec -pkeyopt ec_paramgen_curve:secp384r1 -keyout - -noenc -sha256 -days 3650 \
801 * -subj '/CN=ovpn-test-secp384r1/O=OpenVPN Unit Test Example Corp./OU=Cert Details Dept.'
802 * -addext 'subjectAltName=DNS:unittest.example.com' -addext 'extendedKeyUsage=clientAuth' */
803static const char *cert_details_test_cert =
804 "-----BEGIN CERTIFICATE-----\n"
805 "MIICkzCCAhqgAwIBAgIUKDsZM+PApGdaD2QF9iYaxoFJAkowCgYIKoZIzj0EAwIw\n"
806 "ZTEcMBoGA1UEAwwTb3Zwbi10ZXN0LXNlY3AzODRyMTEoMCYGA1UECgwfT3BlblZQ\n"
807 "TiBVbml0IFRlc3QgRXhhbXBsZSBDb3JwLjEbMBkGA1UECwwSQ2VydCBEZXRhaWxz\n"
808 "IERlcHQuMB4XDTI2MDcwNzEwNTIxNloXDTM2MDcwNDEwNTIxNlowZTEcMBoGA1UE\n"
809 "AwwTb3Zwbi10ZXN0LXNlY3AzODRyMTEoMCYGA1UECgwfT3BlblZQTiBVbml0IFRl\n"
810 "c3QgRXhhbXBsZSBDb3JwLjEbMBkGA1UECwwSQ2VydCBEZXRhaWxzIERlcHQuMHYw\n"
811 "EAYHKoZIzj0CAQYFK4EEACIDYgAEOlKoQVk+wbBD6V/6kg+/oHfqF0Dq08LlCL+B\n"
812 "om4RhutG99QDrow251Ps+Ds/7LQYYRA8+hHyEFrmGM+j2o6KhS5K2uA6dIZL4zLK\n"
813 "vl0NeF2M61Z8tt/IjrFZd+CrEANco4GKMIGHMB0GA1UdDgQWBBSEyG6m+QdWazeg\n"
814 "0CHN7q0edJlqMjAfBgNVHSMEGDAWgBSEyG6m+QdWazeg0CHN7q0edJlqMjAPBgNV\n"
815 "HRMBAf8EBTADAQH/MB8GA1UdEQQYMBaCFHVuaXR0ZXN0LmV4YW1wbGUuY29tMBMG\n"
816 "A1UdJQQMMAoGCCsGAQUFBwMCMAoGCCqGSM49BAMCA2cAMGQCMCyK7aQcyKGW8BWQ\n"
817 "UOYqbJUJZJcviP6ACgJRzK6pgkqt9gY0E0Tb00Qh6D5dBV5i3wIwCMhSgpVJxDrc\n"
818 "pRfligoK8bmv4HEgnV6BDeoDYd41WVMpE9u1issQDHY0SnWC7d9q\n"
819 "-----END CERTIFICATE-----\n";
820const char *const cert_details_cname = "ovpn-test-secp384r1";
821const char *const cert_details_org = "OpenVPN Unit Test Example Corp.";
822const char *const cert_details_org_unit = "Cert Details Dept.";
823const char *const cert_details_serial_number = "229677570263950905252266749734450551528150860362";
824const char *const cert_details_serial_number_hex = "0x283B1933E3C0A4675A0F6405F6261AC68149024A";
825
826void
828{
830 struct gc_arena gc = gc_new();
831
832 const char *fp = backend_x509_get_serial_hex(cert, &gc);
833
834 /* we messed this up between TLS libraries. But let's at least notice in
835 * the future ...*/
836#if defined(ENABLE_CRYPTO_MBEDTLS)
837 assert_string_equal(fp, "28:3B:19:33:E3:C0:A4:67:5A:0F:64:05:F6:26:1A:C6:81:49:02:4A");
838#else
839 assert_string_equal(fp, "28:3b:19:33:e3:c0:a4:67:5a:0f:64:05:f6:26:1a:c6:81:49:02:4a");
840#endif
841
842 const char *sn = backend_x509_get_serial(cert, &gc);
843 assert_string_equal(sn, cert_details_serial_number);
844
845 char username[TLS_USERNAME_LEN + 1] = { 0 }; /* null-terminated */
846
847 int ret = backend_x509_get_username(username, sizeof(username), "CN", cert);
848
849 assert_string_equal(username, cert_details_cname);
850 assert_int_equal(ret, SUCCESS);
851
852 ret = backend_x509_get_username(username, sizeof(username), "serialNumber", cert);
853 assert_int_equal(ret, SUCCESS);
854 assert_string_equal(username, cert_details_serial_number_hex);
855
856 ret = backend_x509_get_username(username, sizeof(username), "O", cert);
857
858 assert_string_equal(username, cert_details_org);
859 assert_int_equal(ret, SUCCESS);
860
861 ret = backend_x509_get_username(username, sizeof(username), "OU", cert);
862
863 assert_string_equal(username, cert_details_org_unit);
864 assert_int_equal(ret, SUCCESS);
865
866 /* Check that FAILURE is returned if a field does not exist. */
867 ret = backend_x509_get_username(username, sizeof(username), "SN", cert);
868 assert_int_equal(ret, FAILURE);
869
870 /* Check that FAILURE is returned for invalid field names. */
871 ret = backend_x509_get_username(username, sizeof(username), "invalidField", cert);
872 assert_int_equal(ret, FAILURE);
873
874 /* Check that FAILURE is returned if the output buffer is too small. Do this separately
875 * for a subject field and for the serial number, because these are different code paths.
876 *
877 * First case: Can't fit all characters. */
878 ret = backend_x509_get_username(username, strlen(cert_details_cname) / 2, "CN", cert);
879 assert_int_equal(ret, FAILURE);
880 ret = backend_x509_get_username(username, strlen(cert_details_serial_number_hex) / 2, "serialNumber", cert);
881 assert_int_equal(ret, FAILURE);
882
883 /* Second case: Can fit the characters but not the terminating '\0'. */
884 ret = backend_x509_get_username(username, strlen(cert_details_cname), "CN", cert);
885 assert_int_equal(ret, FAILURE);
886 ret = backend_x509_get_username(username, strlen(cert_details_serial_number_hex), "serialNumber", cert);
887 assert_int_equal(ret, FAILURE);
888
889 gc_free(&gc);
890 free_certificate(cert);
891}
892
893#if defined(__GNUC__) || defined(__clang__)
894#pragma GCC diagnostic pop
895#endif
896
897/* Certificate with two CNs, "foo" and "bar".
898 *
899 * Generated with:
900 * openssl req -x509 -newkey ec -pkeyopt ec_paramgen_curve:secp384r1 -subj "/CN=foo/CN=bar" \
901 * -noenc -out two_cns.crt -keyout two_cns.key
902 */
903static const char *cert_with_two_cns =
904 "-----BEGIN CERTIFICATE-----\n"
905 "MIIByTCCAVCgAwIBAgIUZuvd8Wfnq5jeRc3ohoJ/Vza54wQwCgYIKoZIzj0EAwIw\n"
906 "HDEMMAoGA1UEAwwDZm9vMQwwCgYDVQQDDANiYXIwHhcNMjYwODI4MTU1NjAwWhcN\n"
907 "MjYwOTI3MTU1NjAwWjAcMQwwCgYDVQQDDANmb28xDDAKBgNVBAMMA2JhcjB2MBAG\n"
908 "ByqGSM49AgEGBSuBBAAiA2IABERAfb210NOACy+QVYAu3EXrcGhTJpZDfhpDnE/h\n"
909 "PvPMWGWzqecTYdseArxZc0T/5Xma36IKCjGGsgN9ypZ5oQugQlB/NrVRCJIuHSGA\n"
910 "hGBWFvnUsqdNo765lGwVdBwhY6NTMFEwHQYDVR0OBBYEFPwnD+wK9R81Syk0qyTI\n"
911 "dFT/BNoJMB8GA1UdIwQYMBaAFPwnD+wK9R81Syk0qyTIdFT/BNoJMA8GA1UdEwEB\n"
912 "/wQFMAMBAf8wCgYIKoZIzj0EAwIDZwAwZAIwGxazGb6RRQtXzOWCPLRKId4e+E88\n"
913 "cwoCK3UwzEr8+Ddf54w5cEZC54f5J6AKFUJjAjBpT/JqF41uK57H+8i/16oZkBcm\n"
914 "OyQnlH8W/UzZo3/weTEBTcNW0iuCpIrS6im8pSk=\n"
915 "-----END CERTIFICATE-----\n";
916
917void
919{
920 /* When there are multiple fields of the same type in the certificate's subject, OpenVPN
921 * should extract the value of the last matching field. This is essentially arbitrary and there
922 * is no correct choice here, but this test exists to make sure that the behavior is consistent
923 * between different backends.
924 */
926
927 char username[TLS_USERNAME_LEN + 1] = { 0 };
928 assert_int_equal(backend_x509_get_username(username, sizeof(username), "CN", cert), SUCCESS);
929 assert_string_equal(username, "bar");
930 free_certificate(cert);
931}
932
933/* Certificate with a null-byte embedded in the CN.
934 *
935 * Generated with the following Python script:
936 *
937 * from cryptography import x509
938 * from cryptography.x509.oid import NameOID, ExtensionOID, ExtendedKeyUsageOID
939 * from cryptography.hazmat.primitives import hashes, serialization
940 * from cryptography.hazmat.primitives.asymmetric import ec
941 * import datetime
942 *
943 * private_key = ec.generate_private_key(ec.SECP384R1())
944 * now = datetime.datetime.now(datetime.timezone.utc)
945 * name = "with\x00null"
946 *
947 * cert = (x509.CertificateBuilder()
948 * .subject_name(x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, name)]))
949 * .issuer_name(x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, name)]))
950 * .public_key(private_key.public_key())
951 * .serial_number(x509.random_serial_number())
952 * .not_valid_before(now)
953 * .not_valid_after(now + datetime.timedelta(days=10 * 365))
954 * .sign(private_key, hashes.SHA256()))
955 *
956 * print(str(cert.public_bytes(serialization.Encoding.PEM), encoding='utf-8'))
957 **/
958static const char *cert_with_null =
959 "-----BEGIN CERTIFICATE-----\n"
960 "MIIBZTCB66ADAgECAhRLWdNRl+C20KKBG4QC9HFPWlOtBzAKBggqhkjOPQQDAjAU\n"
961 "MRIwEAYDVQQDDAl3aXRoAG51bGwwHhcNMjYwODI4MTQzMDA4WhcNMzYwODI1MTQz\n"
962 "MDA4WjAUMRIwEAYDVQQDDAl3aXRoAG51bGwwdjAQBgcqhkjOPQIBBgUrgQQAIgNi\n"
963 "AAT7PE+vJCBiB4CVHBcvJVF9n5n/dGQIn4C8HeYE8M2iXYCIRW5wg6/mlPaeiJY/\n"
964 "Ywh3pa8zhto1+aczbJKTvLgRwXn6N5vNpME1c5iWMzY0WHe1dJyVtoRBvkNvy5+k\n"
965 "GuEwCgYIKoZIzj0EAwIDaQAwZgIxAP2ekdQ8muG8Nv2o3PsBp0CqiaSNByGiP75i\n"
966 "k099bUFvHp/3LSp8Wf4JK2iWzc5h6gIxAINBGg2xjlmMgpXxROKA9qQqaM3d92Mp\n"
967 "EzZyRyPM3PGR83ZPbIaYDq8lCVxVlbYr/Q==\n"
968 "-----END CERTIFICATE-----\n";
969
970void
972{
974 struct gc_arena gc = gc_new();
975
976 /* Trying to get the subject as a whole should fail. */
977 assert_ptr_equal(x509_get_subject(cert, &gc), NULL);
978
979 /* Trying to extract the common name should fail. */
980 char username[TLS_USERNAME_LEN + 1] = { 0 };
981 assert_int_equal(backend_x509_get_username(username, sizeof(username), "CN", cert), FAILURE);
982 gc_free(&gc);
983 free_certificate(cert);
984}
985
986/* Cert with CN="name, O=InjectedOrg" and O=RealOrg.
987 *
988 * Generated with the following Python script:
989 *
990 * from cryptography import x509
991 * from cryptography.x509.oid import NameOID, ExtensionOID, ExtendedKeyUsageOID
992 * from cryptography.hazmat.primitives import hashes, serialization
993 * from cryptography.hazmat.primitives.asymmetric import ec
994 * import datetime
995 *
996 * private_key = ec.generate_private_key(ec.SECP384R1())
997 * now = datetime.datetime.now(datetime.timezone.utc)
998 * name = "name, O=InjectedOrg"
999 * org = "RealOrg"
1000 *
1001 * distinguished_name = x509.Name([
1002 * x509.NameAttribute(NameOID.COMMON_NAME, name),
1003 * x509.NameAttribute(NameOID.ORGANIZATION_NAME, org)
1004 * ])
1005 *
1006 * cert = (x509.CertificateBuilder()
1007 * .subject_name(distinguished_name)
1008 * .issuer_name(distinguished_name)
1009 * .public_key(private_key.public_key())
1010 * .serial_number(x509.random_serial_number())
1011 * .not_valid_before(now)
1012 * .not_valid_after(now + datetime.timedelta(days=10 * 365))
1013 * .sign(private_key, hashes.SHA256()))
1014 *
1015 * print(str(cert.public_bytes(serialization.Encoding.PEM), encoding='utf-8'))
1016 */
1017static const char *cert_with_rfc_2253_chars =
1018 "-----BEGIN CERTIFICATE-----\n"
1019 "MIIBnTCCASOgAwIBAgIUR1IGc6A800U14v/ykZNR21aVubowCgYIKoZIzj0EAwIw\n"
1020 "MDEcMBoGA1UEAwwTbmFtZSwgTz1JbmplY3RlZE9yZzEQMA4GA1UECgwHUmVhbE9y\n"
1021 "ZzAeFw0yNjA4MjgxNTQ3NDdaFw0zNjA4MjUxNTQ3NDdaMDAxHDAaBgNVBAMME25h\n"
1022 "bWUsIE89SW5qZWN0ZWRPcmcxEDAOBgNVBAoMB1JlYWxPcmcwdjAQBgcqhkjOPQIB\n"
1023 "BgUrgQQAIgNiAAR6zl9QPAbAnHWN//MRdowuhu0Sol6N+lqB/qk+D+2NHCd/t4H9\n"
1024 "cJlswUh6EPsmLxgfMYgO2QwClFWEFWvtXQs8BggoidY6i9pmAPhs8+9fmIyuNVpG\n"
1025 "3vUWZrUBRgylwaIwCgYIKoZIzj0EAwIDaAAwZQIwKzXmR8YPQZ1pratM9meVmGkH\n"
1026 "1rpHgV3U8oeg+jXmfVcZJTpDeDz4yBl4V3KBKT7HAjEAj2qkaTz7fiSwBKsxJQWH\n"
1027 "dQFPBCAYU9zZJvlNnEPtmHIwaD/qHXDeClr/HRItU3B9\n"
1028 "-----END CERTIFICATE-----\n";
1029
1030void
1032{
1034 struct gc_arena gc = gc_new();
1035
1036 char *subject = x509_get_subject(cert, &gc);
1037 assert_non_null(subject);
1038
1039 /* Mbed TLS escapes the '=' character but OpenSSL does not. */
1040 const char *expected_subject_openssl = "CN=name\\, O=InjectedOrg, O=RealOrg";
1041 const char *expected_subject_mbedtls = "CN=name\\, O\\=InjectedOrg, O=RealOrg";
1042
1043 assert_true(strcmp(subject, expected_subject_openssl) == 0 || strcmp(subject, expected_subject_mbedtls) == 0);
1044 gc_free(&gc);
1045 free_certificate(cert);
1046}
1047
1048void
1050{
1051 const char *peer_info_normal =
1052 "IV_VER=2.6_git\nIV_PLAT=mac\nIV_TCPNL=1\nIV_NCP=2\n"
1053 "IV_CIPHERS=AES-256-GCM:AES-128-GCM:CHACHA20-POLY1305\n"
1054 "IV_PROTO=94\nIV_LZO_STUB=1\nIV_COMP_STUB=1\nP=78\nIV_COMP_STUBv2=1\n"
1055 "IV_SSL=OpenSSL_3.0.5_5_Jul_2022\nIV_LZ4v2=1";
1056
1057 const char *empty = "";
1058 const char *invalid_proto = "IV_PROTO=seven\nIV_SSL=7\nP=300\nID=xyz";
1059 const char *test_prefix = "UV_IV_PROTO=773\nNP=112\nPD=8\n";
1060
1061
1062 assert_int_equal(extract_iv_proto(peer_info_normal), 94);
1063 assert_int_equal(extract_iv_proto(empty), 0);
1064 assert_int_equal(extract_iv_proto(invalid_proto), 0);
1065 /* This should not pick up the UV_IV_PROTO that has the extra prefix */
1066 assert_int_equal(extract_iv_proto(test_prefix), 0);
1067
1068 assert_int_equal(peer_info_extract_uint(peer_info_normal, "IV_COMP_STUB="), 1);
1069 assert_int_equal(peer_info_extract_int(empty, "IV_COMP_STUB=", "%d", 0xfe0d0d), 0xfe0d0d);
1070 assert_int_equal(peer_info_extract_uint(invalid_proto, "IV_COMP_STUB="), 0);
1071
1072 assert_int_equal(peer_info_extract_int(test_prefix, "NP=", "%d", 23), 112);
1073 assert_int_equal(peer_info_extract_uint(test_prefix, "PD="), 8);
1074 assert_int_equal(peer_info_extract_int(test_prefix, "P=", "%x", 0xfe0d0d), 0xfe0d0d);
1075 assert_int_equal(peer_info_extract_uint(peer_info_normal, "P="), 78);
1076 assert_int_equal(peer_info_extract_uint(test_prefix, "UV_IV_PROTO="), 773);
1077
1078 struct gc_arena gc = gc_new();
1079
1080 const char *peer_ciphers = extract_var_peer_info(peer_info_normal, "IV_CIPHERS=", &gc);
1081 assert_string_equal(peer_ciphers, "AES-256-GCM:AES-128-GCM:CHACHA20-POLY1305");
1082
1083 /* with the extra = this should not extract anything */
1084 const char *proto = extract_var_peer_info(peer_info_normal, "IV_PROTO==", &gc);
1085 assert_null(proto);
1086
1087 proto = extract_var_peer_info(peer_info_normal, "IV_PROTO=", &gc);
1088 assert_string_equal(proto, "94");
1089
1090
1091 const char *double_eq_info = "FOO=7\nFOO==new";
1092 const char *foo_eq = extract_var_peer_info(double_eq_info, "FOO=", &gc);
1093 const char *foo = extract_var_peer_info(double_eq_info, "FOO", &gc);
1094 const char *foo_2eq = extract_var_peer_info(double_eq_info, "FOO==", &gc);
1095
1096 assert_string_equal(foo, "=7");
1097 assert_string_equal(foo_eq, "7");
1098 assert_string_equal(foo_2eq, "new");
1099
1100 assert_int_equal(extract_asymmetric_peer_id(double_eq_info), MAX_PEER_ID);
1101 assert_int_equal(extract_asymmetric_peer_id(peer_info_normal), MAX_PEER_ID);
1102 assert_int_equal(extract_asymmetric_peer_id(invalid_proto), MAX_PEER_ID);
1103 assert_int_equal(extract_asymmetric_peer_id("ID=f7"), 0xf7);
1104 assert_int_equal(extract_asymmetric_peer_id("X=foo\nID=12ab"), 0x12ab);
1105 assert_int_equal(extract_asymmetric_peer_id("X=foo\nID=34dd\nY=bar"), 0x34dd);
1106 assert_int_equal(extract_asymmetric_peer_id("X=foo\nID=12345678"), MAX_PEER_ID);
1107
1108 gc_free(&gc);
1109}
1110
1111int
1112main(void)
1113{
1115
1116 const struct CMUnitTest tests[] = {
1117 cmocka_unit_test(crypto_pem_encode_certificate),
1118 cmocka_unit_test(test_load_certificate_and_key),
1119 cmocka_unit_test(test_load_certificate_and_key_uri),
1131 cmocka_unit_test(test_data_channel_roundtrip_bf_cbc),
1132 cmocka_unit_test(test_data_channel_known_vectors_epoch),
1134 cmocka_unit_test(crypto_test_print_cert_details),
1135 cmocka_unit_test(ssl_test_extract_last_matching_field),
1136 cmocka_unit_test(ssl_test_reject_null_in_cert_subject),
1138 cmocka_unit_test(ssl_test_extract_peer_info),
1139 cmocka_unit_test(test_acc_parse_client_messages),
1140 cmocka_unit_test(test_parse_acc_parameters),
1141 cmocka_unit_test(test_acc_common_protocols),
1142 cmocka_unit_test(test_acc_send_message),
1143 cmocka_unit_test(test_list_intersection)
1144 };
1145
1146#if defined(ENABLE_CRYPTO_OPENSSL)
1147 tls_init_lib();
1148#endif
1149
1150 int ret = cmocka_run_group_tests_name("ssl tests", tests, init, cleanup);
1151
1152#if defined(ENABLE_CRYPTO_OPENSSL)
1153 tls_free_lib();
1154#endif
1155
1156 return ret;
1157}
bool buf_printf(struct buffer *buf, const char *format,...)
printf-style append to a buffer with overflow check.
Definition buffer.c:231
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
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
struct buffer buffer_read_from_file(const char *filename, struct gc_arena *gc)
buffer_read_from_file - copy the content of a file into a buffer
Definition buffer.c:1399
Buffer management functions and garbage collection.
#define BEND(buf)
Return a pointer one past the end of the buffer content.
Definition buffer.h:143
#define BSTR(buf)
Return the buffer content pointer cast to char *.
Definition buffer.h:157
#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 uint8_t * buf_write_alloc(struct buffer *buf, size_t size)
Reserve space at the end of a buffer for writing.
Definition buffer.h:1189
static bool buf_advance(struct buffer *buf, ssize_t size)
Advance the content start of a buffer, consuming bytes from the front.
Definition buffer.h:1165
static bool buf_write(struct buffer *dest, const void *src, size_t size)
Append data to a buffer.
Definition buffer.h:1239
#define CC_BACKSLASH
backslash
Definition buffer.h:1703
static bool buf_write_u8(struct buffer *dest, uint8_t data)
Append a uint8_t to a buffer.
Definition buffer.h:1288
#define BLEN(buf)
Return the length of the buffer content in bytes.
Definition buffer.h:151
#define BLENZ(buf)
Return the length of the buffer content as a size_t.
Definition buffer.h:153
static void gc_free(struct gc_arena *a)
Free all allocations in a garbage collection arena.
Definition buffer.h:1974
#define ALLOC_OBJ_CLEAR(dptr, type)
Allocate and zero-initialise memory for a single object of the given type.
Definition buffer.h:2036
#define buf_init(buf, offset)
Definition buffer.h:364
static struct gc_arena gc_new(void)
Allocate and return a new, empty garbage collection arena.
Definition buffer.h:1958
void free_key_ctx_bi(struct key_ctx_bi *ctx)
Definition crypto.c:1098
void prng_bytes(uint8_t *output, int len)
Definition crypto.c:1695
void init_key_ctx_bi(struct key_ctx_bi *ctx, const struct key2 *key2, int key_direction, const struct key_type *kt, const char *name)
Definition crypto.c:1057
Data Channel Cryptography Module.
#define CO_EPOCH_DATA_KEY_FORMAT
Bit-flag indicating the epoch the data format.
Definition crypto.h:367
static bool aead_usage_limit_reached(const uint64_t limit, const struct key_ctx *key_ctx, uint64_t higest_pid)
Checks if the usage limit for an AEAD cipher is reached.
Definition crypto.h:749
#define KEY_DIRECTION_BIDIRECTIONAL
Definition crypto.h:224
static struct key_type create_kt(const char *cipher, const char *md, const char *optname)
Creates and validates an instance of struct key_type with the provided algs.
Definition crypto.h:670
static bool cipher_valid(const char *ciphername)
Returns if the cipher is valid, based on the given cipher name.
#define OPENVPN_AEAD_TAG_LENGTH
void free_epoch_key_ctx(struct crypto_options *co)
Frees the extra data structures used by epoch keys in crypto_options.
void epoch_init_key_ctx(struct crypto_options *co, const struct key_type *key_type, const struct epoch_key *e1_send, const struct epoch_key *e1_recv, uint16_t future_key_count)
Initialises data channel keys and internal structures for epoch data keys using the provided E0 epoch...
void epoch_iterate_send_key(struct crypto_options *co)
Updates the send key and send_epoch_key in cryptio_options->key_ctx_bi to use the next epoch.
static const char * dco_get_supported_ciphers(void)
Definition dco.h:381
void openvpn_encrypt(struct buffer *buf, struct buffer work, struct crypto_options *opt)
Encrypt and HMAC sign a packet so that it can be sent as a data channel VPN tunnel packet to a remote...
Definition crypto.c:333
bool openvpn_decrypt(struct buffer *buf, struct buffer work, struct crypto_options *opt, const struct frame *frame, const uint8_t *ad_start)
HMAC verify and decrypt a data channel packet received from a remote OpenVPN peer.
Definition crypto.c:776
#define RELIABLE_ACK_SIZE
The maximum number of packet IDs waiting to be acknowledged which can be stored in one reliable_ack s...
Definition reliable.h:43
#define ACK_SIZE(n)
Definition reliable.h:81
@ write
#define BUF_SIZE(f)
Definition mtu.h:188
#define ASSERT(x)
Definition error.h:221
#define MAX_PEER_ID
Definition openvpn.h:528
time_t now
Definition otime.c:33
static void update_time(void)
Definition otime.h:84
void packet_id_init(struct packet_id *p, int seq_backtrack, int time_backtrack, const char *name, int unit)
Definition packet_id.c:96
void packet_id_free(struct packet_id *p)
Definition packet_id.c:126
#define PACKET_ID_EPOCH_MAX
Definition packet_id.h:47
const char * platform_create_temp_file(const char *directory, const char *prefix, struct gc_arena *gc)
Create a temporary file in directory, returns the filename of the created file.
Definition platform.c:545
const char * platform_get_tmp_dir(void)
Get a directory for temporary files.
Definition platform.c:591
struct signal_info siginfo_static
Definition sig.c:44
static char * auth_challenge
Definition ssl.c:308
Control Channel SSL/Data channel negotiation module.
Control Channel SSL library backend module.
void tls_ctx_free(struct tls_root_ctx *ctx)
Frees the library-specific TLSv1 context.
int tls_ctx_load_priv_file(struct tls_root_ctx *ctx, const char *priv_key_file, bool priv_key_file_inline)
Load private key file into the given TLS context.
void tls_free_lib(void)
Free any global SSL library-specific data structures.
Definition ssl_openssl.c:98
void tls_init_lib(void)
Perform any static initialisation necessary by the library.
Definition ssl_openssl.c:91
void tls_ctx_new(struct tls_root_ctx *ctx)
Initialise a library-specific TLS context.
void tls_ctx_load_cert_file(struct tls_root_ctx *ctx, const char *cert_file, bool cert_file_inline)
Load certificate file into the given TLS context.
char * extract_var_peer_info(const char *peer_info, const char *var, struct gc_arena *gc)
Extracts a variable from peer info, the returned string will be allocated using the supplied gc_arena...
Definition ssl_util.c:63
unsigned int peer_info_extract_int(const char *peer_info, const char *field, const char *format, unsigned int default_value)
Extracts the named integer variable and returns its value or default_value if it cannot be extracted.
Definition ssl_util.c:95
uint32_t extract_asymmetric_peer_id(const char *peer_info)
Extracts the ID variable and returns its value or MAX_PEER_ID if it cannot be extracted.
Definition ssl_util.c:119
unsigned int peer_info_extract_uint(const char *peer_info, const char *field)
Extracts the named integer variable and returns its value or 0 if it cannot be extracted.
Definition ssl_util.c:113
SSL utility functions.
static unsigned int extract_iv_proto(const char *peer_info)
Extracts the IV_PROTO variable and returns its value or 0 if it cannot be extracted.
Definition ssl_util.h:77
Control Channel Verification Module.
#define TLS_USERNAME_LEN
Maximum length of common name.
Definition ssl_verify.h:54
Control Channel Verification Module library-specific backend interface.
result_t backend_x509_write_pem(openvpn_x509_cert_t *cert, const char *filename)
char * backend_x509_get_serial_hex(openvpn_x509_cert_t *cert, struct gc_arena *gc)
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)
@ FAILURE
@ SUCCESS
mbedtls_x509_crt openvpn_x509_cert_t
Wrapper structure for dynamically allocated memory.
Definition buffer.h:71
int capacity
Size in bytes of memory allocated by malloc().
Definition buffer.h:72
int len
Length in bytes of the actual content within the allocated memory.
Definition buffer.h:76
Contains all state information for one tunnel.
Definition openvpn.h:455
Security parameter state for processing data channel packets.
Definition crypto.h:286
unsigned int flags
Bit-flags determining behavior of security operation functions.
Definition crypto.h:374
struct key_ctx_bi key_ctx_bi
OpenSSL cipher and HMAC contexts for both sending and receiving directions.
Definition crypto.h:287
struct packet_id packet_id
Current packet ID state for both sending and receiving directions.
Definition crypto.h:326
uint8_t epoch_key[SHA256_DIGEST_LENGTH]
Definition crypto.h:186
Packet geometry parameters.
Definition mtu.h:113
int tun_mtu
the (user) configured tun-mtu.
Definition mtu.h:147
struct frame::@074234134026241341315172337061247271261307273127 buf
int payload_size
the maximum size that a payload that our buffers can hold from either tun device or network link.
Definition mtu.h:118
int headroom
the headroom in the buffer, this is choosen to allow all potential header to be added before the pack...
Definition mtu.h:124
int tailroom
the tailroom in the buffer.
Definition mtu.h:128
Garbage collection arena used to keep track of dynamically allocated memory.
Definition buffer.h:127
Container for bidirectional cipher and HMAC key material.
Definition crypto.h:233
struct key keys[2]
Two unidirectional sets of key material.
Definition crypto.h:236
struct key_ctx encrypt
Cipher and/or HMAC contexts for sending direction.
Definition crypto.h:274
uint16_t epoch
OpenVPN data channel epoch, this variable holds the epoch number this key belongs to.
Definition crypto.h:221
uint64_t plaintext_blocks
Counter for the number of plaintext block encrypted using this cipher with the current key in number ...
Definition crypto.h:215
const char * cipher
const name of the cipher
Definition crypto.h:135
Container for unidirectional cipher and HMAC key material.
Definition crypto.h:145
uint8_t cipher[MAX_CIPHER_KEY_LENGTH]
Key material for cipher operations.
Definition crypto.h:146
uint8_t hmac[MAX_HMAC_KEY_LENGTH]
Key material for HMAC operations.
Definition crypto.h:148
uint64_t id
Definition packet_id.h:133
struct packet_id_send send
Definition packet_id.h:180
Structure that wraps the TLS context.
Definition ssl_mbedtls.h:86
SSL_CTX * ctx
Definition ssl_openssl.h:41
void test_acc_parse_client_messages(void **state)
Definition test_acc.c:79
void test_acc_send_message(void **state)
Definition test_acc.c:269
void test_acc_common_protocols(void **state)
Definition test_acc.c:240
void test_list_intersection(void **state)
Definition test_acc.c:328
void test_parse_acc_parameters(void **state)
Definition test_acc.c:175
static void openvpn_unit_test_setup(void)
Sets up the environment for unit tests like making both stderr and stdout non-buffered to avoid messa...
Definition test_common.h:63
static int cleanup(void **state)
static int init(void **state)
static const char * cert_details_test_cert
Definition test_ssl.c:803
void reschedule_multi_process(struct context *c)
Reschedule tls_multi_process.
Definition test_ssl.c:92
void crypto_test_print_cert_details(void **state)
Definition test_ssl.c:827
static void test_data_channel_roundtrip_aes_192_cbc(void **state)
Definition test_ssl.c:570
static void test_load_certificate_and_key_uri(void **state)
Definition test_ssl.c:230
const char * certfile
Definition test_ssl.c:139
bool get_user_pass_cr(struct user_pass *up, const char *auth_file, const char *prefix, const unsigned int flags, const char *auth_challenge)
Retrieves the user credentials from various sources depending on the flags.
Definition test_ssl.c:81
static openvpn_x509_cert_t * get_certificate(const char *cert_str)
Definition test_ssl.c:782
static void test_data_channel_roundtrip_aes_192_gcm_epoch(void **state)
Definition test_ssl.c:546
const char *const cert_details_org
Definition test_ssl.c:821
static void encrypt_one_packet(struct crypto_options *co, int len)
Definition test_ssl.c:358
void ssl_test_extract_peer_info(void **state)
Definition test_ssl.c:1049
static void test_data_channel_roundtrip_aes_256_cbc(void **state)
Definition test_ssl.c:576
static void test_load_certificate_and_key(void **state)
Definition test_ssl.c:208
void ssl_test_extract_last_matching_field(void **state)
Definition test_ssl.c:918
static const char * cert_with_two_cns
Definition test_ssl.c:903
static void test_data_channel_known_vectors_run(bool epoch)
Definition test_ssl.c:646
static struct key2 create_key(void)
Definition test_ssl.c:618
struct gc_arena gc
Definition test_ssl.c:138
void purge_user_pass(struct user_pass *up, bool force)
Definition test_ssl.c:87
static void check_aead_limits(struct crypto_options *co, bool chachapoly)
Definition test_ssl.c:401
const char * strerror_win32(DWORD errnum, struct gc_arena *gc)
Definition test_ssl.c:63
static const char *const unittest_cert
Definition test_ssl.c:112
static struct @041167262151223363234312074372224332231333353344 global_state
static void run_data_channel_with_cipher_epoch(const char *cipher)
Definition test_ssl.c:506
const char *const cert_details_serial_number
Definition test_ssl.c:823
static const char * cert_with_null
Definition test_ssl.c:958
static int cleanup(void **state)
Definition test_ssl.c:168
static void do_data_channel_round_trip(struct crypto_options *co)
Definition test_ssl.c:304
static void test_data_channel_roundtrip_aes_128_gcm_epoch(void **state)
Definition test_ssl.c:534
static void crypto_pem_encode_certificate(void **state)
Definition test_ssl.c:178
static void test_data_channel_roundtrip_aes_128_gcm(void **state)
Definition test_ssl.c:528
static const char * cert_with_rfc_2253_chars
Definition test_ssl.c:1017
int main(void)
Definition test_ssl.c:1112
void ssl_test_escape_rfc_2253_chars_in_subject(void **state)
Definition test_ssl.c:1031
static void test_data_channel_roundtrip_aes_192_gcm(void **state)
Definition test_ssl.c:540
void throw_signal(const int signum)
Throw a hard signal.
Definition test_ssl.c:69
const char * keyfile
Definition test_ssl.c:140
static void init_frame_parameters(struct frame *frame)
Definition test_ssl.c:274
static void test_data_channel_roundtrip_bf_cbc(void **state)
Definition test_ssl.c:606
static void test_data_channel_roundtrip_chacha20_poly1305(void **state)
Definition test_ssl.c:582
void ssl_test_reject_null_in_cert_subject(void **state)
Definition test_ssl.c:971
static void uninit_crypto_options(struct crypto_options *co)
Definition test_ssl.c:495
static void test_data_channel_roundtrip_aes_256_gcm(void **state)
Definition test_ssl.c:552
const char *const cert_details_cname
Definition test_ssl.c:820
static void test_data_channel_known_vectors_epoch(void **state)
Definition test_ssl.c:750
const char *const cert_details_serial_number_hex
Definition test_ssl.c:824
static void test_data_channel_roundtrip_chacha20_poly1305_epoch(void **state)
Definition test_ssl.c:594
static const char *const unittest_key
Definition test_ssl.c:127
static void test_data_channel_roundtrip_aes_256_gcm_epoch(void **state)
Definition test_ssl.c:558
static int init(void **state)
Definition test_ssl.c:144
static void free_certificate(openvpn_x509_cert_t *cert)
Definition test_ssl.c:793
static void test_data_channel_roundtrip_aes_128_cbc(void **state)
Definition test_ssl.c:564
static struct crypto_options init_crypto_options(const char *cipher, const char *auth, bool epoch, struct key2 *statickey)
Definition test_ssl.c:452
const char *const cert_details_org_unit
Definition test_ssl.c:822
static void run_data_channel_with_cipher(const char *cipher, const char *auth)
Definition test_ssl.c:517
static void test_data_channel_known_vectors_shortpktid(void **state)
Definition test_ssl.c:756