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