OpenVPN
tls_crypt.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) 2016-2021 Sentyron B.V. <openvpn@sentyron.com>
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 "argv.h"
30#include "base64.h"
31#include "crypto.h"
32#include "integer.h"
33#include "platform.h"
34#include "run_command.h"
35#include "session_id.h"
36#include "ssl.h"
37
38#include "tls_crypt.h"
39
40const char *tls_crypt_v2_cli_pem_name = "OpenVPN tls-crypt-v2 client key";
41const char *tls_crypt_v2_srv_pem_name = "OpenVPN tls-crypt-v2 server key";
42
44static const uint8_t TLS_CRYPT_METADATA_TYPE_USER = 0x00;
46static const uint8_t TLS_CRYPT_METADATA_TYPE_TIMESTAMP = 0x01;
47
48static struct key_type
50{
51 return create_kt("AES-256-CTR", "SHA256", "tls-crypt");
52}
53
54int
59
60void
61tls_crypt_init_key(struct key_ctx_bi *key, struct key2 *keydata, const char *key_file,
62 bool key_inline, bool tls_server)
63{
64 const int key_direction = tls_server ? KEY_DIRECTION_NORMAL : KEY_DIRECTION_INVERSE;
65 struct key_type kt = tls_crypt_kt();
66 if (!kt.cipher || !kt.digest)
67 {
68 msg(M_FATAL, "ERROR: --tls-crypt not supported");
69 }
70 crypto_read_openvpn_key(&kt, key, key_file, key_inline, key_direction,
71 "Control Channel Encryption", "tls-crypt", keydata);
72}
73
77static void
78xor_key2(struct key2 *key, const struct key2 *other)
79{
80 ASSERT(key->n == 2 && other->n == 2);
81 for (int k = 0; k < 2; k++)
82 {
83 for (int j = 0; j < MAX_CIPHER_KEY_LENGTH; j++)
84 {
85 key->keys[k].cipher[j] = key->keys[k].cipher[j] ^ other->keys[k].cipher[j];
86 }
87
88 for (int j = 0; j < MAX_HMAC_KEY_LENGTH; j++)
89 {
90 key->keys[k].hmac[j] = key->keys[k].hmac[j] ^ other->keys[k].hmac[j];
91 }
92 }
93}
94
95bool
97{
98 struct key2 rengokeys;
100 strlen(EXPORT_DYNAMIC_TLS_CRYPT_LABEL), rengokeys.keys,
101 sizeof(rengokeys.keys)))
102 {
103 return false;
104 }
105 rengokeys.n = 2;
106
107 session->tls_wrap_reneg.opt = session->tls_wrap.opt;
108 session->tls_wrap_reneg.mode = TLS_WRAP_CRYPT;
109 session->tls_wrap_reneg.cleanup_key_ctx = true;
110 session->tls_wrap_reneg.work = alloc_buf(BUF_SIZE(&session->opt->frame));
111 session->tls_wrap_reneg.opt.pid_persist = NULL;
112
113 packet_id_init(&session->tls_wrap_reneg.opt.packet_id, session->opt->replay_window,
114 session->opt->replay_time, "TLS_WRAP_RENEG", session->key_id);
115
116 if (session->tls_wrap.mode == TLS_WRAP_CRYPT || session->tls_wrap.mode == TLS_WRAP_AUTH)
117 {
118 xor_key2(&rengokeys, &session->tls_wrap.original_wrap_keydata);
119 }
120
121 const int key_direction = session->opt->server ? KEY_DIRECTION_NORMAL : KEY_DIRECTION_INVERSE;
122
123 struct key_direction_state kds;
124 key_direction_state_init(&kds, key_direction);
125
126 struct key_type kt = tls_crypt_kt();
127
128 init_key_ctx_bi(&session->tls_wrap_reneg.opt.key_ctx_bi, &rengokeys, key_direction, &kt,
129 "dynamic tls-crypt");
130 secure_memzero(&rengokeys, sizeof(rengokeys));
131
132 return true;
133}
134
135
136bool
137tls_crypt_wrap(const struct buffer *src, struct buffer *dst, struct crypto_options *opt)
138{
139 const struct key_ctx *ctx = &opt->key_ctx_bi.encrypt;
140 struct gc_arena gc;
141
142 /* IV, packet-ID and implicit IV required for this mode. */
143 ASSERT(ctx->cipher);
144 ASSERT(ctx->hmac);
146 ASSERT(hmac_ctx_size(ctx->hmac) == 256 / 8);
147
148 gc_init(&gc);
149
150 dmsg(D_PACKET_CONTENT, "TLS-CRYPT WRAP FROM: %s", format_hex(BPTR(src), BLEN(src), 80, &gc));
151
152 /* Get packet ID */
153 if (!packet_id_write(&opt->packet_id.send, dst, true, false))
154 {
155 msg(D_CRYPT_ERRORS, "TLS-CRYPT ERROR: packet ID roll over.");
156 goto err;
157 }
158
159 dmsg(D_PACKET_CONTENT, "TLS-CRYPT WRAP AD: %s", format_hex(BPTR(dst), BLEN(dst), 0, &gc));
160
161 /* Buffer overflow check */
163 {
165 "TLS-CRYPT WRAP: buffer size error, "
166 "sc=%d so=%d sl=%d dc=%d do=%d dl=%d",
167 src->capacity, src->offset, src->len, dst->capacity, dst->offset, dst->len);
168 goto err;
169 }
170
171 /* Calculate auth tag and synthetic IV */
172 {
173 uint8_t *tag = NULL;
174 hmac_ctx_reset(ctx->hmac);
175 hmac_ctx_update(ctx->hmac, BPTR(dst), BLEN(dst));
176 hmac_ctx_update(ctx->hmac, BPTR(src), BLEN(src));
177
179 hmac_ctx_final(ctx->hmac, tag);
180
181 dmsg(D_PACKET_CONTENT, "TLS-CRYPT WRAP TAG: %s",
182 format_hex(tag, TLS_CRYPT_TAG_SIZE, 0, &gc));
183
184 /* Use the 128 most significant bits of the tag as IV */
185 ASSERT(cipher_ctx_reset(ctx->cipher, tag));
186 }
187
188 /* Encrypt src */
189 {
190 int outlen = 0;
191 ASSERT(cipher_ctx_update(ctx->cipher, BEND(dst), &outlen, BPTR(src), BLEN(src)));
192 ASSERT(buf_inc_len(dst, outlen));
193 ASSERT(cipher_ctx_final(ctx->cipher, BPTR(dst), &outlen));
194 ASSERT(buf_inc_len(dst, outlen));
195 }
196
197 dmsg(D_PACKET_CONTENT, "TLS-CRYPT WRAP TO: %s", format_hex(BPTR(dst), BLEN(dst), 80, &gc));
198
199 gc_free(&gc);
200 return true;
201
202err:
204 dst->len = 0;
205 gc_free(&gc);
206 return false;
207}
208
209bool
210tls_crypt_unwrap(const struct buffer *src, struct buffer *dst, struct crypto_options *opt)
211{
212 static const char error_prefix[] = "tls-crypt unwrap error";
213 const struct key_ctx *ctx = &opt->key_ctx_bi.decrypt;
214 struct gc_arena gc;
215
216 gc_init(&gc);
217
218 ASSERT(opt);
219 ASSERT(src->len > 0);
220 ASSERT(ctx->cipher);
222
223 dmsg(D_PACKET_CONTENT, "TLS-CRYPT UNWRAP FROM: %s", format_hex(BPTR(src), BLEN(src), 80, &gc));
224
225 if (buf_len(src) < TLS_CRYPT_OFF_CT)
226 {
227 CRYPT_ERROR("packet too short");
228 }
229
230 /* Decrypt cipher text */
231 {
232 int outlen = 0;
233
234 /* Buffer overflow check (should never fail) */
236 {
237 CRYPT_ERROR("potential buffer overflow");
238 }
239
241 {
242 CRYPT_ERROR("cipher reset failed");
243 }
244 if (!cipher_ctx_update(ctx->cipher, BPTR(dst), &outlen, BPTR(src) + TLS_CRYPT_OFF_CT,
245 BLEN(src) - (int)TLS_CRYPT_OFF_CT))
246 {
247 CRYPT_ERROR("cipher update failed");
248 }
249 ASSERT(buf_inc_len(dst, outlen));
250 if (!cipher_ctx_final(ctx->cipher, BPTR(dst), &outlen))
251 {
252 CRYPT_ERROR("cipher final failed");
253 }
254 ASSERT(buf_inc_len(dst, outlen));
255 }
256
257 /* Check authentication */
258 {
259 const uint8_t *tag = BPTR(src) + TLS_CRYPT_OFF_TAG;
260 uint8_t tag_check[TLS_CRYPT_TAG_SIZE] = { 0 };
261
262 dmsg(D_PACKET_CONTENT, "TLS-CRYPT UNWRAP AD: %s",
263 format_hex(BPTR(src), TLS_CRYPT_OFF_TAG, 0, &gc));
264 dmsg(D_PACKET_CONTENT, "TLS-CRYPT UNWRAP TO: %s",
265 format_hex(BPTR(dst), BLEN(dst), 80, &gc));
266
267 hmac_ctx_reset(ctx->hmac);
269 hmac_ctx_update(ctx->hmac, BPTR(dst), BLEN(dst));
270 hmac_ctx_final(ctx->hmac, tag_check);
271
272 if (memcmp_constant_time(tag, tag_check, sizeof(tag_check)))
273 {
274 dmsg(D_CRYPTO_DEBUG, "tag : %s", format_hex(tag, sizeof(tag_check), 0, &gc));
275 dmsg(D_CRYPTO_DEBUG, "tag_check: %s", format_hex(tag_check, sizeof(tag_check), 0, &gc));
276 CRYPT_ERROR("packet authentication failed");
277 }
278 }
279
280 /* Check replay */
281 if (!(opt->flags & CO_IGNORE_PACKET_ID))
282 {
283 struct packet_id_net pin;
284 struct buffer tmp = *src;
286 ASSERT(packet_id_read(&pin, &tmp, true));
287 if (!crypto_check_replay(opt, &pin, 0, error_prefix, &gc))
288 {
289 CRYPT_ERROR("packet replay");
290 }
291 }
292
293 gc_free(&gc);
294 return true;
295
298 dst->len = 0;
299 gc_free(&gc);
300 return false;
301}
302
303static inline void
304tls_crypt_v2_load_client_key(struct key_ctx_bi *key, const struct key2 *key2, bool tls_server)
305{
306 const int key_direction = tls_server ? KEY_DIRECTION_NORMAL : KEY_DIRECTION_INVERSE;
307 struct key_type kt = tls_crypt_kt();
308 if (!kt.cipher || !kt.digest)
309 {
310 msg(M_FATAL, "ERROR: --tls-crypt-v2 not supported");
311 }
312 init_key_ctx_bi(key, key2, key_direction, &kt, "Control Channel Encryption");
313}
314
315void
316tls_crypt_v2_init_client_key(struct key_ctx_bi *key, struct key2 *original_key,
317 struct buffer *wkc_buf, const char *key_file, bool key_inline)
318{
320
322 {
323 msg(M_FATAL, "ERROR: invalid tls-crypt-v2 client key format");
324 }
325
326 struct key2 key2 = { .n = 2 };
327 if (!buf_read(&client_key, &key2.keys, sizeof(key2.keys)))
328 {
329 msg(M_FATAL, "ERROR: not enough data in tls-crypt-v2 client key");
330 }
331
333 *original_key = key2;
334
335 *wkc_buf = client_key;
336}
337
338void
339tls_crypt_v2_init_server_key(struct key_ctx *key_ctx, bool encrypt, const char *key_file,
340 bool key_inline)
341{
342 struct key srv_key;
343 struct buffer srv_key_buf;
344
345 buf_set_write(&srv_key_buf, (void *)&srv_key, sizeof(srv_key));
347 {
348 msg(M_FATAL, "ERROR: invalid tls-crypt-v2 server key format");
349 }
350
351 struct key_type kt = tls_crypt_kt();
352 if (!kt.cipher || !kt.digest)
353 {
354 msg(M_FATAL, "ERROR: --tls-crypt-v2 not supported");
355 }
356 struct key_parameters srv_key_params;
357
358 key_parameters_from_key(&srv_key_params, &srv_key);
359
360 init_key_ctx(key_ctx, &srv_key_params, &kt, encrypt, "tls-crypt-v2 server key");
361 secure_memzero(&srv_key, sizeof(srv_key));
362}
363
364static bool
365tls_crypt_v2_wrap_client_key(struct buffer *wkc, const struct key2 *src_key,
366 const struct buffer *src_metadata, struct key_ctx *server_key,
367 struct gc_arena *gc)
368{
369 cipher_ctx_t *cipher_ctx = server_key->cipher;
370 struct buffer work =
372
373 /* Calculate auth tag and synthetic IV */
375 if (!tag)
376 {
377 msg(M_WARN, "ERROR: could not write tag");
378 return false;
379 }
380 const int data_len = BLEN(src_metadata) + sizeof(src_key->keys) + sizeof(uint16_t);
382 const uint16_t net_len = htons((uint16_t)tagged_len);
385 hmac_ctx_update(hmac_ctx, (void *)&net_len, sizeof(net_len));
386 hmac_ctx_update(hmac_ctx, (void *)src_key->keys, sizeof(src_key->keys));
389
390 dmsg(D_CRYPTO_DEBUG, "TLS-CRYPT WRAP TAG: %s", format_hex(tag, TLS_CRYPT_TAG_SIZE, 0, gc));
391
392 /* Use the 128 most significant bits of the tag as IV */
394
395 /* Overflow check (OpenSSL requires an extra block in the dst buffer) */
397 if (buf_forward_capacity(&work) < padded_len)
398 {
399 msg(M_WARN, "ERROR: could not crypt: insufficient space in dst");
400 return false;
401 }
402
403 /* Encrypt */
404 int outlen = 0;
405 ASSERT(cipher_ctx_update(cipher_ctx, BEND(&work), &outlen, (void *)src_key->keys,
406 sizeof(src_key->keys)));
407 ASSERT(buf_inc_len(&work, outlen));
410 ASSERT(buf_inc_len(&work, outlen));
412 ASSERT(buf_inc_len(&work, outlen));
413 ASSERT(buf_write(&work, &net_len, sizeof(net_len)));
414
415 return buf_copy(wkc, &work);
416}
417
418static bool
419tls_crypt_v2_unwrap_client_key(struct key2 *client_key, struct buffer *metadata,
421{
422 const char *error_prefix = __func__;
423 bool ret = false;
424 struct gc_arena gc = gc_new();
425 /* The crypto API requires one extra cipher block of buffer head room when
426 * decrypting, which nicely matches the tag size of WKc. So
427 * TLS_CRYPT_V2_MAX_WKC_LEN is always large enough for the plaintext. */
428 uint8_t plaintext_buf_data[TLS_CRYPT_V2_MAX_WKC_LEN] = { 0 };
429 struct buffer plaintext = { 0 };
430
431 dmsg(D_TLS_DEBUG_MED, "%s: unwrapping client key (len=%d): %s", __func__,
434
436 {
437 CRYPT_ERROR("wrapped client key too big");
438 }
439
440 /* Decrypt client key and metadata */
441 uint16_t net_len = 0;
443
444 if (BLEN(&wrapped_client_key) < sizeof(net_len))
445 {
446 CRYPT_ERROR("failed to read length");
447 }
448 memcpy(&net_len, BEND(&wrapped_client_key) - sizeof(net_len), sizeof(net_len));
449
450 if (ntohs(net_len) != BLEN(&wrapped_client_key))
451 {
452 dmsg(D_TLS_DEBUG_LOW, "%s: net_len=%u, BLEN=%i", __func__, ntohs(net_len),
454 CRYPT_ERROR("invalid length");
455 }
456
457 buf_inc_len(&wrapped_client_key, -(int)sizeof(net_len));
458
460 {
461 CRYPT_ERROR("failed to read tag");
462 }
463
464 if (!cipher_ctx_reset(server_key->cipher, tag))
465 {
466 CRYPT_ERROR("failed to initialize IV");
467 }
469 int outlen = 0;
472 {
473 CRYPT_ERROR("could not decrypt client key");
474 }
476
478 {
479 CRYPT_ERROR("cipher final failed");
480 }
482
483 /* Check authentication */
486 hmac_ctx_update(server_key->hmac, (void *)&net_len, sizeof(net_len));
489
491 {
492 dmsg(D_CRYPTO_DEBUG, "tag : %s", format_hex(tag, sizeof(tag_check), 0, &gc));
493 dmsg(D_CRYPTO_DEBUG, "tag_check: %s", format_hex(tag_check, sizeof(tag_check), 0, &gc));
494 CRYPT_ERROR("client key authentication error");
495 msg(D_TLS_DEBUG_LOW, "This might be a client-key that was generated for "
496 "a different tls-crypt-v2 server key)");
497 }
498
499 if (buf_len(&plaintext) < sizeof(client_key->keys))
500 {
501 CRYPT_ERROR("failed to read client key");
502 }
503 memcpy(&client_key->keys, BPTR(&plaintext), sizeof(client_key->keys));
504 ASSERT(buf_advance(&plaintext, sizeof(client_key->keys)));
505 client_key->n = 2;
506
507 if (!buf_copy(metadata, &plaintext))
508 {
509 CRYPT_ERROR("metadata too large for supplied buffer");
510 }
511
512 ret = true;
514 if (!ret)
515 {
516 secure_memzero(client_key, sizeof(*client_key));
517 }
519 gc_free(&gc);
520 return ret;
521}
522
523static bool
525{
526 if (ctx->tls_crypt_v2_metadata.len < 1 + sizeof(int64_t))
527 {
528 msg(M_WARN, "ERROR: Client key metadata is too small to contain a timestamp.");
529 return false;
530 }
531
532 const uint8_t *metadata = ctx->tls_crypt_v2_metadata.data;
533 if (*metadata != TLS_CRYPT_METADATA_TYPE_TIMESTAMP)
534 {
535 msg(M_WARN, "ERROR: Client key does not have a timestamp.");
536 return false;
537 }
538
539 int64_t timestamp;
540 memcpy(&timestamp, metadata + 1, sizeof(int64_t));
541 timestamp = (int64_t)ntohll((uint64_t)timestamp);
542 int64_t max_age_in_seconds = (int64_t)max_days * 24 * 60 * 60;
543 if (now - timestamp > max_age_in_seconds)
544 {
545 msg(M_WARN, "ERROR: Client key is too old.");
546 return false;
547 }
548 return true;
549}
550
551static bool
552tls_crypt_v2_verify_metadata(const struct tls_wrap_ctx *ctx, const struct tls_options *opt)
553{
554 bool ret = false;
555 struct gc_arena gc = gc_new();
556 const char *tmp_file = NULL;
557 struct buffer metadata = ctx->tls_crypt_v2_metadata;
558 int metadata_type = buf_read_u8(&metadata);
559 if (metadata_type < 0)
560 {
561 msg(M_WARN, "ERROR: no metadata type");
562 goto cleanup;
563 }
564
565 tmp_file = platform_create_temp_file(opt->tmp_dir, "tls_crypt_v2_metadata_", &gc);
566 if (!tmp_file || !buffer_write_file(tmp_file, &metadata))
567 {
568 msg(M_WARN, "ERROR: could not write metadata to file");
569 goto cleanup;
570 }
571
572 char metadata_type_str[4] = { 0 }; /* Max value: 255 */
574 struct env_set *es = env_set_create(NULL);
575 setenv_str(es, "script_type", "tls-crypt-v2-verify");
576 setenv_str(es, "metadata_type", metadata_type_str);
577 setenv_str(es, "metadata_file", tmp_file);
578
579 struct argv argv = argv_new();
581 argv_msg_prefix(D_TLS_DEBUG, &argv, "Executing tls-crypt-v2-verify");
582
583 ret = openvpn_run_script(&argv, es, 0, "--tls-crypt-v2-verify");
584
585 argv_free(&argv);
587
588 if (!platform_unlink(tmp_file))
589 {
590 msg(M_WARN, "WARNING: failed to remove temp file '%s", tmp_file);
591 }
592
593 if (ret)
594 {
595 msg(D_HANDSHAKE, "TLS CRYPT V2 VERIFY SCRIPT OK");
596 }
597 else
598 {
599 msg(D_HANDSHAKE, "TLS CRYPT V2 VERIFY SCRIPT ERROR");
600 }
601
602cleanup:
603 gc_free(&gc);
604 return ret;
605}
606
607bool
609 const struct tls_options *opt, bool initial_packet)
610{
612 {
613 msg(D_TLS_ERRORS, "Client wants tls-crypt-v2, but no server key present.");
614 return false;
615 }
616
617 msg(D_HANDSHAKE, "Control Channel: using tls-crypt-v2 key");
618
619 struct buffer wrapped_client_key = *buf;
620 uint16_t net_len = 0;
621
622 if (BLEN(&wrapped_client_key) < sizeof(net_len))
623 {
624 msg(D_TLS_ERRORS, "Can not read tls-crypt-v2 client key length");
625 return false;
626 }
627 memcpy(&net_len, BEND(&wrapped_client_key) - sizeof(net_len), sizeof(net_len));
628
629 uint16_t wkc_len = ntohs(net_len);
631 {
632 msg(D_TLS_ERRORS, "Can not locate tls-crypt-v2 client key");
633 return false;
634 }
635
636 if (!initial_packet)
637 {
638 /* This might be a harmless resend of the packet but it is better to
639 * just ignore the WKC part than trying to setup tls-crypt keys again.
640 *
641 * A CONTROL_WKC_V1 packets has a normal packet part and an appended
642 * wrapped control key. These are authenticated individually. We already
643 * set up tls-crypt with the wrapped key, so we are ignoring this part
644 * of the message but we return the normal packet part as the normal
645 * part of the message might have been corrupted earlier and discarded
646 * and this is resend. So return the normal part of the packet,
647 * basically transforming the CONTROL_WKC_V1 into a normal CONTROL_V1
648 * packet*/
649 msg(D_TLS_ERRORS, "control channel security already setup ignoring "
650 "wrapped key part of packet.");
651
652 /* Remove client key from buffer so tls-crypt code can unwrap message */
654 return true;
655 }
656
660 {
661 msg(D_TLS_ERRORS, "Can not unwrap tls-crypt-v2 client key");
663 return false;
664 }
665
667 {
669 return false;
670 }
671
672 if (opt && opt->tls_crypt_v2_verify_script && !tls_crypt_v2_verify_metadata(ctx, opt))
673 {
675 return false;
676 }
677
678 /* Load the decrypted key */
679 ctx->mode = TLS_WRAP_CRYPT;
680 ctx->cleanup_key_ctx = true;
682 memset(&ctx->opt.key_ctx_bi, 0, sizeof(ctx->opt.key_ctx_bi));
684
685 /* Remove client key from buffer so tls-crypt code can unwrap message */
687
688 return true;
689}
690
691void
696
697void
698tls_crypt_v2_write_client_key_file(const char *filename, const char *b64_metadata,
699 const char *server_key_file, bool server_key_inline)
700{
701 struct gc_arena gc = gc_new();
702 struct key_ctx server_key = { 0 };
703 struct buffer client_key_pem = { 0 };
705 struct key2 client_key = { .n = 2 };
706
707 if (!rand_bytes((void *)client_key.keys, sizeof(client_key.keys)))
708 {
709 msg(M_FATAL, "ERROR: could not generate random key");
710 goto cleanup;
711 }
712 ASSERT(buf_write(&dst, client_key.keys, sizeof(client_key.keys)));
713
714 struct buffer metadata;
715 if (b64_metadata)
716 {
720 int decoded_len = openvpn_base64_decode(b64_metadata, BEND(&metadata), BCAP(&metadata));
721 if (decoded_len < 0)
722 {
723 msg(M_FATAL, "ERROR: failed to base64 decode provided metadata");
724 goto cleanup;
725 }
727 {
728 msg(M_FATAL, "ERROR: metadata too long (%d bytes, max %u bytes)", decoded_len,
730 goto cleanup;
731 }
732 ASSERT(buf_inc_len(&metadata, decoded_len));
733 }
734 else
735 {
736 metadata = alloc_buf_gc(1 + sizeof(int64_t), &gc);
737 int64_t timestamp = htonll((uint64_t)now);
739 ASSERT(buf_write(&metadata, &timestamp, sizeof(timestamp)));
740 }
741
743 if (!tls_crypt_v2_wrap_client_key(&dst, &client_key, &metadata, &server_key, &gc))
744 {
745 msg(M_FATAL, "ERROR: could not wrap generated client key");
746 goto cleanup;
747 }
748
749 /* PEM-encode Kc || WKc */
751 {
752 msg(M_FATAL, "ERROR: could not PEM-encode client key");
753 goto cleanup;
754 }
755
756 const char *client_file = filename;
757 bool client_inline = false;
758
759 if (!filename || streq(filename, ""))
760 {
762 client_file = (const char *)BPTR(&client_key_pem);
763 client_inline = true;
764 }
765 else if (!buffer_write_file(filename, &client_key_pem))
766 {
767 msg(M_FATAL, "ERROR: could not write client key file");
768 goto cleanup;
769 }
770
771 /* Sanity check: load client key (as "client") */
774 struct key2 keydata;
775 msg(D_GENKEY, "Testing client-side key loading...");
776 tls_crypt_v2_init_client_key(&test_client_key, &keydata, &test_wrapped_client_key, client_file,
777 client_inline);
779
780 /* Sanity check: unwrap and load client key (as "server") */
782 struct key2 test_client_key2 = { 0 };
783 free_key_ctx(&server_key);
784 tls_crypt_v2_init_server_key(&server_key, false, server_key_file, server_key_inline);
785 msg(D_GENKEY, "Testing server-side key loading...");
786 ASSERT(tls_crypt_v2_unwrap_client_key(&test_client_key2, &test_metadata,
787 test_wrapped_client_key, &server_key));
788 secure_memzero(&test_client_key2, sizeof(test_client_key2));
789 free_buf(&test_wrapped_client_key);
790
791cleanup:
792 secure_memzero(&client_key, sizeof(client_key));
793 free_key_ctx(&server_key);
794 buf_clear(&client_key_pem);
795 buf_clear(&dst);
796
797 gc_free(&gc);
798}
void argv_parse_cmd(struct argv *argres, const char *cmdstr)
Parses a command string, tokenizes it and puts each element into a separate struct argv argument slot...
Definition argv.c:481
void argv_free(struct argv *a)
Frees all memory allocations allocated by the struct argv related functions.
Definition argv.c:101
void argv_msg_prefix(const msglvl_t msglevel, const struct argv *a, const char *prefix)
Similar to argv_msg() but prefixes the messages being written with a given string.
Definition argv.c:259
struct argv argv_new(void)
Allocates a new struct argv and ensures it is initialised.
Definition argv.c:87
#define OPENVPN_BASE64_DECODED_LENGTH(base64_length)
Compute the maximal number of bytes encoded in a base64 string.
Definition base64.h:41
void free_buf(struct buffer *buf)
Definition buffer.c:184
void buf_clear(struct buffer *buf)
Definition buffer.c:163
bool buffer_write_file(const char *filename, const struct buffer *buf)
Write buffer contents to file.
Definition buffer.c:301
struct buffer alloc_buf_gc(size_t size, struct gc_arena *gc)
Definition buffer.c:89
struct buffer alloc_buf(size_t size)
Definition buffer.c:63
#define BEND(buf)
Definition buffer.h:124
static bool buf_copy(struct buffer *dest, const struct buffer *src)
Definition buffer.h:704
#define BPTR(buf)
Definition buffer.h:123
static bool buf_inc_len(struct buffer *buf, int inc)
Definition buffer.h:588
static void gc_init(struct gc_arena *a)
Definition buffer.h:1004
static bool buf_safe(const struct buffer *buf, size_t len)
Definition buffer.h:518
static void buf_set_write(struct buffer *buf, uint8_t *data, int size)
Definition buffer.h:331
static bool buf_read(struct buffer *src, void *dest, int size)
Definition buffer.h:762
static bool buf_advance(struct buffer *buf, int size)
Definition buffer.h:616
static int buf_len(const struct buffer *buf)
Definition buffer.h:253
static int buf_forward_capacity(const struct buffer *buf)
Definition buffer.h:539
static void secure_memzero(void *data, size_t len)
Securely zeroise memory.
Definition buffer.h:414
static uint8_t * buf_write_alloc(struct buffer *buf, size_t size)
Definition buffer.h:633
static bool buf_write(struct buffer *dest, const void *src, size_t size)
Definition buffer.h:660
static int buf_read_u8(struct buffer *buf)
Definition buffer.h:786
#define BLEN(buf)
Definition buffer.h:126
static char * format_hex(const uint8_t *data, size_t size, size_t maxoutput, struct gc_arena *gc)
Definition buffer.h:503
#define BCAP(buf)
Definition buffer.h:129
static void gc_free(struct gc_arena *a)
Definition buffer.h:1025
static struct gc_arena gc_new(void)
Definition buffer.h:1017
#define key2
Definition cert_data.h:80
void free_key_ctx_bi(struct key_ctx_bi *ctx)
Definition crypto.c:1093
void init_key_ctx(struct key_ctx *ctx, const struct key_parameters *key, const struct key_type *kt, int enc, const char *prefix)
Definition crypto.c:989
bool read_pem_key_file(struct buffer *key, const char *pem_name, const char *key_file, bool key_inline)
Read key material from a PEM encoded files into the key structure.
Definition crypto.c:1859
void write_pem_key_file(const char *filename, const char *pem_name)
Generate a server key with enough randomness to fill a key struct and write to file.
Definition crypto.c:1804
void key_parameters_from_key(struct key_parameters *key_params, const struct key *key)
Converts a struct key representation into a struct key_parameters representation.
Definition crypto.c:1182
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:1055
void key_direction_state_init(struct key_direction_state *kds, int key_direction)
Definition crypto.c:1665
void crypto_read_openvpn_key(const struct key_type *key_type, struct key_ctx_bi *ctx, const char *key_file, bool key_inline, const int key_direction, const char *key_name, const char *opt_name, struct key2 *keydata)
Definition crypto.c:1283
bool crypto_check_replay(struct crypto_options *opt, const struct packet_id_net *pin, uint16_t epoch, const char *error_prefix, struct gc_arena *gc)
Check packet ID for replay, and perform replay administration.
Definition crypto.c:369
void free_key_ctx(struct key_ctx *ctx)
Definition crypto.c:1074
Data Channel Cryptography Module.
#define KEY_DIRECTION_NORMAL
Definition crypto.h:232
#define CO_PACKET_ID_LONG_FORM
Bit-flag indicating whether to use OpenVPN's long packet ID format.
Definition crypto.h:345
#define CRYPT_ERROR(format)
Definition crypto.h:395
#define CO_IGNORE_PACKET_ID
Bit-flag indicating whether to ignore the packet ID of a received packet.
Definition crypto.h:348
int memcmp_constant_time(const void *a, const void *b, size_t size)
As memcmp(), but constant-time.
#define KEY_DIRECTION_INVERSE
Definition crypto.h:233
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:672
int cipher_ctx_update(cipher_ctx_t *ctx, uint8_t *dst, int *dst_len, uint8_t *src, int src_len)
Updates the given cipher context, encrypting data in the source buffer, and placing any complete bloc...
void hmac_ctx_update(hmac_ctx_t *ctx, const uint8_t *src, int src_len)
void hmac_ctx_reset(hmac_ctx_t *ctx)
int cipher_ctx_block_size(const cipher_ctx_t *ctx)
Returns the block size of the cipher, in bytes.
void hmac_ctx_final(hmac_ctx_t *ctx, uint8_t *dst)
int hmac_ctx_size(hmac_ctx_t *ctx)
#define MAX_CIPHER_KEY_LENGTH
void crypto_clear_error(void)
int rand_bytes(uint8_t *output, int len)
Wrapper for secure random number generator.
#define MAX_HMAC_KEY_LENGTH
int cipher_ctx_reset(cipher_ctx_t *ctx, const uint8_t *iv_buf)
Resets the given cipher context, setting the IV to the specified value.
int cipher_ctx_final(cipher_ctx_t *ctx, uint8_t *dst, int *dst_len)
Pads the final cipher block using PKCS padding, and output to the destination buffer.
bool crypto_pem_encode(const char *name, struct buffer *dst, const struct buffer *src, struct gc_arena *gc)
Encode binary data as PEM.
mbedtls_cipher_context_t cipher_ctx_t
Generic cipher context.
mbedtls_md_context_t hmac_ctx_t
Generic HMAC context.
void env_set_destroy(struct env_set *es)
Definition env_set.c:166
void setenv_str(struct env_set *es, const char *name, const char *value)
Definition env_set.c:307
struct env_set * env_set_create(struct gc_arena *gc)
Definition env_set.c:156
#define D_TLS_DEBUG_LOW
Definition errlevel.h:76
#define D_CRYPTO_DEBUG
Definition errlevel.h:147
#define D_PACKET_CONTENT
Definition errlevel.h:167
#define D_TLS_DEBUG_MED
Definition errlevel.h:156
#define D_CRYPT_ERRORS
Definition errlevel.h:57
#define D_HANDSHAKE
Definition errlevel.h:71
#define D_GENKEY
Definition errlevel.h:78
#define D_TLS_ERRORS
Definition errlevel.h:58
#define D_TLS_DEBUG
Definition errlevel.h:164
#define TLS_CRYPT_V2_MAX_WKC_LEN
Definition tls_crypt.h:96
#define TLS_CRYPT_BLOCK_SIZE
Definition tls_crypt.h:90
bool tls_crypt_v2_extract_client_key(struct buffer *buf, struct tls_wrap_ctx *ctx, const struct tls_options *opt, bool initial_packet)
Extract a tls-crypt-v2 client key from a P_CONTROL_HARD_RESET_CLIENT_V3 message, and load the key int...
Definition tls_crypt.c:608
void tls_crypt_init_key(struct key_ctx_bi *key, struct key2 *keydata, const char *key_file, bool key_inline, bool tls_server)
Initialize a key_ctx_bi structure for use with --tls-crypt.
Definition tls_crypt.c:61
#define TLS_CRYPT_TAG_SIZE
Definition tls_crypt.h:88
void tls_crypt_v2_init_server_key(struct key_ctx *key_ctx, bool encrypt, const char *key_file, bool key_inline)
Initialize a tls-crypt-v2 server key (used to encrypt/decrypt client keys).
Definition tls_crypt.c:339
void tls_crypt_v2_write_client_key_file(const char *filename, const char *b64_metadata, const char *server_key_file, bool server_key_inline)
Generate a tls-crypt-v2 client key, and write to file.
Definition tls_crypt.c:698
#define TLS_CRYPT_OFF_PID
Definition tls_crypt.h:92
bool tls_crypt_unwrap(const struct buffer *src, struct buffer *dst, struct crypto_options *opt)
Unwrap a control channel packet (decrypts, authenticates and performs replay checks).
Definition tls_crypt.c:210
#define TLS_CRYPT_OFF_TAG
Definition tls_crypt.h:93
#define TLS_CRYPT_OFF_CT
Definition tls_crypt.h:94
bool tls_session_generate_dynamic_tls_crypt_key(struct tls_session *session)
Generates a TLS-Crypt key to be used with dynamic tls-crypt using the TLS EKM exporter function.
Definition tls_crypt.c:96
void tls_crypt_v2_write_server_key_file(const char *filename)
Generate a tls-crypt-v2 server key, and write to file.
Definition tls_crypt.c:692
int tls_crypt_buf_overhead(void)
Returns the maximum overhead (in bytes) added to the destination buffer by tls_crypt_wrap().
Definition tls_crypt.c:55
#define TLS_CRYPT_V2_CLIENT_KEY_LEN
Definition tls_crypt.h:97
void tls_crypt_v2_init_client_key(struct key_ctx_bi *key, struct key2 *original_key, struct buffer *wkc_buf, const char *key_file, bool key_inline)
Initialize a tls-crypt-v2 client key.
Definition tls_crypt.c:316
bool tls_crypt_wrap(const struct buffer *src, struct buffer *dst, struct crypto_options *opt)
Wrap a control channel packet (both authenticates and encrypts the data).
Definition tls_crypt.c:137
#define TLS_CRYPT_V2_MAX_METADATA_LEN
Definition tls_crypt.h:100
#define ntohll(x)
Definition integer.h:36
#define htonll(x)
Definition integer.h:29
#define BUF_SIZE(f)
Definition mtu.h:178
#define M_FATAL
Definition error.h:90
#define dmsg(flags,...)
Definition error.h:172
#define msg(flags,...)
Definition error.h:152
#define ASSERT(x)
Definition error.h:219
#define M_WARN
Definition error.h:92
#define streq(x, y)
Definition options.h:728
time_t now
Definition otime.c:33
void packet_id_init(struct packet_id *p, int seq_backtrack, int time_backtrack, const char *name, int unit)
Definition packet_id.c:96
bool packet_id_read(struct packet_id_net *pin, struct buffer *buf, bool long_form)
Definition packet_id.c:319
bool packet_id_write(struct packet_id_send *p, struct buffer *buf, bool long_form, bool prepend)
Write a packet ID to buf, and update the packet ID state.
Definition packet_id.c:382
static bool packet_id_initialized(const struct packet_id *pid)
Is this struct packet_id initialized?
Definition packet_id.h:271
static int packet_id_size(bool long_form)
Definition packet_id.h:322
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:540
bool platform_unlink(const char *filename)
Definition platform.c:487
static int openvpn_run_script(const struct argv *a, const struct env_set *es, const unsigned int flags, const char *hook)
Will run a script and return the exit code of the script if between 0 and 255, -1 otherwise.
Definition run_command.h:89
int openvpn_base64_decode(const char *str, void *data, int size)
Definition base64.c:160
Control Channel SSL/Data channel negotiation module.
#define EXPORT_DYNAMIC_TLS_CRYPT_LABEL
bool key_state_export_keying_material(struct tls_session *session, const char *label, size_t label_size, void *ekm, size_t ekm_size)
Keying Material Exporters [RFC 5705] allows additional keying material to be derived from existing TL...
Definition argv.h:35
Wrapper structure for dynamically allocated memory.
Definition buffer.h:60
int capacity
Size in bytes of memory allocated by malloc().
Definition buffer.h:61
uint8_t * data
Pointer to the allocated memory.
Definition buffer.h:67
int len
Length in bytes of the actual content within the allocated memory.
Definition buffer.h:65
int offset
Offset in bytes of the actual content within the allocated memory.
Definition buffer.h:63
Security parameter state for processing data channel packets.
Definition crypto.h:293
unsigned int flags
Bit-flags determining behavior of security operation functions.
Definition crypto.h:384
struct key_ctx_bi key_ctx_bi
OpenSSL cipher and HMAC contexts for both sending and receiving directions.
Definition crypto.h:294
struct packet_id packet_id
Current packet ID state for both sending and receiving directions.
Definition crypto.h:331
Garbage collection arena used to keep track of dynamically allocated memory.
Definition buffer.h:116
Container for bidirectional cipher and HMAC key material.
Definition crypto.h:240
int n
The number of key objects stored in the key2.keys array.
Definition crypto.h:241
struct key keys[2]
Two unidirectional sets of key material.
Definition crypto.h:243
Container for two sets of OpenSSL cipher and/or HMAC contexts for both sending and receiving directio...
Definition crypto.h:280
struct key_ctx decrypt
cipher and/or HMAC contexts for receiving direction.
Definition crypto.h:283
struct key_ctx encrypt
Cipher and/or HMAC contexts for sending direction.
Definition crypto.h:281
Container for one set of cipher and/or HMAC contexts.
Definition crypto.h:202
cipher_ctx_t * cipher
Generic cipher context.
Definition crypto.h:203
hmac_ctx_t * hmac
Generic HMAC context.
Definition crypto.h:204
Key ordering of the key2.keys array.
Definition crypto.h:259
internal structure similar to struct key that holds key information but is not represented on wire an...
Definition crypto.h:163
const char * cipher
const name of the cipher
Definition crypto.h:142
const char * digest
Message digest static parameters.
Definition crypto.h:143
Container for unidirectional cipher and HMAC key material.
Definition crypto.h:152
uint8_t cipher[MAX_CIPHER_KEY_LENGTH]
Key material for cipher operations.
Definition crypto.h:153
uint8_t hmac[MAX_HMAC_KEY_LENGTH]
Key material for HMAC operations.
Definition crypto.h:155
Data structure for describing the packet id that is received/send to the network.
Definition packet_id.h:191
struct packet_id_send send
Definition packet_id.h:200
const char * tmp_dir
Definition ssl_common.h:397
int tls_crypt_v2_max_age
Definition ssl_common.h:386
const char * tls_crypt_v2_verify_script
Definition ssl_common.h:385
Security parameter state of a single session within a VPN tunnel.
Definition ssl_common.h:491
Control channel wrapping (–tls-auth/–tls-crypt) context.
Definition ssl_common.h:276
struct buffer tls_crypt_v2_metadata
Received from client.
Definition ssl_common.h:288
bool cleanup_key_ctx
opt.key_ctx_bi is owned by this context
Definition ssl_common.h:289
struct crypto_options opt
Crypto state.
Definition ssl_common.h:283
enum tls_wrap_ctx::@28 mode
Control channel wrapping mode.
struct key_ctx tls_crypt_v2_server_key
Decrypts client keys.
Definition ssl_common.h:285
struct key2 original_wrap_keydata
original key data to be xored in to the key for dynamic tls-crypt.
Definition ssl_common.h:299
struct env_set * es
static int cleanup(void **state)
struct gc_arena gc
Definition test_ssl.c:131
static const char * test_client_key
static const uint8_t TLS_CRYPT_METADATA_TYPE_USER
Metadata contains user-specified data.
Definition tls_crypt.c:44
static bool tls_crypt_v2_check_client_key_age(const struct tls_wrap_ctx *ctx, int max_days)
Definition tls_crypt.c:524
const char * tls_crypt_v2_srv_pem_name
Definition tls_crypt.c:41
static bool tls_crypt_v2_verify_metadata(const struct tls_wrap_ctx *ctx, const struct tls_options *opt)
Definition tls_crypt.c:552
static void tls_crypt_v2_load_client_key(struct key_ctx_bi *key, const struct key2 *key2, bool tls_server)
Definition tls_crypt.c:304
const char * tls_crypt_v2_cli_pem_name
Definition tls_crypt.c:40
static const uint8_t TLS_CRYPT_METADATA_TYPE_TIMESTAMP
Metadata contains a 64-bit unix timestamp in network byte order.
Definition tls_crypt.c:46
static bool tls_crypt_v2_unwrap_client_key(struct key2 *client_key, struct buffer *metadata, struct buffer wrapped_client_key, struct key_ctx *server_key)
Definition tls_crypt.c:419
static bool tls_crypt_v2_wrap_client_key(struct buffer *wkc, const struct key2 *src_key, const struct buffer *src_metadata, struct key_ctx *server_key, struct gc_arena *gc)
Definition tls_crypt.c:365
static void xor_key2(struct key2 *key, const struct key2 *other)
Will produce key = key XOR other.
Definition tls_crypt.c:78
static struct key_type tls_crypt_kt(void)
Definition tls_crypt.c:49