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