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