Debian Codegraph @

contrib/mod_tls.c

raw symbols SCIP
1 /*
2 * mod_tls - An RFC2228 SSL/TLS module for ProFTPD
3 *
4 * Copyright (c) 2000-2002 Peter 'Luna' Runestig <[email protected]>
5 * Copyright (c) 2002-2026 TJ Saunders <[email protected]>
6 * All rights reserved.
7 *
8 * Redistribution and use in source and binary forms, with or without modifi-
9 * cation, are permitted provided that the following conditions are met:
10 *
11 * o Redistributions of source code must retain the above copyright notice,
12 * this list of conditions and the following disclaimer.
13 *
14 * o Redistributions in binary form must reproduce the above copyright no-
15 * tice, this list of conditions and the following disclaimer in the do-
16 * cumentation and/or other materials provided with the distribution.
17 *
18 * o The names of the contributors may not be used to endorse or promote
19 * products derived from this software without specific prior written
20 * permission.
21 *
22 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
23 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
24 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
25 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LI-
26 * ABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUEN-
27 * TIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEV-
29 * ER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABI-
30 * LITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
31 * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
32 *
33 * --- DO NOT DELETE BELOW THIS LINE ----
34 * $Libraries: -lssl -lcrypto$
35 */
36
37 #include "conf.h"
38 #include "privs.h"
39 #include "mod_tls.h"
40
41 #ifdef PR_USE_CTRLS
42 # include "mod_ctrls.h"
43 #endif
44
45 /* Define if you have the LibreSSL library.
46 *
47 * Note that in LibreSSL-3.5.0, the structs became opaque, as they are in
48 * OpenSSL-1.1.0, and thus these version-dependent macros became more
49 * complex.
50 */
51 #if defined(LIBRESSL_VERSION_NUMBER)
52 # define HAVE_LIBRESSL 1
53 #endif
54
55 /* Note that the openssl/ssl.h header is already included in mod_tls.h, so
56 * we don't need to include it here.
57 */
58
59 #include <openssl/err.h>
60 #include <openssl/conf.h>
61 #include <openssl/bn.h>
62 #include <openssl/crypto.h>
63 #include <openssl/dh.h>
64 #include <openssl/rsa.h>
65 #include <openssl/evp.h>
66 #include <openssl/ssl.h>
67 #include <openssl/ssl3.h>
68 #include <openssl/x509v3.h>
69 #include <openssl/pkcs12.h>
70 #include <openssl/rand.h>
71 #if OPENSSL_VERSION_NUMBER > 0x000907000L
72 # ifdef PR_USE_OPENSSL_ENGINE
73 # include <openssl/engine.h>
74 # endif /* PR_USE_OPENSSL_ENGINE */
75 # ifdef PR_USE_OPENSSL_OCSP
76 # include <openssl/ocsp.h>
77 # endif /* PR_USE_OPENSSL_OCSP */
78 #endif
79 #ifdef PR_USE_OPENSSL_ECC
80 # include <openssl/ec.h>
81 # include <openssl/ecdh.h>
82 #endif /* PR_USE_OPENSSL_ECC */
83
84 #ifdef HAVE_MLOCK
85 # include <sys/mman.h>
86 #endif
87
88 #define MOD_TLS_VERSION "mod_tls/2.9.2"
89
90 /* Make sure the version of proftpd is as necessary. */
91 #if PROFTPD_VERSION_NUMBER < 0x0001030602
92 # error "ProFTPD 1.3.6rc2 or later required"
93 #endif
94
95 extern pr_response_t *resp_list, *resp_err_list;
96 extern session_t session;
97 extern xaset_t *server_list;
98 extern int ServerUseReverseDNS;
99
100 static const char *trace_channel = "tls";
101
102 static DH *get_dh(BIGNUM *p, BIGNUM *g) {
103 DH *dh;
104
105 dh = DH_new();
106 if (dh == NULL) {
107 return NULL;
108 }
109
110 #if (OPENSSL_VERSION_NUMBER >= 0x10100000L && !defined(HAVE_LIBRESSL)) || \
111 (defined(HAVE_LIBRESSL) && LIBRESSL_VERSION_NUMBER >= 0x3050000L)
112 if (DH_set0_pqg(dh, p, NULL, g) != 1) {
113 pr_trace_msg(trace_channel, 3, "error setting DH p/q parameters: %s",
114 ERR_error_string(ERR_get_error(), NULL));
115 DH_free(dh);
116 return NULL;
117 }
118 #else
119 dh->p = p;
120 dh->g = g;
121 #endif /* OpenSSL 1.1.x/LibreSSL-3.5.x and later */
122
123 return dh;
124 }
125
126 static X509 *read_cert(FILE *fh, SSL_CTX *ctx) {
127 pem_password_cb *cb;
128 void *cb_data;
129
130 #if (OPENSSL_VERSION_NUMBER >= 0x10100000L && !defined(HAVE_LIBRESSL)) || \
131 (defined(HAVE_LIBRESSL) && LIBRESSL_VERSION_NUMBER >= 0x3050000L)
132 cb = SSL_CTX_get_default_passwd_cb(ctx);
133 cb_data = SSL_CTX_get_default_passwd_cb_userdata(ctx);
134 #else
135 cb = ctx->default_passwd_callback;
136 cb_data = ctx->default_passwd_callback_userdata;
137 #endif /* OpenSSL-1.1.x/LibreSSL-3.5.x and later */
138
139 return PEM_read_X509(fh, NULL, cb, cb_data);
140 }
141
142 static int get_pkey_type(EVP_PKEY *pkey) {
143 int pkey_type;
144
145 #if OPENSSL_VERSION_NUMBER >= 0x10100000L && \
146 !defined(HAVE_LIBRESS)
147 pkey_type = EVP_PKEY_base_id(pkey);
148 #else
149 pkey_type = EVP_PKEY_type(pkey->type);
150 #endif /* OpenSSL 1.1.x and later */
151
152 return pkey_type;
153 }
154
155 /* DH parameters. These are generated using:
156 *
157 * # openssl dhparam -2|-5 512|768|1024|1536|2048|3072|4096 -C
158 *
159 * These should be regenerated periodically by the mod_tls maintainer.
160 * Last updated on 2020-09-06.
161 */
162
163 /*
164 -----BEGIN DH PARAMETERS-----
165 MEYCQQD+cn2+9HFswkQ6nDJE++frLGxfICNarfzXtlq/K4dbp2rqSAEIL2EzcsKZ
166 WsqjOZ1ixcyq0TmRft9FAkUuWYxHAgEF
167 -----END DH PARAMETERS-----
168 */
169
170 static unsigned char dh512_p[] = {
171 0xFE, 0x72, 0x7D, 0xBE, 0xF4, 0x71, 0x6C, 0xC2, 0x44, 0x3A, 0x9C, 0x32,
172 0x44, 0xFB, 0xE7, 0xEB, 0x2C, 0x6C, 0x5F, 0x20, 0x23, 0x5A, 0xAD, 0xFC,
173 0xD7, 0xB6, 0x5A, 0xBF, 0x2B, 0x87, 0x5B, 0xA7, 0x6A, 0xEA, 0x48, 0x01,
174 0x08, 0x2F, 0x61, 0x33, 0x72, 0xC2, 0x99, 0x5A, 0xCA, 0xA3, 0x39, 0x9D,
175 0x62, 0xC5, 0xCC, 0xAA, 0xD1, 0x39, 0x91, 0x7E, 0xDF, 0x45, 0x02, 0x45,
176 0x2E, 0x59, 0x8C, 0x47
177 };
178
179 static unsigned char dh512_g[] = { 0x05 };
180
181 static DH *get_dh512(void) {
182 BIGNUM *p, *g;
183
184 p = BN_bin2bn(dh512_p, sizeof(dh512_p), NULL);
185 g = BN_bin2bn(dh512_g, sizeof(dh512_g), NULL);
186 if (p == NULL ||
187 g == NULL) {
188 return NULL;
189 }
190
191 return get_dh(p, g);
192 }
193
194 /*
195 -----BEGIN DH PARAMETERS-----
196 MGYCYQCRml8Rc/DxvTA+PTaKH5g6VJYqyw5bHvV+tnuTveVldfuboiBWpZpawEtf
197 w2lgFSfrG8S6VoWLQ2vh8x6cAMw9oiSKIq9dLkIrOkKSx2xqc521V6NJZnitOXK3
198 arsZCwsCAQI=
199 -----END DH PARAMETERS-----
200 */
201
202 static unsigned char dh768_p[] = {
203 0x91, 0x9A, 0x5F, 0x11, 0x73, 0xF0, 0xF1, 0xBD, 0x30, 0x3E, 0x3D, 0x36,
204 0x8A, 0x1F, 0x98, 0x3A, 0x54, 0x96, 0x2A, 0xCB, 0x0E, 0x5B, 0x1E, 0xF5,
205 0x7E, 0xB6, 0x7B, 0x93, 0xBD, 0xE5, 0x65, 0x75, 0xFB, 0x9B, 0xA2, 0x20,
206 0x56, 0xA5, 0x9A, 0x5A, 0xC0, 0x4B, 0x5F, 0xC3, 0x69, 0x60, 0x15, 0x27,
207 0xEB, 0x1B, 0xC4, 0xBA, 0x56, 0x85, 0x8B, 0x43, 0x6B, 0xE1, 0xF3, 0x1E,
208 0x9C, 0x00, 0xCC, 0x3D, 0xA2, 0x24, 0x8A, 0x22, 0xAF, 0x5D, 0x2E, 0x42,
209 0x2B, 0x3A, 0x42, 0x92, 0xC7, 0x6C, 0x6A, 0x73, 0x9D, 0xB5, 0x57, 0xA3,
210 0x49, 0x66, 0x78, 0xAD, 0x39, 0x72, 0xB7, 0x6A, 0xBB, 0x19, 0x0B, 0x0B
211 };
212
213 static unsigned char dh768_g[] = { 0x02 };
214
215 static DH *get_dh768(void) {
216 BIGNUM *p, *g;
217
218 p = BN_bin2bn(dh768_p, sizeof(dh768_p), NULL);
219 g = BN_bin2bn(dh768_g, sizeof(dh768_g), NULL);
220 if (p == NULL ||
221 g == NULL) {
222 return NULL;
223 }
224
225 return get_dh(p, g);
226 }
227
228 /*
229 -----BEGIN DH PARAMETERS-----
230 MIGHAoGBAL6bLxesGZixY9/e+yO6YhYZr9tPzICQB4NnyaTyGX+oV7u+hiQ/c0vu
231 b2wiS859u77+obrB4UJD7K5wD/ZZLReITbTlO6dvGyzwAslX3WO1IpoCprHb9KJ9
232 8Y9qSZDpZ9gMXcj+wSNyzeTqrQvOaFH7VzXN2+PonX/X7mT7qanbAgEC
233 -----END DH PARAMETERS-----
234 */
235
236 static unsigned char dh1024_p[] = {
237 0xBE, 0x9B, 0x2F, 0x17, 0xAC, 0x19, 0x98, 0xB1, 0x63, 0xDF, 0xDE, 0xFB,
238 0x23, 0xBA, 0x62, 0x16, 0x19, 0xAF, 0xDB, 0x4F, 0xCC, 0x80, 0x90, 0x07,
239 0x83, 0x67, 0xC9, 0xA4, 0xF2, 0x19, 0x7F, 0xA8, 0x57, 0xBB, 0xBE, 0x86,
240 0x24, 0x3F, 0x73, 0x4B, 0xEE, 0x6F, 0x6C, 0x22, 0x4B, 0xCE, 0x7D, 0xBB,
241 0xBE, 0xFE, 0xA1, 0xBA, 0xC1, 0xE1, 0x42, 0x43, 0xEC, 0xAE, 0x70, 0x0F,
242 0xF6, 0x59, 0x2D, 0x17, 0x88, 0x4D, 0xB4, 0xE5, 0x3B, 0xA7, 0x6F, 0x1B,
243 0x2C, 0xF0, 0x02, 0xC9, 0x57, 0xDD, 0x63, 0xB5, 0x22, 0x9A, 0x02, 0xA6,
244 0xB1, 0xDB, 0xF4, 0xA2, 0x7D, 0xF1, 0x8F, 0x6A, 0x49, 0x90, 0xE9, 0x67,
245 0xD8, 0x0C, 0x5D, 0xC8, 0xFE, 0xC1, 0x23, 0x72, 0xCD, 0xE4, 0xEA, 0xAD,
246 0x0B, 0xCE, 0x68, 0x51, 0xFB, 0x57, 0x35, 0xCD, 0xDB, 0xE3, 0xE8, 0x9D,
247 0x7F, 0xD7, 0xEE, 0x64, 0xFB, 0xA9, 0xA9, 0xDB
248 };
249
250 static unsigned char dh1024_g[] = { 0x02 };
251
252 static DH *get_dh1024(void) {
253 BIGNUM *p, *g;
254
255 p = BN_bin2bn(dh1024_p, sizeof(dh1024_p), NULL);
256 g = BN_bin2bn(dh1024_g, sizeof(dh1024_g), NULL);
257 if (p == NULL ||
258 g == NULL) {
259 return NULL;
260 }
261
262 return get_dh(p, g);
263 }
264
265 /*
266 -----BEGIN DH PARAMETERS-----
267 MIHHAoHBAIlVwpnMVrApIrhfGphb6oHUJq85ndlAWBPrPaR8COnjgKF97ho5TVe3
268 xH8CrQGOUv5bl1gOXKH445mb1IvR6N/6WoLajKpLHEp2vSDJWhGZDcBow7UWZtNG
269 cm2Spp+M5lKXO6ZjZ37fZ9cw8RBOlgqNiuxTvfxYtG42X4Y949KV9ITCs9L1ozat
270 /eSufUdd3ick0EVSCy1iDbk2GU/fZxLO1lpnF2djIqVPkbwyY5e83rBxL3zWsS5u
271 44ec7FQWYwIBAg==
272 -----END DH PARAMETERS-----
273 */
274
275 static unsigned char dh1536_p[] = {
276 0x89, 0x55, 0xC2, 0x99, 0xCC, 0x56, 0xB0, 0x29, 0x22, 0xB8, 0x5F, 0x1A,
277 0x98, 0x5B, 0xEA, 0x81, 0xD4, 0x26, 0xAF, 0x39, 0x9D, 0xD9, 0x40, 0x58,
278 0x13, 0xEB, 0x3D, 0xA4, 0x7C, 0x08, 0xE9, 0xE3, 0x80, 0xA1, 0x7D, 0xEE,
279 0x1A, 0x39, 0x4D, 0x57, 0xB7, 0xC4, 0x7F, 0x02, 0xAD, 0x01, 0x8E, 0x52,
280 0xFE, 0x5B, 0x97, 0x58, 0x0E, 0x5C, 0xA1, 0xF8, 0xE3, 0x99, 0x9B, 0xD4,
281 0x8B, 0xD1, 0xE8, 0xDF, 0xFA, 0x5A, 0x82, 0xDA, 0x8C, 0xAA, 0x4B, 0x1C,
282 0x4A, 0x76, 0xBD, 0x20, 0xC9, 0x5A, 0x11, 0x99, 0x0D, 0xC0, 0x68, 0xC3,
283 0xB5, 0x16, 0x66, 0xD3, 0x46, 0x72, 0x6D, 0x92, 0xA6, 0x9F, 0x8C, 0xE6,
284 0x52, 0x97, 0x3B, 0xA6, 0x63, 0x67, 0x7E, 0xDF, 0x67, 0xD7, 0x30, 0xF1,
285 0x10, 0x4E, 0x96, 0x0A, 0x8D, 0x8A, 0xEC, 0x53, 0xBD, 0xFC, 0x58, 0xB4,
286 0x6E, 0x36, 0x5F, 0x86, 0x3D, 0xE3, 0xD2, 0x95, 0xF4, 0x84, 0xC2, 0xB3,
287 0xD2, 0xF5, 0xA3, 0x36, 0xAD, 0xFD, 0xE4, 0xAE, 0x7D, 0x47, 0x5D, 0xDE,
288 0x27, 0x24, 0xD0, 0x45, 0x52, 0x0B, 0x2D, 0x62, 0x0D, 0xB9, 0x36, 0x19,
289 0x4F, 0xDF, 0x67, 0x12, 0xCE, 0xD6, 0x5A, 0x67, 0x17, 0x67, 0x63, 0x22,
290 0xA5, 0x4F, 0x91, 0xBC, 0x32, 0x63, 0x97, 0xBC, 0xDE, 0xB0, 0x71, 0x2F,
291 0x7C, 0xD6, 0xB1, 0x2E, 0x6E, 0xE3, 0x87, 0x9C, 0xEC, 0x54, 0x16, 0x63
292 };
293
294 static unsigned char dh1536_g[] = { 0x02 };
295
296 static DH *get_dh1536(void) {
297 BIGNUM *p, *g;
298
299 p = BN_bin2bn(dh1536_p, sizeof(dh1536_p), NULL);
300 g = BN_bin2bn(dh1536_g, sizeof(dh1536_g), NULL);
301 if (p == NULL ||
302 g == NULL) {
303 return NULL;
304 }
305
306 return get_dh(p, g);
307 }
308
309 /*
310 -----BEGIN DH PARAMETERS-----
311 MIIBCAKCAQEAokZl6gkqR508V6bb9q3ThOotaZe/XOwJ+Rsn+awFG7p6OIUzELov
312 Bu+fMafN6RBREAYCz4D8rTDMcKS6lSg/y2D58npjQ3drDrOUjuC63S4a9neCxb2c
313 1LRhSdcKcjm0mpvQBBcAUsDsk3iMKceJzPqR7/TJV0AKuigPfHBkh7fuB8Z0hNk2
314 dotwrzEPvA5NFKXnT38V5vPyAFmZOHsYVxcn1GcSL1ktNQ1I9ixh49dMW20vsAWn
315 fNvJMXEuBSWSKkAjgEjI/qL5Wzf7QmiT72ZcJgbVPSYdi4Tv5vh0LC5ArdubHkX/
316 CGtf9RcxDu8h52EK+qJp77xv6c+U4qDHiwIBBQ==
317 -----END DH PARAMETERS-----
318 */
319
320 static unsigned char dh2048_p[] = {
321 0xA2, 0x46, 0x65, 0xEA, 0x09, 0x2A, 0x47, 0x9D, 0x3C, 0x57, 0xA6, 0xDB,
322 0xF6, 0xAD, 0xD3, 0x84, 0xEA, 0x2D, 0x69, 0x97, 0xBF, 0x5C, 0xEC, 0x09,
323 0xF9, 0x1B, 0x27, 0xF9, 0xAC, 0x05, 0x1B, 0xBA, 0x7A, 0x38, 0x85, 0x33,
324 0x10, 0xBA, 0x2F, 0x06, 0xEF, 0x9F, 0x31, 0xA7, 0xCD, 0xE9, 0x10, 0x51,
325 0x10, 0x06, 0x02, 0xCF, 0x80, 0xFC, 0xAD, 0x30, 0xCC, 0x70, 0xA4, 0xBA,
326 0x95, 0x28, 0x3F, 0xCB, 0x60, 0xF9, 0xF2, 0x7A, 0x63, 0x43, 0x77, 0x6B,
327 0x0E, 0xB3, 0x94, 0x8E, 0xE0, 0xBA, 0xDD, 0x2E, 0x1A, 0xF6, 0x77, 0x82,
328 0xC5, 0xBD, 0x9C, 0xD4, 0xB4, 0x61, 0x49, 0xD7, 0x0A, 0x72, 0x39, 0xB4,
329 0x9A, 0x9B, 0xD0, 0x04, 0x17, 0x00, 0x52, 0xC0, 0xEC, 0x93, 0x78, 0x8C,
330 0x29, 0xC7, 0x89, 0xCC, 0xFA, 0x91, 0xEF, 0xF4, 0xC9, 0x57, 0x40, 0x0A,
331 0xBA, 0x28, 0x0F, 0x7C, 0x70, 0x64, 0x87, 0xB7, 0xEE, 0x07, 0xC6, 0x74,
332 0x84, 0xD9, 0x36, 0x76, 0x8B, 0x70, 0xAF, 0x31, 0x0F, 0xBC, 0x0E, 0x4D,
333 0x14, 0xA5, 0xE7, 0x4F, 0x7F, 0x15, 0xE6, 0xF3, 0xF2, 0x00, 0x59, 0x99,
334 0x38, 0x7B, 0x18, 0x57, 0x17, 0x27, 0xD4, 0x67, 0x12, 0x2F, 0x59, 0x2D,
335 0x35, 0x0D, 0x48, 0xF6, 0x2C, 0x61, 0xE3, 0xD7, 0x4C, 0x5B, 0x6D, 0x2F,
336 0xB0, 0x05, 0xA7, 0x7C, 0xDB, 0xC9, 0x31, 0x71, 0x2E, 0x05, 0x25, 0x92,
337 0x2A, 0x40, 0x23, 0x80, 0x48, 0xC8, 0xFE, 0xA2, 0xF9, 0x5B, 0x37, 0xFB,
338 0x42, 0x68, 0x93, 0xEF, 0x66, 0x5C, 0x26, 0x06, 0xD5, 0x3D, 0x26, 0x1D,
339 0x8B, 0x84, 0xEF, 0xE6, 0xF8, 0x74, 0x2C, 0x2E, 0x40, 0xAD, 0xDB, 0x9B,
340 0x1E, 0x45, 0xFF, 0x08, 0x6B, 0x5F, 0xF5, 0x17, 0x31, 0x0E, 0xEF, 0x21,
341 0xE7, 0x61, 0x0A, 0xFA, 0xA2, 0x69, 0xEF, 0xBC, 0x6F, 0xE9, 0xCF, 0x94,
342 0xE2, 0xA0, 0xC7, 0x8B
343 };
344
345 static unsigned char dh2048_g[] = { 0x05 };
346
347 static DH *get_dh2048(void) {
348 BIGNUM *p, *g;
349
350 p = BN_bin2bn(dh2048_p, sizeof(dh2048_p), NULL);
351 g = BN_bin2bn(dh2048_g, sizeof(dh2048_g), NULL);
352 if (p == NULL ||
353 g == NULL) {
354 return NULL;
355 }
356
357 return get_dh(p, g);
358 }
359
360 /*
361 -----BEGIN DH PARAMETERS-----
362 MIIBiAKCAYEAwdh8bBBn4Py0FzcliIJy+D7MWXtQ10LOCikRHQdtgQB4Rbhwb4hn
363 HyT033tytIVC+gXeHOnfem9y0iOWDrHpD1i/Vpax8iKznOCq/HX11YxUIsM74WG3
364 b0cZxTfyBRAZgDSQ176NMtabJ2NFBPTEpk4NUgy11gkqf8FxQr5ZpK7L3i0ozgYS
365 CUBZwxr7cYep/nQ7VI7GNvtne7Bc1TR/4U/hYeqxmT/xi/RKnW3NFktYriyh15hQ
366 cteIJAyEGQFvFVb9BXW3LqjKqWs2C6HciN1Hz6cZtNua19D0PEWCJOkPfaMB84Oz
367 L2zw5GV1fXuBQWJzAyso3gypD6NScMsZYFtJnfDlLRwWuKcRHczRTOlaVVpTMDUG
368 WHNzWgrKqEbyesNrEH7U75M1tE7lwyqTxMbiI30pEAaXTA8boEO/+QwlgW7IBwju
369 KGGDEDrDLbjO0kUqMcy/y7bWOnH83edHOrlc94HBDSUD+FkEkoiqgJzjMnkmQenB
370 ROb2v1nmFR5TAgEC
371 -----END DH PARAMETERS-----
372 */
373
374 static unsigned char dh3072_p[] = {
375 0xC1, 0xD8, 0x7C, 0x6C, 0x10, 0x67, 0xE0, 0xFC, 0xB4, 0x17, 0x37, 0x25,
376 0x88, 0x82, 0x72, 0xF8, 0x3E, 0xCC, 0x59, 0x7B, 0x50, 0xD7, 0x42, 0xCE,
377 0x0A, 0x29, 0x11, 0x1D, 0x07, 0x6D, 0x81, 0x00, 0x78, 0x45, 0xB8, 0x70,
378 0x6F, 0x88, 0x67, 0x1F, 0x24, 0xF4, 0xDF, 0x7B, 0x72, 0xB4, 0x85, 0x42,
379 0xFA, 0x05, 0xDE, 0x1C, 0xE9, 0xDF, 0x7A, 0x6F, 0x72, 0xD2, 0x23, 0x96,
380 0x0E, 0xB1, 0xE9, 0x0F, 0x58, 0xBF, 0x56, 0x96, 0xB1, 0xF2, 0x22, 0xB3,
381 0x9C, 0xE0, 0xAA, 0xFC, 0x75, 0xF5, 0xD5, 0x8C, 0x54, 0x22, 0xC3, 0x3B,
382 0xE1, 0x61, 0xB7, 0x6F, 0x47, 0x19, 0xC5, 0x37, 0xF2, 0x05, 0x10, 0x19,
383 0x80, 0x34, 0x90, 0xD7, 0xBE, 0x8D, 0x32, 0xD6, 0x9B, 0x27, 0x63, 0x45,
384 0x04, 0xF4, 0xC4, 0xA6, 0x4E, 0x0D, 0x52, 0x0C, 0xB5, 0xD6, 0x09, 0x2A,
385 0x7F, 0xC1, 0x71, 0x42, 0xBE, 0x59, 0xA4, 0xAE, 0xCB, 0xDE, 0x2D, 0x28,
386 0xCE, 0x06, 0x12, 0x09, 0x40, 0x59, 0xC3, 0x1A, 0xFB, 0x71, 0x87, 0xA9,
387 0xFE, 0x74, 0x3B, 0x54, 0x8E, 0xC6, 0x36, 0xFB, 0x67, 0x7B, 0xB0, 0x5C,
388 0xD5, 0x34, 0x7F, 0xE1, 0x4F, 0xE1, 0x61, 0xEA, 0xB1, 0x99, 0x3F, 0xF1,
389 0x8B, 0xF4, 0x4A, 0x9D, 0x6D, 0xCD, 0x16, 0x4B, 0x58, 0xAE, 0x2C, 0xA1,
390 0xD7, 0x98, 0x50, 0x72, 0xD7, 0x88, 0x24, 0x0C, 0x84, 0x19, 0x01, 0x6F,
391 0x15, 0x56, 0xFD, 0x05, 0x75, 0xB7, 0x2E, 0xA8, 0xCA, 0xA9, 0x6B, 0x36,
392 0x0B, 0xA1, 0xDC, 0x88, 0xDD, 0x47, 0xCF, 0xA7, 0x19, 0xB4, 0xDB, 0x9A,
393 0xD7, 0xD0, 0xF4, 0x3C, 0x45, 0x82, 0x24, 0xE9, 0x0F, 0x7D, 0xA3, 0x01,
394 0xF3, 0x83, 0xB3, 0x2F, 0x6C, 0xF0, 0xE4, 0x65, 0x75, 0x7D, 0x7B, 0x81,
395 0x41, 0x62, 0x73, 0x03, 0x2B, 0x28, 0xDE, 0x0C, 0xA9, 0x0F, 0xA3, 0x52,
396 0x70, 0xCB, 0x19, 0x60, 0x5B, 0x49, 0x9D, 0xF0, 0xE5, 0x2D, 0x1C, 0x16,
397 0xB8, 0xA7, 0x11, 0x1D, 0xCC, 0xD1, 0x4C, 0xE9, 0x5A, 0x55, 0x5A, 0x53,
398 0x30, 0x35, 0x06, 0x58, 0x73, 0x73, 0x5A, 0x0A, 0xCA, 0xA8, 0x46, 0xF2,
399 0x7A, 0xC3, 0x6B, 0x10, 0x7E, 0xD4, 0xEF, 0x93, 0x35, 0xB4, 0x4E, 0xE5,
400 0xC3, 0x2A, 0x93, 0xC4, 0xC6, 0xE2, 0x23, 0x7D, 0x29, 0x10, 0x06, 0x97,
401 0x4C, 0x0F, 0x1B, 0xA0, 0x43, 0xBF, 0xF9, 0x0C, 0x25, 0x81, 0x6E, 0xC8,
402 0x07, 0x08, 0xEE, 0x28, 0x61, 0x83, 0x10, 0x3A, 0xC3, 0x2D, 0xB8, 0xCE,
403 0xD2, 0x45, 0x2A, 0x31, 0xCC, 0xBF, 0xCB, 0xB6, 0xD6, 0x3A, 0x71, 0xFC,
404 0xDD, 0xE7, 0x47, 0x3A, 0xB9, 0x5C, 0xF7, 0x81, 0xC1, 0x0D, 0x25, 0x03,
405 0xF8, 0x59, 0x04, 0x92, 0x88, 0xAA, 0x80, 0x9C, 0xE3, 0x32, 0x79, 0x26,
406 0x41, 0xE9, 0xC1, 0x44, 0xE6, 0xF6, 0xBF, 0x59, 0xE6, 0x15, 0x1E, 0x53
407 };
408
409 static unsigned char dh3072_g[] = { 0x02 };
410
411 static DH *get_dh3072(void) {
412 BIGNUM *p, *g;
413
414 p = BN_bin2bn(dh3072_p, sizeof(dh3072_p), NULL);
415 g = BN_bin2bn(dh3072_g, sizeof(dh3072_g), NULL);
416 if (p == NULL ||
417 g == NULL) {
418 return NULL;
419 }
420
421 return get_dh(p, g);
422 };
423
424 /*
425 -----BEGIN DH PARAMETERS-----
426 MIICCAKCAgEAkz1L1of+R99oSCqLFhD+RvzATED0RjaMStoF6G7yEgHophYChHBO
427 /JkbPIgVSrnc3LXE3Wf4LplMARdFMx9HmxiWgn+JZ75XgCAJcP4HmZ/3EPQZx+9R
428 E/NHv5n+icG7LvJ1rMqkaJES/4dAXa1dMF/yyebzxX6SOrEbvuLE6JM6wfD74nQ6
429 1LiM1b70lkteDlKLXzPbqvVGfYMrsQ1QtU/k5PNvrTTOEaSwweAdpOdz4K1OJpRd
430 nc1PIz88saIdZA7LuUfEB2O/Z4P5TipqLCTRNFsv77ZzC6Kleli3Fc13TkkGMnMJ
431 NxHkZR4vWsHew4TOY6OaqKlA3G3UuVa0FhdhaE/NGkBY6noMPWOFa1ZkHQe+4RMK
432 MkLQqKLPS3wky/nQ4wzNNNEkkRI/Dur2cNX6YZ6xiHP85iCxyp80VZHmyjPlPtKw
433 Re5Alc52nvoIt/ugTOoAMurEhAdTEqe8PegZ52MTN1VI4sTnE9pmAQe7EVhsOUnj
434 NaKLCu5b0AmEBXpkQvnDfOkLBdhARTLDIM+jFGe6QVjk2AD1zfVS1cQr7X2aX3RS
435 rxMJRusqNo57H1W/r+C11A7oNurCi4I+YXtOH9l+s84Q5tfqA/IqttnDmCA7mHP0
436 ekRnAw4r0N6F9RlroNW65hcEcIdbvefqSuFAikzwIiAApYh12MFwa6MCAQU=
437 -----END DH PARAMETERS-----
438 */
439
440 static unsigned char dh4096_p[] = {
441 0x93, 0x3D, 0x4B, 0xD6, 0x87, 0xFE, 0x47, 0xDF, 0x68, 0x48, 0x2A, 0x8B,
442 0x16, 0x10, 0xFE, 0x46, 0xFC, 0xC0, 0x4C, 0x40, 0xF4, 0x46, 0x36, 0x8C,
443 0x4A, 0xDA, 0x05, 0xE8, 0x6E, 0xF2, 0x12, 0x01, 0xE8, 0xA6, 0x16, 0x02,
444 0x84, 0x70, 0x4E, 0xFC, 0x99, 0x1B, 0x3C, 0x88, 0x15, 0x4A, 0xB9, 0xDC,
445 0xDC, 0xB5, 0xC4, 0xDD, 0x67, 0xF8, 0x2E, 0x99, 0x4C, 0x01, 0x17, 0x45,
446 0x33, 0x1F, 0x47, 0x9B, 0x18, 0x96, 0x82, 0x7F, 0x89, 0x67, 0xBE, 0x57,
447 0x80, 0x20, 0x09, 0x70, 0xFE, 0x07, 0x99, 0x9F, 0xF7, 0x10, 0xF4, 0x19,
448 0xC7, 0xEF, 0x51, 0x13, 0xF3, 0x47, 0xBF, 0x99, 0xFE, 0x89, 0xC1, 0xBB,
449 0x2E, 0xF2, 0x75, 0xAC, 0xCA, 0xA4, 0x68, 0x91, 0x12, 0xFF, 0x87, 0x40,
450 0x5D, 0xAD, 0x5D, 0x30, 0x5F, 0xF2, 0xC9, 0xE6, 0xF3, 0xC5, 0x7E, 0x92,
451 0x3A, 0xB1, 0x1B, 0xBE, 0xE2, 0xC4, 0xE8, 0x93, 0x3A, 0xC1, 0xF0, 0xFB,
452 0xE2, 0x74, 0x3A, 0xD4, 0xB8, 0x8C, 0xD5, 0xBE, 0xF4, 0x96, 0x4B, 0x5E,
453 0x0E, 0x52, 0x8B, 0x5F, 0x33, 0xDB, 0xAA, 0xF5, 0x46, 0x7D, 0x83, 0x2B,
454 0xB1, 0x0D, 0x50, 0xB5, 0x4F, 0xE4, 0xE4, 0xF3, 0x6F, 0xAD, 0x34, 0xCE,
455 0x11, 0xA4, 0xB0, 0xC1, 0xE0, 0x1D, 0xA4, 0xE7, 0x73, 0xE0, 0xAD, 0x4E,
456 0x26, 0x94, 0x5D, 0x9D, 0xCD, 0x4F, 0x23, 0x3F, 0x3C, 0xB1, 0xA2, 0x1D,
457 0x64, 0x0E, 0xCB, 0xB9, 0x47, 0xC4, 0x07, 0x63, 0xBF, 0x67, 0x83, 0xF9,
458 0x4E, 0x2A, 0x6A, 0x2C, 0x24, 0xD1, 0x34, 0x5B, 0x2F, 0xEF, 0xB6, 0x73,
459 0x0B, 0xA2, 0xA5, 0x7A, 0x58, 0xB7, 0x15, 0xCD, 0x77, 0x4E, 0x49, 0x06,
460 0x32, 0x73, 0x09, 0x37, 0x11, 0xE4, 0x65, 0x1E, 0x2F, 0x5A, 0xC1, 0xDE,
461 0xC3, 0x84, 0xCE, 0x63, 0xA3, 0x9A, 0xA8, 0xA9, 0x40, 0xDC, 0x6D, 0xD4,
462 0xB9, 0x56, 0xB4, 0x16, 0x17, 0x61, 0x68, 0x4F, 0xCD, 0x1A, 0x40, 0x58,
463 0xEA, 0x7A, 0x0C, 0x3D, 0x63, 0x85, 0x6B, 0x56, 0x64, 0x1D, 0x07, 0xBE,
464 0xE1, 0x13, 0x0A, 0x32, 0x42, 0xD0, 0xA8, 0xA2, 0xCF, 0x4B, 0x7C, 0x24,
465 0xCB, 0xF9, 0xD0, 0xE3, 0x0C, 0xCD, 0x34, 0xD1, 0x24, 0x91, 0x12, 0x3F,
466 0x0E, 0xEA, 0xF6, 0x70, 0xD5, 0xFA, 0x61, 0x9E, 0xB1, 0x88, 0x73, 0xFC,
467 0xE6, 0x20, 0xB1, 0xCA, 0x9F, 0x34, 0x55, 0x91, 0xE6, 0xCA, 0x33, 0xE5,
468 0x3E, 0xD2, 0xB0, 0x45, 0xEE, 0x40, 0x95, 0xCE, 0x76, 0x9E, 0xFA, 0x08,
469 0xB7, 0xFB, 0xA0, 0x4C, 0xEA, 0x00, 0x32, 0xEA, 0xC4, 0x84, 0x07, 0x53,
470 0x12, 0xA7, 0xBC, 0x3D, 0xE8, 0x19, 0xE7, 0x63, 0x13, 0x37, 0x55, 0x48,
471 0xE2, 0xC4, 0xE7, 0x13, 0xDA, 0x66, 0x01, 0x07, 0xBB, 0x11, 0x58, 0x6C,
472 0x39, 0x49, 0xE3, 0x35, 0xA2, 0x8B, 0x0A, 0xEE, 0x5B, 0xD0, 0x09, 0x84,
473 0x05, 0x7A, 0x64, 0x42, 0xF9, 0xC3, 0x7C, 0xE9, 0x0B, 0x05, 0xD8, 0x40,
474 0x45, 0x32, 0xC3, 0x20, 0xCF, 0xA3, 0x14, 0x67, 0xBA, 0x41, 0x58, 0xE4,
475 0xD8, 0x00, 0xF5, 0xCD, 0xF5, 0x52, 0xD5, 0xC4, 0x2B, 0xED, 0x7D, 0x9A,
476 0x5F, 0x74, 0x52, 0xAF, 0x13, 0x09, 0x46, 0xEB, 0x2A, 0x36, 0x8E, 0x7B,
477 0x1F, 0x55, 0xBF, 0xAF, 0xE0, 0xB5, 0xD4, 0x0E, 0xE8, 0x36, 0xEA, 0xC2,
478 0x8B, 0x82, 0x3E, 0x61, 0x7B, 0x4E, 0x1F, 0xD9, 0x7E, 0xB3, 0xCE, 0x10,
479 0xE6, 0xD7, 0xEA, 0x03, 0xF2, 0x2A, 0xB6, 0xD9, 0xC3, 0x98, 0x20, 0x3B,
480 0x98, 0x73, 0xF4, 0x7A, 0x44, 0x67, 0x03, 0x0E, 0x2B, 0xD0, 0xDE, 0x85,
481 0xF5, 0x19, 0x6B, 0xA0, 0xD5, 0xBA, 0xE6, 0x17, 0x04, 0x70, 0x87, 0x5B,
482 0xBD, 0xE7, 0xEA, 0x4A, 0xE1, 0x40, 0x8A, 0x4C, 0xF0, 0x22, 0x20, 0x00,
483 0xA5, 0x88, 0x75, 0xD8, 0xC1, 0x70, 0x6B, 0xA3
484 };
485
486 static unsigned char dh4096_g[] = { 0x05 };
487
488 static DH *get_dh4096(void) {
489 BIGNUM *p, *g;
490
491 p = BN_bin2bn(dh4096_p, sizeof(dh4096_p), NULL);
492 g = BN_bin2bn(dh4096_g, sizeof(dh4096_g), NULL);
493 if (p == NULL ||
494 g == NULL) {
495 return NULL;
496 }
497
498 return get_dh(p, g);
499 }
500
501 /* ASN1_BIT_STRING_cmp was renamed in 0.9.5 */
502 #if OPENSSL_VERSION_NUMBER < 0x00905100L
503 # define M_ASN1_BIT_STRING_cmp ASN1_BIT_STRING_cmp
504 #endif
505
506 #if defined(SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB)
507 # define TLS_USE_SESSION_TICKETS
508 #endif
509
510 module tls_module;
511
512 struct tls_next_proto {
513 const char *proto;
514 unsigned char *encoded_proto;
515 unsigned int encoded_protolen;
516 };
517
518 typedef struct tls_pkey_obj {
519 struct tls_pkey_obj *next;
520 pool *pool;
521
522 size_t pkeysz;
523
524 char *rsa_pkey;
525 int rsa_passlen;
526 void *rsa_pkey_ptr;
527
528 char *dsa_pkey;
529 int dsa_passlen;
530 void *dsa_pkey_ptr;
531
532 #ifdef PR_USE_OPENSSL_ECC
533 char *ec_pkey;
534 int ec_passlen;
535 void *ec_pkey_ptr;
536 #endif /* PR_USE_OPENSSL_ECC */
537
538 /* Used for stashing the password for a PKCS12 file, which should
539 * contain a certificate. Any passphrase for the private key for that
540 * certificate should be in one of the above RSA/DSA buffers.
541 */
542 char *pkcs12_passwd;
543 int pkcs12_passlen;
544 void *pkcs12_passwd_ptr;
545
546 unsigned int flags;
547 unsigned int sid;
548 const char *path;
549
550 } tls_pkey_t;
551
552 #define TLS_PKEY_USE_RSA 0x0100
553 #define TLS_PKEY_USE_DSA 0x0200
554 #define TLS_PKEY_USE_EC 0x0400
555
556 static tls_pkey_t *tls_pkey_list = NULL;
557 static unsigned int tls_npkeys = 0;
558
559 #define TLS_DEFAULT_CIPHER_SUITE "DEFAULT:!ADH:!EXPORT:!DES"
560 #define TLS_DEFAULT_NEXT_PROTO "ftp"
561
562 /* Module variables */
563 #if OPENSSL_VERSION_NUMBER > 0x000907000L && \
564 defined(PR_USE_OPENSSL_ENGINE)
565 static const char *tls_crypto_device = NULL;
566 #endif /* PR_USE_OPENSSL_ENGINE */
567 static unsigned char tls_engine = FALSE;
568 static unsigned long tls_flags = 0UL, tls_opts = 0UL;
569 static pool *tls_pool = NULL;
570 static tls_pkey_t *tls_pkey = NULL;
571 static int tls_logfd = -1;
572 #if defined(PR_USE_OPENSSL_OCSP)
573 static int tls_stapling = FALSE;
574 static unsigned long tls_stapling_opts = 0UL;
575 # define TLS_STAPLING_OPT_NO_NONCE 0x0001
576 # define TLS_STAPLING_OPT_NO_VERIFY 0x0002
577 # define TLS_STAPLING_OPT_NO_FAKE_TRY_LATER 0x0004
578 static const char *tls_stapling_responder = NULL;
579
580 #define TLS_DEFAULT_STAPLING_TIMEOUT 10
581 static unsigned int tls_stapling_timeout = TLS_DEFAULT_STAPLING_TIMEOUT;
582 #endif
583
584 static char *tls_passphrase_provider = NULL;
585 #define TLS_PASSPHRASE_TIMEOUT 10
586 #define TLS_PASSPHRASE_FL_RSA_KEY 0x0001
587 #define TLS_PASSPHRASE_FL_DSA_KEY 0x0002
588 #define TLS_PASSPHRASE_FL_PKCS12_PASSWD 0x0004
589 #define TLS_PASSPHRASE_FL_EC_KEY 0x0008
590
591 #define TLS_PROTO_SSL_V3 0x0001
592 #define TLS_PROTO_TLS_V1 0x0002
593 #define TLS_PROTO_TLS_V1_1 0x0004
594 #define TLS_PROTO_TLS_V1_2 0x0008
595 #define TLS_PROTO_TLS_V1_3 0x0010
596
597 #if OPENSSL_VERSION_NUMBER >= 0x10101000L
598 # define TLS_PROTO_DEFAULT (TLS_PROTO_TLS_V1|TLS_PROTO_TLS_V1_1|TLS_PROTO_TLS_V1_2|TLS_PROTO_TLS_V1_3)
599 #elif OPENSSL_VERSION_NUMBER >= 0x10001000L
600 # define TLS_PROTO_DEFAULT (TLS_PROTO_TLS_V1|TLS_PROTO_TLS_V1_1|TLS_PROTO_TLS_V1_2)
601 #else
602 # define TLS_PROTO_DEFAULT (TLS_PROTO_TLS_V1)
603 #endif /* OpenSSL 1.0.1 or later */
604
605 static unsigned int tls_protocol = TLS_PROTO_DEFAULT;
606
607 /* This is used for e.g. "TLSProtocol ALL -SSLv3 ...". */
608 #define TLS_PROTO_ALL (TLS_PROTO_SSL_V3|TLS_PROTO_TLS_V1|TLS_PROTO_TLS_V1_1|TLS_PROTO_TLS_V1_2|TLS_PROTO_TLS_V1_3)
609
610 #ifdef SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS
611 static int tls_ssl_opts = (SSL_OP_ALL|SSL_OP_NO_SSLv2|SSL_OP_SINGLE_DH_USE)^SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS;
612 #else
613 /* OpenSSL-0.9.6 and earlier (yes, it appears people still have these versions
614 * installed) does not define the DONT_INSERT_EMPTY_FRAGMENTS option.
615 */
616 static int tls_ssl_opts = SSL_OP_ALL|SSL_OP_NO_SSLv2|SSL_OP_SINGLE_DH_USE;
617 #endif
618
619 static int tls_required_on_auth = 0;
620 static int tls_required_on_ctrl = 0;
621 static int tls_required_on_data = 0;
622 static unsigned char *tls_authenticated = NULL;
623
624 /* Define the minimum DH group length we allow (unless the AllowWeakDH
625 * TLSOption is used).
626 */
627 #define TLS_DH_MIN_LEN 2048
628
629 /* mod_tls session flags */
630 #define TLS_SESS_ON_CTRL 0x0001
631 #define TLS_SESS_ON_DATA 0x0002
632 #define TLS_SESS_PBSZ_OK 0x0004
633 #define TLS_SESS_TLS_REQUIRED 0x0010
634 #define TLS_SESS_VERIFY_CLIENT_REQUIRED 0x0020
635 #define TLS_SESS_NO_PASSWD_NEEDED 0x0040
636 #define TLS_SESS_NEED_DATA_PROT 0x0100
637 #define TLS_SESS_CTRL_RENEGOTIATING 0x0200
638 #define TLS_SESS_DATA_RENEGOTIATING 0x0400
639 #define TLS_SESS_HAVE_CCC 0x0800
640 #define TLS_SESS_VERIFY_SERVER 0x1000
641 #define TLS_SESS_VERIFY_SERVER_NO_DNS 0x2000
642 #define TLS_SESS_VERIFY_CLIENT_OPTIONAL 0x4000
643
644 /* mod_tls option flags */
645 #define TLS_OPT_VERIFY_CERT_FQDN 0x0002
646 #define TLS_OPT_VERIFY_CERT_IP_ADDR 0x0004
647 #define TLS_OPT_ALLOW_DOT_LOGIN 0x0008
648 #define TLS_OPT_EXPORT_CERT_DATA 0x0010
649 #define TLS_OPT_STD_ENV_VARS 0x0020
650 #define TLS_OPT_ALLOW_PER_USER 0x0040
651 #define TLS_OPT_ENABLE_DIAGS 0x0080
652 #define TLS_OPT_NO_SESSION_REUSE_REQUIRED 0x0100
653 #define TLS_OPT_USE_IMPLICIT_SSL 0x0200
654 #define TLS_OPT_ALLOW_CLIENT_RENEGOTIATIONS 0x0400
655 #define TLS_OPT_VERIFY_CERT_CN 0x0800
656 #define TLS_OPT_NO_AUTO_ECDH 0x1000
657 #define TLS_OPT_ALLOW_WEAK_DH 0x2000
658 #define TLS_OPT_IGNORE_SNI 0x4000
659 #define TLS_OPT_ALLOW_WEAK_SECURITY 0x8000
660
661 /* mod_tls SSCN modes */
662 #define TLS_SSCN_MODE_SERVER 0
663 #define TLS_SSCN_MODE_CLIENT 1
664 static unsigned int tls_sscn_mode = TLS_SSCN_MODE_SERVER;
665
666 /* mod_tls cleanup flags */
667 #define TLS_CLEANUP_FL_SESS_INIT 0x0001
668
669 /* mod_tls OCSP constants */
670 #define TLS_OCSP_RESP_MAX_AGE_SECS 300
671
672 /* X509v3 OCSP "must staple" extensions (RFC 7633) */
673 #define TLS_X509V3_TLS_FEAT_OID_TEXT "1.3.6.1.5.5.7.1.24"
674 #define TLS_X509V3_TLS_FEAT_STATUS_REQUEST { 0x30, 0x03, 0x02, 0x01, 0x05 }
675 #define TLS_X509V3_TLS_FEAT_STATUS_REQUEST_V2 { 0x30, 0x03, 0x02, 0x01, 0x17 }
676
677 static char *tls_cipher_suite = NULL;
678 #if OPENSSL_VERSION_NUMBER >= 0x10101000L && \
679 defined(TLS1_3_VERSION)
680 static char *tlsv13_cipher_suite = NULL;
681 #endif /* TLS1_3_VERSION */
682
683 static char *tls_ca_file = NULL, *tls_ca_path = NULL, *tls_ca_chain = NULL;
684 static char *tls_crl_file = NULL, *tls_crl_path = NULL;
685 static char *tls_ec_cert_file = NULL, *tls_ec_key_file = NULL;
686 static void *tls_ecdh_curve = NULL;
687 static char *tls_dsa_cert_file = NULL, *tls_dsa_key_file = NULL;
688 static char *tls_pkcs12_file = NULL;
689 static char *tls_rsa_cert_file = NULL, *tls_rsa_key_file = NULL;
690 static char *tls_rand_file = NULL;
691 #if !defined(OPENSSL_NO_TLSEXT) && !defined(HAVE_LIBRESSL) && \
692 OPENSSL_VERSION_NUMBER >= 0x10002000L
693 static char *tls_serverinfo_file = NULL;
694 #endif /* OPENSSL_NO_TLSEXT */
695 static int tls_use_next_protocol = TRUE;
696 static int tls_use_server_cipher_preference = TRUE;
697 static int tls_use_session_tickets = FALSE;
698
699 #if defined(PSK_MAX_PSK_LEN)
700 static pr_table_t *tls_psks = NULL;
701 # define TLS_MIN_PSK_LEN 20
702 #endif /* PSK support */
703
704 /* Timeout given for TLS handshakes. The default is 5 minutes. */
705 #define TLS_DEFAULT_HANDSHAKE_TIMEOUT 300
706 static unsigned int tls_handshake_timeout = TLS_DEFAULT_HANDSHAKE_TIMEOUT;
707 static unsigned char tls_handshake_timed_out = FALSE;
708 static int tls_handshake_timer_id = -1;
709
710 /* Note: 9 is the default OpenSSL depth. */
711 #define TLS_DEFAULT_VERIFY_DEPTH 9
712 static int tls_verify_depth = TLS_DEFAULT_VERIFY_DEPTH;
713
714 #if OPENSSL_VERSION_NUMBER > 0x000907000L
715 /* No default renegotiation of control channel on TLS sessions. */
716 static int tls_ctrl_renegotiate_timeout = 0;
717
718 /* No default renegotiation of data channel on TLS sessions. */
719 static off_t tls_data_renegotiate_limit = 0;
720 static off_t tls_data_renegotiate_current = 0;
721
722 /* Timeout given for renegotiations to occur before the TLS session is
723 * shutdown. The default is 30 seconds.
724 */
725 static int tls_renegotiate_timeout = 30;
726
727 /* Is client acceptance of a requested renegotiation required? */
728 static unsigned char tls_renegotiate_required = FALSE;
729 #endif
730
731 #define TLS_NETIO_NOTE "mod_tls.SSL"
732
733 static pr_netio_t *tls_ctrl_netio = NULL;
734 static pr_netio_stream_t *tls_ctrl_rd_nstrm = NULL;
735 static pr_netio_stream_t *tls_ctrl_wr_nstrm = NULL;
736
737 static pr_netio_t *tls_data_netio = NULL;
738 static pr_netio_stream_t *tls_data_rd_nstrm = NULL;
739 static pr_netio_stream_t *tls_data_wr_nstrm = NULL;
740
741 static tls_sess_cache_t *tls_sess_cache = NULL;
742 static tls_ocsp_cache_t *tls_ocsp_cache = NULL;
743
744 #if defined(PR_USE_OPENSSL_SSL_SESSION_TICKET_CALLBACK)
745 /* These are used to ensure that TLSv1.3 session tickets are from the same
746 * FTP session.
747 */
748 static const void *tls_ctrl_ticket_appdata = NULL;
749 static size_t tls_ctrl_ticket_appdatasz = 0, tls_ctrl_ticket_appdata_len = 0;
750 static const void *tls_data_ticket_appdata = NULL;
751 static size_t tls_data_ticket_appdatasz = 0, tls_data_ticket_appdata_len = 0;
752 #endif /* PR_USE_OPENSSL_SSL_SESSION_TICKET_CALLBACK */
753
754 /* OpenSSL variables */
755 static SSL *ctrl_ssl = NULL;
756 static SSL_CTX *ssl_ctx = NULL;
757 static array_header *tls_tmp_dhs = NULL;
758 static RSA *tls_tmp_rsa = NULL;
759
760 static void tls_exit_ev(const void *, void *);
761 static int tls_sess_init(void);
762
763 /* SSL/TLS support functions */
764 static void tls_closelog(void);
765 static void tls_end_sess(SSL *, conn_t *, int);
766 #define TLS_SHUTDOWN_FL_BIDIRECTIONAL 0x0001
767
768 static void tls_fatal_error(long, int);
769 static const char *tls_get_errors(void);
770 static const char *tls_get_errors2(pool *p);
771 static char *tls_get_page(size_t, void **);
772 static size_t tls_get_pagesz(void);
773 static int tls_get_passphrase(server_rec *, const char *, const char *,
774 char *, size_t, int);
775
776 static char *tls_get_subj_name(SSL *);
777
778 /* Table-based session cache "provider" for SNI sessions only (Issue #924). */
779 static pr_table_t *tls_sni_sess_tab = NULL;
780
781 static void tls_lookup_all(server_rec *);
782 static int tls_ctx_set_all(server_rec *, SSL_CTX *);
783 static int tls_ctx_set_ca_certs(SSL_CTX *);
784 static int tls_ctx_set_certs(SSL_CTX *, X509 **, X509 **, X509 **);
785 static int tls_ctx_set_crls(SSL_CTX *);
786 static int tls_ctx_set_renegotiations(SSL_CTX *);
787 static int tls_ctx_set_session_cache(server_rec *, SSL_CTX *);
788 static int tls_ctx_set_session_id_context(server_rec *, SSL_CTX *);
789 static int tls_ctx_set_session_tickets(SSL_CTX *);
790 static int tls_ctx_set_stapling(SSL_CTX *);
791 static int tls_ctx_set_stapling_cache(server_rec *, SSL_CTX *);
792 static int tls_ssl_set_all(server_rec *, SSL *);
793
794 static int tls_openlog(void);
795 static int tls_seed_prng(void);
796 static int tls_sess_init(void);
797 static void tls_setup_environ(pool *p, SSL *ssl);
798 static void tls_setup_notes(pool *p, SSL *ssl);
799 static int tls_verify_cb(int ok, X509_STORE_CTX *ctx);
800 static int tls_verify_crl(int ok, X509_STORE_CTX *ctx);
801 static int tls_verify_ocsp(int ok, X509_STORE_CTX *ctx);
802 static char *tls_x509_name_oneline(const X509_NAME *x509_name);
803
804 static int tls_readmore(int);
805 static int tls_writemore(int);
806
807 /* Session cache API */
808 static tls_sess_cache_t *tls_sess_cache_get_cache(const char *);
809 static long tls_sess_cache_get_cache_mode(void);
810 static int tls_sess_cache_open(char *, long);
811 static int tls_sess_cache_close(void);
812 #if defined(PR_USE_CTRLS)
813 static int tls_sess_cache_clear(void);
814 static int tls_sess_cache_remove(void);
815 static int tls_sess_cache_status(pr_ctrls_t *, int);
816 #endif /* PR_USE_CTRLS */
817 static int tls_sess_cache_add_sess_cb(SSL *, SSL_SESSION *);
818 static SSL_SESSION *tls_sess_cache_get_sess_cb(SSL *, const unsigned char *,
819 int, int *);
820 static void tls_sess_cache_delete_sess_cb(SSL_CTX *, SSL_SESSION *);
821
822 /* OCSP response cache API */
823 static tls_ocsp_cache_t *tls_ocsp_cache_get_cache(const char *);
824 static int tls_ocsp_cache_open(char *);
825 static int tls_ocsp_cache_close(void);
826 #if defined(PR_USE_CTRLS)
827 static int tls_ocsp_cache_clear(void);
828 static int tls_ocsp_cache_remove(void);
829 static int tls_ocsp_cache_status(pr_ctrls_t *, int);
830 #endif /* PR_USE_CTRLS */
831
832 #if defined(TLS_USE_SESSION_TICKETS)
833 /* Default maximum ticket key age: 12 hours */
834 static unsigned int tls_ticket_key_max_age = 43200;
835
836 /* Maximum number of session ticket keys: 25 (1 per hour, plus leeway) */
837 static unsigned int tls_ticket_key_max_count = 25;
838 static unsigned int tls_ticket_key_curr_count = 0;
839
840 struct tls_ticket_key {
841 struct tls_ticket_key *next, *prev;
842
843 /* Memory page pointer and size, for locking. */
844 void *page_ptr;
845 size_t pagesz;
846 int locked;
847 time_t created;
848
849 /* 16 bytes for the key name, per OpenSSL implementation. */
850 unsigned char key_name[16];
851 unsigned char cipher_key[32];
852 unsigned char hmac_key[32];
853 };
854
855 /* In-memory list of session ticket keys, newest key first. Note that the
856 * memory pages used for a ticket key will be mlock(2)'d into memory, where
857 * possible.
858 *
859 * Ticket keys will be generated randomly, based on the timeout. Expired
860 * ticket keys will be destroyed when a new key is generated. Tickets
861 * encrypted with older keys will be renewed using the newest key.
862 */
863 static xaset_t *tls_ticket_keys = NULL;
864 #endif
865
866 #ifdef PR_USE_CTRLS
867 static pool *tls_act_pool = NULL;
868 static ctrls_acttab_t tls_acttab[];
869 #endif /* PR_USE_CTRLS */
870
871 static int tls_ctrl_need_init_handshake = TRUE;
872 static int tls_data_need_init_handshake = TRUE;
873
874 static const char *timing_channel = "timing";
875
876 static int tls_keyfile_check_cb(char *buf, int size, int rwflag,
877 void *user_data) {
878 buf[0] = '\0';
879 return 0;
880 }
881
882 static const char *tls_get_fingerprint(pool *p, X509 *cert) {
883 const EVP_MD *md = EVP_sha1();
884 unsigned char fp[EVP_MAX_MD_SIZE];
885 unsigned int fp_len = 0;
886 char *fp_hex = NULL;
887
888 if (X509_digest(cert, md, fp, &fp_len) != 1) {
889 pr_trace_msg(trace_channel, 1,
890 "error obtaining %s digest of X509 cert: %s", OBJ_nid2sn(EVP_MD_type(md)),
891 tls_get_errors());
892 errno = EINVAL;
893 return NULL;
894 }
895
896 fp_hex = pr_str_bin2hex(p, fp, fp_len, 0);
897
898 pr_trace_msg(trace_channel, 8,
899 "%s fingerprint: %s", OBJ_nid2sn(EVP_MD_type(md)), fp_hex);
900 return fp_hex;
901 }
902
903 static const char *get_pkey_typestr(int pkey_type) {
904 const char *str = "unknown";
905
906 switch (pkey_type) {
907 case EVP_PKEY_RSA:
908 str = "RSA";
909 break;
910
911 case EVP_PKEY_DSA:
912 str = "DSA";
913 break;
914
915 #ifdef PR_USE_OPENSSL_ECC
916 case EVP_PKEY_EC:
917 str = "EC";
918 break;
919 #endif /* PR_USE_OPENSSL_EC */
920 }
921
922 return str;
923 }
924
925 static const char *tls_get_fingerprint_from_file(pool *p, const char *path,
926 int expected_pkey_type, const char **errstr) {
927 FILE *fh;
928 X509 *cert = NULL;
929 const char *fingerprint;
930
931 fh = fopen(path, "rb");
932 if (fh == NULL) {
933 int xerrno = errno;
934
935 *errstr = (const char *) pstrdup(p, strerror(xerrno));
936 errno = xerrno;
937 return NULL;
938 }
939
940 /* As the file may contain sensitive data, we do not want it lingering
941 * around in stdio buffers.
942 */
943 (void) setvbuf(fh, NULL, _IONBF, 0);
944
945 cert = PEM_read_X509(fh, &cert, NULL, NULL);
946 (void) fclose(fh);
947
948 if (cert == NULL) {
949 const char *err_msg;
950
951 err_msg = tls_get_errors2(p);
952 *errstr = err_msg;
953
954 pr_trace_msg(trace_channel, 1, "error obtaining X509 cert from '%s': %s",
955 path, err_msg);
956 errno = ENOENT;
957 return NULL;
958 }
959
960 fingerprint = tls_get_fingerprint(p, cert);
961
962 if (cert != NULL) {
963 time_t now;
964 const ASN1_TIME *cert_end_ts;
965 EVP_PKEY *pkey;
966
967 now = time(NULL);
968 #if OPENSSL_VERSION_NUMBER < 0x10100000L || \
969 defined(HAVE_LIBRESSL)
970 cert_end_ts = X509_get_notAfter(cert);
971 #else
972 cert_end_ts = X509_get0_notAfter(cert);
973 #endif
974 pkey = X509_get_pubkey(cert);
975
976 if (pkey != NULL) {
977 int pkey_type;
978
979 pkey_type = get_pkey_type(pkey);
980 EVP_PKEY_free(pkey);
981
982 if (pkey_type != expected_pkey_type) {
983 pr_log_pri(PR_LOG_NOTICE, MOD_TLS_VERSION
984 ": certificate '%s': expected %s certificate, found %s", path,
985 get_pkey_typestr(expected_pkey_type), get_pkey_typestr(pkey_type));
986 }
987 }
988
989 if (X509_cmp_time(cert_end_ts, &now) < 0) {
990 BIO *bio;
991 char *data = NULL;
992 long datalen = 0;
993
994 bio = BIO_new(BIO_s_mem());
995 ASN1_TIME_print(bio, cert_end_ts);
996 datalen = BIO_get_mem_data(bio, &data);
997 if (data != NULL) {
998 data[datalen] = '\0';
999 *errstr = (const char *) pstrcat(p, "expired on ", data, NULL);
1000
1001 } else {
1002 *errstr = "already expired";
1003 }
1004
1005 BIO_free(bio);
1006
1007 pr_log_pri(PR_LOG_NOTICE, MOD_TLS_VERSION
1008 ": certificate '%s': %s", path, *errstr);
1009 }
1010 }
1011
1012 X509_free(cert);
1013 return fingerprint;
1014 }
1015
1016 #if defined(PR_USE_OPENSSL_OCSP)
1017 static const char *ocsp_get_responder_url(pool *p, X509 *cert) {
1018 STACK_OF(OPENSSL_STRING) *strs;
1019 char *ocsp_url = NULL;
1020
1021 strs = X509_get1_ocsp(cert);
1022 if (strs != NULL) {
1023 # if OPENSSL_VERSION_NUMBER >= 0x10000001L
1024 if (sk_OPENSSL_STRING_num(strs) > 0) {
1025 ocsp_url = pstrdup(p, sk_OPENSSL_STRING_value(strs, 0));
1026 }
1027 # endif /* OpenSSL-1.0.0 and later */
1028
1029 /* Yes, this says "email", but it Does The Right Thing(tm) for our needs. */
1030 X509_email_free(strs);
1031 }
1032
1033 return ocsp_url;
1034 }
1035 #endif /* PR_USE_OPENSSL_OCSP */
1036
1037 static void tls_reset_state(void) {
1038 tls_engine = FALSE;
1039 tls_flags = 0UL;
1040 tls_opts = 0UL;
1041
1042 if (tls_logfd >= 0) {
1043 (void) close(tls_logfd);
1044 tls_logfd = -1;
1045 }
1046
1047 tls_cipher_suite = NULL;
1048 # if OPENSSL_VERSION_NUMBER >= 0x10101000L && \
1049 defined(TLS1_3_VERSION)
1050 tlsv13_cipher_suite = NULL;
1051 # endif /* TLS1_3_VERSION */
1052 tls_crl_file = NULL;
1053 tls_crl_path = NULL;
1054 # if defined(PR_USE_OPENSSL_ENGINE)
1055 tls_crypto_device = NULL;
1056 # endif /* PR_USE_OPENSSL_ENGINE */
1057 tls_dsa_cert_file = NULL;
1058 tls_dsa_key_file = NULL;
1059 tls_ec_cert_file = NULL;
1060 tls_ec_key_file = NULL;
1061 tls_pkcs12_file = NULL;
1062 tls_rsa_cert_file = NULL;
1063 tls_rsa_key_file = NULL;
1064 tls_rand_file = NULL;
1065 #if defined(PSK_MAX_PSK_LEN)
1066 tls_psks = NULL;
1067 #endif /* PSK_MAX_PSK_LEN */
1068
1069 #if defined(PR_USE_OPENSSL_OCSP)
1070 tls_stapling = FALSE;
1071 tls_stapling_opts = 0UL;
1072 tls_stapling_responder = NULL;
1073 tls_stapling_timeout = TLS_DEFAULT_STAPLING_TIMEOUT;
1074 #endif /* PR_USE_OPENSSL_OCSP */
1075
1076 tls_handshake_timeout = TLS_DEFAULT_HANDSHAKE_TIMEOUT;
1077 tls_handshake_timed_out = FALSE;
1078 tls_handshake_timer_id = -1;
1079
1080 tls_verify_depth = TLS_DEFAULT_VERIFY_DEPTH;
1081
1082 /* Note that we do NOT want to set the netio and nstrm pointers, ctrl
1083 * channel, to here. Why not? We reset this state when a HOST command
1084 * occurs -- but that does NOT cause the NetIO open() to be called again.
1085 * And only the NetIO open callback sets our netio/nstrm pointers; so we
1086 * leave those as they are (Bug#4370).
1087 */
1088
1089 tls_data_netio = NULL;
1090 tls_data_rd_nstrm = NULL;
1091 tls_data_wr_nstrm = NULL;
1092
1093 tls_tmp_dhs = NULL;
1094 tls_tmp_rsa = NULL;
1095
1096 tls_ctrl_need_init_handshake = TRUE;
1097 tls_data_need_init_handshake = TRUE;
1098
1099 tls_required_on_auth = 0;
1100 tls_required_on_ctrl = 0;
1101 tls_required_on_data = 0;
1102
1103 tls_data_renegotiate_current = 0;
1104 }
1105
1106 static void tls_info_cb(const SSL *ssl, int where, int ret) {
1107 const char *str = "(unknown)";
1108 int w;
1109
1110 pr_signals_handle();
1111
1112 w = where & ~SSL_ST_MASK;
1113
1114 if (w & SSL_ST_CONNECT) {
1115 str = "connecting";
1116
1117 } else if (w & SSL_ST_ACCEPT) {
1118 str = "accepting";
1119
1120 } else {
1121 int ssl_state;
1122
1123 ssl_state = SSL_get_state(ssl);
1124 switch (ssl_state) {
1125 #ifdef SSL_ST_BEFORE
1126 case SSL_ST_BEFORE:
1127 str = "before";
1128 break;
1129 #endif
1130
1131 #if OPENSSL_VERSION_NUMBER >= 0x10100000L && \
1132 !defined(HAVE_LIBRESSL)
1133 case TLS_ST_OK:
1134 #else
1135 case SSL_ST_OK:
1136 #endif /* OpenSSL-1.1.x and later */
1137 str = "ok";
1138 break;
1139
1140 #ifdef SSL_ST_RENEGOTIATE
1141 case SSL_ST_RENEGOTIATE:
1142 str = "renegotiating";
1143 break;
1144 #endif
1145
1146 default:
1147 break;
1148 }
1149 }
1150
1151 if (where & SSL_CB_ACCEPT_LOOP) {
1152 int ssl_state;
1153
1154 ssl_state = SSL_get_state(ssl);
1155
1156 #if OPENSSL_VERSION_NUMBER >= 0x10100000L && \
1157 !defined(HAVE_LIBRESSL)
1158 if (ssl_state == TLS_ST_SR_CLNT_HELLO) {
1159 #else
1160 if (ssl_state == SSL3_ST_SR_CLNT_HELLO_A ||
1161 ssl_state == SSL23_ST_SR_CLNT_HELLO_A) {
1162 #endif /* OpenSSL-1.1.x and later */
1163
1164 if (tls_opts & TLS_OPT_ENABLE_DIAGS) {
1165 tls_log("[info] %s: %s", str, SSL_state_string_long(ssl));
1166 }
1167
1168 /* If we have already completed our initial handshake, then this might
1169 * a session renegotiation.
1170 */
1171 if ((ssl == ctrl_ssl && !tls_ctrl_need_init_handshake) ||
1172 (ssl != ctrl_ssl && !tls_data_need_init_handshake)) {
1173
1174 /* Yes, this is indeed a session renegotiation. If it's a
1175 * renegotiation that we requested, allow it. If it is from a
1176 * data connection, allow it. Otherwise, it's a client-initiated
1177 * renegotiation, and we probably don't want to allow it.
1178 */
1179
1180 if (ssl == ctrl_ssl &&
1181 !(tls_flags & TLS_SESS_CTRL_RENEGOTIATING) &&
1182 !(tls_flags & TLS_SESS_DATA_RENEGOTIATING)) {
1183
1184 if (!(tls_opts & TLS_OPT_ALLOW_CLIENT_RENEGOTIATIONS)) {
1185 tls_log("warning: client-initiated session renegotiation "
1186 "detected, aborting connection");
1187 pr_log_pri(PR_LOG_NOTICE, MOD_TLS_VERSION
1188 ": client-initiated session renegotiation detected, "
1189 "aborting connection");
1190
1191 tls_end_sess(ctrl_ssl, session.c, 0);
1192 pr_table_remove(tls_ctrl_rd_nstrm->notes, TLS_NETIO_NOTE, NULL);
1193 pr_table_remove(tls_ctrl_wr_nstrm->notes, TLS_NETIO_NOTE, NULL);
1194 ctrl_ssl = NULL;
1195
1196 pr_session_disconnect(&tls_module, PR_SESS_DISCONNECT_CONFIG_ACL,
1197 "TLSOption AllowClientRenegotiations");
1198 }
1199 }
1200 }
1201
1202 #if OPENSSL_VERSION_NUMBER >= 0x009080cfL && \
1203 OPENSSL_VERSION_NUMBER < 0x10100000L
1204 } else if (ssl_state & SSL_ST_RENEGOTIATE) {
1205 if (tls_opts & TLS_OPT_ENABLE_DIAGS) {
1206 tls_log("[info] %s: %s", str, SSL_state_string_long(ssl));
1207 }
1208
1209 if ((ssl == ctrl_ssl && !tls_ctrl_need_init_handshake) ||
1210 (ssl != ctrl_ssl && !tls_data_need_init_handshake)) {
1211
1212 if (ssl == ctrl_ssl &&
1213 !(tls_flags & TLS_SESS_CTRL_RENEGOTIATING) &&
1214 !(tls_flags & TLS_SESS_DATA_RENEGOTIATING)) {
1215
1216 /* In OpenSSL-0.9.8l and later, SSL session renegotiations are
1217 * automatically disabled. Thus if the admin has not explicitly
1218 * configured support for client-initiated renegotiations via the
1219 * AllowClientRenegotiations TLSOption, then we need to disconnect
1220 * the client here. Otherwise, the client would hang (up to the
1221 * TLSTimeoutHandshake limit). Since we know, right now, that the
1222 * handshake won't succeed, just drop the connection.
1223 */
1224
1225 if (!(tls_opts & TLS_OPT_ALLOW_CLIENT_RENEGOTIATIONS)) {
1226 tls_log("warning: client-initiated session renegotiation detected, "
1227 "aborting connection");
1228 pr_log_pri(PR_LOG_NOTICE, MOD_TLS_VERSION
1229 ": client-initiated session renegotiation detected, "
1230 "aborting connection");
1231
1232 tls_end_sess(ctrl_ssl, session.c, 0);
1233 pr_table_remove(tls_ctrl_rd_nstrm->notes, TLS_NETIO_NOTE, NULL);
1234 pr_table_remove(tls_ctrl_wr_nstrm->notes, TLS_NETIO_NOTE, NULL);
1235 ctrl_ssl = NULL;
1236
1237 pr_session_disconnect(&tls_module, PR_SESS_DISCONNECT_CONFIG_ACL,
1238 "TLSOption AllowClientRenegotiations");
1239 }
1240 }
1241 }
1242 #endif
1243 }
1244
1245 if (tls_opts & TLS_OPT_ENABLE_DIAGS) {
1246 tls_log("[info] %s: %s", str, SSL_state_string_long(ssl));
1247 }
1248
1249 } else if (where & SSL_CB_HANDSHAKE_START) {
1250 if (tls_opts & TLS_OPT_ENABLE_DIAGS) {
1251 tls_log("[info] %s: %s (HANDSHAKE_START)", str,
1252 SSL_state_string_long(ssl));
1253 }
1254
1255 } else if (where & SSL_CB_HANDSHAKE_DONE) {
1256 if (tls_opts & TLS_OPT_ENABLE_DIAGS) {
1257 tls_log("[info] %s: %s (HANDSHAKE_DONE)", str,
1258 SSL_state_string_long(ssl));
1259 }
1260
1261 /* ctrl_ssl is NULL if this is our initial ctrl SSL, and the handshake has
1262 * not be completed yet.
1263 */
1264 if (ctrl_ssl == NULL) {
1265 if (tls_ctrl_need_init_handshake == FALSE) {
1266 int reused;
1267
1268 /* If this is an accepted renegotiation, log the possibly-changed
1269 * ciphersuite et al.
1270 */
1271
1272 reused = SSL_session_reused((SSL *) ssl);
1273 tls_log("%s renegotiation accepted, using cipher %s (%d bits%s)",
1274 SSL_get_version(ssl), SSL_get_cipher_name(ssl),
1275 SSL_get_cipher_bits(ssl, NULL),
1276 reused > 0 ? ", resumed session" : "");
1277 }
1278
1279 tls_ctrl_need_init_handshake = FALSE;
1280
1281 } else {
1282 if (tls_data_need_init_handshake == FALSE) {
1283 /* If this is an accepted renegotiation, log the possibly-changed
1284 * ciphersuite et al.
1285 */
1286 tls_log("%s renegotiation accepted, using cipher %s (%d bits)",
1287 SSL_get_version(ssl), SSL_get_cipher_name(ssl),
1288 SSL_get_cipher_bits(ssl, NULL));
1289 }
1290
1291 tls_data_need_init_handshake = FALSE;
1292 }
1293
1294 /* Clear the flags set for server-requested renegotiations. */
1295 if (tls_flags & TLS_SESS_CTRL_RENEGOTIATING) {
1296 tls_flags &= ~TLS_SESS_CTRL_RENEGOTIATING;
1297 }
1298
1299 if (tls_flags & ~TLS_SESS_DATA_RENEGOTIATING) {
1300 tls_flags &= ~TLS_SESS_DATA_RENEGOTIATING;
1301 }
1302
1303 } else if (where & SSL_CB_LOOP) {
1304 if (tls_opts & TLS_OPT_ENABLE_DIAGS) {
1305 tls_log("[info] %s: %s", str, SSL_state_string_long(ssl));
1306 }
1307
1308 } else if (where & SSL_CB_ALERT) {
1309 if (tls_opts & TLS_OPT_ENABLE_DIAGS) {
1310 str = (where & SSL_CB_READ) ? "reading" : "writing";
1311 tls_log("[info] %s: SSL/TLS alert %s: %s", str,
1312 SSL_alert_type_string_long(ret), SSL_alert_desc_string_long(ret));
1313 }
1314
1315 } else if (where & SSL_CB_EXIT) {
1316 if (tls_opts & TLS_OPT_ENABLE_DIAGS) {
1317 if (ret == 0) {
1318 tls_log("[info] %s: failed in %s: %s", str,
1319 SSL_state_string_long(ssl), tls_get_errors());
1320
1321 } else if (ret < 0 &&
1322 errno != 0 &&
1323 errno != EAGAIN) {
1324 /* Ignore EAGAIN errors */
1325 tls_log("[info] %s: error in %s (errno %d: %s)",
1326 str, SSL_state_string_long(ssl), errno, strerror(errno));
1327 }
1328 }
1329 }
1330 }
1331
1332 #if OPENSSL_VERSION_NUMBER > 0x000907000L
1333 /* Tables needed for describing bits of the ClientHello. */
1334
1335 struct tls_label {
1336 int labelno;
1337 const char *label_name;
1338 };
1339
1340 /* SSL record types */
1341 static struct tls_label tls_record_type_labels[] = {
1342 { 20, "ChangeCipherSpec" },
1343 { 21, "Alert" },
1344 { 22, "Handshake" },
1345 { 23, "ApplicationData" },
1346 { 0, NULL }
1347 };
1348
1349 /* SSL versions */
1350 static struct tls_label tls_version_labels[] = {
1351 { 0x0002, "SSL 2.0" },
1352 { 0x0300, "SSL 3.0" },
1353 { 0x0301, "TLS 1.0" },
1354 { 0x0302, "TLS 1.1" },
1355 { 0x0303, "TLS 1.2" },
1356 { 0x0304, "TLS 1.3" },
1357
1358 { 0, NULL }
1359 };
1360
1361 /* Cipher suites. These values come from:
1362 * http://www.iana.org/assignments/tls-parameters/tls-parameters.xhtml#tls-parameters-4
1363 */
1364 static struct tls_label tls_ciphersuite_labels[] = {
1365 { 0x0000, "SSL_NULL_WITH_NULL_NULL" },
1366 { 0x0001, "SSL_RSA_WITH_NULL_MD5" },
1367 { 0x0002, "SSL_RSA_WITH_NULL_SHA" },
1368 { 0x0003, "SSL_RSA_EXPORT_WITH_RC4_40_MD5" },
1369 { 0x0004, "SSL_RSA_WITH_RC4_128_MD5" },
1370 { 0x0005, "SSL_RSA_WITH_RC4_128_SHA" },
1371 { 0x0006, "SSL_RSA_EXPORT_WITH_RC2_CBC_40_MD5" },
1372 { 0x0007, "SSL_RSA_WITH_IDEA_CBC_SHA" },
1373 { 0x0008, "SSL_RSA_EXPORT_WITH_DES40_CBC_SHA" },
1374 { 0x0009, "SSL_RSA_WITH_DES_CBC_SHA" },
1375 { 0x000A, "SSL_RSA_WITH_3DES_EDE_CBC_SHA" },
1376 { 0x000B, "SSL_DH_DSS_EXPORT_WITH_DES40_CBC_SHA" },
1377 { 0x000C, "SSL_DH_DSS_WITH_DES_CBC_SHA" },
1378 { 0x000D, "SSL_DH_DSS_WITH_3DES_EDE_CBC_SHA" },
1379 { 0x000E, "SSL_DH_RSA_EXPORT_WITH_DES40_CBC_SHA" },
1380 { 0x000F, "SSL_DH_RSA_WITH_DES_CBC_SHA" },
1381 { 0x0010, "SSL_DH_RSA_WITH_3DES_EDE_CBC_SHA" },
1382 { 0x0011, "SSL_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA" },
1383 { 0x0012, "SSL_DHE_DSS_WITH_DES_CBC_SHA" },
1384 { 0x0013, "SSL_DHE_DSS_WITH_3DES_EDE_CBC_SHA" },
1385 { 0x0014, "SSL_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA" },
1386 { 0x0015, "SSL_DHE_RSA_WITH_DES_CBC_SHA" },
1387 { 0x0016, "SSL_DHE_RSA_WITH_3DES_EDE_CBC_SHA" },
1388 { 0x0017, "SSL_DH_anon_EXPORT_WITH_RC4_40_MD5" },
1389 { 0x0018, "SSL_DH_anon_WITH_RC4_128_MD5" },
1390 { 0x0019, "SSL_DH_anon_EXPORT_WITH_DES40_CBC_SHA" },
1391 { 0x001A, "SSL_DH_anon_WITH_DES_CBC_SHA" },
1392 { 0x001B, "SSL_DH_anon_WITH_3DES_EDE_CBC_SHA" },
1393 { 0x001D, "SSL_FORTEZZA_KEA_WITH_FORTEZZA_CBC_SHA" },
1394 { 0x001E, "SSL_FORTEZZA_KEA_WITH_RC4_128_SHA" },
1395 { 0x001F, "TLS_KRB5_WITH_3DES_EDE_CBC_SHA" },
1396 { 0x0020, "TLS_KRB5_WITH_RC4_128_SHA" },
1397 { 0x0021, "TLS_KRB5_WITH_IDEA_CBC_SHA" },
1398 { 0x0022, "TLS_KRB5_WITH_DES_CBC_MD5" },
1399 { 0x0023, "TLS_KRB5_WITH_3DES_EDE_CBC_MD5" },
1400 { 0x0024, "TLS_KRB5_WITH_RC4_128_MD5" },
1401 { 0x0025, "TLS_KRB5_WITH_IDEA_CBC_MD5" },
1402 { 0x0026, "TLS_KRB5_EXPORT_WITH_DES_CBC_40_SHA" },
1403 { 0x0027, "TLS_KRB5_EXPORT_WITH_RC2_CBC_40_SHA" },
1404 { 0x0028, "TLS_KRB5_EXPORT_WITH_RC4_40_SHA" },
1405 { 0x0029, "TLS_KRB5_EXPORT_WITH_DES_CBC_40_MD5" },
1406 { 0x002A, "TLS_KRB5_EXPORT_WITH_RC2_CBC_40_MD5" },
1407 { 0x002B, "TLS_KRB5_EXPORT_WITH_RC4_40_MD5" },
1408 { 0x002F, "TLS_RSA_WITH_AES_128_CBC_SHA" },
1409 { 0x0030, "TLS_DH_DSS_WITH_AES_128_CBC_SHA" },
1410 { 0x0031, "TLS_DH_RSA_WITH_AES_128_CBC_SHA" },
1411 { 0x0032, "TLS_DHE_DSS_WITH_AES_128_CBC_SHA" },
1412 { 0x0033, "TLS_DHE_RSA_WITH_AES_128_CBC_SHA" },
1413 { 0x0034, "TLS_DH_anon_WITH_AES_128_CBC_SHA" },
1414 { 0x0035, "TLS_RSA_WITH_AES_256_CBC_SHA" },
1415 { 0x0036, "TLS_DH_DSS_WITH_AES_256_CBC_SHA" },
1416 { 0x0037, "TLS_DH_RSA_WITH_AES_256_CBC_SHA" },
1417 { 0x0038, "TLS_DHE_DSS_WITH_AES_256_CBC_SHA" },
1418 { 0x0039, "TLS_DHE_RSA_WITH_AES_256_CBC_SHA" },
1419 { 0x003A, "TLS_DH_anon_WITH_AES_256_CBC_SHA" },
1420 { 0x003B, "TLS_RSA_WITH_NULL_SHA256" },
1421 { 0x003C, "TLS_RSA_WITH_AES_128_CBC_SHA256" },
1422 { 0x003D, "TLS_RSA_WITH_AES_256_CBC_SHA256" },
1423 { 0x003E, "TLS_DH_DSS_WITH_AES_128_CBC_SHA256" },
1424 { 0x003F, "TLS_DH_RSA_WITH_AES_128_CBC_SHA256" },
1425 { 0x0040, "TLS_DHE_DSS_WITH_AES_128_CBC_SHA256" },
1426 { 0x0041, "TLS_RSA_WITH_CAMELLIA_128_CBC_SHA" },
1427 { 0x0042, "TLS_DH_DSS_WITH_CAMELLIA_128_CBC_SHA" },
1428 { 0x0043, "TLS_DH_RSA_WITH_CAMELLIA_128_CBC_SHA" },
1429 { 0x0044, "TLS_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA" },
1430 { 0x0045, "TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA" },
1431 { 0x0046, "TLS_DH_anon_WITH_CAMELLIA_128_CBC_SHA" },
1432 { 0x0067, "TLS_DHE_RSA_WITH_AES_128_CBC_SHA256" },
1433 { 0x0068, "TLS_DH_DSS_WITH_AES_256_CBC_SHA256" },
1434 { 0x0069, "TLS_DH_RSA_WITH_AES_256_CBC_SHA256" },
1435 { 0x006A, "TLS_DHE_DSS_WITH_AES_256_CBC_SHA256" },
1436 { 0x006B, "TLS_DHE_RSA_WITH_AES_256_CBC_SHA256" },
1437 { 0x006C, "TLS_DH_anon_WITH_AES_128_CBC_SHA256" },
1438 { 0x006D, "TLS_DH_anon_WITH_AES_256_CBC_SHA256" },
1439 { 0x0084, "TLS_RSA_WITH_CAMELLIA_256_CBC_SHA" },
1440 { 0x0085, "TLS_DH_DSS_WITH_CAMELLIA_256_CBC_SHA" },
1441 { 0x0086, "TLS_DH_RSA_WITH_CAMELLIA_256_CBC_SHA" },
1442 { 0x0087, "TLS_DHE_DSS_WITH_CAMELLIA_256_CBC_SHA" },
1443 { 0x0088, "TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA" },
1444 { 0x0089, "TLS_DH_anon_WITH_CAMELLIA_256_CBC_SHA" },
1445 { 0x008A, "TLS_PSK_WITH_RC4_128_SHA" },
1446 { 0x008B, "TLS_PSK_WITH_3DES_EDE_CBC_SHA" },
1447 { 0x008C, "TLS_PSK_WITH_AES_128_CBC_SHA" },
1448 { 0x008D, "TLS_PSK_WITH_AES_256_CBC_SHA" },
1449 { 0x008E, "TLS_DHE_PSK_WITH_RC4_128_SHA" },
1450 { 0x008F, "TLS_DHE_PSK_WITH_3DES_EDE_CBC_SHA" },
1451 { 0x0090, "TLS_DHE_PSK_WITH_AES_128_CBC_SHA" },
1452 { 0x0091, "TLS_DHE_PSK_WITH_AES_256_CBC_SHA" },
1453 { 0x0092, "TLS_RSA_PSK_WITH_RC4_128_SHA" },
1454 { 0x0093, "TLS_RSA_PSK_WITH_3DES_EDE_CBC_SHA" },
1455 { 0x0094, "TLS_RSA_PSK_WITH_AES_128_CBC_SHA" },
1456 { 0x0095, "TLS_RSA_PSK_WITH_AES_256_CBC_SHA" },
1457 { 0x0096, "TLS_RSA_WITH_SEED_CBC_SHA" },
1458 { 0x0097, "TLS_DH_DSS_WITH_SEED_CBC_SHA" },
1459 { 0x0098, "TLS_DH_RSA_WITH_SEED_CBC_SHA" },
1460 { 0x0099, "TLS_DHE_DSS_WITH_SEED_CBC_SHA" },
1461 { 0x009A, "TLS_DHE_RSA_WITH_SEED_CBC_SHA" },
1462 { 0x009B, "TLS_DH_anon_WITH_SEED_CBC_SHA" },
1463 { 0x009C, "TLS_RSA_WITH_AES_128_GCM_SHA256" },
1464 { 0x009D, "TLS_RSA_WITH_AES_256_GCM_SHA384" },
1465 { 0x009E, "TLS_DHE_RSA_WITH_AES_128_GCM_SHA256" },
1466 { 0x009F, "TLS_DHE_RSA_WITH_AES_256_GCM_SHA384" },
1467 { 0x00A0, "TLS_DH_RSA_WITH_AES_128_GCM_SHA256" },
1468 { 0x00A1, "TLS_DH_RSA_WITH_AES_256_GCM_SHA384" },
1469 { 0x00A2, "TLS_DHE_DSS_WITH_AES_128_GCM_SHA256" },
1470 { 0x00A3, "TLS_DHE_DSS_WITH_AES_256_GCM_SHA384" },
1471 { 0x00A4, "TLS_DH_DSS_WITH_AES_128_GCM_SHA256" },
1472 { 0x00A5, "TLS_DH_DSS_WITH_AES_256_GCM_SHA384" },
1473 { 0x00A6, "TLS_DH_anon_WITH_AES_128_GCM_SHA256" },
1474 { 0x00A7, "TLS_DH_anon_WITH_AES_256_GCM_SHA384" },
1475 { 0x00A8, "TLS_PSK_WITH_AES_128_GCM_SHA256" },
1476 { 0x00A9, "TLS_PSK_WITH_AES_256_GCM_SHA384" },
1477 { 0x00AA, "TLS_DHE_PSK_WITH_AES_128_GCM_SHA256" },
1478 { 0x00AB, "TLS_DHE_PSK_WITH_AES_256_GCM_SHA384" },
1479 { 0x00AC, "TLS_RSA_PSK_WITH_AES_128_GCM_SHA256" },
1480 { 0x00AD, "TLS_RSA_PSK_WITH_AES_256_GCM_SHA384" },
1481 { 0x00AE, "TLS_PSK_WITH_AES_128_CBC_SHA256" },
1482 { 0x00AF, "TLS_PSK_WITH_AES_256_CBC_SHA384" },
1483 { 0x00B0, "TLS_PSK_WITH_NULL_SHA256" },
1484 { 0x00B1, "TLS_PSK_WITH_NULL_SHA384" },
1485 { 0x00B2, "TLS_DHE_PSK_WITH_AES_128_CBC_SHA256" },
1486 { 0x00B3, "TLS_DHE_PSK_WITH_AES_256_CBC_SHA384"},
1487 { 0x00B4, "TLS_DHE_PSK_WITH_NULL_SHA256" },
1488 { 0x00B5, "TLS_DHE_PSK_WITH_NULL_SHA384" },
1489 { 0x00B6, "TLS_RSA_PSK_WITH_AES_128_CBC_SHA256" },
1490 { 0x00B7, "TLS_RSA_PSK_WITH_AES_256_CBC_SHA384" },
1491 { 0x00B8, "TLS_RSA_PSK_WITH_NULL_SHA256" },
1492 { 0x00B9, "TLS_RSA_PSK_WITH_NULL_SHA384" },
1493 { 0x00BA, "TLS_RSA_WITH_CAMELLIA_128_CBC_SHA256" },
1494 { 0x00BB, "TLS_DH_DSS_WITH_CAMELLIA_128_CBC_SHA256" },
1495 { 0x00BC, "TLS_DH_RSA_WITH_CAMELLIA_128_CBC_SHA256" },
1496 { 0x00BD, "TLS_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA256" },
1497 { 0x00BE, "TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA256" },
1498 { 0x00BF, "TLS_DH_anon_WITH_CAMELLIA_128_CBC_SHA256" },
1499 { 0x00C0, "TLS_RSA_WITH_CAMELLIA_256_CBC_SHA256" },
1500 { 0x00C1, "TLS_DH_DSS_WITH_CAMELLIA_256_CBC_SHA256" },
1501 { 0x00C2, "TLS_DH_RSA_WITH_CAMELLIA_256_CBC_SHA256" },
1502 { 0x00C3, "TLS_DHE_DSS_WITH_CAMELLIA_256_CBC_SHA256" },
1503 { 0x00C4, "TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA256" },
1504 { 0x00C5, "TLS_DH_anon_WITH_CAMELLIA_256_CBC_SHA256" },
1505 { 0x00FF, "TLS_EMPTY_RENEGOTIATION_INFO_SCSV" },
1506 { 0x1301, "TLS_AES_128_GCM_SHA256" },
1507 { 0x1302, "TLS_AES_256_GCM_SHA384" },
1508 { 0x1303, "TLS_CHACHA20_POLY1305_SHA256" },
1509 { 0xC001, "TLS_ECDH_ECDSA_WITH_NULL_SHA" },
1510 { 0xC002, "TLS_ECDH_ECDSA_WITH_RC4_128_SHA" },
1511 { 0xC003, "TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA" },
1512 { 0xC004, "TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA" },
1513 { 0xC005, "TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA" },
1514 { 0xC006, "TLS_ECDHE_ECDSA_WITH_NULL_SHA" },
1515 { 0xC007, "TLS_ECDHE_ECDSA_WITH_RC4_128_SHA" },
1516 { 0xC008, "TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA" },
1517 { 0xC009, "TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA" },
1518 { 0xC00A, "TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA" },
1519 { 0xC00B, "TLS_ECDH_RSA_WITH_NULL_SHA" },
1520 { 0xC00C, "TLS_ECDH_RSA_WITH_RC4_128_SHA" },
1521 { 0xC00D, "TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA" },
1522 { 0xC00E, "TLS_ECDH_RSA_WITH_AES_128_CBC_SHA" },
1523 { 0xC00F, "TLS_ECDH_RSA_WITH_AES_256_CBC_SHA" },
1524 { 0xC010, "TLS_ECDHE_RSA_WITH_NULL_SHA" },
1525 { 0xC011, "TLS_ECDHE_RSA_WITH_RC4_128_SHA" },
1526 { 0xC012, "TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA" },
1527 { 0xC013, "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA" },
1528 { 0xC014, "TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA" },
1529 { 0xC015, "TLS_ECDH_anon_WITH_NULL_SHA" },
1530 { 0xC016, "TLS_ECDH_anon_WITH_RC4_128_SHA" },
1531 { 0xC017, "TLS_ECDH_anon_WITH_3DES_EDE_CBC_SHA" },
1532 { 0xC018, "TLS_ECDH_anon_WITH_AES_128_CBC_SHA" },
1533 { 0xC019, "TLS_ECDH_anon_WITH_AES_256_CBC_SHA" },
1534 { 0xC01A, "TLS_SRP_SHA_WITH_3DES_EDE_CBC_SHA" },
1535 { 0xC01B, "TLS_SRP_SHA_RSA_WITH_3DES_EDE_CBC_SHA" },
1536 { 0xC01C, "TLS_SRP_SHA_DSS_WITH_3DES_EDE_CBC_SHA" },
1537 { 0xC01D, "TLS_SRP_SHA_WITH_AES_128_CBC_SHA" },
1538 { 0xC01E, "TLS_SRP_SHA_RSA_WITH_AES_128_CBC_SHA" },
1539 { 0xC01F, "TLS_SRP_SHA_DSS_WITH_AES_128_CBC_SHA" },
1540 { 0xC020, "TLS_SRP_SHA_WITH_AES_256_CBC_SHA" },
1541 { 0xC021, "TLS_SRP_SHA_RSA_WITH_AES_256_CBC_SHA" },
1542 { 0xC022, "TLS_SRP_SHA_DSS_WITH_AES_256_CBC_SHA" },
1543 { 0xC023, "TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256" },
1544 { 0xC024, "TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384" },
1545 { 0xC025, "TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256" },
1546 { 0xC026, "TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384" },
1547 { 0xC027, "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256" },
1548 { 0xC028, "TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384" },
1549 { 0xC029, "TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256" },
1550 { 0xC02A, "TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384" },
1551 { 0xC02B, "TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256" },
1552 { 0xC02C, "TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384" },
1553 { 0xC02D, "TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256" },
1554 { 0xC02E, "TLS_ECDH_ECDSA_WITH_AES_256_GCM_SHA384" },
1555 { 0xC02F, "TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256" },
1556 { 0xC030, "TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384" },
1557 { 0xC031, "TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256" },
1558 { 0xC032, "TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384" },
1559 { 0xC072, "TLS_ECDHE_ECDSA_WITH_CAMELLIA_128_CBC_SHA256" },
1560 { 0xC073, "TLS_ECDHE_ECDSA_WITH_CAMELLIA_256_CBC_SHA384" },
1561 { 0xC076, "TLS_ECDHE_RSA_WITH_CAMELLIA_128_CBC_SHA256" },
1562 { 0xC077, "TLS_ECDHE_RSA_WITH_CAMELLIA_256_CBC_SHA384" },
1563 { 0xC07A, "TLS_RSA_WITH_CAMELLIA_128_GCM_SHA256" },
1564 { 0xC07B, "TLS_RSA_WITH_CAMELLIA_256_GCM_SHA384" },
1565 { 0xC07C, "TLS_DHE_RSA_WITH_CAMELLIA_128_GCM_SHA256" },
1566 { 0xC07D, "TLS_DHE_RSA_WITH_CAMELLIA_256_GCM_SHA384" },
1567 { 0xC07E, "TLS_DH_RSA_WITH_CAMELLIA_128_GCM_SHA256" },
1568 { 0xC07F, "TLS_DH_RSA_WITH_CAMELLIA_256_GCM_SHA384" },
1569 { 0xC086, "TLS_ECDHE_ECDSA_WITH_CAMELLIA_128_GCM_SHA256" },
1570 { 0xC087, "TLS_ECDHE_ECDSA_WITH_CAMELLIA_256_GCM_SHA384" },
1571 { 0xC08A, "TLS_ECDHE_RSA_WITH_CAMELLIA_128_GCM_SHA256" },
1572 { 0xC08B, "TLS_ECDHE_RSA_WITH_CAMELLIA_256_GCM_SHA384" },
1573 { 0xC09C, "TLS_RSA_WITH_AES_128_CCM" },
1574 { 0xC09D, "TLS_RSA_WITH_AES_256_CCM" },
1575 { 0xC09E, "TLS_DHE_RSA_WITH_AES_128_CCM" },
1576 { 0xC09F, "TLS_DHE_RSA_WITH_AES_256_CCM" },
1577 { 0xC0A0, "TLS_RSA_WITH_AES_128_CCM_8" },
1578 { 0xC0A1, "TLS_RSA_WITH_AES_256_CCM_8" },
1579 { 0xC0A2, "TLS_DHE_RSA_WITH_AES_128_CCM_8" },
1580 { 0xC0A3, "TLS_DHE_RSA_WITH_AES_256_CCM_8" },
1581 { 0xC0AC, "TLS_ECDHE_ECDSA_WITH_AES_128_CCM" },
1582 { 0xC0AD, "TLS_ECDHE_ECDSA_WITH_AES_256_CCM" },
1583 { 0xC0AE, "TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8" },
1584 { 0xC0AF, "TLS_ECDHE_ECDSA_WITH_AES_256_CCM_8" },
1585 { 0xCCA8, "TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256" },
1586 { 0xCCA9, "TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256" },
1587 { 0xCCAA, "TLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256" },
1588 { 0xCCAB, "TLS_PSK_WITH_CHACHA20_POLY1305_SHA256" },
1589 { 0xCCAC, "TLS_ECDHE_PSK_WITH_CHACHA20_POLY1305_SHA256" },
1590 { 0xCCAD, "TLS_DHE_PSK_WITH_CHACHA20_POLY1305_SHA256" },
1591 { 0xCCAE, "TLS_RSA_PSK_WITH_CHACHA20_POLY1305_SHA256" },
1592 { 0xFEFE, "SSL_RSA_FIPS_WITH_DES_CBC_SHA" },
1593 { 0xFEFF, "SSL_RSA_FIPS_WITH_3DES_EDE_CBC_SHA" },
1594
1595 { 0, NULL }
1596 };
1597
1598 /* Compressions */
1599 static struct tls_label tls_compression_labels[] = {
1600 { 0x0000, "None" },
1601 { 0x0001, "Zlib" },
1602
1603 { 0, NULL }
1604 };
1605
1606 /* Extensions */
1607 static struct tls_label tls_extension_labels[] = {
1608 { 0, "server_name" },
1609 { 1, "max_fragment_length" },
1610 { 2, "client_certificate_url" },
1611 { 3, "trusted_ca_keys" },
1612 { 4, "truncated_hmac" },
1613 { 5, "status_request" },
1614 { 6, "user_mapping" },
1615 { 7, "client_authz" },
1616 { 8, "server_authz" },
1617 { 9, "cert_type" },
1618 { 10, "elliptic_curves" },
1619 { 11, "ec_point_formats" },
1620 { 12, "srp" },
1621 { 13, "signature_algorithms" },
1622 { 14, "use_srtp" },
1623 { 15, "heartbeat" },
1624 { 16, "application_layer_protocol_negotiation" },
1625 { 18, "signed_certificate_timestamp" },
1626 { 21, "padding" },
1627 { 22, "encrypt_then_mac" },
1628 { 23, "extended_master_secret" },
1629 { 35, "session_ticket" },
1630 { 41, "psk" },
1631 { 42, "early_data" },
1632 { 43, "supported_versions" },
1633 { 44, "cookie" },
1634 { 45, "psk_kex_modes" },
1635 { 47, "certificate_authorities" },
1636 { 49, "post_handshake_auth" },
1637 { 50, "signature_algorithms_cert" },
1638 { 51, "key_share" },
1639 { 0xFF01, "renegotiate" },
1640 { 13172, "next_proto_neg" },
1641
1642 { 0, NULL }
1643 };
1644
1645 #if defined(TLSEXT_TYPE_signature_algorithms)
1646 /* Signature Algorithms. These values come from:
1647 * https://www.iana.org/assignments/tls-parameters/tls-parameters.xhtml#tls-parameters-16
1648 */
1649 static struct tls_label tls_sigalgo_labels[] = {
1650 { 0x0201, "rsa_pkcs1_sha1" },
1651 { 0x0202, "dsa_sha1" },
1652 { 0x0203, "ecdsa_sha1" },
1653 { 0x0301, "rsa_pkcs1_sha224" },
1654 { 0x0302, "dsa_sha224" },
1655 { 0x0303, "ecdsa_sha224" },
1656 { 0x0401, "rsa_pkcs1_sha256" },
1657 { 0x0402, "dsa_sha256" },
1658 { 0x0403, "ecdsa_secp256r1_sha256" },
1659 { 0x0501, "rsa_pkcs1_sha384" },
1660 { 0x0502, "dsa_sha384" },
1661 { 0x0503, "ecdsa_secp384r1_sha384" },
1662 { 0x0601, "rsa_pkcs1_sha512" },
1663 { 0x0602, "dsa_sha512" },
1664 { 0x0603, "ecdsa_secp521r1_sha512" },
1665 { 0x0804, "rsa_pss_rsae_sha256" },
1666 { 0x0805, "rsa_pss_rsae_sha384" },
1667 { 0x0806, "rsa_pss_rsae_sha512" },
1668 { 0x0807, "ed25519" },
1669 { 0x0808, "ed448" },
1670 { 0x0809, "rsa_pss_pss_sha256" },
1671 { 0x080A, "rsa_pss_pss_sha384" },
1672 { 0x080B, "rsa_pss_pss_sha512" },
1673
1674 { 0, NULL }
1675 };
1676 #endif /* TLSEXT_TYPE_signature_algorithms */
1677
1678 #if defined(TLSEXT_TYPE_psk_kex_modes)
1679 /* PSK KEX modes. These values come from:
1680 * https://tools.ietf.org/html/rfc8446#section-4.2.9
1681 */
1682 static struct tls_label tls_psk_kex_labels[] = {
1683 { 0, "psk_ke" },
1684 { 1, "psk_dhe_key" },
1685
1686 { 0, NULL }
1687 };
1688 #endif /* TLSEXT_TYPE_psk_kex_modes */
1689
1690 static const char *tls_get_label(int labelno, struct tls_label *labels) {
1691 register unsigned int i;
1692
1693 for (i = 0; labels[i].label_name != NULL; i++) {
1694 if (labels[i].labelno == labelno) {
1695 return labels[i].label_name;
1696 }
1697 }
1698
1699 return "[unknown/unsupported]";
1700 }
1701
1702 static void tls_print_ssl_version(BIO *bio, const char *name,
1703 const unsigned char **msg, size_t *msglen, int *pversion) {
1704 int version;
1705
1706 if (*msglen < 2) {
1707 return;
1708 }
1709
1710 version = ((*msg)[0] << 8) | (*msg)[1];
1711 BIO_printf(bio, " %s = %s\n", name,
1712 tls_get_label(version, tls_version_labels));
1713 *msg += 2;
1714 *msglen -= 2;
1715
1716 if (pversion != NULL) {
1717 *pversion = version;
1718 }
1719 }
1720
1721 static void tls_print_hex(BIO *bio, const char *indent, const char *name,
1722 const unsigned char *msg, size_t msglen) {
1723
1724 BIO_printf(bio, "%s (%lu %s)\n", name, (unsigned long) msglen,
1725 msglen != 1 ? "bytes" : "byte");
1726
1727 if (msglen > 0) {
1728 register unsigned int i;
1729
1730 BIO_puts(bio, indent);
1731 for (i = 0; i < msglen; i++) {
1732 BIO_printf(bio, "%02x", msg[i]);
1733 }
1734 BIO_puts(bio, "\n");
1735 }
1736 }
1737
1738 static void tls_print_hexbuf(BIO *bio, const char *indent, const char *name,
1739 size_t namelen, const unsigned char **msg, size_t *msglen) {
1740 size_t buflen;
1741 const unsigned char *ptr;
1742
1743 if (*msglen < namelen) {
1744 return;
1745 }
1746
1747 ptr = *msg;
1748 buflen = ptr[0];
1749
1750 if (namelen > 1) {
1751 buflen = (buflen << 8) | ptr[1];
1752 }
1753
1754 if (*msglen < namelen + buflen) {
1755 return;
1756 }
1757
1758 ptr += namelen;
1759 tls_print_hex(bio, indent, name, ptr, buflen);
1760 *msg += (buflen + namelen);
1761 *msglen -= (buflen + namelen);
1762 }
1763
1764 static void tls_print_random(BIO *bio, const unsigned char **msg,
1765 size_t *msglen) {
1766 pool *tmp_pool;
1767 time_t ts;
1768 const unsigned char *ptr;
1769
1770 if (*msglen < 32) {
1771 return;
1772 }
1773
1774 ptr = *msg;
1775
1776 ts = ((ptr[0] << 24) | (ptr[1] << 16) | (ptr[2] << 8) | ptr[3]);
1777 ptr += 4;
1778
1779 tmp_pool = make_sub_pool(session.pool);
1780 pr_pool_tag(tmp_pool, "TLS Diags pool");
1781
1782 BIO_puts(bio, " random:\n");
1783 BIO_printf(bio, " gmt_unix_time = %s (not guaranteed to be accurate)\n",
1784 pr_strtime3(tmp_pool, ts, TRUE));
1785 tls_print_hex(bio, " ", " random_bytes", ptr, 28);
1786 *msg += 32;
1787 *msglen -= 32;
1788 destroy_pool(tmp_pool);
1789 }
1790
1791 static void tls_print_session_id(BIO *bio, const unsigned char **msg,
1792 size_t *msglen) {
1793 tls_print_hexbuf(bio, " ", " session_id", 1, msg, msglen);
1794 }
1795
1796 static void tls_print_ciphersuites(BIO *bio, const char *name,
1797 const unsigned char **msg, size_t *msglen) {
1798 size_t len;
1799
1800 len = ((*msg[0]) << 8) | (*msg)[1];
1801 *msg += 2;
1802 *msglen -= 2;
1803 BIO_printf(bio, " %s (%lu %s)\n", name, (unsigned long) len,
1804 len != 1 ? "bytes" : "byte");
1805 if (*msglen < len ||
1806 (len & 1)) {
1807 return;
1808 }
1809
1810 while (len > 0) {
1811 unsigned int suiteno;
1812
1813 pr_signals_handle();
1814
1815 suiteno = ((*msg[0]) << 8) | (*msg)[1];
1816 BIO_printf(bio, " %s (0x%x)\n",
1817 tls_get_label(suiteno, tls_ciphersuite_labels), suiteno);
1818
1819 *msg += 2;
1820 *msglen -= 2;
1821 len -= 2;
1822 }
1823 }
1824
1825 static void tls_print_compressions(BIO *bio, const char *name,
1826 const unsigned char **msg, size_t *msglen) {
1827 size_t len;
1828
1829 len = (*msg)[0];
1830 *msg += 1;
1831 *msglen -= 1;
1832
1833 if (*msglen < len) {
1834 return;
1835 }
1836
1837 BIO_printf(bio, " %s (%lu %s)\n", name, (unsigned long) len,
1838 len != 1 ? "bytes" : "byte");
1839 while (len > 0) {
1840 int comp_type;
1841
1842 pr_signals_handle();
1843
1844 comp_type = (*msg)[0];
1845 BIO_printf(bio, " %s\n",
1846 tls_get_label(comp_type, tls_compression_labels));
1847
1848 *msg += 1;
1849 *msglen -= 1;
1850 len -= 1;
1851 }
1852 }
1853
1854 static void tls_print_extension(BIO *bio, const char *indent, int server,
1855 int ext_type, const unsigned char *ext, size_t extlen) {
1856
1857 BIO_printf(bio, "%sextension_type = %s (%lu %s)\n", indent,
1858 tls_get_label(ext_type, tls_extension_labels), (unsigned long) extlen,
1859 extlen != 1 ? "bytes" : "byte");
1860 }
1861
1862 static void tls_print_extensions(BIO *bio, const char *name, int server,
1863 const unsigned char **msg, size_t *msglen) {
1864 size_t len;
1865
1866 if (*msglen == 0) {
1867 BIO_printf(bio, "%s: None\n", name);
1868 return;
1869 }
1870
1871 len = ((*msg)[0] << 8) | (*msg)[1];
1872 if (len != (*msglen - 2)) {
1873 return;
1874 }
1875
1876 *msg += 2;
1877 *msglen -= 2;
1878
1879 BIO_printf(bio, " %s (%lu %s)\n", name, (unsigned long) len,
1880 len != 1 ? "bytes" : "byte");
1881 while (len > 0) {
1882 int ext_type;
1883 size_t ext_len;
1884
1885 pr_signals_handle();
1886
1887 if (*msglen < 4) {
1888 break;
1889 }
1890
1891 ext_type = ((*msg)[0] << 8) | (*msg)[1];
1892 ext_len = ((*msg)[2] << 8) | (*msg)[3];
1893
1894 if (*msglen < (ext_len + 4)) {
1895 break;
1896 }
1897
1898 *msg += 4;
1899 tls_print_extension(bio, " ", server, ext_type, *msg, ext_len);
1900 *msg += ext_len;
1901 *msglen -= (ext_len + 4);
1902 }
1903 }
1904
1905 static void tls_print_client_hello(int io_flag, int version, int content_type,
1906 const unsigned char *buf, size_t buflen, SSL *ssl, void *arg) {
1907 BIO *bio;
1908 char *data = NULL;
1909 long datalen;
1910
1911 bio = BIO_new(BIO_s_mem());
1912
1913 BIO_puts(bio, "\nClientHello:\n");
1914 tls_print_ssl_version(bio, "client_version", &buf, &buflen, NULL);
1915 tls_print_random(bio, &buf, &buflen);
1916 tls_print_session_id(bio, &buf, &buflen);
1917 if (buflen < 2) {
1918 BIO_free(bio);
1919 return;
1920 }
1921 tls_print_ciphersuites(bio, "cipher_suites", &buf, &buflen);
1922 if (buflen < 1) {
1923 BIO_free(bio);
1924 return;
1925 }
1926 tls_print_compressions(bio, "compression_methods", &buf, &buflen);
1927 tls_print_extensions(bio, "extensions", FALSE, &buf, &buflen);
1928
1929 datalen = BIO_get_mem_data(bio, &data);
1930 if (data != NULL) {
1931 data[datalen] = '\0';
1932 tls_log("[msg] %.*s", (int) datalen, data);
1933 }
1934
1935 BIO_free(bio);
1936 }
1937
1938 static void tls_print_server_hello(int io_flag, int version, int content_type,
1939 const unsigned char *buf, size_t buflen, SSL *ssl, void *arg) {
1940 BIO *bio;
1941 char *data = NULL;
1942 long datalen;
1943 int print_session_id = TRUE, print_compressions = TRUE, server_version = 0;
1944 unsigned int suiteno;
1945
1946 bio = BIO_new(BIO_s_mem());
1947
1948 BIO_puts(bio, "\nServerHello:\n");
1949 tls_print_ssl_version(bio, "server_version", &buf, &buflen, &server_version);
1950
1951 #ifdef TLS1_3_VERSION
1952 if (server_version == TLS1_3_VERSION) {
1953 print_session_id = FALSE;
1954 print_compressions = FALSE;
1955 }
1956 #endif /* TLS1_3_VERSION */
1957
1958 tls_print_random(bio, &buf, &buflen);
1959 if (print_session_id == TRUE) {
1960 tls_print_session_id(bio, &buf, &buflen);
1961 }
1962 if (buflen < 2) {
1963 BIO_free(bio);
1964 return;
1965 }
1966
1967 /* Print the selected ciphersuite. */
1968 BIO_printf(bio, " cipher_suites (2 bytes)\n");
1969 suiteno = (buf[0] << 8) | buf[1];
1970 BIO_printf(bio, " %s (0x%x)\n",
1971 tls_get_label(suiteno, tls_ciphersuite_labels), suiteno);
1972 buf += 2;
1973 buflen -= 2;
1974
1975 if (print_compressions == TRUE) {
1976 int comp_type;
1977
1978 if (buflen < 1) {
1979 BIO_free(bio);
1980 return;
1981 }
1982
1983 /* Print the selected compression. */
1984 BIO_printf(bio, " compression_methods (1 byte)\n");
1985 comp_type = *buf;
1986 BIO_printf(bio, " %s\n",
1987 tls_get_label(comp_type, tls_compression_labels));
1988 buf += 1;
1989 buflen -= 1;
1990 }
1991 tls_print_extensions(bio, "extensions", TRUE, &buf, &buflen);
1992
1993 datalen = BIO_get_mem_data(bio, &data);
1994 if (data != NULL) {
1995 data[datalen] = '\0';
1996 tls_log("[msg] %.*s", (int) datalen, data);
1997 }
1998
1999 BIO_free(bio);
2000 }
2001
2002 #ifdef SSL3_MT_NEWSESSION_TICKET
2003 static void tls_print_ticket(int io_flag, int version, int content_type,
2004 const unsigned char *buf, size_t buflen, SSL *ssl, void *arg) {
2005 BIO *bio;
2006 char *data = NULL;
2007 long datalen;
2008
2009 bio = BIO_new(BIO_s_mem());
2010
2011 BIO_puts(bio, "\nNewSessionTicket:\n");
2012 if (buflen != 0) {
2013 unsigned int ticket_lifetime;
2014 int print_ticket_age = FALSE, print_extensions = FALSE;
2015
2016 ticket_lifetime = (buf[0] << 24) | (buf[1] << 16) | (buf[2] << 8) | buf[3];
2017 buf += 4;
2018 buflen -= 4;
2019 BIO_printf(bio, " ticket_lifetime_hint\n %u (sec)\n", ticket_lifetime);
2020
2021 # if defined(TLS1_3_VERSION)
2022 if (SSL_version(ssl) == TLS1_3_VERSION) {
2023 print_ticket_age = TRUE;
2024 print_extensions = TRUE;
2025 }
2026 # endif /* TLS1_3_VERSION */
2027
2028 if (print_ticket_age == TRUE) {
2029 unsigned int ticket_age_add;
2030
2031 ticket_age_add = (buf[0] << 24) | (buf[1] << 16) | (buf[2] << 8) | buf[3];
2032 buf += 4;
2033 buflen -= 4;
2034 BIO_printf(bio, " ticket_age_add\n %u (sec)\n", ticket_age_add);
2035 tls_print_hexbuf(bio, " ", " ticket_nonce", 1, &buf, &buflen);
2036 }
2037
2038 tls_print_hexbuf(bio, " ", " ticket", 2, &buf, &buflen);
2039
2040 if (print_extensions == TRUE) {
2041 tls_print_extensions(bio, "extensions", TRUE, &buf, &buflen);
2042 }
2043
2044 } else {
2045 BIO_puts(bio, " <no ticket>\n");
2046 }
2047
2048 datalen = BIO_get_mem_data(bio, &data);
2049 if (data != NULL) {
2050 data[datalen] = '\0';
2051 tls_log("[msg] %.*s", (int) datalen, data);
2052 }
2053
2054 BIO_free(bio);
2055 }
2056 #endif /* SSL3_MT_NEWSESSION_TICKET */
2057
2058 static void tls_msg_cb(int io_flag, int version, int content_type,
2059 const void *buf, size_t buflen, SSL *ssl, void *arg) {
2060 char *action_str = NULL, *version_str = NULL;
2061 char *bytes_str = buflen != 1 ? "bytes" : "byte";
2062
2063 if (io_flag == 0) {
2064 action_str = "received";
2065
2066 } else if (io_flag == 1) {
2067 action_str = "sent";
2068 }
2069
2070 switch (version) {
2071 case SSL2_VERSION:
2072 version_str = "SSLv2";
2073 break;
2074
2075 case SSL3_VERSION:
2076 version_str = "SSLv3";
2077 break;
2078
2079 case TLS1_VERSION:
2080 version_str = "TLSv1";
2081 break;
2082
2083 # if defined(TLS1_1_VERSION)
2084 case TLS1_1_VERSION:
2085 version_str = "TLSv1.1";
2086 break;
2087 # endif /* TLS1_1_VERSION */
2088
2089 # if defined(TLS1_2_VERSION)
2090 case TLS1_2_VERSION:
2091 version_str = "TLSv1.2";
2092 break;
2093 # endif /* TLS1_2_VERSION */
2094
2095 # if OPENSSL_VERSION_NUMBER >= 0x10101000L && \
2096 defined(TLS1_3_VERSION)
2097 case TLS1_3_VERSION:
2098 version_str = "TLSv1.3";
2099 break;
2100 # endif /* TLS1_3_VERSION */
2101
2102 default:
2103 #ifdef SSL3_RT_HEADER
2104 /* OpenSSL calls this callback for SSL records received; filter those
2105 * from true "unknowns".
2106 */
2107 if (version == 0 &&
2108 (content_type != SSL3_RT_HEADER ||
2109 buflen != SSL3_RT_HEADER_LENGTH)) {
2110 tls_log("[msg] unknown/unsupported version: %d", version);
2111 }
2112 #else
2113 tls_log("[msg] unknown/unsupported version: %d", version);
2114 #endif
2115 break;
2116 }
2117
2118 if (version == SSL3_VERSION ||
2119 #if OPENSSL_VERSION_NUMBER >= 0x10001000L
2120 version == TLS1_1_VERSION ||
2121 version == TLS1_2_VERSION ||
2122 # if OPENSSL_VERSION_NUMBER >= 0x10101000L && \
2123 defined(TLS1_3_VERSION)
2124 version == TLS1_3_VERSION ||
2125 # endif
2126 #endif
2127 version == TLS1_VERSION) {
2128
2129 switch (content_type) {
2130 case SSL3_RT_CHANGE_CIPHER_SPEC:
2131 /* ChangeCipherSpec message */
2132 pr_trace_msg(trace_channel, 27,
2133 "%s %s ChangeCipherSpec (%u %s)", action_str, version_str,
2134 (unsigned int) buflen, bytes_str);
2135 tls_log("[msg] %s %s ChangeCipherSpec message (%u %s)",
2136 action_str, version_str, (unsigned int) buflen, bytes_str);
2137 break;
2138
2139 case SSL3_RT_ALERT: {
2140 /* Alert messages */
2141 pr_trace_msg(trace_channel, 27,
2142 "%s %s Alert (%u %s)", action_str, version_str,
2143 (unsigned int) buflen, bytes_str);
2144 if (buflen == 2) {
2145 char *severity_str = NULL;
2146
2147 /* Peek naughtily into the buffer. */
2148 switch (((const unsigned char *) buf)[0]) {
2149 case SSL3_AL_WARNING:
2150 severity_str = "warning";
2151 break;
2152
2153 case SSL3_AL_FATAL:
2154 severity_str = "fatal";
2155 break;
2156 }
2157
2158 switch (((const unsigned char *) buf)[1]) {
2159 case SSL3_AD_CLOSE_NOTIFY:
2160 tls_log("[msg] %s %s %s 'close_notify' Alert message (%u %s)",
2161 action_str, version_str, severity_str, (unsigned int) buflen,
2162 bytes_str);
2163 break;
2164
2165 case SSL3_AD_UNEXPECTED_MESSAGE:
2166 tls_log("[msg] %s %s %s 'unexpected_message' Alert message "
2167 "(%u %s)", action_str, version_str, severity_str,
2168 (unsigned int) buflen, bytes_str);
2169 break;
2170
2171 case SSL3_AD_BAD_RECORD_MAC:
2172 tls_log("[msg] %s %s %s 'bad_record_mac' Alert message (%u %s)",
2173 action_str, version_str, severity_str, (unsigned int) buflen,
2174 bytes_str);
2175 break;
2176
2177 case 21:
2178 tls_log("[msg] %s %s %s 'decryption_failed' Alert message "
2179 "(%u %s)", action_str, version_str, severity_str,
2180 (unsigned int) buflen, bytes_str);
2181 break;
2182
2183 case 22:
2184 tls_log("[msg] %s %s %s 'record_overflow' Alert message (%u %s)",
2185 action_str, version_str, severity_str, (unsigned int) buflen,
2186 bytes_str);
2187 break;
2188
2189 case SSL3_AD_DECOMPRESSION_FAILURE:
2190 tls_log("[msg] %s %s %s 'decompression_failure' Alert message "
2191 "(%u %s)", action_str, version_str, severity_str,
2192 (unsigned int) buflen, bytes_str);
2193 break;
2194
2195 case SSL3_AD_HANDSHAKE_FAILURE:
2196 tls_log("[msg] %s %s %s 'handshake_failure' Alert message "
2197 "(%u %s)", action_str, version_str, severity_str,
2198 (unsigned int) buflen, bytes_str);
2199 break;
2200
2201 #ifdef SSL3_AD_NO_CERTIFICATE
2202 case SSL3_AD_NO_CERTIFICATE:
2203 tls_log("[msg] %s %s %s 'no_certificate' Alert message "
2204 "(%u %s)", action_str, version_str, severity_str,
2205 (unsigned int) buflen, bytes_str);
2206 break;
2207 #endif /* SSL3_AD_NO_CERTIFICATE */
2208
2209 #ifdef SSL3_AD_BAD_CERTIFICATE
2210 case SSL3_AD_BAD_CERTIFICATE:
2211 tls_log("[msg] %s %s %s 'bad_certificate' Alert message "
2212 "(%u %s)", action_str, version_str, severity_str,
2213 (unsigned int) buflen, bytes_str);
2214 break;
2215 #endif /* SSL3_AD_BAD_CERTIFICATE */
2216
2217 #ifdef SSL3_AD_UNSUPPORTED_CERTIFICATE
2218 case SSL3_AD_UNSUPPORTED_CERTIFICATE:
2219 tls_log("[msg] %s %s %s 'unsupported_certificate' Alert message "
2220 "(%u %s)", action_str, version_str, severity_str,
2221 (unsigned int) buflen, bytes_str);
2222 break;
2223 #endif /* SSL3_AD_UNSUPPORTED_CERTIFICATE */
2224
2225 #ifdef SSL3_AD_CERTIFICATE_REVOKED
2226 case SSL3_AD_CERTIFICATE_REVOKED:
2227 tls_log("[msg] %s %s %s 'certificate_revoked' Alert message "
2228 "(%u %s)", action_str, version_str, severity_str,
2229 (unsigned int) buflen, bytes_str);
2230 break;
2231 #endif /* SSL3_AD_CERTIFICATE_REVOKED */
2232
2233 #ifdef SSL3_AD_CERTIFICATE_EXPIRED
2234 case SSL3_AD_CERTIFICATE_EXPIRED:
2235 tls_log("[msg] %s %s %s 'certificate_expired' Alert message "
2236 "(%u %s)", action_str, version_str, severity_str,
2237 (unsigned int) buflen, bytes_str);
2238 break;
2239 #endif /* SSL3_AD_CERTIFICATE_EXPIRED */
2240
2241 #ifdef SSL3_AD_CERTIFICATE_UNKNOWN
2242 case SSL3_AD_CERTIFICATE_UNKNOWN:
2243 tls_log("[msg] %s %s %s 'certificate_unknown' Alert message "
2244 "(%u %s)", action_str, version_str, severity_str,
2245 (unsigned int) buflen, bytes_str);
2246 break;
2247 #endif /* SSL3_AD_CERTIFICATE_UNKNOWN */
2248
2249 #ifdef SSL3_AD_ILLEGAL_PARAMETER
2250 case SSL3_AD_ILLEGAL_PARAMETER:
2251 tls_log("[msg] %s %s %s 'illegal_parameter' Alert message "
2252 "(%u %s)", action_str, version_str, severity_str,
2253 (unsigned int) buflen, bytes_str);
2254 break;
2255 #endif /* SSL3_AD_ILLEGAL_PARAMETER */
2256 }
2257
2258 } else {
2259 tls_log("[msg] %s %s Alert message, unknown type (%u %s)", action_str,
2260 version_str, (unsigned int) buflen, bytes_str);
2261 }
2262
2263 break;
2264 }
2265
2266 case SSL3_RT_HANDSHAKE: {
2267 /* Handshake messages */
2268 pr_trace_msg(trace_channel, 27,
2269 "%s %s Handshake (%u %s)", action_str, version_str,
2270 (unsigned int) buflen, bytes_str);
2271 if (buflen > 0) {
2272 /* Peek naughtily into the buffer. */
2273 switch (((const unsigned char *) buf)[0]) {
2274 case SSL3_MT_HELLO_REQUEST:
2275 tls_log("[msg] %s %s 'HelloRequest' Handshake message (%u %s)",
2276 action_str, version_str, (unsigned int) buflen, bytes_str);
2277 break;
2278
2279 case SSL3_MT_CLIENT_HELLO: {
2280 const unsigned char *msg;
2281 size_t msglen;
2282
2283 msg = buf;
2284 msglen = buflen;
2285
2286 tls_log("[msg] %s %s 'ClientHello' Handshake message (%u %s)",
2287 action_str, version_str, (unsigned int) msglen, bytes_str);
2288
2289 tls_print_client_hello(io_flag, version, content_type, msg + 4,
2290 msglen - 4, ssl, arg);
2291 break;
2292 }
2293
2294 case SSL3_MT_SERVER_HELLO: {
2295 const unsigned char *msg;
2296 size_t msglen;
2297
2298 msg = buf;
2299 msglen = buflen;
2300
2301 tls_log("[msg] %s %s 'ServerHello' Handshake message (%u %s)",
2302 action_str, version_str, (unsigned int) buflen, bytes_str);
2303
2304 tls_print_server_hello(io_flag, version, content_type, msg + 4,
2305 msglen - 4, ssl, arg);
2306 break;
2307 }
2308
2309 #ifdef SSL3_MT_NEWSESSION_TICKET
2310 case SSL3_MT_NEWSESSION_TICKET: {
2311 const unsigned char *msg;
2312 size_t msglen;
2313
2314 msg = buf;
2315 msglen = buflen;
2316
2317 tls_log("[msg] %s %s 'NewSessionTicket' Handshake message "
2318 "(%u %s)", action_str, version_str, (unsigned int) buflen,
2319 bytes_str);
2320
2321 tls_print_ticket(io_flag, version, content_type, msg + 4,
2322 msglen - 4, ssl, arg);
2323 break;
2324 }
2325 #endif /* SSL3_MT_NEWSESSION_TICKET */
2326
2327 case SSL3_MT_CERTIFICATE:
2328 tls_log("[msg] %s %s 'Certificate' Handshake message (%u %s)",
2329 action_str, version_str, (unsigned int) buflen, bytes_str);
2330 break;
2331
2332 case SSL3_MT_SERVER_KEY_EXCHANGE:
2333 tls_log("[msg] %s %s 'ServerKeyExchange' Handshake message "
2334 "(%u %s)", action_str, version_str, (unsigned int) buflen,
2335 bytes_str);
2336 break;
2337
2338 case SSL3_MT_CERTIFICATE_REQUEST:
2339 tls_log("[msg] %s %s 'CertificateRequest' Handshake message "
2340 "(%u %s)", action_str, version_str, (unsigned int) buflen,
2341 bytes_str);
2342 break;
2343
2344 case SSL3_MT_SERVER_DONE:
2345 tls_log("[msg] %s %s 'ServerHelloDone' Handshake message (%u %s)",
2346 action_str, version_str, (unsigned int) buflen, bytes_str);
2347 break;
2348
2349 case SSL3_MT_CERTIFICATE_VERIFY:
2350 tls_log("[msg] %s %s 'CertificateVerify' Handshake message "
2351 "(%u %s)", action_str, version_str, (unsigned int) buflen,
2352 bytes_str);
2353 break;
2354
2355 case SSL3_MT_CLIENT_KEY_EXCHANGE:
2356 tls_log("[msg] %s %s 'ClientKeyExchange' Handshake message "
2357 "(%u %s)", action_str, version_str, (unsigned int) buflen,
2358 bytes_str);
2359 break;
2360
2361 case SSL3_MT_FINISHED:
2362 tls_log("[msg] %s %s 'Finished' Handshake message (%u %s)",
2363 action_str, version_str, (unsigned int) buflen, bytes_str);
2364 break;
2365
2366 #ifdef SSL3_MT_CERTIFICATE_STATUS
2367 case SSL3_MT_CERTIFICATE_STATUS:
2368 tls_log("[msg] %s %s 'CertificateStatus' Handshake message "
2369 "(%u %s)", action_str, version_str, (unsigned int) buflen,
2370 bytes_str);
2371 break;
2372 #endif /* SSL3_MT_CERTIFICATE_STATUS */
2373
2374 #ifdef SSL3_MT_ENCRYPTED_EXTENSIONS
2375 case SSL3_MT_ENCRYPTED_EXTENSIONS: {
2376 const unsigned char *msg;
2377 size_t msglen;
2378 BIO *bio;
2379 char *data = NULL;
2380 long datalen;
2381
2382 msg = buf;
2383 msglen = buflen;
2384
2385 tls_log("[msg] %s %s 'EncryptedExtensions' Handshake message "
2386 "(%u %s)", action_str, version_str, (unsigned int) buflen,
2387 bytes_str);
2388
2389 bio = BIO_new(BIO_s_mem());
2390
2391 msg += 4;
2392 msglen -= 4;
2393
2394 BIO_puts(bio, "\nEncryptedExtensions:\n");
2395 tls_print_extensions(bio, "extensions", TRUE, &msg, &msglen);
2396 datalen = BIO_get_mem_data(bio, &data);
2397 if (data != NULL) {
2398 data[datalen] = '\0';
2399 tls_log("[msg] %.*s", (int) datalen, data);
2400 }
2401
2402 BIO_free(bio);
2403 break;
2404 }
2405 #endif /* SSL3_MT_ENCRYPTED_EXTENSIONS */
2406 }
2407
2408 } else {
2409 tls_log("[msg] %s %s Handshake message, unknown type %d (%u %s)",
2410 action_str, version_str, content_type, (unsigned int) buflen,
2411 bytes_str);
2412 }
2413
2414 break;
2415 }
2416 }
2417
2418 } else if (version == SSL2_VERSION) {
2419 /* SSLv2 message. Ideally we wouldn't get these, but sometimes badly
2420 * behaving FTPS clients send them.
2421 */
2422
2423 if (buflen > 0) {
2424 /* Peek naughtily into the buffer. */
2425
2426 switch (((const unsigned char *) buf)[0]) {
2427 case 0: {
2428 /* Error */
2429 if (buflen > 3) {
2430 unsigned err_code = (((const unsigned char *) buf)[1] << 8) +
2431 ((const unsigned char *) buf)[2];
2432
2433 switch (err_code) {
2434 case 0x0001:
2435 tls_log("[msg] %s %s 'NO-CIPHER-ERROR' Error message (%u %s)",
2436 action_str, version_str, (unsigned int) buflen, bytes_str);
2437 break;
2438
2439 case 0x0002:
2440 tls_log("[msg] %s %s 'NO-CERTIFICATE-ERROR' Error message "
2441 "(%u %s)", action_str, version_str, (unsigned int) buflen,
2442 bytes_str);
2443 break;
2444
2445 case 0x0004:
2446 tls_log("[msg] %s %s 'BAD-CERTIFICATE-ERROR' Error message "
2447 "(%u %s)", action_str, version_str, (unsigned int) buflen,
2448 bytes_str);
2449 break;
2450
2451 case 0x0006:
2452 tls_log("[msg] %s %s 'UNSUPPORTED-CERTIFICATE-TYPE-ERROR' "
2453 "Error message (%u %s)", action_str, version_str,
2454 (unsigned int) buflen, bytes_str);
2455 break;
2456 }
2457
2458 } else {
2459 tls_log("[msg] %s %s Error message, unknown type %d (%u %s)",
2460 action_str, version_str, content_type, (unsigned int) buflen,
2461 bytes_str);
2462 }
2463 break;
2464 }
2465
2466 case 1:
2467 tls_log("[msg] %s %s 'CLIENT-HELLO' message (%u %s)", action_str,
2468 version_str, (unsigned int) buflen, bytes_str);
2469 break;
2470
2471 case 2:
2472 tls_log("[msg] %s %s 'CLIENT-MASTER-KEY' message (%u %s)", action_str,
2473 version_str, (unsigned int) buflen, bytes_str);
2474 break;
2475
2476 case 3:
2477 tls_log("[msg] %s %s 'CLIENT-FINISHED' message (%u %s)", action_str,
2478 version_str, (unsigned int) buflen, bytes_str);
2479 break;
2480
2481 case 4:
2482 tls_log("[msg] %s %s 'SERVER-HELLO' message (%u %s)", action_str,
2483 version_str, (unsigned int) buflen, bytes_str);
2484 break;
2485
2486 case 5:
2487 tls_log("[msg] %s %s 'SERVER-VERIFY' message (%u %s)", action_str,
2488 version_str, (unsigned int) buflen, bytes_str);
2489 break;
2490
2491 case 6:
2492 tls_log("[msg] %s %s 'SERVER-FINISHED' message (%u %s)", action_str,
2493 version_str, (unsigned int) buflen, bytes_str);
2494 break;
2495
2496 case 7:
2497 tls_log("[msg] %s %s 'REQUEST-CERTIFICATE' message (%u %s)",
2498 action_str, version_str, (unsigned int) buflen, bytes_str);
2499 break;
2500
2501 case 8:
2502 tls_log("[msg] %s %s 'CLIENT-CERTIFICATE' message (%u %s)",
2503 action_str, version_str, (unsigned int) buflen, bytes_str);
2504 break;
2505 }
2506
2507 } else {
2508 tls_log("[msg] %s %s message (%u %s)", action_str, version_str,
2509 (unsigned int) buflen, bytes_str);
2510 }
2511
2512 #ifdef SSL3_RT_HEADER
2513 } else if (version == 0 &&
2514 content_type == SSL3_RT_HEADER &&
2515 buflen == SSL3_RT_HEADER_LENGTH) {
2516 const unsigned char *msg;
2517 const char *record_type;
2518 int msg_len;
2519
2520 msg = buf;
2521 record_type = tls_get_label(msg[0], tls_record_type_labels);
2522 msg_len = msg[buflen - 2] << 8 | msg[buflen - 1];
2523
2524 tls_log("[msg] %s protocol record message (content type = %s, len = %d)",
2525 action_str, record_type, msg_len);
2526 #endif
2527
2528 } else {
2529 /* This case might indicate an issue with OpenSSL itself; the version
2530 * given to the msg_callback function was not initialized, or not set to
2531 * one of the recognized SSL/TLS versions. Weird.
2532 */
2533
2534 tls_log("[msg] %s message of unknown version %d, type %d (%u %s)",
2535 action_str, version, content_type, (unsigned int) buflen, bytes_str);
2536 }
2537
2538 }
2539 #endif
2540
2541 static const char *get_printable_subjaltname(pool *p, const char *data,
2542 size_t datalen) {
2543 register unsigned int i;
2544 char *ptr, *res;
2545 size_t reslen = 0;
2546
2547 /* First, calculate the length of the resulting printable string we'll
2548 * be generating.
2549 */
2550
2551 for (i = 0; i < datalen; i++) {
2552 if (PR_ISPRINT(data[i])) {
2553 reslen++;
2554
2555 } else {
2556 reslen += 4;
2557 }
2558 }
2559
2560 /* Leave one space in the allocated string for the terminating NUL. */
2561 ptr = res = pcalloc(p, reslen + 1);
2562
2563 for (i = 0; i < datalen; i++) {
2564 if (PR_ISPRINT(data[i])) {
2565 *(ptr++) = data[i];
2566
2567 } else {
2568 pr_snprintf(ptr, reslen - (ptr - res), "\\x%02x", data[i]);
2569 ptr += 4;
2570 }
2571 }
2572
2573 return res;
2574 }
2575
2576 static int tls_cert_match_dns_san(pool *p, X509 *cert, const char *dns_name) {
2577 int matched = 0;
2578 #if OPENSSL_VERSION_NUMBER > 0x000907000L
2579 STACK_OF(GENERAL_NAME) *sans;
2580
2581 sans = X509_get_ext_d2i(cert, NID_subject_alt_name, NULL, NULL);
2582 if (sans != NULL) {
2583 register int i;
2584 int nsans = sk_GENERAL_NAME_num(sans);
2585
2586 for (i = 0; i < nsans; i++) {
2587 GENERAL_NAME *alt_name;
2588
2589 pr_signals_handle();
2590
2591 alt_name = sk_GENERAL_NAME_value(sans, i);
2592 if (alt_name->type == GEN_DNS) {
2593 char *dns_san;
2594 size_t dns_sanlen;
2595
2596 #if OPENSSL_VERSION_NUMBER >= 0x10100000L && \
2597 !defined(HAVE_LIBRESSL)
2598 dns_san = (char *) ASN1_STRING_get0_data(alt_name->d.ia5);
2599 #else
2600 dns_san = (char *) ASN1_STRING_data(alt_name->d.ia5);
2601 #endif /* OpenSSL 1.1.x and later */
2602 dns_sanlen = strlen(dns_san);
2603
2604 /* Check for subjectAltName values which contain embedded NULs.
2605 * This can cause verification problems (spoofing), e.g. if the
2606 * string is "www.goodguy.com\0www.badguy.com"; the use of strcmp()
2607 * only checks "www.goodguy.com".
2608 */
2609
2610 if ((size_t) ASN1_STRING_length(alt_name->d.ia5) != dns_sanlen) {
2611 tls_log("%s", "cert dNSName SAN contains embedded NULs, "
2612 "rejecting as possible spoof attempt");
2613 tls_log("suspicious dNSName SAN value: '%s'",
2614 get_printable_subjaltname(p, dns_san,
2615 ASN1_STRING_length(alt_name->d.dNSName)));
2616
2617 GENERAL_NAME_free(alt_name);
2618 sk_GENERAL_NAME_free(sans);
2619 return 0;
2620 }
2621
2622 if (strncasecmp(dns_name, dns_san, dns_sanlen + 1) == 0) {
2623 pr_trace_msg(trace_channel, 8,
2624 "found cert dNSName SAN matching '%s'", dns_name);
2625 matched = 1;
2626
2627 } else {
2628 pr_trace_msg(trace_channel, 9,
2629 "cert dNSName SAN '%s' did not match '%s'", dns_san, dns_name);
2630 }
2631 }
2632
2633 GENERAL_NAME_free(alt_name);
2634
2635 if (matched == 1) {
2636 break;
2637 }
2638 }
2639
2640 sk_GENERAL_NAME_free(sans);
2641 }
2642 #endif /* OpenSSL-0.9.7 or later */
2643
2644 return matched;
2645 }
2646
2647 static int tls_cert_match_ip_san(pool *p, X509 *cert, const char *ipstr) {
2648 int matched = 0;
2649 STACK_OF(GENERAL_NAME) *sans;
2650
2651 sans = X509_get_ext_d2i(cert, NID_subject_alt_name, NULL, NULL);
2652 if (sans != NULL) {
2653 register int i;
2654 int nsans = sk_GENERAL_NAME_num(sans);
2655
2656 for (i = 0; i < nsans; i++) {
2657 GENERAL_NAME *alt_name;
2658
2659 pr_signals_handle();
2660
2661 alt_name = sk_GENERAL_NAME_value(sans, i);
2662 if (alt_name->type == GEN_IPADD) {
2663 const unsigned char *san_data = NULL;
2664 int have_ipstr = FALSE, san_datalen;
2665 #ifdef PR_USE_IPV6
2666 char san_ipstr[INET6_ADDRSTRLEN + 1] = {'\0'};
2667 #else
2668 char san_ipstr[INET_ADDRSTRLEN + 1] = {'\0'};
2669 #endif /* PR_USE_IPV6 */
2670
2671 #if OPENSSL_VERSION_NUMBER >= 0x10100000L && \
2672 !defined(HAVE_LIBRESSL)
2673 san_data = ASN1_STRING_get0_data(alt_name->d.ip);
2674 #else
2675 san_data = ASN1_STRING_data(alt_name->d.ip);
2676 #endif /* OpenSSL 1.1.x and later */
2677
2678 memset(san_ipstr, '\0', sizeof(san_ipstr));
2679
2680 san_datalen = ASN1_STRING_length(alt_name->d.ip);
2681 if (san_datalen == 4) {
2682 /* IPv4 address */
2683 pr_snprintf(san_ipstr, sizeof(san_ipstr)-1, "%u.%u.%u.%u",
2684 san_data[0], san_data[1], san_data[2], san_data[3]);
2685 have_ipstr = TRUE;
2686
2687 #ifdef PR_USE_IPV6
2688 } else if (san_datalen == 16) {
2689 /* IPv6 address */
2690
2691 if (pr_inet_ntop(AF_INET6, san_data, san_ipstr,
2692 sizeof(san_ipstr)-1) == NULL) {
2693 tls_log("unable to convert cert iPAddress SAN value (length %d) "
2694 "to IPv6 representation: %s", san_datalen, strerror(errno));
2695
2696 } else {
2697 have_ipstr = TRUE;
2698 }
2699
2700 #endif /* PR_USE_IPV6 */
2701 } else {
2702 pr_trace_msg(trace_channel, 3,
2703 "unsupported cert SAN ipAddress length (%d), ignoring",
2704 san_datalen);
2705 continue;
2706 }
2707
2708 if (have_ipstr) {
2709 size_t san_ipstrlen;
2710
2711 san_ipstrlen = strlen(san_ipstr);
2712
2713 if (strncmp(ipstr, san_ipstr, san_ipstrlen + 1) == 0) {
2714 pr_trace_msg(trace_channel, 8,
2715 "found cert iPAddress SAN matching '%s'", ipstr);
2716 matched = 1;
2717
2718 } else {
2719 if (san_datalen == 16) {
2720 /* We need to handle the case where the iPAddress SAN might
2721 * have contained an IPv4-mapped IPv6 address, and we're
2722 * comparing against an IPv4 address.
2723 */
2724 if (san_ipstrlen > 7 &&
2725 strncasecmp(san_ipstr, "::ffff:", 7) == 0) {
2726 if (strncmp(ipstr, san_ipstr + 7, san_ipstrlen - 6) == 0) {
2727 pr_trace_msg(trace_channel, 8,
2728 "found cert iPAddress SAN '%s' matching '%s'",
2729 san_ipstr, ipstr);
2730 matched = 1;
2731 }
2732 }
2733
2734 } else {
2735 pr_trace_msg(trace_channel, 9,
2736 "cert iPAddress SAN '%s' did not match '%s'", san_ipstr, ipstr);
2737 }
2738 }
2739 }
2740 }
2741
2742 GENERAL_NAME_free(alt_name);
2743
2744 if (matched == 1) {
2745 break;
2746 }
2747 }
2748
2749 sk_GENERAL_NAME_free(sans);
2750 }
2751
2752 return matched;
2753 }
2754
2755 static char *tls_get_cert_cn(pool *p, X509 *cert) {
2756 int idx = -1;
2757 const X509_NAME *subj_name = NULL;
2758 const X509_NAME_ENTRY *cn_entry = NULL;
2759 const ASN1_STRING *cn_asn1 = NULL;
2760 char *cn_str = NULL;
2761 size_t cn_len = 0;
2762
2763 /* Find the position of the CommonName (CN) field within the Subject of
2764 * the cert.
2765 */
2766 subj_name = X509_get_subject_name(cert);
2767 if (subj_name == NULL) {
2768 errno = ENOENT;
2769 return NULL;
2770 }
2771
2772 idx = X509_NAME_get_index_by_NID(subj_name, NID_commonName, -1);
2773 if (idx < 0) {
2774 errno = ENOENT;
2775 return NULL;
2776 }
2777
2778 cn_entry = X509_NAME_get_entry(subj_name, idx);
2779 if (cn_entry == NULL) {
2780 errno = ENOENT;
2781 return NULL;
2782 }
2783
2784 /* Convert the CN field to a string, by way of an ASN1 object. */
2785 cn_asn1 = X509_NAME_ENTRY_get_data(cn_entry);
2786 if (cn_asn1 == NULL) {
2787 pr_trace_msg(trace_channel, 12,
2788 "error converting CommoName attribute to ASN.1: %s", tls_get_errors());
2789 errno = EPERM;
2790 return NULL;
2791 }
2792
2793 #if OPENSSL_VERSION_NUMBER >= 0x10100000L && \
2794 !defined(HAVE_LIBRESSL)
2795 cn_str = (char *) ASN1_STRING_get0_data(cn_asn1);
2796 #else
2797 cn_str = (char *) ASN1_STRING_data(cn_asn1);
2798 #endif /* OpenSSL 1.1.x and later */
2799
2800 /* Check for CommonName values which contain embedded NULs. This can cause
2801 * verification problems (spoofing), e.g. if the string is
2802 * "www.goodguy.com\0www.badguy.com"; the use of strcmp() only checks
2803 * "www.goodguy.com".
2804 */
2805
2806 cn_len = strlen(cn_str);
2807
2808 if ((size_t) ASN1_STRING_length(cn_asn1) != cn_len) {
2809 tls_log("%s", "cert CommonName contains embedded NULs, rejecting as "
2810 "possible spoof attempt");
2811 tls_log("suspicious CommonName value: '%s'",
2812 get_printable_subjaltname(p, (const char *) cn_str,
2813 ASN1_STRING_length(cn_asn1)));
2814 errno = EPERM;
2815 return NULL;
2816 }
2817
2818 return pstrdup(p, cn_str);
2819 }
2820
2821 static int tls_cert_match_cn(pool *p, X509 *cert, const char *name,
2822 int allow_wildcards) {
2823 int matched = 0;
2824 char *cert_cn = NULL;
2825
2826 cert_cn = tls_get_cert_cn(p, cert);
2827 if (cert_cn == NULL) {
2828 return 0;
2829 }
2830
2831 /* Yes, this is deliberately a case-insensitive comparison. Most CNs
2832 * contain a hostname (case-insensitive); if they contain an IP address,
2833 * the case-insensitivity won't hurt anything. In fact, it's needed for
2834 * e.g. IPv6 addresses.
2835 */
2836 if (strcasecmp(name, cert_cn) == 0) {
2837 matched = 1;
2838 }
2839
2840 if (matched == 0 &&
2841 allow_wildcards == TRUE) {
2842
2843 /* XXX Implement wildcard checking. */
2844 }
2845
2846 return matched;
2847 }
2848
2849 static int tls_check_client_cert(SSL *ssl, conn_t *conn) {
2850 X509 *cert = NULL;
2851 unsigned char have_cn = FALSE, have_dns_ext = FALSE, have_ipaddr_ext = FALSE;
2852 int ok = -1;
2853
2854 /* Only perform these more stringent checks if asked to verify clients. */
2855 if (!(tls_flags & TLS_SESS_VERIFY_CLIENT_REQUIRED)) {
2856 return 0;
2857 }
2858
2859 /* Only perform these checks is configured to do so. */
2860 if (!(tls_opts & TLS_OPT_VERIFY_CERT_FQDN) &&
2861 !(tls_opts & TLS_OPT_VERIFY_CERT_IP_ADDR) &&
2862 !(tls_opts & TLS_OPT_VERIFY_CERT_CN)) {
2863 return 0;
2864 }
2865
2866 cert = SSL_get_peer_certificate(ssl);
2867 if (cert == NULL) {
2868 /* This can be null in the case where some anonymous (insecure)
2869 * cipher suite was used.
2870 */
2871 tls_log("unable to verify '%s': client did not provide certificate",
2872 conn->remote_name);
2873 return -1;
2874 }
2875
2876 /* Check the DNS SANs if configured. */
2877 if (tls_opts & TLS_OPT_VERIFY_CERT_FQDN) {
2878 int matched;
2879
2880 matched = tls_cert_match_dns_san(conn->pool, cert, conn->remote_name);
2881 if (matched == 0) {
2882 tls_log("client cert dNSName SANs do not match remote name '%s'",
2883 conn->remote_name);
2884 return -1;
2885
2886 } else {
2887 tls_log("client cert dNSName SAN matches remote name '%s'",
2888 conn->remote_name);
2889 have_dns_ext = TRUE;
2890 ok = 1;
2891 }
2892 }
2893
2894 /* Check the IP SANs, if configured. */
2895 if (tls_opts & TLS_OPT_VERIFY_CERT_IP_ADDR) {
2896 int matched;
2897
2898 matched = tls_cert_match_ip_san(conn->pool, cert,
2899 pr_netaddr_get_ipstr(conn->remote_addr));
2900 if (matched == 0) {
2901 tls_log("client cert iPAddress SANs do not match client IP '%s'",
2902 pr_netaddr_get_ipstr(conn->remote_addr));
2903 return -1;
2904
2905 } else {
2906 tls_log("client cert iPAddress SAN matches client IP '%s'",
2907 pr_netaddr_get_ipstr(conn->remote_addr));
2908 have_ipaddr_ext = TRUE;
2909 ok = 1;
2910 }
2911 }
2912
2913 /* Check the CN (Common Name) if configured. */
2914 if (tls_opts & TLS_OPT_VERIFY_CERT_CN) {
2915 int matched;
2916
2917 matched = tls_cert_match_cn(conn->pool, cert, conn->remote_name, TRUE);
2918 if (matched == 0) {
2919 tls_log("client cert CommonName does not match client FQDN '%s'",
2920 conn->remote_name);
2921 return -1;
2922
2923 } else {
2924 tls_log("client cert CommonName matches client FQDN '%s'",
2925 conn->remote_name);
2926 have_cn = TRUE;
2927 ok = 1;
2928 }
2929 }
2930
2931 if ((tls_opts & TLS_OPT_VERIFY_CERT_CN) &&
2932 !have_cn) {
2933 tls_log("%s", "client cert missing required X509v3 CommonName");
2934 }
2935
2936 if ((tls_opts & TLS_OPT_VERIFY_CERT_FQDN) &&
2937 !have_dns_ext) {
2938 tls_log("%s", "client cert missing required X509v3 SubjectAltName dNSName");
2939 }
2940
2941 if ((tls_opts & TLS_OPT_VERIFY_CERT_IP_ADDR) &&
2942 !have_ipaddr_ext) {
2943 tls_log("%s", "client cert missing required X509v3 SubjectAltName iPAddress");
2944 }
2945
2946 X509_free(cert);
2947 return ok;
2948 }
2949
2950 static int tls_check_server_cert(SSL *ssl, conn_t *conn) {
2951 X509 *cert = NULL;
2952 int ok = -1;
2953 long verify_result;
2954
2955 /* Only perform these more stringent checks if asked to verify servers. */
2956 if (!(tls_flags & TLS_SESS_VERIFY_SERVER) &&
2957 !(tls_flags & TLS_SESS_VERIFY_SERVER_NO_DNS)) {
2958 return 0;
2959 }
2960
2961 /* Check SSL_get_verify_result */
2962 verify_result = SSL_get_verify_result(ssl);
2963 if (verify_result != X509_V_OK) {
2964 tls_log("unable to verify '%s' server certificate: %s",
2965 conn->remote_name, X509_verify_cert_error_string(verify_result));
2966 return -1;
2967 }
2968
2969 cert = SSL_get_peer_certificate(ssl);
2970 if (cert == NULL) {
2971 /* This can be null in the case where some anonymous (insecure)
2972 * cipher suite was used.
2973 */
2974 tls_log("unable to verify '%s': server did not provide certificate",
2975 conn->remote_name);
2976 return -1;
2977 }
2978
2979 /* XXX If using OpenSSL-1.0.2/1.1.0, we might be able to use:
2980 * X509_match_host() and X509_match_ip()/X509_match_ip_asc().
2981 */
2982
2983 ok = tls_cert_match_ip_san(conn->pool, cert,
2984 pr_netaddr_get_ipstr(conn->remote_addr));
2985 if (ok == 0) {
2986 ok = tls_cert_match_cn(conn->pool, cert,
2987 pr_netaddr_get_ipstr(conn->remote_addr), FALSE);
2988 }
2989
2990 if (ok == 0 &&
2991 !(tls_flags & TLS_SESS_VERIFY_SERVER_NO_DNS)) {
2992 int reverse_dns;
2993 const char *remote_name;
2994 pr_netaddr_t *remote_addr;
2995
2996 reverse_dns = pr_netaddr_set_reverse_dns(TRUE);
2997
2998 pr_netaddr_clear_ipcache(pr_netaddr_get_ipstr(conn->remote_addr));
2999
3000 remote_addr = (pr_netaddr_t *) conn->remote_addr;
3001 remote_addr->na_have_dnsstr = FALSE;
3002
3003 remote_name = pr_netaddr_get_dnsstr(conn->remote_addr);
3004 pr_netaddr_set_reverse_dns(reverse_dns);
3005
3006 ok = tls_cert_match_dns_san(conn->pool, cert, remote_name);
3007 if (ok == 0) {
3008 ok = tls_cert_match_cn(conn->pool, cert, remote_name, TRUE);
3009 }
3010 }
3011
3012 X509_free(cert);
3013 return ok;
3014 }
3015
3016 struct tls_pkey_data {
3017 server_rec *s;
3018 int flags;
3019 char *buf;
3020 size_t buflen, bufsz;
3021 const char *prompt;
3022 };
3023
3024 static void tls_prepare_provider_fds(int stdout_fd, int stderr_fd) {
3025 unsigned long nfiles = 0;
3026 register unsigned int i = 0;
3027 struct rlimit rlim;
3028
3029 if (stdout_fd != STDOUT_FILENO) {
3030 if (dup2(stdout_fd, STDOUT_FILENO) < 0)
3031 tls_log("error duping fd %d to stdout: %s", stdout_fd, strerror(errno));
3032
3033 close(stdout_fd);
3034 }
3035
3036 if (stderr_fd != STDERR_FILENO) {
3037 if (dup2(stderr_fd, STDERR_FILENO) < 0)
3038 tls_log("error duping fd %d to stderr: %s", stderr_fd, strerror(errno));
3039
3040 close(stderr_fd);
3041 }
3042
3043 /* Make sure not to pass on open file descriptors. For stdout and stderr,
3044 * we dup some pipes, so that we can capture what the command may write
3045 * to stdout or stderr. The stderr output will be logged to the TLSLog.
3046 *
3047 * First, use getrlimit() to obtain the maximum number of open files
3048 * for this process -- then close that number.
3049 */
3050 #if defined(RLIMIT_NOFILE) || defined(RLIMIT_OFILE)
3051 # if defined(RLIMIT_NOFILE)
3052 if (getrlimit(RLIMIT_NOFILE, &rlim) < 0) {
3053 # elif defined(RLIMIT_OFILE)
3054 if (getrlimit(RLIMIT_OFILE, &rlim) < 0) {
3055 # endif
3056 /* Ignore ENOSYS (and EPERM, since some libc's use this as ENOSYS). */
3057 if (errno != ENOSYS &&
3058 errno != EPERM) {
3059 tls_log("getrlimit error: %s", strerror(errno));
3060 }
3061
3062 /* Pick some arbitrary high number. */
3063 nfiles = 255;
3064
3065 } else
3066 nfiles = (unsigned long) rlim.rlim_max;
3067 #else /* no RLIMIT_NOFILE or RLIMIT_OFILE */
3068 nfiles = 255;
3069 #endif
3070
3071 if (nfiles > 255) {
3072 nfiles = 255;
3073 }
3074
3075 /* Close the "non-standard" file descriptors. */
3076 for (i = 3; i < nfiles; i++) {
3077 (void) close(i);
3078 }
3079
3080 return;
3081 }
3082
3083 static void tls_prepare_provider_pipes(int *stdout_pipe, int *stderr_pipe) {
3084 if (pipe(stdout_pipe) < 0) {
3085 pr_trace_msg(trace_channel, 2, "error opening stdout pipe: %s",
3086 strerror(errno));
3087 stdout_pipe[0] = -1;
3088 stdout_pipe[1] = STDOUT_FILENO;
3089
3090 } else {
3091 if (fcntl(stdout_pipe[0], F_SETFD, FD_CLOEXEC) < 0) {
3092 pr_trace_msg(trace_channel, 2,
3093 "error setting close-on-exec flag on stdout pipe read fd: %s",
3094 strerror(errno));
3095 }
3096
3097 if (fcntl(stdout_pipe[1], F_SETFD, 0) < 0) {
3098 pr_trace_msg(trace_channel, 2,
3099 "error setting close-on-exec flag on stdout pipe write fd: %s",
3100 strerror(errno));
3101 }
3102 }
3103
3104 if (pipe(stderr_pipe) < 0) {
3105 pr_trace_msg(trace_channel, 2, "error opening stderr pipe: %s",
3106 strerror(errno));
3107 stderr_pipe[0] = -1;
3108 stderr_pipe[1] = STDERR_FILENO;
3109
3110 } else {
3111 if (fcntl(stderr_pipe[0], F_SETFD, FD_CLOEXEC) < 0) {
3112 pr_trace_msg(trace_channel, 2,
3113 "error setting close-on-exec flag on stderr pipe read fd: %s",
3114 strerror(errno));
3115 }
3116
3117 if (fcntl(stderr_pipe[1], F_SETFD, 0) < 0) {
3118 pr_trace_msg(trace_channel, 2,
3119 "error setting close-on-exec flag on stderr pipe write fd: %s",
3120 strerror(errno));
3121 }
3122 }
3123 }
3124
3125 static int tls_exec_passphrase_provider(server_rec *s, char *buf, int buflen,
3126 int flags) {
3127 pid_t pid;
3128 int status;
3129 int stdout_pipe[2], stderr_pipe[2];
3130
3131 struct sigaction sa_ignore, sa_intr, sa_quit;
3132 sigset_t set_chldmask, set_save;
3133
3134 /* Prepare signal dispositions. */
3135 sa_ignore.sa_handler = SIG_IGN;
3136 sigemptyset(&sa_ignore.sa_mask);
3137 sa_ignore.sa_flags = 0;
3138
3139 if (sigaction(SIGINT, &sa_ignore, &sa_intr) < 0) {
3140 return -1;
3141 }
3142
3143 if (sigaction(SIGQUIT, &sa_ignore, &sa_quit) < 0) {
3144 return -1;
3145 }
3146
3147 sigemptyset(&set_chldmask);
3148 sigaddset(&set_chldmask, SIGCHLD);
3149
3150 if (sigprocmask(SIG_BLOCK, &set_chldmask, &set_save) < 0) {
3151 return -1;
3152 }
3153
3154 tls_prepare_provider_pipes(stdout_pipe, stderr_pipe);
3155
3156 pid = fork();
3157 if (pid < 0) {
3158 int xerrno = errno;
3159
3160 pr_log_pri(PR_LOG_ALERT,
3161 MOD_TLS_VERSION ": error: unable to fork: %s", strerror(xerrno));
3162
3163 errno = xerrno;
3164 status = -1;
3165
3166 } else if (pid == 0) {
3167 char nbuf[32];
3168 pool *tmp_pool;
3169 char *stdin_argv[4];
3170
3171 /* Child process */
3172 session.pid = getpid();
3173
3174 /* Note: there is no need to clean up this temporary pool, as we've
3175 * forked. If the exec call succeeds, this child process will exit
3176 * normally, and its process space recovered by the OS. If the exec
3177 * call fails, we still exit, and the process space is recovered by
3178 * the OS. Either way, the memory will be cleaned up without need for
3179 * us to do it explicitly (unless one wanted to be pedantic about it,
3180 * of course).
3181 */
3182 tmp_pool = make_sub_pool(s->pool);
3183
3184 /* Restore previous signal actions. */
3185 sigaction(SIGINT, &sa_intr, NULL);
3186 sigaction(SIGQUIT, &sa_quit, NULL);
3187 sigprocmask(SIG_SETMASK, &set_save, NULL);
3188
3189 stdin_argv[0] = pstrdup(tmp_pool, tls_passphrase_provider);
3190
3191 memset(nbuf, '\0', sizeof(nbuf));
3192 pr_snprintf(nbuf, sizeof(nbuf)-1, "%u", (unsigned int) s->ServerPort);
3193 nbuf[sizeof(nbuf)-1] = '\0';
3194 stdin_argv[1] = pstrcat(tmp_pool, s->ServerName, ":", nbuf, NULL);
3195
3196 if (flags & TLS_PASSPHRASE_FL_RSA_KEY) {
3197 stdin_argv[2] = pstrdup(tmp_pool, "RSA");
3198
3199 } else if (flags & TLS_PASSPHRASE_FL_DSA_KEY) {
3200 stdin_argv[2] = pstrdup(tmp_pool, "DSA");
3201
3202 } else if (flags & TLS_PASSPHRASE_FL_EC_KEY) {
3203 stdin_argv[2] = pstrdup(tmp_pool, "EC");
3204
3205 } else if (flags & TLS_PASSPHRASE_FL_PKCS12_PASSWD) {
3206 stdin_argv[2] = pstrdup(tmp_pool, "PKCS12");
3207 }
3208
3209 stdin_argv[3] = NULL;
3210
3211 PRIVS_ROOT
3212
3213 pr_trace_msg(trace_channel, 17,
3214 "executing '%s' with uid %lu (euid %lu), gid %lu (egid %lu)",
3215 tls_passphrase_provider,
3216 (unsigned long) getuid(), (unsigned long) geteuid(),
3217 (unsigned long) getgid(), (unsigned long) getegid());
3218
3219 pr_log_debug(DEBUG6, MOD_TLS_VERSION
3220 ": executing '%s' with uid %lu (euid %lu), gid %lu (egid %lu)",
3221 tls_passphrase_provider,
3222 (unsigned long) getuid(), (unsigned long) geteuid(),
3223 (unsigned long) getgid(), (unsigned long) getegid());
3224
3225 /* Prepare the file descriptors that the process will inherit. */
3226 tls_prepare_provider_fds(stdout_pipe[1], stderr_pipe[1]);
3227
3228 errno = 0;
3229 execv(tls_passphrase_provider, stdin_argv);
3230
3231 /* Since all previous file descriptors (including those for log files)
3232 * have been closed, and root privs have been revoked, there's little
3233 * chance of directing a message of execv() failure to proftpd's log
3234 * files. execv() only returns if there's an error; the only way we
3235 * can signal this to the waiting parent process is to exit with a
3236 * non-zero value (the value of errno will do nicely).
3237 */
3238
3239 exit(errno);
3240
3241 } else {
3242 int res;
3243 int maxfd, fds, send_sigterm = 1;
3244 fd_set readfds;
3245 time_t start_time = time(NULL);
3246 struct timeval tv;
3247
3248 /* Parent process */
3249
3250 close(stdout_pipe[1]);
3251 close(stderr_pipe[1]);
3252
3253 maxfd = (stderr_pipe[0] > stdout_pipe[0]) ?
3254 stderr_pipe[0] : stdout_pipe[0];
3255
3256 res = waitpid(pid, &status, WNOHANG);
3257 while (res <= 0) {
3258 if (res < 0) {
3259 if (errno != EINTR) {
3260 pr_trace_msg(trace_channel, 2,
3261 "passphrase provider error: unable to wait for pid %u: %s",
3262 (unsigned int) pid, strerror(errno));
3263 status = -1;
3264 break;
3265
3266 } else {
3267 pr_signals_handle();
3268 }
3269 }
3270
3271 /* Check the time elapsed since we started. */
3272 if ((time(NULL) - start_time) > TLS_PASSPHRASE_TIMEOUT) {
3273
3274 /* Send TERM, the first time, to be polite. */
3275 if (send_sigterm) {
3276 send_sigterm = 0;
3277 pr_log_debug(DEBUG6, MOD_TLS_VERSION
3278 ": '%s' has exceeded the timeout (%lu seconds), sending "
3279 "SIGTERM (signal %d)", tls_passphrase_provider,
3280 (unsigned long) TLS_PASSPHRASE_TIMEOUT, SIGTERM);
3281 kill(pid, SIGTERM);
3282
3283 } else {
3284 /* The child is still around? Terminate with extreme prejudice. */
3285 pr_log_debug(DEBUG6, MOD_TLS_VERSION
3286 ": '%s' has exceeded the timeout (%lu seconds), sending "
3287 "SIGKILL (signal %d)", tls_passphrase_provider,
3288 (unsigned long) TLS_PASSPHRASE_TIMEOUT, SIGKILL);
3289 kill(pid, SIGKILL);
3290 }
3291 }
3292
3293 /* Select on the pipe read fds, to see if the child has anything
3294 * to tell us.
3295 */
3296 FD_ZERO(&readfds);
3297
3298 FD_SET(stdout_pipe[0], &readfds);
3299 FD_SET(stderr_pipe[0], &readfds);
3300
3301 /* Note: this delay should be configurable somehow. */
3302 tv.tv_sec = 2L;
3303 tv.tv_usec = 0L;
3304
3305 fds = select(maxfd + 1, &readfds, NULL, NULL, &tv);
3306
3307 if (fds == -1 &&
3308 errno == EINTR) {
3309 pr_signals_handle();
3310 }
3311
3312 if (fds > 0) {
3313 /* The child sent us something. How thoughtful. */
3314
3315 if (FD_ISSET(stdout_pipe[0], &readfds)) {
3316 res = read(stdout_pipe[0], buf, buflen);
3317 if (res > 0) {
3318 buf[buflen-1] = '\0';
3319
3320 while (res &&
3321 (buf[res-1] == '\r' ||
3322 buf[res-1] == '\n')) {
3323 pr_signals_handle();
3324 res--;
3325 }
3326 buf[res] = '\0';
3327
3328 pr_trace_msg(trace_channel, 18, "read passphrase from '%s'",
3329 tls_passphrase_provider);
3330
3331 } else if (res < 0) {
3332 int xerrno = errno;
3333
3334 pr_trace_msg(trace_channel, 3,
3335 "error reading stdout from '%s': %s",
3336 tls_passphrase_provider, strerror(xerrno));
3337
3338 pr_log_debug(DEBUG2, MOD_TLS_VERSION
3339 ": error reading stdout from '%s': %s",
3340 tls_passphrase_provider, strerror(xerrno));
3341 }
3342 }
3343
3344 if (FD_ISSET(stderr_pipe[0], &readfds)) {
3345 long stderrlen, stderrsz;
3346 char *stderrbuf;
3347 pool *tmp_pool = make_sub_pool(s->pool);
3348
3349 stderrbuf = pr_fsio_getpipebuf(tmp_pool, stderr_pipe[0], &stderrsz);
3350 memset(stderrbuf, '\0', stderrsz);
3351
3352 stderrlen = read(stderr_pipe[0], stderrbuf, stderrsz-1);
3353 if (stderrlen > 0) {
3354 while (stderrlen &&
3355 (stderrbuf[stderrlen-1] == '\r' ||
3356 stderrbuf[stderrlen-1] == '\n')) {
3357 stderrlen--;
3358 }
3359 stderrbuf[stderrlen] = '\0';
3360
3361 pr_trace_msg(trace_channel, 5,
3362 "stderr from '%s': %s", tls_passphrase_provider,
3363 stderrbuf);
3364
3365 pr_log_debug(DEBUG5, MOD_TLS_VERSION
3366 ": stderr from '%s': %s", tls_passphrase_provider,
3367 stderrbuf);
3368
3369 } else if (res < 0) {
3370 int xerrno = errno;
3371
3372 pr_trace_msg(trace_channel, 2,
3373 "error reading stderr from '%s': %s",
3374 tls_passphrase_provider, strerror(xerrno));
3375
3376 pr_log_debug(DEBUG2, MOD_TLS_VERSION
3377 ": error reading stderr from '%s': %s",
3378 tls_passphrase_provider, strerror(xerrno));
3379 }
3380
3381 destroy_pool(tmp_pool);
3382 tmp_pool = NULL;
3383 }
3384 }
3385
3386 res = waitpid(pid, &status, WNOHANG);
3387 }
3388 }
3389
3390 /* Restore the previous signal actions. */
3391 if (sigaction(SIGINT, &sa_intr, NULL) < 0) {
3392 return -1;
3393 }
3394
3395 if (sigaction(SIGQUIT, &sa_quit, NULL) < 0) {
3396 return -1;
3397 }
3398
3399 if (sigprocmask(SIG_SETMASK, &set_save, NULL) < 0) {
3400 return -1;
3401 }
3402
3403 if (WIFSIGNALED(status)) {
3404 pr_log_debug(DEBUG2, MOD_TLS_VERSION
3405 ": '%s' died from signal %d", tls_passphrase_provider,
3406 WTERMSIG(status));
3407 errno = EPERM;
3408 return -1;
3409 }
3410
3411 return 0;
3412 }
3413
3414 static int tls_passphrase_cb(char *buf, int buflen, int rwflag, void *d) {
3415 static int need_banner = TRUE;
3416 struct tls_pkey_data *pdata = d;
3417
3418 if (tls_passphrase_provider == NULL) {
3419 register unsigned int attempt;
3420 int pwlen = 0;
3421
3422 tls_log("requesting passphrase from admin");
3423
3424 /* Similar to Apache's mod_ssl, we want to be nice, and display an
3425 * informative message to the proftpd admin, telling them for what
3426 * server they are being requested to provide a passphrase.
3427 */
3428
3429 if (need_banner) {
3430 fprintf(stderr, "\nPlease provide passphrases for these encrypted certificate keys:\n");
3431 need_banner = FALSE;
3432 }
3433
3434 /* You get three attempts at entering the passphrase correctly. */
3435 for (attempt = 0; attempt < 3; attempt++) {
3436 int res;
3437
3438 /* Always handle signals in a loop. */
3439 pr_signals_handle();
3440
3441 res = EVP_read_pw_string(buf, buflen, pdata->prompt, TRUE);
3442
3443 /* A return value of zero from EVP_read_pw_string() means success; -1
3444 * means a system error occurred, and 1 means user interaction problems.
3445 */
3446 if (res != 0) {
3447 fprintf(stderr, "\nPassphrases do not match. Please try again.\n");
3448 continue;
3449 }
3450
3451 /* Ensure that the buffer is NUL-terminated. */
3452 buf[buflen-1] = '\0';
3453 pwlen = strlen(buf);
3454 if (pwlen < 1) {
3455 fprintf(stderr, "Error: passphrase must be at least one character\n");
3456
3457 } else {
3458 sstrncpy(pdata->buf, buf, pdata->bufsz);
3459 pdata->buflen = pwlen;
3460
3461 return pwlen;
3462 }
3463 }
3464
3465 } else {
3466 tls_log("requesting passphrase from '%s'", tls_passphrase_provider);
3467
3468 if (tls_exec_passphrase_provider(pdata->s, buf, buflen, pdata->flags) < 0) {
3469 tls_log("error obtaining passphrase from '%s': %s",
3470 tls_passphrase_provider, strerror(errno));
3471
3472 } else {
3473 /* Ensure that the buffer is NUL-terminated. */
3474 buf[buflen-1] = '\0';
3475
3476 sstrncpy(pdata->buf, buf, pdata->bufsz);
3477 pdata->buflen = strlen(buf);
3478
3479 return pdata->buflen;
3480 }
3481 }
3482
3483 #if OPENSSL_VERSION_NUMBER < 0x00908001
3484 PEMerr(PEM_F_DEF_CALLBACK, PEM_R_PROBLEMS_GETTING_PASSWORD);
3485 #else
3486 PEMerr(PEM_F_PEM_DEF_CALLBACK, PEM_R_PROBLEMS_GETTING_PASSWORD);
3487 #endif
3488
3489 pr_memscrub(buf, buflen);
3490 return -1;
3491 }
3492
3493 static int prompt_fd = -1;
3494
3495 static void set_prompt_fds(void) {
3496
3497 /* Reconnect stderr to the term because proftpd connects stderr, earlier,
3498 * to the general stderr logfile.
3499 */
3500 prompt_fd = open("/dev/null", O_WRONLY);
3501 if (prompt_fd == -1) {
3502 /* This is an arbitrary, meaningless placeholder number. */
3503 prompt_fd = 76;
3504 }
3505
3506 dup2(STDERR_FILENO, prompt_fd);
3507 dup2(STDOUT_FILENO, STDERR_FILENO);
3508 }
3509
3510 static void restore_prompt_fds(void) {
3511 dup2(prompt_fd, STDERR_FILENO);
3512 close(prompt_fd);
3513 prompt_fd = -1;
3514 }
3515
3516 static int tls_get_pkcs12_passwd(server_rec *s, FILE *fp, const char *prompt,
3517 char *buf, size_t bufsz, int flags, struct tls_pkey_data *pdata) {
3518 EVP_PKEY *pkey = NULL;
3519 X509 *cert = NULL;
3520 PKCS12 *p12 = NULL;
3521 char *passwd = NULL;
3522 int res, ok = FALSE;
3523
3524 p12 = d2i_PKCS12_fp(fp, NULL);
3525 if (p12 != NULL) {
3526
3527 /* Check if a password is needed. */
3528 res = PKCS12_verify_mac(p12, NULL, 0);
3529 if (res == 1) {
3530 passwd = NULL;
3531
3532 } else if (res == 0) {
3533 res = PKCS12_verify_mac(p12, "", 0);
3534 if (res == 1) {
3535 passwd = "";
3536 }
3537 }
3538
3539 if (res == 0) {
3540 register unsigned int attempt;
3541
3542 /* This PKCS12 file is password-protected; need to get the password
3543 * from the admin.
3544 */
3545 for (attempt = 0; attempt < 3; attempt++) {
3546 int len = -1;
3547
3548 /* Always handle signals in a loop. */
3549 pr_signals_handle();
3550
3551 /* Clear the error queue at the start of the loop. */
3552 ERR_clear_error();
3553
3554 len = tls_passphrase_cb(buf, bufsz, 0, pdata);
3555 if (len > 0) {
3556 res = PKCS12_verify_mac(p12, buf, -1);
3557 if (res == 1) {
3558 #if OPENSSL_VERSION_NUMBER >= 0x000905000L
3559 /* Use the obtained password as additional entropy, ostensibly
3560 * unknown to attackers who may be watching the network, for
3561 * OpenSSL's PRNG.
3562 *
3563 * Human language gives about 2-3 bits of entropy per byte
3564 * (as per RFC1750).
3565 */
3566 RAND_add(buf, pdata->buflen, pdata->buflen * 0.25);
3567 #endif
3568
3569 res = PKCS12_parse(p12, buf, &pkey, &cert, NULL);
3570 if (res != 1) {
3571 PKCS12_free(p12);
3572 return -1;
3573 }
3574
3575 ok = TRUE;
3576 break;
3577 }
3578 }
3579
3580 fprintf(stderr, "\nWrong password for this PKCS12 file. Please try again.\n");
3581 }
3582 } else {
3583 res = PKCS12_parse(p12, passwd, &pkey, &cert, NULL);
3584 if (res != 1) {
3585 PKCS12_free(p12);
3586 return -1;
3587 }
3588
3589 ok = TRUE;
3590 }
3591
3592 } else {
3593 fprintf(stderr, "\nUnable to read PKCS12 file.\n");
3594 return -1;
3595 }
3596
3597 /* Now we should have an EVP_PKEY (which may or may not need a passphrase),
3598 * and a cert. We don't really care about the cert right now. But we
3599 * DO need to get the passphrase for the private key. Do this by writing
3600 * the key to a BIO, then calling tls_get_passphrase() for that BIO.
3601 *
3602 * It looks like OpenSSL's pkcs12 command-line tool does not allow
3603 * passphrase-protected keys to be written into a PKCS12 structure;
3604 * the key is decrypted first (hence, probably, the password protection
3605 * for the entire PKCS12 structure). Can the same be assumed to be true
3606 * for PKCS12 files created via other applications?
3607 *
3608 * For now, assume yes, that all PKCS12 files will have private keys which
3609 * are not encrypted. If this is found to NOT be the case, then we
3610 * will need to write the obtained private key out to a BIO somehow,
3611 * then call tls_get_passphrase() on that BIO, rather than on a path.
3612 */
3613
3614 if (cert)
3615 X509_free(cert);
3616
3617 if (pkey)
3618 EVP_PKEY_free(pkey);
3619
3620 if (p12)
3621 PKCS12_free(p12);
3622
3623 if (!ok) {
3624 #if OPENSSL_VERSION_NUMBER < 0x00908001
3625 PEMerr(PEM_F_DEF_CALLBACK, PEM_R_PROBLEMS_GETTING_PASSWORD);
3626 #else
3627 PEMerr(PEM_F_PEM_DEF_CALLBACK, PEM_R_PROBLEMS_GETTING_PASSWORD);
3628 #endif
3629 return -1;
3630 }
3631
3632 ERR_clear_error();
3633 return res;
3634 }
3635
3636 static int tls_get_passphrase(server_rec *s, const char *path,
3637 const char *prompt, char *buf, size_t bufsz, int flags) {
3638 FILE *keyf = NULL;
3639 EVP_PKEY *pkey = NULL;
3640 struct tls_pkey_data pdata;
3641 register unsigned int attempt;
3642
3643 if (path) {
3644 int fd, res, xerrno;
3645
3646 /* Open an fp on the cert file. */
3647 PRIVS_ROOT
3648 fd = open(path, O_RDONLY);
3649 xerrno = errno;
3650 PRIVS_RELINQUISH
3651
3652 if (fd < 0) {
3653 SYSerr(SYS_F_FOPEN, xerrno);
3654 return -1;
3655 }
3656
3657 /* Make sure the fd isn't one of the big three. */
3658 if (fd <= STDERR_FILENO) {
3659 res = pr_fs_get_usable_fd(fd);
3660 if (res >= 0) {
3661 close(fd);
3662 fd = res;
3663 }
3664 }
3665
3666 keyf = fdopen(fd, "r");
3667 if (keyf == NULL) {
3668 xerrno = errno;
3669
3670 (void) close(fd);
3671 SYSerr(SYS_F_FOPEN, xerrno);
3672 return -1;
3673 }
3674
3675 /* As the file contains sensitive data, we do not want it lingering
3676 * around in stdio buffers.
3677 */
3678 (void) setvbuf(keyf, NULL, _IONBF, 0);
3679 }
3680
3681 pdata.s = s;
3682 pdata.flags = flags;
3683 pdata.buf = buf;
3684 pdata.buflen = 0;
3685 pdata.bufsz = bufsz;
3686 pdata.prompt = prompt;
3687
3688 set_prompt_fds();
3689
3690 if (flags & TLS_PASSPHRASE_FL_PKCS12_PASSWD) {
3691 int res;
3692
3693 res = tls_get_pkcs12_passwd(s, keyf, prompt, buf, bufsz, flags, &pdata);
3694
3695 if (keyf != NULL) {
3696 fclose(keyf);
3697 keyf = NULL;
3698 }
3699
3700 /* Restore the normal stderr logging. */
3701 restore_prompt_fds();
3702
3703 return res;
3704 }
3705
3706 /* The user gets three tries to enter the correct passphrase. */
3707 for (attempt = 0; attempt < 3; attempt++) {
3708
3709 /* Always handle signals in a loop. */
3710 pr_signals_handle();
3711
3712 /* Clear the error queue at the start of the loop. */
3713 ERR_clear_error();
3714
3715 pkey = PEM_read_PrivateKey(keyf, NULL, tls_passphrase_cb, &pdata);
3716 if (pkey != NULL) {
3717 break;
3718 }
3719
3720 if (keyf != NULL) {
3721 fseek(keyf, 0, SEEK_SET);
3722 }
3723
3724 fprintf(stderr, "\nWrong passphrase for this key. Please try again.\n");
3725 }
3726
3727 if (keyf != NULL) {
3728 fclose(keyf);
3729 keyf = NULL;
3730 }
3731
3732 /* Restore the normal stderr logging. */
3733 restore_prompt_fds();
3734
3735 if (pkey == NULL) {
3736 return -1;
3737 }
3738
3739 EVP_PKEY_free(pkey);
3740
3741 if (pdata.buflen > 0) {
3742 #if OPENSSL_VERSION_NUMBER >= 0x000905000L
3743 /* Use the obtained passphrase as additional entropy, ostensibly
3744 * unknown to attackers who may be watching the network, for
3745 * OpenSSL's PRNG.
3746 *
3747 * Human language gives about 2-3 bits of entropy per byte (RFC1750).
3748 */
3749 RAND_add(buf, pdata.buflen, pdata.buflen * 0.25);
3750 #endif
3751
3752 #ifdef HAVE_MLOCK
3753 PRIVS_ROOT
3754 if (mlock(buf, bufsz) < 0) {
3755 pr_log_debug(DEBUG1, MOD_TLS_VERSION
3756 ": error locking passphrase into memory: %s", strerror(errno));
3757
3758 } else {
3759 pr_log_debug(DEBUG1, MOD_TLS_VERSION ": passphrase locked into memory");
3760 }
3761 PRIVS_RELINQUISH
3762 #endif
3763 }
3764
3765 return pdata.buflen;
3766 }
3767
3768 static int tls_handshake_timeout_cb(CALLBACK_FRAME) {
3769 tls_handshake_timed_out = TRUE;
3770 return 0;
3771 }
3772
3773 static void tls_scrub_pkey(tls_pkey_t *k) {
3774 if (k->rsa_pkey != NULL) {
3775 pr_memscrub(k->rsa_pkey, k->pkeysz);
3776 free(k->rsa_pkey_ptr);
3777 k->rsa_pkey = k->rsa_pkey_ptr = NULL;
3778 k->rsa_passlen = 0;
3779 }
3780
3781 if (k->dsa_pkey != NULL) {
3782 pr_memscrub(k->dsa_pkey, k->pkeysz);
3783 free(k->dsa_pkey_ptr);
3784 k->dsa_pkey = k->dsa_pkey_ptr = NULL;
3785 k->dsa_passlen = 0;
3786 }
3787
3788 #ifdef PR_USE_OPENSSL_ECC
3789 if (k->ec_pkey != NULL) {
3790 pr_memscrub(k->ec_pkey, k->pkeysz);
3791 free(k->ec_pkey_ptr);
3792 k->ec_pkey = k->ec_pkey_ptr = NULL;
3793 k->ec_passlen = 0;
3794 }
3795 #endif /* PR_USE_OPENSSL_ECC */
3796
3797 if (k->pkcs12_passwd != NULL) {
3798 pr_memscrub(k->pkcs12_passwd, k->pkeysz);
3799 free(k->pkcs12_passwd_ptr);
3800 k->pkcs12_passwd = k->pkcs12_passwd_ptr = NULL;
3801 k->pkcs12_passlen = 0;
3802 }
3803
3804 if (k->path != NULL) {
3805 free((void *) k->path);
3806 k->path = NULL;
3807 }
3808
3809 k->next = NULL;
3810 k->sid = 0;
3811 }
3812
3813 static tls_pkey_t *tls_lookup_pkey(server_rec *s, int lock_if_found,
3814 int scrub_unless_match) {
3815 tls_pkey_t *k, *knext, *pkey = NULL;
3816
3817 for (k = tls_pkey_list; k; k = knext) {
3818 pr_signals_handle();
3819
3820 knext = k->next;
3821
3822 if (k->sid != s->sid) {
3823 if (scrub_unless_match) {
3824 /* Scrub the passphrase's memory areas. */
3825 tls_scrub_pkey(k);
3826 }
3827
3828 continue;
3829 }
3830
3831 pkey = k;
3832
3833 if (lock_if_found) {
3834 #ifdef HAVE_MLOCK
3835 /* mlock() the passphrase memory areas again; page locks are not
3836 * inherited across forks.
3837 */
3838 PRIVS_ROOT
3839 if (k->rsa_pkey != NULL &&
3840 k->rsa_passlen > 0) {
3841 if (mlock(k->rsa_pkey, k->pkeysz) < 0) {
3842 tls_log("error locking passphrase into memory: %s", strerror(errno));
3843 }
3844 }
3845
3846 if (k->dsa_pkey != NULL &&
3847 k->dsa_passlen > 0) {
3848 if (mlock(k->dsa_pkey, k->pkeysz) < 0) {
3849 tls_log("error locking passphrase into memory: %s", strerror(errno));
3850 }
3851 }
3852
3853 # ifdef PR_USE_OPENSSL_ECC
3854 if (k->ec_pkey != NULL &&
3855 k->ec_passlen > 0) {
3856 if (mlock(k->ec_pkey, k->pkeysz) < 0) {
3857 tls_log("error locking passphrase into memory: %s", strerror(errno));
3858 }
3859 }
3860 # endif /* PR_USE_OPENSSL_ECC */
3861
3862 if (k->pkcs12_passwd != NULL &&
3863 k->pkcs12_passlen > 0) {
3864 if (mlock(k->pkcs12_passwd, k->pkeysz) < 0) {
3865 tls_log("error locking password into memory: %s", strerror(errno));
3866 }
3867 }
3868 PRIVS_RELINQUISH
3869 #endif /* HAVE_MLOCK */
3870 }
3871
3872 break;
3873 }
3874
3875 return pkey;
3876 }
3877
3878 static int tls_pkey_cb(char *buf, int buflen, int rwflag, void *data) {
3879 tls_pkey_t *k;
3880
3881 if (data == NULL) {
3882 return 0;
3883 }
3884
3885 k = (tls_pkey_t *) data;
3886
3887 if ((k->flags & TLS_PKEY_USE_RSA) && k->rsa_pkey) {
3888 sstrncpy(buf, k->rsa_pkey, buflen);
3889 buf[buflen - 1] = '\0';
3890 return strlen(buf);
3891 }
3892
3893 if ((k->flags & TLS_PKEY_USE_DSA) && k->dsa_pkey) {
3894 sstrncpy(buf, k->dsa_pkey, buflen);
3895 buf[buflen - 1] = '\0';
3896 return strlen(buf);
3897 }
3898
3899 #ifdef PR_USE_OPENSSL_ECC
3900 if ((k->flags & TLS_PKEY_USE_EC) && k->ec_pkey) {
3901 sstrncpy(buf, k->ec_pkey, buflen);
3902 buf[buflen - 1] = '\0';
3903 return strlen(buf);
3904 }
3905 #endif /* PR_USE_OPENSSL_ECC */
3906
3907 return 0;
3908 }
3909
3910 static void tls_remove_pkey(tls_pkey_t *k) {
3911 if (tls_pkey_list != k) {
3912 tls_pkey_t *ki, *prev;
3913
3914 prev = tls_pkey_list;
3915 for (ki = tls_pkey_list->next; ki; ki = ki->next) {
3916 if (ki == k) {
3917 prev->next = k->next;
3918 break;
3919 }
3920
3921 prev = ki;
3922 }
3923
3924 } else {
3925 /* We are the head of the list. */
3926 tls_pkey_list = k->next;
3927 }
3928
3929 if (tls_npkeys > 0) {
3930 tls_npkeys--;
3931 }
3932 }
3933
3934 static void tls_scrub_pkeys(void) {
3935 tls_pkey_t *k, *knext;
3936 unsigned int passphrase_count = 0;
3937
3938 if (tls_pkey_list == NULL) {
3939 return;
3940 }
3941
3942 /* Scrub and free all passphrases in memory. */
3943 for (k = tls_pkey_list; k; k = k->next) {
3944 if (k->rsa_pkey != NULL &&
3945 k->rsa_passlen > 0) {
3946 passphrase_count++;
3947 }
3948
3949 if (k->dsa_pkey != NULL &&
3950 k->dsa_passlen > 0) {
3951 passphrase_count++;
3952 }
3953
3954 #ifdef PR_USE_OPENSSL_ECC
3955 if (k->ec_pkey != NULL &&
3956 k->ec_passlen > 0) {
3957 passphrase_count++;
3958 }
3959 #endif /* PR_USE_OPENSSL_ECC */
3960
3961 if (k->pkcs12_passwd != NULL &&
3962 k->pkcs12_passlen > 0) {
3963 passphrase_count++;
3964 }
3965 }
3966
3967 if (passphrase_count == 0) {
3968 tls_pkey_list = NULL;
3969 tls_npkeys = 0;
3970 return;
3971 }
3972
3973 pr_log_debug(DEBUG5, MOD_TLS_VERSION
3974 ": scrubbing %u %s from memory", passphrase_count,
3975 passphrase_count != 1 ? "passphrases" : "passphrase");
3976
3977 for (k = tls_pkey_list; k; k = knext) {
3978 knext = k->next;
3979
3980 pr_signals_handle();
3981 tls_scrub_pkey(k);
3982 }
3983
3984 tls_pkey_list = NULL;
3985 tls_npkeys = 0;
3986 }
3987
3988 static void tls_clean_pkeys(void) {
3989 register unsigned int i;
3990 tls_pkey_t *k;
3991 pool *tmp_pool;
3992 array_header *dead_keys, *valid_sids;
3993 server_rec *s;
3994
3995 /* We scan the tls_pkey_list for any keys belonging to vhosts (by SID) which
3996 * no longer appear in our configuration.
3997 */
3998
3999 if (tls_pkey_list == NULL) {
4000 return;
4001 }
4002
4003 tmp_pool = make_sub_pool(tls_pool);
4004 pr_pool_tag(tmp_pool, "TLS Passphrase Cleaning");
4005
4006 dead_keys = make_array(tmp_pool, 0, sizeof(tls_pkey_t *));
4007 valid_sids = make_array(tmp_pool, 0, sizeof(unsigned int));
4008
4009 for (s = (server_rec *) server_list->xas_list; s; s = s->next) {
4010 *((unsigned int *) push_array(valid_sids)) = s->sid;
4011 }
4012
4013 for (k = tls_pkey_list; k; k = k->next) {
4014 int dead_key = TRUE;
4015
4016 for (i = 0; i < valid_sids->nelts; i++) {
4017 unsigned int sid;
4018
4019 sid = ((unsigned int *) valid_sids->elts)[i];
4020 if (k->sid == sid) {
4021 dead_key = FALSE;
4022 break;
4023 }
4024 }
4025
4026 if (dead_key) {
4027 *((tls_pkey_t **) push_array(dead_keys)) = k;
4028 }
4029 }
4030
4031 for (i = 0; i < dead_keys->nelts; i++) {
4032 pr_signals_handle();
4033
4034 k = ((tls_pkey_t **) dead_keys->elts)[i];
4035 tls_remove_pkey(k);
4036 tls_scrub_pkey(k);
4037 destroy_pool(k->pool);
4038 }
4039
4040 destroy_pool(tmp_pool);
4041 return;
4042 }
4043
4044 #if OPENSSL_VERSION_NUMBER > 0x000907000L
4045 static int tls_renegotiate_timeout_cb(CALLBACK_FRAME) {
4046 if ((tls_flags & TLS_SESS_ON_CTRL) &&
4047 (tls_flags & TLS_SESS_CTRL_RENEGOTIATING)) {
4048 int ctrl_renegotiated = FALSE;
4049
4050 switch (SSL_version(ctrl_ssl)) {
4051 # if defined(TLS1_3_VERSION) && !defined(HAVE_LIBRESSL)
4052 case TLS1_3_VERSION:
4053 if (SSL_get_key_update_type(ctrl_ssl) == SSL_KEY_UPDATE_NONE) {
4054 ctrl_renegotiated = TRUE;
4055 }
4056 break;
4057 # endif /* TLS1_3_VERSION and no LibreSSL */
4058
4059 default:
4060 if (SSL_renegotiate_pending(ctrl_ssl) == 0) {
4061 ctrl_renegotiated = TRUE;
4062 }
4063 break;
4064 }
4065
4066 if (ctrl_renegotiated == TRUE) {
4067 tls_log("%s", "control channel TLS session renegotiated");
4068 tls_flags &= ~TLS_SESS_CTRL_RENEGOTIATING;
4069
4070 } else if (tls_renegotiate_required == TRUE) {
4071 tls_log("%s", "requested TLS renegotiation timed out on control channel");
4072 tls_log("%s", "shutting down control channel TLS session");
4073 tls_end_sess(ctrl_ssl, session.c, 0);
4074 pr_table_remove(tls_ctrl_rd_nstrm->notes, TLS_NETIO_NOTE, NULL);
4075 pr_table_remove(tls_ctrl_wr_nstrm->notes, TLS_NETIO_NOTE, NULL);
4076 ctrl_ssl = NULL;
4077 }
4078 }
4079
4080 if ((tls_flags & TLS_SESS_ON_DATA) &&
4081 (tls_flags & TLS_SESS_DATA_RENEGOTIATING)) {
4082 int data_renegotiated = FALSE;
4083 SSL *ssl;
4084
4085 ssl = (SSL *) pr_table_get(tls_data_wr_nstrm->notes, TLS_NETIO_NOTE, NULL);
4086 switch (SSL_version(ssl)) {
4087 # if defined(TLS1_3_VERSION) && !defined(HAVE_LIBRESSL)
4088 case TLS1_3_VERSION:
4089 if (SSL_get_key_update_type(ssl) == SSL_KEY_UPDATE_NONE) {
4090 data_renegotiated = TRUE;
4091 }
4092 break;
4093 # endif /* TLS1_3_VERSION and no LibreSSL */
4094
4095 default:
4096 if (SSL_renegotiate_pending(ssl) == 0) {
4097 data_renegotiated = TRUE;
4098 }
4099 break;
4100 }
4101
4102 if (data_renegotiated == TRUE) {
4103 tls_log("%s", "data channel TLS session renegotiated");
4104 tls_flags &= ~TLS_SESS_DATA_RENEGOTIATING;
4105 tls_data_renegotiate_current = 0;
4106
4107 } else if (tls_renegotiate_required == TRUE) {
4108 tls_log("%s", "requested TLS renegotiation timed out on data channel");
4109 tls_log("%s", "shutting down data channel TLS session");
4110 tls_end_sess(ssl, session.d, 0);
4111 pr_table_remove(tls_data_rd_nstrm->notes, TLS_NETIO_NOTE, NULL);
4112 pr_table_remove(tls_data_wr_nstrm->notes, TLS_NETIO_NOTE, NULL);
4113 }
4114 }
4115
4116 return 0;
4117 }
4118
4119 static int tls_ctrl_renegotiate_cb(CALLBACK_FRAME) {
4120 /* Guard against a timer firing as the SSL session is being torn down. */
4121 if (ctrl_ssl == NULL) {
4122 return 0;
4123 }
4124
4125 if (tls_flags & TLS_SESS_ON_CTRL) {
4126 switch (SSL_version(ctrl_ssl)) {
4127 #if defined(TLS1_3_VERSION) && !defined(HAVE_LIBRESSL)
4128 /* If we're a TLSv1.3 session, use SSL_key_update() to request new
4129 * session keys; TLSv1.3 does not support renegotiations.
4130 */
4131 case TLS1_3_VERSION: {
4132 if (SSL_get_key_update_type(ctrl_ssl) == SSL_KEY_UPDATE_NONE) {
4133 tls_flags |= TLS_SESS_CTRL_RENEGOTIATING;
4134
4135 tls_log("requesting TLS key updates on control channel "
4136 "(%lu sec renegotiation interval)", p1);
4137
4138 if (SSL_key_update(ctrl_ssl, SSL_KEY_UPDATE_REQUESTED) != 1) {
4139 tls_log("error requesting TLS key update on control channel: %s",
4140 tls_get_errors());
4141 }
4142
4143 } else {
4144 pr_trace_msg(trace_channel, 7,
4145 "TLS key update on control channel already in progress");
4146 }
4147 }
4148 break;
4149 #endif /* TLS1_3_VERSION and no LibreSSL */
4150
4151 default: {
4152 #if OPENSSL_VERSION_NUMBER >= 0x009080cfL
4153 /* In OpenSSL-0.9.8l and later, SSL session renegotiations
4154 * (both client- and server-initiated) are automatically disabled.
4155 * Unless the admin explicitly configured support for
4156 * client-initiated renegotiations via the AllowClientRenegotiations
4157 * TLSOption, we can't request renegotiations ourselves.
4158 */
4159 if (tls_opts & TLS_OPT_ALLOW_CLIENT_RENEGOTIATIONS) {
4160 #else
4161 if (TRUE) {
4162 #endif
4163 tls_flags |= TLS_SESS_CTRL_RENEGOTIATING;
4164
4165 tls_log("requesting TLS renegotiation on control channel "
4166 "(%lu sec renegotiation interval)", p1);
4167
4168 if (SSL_renegotiate(ctrl_ssl) != 1) {
4169 tls_log("error requesting TLS renegotiation on control channel: %s",
4170 tls_get_errors());
4171 }
4172 }
4173 }
4174 }
4175
4176 /* Restart the timer. */
4177 return 1;
4178 }
4179
4180 return 0;
4181 }
4182 #endif
4183
4184 static DH *tls_dh_cb(SSL *ssl, int is_export, int keylen) {
4185 DH *dh = NULL;
4186 EVP_PKEY *pkey;
4187 int pkeylen = 0, use_pkeylen = FALSE;
4188
4189 /* OpenSSL will only ever call us (currently) with a keylen of 512 or 1024;
4190 * see the SSL_EXPORT_PKEYLENGTH macro in ssl_locl.h. Sigh.
4191 *
4192 * Thus we adjust the DH parameter length according to the size of the
4193 * RSA/DSA private key used for the current connection.
4194 *
4195 * NOTE: This MAY cause interoperability issues with some clients, notably
4196 * Java 7 (and earlier) clients, since Java 7 and earlier supports
4197 * Diffie-Hellman only up to 1024 bits. More sighs. To deal with these
4198 * clients, then, you need to configure a certificate/key of 1024 bits.
4199 */
4200 pkey = SSL_get_privatekey(ssl);
4201 if (pkey != NULL) {
4202 if (get_pkey_type(pkey) == EVP_PKEY_RSA ||
4203 get_pkey_type(pkey) == EVP_PKEY_DSA) {
4204 pkeylen = EVP_PKEY_bits(pkey);
4205
4206 if (pkeylen < TLS_DH_MIN_LEN) {
4207 if (!(tls_opts & TLS_OPT_ALLOW_WEAK_DH)) {
4208 pr_trace_msg(trace_channel, 11,
4209 "certificate private key length %d less than %d bits, using %d "
4210 "(see AllowWeakDH TLSOption)", pkeylen, TLS_DH_MIN_LEN,
4211 TLS_DH_MIN_LEN);
4212 pkeylen = TLS_DH_MIN_LEN;
4213 }
4214 }
4215
4216 if (pkeylen != keylen) {
4217 pr_trace_msg(trace_channel, 13,
4218 "adjusted DH parameter length from %d to %d bits", keylen, pkeylen);
4219 use_pkeylen = TRUE;
4220 }
4221 }
4222 }
4223
4224 if (tls_tmp_dhs != NULL &&
4225 tls_tmp_dhs->nelts > 0) {
4226 register unsigned int i;
4227 DH *best_dh = NULL, **dhs;
4228 int best_dhlen = 0;
4229
4230 dhs = tls_tmp_dhs->elts;
4231
4232 /* Search the configured list of DH parameters twice: once for any sizes
4233 * matching the actual requested size (usually 1024), and once for any
4234 * matching the certificate private key size (pkeylen).
4235 *
4236 * This behavior allows site admins to configure a TLSDHParamFile that
4237 * contains 1024-bit parameters, for e.g. Java 7 (and earlier) clients.
4238 */
4239
4240 /* Note: the keylen argument is in BITS, but DH_size() returns the number
4241 * of BYTES.
4242 */
4243 for (i = 0; i < tls_tmp_dhs->nelts; i++) {
4244 int dhlen;
4245
4246 dhlen = DH_size(dhs[i]) * 8;
4247 if (dhlen == keylen) {
4248 pr_trace_msg(trace_channel, 11,
4249 "found matching DH parameter for key length %d", keylen);
4250 return dhs[i];
4251 }
4252
4253 /* Try to find the next "best" DH to use, where "best" means
4254 * the smallest DH that is larger than the necessary keylen.
4255 */
4256 if (dhlen > keylen) {
4257 if (best_dh != NULL) {
4258 if (dhlen < best_dhlen) {
4259 best_dh = dhs[i];
4260 best_dhlen = dhlen;
4261 }
4262
4263 } else {
4264 best_dh = dhs[i];
4265 best_dhlen = dhlen;
4266 }
4267 }
4268 }
4269
4270 for (i = 0; i < tls_tmp_dhs->nelts; i++) {
4271 int dhlen;
4272
4273 dhlen = DH_size(dhs[i]) * 8;
4274 if (dhlen == pkeylen) {
4275 pr_trace_msg(trace_channel, 11,
4276 "found matching DH parameter for certificate private key length %d",
4277 pkeylen);
4278 return dhs[i];
4279 }
4280
4281 if (dhlen > pkeylen) {
4282 if (best_dh != NULL) {
4283 if (dhlen < best_dhlen) {
4284 best_dh = dhs[i];
4285 best_dhlen = dhlen;
4286 }
4287
4288 } else {
4289 best_dh = dhs[i];
4290 best_dhlen = dhlen;
4291 }
4292 }
4293 }
4294
4295 if (best_dh != NULL) {
4296 pr_trace_msg(trace_channel, 11,
4297 "using best DH parameter for key length %d (length %d)", keylen,
4298 best_dhlen);
4299 return best_dh;
4300 }
4301 }
4302
4303 /* Still no DH parameters found? Use the built-in ones. */
4304
4305 if (keylen < TLS_DH_MIN_LEN) {
4306 if (!(tls_opts & TLS_OPT_ALLOW_WEAK_DH)) {
4307 pr_trace_msg(trace_channel, 11,
4308 "requested key length %d less than %d bits, using %d "
4309 "(see AllowWeakDH TLSOption)", keylen, TLS_DH_MIN_LEN, TLS_DH_MIN_LEN);
4310 keylen = TLS_DH_MIN_LEN;
4311 }
4312 }
4313
4314 if (use_pkeylen) {
4315 keylen = pkeylen;
4316 }
4317
4318 switch (keylen) {
4319 case 512:
4320 dh = get_dh512();
4321 break;
4322
4323 case 768:
4324 dh = get_dh768();
4325 break;
4326
4327 case 1024:
4328 dh = get_dh1024();
4329 break;
4330
4331 case 1536:
4332 dh = get_dh1536();
4333 break;
4334
4335 case 2048:
4336 dh = get_dh2048();
4337 break;
4338
4339 case 3072:
4340 dh = get_dh3072();
4341 break;
4342
4343 case 4096:
4344 dh = get_dh4096();
4345 break;
4346
4347 default:
4348 tls_log("unsupported DH key length %d requested, returning 1024 bits",
4349 keylen);
4350 dh = get_dh1024();
4351 break;
4352 }
4353
4354 pr_trace_msg(trace_channel, 11, "using builtin DH for %d bits", keylen);
4355
4356 /* Add this DH to the list, so that it can be freed properly later. */
4357 if (tls_tmp_dhs == NULL) {
4358 tls_tmp_dhs = make_array(session.pool, 1, sizeof(DH *));
4359 }
4360
4361 *((DH **) push_array(tls_tmp_dhs)) = dh;
4362 return dh;
4363 }
4364
4365 #if !defined(OPENSSL_NO_TLSEXT)
4366 # if defined(TLSEXT_MAXLEN_host_name)
4367 static int tls_sni_cb(SSL *ssl, int *alert_desc, void *user_data) {
4368 const char *server_name = NULL;
4369
4370 server_name = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
4371 if (server_name != NULL) {
4372 const char *host = NULL, *sni;
4373 server_rec *named_server = NULL;
4374
4375 pr_trace_msg(trace_channel, 5, "received SNI '%s'", server_name);
4376
4377 /* If we have already received a HOST command, then we need to
4378 * check that the SNI value matches that of the HOST. Otherwise,
4379 * we stash the SNI, so that if/when a HOST command is received,
4380 * we can check the HOST name against the SNI.
4381 *
4382 * RFC 7151, Section 3.2.2, does not mandate whether HOST must be
4383 * sent before e.g. AUTH TLS or not; the only example the RFC provides
4384 * shows AUTH TLS being used before HOST. Section 4 of that RFC goes
4385 * on to recommend using HOST before AUTH, in general, unless the SNI
4386 * extension will be used, in which case, clients should use AUTH TLS
4387 * before HOST. We need to be ready for either case.
4388 *
4389 * Note that this SNI/HOST check can only really happen for control
4390 * connections, not data connections. FTPS clients do not receive/use
4391 * DNS hostnames for data connections, only IP addresses.
4392 */
4393
4394 host = pr_table_get(session.notes, "mod_core.host", NULL);
4395
4396 /* If we have already stashed an SNI, it means this is probably a data
4397 * connection.
4398 *
4399 * For data connections where an SNI is provided, we MIGHT be able to
4400 * validate that SNI (assuming it is an IP address) against our IP address,
4401 * at least.
4402 */
4403 sni = pr_table_get(session.notes, "mod_tls.sni", NULL);
4404
4405 if (host != NULL &&
4406 sni == NULL) {
4407 /* If the requested HOST does not match the SNI, it's a fatal error.
4408 *
4409 * Bear in mind, however, that the HOST command might have used an
4410 * IPv4/IPv6 address, NOT a name. If that is the case, we do NOT want
4411 * compare that with SNI. Do we?
4412 */
4413
4414 if (pr_netaddr_is_v4(host) != TRUE &&
4415 pr_netaddr_is_v6(host) != TRUE) {
4416 if (strcasecmp(host, server_name) != 0) {
4417 tls_log("warning: SNI '%s' does not match HOST '%s', rejecting "
4418 "SSL/TLS connection", server_name, host);
4419 pr_log_pri(PR_LOG_NOTICE, MOD_TLS_VERSION
4420 ": SNI '%s' does not match HOST '%s', rejecting SSL/TLS connection",
4421 server_name, host);
4422 *alert_desc = SSL_AD_ACCESS_DENIED;
4423 return SSL_TLSEXT_ERR_ALERT_FATAL;
4424 }
4425 }
4426 }
4427
4428 if (tls_opts & TLS_OPT_IGNORE_SNI) {
4429 pr_trace_msg(trace_channel, 5,
4430 "client sent SNI '%s', ignoring due to IgnoreSNI TLSOption",
4431 server_name);
4432 return SSL_TLSEXT_ERR_OK;
4433 }
4434
4435 /* Per RFC 6066, literal IPv4/IPv6 addresses are NOT permitted in the
4436 * SNI. However, some clients will still send such IP addresses.
4437 * We can safely ignore these, since any IP-based virtual host selection
4438 * happens at TCP connect time.
4439 */
4440 if (pr_netaddr_is_v4(server_name) == TRUE ||
4441 pr_netaddr_is_v6(server_name) == TRUE) {
4442 pr_trace_msg(trace_channel, 5,
4443 "client sent IP address SNI '%s', ignoring", server_name);
4444 return SSL_TLSEXT_ERR_OK;
4445 }
4446
4447 if (pr_table_add_dup(session.notes, "mod_tls.sni",
4448 (char *) server_name, 0) < 0) {
4449
4450 /* The session.notes may already have the SNI from the ctrl channel;
4451 * no need to overwrite that.
4452 */
4453 if (errno != EEXIST) {
4454 pr_trace_msg(trace_channel, 3,
4455 "error stashing 'mod_tls.sni' in session.notes: %s", strerror(errno));
4456 }
4457 }
4458
4459 /* Notify any listeners (e.g. mod_autohost) of the requested name, to
4460 * given them a chance to update/modify the configuration.
4461 */
4462 pr_event_generate("mod_tls.sni", server_name);
4463
4464 /* If we have no name-based virtual servers configured (no ServerAlias),
4465 * then just ignore the SNI. Otherwise, configurations which have been
4466 * working will "break" unexpectedly, due to SNI support.
4467 */
4468 if (pr_namebind_count(main_server) == 0) {
4469 pr_trace_msg(trace_channel, 5,
4470 "no name-based <VirtualHost> configured, ignoring SNI '%s'",
4471 server_name);
4472 return SSL_TLSEXT_ERR_OK;
4473 }
4474
4475 /* See if we have a name-based vhost matching the SNI; if so, we want
4476 * to switch to that vhost, in case it is configured with different
4477 * server certificates, CAs.
4478 */
4479
4480 named_server = pr_namebind_get_server(server_name, main_server->addr,
4481 session.c->local_port);
4482 if (named_server == NULL) {
4483 tls_log("no matching server found for client-sent SNI '%s', rejecting "
4484 "SSL/TLS connection", server_name);
4485 pr_log_pri(PR_LOG_NOTICE, MOD_TLS_VERSION
4486 ": no matching server found for client-sent SNI '%s', "
4487 "rejecting SSL/TLS connection", server_name);
4488 #if defined(SSL_AD_UNRECOGNIZED_NAME)
4489 *alert_desc = SSL_AD_UNRECOGNIZED_NAME;
4490 #else
4491 *alert_desc = SSL_AD_ACCESS_DENIED;
4492 #endif /* SSL_AD_UNRECOGNIZED_NAME */
4493 return SSL_TLSEXT_ERR_ALERT_FATAL;
4494 }
4495
4496 if (named_server != main_server) {
4497 unsigned char *engine;
4498 SSL_SESSION *sess;
4499
4500 /* First, check to see whether mod_tls is even enabled for the named
4501 * vhost.
4502 */
4503 engine = get_param_ptr(named_server->conf, "TLSEngine", FALSE);
4504 if (engine == NULL ||
4505 *engine == FALSE) {
4506 tls_log("TLSEngine not enabled for SNI '%s', rejecting client",
4507 server_name);
4508 pr_log_pri(PR_LOG_NOTICE, MOD_TLS_VERSION
4509 ": TLSEngine not enabled for SNI '%s', rejecting client",
4510 server_name);
4511
4512 #if defined(SSL_AD_UNRECOGNIZED_NAME)
4513 *alert_desc = SSL_AD_UNRECOGNIZED_NAME;
4514 #else
4515 *alert_desc = SSL_AD_HANDSHAKE_FAILURE;
4516 #endif /* SSL_AD_UNRECOGNIZED_NAME */
4517 return SSL_TLSEXT_ERR_ALERT_FATAL;
4518 }
4519
4520 tls_lookup_all(named_server);
4521
4522 /* Check to see if a passphrase has been entered for this server. */
4523 tls_pkey = tls_lookup_pkey(named_server, TRUE, TRUE);
4524
4525 if (tls_ssl_set_all(named_server, ssl) < 0) {
4526 tls_log("error initializing OpenSSL session for SNI '%s'", server_name);
4527 pr_log_pri(PR_LOG_NOTICE, MOD_TLS_VERSION
4528 ": error initializing OpenSSL session for SNI '%s'", server_name);
4529 *alert_desc = SSL_AD_ACCESS_DENIED;
4530 return SSL_TLSEXT_ERR_ALERT_FATAL;
4531 }
4532
4533 /* Our new SSL_CTX, from the SNI, might have different protocol
4534 * versions enabled. However, due to the _timing_ of when this SNI
4535 * callback is invoked during the TLS handshake processing, the
4536 * "acceptable" server protocol version has already been determined
4537 * based on the original SSL_CTX. This means that we need to check
4538 * for incompatible protocol versions ourselves. Fun!
4539 *
4540 * We implement this in a naive manner: if the new SSL_CTX has an
4541 * SSL_OP_NO_ option enabled for the protocol version currently
4542 * selected by our SSL_SESSION, fail the callback with
4543 * SSL_AD_PROTOCOL_VERSION.
4544 */
4545 sess = SSL_get_session(ssl);
4546 if (sess != NULL) {
4547 SSL_CTX *ctx;
4548 long ctx_options;
4549 int protocol_ok = FALSE, sess_version;
4550
4551 ctx = SSL_get_SSL_CTX(ssl);
4552 ctx_options = SSL_CTX_get_options(ctx);
4553
4554 #if (OPENSSL_VERSION_NUMBER >= 0x10100000L && !defined(HAVE_LIBRESSL)) || \
4555 (defined(HAVE_LIBRESSL) && LIBRESSL_VERSION_NUMBER >= 0x3050000L)
4556 sess_version = SSL_SESSION_get_protocol_version(sess);
4557 #else
4558 sess_version = sess->ssl_version;
4559 #endif /* OpenSSL 1.1.x/LibreSSL-3.5.x and later */
4560
4561 switch (sess_version) {
4562 case SSL3_VERSION:
4563 if (!(ctx_options & SSL_OP_NO_SSLv3)) {
4564 protocol_ok = TRUE;
4565 }
4566 break;
4567
4568 case TLS1_VERSION:
4569 if (!(ctx_options & SSL_OP_NO_TLSv1)) {
4570 protocol_ok = TRUE;
4571 }
4572 break;
4573
4574 #if defined(TLS1_1_VERSION)
4575 case TLS1_1_VERSION:
4576 # if defined(SSL_OP_NO_TLSv1_1)
4577 if (!(ctx_options & SSL_OP_NO_TLSv1_1)) {
4578 protocol_ok = TRUE;
4579 }
4580 # endif /* SSL_OP_NO_TLSv1_1 */
4581 break;
4582 #endif /* TLS1_1_VERSION */
4583
4584 #if defined(TLS1_2_VERSION)
4585 case TLS1_2_VERSION:
4586 # if defined(SSL_OP_NO_TLSv1_2)
4587 if (!(ctx_options & SSL_OP_NO_TLSv1_2)) {
4588 protocol_ok = TRUE;
4589 }
4590 # endif /* SSL_OP_NO_TLSv1_2 */
4591 break;
4592 #endif /* TLS1_2_VERSION */
4593
4594 #if defined(TLS1_3_VERSION)
4595 case TLS1_3_VERSION:
4596 if (!(ctx_options & SSL_OP_NO_TLSv1_3)) {
4597 protocol_ok = TRUE;
4598 }
4599 break;
4600 #endif /* TLS1_3_VERSION */
4601
4602 default:
4603 pr_trace_msg(trace_channel, 3,
4604 "unknown/unsupported protocol version '%s' (%d) requested by "
4605 "client", SSL_get_version(ssl), sess_version);
4606 break;
4607 }
4608
4609 if (protocol_ok == FALSE) {
4610 tls_log("client-requested protocol version %s not supported by "
4611 "SNI '%s' host", SSL_get_version(ssl), server_name);
4612 pr_log_pri(PR_LOG_NOTICE, MOD_TLS_VERSION
4613 ": client-requested protocol version %s not supported by "
4614 "SNI '%s' host", SSL_get_version(ssl), server_name);
4615 *alert_desc = SSL_AD_PROTOCOL_VERSION;
4616 return SSL_TLSEXT_ERR_ALERT_FATAL;
4617 }
4618 }
4619 }
4620 }
4621
4622 return SSL_TLSEXT_ERR_OK;
4623 }
4624 # endif /* !TLSEXT_MAXLEN_host_name */
4625
4626 static void tls_tlsext_cb(SSL *ssl, int server, int type,
4627 unsigned char *tlsext_data, int tlsext_datalen, void *data) {
4628 char *extension_name = "(unknown)";
4629 int print_basic_info = TRUE;
4630
4631 /* Note: OpenSSL does not implement all possible extensions. For the
4632 * "(unknown)" extensions, see:
4633 *
4634 * http://www.iana.org/assignments/tls-extensiontype-values/tls-extensiontype-values.xhtml#tls-extensiontype-values-1
4635 */
4636 switch (type) {
4637 # ifdef TLSEXT_TYPE_server_name
4638 case TLSEXT_TYPE_server_name: {
4639 BIO *bio = NULL;
4640 char *ext_info = "";
4641 long ext_infolen = 0;
4642
4643 extension_name = "server name";
4644
4645 if (pr_trace_get_level(trace_channel) >= 19 &&
4646 tlsext_datalen >= 2) {
4647
4648 /* We read 2 bytes for the extension length, 1 byte for the
4649 * name type, and 2 bytes for the name length. For the SNI
4650 * format specification, see:
4651 * https://tools.ietf.org/html/rfc6066#section-3
4652 */
4653 int ext_len;
4654
4655 ext_len = (tlsext_data[0] << 8) | tlsext_data[1];
4656 if (tlsext_datalen == ext_len + 2 &&
4657 (ext_len & 1) == 0) {
4658 int name_type;
4659 tlsext_data += 2;
4660
4661 name_type = tlsext_data[0];
4662 tlsext_data += 1;
4663
4664 if (name_type == TLSEXT_NAMETYPE_host_name) {
4665 size_t name_len;
4666
4667 name_len = (tlsext_data[0] << 8) | tlsext_data[1];
4668 tlsext_data += 2;
4669
4670 bio = BIO_new(BIO_s_mem());
4671 BIO_printf(bio, "\n %.*s (%lu)", (int) name_len, tlsext_data,
4672 (unsigned long) name_len);
4673
4674 ext_infolen = BIO_get_mem_data(bio, &ext_info);
4675 if (ext_info != NULL) {
4676 ext_info[ext_infolen] = '\0';
4677 }
4678 }
4679 }
4680 }
4681
4682 pr_trace_msg(trace_channel, 6,
4683 "[tls.tlsext] TLS %s extension \"%s\" (ID %d, %d %s)%.*s",
4684 server ? "server" : "client", extension_name, type,
4685 tlsext_datalen, tlsext_datalen != 1 ? "bytes" : "byte",
4686 (int) ext_infolen, ext_info != NULL ? ext_info : "");
4687
4688 if (bio != NULL) {
4689 BIO_free(bio);
4690 }
4691
4692 print_basic_info = FALSE;
4693 break;
4694 }
4695 # endif
4696
4697 # ifdef TLSEXT_TYPE_max_fragment_length
4698 case TLSEXT_TYPE_max_fragment_length:
4699 extension_name = "max fragment length";
4700 break;
4701 # endif
4702
4703 # ifdef TLSEXT_TYPE_client_certificate_url
4704 case TLSEXT_TYPE_client_certificate_url:
4705 extension_name = "client certificate URL";
4706 break;
4707 # endif
4708
4709 # ifdef TLSEXT_TYPE_trusted_ca_keys
4710 case TLSEXT_TYPE_trusted_ca_keys:
4711 extension_name = "trusted CA keys";
4712 break;
4713 # endif
4714
4715 # ifdef TLSEXT_TYPE_truncated_hmac
4716 case TLSEXT_TYPE_truncated_hmac:
4717 extension_name = "truncated HMAC";
4718 break;
4719 # endif
4720
4721 # ifdef TLSEXT_TYPE_status_request
4722 case TLSEXT_TYPE_status_request:
4723 extension_name = "status request";
4724 break;
4725 # endif
4726
4727 # ifdef TLSEXT_TYPE_user_mapping
4728 case TLSEXT_TYPE_user_mapping:
4729 extension_name = "user mapping";
4730 break;
4731 # endif
4732
4733 # ifdef TLSEXT_TYPE_client_authz
4734 case TLSEXT_TYPE_client_authz:
4735 extension_name = "client authz";
4736 break;
4737 # endif
4738
4739 # ifdef TLSEXT_TYPE_server_authz
4740 case TLSEXT_TYPE_server_authz:
4741 extension_name = "server authz";
4742 break;
4743 # endif
4744
4745 # ifdef TLSEXT_TYPE_cert_type
4746 case TLSEXT_TYPE_cert_type:
4747 extension_name = "cert type";
4748 break;
4749 # endif
4750
4751 # ifdef TLSEXT_TYPE_elliptic_curves
4752 case TLSEXT_TYPE_elliptic_curves:
4753 extension_name = "elliptic curves";
4754 break;
4755 # endif
4756
4757 # ifdef TLSEXT_TYPE_ec_point_formats
4758 case TLSEXT_TYPE_ec_point_formats:
4759 extension_name = "EC point formats";
4760 break;
4761 # endif
4762
4763 # ifdef TLSEXT_TYPE_srp
4764 case TLSEXT_TYPE_srp:
4765 extension_name = "SRP";
4766 break;
4767 # endif
4768
4769 # ifdef TLSEXT_TYPE_signature_algorithms
4770 case TLSEXT_TYPE_signature_algorithms: {
4771 BIO *bio = NULL;
4772 char *ext_info = "";
4773 long ext_infolen = 0;
4774
4775 extension_name = "signature algorithms";
4776
4777 if (pr_trace_get_level(trace_channel) >= 19 &&
4778 tlsext_datalen >= 2) {
4779 int len;
4780
4781 len = (tlsext_data[0] << 8) | tlsext_data[1];
4782 if (tlsext_datalen == len + 2 &&
4783 (len & 1) == 0) {
4784 tlsext_data += 2;
4785
4786 bio = BIO_new(BIO_s_mem());
4787 BIO_puts(bio, "\n");
4788
4789 while (len > 0) {
4790 unsigned int sig_algo;
4791
4792 pr_signals_handle();
4793
4794 sig_algo = (tlsext_data[0] << 8) | tlsext_data[1];
4795 BIO_printf(bio, " %s (0x%x)\n",
4796 tls_get_label(sig_algo, tls_sigalgo_labels), sig_algo);
4797 len -= 2;
4798 tlsext_data += 2;
4799 }
4800
4801 ext_infolen = BIO_get_mem_data(bio, &ext_info);
4802 if (ext_info != NULL) {
4803 ext_info[ext_infolen] = '\0';
4804 }
4805 }
4806 }
4807
4808 pr_trace_msg(trace_channel, 6,
4809 "[tls.tlsext] TLS %s extension \"%s\" (ID %d, %d %s)%.*s",
4810 server ? "server" : "client", extension_name, type,
4811 tlsext_datalen, tlsext_datalen != 1 ? "bytes" : "byte",
4812 (int) ext_infolen, ext_info != NULL ? ext_info : "");
4813
4814 if (bio != NULL) {
4815 BIO_free(bio);
4816 }
4817
4818 print_basic_info = FALSE;
4819 break;
4820 }
4821 # endif
4822
4823 # ifdef TLSEXT_TYPE_use_srtp
4824 case TLSEXT_TYPE_use_srtp:
4825 extension_name = "use SRTP";
4826 break;
4827 # endif
4828
4829 # ifdef TLSEXT_TYPE_heartbeat
4830 case TLSEXT_TYPE_heartbeat:
4831 extension_name = "heartbeat";
4832 break;
4833 # endif
4834
4835 # ifdef TLSEXT_TYPE_signed_certificate_timestamp
4836 case TLSEXT_TYPE_signed_certificate_timestamp:
4837 extension_name = "signed certificate timestamp";
4838 break;
4839 # endif
4840
4841 # ifdef TLSEXT_TYPE_encrypt_then_mac
4842 case TLSEXT_TYPE_encrypt_then_mac:
4843 extension_name = "encrypt then mac";
4844 break;
4845 # endif
4846
4847 # ifdef TLSEXT_TYPE_extended_master_secret
4848 case TLSEXT_TYPE_extended_master_secret:
4849 extension_name = "extended master secret";
4850 break;
4851 # endif
4852
4853 # ifdef TLSEXT_TYPE_session_ticket
4854 case TLSEXT_TYPE_session_ticket:
4855 extension_name = "session ticket";
4856 break;
4857 # endif
4858
4859 # ifdef TLSEXT_TYPE_psk
4860 case TLSEXT_TYPE_psk:
4861 extension_name = "PSK";
4862 break;
4863 # endif
4864
4865 # ifdef TLSEXT_TYPE_supported_versions
4866 case TLSEXT_TYPE_supported_versions: {
4867 BIO *bio = NULL;
4868 char *ext_info = NULL;
4869 long ext_infolen = 0;
4870
4871 /* If we are the server responding, we only indicate the selected
4872 * protocol version. Otherwise, we are a client indicating the range
4873 * of versions supported.
4874 */
4875
4876 extension_name = "supported versions";
4877
4878 if (pr_trace_get_level(trace_channel) >= 19) {
4879 bio = BIO_new(BIO_s_mem());
4880
4881 if (server) {
4882 if (tlsext_datalen == 2) {
4883 int version;
4884
4885 version = (tlsext_data[0] << 8) | tlsext_data[1];
4886 BIO_printf(bio, "\n %s (0x%x)\n",
4887 tls_get_label(version, tls_version_labels), version);
4888 }
4889
4890 } else {
4891 if (tlsext_datalen >= 1) {
4892 int len;
4893
4894 len = tlsext_data[0];
4895 if (tlsext_datalen == len + 1) {
4896 tlsext_data += 1;
4897
4898 BIO_puts(bio, "\n");
4899
4900 while (len > 0) {
4901 int version;
4902
4903 pr_signals_handle();
4904
4905 version = (tlsext_data[0] << 8) | tlsext_data[1];
4906 BIO_printf(bio, " %s (0x%x)\n",
4907 tls_get_label(version, tls_version_labels), version);
4908 len -= 2;
4909 tlsext_data += 2;
4910 }
4911 }
4912 }
4913 }
4914
4915 ext_infolen = BIO_get_mem_data(bio, &ext_info);
4916 if (ext_info != NULL) {
4917 ext_info[ext_infolen] = '\0';
4918 }
4919 }
4920
4921 pr_trace_msg(trace_channel, 6,
4922 "[tls.tlsext] TLS %s extension \"%s\" (ID %d, %d %s)%.*s",
4923 server ? "server" : "client", extension_name, type,
4924 tlsext_datalen, tlsext_datalen != 1 ? "bytes" : "byte",
4925 (int) ext_infolen, ext_info != NULL ? ext_info : "");
4926
4927 if (bio != NULL) {
4928 BIO_free(bio);
4929 }
4930
4931 print_basic_info = FALSE;
4932 break;
4933 }
4934 # endif
4935
4936 # ifdef TLSEXT_TYPE_psk_kex_modes
4937 case TLSEXT_TYPE_psk_kex_modes: {
4938 BIO *bio = NULL;
4939 char *ext_info = NULL;
4940 long ext_infolen = 0;
4941
4942 extension_name = "PSK KEX modes";
4943
4944 if (pr_trace_get_level(trace_channel) >= 19) {
4945 if (tlsext_datalen >= 1) {
4946 int len;
4947
4948 bio = BIO_new(BIO_s_mem());
4949 len = tlsext_data[0];
4950
4951 if (tlsext_datalen == len + 1) {
4952 tlsext_data += 1;
4953
4954 BIO_puts(bio, "\n");
4955
4956 while (len > 0) {
4957 int kex_mode;
4958
4959 pr_signals_handle();
4960
4961 kex_mode = tlsext_data[0];
4962 BIO_printf(bio, " %s (%d)\n",
4963 tls_get_label(kex_mode, tls_psk_kex_labels), kex_mode);
4964 len -= 1;
4965 tlsext_data += 1;
4966 }
4967 }
4968 }
4969
4970 ext_infolen = BIO_get_mem_data(bio, &ext_info);
4971 if (ext_info != NULL) {
4972 ext_info[ext_infolen] = '\0';
4973 }
4974 }
4975
4976 pr_trace_msg(trace_channel, 6,
4977 "[tls.tlsext] TLS %s extension \"%s\" (ID %d, %d %s)%.*s",
4978 server ? "server" : "client", extension_name, type,
4979 tlsext_datalen, tlsext_datalen != 1 ? "bytes" : "byte",
4980 (int) ext_infolen, ext_info != NULL ? ext_info : "");
4981
4982 if (bio != NULL) {
4983 BIO_free(bio);
4984 }
4985
4986 print_basic_info = FALSE;
4987 break;
4988 }
4989 # endif
4990
4991 # ifdef TLSEXT_TYPE_key_share
4992 case TLSEXT_TYPE_key_share:
4993 extension_name = "key share";
4994 break;
4995 # endif
4996
4997 # ifdef TLSEXT_TYPE_renegotiate
4998 case TLSEXT_TYPE_renegotiate:
4999 extension_name = "renegotiation info";
5000 break;
5001 # endif
5002
5003 # ifdef TLSEXT_TYPE_opaque_prf_input
5004 case TLSEXT_TYPE_opaque_prf_input:
5005 extension_name = "opaque PRF input";
5006 break;
5007 # endif
5008
5009 # ifdef TLSEXT_TYPE_next_proto_neg
5010 case TLSEXT_TYPE_next_proto_neg:
5011 extension_name = "next protocol";
5012 break;
5013 # endif
5014
5015 # ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
5016 case TLSEXT_TYPE_application_layer_protocol_negotiation:
5017 extension_name = "application layer protocol";
5018 break;
5019 # endif
5020
5021 # ifdef TLSEXT_TYPE_padding
5022 case TLSEXT_TYPE_padding:
5023 extension_name = "TLS padding";
5024 break;
5025 # endif
5026
5027 # ifdef TLSEXT_TYPE_early_data
5028 case TLSEXT_TYPE_early_data:
5029 extension_name = "early data";
5030 break;
5031 # endif
5032
5033 # ifdef TLSEXT_TYPE_post_handshake_auth
5034 case TLSEXT_TYPE_post_handshake_auth:
5035 extension_name = "post handshake auth";
5036 break;
5037 # endif
5038
5039 default:
5040 print_basic_info = TRUE;
5041 break;
5042 }
5043
5044 if (print_basic_info == TRUE) {
5045 pr_trace_msg(trace_channel, 6,
5046 "[tls.tlsext] TLS %s extension \"%s\" (ID %d, %d %s)",
5047 server ? "server" : "client", extension_name, type, tlsext_datalen,
5048 tlsext_datalen != 1 ? "bytes" : "byte");
5049 }
5050 }
5051 #endif /* !OPENSSL_NO_TLSEXT */
5052
5053 #if defined(PR_USE_OPENSSL_OCSP)
5054 static OCSP_RESPONSE *ocsp_send_request(pool *p, BIO *bio, const char *host,
5055 const char *uri, OCSP_REQUEST *req, unsigned int request_timeout) {
5056 int fd, res;
5057 OCSP_RESPONSE *resp = NULL;
5058 OCSP_REQ_CTX *ctx = NULL;
5059 const char *header_name, *header_value;
5060
5061 res = BIO_get_fd(bio, &fd);
5062 if (res <= 0) {
5063 pr_trace_msg(trace_channel, 3,
5064 "error obtaining OCSP responder socket fd: %s", tls_get_errors());
5065 return NULL;
5066 }
5067
5068 ctx = OCSP_sendreq_new(bio, (char *) uri, NULL, -1);
5069 if (ctx == NULL) {
5070 pr_trace_msg(trace_channel, 4,
5071 "error allocating OCSP request context: %s", tls_get_errors());
5072 return NULL;
5073 }
5074
5075 # if OPENSSL_VERSION_NUMBER >= 0x10000001L
5076 header_name = "Host";
5077 header_value = host;
5078 res = OCSP_REQ_CTX_add1_header(ctx, header_name, header_value);
5079 if (res != 1) {
5080 pr_trace_msg(trace_channel, 4,
5081 "error adding '%s: %s' header to OCSP request context: %s", header_name,
5082 header_value, tls_get_errors());
5083 OCSP_REQ_CTX_free(ctx);
5084 return NULL;
5085 }
5086
5087 header_name = "Accept";
5088 header_value = "application/ocsp-response";
5089 res = OCSP_REQ_CTX_add1_header(ctx, header_name, header_value);
5090 if (res != 1) {
5091 pr_trace_msg(trace_channel, 4,
5092 "error adding '%s: %s' header to OCSP request context: %s", header_name,
5093 header_value, tls_get_errors());
5094 OCSP_REQ_CTX_free(ctx);
5095 return NULL;
5096 }
5097
5098 header_name = "User-Agent";
5099 header_value = "proftpd+" MOD_TLS_VERSION;
5100 res = OCSP_REQ_CTX_add1_header(ctx, header_name, header_value);
5101 if (res != 1) {
5102 pr_trace_msg(trace_channel, 4,
5103 "error adding '%s: %s' header to OCSP request context: %s", header_name,
5104 header_value, tls_get_errors());
5105 OCSP_REQ_CTX_free(ctx);
5106 return NULL;
5107 }
5108
5109 /* If we are using nonces, then we need to explicitly request that no
5110 * caches along the way interfere.
5111 */
5112 if (!(tls_stapling_opts & TLS_STAPLING_OPT_NO_NONCE)) {
5113 header_name = "Pragma";
5114 header_value = "no-cache";
5115 res = OCSP_REQ_CTX_add1_header(ctx, header_name, header_value);
5116 if (res != 1) {
5117 pr_trace_msg(trace_channel, 4,
5118 "error adding '%s: %s' header to OCSP request context: %s", header_name,
5119 header_value, tls_get_errors());
5120 OCSP_REQ_CTX_free(ctx);
5121 return NULL;
5122 }
5123
5124 header_name = "Cache-Control";
5125 header_value = "no-cache, no-store";
5126 res = OCSP_REQ_CTX_add1_header(ctx, header_name, header_value);
5127 if (res != 1) {
5128 pr_trace_msg(trace_channel, 4,
5129 "error adding '%s: %s' header to OCSP request context: %s", header_name,
5130 header_value, tls_get_errors());
5131 OCSP_REQ_CTX_free(ctx);
5132 return NULL;
5133 }
5134 }
5135
5136 /* Only add the request after we've added our headers. */
5137 res = OCSP_REQ_CTX_set1_req(ctx, req);
5138 if (res != 1) {
5139 pr_trace_msg(trace_channel, 4,
5140 "error adding OCSP request to context: %s", tls_get_errors());
5141 OCSP_REQ_CTX_free(ctx);
5142 return NULL;
5143 }
5144 # endif /* OpenSSL-1.0.0 and later */
5145
5146 while (TRUE) {
5147 fd_set fds;
5148 struct timeval tv;
5149
5150 res = OCSP_sendreq_nbio(&resp, ctx);
5151 if (res != -1) {
5152 break;
5153 }
5154
5155 if (request_timeout == 0) {
5156 break;
5157 }
5158
5159 FD_ZERO(&fds);
5160 FD_SET(fd, &fds);
5161 tv.tv_usec = 0;
5162 tv.tv_sec = request_timeout;
5163
5164 if (BIO_should_read(bio)) {
5165 res = select(fd + 1, (void *) &fds, NULL, NULL, &tv);
5166
5167 } else if (BIO_should_write(bio)) {
5168 res = select(fd + 1, NULL, (void *) &fds, NULL, &tv);
5169
5170 } else {
5171 pr_trace_msg(trace_channel, 3,
5172 "unexpected retry condition when talking to OCSP responder '%s%s'",
5173 host, uri);
5174 res = -1;
5175 break;
5176 }
5177
5178 if (res == 0) {
5179 pr_trace_msg(trace_channel, 3,
5180 "timed out talking to OCSP responder '%s%s'", host, uri);
5181 errno = ETIMEDOUT;
5182 res = -1;
5183 break;
5184 }
5185 }
5186
5187 OCSP_REQ_CTX_free(ctx);
5188
5189 if (res) {
5190 if (tls_opts & TLS_OPT_ENABLE_DIAGS) {
5191 BIO *diags_bio;
5192
5193 diags_bio = BIO_new(BIO_s_mem());
5194 if (diags_bio != NULL) {
5195 if (OCSP_RESPONSE_print(diags_bio, resp, 0) == 1) {
5196 char *data = NULL;
5197 long datalen = 0;
5198
5199 datalen = BIO_get_mem_data(diags_bio, &data);
5200 if (data != NULL) {
5201 data[datalen] = '\0';
5202 tls_log("received OCSP response (%ld bytes):\n%s", datalen, data);
5203 }
5204 }
5205 }
5206
5207 BIO_free(diags_bio);
5208 }
5209
5210 return resp;
5211 }
5212
5213 pr_trace_msg(trace_channel, 4,
5214 "error obtaining OCSP response from responder: %s", tls_get_errors());
5215 return NULL;
5216 }
5217
5218 static X509 *ocsp_get_issuing_cert(pool *p, X509 *cert, SSL *ssl) {
5219 int res;
5220 X509 *issuer = NULL;
5221 SSL_CTX *ctx;
5222 X509_STORE *store;
5223 X509_STORE_CTX *store_ctx;
5224 STACK_OF(X509) *extra_certs = NULL;
5225
5226 if (ssl == NULL) {
5227 pr_trace_msg(trace_channel, 4, "%s",
5228 "unable to get issuing cert: no TLS session provided");
5229 errno = EINVAL;
5230 return NULL;
5231 }
5232
5233 ctx = SSL_get_SSL_CTX(ssl);
5234 if (ctx == NULL) {
5235 pr_trace_msg(trace_channel, 4,
5236 "no SSL_CTX found for TLS session: %s", tls_get_errors());
5237 errno = EINVAL;
5238 return NULL;
5239 }
5240
5241 /* First look for the issuer in the CertificateChainFile certs, if any. */
5242 # if OPENSSL_VERSION_NUMBER >= 0x10001000L
5243 (void) SSL_CTX_get_extra_chain_certs(ctx, &extra_certs);
5244 # else
5245 extra_certs = ctx->extra_certs;
5246 # endif
5247
5248 if (extra_certs != NULL &&
5249 sk_X509_num(extra_certs) > 0) {
5250 register int i;
5251
5252 for (i = 0; i < sk_X509_num(extra_certs); i++) {
5253 X509 *extra_cert;
5254
5255 extra_cert = sk_X509_value(extra_certs, i);
5256 if (X509_check_issued(extra_cert, cert) == X509_V_OK) {
5257 issuer = X509_dup(extra_cert);
5258 pr_trace_msg(trace_channel, 14, "found issuer %p for certificate",
5259 issuer);
5260
5261 return issuer;
5262 }
5263 }
5264 }
5265
5266 /* If not found, look in the trusted certs (CACertificateFile/Path). */
5267 store = SSL_CTX_get_cert_store(ctx);
5268 if (store == NULL) {
5269 pr_trace_msg(trace_channel, 4,
5270 "no certificate store found for SSL_CTX: %s", tls_get_errors());
5271
5272 errno = EINVAL;
5273 return NULL;
5274 }
5275
5276 store_ctx = X509_STORE_CTX_new();
5277 if (store_ctx == NULL) {
5278 pr_trace_msg(trace_channel, 4,
5279 "error allocating certificate store context: %s", tls_get_errors());
5280
5281 errno = ENOMEM;
5282 return NULL;
5283 }
5284
5285 res = X509_STORE_CTX_init(store_ctx, store, NULL, NULL);
5286 if (res != 1) {
5287 pr_trace_msg(trace_channel, 4,
5288 "error initializing certificate store context: %s", tls_get_errors());
5289 X509_STORE_CTX_free(store_ctx);
5290
5291 errno = ENOMEM;
5292 return NULL;
5293 }
5294
5295 res = X509_STORE_CTX_get1_issuer(&issuer, store_ctx, cert);
5296 if (res == -1) {
5297 pr_trace_msg(trace_channel, 4,
5298 "error finding issuing certificate: %s", tls_get_errors());
5299 X509_STORE_CTX_free(store_ctx);
5300
5301 errno = EINVAL;
5302 return NULL;
5303 }
5304
5305 if (res == 0) {
5306 pr_trace_msg(trace_channel, 4,
5307 "no issuing certificate found: %s", tls_get_errors());
5308 X509_STORE_CTX_free(store_ctx);
5309
5310 errno = ENOENT;
5311 return NULL;
5312 }
5313
5314 X509_STORE_CTX_free(store_ctx);
5315
5316 pr_trace_msg(trace_channel, 14, "found issuer %p for certificate", issuer);
5317 return issuer;
5318 }
5319
5320 static OCSP_REQUEST *ocsp_get_request(pool *p, X509 *cert, X509 *issuer) {
5321 OCSP_REQUEST *req = NULL;
5322 OCSP_CERTID *cert_id = NULL;
5323
5324 req = OCSP_REQUEST_new();
5325 if (req == NULL) {
5326 pr_trace_msg(trace_channel, 4, "error allocating OCSP request: %s",
5327 tls_get_errors());
5328 return NULL;
5329 }
5330
5331 cert_id = OCSP_cert_to_id(NULL, cert, issuer);
5332 if (cert_id == NULL) {
5333 pr_trace_msg(trace_channel, 4, "error obtaining ID for cert: %s",
5334 tls_get_errors());
5335 OCSP_REQUEST_free(req);
5336 return NULL;
5337 }
5338
5339 if (OCSP_request_add0_id(req, cert_id) == NULL) {
5340 pr_trace_msg(trace_channel, 4, "error adding ID to OCSP request: %s",
5341 tls_get_errors());
5342 OCSP_CERTID_free(cert_id);
5343 OCSP_REQUEST_free(req);
5344 return NULL;
5345 }
5346
5347 if (!(tls_stapling_opts & TLS_STAPLING_OPT_NO_NONCE)) {
5348 OCSP_request_add1_nonce(req, NULL, -1);
5349 }
5350
5351 if (tls_opts & TLS_OPT_ENABLE_DIAGS) {
5352 BIO *diags_bio;
5353
5354 diags_bio = BIO_new(BIO_s_mem());
5355 if (diags_bio != NULL) {
5356 if (OCSP_REQUEST_print(diags_bio, req, 0) == 1) {
5357 char *data = NULL;
5358 long datalen = 0;
5359
5360 datalen = BIO_get_mem_data(diags_bio, &data);
5361 if (data != NULL) {
5362 data[datalen] = '\0';
5363 tls_log("sending OCSP request (%ld bytes):\n%s", datalen, data);
5364 }
5365 }
5366
5367 BIO_free(diags_bio);
5368 }
5369 }
5370
5371 return req;
5372 }
5373
5374 static int ocsp_check_cert_status(pool *p, X509 *cert, X509 *issuer,
5375 OCSP_BASICRESP *basic_resp, int *ocsp_status, int *ocsp_reason) {
5376 int res, status, reason;
5377 OCSP_CERTID *cert_id = NULL;
5378 ASN1_GENERALIZEDTIME *this_update = NULL, *next_update = NULL,
5379 *revoked_at = NULL;
5380
5381 cert_id = OCSP_cert_to_id(NULL, cert, issuer);
5382 if (cert_id == NULL) {
5383 int xerrno = errno;
5384
5385 pr_trace_msg(trace_channel, 3,
5386 "error obtaining cert ID from basic OCSP response: %s", tls_get_errors());
5387
5388 errno = xerrno;
5389 return -1;
5390 }
5391
5392 res = OCSP_resp_find_status(basic_resp, cert_id, &status, &reason,
5393 &revoked_at, &this_update, &next_update);
5394 if (res != 1) {
5395 pr_trace_msg(trace_channel, 3,
5396 "error locating certificate status in OCSP response: %s",
5397 tls_get_errors());
5398
5399 OCSP_CERTID_free(cert_id);
5400 errno = ENOENT;
5401 return -1;
5402 }
5403
5404 OCSP_CERTID_free(cert_id);
5405
5406 res = OCSP_check_validity(this_update, next_update,
5407 TLS_OCSP_RESP_MAX_AGE_SECS, -1);
5408 if (res != 1) {
5409 pr_trace_msg(trace_channel, 3,
5410 "failed time-based validity check of OCSP response: %s",
5411 tls_get_errors());
5412 errno = EINVAL;
5413 return -1;
5414 }
5415
5416 /* Valid or not, we still want to cache this response, AND communicate
5417 * the certificate status, as is, backed to the client via the stapled
5418 * response.
5419 */
5420
5421 pr_trace_msg(trace_channel, 8,
5422 "found certificate status '%s' in OCSP response",
5423 OCSP_cert_status_str(status));
5424 if (status == V_OCSP_CERTSTATUS_REVOKED) {
5425 if (reason != -1) {
5426 pr_trace_msg(trace_channel, 8, "revocation reason: %s",
5427 OCSP_crl_reason_str(reason));
5428 }
5429 }
5430
5431 if (ocsp_status != NULL) {
5432 *ocsp_status = status;
5433 }
5434
5435 if (ocsp_reason != NULL) {
5436 *ocsp_reason = reason;
5437 }
5438
5439 return 0;
5440 }
5441
5442 static int ocsp_check_response(pool *p, X509 *cert, X509 *issuer, SSL *ssl,
5443 OCSP_REQUEST *req, OCSP_RESPONSE *resp) {
5444 int flags = 0, res = 0, resp_status;
5445 OCSP_BASICRESP *basic_resp = NULL;
5446 SSL_CTX *ctx = NULL;
5447 X509_STORE *store = NULL;
5448 STACK_OF(X509) *chain = NULL;
5449
5450 ctx = SSL_get_SSL_CTX(ssl);
5451 if (ctx == NULL) {
5452 pr_trace_msg(trace_channel, 4,
5453 "no SSL_CTX found for TLS session: %s", tls_get_errors());
5454
5455 errno = EINVAL;
5456 return -1;
5457 }
5458
5459 store = SSL_CTX_get_cert_store(ctx);
5460 if (store == NULL) {
5461 pr_trace_msg(trace_channel, 4,
5462 "no certificate store found for SSL_CTX: %s", tls_get_errors());
5463
5464 errno = EINVAL;
5465 return -1;
5466 }
5467
5468 basic_resp = OCSP_response_get1_basic(resp);
5469 if (basic_resp == NULL) {
5470 int xerrno = errno;
5471
5472 pr_trace_msg(trace_channel, 3,
5473 "error getting basic OCSP response: %s", tls_get_errors());
5474
5475 errno = xerrno;
5476 return -1;
5477 }
5478
5479 if (!(tls_stapling_opts & TLS_STAPLING_OPT_NO_NONCE)) {
5480 res = OCSP_check_nonce(req, basic_resp);
5481 if (res < 0) {
5482 pr_trace_msg(trace_channel, 1,
5483 "WARNING: OCSP response is missing request nonce");
5484
5485 } else if (res == 0) {
5486 pr_trace_msg(trace_channel, 3,
5487 "error verifying OCSP response nonce: %s", tls_get_errors());
5488
5489 OCSP_BASICRESP_free(basic_resp);
5490 errno = EINVAL;
5491 return -1;
5492 }
5493 }
5494
5495 chain = sk_X509_new_null();
5496 if (chain != NULL) {
5497 STACK_OF(X509) *extra_certs = NULL;
5498
5499 sk_X509_push(chain, issuer);
5500
5501 # if OPENSSL_VERSION_NUMBER >= 0x10001000L
5502 SSL_CTX_get_extra_chain_certs(ctx, &extra_certs);
5503 # else
5504 extra_certs = ctx->extra_certs;
5505 # endif
5506
5507 if (extra_certs != NULL) {
5508 register int i;
5509
5510 for (i = 0; i < sk_X509_num(extra_certs); i++) {
5511 sk_X509_push(chain, sk_X509_value(extra_certs, i));
5512 }
5513 }
5514 }
5515
5516 flags = OCSP_TRUSTOTHER;
5517 if (tls_stapling_opts & TLS_STAPLING_OPT_NO_VERIFY) {
5518 flags = OCSP_NOVERIFY;
5519 }
5520
5521 res = OCSP_basic_verify(basic_resp, chain, store, flags);
5522 if (res != 1) {
5523 pr_trace_msg(trace_channel, 3,
5524 "error verifying basic OCSP response data: %s", tls_get_errors());
5525
5526 OCSP_BASICRESP_free(basic_resp);
5527
5528 if (chain != NULL) {
5529 sk_X509_free(chain);
5530 }
5531
5532 errno = EINVAL;
5533 return -1;
5534 }
5535
5536 if (chain != NULL) {
5537 sk_X509_free(chain);
5538 }
5539
5540 /* Now that we have verified the response, we can check the response status.
5541 * If we only looked at the status first, then a malicious responder
5542 * could be tricking us, e.g.:
5543 *
5544 * http://www.thoughtcrime.org/papers/ocsp-attack.pdf
5545 */
5546
5547 resp_status = OCSP_response_status(resp);
5548 if (resp_status != OCSP_RESPONSE_STATUS_SUCCESSFUL) {
5549 pr_trace_msg(trace_channel, 3,
5550 "OCSP response not successful: %s (%d)",
5551 OCSP_response_status_str(resp_status), resp_status);
5552
5553 OCSP_BASICRESP_free(basic_resp);
5554 errno = EINVAL;
5555 return -1;
5556 }
5557
5558 res = ocsp_check_cert_status(p, cert, issuer, basic_resp, NULL, NULL);
5559 OCSP_BASICRESP_free(basic_resp);
5560
5561 return res;
5562 }
5563
5564 static int ocsp_connect(pool *p, BIO *bio, unsigned int request_timeout) {
5565 int fd, res;
5566
5567 if (request_timeout > 0) {
5568 BIO_set_nbio(bio, 1);
5569 }
5570
5571 res = BIO_do_connect(bio);
5572 if (res <= 0 &&
5573 (request_timeout == 0 || !BIO_should_retry(bio))) {
5574 pr_trace_msg(trace_channel, 4,
5575 "error connecting to OCSP responder: %s", tls_get_errors());
5576 errno = EPERM;
5577 return -1;
5578 }
5579
5580 if (BIO_get_fd(bio, &fd) < 0) {
5581 pr_trace_msg(trace_channel, 3,
5582 "error obtaining OCSP responder socket fd: %s", tls_get_errors());
5583 errno = EINVAL;
5584 return -1;
5585 }
5586
5587 if (request_timeout > 0 &&
5588 res <= 0) {
5589 struct timeval tv;
5590 fd_set fds;
5591
5592 FD_ZERO(&fds);
5593 FD_SET(fd, &fds);
5594 tv.tv_usec = 0;
5595 tv.tv_sec = request_timeout;
5596 res = select(fd + 1, NULL, (void *) &fds, NULL, &tv);
5597 if (res == 0) {
5598 errno = ETIMEDOUT;
5599 return -1;
5600 }
5601 }
5602
5603 return 0;
5604 }
5605
5606 static OCSP_RESPONSE *ocsp_request_response(pool *p, X509 *cert, SSL *ssl,
5607 const char *url, unsigned int request_timeout) {
5608 BIO *bio;
5609 SSL_CTX *ctx = NULL;
5610 X509 *issuer = NULL;
5611 char *host = NULL, *port = NULL, *uri = NULL;
5612 int res, use_ssl = FALSE;
5613 OCSP_REQUEST *req = NULL;
5614 OCSP_RESPONSE *resp = NULL;
5615
5616 issuer = ocsp_get_issuing_cert(p, cert, ssl);
5617 if (issuer == NULL) {
5618 return NULL;
5619 }
5620
5621 /* Current OpenSSL implementation of OCSP_parse_url() guarantees that
5622 * host, port, and uri will never be NULL. Nice.
5623 */
5624 res = OCSP_parse_url((char *) url, &host, &port, &uri, &use_ssl);
5625 if (res != 1) {
5626 pr_trace_msg(trace_channel, 4, "error parsing OCSP URL '%s': %s", url,
5627 tls_get_errors());
5628 X509_free(issuer);
5629 return NULL;
5630 }
5631
5632 req = ocsp_get_request(p, cert, issuer);
5633 if (req == NULL) {
5634 X509_free(issuer);
5635 OCSP_REQUEST_free(req);
5636 OPENSSL_free(host);
5637 OPENSSL_free(port);
5638 OPENSSL_free(uri);
5639 return NULL;
5640 }
5641
5642 pr_trace_msg(trace_channel, 9,
5643 "parsed OCSP URL '%s' to get host '%s', port '%s', URI '%s'%s",
5644 url, host, port, uri, use_ssl ? ", using TLS" : "");
5645
5646 bio = BIO_new_connect(host);
5647 if (bio == NULL) {
5648 pr_trace_msg(trace_channel, 4, "error allocating connect BIO: %s",
5649 tls_get_errors());
5650
5651 X509_free(issuer);
5652 OCSP_REQUEST_free(req);
5653 OPENSSL_free(host);
5654 OPENSSL_free(port);
5655 OPENSSL_free(uri);
5656 return NULL;
5657 }
5658
5659 BIO_set_conn_port(bio, port);
5660
5661 if (use_ssl) {
5662 BIO *ssl_bio;
5663
5664 ctx = SSL_CTX_new(SSLv23_client_method());
5665 if (ctx == NULL) {
5666 pr_trace_msg(trace_channel, 4, "error allocating SSL context: %s",
5667 tls_get_errors());
5668
5669 X509_free(issuer);
5670 OCSP_REQUEST_free(req);
5671 BIO_free_all(bio);
5672 OPENSSL_free(host);
5673 OPENSSL_free(port);
5674 OPENSSL_free(uri);
5675 return NULL;
5676 }
5677
5678 SSL_CTX_set_mode(ctx, SSL_MODE_AUTO_RETRY);
5679 ssl_bio = BIO_new_ssl(ctx, 1);
5680 bio = BIO_push(ssl_bio, bio);
5681 }
5682
5683 res = ocsp_connect(p, bio, request_timeout);
5684 if (res < 0) {
5685 int xerrno = errno;
5686
5687 pr_trace_msg(trace_channel, 3,
5688 "error connecting to OCSP responder %s:%s: %s", host, port,
5689 strerror(xerrno));
5690
5691 X509_free(issuer);
5692 OCSP_REQUEST_free(req);
5693 BIO_free_all(bio);
5694 OPENSSL_free(host);
5695 OPENSSL_free(port);
5696 OPENSSL_free(uri);
5697
5698 errno = xerrno;
5699 return NULL;
5700 }
5701
5702 resp = ocsp_send_request(p, bio, host, uri, req, request_timeout);
5703
5704 OPENSSL_free(host);
5705 OPENSSL_free(port);
5706 OPENSSL_free(uri);
5707
5708 if (ctx != NULL) {
5709 SSL_CTX_free(ctx);
5710 }
5711
5712 if (bio != NULL) {
5713 BIO_free_all(bio);
5714 }
5715
5716 if (resp == NULL) {
5717 X509_free(issuer);
5718 OCSP_REQUEST_free(req);
5719 return NULL;
5720 }
5721
5722 if (ocsp_check_response(p, cert, issuer, ssl, req, resp) < 0) {
5723 if (errno != ENOSYS) {
5724 X509_free(issuer);
5725 OCSP_REQUEST_free(req);
5726 OCSP_RESPONSE_free(resp);
5727 errno = EINVAL;
5728 return NULL;
5729 }
5730 }
5731
5732 X509_free(issuer);
5733 OCSP_REQUEST_free(req);
5734 return resp;
5735 }
5736
5737 #if OPENSSL_VERSION_NUMBER < 0x10002000L || \
5738 (defined(HAVE_LIBRESSL) && LIBRESSL_VERSION_NUMBER < 0x3050000L)
5739 /* We need to provide our own backport of the ASN1_TIME_diff() function. */
5740 static time_t ASN1_TIME_seconds(const ASN1_TIME *a) {
5741 static const int min[9] = { 0, 0, 1, 1, 0, 0, 0, 0, 0 };
5742 static const int max[9] = { 99, 99, 12, 31, 23, 59, 59, 12, 59 };
5743 time_t t = 0;
5744 char *text;
5745 int text_len;
5746 int i, j, n;
5747 unsigned int nyears, nmons, nhours, nmins, nsecs;
5748
5749 if (a->type != V_ASN1_GENERALIZEDTIME) {
5750 return 0;
5751 }
5752
5753 text_len = a->length;
5754 text = (char *) a->data;
5755
5756 /* GENERALIZEDTIME is similar to UTCTIME except the year is represented
5757 * as YYYY. This stuff treats everything as a two digit field so make
5758 * first two fields 00 to 99
5759 */
5760
5761 if (text_len < 13) {
5762 return 0;
5763 }
5764
5765 nyears = nmons = nhours = nmins = nsecs = 0;
5766
5767 for (i = 0, j = 0; i < 7; i++) {
5768 if (i == 6 &&
5769 (text[j] == 'Z' ||
5770 text[j] == '+' ||
5771 text[j] == '-')) {
5772 i++;
5773 break;
5774 }
5775
5776 if (text[j] < '0' ||
5777 text[j] > '9') {
5778 return 0;
5779 }
5780
5781 n = text[j] - '0';
5782 if (++j > text_len) {
5783 return 0;
5784 }
5785
5786 if (text[j] < '0' ||
5787 text[j] > '9') {
5788 return 0;
5789 }
5790
5791 n = (n * 10) + (text[j] - '0');
5792 if (++j > text_len) {
5793 return 0;
5794 }
5795
5796 if (n < min[i] ||
5797 n > max[i]) {
5798 return 0;
5799 }
5800
5801 switch (i) {
5802 case 0:
5803 /* Years */
5804 nyears = (n * 100);
5805 break;
5806
5807 case 1:
5808 /* Years */
5809 nyears += n;
5810 break;
5811
5812 case 2:
5813 /* Month */
5814 nmons = n - 1;
5815 break;
5816
5817 case 3:
5818 /* Day of month; ignored */
5819 break;
5820
5821 case 4:
5822 /* Hours */
5823 nhours = n;
5824 break;
5825
5826 case 5:
5827 /* Minutes */
5828 nmins = n;
5829 break;
5830
5831 case 6:
5832 /* Seconds */
5833 nsecs = n;
5834 break;
5835 }
5836 }
5837
5838 /* Yes, this is not calendrical accurate. It only needs to be a good
5839 * enough estimation, as it is used (currently) only for determining the
5840 * validity window of an OCSP request (in seconds).
5841 */
5842 t = (nyears * 365 * 86400) + (nmons * 30 * 86400) * (nhours * 3600) + nsecs;
5843
5844 /* Optional fractional seconds: decimal point followed by one or more
5845 * digits.
5846 */
5847 if (text[j] == '.') {
5848 if (++j > text_len) {
5849 return 0;
5850 }
5851
5852 i = j;
5853
5854 while (text[j] >= '0' &&
5855 text[j] <= '9' &&
5856 j <= text_len) {
5857 j++;
5858 }
5859
5860 /* Must have at least one digit after decimal point */
5861 if (i == j) {
5862 return 0;
5863 }
5864 }
5865
5866 if (text[j] == 'Z') {
5867 j++;
5868
5869 } else if (text[j] == '+' ||
5870 text[j] == '-') {
5871 int offsign, offset = 0;
5872
5873 offsign = text[j] == '-' ? -1 : 1;
5874 j++;
5875
5876 if (j + 4 > text_len) {
5877 return 0;
5878 }
5879
5880 for (i = 7; i < 9; i++) {
5881 if (text[j] < '0' ||
5882 text[j] > '9') {
5883 return 0;
5884 }
5885
5886 n = text[j] - '0';
5887 j++;
5888
5889 if (text[j] < '0' ||
5890 text[j] > '9') {
5891 return 0;
5892 }
5893
5894 n = (n * 10) + text[j] - '0';
5895
5896 if (n < min[i] ||
5897 n > max[i]) {
5898 return 0;
5899 }
5900
5901 if (i == 7) {
5902 offset = n * 3600;
5903
5904 } else if (i == 8) {
5905 offset += n * 60;
5906 }
5907
5908 j++;
5909 }
5910
5911 if (offset > 0) {
5912 t += (offset * offsign);
5913 }
5914
5915 } else if (text[j]) {
5916 /* Missing time zone information. */
5917 return 0;
5918 }
5919
5920 return t;
5921 }
5922
5923 static int ASN1_TIME_diff(int *pday, int *psec, const ASN1_TIME *from,
5924 const ASN1_TIME *to) {
5925 time_t from_secs, to_secs, diff_secs;
5926 long diff_days;
5927
5928 from_secs = ASN1_TIME_seconds(from);
5929 if (from_secs == 0) {
5930 return 0;
5931 }
5932
5933 to_secs = ASN1_TIME_seconds(to);
5934 if (to_secs == 0) {
5935 return 0;
5936 }
5937
5938 if (to_secs > from_secs) {
5939 diff_secs = to_secs - from_secs;
5940
5941 } else {
5942 diff_secs = from_secs - to_secs;
5943 }
5944
5945 /* The ASN1_TIME_diff() API in OpenSSL-1.0.2+ offers days and seconds,
5946 * possibly to handle LARGE time differences without overflowing the data
5947 * type for seconds. So we do the same.
5948 */
5949
5950 diff_days = diff_secs % 86400;
5951 diff_secs -= (diff_days * 86400);
5952
5953 if (pday) {
5954 *pday = (int) diff_days;
5955 }
5956
5957 if (psec) {
5958 *psec = diff_secs;
5959 }
5960
5961 return 1;
5962 }
5963 #endif /* Before OpenSSL-1.0.2, or libressl */
5964
5965 static int ocsp_stale_response(pool *p, OCSP_RESPONSE *resp, X509 *cert,
5966 SSL *ssl, time_t age, time_t *expired) {
5967 int res = -1, ocsp_status, stale = FALSE;
5968
5969 ocsp_status = OCSP_response_status(resp);
5970 *expired = 0;
5971
5972 /* If we received a SUCCESSFUL response from the OCSP responder, then
5973 * we consider the response to be stale starting at halfway through its
5974 * validity period (and expired if after the validity period). Otherwise,
5975 * we expire the cached entry after 5 minutes (hardcoded).
5976 */
5977
5978 if (ocsp_status == OCSP_RESPONSE_STATUS_SUCCESSFUL) {
5979 OCSP_BASICRESP *basic_resp = NULL;
5980
5981 basic_resp = OCSP_response_get1_basic(resp);
5982 if (basic_resp != NULL) {
5983 X509 *issuer;
5984
5985 issuer = ocsp_get_issuing_cert(p, cert, ssl);
5986 if (issuer != NULL) {
5987 OCSP_CERTID *cert_id = NULL;
5988
5989 cert_id = OCSP_cert_to_id(NULL, cert, issuer);
5990 if (cert_id != NULL) {
5991 ASN1_GENERALIZEDTIME *this_update = NULL, *next_update = NULL;
5992
5993 res = OCSP_resp_find_status(basic_resp, cert_id, NULL, NULL, NULL,
5994 &this_update, &next_update);
5995 if (res == 1) {
5996 time_t now;
5997
5998 now = time(NULL);
5999
6000 /* If we have passed the nextUpdate time, we have expired. */
6001 if (next_update != NULL) {
6002 res = X509_cmp_time(next_update, &now);
6003 if (res < 0) {
6004 pr_trace_msg(trace_channel, 17,
6005 "cached OCSP response has EXPIRED");
6006 *expired = now;
6007 stale = TRUE;
6008
6009 } else {
6010 int ndays = 0, nsecs = 0;
6011
6012 /* Start requesting fresh responses halfway through the validity
6013 * period:
6014 *
6015 * now > (thisUpdate + ((nextUpdate - thisUpdate) / 2))
6016 *
6017 * or, rephrased slightly differently:
6018 *
6019 * now - ((nextUpdate - thisUpdate) / 2) > thisUpdate
6020 */
6021
6022 res = ASN1_TIME_diff(&ndays, &nsecs, this_update, next_update);
6023 if (res == 1) {
6024 int validity_secs;
6025 time_t refresh_ts;
6026
6027 validity_secs = (ndays * 86400) + nsecs;
6028 refresh_ts = now - (validity_secs / 2);
6029
6030 res = X509_cmp_time(this_update, &refresh_ts);
6031 if (res < 0) {
6032 pr_trace_msg(trace_channel, 17,
6033 "cached OCSP response is stale");
6034 stale = TRUE;
6035 }
6036
6037 } else {
6038 pr_trace_msg(trace_channel, 3, "error computing difference "
6039 "in OCSP response timestamps: %s", tls_get_errors());
6040 }
6041 }
6042
6043 } else {
6044 /* If the OCSP response has no nextUpdate time, then we assume
6045 * it to be stale after one hour (hardcoded).
6046 */
6047 if (age > 3600) {
6048 stale = TRUE;
6049 }
6050 }
6051 }
6052
6053 OCSP_CERTID_free(cert_id);
6054 }
6055
6056 X509_free(issuer);
6057 }
6058
6059 OCSP_BASICRESP_free(basic_resp);
6060
6061 } else {
6062 if (age > 300) {
6063 stale = TRUE;
6064 }
6065 }
6066
6067 } else {
6068 if (age > 300) {
6069 stale = TRUE;
6070 }
6071 }
6072
6073 if (stale == TRUE) {
6074 pr_trace_msg(trace_channel, 8,
6075 "cached %s OCSP response is %s", OCSP_response_status_str(ocsp_status),
6076 *expired > 0 ? "EXPIRED" : "stale");
6077 return 0;
6078 }
6079
6080 return -1;
6081 }
6082
6083 static OCSP_RESPONSE *ocsp_get_cached_response(pool *p,
6084 const char *fingerprint, X509 *cert, SSL *ssl, int *stale) {
6085 OCSP_RESPONSE *resp = NULL;
6086 time_t cache_age = 0, resp_age = 0;
6087 int res;
6088
6089 if (tls_ocsp_cache == NULL) {
6090 errno = ENOSYS;
6091 return NULL;
6092 }
6093
6094 resp = (tls_ocsp_cache->get)(tls_ocsp_cache, fingerprint, &resp_age);
6095 if (resp != NULL) {
6096 time_t now = 0;
6097
6098 time(&now);
6099 cache_age = now - resp_age;
6100 pr_trace_msg(trace_channel, 9,
6101 "found cached OCSP response for fingerprint '%s': %lu %s old",
6102 fingerprint, (unsigned long) cache_age, cache_age != 1 ? "secs" : "sec");
6103 }
6104
6105 if (resp != NULL) {
6106 time_t expired = 0;
6107
6108 res = ocsp_stale_response(p, resp, cert, ssl, cache_age, &expired);
6109 if (expired > 0) {
6110 /* If the response has expired, we need to delete it. */
6111 pr_trace_msg(trace_channel, 5,
6112 "cached OCSP response for fingerprint '%s' expired at %s",
6113 fingerprint, pr_strtime3(p, expired, TRUE));
6114 res = (tls_ocsp_cache->delete)(tls_ocsp_cache, fingerprint);
6115 if (res < 0) {
6116 pr_trace_msg(trace_channel, 3,
6117 "error deleting expired OCSP response from '%s' cache for "
6118 "fingerprint '%s': %s", tls_ocsp_cache->cache_name, fingerprint,
6119 strerror(errno));
6120 }
6121
6122 OCSP_RESPONSE_free(resp);
6123 resp = NULL;
6124 errno = ENOENT;
6125
6126 } else {
6127 if (res == 0) {
6128 *stale = TRUE;
6129
6130 } else {
6131 *stale = FALSE;
6132 }
6133 }
6134
6135 } else {
6136 int xerrno = errno;
6137
6138 pr_trace_msg(trace_channel, 3,
6139 "error retrieving OCSP response from '%s' cache for "
6140 "fingerprint '%s': %s", tls_ocsp_cache->cache_name, fingerprint,
6141 strerror(xerrno));
6142
6143 errno = xerrno;
6144 }
6145
6146 return resp;
6147 }
6148
6149 static int ocsp_add_cached_response(pool *p, const char *fingerprint,
6150 OCSP_RESPONSE *resp) {
6151 int res;
6152 time_t resp_age = 0;
6153
6154 if (fingerprint == NULL ||
6155 tls_ocsp_cache == NULL) {
6156 errno = ENOSYS;
6157 return -1;
6158 }
6159
6160 /* Cache this fake response, so that we don't have to keep redoing this
6161 * for a short amount of time (e.g. 5 minutes).
6162 */
6163 time(&resp_age);
6164 res = (tls_ocsp_cache->add)(tls_ocsp_cache, fingerprint, resp, resp_age);
6165 if (res < 0) {
6166 int xerrno = errno;
6167
6168 pr_trace_msg(trace_channel, 3,
6169 "error adding OCSP response to '%s' cache for fingerprint '%s': %s",
6170 tls_ocsp_cache->cache_name, fingerprint, strerror(xerrno));
6171
6172 errno = xerrno;
6173
6174 } else {
6175 pr_trace_msg(trace_channel, 15,
6176 "added OCSP response to '%s' cache for fingerprint '%s'",
6177 tls_ocsp_cache->cache_name, fingerprint);
6178 }
6179
6180 return res;
6181 }
6182
6183 static int tls_feature_cmp(const ASN1_STRING *str, void *feat_data,
6184 size_t feat_datasz) {
6185 int is_feat = FALSE, res;
6186 ASN1_STRING *feat;
6187
6188 feat = ASN1_STRING_type_new(V_ASN1_OCTET_STRING);
6189 ASN1_STRING_set(feat, feat_data, feat_datasz);
6190
6191 #if OPENSSL_VERSION_NUMBER >= 0x10100000L
6192 res = ASN1_STRING_cmp(str, feat);
6193 #else
6194 res = M_ASN1_OCTET_STRING_cmp(str, feat);
6195 #endif /* Before OpenSSL-1.1.0, or libressl */
6196
6197 if (res == 0) {
6198 is_feat = TRUE;
6199 }
6200 ASN1_STRING_free(feat);
6201
6202 return is_feat;
6203 }
6204
6205 static int tls_cert_must_staple(X509 *cert, int *v2) {
6206 register int i;
6207 int ext_count = 0, must_staple = FALSE;
6208
6209 #if (OPENSSL_VERSION_NUMBER >= 0x10100000L && !defined(HAVE_LIBRESSL)) || \
6210 (defined(HAVE_LIBRESSL) && LIBRESSL_VERSION_NUMBER >= 0x3050000L)
6211 ext_count = X509_get_ext_count(cert);
6212 #else
6213 X509_CINF *ci;
6214 STACK_OF(X509_EXTENSION) *exts;
6215
6216 ci = cert->cert_info;
6217 if (ci == NULL) {
6218 return FALSE;
6219 }
6220
6221 exts = ci->extensions;
6222 ext_count = sk_X509_EXTENSION_num(exts);
6223 #endif /* OpenSSL-1.1.x/LibreSSL-3.5.x or later */
6224
6225 for (i = 0; i < ext_count; i++) {
6226 char buf[1024];
6227 const X509_EXTENSION *ext;
6228 const ASN1_OBJECT *obj;
6229
6230 #if (OPENSSL_VERSION_NUMBER >= 0x10100000L && !defined(HAVE_LIBRESSL)) || \
6231 (defined(HAVE_LIBRESSL) && LIBRESSL_VERSION_NUMBER >= 0x3050000L)
6232 ext = X509_get_ext(cert, i);
6233 #else
6234 ext = sk_X509_EXTENSION_value(exts, i);
6235 #endif /* OpenSSL-1.1.x/LibreSSL-3.5.x or later */
6236
6237 obj = X509_EXTENSION_get_object(ext);
6238 memset(buf, '\0', sizeof(buf));
6239 OBJ_obj2txt(buf, sizeof(buf)-1, obj, 1);
6240
6241 /* Double-check that the OID is that of the "TLS Feature" extension. */
6242 if (strcmp(buf, TLS_X509V3_TLS_FEAT_OID_TEXT) == 0) {
6243 char status_request[] = TLS_X509V3_TLS_FEAT_STATUS_REQUEST;
6244 const ASN1_OCTET_STRING *value;
6245
6246 #if (OPENSSL_VERSION_NUMBER >= 0x10100000L && !defined(HAVE_LIBRESSL)) || \
6247 (defined(HAVE_LIBRESSL) && LIBRESSL_VERSION_NUMBER >= 0x3050000L)
6248 value = X509_EXTENSION_get_data(ext);
6249 #else
6250 value = ext->value;
6251 #endif /* OpenSSL-1.1.x/LibreSSL-3.5.x or later */
6252
6253 /* Is the value of this extension the "status_request" value? */
6254 must_staple = tls_feature_cmp(value, status_request, 5);
6255 if (must_staple != TRUE) {
6256 char status_request_v2[] = TLS_X509V3_TLS_FEAT_STATUS_REQUEST_V2;
6257
6258 /* Is the value of this extension the "status_request_v2" value? */
6259 must_staple = tls_feature_cmp(value, status_request_v2, 5);
6260 if (must_staple == TRUE) {
6261 *v2 = TRUE;
6262 }
6263 }
6264 }
6265 }
6266
6267 return must_staple;
6268 }
6269
6270 static OCSP_RESPONSE *ocsp_get_response(pool *p, SSL *ssl) {
6271 X509 *cert;
6272 const char *fingerprint = NULL;
6273 OCSP_RESPONSE *resp = NULL, *cached_resp = NULL;
6274 int stale_cache = FALSE, use_fake_trylater = FALSE;
6275
6276 /* We need to find a cached OCSP response for the server cert in question,
6277 * thus we need to find out which server cert is used for this session.
6278 */
6279 cert = SSL_get_certificate(ssl);
6280 if (cert != NULL) {
6281 fingerprint = tls_get_fingerprint(p, cert);
6282 if (fingerprint != NULL) {
6283 pr_trace_msg(trace_channel, 3,
6284 "using fingerprint '%s' for server cert", fingerprint);
6285 if (tls_ocsp_cache != NULL) {
6286 cached_resp = ocsp_get_cached_response(p, fingerprint, cert, ssl,
6287 &stale_cache);
6288 if (cached_resp != NULL) {
6289 if (tls_opts & TLS_OPT_ENABLE_DIAGS) {
6290 BIO *diags_bio;
6291
6292 diags_bio = BIO_new(BIO_s_mem());
6293 if (diags_bio != NULL) {
6294 if (OCSP_RESPONSE_print(diags_bio, cached_resp, 0) == 1) {
6295 char *data = NULL;
6296 long datalen = 0;
6297
6298 datalen = BIO_get_mem_data(diags_bio, &data);
6299 if (data != NULL) {
6300 data[datalen] = '\0';
6301 tls_log("cached OCSP response (%ld bytes):\n%s", datalen,
6302 data);
6303 }
6304 }
6305 }
6306
6307 BIO_free(diags_bio);
6308 }
6309
6310 resp = cached_resp;
6311
6312 } else {
6313 int xerrno = errno;
6314
6315 pr_trace_msg(trace_channel, 17,
6316 "no cached OCSP response found in '%s' cache for "
6317 "fingerprint '%s': %s", tls_ocsp_cache->cache_name, fingerprint,
6318 strerror(errno));
6319
6320 errno = xerrno;
6321 }
6322
6323 } else {
6324 /* No TLSStaplingCache configured. */
6325 pr_trace_msg(trace_channel, 17,
6326 "no cached OCSP response found (TLSStaplingCache not configured)");
6327 errno = ENOENT;
6328 }
6329
6330 if (cached_resp == NULL ||
6331 stale_cache == TRUE) {
6332 int xerrno = errno;
6333 OCSP_RESPONSE *fresh_resp = NULL;
6334
6335 if (xerrno == ENOENT ||
6336 stale_cache == TRUE) {
6337 const char *ocsp_url;
6338
6339 if (tls_stapling_responder == NULL) {
6340 ocsp_url = ocsp_get_responder_url(p, cert);
6341 if (ocsp_url != NULL) {
6342 pr_trace_msg(trace_channel, 8,
6343 "found OCSP responder URL '%s' in certificate "
6344 "(fingerprint '%s')", ocsp_url, fingerprint);
6345
6346 } else {
6347 pr_trace_msg(trace_channel, 8,
6348 "no OCSP responder URL found in certificate "
6349 "(fingerprint '%s')", fingerprint);
6350 }
6351
6352 } else {
6353 ocsp_url = tls_stapling_responder;
6354 pr_trace_msg(trace_channel, 8,
6355 "using configured OCSP responder URL '%s'", ocsp_url);
6356 }
6357
6358 if (ocsp_url != NULL) {
6359 fresh_resp = ocsp_request_response(p, cert, ssl, ocsp_url,
6360 tls_stapling_timeout);
6361 if (fresh_resp != NULL) {
6362 resp = fresh_resp;
6363
6364 /* If our previously cached response was stale, delete it so
6365 * that we can cache our new one.
6366 */
6367 if (stale_cache == TRUE) {
6368 int res;
6369
6370 res = (tls_ocsp_cache->delete)(tls_ocsp_cache, fingerprint);
6371 if (res < 0) {
6372 pr_trace_msg(trace_channel, 3,
6373 "error deleting OCSP response from '%s' cache for "
6374 "fingerprint '%s': %s", tls_ocsp_cache->cache_name,
6375 fingerprint, strerror(errno));
6376 }
6377
6378 OCSP_RESPONSE_free(cached_resp);
6379 cached_resp = NULL;
6380 }
6381 }
6382
6383 } else {
6384 pr_trace_msg(trace_channel, 5,
6385 "no OCSP responder URL found in certificate (fingerprint '%s')",
6386 fingerprint);
6387 }
6388
6389 } else {
6390 pr_trace_msg(trace_channel, 5,
6391 "no cached OCSP response found: %s", strerror(xerrno));
6392 }
6393 }
6394 }
6395
6396 } else {
6397 pr_trace_msg(trace_channel, 8, "%s",
6398 "no server certificate found for TLS session");
6399 }
6400
6401 if (resp == NULL) {
6402 use_fake_trylater = TRUE;
6403
6404 /* No proper OCSP response found for stapling; provide a fake tryLater
6405 * response as a fallback. However, if the NoFakeTryLater
6406 * TLSStaplingOption is used, we omit this fake response; some
6407 * implementation e.g. GnuTLS reject/choke on these fake responses.
6408 */
6409 if (tls_stapling_opts & TLS_STAPLING_OPT_NO_FAKE_TRY_LATER) {
6410 use_fake_trylater = FALSE;
6411 }
6412
6413 /* On the other hand, if the server certificate uses the "must staple"
6414 * X509v3 feature, then we MUST provide an OCSP response, even a fake one.
6415 */
6416 if (cert != NULL) {
6417 int must_staple, is_v2 = FALSE;
6418
6419 must_staple = tls_cert_must_staple(cert, &is_v2);
6420 if (must_staple == TRUE) {
6421 pr_trace_msg(trace_channel, 8,
6422 "found status_request%s 'must staple' TLS feature in certificate "
6423 "(fingerprint '%s')", is_v2 ? "_v2" : "", fingerprint);
6424 use_fake_trylater = TRUE;
6425 }
6426 }
6427 }
6428
6429 if (use_fake_trylater) {
6430 pr_trace_msg(trace_channel, 5, "returning fake tryLater OCSP response");
6431
6432 /* If we have not found an OCSP response, then fall back to using
6433 * a fake "tryLater" response.
6434 */
6435 resp = OCSP_response_create(OCSP_RESPONSE_STATUS_TRYLATER, NULL);
6436 if (resp == NULL) {
6437 pr_trace_msg(trace_channel, 1,
6438 "error allocating fake 'tryLater' OCSP response: %s", tls_get_errors());
6439 return NULL;
6440 }
6441 }
6442
6443 /* If this response is not the one we just pulled from the cache, then
6444 * add it.
6445 */
6446 if (resp != cached_resp) {
6447 if (ocsp_add_cached_response(p, fingerprint, resp) < 0) {
6448 if (errno != ENOSYS) {
6449 pr_trace_msg(trace_channel, 3,
6450 "error caching OCSP response: %s", strerror(errno));
6451 }
6452 }
6453 }
6454
6455 return resp;
6456 }
6457
6458 static int tls_ocsp_cb(SSL *ssl, void *user_data) {
6459 OCSP_RESPONSE *resp;
6460 int resp_derlen, reused;
6461 unsigned char *resp_der = NULL;
6462 pool *ocsp_pool;
6463
6464 if (tls_stapling == FALSE) {
6465 /* OCSP stapling disabled; do nothing. */
6466 return SSL_TLSEXT_ERR_NOACK;
6467 }
6468
6469 reused = SSL_session_reused(ssl);
6470 if (reused > 0) {
6471 /* Per RFC 6066, if we are a resumed TLS session, then we should NOT be
6472 * stapling an OCSP response; the original handshake still applies
6473 * (Issue #528).
6474 */
6475 pr_trace_msg(trace_channel, 9,
6476 "OCSP stapling requested but ignored for resumed session, per RFC 6066");
6477 return SSL_TLSEXT_ERR_NOACK;
6478 }
6479
6480 ocsp_pool = make_sub_pool(session.pool);
6481 pr_pool_tag(ocsp_pool, "Session OCSP response pool");
6482
6483 resp = ocsp_get_response(ocsp_pool, ssl);
6484 resp_derlen = i2d_OCSP_RESPONSE(resp, &resp_der);
6485 if (resp_derlen <= 0) {
6486 tls_log("error determining OCSP response length: %s", tls_get_errors());
6487 }
6488 destroy_pool(ocsp_pool);
6489
6490 /* Success or failure, we're done with the OCSP response. */
6491 OCSP_RESPONSE_free(resp);
6492
6493 if (resp_derlen <= 0) {
6494 return SSL_TLSEXT_ERR_NOACK;
6495 }
6496
6497 SSL_set_tlsext_status_ocsp_resp(ssl, resp_der, resp_derlen);
6498 return SSL_TLSEXT_ERR_OK;
6499 }
6500 #endif /* PR_USE_OPENSSL_OCSP */
6501
6502 #if defined(TLS_USE_SESSION_TICKETS)
6503 static int tls_ticket_key_cmp(xasetmember_t *a, xasetmember_t *b) {
6504 struct tls_ticket_key *k1, *k2;
6505
6506 k1 = (struct tls_ticket_key *) a;
6507 k2 = (struct tls_ticket_key *) b;
6508
6509 if (k1->created == k2->created) {
6510 return 0;
6511 }
6512
6513 if (k1->created < k2->created) {
6514 return -1;
6515 }
6516
6517 return 1;
6518 }
6519
6520 static struct tls_ticket_key *create_ticket_key(void) {
6521 struct tls_ticket_key *k;
6522 void *page_ptr = NULL;
6523 size_t pagesz;
6524 char *ptr;
6525 # ifdef HAVE_MLOCK
6526 int res, xerrno = 0;
6527 # endif /* HAVE_MLOCK */
6528
6529 pagesz = sizeof(struct tls_ticket_key);
6530 ptr = tls_get_page(pagesz, &page_ptr);
6531 if (ptr == NULL) {
6532 if (page_ptr != NULL) {
6533 free(page_ptr);
6534 }
6535 return NULL;
6536 }
6537
6538 k = (void *) ptr;
6539 time(&(k->created));
6540
6541 if (RAND_bytes(k->key_name, 16) != 1) {
6542 pr_log_debug(DEBUG1, MOD_TLS_VERSION
6543 ": error generating random bytes: %s", tls_get_errors());
6544 free(page_ptr);
6545 errno = EPERM;
6546 return NULL;
6547 }
6548
6549 if (RAND_bytes(k->cipher_key, 32) != 1) {
6550 pr_log_debug(DEBUG1, MOD_TLS_VERSION
6551 ": error generating random bytes: %s", tls_get_errors());
6552 free(page_ptr);
6553 errno = EPERM;
6554 return NULL;
6555 }
6556
6557 if (RAND_bytes(k->hmac_key, 32) != 1) {
6558 pr_log_debug(DEBUG1, MOD_TLS_VERSION
6559 ": error generating random bytes: %s", tls_get_errors());
6560 free(page_ptr);
6561 errno = EPERM;
6562 return NULL;
6563 }
6564
6565 # ifdef HAVE_MLOCK
6566 PRIVS_ROOT
6567 res = mlock(page_ptr, pagesz);
6568 xerrno = errno;
6569 PRIVS_RELINQUISH
6570
6571 if (res < 0) {
6572 /* Ideally, we would not proceed unless we can ensure this key remains
6573 * only in memory. However, on some systems there may be a limit to the
6574 * amount of locked memory. Erasing the session ticket key here would lead
6575 * to hard-to-debug TLS handshake issues later, for TLSv1.3 sessions which
6576 * use session tickets (and thus need these keys); see Issue #1014.
6577 *
6578 * Thus we now only _try_ to lock the key in memory, but proceed if we
6579 * cannot.
6580 */
6581 pr_log_debug(DEBUG1, MOD_TLS_VERSION
6582 ": error locking session ticket key into memory: %s", strerror(xerrno));
6583 }
6584 # endif /* HAVE_MLOCK */
6585
6586 k->page_ptr = page_ptr;
6587 k->pagesz = pagesz;
6588 return k;
6589 }
6590
6591 static void destroy_ticket_key(struct tls_ticket_key *k) {
6592 void *page_ptr;
6593 size_t pagesz;
6594 # ifdef HAVE_MLOCK
6595 int res, xerrno = 0;
6596 # endif /* HAVE_MLOCK */
6597
6598 if (k == NULL) {
6599 return;
6600 }
6601
6602 page_ptr = k->page_ptr;
6603 pagesz = k->pagesz;
6604
6605 pr_memscrub(k->page_ptr, k->pagesz);
6606
6607 # ifdef HAVE_MLOCK
6608 PRIVS_ROOT
6609 res = munlock(page_ptr, pagesz);
6610 xerrno = errno;
6611 PRIVS_RELINQUISH
6612
6613 if (res < 0) {
6614 pr_log_debug(DEBUG1, MOD_TLS_VERSION
6615 ": error unlocking session ticket key memory: %s", strerror(xerrno));
6616 }
6617 # endif /* HAVE_MLOCK */
6618
6619 free(page_ptr);
6620 }
6621
6622 static int remove_expired_ticket_keys(void) {
6623 struct tls_ticket_key *k = NULL;
6624 int expired_count = 0;
6625 time_t now;
6626
6627 if (tls_ticket_key_curr_count < 2) {
6628 /* Always keep at least one key. */
6629 return 0;
6630 }
6631
6632 time(&now);
6633
6634 for (k = (struct tls_ticket_key *) tls_ticket_keys->xas_list;
6635 k;
6636 k = k->next) {
6637 time_t key_age;
6638
6639 key_age = now - k->created;
6640 if (key_age > tls_ticket_key_max_age) {
6641 if (xaset_remove(tls_ticket_keys, (xasetmember_t *) k) == 0) {
6642 expired_count++;
6643 tls_ticket_key_curr_count--;
6644 }
6645 }
6646 }
6647
6648 return expired_count;
6649 }
6650
6651 static int remove_oldest_ticket_key(void) {
6652 struct tls_ticket_key *k = NULL;
6653 int res;
6654
6655 if (tls_ticket_key_curr_count < 2) {
6656 /* Always keep at least one key. */
6657 return 0;
6658 }
6659
6660 /* Remove the last ticket key in the set. */
6661 for (k = (struct tls_ticket_key *) tls_ticket_keys->xas_list;
6662 k && k->next != NULL;
6663 k = k->next);
6664
6665 res = xaset_remove(tls_ticket_keys, (xasetmember_t *) k);
6666 if (res == 0) {
6667 tls_ticket_key_curr_count--;
6668 }
6669
6670 return res;
6671 }
6672
6673 static int add_ticket_key(struct tls_ticket_key *k) {
6674 int res;
6675
6676 res = remove_expired_ticket_keys();
6677 if (res > 0) {
6678 pr_trace_msg(trace_channel, 9, "removed %d expired %s", res,
6679 res != 1 ? "keys" : "key");
6680 }
6681
6682 if (tls_ticket_key_curr_count == tls_ticket_key_max_count) {
6683 res = remove_oldest_ticket_key();
6684 if (res < 0) {
6685 return -1;
6686 }
6687 }
6688
6689 res = xaset_insert_sort(tls_ticket_keys, (xasetmember_t *) k, FALSE);
6690 if (res == 0) {
6691 tls_ticket_key_curr_count++;
6692 }
6693
6694 return res;
6695 }
6696
6697 /* Note: This lookup routine is where we might look in external storage,
6698 * e.g. Redis/memcache, for clustered/shared pool of ticket keys generated by
6699 * other servers.
6700 */
6701 static struct tls_ticket_key *get_ticket_key(unsigned char *key_name,
6702 size_t key_namelen) {
6703 struct tls_ticket_key *k = NULL;
6704
6705 if (tls_ticket_keys == NULL) {
6706 return NULL;
6707 }
6708
6709 for (k = (struct tls_ticket_key *) tls_ticket_keys->xas_list;
6710 k;
6711 k = k->next) {
6712 if (memcmp(key_name, k->key_name, key_namelen) == 0) {
6713 break;
6714 }
6715 }
6716
6717 return k;
6718 }
6719
6720 static int new_ticket_key_timer_cb(CALLBACK_FRAME) {
6721 struct tls_ticket_key *k;
6722
6723 pr_log_debug(DEBUG9, MOD_TLS_VERSION
6724 ": generating new TLS session ticket key");
6725
6726 k = create_ticket_key();
6727 if (k == NULL) {
6728 pr_log_debug(DEBUG0, MOD_TLS_VERSION
6729 ": unable to generate new session ticket key: %s", strerror(errno));
6730
6731 } else {
6732 add_ticket_key(k);
6733 }
6734
6735 /* Always restart this timer. */
6736 return 1;
6737 }
6738
6739 /* Remember that mlock(2) locks are not inherited across forks, thus
6740 * we want to renew those locks for session processes.
6741 */
6742 static void lock_ticket_keys(void) {
6743 # ifdef HAVE_MLOCK
6744 struct tls_ticket_key *k;
6745
6746 if (tls_ticket_keys == NULL) {
6747 return;
6748 }
6749
6750 for (k = (struct tls_ticket_key *) tls_ticket_keys->xas_list;
6751 k;
6752 k = k->next) {
6753 if (k->locked == FALSE) {
6754 int res, xerrno = 0;
6755
6756 PRIVS_ROOT
6757 res = mlock(k->page_ptr, k->pagesz);
6758 xerrno = errno;
6759 PRIVS_RELINQUISH
6760
6761 if (res < 0) {
6762 pr_log_debug(DEBUG1, MOD_TLS_VERSION
6763 ": error locking session ticket key into memory: %s",
6764 strerror(xerrno));
6765
6766 } else {
6767 k->locked = TRUE;
6768 }
6769 }
6770 }
6771 # endif /* HAVE_MLOCK */
6772 }
6773
6774 static void scrub_ticket_keys(void) {
6775 struct tls_ticket_key *k, *next_k;
6776
6777 if (tls_ticket_keys == NULL) {
6778 return;
6779 }
6780
6781 for (k = (struct tls_ticket_key *) tls_ticket_keys->xas_list; k; k = next_k) {
6782 next_k = k->next;
6783 destroy_ticket_key(k);
6784 }
6785
6786 tls_ticket_keys = NULL;
6787 }
6788
6789 /* TLS session ticket _key_ callback; not to be confused with the TLSv1.3
6790 * session ticket callbacks.
6791 */
6792 static int tls_ticket_key_cb(SSL *ssl, unsigned char *key_name,
6793 unsigned char *iv, EVP_CIPHER_CTX *cipher_ctx, HMAC_CTX *hmac_ctx,
6794 int mode) {
6795 struct tls_ticket_key *k;
6796 char *key_name_str;
6797
6798 /* Note: should we have a list of ciphers from which we randomly choose,
6799 * when creating a key? I.e. should the keys themselves hold references
6800 * to their ciphers, digests?
6801 */
6802 const EVP_CIPHER *cipher = EVP_aes_256_cbc();
6803 # ifdef OPENSSL_NO_SHA256
6804 const EVP_MD *md = EVP_sha1();
6805 # else
6806 const EVP_MD *md = EVP_sha256();
6807 # endif
6808
6809 pr_trace_msg(trace_channel, 19,
6810 "handling session ticket key request on %s session (%s mode)",
6811 SSL_get_version(ssl), mode ? "encrypt" : "decrypt");
6812
6813 if (mode == 1) {
6814 int ticket_key_len, sess_key_len;
6815
6816 if (tls_ticket_keys == NULL) {
6817 return -1;
6818 }
6819
6820 /* Creating a new session ticket. Always use the first key in the set. */
6821 k = (struct tls_ticket_key *) tls_ticket_keys->xas_list;
6822
6823 key_name_str = pr_str_bin2hex(session.pool, k->key_name, 16,
6824 PR_STR_FL_HEX_USE_LC);
6825
6826 pr_trace_msg(trace_channel, 3,
6827 "TLS session ticket: encrypting using key name '%s' for %s session",
6828 key_name_str, SSL_session_reused(ssl) ? "reused" : "new");
6829
6830 /* Warn loudly if the ticket key we are using is not as strong (based on
6831 * cipher key length) as the one negotiated for the session.
6832 */
6833 ticket_key_len = EVP_CIPHER_key_length(cipher) * 8;
6834 sess_key_len = SSL_get_cipher_bits(ssl, NULL);
6835 if (ticket_key_len < sess_key_len) {
6836 pr_log_pri(PR_LOG_INFO, MOD_TLS_VERSION
6837 ": WARNING: TLS session tickets encrypted with weaker key than "
6838 "session: ticket key = %s (%d bytes), session key = %s (%d bytes)",
6839 OBJ_nid2sn(EVP_CIPHER_type(cipher)), ticket_key_len,
6840 SSL_get_cipher_name(ssl), sess_key_len);
6841 }
6842
6843 if (RAND_bytes(iv, EVP_CIPHER_iv_length(cipher)) != 1) {
6844 pr_trace_msg(trace_channel, 3,
6845 "unable to initialize session ticket key IV: %s", tls_get_errors());
6846 return -1;
6847 }
6848
6849 if (EVP_EncryptInit_ex(cipher_ctx, cipher, NULL, k->cipher_key, iv) != 1) {
6850 pr_trace_msg(trace_channel, 3,
6851 "unable to initialize session ticket key cipher: %s", tls_get_errors());
6852 return -1;
6853 }
6854
6855 # if OPENSSL_VERSION_NUMBER >= 0x10000001L
6856 if (HMAC_Init_ex(hmac_ctx, k->hmac_key, 32, md, NULL) != 1) {
6857 pr_trace_msg(trace_channel, 3,
6858 "unable to initialize session ticket key HMAC: %s", tls_get_errors());
6859 return -1;
6860 }
6861 # else
6862 HMAC_Init_ex(hmac_ctx, k->hmac_key, 32, md, NULL);
6863 # endif /* OpenSSL-1.0.0 and later */
6864
6865 memcpy(key_name, k->key_name, 16);
6866 return 1;
6867 }
6868
6869 if (mode == 0) {
6870 struct tls_ticket_key *newest_key;
6871 time_t key_age, now;
6872
6873 key_name_str = pr_str_bin2hex(session.pool, key_name, 16,
6874 PR_STR_FL_HEX_USE_LC);
6875
6876 k = get_ticket_key(key_name, 16);
6877 if (k == NULL) {
6878 /* No matching key found. */
6879 pr_trace_msg(trace_channel, 3,
6880 "TLS session ticket: decrypting ticket using key name '%s': "
6881 "key not found", key_name_str);
6882 return 0;
6883 }
6884
6885 pr_trace_msg(trace_channel, 3,
6886 "TLS session ticket: decrypting ticket using key name '%s'",
6887 key_name_str);
6888
6889 # if OPENSSL_VERSION_NUMBER >= 0x10000001L
6890 if (HMAC_Init_ex(hmac_ctx, k->hmac_key, 32, md, NULL) != 1) {
6891 pr_trace_msg(trace_channel, 3,
6892 "unable to initialize session ticket key HMAC: %s", tls_get_errors());
6893 return 0;
6894 }
6895 # else
6896 HMAC_Init_ex(hmac_ctx, k->hmac_key, 32, md, NULL);
6897 # endif /* OpenSSL-1.0.0 and later */
6898
6899 if (EVP_DecryptInit_ex(cipher_ctx, cipher, NULL, k->cipher_key, iv) != 1) {
6900 pr_trace_msg(trace_channel, 3,
6901 "unable to initialize session ticket key cipher: %s", tls_get_errors());
6902 return 0;
6903 }
6904
6905 /* If the key we found is older than the newest key, tell the client to
6906 * get a new ticket. This helps to reduce the window of time a given
6907 * ticket key is used.
6908 */
6909 time(&now);
6910 key_age = now - k->created;
6911
6912 newest_key = (struct tls_ticket_key *) tls_ticket_keys->xas_list;
6913 if (k != newest_key) {
6914 time_t newest_age;
6915
6916 newest_age = now - newest_key->created;
6917
6918 pr_trace_msg(trace_channel, 3,
6919 "key '%s' age (%lu %s) older than newest key (%lu %s), requesting "
6920 "ticket renewal", key_name_str, (unsigned long) key_age,
6921 key_age != 1 ? "secs" : "sec", (unsigned long) newest_age,
6922 newest_age != 1 ? "secs" : "sec");
6923 return 2;
6924 }
6925
6926 # if defined(TLS1_3_VERSION)
6927 /* If we're a TLSv1.3 session, aim for single-use tickets, and indicate
6928 * that the client should get a new ticket. Will the FTPS client
6929 * Do The Right Thing(tm), and use this new ticket for future data
6930 * transfers?
6931 */
6932 if (SSL_version(ssl) == TLS1_3_VERSION) {
6933 return 2;
6934 }
6935 # endif /* TLS1_3_VERSION */
6936
6937 return 1;
6938 }
6939
6940 pr_trace_msg(trace_channel, 3, "TLS session ticket: unknown mode (%d)", mode);
6941 return -1;
6942 }
6943 #endif /* TLS_USE_SESSION_TICKETS */
6944
6945 #if defined(PR_USE_OPENSSL_SSL_SESSION_TICKET_CALLBACK)
6946 static int tls_generate_session_ticket_cb(SSL *ssl, void *user_data) {
6947 SSL_SESSION *ssl_session;
6948
6949 ssl_session = SSL_get_session(ssl);
6950
6951 if (SSL_SESSION_set1_ticket_appdata(ssl_session,
6952 tls_ctrl_ticket_appdata, tls_ctrl_ticket_appdata_len) != 1) {
6953 tls_log("error setting ticket appdata for ticket: %s",
6954 tls_get_errors());
6955
6956 } else {
6957 if (pr_trace_get_level(trace_channel) >= 19) {
6958 register unsigned int i;
6959 const unsigned char *ticket_appdata;
6960 BIO *bio;
6961 char *text = NULL;
6962 long text_len = 0;
6963
6964 bio = BIO_new(BIO_s_mem());
6965 BIO_printf(bio, "set %lu bytes of ticket appdata (",
6966 (unsigned long) tls_ctrl_ticket_appdata_len);
6967 ticket_appdata = tls_ctrl_ticket_appdata;
6968 for (i = 0; i < tls_ctrl_ticket_appdata_len; i++) {
6969 BIO_printf(bio, "%02x", ticket_appdata[i]);
6970 }
6971 BIO_printf(bio, ") for %s session ticket", SSL_get_version(ssl));
6972
6973 text_len = BIO_get_mem_data(bio, &text);
6974 if (text != NULL) {
6975 text[text_len] = '\0';
6976 pr_trace_msg(trace_channel, 19, "%.*s", (int) text_len, text);
6977 }
6978
6979 BIO_free(bio);
6980
6981 } else {
6982 pr_trace_msg(trace_channel, 9,
6983 "set %lu bytes of ticket appdata for %s session ticket",
6984 (unsigned long) tls_ctrl_ticket_appdata_len, SSL_get_version(ssl));
6985 }
6986 }
6987
6988 return 1;
6989 }
6990
6991 static void get_session_ticket_appdata(SSL *ssl, SSL_SESSION *ssl_session) {
6992 void *appdata = NULL;
6993 size_t appdata_len = 0;
6994
6995 if (SSL_SESSION_get0_ticket_appdata(ssl_session, &appdata,
6996 &appdata_len) != 1) {
6997 tls_log("error obtaining ticket appdata from data transfer ticket: %s",
6998 tls_get_errors());
6999 tls_data_ticket_appdata_len = 0;
7000
7001 return;
7002 }
7003
7004 /* Make sure the ticket appdata length is what we expect; we might have
7005 * received a ticket with different appdata that what we want.
7006 */
7007 if (appdata_len != tls_data_ticket_appdatasz) {
7008 tls_log("received %s session ticket with unexpected appdata "
7009 "(expected %lu bytes, got %lu), ignoring", SSL_get_version(ssl),
7010 (unsigned long) tls_data_ticket_appdatasz, (unsigned long) appdata_len);
7011 tls_data_ticket_appdata_len = 0;
7012
7013 return;
7014 }
7015
7016 /* Note that we need to copy the appdata into our own buffers for later
7017 * comparisons; the OpenSSL docs do not do a good job of describing the
7018 * lifetime of the pointer/buffer returned by
7019 * SSL_SESSION_get0_ticket_appdata.
7020 */
7021 tls_data_ticket_appdata_len = appdata_len;
7022 memcpy((void *) tls_data_ticket_appdata, appdata, appdata_len);
7023
7024 if (pr_trace_get_level(trace_channel) >= 19) {
7025 register unsigned int i;
7026 const unsigned char *ticket_appdata;
7027 BIO *bio;
7028 char *text = NULL;
7029 long text_len = 0;
7030
7031 bio = BIO_new(BIO_s_mem());
7032 BIO_printf(bio, "obtained %lu bytes of ticket appdata (",
7033 (unsigned long) tls_data_ticket_appdata_len);
7034 ticket_appdata = tls_data_ticket_appdata;
7035 for (i = 0; i < tls_data_ticket_appdata_len; i++) {
7036 BIO_printf(bio, "%02x", ticket_appdata[i]);
7037 }
7038 BIO_printf(bio, ") from %s session ticket", SSL_get_version(ssl));
7039
7040 text_len = BIO_get_mem_data(bio, &text);
7041 if (text != NULL) {
7042 text[text_len] = '\0';
7043 pr_trace_msg(trace_channel, 19, "%.*s", (int) text_len, text);
7044 }
7045
7046 BIO_free(bio);
7047
7048 } else {
7049 pr_trace_msg(trace_channel, 9,
7050 "obtained %lu bytes of ticket appdata from %s session ticket",
7051 (unsigned long) tls_data_ticket_appdata_len, SSL_get_version(ssl));
7052 }
7053 }
7054
7055 static SSL_TICKET_RETURN tls_decrypt_session_ticket_data_xfer_cb(SSL *ssl,
7056 SSL_SESSION *ssl_session, const unsigned char *key_name, size_t key_namelen,
7057 SSL_TICKET_STATUS status, void *user_data) {
7058 SSL_TICKET_RETURN res;
7059
7060 switch (status) {
7061 case SSL_TICKET_EMPTY:
7062 case SSL_TICKET_NO_DECRYPT:
7063 tls_data_ticket_appdata_len = 0;
7064 res = SSL_TICKET_RETURN_IGNORE_RENEW;
7065 break;
7066
7067 case SSL_TICKET_SUCCESS:
7068 get_session_ticket_appdata(ssl, ssl_session);
7069 res = SSL_TICKET_RETURN_USE;
7070 break;
7071
7072 case SSL_TICKET_SUCCESS_RENEW:
7073 get_session_ticket_appdata(ssl, ssl_session);
7074 res = SSL_TICKET_RETURN_USE_RENEW;
7075 break;
7076
7077 default:
7078 res = SSL_TICKET_RETURN_IGNORE;
7079 }
7080
7081 return res;
7082 }
7083
7084 /* Note that we want to _use_ any provided TLSv1.3 session tickets, so that
7085 * data transfers can reuse the TLS session from the control connection. BUT
7086 * we do not want to _renew_ (or issue) new tickets, as that will may tickle
7087 * the ECONNRESET bug (see Issue #959) for some data transfers.
7088 */
7089 static SSL_TICKET_RETURN tls_decrypt_session_ticket_data_upload_cb(SSL *ssl,
7090 SSL_SESSION *ssl_session, const unsigned char *key_name, size_t key_namelen,
7091 SSL_TICKET_STATUS status, void *user_data) {
7092 SSL_TICKET_RETURN res;
7093 int renew_tickets = TRUE;
7094
7095 /* Avoid using the given SSL_SESSION pointer unless the status indicates that
7096 * that pointer is valid (Issue #1063).
7097 */
7098
7099 if (status != SSL_TICKET_EMPTY &&
7100 status != SSL_TICKET_NO_DECRYPT) {
7101 int ssl_version;
7102
7103 ssl_version = SSL_SESSION_get_protocol_version(ssl_session);
7104 # if defined(TLS1_3_VERSION)
7105 if (ssl_version == TLS1_3_VERSION) {
7106 pr_trace_msg(trace_channel, 29,
7107 "suppressing renewal of TLSv1.3 tickets for data transfers");
7108 renew_tickets = FALSE;
7109 }
7110 }
7111 # endif /* TLS1_3_VERSION */
7112
7113 switch (status) {
7114 case SSL_TICKET_EMPTY:
7115 case SSL_TICKET_NO_DECRYPT:
7116 tls_data_ticket_appdata_len = 0;
7117 res = SSL_TICKET_RETURN_IGNORE_RENEW;
7118 if (renew_tickets == FALSE) {
7119 res = SSL_TICKET_RETURN_IGNORE;
7120 }
7121 break;
7122
7123 case SSL_TICKET_SUCCESS:
7124 get_session_ticket_appdata(ssl, ssl_session);
7125 res = SSL_TICKET_RETURN_USE;
7126 break;
7127
7128 case SSL_TICKET_SUCCESS_RENEW:
7129 get_session_ticket_appdata(ssl, ssl_session);
7130 res = SSL_TICKET_RETURN_USE_RENEW;
7131 if (renew_tickets == FALSE) {
7132 res = SSL_TICKET_RETURN_USE;
7133 }
7134 break;
7135
7136 default:
7137 res = SSL_TICKET_RETURN_IGNORE;
7138 }
7139
7140 return res;
7141 }
7142 #endif /* PR_USE_OPENSSL_SSL_SESSION_TICKET_CALLBACK */
7143
7144 #if defined(PR_USE_OPENSSL_ECC) && \
7145 OPENSSL_VERSION_NUMBER < 0x10100000L
7146 static EC_KEY *tls_ecdh_cb(SSL *ssl, int is_export, int keylen) {
7147 static EC_KEY *ecdh = NULL;
7148 static int init = 0;
7149
7150 if (init == 0) {
7151 ecdh = EC_KEY_new();
7152
7153 if (ecdh != NULL) {
7154 EC_KEY_set_group(ecdh,
7155 EC_GROUP_new_by_curve_name(NID_X9_62_prime256v1));
7156 }
7157
7158 init = 1;
7159 }
7160
7161 return ecdh;
7162 }
7163 #endif /* PR_USE_OPENSSL_ECC and before OpenSSL-1.1.x */
7164
7165 #if defined(PR_USE_OPENSSL_ALPN)
7166 static int tls_alpn_select_cb(SSL *ssl,
7167 const unsigned char **selected_proto, unsigned char *selected_protolen,
7168 const unsigned char *advertised_proto, unsigned int advertised_protolen,
7169 void *user_data) {
7170 register unsigned int i;
7171 struct tls_next_proto *next_proto;
7172 char *selected_alpn;
7173
7174 pr_trace_msg(trace_channel, 9, "%s",
7175 "ALPN protocols advertised by client:");
7176 for (i = 0; i < advertised_protolen; i++) {
7177 pr_trace_msg(trace_channel, 9,
7178 " %.*s", advertised_proto[i], &(advertised_proto[i+1]));
7179 i += advertised_proto[i] + 1;
7180 }
7181
7182 next_proto = user_data;
7183
7184 if (SSL_select_next_proto(
7185 (unsigned char **) selected_proto, selected_protolen,
7186 next_proto->encoded_proto, next_proto->encoded_protolen,
7187 advertised_proto, advertised_protolen) != OPENSSL_NPN_NEGOTIATED) {
7188 pr_trace_msg(trace_channel, 9,
7189 "no common ALPN protocols found (no '%s' in ALPN protocols)",
7190 next_proto->proto);
7191 return SSL_TLSEXT_ERR_NOACK;
7192 }
7193
7194 selected_alpn = pstrndup(session.pool, (char *) *selected_proto,
7195 *selected_protolen);
7196 pr_trace_msg(trace_channel, 9,
7197 "selected ALPN protocol '%s'", selected_alpn);
7198 return SSL_TLSEXT_ERR_OK;
7199 }
7200 #endif /* ALPN */
7201
7202 #if defined(PR_USE_OPENSSL_NPN)
7203 static int tls_npn_advertised_cb(SSL *ssl,
7204 const unsigned char **advertise_proto, unsigned int *advertise_protolen,
7205 void *user_data) {
7206 struct tls_next_proto *next_proto;
7207
7208 next_proto = user_data;
7209
7210 pr_trace_msg(trace_channel, 9,
7211 "advertising NPN protocol '%s'", next_proto->proto);
7212 *advertise_proto = next_proto->encoded_proto;
7213 *advertise_protolen = next_proto->encoded_protolen;
7214
7215 return SSL_TLSEXT_ERR_OK;
7216 }
7217 #endif /* NPN */
7218
7219 /* Post 0.9.7a, RSA blinding is turned on by default, so there is no need to
7220 * do this manually.
7221 */
7222 #if OPENSSL_VERSION_NUMBER < 0x0090702fL
7223 static void tls_blinding_on(SSL *ssl) {
7224 EVP_PKEY *pkey = NULL;
7225 RSA *rsa = NULL;
7226
7227 /* RSA keys are subject to timing attacks. To attempt to make such
7228 * attacks harder, use RSA blinding.
7229 */
7230
7231 pkey = SSL_get_privatekey(ssl);
7232
7233 if (pkey)
7234 rsa = EVP_PKEY_get1_RSA(pkey);
7235
7236 if (rsa) {
7237 if (RSA_blinding_on(rsa, NULL) != 1) {
7238 tls_log("error setting RSA blinding: %s",
7239 ERR_error_string(ERR_get_error(), NULL));
7240
7241 } else {
7242 tls_log("set RSA blinding on");
7243 }
7244
7245 /* Now, "free" the RSA pointer, to properly decrement the reference
7246 * counter.
7247 */
7248 RSA_free(rsa);
7249
7250 } else {
7251
7252 /* The administrator may have configured DSA keys rather than RSA keys.
7253 * In this case, there is nothing to do.
7254 */
7255 }
7256
7257 return;
7258 }
7259 #endif
7260
7261 static int tls_set_fips(void) {
7262 if (pr_define_exists("TLS_USE_FIPS") != TRUE) {
7263 return 0;
7264 }
7265
7266 #ifdef OPENSSL_FIPS
7267 if (!FIPS_mode()) {
7268 /* Make sure OpenSSL is set to use the default RNG, as per an email
7269 * discussion on the OpenSSL developer list:
7270 *
7271 * "The internal FIPS logic uses the default RNG to see the FIPS RNG
7272 * as part of the self test process..."
7273 */
7274 RAND_set_rand_method(NULL);
7275
7276 if (!FIPS_mode_set(1)) {
7277 const char *errstr;
7278
7279 errstr = tls_get_errors();
7280 tls_log("unable to use FIPS mode: %s", errstr);
7281 pr_log_pri(PR_LOG_ERR, MOD_TLS_VERSION
7282 ": unable to use FIPS mode: %s", errstr);
7283
7284 errno = EPERM;
7285 return -1;
7286 }
7287
7288 pr_log_pri(PR_LOG_NOTICE, MOD_TLS_VERSION ": FIPS mode enabled");
7289
7290 } else {
7291 pr_log_pri(PR_LOG_DEBUG, MOD_TLS_VERSION ": FIPS mode already enabled");
7292 }
7293 #else
7294 pr_log_pri(PR_LOG_WARNING, MOD_TLS_VERSION ": FIPS mode requested, but " OPENSSL_VERSION_TEXT " not built with FIPS support");
7295 #endif /* OPENSSL_FIPS */
7296
7297 return 0;
7298 }
7299
7300 static SSL_CTX *tls_init_ctx(server_rec *s) {
7301 int ssl_opts = tls_ssl_opts;
7302 long ssl_mode = 0;
7303 SSL_CTX *ctx;
7304 #if defined(TLS_USE_SESSION_TICKETS)
7305 config_rec *c;
7306 #endif /* TLS_USE_SESSION_TICKETS */
7307
7308 ctx = SSL_CTX_new(SSLv23_server_method());
7309 if (ctx == NULL) {
7310 pr_log_debug(DEBUG0, MOD_TLS_VERSION ": error: SSL_CTX_new(): %s",
7311 tls_get_errors());
7312 return NULL;
7313 }
7314
7315 #if OPENSSL_VERSION_NUMBER > 0x000906000L
7316 /* The SSL_MODE_AUTO_RETRY mode was added in 0.9.6. */
7317 ssl_mode |= SSL_MODE_AUTO_RETRY;
7318 #endif
7319
7320 #if OPENSSL_VERSION_NUMBER >= 0x1000001fL
7321 /* The SSL_MODE_RELEASE_BUFFERS mode was added in 1.0.0a. */
7322 ssl_mode |= SSL_MODE_RELEASE_BUFFERS;
7323 #endif
7324
7325 if (ssl_mode != 0) {
7326 SSL_CTX_set_mode(ctx, ssl_mode);
7327 }
7328
7329 /* If using OpenSSL-0.9.7 or greater, prevent session resumptions on
7330 * renegotiations (more secure).
7331 */
7332 #if OPENSSL_VERSION_NUMBER > 0x000907000L
7333 ssl_opts |= SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION;
7334 #endif
7335
7336 /* Disable SSL compression. */
7337 #ifdef SSL_OP_NO_COMPRESSION
7338 ssl_opts |= SSL_OP_NO_COMPRESSION;
7339 #endif /* SSL_OP_NO_COMPRESSION */
7340
7341 #if defined(PR_USE_OPENSSL_ECC)
7342 # if defined(SSL_OP_SINGLE_ECDH_USE)
7343 ssl_opts |= SSL_OP_SINGLE_ECDH_USE;
7344 # endif
7345 # if defined(SSL_OP_SAFARI_ECDHE_ECDSA_BUG)
7346 ssl_opts |= SSL_OP_SAFARI_ECDHE_ECDSA_BUG;
7347 # endif
7348 #endif /* ECC support */
7349
7350 #if defined(SSL_OP_CIPHER_SERVER_PREFERENCE)
7351 /* Use the server cipher preferences by default. */
7352 if (tls_use_server_cipher_preference == TRUE) {
7353 ssl_opts |= SSL_OP_CIPHER_SERVER_PREFERENCE;
7354 }
7355 #endif /* SSL_OP_CIPHER_SERVER_PREFERENCE */
7356
7357 SSL_CTX_set_options(ctx, ssl_opts);
7358
7359 #if defined(TLS_USE_SESSION_TICKETS)
7360 c = find_config(s->conf, CONF_PARAM, "TLSSessionTicketKeys", FALSE);
7361 if (c != NULL) {
7362 tls_ticket_key_max_age = *((unsigned int *) c->argv[0]);
7363 tls_ticket_key_max_count = *((unsigned int *) c->argv[1]);
7364 }
7365
7366 /* Generate a random session ticket key, if necessary. Maybe this list
7367 * of keys could be stored as ex/app data in the SSL_CTX?
7368 */
7369 if (tls_ticket_keys == NULL) {
7370 struct tls_ticket_key *k;
7371 unsigned int new_ticket_key_intvl;
7372
7373 pr_log_debug(DEBUG9, MOD_TLS_VERSION
7374 ": generating initial TLS session ticket key");
7375
7376 k = create_ticket_key();
7377 if (k == NULL) {
7378 pr_log_debug(DEBUG0, MOD_TLS_VERSION
7379 ": unable to generate initial session ticket key: %s",
7380 strerror(errno));
7381
7382 } else {
7383 tls_ticket_keys = xaset_create(permanent_pool, tls_ticket_key_cmp);
7384 add_ticket_key(k);
7385 }
7386
7387 /* Also register a timer, to generate new keys every hour (or just under
7388 * the max age of a key, whichever is smaller).
7389 */
7390
7391 new_ticket_key_intvl = 3600;
7392 if (tls_ticket_key_max_age < new_ticket_key_intvl) {
7393 /* Try to get a new ticket a little before one expires. */
7394 new_ticket_key_intvl = tls_ticket_key_max_age - 1;
7395 }
7396
7397 pr_log_debug(DEBUG9, MOD_TLS_VERSION
7398 ": scheduling new TLS session ticket key every %d %s",
7399 new_ticket_key_intvl, new_ticket_key_intvl != 1 ? "secs" : "sec");
7400
7401 pr_timer_add(new_ticket_key_intvl, -1, &tls_module, new_ticket_key_timer_cb,
7402 "New TLS Session Ticket Key");
7403
7404 } else {
7405 struct tls_ticket_key *k;
7406
7407 /* Generate a new key on restart, as part of a good cryptographic
7408 * hygiene.
7409 */
7410 pr_log_debug(DEBUG9, MOD_TLS_VERSION ": generating TLS session ticket key");
7411
7412 k = create_ticket_key();
7413 if (k == NULL) {
7414 pr_log_debug(DEBUG0, MOD_TLS_VERSION
7415 ": unable to generate new session ticket key: %s", strerror(errno));
7416
7417 } else {
7418 add_ticket_key(k);
7419 }
7420 }
7421 #endif /* TLS_USE_SESSION_TICKETS */
7422
7423 #if defined(PR_USE_OPENSSL_SSL_SESSION_TICKET_CALLBACK)
7424 if (SSL_CTX_set_session_ticket_cb(ctx, tls_generate_session_ticket_cb,
7425 tls_decrypt_session_ticket_data_xfer_cb, NULL) != 1) {
7426 pr_trace_msg(trace_channel, 3,
7427 "error setting TLSv1.3 session ticket callback: %s", tls_get_errors());
7428 }
7429 #endif /* PR_USE_OPENSSL_SSL_SESSION_TICKET_CALLBACK */
7430
7431 SSL_CTX_set_tmp_dh_callback(ctx, tls_dh_cb);
7432
7433 #ifdef PR_USE_OPENSSL_ECC
7434 /* If using OpenSSL 1.0.2 or later, let it automatically choose the
7435 * correct/best curve, rather than having to hardcode a fallback.
7436 */
7437 # if defined(SSL_CTX_set_ecdh_auto)
7438 SSL_CTX_set_ecdh_auto(ctx, 1);
7439 # endif
7440 #endif /* PR_USE_OPENSSL_ECC */
7441
7442 /* We always install an info callback, in order to watch for
7443 * client-initiated session renegotiations (Bug#3324). If EnableDiags
7444 * is enabled, that info callback will also log the OpenSSL diagnostic
7445 * information.
7446 */
7447 SSL_CTX_set_info_callback(ctx, tls_info_cb);
7448
7449 return ctx;
7450 }
7451
7452 static const char *tls_get_proto_str(pool *p, unsigned int protos,
7453 unsigned int *count) {
7454 char *proto_str = "";
7455 unsigned int nproto = 0;
7456
7457 if (protos & TLS_PROTO_SSL_V3) {
7458 proto_str = pstrcat(p, proto_str, *proto_str ? ", " : "",
7459 "SSLv3", NULL);
7460 nproto++;
7461 }
7462
7463 if (protos & TLS_PROTO_TLS_V1) {
7464 proto_str = pstrcat(p, proto_str, *proto_str ? ", " : "",
7465 "TLSv1", NULL);
7466 nproto++;
7467 }
7468
7469 if (protos & TLS_PROTO_TLS_V1_1) {
7470 proto_str = pstrcat(p, proto_str, *proto_str ? ", " : "",
7471 "TLSv1.1", NULL);
7472 nproto++;
7473 }
7474
7475 if (protos & TLS_PROTO_TLS_V1_2) {
7476 proto_str = pstrcat(p, proto_str, *proto_str ? ", " : "",
7477 "TLSv1.2", NULL);
7478 nproto++;
7479 }
7480
7481 if (protos & TLS_PROTO_TLS_V1_3) {
7482 proto_str = pstrcat(p, proto_str, *proto_str ? ", " : "",
7483 "TLSv1.3", NULL);
7484 nproto++;
7485 }
7486
7487 *count = nproto;
7488 return proto_str;
7489 }
7490
7491 /* Construct the options value that disables all unsupported protocols. */
7492 static int get_disabled_protocols(unsigned int supported_protocols) {
7493 int disabled_protocols;
7494
7495 /* First, create an options value where ALL protocols are disabled. */
7496 disabled_protocols = (SSL_OP_NO_SSLv2|SSL_OP_NO_SSLv3|SSL_OP_NO_TLSv1);
7497
7498 #ifdef SSL_OP_NO_TLSv1_1
7499 disabled_protocols |= SSL_OP_NO_TLSv1_1;
7500 #endif
7501 #ifdef SSL_OP_NO_TLSv1_2
7502 disabled_protocols |= SSL_OP_NO_TLSv1_2;
7503 #endif
7504 #ifdef SSL_OP_NO_TLSv1_3
7505 disabled_protocols |= SSL_OP_NO_TLSv1_3;
7506 #endif
7507
7508 /* Now, based on the given bitset of supported protocols, clear the
7509 * necessary bits.
7510 */
7511
7512 if (supported_protocols & TLS_PROTO_SSL_V3) {
7513 disabled_protocols &= ~SSL_OP_NO_SSLv3;
7514 }
7515
7516 if (supported_protocols & TLS_PROTO_TLS_V1) {
7517 disabled_protocols &= ~SSL_OP_NO_TLSv1;
7518 }
7519
7520 #if OPENSSL_VERSION_NUMBER >= 0x10001000L
7521 if (supported_protocols & TLS_PROTO_TLS_V1_1) {
7522 disabled_protocols &= ~SSL_OP_NO_TLSv1_1;
7523 }
7524
7525 if (supported_protocols & TLS_PROTO_TLS_V1_2) {
7526 disabled_protocols &= ~SSL_OP_NO_TLSv1_2;
7527 }
7528 #endif /* OpenSSL-1.0.1 or later */
7529
7530 #ifdef SSL_OP_NO_TLSv1_3
7531 if (supported_protocols & TLS_PROTO_TLS_V1_3) {
7532 disabled_protocols &= ~SSL_OP_NO_TLSv1_3;
7533 }
7534 #endif /* OpenSSL 1.1.1 or later */
7535
7536 return disabled_protocols;
7537 }
7538
7539 static int tls_get_block(conn_t *conn) {
7540 int flags;
7541
7542 flags = fcntl(conn->rfd, F_GETFL);
7543 if (flags & O_NONBLOCK) {
7544 return FALSE;
7545 }
7546
7547 return TRUE;
7548 }
7549
7550 static int tls_compare_session_ids(SSL_SESSION *ctrl_sess,
7551 SSL_SESSION *data_sess) {
7552 int res = -1;
7553
7554 #if OPENSSL_VERSION_NUMBER < 0x000907000L
7555 /* In the OpenSSL source code, SSL_SESSION_cmp() ultimately uses memcmp(3)
7556 * to check, and thus returns memcmp(3)'s return value.
7557 */
7558 res = SSL_SESSION_cmp(ctrl_sess, data_sess);
7559 #else
7560 const unsigned char *ctrl_sess_id, *data_sess_id;
7561 unsigned int ctrl_sess_id_len, data_sess_id_len;
7562
7563 # if OPENSSL_VERSION_NUMBER > 0x000908000L
7564 ctrl_sess_id = (const unsigned char *) SSL_SESSION_get_id(ctrl_sess,
7565 &ctrl_sess_id_len);
7566 data_sess_id = (const unsigned char *) SSL_SESSION_get_id(data_sess,
7567 &data_sess_id_len);
7568 # else
7569 /* XXX Directly accessing these fields cannot be a Good Thing. */
7570 ctrl_sess_id = ctrl_sess->session_id;
7571 ctrl_sess_id_len = ctrl_sess->session_id_length;
7572 data_sess_id = data_sess->session_id;
7573 data_sess_id_len = data_sess->session_id_length;
7574 # endif
7575
7576 /* We might use SSL_has_matching_session_id, except that it does not
7577 * appear to be reliable using older versions of OpenSSL (e.g. 1.0.1t in
7578 * my local testing). So just compare the raw session IDs ourselves.
7579 */
7580 if (ctrl_sess_id_len == data_sess_id_len) {
7581 res = memcmp(ctrl_sess_id, data_sess_id, ctrl_sess_id_len);
7582 if (res != 0) {
7583 res = -1;
7584 }
7585
7586 } else {
7587 res = -1;
7588 }
7589 #endif
7590
7591 return res;
7592 }
7593
7594 static int tls_accept(conn_t *conn, unsigned char on_data) {
7595 static unsigned char logged_data = FALSE;
7596 int blocking, res = 0, xerrno = 0;
7597 long cache_mode = 0;
7598 char *subj = NULL;
7599 SSL *ssl = NULL;
7600 BIO *rbio = NULL, *wbio = NULL;
7601
7602 if (ssl_ctx == NULL) {
7603 tls_log("%s", "unable to start session: null SSL_CTX");
7604 return -1;
7605 }
7606
7607 ssl = SSL_new(ssl_ctx);
7608 if (ssl == NULL) {
7609 tls_log("error: unable to start session: %s",
7610 ERR_error_string(ERR_get_error(), NULL));
7611 return -2;
7612 }
7613
7614 /* This works with either rfd or wfd (I hope). */
7615 rbio = BIO_new_socket(conn->rfd, FALSE);
7616 wbio = BIO_new_socket(conn->wfd, FALSE);
7617
7618 SSL_set_bio(ssl, rbio, wbio);
7619
7620 #if !defined(OPENSSL_NO_TLSEXT)
7621 if (tls_opts & TLS_OPT_ENABLE_DIAGS) {
7622 /* Note that older OpenSSL versions, e.g. 0.9.8, do not implement this
7623 * callback. Newer versions which DO implement it do as via a macro.
7624 */
7625 # ifdef SSL_set_tlsext_debug_callback
7626 SSL_set_tlsext_debug_callback(ssl, tls_tlsext_cb);
7627 # endif /* SSL_set_tlsext_debug_callback */
7628 }
7629 #endif /* !OPENSSL_NO_TLSEXT */
7630
7631 /* If configured, set a timer for the handshake. */
7632 if (tls_handshake_timeout) {
7633 tls_handshake_timed_out = FALSE;
7634 tls_handshake_timer_id = pr_timer_add(tls_handshake_timeout, -1,
7635 &tls_module, tls_handshake_timeout_cb, "SSL/TLS handshake");
7636 }
7637
7638 if (on_data) {
7639 /* Make sure that TCP_NODELAY is enabled for the handshake. */
7640 if (pr_inet_set_proto_nodelay(conn->pool, conn, 1) < 0) {
7641 pr_trace_msg(trace_channel, 9,
7642 "error enabling TCP_NODELAY on data conn: %s", strerror(errno));
7643 }
7644
7645 /* Make sure that TCP_CORK (aka TCP_NOPUSH) is DISABLED for the handshake.
7646 * This socket option is set via the pr_inet_set_proto_opts() call made
7647 * in mod_core, upon handling the PASV/EPSV command.
7648 */
7649 if (pr_inet_set_proto_cork(conn->wfd, 0) < 0) {
7650 pr_trace_msg(trace_channel, 9,
7651 "error disabling TCP_CORK on data conn: %s", strerror(errno));
7652 }
7653
7654 cache_mode = SSL_CTX_get_session_cache_mode(ssl_ctx);
7655 if (cache_mode != SSL_SESS_CACHE_OFF) {
7656 /* Disable STORING of any new session IDs in the session cache. We DO
7657 * want to allow LOOKUP of session IDs in the session cache, however.
7658 */
7659 long data_cache_mode;
7660 data_cache_mode = SSL_SESS_CACHE_SERVER|SSL_SESS_CACHE_NO_INTERNAL_STORE;
7661 SSL_CTX_set_session_cache_mode(ssl_ctx, data_cache_mode);
7662 }
7663
7664 #if !defined(OPENSSL_NO_TLSEXT) && defined(TLSEXT_MAXLEN_host_name)
7665 /* Disable any SNI handling for data TLS sessions. */
7666 pr_trace_msg(trace_channel, 5, "ignoring SNI for data connections");
7667 SSL_CTX_set_tlsext_servername_callback(ssl_ctx, NULL);
7668 SSL_CTX_set_tlsext_servername_arg(ssl_ctx, NULL);
7669 #endif /* !OPENSSL_NO_TLSEXT */
7670
7671 #if defined(PR_USE_OPENSSL_SSL_SESSION_TICKET_CALLBACK)
7672 tls_data_ticket_appdata_len = 0;
7673
7674 if (session.curr_cmd_id == PR_CMD_APPE_ID ||
7675 session.curr_cmd_id == PR_CMD_STOR_ID ||
7676 session.curr_cmd_id == PR_CMD_STOU_ID) {
7677
7678 /* Some versions of SSL_do_handshake have a bug in how they handle the
7679 * TLS 1.3 handshake on the server side: after the handshake finishes,
7680 * they automatically send session tickets, even though the client may
7681 * not be expecting data to arrive at this point and sending it could
7682 * cause a deadlock or lost data. This applies at least to OpenSSL 1.1.1c
7683 * and earlier, and the OpenSSL devs currently have no plans to fix it:
7684 *
7685 * https://github.com/openssl/openssl/issues/7948
7686 * https://github.com/openssl/openssl/issues/7967
7687 *
7688 * The correct behavior is to wait to send session tickets on the
7689 * first call to SSL_write. (This is what BoringSSL does.) So, we
7690 * programmatically disable sending/renewing TLSv1.3 session tickets
7691 * for the TLS session on data transfers, specifically uploads
7692 * (Issue #959).
7693 *
7694 * Why is this needed for FTPS uploads only, and not downloads or
7695 * directory listings? An FTPS upload is the only case where we
7696 * are a) the server, and b) in a read-only role. Thus we are not
7697 * expected to _send_ any TCP data, including session tickets.
7698 */
7699 if (SSL_CTX_set_session_ticket_cb(ssl_ctx, tls_generate_session_ticket_cb,
7700 tls_decrypt_session_ticket_data_upload_cb, NULL) != 1) {
7701 pr_trace_msg(trace_channel, 3, "error setting TLSv1.3 session ticket "
7702 "callback for '%s' data transfer: %s", session.curr_cmd,
7703 tls_get_errors());
7704 }
7705 } else {
7706 /* Restore default session ticket callbacks for any other transfer. */
7707 if (SSL_CTX_set_session_ticket_cb(ssl_ctx, tls_generate_session_ticket_cb,
7708 tls_decrypt_session_ticket_data_xfer_cb, NULL) != 1) {
7709 pr_trace_msg(trace_channel, 3, "error setting TLSv1.3 session ticket "
7710 "callback for '%s' data transfer: %s", session.curr_cmd,
7711 tls_get_errors());
7712 }
7713 }
7714 #endif /* PR_USE_OPENSSL_SSL_SESSION_TICKET_CALLBACK */
7715 }
7716
7717 retry:
7718
7719 blocking = tls_get_block(conn);
7720 if (blocking) {
7721 /* Put the connection in non-blocking mode for the duration of the
7722 * TLS handshake. This lets us handle EAGAIN/retries better (i.e.
7723 * without spinning in a tight loop and consuming the CPU).
7724 */
7725 if (pr_inet_set_nonblock(conn->pool, conn) < 0) {
7726 pr_trace_msg(trace_channel, 3,
7727 "error making %s connection nonblocking: %s",
7728 on_data ? "data" : "ctrl", strerror(errno));
7729 }
7730 }
7731
7732 pr_signals_handle();
7733
7734 pr_trace_msg(trace_channel, 17, "calling SSL_accept() on %s conn fd %d",
7735 on_data ? "data" : "ctrl", conn->rfd);
7736 res = SSL_accept(ssl);
7737 xerrno = errno;
7738
7739 pr_trace_msg(trace_channel, 17, "SSL_accept() returned %d for %s conn fd %d",
7740 res, on_data ? "data" : "ctrl", conn->rfd);
7741
7742 if (blocking) {
7743 /* Return the connection to blocking mode. */
7744 if (pr_inet_set_block(conn->pool, conn) < 0) {
7745 pr_trace_msg(trace_channel, 3,
7746 "error making %s connection blocking: %s",
7747 on_data ? "data" : "ctrl", strerror(errno));
7748 }
7749 }
7750
7751 if (res < 1) {
7752 const char *msg = "unable to accept TLS connection";
7753 int errcode;
7754
7755 errcode = SSL_get_error(ssl, res);
7756 pr_signals_handle();
7757
7758 if (tls_handshake_timed_out) {
7759 tls_log("TLS negotiation timed out (%u seconds)", tls_handshake_timeout);
7760 tls_end_sess(ssl, on_data ? session.d : session.c, 0);
7761 return -4;
7762 }
7763
7764 switch (errcode) {
7765 case SSL_ERROR_WANT_READ:
7766 pr_trace_msg(trace_channel, 17,
7767 "WANT_READ encountered while accepting %s conn on fd %d, "
7768 "waiting to read data", on_data ? "data" : "ctrl", conn->rfd);
7769 tls_readmore(conn->rfd);
7770 goto retry;
7771
7772 case SSL_ERROR_WANT_WRITE:
7773 pr_trace_msg(trace_channel, 17,
7774 "WANT_WRITE encountered while accepting %s conn on fd %d, "
7775 "waiting to send data", on_data ? "data" : "ctrl", conn->rfd);
7776 tls_writemore(conn->rfd);
7777 goto retry;
7778
7779 case SSL_ERROR_ZERO_RETURN:
7780 tls_log("%s: TLS connection closed", msg);
7781 break;
7782
7783 case SSL_ERROR_WANT_X509_LOOKUP:
7784 tls_log("%s: needs X509 lookup", msg);
7785 break;
7786
7787 case SSL_ERROR_SYSCALL: {
7788 int xerrcode;
7789
7790 /* Check to see if the OpenSSL error queue has info about this. */
7791 xerrcode = ERR_peek_error();
7792
7793 if (xerrcode == 0) {
7794 /* The OpenSSL error queue doesn't have any more info, so we'll
7795 * examine the SSL_accept() return value itself.
7796 */
7797
7798 if (res == 0) {
7799 /* EOF */
7800 tls_log("%s: received EOF that violates protocol", msg);
7801 tls_log("%s: usually this indicates an FTP-aware router, NAT, or "
7802 "firewall interfering with the TLS handshake", msg);
7803
7804 } else if (res == -1) {
7805 /* Check errno */
7806 tls_log("%s: system call error: [%d] %s", msg, xerrno,
7807 strerror(xerrno));
7808 }
7809
7810 } else {
7811 tls_log("%s: system call error: %s", msg, tls_get_errors());
7812 }
7813
7814 break;
7815 }
7816
7817 case SSL_ERROR_SSL: {
7818 pool *tmp_pool;
7819 unsigned long ssl_errcode = ERR_peek_error();
7820
7821 tls_log("%s: protocol error: %s", msg, tls_get_errors());
7822
7823 tmp_pool = make_sub_pool(conn->pool);
7824
7825 /* The error codes in the OpenSSL error queue are "packed"; we need
7826 * to unpack them to get the reason value.
7827 *
7828 * Try to provide more context for the most commonly ocurring/reported
7829 * handshake errors here.
7830 */
7831
7832 switch (ERR_GET_REASON(ssl_errcode)) {
7833 case SSL_R_UNKNOWN_PROTOCOL: {
7834 long ssl_opts;
7835 char *proto_str = "";
7836
7837 ssl_opts = SSL_get_options(ssl);
7838
7839 #if SSL_OP_NO_SSLv2
7840 if (ssl_opts & SSL_OP_NO_SSLv2) {
7841 proto_str = pstrcat(tmp_pool, proto_str, *proto_str ? ", " : "",
7842 "SSLv2", NULL);
7843 }
7844 #endif /* SSLv2 */
7845
7846 if (ssl_opts & SSL_OP_NO_SSLv3) {
7847 proto_str = pstrcat(tmp_pool, proto_str, *proto_str ? ", " : "",
7848 "SSLv3", NULL);
7849 }
7850
7851 if (ssl_opts & SSL_OP_NO_TLSv1) {
7852 proto_str = pstrcat(tmp_pool, proto_str, *proto_str ? ", " : "",
7853 "TLSv1", NULL);
7854 }
7855
7856 #ifdef SSL_OP_NO_TLSv1_1
7857 if (ssl_opts & SSL_OP_NO_TLSv1_1) {
7858 proto_str = pstrcat(tmp_pool, proto_str, *proto_str ? ", " : "",
7859 "TLSv1.1", NULL);
7860 }
7861 #endif /* TLSv1.1 */
7862
7863 #ifdef SSL_OP_NO_TLSv1_2
7864 if (ssl_opts & SSL_OP_NO_TLSv1_2) {
7865 proto_str = pstrcat(tmp_pool, proto_str, *proto_str ? ", " : "",
7866 "TLSv1.2", NULL);
7867 }
7868 #endif /* TLSv1.2 */
7869
7870 #ifdef SSL_OP_NO_TLSv1_3
7871 if (ssl_opts & SSL_OP_NO_TLSv1_3) {
7872 proto_str = pstrcat(tmp_pool, proto_str, *proto_str ? ", " : "",
7873 "TLSv1.3", NULL);
7874 }
7875 #endif /* TLSv1.3 */
7876
7877 tls_log("%s: perhaps client requested disabled TLS protocol "
7878 "version: %s", msg, proto_str);
7879 break;
7880 }
7881
7882 case SSL_R_NO_SHARED_CIPHER: {
7883 # if OPENSSL_VERSION_NUMBER >= 0x10101000L && \
7884 defined(TLS1_3_VERSION)
7885 if (tlsv13_cipher_suite != NULL) {
7886 tls_log("%s: client does not support any cipher from "
7887 "'TLSCipherSuite %s' or 'TLSCipherSuite TLSv1.3 %s' "
7888 "(see `openssl ciphers` for full list)",
7889 msg, tls_cipher_suite, tlsv13_cipher_suite);
7890
7891 } else {
7892 tls_log("%s: client does not support any cipher from "
7893 "'TLSCipherSuite %s' (see `openssl ciphers %s` for full list)",
7894 msg, tls_cipher_suite, tls_cipher_suite);
7895 }
7896 # else
7897 tls_log("%s: client does not support any cipher from "
7898 "'TLSCipherSuite %s' (see `openssl ciphers %s` for full list)",
7899 msg, tls_cipher_suite, tls_cipher_suite);
7900 # endif /* TLS1_3_VERSION */
7901
7902 break;
7903 }
7904
7905 case SSL_R_PEER_DID_NOT_RETURN_A_CERTIFICATE: {
7906 if (tls_flags & TLS_SESS_VERIFY_CLIENT_REQUIRED) {
7907 tls_log("%s: client did not provide certificate, but one is "
7908 "required via 'TLSVerifyClient on'", msg);
7909 }
7910 break;
7911 }
7912
7913 #if defined(SSL_R_VERSION_TOO_LOW) && !defined(HAVE_LIBRESSL)
7914 case SSL_R_VERSION_TOO_LOW: {
7915 int client_version;
7916
7917 client_version = SSL_client_version(ssl);
7918 switch (client_version) {
7919 # if defined(SSL3_VERSION) && defined(OPENSSL_NO_SSL3)
7920 case SSL3_VERSION:
7921 tls_log("%s: %s lacks support for client requested TLS "
7922 "protocol version: %s", msg, OPENSSL_VERSION_TEXT,
7923 SSL_get_version(ssl));
7924 break;
7925 # endif /* SSLv3 and OPENSSL_NO_SSL3 */
7926
7927 # if defined(TLS1_VERSION) && defined(OPENSSL_NO_TLS1)
7928 case TLS1_VERSION:
7929 tls_log("%s: %s lacks support for client requested TLS "
7930 "protocol version: %s", msg, OPENSSL_VERSION_TEXT,
7931 SSL_get_version(ssl));
7932 break;
7933 # endif /* TLSv1 and OPENSSL_NO_TLS1 */
7934
7935 # if defined(TLS1_1_VERSION) && defined(OPENSSL_NO_TLS1_1)
7936 case TLS1_1_VERSION:
7937 tls_log("%s: %s lacks support for client requested TLS "
7938 "protocol version: %s", msg, OPENSSL_VERSION_TEXT,
7939 SSL_get_version(ssl));
7940 break;
7941 # endif /* TLSv1.1 and OPENSSL_NO_TLS1_1 */
7942
7943 # if defined(TLS1_2_VERSION) && defined(OPENSSL_NO_TLS1_2)
7944 case TLS1_2_VERSION:
7945 tls_log("%s: %s lacks support for client requested TLS "
7946 "protocol version: %s", msg, OPENSSL_VERSION_TEXT,
7947 SSL_get_version(ssl));
7948 break;
7949 # endif /* TLSv1.2 and OPENSSL_NO_TLS1_2 */
7950
7951 # if defined(TLS1_3_VERSION) && defined(OPENSSL_NO_TLS1_3)
7952 case TLS1_3_VERSION:
7953 tls_log("%s: %s lacks support for client requested TLS "
7954 "protocol version: %s", msg, OPENSSL_VERSION_TEXT,
7955 SSL_get_version(ssl));
7956 break;
7957 # endif /* TLSv1.3 and OPENSSL_NO_TLS1_3 */
7958
7959 default:
7960 tls_log("%s: perhaps client requested unsupported TLS protocol "
7961 "version: %s", msg, SSL_get_version(ssl));
7962 }
7963 break;
7964 }
7965 #endif /* SSL_R_VERSION_TOO_LOW */
7966
7967 default:
7968 break;
7969 }
7970
7971 destroy_pool(tmp_pool);
7972 break;
7973 }
7974 }
7975
7976 if (on_data) {
7977 pr_event_generate("mod_tls.data-handshake-failed", &errcode);
7978
7979 } else {
7980 pr_event_generate("mod_tls.ctrl-handshake-failed", &errcode);
7981 }
7982
7983 tls_end_sess(ssl, on_data ? session.d : session.c, 0);
7984 return -3;
7985 }
7986
7987 pr_trace_msg(trace_channel, 17,
7988 "TLS handshake on %s conn fd %d COMPLETED", on_data ? "data" : "ctrl",
7989 conn->rfd);
7990
7991 if (on_data) {
7992 /* Disable TCP_NODELAY, now that the handshake is done. */
7993 if (pr_inet_set_proto_nodelay(conn->pool, conn, 0) < 0) {
7994 pr_trace_msg(trace_channel, 9,
7995 "error disabling TCP_NODELAY on data conn: %s", strerror(errno));
7996 }
7997
7998 /* Re-enable TCP_CORK (aka TCP_NOPUSH), now that the handshake is done. */
7999 if (pr_inet_set_proto_cork(conn->wfd, 1) < 0) {
8000 pr_trace_msg(trace_channel, 9,
8001 "error re-enabling TCP_CORK on data conn: %s", strerror(errno));
8002 }
8003
8004 if (cache_mode != SSL_SESS_CACHE_OFF) {
8005 /* Restore the previous session cache mode. */
8006 SSL_CTX_set_session_cache_mode(ssl_ctx, cache_mode);
8007 }
8008 }
8009
8010 /* Disable the handshake timer. */
8011 pr_timer_remove(tls_handshake_timer_id, &tls_module);
8012
8013 #if defined(PR_USE_OPENSSL_NPN)
8014 /* Which NPN protocol was selected, if any? */
8015 {
8016 const unsigned char *npn = NULL;
8017 unsigned int npn_len = 0;
8018
8019 SSL_get0_next_proto_negotiated(ssl, &npn, &npn_len);
8020 if (npn != NULL &&
8021 npn_len > 0) {
8022 pr_trace_msg(trace_channel, 9,
8023 "negotiated NPN '%.*s'", npn_len, npn);
8024
8025 } else {
8026 pr_trace_msg(trace_channel, 9, "%s", "no NPN negotiated");
8027 }
8028 }
8029 #endif /* NPN */
8030
8031 #if defined(PR_USE_OPENSSL_ALPN)
8032 /* Which ALPN protocol was selected, if any? */
8033 {
8034 const unsigned char *alpn = NULL;
8035 unsigned int alpn_len = 0;
8036
8037 SSL_get0_alpn_selected(ssl, &alpn, &alpn_len);
8038 if (alpn != NULL &&
8039 alpn_len > 0) {
8040 pr_trace_msg(trace_channel, 9,
8041 "selected ALPN '%.*s'", alpn_len, alpn);
8042 } else {
8043 pr_trace_msg(trace_channel, 9, "%s", "no ALPN selected");
8044 }
8045 }
8046 #endif /* ALPN */
8047
8048 /* Manually update the raw bytes counters with the network IO from the
8049 * TLS handshake.
8050 */
8051 session.total_raw_in += (BIO_number_read(rbio) +
8052 BIO_number_read(wbio));
8053 session.total_raw_out += (BIO_number_written(rbio) +
8054 BIO_number_written(wbio));
8055
8056 /* Stash the SSL object in the pointers of the correct NetIO streams. */
8057 if (conn == session.c) {
8058 pr_buffer_t *strm_buf;
8059
8060 ctrl_ssl = ssl;
8061
8062 if (pr_table_add(tls_ctrl_rd_nstrm->notes,
8063 pstrdup(tls_ctrl_rd_nstrm->strm_pool, TLS_NETIO_NOTE),
8064 ssl, sizeof(SSL *)) < 0) {
8065 if (errno != EEXIST) {
8066 tls_log("error stashing '%s' note on ctrl read stream: %s",
8067 TLS_NETIO_NOTE, strerror(errno));
8068 }
8069 }
8070
8071 if (pr_table_add(tls_ctrl_wr_nstrm->notes,
8072 pstrdup(tls_ctrl_wr_nstrm->strm_pool, TLS_NETIO_NOTE),
8073 ssl, sizeof(SSL *)) < 0) {
8074 if (errno != EEXIST) {
8075 tls_log("error stashing '%s' note on ctrl write stream: %s",
8076 TLS_NETIO_NOTE, strerror(errno));
8077 }
8078 }
8079
8080 #if OPENSSL_VERSION_NUMBER >= 0x009080dfL
8081 if (SSL_get_secure_renegotiation_support(ssl) == 1) {
8082 /* If the peer indicates that it can support secure renegotiations, log
8083 * this fact for reference.
8084 *
8085 * Note that while we could use this fact to automatically enable the
8086 * AllowClientRenegotiations TLSOption, in light of CVE-2011-1473
8087 * (where malicious SSL/TLS clients can abuse the fact that session
8088 * renegotiations are more computationally intensive for servers than
8089 * for clients and repeatedly request renegotiations to create a
8090 * denial of service attach), we won't enable AllowClientRenegotiations
8091 * programmatically. The admin will still need to explicitly configure
8092 * that.
8093 */
8094 tls_log("%s", "client supports secure renegotiations");
8095 }
8096 #endif /* OpenSSL 0.9.8m and later */
8097
8098 /* Clear any data from the NetIO stream buffers which may have been read
8099 * in before the SSL/TLS handshake occurred (Bug#3624).
8100 */
8101 strm_buf = tls_ctrl_rd_nstrm->strm_buf;
8102 if (strm_buf != NULL) {
8103 strm_buf->current = NULL;
8104 strm_buf->remaining = strm_buf->buflen;
8105 }
8106
8107 } else if (conn == session.d) {
8108 pr_buffer_t *strm_buf;
8109
8110 if (pr_table_add(tls_data_rd_nstrm->notes,
8111 pstrdup(tls_data_rd_nstrm->strm_pool, TLS_NETIO_NOTE),
8112 ssl, sizeof(SSL *)) < 0) {
8113 if (errno != EEXIST) {
8114 tls_log("error stashing '%s' note on data read stream: %s",
8115 TLS_NETIO_NOTE, strerror(errno));
8116 }
8117 }
8118
8119 if (pr_table_add(tls_data_wr_nstrm->notes,
8120 pstrdup(tls_data_wr_nstrm->strm_pool, TLS_NETIO_NOTE),
8121 ssl, sizeof(SSL *)) < 0) {
8122 if (errno != EEXIST) {
8123 tls_log("error stashing '%s' note on data write stream: %s",
8124 TLS_NETIO_NOTE, strerror(errno));
8125 }
8126 }
8127
8128 /* Clear any data from the NetIO stream buffers which may have been read
8129 * in before the SSL/TLS handshake occurred (Bug#3624).
8130 */
8131 strm_buf = tls_data_rd_nstrm->strm_buf;
8132 if (strm_buf != NULL) {
8133 strm_buf->current = NULL;
8134 strm_buf->remaining = strm_buf->buflen;
8135 }
8136 }
8137
8138 #if OPENSSL_VERSION_NUMBER == 0x009080cfL
8139 /* In OpenSSL-0.9.8l, SSL session renegotiations are automatically
8140 * disabled. Thus if the admin explicitly configured support for
8141 * client-initiated renegotiations via the AllowClientRenegotiations
8142 * TLSOption, then we need to do some hackery to enable renegotiations.
8143 */
8144 if (tls_opts & TLS_OPT_ALLOW_CLIENT_RENEGOTIATIONS) {
8145 ssl->s3->flags |= SSL3_FLAGS_ALLOW_UNSAFE_LEGACY_RENEGOTIATION;
8146 }
8147 #endif
8148
8149 /* TLS handshake on the control channel... */
8150 if (on_data == FALSE) {
8151 int reused;
8152
8153 subj = tls_get_subj_name(ctrl_ssl);
8154 if (subj != NULL) {
8155 tls_log("Client: %s", subj);
8156 }
8157
8158 if (tls_flags & TLS_SESS_VERIFY_CLIENT_REQUIRED) {
8159 /* Now we can go on with our post-handshake, application level
8160 * requirement checks.
8161 */
8162 if (tls_check_client_cert(ssl, conn) < 0) {
8163 tls_end_sess(ssl, session.c, 0);
8164 ctrl_ssl = NULL;
8165 return -1;
8166 }
8167 }
8168
8169 reused = SSL_session_reused(ssl);
8170
8171 tls_log("%s connection accepted, using cipher %s (%d bits%s)",
8172 SSL_get_version(ssl), SSL_get_cipher_name(ssl),
8173 SSL_get_cipher_bits(ssl, NULL),
8174 reused > 0 ? ", resumed session" : "");
8175
8176 /* Setup the TLS environment variables and notes. */
8177 tls_setup_environ(session.pool, ssl);
8178 tls_setup_notes(session.pool, ssl);
8179
8180 if (reused > 0) {
8181 pr_log_writefile(tls_logfd, MOD_TLS_VERSION, "%s",
8182 "client reused previous TLS session for control connection");
8183 }
8184
8185 /* TLS handshake on the data channel... */
8186 } else {
8187
8188 /* We won't check for session reuse for data connections when either
8189 * a) the NoSessionReuseRequired TLSOption has been configured, or
8190 * b) the CCC command has been used (Bug#3465).
8191 */
8192 if (!(tls_opts & TLS_OPT_NO_SESSION_REUSE_REQUIRED) &&
8193 !(tls_flags & TLS_SESS_HAVE_CCC)) {
8194 int reused;
8195 SSL_SESSION *ctrl_sess;
8196
8197 /* Ensure that the following conditions are met:
8198 *
8199 * 1. The client reused an existing TLS session
8200 * 2. The reused TLS session matches the TLS session from the control
8201 * connection.
8202 *
8203 * Make sure we handle session tickets, too, especially for TLSv1.3.
8204 *
8205 * Shutdown the TLS session unless the conditions are met. By
8206 * requiring these conditions, we make sure that the client which is
8207 * talking to us on the control connection is indeed the same client
8208 * that is using this data connection. Without these checks, a
8209 * malicious client might be able to hijack/steal the data transfer.
8210 */
8211
8212 reused = SSL_session_reused(ssl);
8213 if (reused != 1) {
8214 tls_log("%s", "client did not reuse TLS session, rejecting data "
8215 "connection (see the NoSessionReuseRequired TLSOptions parameter)");
8216 tls_end_sess(ssl, session.d, 0);
8217 pr_table_remove(tls_data_rd_nstrm->notes, TLS_NETIO_NOTE, NULL);
8218 pr_table_remove(tls_data_wr_nstrm->notes, TLS_NETIO_NOTE, NULL);
8219 return -1;
8220 }
8221
8222 tls_log("%s", "client reused TLS session for data connection");
8223
8224 ctrl_sess = SSL_get_session(ctrl_ssl);
8225 if (ctrl_sess != NULL) {
8226 SSL_SESSION *data_sess;
8227
8228 data_sess = SSL_get_session(ssl);
8229 if (data_sess != NULL) {
8230 int matching_sess = -1;
8231 long sess_created, sess_expires;
8232 time_t now;
8233
8234 matching_sess = tls_compare_session_ids(ctrl_sess, data_sess);
8235
8236 #ifdef TLS1_3_VERSION
8237 /* TLSv1.3 sessions will show session reuse, but NOT matching session
8238 * IDs. Why? TLSv1.3 completely redid session resumption, and now
8239 * favors session tickets (and stateless servers) rather than
8240 * session IDs (and stateful server session caches).
8241 *
8242 * To prove session reuse via TLSv1.3 session tickets, then, we use
8243 * ticket appdata to generate a random "FTP session ID" that we stick
8244 * in the control session tickets; the data session tickets presented
8245 * should have the exact same appdata, if they are coming from our
8246 * expected control session.
8247 *
8248 * However, we cannot just assume that session tickets will be used
8249 * only for TLSv1.3 sessions. It is possible that session tickets,
8250 * rather than session IDs, will be used for TLSv1.2 and earlier
8251 * sessions as well.
8252 */
8253 if (matching_sess != 0) {
8254
8255 # if defined(PR_USE_OPENSSL_SSL_SESSION_TICKET_CALLBACK)
8256 if (tls_ctrl_ticket_appdata_len > 0 &&
8257 tls_data_ticket_appdata_len > 0 &&
8258 tls_ctrl_ticket_appdata_len == tls_data_ticket_appdata_len) {
8259 if (pr_trace_get_level(trace_channel) >= 19) {
8260 register unsigned int i;
8261 const unsigned char *ticket_appdata;
8262 BIO *bio;
8263 char *text = NULL;
8264 long text_len = 0;
8265
8266 bio = BIO_new(BIO_s_mem());
8267 BIO_puts(bio, "comparing control ticket appdata (");
8268 ticket_appdata = tls_ctrl_ticket_appdata;
8269 for (i = 0; i < tls_ctrl_ticket_appdata_len; i++) {
8270 BIO_printf(bio, "%02x", ticket_appdata[i]);
8271 }
8272
8273 BIO_puts(bio, ") and data ticket appdata (");
8274 ticket_appdata = tls_data_ticket_appdata;
8275 for (i = 0; i < tls_data_ticket_appdata_len; i++) {
8276 BIO_printf(bio, "%02x", ticket_appdata[i]);
8277 }
8278 BIO_puts(bio, ")");
8279
8280 text_len = BIO_get_mem_data(bio, &text);
8281 if (text != NULL) {
8282 text[text_len] = '\0';
8283 pr_trace_msg(trace_channel, 19, "%.*s", (int) text_len, text);
8284 }
8285
8286 BIO_free(bio);
8287 }
8288
8289 matching_sess = memcmp(tls_ctrl_ticket_appdata,
8290 tls_data_ticket_appdata, tls_ctrl_ticket_appdata_len);
8291 if (matching_sess != 0) {
8292 pr_trace_msg(trace_channel, 9,
8293 "mismatched control/data ticket appdata for %s sessions",
8294 SSL_get_version(ssl));
8295 }
8296
8297 } else {
8298 pr_trace_msg(trace_channel, 9,
8299 "mismatched control/data ticket appdata (ctrl = %lu bytes, "
8300 "data = %lu bytes) for %s sessions",
8301 (unsigned long) tls_ctrl_ticket_appdata_len,
8302 (unsigned long) tls_data_ticket_appdata_len,
8303 SSL_get_version(ssl));
8304 }
8305 # else
8306 pr_trace_msg(trace_channel, 9,
8307 "ignoring mismatched control/data session IDs for %s sessions, "
8308 "for now", SSL_get_version(ssl));
8309 matching_sess = 0;
8310 # endif /* PR_USE_OPENSSL_SSL_SESSION_TICKET_CALLBACK */
8311 }
8312 #endif /* TLS1_3_VERSION */
8313
8314 if (matching_sess != 0) {
8315 tls_log("Client did not reuse TLS session from control channel, "
8316 "rejecting data connection (see the NoSessionReuseRequired "
8317 "TLSOptions parameter)");
8318 tls_end_sess(ssl, session.d, 0);
8319 pr_table_remove(tls_data_rd_nstrm->notes, TLS_NETIO_NOTE, NULL);
8320 pr_table_remove(tls_data_wr_nstrm->notes, TLS_NETIO_NOTE, NULL);
8321 return -1;
8322 }
8323
8324 /* The TLS session ID for data and control channels matches.
8325 *
8326 * Many sites are using mod_tls such that OpenSSL's internal
8327 * session caching is being used. And by default, that
8328 * cache expires sessions after 300 secs (5 min). It's possible
8329 * that the control channel TLS session will expire soon;
8330 * unless the client renegotiates that session, the internal
8331 * cache will expire the cached session, and the next data
8332 * transfer could fail (since mod_tls won't allow that session ID
8333 * to be reused again, as it will no longer be in the session
8334 * cache).
8335 *
8336 * Try to warn if this is about to happen.
8337 */
8338
8339 sess_created = SSL_SESSION_get_time(ctrl_sess);
8340 sess_expires = SSL_SESSION_get_timeout(ctrl_sess);
8341 now = time(NULL);
8342
8343 if ((sess_created + sess_expires) >= now) {
8344 unsigned long remaining;
8345
8346 remaining = (unsigned long) ((sess_created + sess_expires) - now);
8347
8348 if (remaining <= 60) {
8349 tls_log("control channel TLS session expires in %lu secs "
8350 "(%lu session cache expiration)", remaining, sess_expires);
8351 tls_log("%s", "Consider using 'TLSSessionCache internal:' to "
8352 "increase the session cache expiration if necessary, or "
8353 "renegotiate the control channel TLS session");
8354 }
8355 }
8356
8357 } else {
8358 /* This should never happen, so log if it does. */
8359 tls_log("%s", "BUG: unable to determine whether client reused TLS "
8360 "session: SSL_get_session() for data connection returned NULL");
8361 tls_log("%s", "rejecting data connection (see TLSOption NoSessionReuseRequired)");
8362 tls_end_sess(ssl, session.d, 0);
8363 pr_table_remove(tls_data_rd_nstrm->notes, TLS_NETIO_NOTE, NULL);
8364 pr_table_remove(tls_data_wr_nstrm->notes, TLS_NETIO_NOTE, NULL);
8365 return -1;
8366 }
8367
8368 } else {
8369 /* This should never happen, so log if it does. */
8370 tls_log("%s", "BUG: unable to determine whether client reused TLS "
8371 "session: SSL_get_session() for control connection returned NULL!");
8372 tls_log("%s", "rejecting data connection (see TLSOption NoSessionReuseRequired)");
8373 tls_end_sess(ssl, session.d, 0);
8374 pr_table_remove(tls_data_rd_nstrm->notes, TLS_NETIO_NOTE, NULL);
8375 pr_table_remove(tls_data_wr_nstrm->notes, TLS_NETIO_NOTE, NULL);
8376 return -1;
8377 }
8378 }
8379
8380 /* Only be verbose with the first TLS data connection, otherwise there
8381 * might be too much noise.
8382 */
8383 if (!logged_data) {
8384 int reused;
8385
8386 reused = SSL_session_reused(ssl);
8387
8388 tls_log("%s data connection accepted, using cipher %s (%d bits%s)",
8389 SSL_get_version(ssl), SSL_get_cipher_name(ssl),
8390 SSL_get_cipher_bits(ssl, NULL),
8391 reused > 0 ? ", resumed session" : "");
8392 logged_data = TRUE;
8393 }
8394 }
8395
8396 return 0;
8397 }
8398
8399 static int tls_connect(conn_t *conn) {
8400 int blocking, res = 0, xerrno = 0;
8401 char *subj = NULL;
8402 SSL *ssl = NULL;
8403 BIO *rbio = NULL, *wbio = NULL;
8404
8405 if (ssl_ctx == NULL) {
8406 tls_log("%s", "unable to start session: null SSL_CTX");
8407 return -1;
8408 }
8409
8410 ssl = SSL_new(ssl_ctx);
8411 if (ssl == NULL) {
8412 tls_log("error: unable to start session: %s",
8413 ERR_error_string(ERR_get_error(), NULL));
8414 return -2;
8415 }
8416
8417 /* Make sure our SSL object uses client methods (Issue#618). */
8418 if (SSL_set_ssl_method(ssl, SSLv23_client_method()) != 1) {
8419 tls_log("error: unable to set client methods: %s",
8420 ERR_error_string(ERR_get_error(), NULL));
8421 SSL_free(ssl);
8422 return -2;
8423 }
8424
8425 /* We deliberately set SSL_VERIFY_NONE here, so that we get to
8426 * determine how to handle the server cert verification result ourselves.
8427 */
8428 SSL_set_verify(ssl, SSL_VERIFY_NONE, NULL);
8429
8430 /* This works with either rfd or wfd (I hope). */
8431 rbio = BIO_new_socket(conn->rfd, FALSE);
8432 wbio = BIO_new_socket(conn->rfd, FALSE);
8433 SSL_set_bio(ssl, rbio, wbio);
8434
8435 /* If configured, set a timer for the handshake. */
8436 if (tls_handshake_timeout) {
8437 tls_handshake_timed_out = FALSE;
8438 tls_handshake_timer_id = pr_timer_add(tls_handshake_timeout, -1,
8439 &tls_module, tls_handshake_timeout_cb, "SSL/TLS handshake");
8440 }
8441
8442 /* Make sure that TCP_NODELAY is enabled for the handshake. */
8443 (void) pr_inet_set_proto_nodelay(conn->pool, conn, 1);
8444
8445 retry:
8446
8447 blocking = tls_get_block(conn);
8448 if (blocking) {
8449 /* Put the connection in non-blocking mode for the duration of the
8450 * TLS handshake. This lets us handle EAGAIN/retries better (i.e.
8451 * without spinning in a tight loop and consuming the CPU).
8452 */
8453 if (pr_inet_set_nonblock(conn->pool, conn) < 0) {
8454 pr_trace_msg(trace_channel, 3,
8455 "error making connection nonblocking: %s", strerror(errno));
8456 }
8457 }
8458
8459 pr_signals_handle();
8460 res = SSL_connect(ssl);
8461 xerrno = errno;
8462
8463 if (blocking) {
8464 /* Return the connection to blocking mode. */
8465 if (pr_inet_set_block(conn->pool, conn) < 0) {
8466 pr_trace_msg(trace_channel, 3,
8467 "error making connection blocking: %s", strerror(errno));
8468 }
8469 }
8470
8471 if (res < 1) {
8472 const char *msg = "unable to connect using TLS connection";
8473 int errcode = SSL_get_error(ssl, res);
8474
8475 pr_signals_handle();
8476
8477 if (tls_handshake_timed_out) {
8478 tls_log("TLS negotiation timed out (%u seconds)", tls_handshake_timeout);
8479 tls_end_sess(ssl, conn, 0);
8480 return -4;
8481 }
8482
8483 switch (errcode) {
8484 case SSL_ERROR_WANT_READ:
8485 pr_trace_msg(trace_channel, 17,
8486 "WANT_READ encountered while connecting on fd %d, "
8487 "waiting to read data", conn->rfd);
8488 tls_readmore(conn->rfd);
8489 goto retry;
8490
8491 case SSL_ERROR_WANT_WRITE:
8492 pr_trace_msg(trace_channel, 17,
8493 "WANT_WRITE encountered while connecting on fd %d, "
8494 "waiting to read data", conn->rfd);
8495 tls_writemore(conn->rfd);
8496 goto retry;
8497
8498 case SSL_ERROR_ZERO_RETURN:
8499 tls_log("%s: TLS connection closed", msg);
8500 break;
8501
8502 case SSL_ERROR_WANT_X509_LOOKUP:
8503 tls_log("%s: needs X509 lookup", msg);
8504 break;
8505
8506 case SSL_ERROR_SYSCALL: {
8507 /* Check to see if the OpenSSL error queue has info about this. */
8508 int xerrcode = ERR_get_error();
8509
8510 if (xerrcode == 0) {
8511 /* The OpenSSL error queue doesn't have any more info, so we'll
8512 * examine the SSL_connect() return value itself.
8513 */
8514
8515 if (res == 0) {
8516 /* EOF */
8517 tls_log("%s: received EOF that violates protocol", msg);
8518
8519 } else if (res == -1) {
8520 /* Check errno */
8521 tls_log("%s: system call error: [%d] %s", msg, xerrno,
8522 strerror(xerrno));
8523 }
8524
8525 } else {
8526 tls_log("%s: system call error: %s", msg, tls_get_errors());
8527 }
8528
8529 break;
8530 }
8531
8532 case SSL_ERROR_SSL:
8533 tls_log("%s: protocol error: %s", msg, tls_get_errors());
8534 break;
8535 }
8536
8537 pr_event_generate("mod_tls.data-handshake-failed", &errcode);
8538
8539 tls_end_sess(ssl, conn, 0);
8540 return -3;
8541 }
8542
8543 /* Disable TCP_NODELAY, now that the handshake is done. */
8544 (void) pr_inet_set_proto_nodelay(conn->pool, conn, 0);
8545
8546 /* Disable the handshake timer. */
8547 pr_timer_remove(tls_handshake_timer_id, &tls_module);
8548
8549 /* Manually update the raw bytes counters with the network IO from the
8550 * TLS handshake.
8551 */
8552 session.total_raw_in += (BIO_number_read(rbio) +
8553 BIO_number_read(wbio));
8554 session.total_raw_out += (BIO_number_written(rbio) +
8555 BIO_number_written(wbio));
8556
8557 /* Stash the SSL object in the pointers of the correct NetIO streams. */
8558 if (conn == session.d) {
8559 pr_buffer_t *strm_buf;
8560
8561 if (pr_table_add(tls_data_rd_nstrm->notes,
8562 pstrdup(tls_data_rd_nstrm->strm_pool, TLS_NETIO_NOTE),
8563 ssl, sizeof(SSL *)) < 0) {
8564 if (errno != EEXIST) {
8565 tls_log("error stashing '%s' note on data read stream: %s",
8566 TLS_NETIO_NOTE, strerror(errno));
8567 }
8568 }
8569
8570 if (pr_table_add(tls_data_wr_nstrm->notes,
8571 pstrdup(tls_data_wr_nstrm->strm_pool, TLS_NETIO_NOTE),
8572 ssl, sizeof(SSL *)) < 0) {
8573 if (errno != EEXIST) {
8574 tls_log("error stashing '%s' note on data write stream: %s",
8575 TLS_NETIO_NOTE, strerror(errno));
8576 }
8577 }
8578
8579 /* Clear any data from the NetIO stream buffers which may have been read
8580 * in before the SSL/TLS handshake occurred (Bug#3624).
8581 */
8582 strm_buf = tls_data_rd_nstrm->strm_buf;
8583 if (strm_buf != NULL) {
8584 strm_buf->current = NULL;
8585 strm_buf->remaining = strm_buf->buflen;
8586 }
8587 }
8588
8589 #if OPENSSL_VERSION_NUMBER == 0x009080cfL
8590 /* In OpenSSL-0.9.8l, SSL session renegotiations are automatically
8591 * disabled. Thus if the admin explicitly configured support for
8592 * client-initiated renegotiations via the AllowClientRenegotiations
8593 * TLSOption, then we need to do some hackery to enable renegotiations.
8594 */
8595 if (tls_opts & TLS_OPT_ALLOW_CLIENT_RENEGOTIATIONS) {
8596 ssl->s3->flags |= SSL3_FLAGS_ALLOW_UNSAFE_LEGACY_RENEGOTIATION;
8597 }
8598 #endif
8599
8600 subj = tls_get_subj_name(ssl);
8601 if (subj) {
8602 tls_log("Server: %s", subj);
8603 }
8604
8605 if (tls_check_server_cert(ssl, conn) < 0) {
8606 tls_end_sess(ssl, conn, 0);
8607 return -1;
8608 }
8609
8610 tls_log("%s connection created, using cipher %s (%d bits)",
8611 SSL_get_version(ssl), SSL_get_cipher_name(ssl),
8612 SSL_get_cipher_bits(ssl, NULL));
8613
8614 return 0;
8615 }
8616
8617 static void tls_cleanup(int flags) {
8618
8619 #if OPENSSL_VERSION_NUMBER > 0x000907000L && \
8620 OPENSSL_VERSION_NUMBER < 0x10100000L
8621 # if defined(PR_USE_OPENSSL_ENGINE)
8622 if (tls_crypto_device != NULL) {
8623 ENGINE_cleanup();
8624 tls_crypto_device = NULL;
8625 }
8626 # endif /* PR_USE_OPENSSL_ENGINE */
8627 #endif
8628
8629 if (ssl_ctx != NULL) {
8630 SSL_CTX_free(ssl_ctx);
8631 ssl_ctx = NULL;
8632 }
8633
8634 /* Close the session cache only AFTER the SSL context has been
8635 * freed/deleted (Issue #795).
8636 */
8637 tls_sess_cache_close();
8638 tls_ocsp_cache_close();
8639
8640 if (tls_tmp_dhs != NULL) {
8641 register unsigned int i;
8642 DH **dhs;
8643
8644 dhs = tls_tmp_dhs->elts;
8645 for (i = 0; i < tls_tmp_dhs->nelts; i++) {
8646 DH_free(dhs[i]);
8647 }
8648
8649 tls_tmp_dhs = NULL;
8650 }
8651
8652 if (tls_tmp_rsa != NULL) {
8653 RSA_free(tls_tmp_rsa);
8654 tls_tmp_rsa = NULL;
8655 }
8656
8657 if (!(flags & TLS_CLEANUP_FL_SESS_INIT)) {
8658 #if OPENSSL_VERSION_NUMBER >= 0x10000001L
8659 /* The ERR_remove_state(0) usage is deprecated due to thread ID
8660 * differences among platforms; see the OpenSSL-1.0.0 CHANGES file
8661 * for details. So for new enough OpenSSL installations, use the
8662 * proper way to clear the error queue state.
8663 */
8664 # if OPENSSL_VERSION_NUMBER < 0x10100000L
8665 ERR_remove_thread_state(NULL);
8666 # endif /* prior to OpenSSL-1.1.x */
8667 #else
8668 ERR_remove_state(0);
8669 #endif /* OpenSSL prior to 1.0.0-beta1 */
8670
8671 #if OPENSSL_VERSION_NUMBER < 0x10100000L
8672 ERR_free_strings();
8673 EVP_cleanup();
8674 #endif /* prior to OpenSSL-1.1.x */
8675
8676 } else {
8677 /* Only call EVP_cleanup() et al if other OpenSSL-using modules are not
8678 * present. If we called EVP_cleanup() here during session
8679 * initialization, and other modules want to use OpenSSL, we may
8680 * be depriving those modules of OpenSSL functionality.
8681 *
8682 * At the moment, the modules known to use OpenSSL are:
8683 * mod_auth_otp
8684 * mod_digest
8685 * mod_ldap
8686 * mod_proxy
8687 * mod_sftp
8688 * mod_sql
8689 * mod_sql_passwd
8690 */
8691 if (pr_module_get("mod_auth_otp.c") == NULL &&
8692 pr_module_get("mod_digest.c") == NULL &&
8693 pr_module_get("mod_ldap.c") == NULL &&
8694 pr_module_get("mod_proxy.c") == NULL &&
8695 pr_module_get("mod_sftp.c") == NULL &&
8696 pr_module_get("mod_sql.c") == NULL &&
8697 pr_module_get("mod_sql_passwd.c") == NULL) {
8698
8699 #if OPENSSL_VERSION_NUMBER >= 0x10000001L
8700 /* The ERR_remove_state(0) usage is deprecated due to thread ID
8701 * differences among platforms; see the OpenSSL-1.0.0c CHANGES file
8702 * for details. So for new enough OpenSSL installations, use the
8703 * proper way to clear the error queue state.
8704 */
8705 # if OPENSSL_VERSION_NUMBER < 0x10100000L
8706 ERR_remove_thread_state(NULL);
8707 # endif /* prior to OpenSSL-1.1.x */
8708 #else
8709 ERR_remove_state(0);
8710 #endif /* OpenSSL prior to 1.0.0-beta1 */
8711
8712 #if OPENSSL_VERSION_NUMBER < 0x10100000L
8713 ERR_free_strings();
8714 EVP_cleanup();
8715 #endif /* prior to OpenSSL-1.1.x */
8716 }
8717 }
8718 }
8719
8720 /* Returns TRUE for SSL data, FALSE for FTP data, and -1 on error.
8721 *
8722 * First, we want for readable data on the socket via select(2). Then
8723 * we use recv(2) to peek at the data; we only need three bytes. Why only
8724 * three bytes? According to the TLS RFCs on SSL record layering, each
8725 * well-formed SSL record starts with:
8726 *
8727 * struct {
8728 * uint8 major;
8729 * uint8 minor;
8730 * } ProtocolVersion;
8731 *
8732 * enum {
8733 * change_cipher_spec(20), alert(21), handshake(22),
8734 * application_data(23), (255)
8735 * } ContentType;
8736 *
8737 * struct {
8738 * ContentType type;
8739 * ProtocolVersion version;
8740 *
8741 * It helps that the first byte, if an SSL record, will be 20-23, or 255.
8742 * The printable ASCII range, which would be used for an FTP command, starts
8743 * at 32 (sp). We read three bytes to include the protocol version, to
8744 * help increase confidence in our guess at whether these data are a well-
8745 * formed SSL record, or an FTP command.
8746 */
8747 static int peek_is_ssl_data(int fd) {
8748 register unsigned int i;
8749 int res;
8750 fd_set rfds;
8751 struct timeval tv;
8752 ssize_t len;
8753 unsigned char buf[3];
8754
8755 /* We'll wait up to 5 secs, or until interrupted, for the next data. */
8756 tv.tv_sec = 5;
8757 tv.tv_usec = 0;
8758
8759 pr_trace_msg(trace_channel, 20, "peeking at next data for fd %d, for %d secs",
8760 fd, (int) tv.tv_sec);
8761
8762 FD_ZERO(&rfds);
8763 FD_SET(fd, &rfds);
8764
8765 res = select(fd + 1, &rfds, NULL, NULL, &tv);
8766 while (res < 0) {
8767 int xerrno = errno;
8768
8769 if (xerrno == EINTR) {
8770 pr_signals_handle();
8771 res = select(fd + 1, &rfds, NULL, NULL, &tv);
8772 continue;
8773 }
8774
8775 pr_trace_msg(trace_channel, 20,
8776 "error waiting for next data on fd %d: %s", fd, strerror(xerrno));
8777 errno = xerrno;
8778 return -1;
8779 }
8780
8781 if (res == 0) {
8782 /* Timed out. Error on the side of optimism, and assume the next data
8783 * will be an SSL record. This is what mod_tls would do, if we were not
8784 * peeking.
8785 */
8786 pr_trace_msg(trace_channel, 20,
8787 "timed out after %d secs peeking at next data, assuming SSL data",
8788 (int) tv.tv_sec);
8789 return TRUE;
8790 }
8791
8792 /* If we reach here, the peer must have sent something. Let's see what it
8793 * might be. Chances are that we received at least 3 bytes, but to be
8794 * defensive, we use MSG_WAITALL anyway. TCP allows for sending one byte
8795 * at time, if need be. Fortunately, either SSL record or FTP command will
8796 * require more than three bytes.
8797 */
8798 memset(&buf, 0, sizeof(buf));
8799 len = recv(fd, buf, sizeof(buf), MSG_PEEK|MSG_WAITALL);
8800 while (len < 0) {
8801 int xerrno = errno;
8802
8803 if (xerrno == EINTR) {
8804 pr_signals_handle();
8805 len = recv(fd, &buf, sizeof(buf), MSG_PEEK|MSG_WAITALL);
8806 continue;
8807 }
8808
8809 pr_trace_msg(trace_channel, 20,
8810 "error peeking at next data: %s", strerror(xerrno));
8811 errno = xerrno;
8812 return -1;
8813 }
8814
8815 pr_trace_msg(trace_channel, 20, "peeking at %ld bytes of next data",
8816 (long) len);
8817 for (i = 0; i < len; i++) {
8818 if (PR_ISPRINT(buf[i]) == 0) {
8819 /* Not a printable character; assume it's SSL data. */
8820 pr_trace_msg(trace_channel, 20,
8821 "byte %u of peeked data is a non-printable ASCII character (%d), "
8822 "assuming SSL data", i, (int) buf[i]);
8823 return TRUE;
8824 }
8825 }
8826
8827 pr_trace_msg(trace_channel, 20,
8828 "all %ld bytes of peeked data are printable ASCII characters, assuming "
8829 "FTP data", (long) len);
8830 return FALSE;
8831 }
8832
8833 static void tls_end_sess(SSL *ssl, conn_t *conn, int flags) {
8834 int lineno, res = 0;
8835 int shutdown_state;
8836 BIO *rbio, *wbio;
8837 int bread, bwritten;
8838 unsigned long rbio_rbytes, rbio_wbytes, wbio_rbytes, wbio_wbytes;
8839
8840 if (ssl == NULL) {
8841 return;
8842 }
8843
8844 rbio = SSL_get_rbio(ssl);
8845 rbio_rbytes = BIO_number_read(rbio);
8846 rbio_wbytes = BIO_number_written(rbio);
8847
8848 wbio = SSL_get_wbio(ssl);
8849 wbio_rbytes = BIO_number_read(wbio);
8850 wbio_wbytes = BIO_number_written(wbio);
8851
8852 /* A 'close_notify' alert (SSL shutdown message) may have been previously
8853 * sent to the client via tls_netio_shutdown_cb().
8854 */
8855
8856 shutdown_state = SSL_get_shutdown(ssl);
8857 if (!(shutdown_state & SSL_SENT_SHUTDOWN)) {
8858 errno = 0;
8859
8860 if (conn != NULL) {
8861 /* Disable any socket buffering (Nagle, TCP_CORK), so that the alert
8862 * is sent in a timely manner (avoiding TLS shutdown latency).
8863 */
8864 if (pr_inet_set_proto_nodelay(conn->pool, conn, 1) < 0) {
8865 pr_trace_msg(trace_channel, 9,
8866 "error enabling TCP_NODELAY on conn: %s", strerror(errno));
8867 }
8868
8869 if (pr_inet_set_proto_cork(conn->wfd, 0) < 0) {
8870 pr_trace_msg(trace_channel, 9,
8871 "error disabling TCP_CORK on fd %d: %s", conn->wfd, strerror(errno));
8872 }
8873 }
8874
8875 /* 'close_notify' not already sent; send it now. */
8876 pr_trace_msg(trace_channel, 17,
8877 "shutting down %s TLS session, 'close_notify' not already sent; "
8878 "sending now", ssl == ctrl_ssl ? "control" : "data");
8879 lineno = __LINE__ + 1;
8880 res = SSL_shutdown(ssl);
8881 }
8882
8883 if (res == 0) {
8884 /* Now call SSL_shutdown() again, but only if necessary. */
8885 if (flags & TLS_SHUTDOWN_FL_BIDIRECTIONAL) {
8886 shutdown_state = SSL_get_shutdown(ssl);
8887
8888 res = 1;
8889 if (!(shutdown_state & SSL_RECEIVED_SHUTDOWN) &&
8890 conn != NULL) {
8891 int is_ssl_data = FALSE, xerrno;
8892
8893 pr_trace_msg(trace_channel, 17,
8894 "shutting down %s TLS session, 'close_notify' not received; "
8895 "peeking at next data", ssl == ctrl_ssl ? "control" : "data");
8896
8897 /* This where we need to peek at the next data, to see whether we
8898 * dealing with a well-behaved FTPS client, which will be sending
8899 * its `close_notify` to properly shutdown the TLS session, or with
8900 * a buggy/ill-behaved FTPS client which will not send a `close_notify`,
8901 * and instead will just send the next FTP command in plaintext.
8902 *
8903 * If it's the latter case, then we do NOT want to wait for a
8904 * `close_notify` that will never come. Doing so will cause the
8905 * plaintext FTP command to be treated as an SSL record, which will
8906 * fail with a "wrong version number" SSL error.
8907 */
8908
8909 is_ssl_data = peek_is_ssl_data(conn->rfd);
8910 if (is_ssl_data < 0) {
8911 SSL_free(ssl);
8912 pr_session_disconnect(&tls_module, PR_SESS_DISCONNECT_BY_APPLICATION,
8913 NULL);
8914 return;
8915 }
8916
8917 if (is_ssl_data == FALSE) {
8918 /* We're dealing with a buggy/ill-behaved FTPS client. Sigh. */
8919 pr_trace_msg(trace_channel, 17,
8920 "shut down TLS session uncleanly, next data is FTP command from "
8921 "buggy/ill-behaved FTPS client");
8922 SSL_free(ssl);
8923 return;
8924 }
8925
8926 errno = 0;
8927 lineno = __LINE__ + 1;
8928 res = SSL_shutdown(ssl);
8929 xerrno = errno;
8930
8931 pr_trace_msg(trace_channel, 17,
8932 "shutting down %s TLS session, 'close_notify' not received; "
8933 "SSL_shutdown() returned %d", ssl == ctrl_ssl ? "control" : "data",
8934 res);
8935
8936 errno = xerrno;
8937 }
8938 }
8939
8940 /* If SSL_shutdown() returned -1 here, an error occurred during the
8941 * shutdown.
8942 */
8943 if (res < 0) {
8944 long err_code;
8945
8946 err_code = SSL_get_error(ssl, res);
8947 switch (err_code) {
8948 case SSL_ERROR_WANT_READ:
8949 tls_log("SSL_shutdown error: WANT_READ");
8950 break;
8951
8952 case SSL_ERROR_WANT_WRITE:
8953 tls_log("SSL_shutdown error: WANT_WRITE");
8954 break;
8955
8956 case SSL_ERROR_SSL: {
8957 unsigned long ssl_errcode = ERR_peek_error();
8958
8959 /* The error codes in the OpenSSL error queue are "packed"; we need
8960 * to unpack them to get the reason value.
8961 */
8962
8963 #ifdef SSL_R_SHUTDOWN_WHILE_IN_INIT
8964 if (ERR_GET_REASON(ssl_errcode) != SSL_R_SHUTDOWN_WHILE_IN_INIT) {
8965 /* This SHUTDOWN_WHILE_IN_INIT can happen if the TLS handshake
8966 * failed before being completed. As such, logging this shutdown
8967 * error on an incomplete session is spurious and not helpful.
8968 */
8969 tls_log("SSL_shutdown error: SSL: %s", tls_get_errors());
8970 }
8971 #else
8972 (void) ssl_errcode;
8973 tls_log("SSL_shutdown error: SSL: %s", tls_get_errors());
8974 #endif /* No SSL_R_SHUTDOWN_WHILE_IN_INIT */
8975
8976 break;
8977 }
8978
8979 case SSL_ERROR_ZERO_RETURN:
8980 /* Clean shutdown, nothing we need to do. */
8981 break;
8982
8983 case SSL_ERROR_SYSCALL:
8984 if (errno != 0 &&
8985 errno != EOF &&
8986 errno != EBADF &&
8987 errno != EPIPE &&
8988 errno != EPERM &&
8989 errno != ENOSYS) {
8990 tls_log("SSL_shutdown syscall error: %s", strerror(errno));
8991 }
8992 break;
8993
8994 default:
8995 tls_log("SSL_shutdown error [%ld], line %d: %s", err_code, lineno,
8996 tls_get_errors());
8997 pr_log_debug(DEBUG0, MOD_TLS_VERSION
8998 ": SSL_shutdown error [%ld], line %d: %s", err_code, lineno,
8999 tls_get_errors());
9000 break;
9001 }
9002 }
9003
9004 } else if (res < 0) {
9005 long err_code;
9006
9007 err_code = SSL_get_error(ssl, res);
9008 switch (err_code) {
9009 case SSL_ERROR_WANT_READ:
9010 case SSL_ERROR_WANT_WRITE:
9011 case SSL_ERROR_ZERO_RETURN:
9012 /* Clean shutdown, nothing we need to do. The WANT_READ/WANT_WRITE
9013 * error codes crept into OpenSSL 0.9.8m, with changes to make
9014 * SSL_shutdown() work properly for non-blocking sockets. And
9015 * handling these error codes for older OpenSSL versions won't break
9016 * things.
9017 */
9018 break;
9019
9020 case SSL_ERROR_SSL: {
9021 unsigned long ssl_errcode = ERR_peek_error();
9022
9023 /* The error codes in the OpenSSL error queue are "packed"; we need
9024 * to unpack them to get the reason value.
9025 */
9026
9027 #ifdef SSL_R_SHUTDOWN_WHILE_IN_INIT
9028 if (ERR_GET_REASON(ssl_errcode) != SSL_R_SHUTDOWN_WHILE_IN_INIT) {
9029 /* This SHUTDOWN_WHILE_IN_INIT can happen if the TLS handshake
9030 * failed before being completed. As such, logging this shutdown
9031 * error on an incomplete session is spurious and not helpful.
9032 */
9033 tls_log("SSL_shutdown error: SSL: %s", tls_get_errors());
9034 }
9035 #else
9036 (void) ssl_errcode;
9037 tls_log("SSL_shutdown error: SSL: %s", tls_get_errors());
9038 #endif /* No SSL_R_SHUTDOWN_WHILE_IN_INIT */
9039 break;
9040 }
9041
9042 case SSL_ERROR_SYSCALL:
9043 if (errno != 0 &&
9044 errno != EOF &&
9045 errno != EBADF &&
9046 errno != EPIPE &&
9047 errno != EPERM &&
9048 errno != ENOSYS) {
9049 tls_log("SSL_shutdown syscall error: %s", strerror(errno));
9050 }
9051 break;
9052
9053 default:
9054 tls_fatal_error(err_code, lineno);
9055 break;
9056 }
9057 }
9058
9059 bread = (BIO_number_read(rbio) - rbio_rbytes) +
9060 (BIO_number_read(wbio) - wbio_rbytes);
9061 bwritten = (BIO_number_written(rbio) - rbio_wbytes) +
9062 (BIO_number_written(wbio) - wbio_wbytes);
9063
9064 /* Manually update session.total_raw_in/out, in order to have %I/%O be
9065 * accurately represented for the raw traffic.
9066 */
9067 if (bread > 0) {
9068 session.total_raw_in += bread;
9069 }
9070
9071 if (bwritten > 0) {
9072 session.total_raw_out += bwritten;
9073 }
9074
9075 if (ssl != ctrl_ssl &&
9076 ctrl_ssl != NULL &&
9077 SSL_get_session(ssl) == SSL_get_session(ctrl_ssl)) {
9078 /* Uh-oh; our two SSL objects are pointing at the same SSL_SESSION object.
9079 * This can happen when the SSL_SESSION is resumed, enabled by session
9080 * caching. Which is normally a Good Thing.
9081 *
9082 * But Issue#1963 happens when that SSL_SESSION object is freed twice:
9083 * once via SSL_free() on this SSL, and again on SSL_free() for the
9084 * other SSL. Yuck.
9085 *
9086 * So we manually handle the situation by clearing the duplicate
9087 * SSL_SESSION pointer from the data SSL. Why the data SSL, and not the
9088 * control SSL? We could be handling multiple concurrent data transfers,
9089 * and/or the client may reuse the session again on a subsequent data
9090 * transfer.
9091 *
9092 * Note that older OpenSSL versions used two different SSL_SESSION objects,
9093 * hence why we have not seen this occur frequently in the past. (Or it
9094 * was not reported.) And for TLSv1.3 resumed sessions, the SSL_SESSION
9095 * objects are different, hence no double-free.
9096 */
9097 pr_trace_msg(trace_channel, 29,
9098 "data SSL %p being ended has same SSL_SESSION %p as control SSL, "
9099 "clearing the data SSL pointer manually (see Issue #1963)", ssl,
9100 SSL_get_session(ssl));
9101 if (SSL_set_session(ssl, NULL) != 1) {
9102 pr_trace_msg(trace_channel, 29,
9103 "error setting NULL session on SSL %p: %s", ssl, tls_get_errors());
9104 }
9105
9106 /* Note that, per findings in Issue #2056, we also need to manually
9107 * increment the refcount of the ctrl_ssl session, lest we still
9108 * inadvertently corrupt the OpenSSL internal session cache state.
9109 * Sigh.
9110 */
9111 if (SSL_SESSION_up_ref(SSL_get_session(ctrl_ssl)) != 1) {
9112 pr_trace_msg(trace_channel, 29,
9113 "error incrementing session refcount on SSL %p: %s", ctrl_ssl,
9114 tls_get_errors());
9115 }
9116 }
9117
9118 SSL_free(ssl);
9119
9120 if (res >= 0) {
9121 pr_trace_msg(trace_channel, 17, "%s TLS session cleanly shut down",
9122 ssl == ctrl_ssl ? "control" : "data");
9123 }
9124 }
9125
9126 static const char *tls_get_errors2(pool *p) {
9127 unsigned int count = 0;
9128 unsigned long error_code;
9129 BIO *bio = NULL;
9130 char *data = NULL;
9131 long datalen;
9132 const char *error_data = NULL, *str = "(unknown)";
9133 int error_flags = 0;
9134
9135 /* Use ERR_print_errors() and a memory BIO to build up a string with
9136 * all of the error messages from the error queue.
9137 */
9138
9139 error_code = ERR_get_error_line_data(NULL, NULL, &error_data, &error_flags);
9140 if (error_code) {
9141 bio = BIO_new(BIO_s_mem());
9142 }
9143
9144 while (error_code) {
9145 pr_signals_handle();
9146
9147 if (error_flags & ERR_TXT_STRING) {
9148 BIO_printf(bio, "\n (%u) %s [%s]", ++count,
9149 ERR_error_string(error_code, NULL), error_data);
9150
9151 } else {
9152 BIO_printf(bio, "\n (%u) %s", ++count,
9153 ERR_error_string(error_code, NULL));
9154 }
9155
9156 error_data = NULL;
9157 error_flags = 0;
9158 error_code = ERR_get_error_line_data(NULL, NULL, &error_data, &error_flags);
9159 }
9160
9161 datalen = BIO_get_mem_data(bio, &data);
9162 if (data) {
9163 data[datalen] = '\0';
9164 str = pstrdup(p, data);
9165 }
9166
9167 if (bio) {
9168 BIO_free(bio);
9169 }
9170
9171 return str;
9172 }
9173
9174 static const char *tls_get_errors(void) {
9175 return tls_get_errors2(session.pool);
9176 }
9177
9178 /* Return a page-aligned pointer to memory of at least the given size. */
9179 static char *tls_get_page(size_t sz, void **ptr) {
9180 void *d;
9181 long pagesz = tls_get_pagesz(), p;
9182
9183 d = calloc(1, sz + (pagesz-1));
9184 if (d == NULL) {
9185 pr_log_pri(PR_LOG_ALERT, MOD_TLS_VERSION ": Out of memory!");
9186 exit(1);
9187 }
9188
9189 *ptr = d;
9190
9191 p = ((long) d + (pagesz-1)) &~ (pagesz-1);
9192
9193 return ((char *) p);
9194 }
9195
9196 /* Return the size of a page on this architecture. */
9197 static size_t tls_get_pagesz(void) {
9198 long pagesz;
9199
9200 #if defined(_SC_PAGESIZE)
9201 pagesz = sysconf(_SC_PAGESIZE);
9202 #elif defined(_SC_PAGE_SIZE)
9203 pagesz = sysconf(_SC_PAGE_SIZE);
9204 #else
9205 /* Default to using OpenSSL's defined buffer size for PEM files. */
9206 pagesz = PEM_BUFSIZE;
9207 #endif /* !_SC_PAGESIZE and !_SC_PAGE_SIZE */
9208
9209 return pagesz;
9210 }
9211
9212 static char *tls_get_subj_name(SSL *ssl) {
9213 X509 *cert = SSL_get_peer_certificate(ssl);
9214
9215 if (cert) {
9216 char *name = tls_x509_name_oneline(X509_get_subject_name(cert));
9217 X509_free(cert);
9218 return name;
9219 }
9220
9221 return NULL;
9222 }
9223
9224 static void tls_fatal_error(long error, int lineno) {
9225
9226 switch (error) {
9227 case SSL_ERROR_NONE:
9228 return;
9229
9230 case SSL_ERROR_SSL:
9231 tls_log("panic: SSL_ERROR_SSL, line %d: %s", lineno, tls_get_errors());
9232 break;
9233
9234 case SSL_ERROR_WANT_READ:
9235 tls_log("panic: SSL_ERROR_WANT_READ, line %d", lineno);
9236 break;
9237
9238 case SSL_ERROR_WANT_WRITE:
9239 tls_log("panic: SSL_ERROR_WANT_WRITE, line %d", lineno);
9240 break;
9241
9242 case SSL_ERROR_WANT_X509_LOOKUP:
9243 tls_log("panic: SSL_ERROR_WANT_X509_LOOKUP, line %d", lineno);
9244 break;
9245
9246 case SSL_ERROR_SYSCALL: {
9247 long xerrcode = ERR_get_error();
9248
9249 if (errno == ECONNRESET) {
9250 pr_trace_msg(trace_channel, 17,
9251 "SSL_ERROR_SYSCALL error (errcode %ld) occurred on line %d; ignoring "
9252 "ECONNRESET (%s)", xerrcode, lineno, strerror(errno));
9253 return;
9254 }
9255
9256 /* Check to see if the OpenSSL error queue has info about this. */
9257 if (xerrcode == 0) {
9258 /* The OpenSSL error queue doesn't have any more info, so we'll
9259 * examine the error value itself.
9260 */
9261
9262 if (errno == EOF) {
9263 tls_log("panic: SSL_ERROR_SYSCALL, line %d: "
9264 "EOF that violates protocol", lineno);
9265
9266 } else {
9267 /* Check errno */
9268 tls_log("panic: SSL_ERROR_SYSCALL, line %d: system error: %s", lineno,
9269 strerror(errno));
9270 }
9271
9272 } else {
9273 tls_log("panic: SSL_ERROR_SYSCALL, line %d: %s", lineno,
9274 tls_get_errors());
9275 }
9276
9277 break;
9278 }
9279
9280 case SSL_ERROR_ZERO_RETURN:
9281 tls_log("panic: SSL_ERROR_ZERO_RETURN, line %d", lineno);
9282 break;
9283
9284 case SSL_ERROR_WANT_CONNECT:
9285 tls_log("panic: SSL_ERROR_WANT_CONNECT, line %d", lineno);
9286 break;
9287
9288 default:
9289 tls_log("panic: SSL_ERROR %ld, line %d", error, lineno);
9290 break;
9291 }
9292
9293 tls_log("%s", "unexpected OpenSSL error, disconnecting");
9294 pr_log_pri(PR_LOG_WARNING, "%s", MOD_TLS_VERSION
9295 ": unexpected OpenSSL error, disconnecting");
9296
9297 pr_session_disconnect(&tls_module, PR_SESS_DISCONNECT_BY_APPLICATION, NULL);
9298 }
9299
9300 /* This function checks if the client's cert is in the ~/.tlslogin file
9301 * of the "user".
9302 */
9303 static int tls_dotlogin_allow(const char *user) {
9304 char buf[512] = {'\0'}, *home = NULL;
9305 FILE *fp = NULL;
9306 X509 *client_cert = NULL, *file_cert = NULL;
9307 struct passwd *pwd = NULL;
9308 pool *tmp_pool = NULL;
9309 unsigned char allow_user = FALSE;
9310 int xerrno;
9311
9312 if (!(tls_flags & TLS_SESS_ON_CTRL) ||
9313 ctrl_ssl == NULL ||
9314 user == NULL) {
9315 return FALSE;
9316 }
9317
9318 /* If the client did not provide a cert, we cannot do the .tlslogin check. */
9319 client_cert = SSL_get_peer_certificate(ctrl_ssl);
9320 if (client_cert == NULL) {
9321 pr_trace_msg(trace_channel, 9, "%s",
9322 "client did not provide certificate, skipping AllowDotLogin check");
9323 return FALSE;
9324 }
9325
9326 tmp_pool = make_sub_pool(permanent_pool);
9327
9328 PRIVS_ROOT
9329 pwd = pr_auth_getpwnam(tmp_pool, user);
9330 PRIVS_RELINQUISH
9331
9332 if (pwd == NULL) {
9333 X509_free(client_cert);
9334 destroy_pool(tmp_pool);
9335 return FALSE;
9336 }
9337
9338 /* Handle the case where the user's home directory is a symlink. */
9339 PRIVS_USER
9340 home = dir_realpath(tmp_pool, pwd->pw_dir);
9341 PRIVS_RELINQUISH
9342
9343 pr_snprintf(buf, sizeof(buf), "%s/.tlslogin", home ? home : pwd->pw_dir);
9344 buf[sizeof(buf)-1] = '\0';
9345
9346 /* No need for the temporary pool any more. */
9347 destroy_pool(tmp_pool);
9348 tmp_pool = NULL;
9349
9350 PRIVS_ROOT
9351 fp = fopen(buf, "r");
9352 xerrno = errno;
9353 PRIVS_RELINQUISH
9354
9355 if (fp == NULL) {
9356 X509_free(client_cert);
9357 tls_log(".tlslogin check: unable to open '%s': %s", buf, strerror(xerrno));
9358 return FALSE;
9359 }
9360
9361 /* As the file may contain sensitive data, we do not want it lingering
9362 * around in stdio buffers.
9363 */
9364 (void) setvbuf(fp, NULL, _IONBF, 0);
9365
9366 while ((file_cert = PEM_read_X509(fp, NULL, NULL, NULL))) {
9367 const ASN1_BIT_STRING *client_sig = NULL, *file_sig = NULL;
9368
9369 pr_signals_handle();
9370
9371 #if (OPENSSL_VERSION_NUMBER >= 0x10100000L && !defined(HAVE_LIBRESSL)) || \
9372 (defined(HAVE_LIBRESSL) && LIBRESSL_VERSION_NUMBER >= 0x3050000L)
9373 X509_get0_signature(&client_sig, NULL, client_cert);
9374 X509_get0_signature(&file_sig, NULL, file_cert);
9375 #else
9376 client_sig = client_cert->signature;
9377 file_sig = file_cert->signature;
9378 #endif /* OpenSSL-1.1.x/LibreSSL-3.5.x and later */
9379
9380 #if OPENSSL_VERSION_NUMBER >= 0x10100000L
9381 if (!ASN1_STRING_cmp(client_sig, file_sig)) {
9382 #else
9383 if (!M_ASN1_BIT_STRING_cmp(client_sig, file_sig)) {
9384 #endif /* OpenSSL-1.1.x and later */
9385 allow_user = TRUE;
9386 }
9387
9388 if (allow_user == FALSE) {
9389 BIO *bio;
9390 char *data;
9391 long datalen;
9392 unsigned long nameflags, skipflags;
9393
9394 nameflags = XN_FLAG_ONELINE;
9395 skipflags = X509_FLAG_NO_PUBKEY|X509_FLAG_NO_EXTENSIONS|X509_FLAG_NO_SIGDUMP|X509_FLAG_NO_AUX;
9396 #ifdef X509_FLAG_NO_ATTRIBUTES
9397 skipflags |= X509_FLAG_NO_ATTRIBUTES;
9398 #endif
9399 #ifdef X509_FLAG_NO_IDS
9400 skipflags |= X509_FLAG_NO_IDS;
9401 #endif
9402
9403 tls_log(".tlslogin local/remote certificate MISMATCH");
9404 bio = BIO_new(BIO_s_mem());
9405 X509_print_ex(bio, file_cert, nameflags, skipflags);
9406 datalen = BIO_get_mem_data(bio, &data);
9407 data[datalen] = '\0';
9408 tls_log(".tlslogin local file certificate:\n%.*s", (int) datalen, data);
9409 BIO_free(bio);
9410
9411 bio = BIO_new(BIO_s_mem());
9412 X509_print_ex(bio, client_cert, nameflags, skipflags);
9413 datalen = BIO_get_mem_data(bio, &data);
9414 data[datalen] = '\0';
9415 tls_log(".tlslogin remote client certificate:\n%.*s", (int) datalen, data);
9416 BIO_free(bio);
9417 }
9418
9419 X509_free(file_cert);
9420 if (allow_user == TRUE) {
9421 break;
9422 }
9423 }
9424
9425 X509_free(client_cert);
9426 fclose(fp);
9427
9428 return allow_user;
9429 }
9430
9431 static int tls_cert_to_user(const char *user_name, const char *field_name) {
9432 X509 *client_cert = NULL;
9433 unsigned char allow_user = FALSE;
9434 const unsigned char *field_value = NULL;
9435
9436 if (!(tls_flags & TLS_SESS_ON_CTRL) ||
9437 ctrl_ssl == NULL ||
9438 user_name == NULL ||
9439 field_name == NULL) {
9440 return FALSE;
9441 }
9442
9443 /* If the client did not provide a cert, we cannot do the TLSUserName
9444 * check.
9445 */
9446 client_cert = SSL_get_peer_certificate(ctrl_ssl);
9447 if (client_cert == NULL) {
9448 return FALSE;
9449 }
9450
9451 if (strcmp(field_name, "CommonName") == 0) {
9452 const X509_NAME *name;
9453 int pos = -1;
9454
9455 name = X509_get_subject_name(client_cert);
9456
9457 while (TRUE) {
9458 const X509_NAME_ENTRY *entry;
9459 const ASN1_STRING *data;
9460 int data_len;
9461 const unsigned char *data_str = NULL;
9462
9463 pr_signals_handle();
9464
9465 pos = X509_NAME_get_index_by_NID(name, NID_commonName, pos);
9466 if (pos == -1) {
9467 break;
9468 }
9469
9470 entry = X509_NAME_get_entry(name, pos);
9471 data = X509_NAME_ENTRY_get_data(entry);
9472 data_len = ASN1_STRING_length(data);
9473 #if OPENSSL_VERSION_NUMBER >= 0x10100000L && \
9474 !defined(HAVE_LIBRESSL)
9475 data_str = ASN1_STRING_get0_data(data);
9476 #else
9477 data_str = ASN1_STRING_data(data);
9478 #endif /* OpenSSL 1.1.x and later */
9479
9480 /* Watch for any embedded NULs, which can cause verification
9481 * problems via spoofing.
9482 */
9483 if ((size_t) data_len != strlen((char *) data_str)) {
9484 tls_log("%s", "client cert CommonName contains embedded NULs, "
9485 "ignoring as possible spoof attempt");
9486 tls_log("suspicious CommonName value: '%s'", data_str);
9487
9488 } else {
9489
9490 /* There can be multiple CommonNames... */
9491 if (strcmp((char *) data_str, user_name) == 0) {
9492 field_value = data_str;
9493 allow_user = TRUE;
9494
9495 tls_log("matched client cert CommonName '%s' to user '%s'",
9496 field_value, user_name);
9497 break;
9498 }
9499 }
9500 }
9501
9502 } else if (strcmp(field_name, "EmailSubjAltName") == 0) {
9503 STACK_OF(GENERAL_NAME) *sk_alt_names;
9504
9505 sk_alt_names = X509_get_ext_d2i(client_cert, NID_subject_alt_name, NULL,
9506 NULL);
9507 if (sk_alt_names != NULL) {
9508 register int i;
9509 int nnames = sk_GENERAL_NAME_num(sk_alt_names);
9510
9511 for (i = 0; i < nnames; i++) {
9512 GENERAL_NAME *name;
9513
9514 pr_signals_handle();
9515
9516 name = sk_GENERAL_NAME_value(sk_alt_names, i);
9517
9518 /* We're only looking for the Email type. */
9519 if (name->type == GEN_EMAIL) {
9520 int data_len;
9521 const unsigned char *data_str = NULL;
9522
9523 data_len = ASN1_STRING_length(name->d.ia5);
9524
9525 #if OPENSSL_VERSION_NUMBER >= 0x10100000L && \
9526 !defined(HAVE_LIBRESSL)
9527 data_str = ASN1_STRING_get0_data(name->d.ia5);
9528 #else
9529 data_str = ASN1_STRING_data(name->d.ia5);
9530 #endif /* OpenSSL 1.1.x and later */
9531
9532 /* Watch for any embedded NULs, which can cause verification
9533 * problems via spoofing.
9534 */
9535 if ((size_t) data_len != strlen((char *) data_str)) {
9536 tls_log("%s", "client cert Email SAN contains embedded NULs, "
9537 "ignoring as possible spoof attempt");
9538 tls_log("suspicious Email SubjAltName value: '%s'", data_str);
9539
9540 } else {
9541
9542 /* There can be multiple Email SANs... */
9543 if (strcmp((char *) data_str, user_name) == 0) {
9544 field_value = data_str;
9545 allow_user = TRUE;
9546
9547 tls_log("matched client cert Email SubjAltName '%s' to user '%s'",
9548 field_value, user_name);
9549 GENERAL_NAME_free(name);
9550 break;
9551 }
9552 }
9553 }
9554
9555 GENERAL_NAME_free(name);
9556 }
9557
9558 sk_GENERAL_NAME_free(sk_alt_names);
9559 }
9560
9561 } else {
9562 /* Custom OID. */
9563 int nexts;
9564
9565 nexts = X509_get_ext_count(client_cert);
9566 if (nexts > 0) {
9567 register int i;
9568
9569 for (i = 0; i < nexts; i++) {
9570 const X509_EXTENSION *ext = NULL;
9571 const ASN1_OBJECT *asn_object = NULL;
9572 char oid[PR_TUNABLE_PATH_MAX];
9573
9574 pr_signals_handle();
9575
9576 ext = X509_get_ext(client_cert, i);
9577 asn_object = X509_EXTENSION_get_object(ext);
9578
9579 /* Get the OID of this extension, as a string. */
9580 memset(oid, '\0', sizeof(oid));
9581 if (OBJ_obj2txt(oid, sizeof(oid)-1, asn_object, 1) > 0) {
9582 if (strcmp(oid, field_name) == 0) {
9583 const ASN1_OCTET_STRING *asn_data = NULL;
9584 const unsigned char *asn_datastr = NULL;
9585 int asn_datalen;
9586
9587 asn_data = X509_EXTENSION_get_data(ext);
9588 asn_datalen = ASN1_STRING_length(asn_data);
9589 #if OPENSSL_VERSION_NUMBER >= 0x10100000L && \
9590 !defined(HAVE_LIBRESSL)
9591 asn_datastr = ASN1_STRING_get0_data(asn_data);
9592 #else
9593 asn_datastr = ASN1_STRING_data(asn_data);
9594 #endif /* OpenSSL 1.1.x and later */
9595
9596 /* Watch for any embedded NULs, which can cause verification
9597 * problems via spoofing.
9598 */
9599 if ((size_t) asn_datalen != strlen((char *) asn_datastr)) {
9600 tls_log("client cert %s extension contains embedded NULs, "
9601 "ignoring as possible spoof attempt", field_name);
9602 tls_log("suspicious %s extension value: '%s'", field_name,
9603 asn_datastr);
9604
9605 } else {
9606
9607 /* There might be multiple matching extensions? */
9608 if (strcmp((char *) asn_datastr, user_name) == 0) {
9609 field_value = asn_datastr;
9610 allow_user = TRUE;
9611
9612 tls_log("matched client cert %s extension '%s' to user '%s'",
9613 field_name, field_value, user_name);
9614 break;
9615 }
9616 }
9617 }
9618 }
9619 }
9620 }
9621 }
9622
9623 X509_free(client_cert);
9624 return allow_user;
9625 }
9626
9627 static int tls_readmore(int rfd) {
9628 fd_set rfds;
9629 struct timeval tv;
9630
9631 FD_ZERO(&rfds);
9632 FD_SET(rfd, &rfds);
9633
9634 /* Use a timeout of 15 seconds */
9635 tv.tv_sec = 15;
9636 tv.tv_usec = 0;
9637
9638 return select(rfd + 1, &rfds, NULL, NULL, &tv);
9639 }
9640
9641 static int tls_writemore(int wfd) {
9642 fd_set wfds;
9643 struct timeval tv;
9644
9645 FD_ZERO(&wfds);
9646 FD_SET(wfd, &wfds);
9647
9648 /* Use a timeout of 15 seconds */
9649 tv.tv_sec = 15;
9650 tv.tv_usec = 0;
9651
9652 return select(wfd + 1, NULL, &wfds, NULL, &tv);
9653 }
9654
9655 static ssize_t tls_read(SSL *ssl, void *buf, size_t len) {
9656 ssize_t count;
9657 int lineno, xerrno = 0;
9658
9659 retry:
9660 pr_signals_handle();
9661
9662 /* Help ensure we have a clean/trustable errno value. */
9663 errno = 0;
9664
9665 lineno = __LINE__ + 1;
9666 count = SSL_read(ssl, buf, len);
9667 xerrno = errno;
9668
9669 if (count < 0) {
9670 long err;
9671 int fd;
9672
9673 err = SSL_get_error(ssl, count);
9674 fd = SSL_get_fd(ssl);
9675
9676 /* read(2) returns only the generic error number -1 */
9677 count = -1;
9678
9679 switch (err) {
9680 case SSL_ERROR_WANT_READ:
9681 /* OpenSSL needs more data from the wire to finish the current block,
9682 * so we wait a little while for it.
9683 */
9684 pr_trace_msg(trace_channel, 17,
9685 "WANT_READ encountered while reading TLS data on fd %d, "
9686 "waiting to read data", fd);
9687 err = tls_readmore(fd);
9688 if (err > 0) {
9689 goto retry;
9690
9691 } else if (err == 0) {
9692 /* Still missing data after timeout. Simulate an EINTR and return.
9693 */
9694 xerrno = EINTR;
9695
9696 /* If err < 0, i.e. some error from the select(), everything is
9697 * already in place; errno is properly set and this function
9698 * returns -1.
9699 */
9700 break;
9701 }
9702
9703 case SSL_ERROR_WANT_WRITE:
9704 /* OpenSSL needs to write more data to the wire to finish the current
9705 * block, so we wait a little while for it.
9706 */
9707 pr_trace_msg(trace_channel, 17,
9708 "WANT_WRITE encountered while writing TLS data on fd %d, "
9709 "waiting to send data", fd);
9710 err = tls_writemore(fd);
9711 if (err > 0) {
9712 goto retry;
9713
9714 } else if (err == 0) {
9715 /* Still missing data after timeout. Simulate an EINTR and return.
9716 */
9717 xerrno = EINTR;
9718
9719 /* If err < 0, i.e. some error from the select(), everything is
9720 * already in place; errno is properly set and this function
9721 * returns -1.
9722 */
9723 break;
9724 }
9725
9726 case SSL_ERROR_ZERO_RETURN:
9727 tls_log("read EOF from client");
9728 break;
9729
9730 case SSL_ERROR_SSL:
9731 case SSL_ERROR_SYSCALL:
9732 default:
9733 tls_fatal_error(err, lineno);
9734 break;
9735 }
9736 }
9737
9738 errno = xerrno;
9739 return count;
9740 }
9741
9742 static int tls_seed_prng(void) {
9743 char *heapdata, stackdata[1024];
9744 static char rand_file[300];
9745 FILE *fp = NULL;
9746
9747 #if OPENSSL_VERSION_NUMBER >= 0x00905100L
9748 if (RAND_status() == 1)
9749
9750 /* PRNG already well-seeded. */
9751 return 0;
9752 #endif
9753
9754 tls_log("PRNG not seeded with enough data, looking for entropy sources");
9755
9756 /* If the device '/dev/urandom' is present, OpenSSL uses it by default.
9757 * Check if it's present, else we have to make random data ourselves.
9758 */
9759 fp = fopen("/dev/urandom", "r");
9760 if (fp != NULL) {
9761 fclose(fp);
9762
9763 tls_log("device /dev/urandom is present, assuming OpenSSL will use that "
9764 "for PRNG data");
9765 return 0;
9766 }
9767
9768 /* Lookup any configured TLSRandomSeed. */
9769 tls_rand_file = get_param_ptr(main_server->conf, "TLSRandomSeed", FALSE);
9770 if (tls_rand_file == NULL) {
9771 /* The ftpd's random file is (openssl-dir)/.rnd */
9772 memset(rand_file, '\0', sizeof(rand_file));
9773 pr_snprintf(rand_file, sizeof(rand_file)-1, "%s/.rnd",
9774 X509_get_default_cert_area());
9775 tls_rand_file = rand_file;
9776 }
9777
9778 #if OPENSSL_VERSION_NUMBER >= 0x00905100L
9779 /* In OpenSSL 0.9.5 and later, specifying -1 here means "read the entire
9780 * file", which is exactly what we want.
9781 */
9782 if (RAND_load_file(tls_rand_file, -1) == 0) {
9783 #else
9784 /* In versions of OpenSSL prior to 0.9.5, we have to specify the amount of
9785 * bytes to read in. Since RAND_write_file(3) typically writes 1K of data
9786 * out, we will read 1K bytes in.
9787 */
9788 if (RAND_load_file(tls_rand_file, 1024) != 1024) {
9789 #endif
9790 struct timeval tv;
9791 pid_t pid;
9792
9793 #if OPENSSL_VERSION_NUMBER >= 0x00905100L
9794 tls_log("unable to load PRNG seed data from '%s': %s", tls_rand_file,
9795 tls_get_errors());
9796 #else
9797 tls_log("unable to load 1024 bytes of PRNG seed data from '%s': %s",
9798 tls_rand_file, tls_get_errors());
9799 #endif
9800
9801 /* No random file found, create new seed. */
9802 gettimeofday(&tv, NULL);
9803 RAND_seed(&(tv.tv_sec), sizeof(tv.tv_sec));
9804 RAND_seed(&(tv.tv_usec), sizeof(tv.tv_usec));
9805
9806 pid = getpid();
9807 RAND_seed(&pid, sizeof(pid_t));
9808 RAND_seed(stackdata, sizeof(stackdata));
9809
9810 heapdata = malloc(sizeof(stackdata));
9811 if (heapdata != NULL) {
9812 RAND_seed(heapdata, sizeof(stackdata));
9813 free(heapdata);
9814 }
9815
9816 } else {
9817 tls_log("loaded PRNG seed data from '%s'", tls_rand_file);
9818 }
9819
9820 #if OPENSSL_VERSION_NUMBER >= 0x00905100L
9821 if (RAND_status() == 0) {
9822 /* PRNG still badly seeded. */
9823 return -1;
9824 }
9825 #endif
9826
9827 return 0;
9828 }
9829
9830 /* Note: these mappings should probably be added to the mod_tls docs.
9831 */
9832
9833 static void tls_setup_cert_ext_environ(const char *env_prefix, X509 *cert) {
9834
9835 /* NOTE: in the future, add ways of adding subjectAltName (and other
9836 * extensions?) to the environment.
9837 */
9838
9839 #if 0
9840 int nexts = 0;
9841
9842 nexts = X509_get_ext_count(cert);
9843 if (nexts > 0) {
9844 register int i;
9845
9846 for (i = 0; i < nexts; i++) {
9847 X509_EXTENSION *ext;
9848 const char *extstr;
9849
9850 ext = X509_get_ext(cert, i);
9851 extstr = OBJ_nid2sn(OBJ_obj2nid(X509_EXTENSION_get_object(ext)));
9852 }
9853 }
9854 #endif
9855
9856 return;
9857 }
9858
9859 /* Note: these mappings should probably be added to the mod_tls docs.
9860 *
9861 * Name Short Name NID
9862 * ---- ---------- ---
9863 * countryName C NID_countryName
9864 * commonName CN NID_commonName
9865 * description D NID_description
9866 * givenName G NID_givenName
9867 * initials I NID_initials
9868 * localityName L NID_localityName
9869 * organizationName O NID_organizationName
9870 * organizationalUnitName OU NID_organizationalUnitName
9871 * stateOrProvinceName ST NID_stateOrProvinceName
9872 * surname S NID_surname
9873 * title T NID_title
9874 * uniqueIdentifer UID NID_x500UniqueIdentifier
9875 * (or NID_uniqueIdentifier, depending
9876 * on OpenSSL version)
9877 * email Email NID_pkcs9_emailAddress
9878 */
9879
9880 static void tls_setup_cert_dn_environ(const char *env_prefix,
9881 const X509_NAME *name) {
9882 register int i;
9883 int nentries;
9884 char *k, *v;
9885
9886 #if OPENSSL_VERSION_NUMBER >= 0x10100000L
9887 nentries = X509_NAME_entry_count(name);
9888 #else
9889 nentries = sk_X509_NAME_ENTRY_num(name->entries);
9890 #endif /* OpenSSL-1.1.x and later */
9891
9892 for (i = 0; i < nentries; i++) {
9893 const X509_NAME_ENTRY *entry;
9894 const unsigned char *entry_data;
9895 int nid, entry_len;
9896
9897 pr_signals_handle();
9898
9899 #if OPENSSL_VERSION_NUMBER >= 0x10100000L
9900 entry = X509_NAME_get_entry(name, i);
9901 nid = OBJ_obj2nid(X509_NAME_ENTRY_get_object(entry));
9902 entry_data = ASN1_STRING_get0_data(X509_NAME_ENTRY_get_data(entry));
9903 entry_len = ASN1_STRING_length(X509_NAME_ENTRY_get_data(entry));
9904 #else
9905 entry = sk_X509_NAME_ENTRY_value(name->entries, i);
9906 nid = OBJ_obj2nid(entry->object);
9907 entry_data = entry->value->data;
9908 entry_len = entry->value->length;
9909 #endif /* OpenSSL-1.1.x and later */
9910
9911 switch (nid) {
9912 case NID_countryName:
9913 k = pstrcat(session.pool, env_prefix, "C", NULL);
9914 v = pstrndup(session.pool, (const char *) entry_data, entry_len);
9915 pr_env_set(session.pool, k, v);
9916 break;
9917
9918 case NID_commonName:
9919 k = pstrcat(session.pool, env_prefix, "CN", NULL);
9920 v = pstrndup(session.pool, (const char *) entry_data, entry_len);
9921 pr_env_set(session.pool, k, v);
9922 break;
9923
9924 case NID_description:
9925 k = pstrcat(main_server->pool, env_prefix, "D", NULL);
9926 v = pstrndup(session.pool, (const char *) entry_data, entry_len);
9927 pr_env_set(main_server->pool, k, v);
9928 break;
9929
9930 case NID_givenName:
9931 k = pstrcat(main_server->pool, env_prefix, "G", NULL);
9932 v = pstrndup(session.pool, (const char *) entry_data, entry_len);
9933 pr_env_set(main_server->pool, k, v);
9934 break;
9935
9936 case NID_initials:
9937 k = pstrcat(main_server->pool, env_prefix, "I", NULL);
9938 v = pstrndup(session.pool, (const char *) entry_data, entry_len);
9939 pr_env_set(main_server->pool, k, v);
9940 break;
9941
9942 case NID_localityName:
9943 k = pstrcat(main_server->pool, env_prefix, "L", NULL);
9944 v = pstrndup(session.pool, (const char *) entry_data, entry_len);
9945 pr_env_set(main_server->pool, k, v);
9946 break;
9947
9948 case NID_organizationName:
9949 k = pstrcat(main_server->pool, env_prefix, "O", NULL);
9950 v = pstrndup(session.pool, (const char *) entry_data, entry_len);
9951 pr_env_set(main_server->pool, k, v);
9952 break;
9953
9954 case NID_organizationalUnitName:
9955 k = pstrcat(main_server->pool, env_prefix, "OU", NULL);
9956 v = pstrndup(session.pool, (const char *) entry_data, entry_len);
9957 pr_env_set(main_server->pool, k, v);
9958 break;
9959
9960 case NID_stateOrProvinceName:
9961 k = pstrcat(main_server->pool, env_prefix, "ST", NULL);
9962 v = pstrndup(session.pool, (const char *) entry_data, entry_len);
9963 pr_env_set(main_server->pool, k, v);
9964 break;
9965
9966 case NID_surname:
9967 k = pstrcat(main_server->pool, env_prefix, "S", NULL);
9968 v = pstrndup(session.pool, (const char *) entry_data, entry_len);
9969 pr_env_set(main_server->pool, k, v);
9970 break;
9971
9972 case NID_title:
9973 k = pstrcat(main_server->pool, env_prefix, "T", NULL);
9974 v = pstrndup(session.pool, (const char *) entry_data, entry_len);
9975 pr_env_set(main_server->pool, k, v);
9976 break;
9977
9978 #if OPENSSL_VERSION_NUMBER >= 0x00907000L
9979 case NID_x500UniqueIdentifier:
9980 #else
9981 case NID_uniqueIdentifier:
9982 #endif
9983 k = pstrcat(main_server->pool, env_prefix, "UID", NULL);
9984 v = pstrndup(session.pool, (const char *) entry_data, entry_len);
9985 pr_env_set(main_server->pool, k, v);
9986 break;
9987
9988 case NID_pkcs9_emailAddress:
9989 k = pstrcat(main_server->pool, env_prefix, "Email", NULL);
9990 v = pstrndup(session.pool, (const char *) entry_data, entry_len);
9991 pr_env_set(main_server->pool, k, v);
9992 break;
9993
9994 default:
9995 break;
9996 }
9997 }
9998 }
9999
10000 static void tls_setup_cert_environ(pool *p, const char *env_prefix,
10001 X509 *cert) {
10002 char *data = NULL, *k, *v;
10003 long datalen = 0;
10004 BIO *bio = NULL;
10005
10006 if (tls_opts & TLS_OPT_STD_ENV_VARS) {
10007 char buf[80] = {'\0'};
10008 ASN1_INTEGER *serial = X509_get_serialNumber(cert);
10009 const X509_ALGOR *algo = NULL;
10010 const X509_PUBKEY *pubkey = NULL;
10011
10012 memset(buf, '\0', sizeof(buf));
10013 pr_snprintf(buf, sizeof(buf) - 1, "%lu", X509_get_version(cert) + 1);
10014 buf[sizeof(buf)-1] = '\0';
10015
10016 k = pstrcat(p, env_prefix, "M_VERSION", NULL);
10017 v = pstrdup(p, buf);
10018 pr_env_set(p, k, v);
10019
10020 if (ASN1_STRING_length(serial) < 4) {
10021 memset(buf, '\0', sizeof(buf));
10022 pr_snprintf(buf, sizeof(buf) - 1, "%lu", ASN1_INTEGER_get(serial));
10023 buf[sizeof(buf)-1] = '\0';
10024
10025 k = pstrcat(p, env_prefix, "M_SERIAL", NULL);
10026 v = pstrdup(p, buf);
10027 pr_env_set(p, k, v);
10028
10029 } else {
10030
10031 /* NOTE: actually, the number is printable, I'm just being lazy. This
10032 * case is much harder to deal with, and not really worth the effort.
10033 */
10034 tls_log("%s", "certificate serial number not printable");
10035 }
10036
10037 k = pstrcat(p, env_prefix, "S_DN", NULL);
10038 v = pstrdup(p, tls_x509_name_oneline(X509_get_subject_name(cert)));
10039 pr_env_set(p, k, v);
10040
10041 tls_setup_cert_dn_environ(pstrcat(p, env_prefix, "S_DN_",
10042 NULL), X509_get_subject_name(cert));
10043
10044 k = pstrcat(p, env_prefix, "I_DN", NULL);
10045 v = pstrdup(p, tls_x509_name_oneline(X509_get_issuer_name(cert)));
10046 pr_env_set(p, k, v);
10047
10048 tls_setup_cert_dn_environ(pstrcat(p, env_prefix, "I_DN_", NULL),
10049 X509_get_issuer_name(cert));
10050
10051 tls_setup_cert_ext_environ(pstrcat(p, env_prefix, "EXT_", NULL), cert);
10052
10053 bio = BIO_new(BIO_s_mem());
10054 #if OPENSSL_VERSION_NUMBER < 0x10100000L || \
10055 defined(HAVE_LIBRESSL)
10056 ASN1_TIME_print(bio, X509_get_notBefore(cert));
10057 #else
10058 ASN1_TIME_print(bio, X509_get0_notBefore(cert));
10059 #endif
10060 datalen = BIO_get_mem_data(bio, &data);
10061 data[datalen] = '\0';
10062
10063 k = pstrcat(p, env_prefix, "V_START", NULL);
10064 v = pstrdup(p, data);
10065 pr_env_set(p, k, v);
10066
10067 BIO_free(bio);
10068
10069 bio = BIO_new(BIO_s_mem());
10070 #if OPENSSL_VERSION_NUMBER < 0x10100000L || \
10071 defined(HAVE_LIBRESSL)
10072 ASN1_TIME_print(bio, X509_get_notAfter(cert));
10073 #else
10074 ASN1_TIME_print(bio, X509_get0_notAfter(cert));
10075 #endif
10076 datalen = BIO_get_mem_data(bio, &data);
10077 data[datalen] = '\0';
10078
10079 k = pstrcat(p, env_prefix, "V_END", NULL);
10080 v = pstrdup(p, data);
10081 pr_env_set(p, k, v);
10082
10083 BIO_free(bio);
10084
10085 bio = BIO_new(BIO_s_mem());
10086 #if (OPENSSL_VERSION_NUMBER >= 0x10100000L && !defined(HAVE_LIBRESSL)) || \
10087 (defined(HAVE_LIBRESSL) && LIBRESSL_VERSION_NUMBER >= 0x3050000L)
10088 X509_get0_signature(NULL, &algo, cert);
10089 #else
10090 algo = cert->cert_info->signature;
10091 #endif /* OpenSSL-1.1.x/LibreSSL-3.5.x and later */
10092 i2a_ASN1_OBJECT(bio, algo->algorithm);
10093 datalen = BIO_get_mem_data(bio, &data);
10094 data[datalen] = '\0';
10095
10096 k = pstrcat(p, env_prefix, "A_SIG", NULL);
10097 v = pstrdup(p, data);
10098 pr_env_set(p, k, v);
10099
10100 BIO_free(bio);
10101
10102 bio = BIO_new(BIO_s_mem());
10103 #if (OPENSSL_VERSION_NUMBER >= 0x10100000L && !defined(HAVE_LIBRESSL)) || \
10104 (defined(HAVE_LIBRESSL) && LIBRESSL_VERSION_NUMBER >= 0x3050000L)
10105 pubkey = X509_get_X509_PUBKEY(cert);
10106 X509_PUBKEY_get0_param(NULL, NULL, NULL, (X509_ALGOR **) &algo, pubkey);
10107 #else
10108 pubkey = cert->cert_info->key;
10109 algo = pubkey->algor;
10110 #endif /* OpenSSL-1.1.x/LibreSSL-3.5.x and later */
10111 i2a_ASN1_OBJECT(bio, algo->algorithm);
10112 datalen = BIO_get_mem_data(bio, &data);
10113 data[datalen] = '\0';
10114
10115 k = pstrcat(p, env_prefix, "A_KEY", NULL);
10116 v = pstrdup(p, data);
10117 pr_env_set(p, k, v);
10118
10119 BIO_free(bio);
10120 }
10121
10122 bio = BIO_new(BIO_s_mem());
10123 PEM_write_bio_X509(bio, cert);
10124 datalen = BIO_get_mem_data(bio, &data);
10125 data[datalen] = '\0';
10126
10127 k = pstrcat(p, env_prefix, "CERT", NULL);
10128 v = pstrdup(p, data);
10129 pr_env_set(p, k, v);
10130
10131 BIO_free(bio);
10132 }
10133
10134 static void tls_setup_environ(pool *p, SSL *ssl) {
10135 X509 *cert = NULL;
10136 STACK_OF(X509) *sk_cert_chain = NULL;
10137 char *k, *v;
10138
10139 if (!(tls_opts & TLS_OPT_EXPORT_CERT_DATA) &&
10140 !(tls_opts & TLS_OPT_STD_ENV_VARS)) {
10141 return;
10142 }
10143
10144 if (tls_opts & TLS_OPT_STD_ENV_VARS) {
10145 SSL_CIPHER *cipher = NULL;
10146 SSL_SESSION *ssl_session = NULL;
10147 const char *sni = NULL;
10148
10149 k = pstrdup(p, "FTPS");
10150 v = pstrdup(p, "1");
10151 pr_env_set(p, k, v);
10152
10153 k = pstrdup(p, "TLS_PROTOCOL");
10154 v = pstrdup(p, SSL_get_version(ssl));
10155 pr_env_set(p, k, v);
10156
10157 /* Process the TLS session-related environ variable. */
10158 ssl_session = SSL_get_session(ssl);
10159 if (ssl_session != NULL) {
10160 const unsigned char *sess_data;
10161 unsigned int sess_datalen;
10162 char *sess_id;
10163
10164 #if OPENSSL_VERSION_NUMBER >= 0x10100000L
10165 sess_data = SSL_SESSION_get_id(ssl_session, &sess_datalen);
10166 #else
10167 sess_datalen = ssl_session->session_id_length;
10168 sess_data = ssl_session->session_id;
10169 #endif /* OpenSSL-1.1.x and later */
10170
10171 sess_id = pr_str_bin2hex(p, sess_data, sess_datalen,
10172 PR_STR_FL_HEX_USE_UC);
10173
10174 k = pstrdup(p, "TLS_SESSION_ID");
10175 pr_env_set(p, k, sess_id);
10176 }
10177
10178 /* Process the TLS cipher-related environ variables. */
10179 cipher = (SSL_CIPHER *) SSL_get_current_cipher(ssl);
10180 if (cipher != NULL) {
10181 char buf[10] = {'\0'};
10182 int cipher_bits_used = 0, cipher_bits_possible = 0;
10183
10184 k = pstrdup(p, "TLS_CIPHER");
10185 v = pstrdup(p, SSL_CIPHER_get_name(cipher));
10186 pr_env_set(p, k, v);
10187
10188 cipher_bits_used = SSL_CIPHER_get_bits(cipher, &cipher_bits_possible);
10189
10190 if (cipher_bits_used < 56) {
10191 k = pstrdup(p, "TLS_CIPHER_EXPORT");
10192 v = pstrdup(p, "1");
10193 pr_env_set(p, k, v);
10194 }
10195
10196 memset(buf, '\0', sizeof(buf));
10197 pr_snprintf(buf, sizeof(buf), "%d", cipher_bits_possible);
10198 buf[sizeof(buf)-1] = '\0';
10199
10200 k = pstrdup(p, "TLS_CIPHER_KEYSIZE_POSSIBLE");
10201 v = pstrdup(p, buf);
10202 pr_env_set(p, k, v);
10203
10204 memset(buf, '\0', sizeof(buf));
10205 pr_snprintf(buf, sizeof(buf), "%d", cipher_bits_used);
10206 buf[sizeof(buf)-1] = '\0';
10207
10208 k = pstrdup(p, "TLS_CIPHER_KEYSIZE_USED");
10209 v = pstrdup(p, buf);
10210 pr_env_set(p, k, v);
10211 }
10212
10213 sni = pr_table_get(session.notes, "mod_tls.sni", NULL);
10214 if (sni != NULL) {
10215 k = pstrdup(p, "TLS_SERVER_NAME");
10216 v = pstrdup(p, sni);
10217 pr_env_set(p, k, v);
10218 }
10219
10220 k = pstrdup(p, "TLS_LIBRARY_VERSION");
10221 v = pstrdup(p, OPENSSL_VERSION_TEXT);
10222 pr_env_set(p, k, v);
10223 }
10224
10225 sk_cert_chain = SSL_get_peer_cert_chain(ssl);
10226 if (sk_cert_chain != NULL) {
10227 register int i;
10228 char *data = NULL;
10229 long datalen = 0;
10230 BIO *bio = NULL;
10231
10232 /* Adding TLS_CLIENT_CERT_CHAIN environ variables. */
10233 for (i = 0; i < sk_X509_num(sk_cert_chain); i++) {
10234 size_t klen = 256;
10235
10236 pr_signals_handle();
10237
10238 k = pcalloc(p, klen);
10239 pr_snprintf(k, klen - 1, "%s%u", "TLS_CLIENT_CERT_CHAIN", i + 1);
10240
10241 bio = BIO_new(BIO_s_mem());
10242 PEM_write_bio_X509(bio, sk_X509_value(sk_cert_chain, i));
10243 datalen = BIO_get_mem_data(bio, &data);
10244 data[datalen] = '\0';
10245
10246 v = pstrdup(p, data);
10247 pr_env_set(p, k, v);
10248
10249 BIO_free(bio);
10250 }
10251 }
10252
10253 /* Note: SSL_get_certificate() does NOT increment a reference counter,
10254 * so we do not call X509_free() on it.
10255 */
10256 cert = SSL_get_certificate(ssl);
10257 if (cert != NULL) {
10258 tls_setup_cert_environ(p, "TLS_SERVER_", cert);
10259
10260 } else {
10261 tls_log("unable to set server certificate environ variables: "
10262 "Server certificate unavailable");
10263 }
10264
10265 cert = SSL_get_peer_certificate(ssl);
10266 if (cert != NULL) {
10267 tls_setup_cert_environ(p, "TLS_CLIENT_", cert);
10268 X509_free(cert);
10269
10270 } else {
10271 tls_log("unable to set client certificate environ variables: "
10272 "Client certificate unavailable");
10273 }
10274 }
10275
10276 static void tls_setup_notes(pool *p, SSL *ssl) {
10277 X509 *client_cert = NULL;
10278 SSL_CIPHER *cipher = NULL;
10279 const char *sni = NULL;
10280
10281 (void) pr_table_add_dup(session.notes, "FTPS", "1", 0);
10282 (void) pr_table_add_dup(session.notes, "TLS_PROTOCOL", SSL_get_version(ssl),
10283 0);
10284
10285 /* Process the TLS cipher-related values. */
10286 cipher = (SSL_CIPHER *) SSL_get_current_cipher(ssl);
10287 if (cipher != NULL) {
10288 (void) pr_table_add_dup(session.notes, "TLS_CIPHER",
10289 SSL_CIPHER_get_name(cipher), 0);
10290 }
10291
10292 sni = pr_table_get(session.notes, "mod_tls.sni", NULL);
10293 if (sni != NULL) {
10294 (void) pr_table_add_dup(session.notes, "TLS_SERVER_NAME", sni, 0);
10295 }
10296
10297 client_cert = SSL_get_peer_certificate(ssl);
10298 if (client_cert != NULL) {
10299 const X509_ALGOR *algo = NULL;
10300 const X509_PUBKEY *pubkey = NULL;
10301 BIO *bio = NULL;
10302 char *data = NULL;
10303 long datalen = 0;
10304
10305 /* Client cert CN */
10306 data = tls_get_cert_cn(p, client_cert);
10307 if (data != NULL) {
10308 (void) pr_table_add_dup(session.notes, "TLS_CLIENT_S_DN_CN", data, 0);
10309 }
10310
10311 /* Client cert key algo */
10312 bio = BIO_new(BIO_s_mem());
10313 #if OPENSSL_VERSION_NUMBER >= 0x10100000L
10314 pubkey = X509_get_X509_PUBKEY(client_cert);
10315 X509_PUBKEY_get0_param(NULL, NULL, NULL, (X509_ALGOR **) &algo, pubkey);
10316 #else
10317 pubkey = client_cert->cert_info->key;
10318 algo = pubkey->algor;
10319 #endif /* OpenSSL-1.1.x and later */
10320 i2a_ASN1_OBJECT(bio, algo->algorithm);
10321 datalen = BIO_get_mem_data(bio, &data);
10322 data[datalen] = '\0';
10323
10324 (void) pr_table_add_dup(session.notes, "TLS_CLIENT_A_KEY", data, 0);
10325 BIO_free(bio);
10326
10327 /* Client cert signature algorithm. */
10328 bio = BIO_new(BIO_s_mem());
10329 #if (OPENSSL_VERSION_NUMBER >= 0x10100000L && !defined(HAVE_LIBRESSL)) || \
10330 (defined(HAVE_LIBRESSL) && LIBRESSL_VERSION_NUMBER >= 0x3050000L)
10331 X509_get0_signature(NULL, &algo, client_cert);
10332 #else
10333 algo = client_cert->cert_info->signature;
10334 #endif /* OpenSSL-1.1.x/Libre-3.5.x and later */
10335 i2a_ASN1_OBJECT(bio, algo->algorithm);
10336 datalen = BIO_get_mem_data(bio, &data);
10337 data[datalen] = '\0';
10338
10339 (void) pr_table_add_dup(session.notes, "TLS_CLIENT_A_SIG", data, 0);
10340 BIO_free(bio);
10341 }
10342
10343 (void) pr_table_add_dup(session.notes, "TLS_LIBRARY_VERSION",
10344 OPENSSL_VERSION_TEXT, 0);
10345 }
10346
10347 static int tls_verify_cb(int ok, X509_STORE_CTX *ctx) {
10348 config_rec *c;
10349 int verify_error = 0;
10350
10351 /* We can configure the server to skip the peer's cert verification */
10352 if (!(tls_flags & TLS_SESS_VERIFY_CLIENT_REQUIRED) &&
10353 !(tls_flags & TLS_SESS_VERIFY_CLIENT_OPTIONAL)) {
10354 return 1;
10355 }
10356
10357 c = find_config(main_server->conf, CONF_PARAM, "TLSVerifyOrder", FALSE);
10358 if (c != NULL) {
10359 register unsigned int i;
10360
10361 for (i = 0; i < c->argc; i++) {
10362 char *mech = c->argv[i];
10363
10364 if (strcasecmp(mech, "crl") == 0) {
10365 ok = tls_verify_crl(ok, ctx);
10366 if (!ok) {
10367 break;
10368 }
10369
10370 } else if (strcasecmp(mech, "ocsp") == 0) {
10371 ok = tls_verify_ocsp(ok, ctx);
10372 if (!ok) {
10373 break;
10374 }
10375 }
10376 }
10377
10378 } else {
10379 /* If no TLSVerifyOrder was specified, default to the old behavior of
10380 * always checking CRLs, if configured, and not paying attention to
10381 * any AIA attributes (i.e. no use of OCSP).
10382 */
10383 ok = tls_verify_crl(ok, ctx);
10384 }
10385
10386 if (!ok) {
10387 X509 *cert;
10388 int ctx_error, depth;
10389
10390 cert = X509_STORE_CTX_get_current_cert(ctx);
10391 depth = X509_STORE_CTX_get_error_depth(ctx);
10392
10393 #if OPENSSL_VERSION_NUMBER >= 0x10100000L
10394 verify_error = X509_STORE_CTX_get_error(ctx);
10395 #else
10396 verify_error = ctx->error;
10397 #endif /* OpenSSL-1.1.x and later */
10398
10399 tls_log("error: unable to verify certificate at depth %d: %s", depth,
10400 X509_verify_cert_error_string(verify_error));
10401 tls_log("error: cert subject: %s", tls_x509_name_oneline(
10402 X509_get_subject_name(cert)));
10403 tls_log("error: cert issuer: %s", tls_x509_name_oneline(
10404 X509_get_issuer_name(cert)));
10405
10406 /* Catch a too long certificate chain here. */
10407 if (depth > tls_verify_depth) {
10408 /* Note that by setting this error, we are effectively overriding
10409 * the previous verification error; this could become the value of
10410 * the subsequent ctx_error.
10411 */
10412 X509_STORE_CTX_set_error(ctx, X509_V_ERR_CERT_CHAIN_TOO_LONG);
10413 }
10414
10415 #if OPENSSL_VERSION_NUMBER >= 0x10100000L
10416 ctx_error = X509_STORE_CTX_get_error(ctx);
10417 #else
10418 ctx_error = ctx->error;
10419 #endif /* OpenSSL-1.1.x and later */
10420
10421 switch (ctx_error) {
10422 case X509_V_ERR_APPLICATION_VERIFICATION:
10423 case X509_V_ERR_CERT_CHAIN_TOO_LONG:
10424 case X509_V_ERR_CERT_HAS_EXPIRED:
10425 case X509_V_ERR_CERT_REVOKED:
10426 case X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT:
10427 case X509_V_ERR_INVALID_PURPOSE:
10428 case X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN:
10429 case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY:
10430 case X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE:
10431 tls_log("client certificate failed verification: %s",
10432 X509_verify_cert_error_string(ctx_error));
10433 ok = 0;
10434 break;
10435
10436 default:
10437 tls_log("error verifying client certificate: [%d] %s",
10438 ctx_error, X509_verify_cert_error_string(ctx_error));
10439 ok = 0;
10440 break;
10441 }
10442 }
10443
10444 if (ok) {
10445 pr_event_generate("mod_tls.verify-client", NULL);
10446
10447 } else {
10448 pr_event_generate("mod_tls.verify-client-failed", &verify_error);
10449 }
10450
10451 return ok;
10452 }
10453
10454 static int tls_verify_crl(int ok, X509_STORE_CTX *ctx) {
10455 register unsigned int i = 0;
10456 const X509_NAME *subject = NULL, *issuer = NULL;
10457 X509 *xs = NULL;
10458 STACK_OF(X509_CRL) *crls = NULL;
10459 int res, verify_error;
10460
10461 verify_error = X509_STORE_CTX_get_error(ctx);
10462 xs = X509_STORE_CTX_get_current_cert(ctx);
10463 subject = X509_get_subject_name(xs);
10464 issuer = X509_get_issuer_name(xs);
10465
10466 pr_trace_msg(trace_channel, 15,
10467 "verifying cert: subject = '%s', issuer = '%s', error = %s (ok = %d)",
10468 tls_x509_name_oneline(subject), tls_x509_name_oneline(issuer),
10469 X509_verify_cert_error_string(verify_error), ok);
10470
10471 #if OPENSSL_VERSION_NUMBER >= 0x10100000L && \
10472 !defined(HAVE_LIBRESSL)
10473 crls = X509_STORE_CTX_get1_crls(ctx, issuer);
10474 #elif OPENSSL_VERSION_NUMBER >= 0x10000000L && \
10475 !defined(HAVE_LIBRESSL)
10476 crls = X509_STORE_get1_crls(ctx, issuer);
10477 #else
10478 /* Your OpenSSL is before 1.0.0. You really need to upgrade. */
10479 crls = NULL;
10480 #endif /* OpenSSL-1.1.x and later */
10481
10482 if (crls != NULL) {
10483 unsigned int crl_count;
10484 X509_OBJECT *obj = NULL;
10485 EVP_PKEY *pkey;
10486
10487 obj = X509_STORE_CTX_get_obj_by_subject(ctx, X509_LU_X509, issuer);
10488 if (obj == NULL) {
10489 pr_trace_msg(trace_channel, 1,
10490 "error getting CRL issuer '%s' certificate: %s",
10491 tls_x509_name_oneline(issuer), tls_get_errors());
10492 X509_STORE_CTX_set_error(ctx, X509_V_ERR_UNABLE_TO_GET_CRL);
10493 sk_X509_CRL_free(crls);
10494 return FALSE;
10495 }
10496
10497 pkey = X509_get_pubkey(X509_OBJECT_get0_X509(obj));
10498 X509_OBJECT_free(obj);
10499
10500 if (pkey == NULL) {
10501 pr_trace_msg(trace_channel, 1,
10502 "error getting CRL issuer '%s' public key: %s",
10503 tls_x509_name_oneline(issuer), tls_get_errors());
10504 X509_STORE_CTX_set_error(ctx, X509_V_ERR_CRL_SIGNATURE_FAILURE);
10505 sk_X509_CRL_free(crls);
10506 return FALSE;
10507 }
10508
10509 crl_count = sk_X509_CRL_num(crls);
10510 for (i = 0; i < crl_count; i++) {
10511 X509_CRL *crl = NULL;
10512 X509_NAME *crl_issuer = NULL;
10513 char buf[512];
10514 int len;
10515 BIO *b = BIO_new(BIO_s_mem());
10516
10517 crl = sk_X509_CRL_value(crls, i);
10518 BIO_printf(b, "Issuer: ");
10519 crl_issuer = X509_CRL_get_issuer(crl);
10520 X509_NAME_print(b, crl_issuer, 0);
10521
10522 BIO_printf(b, ", lastUpdate: ");
10523 #if OPENSSL_VERSION_NUMBER >= 0x10100000L
10524 ASN1_UTCTIME_print(b, X509_CRL_get0_lastUpdate(crl));
10525 #else
10526 ASN1_UTCTIME_print(b, crl->crl->lastUpdate);
10527 #endif /* OpenSSL-1.1.x and later */
10528
10529 BIO_printf(b, ", nextUpdate: ");
10530 #if OPENSSL_VERSION_NUMBER >= 0x10100000L
10531 ASN1_UTCTIME_print(b, X509_CRL_get0_nextUpdate(crl));
10532 #else
10533 ASN1_UTCTIME_print(b, crl->crl->nextUpdate);
10534 #endif /* OpenSSL-1.1.x and later */
10535
10536 len = BIO_read(b, buf, sizeof(buf) - 1);
10537 if ((size_t) len >= sizeof(buf)) {
10538 len = sizeof(buf)-1;
10539 }
10540 buf[len] = '\0';
10541
10542 BIO_free(b);
10543 tls_log("CRL: %s", buf);
10544
10545 /* Verify the signature on this CRL using the public key from the issuer
10546 * of the CRL.
10547 */
10548 res = X509_CRL_verify(crl, pkey);
10549 if (res <= 0) {
10550 tls_log("invalid signature on CRL: %s", tls_get_errors());
10551
10552 X509_STORE_CTX_set_error(ctx, X509_V_ERR_CRL_SIGNATURE_FAILURE);
10553 sk_X509_CRL_free(crls);
10554 return FALSE;
10555 }
10556
10557 /* Check the last update of the CRL to make sure it's valid. */
10558 #if OPENSSL_VERSION_NUMBER >= 0x10100000L && \
10559 !defined(HAVE_LIBRESSL)
10560 res = X509_cmp_current_time(X509_CRL_get0_lastUpdate(crl));
10561 #else
10562 res = X509_cmp_current_time(X509_CRL_get_lastUpdate(crl));
10563 #endif /* OpenSSL 1.1.x and later */
10564 if (res == 0) {
10565 tls_log("CRL has invalid lastUpdate field: %s", tls_get_errors());
10566
10567 X509_STORE_CTX_set_error(ctx,
10568 X509_V_ERR_ERROR_IN_CRL_LAST_UPDATE_FIELD);
10569 sk_X509_CRL_free(crls);
10570 return FALSE;
10571 }
10572
10573 if (res > 0) {
10574 tls_log("%s", "CRL is not yet valid, ignoring all certificates until "
10575 "an updated CRL is obtained");
10576
10577 X509_STORE_CTX_set_error(ctx, X509_V_ERR_CRL_NOT_YET_VALID);
10578 sk_X509_CRL_free(crls);
10579 return TRUE;
10580 }
10581
10582 /* Check next update of CRL to make sure it's not expired. */
10583 #if OPENSSL_VERSION_NUMBER >= 0x10100000L && \
10584 !defined(HAVE_LIBRESSL)
10585 res = X509_cmp_current_time(X509_CRL_get0_nextUpdate(crl));
10586 #else
10587 res = X509_cmp_current_time(X509_CRL_get_nextUpdate(crl));
10588 #endif /* OpenSSL 1.1.x and later */
10589
10590 if (res == 0) {
10591 tls_log("CRL has invalid lastUpdate field: %s", tls_get_errors());
10592
10593 X509_STORE_CTX_set_error(ctx,
10594 X509_V_ERR_ERROR_IN_CRL_LAST_UPDATE_FIELD);
10595 sk_X509_CRL_free(crls);
10596 return FALSE;
10597 }
10598
10599 if (res == 0) {
10600 tls_log("CRL has invalid nextUpdate field: %s", tls_get_errors());
10601
10602 X509_STORE_CTX_set_error(ctx,
10603 X509_V_ERR_ERROR_IN_CRL_NEXT_UPDATE_FIELD);
10604 sk_X509_CRL_free(crls);
10605 return FALSE;
10606 }
10607
10608 if (res < 0) {
10609 /* XXX This is a bit draconian, rejecting all certificates if the CRL
10610 * has expired. See also Bug#3216, about automatically reloading
10611 * the CRL file when it has expired.
10612 */
10613 tls_log("%s", "CRL is expired, revoking all certificates until an "
10614 "updated CRL is obtained");
10615
10616 X509_STORE_CTX_set_error(ctx, X509_V_ERR_CRL_HAS_EXPIRED);
10617 sk_X509_CRL_free(crls);
10618 return FALSE;
10619 }
10620 }
10621
10622 sk_X509_CRL_free(crls);
10623 crls = NULL;
10624 }
10625
10626 return ok;
10627 }
10628
10629 #if OPENSSL_VERSION_NUMBER > 0x000907000L && defined(PR_USE_OPENSSL_OCSP)
10630 static int tls_verify_ocsp_url(X509_STORE_CTX *ctx, X509 *cert,
10631 const char *url) {
10632 BIO *conn;
10633 X509 *issuing_cert = NULL;
10634 const X509_NAME *subj = NULL;
10635 X509_STORE *store = NULL;
10636 const char *subj_name;
10637 char *host = NULL, *port = NULL, *uri = NULL;
10638 int ok = FALSE, res = 0 , use_ssl = 0;
10639 int ocsp_status, ocsp_cert_status, ocsp_reason;
10640 OCSP_REQUEST *req = NULL;
10641 OCSP_RESPONSE *resp = NULL;
10642 OCSP_BASICRESP *basic_resp = NULL;
10643 SSL_CTX *ocsp_ssl_ctx = NULL;
10644
10645 if (cert == NULL ||
10646 url == NULL) {
10647 return FALSE;
10648 }
10649
10650 subj = X509_get_subject_name(cert);
10651 subj_name = tls_x509_name_oneline(subj);
10652
10653 tls_log("checking OCSP URL '%s' for client cert '%s'", url, subj_name);
10654
10655 /* Current OpenSSL implementation of OCSP_parse_url() guarantees that
10656 * host, port, and uri will never be NULL. Nice.
10657 */
10658 if (OCSP_parse_url((char *) url, &host, &port, &uri, &use_ssl) != 1) {
10659 tls_log("error parsing OCSP URL '%s': %s", url, tls_get_errors());
10660 return FALSE;
10661 }
10662
10663 tls_log("connecting to OCSP responder at host '%s', port '%s', URI '%s'%s",
10664 host, port, uri, use_ssl ? ", using SSL/TLS" : "");
10665
10666 /* Connect to the OCSP responder indicated */
10667 conn = BIO_new_connect(host);
10668 if (conn == NULL) {
10669 tls_log("error creating connection BIO: %s", tls_get_errors());
10670
10671 OPENSSL_free(host);
10672 OPENSSL_free(port);
10673 OPENSSL_free(uri);
10674
10675 return FALSE;
10676 }
10677
10678 BIO_set_conn_port(conn, port);
10679
10680 /* If use_ssl is true, we need to a) create an SSL_CTX object to use, and
10681 * push it onto the BIO chain so that SSL/TLS actually happens.
10682 * When doing so, what version of SSL/TLS should we use?
10683 */
10684 if (use_ssl == 1) {
10685 BIO *ocsp_ssl_bio = NULL;
10686
10687 /* Note: this code used openssl/apps/ocsp.c as a model. */
10688 ocsp_ssl_ctx = SSL_CTX_new(SSLv23_client_method());
10689 if (ocsp_ssl_ctx != NULL) {
10690 SSL_CTX_set_mode(ocsp_ssl_ctx, SSL_MODE_AUTO_RETRY);
10691
10692 ocsp_ssl_bio = BIO_new_ssl(ocsp_ssl_ctx, 1);
10693 BIO_push(ocsp_ssl_bio, conn);
10694
10695 } else {
10696 tls_log("error allocating SSL_CTX object for OCSP verification: %s",
10697 tls_get_errors());
10698 }
10699 }
10700
10701 res = ocsp_connect(session.pool, conn, 0);
10702 if (res < 0) {
10703 tls_log("error connecting to OCSP URL '%s': %s", url, tls_get_errors());
10704
10705 if (ocsp_ssl_ctx != NULL) {
10706 SSL_CTX_free(ocsp_ssl_ctx);
10707 }
10708
10709 BIO_free_all(conn);
10710 OPENSSL_free(host);
10711 OPENSSL_free(port);
10712 OPENSSL_free(uri);
10713
10714 /* XXX Should we give the client the benefit of the doubt, and allow
10715 * it to connect even though we can't talk to its OCSP responder? Or
10716 * do we fail-close, and penalize the client if the OCSP responder is
10717 * down (e.g. for maintenance)?
10718 */
10719
10720 return FALSE;
10721 }
10722
10723 /* XXX Why are we querying the OCSP responder about the client cert's
10724 * issuing CA, rather than querying about the client cert itself?
10725 */
10726
10727 res = X509_STORE_CTX_get1_issuer(&issuing_cert, ctx, cert);
10728 if (res != 1) {
10729 tls_log("error retrieving issuing cert for client cert '%s': %s",
10730 subj_name, tls_get_errors());
10731
10732 if (ocsp_ssl_ctx != NULL) {
10733 SSL_CTX_free(ocsp_ssl_ctx);
10734 }
10735
10736 BIO_free_all(conn);
10737 OPENSSL_free(host);
10738 OPENSSL_free(port);
10739 OPENSSL_free(uri);
10740
10741 return FALSE;
10742 }
10743
10744 req = ocsp_get_request(session.pool, cert, issuing_cert);
10745 if (req == NULL) {
10746 if (ocsp_ssl_ctx != NULL) {
10747 SSL_CTX_free(ocsp_ssl_ctx);
10748 }
10749
10750 X509_free(issuing_cert);
10751 BIO_free_all(conn);
10752 OPENSSL_free(host);
10753 OPENSSL_free(port);
10754 OPENSSL_free(uri);
10755
10756 return FALSE;
10757 }
10758
10759 # if 0
10760 /* XXX ideally we would set the requestor name to the subject name of the
10761 * cert configured via TLS{DSA,RSA}CertificateFile here.
10762 */
10763 if (OCSP_request_set1_name(req, /* server cert X509_NAME subj name */) != 1) {
10764 tls_log("error adding requestor name '%s' to OCSP request: %s",
10765 requestor_name, tls_get_errors());
10766
10767 if (ocsp_ssl_ctx != NULL) {
10768 SSL_CTX_free(ocsp_ssl_ctx);
10769 }
10770
10771 OCSP_REQUEST_free(req);
10772 X509_free(issuing_cert);
10773 BIO_free_all(conn);
10774 OPENSSL_free(host);
10775 OPENSSL_free(port);
10776 OPENSSL_free(uri);
10777
10778 return FALSE;
10779 }
10780 # endif
10781
10782 if (tls_opts & TLS_OPT_ENABLE_DIAGS) {
10783 BIO *bio;
10784
10785 bio = BIO_new(BIO_s_mem());
10786 if (bio != NULL) {
10787 if (OCSP_REQUEST_print(bio, req, 0) == 1) {
10788 char *data = NULL;
10789 long datalen;
10790
10791 datalen = BIO_get_mem_data(bio, &data);
10792 if (data != NULL) {
10793 data[datalen] = '\0';
10794 tls_log("sending OCSP request (%ld bytes):\n%s", datalen, data);
10795 }
10796 }
10797
10798 BIO_free(bio);
10799 }
10800 }
10801
10802 resp = ocsp_send_request(session.pool, conn, host, uri, req, 0);
10803 if (resp == NULL) {
10804 tls_log("error receiving response from OCSP responder at '%s': %s", url,
10805 tls_get_errors());
10806
10807 if (ocsp_ssl_ctx != NULL) {
10808 SSL_CTX_free(ocsp_ssl_ctx);
10809 }
10810
10811 OCSP_REQUEST_free(req);
10812 X509_free(issuing_cert);
10813 BIO_free_all(conn);
10814 OPENSSL_free(host);
10815 OPENSSL_free(port);
10816 OPENSSL_free(uri);
10817
10818 return FALSE;
10819 }
10820
10821 if (tls_opts & TLS_OPT_ENABLE_DIAGS) {
10822 BIO *bio;
10823
10824 bio = BIO_new(BIO_s_mem());
10825 if (bio != NULL) {
10826 if (OCSP_RESPONSE_print(bio, resp, 0) == 1) {
10827 char *data = NULL;
10828 long datalen;
10829
10830 datalen = BIO_get_mem_data(bio, &data);
10831 if (data != NULL) {
10832 data[datalen] = '\0';
10833 tls_log("received OCSP response (%ld bytes):\n%s", datalen, data);
10834 }
10835 }
10836
10837 BIO_free(bio);
10838 }
10839 }
10840
10841 tls_log("checking response from OCSP responder at URL '%s' for client cert "
10842 "'%s'", url, subj_name);
10843
10844 basic_resp = OCSP_response_get1_basic(resp);
10845 if (basic_resp == NULL) {
10846 tls_log("error retrieving basic response from OCSP responder at '%s': %s",
10847 url, tls_get_errors());
10848
10849 if (ocsp_ssl_ctx != NULL) {
10850 SSL_CTX_free(ocsp_ssl_ctx);
10851 }
10852
10853 OCSP_RESPONSE_free(resp);
10854 OCSP_REQUEST_free(req);
10855 X509_free(issuing_cert);
10856 BIO_free_all(conn);
10857 OPENSSL_free(host);
10858 OPENSSL_free(port);
10859 OPENSSL_free(uri);
10860
10861 return FALSE;
10862 }
10863
10864 #if (OPENSSL_VERSION_NUMBER >= 0x10100000L && !defined(HAVE_LIBRESSL)) || \
10865 (defined(HAVE_LIBRESSL) && LIBRESSL_VERSION_NUMBER >= 0x3050000L)
10866 store = X509_STORE_CTX_get0_store(ctx);
10867 #else
10868 store = ctx->ctx;
10869 #endif /* OpenSSL-1.1.x/LibreSSL-3.5.x and later */
10870 res = OCSP_basic_verify(basic_resp, NULL, store, 0);
10871 if (res != 1) {
10872 tls_log("error verifying basic response from OCSP responder at '%s': %s",
10873 url, tls_get_errors());
10874
10875 if (ocsp_ssl_ctx != NULL) {
10876 SSL_CTX_free(ocsp_ssl_ctx);
10877 }
10878
10879 OCSP_REQUEST_free(req);
10880 OCSP_BASICRESP_free(basic_resp);
10881 OCSP_RESPONSE_free(resp);
10882 X509_free(issuing_cert);
10883 BIO_free_all(conn);
10884 OPENSSL_free(host);
10885 OPENSSL_free(port);
10886 OPENSSL_free(uri);
10887
10888 return FALSE;
10889 }
10890
10891 /* Now that we have verified the response, we can check the response status.
10892 * If we only looked at the status first, then a malicious responder
10893 * could be tricking us, e.g.:
10894 *
10895 * http://www.thoughtcrime.org/papers/ocsp-attack.pdf
10896 */
10897
10898 ocsp_status = OCSP_response_status(resp);
10899 if (ocsp_status != OCSP_RESPONSE_STATUS_SUCCESSFUL) {
10900 tls_log("unable to verify client cert '%s' via OCSP responder at '%s': "
10901 "response status '%s' (%d)", subj_name, url,
10902 OCSP_response_status_str(ocsp_status), ocsp_status);
10903
10904 if (ocsp_ssl_ctx != NULL) {
10905 SSL_CTX_free(ocsp_ssl_ctx);
10906 }
10907
10908 OCSP_REQUEST_free(req);
10909 OCSP_BASICRESP_free(basic_resp);
10910 OCSP_RESPONSE_free(resp);
10911 X509_free(issuing_cert);
10912 BIO_free_all(conn);
10913 OPENSSL_free(host);
10914 OPENSSL_free(port);
10915 OPENSSL_free(uri);
10916
10917 switch (ocsp_status) {
10918 case OCSP_RESPONSE_STATUS_MALFORMEDREQUEST:
10919 case OCSP_RESPONSE_STATUS_INTERNALERROR:
10920 case OCSP_RESPONSE_STATUS_SIGREQUIRED:
10921 case OCSP_RESPONSE_STATUS_UNAUTHORIZED:
10922 case OCSP_RESPONSE_STATUS_TRYLATER:
10923 /* XXX For now, for the above OCSP response reasons, give the client
10924 * the benefit of the doubt, since all of the above non-success
10925 * response codes indicate either a) an issue with the OCSP responder
10926 * outside of the client's control, or b) an issue with our OCSP
10927 * implementation (e.g. SIGREQUIRED, UNAUTHORIZED).
10928 */
10929 ok = TRUE;
10930 break;
10931
10932 default:
10933 ok = FALSE;
10934 }
10935
10936 return ok;
10937 }
10938
10939 if (ocsp_check_cert_status(session.pool, cert, issuing_cert, basic_resp,
10940 &ocsp_cert_status, &ocsp_reason) < 0) {
10941 tls_log("unable to retrieve cert status from OCSP response: %s",
10942 tls_get_errors());
10943
10944 if (ocsp_ssl_ctx != NULL) {
10945 SSL_CTX_free(ocsp_ssl_ctx);
10946 }
10947
10948 OCSP_REQUEST_free(req);
10949 OCSP_BASICRESP_free(basic_resp);
10950 OCSP_RESPONSE_free(resp);
10951 X509_free(issuing_cert);
10952 BIO_free_all(conn);
10953 OPENSSL_free(host);
10954 OPENSSL_free(port);
10955 OPENSSL_free(uri);
10956
10957 return FALSE;
10958 }
10959
10960 tls_log("client cert '%s' has '%s' (%d) status according to OCSP responder "
10961 "at '%s'", subj_name, OCSP_cert_status_str(ocsp_cert_status),
10962 ocsp_cert_status, url);
10963
10964 switch (ocsp_cert_status) {
10965 case V_OCSP_CERTSTATUS_GOOD:
10966 ok = TRUE;
10967 break;
10968
10969 case V_OCSP_CERTSTATUS_REVOKED:
10970 tls_log("client cert '%s' has '%s' status due to: %s", subj_name,
10971 OCSP_cert_status_str(ocsp_status), OCSP_crl_reason_str(ocsp_reason));
10972 ok = FALSE;
10973 break;
10974
10975 case V_OCSP_CERTSTATUS_UNKNOWN:
10976 /* If the client cert points to an OCSP responder which claims not to
10977 * know about the client cert, then we shouldn't trust that client
10978 * cert. Otherwise, a client could present a cert pointing to an
10979 * OCSP responder which they KNOW won't know about the client cert,
10980 * and could then slip through the verification process.
10981 */
10982 ok = FALSE;
10983 break;
10984
10985 default:
10986 ok = FALSE;
10987 }
10988
10989 if (ocsp_ssl_ctx != NULL) {
10990 SSL_CTX_free(ocsp_ssl_ctx);
10991 }
10992
10993 OCSP_REQUEST_free(req);
10994 OCSP_BASICRESP_free(basic_resp);
10995 OCSP_RESPONSE_free(resp);
10996 X509_free(issuing_cert);
10997 BIO_free_all(conn);
10998 OPENSSL_free(host);
10999 OPENSSL_free(port);
11000 OPENSSL_free(uri);
11001
11002 return ok;
11003 }
11004 #endif
11005
11006 static int tls_verify_ocsp(int ok, X509_STORE_CTX *ctx) {
11007 #if OPENSSL_VERSION_NUMBER > 0x000907000L && defined(PR_USE_OPENSSL_OCSP)
11008 register int i;
11009 X509 *cert;
11010 const char *subj;
11011 STACK_OF(ACCESS_DESCRIPTION) *descs;
11012 pool *tmp_pool = NULL;
11013 array_header *ocsp_urls = NULL;
11014
11015 /* Set a default verification error here; it will be superseded as needed
11016 * later during the verification process.
11017 */
11018 X509_STORE_CTX_set_error(ctx, X509_V_ERR_APPLICATION_VERIFICATION);
11019
11020 cert = X509_STORE_CTX_get_current_cert(ctx);
11021 if (cert == NULL) {
11022 return ok;
11023 }
11024
11025 subj = tls_x509_name_oneline(X509_get_subject_name(cert));
11026
11027 descs = X509_get_ext_d2i(cert, NID_info_access, NULL, NULL);
11028 if (descs == NULL) {
11029 tls_log("Client cert '%s' contained no AuthorityInfoAccess attribute, "
11030 "unable to verify via OCSP", subj);
11031 return ok;
11032 }
11033
11034 for (i = 0; i < sk_ACCESS_DESCRIPTION_num(descs); i++) {
11035 ACCESS_DESCRIPTION *desc;
11036
11037 desc = sk_ACCESS_DESCRIPTION_value(descs, i);
11038 if (OBJ_obj2nid(desc->method) == NID_ad_OCSP) {
11039 /* Found an OCSP AuthorityInfoAccess attribute */
11040
11041 if (desc->location->type != GEN_URI) {
11042 /* Not a valid URI, ignore it. */
11043 continue;
11044 }
11045
11046 /* Add this URL to the list of OCSP URLs to check. */
11047 if (ocsp_urls == NULL) {
11048 tmp_pool = make_sub_pool(session.pool);
11049 ocsp_urls = make_array(tmp_pool, 1, sizeof(char *));
11050 }
11051
11052 #if OPENSSL_VERSION_NUMBER >= 0x10100000L && \
11053 !defined(HAVE_LIBRESSL)
11054 *((char **) push_array(ocsp_urls)) = pstrdup(tmp_pool,
11055 (char *) ASN1_STRING_get0_data(desc->location->d.uniformResourceIdentifier));
11056 #else
11057 *((char **) push_array(ocsp_urls)) = pstrdup(tmp_pool,
11058 (char *) ASN1_STRING_data(desc->location->d.uniformResourceIdentifier));
11059 #endif /* OpenSSL 1.1.x and later */
11060 }
11061 }
11062
11063 if (ocsp_urls == NULL) {
11064 tls_log("found no OCSP URLs in AuthorityInfoAccess attribute for client "
11065 "cert '%s', unable to verify via OCSP", subj);
11066 AUTHORITY_INFO_ACCESS_free(descs);
11067 return ok;
11068 }
11069
11070 tls_log("found %u OCSP %s in AuthorityInfoAccess attribute for client cert "
11071 "'%s'", ocsp_urls->nelts, ocsp_urls->nelts != 1 ? "URLs" : "URL", subj);
11072
11073 /* Check each of the URLs. */
11074 for (i = 0; i < (int) ocsp_urls->nelts; i++) {
11075 char *url = ((char **) ocsp_urls->elts)[i];
11076
11077 ok = tls_verify_ocsp_url(ctx, cert, url);
11078 if (ok)
11079 break;
11080 }
11081
11082 destroy_pool(tmp_pool);
11083 AUTHORITY_INFO_ACCESS_free(descs);
11084
11085 return ok;
11086 #else
11087 return ok;
11088 #endif
11089 }
11090
11091 static ssize_t tls_write(SSL *ssl, const void *buf, size_t len) {
11092 ssize_t count;
11093 int lineno, xerrno = 0;
11094
11095 /* Help ensure we have a clean/trustable errno value. */
11096 errno = 0;
11097
11098 lineno = __LINE__ + 1;
11099 count = SSL_write(ssl, buf, len);
11100 xerrno = errno;
11101
11102 if (count < 0) {
11103 long err = SSL_get_error(ssl, count);
11104
11105 /* write(2) returns only the generic error number -1 */
11106 count = -1;
11107
11108 switch (err) {
11109 case SSL_ERROR_WANT_READ:
11110 case SSL_ERROR_WANT_WRITE:
11111 /* Simulate an EINTR in case OpenSSL wants to write more. */
11112 xerrno = EINTR;
11113 break;
11114
11115 case SSL_ERROR_SSL:
11116 case SSL_ERROR_SYSCALL:
11117 default:
11118 tls_fatal_error(err, lineno);
11119 break;
11120 }
11121 }
11122
11123 errno = xerrno;
11124 return count;
11125 }
11126
11127 static char *tls_x509_name_oneline(const X509_NAME *x509_name) {
11128 static char buf[1024] = {'\0'};
11129
11130 /* If we are using OpenSSL 0.9.6 or newer, we want to use
11131 * X509_NAME_print_ex() instead of X509_NAME_oneline().
11132 */
11133
11134 #if OPENSSL_VERSION_NUMBER < 0x000906000L
11135 memset(&buf, '\0', sizeof(buf));
11136 return X509_NAME_oneline(x509_name, buf, sizeof(buf)-1);
11137 #else
11138
11139 /* Sigh...do it the hard way. */
11140 BIO *mem = BIO_new(BIO_s_mem());
11141 char *data = NULL;
11142 long datalen = 0;
11143 int ok;
11144
11145 ok = X509_NAME_print_ex(mem, x509_name, 0, XN_FLAG_ONELINE);
11146 if (ok) {
11147 datalen = BIO_get_mem_data(mem, &data);
11148
11149 if (data) {
11150 memset(&buf, '\0', sizeof(buf));
11151
11152 if ((size_t) datalen >= sizeof(buf)) {
11153 datalen = sizeof(buf)-1;
11154 }
11155
11156 memcpy(buf, data, datalen);
11157
11158 buf[datalen] = '\0';
11159 buf[sizeof(buf)-1] = '\0';
11160
11161 BIO_free(mem);
11162 return buf;
11163 }
11164 }
11165
11166 BIO_free(mem);
11167 return NULL;
11168 #endif /* OPENSSL_VERSION_NUMBER >= 0x000906000 */
11169 }
11170
11171 /* Session cache API */
11172
11173 struct tls_scache {
11174 struct tls_scache *next, *prev;
11175
11176 const char *name;
11177 tls_sess_cache_t *cache;
11178 };
11179
11180 static pool *tls_sess_cache_pool = NULL;
11181 static struct tls_scache *tls_sess_caches = NULL;
11182 static unsigned int tls_sess_ncaches = 0;
11183
11184 int tls_sess_cache_register(const char *name, tls_sess_cache_t *cache) {
11185 struct tls_scache *sc;
11186
11187 if (name == NULL ||
11188 cache == NULL) {
11189 errno = EINVAL;
11190 return -1;
11191 }
11192
11193 if (tls_sess_cache_pool == NULL) {
11194 tls_sess_cache_pool = make_sub_pool(permanent_pool);
11195 pr_pool_tag(tls_sess_cache_pool, "TLS Session Cache API Pool");
11196 }
11197
11198 /* Make sure this cache has not already been registered. */
11199 if (tls_sess_cache_get_cache(name) != NULL) {
11200 errno = EEXIST;
11201 return -1;
11202 }
11203
11204 sc = pcalloc(tls_sess_cache_pool, sizeof(struct tls_scache));
11205
11206 /* XXX Should this name string be dup'd from the tls_sess_cache_pool? */
11207 sc->name = name;
11208 cache->cache_name = pstrdup(tls_sess_cache_pool, name);
11209 sc->cache = cache;
11210
11211 if (tls_sess_caches) {
11212 sc->next = tls_sess_caches;
11213
11214 } else {
11215 sc->next = NULL;
11216 }
11217
11218 tls_sess_caches = sc;
11219 tls_sess_ncaches++;
11220
11221 return 0;
11222 }
11223
11224 int tls_sess_cache_unregister(const char *name) {
11225 struct tls_scache *sc;
11226
11227 if (name == NULL) {
11228 errno = EINVAL;
11229 return -1;
11230 }
11231
11232 for (sc = tls_sess_caches; sc; sc = sc->next) {
11233 if (strcmp(sc->name, name) == 0) {
11234
11235 if (sc->prev) {
11236 sc->prev->next = sc->next;
11237
11238 } else {
11239 /* If prev is NULL, this is the head of the list. */
11240 tls_sess_caches = sc->next;
11241 }
11242
11243 if (sc->next) {
11244 sc->next->prev = sc->prev;
11245 }
11246
11247 sc->next = sc->prev = NULL;
11248 tls_sess_ncaches--;
11249
11250 /* If the session cache being unregistered is in use, update the
11251 * session-cache-in-use pointer.
11252 */
11253 if (sc->cache == tls_sess_cache) {
11254 tls_sess_cache_close();
11255 tls_sess_cache = NULL;
11256 }
11257
11258 /* NOTE: a counter should be kept of the number of unregistrations,
11259 * as the memory for a registration is not freed on unregistration.
11260 */
11261
11262 return 0;
11263 }
11264 }
11265
11266 errno = ENOENT;
11267 return -1;
11268 }
11269
11270 static tls_sess_cache_t *tls_sess_cache_get_cache(const char *name) {
11271 struct tls_scache *sc;
11272
11273 if (name == NULL) {
11274 errno = EINVAL;
11275 return NULL;
11276 }
11277
11278 for (sc = tls_sess_caches; sc; sc = sc->next) {
11279 if (strcmp(sc->name, name) == 0) {
11280 return sc->cache;
11281 }
11282 }
11283
11284 errno = ENOENT;
11285 return NULL;
11286 }
11287
11288 static long tls_sess_cache_get_cache_mode(void) {
11289 if (tls_sess_cache == NULL) {
11290 return 0;
11291 }
11292
11293 return tls_sess_cache->cache_mode;
11294 }
11295
11296 static int tls_sess_cache_open(char *info, long timeout) {
11297 int res;
11298
11299 if (tls_sess_cache == NULL) {
11300 errno = ENOSYS;
11301 return -1;
11302 }
11303
11304 res = (tls_sess_cache->open)(tls_sess_cache, info, timeout);
11305 return res;
11306 }
11307
11308 static int tls_sess_cache_close(void) {
11309 int res;
11310
11311 if (tls_sess_cache == NULL) {
11312 errno = ENOSYS;
11313 return -1;
11314 }
11315
11316 res = (tls_sess_cache->close)(tls_sess_cache);
11317 return res;
11318 }
11319
11320 #ifdef PR_USE_CTRLS
11321 static int tls_sess_cache_clear(void) {
11322 int res;
11323
11324 if (tls_sess_cache == NULL) {
11325 errno = ENOSYS;
11326 return -1;
11327 }
11328
11329 res = (tls_sess_cache->clear)(tls_sess_cache);
11330 return res;
11331 }
11332
11333 static int tls_sess_cache_remove(void) {
11334 int res;
11335
11336 if (tls_sess_cache == NULL) {
11337 errno = ENOSYS;
11338 return -1;
11339 }
11340
11341 res = (tls_sess_cache->remove)(tls_sess_cache);
11342 return res;
11343 }
11344
11345 static void sess_cache_printf(void *ctrl, const char *fmt, ...) {
11346 char buf[PR_TUNABLE_BUFFER_SIZE];
11347 va_list msg;
11348
11349 memset(buf, '\0', sizeof(buf));
11350
11351 va_start(msg, fmt);
11352 pr_vsnprintf(buf, sizeof(buf), fmt, msg);
11353 va_end(msg);
11354
11355 buf[sizeof(buf)-1] = '\0';
11356 pr_ctrls_add_response(ctrl, "%s", buf);
11357 }
11358
11359 static int tls_sess_cache_status(pr_ctrls_t *ctrl, int flags) {
11360 int res = 0;
11361
11362 if (tls_sess_cache != NULL) {
11363 res = (tls_sess_cache->status)(tls_sess_cache, sess_cache_printf, ctrl,
11364 flags);
11365 return res;
11366 }
11367
11368 pr_ctrls_add_response(ctrl, "No TLSSessionCache configured");
11369 return res;
11370 }
11371 #endif /* PR_USE_CTRLS */
11372
11373 /* OCSP response cache API */
11374
11375 struct tls_ocache {
11376 struct tls_ocache *next, *prev;
11377
11378 const char *name;
11379 tls_ocsp_cache_t *cache;
11380 };
11381
11382 #if defined(PR_USE_OPENSSL_OCSP)
11383 static pool *tls_ocsp_cache_pool = NULL;
11384 static struct tls_ocache *tls_ocsp_caches = NULL;
11385 static unsigned int tls_ocsp_ncaches = 0;
11386 #endif /* PR_USE_OPENSSL_OCSP */
11387
11388 int tls_ocsp_cache_register(const char *name, tls_ocsp_cache_t *cache) {
11389 #if defined(PR_USE_OPENSSL_OCSP)
11390 struct tls_ocache *oc;
11391
11392 if (name == NULL ||
11393 cache == NULL) {
11394 errno = EINVAL;
11395 return -1;
11396 }
11397
11398 if (tls_ocsp_cache_pool == NULL) {
11399 tls_ocsp_cache_pool = make_sub_pool(permanent_pool);
11400 pr_pool_tag(tls_ocsp_cache_pool, "TLS OCSP Response Cache API Pool");
11401 }
11402
11403 /* Make sure this cache has not already been registered. */
11404 if (tls_ocsp_cache_get_cache(name) != NULL) {
11405 errno = EEXIST;
11406 return -1;
11407 }
11408
11409 oc = pcalloc(tls_ocsp_cache_pool, sizeof(struct tls_ocache));
11410
11411 /* XXX Should this name string be dup'd from the tls_ocsp_cache_pool? */
11412 oc->name = name;
11413 cache->cache_name = pstrdup(tls_ocsp_cache_pool, name);
11414 oc->cache = cache;
11415
11416 if (tls_ocsp_caches != NULL) {
11417 oc->next = tls_ocsp_caches;
11418
11419 } else {
11420 oc->next = NULL;
11421 }
11422
11423 tls_ocsp_caches = oc;
11424 tls_ocsp_ncaches++;
11425
11426 return 0;
11427 #else
11428 errno = ENOSYS;
11429 return -1;
11430 #endif /* PR_USE_OPENSSL_OCSP */
11431 }
11432
11433 int tls_ocsp_cache_unregister(const char *name) {
11434 #if defined(PR_USE_OPENSSL_OCSP)
11435 struct tls_ocache *oc;
11436
11437 if (name == NULL) {
11438 errno = EINVAL;
11439 return -1;
11440 }
11441
11442 for (oc = tls_ocsp_caches; oc; oc = oc->next) {
11443 if (strcmp(oc->name, name) == 0) {
11444
11445 if (oc->prev) {
11446 oc->prev->next = oc->next;
11447
11448 } else {
11449 /* If prev is NULL, this is the head of the list. */
11450 tls_ocsp_caches = oc->next;
11451 }
11452
11453 if (oc->next) {
11454 oc->next->prev = oc->prev;
11455 }
11456
11457 oc->next = oc->prev = NULL;
11458 tls_ocsp_ncaches--;
11459
11460 /* If the OCSP response cache being unregistered is in use, update the
11461 * ocsp-cache-in-use pointer.
11462 */
11463 if (oc->cache == tls_ocsp_cache) {
11464 tls_ocsp_cache_close();
11465 tls_ocsp_cache = NULL;
11466 }
11467
11468 /* NOTE: a counter should be kept of the number of unregistrations,
11469 * as the memory for a registration is not freed on unregistration.
11470 */
11471
11472 return 0;
11473 }
11474 }
11475
11476 errno = ENOENT;
11477 return -1;
11478 #else
11479 errno = ENOSYS;
11480 return -1;
11481 #endif /* PR_USE_OPENSSL_OCSP */
11482 }
11483
11484 static tls_ocsp_cache_t *tls_ocsp_cache_get_cache(const char *name) {
11485 #if defined(PR_USE_OPENSSL_OCSP)
11486 struct tls_ocache *oc;
11487
11488 if (name == NULL) {
11489 errno = EINVAL;
11490 return NULL;
11491 }
11492
11493 for (oc = tls_ocsp_caches; oc; oc = oc->next) {
11494 if (strcmp(oc->name, name) == 0) {
11495 return oc->cache;
11496 }
11497 }
11498
11499 errno = ENOENT;
11500 return NULL;
11501 #else
11502 errno = ENOSYS;
11503 return NULL;
11504 #endif /* PR_USE_OPENSSL_OCSP */
11505 }
11506
11507 static int tls_ocsp_cache_open(char *info) {
11508 #if defined(PR_USE_OPENSSL_OCSP)
11509 int res;
11510
11511 if (tls_ocsp_cache == NULL) {
11512 errno = ENOSYS;
11513 return -1;
11514 }
11515
11516 res = (tls_ocsp_cache->open)(tls_ocsp_cache, info);
11517 return res;
11518 #else
11519 errno = ENOSYS;
11520 return -1;
11521 #endif /* PR_USE_OPENSSL_OCSP */
11522 }
11523
11524 static int tls_ocsp_cache_close(void) {
11525 #if defined(PR_USE_OPENSSL_OCSP)
11526 int res;
11527
11528 if (tls_ocsp_cache == NULL) {
11529 errno = ENOSYS;
11530 return -1;
11531 }
11532
11533 res = (tls_ocsp_cache->close)(tls_ocsp_cache);
11534 return res;
11535 #else
11536 errno = ENOSYS;
11537 return -1;
11538 #endif /* PR_USE_OPENSSL_OCSP */
11539 }
11540
11541 #ifdef PR_USE_CTRLS
11542 static int tls_ocsp_cache_clear(void) {
11543 # if defined(PR_USE_OPENSSL_OCSP)
11544 int res;
11545
11546 if (tls_ocsp_cache == NULL) {
11547 errno = ENOSYS;
11548 return -1;
11549 }
11550
11551 res = (tls_ocsp_cache->clear)(tls_ocsp_cache);
11552 return res;
11553 # else
11554 errno = ENOSYS;
11555 return -1;
11556 # endif /* PR_USE_OPENSSL_OCSP */
11557 }
11558
11559 static int tls_ocsp_cache_remove(void) {
11560 # if defined(PR_USE_OPENSSL_OCSP)
11561 int res;
11562
11563 if (tls_ocsp_cache == NULL) {
11564 errno = ENOSYS;
11565 return -1;
11566 }
11567
11568 res = (tls_ocsp_cache->remove)(tls_ocsp_cache);
11569 return res;
11570 # else
11571 errno = ENOSYS;
11572 return -1;
11573 # endif /* PR_USE_OPENSSL_OCSP */
11574 }
11575
11576 # if defined(PR_USE_OPENSSL_OCSP)
11577 static void ocsp_cache_printf(void *ctrl, const char *fmt, ...) {
11578 char buf[PR_TUNABLE_BUFFER_SIZE];
11579 va_list msg;
11580
11581 memset(buf, '\0', sizeof(buf));
11582
11583 va_start(msg, fmt);
11584 pr_vsnprintf(buf, sizeof(buf), fmt, msg);
11585 va_end(msg);
11586
11587 buf[sizeof(buf)-1] = '\0';
11588 pr_ctrls_add_response(ctrl, "%s", buf);
11589 }
11590 # endif /* PR_USE_OPENSSL_OCSP */
11591
11592 static int tls_ocsp_cache_status(pr_ctrls_t *ctrl, int flags) {
11593 # if defined(PR_USE_OPENSSL_OCSP)
11594 int res = 0;
11595
11596 if (tls_ocsp_cache != NULL) {
11597 res = (tls_ocsp_cache->status)(tls_ocsp_cache, ocsp_cache_printf, ctrl,
11598 flags);
11599 return res;
11600 }
11601
11602 pr_ctrls_add_response(ctrl, "No TLSStaplingCache configured");
11603 return res;
11604 # else
11605 errno = ENOSYS;
11606 return -1;
11607 # endif /* PR_USE_OPENSSL_OCSP */
11608 }
11609 #endif /* PR_USE_CTRLS */
11610
11611 /* Controls
11612 */
11613
11614 #if defined(PR_USE_CTRLS)
11615 static int tls_handle_sesscache_clear(pr_ctrls_t *ctrl, int reqargc,
11616 char **reqargv) {
11617 int res;
11618
11619 res = tls_sess_cache_clear();
11620 if (res < 0) {
11621 pr_ctrls_add_response(ctrl,
11622 "tls sesscache: error clearing session cache: %s", strerror(errno));
11623 return PR_CTRLS_STATUS_INTERNAL_ERROR;
11624 }
11625
11626 pr_ctrls_add_response(ctrl, "tls sesscache: cleared %d %s from '%s' "
11627 "session cache", res, res != 1 ? "sessions" : "session",
11628 tls_sess_cache->cache_name);
11629 return PR_CTRLS_STATUS_OK;
11630 }
11631
11632 static int tls_handle_sesscache_info(pr_ctrls_t *ctrl, int reqargc,
11633 char **reqargv) {
11634 int flags = 0, optc, res;
11635 const char *opts = "v";
11636
11637 pr_getopt_reset();
11638
11639 while ((optc = getopt(reqargc, reqargv, opts)) != -1) {
11640 switch (optc) {
11641 case 'v':
11642 flags = TLS_SESS_CACHE_STATUS_FL_SHOW_SESSIONS;
11643 break;
11644
11645 case '?':
11646 pr_ctrls_add_response(ctrl,
11647 "tls sesscache: unsupported parameter: '%s'", reqargv[1]);
11648 return PR_CTRLS_STATUS_WRONG_PARAMETERS;
11649 }
11650 }
11651
11652 res = tls_sess_cache_status(ctrl, flags);
11653 if (res < 0) {
11654 pr_ctrls_add_response(ctrl,
11655 "tls sesscache: error obtaining session cache status: %s",
11656 strerror(errno));
11657 return PR_CTRLS_STATUS_INTERNAL_ERROR;
11658 }
11659
11660 return PR_CTRLS_STATUS_OK;
11661 }
11662
11663 static int tls_handle_sesscache_remove(pr_ctrls_t *ctrl, int reqargc,
11664 char **reqargv) {
11665 int res;
11666
11667 res = tls_sess_cache_remove();
11668 if (res < 0) {
11669 pr_ctrls_add_response(ctrl,
11670 "tls sesscache: error removing session cache: %s", strerror(errno));
11671 return PR_CTRLS_STATUS_INTERNAL_ERROR;
11672 }
11673
11674 pr_ctrls_add_response(ctrl, "tls sesscache: removed '%s' session cache",
11675 tls_sess_cache->cache_name);
11676 return PR_CTRLS_STATUS_OK;
11677 }
11678
11679 static int tls_handle_sesscache(pr_ctrls_t *ctrl, int reqargc, char **reqargv) {
11680
11681 /* Sanity check */
11682 if (reqargc == 0 ||
11683 reqargv == NULL) {
11684 pr_ctrls_add_response(ctrl, "tls sesscache: missing required parameters");
11685 return PR_CTRLS_STATUS_WRONG_PARAMETERS;
11686 }
11687
11688 if (strcmp(reqargv[0], "info") == 0) {
11689 /* Check the ACLs. */
11690 if (pr_ctrls_check_acl(ctrl, tls_acttab, "info") != TRUE) {
11691 pr_ctrls_add_response(ctrl, "access denied");
11692 return PR_CTRLS_STATUS_ACCESS_DENIED;
11693 }
11694
11695 return tls_handle_sesscache_info(ctrl, reqargc, reqargv);
11696
11697 } else if (strcmp(reqargv[0], "clear") == 0) {
11698 /* Check the ACLs. */
11699 if (pr_ctrls_check_acl(ctrl, tls_acttab, "clear") != TRUE) {
11700 pr_ctrls_add_response(ctrl, "access denied");
11701 return PR_CTRLS_STATUS_ACCESS_DENIED;
11702 }
11703
11704 return tls_handle_sesscache_clear(ctrl, reqargc, reqargv);
11705
11706 } else if (strcmp(reqargv[0], "remove") == 0) {
11707 /* Check the ACLs. */
11708 if (pr_ctrls_check_acl(ctrl, tls_acttab, "remove") != TRUE) {
11709 pr_ctrls_add_response(ctrl, "access denied");
11710 return PR_CTRLS_STATUS_ACCESS_DENIED;
11711 }
11712
11713 return tls_handle_sesscache_remove(ctrl, reqargc, reqargv);
11714 }
11715
11716 pr_ctrls_add_response(ctrl, "tls sesscache: unknown sesscache action: '%s'",
11717 reqargv[0]);
11718 return PR_CTRLS_STATUS_UNSUPPORTED_OPERATION;
11719 }
11720
11721 static int tls_handle_ocspcache_info(pr_ctrls_t *ctrl, int reqargc,
11722 char **reqargv) {
11723 int flags = 0, optc, res;
11724 const char *opts = "v";
11725
11726 pr_getopt_reset();
11727
11728 while ((optc = getopt(reqargc, reqargv, opts)) != -1) {
11729 switch (optc) {
11730 case '?':
11731 pr_ctrls_add_response(ctrl,
11732 "tls ocspcache: unsupported parameter: '%s'", reqargv[1]);
11733 return PR_CTRLS_STATUS_WRONG_PARAMETERS;
11734 }
11735 }
11736
11737 res = tls_ocsp_cache_status(ctrl, flags);
11738 if (res < 0) {
11739 pr_ctrls_add_response(ctrl,
11740 "tls ocspcache: error obtaining OCSP cache status: %s",
11741 strerror(errno));
11742 return PR_CTRLS_STATUS_INTERNAL_ERROR;
11743 }
11744
11745 return PR_CTRLS_STATUS_OK;
11746 }
11747
11748 static int tls_handle_ocspcache_clear(pr_ctrls_t *ctrl, int reqargc,
11749 char **reqargv) {
11750 int res;
11751
11752 res = tls_ocsp_cache_clear();
11753 if (res < 0) {
11754 pr_ctrls_add_response(ctrl,
11755 "tls ocspcache: error clearing OCSP cache: %s", strerror(errno));
11756 return PR_CTRLS_STATUS_INTERNAL_ERROR;
11757 }
11758
11759 pr_ctrls_add_response(ctrl, "tls ocspcache: cleared %d %s from '%s' "
11760 "OCSP cache", res, res != 1 ? "responses" : "response",
11761 tls_ocsp_cache->cache_name);
11762 return PR_CTRLS_STATUS_OK;
11763 }
11764
11765 static int tls_handle_ocspcache_remove(pr_ctrls_t *ctrl, int reqargc,
11766 char **reqargv) {
11767 int res;
11768
11769 res = tls_ocsp_cache_remove();
11770 if (res < 0) {
11771 pr_ctrls_add_response(ctrl,
11772 "tls ocspcache: error removing OCSP cache: %s", strerror(errno));
11773 return PR_CTRLS_STATUS_INTERNAL_ERROR;
11774 }
11775
11776 pr_ctrls_add_response(ctrl, "tls sesscache: removed '%s' OCSP cache",
11777 tls_ocsp_cache->cache_name);
11778 return PR_CTRLS_STATUS_OK;
11779 }
11780
11781 static int tls_handle_ocspcache(pr_ctrls_t *ctrl, int reqargc, char **reqargv) {
11782 /* Sanity check */
11783 if (reqargc == 0 ||
11784 reqargv == NULL) {
11785 pr_ctrls_add_response(ctrl, "tls ocspcache: missing required parameters");
11786 return PR_CTRLS_STATUS_WRONG_PARAMETERS;
11787 }
11788
11789 if (strcmp(reqargv[0], "info") == 0) {
11790 /* Check the ACLs. */
11791 if (pr_ctrls_check_acl(ctrl, tls_acttab, "info") != TRUE) {
11792 pr_ctrls_add_response(ctrl, "access denied");
11793 return PR_CTRLS_STATUS_ACCESS_DENIED;
11794 }
11795
11796 return tls_handle_ocspcache_info(ctrl, reqargc, reqargv);
11797
11798 } else if (strcmp(reqargv[0], "clear") == 0) {
11799 /* Check the ACLs. */
11800 if (pr_ctrls_check_acl(ctrl, tls_acttab, "clear") != TRUE) {
11801 pr_ctrls_add_response(ctrl, "access denied");
11802 return PR_CTRLS_STATUS_ACCESS_DENIED;
11803 }
11804
11805 return tls_handle_ocspcache_clear(ctrl, reqargc, reqargv);
11806
11807 } else if (strcmp(reqargv[0], "remove") == 0) {
11808 /* Check the ACLs. */
11809 if (pr_ctrls_check_acl(ctrl, tls_acttab, "remove") != TRUE) {
11810 pr_ctrls_add_response(ctrl, "access denied");
11811 return PR_CTRLS_STATUS_ACCESS_DENIED;
11812 }
11813
11814 return tls_handle_ocspcache_remove(ctrl, reqargc, reqargv);
11815 }
11816
11817 pr_ctrls_add_response(ctrl, "tls ocspcache: unknown ocspcache action: '%s'",
11818 reqargv[0]);
11819 return PR_CTRLS_STATUS_UNSUPPORTED_OPERATION;
11820 }
11821
11822 /* Our main ftpdctl action handler */
11823 static int tls_handle_tls(pr_ctrls_t *ctrl, int reqargc, char **reqargv) {
11824
11825 /* Sanity check */
11826 if (reqargc == 0 ||
11827 reqargv == NULL) {
11828 pr_ctrls_add_response(ctrl, "missing required parameters");
11829 return PR_CTRLS_STATUS_WRONG_PARAMETERS;
11830 }
11831
11832 if (strcmp(reqargv[0], "sesscache") == 0) {
11833 /* Check the ACLs. */
11834 if (pr_ctrls_check_acl(ctrl, tls_acttab, "sesscache") != TRUE) {
11835 pr_ctrls_add_response(ctrl, "access denied");
11836 return PR_CTRLS_STATUS_ACCESS_DENIED;
11837 }
11838
11839 return tls_handle_sesscache(ctrl, --reqargc, ++reqargv);
11840 }
11841
11842 if (strcmp(reqargv[0], "ocspcache") == 0) {
11843 /* Check the ACLs. */
11844 if (pr_ctrls_check_acl(ctrl, tls_acttab, "ocspcache") != TRUE) {
11845 pr_ctrls_add_response(ctrl, "access denied");
11846 return PR_CTRLS_STATUS_ACCESS_DENIED;
11847 }
11848
11849 return tls_handle_ocspcache(ctrl, --reqargc, ++reqargv);
11850 }
11851
11852 pr_ctrls_add_response(ctrl, "unknown tls action: '%s'", reqargv[0]);
11853 return PR_CTRLS_STATUS_UNSUPPORTED_OPERATION;
11854 }
11855 #endif /* PR_USE_CTRLS */
11856
11857 /* TLSSessionCache callbacks
11858 */
11859
11860 static int tls_sess_cache_add_sess_cb(SSL *ssl, SSL_SESSION *sess) {
11861 unsigned char *sess_id;
11862 unsigned int sess_id_len;
11863 int res;
11864 long expires;
11865
11866 if (tls_sess_cache == NULL) {
11867 tls_log("unable to add session to session cache: %s", strerror(ENOSYS));
11868
11869 SSL_SESSION_free(sess);
11870 return 1;
11871 }
11872
11873 pr_trace_msg(trace_channel, 9, "adding new SSL session to '%s' cache",
11874 tls_sess_cache->cache_name);
11875
11876 SSL_set_timeout(sess, tls_sess_cache->cache_timeout);
11877
11878 #if OPENSSL_VERSION_NUMBER > 0x000908000L
11879 sess_id = (unsigned char *) SSL_SESSION_get_id(sess, &sess_id_len);
11880 #else
11881 /* XXX Directly accessing these fields cannot be a Good Thing. */
11882 sess_id = sess->session_id;
11883 sess_id_len = sess->session_id_length;
11884 #endif
11885
11886 /* The expiration timestamp stored in the session cache is the
11887 * Unix epoch time, not an interval.
11888 */
11889 expires = SSL_SESSION_get_time(sess) + tls_sess_cache->cache_timeout;
11890
11891 res = (tls_sess_cache->add)(tls_sess_cache, sess_id, sess_id_len, expires,
11892 sess);
11893 if (res < 0) {
11894 long cache_mode;
11895
11896 tls_log("error adding session to '%s' cache: %s",
11897 tls_sess_cache->cache_name, strerror(errno));
11898
11899 cache_mode = tls_sess_cache_get_cache_mode();
11900 #ifdef SSL_SESS_CACHE_NO_INTERNAL
11901 if (cache_mode & SSL_SESS_CACHE_NO_INTERNAL) {
11902 /* Call SSL_SESSION_free() here, and return 1. We told OpenSSL that we
11903 * are the only cache, so failing to call SSL_SESSION_free() could
11904 * result in a memory leak.
11905 */
11906 SSL_SESSION_free(sess);
11907 return 1;
11908 }
11909 #endif /* !SSL_SESS_CACHE_NO_INTERNAL */
11910 }
11911
11912 /* Return zero to indicate to OpenSSL that we have not called
11913 * SSL_SESSION_free().
11914 */
11915 return 0;
11916 }
11917
11918 static SSL_SESSION *tls_sess_cache_get_sess_cb(SSL *ssl,
11919 const unsigned char *id, int sess_id_len, int *do_copy) {
11920 SSL_SESSION *sess;
11921 const unsigned char *sess_id;
11922
11923 pr_trace_msg(trace_channel, 9, "getting SSL session from '%s' cache",
11924 tls_sess_cache->cache_name);
11925
11926 sess_id = id;
11927
11928 /* Indicate to OpenSSL that the ref count should not be incremented
11929 * by setting the do_copy pointer to zero.
11930 */
11931 *do_copy = 0;
11932
11933 /* The actual session_id_length field in the OpenSSL SSL_SESSION struct
11934 * is unsigned, not signed. But for some reason, the expected callback
11935 * signature uses 'int', not 'unsigned int'. Hopefully the implicit
11936 * cast below (our callback uses 'unsigned int') won't cause problems.
11937 * Just to be sure, check if OpenSSL is giving us a negative ID length.
11938 */
11939 if (sess_id_len <= 0) {
11940 tls_log("OpenSSL invoked TLS session cache 'get' callback with session "
11941 "ID length %d, returning null", sess_id_len);
11942 return NULL;
11943 }
11944
11945 if (tls_sess_cache == NULL) {
11946 tls_log("unable to get session from session cache: %s", strerror(ENOSYS));
11947 return NULL;
11948 }
11949
11950 sess = (tls_sess_cache->get)(tls_sess_cache, sess_id, sess_id_len);
11951 if (sess == NULL) {
11952 int xerrno = errno;
11953
11954 pr_trace_msg(trace_channel, 5,
11955 "error retrieving session from '%s' cache: %s",
11956 tls_sess_cache->cache_name, strerror(xerrno));
11957 if (xerrno != ENOENT) {
11958 tls_log("error retrieving session from '%s' cache: %s",
11959 tls_sess_cache->cache_name, strerror(xerrno));
11960 }
11961 }
11962
11963 return sess;
11964 }
11965
11966 static void tls_sess_cache_delete_sess_cb(SSL_CTX *ctx, SSL_SESSION *sess) {
11967 unsigned char *sess_id;
11968 unsigned int sess_id_len;
11969 int res;
11970
11971 if (tls_sess_cache == NULL) {
11972 tls_log("unable to remove session from session cache: %s",
11973 strerror(ENOSYS));
11974 return;
11975 }
11976
11977 pr_trace_msg(trace_channel, 9, "removing SSL session from '%s' cache",
11978 tls_sess_cache->cache_name);
11979
11980 #if OPENSSL_VERSION_NUMBER > 0x000908000L
11981 sess_id = (unsigned char *) SSL_SESSION_get_id(sess, &sess_id_len);
11982 #else
11983 /* XXX Directly accessing these fields cannot be a Good Thing. */
11984 sess_id = sess->session_id;
11985 sess_id_len = sess->session_id_length;
11986 #endif
11987
11988 res = (tls_sess_cache->delete)(tls_sess_cache, sess_id, sess_id_len);
11989 if (res < 0) {
11990 tls_log("error removing session from '%s' cache: %s",
11991 tls_sess_cache->cache_name, strerror(errno));
11992 }
11993
11994 return;
11995 }
11996
11997 /* Ideally we would use the OPENSSL_NO_PSK macro. However, to use this, we
11998 * would need to say "if !defined(OPENSSL_NO_PSK)". And that does not work
11999 * as well for older OpenSSL installations, where that macro would not be
12000 * defined anyway. So instead, we use the presence of another PSK-related
12001 * macro as a more reliable sentinel.
12002 */
12003
12004 #if defined(PSK_MAX_PSK_LEN)
12005 /* PSK callbacks */
12006
12007 static int set_random_bn(unsigned char *psk, unsigned int max_psklen) {
12008 BIGNUM *bn = NULL;
12009 int res = 0;
12010
12011 bn = BN_new();
12012 if (BN_pseudo_rand(bn, max_psklen, 0, 0) != 1) {
12013 tls_log("error generating pseudo-random number: %s",
12014 ERR_error_string(ERR_get_error(), NULL));
12015 }
12016
12017 res = BN_bn2bin(bn, psk);
12018 BN_free(bn);
12019
12020 return res;
12021 }
12022
12023 static unsigned int tls_lookup_psk(SSL *ssl, const char *identity,
12024 unsigned char *psk, unsigned int max_psklen) {
12025 const void *v = NULL;
12026 BIGNUM *bn = NULL;
12027 int bn_len = -1, res;
12028
12029 if (identity == NULL) {
12030 tls_log("%s", "error: client did not provide PSK identity name, providing "
12031 "random fake PSK");
12032
12033 res = set_random_bn(psk, max_psklen);
12034 return res;
12035 }
12036
12037 pr_trace_msg(trace_channel, 5,
12038 "PSK lookup: identity '%s' requested", identity);
12039
12040 if (tls_psks == NULL) {
12041 tls_log("warning: no pre-shared keys configured, providing random fake "
12042 "PSK for identity '%s'", identity);
12043
12044 res = set_random_bn(psk, max_psklen);
12045 return res;
12046 }
12047
12048 v = pr_table_get(tls_psks, identity, NULL);
12049 if (v == NULL) {
12050 tls_log("warning: requested PSK identity '%s' not configured, providing "
12051 "random fake PSK", identity);
12052
12053 res = set_random_bn(psk, max_psklen);
12054 return res;
12055 }
12056
12057 bn = (BIGNUM *) v;
12058 bn_len = BN_num_bytes(bn);
12059
12060 if (bn_len > (int) max_psklen) {
12061 tls_log("warning: unable to use '%s' PSK: max buffer size (%u bytes) "
12062 "too small for key (%d bytes), providing random fake PSK", identity,
12063 max_psklen, bn_len);
12064
12065 res = set_random_bn(psk, max_psklen);
12066 return res;
12067 }
12068
12069 res = BN_bn2bin(bn, psk);
12070 if (res == 0) {
12071 tls_log("error converting PSK for identity '%s' to binary: %s",
12072 identity, tls_get_errors());
12073 return 0;
12074 }
12075
12076 pr_trace_msg(trace_channel, 5,
12077 "found PSK (%d bytes) for identity '%s'", res, identity);
12078 return res;
12079 }
12080
12081 #endif /* PSK_MAX_PSK_LEN */
12082
12083 /* NetIO callbacks
12084 */
12085
12086 static void tls_netio_abort_cb(pr_netio_stream_t *nstrm) {
12087 nstrm->strm_flags |= PR_NETIO_SESS_ABORT;
12088 }
12089
12090 static int tls_netio_close_cb(pr_netio_stream_t *nstrm) {
12091 int res = 0;
12092 SSL *ssl = NULL;
12093
12094 ssl = (SSL *) pr_table_get(nstrm->notes, TLS_NETIO_NOTE, NULL);
12095 if (ssl != NULL) {
12096 if (nstrm->strm_type == PR_NETIO_STRM_CTRL) {
12097 if (nstrm->strm_mode == PR_NETIO_IO_RD) {
12098 tls_ctrl_rd_nstrm = NULL;
12099
12100 } else if (nstrm->strm_mode == PR_NETIO_IO_WR) {
12101 tls_ctrl_wr_nstrm = NULL;
12102
12103 tls_end_sess(ssl, session.c, 0);
12104 tls_ctrl_netio = NULL;
12105 tls_flags &= ~TLS_SESS_ON_CTRL;
12106 }
12107 }
12108
12109 if (nstrm->strm_type == PR_NETIO_STRM_DATA) {
12110 if (nstrm->strm_mode == PR_NETIO_IO_RD) {
12111 tls_data_rd_nstrm = NULL;
12112
12113 } else if (nstrm->strm_mode == PR_NETIO_IO_WR) {
12114 tls_data_wr_nstrm = NULL;
12115
12116 tls_end_sess(ssl, session.d, 0);
12117 tls_data_netio = NULL;
12118 tls_flags &= ~TLS_SESS_ON_DATA;
12119 tls_data_renegotiate_current = 0;
12120 }
12121 }
12122 }
12123
12124 res = close(nstrm->strm_fd);
12125 nstrm->strm_fd = -1;
12126
12127 return res;
12128 }
12129
12130 static pr_netio_stream_t *tls_netio_open_cb(pr_netio_stream_t *nstrm, int fd,
12131 int mode) {
12132 nstrm->strm_fd = fd;
12133 nstrm->strm_mode = mode;
12134
12135 /* Cache a pointer to this stream. */
12136 if (nstrm->strm_type == PR_NETIO_STRM_CTRL) {
12137 /* Note: We need to make this more generalized, so that mod_tls can be
12138 * used to open multiple different read/write control streams. To do
12139 * so, we need a small (e.g. 4) array of pr_netio_stream_t pointers
12140 * for both read and write streams, and to iterate through them. Need
12141 * iterate through and set strm_data appropriately in tls_accept(), too.
12142 *
12143 * This will needed to support FTPS connections to backend servers from
12144 * mod_proxy, for example.
12145 */
12146 if (nstrm->strm_mode == PR_NETIO_IO_RD) {
12147 if (tls_ctrl_rd_nstrm == NULL) {
12148 tls_ctrl_rd_nstrm = nstrm;
12149 }
12150 }
12151
12152 if (nstrm->strm_mode == PR_NETIO_IO_WR) {
12153 if (tls_ctrl_wr_nstrm == NULL) {
12154 tls_ctrl_wr_nstrm = nstrm;
12155 }
12156 }
12157
12158 } else if (nstrm->strm_type == PR_NETIO_STRM_DATA) {
12159 tls_data_renegotiate_current = 0;
12160
12161 if (nstrm->strm_mode == PR_NETIO_IO_RD) {
12162 tls_data_rd_nstrm = nstrm;
12163 }
12164
12165 if (nstrm->strm_mode == PR_NETIO_IO_WR) {
12166 tls_data_wr_nstrm = nstrm;
12167 }
12168
12169 /* Note: from the FTP-TLS Draft 9.2:
12170 *
12171 * It is quite reasonable for the server to insist that the data
12172 * connection uses a TLS cached session. This might be a cache of a
12173 * previous data connection or of the control connection. If this is
12174 * the reason for the refusal to allow the data transfer then the
12175 * '522' reply should indicate this.
12176 *
12177 * and, from 10.4:
12178 *
12179 * If a server needs to have the connection protected then it will
12180 * reply to the STOR/RETR/NLST/... command with a '522' indicating
12181 * that the current state of the data connection protection level is
12182 * not sufficient for that data transfer at that time.
12183 *
12184 * This points out the need for a module to be able to influence
12185 * command response codes in a more flexible manner...
12186 */
12187 }
12188
12189 return nstrm;
12190 }
12191
12192 static int tls_netio_poll_cb(pr_netio_stream_t *nstrm) {
12193 fd_set rfds, wfds;
12194 struct timeval tval;
12195
12196 FD_ZERO(&rfds);
12197 FD_ZERO(&wfds);
12198
12199 if (nstrm->strm_mode == PR_NETIO_IO_RD) {
12200 FD_SET(nstrm->strm_fd, &rfds);
12201
12202 } else {
12203 FD_SET(nstrm->strm_fd, &wfds);
12204 }
12205
12206 tval.tv_sec = (nstrm->strm_flags & PR_NETIO_SESS_INTR) ?
12207 nstrm->strm_interval : 10;
12208 tval.tv_usec = 0;
12209
12210 return select(nstrm->strm_fd + 1, &rfds, &wfds, NULL, &tval);
12211 }
12212
12213 static int tls_netio_postopen_cb(pr_netio_stream_t *nstrm) {
12214
12215 /* If this is a data stream, and it's for writing, and TLS is required,
12216 * then do a TLS handshake.
12217 */
12218
12219 if (nstrm->strm_type == PR_NETIO_STRM_DATA &&
12220 nstrm->strm_mode == PR_NETIO_IO_WR) {
12221
12222 /* Enforce the "data" part of TLSRequired, if configured. */
12223 if (tls_required_on_data == 1 ||
12224 (tls_flags & TLS_SESS_NEED_DATA_PROT)) {
12225 SSL *ssl = NULL;
12226
12227 /* XXX How to force 421 response code for failed secure FXP/SSCN? */
12228
12229 /* Directory listings (LIST, MLSD, NLST) are ALWAYS handled in server
12230 * mode, regardless of SSCN mode.
12231 */
12232 if (session.curr_cmd_id == PR_CMD_LIST_ID ||
12233 session.curr_cmd_id == PR_CMD_MLSD_ID ||
12234 session.curr_cmd_id == PR_CMD_NLST_ID ||
12235 tls_sscn_mode == TLS_SSCN_MODE_SERVER) {
12236 X509 *ctrl_cert = NULL, *data_cert = NULL;
12237 uint64_t start_ms = 0;
12238
12239 pr_gettimeofday_millis(&start_ms);
12240
12241 tls_data_need_init_handshake = TRUE;
12242 if (tls_accept(session.d, TRUE) < 0) {
12243 tls_log("%s",
12244 "unable to open data connection: TLS negotiation failed");
12245 session.d->xerrno = errno = EPERM;
12246 return -1;
12247 }
12248
12249 if (pr_trace_get_level(timing_channel) >= 4) {
12250 unsigned long elapsed_ms;
12251 uint64_t finish_ms;
12252
12253 pr_gettimeofday_millis(&finish_ms);
12254 elapsed_ms = (unsigned long) (finish_ms - start_ms);
12255
12256 pr_trace_msg(timing_channel, 4,
12257 "TLS data handshake duration: %lu ms", elapsed_ms);
12258 }
12259
12260 ssl = (SSL *) pr_table_get(nstrm->notes, TLS_NETIO_NOTE, NULL);
12261
12262 /* Make sure that the certificate used, if any, for this data channel
12263 * handshake is the same as that used for the control channel handshake.
12264 * This may be too strict of a requirement, though.
12265 */
12266 ctrl_cert = SSL_get_peer_certificate(ctrl_ssl);
12267 data_cert = SSL_get_peer_certificate(ssl);
12268
12269 if (ctrl_cert != NULL &&
12270 data_cert != NULL) {
12271 if (X509_cmp(ctrl_cert, data_cert)) {
12272 X509_free(ctrl_cert);
12273 X509_free(data_cert);
12274
12275 /* Properly shutdown the TLS session. */
12276 tls_end_sess(ssl, session.d, 0);
12277 pr_table_remove(tls_data_rd_nstrm->notes, TLS_NETIO_NOTE, NULL);
12278 pr_table_remove(tls_data_wr_nstrm->notes, TLS_NETIO_NOTE, NULL);
12279
12280 tls_log("%s", "unable to open data connection: control/data "
12281 "certificate mismatch");
12282
12283 session.d->xerrno = errno = EPERM;
12284 return -1;
12285 }
12286
12287 if (ctrl_cert) {
12288 X509_free(ctrl_cert);
12289 }
12290
12291 if (data_cert) {
12292 X509_free(data_cert);
12293 }
12294 }
12295
12296 } else if (tls_sscn_mode == TLS_SSCN_MODE_CLIENT) {
12297 tls_log("%s", "making TLS connection for data connection");
12298 if (tls_connect(session.d) < 0) {
12299 tls_log("%s",
12300 "unable to open data connection: TLS connection failed");
12301 session.d->xerrno = errno = EPERM;
12302 return -1;
12303 }
12304 }
12305
12306 #if OPENSSL_VERSION_NUMBER < 0x0090702fL
12307 /* Make sure blinding is turned on. (For some reason, this only seems
12308 * to be allowed on SSL objects, not on SSL_CTX objects. Bummer).
12309 */
12310 tls_blinding_on(ssl);
12311 #endif
12312
12313 tls_flags |= TLS_SESS_ON_DATA;
12314 }
12315 }
12316
12317 return 0;
12318 }
12319
12320 static void tls_data_renegotiate(SSL *ssl) {
12321 if (tls_flags & TLS_SESS_DATA_RENEGOTIATING) {
12322 return;
12323 }
12324
12325 tls_data_renegotiate_current = session.xfer.total_bytes;
12326
12327 if (tls_data_renegotiate_limit > 0 &&
12328 tls_data_renegotiate_current >= tls_data_renegotiate_limit) {
12329
12330 switch (SSL_version(ssl)) {
12331 # if defined(TLS1_3_VERSION) && !defined(HAVE_LIBRESSL)
12332 /* If we're a TLSv1.3 session, use SSL_key_update() to request new
12333 * session keys; TLSv1.3 does not support renegotiations.
12334 */
12335 case TLS1_3_VERSION: {
12336 if (SSL_get_key_update_type(ctrl_ssl) == SSL_KEY_UPDATE_NONE) {
12337 tls_flags |= TLS_SESS_DATA_RENEGOTIATING;
12338
12339 tls_log("requesting TLS key updates on data channel "
12340 "(%" PR_LU " KB data limit)",
12341 (pr_off_t) (tls_data_renegotiate_limit / 1024));
12342
12343 if (SSL_key_update(ssl, SSL_KEY_UPDATE_REQUESTED) != 1) {
12344 tls_log("error requesting TLS key update on data channel: %s",
12345 tls_get_errors());
12346 }
12347
12348 } else {
12349 pr_trace_msg(trace_channel, 7,
12350 "TLS key update on data channel already in progress");
12351 }
12352 }
12353 break;
12354 # endif /* TLS1_3_VERSION and no LibreSSL */
12355
12356 default: {
12357 tls_flags |= TLS_SESS_DATA_RENEGOTIATING;
12358
12359 tls_log("requesting TLS renegotiation on data channel "
12360 "(%" PR_LU " KB data limit)",
12361 (pr_off_t) (tls_data_renegotiate_limit / 1024));
12362
12363 if (SSL_renegotiate(ssl) != 1) {
12364 tls_log("error requesting TLS renegotiation on data channel: %s",
12365 tls_get_errors());
12366 }
12367
12368 pr_timer_add(tls_renegotiate_timeout, -1, &tls_module,
12369 tls_renegotiate_timeout_cb, "SSL/TLS renegotiation timeout");
12370 }
12371 }
12372 }
12373 }
12374
12375 static int tls_netio_read_cb(pr_netio_stream_t *nstrm, char *buf,
12376 size_t buflen) {
12377 SSL *ssl;
12378
12379 ssl = (SSL *) pr_table_get(nstrm->notes, TLS_NETIO_NOTE, NULL);
12380 if (ssl != NULL) {
12381 BIO *rbio, *wbio;
12382 int bread = 0, bwritten = 0, xerrno = 0;
12383 ssize_t res = 0;
12384 unsigned long rbio_rbytes, rbio_wbytes, wbio_rbytes, wbio_wbytes;
12385
12386 rbio = SSL_get_rbio(ssl);
12387 rbio_rbytes = BIO_number_read(rbio);
12388 rbio_wbytes = BIO_number_written(rbio);
12389
12390 wbio = SSL_get_wbio(ssl);
12391 wbio_rbytes = BIO_number_read(wbio);
12392 wbio_wbytes = BIO_number_written(wbio);
12393
12394 if (nstrm->strm_type == PR_NETIO_STRM_DATA) {
12395 tls_data_renegotiate(ssl);
12396 }
12397
12398 res = tls_read(ssl, buf, buflen);
12399 xerrno = errno;
12400
12401 bread = (BIO_number_read(rbio) - rbio_rbytes) +
12402 (BIO_number_read(wbio) - wbio_rbytes);
12403 bwritten = (BIO_number_written(rbio) - rbio_wbytes) +
12404 (BIO_number_written(wbio) - wbio_wbytes);
12405
12406 /* Manually update session.total_raw_in with the difference between
12407 * the raw bytes read in versus the non-SSL bytes read in, in order to
12408 * have %I be accurately represented for the raw traffic.
12409 */
12410 if (res > 0) {
12411 session.total_raw_in += (bread - res);
12412 }
12413
12414 /* Manually update session.total_raw_out, in order to have %O be
12415 * accurately represented for the raw traffic.
12416 */
12417 if (bwritten > 0) {
12418 session.total_raw_out += bwritten;
12419 }
12420
12421 errno = xerrno;
12422 return res;
12423 }
12424
12425 return read(nstrm->strm_fd, buf, buflen);
12426 }
12427
12428 static pr_netio_stream_t *tls_netio_reopen_cb(pr_netio_stream_t *nstrm, int fd,
12429 int mode) {
12430
12431 if (nstrm->strm_fd != -1) {
12432 close(nstrm->strm_fd);
12433 }
12434
12435 nstrm->strm_fd = fd;
12436 nstrm->strm_mode = mode;
12437
12438 /* NOTE: a no-op? */
12439 return nstrm;
12440 }
12441
12442 static int tls_netio_shutdown_cb(pr_netio_stream_t *nstrm, int how) {
12443
12444 if (how == 1 ||
12445 how == 2) {
12446 /* Closing this stream for writing; we need to send the 'close_notify'
12447 * alert first, so that the client knows, at the application layer,
12448 * that the SSL/TLS session is shutting down.
12449 */
12450
12451 if (nstrm->strm_mode == PR_NETIO_IO_WR &&
12452 (nstrm->strm_type == PR_NETIO_STRM_CTRL ||
12453 nstrm->strm_type == PR_NETIO_STRM_DATA)) {
12454 SSL *ssl;
12455
12456 ssl = (SSL *) pr_table_get(nstrm->notes, TLS_NETIO_NOTE, NULL);
12457 if (ssl != NULL) {
12458 BIO *rbio, *wbio;
12459 int bread = 0, bwritten = 0;
12460 unsigned long rbio_rbytes, rbio_wbytes, wbio_rbytes, wbio_wbytes;
12461 conn_t *conn;
12462
12463 rbio = SSL_get_rbio(ssl);
12464 rbio_rbytes = BIO_number_read(rbio);
12465 rbio_wbytes = BIO_number_written(rbio);
12466
12467 wbio = SSL_get_wbio(ssl);
12468 wbio_rbytes = BIO_number_read(wbio);
12469 wbio_wbytes = BIO_number_written(wbio);
12470
12471 if (!(SSL_get_shutdown(ssl) & SSL_SENT_SHUTDOWN)) {
12472
12473 /* Disable any socket buffering (Nagle, TCP_CORK), so that the alert
12474 * is sent in a timely manner (avoiding TLS shutdown latency).
12475 */
12476 conn = (nstrm->strm_type == PR_NETIO_STRM_DATA) ? session.d :
12477 session.c;
12478 if (conn != NULL) {
12479 if (pr_inet_set_proto_nodelay(conn->pool, conn, 1) < 0) {
12480 pr_trace_msg(trace_channel, 9,
12481 "error enabling TCP_NODELAY on conn: %s", strerror(errno));
12482 }
12483
12484 if (pr_inet_set_proto_cork(conn->wfd, 0) < 0) {
12485 pr_trace_msg(trace_channel, 9,
12486 "error disabling TCP_CORK on fd %d: %s", conn->wfd,
12487 strerror(errno));
12488 }
12489 }
12490
12491 /* We haven't sent a 'close_notify' alert yet; do so now. */
12492 SSL_shutdown(ssl);
12493 }
12494
12495 bread = (BIO_number_read(rbio) - rbio_rbytes) +
12496 (BIO_number_read(wbio) - wbio_rbytes);
12497 bwritten = (BIO_number_written(rbio) - rbio_wbytes) +
12498 (BIO_number_written(wbio) - wbio_wbytes);
12499
12500 /* Manually update session.total_raw_in/out, in order to have %I/%O be
12501 * accurately represented for the raw traffic.
12502 */
12503 if (bread > 0) {
12504 session.total_raw_in += bread;
12505 }
12506
12507 if (bwritten > 0) {
12508 session.total_raw_out += bwritten;
12509 }
12510
12511 } else {
12512 pr_trace_msg(trace_channel, 3,
12513 "no TLS found in stream notes for '%s'", TLS_NETIO_NOTE);
12514 }
12515 }
12516 }
12517
12518 return shutdown(nstrm->strm_fd, how);
12519 }
12520
12521 static int tls_netio_write_cb(pr_netio_stream_t *nstrm, char *buf,
12522 size_t buflen) {
12523 SSL *ssl;
12524
12525 ssl = (SSL *) pr_table_get(nstrm->notes, TLS_NETIO_NOTE, NULL);
12526 if (ssl != NULL) {
12527 BIO *rbio, *wbio;
12528 int bread = 0, bwritten = 0, xerrno = 0;
12529 ssize_t res = 0;
12530 unsigned long rbio_rbytes, rbio_wbytes, wbio_rbytes, wbio_wbytes;
12531
12532 rbio = SSL_get_rbio(ssl);
12533 rbio_rbytes = BIO_number_read(rbio);
12534 rbio_wbytes = BIO_number_written(rbio);
12535
12536 wbio = SSL_get_wbio(ssl);
12537 wbio_rbytes = BIO_number_read(wbio);
12538 wbio_wbytes = BIO_number_written(wbio);
12539
12540 if (nstrm->strm_type == PR_NETIO_STRM_DATA) {
12541 tls_data_renegotiate(ssl);
12542 }
12543
12544 res = tls_write(ssl, buf, buflen);
12545 xerrno = errno;
12546
12547 bread = (BIO_number_read(rbio) - rbio_rbytes) +
12548 (BIO_number_read(wbio) - wbio_rbytes);
12549 bwritten = (BIO_number_written(rbio) - rbio_wbytes) +
12550 (BIO_number_written(wbio) - wbio_wbytes);
12551
12552 /* Manually update session.total_raw_in, in order to have %I be
12553 * accurately represented for the raw traffic.
12554 */
12555 if (bread > 0) {
12556 session.total_raw_in += bread;
12557 }
12558
12559 /* Manually update session.total_raw_out with the difference between
12560 * the raw bytes written out versus the non-SSL bytes written out,
12561 * in order to have %) be accurately represented for the raw traffic.
12562 */
12563 if (res > 0) {
12564 session.total_raw_out += (bwritten - res);
12565 }
12566
12567 errno = xerrno;
12568 return res;
12569 }
12570
12571 return write(nstrm->strm_fd, buf, buflen);
12572 }
12573
12574 static void tls_netio_install_ctrl(void) {
12575 pr_netio_t *netio;
12576
12577 if (tls_ctrl_netio) {
12578 /* If we already have our ctrl netio, then it's been registered, and
12579 * we don't need to do anything more.
12580 */
12581 return;
12582 }
12583
12584 tls_ctrl_netio = netio = pr_alloc_netio2(permanent_pool, &tls_module, NULL);
12585
12586 netio->abort = tls_netio_abort_cb;
12587 netio->close = tls_netio_close_cb;
12588 netio->open = tls_netio_open_cb;
12589 netio->poll = tls_netio_poll_cb;
12590 netio->postopen = tls_netio_postopen_cb;
12591 netio->read = tls_netio_read_cb;
12592 netio->reopen = tls_netio_reopen_cb;
12593 netio->shutdown = tls_netio_shutdown_cb;
12594 netio->write = tls_netio_write_cb;
12595
12596 pr_unregister_netio(PR_NETIO_STRM_CTRL);
12597
12598 if (pr_register_netio(netio, PR_NETIO_STRM_CTRL) < 0) {
12599 pr_log_pri(PR_LOG_NOTICE, MOD_TLS_VERSION ": error registering netio: %s",
12600 strerror(errno));
12601 }
12602 }
12603
12604 static void tls_netio_install_data(void) {
12605 pr_netio_t *netio = tls_data_netio ? tls_data_netio :
12606 (tls_data_netio = pr_alloc_netio2(session.pool ? session.pool :
12607 permanent_pool, &tls_module, NULL));
12608
12609 netio->abort = tls_netio_abort_cb;
12610 netio->close = tls_netio_close_cb;
12611 netio->open = tls_netio_open_cb;
12612 netio->poll = tls_netio_poll_cb;
12613 netio->postopen = tls_netio_postopen_cb;
12614 netio->read = tls_netio_read_cb;
12615 netio->reopen = tls_netio_reopen_cb;
12616 netio->shutdown = tls_netio_shutdown_cb;
12617 netio->write = tls_netio_write_cb;
12618
12619 pr_unregister_netio(PR_NETIO_STRM_DATA);
12620
12621 if (pr_register_netio(netio, PR_NETIO_STRM_DATA) < 0) {
12622 pr_log_pri(PR_LOG_NOTICE, MOD_TLS_VERSION ": error registering netio: %s",
12623 strerror(errno));
12624 }
12625 }
12626
12627 /* Logging functions
12628 */
12629
12630 static void tls_closelog(void) {
12631
12632 /* Sanity check */
12633 if (tls_logfd != -1) {
12634 close(tls_logfd);
12635 tls_logfd = -1;
12636 }
12637
12638 return;
12639 }
12640
12641 int tls_log(const char *fmt, ...) {
12642 va_list msg;
12643 int res;
12644
12645 /* Sanity check */
12646 if (tls_logfd < 0) {
12647 return 0;
12648 }
12649
12650 va_start(msg, fmt);
12651 res = pr_log_vwritefile(tls_logfd, MOD_TLS_VERSION, fmt, msg);
12652 va_end(msg);
12653
12654 return res;
12655 }
12656
12657 static int tls_openlog(void) {
12658 int res = 0, xerrno;
12659 char *path;
12660
12661 /* Sanity checks */
12662 path = get_param_ptr(main_server->conf, "TLSLog", FALSE);
12663 if (path == NULL ||
12664 strncasecmp(path, "none", 5) == 0) {
12665 return 0;
12666 }
12667
12668 pr_signals_block();
12669 PRIVS_ROOT
12670 res = pr_log_openfile(path, &tls_logfd, PR_LOG_SYSTEM_MODE);
12671 xerrno = errno;
12672 PRIVS_RELINQUISH
12673 pr_signals_unblock();
12674
12675 errno = xerrno;
12676 return res;
12677 }
12678
12679 /* Authentication handlers
12680 */
12681
12682 /* This function does the main authentication work, and is called in the
12683 * normal course of events:
12684 *
12685 * cmd->argv[0]: user name
12686 * cmd->argv[1]: cleartext password
12687 */
12688 MODRET tls_authenticate(cmd_rec *cmd) {
12689 if (!tls_engine) {
12690 return PR_DECLINED(cmd);
12691 }
12692
12693 /* Possible authentication combinations:
12694 *
12695 * TLS handshake + passwd (default)
12696 * TLS handshake + .tlslogin (passwd ignored)
12697 */
12698
12699 if (tls_flags & TLS_SESS_ON_CTRL) {
12700 config_rec *c;
12701
12702 if (tls_opts & TLS_OPT_ALLOW_DOT_LOGIN) {
12703 if (tls_dotlogin_allow(cmd->argv[0])) {
12704 tls_log("TLS/X509 .tlslogin check successful for user '%s'",
12705 (char *) cmd->argv[0]);
12706 pr_log_auth(PR_LOG_NOTICE, "USER %s: TLS/X509 .tlslogin authentication "
12707 "successful", (char *) cmd->argv[0]);
12708 session.auth_mech = "mod_tls.c";
12709 return mod_create_data(cmd, (void *) PR_AUTH_RFC2228_OK);
12710
12711 } else {
12712 tls_log("TLS/X509 .tlslogin check failed for user '%s'",
12713 (char *) cmd->argv[0]);
12714 }
12715 }
12716
12717 c = find_config(main_server->conf, CONF_PARAM, "TLSUserName", FALSE);
12718 if (c != NULL) {
12719 if (tls_cert_to_user(cmd->argv[0], c->argv[0])) {
12720 tls_log("TLS/X509 TLSUserName '%s' check successful for user '%s'",
12721 (char *) c->argv[0], (char *) cmd->argv[0]);
12722 pr_log_auth(PR_LOG_NOTICE,
12723 "USER %s: TLS/X509 TLSUserName authentication successful",
12724 (char *) cmd->argv[0]);
12725 session.auth_mech = "mod_tls.c";
12726 return mod_create_data(cmd, (void *) PR_AUTH_RFC2228_OK);
12727
12728 } else {
12729 tls_log("TLS/X509 TLSUserName '%s' check failed for user '%s'",
12730 (char *) c->argv[0], (char *) cmd->argv[0]);
12731 }
12732 }
12733 }
12734
12735 return PR_DECLINED(cmd);
12736 }
12737
12738 /* This function is called only when UserPassword is involved, used to
12739 * override the configured password for a user.
12740 *
12741 * cmd->argv[0]: hashed password (from proftpd.conf)
12742 * cmd->argv[1]: user name
12743 * cmd->argv[2]: cleartext password
12744 */
12745 MODRET tls_auth_check(cmd_rec *cmd) {
12746 if (!tls_engine)
12747 return PR_DECLINED(cmd);
12748
12749 /* Possible authentication combinations:
12750 *
12751 * TLS handshake + passwd (default)
12752 * TLS handshake + .tlslogin (passwd ignored)
12753 */
12754
12755 if (tls_flags & TLS_SESS_ON_CTRL) {
12756 config_rec *c;
12757
12758 if (tls_opts & TLS_OPT_ALLOW_DOT_LOGIN) {
12759 if (tls_dotlogin_allow(cmd->argv[1])) {
12760 tls_log("TLS/X509 .tlslogin check successful for user '%s'",
12761 (char *) cmd->argv[0]);
12762 pr_log_auth(PR_LOG_NOTICE, "USER %s: TLS/X509 .tlslogin authentication "
12763 "successful", (char *) cmd->argv[1]);
12764 session.auth_mech = "mod_tls.c";
12765 return mod_create_data(cmd, (void *) PR_AUTH_RFC2228_OK);
12766
12767 } else {
12768 tls_log("TLS/X509 .tlslogin check failed for user '%s'",
12769 (char *) cmd->argv[1]);
12770 }
12771 }
12772
12773 c = find_config(main_server->conf, CONF_PARAM, "TLSUserName", FALSE);
12774 if (c != NULL) {
12775 if (tls_cert_to_user(cmd->argv[0], c->argv[0])) {
12776 tls_log("TLS/X509 TLSUserName '%s' check successful for user '%s'",
12777 (char *) c->argv[0], (char *) cmd->argv[0]);
12778 pr_log_auth(PR_LOG_NOTICE,
12779 "USER %s: TLS/X509 TLSUserName authentication successful",
12780 (char *) cmd->argv[0]);
12781 session.auth_mech = "mod_tls.c";
12782 return mod_create_data(cmd, (void *) PR_AUTH_RFC2228_OK);
12783
12784 } else {
12785 tls_log("TLS/X509 TLSUserName '%s' check failed for user '%s'",
12786 (char *) c->argv[0], (char *) cmd->argv[0]);
12787 }
12788 }
12789 }
12790
12791 return PR_DECLINED(cmd);
12792 }
12793
12794 /* Command handlers
12795 */
12796
12797 MODRET tls_any(cmd_rec *cmd) {
12798 if (!tls_engine)
12799 return PR_DECLINED(cmd);
12800
12801 /* Some commands need not be hindered. */
12802 if (pr_cmd_cmp(cmd, PR_CMD_SYST_ID) == 0 ||
12803 pr_cmd_cmp(cmd, PR_CMD_AUTH_ID) == 0 ||
12804 pr_cmd_cmp(cmd, PR_CMD_FEAT_ID) == 0 ||
12805 pr_cmd_cmp(cmd, PR_CMD_HOST_ID) == 0 ||
12806 pr_cmd_cmp(cmd, PR_CMD_CLNT_ID) == 0 ||
12807 pr_cmd_cmp(cmd, PR_CMD_QUIT_ID) == 0) {
12808 return PR_DECLINED(cmd);
12809 }
12810
12811 if (tls_required_on_auth == 1 &&
12812 !(tls_flags & TLS_SESS_ON_CTRL)) {
12813
12814 if (!(tls_opts & TLS_OPT_ALLOW_PER_USER)) {
12815 if (pr_cmd_cmp(cmd, PR_CMD_USER_ID) == 0 ||
12816 pr_cmd_cmp(cmd, PR_CMD_PASS_ID) == 0 ||
12817 pr_cmd_cmp(cmd, PR_CMD_ACCT_ID) == 0) {
12818 tls_log("SSL/TLS required but absent for authentication, "
12819 "denying %s command", (char *) cmd->argv[0]);
12820 pr_response_add_err(R_550,
12821 _("SSL/TLS required on the control channel"));
12822
12823 pr_cmd_set_errno(cmd, EPERM);
12824 errno = EPERM;
12825 return PR_ERROR(cmd);
12826 }
12827 }
12828 }
12829
12830 if (tls_required_on_ctrl == 1 &&
12831 !(tls_flags & TLS_SESS_ON_CTRL)) {
12832
12833 if (!(tls_opts & TLS_OPT_ALLOW_PER_USER)) {
12834 tls_log("SSL/TLS required but absent on control channel, "
12835 "denying %s command", (char *) cmd->argv[0]);
12836 pr_response_add_err(R_550, _("SSL/TLS required on the control channel"));
12837
12838 pr_cmd_set_errno(cmd, EPERM);
12839 errno = EPERM;
12840 return PR_ERROR(cmd);
12841
12842 } else {
12843
12844 if (tls_authenticated &&
12845 *tls_authenticated == TRUE) {
12846 tls_log("SSL/TLS required but absent on control channel, "
12847 "denying %s command", (char *) cmd->argv[0]);
12848 pr_response_add_err(R_550,
12849 _("SSL/TLS required on the control channel"));
12850
12851 pr_cmd_set_errno(cmd, EPERM);
12852 errno = EPERM;
12853 return PR_ERROR(cmd);
12854 }
12855 }
12856 }
12857
12858 /* TLSRequired checks */
12859
12860 if (tls_required_on_data == 1) {
12861 /* TLSRequired encompasses all data transfers for this session, the
12862 * client did not specify an appropriate PROT, and the command is one
12863 * which will trigger a data transfer...
12864 */
12865
12866 if (!(tls_flags & TLS_SESS_NEED_DATA_PROT)) {
12867 if (pr_cmd_cmp(cmd, PR_CMD_APPE_ID) == 0 ||
12868 pr_cmd_cmp(cmd, PR_CMD_LIST_ID) == 0 ||
12869 pr_cmd_cmp(cmd, PR_CMD_MLSD_ID) == 0 ||
12870 pr_cmd_cmp(cmd, PR_CMD_NLST_ID) == 0 ||
12871 pr_cmd_cmp(cmd, PR_CMD_RETR_ID) == 0 ||
12872 pr_cmd_cmp(cmd, PR_CMD_STOR_ID) == 0 ||
12873 pr_cmd_cmp(cmd, PR_CMD_STOU_ID) == 0) {
12874 tls_log("SSL/TLS required but absent on data channel, "
12875 "denying %s command", (char *) cmd->argv[0]);
12876 pr_response_add_err(R_522, _("SSL/TLS required on the data channel"));
12877
12878 pr_cmd_set_errno(cmd, EPERM);
12879 errno = EPERM;
12880 return PR_ERROR(cmd);
12881 }
12882 }
12883
12884 } else {
12885
12886 /* TLSRequired is not in effect for all data transfers for this session.
12887 * If this command will trigger a data transfer, check the current
12888 * context to see if there's a directory-level TLSRequired for data
12889 * transfers.
12890 *
12891 * XXX ideally, rather than using the current directory location, we'd
12892 * do the lookup based on the target location.
12893 */
12894
12895 if (pr_cmd_cmp(cmd, PR_CMD_APPE_ID) == 0 ||
12896 pr_cmd_cmp(cmd, PR_CMD_LIST_ID) == 0 ||
12897 pr_cmd_cmp(cmd, PR_CMD_MLSD_ID) == 0 ||
12898 pr_cmd_cmp(cmd, PR_CMD_NLST_ID) == 0 ||
12899 pr_cmd_cmp(cmd, PR_CMD_RETR_ID) == 0 ||
12900 pr_cmd_cmp(cmd, PR_CMD_STOR_ID) == 0 ||
12901 pr_cmd_cmp(cmd, PR_CMD_STOU_ID) == 0) {
12902 config_rec *c;
12903
12904 c = find_config(CURRENT_CONF, CONF_PARAM, "TLSRequired", FALSE);
12905 if (c) {
12906 int tls_required;
12907
12908 tls_required = *((int *) c->argv[1]);
12909
12910 if (tls_required == TRUE &&
12911 !(tls_flags & TLS_SESS_NEED_DATA_PROT)) {
12912 tls_log("%s command denied by TLSRequired in directory '%s'",
12913 (char *) cmd->argv[0],
12914 session.dir_config ? session.dir_config->name :
12915 session.anon_config ? session.anon_config->name :
12916 main_server->ServerName);
12917 pr_response_add_err(R_522, _("SSL/TLS required on the data channel"));
12918
12919 pr_cmd_set_errno(cmd, EPERM);
12920 errno = EPERM;
12921 return PR_ERROR(cmd);
12922 }
12923 }
12924 }
12925 }
12926
12927 return PR_DECLINED(cmd);
12928 }
12929
12930 MODRET tls_auth(cmd_rec *cmd) {
12931 register unsigned int i = 0;
12932 char *mode;
12933 unsigned char *authenticated = NULL;
12934
12935 if (tls_engine == FALSE) {
12936 return PR_DECLINED(cmd);
12937 }
12938
12939 /* If we already have protection on the control channel (i.e. AUTH has
12940 * already been sent by the client and handled), then reject this second
12941 * AUTH. Clients that want to renegotiate can either use SSL/TLS's
12942 * renegotiation facilities, or disconnect and start over.
12943 */
12944 if (tls_flags & TLS_SESS_ON_CTRL) {
12945 tls_log("Unwilling to accept AUTH after AUTH for this session");
12946 pr_response_add_err(R_503, _("Unwilling to accept second AUTH"));
12947
12948 pr_cmd_set_errno(cmd, EPERM);
12949 errno = EPERM;
12950 return PR_ERROR(cmd);
12951 }
12952
12953 if (cmd->argc < 2) {
12954 pr_response_add_err(R_504, _("AUTH requires at least one argument"));
12955
12956 pr_cmd_set_errno(cmd, EINVAL);
12957 errno = EINVAL;
12958 return PR_ERROR(cmd);
12959 }
12960
12961 if (tls_flags & TLS_SESS_HAVE_CCC) {
12962 tls_log("Unwilling to accept AUTH after CCC for this session");
12963 pr_response_add_err(R_534, _("Unwilling to accept security parameters"));
12964
12965 pr_cmd_set_errno(cmd, EPERM);
12966 errno = EPERM;
12967 return PR_ERROR(cmd);
12968 }
12969
12970 /* CAN we even handle an AUTH command? If we do not have the necessary
12971 * certificates, then we should indicate that we cannot.
12972 */
12973 if (tls_rsa_cert_file == NULL &&
12974 tls_dsa_cert_file == NULL &&
12975 tls_ec_cert_file == NULL &&
12976 tls_pkcs12_file == NULL) {
12977 tls_log("Unable to accept AUTH %s due to lack of certificates", cmd->arg);
12978 pr_response_add_err(R_431, _("Necessary security resource unavailable"));
12979
12980 pr_cmd_set_errno(cmd, EPERM);
12981 errno = EPERM;
12982 return PR_ERROR(cmd);
12983 }
12984
12985 /* If the client has already authenticated via USER/PASS, AND if the
12986 * AllowPerUser TLSOption is NOT in effect, then do not allow the AUTH
12987 * command.
12988 */
12989 authenticated = get_param_ptr(cmd->server->conf, "authenticated", FALSE);
12990 if (authenticated != NULL &&
12991 *authenticated == TRUE &&
12992 !(tls_opts & TLS_OPT_ALLOW_PER_USER)) {
12993 tls_log("Unwilling to accept AUTH after USER/PASS authentication for this session unless AllowPerUser TLSOption is used");
12994 pr_response_add_err(R_534, _("Unwilling to accept security parameters"));
12995
12996 pr_cmd_set_errno(cmd, EPERM);
12997 errno = EPERM;
12998 return PR_ERROR(cmd);
12999 }
13000
13001 /* Convert the parameter to upper case */
13002 mode = cmd->argv[1];
13003 for (i = 0; i < strlen(mode); i++) {
13004 if (PR_ISALPHA((int) mode[i])) {
13005 mode[i] = toupper(mode[i]);
13006 }
13007 }
13008
13009 if (strncmp(mode, "TLS", 4) == 0 ||
13010 strncmp(mode, "TLS-C", 6) == 0) {
13011 uint64_t start_ms = 0;
13012
13013 pr_response_send(R_234, _("AUTH %s successful"), (char *) cmd->argv[1]);
13014 tls_log("%s", "TLS/TLS-C requested, starting TLS handshake");
13015
13016 if (pr_trace_get_level(timing_channel) > 0) {
13017 pr_gettimeofday_millis(&start_ms);
13018 }
13019
13020 pr_event_generate("mod_tls.ctrl-handshake", session.c);
13021 if (tls_accept(session.c, FALSE) < 0) {
13022 tls_log("%s", "TLS/TLS-C negotiation failed on control channel");
13023
13024 if (tls_required_on_ctrl == 1) {
13025 pr_response_send_async(R_421, _("TLS handshake failed"));
13026 pr_session_disconnect(&tls_module, PR_SESS_DISCONNECT_CONFIG_ACL,
13027 "TLSRequired");
13028 }
13029
13030 /* If we reach this point, the debug logging may show gibberish
13031 * commands from the client. In reality, this gibberish is probably
13032 * more encrypted data from the client.
13033 */
13034 pr_response_send_async(R_421, _("TLS handshake failed"));
13035 pr_session_disconnect(&tls_module, PR_SESS_DISCONNECT_BY_APPLICATION,
13036 NULL);
13037 }
13038
13039 #if OPENSSL_VERSION_NUMBER < 0x0090702fL
13040 /* Make sure blinding is turned on. (For some reason, this only seems
13041 * to be allowed on SSL objects, not on SSL_CTX objects. Bummer).
13042 */
13043 tls_blinding_on(ctrl_ssl);
13044 #endif
13045
13046 tls_flags |= TLS_SESS_ON_CTRL;
13047
13048 if (pr_trace_get_level(timing_channel) >= 4) {
13049 unsigned long elapsed_ms;
13050 uint64_t finish_ms;
13051
13052 pr_gettimeofday_millis(&finish_ms);
13053
13054 elapsed_ms = (unsigned long) (finish_ms - session.connect_time_ms);
13055 pr_trace_msg(timing_channel, 4,
13056 "Time before TLS ctrl handshake: %lu ms", elapsed_ms);
13057
13058 elapsed_ms = (unsigned long) (finish_ms - start_ms);
13059 pr_trace_msg(timing_channel, 4,
13060 "TLS ctrl handshake duration: %lu ms", elapsed_ms);
13061 }
13062
13063 } else if (strncmp(mode, "SSL", 4) == 0 ||
13064 strncmp(mode, "TLS-P", 6) == 0) {
13065 uint64_t start_ms = 0;
13066
13067 pr_response_send(R_234, _("AUTH %s successful"), (char *) cmd->argv[1]);
13068 tls_log("%s", "SSL/TLS-P requested, starting TLS handshake");
13069
13070 if (pr_trace_get_level(timing_channel) > 0) {
13071 pr_gettimeofday_millis(&start_ms);
13072 }
13073
13074 if (tls_accept(session.c, FALSE) < 0) {
13075 tls_log("%s", "SSL/TLS-P negotiation failed on control channel");
13076
13077 if (tls_required_on_ctrl == 1) {
13078 pr_response_send_async(R_421, _("TLS handshake failed"));
13079 pr_session_disconnect(&tls_module, PR_SESS_DISCONNECT_CONFIG_ACL,
13080 "TLSRequired");
13081 }
13082
13083 /* If we reach this point, the debug logging may show gibberish
13084 * commands from the client. In reality, this gibberish is probably
13085 * more encrypted data from the client.
13086 */
13087 pr_response_send_async(R_421, _("TLS handshake failed"));
13088 pr_session_disconnect(&tls_module, PR_SESS_DISCONNECT_BY_APPLICATION,
13089 NULL);
13090 }
13091
13092 #if OPENSSL_VERSION_NUMBER < 0x0090702fL
13093 /* Make sure blinding is turned on. (For some reason, this only seems
13094 * to be allowed on SSL objects, not on SSL_CTX objects. Bummer).
13095 */
13096 tls_blinding_on(ctrl_ssl);
13097 #endif
13098
13099 tls_flags |= TLS_SESS_ON_CTRL;
13100 tls_flags |= TLS_SESS_NEED_DATA_PROT;
13101
13102 if (pr_trace_get_level(timing_channel) >= 4) {
13103 unsigned long elapsed_ms;
13104 uint64_t finish_ms;
13105
13106 pr_gettimeofday_millis(&finish_ms);
13107
13108 elapsed_ms = (unsigned long) (finish_ms - session.connect_time_ms);
13109 pr_trace_msg(timing_channel, 4,
13110 "Time before TLS ctrl handshake: %lu ms", elapsed_ms);
13111
13112 elapsed_ms = (unsigned long) (finish_ms - start_ms);
13113 pr_trace_msg(timing_channel, 4,
13114 "TLS ctrl handshake duration: %lu ms", elapsed_ms);
13115 }
13116
13117 } else {
13118 tls_log("AUTH %s unsupported, declining", (char *) cmd->argv[1]);
13119
13120 /* Allow other RFC2228 modules a chance a handling this command. */
13121 return PR_DECLINED(cmd);
13122 }
13123
13124 pr_session_set_protocol("ftps");
13125 session.rfc2228_mech = "TLS";
13126
13127 return PR_HANDLED(cmd);
13128 }
13129
13130 MODRET tls_ccc(cmd_rec *cmd) {
13131
13132 if (!tls_engine ||
13133 !session.rfc2228_mech ||
13134 strncmp(session.rfc2228_mech, "TLS", 4) != 0) {
13135 return PR_DECLINED(cmd);
13136 }
13137
13138 if (!(tls_flags & TLS_SESS_ON_CTRL)) {
13139 pr_response_add_err(R_533,
13140 _("CCC not allowed on insecure control connection"));
13141
13142 pr_cmd_set_errno(cmd, EPERM);
13143 errno = EPERM;
13144 return PR_ERROR(cmd);
13145 }
13146
13147 if (tls_required_on_ctrl == 1) {
13148 pr_response_add_err(R_534, _("Unwilling to accept security parameters"));
13149 tls_log("%s: unwilling to accept security parameters: "
13150 "TLSRequired setting does not allow for unprotected control channel",
13151 (char *) cmd->argv[0]);
13152
13153 pr_cmd_set_errno(cmd, EPERM);
13154 errno = EPERM;
13155 return PR_ERROR(cmd);
13156 }
13157
13158 /* Check for <Limit> restrictions. */
13159 if (!dir_check(cmd->tmp_pool, cmd, G_NONE, session.cwd, NULL)) {
13160
13161 pr_log_debug(DEBUG8, "%s %s denied by <Limit> configuration",
13162 (char *) cmd->argv[0], cmd->arg);
13163 tls_log("%s: unwilling to accept security parameters",
13164 (char *) cmd->argv[0]);
13165 pr_response_add_err(R_534, _("Unwilling to accept security parameters"));
13166
13167 pr_cmd_set_errno(cmd, EPERM);
13168 errno = EPERM;
13169 return PR_ERROR(cmd);
13170 }
13171
13172 tls_log("received CCC, clearing control channel protection");
13173
13174 /* Send the OK response asynchronously; the spec dictates that the
13175 * response be sent prior to performing the TLS session shutdown.
13176 */
13177 pr_response_send_async(R_200, _("Clearing control channel protection"));
13178
13179 /* Close the TLS session, but only one the control channel.
13180 * The data channel, if protected, should remain so.
13181 */
13182
13183 tls_end_sess(ctrl_ssl, session.c, TLS_SHUTDOWN_FL_BIDIRECTIONAL);
13184 pr_table_remove(tls_ctrl_rd_nstrm->notes, TLS_NETIO_NOTE, NULL);
13185 pr_table_remove(tls_ctrl_wr_nstrm->notes, TLS_NETIO_NOTE, NULL);
13186 ctrl_ssl = NULL;
13187
13188 /* Remove our NetIO for the control channel. */
13189 pr_unregister_netio(PR_NETIO_STRM_CTRL);
13190
13191 tls_flags &= ~TLS_SESS_ON_CTRL;
13192 tls_flags |= TLS_SESS_HAVE_CCC;
13193
13194 return PR_HANDLED(cmd);
13195 }
13196
13197 MODRET tls_pbsz(cmd_rec *cmd) {
13198
13199 if (!tls_engine ||
13200 !session.rfc2228_mech ||
13201 strncmp(session.rfc2228_mech, "TLS", 4) != 0)
13202 return PR_DECLINED(cmd);
13203
13204 CHECK_CMD_ARGS(cmd, 2);
13205
13206 if (!(tls_flags & TLS_SESS_ON_CTRL)) {
13207 pr_response_add_err(R_503,
13208 _("PBSZ not allowed on insecure control connection"));
13209
13210 pr_cmd_set_errno(cmd, EPERM);
13211 errno = EPERM;
13212 return PR_ERROR(cmd);
13213 }
13214
13215 /* We expect "PBSZ 0" */
13216 if (strncmp(cmd->argv[1], "0", 2) == 0) {
13217 pr_response_add(R_200, _("PBSZ 0 successful"));
13218
13219 } else {
13220 pr_response_add(R_200, _("PBSZ=0 successful"));
13221 }
13222
13223 tls_flags |= TLS_SESS_PBSZ_OK;
13224 return PR_HANDLED(cmd);
13225 }
13226
13227 MODRET tls_post_auth(cmd_rec *cmd) {
13228 const char *sni = NULL;
13229 server_rec *named_server = NULL;
13230 cmd_rec *host_cmd = NULL;
13231
13232 if (tls_engine == FALSE) {
13233 return PR_DECLINED(cmd);
13234 }
13235
13236 /* We are specifically looking for SNI provided by the client during
13237 * a successful AUTH TLS handshake.
13238 */
13239 if (session.rfc2228_mech == NULL ||
13240 strncmp(session.rfc2228_mech, "TLS", 4) != 0) {
13241 return PR_DECLINED(cmd);
13242 }
13243
13244 sni = pr_table_get(session.notes, "mod_tls.sni", NULL);
13245 if (sni == NULL) {
13246 /* No SNI provided. */
13247 return PR_DECLINED(cmd);
13248 }
13249
13250 if (tls_opts & TLS_OPT_IGNORE_SNI) {
13251 return PR_DECLINED(cmd);
13252 }
13253
13254 named_server = pr_namebind_get_server(sni, main_server->addr,
13255 session.c->local_port);
13256 if (named_server == NULL) {
13257 pr_trace_msg(trace_channel, 5,
13258 "client sent SNI '%s', but no matching host found", sni);
13259 return PR_DECLINED(cmd);
13260 }
13261
13262 if (named_server == main_server) {
13263 return PR_DECLINED(cmd);
13264 }
13265
13266 /* Set a session flag indicating that the main_server pointer changed. */
13267 pr_log_debug(DEBUG0,
13268 "Changing to server '%s' (ServerAlias %s) due to TLS SNI",
13269 named_server->ServerName, sni);
13270 session.prev_server = main_server;
13271 main_server = named_server;
13272
13273 pr_event_generate("core.session-reinit", named_server);
13274
13275 /* Now we need to inform the modules of the changed config, to let them
13276 * do their checks.
13277 */
13278
13279 host_cmd = pr_cmd_alloc(cmd->tmp_pool, 2, pstrdup(cmd->tmp_pool, C_HOST), sni,
13280 NULL);
13281 pr_cmd_dispatch_phase(host_cmd, POST_CMD, 0);
13282 pr_cmd_dispatch_phase(host_cmd, LOG_CMD, 0);
13283 pr_response_clear(&resp_list);
13284
13285 return PR_DECLINED(cmd);
13286 }
13287
13288 MODRET tls_log_auth(cmd_rec *cmd) {
13289 if (tls_engine == FALSE) {
13290 return PR_DECLINED(cmd);
13291 }
13292
13293 /* Ensure any sensitive passphrases are scrubbed. */
13294 (void) tls_lookup_pkey(main_server, FALSE, TRUE);
13295
13296 return PR_DECLINED(cmd);
13297 }
13298
13299 MODRET tls_post_pass(cmd_rec *cmd) {
13300 config_rec *c, *protocols_config;
13301
13302 if (tls_engine == FALSE) {
13303 return PR_DECLINED(cmd);
13304 }
13305
13306 c = find_config(main_server->conf, CONF_PARAM, "TLSOptions", FALSE);
13307 while (c != NULL) {
13308 unsigned long opts = 0;
13309
13310 pr_signals_handle();
13311
13312 opts = *((unsigned long *) c->argv[0]);
13313 tls_opts |= opts;
13314
13315 c = find_config_next(c, c->next, CONF_PARAM, "TLSOptions", FALSE);
13316 }
13317
13318 /* At this point, we can look up the Protocols config if the client has been
13319 * authenticated, which may have been tweaked via mod_ifsession's
13320 * user/group/class-specific sections.
13321 */
13322 protocols_config = find_config(main_server->conf, CONF_PARAM, "Protocols",
13323 FALSE);
13324
13325 if (!(tls_opts & TLS_OPT_ALLOW_PER_USER) &&
13326 protocols_config == NULL) {
13327 return PR_DECLINED(cmd);
13328 }
13329
13330 tls_authenticated = get_param_ptr(cmd->server->conf, "authenticated", FALSE);
13331
13332 if (tls_authenticated &&
13333 *tls_authenticated == TRUE) {
13334
13335 c = find_config(TOPLEVEL_CONF, CONF_PARAM, "TLSRequired", FALSE);
13336 if (c != NULL) {
13337 /* Lookup the TLSRequired directive again in this context (which could be
13338 * <Anonymous>, for example, or modified by mod_ifsession).
13339 */
13340
13341 tls_required_on_ctrl = *((int *) c->argv[0]);
13342 tls_required_on_data = *((int *) c->argv[1]);
13343 tls_required_on_auth = *((int *) c->argv[2]);
13344
13345 /* We cannot return PR_ERROR for the PASS command at this point, since
13346 * this is a POST_CMD handler. Instead, we will simply check the
13347 * TLSRequired policy, and if the current session does not make the
13348 * cut, well, then the session gets cut.
13349 */
13350 if ((tls_required_on_ctrl == 1 ||
13351 tls_required_on_auth == 1) &&
13352 (!(tls_flags & TLS_SESS_ON_CTRL))) {
13353 tls_log("SSL/TLS required but absent on control channel, "
13354 "disconnecting");
13355 pr_response_send(R_530, "%s", _("Login incorrect."));
13356 pr_session_disconnect(&tls_module, PR_SESS_DISCONNECT_CONFIG_ACL,
13357 "TLSRequired");
13358 }
13359 }
13360
13361 if (protocols_config != NULL) {
13362 register unsigned int i;
13363 int allow_sess = FALSE;
13364 array_header *protocols;
13365 char **elts;
13366
13367 protocols = protocols_config->argv[0];
13368 elts = protocols->elts;
13369
13370 for (i = 0; i < protocols->nelts; i++) {
13371 char *proto;
13372
13373 proto = elts[i];
13374 if (proto != NULL) {
13375 /* We only want to check for 'ftps' in the configured Protocols list
13376 * if the RFC2228 mechanism is "TLS".
13377 */
13378
13379 if (strcasecmp(proto, "ftp") == 0) {
13380 if (session.rfc2228_mech == NULL ||
13381 strcmp(session.rfc2228_mech, "TLS") != 0) {
13382 allow_sess = TRUE;
13383 break;
13384 }
13385 }
13386
13387 if (strcasecmp(proto, "ftps") == 0) {
13388 if (session.rfc2228_mech != NULL &&
13389 strcmp(session.rfc2228_mech, "TLS") == 0) {
13390 allow_sess = TRUE;
13391 break;
13392 }
13393 }
13394 }
13395 }
13396
13397 if (allow_sess == FALSE) {
13398 tls_log("%s protocol denied by Protocols config",
13399 pr_session_get_protocol(0));
13400 pr_response_send(R_530, "%s", _("Login incorrect."));
13401 pr_session_disconnect(&tls_module, PR_SESS_DISCONNECT_CONFIG_ACL,
13402 "Denied by Protocols setting");
13403 }
13404 }
13405 }
13406
13407 return PR_DECLINED(cmd);
13408 }
13409
13410 MODRET tls_post_user(cmd_rec *cmd) {
13411 const void *ifsess_note;
13412 config_rec *c;
13413
13414 if (tls_engine == FALSE) {
13415 return PR_DECLINED(cmd);
13416 }
13417
13418 /* Look for a session note, stashed by mod_ifsession when its
13419 * PerUnauthenticatedUser option is set. That is our cue to honor any
13420 * <IfUser>/<IfGroup> TLSRequired settings for this user.
13421 */
13422 ifsess_note = pr_table_get(session.notes,
13423 "mod_ifsession.per-unauthenticated-user", NULL);
13424 if (ifsess_note == NULL) {
13425 return PR_DECLINED(cmd);
13426 }
13427
13428 c = find_config(main_server->conf, CONF_PARAM, "TLSOptions", FALSE);
13429 while (c != NULL) {
13430 unsigned long opts = 0;
13431
13432 pr_signals_handle();
13433
13434 opts = *((unsigned long *) c->argv[0]);
13435 tls_opts |= opts;
13436
13437 c = find_config_next(c, c->next, CONF_PARAM, "TLSOptions", FALSE);
13438 }
13439
13440 if (!(tls_opts & TLS_OPT_ALLOW_PER_USER)) {
13441 return PR_DECLINED(cmd);
13442 }
13443
13444 c = find_config(main_server->conf, CONF_PARAM, "TLSRequired", FALSE);
13445 if (c != NULL) {
13446 tls_required_on_ctrl = *((int *) c->argv[0]);
13447 tls_required_on_data = *((int *) c->argv[1]);
13448 tls_required_on_auth = *((int *) c->argv[2]);
13449
13450 /* We cannot return PR_ERROR for the USER command at this point, since
13451 * this is a POST_CMD handler. Instead, we will simply check the
13452 * TLSRequired policy, and if the current session does not make the
13453 * cut, well, then the session gets cut.
13454 */
13455 if ((tls_required_on_ctrl == 1 ||
13456 tls_required_on_auth == 1) &&
13457 (!(tls_flags & TLS_SESS_ON_CTRL))) {
13458 tls_log("SSL/TLS required but absent on control channel, "
13459 "disconnecting");
13460 pr_response_send(R_530, "%s", _("Login incorrect."));
13461 pr_session_disconnect(&tls_module, PR_SESS_DISCONNECT_CONFIG_ACL,
13462 "TLSRequired");
13463 }
13464 }
13465
13466 return PR_DECLINED(cmd);
13467 }
13468
13469 MODRET tls_prot(cmd_rec *cmd) {
13470 char *prot;
13471
13472 if (!tls_engine ||
13473 !session.rfc2228_mech ||
13474 strncmp(session.rfc2228_mech, "TLS", 4) != 0) {
13475 return PR_DECLINED(cmd);
13476 }
13477
13478 CHECK_CMD_ARGS(cmd, 2);
13479
13480 if (!(tls_flags & TLS_SESS_ON_CTRL) &&
13481 !(tls_flags & TLS_SESS_HAVE_CCC)) {
13482 pr_response_add_err(R_503,
13483 _("PROT not allowed on insecure control connection"));
13484
13485 pr_cmd_set_errno(cmd, EPERM);
13486 errno = EPERM;
13487 return PR_ERROR(cmd);
13488 }
13489
13490 /* In theory, we could enforce the RFC 4217 semantics, which require
13491 * that PBSZ be sent before the PROT command.
13492 *
13493 * However, some broken FTPS clients do not send PBSZ before PROT. And,
13494 * in practice, since the PBSZ value for FTPS is ALWAYS zero, there is little
13495 * value in punishing users of these broken clients by refusing to work
13496 * with their client.
13497 *
13498 * Thus we've relaxed our PBSZ requirements, by acting as if PBSZ has been
13499 * sent already, even if it has not. For now.
13500 */
13501
13502 /* Check for <Limit> restrictions. */
13503 if (!dir_check(cmd->tmp_pool, cmd, G_NONE, session.cwd, NULL)) {
13504
13505 pr_log_debug(DEBUG8, "%s %s denied by <Limit> configuration",
13506 (char *) cmd->argv[0], cmd->arg);
13507 tls_log("%s: denied by <Limit> configuration", (char *) cmd->argv[0]);
13508 pr_response_add_err(R_534, _("Unwilling to accept security parameters"));
13509
13510 pr_cmd_set_errno(cmd, EPERM);
13511 errno = EPERM;
13512 return PR_ERROR(cmd);
13513 }
13514
13515 /* Only PROT C or PROT P is valid with respect to SSL/TLS. */
13516 prot = cmd->argv[1];
13517 if (strncmp(prot, "C", 2) == 0) {
13518 char *mesg = "Protection set to Clear";
13519
13520 if (tls_required_on_data != 1) {
13521 /* Only accept this if SSL/TLS is not required, by policy, on data
13522 * connections.
13523 */
13524 tls_flags &= ~TLS_SESS_NEED_DATA_PROT;
13525 pr_response_add(R_200, "%s", mesg);
13526 tls_log("%s", mesg);
13527
13528 } else {
13529 pr_response_add_err(R_534, _("Unwilling to accept security parameters"));
13530 tls_log("%s: TLSRequired requires protection for data transfers",
13531 (char *) cmd->argv[0]);
13532 tls_log("%s: unwilling to accept security parameter (%s)",
13533 (char *) cmd->argv[0], prot);
13534
13535 pr_cmd_set_errno(cmd, EPERM);
13536 errno = EPERM;
13537 return PR_ERROR(cmd);
13538 }
13539
13540 } else if (strncmp(prot, "P", 2) == 0) {
13541 char *mesg = "Protection set to Private";
13542
13543 if (tls_required_on_data != -1) {
13544 /* Only accept this if SSL/TLS is allowed, by policy, on data
13545 * connections.
13546 */
13547 tls_flags |= TLS_SESS_NEED_DATA_PROT;
13548 pr_response_add(R_200, "%s", mesg);
13549 tls_log("%s", mesg);
13550
13551 } else {
13552 pr_response_add_err(R_534, _("Unwilling to accept security parameters"));
13553 tls_log("%s: TLSRequired does not allow protection for data transfers",
13554 (char *) cmd->argv[0]);
13555 tls_log("%s: unwilling to accept security parameter (%s)",
13556 (char *) cmd->argv[0], prot);
13557
13558 pr_cmd_set_errno(cmd, EPERM);
13559 errno = EPERM;
13560 return PR_ERROR(cmd);
13561 }
13562
13563 } else if (strncmp(prot, "S", 2) == 0 ||
13564 strncmp(prot, "E", 2) == 0) {
13565 pr_response_add_err(R_536, _("PROT %s unsupported"), prot);
13566
13567 /* By the time the logic reaches this point, there must have been
13568 * an SSL/TLS session negotiated; other AUTH mechanisms will handle
13569 * things differently, and when they do, the logic of this handler
13570 * would not reach this point. This means that it would not be impolite
13571 * to return ERROR here, rather than DECLINED: it shows that mod_tls
13572 * is handling the security mechanism, and that this module does not
13573 * allow for the unsupported PROT levels.
13574 */
13575
13576 pr_cmd_set_errno(cmd, ENOSYS);
13577 errno = ENOSYS;
13578 return PR_ERROR(cmd);
13579
13580 } else {
13581 pr_response_add_err(R_504, _("PROT %s unsupported"), prot);
13582
13583 pr_cmd_set_errno(cmd, ENOSYS);
13584 errno = ENOSYS;
13585 return PR_ERROR(cmd);
13586 }
13587
13588 tls_flags |= TLS_SESS_PBSZ_OK;
13589 return PR_HANDLED(cmd);
13590 }
13591
13592 MODRET tls_sscn(cmd_rec *cmd) {
13593
13594 if (tls_engine == FALSE ||
13595 session.rfc2228_mech == NULL ||
13596 strncmp(session.rfc2228_mech, "TLS", 4) != 0) {
13597 return PR_DECLINED(cmd);
13598 }
13599
13600 if (cmd->argc > 2) {
13601 int xerrno = EINVAL;
13602
13603 tls_log("denying malformed SSCN command: '%s %s'", (char *) cmd->argv[0],
13604 cmd->arg);
13605 pr_response_add_err(R_504, _("%s: %s"), (char *) cmd->argv[0],
13606 strerror(xerrno));
13607
13608 pr_cmd_set_errno(cmd, xerrno);
13609 errno = xerrno;
13610 return PR_ERROR(cmd);
13611 }
13612
13613 if (!dir_check(cmd->tmp_pool, cmd, cmd->group, session.cwd, NULL)) {
13614 int xerrno = EPERM;
13615
13616 pr_log_debug(DEBUG8, "%s %s denied by <Limit> configuration",
13617 (char *) cmd->argv[0], cmd->arg);
13618 tls_log("%s denied by <Limit> configuration", (char *) cmd->argv[0]);
13619 pr_response_add_err(R_550, _("%s: %s"), (char *) cmd->argv[0],
13620 strerror(xerrno));
13621
13622 pr_cmd_set_errno(cmd, xerrno);
13623 errno = xerrno;
13624 return PR_ERROR(cmd);
13625 }
13626
13627 if (cmd->argc == 1) {
13628 /* Client is querying our SSCN mode. */
13629 pr_response_add(R_200, "%s:%s METHOD", (char *) cmd->argv[0],
13630 tls_sscn_mode == TLS_SSCN_MODE_SERVER ? "SERVER" : "CLIENT");
13631
13632 } else {
13633 /* Parameter MUST be one of: "ON", "OFF. */
13634 if (strncmp(cmd->argv[1], "ON", 3) == 0) {
13635 tls_sscn_mode = TLS_SSCN_MODE_CLIENT;
13636 pr_response_add(R_200, "%s:CLIENT METHOD", (char *) cmd->argv[0]);
13637
13638 } else if (strncmp(cmd->argv[1], "OFF", 4) == 0) {
13639 tls_sscn_mode = TLS_SSCN_MODE_SERVER;
13640 pr_response_add(R_200, "%s:SERVER METHOD", (char *) cmd->argv[0]);
13641
13642 } else {
13643 int xerrno = EINVAL;
13644
13645 tls_log("denying unsupported SSCN command: '%s %s'",
13646 (char *) cmd->argv[0], (char *) cmd->argv[1]);
13647 pr_response_add_err(R_501, _("%s: %s"), (char *) cmd->argv[0],
13648 strerror(xerrno));
13649
13650 pr_cmd_set_errno(cmd, xerrno);
13651 errno = xerrno;
13652 return PR_ERROR(cmd);
13653 }
13654 }
13655
13656 return PR_HANDLED(cmd);
13657 }
13658
13659 /* Configuration handlers
13660 */
13661
13662 /* usage: TLSCACertificateFile file */
13663 MODRET set_tlscacertfile(cmd_rec *cmd) {
13664 int res;
13665 char *path;
13666 SSL_CTX *ctx;
13667
13668 CHECK_ARGS(cmd, 1);
13669 CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL);
13670
13671 path = cmd->argv[1];
13672
13673 PRIVS_ROOT
13674
13675 ctx = SSL_CTX_new(SSLv23_server_method());
13676 if (ctx != NULL) {
13677 res = SSL_CTX_load_verify_locations(ctx, path, NULL);
13678 if (res != 1) {
13679 unsigned long err_code;
13680 const char *err_msg;
13681
13682 PRIVS_RELINQUISH
13683
13684 /* Unfortunately, if the specified path exists but does not contain
13685 * any certificate data, the error queue is not helpful. Thanks,
13686 * OpenSSL. Thus we have to peek first.
13687 */
13688 err_code = ERR_peek_error();
13689 if (err_code != 0) {
13690 err_msg = tls_get_errors2(cmd->tmp_pool);
13691
13692 } else {
13693 err_msg = "file contained no certificate data";
13694 }
13695
13696 CONF_ERROR(cmd, pstrcat(cmd->tmp_pool,
13697 "unable to use '", path, "': ", err_msg, NULL));
13698 }
13699
13700 SSL_CTX_free(ctx);
13701
13702 } else {
13703 res = file_exists2(cmd->tmp_pool, path);
13704 if (res == FALSE) {
13705 PRIVS_RELINQUISH
13706 CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, "'", path, "' does not exist",
13707 NULL));
13708 }
13709 }
13710
13711 PRIVS_RELINQUISH
13712
13713 if (*path != '/') {
13714 CONF_ERROR(cmd, "parameter must be an absolute path");
13715 }
13716
13717 add_config_param_str(cmd->argv[0], 1, path);
13718 return PR_HANDLED(cmd);
13719 }
13720
13721 /* usage: TLSCACertificatePath path */
13722 MODRET set_tlscacertpath(cmd_rec *cmd) {
13723 int res;
13724 char *path;
13725
13726 CHECK_ARGS(cmd, 1);
13727 CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL);
13728
13729 path = cmd->argv[1];
13730
13731 PRIVS_ROOT
13732 res = dir_exists2(cmd->tmp_pool, path);
13733 PRIVS_RELINQUISH
13734
13735 if (res == FALSE) {
13736 CONF_ERROR(cmd, "parameter must be a directory path");
13737 }
13738
13739 if (*path != '/') {
13740 CONF_ERROR(cmd, "parameter must be an absolute path");
13741 }
13742
13743 add_config_param_str(cmd->argv[0], 1, path);
13744 return PR_HANDLED(cmd);
13745 }
13746
13747 /* usage: TLSCARevocationFile file */
13748 MODRET set_tlscacrlfile(cmd_rec *cmd) {
13749 int res;
13750 char *path;
13751 X509_STORE *store;
13752
13753 CHECK_ARGS(cmd, 1);
13754 CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL);
13755
13756 path = cmd->argv[1];
13757
13758 PRIVS_ROOT
13759
13760 store = X509_STORE_new();
13761 if (store != NULL) {
13762 res = X509_STORE_load_locations(store, path, NULL);
13763 if (res != 1) {
13764 unsigned long err_code;
13765 const char *err_msg;
13766
13767 PRIVS_RELINQUISH
13768
13769 /* Unfortunately, if the specified path exists but does not contain
13770 * any CRL data, the error queue is not helpful. Thanks, OpenSSL.
13771 * Thus we have to peek first.
13772 */
13773 err_code = ERR_peek_error();
13774 if (err_code != 0) {
13775 err_msg = tls_get_errors2(cmd->tmp_pool);
13776
13777 } else {
13778 err_msg = "file contained no CRL data";
13779 }
13780
13781 CONF_ERROR(cmd, pstrcat(cmd->tmp_pool,
13782 "unable to use '", path, "': ", err_msg, NULL));
13783 }
13784
13785 X509_STORE_free(store);
13786
13787 } else {
13788 res = file_exists2(cmd->tmp_pool, path);
13789 if (res == FALSE) {
13790 PRIVS_RELINQUISH
13791 CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, "'", path, "' does not exist",
13792 NULL));
13793 }
13794 }
13795
13796 PRIVS_RELINQUISH
13797
13798 if (*path != '/') {
13799 CONF_ERROR(cmd, "parameter must be an absolute path");
13800 }
13801
13802 add_config_param_str(cmd->argv[0], 1, path);
13803 return PR_HANDLED(cmd);
13804 }
13805
13806 /* usage: TLSCARevocationPath path */
13807 MODRET set_tlscacrlpath(cmd_rec *cmd) {
13808 int res;
13809 char *path;
13810
13811 CHECK_ARGS(cmd, 1);
13812 CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL);
13813
13814 path = cmd->argv[1];
13815
13816 PRIVS_ROOT
13817 res = dir_exists2(cmd->tmp_pool, path);
13818 PRIVS_RELINQUISH
13819
13820 if (!res) {
13821 CONF_ERROR(cmd, "parameter must be a directory path");
13822 }
13823
13824 if (*path != '/') {
13825 CONF_ERROR(cmd, "parameter must be an absolute path");
13826 }
13827
13828 add_config_param_str(cmd->argv[0], 1, path);
13829 return PR_HANDLED(cmd);
13830 }
13831
13832 /* usage: TLSCertificateChainFile file */
13833 MODRET set_tlscertchain(cmd_rec *cmd) {
13834 int res;
13835 char *path;
13836 SSL_CTX *ctx;
13837
13838 CHECK_ARGS(cmd, 1);
13839 CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL);
13840
13841 path = cmd->argv[1];
13842
13843 PRIVS_ROOT
13844
13845 ctx = SSL_CTX_new(SSLv23_server_method());
13846 if (ctx != NULL) {
13847 res = SSL_CTX_use_certificate_chain_file(ctx, path);
13848 if (res != 1) {
13849 unsigned long err_code;
13850 const char *err_msg;
13851
13852 PRIVS_RELINQUISH
13853
13854 /* Unfortunately, if the specified path exists but does not contain
13855 * any certificate data, the error queue is not helpful. Thanks,
13856 * OpenSSL. Thus we have to peek first.
13857 */
13858 err_code = ERR_peek_error();
13859 if (err_code != 0) {
13860 err_msg = tls_get_errors2(cmd->tmp_pool);
13861
13862 } else {
13863 err_msg = "file contained no certificate data";
13864 }
13865
13866 CONF_ERROR(cmd, pstrcat(cmd->tmp_pool,
13867 "unable to use '", path, "': ", err_msg, NULL));
13868 }
13869
13870 SSL_CTX_free(ctx);
13871
13872 } else {
13873 res = file_exists2(cmd->tmp_pool, path);
13874 if (res == FALSE) {
13875 PRIVS_RELINQUISH
13876 CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, "'", path, "' does not exist",
13877 NULL));
13878 }
13879 }
13880
13881 PRIVS_RELINQUISH
13882
13883 if (*path != '/') {
13884 CONF_ERROR(cmd, "parameter must be an absolute path");
13885 }
13886
13887 add_config_param_str(cmd->argv[0], 1, path);
13888 return PR_HANDLED(cmd);
13889 }
13890
13891 /* usage: TLSCipherSuite [protocol] string */
13892 MODRET set_tlsciphersuite(cmd_rec *cmd) {
13893 config_rec *c = NULL;
13894 char *ciphersuite = NULL;
13895 int protocol = 0;
13896 SSL_CTX *ctx;
13897
13898 CHECK_ARGS(cmd, 1);
13899 CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL);
13900
13901 if (cmd->argc-1 == 1) {
13902 ciphersuite = cmd->argv[1];
13903
13904 /* Currently, OpenSSL ciphersuite names for TLSv1.3 all use underscores;
13905 * ciphersuite names for TLSv1.2 and older do NOT use underscores.
13906 *
13907 * So if we see an underscore in the configured ciphersuites here, we
13908 * know that the optional protocol parameter has NOT been used, and that
13909 * a TLSv1.3 ciphersuite is being configured -- and that this situation
13910 * will be silently ignored by OpenSSL.
13911 */
13912 if (strchr(ciphersuite, '_') != NULL) {
13913 CONF_ERROR(cmd, pstrcat(cmd->tmp_pool,
13914 "use of TLSv1.3 ciphersuite in '", ciphersuite,
13915 "' requires protocol parameter; use 'TLSCipherSuite TLSv1.3 ",
13916 ciphersuite, "'", NULL));
13917 }
13918
13919 } else if (cmd->argc-1 == 2) {
13920 char *protocol_text;
13921
13922 protocol_text = cmd->argv[1];
13923 if (strcasecmp(protocol_text, "TLSv1.3") == 0) {
13924 protocol = TLS_PROTO_TLS_V1_3;
13925
13926 } else if (strcasecmp(protocol_text, "TLSv1.2") == 0) {
13927 protocol = TLS_PROTO_TLS_V1_2;
13928
13929 } else if (strcasecmp(protocol_text, "TLSv1.1") == 0) {
13930 protocol = TLS_PROTO_TLS_V1_1;
13931
13932 } else if (strcasecmp(protocol_text, "TLSv1.0") == 0) {
13933 protocol = TLS_PROTO_TLS_V1;
13934
13935 } else {
13936 CONF_ERROR(cmd, pstrcat(cmd->tmp_pool,
13937 "unknown/unsupported protocol specifier: ", protocol_text, NULL));
13938 }
13939
13940 ciphersuite = cmd->argv[2];
13941 }
13942
13943 c = add_config_param(cmd->argv[0], 2, NULL, NULL);
13944
13945 if (protocol == TLS_PROTO_TLS_V1_3) {
13946 ciphersuite = pstrdup(c->pool, ciphersuite);
13947
13948 } else {
13949 /* Make sure that EXPORT ciphers cannot be used, per Bug#4163. Note that
13950 * this breaks system profiles, so handle them specially.
13951 */
13952 if (strncmp(ciphersuite, "PROFILE=", 8) == 0) {
13953 ciphersuite = pstrdup(c->pool, ciphersuite);
13954
13955 } else {
13956 ciphersuite = pstrcat(c->pool, ciphersuite, ":!EXPORT", NULL);
13957 }
13958 }
13959
13960 /* Check that our construct ciphersuite is acceptable. */
13961 ctx = SSL_CTX_new(SSLv23_server_method());
13962 if (ctx != NULL) {
13963 int res = 1;
13964
13965 if (protocol == TLS_PROTO_TLS_V1_3) {
13966 #if OPENSSL_VERSION_NUMBER >= 0x10101000L && \
13967 defined(TLS1_3_VERSION)
13968 res = SSL_CTX_set_ciphersuites(ctx, ciphersuite);
13969 #endif /* TLS1_3_VERSION */
13970
13971 } else {
13972 res = SSL_CTX_set_cipher_list(ctx, ciphersuite);
13973 }
13974
13975 if (res != 1) {
13976 CONF_ERROR(cmd, pstrcat(cmd->tmp_pool,
13977 "unable to use ciphersuite '", ciphersuite, "': ",
13978 tls_get_errors2(cmd->tmp_pool), NULL));
13979 }
13980
13981 SSL_CTX_free(ctx);
13982 }
13983
13984 c->argv[0] = ciphersuite;
13985 c->argv[1] = palloc(c->pool, sizeof(int));
13986 *((int *) c->argv[1]) = protocol;
13987
13988 if (pr_module_exists("mod_ifsession.c")) {
13989 /* These are needed in case this directive is used with mod_ifsession
13990 * configuration.
13991 */
13992 c->flags |= CF_MULTI;
13993 }
13994
13995 return PR_HANDLED(cmd);
13996 }
13997
13998 /* usage: TLSControlsACLs actions|all allow|deny user|group list */
13999 MODRET set_tlsctrlsacls(cmd_rec *cmd) {
14000 #if defined(PR_USE_CTRLS)
14001 char *bad_action = NULL, **actions = NULL;
14002
14003 CHECK_ARGS(cmd, 4);
14004 CHECK_CONF(cmd, CONF_ROOT);
14005
14006 actions = pr_ctrls_parse_acl(cmd->tmp_pool, cmd->argv[1]);
14007
14008 /* Check the second parameter to make sure it is "allow" or "deny" */
14009 if (strcmp(cmd->argv[2], "allow") != 0 &&
14010 strcmp(cmd->argv[2], "deny") != 0) {
14011 CONF_ERROR(cmd, "second parameter must be 'allow' or 'deny'");
14012 }
14013
14014 /* Check the third parameter to make sure it is "user" or "group" */
14015 if (strcmp(cmd->argv[3], "user") != 0 &&
14016 strcmp(cmd->argv[3], "group") != 0) {
14017 CONF_ERROR(cmd, "third parameter must be 'user' or 'group'");
14018 }
14019
14020 bad_action = pr_ctrls_set_module_acls(tls_acttab, tls_act_pool, actions,
14021 cmd->argv[2], cmd->argv[3], cmd->argv[4]);
14022 if (bad_action != NULL) {
14023 CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, ": unknown action: '",
14024 bad_action, "'", NULL));
14025 }
14026
14027 return PR_HANDLED(cmd);
14028 #else
14029 CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, "The ", cmd->argv[0],
14030 " directive requires Controls support (--enable-ctrls)", NULL));
14031 #endif /* PR_USE_CTRLS */
14032 }
14033
14034 /* usage: TLSCryptoDevice driver|"ALL" */
14035 MODRET set_tlscryptodevice(cmd_rec *cmd) {
14036 #if OPENSSL_VERSION_NUMBER > 0x000907000L
14037 CHECK_ARGS(cmd, 1);
14038 CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL);
14039
14040 (void) add_config_param_str(cmd->argv[0], 1, cmd->argv[1]);
14041
14042 return PR_HANDLED(cmd);
14043
14044 #else /* OpenSSL is too old for ENGINE support */
14045 CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, "The ", cmd->argv[0],
14046 "directive cannot be used on the system, as the OpenSSL version is too old",
14047 NULL));
14048 #endif
14049 }
14050
14051 /* usage: TLSDHParamFile file */
14052 MODRET set_tlsdhparamfile(cmd_rec *cmd) {
14053 int res;
14054 char *path;
14055
14056 CHECK_ARGS(cmd, 1);
14057 CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL);
14058
14059 path = cmd->argv[1];
14060
14061 PRIVS_ROOT
14062 res = file_exists2(cmd->tmp_pool, path);
14063 PRIVS_RELINQUISH
14064
14065 if (res == FALSE) {
14066 CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, "'", path, "' does not exist",
14067 NULL));
14068 }
14069
14070 if (*path != '/') {
14071 CONF_ERROR(cmd, "parameter must be an absolute path");
14072 }
14073
14074 add_config_param_str(cmd->argv[0], 1, path);
14075 return PR_HANDLED(cmd);
14076 }
14077
14078 /* usage: TLSDSACertificateFile file */
14079 MODRET set_tlsdsacertfile(cmd_rec *cmd) {
14080 char *path;
14081 const char *fingerprint, *errstr = NULL;
14082
14083 CHECK_ARGS(cmd, 1);
14084 CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL);
14085
14086 path = cmd->argv[1];
14087 if (*path != '/') {
14088 CONF_ERROR(cmd, "parameter must be an absolute path");
14089 }
14090
14091 PRIVS_ROOT
14092 fingerprint = tls_get_fingerprint_from_file(cmd->tmp_pool, path, EVP_PKEY_DSA,
14093 &errstr);
14094 PRIVS_RELINQUISH
14095
14096 if (fingerprint == NULL) {
14097 if (errstr == NULL) {
14098 errstr = "does not exist or does not contain a certificate";
14099 }
14100
14101 CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, "unable to use '", path, "': ",
14102 errstr, NULL));
14103 }
14104
14105 add_config_param_str(cmd->argv[0], 2, path, fingerprint);
14106 return PR_HANDLED(cmd);
14107 }
14108
14109 /* usage: TLSDSACertificateKeyFile file */
14110 MODRET set_tlsdsakeyfile(cmd_rec *cmd) {
14111 int res;
14112 char *path;
14113 SSL_CTX *ctx;
14114
14115 CHECK_ARGS(cmd, 1);
14116 CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL);
14117
14118 path = cmd->argv[1];
14119
14120 PRIVS_ROOT
14121
14122 ctx = SSL_CTX_new(SSLv23_server_method());
14123 if (ctx != NULL) {
14124 /* Note that the configured key file might be passphrase-protected. We
14125 * do not necessarily want to prompt for the passphrase here, so if that
14126 * is the error returned, it is an expected condition, and indicates that
14127 * the encoding of the key is acceptable.
14128 */
14129 SSL_CTX_set_default_passwd_cb(ctx, tls_keyfile_check_cb);
14130
14131 res = SSL_CTX_use_PrivateKey_file(ctx, path, X509_FILETYPE_PEM);
14132 if (res != 1) {
14133 unsigned long err_code;
14134
14135 err_code = ERR_peek_error();
14136 switch (ERR_GET_REASON(err_code)) {
14137 /* These are "expected" error codes from working with
14138 * passphrase-protected keys.
14139 */
14140 case EVP_R_BAD_DECRYPT:
14141 case PEM_R_BAD_PASSWORD_READ:
14142 break;
14143
14144 default: {
14145 PRIVS_RELINQUISH
14146
14147 CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, "unable to use '", path, "': ",
14148 tls_get_errors2(cmd->tmp_pool), NULL));
14149 }
14150 }
14151 }
14152
14153 SSL_CTX_free(ctx);
14154
14155 } else {
14156 res = file_exists2(cmd->tmp_pool, path);
14157 if (res == FALSE) {
14158 PRIVS_RELINQUISH
14159 CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, "'", path, "' does not exist",
14160 NULL));
14161 }
14162 }
14163
14164 PRIVS_RELINQUISH
14165
14166 if (*path != '/') {
14167 CONF_ERROR(cmd, "parameter must be an absolute path");
14168 }
14169
14170 add_config_param_str(cmd->argv[0], 1, path);
14171 return PR_HANDLED(cmd);
14172 }
14173
14174 /* usage: TLSECCertificateFile file */
14175 MODRET set_tlseccertfile(cmd_rec *cmd) {
14176 #ifdef PR_USE_OPENSSL_ECC
14177 char *path;
14178 const char *fingerprint, *errstr = NULL;
14179
14180 CHECK_ARGS(cmd, 1);
14181 CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL);
14182
14183 path = cmd->argv[1];
14184 if (*path != '/') {
14185 CONF_ERROR(cmd, "parameter must be an absolute path");
14186 }
14187
14188 PRIVS_ROOT
14189 fingerprint = tls_get_fingerprint_from_file(cmd->tmp_pool, path, EVP_PKEY_EC,
14190 &errstr);
14191 PRIVS_RELINQUISH
14192
14193 if (fingerprint == NULL) {
14194 CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, "'", path,
14195 "' does not exist or does not contain a certificate", NULL));
14196 }
14197
14198 add_config_param_str(cmd->argv[0], 2, path, fingerprint);
14199 return PR_HANDLED(cmd);
14200 #else
14201 CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, "The ", (char *) cmd->argv[0],
14202 " directive cannot be used on this system, as your OpenSSL version "
14203 "does not have EC support", NULL));
14204 #endif /* PR_USE_OPENSSL_ECC */
14205 }
14206
14207 /* usage: TLSECCertificateKeyFile file */
14208 MODRET set_tlseckeyfile(cmd_rec *cmd) {
14209 #ifdef PR_USE_OPENSSL_ECC
14210 int res;
14211 char *path;
14212 SSL_CTX *ctx;
14213
14214 CHECK_ARGS(cmd, 1);
14215 CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL);
14216
14217 path = cmd->argv[1];
14218
14219 PRIVS_ROOT
14220
14221 ctx = SSL_CTX_new(SSLv23_server_method());
14222 if (ctx != NULL) {
14223 /* Note that the configured key file might be passphrase-protected. We
14224 * do not necessarily want to prompt for the passphrase here, so if that
14225 * is the error returned, it is an expected condition, and indicates that
14226 * the encoding of the key is acceptable.
14227 */
14228 SSL_CTX_set_default_passwd_cb(ctx, tls_keyfile_check_cb);
14229
14230 res = SSL_CTX_use_PrivateKey_file(ctx, path, X509_FILETYPE_PEM);
14231 if (res != 1) {
14232 unsigned long err_code;
14233
14234 err_code = ERR_peek_error();
14235 switch (ERR_GET_REASON(err_code)) {
14236 /* These are "expected" error codes from working with
14237 * passphrase-protected keys.
14238 */
14239 case EVP_R_BAD_DECRYPT:
14240 case PEM_R_BAD_PASSWORD_READ:
14241 break;
14242
14243 default: {
14244 PRIVS_RELINQUISH
14245
14246 CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, "unable to use '", path, "': ",
14247 tls_get_errors2(cmd->tmp_pool), NULL));
14248 }
14249 }
14250 }
14251
14252 SSL_CTX_free(ctx);
14253
14254 } else {
14255 res = file_exists2(cmd->tmp_pool, path);
14256 if (res == FALSE) {
14257 PRIVS_RELINQUISH
14258 CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, "'", path, "' does not exist",
14259 NULL));
14260 }
14261 }
14262
14263 PRIVS_RELINQUISH
14264
14265 if (*path != '/') {
14266 CONF_ERROR(cmd, "parameter must be an absolute path");
14267 }
14268
14269 add_config_param_str(cmd->argv[0], 1, path);
14270 return PR_HANDLED(cmd);
14271 #else
14272 CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, "The ", (char *) cmd->argv[0],
14273 " directive cannot be used on this system, as your OpenSSL version "
14274 "does not have EC support", NULL));
14275 #endif /* PR_USE_OPENSSL_ECC */
14276 }
14277
14278 /* usage: TLSECDHCurve name */
14279 MODRET set_tlsecdhcurve(cmd_rec *cmd) {
14280 #ifdef PR_USE_OPENSSL_ECC
14281 char *curve_names = NULL;
14282 # if defined(SSL_CTX_set1_curves_list)
14283 SSL_CTX *ctx = NULL;
14284 # else
14285 int curve_nid = -1;
14286 EC_KEY *ec_key = NULL;
14287 # endif /* No SSL_CTX_set1_curves_list; pre-OpenSSL 1.0.2 */
14288
14289 CHECK_ARGS(cmd, 1);
14290 CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL);
14291
14292 curve_names = cmd->argv[1];
14293
14294 # if defined(SSL_CTX_set1_curves_list)
14295 if (strcasecmp(curve_names, "auto") != 0) {
14296 ctx = SSL_CTX_new(SSLv23_server_method());
14297 }
14298
14299 if (ctx != NULL) {
14300 int res;
14301
14302 res = SSL_CTX_set1_curves_list(ctx, curve_names);
14303 if (res != 1) {
14304 CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, "unable to use ECDH curves '",
14305 curve_names, "': ", tls_get_errors2(cmd->tmp_pool), NULL));
14306 }
14307
14308 SSL_CTX_free(ctx);
14309 }
14310
14311 (void) add_config_param_str(cmd->argv[0], 1, curve_names);
14312
14313 # else
14314 /* The special-case handling of these curve names is copied from OpenSSL's
14315 * apps/ecparam.c code.
14316 */
14317
14318 if (strcmp(curve_names, "secp192r1") == 0) {
14319 curve_nid = NID_X9_62_prime192v1;
14320
14321 } else if (strcmp(curve_names, "secp256r1") == 0) {
14322 curve_nid = NID_X9_62_prime256v1;
14323
14324 } else {
14325 curve_nid = OBJ_sn2nid(curve_names);
14326 }
14327
14328 ec_key = EC_KEY_new_by_curve_name(curve_nid);
14329 if (ec_key == NULL) {
14330 char *err_str = "unknown/unsupported curve";
14331
14332 if (curve_nid > 0) {
14333 err_str = ERR_error_string(ERR_get_error(), NULL);
14334 }
14335
14336 if (strchr(curve_names, ':') != NULL) {
14337 CONF_ERROR(cmd, pstrcat(cmd->tmp_pool,
14338 "configuring multiple curves '", curve_names,
14339 "' not supported by OpenSSL version ", OPENSSL_VERSION_TEXT, NULL));
14340
14341 } else {
14342 CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, "unable to create '", curve_names,
14343 "' EC curve: ", err_str, NULL));
14344 }
14345 }
14346
14347 (void) add_config_param(cmd->argv[0], 1, ec_key);
14348 # endif /* pre-OpenSSL-1.0.2 */
14349
14350 return PR_HANDLED(cmd);
14351
14352 #else
14353 CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, "The ", cmd->argv[0],
14354 " directive cannot be used on this system, as your OpenSSL version "
14355 "does not have EC support", NULL));
14356 #endif /* PR_USE_OPENSSL_ECC */
14357 }
14358
14359 /* usage: TLSEngine on|off */
14360 MODRET set_tlsengine(cmd_rec *cmd) {
14361 int engine = -1;
14362 config_rec *c = NULL;
14363
14364 CHECK_ARGS(cmd, 1);
14365 CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL);
14366
14367 engine = get_boolean(cmd, 1);
14368 if (engine == -1) {
14369 CONF_ERROR(cmd, "expected Boolean parameter");
14370 }
14371
14372 c = add_config_param(cmd->argv[0], 1, NULL);
14373 c->argv[0] = pcalloc(c->pool, sizeof(unsigned char));
14374 *((unsigned char *) c->argv[0]) = engine;
14375
14376 return PR_HANDLED(cmd);
14377 }
14378
14379 /* usage: TLSLog file */
14380 MODRET set_tlslog(cmd_rec *cmd) {
14381 CHECK_ARGS(cmd, 1);
14382 CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL);
14383
14384 add_config_param_str(cmd->argv[0], 1, cmd->argv[1]);
14385 return PR_HANDLED(cmd);
14386 }
14387
14388 /* usage: TLSMasqueradeAddress ip-addr|dns-name */
14389 MODRET set_tlsmasqaddr(cmd_rec *cmd) {
14390 config_rec *c = NULL;
14391 const pr_netaddr_t *masq_addr = NULL;
14392 unsigned int addr_flags = PR_NETADDR_GET_ADDR_FL_INCL_DEVICE;
14393
14394 CHECK_ARGS(cmd, 1);
14395 CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL);
14396
14397 /* We can only masquerade as one address, so we don't need to know if the
14398 * given name might map to multiple addresses.
14399 */
14400 masq_addr = pr_netaddr_get_addr2(cmd->server->pool, cmd->argv[1], NULL,
14401 addr_flags);
14402 if (masq_addr == NULL) {
14403 return PR_ERROR_MSG(cmd, NULL, pstrcat(cmd->tmp_pool, cmd->argv[0],
14404 ": unable to resolve \"", cmd->argv[1], "\"", NULL));
14405 }
14406
14407 c = add_config_param(cmd->argv[0], 2, (void *) masq_addr, NULL);
14408 c->argv[1] = pstrdup(c->pool, cmd->argv[1]);
14409
14410 return PR_HANDLED(cmd);
14411 }
14412
14413 /* usage: TLSNextProtocol on|off */
14414 MODRET set_tlsnextprotocol(cmd_rec *cmd) {
14415 #if !defined(OPENSSL_NO_TLSEXT)
14416 config_rec *c;
14417 int use_next_protocol = FALSE;
14418
14419 CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL);
14420 CHECK_ARGS(cmd, 1);
14421
14422 use_next_protocol = get_boolean(cmd, 1);
14423 if (use_next_protocol == -1) {
14424 CONF_ERROR(cmd, "expected Boolean parameter");
14425 }
14426
14427 c = add_config_param(cmd->argv[0], 1, NULL);
14428 c->argv[0] = palloc(c->pool, sizeof(int));
14429 *((int *) c->argv[0]) = use_next_protocol;
14430 return PR_HANDLED(cmd);
14431
14432 #else
14433 CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, "The ", cmd->argv[0],
14434 " directive cannot be used on this system, as your OpenSSL version "
14435 "does not have NPN/ALPN support", NULL));
14436 #endif /* !OPENSSL_NO_TLSEXT */
14437 }
14438
14439 /* usage: TLSOptions opt1 opt2 ... */
14440 MODRET set_tlsoptions(cmd_rec *cmd) {
14441 config_rec *c = NULL;
14442 register unsigned int i = 0;
14443 unsigned long opts = 0UL;
14444
14445 if (cmd->argc-1 == 0) {
14446 CONF_ERROR(cmd, "wrong number of parameters");
14447 }
14448
14449 CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL);
14450
14451 c = add_config_param(cmd->argv[0], 1, NULL);
14452
14453 for (i = 1; i < cmd->argc; i++) {
14454 if (strcmp(cmd->argv[i], "AllowDotLogin") == 0) {
14455 opts |= TLS_OPT_ALLOW_DOT_LOGIN;
14456
14457 } else if (strcmp(cmd->argv[i], "AllowPerUser") == 0) {
14458 opts |= TLS_OPT_ALLOW_PER_USER;
14459
14460 } else if (strcmp(cmd->argv[i], "AllowWeakDH") == 0) {
14461 opts |= TLS_OPT_ALLOW_WEAK_DH;
14462
14463 } else if (strcmp(cmd->argv[i], "AllowWeakSecurity") == 0) {
14464 #if OPENSSL_VERSION_NUMBER >= 0x10100000L
14465 opts |= TLS_OPT_ALLOW_WEAK_SECURITY;
14466 #else
14467 CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, "The ", cmd->argv[i],
14468 " option cannot be used on this system, as your OpenSSL version "
14469 "is too old; requires OpenSSL-1.1.0 or later", NULL));
14470 #endif /* OpenSSL-1.1.0 and later */
14471
14472 } else if (strcmp(cmd->argv[i], "AllowClientRenegotiation") == 0 ||
14473 strcmp(cmd->argv[i], "AllowClientRenegotiations") == 0) {
14474 opts |= TLS_OPT_ALLOW_CLIENT_RENEGOTIATIONS;
14475
14476 } else if (strcmp(cmd->argv[i], "EnableDiags") == 0) {
14477 opts |= TLS_OPT_ENABLE_DIAGS;
14478
14479 } else if (strcmp(cmd->argv[i], "ExportCertData") == 0) {
14480 opts |= TLS_OPT_EXPORT_CERT_DATA;
14481
14482 } else if (strcmp(cmd->argv[i], "IgnoreSNI") == 0) {
14483 opts |= TLS_OPT_IGNORE_SNI;
14484
14485 #ifdef SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS
14486 } else if (strcmp(cmd->argv[i], "NoEmptyFragments") == 0) {
14487 /* Unlike the other TLSOptions, this option is handled slightly
14488 * differently, due to the fact that option affects the creation
14489 * of the SSL_CTX.
14490 *
14491 */
14492 tls_ssl_opts |= SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS;
14493 #else
14494 pr_log_pri(PR_LOG_NOTICE, MOD_TLS_VERSION ": TLSOption NoEmptyFragments not supported (OpenSSL version is too old)");
14495 #endif
14496
14497 } else if (strcmp(cmd->argv[i], "NoSessionReuseRequired") == 0) {
14498 opts |= TLS_OPT_NO_SESSION_REUSE_REQUIRED;
14499
14500 } else if (strcmp(cmd->argv[i], "StdEnvVars") == 0) {
14501 opts |= TLS_OPT_STD_ENV_VARS;
14502
14503 } else if (strcmp(cmd->argv[i], "dNSNameRequired") == 0) {
14504 opts |= TLS_OPT_VERIFY_CERT_FQDN;
14505
14506 } else if (strcmp(cmd->argv[i], "iPAddressRequired") == 0) {
14507 opts |= TLS_OPT_VERIFY_CERT_IP_ADDR;
14508
14509 } else if (strcmp(cmd->argv[i], "UseImplicitSSL") == 0) {
14510 opts |= TLS_OPT_USE_IMPLICIT_SSL;
14511
14512 } else if (strcmp(cmd->argv[i], "CommonNameRequired") == 0) {
14513 opts |= TLS_OPT_VERIFY_CERT_CN;
14514
14515 } else if (strcmp(cmd->argv[i], "NoAutoECDH") == 0) {
14516 opts |= TLS_OPT_NO_AUTO_ECDH;
14517
14518 } else {
14519 CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, ": unknown TLSOption '",
14520 cmd->argv[i], "'", NULL));
14521 }
14522 }
14523
14524 c->argv[0] = pcalloc(c->pool, sizeof(unsigned long));
14525 *((unsigned long *) c->argv[0]) = opts;
14526
14527 if (pr_module_exists("mod_ifsession.c")) {
14528 /* These are needed in case this directive is used with mod_ifsession
14529 * configuration.
14530 */
14531 c->flags |= CF_MULTI;
14532 }
14533
14534 return PR_HANDLED(cmd);
14535 }
14536
14537 /* usage: TLSPassPhraseProvider path */
14538 MODRET set_tlspassphraseprovider(cmd_rec *cmd) {
14539 struct stat st;
14540 char *path;
14541
14542 CHECK_ARGS(cmd, 1);
14543 CHECK_CONF(cmd, CONF_ROOT);
14544
14545 path = cmd->argv[1];
14546
14547 if (*path != '/') {
14548 CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, "must be a full path: '", path, "'",
14549 NULL));
14550 }
14551
14552 if (stat(path, &st) < 0) {
14553 CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, "error checking '", path, "': ",
14554 strerror(errno), NULL));
14555 }
14556
14557 if (!S_ISREG(st.st_mode)) {
14558 CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, "unable to use '", path,
14559 ": Not a regular file", NULL));
14560 }
14561
14562 tls_passphrase_provider = pstrdup(permanent_pool, path);
14563 return PR_HANDLED(cmd);
14564 }
14565
14566 /* usage: TLSPKCS12File file */
14567 MODRET set_tlspkcs12file(cmd_rec *cmd) {
14568 int res;
14569 char *path;
14570
14571 CHECK_ARGS(cmd, 1);
14572 CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL);
14573
14574 path = cmd->argv[1];
14575
14576 PRIVS_ROOT
14577 res = file_exists2(cmd->tmp_pool, path);
14578 PRIVS_RELINQUISH
14579
14580 if (!res) {
14581 CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, "'", path, "' does not exist",
14582 NULL));
14583 }
14584
14585 if (*path != '/') {
14586 CONF_ERROR(cmd, "parameter must be an absolute path");
14587 }
14588
14589 add_config_param_str(cmd->argv[0], 1, path);
14590 return PR_HANDLED(cmd);
14591 }
14592
14593 /* usage: TLSPreSharedKey name path */
14594 MODRET set_tlspresharedkey(cmd_rec *cmd) {
14595 #if defined(PSK_MAX_PSK_LEN)
14596 char *identity, *path;
14597 size_t identity_len, path_len;
14598
14599 CHECK_ARGS(cmd, 2);
14600 CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL);
14601
14602 identity = cmd->argv[1];
14603 path = cmd->argv[2];
14604
14605 identity_len = strlen(identity);
14606 if (identity_len > PSK_MAX_IDENTITY_LEN) {
14607 char buf[32];
14608
14609 memset(buf, '\0', sizeof(buf));
14610 pr_snprintf(buf, sizeof(buf)-1, "%u", (unsigned int) PSK_MAX_IDENTITY_LEN);
14611
14612 CONF_ERROR(cmd, pstrcat(cmd->tmp_pool,
14613 "TLSPreSharedKey identity '", identity, "' exceed maximum length ",
14614 buf, path, NULL))
14615 }
14616
14617 /* Ensure that the given path starts with "hex:", denoting the
14618 * format of the key at the given path. Support for other formats, e.g.
14619 * bcrypt or somesuch, will be added later.
14620 */
14621 path_len = strlen(path);
14622 if (path_len < 5 ||
14623 strncmp(path, "hex:", 4) != 0) {
14624 CONF_ERROR(cmd, pstrcat(cmd->tmp_pool,
14625 "unsupported TLSPreSharedKey format: ", path, NULL))
14626 }
14627
14628 (void) add_config_param_str(cmd->argv[0], 2, identity, path);
14629 #else
14630 pr_log_debug(DEBUG0,
14631 "%s is not supported by this build/version of OpenSSL, ignoring",
14632 (char *) cmd->argv[0]);
14633 #endif /* PSK_MAX_PSK_LEN */
14634
14635 return PR_HANDLED(cmd);
14636 }
14637
14638 /* usage: TLSProtocol version1 ... versionN */
14639 MODRET set_tlsprotocol(cmd_rec *cmd) {
14640 register unsigned int i;
14641 config_rec *c;
14642 unsigned int protocols = 0;
14643
14644 if (cmd->argc-1 == 0) {
14645 CONF_ERROR(cmd, "wrong number of parameters");
14646 }
14647
14648 CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL);
14649
14650 if (strcasecmp(cmd->argv[1], "all") == 0) {
14651 /* We're in an additive/subtractive type of configuration. */
14652 protocols = TLS_PROTO_ALL;
14653
14654 for (i = 2; i < cmd->argc; i++) {
14655 int disable = FALSE;
14656 char *proto_name;
14657
14658 proto_name = cmd->argv[i];
14659
14660 if (*proto_name == '+') {
14661 proto_name++;
14662
14663 } else if (*proto_name == '-') {
14664 disable = TRUE;
14665 proto_name++;
14666
14667 } else {
14668 /* Using the additive/subtractive approach requires a +/- prefix;
14669 * it's malformed without such prefaces.
14670 */
14671 CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, "missing required +/- prefix: ",
14672 proto_name, NULL));
14673 }
14674
14675 if (strncasecmp(proto_name, "SSLv3", 6) == 0) {
14676 if (disable) {
14677 protocols &= ~TLS_PROTO_SSL_V3;
14678 } else {
14679 protocols |= TLS_PROTO_SSL_V3;
14680 }
14681
14682 } else if (strncasecmp(proto_name, "TLSv1", 6) == 0 ||
14683 strncasecmp(proto_name, "TLSv1.0", 8) == 0) {
14684 if (disable) {
14685 protocols &= ~TLS_PROTO_TLS_V1;
14686 } else {
14687 protocols |= TLS_PROTO_TLS_V1;
14688 }
14689
14690 } else if (strncasecmp(proto_name, "TLSv1.1", 8) == 0) {
14691 #if OPENSSL_VERSION_NUMBER >= 0x10001000L
14692 if (disable) {
14693 protocols &= ~TLS_PROTO_TLS_V1_1;
14694 } else {
14695 protocols |= TLS_PROTO_TLS_V1_1;
14696 }
14697 #else
14698 CONF_ERROR(cmd, "Your OpenSSL installation does not support TLSv1.1");
14699 #endif /* OpenSSL 1.0.1 or later */
14700
14701 } else if (strncasecmp(proto_name, "TLSv1.2", 8) == 0) {
14702 #if OPENSSL_VERSION_NUMBER >= 0x10001000L
14703 if (disable) {
14704 protocols &= ~TLS_PROTO_TLS_V1_2;
14705 } else {
14706 protocols |= TLS_PROTO_TLS_V1_2;
14707 }
14708 #else
14709 CONF_ERROR(cmd, "Your OpenSSL installation does not support TLSv1.2");
14710 #endif /* OpenSSL 1.0.1 or later */
14711
14712 } else if (strncasecmp(proto_name, "TLSv1.3", 8) == 0) {
14713 #ifdef TLS1_3_VERSION
14714 if (disable) {
14715 protocols &= ~TLS_PROTO_TLS_V1_3;
14716 } else {
14717 protocols |= TLS_PROTO_TLS_V1_3;
14718 }
14719 #else
14720 CONF_ERROR(cmd, "Your OpenSSL installation does not support TLSv1.3");
14721 #endif /* OpenSSL 1.1.1 or later */
14722
14723 } else {
14724 CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, "unknown protocol: '",
14725 cmd->argv[i], "'", NULL));
14726 }
14727 }
14728
14729 } else {
14730 for (i = 1; i < cmd->argc; i++) {
14731 if (strncasecmp(cmd->argv[i], "SSLv23", 7) == 0) {
14732 protocols |= TLS_PROTO_SSL_V3;
14733 protocols |= TLS_PROTO_TLS_V1;
14734 #ifdef SSL_OP_NO_TLSv1_1
14735 protocols |= TLS_PROTO_TLS_V1_1;
14736 #endif
14737 #ifdef SSL_OP_NO_TLSv1_2
14738 protocols |= TLS_PROTO_TLS_V1_2;
14739 #endif
14740 #ifdef SSL_OP_NO_TLSv1_3
14741 protocols |= TLS_PROTO_TLS_V1_3;
14742 #endif
14743
14744 } else if (strncasecmp(cmd->argv[i], "SSLv3", 6) == 0) {
14745 protocols |= TLS_PROTO_SSL_V3;
14746
14747 } else if (strncasecmp(cmd->argv[i], "TLSv1", 6) == 0 ||
14748 strncasecmp(cmd->argv[i], "TLSv1.0", 8) == 0) {
14749 protocols |= TLS_PROTO_TLS_V1;
14750
14751 } else if (strncasecmp(cmd->argv[i], "TLSv1.1", 8) == 0) {
14752 #if OPENSSL_VERSION_NUMBER >= 0x10001000L
14753 protocols |= TLS_PROTO_TLS_V1_1;
14754 #else
14755 CONF_ERROR(cmd, "Your OpenSSL installation does not support TLSv1.1");
14756 #endif /* OpenSSL 1.0.1 or later */
14757
14758 } else if (strncasecmp(cmd->argv[i], "TLSv1.2", 8) == 0) {
14759 #if OPENSSL_VERSION_NUMBER >= 0x10001000L
14760 protocols |= TLS_PROTO_TLS_V1_2;
14761 #else
14762 CONF_ERROR(cmd, "Your OpenSSL installation does not support TLSv1.2");
14763 #endif /* OpenSSL 1.0.1 or later */
14764
14765 } else if (strncasecmp(cmd->argv[i], "TLSv1.3", 8) == 0) {
14766 #ifdef TLS1_3_VERSION
14767 protocols |= TLS_PROTO_TLS_V1_3;
14768 #else
14769 CONF_ERROR(cmd, "Your OpenSSL installation does not support TLSv1.3");
14770 #endif /* OpenSSL 1.1.1 or later */
14771
14772 } else {
14773 CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, "unknown protocol: '",
14774 cmd->argv[i], "'", NULL));
14775 }
14776 }
14777 }
14778
14779 c = add_config_param(cmd->argv[0], 1, NULL);
14780 c->argv[0] = palloc(c->pool, sizeof(unsigned int));
14781 *((unsigned int *) c->argv[0]) = protocols;
14782
14783 return PR_HANDLED(cmd);
14784 }
14785
14786 /* usage: TLSRandomSeed file */
14787 MODRET set_tlsrandseed(cmd_rec *cmd) {
14788 CHECK_ARGS(cmd, 1);
14789 CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL);
14790
14791 add_config_param_str(cmd->argv[0], 1, cmd->argv[1]);
14792 return PR_HANDLED(cmd);
14793 }
14794
14795 /* usage: TLSRenegotiate [ctrl nsecs] [data nbytes] */
14796 MODRET set_tlsrenegotiate(cmd_rec *cmd) {
14797 #if OPENSSL_VERSION_NUMBER > 0x000907000L
14798 register unsigned int i = 0;
14799 config_rec *c = NULL;
14800
14801 if (cmd->argc-1 < 1 ||
14802 cmd->argc-1 > 8) {
14803 CONF_ERROR(cmd, "wrong number of parameters");
14804 }
14805
14806 CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL);
14807
14808 if (strncasecmp(cmd->argv[1], "none", 5) == 0) {
14809 add_config_param(cmd->argv[0], 0);
14810 return PR_HANDLED(cmd);
14811 }
14812
14813 c = add_config_param(cmd->argv[0], 4, NULL, NULL, NULL, NULL);
14814 c->argv[0] = pcalloc(c->pool, sizeof(int));
14815 *((int *) c->argv[0]) = 0;
14816 c->argv[1] = pcalloc(c->pool, sizeof(off_t));
14817 *((off_t *) c->argv[1]) = 0;
14818 c->argv[2] = pcalloc(c->pool, sizeof(int));
14819 *((int *) c->argv[2]) = 0;
14820 c->argv[3] = pcalloc(c->pool, sizeof(unsigned char));
14821 *((unsigned char *) c->argv[3]) = TRUE;
14822
14823 for (i = 1; i < cmd->argc;) {
14824 if (strcmp(cmd->argv[i], "ctrl") == 0) {
14825 int secs;
14826
14827 secs = atoi(cmd->argv[i+1]);
14828 *((int *) c->argv[0]) = secs;
14829
14830 i += 2;
14831
14832 } else if (strcmp(cmd->argv[i], "data") == 0) {
14833 char *ptr = NULL;
14834 unsigned long kbytes;
14835
14836 kbytes = strtoul(cmd->argv[i+1], &ptr, 10);
14837 if (ptr && *ptr) {
14838 CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, cmd->argv[i],
14839 " must be valid number: '", cmd->argv[i+1], "'", NULL));
14840 }
14841
14842 *((off_t *) c->argv[1]) = (off_t) kbytes * 1024;
14843
14844 i += 2;
14845
14846 } else if (strcmp(cmd->argv[i], "required") == 0) {
14847 int required;
14848
14849 required = get_boolean(cmd, i+1);
14850 if (required != -1) {
14851 *((unsigned char *) c->argv[3]) = required;
14852
14853 } else {
14854 CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, cmd->argv[i],
14855 " must be a Boolean value: '", cmd->argv[i+1], "'", NULL));
14856 }
14857
14858 i += 2;
14859
14860 } else if (strcmp(cmd->argv[i], "timeout") == 0) {
14861 int secs = atoi(cmd->argv[i+1]);
14862
14863 if (secs > 0) {
14864 *((int *) c->argv[2]) = secs;
14865
14866 } else {
14867 CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, cmd->argv[i],
14868 " must be greater than zero: '", cmd->argv[i+1], "'", NULL));
14869 }
14870
14871 i += 2;
14872
14873 } else {
14874 CONF_ERROR(cmd, pstrcat(cmd->tmp_pool,
14875 ": unknown TLSRenegotiate argument '", cmd->argv[i], "'", NULL));
14876 }
14877 }
14878
14879 return PR_HANDLED(cmd);
14880 #else
14881 CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, " requires OpenSSL-0.9.7 or greater",
14882 NULL));
14883 #endif
14884 }
14885
14886 /* usage: TLSRequired on|off|both|control|ctrl|[!]data|auth|auth+data */
14887 MODRET set_tlsrequired(cmd_rec *cmd) {
14888 int required = -1;
14889 int on_auth = 0, on_ctrl = 0, on_data = 0;
14890 config_rec *c = NULL;
14891
14892 CHECK_ARGS(cmd, 1);
14893 CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL|CONF_ANON|CONF_DIR|
14894 CONF_DYNDIR);
14895
14896 required = get_boolean(cmd, 1);
14897 if (required == -1) {
14898 if (strcmp(cmd->argv[1], "control") == 0 ||
14899 strcmp(cmd->argv[1], "ctrl") == 0) {
14900 on_auth = 1;
14901 on_ctrl = 1;
14902
14903 } else if (strcmp(cmd->argv[1], "data") == 0) {
14904 on_data = 1;
14905
14906 } else if (strcmp(cmd->argv[1], "!data") == 0) {
14907 on_data = -1;
14908
14909 } else if (strcmp(cmd->argv[1], "both") == 0 ||
14910 strcmp(cmd->argv[1], "ctrl+data") == 0) {
14911 on_auth = 1;
14912 on_ctrl = 1;
14913 on_data = 1;
14914
14915 } else if (strcmp(cmd->argv[1], "ctrl+!data") == 0) {
14916 on_auth = 1;
14917 on_ctrl = 1;
14918 on_data = -1;
14919
14920 } else if (strcmp(cmd->argv[1], "auth") == 0) {
14921 on_auth = 1;
14922
14923 } else if (strcmp(cmd->argv[1], "auth+data") == 0) {
14924 on_auth = 1;
14925 on_data = 1;
14926
14927 } else if (strcmp(cmd->argv[1], "auth+!data") == 0) {
14928 on_auth = 1;
14929 on_data = -1;
14930
14931 } else
14932 CONF_ERROR(cmd, "bad parameter");
14933
14934 } else {
14935 if (required == TRUE) {
14936 on_auth = 1;
14937 on_ctrl = 1;
14938 on_data = 1;
14939 }
14940 }
14941
14942 c = add_config_param(cmd->argv[0], 3, NULL, NULL, NULL);
14943 c->argv[0] = pcalloc(c->pool, sizeof(int));
14944 *((int *) c->argv[0]) = on_ctrl;
14945 c->argv[1] = pcalloc(c->pool, sizeof(int));
14946 *((int *) c->argv[1]) = on_data;
14947 c->argv[2] = pcalloc(c->pool, sizeof(int));
14948 *((int *) c->argv[2]) = on_auth;
14949
14950 c->flags |= CF_MERGEDOWN;
14951
14952 return PR_HANDLED(cmd);
14953 }
14954
14955 /* usage: TLSRSACertificateFile file */
14956 MODRET set_tlsrsacertfile(cmd_rec *cmd) {
14957 char *path;
14958 const char *fingerprint, *errstr = NULL;
14959
14960 CHECK_ARGS(cmd, 1);
14961 CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL);
14962
14963 path = cmd->argv[1];
14964 if (*path != '/') {
14965 CONF_ERROR(cmd, "parameter must be an absolute path");
14966 }
14967
14968 PRIVS_ROOT
14969 fingerprint = tls_get_fingerprint_from_file(cmd->tmp_pool, path, EVP_PKEY_RSA,
14970 &errstr);
14971 PRIVS_RELINQUISH
14972
14973 if (fingerprint == NULL) {
14974 CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, "'", path,
14975 "' does not exist or does not contain a certificate", NULL));
14976 }
14977
14978 add_config_param_str(cmd->argv[0], 2, path, fingerprint);
14979 return PR_HANDLED(cmd);
14980 }
14981
14982 /* usage: TLSRSACertificateKeyFile file */
14983 MODRET set_tlsrsakeyfile(cmd_rec *cmd) {
14984 int res;
14985 char *path;
14986 SSL_CTX *ctx;
14987
14988 CHECK_ARGS(cmd, 1);
14989 CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL);
14990
14991 path = cmd->argv[1];
14992
14993 PRIVS_ROOT
14994
14995 ctx = SSL_CTX_new(SSLv23_server_method());
14996 if (ctx != NULL) {
14997 /* Note that the configured key file might be passphrase-protected. We
14998 * do not necessarily want to prompt for the passphrase here, so if that
14999 * is the error returned, it is an expected condition, and indicates that
15000 * the encoding of the key is acceptable.
15001 */
15002 SSL_CTX_set_default_passwd_cb(ctx, tls_keyfile_check_cb);
15003
15004 res = SSL_CTX_use_PrivateKey_file(ctx, path, X509_FILETYPE_PEM);
15005 if (res != 1) {
15006 unsigned long err_code;
15007
15008 err_code = ERR_peek_error();
15009 switch (ERR_GET_REASON(err_code)) {
15010 /* These are "expected" error codes from working with
15011 * passphrase-protected keys.
15012 */
15013 case EVP_R_BAD_DECRYPT:
15014 case PEM_R_BAD_PASSWORD_READ:
15015 break;
15016
15017 default: {
15018 PRIVS_RELINQUISH
15019
15020 CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, "unable to use '", path, "': ",
15021 tls_get_errors2(cmd->tmp_pool), NULL));
15022 }
15023 }
15024 }
15025
15026 SSL_CTX_free(ctx);
15027
15028 } else {
15029 res = file_exists2(cmd->tmp_pool, path);
15030 if (res == FALSE) {
15031 PRIVS_RELINQUISH
15032 CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, "'", path, "' does not exist",
15033 NULL));
15034 }
15035 }
15036
15037 PRIVS_RELINQUISH
15038
15039 if (*path != '/') {
15040 CONF_ERROR(cmd, "parameter must be an absolute path");
15041 }
15042
15043 add_config_param_str(cmd->argv[0], 1, path);
15044 return PR_HANDLED(cmd);
15045 }
15046
15047 /* usage: TLSServerCipherPreference on|off */
15048 MODRET set_tlsservercipherpreference(cmd_rec *cmd) {
15049 int use_server_prefs = -1;
15050 #ifdef SSL_OP_CIPHER_SERVER_PREFERENCE
15051 config_rec *c = NULL;
15052 #endif
15053
15054 CHECK_ARGS(cmd, 1);
15055 CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL);
15056
15057 use_server_prefs = get_boolean(cmd, 1);
15058 if (use_server_prefs == -1) {
15059 CONF_ERROR(cmd, "expected Boolean parameter");
15060 }
15061
15062 #ifdef SSL_OP_CIPHER_SERVER_PREFERENCE
15063 c = add_config_param(cmd->argv[0], 1, NULL);
15064 c->argv[0] = pcalloc(c->pool, sizeof(int));
15065 *((int *) c->argv[0]) = use_server_prefs;
15066
15067 #else
15068 pr_log_debug(DEBUG0,
15069 "%s is not supported by this version of OpenSSL, ignoring",
15070 (char *) cmd->argv[0]);
15071 #endif /* SSL_OP_CIPHER_SERVER_PREFERENCE */
15072
15073 return PR_HANDLED(cmd);
15074 }
15075
15076 /* usage: TLSServerInfoFile path */
15077 MODRET set_tlsserverinfofile(cmd_rec *cmd) {
15078 #if !defined(OPENSSL_NO_TLSEXT) && OPENSSL_VERSION_NUMBER >= 0x10002000L
15079 char *path;
15080
15081 CHECK_ARGS(cmd, 1);
15082 CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL);
15083
15084 path = cmd->argv[1];
15085 if (*path != '/') {
15086 CONF_ERROR(cmd, "parameter must be an absolute path");
15087 }
15088
15089 add_config_param_str(cmd->argv[0], 1, path);
15090 #else
15091 pr_log_debug(DEBUG0,
15092 "%s is not supported by this version of OpenSSL, ignoring",
15093 (char *) cmd->argv[0]);
15094 #endif /* OPENSSL_NO_TLSEXT */
15095
15096 return PR_HANDLED(cmd);
15097 }
15098
15099 /* usage: TLSSessionCache "off"|type:/info [timeout] */
15100 MODRET set_tlssessioncache(cmd_rec *cmd) {
15101 char *provider = NULL, *info = NULL;
15102 config_rec *c;
15103 long timeout = -1;
15104 int enabled = -1;
15105
15106 if (cmd->argc < 2 ||
15107 cmd->argc > 3) {
15108 CONF_ERROR(cmd, "wrong number of parameters");
15109 }
15110
15111 CHECK_CONF(cmd, CONF_ROOT);
15112
15113 /* Has session caching been explicitly turned off? */
15114 enabled = get_boolean(cmd, 1);
15115 if (enabled != FALSE) {
15116 char *ptr;
15117
15118 /* Separate the type/info parameter into pieces. */
15119 ptr = strchr(cmd->argv[1], ':');
15120 if (ptr == NULL) {
15121 CONF_ERROR(cmd, "badly formatted parameter");
15122 }
15123
15124 *ptr = '\0';
15125 provider = cmd->argv[1];
15126 info = ptr + 1;
15127
15128 /* Verify that the requested cache type has been registered. */
15129 if (strncmp(provider, "internal", 9) != 0) {
15130 if (tls_sess_cache_get_cache(provider) == NULL) {
15131 CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, "session cache type '",
15132 provider, "' not available", NULL));
15133 }
15134 }
15135 }
15136
15137 if (cmd->argc == 3) {
15138 char *ptr = NULL;
15139
15140 timeout = strtol(cmd->argv[2], &ptr, 10);
15141 if (ptr && *ptr) {
15142 CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, "'", cmd->argv[2],
15143 "' is not a valid timeout value", NULL));
15144 }
15145
15146 if (timeout < 1) {
15147 CONF_ERROR(cmd, "timeout be greater than 1");
15148 }
15149
15150 } else {
15151 /* Default timeout is 30 min (1800 secs). */
15152 timeout = 1800;
15153 }
15154
15155 c = add_config_param(cmd->argv[0], 3, NULL, NULL, NULL);
15156 if (provider != NULL) {
15157 c->argv[0] = pstrdup(c->pool, provider);
15158 }
15159
15160 if (info != NULL) {
15161 c->argv[1] = pstrdup(c->pool, info);
15162 }
15163
15164 c->argv[2] = palloc(c->pool, sizeof(long));
15165 *((long *) c->argv[2]) = timeout;
15166
15167 return PR_HANDLED(cmd);
15168 }
15169
15170 /* usage: TLSSessionTicketKeys [age secs] [count num] */
15171 MODRET set_tlssessionticketkeys(cmd_rec *cmd) {
15172 #if defined(TLS_USE_SESSION_TICKETS)
15173 register unsigned int i;
15174 int max_age = -1, max_nkeys = -1;
15175 config_rec *c = NULL;
15176
15177 if (cmd->argc != 3 &&
15178 cmd->argc != 5) {
15179 CONF_ERROR(cmd, "wrong number of parameters");
15180 }
15181
15182 CHECK_CONF(cmd, CONF_ROOT);
15183
15184 for (i = 1; i < cmd->argc; i++) {
15185 if (strcasecmp(cmd->argv[i], "age") == 0) {
15186 if (pr_str_get_duration(cmd->argv[i+1], &max_age) < 0) {
15187 CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, "error parsing age value '",
15188 cmd->argv[i+1], "': ", strerror(errno), NULL));
15189 }
15190
15191 /* Note that we do not allow ticket keys to age out faster than 1
15192 * minute. Less than that is a bit ridiculous, no?
15193 */
15194 if (max_age < 60) {
15195 CONF_ERROR(cmd, "max key age must be at least 60sec");
15196 }
15197
15198 i++;
15199
15200 } else if (strcasecmp(cmd->argv[i], "count") == 0) {
15201 max_nkeys = atoi(cmd->argv[i+1]);
15202 if (max_nkeys < 0) {
15203 CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, "error parsing count value '",
15204 cmd->argv[i+1], "': ", strerror(EINVAL), NULL));
15205 }
15206
15207 /* Note that we need at least ONE ticket key for session tickets to
15208 * even work.
15209 */
15210 if (max_nkeys < 2) {
15211 CONF_ERROR(cmd, "max key count must be at least 1");
15212 }
15213
15214 i++;
15215
15216 } else {
15217 CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, "unknown parameter: ",
15218 (char *) cmd->argv[i], NULL));
15219 }
15220 }
15221
15222 c = add_config_param(cmd->argv[0], 2, NULL, NULL);
15223 c->argv[0] = pcalloc(c->pool, sizeof(unsigned int));
15224 *((unsigned int *) c->argv[0]) = max_age;
15225 c->argv[1] = pcalloc(c->pool, sizeof(unsigned int));
15226 *((unsigned int *) c->argv[1]) = max_nkeys;
15227
15228 return PR_HANDLED(cmd);
15229 #else
15230 CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, "The ", cmd->argv[0],
15231 " directive cannot be used on this system, as your OpenSSL version "
15232 "does not have session ticket support", NULL));
15233 #endif /* TLS_USE_SESSION_TICKETS */
15234 }
15235
15236 /* usage; TLSSessionTickets on|off */
15237 MODRET set_tlssessiontickets(cmd_rec *cmd) {
15238 #if defined(TLS_USE_SESSION_TICKETS)
15239 int session_tickets = -1;
15240 config_rec *c = NULL;
15241
15242 CHECK_ARGS(cmd, 1);
15243 CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL);
15244
15245 session_tickets = get_boolean(cmd, 1);
15246 if (session_tickets == -1) {
15247 CONF_ERROR(cmd, "expected Boolean parameter");
15248 }
15249
15250 c = add_config_param(cmd->argv[0], 1, NULL);
15251 c->argv[0] = pcalloc(c->pool, sizeof(int));
15252 *((int *) c->argv[0]) = session_tickets;
15253
15254 return PR_HANDLED(cmd);
15255 #else
15256 CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, "The ", cmd->argv[0],
15257 " directive cannot be used on this system, as your OpenSSL version "
15258 "does not have session ticket support", NULL));
15259 #endif /* TLS_USE_SESSION_TICKETS */
15260 }
15261
15262 /* usage: TLSStapling on|off */
15263 MODRET set_tlsstapling(cmd_rec *cmd) {
15264 #if defined(PR_USE_OPENSSL_OCSP)
15265 int stapling = -1;
15266 config_rec *c = NULL;
15267
15268 CHECK_ARGS(cmd, 1);
15269 CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL);
15270
15271 stapling = get_boolean(cmd, 1);
15272 if (stapling == -1) {
15273 CONF_ERROR(cmd, "expected Boolean parameter");
15274 }
15275
15276 c = add_config_param(cmd->argv[0], 1, NULL);
15277 c->argv[0] = pcalloc(c->pool, sizeof(int));
15278 *((int *) c->argv[0]) = stapling;
15279
15280 return PR_HANDLED(cmd);
15281 #else
15282 CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, "The ", cmd->argv[0],
15283 " directive cannot be used on this system, as your OpenSSL version "
15284 "does not have OCSP support", NULL));
15285 #endif /* PR_USE_OPENSSL_OCSP */
15286 }
15287
15288 /* usage: TLSStaplingCache "off"|type:/info */
15289 MODRET set_tlsstaplingcache(cmd_rec *cmd) {
15290 char *provider = NULL, *info = NULL;
15291 config_rec *c;
15292 int enabled = -1;
15293
15294 CHECK_ARGS(cmd, 1);
15295 CHECK_CONF(cmd, CONF_ROOT);
15296
15297 /* Has OCSP response caching been explicitly turned off? */
15298 enabled = get_boolean(cmd, 1);
15299 if (enabled != FALSE) {
15300 char *ptr;
15301
15302 /* Separate the type/info parameter into pieces. */
15303 ptr = strchr(cmd->argv[1], ':');
15304 if (ptr == NULL) {
15305 CONF_ERROR(cmd, "badly formatted parameter");
15306 }
15307
15308 *ptr = '\0';
15309 provider = cmd->argv[1];
15310 info = ptr + 1;
15311
15312 /* Verify that the requested cache type has been registered. */
15313 if (tls_ocsp_cache_get_cache(provider) == NULL) {
15314 CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, "OCSP stapling cache type '",
15315 provider, "' not available", NULL));
15316 }
15317 }
15318
15319 c = add_config_param(cmd->argv[0], 2, NULL, NULL);
15320 if (provider != NULL) {
15321 c->argv[0] = pstrdup(c->pool, provider);
15322 }
15323
15324 if (info != NULL) {
15325 c->argv[1] = pstrdup(c->pool, info);
15326 }
15327
15328 return PR_HANDLED(cmd);
15329 }
15330
15331 /* usage: TLSStaplingOptions opt1 opt2 ... */
15332 MODRET set_tlsstaplingoptions(cmd_rec *cmd) {
15333 #if defined(PR_USE_OPENSSL_OCSP)
15334 config_rec *c = NULL;
15335 register unsigned int i = 0;
15336 unsigned long opts = 0UL;
15337
15338 if (cmd->argc-1 == 0) {
15339 CONF_ERROR(cmd, "wrong number of parameters");
15340 }
15341
15342 CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL);
15343
15344 c = add_config_param(cmd->argv[0], 1, NULL);
15345
15346 for (i = 1; i < cmd->argc; i++) {
15347 if (strcmp(cmd->argv[i], "NoNonce") == 0) {
15348 opts |= TLS_STAPLING_OPT_NO_NONCE;
15349
15350 } else if (strcmp(cmd->argv[i], "NoVerify") == 0) {
15351 opts |= TLS_STAPLING_OPT_NO_VERIFY;
15352
15353 } else if (strcmp(cmd->argv[i], "NoFakeTryLater") == 0) {
15354 opts |= TLS_STAPLING_OPT_NO_FAKE_TRY_LATER;
15355
15356 } else {
15357 CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, ": unknown TLSStaplingOption '",
15358 cmd->argv[i], "'", NULL));
15359 }
15360 }
15361
15362 c->argv[0] = pcalloc(c->pool, sizeof(unsigned long));
15363 *((unsigned long *) c->argv[0]) = opts;
15364 #endif /* PR_USE_OPENSSL_OCSP */
15365
15366 return PR_HANDLED(cmd);
15367 }
15368
15369 /* usage: TLSStaplingResponder url */
15370 MODRET set_tlsstaplingresponder(cmd_rec *cmd) {
15371 #if defined(PR_USE_OPENSSL_OCSP)
15372 char *host = NULL, *port = NULL, *uri = NULL, *url;
15373 int use_ssl = 0;
15374
15375 CHECK_ARGS(cmd, 1);
15376 CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL);
15377
15378 url = cmd->argv[1];
15379 if (OCSP_parse_url(url, &host, &port, &uri, &use_ssl) != 1) {
15380 CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, "error parsing URL '", url, "': ",
15381 tls_get_errors(), NULL));
15382 }
15383
15384 OPENSSL_free(host);
15385 OPENSSL_free(port);
15386 OPENSSL_free(uri);
15387
15388 add_config_param_str(cmd->argv[0], 1, url);
15389 #endif /* PR_USE_OPENSSL_OCSP */
15390
15391 return PR_HANDLED(cmd);
15392 }
15393
15394 /* usage: TLSStaplingTimeout secs */
15395 MODRET set_tlsstaplingtimeout(cmd_rec *cmd) {
15396 int timeout = -1;
15397 config_rec *c = NULL;
15398
15399 CHECK_ARGS(cmd, 1);
15400 CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL);
15401
15402 if (pr_str_get_duration(cmd->argv[1], &timeout) < 0) {
15403 CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, "error parsing timeout value '",
15404 cmd->argv[1], "': ", strerror(errno), NULL));
15405 }
15406
15407 c = add_config_param(cmd->argv[0], 1, NULL);
15408 c->argv[0] = pcalloc(c->pool, sizeof(unsigned int));
15409 *((unsigned int *) c->argv[0]) = timeout;
15410
15411 return PR_HANDLED(cmd);
15412 }
15413
15414 /* usage: TLSTimeoutHandshake secs */
15415 MODRET set_tlstimeouthandshake(cmd_rec *cmd) {
15416 int timeout = -1;
15417 config_rec *c = NULL;
15418
15419 CHECK_ARGS(cmd, 1);
15420 CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL);
15421
15422 if (pr_str_get_duration(cmd->argv[1], &timeout) < 0) {
15423 CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, "error parsing timeout value '",
15424 cmd->argv[1], "': ", strerror(errno), NULL));
15425 }
15426
15427 c = add_config_param(cmd->argv[0], 1, NULL);
15428 c->argv[0] = pcalloc(c->pool, sizeof(unsigned int));
15429 *((unsigned int *) c->argv[0]) = timeout;
15430
15431 return PR_HANDLED(cmd);
15432 }
15433
15434 /* usage: TLSUserName CommonName|EmailSubjAltName|custom-oid */
15435 MODRET set_tlsusername(cmd_rec *cmd) {
15436 CHECK_ARGS(cmd, 1);
15437 CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL);
15438
15439 /* Make sure the parameter is either "CommonName",
15440 * "EmailSubjAltName", or a custom OID.
15441 */
15442 if (strcmp(cmd->argv[1], "CommonName") != 0 &&
15443 strcmp(cmd->argv[1], "EmailSubjAltName") != 0) {
15444 register unsigned int i;
15445 char *param;
15446 size_t param_len;
15447
15448 param = cmd->argv[1];
15449 param_len = strlen(param);
15450 for (i = 0; i < param_len; i++) {
15451 if (!PR_ISDIGIT(param[i]) &&
15452 param[i] != '.') {
15453 CONF_ERROR(cmd, "badly formatted OID parameter");
15454 }
15455 }
15456 }
15457
15458 add_config_param_str(cmd->argv[0], 1, cmd->argv[1]);
15459 return PR_HANDLED(cmd);
15460 }
15461
15462 /* usage: TLSVerifyClient on|off|optional */
15463 MODRET set_tlsverifyclient(cmd_rec *cmd) {
15464 int verify_client = -1;
15465 config_rec *c = NULL;
15466
15467 CHECK_ARGS(cmd, 1);
15468 CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL);
15469
15470 verify_client = get_boolean(cmd, 1);
15471 if (verify_client == -1) {
15472 if (strcasecmp(cmd->argv[1], "optional") != 0) {
15473 CONF_ERROR(cmd, "expected Boolean parameter");
15474 }
15475
15476 verify_client = 2;
15477 }
15478
15479 c = add_config_param(cmd->argv[0], 1, NULL);
15480 c->argv[0] = pcalloc(c->pool, sizeof(unsigned char));
15481 *((unsigned char *) c->argv[0]) = verify_client;
15482
15483 return PR_HANDLED(cmd);
15484 }
15485
15486 /* usage: TLSVerifyDepth depth */
15487 MODRET set_tlsverifydepth(cmd_rec *cmd) {
15488 int depth = -1;
15489 config_rec *c = NULL;
15490
15491 CHECK_ARGS(cmd, 1);
15492 CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL);
15493
15494 depth = atoi(cmd->argv[1]);
15495 if (depth < 0) {
15496 CONF_ERROR(cmd, "depth must be zero or greater");
15497 }
15498
15499 c = add_config_param(cmd->argv[0], 1, NULL);
15500 c->argv[0] = pcalloc(c->pool, sizeof(int));
15501 *((int *) c->argv[0]) = depth;
15502
15503 return PR_HANDLED(cmd);
15504 }
15505
15506 /* usage: TLSVerifyOrder mech1 ... */
15507 MODRET set_tlsverifyorder(cmd_rec *cmd) {
15508 register unsigned int i = 0;
15509 config_rec *c = NULL;
15510
15511 /* We only support two client cert verification mechanisms at the moment:
15512 * CRLs and OCSP.
15513 */
15514 if (cmd->argc-1 < 1 ||
15515 cmd->argc-1 > 2) {
15516 CONF_ERROR(cmd, "wrong number of parameters");
15517 }
15518
15519 CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL);
15520
15521 for (i = 1; i < cmd->argc; i++) {
15522 char *mech = cmd->argv[i];
15523
15524 if (strncasecmp(mech, "crl", 4) != 0
15525 #if OPENSSL_VERSION_NUMBER > 0x000907000L
15526 && strncasecmp(mech, "ocsp", 5) != 0) {
15527 #else
15528 ) {
15529 #endif
15530 CONF_ERROR(cmd, pstrcat(cmd->tmp_pool,
15531 "unsupported verification mechanism '", mech, "' requested", NULL));
15532 }
15533 }
15534
15535 c = add_config_param(cmd->argv[0], cmd->argc-1, NULL, NULL);
15536 for (i = 1; i < cmd->argc; i++) {
15537 char *mech = cmd->argv[i];
15538
15539 if (strncasecmp(mech, "crl", 4) == 0) {
15540 c->argv[i-1] = pstrdup(c->pool, "crl");
15541
15542 #if OPENSSL_VERSION_NUMBER > 0x000907000L
15543 } else if (strncasecmp(mech, "ocsp", 5) == 0) {
15544 c->argv[i-1] = pstrdup(c->pool, "ocsp");
15545 #endif
15546 }
15547 }
15548
15549 return PR_HANDLED(cmd);
15550 }
15551
15552 /* usage: TLSVerifyServer on|NoReverseDNS|off */
15553 MODRET set_tlsverifyserver(cmd_rec *cmd) {
15554 int setting = -1;
15555 config_rec *c = NULL;
15556
15557 CHECK_ARGS(cmd, 1);
15558 CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL);
15559
15560 setting = get_boolean(cmd, 1);
15561 if (setting == -1) {
15562 if (strcasecmp(cmd->argv[1], "NoReverseDNS") != 0) {
15563 CONF_ERROR(cmd, "expected Boolean parameter");
15564 }
15565
15566 setting = 2;
15567 }
15568
15569 c = add_config_param(cmd->argv[0], 1, NULL);
15570 c->argv[0] = pcalloc(c->pool, sizeof(int));
15571 *((int *) c->argv[0]) = setting;
15572
15573 return PR_HANDLED(cmd);
15574 }
15575
15576 /* Event handlers
15577 */
15578
15579 #if defined(PR_SHARED_MODULE)
15580 static void tls_mod_unload_ev(const void *event_data, void *user_data) {
15581 if (strcmp("mod_tls.c", (const char *) event_data) == 0) {
15582 /* Unregister ourselves from all events. */
15583 pr_event_unregister(&tls_module, NULL, NULL);
15584
15585 pr_timer_remove(-1, &tls_module);
15586 # if defined(TLS_USE_SESSION_TICKETS)
15587 scrub_ticket_keys();
15588 # endif /* TLS_USE_SESSION_TICKETS */
15589
15590 # ifdef PR_USE_CTRLS
15591 /* Unregister any control actions. */
15592 pr_ctrls_unregister(&tls_module, "tls");
15593
15594 destroy_pool(tls_act_pool);
15595 tls_act_pool = NULL;
15596 # endif /* PR_USE_CTRLS */
15597
15598 /* Cleanup the OpenSSL stuff. */
15599 tls_cleanup(0);
15600
15601 /* Unregister our NetIO handler for the control channel. */
15602 pr_unregister_netio(PR_NETIO_STRM_CTRL);
15603
15604 if (tls_ctrl_netio) {
15605 destroy_pool(tls_ctrl_netio->pool);
15606 tls_ctrl_netio = NULL;
15607 }
15608
15609 if (tls_data_netio) {
15610 destroy_pool(tls_data_netio->pool);
15611 tls_data_netio = NULL;
15612 }
15613
15614 close(tls_logfd);
15615 tls_logfd = -1;
15616 }
15617 }
15618 #endif /* PR_SHARED_MODULE */
15619
15620 static void tls_sess_reinit_ev(const void *event_data, void *user_data) {
15621 int res;
15622
15623 /* If the client has already established a TLS session, then do nothing;
15624 * we cannot easily force a re-handshake using different credentials very
15625 * easily. (Right?)
15626 */
15627 if (session.rfc2228_mech != NULL) {
15628 pr_trace_msg(trace_channel, 17,
15629 "ignored 'core.session-reinit' event due to existing SSL session");
15630 return;
15631 }
15632
15633 /* A HOST command changed the main_server pointer; reinitialize ourselves. */
15634
15635 pr_event_unregister(&tls_module, "core.exit", tls_exit_ev);
15636 pr_event_unregister(&tls_module, "core.session-reinit", tls_sess_reinit_ev);
15637
15638 tls_reset_state();
15639
15640 /* XXX How to indicate, to sess_init. to NOT re-register the following event
15641 * listeners?
15642 *
15643 *
15644 * XXX How to indicate, to sess_init, to NOT re-add the pr_feat_add TLS
15645 * features. Same for TLS HELP stuff.
15646 * ANSWER: Add unit tests for Feature API, Help API for adding duplicates;
15647 * ensure APIs detect and ignore such duplicates.
15648 */
15649
15650 res = tls_sess_init();
15651 if (res < 0) {
15652 pr_session_disconnect(&tls_module, PR_SESS_DISCONNECT_SESSION_INIT_FAILED,
15653 NULL);
15654 }
15655 }
15656
15657 /* Daemon PID */
15658 extern pid_t mpid;
15659
15660 static void tls_shutdown_ev(const void *event_data, void *user_data) {
15661 if (mpid == getpid()) {
15662 tls_scrub_pkeys();
15663 #if defined(TLS_USE_SESSION_TICKETS)
15664 scrub_ticket_keys();
15665 #endif /* TLS_USE_SESSION_TICKETS */
15666 destroy_pool(tls_pool);
15667 tls_pool = NULL;
15668 }
15669
15670 /* Write out a new RandomSeed file, for use later. */
15671 if (tls_rand_file) {
15672 int res;
15673
15674 res = RAND_write_file(tls_rand_file);
15675 if (res < 0) {
15676 pr_log_pri(PR_LOG_WARNING, MOD_TLS_VERSION
15677 ": error writing PRNG seed data to '%s': %s", tls_rand_file,
15678 tls_get_errors());
15679
15680 } else {
15681 pr_log_debug(DEBUG2, MOD_TLS_VERSION
15682 ": wrote %d bytes of PRNG seed data to '%s'", res, tls_rand_file);
15683 }
15684 }
15685
15686 if (ssl_ctx != NULL) {
15687 SSL_CTX_free(ssl_ctx);
15688 ssl_ctx = NULL;
15689 }
15690
15691 #if OPENSSL_VERSION_NUMBER < 0x10100000L
15692 RAND_cleanup();
15693 #endif /* prior to OpenSSL-1.1.x */
15694 }
15695
15696 static void tls_restart_ev(const void *event_data, void *user_data) {
15697 #ifdef PR_USE_CTRLS
15698 register unsigned int i;
15699 #endif /* PR_USE_CTRLS */
15700
15701 /* Note: We SHOULD scrub all of the mlock'd passphrases from memory here.
15702 * However, doing so would require that some outside agency, such as
15703 * a TLSPassPhraseProvider, provide those passphrases again. And some
15704 * sites deem such providers insecure, but do have servers restarted due
15705 * to e.g. log rotation, without changing the passphrases/certs. For
15706 * such sites, then, we will opportunistically scrub the pkeys later,
15707 * during the phase where such passphrases are obtained as needed;
15708 * see Bug#4260.
15709 */
15710
15711 #ifdef PR_USE_CTRLS
15712 if (tls_act_pool != NULL) {
15713 destroy_pool(tls_act_pool);
15714 tls_act_pool = NULL;
15715 }
15716
15717 tls_act_pool = make_sub_pool(permanent_pool);
15718 pr_pool_tag(tls_act_pool, "TLS Controls Pool");
15719
15720 /* Re-create the controls ACLs. */
15721 for (i = 0; tls_acttab[i].act_action; i++) {
15722 tls_acttab[i].act_acl = palloc(tls_act_pool, sizeof(ctrls_acl_t));
15723 pr_ctrls_init_acl(tls_acttab[i].act_acl);
15724 }
15725 #endif /* PR_USE_CTRLS */
15726
15727 tls_closelog();
15728 }
15729
15730 static void tls_exit_ev(const void *event_data, void *user_data) {
15731
15732 if (ssl_ctx != NULL) {
15733 time_t now;
15734
15735 /* Help out with the TLS session cache grooming by flushing any
15736 * expired sessions out right now. The client is closing its
15737 * connection to us anyway, so some additional latency here shouldn't
15738 * be noticed. Right?
15739 */
15740 now = time(NULL);
15741 SSL_CTX_flush_sessions(ssl_ctx, (long) now);
15742 }
15743
15744 /* If diags are enabled, log some OpenSSL stats. */
15745 if (ssl_ctx != NULL &&
15746 (tls_opts & TLS_OPT_ENABLE_DIAGS)) {
15747 long res;
15748
15749 res = SSL_CTX_sess_accept(ssl_ctx);
15750 tls_log("[stat]: SSL/TLS sessions attempted: %ld", res);
15751
15752 res = SSL_CTX_sess_accept_good(ssl_ctx);
15753 tls_log("[stat]: SSL/TLS sessions established: %ld", res);
15754
15755 res = SSL_CTX_sess_accept_renegotiate(ssl_ctx);
15756 tls_log("[stat]: SSL/TLS sessions renegotiated: %ld", res);
15757
15758 res = SSL_CTX_sess_hits(ssl_ctx);
15759 tls_log("[stat]: SSL/TLS sessions resumed: %ld", res);
15760
15761 res = SSL_CTX_sess_number(ssl_ctx);
15762 tls_log("[stat]: SSL/TLS sessions in cache: %ld", res);
15763
15764 res = SSL_CTX_sess_cb_hits(ssl_ctx);
15765 tls_log("[stat]: SSL/TLS session cache hits: %ld", res);
15766
15767 res = SSL_CTX_sess_misses(ssl_ctx);
15768 tls_log("[stat]: SSL/TLS session cache misses: %ld", res);
15769
15770 res = SSL_CTX_sess_timeouts(ssl_ctx);
15771 tls_log("[stat]: SSL/TLS session cache timeouts: %ld", res);
15772
15773 res = SSL_CTX_sess_cache_full(ssl_ctx);
15774 tls_log("[stat]: SSL/TLS session cache size exceeded: %ld", res);
15775 }
15776
15777 if (tls_sni_sess_tab != NULL) {
15778 (void) pr_table_empty(tls_sni_sess_tab);
15779 (void) pr_table_free(tls_sni_sess_tab);
15780 tls_sni_sess_tab = NULL;
15781 }
15782
15783 if (tls_pkey != NULL) {
15784 tls_scrub_pkey(tls_pkey);
15785 tls_pkey = NULL;
15786 }
15787
15788 /* OpenSSL cleanup */
15789 tls_cleanup(0);
15790
15791 /* Done with the NetIO objects. Note that we only really need to
15792 * destroy the data channel NetIO object; the control channel NetIO
15793 * object is allocated out of the permanent pool, in the daemon process,
15794 * and thus we have a read-only copy.
15795 */
15796
15797 if (tls_ctrl_netio != NULL) {
15798 pr_unregister_netio(PR_NETIO_STRM_CTRL);
15799 destroy_pool(tls_ctrl_netio->pool);
15800 tls_ctrl_netio = NULL;
15801 }
15802
15803 if (tls_data_netio != NULL) {
15804 pr_unregister_netio(PR_NETIO_STRM_DATA);
15805 destroy_pool(tls_data_netio->pool);
15806 tls_data_netio = NULL;
15807 }
15808
15809 if (mpid != getpid()) {
15810 tls_scrub_pkeys();
15811 }
15812
15813 tls_closelog();
15814 }
15815
15816 static void tls_timeout_ev(const void *event_data, void *user_data) {
15817
15818 if (session.c &&
15819 ctrl_ssl != NULL &&
15820 (tls_flags & TLS_SESS_ON_CTRL)) {
15821 /* Try to properly close the TLS session down on the control channel,
15822 * if there is one.
15823 */
15824 tls_end_sess(ctrl_ssl, session.c, 0);
15825 pr_table_remove(tls_ctrl_rd_nstrm->notes, TLS_NETIO_NOTE, NULL);
15826 pr_table_remove(tls_ctrl_wr_nstrm->notes, TLS_NETIO_NOTE, NULL);
15827 ctrl_ssl = NULL;
15828 }
15829 }
15830
15831 static tls_pkey_t *tls_find_pkey(server_rec *s, int flags) {
15832 tls_pkey_t *k, *pkey = NULL;
15833
15834 for (k = tls_pkey_list; k; k = k->next) {
15835 if (k->sid == s->sid) {
15836 switch (flags) {
15837 case TLS_PASSPHRASE_FL_RSA_KEY:
15838 if (k->rsa_pkey != NULL) {
15839 pkey = k;
15840 }
15841 break;
15842
15843 case TLS_PASSPHRASE_FL_DSA_KEY:
15844 if (k->dsa_pkey != NULL) {
15845 pkey = k;
15846 }
15847 break;
15848
15849 case TLS_PASSPHRASE_FL_EC_KEY:
15850 #ifdef PR_USE_OPENSSL_ECC
15851 if (k->ec_pkey != NULL) {
15852 pkey = k;
15853 }
15854 #endif /* PR_USE_OPENSSL_ECC */
15855 break;
15856
15857 case TLS_PASSPHRASE_FL_PKCS12_PASSWD:
15858 if (k->pkcs12_passwd != NULL) {
15859 pkey = k;
15860 }
15861 break;
15862
15863 default:
15864 break;
15865 }
15866
15867 if (pkey != NULL) {
15868 break;
15869 }
15870 }
15871 }
15872
15873 return pkey;
15874 }
15875
15876 static tls_pkey_t *tls_get_key_passphrase(server_rec *s, const char *path,
15877 int flags) {
15878 int res, *pass_len = NULL;
15879 tls_pkey_t *k = NULL;
15880 const char *key_type = "unsupported";
15881 char buf[256], **key_data = NULL;
15882 void **key_ptr = NULL;
15883
15884 switch (flags) {
15885 case TLS_PASSPHRASE_FL_RSA_KEY:
15886 key_type = "RSA";
15887 break;
15888
15889 case TLS_PASSPHRASE_FL_DSA_KEY:
15890 key_type = "DSA";
15891 break;
15892
15893 case TLS_PASSPHRASE_FL_EC_KEY:
15894 key_type = "EC";
15895 break;
15896
15897 case TLS_PASSPHRASE_FL_PKCS12_PASSWD:
15898 key_type = "PKCS12";
15899 break;
15900
15901 default:
15902 errno = EINVAL;
15903 return NULL;
15904 }
15905
15906 pr_trace_msg(trace_channel, 14,
15907 "obtaining passphrase/password for %s cert for path %s", key_type, path);
15908
15909 /* First see if we have an existing (and usable!) passphrase already
15910 * stored for this server/key type/path.
15911 */
15912 k = tls_find_pkey(s, flags);
15913 if (k != NULL) {
15914 /* Remove the key from the list; we will be adding this key, or another
15915 * one, back to the list in its place.
15916 */
15917 tls_remove_pkey(k);
15918
15919 pr_trace_msg(trace_channel, 19,
15920 "FOUND existing %s pkey found for server ID %u (path %s)", key_type,
15921 s->sid, k->path);
15922
15923 /* If this key is for the same path, consider it usable. */
15924 if (strcmp(path, k->path) == 0) {
15925 pr_trace_msg(trace_channel, 14,
15926 "reusing stored %s for %s certificate from path '%s'",
15927 flags != TLS_PASSPHRASE_FL_PKCS12_PASSWD ? "passphrase" : "password",
15928 key_type, path);
15929 return k;
15930 }
15931
15932 /* Not for the same path? Consider this key stale, and scrub it. */
15933 tls_scrub_pkey(k);
15934 }
15935
15936 if (k == NULL) {
15937 pool *key_pool;
15938
15939 key_pool = make_sub_pool(tls_pool);
15940 pr_pool_tag(key_pool, "Private Key Pool");
15941
15942 k = pcalloc(key_pool, sizeof(tls_pkey_t));
15943 k->pool = key_pool;
15944 }
15945
15946 k->pkeysz = PEM_BUFSIZE;
15947
15948 switch (flags) {
15949 case TLS_PASSPHRASE_FL_RSA_KEY:
15950 key_data = &(k->rsa_pkey);
15951 key_ptr = &(k->rsa_pkey_ptr);
15952 pass_len = &(k->rsa_passlen);
15953 break;
15954
15955 case TLS_PASSPHRASE_FL_DSA_KEY:
15956 key_data = &(k->dsa_pkey);
15957 key_ptr = &(k->dsa_pkey_ptr);
15958 pass_len = &(k->dsa_passlen);
15959 break;
15960
15961 case TLS_PASSPHRASE_FL_EC_KEY:
15962 #ifdef PR_USE_OPENSSL_ECC
15963 key_data = &(k->ec_pkey);
15964 key_ptr = &(k->ec_pkey_ptr);
15965 pass_len = &(k->ec_passlen);
15966 #endif /* PR_USE_OPENSSL_ECC */
15967 break;
15968
15969 case TLS_PASSPHRASE_FL_PKCS12_PASSWD:
15970 key_data = &(k->pkcs12_passwd);
15971 key_ptr = &(k->pkcs12_passwd_ptr);
15972 pass_len = &(k->pkcs12_passlen);
15973 break;
15974
15975 default:
15976 errno = EINVAL;
15977 return NULL;
15978 }
15979
15980 res = pr_snprintf(buf, sizeof(buf)-1, "%s %s for the %s#%d (%s) server: ",
15981 key_type, flags != TLS_PASSPHRASE_FL_PKCS12_PASSWD ? "key" : "password",
15982 pr_netaddr_get_ipstr(s->addr), s->ServerPort, s->ServerName);
15983 buf[res] = '\0';
15984 buf[sizeof(buf)-1] = '\0';
15985
15986 *key_data = tls_get_page(PEM_BUFSIZE, key_ptr);
15987 if (*key_data == NULL) {
15988 pr_log_pri(PR_LOG_ALERT, MOD_TLS_VERSION ": Out of memory!");
15989 pr_session_disconnect(&tls_module, PR_SESS_DISCONNECT_NOMEM, NULL);
15990 }
15991
15992 res = tls_get_passphrase(s, path, buf, *key_data, k->pkeysz-1, flags);
15993 if (res < 0) {
15994 const char *errors;
15995
15996 errors = tls_get_errors();
15997 if (errors == NULL) {
15998 errors = "Not provided";
15999 }
16000
16001 pr_trace_msg(trace_channel, 1, "error reading %s %s: %s", key_type,
16002 flags != TLS_PASSPHRASE_FL_PKCS12_PASSWD ? "passphrase" : "password",
16003 errors);
16004 pr_log_debug(DEBUG0, MOD_TLS_VERSION ": error reading %s %s: %s", key_type,
16005 flags != TLS_PASSPHRASE_FL_PKCS12_PASSWD ? "passphrase" : "password",
16006 errors);
16007
16008 pr_log_pri(PR_LOG_ERR, MOD_TLS_VERSION
16009 ": unable to use %s certificate %sin '%s', exiting", key_type,
16010 flags != TLS_PASSPHRASE_FL_PKCS12_PASSWD ? "key " : "", path);
16011 pr_session_disconnect(&tls_module, PR_SESS_DISCONNECT_BY_APPLICATION, NULL);
16012 }
16013
16014 *pass_len = res;
16015 k->path = strdup(path);
16016 k->sid = s->sid;
16017
16018 return k;
16019 }
16020
16021 static void tls_get_passphrases(void) {
16022 server_rec *s = NULL;
16023
16024 for (s = (server_rec *) server_list->xas_list; s; s = s->next) {
16025 config_rec *rsa = NULL, *dsa = NULL, *ec = NULL, *pkcs12 = NULL;
16026 tls_pkey_t *k = NULL;
16027 const char *path;
16028
16029 /* Find any TLS*CertificateKeyFile directives. If they aren't present,
16030 * look for TLS*CertificateFile directives (when appropriate).
16031 */
16032 rsa = find_config(s->conf, CONF_PARAM, "TLSRSACertificateKeyFile", FALSE);
16033 if (rsa == NULL) {
16034 rsa = find_config(s->conf, CONF_PARAM, "TLSRSACertificateFile", FALSE);
16035 }
16036
16037 dsa = find_config(s->conf, CONF_PARAM, "TLSDSACertificateKeyFile", FALSE);
16038 if (dsa == NULL) {
16039 dsa = find_config(s->conf, CONF_PARAM, "TLSDSACertificateFile", FALSE);
16040 }
16041
16042 ec = find_config(s->conf, CONF_PARAM, "TLSECCertificateKeyFile", FALSE);
16043 if (ec == NULL) {
16044 ec = find_config(s->conf, CONF_PARAM, "TLSECCertificateFile", FALSE);
16045 }
16046
16047 pkcs12 = find_config(s->conf, CONF_PARAM, "TLSPKCS12File", FALSE);
16048
16049 if (rsa == NULL &&
16050 dsa == NULL &&
16051 ec == NULL &&
16052 pkcs12 == NULL) {
16053 continue;
16054 }
16055
16056 if (rsa != NULL) {
16057 path = rsa->argv[0];
16058 k = tls_get_key_passphrase(s, path, TLS_PASSPHRASE_FL_RSA_KEY);
16059 }
16060
16061 if (dsa != NULL) {
16062 path = dsa->argv[0];
16063 k = tls_get_key_passphrase(s, path, TLS_PASSPHRASE_FL_DSA_KEY);
16064 }
16065
16066 #ifdef PR_USE_OPENSSL_ECC
16067 if (ec != NULL) {
16068 path = ec->argv[0];
16069 k = tls_get_key_passphrase(s, path, TLS_PASSPHRASE_FL_EC_KEY);
16070 }
16071 #endif /* PR_USE_OPENSSL_ECC */
16072
16073 if (pkcs12 != NULL) {
16074 path = pkcs12->argv[0];
16075 k = tls_get_key_passphrase(s, path, TLS_PASSPHRASE_FL_PKCS12_PASSWD);
16076 }
16077
16078 k->next = tls_pkey_list;
16079 tls_pkey_list = k;
16080 tls_npkeys++;
16081 }
16082 }
16083
16084 static void tls_postparse_ev(const void *event_data, void *user_data) {
16085 server_rec *s = NULL;
16086
16087 /* Check for incompatible configurations. For example, configuring:
16088 *
16089 * TLSOptions AllowPerUser
16090 * TLSRequired auth
16091 *
16092 * cannot be supported; the AllowPerUser means that the requirement of
16093 * SSL/TLS protection during authentication cannot be enforced.
16094 */
16095
16096 for (s = (server_rec *) server_list->xas_list; s; s = s->next) {
16097 unsigned long *opts;
16098 config_rec *toplevel_c = NULL, *other_c = NULL;
16099 int toplevel_auth_requires_ssl = FALSE, other_auth_requires_ssl = TRUE;
16100
16101 opts = get_param_ptr(s->conf, "TLSOptions", FALSE);
16102 if (opts == NULL) {
16103 continue;
16104 }
16105
16106 /* The purpose of this check is to watch for configurations such as:
16107 *
16108 * <IfModule mod_tls.c>
16109 * ...
16110 * TLSRequired on
16111 * ...
16112 * TLSOptions AllowPerUser
16113 * ...
16114 * </IfModule>
16115 *
16116 * This policy cannot be enforced; we cannot require use of SSL/TLS
16117 * (specifically at authentication time, when we do NOT know the user)
16118 * AND also allow per-user SSL/TLS requirements. It's a chicken-and-egg
16119 * problem.
16120 *
16121 * However, we DO want to allow configurations like:
16122 *
16123 * <IfModule mod_tls.c>
16124 * ...
16125 * TLSRequired on
16126 * ...
16127 * TLSOptions AllowPerUser
16128 * ...
16129 * </IfModule>
16130 *
16131 * <Anonymous ...>
16132 * ...
16133 * <IfModule mod_tls.c>
16134 * TLSRequired off
16135 * </IfModule>
16136 * </Anonymous>
16137 *
16138 * Thus this check is a bit tricky. We look first in this server_rec's
16139 * config list for a top-level TLSRequired setting. If it is 'on' AND
16140 * if the AllowPerUser TLSOption is set, AND we find no other TLSRequired
16141 * configs deeper in the server_rec whose value is 'off', then log the
16142 * error and quit. Otherwise, let things proceed.
16143 *
16144 * If the mod_ifsession module is present, skip this check as well; we
16145 * will not be able to suss out any TLSRequired settings which are
16146 * lurking in mod_ifsession's grasp until authentication time.
16147 *
16148 * I still regret adding support for the AllowPerUser TLSOption. Users
16149 * just cannot seem to wrap their minds around the fact that the user
16150 * is not known at the time when the SSL/TLS session is done. Sigh.
16151 */
16152
16153 if (pr_module_exists("mod_ifsession.c")) {
16154 continue;
16155 }
16156
16157 toplevel_c = find_config(s->conf, CONF_PARAM, "TLSRequired", FALSE);
16158 if (toplevel_c) {
16159 toplevel_auth_requires_ssl = *((int *) toplevel_c->argv[2]);
16160 }
16161
16162 /* If this toplevel TLSRequired value is 'off', then we need check no
16163 * further.
16164 */
16165 if (!toplevel_auth_requires_ssl) {
16166 continue;
16167 }
16168
16169 /* This time, we recurse deeper into the server_rec's configs.
16170 * We need only pay attention to settings we find in the CONF_DIR or
16171 * CONF_ANON config contexts. And we need only look until we find such
16172 * a setting does not require SSL/TLS during authentication, for at that
16173 * point we know it is not a misconfiguration.
16174 */
16175 find_config_set_top(NULL);
16176 other_c = find_config(s->conf, CONF_PARAM, "TLSRequired", TRUE);
16177 while (other_c) {
16178 int auth_requires_ssl;
16179
16180 pr_signals_handle();
16181
16182 if (other_c->parent == NULL ||
16183 (other_c->parent->config_type != CONF_ANON &&
16184 other_c->parent->config_type != CONF_DIR)) {
16185 /* Not what we're looking for; continue on. */
16186 other_c = find_config_next(other_c, other_c->next, CONF_PARAM,
16187 "TLSRequired", TRUE);
16188 continue;
16189 }
16190
16191 auth_requires_ssl = *((int *) other_c->argv[2]);
16192 if (!auth_requires_ssl) {
16193 other_auth_requires_ssl = FALSE;
16194 break;
16195 }
16196
16197 other_c = find_config_next(other_c, other_c->next, CONF_PARAM,
16198 "TLSRequired", TRUE);
16199 }
16200
16201 if ((*opts & TLS_OPT_ALLOW_PER_USER) &&
16202 toplevel_auth_requires_ssl == TRUE &&
16203 other_auth_requires_ssl == TRUE) {
16204 pr_log_pri(PR_LOG_NOTICE, MOD_TLS_VERSION ": Server %s: cannot enforce "
16205 "both 'TLSRequired auth' and 'TLSOptions AllowPerUser' at the "
16206 "same time", s->ServerName);
16207 pr_session_disconnect(&tls_module, PR_SESS_DISCONNECT_BAD_CONFIG, NULL);
16208 }
16209 }
16210
16211 if (ServerType == SERVER_INETD) {
16212 if (tls_set_fips() < 0) {
16213 pr_log_pri(PR_LOG_NOTICE, MOD_TLS_VERSION
16214 ": error initialising FIPS");
16215 pr_session_disconnect(&tls_module, PR_SESS_DISCONNECT_BY_APPLICATION,
16216 NULL);
16217 }
16218 }
16219
16220 /* Initialize the OpenSSL context. */
16221 ssl_ctx = tls_init_ctx(main_server);
16222 if (ssl_ctx == NULL) {
16223 pr_log_pri(PR_LOG_NOTICE, MOD_TLS_VERSION
16224 ": error initialising OpenSSL context");
16225 pr_session_disconnect(&tls_module, PR_SESS_DISCONNECT_BY_APPLICATION, NULL);
16226 }
16227
16228 if (tls_seed_prng() < 0) {
16229 pr_log_debug(DEBUG1, MOD_TLS_VERSION ": unable to properly seed PRNG");
16230 }
16231
16232 tls_pool = make_sub_pool(permanent_pool);
16233 pr_pool_tag(tls_pool, MOD_TLS_VERSION);
16234
16235 tls_ctx_set_session_cache(main_server, ssl_ctx);
16236 tls_ctx_set_stapling_cache(main_server, ssl_ctx);
16237 tls_ctx_set_session_id_context(main_server, ssl_ctx);
16238
16239 /* We can only get the passphrases for certs once OpenSSL has been
16240 * initialized.
16241 */
16242 tls_get_passphrases();
16243
16244 /* Clean up the pkey list, scrubbing any stale/irrelevant keys. */
16245 tls_clean_pkeys();
16246
16247 /* Install our control channel NetIO handlers. This is done here
16248 * specifically because we need to cache a pointer to the nstrm that
16249 * is passed to the open callback(). Ideally we'd only install our
16250 * custom NetIO handlers if the appropriate AUTH command was given.
16251 * But by then, the open() callback will have already been called, and
16252 * we will not have a chance to get that nstrm pointer.
16253 */
16254 tls_netio_install_ctrl();
16255 }
16256
16257 static void tls_lookup_dh_params(server_rec *s) {
16258 config_rec *c;
16259
16260 c = find_config(s->conf, CONF_PARAM, "TLSDHParamFile", FALSE);
16261 while (c != NULL) {
16262 const char *path;
16263 FILE *fp;
16264 int xerrno;
16265
16266 pr_signals_handle();
16267
16268 path = c->argv[0];
16269
16270 /* Load the DH params from the file. */
16271 PRIVS_ROOT
16272 fp = fopen(path, "r");
16273 xerrno = errno;
16274 PRIVS_RELINQUISH
16275
16276 if (fp != NULL) {
16277 DH *dh;
16278
16279 dh = PEM_read_DHparams(fp, NULL, NULL, NULL);
16280 if (dh != NULL) {
16281 if (tls_tmp_dhs == NULL) {
16282 tls_tmp_dhs = make_array(session.pool, 1, sizeof(DH *));
16283 }
16284 }
16285
16286 while (dh != NULL) {
16287 pr_signals_handle();
16288 *((DH **) push_array(tls_tmp_dhs)) = dh;
16289 dh = PEM_read_DHparams(fp, NULL, NULL, NULL);
16290 }
16291
16292 fclose(fp);
16293
16294 } else {
16295 pr_log_debug(DEBUG3, MOD_TLS_VERSION
16296 ": unable to open TLSDHParamFile '%s': %s", path, strerror(xerrno));
16297 }
16298
16299 c = find_config_next(c, c->next, CONF_PARAM, "TLSDHParamFile", FALSE);
16300 }
16301 }
16302
16303 static void tls_lookup_psks(server_rec *s) {
16304 #if defined(PSK_MAX_PSK_LEN)
16305 config_rec *c;
16306
16307 if (tls_psks != NULL) {
16308 pr_table_empty(tls_psks);
16309 pr_table_free(tls_psks);
16310 tls_psks = NULL;
16311 }
16312
16313 c = find_config(s->conf, CONF_PARAM, "TLSPreSharedKey", FALSE);
16314 while (c != NULL) {
16315 register int i;
16316 char key_buf[PR_TUNABLE_BUFFER_SIZE], *identity, *path;
16317 int fd, key_len, valid_hex = TRUE, res, xerrno;
16318 struct stat st;
16319 BIGNUM *bn = NULL;
16320
16321 pr_signals_handle();
16322
16323 identity = c->argv[0];
16324 path = c->argv[1];
16325
16326 /* Advance past the "hex:" format prefix. */
16327 path += 4;
16328
16329 PRIVS_ROOT
16330 fd = open(path, O_RDONLY);
16331 xerrno = errno;
16332 PRIVS_RELINQUISH
16333
16334 if (fd < 0) {
16335 pr_log_debug(DEBUG2, MOD_TLS_VERSION
16336 ": error opening TLSPreSharedKey file '%s': %s", path,
16337 strerror(xerrno));
16338 c = find_config_next(c, c->next, CONF_PARAM, "TLSPreSharedKey", FALSE);
16339 continue;
16340 }
16341
16342 if (fstat(fd, &st) < 0) {
16343 pr_log_debug(DEBUG2, MOD_TLS_VERSION
16344 ": error checking TLSPreSharedKey file '%s': %s", path,
16345 strerror(errno));
16346 (void) close(fd);
16347 c = find_config_next(c, c->next, CONF_PARAM, "TLSPreSharedKey", FALSE);
16348 continue;
16349 }
16350
16351 /* Check on the permissions of the file; skip it if the permissions
16352 * are too permissive, e.g. file is world-read/writable.
16353 */
16354 if (st.st_mode & S_IROTH) {
16355 pr_log_debug(DEBUG2, MOD_TLS_VERSION
16356 ": unable to use TLSPreSharedKey file '%s': file is world-readable",
16357 path);
16358 (void) close(fd);
16359 c = find_config_next(c, c->next, CONF_PARAM, "TLSPreSharedKey", FALSE);
16360 continue;
16361 }
16362
16363 if (st.st_mode & S_IWOTH) {
16364 pr_log_debug(DEBUG2, MOD_TLS_VERSION
16365 ": unable to use TLSPreSharedKey file '%s': file is world-writable",
16366 path);
16367 (void) close(fd);
16368 c = find_config_next(c, c->next, CONF_PARAM, "TLSPreSharedKey", FALSE);
16369 continue;
16370 }
16371
16372 /* Read the entire key into memory. */
16373 key_len = read(fd, key_buf, sizeof(key_buf)-1);
16374 (void) close(fd);
16375
16376 if (key_len < 0) {
16377 pr_log_debug(DEBUG2, MOD_TLS_VERSION
16378 ": error reading TLSPreSharedKey file '%s': %s", path,
16379 strerror(xerrno));
16380 c = find_config_next(c, c->next, CONF_PARAM, "TLSPreSharedKey", FALSE);
16381 continue;
16382
16383 } else if (key_len == 0) {
16384 pr_log_debug(DEBUG2, MOD_TLS_VERSION
16385 ": read zero bytes from TLSPreSharedKey file '%s', ignoring", path);
16386 c = find_config_next(c, c->next, CONF_PARAM, "TLSPreSharedKey", FALSE);
16387 continue;
16388
16389 } else if (key_len < TLS_MIN_PSK_LEN) {
16390 pr_log_debug(DEBUG2, MOD_TLS_VERSION
16391 ": read %d bytes from TLSPreSharedKey file '%s', need at least %d "
16392 "bytes of key data, ignoring", key_len, path, TLS_MIN_PSK_LEN);
16393 c = find_config_next(c, c->next, CONF_PARAM, "TLSPreSharedKey", FALSE);
16394 continue;
16395 }
16396
16397 key_buf[key_len] = '\0';
16398 key_buf[sizeof(key_buf)-1] = '\0';
16399
16400 /* Ignore any trailing newlines. */
16401 if (key_buf[key_len-1] == '\n') {
16402 key_buf[key_len-1] = '\0';
16403 key_len--;
16404 }
16405
16406 if (key_buf[key_len-1] == '\r') {
16407 key_buf[key_len-1] = '\0';
16408 key_len--;
16409 }
16410
16411 /* Ensure that it is all hex encoded data */
16412 for (i = 0; i < key_len; i++) {
16413 if (PR_ISXDIGIT((int) key_buf[i]) == 0) {
16414 valid_hex = FALSE;
16415 break;
16416 }
16417 }
16418
16419 if (valid_hex == FALSE) {
16420 pr_log_debug(DEBUG2, MOD_TLS_VERSION
16421 ": unable to use '%s': not a hex number", key_buf);
16422 c = find_config_next(c, c->next, CONF_PARAM, "TLSPreSharedKey", FALSE);
16423 continue;
16424 }
16425
16426 res = BN_hex2bn(&bn, key_buf);
16427 if (res == 0) {
16428 pr_log_debug(DEBUG2, MOD_TLS_VERSION
16429 ": failed to convert '%s' to BIGNUM: %s", key_buf,
16430 tls_get_errors());
16431
16432 if (bn != NULL) {
16433 BN_free(bn);
16434 }
16435
16436 c = find_config_next(c, c->next, CONF_PARAM, "TLSPreSharedKey", FALSE);
16437 continue;
16438 }
16439
16440 if (tls_psks == NULL) {
16441 tls_psks = pr_table_nalloc(session.pool, 0, 2);
16442 }
16443
16444 if (pr_table_add(tls_psks, identity, bn, sizeof(BIGNUM *)) < 0) {
16445 pr_log_debug(DEBUG0, MOD_TLS_VERSION
16446 ": error stashing key for identity '%s': %s", identity,
16447 strerror(errno));
16448 BN_free(bn);
16449 }
16450
16451 c = find_config_next(c, c->next, CONF_PARAM, "TLSPreSharedKey", FALSE);
16452 }
16453 #endif /* PSK_MAX_PSK_LEN */
16454 }
16455
16456 static void tls_lookup_renegotiate(server_rec *s) {
16457 #if OPENSSL_VERSION_NUMBER > 0x000907000L
16458 config_rec *c = NULL;
16459
16460 /* Lookup/process any configured TLSRenegotiate parameters. */
16461 c = find_config(s->conf, CONF_PARAM, "TLSRenegotiate", FALSE);
16462 if (c == NULL) {
16463 return;
16464 }
16465
16466 if (c->argc == 0) {
16467 /* Disable all server-side requested renegotiations; clients can still
16468 * request renegotiations.
16469 */
16470 tls_ctrl_renegotiate_timeout = 0;
16471 tls_data_renegotiate_limit = 0;
16472 tls_renegotiate_timeout = 0;
16473 tls_renegotiate_required = FALSE;
16474
16475 } else {
16476 int ctrl_timeout = *((int *) c->argv[0]);
16477 off_t data_limit = *((off_t *) c->argv[1]);
16478 int renegotiate_timeout = *((int *) c->argv[2]);
16479 unsigned char renegotiate_required = *((unsigned char *) c->argv[3]);
16480
16481 if (data_limit > 0) {
16482 tls_data_renegotiate_limit = data_limit;
16483 }
16484
16485 if (renegotiate_timeout > 0) {
16486 tls_renegotiate_timeout = renegotiate_timeout;
16487 }
16488
16489 tls_renegotiate_required = renegotiate_required;
16490
16491 /* Set any control channel renegotiation timers, if need be. */
16492 pr_timer_add(ctrl_timeout ? ctrl_timeout : tls_ctrl_renegotiate_timeout,
16493 -1, &tls_module, tls_ctrl_renegotiate_cb, "SSL/TLS renegotiation");
16494 }
16495 #endif
16496 }
16497
16498 static void tls_lookup_stapling(server_rec *s) {
16499 #if defined(PR_USE_OPENSSL_OCSP)
16500 config_rec *c;
16501
16502 /* Reset to defaults. */
16503 tls_stapling_opts = 0UL;
16504
16505 c = find_config(s->conf, CONF_PARAM, "TLSStaplingOptions", FALSE);
16506 while (c != NULL) {
16507 unsigned long opts = 0;
16508
16509 pr_signals_handle();
16510
16511 opts = *((unsigned long *) c->argv[0]);
16512 tls_stapling_opts |= opts;
16513
16514 c = find_config_next(c, c->next, CONF_PARAM, "TLSStaplingOptions", FALSE);
16515 }
16516
16517 c = find_config(s->conf, CONF_PARAM, "TLSStaplingResponder", FALSE);
16518 if (c != NULL) {
16519 tls_stapling_responder = c->argv[0];
16520
16521 } else {
16522 /* Reset to default. */
16523 tls_stapling_responder = NULL;
16524 }
16525
16526 c = find_config(s->conf, CONF_PARAM, "TLSStaplingTimeout", FALSE);
16527 if (c != NULL) {
16528 tls_stapling_timeout = *((unsigned int *) c->argv[0]);
16529
16530 } else {
16531 /* Reset the default. */
16532 tls_stapling_timeout = TLS_DEFAULT_STAPLING_TIMEOUT;
16533 }
16534
16535 /* If a TLSStaplingCache has been configured, then TLSStapling should
16536 * be enabled by default.
16537 */
16538 if (tls_ocsp_cache != NULL) {
16539 tls_stapling = TRUE;
16540 }
16541
16542 c = find_config(s->conf, CONF_PARAM, "TLSStapling", FALSE);
16543 if (c != NULL) {
16544 tls_stapling = *((int *) c->argv[0]);
16545
16546 } else {
16547 /* Reset the default. */
16548 tls_stapling = FALSE;
16549 }
16550 #endif /* PR_USE_OPENSSL_OCSP */
16551 }
16552
16553 static void tls_lookup_verify(server_rec *s) {
16554 config_rec *c;
16555
16556 /* Clear client verification-related flags. */
16557 tls_flags &= ~TLS_SESS_VERIFY_CLIENT_REQUIRED;
16558 tls_flags &= ~TLS_SESS_VERIFY_CLIENT_OPTIONAL;
16559
16560 /* TLSVerifyClient */
16561 c = find_config(s->conf, CONF_PARAM, "TLSVerifyClient", FALSE);
16562 if (c != NULL) {
16563 unsigned char verify_client;
16564
16565 verify_client = *((unsigned char *) c->argv[0]);
16566 switch (verify_client) {
16567 case 0:
16568 break;
16569
16570 case 1:
16571 tls_flags |= TLS_SESS_VERIFY_CLIENT_REQUIRED;
16572 break;
16573
16574 case 2:
16575 tls_flags |= TLS_SESS_VERIFY_CLIENT_OPTIONAL;
16576 break;
16577
16578 default:
16579 break;
16580 }
16581 }
16582
16583 /* Clear server verification-related flags. */
16584 tls_flags &= ~TLS_SESS_VERIFY_SERVER_NO_DNS;
16585 tls_flags &= ~TLS_SESS_VERIFY_SERVER;
16586
16587 /* TLSVerifyServer */
16588 c = find_config(s->conf, CONF_PARAM, "TLSVerifyServer", FALSE);
16589 if (c != NULL) {
16590 int setting;
16591
16592 setting = *((int *) c->argv[0]);
16593 switch (setting) {
16594 case 2:
16595 tls_flags |= TLS_SESS_VERIFY_SERVER_NO_DNS;
16596 break;
16597
16598 case 1:
16599 tls_flags |= TLS_SESS_VERIFY_SERVER;
16600 break;
16601 }
16602
16603 } else {
16604 tls_flags |= TLS_SESS_VERIFY_SERVER;
16605 }
16606
16607 /* If TLSVerifyClient/Server is on, look up the verification depth. */
16608 if (tls_flags & (TLS_SESS_VERIFY_CLIENT_REQUIRED|TLS_SESS_VERIFY_SERVER|TLS_SESS_VERIFY_SERVER_NO_DNS)) {
16609 int *depth = NULL;
16610
16611 depth = get_param_ptr(s->conf, "TLSVerifyDepth", FALSE);
16612 if (depth != NULL) {
16613 tls_verify_depth = *depth;
16614
16615 } else {
16616 /* Reset the default. */
16617 tls_verify_depth = TLS_DEFAULT_VERIFY_DEPTH;
16618 }
16619 }
16620 }
16621
16622 static void tls_lookup_all(server_rec *s) {
16623 config_rec *c;
16624
16625 /* TLSCACertificate{File,Path} */
16626 tls_ca_file = get_param_ptr(s->conf, "TLSCACertificateFile", FALSE);
16627 tls_ca_path = get_param_ptr(s->conf, "TLSCACertificatePath", FALSE);
16628
16629 /* TLSCARevocation{File,Path} */
16630 tls_crl_file = get_param_ptr(s->conf, "TLSCARevocationFile", FALSE);
16631 tls_crl_path = get_param_ptr(s->conf, "TLSCARevocationPath", FALSE);
16632
16633 /* TLSCertificateChainFile */
16634 tls_ca_chain = get_param_ptr(s->conf, "TLSCertificateChainFile", FALSE);
16635
16636 /* TLS*CertificateFile. Assume that, if no separate key files are configured,
16637 * the keys are in the same file as the corresponding certificate.
16638 */
16639 tls_dsa_cert_file = get_param_ptr(s->conf, "TLSDSACertificateFile", FALSE);
16640 tls_dsa_key_file = get_param_ptr(s->conf, "TLSDSACertificateKeyFile", FALSE);
16641
16642 tls_ec_cert_file = get_param_ptr(s->conf, "TLSECCertificateFile", FALSE);
16643 tls_ec_key_file = get_param_ptr(s->conf, "TLSECCertificateKeyFile", FALSE);
16644
16645 tls_pkcs12_file = get_param_ptr(s->conf, "TLSPKCS12File", FALSE);
16646
16647 tls_rsa_cert_file = get_param_ptr(s->conf, "TLSRSACertificateFile", FALSE);
16648 tls_rsa_key_file = get_param_ptr(s->conf, "TLSRSACertificateKeyFile", FALSE);
16649
16650 /* TLSCipherSuite */
16651 c = find_config(s->conf, CONF_PARAM, "TLSCipherSuite", FALSE);
16652 while (c != NULL) {
16653 int protocol;
16654
16655 pr_signals_handle();
16656
16657 protocol = *((int *) c->argv[1]);
16658
16659 #if OPENSSL_VERSION_NUMBER >= 0x10101000L && \
16660 defined(TLS1_3_VERSION)
16661 if (protocol == TLS_PROTO_TLS_V1_3) {
16662 tlsv13_cipher_suite = c->argv[0];
16663
16664 } else {
16665 tls_cipher_suite = c->argv[0];
16666 }
16667 #else
16668 tls_cipher_suite = c->argv[0];
16669 #endif /* TLS1_3_VERSION */
16670
16671 c = find_config_next(c, c->next, CONF_PARAM, "TLSCipherSuite", FALSE);
16672 }
16673
16674 if (tls_cipher_suite == NULL) {
16675 tls_cipher_suite = TLS_DEFAULT_CIPHER_SUITE;
16676 }
16677
16678 tls_lookup_dh_params(s);
16679
16680 /* TLSECDHCurve */
16681 #if defined(PR_USE_OPENSSL_ECC)
16682 c = find_config(s->conf, CONF_PARAM, "TLSECDHCurve", FALSE);
16683 if (c != NULL) {
16684 tls_ecdh_curve = (void *) c->argv[0];
16685
16686 } else {
16687 /* Reset the default. */
16688 tls_ecdh_curve = NULL;
16689 }
16690 #endif /* PR_USE_OPENSSL_ECC */
16691
16692 /* TLSNextProtocol */
16693 #if !defined(OPENSSL_NO_TLSEXT)
16694 c = find_config(s->conf, CONF_PARAM, "TLSNextProtocol", FALSE);
16695 if (c != NULL) {
16696 tls_use_next_protocol = *((int *) c->argv[0]);
16697
16698 } else {
16699 /* Reset the default. */
16700 tls_use_next_protocol = TRUE;
16701 }
16702 #endif /* !OPENSSL_NO_TLSEXT */
16703
16704 /* TLSOptions */
16705 c = find_config(s->conf, CONF_PARAM, "TLSOptions", FALSE);
16706 while (c != NULL) {
16707 unsigned long opts = 0;
16708
16709 pr_signals_handle();
16710
16711 opts = *((unsigned long *) c->argv[0]);
16712 tls_opts |= opts;
16713
16714 c = find_config_next(c, c->next, CONF_PARAM, "TLSOptions", FALSE);
16715 }
16716
16717 /* If UseReverseDNS is set to off, disable TLS_OPT_VERIFY_CERT_FQDN. */
16718 if (!ServerUseReverseDNS &&
16719 ((tls_opts & TLS_OPT_VERIFY_CERT_FQDN) ||
16720 (tls_opts & TLS_OPT_VERIFY_CERT_CN))) {
16721
16722 if (tls_opts & TLS_OPT_VERIFY_CERT_FQDN) {
16723 tls_opts &= ~TLS_OPT_VERIFY_CERT_FQDN;
16724 tls_log("%s", "reverse DNS off, disabling TLSOption dNSNameRequired");
16725 }
16726
16727 if (tls_opts & TLS_OPT_VERIFY_CERT_CN) {
16728 tls_opts &= ~TLS_OPT_VERIFY_CERT_CN;
16729 tls_log("%s", "reverse DNS off, disabling TLSOption CommonNameRequired");
16730 }
16731 }
16732
16733 /* TLSProtocol */
16734 c = find_config(s->conf, CONF_PARAM, "TLSProtocol", FALSE);
16735 if (c != NULL) {
16736 tls_protocol = *((unsigned int *) c->argv[0]);
16737
16738 } else {
16739 /* Reset the default. */
16740 tls_protocol = TLS_PROTO_DEFAULT;
16741 }
16742
16743 tls_lookup_psks(s);
16744
16745 tls_lookup_renegotiate(s);
16746
16747 /* TLSRequired */
16748 c = find_config(s->conf, CONF_PARAM, "TLSRequired", FALSE);
16749 if (c != NULL) {
16750 tls_required_on_ctrl = *((int *) c->argv[0]);
16751 tls_required_on_data = *((int *) c->argv[1]);
16752 tls_required_on_auth = *((int *) c->argv[2]);
16753
16754 } else {
16755 /* Reset the default. */
16756 tls_required_on_ctrl = 0;
16757 tls_required_on_data = 0;
16758 tls_required_on_auth = 0;
16759 }
16760
16761 /* TLSServerCipherPreference */
16762 #if defined(SSL_OP_CIPHER_SERVER_PREFERENCE)
16763 c = find_config(s->conf, CONF_PARAM, "TLSServerCipherPreference",
16764 FALSE);
16765 if (c != NULL) {
16766 tls_use_server_cipher_preference = *((int *) c->argv[0]);
16767
16768 } else {
16769 /* Reset the default. */
16770 tls_use_server_cipher_preference = TRUE;
16771 }
16772 #endif /* SSL_OP_CIPHER_SERVER_PREFERENCE */
16773
16774 /* TLSServerInfoFile */
16775 #if !defined(OPENSSL_NO_TLSEXT)
16776 # if OPENSSL_VERSION_NUMBER >= 0x10002000L && \
16777 !defined(HAVE_LIBRESSL)
16778 c = find_config(s->conf, CONF_PARAM, "TLSServerInfoFile", FALSE);
16779 if (c != NULL) {
16780 tls_serverinfo_file = c->argv[0];
16781
16782 } else {
16783 /* Reset the default. */
16784 tls_serverinfo_file = NULL;
16785 }
16786 # endif /* OpenSSL-1.0.2 and later */
16787 #endif /* !OPENSSL_NO_TLSEXT */
16788
16789 /* TLSSessionTickets */
16790 #if defined(TLS_USE_SESSION_TICKETS)
16791 c = find_config(s->conf, CONF_PARAM, "TLSSessionTickets", FALSE);
16792 if (c != NULL) {
16793 tls_use_session_tickets = *((int *) c->argv[0]);
16794
16795 } else {
16796 /* Reset the default. */
16797 tls_use_session_tickets = FALSE;
16798 }
16799 #endif /* TLS_USE_SESSION_TICKETS */
16800
16801 tls_lookup_stapling(s);
16802
16803 /* TLSTimeoutHandshake */
16804 c = find_config(s->conf, CONF_PARAM, "TLSTimeoutHandshake", FALSE);
16805 if (c != NULL) {
16806 tls_handshake_timeout = *((unsigned int *) c->argv[0]);
16807
16808 } else {
16809 /* Reset the default. */
16810 tls_handshake_timeout = TLS_DEFAULT_HANDSHAKE_TIMEOUT;
16811 }
16812
16813 tls_lookup_verify(s);
16814 }
16815
16816 /* SSL setters */
16817
16818 static int tls_ssl_set_cert_chain(SSL *ssl) {
16819 #if OPENSSL_VERSION_NUMBER >= 0x10100000L && \
16820 !defined(HAVE_LIBRESSL)
16821 int res;
16822
16823 if (tls_ca_chain == NULL) {
16824 return 0;
16825 }
16826
16827 tls_log("adding certs from '%s' to SSL certificate chain", tls_ca_chain);
16828 PRIVS_ROOT
16829 res = SSL_use_certificate_chain_file(ssl, tls_ca_chain);
16830 PRIVS_RELINQUISH
16831
16832 if (res != 1) {
16833 tls_log("unable to read certificate chain '%s': %s", tls_ca_chain,
16834 tls_get_errors());
16835 return -1;
16836 }
16837 #endif /* OpenSSL 1.1.x and later */
16838
16839 return 0;
16840 }
16841
16842 static int tls_ssl_set_ciphers(SSL *ssl) {
16843 SSL_set_cipher_list(ssl, tls_cipher_suite);
16844
16845 #if OPENSSL_VERSION_NUMBER >= 0x10101000L && \
16846 defined(TLS1_3_VERSION)
16847 if (tlsv13_cipher_suite != NULL) {
16848 SSL_set_ciphersuites(ssl, tlsv13_cipher_suite);
16849 }
16850 #endif /* TLS1_3_VERSION */
16851
16852 return 0;
16853 }
16854
16855 static int tls_ssl_set_crls(SSL *ssl) {
16856 return 0;
16857 }
16858
16859 static int tls_ssl_set_ecdh_curve(SSL *ssl) {
16860 #if defined(PR_USE_OPENSSL_ECC)
16861 # if defined(SSL_CTX_set_ecdh_auto)
16862 if (tls_opts & TLS_OPT_NO_AUTO_ECDH) {
16863 SSL_set_ecdh_auto(ssl, 0);
16864 }
16865 # endif
16866
16867 if (tls_ecdh_curve != NULL) {
16868 # if defined(SSL_CTX_set1_curves_list)
16869 char *curve_names;
16870
16871 curve_names = tls_ecdh_curve;
16872 if (strcasecmp(curve_names, "auto") != 0) {
16873 SSL_set1_curves_list(ssl, curve_names);
16874 }
16875 # else
16876 const EC_KEY *ec_key;
16877
16878 ec_key = tls_ecdh_curve;
16879 SSL_set_tmp_ecdh(ssl, ec_key);
16880 # endif /* pre OpenSSL-1.0.2 */
16881
16882 SSL_set_options(ssl, SSL_OP_SINGLE_ECDH_USE);
16883 } else {
16884 # if OPENSSL_VERSION_NUMBER < 0x10100000L
16885 SSL_set_tmp_ecdh_callback(ssl, tls_ecdh_cb);
16886 # endif /* Before OpenSSL-1.1.x */
16887 }
16888 #endif /* PR_USE_OPENSS_ECC */
16889
16890 return 0;
16891 }
16892
16893 static int tls_ssl_set_psks(SSL *ssl) {
16894 #if defined(PSK_MAX_PSK_LEN)
16895 if (tls_psks == NULL ||
16896 pr_table_count(tls_psks) == 0) {
16897 SSL_set_psk_server_callback(ssl, NULL);
16898 return 0;
16899 }
16900
16901 pr_trace_msg(trace_channel, 9,
16902 "enabling support for PSK identities (%d)", pr_table_count(tls_psks));
16903 SSL_set_psk_server_callback(ssl, tls_lookup_psk);
16904 #endif /* PSK_MAX_PSK_LEN */
16905
16906 return 0;
16907 }
16908
16909 static int tls_ssl_set_options(SSL *ssl) {
16910
16911 #if OPENSSL_VERSION_NUMBER > 0x009080cfL
16912 SSL_clear_options(ssl, SSL_OP_CIPHER_SERVER_PREFERENCE);
16913
16914 /* The OpenSSL team realized that the flag added in 0.9.8l, the
16915 * SSL3_FLAGS_ALLOW_UNSAFE_LEGACY_RENEGOTIATION flag, was a bad idea.
16916 * So in later versions, it was changed to a context flag,
16917 * SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION.
16918 */
16919 SSL_clear_options(ssl, SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION);
16920 if (tls_opts & TLS_OPT_ALLOW_CLIENT_RENEGOTIATIONS) {
16921 SSL_set_options(ssl, SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION);
16922 }
16923 #endif
16924
16925 #if defined(SSL_OP_CIPHER_SERVER_PREFERENCE)
16926 if (tls_use_server_cipher_preference == TRUE) {
16927 SSL_set_options(ssl, SSL_OP_CIPHER_SERVER_PREFERENCE);
16928 }
16929 #endif /* SSL_OP_CIPHER_SERVER_PREFERENCE */
16930
16931 #if OPENSSL_VERSION_NUMBER > 0x000907000L
16932 /* Install a callback for logging OpenSSL message information, if requested.
16933 */
16934 if (tls_opts & TLS_OPT_ENABLE_DIAGS) {
16935 tls_log("%s",
16936 "TLSOption EnableDiags enabled, setting diagnostics callback");
16937 SSL_set_msg_callback(ssl, tls_msg_cb);
16938
16939 } else {
16940 SSL_set_msg_callback(ssl, NULL);
16941 }
16942 #endif
16943
16944 return 0;
16945 }
16946
16947 static int tls_ssl_set_next_protocol(SSL *ssl) {
16948 #if !defined(OPENSSL_NO_TLSEXT)
16949 register unsigned int i;
16950 const char *proto = TLS_DEFAULT_NEXT_PROTO;
16951 size_t encoded_protolen, proto_len;
16952 unsigned char *encoded_proto;
16953 struct tls_next_proto *next_proto;
16954 SSL_CTX *ctx;
16955
16956 ctx = SSL_get_SSL_CTX(ssl);
16957
16958 if (tls_use_next_protocol == FALSE) {
16959 # if defined(PR_USE_OPENSSL_NPN)
16960 SSL_CTX_set_next_protos_advertised_cb(ctx, NULL, NULL);
16961 # endif /* NPN */
16962
16963 # if defined(PR_USE_OPENSSL_ALPN)
16964 SSL_CTX_set_alpn_select_cb(ctx, NULL, NULL);
16965 # endif /* ALPN */
16966
16967 return 0;
16968 }
16969
16970 proto_len = strlen(proto);
16971 encoded_protolen = proto_len + 1;
16972 encoded_proto = palloc(session.pool, encoded_protolen);
16973 encoded_proto[0] = proto_len;
16974 for (i = 0; i < proto_len; i++) {
16975 encoded_proto[i+1] = proto[i];
16976 }
16977
16978 next_proto = palloc(session.pool, sizeof(struct tls_next_proto));
16979 next_proto->proto = pstrdup(session.pool, proto);
16980 next_proto->encoded_proto = encoded_proto;
16981 next_proto->encoded_protolen = encoded_protolen;
16982
16983 # if defined(PR_USE_OPENSSL_NPN)
16984 SSL_CTX_set_next_protos_advertised_cb(ctx, tls_npn_advertised_cb, next_proto);
16985 # endif /* NPN */
16986
16987 # if defined(PR_USE_OPENSSL_ALPN)
16988 SSL_CTX_set_alpn_select_cb(ctx, tls_alpn_select_cb, next_proto);
16989 # endif /* ALPN */
16990 #endif /* !OPENSSL_NO_TLSEXT */
16991
16992 return 0;
16993 }
16994
16995 static int tls_ssl_set_protocol(server_rec *s, SSL *ssl) {
16996 int all_proto, disabled_proto;
16997 unsigned int enabled_proto_count = 0;
16998 const char *enabled_proto_str = NULL;
16999
17000 /* First, make sure ALL protocol versions are disabled by default. */
17001 all_proto = get_disabled_protocols(0);
17002 SSL_set_options(ssl, all_proto);
17003
17004 disabled_proto = get_disabled_protocols(tls_protocol);
17005
17006 /* Per the comments in <ssl/ssl.h>, SSL_CTX_set_options() uses |= on
17007 * the previous value. This means we can easily OR in our new option
17008 * values with any previously set values.
17009 */
17010 enabled_proto_str = tls_get_proto_str(s->pool, tls_protocol,
17011 &enabled_proto_count);
17012
17013 pr_log_debug(DEBUG8, MOD_TLS_VERSION ": supporting %s %s", enabled_proto_str,
17014 enabled_proto_count != 1 ? "protocols" : "protocol only");
17015
17016 /* Now we clear all of the NO_ protocol version options EXCEPT for the
17017 * enabled versions.
17018 *
17019 * This is more convoluted than it should be, because of the expression
17020 * of enabled protocol versions via OP_NO_ negations, and bitmasking.
17021 */
17022 #if OPENSSL_VERSION_NUMBER > 0x000908000L
17023 SSL_clear_options(ssl, all_proto|disabled_proto);
17024 #endif
17025 SSL_set_options(ssl, disabled_proto);
17026
17027 return 0;
17028 }
17029
17030 static int tls_ssl_set_renegotiations(SSL *ssl) {
17031 #if defined(SSL_OP_NO_RENEGOTIATION)
17032 if (tls_ctrl_renegotiate_timeout == 0 &&
17033 tls_data_renegotiate_limit == 0 &&
17034 tls_renegotiate_timeout == 0 &&
17035 tls_renegotiate_required == FALSE) {
17036 /* If server-requested renegotiations are disabled, reject
17037 * client-initiated renegotiations, too.
17038 */
17039 SSL_set_options(ssl, SSL_OP_NO_RENEGOTIATION);
17040 }
17041 #endif /* SSL_OP_NO_RENEGOTIATION */
17042
17043 return 0;
17044 }
17045
17046 static int tls_ssl_set_session_tickets(SSL *ssl) {
17047 #if defined(TLS_USE_SESSION_TICKETS) && \
17048 defined(SSL_OP_NO_TICKET)
17049 if (tls_use_session_tickets == TRUE) {
17050 /* Ensure that tickets are enabled in the SSL options. */
17051 SSL_clear_options(ssl, SSL_OP_NO_TICKET);
17052
17053 } else {
17054 # ifdef TLS1_3_VERSION
17055 /* Disable session tickets unless it's a TLSv1.3 session. */
17056 if (SSL_version(ssl) != TLS1_3_VERSION) {
17057 SSL_set_options(ssl, SSL_OP_NO_TICKET);
17058 }
17059 # else
17060 /* Disable session tickets. */
17061 SSL_set_options(ssl, SSL_OP_NO_TICKET);
17062 # endif /* TLS1_3_VERSION */
17063 }
17064 #endif /* TLS_USE_SESSION_TICKETS and SSL_OP_NO_TICKET */
17065
17066 return 0;
17067 }
17068
17069 static int tls_ssl_set_verify(SSL *ssl) {
17070 int verify_mode = 0;
17071
17072 if (tls_flags & TLS_SESS_VERIFY_CLIENT_OPTIONAL) {
17073 verify_mode = SSL_VERIFY_PEER;
17074 }
17075
17076 if (tls_flags & TLS_SESS_VERIFY_CLIENT_REQUIRED) {
17077 /* If we are verifying clients, make sure the client sends a cert;
17078 * the protocol allows for the client to disregard a request for
17079 * its cert by the server.
17080 */
17081 verify_mode |= (SSL_VERIFY_PEER|SSL_VERIFY_FAIL_IF_NO_PEER_CERT);
17082 }
17083
17084 if (verify_mode != 0) {
17085 SSL_set_verify(ssl, verify_mode, tls_verify_cb);
17086
17087 /* Note: we add one to the configured depth purposefully. As noted
17088 * in the OpenSSL man pages, the verification process will silently
17089 * stop at the configured depth, and the error messages ensuing will
17090 * be that of an incomplete certificate chain, rather than the
17091 * "chain too long" error that might be expected. To log the "chain
17092 * too long" condition, we add one to the configured depth, and catch,
17093 * in the verify callback, the exceeding of the actual depth.
17094 */
17095 SSL_set_verify_depth(ssl, tls_verify_depth + 1);
17096 }
17097
17098 return 0;
17099 }
17100
17101 static int tls_ssl_set_session_id_context(server_rec *s, SSL *ssl) {
17102 SSL_SESSION *sess;
17103
17104 /* Update the session ID context to use. This is important; it ensures
17105 * that the session IDs for this particular vhost will differ from those
17106 * for another vhost. An external TLS session cache will possibly
17107 * cache sessions from all vhosts together, and we need to keep them
17108 * separate.
17109 */
17110
17111 pr_trace_msg(trace_channel, 19,
17112 "setting session ID context '%u' (%lu bytes) on SSL %p", s->sid,
17113 sizeof(s->sid), ssl);
17114 SSL_set_session_id_context(ssl, (unsigned char *) &(s->sid), sizeof(s->sid));
17115
17116 #if defined(PR_USE_OPENSSL_SSL_SESSION_SET1_ID_CONTEXT)
17117 sess = SSL_get_session(ssl);
17118 if (sess != NULL) {
17119 pr_trace_msg(trace_channel, 19,
17120 "setting session ID context '%u' (%lu bytes) on SSL_SESSION %p (SSL %p)",
17121 s->sid, sizeof(s->sid), sess, ssl);
17122 SSL_SESSION_set1_id_context(sess, (unsigned char *) &(s->sid),
17123 sizeof(s->sid));
17124 }
17125 #endif
17126
17127 return 0;
17128 }
17129
17130 static char *get_sess_id_text(BIO *bio, const unsigned char *id,
17131 unsigned int idsz) {
17132 char *data = NULL;
17133 long datalen;
17134
17135 if (idsz > 0) {
17136 register unsigned int i;
17137
17138 for (i = 0; i < idsz; i++) {
17139 BIO_printf(bio, "%02x", id[i]);
17140 }
17141
17142 } else {
17143 BIO_printf(bio, "%s", "NONE");
17144 }
17145
17146 datalen = BIO_get_mem_data(bio, &data);
17147 if (data != NULL) {
17148 data[datalen] = '\0';
17149
17150 } else {
17151 data = "UNKNOWN";
17152 }
17153
17154 return data;
17155 }
17156
17157 static int tls_sni_sess_tab_add_cb(SSL *ssl, SSL_SESSION *sess) {
17158 unsigned char *sess_id;
17159 unsigned int sess_id_len;
17160 void *key;
17161
17162 #if OPENSSL_VERSION_NUMBER > 0x000908000L
17163 sess_id = (unsigned char *) SSL_SESSION_get_id(sess, &sess_id_len);
17164 #else
17165 /* XXX Directly accessing these fields cannot be a Good Thing. */
17166 sess_id = sess->session_id;
17167 sess_id_len = sess->session_id_length;
17168 #endif
17169
17170 key = pr_table_pcalloc(tls_sni_sess_tab, sess_id_len);
17171 memcpy(key, sess_id, sess_id_len);
17172
17173 if (pr_table_kadd(tls_sni_sess_tab, key, (size_t) sess_id_len,
17174 sess, sizeof(sess)) < 0) {
17175 pr_trace_msg(trace_channel, 3, "error adding SSL_SESSION to SNI table: %s",
17176 strerror(errno));
17177 return 0;
17178 }
17179
17180 if (pr_trace_get_level(trace_channel) >= 29) {
17181 BIO *bio;
17182 char *data = NULL;
17183 long datalen;
17184
17185 bio = BIO_new(BIO_s_mem());
17186 SSL_SESSION_print(bio, sess);
17187
17188 datalen = BIO_get_mem_data(bio, &data);
17189 if (data != NULL) {
17190 data[datalen] = '\0';
17191
17192 pr_trace_msg(trace_channel, 29, "added session to SNI table:\n%.*s",
17193 (int) datalen, data);
17194 }
17195
17196 BIO_free(bio);
17197
17198 } else {
17199 BIO *bio;
17200 char *text;
17201
17202 bio = BIO_new(BIO_s_mem());
17203 text = get_sess_id_text(bio, sess_id, sess_id_len);
17204 pr_trace_msg(trace_channel, 9, "added session (ID %s) to SNI table", text);
17205 BIO_free(bio);
17206 }
17207
17208 return 0;
17209 }
17210
17211 static SSL_SESSION *tls_sni_sess_tab_get_cb(SSL *ssl,
17212 const unsigned char *sess_id, int sess_id_len, int *do_copy) {
17213 SSL_SESSION *sess = NULL;
17214 const void *val;
17215 BIO *bio;
17216 char *text;
17217
17218 /* Indicate to OpenSSL that the ref count should not be incremented
17219 * by setting the do_copy pointer to zero.
17220 */
17221 *do_copy = 0;
17222
17223 bio = BIO_new(BIO_s_mem());
17224 text = get_sess_id_text(bio, sess_id, sess_id_len);
17225 pr_trace_msg(trace_channel, 9, "getting session (ID %s) from SNI table",
17226 text);
17227
17228 val = pr_table_kget(tls_sni_sess_tab, (const void *) sess_id,
17229 (size_t) sess_id_len, NULL);
17230 if (val == NULL) {
17231 pr_trace_msg(trace_channel, 9, "session (ID %s) not found in SNI table",
17232 text);
17233 BIO_free(bio);
17234
17235 errno = ENOENT;
17236 return NULL;
17237 }
17238
17239 sess = (SSL_SESSION *) val;
17240
17241 if (pr_trace_get_level(trace_channel) >= 29) {
17242 char *data = NULL;
17243 long datalen;
17244
17245 BIO_free(bio);
17246 bio = BIO_new(BIO_s_mem());
17247 SSL_SESSION_print(bio, sess);
17248
17249 datalen = BIO_get_mem_data(bio, &data);
17250 if (data != NULL) {
17251 data[datalen] = '\0';
17252
17253 pr_trace_msg(trace_channel, 29, "found session in SNI table:\n%.*s",
17254 (int) datalen, data);
17255 }
17256
17257 } else {
17258 pr_trace_msg(trace_channel, 9, "found session (ID %s) in SNI table", text);
17259 }
17260
17261 BIO_free(bio);
17262 return sess;
17263 }
17264
17265 static void tls_sni_sess_tab_delete_cb(SSL_CTX *ctx, SSL_SESSION *sess) {
17266 unsigned char *sess_id;
17267 unsigned int sess_id_len;
17268 const void *val;
17269 BIO *bio;
17270 char *text;
17271
17272 #if OPENSSL_VERSION_NUMBER > 0x000908000L
17273 sess_id = (unsigned char *) SSL_SESSION_get_id(sess, &sess_id_len);
17274 #else
17275 /* XXX Directly accessing these fields cannot be a Good Thing. */
17276 sess_id = sess->session_id;
17277 sess_id_len = sess->session_id_length;
17278 #endif
17279
17280 bio = BIO_new(BIO_s_mem());
17281 text = get_sess_id_text(bio, sess_id, sess_id_len);
17282 pr_trace_msg(trace_channel, 9, "removing session (ID %s) from SNI table",
17283 text);
17284
17285 val = pr_table_kremove(tls_sni_sess_tab, (const void *) sess_id,
17286 (size_t) sess_id_len, NULL);
17287 if (val == NULL) {
17288 if (errno == ENOENT) {
17289 pr_trace_msg(trace_channel, 9, "no session (ID %s) found in SNI table",
17290 text);
17291
17292 } else {
17293 pr_trace_msg(trace_channel, 9,
17294 "error removing session (ID %s) from SNI table: %s", text,
17295 strerror(errno));
17296 }
17297 }
17298
17299 BIO_free(bio);
17300 }
17301
17302 static int tls_ssl_set_all(server_rec *s, SSL *ssl) {
17303 SSL_CTX *ctx = NULL;
17304 long cache_mode;
17305
17306 /* This is the key to switching CAs, cert chains, etc for the SSL object
17307 * for SNI support: build an entirely new SSL_CTX, using the new/proper CAs
17308 * et al, and set that on the SSL object.
17309 */
17310 ctx = tls_init_ctx(s);
17311 if (ctx == NULL) {
17312 return -1;
17313 }
17314
17315 pr_trace_msg(trace_channel, 19,
17316 "setting new SSL_CTX for future data transfers");
17317
17318 /* Update the SSL_CTX for the possibly changed <VirtualHost> config.
17319 *
17320 * Even though our SSL has already been created from this SSL_CTX,
17321 * which means any SSL_CTX changes WILL NOT be conveyed to our SSL,
17322 * we update it for any data transfer SSL objects later.
17323 */
17324 if (tls_ctx_set_all(s, ctx) < 0) {
17325 return -1;
17326 }
17327
17328 /* Copy the existing session cache settings into the new SSL_CTX. */
17329 cache_mode = SSL_CTX_get_session_cache_mode(ssl_ctx);
17330 SSL_CTX_set_session_cache_mode(ctx, cache_mode);
17331
17332 if (cache_mode == SSL_SESS_CACHE_OFF) {
17333 /* Make sure we automatically relax the "SSL session reuse required
17334 * for data connections" requirement; to enforce such a requirement
17335 * TLS session caching MUST be enabled. So if session caching has been
17336 * explicitly disabled, relax that policy as well.
17337 */
17338 tls_opts |= TLS_OPT_NO_SESSION_REUSE_REQUIRED;
17339 }
17340
17341 /* Use an in-memory table-based session store to preserve sessions
17342 * across the SNI-mandated SSL_CTX changes, in order to preserve
17343 * session resumption for data transfers (Issue #924).
17344 *
17345 * Note that this is only necessary if a TLSSessionCache has not been
17346 * configured.
17347 */
17348
17349 if (SSL_CTX_sess_get_new_cb(ssl_ctx) == NULL) {
17350 tls_sni_sess_tab = pr_table_alloc(session.pool, 0);
17351
17352 /* Yes, it looks strange to be setting these callbacks on the old
17353 * SSL_CTX, the one we will be replacing with our new SNI SSL_CTX.
17354 *
17355 * However, that old SSL_CTX is preserved (and used!) in the SSL object
17356 * via the initial_ctx, and thus its callbacks are used when adding
17357 * sessions. And later, for data transfers, the SNI SSL_CTX callbacks
17358 * will be used for session lookup. Fun, huh?
17359 */
17360 SSL_CTX_sess_set_new_cb(ssl_ctx, tls_sni_sess_tab_add_cb);
17361 SSL_CTX_sess_set_get_cb(ssl_ctx, tls_sni_sess_tab_get_cb);
17362 SSL_CTX_sess_set_remove_cb(ssl_ctx, tls_sni_sess_tab_delete_cb);
17363 }
17364
17365 SSL_CTX_sess_set_new_cb(ctx, SSL_CTX_sess_get_new_cb(ssl_ctx));
17366 SSL_CTX_sess_set_get_cb(ctx, SSL_CTX_sess_get_get_cb(ssl_ctx));
17367 SSL_CTX_sess_set_remove_cb(ctx, SSL_CTX_sess_get_remove_cb(ssl_ctx));
17368 SSL_CTX_set_timeout(ctx, SSL_CTX_get_timeout(ssl_ctx));
17369
17370 /* We MUST update the session ID context for the current SSL before we
17371 * replace its SSL_CTX, due to logic in the SSL_set_SSL_CTX internals.
17372 */
17373 if (tls_ssl_set_session_id_context(s, ssl) < 0 ||
17374 tls_ctx_set_session_id_context(s, ctx) < 0) {
17375 return -1;
17376 }
17377
17378 /* Inexplicable OpenSSL errors occur if the cert chain is updated after
17379 * calling SSL_set_SSL_CTX, so we do it beforehand.
17380 */
17381 if (tls_ssl_set_cert_chain(ssl) < 0) {
17382 return -1;
17383 }
17384
17385 #if OPENSSL_VERSION_NUMBER > 0x009080cfL
17386 /* Note that it is important that we update the SSL with the new SSL_CTX
17387 * AFTER it has been provisioned. That way, the new/changed certs in the
17388 * SSL_CTX will be properly copied/updated in the SSL object.
17389 */
17390 ctx = SSL_set_SSL_CTX(ssl, ctx);
17391 #endif
17392
17393 if (ssl_ctx != NULL) {
17394 /* Try not to leak memory. */
17395 SSL_CTX_free(ssl_ctx);
17396 }
17397
17398 ssl_ctx = ctx;
17399
17400 pr_trace_msg(trace_channel, 19, "resetting SSL for ctrl connection");
17401
17402 if (tls_ssl_set_ciphers(ssl) < 0) {
17403 return -1;
17404 }
17405
17406 if (tls_ssl_set_crls(ssl) < 0) {
17407 return -1;
17408 }
17409
17410 if (tls_ssl_set_ecdh_curve(ssl) < 0) {
17411 return -1;
17412 }
17413
17414 if (tls_ssl_set_psks(ssl) < 0) {
17415 return -1;
17416 }
17417
17418 if (tls_ssl_set_options(ssl) < 0) {
17419 return -1;
17420 }
17421
17422 if (tls_ssl_set_next_protocol(ssl) < 0) {
17423 return -1;
17424 }
17425
17426 if (tls_ssl_set_protocol(s, ssl) < 0) {
17427 return -1;
17428 }
17429
17430 if (tls_ssl_set_renegotiations(ssl) < 0) {
17431 return -1;
17432 }
17433
17434 /* Note that we set this after setting the protocol versions, since the
17435 * supported protocol version flags will affect session tickets, due to
17436 * TLSv1.3' use of tickets.
17437 */
17438 if (tls_ssl_set_session_tickets(ssl) < 0) {
17439 return -1;
17440 }
17441
17442 if (tls_ssl_set_verify(ssl) < 0) {
17443 return -1;
17444 }
17445
17446 return 0;
17447 }
17448
17449 /* SSL_CTX setters */
17450
17451 static int tls_ctx_set_ca_certs(SSL_CTX *ctx) {
17452 if (tls_ca_file == NULL &&
17453 tls_ca_path == NULL) {
17454 /* Default to using locations set in the OpenSSL config file. */
17455 pr_trace_msg(trace_channel, 9,
17456 "using default OpenSSL verification locations (see $SSL_CERT_DIR "
17457 "environment variable)");
17458
17459 if (SSL_CTX_set_default_verify_paths(ctx) != 1) {
17460 tls_log("error setting default verification locations: %s",
17461 tls_get_errors());
17462 }
17463
17464 return 0;
17465 }
17466
17467 /* Set the locations used for verifying certificates. */
17468 PRIVS_ROOT
17469 if (SSL_CTX_load_verify_locations(ctx, tls_ca_file, tls_ca_path) != 1) {
17470 PRIVS_RELINQUISH
17471
17472 tls_log("unable to set CA verification using file '%s' or directory '%s': "
17473 "%s", tls_ca_file ? tls_ca_file : "(none)",
17474 tls_ca_path ? tls_ca_path : "(none)", tls_get_errors());
17475 return -1;
17476 }
17477 PRIVS_RELINQUISH
17478
17479 if (tls_ca_file != NULL) {
17480 pr_trace_msg(trace_channel, 19, "using CA verification file '%s'",
17481 tls_ca_file);
17482 }
17483
17484 if (tls_ca_path != NULL) {
17485 pr_trace_msg(trace_channel, 19, "using CA verification directory '%s'",
17486 tls_ca_path);
17487 }
17488
17489 if (tls_ca_file != NULL) {
17490 STACK_OF(X509_NAME) *sk;
17491
17492 /* Use SSL_load_client_CA_file() to load all of the CA certs (since
17493 * there can be more than one) from the TLSCACertificateFile. The
17494 * entire list of CAs in that file will be present to the client as
17495 * the "acceptable client CA" list.
17496 */
17497
17498 PRIVS_ROOT
17499 sk = SSL_load_client_CA_file(tls_ca_file);
17500 PRIVS_RELINQUISH
17501
17502 if (sk != NULL) {
17503 SSL_CTX_set_client_CA_list(ctx, sk);
17504
17505 } else {
17506 tls_log("unable to read certificates in '%s': %s", tls_ca_file,
17507 tls_get_errors());
17508 }
17509 }
17510
17511 if (tls_ca_path != NULL) {
17512 DIR *cacertdir = NULL;
17513
17514 PRIVS_ROOT
17515 cacertdir = opendir(tls_ca_path);
17516 PRIVS_RELINQUISH
17517
17518 if (cacertdir != NULL) {
17519 struct dirent *cadent = NULL;
17520 pool *tmp_pool = make_sub_pool(permanent_pool);
17521
17522 while ((cadent = readdir(cacertdir)) != NULL) {
17523 FILE *cacertf;
17524 char *cacertname;
17525
17526 pr_signals_handle();
17527
17528 /* Skip dot directories. */
17529 if (is_dotdir(cadent->d_name)) {
17530 continue;
17531 }
17532
17533 cacertname = pdircat(tmp_pool, tls_ca_path, cadent->d_name, NULL);
17534
17535 PRIVS_ROOT
17536 cacertf = fopen(cacertname, "r");
17537 PRIVS_RELINQUISH
17538
17539 if (cacertf != NULL) {
17540 X509 *x509;
17541
17542 x509 = PEM_read_X509(cacertf, NULL, NULL, NULL);
17543 if (x509 != NULL) {
17544 if (SSL_CTX_add_client_CA(ctx, x509) != 1) {
17545 tls_log("error adding '%s' to client CA list: %s", cacertname,
17546 tls_get_errors());
17547 }
17548
17549 } else {
17550 tls_log("unable to read '%s': %s", cacertname, tls_get_errors());
17551 }
17552
17553 fclose(cacertf);
17554
17555 } else {
17556 tls_log("unable to open '%s': %s", cacertname, strerror(errno));
17557 }
17558 }
17559
17560 destroy_pool(tmp_pool);
17561 closedir(cacertdir);
17562
17563 } else {
17564 tls_log("unable to add CAs in '%s': %s", tls_ca_path, strerror(errno));
17565 }
17566 }
17567
17568 return 0;
17569 }
17570
17571 static int tls_ctx_set_dsa_cert(SSL_CTX *ctx, X509 **dsa_cert) {
17572 X509 *cert;
17573 FILE *fh = NULL;
17574 int res, xerrno;
17575 const char *key_file = NULL;
17576
17577 if (tls_dsa_cert_file == NULL) {
17578 return 0;
17579 }
17580
17581 PRIVS_ROOT
17582 fh = fopen(tls_dsa_cert_file, "r");
17583 xerrno = errno;
17584 if (fh == NULL) {
17585 PRIVS_RELINQUISH
17586 tls_log("error reading TLSDSACertificateFile '%s': %s", tls_dsa_cert_file,
17587 strerror(xerrno));
17588 errno = xerrno;
17589 return -1;
17590 }
17591
17592 /* Assume that if no separate TLSDSACertificateKeyFile was configured (or
17593 * that if the configured TLSDSACertificateKeyFile is to the same path as
17594 * the TLSDSACertificateFile), that the cert and key are in the same file.
17595 * In that case, the file contains sensitive data, and we do not want it
17596 * lingering around in stdio buffers.
17597 */
17598 if (tls_dsa_key_file == NULL ||
17599 strcmp(tls_dsa_cert_file, tls_dsa_key_file) == 0) {
17600 (void) setvbuf(fh, NULL, _IONBF, 0);
17601 }
17602
17603 cert = read_cert(fh, ctx);
17604 if (cert == NULL) {
17605 PRIVS_RELINQUISH
17606 tls_log("error reading TLSDSACertificateFile '%s': %s", tls_dsa_cert_file,
17607 tls_get_errors());
17608 fclose(fh);
17609 return -1;
17610 }
17611
17612 fclose(fh);
17613
17614 /* SSL_CTX_use_certificate() will increment the refcount on cert, so we
17615 * can safely call X509_free() on it. However, we need to keep that
17616 * pointer around until after the handling of a cert chain file.
17617 */
17618 res = SSL_CTX_use_certificate(ctx, cert);
17619 if (res <= 0) {
17620 PRIVS_RELINQUISH
17621
17622 tls_log("error loading TLSDSACertificateFile '%s': %s", tls_dsa_cert_file,
17623 tls_get_errors());
17624 return -1;
17625 }
17626
17627 *dsa_cert = cert;
17628 pr_trace_msg(trace_channel, 19, "loaded DSA server certificate from '%s'",
17629 tls_dsa_cert_file);
17630
17631 key_file = tls_dsa_key_file;
17632 if (key_file == NULL) {
17633 /* Assume the private key is in the cert file. */
17634 key_file = tls_dsa_cert_file;
17635 }
17636
17637 if (tls_pkey != NULL) {
17638 tls_pkey->flags |= TLS_PKEY_USE_DSA;
17639 tls_pkey->flags &= ~(TLS_PKEY_USE_RSA|TLS_PKEY_USE_EC);
17640 }
17641
17642 res = SSL_CTX_use_PrivateKey_file(ctx, key_file, X509_FILETYPE_PEM);
17643 if (res <= 0) {
17644 PRIVS_RELINQUISH
17645
17646 tls_log("error loading TLSDSACertificateKeyFile '%s': %s", key_file,
17647 tls_get_errors());
17648 return -1;
17649 }
17650
17651 res = SSL_CTX_check_private_key(ctx);
17652 if (res != 1) {
17653 PRIVS_RELINQUISH
17654
17655 tls_log("error checking key from TLSDSACertificateKeyFile '%s': %s",
17656 key_file, tls_get_errors());
17657 return -1;
17658 }
17659 PRIVS_RELINQUISH
17660
17661 return 0;
17662 }
17663
17664 static int tls_ctx_set_ec_cert(SSL_CTX *ctx, X509 **ec_cert) {
17665 #if defined(PR_USE_OPENSSL_ECC)
17666 X509 *cert;
17667 FILE *fh = NULL;
17668 int res, xerrno;
17669 const char *key_file = NULL;
17670
17671 if (tls_ec_cert_file == NULL) {
17672 return 0;
17673 }
17674
17675 PRIVS_ROOT
17676 fh = fopen(tls_ec_cert_file, "r");
17677 xerrno = errno;
17678 if (fh == NULL) {
17679 PRIVS_RELINQUISH
17680 tls_log("error reading TLSECCertificateFile '%s': %s", tls_ec_cert_file,
17681 strerror(xerrno));
17682 errno = xerrno;
17683 return -1;
17684 }
17685
17686 /* Assume that if no separate TLSECCertificateKeyFile was configured (or
17687 * that if the configured TLSECCertificateKeyFile is to the same path as
17688 * the TLSECCertificateFile), that the cert and key are in the same file.
17689 * In that case, the file contains sensitive data, and we do not want it
17690 * lingering around in stdio buffers.
17691 */
17692 if (tls_ec_key_file == NULL ||
17693 strcmp(tls_ec_cert_file, tls_ec_key_file) == 0) {
17694 (void) setvbuf(fh, NULL, _IONBF, 0);
17695 }
17696
17697 cert = read_cert(fh, ctx);
17698 if (cert == NULL) {
17699 PRIVS_RELINQUISH
17700 tls_log("error reading TLSECCertificateFile '%s': %s", tls_ec_cert_file,
17701 tls_get_errors());
17702 fclose(fh);
17703 return -1;
17704 }
17705
17706 fclose(fh);
17707
17708 /* SSL_CTX_use_certificate() will increment the refcount on cert, so we
17709 * can safely call X509_free() on it. However, we need to keep that
17710 * pointer around until after the handling of a cert chain file.
17711 */
17712 res = SSL_CTX_use_certificate(ctx, cert);
17713 if (res <= 0) {
17714 PRIVS_RELINQUISH
17715
17716 tls_log("error loading TLSECCertificateFile '%s': %s", tls_ec_cert_file,
17717 tls_get_errors());
17718 return -1;
17719 }
17720
17721 *ec_cert = cert;
17722 pr_trace_msg(trace_channel, 19, "loaded EC server certificate from '%s'",
17723 tls_ec_cert_file);
17724
17725 key_file = tls_ec_key_file;
17726 if (key_file == NULL) {
17727 /* Assume the private key is in the cert file. */
17728 key_file = tls_ec_cert_file;
17729 }
17730
17731 if (tls_pkey != NULL) {
17732 tls_pkey->flags |= TLS_PKEY_USE_EC;
17733 tls_pkey->flags &= ~(TLS_PKEY_USE_RSA|TLS_PKEY_USE_DSA);
17734 }
17735
17736 res = SSL_CTX_use_PrivateKey_file(ctx, key_file, X509_FILETYPE_PEM);
17737 if (res <= 0) {
17738 PRIVS_RELINQUISH
17739
17740 tls_log("error loading TLSECCertificateKeyFile '%s': %s", key_file,
17741 tls_get_errors());
17742 return -1;
17743 }
17744
17745 res = SSL_CTX_check_private_key(ctx);
17746 if (res != 1) {
17747 PRIVS_RELINQUISH
17748
17749 tls_log("error checking key from TLSECCertificateKeyFile '%s': %s",
17750 key_file, tls_get_errors());
17751 return -1;
17752 }
17753
17754 PRIVS_RELINQUISH
17755 #endif /* PR_USE_OPENSSL_ECC */
17756
17757 return 0;
17758 }
17759
17760 static int tls_ctx_set_pkcs12_cert(SSL_CTX *ctx, X509 **dsa_cert,
17761 X509 **ec_cert, X509 **rsa_cert) {
17762 PKCS12 *p12 = NULL;
17763 X509 *cert = NULL;
17764 EVP_PKEY *pkey = NULL;
17765 FILE *fh;
17766 int res, xerrno;
17767 char *passwd = "";
17768
17769 if (tls_pkcs12_file == NULL) {
17770 return 0;
17771 }
17772
17773 if (tls_pkey) {
17774 passwd = tls_pkey->pkcs12_passwd;
17775 }
17776
17777 PRIVS_ROOT
17778 fh = fopen(tls_pkcs12_file, "r");
17779 xerrno = errno;
17780 if (fh == NULL) {
17781 PRIVS_RELINQUISH
17782
17783 tls_log("error opening TLSPKCS12File '%s': %s", tls_pkcs12_file,
17784 strerror(xerrno));
17785 errno = xerrno;
17786 return -1;
17787 }
17788
17789 /* As the file may contain sensitive data, we do not want it lingering
17790 * around in stdio buffers.
17791 */
17792 (void) setvbuf(fh, NULL, _IONBF, 0);
17793
17794 /* Note that this should NOT fail; we will have already parsed the PKCS12
17795 * file, in order to get the password and key passphrases.
17796 */
17797 p12 = d2i_PKCS12_fp(fh, NULL);
17798 if (p12 == NULL) {
17799 PRIVS_RELINQUISH
17800
17801 tls_log("error reading TLSPKCS12File '%s': %s", tls_pkcs12_file,
17802 tls_get_errors());
17803 fclose(fh);
17804 return -1;
17805 }
17806
17807 fclose(fh);
17808
17809 /* XXX Need to add support for any CA certs contained in the PKCS12 file. */
17810 if (PKCS12_parse(p12, passwd, &pkey, &cert, NULL) != 1) {
17811 PRIVS_RELINQUISH
17812
17813 tls_log("error parsing info in TLSPKCS12File '%s': %s", tls_pkcs12_file,
17814 tls_get_errors());
17815
17816 PKCS12_free(p12);
17817
17818 if (cert != NULL) {
17819 X509_free(cert);
17820 }
17821
17822 if (pkey != NULL) {
17823 EVP_PKEY_free(pkey);
17824 }
17825
17826 return -1;
17827 }
17828
17829 /* Note: You MIGHT be tempted to call SSL_CTX_check_private_key(ctx) here,
17830 * to make sure that the private key can be used. But doing so will not
17831 * work as expected, and will error out with:
17832 *
17833 * SSL_CTX_check_private_key:no certificate assigned
17834 *
17835 * To make PKCS#12 support work, do not make that call here.
17836 */
17837
17838 res = SSL_CTX_use_certificate(ctx, cert);
17839 if (res <= 0) {
17840 PRIVS_RELINQUISH
17841
17842 tls_log("error loading certificate from TLSPKCS12File '%s' %s",
17843 tls_pkcs12_file, tls_get_errors());
17844 PKCS12_free(p12);
17845
17846 if (cert != NULL) {
17847 X509_free(cert);
17848 }
17849
17850 if (pkey != NULL) {
17851 EVP_PKEY_free(pkey);
17852 }
17853
17854 return -1;
17855 }
17856
17857 if (pkey != NULL &&
17858 tls_pkey != NULL) {
17859 switch (get_pkey_type(pkey)) {
17860 case EVP_PKEY_RSA:
17861 tls_pkey->flags |= TLS_PKEY_USE_RSA;
17862 tls_pkey->flags &= ~(TLS_PKEY_USE_DSA|TLS_PKEY_USE_EC);
17863 break;
17864
17865 case EVP_PKEY_DSA:
17866 tls_pkey->flags |= TLS_PKEY_USE_DSA;
17867 tls_pkey->flags &= ~(TLS_PKEY_USE_RSA|TLS_PKEY_USE_EC);
17868 break;
17869
17870 #ifdef PR_USE_OPENSSL_ECC
17871 case EVP_PKEY_EC:
17872 tls_pkey->flags |= TLS_PKEY_USE_EC;
17873 tls_pkey->flags &= ~(TLS_PKEY_USE_RSA|TLS_PKEY_USE_DSA);
17874 break;
17875 #endif /* PR_USE_OPENSSL_ECC */
17876 }
17877 }
17878
17879 res = SSL_CTX_use_PrivateKey(ctx, pkey);
17880 if (res <= 0) {
17881 PRIVS_RELINQUISH
17882
17883 tls_log("error loading key from TLSPKCS12File '%s' %s", tls_pkcs12_file,
17884 tls_get_errors());
17885
17886 PKCS12_free(p12);
17887
17888 if (cert != NULL) {
17889 X509_free(cert);
17890 }
17891
17892 if (pkey != NULL) {
17893 EVP_PKEY_free(pkey);
17894 }
17895
17896 return -1;
17897 }
17898
17899 res = SSL_CTX_check_private_key(ctx);
17900 if (res != 1) {
17901 PRIVS_RELINQUISH
17902
17903 tls_log("error checking key from TLSPKCS12File '%s': %s", tls_pkcs12_file,
17904 tls_get_errors());
17905
17906 PKCS12_free(p12);
17907
17908 if (cert != NULL) {
17909 X509_free(cert);
17910 }
17911
17912 if (pkey != NULL) {
17913 EVP_PKEY_free(pkey);
17914 }
17915
17916 return -1;
17917 }
17918
17919 /* SSL_CTX_use_certificate() will increment the refcount on cert, so we
17920 * can safely call X509_free() on it. However, we need to keep that
17921 * pointer around until after the handling of a cert chain file.
17922 */
17923 if (pkey != NULL) {
17924 switch (get_pkey_type(pkey)) {
17925 case EVP_PKEY_RSA:
17926 *rsa_cert = cert;
17927 break;
17928
17929 case EVP_PKEY_DSA:
17930 *dsa_cert = cert;
17931 break;
17932
17933 #ifdef PR_USE_OPENSSL_ECC
17934 case EVP_PKEY_EC:
17935 *ec_cert = cert;
17936 break;
17937 #endif /* PR_USE_OPENSSL_ECC */
17938 }
17939 }
17940
17941 if (pkey != NULL) {
17942 EVP_PKEY_free(pkey);
17943 }
17944
17945 if (p12 != NULL) {
17946 PKCS12_free(p12);
17947 }
17948
17949 PRIVS_RELINQUISH
17950
17951 return 0;
17952 }
17953
17954 static int tls_ctx_set_rsa_cert(SSL_CTX *ctx, X509 **rsa_cert) {
17955 X509 *cert;
17956 FILE *fh = NULL;
17957 int res, xerrno;
17958 const char *key_file = NULL;
17959
17960 if (tls_rsa_cert_file == NULL) {
17961 return 0;
17962 }
17963
17964 PRIVS_ROOT
17965 fh = fopen(tls_rsa_cert_file, "r");
17966 xerrno = errno;
17967 if (fh == NULL) {
17968 PRIVS_RELINQUISH
17969 pr_log_pri(PR_LOG_DEBUG, MOD_TLS_VERSION
17970 ": error reading TLSRSACertificateFile '%s': %s", tls_rsa_cert_file,
17971 strerror(xerrno));
17972 errno = xerrno;
17973 return -1;
17974 }
17975
17976 /* Assume that if no separate TLSRSACertificateKeyFile was configured (or
17977 * that if the configured TLSRSACertificateKeyFile is to the same path as
17978 * the TLSRSACertificateFile), that the cert and key are in the same file.
17979 * In that case, the file contains sensitive data, and we do not want it
17980 * lingering around in stdio buffers.
17981 */
17982 if (tls_rsa_key_file == NULL ||
17983 strcmp(tls_rsa_cert_file, tls_rsa_key_file) == 0) {
17984 (void) setvbuf(fh, NULL, _IONBF, 0);
17985 }
17986
17987 cert = read_cert(fh, ctx);
17988 if (cert == NULL) {
17989 PRIVS_RELINQUISH
17990 pr_log_pri(PR_LOG_NOTICE, MOD_TLS_VERSION
17991 ": error reading TLSRSACertificateFile '%s': %s", tls_rsa_cert_file,
17992 tls_get_errors());
17993 fclose(fh);
17994 return -1;
17995 }
17996
17997 fclose(fh);
17998
17999 /* SSL_CTX_use_certificate() will increment the refcount on cert, so we
18000 * can safely call X509_free() on it. However, we need to keep that
18001 * pointer around until after the handling of a cert chain file.
18002 */
18003 res = SSL_CTX_use_certificate(ctx, cert);
18004 if (res <= 0) {
18005 PRIVS_RELINQUISH
18006
18007 pr_log_pri(PR_LOG_NOTICE, MOD_TLS_VERSION
18008 ": error loading TLSRSACertificateFile '%s': %s", tls_rsa_cert_file,
18009 tls_get_errors());
18010 return -1;
18011 }
18012
18013 *rsa_cert = cert;
18014 pr_trace_msg(trace_channel, 19, "loaded RSA server certificate from '%s'",
18015 tls_rsa_cert_file);
18016
18017 key_file = tls_rsa_key_file;
18018 if (key_file == NULL) {
18019 /* Assume the private key is in the cert file. */
18020 key_file = tls_rsa_cert_file;
18021 }
18022
18023 if (tls_pkey != NULL) {
18024 tls_pkey->flags |= TLS_PKEY_USE_RSA;
18025 tls_pkey->flags &= ~(TLS_PKEY_USE_DSA|TLS_PKEY_USE_EC);
18026 }
18027
18028 res = SSL_CTX_use_PrivateKey_file(ctx, key_file, X509_FILETYPE_PEM);
18029 if (res <= 0) {
18030 const char *errors;
18031
18032 PRIVS_RELINQUISH
18033 errors = tls_get_errors();
18034
18035 pr_trace_msg(trace_channel, 3,
18036 "error loading TLSRSACertificateKeyFile '%s': %s", key_file, errors);
18037 pr_log_pri(PR_LOG_NOTICE, MOD_TLS_VERSION
18038 ": error loading TLSRSACertificateKeyFile '%s': %s", key_file, errors);
18039 return -1;
18040 }
18041
18042 res = SSL_CTX_check_private_key(ctx);
18043 if (res != 1) {
18044 const char *errors;
18045
18046 PRIVS_RELINQUISH
18047 errors = tls_get_errors();
18048
18049 pr_trace_msg(trace_channel, 3,
18050 "error checking key from TLSRSACertificateKeyFile '%s': %s", key_file,
18051 errors);
18052 pr_log_pri(PR_LOG_NOTICE, MOD_TLS_VERSION
18053 ": error checking key from TLSRSACertificateKeyFile '%s': %s", key_file,
18054 errors);
18055 return -1;
18056 }
18057 PRIVS_RELINQUISH
18058
18059 return 0;
18060 }
18061
18062 static int tls_ctx_set_cert_chain(SSL_CTX *ctx, X509 *dsa_cert, X509 *ec_cert,
18063 X509 *rsa_cert) {
18064 #if defined(SSL_CTRL_CHAIN_CERT)
18065 BIO *bio;
18066 X509 *cert;
18067 unsigned int count = 0;
18068
18069 if (tls_ca_chain == NULL) {
18070 return 0;
18071 }
18072
18073 PRIVS_ROOT
18074 bio = BIO_new_file(tls_ca_chain, "r");
18075 PRIVS_RELINQUISH
18076
18077 if (bio == NULL) {
18078 tls_log("unable to read certificate chain '%s': %s", tls_ca_chain,
18079 tls_get_errors());
18080 return 0;
18081 }
18082
18083 if (SSL_CTX_clear_chain_certs(ctx) != 1) {
18084 tls_log("error clearing SSL_CTX chain certs: %s", tls_get_errors());
18085 BIO_free(bio);
18086 return -1;
18087 }
18088
18089 cert = PEM_read_bio_X509(bio, NULL, NULL, NULL);
18090 while (cert != NULL) {
18091 pr_signals_handle();
18092
18093 if (rsa_cert != NULL) {
18094 /* Skip this cert if it is the same as the configured RSA server cert. */
18095 if (X509_cmp(rsa_cert, cert) == 0) {
18096 X509_free(cert);
18097 cert = PEM_read_bio_X509(bio, NULL, NULL, NULL);
18098 continue;
18099 }
18100 }
18101
18102 if (dsa_cert != NULL) {
18103 /* Skip this cert if it is the same as the configured DSA server cert. */
18104 if (X509_cmp(dsa_cert, cert) == 0) {
18105 X509_free(cert);
18106 cert = PEM_read_bio_X509(bio, NULL, NULL, NULL);
18107 continue;
18108 }
18109 }
18110
18111 if (ec_cert != NULL) {
18112 /* Skip this cert if it is the same as the configured EC server cert. */
18113 if (X509_cmp(ec_cert, cert) == 0) {
18114 X509_free(cert);
18115 cert = PEM_read_bio_X509(bio, NULL, NULL, NULL);
18116 continue;
18117 }
18118 }
18119
18120 if (SSL_CTX_add1_chain_cert(ctx, cert) != 1) {
18121 tls_log("error adding cert to SSL_CTX certificate chain: %s",
18122 tls_get_errors());
18123 X509_free(cert);
18124 break;
18125 }
18126
18127 count++;
18128 cert = PEM_read_bio_X509(bio, NULL, NULL, NULL);
18129 }
18130
18131 BIO_free(bio);
18132 ERR_clear_error();
18133
18134 tls_log("added %u certs from '%s' to SSL_CTX certificate chain", count,
18135 tls_ca_chain);
18136 #endif /* SSL_CTRL_CHAIN_CERT */
18137
18138 return 0;
18139 }
18140
18141 static int tls_ctx_set_certs(SSL_CTX *ctx, X509 **dsa_cert, X509 **ec_cert,
18142 X509 **rsa_cert) {
18143 if (tls_ctx_set_dsa_cert(ctx, dsa_cert) < 0 ||
18144 tls_ctx_set_ec_cert(ctx, ec_cert) < 0 ||
18145 tls_ctx_set_pkcs12_cert(ctx, dsa_cert, ec_cert, rsa_cert) < 0 ||
18146 tls_ctx_set_rsa_cert(ctx, rsa_cert) < 0) {
18147 return -1;
18148 }
18149
18150 /* Log a warning if the server was badly misconfigured, and has no server
18151 * certs at all. The client will probably see this situation as something
18152 * like:
18153 *
18154 * error:14094410:SSL routines:SSL3_READ_BYTES:sslv3 alert handshake failure
18155 *
18156 * And the TLSLog will show the error as:
18157 *
18158 * error:1408A0C1:SSL routines:SSL3_GET_CLIENT_HELLO:no shared cipher
18159 */
18160 if (tls_rsa_cert_file == NULL &&
18161 tls_dsa_cert_file == NULL &&
18162 tls_ec_cert_file == NULL &&
18163 tls_pkcs12_file == NULL) {
18164 tls_log("no TLSRSACertificateFile, TLSDSACertificateFile, "
18165 "TLSECCertificateFile, or TLSPKCS12File configured; "
18166 "unable to handle SSL/TLS connections");
18167 pr_log_pri(PR_LOG_NOTICE, MOD_TLS_VERSION
18168 ": no TLSRSACertificateFile, TLSDSACertificateFile, "
18169 "TLSECCertificateFile or TLSPKCS12File configured; "
18170 "unable to handle SSL/TLS connections");
18171 }
18172
18173 return 0;
18174 }
18175
18176 static int tls_ctx_set_ciphers(SSL_CTX *ctx) {
18177 SSL_CTX_set_cipher_list(ctx, tls_cipher_suite);
18178
18179 #if OPENSSL_VERSION_NUMBER >= 0x10101000L && \
18180 defined(TLS1_3_VERSION)
18181 if (tlsv13_cipher_suite != NULL) {
18182 SSL_CTX_set_ciphersuites(ctx, tlsv13_cipher_suite);
18183 }
18184 #endif /* TLS1_3_VERSION */
18185
18186 return 0;
18187 }
18188
18189 static int tls_ctx_set_crls(SSL_CTX *ctx) {
18190 X509_STORE *store;
18191
18192 if (tls_crl_file == NULL &&
18193 tls_crl_path == NULL) {
18194 return 0;
18195 }
18196
18197 store = SSL_CTX_get_cert_store(ctx);
18198 if (store == NULL) {
18199 tls_log("error getting SSL_CTX store: %s", tls_get_errors());
18200 return -1;
18201 }
18202
18203 PRIVS_ROOT
18204 if (X509_STORE_load_locations(store, tls_crl_file, tls_crl_path) != 1) {
18205 if (tls_crl_file != NULL &&
18206 tls_crl_path == NULL) {
18207 tls_log("error loading TLSCARevocationFile '%s': %s", tls_crl_file,
18208 tls_get_errors());
18209
18210 } else if (tls_crl_file == NULL &&
18211 tls_crl_path != NULL) {
18212 tls_log("error loading TLSCARevocationPath '%s': %s", tls_crl_path,
18213 tls_get_errors());
18214
18215 } else {
18216 tls_log("error loading TLSCARevocationFile '%s', "
18217 "TLSCARevocationPath '%s': %s", tls_crl_file, tls_crl_path,
18218 tls_get_errors());
18219 }
18220 }
18221
18222 PRIVS_RELINQUISH
18223
18224 if (tls_crl_file != NULL) {
18225 pr_trace_msg(trace_channel, 19, "using CRL file '%s'", tls_crl_file);
18226 }
18227
18228 if (tls_crl_path != NULL) {
18229 pr_trace_msg(trace_channel, 19, "using CRL directory '%s'", tls_crl_path);
18230 }
18231
18232 /* Make sure we enable CRL checking, now that we've loaded them. */
18233 X509_STORE_set_flags(store, X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
18234 X509_STORE_set_purpose(store, X509_PURPOSE_SSL_CLIENT);
18235
18236 return 0;
18237 }
18238
18239 static int tls_ctx_set_ecdh_curve(SSL_CTX *ctx) {
18240 #if defined(PR_USE_OPENSSL_ECC)
18241 # if defined(SSL_CTX_set_ecdh_auto)
18242 if (tls_opts & TLS_OPT_NO_AUTO_ECDH) {
18243 SSL_CTX_set_ecdh_auto(ctx, 0);
18244 }
18245 # endif
18246
18247 if (tls_ecdh_curve != NULL) {
18248 # if defined(SSL_CTX_set1_curves_list)
18249 char *curve_names;
18250
18251 curve_names = tls_ecdh_curve;
18252 if (strcasecmp(curve_names, "auto") != 0) {
18253 SSL_CTX_set1_curves_list(ctx, curve_names);
18254 }
18255 # else
18256 const EC_KEY *ec_key;
18257
18258 ec_key = tls_ecdh_curve;
18259 SSL_CTX_set_tmp_ecdh(ctx, ec_key);
18260 # endif /* pre OpenSSL-1.0.2 */
18261
18262 SSL_CTX_set_options(ctx, SSL_OP_SINGLE_ECDH_USE);
18263 } else {
18264 # if OPENSSL_VERSION_NUMBER < 0x10100000L
18265 SSL_CTX_set_tmp_ecdh_callback(ctx, tls_ecdh_cb);
18266 # endif /* Before OpenSSL-1.1.x */
18267 }
18268 #endif /* PR_USE_OPENSS_ECC */
18269
18270 return 0;
18271 }
18272
18273 static int tls_ctx_set_next_protocol(SSL_CTX *ctx) {
18274 #if !defined(OPENSSL_NO_TLSEXT)
18275 register unsigned int i;
18276 const char *proto = TLS_DEFAULT_NEXT_PROTO;
18277 size_t encoded_protolen, proto_len;
18278 unsigned char *encoded_proto;
18279 struct tls_next_proto *next_proto;
18280
18281 if (tls_use_next_protocol == FALSE) {
18282 return 0;
18283 }
18284
18285 proto_len = strlen(proto);
18286 encoded_protolen = proto_len + 1;
18287 encoded_proto = palloc(session.pool, encoded_protolen);
18288 encoded_proto[0] = proto_len;
18289 for (i = 0; i < proto_len; i++) {
18290 encoded_proto[i+1] = proto[i];
18291 }
18292
18293 next_proto = palloc(session.pool, sizeof(struct tls_next_proto));
18294 next_proto->proto = pstrdup(session.pool, proto);
18295 next_proto->encoded_proto = encoded_proto;
18296 next_proto->encoded_protolen = encoded_protolen;
18297
18298 # if defined(PR_USE_OPENSSL_NPN)
18299 SSL_CTX_set_next_protos_advertised_cb(ctx, tls_npn_advertised_cb, next_proto);
18300 # endif /* NPN */
18301
18302 # if defined(PR_USE_OPENSSL_ALPN)
18303 SSL_CTX_set_alpn_select_cb(ctx, tls_alpn_select_cb, next_proto);
18304 # endif /* ALPN */
18305 #endif /* !OPENSSL_NO_TLSEXT */
18306
18307 return 0;
18308 }
18309
18310 static int tls_ctx_set_options(SSL_CTX *ctx) {
18311 #if OPENSSL_VERSION_NUMBER > 0x009080cfL
18312 # if defined(SSL_OP_CIPHER_SERVER_PREFERENCE)
18313 SSL_CTX_clear_options(ctx, SSL_OP_CIPHER_SERVER_PREFERENCE);
18314 # endif /* SSL_OP_CIPHER_SERVER_PREFERENCE */
18315
18316 /* The OpenSSL team realized that the flag added in 0.9.8l, the
18317 * SSL3_FLAGS_ALLOW_UNSAFE_LEGACY_RENEGOTIATION flag, was a bad idea.
18318 * So in later versions, it was changed to a context flag,
18319 * SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION.
18320 */
18321 SSL_CTX_clear_options(ctx, SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION);
18322 if (tls_opts & TLS_OPT_ALLOW_CLIENT_RENEGOTIATIONS) {
18323 SSL_CTX_set_options(ctx, SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION);
18324 }
18325 #endif
18326
18327 #if defined(SSL_OP_CIPHER_SERVER_PREFERENCE)
18328 if (tls_use_server_cipher_preference == TRUE) {
18329 SSL_CTX_set_options(ctx, SSL_OP_CIPHER_SERVER_PREFERENCE);
18330 }
18331 #endif /* SSL_OP_CIPHER_SERVER_PREFERENCE */
18332
18333 #if OPENSSL_VERSION_NUMBER > 0x000907000L
18334 /* Install a callback for logging OpenSSL message information, if requested.
18335 */
18336 if (tls_opts & TLS_OPT_ENABLE_DIAGS) {
18337 tls_log("%s",
18338 "TLSOption EnableDiags enabled, setting diagnostics callback");
18339 SSL_CTX_set_msg_callback(ctx, tls_msg_cb);
18340 }
18341 #endif
18342
18343 return 0;
18344 }
18345
18346 static int tls_ctx_set_pkey(SSL_CTX *ctx) {
18347 if (tls_pkey != NULL) {
18348 SSL_CTX_set_default_passwd_cb(ctx, tls_pkey_cb);
18349 SSL_CTX_set_default_passwd_cb_userdata(ctx, (void *) tls_pkey);
18350 }
18351
18352 return 0;
18353 }
18354
18355 static int tls_ctx_set_protocol(server_rec *s, SSL_CTX *ctx) {
18356 int all_proto, disabled_proto;
18357 unsigned int enabled_proto_count = 0;
18358 const char *enabled_proto_str = NULL;
18359
18360 /* First, make sure ALL protocol versions are disabled by default. */
18361 all_proto = get_disabled_protocols(0);
18362 SSL_CTX_set_options(ctx, all_proto);
18363
18364 disabled_proto = get_disabled_protocols(tls_protocol);
18365
18366 /* Per the comments in <ssl/ssl.h>, SSL_CTX_set_options() uses |= on
18367 * the previous value. This means we can easily OR in our new option
18368 * values with any previously set values.
18369 */
18370 enabled_proto_str = tls_get_proto_str(s->pool, tls_protocol,
18371 &enabled_proto_count);
18372
18373 pr_log_debug(DEBUG8, MOD_TLS_VERSION ": supporting %s %s", enabled_proto_str,
18374 enabled_proto_count != 1 ? "protocols" : "protocol only");
18375
18376 /* Now we clear all of the NO_ protocol version options EXCEPT for the
18377 * enabled versions.
18378 *
18379 * This is more convoluted than it should be, because of the expression
18380 * of enabled protocol versions via OP_NO_ negations, and bitmasking.
18381 */
18382 #if OPENSSL_VERSION_NUMBER > 0x009080cfL
18383 SSL_CTX_clear_options(ctx, all_proto|disabled_proto);
18384 #endif
18385 SSL_CTX_set_options(ctx, disabled_proto);
18386
18387 return 0;
18388 }
18389
18390 static int tls_ctx_set_psks(SSL_CTX *ctx) {
18391 #if defined(PSK_MAX_PSK_LEN)
18392 if (tls_psks != NULL &&
18393 pr_table_count(tls_psks) > 0) {
18394 pr_trace_msg(trace_channel, 9,
18395 "enabling support for PSK identities (%d)", pr_table_count(tls_psks));
18396 SSL_CTX_set_psk_server_callback(ctx, tls_lookup_psk);
18397 }
18398 #endif /* PSK_MAX_PSK_LEN */
18399
18400 return 0;
18401 }
18402
18403 static int tls_ctx_set_renegotiations(SSL_CTX *ctx) {
18404 #if defined(SSL_OP_NO_RENEGOTIATION)
18405 if (tls_ctrl_renegotiate_timeout == 0 &&
18406 tls_data_renegotiate_limit == 0 &&
18407 tls_renegotiate_timeout == 0 &&
18408 tls_renegotiate_required == FALSE) {
18409 /* If server-requested renegotiations are disabled, reject
18410 * client-initiated renegotiations, too.
18411 */
18412 SSL_CTX_set_options(ctx, SSL_OP_NO_RENEGOTIATION);
18413 }
18414 #endif /* SSL_OP_NO_RENEGOTIATION */
18415
18416 return 0;
18417 }
18418
18419 static int tls_ctx_set_serverinfo(SSL_CTX *ctx) {
18420 #if !defined(OPENSSL_NO_TLSEXT)
18421 # if OPENSSL_VERSION_NUMBER >= 0x10002000L && \
18422 !defined(HAVE_LIBRESSL)
18423 if (tls_serverinfo_file == NULL) {
18424 return 0;
18425 }
18426
18427 if (SSL_CTX_use_serverinfo_file(ctx, tls_serverinfo_file) != 1) {
18428 tls_log("error setting server info using '%s': %s", tls_serverinfo_file,
18429 tls_get_errors());
18430 }
18431 # endif /* OpenSSL-1.0.2 and later */
18432 #endif /* !OPENSSL_NO_TLSEXT */
18433
18434 return 0;
18435 }
18436
18437 static int tls_ctx_set_session_id_context(server_rec *s, SSL_CTX *ctx) {
18438 /* Update the session ID context to use. This is important; it ensures
18439 * that the session IDs for this particular vhost will differ from those
18440 * for another vhost. An external TLS session cache will possibly
18441 * cache sessions from all vhosts together, and we need to keep them
18442 * separate.
18443 */
18444 pr_trace_msg(trace_channel, 19,
18445 "setting session ID context '%u' (%lu bytes) on SSL_CTX %p", s->sid,
18446 sizeof(s->sid), ctx);
18447 SSL_CTX_set_session_id_context(ctx, (unsigned char *) &(s->sid),
18448 sizeof(s->sid));
18449
18450 return 0;
18451 }
18452
18453 static int tls_ctx_set_session_cache(server_rec *s, SSL_CTX *ctx) {
18454 config_rec *c;
18455 const char *provider;
18456 long timeout;
18457
18458 c = find_config(s->conf, CONF_PARAM, "TLSSessionCache", FALSE);
18459 if (c == NULL) {
18460 /* No explicit external session cache configured. */
18461
18462 #if OPENSSL_VERSION_NUMBER > 0x000907000L
18463 /* If we support renegotiations, then make the cache lifetime be 10%
18464 * longer than the control connection renegotiation timer.
18465 */
18466 timeout = 15840;
18467 #else
18468 /* If we are not supporting reneogtiations because the OpenSSL version
18469 * is too old, then set the default cache lifetime to 30 minutes.
18470 */
18471 timeout = 1800;
18472 #endif /* OpenSSL older than 0.9.7. */
18473
18474 /* Make sure that we enable OpenSSL internal caching, AND that the
18475 * cache timeout is longer than the default control channel
18476 * renegotiation.
18477 */
18478
18479 SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_SERVER);
18480 SSL_CTX_set_timeout(ctx, timeout);
18481
18482 return 0;
18483 }
18484
18485 /* Look up and initialize the configured session cache provider. */
18486 provider = c->argv[0];
18487 timeout = *((long *) c->argv[2]);
18488
18489 if (provider != NULL) {
18490 if (strncmp(provider, "internal", 9) != 0) {
18491 tls_sess_cache = tls_sess_cache_get_cache(provider);
18492
18493 pr_log_debug(DEBUG8, MOD_TLS_VERSION ": opening '%s' TLSSessionCache",
18494 provider);
18495
18496 if (tls_sess_cache_open(c->argv[1], timeout) == 0) {
18497 long cache_mode, cache_flags;
18498
18499 cache_mode = SSL_SESS_CACHE_SERVER;
18500
18501 /* We could force OpenSSL to use ONLY the configured external session
18502 * caching mechanism by using the SSL_SESS_CACHE_NO_INTERNAL mode flag
18503 * (available in OpenSSL 0.9.6h and later).
18504 *
18505 * However, consider the case where the serialized session data is
18506 * too large for the external cache, or the external cache refuses
18507 * to add the session for some reason. If OpenSSL is using only our
18508 * external cache, that session is lost (which could cause problems
18509 * e.g. for later protected data transfers, which require that the
18510 * SSL session from the control connection be reused).
18511 *
18512 * If the external cache can be reasonably sure that session data
18513 * can be added, then the NO_INTERNAL flag is a good idea; it keeps
18514 * OpenSSL from allocating more memory than necessary. Having both
18515 * an internal and an external cache of the same data is a bit
18516 * unresourceful. Thus we ask the external cache mechanism what
18517 * additional cache mode flags to use.
18518 */
18519
18520 cache_flags = tls_sess_cache_get_cache_mode();
18521 cache_mode |= cache_flags;
18522
18523 SSL_CTX_set_session_cache_mode(ctx, cache_mode);
18524 SSL_CTX_set_timeout(ctx, timeout);
18525
18526 SSL_CTX_sess_set_new_cb(ctx, tls_sess_cache_add_sess_cb);
18527 SSL_CTX_sess_set_get_cb(ctx, tls_sess_cache_get_sess_cb);
18528 SSL_CTX_sess_set_remove_cb(ctx, tls_sess_cache_delete_sess_cb);
18529
18530 } else {
18531 pr_log_debug(DEBUG1, MOD_TLS_VERSION
18532 ": error opening '%s' TLSSessionCache: %s", provider,
18533 strerror(errno));
18534
18535 /* Default to using OpenSSL's own internal session caching. */
18536 SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_SERVER);
18537 }
18538
18539 } else {
18540 /* Default to using OpenSSL's own internal session caching. */
18541 SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_SERVER);
18542 SSL_CTX_set_timeout(ctx, timeout);
18543 }
18544
18545 } else {
18546 /* SSL session caching has been explicitly turned off. */
18547
18548 pr_log_debug(DEBUG3, MOD_TLS_VERSION
18549 ": TLSSessionCache off, disabling TLS session caching and setting "
18550 "NoSessionReuseRequired TLSOption");
18551
18552 SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_OFF);
18553
18554 /* Make sure we automatically relax the "SSL session reuse required
18555 * for data connections" requirement; to enforce such a requirement
18556 * TLS session caching MUST be enabled. So if session caching has been
18557 * explicitly disabled, relax that policy as well.
18558 */
18559 tls_opts |= TLS_OPT_NO_SESSION_REUSE_REQUIRED;
18560 }
18561
18562 return 0;
18563 }
18564
18565 static int tls_ctx_set_session_tickets(SSL_CTX *ctx) {
18566 #if defined(TLS_USE_SESSION_TICKETS) && \
18567 defined(SSL_OP_NO_TICKET)
18568 if (tls_use_session_tickets == TRUE) {
18569 if (SSL_CTX_set_tlsext_ticket_key_cb(ctx, tls_ticket_key_cb) == 0) {
18570 pr_log_pri(PR_LOG_WARNING, MOD_TLS_VERSION
18571 ": mod_tls compiled with Session Ticket support, but linked to "
18572 "an OpenSSL library without tlsext support, therefore Session "
18573 "Tickets are not available");
18574 }
18575
18576 /* Ensure that tickets are enabled in the SSL_CTX options. */
18577 SSL_CTX_clear_options(ctx, SSL_OP_NO_TICKET);
18578
18579 } else {
18580 # ifdef TLS1_3_VERSION
18581 /* If we might handle TLSv1.3 sessions, we need the callback for session
18582 * resumption; TLSv1.3 prefers stateless session tickets vs stateful
18583 * server-side session IDs.
18584 */
18585 if (SSL_CTX_get_options(ctx) & SSL_OP_NO_TLSv1_3) {
18586 SSL_CTX_set_options(ctx, SSL_OP_NO_TICKET);
18587 SSL_CTX_set_tlsext_ticket_key_cb(ctx, NULL);
18588
18589 } else {
18590 if (SSL_CTX_set_tlsext_ticket_key_cb(ctx, tls_ticket_key_cb) == 0) {
18591 pr_log_pri(PR_LOG_WARNING, MOD_TLS_VERSION
18592 ": mod_tls compiled with Session Ticket support, but linked to "
18593 "an OpenSSL library without tlsext support, therefore Session "
18594 "Tickets are not available");
18595 }
18596
18597 SSL_CTX_clear_options(ctx, SSL_OP_NO_TICKET);
18598 }
18599 # else
18600 SSL_CTX_set_options(ctx, SSL_OP_NO_TICKET);
18601 SSL_CTX_set_tlsext_ticket_key_cb(ctx, NULL);
18602 # endif /* TLS1_3_VERSION */
18603 }
18604 #endif /* TLS_USE_SESSION_TICKETS and SSL_OP_NO_TICKET */
18605
18606 return 0;
18607 }
18608
18609 static int tls_ctx_set_stapling(SSL_CTX *ctx) {
18610 #if defined(PR_USE_OPENSSL_OCSP)
18611 SSL_CTX_set_tlsext_status_cb(ctx, tls_ocsp_cb);
18612 SSL_CTX_set_tlsext_status_arg(ctx, NULL);
18613 #endif /* PR_USE_OPENSSL_OCSP */
18614
18615 return 0;
18616 }
18617
18618 static int tls_ctx_set_stapling_cache(server_rec *s, SSL_CTX *ctx) {
18619 #if defined(PR_USE_OPENSSL_OCSP)
18620 config_rec *c;
18621 const char *provider;
18622
18623 c = find_config(s->conf, CONF_PARAM, "TLSStaplingCache", FALSE);
18624 if (c == NULL) {
18625 return 0;
18626 }
18627
18628 /* Look up and initialize the configured OCSP cache provider. */
18629 provider = c->argv[0];
18630
18631 if (provider != NULL) {
18632 tls_ocsp_cache = tls_ocsp_cache_get_cache(provider);
18633
18634 pr_log_debug(DEBUG8, MOD_TLS_VERSION ": opening '%s' TLSStaplingCache",
18635 provider);
18636
18637 if (tls_ocsp_cache_open(c->argv[1]) < 0 &&
18638 errno != ENOSYS) {
18639 pr_log_debug(DEBUG1, MOD_TLS_VERSION
18640 ": error opening '%s' TLSStaplingCache: %s", provider,
18641 strerror(errno));
18642 tls_ocsp_cache = NULL;
18643 }
18644 }
18645 #endif /* PR_USE_OPENSSL_OCSP */
18646
18647 return 0;
18648 }
18649
18650 static int tls_ctx_set_verify(SSL_CTX *ctx) {
18651 int verify_mode = 0;
18652
18653 if (tls_flags & TLS_SESS_VERIFY_CLIENT_OPTIONAL) {
18654 verify_mode = SSL_VERIFY_PEER;
18655 }
18656
18657 if (tls_flags & TLS_SESS_VERIFY_CLIENT_REQUIRED) {
18658 /* If we are verifying clients, make sure the client sends a cert;
18659 * the protocol allows for the client to disregard a request for
18660 * its cert by the server.
18661 */
18662 verify_mode |= (SSL_VERIFY_PEER|SSL_VERIFY_FAIL_IF_NO_PEER_CERT);
18663 }
18664
18665 if (verify_mode != 0) {
18666 SSL_CTX_set_verify(ctx, verify_mode, tls_verify_cb);
18667
18668 /* Note: we add one to the configured depth purposefully. As noted
18669 * in the OpenSSL man pages, the verification process will silently
18670 * stop at the configured depth, and the error messages ensuing will
18671 * be that of an incomplete certificate chain, rather than the
18672 * "chain too long" error that might be expected. To log the "chain
18673 * too long" condition, we add one to the configured depth, and catch,
18674 * in the verify callback, the exceeding of the actual depth.
18675 */
18676 SSL_CTX_set_verify_depth(ctx, tls_verify_depth + 1);
18677 }
18678
18679 return 0;
18680 }
18681
18682 static int tls_ctx_set_all(server_rec *s, SSL_CTX *ctx) {
18683 X509 *dsa_cert = NULL, *ec_cert = NULL, *rsa_cert = NULL;
18684
18685 if (tls_opts & TLS_OPT_ALLOW_WEAK_SECURITY) {
18686 #if OPENSSL_VERSION_NUMBER >= 0x10100000L && \
18687 !defined(HAVE_LIBRESSL)
18688 SSL_CTX_set_security_level(ctx, 0);
18689 #endif /* OpenSSL-1.1.0 and later */
18690 }
18691
18692 if (tls_ctx_set_pkey(ctx) < 0) {
18693 return -1;
18694 }
18695
18696 if (tls_ctx_set_ca_certs(ctx) < 0) {
18697 return -1;
18698 }
18699
18700 if (tls_ctx_set_certs(ctx, &dsa_cert, &ec_cert, &rsa_cert) < 0) {
18701 return -1;
18702 }
18703
18704 /* Handle a CertificateChainFile. We need to do this here, after the
18705 * server cert has been loaded, so that we can decide whether the
18706 * CertificateChainFile contains another copy of the server cert (or not).
18707 */
18708 if (tls_ctx_set_cert_chain(ctx, dsa_cert, ec_cert, rsa_cert) < 0) {
18709 return -1;
18710 }
18711
18712 if (dsa_cert != NULL) {
18713 X509_free(dsa_cert);
18714 dsa_cert = NULL;
18715 }
18716
18717 if (ec_cert != NULL) {
18718 X509_free(ec_cert);
18719 ec_cert = NULL;
18720 }
18721
18722 if (rsa_cert != NULL) {
18723 X509_free(rsa_cert);
18724 rsa_cert = NULL;
18725 }
18726
18727 if (tls_ctx_set_ciphers(ctx) < 0) {
18728 return -1;
18729 }
18730
18731 if (tls_ctx_set_crls(ctx) < 0) {
18732 return -1;
18733 }
18734
18735 if (tls_ctx_set_ecdh_curve(ctx) < 0) {
18736 return -1;
18737 }
18738
18739 if (tls_ctx_set_psks(ctx) < 0) {
18740 return -1;
18741 }
18742
18743 if (tls_ctx_set_options(ctx) < 0) {
18744 return -1;
18745 }
18746
18747 if (tls_ctx_set_next_protocol(ctx) < 0) {
18748 return -1;
18749 }
18750
18751 if (tls_ctx_set_protocol(s, ctx) < 0) {
18752 return -1;
18753 }
18754
18755 if (tls_ctx_set_renegotiations(ctx) < 0) {
18756 return -1;
18757 }
18758
18759 /* Note that we set this after setting the protocol versions, since the
18760 * supported protocol version flags will affect session tickets, due to
18761 * TLSv1.3' use of tickets.
18762 */
18763 if (tls_ctx_set_session_tickets(ctx) < 0) {
18764 return -1;
18765 }
18766
18767 if (tls_ctx_set_serverinfo(ctx) < 0) {
18768 return -1;
18769 }
18770
18771 if (tls_ctx_set_stapling(ctx) < 0) {
18772 return -1;
18773 }
18774
18775 if (tls_ctx_set_verify(ctx) < 0) {
18776 return -1;
18777 }
18778
18779 return 0;
18780 }
18781
18782 /* Initialization routines
18783 */
18784
18785 static int tls_init(void) {
18786 unsigned long openssl_version;
18787
18788 /* Check that the OpenSSL headers used match the version of the
18789 * OpenSSL library used.
18790 *
18791 * For now, we only log if there is a difference.
18792 */
18793
18794 #if OPENSSL_VERSION_NUMBER < 0x10100000L || \
18795 defined(HAVE_LIBRESSL)
18796 openssl_version = SSLeay();
18797 #else
18798 openssl_version = OpenSSL_version_num();
18799 #endif /* prior to OpenSSL-1.1.x */
18800
18801 if (openssl_version != OPENSSL_VERSION_NUMBER) {
18802 int unexpected_version_mismatch = TRUE;
18803
18804 if (OPENSSL_VERSION_NUMBER >= 0x1000000fL) {
18805 /* OpenSSL versions after 1.0.0 try to maintain ABI compatibility.
18806 * So we will warn about header/library version mismatches only if
18807 * the library is older than the headers.
18808 */
18809 if (openssl_version >= OPENSSL_VERSION_NUMBER) {
18810 unexpected_version_mismatch = FALSE;
18811 }
18812 }
18813
18814 if (unexpected_version_mismatch == TRUE) {
18815 const char *version_text = NULL;
18816
18817 #if OPENSSL_VERSION_NUMBER < 0x10100000L || \
18818 defined(HAVE_LIBRESSL)
18819 version_text = SSLeay_version(SSLEAY_VERSION);
18820 #else
18821 version_text = OpenSSL_version(OPENSSL_VERSION);
18822 #endif /* prior to OpenSSL-1.1.x */
18823
18824 pr_log_pri(PR_LOG_WARNING, MOD_TLS_VERSION
18825 ": compiled using OpenSSL version '%s' headers, but linked to "
18826 "OpenSSL version '%s' library", OPENSSL_VERSION_TEXT, version_text);
18827 tls_log("compiled using OpenSSL version '%s' headers, but linked to "
18828 "OpenSSL version '%s' library", OPENSSL_VERSION_TEXT, version_text);
18829 }
18830 }
18831
18832 pr_log_debug(DEBUG2, MOD_TLS_VERSION ": using " OPENSSL_VERSION_TEXT);
18833
18834 #if defined(PR_SHARED_MODULE)
18835 pr_event_register(&tls_module, "core.module-unload", tls_mod_unload_ev, NULL);
18836 #endif /* PR_SHARED_MODULE */
18837 pr_event_register(&tls_module, "core.postparse", tls_postparse_ev, NULL);
18838 pr_event_register(&tls_module, "core.restart", tls_restart_ev, NULL);
18839 pr_event_register(&tls_module, "core.shutdown", tls_shutdown_ev, NULL);
18840
18841 #if OPENSSL_VERSION_NUMBER < 0x10100000L
18842 OPENSSL_config(NULL);
18843
18844 /* It looks like calling OpenSSL_add_all_algorithms() is necessary for
18845 * handling some algorithms (e.g. PKCS12 files) which are NOT added by
18846 * just calling SSL_library_init().
18847 */
18848 OpenSSL_add_all_algorithms();
18849
18850 SSL_load_error_strings();
18851 SSL_library_init();
18852 ERR_load_crypto_strings();
18853 #endif /* prior to OpenSSL-1.1.x */
18854
18855 #ifdef PR_USE_CTRLS
18856 if (pr_ctrls_register(&tls_module, "tls", "query/tune mod_tls settings",
18857 tls_handle_tls) < 0) {
18858 pr_log_pri(PR_LOG_NOTICE, MOD_TLS_VERSION
18859 ": error registering 'tls' control: %s", strerror(errno));
18860
18861 } else {
18862 register unsigned int i;
18863
18864 tls_act_pool = make_sub_pool(permanent_pool);
18865 pr_pool_tag(tls_act_pool, "TLS Controls Pool");
18866
18867 for (i = 0; tls_acttab[i].act_action; i++) {
18868 tls_acttab[i].act_acl = palloc(tls_act_pool, sizeof(ctrls_acl_t));
18869 pr_ctrls_init_acl(tls_acttab[i].act_acl);
18870 }
18871 }
18872 #endif /* PR_USE_CTRLS */
18873
18874 return 0;
18875 }
18876
18877 static int tls_sess_init(void) {
18878 int res = 0;
18879 unsigned char *tmp = NULL;
18880 config_rec *c = NULL;
18881
18882 #if defined(TLS_USE_SESSION_TICKETS)
18883 lock_ticket_keys();
18884 #endif /* TLS_USE_SESSION_TICKETS */
18885
18886 pr_event_register(&tls_module, "core.session-reinit", tls_sess_reinit_ev,
18887 NULL);
18888
18889 /* First, check to see whether mod_tls is even enabled. */
18890 tmp = get_param_ptr(main_server->conf, "TLSEngine", FALSE);
18891 if (tmp != NULL &&
18892 *tmp == TRUE) {
18893 tls_engine = TRUE;
18894 }
18895
18896 if (tls_engine == FALSE) {
18897 /* If we have no ServerAlias vhosts at all, then it is OK to clean up
18898 * all of the TLS/OpenSSL-related code from this process. Otherwise,
18899 * a client MIGHT send a HOST command for a TLS-enabled vhost; if we
18900 * were to always cleanup OpenSSL here, that HOST command would inevitably
18901 * lead to a problem.
18902 */
18903
18904 res = pr_namebind_count(main_server);
18905 if (res == 0) {
18906 /* No need for this module's control channel NetIO handlers anymore. */
18907 pr_unregister_netio(PR_NETIO_STRM_CTRL);
18908
18909 /* No need for all the OpenSSL stuff in this process space, either. */
18910 tls_cleanup(TLS_CLEANUP_FL_SESS_INIT);
18911 tls_scrub_pkeys();
18912 }
18913
18914 return 0;
18915 }
18916
18917 /* Open the TLSLog, if configured */
18918 res = tls_openlog();
18919 if (res < 0) {
18920 if (res == -1) {
18921 pr_log_pri(PR_LOG_NOTICE, MOD_TLS_VERSION
18922 ": notice: unable to open TLSLog: %s", strerror(errno));
18923
18924 } else if (res == PR_LOG_WRITABLE_DIR) {
18925 pr_log_pri(PR_LOG_WARNING, MOD_TLS_VERSION
18926 ": notice: unable to open TLSLog: parent directory is world-writable");
18927
18928 } else if (res == PR_LOG_SYMLINK) {
18929 pr_log_pri(PR_LOG_WARNING, MOD_TLS_VERSION
18930 ": notice: unable to open TLSLog: cannot log to a symbolic link");
18931 }
18932 }
18933
18934 tls_lookup_all(main_server);
18935
18936 /* Check to see if a passphrase has been entered for this server. */
18937 tls_pkey = tls_lookup_pkey(main_server, TRUE, FALSE);
18938
18939 if (tls_ctx_set_all(main_server, ssl_ctx) < 0) {
18940 tls_log("%s", "error initializing OpenSSL context for this session");
18941 return -1;
18942 }
18943
18944 #if !defined(OPENSSL_NO_TLSEXT) && defined(TLSEXT_MAXLEN_host_name)
18945 SSL_CTX_set_tlsext_servername_callback(ssl_ctx, tls_sni_cb);
18946 SSL_CTX_set_tlsext_servername_arg(ssl_ctx, NULL);
18947 #endif /* !OPENSSL_NO_TLSEXT */
18948
18949 #if defined(PR_USE_OPENSSL_SSL_SESSION_TICKET_CALLBACK)
18950 /* Generate random ticket appdata that will uniquely (hopefully) identify
18951 * this particular FTP session.
18952 *
18953 * Note that we only want to do this once, so that the identifying data
18954 * does not change across SNI/HOST.
18955 */
18956 if (tls_ctrl_ticket_appdatasz == 0) {
18957 tls_ctrl_ticket_appdatasz = tls_data_ticket_appdatasz = 32;
18958
18959 if (tls_ctrl_ticket_appdata == NULL) {
18960 tls_ctrl_ticket_appdata = palloc(session.pool,
18961 tls_ctrl_ticket_appdatasz);
18962 }
18963
18964 /* Allocate space for the data connection ticket appdata as well; we
18965 * only need one buffer for this.
18966 */
18967 if (tls_data_ticket_appdata == NULL) {
18968 tls_data_ticket_appdata = palloc(session.pool,
18969 tls_data_ticket_appdatasz);
18970 }
18971
18972 if (RAND_bytes((unsigned char *) tls_ctrl_ticket_appdata,
18973 tls_ctrl_ticket_appdatasz) != 1) {
18974 tls_log("error generating %lu bytes of random ticket appdata: %s",
18975 (unsigned long) tls_ctrl_ticket_appdatasz, tls_get_errors());
18976 tls_ctrl_ticket_appdata_len = 0;
18977
18978 } else {
18979 tls_ctrl_ticket_appdata_len = tls_ctrl_ticket_appdatasz;
18980 }
18981 }
18982 #endif /* PR_USE_OPENSSL_SSL_SESSION_TICKET_CALLBACK */
18983
18984 /* We need to check for FIPS mode in the child process as well, in order
18985 * to re-seed the FIPS PRNG for this process ID. Annoying, isn't it?
18986 */
18987 if (ServerType == SERVER_STANDALONE) {
18988 if (tls_set_fips() < 0) {
18989 return -1;
18990 }
18991 }
18992
18993 #if OPENSSL_VERSION_NUMBER > 0x000907000L
18994 /* Handle any requested crypto accelerators/drivers. */
18995 c = find_config(main_server->conf, CONF_PARAM, "TLSCryptoDevice", FALSE);
18996 if (c != NULL) {
18997 # if defined(PR_USE_OPENSSL_ENGINE)
18998 tls_crypto_device = (const char *) c->argv[0];
18999
19000 if (strcasecmp(tls_crypto_device, "ALL") == 0) {
19001 /* Load all ENGINE implementations bundled with OpenSSL. */
19002 ENGINE_load_builtin_engines();
19003 ENGINE_register_all_complete();
19004 #if OPENSSL_VERSION_NUMBER < 0x10100000L
19005 OPENSSL_config(NULL);
19006 #endif /* prior to OpenSSL-1.1.x */
19007
19008 tls_log("%s", "enabled all builtin crypto devices");
19009
19010 } else {
19011 ENGINE *e;
19012
19013 /* Load all ENGINE implementations bundled with OpenSSL. */
19014 ENGINE_load_builtin_engines();
19015 #if OPENSSL_VERSION_NUMBER < 0x10100000L
19016 OPENSSL_config(NULL);
19017 #endif /* prior to OpenSSL-1.1.x */
19018
19019 e = ENGINE_by_id(tls_crypto_device);
19020 if (e != NULL) {
19021 if (ENGINE_init(e)) {
19022 if (ENGINE_set_default(e, ENGINE_METHOD_ALL)) {
19023 ENGINE_finish(e);
19024 ENGINE_free(e);
19025
19026 tls_log("using TLSCryptoDevice '%s'", tls_crypto_device);
19027
19028 } else {
19029 /* The requested driver could not be used as the default for
19030 * some odd reason.
19031 */
19032 tls_log("unable to register TLSCryptoDevice '%s' as the "
19033 "default: %s", tls_crypto_device, tls_get_errors());
19034
19035 ENGINE_finish(e);
19036 ENGINE_free(e);
19037 e = NULL;
19038 tls_crypto_device = NULL;
19039 }
19040
19041 } else {
19042 /* The requested driver could not be initialized. */
19043 tls_log("unable to initialize TLSCryptoDevice '%s': %s",
19044 tls_crypto_device, tls_get_errors());
19045
19046 ENGINE_free(e);
19047 e = NULL;
19048 tls_crypto_device = NULL;
19049 }
19050
19051 } else {
19052 /* The requested driver is not available. */
19053 tls_log("TLSCryptoDevice '%s' is not available", tls_crypto_device);
19054 tls_crypto_device = NULL;
19055 }
19056 }
19057 # else
19058 tls_log("%s", "TLSCryptoDevice not supported by OpenSSL");
19059 # endif /* PR_USE_OPENSSL_ENGINE */
19060 }
19061 #endif
19062
19063 /* Install our data channel NetIO handlers. */
19064 tls_netio_install_data();
19065
19066 pr_event_register(&tls_module, "core.exit", tls_exit_ev, NULL);
19067
19068 /* There are several timeouts which can cause the client to be disconnected;
19069 * register a listener for them which can politely/cleanly shut the SSL/TLS
19070 * session down before the connection is closed.
19071 */
19072 pr_event_register(&tls_module, "core.timeout-idle", tls_timeout_ev, NULL);
19073 pr_event_register(&tls_module, "core.timeout-login", tls_timeout_ev, NULL);
19074 pr_event_register(&tls_module, "core.timeout-no-transfer", tls_timeout_ev,
19075 NULL);
19076 pr_event_register(&tls_module, "core.timeout-session", tls_timeout_ev, NULL);
19077 pr_event_register(&tls_module, "core.timeout-stalled", tls_timeout_ev, NULL);
19078
19079 /* Add the additional features implemented by this module into the
19080 * list, to be displayed in response to a FEAT command.
19081 */
19082 pr_feat_add("AUTH TLS");
19083 pr_feat_add("CCC");
19084 pr_feat_add("PBSZ");
19085 pr_feat_add("PROT");
19086 pr_feat_add("SSCN");
19087
19088 /* Add the commands handled by this module to the HELP list. */
19089 pr_help_add(C_AUTH, _("<sp> base64-data"), TRUE);
19090 pr_help_add(C_PBSZ, _("<sp> protection buffer size"), TRUE);
19091 pr_help_add(C_PROT, _("<sp> protection code"), TRUE);
19092
19093 if (tls_opts & TLS_OPT_USE_IMPLICIT_SSL) {
19094 uint64_t start_ms = 0;
19095
19096 tls_log("%s", "TLSOption UseImplicitSSL in effect, starting SSL/TLS "
19097 "handshake");
19098
19099 if (pr_trace_get_level(timing_channel) > 0) {
19100 pr_gettimeofday_millis(&start_ms);
19101 }
19102
19103 if (tls_accept(session.c, FALSE) < 0) {
19104 tls_log("%s", "implicit SSL/TLS negotiation failed on control channel");
19105
19106 /* Rather than returning an error to the init callback, we disconnect
19107 * the session ourselves here. Makes for slightly nicer logging.
19108 */
19109 pr_response_send_async(R_421, _("TLS handshake failed"));
19110 pr_session_disconnect(&tls_module, PR_SESS_DISCONNECT_CLIENT_EOF,
19111 "Failed TLS handshake");
19112 }
19113
19114 tls_flags |= TLS_SESS_ON_CTRL;
19115
19116 if (tls_required_on_data != -1) {
19117 tls_flags |= TLS_SESS_NEED_DATA_PROT;
19118 }
19119
19120 if (pr_trace_get_level(timing_channel) >= 4) {
19121 unsigned long elapsed_ms;
19122 uint64_t finish_ms;
19123
19124 pr_gettimeofday_millis(&finish_ms);
19125
19126 elapsed_ms = (unsigned long) (finish_ms - session.connect_time_ms);
19127 pr_trace_msg(timing_channel, 4,
19128 "Time before TLS ctrl handshake: %lu ms", elapsed_ms);
19129
19130 elapsed_ms = (unsigned long) (finish_ms - start_ms);
19131 pr_trace_msg(timing_channel, 4,
19132 "TLS ctrl handshake duration: %lu ms", elapsed_ms);
19133 }
19134
19135 pr_session_set_protocol("ftps");
19136 session.rfc2228_mech = "TLS";
19137 }
19138
19139 return 0;
19140 }
19141
19142 #if defined(PR_USE_CTRLS)
19143 static ctrls_acttab_t tls_acttab[] = {
19144 { "clear", NULL, NULL, NULL },
19145 { "info", NULL, NULL, NULL },
19146 { "ocspcache", NULL, NULL, NULL },
19147 { "sesscache", NULL, NULL, NULL },
19148
19149 { NULL, NULL, NULL, NULL }
19150 };
19151 #endif /* PR_USE_CTRLS */
19152
19153 /* Module API tables
19154 */
19155
19156 static conftable tls_conftab[] = {
19157 { "TLSCACertificateFile", set_tlscacertfile, NULL },
19158 { "TLSCACertificatePath", set_tlscacertpath, NULL },
19159 { "TLSCARevocationFile", set_tlscacrlfile, NULL },
19160 { "TLSCARevocationPath", set_tlscacrlpath, NULL },
19161 { "TLSCertificateChainFile", set_tlscertchain, NULL },
19162 { "TLSCipherSuite", set_tlsciphersuite, NULL },
19163 { "TLSControlsACLs", set_tlsctrlsacls, NULL },
19164 { "TLSCryptoDevice", set_tlscryptodevice, NULL },
19165 { "TLSDHParamFile", set_tlsdhparamfile, NULL },
19166 { "TLSDSACertificateFile", set_tlsdsacertfile, NULL },
19167 { "TLSDSACertificateKeyFile", set_tlsdsakeyfile, NULL },
19168 { "TLSECCertificateFile", set_tlseccertfile, NULL },
19169 { "TLSECCertificateKeyFile", set_tlseckeyfile, NULL },
19170 { "TLSECDHCurve", set_tlsecdhcurve, NULL },
19171 { "TLSEngine", set_tlsengine, NULL },
19172 { "TLSLog", set_tlslog, NULL },
19173 { "TLSMasqueradeAddress", set_tlsmasqaddr, NULL },
19174 { "TLSNextProtocol", set_tlsnextprotocol, NULL },
19175 { "TLSOptions", set_tlsoptions, NULL },
19176 { "TLSPassPhraseProvider", set_tlspassphraseprovider, NULL },
19177 { "TLSPKCS12File", set_tlspkcs12file, NULL },
19178 { "TLSPreSharedKey", set_tlspresharedkey, NULL },
19179 { "TLSProtocol", set_tlsprotocol, NULL },
19180 { "TLSRandomSeed", set_tlsrandseed, NULL },
19181 { "TLSRenegotiate", set_tlsrenegotiate, NULL },
19182 { "TLSRequired", set_tlsrequired, NULL },
19183 { "TLSRSACertificateFile", set_tlsrsacertfile, NULL },
19184 { "TLSRSACertificateKeyFile", set_tlsrsakeyfile, NULL },
19185 { "TLSServerCipherPreference",set_tlsservercipherpreference, NULL },
19186 { "TLSServerInfoFile", set_tlsserverinfofile, NULL },
19187 { "TLSSessionCache", set_tlssessioncache, NULL },
19188 { "TLSSessionTicketKeys", set_tlssessionticketkeys, NULL },
19189 { "TLSSessionTickets", set_tlssessiontickets, NULL },
19190 { "TLSStapling", set_tlsstapling, NULL },
19191 { "TLSStaplingCache", set_tlsstaplingcache, NULL },
19192 { "TLSStaplingOptions", set_tlsstaplingoptions, NULL },
19193 { "TLSStaplingResponder", set_tlsstaplingresponder, NULL },
19194 { "TLSStaplingTimeout", set_tlsstaplingtimeout, NULL },
19195 { "TLSTimeoutHandshake", set_tlstimeouthandshake,NULL },
19196 { "TLSUserName", set_tlsusername, NULL },
19197 { "TLSVerifyClient", set_tlsverifyclient, NULL },
19198 { "TLSVerifyDepth", set_tlsverifydepth, NULL },
19199 { "TLSVerifyOrder", set_tlsverifyorder, NULL },
19200 { "TLSVerifyServer", set_tlsverifyserver, NULL },
19201 { NULL , NULL, NULL}
19202 };
19203
19204 static cmdtable tls_cmdtab[] = {
19205 { PRE_CMD, C_ANY, G_NONE, tls_any, FALSE, FALSE },
19206 { CMD, C_AUTH, G_NONE, tls_auth, FALSE, FALSE, CL_SEC },
19207 { CMD, C_CCC, G_NONE, tls_ccc, TRUE, FALSE, CL_SEC },
19208 { CMD, C_PBSZ, G_NONE, tls_pbsz, FALSE, FALSE, CL_SEC },
19209 { CMD, C_PROT, G_NONE, tls_prot, FALSE, FALSE, CL_SEC },
19210 { CMD, "SSCN", G_NONE, tls_sscn, TRUE, FALSE, CL_SEC },
19211 { POST_CMD, C_PASS, G_NONE, tls_post_pass, FALSE, FALSE },
19212 { POST_CMD, C_USER, G_NONE, tls_post_user, FALSE, FALSE },
19213 { POST_CMD, C_AUTH, G_NONE, tls_post_auth, FALSE, FALSE },
19214 { LOG_CMD, C_AUTH, G_NONE, tls_log_auth, FALSE, FALSE },
19215 { LOG_CMD_ERR,C_AUTH, G_NONE, tls_log_auth, FALSE, FALSE },
19216 { 0, NULL }
19217 };
19218
19219 static authtable tls_authtab[] = {
19220 { 0, "auth", tls_authenticate },
19221 { 0, "check", tls_auth_check },
19222 { 0, "requires_pass", tls_authenticate },
19223 { 0, NULL }
19224 };
19225
19226 module tls_module = {
19227
19228 /* Always NULL */
19229 NULL, NULL,
19230
19231 /* Module API version */
19232 0x20,
19233
19234 /* Module name */
19235 "tls",
19236
19237 /* Module configuration handler table */
19238 tls_conftab,
19239
19240 /* Module command handler table */
19241 tls_cmdtab,
19242
19243 /* Module authentication handler table */
19244 tls_authtab,
19245
19246 /* Module initialization */
19247 tls_init,
19248
19249 /* Session initialization */
19250 tls_sess_init,
19251
19252 /* Module version */
19253 MOD_TLS_VERSION
19254 };