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