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) 2016-2018 Fox Crypto B.V. <openvpn@fox-it.com>
9  *
10  *  This program is free software; you can redistribute it and/or modify
11  *  it under the terms of the GNU General Public License version 2
12  *  as published by the Free Software Foundation.
13  *
14  *  This program is distributed in the hope that it will be useful,
15  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
16  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17  *  GNU General Public License for more details.
18  *
19  *  You should have received a copy of the GNU General Public License along
20  *  with this program; if not, write to the Free Software Foundation, Inc.,
21  *  51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
22  */
23 
24 #ifdef HAVE_CONFIG_H
25 #include "config.h"
26 #elif defined(_MSC_VER)
27 #include "config-msvc.h"
28 #endif
29 
30 #include "syshead.h"
31 
32 #include "argv.h"
33 #include "base64.h"
34 #include "crypto.h"
35 #include "platform.h"
36 #include "run_command.h"
37 #include "session_id.h"
38 #include "ssl.h"
39 
40 #include "tls_crypt.h"
41 
42 const char *tls_crypt_v2_cli_pem_name = "OpenVPN tls-crypt-v2 client key";
43 const char *tls_crypt_v2_srv_pem_name = "OpenVPN tls-crypt-v2 server key";
44 
45 /** Metadata contains user-specified data */
46 static const uint8_t TLS_CRYPT_METADATA_TYPE_USER           = 0x00;
47 /** Metadata contains a 64-bit unix timestamp in network byte order */
48 static const uint8_t TLS_CRYPT_METADATA_TYPE_TIMESTAMP      = 0x01;
49 
50 static struct key_type
tls_crypt_kt(void)51 tls_crypt_kt(void)
52 {
53     struct key_type kt;
54     kt.cipher = cipher_kt_get("AES-256-CTR");
55     kt.digest = md_kt_get("SHA256");
56 
57     if (!kt.cipher)
58     {
59         msg(M_WARN, "ERROR: --tls-crypt requires AES-256-CTR support.");
60         return (struct key_type) { 0 };
61     }
62     if (!kt.digest)
63     {
64         msg(M_WARN, "ERROR: --tls-crypt requires HMAC-SHA-256 support.");
65         return (struct key_type) { 0 };
66     }
67 
68     kt.cipher_length = cipher_kt_key_size(kt.cipher);
69     kt.hmac_length = md_kt_size(kt.digest);
70 
71     return kt;
72 }
73 
74 int
tls_crypt_buf_overhead(void)75 tls_crypt_buf_overhead(void)
76 {
77     return packet_id_size(true) + TLS_CRYPT_TAG_SIZE + TLS_CRYPT_BLOCK_SIZE;
78 }
79 
80 void
tls_crypt_init_key(struct key_ctx_bi * key,const char * key_file,bool key_inline,bool tls_server)81 tls_crypt_init_key(struct key_ctx_bi *key, const char *key_file,
82                    bool key_inline, bool tls_server)
83 {
84     const int key_direction = tls_server ?
85                               KEY_DIRECTION_NORMAL : KEY_DIRECTION_INVERSE;
86     struct key_type kt = tls_crypt_kt();
87     if (!kt.cipher || !kt.digest)
88     {
89         msg(M_FATAL, "ERROR: --tls-crypt not supported");
90     }
91     crypto_read_openvpn_key(&kt, key, key_file, key_inline, key_direction,
92                             "Control Channel Encryption", "tls-crypt");
93 }
94 
95 void
tls_crypt_adjust_frame_parameters(struct frame * frame)96 tls_crypt_adjust_frame_parameters(struct frame *frame)
97 {
98     frame_add_to_extra_frame(frame, tls_crypt_buf_overhead());
99 
100     msg(D_MTU_DEBUG, "%s: Adjusting frame parameters for tls-crypt by %i bytes",
101         __func__, tls_crypt_buf_overhead());
102 }
103 
104 
105 bool
tls_crypt_wrap(const struct buffer * src,struct buffer * dst,struct crypto_options * opt)106 tls_crypt_wrap(const struct buffer *src, struct buffer *dst,
107                struct crypto_options *opt)
108 {
109     const struct key_ctx *ctx = &opt->key_ctx_bi.encrypt;
110     struct gc_arena gc;
111 
112     /* IV, packet-ID and implicit IV required for this mode. */
113     ASSERT(ctx->cipher);
114     ASSERT(ctx->hmac);
115     ASSERT(packet_id_initialized(&opt->packet_id));
116     ASSERT(hmac_ctx_size(ctx->hmac) == 256/8);
117 
118     gc_init(&gc);
119 
120     dmsg(D_PACKET_CONTENT, "TLS-CRYPT WRAP FROM: %s",
121          format_hex(BPTR(src), BLEN(src), 80, &gc));
122 
123     /* Get packet ID */
124     if (!packet_id_write(&opt->packet_id.send, dst, true, false))
125     {
126         msg(D_CRYPT_ERRORS, "TLS-CRYPT ERROR: packet ID roll over.");
127         goto err;
128     }
129 
130     dmsg(D_PACKET_CONTENT, "TLS-CRYPT WRAP AD: %s",
131          format_hex(BPTR(dst), BLEN(dst), 0, &gc));
132 
133     /* Buffer overflow check */
134     if (!buf_safe(dst, BLEN(src) + TLS_CRYPT_BLOCK_SIZE + TLS_CRYPT_TAG_SIZE))
135     {
136         msg(D_CRYPT_ERRORS, "TLS-CRYPT WRAP: buffer size error, "
137             "sc=%d so=%d sl=%d dc=%d do=%d dl=%d", src->capacity, src->offset,
138             src->len, dst->capacity, dst->offset, dst->len);
139         goto err;
140     }
141 
142     /* Calculate auth tag and synthetic IV */
143     {
144         uint8_t *tag = NULL;
145         hmac_ctx_reset(ctx->hmac);
146         hmac_ctx_update(ctx->hmac, BPTR(dst), BLEN(dst));
147         hmac_ctx_update(ctx->hmac, BPTR(src), BLEN(src));
148 
149         ASSERT(tag = buf_write_alloc(dst, TLS_CRYPT_TAG_SIZE));
150         hmac_ctx_final(ctx->hmac, tag);
151 
152         dmsg(D_PACKET_CONTENT, "TLS-CRYPT WRAP TAG: %s",
153              format_hex(tag, TLS_CRYPT_TAG_SIZE, 0, &gc));
154 
155         /* Use the 128 most significant bits of the tag as IV */
156         ASSERT(cipher_ctx_reset(ctx->cipher, tag));
157     }
158 
159     /* Encrypt src */
160     {
161         int outlen = 0;
162         ASSERT(cipher_ctx_update(ctx->cipher, BEND(dst), &outlen,
163                                  BPTR(src), BLEN(src)));
164         ASSERT(buf_inc_len(dst, outlen));
165         ASSERT(cipher_ctx_final(ctx->cipher, BPTR(dst), &outlen));
166         ASSERT(buf_inc_len(dst, outlen));
167     }
168 
169     dmsg(D_PACKET_CONTENT, "TLS-CRYPT WRAP TO: %s",
170          format_hex(BPTR(dst), BLEN(dst), 80, &gc));
171 
172     gc_free(&gc);
173     return true;
174 
175 err:
176     crypto_clear_error();
177     dst->len = 0;
178     gc_free(&gc);
179     return false;
180 }
181 
182 bool
tls_crypt_unwrap(const struct buffer * src,struct buffer * dst,struct crypto_options * opt)183 tls_crypt_unwrap(const struct buffer *src, struct buffer *dst,
184                  struct crypto_options *opt)
185 {
186     static const char error_prefix[] = "tls-crypt unwrap error";
187     const struct key_ctx *ctx = &opt->key_ctx_bi.decrypt;
188     struct gc_arena gc;
189 
190     gc_init(&gc);
191 
192     ASSERT(opt);
193     ASSERT(src->len > 0);
194     ASSERT(ctx->cipher);
195     ASSERT(packet_id_initialized(&opt->packet_id)
196            || (opt->flags & CO_IGNORE_PACKET_ID));
197 
198     dmsg(D_PACKET_CONTENT, "TLS-CRYPT UNWRAP FROM: %s",
199          format_hex(BPTR(src), BLEN(src), 80, &gc));
200 
201     if (buf_len(src) < TLS_CRYPT_OFF_CT)
202     {
203         CRYPT_ERROR("packet too short");
204     }
205 
206     /* Decrypt cipher text */
207     {
208         int outlen = 0;
209 
210         /* Buffer overflow check (should never fail) */
211         if (!buf_safe(dst, BLEN(src) - TLS_CRYPT_OFF_CT + TLS_CRYPT_BLOCK_SIZE))
212         {
213             CRYPT_ERROR("potential buffer overflow");
214         }
215 
216         if (!cipher_ctx_reset(ctx->cipher, BPTR(src) + TLS_CRYPT_OFF_TAG))
217         {
218             CRYPT_ERROR("cipher reset failed");
219         }
220         if (!cipher_ctx_update(ctx->cipher, BPTR(dst), &outlen,
221                                BPTR(src) + TLS_CRYPT_OFF_CT, BLEN(src) - TLS_CRYPT_OFF_CT))
222         {
223             CRYPT_ERROR("cipher update failed");
224         }
225         ASSERT(buf_inc_len(dst, outlen));
226         if (!cipher_ctx_final(ctx->cipher, BPTR(dst), &outlen))
227         {
228             CRYPT_ERROR("cipher final failed");
229         }
230         ASSERT(buf_inc_len(dst, outlen));
231     }
232 
233     /* Check authentication */
234     {
235         const uint8_t *tag = BPTR(src) + TLS_CRYPT_OFF_TAG;
236         uint8_t tag_check[TLS_CRYPT_TAG_SIZE] = { 0 };
237 
238         dmsg(D_PACKET_CONTENT, "TLS-CRYPT UNWRAP AD: %s",
239              format_hex(BPTR(src), TLS_CRYPT_OFF_TAG, 0, &gc));
240         dmsg(D_PACKET_CONTENT, "TLS-CRYPT UNWRAP TO: %s",
241              format_hex(BPTR(dst), BLEN(dst), 80, &gc));
242 
243         hmac_ctx_reset(ctx->hmac);
244         hmac_ctx_update(ctx->hmac, BPTR(src), TLS_CRYPT_OFF_TAG);
245         hmac_ctx_update(ctx->hmac, BPTR(dst), BLEN(dst));
246         hmac_ctx_final(ctx->hmac, tag_check);
247 
248         if (memcmp_constant_time(tag, tag_check, sizeof(tag_check)))
249         {
250             dmsg(D_CRYPTO_DEBUG, "tag      : %s",
251                  format_hex(tag, sizeof(tag_check), 0, &gc));
252             dmsg(D_CRYPTO_DEBUG, "tag_check: %s",
253                  format_hex(tag_check, sizeof(tag_check), 0, &gc));
254             CRYPT_ERROR("packet authentication failed");
255         }
256     }
257 
258     /* Check replay */
259     if (!(opt->flags & CO_IGNORE_PACKET_ID))
260     {
261         struct packet_id_net pin;
262         struct buffer tmp = *src;
263         ASSERT(buf_advance(&tmp, TLS_CRYPT_OFF_PID));
264         ASSERT(packet_id_read(&pin, &tmp, true));
265         if (!crypto_check_replay(opt, &pin, error_prefix, &gc))
266         {
267             CRYPT_ERROR("packet replay");
268         }
269     }
270 
271     gc_free(&gc);
272     return true;
273 
274 error_exit:
275     crypto_clear_error();
276     dst->len = 0;
277     gc_free(&gc);
278     return false;
279 }
280 
281 static inline void
tls_crypt_v2_load_client_key(struct key_ctx_bi * key,const struct key2 * key2,bool tls_server)282 tls_crypt_v2_load_client_key(struct key_ctx_bi *key, const struct key2 *key2,
283                              bool tls_server)
284 {
285     const int key_direction = tls_server ?
286                               KEY_DIRECTION_NORMAL : KEY_DIRECTION_INVERSE;
287     struct key_type kt = tls_crypt_kt();
288     if (!kt.cipher || !kt.digest)
289     {
290         msg(M_FATAL, "ERROR: --tls-crypt-v2 not supported");
291     }
292     init_key_ctx_bi(key, key2, key_direction, &kt,
293                     "Control Channel Encryption");
294 }
295 
296 void
tls_crypt_v2_init_client_key(struct key_ctx_bi * key,struct buffer * wkc_buf,const char * key_file,bool key_inline)297 tls_crypt_v2_init_client_key(struct key_ctx_bi *key, struct buffer *wkc_buf,
298                              const char *key_file, bool key_inline)
299 {
300     struct buffer client_key = alloc_buf(TLS_CRYPT_V2_CLIENT_KEY_LEN
301                                          + TLS_CRYPT_V2_MAX_WKC_LEN);
302 
303     if (!read_pem_key_file(&client_key, tls_crypt_v2_cli_pem_name,
304                            key_file, key_inline))
305     {
306         msg(M_FATAL, "ERROR: invalid tls-crypt-v2 client key format");
307     }
308 
309     struct key2 key2;
310     if (!buf_read(&client_key, &key2.keys, sizeof(key2.keys)))
311     {
312         msg(M_FATAL, "ERROR: not enough data in tls-crypt-v2 client key");
313     }
314 
315     tls_crypt_v2_load_client_key(key, &key2, false);
316     secure_memzero(&key2, sizeof(key2));
317 
318     *wkc_buf = client_key;
319 }
320 
321 void
tls_crypt_v2_init_server_key(struct key_ctx * key_ctx,bool encrypt,const char * key_file,bool key_inline)322 tls_crypt_v2_init_server_key(struct key_ctx *key_ctx, bool encrypt,
323                              const char *key_file, bool key_inline)
324 {
325     struct key srv_key;
326     struct buffer srv_key_buf;
327 
328     buf_set_write(&srv_key_buf, (void *)&srv_key, sizeof(srv_key));
329     if (!read_pem_key_file(&srv_key_buf, tls_crypt_v2_srv_pem_name,
330                            key_file, key_inline))
331     {
332         msg(M_FATAL, "ERROR: invalid tls-crypt-v2 server key format");
333     }
334 
335     struct key_type kt = tls_crypt_kt();
336     if (!kt.cipher || !kt.digest)
337     {
338         msg(M_FATAL, "ERROR: --tls-crypt-v2 not supported");
339     }
340     init_key_ctx(key_ctx, &srv_key, &kt, encrypt, "tls-crypt-v2 server key");
341     secure_memzero(&srv_key, sizeof(srv_key));
342 }
343 
344 static bool
tls_crypt_v2_wrap_client_key(struct buffer * wkc,const struct key2 * src_key,const struct buffer * src_metadata,struct key_ctx * server_key,struct gc_arena * gc)345 tls_crypt_v2_wrap_client_key(struct buffer *wkc,
346                              const struct key2 *src_key,
347                              const struct buffer *src_metadata,
348                              struct key_ctx *server_key, struct gc_arena *gc)
349 {
350     cipher_ctx_t *cipher_ctx = server_key->cipher;
351     struct buffer work = alloc_buf_gc(TLS_CRYPT_V2_MAX_WKC_LEN
352                                       + cipher_ctx_block_size(cipher_ctx), gc);
353 
354     /* Calculate auth tag and synthetic IV */
355     uint8_t *tag = buf_write_alloc(&work, TLS_CRYPT_TAG_SIZE);
356     if (!tag)
357     {
358         msg(M_WARN, "ERROR: could not write tag");
359         return false;
360     }
361     uint16_t net_len = htons(sizeof(src_key->keys) + BLEN(src_metadata)
362                              + TLS_CRYPT_V2_TAG_SIZE + sizeof(uint16_t));
363     hmac_ctx_t *hmac_ctx = server_key->hmac;
364     hmac_ctx_reset(hmac_ctx);
365     hmac_ctx_update(hmac_ctx, (void *)&net_len, sizeof(net_len));
366     hmac_ctx_update(hmac_ctx, (void *)src_key->keys, sizeof(src_key->keys));
367     hmac_ctx_update(hmac_ctx, BPTR(src_metadata), BLEN(src_metadata));
368     hmac_ctx_final(hmac_ctx, tag);
369 
370     dmsg(D_CRYPTO_DEBUG, "TLS-CRYPT WRAP TAG: %s",
371          format_hex(tag, TLS_CRYPT_TAG_SIZE, 0, gc));
372 
373     /* Use the 128 most significant bits of the tag as IV */
374     ASSERT(cipher_ctx_reset(cipher_ctx, tag));
375 
376     /* Overflow check (OpenSSL requires an extra block in the dst buffer) */
377     if (buf_forward_capacity(&work) < (sizeof(src_key->keys)
378                                        + BLEN(src_metadata)
379                                        + sizeof(net_len)
380                                        + cipher_ctx_block_size(cipher_ctx)))
381     {
382         msg(M_WARN, "ERROR: could not crypt: insufficient space in dst");
383         return false;
384     }
385 
386     /* Encrypt */
387     int outlen = 0;
388     ASSERT(cipher_ctx_update(cipher_ctx, BEND(&work), &outlen,
389                              (void *)src_key->keys, sizeof(src_key->keys)));
390     ASSERT(buf_inc_len(&work, outlen));
391     ASSERT(cipher_ctx_update(cipher_ctx, BEND(&work), &outlen,
392                              BPTR(src_metadata), BLEN(src_metadata)));
393     ASSERT(buf_inc_len(&work, outlen));
394     ASSERT(cipher_ctx_final(cipher_ctx, BEND(&work), &outlen));
395     ASSERT(buf_inc_len(&work, outlen));
396     ASSERT(buf_write(&work, &net_len, sizeof(net_len)));
397 
398     return buf_copy(wkc, &work);
399 }
400 
401 static bool
tls_crypt_v2_unwrap_client_key(struct key2 * client_key,struct buffer * metadata,struct buffer wrapped_client_key,struct key_ctx * server_key)402 tls_crypt_v2_unwrap_client_key(struct key2 *client_key, struct buffer *metadata,
403                                struct buffer wrapped_client_key,
404                                struct key_ctx *server_key)
405 {
406     const char *error_prefix = __func__;
407     bool ret = false;
408     struct gc_arena gc = gc_new();
409     /* The crypto API requires one extra cipher block of buffer head room when
410      * decrypting, which nicely matches the tag size of WKc.  So
411      * TLS_CRYPT_V2_MAX_WKC_LEN is always large enough for the plaintext. */
412     uint8_t plaintext_buf_data[TLS_CRYPT_V2_MAX_WKC_LEN] = { 0 };
413     struct buffer plaintext = { 0 };
414 
415     dmsg(D_TLS_DEBUG_MED, "%s: unwrapping client key (len=%d): %s", __func__,
416          BLEN(&wrapped_client_key), format_hex(BPTR(&wrapped_client_key),
417                                                BLEN(&wrapped_client_key),
418                                                0, &gc));
419 
420     if (TLS_CRYPT_V2_MAX_WKC_LEN < BLEN(&wrapped_client_key))
421     {
422         CRYPT_ERROR("wrapped client key too big");
423     }
424 
425     /* Decrypt client key and metadata */
426     uint16_t net_len = 0;
427     const uint8_t *tag = BPTR(&wrapped_client_key);
428 
429     if (BLEN(&wrapped_client_key) < sizeof(net_len))
430     {
431         CRYPT_ERROR("failed to read length");
432     }
433     memcpy(&net_len, BEND(&wrapped_client_key) - sizeof(net_len),
434            sizeof(net_len));
435 
436     if (ntohs(net_len) != BLEN(&wrapped_client_key))
437     {
438         dmsg(D_TLS_DEBUG_LOW, "%s: net_len=%u, BLEN=%i", __func__,
439              ntohs(net_len), BLEN(&wrapped_client_key));
440         CRYPT_ERROR("invalid length");
441     }
442 
443     buf_inc_len(&wrapped_client_key, -(int)sizeof(net_len));
444 
445     if (!buf_advance(&wrapped_client_key, TLS_CRYPT_TAG_SIZE))
446     {
447         CRYPT_ERROR("failed to read tag");
448     }
449 
450     if (!cipher_ctx_reset(server_key->cipher, tag))
451     {
452         CRYPT_ERROR("failed to initialize IV");
453     }
454     buf_set_write(&plaintext, plaintext_buf_data, sizeof(plaintext_buf_data));
455     int outlen = 0;
456     if (!cipher_ctx_update(server_key->cipher, BPTR(&plaintext), &outlen,
457                            BPTR(&wrapped_client_key),
458                            BLEN(&wrapped_client_key)))
459     {
460         CRYPT_ERROR("could not decrypt client key");
461     }
462     ASSERT(buf_inc_len(&plaintext, outlen));
463 
464     if (!cipher_ctx_final(server_key->cipher, BEND(&plaintext), &outlen))
465     {
466         CRYPT_ERROR("cipher final failed");
467     }
468     ASSERT(buf_inc_len(&plaintext, outlen));
469 
470     /* Check authentication */
471     uint8_t tag_check[TLS_CRYPT_TAG_SIZE] = { 0 };
472     hmac_ctx_reset(server_key->hmac);
473     hmac_ctx_update(server_key->hmac, (void *)&net_len, sizeof(net_len));
474     hmac_ctx_update(server_key->hmac, BPTR(&plaintext),
475                     BLEN(&plaintext));
476     hmac_ctx_final(server_key->hmac, tag_check);
477 
478     if (memcmp_constant_time(tag, tag_check, sizeof(tag_check)))
479     {
480         dmsg(D_CRYPTO_DEBUG, "tag      : %s",
481              format_hex(tag, sizeof(tag_check), 0, &gc));
482         dmsg(D_CRYPTO_DEBUG, "tag_check: %s",
483              format_hex(tag_check, sizeof(tag_check), 0, &gc));
484         CRYPT_ERROR("client key authentication error");
485     }
486 
487     if (buf_len(&plaintext) < sizeof(client_key->keys))
488     {
489         CRYPT_ERROR("failed to read client key");
490     }
491     memcpy(&client_key->keys, BPTR(&plaintext), sizeof(client_key->keys));
492     ASSERT(buf_advance(&plaintext, sizeof(client_key->keys)));
493 
494     if (!buf_copy(metadata, &plaintext))
495     {
496         CRYPT_ERROR("metadata too large for supplied buffer");
497     }
498 
499     ret = true;
500 error_exit:
501     if (!ret)
502     {
503         secure_memzero(client_key, sizeof(*client_key));
504     }
505     buf_clear(&plaintext);
506     gc_free(&gc);
507     return ret;
508 }
509 
510 static bool
tls_crypt_v2_verify_metadata(const struct tls_wrap_ctx * ctx,const struct tls_options * opt)511 tls_crypt_v2_verify_metadata(const struct tls_wrap_ctx *ctx,
512                              const struct tls_options *opt)
513 {
514     bool ret = false;
515     struct gc_arena gc = gc_new();
516     const char *tmp_file = NULL;
517     struct buffer metadata = ctx->tls_crypt_v2_metadata;
518     int metadata_type = buf_read_u8(&metadata);
519     if (metadata_type < 0)
520     {
521         msg(M_WARN, "ERROR: no metadata type");
522         goto cleanup;
523     }
524 
525     tmp_file = platform_create_temp_file(opt->tmp_dir, "tls_crypt_v2_metadata_",
526                                          &gc);
527     if (!tmp_file || !buffer_write_file(tmp_file, &metadata))
528     {
529         msg(M_WARN, "ERROR: could not write metadata to file");
530         goto cleanup;
531     }
532 
533     char metadata_type_str[4] = { 0 }; /* Max value: 255 */
534     openvpn_snprintf(metadata_type_str, sizeof(metadata_type_str),
535                      "%i", metadata_type);
536     struct env_set *es = env_set_create(NULL);
537     setenv_str(es, "script_type", "tls-crypt-v2-verify");
538     setenv_str(es, "metadata_type", metadata_type_str);
539     setenv_str(es, "metadata_file", tmp_file);
540 
541     struct argv argv = argv_new();
542     argv_parse_cmd(&argv, opt->tls_crypt_v2_verify_script);
543     argv_msg_prefix(D_TLS_DEBUG, &argv, "Executing tls-crypt-v2-verify");
544 
545     ret = openvpn_run_script(&argv, es, 0, "--tls-crypt-v2-verify");
546 
547     argv_free(&argv);
548     env_set_destroy(es);
549 
550     if (!platform_unlink(tmp_file))
551     {
552         msg(M_WARN, "WARNING: failed to remove temp file '%s", tmp_file);
553     }
554 
555     if (ret)
556     {
557         msg(D_HANDSHAKE, "TLS CRYPT V2 VERIFY SCRIPT OK");
558     }
559     else
560     {
561         msg(D_HANDSHAKE, "TLS CRYPT V2 VERIFY SCRIPT ERROR");
562     }
563 
564 cleanup:
565     gc_free(&gc);
566     return ret;
567 }
568 
569 bool
tls_crypt_v2_extract_client_key(struct buffer * buf,struct tls_wrap_ctx * ctx,const struct tls_options * opt)570 tls_crypt_v2_extract_client_key(struct buffer *buf,
571                                 struct tls_wrap_ctx *ctx,
572                                 const struct tls_options *opt)
573 {
574     if (!ctx->tls_crypt_v2_server_key.cipher)
575     {
576         msg(D_TLS_ERRORS,
577             "Client wants tls-crypt-v2, but no server key present.");
578         return false;
579     }
580 
581     msg(D_HANDSHAKE, "Control Channel: using tls-crypt-v2 key");
582 
583     struct buffer wrapped_client_key = *buf;
584     uint16_t net_len = 0;
585 
586     if (BLEN(&wrapped_client_key) < sizeof(net_len))
587     {
588         msg(D_TLS_ERRORS, "failed to read length");
589     }
590     memcpy(&net_len, BEND(&wrapped_client_key) - sizeof(net_len),
591            sizeof(net_len));
592 
593     size_t wkc_len = ntohs(net_len);
594     if (!buf_advance(&wrapped_client_key, BLEN(&wrapped_client_key) - wkc_len))
595     {
596         msg(D_TLS_ERRORS, "Can not locate tls-crypt-v2 client key");
597         return false;
598     }
599 
600     struct key2 client_key = { 0 };
601     ctx->tls_crypt_v2_metadata = alloc_buf(TLS_CRYPT_V2_MAX_METADATA_LEN);
602     if (!tls_crypt_v2_unwrap_client_key(&client_key,
603                                         &ctx->tls_crypt_v2_metadata,
604                                         wrapped_client_key,
605                                         &ctx->tls_crypt_v2_server_key))
606     {
607         msg(D_TLS_ERRORS, "Can not unwrap tls-crypt-v2 client key");
608         secure_memzero(&client_key, sizeof(client_key));
609         return false;
610     }
611 
612     /* Load the decrypted key */
613     ctx->mode = TLS_WRAP_CRYPT;
614     ctx->cleanup_key_ctx = true;
615     ctx->opt.flags |= CO_PACKET_ID_LONG_FORM;
616     memset(&ctx->opt.key_ctx_bi, 0, sizeof(ctx->opt.key_ctx_bi));
617     tls_crypt_v2_load_client_key(&ctx->opt.key_ctx_bi, &client_key, true);
618     secure_memzero(&client_key, sizeof(client_key));
619 
620     /* Remove client key from buffer so tls-crypt code can unwrap message */
621     ASSERT(buf_inc_len(buf, -(BLEN(&wrapped_client_key))));
622 
623     if (opt && opt->tls_crypt_v2_verify_script)
624     {
625         return tls_crypt_v2_verify_metadata(ctx, opt);
626     }
627 
628     return true;
629 }
630 
631 void
tls_crypt_v2_write_server_key_file(const char * filename)632 tls_crypt_v2_write_server_key_file(const char *filename)
633 {
634     write_pem_key_file(filename, tls_crypt_v2_srv_pem_name);
635 }
636 
637 void
tls_crypt_v2_write_client_key_file(const char * filename,const char * b64_metadata,const char * server_key_file,bool server_key_inline)638 tls_crypt_v2_write_client_key_file(const char *filename,
639                                    const char *b64_metadata,
640                                    const char *server_key_file,
641                                    bool server_key_inline)
642 {
643     struct gc_arena gc = gc_new();
644     struct key_ctx server_key = { 0 };
645     struct buffer client_key_pem = { 0 };
646     struct buffer dst = alloc_buf_gc(TLS_CRYPT_V2_CLIENT_KEY_LEN
647                                      + TLS_CRYPT_V2_MAX_WKC_LEN, &gc);
648     struct key2 client_key = { 2 };
649 
650     if (!rand_bytes((void *)client_key.keys, sizeof(client_key.keys)))
651     {
652         msg(M_FATAL, "ERROR: could not generate random key");
653         goto cleanup;
654     }
655     ASSERT(buf_write(&dst, client_key.keys, sizeof(client_key.keys)));
656 
657     struct buffer metadata = alloc_buf_gc(TLS_CRYPT_V2_MAX_METADATA_LEN, &gc);
658     if (b64_metadata)
659     {
660         if (TLS_CRYPT_V2_MAX_B64_METADATA_LEN < strlen(b64_metadata))
661         {
662             msg(M_FATAL,
663                 "ERROR: metadata too long (%d bytes, max %u bytes)",
664                 (int)strlen(b64_metadata), TLS_CRYPT_V2_MAX_B64_METADATA_LEN);
665         }
666         ASSERT(buf_write(&metadata, &TLS_CRYPT_METADATA_TYPE_USER, 1));
667         int decoded_len = openvpn_base64_decode(b64_metadata, BEND(&metadata),
668                                                 BCAP(&metadata));
669         if (decoded_len < 0)
670         {
671             msg(M_FATAL, "ERROR: failed to base64 decode provided metadata");
672             goto cleanup;
673         }
674         ASSERT(buf_inc_len(&metadata, decoded_len));
675     }
676     else
677     {
678         int64_t timestamp = htonll((uint64_t)now);
679         ASSERT(buf_write(&metadata, &TLS_CRYPT_METADATA_TYPE_TIMESTAMP, 1));
680         ASSERT(buf_write(&metadata, &timestamp, sizeof(timestamp)));
681     }
682 
683     tls_crypt_v2_init_server_key(&server_key, true, server_key_file,
684                                  server_key_inline);
685     if (!tls_crypt_v2_wrap_client_key(&dst, &client_key, &metadata, &server_key,
686                                       &gc))
687     {
688         msg(M_FATAL, "ERROR: could not wrap generated client key");
689         goto cleanup;
690     }
691 
692     /* PEM-encode Kc || WKc */
693     if (!crypto_pem_encode(tls_crypt_v2_cli_pem_name, &client_key_pem, &dst,
694                            &gc))
695     {
696         msg(M_FATAL, "ERROR: could not PEM-encode client key");
697         goto cleanup;
698     }
699 
700     const char *client_file = filename;
701     bool client_inline = false;
702 
703     if (!filename || streq(filename, ""))
704     {
705         printf("%.*s\n", BLEN(&client_key_pem), BPTR(&client_key_pem));
706         client_file = (const char *)BPTR(&client_key_pem);
707         client_inline = true;
708     }
709     else if (!buffer_write_file(filename, &client_key_pem))
710     {
711         msg(M_FATAL, "ERROR: could not write client key file");
712         goto cleanup;
713     }
714 
715     /* Sanity check: load client key (as "client") */
716     struct key_ctx_bi test_client_key;
717     struct buffer test_wrapped_client_key;
718     msg(D_GENKEY, "Testing client-side key loading...");
719     tls_crypt_v2_init_client_key(&test_client_key, &test_wrapped_client_key,
720                                  client_file, client_inline);
721     free_key_ctx_bi(&test_client_key);
722 
723     /* Sanity check: unwrap and load client key (as "server") */
724     struct buffer test_metadata = alloc_buf_gc(TLS_CRYPT_V2_MAX_METADATA_LEN,
725                                                &gc);
726     struct key2 test_client_key2 = { 0 };
727     free_key_ctx(&server_key);
728     tls_crypt_v2_init_server_key(&server_key, false, server_key_file,
729                                  server_key_inline);
730     msg(D_GENKEY, "Testing server-side key loading...");
731     ASSERT(tls_crypt_v2_unwrap_client_key(&test_client_key2, &test_metadata,
732                                           test_wrapped_client_key, &server_key));
733     secure_memzero(&test_client_key2, sizeof(test_client_key2));
734     free_buf(&test_wrapped_client_key);
735 
736 cleanup:
737     secure_memzero(&client_key, sizeof(client_key));
738     free_key_ctx(&server_key);
739     buf_clear(&client_key_pem);
740     buf_clear(&dst);
741 
742     gc_free(&gc);
743 }
744