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