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