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