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