OpenVPN
crypto.c
Go to the documentation of this file.
1/*
2 * OpenVPN -- An application to securely tunnel IP networks
3 * over a single TCP/UDP port, with support for SSL/TLS-based
4 * session authentication and key exchange,
5 * packet encryption, packet authentication, and
6 * packet compression.
7 *
8 * Copyright (C) 2002-2025 OpenVPN Inc <sales@openvpn.net>
9 * Copyright (C) 2010-2021 Fox Crypto B.V. <openvpn@foxcrypto.com>
10 *
11 * This program is free software; you can redistribute it and/or modify
12 * it under the terms of the GNU General Public License version 2
13 * as published by the Free Software Foundation.
14 *
15 * This program is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 * GNU General Public License for more details.
19 *
20 * You should have received a copy of the GNU General Public License along
21 * with this program; if not, see <https://www.gnu.org/licenses/>.
22 */
23
24#ifdef HAVE_CONFIG_H
25#include "config.h"
26#endif
27
28#include <inttypes.h>
29
30#include "syshead.h"
31#include <string.h>
32
33#include "crypto.h"
34#include "crypto_epoch.h"
35#include "packet_id.h"
36#include "error.h"
37#include "integer.h"
38#include "platform.h"
39
40#include "memdbg.h"
41
42/*
43 * Encryption and Compression Routines.
44 *
45 * On entry, buf contains the input data and length.
46 * On exit, it should be set to the output data and length.
47 *
48 * If buf->len is <= 0 we should return
49 * If buf->len is set to 0 on exit it tells the caller to ignore the packet.
50 *
51 * work is a workspace buffer we are given of size BUF_SIZE.
52 * work may be used to return output data, or the input buffer
53 * may be modified and returned as output. If output data is
54 * returned in work, the data should start after buf.headroom bytes
55 * of padding to leave room for downstream routines to prepend.
56 *
57 * Up to a total of buf.headroom bytes may be prepended to the input buf
58 * by all routines (encryption, decryption, compression, and decompression).
59 *
60 * Note that the buf_prepend return will assert if we try to
61 * make a header bigger than buf.headroom. This should not
62 * happen unless the frame parameters are wrong.
63 */
64
65static void
66openvpn_encrypt_aead(struct buffer *buf, struct buffer work, struct crypto_options *opt)
67{
68 struct gc_arena gc;
69 int outlen = 0;
70 const bool use_epoch_data_format = opt->flags & CO_EPOCH_DATA_KEY_FORMAT;
71
72 if (use_epoch_data_format)
73 {
75 }
76
77 const struct key_ctx *ctx = &opt->key_ctx_bi.encrypt;
78 uint8_t *mac_out = NULL;
79 const int mac_len = OPENVPN_AEAD_TAG_LENGTH;
80
81 /* IV, packet-ID and implicit IV required for this mode. */
82 ASSERT(ctx->cipher);
84
85 gc_init(&gc);
86
87 /* Prepare IV */
88 {
89 struct buffer iv_buffer;
91 const int iv_len = cipher_ctx_iv_length(ctx->cipher);
92
94
96
97 /* IV starts with packet id to make the IV unique for packet */
99 {
101 {
102 msg(D_CRYPT_ERRORS, "ENCRYPT ERROR: packet ID roll over");
103 goto err;
104 }
105 }
106 else
107 {
108 if (!packet_id_write(&opt->packet_id.send, &iv_buffer, false, false))
109 {
110 msg(D_CRYPT_ERRORS, "ENCRYPT ERROR: packet ID roll over");
111 goto err;
112 }
113 }
114 /* Write packet id part of IV to work buffer */
115 ASSERT(buf_write(&work, iv, buf_len(&iv_buffer)));
116
117 /* This generates the IV by XORing the implicit part of the IV
118 * with the packet id already written to the iv buffer */
119 for (int i = 0; i < iv_len; i++)
120 {
121 iv[i] = iv[i] ^ ctx->implicit_iv[i];
122 }
123
124 dmsg(D_PACKET_CONTENT, "ENCRYPT IV: %s", format_hex(iv, iv_len, 0, &gc));
125
126 /* Init cipher_ctx with IV. key & keylen are already initialized */
127 ASSERT(cipher_ctx_reset(ctx->cipher, iv));
128 }
129
130 dmsg(D_PACKET_CONTENT, "ENCRYPT FROM: %s", format_hex(BPTR(buf), BLEN(buf), 80, &gc));
131
132 /* Buffer overflow check */
133 if (!buf_safe(&work, buf->len + mac_len + cipher_ctx_block_size(ctx->cipher)))
134 {
135 msg(D_CRYPT_ERRORS, "ENCRYPT: buffer size error, bc=%d bo=%d bl=%d wc=%d wo=%d wl=%d",
136 buf->capacity, buf->offset, buf->len, work.capacity, work.offset, work.len);
137 goto err;
138 }
139
140 /* For AEAD ciphers, authenticate Additional Data, including opcode */
141 ASSERT(cipher_ctx_update_ad(ctx->cipher, BPTR(&work), BLEN(&work)));
142 dmsg(D_PACKET_CONTENT, "ENCRYPT AD: %s", format_hex(BPTR(&work), BLEN(&work), 0, &gc));
143
145 {
146 /* Reserve space for authentication tag */
149 }
150
151 /* Encrypt packet ID, payload */
152 ASSERT(cipher_ctx_update(ctx->cipher, BEND(&work), &outlen, BPTR(buf), BLEN(buf)));
153 ASSERT(buf_inc_len(&work, outlen));
154
155 /* update number of plaintext blocks encrypted. Use the (x + (n-1))/n trick
156 * to round up the result to the number of blocks used */
159
160 /* Flush the encryption buffer */
161 ASSERT(cipher_ctx_final(ctx->cipher, BEND(&work), &outlen));
162 ASSERT(buf_inc_len(&work, outlen));
163
164 /* if the tag is at end the end, allocate it now */
166 {
167 /* Reserve space for authentication tag */
170 }
171
172 /* Write authentication tag */
174
175 *buf = work;
176
177 dmsg(D_PACKET_CONTENT, "ENCRYPT TO: %s", format_hex(BPTR(buf), BLEN(buf), 80, &gc));
178
179 gc_free(&gc);
180 return;
181
182err:
184 buf->len = 0;
185 gc_free(&gc);
186 return;
187}
188
189static void
190openvpn_encrypt_v1(struct buffer *buf, struct buffer work, struct crypto_options *opt)
191{
192 struct gc_arena gc;
193 gc_init(&gc);
194
195 if (buf->len > 0 && opt)
196 {
197 const struct key_ctx *ctx = &opt->key_ctx_bi.encrypt;
198 uint8_t *mac_out = NULL;
199 const uint8_t *hmac_start = NULL;
200
201 /* Do Encrypt from buf -> work */
202 if (ctx->cipher)
203 {
204 uint8_t iv_buf[OPENVPN_MAX_IV_LENGTH] = { 0 };
205 const int iv_size = cipher_ctx_iv_length(ctx->cipher);
206 int outlen;
207
208 /* Reserve space for HMAC */
209 if (ctx->hmac)
210 {
211 mac_out = buf_write_alloc(&work, hmac_ctx_size(ctx->hmac));
212 ASSERT(mac_out);
213 hmac_start = BEND(&work);
214 }
215
216 if (cipher_ctx_mode_cbc(ctx->cipher))
217 {
218 /* generate pseudo-random IV */
219 prng_bytes(iv_buf, iv_size);
220
221 /* Put packet ID in plaintext buffer */
223 && !packet_id_write(&opt->packet_id.send, buf,
224 opt->flags & CO_PACKET_ID_LONG_FORM, true))
225 {
226 msg(D_CRYPT_ERRORS, "ENCRYPT ERROR: packet ID roll over");
227 goto err;
228 }
229 }
230 else if (cipher_ctx_mode_ofb_cfb(ctx->cipher))
231 {
232 struct buffer b;
233
234 /* packet-ID required for this mode. */
236
238 ASSERT(packet_id_write(&opt->packet_id.send, &b, true, false));
239 }
240 else /* We only support CBC, CFB, or OFB modes right now */
241 {
242 ASSERT(0);
243 }
244
245 /* write the pseudo-randomly IV (CBC)/packet ID (OFB/CFB) */
246 ASSERT(buf_write(&work, iv_buf, iv_size));
247 dmsg(D_PACKET_CONTENT, "ENCRYPT IV: %s", format_hex(iv_buf, iv_size, 0, &gc));
248
249 dmsg(D_PACKET_CONTENT, "ENCRYPT FROM: %s", format_hex(BPTR(buf), BLEN(buf), 80, &gc));
250
251 /* cipher_ctx was already initialized with key & keylen */
253
254 /* Buffer overflow check */
255 if (!buf_safe(&work, buf->len + cipher_ctx_block_size(ctx->cipher)))
256 {
258 "ENCRYPT: buffer size error, bc=%d bo=%d bl=%d wc=%d wo=%d wl=%d cbs=%d",
259 buf->capacity, buf->offset, buf->len, work.capacity, work.offset, work.len,
261 goto err;
262 }
263
264 /* Encrypt packet ID, payload */
265 ASSERT(cipher_ctx_update(ctx->cipher, BEND(&work), &outlen, BPTR(buf), BLEN(buf)));
266 ASSERT(buf_inc_len(&work, outlen));
267
268 /* Flush the encryption buffer */
269 ASSERT(cipher_ctx_final(ctx->cipher, BEND(&work), &outlen));
270 ASSERT(buf_inc_len(&work, outlen));
271
272 /* For all CBC mode ciphers, check the last block is complete */
274 }
275 else /* No Encryption */
276 {
279 true))
280 {
281 msg(D_CRYPT_ERRORS, "ENCRYPT ERROR: packet ID roll over");
282 goto err;
283 }
284 if (ctx->hmac)
285 {
286 hmac_start = BPTR(buf);
288 }
289 if (BLEN(&work))
290 {
291 buf_write_prepend(buf, BPTR(&work), BLEN(&work));
292 }
293 work = *buf;
294 }
295
296 /* HMAC the ciphertext (or plaintext if !cipher) */
297 if (ctx->hmac)
298 {
299 hmac_ctx_reset(ctx->hmac);
302 dmsg(D_PACKET_CONTENT, "ENCRYPT HMAC: %s",
303 format_hex(mac_out, hmac_ctx_size(ctx->hmac), 80, &gc));
304 }
305
306 *buf = work;
307
308 dmsg(D_PACKET_CONTENT, "ENCRYPT TO: %s", format_hex(BPTR(&work), BLEN(&work), 80, &gc));
309 }
310
311 gc_free(&gc);
312 return;
313
314err:
316 buf->len = 0;
317 gc_free(&gc);
318 return;
319}
320
321void
322openvpn_encrypt(struct buffer *buf, struct buffer work, struct crypto_options *opt)
323{
324 if (buf->len > 0 && opt)
325 {
327 {
328 openvpn_encrypt_aead(buf, work, opt);
329 }
330 else
331 {
332 openvpn_encrypt_v1(buf, work, opt);
333 }
334 }
335}
336
338cipher_get_aead_limits(const char *ciphername)
339{
340 if (!cipher_kt_mode_aead(ciphername))
341 {
342 return 0;
343 }
344
345 if (cipher_kt_name(ciphername) == cipher_kt_name("CHACHA20-POLY1305"))
346 {
347 return 0;
348 }
349
350 /* Assume all other ciphers require the limit */
351
352 /* We focus here on the equation
353 *
354 * q + s <= p^(1/2) * 2^(129/2) - 1
355 *
356 * as is the one that is limiting us.
357 *
358 * With p = 2^-57 this becomes
359 *
360 * q + s <= (2^36 - 1)
361 *
362 */
363 uint64_t rs = (1ull << 36) - 1;
364
365 return rs;
366}
367
368bool
370 const char *error_prefix, struct gc_arena *gc)
371{
372 bool ret = false;
373 struct packet_id_rec *recv;
374
375 if (epoch == 0 || opt->key_ctx_bi.decrypt.epoch == epoch)
376 {
377 recv = &opt->packet_id.rec;
378 }
379 else if (epoch == opt->epoch_retiring_data_receive_key.epoch)
380 {
381 recv = &opt->epoch_retiring_key_pid_recv;
382 }
383 else
384 {
385 /* We have an epoch that is neither current or old recv key but
386 * is authenticated, ie we need to move to a new current recv key */
388 "Received data packet with new epoch %d. Updating "
389 "receive key",
390 epoch);
392 recv = &opt->packet_id.rec;
393 }
394
396 if (packet_id_test(recv, pin))
397 {
398 packet_id_add(recv, pin);
399 if (opt->pid_persist && (opt->flags & CO_PACKET_ID_LONG_FORM))
400 {
402 }
403 ret = true;
404 }
405 else
406 {
407 if (!(opt->flags & CO_MUTE_REPLAY_WARNINGS))
408 {
410 "%s: bad packet ID (may be a replay): %s -- "
411 "see the man page entry for --replay-window for "
412 "more info or silence this warning with --mute-replay-warnings",
413 error_prefix, packet_id_net_print(pin, true, gc));
414 }
415 }
416 return ret;
417}
418
427static bool
428openvpn_decrypt_aead(struct buffer *buf, struct buffer work, struct crypto_options *opt,
429 const struct frame *frame, const uint8_t *ad_start)
430{
431 static const char error_prefix[] = "AEAD Decrypt error";
432 struct packet_id_net pin = { 0 };
433 struct gc_arena gc;
434 gc_init(&gc);
435
436 struct key_ctx *ctx = &opt->key_ctx_bi.decrypt;
437 const bool use_epoch_data_format = opt->flags & CO_EPOCH_DATA_KEY_FORMAT;
438 if (!use_epoch_data_format && cipher_decrypt_verify_fail_exceeded(ctx))
439 {
440 CRYPT_DROP("Decryption failed verification limit reached.");
441 }
442
443 const int tag_size = OPENVPN_AEAD_TAG_LENGTH;
444
445
446 ASSERT(opt);
447 ASSERT(frame);
448 ASSERT(buf->len > 0);
449 ASSERT(ctx->cipher);
450
451 dmsg(D_PACKET_CONTENT, "DECRYPT FROM: %s", format_hex(BPTR(buf), BLEN(buf), 80, &gc));
452
453 ASSERT(ad_start >= buf->data && ad_start <= BPTR(buf));
454
455 ASSERT(buf_init(&work, frame->buf.headroom));
456
457 /* IV and Packet ID required for this mode */
459
460 /* Ensure that the packet size is long enough */
461 int min_packet_len = packet_id_size(false) + tag_size + 1;
462
463 if (use_epoch_data_format)
464 {
465 min_packet_len += sizeof(uint32_t);
466 }
467
468 if (buf->len < min_packet_len)
469 {
470 CRYPT_ERROR("missing IV info, missing tag or no payload");
471 }
472
473 uint16_t epoch = 0;
474 /* Combine IV from explicit part from packet and implicit part from context */
475 {
476 uint8_t iv[OPENVPN_MAX_IV_LENGTH] = { 0 };
477 const int iv_len = cipher_ctx_iv_length(ctx->cipher);
478
479 /* Read packet id. For epoch data format also lookup the epoch key
480 * to be able to use the implicit IV of the correct decryption key */
481 if (use_epoch_data_format)
482 {
483 /* packet ID format is 16 bit epoch + 48 per epoch packet-counter */
484 const size_t packet_iv_len = sizeof(uint64_t);
485
486 /* copy the epoch-counter part into the IV */
487 memcpy(iv, BPTR(buf), packet_iv_len);
488
489 epoch = packet_id_read_epoch(&pin, buf);
490 if (epoch == 0)
491 {
492 CRYPT_ERROR("error reading packet-id");
493 }
495 if (!ctx)
496 {
497 CRYPT_ERROR("data packet with unknown epoch");
498 }
500 {
501 CRYPT_DROP("Decryption failed verification limit reached");
502 }
503 }
504 else
505 {
506 const size_t packet_iv_len = packet_id_size(false);
507 /* Packet ID form is a 32 bit packet counter */
508 memcpy(iv, BPTR(buf), packet_iv_len);
509 if (!packet_id_read(&pin, buf, false))
510 {
511 CRYPT_ERROR("error reading packet-id");
512 }
513 }
514
515 /* This generates the IV by XORing the implicit part of the IV
516 * with the packet id already written to the iv buffer */
517 for (int i = 0; i < iv_len; i++)
518 {
519 iv[i] = iv[i] ^ ctx->implicit_iv[i];
520 }
521
522 dmsg(D_PACKET_CONTENT, "DECRYPT IV: %s", format_hex(iv, iv_len, 0, &gc));
523
524 /* Load IV, ctx->cipher was already initialized with key & keylen */
525 if (!cipher_ctx_reset(ctx->cipher, iv))
526 {
527 CRYPT_ERROR("cipher init failed");
528 }
529 }
530
531 const int ad_size = BPTR(buf) - ad_start;
532
533 uint8_t *tag_ptr = NULL;
534 int data_len = 0;
535
536 if (use_epoch_data_format)
537 {
538 data_len = BLEN(buf) - tag_size;
539 tag_ptr = BPTR(buf) + data_len;
540 }
541 else
542 {
543 tag_ptr = BPTR(buf);
544 ASSERT(buf_advance(buf, tag_size));
545 data_len = BLEN(buf);
546 }
547
548 dmsg(D_PACKET_CONTENT, "DECRYPT MAC: %s", format_hex(tag_ptr, tag_size, 0, &gc));
549 dmsg(D_PACKET_CONTENT, "DECRYPT FROM: %s", format_hex(BPTR(buf), BLEN(buf), 0, &gc));
550
551 /* Buffer overflow check (should never fail) */
552 if (!buf_safe(&work, buf->len + cipher_ctx_block_size(ctx->cipher)))
553 {
554 CRYPT_ERROR("potential buffer overflow");
555 }
556
557 /* feed in tag and the authenticated data */
558 ASSERT(cipher_ctx_update_ad(ctx->cipher, ad_start, ad_size));
559 dmsg(D_PACKET_CONTENT, "DECRYPT AD: %s", format_hex(ad_start, ad_size, 0, &gc));
560
561 /* Decrypt and authenticate packet */
562 int outlen;
563 if (!cipher_ctx_update(ctx->cipher, BPTR(&work), &outlen, BPTR(buf), data_len))
564 {
565 CRYPT_ERROR("packet decryption failed");
566 }
567
568 ASSERT(buf_inc_len(&work, outlen));
569 if (!cipher_ctx_final_check_tag(ctx->cipher, BPTR(&work) + outlen, &outlen, tag_ptr, tag_size))
570 {
572 CRYPT_DROP("packet tag authentication failed");
573 }
574 ASSERT(buf_inc_len(&work, outlen));
575
576 dmsg(D_PACKET_CONTENT, "DECRYPT TO: %s", format_hex(BPTR(&work), BLEN(&work), 80, &gc));
577
578 if (!crypto_check_replay(opt, &pin, epoch, error_prefix, &gc))
579 {
580 goto error_exit;
581 }
582
583
584 /* update number of plaintext blocks decrypted. Use the (x + (n-1))/n trick
585 * to round up the result to the number of blocks used. */
586 const int blocksize = AEAD_LIMIT_BLOCKSIZE;
587 opt->key_ctx_bi.decrypt.plaintext_blocks += (outlen + (blocksize - 1)) / blocksize;
588
589 *buf = work;
590
591 gc_free(&gc);
592 return true;
593
594error_exit:
596 buf->len = 0;
597 gc_free(&gc);
598 return false;
599}
600
601/*
602 * Unwrap (authenticate, decrypt and check replay protection) CBC, OFB or CFB
603 * mode data channel packets.
604 *
605 * Set buf->len to 0 and return false on decrypt error.
606 *
607 * On success, buf is set to point to plaintext, true is returned.
608 */
609static bool
610openvpn_decrypt_v1(struct buffer *buf, struct buffer work, struct crypto_options *opt,
611 const struct frame *frame)
612{
613 static const char error_prefix[] = "Authenticate/Decrypt packet error";
614 struct gc_arena gc;
615 gc_init(&gc);
616
617 if (buf->len > 0 && opt)
618 {
619 const struct key_ctx *ctx = &opt->key_ctx_bi.decrypt;
620 struct packet_id_net pin;
621 bool have_pin = false;
622
623 dmsg(D_PACKET_CONTENT, "DECRYPT FROM: %s", format_hex(BPTR(buf), BLEN(buf), 80, &gc));
624
625 /* Verify the HMAC */
626 if (ctx->hmac)
627 {
628 int hmac_len;
629 uint8_t local_hmac[MAX_HMAC_KEY_LENGTH]; /* HMAC of ciphertext computed locally */
630
631 hmac_ctx_reset(ctx->hmac);
632
633 /* Assume the length of the input HMAC */
634 hmac_len = hmac_ctx_size(ctx->hmac);
635
636 /* Authentication fails if insufficient data in packet for HMAC */
637 if (buf->len < hmac_len)
638 {
639 CRYPT_ERROR("missing authentication info");
640 }
641
642 hmac_ctx_update(ctx->hmac, BPTR(buf) + hmac_len, BLEN(buf) - hmac_len);
643 hmac_ctx_final(ctx->hmac, local_hmac);
644
645 /* Compare locally computed HMAC with packet HMAC */
646 if (memcmp_constant_time(local_hmac, BPTR(buf), hmac_len))
647 {
648 CRYPT_DROP("packet HMAC authentication failed");
649 }
650
651 ASSERT(buf_advance(buf, hmac_len));
652 }
653
654 /* Decrypt packet ID + payload */
655
656 if (ctx->cipher)
657 {
658 const int iv_size = cipher_ctx_iv_length(ctx->cipher);
659 uint8_t iv_buf[OPENVPN_MAX_IV_LENGTH] = { 0 };
660 int outlen;
661
662 /* initialize work buffer with buf.headroom bytes of prepend capacity */
663 ASSERT(buf_init(&work, frame->buf.headroom));
664
665 /* read the IV from the packet */
666 if (buf->len < iv_size)
667 {
668 CRYPT_ERROR("missing IV info");
669 }
670 memcpy(iv_buf, BPTR(buf), iv_size);
671 ASSERT(buf_advance(buf, iv_size));
672 dmsg(D_PACKET_CONTENT, "DECRYPT IV: %s", format_hex(iv_buf, iv_size, 0, &gc));
673
674 if (buf->len < 1)
675 {
676 CRYPT_ERROR("missing payload");
677 }
678
679 /* ctx->cipher was already initialized with key & keylen */
680 if (!cipher_ctx_reset(ctx->cipher, iv_buf))
681 {
682 CRYPT_ERROR("decrypt initialization failed");
683 }
684
685 /* Buffer overflow check (should never happen) */
686 if (!buf_safe(&work, buf->len + cipher_ctx_block_size(ctx->cipher)))
687 {
688 CRYPT_ERROR("packet too big to decrypt");
689 }
690
691 /* Decrypt packet ID, payload */
692 if (!cipher_ctx_update(ctx->cipher, BPTR(&work), &outlen, BPTR(buf), BLEN(buf)))
693 {
694 CRYPT_ERROR("packet decryption failed");
695 }
696 ASSERT(buf_inc_len(&work, outlen));
697
698 /* Flush the decryption buffer */
699 if (!cipher_ctx_final(ctx->cipher, BPTR(&work) + outlen, &outlen))
700 {
701 CRYPT_DROP("packet authentication failed, dropping.");
702 }
703 ASSERT(buf_inc_len(&work, outlen));
704
705 dmsg(D_PACKET_CONTENT, "DECRYPT TO: %s", format_hex(BPTR(&work), BLEN(&work), 80, &gc));
706
707 /* Get packet ID from plaintext buffer or IV, depending on cipher mode */
708 {
709 if (cipher_ctx_mode_cbc(ctx->cipher))
710 {
712 {
713 if (!packet_id_read(&pin, &work,
715 {
716 CRYPT_ERROR("error reading CBC packet-id");
717 }
718 have_pin = true;
719 }
720 }
721 else if (cipher_ctx_mode_ofb_cfb(ctx->cipher))
722 {
723 struct buffer b;
724
725 /* packet-ID required for this mode. */
727
729 if (!packet_id_read(&pin, &b, true))
730 {
731 CRYPT_ERROR("error reading CFB/OFB packet-id");
732 }
733 have_pin = true;
734 }
735 else /* We only support CBC, CFB, or OFB modes right now */
736 {
737 ASSERT(0);
738 }
739 }
740 }
741 else
742 {
743 work = *buf;
745 {
747 {
748 CRYPT_ERROR("error reading packet-id");
749 }
751 }
752 }
753
754 if (have_pin && !crypto_check_replay(opt, &pin, 0, error_prefix, &gc))
755 {
756 goto error_exit;
757 }
758 *buf = work;
759 }
760
761 gc_free(&gc);
762 return true;
763
766 buf->len = 0;
767 gc_free(&gc);
768 return false;
769}
770
771
772bool
773openvpn_decrypt(struct buffer *buf, struct buffer work, struct crypto_options *opt,
774 const struct frame *frame, const uint8_t *ad_start)
775{
776 bool ret = false;
777
778 if (buf->len > 0 && opt)
779 {
781 {
782 ret = openvpn_decrypt_aead(buf, work, opt, frame, ad_start);
783 }
784 else
785 {
786 ret = openvpn_decrypt_v1(buf, work, opt, frame);
787 }
788 }
789 else
790 {
791 ret = true;
792 }
793 return ret;
794}
795
796unsigned int
797calculate_crypto_overhead(const struct key_type *kt, unsigned int pkt_id_size, bool occ)
798{
799 unsigned int crypto_overhead = 0;
800
801 if (!cipher_kt_mode_cbc(kt->cipher))
802 {
803 /* In CBC mode, the packet id is part of the payload size/overhead */
805 }
806
808 {
809 /* For AEAD ciphers, we basically use a stream cipher/CTR for
810 * the encryption, so no overhead apart from the extra bytes
811 * we add */
813
814 if (occ)
815 {
816 /* the frame calculation of old clients adds these to the link-mtu
817 * even though they are not part of the actual packet */
820 }
821 }
822 else
823 {
824 if (cipher_defined(kt->cipher))
825 {
826 /* CBC, OFB or CFB mode */
827 if (occ)
828 {
830 }
831 /* IV is always added (no-iv has been removed a while ago) */
833 }
834 if (md_defined(kt->digest))
835 {
837 }
838 }
839
840 return crypto_overhead;
841}
842
843unsigned int
849
850static void
851warn_insecure_key_type(const char *ciphername)
852{
853 if (cipher_kt_insecure(ciphername))
854 {
855 msg(M_WARN,
856 "WARNING: INSECURE cipher (%s) with block size less than 128"
857 " bit (%d bit). This allows attacks like SWEET32. Mitigate by "
858 "using a --cipher with a larger block size (e.g. AES-256-CBC). "
859 "Support for these insecure ciphers will be removed in "
860 "OpenVPN 2.7.",
861 ciphername, cipher_kt_block_size(ciphername) * 8);
862 }
863}
864
865/*
866 * Build a struct key_type.
867 */
868void
869init_key_type(struct key_type *kt, const char *ciphername, const char *authname, bool tls_mode,
870 bool warn)
871{
872 bool aead_cipher = false;
873
874 ASSERT(ciphername);
875 ASSERT(authname);
876
877 CLEAR(*kt);
878 kt->cipher = ciphername;
879 if (strcmp(ciphername, "none") != 0)
880 {
881 if (!cipher_valid(ciphername))
882 {
883 msg(M_FATAL, "Cipher %s not supported", ciphername);
884 }
885
886 /* check legal cipher mode */
891#endif
892 ))
893 {
894 msg(M_FATAL, "Cipher '%s' mode not supported", ciphername);
895 }
896
898 {
899 msg(M_FATAL, "Cipher '%s' not allowed: block size too big.", ciphername);
900 }
901 if (warn)
902 {
903 warn_insecure_key_type(ciphername);
904 }
905 }
906 else
907 {
908 if (warn)
909 {
910 msg(M_WARN, "******* WARNING *******: '--cipher none' was specified. "
911 "This means NO encryption will be performed and tunnelled "
912 "data WILL be transmitted in clear text over the network! "
913 "PLEASE DO RECONSIDER THIS SETTING!");
914 }
915 }
916 kt->digest = authname;
917 if (strcmp(authname, "none") != 0)
918 {
919 if (aead_cipher) /* Ignore auth for AEAD ciphers */
920 {
921 kt->digest = "none";
922 }
923 else
924 {
925 int hmac_length = md_kt_size(kt->digest);
926
928 {
929 msg(M_FATAL, "HMAC '%s' not allowed: digest size too big.", authname);
930 }
931 }
932 }
933 else if (!aead_cipher)
934 {
935 if (warn)
936 {
937 msg(M_WARN, "******* WARNING *******: '--auth none' was specified. "
938 "This means no authentication will be performed on received "
939 "packets, meaning you CANNOT trust that the data received by "
940 "the remote side have NOT been manipulated. "
941 "PLEASE DO RECONSIDER THIS SETTING!");
942 }
943 }
944}
945
957static void
959{
960 /* Only use implicit IV in AEAD cipher mode, where HMAC key is not used */
962 {
963 size_t impl_iv_len = 0;
964 size_t impl_iv_offset = 0;
966
967 /* Epoch keys use XOR of full IV length with the packet id to generate
968 * IVs. Old data format uses concatenation instead (XOR with 0 for the
969 * first 4 bytes (sizeof(packet_id_type) */
970 if (key->epoch)
971 {
973 impl_iv_offset = 0;
974 }
975 else
976 {
979 }
983 CLEAR(ctx->implicit_iv);
985 }
986}
987
988/* given a key and key_type, build a key_ctx */
989void
990init_key_ctx(struct key_ctx *ctx, const struct key_parameters *key, const struct key_type *kt,
991 int enc, const char *prefix)
992{
993 struct gc_arena gc = gc_new();
994 CLEAR(*ctx);
995 if (cipher_defined(kt->cipher))
996 {
997 ASSERT(key->cipher_size >= cipher_kt_key_size(kt->cipher));
998 ctx->cipher = cipher_ctx_new();
999 cipher_ctx_init(ctx->cipher, key->cipher, kt->cipher, enc);
1000
1001 const char *ciphername = cipher_kt_name(kt->cipher);
1002 msg(D_CIPHER_INIT, "%s: Cipher '%s' initialized with %d bit key", prefix, ciphername,
1003 cipher_kt_key_size(kt->cipher) * 8);
1004
1005 dmsg(D_SHOW_KEYS, "%s: CIPHER KEY: %s", prefix,
1007 dmsg(D_CRYPTO_DEBUG, "%s: CIPHER block_size=%d iv_size=%d", prefix,
1009 warn_insecure_key_type(ciphername);
1010 }
1011
1012 if (md_defined(kt->digest))
1013 {
1014 ASSERT(key->hmac_size >= md_kt_size(kt->digest));
1015 ctx->hmac = hmac_ctx_new();
1016 hmac_ctx_init(ctx->hmac, key->hmac, kt->digest);
1017
1018 msg(D_CIPHER_INIT, "%s: Using %d bit message hash '%s' for HMAC authentication", prefix,
1019 md_kt_size(kt->digest) * 8, md_kt_name(kt->digest));
1020
1021 dmsg(D_SHOW_KEYS, "%s: HMAC KEY: %s", prefix,
1022 format_hex(key->hmac, md_kt_size(kt->digest), 0, &gc));
1023
1024 dmsg(D_CRYPTO_DEBUG, "%s: HMAC size=%d block_size=%d", prefix, md_kt_size(kt->digest),
1025 hmac_ctx_size(ctx->hmac));
1026 }
1027 ctx->epoch = key->epoch;
1028 gc_free(&gc);
1029}
1030
1031void
1032init_key_bi_ctx_send(struct key_ctx *ctx, const struct key_parameters *key_params,
1033 const struct key_type *kt, const char *name)
1034{
1035 char log_prefix[128] = { 0 };
1036
1037 snprintf(log_prefix, sizeof(log_prefix), "Outgoing %s", name);
1038 init_key_ctx(ctx, key_params, kt, OPENVPN_OP_ENCRYPT, log_prefix);
1039 key_ctx_update_implicit_iv(ctx, key_params);
1040 ctx->epoch = key_params->epoch;
1041}
1042
1043void
1044init_key_bi_ctx_recv(struct key_ctx *ctx, const struct key_parameters *key_params,
1045 const struct key_type *kt, const char *name)
1046{
1047 char log_prefix[128] = { 0 };
1048
1049 snprintf(log_prefix, sizeof(log_prefix), "Incoming %s", name);
1050 init_key_ctx(ctx, key_params, kt, OPENVPN_OP_DECRYPT, log_prefix);
1051 key_ctx_update_implicit_iv(ctx, key_params);
1052 ctx->epoch = key_params->epoch;
1053}
1054
1055void
1056init_key_ctx_bi(struct key_ctx_bi *ctx, const struct key2 *key2, int key_direction,
1057 const struct key_type *kt, const char *name)
1058{
1059 struct key_direction_state kds;
1060
1061 key_direction_state_init(&kds, key_direction);
1062
1063 struct key_parameters send_key;
1064 struct key_parameters recv_key;
1065
1066 key_parameters_from_key(&send_key, &key2->keys[kds.out_key]);
1067 key_parameters_from_key(&recv_key, &key2->keys[kds.in_key]);
1068
1069 init_key_bi_ctx_send(&ctx->encrypt, &send_key, kt, name);
1070 init_key_bi_ctx_recv(&ctx->decrypt, &recv_key, kt, name);
1071 ctx->initialized = true;
1072}
1073
1074void
1076{
1077 if (ctx->cipher)
1078 {
1079 cipher_ctx_free(ctx->cipher);
1080 ctx->cipher = NULL;
1081 }
1082 if (ctx->hmac)
1083 {
1084 hmac_ctx_cleanup(ctx->hmac);
1085 hmac_ctx_free(ctx->hmac);
1086 ctx->hmac = NULL;
1087 }
1088 CLEAR(ctx->implicit_iv);
1089 ctx->plaintext_blocks = 0;
1090 ctx->epoch = 0;
1091}
1092
1093void
1095{
1096 free_key_ctx(&ctx->encrypt);
1097 free_key_ctx(&ctx->decrypt);
1098 ctx->initialized = false;
1099}
1100
1101static bool
1102key_is_zero(struct key *key, const struct key_type *kt)
1103{
1104 int cipher_length = cipher_kt_key_size(kt->cipher);
1105 for (int i = 0; i < cipher_length; ++i)
1106 {
1107 if (key->cipher[i])
1108 {
1109 return false;
1110 }
1111 }
1112 msg(D_CRYPT_ERRORS, "CRYPTO INFO: WARNING: zero key detected");
1113 return true;
1114}
1115
1116/*
1117 * Make sure that cipher key is a valid key for current key_type.
1118 */
1119bool
1120check_key(struct key *key, const struct key_type *kt)
1121{
1122 if (cipher_defined(kt->cipher))
1123 {
1124 /*
1125 * Check for zero key
1126 */
1127 if (key_is_zero(key, kt))
1128 {
1129 return false;
1130 }
1131 }
1132 return true;
1133}
1134
1135/*
1136 * Generate a random key.
1137 */
1138static void
1140{
1141 int cipher_len = MAX_CIPHER_KEY_LENGTH;
1142 int hmac_len = MAX_HMAC_KEY_LENGTH;
1143
1144 struct gc_arena gc = gc_new();
1145
1146 CLEAR(*key);
1147 if (!rand_bytes(key->cipher, cipher_len) || !rand_bytes(key->hmac, hmac_len))
1148 {
1149 msg(M_FATAL, "ERROR: Random number generator cannot obtain entropy for key generation");
1150 }
1151
1152 dmsg(D_SHOW_KEY_SOURCE, "Cipher source entropy: %s",
1153 format_hex(key->cipher, cipher_len, 0, &gc));
1154 dmsg(D_SHOW_KEY_SOURCE, "HMAC source entropy: %s", format_hex(key->hmac, hmac_len, 0, &gc));
1155
1156 gc_free(&gc);
1157}
1158
1159static void
1160key_print(const struct key *key, const struct key_type *kt, const char *prefix)
1161{
1162 struct gc_arena gc = gc_new();
1163 dmsg(D_SHOW_KEY_SOURCE, "%s (cipher, %s, %d bits): %s", prefix, cipher_kt_name(kt->cipher),
1164 cipher_kt_key_size(kt->cipher) * 8,
1166 dmsg(D_SHOW_KEY_SOURCE, "%s (hmac, %s, %d bits): %s", prefix, md_kt_name(kt->digest),
1167 md_kt_size(kt->digest) * 8, format_hex(key->hmac, md_kt_size(kt->digest), 0, &gc));
1168 gc_free(&gc);
1169}
1173void
1174key2_print(const struct key2 *k, const struct key_type *kt, const char *prefix0,
1175 const char *prefix1)
1176{
1177 ASSERT(k->n == 2);
1178 key_print(&k->keys[0], kt, prefix0);
1179 key_print(&k->keys[1], kt, prefix1);
1180}
1181
1182void
1183key_parameters_from_key(struct key_parameters *key_params, const struct key *key)
1184{
1185 CLEAR(*key_params);
1186 memcpy(key_params->cipher, key->cipher, MAX_CIPHER_KEY_LENGTH);
1187 key_params->cipher_size = MAX_CIPHER_KEY_LENGTH;
1188 memcpy(key_params->hmac, key->hmac, MAX_HMAC_KEY_LENGTH);
1189 key_params->hmac_size = MAX_HMAC_KEY_LENGTH;
1190}
1191
1192void
1194{
1195 int i, j;
1196 struct gc_arena gc = gc_new();
1198 struct buffer work = alloc_buf_gc(BUF_SIZE(frame), &gc);
1201 struct buffer buf = clear_buf();
1202 void *buf_p;
1203
1204 /* init work */
1205 ASSERT(buf_init(&work, frame->buf.headroom));
1206
1207 /* init implicit IV */
1208 {
1209 cipher_ctx_t *cipher = co->key_ctx_bi.encrypt.cipher;
1210 if (cipher_ctx_mode_aead(cipher))
1211 {
1214
1215 /* Generate dummy implicit IV */
1217
1220 }
1221 }
1222
1223 msg(M_INFO, "Entering " PACKAGE_NAME " crypto self-test mode.");
1224 for (i = 1; i <= frame->buf.payload_size; ++i)
1225 {
1226 update_time();
1227
1228 msg(M_INFO, "TESTING ENCRYPT/DECRYPT of packet length=%d", i);
1229
1230 /*
1231 * Load src with random data.
1232 */
1233 ASSERT(buf_init(&src, 0));
1234 ASSERT(i <= src.capacity);
1235 src.len = i;
1237
1238 /* copy source to input buf */
1239 buf = work;
1240 buf_p = buf_write_alloc(&buf, BLEN(&src));
1241 ASSERT(buf_p);
1242 memcpy(buf_p, BPTR(&src), BLEN(&src));
1243
1244 /* initialize work buffer with buf.headroom bytes of prepend capacity */
1246
1247 /* encrypt */
1249
1250 /* decrypt */
1251 openvpn_decrypt(&buf, decrypt_workspace, co, frame, BPTR(&buf));
1252
1253 /* compare */
1254 if (buf.len != src.len)
1255 {
1256 msg(M_FATAL, "SELF TEST FAILED, src.len=%d buf.len=%d", src.len, buf.len);
1257 }
1258 for (j = 0; j < i; ++j)
1259 {
1260 const uint8_t in = *(BPTR(&src) + j);
1261 const uint8_t out = *(BPTR(&buf) + j);
1262 if (in != out)
1263 {
1264 msg(M_FATAL, "SELF TEST FAILED, pos=%d in=%d out=%d", j, in, out);
1265 }
1266 }
1267 }
1268 msg(M_INFO, PACKAGE_NAME " crypto self-test mode SUCCEEDED.");
1269 gc_free(&gc);
1270}
1271
1272const char *
1274{
1275 if (is_inline)
1276 {
1277 return "[[INLINE]]";
1278 }
1279
1280 return np(str);
1281}
1282
1283void
1285 const char *key_file, bool key_inline, const int key_direction,
1286 const char *key_name, const char *opt_name, struct key2 *keydata)
1287{
1288 struct key2 key2;
1289 struct key_direction_state kds;
1290 unsigned int flags = RKF_MUST_SUCCEED;
1291
1292 if (key_inline)
1293 {
1294 flags |= RKF_INLINE;
1295 }
1296 read_key_file(&key2, key_file, flags);
1297
1298 if (key2.n != 2)
1299 {
1300 msg(M_ERR,
1301 "File '%s' does not have OpenVPN Static Key format. Using "
1302 "free-form passphrase file is not supported anymore.",
1303 print_key_filename(key_file, key_inline));
1304 }
1305
1306 /* check for and fix highly unlikely key problems */
1307 verify_fix_key2(&key2, key_type, key_file);
1308
1309 /* handle key direction */
1310 key_direction_state_init(&kds, key_direction);
1311 must_have_n_keys(key_file, opt_name, &key2, kds.need_keys);
1312
1313 /* initialize key in both directions */
1314 init_key_ctx_bi(ctx, &key2, key_direction, key_type, key_name);
1315 if (keydata)
1316 {
1317 *keydata = key2;
1318 }
1319 secure_memzero(&key2, sizeof(key2));
1320}
1321
1322/* header and footer for static key file */
1323static const char static_key_head[] = "-----BEGIN OpenVPN Static key V1-----";
1324static const char static_key_foot[] = "-----END OpenVPN Static key V1-----";
1325
1326static const char printable_char_fmt[] =
1327 "Non-Hex character ('%c') found at line %d in key file '%s' (%d/%d/%d bytes found/min/max)";
1328
1329static const char unprintable_char_fmt[] =
1330 "Non-Hex, unprintable character (0x%02x) found at line %d in key file '%s' (%d/%d/%d bytes found/min/max)";
1331
1332/* read key from file */
1333
1334void
1335read_key_file(struct key2 *key2, const char *file, const unsigned int flags)
1336{
1337 struct gc_arena gc = gc_new();
1338 struct buffer in;
1339 int size;
1340 uint8_t hex_byte[3] = { 0, 0, 0 };
1341
1342 /* parse info */
1343 const unsigned char *cp;
1344 int hb_index = 0;
1345 int line_num = 1;
1346 int line_index = 0;
1347 int match = 0;
1348
1349 /* output */
1350 uint8_t *out = (uint8_t *)&key2->keys;
1351 const int keylen = sizeof(key2->keys);
1352 int count = 0;
1353
1354 /* parse states */
1355#define PARSE_INITIAL 0
1356#define PARSE_HEAD 1
1357#define PARSE_DATA 2
1358#define PARSE_DATA_COMPLETE 3
1359#define PARSE_FOOT 4
1360#define PARSE_FINISHED 5
1361 int state = PARSE_INITIAL;
1362
1363 /* constants */
1364 const int hlen = strlen(static_key_head);
1365 const int flen = strlen(static_key_foot);
1366 const int onekeylen = sizeof(key2->keys[0]);
1367
1368 CLEAR(*key2);
1369
1370 /*
1371 * Key can be provided as a filename in 'file' or if RKF_INLINE
1372 * is set, the actual key data itself in ascii form.
1373 */
1374 if (flags & RKF_INLINE) /* 'file' is a string containing ascii representation of key */
1375 {
1376 size = strlen(file) + 1;
1377 buf_set_read(&in, (const uint8_t *)file, size);
1378 }
1379 else /* 'file' is a filename which refers to a file containing the ascii key */
1380 {
1381 in = buffer_read_from_file(file, &gc);
1382 if (!buf_valid(&in))
1383 {
1384 msg(M_FATAL, "Read error on key file ('%s')", file);
1385 }
1386
1387 size = in.len;
1388 }
1389
1390 cp = (unsigned char *)in.data;
1391 while (size > 0)
1392 {
1393 const unsigned char c = *cp;
1394
1395#if 0
1396 msg(M_INFO, "char='%c'[%d] s=%d ln=%d li=%d m=%d c=%d",
1397 c, (int)c, state, line_num, line_index, match, count);
1398#endif
1399
1400 if (c == '\n')
1401 {
1402 line_index = match = 0;
1403 ++line_num;
1404 }
1405 else
1406 {
1407 /* first char of new line */
1408 if (!line_index)
1409 {
1410 /* first char of line after header line? */
1411 if (state == PARSE_HEAD)
1412 {
1413 state = PARSE_DATA;
1414 }
1415
1416 /* first char of footer */
1417 if ((state == PARSE_DATA || state == PARSE_DATA_COMPLETE) && c == '-')
1418 {
1419 state = PARSE_FOOT;
1420 }
1421 }
1422
1423 /* compare read chars with header line */
1424 if (state == PARSE_INITIAL)
1425 {
1426 if (line_index < hlen && c == static_key_head[line_index])
1427 {
1428 if (++match == hlen)
1429 {
1430 state = PARSE_HEAD;
1431 }
1432 }
1433 }
1434
1435 /* compare read chars with footer line */
1436 if (state == PARSE_FOOT)
1437 {
1439 {
1440 if (++match == flen)
1441 {
1442 state = PARSE_FINISHED;
1443 }
1444 }
1445 }
1446
1447 /* reading key */
1448 if (state == PARSE_DATA)
1449 {
1450 if (isxdigit(c))
1451 {
1452 ASSERT(hb_index >= 0 && hb_index < 2);
1453 hex_byte[hb_index++] = c;
1454 if (hb_index == 2)
1455 {
1456 uint8_t u;
1457 ASSERT(sscanf((const char *)hex_byte, "%" SCNx8, &u) == 1);
1458 *out++ = u;
1459 hb_index = 0;
1460 if (++count == keylen)
1461 {
1462 state = PARSE_DATA_COMPLETE;
1463 }
1464 }
1465 }
1466 else if (isspace(c))
1467 {
1468 /* ignore white space characters */
1469 }
1470 else
1471 {
1474 keylen);
1475 }
1476 }
1477 ++line_index;
1478 }
1479 ++cp;
1480 --size;
1481 }
1482
1483 /*
1484 * Normally we will read either 1 or 2 keys from file.
1485 */
1486 key2->n = count / onekeylen;
1487
1488 ASSERT(key2->n >= 0 && key2->n <= (int)SIZE(key2->keys));
1489
1490 if (flags & RKF_MUST_SUCCEED)
1491 {
1492 if (!key2->n)
1493 {
1494 msg(M_FATAL,
1495 "Insufficient key material or header text not found in file '%s' (%d/%d/%d bytes found/min/max)",
1497 }
1498
1499 if (state != PARSE_FINISHED)
1500 {
1501 msg(M_FATAL, "Footer text not found in file '%s' (%d/%d/%d bytes found/min/max)",
1503 }
1504 }
1505
1506 /* zero file read buffer if not an inline file */
1507 if (!(flags & RKF_INLINE))
1508 {
1509 buf_clear(&in);
1510 }
1511
1512#if 0
1513 /* DEBUGGING */
1514 {
1515 int i;
1516 printf("KEY READ, n=%d\n", key2->n);
1517 for (i = 0; i < (int) SIZE(key2->keys); ++i)
1518 {
1519 /* format key as ascii */
1520 const char *fmt = format_hex_ex((const uint8_t *)&key2->keys[i],
1521 sizeof(key2->keys[i]),
1522 0,
1523 16,
1524 "\n",
1525 &gc);
1526 printf("[%d]\n%s\n\n", i, fmt);
1527 }
1528 }
1529#endif
1530
1531 /* pop our garbage collection level */
1532 gc_free(&gc);
1533}
1534
1535int
1536write_key_file(const int nkeys, const char *filename)
1537{
1538 struct gc_arena gc = gc_new();
1539
1540 int nbits = nkeys * sizeof(struct key) * 8;
1541
1542 /* must be large enough to hold full key file */
1543 struct buffer out = alloc_buf_gc(2048, &gc);
1544
1545 /* how to format the ascii file representation of key */
1546 const int bytes_per_line = 16;
1547
1548 /* write header */
1549 buf_printf(&out, "#\n# %d bit OpenVPN static key\n#\n", nbits);
1550 buf_printf(&out, "%s\n", static_key_head);
1551
1552 for (int i = 0; i < nkeys; ++i)
1553 {
1554 struct key key;
1555 char *fmt;
1556
1557 /* generate random bits */
1559
1560 /* format key as ascii */
1561 fmt = format_hex_ex((const uint8_t *)&key, sizeof(key), 0, bytes_per_line, "\n", &gc);
1562
1563 /* write to holding buffer */
1564 buf_printf(&out, "%s\n", fmt);
1565
1566 /* zero memory which held key component (will be freed by GC) */
1567 secure_memzero(fmt, strlen(fmt));
1568 secure_memzero(&key, sizeof(key));
1569 }
1570
1571 buf_printf(&out, "%s\n", static_key_foot);
1572
1573 /* write key file to stdout if no filename given */
1574 if (!filename || strcmp(filename, "") == 0)
1575 {
1576 printf("%.*s\n", BLEN(&out), BPTR(&out));
1577 }
1578 /* write key file, now formatted in out, to file */
1579 else if (!buffer_write_file(filename, &out))
1580 {
1581 nbits = -1;
1582 }
1583
1584 /* zero memory which held file content (memory will be freed by GC) */
1585 buf_clear(&out);
1586
1587 /* pop our garbage collection level */
1588 gc_free(&gc);
1589
1590 return nbits;
1591}
1592
1593void
1594must_have_n_keys(const char *filename, const char *option, const struct key2 *key2, int n)
1595{
1596 if (key2->n < n)
1597 {
1598#ifdef ENABLE_SMALL
1599 msg(M_FATAL,
1600 "Key file '%s' used in --%s contains insufficient key material [keys found=%d required=%d]",
1601 filename, option, key2->n, n);
1602#else
1603 msg(M_FATAL,
1604 "Key file '%s' used in --%s contains insufficient key material [keys found=%d required=%d] -- try generating a new key file with '" PACKAGE
1605 " --genkey secret [file]', or use the existing key file in bidirectional mode by specifying --%s without a key direction parameter",
1606 filename, option, key2->n, n, option);
1607#endif
1608 }
1609}
1610
1611int
1612ascii2keydirection(int msglevel, const char *str)
1613{
1614 if (!str)
1615 {
1617 }
1618 else if (!strcmp(str, "0"))
1619 {
1620 return KEY_DIRECTION_NORMAL;
1621 }
1622 else if (!strcmp(str, "1"))
1623 {
1624 return KEY_DIRECTION_INVERSE;
1625 }
1626 else
1627 {
1628 msg(msglevel, "Unknown key direction '%s' -- must be '0' or '1'", str);
1629 return -1;
1630 }
1631 return KEY_DIRECTION_BIDIRECTIONAL; /* NOTREACHED */
1632}
1633
1634const char *
1635keydirection2ascii(int kd, bool remote, bool humanreadable)
1636{
1638 {
1639 if (humanreadable)
1640 {
1641 return "not set";
1642 }
1643 else
1644 {
1645 return NULL;
1646 }
1647 }
1648 else if (kd == KEY_DIRECTION_NORMAL)
1649 {
1650 return remote ? "1" : "0";
1651 }
1652 else if (kd == KEY_DIRECTION_INVERSE)
1653 {
1654 return remote ? "0" : "1";
1655 }
1656 else
1657 {
1658 ASSERT(0);
1659 }
1660 return NULL; /* NOTREACHED */
1661}
1662
1663void
1664key_direction_state_init(struct key_direction_state *kds, int key_direction)
1665{
1666 CLEAR(*kds);
1667 switch (key_direction)
1668 {
1670 kds->out_key = 0;
1671 kds->in_key = 1;
1672 kds->need_keys = 2;
1673 break;
1674
1676 kds->out_key = 1;
1677 kds->in_key = 0;
1678 kds->need_keys = 2;
1679 break;
1680
1682 kds->out_key = 0;
1683 kds->in_key = 0;
1684 kds->need_keys = 1;
1685 break;
1686
1687 default:
1688 ASSERT(0);
1689 }
1690}
1691
1692void
1693verify_fix_key2(struct key2 *key2, const struct key_type *kt, const char *shared_secret_file)
1694{
1695 int i;
1696
1697 for (i = 0; i < key2->n; ++i)
1698 {
1699 /* This should be a very improbable failure */
1700 if (!check_key(&key2->keys[i], kt))
1701 {
1702 msg(M_FATAL, "Key #%d in '%s' is bad. Try making a new key with --genkey.", i + 1,
1703 shared_secret_file);
1704 }
1705 }
1706}
1707
1708void
1709prng_bytes(uint8_t *output, int len)
1710{
1711 ASSERT(rand_bytes(output, len));
1712}
1713
1714/* an analogue to the random() function, but use prng_bytes */
1715long int
1717{
1718 long int l;
1719 prng_bytes((unsigned char *)&l, sizeof(l));
1720 if (l < 0)
1721 {
1722 l = -l;
1723 }
1724 return l;
1725}
1726
1727void
1728print_cipher(const char *ciphername)
1729{
1730 printf("%s (%d bit key, ", cipher_kt_name(ciphername), cipher_kt_key_size(ciphername) * 8);
1731
1732 if (cipher_kt_block_size(ciphername) == 1)
1733 {
1734 printf("stream cipher");
1735 }
1736 else
1737 {
1738 printf("%d bit block", cipher_kt_block_size(ciphername) * 8);
1739 }
1740
1741 if (!cipher_kt_mode_cbc(ciphername))
1742 {
1743 printf(", TLS client/server mode only");
1744 }
1745
1746 const char *reason;
1747 if (!cipher_valid_reason(ciphername, &reason))
1748 {
1749 printf(", %s", reason);
1750 }
1751
1752 printf(")\n");
1753}
1754
1755static const cipher_name_pair *
1756get_cipher_name_pair(const char *cipher_name)
1757{
1758 const cipher_name_pair *pair;
1759 size_t i = 0;
1760
1761 /* Search for a cipher name translation */
1763 {
1765 if (0 == strcmp(cipher_name, pair->openvpn_name)
1766 || 0 == strcmp(cipher_name, pair->lib_name))
1767 {
1768 return pair;
1769 }
1770 }
1771
1772 /* Nothing found, return null */
1773 return NULL;
1774}
1775
1776const char *
1778{
1779 const cipher_name_pair *pair = get_cipher_name_pair(cipher_name);
1780
1781 if (NULL == pair)
1782 {
1783 return cipher_name;
1784 }
1785
1786 return pair->lib_name;
1787}
1788
1789const char *
1790translate_cipher_name_to_openvpn(const char *cipher_name)
1791{
1792 const cipher_name_pair *pair = get_cipher_name_pair(cipher_name);
1793
1794 if (NULL == pair)
1795 {
1796 return cipher_name;
1797 }
1798
1799 return pair->openvpn_name;
1800}
1801
1802void
1803write_pem_key_file(const char *filename, const char *pem_name)
1804{
1805 struct gc_arena gc = gc_new();
1806 struct key server_key = { 0 };
1807 struct buffer server_key_buf = clear_buf();
1808 struct buffer server_key_pem = clear_buf();
1809
1810 if (!rand_bytes((void *)&server_key, sizeof(server_key)))
1811 {
1812 msg(M_NONFATAL, "ERROR: could not generate random key");
1813 goto cleanup;
1814 }
1815 buf_set_read(&server_key_buf, (void *)&server_key, sizeof(server_key));
1817 {
1818 msg(M_WARN, "ERROR: could not PEM-encode key");
1819 goto cleanup;
1820 }
1821
1822 if (!filename || strcmp(filename, "") == 0)
1823 {
1825 }
1826 else if (!buffer_write_file(filename, &server_key_pem))
1827 {
1828 msg(M_ERR, "ERROR: could not write key file");
1829 goto cleanup;
1830 }
1831
1832cleanup:
1835 gc_free(&gc);
1836 return;
1837}
1838
1839bool
1841{
1842 const int len = BCAP(key);
1843
1844 msg(M_INFO, "Using random %s.", key_name);
1845
1846 if (!rand_bytes(BEND(key), len))
1847 {
1848 msg(M_WARN, "ERROR: could not generate random key");
1849 return false;
1850 }
1851
1853
1854 return true;
1855}
1856
1857bool
1858read_pem_key_file(struct buffer *key, const char *pem_name, const char *key_file, bool key_inline)
1859{
1860 bool ret = false;
1861 struct buffer key_pem = { 0 };
1862 struct gc_arena gc = gc_new();
1863
1864 if (!key_inline)
1865 {
1866 key_pem = buffer_read_from_file(key_file, &gc);
1867 if (!buf_valid(&key_pem))
1868 {
1869 msg(M_WARN, "ERROR: failed to read %s file (%s)", pem_name, key_file);
1870 goto cleanup;
1871 }
1872 }
1873 else
1874 {
1875 buf_set_read(&key_pem, (const void *)key_file, strlen(key_file) + 1);
1876 }
1877
1878 if (!crypto_pem_decode(pem_name, key, &key_pem))
1879 {
1880 msg(M_WARN, "ERROR: %s pem decode failed", pem_name);
1881 goto cleanup;
1882 }
1883
1884 ret = true;
1885cleanup:
1886 if (!key_inline)
1887 {
1888 buf_clear(&key_pem);
1889 }
1890 gc_free(&gc);
1891 return ret;
1892}
1893
1894bool
1896{
1897 /* Modern TLS libraries might no longer support the TLS 1.0 PRF with
1898 * MD5+SHA1. This allows us to establish connections only
1899 * with other 2.6.0+ OpenVPN peers.
1900 * Do a simple dummy test here to see if it works. */
1901 const char *seed = "tls1-prf-test";
1902 const char *secret = "tls1-prf-test-secret";
1903 uint8_t out[8];
1904 uint8_t expected_out[] = { 'q', 'D', 0xfe, '%', '@', 's', 'u', 0x95 };
1905
1906 int ret = ssl_tls1_PRF((uint8_t *)seed, strlen(seed), (uint8_t *)secret,
1907 strlen(secret), out, sizeof(out));
1908
1909 return (ret && memcmp(out, expected_out, sizeof(out)) == 0);
1910}
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
bool buf_printf(struct buffer *buf, const char *format,...)
Definition buffer.c:241
char * format_hex_ex(const uint8_t *data, int size, int maxoutput, unsigned int space_break_flags, const char *separator, struct gc_arena *gc)
Definition buffer.c:483
struct buffer alloc_buf_gc(size_t size, struct gc_arena *gc)
Definition buffer.c:89
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:1348
#define BEND(buf)
Definition buffer.h:124
static char * format_hex(const uint8_t *data, int size, int maxoutput, struct gc_arena *gc)
Definition buffer.h:503
static struct buffer clear_buf(void)
Return an empty struct buffer.
Definition buffer.h:222
#define BPTR(buf)
Definition buffer.h:123
static bool buf_write_prepend(struct buffer *dest, const void *src, int size)
Definition buffer.h:672
static bool buf_inc_len(struct buffer *buf, int inc)
Definition buffer.h:588
static bool buf_valid(const struct buffer *buf)
Definition buffer.h:234
static void gc_init(struct gc_arena *a)
Definition buffer.h:994
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_advance(struct buffer *buf, int size)
Definition buffer.h:616
static int buf_len(const struct buffer *buf)
Definition buffer.h:253
static void buf_set_read(struct buffer *buf, const uint8_t *data, size_t size)
Definition buffer.h:348
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 uint8_t * buf_prepend(struct buffer *buf, int size)
Definition buffer.h:604
#define BLEN(buf)
Definition buffer.h:126
#define BCAP(buf)
Definition buffer.h:129
static void gc_free(struct gc_arena *a)
Definition buffer.h:1015
#define buf_init(buf, offset)
Definition buffer.h:209
static struct gc_arena gc_new(void)
Definition buffer.h:1007
#define key2
Definition cert_data.h:80
const char * translate_cipher_name_from_openvpn(const char *cipher_name)
Translate an OpenVPN cipher name to a crypto library cipher name.
Definition crypto.c:1777
static void key_print(const struct key *key, const struct key_type *kt, const char *prefix)
Definition crypto.c:1160
static const char static_key_head[]
Definition crypto.c:1323
void free_key_ctx_bi(struct key_ctx_bi *ctx)
Definition crypto.c:1094
const char * print_key_filename(const char *str, bool is_inline)
To be used when printing a string that may contain inline data.
Definition crypto.c:1273
static void warn_insecure_key_type(const char *ciphername)
Definition crypto.c:851
void prng_bytes(uint8_t *output, int len)
Definition crypto.c:1709
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:990
unsigned int calculate_crypto_overhead(const struct key_type *kt, unsigned int pkt_id_size, bool occ)
Calculate the maximum overhead that our encryption has on a packet.
Definition crypto.c:797
void key2_print(const struct key2 *k, const struct key_type *kt, const char *prefix0, const char *prefix1)
Prints the keys in a key2 structure.
Definition crypto.c:1174
void verify_fix_key2(struct key2 *key2, const struct key_type *kt, const char *shared_secret_file)
Definition crypto.c:1693
void init_key_bi_ctx_send(struct key_ctx *ctx, const struct key_parameters *key_params, const struct key_type *kt, const char *name)
Definition crypto.c:1032
void read_key_file(struct key2 *key2, const char *file, const unsigned int flags)
Definition crypto.c:1335
long int get_random(void)
Definition crypto.c:1716
static bool key_is_zero(struct key *key, const struct key_type *kt)
Definition crypto.c:1102
static bool openvpn_decrypt_aead(struct buffer *buf, struct buffer work, struct crypto_options *opt, const struct frame *frame, const uint8_t *ad_start)
Unwrap (authenticate, decrypt and check replay protection) AEAD-mode data channel packets.
Definition crypto.c:428
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:1858
#define PARSE_FOOT
void init_key_type(struct key_type *kt, const char *ciphername, const char *authname, bool tls_mode, bool warn)
Initialize a key_type structure with.
Definition crypto.c:869
#define PARSE_DATA
int ascii2keydirection(int msglevel, const char *str)
Definition crypto.c:1612
#define PARSE_FINISHED
bool generate_ephemeral_key(struct buffer *key, const char *key_name)
Generate ephermal key material into the key structure.
Definition crypto.c:1840
void must_have_n_keys(const char *filename, const char *option, const struct key2 *key2, int n)
Definition crypto.c:1594
const char * keydirection2ascii(int kd, bool remote, bool humanreadable)
Definition crypto.c:1635
int write_key_file(const int nkeys, const char *filename)
Write nkeys 1024-bits keys to file.
Definition crypto.c:1536
bool check_key(struct key *key, const struct key_type *kt)
Definition crypto.c:1120
#define PARSE_INITIAL
const char * translate_cipher_name_to_openvpn(const char *cipher_name)
Translate a crypto library cipher name to an OpenVPN cipher name.
Definition crypto.c:1790
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:1803
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:1183
#define PARSE_DATA_COMPLETE
#define PARSE_HEAD
static const char static_key_foot[]
Definition crypto.c:1324
uint64_t cipher_get_aead_limits(const char *ciphername)
Check if the cipher is an AEAD cipher and needs to be limited to a certain number of number of blocks...
Definition crypto.c:338
static const cipher_name_pair * get_cipher_name_pair(const char *cipher_name)
Definition crypto.c:1756
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:1056
bool check_tls_prf_working(void)
Checks if the current TLS library supports the TLS 1.0 PRF with MD5+SHA1 that OpenVPN uses when TLS K...
Definition crypto.c:1895
void key_direction_state_init(struct key_direction_state *kds, int key_direction)
Definition crypto.c:1664
unsigned int crypto_max_overhead(void)
Return the worst-case OpenVPN crypto overhead (in bytes)
Definition crypto.c:844
static void openvpn_encrypt_v1(struct buffer *buf, struct buffer work, struct crypto_options *opt)
Definition crypto.c:190
static void key_ctx_update_implicit_iv(struct key_ctx *ctx, const struct key_parameters *key)
Update the implicit IV for a key_ctx based on TLS session ids and cipher used.
Definition crypto.c:958
static const char unprintable_char_fmt[]
Definition crypto.c:1329
void print_cipher(const char *ciphername)
Print a cipher list entry.
Definition crypto.c:1728
static void generate_key_random(struct key *key)
Definition crypto.c:1139
void test_crypto(struct crypto_options *co, struct frame *frame)
Definition crypto.c:1193
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:1284
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
static void openvpn_encrypt_aead(struct buffer *buf, struct buffer work, struct crypto_options *opt)
Definition crypto.c:66
static bool openvpn_decrypt_v1(struct buffer *buf, struct buffer work, struct crypto_options *opt, const struct frame *frame)
Definition crypto.c:610
void free_key_ctx(struct key_ctx *ctx)
Definition crypto.c:1075
static const char printable_char_fmt[]
Definition crypto.c:1326
void init_key_bi_ctx_recv(struct key_ctx *ctx, const struct key_parameters *key_params, const struct key_type *kt, const char *name)
Definition crypto.c:1044
Data Channel Cryptography Module.
#define AEAD_LIMIT_BLOCKSIZE
Blocksize used for the AEAD limit caluclation.
Definition crypto.h:734
#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
static bool cipher_decrypt_verify_fail_exceeded(const struct key_ctx *ctx)
Check if the number of failed decryption is over the acceptable limit.
Definition crypto.h:707
#define OPENVPN_AEAD_MIN_IV_LEN
Minimal IV length for AEAD mode ciphers (in bytes): 4-byte packet id + 8 bytes implicit IV.
Definition crypto.h:402
#define CRYPT_DROP(format)
Definition crypto.h:396
#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
#define CO_EPOCH_DATA_KEY_FORMAT
Bit-flag indicating the epoch the data format.
Definition crypto.h:377
#define RKF_INLINE
Definition crypto.h:405
#define CO_MUTE_REPLAY_WARNINGS
Bit-flag indicating not to display replay warnings.
Definition crypto.h:354
#define KEY_DIRECTION_BIDIRECTIONAL
Definition crypto.h:231
#define RKF_MUST_SUCCEED
Definition crypto.h:404
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
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...
bool ssl_tls1_PRF(const uint8_t *seed, size_t seed_len, const uint8_t *secret, size_t secret_len, uint8_t *output, size_t output_len)
Calculates the TLS 1.0-1.1 PRF function.
void hmac_ctx_update(hmac_ctx_t *ctx, const uint8_t *src, int src_len)
hmac_ctx_t * hmac_ctx_new(void)
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.
bool cipher_kt_mode_cbc(const char *ciphername)
Check if the supplied cipher is a supported CBC mode cipher.
void hmac_ctx_init(hmac_ctx_t *ctx, const uint8_t *key, const char *mdname)
static bool cipher_defined(const char *ciphername)
Checks if the cipher is defined and is not the null (none) cipher.
void hmac_ctx_final(hmac_ctx_t *ctx, uint8_t *dst)
int cipher_ctx_iv_length(const cipher_ctx_t *ctx)
Returns the size of the IV used by the cipher, in bytes, or 0 if no IV is used.
int cipher_kt_block_size(const char *ciphername)
Returns the block size of the cipher, in bytes.
bool cipher_kt_mode_aead(const char *ciphername)
Check if the supplied cipher is a supported AEAD mode cipher.
bool cipher_ctx_mode_cbc(const cipher_ctx_t *ctx)
Check if the supplied cipher is a supported CBC mode cipher.
cipher_ctx_t * cipher_ctx_new(void)
Generic cipher functions.
bool cipher_kt_mode_ofb_cfb(const char *ciphername)
Check if the supplied cipher is a supported OFB or CFB mode cipher.
const char * md_kt_name(const char *mdname)
Retrieve a string describing the digest digest (e.g.
int hmac_ctx_size(hmac_ctx_t *ctx)
bool cipher_kt_insecure(const char *ciphername)
Returns true if we consider this cipher to be insecure.
#define MAX_CIPHER_KEY_LENGTH
void crypto_clear_error(void)
bool crypto_pem_decode(const char *name, struct buffer *dst, const struct buffer *src)
Decode a PEM buffer to binary data.
void cipher_ctx_free(cipher_ctx_t *ctx)
Cleanup and free a cipher context.
int cipher_ctx_mode(const cipher_ctx_t *ctx)
Returns the mode that the cipher runs in.
bool cipher_ctx_mode_ofb_cfb(const cipher_ctx_t *ctx)
Check if the supplied cipher is a supported OFB or CFB mode cipher.
bool cipher_ctx_mode_aead(const cipher_ctx_t *ctx)
Check if the supplied cipher is a supported AEAD mode cipher.
static bool cipher_valid(const char *ciphername)
Returns if the cipher is valid, based on the given cipher name.
void hmac_ctx_free(hmac_ctx_t *ctx)
int cipher_kt_iv_size(const char *ciphername)
Returns the size of the IV used by the cipher, in bytes, or 0 if no IV is used.
int cipher_kt_tag_size(const char *ciphername)
Returns the MAC tag size of the cipher, in bytes.
int cipher_ctx_update_ad(cipher_ctx_t *ctx, const uint8_t *src, int src_len)
Updates the given cipher context, providing additional data (AD) for authenticated encryption with ad...
int rand_bytes(uint8_t *output, int len)
Wrapper for secure random number generator.
const size_t cipher_name_translation_table_count
const char * cipher_kt_name(const char *ciphername)
Retrieve a normalised string describing the cipher (e.g.
#define MAX_HMAC_KEY_LENGTH
#define OPENVPN_AEAD_TAG_LENGTH
void cipher_ctx_init(cipher_ctx_t *ctx, const uint8_t *key, const char *ciphername, crypto_operation_t enc)
Initialise a cipher context, based on the given key and key type.
int cipher_ctx_get_tag(cipher_ctx_t *ctx, uint8_t *tag, int tag_len)
Gets the computed message authenticated code (MAC) tag for this cipher.
int cipher_kt_key_size(const char *ciphername)
Returns the size of keys used by the cipher, in bytes.
#define OPENVPN_MAX_CIPHER_BLOCK_SIZE
void hmac_ctx_cleanup(hmac_ctx_t *ctx)
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.
const cipher_name_pair cipher_name_translation_table[]
Cipher name translation table.
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.
#define OPENVPN_MAX_HMAC_SIZE
unsigned char md_kt_size(const char *mdname)
Returns the size of the message digest, in bytes.
static bool md_defined(const char *mdname)
Checks if the cipher is defined and is not the null (none) cipher.
bool cipher_valid_reason(const char *ciphername, const char **reason)
Returns if the cipher is valid, based on the given cipher name and provides a reason if invalid.
int cipher_ctx_final_check_tag(cipher_ctx_t *ctx, uint8_t *dst, int *dst_len, uint8_t *tag, size_t tag_len)
Like cipher_ctx_final, but check the computed authentication tag against the supplied (expected) tag.
bool crypto_pem_encode(const char *name, struct buffer *dst, const struct buffer *src, struct gc_arena *gc)
Encode binary data as PEM.
void epoch_replace_update_recv_key(struct crypto_options *co, uint16_t new_epoch)
This is called when the peer uses a new send key that is not the default key.
void epoch_check_send_iterate(struct crypto_options *opt)
Checks if we need to iterate the send epoch key.
struct key_ctx * epoch_lookup_decrypt_key(struct crypto_options *opt, uint16_t epoch)
Using an epoch, this function will try to retrieve a decryption key context that matches that epoch f...
#define OPENVPN_OP_DECRYPT
Cipher should decrypt.
mbedtls_cipher_context_t cipher_ctx_t
Generic cipher context.
#define OPENVPN_MODE_CBC
Cipher is in CBC mode.
#define OPENVPN_MAX_IV_LENGTH
Maximum length of an IV.
#define OPENVPN_OP_ENCRYPT
Cipher should encrypt.
#define D_CRYPTO_DEBUG
Definition errlevel.h:147
#define D_CIPHER_INIT
Definition errlevel.h:107
#define D_PACKET_CONTENT
Definition errlevel.h:167
#define D_CRYPT_ERRORS
Definition errlevel.h:57
#define D_SHOW_KEYS
Definition errlevel.h:120
#define D_SHOW_KEY_SOURCE
Definition errlevel.h:121
#define D_GENKEY
Definition errlevel.h:78
#define M_INFO
Definition errlevel.h:54
#define D_REPLAY_ERRORS
Definition errlevel.h:61
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:322
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:773
static int max_int(int x, int y)
Definition integer.h:92
#define BUF_SIZE(f)
Definition mtu.h:178
static const char * np(const char *str)
Definition multi-auth.c:146
#define BOOL_CAST(x)
Definition basic.h:26
#define CLEAR(x)
Definition basic.h:32
#define SIZE(x)
Definition basic.h:29
#define M_FATAL
Definition error.h:88
#define M_NONFATAL
Definition error.h:89
#define dmsg(flags,...)
Definition error.h:170
#define M_ERR
Definition error.h:104
#define msg(flags,...)
Definition error.h:150
#define ASSERT(x)
Definition error.h:217
#define M_WARN
Definition error.h:90
static void update_time(void)
Definition otime.h:76
uint16_t packet_id_read_epoch(struct packet_id_net *pin, struct buffer *buf)
Reads the packet ID containing both the epoch and the per-epoch counter from the buf.
Definition packet_id.c:647
bool packet_id_write_epoch(struct packet_id_send *p, uint16_t epoch, struct buffer *buf)
Writes the packet ID containing both the epoch and the packet id to the buffer specified by buf.
Definition packet_id.c:666
bool packet_id_test(struct packet_id_rec *p, const struct packet_id_net *pin)
Definition packet_id.c:215
bool packet_id_read(struct packet_id_net *pin, struct buffer *buf, bool long_form)
Definition packet_id.c:314
const char * packet_id_net_print(const struct packet_id_net *pin, bool print_timestamp, struct gc_arena *gc)
Definition packet_id.c:418
void packet_id_add(struct packet_id_rec *p, const struct packet_id_net *pin)
Definition packet_id.c:132
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:377
uint32_t packet_id_type
Definition packet_id.h:45
static void packet_id_reap_test(struct packet_id_rec *p)
Definition packet_id.h:325
static void packet_id_persist_save_obj(struct packet_id_persist *p, const struct packet_id *pid)
Definition packet_id.h:285
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:313
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
Struct used in cipher name translation table.
const char * openvpn_name
Cipher name used by OpenVPN.
const char * lib_name
Cipher name used by crypto library.
Security parameter state for processing data channel packets.
Definition crypto.h:293
struct key_ctx epoch_retiring_data_receive_key
The old key before the sender switched to a new epoch data key.
Definition crypto.h:328
unsigned int flags
Bit-flags determining behavior of security operation functions.
Definition crypto.h:384
struct packet_id_persist * pid_persist
Persistent packet ID state for keeping state between successive OpenVPN process startups.
Definition crypto.h:340
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_rec epoch_retiring_key_pid_recv
Definition crypto.h:329
struct packet_id packet_id
Current packet ID state for both sending and receiving directions.
Definition crypto.h:331
Packet geometry parameters.
Definition mtu.h:103
int payload_size
the maximum size that a payload that our buffers can hold from either tun device or network link.
Definition mtu.h:108
int headroom
the headroom in the buffer, this is choosen to allow all potential header to be added before the pack...
Definition mtu.h:114
struct frame::@8 buf
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
bool initialized
Definition crypto.h:285
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
uint8_t implicit_iv[OPENVPN_MAX_IV_LENGTH]
This implicit IV will be always XORed with the packet id that is sent on the wire to get the IV.
Definition crypto.h:216
uint16_t epoch
OpenVPN data channel epoch, this variable holds the epoch number this key belongs to.
Definition crypto.h:228
uint64_t failed_verifications
number of failed verification using this cipher
Definition crypto.h:224
cipher_ctx_t * cipher
Generic cipher context.
Definition crypto.h:203
hmac_ctx_t * hmac
Generic HMAC context.
Definition crypto.h:204
uint64_t plaintext_blocks
Counter for the number of plaintext block encrypted using this cipher with the current key in number ...
Definition crypto.h:222
Key ordering of the key2.keys array.
Definition crypto.h:259
int need_keys
The number of key objects necessary to support both sending and receiving.
Definition crypto.h:264
int in_key
Index into the key2.keys array for the receiving direction.
Definition crypto.h:262
int out_key
Index into the key2.keys array for the sending direction.
Definition crypto.h:260
internal structure similar to struct key that holds key information but is not represented on wire an...
Definition crypto.h:163
int hmac_size
Number of bytes set in the HMac key material.
Definition crypto.h:174
int cipher_size
Number of bytes set in the cipher key material.
Definition crypto.h:168
uint16_t epoch
the epoch of the key.
Definition crypto.h:179
uint8_t hmac[MAX_HMAC_KEY_LENGTH]
Key material for HMAC operations.
Definition crypto.h:171
uint8_t cipher[MAX_CIPHER_KEY_LENGTH]
Key material for cipher operations.
Definition crypto.h:165
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
struct packet_id_rec rec
Definition packet_id.h:201
static int cleanup(void **state)
struct gc_arena gc
Definition test_ssl.c:154