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