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