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