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