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-2018 OpenVPN Inc <sales@openvpn.net>
9  * Copyright (C) 2010-2018 Fox Crypto B.V. <openvpn@fox-it.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;
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, int keysize, 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  if (keysize > 0 && keysize <= MAX_CIPHER_KEY_LENGTH)
760  {
761  kt->cipher_length = keysize;
762  }
763 
764  /* check legal cipher mode */
765  aead_cipher = cipher_kt_mode_aead(kt->cipher);
766  if (!(cipher_kt_mode_cbc(kt->cipher)
767  || (tls_mode && aead_cipher)
768 #ifdef ENABLE_OFB_CFB_MODE
769  || (tls_mode && cipher_kt_mode_ofb_cfb(kt->cipher))
770 #endif
771  ))
772  {
773  msg(M_FATAL, "Cipher '%s' mode not supported", ciphername);
774  }
775 
777  {
778  msg(M_FATAL, "Cipher '%s' not allowed: block size too big.", ciphername);
779  }
780  if (warn)
781  {
782  warn_insecure_key_type(ciphername, kt->cipher);
783  }
784  }
785  else
786  {
787  if (warn)
788  {
789  msg(M_WARN, "******* WARNING *******: '--cipher none' was specified. "
790  "This means NO encryption will be performed and tunnelled "
791  "data WILL be transmitted in clear text over the network! "
792  "PLEASE DO RECONSIDER THIS SETTING!");
793  }
794  }
795  if (strcmp(authname, "none") != 0)
796  {
797  if (!aead_cipher) /* Ignore auth for AEAD ciphers */
798  {
799  kt->digest = md_kt_get(authname);
800  kt->hmac_length = md_kt_size(kt->digest);
801 
802  if (OPENVPN_MAX_HMAC_SIZE < kt->hmac_length)
803  {
804  msg(M_FATAL, "HMAC '%s' not allowed: digest size too big.", authname);
805  }
806  }
807  }
808  else if (!aead_cipher)
809  {
810  if (warn)
811  {
812  msg(M_WARN, "******* WARNING *******: '--auth none' was specified. "
813  "This means no authentication will be performed on received "
814  "packets, meaning you CANNOT trust that the data received by "
815  "the remote side have NOT been manipulated. "
816  "PLEASE DO RECONSIDER THIS SETTING!");
817  }
818  }
819 }
820 
821 /* given a key and key_type, build a key_ctx */
822 void
823 init_key_ctx(struct key_ctx *ctx, const struct key *key,
824  const struct key_type *kt, int enc,
825  const char *prefix)
826 {
827  struct gc_arena gc = gc_new();
828  CLEAR(*ctx);
829  if (kt->cipher && kt->cipher_length > 0)
830  {
831 
832  ctx->cipher = cipher_ctx_new();
833  cipher_ctx_init(ctx->cipher, key->cipher, kt->cipher_length,
834  kt->cipher, enc);
835 
836  const char *ciphername = cipher_kt_name(kt->cipher);
837  msg(D_HANDSHAKE, "%s: Cipher '%s' initialized with %d bit key",
838  prefix,
839  ciphername,
840  kt->cipher_length *8);
841 
842  dmsg(D_SHOW_KEYS, "%s: CIPHER KEY: %s", prefix,
843  format_hex(key->cipher, kt->cipher_length, 0, &gc));
844  dmsg(D_CRYPTO_DEBUG, "%s: CIPHER block_size=%d iv_size=%d",
845  prefix, cipher_kt_block_size(kt->cipher),
847  warn_insecure_key_type(ciphername, kt->cipher);
848  }
849  if (kt->digest && kt->hmac_length > 0)
850  {
851  ctx->hmac = hmac_ctx_new();
852  hmac_ctx_init(ctx->hmac, key->hmac, kt->hmac_length, kt->digest);
853 
855  "%s: Using %d bit message hash '%s' for HMAC authentication",
856  prefix, md_kt_size(kt->digest) * 8, md_kt_name(kt->digest));
857 
858  dmsg(D_SHOW_KEYS, "%s: HMAC KEY: %s", prefix,
859  format_hex(key->hmac, kt->hmac_length, 0, &gc));
860 
861  dmsg(D_CRYPTO_DEBUG, "%s: HMAC size=%d block_size=%d",
862  prefix,
863  md_kt_size(kt->digest),
864  hmac_ctx_size(ctx->hmac));
865 
866  }
867  gc_free(&gc);
868 }
869 
870 void
871 init_key_ctx_bi(struct key_ctx_bi *ctx, const struct key2 *key2,
872  int key_direction, const struct key_type *kt, const char *name)
873 {
874  char log_prefix[128] = { 0 };
875  struct key_direction_state kds;
876 
877  key_direction_state_init(&kds, key_direction);
878 
879  openvpn_snprintf(log_prefix, sizeof(log_prefix), "Outgoing %s", name);
880  init_key_ctx(&ctx->encrypt, &key2->keys[kds.out_key], kt,
881  OPENVPN_OP_ENCRYPT, log_prefix);
882 
883  openvpn_snprintf(log_prefix, sizeof(log_prefix), "Incoming %s", name);
884  init_key_ctx(&ctx->decrypt, &key2->keys[kds.in_key], kt,
885  OPENVPN_OP_DECRYPT, log_prefix);
886 
887  ctx->initialized = true;
888 }
889 
890 void
891 free_key_ctx(struct key_ctx *ctx)
892 {
893  if (ctx->cipher)
894  {
895  cipher_ctx_free(ctx->cipher);
896  ctx->cipher = NULL;
897  }
898  if (ctx->hmac)
899  {
900  hmac_ctx_cleanup(ctx->hmac);
901  hmac_ctx_free(ctx->hmac);
902  ctx->hmac = NULL;
903  }
904  ctx->implicit_iv_len = 0;
905 }
906 
907 void
909 {
910  free_key_ctx(&ctx->encrypt);
911  free_key_ctx(&ctx->decrypt);
912 }
913 
914 static bool
915 key_is_zero(struct key *key, const struct key_type *kt)
916 {
917  int i;
918  for (i = 0; i < kt->cipher_length; ++i)
919  {
920  if (key->cipher[i])
921  {
922  return false;
923  }
924  }
925  msg(D_CRYPT_ERRORS, "CRYPTO INFO: WARNING: zero key detected");
926  return true;
927 }
928 
929 /*
930  * Make sure that cipher key is a valid key for current key_type.
931  */
932 bool
933 check_key(struct key *key, const struct key_type *kt)
934 {
935  if (kt->cipher)
936  {
937  /*
938  * Check for zero key
939  */
940  if (key_is_zero(key, kt))
941  {
942  return false;
943  }
944 
945  /*
946  * Check for weak or semi-weak DES keys.
947  */
948  {
949  const int ndc = key_des_num_cblocks(kt->cipher);
950  if (ndc)
951  {
952  return key_des_check(key->cipher, kt->cipher_length, ndc);
953  }
954  else
955  {
956  return true;
957  }
958  }
959  }
960  return true;
961 }
962 
963 /*
964  * Make safe mutations to key to ensure it is valid,
965  * such as ensuring correct parity on DES keys.
966  *
967  * This routine cannot guarantee it will generate a good
968  * key. You must always call check_key after this routine
969  * to make sure.
970  */
971 void
972 fixup_key(struct key *key, const struct key_type *kt)
973 {
974  struct gc_arena gc = gc_new();
975  if (kt->cipher)
976  {
977 #ifdef ENABLE_DEBUG
978  const struct key orig = *key;
979 #endif
980  const int ndc = key_des_num_cblocks(kt->cipher);
981 
982  if (ndc)
983  {
984  key_des_fixup(key->cipher, kt->cipher_length, ndc);
985  }
986 
987 #ifdef ENABLE_DEBUG
989  {
990  if (memcmp(orig.cipher, key->cipher, kt->cipher_length))
991  {
992  dmsg(D_CRYPTO_DEBUG, "CRYPTO INFO: fixup_key: before=%s after=%s",
993  format_hex(orig.cipher, kt->cipher_length, 0, &gc),
994  format_hex(key->cipher, kt->cipher_length, 0, &gc));
995  }
996  }
997 #endif
998  }
999  gc_free(&gc);
1000 }
1001 
1002 void
1004 {
1005  ASSERT(kt);
1006 
1007  if (!packet_id && (cipher_kt_mode_ofb_cfb(kt->cipher)
1008  || cipher_kt_mode_aead(kt->cipher)))
1009  {
1010  msg(M_FATAL, "--no-replay cannot be used with a CFB, OFB or AEAD mode cipher");
1011  }
1012 }
1013 
1014 /*
1015  * Generate a random key. If key_type is provided, make
1016  * sure generated key is valid for key_type.
1017  */
1018 void
1019 generate_key_random(struct key *key, const struct key_type *kt)
1020 {
1021  int cipher_len = MAX_CIPHER_KEY_LENGTH;
1022  int hmac_len = MAX_HMAC_KEY_LENGTH;
1023 
1024  struct gc_arena gc = gc_new();
1025 
1026  do
1027  {
1028  CLEAR(*key);
1029  if (kt)
1030  {
1031  if (kt->cipher && kt->cipher_length > 0 && kt->cipher_length <= cipher_len)
1032  {
1033  cipher_len = kt->cipher_length;
1034  }
1035 
1036  if (kt->digest && kt->hmac_length > 0 && kt->hmac_length <= hmac_len)
1037  {
1038  hmac_len = kt->hmac_length;
1039  }
1040  }
1041  if (!rand_bytes(key->cipher, cipher_len)
1042  || !rand_bytes(key->hmac, hmac_len))
1043  {
1044  msg(M_FATAL, "ERROR: Random number generator cannot obtain entropy for key generation");
1045  }
1046 
1047  dmsg(D_SHOW_KEY_SOURCE, "Cipher source entropy: %s", format_hex(key->cipher, cipher_len, 0, &gc));
1048  dmsg(D_SHOW_KEY_SOURCE, "HMAC source entropy: %s", format_hex(key->hmac, hmac_len, 0, &gc));
1049 
1050  if (kt)
1051  {
1052  fixup_key(key, kt);
1053  }
1054  } while (kt && !check_key(key, kt));
1055 
1056  gc_free(&gc);
1057 }
1058 
1059 /*
1060  * Print key material
1061  */
1062 void
1063 key2_print(const struct key2 *k,
1064  const struct key_type *kt,
1065  const char *prefix0,
1066  const char *prefix1)
1067 {
1068  struct gc_arena gc = gc_new();
1069  ASSERT(k->n == 2);
1070  dmsg(D_SHOW_KEY_SOURCE, "%s (cipher): %s",
1071  prefix0,
1072  format_hex(k->keys[0].cipher, kt->cipher_length, 0, &gc));
1073  dmsg(D_SHOW_KEY_SOURCE, "%s (hmac): %s",
1074  prefix0,
1075  format_hex(k->keys[0].hmac, kt->hmac_length, 0, &gc));
1076  dmsg(D_SHOW_KEY_SOURCE, "%s (cipher): %s",
1077  prefix1,
1078  format_hex(k->keys[1].cipher, kt->cipher_length, 0, &gc));
1079  dmsg(D_SHOW_KEY_SOURCE, "%s (hmac): %s",
1080  prefix1,
1081  format_hex(k->keys[1].hmac, kt->hmac_length, 0, &gc));
1082  gc_free(&gc);
1083 }
1084 
1085 void
1087 {
1088  int i, j;
1089  struct gc_arena gc = gc_new();
1090  struct buffer src = alloc_buf_gc(TUN_MTU_SIZE(frame), &gc);
1091  struct buffer work = alloc_buf_gc(BUF_SIZE(frame), &gc);
1092  struct buffer encrypt_workspace = alloc_buf_gc(BUF_SIZE(frame), &gc);
1093  struct buffer decrypt_workspace = alloc_buf_gc(BUF_SIZE(frame), &gc);
1094  struct buffer buf = clear_buf();
1095  void *buf_p;
1096 
1097  /* init work */
1098  ASSERT(buf_init(&work, FRAME_HEADROOM(frame)));
1099 
1100  /* init implicit IV */
1101  {
1102  const cipher_kt_t *cipher =
1104 
1105  if (cipher_kt_mode_aead(cipher))
1106  {
1107  size_t impl_iv_len = cipher_kt_iv_size(cipher) - sizeof(packet_id_type);
1110 
1111  /* Generate dummy implicit IV */
1114  co->key_ctx_bi.encrypt.implicit_iv_len = impl_iv_len;
1115 
1116  memcpy(co->key_ctx_bi.decrypt.implicit_iv,
1118  co->key_ctx_bi.decrypt.implicit_iv_len = impl_iv_len;
1119  }
1120  }
1121 
1122  msg(M_INFO, "Entering " PACKAGE_NAME " crypto self-test mode.");
1123  for (i = 1; i <= TUN_MTU_SIZE(frame); ++i)
1124  {
1125  update_time();
1126 
1127  msg(M_INFO, "TESTING ENCRYPT/DECRYPT of packet length=%d", i);
1128 
1129  /*
1130  * Load src with random data.
1131  */
1132  ASSERT(buf_init(&src, 0));
1133  ASSERT(i <= src.capacity);
1134  src.len = i;
1135  ASSERT(rand_bytes(BPTR(&src), BLEN(&src)));
1136 
1137  /* copy source to input buf */
1138  buf = work;
1139  buf_p = buf_write_alloc(&buf, BLEN(&src));
1140  ASSERT(buf_p);
1141  memcpy(buf_p, BPTR(&src), BLEN(&src));
1142 
1143  /* initialize work buffer with FRAME_HEADROOM bytes of prepend capacity */
1144  ASSERT(buf_init(&encrypt_workspace, FRAME_HEADROOM(frame)));
1145 
1146  /* encrypt */
1147  openvpn_encrypt(&buf, encrypt_workspace, co);
1148 
1149  /* decrypt */
1150  openvpn_decrypt(&buf, decrypt_workspace, co, frame, BPTR(&buf));
1151 
1152  /* compare */
1153  if (buf.len != src.len)
1154  {
1155  msg(M_FATAL, "SELF TEST FAILED, src.len=%d buf.len=%d", src.len, buf.len);
1156  }
1157  for (j = 0; j < i; ++j)
1158  {
1159  const uint8_t in = *(BPTR(&src) + j);
1160  const uint8_t out = *(BPTR(&buf) + j);
1161  if (in != out)
1162  {
1163  msg(M_FATAL, "SELF TEST FAILED, pos=%d in=%d out=%d", j, in, out);
1164  }
1165  }
1166  }
1167  msg(M_INFO, PACKAGE_NAME " crypto self-test mode SUCCEEDED.");
1168  gc_free(&gc);
1169 }
1170 
1171 const char *
1172 print_key_filename(const char *str, bool is_inline)
1173 {
1174  if (is_inline)
1175  {
1176  return "[[INLINE]]";
1177  }
1178 
1179  return np(str);
1180 }
1181 
1182 void
1184  struct key_ctx_bi *ctx, const char *key_file,
1185  bool key_inline, const int key_direction,
1186  const char *key_name, const char *opt_name)
1187 {
1188  struct key2 key2;
1189  struct key_direction_state kds;
1190  unsigned int flags = RKF_MUST_SUCCEED;
1191 
1192  if (key_inline)
1193  {
1194  flags |= RKF_INLINE;
1195  }
1196  read_key_file(&key2, key_file, flags);
1197 
1198  if (key2.n != 2)
1199  {
1200  msg(M_ERR, "File '%s' does not have OpenVPN Static Key format. Using "
1201  "free-form passphrase file is not supported anymore.",
1202  print_key_filename(key_file, key_inline));
1203  }
1204 
1205  /* check for and fix highly unlikely key problems */
1206  verify_fix_key2(&key2, key_type, key_file);
1207 
1208  /* handle key direction */
1209  key_direction_state_init(&kds, key_direction);
1210  must_have_n_keys(key_file, opt_name, &key2, kds.need_keys);
1211 
1212  /* initialize key in both directions */
1213  init_key_ctx_bi(ctx, &key2, key_direction, key_type, key_name);
1214  secure_memzero(&key2, sizeof(key2));
1215 }
1216 
1217 /* header and footer for static key file */
1218 static const char static_key_head[] = "-----BEGIN OpenVPN Static key V1-----";
1219 static const char static_key_foot[] = "-----END OpenVPN Static key V1-----";
1220 
1221 static const char printable_char_fmt[] =
1222  "Non-Hex character ('%c') found at line %d in key file '%s' (%d/%d/%d bytes found/min/max)";
1223 
1224 static const char unprintable_char_fmt[] =
1225  "Non-Hex, unprintable character (0x%02x) found at line %d in key file '%s' (%d/%d/%d bytes found/min/max)";
1226 
1227 /* read key from file */
1228 
1229 void
1230 read_key_file(struct key2 *key2, const char *file, const unsigned int flags)
1231 {
1232  struct gc_arena gc = gc_new();
1233  struct buffer in;
1234  int size;
1235  uint8_t hex_byte[3] = {0, 0, 0};
1236 
1237  /* parse info */
1238  const unsigned char *cp;
1239  int hb_index = 0;
1240  int line_num = 1;
1241  int line_index = 0;
1242  int match = 0;
1243 
1244  /* output */
1245  uint8_t *out = (uint8_t *) &key2->keys;
1246  const int keylen = sizeof(key2->keys);
1247  int count = 0;
1248 
1249  /* parse states */
1250 #define PARSE_INITIAL 0
1251 #define PARSE_HEAD 1
1252 #define PARSE_DATA 2
1253 #define PARSE_DATA_COMPLETE 3
1254 #define PARSE_FOOT 4
1255 #define PARSE_FINISHED 5
1256  int state = PARSE_INITIAL;
1257 
1258  /* constants */
1259  const int hlen = strlen(static_key_head);
1260  const int flen = strlen(static_key_foot);
1261  const int onekeylen = sizeof(key2->keys[0]);
1262 
1263  CLEAR(*key2);
1264 
1265  /*
1266  * Key can be provided as a filename in 'file' or if RKF_INLINE
1267  * is set, the actual key data itself in ascii form.
1268  */
1269  if (flags & RKF_INLINE) /* 'file' is a string containing ascii representation of key */
1270  {
1271  size = strlen(file) + 1;
1272  buf_set_read(&in, (const uint8_t *)file, size);
1273  }
1274  else /* 'file' is a filename which refers to a file containing the ascii key */
1275  {
1276  in = buffer_read_from_file(file, &gc);
1277  if (!buf_valid(&in))
1278  {
1279  msg(M_FATAL, "Read error on key file ('%s')", file);
1280  }
1281 
1282  size = in.len;
1283  }
1284 
1285  cp = (unsigned char *)in.data;
1286  while (size > 0)
1287  {
1288  const unsigned char c = *cp;
1289 
1290 #if 0
1291  msg(M_INFO, "char='%c'[%d] s=%d ln=%d li=%d m=%d c=%d",
1292  c, (int)c, state, line_num, line_index, match, count);
1293 #endif
1294 
1295  if (c == '\n')
1296  {
1297  line_index = match = 0;
1298  ++line_num;
1299  }
1300  else
1301  {
1302  /* first char of new line */
1303  if (!line_index)
1304  {
1305  /* first char of line after header line? */
1306  if (state == PARSE_HEAD)
1307  {
1308  state = PARSE_DATA;
1309  }
1310 
1311  /* first char of footer */
1312  if ((state == PARSE_DATA || state == PARSE_DATA_COMPLETE) && c == '-')
1313  {
1314  state = PARSE_FOOT;
1315  }
1316  }
1317 
1318  /* compare read chars with header line */
1319  if (state == PARSE_INITIAL)
1320  {
1321  if (line_index < hlen && c == static_key_head[line_index])
1322  {
1323  if (++match == hlen)
1324  {
1325  state = PARSE_HEAD;
1326  }
1327  }
1328  }
1329 
1330  /* compare read chars with footer line */
1331  if (state == PARSE_FOOT)
1332  {
1333  if (line_index < flen && c == static_key_foot[line_index])
1334  {
1335  if (++match == flen)
1336  {
1337  state = PARSE_FINISHED;
1338  }
1339  }
1340  }
1341 
1342  /* reading key */
1343  if (state == PARSE_DATA)
1344  {
1345  if (isxdigit(c))
1346  {
1347  ASSERT(hb_index >= 0 && hb_index < 2);
1348  hex_byte[hb_index++] = c;
1349  if (hb_index == 2)
1350  {
1351  unsigned int u;
1352  ASSERT(sscanf((const char *)hex_byte, "%x", &u) == 1);
1353  *out++ = u;
1354  hb_index = 0;
1355  if (++count == keylen)
1356  {
1357  state = PARSE_DATA_COMPLETE;
1358  }
1359  }
1360  }
1361  else if (isspace(c))
1362  {
1363  }
1364  else
1365  {
1366  msg(M_FATAL,
1367  (isprint(c) ? printable_char_fmt : unprintable_char_fmt),
1368  c, line_num,
1369  print_key_filename(file, flags & RKF_INLINE), count,
1370  onekeylen, keylen);
1371  }
1372  }
1373  ++line_index;
1374  }
1375  ++cp;
1376  --size;
1377  }
1378 
1379  /*
1380  * Normally we will read either 1 or 2 keys from file.
1381  */
1382  key2->n = count / onekeylen;
1383 
1384  ASSERT(key2->n >= 0 && key2->n <= (int) SIZE(key2->keys));
1385 
1386  if (flags & RKF_MUST_SUCCEED)
1387  {
1388  if (!key2->n)
1389  {
1390  msg(M_FATAL, "Insufficient key material or header text not found in file '%s' (%d/%d/%d bytes found/min/max)",
1391  print_key_filename(file, flags & RKF_INLINE), count, onekeylen,
1392  keylen);
1393  }
1394 
1395  if (state != PARSE_FINISHED)
1396  {
1397  msg(M_FATAL, "Footer text not found in file '%s' (%d/%d/%d bytes found/min/max)",
1398  print_key_filename(file, flags & RKF_INLINE), count, onekeylen,
1399  keylen);
1400  }
1401  }
1402 
1403  /* zero file read buffer if not an inline file */
1404  if (!(flags & RKF_INLINE))
1405  {
1406  buf_clear(&in);
1407  }
1408 
1409 #if 0
1410  /* DEBUGGING */
1411  {
1412  int i;
1413  printf("KEY READ, n=%d\n", key2->n);
1414  for (i = 0; i < (int) SIZE(key2->keys); ++i)
1415  {
1416  /* format key as ascii */
1417  const char *fmt = format_hex_ex((const uint8_t *)&key2->keys[i],
1418  sizeof(key2->keys[i]),
1419  0,
1420  16,
1421  "\n",
1422  &gc);
1423  printf("[%d]\n%s\n\n", i, fmt);
1424  }
1425  }
1426 #endif
1427 
1428  /* pop our garbage collection level */
1429  gc_free(&gc);
1430 }
1431 
1432 int
1433 write_key_file(const int nkeys, const char *filename)
1434 {
1435  struct gc_arena gc = gc_new();
1436 
1437  int nbits = nkeys * sizeof(struct key) * 8;
1438 
1439  /* must be large enough to hold full key file */
1440  struct buffer out = alloc_buf_gc(2048, &gc);
1441 
1442  /* how to format the ascii file representation of key */
1443  const int bytes_per_line = 16;
1444 
1445  /* write header */
1446  buf_printf(&out, "#\n# %d bit OpenVPN static key\n#\n", nbits);
1447  buf_printf(&out, "%s\n", static_key_head);
1448 
1449  for (int i = 0; i < nkeys; ++i)
1450  {
1451  struct key key;
1452  char *fmt;
1453 
1454  /* generate random bits */
1455  generate_key_random(&key, NULL);
1456 
1457  /* format key as ascii */
1458  fmt = format_hex_ex((const uint8_t *)&key,
1459  sizeof(key),
1460  0,
1461  bytes_per_line,
1462  "\n",
1463  &gc);
1464 
1465  /* write to holding buffer */
1466  buf_printf(&out, "%s\n", fmt);
1467 
1468  /* zero memory which held key component (will be freed by GC) */
1469  secure_memzero(fmt, strlen(fmt));
1470  secure_memzero(&key, sizeof(key));
1471  }
1472 
1473  buf_printf(&out, "%s\n", static_key_foot);
1474 
1475  /* write key file to stdout if no filename given */
1476  if (!filename || strcmp(filename, "")==0)
1477  {
1478  printf("%.*s\n", BLEN(&out), BPTR(&out));
1479  }
1480  /* write key file, now formatted in out, to file */
1481  else if (!buffer_write_file(filename, &out))
1482  {
1483  nbits = -1;
1484  }
1485 
1486  /* zero memory which held file content (memory will be freed by GC) */
1487  buf_clear(&out);
1488 
1489  /* pop our garbage collection level */
1490  gc_free(&gc);
1491 
1492  return nbits;
1493 }
1494 
1495 void
1496 must_have_n_keys(const char *filename, const char *option, const struct key2 *key2, int n)
1497 {
1498  if (key2->n < n)
1499  {
1500 #ifdef ENABLE_SMALL
1501  msg(M_FATAL, "Key file '%s' used in --%s contains insufficient key material [keys found=%d required=%d]", filename, option, key2->n, n);
1502 #else
1503  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);
1504 #endif
1505  }
1506 }
1507 
1508 int
1509 ascii2keydirection(int msglevel, const char *str)
1510 {
1511  if (!str)
1512  {
1514  }
1515  else if (!strcmp(str, "0"))
1516  {
1517  return KEY_DIRECTION_NORMAL;
1518  }
1519  else if (!strcmp(str, "1"))
1520  {
1521  return KEY_DIRECTION_INVERSE;
1522  }
1523  else
1524  {
1525  msg(msglevel, "Unknown key direction '%s' -- must be '0' or '1'", str);
1526  return -1;
1527  }
1528  return KEY_DIRECTION_BIDIRECTIONAL; /* NOTREACHED */
1529 }
1530 
1531 const char *
1532 keydirection2ascii(int kd, bool remote, bool humanreadable)
1533 {
1534  if (kd == KEY_DIRECTION_BIDIRECTIONAL)
1535  {
1536  if (humanreadable)
1537  {
1538  return "not set";
1539  }
1540  else
1541  {
1542  return NULL;
1543  }
1544  }
1545  else if (kd == KEY_DIRECTION_NORMAL)
1546  {
1547  return remote ? "1" : "0";
1548  }
1549  else if (kd == KEY_DIRECTION_INVERSE)
1550  {
1551  return remote ? "0" : "1";
1552  }
1553  else
1554  {
1555  ASSERT(0);
1556  }
1557  return NULL; /* NOTREACHED */
1558 }
1559 
1560 void
1561 key_direction_state_init(struct key_direction_state *kds, int key_direction)
1562 {
1563  CLEAR(*kds);
1564  switch (key_direction)
1565  {
1566  case KEY_DIRECTION_NORMAL:
1567  kds->out_key = 0;
1568  kds->in_key = 1;
1569  kds->need_keys = 2;
1570  break;
1571 
1572  case KEY_DIRECTION_INVERSE:
1573  kds->out_key = 1;
1574  kds->in_key = 0;
1575  kds->need_keys = 2;
1576  break;
1577 
1579  kds->out_key = 0;
1580  kds->in_key = 0;
1581  kds->need_keys = 1;
1582  break;
1583 
1584  default:
1585  ASSERT(0);
1586  }
1587 }
1588 
1589 void
1590 verify_fix_key2(struct key2 *key2, const struct key_type *kt, const char *shared_secret_file)
1591 {
1592  int i;
1593 
1594  for (i = 0; i < key2->n; ++i)
1595  {
1596  /* Fix parity for DES keys and make sure not a weak key */
1597  fixup_key(&key2->keys[i], kt);
1598 
1599  /* This should be a very improbable failure */
1600  if (!check_key(&key2->keys[i], kt))
1601  {
1602  msg(M_FATAL, "Key #%d in '%s' is bad. Try making a new key with --genkey.",
1603  i+1, shared_secret_file);
1604  }
1605  }
1606 }
1607 
1608 /* given a key and key_type, write key to buffer */
1609 bool
1610 write_key(const struct key *key, const struct key_type *kt,
1611  struct buffer *buf)
1612 {
1614  && kt->hmac_length <= MAX_HMAC_KEY_LENGTH);
1615 
1616  if (!buf_write(buf, &kt->cipher_length, 1))
1617  {
1618  return false;
1619  }
1620  if (!buf_write(buf, &kt->hmac_length, 1))
1621  {
1622  return false;
1623  }
1624  if (!buf_write(buf, key->cipher, kt->cipher_length))
1625  {
1626  return false;
1627  }
1628  if (!buf_write(buf, key->hmac, kt->hmac_length))
1629  {
1630  return false;
1631  }
1632 
1633  return true;
1634 }
1635 
1636 /*
1637  * Given a key_type and buffer, read key from buffer.
1638  * Return: 1 on success
1639  * -1 read failure
1640  * 0 on key length mismatch
1641  */
1642 int
1643 read_key(struct key *key, const struct key_type *kt, struct buffer *buf)
1644 {
1645  uint8_t cipher_length;
1646  uint8_t hmac_length;
1647 
1648  CLEAR(*key);
1649  if (!buf_read(buf, &cipher_length, 1))
1650  {
1651  goto read_err;
1652  }
1653  if (!buf_read(buf, &hmac_length, 1))
1654  {
1655  goto read_err;
1656  }
1657 
1658  if (cipher_length != kt->cipher_length || hmac_length != kt->hmac_length)
1659  {
1660  goto key_len_err;
1661  }
1662 
1663  if (!buf_read(buf, key->cipher, cipher_length))
1664  {
1665  goto read_err;
1666  }
1667  if (!buf_read(buf, key->hmac, hmac_length))
1668  {
1669  goto read_err;
1670  }
1671 
1672  return 1;
1673 
1674 read_err:
1675  msg(D_TLS_ERRORS, "TLS Error: error reading key from remote");
1676  return -1;
1677 
1678 key_len_err:
1679  msg(D_TLS_ERRORS,
1680  "TLS Error: key length mismatch, local cipher/hmac %d/%d, remote cipher/hmac %d/%d",
1681  kt->cipher_length, kt->hmac_length, cipher_length, hmac_length);
1682  return 0;
1683 }
1684 
1685 /*
1686  * Random number functions, used in cases where we want
1687  * reasonably strong cryptographic random number generation
1688  * without depleting our entropy pool. Used for random
1689  * IV values and a number of other miscellaneous tasks.
1690  */
1691 
1692 static uint8_t *nonce_data = NULL; /* GLOBAL */
1693 static const md_kt_t *nonce_md = NULL; /* GLOBAL */
1694 static int nonce_secret_len = 0; /* GLOBAL */
1695 
1696 /* Reset the nonce value, also done periodically to refresh entropy */
1697 static void
1699 {
1700  const int size = md_kt_size(nonce_md) + nonce_secret_len;
1701 #if 1 /* Must be 1 for real usage */
1702  if (!rand_bytes(nonce_data, size))
1703  {
1704  msg(M_FATAL, "ERROR: Random number generator cannot obtain entropy for PRNG");
1705  }
1706 #else
1707  /* Only for testing -- will cause a predictable PRNG sequence */
1708  {
1709  int i;
1710  for (i = 0; i < size; ++i)
1711  {
1712  nonce_data[i] = (uint8_t) i;
1713  }
1714  }
1715 #endif
1716 }
1717 
1718 void
1719 prng_init(const char *md_name, const int nonce_secret_len_parm)
1720 {
1721  prng_uninit();
1722  nonce_md = md_name ? md_kt_get(md_name) : NULL;
1723  if (nonce_md)
1724  {
1725  ASSERT(nonce_secret_len_parm >= NONCE_SECRET_LEN_MIN && nonce_secret_len_parm <= NONCE_SECRET_LEN_MAX);
1726  nonce_secret_len = nonce_secret_len_parm;
1727  {
1728  const int size = md_kt_size(nonce_md) + nonce_secret_len;
1729  dmsg(D_CRYPTO_DEBUG, "PRNG init md=%s size=%d", md_kt_name(nonce_md), size);
1730  nonce_data = (uint8_t *) malloc(size);
1732  prng_reset_nonce();
1733  }
1734  }
1735 }
1736 
1737 void
1739 {
1740  free(nonce_data);
1741  nonce_data = NULL;
1742  nonce_md = NULL;
1743  nonce_secret_len = 0;
1744 }
1745 
1746 void
1747 prng_bytes(uint8_t *output, int len)
1748 {
1749  static size_t processed = 0;
1750 
1751  if (nonce_md)
1752  {
1753  const int md_size = md_kt_size(nonce_md);
1754  while (len > 0)
1755  {
1756  const int blen = min_int(len, md_size);
1758  memcpy(output, nonce_data, blen);
1759  output += blen;
1760  len -= blen;
1761 
1762  /* Ensure that random data is reset regularly */
1763  processed += blen;
1764  if (processed > PRNG_NONCE_RESET_BYTES)
1765  {
1766  prng_reset_nonce();
1767  processed = 0;
1768  }
1769  }
1770  }
1771  else
1772  {
1773  ASSERT(rand_bytes(output, len));
1774  }
1775 }
1776 
1777 /* an analogue to the random() function, but use prng_bytes */
1778 long int
1780 {
1781  long int l;
1782  prng_bytes((unsigned char *)&l, sizeof(l));
1783  if (l < 0)
1784  {
1785  l = -l;
1786  }
1787  return l;
1788 }
1789 
1790 void
1792 {
1793  const char *var_key_size = cipher_kt_var_key_size(cipher) ?
1794  " by default" : "";
1795 
1796  printf("%s (%d bit key%s, ",
1797  cipher_kt_name(cipher),
1798  cipher_kt_key_size(cipher) * 8, var_key_size);
1799 
1800  if (cipher_kt_block_size(cipher) == 1)
1801  {
1802  printf("stream cipher");
1803  }
1804  else
1805  {
1806  printf("%d bit block", cipher_kt_block_size(cipher) * 8);
1807  }
1808 
1809  if (!cipher_kt_mode_cbc(cipher))
1810  {
1811  printf(", TLS client/server mode only");
1812  }
1813 
1814  printf(")\n");
1815 }
1816 
1817 static const cipher_name_pair *
1818 get_cipher_name_pair(const char *cipher_name)
1819 {
1820  const cipher_name_pair *pair;
1821  size_t i = 0;
1822 
1823  /* Search for a cipher name translation */
1824  for (; i < cipher_name_translation_table_count; i++)
1825  {
1826  pair = &cipher_name_translation_table[i];
1827  if (0 == strcmp(cipher_name, pair->openvpn_name)
1828  || 0 == strcmp(cipher_name, pair->lib_name))
1829  {
1830  return pair;
1831  }
1832  }
1833 
1834  /* Nothing found, return null */
1835  return NULL;
1836 }
1837 
1838 const char *
1839 translate_cipher_name_from_openvpn(const char *cipher_name)
1840 {
1841  const cipher_name_pair *pair = get_cipher_name_pair(cipher_name);
1842 
1843  if (NULL == pair)
1844  {
1845  return cipher_name;
1846  }
1847 
1848  return pair->lib_name;
1849 }
1850 
1851 const char *
1852 translate_cipher_name_to_openvpn(const char *cipher_name)
1853 {
1854  const cipher_name_pair *pair = get_cipher_name_pair(cipher_name);
1855 
1856  if (NULL == pair)
1857  {
1858  return cipher_name;
1859  }
1860 
1861  return pair->openvpn_name;
1862 }
1863 
1864 void
1865 write_pem_key_file(const char *filename, const char *pem_name)
1866 {
1867  struct gc_arena gc = gc_new();
1868  struct key server_key = { 0 };
1869  struct buffer server_key_buf = clear_buf();
1870  struct buffer server_key_pem = clear_buf();
1871 
1872  if (!rand_bytes((void *)&server_key, sizeof(server_key)))
1873  {
1874  msg(M_NONFATAL, "ERROR: could not generate random key");
1875  goto cleanup;
1876  }
1877  buf_set_read(&server_key_buf, (void *)&server_key, sizeof(server_key));
1878  if (!crypto_pem_encode(pem_name, &server_key_pem,
1879  &server_key_buf, &gc))
1880  {
1881  msg(M_WARN, "ERROR: could not PEM-encode key");
1882  goto cleanup;
1883  }
1884 
1885  if (!filename || strcmp(filename, "")==0)
1886  {
1887  printf("%.*s", BLEN(&server_key_pem), BPTR(&server_key_pem));
1888  }
1889  else if (!buffer_write_file(filename, &server_key_pem))
1890  {
1891  msg(M_ERR, "ERROR: could not write key file");
1892  goto cleanup;
1893  }
1894 
1895 cleanup:
1896  secure_memzero(&server_key, sizeof(server_key));
1897  buf_clear(&server_key_pem);
1898  gc_free(&gc);
1899  return;
1900 }
1901 
1902 bool
1903 generate_ephemeral_key(struct buffer *key, const char *key_name)
1904 {
1905  const int len = BCAP(key);
1906 
1907  msg(M_INFO, "Using random %s.", key_name);
1908 
1909  if (!rand_bytes(BEND(key), len))
1910  {
1911  msg(M_WARN, "ERROR: could not generate random key");
1912  return false;
1913  }
1914 
1915  buf_inc_len(key, len);
1916 
1917  return true;
1918 }
1919 
1920 bool
1921 read_pem_key_file(struct buffer *key, const char *pem_name,
1922  const char *key_file, bool key_inline)
1923 {
1924  bool ret = false;
1925  struct buffer key_pem = { 0 };
1926  struct gc_arena gc = gc_new();
1927 
1928  if (!key_inline)
1929  {
1930  key_pem = buffer_read_from_file(key_file, &gc);
1931  if (!buf_valid(&key_pem))
1932  {
1933  msg(M_WARN, "ERROR: failed to read %s file (%s)",
1934  pem_name, key_file);
1935  goto cleanup;
1936  }
1937  }
1938  else
1939  {
1940  buf_set_read(&key_pem, (const void *)key_file, strlen(key_file) + 1);
1941  }
1942 
1943  if (!crypto_pem_decode(pem_name, key, &key_pem))
1944  {
1945  msg(M_WARN, "ERROR: %s pem decode failed", pem_name);
1946  goto cleanup;
1947  }
1948 
1949  ret = true;
1950 cleanup:
1951  if (!key_inline)
1952  {
1953  buf_clear(&key_pem);
1954  }
1955  gc_free(&gc);
1956  return ret;
1957 }
#define M_NONFATAL
Definition: error.h:95
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:1643
#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:1818
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:891
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:1086
static const char unprintable_char_fmt[]
Definition: crypto.c:1224
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
#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:823
void prng_init(const char *md_name, const int nonce_secret_len_parm)
Pseudo-random number generator initialisation.
Definition: crypto.c:1719
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:915
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:972
#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
bool write_key(const struct key *key, const struct key_type *kt, struct buffer *buf)
Definition: crypto.c:1610
static void frame_add_to_extra_frame(struct frame *frame, const unsigned int increment)
Definition: mtu.h:274
#define dmsg
Definition: error.h:174
#define D_TLS_ERRORS
Definition: errlevel.h:59
const char * openvpn_name
Cipher name used by OpenVPN.
static bool buf_safe(const struct buffer *buf, int len)
Definition: buffer.h:541
static uint8_t * buf_write_alloc(struct buffer *buf, int size)
Definition: buffer.h:656
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
static bool match(const WIN32_FIND_DATA *find, LPCTSTR ext)
Definition: automatic.c:112
#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:1694
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:1698
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 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:1693
#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:1399
#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:221
bool check_key(struct key *key, const struct key_type *kt)
Definition: crypto.c:933
bool generate_ephemeral_key(struct buffer *key, const char *key_name)
Generate ephermal key material into the key structure.
Definition: crypto.c:1903
static bool check_debug_level(unsigned int level)
Definition: error.h:245
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:1218
#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:1003
#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:1791
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
static bool buf_write(struct buffer *dest, const void *src, int size)
Definition: buffer.h:689
void must_have_n_keys(const char *filename, const char *option, const struct key2 *key2, int n)
Definition: crypto.c:1496
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:468
void prng_uninit(void)
Definition: crypto.c:1738
#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:1747
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:1172
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:1230
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:1921
static uint8_t * nonce_data
Definition: crypto.c:1692
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:1865
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:462
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:1532
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:871
static const char printable_char_fmt[]
Definition: crypto.c:1221
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.
#define msg
Definition: error.h:173
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:1509
void free_key_ctx_bi(struct key_ctx_bi *ctx)
Definition: crypto.c:908
#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:1561
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:465
#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.
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
unsigned __int8 uint8_t
Definition: config-msvc.h:159
#define M_ERR
Definition: error.h:110
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:1219
#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:1433
Wrapper structure for dynamically allocated memory.
Definition: buffer.h:60
#define M_FATAL
Definition: error.h:94
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:1852
#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
const char * translate_cipher_name_from_openvpn(const char *cipher_name)
Translate a data channel cipher name from the crypto library specific name to the OpenVPN config file...
Definition: crypto.c:1839
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:96
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:1019
void key2_print(const struct key2 *k, const struct key_type *kt, const char *prefix0, const char *prefix1)
Definition: crypto.c:1063
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 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:1183
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:1779
#define BEND(buf)
Definition: buffer.h:125
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:94
void verify_fix_key2(struct key2 *key2, const struct key_type *kt, const char *shared_secret_file)
Definition: crypto.c:1590
#define PARSE_FINISHED
void hmac_ctx_free(hmac_ctx_t *ctx)
static void buf_set_read(struct buffer *buf, const uint8_t *data, int size)
Definition: buffer.h:335
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
void init_key_type(struct key_type *kt, const char *ciphername, const char *authname, int keysize, bool tls_mode, bool warn)
Initialize a key_type structure with.
Definition: crypto.c:741
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