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