OpenVPN
ssl.c
Go to the documentation of this file.
1 /*
2  * OpenVPN -- An application to securely tunnel IP networks
3  * over a single TCP/UDP port, with support for SSL/TLS-based
4  * session authentication and key exchange,
5  * packet encryption, packet authentication, and
6  * packet compression.
7  *
8  * Copyright (C) 2002-2018 OpenVPN Inc <sales@openvpn.net>
9  * Copyright (C) 2010-2018 Fox Crypto B.V. <openvpn@fox-it.com>
10  * Copyright (C) 2008-2013 David Sommerseth <dazo@users.sourceforge.net>
11  *
12  * This program is free software; you can redistribute it and/or modify
13  * it under the terms of the GNU General Public License version 2
14  * as published by the Free Software Foundation.
15  *
16  * This program is distributed in the hope that it will be useful,
17  * but WITHOUT ANY WARRANTY; without even the implied warranty of
18  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19  * GNU General Public License for more details.
20  *
21  * You should have received a copy of the GNU General Public License along
22  * with this program; if not, write to the Free Software Foundation, Inc.,
23  * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
24  */
25 
30 /*
31  * The routines in this file deal with dynamically negotiating
32  * the data channel HMAC and cipher keys through a TLS session.
33  *
34  * Both the TLS session and the data channel are multiplexed
35  * over the same TCP/UDP port.
36  */
37 #ifdef HAVE_CONFIG_H
38 #include "config.h"
39 #elif defined(_MSC_VER)
40 #include "config-msvc.h"
41 #endif
42 
43 #include "syshead.h"
44 #include "win32.h"
45 
46 #include "error.h"
47 #include "common.h"
48 #include "socket.h"
49 #include "misc.h"
50 #include "fdmisc.h"
51 #include "interval.h"
52 #include "perf.h"
53 #include "status.h"
54 #include "gremlin.h"
55 #include "pkcs11.h"
56 #include "route.h"
57 #include "tls_crypt.h"
58 
59 #include "ssl.h"
60 #include "ssl_verify.h"
61 #include "ssl_backend.h"
62 
63 #include "memdbg.h"
64 
65 #ifndef ENABLE_OCC
66 static const char ssl_default_options_string[] = "V0 UNDEF";
67 #endif
68 
69 static inline const char *
71 {
72 #ifdef ENABLE_OCC
73  return session->opt->local_options;
74 #else
75  return ssl_default_options_string;
76 #endif
77 }
78 
79 #ifdef MEASURE_TLS_HANDSHAKE_STATS
80 
81 static int tls_handshake_success; /* GLOBAL */
82 static int tls_handshake_error; /* GLOBAL */
83 static int tls_packets_generated; /* GLOBAL */
84 static int tls_packets_sent; /* GLOBAL */
85 
86 #define INCR_SENT ++tls_packets_sent
87 #define INCR_GENERATED ++tls_packets_generated
88 #define INCR_SUCCESS ++tls_handshake_success
89 #define INCR_ERROR ++tls_handshake_error
90 
91 void
92 show_tls_performance_stats(void)
93 {
94  msg(D_TLS_DEBUG_LOW, "TLS Handshakes, success=%f%% (good=%d, bad=%d), retransmits=%f%%",
95  (double) tls_handshake_success / (tls_handshake_success + tls_handshake_error) * 100.0,
96  tls_handshake_success, tls_handshake_error,
97  (double) (tls_packets_sent - tls_packets_generated) / tls_packets_generated * 100.0);
98 }
99 #else /* ifdef MEASURE_TLS_HANDSHAKE_STATS */
100 
101 #define INCR_SENT
102 #define INCR_GENERATED
103 #define INCR_SUCCESS
104 #define INCR_ERROR
105 
106 #endif /* ifdef MEASURE_TLS_HANDSHAKE_STATS */
107 
112  {"ADH-SEED-SHA", "TLS-DH-anon-WITH-SEED-CBC-SHA"},
113  {"AES128-GCM-SHA256", "TLS-RSA-WITH-AES-128-GCM-SHA256"},
114  {"AES128-SHA256", "TLS-RSA-WITH-AES-128-CBC-SHA256"},
115  {"AES128-SHA", "TLS-RSA-WITH-AES-128-CBC-SHA"},
116  {"AES256-GCM-SHA384", "TLS-RSA-WITH-AES-256-GCM-SHA384"},
117  {"AES256-SHA256", "TLS-RSA-WITH-AES-256-CBC-SHA256"},
118  {"AES256-SHA", "TLS-RSA-WITH-AES-256-CBC-SHA"},
119  {"CAMELLIA128-SHA256", "TLS-RSA-WITH-CAMELLIA-128-CBC-SHA256"},
120  {"CAMELLIA128-SHA", "TLS-RSA-WITH-CAMELLIA-128-CBC-SHA"},
121  {"CAMELLIA256-SHA256", "TLS-RSA-WITH-CAMELLIA-256-CBC-SHA256"},
122  {"CAMELLIA256-SHA", "TLS-RSA-WITH-CAMELLIA-256-CBC-SHA"},
123  {"DES-CBC3-SHA", "TLS-RSA-WITH-3DES-EDE-CBC-SHA"},
124  {"DES-CBC-SHA", "TLS-RSA-WITH-DES-CBC-SHA"},
125  {"DH-DSS-SEED-SHA", "TLS-DH-DSS-WITH-SEED-CBC-SHA"},
126  {"DHE-DSS-AES128-GCM-SHA256", "TLS-DHE-DSS-WITH-AES-128-GCM-SHA256"},
127  {"DHE-DSS-AES128-SHA256", "TLS-DHE-DSS-WITH-AES-128-CBC-SHA256"},
128  {"DHE-DSS-AES128-SHA", "TLS-DHE-DSS-WITH-AES-128-CBC-SHA"},
129  {"DHE-DSS-AES256-GCM-SHA384", "TLS-DHE-DSS-WITH-AES-256-GCM-SHA384"},
130  {"DHE-DSS-AES256-SHA256", "TLS-DHE-DSS-WITH-AES-256-CBC-SHA256"},
131  {"DHE-DSS-AES256-SHA", "TLS-DHE-DSS-WITH-AES-256-CBC-SHA"},
132  {"DHE-DSS-CAMELLIA128-SHA256", "TLS-DHE-DSS-WITH-CAMELLIA-128-CBC-SHA256"},
133  {"DHE-DSS-CAMELLIA128-SHA", "TLS-DHE-DSS-WITH-CAMELLIA-128-CBC-SHA"},
134  {"DHE-DSS-CAMELLIA256-SHA256", "TLS-DHE-DSS-WITH-CAMELLIA-256-CBC-SHA256"},
135  {"DHE-DSS-CAMELLIA256-SHA", "TLS-DHE-DSS-WITH-CAMELLIA-256-CBC-SHA"},
136  {"DHE-DSS-SEED-SHA", "TLS-DHE-DSS-WITH-SEED-CBC-SHA"},
137  {"DHE-RSA-AES128-GCM-SHA256", "TLS-DHE-RSA-WITH-AES-128-GCM-SHA256"},
138  {"DHE-RSA-AES128-SHA256", "TLS-DHE-RSA-WITH-AES-128-CBC-SHA256"},
139  {"DHE-RSA-AES128-SHA", "TLS-DHE-RSA-WITH-AES-128-CBC-SHA"},
140  {"DHE-RSA-AES256-GCM-SHA384", "TLS-DHE-RSA-WITH-AES-256-GCM-SHA384"},
141  {"DHE-RSA-AES256-SHA256", "TLS-DHE-RSA-WITH-AES-256-CBC-SHA256"},
142  {"DHE-RSA-AES256-SHA", "TLS-DHE-RSA-WITH-AES-256-CBC-SHA"},
143  {"DHE-RSA-CAMELLIA128-SHA256", "TLS-DHE-RSA-WITH-CAMELLIA-128-CBC-SHA256"},
144  {"DHE-RSA-CAMELLIA128-SHA", "TLS-DHE-RSA-WITH-CAMELLIA-128-CBC-SHA"},
145  {"DHE-RSA-CAMELLIA256-SHA256", "TLS-DHE-RSA-WITH-CAMELLIA-256-CBC-SHA256"},
146  {"DHE-RSA-CAMELLIA256-SHA", "TLS-DHE-RSA-WITH-CAMELLIA-256-CBC-SHA"},
147  {"DHE-RSA-CHACHA20-POLY1305", "TLS-DHE-RSA-WITH-CHACHA20-POLY1305-SHA256"},
148  {"DHE-RSA-SEED-SHA", "TLS-DHE-RSA-WITH-SEED-CBC-SHA"},
149  {"DH-RSA-SEED-SHA", "TLS-DH-RSA-WITH-SEED-CBC-SHA"},
150  {"ECDH-ECDSA-AES128-GCM-SHA256", "TLS-ECDH-ECDSA-WITH-AES-128-GCM-SHA256"},
151  {"ECDH-ECDSA-AES128-SHA256", "TLS-ECDH-ECDSA-WITH-AES-128-CBC-SHA256"},
152  {"ECDH-ECDSA-AES128-SHA", "TLS-ECDH-ECDSA-WITH-AES-128-CBC-SHA"},
153  {"ECDH-ECDSA-AES256-GCM-SHA384", "TLS-ECDH-ECDSA-WITH-AES-256-GCM-SHA384"},
154  {"ECDH-ECDSA-AES256-SHA256", "TLS-ECDH-ECDSA-WITH-AES-256-CBC-SHA256"},
155  {"ECDH-ECDSA-AES256-SHA384", "TLS-ECDH-ECDSA-WITH-AES-256-CBC-SHA384"},
156  {"ECDH-ECDSA-AES256-SHA", "TLS-ECDH-ECDSA-WITH-AES-256-CBC-SHA"},
157  {"ECDH-ECDSA-CAMELLIA128-SHA256", "TLS-ECDH-ECDSA-WITH-CAMELLIA-128-CBC-SHA256"},
158  {"ECDH-ECDSA-CAMELLIA128-SHA", "TLS-ECDH-ECDSA-WITH-CAMELLIA-128-CBC-SHA"},
159  {"ECDH-ECDSA-CAMELLIA256-SHA256", "TLS-ECDH-ECDSA-WITH-CAMELLIA-256-CBC-SHA256"},
160  {"ECDH-ECDSA-CAMELLIA256-SHA", "TLS-ECDH-ECDSA-WITH-CAMELLIA-256-CBC-SHA"},
161  {"ECDH-ECDSA-DES-CBC3-SHA", "TLS-ECDH-ECDSA-WITH-3DES-EDE-CBC-SHA"},
162  {"ECDH-ECDSA-DES-CBC-SHA", "TLS-ECDH-ECDSA-WITH-DES-CBC-SHA"},
163  {"ECDH-ECDSA-RC4-SHA", "TLS-ECDH-ECDSA-WITH-RC4-128-SHA"},
164  {"ECDHE-ECDSA-AES128-GCM-SHA256", "TLS-ECDHE-ECDSA-WITH-AES-128-GCM-SHA256"},
165  {"ECDHE-ECDSA-AES128-SHA256", "TLS-ECDHE-ECDSA-WITH-AES-128-CBC-SHA256"},
166  {"ECDHE-ECDSA-AES128-SHA384", "TLS-ECDHE-ECDSA-WITH-AES-128-CBC-SHA384"},
167  {"ECDHE-ECDSA-AES128-SHA", "TLS-ECDHE-ECDSA-WITH-AES-128-CBC-SHA"},
168  {"ECDHE-ECDSA-AES256-GCM-SHA384", "TLS-ECDHE-ECDSA-WITH-AES-256-GCM-SHA384"},
169  {"ECDHE-ECDSA-AES256-SHA256", "TLS-ECDHE-ECDSA-WITH-AES-256-CBC-SHA256"},
170  {"ECDHE-ECDSA-AES256-SHA384", "TLS-ECDHE-ECDSA-WITH-AES-256-CBC-SHA384"},
171  {"ECDHE-ECDSA-AES256-SHA", "TLS-ECDHE-ECDSA-WITH-AES-256-CBC-SHA"},
172  {"ECDHE-ECDSA-CAMELLIA128-SHA256", "TLS-ECDHE-ECDSA-WITH-CAMELLIA-128-CBC-SHA256"},
173  {"ECDHE-ECDSA-CAMELLIA128-SHA", "TLS-ECDHE-ECDSA-WITH-CAMELLIA-128-CBC-SHA"},
174  {"ECDHE-ECDSA-CAMELLIA256-SHA256", "TLS-ECDHE-ECDSA-WITH-CAMELLIA-256-CBC-SHA256"},
175  {"ECDHE-ECDSA-CAMELLIA256-SHA", "TLS-ECDHE-ECDSA-WITH-CAMELLIA-256-CBC-SHA"},
176  {"ECDHE-ECDSA-CHACHA20-POLY1305", "TLS-ECDHE-ECDSA-WITH-CHACHA20-POLY1305-SHA256"},
177  {"ECDHE-ECDSA-DES-CBC3-SHA", "TLS-ECDHE-ECDSA-WITH-3DES-EDE-CBC-SHA"},
178  {"ECDHE-ECDSA-DES-CBC-SHA", "TLS-ECDHE-ECDSA-WITH-DES-CBC-SHA"},
179  {"ECDHE-ECDSA-RC4-SHA", "TLS-ECDHE-ECDSA-WITH-RC4-128-SHA"},
180  {"ECDHE-RSA-AES128-GCM-SHA256", "TLS-ECDHE-RSA-WITH-AES-128-GCM-SHA256"},
181  {"ECDHE-RSA-AES128-SHA256", "TLS-ECDHE-RSA-WITH-AES-128-CBC-SHA256"},
182  {"ECDHE-RSA-AES128-SHA384", "TLS-ECDHE-RSA-WITH-AES-128-CBC-SHA384"},
183  {"ECDHE-RSA-AES128-SHA", "TLS-ECDHE-RSA-WITH-AES-128-CBC-SHA"},
184  {"ECDHE-RSA-AES256-GCM-SHA384", "TLS-ECDHE-RSA-WITH-AES-256-GCM-SHA384"},
185  {"ECDHE-RSA-AES256-SHA256", "TLS-ECDHE-RSA-WITH-AES-256-CBC-SHA256"},
186  {"ECDHE-RSA-AES256-SHA384", "TLS-ECDHE-RSA-WITH-AES-256-CBC-SHA384"},
187  {"ECDHE-RSA-AES256-SHA", "TLS-ECDHE-RSA-WITH-AES-256-CBC-SHA"},
188  {"ECDHE-RSA-CAMELLIA128-SHA256", "TLS-ECDHE-RSA-WITH-CAMELLIA-128-CBC-SHA256"},
189  {"ECDHE-RSA-CAMELLIA128-SHA", "TLS-ECDHE-RSA-WITH-CAMELLIA-128-CBC-SHA"},
190  {"ECDHE-RSA-CAMELLIA256-SHA256", "TLS-ECDHE-RSA-WITH-CAMELLIA-256-CBC-SHA256"},
191  {"ECDHE-RSA-CAMELLIA256-SHA", "TLS-ECDHE-RSA-WITH-CAMELLIA-256-CBC-SHA"},
192  {"ECDHE-RSA-CHACHA20-POLY1305", "TLS-ECDHE-RSA-WITH-CHACHA20-POLY1305-SHA256"},
193  {"ECDHE-RSA-DES-CBC3-SHA", "TLS-ECDHE-RSA-WITH-3DES-EDE-CBC-SHA"},
194  {"ECDHE-RSA-DES-CBC-SHA", "TLS-ECDHE-RSA-WITH-DES-CBC-SHA"},
195  {"ECDHE-RSA-RC4-SHA", "TLS-ECDHE-RSA-WITH-RC4-128-SHA"},
196  {"ECDH-RSA-AES128-GCM-SHA256", "TLS-ECDH-RSA-WITH-AES-128-GCM-SHA256"},
197  {"ECDH-RSA-AES128-SHA256", "TLS-ECDH-RSA-WITH-AES-128-CBC-SHA256"},
198  {"ECDH-RSA-AES128-SHA384", "TLS-ECDH-RSA-WITH-AES-128-CBC-SHA384"},
199  {"ECDH-RSA-AES128-SHA", "TLS-ECDH-RSA-WITH-AES-128-CBC-SHA"},
200  {"ECDH-RSA-AES256-GCM-SHA384", "TLS-ECDH-RSA-WITH-AES-256-GCM-SHA384"},
201  {"ECDH-RSA-AES256-SHA256", "TLS-ECDH-RSA-WITH-AES-256-CBC-SHA256"},
202  {"ECDH-RSA-AES256-SHA384", "TLS-ECDH-RSA-WITH-AES-256-CBC-SHA384"},
203  {"ECDH-RSA-AES256-SHA", "TLS-ECDH-RSA-WITH-AES-256-CBC-SHA"},
204  {"ECDH-RSA-CAMELLIA128-SHA256", "TLS-ECDH-RSA-WITH-CAMELLIA-128-CBC-SHA256"},
205  {"ECDH-RSA-CAMELLIA128-SHA", "TLS-ECDH-RSA-WITH-CAMELLIA-128-CBC-SHA"},
206  {"ECDH-RSA-CAMELLIA256-SHA256", "TLS-ECDH-RSA-WITH-CAMELLIA-256-CBC-SHA256"},
207  {"ECDH-RSA-CAMELLIA256-SHA", "TLS-ECDH-RSA-WITH-CAMELLIA-256-CBC-SHA"},
208  {"ECDH-RSA-DES-CBC3-SHA", "TLS-ECDH-RSA-WITH-3DES-EDE-CBC-SHA"},
209  {"ECDH-RSA-DES-CBC-SHA", "TLS-ECDH-RSA-WITH-DES-CBC-SHA"},
210  {"ECDH-RSA-RC4-SHA", "TLS-ECDH-RSA-WITH-RC4-128-SHA"},
211  {"EDH-DSS-DES-CBC3-SHA", "TLS-DHE-DSS-WITH-3DES-EDE-CBC-SHA"},
212  {"EDH-DSS-DES-CBC-SHA", "TLS-DHE-DSS-WITH-DES-CBC-SHA"},
213  {"EDH-RSA-DES-CBC3-SHA", "TLS-DHE-RSA-WITH-3DES-EDE-CBC-SHA"},
214  {"EDH-RSA-DES-CBC-SHA", "TLS-DHE-RSA-WITH-DES-CBC-SHA"},
215  {"EXP-DES-CBC-SHA", "TLS-RSA-EXPORT-WITH-DES40-CBC-SHA"},
216  {"EXP-EDH-DSS-DES-CBC-SHA", "TLS-DH-DSS-EXPORT-WITH-DES40-CBC-SHA"},
217  {"EXP-EDH-RSA-DES-CBC-SHA", "TLS-DH-RSA-EXPORT-WITH-DES40-CBC-SHA"},
218  {"EXP-RC2-CBC-MD5", "TLS-RSA-EXPORT-WITH-RC2-CBC-40-MD5"},
219  {"EXP-RC4-MD5", "TLS-RSA-EXPORT-WITH-RC4-40-MD5"},
220  {"NULL-MD5", "TLS-RSA-WITH-NULL-MD5"},
221  {"NULL-SHA256", "TLS-RSA-WITH-NULL-SHA256"},
222  {"NULL-SHA", "TLS-RSA-WITH-NULL-SHA"},
223  {"PSK-3DES-EDE-CBC-SHA", "TLS-PSK-WITH-3DES-EDE-CBC-SHA"},
224  {"PSK-AES128-CBC-SHA", "TLS-PSK-WITH-AES-128-CBC-SHA"},
225  {"PSK-AES256-CBC-SHA", "TLS-PSK-WITH-AES-256-CBC-SHA"},
226  {"PSK-RC4-SHA", "TLS-PSK-WITH-RC4-128-SHA"},
227  {"RC4-MD5", "TLS-RSA-WITH-RC4-128-MD5"},
228  {"RC4-SHA", "TLS-RSA-WITH-RC4-128-SHA"},
229  {"SEED-SHA", "TLS-RSA-WITH-SEED-CBC-SHA"},
230  {"SRP-DSS-3DES-EDE-CBC-SHA", "TLS-SRP-SHA-DSS-WITH-3DES-EDE-CBC-SHA"},
231  {"SRP-DSS-AES-128-CBC-SHA", "TLS-SRP-SHA-DSS-WITH-AES-128-CBC-SHA"},
232  {"SRP-DSS-AES-256-CBC-SHA", "TLS-SRP-SHA-DSS-WITH-AES-256-CBC-SHA"},
233  {"SRP-RSA-3DES-EDE-CBC-SHA", "TLS-SRP-SHA-RSA-WITH-3DES-EDE-CBC-SHA"},
234  {"SRP-RSA-AES-128-CBC-SHA", "TLS-SRP-SHA-RSA-WITH-AES-128-CBC-SHA"},
235  {"SRP-RSA-AES-256-CBC-SHA", "TLS-SRP-SHA-RSA-WITH-AES-256-CBC-SHA"},
236 #ifdef ENABLE_CRYPTO_OPENSSL
237  /* OpenSSL-specific group names */
238  {"DEFAULT", "DEFAULT"},
239  {"ALL", "ALL"},
240  {"HIGH", "HIGH"}, {"!HIGH", "!HIGH"},
241  {"MEDIUM", "MEDIUM"}, {"!MEDIUM", "!MEDIUM"},
242  {"LOW", "LOW"}, {"!LOW", "!LOW"},
243  {"ECDH", "ECDH"}, {"!ECDH", "!ECDH"},
244  {"ECDSA", "ECDSA"}, {"!ECDSA", "!ECDSA"},
245  {"EDH", "EDH"}, {"!EDH", "!EDH"},
246  {"EXP", "EXP"}, {"!EXP", "!EXP"},
247  {"RSA", "RSA"}, {"!RSA", "!RSA"},
248  {"kRSA", "kRSA"}, {"!kRSA", "!kRSA"},
249  {"SRP", "SRP"}, {"!SRP", "!SRP"},
250 #endif
251  {NULL, NULL}
252 };
253 
265 static void
266 key_ctx_update_implicit_iv(struct key_ctx *ctx, uint8_t *key, size_t key_len);
267 
268 const tls_cipher_name_pair *
269 tls_get_cipher_name_pair(const char *cipher_name, size_t len)
270 {
272 
273  while (pair->openssl_name != NULL)
274  {
275  if ((strlen(pair->openssl_name) == len && 0 == memcmp(cipher_name, pair->openssl_name, len))
276  || (strlen(pair->iana_name) == len && 0 == memcmp(cipher_name, pair->iana_name, len)))
277  {
278  return pair;
279  }
280  pair++;
281  }
282 
283  /* No entry found, return NULL */
284  return NULL;
285 }
286 
294 static void
295 tls_limit_reneg_bytes(const cipher_kt_t *cipher, int *reneg_bytes)
296 {
297  if (cipher && (cipher_kt_block_size(cipher) < 128/8))
298  {
299  if (*reneg_bytes == -1) /* Not user-specified */
300  {
301  msg(M_WARN, "WARNING: cipher with small block size in use, "
302  "reducing reneg-bytes to 64MB to mitigate SWEET32 attacks.");
303  *reneg_bytes = 64 * 1024 * 1024;
304  }
305  }
306 }
307 
308 /*
309  * Max number of bytes we will add
310  * for data structures common to both
311  * data and control channel packets.
312  * (opcode only).
313  */
314 void
316 {
317  frame_add_to_extra_frame(frame, 1); /* space for opcode */
318 }
319 
320 /*
321  * Max number of bytes we will add
322  * to control channel packet.
323  */
324 static void
325 tls_init_control_channel_frame_parameters(const struct frame *data_channel_frame,
326  struct frame *frame)
327 {
328  /*
329  * frame->extra_frame is already initialized with tls_auth buffer requirements,
330  * if --tls-auth is enabled.
331  */
332 
333  /* inherit link MTU and extra_link from data channel */
334  frame->link_mtu = data_channel_frame->link_mtu;
335  frame->extra_link = data_channel_frame->extra_link;
336 
337  /* set extra_frame */
341 
342  /* set dynamic link MTU to cap control channel packets at 1250 bytes */
343  ASSERT(TUN_LINK_DELTA(frame) < min_int(frame->link_mtu, 1250));
344  frame->link_mtu_dynamic = min_int(frame->link_mtu, 1250) - TUN_LINK_DELTA(frame);
345 }
346 
347 void
349 {
350  tls_init_lib();
351 
352  crypto_init_lib();
353 }
354 
355 void
357 {
359  prng_uninit();
360 
361  tls_free_lib();
362 }
363 
364 /*
365  * OpenSSL library calls pem_password_callback if the
366  * private key is protected by a password.
367  */
368 
369 static struct user_pass passbuf; /* GLOBAL */
370 
371 void
372 pem_password_setup(const char *auth_file)
373 {
374  if (!strlen(passbuf.password))
375  {
377  }
378 }
379 
380 int
381 pem_password_callback(char *buf, int size, int rwflag, void *u)
382 {
383  if (buf)
384  {
385  /* prompt for password even if --askpass wasn't specified */
386  pem_password_setup(NULL);
387  strncpynt(buf, passbuf.password, size);
388  purge_user_pass(&passbuf, false);
389 
390  return strlen(buf);
391  }
392  return 0;
393 }
394 
395 /*
396  * Auth username/password handling
397  */
398 
399 static bool auth_user_pass_enabled; /* GLOBAL */
400 static struct user_pass auth_user_pass; /* GLOBAL */
401 
402 #ifdef ENABLE_CLIENT_CR
403 static char *auth_challenge; /* GLOBAL */
404 #endif
405 
406 void
407 auth_user_pass_setup(const char *auth_file, const struct static_challenge_info *sci)
408 {
409  auth_user_pass_enabled = true;
410  if (!auth_user_pass.defined)
411  {
412 #if AUTO_USERID
413  get_user_pass_auto_userid(&auth_user_pass, auth_file);
414 #else
415 #ifdef ENABLE_CLIENT_CR
416  if (auth_challenge) /* dynamic challenge/response */
417  {
419  auth_file,
420  UP_TYPE_AUTH,
423  }
424  else if (sci) /* static challenge response */
425  {
427  if (sci->flags & SC_ECHO)
428  {
430  }
432  auth_file,
433  UP_TYPE_AUTH,
434  flags,
435  sci->challenge_text);
436  }
437  else
438 #endif /* ifdef ENABLE_CLIENT_CR */
440 #endif /* if AUTO_USERID */
441  }
442 }
443 
444 /*
445  * Disable password caching
446  */
447 void
449 {
450  passbuf.nocache = true;
451  auth_user_pass.nocache = true;
452  /* wait for push-reply, because auth-token may invert nocache */
454 }
455 
456 /*
457  * Set an authentication token
458  */
459 void
460 ssl_set_auth_token(const char *token)
461 {
463  {
464  msg(M_INFO,
465  "auth-token received, disabling auth-nocache for the "
466  "authentication token");
467  auth_user_pass.nocache = false;
468  }
469 
471 }
472 
473 /*
474  * Forget private key password AND auth-user-pass username/password.
475  */
476 void
477 ssl_purge_auth(const bool auth_user_pass_only)
478 {
479  if (!auth_user_pass_only)
480  {
481 #ifdef ENABLE_PKCS11
482  pkcs11_logout();
483 #endif
484  purge_user_pass(&passbuf, true);
485  }
487 #ifdef ENABLE_CLIENT_CR
489 #endif
490 }
491 
492 #ifdef ENABLE_CLIENT_CR
493 
494 void
496 {
498  auth_challenge = NULL;
499 }
500 
501 void
502 ssl_put_auth_challenge(const char *cr_str)
503 {
505  auth_challenge = string_alloc(cr_str, NULL);
506 }
507 
508 #endif
509 
510 /*
511  * Parse a TLS version string, returning a TLS_VER_x constant.
512  * If version string is not recognized and extra == "or-highest",
513  * return tls_version_max().
514  */
515 int
516 tls_version_parse(const char *vstr, const char *extra)
517 {
518  const int max_version = tls_version_max();
519  if (!strcmp(vstr, "1.0") && TLS_VER_1_0 <= max_version)
520  {
521  return TLS_VER_1_0;
522  }
523  else if (!strcmp(vstr, "1.1") && TLS_VER_1_1 <= max_version)
524  {
525  return TLS_VER_1_1;
526  }
527  else if (!strcmp(vstr, "1.2") && TLS_VER_1_2 <= max_version)
528  {
529  return TLS_VER_1_2;
530  }
531  else if (!strcmp(vstr, "1.3") && TLS_VER_1_3 <= max_version)
532  {
533  return TLS_VER_1_3;
534  }
535  else if (extra && !strcmp(extra, "or-highest"))
536  {
537  return max_version;
538  }
539  else
540  {
541  return TLS_VER_BAD;
542  }
543 }
544 
556 static void
557 tls_ctx_reload_crl(struct tls_root_ctx *ssl_ctx, const char *crl_file,
558  const char *crl_file_inline)
559 {
560  /* if something goes wrong with stat(), we'll store 0 as mtime */
561  platform_stat_t crl_stat = {0};
562 
563  /*
564  * an inline CRL can't change at runtime, therefore there is no need to
565  * reload it. It will be reloaded upon config change + SIGHUP.
566  * Use always '1' as dummy timestamp in this case: it will trigger the
567  * first load, but will prevent any future reload.
568  */
569  if (crl_file_inline)
570  {
571  crl_stat.st_mtime = 1;
572  }
573  else if (platform_stat(crl_file, &crl_stat) < 0)
574  {
575  msg(M_WARN, "WARNING: Failed to stat CRL file, not (re)loading CRL.");
576  return;
577  }
578 
579  /*
580  * Store the CRL if this is the first time or if the file was changed since
581  * the last load.
582  * Note: Windows does not support tv_nsec.
583  */
584  if ((ssl_ctx->crl_last_size == crl_stat.st_size)
585  && (ssl_ctx->crl_last_mtime == crl_stat.st_mtime))
586  {
587  return;
588  }
589 
590  ssl_ctx->crl_last_mtime = crl_stat.st_mtime;
591  ssl_ctx->crl_last_size = crl_stat.st_size;
592  backend_tls_ctx_reload_crl(ssl_ctx, crl_file, crl_file_inline);
593 }
594 
595 /*
596  * Initialize SSL context.
597  * All files are in PEM format.
598  */
599 void
600 init_ssl(const struct options *options, struct tls_root_ctx *new_ctx)
601 {
602  ASSERT(NULL != new_ctx);
603 
604  tls_clear_error();
605 
606  if (options->tls_server)
607  {
608  tls_ctx_server_new(new_ctx);
609 
610  if (options->dh_file)
611  {
612  tls_ctx_load_dh_params(new_ctx, options->dh_file,
613  options->dh_file_inline);
614  }
615  }
616  else /* if client */
617  {
618  tls_ctx_client_new(new_ctx);
619  }
620 
621  /* Restrict allowed certificate crypto algorithms */
622  tls_ctx_set_cert_profile(new_ctx, options->tls_cert_profile);
623 
624  /* Allowable ciphers */
625  /* Since @SECLEVEL also influces loading of certificates, set the
626  * cipher restrictions before loading certificates */
627  tls_ctx_restrict_ciphers(new_ctx, options->cipher_list);
628 
629  if (!tls_ctx_set_options(new_ctx, options->ssl_flags))
630  {
631  goto err;
632  }
633 
634  if (options->pkcs12_file)
635  {
636  if (0 != tls_ctx_load_pkcs12(new_ctx, options->pkcs12_file,
637  options->pkcs12_file_inline, !options->ca_file))
638  {
639  goto err;
640  }
641  }
642 #ifdef ENABLE_PKCS11
643  else if (options->pkcs11_providers[0])
644  {
645  if (!tls_ctx_use_pkcs11(new_ctx, options->pkcs11_id_management, options->pkcs11_id))
646  {
647  msg(M_WARN, "Cannot load certificate \"%s\" using PKCS#11 interface",
648  options->pkcs11_id);
649  goto err;
650  }
651  }
652 #endif
653 #ifdef ENABLE_CRYPTOAPI
654  else if (options->cryptoapi_cert)
655  {
656  tls_ctx_load_cryptoapi(new_ctx, options->cryptoapi_cert);
657  }
658 #endif
659 #ifdef MANAGMENT_EXTERNAL_KEY
660  else if ((options->management_flags & MF_EXTERNAL_KEY)
661  && (options->cert_file || options->management_flags & MF_EXTERNAL_CERT))
662  {
663  if (options->cert_file)
664  {
666  options->cert_file_inline);
667  }
668  else
669  {
670  char *external_certificate = management_query_cert(management,
671  options->management_certificate);
673  external_certificate);
674  free(external_certificate);
675  }
676  }
677 #endif
678  else
679  {
680  /* Load Certificate */
681  if (options->cert_file)
682  {
683  tls_ctx_load_cert_file(new_ctx, options->cert_file, options->cert_file_inline);
684  }
685 
686  /* Load Private Key */
687  if (options->priv_key_file)
688  {
689  if (0 != tls_ctx_load_priv_file(new_ctx, options->priv_key_file, options->priv_key_file_inline))
690  {
691  goto err;
692  }
693  }
694  }
695 
696  if (options->ca_file || options->ca_path)
697  {
698  tls_ctx_load_ca(new_ctx, options->ca_file, options->ca_file_inline,
699  options->ca_path, options->tls_server);
700  }
701 
702  /* Load extra certificates that are part of our own certificate
703  * chain but shouldn't be included in the verify chain */
704  if (options->extra_certs_file)
705  {
707  }
708 
709  /* Check certificate notBefore and notAfter */
710  tls_ctx_check_cert_time(new_ctx);
711 
712  /* Read CRL */
713  if (options->crl_file && !(options->ssl_flags & SSLF_CRL_VERIFY_DIR))
714  {
715  tls_ctx_reload_crl(new_ctx, options->crl_file, options->crl_file_inline);
716  }
717 
718  /* Once keys and cert are loaded, load ECDH parameters */
719  if (options->tls_server)
720  {
721  tls_ctx_load_ecdh_params(new_ctx, options->ecdh_curve);
722  }
723 
724 #ifdef ENABLE_CRYPTO_MBEDTLS
725  /* Personalise the random by mixing in the certificate */
726  tls_ctx_personalise_random(new_ctx);
727 #endif
728 
729  tls_clear_error();
730  return;
731 
732 err:
733  tls_clear_error();
734  tls_ctx_free(new_ctx);
735  return;
736 }
737 
738 /*
739  * Map internal constants to ascii names.
740  */
741 static const char *
742 state_name(int state)
743 {
744  switch (state)
745  {
746  case S_UNDEF:
747  return "S_UNDEF";
748 
749  case S_INITIAL:
750  return "S_INITIAL";
751 
752  case S_PRE_START:
753  return "S_PRE_START";
754 
755  case S_START:
756  return "S_START";
757 
758  case S_SENT_KEY:
759  return "S_SENT_KEY";
760 
761  case S_GOT_KEY:
762  return "S_GOT_KEY";
763 
764  case S_ACTIVE:
765  return "S_ACTIVE";
766 
767  case S_NORMAL_OP:
768  return "S_NORMAL_OP";
769 
770  case S_ERROR:
771  return "S_ERROR";
772 
773  default:
774  return "S_???";
775  }
776 }
777 
778 static const char *
780 {
781  switch (op)
782  {
784  return "P_CONTROL_HARD_RESET_CLIENT_V1";
785 
787  return "P_CONTROL_HARD_RESET_SERVER_V1";
788 
790  return "P_CONTROL_HARD_RESET_CLIENT_V2";
791 
793  return "P_CONTROL_HARD_RESET_SERVER_V2";
794 
796  return "P_CONTROL_SOFT_RESET_V1";
797 
798  case P_CONTROL_V1:
799  return "P_CONTROL_V1";
800 
801  case P_ACK_V1:
802  return "P_ACK_V1";
803 
804  case P_DATA_V1:
805  return "P_DATA_V1";
806 
807  case P_DATA_V2:
808  return "P_DATA_V2";
809 
810  default:
811  return "P_???";
812  }
813 }
814 
815 static const char *
817 {
818  switch (index)
819  {
820  case TM_ACTIVE:
821  return "TM_ACTIVE";
822 
823  case TM_UNTRUSTED:
824  return "TM_UNTRUSTED";
825 
826  case TM_LAME_DUCK:
827  return "TM_LAME_DUCK";
828 
829  default:
830  return "TM_???";
831  }
832 }
833 
834 /*
835  * For debugging.
836  */
837 static const char *
838 print_key_id(struct tls_multi *multi, struct gc_arena *gc)
839 {
840  int i;
841  struct buffer out = alloc_buf_gc(256, gc);
842 
843  for (i = 0; i < KEY_SCAN_SIZE; ++i)
844  {
845  struct key_state *ks = multi->key_scan[i];
846  buf_printf(&out, " [key#%d state=%s id=%d sid=%s]", i,
847  state_name(ks->state), ks->key_id,
849  }
850 
851  return BSTR(&out);
852 }
853 
854 bool
855 is_hard_reset(int op, int key_method)
856 {
857  if (!key_method || key_method == 1)
858  {
860  {
861  return true;
862  }
863  }
864 
865  if (!key_method || key_method >= 2)
866  {
868  {
869  return true;
870  }
871  }
872 
873  return false;
874 }
875 
899 static void
901 {
902  update_time();
903 
904  CLEAR(*ks);
905 
906  /*
907  * Build TLS object that reads/writes ciphertext
908  * to/from memory BIOs.
909  */
910  key_state_ssl_init(&ks->ks_ssl, &session->opt->ssl_ctx, session->opt->server,
911  session);
912 
913  /* Set control-channel initiation mode */
914  ks->initial_opcode = session->initial_opcode;
916  ks->state = S_INITIAL;
917  ks->key_id = session->key_id;
918 
919  /*
920  * key_id increments to KEY_ID_MASK then recycles back to 1.
921  * This way you know that if key_id is 0, it is the first key.
922  */
923  ++session->key_id;
924  session->key_id &= P_KEY_ID_MASK;
925  if (!session->key_id)
926  {
927  session->key_id = 1;
928  }
929 
930  /* allocate key source material object */
931  ALLOC_OBJ_CLEAR(ks->key_src, struct key_source2);
932 
933  /* allocate reliability objects */
936  ALLOC_OBJ_CLEAR(ks->rec_ack, struct reliable_ack);
937 
938  /* allocate buffers */
941  ks->ack_write_buf = alloc_buf(BUF_SIZE(&session->opt->frame));
942  reliable_init(ks->send_reliable, BUF_SIZE(&session->opt->frame),
944  ks->key_id ? false : session->opt->xmit_hold);
945  reliable_init(ks->rec_reliable, BUF_SIZE(&session->opt->frame),
947  false);
949 
950  /* init packet ID tracker */
951  if (session->opt->replay)
952  {
954  session->opt->replay_window, session->opt->replay_time, "SSL",
955  ks->key_id);
956  }
957 
958  ks->crypto_options.pid_persist = NULL;
959 
960 #ifdef MANAGEMENT_DEF_AUTH
961  ks->mda_key_id = session->opt->mda_context->mda_key_id_counter++;
962 #endif
963 }
964 
965 
979 static void
980 key_state_free(struct key_state *ks, bool clear)
981 {
982  ks->state = S_UNDEF;
983 
985 
989  free_buf(&ks->ack_write_buf);
991 
992  if (ks->send_reliable)
993  {
995  free(ks->send_reliable);
996  }
997 
998  if (ks->rec_reliable)
999  {
1001  free(ks->rec_reliable);
1002  }
1003 
1004  if (ks->rec_ack)
1005  {
1006  free(ks->rec_ack);
1007  }
1008 
1009  if (ks->key_src)
1010  {
1011  free(ks->key_src);
1012  }
1013 
1015 
1016 #ifdef PLUGIN_DEF_AUTH
1018 #endif
1019 
1020  if (clear)
1021  {
1022  secure_memzero(ks, sizeof(*ks));
1023  }
1024 }
1025 
1039 static inline bool
1041 {
1042  return (session->opt->auth_user_pass_verify_script
1044 #ifdef MANAGEMENT_DEF_AUTH
1045  || management_enable_def_auth(management)
1046 #endif
1047  );
1048 }
1049 
1050 
1071 static void
1073 {
1074  struct gc_arena gc = gc_new();
1075 
1076  dmsg(D_TLS_DEBUG, "TLS: tls_session_init: entry");
1077 
1078  CLEAR(*session);
1079 
1080  /* Set options data to point to parent's option structure */
1081  session->opt = &multi->opt;
1082 
1083  /* Randomize session # if it is 0 */
1084  while (!session_id_defined(&session->session_id))
1085  {
1086  session_id_random(&session->session_id);
1087  }
1088 
1089  /* Are we a TLS server or client? */
1090  ASSERT(session->opt->key_method >= 1);
1091  if (session->opt->key_method == 1)
1092  {
1093  session->initial_opcode = session->opt->server ?
1095  }
1096  else /* session->opt->key_method >= 2 */
1097  {
1098  session->initial_opcode = session->opt->server ?
1100  }
1101 
1102  /* Initialize control channel authentication parameters */
1103  session->tls_wrap = session->opt->tls_wrap;
1104  session->tls_wrap.work = alloc_buf(BUF_SIZE(&session->opt->frame));
1105 
1106  /* initialize packet ID replay window for --tls-auth */
1108  session->opt->replay_window,
1109  session->opt->replay_time,
1110  "TLS_WRAP", session->key_id);
1111 
1112  /* load most recent packet-id to replay protect on --tls-auth */
1114  &session->tls_wrap.opt.packet_id);
1115 
1116  key_state_init(session, &session->key[KS_PRIMARY]);
1117 
1118  dmsg(D_TLS_DEBUG, "TLS: tls_session_init: new session object, sid=%s",
1119  session_id_print(&session->session_id, &gc));
1120 
1121  gc_free(&gc);
1122 }
1123 
1136 static void
1138 {
1139  int i;
1140 
1142  {
1143  packet_id_free(&session->tls_wrap.opt.packet_id);
1144  }
1145 
1146  free_buf(&session->tls_wrap.work);
1147 
1148  for (i = 0; i < KS_SIZE; ++i)
1149  {
1150  key_state_free(&session->key[i], false);
1151  }
1152 
1153  if (session->common_name)
1154  {
1155  free(session->common_name);
1156  }
1157 
1158  cert_hash_free(session->cert_hash_set);
1159 
1160  if (clear)
1161  {
1162  secure_memzero(session, sizeof(*session));
1163  }
1164 }
1165 
1171 static void
1172 move_session(struct tls_multi *multi, int dest, int src, bool reinit_src)
1173 {
1174  msg(D_TLS_DEBUG_LOW, "TLS: move_session: dest=%s src=%s reinit_src=%d",
1175  session_index_name(dest),
1176  session_index_name(src),
1177  reinit_src);
1178  ASSERT(src != dest);
1179  ASSERT(src >= 0 && src < TM_SIZE);
1180  ASSERT(dest >= 0 && dest < TM_SIZE);
1181  tls_session_free(&multi->session[dest], false);
1182  multi->session[dest] = multi->session[src];
1183 
1184  if (reinit_src)
1185  {
1186  tls_session_init(multi, &multi->session[src]);
1187  }
1188  else
1189  {
1190  secure_memzero(&multi->session[src], sizeof(multi->session[src]));
1191  }
1192 
1193  dmsg(D_TLS_DEBUG, "TLS: move_session: exit");
1194 }
1195 
1196 static void
1198 {
1199  tls_session_free(session, false);
1200  tls_session_init(multi, session);
1201 }
1202 
1203 /*
1204  * Used to determine in how many seconds we should be
1205  * called again.
1206  */
1207 static inline void
1208 compute_earliest_wakeup(interval_t *earliest, interval_t seconds_from_now)
1209 {
1210  if (seconds_from_now < *earliest)
1211  {
1212  *earliest = seconds_from_now;
1213  }
1214  if (*earliest < 0)
1215  {
1216  *earliest = 0;
1217  }
1218 }
1219 
1220 /*
1221  * Return true if "lame duck" or retiring key has expired and can
1222  * no longer be used.
1223  */
1224 static inline bool
1226 {
1227  const struct key_state *lame = &session->key[KS_LAME_DUCK];
1228  if (lame->state >= S_INITIAL)
1229  {
1230  const time_t local_now = now;
1231  ASSERT(lame->must_die); /* a lame duck key must always have an expiration */
1232  if (local_now < lame->must_die)
1233  {
1234  compute_earliest_wakeup(wakeup, lame->must_die - local_now);
1235  return false;
1236  }
1237  else
1238  {
1239  return true;
1240  }
1241  }
1242  else if (lame->state == S_ERROR)
1243  {
1244  return true;
1245  }
1246  else
1247  {
1248  return false;
1249  }
1250 }
1251 
1252 struct tls_multi *
1254 {
1255  struct tls_multi *ret;
1256 
1257  ALLOC_OBJ_CLEAR(ret, struct tls_multi);
1258 
1259  /* get command line derived options */
1260  ret->opt = *tls_options;
1261 
1262  /* set up list of keys to be scanned by data channel encrypt and decrypt routines */
1263  ASSERT(SIZE(ret->key_scan) == 3);
1264  ret->key_scan[0] = &ret->session[TM_ACTIVE].key[KS_PRIMARY];
1265  ret->key_scan[1] = &ret->session[TM_ACTIVE].key[KS_LAME_DUCK];
1266  ret->key_scan[2] = &ret->session[TM_LAME_DUCK].key[KS_LAME_DUCK];
1267 
1268  /* By default not use P_DATA_V2 */
1269  ret->use_peer_id = false;
1270 
1271  return ret;
1272 }
1273 
1274 void
1275 tls_multi_init_finalize(struct tls_multi *multi, const struct frame *frame)
1276 {
1278 
1279  /* initialize the active and untrusted sessions */
1280 
1281  tls_session_init(multi, &multi->session[TM_ACTIVE]);
1282 
1283  if (!multi->opt.single_session)
1284  {
1285  tls_session_init(multi, &multi->session[TM_UNTRUSTED]);
1286  }
1287 }
1288 
1289 /*
1290  * Initialize and finalize a standalone tls-auth verification object.
1291  */
1292 
1293 struct tls_auth_standalone *
1295  struct gc_arena *gc)
1296 {
1297  struct tls_auth_standalone *tas;
1298 
1299  ALLOC_OBJ_CLEAR_GC(tas, struct tls_auth_standalone, gc);
1300 
1301  tas->tls_wrap = tls_options->tls_wrap;
1302 
1303  /*
1304  * Standalone tls-auth is in read-only mode with respect to TLS
1305  * control channel state. After we build a new client instance
1306  * object, we will process this session-initiating packet for real.
1307  */
1309 
1310  /* get initial frame parms, still need to finalize */
1311  tas->frame = tls_options->frame;
1312 
1313  return tas;
1314 }
1315 
1316 void
1318  const struct frame *frame)
1319 {
1321 }
1322 
1323 /*
1324  * Set local and remote option compatibility strings.
1325  * Used to verify compatibility of local and remote option
1326  * sets.
1327  */
1328 void
1330  const char *local,
1331  const char *remote)
1332 {
1333 #ifdef ENABLE_OCC
1334  /* initialize options string */
1335  multi->opt.local_options = local;
1336  multi->opt.remote_options = remote;
1337 #endif
1338 }
1339 
1340 /*
1341  * Cleanup a tls_multi structure and free associated memory allocations.
1342  */
1343 void
1344 tls_multi_free(struct tls_multi *multi, bool clear)
1345 {
1346  int i;
1347 
1348  ASSERT(multi);
1349 
1350 #ifdef MANAGEMENT_DEF_AUTH
1351  man_def_auth_set_client_reason(multi, NULL);
1352 
1353 #endif
1354 #if P2MP_SERVER
1355  free(multi->peer_info);
1356 #endif
1357 
1358  if (multi->locked_cn)
1359  {
1360  free(multi->locked_cn);
1361  }
1362 
1363  if (multi->locked_username)
1364  {
1365  free(multi->locked_username);
1366  }
1367 
1369 
1370  if (multi->auth_token)
1371  {
1373  free(multi->auth_token);
1374  }
1375 
1376  free(multi->remote_ciphername);
1377 
1378  for (i = 0; i < TM_SIZE; ++i)
1379  {
1380  tls_session_free(&multi->session[i], false);
1381  }
1382 
1383  if (clear)
1384  {
1385  secure_memzero(multi, sizeof(*multi));
1386  }
1387 
1388  free(multi);
1389 }
1390 
1391 
1392 /*
1393  * Move a packet authentication HMAC + related fields to or from the front
1394  * of the buffer so it can be processed by encrypt/decrypt.
1395  */
1396 
1397 /*
1398  * Dependent on hmac size, opcode size, and session_id size.
1399  * Will assert if too small.
1400  */
1401 #define SWAP_BUF_SIZE 256
1402 
1403 static bool
1404 swap_hmac(struct buffer *buf, const struct crypto_options *co, bool incoming)
1405 {
1406  const struct key_ctx *ctx;
1407 
1408  ASSERT(co);
1409 
1410  ctx = (incoming ? &co->key_ctx_bi.decrypt : &co->key_ctx_bi.encrypt);
1411  ASSERT(ctx->hmac);
1412 
1413  {
1414  /* hmac + packet_id (8 bytes) */
1415  const int hmac_size = hmac_ctx_size(ctx->hmac) + packet_id_size(true);
1416 
1417  /* opcode + session_id */
1418  const int osid_size = 1 + SID_SIZE;
1419 
1420  int e1, e2;
1421  uint8_t *b = BPTR(buf);
1422  uint8_t buf1[SWAP_BUF_SIZE];
1423  uint8_t buf2[SWAP_BUF_SIZE];
1424 
1425  if (incoming)
1426  {
1427  e1 = osid_size;
1428  e2 = hmac_size;
1429  }
1430  else
1431  {
1432  e1 = hmac_size;
1433  e2 = osid_size;
1434  }
1435 
1436  ASSERT(e1 <= SWAP_BUF_SIZE && e2 <= SWAP_BUF_SIZE);
1437 
1438  if (buf->len >= e1 + e2)
1439  {
1440  memcpy(buf1, b, e1);
1441  memcpy(buf2, b + e1, e2);
1442  memcpy(b, buf2, e2);
1443  memcpy(b + e2, buf1, e1);
1444  return true;
1445  }
1446  else
1447  {
1448  return false;
1449  }
1450  }
1451 }
1452 
1453 #undef SWAP_BUF_SIZE
1454 
1455 /*
1456  * Write a control channel authentication record.
1457  */
1458 static void
1460  struct key_state *ks,
1461  struct buffer *buf,
1462  struct link_socket_actual **to_link_addr,
1463  int opcode,
1464  int max_ack,
1465  bool prepend_ack)
1466 {
1467  uint8_t header = ks->key_id | (opcode << P_OPCODE_SHIFT);
1468  struct buffer null = clear_buf();
1469 
1472  (ks->rec_ack, buf, &ks->session_id_remote, max_ack, prepend_ack));
1473 
1474  if (session->tls_wrap.mode == TLS_WRAP_AUTH
1475  || session->tls_wrap.mode == TLS_WRAP_NONE)
1476  {
1477  ASSERT(session_id_write_prepend(&session->session_id, buf));
1478  ASSERT(buf_write_prepend(buf, &header, sizeof(header)));
1479  }
1480  if (session->tls_wrap.mode == TLS_WRAP_AUTH)
1481  {
1482  /* no encryption, only write hmac */
1483  openvpn_encrypt(buf, null, &session->tls_wrap.opt);
1484  ASSERT(swap_hmac(buf, &session->tls_wrap.opt, false));
1485  }
1486  else if (session->tls_wrap.mode == TLS_WRAP_CRYPT)
1487  {
1488  ASSERT(buf_init(&session->tls_wrap.work, buf->offset));
1489  ASSERT(buf_write(&session->tls_wrap.work, &header, sizeof(header)));
1490  ASSERT(session_id_write(&session->session_id, &session->tls_wrap.work));
1491  if (tls_crypt_wrap(buf, &session->tls_wrap.work, &session->tls_wrap.opt))
1492  {
1493  /* Don't change the original data in buf, it's used by the reliability
1494  * layer to resend on failure. */
1495  *buf = session->tls_wrap.work;
1496  }
1497  else
1498  {
1499  buf->len = 0;
1500  return;
1501  }
1502  }
1503  *to_link_addr = &ks->remote_addr;
1504 }
1505 
1506 /*
1507  * Read a control channel authentication record.
1508  */
1509 static bool
1511  struct tls_wrap_ctx *ctx,
1512  const struct link_socket_actual *from)
1513 {
1514  struct gc_arena gc = gc_new();
1515  bool ret = false;
1516 
1517  if (ctx->mode == TLS_WRAP_AUTH)
1518  {
1519  struct buffer null = clear_buf();
1520 
1521  /* move the hmac record to the front of the packet */
1522  if (!swap_hmac(buf, &ctx->opt, true))
1523  {
1524  msg(D_TLS_ERRORS,
1525  "TLS Error: cannot locate HMAC in incoming packet from %s",
1526  print_link_socket_actual(from, &gc));
1527  gc_free(&gc);
1528  return false;
1529  }
1530 
1531  /* authenticate only (no decrypt) and remove the hmac record
1532  * from the head of the buffer */
1533  openvpn_decrypt(buf, null, &ctx->opt, NULL, BPTR(buf));
1534  if (!buf->len)
1535  {
1536  msg(D_TLS_ERRORS,
1537  "TLS Error: incoming packet authentication failed from %s",
1538  print_link_socket_actual(from, &gc));
1539  goto cleanup;
1540  }
1541 
1542  }
1543  else if (ctx->mode == TLS_WRAP_CRYPT)
1544  {
1545  struct buffer tmp = alloc_buf_gc(buf_forward_capacity_total(buf), &gc);
1546  if (!tls_crypt_unwrap(buf, &tmp, &ctx->opt))
1547  {
1548  msg(D_TLS_ERRORS, "TLS Error: tls-crypt unwrapping failed from %s",
1549  print_link_socket_actual(from, &gc));
1550  goto cleanup;
1551  }
1552  ASSERT(buf_init(buf, buf->offset));
1553  ASSERT(buf_copy(buf, &tmp));
1554  buf_clear(&tmp);
1555  }
1556 
1557  if (ctx->mode == TLS_WRAP_NONE || ctx->mode == TLS_WRAP_AUTH)
1558  {
1559  /* advance buffer pointer past opcode & session_id since our caller
1560  * already read it */
1561  buf_advance(buf, SID_SIZE + 1);
1562  }
1563 
1564  ret = true;
1565 cleanup:
1566  gc_free(&gc);
1567  return ret;
1568 }
1569 
1570 /*
1571  * For debugging, print contents of key_source2 structure.
1572  */
1573 
1574 static void
1576  const char *prefix)
1577 {
1578  struct gc_arena gc = gc_new();
1579 
1580  VALGRIND_MAKE_READABLE((void *)k->pre_master, sizeof(k->pre_master));
1581  VALGRIND_MAKE_READABLE((void *)k->random1, sizeof(k->random1));
1582  VALGRIND_MAKE_READABLE((void *)k->random2, sizeof(k->random2));
1583 
1585  "%s pre_master: %s",
1586  prefix,
1587  format_hex(k->pre_master, sizeof(k->pre_master), 0, &gc));
1589  "%s random1: %s",
1590  prefix,
1591  format_hex(k->random1, sizeof(k->random1), 0, &gc));
1593  "%s random2: %s",
1594  prefix,
1595  format_hex(k->random2, sizeof(k->random2), 0, &gc));
1596 
1597  gc_free(&gc);
1598 }
1599 
1600 static void
1602 {
1603  key_source_print(&k->client, "Client");
1604  key_source_print(&k->server, "Server");
1605 }
1606 
1607 /*
1608  * Generate the hash required by for the \c tls1_PRF function.
1609  *
1610  * @param md_kt Message digest to use
1611  * @param sec Secret to base the hash on
1612  * @param sec_len Length of the secret
1613  * @param seed Seed to hash
1614  * @param seed_len Length of the seed
1615  * @param out Output buffer
1616  * @param olen Length of the output buffer
1617  */
1618 static void
1619 tls1_P_hash(const md_kt_t *md_kt,
1620  const uint8_t *sec,
1621  int sec_len,
1622  const uint8_t *seed,
1623  int seed_len,
1624  uint8_t *out,
1625  int olen)
1626 {
1627  struct gc_arena gc = gc_new();
1628  int chunk;
1629  hmac_ctx_t *ctx;
1630  hmac_ctx_t *ctx_tmp;
1632  unsigned int A1_len;
1633 
1634 #ifdef ENABLE_DEBUG
1635  const int olen_orig = olen;
1636  const uint8_t *out_orig = out;
1637 #endif
1638 
1639  ctx = hmac_ctx_new();
1640  ctx_tmp = hmac_ctx_new();
1641 
1642  dmsg(D_SHOW_KEY_SOURCE, "tls1_P_hash sec: %s", format_hex(sec, sec_len, 0, &gc));
1643  dmsg(D_SHOW_KEY_SOURCE, "tls1_P_hash seed: %s", format_hex(seed, seed_len, 0, &gc));
1644 
1645  chunk = md_kt_size(md_kt);
1646  A1_len = md_kt_size(md_kt);
1647 
1648  hmac_ctx_init(ctx, sec, sec_len, md_kt);
1649  hmac_ctx_init(ctx_tmp, sec, sec_len, md_kt);
1650 
1651  hmac_ctx_update(ctx,seed,seed_len);
1652  hmac_ctx_final(ctx, A1);
1653 
1654  for (;; )
1655  {
1656  hmac_ctx_reset(ctx);
1657  hmac_ctx_reset(ctx_tmp);
1658  hmac_ctx_update(ctx,A1,A1_len);
1659  hmac_ctx_update(ctx_tmp,A1,A1_len);
1660  hmac_ctx_update(ctx,seed,seed_len);
1661 
1662  if (olen > chunk)
1663  {
1664  hmac_ctx_final(ctx, out);
1665  out += chunk;
1666  olen -= chunk;
1667  hmac_ctx_final(ctx_tmp, A1); /* calc the next A1 value */
1668  }
1669  else /* last one */
1670  {
1671  hmac_ctx_final(ctx, A1);
1672  memcpy(out,A1,olen);
1673  break;
1674  }
1675  }
1676  hmac_ctx_cleanup(ctx);
1677  hmac_ctx_free(ctx);
1678  hmac_ctx_cleanup(ctx_tmp);
1679  hmac_ctx_free(ctx_tmp);
1680  secure_memzero(A1, sizeof(A1));
1681 
1682  dmsg(D_SHOW_KEY_SOURCE, "tls1_P_hash out: %s", format_hex(out_orig, olen_orig, 0, &gc));
1683  gc_free(&gc);
1684 }
1685 
1686 /*
1687  * Use the TLS PRF function for generating data channel keys.
1688  * This code is based on the OpenSSL library.
1689  *
1690  * TLS generates keys as such:
1691  *
1692  * master_secret[48] = PRF(pre_master_secret[48], "master secret",
1693  * ClientHello.random[32] + ServerHello.random[32])
1694  *
1695  * key_block[] = PRF(SecurityParameters.master_secret[48],
1696  * "key expansion",
1697  * SecurityParameters.server_random[32] +
1698  * SecurityParameters.client_random[32]);
1699  *
1700  * Notes:
1701  *
1702  * (1) key_block contains a full set of 4 keys.
1703  * (2) The pre-master secret is generated by the client.
1704  */
1705 static void
1706 tls1_PRF(const uint8_t *label,
1707  int label_len,
1708  const uint8_t *sec,
1709  int slen,
1710  uint8_t *out1,
1711  int olen)
1712 {
1713  struct gc_arena gc = gc_new();
1714  const md_kt_t *md5 = md_kt_get("MD5");
1715  const md_kt_t *sha1 = md_kt_get("SHA1");
1716  int len,i;
1717  const uint8_t *S1,*S2;
1718  uint8_t *out2;
1719 
1720  out2 = (uint8_t *) gc_malloc(olen, false, &gc);
1721 
1722  len = slen/2;
1723  S1 = sec;
1724  S2 = &(sec[len]);
1725  len += (slen&1); /* add for odd, make longer */
1726 
1727  tls1_P_hash(md5,S1,len,label,label_len,out1,olen);
1728  tls1_P_hash(sha1,S2,len,label,label_len,out2,olen);
1729 
1730  for (i = 0; i<olen; i++)
1731  {
1732  out1[i] ^= out2[i];
1733  }
1734 
1735  secure_memzero(out2, olen);
1736 
1737  dmsg(D_SHOW_KEY_SOURCE, "tls1_PRF out[%d]: %s", olen, format_hex(out1, olen, 0, &gc));
1738 
1739  gc_free(&gc);
1740 }
1741 
1742 static void
1743 openvpn_PRF(const uint8_t *secret,
1744  int secret_len,
1745  const char *label,
1746  const uint8_t *client_seed,
1747  int client_seed_len,
1748  const uint8_t *server_seed,
1749  int server_seed_len,
1750  const struct session_id *client_sid,
1751  const struct session_id *server_sid,
1752  uint8_t *output,
1753  int output_len)
1754 {
1755  /* concatenate seed components */
1756 
1757  struct buffer seed = alloc_buf(strlen(label)
1758  + client_seed_len
1759  + server_seed_len
1760  + SID_SIZE * 2);
1761 
1762  ASSERT(buf_write(&seed, label, strlen(label)));
1763  ASSERT(buf_write(&seed, client_seed, client_seed_len));
1764  ASSERT(buf_write(&seed, server_seed, server_seed_len));
1765 
1766  if (client_sid)
1767  {
1768  ASSERT(buf_write(&seed, client_sid->id, SID_SIZE));
1769  }
1770  if (server_sid)
1771  {
1772  ASSERT(buf_write(&seed, server_sid->id, SID_SIZE));
1773  }
1774 
1775  /* compute PRF */
1776  tls1_PRF(BPTR(&seed), BLEN(&seed), secret, secret_len, output, output_len);
1777 
1778  buf_clear(&seed);
1779  free_buf(&seed);
1780 
1781  VALGRIND_MAKE_READABLE((void *)output, output_len);
1782 }
1783 
1784 /*
1785  * Using source entropy from local and remote hosts, mix into
1786  * master key.
1787  */
1788 static bool
1790  const struct key_type *key_type,
1791  const struct key_source2 *key_src,
1792  const struct session_id *client_sid,
1793  const struct session_id *server_sid,
1794  bool server)
1795 {
1796  uint8_t master[48] = { 0 };
1797  struct key2 key2 = { 0 };
1798  bool ret = false;
1799 
1800  if (key->initialized)
1801  {
1802  msg(D_TLS_ERRORS, "TLS Error: key already initialized");
1803  goto exit;
1804  }
1805 
1806  /* debugging print of source key material */
1807  key_source2_print(key_src);
1808 
1809  /* compute master secret */
1810  openvpn_PRF(key_src->client.pre_master,
1811  sizeof(key_src->client.pre_master),
1812  KEY_EXPANSION_ID " master secret",
1813  key_src->client.random1,
1814  sizeof(key_src->client.random1),
1815  key_src->server.random1,
1816  sizeof(key_src->server.random1),
1817  NULL,
1818  NULL,
1819  master,
1820  sizeof(master));
1821 
1822  /* compute key expansion */
1823  openvpn_PRF(master,
1824  sizeof(master),
1825  KEY_EXPANSION_ID " key expansion",
1826  key_src->client.random2,
1827  sizeof(key_src->client.random2),
1828  key_src->server.random2,
1829  sizeof(key_src->server.random2),
1830  client_sid,
1831  server_sid,
1832  (uint8_t *)key2.keys,
1833  sizeof(key2.keys));
1834 
1835  key2.n = 2;
1836 
1837  key2_print(&key2, key_type, "Master Encrypt", "Master Decrypt");
1838 
1839  /* check for weak keys */
1840  for (int i = 0; i < 2; ++i)
1841  {
1842  fixup_key(&key2.keys[i], key_type);
1843  if (!check_key(&key2.keys[i], key_type))
1844  {
1845  msg(D_TLS_ERRORS, "TLS Error: Bad dynamic key generated");
1846  goto exit;
1847  }
1848  }
1849 
1850  /* Initialize OpenSSL key contexts */
1851  int key_direction = server ? KEY_DIRECTION_INVERSE : KEY_DIRECTION_NORMAL;
1852  init_key_ctx_bi(key, &key2, key_direction, key_type, "Data Channel");
1853 
1854  /* Initialize implicit IVs */
1855  key_ctx_update_implicit_iv(&key->encrypt, key2.keys[(int)server].hmac,
1857  key_ctx_update_implicit_iv(&key->decrypt, key2.keys[1-(int)server].hmac,
1859 
1860  ret = true;
1861 
1862 exit:
1863  secure_memzero(&master, sizeof(master));
1864  secure_memzero(&key2, sizeof(key2));
1865 
1866  return ret;
1867 }
1868 
1869 static void
1870 key_ctx_update_implicit_iv(struct key_ctx *ctx, uint8_t *key, size_t key_len)
1871 {
1872  const cipher_kt_t *cipher_kt = cipher_ctx_get_cipher_kt(ctx->cipher);
1873 
1874  /* Only use implicit IV in AEAD cipher mode, where HMAC key is not used */
1875  if (cipher_kt_mode_aead(cipher_kt))
1876  {
1877  size_t impl_iv_len = 0;
1879  impl_iv_len = cipher_kt_iv_size(cipher_kt) - sizeof(packet_id_type);
1880  ASSERT(impl_iv_len <= OPENVPN_MAX_IV_LENGTH);
1881  ASSERT(impl_iv_len <= key_len);
1882  memcpy(ctx->implicit_iv, key, impl_iv_len);
1883  ctx->implicit_iv_len = impl_iv_len;
1884  }
1885 }
1886 
1887 bool
1888 tls_item_in_cipher_list(const char *item, const char *list)
1889 {
1890  char *tmp_ciphers = string_alloc(list, NULL);
1891  char *tmp_ciphers_orig = tmp_ciphers;
1892 
1893  const char *token = strtok(tmp_ciphers, ":");
1894  while (token)
1895  {
1896  if (0 == strcmp(token, item))
1897  {
1898  break;
1899  }
1900  token = strtok(NULL, ":");
1901  }
1902  free(tmp_ciphers_orig);
1903 
1904  return token != NULL;
1905 }
1906 
1907 void
1908 tls_poor_mans_ncp(struct options *o, const char *remote_ciphername)
1909 {
1910  if (o->ncp_enabled && remote_ciphername
1911  && 0 != strcmp(o->ciphername, remote_ciphername))
1912  {
1913  if (tls_item_in_cipher_list(remote_ciphername, o->ncp_ciphers))
1914  {
1915  o->ciphername = string_alloc(remote_ciphername, &o->gc);
1916  msg(D_TLS_DEBUG_LOW, "Using peer cipher '%s'", o->ciphername);
1917  }
1918  }
1919 }
1920 
1927 static bool
1929 {
1930  bool ret = false;
1931  struct key_state *ks = &session->key[KS_PRIMARY]; /* primary key */
1932  const struct session_id *client_sid = session->opt->server ?
1933  &ks->session_id_remote : &session->session_id;
1934  const struct session_id *server_sid = !session->opt->server ?
1935  &ks->session_id_remote : &session->session_id;
1936 
1937  ASSERT(ks->authenticated);
1938 
1939  ks->crypto_options.flags = session->opt->crypto_flags;
1941  &session->opt->key_type, ks->key_src, client_sid, server_sid,
1942  session->opt->server))
1943  {
1944  msg(D_TLS_ERRORS, "TLS Error: generate_key_expansion failed");
1945  goto cleanup;
1946  }
1948  &session->opt->renegotiate_bytes);
1949 
1950  ret = true;
1951 cleanup:
1952  secure_memzero(ks->key_src, sizeof(*ks->key_src));
1953  return ret;
1954 }
1955 
1956 bool
1958  struct options *options, struct frame *frame)
1959 {
1960  if (!session->opt->server
1961  && 0 != strcmp(options->ciphername, session->opt->config_ciphername)
1962  && !tls_item_in_cipher_list(options->ciphername, options->ncp_ciphers))
1963  {
1964  msg(D_TLS_ERRORS, "Error: pushed cipher not allowed - %s not in %s or %s",
1965  options->ciphername, session->opt->config_ciphername,
1966  options->ncp_ciphers);
1967  /* undo cipher push, abort connection setup */
1968  options->ciphername = session->opt->config_ciphername;
1969  return false;
1970  }
1971 
1972  if (strcmp(options->ciphername, session->opt->config_ciphername))
1973  {
1974  msg(D_HANDSHAKE, "Data Channel: using negotiated cipher '%s'",
1975  options->ciphername);
1976  if (options->keysize)
1977  {
1978  msg(D_HANDSHAKE, "NCP: overriding user-set keysize with default");
1979  options->keysize = 0;
1980  }
1981  }
1982 
1983  init_key_type(&session->opt->key_type, options->ciphername,
1984  options->authname, options->keysize, true, true);
1985 
1986  bool packet_id_long_form = cipher_kt_mode_ofb_cfb(session->opt->key_type.cipher);
1987  session->opt->crypto_flags &= ~(CO_PACKET_ID_LONG_FORM);
1988  if (packet_id_long_form)
1989  {
1991  }
1992 
1993  /* Update frame parameters: undo worst-case overhead, add actual overhead */
1995  crypto_adjust_frame_parameters(frame, &session->opt->key_type,
1996  options->replay, packet_id_long_form);
1997  frame_finalize(frame, options->ce.link_mtu_defined, options->ce.link_mtu,
1998  options->ce.tun_mtu_defined, options->ce.tun_mtu);
1999  frame_init_mssfix(frame, options);
2000  frame_print(frame, D_MTU_INFO, "Data Channel MTU parms");
2001 
2003 }
2004 
2005 static bool
2007  uint8_t *out,
2008  int outlen)
2009 {
2010  if (!rand_bytes(out, outlen))
2011  {
2012  msg(M_FATAL, "ERROR: Random number generator cannot obtain entropy for key generation [SSL]");
2013  }
2014  if (!buf_write(buf, out, outlen))
2015  {
2016  return false;
2017  }
2018  return true;
2019 }
2020 
2021 static bool
2023  struct buffer *buf,
2024  bool server)
2025 {
2026  struct key_source *k = &k2->client;
2027  if (server)
2028  {
2029  k = &k2->server;
2030  }
2031 
2032  CLEAR(*k);
2033 
2034  if (!server)
2035  {
2036  if (!random_bytes_to_buf(buf, k->pre_master, sizeof(k->pre_master)))
2037  {
2038  return false;
2039  }
2040  }
2041 
2042  if (!random_bytes_to_buf(buf, k->random1, sizeof(k->random1)))
2043  {
2044  return false;
2045  }
2046  if (!random_bytes_to_buf(buf, k->random2, sizeof(k->random2)))
2047  {
2048  return false;
2049  }
2050 
2051  return true;
2052 }
2053 
2054 static int
2056  struct buffer *buf,
2057  bool server)
2058 {
2059  struct key_source *k = &k2->client;
2060 
2061  if (!server)
2062  {
2063  k = &k2->server;
2064  }
2065 
2066  CLEAR(*k);
2067 
2068  if (server)
2069  {
2070  if (!buf_read(buf, k->pre_master, sizeof(k->pre_master)))
2071  {
2072  return 0;
2073  }
2074  }
2075 
2076  if (!buf_read(buf, k->random1, sizeof(k->random1)))
2077  {
2078  return 0;
2079  }
2080  if (!buf_read(buf, k->random2, sizeof(k->random2)))
2081  {
2082  return 0;
2083  }
2084 
2085  return 1;
2086 }
2087 
2088 static void
2090 {
2091  struct buffer *b;
2092 
2093  while ((b = buffer_list_peek(ks->paybuf)))
2094  {
2096  buffer_list_pop(ks->paybuf);
2097  }
2098 }
2099 
2100 /* true if no in/out acknowledgements pending */
2101 #define FULL_SYNC \
2102  (reliable_empty(ks->send_reliable) && reliable_ack_empty(ks->rec_ack))
2103 
2104 /*
2105  * Move the active key to the lame duck key and reinitialize the
2106  * active key.
2107  */
2108 static void
2110 {
2111  struct key_state *ks = &session->key[KS_PRIMARY]; /* primary key */
2112  struct key_state *ks_lame = &session->key[KS_LAME_DUCK]; /* retiring key */
2113 
2114  ks->must_die = now + session->opt->transition_window; /* remaining lifetime of old key */
2115  key_state_free(ks_lame, false);
2116  *ks_lame = *ks;
2117 
2118  key_state_init(session, ks);
2119  ks->session_id_remote = ks_lame->session_id_remote;
2120  ks->remote_addr = ks_lame->remote_addr;
2121 }
2122 
2123 /*
2124  * Read/write strings from/to a struct buffer with a u16 length prefix.
2125  */
2126 
2127 static bool
2129 {
2130  if (!buf_write_u16(buf, 0))
2131  {
2132  return false;
2133  }
2134  return true;
2135 }
2136 
2137 static bool
2138 write_string(struct buffer *buf, const char *str, const int maxlen)
2139 {
2140  const int len = strlen(str) + 1;
2141  if (len < 1 || (maxlen >= 0 && len > maxlen))
2142  {
2143  return false;
2144  }
2145  if (!buf_write_u16(buf, len))
2146  {
2147  return false;
2148  }
2149  if (!buf_write(buf, str, len))
2150  {
2151  return false;
2152  }
2153  return true;
2154 }
2155 
2156 static bool
2157 read_string(struct buffer *buf, char *str, const unsigned int capacity)
2158 {
2159  const int len = buf_read_u16(buf);
2160  if (len < 1 || len > (int)capacity)
2161  {
2162  return false;
2163  }
2164  if (!buf_read(buf, str, len))
2165  {
2166  return false;
2167  }
2168  str[len-1] = '\0';
2169  return true;
2170 }
2171 
2172 static char *
2174 {
2175  const int len = buf_read_u16(buf);
2176  char *str;
2177 
2178  if (len < 1)
2179  {
2180  return NULL;
2181  }
2182  str = (char *) malloc(len);
2183  check_malloc_return(str);
2184  if (!buf_read(buf, str, len))
2185  {
2186  free(str);
2187  return NULL;
2188  }
2189  str[len-1] = '\0';
2190  return str;
2191 }
2192 
2193 /*
2194  * Handle the reading and writing of key data to and from
2195  * the TLS control channel (cleartext).
2196  */
2197 
2198 static bool
2200 {
2201  struct key key;
2202  struct key_state *ks = &session->key[KS_PRIMARY]; /* primary key */
2203 
2204  ASSERT(session->opt->key_method == 1);
2205  ASSERT(buf_init(buf, 0));
2206 
2207  generate_key_random(&key, &session->opt->key_type);
2208  if (!check_key(&key, &session->opt->key_type))
2209  {
2210  msg(D_TLS_ERRORS, "TLS Error: Bad encrypting key generated");
2211  return false;
2212  }
2213 
2214  if (!write_key(&key, &session->opt->key_type, buf))
2215  {
2216  msg(D_TLS_ERRORS, "TLS Error: write_key failed");
2217  return false;
2218  }
2219 
2221  &session->opt->key_type, OPENVPN_OP_ENCRYPT,
2222  "Data Channel Encrypt");
2223  secure_memzero(&key, sizeof(key));
2224 
2225  /* send local options string */
2226  {
2227  const char *local_options = local_options_string(session);
2228  const int optlen = strlen(local_options) + 1;
2229  if (!buf_write(buf, local_options, optlen))
2230  {
2231  msg(D_TLS_ERRORS, "TLS Error: KM1 write options failed");
2232  return false;
2233  }
2234  }
2235 
2236  return true;
2237 }
2238 
2239 static bool
2241 {
2242  struct gc_arena gc = gc_new();
2243  bool ret = false;
2244 
2245  if (session->opt->push_peer_info_detail > 0)
2246  {
2247  struct env_set *es = session->opt->es;
2248  struct env_item *e;
2249  struct buffer out = alloc_buf_gc(512*3, &gc);
2250 
2251  /* push version */
2252  buf_printf(&out, "IV_VER=%s\n", PACKAGE_VERSION);
2253 
2254  /* push platform */
2255 #if defined(TARGET_LINUX)
2256  buf_printf(&out, "IV_PLAT=linux\n");
2257 #elif defined(TARGET_SOLARIS)
2258  buf_printf(&out, "IV_PLAT=solaris\n");
2259 #elif defined(TARGET_OPENBSD)
2260  buf_printf(&out, "IV_PLAT=openbsd\n");
2261 #elif defined(TARGET_DARWIN)
2262  buf_printf(&out, "IV_PLAT=mac\n");
2263 #elif defined(TARGET_NETBSD)
2264  buf_printf(&out, "IV_PLAT=netbsd\n");
2265 #elif defined(TARGET_FREEBSD)
2266  buf_printf(&out, "IV_PLAT=freebsd\n");
2267 #elif defined(TARGET_ANDROID)
2268  buf_printf(&out, "IV_PLAT=android\n");
2269 #elif defined(_WIN32)
2270  buf_printf(&out, "IV_PLAT=win\n");
2271 #endif
2272 
2273  /* support for P_DATA_V2 */
2274  buf_printf(&out, "IV_PROTO=2\n");
2275 
2276  /* support for Negotiable Crypto Paramters */
2277  if (session->opt->ncp_enabled
2278  && (session->opt->mode == MODE_SERVER || session->opt->pull))
2279  {
2280  buf_printf(&out, "IV_NCP=2\n");
2281  }
2282 
2283  /* push compression status */
2284 #ifdef USE_COMP
2285  comp_generate_peer_info_string(&session->opt->comp_options, &out);
2286 #endif
2287 
2288  if (session->opt->push_peer_info_detail >= 2)
2289  {
2290  /* push mac addr */
2291  struct route_gateway_info rgi;
2292  get_default_gateway(&rgi);
2293  if (rgi.flags & RGI_HWADDR_DEFINED)
2294  {
2295  buf_printf(&out, "IV_HWADDR=%s\n", format_hex_ex(rgi.hwaddr, 6, 0, 1, ":", &gc));
2296  }
2297  buf_printf(&out, "IV_SSL=%s\n", get_ssl_library_version() );
2298 #if defined(_WIN32)
2299  buf_printf(&out, "IV_PLAT_VER=%s\n", win32_version_string(&gc, false));
2300 #endif
2301  }
2302 
2303  /* push env vars that begin with UV_, IV_PLAT_VER and IV_GUI_VER */
2304  for (e = es->list; e != NULL; e = e->next)
2305  {
2306  if (e->string)
2307  {
2308  if ((((strncmp(e->string, "UV_", 3)==0
2309  || strncmp(e->string, "IV_PLAT_VER=", sizeof("IV_PLAT_VER=")-1)==0)
2310  && session->opt->push_peer_info_detail >= 2)
2311  || (strncmp(e->string,"IV_GUI_VER=",sizeof("IV_GUI_VER=")-1)==0))
2312  && buf_safe(&out, strlen(e->string)+1))
2313  {
2314  buf_printf(&out, "%s\n", e->string);
2315  }
2316  }
2317  }
2318 
2319  if (!write_string(buf, BSTR(&out), -1))
2320  {
2321  goto error;
2322  }
2323  }
2324  else
2325  {
2326  if (!write_empty_string(buf)) /* no peer info */
2327  {
2328  goto error;
2329  }
2330  }
2331  ret = true;
2332 
2333 error:
2334  gc_free(&gc);
2335  return ret;
2336 }
2337 
2338 static bool
2340 {
2341  struct key_state *ks = &session->key[KS_PRIMARY]; /* primary key */
2342 
2343  ASSERT(session->opt->key_method == 2);
2344  ASSERT(buf_init(buf, 0));
2345 
2346  /* write a uint32 0 */
2347  if (!buf_write_u32(buf, 0))
2348  {
2349  goto error;
2350  }
2351 
2352  /* write key_method + flags */
2353  if (!buf_write_u8(buf, (session->opt->key_method & KEY_METHOD_MASK)))
2354  {
2355  goto error;
2356  }
2357 
2358  /* write key source material */
2359  if (!key_source2_randomize_write(ks->key_src, buf, session->opt->server))
2360  {
2361  goto error;
2362  }
2363 
2364  /* write options string */
2365  {
2366  if (!write_string(buf, local_options_string(session), TLS_OPTIONS_LEN))
2367  {
2368  goto error;
2369  }
2370  }
2371 
2372  /* write username/password if specified */
2374  {
2375 #ifdef ENABLE_CLIENT_CR
2376  auth_user_pass_setup(session->opt->auth_user_pass_file, session->opt->sci);
2377 #else
2378  auth_user_pass_setup(session->opt->auth_user_pass_file, NULL);
2379 #endif
2380  if (!write_string(buf, auth_user_pass.username, -1))
2381  {
2382  goto error;
2383  }
2384  if (!write_string(buf, auth_user_pass.password, -1))
2385  {
2386  goto error;
2387  }
2388  /* if auth-nocache was specified, the auth_user_pass object reaches
2389  * a "complete" state only after having received the push-reply
2390  * message.
2391  * This is the case because auth-token statement in a push-reply would
2392  * invert its nocache.
2393  *
2394  * For this reason, skip the purge operation here if no push-reply
2395  * message has been received yet.
2396  *
2397  * This normally happens upon first negotiation only.
2398  */
2400  {
2402  }
2403  }
2404  else
2405  {
2406  if (!write_empty_string(buf)) /* no username */
2407  {
2408  goto error;
2409  }
2410  if (!write_empty_string(buf)) /* no password */
2411  {
2412  goto error;
2413  }
2414  }
2415 
2416  if (!push_peer_info(buf, session))
2417  {
2418  goto error;
2419  }
2420 
2421  /* Generate tunnel keys if we're a TLS server.
2422  * If we're a p2mp server and IV_NCP >= 2 is negotiated, the first key
2423  * generation is postponed until after the pull/push, so we can process pushed
2424  * cipher directives.
2425  */
2426  if (session->opt->server && !(session->opt->ncp_enabled
2427  && session->opt->mode == MODE_SERVER && ks->key_id <= 0))
2428  {
2429  if (ks->authenticated)
2430  {
2432  {
2433  msg(D_TLS_ERRORS, "TLS Error: server generate_key_expansion failed");
2434  goto error;
2435  }
2436  }
2437  }
2438 
2439  return true;
2440 
2441 error:
2442  msg(D_TLS_ERRORS, "TLS Error: Key Method #2 write failed");
2443  secure_memzero(ks->key_src, sizeof(*ks->key_src));
2444  return false;
2445 }
2446 
2447 static bool
2449 {
2450  int status;
2451  struct key key;
2452  struct key_state *ks = &session->key[KS_PRIMARY]; /* primary key */
2453 
2454  ASSERT(session->opt->key_method == 1);
2455 
2456  if (!session->verified)
2457  {
2458  msg(D_TLS_ERRORS,
2459  "TLS Error: Certificate verification failed (key-method 1)");
2460  goto error;
2461  }
2462 
2463  status = read_key(&key, &session->opt->key_type, buf);
2464  if (status != 1)
2465  {
2466  msg(D_TLS_ERRORS,
2467  "TLS Error: Error reading data channel key from plaintext buffer");
2468  goto error;
2469  }
2470 
2471  if (!check_key(&key, &session->opt->key_type))
2472  {
2473  msg(D_TLS_ERRORS, "TLS Error: Bad decrypting key received from peer");
2474  goto error;
2475  }
2476 
2477  if (buf->len < 1)
2478  {
2479  msg(D_TLS_ERRORS, "TLS Error: Missing options string");
2480  goto error;
2481  }
2482 
2483 #ifdef ENABLE_OCC
2484  /* compare received remote options string
2485  * with our locally computed options string */
2486  if (!session->opt->disable_occ
2487  && !options_cmp_equal_safe((char *) BPTR(buf), session->opt->remote_options, buf->len))
2488  {
2489  options_warning_safe((char *) BPTR(buf), session->opt->remote_options, buf->len);
2490  }
2491 #endif
2492 
2493  buf_clear(buf);
2494 
2496  &session->opt->key_type, OPENVPN_OP_DECRYPT,
2497  "Data Channel Decrypt");
2498  secure_memzero(&key, sizeof(key));
2499  ks->authenticated = true;
2500  return true;
2501 
2502 error:
2503  buf_clear(buf);
2504  secure_memzero(&key, sizeof(key));
2505  return false;
2506 }
2507 
2508 static bool
2509 key_method_2_read(struct buffer *buf, struct tls_multi *multi, struct tls_session *session)
2510 {
2511  struct key_state *ks = &session->key[KS_PRIMARY]; /* primary key */
2512 
2513  int key_method_flags;
2514  bool username_status, password_status;
2515 
2516  struct gc_arena gc = gc_new();
2517  char *options;
2518  struct user_pass *up = NULL;
2519 
2520  /* allocate temporary objects */
2521  ALLOC_ARRAY_CLEAR_GC(options, char, TLS_OPTIONS_LEN, &gc);
2522 
2523  ASSERT(session->opt->key_method == 2);
2524 
2525  /* discard leading uint32 */
2526  if (!buf_advance(buf, 4))
2527  {
2528  msg(D_TLS_ERRORS, "TLS ERROR: Plaintext buffer too short (%d bytes).",
2529  buf->len);
2530  goto error;
2531  }
2532 
2533  /* get key method */
2534  key_method_flags = buf_read_u8(buf);
2535  if ((key_method_flags & KEY_METHOD_MASK) != 2)
2536  {
2537  msg(D_TLS_ERRORS,
2538  "TLS ERROR: Unknown key_method/flags=%d received from remote host",
2539  key_method_flags);
2540  goto error;
2541  }
2542 
2543  /* get key source material (not actual keys yet) */
2544  if (!key_source2_read(ks->key_src, buf, session->opt->server))
2545  {
2546  msg(D_TLS_ERRORS, "TLS Error: Error reading remote data channel key source entropy from plaintext buffer");
2547  goto error;
2548  }
2549 
2550  /* get options */
2551  if (!read_string(buf, options, TLS_OPTIONS_LEN))
2552  {
2553  msg(D_TLS_ERRORS, "TLS Error: Failed to read required OCC options string");
2554  goto error;
2555  }
2556 
2557  ks->authenticated = false;
2558 
2559  /* always extract username + password fields from buf, even if not
2560  * authenticating for it, because otherwise we can't get at the
2561  * peer_info data which follows behind
2562  */
2563  ALLOC_OBJ_CLEAR_GC(up, struct user_pass, &gc);
2564  username_status = read_string(buf, up->username, USER_PASS_LEN);
2565  password_status = read_string(buf, up->password, USER_PASS_LEN);
2566 
2567 #if P2MP_SERVER
2568  /* get peer info from control channel */
2569  free(multi->peer_info);
2570  multi->peer_info = read_string_alloc(buf);
2571  if (multi->peer_info)
2572  {
2573  output_peer_info_env(session->opt->es, multi->peer_info);
2574  }
2575 
2576  free(multi->remote_ciphername);
2577  multi->remote_ciphername =
2578  options_string_extract_option(options, "cipher", NULL);
2579 
2580  if (tls_peer_info_ncp_ver(multi->peer_info) < 2)
2581  {
2582  /* Peer does not support NCP, but leave NCP enabled if the local and
2583  * remote cipher do not match to attempt 'poor-man's NCP'.
2584  */
2585  if (multi->remote_ciphername == NULL
2586  || 0 == strcmp(multi->remote_ciphername, multi->opt.config_ciphername))
2587  {
2588  session->opt->ncp_enabled = false;
2589  }
2590  }
2591 #endif /* if P2MP_SERVER */
2592 
2593  if (tls_session_user_pass_enabled(session))
2594  {
2595  /* Perform username/password authentication */
2596  if (!username_status || !password_status)
2597  {
2598  CLEAR(*up);
2599  if (!(session->opt->ssl_flags & SSLF_AUTH_USER_PASS_OPTIONAL))
2600  {
2601  msg(D_TLS_ERRORS, "TLS Error: Auth Username/Password was not provided by peer");
2602  goto error;
2603  }
2604  }
2605 
2606  verify_user_pass(up, multi, session);
2607  }
2608  else
2609  {
2610  /* Session verification should have occurred during TLS negotiation*/
2611  if (!session->verified)
2612  {
2613  msg(D_TLS_ERRORS,
2614  "TLS Error: Certificate verification failed (key-method 2)");
2615  goto error;
2616  }
2617  ks->authenticated = true;
2618  }
2619 
2620  /* clear username and password from memory */
2621  secure_memzero(up, sizeof(*up));
2622 
2623  /* Perform final authentication checks */
2624  if (ks->authenticated)
2625  {
2626  verify_final_auth_checks(multi, session);
2627  }
2628 
2629 #ifdef ENABLE_OCC
2630  /* check options consistency */
2631  if (!session->opt->disable_occ
2632  && !options_cmp_equal(options, session->opt->remote_options))
2633  {
2634  options_warning(options, session->opt->remote_options);
2635  if (session->opt->ssl_flags & SSLF_OPT_VERIFY)
2636  {
2637  msg(D_TLS_ERRORS, "Option inconsistency warnings triggering disconnect due to --opt-verify");
2638  ks->authenticated = false;
2639  }
2640  }
2641 #endif
2642 
2643  buf_clear(buf);
2644 
2645  /*
2646  * Call OPENVPN_PLUGIN_TLS_FINAL plugin if defined, for final
2647  * veto opportunity over authentication decision.
2648  */
2650  {
2652 
2653  if (plugin_call(session->opt->plugins, OPENVPN_PLUGIN_TLS_FINAL, NULL, NULL, session->opt->es) != OPENVPN_PLUGIN_FUNC_SUCCESS)
2654  {
2655  ks->authenticated = false;
2656  }
2657 
2658  setenv_del(session->opt->es, "exported_keying_material");
2659  }
2660 
2661  /*
2662  * Generate tunnel keys if we're a client.
2663  * If --pull is enabled, the first key generation is postponed until after the
2664  * pull/push, so we can process pushed cipher directives.
2665  */
2666  if (!session->opt->server && (!session->opt->pull || ks->key_id > 0))
2667  {
2669  {
2670  msg(D_TLS_ERRORS, "TLS Error: client generate_key_expansion failed");
2671  goto error;
2672  }
2673  }
2674 
2675  gc_free(&gc);
2676  return true;
2677 
2678 error:
2679  secure_memzero(ks->key_src, sizeof(*ks->key_src));
2680  if (up)
2681  {
2682  secure_memzero(up, sizeof(*up));
2683  }
2684  buf_clear(buf);
2685  gc_free(&gc);
2686  return false;
2687 }
2688 
2689 static int
2691 {
2692  int ret = o->handshake_window;
2693  const int r2 = o->renegotiate_seconds / 2;
2694 
2695  if (o->renegotiate_seconds && r2 < ret)
2696  {
2697  ret = r2;
2698  }
2699  return ret;
2700 }
2701 
2702 /*
2703  * This is the primary routine for processing TLS stuff inside the
2704  * the main event loop. When this routine exits
2705  * with non-error status, it will set *wakeup to the number of seconds
2706  * when it wants to be called again.
2707  *
2708  * Return value is true if we have placed a packet in *to_link which we
2709  * want to send to our peer.
2710  */
2711 static bool
2712 tls_process(struct tls_multi *multi,
2713  struct tls_session *session,
2714  struct buffer *to_link,
2715  struct link_socket_actual **to_link_addr,
2716  struct link_socket_info *to_link_socket_info,
2717  interval_t *wakeup)
2718 {
2719  struct gc_arena gc = gc_new();
2720  struct buffer *buf;
2721  bool state_change = false;
2722  bool active = false;
2723  struct key_state *ks = &session->key[KS_PRIMARY]; /* primary key */
2724  struct key_state *ks_lame = &session->key[KS_LAME_DUCK]; /* retiring key */
2725 
2726  /* Make sure we were initialized and that we're not in an error state */
2727  ASSERT(ks->state != S_UNDEF);
2728  ASSERT(ks->state != S_ERROR);
2729  ASSERT(session_id_defined(&session->session_id));
2730 
2731  /* Should we trigger a soft reset? -- new key, keeps old key for a while */
2732  if (ks->state >= S_ACTIVE
2733  && ((session->opt->renegotiate_seconds
2734  && now >= ks->established + session->opt->renegotiate_seconds)
2735  || (session->opt->renegotiate_bytes > 0
2736  && ks->n_bytes >= session->opt->renegotiate_bytes)
2737  || (session->opt->renegotiate_packets
2738  && ks->n_packets >= session->opt->renegotiate_packets)
2740  {
2741  msg(D_TLS_DEBUG_LOW, "TLS: soft reset sec=%d/%d bytes=" counter_format
2742  "/%d pkts=" counter_format "/%d",
2743  (int) (now - ks->established), session->opt->renegotiate_seconds,
2744  ks->n_bytes, session->opt->renegotiate_bytes,
2745  ks->n_packets, session->opt->renegotiate_packets);
2746  key_state_soft_reset(session);
2747  }
2748 
2749  /* Kill lame duck key transition_window seconds after primary key negotiation */
2750  if (lame_duck_must_die(session, wakeup))
2751  {
2752  key_state_free(ks_lame, true);
2753  msg(D_TLS_DEBUG_LOW, "TLS: tls_process: killed expiring key");
2754  }
2755 
2756  do
2757  {
2758  update_time();
2759 
2760  dmsg(D_TLS_DEBUG, "TLS: tls_process: chg=%d ks=%s lame=%s to_link->len=%d wakeup=%d",
2761  state_change,
2762  state_name(ks->state),
2763  state_name(ks_lame->state),
2764  to_link->len,
2765  *wakeup);
2766 
2767  state_change = false;
2768 
2769  /*
2770  * TLS activity is finished once we get to S_ACTIVE,
2771  * though we will still process acknowledgements.
2772  *
2773  * CHANGED with 2.0 -> now we may send tunnel configuration
2774  * info over the control channel.
2775  */
2776 
2777  /* Initial handshake */
2778  if (ks->state == S_INITIAL)
2779  {
2781  if (buf)
2782  {
2783  ks->must_negotiate = now + session->opt->handshake_window;
2785 
2786  /* null buffer */
2789 
2790  ks->state = S_PRE_START;
2791  state_change = true;
2792  dmsg(D_TLS_DEBUG, "TLS: Initial Handshake, sid=%s",
2793  session_id_print(&session->session_id, &gc));
2794 
2795 #ifdef ENABLE_MANAGEMENT
2797  {
2800  NULL,
2801  NULL,
2802  NULL,
2803  NULL,
2804  NULL);
2805  }
2806 #endif
2807  }
2808  }
2809 
2810  /* Are we timed out on receive? */
2811  if (now >= ks->must_negotiate)
2812  {
2813  if (ks->state < S_ACTIVE)
2814  {
2815  msg(D_TLS_ERRORS,
2816  "TLS Error: TLS key negotiation failed to occur within %d seconds (check your network connectivity)",
2817  session->opt->handshake_window);
2818  goto error;
2819  }
2820  else /* assume that ks->state == S_ACTIVE */
2821  {
2822  dmsg(D_TLS_DEBUG_MED, "STATE S_NORMAL_OP");
2823  ks->state = S_NORMAL_OP;
2824  ks->must_negotiate = 0;
2825  }
2826  }
2827 
2828  /* Wait for Initial Handshake ACK */
2829  if (ks->state == S_PRE_START && FULL_SYNC)
2830  {
2831  ks->state = S_START;
2832  state_change = true;
2833 
2834  /*
2835  * Attempt CRL reload before TLS negotiation. Won't be performed if
2836  * the file was not modified since the last reload
2837  */
2838  if (session->opt->crl_file
2839  && !(session->opt->ssl_flags & SSLF_CRL_VERIFY_DIR))
2840  {
2841  tls_ctx_reload_crl(&session->opt->ssl_ctx,
2842  session->opt->crl_file, session->opt->crl_file_inline);
2843  }
2844 
2845  /* New connection, remove any old X509 env variables */
2846  tls_x509_clear_env(session->opt->es);
2847 
2848  dmsg(D_TLS_DEBUG_MED, "STATE S_START");
2849  }
2850 
2851  /* Wait for ACK */
2852  if (((ks->state == S_GOT_KEY && !session->opt->server)
2853  || (ks->state == S_SENT_KEY && session->opt->server)))
2854  {
2855  if (FULL_SYNC)
2856  {
2857  ks->established = now;
2858  dmsg(D_TLS_DEBUG_MED, "STATE S_ACTIVE");
2860  {
2861  print_details(&ks->ks_ssl, "Control Channel:");
2862  }
2863  state_change = true;
2864  ks->state = S_ACTIVE;
2865  INCR_SUCCESS;
2866 
2867  /* Set outgoing address for data channel packets */
2868  link_socket_set_outgoing_addr(NULL, to_link_socket_info, &ks->remote_addr, session->common_name, session->opt->es);
2869 
2870  /* Flush any payload packets that were buffered before our state transitioned to S_ACTIVE */
2872 
2873 #ifdef MEASURE_TLS_HANDSHAKE_STATS
2874  show_tls_performance_stats();
2875 #endif
2876  }
2877  }
2878 
2879  /* Reliable buffer to outgoing TCP/UDP (send up to CONTROL_SEND_ACK_MAX ACKs
2880  * for previously received packets) */
2881  if (!to_link->len && reliable_can_send(ks->send_reliable))
2882  {
2883  int opcode;
2884  struct buffer b;
2885 
2886  buf = reliable_send(ks->send_reliable, &opcode);
2887  ASSERT(buf);
2888  b = *buf;
2889  INCR_SENT;
2890 
2891  write_control_auth(session, ks, &b, to_link_addr, opcode,
2892  CONTROL_SEND_ACK_MAX, true);
2893  *to_link = b;
2894  active = true;
2895  state_change = true;
2896  dmsg(D_TLS_DEBUG, "Reliable -> TCP/UDP");
2897  break;
2898  }
2899 
2900  /* Write incoming ciphertext to TLS object */
2902  if (buf)
2903  {
2904  int status = 0;
2905  if (buf->len)
2906  {
2907  status = key_state_write_ciphertext(&ks->ks_ssl, buf);
2908  if (status == -1)
2909  {
2910  msg(D_TLS_ERRORS,
2911  "TLS Error: Incoming Ciphertext -> TLS object write error");
2912  goto error;
2913  }
2914  }
2915  else
2916  {
2917  status = 1;
2918  }
2919  if (status == 1)
2920  {
2921  reliable_mark_deleted(ks->rec_reliable, buf, true);
2922  state_change = true;
2923  dmsg(D_TLS_DEBUG, "Incoming Ciphertext -> TLS");
2924  }
2925  }
2926 
2927  /* Read incoming plaintext from TLS object */
2928  buf = &ks->plaintext_read_buf;
2929  if (!buf->len)
2930  {
2931  int status;
2932 
2933  ASSERT(buf_init(buf, 0));
2935  update_time();
2936  if (status == -1)
2937  {
2938  msg(D_TLS_ERRORS, "TLS Error: TLS object -> incoming plaintext read error");
2939  goto error;
2940  }
2941  if (status == 1)
2942  {
2943  state_change = true;
2944  dmsg(D_TLS_DEBUG, "TLS -> Incoming Plaintext");
2945 
2946  /* More data may be available, wake up again asap to check. */
2947  *wakeup = 0;
2948  }
2949  }
2950 
2951  /* Send Key */
2952  buf = &ks->plaintext_write_buf;
2953  if (!buf->len && ((ks->state == S_START && !session->opt->server)
2954  || (ks->state == S_GOT_KEY && session->opt->server)))
2955  {
2956  if (session->opt->key_method == 1)
2957  {
2958  if (!key_method_1_write(buf, session))
2959  {
2960  goto error;
2961  }
2962  }
2963  else if (session->opt->key_method == 2)
2964  {
2965  if (!key_method_2_write(buf, session))
2966  {
2967  goto error;
2968  }
2969  }
2970  else
2971  {
2972  ASSERT(0);
2973  }
2974 
2975  state_change = true;
2976  dmsg(D_TLS_DEBUG_MED, "STATE S_SENT_KEY");
2977  ks->state = S_SENT_KEY;
2978  }
2979 
2980  /* Receive Key */
2981  buf = &ks->plaintext_read_buf;
2982  if (buf->len
2983  && ((ks->state == S_SENT_KEY && !session->opt->server)
2984  || (ks->state == S_START && session->opt->server)))
2985  {
2986  if (session->opt->key_method == 1)
2987  {
2988  if (!key_method_1_read(buf, session))
2989  {
2990  goto error;
2991  }
2992  }
2993  else if (session->opt->key_method == 2)
2994  {
2995  if (!key_method_2_read(buf, multi, session))
2996  {
2997  goto error;
2998  }
2999  }
3000  else
3001  {
3002  ASSERT(0);
3003  }
3004 
3005  state_change = true;
3006  dmsg(D_TLS_DEBUG_MED, "STATE S_GOT_KEY");
3007  ks->state = S_GOT_KEY;
3008  }
3009 
3010  /* Write outgoing plaintext to TLS object */
3011  buf = &ks->plaintext_write_buf;
3012  if (buf->len)
3013  {
3014  int status = key_state_write_plaintext(&ks->ks_ssl, buf);
3015  if (status == -1)
3016  {
3017  msg(D_TLS_ERRORS,
3018  "TLS ERROR: Outgoing Plaintext -> TLS object write error");
3019  goto error;
3020  }
3021  if (status == 1)
3022  {
3023  state_change = true;
3024  dmsg(D_TLS_DEBUG, "Outgoing Plaintext -> TLS");
3025  }
3026  }
3027 
3028  /* Outgoing Ciphertext to reliable buffer */
3029  if (ks->state >= S_START)
3030  {
3032  if (buf)
3033  {
3035  if (status == -1)
3036  {
3037  msg(D_TLS_ERRORS,
3038  "TLS Error: Ciphertext -> reliable TCP/UDP transport read error");
3039  goto error;
3040  }
3041  if (status == 1)
3042  {
3045  state_change = true;
3046  dmsg(D_TLS_DEBUG, "Outgoing Ciphertext -> Reliable");
3047  }
3048  }
3049  }
3050  }
3051  while (state_change);
3052 
3053  update_time();
3054 
3055  /* Send 1 or more ACKs (each received control packet gets one ACK) */
3056  if (!to_link->len && !reliable_ack_empty(ks->rec_ack))
3057  {
3058  struct buffer buf = ks->ack_write_buf;
3059  ASSERT(buf_init(&buf, FRAME_HEADROOM(&multi->opt.frame)));
3060  write_control_auth(session, ks, &buf, to_link_addr, P_ACK_V1,
3061  RELIABLE_ACK_SIZE, false);
3062  *to_link = buf;
3063  active = true;
3064  dmsg(D_TLS_DEBUG, "Dedicated ACK -> TCP/UDP");
3065  }
3066 
3067  /* When should we wake up again? */
3068  {
3069  if (ks->state >= S_INITIAL)
3070  {
3071  compute_earliest_wakeup(wakeup,
3073 
3074  if (ks->must_negotiate)
3075  {
3077  }
3078  }
3079 
3080  if (ks->established && session->opt->renegotiate_seconds)
3081  {
3082  compute_earliest_wakeup(wakeup,
3083  ks->established + session->opt->renegotiate_seconds - now);
3084  }
3085 
3086  /* prevent event-loop spinning by setting minimum wakeup of 1 second */
3087  if (*wakeup <= 0)
3088  {
3089  *wakeup = 1;
3090 
3091  /* if we had something to send to remote, but to_link was busy,
3092  * let caller know we need to be called again soon */
3093  active = true;
3094  }
3095 
3096  dmsg(D_TLS_DEBUG, "TLS: tls_process: timeout set to %d", *wakeup);
3097 
3098  gc_free(&gc);
3099  return active;
3100  }
3101 
3102 error:
3103  tls_clear_error();
3104  ks->state = S_ERROR;
3105  msg(D_TLS_ERRORS, "TLS Error: TLS handshake failed");
3106  INCR_ERROR;
3107  gc_free(&gc);
3108  return false;
3109 }
3110 
3111 /*
3112  * Called by the top-level event loop.
3113  *
3114  * Basically decides if we should call tls_process for
3115  * the active or untrusted sessions.
3116  */
3117 
3118 int
3120  struct buffer *to_link,
3121  struct link_socket_actual **to_link_addr,
3122  struct link_socket_info *to_link_socket_info,
3123  interval_t *wakeup)
3124 {
3125  struct gc_arena gc = gc_new();
3126  int i;
3127  int active = TLSMP_INACTIVE;
3128  bool error = false;
3129  int tas;
3130 
3132 
3133  tls_clear_error();
3134 
3135  /*
3136  * Process each session object having state of S_INITIAL or greater,
3137  * and which has a defined remote IP addr.
3138  */
3139 
3140  for (i = 0; i < TM_SIZE; ++i)
3141  {
3142  struct tls_session *session = &multi->session[i];
3143  struct key_state *ks = &session->key[KS_PRIMARY];
3144  struct key_state *ks_lame = &session->key[KS_LAME_DUCK];
3145 
3146  /* set initial remote address */
3147  if (i == TM_ACTIVE && ks->state == S_INITIAL
3148  && link_socket_actual_defined(&to_link_socket_info->lsa->actual))
3149  {
3150  ks->remote_addr = to_link_socket_info->lsa->actual;
3151  }
3152 
3153  dmsg(D_TLS_DEBUG,
3154  "TLS: tls_multi_process: i=%d state=%s, mysid=%s, stored-sid=%s, stored-ip=%s",
3155  i,
3156  state_name(ks->state),
3157  session_id_print(&session->session_id, &gc),
3160 
3162  {
3163  struct link_socket_actual *tla = NULL;
3164 
3165  update_time();
3166 
3167  if (tls_process(multi, session, to_link, &tla,
3168  to_link_socket_info, wakeup))
3169  {
3170  active = TLSMP_ACTIVE;
3171  }
3172 
3173  /*
3174  * If tls_process produced an outgoing packet,
3175  * return the link_socket_actual object (which
3176  * contains the outgoing address).
3177  */
3178  if (tla)
3179  {
3180  multi->to_link_addr = *tla;
3181  *to_link_addr = &multi->to_link_addr;
3182  }
3183 
3184  /*
3185  * If tls_process hits an error:
3186  * (1) If the session has an unexpired lame duck key, preserve it.
3187  * (2) Reinitialize the session.
3188  * (3) Increment soft error count
3189  */
3190  if (ks->state == S_ERROR)
3191  {
3192  ++multi->n_soft_errors;
3193 
3194  if (i == TM_ACTIVE)
3195  {
3196  error = true;
3197  }
3198 
3199  if (i == TM_ACTIVE
3200  && ks_lame->state >= S_ACTIVE
3201  && !multi->opt.single_session)
3202  {
3203  move_session(multi, TM_LAME_DUCK, TM_ACTIVE, true);
3204  }
3205  else
3206  {
3207  reset_session(multi, session);
3208  }
3209  }
3210  }
3211  }
3212 
3213  update_time();
3214 
3216 
3217  /*
3218  * If lame duck session expires, kill it.
3219  */
3220  if (lame_duck_must_die(&multi->session[TM_LAME_DUCK], wakeup))
3221  {
3222  tls_session_free(&multi->session[TM_LAME_DUCK], true);
3223  msg(D_TLS_DEBUG_LOW, "TLS: tls_multi_process: killed expiring key");
3224  }
3225 
3226  /*
3227  * If untrusted session achieves TLS authentication,
3228  * move it to active session, usurping any prior session.
3229  *
3230  * A semi-trusted session is one in which the certificate authentication
3231  * succeeded (if cert verification is enabled) but the username/password
3232  * verification failed. A semi-trusted session can forward data on the
3233  * TLS control channel but not on the tunnel channel.
3234  */
3235  if (DECRYPT_KEY_ENABLED(multi, &multi->session[TM_UNTRUSTED].key[KS_PRIMARY]))
3236  {
3237  move_session(multi, TM_ACTIVE, TM_UNTRUSTED, true);
3238  msg(D_TLS_DEBUG_LOW, "TLS: tls_multi_process: untrusted session promoted to %strusted",
3239  tas == TLS_AUTHENTICATION_SUCCEEDED ? "" : "semi-");
3240  }
3241 
3242  /*
3243  * A hard error means that TM_ACTIVE hit an S_ERROR state and that no
3244  * other key state objects are S_ACTIVE or higher.
3245  */
3246  if (error)
3247  {
3248  for (i = 0; i < (int) SIZE(multi->key_scan); ++i)
3249  {
3250  if (multi->key_scan[i]->state >= S_ACTIVE)
3251  {
3252  goto nohard;
3253  }
3254  }
3255  ++multi->n_hard_errors;
3256  }
3257 nohard:
3258 
3259 #ifdef ENABLE_DEBUG
3260  /* DEBUGGING -- flood peer with repeating connection attempts */
3261  {
3262  const int throw_level = GREMLIN_CONNECTION_FLOOD_LEVEL(multi->opt.gremlin);
3263  if (throw_level)
3264  {
3265  for (i = 0; i < (int) SIZE(multi->key_scan); ++i)
3266  {
3267  if (multi->key_scan[i]->state >= throw_level)
3268  {
3269  ++multi->n_hard_errors;
3270  ++multi->n_soft_errors;
3271  }
3272  }
3273  }
3274  }
3275 #endif
3276 
3277  perf_pop();
3278  gc_free(&gc);
3279 
3280  return (tas == TLS_AUTHENTICATION_FAILED) ? TLSMP_KILL : active;
3281 }
3282 
3283 /*
3284  * Pre and post-process the encryption & decryption buffers in order
3285  * to implement a multiplexed TLS channel over the TCP/UDP port.
3286  */
3287 
3288 /*
3289  *
3290  * When we are in TLS mode, this is the first routine which sees
3291  * an incoming packet.
3292  *
3293  * If it's a data packet, we set opt so that our caller can
3294  * decrypt it. We also give our caller the appropriate decryption key.
3295  *
3296  * If it's a control packet, we authenticate it and process it,
3297  * possibly creating a new tls_session if it represents the
3298  * first packet of a new session. For control packets, we will
3299  * also zero the size of *buf so that our caller ignores the
3300  * packet on our return.
3301  *
3302  * Note that openvpn only allows one active session at a time,
3303  * so a new session (once authenticated) will always usurp
3304  * an old session.
3305  *
3306  * Return true if input was an authenticated control channel
3307  * packet.
3308  *
3309  * If we are running in TLS thread mode, all public routines
3310  * below this point must be called with the L_TLS lock held.
3311  */
3312 
3313 bool
3315  const struct link_socket_actual *from,
3316  struct buffer *buf,
3317  struct crypto_options **opt,
3318  bool floated,
3319  const uint8_t **ad_start)
3320 {
3321  struct gc_arena gc = gc_new();
3322  bool ret = false;
3323 
3324  if (buf->len > 0)
3325  {
3326  int i;
3327  int op;
3328  int key_id;
3329 
3330  /* get opcode and key ID */
3331  {
3332  uint8_t c = *BPTR(buf);
3333  op = c >> P_OPCODE_SHIFT;
3334  key_id = c & P_KEY_ID_MASK;
3335  }
3336 
3337  if ((op == P_DATA_V1) || (op == P_DATA_V2))
3338  {
3339  /* data channel packet */
3340  for (i = 0; i < KEY_SCAN_SIZE; ++i)
3341  {
3342  struct key_state *ks = multi->key_scan[i];
3343 
3344  /*
3345  * This is the basic test of TLS state compatibility between a local OpenVPN
3346  * instance and its remote peer.
3347  *
3348  * If the test fails, it tells us that we are getting a packet from a source
3349  * which claims reference to a prior negotiated TLS session, but the local
3350  * OpenVPN instance has no memory of such a negotiation.
3351  *
3352  * It almost always occurs on UDP sessions when the passive side of the
3353  * connection is restarted without the active side restarting as well (the
3354  * passive side is the server which only listens for the connections, the
3355  * active side is the client which initiates connections).
3356  */
3357  if (DECRYPT_KEY_ENABLED(multi, ks)
3358  && key_id == ks->key_id
3359  && ks->authenticated
3360 #ifdef ENABLE_DEF_AUTH
3361  && !ks->auth_deferred
3362 #endif
3363  && (floated || link_socket_actual_match(from, &ks->remote_addr)))
3364  {
3366  {
3368  "Key %s [%d] not initialized (yet), dropping packet.",
3369  print_link_socket_actual(from, &gc), key_id);
3370  goto error_lite;
3371  }
3372 
3373  /* return appropriate data channel decrypt key in opt */
3374  *opt = &ks->crypto_options;
3375  if (op == P_DATA_V2)
3376  {
3377  *ad_start = BPTR(buf);
3378  }
3379  ASSERT(buf_advance(buf, 1));
3380  if (op == P_DATA_V1)
3381  {
3382  *ad_start = BPTR(buf);
3383  }
3384  else if (op == P_DATA_V2)
3385  {
3386  if (buf->len < 4)
3387  {
3388  msg(D_TLS_ERRORS, "Protocol error: received P_DATA_V2 from %s but length is < 4",
3389  print_link_socket_actual(from, &gc));
3390  goto error;
3391  }
3392  ASSERT(buf_advance(buf, 3));
3393  }
3394 
3395  ++ks->n_packets;
3396  ks->n_bytes += buf->len;
3398  "TLS: tls_pre_decrypt, key_id=%d, IP=%s",
3399  key_id, print_link_socket_actual(from, &gc));
3400  gc_free(&gc);
3401  return ret;
3402  }
3403  }
3404 
3405  msg(D_TLS_ERRORS,
3406  "TLS Error: local/remote TLS keys are out of sync: %s [%d]",
3407  print_link_socket_actual(from, &gc), key_id);
3408  goto error_lite;
3409  }
3410  else /* control channel packet */
3411  {
3412  bool do_burst = false;
3413  bool new_link = false;
3414  struct session_id sid; /* remote session ID */
3415 
3416  /* verify legal opcode */
3417  if (op < P_FIRST_OPCODE || op > P_LAST_OPCODE)
3418  {
3419  msg(D_TLS_ERRORS,
3420  "TLS Error: unknown opcode received from %s op=%d",
3421  print_link_socket_actual(from, &gc), op);
3422  goto error;
3423  }
3424 
3425  /* hard reset ? */
3426  if (is_hard_reset(op, 0))
3427  {
3428  /* verify client -> server or server -> client connection */
3429  if (((op == P_CONTROL_HARD_RESET_CLIENT_V1
3430  || op == P_CONTROL_HARD_RESET_CLIENT_V2) && !multi->opt.server)
3432  || op == P_CONTROL_HARD_RESET_SERVER_V2) && multi->opt.server))
3433  {
3434  msg(D_TLS_ERRORS,
3435  "TLS Error: client->client or server->server connection attempted from %s",
3436  print_link_socket_actual(from, &gc));
3437  goto error;
3438  }
3439  }
3440 
3441  /*
3442  * Authenticate Packet
3443  */
3444  dmsg(D_TLS_DEBUG, "TLS: control channel, op=%s, IP=%s",
3446 
3447  /* get remote session-id */
3448  {
3449  struct buffer tmp = *buf;
3450  buf_advance(&tmp, 1);
3451  if (!session_id_read(&sid, &tmp) || !session_id_defined(&sid))
3452  {
3453  msg(D_TLS_ERRORS,
3454  "TLS Error: session-id not found in packet from %s",
3455  print_link_socket_actual(from, &gc));
3456  goto error;
3457  }
3458  }
3459 
3460  /* use session ID to match up packet with appropriate tls_session object */
3461  for (i = 0; i < TM_SIZE; ++i)
3462  {
3463  struct tls_session *session = &multi->session[i];
3464  struct key_state *ks = &session->key[KS_PRIMARY];
3465 
3466  dmsg(D_TLS_DEBUG,
3467  "TLS: initial packet test, i=%d state=%s, mysid=%s, rec-sid=%s, rec-ip=%s, stored-sid=%s, stored-ip=%s",
3468  i,
3469  state_name(ks->state),
3470  session_id_print(&session->session_id, &gc),
3471  session_id_print(&sid, &gc),
3472  print_link_socket_actual(from, &gc),
3475 
3476  if (session_id_equal(&ks->session_id_remote, &sid))
3477  /* found a match */
3478  {
3479  if (i == TM_LAME_DUCK)
3480  {
3481  msg(D_TLS_ERRORS,
3482  "TLS ERROR: received control packet with stale session-id=%s",
3483  session_id_print(&sid, &gc));
3484  goto error;
3485  }
3486  dmsg(D_TLS_DEBUG,
3487  "TLS: found match, session[%d], sid=%s",
3488  i, session_id_print(&sid, &gc));
3489  break;
3490  }
3491  }
3492 
3493  /*
3494  * Initial packet received.
3495  */
3496 
3497  if (i == TM_SIZE && is_hard_reset(op, 0))
3498  {
3499  struct tls_session *session = &multi->session[TM_ACTIVE];
3500  struct key_state *ks = &session->key[KS_PRIMARY];
3501 
3502  if (!is_hard_reset(op, multi->opt.key_method))
3503  {
3504  msg(D_TLS_ERRORS, "TLS ERROR: initial packet local/remote key_method mismatch, local key_method=%d, op=%s",
3505  multi->opt.key_method,
3506  packet_opcode_name(op));
3507  goto error;
3508  }
3509 
3510  /*
3511  * If we have no session currently in progress, the initial packet will
3512  * open a new session in TM_ACTIVE rather than TM_UNTRUSTED.
3513  */
3515  {
3516  if (multi->opt.single_session && multi->n_sessions)
3517  {
3518  msg(D_TLS_ERRORS,
3519  "TLS Error: Cannot accept new session request from %s due to session context expire or --single-session [1]",
3520  print_link_socket_actual(from, &gc));
3521  goto error;
3522  }
3523 
3524 #ifdef ENABLE_MANAGEMENT
3525  if (management)
3526  {
3529  NULL,
3530  NULL,
3531  NULL,
3532  NULL,
3533  NULL);
3534  }
3535 #endif
3536 
3538  "TLS: Initial packet from %s, sid=%s",
3539  print_link_socket_actual(from, &gc),
3540  session_id_print(&sid, &gc));
3541 
3542  do_burst = true;
3543  new_link = true;
3544  i = TM_ACTIVE;
3545  session->untrusted_addr = *from;
3546  }
3547  }
3548 
3549  if (i == TM_SIZE && is_hard_reset(op, 0))
3550  {
3551  /*
3552  * No match with existing sessions,
3553  * probably a new session.
3554  */
3555  struct tls_session *session = &multi->session[TM_UNTRUSTED];
3556 
3557  /*
3558  * If --single-session, don't allow any hard-reset connection request
3559  * unless it the the first packet of the session.
3560  */
3561  if (multi->opt.single_session)
3562  {
3563  msg(D_TLS_ERRORS,
3564  "TLS Error: Cannot accept new session request from %s due to session context expire or --single-session [2]",
3565  print_link_socket_actual(from, &gc));
3566  goto error;
3567  }
3568 
3569  if (!is_hard_reset(op, multi->opt.key_method))
3570  {
3571  msg(D_TLS_ERRORS, "TLS ERROR: new session local/remote key_method mismatch, local key_method=%d, op=%s",
3572  multi->opt.key_method,
3573  packet_opcode_name(op));
3574  goto error;
3575  }
3576 
3577  if (!read_control_auth(buf, &session->tls_wrap, from))
3578  {
3579  goto error;
3580  }
3581 
3582  /*
3583  * New session-initiating control packet is authenticated at this point,
3584  * assuming that the --tls-auth command line option was used.
3585  *
3586  * Without --tls-auth, we leave authentication entirely up to TLS.
3587  */
3589  "TLS: new session incoming connection from %s",
3590  print_link_socket_actual(from, &gc));
3591 
3592  new_link = true;
3593  i = TM_UNTRUSTED;
3594  session->untrusted_addr = *from;
3595  }
3596  else
3597  {
3598  struct tls_session *session = &multi->session[i];
3599  struct key_state *ks = &session->key[KS_PRIMARY];
3600 
3601  /*
3602  * Packet must belong to an existing session.
3603  */
3604  if (i != TM_ACTIVE && i != TM_UNTRUSTED)
3605  {
3606  msg(D_TLS_ERRORS,
3607  "TLS Error: Unroutable control packet received from %s (si=%d op=%s)",
3608  print_link_socket_actual(from, &gc),
3609  i,
3610  packet_opcode_name(op));
3611  goto error;
3612  }
3613 
3614  /*
3615  * Verify remote IP address
3616  */
3617  if (!new_link && !link_socket_actual_match(&ks->remote_addr, from))
3618  {
3619  msg(D_TLS_ERRORS, "TLS Error: Received control packet from unexpected IP addr: %s",
3620  print_link_socket_actual(from, &gc));
3621  goto error;
3622  }
3623 
3624  /*
3625  * Remote is requesting a key renegotiation
3626  */
3627  if (op == P_CONTROL_SOFT_RESET_V1
3628  && DECRYPT_KEY_ENABLED(multi, ks))
3629  {
3630  if (!read_control_auth(buf, &session->tls_wrap, from))
3631  {
3632  goto error;
3633  }
3634 
3635  key_state_soft_reset(session);
3636 
3637  dmsg(D_TLS_DEBUG,
3638  "TLS: received P_CONTROL_SOFT_RESET_V1 s=%d sid=%s",
3639  i, session_id_print(&sid, &gc));
3640  }
3641  else
3642  {
3643  /*
3644  * Remote responding to our key renegotiation request?
3645  */
3646  if (op == P_CONTROL_SOFT_RESET_V1)
3647  {
3648  do_burst = true;
3649  }
3650 
3651  if (!read_control_auth(buf, &session->tls_wrap, from))
3652  {
3653  goto error;
3654  }
3655 
3656  dmsg(D_TLS_DEBUG,
3657  "TLS: received control channel packet s#=%d sid=%s",
3658  i, session_id_print(&sid, &gc));
3659  }
3660  }
3661 
3662  /*
3663  * We have an authenticated control channel packet (if --tls-auth was set).
3664  * Now pass to our reliability layer which deals with
3665  * packet acknowledgements, retransmits, sequencing, etc.
3666  */
3667  {
3668  struct tls_session *session = &multi->session[i];
3669  struct key_state *ks = &session->key[KS_PRIMARY];
3670 
3671  /* Make sure we were initialized and that we're not in an error state */
3672  ASSERT(ks->state != S_UNDEF);
3673  ASSERT(ks->state != S_ERROR);
3674  ASSERT(session_id_defined(&session->session_id));
3675 
3676  /* Let our caller know we processed a control channel packet */
3677  ret = true;
3678 
3679  /*
3680  * Set our remote address and remote session_id
3681  */
3682  if (new_link)
3683  {
3684  ks->session_id_remote = sid;
3685  ks->remote_addr = *from;
3686  ++multi->n_sessions;
3687  }
3688  else if (!link_socket_actual_match(&ks->remote_addr, from))
3689  {
3690  msg(D_TLS_ERRORS,
3691  "TLS Error: Existing session control channel packet from unknown IP address: %s",
3692  print_link_socket_actual(from, &gc));
3693  goto error;
3694  }
3695 
3696  /*
3697  * Should we do a retransmit of all unacknowledged packets in
3698  * the send buffer? This improves the start-up efficiency of the
3699  * initial key negotiation after the 2nd peer comes online.
3700  */
3701  if (do_burst && !session->burst)
3702  {
3704  session->burst = true;
3705  }
3706 
3707  /* Check key_id */
3708  if (ks->key_id != key_id)
3709  {
3710  msg(D_TLS_ERRORS,
3711  "TLS ERROR: local/remote key IDs out of sync (%d/%d) ID: %s",
3712  ks->key_id, key_id, print_key_id(multi, &gc));
3713  goto error;
3714  }
3715 
3716  /*
3717  * Process incoming ACKs for packets we can now
3718  * delete from reliable send buffer
3719  */
3720  {
3721  /* buffers all packet IDs to delete from send_reliable */
3722  struct reliable_ack send_ack;
3723 
3724  send_ack.len = 0;
3725  if (!reliable_ack_read(&send_ack, buf, &session->session_id))
3726  {
3727  msg(D_TLS_ERRORS,
3728  "TLS Error: reading acknowledgement record from packet");
3729  goto error;
3730  }
3731  reliable_send_purge(ks->send_reliable, &send_ack);
3732  }
3733 
3734  if (op != P_ACK_V1 && reliable_can_get(ks->rec_reliable))
3735  {
3736  packet_id_type id;
3737 
3738  /* Extract the packet ID from the packet */
3739  if (reliable_ack_read_packet_id(buf, &id))
3740  {
3741  /* Avoid deadlock by rejecting packet that would de-sequentialize receive buffer */
3743  {
3744  if (reliable_not_replay(ks->rec_reliable, id))
3745  {
3746  /* Save incoming ciphertext packet to reliable buffer */
3747  struct buffer *in = reliable_get_buf(ks->rec_reliable);
3748  ASSERT(in);
3749  if(!buf_copy(in, buf))
3750  {
3752  "Incoming control channel packet too big, dropping.");
3753  goto error;
3754  }
3756  }
3757 
3758  /* Process outgoing acknowledgment for packet just received, even if it's a replay */
3760  }
3761  }
3762  }
3763  }
3764  }
3765  }
3766 
3767 done:
3768  buf->len = 0;
3769  *opt = NULL;
3770  gc_free(&gc);
3771  return ret;
3772 
3773 error:
3774  ++multi->n_soft_errors;
3775 error_lite:
3776  tls_clear_error();
3777  goto done;
3778 }
3779 
3780 /*
3781  * This function is similar to tls_pre_decrypt, except it is called
3782  * when we are in server mode and receive an initial incoming
3783  * packet. Note that we don't modify
3784  * any state in our parameter objects. The purpose is solely to
3785  * determine whether we should generate a client instance
3786  * object, in which case true is returned.
3787  *
3788  * This function is essentially the first-line HMAC firewall
3789  * on the UDP port listener in --mode server mode.
3790  */
3791 bool
3793  const struct link_socket_actual *from,
3794  const struct buffer *buf)
3795 
3796 {
3797  struct gc_arena gc = gc_new();
3798  bool ret = false;
3799 
3800  if (buf->len > 0)
3801  {
3802  int op;
3803  int key_id;
3804 
3805  /* get opcode and key ID */
3806  {
3807  uint8_t c = *BPTR(buf);
3808  op = c >> P_OPCODE_SHIFT;
3809  key_id = c & P_KEY_ID_MASK;
3810  }
3811 
3812  /* this packet is from an as-yet untrusted source, so
3813  * scrutinize carefully */
3814 
3816  {
3817  /*
3818  * This can occur due to bogus data or DoS packets.
3819  */
3821  "TLS State Error: No TLS state for client %s, opcode=%d",
3822  print_link_socket_actual(from, &gc),
3823  op);
3824  goto error;
3825  }
3826 
3827  if (key_id != 0)
3828  {
3830  "TLS State Error: Unknown key ID (%d) received from %s -- 0 was expected",
3831  key_id,
3832  print_link_socket_actual(from, &gc));
3833  goto error;
3834  }
3835 
3836  if (buf->len > EXPANDED_SIZE_DYNAMIC(&tas->frame))
3837  {
3839  "TLS State Error: Large packet (size %d) received from %s -- a packet no larger than %d bytes was expected",
3840  buf->len,
3841  print_link_socket_actual(from, &gc),
3842  EXPANDED_SIZE_DYNAMIC(&tas->frame));
3843  goto error;
3844  }
3845 
3846  {
3847  struct buffer newbuf = clone_buf(buf);
3848  struct tls_wrap_ctx tls_wrap_tmp = tas->tls_wrap;
3849  bool status;
3850 
3851  /* HMAC test, if --tls-auth was specified */
3852  status = read_control_auth(&newbuf, &tls_wrap_tmp, from);
3853  free_buf(&newbuf);
3854  if (!status)
3855  {
3856  goto error;
3857  }
3858 
3859  /*
3860  * At this point, if --tls-auth is being used, we know that
3861  * the packet has passed the HMAC test, but we don't know if
3862  * it is a replay yet. We will attempt to defeat replays
3863  * by not advancing to the S_START state until we
3864  * receive an ACK from our first reply to the client
3865  * that includes an HMAC of our randomly generated 64 bit
3866  * session ID.
3867  *
3868  * On the other hand if --tls-auth is not being used, we
3869  * will proceed to begin the TLS authentication
3870  * handshake with only cursory integrity checks having
3871  * been performed, since we will be leaving the task
3872  * of authentication solely up to TLS.
3873  */
3874 
3875  ret = true;
3876  }
3877  }
3878  gc_free(&gc);
3879  return ret;
3880 
3881 error:
3882  tls_clear_error();
3883  gc_free(&gc);
3884  return ret;
3885 }
3886 
3887 /* Choose the key with which to encrypt a data packet */
3888 void
3890  struct buffer *buf, struct crypto_options **opt)
3891 {
3892  multi->save_ks = NULL;
3893  if (buf->len > 0)
3894  {
3895  int i;
3896  struct key_state *ks_select = NULL;
3897  for (i = 0; i < KEY_SCAN_SIZE; ++i)
3898  {
3899  struct key_state *ks = multi->key_scan[i];
3900  if (ks->state >= S_ACTIVE
3901  && ks->authenticated
3903 #ifdef ENABLE_DEF_AUTH
3904  && !ks->auth_deferred
3905 #endif
3906  )
3907  {
3908  if (!ks_select)
3909  {
3910  ks_select = ks;
3911  }
3912  if (now >= ks->auth_deferred_expire)
3913  {
3914  ks_select = ks;
3915  break;
3916  }
3917  }
3918  }
3919 
3920  if (ks_select)
3921  {
3922  *opt = &ks_select->crypto_options;
3923  multi->save_ks = ks_select;
3924  dmsg(D_TLS_KEYSELECT, "TLS: tls_pre_encrypt: key_id=%d", ks_select->key_id);
3925  return;
3926  }
3927  else
3928  {
3929  struct gc_arena gc = gc_new();
3930  dmsg(D_TLS_KEYSELECT, "TLS Warning: no data channel send key available: %s",
3931  print_key_id(multi, &gc));
3932  gc_free(&gc);
3933  }
3934  }
3935 
3936  buf->len = 0;
3937  *opt = NULL;
3938 }
3939 
3940 void
3941 tls_prepend_opcode_v1(const struct tls_multi *multi, struct buffer *buf)
3942 {
3943  struct key_state *ks = multi->save_ks;
3944  uint8_t op;
3945 
3946  msg(D_TLS_DEBUG, __func__);
3947 
3948  ASSERT(ks);
3949 
3950  op = (P_DATA_V1 << P_OPCODE_SHIFT) | ks->key_id;
3951  ASSERT(buf_write_prepend(buf, &op, 1));
3952 }
3953 
3954 void
3955 tls_prepend_opcode_v2(const struct tls_multi *multi, struct buffer *buf)
3956 {
3957  struct key_state *ks = multi->save_ks;
3958  uint32_t peer;
3959 
3960  msg(D_TLS_DEBUG, __func__);
3961 
3962  ASSERT(ks);
3963 
3964  peer = htonl(((P_DATA_V2 << P_OPCODE_SHIFT) | ks->key_id) << 24
3965  | (multi->peer_id & 0xFFFFFF));
3966  ASSERT(buf_write_prepend(buf, &peer, 4));
3967 }
3968 
3969 void
3970 tls_post_encrypt(struct tls_multi *multi, struct buffer *buf)
3971 {
3972  struct key_state *ks = multi->save_ks;
3973  multi->save_ks = NULL;
3974 
3975  if (buf->len > 0)
3976  {
3977  ASSERT(ks);
3978 
3979  ++ks->n_packets;
3980  ks->n_bytes += buf->len;
3981  }
3982 }
3983 
3984 /*
3985  * Send a payload over the TLS control channel.
3986  * Called externally.
3987  */
3988 
3989 bool
3991  const uint8_t *data,
3992  int size)
3993 {
3994  struct tls_session *session;
3995  struct key_state *ks;
3996  bool ret = false;
3997 
3998  tls_clear_error();
3999 
4000  ASSERT(multi);
4001 
4002  session = &multi->session[TM_ACTIVE];
4003  ks = &session->key[KS_PRIMARY];
4004 
4005  if (ks->state >= S_ACTIVE)
4006  {
4007  if (key_state_write_plaintext_const(&ks->ks_ssl, data, size) == 1)
4008  {
4009  ret = true;
4010  }
4011  }
4012  else
4013  {
4014  if (!ks->paybuf)
4015  {
4016  ks->paybuf = buffer_list_new(0);
4017  }
4018  buffer_list_push_data(ks->paybuf, data, (size_t)size);
4019  ret = true;
4020  }
4021 
4022 
4023  tls_clear_error();
4024 
4025  return ret;
4026 }
4027 
4028 bool
4030  struct buffer *buf)
4031 {
4032  struct tls_session *session;
4033  struct key_state *ks;
4034  bool ret = false;
4035 
4036  tls_clear_error();
4037 
4038  ASSERT(multi);
4039 
4040  session = &multi->session[TM_ACTIVE];
4041  ks = &session->key[KS_PRIMARY];
4042 
4043  if (ks->state >= S_ACTIVE && BLEN(&ks->plaintext_read_buf))
4044  {
4045  if (buf_copy(buf, &ks->plaintext_read_buf))
4046  {
4047  ret = true;
4048  }
4049  ks->plaintext_read_buf.len = 0;
4050  }
4051 
4052  tls_clear_error();
4053 
4054  return ret;
4055 }
4056 
4057 void
4058 tls_update_remote_addr(struct tls_multi *multi, const struct link_socket_actual *addr)
4059 {
4060  struct gc_arena gc = gc_new();
4061  int i, j;
4062 
4063  for (i = 0; i < TM_SIZE; ++i)
4064  {
4065  struct tls_session *session = &multi->session[i];
4066 
4067  for (j = 0; j < KS_SIZE; ++j)
4068  {
4069  struct key_state *ks = &session->key[j];
4070 
4072  || link_socket_actual_match(addr, &ks->remote_addr))
4073  {
4074  continue;
4075  }
4076 
4077  dmsg(D_TLS_KEYSELECT, "TLS: tls_update_remote_addr from IP=%s to IP=%s",
4079  print_link_socket_actual(addr, &gc));
4080 
4081  ks->remote_addr = *addr;
4082  }
4083  }
4084  gc_free(&gc);
4085 }
4086 
4087 int
4088 tls_peer_info_ncp_ver(const char *peer_info)
4089 {
4090  const char *ncpstr = peer_info ? strstr(peer_info, "IV_NCP=") : NULL;
4091  if (ncpstr)
4092  {
4093  int ncp = 0;
4094  int r = sscanf(ncpstr, "IV_NCP=%d", &ncp);
4095  if (r == 1)
4096  {
4097  return ncp;
4098  }
4099  }
4100  return 0;
4101 }
4102 
4103 bool
4104 tls_check_ncp_cipher_list(const char *list)
4105 {
4106  bool unsupported_cipher_found = false;
4107 
4108  ASSERT(list);
4109 
4110  char *const tmp_ciphers = string_alloc(list, NULL);
4111  const char *token = strtok(tmp_ciphers, ":");
4112  while (token)
4113  {
4115  {
4116  msg(M_WARN, "Unsupported cipher in --ncp-ciphers: %s", token);
4117  unsupported_cipher_found = true;
4118  }
4119  token = strtok(NULL, ":");
4120  }
4121  free(tmp_ciphers);
4122 
4123  return 0 < strlen(list) && !unsupported_cipher_found;
4124 }
4125 
4126 /*
4127  * Dump a human-readable rendition of an openvpn packet
4128  * into a garbage collectable string which is returned.
4129  */
4130 const char *
4131 protocol_dump(struct buffer *buffer, unsigned int flags, struct gc_arena *gc)
4132 {
4133  struct buffer out = alloc_buf_gc(256, gc);
4134  struct buffer buf = *buffer;
4135 
4136  uint8_t c;
4137  int op;
4138  int key_id;
4139 
4140  int tls_auth_hmac_size = (flags & PD_TLS_AUTH_HMAC_SIZE_MASK);
4141 
4142  if (buf.len <= 0)
4143  {
4144  buf_printf(&out, "DATA UNDEF len=%d", buf.len);
4145  goto done;
4146  }
4147 
4148  if (!(flags & PD_TLS))
4149  {
4150  goto print_data;
4151  }
4152 
4153  /*
4154  * Initial byte (opcode)
4155  */
4156  if (!buf_read(&buf, &c, sizeof(c)))
4157  {
4158  goto done;
4159  }
4160  op = (c >> P_OPCODE_SHIFT);
4161  key_id = c & P_KEY_ID_MASK;
4162  buf_printf(&out, "%s kid=%d", packet_opcode_name(op), key_id);
4163 
4164  if ((op == P_DATA_V1) || (op == P_DATA_V2))
4165  {
4166  goto print_data;
4167  }
4168 
4169  /*
4170  * Session ID
4171  */
4172  {
4173  struct session_id sid;
4174 
4175  if (!session_id_read(&sid, &buf))
4176  {
4177  goto done;
4178  }
4179  if (flags & PD_VERBOSE)
4180  {
4181  buf_printf(&out, " sid=%s", session_id_print(&sid, gc));
4182  }
4183  }
4184 
4185  /*
4186  * tls-auth hmac + packet_id
4187  */
4188  if (tls_auth_hmac_size)
4189  {
4190  struct packet_id_net pin;
4191  uint8_t tls_auth_hmac[MAX_HMAC_KEY_LENGTH];
4192 
4193  ASSERT(tls_auth_hmac_size <= MAX_HMAC_KEY_LENGTH);
4194 
4195  if (!buf_read(&buf, tls_auth_hmac, tls_auth_hmac_size))
4196  {
4197  goto done;
4198  }
4199  if (flags & PD_VERBOSE)
4200  {
4201  buf_printf(&out, " tls_hmac=%s", format_hex(tls_auth_hmac, tls_auth_hmac_size, 0, gc));
4202  }
4203 
4204  if (!packet_id_read(&pin, &buf, true))
4205  {
4206  goto done;
4207  }
4208  buf_printf(&out, " pid=%s", packet_id_net_print(&pin, (flags & PD_VERBOSE), gc));
4209  }
4210 
4211  /*
4212  * ACK list
4213  */
4214  buf_printf(&out, " %s", reliable_ack_print(&buf, (flags & PD_VERBOSE), gc));
4215 
4216  if (op == P_ACK_V1)
4217  {
4218  goto done;
4219  }
4220 
4221  /*
4222  * Packet ID
4223  */
4224  {
4225  packet_id_type l;
4226  if (!buf_read(&buf, &l, sizeof(l)))
4227  {
4228  goto done;
4229  }
4230  l = ntohpid(l);
4232  }
4233 
4234 print_data:
4235  if (flags & PD_SHOW_DATA)
4236  {
4237  buf_printf(&out, " DATA %s", format_hex(BPTR(&buf), BLEN(&buf), 80, gc));
4238  }
4239  else
4240  {
4241  buf_printf(&out, " DATA len=%d", buf.len);
4242  }
4243 
4244 done:
4245  return BSTR(&out);
4246 }
4247 
4248 void
4250 {
4251  auth_user_pass.wait_for_push = false;
4253 }
static void tls_init_control_channel_frame_parameters(const struct frame *data_channel_frame, struct frame *frame)
Definition: ssl.c:325
struct reliable * rec_reliable
Definition: ssl_common.h:190
#define TLSMP_ACTIVE
Definition: ssl.h:228
bool cipher_kt_mode_aead(const cipher_kt_t *cipher)
Check if the supplied cipher is a supported AEAD mode cipher.
char * management_query_cert(struct management *man, const char *cert_name)
Definition: manage.c:3687
static bool buf_write_u8(struct buffer *dest, int data)
Definition: buffer.h:696
void reliable_free(struct reliable *rel)
Free allocated memory associated with a reliable structure.
Definition: reliable.c:327
static const char * packet_opcode_name(int op)
Definition: ssl.c:779
const cipher_kt_t * cipher_ctx_get_cipher_kt(const cipher_ctx_t *ctx)
Returns the static cipher parameters for this context.
void options_warning(char *actual, const char *expected)
Definition: options.c:3764
const char * ecdh_curve
Definition: options.h:511
struct key_type key_type
Definition: ssl_common.h:241
int read_key(struct key *key, const struct key_type *kt, struct buffer *buf)
Definition: crypto.c:1627
#define EXPANDED_SIZE_DYNAMIC(f)
Definition: mtu.h:173
int tls_ctx_load_pkcs12(struct tls_root_ctx *ctx, const char *pkcs12_file, const char *pkcs12_file_inline, bool load_ca_file)
Load PKCS #12 file for key, cert and (optionally) CA certs, and add to library-specific TLS context...
Definition: ssl_openssl.c:635
#define P_CONTROL_HARD_RESET_SERVER_V1
Definition: ssl.h:55
static const char * print_key_id(struct tls_multi *multi, struct gc_arena *gc)
Definition: ssl.c:838
size_t implicit_iv_len
The length of implicit_iv.
Definition: crypto.h:170
const char * ca_file_inline
Definition: options.h:518
Security parameter state for processing data channel packets.
Definition: crypto.h:232
struct key_state_ssl ks_ssl
Definition: ssl_common.h:171
#define D_TLS_KEYSELECT
Definition: errlevel.h:143
const char * management_certificate
Definition: options.h:372
#define CO_PACKET_ID_LONG_FORM
Bit-flag indicating whether to use OpenVPN&#39;s long packet ID format.
Definition: crypto.h:245
static void strncpynt(char *dest, const char *src, size_t maxlen)
Definition: buffer.h:348
#define TM_ACTIVE
Active tls_session.
Definition: ssl_common.h:456
Security parameter state of one TLS and data channel key session.
Definition: ssl_common.h:161
static void compute_earliest_wakeup(interval_t *earliest, interval_t seconds_from_now)
Definition: ssl.c:1208
bool tun_mtu_defined
Definition: options.h:108
struct buffer work
Work buffer (only for –tls-crypt)
Definition: ssl_common.h:228
bool ncp_enabled
Definition: options.h:482
unsigned int management_flags
Definition: options.h:371
struct packet_id packet_id
Current packet ID state for both sending and receiving directions.
Definition: crypto.h:238
struct key_state key[KS_SIZE]
Definition: ssl_common.h:436
#define TLSMP_INACTIVE
Definition: ssl.h:227
const char * crl_file
Definition: ssl_common.h:278
struct buffer plaintext_read_buf
Definition: ssl_common.h:185
int n_sessions
Number of sessions negotiated thus far.
Definition: ssl_common.h:519
#define S_NORMAL_OP
Normal operational key_state state.
Definition: ssl_common.h:110
void tls_auth_standalone_finalize(struct tls_auth_standalone *tas, const struct frame *frame)
Definition: ssl.c:1317
#define SSLF_CRL_VERIFY_DIR
Definition: ssl_common.h:335
bool options_cmp_equal_safe(char *actual, const char *expected, size_t actual_n)
Definition: options.c:3895
void free_buf(struct buffer *buf)
Definition: buffer.c:183
void ssl_put_auth_challenge(const char *cr_str)
Definition: ssl.c:502
#define D_TLS_DEBUG_LOW
Definition: errlevel.h:77
const char * cipher_list
Definition: options.h:509
static bool write_string(struct buffer *buf, const char *str, const int maxlen)
Definition: ssl.c:2138
unsigned int flags
Bit-flags determining behavior of security operation functions.
Definition: crypto.h:257
bool tls_server
Definition: options.h:500
#define TLS_MULTI_AUTH_STATUS_INTERVAL
Definition: ssl.h:97
void tls_ctx_load_cryptoapi(struct tls_root_ctx *ctx, const char *cryptoapi_cert)
Definition: ssl_openssl.c:764
char * string_alloc(const char *str, struct gc_arena *gc)
Definition: buffer.c:663
#define S_PRE_START
Waiting for the remote OpenVPN peer to acknowledge during the initial three-way handshake.
Definition: ssl_common.h:86
static const char * session_index_name(int index)
Definition: ssl.c:816
static void tls_ctx_reload_crl(struct tls_root_ctx *ssl_ctx, const char *crl_file, const char *crl_file_inline)
Load (or possibly reload) the CRL file into the SSL context.
Definition: ssl.c:557
static bool session_id_equal(const struct session_id *sid1, const struct session_id *sid2)
Definition: session_id.h:48
#define D_TLS_DEBUG
Definition: errlevel.h:160
#define USER_PASS_LEN
Definition: misc.h:76
struct key keys[2]
Two unidirectional sets of key material.
Definition: crypto.h:185
void init_key_ctx(struct key_ctx *ctx, const struct key *key, const struct key_type *kt, int enc, const char *prefix)
Definition: crypto.c:821
static void tls_limit_reneg_bytes(const cipher_kt_t *cipher, int *reneg_bytes)
Limit the reneg_bytes value when using a small-block (<128 bytes) cipher.
Definition: ssl.c:295
const char * cert_file
Definition: options.h:505
struct packet_id_persist * pid_persist
Persistent packet ID state for keeping state between successive OpenVPN process startups.
Definition: crypto.h:240
bool options_cmp_equal(char *actual, const char *expected)
Definition: options.c:3758
const char * tls_cert_profile
Definition: options.h:510
#define GET_USER_PASS_STATIC_CHALLENGE
Definition: misc.h:125
Container for both halves of random material to be used in key method 2 data channel key generation...
Definition: ssl_common.h:138
static bool session_id_write(const struct session_id *sid, struct buffer *buf)
Definition: session_id.h:73
static void secure_memzero(void *data, size_t len)
Securely zeroise memory.
Definition: buffer.h:401
#define TLS_OPTIONS_LEN
Definition: ssl.h:104
void tls_ctx_load_ecdh_params(struct tls_root_ctx *ctx, const char *curve_name)
Load Elliptic Curve Parameters, and load them into the library-specific TLS context.
Definition: ssl_openssl.c:552
int key_state_write_plaintext_const(struct key_state_ssl *ks_ssl, const uint8_t *data, int len)
Insert plaintext data into the TLS module.
Definition: ssl_openssl.c:1803
static bool buf_advance(struct buffer *buf, int size)
Definition: buffer.h:622
void packet_id_persist_load_obj(const struct packet_id_persist *p, struct packet_id *pid)
Definition: packet_id.c:524
#define M_INFO
Definition: errlevel.h:55
Packet geometry parameters.
Definition: mtu.h:93
struct key_state * save_ks
Definition: ssl_common.h:511
#define UP_TYPE_AUTH
Definition: ssl_common.h:41
#define SIZE(x)
Definition: basic.h:30
#define OPENVPN_MAX_IV_LENGTH
Maximum length of an IV.
bool cipher_kt_mode_ofb_cfb(const cipher_kt_t *cipher)
Check if the supplied cipher is a supported OFB or CFB mode cipher.
void fixup_key(struct key *key, const struct key_type *kt)
Definition: crypto.c:974
static void key_state_soft_reset(struct tls_session *session)
Definition: ssl.c:2109
static void link_socket_set_outgoing_addr(const struct buffer *buf, struct link_socket_info *info, const struct link_socket_actual *act, const char *common_name, struct env_set *es)
Definition: socket.h:971
const char * ca_path
Definition: options.h:503
struct tls_options * opt
Definition: ssl_common.h:401
time_t must_negotiate
Definition: ssl_common.h:174
#define SSLF_AUTH_USER_PASS_OPTIONAL
Definition: ssl_common.h:333
char * peer_info
Definition: ssl_common.h:550
const char * ca_file
Definition: options.h:502
const char * print_link_socket_actual(const struct link_socket_actual *act, struct gc_arena *gc)
Definition: socket.c:2772
#define RELIABLE_ACK_SIZE
The maximum number of packet IDs waiting to be acknowledged which can be stored in one reliable_ack s...
Definition: reliable.h:46
static void gc_free(struct gc_arena *a)
Definition: buffer.h:999
struct tls_root_ctx ssl_ctx
Definition: ssl_common.h:238
static bool check_debug_level(unsigned int level)
Definition: error.h:245
bool write_key(const struct key *key, const struct key_type *kt, struct buffer *buf)
Definition: crypto.c:1594
bool verified
Definition: ssl_common.h:431
void options_warning_safe(char *actual, const char *expected, size_t actual_n)
Definition: options.c:3918
void tls_post_encrypt(struct tls_multi *multi, struct buffer *buf)
Perform some accounting for the key state used.
Definition: ssl.c:3970
static int plugin_call(const struct plugin_list *pl, const int type, const struct argv *av, struct plugin_return *pr, struct env_set *es)
Definition: plugin.h:201
const char * auth_user_pass_verify_script
Definition: ssl_common.h:309
const char * priv_key_file
Definition: options.h:507
void session_id_random(struct session_id *sid)
Definition: session_id.c:51
Security parameter state for a single VPN tunnel.
Definition: ssl_common.h:494
#define D_TLS_ERRORS
Definition: errlevel.h:59
static bool buf_safe(const struct buffer *buf, int len)
Definition: buffer.h:524
struct buffer_list * buffer_list_new(const int max_size)
Definition: buffer.c:1176
static bool tls_process(struct tls_multi *multi, struct tls_session *session, struct buffer *to_link, struct link_socket_actual **to_link_addr, struct link_socket_info *to_link_socket_info, interval_t *wakeup)
Definition: ssl.c:2712
int pem_password_callback(char *buf, int size, int rwflag, void *u)
Callback to retrieve the user&#39;s password.
Definition: ssl.c:381
#define ASSERT(x)
Definition: error.h:221
int tls_authentication_status(struct tls_multi *multi, const int latency)
Definition: ssl_verify.c:941
void key_state_ssl_free(struct key_state_ssl *ks_ssl)
Free the SSL channel part of the given key state.
Definition: ssl_openssl.c:1770
#define SID_SIZE
Definition: session_id.h:45
void tls_multi_free(struct tls_multi *multi, bool clear)
Cleanup a tls_multi structure and free associated memory allocations.
Definition: ssl.c:1344
const char * auth_user_pass_file
Definition: ssl_common.h:312
int n
The number of key objects stored in the key2.keys array.
Definition: crypto.h:183
struct reliable_ack * rec_ack
Definition: ssl_common.h:191
struct buffer alloc_buf(size_t size)
Definition: buffer.c:62
void buffer_list_free(struct buffer_list *ol)
Definition: buffer.c:1186
void backend_tls_ctx_reload_crl(struct tls_root_ctx *ssl_ctx, const char *crl_file, const char *crl_inline)
Reload the Certificate Revocation List for the SSL channel.
Definition: ssl_openssl.c:949
const char * crl_file_inline
Definition: options.h:521
int handshake_window
Definition: ssl_common.h:267
bool tls_item_in_cipher_list(const char *item, const char *list)
Return true iff item is present in the colon-separated zero-terminated cipher list.
Definition: ssl.c:1888
struct crypto_options opt
Crypto state.
Definition: ssl_common.h:227
void tls_update_remote_addr(struct tls_multi *multi, const struct link_socket_actual *addr)
Updates remote address in TLS sessions.
Definition: ssl.c:4058
#define S_UNDEF
Undefined state, used after a key_state is cleaned up.
Definition: ssl_common.h:78
struct cert_hash_set * cert_hash_set
Definition: ssl_common.h:425
static bool lame_duck_must_die(const struct tls_session *session, interval_t *wakeup)
Definition: ssl.c:1225
void set_auth_token(struct user_pass *up, const char *token)
Definition: misc.c:527
#define packet_id_format
Definition: packet_id.h:95
static void perf_pop(void)
Definition: perf.h:82
#define M_FATAL
Definition: error.h:94
bool buf_printf(struct buffer *buf, const char *format,...)
Definition: buffer.c:243
#define D_MULTI_DROPPED
Definition: errlevel.h:102
static bool read_string(struct buffer *buf, char *str, const unsigned int capacity)
Definition: ssl.c:2157
static void perf_push(int type)
Definition: perf.h:78
void tls_prepend_opcode_v2(const struct tls_multi *multi, struct buffer *buf)
Prepend an OpenVPN data channel P_DATA_V2 header to the packet.
Definition: ssl.c:3955
time_t crl_last_mtime
CRL last modification time.
Definition: ssl_mbedtls.h:76
static char * format_hex(const uint8_t *data, int size, int maxoutput, struct gc_arena *gc)
Definition: buffer.h:509
#define CLEAR(x)
Definition: basic.h:33
int tls_ctx_use_external_private_key(struct tls_root_ctx *ctx, const char *cert_file, const char *cert_file_inline)
Definition: ssl_openssl.c:1291
bool defined
Definition: misc.h:67
#define D_MTU_INFO
Definition: errlevel.h:106
static int buf_read_u8(struct buffer *buf)
Definition: buffer.h:795
const char * win32_version_string(struct gc_arena *gc, bool add_name)
Definition: win32.c:1442
int cipher_kt_iv_size(const cipher_kt_t *cipher_kt)
Returns the size of the IV used by the cipher, in bytes, or 0 if no IV is used.
void key_state_export_keying_material(struct key_state_ssl *ks_ssl, struct tls_session *session) __attribute__((nonnull))
Keying Material Exporters [RFC 5705] allows additional keying material to be derived from existing TL...
Definition: ssl_openssl.c:148
const char * protocol_dump(struct buffer *buffer, unsigned int flags, struct gc_arena *gc)
Definition: ssl.c:4131
#define ENABLE_DEF_AUTH
Definition: config-msvc.h:5
#define TLS_VER_1_1
Definition: ssl_backend.h:115
static void flush_payload_buffer(struct key_state *ks)
Definition: ssl.c:2089
bool packet_id_read(struct packet_id_net *pin, struct buffer *buf, bool long_form)
Definition: packet_id.c:301
struct buffer * reliable_get_buf(struct reliable *rel)
Get the buffer of a free reliable entry in which to store a packet.
Definition: reliable.c:473
const char * pkcs12_file_inline
Definition: options.h:524
static bool push_peer_info(struct buffer *buf, struct tls_session *session)
Definition: ssl.c:2240
#define DECRYPT_KEY_ENABLED(multi, ks)
Check whether the ks key_state is ready to receive data channel packets.
Definition: ssl_verify.h:89
int key_state_write_plaintext(struct key_state_ssl *ks_ssl, struct buffer *buf)
Insert a plaintext buffer into the TLS module.
Definition: ssl_openssl.c:1785
#define TLS_VER_BAD
Parse a TLS version specifier.
Definition: ssl_backend.h:112
uint8_t random1[32]
Seed used for master secret generation, provided by both client and server.
Definition: ssl_common.h:125
void tls_free_lib(void)
Free any global SSL library-specific data structures.
Definition: ssl_openssl.c:89
bool check_key(struct key *key, const struct key_type *kt)
Definition: crypto.c:935
#define OPENVPN_STATE_AUTH
Definition: manage.h:502
unsigned int crypto_flags
Definition: ssl_common.h:292
bool tls_pre_decrypt_lite(const struct tls_auth_standalone *tas, const struct link_socket_actual *from, const struct buffer *buf)
Inspect an incoming packet for which no VPN tunnel is active, and determine whether a new VPN tunnel ...
Definition: ssl.c:3792
#define OPENVPN_PLUGIN_FUNC_SUCCESS
bool authenticated
Definition: ssl_common.h:201
struct tls_session session[TM_SIZE]
Array of tls_session objects representing control channel sessions with the remote peer...
Definition: ssl_common.h:569
const char * get_ssl_library_version(void)
return a pointer to a static memory area containing the name and version number of the SSL library in...
Definition: ssl_openssl.c:2042
static bool packet_id_initialized(const struct packet_id *pid)
Is this struct packet_id initialized?
Definition: packet_id.h:274
static struct user_pass auth_user_pass
Definition: ssl.c:400
void ssl_set_auth_token(const char *token)
Definition: ssl.c:460
const char * config_ciphername
Definition: ssl_common.h:298
const char * pkcs12_file
Definition: options.h:508
static void frame_add_to_extra_frame(struct frame *frame, const int increment)
Definition: mtu.h:274
struct reliable * send_reliable
Definition: ssl_common.h:189
int renegotiate_bytes
Definition: ssl_common.h:269
void hmac_ctx_cleanup(hmac_ctx_t *ctx)
mbedtls_md_context_t hmac_ctx_t
Generic HMAC context.
#define SSLF_OPT_VERIFY
Definition: ssl_common.h:334
bool link_mtu_defined
Definition: options.h:112
char username[USER_PASS_LEN]
Definition: misc.h:78
uint8_t hmac[MAX_HMAC_KEY_LENGTH]
Key material for HMAC operations.
Definition: crypto.h:155
void packet_id_free(struct packet_id *p)
Definition: packet_id.c:101
bool is_hard_reset(int op, int key_method)
Given a key_method, return true if opcode represents the required form of hard_reset.
Definition: ssl.c:855
static bool buf_read(struct buffer *src, void *dest, int size)
Definition: buffer.h:783
#define MODE_SERVER
Definition: options.h:186
void tls_pre_encrypt(struct tls_multi *multi, struct buffer *buf, struct crypto_options **opt)
Choose the appropriate security parameters with which to process an outgoing packet.
Definition: ssl.c:3889
bool use_peer_id
Definition: ssl_common.h:555
bool initialized
Definition: crypto.h:225
int offset
Offset in bytes of the actual content within the allocated memory.
Definition: buffer.h:64
void tls_ctx_client_new(struct tls_root_ctx *ctx)
Initialises a library-specific TLS context for a client.
Definition: ssl_openssl.c:117
#define TLS_VER_1_2
Definition: ssl_backend.h:116
struct link_socket_actual to_link_addr
Definition: ssl_common.h:517
#define OPENVPN_AEAD_MIN_IV_LEN
Minimal IV length for AEAD mode ciphers (in bytes): 4-byte packet id + 8 bytes implicit IV...
Definition: crypto.h:268
void reliable_mark_active_outgoing(struct reliable *rel, struct buffer *buf, int opcode)
Mark the reliable entry associated with the given buffer as active outgoing.
Definition: reliable.c:696
list flags
int len
Length in bytes of the actual content within the allocated memory.
Definition: buffer.h:66
void tls_ctx_set_cert_profile(struct tls_root_ctx *ctx, const char *profile)
Set the TLS certificate profile.
Definition: ssl_openssl.c:425
#define SWAP_BUF_SIZE
Definition: ssl.c:1401
void setenv_del(struct env_set *es, const char *name)
Definition: env_set.c:330
#define S_ACTIVE
Operational key_state state immediately after negotiation has completed while still within the handsh...
Definition: ssl_common.h:102
const char * ncp_ciphers
Definition: options.h:483
static void reliable_set_timeout(struct reliable *rel, interval_t timeout)
Definition: reliable.h:465
static bool buf_write(struct buffer *dest, const void *src, int size)
Definition: buffer.h:672
off_t crl_last_size
size of last loaded CRL
Definition: ssl_mbedtls.h:77
struct key_state * key_scan[KEY_SCAN_SIZE]
List of key_state objects in the order they should be scanned by data channel modules.
Definition: ssl_common.h:502
const char * packet_id_net_print(const struct packet_id_net *pin, bool print_timestamp, struct gc_arena *gc)
Definition: packet_id.c:391
void prng_uninit(void)
Definition: crypto.c:1720
struct tls_auth_standalone * tls_auth_standalone_init(struct tls_options *tls_options, struct gc_arena *gc)
Definition: ssl.c:1294
static char * auth_challenge
Definition: ssl.c:403
static bool key_source2_randomize_write(struct key_source2 *k2, struct buffer *buf, bool server)
Definition: ssl.c:2022
uint8_t id[8]
Definition: session_id.h:40
struct link_socket_actual remote_addr
Definition: ssl_common.h:179
bool nocache
Definition: misc.h:68
char * options_string_extract_option(const char *options_string, const char *opt_name, struct gc_arena *gc)
Given an OpenVPN options string, extract the value of an option.
Definition: options.c:3934
#define BPTR(buf)
Definition: buffer.h:124
void packet_id_init(struct packet_id *p, int seq_backtrack, int time_backtrack, const char *name, int unit)
Definition: packet_id.c:78
bool reliable_ack_write(struct reliable_ack *ack, struct buffer *buf, const struct session_id *sid, int max, bool prepend)
Write a packet ID acknowledgment record to a buffer.
Definition: reliable.c:213
#define BUF_SIZE(f)
Definition: mtu.h:194
static bool write_empty_string(struct buffer *buf)
Definition: ssl.c:2128
void init_ssl(const struct options *options, struct tls_root_ctx *new_ctx)
Build master SSL context object that serves for the whole of OpenVPN instantiation.
Definition: ssl.c:600
#define KEY_DIRECTION_NORMAL
Definition: crypto.h:174
void print_details(struct key_state_ssl *ks_ssl, const char *prefix)
Definition: ssl_openssl.c:1869
Control channel wrapping (–tls-auth/–tls-crypt) context.
Definition: ssl_common.h:220
static void move_session(struct tls_multi *multi, int dest, int src, bool reinit_src)
Definition: ssl.c:1172
#define KEY_SCAN_SIZE
Definition: ssl_common.h:478
uint8_t random2[32]
Seed used for key expansion, provided by both client and server.
Definition: ssl_common.h:128
#define OPENVPN_STATE_WAIT
Definition: manage.h:501
#define GET_USER_PASS_STATIC_CHALLENGE_ECHO
Definition: misc.h:126
interval_t packet_timeout
Definition: ssl_common.h:268
void tls_prepend_opcode_v1(const struct tls_multi *multi, struct buffer *buf)
Prepend a one-byte OpenVPN data channel P_DATA_V1 opcode to the packet.
Definition: ssl.c:3941
#define S_ERROR
Error state.
Definition: ssl_common.h:77
int tun_mtu
Definition: options.h:107
static void tls1_PRF(const uint8_t *label, int label_len, const uint8_t *sec, int slen, uint8_t *out1, int olen)
Definition: ssl.c:1706
interval_t renegotiate_seconds
Definition: ssl_common.h:271
#define KS_SIZE
Size of the tls_session.key array.
Definition: ssl_common.h:372
int md_kt_size(const md_kt_t *kt)
Returns the size of the message digest, in bytes.
struct env_item * list
Definition: env_set.h:44
#define P_KEY_ID_MASK
Definition: ssl.h:50
void tls_ctx_free(struct tls_root_ctx *ctx)
Frees the library-specific TLSv1 context.
Definition: ssl_openssl.c:130
unsigned int packet_id_print_type
Definition: packet_id.h:96
void key_state_ssl_init(struct key_state_ssl *ks_ssl, const struct tls_root_ctx *ssl_ctx, bool is_server, struct tls_session *session)
Initialise the SSL channel part of the given key state.
Definition: ssl_openssl.c:1730
struct session_id session_id_remote
Definition: ssl_common.h:178
const char * iana_name
Definition: ssl_backend.h:62
#define AUTH_TOKEN_SIZE
Size of server side generated auth tokens.
Definition: ssl_common.h:376
static bool tls_session_generate_data_channel_keys(struct tls_session *session)
Generate data channel keys for the supplied TLS session.
Definition: ssl.c:1928
static bool packet_id_close_to_wrapping(const struct packet_id_send *p)
Definition: packet_id.h:311
int rand_bytes(uint8_t *output, int len)
Wrapper for secure random number generator.
#define counter_format
Definition: common.h:39
const char * crl_file_inline
Definition: ssl_common.h:279
void frame_print(const struct frame *frame, int level, const char *prefix)
Definition: mtu.c:139
static struct gc_arena gc_new(void)
Definition: buffer.h:991
Container for one half of random material to be used in key method 2 data channel key generation...
Definition: ssl_common.h:121
#define KS_PRIMARY
Primary key state index.
Definition: ssl_common.h:368
bool single_session
Definition: ssl_common.h:259
bool tls_crypt_wrap(const struct buffer *src, struct buffer *dst, struct crypto_options *opt)
Wrap a control channel packet (both authenticates and encrypts the data).
Definition: tls_crypt.c:93
time_t now
Definition: otime.c:36
void reliable_ack_adjust_frame_parameters(struct frame *frame, int max)
Definition: reliable.c:258
void key_state_rm_auth_control_file(struct key_state *ks)
Remove the given key state&#39;s auth control file, if it exists.
#define malloc
Definition: cmocka.c:1795
#define P_CONTROL_HARD_RESET_SERVER_V2
Definition: ssl.h:64
const char * authname
Definition: options.h:484
#define S_START
Three-way handshake is complete, start of key exchange.
Definition: ssl_common.h:91
#define INCR_SUCCESS
Definition: ssl.c:103
void tls_ctx_load_extra_certs(struct tls_root_ctx *ctx, const char *extra_certs_file, const char *extra_certs_file_inline)
Load extra certificate authority certificates from the given file or path.
Definition: ssl_openssl.c:1503
time_t established
Definition: ssl_common.h:173
#define ALLOC_OBJ_CLEAR(dptr, type)
Definition: buffer.h:1026
#define TM_UNTRUSTED
As yet un-trusted tls_session being negotiated.
Definition: ssl_common.h:457
struct crypto_options crypto_options
Definition: ssl_common.h:181
#define P_LAST_OPCODE
Definition: ssl.h:68
struct tls_multi * tls_multi_init(struct tls_options *tls_options)
Allocate and initialize a tls_multi structure.
Definition: ssl.c:1253
char * locked_cn
Definition: ssl_common.h:531
bool reliable_not_replay(const struct reliable *rel, packet_id_type id)
Check that a received packet&#39;s ID is not a replay.
Definition: reliable.c:426
void hmac_ctx_update(hmac_ctx_t *ctx, const uint8_t *src, int src_len)
struct buffer * reliable_get_buf_output_sequenced(struct reliable *rel)
Get the buffer of free reliable entry and check whether the outgoing acknowledgment sequence is still...
Definition: reliable.c:490
void free_ssl_lib(void)
Definition: ssl.c:356
static void key_ctx_update_implicit_iv(struct key_ctx *ctx, uint8_t *key, size_t key_len)
Update the implicit IV for a key_ctx_bi based on TLS session ids and cipher used. ...
Definition: ssl.c:1870
int extra_link
Maximum number of bytes in excess of external network interface&#39;s MTU that might be read from or writ...
Definition: mtu.h:122
#define FRAME_HEADROOM(f)
Definition: mtu.h:187
#define ntohpid(x)
Definition: packet_id.h:64
const char * reliable_ack_print(struct buffer *buf, bool verbose, struct gc_arena *gc)
Definition: reliable.c:265
int n_hard_errors
Definition: ssl_common.h:525
int transition_window
Definition: ssl_common.h:266
#define KEY_DIRECTION_INVERSE
Definition: crypto.h:175
#define INLINE_FILE_TAG
Definition: common.h:95
void * gc_malloc(size_t size, bool clear, struct gc_arena *a)
Definition: buffer.c:383
void frame_init_mssfix(struct frame *frame, const struct options *options)
Set the –mssfix option.
Definition: mtu.c:130
static struct user_pass passbuf
Definition: ssl.c:369
cipher_ctx_t * cipher
Generic cipher context.
Definition: crypto.h:166
#define TLS_RELIABLE_N_SEND_BUFFERS
Definition: ssl.h:79
bool xmit_hold
Definition: ssl_common.h:247
#define GET_USER_PASS_PASSWORD_ONLY
Definition: misc.h:118
unsigned __int32 uint32_t
Definition: config-msvc.h:120
mbedtls_md_info_t md_kt_t
Generic message digest key type context.
#define D_TLS_STATE_ERRORS
Definition: errlevel.h:130
#define S_INITIAL
Initial key_state state after initialization by key_state_init() before start of three-way handshake...
Definition: ssl_common.h:81
unsigned int flags
Definition: route.h:152
int keysize
Definition: options.h:485
#define INCR_ERROR
Definition: ssl.c:104
const char * ciphername
Definition: options.h:481
void tls_ctx_restrict_ciphers(struct tls_root_ctx *ctx, const char *ciphers)
Restrict the list of ciphers that can be used within the TLS context.
Definition: ssl_openssl.c:324
static bool buf_write_u16(struct buffer *dest, int data)
Definition: buffer.h:703
void pem_password_setup(const char *auth_file)
Definition: ssl.c:372
interval_t reliable_send_timeout(const struct reliable *rel)
Determined how many seconds until the earliest resend should be attempted.
Definition: reliable.c:627
void ssl_purge_auth(const bool auth_user_pass_only)
Definition: ssl.c:477
static bool swap_hmac(struct buffer *buf, const struct crypto_options *co, bool incoming)
Definition: ssl.c:1404
int key_id
The current active key id, used to keep track of renegotiations.
Definition: ssl_common.h:417
static bool link_socket_actual_defined(const struct link_socket_actual *act)
Definition: socket.h:684
Container for one set of cipher and/or HMAC contexts.
Definition: crypto.h:164
bool ncp_enabled
Definition: ssl_common.h:300
#define P_CONTROL_V1
Definition: ssl.h:57
#define OPENVPN_PLUGIN_TLS_FINAL
static void reset_session(struct tls_multi *multi, struct tls_session *session)
Definition: ssl.c:1197
struct buffer_list * paybuf
Definition: ssl_common.h:193
mbedtls_cipher_info_t cipher_kt_t
Generic cipher key type context.
static bool reliable_ack_empty(struct reliable_ack *ack)
Check whether an acknowledgment structure contains any packet IDs to be acknowledged.
Definition: reliable.h:151
#define TLS_RELIABLE_N_REC_BUFFERS
Definition: ssl.h:80
void tls_adjust_frame_parameters(struct frame *frame)
Definition: ssl.c:315
struct key_ctx encrypt
Cipher and/or HMAC contexts for sending direction.
Definition: crypto.h:221
static bool session_id_defined(const struct session_id *sid1)
Definition: session_id.h:55
const char * extra_certs_file
Definition: options.h:506
void tls_ctx_server_new(struct tls_root_ctx *ctx)
Initialise a library-specific TLS context for a server.
Definition: ssl_openssl.c:104
int key_state_read_plaintext(struct key_state_ssl *ks_ssl, struct buffer *buf, int maxlen)
Extract plaintext data from the TLS module.
Definition: ssl_openssl.c:1847
int replay_window
Definition: ssl_common.h:294
static SERVICE_STATUS status
Definition: automatic.c:47
void init_key_ctx_bi(struct key_ctx_bi *ctx, const struct key2 *key2, int key_direction, const struct key_type *kt, const char *name)
Definition: crypto.c:874
static bool key_method_1_write(struct buffer *buf, struct tls_session *session)
Definition: ssl.c:2199
unsigned int ssl_flags
Definition: options.h:531
static bool session_id_read(struct session_id *sid, struct buffer *buf)
Definition: session_id.h:61
#define P_CONTROL_HARD_RESET_CLIENT_V2
Definition: ssl.h:63
struct cert_hash_set * locked_cert_hash_set
Definition: ssl_common.h:533
bool tls_check_ncp_cipher_list(const char *list)
Check whether the ciphers in the supplied list are supported.
Definition: ssl.c:4104
struct tls_wrap_ctx tls_wrap
Definition: ssl.h:129
void ssl_set_auth_nocache(void)
Definition: ssl.c:448
int hmac_ctx_size(const hmac_ctx_t *ctx)
struct tls_wrap_ctx tls_wrap
Definition: ssl_common.h:407
#define PERF_TLS_MULTI_PROCESS
Definition: perf.h:42
bool tls_session_update_crypto_params(struct tls_session *session, struct options *options, struct frame *frame)
Update TLS session crypto parameters (cipher and auth) and derive data channel keys based on the supp...
Definition: ssl.c:1957
struct tls_options opt
Definition: ssl_common.h:500
void buf_clear(struct buffer *buf)
Definition: buffer.c:162
int n_soft_errors
Definition: ssl_common.h:526
void crypto_adjust_frame_parameters(struct frame *frame, const struct key_type *kt, bool packet_id, bool packet_id_long_form)
Calculate crypto overhead and adjust frame to account for that.
Definition: crypto.c:698
const md_kt_t * md_kt_get(const char *digest)
Return message digest parameters, based on the given digest name.
const char * cert_file_inline
Definition: options.h:519
const struct plugin_list * plugins
Definition: ssl_common.h:322
struct buffer plaintext_write_buf
Definition: ssl_common.h:186
struct env_item * next
Definition: env_set.h:39
static bool buf_copy(struct buffer *dest, const struct buffer *src)
Definition: buffer.h:717
struct link_socket_actual untrusted_addr
Definition: ssl_common.h:434
char * string
Definition: env_set.h:38
hmac_ctx_t * hmac
Generic HMAC context.
Definition: crypto.h:167
#define S_GOT_KEY
Local OpenVPN process has received the remote&#39;s part of the key material.
Definition: ssl_common.h:97
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:497
#define RGI_HWADDR_DEFINED
Definition: route.h:148
#define PAYLOAD_SIZE_DYNAMIC(f)
Definition: mtu.h:166
void free_key_ctx_bi(struct key_ctx_bi *ctx)
Definition: crypto.c:912
#define PD_TLS_AUTH_HMAC_SIZE_MASK
Definition: ssl.h:570
#define CO_IGNORE_PACKET_ID
Bit-flag indicating whether to ignore the packet ID of a received packet.
Definition: crypto.h:248
char * remote_ciphername
cipher specified in peer&#39;s config file
Definition: ssl_common.h:557
#define INCR_SENT
Definition: ssl.c:101
bool tls_rec_payload(struct tls_multi *multi, struct buffer *buf)
Definition: ssl.c:4029
static void key_source2_print(const struct key_source2 *k)
Definition: ssl.c:1601
void tls_multi_init_set_options(struct tls_multi *multi, const char *local, const char *remote)
Definition: ssl.c:1329
static const char * local_options_string(const struct tls_session *session)
Definition: ssl.c:70
struct connection_entry ce
Definition: options.h:208
static void openvpn_PRF(const uint8_t *secret, int secret_len, const char *label, const uint8_t *client_seed, int client_seed_len, const uint8_t *server_seed, int server_seed_len, const struct session_id *client_sid, const struct session_id *server_sid, uint8_t *output, int output_len)
Definition: ssl.c:1743
Get a tls_cipher_name_pair containing OpenSSL and IANA names for supplied TLS cipher name...
Definition: ssl_backend.h:62
struct packet_id_send send
Definition: packet_id.h:207
uint8_t * data
Pointer to the allocated memory.
Definition: buffer.h:68
#define dmsg
Definition: error.h:174
bool wait_for_push
Definition: misc.h:70
const char * local_options
Definition: ssl_common.h:252
#define TM_SIZE
Size of the tls_multi.session array.
Definition: ssl_common.h:461
#define TLS_VER_1_0
Definition: ssl_backend.h:114
#define TLS_AUTHENTICATION_FAILED
Definition: ssl_verify.h:69
struct key_ctx decrypt
cipher and/or HMAC contexts for receiving direction.
Definition: crypto.h:223
struct key_source client
Random provided by client.
Definition: ssl_common.h:139
int platform_stat(const char *path, platform_stat_t *buf)
Definition: platform.c:327
#define TLS_VER_1_3
Definition: ssl_backend.h:117
#define MAX_HMAC_KEY_LENGTH
void openvpn_encrypt(struct buffer *buf, struct buffer work, struct crypto_options *opt)
Encrypt and HMAC sign a packet so that it can be sent as a data channel VPN tunnel packet to a remote...
Definition: crypto.c:303
Container for bidirectional cipher and HMAC key material.
Definition: crypto.h:181
void tls_ctx_check_cert_time(const struct tls_root_ctx *ctx)
Check our certificate notBefore and notAfter fields, and warn if the cert is either not yet valid or ...
Definition: ssl_openssl.c:459
int tls_version_parse(const char *vstr, const char *extra)
Definition: ssl.c:516
static bool tls_session_user_pass_enabled(struct tls_session *session)
Returns whether or not the server should check for username/password.
Definition: ssl.c:1040
#define P_DATA_V1
Definition: ssl.h:59
static void tls1_P_hash(const md_kt_t *md_kt, const uint8_t *sec, int sec_len, const uint8_t *seed, int seed_len, uint8_t *out, int olen)
Definition: ssl.c:1619
#define CONTROL_SEND_ACK_MAX
Definition: ssl.h:74
#define BLEN(buf)
Definition: buffer.h:127
time_t auth_deferred_expire
Definition: ssl_common.h:202
struct key_source server
Random provided by server.
Definition: ssl_common.h:140
static void tls_session_init(struct tls_multi *multi, struct tls_session *session)
Initialize a tls_session structure.
Definition: ssl.c:1072
bool reliable_wont_break_sequentiality(const struct reliable *rel, packet_id_type id)
Check that a received packet&#39;s ID can safely be stored in the reliable structure&#39;s processing window...
Definition: reliable.c:453
static bool read_control_auth(struct buffer *buf, struct tls_wrap_ctx *ctx, const struct link_socket_actual *from)
Definition: ssl.c:1510
void init_ssl_lib(void)
Definition: ssl.c:348
void tls_poor_mans_ncp(struct options *o, const char *remote_ciphername)
"Poor man&#39;s NCP": Use peer cipher if it is an allowed (NCP) cipher.
Definition: ssl.c:1908
void verify_user_pass(struct user_pass *up, struct tls_multi *multi, struct tls_session *session)
Verify the given username and password, using either an external script, a plugin, or the management interface.
Definition: ssl_verify.c:1282
#define P_OPCODE_SHIFT
Definition: ssl.h:51
struct buffer * reliable_get_buf_sequenced(struct reliable *rel)
Get the buffer of the next sequential and active entry.
Definition: reliable.c:526
void auth_user_pass_setup(const char *auth_file, const struct static_challenge_info *sci)
Definition: ssl.c:407
struct frame frame
Definition: ssl.h:130
#define D_HANDSHAKE
Definition: errlevel.h:72
static bool get_user_pass(struct user_pass *up, const char *auth_file, const char *prefix, const unsigned int flags)
Definition: misc.h:137
int key_id
Key id for this key_state, inherited from struct tls_session.
Definition: ssl_common.h:169
#define GET_USER_PASS_DYNAMIC_CHALLENGE
Definition: misc.h:124
bool openvpn_decrypt(struct buffer *buf, struct buffer work, struct crypto_options *opt, const struct frame *frame, const uint8_t *ad_start)
HMAC verify and decrypt a data channel packet received from a remote OpenVPN peer.
Definition: crypto.c:672
#define D_SHOW_KEY_SOURCE
Definition: errlevel.h:118
#define TLSMP_KILL
Definition: ssl.h:229
void tls_ctx_load_ca(struct tls_root_ctx *ctx, const char *ca_file, const char *ca_file_inline, const char *ca_path, bool tls_server)
Load certificate authority certificates from the given file or path.
Definition: ssl_openssl.c:1350
unsigned __int8 uint8_t
Definition: config-msvc.h:122
struct buffer * reliable_send(struct reliable *rel, int *opcode)
Get the next packet to send to the remote peer.
Definition: reliable.c:570
void reliable_mark_deleted(struct reliable *rel, struct buffer *buf, bool inc_pid)
Remove an entry from a reliable structure.
Definition: reliable.c:723
struct session_id session_id
Definition: ssl_common.h:410
bool get_user_pass_cr(struct user_pass *up, const char *auth_file, const char *prefix, const unsigned int flags, const char *auth_challenge)
Definition: misc.c:124
bool tls_pre_decrypt(struct tls_multi *multi, const struct link_socket_actual *from, struct buffer *buf, struct crypto_options **opt, bool floated, const uint8_t **ad_start)
Determine whether an incoming packet is a data channel or control channel packet, and process accordi...
Definition: ssl.c:3314
#define ALLOC_ARRAY_CLEAR_GC(dptr, type, n, gc)
Definition: buffer.h:1048
void purge_user_pass(struct user_pass *up, const bool force)
Definition: misc.c:506
Structure that wraps the TLS context.
Definition: ssl_mbedtls.h:66
static bool buf_write_u32(struct buffer *dest, int data)
Definition: buffer.h:710
#define ALLOC_OBJ_CLEAR_GC(dptr, type, gc)
Definition: buffer.h:1063
static char * read_string_alloc(struct buffer *buf)
Definition: ssl.c:2173
char * auth_token
If server sends a generated auth-token, this is the token to use for future user/pass authentications...
Definition: ssl_common.h:559
#define OPENVPN_PLUGIN_AUTH_USER_PASS_VERIFY
bool plugin_defined(const struct plugin_list *pl, const int type)
Definition: plugin.c:895
static void key_state_free(struct key_state *ks, bool clear)
Cleanup a key_state structure.
Definition: ssl.c:980
#define KS_LAME_DUCK
Key state index that will retire soon.
Definition: ssl_common.h:369
static void check_malloc_return(const void *p)
Definition: buffer.h:1069
#define P_CONTROL_SOFT_RESET_V1
Definition: ssl.h:56
const char * extra_certs_file_inline
Definition: options.h:520
struct key_source2 * key_src
Definition: ssl_common.h:183
int initial_opcode
Definition: ssl_common.h:409
void tls_ctx_load_dh_params(struct tls_root_ctx *ctx, const char *dh_file, const char *dh_file_inline)
Load Diffie Hellman Parameters, and load them into the library-specific TLS context.
Definition: ssl_openssl.c:508
static bool key_method_1_read(struct buffer *buf, struct tls_session *session)
Definition: ssl.c:2448
struct key_ctx_bi key_ctx_bi
OpenSSL cipher and HMAC contexts for both sending and receiving directions.
Definition: crypto.h:234
void delayed_auth_pass_purge(void)
Definition: ssl.c:4249
Security parameter state of a single session within a VPN tunnel.
Definition: ssl_common.h:398
#define VALGRIND_MAKE_READABLE(addr, len)
Definition: memdbg.h:53
#define S_SENT_KEY
Local OpenVPN process has sent its part of the key material.
Definition: ssl_common.h:94
bool tls_ctx_set_options(struct tls_root_ctx *ctx, unsigned int ssl_flags)
Set any library specific options.
Definition: ssl_openssl.c:280
void output_peer_info_env(struct env_set *es, const char *peer_info)
Definition: misc.c:783
static void write_control_auth(struct tls_session *session, struct key_state *ks, struct buffer *buf, struct link_socket_actual **to_link_addr, int opcode, int max_ack, bool prepend_ack)
Definition: ssl.c:1459
#define msg
Definition: error.h:173
Definition: misc.h:65
int renegotiate_packets
Definition: ssl_common.h:270
int push_peer_info_detail
Definition: ssl_common.h:265
The acknowledgment structure in which packet IDs are stored for later acknowledgment.
Definition: reliable.h:64
int initial_opcode
Definition: ssl_common.h:177
bool disable_occ
Definition: ssl_common.h:261
Wrapper structure for dynamically allocated memory.
Definition: buffer.h:60
bool reliable_ack_read_packet_id(struct buffer *buf, packet_id_type *pid)
Read the packet ID of a received packet.
Definition: reliable.c:123
struct frame frame
Definition: ssl_common.h:306
void tls_multi_init_finalize(struct tls_multi *multi, const struct frame *frame)
Finalize initialization of a tls_multi structure.
Definition: ssl.c:1275
#define TLS_AUTHENTICATION_SUCCEEDED
Definition: ssl_verify.h:68
#define buf_init(buf, offset)
Definition: buffer.h:196
#define OPENVPN_OP_ENCRYPT
Cipher should encrypt.
bool tls_send_payload(struct tls_multi *multi, const uint8_t *data, int size)
Definition: ssl.c:3990
static bool buf_write_prepend(struct buffer *dest, const void *src, int size)
Definition: buffer.h:684
static bool key_method_2_write(struct buffer *buf, struct tls_session *session)
Definition: ssl.c:2339
void frame_finalize(struct frame *frame, bool link_mtu_defined, int link_mtu, bool tun_mtu_defined, int tun_mtu)
Definition: mtu.c:56
#define OPENVPN_OP_DECRYPT
Cipher should decrypt.
bool reliable_can_send(const struct reliable *rel)
Check whether a reliable structure has any active entries ready to be (re)sent.
Definition: reliable.c:542
void management_set_state(struct management *man, const int state, const char *detail, const in_addr_t *tun_local_ip, const struct in6_addr *tun_local_ip6, const struct openvpn_sockaddr *local, const struct openvpn_sockaddr *remote)
Definition: manage.c:2685
int cipher_kt_block_size(const cipher_kt_t *cipher_kt)
Returns the block size of the cipher, in bytes.
char * locked_username
Definition: ssl_common.h:532
char * common_name
Definition: ssl_common.h:423
void reliable_init(struct reliable *rel, int buf_size, int offset, int array_size, bool hold)
Initialize a reliable structure.
Definition: reliable.c:309
int tls_ctx_load_priv_file(struct tls_root_ctx *ctx, const char *priv_key_file, const char *priv_key_file_inline)
Load private key file into the given TLS context.
Definition: ssl_openssl.c:882
void crypto_uninit_lib(void)
const char * translate_cipher_name_from_openvpn(const char *cipher_name)
Translate a data channel cipher name from the crypto library specific name to the OpenVPN config file...
Definition: crypto.c:1794
The reliability layer storage structure for one VPN tunnel&#39;s control channel in one direction...
Definition: reliable.h:88
int link_mtu
Maximum packet size to be sent over the external network interface.
Definition: mtu.h:94
#define D_TLS_DEBUG_MED
Definition: errlevel.h:152
#define TM_LAME_DUCK
Old tls_session.
Definition: ssl_common.h:460
struct buffer alloc_buf_gc(size_t size, struct gc_arena *gc)
Definition: buffer.c:88
uint8_t hwaddr[6]
Definition: route.h:162
uint32_t peer_id
Definition: ssl_common.h:554
int key_state_write_ciphertext(struct key_state_ssl *ks_ssl, struct buffer *buf)
Insert a ciphertext buffer into the TLS module.
Definition: ssl_openssl.c:1832
uint32_t packet_id_type
Definition: packet_id.h:49
#define PD_VERBOSE
Definition: ssl.h:573
static const char * state_name(int state)
Definition: ssl.c:742
void tls_init_lib(void)
Perform any static initialisation necessary by the library.
Definition: ssl_openssl.c:76
bool tls_crypt_unwrap(const struct buffer *src, struct buffer *dst, struct crypto_options *opt)
Unwrap a control channel packet (decrypts, authenticates and performs replay checks).
Definition: tls_crypt.c:170
static bool generate_key_expansion(struct key_ctx_bi *key, const struct key_type *key_type, const struct key_source2 *key_src, const struct session_id *client_sid, const struct session_id *server_sid, bool server)
Definition: ssl.c:1789
void tls_clear_error(void)
Clear the underlying SSL library&#39;s error state.
Definition: ssl_openssl.c:98
void ssl_purge_auth_challenge(void)
Definition: ssl.c:495
static int min_int(int x, int y)
Definition: integer.h:47
#define PACKAGE_VERSION
Definition: config.h:742
static int buf_forward_capacity_total(const struct buffer *buf)
Definition: buffer.h:563
bool reliable_can_get(const struct reliable *rel)
Check whether a reliable structure has any free buffers available for use.
Definition: reliable.c:407
#define free
Definition: cmocka.c:1850
void tls_ctx_load_cert_file(struct tls_root_ctx *ctx, const char *cert_file, const char *cert_file_inline)
Use Windows cryptoapi for key and cert, and add to library-specific TLS context.
Definition: ssl_openssl.c:875
void tls_x509_clear_env(struct env_set *es)
Remove any X509_ env variables from env_set es.
Definition: ssl_verify.c:1533
int tls_version_max(void)
Return the maximum TLS version (as a TLS_VER_x constant) supported by current SSL implementation...
Definition: ssl_openssl.c:211
#define PD_TLS
Definition: ssl.h:572
#define P_CONTROL_HARD_RESET_CLIENT_V1
Definition: ssl.h:54
void generate_key_random(struct key *key, const struct key_type *kt)
Definition: crypto.c:1021
void key2_print(const struct key2 *k, const struct key_type *kt, const char *prefix0, const char *prefix1)
Definition: crypto.c:1065
Garbage collection arena used to keep track of dynamically allocated memory.
Definition: buffer.h:116
bool reliable_ack_read(struct reliable_ack *ack, struct buffer *buf, const struct session_id *sid)
Read an acknowledgment record from a received packet.
Definition: reliable.c:158
const char * openssl_name
Definition: ssl_backend.h:62
void get_default_gateway(struct route_gateway_info *rgi)
Definition: route.c:2718
static bool link_socket_actual_match(const struct link_socket_actual *a1, const struct link_socket_actual *a2)
Definition: socket.h:871
void cert_hash_free(struct cert_hash_set *chs)
Frees the given set of certificate hashes.
Definition: ssl_verify.c:268
int key_method
Definition: ssl_common.h:257
#define FULL_SYNC
Definition: ssl.c:2101
static int buf_read_u16(struct buffer *buf)
Definition: buffer.h:808
static struct buffer clear_buf(void)
Return an empty struct buffer.
Definition: buffer.h:209
int interval_t
Definition: common.h:45
#define UP_TYPE_PRIVATE_KEY
Definition: ssl_common.h:42
static void key_source_print(const struct key_source *k, const char *prefix)
Definition: ssl.c:1575
counter_type n_bytes
Definition: ssl_common.h:195
struct buffer ack_write_buf
Definition: ssl_common.h:187
const char * session_id_print(const struct session_id *sid, struct gc_arena *gc)
Definition: session_id.c:57
uint8_t implicit_iv[OPENVPN_MAX_IV_LENGTH]
The implicit part of the IV.
Definition: crypto.h:168
void hmac_ctx_init(hmac_ctx_t *ctx, const uint8_t *key, int key_length, const md_kt_t *kt)
int key_state_read_ciphertext(struct key_state_ssl *ks_ssl, struct buffer *buf, int maxlen)
Extract ciphertext data from the TLS module.
Definition: ssl_openssl.c:1817
static const tls_cipher_name_pair tls_cipher_name_translation_table[]
SSL/TLS Cipher suite name translation table.
Definition: ssl.c:111
static void key_state_init(struct tls_session *session, struct key_state *ks)
Initialize a key_state structure.
Definition: ssl.c:900
static int key_source2_read(struct key_source2 *k2, struct buffer *buf, bool server)
Definition: ssl.c:2055
#define BSTR(buf)
Definition: buffer.h:129
static bool auth_user_pass_enabled
Definition: ssl.c:399
hmac_ctx_t * hmac_ctx_new(void)
#define TUN_LINK_DELTA(f)
Definition: mtu.h:151
#define KEY_METHOD_MASK
Definition: ssl.h:116
size_t crypto_max_overhead(void)
Return the worst-case OpenVPN crypto overhead (in bytes)
Definition: crypto.c:732
const char * dh_file
Definition: options.h:504
time_t must_die
Definition: ssl_common.h:175
#define KEY_EXPANSION_ID
Definition: ssl.h:47
static void tls_session_free(struct tls_session *session, bool clear)
Clean up a tls_session structure.
Definition: ssl.c:1137
char password[USER_PASS_LEN]
Definition: misc.h:79
struct buffer clone_buf(const struct buffer *buf)
Definition: buffer.c:115
void verify_final_auth_checks(struct tls_multi *multi, struct tls_session *session)
Perform final authentication checks, including locking of the cn, the allowed certificate hashes...
Definition: ssl_verify.c:1471
static bool random_bytes_to_buf(struct buffer *buf, uint8_t *out, int outlen)
Definition: ssl.c:2006
void reliable_mark_active_incoming(struct reliable *rel, struct buffer *buf, packet_id_type pid, int opcode)
Mark the reliable entry associated with the given buffer as active incoming.
Definition: reliable.c:664
struct gc_arena gc
Definition: options.h:178
void hmac_ctx_final(hmac_ctx_t *ctx, uint8_t *dst)
const cipher_kt_t * cipher
Cipher static parameters.
Definition: crypto.h:143
static void update_time(void)
Definition: otime.h:93
bool replay
Definition: options.h:489
static int auth_deferred_expire_window(const struct tls_options *o)
Definition: ssl.c:2690
char * dest
Definition: compat-lz4.h:431
counter_type n_packets
Definition: ssl_common.h:196
int tls_peer_info_ncp_ver(const char *peer_info)
Return the Negotiable Crypto Parameters version advertised in the peer info string, or 0 if none specified.
Definition: ssl.c:4088
#define TLS_CHANNEL_BUF_SIZE
Definition: common.h:78
#define MF_EXTERNAL_CERT
Definition: manage.h:355
void buffer_list_pop(struct buffer_list *ol)
Definition: buffer.c:1328
#define P_ACK_V1
Definition: ssl.h:58
void hmac_ctx_free(hmac_ctx_t *ctx)
struct buffer * buffer_list_peek(struct buffer_list *ol)
Definition: buffer.c:1258
const char * dh_file_inline
Definition: options.h:523
struct buffer_entry * buffer_list_push_data(struct buffer_list *ol, const void *data, size_t size)
Definition: buffer.c:1231
const char * remote_options
Definition: ssl_common.h:253
#define P_DATA_V2
Definition: ssl.h:60
const tls_cipher_name_pair * tls_get_cipher_name_pair(const char *cipher_name, size_t len)
Definition: ssl.c:269
int replay_time
Definition: ssl_common.h:295
void reliable_schedule_now(struct reliable *rel)
Reschedule all entries of a reliable structure to be ready for (re)sending immediately.
Definition: reliable.c:608
void reliable_send_purge(struct reliable *rel, const struct reliable_ack *ack)
Remove acknowledged packets from a reliable structure.
Definition: reliable.c:355
static int packet_id_size(bool long_form)
Definition: packet_id.h:305
const cipher_kt_t * cipher_kt_get(const char *ciphername)
Return cipher parameters, based on the given cipher name.
void crypto_init_lib(void)
unsigned int ssl_flags
Definition: ssl_common.h:340
char * priv_key_file_inline
Definition: options.h:522
struct _stat platform_stat_t
Definition: platform.h:141
#define PD_SHOW_DATA
Definition: ssl.h:571
uint8_t pre_master[48]
Random used for master secret generation, provided only by client OpenVPN peer.
Definition: ssl_common.h:122
#define M_WARN
Definition: error.h:96
void hmac_ctx_reset(hmac_ctx_t *ctx)
struct env_set * es
Definition: ssl_common.h:321
static bool session_id_write_prepend(const struct session_id *sid, struct buffer *buf)
Definition: session_id.h:67
static bool key_method_2_read(struct buffer *buf, struct tls_multi *multi, struct tls_session *session)
Definition: ssl.c:2509
Container for two sets of OpenSSL cipher and/or HMAC contexts for both sending and receiving directio...
Definition: crypto.h:219
void init_key_type(struct key_type *kt, const char *ciphername, const char *authname, int keysize, bool tls_mode, bool warn)
Initialize a key_type structure with.
Definition: crypto.c:743
Container for unidirectional cipher and HMAC key material.
Definition: crypto.h:151
struct tls_wrap_ctx tls_wrap
TLS handshake wrapping state.
Definition: ssl_common.h:303
#define GET_USER_PASS_MANAGEMENT
Definition: misc.h:116
bool reliable_ack_acknowledge_packet_id(struct reliable_ack *ack, packet_id_type pid)
Record a packet ID for later acknowledgment.
Definition: reliable.c:141
int link_mtu_dynamic
Dynamic MTU value for the external network interface.
Definition: mtu.h:97
enum tls_wrap_ctx::@9 mode
Control channel wrapping mode.
int link_mtu
Definition: options.h:111
#define INCR_GENERATED
Definition: ssl.c:102
int tls_multi_process(struct tls_multi *multi, struct buffer *to_link, struct link_socket_actual **to_link_addr, struct link_socket_info *to_link_socket_info, interval_t *wakeup)
Definition: ssl.c:3119
const char * crl_file
Definition: options.h:516