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