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
1328void
1330 const char *key_name)
1331{
1332 struct key2 key2;
1333 key2.n = 2;
1337}
1338
1339
1340/* header and footer for static key file */
1341static const char static_key_head[] = "-----BEGIN OpenVPN Static key V1-----";
1342static const char static_key_foot[] = "-----END OpenVPN Static key V1-----";
1343
1344static const char printable_char_fmt[] =
1345 "Non-Hex character ('%c') found at line %d in key file '%s' (%d/%d/%d bytes found/min/max)";
1346
1347static const char unprintable_char_fmt[] =
1348 "Non-Hex, unprintable character (0x%02x) found at line %d in key file '%s' (%d/%d/%d bytes found/min/max)";
1349
1350/* read key from file */
1351
1352void
1353read_key_file(struct key2 *key2, const char *file, const unsigned int flags)
1354{
1355 struct gc_arena gc = gc_new();
1356 struct buffer in;
1357 int size;
1358 uint8_t hex_byte[3] = { 0, 0, 0 };
1359
1360 /* parse info */
1361 const unsigned char *cp;
1362 int hb_index = 0;
1363 int line_num = 1;
1364 int line_index = 0;
1365 int match = 0;
1366
1367 /* output */
1368 uint8_t *out = (uint8_t *)&key2->keys;
1369 const int keylen = sizeof(key2->keys);
1370 int count = 0;
1371
1372 /* parse states */
1373#define PARSE_INITIAL 0
1374#define PARSE_HEAD 1
1375#define PARSE_DATA 2
1376#define PARSE_DATA_COMPLETE 3
1377#define PARSE_FOOT 4
1378#define PARSE_FINISHED 5
1379 int state = PARSE_INITIAL;
1380
1381 /* constants */
1382 const int hlen = (int)strlen(static_key_head);
1383 const int flen = (int)strlen(static_key_foot);
1384 const int onekeylen = sizeof(key2->keys[0]);
1385
1386 CLEAR(*key2);
1387
1388 /*
1389 * Key can be provided as a filename in 'file' or if RKF_INLINE
1390 * is set, the actual key data itself in ascii form.
1391 */
1392 if (flags & RKF_INLINE) /* 'file' is a string containing ascii representation of key */
1393 {
1394 size_t buf_size = strlen(file) + 1;
1396 size = (int)buf_size;
1397 buf_set_read(&in, (const uint8_t *)file, size);
1398 }
1399 else /* 'file' is a filename which refers to a file containing the ascii key */
1400 {
1401 in = buffer_read_from_file(file, &gc);
1402 if (!buf_valid(&in))
1403 {
1404 msg(M_FATAL, "Read error on key file ('%s')", file);
1405 }
1406
1407 size = in.len;
1408 }
1409
1410 cp = (unsigned char *)in.data;
1411 while (size > 0)
1412 {
1413 const unsigned char c = *cp;
1414
1415#if 0
1416 msg(M_INFO, "char='%c'[%d] s=%d ln=%d li=%d m=%d c=%d",
1417 c, (int)c, state, line_num, line_index, match, count);
1418#endif
1419
1420 if (c == '\n')
1421 {
1422 line_index = match = 0;
1423 ++line_num;
1424 }
1425 else
1426 {
1427 /* first char of new line */
1428 if (!line_index)
1429 {
1430 /* first char of line after header line? */
1431 if (state == PARSE_HEAD)
1432 {
1433 state = PARSE_DATA;
1434 }
1435
1436 /* first char of footer */
1437 if ((state == PARSE_DATA || state == PARSE_DATA_COMPLETE) && c == '-')
1438 {
1439 state = PARSE_FOOT;
1440 }
1441 }
1442
1443 /* compare read chars with header line */
1444 if (state == PARSE_INITIAL)
1445 {
1446 if (line_index < hlen && c == static_key_head[line_index])
1447 {
1448 if (++match == hlen)
1449 {
1450 state = PARSE_HEAD;
1451 }
1452 }
1453 }
1454
1455 /* compare read chars with footer line */
1456 if (state == PARSE_FOOT)
1457 {
1459 {
1460 if (++match == flen)
1461 {
1462 state = PARSE_FINISHED;
1463 }
1464 }
1465 }
1466
1467 /* reading key */
1468 if (state == PARSE_DATA)
1469 {
1470 if (isxdigit(c))
1471 {
1472 ASSERT(hb_index >= 0 && hb_index < 2);
1473 hex_byte[hb_index++] = c;
1474 if (hb_index == 2)
1475 {
1476 uint8_t u;
1477 ASSERT(sscanf((const char *)hex_byte, "%" SCNx8, &u) == 1);
1478 *out++ = u;
1479 hb_index = 0;
1480 if (++count == keylen)
1481 {
1482 state = PARSE_DATA_COMPLETE;
1483 }
1484 }
1485 }
1486 else if (isspace(c))
1487 {
1488 /* ignore white space characters */
1489 }
1490 else
1491 {
1494 keylen);
1495 }
1496 }
1497 ++line_index;
1498 }
1499 ++cp;
1500 --size;
1501 }
1502
1503 /*
1504 * Normally we will read either 1 or 2 keys from file.
1505 */
1506 key2->n = count / onekeylen;
1507
1508 ASSERT(key2->n >= 0 && key2->n <= (int)SIZE(key2->keys));
1509
1510 if (flags & RKF_MUST_SUCCEED)
1511 {
1512 if (!key2->n)
1513 {
1514 msg(M_FATAL,
1515 "Insufficient key material or header text not found in file '%s' (%d/%d/%d bytes found/min/max)",
1517 }
1518
1519 if (state != PARSE_FINISHED)
1520 {
1521 msg(M_FATAL, "Footer text not found in file '%s' (%d/%d/%d bytes found/min/max)",
1523 }
1524 }
1525
1526 /* zero file read buffer if not an inline file */
1527 if (!(flags & RKF_INLINE))
1528 {
1529 buf_clear(&in);
1530 }
1531
1532#if 0
1533 /* DEBUGGING */
1534 {
1535 int i;
1536 printf("KEY READ, n=%d\n", key2->n);
1537 for (i = 0; i < (int) SIZE(key2->keys); ++i)
1538 {
1539 /* format key as ascii */
1540 const char *fmt = format_hex_ex((const uint8_t *)&key2->keys[i],
1541 sizeof(key2->keys[i]),
1542 0,
1543 16,
1544 "\n",
1545 &gc);
1546 printf("[%d]\n%s\n\n", i, fmt);
1547 }
1548 }
1549#endif
1550
1551 /* pop our garbage collection level */
1552 gc_free(&gc);
1553}
1554
1555int
1556write_key_file(const int nkeys, const char *filename)
1557{
1558 struct gc_arena gc = gc_new();
1559
1560 int nbits = nkeys * sizeof(struct key) * 8;
1561
1562 /* must be large enough to hold full key file */
1563 struct buffer out = alloc_buf_gc(2048, &gc);
1564
1565 /* how to format the ascii file representation of key */
1566 const int bytes_per_line = 16;
1567
1568 /* write header */
1569 buf_printf(&out, "#\n# %d bit OpenVPN static key\n#\n", nbits);
1570 buf_printf(&out, "%s\n", static_key_head);
1571
1572 for (int i = 0; i < nkeys; ++i)
1573 {
1574 struct key key;
1575 char *fmt;
1576
1577 /* generate random bits */
1579
1580 /* format key as ascii */
1581 fmt = format_hex_ex((const uint8_t *)&key, sizeof(key), 0, bytes_per_line, "\n", &gc);
1582
1583 /* write to holding buffer */
1584 buf_printf(&out, "%s\n", fmt);
1585
1586 /* zero memory which held key component (will be freed by GC) */
1587 secure_memzero(fmt, strlen(fmt));
1588 secure_memzero(&key, sizeof(key));
1589 }
1590
1591 buf_printf(&out, "%s\n", static_key_foot);
1592
1593 /* write key file to stdout if no filename given */
1594 if (!filename || strcmp(filename, "") == 0)
1595 {
1596 printf("%.*s\n", BLEN(&out), BPTR(&out));
1597 }
1598 /* write key file, now formatted in out, to file */
1599 else if (!buffer_write_file(filename, &out))
1600 {
1601 nbits = -1;
1602 }
1603
1604 /* zero memory which held file content (memory will be freed by GC) */
1605 buf_clear(&out);
1606
1607 /* pop our garbage collection level */
1608 gc_free(&gc);
1609
1610 return nbits;
1611}
1612
1613void
1614must_have_n_keys(const char *filename, const char *option, const struct key2 *key2, int n)
1615{
1616 if (key2->n < n)
1617 {
1618#ifdef ENABLE_SMALL
1619 msg(M_FATAL,
1620 "Key file '%s' used in --%s contains insufficient key material [keys found=%d required=%d]",
1621 filename, option, key2->n, n);
1622#else
1623 msg(M_FATAL,
1624 "Key file '%s' used in --%s contains insufficient key material [keys found=%d required=%d] -- try generating a new key file with '" PACKAGE
1625 " --genkey secret [file]', or use the existing key file in bidirectional mode by specifying --%s without a key direction parameter",
1626 filename, option, key2->n, n, option);
1627#endif
1628 }
1629}
1630
1631int
1632ascii2keydirection(msglvl_t msglevel, const char *str)
1633{
1634 if (!str)
1635 {
1637 }
1638 else if (!strcmp(str, "0"))
1639 {
1640 return KEY_DIRECTION_NORMAL;
1641 }
1642 else if (!strcmp(str, "1"))
1643 {
1644 return KEY_DIRECTION_INVERSE;
1645 }
1646 else
1647 {
1648 msg(msglevel, "Unknown key direction '%s' -- must be '0' or '1'", str);
1649 return -1;
1650 }
1651 return KEY_DIRECTION_BIDIRECTIONAL; /* NOTREACHED */
1652}
1653
1654const char *
1655keydirection2ascii(int kd, bool remote, bool humanreadable)
1656{
1658 {
1659 if (humanreadable)
1660 {
1661 return "not set";
1662 }
1663 else
1664 {
1665 return NULL;
1666 }
1667 }
1668 else if (kd == KEY_DIRECTION_NORMAL)
1669 {
1670 return remote ? "1" : "0";
1671 }
1672 else if (kd == KEY_DIRECTION_INVERSE)
1673 {
1674 return remote ? "0" : "1";
1675 }
1676 else
1677 {
1678 ASSERT(0);
1679 }
1680 return NULL; /* NOTREACHED */
1681}
1682
1683void
1684key_direction_state_init(struct key_direction_state *kds, int key_direction)
1685{
1686 CLEAR(*kds);
1687 switch (key_direction)
1688 {
1690 kds->out_key = 0;
1691 kds->in_key = 1;
1692 kds->need_keys = 2;
1693 break;
1694
1696 kds->out_key = 1;
1697 kds->in_key = 0;
1698 kds->need_keys = 2;
1699 break;
1700
1702 kds->out_key = 0;
1703 kds->in_key = 0;
1704 kds->need_keys = 1;
1705 break;
1706
1707 default:
1708 ASSERT(0);
1709 }
1710}
1711
1712void
1713verify_fix_key2(struct key2 *key2, const struct key_type *kt, const char *shared_secret_file)
1714{
1715 int i;
1716
1717 for (i = 0; i < key2->n; ++i)
1718 {
1719 /* This should be a very improbable failure */
1720 if (!check_key(&key2->keys[i], kt))
1721 {
1722 msg(M_FATAL, "Key #%d in '%s' is bad. Try making a new key with --genkey.", i + 1,
1723 shared_secret_file);
1724 }
1725 }
1726}
1727
1728void
1729prng_bytes(uint8_t *output, int len)
1730{
1731 ASSERT(rand_bytes(output, len));
1732}
1733
1734/* an analogue to the random() function, but use prng_bytes */
1735long int
1737{
1738 long int l;
1739 prng_bytes((unsigned char *)&l, sizeof(l));
1740 if (l < 0)
1741 {
1742 l = -l;
1743 }
1744 return l;
1745}
1746
1747void
1748print_cipher(const char *ciphername)
1749{
1750 printf("%s (%d bit key, ", cipher_kt_name(ciphername), cipher_kt_key_size(ciphername) * 8);
1751
1752 if (cipher_kt_block_size(ciphername) == 1)
1753 {
1754 printf("stream cipher");
1755 }
1756 else
1757 {
1758 printf("%d bit block", cipher_kt_block_size(ciphername) * 8);
1759 }
1760
1761 if (!cipher_kt_mode_cbc(ciphername))
1762 {
1763 printf(", TLS client/server mode only");
1764 }
1765
1766 const char *reason;
1767 if (!cipher_valid_reason(ciphername, &reason))
1768 {
1769 printf(", %s", reason);
1770 }
1771
1772 printf(")\n");
1773}
1774
1775static const cipher_name_pair *
1776get_cipher_name_pair(const char *cipher_name)
1777{
1778 const cipher_name_pair *pair;
1779 size_t i = 0;
1780
1781 /* Search for a cipher name translation */
1783 {
1785 if (0 == strcmp(cipher_name, pair->openvpn_name)
1786 || 0 == strcmp(cipher_name, pair->lib_name))
1787 {
1788 return pair;
1789 }
1790 }
1791
1792 /* Nothing found, return null */
1793 return NULL;
1794}
1795
1796const char *
1798{
1799 const cipher_name_pair *pair = get_cipher_name_pair(cipher_name);
1800
1801 if (NULL == pair)
1802 {
1803 return cipher_name;
1804 }
1805
1806 return pair->lib_name;
1807}
1808
1809const char *
1810translate_cipher_name_to_openvpn(const char *cipher_name)
1811{
1812 const cipher_name_pair *pair = get_cipher_name_pair(cipher_name);
1813
1814 if (NULL == pair)
1815 {
1816 return cipher_name;
1817 }
1818
1819 return pair->openvpn_name;
1820}
1821
1822void
1823write_pem_key_file(const char *filename, const char *pem_name)
1824{
1825 struct gc_arena gc = gc_new();
1826 struct key server_key = { 0 };
1827 struct buffer server_key_buf = clear_buf();
1828 struct buffer server_key_pem = clear_buf();
1829
1830 if (!rand_bytes((void *)&server_key, sizeof(server_key)))
1831 {
1832 msg(M_NONFATAL, "ERROR: could not generate random key");
1833 goto cleanup;
1834 }
1835 buf_set_read(&server_key_buf, (void *)&server_key, sizeof(server_key));
1837 {
1838 msg(M_WARN, "ERROR: could not PEM-encode key");
1839 goto cleanup;
1840 }
1841
1842 if (!filename || strcmp(filename, "") == 0)
1843 {
1845 }
1846 else if (!buffer_write_file(filename, &server_key_pem))
1847 {
1848 msg(M_ERR, "ERROR: could not write key file");
1849 goto cleanup;
1850 }
1851
1852cleanup:
1855 gc_free(&gc);
1856 return;
1857}
1858
1859bool
1861{
1862 const int len = BCAP(key);
1863
1864 msg(M_INFO, "Using random %s.", key_name);
1865
1866 if (!rand_bytes(BEND(key), len))
1867 {
1868 msg(M_WARN, "ERROR: could not generate random key");
1869 return false;
1870 }
1871
1873
1874 return true;
1875}
1876
1877bool
1878read_pem_key_file(struct buffer *key, const char *pem_name, const char *key_file, bool key_inline)
1879{
1880 bool ret = false;
1881 struct buffer key_pem = { 0 };
1882 struct gc_arena gc = gc_new();
1883
1884 if (!key_inline)
1885 {
1886 key_pem = buffer_read_from_file(key_file, &gc);
1887 if (!buf_valid(&key_pem))
1888 {
1889 msg(M_WARN, "ERROR: failed to read %s file (%s)", pem_name, key_file);
1890 goto cleanup;
1891 }
1892 }
1893 else
1894 {
1895 buf_set_read(&key_pem, (const void *)key_file, strlen(key_file) + 1);
1896 }
1897
1898 if (!crypto_pem_decode(pem_name, key, &key_pem))
1899 {
1900 msg(M_WARN, "ERROR: %s pem decode failed", pem_name);
1901 goto cleanup;
1902 }
1903
1904 ret = true;
1905cleanup:
1906 if (!key_inline)
1907 {
1908 buf_clear(&key_pem);
1909 }
1910 gc_free(&gc);
1911 return ret;
1912}
1913
1914bool
1916{
1917 /* Modern TLS libraries might no longer support the TLS 1.0 PRF with
1918 * MD5+SHA1. This allows us to establish connections only
1919 * with other 2.6.0+ OpenVPN peers.
1920 * Do a simple dummy test here to see if it works. */
1921 const char *seed = "tls1-prf-test";
1922 const char *secret = "tls1-prf-test-secret";
1923 uint8_t out[8];
1924 uint8_t expected_out[] = { 'q', 'D', 0xfe, '%', '@', 's', 'u', 0x95 };
1925
1926 int ret = ssl_tls1_PRF((uint8_t *)seed, strlen(seed), (uint8_t *)secret,
1927 strlen(secret), out, sizeof(out));
1928
1929 return (ret && memcmp(out, expected_out, sizeof(out)) == 0);
1930}
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:1797
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:1341
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:1729
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:1713
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:1353
long int get_random(void)
Definition crypto.c:1736
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:1878
#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:1632
#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:1860
void must_have_n_keys(const char *filename, const char *option, const struct key2 *key2, int n)
Definition crypto.c:1614
const char * keydirection2ascii(int kd, bool remote, bool humanreadable)
Definition crypto.c:1655
int write_key_file(const int nkeys, const char *filename)
Write nkeys 1024-bits keys to file.
Definition crypto.c:1556
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:1810
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:1823
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:1342
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:1776
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:1915
void key_direction_state_init(struct key_direction_state *kds, int key_direction)
Definition crypto.c:1684
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:1347
void print_cipher(const char *ciphername)
Print a cipher list entry.
Definition crypto.c:1748
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 generate_test_crypto_random_key(const struct key_type *key_type, struct key_ctx_bi *ctx, const char *key_name)
Generate a random key and initialise ctx to be used the in the crypto random test.
Definition crypto.c:1329
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:1344
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:743
#define KEY_DIRECTION_NORMAL
Definition crypto.h:232
#define CO_PACKET_ID_LONG_FORM
Bit-flag indicating whether to use OpenVPN's long packet ID format.
Definition crypto.h:347
static bool cipher_decrypt_verify_fail_exceeded(const struct key_ctx *ctx)
Check if the number of failed decryption is over the acceptable limit.
Definition crypto.h:716
#define OPENVPN_AEAD_MIN_IV_LEN
Minimal IV length for AEAD mode ciphers (in bytes): 4-byte packet id + 8 bytes implicit IV.
Definition crypto.h:404
#define CRYPT_DROP(format)
Definition crypto.h:398
#define CRYPT_ERROR(format)
Definition crypto.h:397
#define CO_IGNORE_PACKET_ID
Bit-flag indicating whether to ignore the packet ID of a received packet.
Definition crypto.h:350
#define CO_EPOCH_DATA_KEY_FORMAT
Bit-flag indicating the epoch the data format.
Definition crypto.h:379
#define RKF_INLINE
Definition crypto.h:407
#define CO_MUTE_REPLAY_WARNINGS
Bit-flag indicating not to display replay warnings.
Definition crypto.h:356
#define KEY_DIRECTION_BIDIRECTIONAL
Definition crypto.h:231
#define RKF_MUST_SUCCEED
Definition crypto.h:406
int memcmp_constant_time(const void *a, const void *b, size_t size)
As memcmp(), but constant-time.
#define KEY_DIRECTION_INVERSE
Definition crypto.h:233
int cipher_ctx_update(cipher_ctx_t *ctx, uint8_t *dst, int *dst_len, uint8_t *src, int src_len)
Updates the given cipher context, encrypting data in the source buffer, and placing any complete bloc...
bool ssl_tls1_PRF(const uint8_t *seed, size_t seed_len, const uint8_t *secret, size_t secret_len, uint8_t *output, size_t output_len)
Calculates the TLS 1.0-1.1 PRF function.
void hmac_ctx_update(hmac_ctx_t *ctx, const uint8_t *src, int src_len)
hmac_ctx_t * hmac_ctx_new(void)
void hmac_ctx_reset(hmac_ctx_t *ctx)
int cipher_ctx_block_size(const cipher_ctx_t *ctx)
Returns the block size of the cipher, in bytes.
bool cipher_kt_mode_cbc(const char *ciphername)
Check if the supplied cipher is a supported CBC mode cipher.
void hmac_ctx_init(hmac_ctx_t *ctx, const uint8_t *key, const char *mdname)
static bool cipher_defined(const char *ciphername)
Checks if the cipher is defined and is not the null (none) cipher.
void hmac_ctx_final(hmac_ctx_t *ctx, uint8_t *dst)
int cipher_ctx_iv_length(const cipher_ctx_t *ctx)
Returns the size of the IV used by the cipher, in bytes, or 0 if no IV is used.
int cipher_kt_block_size(const char *ciphername)
Returns the block size of the cipher, in bytes.
bool cipher_kt_mode_aead(const char *ciphername)
Check if the supplied cipher is a supported AEAD mode cipher.
bool cipher_ctx_mode_cbc(const cipher_ctx_t *ctx)
Check if the supplied cipher is a supported CBC mode cipher.
cipher_ctx_t * cipher_ctx_new(void)
Generic cipher functions.
bool cipher_kt_mode_ofb_cfb(const char *ciphername)
Check if the supplied cipher is a supported OFB or CFB mode cipher.
const char * md_kt_name(const char *mdname)
Retrieve a string describing the digest digest (e.g.
int hmac_ctx_size(hmac_ctx_t *ctx)
bool cipher_kt_insecure(const char *ciphername)
Returns true if we consider this cipher to be insecure.
#define MAX_CIPHER_KEY_LENGTH
void crypto_clear_error(void)
bool crypto_pem_decode(const char *name, struct buffer *dst, const struct buffer *src)
Decode a PEM buffer to binary data.
void cipher_ctx_free(cipher_ctx_t *ctx)
Cleanup and free a cipher context.
int cipher_ctx_mode(const cipher_ctx_t *ctx)
Returns the mode that the cipher runs in.
bool cipher_ctx_mode_ofb_cfb(const cipher_ctx_t *ctx)
Check if the supplied cipher is a supported OFB or CFB mode cipher.
bool cipher_ctx_mode_aead(const cipher_ctx_t *ctx)
Check if the supplied cipher is a supported AEAD mode cipher.
static bool cipher_valid(const char *ciphername)
Returns if the cipher is valid, based on the given cipher name.
void hmac_ctx_free(hmac_ctx_t *ctx)
int cipher_kt_iv_size(const char *ciphername)
Returns the size of the IV used by the cipher, in bytes, or 0 if no IV is used.
int cipher_kt_tag_size(const char *ciphername)
Returns the MAC tag size of the cipher, in bytes.
int cipher_ctx_update_ad(cipher_ctx_t *ctx, const uint8_t *src, int src_len)
Updates the given cipher context, providing additional data (AD) for authenticated encryption with ad...
int rand_bytes(uint8_t *output, int len)
Wrapper for secure random number generator.
const size_t cipher_name_translation_table_count
const char * cipher_kt_name(const char *ciphername)
Retrieve a normalised string describing the cipher (e.g.
#define MAX_HMAC_KEY_LENGTH
#define OPENVPN_AEAD_TAG_LENGTH
void cipher_ctx_init(cipher_ctx_t *ctx, const uint8_t *key, const char *ciphername, crypto_operation_t enc)
Initialise a cipher context, based on the given key and key type.
int cipher_ctx_get_tag(cipher_ctx_t *ctx, uint8_t *tag, int tag_len)
Gets the computed message authenticated code (MAC) tag for this cipher.
int cipher_kt_key_size(const char *ciphername)
Returns the size of keys used by the cipher, in bytes.
#define OPENVPN_MAX_CIPHER_BLOCK_SIZE
void hmac_ctx_cleanup(hmac_ctx_t *ctx)
int cipher_ctx_reset(cipher_ctx_t *ctx, const uint8_t *iv_buf)
Resets the given cipher context, setting the IV to the specified value.
const cipher_name_pair cipher_name_translation_table[]
Cipher name translation table.
int cipher_ctx_final(cipher_ctx_t *ctx, uint8_t *dst, int *dst_len)
Pads the final cipher block using PKCS padding, and output to the destination buffer.
#define OPENVPN_MAX_HMAC_SIZE
unsigned char md_kt_size(const char *mdname)
Returns the size of the message digest, in bytes.
static bool md_defined(const char *mdname)
Checks if the cipher is defined and is not the null (none) cipher.
bool cipher_valid_reason(const char *ciphername, const char **reason)
Returns if the cipher is valid, based on the given cipher name and provides a reason if invalid.
int cipher_ctx_final_check_tag(cipher_ctx_t *ctx, uint8_t *dst, int *dst_len, uint8_t *tag, size_t tag_len)
Like cipher_ctx_final, but check the computed authentication tag against the supplied (expected) tag.
bool crypto_pem_encode(const char *name, struct buffer *dst, const struct buffer *src, struct gc_arena *gc)
Encode binary data as PEM.
void epoch_replace_update_recv_key(struct crypto_options *co, uint16_t new_epoch)
This is called when the peer uses a new send key that is not the default key.
void epoch_check_send_iterate(struct crypto_options *opt)
Checks if we need to iterate the send epoch key.
struct key_ctx * epoch_lookup_decrypt_key(struct crypto_options *opt, uint16_t epoch)
Using an epoch, this function will try to retrieve a decryption key context that matches that epoch f...
#define OPENVPN_OP_DECRYPT
Cipher should decrypt.
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