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