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  unsigned int 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__, crypto_overhead);
729 }
730 
731 unsigned int
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_insecure(kt->cipher))
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  {
924  if (key->cipher[i])
925  {
926  return false;
927  }
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 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 = buffer_read_from_file(file, &gc);
1274  if (!buf_valid(&in))
1275  {
1276  msg(M_FATAL, "Read error on key file ('%s')", file);
1277  }
1278 
1279  size = in.len;
1280  }
1281 
1282  cp = (unsigned char *)in.data;
1283  while (size > 0)
1284  {
1285  const unsigned char c = *cp;
1286 
1287 #if 0
1288  msg(M_INFO, "char='%c'[%d] s=%d ln=%d li=%d m=%d c=%d",
1289  c, (int)c, state, line_num, line_index, match, count);
1290 #endif
1291 
1292  if (c == '\n')
1293  {
1294  line_index = match = 0;
1295  ++line_num;
1296  }
1297  else
1298  {
1299  /* first char of new line */
1300  if (!line_index)
1301  {
1302  /* first char of line after header line? */
1303  if (state == PARSE_HEAD)
1304  {
1305  state = PARSE_DATA;
1306  }
1307 
1308  /* first char of footer */
1309  if ((state == PARSE_DATA || state == PARSE_DATA_COMPLETE) && c == '-')
1310  {
1311  state = PARSE_FOOT;
1312  }
1313  }
1314 
1315  /* compare read chars with header line */
1316  if (state == PARSE_INITIAL)
1317  {
1318  if (line_index < hlen && c == static_key_head[line_index])
1319  {
1320  if (++match == hlen)
1321  {
1322  state = PARSE_HEAD;
1323  }
1324  }
1325  }
1326 
1327  /* compare read chars with footer line */
1328  if (state == PARSE_FOOT)
1329  {
1330  if (line_index < flen && c == static_key_foot[line_index])
1331  {
1332  if (++match == flen)
1333  {
1334  state = PARSE_FINISHED;
1335  }
1336  }
1337  }
1338 
1339  /* reading key */
1340  if (state == PARSE_DATA)
1341  {
1342  if (isxdigit(c))
1343  {
1344  ASSERT(hb_index >= 0 && hb_index < 2);
1345  hex_byte[hb_index++] = c;
1346  if (hb_index == 2)
1347  {
1348  unsigned int u;
1349  ASSERT(sscanf((const char *)hex_byte, "%x", &u) == 1);
1350  *out++ = u;
1351  hb_index = 0;
1352  if (++count == keylen)
1353  {
1354  state = PARSE_DATA_COMPLETE;
1355  }
1356  }
1357  }
1358  else if (isspace(c))
1359  {
1360  }
1361  else
1362  {
1363  msg(M_FATAL,
1364  (isprint(c) ? printable_char_fmt : unprintable_char_fmt),
1365  c, line_num, error_filename, count, onekeylen, keylen);
1366  }
1367  }
1368  ++line_index;
1369  }
1370  ++cp;
1371  --size;
1372  }
1373 
1374  /*
1375  * Normally we will read either 1 or 2 keys from file.
1376  */
1377  key2->n = count / onekeylen;
1378 
1379  ASSERT(key2->n >= 0 && key2->n <= (int) SIZE(key2->keys));
1380 
1381  if (flags & RKF_MUST_SUCCEED)
1382  {
1383  if (!key2->n)
1384  {
1385  msg(M_FATAL, "Insufficient key material or header text not found in file '%s' (%d/%d/%d bytes found/min/max)",
1386  error_filename, count, onekeylen, keylen);
1387  }
1388 
1389  if (state != PARSE_FINISHED)
1390  {
1391  msg(M_FATAL, "Footer text not found in file '%s' (%d/%d/%d bytes found/min/max)",
1392  error_filename, count, onekeylen, keylen);
1393  }
1394  }
1395 
1396  /* zero file read buffer if not an inline file */
1397  if (!(flags & RKF_INLINE))
1398  {
1399  buf_clear(&in);
1400  }
1401 
1402 #if 0
1403  /* DEBUGGING */
1404  {
1405  int i;
1406  printf("KEY READ, n=%d\n", key2->n);
1407  for (i = 0; i < (int) SIZE(key2->keys); ++i)
1408  {
1409  /* format key as ascii */
1410  const char *fmt = format_hex_ex((const uint8_t *)&key2->keys[i],
1411  sizeof(key2->keys[i]),
1412  0,
1413  16,
1414  "\n",
1415  &gc);
1416  printf("[%d]\n%s\n\n", i, fmt);
1417  }
1418  }
1419 #endif
1420 
1421  /* pop our garbage collection level */
1422  gc_free(&gc);
1423 }
1424 
1425 int
1426 write_key_file(const int nkeys, const char *filename)
1427 {
1428  struct gc_arena gc = gc_new();
1429 
1430  int nbits = nkeys * sizeof(struct key) * 8;
1431 
1432  /* must be large enough to hold full key file */
1433  struct buffer out = alloc_buf_gc(2048, &gc);
1434 
1435  /* how to format the ascii file representation of key */
1436  const int bytes_per_line = 16;
1437 
1438  /* write header */
1439  buf_printf(&out, "#\n# %d bit OpenVPN static key\n#\n", nbits);
1440  buf_printf(&out, "%s\n", static_key_head);
1441 
1442  for (int i = 0; i < nkeys; ++i)
1443  {
1444  struct key key;
1445  char *fmt;
1446 
1447  /* generate random bits */
1448  generate_key_random(&key, NULL);
1449 
1450  /* format key as ascii */
1451  fmt = format_hex_ex((const uint8_t *)&key,
1452  sizeof(key),
1453  0,
1454  bytes_per_line,
1455  "\n",
1456  &gc);
1457 
1458  /* write to holding buffer */
1459  buf_printf(&out, "%s\n", fmt);
1460 
1461  /* zero memory which held key component (will be freed by GC) */
1462  secure_memzero(fmt, strlen(fmt));
1463  secure_memzero(&key, sizeof(key));
1464  }
1465 
1466  buf_printf(&out, "%s\n", static_key_foot);
1467 
1468  /* write key file, now formatted in out, to file */
1469  if (!buffer_write_file(filename, &out))
1470  {
1471  nbits = -1;
1472  }
1473 
1474  /* zero memory which held file content (memory will be freed by GC) */
1475  buf_clear(&out);
1476 
1477  /* pop our garbage collection level */
1478  gc_free(&gc);
1479 
1480  return nbits;
1481 }
1482 
1483 void
1484 must_have_n_keys(const char *filename, const char *option, const struct key2 *key2, int n)
1485 {
1486  if (key2->n < n)
1487  {
1488 #ifdef ENABLE_SMALL
1489  msg(M_FATAL, "Key file '%s' used in --%s contains insufficient key material [keys found=%d required=%d]", filename, option, key2->n, n);
1490 #else
1491  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);
1492 #endif
1493  }
1494 }
1495 
1496 int
1497 ascii2keydirection(int msglevel, const char *str)
1498 {
1499  if (!str)
1500  {
1502  }
1503  else if (!strcmp(str, "0"))
1504  {
1505  return KEY_DIRECTION_NORMAL;
1506  }
1507  else if (!strcmp(str, "1"))
1508  {
1509  return KEY_DIRECTION_INVERSE;
1510  }
1511  else
1512  {
1513  msg(msglevel, "Unknown key direction '%s' -- must be '0' or '1'", str);
1514  return -1;
1515  }
1516  return KEY_DIRECTION_BIDIRECTIONAL; /* NOTREACHED */
1517 }
1518 
1519 const char *
1520 keydirection2ascii(int kd, bool remote, bool humanreadable)
1521 {
1522  if (kd == KEY_DIRECTION_BIDIRECTIONAL)
1523  {
1524  if (humanreadable)
1525  {
1526  return "not set";
1527  }
1528  else
1529  {
1530  return NULL;
1531  }
1532  }
1533  else if (kd == KEY_DIRECTION_NORMAL)
1534  {
1535  return remote ? "1" : "0";
1536  }
1537  else if (kd == KEY_DIRECTION_INVERSE)
1538  {
1539  return remote ? "0" : "1";
1540  }
1541  else
1542  {
1543  ASSERT(0);
1544  }
1545  return NULL; /* NOTREACHED */
1546 }
1547 
1548 void
1549 key_direction_state_init(struct key_direction_state *kds, int key_direction)
1550 {
1551  CLEAR(*kds);
1552  switch (key_direction)
1553  {
1554  case KEY_DIRECTION_NORMAL:
1555  kds->out_key = 0;
1556  kds->in_key = 1;
1557  kds->need_keys = 2;
1558  break;
1559 
1560  case KEY_DIRECTION_INVERSE:
1561  kds->out_key = 1;
1562  kds->in_key = 0;
1563  kds->need_keys = 2;
1564  break;
1565 
1567  kds->out_key = 0;
1568  kds->in_key = 0;
1569  kds->need_keys = 1;
1570  break;
1571 
1572  default:
1573  ASSERT(0);
1574  }
1575 }
1576 
1577 void
1578 verify_fix_key2(struct key2 *key2, const struct key_type *kt, const char *shared_secret_file)
1579 {
1580  int i;
1581 
1582  for (i = 0; i < key2->n; ++i)
1583  {
1584  /* Fix parity for DES keys and make sure not a weak key */
1585  fixup_key(&key2->keys[i], kt);
1586 
1587  /* This should be a very improbable failure */
1588  if (!check_key(&key2->keys[i], kt))
1589  {
1590  msg(M_FATAL, "Key #%d in '%s' is bad. Try making a new key with --genkey.",
1591  i+1, shared_secret_file);
1592  }
1593  }
1594 }
1595 
1596 /* given a key and key_type, write key to buffer */
1597 bool
1598 write_key(const struct key *key, const struct key_type *kt,
1599  struct buffer *buf)
1600 {
1602  && kt->hmac_length <= MAX_HMAC_KEY_LENGTH);
1603 
1604  if (!buf_write(buf, &kt->cipher_length, 1))
1605  {
1606  return false;
1607  }
1608  if (!buf_write(buf, &kt->hmac_length, 1))
1609  {
1610  return false;
1611  }
1612  if (!buf_write(buf, key->cipher, kt->cipher_length))
1613  {
1614  return false;
1615  }
1616  if (!buf_write(buf, key->hmac, kt->hmac_length))
1617  {
1618  return false;
1619  }
1620 
1621  return true;
1622 }
1623 
1624 /*
1625  * Given a key_type and buffer, read key from buffer.
1626  * Return: 1 on success
1627  * -1 read failure
1628  * 0 on key length mismatch
1629  */
1630 int
1631 read_key(struct key *key, const struct key_type *kt, struct buffer *buf)
1632 {
1633  uint8_t cipher_length;
1634  uint8_t hmac_length;
1635 
1636  CLEAR(*key);
1637  if (!buf_read(buf, &cipher_length, 1))
1638  {
1639  goto read_err;
1640  }
1641  if (!buf_read(buf, &hmac_length, 1))
1642  {
1643  goto read_err;
1644  }
1645 
1646  if (cipher_length != kt->cipher_length || hmac_length != kt->hmac_length)
1647  {
1648  goto key_len_err;
1649  }
1650 
1651  if (!buf_read(buf, key->cipher, cipher_length))
1652  {
1653  goto read_err;
1654  }
1655  if (!buf_read(buf, key->hmac, hmac_length))
1656  {
1657  goto read_err;
1658  }
1659 
1660  return 1;
1661 
1662 read_err:
1663  msg(D_TLS_ERRORS, "TLS Error: error reading key from remote");
1664  return -1;
1665 
1666 key_len_err:
1667  msg(D_TLS_ERRORS,
1668  "TLS Error: key length mismatch, local cipher/hmac %d/%d, remote cipher/hmac %d/%d",
1669  kt->cipher_length, kt->hmac_length, cipher_length, hmac_length);
1670  return 0;
1671 }
1672 
1673 /*
1674  * Random number functions, used in cases where we want
1675  * reasonably strong cryptographic random number generation
1676  * without depleting our entropy pool. Used for random
1677  * IV values and a number of other miscellaneous tasks.
1678  */
1679 
1680 static uint8_t *nonce_data = NULL; /* GLOBAL */
1681 static const md_kt_t *nonce_md = NULL; /* GLOBAL */
1682 static int nonce_secret_len = 0; /* GLOBAL */
1683 
1684 /* Reset the nonce value, also done periodically to refresh entropy */
1685 static void
1687 {
1688  const int size = md_kt_size(nonce_md) + nonce_secret_len;
1689 #if 1 /* Must be 1 for real usage */
1690  if (!rand_bytes(nonce_data, size))
1691  {
1692  msg(M_FATAL, "ERROR: Random number generator cannot obtain entropy for PRNG");
1693  }
1694 #else
1695  /* Only for testing -- will cause a predictable PRNG sequence */
1696  {
1697  int i;
1698  for (i = 0; i < size; ++i)
1699  {
1700  nonce_data[i] = (uint8_t) i;
1701  }
1702  }
1703 #endif
1704 }
1705 
1706 void
1707 prng_init(const char *md_name, const int nonce_secret_len_parm)
1708 {
1709  prng_uninit();
1710  nonce_md = md_name ? md_kt_get(md_name) : NULL;
1711  if (nonce_md)
1712  {
1713  ASSERT(nonce_secret_len_parm >= NONCE_SECRET_LEN_MIN && nonce_secret_len_parm <= NONCE_SECRET_LEN_MAX);
1714  nonce_secret_len = nonce_secret_len_parm;
1715  {
1716  const int size = md_kt_size(nonce_md) + nonce_secret_len;
1717  dmsg(D_CRYPTO_DEBUG, "PRNG init md=%s size=%d", md_kt_name(nonce_md), size);
1718  nonce_data = (uint8_t *) malloc(size);
1720  prng_reset_nonce();
1721  }
1722  }
1723 }
1724 
1725 void
1727 {
1728  free(nonce_data);
1729  nonce_data = NULL;
1730  nonce_md = NULL;
1731  nonce_secret_len = 0;
1732 }
1733 
1734 void
1735 prng_bytes(uint8_t *output, int len)
1736 {
1737  static size_t processed = 0;
1738 
1739  if (nonce_md)
1740  {
1741  const int md_size = md_kt_size(nonce_md);
1742  while (len > 0)
1743  {
1744  const int blen = min_int(len, md_size);
1746  memcpy(output, nonce_data, blen);
1747  output += blen;
1748  len -= blen;
1749 
1750  /* Ensure that random data is reset regularly */
1751  processed += blen;
1752  if (processed > PRNG_NONCE_RESET_BYTES)
1753  {
1754  prng_reset_nonce();
1755  processed = 0;
1756  }
1757  }
1758  }
1759  else
1760  {
1761  ASSERT(rand_bytes(output, len));
1762  }
1763 }
1764 
1765 /* an analogue to the random() function, but use prng_bytes */
1766 long int
1768 {
1769  long int l;
1770  prng_bytes((unsigned char *)&l, sizeof(l));
1771  if (l < 0)
1772  {
1773  l = -l;
1774  }
1775  return l;
1776 }
1777 
1778 void
1780 {
1781  const char *var_key_size = cipher_kt_var_key_size(cipher) ?
1782  " by default" : "";
1783 
1784  printf("%s (%d bit key%s, ",
1786  cipher_kt_key_size(cipher) * 8, var_key_size);
1787 
1788  if (cipher_kt_block_size(cipher) == 1)
1789  {
1790  printf("stream cipher");
1791  }
1792  else
1793  {
1794  printf("%d bit block", cipher_kt_block_size(cipher) * 8);
1795  }
1796 
1797  if (!cipher_kt_mode_cbc(cipher))
1798  {
1799  printf(", TLS client/server mode only");
1800  }
1801 
1802  printf(")\n");
1803 }
1804 
1805 static const cipher_name_pair *
1806 get_cipher_name_pair(const char *cipher_name)
1807 {
1808  const cipher_name_pair *pair;
1809  size_t i = 0;
1810 
1811  /* Search for a cipher name translation */
1812  for (; i < cipher_name_translation_table_count; i++)
1813  {
1814  pair = &cipher_name_translation_table[i];
1815  if (0 == strcmp(cipher_name, pair->openvpn_name)
1816  || 0 == strcmp(cipher_name, pair->lib_name))
1817  {
1818  return pair;
1819  }
1820  }
1821 
1822  /* Nothing found, return null */
1823  return NULL;
1824 }
1825 
1826 const char *
1827 translate_cipher_name_from_openvpn(const char *cipher_name)
1828 {
1829  const cipher_name_pair *pair = get_cipher_name_pair(cipher_name);
1830 
1831  if (NULL == pair)
1832  {
1833  return cipher_name;
1834  }
1835 
1836  return pair->lib_name;
1837 }
1838 
1839 const char *
1840 translate_cipher_name_to_openvpn(const char *cipher_name)
1841 {
1842  const cipher_name_pair *pair = get_cipher_name_pair(cipher_name);
1843 
1844  if (NULL == pair)
1845  {
1846  return cipher_name;
1847  }
1848 
1849  return pair->openvpn_name;
1850 }
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:1631
#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:1806
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
unsigned int crypto_max_overhead(void)
Return the worst-case OpenVPN crypto overhead (in bytes)
Definition: crypto.c:732
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:257
Key ordering of the key2.keys array.
Definition: crypto.h:198
#define D_CRYPTO_DEBUG
Definition: errlevel.h:144
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:1707
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:639
#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:1023
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:1598
static void frame_add_to_extra_frame(struct frame *frame, const unsigned int increment)
Definition: mtu.h:274
#define D_TLS_ERRORS
Definition: errlevel.h:59
const char * openvpn_name
Cipher name used by OpenVPN.
static bool buf_safe(const struct buffer *buf, int len)
Definition: buffer.h:541
#define ASSERT(x)
Definition: error.h:221
static uint8_t * buf_write_alloc(struct buffer *buf, int size)
Definition: buffer.h:656
int n
The number of key objects stored in the key2.keys array.
Definition: crypto.h:183
#define OPENVPN_MAX_CIPHER_BLOCK_SIZE
int out_key
Index into the key2.keys array for the sending direction.
Definition: crypto.h:200
static bool match(const WIN32_FIND_DATA *find, LPCTSTR ext)
Definition: automatic.c:112
#define OPENVPN_MAX_HMAC_SIZE
#define M_FATAL
Definition: error.h:94
bool buf_printf(struct buffer *buf, const char *format,...)
Definition: buffer.c:245
int cipher_ctx_reset(cipher_ctx_t *ctx, const uint8_t *iv_buf)
Resets the given cipher context, setting the IV to the specified value.
static char * format_hex(const uint8_t *data, int size, int maxoutput, struct gc_arena *gc)
Definition: buffer.h:526
#define CLEAR(x)
Definition: basic.h:33
static int nonce_secret_len
Definition: crypto.c:1682
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:1686
bool cipher_kt_insecure(const cipher_kt_t *cipher)
Returns true if we consider this cipher to be insecure.
int cipher_kt_tag_size(const cipher_kt_t *cipher_kt)
Returns the MAC tag size of the cipher, in bytes.
static bool cipher_kt_var_key_size(const cipher_kt_t *cipher)
#define MAX_CIPHER_KEY_LENGTH
static const md_kt_t * nonce_md
Definition: crypto.c:1681
#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:1402
#define PARSE_INITIAL
bool buffer_write_file(const char *filename, const struct buffer *buf)
Write buffer contents to file.
Definition: buffer.c:372
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:274
bool key_des_check(uint8_t *key, int key_len, int ndc)
void hmac_ctx_cleanup(hmac_ctx_t *ctx)
struct packet_id_rec rec
Definition: packet_id.h:208
uint8_t hmac[MAX_HMAC_KEY_LENGTH]
Key material for HMAC operations.
Definition: crypto.h:155
static bool buf_read(struct buffer *src, void *dest, int size)
Definition: buffer.h:800
static const char static_key_head[]
Definition: crypto.c:1213
#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: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: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
void print_cipher(const cipher_kt_t *cipher)
Print a cipher list entry.
Definition: crypto.c:1779
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:689
void must_have_n_keys(const char *filename, const char *option, const struct key2 *key2, int n)
Definition: crypto.c:1484
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:430
void prng_uninit(void)
Definition: crypto.c:1726
#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:299
static uint8_t * buf_prepend(struct buffer *buf, int size)
Definition: buffer.h:627
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:1015
#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:1735
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:1225
static void gc_init(struct gc_arena *a)
Definition: buffer.h:1002
#define KEY_DIRECTION_INVERSE
Definition: crypto.h:175
#define INLINE_FILE_TAG
Definition: common.h:95
static uint8_t * nonce_data
Definition: crypto.c:1680
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:424
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:1520
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: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)
void buf_clear(struct buffer *buf)
Definition: buffer.c:164
void key_des_fixup(uint8_t *key, int key_len, int ndc)
void crypto_adjust_frame_parameters(struct frame *frame, const struct key_type *kt, bool packet_id, bool packet_id_long_form)
Calculate crypto overhead and adjust frame to account for that.
Definition: crypto.c: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:522
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:1497
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:1549
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:427
#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:44
#define D_SHOW_KEY_SOURCE
Definition: errlevel.h:118
unsigned __int8 uint8_t
Definition: config-msvc.h:123
static bool buf_inc_len(struct buffer *buf, int inc)
Definition: buffer.h:611
const size_t cipher_name_translation_table_count
static void check_malloc_return(const void *p)
Definition: buffer.h:1093
const md_kt_t * digest
Message digest static parameters.
Definition: crypto.h:144
struct key_ctx_bi key_ctx_bi
OpenSSL cipher and HMAC contexts for both sending and receiving directions.
Definition: crypto.h:234
#define FRAME_HEADROOM_MARKER_DECRYPT
Definition: mtu.h:129
#define CO_MUTE_REPLAY_WARNINGS
Bit-flag indicating not to display replay warnings.
Definition: crypto.h:254
static const char static_key_foot[]
Definition: crypto.c: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)
Write nkeys 1024-bits keys to file.
Definition: crypto.c:1426
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:1840
#define buf_init(buf, offset)
Definition: buffer.h:196
#define OPENVPN_OP_ENCRYPT
Cipher should encrypt.
static bool buf_write_prepend(struct buffer *dest, const void *src, int size)
Definition: buffer.h:701
#define D_SHOW_KEYS
Definition: errlevel.h: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:1827
struct buffer alloc_buf_gc(size_t size, struct gc_arena *gc)
Definition: buffer.c:90
static int memcmp_constant_time(const void *a, const void *b, size_t size)
As memcmp(), but constant-time.
Definition: crypto.h:500
uint32_t packet_id_type
Definition: packet_id.h:49
static int min_int(int x, int y)
Definition: integer.h:57
#define free
Definition: cmocka.c:1850
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: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:1767
#define BEND(buf)
Definition: buffer.h:125
static void openvpn_encrypt_v1(struct buffer *buf, struct buffer work, struct crypto_options *opt)
Definition: crypto.c: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:1578
#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:162