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