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