1 /*
2  * mod_tls - An RFC2228 SSL/TLS module for ProFTPD
3  *
4  * Copyright (c) 2000-2002 Peter 'Luna' Runestig <peter@runestig.com>
5  * Copyright (c) 2002-2021 TJ Saunders <tj@castaglia.org>
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 #if defined(LIBRESSL_VERSION_NUMBER)
47 # define HAVE_LIBRESSL	1
48 #endif
49 
50 /* Note that the openssl/ssl.h header is already included in mod_tls.h, so
51  * we don't need to include it here.
52 */
53 
54 #include <openssl/err.h>
55 #include <openssl/conf.h>
56 #include <openssl/crypto.h>
57 #include <openssl/evp.h>
58 #include <openssl/ssl.h>
59 #include <openssl/ssl3.h>
60 #include <openssl/x509v3.h>
61 #include <openssl/pkcs12.h>
62 #include <openssl/rand.h>
63 #if OPENSSL_VERSION_NUMBER > 0x000907000L
64 # include <openssl/engine.h>
65 # ifdef PR_USE_OPENSSL_OCSP
66 #  include <openssl/ocsp.h>
67 # endif /* PR_USE_OPENSSL_OCSP */
68 #endif
69 #ifdef PR_USE_OPENSSL_ECC
70 # include <openssl/ec.h>
71 # include <openssl/ecdh.h>
72 #endif /* PR_USE_OPENSSL_ECC */
73 
74 #ifdef HAVE_MLOCK
75 # include <sys/mman.h>
76 #endif
77 
78 #define MOD_TLS_VERSION		"mod_tls/2.9"
79 
80 /* Make sure the version of proftpd is as necessary. */
81 #if PROFTPD_VERSION_NUMBER < 0x0001030602
82 # error "ProFTPD 1.3.6rc2 or later required"
83 #endif
84 
85 extern pr_response_t *resp_list, *resp_err_list;
86 extern session_t session;
87 extern xaset_t *server_list;
88 extern int ServerUseReverseDNS;
89 
90 static const char *trace_channel = "tls";
91 
get_dh(BIGNUM * p,BIGNUM * g)92 static DH *get_dh(BIGNUM *p, BIGNUM *g) {
93   DH *dh;
94 
95   dh = DH_new();
96   if (dh == NULL) {
97     return NULL;
98   }
99 
100 #if OPENSSL_VERSION_NUMBER >= 0x10100000L && \
101     !defined(HAVE_LIBRESSL)
102   if (DH_set0_pqg(dh, p, NULL, g) != 1) {
103     pr_trace_msg(trace_channel, 3, "error setting DH p/q parameters: %s",
104       ERR_error_string(ERR_get_error(), NULL));
105     DH_free(dh);
106     return NULL;
107   }
108 #else
109   dh->p = p;
110   dh->g = g;
111 #endif /* OpenSSL 1.1.x and later */
112 
113   return dh;
114 }
115 
read_cert(FILE * fh,SSL_CTX * ctx)116 static X509 *read_cert(FILE *fh, SSL_CTX *ctx) {
117   pem_password_cb *cb;
118   void *cb_data;
119 
120 #if OPENSSL_VERSION_NUMBER >= 0x10100000L && \
121     !defined(HAVE_LIBRESSL)
122   cb = SSL_CTX_get_default_passwd_cb(ctx);
123   cb_data = SSL_CTX_get_default_passwd_cb_userdata(ctx);
124 #else
125   cb = ctx->default_passwd_callback;
126   cb_data = ctx->default_passwd_callback_userdata;
127 #endif /* OpenSSL-1.1.x and later */
128 
129   return PEM_read_X509(fh, NULL, cb, cb_data);
130 }
131 
get_pkey_type(EVP_PKEY * pkey)132 static int get_pkey_type(EVP_PKEY *pkey) {
133   int pkey_type;
134 
135 #if OPENSSL_VERSION_NUMBER >= 0x10100000L && \
136     !defined(HAVE_LIBRESS)
137   pkey_type = EVP_PKEY_base_id(pkey);
138 #else
139   pkey_type = EVP_PKEY_type(pkey->type);
140 #endif /* OpenSSL 1.1.x and later */
141 
142   return pkey_type;
143 }
144 
145 /* DH parameters.  These are generated using:
146  *
147  *  # openssl dhparam -2|-5 512|768|1024|1536|2048 -C
148  *
149  * These should be regenerated periodically by the mod_tls maintainer.
150  * Last updated on 2017-11-05.
151  */
152 
153 /*
154 -----BEGIN DH PARAMETERS-----
155 MEYCQQCL+zVkxPxBAhTTb+fy7WHmJquLvuQi64x++T+GwWyF+xdx9uuVJMTM4CT6
156 mNmOUzVgDgqF4MOsdM/lBBpGIf6TAgEC
157 -----END DH PARAMETERS-----
158 */
159 
160 static unsigned char dh512_p[] = {
161   0x8B, 0xFB, 0x35, 0x64, 0xC4, 0xFC, 0x41, 0x02, 0x14, 0xD3,
162   0x6F, 0xE7, 0xF2, 0xED, 0x61, 0xE6, 0x26, 0xAB, 0x8B, 0xBE,
163   0xE4, 0x22, 0xEB, 0x8C, 0x7E, 0xF9, 0x3F, 0x86, 0xC1, 0x6C,
164   0x85, 0xFB, 0x17, 0x71, 0xF6, 0xEB, 0x95, 0x24, 0xC4, 0xCC,
165   0xE0, 0x24, 0xFA, 0x98, 0xD9, 0x8E, 0x53, 0x35, 0x60, 0x0E,
166   0x0A, 0x85, 0xE0, 0xC3, 0xAC, 0x74, 0xCF, 0xE5, 0x04, 0x1A,
167   0x46, 0x21, 0xFE, 0x93
168 };
169 
170 static unsigned char dh512_g[] = {
171   0x02,
172 };
173 
get_dh512(void)174 static DH *get_dh512(void) {
175   BIGNUM *p, *g;
176 
177   p = BN_bin2bn(dh512_p, sizeof(dh512_p), NULL);
178   g = BN_bin2bn(dh512_g, sizeof(dh512_g), NULL);
179   if (p == NULL ||
180       g == NULL) {
181     return NULL;
182   }
183 
184   return get_dh(p, g);
185 }
186 
187 /*
188 -----BEGIN DH PARAMETERS-----
189 MGYCYQDnYwkZ4E2h4fHgF2bPXiIJN646dxUCkrlo7iqXZOQYmv6hPvKOZ4UQnAKk
190 cCdcdg4k5XOJB0tIMsEhoS54157KeQSyRTv+5dWCooH/BURgNMOPwBsEwsO0oO1o
191 PaAFy8sCAQI=
192 -----END DH PARAMETERS-----
193 */
194 
195 static unsigned char dh768_p[] = {
196   0xE7, 0x63, 0x09, 0x19, 0xE0, 0x4D, 0xA1, 0xE1, 0xF1, 0xE0,
197   0x17, 0x66, 0xCF, 0x5E, 0x22, 0x09, 0x37, 0xAE, 0x3A, 0x77,
198   0x15, 0x02, 0x92, 0xB9, 0x68, 0xEE, 0x2A, 0x97, 0x64, 0xE4,
199   0x18, 0x9A, 0xFE, 0xA1, 0x3E, 0xF2, 0x8E, 0x67, 0x85, 0x10,
200   0x9C, 0x02, 0xA4, 0x70, 0x27, 0x5C, 0x76, 0x0E, 0x24, 0xE5,
201   0x73, 0x89, 0x07, 0x4B, 0x48, 0x32, 0xC1, 0x21, 0xA1, 0x2E,
202   0x78, 0xD7, 0x9E, 0xCA, 0x79, 0x04, 0xB2, 0x45, 0x3B, 0xFE,
203   0xE5, 0xD5, 0x82, 0xA2, 0x81, 0xFF, 0x05, 0x44, 0x60, 0x34,
204   0xC3, 0x8F, 0xC0, 0x1B, 0x04, 0xC2, 0xC3, 0xB4, 0xA0, 0xED,
205   0x68, 0x3D, 0xA0, 0x05, 0xCB, 0xCB
206 };
207 
208 static unsigned char dh768_g[] = {
209   0x02,
210 };
211 
get_dh768(void)212 static DH *get_dh768(void) {
213   BIGNUM *p, *g;
214 
215   p = BN_bin2bn(dh768_p, sizeof(dh768_p), NULL);
216   g = BN_bin2bn(dh768_g, sizeof(dh768_g), NULL);
217   if (p == NULL ||
218       g == NULL) {
219     return NULL;
220   }
221 
222   return get_dh(p, g);
223 }
224 
225 /*
226 -----BEGIN DH PARAMETERS-----
227 MIGHAoGBAJV/vSQ/gR3sxcHZjrjh21KCvzpkz87BqRfsFuhJQl175H9VTqbLpAK+
228 uYrLVcBpdMA4zWVzr1vgYhoFzuyWk1iVcJ93o5Nza6wNNeXTa/5hMNCkjIAtpr0e
229 yarRXsIkSWg5fHCsTDgAnARmdNw3/Aogw4JjONxRtVm4BcDfHyBjAgEC
230 -----END DH PARAMETERS-----
231 */
232 
233 static unsigned char dh1024_p[] = {
234   0x95, 0x7F, 0xBD, 0x24, 0x3F, 0x81, 0x1D, 0xEC, 0xC5, 0xC1,
235   0xD9, 0x8E, 0xB8, 0xE1, 0xDB, 0x52, 0x82, 0xBF, 0x3A, 0x64,
236   0xCF, 0xCE, 0xC1, 0xA9, 0x17, 0xEC, 0x16, 0xE8, 0x49, 0x42,
237   0x5D, 0x7B, 0xE4, 0x7F, 0x55, 0x4E, 0xA6, 0xCB, 0xA4, 0x02,
238   0xBE, 0xB9, 0x8A, 0xCB, 0x55, 0xC0, 0x69, 0x74, 0xC0, 0x38,
239   0xCD, 0x65, 0x73, 0xAF, 0x5B, 0xE0, 0x62, 0x1A, 0x05, 0xCE,
240   0xEC, 0x96, 0x93, 0x58, 0x95, 0x70, 0x9F, 0x77, 0xA3, 0x93,
241   0x73, 0x6B, 0xAC, 0x0D, 0x35, 0xE5, 0xD3, 0x6B, 0xFE, 0x61,
242   0x30, 0xD0, 0xA4, 0x8C, 0x80, 0x2D, 0xA6, 0xBD, 0x1E, 0xC9,
243   0xAA, 0xD1, 0x5E, 0xC2, 0x24, 0x49, 0x68, 0x39, 0x7C, 0x70,
244   0xAC, 0x4C, 0x38, 0x00, 0x9C, 0x04, 0x66, 0x74, 0xDC, 0x37,
245   0xFC, 0x0A, 0x20, 0xC3, 0x82, 0x63, 0x38, 0xDC, 0x51, 0xB5,
246   0x59, 0xB8, 0x05, 0xC0, 0xDF, 0x1F, 0x20, 0x63
247 };
248 
249 static unsigned char dh1024_g[] = {
250   0x02,
251 };
252 
get_dh1024(void)253 static DH *get_dh1024(void) {
254   BIGNUM *p, *g;
255 
256   p = BN_bin2bn(dh1024_p, sizeof(dh1024_p), NULL);
257   g = BN_bin2bn(dh1024_g, sizeof(dh1024_g), NULL);
258   if (p == NULL ||
259       g == NULL) {
260     return NULL;
261   }
262 
263   return get_dh(p, g);
264 }
265 
266 /*
267 -----BEGIN DH PARAMETERS-----
268 MIHHAoHBAP+InzoPE/HUefE6f38OjaAG40sy97P7d6Ha9WVQoY+G/dpjuuOXXAm0
269 BidROsE7Pt+VZKNZF3Xy5Qw6DvblwwNykf1/ndZJO/IETJ+afQMiLKp6l/FDq3qn
270 xDCL8xJA/PjO9d3DSBZhzBJPKf+2U6B2V6U1ljXgakhRtOnwL6uRU1rKreHZv7cB
271 0WbQAJpJ+pw4+asBU4lJVAa6mfWmRGHxyqcvXKBem4ZlxPMTjsV3Ynkey/Fe6ByA
272 I6e6E/43iwIBAg==
273 -----END DH PARAMETERS-----
274 */
275 
276 static unsigned char dh1536_p[] = {
277   0xFF, 0x88, 0x9F, 0x3A, 0x0F, 0x13, 0xF1, 0xD4, 0x79, 0xF1,
278   0x3A, 0x7F, 0x7F, 0x0E, 0x8D, 0xA0, 0x06, 0xE3, 0x4B, 0x32,
279   0xF7, 0xB3, 0xFB, 0x77, 0xA1, 0xDA, 0xF5, 0x65, 0x50, 0xA1,
280   0x8F, 0x86, 0xFD, 0xDA, 0x63, 0xBA, 0xE3, 0x97, 0x5C, 0x09,
281   0xB4, 0x06, 0x27, 0x51, 0x3A, 0xC1, 0x3B, 0x3E, 0xDF, 0x95,
282   0x64, 0xA3, 0x59, 0x17, 0x75, 0xF2, 0xE5, 0x0C, 0x3A, 0x0E,
283   0xF6, 0xE5, 0xC3, 0x03, 0x72, 0x91, 0xFD, 0x7F, 0x9D, 0xD6,
284   0x49, 0x3B, 0xF2, 0x04, 0x4C, 0x9F, 0x9A, 0x7D, 0x03, 0x22,
285   0x2C, 0xAA, 0x7A, 0x97, 0xF1, 0x43, 0xAB, 0x7A, 0xA7, 0xC4,
286   0x30, 0x8B, 0xF3, 0x12, 0x40, 0xFC, 0xF8, 0xCE, 0xF5, 0xDD,
287   0xC3, 0x48, 0x16, 0x61, 0xCC, 0x12, 0x4F, 0x29, 0xFF, 0xB6,
288   0x53, 0xA0, 0x76, 0x57, 0xA5, 0x35, 0x96, 0x35, 0xE0, 0x6A,
289   0x48, 0x51, 0xB4, 0xE9, 0xF0, 0x2F, 0xAB, 0x91, 0x53, 0x5A,
290   0xCA, 0xAD, 0xE1, 0xD9, 0xBF, 0xB7, 0x01, 0xD1, 0x66, 0xD0,
291   0x00, 0x9A, 0x49, 0xFA, 0x9C, 0x38, 0xF9, 0xAB, 0x01, 0x53,
292   0x89, 0x49, 0x54, 0x06, 0xBA, 0x99, 0xF5, 0xA6, 0x44, 0x61,
293   0xF1, 0xCA, 0xA7, 0x2F, 0x5C, 0xA0, 0x5E, 0x9B, 0x86, 0x65,
294   0xC4, 0xF3, 0x13, 0x8E, 0xC5, 0x77, 0x62, 0x79, 0x1E, 0xCB,
295   0xF1, 0x5E, 0xE8, 0x1C, 0x80, 0x23, 0xA7, 0xBA, 0x13, 0xFE,
296   0x37, 0x8B
297 };
298 
299 static unsigned char dh1536_g[] = {
300   0x02,
301 };
302 
get_dh1536(void)303 static DH *get_dh1536(void) {
304   BIGNUM *p, *g;
305 
306   p = BN_bin2bn(dh1536_p, sizeof(dh1536_p), NULL);
307   g = BN_bin2bn(dh1536_g, sizeof(dh1536_g), NULL);
308   if (p == NULL ||
309       g == NULL) {
310     return NULL;
311   }
312 
313   return get_dh(p, g);
314 }
315 
316 /*
317 -----BEGIN DH PARAMETERS-----
318 MIIBCAKCAQEA6reKef5mzbMM6SjeNRpZ1or1A3DYkess2nSPteTU4uFuDIL3mPpJ
319 HffFlrYurSb6YbK4fNWUZJd//CMEpOZQUE3C1KLEdHrBnW8SvgvuA/ts4j+LaDL2
320 0GegAOY90d3FgYtP8NKBaBVF+5yRmB/h4QquXctNdR6+megs1HnFoTEoVvZR7EkN
321 36C5j2me0vQ3E77mvAHtFnnB4nrYf6otj2DO81rt2QeeKEtfO1rd/fmqlN0aR1c0
322 OUArFXmjFKwic9UJfp6mpPE+ySso6EGNqss+Fippo+CoZCSVBPG95EPf3J9xR4/g
323 pjsF+NHDTls/hzQkq7/10NLB6mU4WwMVVwIBBQ==
324 -----END DH PARAMETERS-----
325 */
326 
327 static unsigned char dh2048_p[] = {
328   0xEA, 0xB7, 0x8A, 0x79, 0xFE, 0x66, 0xCD, 0xB3, 0x0C, 0xE9,
329   0x28, 0xDE, 0x35, 0x1A, 0x59, 0xD6, 0x8A, 0xF5, 0x03, 0x70,
330   0xD8, 0x91, 0xEB, 0x2C, 0xDA, 0x74, 0x8F, 0xB5, 0xE4, 0xD4,
331   0xE2, 0xE1, 0x6E, 0x0C, 0x82, 0xF7, 0x98, 0xFA, 0x49, 0x1D,
332   0xF7, 0xC5, 0x96, 0xB6, 0x2E, 0xAD, 0x26, 0xFA, 0x61, 0xB2,
333   0xB8, 0x7C, 0xD5, 0x94, 0x64, 0x97, 0x7F, 0xFC, 0x23, 0x04,
334   0xA4, 0xE6, 0x50, 0x50, 0x4D, 0xC2, 0xD4, 0xA2, 0xC4, 0x74,
335   0x7A, 0xC1, 0x9D, 0x6F, 0x12, 0xBE, 0x0B, 0xEE, 0x03, 0xFB,
336   0x6C, 0xE2, 0x3F, 0x8B, 0x68, 0x32, 0xF6, 0xD0, 0x67, 0xA0,
337   0x00, 0xE6, 0x3D, 0xD1, 0xDD, 0xC5, 0x81, 0x8B, 0x4F, 0xF0,
338   0xD2, 0x81, 0x68, 0x15, 0x45, 0xFB, 0x9C, 0x91, 0x98, 0x1F,
339   0xE1, 0xE1, 0x0A, 0xAE, 0x5D, 0xCB, 0x4D, 0x75, 0x1E, 0xBE,
340   0x99, 0xE8, 0x2C, 0xD4, 0x79, 0xC5, 0xA1, 0x31, 0x28, 0x56,
341   0xF6, 0x51, 0xEC, 0x49, 0x0D, 0xDF, 0xA0, 0xB9, 0x8F, 0x69,
342   0x9E, 0xD2, 0xF4, 0x37, 0x13, 0xBE, 0xE6, 0xBC, 0x01, 0xED,
343   0x16, 0x79, 0xC1, 0xE2, 0x7A, 0xD8, 0x7F, 0xAA, 0x2D, 0x8F,
344   0x60, 0xCE, 0xF3, 0x5A, 0xED, 0xD9, 0x07, 0x9E, 0x28, 0x4B,
345   0x5F, 0x3B, 0x5A, 0xDD, 0xFD, 0xF9, 0xAA, 0x94, 0xDD, 0x1A,
346   0x47, 0x57, 0x34, 0x39, 0x40, 0x2B, 0x15, 0x79, 0xA3, 0x14,
347   0xAC, 0x22, 0x73, 0xD5, 0x09, 0x7E, 0x9E, 0xA6, 0xA4, 0xF1,
348   0x3E, 0xC9, 0x2B, 0x28, 0xE8, 0x41, 0x8D, 0xAA, 0xCB, 0x3E,
349   0x16, 0x2A, 0x69, 0xA3, 0xE0, 0xA8, 0x64, 0x24, 0x95, 0x04,
350   0xF1, 0xBD, 0xE4, 0x43, 0xDF, 0xDC, 0x9F, 0x71, 0x47, 0x8F,
351   0xE0, 0xA6, 0x3B, 0x05, 0xF8, 0xD1, 0xC3, 0x4E, 0x5B, 0x3F,
352   0x87, 0x34, 0x24, 0xAB, 0xBF, 0xF5, 0xD0, 0xD2, 0xC1, 0xEA,
353   0x65, 0x38, 0x5B, 0x03, 0x15, 0x57
354 };
355 
356 static unsigned char dh2048_g[] = {
357   0x05,
358 };
359 
get_dh2048(void)360 static DH *get_dh2048(void) {
361   BIGNUM *p, *g;
362 
363   p = BN_bin2bn(dh2048_p, sizeof(dh2048_p), NULL);
364   g = BN_bin2bn(dh2048_g, sizeof(dh2048_g), NULL);
365   if (p == NULL ||
366       g == NULL) {
367     return NULL;
368   }
369 
370   return get_dh(p, g);
371 }
372 
373 /* ASN1_BIT_STRING_cmp was renamed in 0.9.5 */
374 #if OPENSSL_VERSION_NUMBER < 0x00905100L
375 # define M_ASN1_BIT_STRING_cmp ASN1_BIT_STRING_cmp
376 #endif
377 
378 #if defined(SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB)
379 # define TLS_USE_SESSION_TICKETS
380 #endif
381 
382 module tls_module;
383 
384 struct tls_next_proto {
385   const char *proto;
386   unsigned char *encoded_proto;
387   unsigned int encoded_protolen;
388 };
389 
390 typedef struct tls_pkey_obj {
391   struct tls_pkey_obj *next;
392   pool *pool;
393 
394   size_t pkeysz;
395 
396   char *rsa_pkey;
397   int rsa_passlen;
398   void *rsa_pkey_ptr;
399 
400   char *dsa_pkey;
401   int dsa_passlen;
402   void *dsa_pkey_ptr;
403 
404 #ifdef PR_USE_OPENSSL_ECC
405   char *ec_pkey;
406   int ec_passlen;
407   void *ec_pkey_ptr;
408 #endif /* PR_USE_OPENSSL_ECC */
409 
410   /* Used for stashing the password for a PKCS12 file, which should
411    * contain a certificate.  Any passphrase for the private key for that
412    * certificate should be in one of the above RSA/DSA buffers.
413    */
414   char *pkcs12_passwd;
415   int pkcs12_passlen;
416   void *pkcs12_passwd_ptr;
417 
418   unsigned int flags;
419   unsigned int sid;
420   const char *path;
421 
422 } tls_pkey_t;
423 
424 #define TLS_PKEY_USE_RSA		0x0100
425 #define TLS_PKEY_USE_DSA		0x0200
426 #define TLS_PKEY_USE_EC			0x0400
427 
428 static tls_pkey_t *tls_pkey_list = NULL;
429 static unsigned int tls_npkeys = 0;
430 
431 #define TLS_DEFAULT_CIPHER_SUITE	"DEFAULT:!ADH:!EXPORT:!DES"
432 #define TLS_DEFAULT_NEXT_PROTO		"ftp"
433 
434 /* SSL record/buffer sizes */
435 #define TLS_HANDSHAKE_WRITE_BUFFER_SIZE			1400
436 
437 /* SSL adaptive buffer sizes/values */
438 #define TLS_DATA_ADAPTIVE_WRITE_MIN_BUFFER_SIZE		(4 * 1024)
439 #define TLS_DATA_ADAPTIVE_WRITE_MAX_BUFFER_SIZE		(16 * 1024)
440 #define TLS_DATA_ADAPTIVE_WRITE_BOOST_THRESHOLD		(1024 * 1024)
441 #define TLS_DATA_ADAPTIVE_WRITE_BOOST_INTERVAL_MS	1000
442 
443 static uint64_t tls_data_adaptive_bytes_written_ms = 0L;
444 static off_t tls_data_adaptive_bytes_written_count = 0;
445 
446 /* Module variables */
447 #if OPENSSL_VERSION_NUMBER > 0x000907000L
448 static const char *tls_crypto_device = NULL;
449 #endif
450 static unsigned char tls_engine = FALSE;
451 static unsigned long tls_flags = 0UL, tls_opts = 0UL;
452 static pool *tls_pool = NULL;
453 static tls_pkey_t *tls_pkey = NULL;
454 static int tls_logfd = -1;
455 #if defined(PR_USE_OPENSSL_OCSP)
456 static int tls_stapling = FALSE;
457 static unsigned long tls_stapling_opts = 0UL;
458 # define TLS_STAPLING_OPT_NO_NONCE		0x0001
459 # define TLS_STAPLING_OPT_NO_VERIFY		0x0002
460 # define TLS_STAPLING_OPT_NO_FAKE_TRY_LATER	0x0004
461 static const char *tls_stapling_responder = NULL;
462 
463 #define TLS_DEFAULT_STAPLING_TIMEOUT	10
464 static unsigned int tls_stapling_timeout = TLS_DEFAULT_STAPLING_TIMEOUT;
465 #endif
466 
467 static char *tls_passphrase_provider = NULL;
468 #define TLS_PASSPHRASE_TIMEOUT		10
469 #define TLS_PASSPHRASE_FL_RSA_KEY	0x0001
470 #define TLS_PASSPHRASE_FL_DSA_KEY	0x0002
471 #define TLS_PASSPHRASE_FL_PKCS12_PASSWD	0x0004
472 #define TLS_PASSPHRASE_FL_EC_KEY	0x0008
473 
474 #define TLS_PROTO_SSL_V3		0x0001
475 #define TLS_PROTO_TLS_V1		0x0002
476 #define TLS_PROTO_TLS_V1_1		0x0004
477 #define TLS_PROTO_TLS_V1_2		0x0008
478 #define TLS_PROTO_TLS_V1_3		0x0010
479 
480 #if OPENSSL_VERSION_NUMBER >= 0x10101000L
481 # define TLS_PROTO_DEFAULT		(TLS_PROTO_TLS_V1|TLS_PROTO_TLS_V1_1|TLS_PROTO_TLS_V1_2|TLS_PROTO_TLS_V1_3)
482 #elif OPENSSL_VERSION_NUMBER >= 0x10001000L
483 # define TLS_PROTO_DEFAULT		(TLS_PROTO_TLS_V1|TLS_PROTO_TLS_V1_1|TLS_PROTO_TLS_V1_2)
484 #else
485 # define TLS_PROTO_DEFAULT		(TLS_PROTO_TLS_V1)
486 #endif /* OpenSSL 1.0.1 or later */
487 
488 static unsigned int tls_protocol = TLS_PROTO_DEFAULT;
489 
490 /* This is used for e.g. "TLSProtocol ALL -SSLv3 ...". */
491 #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)
492 
493 #ifdef SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS
494 static int tls_ssl_opts = (SSL_OP_ALL|SSL_OP_NO_SSLv2|SSL_OP_SINGLE_DH_USE)^SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS;
495 #else
496 /* OpenSSL-0.9.6 and earlier (yes, it appears people still have these versions
497  * installed) does not define the DONT_INSERT_EMPTY_FRAGMENTS option.
498  */
499 static int tls_ssl_opts = SSL_OP_ALL|SSL_OP_NO_SSLv2|SSL_OP_SINGLE_DH_USE;
500 #endif
501 
502 static int tls_required_on_auth = 0;
503 static int tls_required_on_ctrl = 0;
504 static int tls_required_on_data = 0;
505 static unsigned char *tls_authenticated = NULL;
506 
507 /* Define the minimum DH group length we allow (unless the AllowWeakDH
508  * TLSOption is used).  Ideally this would be 2048, per https://weakdh.org,
509  * but for compatibility with older Java versions, which only support up to
510  * 1024, we'll use 1024.  For now.
511  */
512 #define TLS_DH_MIN_LEN				1024
513 
514 /* mod_tls session flags */
515 #define	TLS_SESS_ON_CTRL			0x0001
516 #define TLS_SESS_ON_DATA			0x0002
517 #define TLS_SESS_PBSZ_OK			0x0004
518 #define TLS_SESS_TLS_REQUIRED			0x0010
519 #define TLS_SESS_VERIFY_CLIENT_REQUIRED		0x0020
520 #define TLS_SESS_NO_PASSWD_NEEDED		0x0040
521 #define TLS_SESS_NEED_DATA_PROT			0x0100
522 #define TLS_SESS_CTRL_RENEGOTIATING		0x0200
523 #define TLS_SESS_DATA_RENEGOTIATING		0x0400
524 #define TLS_SESS_HAVE_CCC			0x0800
525 #define TLS_SESS_VERIFY_SERVER			0x1000
526 #define TLS_SESS_VERIFY_SERVER_NO_DNS		0x2000
527 #define TLS_SESS_VERIFY_CLIENT_OPTIONAL		0x4000
528 
529 /* mod_tls option flags */
530 #define TLS_OPT_VERIFY_CERT_FQDN			0x0002
531 #define TLS_OPT_VERIFY_CERT_IP_ADDR			0x0004
532 #define TLS_OPT_ALLOW_DOT_LOGIN				0x0008
533 #define TLS_OPT_EXPORT_CERT_DATA			0x0010
534 #define TLS_OPT_STD_ENV_VARS				0x0020
535 #define TLS_OPT_ALLOW_PER_USER				0x0040
536 #define TLS_OPT_ENABLE_DIAGS				0x0080
537 #define TLS_OPT_NO_SESSION_REUSE_REQUIRED		0x0100
538 #define TLS_OPT_USE_IMPLICIT_SSL			0x0200
539 #define TLS_OPT_ALLOW_CLIENT_RENEGOTIATIONS		0x0400
540 #define TLS_OPT_VERIFY_CERT_CN				0x0800
541 #define TLS_OPT_NO_AUTO_ECDH				0x1000
542 #define TLS_OPT_ALLOW_WEAK_DH				0x2000
543 #define TLS_OPT_IGNORE_SNI				0x4000
544 
545 /* mod_tls SSCN modes */
546 #define TLS_SSCN_MODE_SERVER				0
547 #define TLS_SSCN_MODE_CLIENT				1
548 static unsigned int tls_sscn_mode = TLS_SSCN_MODE_SERVER;
549 
550 /* mod_tls cleanup flags */
551 #define TLS_CLEANUP_FL_SESS_INIT	0x0001
552 
553 /* mod_tls OCSP constants */
554 #define TLS_OCSP_RESP_MAX_AGE_SECS	300
555 
556 /* X509v3 OCSP "must staple" extensions (RFC 7633) */
557 #define TLS_X509V3_TLS_FEAT_OID_TEXT		"1.3.6.1.5.5.7.1.24"
558 #define TLS_X509V3_TLS_FEAT_STATUS_REQUEST 	{ 0x30, 0x03, 0x02, 0x01, 0x05 }
559 #define TLS_X509V3_TLS_FEAT_STATUS_REQUEST_V2	{ 0x30, 0x03, 0x02, 0x01, 0x17 }
560 
561 static char *tls_cipher_suite = NULL;
562 static char *tls_ca_file = NULL, *tls_ca_path = NULL, *tls_ca_chain = NULL;
563 static char *tls_crl_file = NULL, *tls_crl_path = NULL;
564 static char *tls_ec_cert_file = NULL, *tls_ec_key_file = NULL;
565 static void *tls_ecdh_curve = NULL;
566 static char *tls_dsa_cert_file = NULL, *tls_dsa_key_file = NULL;
567 static char *tls_pkcs12_file = NULL;
568 static char *tls_rsa_cert_file = NULL, *tls_rsa_key_file = NULL;
569 static char *tls_rand_file = NULL;
570 #if !defined(OPENSSL_NO_TLSEXT) && \
571     OPENSSL_VERSION_NUMBER >= 0x10002000L
572 static char *tls_serverinfo_file = NULL;
573 #endif /* OPENSSL_NO_TLSEXT */
574 static int tls_use_next_protocol = TRUE;
575 static int tls_use_server_cipher_preference = TRUE;
576 static int tls_use_session_tickets = FALSE;
577 
578 #if defined(PSK_MAX_PSK_LEN)
579 static pr_table_t *tls_psks = NULL;
580 # define TLS_MIN_PSK_LEN	20
581 #endif /* PSK support */
582 
583 /* Timeout given for TLS handshakes.  The default is 5 minutes. */
584 #define TLS_DEFAULT_HANDSHAKE_TIMEOUT		300
585 static unsigned int tls_handshake_timeout = TLS_DEFAULT_HANDSHAKE_TIMEOUT;
586 static unsigned char tls_handshake_timed_out = FALSE;
587 static int tls_handshake_timer_id = -1;
588 
589 /* Note: 9 is the default OpenSSL depth. */
590 #define TLS_DEFAULT_VERIFY_DEPTH	9
591 static int tls_verify_depth = TLS_DEFAULT_VERIFY_DEPTH;
592 
593 #if OPENSSL_VERSION_NUMBER > 0x000907000L
594 /* Renegotiate control channel on TLS sessions after 4 hours, by default. */
595 static int tls_ctrl_renegotiate_timeout = 14400;
596 
597 /* Renegotiate data channel on TLS sessions after 1 gigabyte, by default. */
598 static off_t tls_data_renegotiate_limit = 1024 * 1024 * 1024;
599 
600 /* Timeout given for renegotiations to occur before the TLS session is
601  * shutdown.  The default is 30 seconds.
602  */
603 static int tls_renegotiate_timeout = 30;
604 
605 /* Is client acceptance of a requested renegotiation required? */
606 static unsigned char tls_renegotiate_required = TRUE;
607 #endif
608 
609 #define TLS_NETIO_NOTE		"mod_tls.SSL"
610 
611 static pr_netio_t *tls_ctrl_netio = NULL;
612 static pr_netio_stream_t *tls_ctrl_rd_nstrm = NULL;
613 static pr_netio_stream_t *tls_ctrl_wr_nstrm = NULL;
614 
615 static pr_netio_t *tls_data_netio = NULL;
616 static pr_netio_stream_t *tls_data_rd_nstrm = NULL;
617 static pr_netio_stream_t *tls_data_wr_nstrm = NULL;
618 
619 static tls_sess_cache_t *tls_sess_cache = NULL;
620 static tls_ocsp_cache_t *tls_ocsp_cache = NULL;
621 
622 #if defined(PR_USE_OPENSSL_SSL_SESSION_TICKET_CALLBACK)
623 /* These are used to ensure that TLSv1.3 session tickets are from the same
624  * FTP session.
625  */
626 static const void *tls_ctrl_ticket_appdata = NULL;
627 static size_t tls_ctrl_ticket_appdatasz = 0, tls_ctrl_ticket_appdata_len = 0;
628 static const void *tls_data_ticket_appdata = NULL;
629 static size_t tls_data_ticket_appdatasz = 0, tls_data_ticket_appdata_len = 0;
630 #endif /* PR_USE_OPENSSL_SSL_SESSION_TICKET_CALLBACK */
631 
632 /* OpenSSL variables */
633 static SSL *ctrl_ssl = NULL;
634 static SSL_CTX *ssl_ctx = NULL;
635 static X509_STORE *tls_crl_store = NULL;
636 static array_header *tls_tmp_dhs = NULL;
637 static RSA *tls_tmp_rsa = NULL;
638 
639 static void tls_exit_ev(const void *, void *);
640 static int tls_sess_init(void);
641 
642 /* SSL/TLS support functions */
643 static void tls_closelog(void);
644 static void tls_end_sess(SSL *, conn_t *, int);
645 #define TLS_SHUTDOWN_FL_BIDIRECTIONAL		0x0001
646 
647 static void tls_fatal_error(long, int);
648 static const char *tls_get_errors(void);
649 static const char *tls_get_errors2(pool *p);
650 static char *tls_get_page(size_t, void **);
651 static size_t tls_get_pagesz(void);
652 static int tls_get_passphrase(server_rec *, const char *, const char *,
653   char *, size_t, int);
654 
655 static char *tls_get_subj_name(SSL *);
656 
657 /* Table-based session cache "provider" for SNI sessions only (Issue #924). */
658 static pr_table_t *tls_sni_sess_tab = NULL;
659 
660 static void tls_lookup_all(server_rec *);
661 static int tls_ctx_set_all(server_rec *, SSL_CTX *);
662 static int tls_ctx_set_ca_certs(SSL_CTX *);
663 static int tls_ctx_set_certs(SSL_CTX *, X509 **, X509 **, X509 **);
664 static int tls_ctx_set_crls(SSL_CTX *);
665 static int tls_ctx_set_session_cache(server_rec *, SSL_CTX *);
666 static int tls_ctx_set_session_id_context(server_rec *, SSL_CTX *);
667 static int tls_ctx_set_session_tickets(SSL_CTX *);
668 static int tls_ctx_set_stapling(SSL_CTX *);
669 static int tls_ctx_set_stapling_cache(server_rec *, SSL_CTX *);
670 static int tls_ssl_set_all(server_rec *, SSL *);
671 
672 static int tls_openlog(void);
673 static int tls_seed_prng(void);
674 static int tls_sess_init(void);
675 static void tls_setup_environ(pool *, SSL *);
676 static void tls_setup_notes(pool *, SSL *);
677 static int tls_verify_cb(int, X509_STORE_CTX *);
678 static int tls_verify_crl(int, X509_STORE_CTX *);
679 static int tls_verify_ocsp(int, X509_STORE_CTX *);
680 static char *tls_x509_name_oneline(X509_NAME *);
681 
682 static int tls_readmore(int);
683 static int tls_writemore(int);
684 
685 /* Session cache API */
686 static tls_sess_cache_t *tls_sess_cache_get_cache(const char *);
687 static long tls_sess_cache_get_cache_mode(void);
688 static int tls_sess_cache_open(char *, long);
689 static int tls_sess_cache_close(void);
690 #if defined(PR_USE_CTRLS)
691 static int tls_sess_cache_clear(void);
692 static int tls_sess_cache_remove(void);
693 static int tls_sess_cache_status(pr_ctrls_t *, int);
694 #endif /* PR_USE_CTRLS */
695 static int tls_sess_cache_add_sess_cb(SSL *, SSL_SESSION *);
696 static SSL_SESSION *tls_sess_cache_get_sess_cb(SSL *, unsigned char *, int,
697   int *);
698 static void tls_sess_cache_delete_sess_cb(SSL_CTX *, SSL_SESSION *);
699 
700 /* OCSP response cache API */
701 static tls_ocsp_cache_t *tls_ocsp_cache_get_cache(const char *);
702 static int tls_ocsp_cache_open(char *);
703 static int tls_ocsp_cache_close(void);
704 #if defined(PR_USE_CTRLS)
705 static int tls_ocsp_cache_clear(void);
706 static int tls_ocsp_cache_remove(void);
707 static int tls_ocsp_cache_status(pr_ctrls_t *, int);
708 #endif /* PR_USE_CTRLS */
709 
710 #if defined(TLS_USE_SESSION_TICKETS)
711 /* Default maximum ticket key age: 12 hours */
712 static unsigned int tls_ticket_key_max_age = 43200;
713 
714 /* Maximum number of session ticket keys: 25 (1 per hour, plus leeway) */
715 static unsigned int tls_ticket_key_max_count = 25;
716 static unsigned int tls_ticket_key_curr_count = 0;
717 
718 struct tls_ticket_key {
719   struct tls_ticket_key *next, *prev;
720 
721   /* Memory page pointer and size, for locking. */
722   void *page_ptr;
723   size_t pagesz;
724   int locked;
725   time_t created;
726 
727   /* 16 bytes for the key name, per OpenSSL implementation. */
728   unsigned char key_name[16];
729   unsigned char cipher_key[32];
730   unsigned char hmac_key[32];
731 };
732 
733 /* In-memory list of session ticket keys, newest key first.  Note that the
734  * memory pages used for a ticket key will be mlock(2)'d into memory, where
735  * possible.
736  *
737  * Ticket keys will be generated randomly, based on the timeout.  Expired
738  * ticket keys will be destroyed when a new key is generated.  Tickets
739  * encrypted with older keys will be renewed using the newest key.
740  */
741 static xaset_t *tls_ticket_keys = NULL;
742 #endif
743 
744 #ifdef PR_USE_CTRLS
745 static pool *tls_act_pool = NULL;
746 static ctrls_acttab_t tls_acttab[];
747 #endif /* PR_USE_CTRLS */
748 
749 static int tls_ctrl_need_init_handshake = TRUE;
750 static int tls_data_need_init_handshake = TRUE;
751 
752 static const char *timing_channel = "timing";
753 
tls_keyfile_check_cb(char * buf,int size,int rwflag,void * user_data)754 static int tls_keyfile_check_cb(char *buf, int size, int rwflag,
755     void *user_data) {
756   buf[0] = '\0';
757   return 0;
758 }
759 
tls_get_fingerprint(pool * p,X509 * cert)760 static const char *tls_get_fingerprint(pool *p, X509 *cert) {
761   const EVP_MD *md = EVP_sha1();
762   unsigned char fp[EVP_MAX_MD_SIZE];
763   unsigned int fp_len = 0;
764   char *fp_hex = NULL;
765 
766   if (X509_digest(cert, md, fp, &fp_len) != 1) {
767     pr_trace_msg(trace_channel, 1,
768       "error obtaining %s digest of X509 cert: %s", OBJ_nid2sn(EVP_MD_type(md)),
769       tls_get_errors());
770     errno = EINVAL;
771     return NULL;
772   }
773 
774   fp_hex = pr_str_bin2hex(p, fp, fp_len, 0);
775 
776   pr_trace_msg(trace_channel, 8,
777     "%s fingerprint: %s", OBJ_nid2sn(EVP_MD_type(md)), fp_hex);
778   return fp_hex;
779 }
780 
get_pkey_typestr(int pkey_type)781 static const char *get_pkey_typestr(int pkey_type) {
782   const char *str = "unknown";
783 
784   switch (pkey_type) {
785     case EVP_PKEY_RSA:
786       str = "RSA";
787       break;
788 
789     case EVP_PKEY_DSA:
790       str = "DSA";
791       break;
792 
793 #ifdef PR_USE_OPENSSL_ECC
794     case EVP_PKEY_EC:
795       str = "EC";
796       break;
797 #endif /* PR_USE_OPENSSL_EC */
798   }
799 
800   return str;
801 }
802 
tls_get_fingerprint_from_file(pool * p,const char * path,int expected_pkey_type,const char ** errstr)803 static const char *tls_get_fingerprint_from_file(pool *p, const char *path,
804     int expected_pkey_type, const char **errstr) {
805   FILE *fh;
806   X509 *cert = NULL;
807   const char *fingerprint;
808 
809   fh = fopen(path, "rb");
810   if (fh == NULL) {
811     int xerrno = errno;
812 
813     *errstr = (const char *) pstrdup(p, strerror(xerrno));
814     errno = xerrno;
815     return NULL;
816   }
817 
818   /* As the file may contain sensitive data, we do not want it lingering
819    * around in stdio buffers.
820    */
821   (void) setvbuf(fh, NULL, _IONBF, 0);
822 
823   cert = PEM_read_X509(fh, &cert, NULL, NULL);
824   (void) fclose(fh);
825 
826   if (cert == NULL) {
827     const char *err_msg;
828 
829     err_msg = tls_get_errors2(p);
830     *errstr = err_msg;
831 
832     pr_trace_msg(trace_channel, 1, "error obtaining X509 cert from '%s': %s",
833       path, err_msg);
834     errno = ENOENT;
835     return NULL;
836   }
837 
838   fingerprint = tls_get_fingerprint(p, cert);
839 
840   if (cert != NULL) {
841     time_t now;
842     const ASN1_TIME *cert_end_ts;
843     EVP_PKEY *pkey;
844 
845     now = time(NULL);
846     cert_end_ts = X509_get_notAfter(cert);
847     pkey = X509_get_pubkey(cert);
848 
849     if (pkey != NULL) {
850       int pkey_type;
851 
852       pkey_type = get_pkey_type(pkey);
853       EVP_PKEY_free(pkey);
854 
855       if (pkey_type != expected_pkey_type) {
856         pr_log_pri(PR_LOG_NOTICE, MOD_TLS_VERSION
857           ": certificate '%s': expected %s certificate, found %s", path,
858           get_pkey_typestr(expected_pkey_type), get_pkey_typestr(pkey_type));
859       }
860     }
861 
862     if (X509_cmp_time(cert_end_ts, &now) < 0) {
863       BIO *bio;
864       char *data = NULL;
865       long datalen = 0;
866 
867       bio = BIO_new(BIO_s_mem());
868       ASN1_TIME_print(bio, cert_end_ts);
869       datalen = BIO_get_mem_data(bio, &data);
870       if (data != NULL) {
871         data[datalen] = '\0';
872         *errstr = (const char *) pstrcat(p, "expired on ", data, NULL);
873 
874       } else {
875         *errstr = "already expired";
876       }
877 
878       BIO_free(bio);
879 
880       pr_log_pri(PR_LOG_NOTICE, MOD_TLS_VERSION
881         ": certificate '%s': %s",  path, *errstr);
882     }
883   }
884 
885   X509_free(cert);
886   return fingerprint;
887 }
888 
889 #if defined(PR_USE_OPENSSL_OCSP)
ocsp_get_responder_url(pool * p,X509 * cert)890 static const char *ocsp_get_responder_url(pool *p, X509 *cert) {
891   STACK_OF(OPENSSL_STRING) *strs;
892   char *ocsp_url = NULL;
893 
894   strs = X509_get1_ocsp(cert);
895   if (strs != NULL) {
896 # if OPENSSL_VERSION_NUMBER >= 0x10000001L
897     if (sk_OPENSSL_STRING_num(strs) > 0) {
898       ocsp_url = pstrdup(p, sk_OPENSSL_STRING_value(strs, 0));
899     }
900 # endif /* OpenSSL-1.0.0 and later */
901 
902     /* Yes, this says "email", but it Does The Right Thing(tm) for our needs. */
903     X509_email_free(strs);
904   }
905 
906   return ocsp_url;
907 }
908 #endif /* PR_USE_OPENSSL_OCSP */
909 
tls_reset_state(void)910 static void tls_reset_state(void) {
911   tls_engine = FALSE;
912   tls_flags = 0UL;
913   tls_opts = 0UL;
914 
915   if (tls_logfd >= 0) {
916     (void) close(tls_logfd);
917     tls_logfd = -1;
918   }
919 
920   tls_cipher_suite = NULL;
921   tls_crl_file = NULL;
922   tls_crl_path = NULL;
923   tls_crypto_device = NULL;
924   tls_dsa_cert_file = NULL;
925   tls_dsa_key_file = NULL;
926   tls_ec_cert_file = NULL;
927   tls_ec_key_file = NULL;
928   tls_pkcs12_file = NULL;
929   tls_rsa_cert_file = NULL;
930   tls_rsa_key_file = NULL;
931   tls_rand_file = NULL;
932 #if defined(PSK_MAX_PSK_LEN)
933   tls_psks = NULL;
934 #endif /* PSK_MAX_PSK_LEN */
935 
936 #if defined(PR_USE_OPENSSL_OCSP)
937   tls_stapling = FALSE;
938   tls_stapling_opts = 0UL;
939   tls_stapling_responder = NULL;
940   tls_stapling_timeout = TLS_DEFAULT_STAPLING_TIMEOUT;
941 #endif /* PR_USE_OPENSSL_OCSP */
942 
943   tls_handshake_timeout = TLS_DEFAULT_HANDSHAKE_TIMEOUT;
944   tls_handshake_timed_out = FALSE;
945   tls_handshake_timer_id = -1;
946 
947   tls_verify_depth = TLS_DEFAULT_VERIFY_DEPTH;
948 
949   /* Note that we do NOT want to set the netio and nstrm pointers, ctrl
950    * channel, to here.  Why not?  We reset this state when a HOST command
951    * occurs -- but that does NOT cause the NetIO open() to be called again.
952    * And only the NetIO open callback sets our netio/nstrm pointers; so we
953    * leave those as they are (Bug#4370).
954    */
955 
956   tls_data_netio = NULL;
957   tls_data_rd_nstrm = NULL;
958   tls_data_wr_nstrm = NULL;
959 
960   tls_crl_store = NULL;
961   tls_tmp_dhs = NULL;
962   tls_tmp_rsa = NULL;
963 
964   tls_ctrl_need_init_handshake = TRUE;
965   tls_data_need_init_handshake = TRUE;
966 
967   tls_required_on_auth = 0;
968   tls_required_on_ctrl = 0;
969   tls_required_on_data = 0;
970 }
971 
tls_info_cb(const SSL * ssl,int where,int ret)972 static void tls_info_cb(const SSL *ssl, int where, int ret) {
973   const char *str = "(unknown)";
974   int w;
975 
976   pr_signals_handle();
977 
978   w = where & ~SSL_ST_MASK;
979 
980   if (w & SSL_ST_CONNECT) {
981     str = "connecting";
982 
983   } else if (w & SSL_ST_ACCEPT) {
984     str = "accepting";
985 
986   } else {
987     int ssl_state;
988 
989     ssl_state = SSL_get_state(ssl);
990     switch (ssl_state) {
991 #ifdef SSL_ST_BEFORE
992       case SSL_ST_BEFORE:
993         str = "before";
994         break;
995 #endif
996 
997 #if OPENSSL_VERSION_NUMBER >= 0x10100000L && \
998     !defined(HAVE_LIBRESSL)
999       case TLS_ST_OK:
1000 #else
1001       case SSL_ST_OK:
1002 #endif /* OpenSSL-1.1.x and later */
1003         str = "ok";
1004         break;
1005 
1006 #ifdef SSL_ST_RENEGOTIATE
1007       case SSL_ST_RENEGOTIATE:
1008         str = "renegotiating";
1009         break;
1010 #endif
1011 
1012       default:
1013         break;
1014     }
1015   }
1016 
1017   if (where & SSL_CB_ACCEPT_LOOP) {
1018     int ssl_state;
1019 
1020     ssl_state = SSL_get_state(ssl);
1021 
1022 #if OPENSSL_VERSION_NUMBER >= 0x10100000L && \
1023     !defined(HAVE_LIBRESSL)
1024     if (ssl_state == TLS_ST_SR_CLNT_HELLO) {
1025 #else
1026     if (ssl_state == SSL3_ST_SR_CLNT_HELLO_A ||
1027         ssl_state == SSL23_ST_SR_CLNT_HELLO_A) {
1028 #endif /* OpenSSL-1.1.x and later */
1029 
1030       if (tls_opts & TLS_OPT_ENABLE_DIAGS) {
1031         tls_log("[info] %s: %s", str, SSL_state_string_long(ssl));
1032       }
1033 
1034       /* If we have already completed our initial handshake, then this might
1035        * a session renegotiation.
1036        */
1037       if ((ssl == ctrl_ssl && !tls_ctrl_need_init_handshake) ||
1038           (ssl != ctrl_ssl && !tls_data_need_init_handshake)) {
1039 
1040         /* Yes, this is indeed a session renegotiation. If it's a
1041          * renegotiation that we requested, allow it.  If it is from a
1042          * data connection, allow it.  Otherwise, it's a client-initiated
1043          * renegotiation, and we probably don't want to allow it.
1044          */
1045 
1046         if (ssl == ctrl_ssl &&
1047             !(tls_flags & TLS_SESS_CTRL_RENEGOTIATING) &&
1048             !(tls_flags & TLS_SESS_DATA_RENEGOTIATING)) {
1049 
1050           if (!(tls_opts & TLS_OPT_ALLOW_CLIENT_RENEGOTIATIONS)) {
1051             tls_log("warning: client-initiated session renegotiation "
1052               "detected, aborting connection");
1053             pr_log_pri(PR_LOG_NOTICE, MOD_TLS_VERSION
1054               ": client-initiated session renegotiation detected, "
1055               "aborting connection");
1056 
1057             tls_end_sess(ctrl_ssl, session.c, 0);
1058             pr_table_remove(tls_ctrl_rd_nstrm->notes, TLS_NETIO_NOTE, NULL);
1059             pr_table_remove(tls_ctrl_wr_nstrm->notes, TLS_NETIO_NOTE, NULL);
1060             ctrl_ssl = NULL;
1061 
1062             pr_session_disconnect(&tls_module, PR_SESS_DISCONNECT_CONFIG_ACL,
1063               "TLSOption AllowClientRenegotiations");
1064           }
1065         }
1066       }
1067 
1068 #if OPENSSL_VERSION_NUMBER >= 0x009080cfL && \
1069     OPENSSL_VERSION_NUMBER < 0x10100000L
1070     } else if (ssl_state & SSL_ST_RENEGOTIATE) {
1071       if (tls_opts & TLS_OPT_ENABLE_DIAGS) {
1072         tls_log("[info] %s: %s", str, SSL_state_string_long(ssl));
1073       }
1074 
1075       if ((ssl == ctrl_ssl && !tls_ctrl_need_init_handshake) ||
1076           (ssl != ctrl_ssl && !tls_data_need_init_handshake)) {
1077 
1078         if (ssl == ctrl_ssl &&
1079             !(tls_flags & TLS_SESS_CTRL_RENEGOTIATING) &&
1080             !(tls_flags & TLS_SESS_DATA_RENEGOTIATING)) {
1081 
1082           /* In OpenSSL-0.9.8l and later, SSL session renegotiations are
1083            * automatically disabled.  Thus if the admin has not explicitly
1084            * configured support for client-initiated renegotiations via the
1085            * AllowClientRenegotiations TLSOption, then we need to disconnect
1086            * the client here.  Otherwise, the client would hang (up to the
1087            * TLSTimeoutHandshake limit).  Since we know, right now, that the
1088            * handshake won't succeed, just drop the connection.
1089            */
1090 
1091           if (!(tls_opts & TLS_OPT_ALLOW_CLIENT_RENEGOTIATIONS)) {
1092             tls_log("warning: client-initiated session renegotiation detected, "
1093               "aborting connection");
1094             pr_log_pri(PR_LOG_NOTICE, MOD_TLS_VERSION
1095               ": client-initiated session renegotiation detected, "
1096               "aborting connection");
1097 
1098             tls_end_sess(ctrl_ssl, session.c, 0);
1099             pr_table_remove(tls_ctrl_rd_nstrm->notes, TLS_NETIO_NOTE, NULL);
1100             pr_table_remove(tls_ctrl_wr_nstrm->notes, TLS_NETIO_NOTE, NULL);
1101             ctrl_ssl = NULL;
1102 
1103             pr_session_disconnect(&tls_module, PR_SESS_DISCONNECT_CONFIG_ACL,
1104               "TLSOption AllowClientRenegotiations");
1105           }
1106         }
1107       }
1108 #endif
1109     }
1110 
1111   } else if (where & SSL_CB_HANDSHAKE_START) {
1112     if (tls_opts & TLS_OPT_ENABLE_DIAGS) {
1113       tls_log("[info] %s: %s (HANDSHAKE_START)", str,
1114         SSL_state_string_long(ssl));
1115     }
1116 
1117   } else if (where & SSL_CB_HANDSHAKE_DONE) {
1118     if (tls_opts & TLS_OPT_ENABLE_DIAGS) {
1119       tls_log("[info] %s: %s (HANDSHAKE_DONE)", str,
1120         SSL_state_string_long(ssl));
1121     }
1122 
1123     /* ctrl_ssl is NULL if this is our initial ctrl SSL, and the handshake has
1124      * not be completed yet.
1125      */
1126     if (ctrl_ssl == NULL) {
1127       if (tls_ctrl_need_init_handshake == FALSE) {
1128         int reused;
1129 
1130         /* If this is an accepted renegotiation, log the possibly-changed
1131          * ciphersuite et al.
1132          */
1133 
1134         reused = SSL_session_reused((SSL *) ssl);
1135         tls_log("%s renegotiation accepted, using cipher %s (%d bits%s)",
1136           SSL_get_version(ssl), SSL_get_cipher_name(ssl),
1137           SSL_get_cipher_bits(ssl, NULL),
1138           reused > 0 ? ", resumed session" : "");
1139       }
1140 
1141       tls_ctrl_need_init_handshake = FALSE;
1142 
1143     } else {
1144       if (tls_data_need_init_handshake == FALSE) {
1145         /* If this is an accepted renegotiation, log the possibly-changed
1146          * ciphersuite et al.
1147          */
1148         tls_log("%s renegotiation accepted, using cipher %s (%d bits)",
1149           SSL_get_version(ssl), SSL_get_cipher_name(ssl),
1150           SSL_get_cipher_bits(ssl, NULL));
1151       }
1152 
1153       tls_data_need_init_handshake = FALSE;
1154     }
1155 
1156     /* Clear the flags set for server-requested renegotiations. */
1157     if (tls_flags & TLS_SESS_CTRL_RENEGOTIATING) {
1158       tls_flags &= ~TLS_SESS_CTRL_RENEGOTIATING;
1159     }
1160 
1161     if (tls_flags & ~TLS_SESS_DATA_RENEGOTIATING) {
1162       tls_flags &= ~TLS_SESS_DATA_RENEGOTIATING;
1163     }
1164 
1165   } else if (where & SSL_CB_LOOP) {
1166     if (tls_opts & TLS_OPT_ENABLE_DIAGS) {
1167       tls_log("[info] %s: %s", str, SSL_state_string_long(ssl));
1168     }
1169 
1170   } else if (where & SSL_CB_ALERT) {
1171     if (tls_opts & TLS_OPT_ENABLE_DIAGS) {
1172       str = (where & SSL_CB_READ) ? "reading" : "writing";
1173       tls_log("[info] %s: SSL/TLS alert %s: %s", str,
1174         SSL_alert_type_string_long(ret), SSL_alert_desc_string_long(ret));
1175     }
1176 
1177   } else if (where & SSL_CB_EXIT) {
1178     if (tls_opts & TLS_OPT_ENABLE_DIAGS) {
1179       if (ret == 0) {
1180         tls_log("[info] %s: failed in %s: %s", str,
1181           SSL_state_string_long(ssl), tls_get_errors());
1182 
1183       } else if (ret < 0 &&
1184                  errno != 0 &&
1185                  errno != EAGAIN) {
1186         /* Ignore EAGAIN errors */
1187         tls_log("[info] %s: error in %s (errno %d: %s)",
1188           str, SSL_state_string_long(ssl), errno, strerror(errno));
1189       }
1190     }
1191   }
1192 }
1193 
1194 #if OPENSSL_VERSION_NUMBER > 0x000907000L
1195 /* Tables needed for describing bits of the ClientHello. */
1196 
1197 struct tls_label {
1198   int labelno;
1199   const char *label_name;
1200 };
1201 
1202 /* SSL record types */
1203 static struct tls_label tls_record_type_labels[] = {
1204   { 20, "ChangeCipherSpec" },
1205   { 21, "Alert" },
1206   { 22, "Handshake" },
1207   { 23, "ApplicationData" },
1208   { 0, NULL }
1209 };
1210 
1211 /* SSL versions */
1212 static struct tls_label tls_version_labels[] = {
1213   { 0x0002, "SSL 2.0" },
1214   { 0x0300, "SSL 3.0" },
1215   { 0x0301, "TLS 1.0" },
1216   { 0x0302, "TLS 1.1" },
1217   { 0x0303, "TLS 1.2" },
1218   { 0x0304, "TLS 1.3" },
1219 
1220   { 0, NULL }
1221 };
1222 
1223 /* Cipher suites.  These values come from:
1224  *   http://www.iana.org/assignments/tls-parameters/tls-parameters.xhtml#tls-parameters-4
1225  */
1226 static struct tls_label tls_ciphersuite_labels[] = {
1227   { 0x0000, "SSL_NULL_WITH_NULL_NULL" },
1228   { 0x0001, "SSL_RSA_WITH_NULL_MD5" },
1229   { 0x0002, "SSL_RSA_WITH_NULL_SHA" },
1230   { 0x0003, "SSL_RSA_EXPORT_WITH_RC4_40_MD5" },
1231   { 0x0004, "SSL_RSA_WITH_RC4_128_MD5" },
1232   { 0x0005, "SSL_RSA_WITH_RC4_128_SHA" },
1233   { 0x0006, "SSL_RSA_EXPORT_WITH_RC2_CBC_40_MD5" },
1234   { 0x0007, "SSL_RSA_WITH_IDEA_CBC_SHA" },
1235   { 0x0008, "SSL_RSA_EXPORT_WITH_DES40_CBC_SHA" },
1236   { 0x0009, "SSL_RSA_WITH_DES_CBC_SHA" },
1237   { 0x000A, "SSL_RSA_WITH_3DES_EDE_CBC_SHA" },
1238   { 0x000B, "SSL_DH_DSS_EXPORT_WITH_DES40_CBC_SHA" },
1239   { 0x000C, "SSL_DH_DSS_WITH_DES_CBC_SHA" },
1240   { 0x000D, "SSL_DH_DSS_WITH_3DES_EDE_CBC_SHA" },
1241   { 0x000E, "SSL_DH_RSA_EXPORT_WITH_DES40_CBC_SHA" },
1242   { 0x000F, "SSL_DH_RSA_WITH_DES_CBC_SHA" },
1243   { 0x0010, "SSL_DH_RSA_WITH_3DES_EDE_CBC_SHA" },
1244   { 0x0011, "SSL_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA" },
1245   { 0x0012, "SSL_DHE_DSS_WITH_DES_CBC_SHA" },
1246   { 0x0013, "SSL_DHE_DSS_WITH_3DES_EDE_CBC_SHA" },
1247   { 0x0014, "SSL_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA" },
1248   { 0x0015, "SSL_DHE_RSA_WITH_DES_CBC_SHA" },
1249   { 0x0016, "SSL_DHE_RSA_WITH_3DES_EDE_CBC_SHA" },
1250   { 0x0017, "SSL_DH_anon_EXPORT_WITH_RC4_40_MD5" },
1251   { 0x0018, "SSL_DH_anon_WITH_RC4_128_MD5" },
1252   { 0x0019, "SSL_DH_anon_EXPORT_WITH_DES40_CBC_SHA" },
1253   { 0x001A, "SSL_DH_anon_WITH_DES_CBC_SHA" },
1254   { 0x001B, "SSL_DH_anon_WITH_3DES_EDE_CBC_SHA" },
1255   { 0x001D, "SSL_FORTEZZA_KEA_WITH_FORTEZZA_CBC_SHA" },
1256   { 0x001E, "SSL_FORTEZZA_KEA_WITH_RC4_128_SHA" },
1257   { 0x001F, "TLS_KRB5_WITH_3DES_EDE_CBC_SHA" },
1258   { 0x0020, "TLS_KRB5_WITH_RC4_128_SHA" },
1259   { 0x0021, "TLS_KRB5_WITH_IDEA_CBC_SHA" },
1260   { 0x0022, "TLS_KRB5_WITH_DES_CBC_MD5" },
1261   { 0x0023, "TLS_KRB5_WITH_3DES_EDE_CBC_MD5" },
1262   { 0x0024, "TLS_KRB5_WITH_RC4_128_MD5" },
1263   { 0x0025, "TLS_KRB5_WITH_IDEA_CBC_MD5" },
1264   { 0x0026, "TLS_KRB5_EXPORT_WITH_DES_CBC_40_SHA" },
1265   { 0x0027, "TLS_KRB5_EXPORT_WITH_RC2_CBC_40_SHA" },
1266   { 0x0028, "TLS_KRB5_EXPORT_WITH_RC4_40_SHA" },
1267   { 0x0029, "TLS_KRB5_EXPORT_WITH_DES_CBC_40_MD5" },
1268   { 0x002A, "TLS_KRB5_EXPORT_WITH_RC2_CBC_40_MD5" },
1269   { 0x002B, "TLS_KRB5_EXPORT_WITH_RC4_40_MD5" },
1270   { 0x002F, "TLS_RSA_WITH_AES_128_CBC_SHA" },
1271   { 0x0030, "TLS_DH_DSS_WITH_AES_128_CBC_SHA" },
1272   { 0x0031, "TLS_DH_RSA_WITH_AES_128_CBC_SHA" },
1273   { 0x0032, "TLS_DHE_DSS_WITH_AES_128_CBC_SHA" },
1274   { 0x0033, "TLS_DHE_RSA_WITH_AES_128_CBC_SHA" },
1275   { 0x0034, "TLS_DH_anon_WITH_AES_128_CBC_SHA" },
1276   { 0x0035, "TLS_RSA_WITH_AES_256_CBC_SHA" },
1277   { 0x0036, "TLS_DH_DSS_WITH_AES_256_CBC_SHA" },
1278   { 0x0037, "TLS_DH_RSA_WITH_AES_256_CBC_SHA" },
1279   { 0x0038, "TLS_DHE_DSS_WITH_AES_256_CBC_SHA" },
1280   { 0x0039, "TLS_DHE_RSA_WITH_AES_256_CBC_SHA" },
1281   { 0x003A, "TLS_DH_anon_WITH_AES_256_CBC_SHA" },
1282   { 0x003B, "TLS_RSA_WITH_NULL_SHA256" },
1283   { 0x003C, "TLS_RSA_WITH_AES_128_CBC_SHA256" },
1284   { 0x003D, "TLS_RSA_WITH_AES_256_CBC_SHA256" },
1285   { 0x003E, "TLS_DH_DSS_WITH_AES_128_CBC_SHA256" },
1286   { 0x003F, "TLS_DH_RSA_WITH_AES_128_CBC_SHA256" },
1287   { 0x0040, "TLS_DHE_DSS_WITH_AES_128_CBC_SHA256" },
1288   { 0x0041, "TLS_RSA_WITH_CAMELLIA_128_CBC_SHA" },
1289   { 0x0042, "TLS_DH_DSS_WITH_CAMELLIA_128_CBC_SHA" },
1290   { 0x0043, "TLS_DH_RSA_WITH_CAMELLIA_128_CBC_SHA" },
1291   { 0x0044, "TLS_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA" },
1292   { 0x0045, "TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA" },
1293   { 0x0046, "TLS_DH_anon_WITH_CAMELLIA_128_CBC_SHA" },
1294   { 0x0067, "TLS_DHE_RSA_WITH_AES_128_CBC_SHA256" },
1295   { 0x0068, "TLS_DH_DSS_WITH_AES_256_CBC_SHA256" },
1296   { 0x0069, "TLS_DH_RSA_WITH_AES_256_CBC_SHA256" },
1297   { 0x006A, "TLS_DHE_DSS_WITH_AES_256_CBC_SHA256" },
1298   { 0x006B, "TLS_DHE_RSA_WITH_AES_256_CBC_SHA256" },
1299   { 0x006C, "TLS_DH_anon_WITH_AES_128_CBC_SHA256" },
1300   { 0x006D, "TLS_DH_anon_WITH_AES_256_CBC_SHA256" },
1301   { 0x0084, "TLS_RSA_WITH_CAMELLIA_256_CBC_SHA" },
1302   { 0x0085, "TLS_DH_DSS_WITH_CAMELLIA_256_CBC_SHA" },
1303   { 0x0086, "TLS_DH_RSA_WITH_CAMELLIA_256_CBC_SHA" },
1304   { 0x0087, "TLS_DHE_DSS_WITH_CAMELLIA_256_CBC_SHA" },
1305   { 0x0088, "TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA" },
1306   { 0x0089, "TLS_DH_anon_WITH_CAMELLIA_256_CBC_SHA" },
1307   { 0x008A, "TLS_PSK_WITH_RC4_128_SHA" },
1308   { 0x008B, "TLS_PSK_WITH_3DES_EDE_CBC_SHA" },
1309   { 0x008C, "TLS_PSK_WITH_AES_128_CBC_SHA" },
1310   { 0x008D, "TLS_PSK_WITH_AES_256_CBC_SHA" },
1311   { 0x008E, "TLS_DHE_PSK_WITH_RC4_128_SHA" },
1312   { 0x008F, "TLS_DHE_PSK_WITH_3DES_EDE_CBC_SHA" },
1313   { 0x0090, "TLS_DHE_PSK_WITH_AES_128_CBC_SHA" },
1314   { 0x0091, "TLS_DHE_PSK_WITH_AES_256_CBC_SHA" },
1315   { 0x0092, "TLS_RSA_PSK_WITH_RC4_128_SHA" },
1316   { 0x0093, "TLS_RSA_PSK_WITH_3DES_EDE_CBC_SHA" },
1317   { 0x0094, "TLS_RSA_PSK_WITH_AES_128_CBC_SHA" },
1318   { 0x0095, "TLS_RSA_PSK_WITH_AES_256_CBC_SHA" },
1319   { 0x0096, "TLS_RSA_WITH_SEED_CBC_SHA" },
1320   { 0x0097, "TLS_DH_DSS_WITH_SEED_CBC_SHA" },
1321   { 0x0098, "TLS_DH_RSA_WITH_SEED_CBC_SHA" },
1322   { 0x0099, "TLS_DHE_DSS_WITH_SEED_CBC_SHA" },
1323   { 0x009A, "TLS_DHE_RSA_WITH_SEED_CBC_SHA" },
1324   { 0x009B, "TLS_DH_anon_WITH_SEED_CBC_SHA" },
1325   { 0x009C, "TLS_RSA_WITH_AES_128_GCM_SHA256" },
1326   { 0x009D, "TLS_RSA_WITH_AES_256_GCM_SHA384" },
1327   { 0x009E, "TLS_DHE_RSA_WITH_AES_128_GCM_SHA256" },
1328   { 0x009F, "TLS_DHE_RSA_WITH_AES_256_GCM_SHA384" },
1329   { 0x00A0, "TLS_DH_RSA_WITH_AES_128_GCM_SHA256" },
1330   { 0x00A1, "TLS_DH_RSA_WITH_AES_256_GCM_SHA384" },
1331   { 0x00A2, "TLS_DHE_DSS_WITH_AES_128_GCM_SHA256" },
1332   { 0x00A3, "TLS_DHE_DSS_WITH_AES_256_GCM_SHA384" },
1333   { 0x00A4, "TLS_DH_DSS_WITH_AES_128_GCM_SHA256" },
1334   { 0x00A5, "TLS_DH_DSS_WITH_AES_256_GCM_SHA384" },
1335   { 0x00A6, "TLS_DH_anon_WITH_AES_128_GCM_SHA256" },
1336   { 0x00A7, "TLS_DH_anon_WITH_AES_256_GCM_SHA384" },
1337   { 0x00A8, "TLS_PSK_WITH_AES_128_GCM_SHA256" },
1338   { 0x00A9, "TLS_PSK_WITH_AES_256_GCM_SHA384" },
1339   { 0x00AA, "TLS_DHE_PSK_WITH_AES_128_GCM_SHA256" },
1340   { 0x00AB, "TLS_DHE_PSK_WITH_AES_256_GCM_SHA384" },
1341   { 0x00AC, "TLS_RSA_PSK_WITH_AES_128_GCM_SHA256" },
1342   { 0x00AD, "TLS_RSA_PSK_WITH_AES_256_GCM_SHA384" },
1343   { 0x00AE, "TLS_PSK_WITH_AES_128_CBC_SHA256" },
1344   { 0x00AF, "TLS_PSK_WITH_AES_256_CBC_SHA384" },
1345   { 0x00B0, "TLS_PSK_WITH_NULL_SHA256" },
1346   { 0x00B1, "TLS_PSK_WITH_NULL_SHA384" },
1347   { 0x00B2, "TLS_DHE_PSK_WITH_AES_128_CBC_SHA256" },
1348   { 0x00B3, "TLS_DHE_PSK_WITH_AES_256_CBC_SHA384"},
1349   { 0x00B4, "TLS_DHE_PSK_WITH_NULL_SHA256" },
1350   { 0x00B5, "TLS_DHE_PSK_WITH_NULL_SHA384" },
1351   { 0x00B6, "TLS_RSA_PSK_WITH_AES_128_CBC_SHA256" },
1352   { 0x00B7, "TLS_RSA_PSK_WITH_AES_256_CBC_SHA384" },
1353   { 0x00B8, "TLS_RSA_PSK_WITH_NULL_SHA256" },
1354   { 0x00B9, "TLS_RSA_PSK_WITH_NULL_SHA384" },
1355   { 0x00BA, "TLS_RSA_WITH_CAMELLIA_128_CBC_SHA256" },
1356   { 0x00BB, "TLS_DH_DSS_WITH_CAMELLIA_128_CBC_SHA256" },
1357   { 0x00BC, "TLS_DH_RSA_WITH_CAMELLIA_128_CBC_SHA256" },
1358   { 0x00BD, "TLS_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA256" },
1359   { 0x00BE, "TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA256" },
1360   { 0x00BF, "TLS_DH_anon_WITH_CAMELLIA_128_CBC_SHA256" },
1361   { 0x00C0, "TLS_RSA_WITH_CAMELLIA_256_CBC_SHA256" },
1362   { 0x00C1, "TLS_DH_DSS_WITH_CAMELLIA_256_CBC_SHA256" },
1363   { 0x00C2, "TLS_DH_RSA_WITH_CAMELLIA_256_CBC_SHA256" },
1364   { 0x00C3, "TLS_DHE_DSS_WITH_CAMELLIA_256_CBC_SHA256" },
1365   { 0x00C4, "TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA256" },
1366   { 0x00C5, "TLS_DH_anon_WITH_CAMELLIA_256_CBC_SHA256" },
1367   { 0x00FF, "TLS_EMPTY_RENEGOTIATION_INFO_SCSV" },
1368   { 0x1301, "TLS_AES_128_GCM_SHA256" },
1369   { 0x1302, "TLS_AES_256_GCM_SHA384" },
1370   { 0x1303, "TLS_CHACHA20_POLY1305_SHA256" },
1371   { 0xC001, "TLS_ECDH_ECDSA_WITH_NULL_SHA" },
1372   { 0xC002, "TLS_ECDH_ECDSA_WITH_RC4_128_SHA" },
1373   { 0xC003, "TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA" },
1374   { 0xC004, "TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA" },
1375   { 0xC005, "TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA" },
1376   { 0xC006, "TLS_ECDHE_ECDSA_WITH_NULL_SHA" },
1377   { 0xC007, "TLS_ECDHE_ECDSA_WITH_RC4_128_SHA" },
1378   { 0xC008, "TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA" },
1379   { 0xC009, "TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA" },
1380   { 0xC00A, "TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA" },
1381   { 0xC00B, "TLS_ECDH_RSA_WITH_NULL_SHA" },
1382   { 0xC00C, "TLS_ECDH_RSA_WITH_RC4_128_SHA" },
1383   { 0xC00D, "TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA" },
1384   { 0xC00E, "TLS_ECDH_RSA_WITH_AES_128_CBC_SHA" },
1385   { 0xC00F, "TLS_ECDH_RSA_WITH_AES_256_CBC_SHA" },
1386   { 0xC010, "TLS_ECDHE_RSA_WITH_NULL_SHA" },
1387   { 0xC011, "TLS_ECDHE_RSA_WITH_RC4_128_SHA" },
1388   { 0xC012, "TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA" },
1389   { 0xC013, "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA" },
1390   { 0xC014, "TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA" },
1391   { 0xC015, "TLS_ECDH_anon_WITH_NULL_SHA" },
1392   { 0xC016, "TLS_ECDH_anon_WITH_RC4_128_SHA" },
1393   { 0xC017, "TLS_ECDH_anon_WITH_3DES_EDE_CBC_SHA" },
1394   { 0xC018, "TLS_ECDH_anon_WITH_AES_128_CBC_SHA" },
1395   { 0xC019, "TLS_ECDH_anon_WITH_AES_256_CBC_SHA" },
1396   { 0xC01A, "TLS_SRP_SHA_WITH_3DES_EDE_CBC_SHA" },
1397   { 0xC01B, "TLS_SRP_SHA_RSA_WITH_3DES_EDE_CBC_SHA" },
1398   { 0xC01C, "TLS_SRP_SHA_DSS_WITH_3DES_EDE_CBC_SHA" },
1399   { 0xC01D, "TLS_SRP_SHA_WITH_AES_128_CBC_SHA" },
1400   { 0xC01E, "TLS_SRP_SHA_RSA_WITH_AES_128_CBC_SHA" },
1401   { 0xC01F, "TLS_SRP_SHA_DSS_WITH_AES_128_CBC_SHA" },
1402   { 0xC020, "TLS_SRP_SHA_WITH_AES_256_CBC_SHA" },
1403   { 0xC021, "TLS_SRP_SHA_RSA_WITH_AES_256_CBC_SHA" },
1404   { 0xC022, "TLS_SRP_SHA_DSS_WITH_AES_256_CBC_SHA" },
1405   { 0xC023, "TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256" },
1406   { 0xC024, "TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384" },
1407   { 0xC025, "TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256" },
1408   { 0xC026, "TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384" },
1409   { 0xC027, "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256" },
1410   { 0xC028, "TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384" },
1411   { 0xC029, "TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256" },
1412   { 0xC02A, "TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384" },
1413   { 0xC02B, "TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256" },
1414   { 0xC02C, "TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384" },
1415   { 0xC02D, "TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256" },
1416   { 0xC02E, "TLS_ECDH_ECDSA_WITH_AES_256_GCM_SHA384" },
1417   { 0xC02F, "TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256" },
1418   { 0xC030, "TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384" },
1419   { 0xC031, "TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256" },
1420   { 0xC032, "TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384" },
1421   { 0xC07A, "TLS_RSA_WITH_CAMELLIA_128_GCM_SHA256" },
1422   { 0xC07B, "TLS_RSA_WITH_CAMELLIA_256_GCM_SHA384" },
1423   { 0xC086, "TLS_ECDHE_ECDSA_WITH_CAMELLIA_128_GCM_SHA256" },
1424   { 0xC087, "TLS_ECDHE_ECDSA_WITH_CAMELLIA_256_GCM_SHA384" },
1425   { 0xC08A, "TLS_ECDHE_RSA_WITH_CAMELLIA_128_GCM_SHA256" },
1426   { 0xC08B, "TLS_ECDHE_RSA_WITH_CAMELLIA_256_GCM_SHA384" },
1427   { 0xC09C, "TLS_RSA_WITH_AES_128_CCM" },
1428   { 0xC09D, "TLS_RSA_WITH_AES_256_CCM" },
1429   { 0xC0AC, "TLS_ECDHE_ECDSA_WITH_AES_128_CCM" },
1430   { 0xC0AD, "TLS_ECDHE_ECDSA_WITH_AES_256_CCM" },
1431   { 0xC0AE, "TLS_DHE_RSA_WITH_AES_128_CCM" },
1432   { 0xC0AF, "TLS_DHE_RSA_WITH_AES_256_CCM" },
1433   { 0xCCA8, "TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256" },
1434   { 0xCCA9, "TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256" },
1435   { 0xCCAA, "TLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256" },
1436   { 0xCCAB, "TLS_PSK_WITH_CHACHA20_POLY1305_SHA256" },
1437   { 0xCCAC, "TLS_ECDHE_PSK_WITH_CHACHA20_POLY1305_SHA256" },
1438   { 0xCCAD, "TLS_DHE_PSK_WITH_CHACHA20_POLY1305_SHA256" },
1439   { 0xCCAE, "TLS_RSA_PSK_WITH_CHACHA20_POLY1305_SHA256" },
1440   { 0xFEFE, "SSL_RSA_FIPS_WITH_DES_CBC_SHA" },
1441   { 0xFEFF, "SSL_RSA_FIPS_WITH_3DES_EDE_CBC_SHA" },
1442 
1443   { 0, NULL }
1444 };
1445 
1446 /* Compressions */
1447 static struct tls_label tls_compression_labels[] = {
1448   { 0x0000, "None" },
1449   { 0x0001, "Zlib" },
1450 
1451   { 0, NULL }
1452 };
1453 
1454 /* Extensions */
1455 static struct tls_label tls_extension_labels[] = {
1456   { 0, "server_name" },
1457   { 1, "max_fragment_length" },
1458   { 2, "client_certificate_url" },
1459   { 3, "trusted_ca_keys" },
1460   { 4, "truncated_hmac" },
1461   { 5, "status_request" },
1462   { 6, "user_mapping" },
1463   { 7, "client_authz" },
1464   { 8, "server_authz" },
1465   { 9, "cert_type" },
1466   { 10, "elliptic_curves" },
1467   { 11, "ec_point_formats" },
1468   { 12, "srp" },
1469   { 13, "signature_algorithms" },
1470   { 14, "use_srtp" },
1471   { 15, "heartbeat" },
1472   { 16, "application_layer_protocol_negotiation" },
1473   { 18, "signed_certificate_timestamp" },
1474   { 21, "padding" },
1475   { 22, "encrypt_then_mac" },
1476   { 23, "extended_master_secret" },
1477   { 35, "session_ticket" },
1478   { 41, "psk" },
1479   { 42, "early_data" },
1480   { 43, "supported_versions" },
1481   { 44, "cookie" },
1482   { 45, "psk_kex_modes" },
1483   { 47, "certificate_authorities" },
1484   { 49, "post_handshake_auth" },
1485   { 50, "signature_algorithms_cert" },
1486   { 51, "key_share" },
1487   { 0xFF01, "renegotiate" },
1488   { 13172, "next_proto_neg" },
1489 
1490   { 0, NULL }
1491 };
1492 
1493 #if defined(TLSEXT_TYPE_signature_algorithms)
1494 /* Signature Algorithms.  These values come from:
1495  *   https://www.iana.org/assignments/tls-parameters/tls-parameters.xhtml#tls-parameters-16
1496  */
1497 static struct tls_label tls_sigalgo_labels[] = {
1498   { 0x0201, "rsa_pkcs1_sha1" },
1499   { 0x0202, "dsa_sha1" },
1500   { 0x0203, "ecdsa_sha1" },
1501   { 0x0301, "rsa_pkcs1_sha224" },
1502   { 0x0302, "dsa_sha224" },
1503   { 0x0303, "ecdsa_sha224" },
1504   { 0x0401, "rsa_pkcs1_sha256" },
1505   { 0x0402, "dsa_sha256" },
1506   { 0x0403, "ecdsa_secp256r1_sha256" },
1507   { 0x0501, "rsa_pkcs1_sha384" },
1508   { 0x0502, "dsa_sha384" },
1509   { 0x0503, "ecdsa_secp384r1_sha384" },
1510   { 0x0601, "rsa_pkcs1_sha512" },
1511   { 0x0602, "dsa_sha512" },
1512   { 0x0603, "ecdsa_secp521r1_sha512" },
1513   { 0x0804, "rsa_pss_rsae_sha256" },
1514   { 0x0805, "rsa_pss_rsae_sha384" },
1515   { 0x0806, "rsa_pss_rsae_sha512" },
1516   { 0x0807, "ed25519" },
1517   { 0x0808, "ed448" },
1518   { 0x0809, "rsa_pss_pss_sha256" },
1519   { 0x080A, "rsa_pss_pss_sha384" },
1520   { 0x080B, "rsa_pss_pss_sha512" },
1521 
1522   { 0, NULL }
1523 };
1524 #endif /* TLSEXT_TYPE_signature_algorithms */
1525 
1526 #if defined(TLSEXT_TYPE_psk_kex_modes)
1527 /* PSK KEX modes.  These values come from:
1528  *   https://tools.ietf.org/html/rfc8446#section-4.2.9
1529  */
1530 static struct tls_label tls_psk_kex_labels[] = {
1531   { 0, "psk_ke" },
1532   { 1, "psk_dhe_key" },
1533 
1534   { 0, NULL }
1535 };
1536 #endif /* TLSEXT_TYPE_psk_kex_modes */
1537 
1538 static const char *tls_get_label(int labelno, struct tls_label *labels) {
1539   register unsigned int i;
1540 
1541   for (i = 0; labels[i].label_name != NULL; i++) {
1542     if (labels[i].labelno == labelno) {
1543       return labels[i].label_name;
1544     }
1545   }
1546 
1547   return "[unknown/unsupported]";
1548 }
1549 
1550 static void tls_print_ssl_version(BIO *bio, const char *name,
1551     const unsigned char **msg, size_t *msglen, int *pversion) {
1552   int version;
1553 
1554   if (*msglen < 2) {
1555     return;
1556   }
1557 
1558   version = ((*msg)[0] << 8) | (*msg)[1];
1559   BIO_printf(bio, "  %s = %s\n", name,
1560     tls_get_label(version, tls_version_labels));
1561   *msg += 2;
1562   *msglen -= 2;
1563 
1564   if (pversion != NULL) {
1565     *pversion = version;
1566   }
1567 }
1568 
1569 static void tls_print_hex(BIO *bio, const char *indent, const char *name,
1570     const unsigned char *msg, size_t msglen) {
1571 
1572   BIO_printf(bio, "%s (%lu %s)\n", name, (unsigned long) msglen,
1573     msglen != 1 ? "bytes" : "byte");
1574 
1575   if (msglen > 0) {
1576     register unsigned int i;
1577 
1578     BIO_puts(bio, indent);
1579     for (i = 0; i < msglen; i++) {
1580       BIO_printf(bio, "%02x", msg[i]);
1581     }
1582     BIO_puts(bio, "\n");
1583   }
1584 }
1585 
1586 static void tls_print_hexbuf(BIO *bio, const char *indent, const char *name,
1587     size_t namelen, const unsigned char **msg, size_t *msglen) {
1588   size_t buflen;
1589   const unsigned char *ptr;
1590 
1591   if (*msglen < namelen) {
1592     return;
1593   }
1594 
1595   ptr = *msg;
1596   buflen = ptr[0];
1597 
1598   if (namelen > 1) {
1599     buflen = (buflen << 8) | ptr[1];
1600   }
1601 
1602   if (*msglen < namelen + buflen) {
1603     return;
1604   }
1605 
1606   ptr += namelen;
1607   tls_print_hex(bio, indent, name, ptr, buflen);
1608   *msg += (buflen + namelen);
1609   *msglen -= (buflen + namelen);
1610 }
1611 
1612 static void tls_print_random(BIO *bio, const unsigned char **msg,
1613     size_t *msglen) {
1614   pool *tmp_pool;
1615   time_t ts;
1616   const unsigned char *ptr;
1617 
1618   if (*msglen < 32) {
1619     return;
1620   }
1621 
1622   ptr = *msg;
1623 
1624   ts = ((ptr[0] << 24) | (ptr[1] << 16) | (ptr[2] << 8) | ptr[3]);
1625   ptr += 4;
1626 
1627   tmp_pool = make_sub_pool(session.pool);
1628   pr_pool_tag(tmp_pool, "TLS Diags pool");
1629 
1630   BIO_puts(bio, "  random:\n");
1631   BIO_printf(bio, "    gmt_unix_time = %s (not guaranteed to be accurate)\n",
1632     pr_strtime3(tmp_pool, ts, TRUE));
1633   tls_print_hex(bio, "      ", "    random_bytes", ptr, 28);
1634   *msg += 32;
1635   *msglen -= 32;
1636   destroy_pool(tmp_pool);
1637 }
1638 
1639 static void tls_print_session_id(BIO *bio, const unsigned char **msg,
1640     size_t *msglen) {
1641   tls_print_hexbuf(bio, "    ", "  session_id", 1, msg, msglen);
1642 }
1643 
1644 static void tls_print_ciphersuites(BIO *bio, const char *name,
1645     const unsigned char **msg, size_t *msglen) {
1646   size_t len;
1647 
1648   len = ((*msg[0]) << 8) | (*msg)[1];
1649   *msg += 2;
1650   *msglen -= 2;
1651   BIO_printf(bio, "  %s (%lu %s)\n", name, (unsigned long) len,
1652     len != 1 ? "bytes" : "byte");
1653   if (*msglen < len ||
1654       (len & 1)) {
1655     return;
1656   }
1657 
1658   while (len > 0) {
1659     unsigned int suiteno;
1660 
1661     pr_signals_handle();
1662 
1663     suiteno = ((*msg[0]) << 8) | (*msg)[1];
1664     BIO_printf(bio, "    %s (0x%x)\n",
1665       tls_get_label(suiteno, tls_ciphersuite_labels), suiteno);
1666 
1667     *msg += 2;
1668     *msglen -= 2;
1669     len -= 2;
1670   }
1671 }
1672 
1673 static void tls_print_compressions(BIO *bio, const char *name,
1674     const unsigned char **msg, size_t *msglen) {
1675   size_t len;
1676 
1677   len = (*msg)[0];
1678   *msg += 1;
1679   *msglen -= 1;
1680 
1681   if (*msglen < len) {
1682     return;
1683   }
1684 
1685   BIO_printf(bio, "  %s (%lu %s)\n", name, (unsigned long) len,
1686     len != 1 ? "bytes" : "byte");
1687   while (len > 0) {
1688     int comp_type;
1689 
1690     pr_signals_handle();
1691 
1692     comp_type = (*msg)[0];
1693     BIO_printf(bio, "    %s\n",
1694       tls_get_label(comp_type, tls_compression_labels));
1695 
1696     *msg += 1;
1697     *msglen -= 1;
1698     len -= 1;
1699   }
1700 }
1701 
1702 static void tls_print_extension(BIO *bio, const char *indent, int server,
1703     int ext_type, const unsigned char *ext, size_t extlen) {
1704 
1705   BIO_printf(bio, "%sextension_type = %s (%lu %s)\n", indent,
1706     tls_get_label(ext_type, tls_extension_labels), (unsigned long) extlen,
1707     extlen != 1 ? "bytes" : "byte");
1708 }
1709 
1710 static void tls_print_extensions(BIO *bio, const char *name, int server,
1711     const unsigned char **msg, size_t *msglen) {
1712   size_t len;
1713 
1714   if (*msglen == 0) {
1715     BIO_printf(bio, "%s: None\n", name);
1716     return;
1717   }
1718 
1719   len = ((*msg)[0] << 8) | (*msg)[1];
1720   if (len != (*msglen - 2)) {
1721     return;
1722   }
1723 
1724   *msg += 2;
1725   *msglen -= 2;
1726 
1727   BIO_printf(bio, "  %s (%lu %s)\n", name, (unsigned long) len,
1728     len != 1 ? "bytes" : "byte");
1729   while (len > 0) {
1730     int ext_type;
1731     size_t ext_len;
1732 
1733     pr_signals_handle();
1734 
1735     if (*msglen < 4) {
1736       break;
1737     }
1738 
1739     ext_type = ((*msg)[0] << 8) | (*msg)[1];
1740     ext_len = ((*msg)[2] << 8) | (*msg)[3];
1741 
1742     if (*msglen < (ext_len + 4)) {
1743       break;
1744     }
1745 
1746     *msg += 4;
1747     tls_print_extension(bio, "    ", server, ext_type, *msg, ext_len);
1748     *msg += ext_len;
1749     *msglen -= (ext_len + 4);
1750   }
1751 }
1752 
1753 static void tls_print_client_hello(int io_flag, int version, int content_type,
1754     const unsigned char *buf, size_t buflen, SSL *ssl, void *arg) {
1755   BIO *bio;
1756   char *data = NULL;
1757   long datalen;
1758 
1759   bio = BIO_new(BIO_s_mem());
1760 
1761   BIO_puts(bio, "\nClientHello:\n");
1762   tls_print_ssl_version(bio, "client_version", &buf, &buflen, NULL);
1763   tls_print_random(bio, &buf, &buflen);
1764   tls_print_session_id(bio, &buf, &buflen);
1765   if (buflen < 2) {
1766     BIO_free(bio);
1767     return;
1768   }
1769   tls_print_ciphersuites(bio, "cipher_suites", &buf, &buflen);
1770   if (buflen < 1) {
1771     BIO_free(bio);
1772     return;
1773   }
1774   tls_print_compressions(bio, "compression_methods", &buf, &buflen);
1775   tls_print_extensions(bio, "extensions", FALSE, &buf, &buflen);
1776 
1777   datalen = BIO_get_mem_data(bio, &data);
1778   if (data != NULL) {
1779     data[datalen] = '\0';
1780     tls_log("[msg] %.*s", (int) datalen, data);
1781   }
1782 
1783   BIO_free(bio);
1784 }
1785 
1786 static void tls_print_server_hello(int io_flag, int version, int content_type,
1787     const unsigned char *buf, size_t buflen, SSL *ssl, void *arg) {
1788   BIO *bio;
1789   char *data = NULL;
1790   long datalen;
1791   int print_session_id = TRUE, print_compressions = TRUE, server_version;
1792   unsigned int suiteno;
1793 
1794   bio = BIO_new(BIO_s_mem());
1795 
1796   BIO_puts(bio, "\nServerHello:\n");
1797   tls_print_ssl_version(bio, "server_version", &buf, &buflen, &server_version);
1798 
1799 #ifdef TLS1_3_VERSION
1800   if (server_version == TLS1_3_VERSION) {
1801     print_session_id = FALSE;
1802     print_compressions = FALSE;
1803   }
1804 #endif /* TLS1_3_VERSION */
1805 
1806   tls_print_random(bio, &buf, &buflen);
1807   if (print_session_id == TRUE) {
1808     tls_print_session_id(bio, &buf, &buflen);
1809   }
1810   if (buflen < 2) {
1811     BIO_free(bio);
1812     return;
1813   }
1814 
1815   /* Print the selected ciphersuite. */
1816   BIO_printf(bio, "  cipher_suites (2 bytes)\n");
1817   suiteno = (buf[0] << 8) | buf[1];
1818   BIO_printf(bio, "    %s (0x%x)\n",
1819     tls_get_label(suiteno, tls_ciphersuite_labels), suiteno);
1820   buf += 2;
1821   buflen -= 2;
1822 
1823   if (print_compressions == TRUE) {
1824     int comp_type;
1825 
1826     if (buflen < 1) {
1827       BIO_free(bio);
1828       return;
1829     }
1830 
1831     /* Print the selected compression. */
1832     BIO_printf(bio, "  compression_methods (1 byte)\n");
1833     comp_type = *buf;
1834     BIO_printf(bio, "    %s\n",
1835       tls_get_label(comp_type, tls_compression_labels));
1836     buf += 1;
1837     buflen -= 1;
1838   }
1839   tls_print_extensions(bio, "extensions", TRUE, &buf, &buflen);
1840 
1841   datalen = BIO_get_mem_data(bio, &data);
1842   if (data != NULL) {
1843     data[datalen] = '\0';
1844     tls_log("[msg] %.*s", (int) datalen, data);
1845   }
1846 
1847   BIO_free(bio);
1848 }
1849 
1850 #ifdef SSL3_MT_NEWSESSION_TICKET
1851 static void tls_print_ticket(int io_flag, int version, int content_type,
1852     const unsigned char *buf, size_t buflen, SSL *ssl, void *arg) {
1853   BIO *bio;
1854   char *data = NULL;
1855   long datalen;
1856 
1857   bio = BIO_new(BIO_s_mem());
1858 
1859   BIO_puts(bio, "\nNewSessionTicket:\n");
1860   if (buflen != 0) {
1861     unsigned int ticket_lifetime;
1862     int print_ticket_age = FALSE, print_extensions = FALSE;
1863 
1864     ticket_lifetime = (buf[0] << 24) | (buf[1] << 16) | (buf[2] << 8) | buf[3];
1865     buf += 4;
1866     buflen -= 4;
1867     BIO_printf(bio, "  ticket_lifetime_hint\n    %u (sec)\n", ticket_lifetime);
1868 
1869 # if defined(TLS1_3_VERSION)
1870     if (SSL_version(ssl) == TLS1_3_VERSION) {
1871       print_ticket_age = TRUE;
1872       print_extensions = TRUE;
1873     }
1874 # endif /* TLS1_3_VERSION */
1875 
1876     if (print_ticket_age == TRUE) {
1877       unsigned int ticket_age_add;
1878 
1879       ticket_age_add = (buf[0] << 24) | (buf[1] << 16) | (buf[2] << 8) | buf[3];
1880       buf += 4;
1881       buflen -= 4;
1882       BIO_printf(bio, "  ticket_age_add\n    %u (sec)\n", ticket_age_add);
1883       tls_print_hexbuf(bio, "    ", "  ticket_nonce", 1, &buf, &buflen);
1884     }
1885 
1886     tls_print_hexbuf(bio, "    ", "  ticket", 2, &buf, &buflen);
1887 
1888     if (print_extensions == TRUE) {
1889       tls_print_extensions(bio, "extensions", TRUE, &buf, &buflen);
1890     }
1891 
1892   } else {
1893     BIO_puts(bio, "  <no ticket>\n");
1894   }
1895 
1896   datalen = BIO_get_mem_data(bio, &data);
1897   if (data != NULL) {
1898     data[datalen] = '\0';
1899     tls_log("[msg] %.*s", (int) datalen, data);
1900   }
1901 
1902   BIO_free(bio);
1903 }
1904 #endif /* SSL3_MT_NEWSESSION_TICKET */
1905 
1906 static void tls_msg_cb(int io_flag, int version, int content_type,
1907     const void *buf, size_t buflen, SSL *ssl, void *arg) {
1908   char *action_str = NULL, *version_str = NULL;
1909   char *bytes_str = buflen != 1 ? "bytes" : "byte";
1910 
1911   if (io_flag == 0) {
1912     action_str = "received";
1913 
1914   } else if (io_flag == 1) {
1915     action_str = "sent";
1916   }
1917 
1918   switch (version) {
1919     case SSL2_VERSION:
1920       version_str = "SSLv2";
1921       break;
1922 
1923     case SSL3_VERSION:
1924       version_str = "SSLv3";
1925       break;
1926 
1927     case TLS1_VERSION:
1928       version_str = "TLSv1";
1929       break;
1930 
1931 # if defined(TLS1_1_VERSION)
1932     case TLS1_1_VERSION:
1933       version_str = "TLSv1.1";
1934       break;
1935 # endif /* TLS1_1_VERSION */
1936 
1937 # if defined(TLS1_2_VERSION)
1938     case TLS1_2_VERSION:
1939       version_str = "TLSv1.2";
1940       break;
1941 # endif /* TLS1_2_VERSION */
1942 
1943 # if OPENSSL_VERSION_NUMBER >= 0x10101000L && \
1944      defined(TLS1_3_VERSION) && !defined(LIBRESSL_VERSION_NUMBER)
1945     case TLS1_3_VERSION:
1946       version_str = "TLSv1.3";
1947       break;
1948 # endif /* TLS1_3_VERSION */
1949 
1950     default:
1951 #ifdef SSL3_RT_HEADER
1952       /* OpenSSL calls this callback for SSL records received; filter those
1953        * from true "unknowns".
1954        */
1955       if (version == 0 &&
1956           (content_type != SSL3_RT_HEADER ||
1957            buflen != SSL3_RT_HEADER_LENGTH)) {
1958         tls_log("[msg] unknown/unsupported version: %d", version);
1959       }
1960 #else
1961       tls_log("[msg] unknown/unsupported version: %d", version);
1962 #endif
1963       break;
1964   }
1965 
1966   if (version == SSL3_VERSION ||
1967 #if OPENSSL_VERSION_NUMBER >= 0x10001000L
1968       version == TLS1_1_VERSION ||
1969       version == TLS1_2_VERSION ||
1970 # if OPENSSL_VERSION_NUMBER >= 0x10101000L && \
1971      defined(TLS1_3_VERSION) && !defined(LIBRESSL_VERSION_NUMBER)
1972       version == TLS1_3_VERSION ||
1973 # endif
1974 #endif
1975       version == TLS1_VERSION) {
1976 
1977     switch (content_type) {
1978       case SSL3_RT_CHANGE_CIPHER_SPEC:
1979         /* ChangeCipherSpec message */
1980         pr_trace_msg(trace_channel, 27,
1981           "%s %s ChangeCipherSpec (%u %s)", action_str, version_str,
1982           (unsigned int) buflen, bytes_str);
1983         tls_log("[msg] %s %s ChangeCipherSpec message (%u %s)",
1984           action_str, version_str, (unsigned int) buflen, bytes_str);
1985         break;
1986 
1987       case SSL3_RT_ALERT: {
1988         /* Alert messages */
1989         pr_trace_msg(trace_channel, 27,
1990           "%s %s Alert (%u %s)", action_str, version_str,
1991           (unsigned int) buflen, bytes_str);
1992         if (buflen == 2) {
1993           char *severity_str = NULL;
1994 
1995           /* Peek naughtily into the buffer. */
1996           switch (((const unsigned char *) buf)[0]) {
1997             case SSL3_AL_WARNING:
1998               severity_str = "warning";
1999               break;
2000 
2001             case SSL3_AL_FATAL:
2002               severity_str = "fatal";
2003               break;
2004           }
2005 
2006           switch (((const unsigned char *) buf)[1]) {
2007             case SSL3_AD_CLOSE_NOTIFY:
2008               tls_log("[msg] %s %s %s 'close_notify' Alert message (%u %s)",
2009                 action_str, version_str, severity_str, (unsigned int) buflen,
2010                 bytes_str);
2011               break;
2012 
2013             case SSL3_AD_UNEXPECTED_MESSAGE:
2014               tls_log("[msg] %s %s %s 'unexpected_message' Alert message "
2015                 "(%u %s)", action_str, version_str, severity_str,
2016                 (unsigned int) buflen, bytes_str);
2017               break;
2018 
2019             case SSL3_AD_BAD_RECORD_MAC:
2020               tls_log("[msg] %s %s %s 'bad_record_mac' Alert message (%u %s)",
2021                 action_str, version_str, severity_str, (unsigned int) buflen,
2022                 bytes_str);
2023               break;
2024 
2025             case 21:
2026               tls_log("[msg] %s %s %s 'decryption_failed' Alert message "
2027                 "(%u %s)", action_str, version_str, severity_str,
2028                 (unsigned int) buflen, bytes_str);
2029               break;
2030 
2031             case 22:
2032               tls_log("[msg] %s %s %s 'record_overflow' Alert message (%u %s)",
2033                 action_str, version_str, severity_str, (unsigned int) buflen,
2034                 bytes_str);
2035               break;
2036 
2037             case SSL3_AD_DECOMPRESSION_FAILURE:
2038               tls_log("[msg] %s %s %s 'decompression_failure' Alert message "
2039                 "(%u %s)", action_str, version_str, severity_str,
2040                 (unsigned int) buflen, bytes_str);
2041               break;
2042 
2043             case SSL3_AD_HANDSHAKE_FAILURE:
2044               tls_log("[msg] %s %s %s 'handshake_failure' Alert message "
2045                 "(%u %s)", action_str, version_str, severity_str,
2046                 (unsigned int) buflen, bytes_str);
2047               break;
2048 
2049 #ifdef SSL3_AD_NO_CERTIFICATE
2050             case SSL3_AD_NO_CERTIFICATE:
2051               tls_log("[msg] %s %s %s 'no_certificate' Alert message "
2052                 "(%u %s)", action_str, version_str, severity_str,
2053                 (unsigned int) buflen, bytes_str);
2054               break;
2055 #endif /* SSL3_AD_NO_CERTIFICATE */
2056 
2057 #ifdef SSL3_AD_BAD_CERTIFICATE
2058             case SSL3_AD_BAD_CERTIFICATE:
2059               tls_log("[msg] %s %s %s 'bad_certificate' Alert message "
2060                 "(%u %s)", action_str, version_str, severity_str,
2061                 (unsigned int) buflen, bytes_str);
2062               break;
2063 #endif /* SSL3_AD_BAD_CERTIFICATE */
2064 
2065 #ifdef SSL3_AD_UNSUPPORTED_CERTIFICATE
2066             case SSL3_AD_UNSUPPORTED_CERTIFICATE:
2067               tls_log("[msg] %s %s %s 'unsupported_certificate' Alert message "
2068                 "(%u %s)", action_str, version_str, severity_str,
2069                 (unsigned int) buflen, bytes_str);
2070               break;
2071 #endif /* SSL3_AD_UNSUPPORTED_CERTIFICATE */
2072 
2073 #ifdef SSL3_AD_CERTIFICATE_REVOKED
2074             case SSL3_AD_CERTIFICATE_REVOKED:
2075               tls_log("[msg] %s %s %s 'certificate_revoked' Alert message "
2076                 "(%u %s)", action_str, version_str, severity_str,
2077                 (unsigned int) buflen, bytes_str);
2078               break;
2079 #endif /* SSL3_AD_CERTIFICATE_REVOKED */
2080 
2081 #ifdef SSL3_AD_CERTIFICATE_EXPIRED
2082             case SSL3_AD_CERTIFICATE_EXPIRED:
2083               tls_log("[msg] %s %s %s 'certificate_expired' Alert message "
2084                 "(%u %s)", action_str, version_str, severity_str,
2085                 (unsigned int) buflen, bytes_str);
2086               break;
2087 #endif /* SSL3_AD_CERTIFICATE_EXPIRED */
2088 
2089 #ifdef SSL3_AD_CERTIFICATE_UNKNOWN
2090             case SSL3_AD_CERTIFICATE_UNKNOWN:
2091               tls_log("[msg] %s %s %s 'certificate_unknown' Alert message "
2092                 "(%u %s)", action_str, version_str, severity_str,
2093                 (unsigned int) buflen, bytes_str);
2094               break;
2095 #endif /* SSL3_AD_CERTIFICATE_UNKNOWN */
2096 
2097 #ifdef SSL3_AD_ILLEGAL_PARAMETER
2098             case SSL3_AD_ILLEGAL_PARAMETER:
2099               tls_log("[msg] %s %s %s 'illegal_parameter' Alert message "
2100                 "(%u %s)", action_str, version_str, severity_str,
2101                 (unsigned int) buflen, bytes_str);
2102               break;
2103 #endif /* SSL3_AD_ILLEGAL_PARAMETER */
2104           }
2105 
2106         } else {
2107           tls_log("[msg] %s %s Alert message, unknown type (%u %s)", action_str,
2108             version_str, (unsigned int) buflen, bytes_str);
2109         }
2110 
2111         break;
2112       }
2113 
2114       case SSL3_RT_HANDSHAKE: {
2115         /* Handshake messages */
2116         pr_trace_msg(trace_channel, 27,
2117           "%s %s Handshake (%u %s)", action_str, version_str,
2118           (unsigned int) buflen, bytes_str);
2119         if (buflen > 0) {
2120           /* Peek naughtily into the buffer. */
2121           switch (((const unsigned char *) buf)[0]) {
2122             case SSL3_MT_HELLO_REQUEST:
2123               tls_log("[msg] %s %s 'HelloRequest' Handshake message (%u %s)",
2124                 action_str, version_str, (unsigned int) buflen, bytes_str);
2125               break;
2126 
2127             case SSL3_MT_CLIENT_HELLO: {
2128               const unsigned char *msg;
2129               size_t msglen;
2130 
2131               msg = buf;
2132               msglen = buflen;
2133 
2134               tls_log("[msg] %s %s 'ClientHello' Handshake message (%u %s)",
2135                 action_str, version_str, (unsigned int) msglen, bytes_str);
2136 
2137               tls_print_client_hello(io_flag, version, content_type, msg + 4,
2138                 msglen - 4, ssl, arg);
2139               break;
2140             }
2141 
2142             case SSL3_MT_SERVER_HELLO: {
2143               const unsigned char *msg;
2144               size_t msglen;
2145 
2146               msg = buf;
2147               msglen = buflen;
2148 
2149               tls_log("[msg] %s %s 'ServerHello' Handshake message (%u %s)",
2150                 action_str, version_str, (unsigned int) buflen, bytes_str);
2151 
2152               tls_print_server_hello(io_flag, version, content_type, msg + 4,
2153                 msglen - 4, ssl, arg);
2154               break;
2155             }
2156 
2157 #ifdef SSL3_MT_NEWSESSION_TICKET
2158             case SSL3_MT_NEWSESSION_TICKET: {
2159               const unsigned char *msg;
2160               size_t msglen;
2161 
2162               msg = buf;
2163               msglen = buflen;
2164 
2165               tls_log("[msg] %s %s 'NewSessionTicket' Handshake message "
2166                 "(%u %s)", action_str, version_str, (unsigned int) buflen,
2167                 bytes_str);
2168 
2169               tls_print_ticket(io_flag, version, content_type, msg + 4,
2170                 msglen - 4, ssl, arg);
2171               break;
2172             }
2173 #endif /* SSL3_MT_NEWSESSION_TICKET */
2174 
2175             case SSL3_MT_CERTIFICATE:
2176               tls_log("[msg] %s %s 'Certificate' Handshake message (%u %s)",
2177                 action_str, version_str, (unsigned int) buflen, bytes_str);
2178               break;
2179 
2180             case SSL3_MT_SERVER_KEY_EXCHANGE:
2181               tls_log("[msg] %s %s 'ServerKeyExchange' Handshake message "
2182                 "(%u %s)", action_str, version_str, (unsigned int) buflen,
2183                 bytes_str);
2184               break;
2185 
2186             case SSL3_MT_CERTIFICATE_REQUEST:
2187               tls_log("[msg] %s %s 'CertificateRequest' Handshake message "
2188                 "(%u %s)", action_str, version_str, (unsigned int) buflen,
2189                 bytes_str);
2190               break;
2191 
2192             case SSL3_MT_SERVER_DONE:
2193               tls_log("[msg] %s %s 'ServerHelloDone' Handshake message (%u %s)",
2194                 action_str, version_str, (unsigned int) buflen, bytes_str);
2195               break;
2196 
2197             case SSL3_MT_CERTIFICATE_VERIFY:
2198               tls_log("[msg] %s %s 'CertificateVerify' Handshake message "
2199                 "(%u %s)", action_str, version_str, (unsigned int) buflen,
2200                 bytes_str);
2201               break;
2202 
2203             case SSL3_MT_CLIENT_KEY_EXCHANGE:
2204               tls_log("[msg] %s %s 'ClientKeyExchange' Handshake message "
2205                 "(%u %s)", action_str, version_str, (unsigned int) buflen,
2206                 bytes_str);
2207               break;
2208 
2209             case SSL3_MT_FINISHED:
2210               tls_log("[msg] %s %s 'Finished' Handshake message (%u %s)",
2211                 action_str, version_str, (unsigned int) buflen, bytes_str);
2212               break;
2213 
2214 #ifdef SSL3_MT_CERTIFICATE_STATUS
2215             case SSL3_MT_CERTIFICATE_STATUS:
2216               tls_log("[msg] %s %s 'CertificateStatus' Handshake message "
2217                 "(%u %s)", action_str, version_str, (unsigned int) buflen,
2218                 bytes_str);
2219               break;
2220 #endif /* SSL3_MT_CERTIFICATE_STATUS */
2221 
2222 #ifdef SSL3_MT_ENCRYPTED_EXTENSIONS
2223             case SSL3_MT_ENCRYPTED_EXTENSIONS: {
2224               const unsigned char *msg;
2225               size_t msglen;
2226               BIO *bio;
2227               char *data = NULL;
2228               long datalen;
2229 
2230               msg = buf;
2231               msglen = buflen;
2232 
2233               tls_log("[msg] %s %s 'EncryptedExtensions' Handshake message "
2234                 "(%u %s)", action_str, version_str, (unsigned int) buflen,
2235                 bytes_str);
2236 
2237               bio = BIO_new(BIO_s_mem());
2238 
2239               msg += 4;
2240               msglen -= 4;
2241 
2242               BIO_puts(bio, "\nEncryptedExtensions:\n");
2243               tls_print_extensions(bio, "extensions", TRUE, &msg, &msglen);
2244               datalen = BIO_get_mem_data(bio, &data);
2245               if (data != NULL) {
2246                 data[datalen] = '\0';
2247                 tls_log("[msg] %.*s", (int) datalen, data);
2248               }
2249 
2250               BIO_free(bio);
2251               break;
2252             }
2253 #endif /* SSL3_MT_ENCRYPTED_EXTENSIONS */
2254           }
2255 
2256         } else {
2257           tls_log("[msg] %s %s Handshake message, unknown type %d (%u %s)",
2258             action_str, version_str, content_type, (unsigned int) buflen,
2259             bytes_str);
2260         }
2261 
2262         break;
2263       }
2264     }
2265 
2266   } else if (version == SSL2_VERSION) {
2267     /* SSLv2 message.  Ideally we wouldn't get these, but sometimes badly
2268      * behaving FTPS clients send them.
2269      */
2270 
2271     if (buflen > 0) {
2272       /* Peek naughtily into the buffer. */
2273 
2274       switch (((const unsigned char *) buf)[0]) {
2275         case 0: {
2276           /* Error */
2277           if (buflen > 3) {
2278             unsigned err_code = (((const unsigned char *) buf)[1] << 8) +
2279               ((const unsigned char *) buf)[2];
2280 
2281             switch (err_code) {
2282               case 0x0001:
2283                 tls_log("[msg] %s %s 'NO-CIPHER-ERROR' Error message (%u %s)",
2284                   action_str, version_str, (unsigned int) buflen, bytes_str);
2285                 break;
2286 
2287               case 0x0002:
2288                 tls_log("[msg] %s %s 'NO-CERTIFICATE-ERROR' Error message "
2289                   "(%u %s)", action_str, version_str, (unsigned int) buflen,
2290                   bytes_str);
2291                 break;
2292 
2293               case 0x0004:
2294                 tls_log("[msg] %s %s 'BAD-CERTIFICATE-ERROR' Error message "
2295                   "(%u %s)", action_str, version_str, (unsigned int) buflen,
2296                   bytes_str);
2297                 break;
2298 
2299               case 0x0006:
2300                 tls_log("[msg] %s %s 'UNSUPPORTED-CERTIFICATE-TYPE-ERROR' "
2301                   "Error message (%u %s)", action_str, version_str,
2302                   (unsigned int) buflen, bytes_str);
2303                 break;
2304             }
2305 
2306           } else {
2307             tls_log("[msg] %s %s Error message, unknown type %d (%u %s)",
2308               action_str, version_str, content_type, (unsigned int) buflen,
2309               bytes_str);
2310           }
2311           break;
2312         }
2313 
2314         case 1:
2315           tls_log("[msg] %s %s 'CLIENT-HELLO' message (%u %s)", action_str,
2316             version_str, (unsigned int) buflen, bytes_str);
2317           break;
2318 
2319         case 2:
2320           tls_log("[msg] %s %s 'CLIENT-MASTER-KEY' message (%u %s)", action_str,
2321             version_str, (unsigned int) buflen, bytes_str);
2322           break;
2323 
2324         case 3:
2325           tls_log("[msg] %s %s 'CLIENT-FINISHED' message (%u %s)", action_str,
2326             version_str, (unsigned int) buflen, bytes_str);
2327           break;
2328 
2329         case 4:
2330           tls_log("[msg] %s %s 'SERVER-HELLO' message (%u %s)", action_str,
2331             version_str, (unsigned int) buflen, bytes_str);
2332           break;
2333 
2334         case 5:
2335           tls_log("[msg] %s %s 'SERVER-VERIFY' message (%u %s)", action_str,
2336             version_str, (unsigned int) buflen, bytes_str);
2337           break;
2338 
2339         case 6:
2340           tls_log("[msg] %s %s 'SERVER-FINISHED' message (%u %s)", action_str,
2341             version_str, (unsigned int) buflen, bytes_str);
2342           break;
2343 
2344         case 7:
2345           tls_log("[msg] %s %s 'REQUEST-CERTIFICATE' message (%u %s)",
2346             action_str, version_str, (unsigned int) buflen, bytes_str);
2347           break;
2348 
2349         case 8:
2350           tls_log("[msg] %s %s 'CLIENT-CERTIFICATE' message (%u %s)",
2351             action_str, version_str, (unsigned int) buflen, bytes_str);
2352           break;
2353       }
2354 
2355     } else {
2356       tls_log("[msg] %s %s message (%u %s)", action_str, version_str,
2357         (unsigned int) buflen, bytes_str);
2358     }
2359 
2360 #ifdef SSL3_RT_HEADER
2361   } else if (version == 0 &&
2362              content_type == SSL3_RT_HEADER &&
2363              buflen == SSL3_RT_HEADER_LENGTH) {
2364     const char *msg;
2365     const char *record_type;
2366     int msg_len;
2367 
2368     msg = buf;
2369     record_type = tls_get_label(msg[0], tls_record_type_labels);
2370     msg_len = msg[buflen - 2] << 8 | msg[buflen - 1];
2371 
2372     tls_log("[msg] %s protocol record message (content type = %s, len = %d)",
2373       action_str, record_type, msg_len);
2374 #endif
2375 
2376   } else {
2377     /* This case might indicate an issue with OpenSSL itself; the version
2378      * given to the msg_callback function was not initialized, or not set to
2379      * one of the recognized SSL/TLS versions.  Weird.
2380      */
2381 
2382     tls_log("[msg] %s message of unknown version %d, type %d (%u %s)",
2383       action_str, version, content_type, (unsigned int) buflen, bytes_str);
2384   }
2385 
2386 }
2387 #endif
2388 
2389 static const char *get_printable_subjaltname(pool *p, const char *data,
2390     size_t datalen) {
2391   register unsigned int i;
2392   char *ptr, *res;
2393   size_t reslen = 0;
2394 
2395   /* First, calculate the length of the resulting printable string we'll
2396    * be generating.
2397    */
2398 
2399   for (i = 0; i < datalen; i++) {
2400     if (PR_ISPRINT(data[i])) {
2401       reslen++;
2402 
2403     } else {
2404       reslen += 4;
2405     }
2406   }
2407 
2408   /* Leave one space in the allocated string for the terminating NUL. */
2409   ptr = res = pcalloc(p, reslen + 1);
2410 
2411   for (i = 0; i < datalen; i++) {
2412     if (PR_ISPRINT(data[i])) {
2413       *(ptr++) = data[i];
2414 
2415     } else {
2416       pr_snprintf(ptr, reslen - (ptr - res), "\\x%02x", data[i]);
2417       ptr += 4;
2418     }
2419   }
2420 
2421   return res;
2422 }
2423 
2424 static int tls_cert_match_dns_san(pool *p, X509 *cert, const char *dns_name) {
2425   int matched = 0;
2426 #if OPENSSL_VERSION_NUMBER > 0x000907000L
2427   STACK_OF(GENERAL_NAME) *sans;
2428 
2429   sans = X509_get_ext_d2i(cert, NID_subject_alt_name, NULL, NULL);
2430   if (sans != NULL) {
2431     register int i;
2432     int nsans = sk_GENERAL_NAME_num(sans);
2433 
2434     for (i = 0; i < nsans; i++) {
2435       GENERAL_NAME *alt_name;
2436 
2437       pr_signals_handle();
2438 
2439       alt_name = sk_GENERAL_NAME_value(sans, i);
2440       if (alt_name->type == GEN_DNS) {
2441         char *dns_san;
2442         size_t dns_sanlen;
2443 
2444         dns_san = (char *) ASN1_STRING_data(alt_name->d.ia5);
2445         dns_sanlen = strlen(dns_san);
2446 
2447         /* Check for subjectAltName values which contain embedded NULs.
2448          * This can cause verification problems (spoofing), e.g. if the
2449          * string is "www.goodguy.com\0www.badguy.com"; the use of strcmp()
2450          * only checks "www.goodguy.com".
2451          */
2452 
2453         if ((size_t) ASN1_STRING_length(alt_name->d.ia5) != dns_sanlen) {
2454           tls_log("%s", "cert dNSName SAN contains embedded NULs, "
2455             "rejecting as possible spoof attempt");
2456           tls_log("suspicious dNSName SAN value: '%s'",
2457             get_printable_subjaltname(p, dns_san,
2458               ASN1_STRING_length(alt_name->d.dNSName)));
2459 
2460           GENERAL_NAME_free(alt_name);
2461           sk_GENERAL_NAME_free(sans);
2462           return 0;
2463         }
2464 
2465         if (strncasecmp(dns_name, dns_san, dns_sanlen + 1) == 0) {
2466           pr_trace_msg(trace_channel, 8,
2467             "found cert dNSName SAN matching '%s'", dns_name);
2468           matched = 1;
2469 
2470         } else {
2471           pr_trace_msg(trace_channel, 9,
2472             "cert dNSName SAN '%s' did not match '%s'", dns_san, dns_name);
2473         }
2474       }
2475 
2476       GENERAL_NAME_free(alt_name);
2477 
2478       if (matched == 1) {
2479         break;
2480       }
2481     }
2482 
2483     sk_GENERAL_NAME_free(sans);
2484   }
2485 #endif /* OpenSSL-0.9.7 or later */
2486 
2487   return matched;
2488 }
2489 
2490 static int tls_cert_match_ip_san(pool *p, X509 *cert, const char *ipstr) {
2491   int matched = 0;
2492   STACK_OF(GENERAL_NAME) *sans;
2493 
2494   sans = X509_get_ext_d2i(cert, NID_subject_alt_name, NULL, NULL);
2495   if (sans != NULL) {
2496     register int i;
2497     int nsans = sk_GENERAL_NAME_num(sans);
2498 
2499     for (i = 0; i < nsans; i++) {
2500       GENERAL_NAME *alt_name;
2501 
2502       pr_signals_handle();
2503 
2504       alt_name = sk_GENERAL_NAME_value(sans, i);
2505       if (alt_name->type == GEN_IPADD) {
2506         unsigned char *san_data = NULL;
2507         int have_ipstr = FALSE, san_datalen;
2508 #ifdef PR_USE_IPV6
2509         char san_ipstr[INET6_ADDRSTRLEN + 1] = {'\0'};
2510 #else
2511         char san_ipstr[INET_ADDRSTRLEN + 1] = {'\0'};
2512 #endif /* PR_USE_IPV6 */
2513 
2514         san_data = ASN1_STRING_data(alt_name->d.ip);
2515         memset(san_ipstr, '\0', sizeof(san_ipstr));
2516 
2517         san_datalen = ASN1_STRING_length(alt_name->d.ip);
2518         if (san_datalen == 4) {
2519           /* IPv4 address */
2520           pr_snprintf(san_ipstr, sizeof(san_ipstr)-1, "%u.%u.%u.%u",
2521             san_data[0], san_data[1], san_data[2], san_data[3]);
2522           have_ipstr = TRUE;
2523 
2524 #ifdef PR_USE_IPV6
2525         } else if (san_datalen == 16) {
2526           /* IPv6 address */
2527 
2528           if (pr_inet_ntop(AF_INET6, san_data, san_ipstr,
2529               sizeof(san_ipstr)-1) == NULL) {
2530             tls_log("unable to convert cert iPAddress SAN value (length %d) "
2531               "to IPv6 representation: %s", san_datalen, strerror(errno));
2532 
2533           } else {
2534             have_ipstr = TRUE;
2535           }
2536 
2537 #endif /* PR_USE_IPV6 */
2538         } else {
2539           pr_trace_msg(trace_channel, 3,
2540             "unsupported cert SAN ipAddress length (%d), ignoring",
2541             san_datalen);
2542           continue;
2543         }
2544 
2545         if (have_ipstr) {
2546           size_t san_ipstrlen;
2547 
2548           san_ipstrlen = strlen(san_ipstr);
2549 
2550           if (strncmp(ipstr, san_ipstr, san_ipstrlen + 1) == 0) {
2551             pr_trace_msg(trace_channel, 8,
2552               "found cert iPAddress SAN matching '%s'", ipstr);
2553             matched = 1;
2554 
2555           } else {
2556             if (san_datalen == 16) {
2557               /* We need to handle the case where the iPAddress SAN might
2558                * have contained an IPv4-mapped IPv6 address, and we're
2559                * comparing against an IPv4 address.
2560                */
2561               if (san_ipstrlen > 7 &&
2562                   strncasecmp(san_ipstr, "::ffff:", 7) == 0) {
2563                 if (strncmp(ipstr, san_ipstr + 7, san_ipstrlen - 6) == 0) {
2564                   pr_trace_msg(trace_channel, 8,
2565                     "found cert iPAddress SAN '%s' matching '%s'",
2566                     san_ipstr, ipstr);
2567                     matched = 1;
2568                 }
2569               }
2570 
2571             } else {
2572               pr_trace_msg(trace_channel, 9,
2573                 "cert iPAddress SAN '%s' did not match '%s'", san_ipstr, ipstr);
2574             }
2575           }
2576         }
2577       }
2578 
2579       GENERAL_NAME_free(alt_name);
2580 
2581       if (matched == 1) {
2582         break;
2583       }
2584     }
2585 
2586     sk_GENERAL_NAME_free(sans);
2587   }
2588 
2589   return matched;
2590 }
2591 
2592 static int tls_cert_match_cn(pool *p, X509 *cert, const char *name,
2593     int allow_wildcards) {
2594   int matched = 0, idx = -1;
2595   X509_NAME *subj_name = NULL;
2596   X509_NAME_ENTRY *cn_entry = NULL;
2597   ASN1_STRING *cn_asn1 = NULL;
2598   char *cn_str = NULL;
2599   size_t cn_len = 0;
2600 
2601   /* Find the position of the CommonName (CN) field within the Subject of
2602    * the cert.
2603    */
2604   subj_name = X509_get_subject_name(cert);
2605   if (subj_name == NULL) {
2606     pr_trace_msg(trace_channel, 12,
2607       "unable to check certificate CommonName against '%s': "
2608       "unable to get Subject", name);
2609     return 0;
2610   }
2611 
2612   idx = X509_NAME_get_index_by_NID(subj_name, NID_commonName, -1);
2613   if (idx < 0) {
2614     pr_trace_msg(trace_channel, 12,
2615       "unable to check certificate CommonName against '%s': "
2616       "no CommoName attribute found", name);
2617     return 0;
2618   }
2619 
2620   cn_entry = X509_NAME_get_entry(subj_name, idx);
2621   if (cn_entry == NULL) {
2622     pr_trace_msg(trace_channel, 12,
2623       "unable to check certificate CommonName against '%s': "
2624       "error obtaining CommoName attribute found: %s", name, tls_get_errors());
2625     return 0;
2626   }
2627 
2628   /* Convert the CN field to a string, by way of an ASN1 object. */
2629   cn_asn1 = X509_NAME_ENTRY_get_data(cn_entry);
2630   if (cn_asn1 == NULL) {
2631     pr_trace_msg(trace_channel, 12,
2632       "unable to check certificate CommonName against '%s': "
2633       "error converting CommoName attribute to ASN.1: %s", name,
2634       tls_get_errors());
2635     return 0;
2636   }
2637 
2638   cn_str = (char *) ASN1_STRING_data(cn_asn1);
2639 
2640   /* Check for CommonName values which contain embedded NULs.  This can cause
2641    * verification problems (spoofing), e.g. if the string is
2642    * "www.goodguy.com\0www.badguy.com"; the use of strcmp() only checks
2643    * "www.goodguy.com".
2644    */
2645 
2646   cn_len = strlen(cn_str);
2647 
2648   if ((size_t) ASN1_STRING_length(cn_asn1) != cn_len) {
2649     tls_log("%s", "cert CommonName contains embedded NULs, rejecting as "
2650       "possible spoof attempt");
2651     tls_log("suspicious CommonName value: '%s'",
2652       get_printable_subjaltname(p, (const char *) cn_str,
2653         ASN1_STRING_length(cn_asn1)));
2654     return 0;
2655   }
2656 
2657   /* Yes, this is deliberately a case-insensitive comparison.  Most CNs
2658    * contain a hostname (case-insensitive); if they contain an IP address,
2659    * the case-insensitivity won't hurt anything.  In fact, it's needed for
2660    * e.g. IPv6 addresses.
2661    */
2662   if (strncasecmp(name, cn_str, cn_len + 1) == 0) {
2663     matched = 1;
2664   }
2665 
2666   if (matched == 0 &&
2667       allow_wildcards) {
2668 
2669     /* XXX Implement wildcard checking. */
2670   }
2671 
2672   return matched;
2673 }
2674 
2675 static int tls_check_client_cert(SSL *ssl, conn_t *conn) {
2676   X509 *cert = NULL;
2677   unsigned char have_cn = FALSE, have_dns_ext = FALSE, have_ipaddr_ext = FALSE;
2678   int ok = -1;
2679 
2680   /* Only perform these more stringent checks if asked to verify clients. */
2681   if (!(tls_flags & TLS_SESS_VERIFY_CLIENT_REQUIRED)) {
2682     return 0;
2683   }
2684 
2685   /* Only perform these checks is configured to do so. */
2686   if (!(tls_opts & TLS_OPT_VERIFY_CERT_FQDN) &&
2687       !(tls_opts & TLS_OPT_VERIFY_CERT_IP_ADDR) &&
2688       !(tls_opts & TLS_OPT_VERIFY_CERT_CN)) {
2689     return 0;
2690   }
2691 
2692   cert = SSL_get_peer_certificate(ssl);
2693   if (cert == NULL) {
2694     /* This can be null in the case where some anonymous (insecure)
2695      * cipher suite was used.
2696      */
2697     tls_log("unable to verify '%s': client did not provide certificate",
2698       conn->remote_name);
2699     return -1;
2700   }
2701 
2702   /* Check the DNS SANs if configured. */
2703   if (tls_opts & TLS_OPT_VERIFY_CERT_FQDN) {
2704     int matched;
2705 
2706     matched = tls_cert_match_dns_san(conn->pool, cert, conn->remote_name);
2707     if (matched == 0) {
2708       tls_log("client cert dNSName SANs do not match remote name '%s'",
2709         conn->remote_name);
2710       return -1;
2711 
2712     } else {
2713       tls_log("client cert dNSName SAN matches remote name '%s'",
2714         conn->remote_name);
2715       have_dns_ext = TRUE;
2716       ok = 1;
2717     }
2718   }
2719 
2720   /* Check the IP SANs, if configured. */
2721   if (tls_opts & TLS_OPT_VERIFY_CERT_IP_ADDR) {
2722     int matched;
2723 
2724     matched = tls_cert_match_ip_san(conn->pool, cert,
2725       pr_netaddr_get_ipstr(conn->remote_addr));
2726     if (matched == 0) {
2727       tls_log("client cert iPAddress SANs do not match client IP '%s'",
2728         pr_netaddr_get_ipstr(conn->remote_addr));
2729       return -1;
2730 
2731     } else {
2732       tls_log("client cert iPAddress SAN matches client IP '%s'",
2733         pr_netaddr_get_ipstr(conn->remote_addr));
2734       have_ipaddr_ext = TRUE;
2735       ok = 1;
2736     }
2737   }
2738 
2739   /* Check the CN (Common Name) if configured. */
2740   if (tls_opts & TLS_OPT_VERIFY_CERT_CN) {
2741     int matched;
2742 
2743     matched = tls_cert_match_cn(conn->pool, cert, conn->remote_name, TRUE);
2744     if (matched == 0) {
2745       tls_log("client cert CommonName does not match client FQDN '%s'",
2746         conn->remote_name);
2747       return -1;
2748 
2749     } else {
2750       tls_log("client cert CommonName matches client FQDN '%s'",
2751         conn->remote_name);
2752       have_cn = TRUE;
2753       ok = 1;
2754     }
2755   }
2756 
2757   if ((tls_opts & TLS_OPT_VERIFY_CERT_CN) &&
2758       !have_cn) {
2759     tls_log("%s", "client cert missing required X509v3 CommonName");
2760   }
2761 
2762   if ((tls_opts & TLS_OPT_VERIFY_CERT_FQDN) &&
2763       !have_dns_ext) {
2764     tls_log("%s", "client cert missing required X509v3 SubjectAltName dNSName");
2765   }
2766 
2767   if ((tls_opts & TLS_OPT_VERIFY_CERT_IP_ADDR) &&
2768       !have_ipaddr_ext) {
2769     tls_log("%s", "client cert missing required X509v3 SubjectAltName iPAddress");
2770   }
2771 
2772   X509_free(cert);
2773   return ok;
2774 }
2775 
2776 static int tls_check_server_cert(SSL *ssl, conn_t *conn) {
2777   X509 *cert = NULL;
2778   int ok = -1;
2779   long verify_result;
2780 
2781   /* Only perform these more stringent checks if asked to verify servers. */
2782   if (!(tls_flags & TLS_SESS_VERIFY_SERVER) &&
2783       !(tls_flags & TLS_SESS_VERIFY_SERVER_NO_DNS)) {
2784     return 0;
2785   }
2786 
2787   /* Check SSL_get_verify_result */
2788   verify_result = SSL_get_verify_result(ssl);
2789   if (verify_result != X509_V_OK) {
2790     tls_log("unable to verify '%s' server certificate: %s",
2791       conn->remote_name, X509_verify_cert_error_string(verify_result));
2792     return -1;
2793   }
2794 
2795   cert = SSL_get_peer_certificate(ssl);
2796   if (cert == NULL) {
2797     /* This can be null in the case where some anonymous (insecure)
2798      * cipher suite was used.
2799      */
2800     tls_log("unable to verify '%s': server did not provide certificate",
2801       conn->remote_name);
2802     return -1;
2803   }
2804 
2805   /* XXX If using OpenSSL-1.0.2/1.1.0, we might be able to use:
2806    * X509_match_host() and X509_match_ip()/X509_match_ip_asc().
2807    */
2808 
2809   ok = tls_cert_match_ip_san(conn->pool, cert,
2810     pr_netaddr_get_ipstr(conn->remote_addr));
2811   if (ok == 0) {
2812     ok = tls_cert_match_cn(conn->pool, cert,
2813       pr_netaddr_get_ipstr(conn->remote_addr), FALSE);
2814   }
2815 
2816   if (ok == 0 &&
2817       !(tls_flags & TLS_SESS_VERIFY_SERVER_NO_DNS)) {
2818     int reverse_dns;
2819     const char *remote_name;
2820     pr_netaddr_t *remote_addr;
2821 
2822     reverse_dns = pr_netaddr_set_reverse_dns(TRUE);
2823 
2824     pr_netaddr_clear_ipcache(pr_netaddr_get_ipstr(conn->remote_addr));
2825 
2826     remote_addr = (pr_netaddr_t *) conn->remote_addr;
2827     remote_addr->na_have_dnsstr = FALSE;
2828 
2829     remote_name = pr_netaddr_get_dnsstr(conn->remote_addr);
2830     pr_netaddr_set_reverse_dns(reverse_dns);
2831 
2832     ok = tls_cert_match_dns_san(conn->pool, cert, remote_name);
2833     if (ok == 0) {
2834       ok = tls_cert_match_cn(conn->pool, cert, remote_name, TRUE);
2835     }
2836   }
2837 
2838   X509_free(cert);
2839   return ok;
2840 }
2841 
2842 struct tls_pkey_data {
2843   server_rec *s;
2844   int flags;
2845   char *buf;
2846   size_t buflen, bufsz;
2847   const char *prompt;
2848 };
2849 
2850 static void tls_prepare_provider_fds(int stdout_fd, int stderr_fd) {
2851   unsigned long nfiles = 0;
2852   register unsigned int i = 0;
2853   struct rlimit rlim;
2854 
2855   if (stdout_fd != STDOUT_FILENO) {
2856     if (dup2(stdout_fd, STDOUT_FILENO) < 0)
2857       tls_log("error duping fd %d to stdout: %s", stdout_fd, strerror(errno));
2858 
2859     close(stdout_fd);
2860   }
2861 
2862   if (stderr_fd != STDERR_FILENO) {
2863     if (dup2(stderr_fd, STDERR_FILENO) < 0)
2864       tls_log("error duping fd %d to stderr: %s", stderr_fd, strerror(errno));
2865 
2866     close(stderr_fd);
2867   }
2868 
2869   /* Make sure not to pass on open file descriptors. For stdout and stderr,
2870    * we dup some pipes, so that we can capture what the command may write
2871    * to stdout or stderr.  The stderr output will be logged to the TLSLog.
2872    *
2873    * First, use getrlimit() to obtain the maximum number of open files
2874    * for this process -- then close that number.
2875    */
2876 #if defined(RLIMIT_NOFILE) || defined(RLIMIT_OFILE)
2877 # if defined(RLIMIT_NOFILE)
2878   if (getrlimit(RLIMIT_NOFILE, &rlim) < 0) {
2879 # elif defined(RLIMIT_OFILE)
2880   if (getrlimit(RLIMIT_OFILE, &rlim) < 0) {
2881 # endif
2882     /* Ignore ENOSYS (and EPERM, since some libc's use this as ENOSYS). */
2883     if (errno != ENOSYS &&
2884         errno != EPERM) {
2885       tls_log("getrlimit error: %s", strerror(errno));
2886     }
2887 
2888     /* Pick some arbitrary high number. */
2889     nfiles = 255;
2890 
2891   } else
2892     nfiles = (unsigned long) rlim.rlim_max;
2893 #else /* no RLIMIT_NOFILE or RLIMIT_OFILE */
2894    nfiles = 255;
2895 #endif
2896 
2897   if (nfiles > 255) {
2898     nfiles = 255;
2899   }
2900 
2901   /* Close the "non-standard" file descriptors. */
2902   for (i = 3; i < nfiles; i++) {
2903     (void) close(i);
2904   }
2905 
2906   return;
2907 }
2908 
2909 static void tls_prepare_provider_pipes(int *stdout_pipe, int *stderr_pipe) {
2910   if (pipe(stdout_pipe) < 0) {
2911     pr_trace_msg(trace_channel, 2, "error opening stdout pipe: %s",
2912       strerror(errno));
2913     stdout_pipe[0] = -1;
2914     stdout_pipe[1] = STDOUT_FILENO;
2915 
2916   } else {
2917     if (fcntl(stdout_pipe[0], F_SETFD, FD_CLOEXEC) < 0) {
2918       pr_trace_msg(trace_channel, 2,
2919         "error setting close-on-exec flag on stdout pipe read fd: %s",
2920         strerror(errno));
2921     }
2922 
2923     if (fcntl(stdout_pipe[1], F_SETFD, 0) < 0) {
2924       pr_trace_msg(trace_channel, 2,
2925         "error setting close-on-exec flag on stdout pipe write fd: %s",
2926         strerror(errno));
2927     }
2928   }
2929 
2930   if (pipe(stderr_pipe) < 0) {
2931     pr_trace_msg(trace_channel, 2, "error opening stderr pipe: %s",
2932       strerror(errno));
2933     stderr_pipe[0] = -1;
2934     stderr_pipe[1] = STDERR_FILENO;
2935 
2936   } else {
2937     if (fcntl(stderr_pipe[0], F_SETFD, FD_CLOEXEC) < 0) {
2938       pr_trace_msg(trace_channel, 2,
2939         "error setting close-on-exec flag on stderr pipe read fd: %s",
2940         strerror(errno));
2941     }
2942 
2943     if (fcntl(stderr_pipe[1], F_SETFD, 0) < 0) {
2944       pr_trace_msg(trace_channel, 2,
2945         "error setting close-on-exec flag on stderr pipe write fd: %s",
2946         strerror(errno));
2947     }
2948   }
2949 }
2950 
2951 static int tls_exec_passphrase_provider(server_rec *s, char *buf, int buflen,
2952     int flags) {
2953   pid_t pid;
2954   int status;
2955   int stdout_pipe[2], stderr_pipe[2];
2956 
2957   struct sigaction sa_ignore, sa_intr, sa_quit;
2958   sigset_t set_chldmask, set_save;
2959 
2960   /* Prepare signal dispositions. */
2961   sa_ignore.sa_handler = SIG_IGN;
2962   sigemptyset(&sa_ignore.sa_mask);
2963   sa_ignore.sa_flags = 0;
2964 
2965   if (sigaction(SIGINT, &sa_ignore, &sa_intr) < 0) {
2966     return -1;
2967   }
2968 
2969   if (sigaction(SIGQUIT, &sa_ignore, &sa_quit) < 0) {
2970     return -1;
2971   }
2972 
2973   sigemptyset(&set_chldmask);
2974   sigaddset(&set_chldmask, SIGCHLD);
2975 
2976   if (sigprocmask(SIG_BLOCK, &set_chldmask, &set_save) < 0) {
2977     return -1;
2978   }
2979 
2980   tls_prepare_provider_pipes(stdout_pipe, stderr_pipe);
2981 
2982   pid = fork();
2983   if (pid < 0) {
2984     int xerrno = errno;
2985 
2986     pr_log_pri(PR_LOG_ALERT,
2987       MOD_TLS_VERSION ": error: unable to fork: %s", strerror(xerrno));
2988 
2989     errno = xerrno;
2990     status = -1;
2991 
2992   } else if (pid == 0) {
2993     char nbuf[32];
2994     pool *tmp_pool;
2995     char *stdin_argv[4];
2996 
2997     /* Child process */
2998     session.pid = getpid();
2999 
3000     /* Note: there is no need to clean up this temporary pool, as we've
3001      * forked.  If the exec call succeeds, this child process will exit
3002      * normally, and its process space recovered by the OS.  If the exec
3003      * call fails, we still exit, and the process space is recovered by
3004      * the OS.  Either way, the memory will be cleaned up without need for
3005      * us to do it explicitly (unless one wanted to be pedantic about it,
3006      * of course).
3007      */
3008     tmp_pool = make_sub_pool(s->pool);
3009 
3010     /* Restore previous signal actions. */
3011     sigaction(SIGINT, &sa_intr, NULL);
3012     sigaction(SIGQUIT, &sa_quit, NULL);
3013     sigprocmask(SIG_SETMASK, &set_save, NULL);
3014 
3015     stdin_argv[0] = pstrdup(tmp_pool, tls_passphrase_provider);
3016 
3017     memset(nbuf, '\0', sizeof(nbuf));
3018     pr_snprintf(nbuf, sizeof(nbuf)-1, "%u", (unsigned int) s->ServerPort);
3019     nbuf[sizeof(nbuf)-1] = '\0';
3020     stdin_argv[1] = pstrcat(tmp_pool, s->ServerName, ":", nbuf, NULL);
3021 
3022     if (flags & TLS_PASSPHRASE_FL_RSA_KEY) {
3023       stdin_argv[2] = pstrdup(tmp_pool, "RSA");
3024 
3025     } else if (flags & TLS_PASSPHRASE_FL_DSA_KEY) {
3026       stdin_argv[2] = pstrdup(tmp_pool, "DSA");
3027 
3028     } else if (flags & TLS_PASSPHRASE_FL_EC_KEY) {
3029       stdin_argv[2] = pstrdup(tmp_pool, "EC");
3030 
3031     } else if (flags & TLS_PASSPHRASE_FL_PKCS12_PASSWD) {
3032       stdin_argv[2] = pstrdup(tmp_pool, "PKCS12");
3033     }
3034 
3035     stdin_argv[3] = NULL;
3036 
3037     PRIVS_ROOT
3038 
3039     pr_trace_msg(trace_channel, 17,
3040       "executing '%s' with uid %lu (euid %lu), gid %lu (egid %lu)",
3041       tls_passphrase_provider,
3042       (unsigned long) getuid(), (unsigned long) geteuid(),
3043       (unsigned long) getgid(), (unsigned long) getegid());
3044 
3045     pr_log_debug(DEBUG6, MOD_TLS_VERSION
3046       ": executing '%s' with uid %lu (euid %lu), gid %lu (egid %lu)",
3047       tls_passphrase_provider,
3048       (unsigned long) getuid(), (unsigned long) geteuid(),
3049       (unsigned long) getgid(), (unsigned long) getegid());
3050 
3051     /* Prepare the file descriptors that the process will inherit. */
3052     tls_prepare_provider_fds(stdout_pipe[1], stderr_pipe[1]);
3053 
3054     errno = 0;
3055     execv(tls_passphrase_provider, stdin_argv);
3056 
3057     /* Since all previous file descriptors (including those for log files)
3058      * have been closed, and root privs have been revoked, there's little
3059      * chance of directing a message of execv() failure to proftpd's log
3060      * files.  execv() only returns if there's an error; the only way we
3061      * can signal this to the waiting parent process is to exit with a
3062      * non-zero value (the value of errno will do nicely).
3063      */
3064 
3065     exit(errno);
3066 
3067   } else {
3068     int res;
3069     int maxfd, fds, send_sigterm = 1;
3070     fd_set readfds;
3071     time_t start_time = time(NULL);
3072     struct timeval tv;
3073 
3074     /* Parent process */
3075 
3076     close(stdout_pipe[1]);
3077     close(stderr_pipe[1]);
3078 
3079     maxfd = (stderr_pipe[0] > stdout_pipe[0]) ?
3080       stderr_pipe[0] : stdout_pipe[0];
3081 
3082     res = waitpid(pid, &status, WNOHANG);
3083     while (res <= 0) {
3084       if (res < 0) {
3085         if (errno != EINTR) {
3086           pr_trace_msg(trace_channel, 2,
3087             "passphrase provider error: unable to wait for pid %u: %s",
3088             (unsigned int) pid, strerror(errno));
3089           status = -1;
3090           break;
3091 
3092         } else {
3093           pr_signals_handle();
3094         }
3095       }
3096 
3097       /* Check the time elapsed since we started. */
3098       if ((time(NULL) - start_time) > TLS_PASSPHRASE_TIMEOUT) {
3099 
3100         /* Send TERM, the first time, to be polite. */
3101         if (send_sigterm) {
3102           send_sigterm = 0;
3103           pr_log_debug(DEBUG6, MOD_TLS_VERSION
3104             ": '%s' has exceeded the timeout (%lu seconds), sending "
3105             "SIGTERM (signal %d)", tls_passphrase_provider,
3106             (unsigned long) TLS_PASSPHRASE_TIMEOUT, SIGTERM);
3107           kill(pid, SIGTERM);
3108 
3109         } else {
3110           /* The child is still around?  Terminate with extreme prejudice. */
3111           pr_log_debug(DEBUG6, MOD_TLS_VERSION
3112             ": '%s' has exceeded the timeout (%lu seconds), sending "
3113             "SIGKILL (signal %d)", tls_passphrase_provider,
3114             (unsigned long) TLS_PASSPHRASE_TIMEOUT, SIGKILL);
3115           kill(pid, SIGKILL);
3116         }
3117       }
3118 
3119       /* Select on the pipe read fds, to see if the child has anything
3120        * to tell us.
3121        */
3122       FD_ZERO(&readfds);
3123 
3124       FD_SET(stdout_pipe[0], &readfds);
3125       FD_SET(stderr_pipe[0], &readfds);
3126 
3127       /* Note: this delay should be configurable somehow. */
3128       tv.tv_sec = 2L;
3129       tv.tv_usec = 0L;
3130 
3131       fds = select(maxfd + 1, &readfds, NULL, NULL, &tv);
3132 
3133       if (fds == -1 &&
3134           errno == EINTR) {
3135         pr_signals_handle();
3136       }
3137 
3138       if (fds > 0) {
3139         /* The child sent us something.  How thoughtful. */
3140 
3141         if (FD_ISSET(stdout_pipe[0], &readfds)) {
3142           res = read(stdout_pipe[0], buf, buflen);
3143           if (res > 0) {
3144             buf[buflen-1] = '\0';
3145 
3146             while (res &&
3147                    (buf[res-1] == '\r' ||
3148                     buf[res-1] == '\n')) {
3149               pr_signals_handle();
3150               res--;
3151             }
3152             buf[res] = '\0';
3153 
3154             pr_trace_msg(trace_channel, 18, "read passphrase from '%s'",
3155               tls_passphrase_provider);
3156 
3157           } else if (res < 0) {
3158             int xerrno = errno;
3159 
3160             pr_trace_msg(trace_channel, 3,
3161               "error reading stdout from '%s': %s",
3162               tls_passphrase_provider, strerror(xerrno));
3163 
3164             pr_log_debug(DEBUG2, MOD_TLS_VERSION
3165               ": error reading stdout from '%s': %s",
3166               tls_passphrase_provider, strerror(xerrno));
3167           }
3168         }
3169 
3170         if (FD_ISSET(stderr_pipe[0], &readfds)) {
3171           long stderrlen, stderrsz;
3172           char *stderrbuf;
3173           pool *tmp_pool = make_sub_pool(s->pool);
3174 
3175           stderrbuf = pr_fsio_getpipebuf(tmp_pool, stderr_pipe[0], &stderrsz);
3176           memset(stderrbuf, '\0', stderrsz);
3177 
3178           stderrlen = read(stderr_pipe[0], stderrbuf, stderrsz-1);
3179           if (stderrlen > 0) {
3180             while (stderrlen &&
3181                    (stderrbuf[stderrlen-1] == '\r' ||
3182                     stderrbuf[stderrlen-1] == '\n')) {
3183               stderrlen--;
3184             }
3185             stderrbuf[stderrlen] = '\0';
3186 
3187             pr_trace_msg(trace_channel, 5,
3188               "stderr from '%s': %s", tls_passphrase_provider,
3189               stderrbuf);
3190 
3191             pr_log_debug(DEBUG5, MOD_TLS_VERSION
3192               ": stderr from '%s': %s", tls_passphrase_provider,
3193               stderrbuf);
3194 
3195           } else if (res < 0) {
3196             int xerrno = errno;
3197 
3198             pr_trace_msg(trace_channel, 2,
3199               "error reading stderr from '%s': %s",
3200               tls_passphrase_provider, strerror(xerrno));
3201 
3202             pr_log_debug(DEBUG2, MOD_TLS_VERSION
3203               ": error reading stderr from '%s': %s",
3204               tls_passphrase_provider, strerror(xerrno));
3205           }
3206 
3207           destroy_pool(tmp_pool);
3208           tmp_pool = NULL;
3209         }
3210       }
3211 
3212       res = waitpid(pid, &status, WNOHANG);
3213     }
3214   }
3215 
3216   /* Restore the previous signal actions. */
3217   if (sigaction(SIGINT, &sa_intr, NULL) < 0) {
3218     return -1;
3219   }
3220 
3221   if (sigaction(SIGQUIT, &sa_quit, NULL) < 0) {
3222     return -1;
3223   }
3224 
3225   if (sigprocmask(SIG_SETMASK, &set_save, NULL) < 0) {
3226     return -1;
3227   }
3228 
3229   if (WIFSIGNALED(status)) {
3230     pr_log_debug(DEBUG2, MOD_TLS_VERSION
3231       ": '%s' died from signal %d", tls_passphrase_provider,
3232       WTERMSIG(status));
3233     errno = EPERM;
3234     return -1;
3235   }
3236 
3237   return 0;
3238 }
3239 
3240 static int tls_passphrase_cb(char *buf, int buflen, int rwflag, void *d) {
3241   static int need_banner = TRUE;
3242   struct tls_pkey_data *pdata = d;
3243 
3244   if (tls_passphrase_provider == NULL) {
3245     register unsigned int attempt;
3246     int pwlen = 0;
3247 
3248     tls_log("requesting passphrase from admin");
3249 
3250     /* Similar to Apache's mod_ssl, we want to be nice, and display an
3251      * informative message to the proftpd admin, telling them for what
3252      * server they are being requested to provide a passphrase.
3253      */
3254 
3255     if (need_banner) {
3256       fprintf(stderr, "\nPlease provide passphrases for these encrypted certificate keys:\n");
3257       need_banner = FALSE;
3258     }
3259 
3260     /* You get three attempts at entering the passphrase correctly. */
3261     for (attempt = 0; attempt < 3; attempt++) {
3262       int res;
3263 
3264       /* Always handle signals in a loop. */
3265       pr_signals_handle();
3266 
3267       res = EVP_read_pw_string(buf, buflen, pdata->prompt, TRUE);
3268 
3269       /* A return value of zero from EVP_read_pw_string() means success; -1
3270        * means a system error occurred, and 1 means user interaction problems.
3271        */
3272       if (res != 0) {
3273         fprintf(stderr, "\nPassphrases do not match.  Please try again.\n");
3274         continue;
3275       }
3276 
3277       /* Ensure that the buffer is NUL-terminated. */
3278       buf[buflen-1] = '\0';
3279       pwlen = strlen(buf);
3280       if (pwlen < 1) {
3281         fprintf(stderr, "Error: passphrase must be at least one character\n");
3282 
3283       } else {
3284         sstrncpy(pdata->buf, buf, pdata->bufsz);
3285         pdata->buflen = pwlen;
3286 
3287         return pwlen;
3288       }
3289     }
3290 
3291   } else {
3292     tls_log("requesting passphrase from '%s'", tls_passphrase_provider);
3293 
3294     if (tls_exec_passphrase_provider(pdata->s, buf, buflen, pdata->flags) < 0) {
3295       tls_log("error obtaining passphrase from '%s': %s",
3296         tls_passphrase_provider, strerror(errno));
3297 
3298     } else {
3299       /* Ensure that the buffer is NUL-terminated. */
3300       buf[buflen-1] = '\0';
3301 
3302       sstrncpy(pdata->buf, buf, pdata->bufsz);
3303       pdata->buflen = strlen(buf);
3304 
3305       return pdata->buflen;
3306     }
3307   }
3308 
3309 #if OPENSSL_VERSION_NUMBER < 0x00908001
3310   PEMerr(PEM_F_DEF_CALLBACK, PEM_R_PROBLEMS_GETTING_PASSWORD);
3311 #else
3312   PEMerr(PEM_F_PEM_DEF_CALLBACK, PEM_R_PROBLEMS_GETTING_PASSWORD);
3313 #endif
3314 
3315   pr_memscrub(buf, buflen);
3316   return -1;
3317 }
3318 
3319 static int prompt_fd = -1;
3320 
3321 static void set_prompt_fds(void) {
3322 
3323   /* Reconnect stderr to the term because proftpd connects stderr, earlier,
3324    * to the general stderr logfile.
3325    */
3326   prompt_fd = open("/dev/null", O_WRONLY);
3327   if (prompt_fd == -1) {
3328     /* This is an arbitrary, meaningless placeholder number. */
3329     prompt_fd = 76;
3330   }
3331 
3332   dup2(STDERR_FILENO, prompt_fd);
3333   dup2(STDOUT_FILENO, STDERR_FILENO);
3334 }
3335 
3336 static void restore_prompt_fds(void) {
3337   dup2(prompt_fd, STDERR_FILENO);
3338   close(prompt_fd);
3339   prompt_fd = -1;
3340 }
3341 
3342 static int tls_get_pkcs12_passwd(server_rec *s, FILE *fp, const char *prompt,
3343     char *buf, size_t bufsz, int flags, struct tls_pkey_data *pdata) {
3344   EVP_PKEY *pkey = NULL;
3345   X509 *cert = NULL;
3346   PKCS12 *p12 = NULL;
3347   char *passwd = NULL;
3348   int res, ok = FALSE;
3349 
3350   p12 = d2i_PKCS12_fp(fp, NULL);
3351   if (p12 != NULL) {
3352 
3353     /* Check if a password is needed. */
3354     res = PKCS12_verify_mac(p12, NULL, 0);
3355     if (res == 1) {
3356       passwd = NULL;
3357 
3358     } else if (res == 0) {
3359       res = PKCS12_verify_mac(p12, "", 0);
3360       if (res == 1) {
3361         passwd = "";
3362       }
3363     }
3364 
3365     if (res == 0) {
3366       register unsigned int attempt;
3367 
3368       /* This PKCS12 file is password-protected; need to get the password
3369        * from the admin.
3370        */
3371       for (attempt = 0; attempt < 3; attempt++) {
3372         int len = -1;
3373 
3374         /* Always handle signals in a loop. */
3375         pr_signals_handle();
3376 
3377         /* Clear the error queue at the start of the loop. */
3378         ERR_clear_error();
3379 
3380         len = tls_passphrase_cb(buf, bufsz, 0, pdata);
3381         if (len > 0) {
3382           res = PKCS12_verify_mac(p12, buf, -1);
3383           if (res == 1) {
3384 #if OPENSSL_VERSION_NUMBER >= 0x000905000L
3385             /* Use the obtained password as additional entropy, ostensibly
3386              * unknown to attackers who may be watching the network, for
3387              * OpenSSL's PRNG.
3388              *
3389              * Human language gives about 2-3 bits of entropy per byte
3390              * (as per RFC1750).
3391              */
3392             RAND_add(buf, pdata->buflen, pdata->buflen * 0.25);
3393 #endif
3394 
3395             res = PKCS12_parse(p12, buf, &pkey, &cert, NULL);
3396             if (res != 1) {
3397               PKCS12_free(p12);
3398               return -1;
3399             }
3400 
3401             ok = TRUE;
3402             break;
3403           }
3404         }
3405 
3406         fprintf(stderr, "\nWrong password for this PKCS12 file.  Please try again.\n");
3407       }
3408     } else {
3409       res = PKCS12_parse(p12, passwd, &pkey, &cert, NULL);
3410       if (res != 1) {
3411         PKCS12_free(p12);
3412         return -1;
3413       }
3414 
3415       ok = TRUE;
3416     }
3417 
3418   } else {
3419     fprintf(stderr, "\nUnable to read PKCS12 file.\n");
3420     return -1;
3421   }
3422 
3423   /* Now we should have an EVP_PKEY (which may or may not need a passphrase),
3424    * and a cert.  We don't really care about the cert right now.  But we
3425    * DO need to get the passphrase for the private key.  Do this by writing
3426    * the key to a BIO, then calling tls_get_passphrase() for that BIO.
3427    *
3428    * It looks like OpenSSL's pkcs12 command-line tool does not allow
3429    * passphrase-protected keys to be written into a PKCS12 structure;
3430    * the key is decrypted first (hence, probably, the password protection
3431    * for the entire PKCS12 structure).  Can the same be assumed to be true
3432    * for PKCS12 files created via other applications?
3433    *
3434    * For now, assume yes, that all PKCS12 files will have private keys which
3435    * are not encrypted.  If this is found to NOT be the case, then we
3436    * will need to write the obtained private key out to a BIO somehow,
3437    * then call tls_get_passphrase() on that BIO, rather than on a path.
3438    */
3439 
3440   if (cert)
3441     X509_free(cert);
3442 
3443   if (pkey)
3444     EVP_PKEY_free(pkey);
3445 
3446   if (p12)
3447     PKCS12_free(p12);
3448 
3449   if (!ok) {
3450 #if OPENSSL_VERSION_NUMBER < 0x00908001
3451     PEMerr(PEM_F_DEF_CALLBACK, PEM_R_PROBLEMS_GETTING_PASSWORD);
3452 #else
3453     PEMerr(PEM_F_PEM_DEF_CALLBACK, PEM_R_PROBLEMS_GETTING_PASSWORD);
3454 #endif
3455     return -1;
3456   }
3457 
3458   ERR_clear_error();
3459   return res;
3460 }
3461 
3462 static int tls_get_passphrase(server_rec *s, const char *path,
3463     const char *prompt, char *buf, size_t bufsz, int flags) {
3464   FILE *keyf = NULL;
3465   EVP_PKEY *pkey = NULL;
3466   struct tls_pkey_data pdata;
3467   register unsigned int attempt;
3468 
3469   if (path) {
3470     int fd, res, xerrno;
3471 
3472     /* Open an fp on the cert file. */
3473     PRIVS_ROOT
3474     fd = open(path, O_RDONLY);
3475     xerrno = errno;
3476     PRIVS_RELINQUISH
3477 
3478     if (fd < 0) {
3479       SYSerr(SYS_F_FOPEN, xerrno);
3480       return -1;
3481     }
3482 
3483     /* Make sure the fd isn't one of the big three. */
3484     if (fd <= STDERR_FILENO) {
3485       res = pr_fs_get_usable_fd(fd);
3486       if (res >= 0) {
3487         close(fd);
3488         fd = res;
3489       }
3490     }
3491 
3492     keyf = fdopen(fd, "r");
3493     if (keyf == NULL) {
3494       xerrno = errno;
3495 
3496       (void) close(fd);
3497       SYSerr(SYS_F_FOPEN, xerrno);
3498       return -1;
3499     }
3500 
3501     /* As the file contains sensitive data, we do not want it lingering
3502      * around in stdio buffers.
3503      */
3504     (void) setvbuf(keyf, NULL, _IONBF, 0);
3505   }
3506 
3507   pdata.s = s;
3508   pdata.flags = flags;
3509   pdata.buf = buf;
3510   pdata.buflen = 0;
3511   pdata.bufsz = bufsz;
3512   pdata.prompt = prompt;
3513 
3514   set_prompt_fds();
3515 
3516   if (flags & TLS_PASSPHRASE_FL_PKCS12_PASSWD) {
3517     int res;
3518 
3519     res = tls_get_pkcs12_passwd(s, keyf, prompt, buf, bufsz, flags, &pdata);
3520 
3521     if (keyf != NULL) {
3522       fclose(keyf);
3523       keyf = NULL;
3524     }
3525 
3526     /* Restore the normal stderr logging. */
3527     restore_prompt_fds();
3528 
3529     return res;
3530   }
3531 
3532   /* The user gets three tries to enter the correct passphrase. */
3533   for (attempt = 0; attempt < 3; attempt++) {
3534 
3535     /* Always handle signals in a loop. */
3536     pr_signals_handle();
3537 
3538     /* Clear the error queue at the start of the loop. */
3539     ERR_clear_error();
3540 
3541     pkey = PEM_read_PrivateKey(keyf, NULL, tls_passphrase_cb, &pdata);
3542     if (pkey != NULL) {
3543       break;
3544     }
3545 
3546     if (keyf != NULL) {
3547       fseek(keyf, 0, SEEK_SET);
3548     }
3549 
3550     fprintf(stderr, "\nWrong passphrase for this key.  Please try again.\n");
3551   }
3552 
3553   if (keyf != NULL) {
3554     fclose(keyf);
3555     keyf = NULL;
3556   }
3557 
3558   /* Restore the normal stderr logging. */
3559   restore_prompt_fds();
3560 
3561   if (pkey == NULL) {
3562     return -1;
3563   }
3564 
3565   EVP_PKEY_free(pkey);
3566 
3567   if (pdata.buflen > 0) {
3568 #if OPENSSL_VERSION_NUMBER >= 0x000905000L
3569     /* Use the obtained passphrase as additional entropy, ostensibly
3570      * unknown to attackers who may be watching the network, for
3571      * OpenSSL's PRNG.
3572      *
3573      * Human language gives about 2-3 bits of entropy per byte (RFC1750).
3574      */
3575     RAND_add(buf, pdata.buflen, pdata.buflen * 0.25);
3576 #endif
3577 
3578 #ifdef HAVE_MLOCK
3579     PRIVS_ROOT
3580     if (mlock(buf, bufsz) < 0) {
3581       pr_log_debug(DEBUG1, MOD_TLS_VERSION
3582         ": error locking passphrase into memory: %s", strerror(errno));
3583 
3584     } else {
3585       pr_log_debug(DEBUG1, MOD_TLS_VERSION ": passphrase locked into memory");
3586     }
3587     PRIVS_RELINQUISH
3588 #endif
3589   }
3590 
3591   return pdata.buflen;
3592 }
3593 
3594 static int tls_handshake_timeout_cb(CALLBACK_FRAME) {
3595   tls_handshake_timed_out = TRUE;
3596   return 0;
3597 }
3598 
3599 static void tls_scrub_pkey(tls_pkey_t *k) {
3600   if (k->rsa_pkey != NULL) {
3601     pr_memscrub(k->rsa_pkey, k->pkeysz);
3602     free(k->rsa_pkey_ptr);
3603     k->rsa_pkey = k->rsa_pkey_ptr = NULL;
3604     k->rsa_passlen = 0;
3605   }
3606 
3607   if (k->dsa_pkey != NULL) {
3608     pr_memscrub(k->dsa_pkey, k->pkeysz);
3609     free(k->dsa_pkey_ptr);
3610     k->dsa_pkey = k->dsa_pkey_ptr = NULL;
3611     k->dsa_passlen = 0;
3612   }
3613 
3614 #ifdef PR_USE_OPENSSL_ECC
3615   if (k->ec_pkey != NULL) {
3616     pr_memscrub(k->ec_pkey, k->pkeysz);
3617     free(k->ec_pkey_ptr);
3618     k->ec_pkey = k->ec_pkey_ptr = NULL;
3619     k->ec_passlen = 0;
3620   }
3621 #endif /* PR_USE_OPENSSL_ECC */
3622 
3623   if (k->pkcs12_passwd != NULL) {
3624     pr_memscrub(k->pkcs12_passwd, k->pkeysz);
3625     free(k->pkcs12_passwd_ptr);
3626     k->pkcs12_passwd = k->pkcs12_passwd_ptr = NULL;
3627     k->pkcs12_passlen = 0;
3628   }
3629 
3630   if (k->path != NULL) {
3631     free((void *) k->path);
3632     k->path = NULL;
3633   }
3634 
3635   k->next = NULL;
3636   k->sid = 0;
3637 }
3638 
3639 static tls_pkey_t *tls_lookup_pkey(server_rec *s, int lock_if_found,
3640     int scrub_unless_match) {
3641   tls_pkey_t *k, *knext, *pkey = NULL;
3642 
3643   for (k = tls_pkey_list; k; k = knext) {
3644     pr_signals_handle();
3645 
3646     knext = k->next;
3647 
3648     if (k->sid != s->sid) {
3649       if (scrub_unless_match) {
3650         /* Scrub the passphrase's memory areas. */
3651         tls_scrub_pkey(k);
3652       }
3653 
3654       continue;
3655     }
3656 
3657     pkey = k;
3658 
3659     if (lock_if_found) {
3660 #ifdef HAVE_MLOCK
3661       /* mlock() the passphrase memory areas again; page locks are not
3662        * inherited across forks.
3663        */
3664       PRIVS_ROOT
3665       if (k->rsa_pkey != NULL &&
3666           k->rsa_passlen > 0) {
3667         if (mlock(k->rsa_pkey, k->pkeysz) < 0) {
3668           tls_log("error locking passphrase into memory: %s", strerror(errno));
3669         }
3670       }
3671 
3672       if (k->dsa_pkey != NULL &&
3673           k->dsa_passlen > 0) {
3674         if (mlock(k->dsa_pkey, k->pkeysz) < 0) {
3675           tls_log("error locking passphrase into memory: %s", strerror(errno));
3676         }
3677       }
3678 
3679 # ifdef PR_USE_OPENSSL_ECC
3680       if (k->ec_pkey != NULL &&
3681           k->ec_passlen > 0) {
3682         if (mlock(k->ec_pkey, k->pkeysz) < 0) {
3683           tls_log("error locking passphrase into memory: %s", strerror(errno));
3684         }
3685       }
3686 # endif /* PR_USE_OPENSSL_ECC */
3687 
3688       if (k->pkcs12_passwd != NULL &&
3689           k->pkcs12_passlen > 0) {
3690         if (mlock(k->pkcs12_passwd, k->pkeysz) < 0) {
3691           tls_log("error locking password into memory: %s", strerror(errno));
3692         }
3693       }
3694       PRIVS_RELINQUISH
3695 #endif /* HAVE_MLOCK */
3696     }
3697 
3698     break;
3699   }
3700 
3701   return pkey;
3702 }
3703 
3704 static int tls_pkey_cb(char *buf, int buflen, int rwflag, void *data) {
3705   tls_pkey_t *k;
3706 
3707   if (data == NULL) {
3708     return 0;
3709   }
3710 
3711   k = (tls_pkey_t *) data;
3712 
3713   if ((k->flags & TLS_PKEY_USE_RSA) && k->rsa_pkey) {
3714     sstrncpy(buf, k->rsa_pkey, buflen);
3715     buf[buflen - 1] = '\0';
3716     return strlen(buf);
3717   }
3718 
3719   if ((k->flags & TLS_PKEY_USE_DSA) && k->dsa_pkey) {
3720     sstrncpy(buf, k->dsa_pkey, buflen);
3721     buf[buflen - 1] = '\0';
3722     return strlen(buf);
3723   }
3724 
3725 #ifdef PR_USE_OPENSSL_ECC
3726   if ((k->flags & TLS_PKEY_USE_EC) && k->ec_pkey) {
3727     sstrncpy(buf, k->ec_pkey, buflen);
3728     buf[buflen - 1] = '\0';
3729     return strlen(buf);
3730   }
3731 #endif /* PR_USE_OPENSSL_ECC */
3732 
3733   return 0;
3734 }
3735 
3736 static void tls_remove_pkey(tls_pkey_t *k) {
3737   if (tls_pkey_list != k) {
3738     tls_pkey_t *ki, *prev;
3739 
3740     prev = tls_pkey_list;
3741     for (ki = tls_pkey_list->next; ki; ki = ki->next) {
3742       if (ki == k) {
3743         prev->next = k->next;
3744         break;
3745       }
3746 
3747       prev = ki;
3748     }
3749 
3750   } else {
3751     /* We are the head of the list. */
3752     tls_pkey_list = k->next;
3753   }
3754 
3755   if (tls_npkeys > 0) {
3756     tls_npkeys--;
3757   }
3758 }
3759 
3760 static void tls_scrub_pkeys(void) {
3761   tls_pkey_t *k, *knext;
3762   unsigned int passphrase_count = 0;
3763 
3764   if (tls_pkey_list == NULL) {
3765     return;
3766   }
3767 
3768   /* Scrub and free all passphrases in memory. */
3769   for (k = tls_pkey_list; k; k = k->next) {
3770     if (k->rsa_pkey != NULL &&
3771         k->rsa_passlen > 0) {
3772       passphrase_count++;
3773     }
3774 
3775     if (k->dsa_pkey != NULL &&
3776         k->dsa_passlen > 0) {
3777       passphrase_count++;
3778     }
3779 
3780 #ifdef PR_USE_OPENSSL_ECC
3781     if (k->ec_pkey != NULL &&
3782         k->ec_passlen > 0) {
3783       passphrase_count++;
3784     }
3785 #endif /* PR_USE_OPENSSL_ECC */
3786 
3787     if (k->pkcs12_passwd != NULL &&
3788         k->pkcs12_passlen > 0) {
3789       passphrase_count++;
3790     }
3791   }
3792 
3793   if (passphrase_count == 0) {
3794     tls_pkey_list = NULL;
3795     tls_npkeys = 0;
3796     return;
3797   }
3798 
3799   pr_log_debug(DEBUG5, MOD_TLS_VERSION
3800     ": scrubbing %u %s from memory", passphrase_count,
3801     passphrase_count != 1 ? "passphrases" : "passphrase");
3802 
3803   for (k = tls_pkey_list; k; k = knext) {
3804     knext = k->next;
3805 
3806     pr_signals_handle();
3807     tls_scrub_pkey(k);
3808   }
3809 
3810   tls_pkey_list = NULL;
3811   tls_npkeys = 0;
3812 }
3813 
3814 static void tls_clean_pkeys(void) {
3815   register unsigned int i;
3816   tls_pkey_t *k;
3817   pool *tmp_pool;
3818   array_header *dead_keys, *valid_sids;
3819   server_rec *s;
3820 
3821   /* We scan the tls_pkey_list for any keys belonging to vhosts (by SID) which
3822    * no longer appear in our configuration.
3823    */
3824 
3825   if (tls_pkey_list == NULL) {
3826     return;
3827   }
3828 
3829   tmp_pool = make_sub_pool(tls_pool);
3830   pr_pool_tag(tmp_pool, "TLS Passphrase Cleaning");
3831 
3832   dead_keys = make_array(tmp_pool, 0, sizeof(tls_pkey_t *));
3833   valid_sids = make_array(tmp_pool, 0, sizeof(unsigned int));
3834 
3835   for (s = (server_rec *) server_list->xas_list; s; s = s->next) {
3836     *((unsigned int *) push_array(valid_sids)) = s->sid;
3837   }
3838 
3839   for (k = tls_pkey_list; k; k = k->next) {
3840     int dead_key = TRUE;
3841 
3842     for (i = 0; i < valid_sids->nelts; i++) {
3843       unsigned int sid;
3844 
3845       sid = ((unsigned int *) valid_sids->elts)[i];
3846       if (k->sid == sid) {
3847         dead_key = FALSE;
3848         break;
3849       }
3850     }
3851 
3852     if (dead_key) {
3853       *((tls_pkey_t **) push_array(dead_keys)) = k;
3854     }
3855   }
3856 
3857   for (i = 0; i < dead_keys->nelts; i++) {
3858     pr_signals_handle();
3859 
3860     k = ((tls_pkey_t **) dead_keys->elts)[i];
3861     tls_remove_pkey(k);
3862     tls_scrub_pkey(k);
3863     destroy_pool(k->pool);
3864   }
3865 
3866   destroy_pool(tmp_pool);
3867   return;
3868 }
3869 
3870 #if OPENSSL_VERSION_NUMBER > 0x000907000L
3871 static int tls_renegotiate_timeout_cb(CALLBACK_FRAME) {
3872   if ((tls_flags & TLS_SESS_ON_CTRL) &&
3873       (tls_flags & TLS_SESS_CTRL_RENEGOTIATING)) {
3874 
3875     if (!SSL_renegotiate_pending(ctrl_ssl)) {
3876       tls_log("%s", "control channel TLS session renegotiated");
3877       tls_flags &= ~TLS_SESS_CTRL_RENEGOTIATING;
3878 
3879     } else if (tls_renegotiate_required) {
3880       tls_log("%s", "requested TLS renegotiation timed out on control channel");
3881       tls_log("%s", "shutting down control channel TLS session");
3882       tls_end_sess(ctrl_ssl, session.c, 0);
3883       pr_table_remove(tls_ctrl_rd_nstrm->notes, TLS_NETIO_NOTE, NULL);
3884       pr_table_remove(tls_ctrl_wr_nstrm->notes, TLS_NETIO_NOTE, NULL);
3885       ctrl_ssl = NULL;
3886     }
3887   }
3888 
3889   if ((tls_flags & TLS_SESS_ON_DATA) &&
3890       (tls_flags & TLS_SESS_DATA_RENEGOTIATING)) {
3891     SSL *ssl;
3892 
3893     ssl = (SSL *) pr_table_get(tls_data_wr_nstrm->notes, TLS_NETIO_NOTE, NULL);
3894     if (!SSL_renegotiate_pending(ssl)) {
3895       tls_log("%s", "data channel TLS session renegotiated");
3896       tls_flags &= ~TLS_SESS_DATA_RENEGOTIATING;
3897 
3898     } else if (tls_renegotiate_required) {
3899       tls_log("%s", "requested TLS renegotiation timed out on data channel");
3900       tls_log("%s", "shutting down data channel TLS session");
3901       tls_end_sess(ssl, session.d, 0);
3902       pr_table_remove(tls_data_rd_nstrm->notes, TLS_NETIO_NOTE, NULL);
3903       pr_table_remove(tls_data_wr_nstrm->notes, TLS_NETIO_NOTE, NULL);
3904     }
3905   }
3906 
3907   return 0;
3908 }
3909 
3910 static int tls_ctrl_renegotiate_cb(CALLBACK_FRAME) {
3911 
3912   /* Guard against a timer firing as the SSL session is being torn down. */
3913   if (ctrl_ssl == NULL) {
3914     return 0;
3915   }
3916 
3917   if (tls_flags & TLS_SESS_ON_CTRL) {
3918 
3919     if (TRUE
3920 #if OPENSSL_VERSION_NUMBER >= 0x009080cfL
3921         /* In OpenSSL-0.9.8l and later, SSL session renegotiations
3922          * (both client- and server-initiated) are automatically disabled.
3923          * Unless the admin explicitly configured support for
3924          * client-initiated renegotiations via the AllowClientRenegotiations
3925          * TLSOption, we can't request renegotiations ourselves.
3926          */
3927         && (tls_opts & TLS_OPT_ALLOW_CLIENT_RENEGOTIATIONS)
3928 #endif
3929       ) {
3930       tls_flags |= TLS_SESS_CTRL_RENEGOTIATING;
3931 
3932       tls_log("requesting TLS renegotiation on control channel "
3933         "(%lu sec renegotiation interval)", p1);
3934       SSL_renegotiate(ctrl_ssl);
3935       /* SSL_do_handshake(ctrl_ssl); */
3936 
3937       pr_timer_add(tls_renegotiate_timeout, -1, &tls_module,
3938         tls_renegotiate_timeout_cb, "SSL/TLS renegotiation");
3939 
3940       /* Restart the timer. */
3941       return 1;
3942     }
3943   }
3944 
3945   return 0;
3946 }
3947 #endif
3948 
3949 static DH *tls_dh_cb(SSL *ssl, int is_export, int keylen) {
3950   DH *dh = NULL;
3951   EVP_PKEY *pkey;
3952   int pkeylen = 0, use_pkeylen = FALSE;
3953 
3954   /* OpenSSL will only ever call us (currently) with a keylen of 512 or 1024;
3955    * see the SSL_EXPORT_PKEYLENGTH macro in ssl_locl.h.  Sigh.
3956    *
3957    * Thus we adjust the DH parameter length according to the size of the
3958    * RSA/DSA private key used for the current connection.
3959    *
3960    * NOTE: This MAY cause interoperability issues with some clients, notably
3961    * Java 7 (and earlier) clients, since Java 7 and earlier supports
3962    * Diffie-Hellman only up to 1024 bits.  More sighs.  To deal with these
3963    * clients, then, you need to configure a certificate/key of 1024 bits.
3964    */
3965   pkey = SSL_get_privatekey(ssl);
3966   if (pkey != NULL) {
3967     if (get_pkey_type(pkey) == EVP_PKEY_RSA ||
3968         get_pkey_type(pkey) == EVP_PKEY_DSA) {
3969       pkeylen = EVP_PKEY_bits(pkey);
3970 
3971       if (pkeylen < TLS_DH_MIN_LEN) {
3972         if (!(tls_opts & TLS_OPT_ALLOW_WEAK_DH)) {
3973           pr_trace_msg(trace_channel, 11,
3974             "certificate private key length %d less than %d bits, using %d "
3975             "(see AllowWeakDH TLSOption)", pkeylen, TLS_DH_MIN_LEN,
3976             TLS_DH_MIN_LEN);
3977           pkeylen = TLS_DH_MIN_LEN;
3978         }
3979       }
3980 
3981       if (pkeylen != keylen) {
3982         pr_trace_msg(trace_channel, 13,
3983           "adjusted DH parameter length from %d to %d bits", keylen, pkeylen);
3984         use_pkeylen = TRUE;
3985       }
3986     }
3987   }
3988 
3989   if (tls_tmp_dhs != NULL &&
3990       tls_tmp_dhs->nelts > 0) {
3991     register unsigned int i;
3992     DH *best_dh = NULL, **dhs;
3993     int best_dhlen = 0;
3994 
3995     dhs = tls_tmp_dhs->elts;
3996 
3997     /* Search the configured list of DH parameters twice: once for any sizes
3998      * matching the actual requested size (usually 1024), and once for any
3999      * matching the certificate private key size (pkeylen).
4000      *
4001      * This behavior allows site admins to configure a TLSDHParamFile that
4002      * contains 1024-bit parameters, for e.g. Java 7 (and earlier) clients.
4003      */
4004 
4005     /* Note: the keylen argument is in BITS, but DH_size() returns the number
4006      * of BYTES.
4007      */
4008     for (i = 0; i < tls_tmp_dhs->nelts; i++) {
4009       int dhlen;
4010 
4011       dhlen = DH_size(dhs[i]) * 8;
4012       if (dhlen == keylen) {
4013         pr_trace_msg(trace_channel, 11,
4014           "found matching DH parameter for key length %d", keylen);
4015         return dhs[i];
4016       }
4017 
4018       /* Try to find the next "best" DH to use, where "best" means
4019        * the smallest DH that is larger than the necessary keylen.
4020        */
4021       if (dhlen > keylen) {
4022         if (best_dh != NULL) {
4023           if (dhlen < best_dhlen) {
4024             best_dh = dhs[i];
4025             best_dhlen = dhlen;
4026           }
4027 
4028         } else {
4029           best_dh = dhs[i];
4030           best_dhlen = dhlen;
4031         }
4032       }
4033     }
4034 
4035     for (i = 0; i < tls_tmp_dhs->nelts; i++) {
4036       int dhlen;
4037 
4038       dhlen = DH_size(dhs[i]) * 8;
4039       if (dhlen == pkeylen) {
4040         pr_trace_msg(trace_channel, 11,
4041           "found matching DH parameter for certificate private key length %d",
4042           pkeylen);
4043         return dhs[i];
4044       }
4045 
4046       if (dhlen > pkeylen) {
4047         if (best_dh != NULL) {
4048           if (dhlen < best_dhlen) {
4049             best_dh = dhs[i];
4050             best_dhlen = dhlen;
4051           }
4052 
4053         } else {
4054           best_dh = dhs[i];
4055           best_dhlen = dhlen;
4056         }
4057       }
4058     }
4059 
4060     if (best_dh != NULL) {
4061       pr_trace_msg(trace_channel, 11,
4062         "using best DH parameter for key length %d (length %d)", keylen,
4063         best_dhlen);
4064       return best_dh;
4065     }
4066   }
4067 
4068   /* Still no DH parameters found?  Use the built-in ones. */
4069 
4070   if (keylen < TLS_DH_MIN_LEN) {
4071     if (!(tls_opts & TLS_OPT_ALLOW_WEAK_DH)) {
4072       pr_trace_msg(trace_channel, 11,
4073         "requested key length %d less than %d bits, using %d "
4074         "(see AllowWeakDH TLSOption)", keylen, TLS_DH_MIN_LEN, TLS_DH_MIN_LEN);
4075       keylen = TLS_DH_MIN_LEN;
4076     }
4077   }
4078 
4079   if (use_pkeylen) {
4080     keylen = pkeylen;
4081   }
4082 
4083   switch (keylen) {
4084     case 512:
4085       dh = get_dh512();
4086       break;
4087 
4088     case 768:
4089       dh = get_dh768();
4090       break;
4091 
4092     case 1024:
4093       dh = get_dh1024();
4094       break;
4095 
4096     case 1536:
4097       dh = get_dh1536();
4098       break;
4099 
4100     case 2048:
4101       dh = get_dh2048();
4102       break;
4103 
4104     default:
4105       tls_log("unsupported DH key length %d requested, returning 1024 bits",
4106         keylen);
4107       dh = get_dh1024();
4108       break;
4109   }
4110 
4111   pr_trace_msg(trace_channel, 11, "using builtin DH for %d bits", keylen);
4112 
4113   /* Add this DH to the list, so that it can be freed properly later. */
4114   if (tls_tmp_dhs == NULL) {
4115     tls_tmp_dhs = make_array(session.pool, 1, sizeof(DH *));
4116   }
4117 
4118   *((DH **) push_array(tls_tmp_dhs)) = dh;
4119   return dh;
4120 }
4121 
4122 #if !defined(OPENSSL_NO_TLSEXT)
4123 # if defined(TLSEXT_MAXLEN_host_name)
4124 static int tls_sni_cb(SSL *ssl, int *alert_desc, void *user_data) {
4125   const char *server_name = NULL;
4126 
4127   server_name = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
4128   if (server_name != NULL) {
4129     const char *host = NULL, *sni;
4130     server_rec *named_server = NULL;
4131 
4132     pr_trace_msg(trace_channel, 5, "received SNI '%s'", server_name);
4133 
4134     /* If we have already received a HOST command, then we need to
4135      * check that the SNI value matches that of the HOST.  Otherwise,
4136      * we stash the SNI, so that if/when a HOST command is received,
4137      * we can check the HOST name against the SNI.
4138      *
4139      * RFC 7151, Section 3.2.2, does not mandate whether HOST must be
4140      * sent before e.g. AUTH TLS or not; the only example the RFC provides
4141      * shows AUTH TLS being used before HOST.  Section 4 of that RFC goes
4142      * on to recommend using HOST before AUTH, in general, unless the SNI
4143      * extension will be used, in which case, clients should use AUTH TLS
4144      * before HOST.  We need to be ready for either case.
4145      *
4146      * Note that this SNI/HOST check can only really happen for control
4147      * connections, not data connections.  FTPS clients do not receive/use
4148      * DNS hostnames for data connections, only IP addresses.
4149      */
4150 
4151     host = pr_table_get(session.notes, "mod_core.host", NULL);
4152 
4153     /* If we have already stashed an SNI, it means this is probably a data
4154      * connection.
4155      *
4156      * For data connections where an SNI is provided, we MIGHT be able to
4157      * validate that SNI (assuming it is an IP address) against our IP address,
4158      * at least.
4159      */
4160     sni = pr_table_get(session.notes, "mod_tls.sni", NULL);
4161 
4162     if (host != NULL &&
4163         sni == NULL) {
4164       /* If the requested HOST does not match the SNI, it's a fatal error.
4165        *
4166        * Bear in mind, however, that the HOST command might have used an
4167        * IPv4/IPv6 address, NOT a name.  If that is the case, we do NOT want
4168        * compare that with SNI.  Do we?
4169        */
4170 
4171       if (pr_netaddr_is_v4(host) != TRUE &&
4172           pr_netaddr_is_v6(host) != TRUE) {
4173         if (strcasecmp(host, server_name) != 0) {
4174           tls_log("warning: SNI '%s' does not match HOST '%s', rejecting "
4175             "SSL/TLS connection", server_name, host);
4176           pr_log_pri(PR_LOG_NOTICE, MOD_TLS_VERSION
4177             ": SNI '%s' does not match HOST '%s', rejecting SSL/TLS connection",
4178             server_name, host);
4179           *alert_desc = SSL_AD_ACCESS_DENIED;
4180           return SSL_TLSEXT_ERR_ALERT_FATAL;
4181         }
4182       }
4183     }
4184 
4185     if (tls_opts & TLS_OPT_IGNORE_SNI) {
4186       pr_trace_msg(trace_channel, 5,
4187         "client sent SNI '%s', ignoring due to IgnoreSNI TLSOption",
4188         server_name);
4189       return SSL_TLSEXT_ERR_OK;
4190     }
4191 
4192     /* Per RFC 6066, literal IPv4/IPv6 addresses are NOT permitted in the
4193      * SNI.  However, some clients will still send such IP addresses.
4194      * We can safely ignore these, since any IP-based virtual host selection
4195      * happens at TCP connect time.
4196      */
4197     if (pr_netaddr_is_v4(server_name) == TRUE ||
4198         pr_netaddr_is_v6(server_name) == TRUE) {
4199       pr_trace_msg(trace_channel, 5,
4200         "client sent IP address SNI '%s', ignoring", server_name);
4201       return SSL_TLSEXT_ERR_OK;
4202     }
4203 
4204     if (pr_table_add_dup(session.notes, "mod_tls.sni",
4205         (char *) server_name, 0) < 0) {
4206 
4207       /* The session.notes may already have the SNI from the ctrl channel;
4208        * no need to overwrite that.
4209        */
4210       if (errno != EEXIST) {
4211         pr_trace_msg(trace_channel, 3,
4212           "error stashing 'mod_tls.sni' in session.notes: %s", strerror(errno));
4213       }
4214     }
4215 
4216     /* Notify any listeners (e.g. mod_autohost) of the requested name, to
4217      * given them a chance to update/modify the configuration.
4218      */
4219     pr_event_generate("mod_tls.sni", server_name);
4220 
4221     /* If we have no name-based virtual servers configured (no ServerAlias),
4222      * then just ignore the SNI.  Otherwise, configurations which have been
4223      * working will "break" unexpectedly, due to SNI support.
4224      */
4225     if (pr_namebind_count(main_server) == 0) {
4226       pr_trace_msg(trace_channel, 5,
4227         "no name-based <VirtualHost> configured, ignoring SNI '%s'",
4228         server_name);
4229       return SSL_TLSEXT_ERR_OK;
4230     }
4231 
4232     /* See if we have a name-based vhost matching the SNI; if so, we want
4233      * to switch to that vhost, in case it is configured with different
4234      * server certificates, CAs.
4235      */
4236 
4237     named_server = pr_namebind_get_server(server_name, main_server->addr,
4238       session.c->local_port);
4239     if (named_server == NULL) {
4240       tls_log("no matching server found for client-sent SNI '%s', rejecting "
4241         "SSL/TLS connection", server_name);
4242       pr_log_pri(PR_LOG_NOTICE, MOD_TLS_VERSION
4243         ": no matching server found for client-sent SNI '%s', "
4244         "rejecting SSL/TLS connection", server_name);
4245 #if defined(SSL_AD_UNRECOGNIZED_NAME)
4246       *alert_desc = SSL_AD_UNRECOGNIZED_NAME;
4247 #else
4248       *alert_desc = SSL_AD_ACCESS_DENIED;
4249 #endif /* SSL_AD_UNRECOGNIZED_NAME */
4250       return SSL_TLSEXT_ERR_ALERT_FATAL;
4251     }
4252 
4253     if (named_server != main_server) {
4254       unsigned char *engine;
4255       SSL_SESSION *sess;
4256 
4257       /* First, check to see whether mod_tls is even enabled for the named
4258        * vhost.
4259        */
4260       engine = get_param_ptr(named_server->conf, "TLSEngine", FALSE);
4261       if (engine == NULL ||
4262           *engine == FALSE) {
4263         tls_log("TLSEngine not enabled for SNI '%s', rejecting client",
4264           server_name);
4265         pr_log_pri(PR_LOG_NOTICE, MOD_TLS_VERSION
4266           ": TLSEngine not enabled for SNI '%s', rejecting client",
4267           server_name);
4268 
4269 #if defined(SSL_AD_UNRECOGNIZED_NAME)
4270         *alert_desc = SSL_AD_UNRECOGNIZED_NAME;
4271 #else
4272         *alert_desc = SSL_AD_HANDSHAKE_FAILURE;
4273 #endif /* SSL_AD_UNRECOGNIZED_NAME */
4274         return SSL_TLSEXT_ERR_ALERT_FATAL;
4275       }
4276 
4277       tls_lookup_all(named_server);
4278 
4279       /* Check to see if a passphrase has been entered for this server. */
4280       tls_pkey = tls_lookup_pkey(named_server, TRUE, TRUE);
4281 
4282       if (tls_ssl_set_all(named_server, ssl) < 0) {
4283         tls_log("error initializing OpenSSL session for SNI '%s'", server_name);
4284         pr_log_pri(PR_LOG_NOTICE, MOD_TLS_VERSION
4285           ": error initializing OpenSSL session for SNI '%s'", server_name);
4286         *alert_desc = SSL_AD_ACCESS_DENIED;
4287         return SSL_TLSEXT_ERR_ALERT_FATAL;
4288       }
4289 
4290       /* Our new SSL_CTX, from the SNI, might have different protocol
4291        * versions enabled.  However, due to the _timing_ of when this SNI
4292        * callback is invoked during the TLS handshake processing, the
4293        * "acceptable" server protocol version has already been determined
4294        * based on the original SSL_CTX.  This means that we need to check
4295        * for incompatible protocol versions ourselves.  Fun!
4296        *
4297        * We implement this in a naive manner: if the new SSL_CTX has an
4298        * SSL_OP_NO_ option enabled for the protocol version currently
4299        * selected by our SSL_SESSION, fail the callback with
4300        * SSL_AD_PROTOCOL_VERSION.
4301        */
4302       sess = SSL_get_session(ssl);
4303       if (sess != NULL) {
4304         SSL_CTX *ctx;
4305         long ctx_options;
4306         int protocol_ok = FALSE, sess_version;
4307 
4308         ctx = SSL_get_SSL_CTX(ssl);
4309         ctx_options = SSL_CTX_get_options(ctx);
4310 
4311 #if OPENSSL_VERSION_NUMBER >= 0x10100000L && \
4312     !defined(HAVE_LIBRESSL)
4313         sess_version = SSL_SESSION_get_protocol_version(sess);
4314 #else
4315         sess_version = sess->ssl_version;
4316 #endif /* OpenSSL 1.1.x and later */
4317 
4318         switch (sess_version) {
4319           case SSL3_VERSION:
4320             if (!(ctx_options & SSL_OP_NO_SSLv3)) {
4321               protocol_ok = TRUE;
4322             }
4323             break;
4324 
4325           case TLS1_VERSION:
4326             if (!(ctx_options & SSL_OP_NO_TLSv1)) {
4327               protocol_ok = TRUE;
4328             }
4329             break;
4330 
4331 #if defined(TLS1_1_VERSION)
4332           case TLS1_1_VERSION:
4333             if (!(ctx_options & SSL_OP_NO_TLSv1_1)) {
4334               protocol_ok = TRUE;
4335             }
4336             break;
4337 #endif /* TLS1_1_VERSION */
4338 
4339 #if defined(TLS1_2_VERSION)
4340           case TLS1_2_VERSION:
4341             if (!(ctx_options & SSL_OP_NO_TLSv1_2)) {
4342               protocol_ok = TRUE;
4343             }
4344             break;
4345 #endif /* TLS1_2_VERSION */
4346 
4347 #if defined(TLS1_3_VERSION)
4348           case TLS1_3_VERSION:
4349             if (!(ctx_options & SSL_OP_NO_TLSv1_3)) {
4350               protocol_ok = TRUE;
4351             }
4352             break;
4353 #endif /* TLS1_3_VERSION */
4354 
4355           default:
4356             pr_trace_msg(trace_channel, 3,
4357               "unknown/unsupported protocol version '%s' (%d) requested by "
4358               "client", SSL_get_version(ssl), sess_version);
4359             break;
4360         }
4361 
4362         if (protocol_ok == FALSE) {
4363           tls_log("client-requested protocol version %s not supported by "
4364             "SNI '%s' host", SSL_get_version(ssl), server_name);
4365           pr_log_pri(PR_LOG_NOTICE, MOD_TLS_VERSION
4366             ": client-requested protocol version %s not supported by "
4367             "SNI '%s' host", SSL_get_version(ssl), server_name);
4368           *alert_desc = SSL_AD_PROTOCOL_VERSION;
4369           return SSL_TLSEXT_ERR_ALERT_FATAL;
4370         }
4371       }
4372     }
4373   }
4374 
4375   return SSL_TLSEXT_ERR_OK;
4376 }
4377 # endif /* !TLSEXT_MAXLEN_host_name */
4378 
4379 static void tls_tlsext_cb(SSL *ssl, int server, int type,
4380     unsigned char *tlsext_data, int tlsext_datalen, void *data) {
4381   char *extension_name = "(unknown)";
4382   int print_basic_info = TRUE;
4383 
4384   /* Note: OpenSSL does not implement all possible extensions.  For the
4385    * "(unknown)" extensions, see:
4386    *
4387    *  http://www.iana.org/assignments/tls-extensiontype-values/tls-extensiontype-values.xhtml#tls-extensiontype-values-1
4388    */
4389   switch (type) {
4390 # ifdef TLSEXT_TYPE_server_name
4391     case TLSEXT_TYPE_server_name: {
4392       BIO *bio = NULL;
4393       char *ext_info = "";
4394       long ext_infolen = 0;
4395 
4396       extension_name = "server name";
4397 
4398       if (pr_trace_get_level(trace_channel) >= 19 &&
4399           tlsext_datalen >= 2) {
4400 
4401         /* We read 2 bytes for the extension length, 1 byte for the
4402          * name type, and 2 bytes for the name length.  For the SNI
4403          * format specification, see:
4404          *   https://tools.ietf.org/html/rfc6066#section-3
4405          */
4406         int ext_len;
4407 
4408         ext_len = (tlsext_data[0] << 8) | tlsext_data[1];
4409         if (tlsext_datalen == ext_len + 2 &&
4410             (ext_len & 1) == 0) {
4411           int name_type;
4412           tlsext_data += 2;
4413 
4414           name_type = tlsext_data[0];
4415           tlsext_data += 1;
4416 
4417           if (name_type == TLSEXT_NAMETYPE_host_name) {
4418             size_t name_len;
4419 
4420             name_len = (tlsext_data[0] << 8) | tlsext_data[1];
4421             tlsext_data += 2;
4422 
4423             bio = BIO_new(BIO_s_mem());
4424             BIO_printf(bio, "\n  %.*s (%lu)", (int) name_len, tlsext_data,
4425               (unsigned long) name_len);
4426 
4427             ext_infolen = BIO_get_mem_data(bio, &ext_info);
4428             if (ext_info != NULL) {
4429               ext_info[ext_infolen] = '\0';
4430             }
4431           }
4432         }
4433       }
4434 
4435       pr_trace_msg(trace_channel, 6,
4436         "[tls.tlsext] TLS %s extension \"%s\" (ID %d, %d %s)%.*s",
4437         server ? "server" : "client", extension_name, type,
4438         tlsext_datalen, tlsext_datalen != 1 ? "bytes" : "byte",
4439         (int) ext_infolen, ext_info);
4440 
4441       if (bio != NULL) {
4442         BIO_free(bio);
4443       }
4444 
4445       print_basic_info = FALSE;
4446       break;
4447     }
4448 # endif
4449 
4450 # ifdef TLSEXT_TYPE_max_fragment_length
4451     case TLSEXT_TYPE_max_fragment_length:
4452       extension_name = "max fragment length";
4453       break;
4454 # endif
4455 
4456 # ifdef TLSEXT_TYPE_client_certificate_url
4457     case TLSEXT_TYPE_client_certificate_url:
4458       extension_name = "client certificate URL";
4459       break;
4460 # endif
4461 
4462 # ifdef TLSEXT_TYPE_trusted_ca_keys
4463     case TLSEXT_TYPE_trusted_ca_keys:
4464       extension_name = "trusted CA keys";
4465       break;
4466 # endif
4467 
4468 # ifdef TLSEXT_TYPE_truncated_hmac
4469     case TLSEXT_TYPE_truncated_hmac:
4470       extension_name = "truncated HMAC";
4471       break;
4472 # endif
4473 
4474 # ifdef TLSEXT_TYPE_status_request
4475     case TLSEXT_TYPE_status_request:
4476       extension_name = "status request";
4477       break;
4478 # endif
4479 
4480 # ifdef TLSEXT_TYPE_user_mapping
4481     case TLSEXT_TYPE_user_mapping:
4482       extension_name = "user mapping";
4483       break;
4484 # endif
4485 
4486 # ifdef TLSEXT_TYPE_client_authz
4487     case TLSEXT_TYPE_client_authz:
4488       extension_name = "client authz";
4489       break;
4490 # endif
4491 
4492 # ifdef TLSEXT_TYPE_server_authz
4493     case TLSEXT_TYPE_server_authz:
4494       extension_name = "server authz";
4495       break;
4496 # endif
4497 
4498 # ifdef TLSEXT_TYPE_cert_type
4499     case TLSEXT_TYPE_cert_type:
4500       extension_name = "cert type";
4501       break;
4502 # endif
4503 
4504 # ifdef TLSEXT_TYPE_elliptic_curves
4505     case TLSEXT_TYPE_elliptic_curves:
4506       extension_name = "elliptic curves";
4507       break;
4508 # endif
4509 
4510 # ifdef TLSEXT_TYPE_ec_point_formats
4511     case TLSEXT_TYPE_ec_point_formats:
4512       extension_name = "EC point formats";
4513       break;
4514 # endif
4515 
4516 # ifdef TLSEXT_TYPE_srp
4517     case TLSEXT_TYPE_srp:
4518       extension_name = "SRP";
4519       break;
4520 # endif
4521 
4522 # ifdef TLSEXT_TYPE_signature_algorithms
4523     case TLSEXT_TYPE_signature_algorithms: {
4524       BIO *bio = NULL;
4525       char *ext_info = "";
4526       long ext_infolen = 0;
4527 
4528       extension_name = "signature algorithms";
4529 
4530       if (pr_trace_get_level(trace_channel) >= 19 &&
4531           tlsext_datalen >= 2) {
4532         int len;
4533 
4534         len = (tlsext_data[0] << 8) | tlsext_data[1];
4535         if (tlsext_datalen == len + 2 &&
4536             (len & 1) == 0) {
4537           tlsext_data += 2;
4538 
4539           bio = BIO_new(BIO_s_mem());
4540           BIO_puts(bio, "\n");
4541 
4542           while (len > 0) {
4543             unsigned int sig_algo;
4544 
4545             pr_signals_handle();
4546 
4547             sig_algo = (tlsext_data[0] << 8) | tlsext_data[1];
4548             BIO_printf(bio, "  %s (0x%x)\n",
4549               tls_get_label(sig_algo, tls_sigalgo_labels), sig_algo);
4550             len -= 2;
4551             tlsext_data += 2;
4552           }
4553 
4554           ext_infolen = BIO_get_mem_data(bio, &ext_info);
4555           if (ext_info != NULL) {
4556             ext_info[ext_infolen] = '\0';
4557           }
4558         }
4559       }
4560 
4561       pr_trace_msg(trace_channel, 6,
4562         "[tls.tlsext] TLS %s extension \"%s\" (ID %d, %d %s)%.*s",
4563         server ? "server" : "client", extension_name, type,
4564         tlsext_datalen, tlsext_datalen != 1 ? "bytes" : "byte",
4565         (int) ext_infolen, ext_info);
4566 
4567       if (bio != NULL) {
4568         BIO_free(bio);
4569       }
4570 
4571       print_basic_info = FALSE;
4572       break;
4573     }
4574 # endif
4575 
4576 # ifdef TLSEXT_TYPE_use_srtp
4577     case TLSEXT_TYPE_use_srtp:
4578       extension_name = "use SRTP";
4579       break;
4580 # endif
4581 
4582 # ifdef TLSEXT_TYPE_heartbeat
4583     case TLSEXT_TYPE_heartbeat:
4584       extension_name = "heartbeat";
4585       break;
4586 # endif
4587 
4588 # ifdef TLSEXT_TYPE_signed_certificate_timestamp
4589     case TLSEXT_TYPE_signed_certificate_timestamp:
4590       extension_name = "signed certificate timestamp";
4591       break;
4592 # endif
4593 
4594 # ifdef TLSEXT_TYPE_encrypt_then_mac
4595     case TLSEXT_TYPE_encrypt_then_mac:
4596       extension_name = "encrypt then mac";
4597       break;
4598 # endif
4599 
4600 # ifdef TLSEXT_TYPE_extended_master_secret
4601     case TLSEXT_TYPE_extended_master_secret:
4602       extension_name = "extended master secret";
4603       break;
4604 # endif
4605 
4606 # ifdef TLSEXT_TYPE_session_ticket
4607     case TLSEXT_TYPE_session_ticket:
4608       extension_name = "session ticket";
4609       break;
4610 # endif
4611 
4612 # ifdef TLSEXT_TYPE_psk
4613     case TLSEXT_TYPE_psk:
4614       extension_name = "PSK";
4615       break;
4616 # endif
4617 
4618 # ifdef TLSEXT_TYPE_supported_versions
4619     case TLSEXT_TYPE_supported_versions: {
4620       BIO *bio = NULL;
4621       char *ext_info = NULL;
4622       long ext_infolen = 0;
4623 
4624       /* If we are the server responding, we only indicate the selected
4625        * protocol version.  Otherwise, we are a client indicating the range
4626        * of versions supported.
4627        */
4628 
4629       extension_name = "supported versions";
4630 
4631       if (pr_trace_get_level(trace_channel) >= 19) {
4632         bio = BIO_new(BIO_s_mem());
4633 
4634         if (server) {
4635           if (tlsext_datalen == 2) {
4636             int version;
4637 
4638             version = (tlsext_data[0] << 8) | tlsext_data[1];
4639             BIO_printf(bio, "\n  %s (0x%x)\n",
4640               tls_get_label(version, tls_version_labels), version);
4641           }
4642 
4643         } else {
4644           if (tlsext_datalen >= 1) {
4645             int len;
4646 
4647             len = tlsext_data[0];
4648             if (tlsext_datalen == len + 1) {
4649               tlsext_data += 1;
4650 
4651               BIO_puts(bio, "\n");
4652 
4653               while (len > 0) {
4654                 int version;
4655 
4656                 pr_signals_handle();
4657 
4658                 version = (tlsext_data[0] << 8) | tlsext_data[1];
4659                 BIO_printf(bio, "  %s (0x%x)\n",
4660                   tls_get_label(version, tls_version_labels), version);
4661                 len -= 2;
4662                 tlsext_data += 2;
4663               }
4664             }
4665           }
4666         }
4667 
4668         ext_infolen = BIO_get_mem_data(bio, &ext_info);
4669         if (ext_info != NULL) {
4670           ext_info[ext_infolen] = '\0';
4671         }
4672       }
4673 
4674       pr_trace_msg(trace_channel, 6,
4675         "[tls.tlsext] TLS %s extension \"%s\" (ID %d, %d %s)%.*s",
4676         server ? "server" : "client", extension_name, type,
4677         tlsext_datalen, tlsext_datalen != 1 ? "bytes" : "byte",
4678         (int) ext_infolen, ext_info);
4679 
4680       if (bio != NULL) {
4681         BIO_free(bio);
4682       }
4683 
4684       print_basic_info = FALSE;
4685       break;
4686     }
4687 # endif
4688 
4689 # ifdef TLSEXT_TYPE_psk_kex_modes
4690     case TLSEXT_TYPE_psk_kex_modes: {
4691       BIO *bio = NULL;
4692       char *ext_info = NULL;
4693       long ext_infolen = 0;
4694 
4695       extension_name = "PSK KEX modes";
4696 
4697       if (pr_trace_get_level(trace_channel) >= 19) {
4698         if (tlsext_datalen >= 1) {
4699           int len;
4700 
4701           bio = BIO_new(BIO_s_mem());
4702           len = tlsext_data[0];
4703 
4704           if (tlsext_datalen == len + 1) {
4705             tlsext_data += 1;
4706 
4707             BIO_puts(bio, "\n");
4708 
4709             while (len > 0) {
4710               int kex_mode;
4711 
4712               pr_signals_handle();
4713 
4714               kex_mode = tlsext_data[0];
4715               BIO_printf(bio, "  %s (%d)\n",
4716                 tls_get_label(kex_mode, tls_psk_kex_labels), kex_mode);
4717               len -= 1;
4718               tlsext_data += 1;
4719             }
4720           }
4721         }
4722 
4723         ext_infolen = BIO_get_mem_data(bio, &ext_info);
4724         if (ext_info != NULL) {
4725           ext_info[ext_infolen] = '\0';
4726         }
4727       }
4728 
4729       pr_trace_msg(trace_channel, 6,
4730         "[tls.tlsext] TLS %s extension \"%s\" (ID %d, %d %s)%.*s",
4731         server ? "server" : "client", extension_name, type,
4732         tlsext_datalen, tlsext_datalen != 1 ? "bytes" : "byte",
4733         (int) ext_infolen, ext_info);
4734 
4735       if (bio != NULL) {
4736         BIO_free(bio);
4737       }
4738 
4739       print_basic_info = FALSE;
4740       break;
4741     }
4742 # endif
4743 
4744 # ifdef TLSEXT_TYPE_key_share
4745     case TLSEXT_TYPE_key_share:
4746       extension_name = "key share";
4747       break;
4748 # endif
4749 
4750 # ifdef TLSEXT_TYPE_renegotiate
4751     case TLSEXT_TYPE_renegotiate:
4752       extension_name = "renegotiation info";
4753       break;
4754 # endif
4755 
4756 # ifdef TLSEXT_TYPE_opaque_prf_input
4757     case TLSEXT_TYPE_opaque_prf_input:
4758       extension_name = "opaque PRF input";
4759       break;
4760 # endif
4761 
4762 # ifdef TLSEXT_TYPE_next_proto_neg
4763     case TLSEXT_TYPE_next_proto_neg:
4764       extension_name = "next protocol";
4765       break;
4766 # endif
4767 
4768 # ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
4769     case TLSEXT_TYPE_application_layer_protocol_negotiation:
4770       extension_name = "application layer protocol";
4771       break;
4772 # endif
4773 
4774 # ifdef TLSEXT_TYPE_padding
4775     case TLSEXT_TYPE_padding:
4776       extension_name = "TLS padding";
4777       break;
4778 # endif
4779 
4780 # ifdef TLSEXT_TYPE_early_data
4781     case TLSEXT_TYPE_early_data:
4782       extension_name = "early data";
4783       break;
4784 # endif
4785 
4786 # ifdef TLSEXT_TYPE_post_handshake_auth
4787     case TLSEXT_TYPE_post_handshake_auth:
4788       extension_name = "post handshake auth";
4789       break;
4790 # endif
4791 
4792     default:
4793       print_basic_info = TRUE;
4794       break;
4795   }
4796 
4797   if (print_basic_info == TRUE) {
4798     pr_trace_msg(trace_channel, 6,
4799       "[tls.tlsext] TLS %s extension \"%s\" (ID %d, %d %s)",
4800       server ? "server" : "client", extension_name, type, tlsext_datalen,
4801       tlsext_datalen != 1 ? "bytes" : "byte");
4802   }
4803 }
4804 #endif /* !OPENSSL_NO_TLSEXT */
4805 
4806 #if defined(PR_USE_OPENSSL_OCSP)
4807 static OCSP_RESPONSE *ocsp_send_request(pool *p, BIO *bio, const char *host,
4808     const char *uri, OCSP_REQUEST *req, unsigned int request_timeout) {
4809   int fd, res;
4810   OCSP_RESPONSE *resp = NULL;
4811   OCSP_REQ_CTX *ctx = NULL;
4812   const char *header_name, *header_value;
4813 
4814   res = BIO_get_fd(bio, &fd);
4815   if (res <= 0) {
4816     pr_trace_msg(trace_channel, 3,
4817       "error obtaining OCSP responder socket fd: %s", tls_get_errors());
4818     return NULL;
4819   }
4820 
4821   ctx = OCSP_sendreq_new(bio, (char *) uri, NULL, -1);
4822   if (ctx == NULL) {
4823     pr_trace_msg(trace_channel, 4,
4824       "error allocating OCSP request context: %s", tls_get_errors());
4825     return NULL;
4826   }
4827 
4828 # if OPENSSL_VERSION_NUMBER >= 0x10000001L
4829   header_name = "Host";
4830   header_value = host;
4831   res = OCSP_REQ_CTX_add1_header(ctx, header_name, header_value);
4832   if (res != 1) {
4833     pr_trace_msg(trace_channel, 4,
4834       "error adding '%s: %s' header to OCSP request context: %s", header_name,
4835       header_value, tls_get_errors());
4836     OCSP_REQ_CTX_free(ctx);
4837     return NULL;
4838   }
4839 
4840   header_name = "Accept";
4841   header_value = "application/ocsp-response";
4842   res = OCSP_REQ_CTX_add1_header(ctx, header_name, header_value);
4843   if (res != 1) {
4844     pr_trace_msg(trace_channel, 4,
4845       "error adding '%s: %s' header to OCSP request context: %s", header_name,
4846       header_value, tls_get_errors());
4847     OCSP_REQ_CTX_free(ctx);
4848     return NULL;
4849   }
4850 
4851   header_name = "User-Agent";
4852   header_value = "proftpd+" MOD_TLS_VERSION;
4853   res = OCSP_REQ_CTX_add1_header(ctx, header_name, header_value);
4854   if (res != 1) {
4855     pr_trace_msg(trace_channel, 4,
4856       "error adding '%s: %s' header to OCSP request context: %s", header_name,
4857       header_value, tls_get_errors());
4858     OCSP_REQ_CTX_free(ctx);
4859     return NULL;
4860   }
4861 
4862   /* If we are using nonces, then we need to explicitly request that no
4863    * caches along the way interfere.
4864    */
4865   if (!(tls_stapling_opts & TLS_STAPLING_OPT_NO_NONCE)) {
4866     header_name = "Pragma";
4867     header_value = "no-cache";
4868     res = OCSP_REQ_CTX_add1_header(ctx, header_name, header_value);
4869     if (res != 1) {
4870       pr_trace_msg(trace_channel, 4,
4871         "error adding '%s: %s' header to OCSP request context: %s", header_name,
4872         header_value, tls_get_errors());
4873       OCSP_REQ_CTX_free(ctx);
4874       return NULL;
4875     }
4876 
4877     header_name = "Cache-Control";
4878     header_value = "no-cache, no-store";
4879     res = OCSP_REQ_CTX_add1_header(ctx, header_name, header_value);
4880     if (res != 1) {
4881       pr_trace_msg(trace_channel, 4,
4882         "error adding '%s: %s' header to OCSP request context: %s", header_name,
4883         header_value, tls_get_errors());
4884       OCSP_REQ_CTX_free(ctx);
4885       return NULL;
4886     }
4887   }
4888 
4889   /* Only add the request after we've added our headers. */
4890   res = OCSP_REQ_CTX_set1_req(ctx, req);
4891   if (res != 1) {
4892     pr_trace_msg(trace_channel, 4,
4893       "error adding OCSP request to context: %s", tls_get_errors());
4894     OCSP_REQ_CTX_free(ctx);
4895     return NULL;
4896   }
4897 # endif /* OpenSSL-1.0.0 and later */
4898 
4899   while (TRUE) {
4900     fd_set fds;
4901     struct timeval tv;
4902 
4903     res = OCSP_sendreq_nbio(&resp, ctx);
4904     if (res != -1) {
4905       break;
4906     }
4907 
4908     if (request_timeout == 0) {
4909       break;
4910     }
4911 
4912     FD_ZERO(&fds);
4913     FD_SET(fd, &fds);
4914     tv.tv_usec = 0;
4915     tv.tv_sec = request_timeout;
4916 
4917     if (BIO_should_read(bio)) {
4918       res = select(fd + 1, (void *) &fds, NULL, NULL, &tv);
4919 
4920     } else if (BIO_should_write(bio)) {
4921       res = select(fd + 1, NULL, (void *) &fds, NULL, &tv);
4922 
4923     } else {
4924       pr_trace_msg(trace_channel, 3,
4925         "unexpected retry condition when talking to OCSP responder '%s%s'",
4926         host, uri);
4927       res = -1;
4928       break;
4929     }
4930 
4931     if (res == 0) {
4932       pr_trace_msg(trace_channel, 3,
4933          "timed out talking to OCSP responder '%s%s'", host, uri);
4934       errno = ETIMEDOUT;
4935       res = -1;
4936       break;
4937     }
4938   }
4939 
4940   OCSP_REQ_CTX_free(ctx);
4941 
4942   if (res) {
4943     if (tls_opts & TLS_OPT_ENABLE_DIAGS) {
4944       BIO *diags_bio;
4945 
4946       diags_bio = BIO_new(BIO_s_mem());
4947       if (diags_bio != NULL) {
4948         if (OCSP_RESPONSE_print(diags_bio, resp, 0) == 1) {
4949           char *data = NULL;
4950           long datalen = 0;
4951 
4952           datalen = BIO_get_mem_data(diags_bio, &data);
4953           if (data != NULL) {
4954             data[datalen] = '\0';
4955             tls_log("received OCSP response (%ld bytes):\n%s", datalen, data);
4956           }
4957         }
4958       }
4959 
4960       BIO_free(diags_bio);
4961     }
4962 
4963     return resp;
4964   }
4965 
4966   pr_trace_msg(trace_channel, 4,
4967     "error obtaining OCSP response from responder: %s", tls_get_errors());
4968   return NULL;
4969 }
4970 
4971 static X509 *ocsp_get_issuing_cert(pool *p, X509 *cert, SSL *ssl) {
4972   int res;
4973   X509 *issuer = NULL;
4974   SSL_CTX *ctx;
4975   X509_STORE *store;
4976   X509_STORE_CTX *store_ctx;
4977   STACK_OF(X509) *extra_certs = NULL;
4978 
4979   if (ssl == NULL) {
4980     pr_trace_msg(trace_channel, 4, "%s",
4981       "unable to get issuing cert: no TLS session provided");
4982     errno = EINVAL;
4983     return NULL;
4984   }
4985 
4986   ctx = SSL_get_SSL_CTX(ssl);
4987   if (ctx == NULL) {
4988     pr_trace_msg(trace_channel, 4,
4989       "no SSL_CTX found for TLS session: %s", tls_get_errors());
4990     errno = EINVAL;
4991     return NULL;
4992   }
4993 
4994   /* First look for the issuer in the CertificateChainFile certs, if any. */
4995 # if OPENSSL_VERSION_NUMBER >= 0x10001000L
4996   (void) SSL_CTX_get_extra_chain_certs(ctx, &extra_certs);
4997 # else
4998   extra_certs = ctx->extra_certs;
4999 # endif
5000 
5001   if (extra_certs != NULL &&
5002       sk_X509_num(extra_certs) > 0) {
5003     register int i;
5004 
5005     for (i = 0; i < sk_X509_num(extra_certs); i++) {
5006       X509 *extra_cert;
5007 
5008       extra_cert = sk_X509_value(extra_certs, i);
5009       if (X509_check_issued(extra_cert, cert) == X509_V_OK) {
5010         issuer = X509_dup(extra_cert);
5011         pr_trace_msg(trace_channel, 14, "found issuer %p for certificate",
5012           issuer);
5013 
5014         return issuer;
5015       }
5016     }
5017   }
5018 
5019   /* If not found, look in the trusted certs (CACertificateFile/Path). */
5020   store = SSL_CTX_get_cert_store(ctx);
5021   if (store == NULL) {
5022     pr_trace_msg(trace_channel, 4,
5023       "no certificate store found for SSL_CTX: %s", tls_get_errors());
5024 
5025     errno = EINVAL;
5026     return NULL;
5027   }
5028 
5029   store_ctx = X509_STORE_CTX_new();
5030   if (store_ctx == NULL) {
5031     pr_trace_msg(trace_channel, 4,
5032       "error allocating certificate store context: %s", tls_get_errors());
5033 
5034     errno = ENOMEM;
5035     return NULL;
5036   }
5037 
5038   res = X509_STORE_CTX_init(store_ctx, store, NULL, NULL);
5039   if (res != 1) {
5040     pr_trace_msg(trace_channel, 4,
5041       "error initializing certificate store context: %s", tls_get_errors());
5042     X509_STORE_CTX_free(store_ctx);
5043 
5044     errno = ENOMEM;
5045     return NULL;
5046   }
5047 
5048   res = X509_STORE_CTX_get1_issuer(&issuer, store_ctx, cert);
5049   if (res == -1) {
5050     pr_trace_msg(trace_channel, 4,
5051       "error finding issuing certificate: %s", tls_get_errors());
5052     X509_STORE_CTX_free(store_ctx);
5053 
5054     errno = EINVAL;
5055     return NULL;
5056   }
5057 
5058   if (res == 0) {
5059     pr_trace_msg(trace_channel, 4,
5060       "no issuing certificate found: %s", tls_get_errors());
5061     X509_STORE_CTX_free(store_ctx);
5062 
5063     errno = ENOENT;
5064     return NULL;
5065   }
5066 
5067   X509_STORE_CTX_free(store_ctx);
5068 
5069   pr_trace_msg(trace_channel, 14, "found issuer %p for certificate", issuer);
5070   return issuer;
5071 }
5072 
5073 static OCSP_REQUEST *ocsp_get_request(pool *p, X509 *cert, X509 *issuer) {
5074   OCSP_REQUEST *req = NULL;
5075   OCSP_CERTID *cert_id = NULL;
5076 
5077   req = OCSP_REQUEST_new();
5078   if (req == NULL) {
5079     pr_trace_msg(trace_channel, 4, "error allocating OCSP request: %s",
5080       tls_get_errors());
5081     return NULL;
5082   }
5083 
5084   cert_id = OCSP_cert_to_id(NULL, cert, issuer);
5085   if (cert_id == NULL) {
5086     pr_trace_msg(trace_channel, 4, "error obtaining ID for cert: %s",
5087       tls_get_errors());
5088     OCSP_REQUEST_free(req);
5089     return NULL;
5090   }
5091 
5092   if (OCSP_request_add0_id(req, cert_id) == NULL) {
5093     pr_trace_msg(trace_channel, 4, "error adding ID to OCSP request: %s",
5094       tls_get_errors());
5095     OCSP_CERTID_free(cert_id);
5096     OCSP_REQUEST_free(req);
5097     return NULL;
5098   }
5099 
5100   if (!(tls_stapling_opts & TLS_STAPLING_OPT_NO_NONCE)) {
5101     OCSP_request_add1_nonce(req, NULL, -1);
5102   }
5103 
5104   if (tls_opts & TLS_OPT_ENABLE_DIAGS) {
5105     BIO *diags_bio;
5106 
5107     diags_bio = BIO_new(BIO_s_mem());
5108     if (diags_bio != NULL) {
5109       if (OCSP_REQUEST_print(diags_bio, req, 0) == 1) {
5110         char *data = NULL;
5111         long datalen = 0;
5112 
5113         datalen = BIO_get_mem_data(diags_bio, &data);
5114         if (data != NULL) {
5115           data[datalen] = '\0';
5116           tls_log("sending OCSP request (%ld bytes):\n%s", datalen, data);
5117         }
5118       }
5119 
5120       BIO_free(diags_bio);
5121     }
5122   }
5123 
5124   return req;
5125 }
5126 
5127 static int ocsp_check_cert_status(pool *p, X509 *cert, X509 *issuer,
5128     OCSP_BASICRESP *basic_resp, int *ocsp_status, int *ocsp_reason) {
5129   int res, status, reason;
5130   OCSP_CERTID *cert_id = NULL;
5131   ASN1_GENERALIZEDTIME *this_update = NULL, *next_update = NULL,
5132     *revoked_at = NULL;
5133 
5134   cert_id = OCSP_cert_to_id(NULL, cert, issuer);
5135   if (cert_id == NULL) {
5136     int xerrno = errno;
5137 
5138     pr_trace_msg(trace_channel, 3,
5139       "error obtaining cert ID from basic OCSP response: %s", tls_get_errors());
5140 
5141     errno = xerrno;
5142     return -1;
5143   }
5144 
5145   res = OCSP_resp_find_status(basic_resp, cert_id, &status, &reason,
5146     &revoked_at, &this_update, &next_update);
5147   if (res != 1) {
5148     pr_trace_msg(trace_channel, 3,
5149       "error locating certificate status in OCSP response: %s",
5150       tls_get_errors());
5151 
5152     OCSP_CERTID_free(cert_id);
5153     errno = ENOENT;
5154     return -1;
5155   }
5156 
5157   OCSP_CERTID_free(cert_id);
5158 
5159   res = OCSP_check_validity(this_update, next_update,
5160     TLS_OCSP_RESP_MAX_AGE_SECS, -1);
5161   if (res != 1) {
5162     pr_trace_msg(trace_channel, 3,
5163       "failed time-based validity check of OCSP response: %s",
5164       tls_get_errors());
5165     errno = EINVAL;
5166     return -1;
5167   }
5168 
5169   /* Valid or not, we still want to cache this response, AND communicate
5170    * the certificate status, as is, backed to the client via the stapled
5171    * response.
5172    */
5173 
5174   pr_trace_msg(trace_channel, 8,
5175     "found certificate status '%s' in OCSP response",
5176     OCSP_cert_status_str(status));
5177   if (status == V_OCSP_CERTSTATUS_REVOKED) {
5178     if (reason != -1) {
5179       pr_trace_msg(trace_channel, 8, "revocation reason: %s",
5180         OCSP_crl_reason_str(reason));
5181     }
5182   }
5183 
5184   if (ocsp_status != NULL) {
5185     *ocsp_status = status;
5186   }
5187 
5188   if (ocsp_reason != NULL) {
5189     *ocsp_reason = reason;
5190   }
5191 
5192   return 0;
5193 }
5194 
5195 static int ocsp_check_response(pool *p, X509 *cert, X509 *issuer, SSL *ssl,
5196     OCSP_REQUEST *req, OCSP_RESPONSE *resp) {
5197   int flags = 0, res = 0, resp_status;
5198   OCSP_BASICRESP *basic_resp = NULL;
5199   SSL_CTX *ctx = NULL;
5200   X509_STORE *store = NULL;
5201   STACK_OF(X509) *chain = NULL;
5202 
5203   ctx = SSL_get_SSL_CTX(ssl);
5204   if (ctx == NULL) {
5205     pr_trace_msg(trace_channel, 4,
5206       "no SSL_CTX found for TLS session: %s", tls_get_errors());
5207 
5208     errno = EINVAL;
5209     return -1;
5210   }
5211 
5212   store = SSL_CTX_get_cert_store(ctx);
5213   if (store == NULL) {
5214     pr_trace_msg(trace_channel, 4,
5215       "no certificate store found for SSL_CTX: %s", tls_get_errors());
5216 
5217     errno = EINVAL;
5218     return -1;
5219   }
5220 
5221   basic_resp = OCSP_response_get1_basic(resp);
5222   if (basic_resp == NULL) {
5223     int xerrno = errno;
5224 
5225     pr_trace_msg(trace_channel, 3,
5226       "error getting basic OCSP response: %s", tls_get_errors());
5227 
5228     errno = xerrno;
5229     return -1;
5230   }
5231 
5232   if (!(tls_stapling_opts & TLS_STAPLING_OPT_NO_NONCE)) {
5233     res = OCSP_check_nonce(req, basic_resp);
5234     if (res < 0) {
5235       pr_trace_msg(trace_channel, 1,
5236         "WARNING: OCSP response is missing request nonce");
5237 
5238     } else if (res == 0) {
5239       pr_trace_msg(trace_channel, 3,
5240         "error verifying OCSP response nonce: %s", tls_get_errors());
5241 
5242       OCSP_BASICRESP_free(basic_resp);
5243       errno = EINVAL;
5244       return -1;
5245     }
5246   }
5247 
5248   chain = sk_X509_new_null();
5249   if (chain != NULL) {
5250     STACK_OF(X509) *extra_certs = NULL;
5251 
5252     sk_X509_push(chain, issuer);
5253 
5254 # if OPENSSL_VERSION_NUMBER >= 0x10001000L
5255     SSL_CTX_get_extra_chain_certs(ctx, &extra_certs);
5256 # else
5257     extra_certs = ctx->extra_certs;
5258 # endif
5259 
5260     if (extra_certs != NULL) {
5261       register int i;
5262 
5263       for (i = 0; i < sk_X509_num(extra_certs); i++) {
5264         sk_X509_push(chain, sk_X509_value(extra_certs, i));
5265       }
5266     }
5267   }
5268 
5269   flags = OCSP_TRUSTOTHER;
5270   if (tls_stapling_opts & TLS_STAPLING_OPT_NO_VERIFY) {
5271     flags = OCSP_NOVERIFY;
5272   }
5273 
5274   res = OCSP_basic_verify(basic_resp, chain, store, flags);
5275   if (res != 1) {
5276     pr_trace_msg(trace_channel, 3,
5277       "error verifying basic OCSP response data: %s", tls_get_errors());
5278 
5279     OCSP_BASICRESP_free(basic_resp);
5280 
5281     if (chain != NULL) {
5282       sk_X509_free(chain);
5283     }
5284 
5285     errno = EINVAL;
5286     return -1;
5287   }
5288 
5289   if (chain != NULL) {
5290     sk_X509_free(chain);
5291   }
5292 
5293   /* Now that we have verified the response, we can check the response status.
5294    * If we only looked at the status first, then a malicious responder
5295    * could be tricking us, e.g.:
5296    *
5297    *  http://www.thoughtcrime.org/papers/ocsp-attack.pdf
5298    */
5299 
5300   resp_status = OCSP_response_status(resp);
5301   if (resp_status != OCSP_RESPONSE_STATUS_SUCCESSFUL) {
5302     pr_trace_msg(trace_channel, 3,
5303       "OCSP response not successful: %s (%d)",
5304       OCSP_response_status_str(resp_status), resp_status);
5305 
5306     OCSP_BASICRESP_free(basic_resp);
5307     errno = EINVAL;
5308     return -1;
5309   }
5310 
5311   res = ocsp_check_cert_status(p, cert, issuer, basic_resp, NULL, NULL);
5312   OCSP_BASICRESP_free(basic_resp);
5313 
5314   return res;
5315 }
5316 
5317 static int ocsp_connect(pool *p, BIO *bio, unsigned int request_timeout) {
5318   int fd, res;
5319 
5320   if (request_timeout > 0) {
5321     BIO_set_nbio(bio, 1);
5322   }
5323 
5324   res = BIO_do_connect(bio);
5325   if (res <= 0 &&
5326       (request_timeout == 0 || !BIO_should_retry(bio))) {
5327     pr_trace_msg(trace_channel, 4,
5328       "error connecting to OCSP responder: %s", tls_get_errors());
5329     errno = EPERM;
5330     return -1;
5331   }
5332 
5333   if (BIO_get_fd(bio, &fd) < 0) {
5334     pr_trace_msg(trace_channel, 3,
5335       "error obtaining OCSP responder socket fd: %s", tls_get_errors());
5336     errno = EINVAL;
5337     return -1;
5338   }
5339 
5340   if (request_timeout > 0 &&
5341       res <= 0) {
5342     struct timeval tv;
5343     fd_set fds;
5344 
5345     FD_ZERO(&fds);
5346     FD_SET(fd, &fds);
5347     tv.tv_usec = 0;
5348     tv.tv_sec = request_timeout;
5349     res = select(fd + 1, NULL, (void *) &fds, NULL, &tv);
5350     if (res == 0) {
5351       errno = ETIMEDOUT;
5352       return -1;
5353     }
5354   }
5355 
5356   return 0;
5357 }
5358 
5359 static OCSP_RESPONSE *ocsp_request_response(pool *p, X509 *cert, SSL *ssl,
5360     const char *url, unsigned int request_timeout) {
5361   BIO *bio;
5362   SSL_CTX *ctx = NULL;
5363   X509 *issuer = NULL;
5364   char *host = NULL, *port = NULL, *uri = NULL;
5365   int res, use_ssl = FALSE;
5366   OCSP_REQUEST *req = NULL;
5367   OCSP_RESPONSE *resp = NULL;
5368 
5369   issuer = ocsp_get_issuing_cert(p, cert, ssl);
5370   if (issuer == NULL) {
5371     return NULL;
5372   }
5373 
5374   /* Current OpenSSL implementation of OCSP_parse_url() guarantees that
5375    * host, port, and uri will never be NULL.  Nice.
5376    */
5377   res = OCSP_parse_url((char *) url, &host, &port, &uri, &use_ssl);
5378   if (res != 1) {
5379     pr_trace_msg(trace_channel, 4, "error parsing OCSP URL '%s': %s", url,
5380       tls_get_errors());
5381     X509_free(issuer);
5382     return NULL;
5383   }
5384 
5385   req = ocsp_get_request(p, cert, issuer);
5386   if (req == NULL) {
5387     X509_free(issuer);
5388     OCSP_REQUEST_free(req);
5389     OPENSSL_free(host);
5390     OPENSSL_free(port);
5391     OPENSSL_free(uri);
5392     return NULL;
5393   }
5394 
5395   pr_trace_msg(trace_channel, 9,
5396     "parsed OCSP URL '%s' to get host '%s', port '%s', URI '%s'%s",
5397     url, host, port, uri, use_ssl ? ", using TLS" : "");
5398 
5399   bio = BIO_new_connect(host);
5400   if (bio == NULL) {
5401     pr_trace_msg(trace_channel, 4, "error allocating connect BIO: %s",
5402       tls_get_errors());
5403 
5404     X509_free(issuer);
5405     OCSP_REQUEST_free(req);
5406     OPENSSL_free(host);
5407     OPENSSL_free(port);
5408     OPENSSL_free(uri);
5409     return NULL;
5410   }
5411 
5412   BIO_set_conn_port(bio, port);
5413 
5414   if (use_ssl) {
5415     BIO *ssl_bio;
5416 
5417     ctx = SSL_CTX_new(SSLv23_client_method());
5418     if (ctx == NULL) {
5419       pr_trace_msg(trace_channel, 4, "error allocating SSL context: %s",
5420         tls_get_errors());
5421 
5422       X509_free(issuer);
5423       OCSP_REQUEST_free(req);
5424       BIO_free_all(bio);
5425       OPENSSL_free(host);
5426       OPENSSL_free(port);
5427       OPENSSL_free(uri);
5428       return NULL;
5429     }
5430 
5431     SSL_CTX_set_mode(ctx, SSL_MODE_AUTO_RETRY);
5432     ssl_bio = BIO_new_ssl(ctx, 1);
5433     bio = BIO_push(ssl_bio, bio);
5434   }
5435 
5436   res = ocsp_connect(p, bio, request_timeout);
5437   if (res < 0) {
5438     int xerrno = errno;
5439 
5440     pr_trace_msg(trace_channel, 3,
5441       "error connecting to OCSP responder %s:%s: %s", host, port,
5442       strerror(xerrno));
5443 
5444     X509_free(issuer);
5445     OCSP_REQUEST_free(req);
5446     BIO_free_all(bio);
5447     OPENSSL_free(host);
5448     OPENSSL_free(port);
5449     OPENSSL_free(uri);
5450 
5451     errno = xerrno;
5452     return NULL;
5453   }
5454 
5455   resp = ocsp_send_request(p, bio, host, uri, req, request_timeout);
5456 
5457   OPENSSL_free(host);
5458   OPENSSL_free(port);
5459   OPENSSL_free(uri);
5460 
5461   if (ctx != NULL) {
5462     SSL_CTX_free(ctx);
5463   }
5464 
5465   if (bio != NULL) {
5466     BIO_free_all(bio);
5467   }
5468 
5469   if (resp == NULL) {
5470     X509_free(issuer);
5471     OCSP_REQUEST_free(req);
5472     return NULL;
5473   }
5474 
5475   if (ocsp_check_response(p, cert, issuer, ssl, req, resp) < 0) {
5476     if (errno != ENOSYS) {
5477       X509_free(issuer);
5478       OCSP_REQUEST_free(req);
5479       OCSP_RESPONSE_free(resp);
5480       errno = EINVAL;
5481       return NULL;
5482     }
5483   }
5484 
5485   X509_free(issuer);
5486   OCSP_REQUEST_free(req);
5487   return resp;
5488 }
5489 
5490 #if OPENSSL_VERSION_NUMBER < 0x10002000L || \
5491     defined(HAVE_LIBRESSL)
5492 /* We need to provide our own backport of the ASN1_TIME_diff() function. */
5493 static time_t ASN1_TIME_seconds(const ASN1_TIME *a) {
5494   static const int min[9] = { 0, 0, 1, 1, 0, 0, 0, 0, 0 };
5495   static const int max[9] = { 99, 99, 12, 31, 23, 59, 59, 12, 59 };
5496   time_t t = 0;
5497   char *text;
5498   int text_len;
5499   int i, j, n;
5500   unsigned int nyears, nmons, nhours, nmins, nsecs;
5501 
5502   if (a->type != V_ASN1_GENERALIZEDTIME) {
5503     return 0;
5504   }
5505 
5506   text_len = a->length;
5507   text = (char *) a->data;
5508 
5509   /* GENERALIZEDTIME is similar to UTCTIME except the year is represented
5510    * as YYYY. This stuff treats everything as a two digit field so make
5511    * first two fields 00 to 99
5512    */
5513 
5514   if (text_len < 13) {
5515     return 0;
5516   }
5517 
5518   nyears = nmons = nhours = nmins = nsecs = 0;
5519 
5520   for (i = 0, j = 0; i < 7; i++) {
5521     if (i == 6 &&
5522         (text[j] == 'Z' ||
5523          text[j] == '+' ||
5524          text[j] == '-')) {
5525       i++;
5526       break;
5527     }
5528 
5529     if (text[j] < '0' ||
5530         text[j] > '9') {
5531       return 0;
5532     }
5533 
5534     n = text[j] - '0';
5535     if (++j > text_len) {
5536       return 0;
5537     }
5538 
5539     if (text[j] < '0' ||
5540         text[j] > '9') {
5541       return 0;
5542     }
5543 
5544     n = (n * 10) + (text[j] - '0');
5545     if (++j > text_len) {
5546       return 0;
5547     }
5548 
5549     if (n < min[i] ||
5550         n > max[i]) {
5551       return 0;
5552     }
5553 
5554     switch (i) {
5555       case 0:
5556         /* Years */
5557         nyears = (n * 100);
5558         break;
5559 
5560       case 1:
5561         /* Years */
5562         nyears += n;
5563         break;
5564 
5565       case 2:
5566         /* Month */
5567         nmons = n - 1;
5568         break;
5569 
5570       case 3:
5571         /* Day of month; ignored */
5572         break;
5573 
5574       case 4:
5575         /* Hours */
5576         nhours = n;
5577         break;
5578 
5579       case 5:
5580         /* Minutes */
5581         nmins = n;
5582         break;
5583 
5584       case 6:
5585         /* Seconds */
5586         nsecs = n;
5587         break;
5588     }
5589   }
5590 
5591   /* Yes, this is not calendrical accurate.  It only needs to be a good
5592    * enough estimation, as it is used (currently) only for determining the
5593    * validity window of an OCSP request (in seconds).
5594    */
5595   t = (nyears * 365 * 86400) + (nmons * 30 * 86400) * (nhours * 3600) + nsecs;
5596 
5597   /* Optional fractional seconds: decimal point followed by one or more
5598    * digits.
5599    */
5600   if (text[j] == '.') {
5601     if (++j > text_len) {
5602       return 0;
5603     }
5604 
5605     i = j;
5606 
5607     while (text[j] >= '0' &&
5608            text[j] <= '9' &&
5609            j <= text_len) {
5610       j++;
5611     }
5612 
5613     /* Must have at least one digit after decimal point */
5614     if (i == j) {
5615       return 0;
5616     }
5617   }
5618 
5619   if (text[j] == 'Z') {
5620     j++;
5621 
5622   } else if (text[j] == '+' ||
5623              text[j] == '-') {
5624     int offsign, offset = 0;
5625 
5626     offsign = text[j] == '-' ? -1 : 1;
5627     j++;
5628 
5629     if (j + 4 > text_len) {
5630       return 0;
5631     }
5632 
5633     for (i = 7; i < 9; i++) {
5634       if (text[j] < '0' ||
5635           text[j] > '9') {
5636         return 0;
5637       }
5638 
5639       n = text[j] - '0';
5640       j++;
5641 
5642       if (text[j] < '0' ||
5643           text[j] > '9') {
5644         return 0;
5645       }
5646 
5647       n = (n * 10) + text[j] - '0';
5648 
5649       if (n < min[i] ||
5650           n > max[i]) {
5651         return 0;
5652       }
5653 
5654       if (i == 7) {
5655         offset = n * 3600;
5656 
5657       } else if (i == 8) {
5658         offset += n * 60;
5659       }
5660 
5661       j++;
5662     }
5663 
5664     if (offset > 0) {
5665       t += (offset * offsign);
5666     }
5667 
5668   } else if (text[j]) {
5669     /* Missing time zone information. */
5670     return 0;
5671   }
5672 
5673   return t;
5674 }
5675 
5676 static int ASN1_TIME_diff(int *pday, int *psec, const ASN1_TIME *from,
5677     const ASN1_TIME *to) {
5678   time_t from_secs, to_secs, diff_secs;
5679   long diff_days;
5680 
5681   from_secs = ASN1_TIME_seconds(from);
5682   if (from_secs == 0) {
5683     return 0;
5684   }
5685 
5686   to_secs = ASN1_TIME_seconds(to);
5687   if (to_secs == 0) {
5688     return 0;
5689   }
5690 
5691   if (to_secs > from_secs) {
5692     diff_secs = to_secs - from_secs;
5693 
5694   } else {
5695     diff_secs = from_secs - to_secs;
5696   }
5697 
5698   /* The ASN1_TIME_diff() API in OpenSSL-1.0.2+ offers days and seconds,
5699    * possibly to handle LARGE time differences without overflowing the data
5700    * type for seconds.  So we do the same.
5701    */
5702 
5703   diff_days = diff_secs % 86400;
5704   diff_secs -= (diff_days * 86400);
5705 
5706   if (pday) {
5707     *pday = (int) diff_days;
5708   }
5709 
5710   if (psec) {
5711     *psec = diff_secs;
5712   }
5713 
5714   return 1;
5715 }
5716 #endif /* Before OpenSSL-1.0.2, or libressl */
5717 
5718 static int ocsp_stale_response(pool *p, OCSP_RESPONSE *resp, X509 *cert,
5719     SSL *ssl, time_t age, time_t *expired) {
5720   int res = -1, ocsp_status, stale = FALSE;
5721 
5722   ocsp_status = OCSP_response_status(resp);
5723   *expired = 0;
5724 
5725   /* If we received a SUCCESSFUL response from the OCSP responder, then
5726    * we consider the response to be stale starting at halfway through its
5727    * validity period (and expired if after the validity period).  Otherwise,
5728    * we expire the cached entry after 5 minutes (hardcoded).
5729    */
5730 
5731   if (ocsp_status == OCSP_RESPONSE_STATUS_SUCCESSFUL) {
5732     OCSP_BASICRESP *basic_resp = NULL;
5733 
5734     basic_resp = OCSP_response_get1_basic(resp);
5735     if (basic_resp != NULL) {
5736       X509 *issuer;
5737 
5738       issuer = ocsp_get_issuing_cert(p, cert, ssl);
5739       if (issuer != NULL) {
5740         OCSP_CERTID *cert_id = NULL;
5741 
5742         cert_id = OCSP_cert_to_id(NULL, cert, issuer);
5743         if (cert_id != NULL) {
5744           ASN1_GENERALIZEDTIME *this_update = NULL, *next_update = NULL;
5745 
5746           res = OCSP_resp_find_status(basic_resp, cert_id, NULL, NULL, NULL,
5747             &this_update, &next_update);
5748           if (res == 1) {
5749             time_t now;
5750 
5751             now = time(NULL);
5752 
5753             /* If we have passed the nextUpdate time, we have expired. */
5754             if (next_update != NULL) {
5755               res = X509_cmp_time(next_update, &now);
5756               if (res < 0) {
5757                 pr_trace_msg(trace_channel, 17,
5758                   "cached OCSP response has EXPIRED");
5759                 *expired = now;
5760                 stale = TRUE;
5761 
5762               } else {
5763                 int ndays = 0, nsecs = 0;
5764 
5765                 /* Start requesting fresh responses halfway through the validity
5766                  * period:
5767                  *
5768                  *  now > (thisUpdate + ((nextUpdate - thisUpdate) / 2))
5769                  *
5770                  * or, rephrased slightly differently:
5771                  *
5772                  *  now - ((nextUpdate - thisUpdate) / 2) > thisUpdate
5773                  */
5774 
5775                 res = ASN1_TIME_diff(&ndays, &nsecs, this_update, next_update);
5776                 if (res == 1) {
5777                   int validity_secs;
5778                   time_t refresh_ts;
5779 
5780                   validity_secs = (ndays * 86400) + nsecs;
5781                   refresh_ts = now - (validity_secs / 2);
5782 
5783                   res = X509_cmp_time(this_update, &refresh_ts);
5784                   if (res < 0) {
5785                     pr_trace_msg(trace_channel, 17,
5786                       "cached OCSP response is stale");
5787                     stale = TRUE;
5788                   }
5789 
5790                 } else {
5791                   pr_trace_msg(trace_channel, 3, "error computing difference "
5792                     "in OCSP response timestamps: %s", tls_get_errors());
5793                 }
5794               }
5795 
5796             } else {
5797               /* If the OCSP response has no nextUpdate time, then we assume
5798                * it to be stale after one hour (hardcoded).
5799                */
5800               if (age > 3600) {
5801                 stale = TRUE;
5802               }
5803             }
5804           }
5805 
5806           OCSP_CERTID_free(cert_id);
5807         }
5808 
5809         X509_free(issuer);
5810       }
5811 
5812       OCSP_BASICRESP_free(basic_resp);
5813 
5814     } else {
5815       if (age > 300) {
5816         stale = TRUE;
5817       }
5818     }
5819 
5820   } else {
5821     if (age > 300) {
5822       stale = TRUE;
5823     }
5824   }
5825 
5826   if (stale == TRUE) {
5827     pr_trace_msg(trace_channel, 8,
5828       "cached %s OCSP response is %s", OCSP_response_status_str(ocsp_status),
5829       *expired > 0 ? "EXPIRED" : "stale");
5830     return 0;
5831   }
5832 
5833   return -1;
5834 }
5835 
5836 static OCSP_RESPONSE *ocsp_get_cached_response(pool *p,
5837     const char *fingerprint, X509 *cert, SSL *ssl, int *stale) {
5838   OCSP_RESPONSE *resp = NULL;
5839   time_t cache_age = 0, resp_age = 0;
5840   int res;
5841 
5842   if (tls_ocsp_cache == NULL) {
5843     errno = ENOSYS;
5844     return NULL;
5845   }
5846 
5847   resp = (tls_ocsp_cache->get)(tls_ocsp_cache, fingerprint, &resp_age);
5848   if (resp != NULL) {
5849     time_t now = 0;
5850 
5851     time(&now);
5852     cache_age = now - resp_age;
5853     pr_trace_msg(trace_channel, 9,
5854       "found cached OCSP response for fingerprint '%s': %lu %s old",
5855       fingerprint, (unsigned long) cache_age, cache_age != 1 ? "secs" : "sec");
5856   }
5857 
5858   if (resp != NULL) {
5859     time_t expired = 0;
5860 
5861     res = ocsp_stale_response(p, resp, cert, ssl, cache_age, &expired);
5862     if (expired > 0) {
5863       /* If the response has expired, we need to delete it. */
5864       pr_trace_msg(trace_channel, 5,
5865         "cached OCSP response for fingerprint '%s' expired at %s",
5866         fingerprint, pr_strtime3(p, expired, TRUE));
5867       res = (tls_ocsp_cache->delete)(tls_ocsp_cache, fingerprint);
5868       if (res < 0) {
5869         pr_trace_msg(trace_channel, 3,
5870           "error deleting expired OCSP response from '%s' cache for "
5871           "fingerprint '%s': %s", tls_ocsp_cache->cache_name, fingerprint,
5872           strerror(errno));
5873       }
5874 
5875       OCSP_RESPONSE_free(resp);
5876       resp = NULL;
5877       errno = ENOENT;
5878 
5879     } else {
5880       if (res == 0) {
5881         *stale = TRUE;
5882 
5883       } else {
5884         *stale = FALSE;
5885       }
5886     }
5887 
5888   } else {
5889     int xerrno = errno;
5890 
5891     pr_trace_msg(trace_channel, 3,
5892       "error retrieving OCSP response from '%s' cache for "
5893       "fingerprint '%s': %s", tls_ocsp_cache->cache_name, fingerprint,
5894       strerror(xerrno));
5895 
5896     errno = xerrno;
5897   }
5898 
5899   return resp;
5900 }
5901 
5902 static int ocsp_add_cached_response(pool *p, const char *fingerprint,
5903     OCSP_RESPONSE *resp) {
5904   int res;
5905   time_t resp_age = 0;
5906 
5907   if (fingerprint == NULL ||
5908       tls_ocsp_cache == NULL) {
5909     errno = ENOSYS;
5910     return -1;
5911   }
5912 
5913   /* Cache this fake response, so that we don't have to keep redoing this
5914    * for a short amount of time (e.g. 5 minutes).
5915    */
5916   time(&resp_age);
5917   res = (tls_ocsp_cache->add)(tls_ocsp_cache, fingerprint, resp, resp_age);
5918   if (res < 0) {
5919     int xerrno = errno;
5920 
5921     pr_trace_msg(trace_channel, 3,
5922       "error adding OCSP response to '%s' cache for fingerprint '%s': %s",
5923       tls_ocsp_cache->cache_name, fingerprint, strerror(xerrno));
5924 
5925     errno = xerrno;
5926 
5927   } else {
5928     pr_trace_msg(trace_channel, 15,
5929       "added OCSP response to '%s' cache for fingerprint '%s'",
5930       tls_ocsp_cache->cache_name, fingerprint);
5931   }
5932 
5933   return res;
5934 }
5935 
5936 static int tls_feature_cmp(ASN1_STRING *str, void *feat_data,
5937     size_t feat_datasz) {
5938   int is_feat = FALSE, res;
5939   ASN1_STRING *feat;
5940 
5941   feat = ASN1_STRING_type_new(V_ASN1_OCTET_STRING);
5942   ASN1_STRING_set(feat, feat_data, feat_datasz);
5943 
5944 #if OPENSSL_VERSION_NUMBER >= 0x10100000L
5945   res = ASN1_STRING_cmp(str, feat);
5946 #else
5947   res = M_ASN1_OCTET_STRING_cmp(str, feat);
5948 #endif /* Before OpenSSL-1.1.0, or libressl */
5949 
5950   if (res == 0) {
5951     is_feat = TRUE;
5952   }
5953   ASN1_STRING_free(feat);
5954 
5955   return is_feat;
5956 }
5957 
5958 static int tls_cert_must_staple(X509 *cert, int *v2) {
5959   register int i;
5960   int ext_count = 0, must_staple = FALSE;
5961 
5962 #if OPENSSL_VERSION_NUMBER >= 0x10100000L && \
5963     !defined(HAVE_LIBRESSL)
5964   ext_count = X509_get_ext_count(cert);
5965 #else
5966   X509_CINF *ci;
5967   STACK_OF(X509_EXTENSION) *exts;
5968 
5969   ci = cert->cert_info;
5970   if (ci == NULL) {
5971     return FALSE;
5972   }
5973 
5974   exts = ci->extensions;
5975   ext_count = sk_X509_EXTENSION_num(exts);
5976 #endif /* Before OpenSSL-1.1.0, or libressl */
5977 
5978   for (i = 0; i < ext_count; i++) {
5979     char buf[1024];
5980     X509_EXTENSION *ext;
5981     ASN1_OBJECT *obj;
5982 
5983 #if OPENSSL_VERSION_NUMBER >= 0x10100000L && \
5984     !defined(HAVE_LIBRESSL)
5985     ext = X509_get_ext(cert, i);
5986 #else
5987     ext = sk_X509_EXTENSION_value(exts, i);
5988 #endif /* Before OpenSSL-1.1.0, or libressl */
5989 
5990     obj = X509_EXTENSION_get_object(ext);
5991     memset(buf, '\0', sizeof(buf));
5992     OBJ_obj2txt(buf, sizeof(buf)-1, obj, 1);
5993 
5994     /* Double-check that the OID is that of the "TLS Feature" extension. */
5995     if (strcmp(buf, TLS_X509V3_TLS_FEAT_OID_TEXT) == 0) {
5996       char status_request[] = TLS_X509V3_TLS_FEAT_STATUS_REQUEST;
5997       ASN1_OCTET_STRING *value;
5998 
5999 #if OPENSSL_VERSION_NUMBER >= 0x10100000L && \
6000     !defined(HAVE_LIBRESSL)
6001       value = X509_EXTENSION_get_data(ext);
6002 #else
6003       value = ext->value;
6004 #endif /* Before OpenSSL-1.1.0, or libressl */
6005 
6006       /* Is the value of this extension the "status_request" value? */
6007       must_staple = tls_feature_cmp(value, status_request, 5);
6008       if (must_staple != TRUE) {
6009         char status_request_v2[] = TLS_X509V3_TLS_FEAT_STATUS_REQUEST_V2;
6010 
6011         /* Is the value of this extension the "status_request_v2" value? */
6012         must_staple = tls_feature_cmp(value, status_request_v2, 5);
6013         if (must_staple == TRUE) {
6014           *v2 = TRUE;
6015         }
6016       }
6017     }
6018   }
6019 
6020   return must_staple;
6021 }
6022 
6023 static OCSP_RESPONSE *ocsp_get_response(pool *p, SSL *ssl) {
6024   X509 *cert;
6025   const char *fingerprint = NULL;
6026   OCSP_RESPONSE *resp = NULL, *cached_resp = NULL;
6027   int stale_cache = FALSE, use_fake_trylater = FALSE;
6028 
6029   /* We need to find a cached OCSP response for the server cert in question,
6030    * thus we need to find out which server cert is used for this session.
6031    */
6032   cert = SSL_get_certificate(ssl);
6033   if (cert != NULL) {
6034     fingerprint = tls_get_fingerprint(p, cert);
6035     if (fingerprint != NULL) {
6036       pr_trace_msg(trace_channel, 3,
6037         "using fingerprint '%s' for server cert", fingerprint);
6038       if (tls_ocsp_cache != NULL) {
6039         cached_resp = ocsp_get_cached_response(p, fingerprint, cert, ssl,
6040           &stale_cache);
6041         if (cached_resp != NULL) {
6042           if (tls_opts & TLS_OPT_ENABLE_DIAGS) {
6043             BIO *diags_bio;
6044 
6045             diags_bio = BIO_new(BIO_s_mem());
6046             if (diags_bio != NULL) {
6047               if (OCSP_RESPONSE_print(diags_bio, cached_resp, 0) == 1) {
6048                 char *data = NULL;
6049                 long datalen = 0;
6050 
6051                 datalen = BIO_get_mem_data(diags_bio, &data);
6052                 if (data != NULL) {
6053                   data[datalen] = '\0';
6054                   tls_log("cached OCSP response (%ld bytes):\n%s", datalen,
6055                     data);
6056                 }
6057               }
6058             }
6059 
6060             BIO_free(diags_bio);
6061           }
6062 
6063           resp = cached_resp;
6064 
6065         } else {
6066           int xerrno = errno;
6067 
6068           pr_trace_msg(trace_channel, 17,
6069             "no cached OCSP response found in '%s' cache for "
6070             "fingerprint '%s': %s", tls_ocsp_cache->cache_name, fingerprint,
6071             strerror(errno));
6072 
6073           errno = xerrno;
6074         }
6075 
6076       } else {
6077         /* No TLSStaplingCache configured. */
6078         pr_trace_msg(trace_channel, 17,
6079           "no cached OCSP response found (TLSStaplingCache not configured)");
6080         errno = ENOENT;
6081       }
6082 
6083       if (cached_resp == NULL ||
6084           stale_cache == TRUE) {
6085         int xerrno = errno;
6086         OCSP_RESPONSE *fresh_resp = NULL;
6087 
6088         if (xerrno == ENOENT ||
6089             stale_cache == TRUE) {
6090           const char *ocsp_url;
6091 
6092           if (tls_stapling_responder == NULL) {
6093             ocsp_url = ocsp_get_responder_url(p, cert);
6094             if (ocsp_url != NULL) {
6095               pr_trace_msg(trace_channel, 8,
6096                 "found OCSP responder URL '%s' in certificate "
6097                 "(fingerprint '%s')", ocsp_url, fingerprint);
6098 
6099             } else {
6100               pr_trace_msg(trace_channel, 8,
6101                 "no OCSP responder URL found in certificate "
6102                 "(fingerprint '%s')", fingerprint);
6103             }
6104 
6105           } else {
6106             ocsp_url = tls_stapling_responder;
6107             pr_trace_msg(trace_channel, 8,
6108               "using configured OCSP responder URL '%s'", ocsp_url);
6109           }
6110 
6111           if (ocsp_url != NULL) {
6112             fresh_resp = ocsp_request_response(p, cert, ssl, ocsp_url,
6113               tls_stapling_timeout);
6114             if (fresh_resp != NULL) {
6115               resp = fresh_resp;
6116 
6117               /* If our previously cached response was stale, delete it so
6118                * that we can cache our new one.
6119                */
6120               if (stale_cache == TRUE) {
6121                 int res;
6122 
6123                 res = (tls_ocsp_cache->delete)(tls_ocsp_cache, fingerprint);
6124                 if (res < 0) {
6125                   pr_trace_msg(trace_channel, 3,
6126                     "error deleting OCSP response from '%s' cache for "
6127                     "fingerprint '%s': %s", tls_ocsp_cache->cache_name,
6128                     fingerprint, strerror(errno));
6129                 }
6130 
6131                 OCSP_RESPONSE_free(cached_resp);
6132                 cached_resp = NULL;
6133               }
6134             }
6135 
6136           } else {
6137             pr_trace_msg(trace_channel, 5,
6138               "no OCSP responder URL found in certificate (fingerprint '%s')",
6139               fingerprint);
6140           }
6141 
6142         } else {
6143           pr_trace_msg(trace_channel, 5,
6144             "no cached OCSP response found: %s", strerror(xerrno));
6145         }
6146       }
6147     }
6148 
6149   } else {
6150     pr_trace_msg(trace_channel, 8, "%s",
6151       "no server certificate found for TLS session");
6152   }
6153 
6154   if (resp == NULL) {
6155     use_fake_trylater = TRUE;
6156 
6157     /* No proper OCSP response found for stapling; provide a fake tryLater
6158      * response as a fallback.  However, if the NoFakeTryLater
6159      * TLSStaplingOption is used, we omit this fake response; some
6160      * implementation e.g. GnuTLS reject/choke on these fake responses.
6161      */
6162     if (tls_stapling_opts & TLS_STAPLING_OPT_NO_FAKE_TRY_LATER) {
6163       use_fake_trylater = FALSE;
6164     }
6165 
6166     /* On the other hand, if the server certificate uses the "must staple"
6167      * X509v3 feature, then we MUST provide an OCSP response, even a fake one.
6168      */
6169     if (cert != NULL) {
6170       int must_staple, is_v2 = FALSE;
6171 
6172       must_staple = tls_cert_must_staple(cert, &is_v2);
6173       if (must_staple == TRUE) {
6174         pr_trace_msg(trace_channel, 8,
6175           "found status_request%s 'must staple' TLS feature in certificate "
6176           "(fingerprint '%s')", is_v2 ? "_v2" : "", fingerprint);
6177         use_fake_trylater = TRUE;
6178       }
6179     }
6180   }
6181 
6182   if (use_fake_trylater) {
6183     pr_trace_msg(trace_channel, 5, "returning fake tryLater OCSP response");
6184 
6185     /* If we have not found an OCSP response, then fall back to using
6186      * a fake "tryLater" response.
6187      */
6188     resp = OCSP_response_create(OCSP_RESPONSE_STATUS_TRYLATER, NULL);
6189     if (resp == NULL) {
6190       pr_trace_msg(trace_channel, 1,
6191         "error allocating fake 'tryLater' OCSP response: %s", tls_get_errors());
6192       return NULL;
6193     }
6194   }
6195 
6196   /* If this response is not the one we just pulled from the cache, then
6197    * add it.
6198    */
6199   if (resp != cached_resp) {
6200     if (ocsp_add_cached_response(p, fingerprint, resp) < 0) {
6201       if (errno != ENOSYS) {
6202         pr_trace_msg(trace_channel, 3,
6203           "error caching OCSP response: %s", strerror(errno));
6204       }
6205     }
6206   }
6207 
6208   return resp;
6209 }
6210 
6211 static int tls_ocsp_cb(SSL *ssl, void *user_data) {
6212   OCSP_RESPONSE *resp;
6213   int resp_derlen, reused;
6214   unsigned char *resp_der = NULL;
6215   pool *ocsp_pool;
6216 
6217   if (tls_stapling == FALSE) {
6218     /* OCSP stapling disabled; do nothing. */
6219     return SSL_TLSEXT_ERR_NOACK;
6220   }
6221 
6222   reused = SSL_session_reused(ssl);
6223   if (reused > 0) {
6224     /* Per RFC 6066, if we are a resumed TLS session, then we should NOT be
6225      * stapling an OCSP response; the original handshake still applies
6226      * (Issue #528).
6227      */
6228     pr_trace_msg(trace_channel, 9,
6229       "OCSP stapling requested but ignored for resumed session, per RFC 6066");
6230     return SSL_TLSEXT_ERR_NOACK;
6231   }
6232 
6233   ocsp_pool = make_sub_pool(session.pool);
6234   pr_pool_tag(ocsp_pool, "Session OCSP response pool");
6235 
6236   resp = ocsp_get_response(ocsp_pool, ssl);
6237   resp_derlen = i2d_OCSP_RESPONSE(resp, &resp_der);
6238   if (resp_derlen <= 0) {
6239     tls_log("error determining OCSP response length: %s", tls_get_errors());
6240   }
6241   destroy_pool(ocsp_pool);
6242 
6243   /* Success or failure, we're done with the OCSP response. */
6244   OCSP_RESPONSE_free(resp);
6245 
6246   if (resp_derlen <= 0) {
6247     return SSL_TLSEXT_ERR_NOACK;
6248   }
6249 
6250   SSL_set_tlsext_status_ocsp_resp(ssl, resp_der, resp_derlen);
6251   return SSL_TLSEXT_ERR_OK;
6252 }
6253 #endif /* PR_USE_OPENSSL_OCSP */
6254 
6255 #if defined(TLS_USE_SESSION_TICKETS)
6256 static int tls_ticket_key_cmp(xasetmember_t *a, xasetmember_t *b) {
6257   struct tls_ticket_key *k1, *k2;
6258 
6259   k1 = (struct tls_ticket_key *) a;
6260   k2 = (struct tls_ticket_key *) b;
6261 
6262   if (k1->created == k2->created) {
6263     return 0;
6264   }
6265 
6266   if (k1->created < k2->created) {
6267     return -1;
6268   }
6269 
6270   return 1;
6271 }
6272 
6273 static struct tls_ticket_key *create_ticket_key(void) {
6274   struct tls_ticket_key *k;
6275   void *page_ptr = NULL;
6276   size_t pagesz;
6277   char *ptr;
6278 # ifdef HAVE_MLOCK
6279   int res, xerrno = 0;
6280 # endif /* HAVE_MLOCK */
6281 
6282   pagesz = sizeof(struct tls_ticket_key);
6283   ptr = tls_get_page(pagesz, &page_ptr);
6284   if (ptr == NULL) {
6285     if (page_ptr != NULL) {
6286       free(page_ptr);
6287     }
6288     return NULL;
6289   }
6290 
6291   k = (void *) ptr;
6292   time(&(k->created));
6293 
6294   if (RAND_bytes(k->key_name, 16) != 1) {
6295     pr_log_debug(DEBUG1, MOD_TLS_VERSION
6296       ": error generating random bytes: %s", tls_get_errors());
6297     free(page_ptr);
6298     errno = EPERM;
6299     return NULL;
6300   }
6301 
6302   if (RAND_bytes(k->cipher_key, 32) != 1) {
6303     pr_log_debug(DEBUG1, MOD_TLS_VERSION
6304       ": error generating random bytes: %s", tls_get_errors());
6305     free(page_ptr);
6306     errno = EPERM;
6307     return NULL;
6308   }
6309 
6310   if (RAND_bytes(k->hmac_key, 32) != 1) {
6311     pr_log_debug(DEBUG1, MOD_TLS_VERSION
6312       ": error generating random bytes: %s", tls_get_errors());
6313     free(page_ptr);
6314     errno = EPERM;
6315     return NULL;
6316   }
6317 
6318 # ifdef HAVE_MLOCK
6319   PRIVS_ROOT
6320   res = mlock(page_ptr, pagesz);
6321   xerrno = errno;
6322   PRIVS_RELINQUISH
6323 
6324   if (res < 0) {
6325     /* Ideally, we would not proceed unless we can ensure this key remains
6326      * only in memory.  However, on some systems there may be a limit to the
6327      * amount of locked memory.  Erasing the session ticket key here would lead
6328      * to hard-to-debug TLS handshake issues later, for TLSv1.3 sessions which
6329      * use session tickets (and thus need these keys); see Issue #1014.
6330      *
6331      * Thus we now only _try_ to lock the key in memory, but proceed if we
6332      * cannot.
6333      */
6334     pr_log_debug(DEBUG1, MOD_TLS_VERSION
6335       ": error locking session ticket key into memory: %s", strerror(xerrno));
6336   }
6337 # endif /* HAVE_MLOCK */
6338 
6339   k->page_ptr = page_ptr;
6340   k->pagesz = pagesz;
6341   return k;
6342 }
6343 
6344 static void destroy_ticket_key(struct tls_ticket_key *k) {
6345   void *page_ptr;
6346   size_t pagesz;
6347 # ifdef HAVE_MLOCK
6348   int res, xerrno = 0;
6349 # endif /* HAVE_MLOCK */
6350 
6351   if (k == NULL) {
6352     return;
6353   }
6354 
6355   page_ptr = k->page_ptr;
6356   pagesz = k->pagesz;
6357 
6358   pr_memscrub(k->page_ptr, k->pagesz);
6359 
6360 # ifdef HAVE_MLOCK
6361   PRIVS_ROOT
6362   res = munlock(page_ptr, pagesz);
6363   xerrno = errno;
6364   PRIVS_RELINQUISH
6365 
6366   if (res < 0) {
6367     pr_log_debug(DEBUG1, MOD_TLS_VERSION
6368       ": error unlocking session ticket key memory: %s", strerror(xerrno));
6369   }
6370 # endif /* HAVE_MLOCK */
6371 
6372   free(page_ptr);
6373 }
6374 
6375 static int remove_expired_ticket_keys(void) {
6376   struct tls_ticket_key *k = NULL;
6377   int expired_count = 0;
6378   time_t now;
6379 
6380   if (tls_ticket_key_curr_count < 2) {
6381     /* Always keep at least one key. */
6382     return 0;
6383   }
6384 
6385   time(&now);
6386 
6387   for (k = (struct tls_ticket_key *) tls_ticket_keys->xas_list;
6388        k;
6389        k = k->next) {
6390     time_t key_age;
6391 
6392     key_age = now - k->created;
6393     if (key_age > tls_ticket_key_max_age) {
6394       if (xaset_remove(tls_ticket_keys, (xasetmember_t *) k) == 0) {
6395         expired_count++;
6396         tls_ticket_key_curr_count--;
6397       }
6398     }
6399   }
6400 
6401   return expired_count;
6402 }
6403 
6404 static int remove_oldest_ticket_key(void) {
6405   struct tls_ticket_key *k = NULL;
6406   int res;
6407 
6408   if (tls_ticket_key_curr_count < 2) {
6409     /* Always keep at least one key. */
6410     return 0;
6411   }
6412 
6413   /* Remove the last ticket key in the set. */
6414   for (k = (struct tls_ticket_key *) tls_ticket_keys->xas_list;
6415        k && k->next != NULL;
6416        k = k->next);
6417 
6418   res = xaset_remove(tls_ticket_keys, (xasetmember_t *) k);
6419   if (res == 0) {
6420     tls_ticket_key_curr_count--;
6421   }
6422 
6423   return res;
6424 }
6425 
6426 static int add_ticket_key(struct tls_ticket_key *k) {
6427   int res;
6428 
6429   res = remove_expired_ticket_keys();
6430   if (res > 0) {
6431     pr_trace_msg(trace_channel, 9, "removed %d expired %s", res,
6432       res != 1 ? "keys" : "key");
6433   }
6434 
6435   if (tls_ticket_key_curr_count == tls_ticket_key_max_count) {
6436     res = remove_oldest_ticket_key();
6437     if (res < 0) {
6438       return -1;
6439     }
6440   }
6441 
6442   res = xaset_insert_sort(tls_ticket_keys, (xasetmember_t *) k, FALSE);
6443   if (res == 0) {
6444     tls_ticket_key_curr_count++;
6445   }
6446 
6447   return res;
6448 }
6449 
6450 /* Note: This lookup routine is where we might look in external storage,
6451  * e.g. Redis/memcache, for clustered/shared pool of ticket keys generated by
6452  * other servers.
6453  */
6454 static struct tls_ticket_key *get_ticket_key(unsigned char *key_name,
6455     size_t key_namelen) {
6456   struct tls_ticket_key *k = NULL;
6457 
6458   if (tls_ticket_keys == NULL) {
6459     return NULL;
6460   }
6461 
6462   for (k = (struct tls_ticket_key *) tls_ticket_keys->xas_list;
6463        k;
6464        k = k->next) {
6465     if (memcmp(key_name, k->key_name, key_namelen) == 0) {
6466       break;
6467     }
6468   }
6469 
6470   return k;
6471 }
6472 
6473 static int new_ticket_key_timer_cb(CALLBACK_FRAME) {
6474   struct tls_ticket_key *k;
6475 
6476   pr_log_debug(DEBUG9, MOD_TLS_VERSION
6477     ": generating new TLS session ticket key");
6478 
6479   k = create_ticket_key();
6480   if (k == NULL) {
6481     pr_log_debug(DEBUG0, MOD_TLS_VERSION
6482       ": unable to generate new session ticket key: %s", strerror(errno));
6483 
6484   } else {
6485     add_ticket_key(k);
6486   }
6487 
6488   /* Always restart this timer. */
6489   return 1;
6490 }
6491 
6492 /* Remember that mlock(2) locks are not inherited across forks, thus
6493  * we want to renew those locks for session processes.
6494  */
6495 static void lock_ticket_keys(void) {
6496 # ifdef HAVE_MLOCK
6497   struct tls_ticket_key *k;
6498 
6499   if (tls_ticket_keys == NULL) {
6500     return;
6501   }
6502 
6503   for (k = (struct tls_ticket_key *) tls_ticket_keys->xas_list;
6504        k;
6505        k = k->next) {
6506     if (k->locked == FALSE) {
6507       int res, xerrno = 0;
6508 
6509       PRIVS_ROOT
6510       res = mlock(k->page_ptr, k->pagesz);
6511       xerrno = errno;
6512       PRIVS_RELINQUISH
6513 
6514       if (res < 0) {
6515         pr_log_debug(DEBUG1, MOD_TLS_VERSION
6516           ": error locking session ticket key into memory: %s",
6517           strerror(xerrno));
6518 
6519       } else {
6520         k->locked = TRUE;
6521       }
6522     }
6523   }
6524 # endif /* HAVE_MLOCK */
6525 }
6526 
6527 static void scrub_ticket_keys(void) {
6528   struct tls_ticket_key *k, *next_k;
6529 
6530   if (tls_ticket_keys == NULL) {
6531     return;
6532   }
6533 
6534   for (k = (struct tls_ticket_key *) tls_ticket_keys->xas_list; k; k = next_k) {
6535     next_k = k->next;
6536     destroy_ticket_key(k);
6537   }
6538 
6539   tls_ticket_keys = NULL;
6540 }
6541 
6542 /* TLS session ticket _key_ callback; not to be confused with the TLSv1.3
6543  * session ticket callbacks.
6544  */
6545 static int tls_ticket_key_cb(SSL *ssl, unsigned char *key_name,
6546     unsigned char *iv, EVP_CIPHER_CTX *cipher_ctx, HMAC_CTX *hmac_ctx,
6547     int mode) {
6548   struct tls_ticket_key *k;
6549   char *key_name_str;
6550 
6551   /* Note: should we have a list of ciphers from which we randomly choose,
6552    * when creating a key?  I.e. should the keys themselves hold references
6553    * to their ciphers, digests?
6554    */
6555   const EVP_CIPHER *cipher = EVP_aes_256_cbc();
6556 # ifdef OPENSSL_NO_SHA256
6557   const EVP_MD *md = EVP_sha1();
6558 # else
6559   const EVP_MD *md = EVP_sha256();
6560 # endif
6561 
6562   pr_trace_msg(trace_channel, 19,
6563     "handling session ticket key request on %s session (%s mode)",
6564     SSL_get_version(ssl), mode ? "encrypt" : "decrypt");
6565 
6566   if (mode == 1) {
6567     int ticket_key_len, sess_key_len;
6568 
6569     if (tls_ticket_keys == NULL) {
6570       return -1;
6571     }
6572 
6573     /* Creating a new session ticket.  Always use the first key in the set. */
6574     k = (struct tls_ticket_key *) tls_ticket_keys->xas_list;
6575 
6576     key_name_str = pr_str_bin2hex(session.pool, k->key_name, 16,
6577       PR_STR_FL_HEX_USE_LC);
6578 
6579     pr_trace_msg(trace_channel, 3,
6580       "TLS session ticket: encrypting using key name '%s' for %s session",
6581       key_name_str, SSL_session_reused(ssl) ? "reused" : "new");
6582 
6583     /* Warn loudly if the ticket key we are using is not as strong (based on
6584      * cipher key length) as the one negotiated for the session.
6585      */
6586     ticket_key_len = EVP_CIPHER_key_length(cipher) * 8;
6587     sess_key_len = SSL_get_cipher_bits(ssl, NULL);
6588     if (ticket_key_len < sess_key_len) {
6589       pr_log_pri(PR_LOG_INFO, MOD_TLS_VERSION
6590         ": WARNING: TLS session tickets encrypted with weaker key than "
6591         "session: ticket key = %s (%d bytes), session key = %s (%d bytes)",
6592         OBJ_nid2sn(EVP_CIPHER_type(cipher)), ticket_key_len,
6593         SSL_get_cipher_name(ssl), sess_key_len);
6594     }
6595 
6596     if (RAND_bytes(iv, EVP_CIPHER_iv_length(cipher)) != 1) {
6597       pr_trace_msg(trace_channel, 3,
6598         "unable to initialize session ticket key IV: %s", tls_get_errors());
6599       return -1;
6600     }
6601 
6602     if (EVP_EncryptInit_ex(cipher_ctx, cipher, NULL, k->cipher_key, iv) != 1) {
6603       pr_trace_msg(trace_channel, 3,
6604         "unable to initialize session ticket key cipher: %s", tls_get_errors());
6605       return -1;
6606     }
6607 
6608 # if OPENSSL_VERSION_NUMBER >= 0x10000001L
6609     if (HMAC_Init_ex(hmac_ctx, k->hmac_key, 32, md, NULL) != 1) {
6610       pr_trace_msg(trace_channel, 3,
6611         "unable to initialize session ticket key HMAC: %s", tls_get_errors());
6612       return -1;
6613     }
6614 # else
6615     HMAC_Init_ex(hmac_ctx, k->hmac_key, 32, md, NULL);
6616 # endif /* OpenSSL-1.0.0 and later */
6617 
6618     memcpy(key_name, k->key_name, 16);
6619     return 1;
6620   }
6621 
6622   if (mode == 0) {
6623     struct tls_ticket_key *newest_key;
6624     time_t key_age, now;
6625 
6626     key_name_str = pr_str_bin2hex(session.pool, key_name, 16,
6627       PR_STR_FL_HEX_USE_LC);
6628 
6629     k = get_ticket_key(key_name, 16);
6630     if (k == NULL) {
6631       /* No matching key found. */
6632       pr_trace_msg(trace_channel, 3,
6633         "TLS session ticket: decrypting ticket using key name '%s': "
6634         "key not found", key_name_str);
6635       return 0;
6636     }
6637 
6638     pr_trace_msg(trace_channel, 3,
6639       "TLS session ticket: decrypting ticket using key name '%s'",
6640       key_name_str);
6641 
6642 # if OPENSSL_VERSION_NUMBER >= 0x10000001L
6643     if (HMAC_Init_ex(hmac_ctx, k->hmac_key, 32, md, NULL) != 1) {
6644       pr_trace_msg(trace_channel, 3,
6645         "unable to initialize session ticket key HMAC: %s", tls_get_errors());
6646       return 0;
6647     }
6648 # else
6649     HMAC_Init_ex(hmac_ctx, k->hmac_key, 32, md, NULL);
6650 # endif /* OpenSSL-1.0.0 and later */
6651 
6652     if (EVP_DecryptInit_ex(cipher_ctx, cipher, NULL, k->cipher_key, iv) != 1) {
6653       pr_trace_msg(trace_channel, 3,
6654         "unable to initialize session ticket key cipher: %s", tls_get_errors());
6655       return 0;
6656     }
6657 
6658     /* If the key we found is older than the newest key, tell the client to
6659      * get a new ticket.  This helps to reduce the window of time a given
6660      * ticket key is used.
6661      */
6662     time(&now);
6663     key_age = now - k->created;
6664 
6665     newest_key = (struct tls_ticket_key *) tls_ticket_keys->xas_list;
6666     if (k != newest_key) {
6667       time_t newest_age;
6668 
6669       newest_age = now - newest_key->created;
6670 
6671       pr_trace_msg(trace_channel, 3,
6672         "key '%s' age (%lu %s) older than newest key (%lu %s), requesting "
6673         "ticket renewal", key_name_str, (unsigned long) key_age,
6674         key_age != 1 ? "secs" : "sec", (unsigned long) newest_age,
6675         newest_age != 1 ? "secs" : "sec");
6676       return 2;
6677     }
6678 
6679 # if defined(TLS1_3_VERSION)
6680     /* If we're a TLSv1.3 session, aim for single-use tickets, and indicate
6681      * that the client should get a new ticket.  Will the FTPS client
6682      * Do The Right Thing(tm), and use this new ticket for future data
6683      * transfers?
6684      */
6685     if (SSL_version(ssl) == TLS1_3_VERSION) {
6686       return 2;
6687     }
6688 # endif /* TLS1_3_VERSION */
6689 
6690     return 1;
6691   }
6692 
6693   pr_trace_msg(trace_channel, 3, "TLS session ticket: unknown mode (%d)", mode);
6694   return -1;
6695 }
6696 #endif /* TLS_USE_SESSION_TICKETS */
6697 
6698 #if defined(PR_USE_OPENSSL_SSL_SESSION_TICKET_CALLBACK)
6699 static int tls_generate_session_ticket_cb(SSL *ssl, void *user_data) {
6700   SSL_SESSION *ssl_session;
6701 
6702   ssl_session = SSL_get_session(ssl);
6703 
6704   if (SSL_SESSION_set1_ticket_appdata(ssl_session,
6705       tls_ctrl_ticket_appdata, tls_ctrl_ticket_appdata_len) != 1) {
6706     tls_log("error setting ticket appdata for ticket: %s",
6707       tls_get_errors());
6708 
6709   } else {
6710     if (pr_trace_get_level(trace_channel) >= 19) {
6711       register unsigned int i;
6712       unsigned char *ticket_appdata;
6713       BIO *bio;
6714       char *text = NULL;
6715       long text_len = 0;
6716 
6717       bio = BIO_new(BIO_s_mem());
6718       BIO_printf(bio, "set %lu bytes of ticket appdata (",
6719         (unsigned long) tls_ctrl_ticket_appdata_len);
6720       ticket_appdata = tls_ctrl_ticket_appdata;
6721       for (i = 0; i < tls_ctrl_ticket_appdata_len; i++) {
6722         BIO_printf(bio, "%02x", ticket_appdata[i]);
6723       }
6724       BIO_printf(bio, ") for %s session ticket", SSL_get_version(ssl));
6725 
6726       text_len = BIO_get_mem_data(bio, &text);
6727       if (text != NULL) {
6728         text[text_len] = '\0';
6729         pr_trace_msg(trace_channel, 19, "%.*s", (int) text_len, text);
6730       }
6731 
6732       BIO_free(bio);
6733 
6734     } else {
6735       pr_trace_msg(trace_channel, 9,
6736         "set %lu bytes of ticket appdata for %s session ticket",
6737         (unsigned long) tls_ctrl_ticket_appdata_len, SSL_get_version(ssl));
6738     }
6739   }
6740 
6741   return 1;
6742 }
6743 
6744 static void get_session_ticket_appdata(SSL *ssl, SSL_SESSION *ssl_session) {
6745   void *appdata = NULL;
6746   size_t appdata_len = 0;
6747 
6748   if (SSL_SESSION_get0_ticket_appdata(ssl_session, &appdata,
6749       &appdata_len) != 1) {
6750     tls_log("error obtaining ticket appdata from data transfer ticket: %s",
6751       tls_get_errors());
6752     tls_data_ticket_appdata_len = 0;
6753 
6754     return;
6755   }
6756 
6757   /* Make sure the ticket appdata length is what we expect; we might have
6758    * received a ticket with different appdata that what we want.
6759    */
6760   if (appdata_len != tls_data_ticket_appdatasz) {
6761     tls_log("received %s session ticket with unexpected appdata "
6762       "(expected %lu bytes, got %lu), ignoring", SSL_get_version(ssl),
6763       (unsigned long) tls_data_ticket_appdatasz, (unsigned long) appdata_len);
6764     tls_data_ticket_appdata_len = 0;
6765 
6766     return;
6767   }
6768 
6769   /* Note that we need to copy the appdata into our own buffers for later
6770    * comparisons; the OpenSSL docs do not do a good job of describing the
6771    * lifetime of the pointer/buffer returned by
6772    * SSL_SESSION_get0_ticket_appdata.
6773    */
6774   tls_data_ticket_appdata_len = appdata_len;
6775   memcpy(tls_data_ticket_appdata, appdata, appdata_len);
6776 
6777   if (pr_trace_get_level(trace_channel) >= 19) {
6778     register unsigned int i;
6779     unsigned char *ticket_appdata;
6780     BIO *bio;
6781     char *text = NULL;
6782     long text_len = 0;
6783 
6784     bio = BIO_new(BIO_s_mem());
6785     BIO_printf(bio, "obtained %lu bytes of ticket appdata (",
6786       (unsigned long) tls_data_ticket_appdata_len);
6787     ticket_appdata = tls_data_ticket_appdata;
6788     for (i = 0; i < tls_data_ticket_appdata_len; i++) {
6789       BIO_printf(bio, "%02x", ticket_appdata[i]);
6790     }
6791     BIO_printf(bio, ") from %s session ticket", SSL_get_version(ssl));
6792 
6793     text_len = BIO_get_mem_data(bio, &text);
6794     if (text != NULL) {
6795       text[text_len] = '\0';
6796       pr_trace_msg(trace_channel, 19, "%.*s", (int) text_len, text);
6797     }
6798 
6799     BIO_free(bio);
6800 
6801   } else {
6802     pr_trace_msg(trace_channel, 9,
6803       "obtained %lu bytes of ticket appdata from %s session ticket",
6804       (unsigned long) tls_data_ticket_appdata_len, SSL_get_version(ssl));
6805   }
6806 }
6807 
6808 static SSL_TICKET_RETURN tls_decrypt_session_ticket_data_xfer_cb(SSL *ssl,
6809     SSL_SESSION *ssl_session, const unsigned char *key_name, size_t key_namelen,
6810     SSL_TICKET_STATUS status, void *user_data) {
6811   SSL_TICKET_RETURN res;
6812 
6813   switch (status) {
6814     case SSL_TICKET_EMPTY:
6815     case SSL_TICKET_NO_DECRYPT:
6816       tls_data_ticket_appdata_len = 0;
6817       res = SSL_TICKET_RETURN_IGNORE_RENEW;
6818       break;
6819 
6820     case SSL_TICKET_SUCCESS:
6821       get_session_ticket_appdata(ssl, ssl_session);
6822       res = SSL_TICKET_RETURN_USE;
6823       break;
6824 
6825     case SSL_TICKET_SUCCESS_RENEW:
6826       get_session_ticket_appdata(ssl, ssl_session);
6827       res = SSL_TICKET_RETURN_USE_RENEW;
6828       break;
6829 
6830     default:
6831       res = SSL_TICKET_RETURN_IGNORE;
6832   }
6833 
6834   return res;
6835 }
6836 
6837 /* Note that we want to _use_ any provided TLSv1.3 session tickets, so that
6838  * data transfers can reuse the TLS session from the control connection.  BUT
6839  * we do not want to _renew_ (or issue) new tickets, as that will may tickle
6840  * the ECONNRESET bug (see Issue #959) for some data transfers.
6841  */
6842 static SSL_TICKET_RETURN tls_decrypt_session_ticket_data_upload_cb(SSL *ssl,
6843     SSL_SESSION *ssl_session, const unsigned char *key_name, size_t key_namelen,
6844     SSL_TICKET_STATUS status, void *user_data) {
6845   SSL_TICKET_RETURN res;
6846   int renew_tickets = TRUE;
6847 
6848   /* Avoid using the given SSL_SESSION pointer unless the status indicates that
6849    * that pointer is valid (Issue #1063).
6850    */
6851 
6852   if (status != SSL_TICKET_EMPTY &&
6853       status != SSL_TICKET_NO_DECRYPT) {
6854     int ssl_version;
6855 
6856     ssl_version = SSL_SESSION_get_protocol_version(ssl_session);
6857 # if defined(TLS1_3_VERSION)
6858     if (ssl_version == TLS1_3_VERSION) {
6859       pr_trace_msg(trace_channel, 29,
6860         "suppressing renewal of TLSv1.3 tickets for data transfers");
6861       renew_tickets = FALSE;
6862     }
6863   }
6864 # endif /* TLS1_3_VERSION */
6865 
6866   switch (status) {
6867     case SSL_TICKET_EMPTY:
6868     case SSL_TICKET_NO_DECRYPT:
6869       tls_data_ticket_appdata_len = 0;
6870       res = SSL_TICKET_RETURN_IGNORE_RENEW;
6871       if (renew_tickets == FALSE) {
6872         res = SSL_TICKET_RETURN_IGNORE;
6873       }
6874       break;
6875 
6876     case SSL_TICKET_SUCCESS:
6877       get_session_ticket_appdata(ssl, ssl_session);
6878       res = SSL_TICKET_RETURN_USE;
6879       break;
6880 
6881     case SSL_TICKET_SUCCESS_RENEW:
6882       get_session_ticket_appdata(ssl, ssl_session);
6883       res = SSL_TICKET_RETURN_USE_RENEW;
6884       if (renew_tickets == FALSE) {
6885         res = SSL_TICKET_RETURN_USE;
6886       }
6887       break;
6888 
6889     default:
6890       res = SSL_TICKET_RETURN_IGNORE;
6891   }
6892 
6893   return res;
6894 }
6895 #endif /* PR_USE_OPENSSL_SSL_SESSION_TICKET_CALLBACK */
6896 
6897 #if defined(PR_USE_OPENSSL_ECC) && \
6898     OPENSSL_VERSION_NUMBER < 0x10100000L
6899 static EC_KEY *tls_ecdh_cb(SSL *ssl, int is_export, int keylen) {
6900   static EC_KEY *ecdh = NULL;
6901   static int init = 0;
6902 
6903   if (init == 0) {
6904     ecdh = EC_KEY_new();
6905 
6906     if (ecdh != NULL) {
6907       EC_KEY_set_group(ecdh,
6908         EC_GROUP_new_by_curve_name(NID_X9_62_prime256v1));
6909     }
6910 
6911     init = 1;
6912   }
6913 
6914   return ecdh;
6915 }
6916 #endif /* PR_USE_OPENSSL_ECC and before OpenSSL-1.1.x */
6917 
6918 #if defined(PR_USE_OPENSSL_ALPN)
6919 static int tls_alpn_select_cb(SSL *ssl,
6920     const unsigned char **selected_proto, unsigned char *selected_protolen,
6921     const unsigned char *advertised_proto, unsigned int advertised_protolen,
6922     void *user_data) {
6923   register unsigned int i;
6924   struct tls_next_proto *next_proto;
6925   char *selected_alpn;
6926 
6927   pr_trace_msg(trace_channel, 9, "%s",
6928     "ALPN protocols advertised by client:");
6929   for (i = 0; i < advertised_protolen; i++) {
6930     pr_trace_msg(trace_channel, 9,
6931       " %*s", advertised_proto[i], &(advertised_proto[i+1]));
6932     i += advertised_proto[i] + 1;
6933   }
6934 
6935   next_proto = user_data;
6936 
6937   if (SSL_select_next_proto(
6938       (unsigned char **) selected_proto, selected_protolen,
6939       next_proto->encoded_proto, next_proto->encoded_protolen,
6940       advertised_proto, advertised_protolen) != OPENSSL_NPN_NEGOTIATED) {
6941     pr_trace_msg(trace_channel, 9,
6942       "no common ALPN protocols found (no '%s' in ALPN protocols)",
6943       next_proto->proto);
6944     return SSL_TLSEXT_ERR_NOACK;
6945   }
6946 
6947   selected_alpn = pstrndup(session.pool, (char *) *selected_proto,
6948     *selected_protolen);
6949   pr_trace_msg(trace_channel, 9,
6950     "selected ALPN protocol '%s'", selected_alpn);
6951   return SSL_TLSEXT_ERR_OK;
6952 }
6953 #endif /* ALPN */
6954 
6955 #if defined(PR_USE_OPENSSL_NPN)
6956 static int tls_npn_advertised_cb(SSL *ssl,
6957     const unsigned char **advertise_proto, unsigned int *advertise_protolen,
6958     void *user_data) {
6959   struct tls_next_proto *next_proto;
6960 
6961   next_proto = user_data;
6962 
6963   pr_trace_msg(trace_channel, 9,
6964     "advertising NPN protocol '%s'", next_proto->proto);
6965   *advertise_proto = next_proto->encoded_proto;
6966   *advertise_protolen = next_proto->encoded_protolen;
6967 
6968   return SSL_TLSEXT_ERR_OK;
6969 }
6970 #endif /* NPN */
6971 
6972 /* Post 0.9.7a, RSA blinding is turned on by default, so there is no need to
6973  * do this manually.
6974  */
6975 #if OPENSSL_VERSION_NUMBER < 0x0090702fL
6976 static void tls_blinding_on(SSL *ssl) {
6977   EVP_PKEY *pkey = NULL;
6978   RSA *rsa = NULL;
6979 
6980   /* RSA keys are subject to timing attacks.  To attempt to make such
6981    * attacks harder, use RSA blinding.
6982    */
6983 
6984   pkey = SSL_get_privatekey(ssl);
6985 
6986   if (pkey)
6987     rsa = EVP_PKEY_get1_RSA(pkey);
6988 
6989   if (rsa) {
6990     if (RSA_blinding_on(rsa, NULL) != 1) {
6991       tls_log("error setting RSA blinding: %s",
6992         ERR_error_string(ERR_get_error(), NULL));
6993 
6994     } else {
6995       tls_log("set RSA blinding on");
6996     }
6997 
6998     /* Now, "free" the RSA pointer, to properly decrement the reference
6999      * counter.
7000      */
7001     RSA_free(rsa);
7002 
7003   } else {
7004 
7005     /* The administrator may have configured DSA keys rather than RSA keys.
7006      * In this case, there is nothing to do.
7007      */
7008   }
7009 
7010   return;
7011 }
7012 #endif
7013 
7014 static int tls_set_fips(void) {
7015   if (pr_define_exists("TLS_USE_FIPS") != TRUE) {
7016     return 0;
7017   }
7018 
7019 #ifdef OPENSSL_FIPS
7020   if (!FIPS_mode()) {
7021     /* Make sure OpenSSL is set to use the default RNG, as per an email
7022      * discussion on the OpenSSL developer list:
7023      *
7024      *  "The internal FIPS logic uses the default RNG to see the FIPS RNG
7025      *   as part of the self test process..."
7026      */
7027     RAND_set_rand_method(NULL);
7028 
7029     if (!FIPS_mode_set(1)) {
7030       const char *errstr;
7031 
7032       errstr = tls_get_errors();
7033       tls_log("unable to use FIPS mode: %s", errstr);
7034       pr_log_pri(PR_LOG_ERR, MOD_TLS_VERSION
7035         ": unable to use FIPS mode: %s", errstr);
7036 
7037       errno = EPERM;
7038       return -1;
7039     }
7040 
7041     pr_log_pri(PR_LOG_NOTICE, MOD_TLS_VERSION ": FIPS mode enabled");
7042 
7043   } else {
7044     pr_log_pri(PR_LOG_DEBUG, MOD_TLS_VERSION ": FIPS mode already enabled");
7045   }
7046 #else
7047   pr_log_pri(PR_LOG_WARNING, MOD_TLS_VERSION ": FIPS mode requested, but " OPENSSL_VERSION_TEXT " not built with FIPS support");
7048 #endif /* OPENSSL_FIPS */
7049 
7050   return 0;
7051 }
7052 
7053 static SSL_CTX *tls_init_ctx(server_rec *s) {
7054   int ssl_opts = tls_ssl_opts;
7055   long ssl_mode = 0;
7056   SSL_CTX *ctx;
7057 #if defined(TLS_USE_SESSION_TICKETS)
7058   config_rec *c;
7059 #endif /* TLS_USE_SESSION_TICKETS */
7060 
7061   ctx = SSL_CTX_new(SSLv23_server_method());
7062   if (ctx == NULL) {
7063     pr_log_debug(DEBUG0, MOD_TLS_VERSION ": error: SSL_CTX_new(): %s",
7064       tls_get_errors());
7065     return NULL;
7066   }
7067 
7068 #if OPENSSL_VERSION_NUMBER > 0x000906000L
7069   /* The SSL_MODE_AUTO_RETRY mode was added in 0.9.6. */
7070   ssl_mode |= SSL_MODE_AUTO_RETRY;
7071 #endif
7072 
7073 #if OPENSSL_VERSION_NUMBER >= 0x1000001fL
7074   /* The SSL_MODE_RELEASE_BUFFERS mode was added in 1.0.0a. */
7075   ssl_mode |= SSL_MODE_RELEASE_BUFFERS;
7076 #endif
7077 
7078   if (ssl_mode != 0) {
7079     SSL_CTX_set_mode(ctx, ssl_mode);
7080   }
7081 
7082   /* If using OpenSSL-0.9.7 or greater, prevent session resumptions on
7083    * renegotiations (more secure).
7084    */
7085 #if OPENSSL_VERSION_NUMBER > 0x000907000L
7086   ssl_opts |= SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION;
7087 #endif
7088 
7089   /* Disable SSL compression. */
7090 #ifdef SSL_OP_NO_COMPRESSION
7091   ssl_opts |= SSL_OP_NO_COMPRESSION;
7092 #endif /* SSL_OP_NO_COMPRESSION */
7093 
7094 #if defined(PR_USE_OPENSSL_ECC)
7095 # if defined(SSL_OP_SINGLE_ECDH_USE)
7096   ssl_opts |= SSL_OP_SINGLE_ECDH_USE;
7097 # endif
7098 # if defined(SSL_OP_SAFARI_ECDHE_ECDSA_BUG)
7099   ssl_opts |= SSL_OP_SAFARI_ECDHE_ECDSA_BUG;
7100 # endif
7101 #endif /* ECC support */
7102 
7103 #if defined(SSL_OP_CIPHER_SERVER_PREFERENCE)
7104   /* Use the server cipher preferences by default. */
7105   if (tls_use_server_cipher_preference == TRUE) {
7106     ssl_opts |= SSL_OP_CIPHER_SERVER_PREFERENCE;
7107   }
7108 #endif /* SSL_OP_CIPHER_SERVER_PREFERENCE */
7109 
7110   SSL_CTX_set_options(ctx, ssl_opts);
7111 
7112 #if defined(TLS_USE_SESSION_TICKETS)
7113   c = find_config(s->conf, CONF_PARAM, "TLSSessionTicketKeys", FALSE);
7114   if (c != NULL) {
7115     tls_ticket_key_max_age = *((unsigned int *) c->argv[0]);
7116     tls_ticket_key_max_count = *((unsigned int *) c->argv[1]);
7117   }
7118 
7119   /* Generate a random session ticket key, if necessary.  Maybe this list
7120    * of keys could be stored as ex/app data in the SSL_CTX?
7121    */
7122   if (tls_ticket_keys == NULL) {
7123     struct tls_ticket_key *k;
7124     unsigned int new_ticket_key_intvl;
7125 
7126     pr_log_debug(DEBUG9, MOD_TLS_VERSION
7127       ": generating initial TLS session ticket key");
7128 
7129     k = create_ticket_key();
7130     if (k == NULL) {
7131       pr_log_debug(DEBUG0, MOD_TLS_VERSION
7132         ": unable to generate initial session ticket key: %s",
7133         strerror(errno));
7134 
7135     } else {
7136       tls_ticket_keys = xaset_create(permanent_pool, tls_ticket_key_cmp);
7137       add_ticket_key(k);
7138     }
7139 
7140     /* Also register a timer, to generate new keys every hour (or just under
7141      * the max age of a key, whichever is smaller).
7142      */
7143 
7144     new_ticket_key_intvl = 3600;
7145     if (tls_ticket_key_max_age < new_ticket_key_intvl) {
7146       /* Try to get a new ticket a little before one expires. */
7147       new_ticket_key_intvl = tls_ticket_key_max_age - 1;
7148     }
7149 
7150     pr_log_debug(DEBUG9, MOD_TLS_VERSION
7151       ": scheduling new TLS session ticket key every %d %s",
7152       new_ticket_key_intvl, new_ticket_key_intvl != 1 ? "secs" : "sec");
7153 
7154     pr_timer_add(new_ticket_key_intvl, -1, &tls_module, new_ticket_key_timer_cb,
7155       "New TLS Session Ticket Key");
7156 
7157   } else {
7158     struct tls_ticket_key *k;
7159 
7160     /* Generate a new key on restart, as part of a good cryptographic
7161      * hygiene.
7162      */
7163     pr_log_debug(DEBUG9, MOD_TLS_VERSION ": generating TLS session ticket key");
7164 
7165     k = create_ticket_key();
7166     if (k == NULL) {
7167       pr_log_debug(DEBUG0, MOD_TLS_VERSION
7168         ": unable to generate new session ticket key: %s", strerror(errno));
7169 
7170     } else {
7171       add_ticket_key(k);
7172     }
7173   }
7174 #endif /* TLS_USE_SESSION_TICKETS */
7175 
7176 #if defined(PR_USE_OPENSSL_SSL_SESSION_TICKET_CALLBACK)
7177   if (SSL_CTX_set_session_ticket_cb(ctx, tls_generate_session_ticket_cb,
7178       tls_decrypt_session_ticket_data_xfer_cb, NULL) != 1) {
7179     pr_trace_msg(trace_channel, 3,
7180       "error setting TLSv1.3 session ticket callback: %s", tls_get_errors());
7181   }
7182 #endif /* PR_USE_OPENSSL_SSL_SESSION_TICKET_CALLBACK */
7183 
7184   SSL_CTX_set_tmp_dh_callback(ctx, tls_dh_cb);
7185 
7186 #ifdef PR_USE_OPENSSL_ECC
7187   /* If using OpenSSL 1.0.2 or later, let it automatically choose the
7188    * correct/best curve, rather than having to hardcode a fallback.
7189    */
7190 # if defined(SSL_CTX_set_ecdh_auto)
7191   SSL_CTX_set_ecdh_auto(ctx, 1);
7192 # endif
7193 #endif /* PR_USE_OPENSSL_ECC */
7194 
7195   /* We always install an info callback, in order to watch for
7196    * client-initiated session renegotiations (Bug#3324).  If EnableDiags
7197    * is enabled, that info callback will also log the OpenSSL diagnostic
7198    * information.
7199    */
7200   SSL_CTX_set_info_callback(ctx, tls_info_cb);
7201 
7202   return ctx;
7203 }
7204 
7205 static const char *tls_get_proto_str(pool *p, unsigned int protos,
7206     unsigned int *count) {
7207   char *proto_str = "";
7208   unsigned int nproto = 0;
7209 
7210   if (protos & TLS_PROTO_SSL_V3) {
7211     proto_str = pstrcat(p, proto_str, *proto_str ? ", " : "",
7212       "SSLv3", NULL);
7213     nproto++;
7214   }
7215 
7216   if (protos & TLS_PROTO_TLS_V1) {
7217     proto_str = pstrcat(p, proto_str, *proto_str ? ", " : "",
7218       "TLSv1", NULL);
7219     nproto++;
7220   }
7221 
7222   if (protos & TLS_PROTO_TLS_V1_1) {
7223     proto_str = pstrcat(p, proto_str, *proto_str ? ", " : "",
7224       "TLSv1.1", NULL);
7225     nproto++;
7226   }
7227 
7228   if (protos & TLS_PROTO_TLS_V1_2) {
7229     proto_str = pstrcat(p, proto_str, *proto_str ? ", " : "",
7230       "TLSv1.2", NULL);
7231     nproto++;
7232   }
7233 
7234   if (protos & TLS_PROTO_TLS_V1_3) {
7235     proto_str = pstrcat(p, proto_str, *proto_str ? ", " : "",
7236       "TLSv1.3", NULL);
7237     nproto++;
7238   }
7239 
7240   *count = nproto;
7241   return proto_str;
7242 }
7243 
7244 /* Construct the options value that disables all unsupported protocols. */
7245 static int get_disabled_protocols(unsigned int supported_protocols) {
7246   int disabled_protocols;
7247 
7248   /* First, create an options value where ALL protocols are disabled. */
7249   disabled_protocols = (SSL_OP_NO_SSLv2|SSL_OP_NO_SSLv3|SSL_OP_NO_TLSv1);
7250 
7251 #ifdef SSL_OP_NO_TLSv1_1
7252   disabled_protocols |= SSL_OP_NO_TLSv1_1;
7253 #endif
7254 #ifdef SSL_OP_NO_TLSv1_2
7255   disabled_protocols |= SSL_OP_NO_TLSv1_2;
7256 #endif
7257 #ifdef SSL_OP_NO_TLSv1_3
7258   disabled_protocols |= SSL_OP_NO_TLSv1_3;
7259 #endif
7260 
7261   /* Now, based on the given bitset of supported protocols, clear the
7262    * necessary bits.
7263    */
7264 
7265   if (supported_protocols & TLS_PROTO_SSL_V3) {
7266     disabled_protocols &= ~SSL_OP_NO_SSLv3;
7267   }
7268 
7269   if (supported_protocols & TLS_PROTO_TLS_V1) {
7270     disabled_protocols &= ~SSL_OP_NO_TLSv1;
7271   }
7272 
7273 #if OPENSSL_VERSION_NUMBER >= 0x10001000L
7274   if (supported_protocols & TLS_PROTO_TLS_V1_1) {
7275     disabled_protocols &= ~SSL_OP_NO_TLSv1_1;
7276   }
7277 
7278   if (supported_protocols & TLS_PROTO_TLS_V1_2) {
7279     disabled_protocols &= ~SSL_OP_NO_TLSv1_2;
7280   }
7281 #endif /* OpenSSL-1.0.1 or later */
7282 
7283 #ifdef SSL_OP_NO_TLSv1_3
7284   if (supported_protocols & TLS_PROTO_TLS_V1_3) {
7285     disabled_protocols &= ~SSL_OP_NO_TLSv1_3;
7286   }
7287 #endif /* OpenSSL 1.1.1 or later */
7288 
7289   return disabled_protocols;
7290 }
7291 
7292 static int tls_get_block(conn_t *conn) {
7293   int flags;
7294 
7295   flags = fcntl(conn->rfd, F_GETFL);
7296   if (flags & O_NONBLOCK) {
7297     return FALSE;
7298   }
7299 
7300   return TRUE;
7301 }
7302 
7303 static int tls_compare_session_ids(SSL_SESSION *ctrl_sess,
7304     SSL_SESSION *data_sess) {
7305   int res = -1;
7306 
7307 #if OPENSSL_VERSION_NUMBER < 0x000907000L
7308   /* In the OpenSSL source code, SSL_SESSION_cmp() ultimately uses memcmp(3)
7309    * to check, and thus returns memcmp(3)'s return value.
7310    */
7311   res = SSL_SESSION_cmp(ctrl_sess, data_sess);
7312 #else
7313   const unsigned char *ctrl_sess_id, *data_sess_id;
7314   unsigned int ctrl_sess_id_len, data_sess_id_len;
7315 
7316 # if OPENSSL_VERSION_NUMBER > 0x000908000L
7317   ctrl_sess_id = (const unsigned char *) SSL_SESSION_get_id(ctrl_sess,
7318     &ctrl_sess_id_len);
7319   data_sess_id = (const unsigned char *) SSL_SESSION_get_id(data_sess,
7320     &data_sess_id_len);
7321 # else
7322   /* XXX Directly accessing these fields cannot be a Good Thing. */
7323   ctrl_sess_id = ctrl_sess->session_id;
7324   ctrl_sess_id_len = ctrl_sess->session_id_length;
7325   data_sess_id = data_sess->session_id;
7326   data_sess_id_len = data_sess->session_id_length;
7327 # endif
7328 
7329   /* We might use SSL_has_matching_session_id, except that it does not
7330    * appear to be reliable using older versions of OpenSSL (e.g. 1.0.1t in
7331    * my local testing).  So just compare the raw session IDs ourselves.
7332    */
7333   if (ctrl_sess_id_len == data_sess_id_len) {
7334     res = memcmp(ctrl_sess_id, data_sess_id, ctrl_sess_id_len);
7335     if (res != 0) {
7336       res = -1;
7337     }
7338 
7339   } else {
7340     res = -1;
7341   }
7342 #endif
7343 
7344   return res;
7345 }
7346 
7347 static int tls_accept(conn_t *conn, unsigned char on_data) {
7348   static unsigned char logged_data = FALSE;
7349   int blocking, res = 0, xerrno = 0;
7350   long cache_mode = 0;
7351   char *subj = NULL;
7352   SSL *ssl = NULL;
7353   BIO *rbio = NULL, *wbio = NULL;
7354 
7355   if (ssl_ctx == NULL) {
7356     tls_log("%s", "unable to start session: null SSL_CTX");
7357     return -1;
7358   }
7359 
7360   ssl = SSL_new(ssl_ctx);
7361   if (ssl == NULL) {
7362     tls_log("error: unable to start session: %s",
7363       ERR_error_string(ERR_get_error(), NULL));
7364     return -2;
7365   }
7366 
7367   /* This works with either rfd or wfd (I hope). */
7368   rbio = BIO_new_socket(conn->rfd, FALSE);
7369   wbio = BIO_new_socket(conn->wfd, FALSE);
7370 
7371   /* During handshakes, set the write buffer size smaller, so that we do not
7372    * overflow the (new) connection's TCP CWND size and force another round
7373    * trip.
7374    *
7375    * Then, later, we set a larger buffer size, but ONLY if we are doing a data
7376    * transfer.  For the control connection, the interactions/messages are
7377    * assumed to be small, thus there's no need for the larger buffer size.
7378    * Right?
7379    */
7380   (void) BIO_set_write_buf_size(wbio, TLS_HANDSHAKE_WRITE_BUFFER_SIZE);
7381 
7382   SSL_set_bio(ssl, rbio, wbio);
7383 
7384 #if !defined(OPENSSL_NO_TLSEXT)
7385   if (tls_opts & TLS_OPT_ENABLE_DIAGS) {
7386     /* Note that older OpenSSL versions, e.g. 0.9.8, do not implement this
7387      * callback.  Newer versions which DO implement it do as via a macro.
7388      */
7389 # ifdef SSL_set_tlsext_debug_callback
7390     SSL_set_tlsext_debug_callback(ssl, tls_tlsext_cb);
7391 # endif /* SSL_set_tlsext_debug_callback */
7392   }
7393 #endif /* !OPENSSL_NO_TLSEXT */
7394 
7395   /* If configured, set a timer for the handshake. */
7396   if (tls_handshake_timeout) {
7397     tls_handshake_timed_out = FALSE;
7398     tls_handshake_timer_id = pr_timer_add(tls_handshake_timeout, -1,
7399       &tls_module, tls_handshake_timeout_cb, "SSL/TLS handshake");
7400   }
7401 
7402   if (on_data) {
7403     /* Make sure that TCP_NODELAY is enabled for the handshake. */
7404     if (pr_inet_set_proto_nodelay(conn->pool, conn, 1) < 0) {
7405       pr_trace_msg(trace_channel, 9,
7406         "error enabling TCP_NODELAY on data conn: %s", strerror(errno));
7407     }
7408 
7409     /* Make sure that TCP_CORK (aka TCP_NOPUSH) is DISABLED for the handshake.
7410      * This socket option is set via the pr_inet_set_proto_opts() call made
7411      * in mod_core, upon handling the PASV/EPSV command.
7412      */
7413     if (pr_inet_set_proto_cork(conn->wfd, 0) < 0) {
7414       pr_trace_msg(trace_channel, 9,
7415         "error disabling TCP_CORK on data conn: %s", strerror(errno));
7416     }
7417 
7418     cache_mode = SSL_CTX_get_session_cache_mode(ssl_ctx);
7419     if (cache_mode != SSL_SESS_CACHE_OFF) {
7420       /* Disable STORING of any new session IDs in the session cache. We DO
7421        * want to allow LOOKUP of session IDs in the session cache, however.
7422        */
7423       long data_cache_mode;
7424       data_cache_mode = SSL_SESS_CACHE_SERVER|SSL_SESS_CACHE_NO_INTERNAL_STORE;
7425       SSL_CTX_set_session_cache_mode(ssl_ctx, data_cache_mode);
7426     }
7427 
7428 #if !defined(OPENSSL_NO_TLSEXT) && defined(TLSEXT_MAXLEN_host_name)
7429     /* Disable any SNI handling for data TLS sessions. */
7430     pr_trace_msg(trace_channel, 5, "ignoring SNI for data connections");
7431     SSL_CTX_set_tlsext_servername_callback(ssl_ctx, NULL);
7432     SSL_CTX_set_tlsext_servername_arg(ssl_ctx, NULL);
7433 #endif /* !OPENSSL_NO_TLSEXT */
7434 
7435 #if defined(PR_USE_OPENSSL_SSL_SESSION_TICKET_CALLBACK)
7436     tls_data_ticket_appdata_len = 0;
7437 
7438     if (session.curr_cmd_id == PR_CMD_APPE_ID ||
7439         session.curr_cmd_id == PR_CMD_STOR_ID ||
7440         session.curr_cmd_id == PR_CMD_STOU_ID) {
7441 
7442       /* Some versions of SSL_do_handshake have a bug in how they handle the
7443        * TLS 1.3 handshake on the server side: after the handshake finishes,
7444        * they automatically send session tickets, even though the client may
7445        * not be expecting data to arrive at this point and sending it could
7446        * cause a deadlock or lost data. This applies at least to OpenSSL 1.1.1c
7447        * and earlier, and the OpenSSL devs currently have no plans to fix it:
7448        *
7449        *  https://github.com/openssl/openssl/issues/7948
7450        *  https://github.com/openssl/openssl/issues/7967
7451        *
7452        * The correct behavior is to wait to send session tickets on the
7453        * first call to SSL_write. (This is what BoringSSL does.) So, we
7454        * programmatically disable sending/renewing TLSv1.3 session tickets
7455        * for the TLS session on data transfers, specifically uploads
7456        * (Issue #959).
7457        *
7458        * Why is this needed for FTPS uploads only, and not downloads or
7459        * directory listings?  An FTPS upload is the only case where we
7460        * are a) the server, and b) in a read-only role.  Thus we are not
7461        * expected to _send_ any TCP data, including session tickets.
7462        */
7463       if (SSL_CTX_set_session_ticket_cb(ssl_ctx, tls_generate_session_ticket_cb,
7464           tls_decrypt_session_ticket_data_upload_cb, NULL) != 1) {
7465         pr_trace_msg(trace_channel, 3, "error setting TLSv1.3 session ticket "
7466           "callback for '%s' data transfer: %s", session.curr_cmd,
7467           tls_get_errors());
7468       }
7469     } else {
7470       /* Restore default session ticket callbacks for any other transfer. */
7471       if (SSL_CTX_set_session_ticket_cb(ssl_ctx, tls_generate_session_ticket_cb,
7472           tls_decrypt_session_ticket_data_xfer_cb, NULL) != 1) {
7473         pr_trace_msg(trace_channel, 3, "error setting TLSv1.3 session ticket "
7474           "callback for '%s' data transfer: %s", session.curr_cmd,
7475           tls_get_errors());
7476       }
7477     }
7478 #endif /* PR_USE_OPENSSL_SSL_SESSION_TICKET_CALLBACK */
7479   }
7480 
7481   retry:
7482 
7483   blocking = tls_get_block(conn);
7484   if (blocking) {
7485     /* Put the connection in non-blocking mode for the duration of the
7486      * TLS handshake.  This lets us handle EAGAIN/retries better (i.e.
7487      * without spinning in a tight loop and consuming the CPU).
7488      */
7489     if (pr_inet_set_nonblock(conn->pool, conn) < 0) {
7490       pr_trace_msg(trace_channel, 3,
7491         "error making %s connection nonblocking: %s",
7492         on_data ? "data" : "ctrl", strerror(errno));
7493     }
7494   }
7495 
7496   pr_signals_handle();
7497 
7498   pr_trace_msg(trace_channel, 17, "calling SSL_accept() on %s conn fd %d",
7499     on_data ? "data" : "ctrl", conn->rfd);
7500   res = SSL_accept(ssl);
7501   xerrno = errno;
7502 
7503   pr_trace_msg(trace_channel, 17, "SSL_accept() returned %d for %s conn fd %d",
7504     res, on_data ? "data" : "ctrl", conn->rfd);
7505 
7506   if (blocking) {
7507     /* Return the connection to blocking mode. */
7508     if (pr_inet_set_block(conn->pool, conn) < 0) {
7509       pr_trace_msg(trace_channel, 3,
7510         "error making %s connection blocking: %s",
7511         on_data ? "data" : "ctrl", strerror(errno));
7512     }
7513   }
7514 
7515   if (res < 1) {
7516     const char *msg = "unable to accept TLS connection";
7517     int errcode = SSL_get_error(ssl, res);
7518 
7519     pr_signals_handle();
7520 
7521     if (tls_handshake_timed_out) {
7522       tls_log("TLS negotiation timed out (%u seconds)", tls_handshake_timeout);
7523       tls_end_sess(ssl, on_data ? session.d : session.c, 0);
7524       return -4;
7525     }
7526 
7527     switch (errcode) {
7528       case SSL_ERROR_WANT_READ:
7529         pr_trace_msg(trace_channel, 17,
7530           "WANT_READ encountered while accepting %s conn on fd %d, "
7531           "waiting to read data", on_data ? "data" : "ctrl", conn->rfd);
7532         tls_readmore(conn->rfd);
7533         goto retry;
7534 
7535       case SSL_ERROR_WANT_WRITE:
7536         pr_trace_msg(trace_channel, 17,
7537           "WANT_WRITE encountered while accepting %s conn on fd %d, "
7538           "waiting to send data", on_data ? "data" : "ctrl", conn->rfd);
7539         tls_writemore(conn->rfd);
7540         goto retry;
7541 
7542       case SSL_ERROR_ZERO_RETURN:
7543         tls_log("%s: TLS connection closed", msg);
7544         break;
7545 
7546       case SSL_ERROR_WANT_X509_LOOKUP:
7547         tls_log("%s: needs X509 lookup", msg);
7548         break;
7549 
7550       case SSL_ERROR_SYSCALL: {
7551         /* Check to see if the OpenSSL error queue has info about this. */
7552         int xerrcode = ERR_get_error();
7553 
7554         if (xerrcode == 0) {
7555           /* The OpenSSL error queue doesn't have any more info, so we'll
7556            * examine the SSL_accept() return value itself.
7557            */
7558 
7559           if (res == 0) {
7560             /* EOF */
7561             tls_log("%s: received EOF that violates protocol", msg);
7562             tls_log("%s: usually this indicates an FTP-aware router, NAT, or "
7563               "firewall interfering with the TLS handshake", msg);
7564 
7565           } else if (res == -1) {
7566             /* Check errno */
7567             tls_log("%s: system call error: [%d] %s", msg, xerrno,
7568               strerror(xerrno));
7569           }
7570 
7571         } else {
7572           tls_log("%s: system call error: %s", msg, tls_get_errors());
7573         }
7574 
7575         break;
7576       }
7577 
7578       case SSL_ERROR_SSL: {
7579         pool *tmp_pool;
7580         unsigned long ssl_errcode = ERR_peek_error();
7581 
7582         tls_log("%s: protocol error: %s", msg, tls_get_errors());
7583 
7584         tmp_pool = make_sub_pool(conn->pool);
7585 
7586         /* The error codes in the OpenSSL error queue are "packed"; we need
7587          * to unpack them to get the reason value.
7588          *
7589          * Try to provide more context for the most commonly ocurring/reported
7590          * handshake errors here.
7591          */
7592 
7593         switch (ERR_GET_REASON(ssl_errcode)) {
7594           case SSL_R_UNKNOWN_PROTOCOL: {
7595             long ssl_opts;
7596             char *proto_str = "";
7597 
7598             ssl_opts = SSL_get_options(ssl);
7599 
7600 #if SSL_OP_NO_SSLv2
7601             if (ssl_opts & SSL_OP_NO_SSLv2) {
7602               proto_str = pstrcat(tmp_pool, proto_str, *proto_str ? ", " : "",
7603                 "SSLv2", NULL);
7604             }
7605 #endif /* SSLv2 */
7606 
7607             if (ssl_opts & SSL_OP_NO_SSLv3) {
7608               proto_str = pstrcat(tmp_pool, proto_str, *proto_str ? ", " : "",
7609                 "SSLv3", NULL);
7610             }
7611 
7612             if (ssl_opts & SSL_OP_NO_TLSv1) {
7613               proto_str = pstrcat(tmp_pool, proto_str, *proto_str ? ", " : "",
7614                 "TLSv1", NULL);
7615             }
7616 
7617 #ifdef SSL_OP_NO_TLSv1_1
7618             if (ssl_opts & SSL_OP_NO_TLSv1_1) {
7619               proto_str = pstrcat(tmp_pool, proto_str, *proto_str ? ", " : "",
7620                 "TLSv1.1", NULL);
7621             }
7622 #endif /* TLSv1.1 */
7623 
7624 #ifdef SSL_OP_NO_TLSv1_2
7625             if (ssl_opts & SSL_OP_NO_TLSv1_2) {
7626               proto_str = pstrcat(tmp_pool, proto_str, *proto_str ? ", " : "",
7627                 "TLSv1.2", NULL);
7628             }
7629 #endif /* TLSv1.2 */
7630 
7631 #ifdef SSL_OP_NO_TLSv1_3
7632             if (ssl_opts & SSL_OP_NO_TLSv1_3) {
7633               proto_str = pstrcat(tmp_pool, proto_str, *proto_str ? ", " : "",
7634                 "TLSv1.3", NULL);
7635             }
7636 #endif /* TLSv1.3 */
7637 
7638             tls_log("%s: perhaps client requested disabled TLS protocol "
7639               "version: %s", msg, proto_str);
7640             break;
7641           }
7642 
7643           case SSL_R_NO_SHARED_CIPHER: {
7644             tls_log("%s: client does not support any cipher from "
7645               "'TLSCipherSuite %s' (see `openssl ciphers %s` for full list)",
7646               msg, tls_cipher_suite, tls_cipher_suite);
7647             break;
7648           }
7649 
7650           case SSL_R_PEER_DID_NOT_RETURN_A_CERTIFICATE: {
7651             if (tls_flags & TLS_SESS_VERIFY_CLIENT_REQUIRED) {
7652               tls_log("%s: client did not provide certificate, but one is "
7653                 "required via 'TLSVerifyClient on'", msg);
7654             }
7655             break;
7656           }
7657 
7658 #if defined(SSL_R_VERSION_TOO_LOW)
7659           case SSL_R_VERSION_TOO_LOW: {
7660             int client_version;
7661 
7662             client_version = SSL_client_version(ssl);
7663             switch (client_version) {
7664 # if defined(SSL3_VERSION) && defined(OPENSSL_NO_SSL3)
7665               case SSL3_VERSION:
7666                 tls_log("%s: %s lacks support for client requested TLS "
7667                   "protocol version: %s", msg, OPENSSL_VERSION_TEXT,
7668                   SSL_get_version(ssl));
7669                 break;
7670 # endif /* SSLv3 and OPENSSL_NO_SSL3 */
7671 
7672 # if defined(TLS1_VERSION) && defined(OPENSSL_NO_TLS1)
7673               case TLS1_VERSION:
7674                 tls_log("%s: %s lacks support for client requested TLS "
7675                   "protocol version: %s", msg, OPENSSL_VERSION_TEXT,
7676                   SSL_get_version(ssl));
7677                 break;
7678 # endif /* TLSv1 and OPENSSL_NO_TLS1 */
7679 
7680 # if defined(TLS1_1_VERSION) && defined(OPENSSL_NO_TLS1_1)
7681               case TLS1_1_VERSION:
7682                 tls_log("%s: %s lacks support for client requested TLS "
7683                   "protocol version: %s", msg, OPENSSL_VERSION_TEXT,
7684                   SSL_get_version(ssl));
7685                 break;
7686 # endif /* TLSv1.1 and OPENSSL_NO_TLS1_1 */
7687 
7688 # if defined(TLS1_2_VERSION) && defined(OPENSSL_NO_TLS1_2)
7689               case TLS1_2_VERSION:
7690                 tls_log("%s: %s lacks support for client requested TLS "
7691                   "protocol version: %s", msg, OPENSSL_VERSION_TEXT,
7692                   SSL_get_version(ssl));
7693                 break;
7694 # endif /* TLSv1.2 and OPENSSL_NO_TLS1_2 */
7695 
7696 # if defined(TLS1_3_VERSION) && defined(OPENSSL_NO_TLS1_3)
7697               case TLS1_3_VERSION:
7698                 tls_log("%s: %s lacks support for client requested TLS "
7699                   "protocol version: %s", msg, OPENSSL_VERSION_TEXT,
7700                   SSL_get_version(ssl));
7701                 break;
7702 # endif /* TLSv1.3 and OPENSSL_NO_TLS1_3 */
7703 
7704               default:
7705                 tls_log("%s: perhaps client requested unsupported TLS protocol "
7706                   "version: %s", msg, SSL_get_version(ssl));
7707             }
7708             break;
7709           }
7710 #endif /* SSL_R_VERSION_TOO_LOW */
7711 
7712           default:
7713             break;
7714         }
7715 
7716         destroy_pool(tmp_pool);
7717         break;
7718       }
7719     }
7720 
7721     if (on_data) {
7722       pr_event_generate("mod_tls.data-handshake-failed", &errcode);
7723 
7724     } else {
7725       pr_event_generate("mod_tls.ctrl-handshake-failed", &errcode);
7726     }
7727 
7728     tls_end_sess(ssl, on_data ? session.d : session.c, 0);
7729     return -3;
7730   }
7731 
7732   pr_trace_msg(trace_channel, 17,
7733     "TLS handshake on %s conn fd %d COMPLETED", on_data ? "data" : "ctrl",
7734     conn->rfd);
7735 
7736   if (on_data) {
7737     /* Disable TCP_NODELAY, now that the handshake is done. */
7738     if (pr_inet_set_proto_nodelay(conn->pool, conn, 0) < 0) {
7739       pr_trace_msg(trace_channel, 9,
7740         "error disabling TCP_NODELAY on data conn: %s", strerror(errno));
7741     }
7742 
7743     /* Re-enable TCP_CORK (aka TCP_NOPUSH), now that the handshake is done. */
7744     if (pr_inet_set_proto_cork(conn->wfd, 1) < 0) {
7745       pr_trace_msg(trace_channel, 9,
7746         "error re-enabling TCP_CORK on data conn: %s", strerror(errno));
7747     }
7748 
7749     if (cache_mode != SSL_SESS_CACHE_OFF) {
7750       /* Restore the previous session cache mode. */
7751       SSL_CTX_set_session_cache_mode(ssl_ctx, cache_mode);
7752     }
7753 
7754     (void) BIO_set_write_buf_size(wbio,
7755       TLS_DATA_ADAPTIVE_WRITE_MIN_BUFFER_SIZE);
7756     tls_data_adaptive_bytes_written_ms = 0L;
7757     tls_data_adaptive_bytes_written_count = 0;
7758   }
7759 
7760   /* Disable the handshake timer. */
7761   pr_timer_remove(tls_handshake_timer_id, &tls_module);
7762 
7763 #if defined(PR_USE_OPENSSL_NPN)
7764   /* Which NPN protocol was selected, if any? */
7765   {
7766     const unsigned char *npn = NULL;
7767     unsigned int npn_len = 0;
7768 
7769     SSL_get0_next_proto_negotiated(ssl, &npn, &npn_len);
7770     if (npn != NULL &&
7771         npn_len > 0) {
7772       pr_trace_msg(trace_channel, 9,
7773         "negotiated NPN '%*s'", npn_len, npn);
7774 
7775     } else {
7776       pr_trace_msg(trace_channel, 9, "%s", "no NPN negotiated");
7777     }
7778   }
7779 #endif /* NPN */
7780 
7781 #if defined(PR_USE_OPENSSL_ALPN)
7782   /* Which ALPN protocol was selected, if any? */
7783   {
7784     const unsigned char *alpn = NULL;
7785     unsigned int alpn_len = 0;
7786 
7787     SSL_get0_alpn_selected(ssl, &alpn, &alpn_len);
7788     if (alpn != NULL &&
7789         alpn_len > 0) {
7790       pr_trace_msg(trace_channel, 9,
7791         "selected ALPN '%*s'", alpn_len, alpn);
7792     } else {
7793       pr_trace_msg(trace_channel, 9, "%s", "no ALPN selected");
7794     }
7795   }
7796 #endif /* ALPN */
7797 
7798   /* Manually update the raw bytes counters with the network IO from the
7799    * TLS handshake.
7800    */
7801   session.total_raw_in += (BIO_number_read(rbio) +
7802     BIO_number_read(wbio));
7803   session.total_raw_out += (BIO_number_written(rbio) +
7804     BIO_number_written(wbio));
7805 
7806   /* Stash the SSL object in the pointers of the correct NetIO streams. */
7807   if (conn == session.c) {
7808     pr_buffer_t *strm_buf;
7809 
7810     ctrl_ssl = ssl;
7811 
7812     if (pr_table_add(tls_ctrl_rd_nstrm->notes,
7813         pstrdup(tls_ctrl_rd_nstrm->strm_pool, TLS_NETIO_NOTE),
7814         ssl, sizeof(SSL *)) < 0) {
7815       if (errno != EEXIST) {
7816         tls_log("error stashing '%s' note on ctrl read stream: %s",
7817           TLS_NETIO_NOTE, strerror(errno));
7818       }
7819     }
7820 
7821     if (pr_table_add(tls_ctrl_wr_nstrm->notes,
7822         pstrdup(tls_ctrl_wr_nstrm->strm_pool, TLS_NETIO_NOTE),
7823         ssl, sizeof(SSL *)) < 0) {
7824       if (errno != EEXIST) {
7825         tls_log("error stashing '%s' note on ctrl write stream: %s",
7826           TLS_NETIO_NOTE, strerror(errno));
7827       }
7828     }
7829 
7830 #if OPENSSL_VERSION_NUMBER >= 0x009080dfL
7831     if (SSL_get_secure_renegotiation_support(ssl) == 1) {
7832       /* If the peer indicates that it can support secure renegotiations, log
7833        * this fact for reference.
7834        *
7835        * Note that while we could use this fact to automatically enable the
7836        * AllowClientRenegotiations TLSOption, in light of CVE-2011-1473
7837        * (where malicious SSL/TLS clients can abuse the fact that session
7838        * renegotiations are more computationally intensive for servers than
7839        * for clients and repeatedly request renegotiations to create a
7840        * denial of service attach), we won't enable AllowClientRenegotiations
7841        * programmatically.  The admin will still need to explicitly configure
7842        * that.
7843        */
7844       tls_log("%s", "client supports secure renegotiations");
7845     }
7846 #endif /* OpenSSL 0.9.8m and later */
7847 
7848     /* Clear any data from the NetIO stream buffers which may have been read
7849      * in before the SSL/TLS handshake occurred (Bug#3624).
7850      */
7851     strm_buf = tls_ctrl_rd_nstrm->strm_buf;
7852     if (strm_buf != NULL) {
7853       strm_buf->current = NULL;
7854       strm_buf->remaining = strm_buf->buflen;
7855     }
7856 
7857   } else if (conn == session.d) {
7858     pr_buffer_t *strm_buf;
7859 
7860     if (pr_table_add(tls_data_rd_nstrm->notes,
7861         pstrdup(tls_data_rd_nstrm->strm_pool, TLS_NETIO_NOTE),
7862         ssl, sizeof(SSL *)) < 0) {
7863       if (errno != EEXIST) {
7864         tls_log("error stashing '%s' note on data read stream: %s",
7865           TLS_NETIO_NOTE, strerror(errno));
7866       }
7867     }
7868 
7869     if (pr_table_add(tls_data_wr_nstrm->notes,
7870         pstrdup(tls_data_wr_nstrm->strm_pool, TLS_NETIO_NOTE),
7871         ssl, sizeof(SSL *)) < 0) {
7872       if (errno != EEXIST) {
7873         tls_log("error stashing '%s' note on data write stream: %s",
7874           TLS_NETIO_NOTE, strerror(errno));
7875       }
7876     }
7877 
7878     /* Clear any data from the NetIO stream buffers which may have been read
7879      * in before the SSL/TLS handshake occurred (Bug#3624).
7880      */
7881     strm_buf = tls_data_rd_nstrm->strm_buf;
7882     if (strm_buf != NULL) {
7883       strm_buf->current = NULL;
7884       strm_buf->remaining = strm_buf->buflen;
7885     }
7886   }
7887 
7888 #if OPENSSL_VERSION_NUMBER == 0x009080cfL
7889   /* In OpenSSL-0.9.8l, SSL session renegotiations are automatically
7890    * disabled.  Thus if the admin explicitly configured support for
7891    * client-initiated renegotiations via the AllowClientRenegotiations
7892    * TLSOption, then we need to do some hackery to enable renegotiations.
7893    */
7894   if (tls_opts & TLS_OPT_ALLOW_CLIENT_RENEGOTIATIONS) {
7895     ssl->s3->flags |= SSL3_FLAGS_ALLOW_UNSAFE_LEGACY_RENEGOTIATION;
7896   }
7897 #endif
7898 
7899   /* TLS handshake on the control channel... */
7900   if (on_data == FALSE) {
7901     int reused;
7902 
7903     subj = tls_get_subj_name(ctrl_ssl);
7904     if (subj != NULL) {
7905       tls_log("Client: %s", subj);
7906     }
7907 
7908     if (tls_flags & TLS_SESS_VERIFY_CLIENT_REQUIRED) {
7909       /* Now we can go on with our post-handshake, application level
7910        * requirement checks.
7911        */
7912       if (tls_check_client_cert(ssl, conn) < 0) {
7913         tls_end_sess(ssl, session.c, 0);
7914         ctrl_ssl = NULL;
7915         return -1;
7916       }
7917     }
7918 
7919     reused = SSL_session_reused(ssl);
7920 
7921     tls_log("%s connection accepted, using cipher %s (%d bits%s)",
7922       SSL_get_version(ssl), SSL_get_cipher_name(ssl),
7923       SSL_get_cipher_bits(ssl, NULL),
7924       reused > 0 ? ", resumed session" : "");
7925 
7926     /* Setup the TLS environment variables and notes. */
7927     tls_setup_environ(session.pool, ssl);
7928     tls_setup_notes(session.pool, ssl);
7929 
7930     if (reused > 0) {
7931       pr_log_writefile(tls_logfd, MOD_TLS_VERSION, "%s",
7932         "client reused previous TLS session for control connection");
7933     }
7934 
7935   /* TLS handshake on the data channel... */
7936   } else {
7937 
7938     /* We won't check for session reuse for data connections when either
7939      * a) the NoSessionReuseRequired TLSOption has been configured, or
7940      * b) the CCC command has been used (Bug#3465).
7941      */
7942     if (!(tls_opts & TLS_OPT_NO_SESSION_REUSE_REQUIRED) &&
7943         !(tls_flags & TLS_SESS_HAVE_CCC)) {
7944       int reused;
7945       SSL_SESSION *ctrl_sess;
7946 
7947       /* Ensure that the following conditions are met:
7948        *
7949        *   1. The client reused an existing TLS session
7950        *   2. The reused TLS session matches the TLS session from the control
7951        *      connection.
7952        *
7953        * Make sure we handle session tickets, too, especially for TLSv1.3.
7954        *
7955        * Shutdown the TLS session unless the conditions are met.  By
7956        * requiring these conditions, we make sure that the client which is
7957        * talking to us on the control connection is indeed the same client
7958        * that is using this data connection.  Without these checks, a
7959        * malicious client might be able to hijack/steal the data transfer.
7960        */
7961 
7962       reused = SSL_session_reused(ssl);
7963       if (reused != 1) {
7964         tls_log("%s", "client did not reuse TLS session, rejecting data "
7965           "connection (see the NoSessionReuseRequired TLSOptions parameter)");
7966         tls_end_sess(ssl, session.d, 0);
7967         pr_table_remove(tls_data_rd_nstrm->notes, TLS_NETIO_NOTE, NULL);
7968         pr_table_remove(tls_data_wr_nstrm->notes, TLS_NETIO_NOTE, NULL);
7969         return -1;
7970       }
7971 
7972       tls_log("%s", "client reused TLS session for data connection");
7973 
7974       ctrl_sess = SSL_get_session(ctrl_ssl);
7975       if (ctrl_sess != NULL) {
7976         SSL_SESSION *data_sess;
7977 
7978         data_sess = SSL_get_session(ssl);
7979         if (data_sess != NULL) {
7980           int matching_sess = -1;
7981           long sess_created, sess_expires;
7982           time_t now;
7983 
7984           matching_sess = tls_compare_session_ids(ctrl_sess, data_sess);
7985 
7986 #ifdef TLS1_3_VERSION
7987           /* TLSv1.3 sessions will show session reuse, but NOT matching session
7988            * IDs.  Why?  TLSv1.3 completely redid session resumption, and now
7989            * favors session tickets (and stateless servers) rather than
7990            * session IDs (and stateful server session caches).
7991            *
7992            * To prove session reuse via TLSv1.3 session tickets, then, we use
7993            * ticket appdata to generate a random "FTP session ID" that we stick
7994            * in the control session tickets; the data session tickets presented
7995            * should have the exact same appdata, if they are coming from our
7996            * expected control session.
7997            *
7998            * However, we cannot just assume that session tickets will be used
7999            * only for TLSv1.3 sessions.  It is possible that session tickets,
8000            * rather than session IDs, will be used for TLSv1.2 and earlier
8001            * sessions as well.
8002            */
8003           if (matching_sess != 0) {
8004 
8005 # if defined(PR_USE_OPENSSL_SSL_SESSION_TICKET_CALLBACK)
8006             if (tls_ctrl_ticket_appdata_len > 0 &&
8007                 tls_data_ticket_appdata_len > 0 &&
8008                 tls_ctrl_ticket_appdata_len == tls_data_ticket_appdata_len) {
8009               if (pr_trace_get_level(trace_channel) >= 19) {
8010                 register unsigned int i;
8011                 unsigned char *ticket_appdata;
8012                 BIO *bio;
8013                 char *text = NULL;
8014                 long text_len = 0;
8015 
8016                 bio = BIO_new(BIO_s_mem());
8017                 BIO_puts(bio, "comparing control ticket appdata (");
8018                 ticket_appdata = tls_ctrl_ticket_appdata;
8019                 for (i = 0; i < tls_ctrl_ticket_appdata_len; i++) {
8020                   BIO_printf(bio, "%02x", ticket_appdata[i]);
8021                 }
8022 
8023                 BIO_puts(bio, ") and data ticket appdata (");
8024                 ticket_appdata = tls_data_ticket_appdata;
8025                 for (i = 0; i < tls_data_ticket_appdata_len; i++) {
8026                   BIO_printf(bio, "%02x", ticket_appdata[i]);
8027                 }
8028                 BIO_puts(bio, ")");
8029 
8030                 text_len = BIO_get_mem_data(bio, &text);
8031                 if (text != NULL) {
8032                   text[text_len] = '\0';
8033                   pr_trace_msg(trace_channel, 19, "%.*s", (int) text_len, text);
8034                 }
8035 
8036                 BIO_free(bio);
8037               }
8038 
8039               matching_sess = memcmp(tls_ctrl_ticket_appdata,
8040                 tls_data_ticket_appdata, tls_ctrl_ticket_appdata_len);
8041               if (matching_sess != 0) {
8042                 pr_trace_msg(trace_channel, 9,
8043                   "mismatched control/data ticket appdata for %s sessions",
8044                   SSL_get_version(ssl));
8045               }
8046 
8047             } else {
8048               pr_trace_msg(trace_channel, 9,
8049                 "mismatched control/data ticket appdata (ctrl = %lu bytes, "
8050                 "data = %lu bytes) for %s sessions",
8051                 (unsigned long) tls_ctrl_ticket_appdata_len,
8052                 (unsigned long) tls_data_ticket_appdata_len,
8053                 SSL_get_version(ssl));
8054             }
8055 # else
8056             pr_trace_msg(trace_channel, 9,
8057              "ignoring mismatched control/data session IDs for %s sessions, "
8058              "for now", SSL_get_version(ssl));
8059             matching_sess = 0;
8060 # endif /* PR_USE_OPENSSL_SSL_SESSION_TICKET_CALLBACK */
8061           }
8062 #endif /* TLS1_3_VERSION */
8063 
8064           if (matching_sess != 0) {
8065             tls_log("Client did not reuse TLS session from control channel, "
8066               "rejecting data connection (see the NoSessionReuseRequired "
8067               "TLSOptions parameter)");
8068             tls_end_sess(ssl, session.d, 0);
8069             pr_table_remove(tls_data_rd_nstrm->notes, TLS_NETIO_NOTE, NULL);
8070             pr_table_remove(tls_data_wr_nstrm->notes, TLS_NETIO_NOTE, NULL);
8071             return -1;
8072           }
8073 
8074           /* The TLS session ID for data and control channels matches.
8075            *
8076            * Many sites are using mod_tls such that OpenSSL's internal
8077            * session caching is being used.  And by default, that
8078            * cache expires sessions after 300 secs (5 min).  It's possible
8079            * that the control channel TLS session will expire soon;
8080            * unless the client renegotiates that session, the internal
8081            * cache will expire the cached session, and the next data
8082            * transfer could fail (since mod_tls won't allow that session ID
8083            * to be reused again, as it will no longer be in the session
8084            * cache).
8085            *
8086            * Try to warn if this is about to happen.
8087            */
8088 
8089           sess_created = SSL_SESSION_get_time(ctrl_sess);
8090           sess_expires = SSL_SESSION_get_timeout(ctrl_sess);
8091           now = time(NULL);
8092 
8093           if ((sess_created + sess_expires) >= now) {
8094             unsigned long remaining;
8095 
8096             remaining = (unsigned long) ((sess_created + sess_expires) - now);
8097 
8098             if (remaining <= 60) {
8099               tls_log("control channel TLS session expires in %lu secs "
8100                 "(%lu session cache expiration)", remaining, sess_expires);
8101               tls_log("%s", "Consider using 'TLSSessionCache internal:' to "
8102                 "increase the session cache expiration if necessary, or "
8103                 "renegotiate the control channel TLS session");
8104             }
8105           }
8106 
8107         } else {
8108           /* This should never happen, so log if it does. */
8109           tls_log("%s", "BUG: unable to determine whether client reused TLS "
8110             "session: SSL_get_session() for data connection returned NULL");
8111           tls_log("%s", "rejecting data connection (see TLSOption NoSessionReuseRequired)");
8112           tls_end_sess(ssl, session.d, 0);
8113           pr_table_remove(tls_data_rd_nstrm->notes, TLS_NETIO_NOTE, NULL);
8114           pr_table_remove(tls_data_wr_nstrm->notes, TLS_NETIO_NOTE, NULL);
8115           return -1;
8116         }
8117 
8118       } else {
8119         /* This should never happen, so log if it does. */
8120         tls_log("%s", "BUG: unable to determine whether client reused TLS "
8121           "session: SSL_get_session() for control connection returned NULL!");
8122         tls_log("%s", "rejecting data connection (see TLSOption NoSessionReuseRequired)");
8123         tls_end_sess(ssl, session.d, 0);
8124         pr_table_remove(tls_data_rd_nstrm->notes, TLS_NETIO_NOTE, NULL);
8125         pr_table_remove(tls_data_wr_nstrm->notes, TLS_NETIO_NOTE, NULL);
8126         return -1;
8127       }
8128     }
8129 
8130     /* Only be verbose with the first TLS data connection, otherwise there
8131      * might be too much noise.
8132      */
8133     if (!logged_data) {
8134       int reused;
8135 
8136       reused = SSL_session_reused(ssl);
8137 
8138       tls_log("%s data connection accepted, using cipher %s (%d bits%s)",
8139         SSL_get_version(ssl), SSL_get_cipher_name(ssl),
8140         SSL_get_cipher_bits(ssl, NULL),
8141         reused > 0 ? ", resumed session" : "");
8142       logged_data = TRUE;
8143     }
8144   }
8145 
8146   return 0;
8147 }
8148 
8149 static int tls_connect(conn_t *conn) {
8150   int blocking, res = 0, xerrno = 0;
8151   char *subj = NULL;
8152   SSL *ssl = NULL;
8153   BIO *rbio = NULL, *wbio = NULL;
8154 
8155   if (ssl_ctx == NULL) {
8156     tls_log("%s", "unable to start session: null SSL_CTX");
8157     return -1;
8158   }
8159 
8160   ssl = SSL_new(ssl_ctx);
8161   if (ssl == NULL) {
8162     tls_log("error: unable to start session: %s",
8163       ERR_error_string(ERR_get_error(), NULL));
8164     return -2;
8165   }
8166 
8167   /* Make sure our SSL object uses client methods (Issue#618). */
8168   if (SSL_set_ssl_method(ssl, SSLv23_client_method()) != 1) {
8169     tls_log("error: unable to set client methods: %s",
8170       ERR_error_string(ERR_get_error(), NULL));
8171     SSL_free(ssl);
8172     return -2;
8173   }
8174 
8175   /* We deliberately set SSL_VERIFY_NONE here, so that we get to
8176    * determine how to handle the server cert verification result ourselves.
8177    */
8178   SSL_set_verify(ssl, SSL_VERIFY_NONE, NULL);
8179 
8180   /* This works with either rfd or wfd (I hope). */
8181   rbio = BIO_new_socket(conn->rfd, FALSE);
8182   wbio = BIO_new_socket(conn->rfd, FALSE);
8183   SSL_set_bio(ssl, rbio, wbio);
8184 
8185   /* If configured, set a timer for the handshake. */
8186   if (tls_handshake_timeout) {
8187     tls_handshake_timed_out = FALSE;
8188     tls_handshake_timer_id = pr_timer_add(tls_handshake_timeout, -1,
8189       &tls_module, tls_handshake_timeout_cb, "SSL/TLS handshake");
8190   }
8191 
8192   /* Make sure that TCP_NODELAY is enabled for the handshake. */
8193   (void) pr_inet_set_proto_nodelay(conn->pool, conn, 1);
8194 
8195   retry:
8196 
8197   blocking = tls_get_block(conn);
8198   if (blocking) {
8199     /* Put the connection in non-blocking mode for the duration of the
8200      * TLS handshake.  This lets us handle EAGAIN/retries better (i.e.
8201      * without spinning in a tight loop and consuming the CPU).
8202      */
8203     if (pr_inet_set_nonblock(conn->pool, conn) < 0) {
8204       pr_trace_msg(trace_channel, 3,
8205         "error making connection nonblocking: %s", strerror(errno));
8206     }
8207   }
8208 
8209   pr_signals_handle();
8210   res = SSL_connect(ssl);
8211   xerrno = errno;
8212 
8213   if (blocking) {
8214     /* Return the connection to blocking mode. */
8215     if (pr_inet_set_block(conn->pool, conn) < 0) {
8216       pr_trace_msg(trace_channel, 3,
8217         "error making connection blocking: %s", strerror(errno));
8218     }
8219   }
8220 
8221   if (res < 1) {
8222     const char *msg = "unable to connect using TLS connection";
8223     int errcode = SSL_get_error(ssl, res);
8224 
8225     pr_signals_handle();
8226 
8227     if (tls_handshake_timed_out) {
8228       tls_log("TLS negotiation timed out (%u seconds)", tls_handshake_timeout);
8229       tls_end_sess(ssl, conn, 0);
8230       return -4;
8231     }
8232 
8233     switch (errcode) {
8234       case SSL_ERROR_WANT_READ:
8235         pr_trace_msg(trace_channel, 17,
8236           "WANT_READ encountered while connecting on fd %d, "
8237           "waiting to read data", conn->rfd);
8238         tls_readmore(conn->rfd);
8239         goto retry;
8240 
8241       case SSL_ERROR_WANT_WRITE:
8242         pr_trace_msg(trace_channel, 17,
8243           "WANT_WRITE encountered while connecting on fd %d, "
8244           "waiting to read data", conn->rfd);
8245         tls_writemore(conn->rfd);
8246         goto retry;
8247 
8248       case SSL_ERROR_ZERO_RETURN:
8249         tls_log("%s: TLS connection closed", msg);
8250         break;
8251 
8252       case SSL_ERROR_WANT_X509_LOOKUP:
8253         tls_log("%s: needs X509 lookup", msg);
8254         break;
8255 
8256       case SSL_ERROR_SYSCALL: {
8257         /* Check to see if the OpenSSL error queue has info about this. */
8258         int xerrcode = ERR_get_error();
8259 
8260         if (xerrcode == 0) {
8261           /* The OpenSSL error queue doesn't have any more info, so we'll
8262            * examine the SSL_connect() return value itself.
8263            */
8264 
8265           if (res == 0) {
8266             /* EOF */
8267             tls_log("%s: received EOF that violates protocol", msg);
8268 
8269           } else if (res == -1) {
8270             /* Check errno */
8271             tls_log("%s: system call error: [%d] %s", msg, xerrno,
8272               strerror(xerrno));
8273           }
8274 
8275         } else {
8276           tls_log("%s: system call error: %s", msg, tls_get_errors());
8277         }
8278 
8279         break;
8280       }
8281 
8282       case SSL_ERROR_SSL:
8283         tls_log("%s: protocol error: %s", msg, tls_get_errors());
8284         break;
8285     }
8286 
8287     pr_event_generate("mod_tls.data-handshake-failed", &errcode);
8288 
8289     tls_end_sess(ssl, conn, 0);
8290     return -3;
8291   }
8292 
8293   /* Disable TCP_NODELAY, now that the handshake is done. */
8294   (void) pr_inet_set_proto_nodelay(conn->pool, conn, 0);
8295 
8296   /* Disable the handshake timer. */
8297   pr_timer_remove(tls_handshake_timer_id, &tls_module);
8298 
8299   /* Manually update the raw bytes counters with the network IO from the
8300    * TLS handshake.
8301    */
8302   session.total_raw_in += (BIO_number_read(rbio) +
8303     BIO_number_read(wbio));
8304   session.total_raw_out += (BIO_number_written(rbio) +
8305     BIO_number_written(wbio));
8306 
8307   /* Stash the SSL object in the pointers of the correct NetIO streams. */
8308   if (conn == session.d) {
8309     pr_buffer_t *strm_buf;
8310 
8311     if (pr_table_add(tls_data_rd_nstrm->notes,
8312         pstrdup(tls_data_rd_nstrm->strm_pool, TLS_NETIO_NOTE),
8313         ssl, sizeof(SSL *)) < 0) {
8314       if (errno != EEXIST) {
8315         tls_log("error stashing '%s' note on data read stream: %s",
8316           TLS_NETIO_NOTE, strerror(errno));
8317       }
8318     }
8319 
8320     if (pr_table_add(tls_data_wr_nstrm->notes,
8321         pstrdup(tls_data_wr_nstrm->strm_pool, TLS_NETIO_NOTE),
8322         ssl, sizeof(SSL *)) < 0) {
8323       if (errno != EEXIST) {
8324         tls_log("error stashing '%s' note on data write stream: %s",
8325           TLS_NETIO_NOTE, strerror(errno));
8326       }
8327     }
8328 
8329     /* Clear any data from the NetIO stream buffers which may have been read
8330      * in before the SSL/TLS handshake occurred (Bug#3624).
8331      */
8332     strm_buf = tls_data_rd_nstrm->strm_buf;
8333     if (strm_buf != NULL) {
8334       strm_buf->current = NULL;
8335       strm_buf->remaining = strm_buf->buflen;
8336     }
8337   }
8338 
8339 #if OPENSSL_VERSION_NUMBER == 0x009080cfL
8340   /* In OpenSSL-0.9.8l, SSL session renegotiations are automatically
8341    * disabled.  Thus if the admin explicitly configured support for
8342    * client-initiated renegotiations via the AllowClientRenegotiations
8343    * TLSOption, then we need to do some hackery to enable renegotiations.
8344    */
8345   if (tls_opts & TLS_OPT_ALLOW_CLIENT_RENEGOTIATIONS) {
8346     ssl->s3->flags |= SSL3_FLAGS_ALLOW_UNSAFE_LEGACY_RENEGOTIATION;
8347   }
8348 #endif
8349 
8350   subj = tls_get_subj_name(ssl);
8351   if (subj) {
8352     tls_log("Server: %s", subj);
8353   }
8354 
8355   if (tls_check_server_cert(ssl, conn) < 0) {
8356     tls_end_sess(ssl, conn, 0);
8357     return -1;
8358   }
8359 
8360   tls_log("%s connection created, using cipher %s (%d bits)",
8361     SSL_get_version(ssl), SSL_get_cipher_name(ssl),
8362     SSL_get_cipher_bits(ssl, NULL));
8363 
8364   return 0;
8365 }
8366 
8367 static void tls_cleanup(int flags) {
8368 
8369 #if OPENSSL_VERSION_NUMBER > 0x000907000L
8370   if (tls_crypto_device != NULL) {
8371     ENGINE_cleanup();
8372     tls_crypto_device = NULL;
8373   }
8374 #endif
8375 
8376   if (tls_crl_store != NULL) {
8377     X509_STORE_free(tls_crl_store);
8378     tls_crl_store = NULL;
8379   }
8380 
8381   if (ssl_ctx != NULL) {
8382     SSL_CTX_free(ssl_ctx);
8383     ssl_ctx = NULL;
8384   }
8385 
8386   /* Close the session cache only AFTER the SSL context has been
8387    * freed/deleted (Issue #795).
8388    */
8389   tls_sess_cache_close();
8390   tls_ocsp_cache_close();
8391 
8392   if (tls_tmp_dhs != NULL) {
8393     register unsigned int i;
8394     DH **dhs;
8395 
8396     dhs = tls_tmp_dhs->elts;
8397     for (i = 0; i < tls_tmp_dhs->nelts; i++) {
8398       DH_free(dhs[i]);
8399     }
8400 
8401     tls_tmp_dhs = NULL;
8402   }
8403 
8404   if (tls_tmp_rsa != NULL) {
8405     RSA_free(tls_tmp_rsa);
8406     tls_tmp_rsa = NULL;
8407   }
8408 
8409   if (!(flags & TLS_CLEANUP_FL_SESS_INIT)) {
8410     ERR_free_strings();
8411 
8412 #if OPENSSL_VERSION_NUMBER >= 0x10000001L
8413     /* The ERR_remove_state(0) usage is deprecated due to thread ID
8414      * differences among platforms; see the OpenSSL-1.0.0 CHANGES file
8415      * for details.  So for new enough OpenSSL installations, use the
8416      * proper way to clear the error queue state.
8417      */
8418     ERR_remove_thread_state(NULL);
8419 #else
8420     ERR_remove_state(0);
8421 #endif /* OpenSSL prior to 1.0.0-beta1 */
8422 
8423     EVP_cleanup();
8424 
8425   } else {
8426     /* Only call EVP_cleanup() et al if other OpenSSL-using modules are not
8427      * present.  If we called EVP_cleanup() here during session
8428      * initialization, and other modules want to use OpenSSL, we may
8429      * be depriving those modules of OpenSSL functionality.
8430      *
8431      * At the moment, the modules known to use OpenSSL are:
8432      *   mod_auth_otp
8433      *   mod_digest
8434      *   mod_ldap
8435      *   mod_proxy
8436      *   mod_sftp
8437      *   mod_sql
8438      *   mod_sql_passwd
8439      */
8440     if (pr_module_get("mod_auth_otp.c") == NULL &&
8441         pr_module_get("mod_digest.c") == NULL &&
8442         pr_module_get("mod_ldap.c") == NULL &&
8443         pr_module_get("mod_proxy.c") == NULL &&
8444         pr_module_get("mod_sftp.c") == NULL &&
8445         pr_module_get("mod_sql.c") == NULL &&
8446         pr_module_get("mod_sql_passwd.c") == NULL) {
8447       ERR_free_strings();
8448 
8449 #if OPENSSL_VERSION_NUMBER >= 0x10000001L
8450       /* The ERR_remove_state(0) usage is deprecated due to thread ID
8451        * differences among platforms; see the OpenSSL-1.0.0c CHANGES file
8452        * for details.  So for new enough OpenSSL installations, use the
8453        * proper way to clear the error queue state.
8454        */
8455       ERR_remove_thread_state(NULL);
8456 #else
8457       ERR_remove_state(0);
8458 #endif /* OpenSSL prior to 1.0.0-beta1 */
8459 
8460       EVP_cleanup();
8461     }
8462   }
8463 }
8464 
8465 /* Returns TRUE for SSL data, FALSE for FTP data, and -1 on error.
8466  *
8467  * First, we want for readable data on the socket via select(2).  Then
8468  * we use recv(2) to peek at the data; we only need three bytes.  Why only
8469  * three bytes?  According to the TLS RFCs on SSL record layering, each
8470  * well-formed SSL record starts with:
8471  *
8472  *    struct {
8473  *        uint8 major;
8474  *        uint8 minor;
8475  *    } ProtocolVersion;
8476  *
8477  *    enum {
8478  *        change_cipher_spec(20), alert(21), handshake(22),
8479  *        application_data(23), (255)
8480  *    } ContentType;
8481  *
8482  *    struct {
8483  *        ContentType type;
8484  *        ProtocolVersion version;
8485  *
8486  * It helps that the first byte, if an SSL record, will be 20-23, or 255.
8487  * The printable ASCII range, which would be used for an FTP command, starts
8488  * at 32 (sp).  We read three bytes to include the protocol version, to
8489  * help increase confidence in our guess at whether these data are a well-
8490  * formed SSL record, or an FTP command.
8491  */
8492 static int peek_is_ssl_data(int fd) {
8493   register unsigned int i;
8494   int res;
8495   fd_set rfds;
8496   struct timeval tv;
8497   ssize_t len;
8498   unsigned char buf[3];
8499 
8500   /* We'll wait up to 5 secs, or until interrupted, for the next data. */
8501   tv.tv_sec = 5;
8502   tv.tv_usec = 0;
8503 
8504   pr_trace_msg(trace_channel, 20, "peeking at next data for fd %d, for %d secs",
8505     fd, (int) tv.tv_sec);
8506 
8507   FD_ZERO(&rfds);
8508   FD_SET(fd, &rfds);
8509 
8510   res = select(fd + 1, &rfds, NULL, NULL, &tv);
8511   while (res < 0) {
8512     int xerrno = errno;
8513 
8514     if (xerrno == EINTR) {
8515       pr_signals_handle();
8516       res = select(fd + 1, &rfds, NULL, NULL, &tv);
8517       continue;
8518     }
8519 
8520     pr_trace_msg(trace_channel, 20,
8521       "error waiting for next data on fd %d: %s", fd, strerror(xerrno));
8522     errno = xerrno;
8523     return -1;
8524   }
8525 
8526   if (res == 0) {
8527     /* Timed out.  Error on the side of optimism, and assume the next data
8528      * will be an SSL record.  This is what mod_tls would do, if we were not
8529      * peeking.
8530      */
8531     pr_trace_msg(trace_channel, 20,
8532       "timed out after %d secs peeking at next data, assuming SSL data",
8533       (int) tv.tv_sec);
8534     return TRUE;
8535   }
8536 
8537   /* If we reach here, the peer must have sent something.  Let's see what it
8538    * might be.  Chances are that we received at least 3 bytes, but to be
8539    * defensive, we use MSG_WAITALL anyway.  TCP allows for sending one byte
8540    * at time, if need be.  Fortunately, either SSL record or FTP command will
8541    * require more than three bytes.
8542    */
8543   memset(&buf, 0, sizeof(buf));
8544   len = recv(fd, buf, sizeof(buf), MSG_PEEK|MSG_WAITALL);
8545   while (len < 0) {
8546     int xerrno = errno;
8547 
8548     if (xerrno == EINTR) {
8549       pr_signals_handle();
8550       len = recv(fd, &buf, sizeof(buf), MSG_PEEK|MSG_WAITALL);
8551       continue;
8552     }
8553 
8554     pr_trace_msg(trace_channel, 20,
8555       "error peeking at next data: %s", strerror(xerrno));
8556     errno = xerrno;
8557     return -1;
8558   }
8559 
8560   pr_trace_msg(trace_channel, 20, "peeking at %ld bytes of next data",
8561     (long) len);
8562   for (i = 0; i < len; i++) {
8563     if (PR_ISPRINT(buf[i]) == 0) {
8564       /* Not a printable character; assume it's SSL data. */
8565       pr_trace_msg(trace_channel, 20,
8566         "byte %u of peeked data is a non-printable ASCII character (%d), "
8567         "assuming SSL data", i, (int) buf[i]);
8568       return TRUE;
8569     }
8570   }
8571 
8572   pr_trace_msg(trace_channel, 20,
8573     "all %ld bytes of peeked data are printable ASCII characters, assuming "
8574     "FTP data", (long) len);
8575   return FALSE;
8576 }
8577 
8578 static void tls_end_sess(SSL *ssl, conn_t *conn, int flags) {
8579   int lineno, res = 0;
8580   int shutdown_state;
8581   BIO *rbio, *wbio;
8582   int bread, bwritten;
8583   unsigned long rbio_rbytes, rbio_wbytes, wbio_rbytes, wbio_wbytes;
8584 
8585   if (ssl == NULL) {
8586     return;
8587   }
8588 
8589   rbio = SSL_get_rbio(ssl);
8590   rbio_rbytes = BIO_number_read(rbio);
8591   rbio_wbytes = BIO_number_written(rbio);
8592 
8593   wbio = SSL_get_wbio(ssl);
8594   wbio_rbytes = BIO_number_read(wbio);
8595   wbio_wbytes = BIO_number_written(wbio);
8596 
8597   /* A 'close_notify' alert (SSL shutdown message) may have been previously
8598    * sent to the client via tls_netio_shutdown_cb().
8599    */
8600 
8601   shutdown_state = SSL_get_shutdown(ssl);
8602   if (!(shutdown_state & SSL_SENT_SHUTDOWN)) {
8603     errno = 0;
8604 
8605     if (conn != NULL) {
8606       /* Disable any socket buffering (Nagle, TCP_CORK), so that the alert
8607        * is sent in a timely manner (avoiding TLS shutdown latency).
8608        */
8609       if (pr_inet_set_proto_nodelay(conn->pool, conn, 1) < 0) {
8610         pr_trace_msg(trace_channel, 9,
8611           "error enabling TCP_NODELAY on conn: %s", strerror(errno));
8612       }
8613 
8614       if (pr_inet_set_proto_cork(conn->wfd, 0) < 0) {
8615         pr_trace_msg(trace_channel, 9,
8616           "error disabling TCP_CORK on fd %d: %s", conn->wfd, strerror(errno));
8617       }
8618     }
8619 
8620     /* 'close_notify' not already sent; send it now. */
8621     pr_trace_msg(trace_channel, 17,
8622       "shutting down TLS session, 'close_notify' not already sent; "
8623       "sending now");
8624     lineno = __LINE__ + 1;
8625     res = SSL_shutdown(ssl);
8626   }
8627 
8628   if (res == 0) {
8629     /* Now call SSL_shutdown() again, but only if necessary. */
8630     if (flags & TLS_SHUTDOWN_FL_BIDIRECTIONAL) {
8631       shutdown_state = SSL_get_shutdown(ssl);
8632 
8633       res = 1;
8634       if (!(shutdown_state & SSL_RECEIVED_SHUTDOWN)) {
8635         int is_ssl_data = FALSE, xerrno;
8636 
8637         pr_trace_msg(trace_channel, 17,
8638           "shutting down TLS session, 'close_notify' not received; "
8639           "peeking at next data");
8640 
8641         /* This where we need to peek at the next data, to see whether we
8642          * dealing with a well-behaved FTPS client, which will be sending
8643          * its `close_notify` to properly shutdown the TLS session, or with
8644          * a buggy/ill-behaved FTPS client which will not send a `close_notify`,
8645          * and instead will just send the next FTP command in plaintext.
8646          *
8647          * If it's the latter case, then we do NOT want to wait for a
8648          * `close_notify` that will never come.  Doing so will cause the
8649          * plaintext FTP command to be treated as an SSL record, which will
8650          * fail with a "wrong version number" SSL error.
8651          */
8652 
8653         is_ssl_data = peek_is_ssl_data(conn->rfd);
8654         if (is_ssl_data < 0) {
8655           SSL_free(ssl);
8656           pr_session_disconnect(&tls_module, PR_SESS_DISCONNECT_BY_APPLICATION,
8657             NULL);
8658           return;
8659         }
8660 
8661         if (is_ssl_data == FALSE) {
8662           /* We're dealing with a buggy/ill-behaved FTPS client.  Sigh. */
8663           pr_trace_msg(trace_channel, 17,
8664             "shut down TLS session uncleanly, next data is FTP command from "
8665             "buggy/ill-behaved FTPS client");
8666           SSL_free(ssl);
8667           return;
8668         }
8669 
8670         errno = 0;
8671         lineno = __LINE__ + 1;
8672         res = SSL_shutdown(ssl);
8673         xerrno = errno;
8674 
8675         pr_trace_msg(trace_channel, 17,
8676           "shutting down TLS session, 'close_notify' not received; "
8677           "SSL_shutdown() returned %d", res);
8678 
8679         errno = xerrno;
8680       }
8681     }
8682 
8683     /* If SSL_shutdown() returned -1 here, an error occurred during the
8684      * shutdown.
8685      */
8686     if (res < 0) {
8687       long err_code;
8688 
8689       err_code = SSL_get_error(ssl, res);
8690       switch (err_code) {
8691         case SSL_ERROR_WANT_READ:
8692           tls_log("SSL_shutdown error: WANT_READ");
8693           break;
8694 
8695         case SSL_ERROR_WANT_WRITE:
8696           tls_log("SSL_shutdown error: WANT_WRITE");
8697           break;
8698 
8699         case SSL_ERROR_SSL: {
8700           unsigned long ssl_errcode = ERR_peek_error();
8701 
8702           /* The error codes in the OpenSSL error queue are "packed"; we need
8703            * to unpack them to get the reason value.
8704            */
8705 
8706 #ifdef SSL_R_SHUTDOWN_WHILE_IN_INIT
8707           if (ERR_GET_REASON(ssl_errcode) != SSL_R_SHUTDOWN_WHILE_IN_INIT) {
8708             /* This SHUTDOWN_WHILE_IN_INIT can happen if the TLS handshake
8709              * failed before being completed.  As such, logging this shutdown
8710              * error on an incomplete session is spurious and not helpful.
8711              */
8712             tls_log("SSL_shutdown error: SSL: %s", tls_get_errors());
8713           }
8714 #else
8715           (void) ssl_errcode;
8716           tls_log("SSL_shutdown error: SSL: %s", tls_get_errors());
8717 #endif /* No SSL_R_SHUTDOWN_WHILE_IN_INIT */
8718 
8719           break;
8720         }
8721 
8722         case SSL_ERROR_ZERO_RETURN:
8723           /* Clean shutdown, nothing we need to do. */
8724           break;
8725 
8726         case SSL_ERROR_SYSCALL:
8727           if (errno != 0 &&
8728               errno != EOF &&
8729               errno != EBADF &&
8730               errno != EPIPE &&
8731               errno != EPERM &&
8732               errno != ENOSYS) {
8733             tls_log("SSL_shutdown syscall error: %s", strerror(errno));
8734           }
8735           break;
8736 
8737         default:
8738           tls_log("SSL_shutdown error [%ld]: %s", err_code, tls_get_errors());
8739           pr_log_debug(DEBUG0, MOD_TLS_VERSION
8740             ": SSL_shutdown error [%ld]: %s", err_code, tls_get_errors());
8741           break;
8742       }
8743     }
8744 
8745   } else if (res < 0) {
8746     long err_code;
8747 
8748     err_code = SSL_get_error(ssl, res);
8749     switch (err_code) {
8750       case SSL_ERROR_WANT_READ:
8751       case SSL_ERROR_WANT_WRITE:
8752       case SSL_ERROR_ZERO_RETURN:
8753         /* Clean shutdown, nothing we need to do.  The WANT_READ/WANT_WRITE
8754          * error codes crept into OpenSSL 0.9.8m, with changes to make
8755          * SSL_shutdown() work properly for non-blocking sockets.  And
8756          * handling these error codes for older OpenSSL versions won't break
8757          * things.
8758          */
8759         break;
8760 
8761       case SSL_ERROR_SSL: {
8762         unsigned long ssl_errcode = ERR_peek_error();
8763 
8764         /* The error codes in the OpenSSL error queue are "packed"; we need
8765          * to unpack them to get the reason value.
8766          */
8767 
8768 #ifdef SSL_R_SHUTDOWN_WHILE_IN_INIT
8769         if (ERR_GET_REASON(ssl_errcode) != SSL_R_SHUTDOWN_WHILE_IN_INIT) {
8770           /* This SHUTDOWN_WHILE_IN_INIT can happen if the TLS handshake
8771            * failed before being completed.  As such, logging this shutdown
8772            * error on an incomplete session is spurious and not helpful.
8773            */
8774           tls_log("SSL_shutdown error: SSL: %s", tls_get_errors());
8775         }
8776 #else
8777         (void) ssl_errcode;
8778         tls_log("SSL_shutdown error: SSL: %s", tls_get_errors());
8779 #endif /* No SSL_R_SHUTDOWN_WHILE_IN_INIT */
8780         break;
8781       }
8782 
8783       case SSL_ERROR_SYSCALL:
8784         if (errno != 0 &&
8785             errno != EOF &&
8786             errno != EBADF &&
8787             errno != EPIPE &&
8788             errno != EPERM &&
8789             errno != ENOSYS) {
8790           tls_log("SSL_shutdown syscall error: %s", strerror(errno));
8791         }
8792         break;
8793 
8794       default:
8795         tls_fatal_error(err_code, lineno);
8796         break;
8797     }
8798   }
8799 
8800   bread = (BIO_number_read(rbio) - rbio_rbytes) +
8801     (BIO_number_read(wbio) - wbio_rbytes);
8802   bwritten = (BIO_number_written(rbio) - rbio_wbytes) +
8803     (BIO_number_written(wbio) - wbio_wbytes);
8804 
8805   /* Manually update session.total_raw_in/out, in order to have %I/%O be
8806    * accurately represented for the raw traffic.
8807    */
8808   if (bread > 0) {
8809     session.total_raw_in += bread;
8810   }
8811 
8812   if (bwritten > 0) {
8813     session.total_raw_out += bwritten;
8814   }
8815 
8816   SSL_free(ssl);
8817 
8818   if (res >= 0) {
8819     pr_trace_msg(trace_channel, 17, "TLS session cleanly shut down");
8820   }
8821 }
8822 
8823 static const char *tls_get_errors2(pool *p) {
8824   unsigned int count = 0;
8825   unsigned long error_code;
8826   BIO *bio = NULL;
8827   char *data = NULL;
8828   long datalen;
8829   const char *error_data = NULL, *str = "(unknown)";
8830   int error_flags = 0;
8831 
8832   /* Use ERR_print_errors() and a memory BIO to build up a string with
8833    * all of the error messages from the error queue.
8834    */
8835 
8836   error_code = ERR_get_error_line_data(NULL, NULL, &error_data, &error_flags);
8837   if (error_code) {
8838     bio = BIO_new(BIO_s_mem());
8839   }
8840 
8841   while (error_code) {
8842     pr_signals_handle();
8843 
8844     if (error_flags & ERR_TXT_STRING) {
8845       BIO_printf(bio, "\n  (%u) %s [%s]", ++count,
8846         ERR_error_string(error_code, NULL), error_data);
8847 
8848     } else {
8849       BIO_printf(bio, "\n  (%u) %s", ++count,
8850         ERR_error_string(error_code, NULL));
8851     }
8852 
8853     error_data = NULL;
8854     error_flags = 0;
8855     error_code = ERR_get_error_line_data(NULL, NULL, &error_data, &error_flags);
8856   }
8857 
8858   datalen = BIO_get_mem_data(bio, &data);
8859   if (data) {
8860     data[datalen] = '\0';
8861     str = pstrdup(p, data);
8862   }
8863 
8864   if (bio) {
8865     BIO_free(bio);
8866   }
8867 
8868   return str;
8869 }
8870 
8871 static const char *tls_get_errors(void) {
8872   return tls_get_errors2(session.pool);
8873 }
8874 
8875 /* Return a page-aligned pointer to memory of at least the given size. */
8876 static char *tls_get_page(size_t sz, void **ptr) {
8877   void *d;
8878   long pagesz = tls_get_pagesz(), p;
8879 
8880   d = calloc(1, sz + (pagesz-1));
8881   if (d == NULL) {
8882     pr_log_pri(PR_LOG_ALERT, MOD_TLS_VERSION ": Out of memory!");
8883     exit(1);
8884   }
8885 
8886   *ptr = d;
8887 
8888   p = ((long) d + (pagesz-1)) &~ (pagesz-1);
8889 
8890   return ((char *) p);
8891 }
8892 
8893 /* Return the size of a page on this architecture. */
8894 static size_t tls_get_pagesz(void) {
8895   long pagesz;
8896 
8897 #if defined(_SC_PAGESIZE)
8898   pagesz = sysconf(_SC_PAGESIZE);
8899 #elif defined(_SC_PAGE_SIZE)
8900   pagesz = sysconf(_SC_PAGE_SIZE);
8901 #else
8902   /* Default to using OpenSSL's defined buffer size for PEM files. */
8903   pagesz = PEM_BUFSIZE;
8904 #endif /* !_SC_PAGESIZE and !_SC_PAGE_SIZE */
8905 
8906   return pagesz;
8907 }
8908 
8909 static char *tls_get_subj_name(SSL *ssl) {
8910   X509 *cert = SSL_get_peer_certificate(ssl);
8911 
8912   if (cert) {
8913     char *name = tls_x509_name_oneline(X509_get_subject_name(cert));
8914     X509_free(cert);
8915     return name;
8916   }
8917 
8918   return NULL;
8919 }
8920 
8921 static void tls_fatal_error(long error, int lineno) {
8922 
8923   switch (error) {
8924     case SSL_ERROR_NONE:
8925       return;
8926 
8927     case SSL_ERROR_SSL:
8928       tls_log("panic: SSL_ERROR_SSL, line %d: %s", lineno, tls_get_errors());
8929       break;
8930 
8931     case SSL_ERROR_WANT_READ:
8932       tls_log("panic: SSL_ERROR_WANT_READ, line %d", lineno);
8933       break;
8934 
8935     case SSL_ERROR_WANT_WRITE:
8936       tls_log("panic: SSL_ERROR_WANT_WRITE, line %d", lineno);
8937       break;
8938 
8939     case SSL_ERROR_WANT_X509_LOOKUP:
8940       tls_log("panic: SSL_ERROR_WANT_X509_LOOKUP, line %d", lineno);
8941       break;
8942 
8943     case SSL_ERROR_SYSCALL: {
8944       long xerrcode = ERR_get_error();
8945 
8946       if (errno == ECONNRESET) {
8947         pr_trace_msg(trace_channel, 17,
8948           "SSL_ERROR_SYSCALL error (errcode %ld) occurred on line %d; ignoring "
8949           "ECONNRESET (%s)", xerrcode, lineno, strerror(errno));
8950         return;
8951       }
8952 
8953       /* Check to see if the OpenSSL error queue has info about this. */
8954       if (xerrcode == 0) {
8955         /* The OpenSSL error queue doesn't have any more info, so we'll
8956          * examine the error value itself.
8957          */
8958 
8959         if (errno == EOF) {
8960           tls_log("panic: SSL_ERROR_SYSCALL, line %d: "
8961             "EOF that violates protocol", lineno);
8962 
8963         } else {
8964           /* Check errno */
8965           tls_log("panic: SSL_ERROR_SYSCALL, line %d: system error: %s", lineno,
8966             strerror(errno));
8967         }
8968 
8969       } else {
8970         tls_log("panic: SSL_ERROR_SYSCALL, line %d: %s", lineno,
8971           tls_get_errors());
8972       }
8973 
8974       break;
8975     }
8976 
8977     case SSL_ERROR_ZERO_RETURN:
8978       tls_log("panic: SSL_ERROR_ZERO_RETURN, line %d", lineno);
8979       break;
8980 
8981     case SSL_ERROR_WANT_CONNECT:
8982       tls_log("panic: SSL_ERROR_WANT_CONNECT, line %d", lineno);
8983       break;
8984 
8985     default:
8986       tls_log("panic: SSL_ERROR %ld, line %d", error, lineno);
8987       break;
8988   }
8989 
8990   tls_log("%s", "unexpected OpenSSL error, disconnecting");
8991   pr_log_pri(PR_LOG_WARNING, "%s", MOD_TLS_VERSION
8992     ": unexpected OpenSSL error, disconnecting");
8993 
8994   pr_session_disconnect(&tls_module, PR_SESS_DISCONNECT_BY_APPLICATION, NULL);
8995 }
8996 
8997 /* This function checks if the client's cert is in the ~/.tlslogin file
8998  * of the "user".
8999  */
9000 static int tls_dotlogin_allow(const char *user) {
9001   char buf[512] = {'\0'}, *home = NULL;
9002   FILE *fp = NULL;
9003   X509 *client_cert = NULL, *file_cert = NULL;
9004   struct passwd *pwd = NULL;
9005   pool *tmp_pool = NULL;
9006   unsigned char allow_user = FALSE;
9007   int xerrno;
9008 
9009   if (!(tls_flags & TLS_SESS_ON_CTRL) ||
9010       ctrl_ssl == NULL ||
9011       user == NULL) {
9012     return FALSE;
9013   }
9014 
9015   /* If the client did not provide a cert, we cannot do the .tlslogin check. */
9016   client_cert = SSL_get_peer_certificate(ctrl_ssl);
9017   if (client_cert == NULL) {
9018     pr_trace_msg(trace_channel, 9, "%s",
9019       "client did not provide certificate, skipping AllowDotLogin check");
9020     return FALSE;
9021   }
9022 
9023   tmp_pool = make_sub_pool(permanent_pool);
9024 
9025   PRIVS_ROOT
9026   pwd = pr_auth_getpwnam(tmp_pool, user);
9027   PRIVS_RELINQUISH
9028 
9029   if (pwd == NULL) {
9030     X509_free(client_cert);
9031     destroy_pool(tmp_pool);
9032     return FALSE;
9033   }
9034 
9035   /* Handle the case where the user's home directory is a symlink. */
9036   PRIVS_USER
9037   home = dir_realpath(tmp_pool, pwd->pw_dir);
9038   PRIVS_RELINQUISH
9039 
9040   pr_snprintf(buf, sizeof(buf), "%s/.tlslogin", home ? home : pwd->pw_dir);
9041   buf[sizeof(buf)-1] = '\0';
9042 
9043   /* No need for the temporary pool any more. */
9044   destroy_pool(tmp_pool);
9045   tmp_pool = NULL;
9046 
9047   PRIVS_ROOT
9048   fp = fopen(buf, "r");
9049   xerrno = errno;
9050   PRIVS_RELINQUISH
9051 
9052   if (fp == NULL) {
9053     X509_free(client_cert);
9054     tls_log(".tlslogin check: unable to open '%s': %s", buf, strerror(xerrno));
9055     return FALSE;
9056   }
9057 
9058   /* As the file may contain sensitive data, we do not want it lingering
9059    * around in stdio buffers.
9060    */
9061   (void) setvbuf(fp, NULL, _IONBF, 0);
9062 
9063   while ((file_cert = PEM_read_X509(fp, NULL, NULL, NULL))) {
9064     const ASN1_BIT_STRING *client_sig = NULL, *file_sig = NULL;
9065 
9066     pr_signals_handle();
9067 
9068 #if OPENSSL_VERSION_NUMBER >= 0x10100000L && \
9069     !defined(HAVE_LIBRESSL)
9070     X509_get0_signature(&client_sig, NULL, client_cert);
9071     X509_get0_signature(&file_sig, NULL, file_cert);
9072 #else
9073     client_sig = client_cert->signature;
9074     file_sig = file_cert->signature;
9075 #endif /* OpenSSL-1.1.x and later */
9076 
9077 #if OPENSSL_VERSION_NUMBER >= 0x10100000L
9078     if (!ASN1_STRING_cmp(client_sig, file_sig)) {
9079 #else
9080     if (!M_ASN1_BIT_STRING_cmp(client_sig, file_sig)) {
9081 #endif /* OpenSSL-1.1.x and later */
9082       allow_user = TRUE;
9083     }
9084 
9085     X509_free(file_cert);
9086     if (allow_user) {
9087       break;
9088     }
9089   }
9090 
9091   X509_free(client_cert);
9092   fclose(fp);
9093 
9094   return allow_user;
9095 }
9096 
9097 static int tls_cert_to_user(const char *user_name, const char *field_name) {
9098   X509 *client_cert = NULL;
9099   unsigned char allow_user = FALSE;
9100   unsigned char *field_value = NULL;
9101 
9102   if (!(tls_flags & TLS_SESS_ON_CTRL) ||
9103       ctrl_ssl == NULL ||
9104       user_name == NULL ||
9105       field_name == NULL) {
9106     return FALSE;
9107   }
9108 
9109   /* If the client did not provide a cert, we cannot do the TLSUserName
9110    * check.
9111    */
9112   client_cert = SSL_get_peer_certificate(ctrl_ssl);
9113   if (client_cert == NULL) {
9114     return FALSE;
9115   }
9116 
9117   if (strcmp(field_name, "CommonName") == 0) {
9118     X509_NAME *name;
9119     int pos = -1;
9120 
9121     name = X509_get_subject_name(client_cert);
9122 
9123     while (TRUE) {
9124       X509_NAME_ENTRY *entry;
9125       ASN1_STRING *data;
9126       int data_len;
9127       unsigned char *data_str = NULL;
9128 
9129       pr_signals_handle();
9130 
9131       pos = X509_NAME_get_index_by_NID(name, NID_commonName, pos);
9132       if (pos == -1) {
9133         break;
9134       }
9135 
9136       entry = X509_NAME_get_entry(name, pos);
9137       data = X509_NAME_ENTRY_get_data(entry);
9138       data_len = ASN1_STRING_length(data);
9139       data_str = ASN1_STRING_data(data);
9140 
9141       /* Watch for any embedded NULs, which can cause verification
9142        * problems via spoofing.
9143        */
9144       if ((size_t) data_len != strlen((char *) data_str)) {
9145         tls_log("%s", "client cert CommonName contains embedded NULs, "
9146           "ignoring as possible spoof attempt");
9147         tls_log("suspicious CommonName value: '%s'", data_str);
9148 
9149       } else {
9150 
9151         /* There can be multiple CommonNames... */
9152         if (strcmp((char *) data_str, user_name) == 0) {
9153           field_value = data_str;
9154           allow_user = TRUE;
9155 
9156           tls_log("matched client cert CommonName '%s' to user '%s'",
9157             field_value, user_name);
9158           break;
9159         }
9160       }
9161     }
9162 
9163   } else if (strcmp(field_name, "EmailSubjAltName") == 0) {
9164     STACK_OF(GENERAL_NAME) *sk_alt_names;
9165 
9166     sk_alt_names = X509_get_ext_d2i(client_cert, NID_subject_alt_name, NULL,
9167       NULL);
9168     if (sk_alt_names != NULL) {
9169       register int i;
9170       int nnames = sk_GENERAL_NAME_num(sk_alt_names);
9171 
9172       for (i = 0; i < nnames; i++) {
9173         GENERAL_NAME *name;
9174 
9175         pr_signals_handle();
9176 
9177         name = sk_GENERAL_NAME_value(sk_alt_names, i);
9178 
9179         /* We're only looking for the Email type. */
9180         if (name->type == GEN_EMAIL) {
9181           int data_len;
9182           unsigned char *data_str = NULL;
9183 
9184           data_len = ASN1_STRING_length(name->d.ia5);
9185           data_str = ASN1_STRING_data(name->d.ia5);
9186 
9187           /* Watch for any embedded NULs, which can cause verification
9188            * problems via spoofing.
9189            */
9190           if ((size_t) data_len != strlen((char *) data_str)) {
9191             tls_log("%s", "client cert Email SAN contains embedded NULs, "
9192               "ignoring as possible spoof attempt");
9193             tls_log("suspicious Email SubjAltName value: '%s'", data_str);
9194 
9195           } else {
9196 
9197             /* There can be multiple Email SANs... */
9198             if (strcmp((char *) data_str, user_name) == 0) {
9199               field_value = data_str;
9200               allow_user = TRUE;
9201 
9202               tls_log("matched client cert Email SubjAltName '%s' to user '%s'",
9203                 field_value, user_name);
9204               GENERAL_NAME_free(name);
9205               break;
9206             }
9207           }
9208         }
9209 
9210         GENERAL_NAME_free(name);
9211       }
9212 
9213       sk_GENERAL_NAME_free(sk_alt_names);
9214     }
9215 
9216   } else {
9217     /* Custom OID. */
9218     int nexts;
9219 
9220     nexts = X509_get_ext_count(client_cert);
9221     if (nexts > 0) {
9222       register int i;
9223 
9224       for (i = 0; i < nexts; i++) {
9225         X509_EXTENSION *ext = NULL;
9226         ASN1_OBJECT *asn_object = NULL;
9227         char oid[PR_TUNABLE_PATH_MAX];
9228 
9229         pr_signals_handle();
9230 
9231         ext = X509_get_ext(client_cert, i);
9232         asn_object = X509_EXTENSION_get_object(ext);
9233 
9234         /* Get the OID of this extension, as a string. */
9235         memset(oid, '\0', sizeof(oid));
9236         if (OBJ_obj2txt(oid, sizeof(oid)-1, asn_object, 1) > 0) {
9237           if (strcmp(oid, field_name) == 0) {
9238             ASN1_OCTET_STRING *asn_data = NULL;
9239             unsigned char *asn_datastr = NULL;
9240             int asn_datalen;
9241 
9242             asn_data = X509_EXTENSION_get_data(ext);
9243             asn_datalen = ASN1_STRING_length(asn_data);
9244             asn_datastr = ASN1_STRING_data(asn_data);
9245 
9246             /* Watch for any embedded NULs, which can cause verification
9247              * problems via spoofing.
9248              */
9249             if ((size_t) asn_datalen != strlen((char *) asn_datastr)) {
9250               tls_log("client cert %s extension contains embedded NULs, "
9251                 "ignoring as possible spoof attempt", field_name);
9252               tls_log("suspicious %s extension value: '%s'", field_name,
9253                 asn_datastr);
9254 
9255             } else {
9256 
9257               /* There might be multiple matching extensions? */
9258               if (strcmp((char *) asn_datastr, user_name) == 0) {
9259                 field_value = asn_datastr;
9260                 allow_user = TRUE;
9261 
9262                 tls_log("matched client cert %s extension '%s' to user '%s'",
9263                   field_name, field_value, user_name);
9264                 break;
9265               }
9266             }
9267           }
9268         }
9269       }
9270     }
9271   }
9272 
9273   X509_free(client_cert);
9274   return allow_user;
9275 }
9276 
9277 static int tls_readmore(int rfd) {
9278   fd_set rfds;
9279   struct timeval tv;
9280 
9281   FD_ZERO(&rfds);
9282   FD_SET(rfd, &rfds);
9283 
9284   /* Use a timeout of 15 seconds */
9285   tv.tv_sec = 15;
9286   tv.tv_usec = 0;
9287 
9288   return select(rfd + 1, &rfds, NULL, NULL, &tv);
9289 }
9290 
9291 static int tls_writemore(int wfd) {
9292   fd_set wfds;
9293   struct timeval tv;
9294 
9295   FD_ZERO(&wfds);
9296   FD_SET(wfd, &wfds);
9297 
9298   /* Use a timeout of 15 seconds */
9299   tv.tv_sec = 15;
9300   tv.tv_usec = 0;
9301 
9302   return select(wfd + 1, NULL, &wfds, NULL, &tv);
9303 }
9304 
9305 static ssize_t tls_read(SSL *ssl, void *buf, size_t len) {
9306   ssize_t count;
9307   int lineno, xerrno = 0;
9308 
9309   retry:
9310   pr_signals_handle();
9311 
9312   /* Help ensure we have a clean/trustable errno value. */
9313   errno = 0;
9314 
9315   lineno = __LINE__ + 1;
9316   count = SSL_read(ssl, buf, len);
9317   xerrno = errno;
9318 
9319   if (count < 0) {
9320     long err;
9321     int fd;
9322 
9323     err = SSL_get_error(ssl, count);
9324     fd = SSL_get_fd(ssl);
9325 
9326     /* read(2) returns only the generic error number -1 */
9327     count = -1;
9328 
9329     switch (err) {
9330       case SSL_ERROR_WANT_READ:
9331         /* OpenSSL needs more data from the wire to finish the current block,
9332          * so we wait a little while for it.
9333          */
9334         pr_trace_msg(trace_channel, 17,
9335           "WANT_READ encountered while reading TLS data on fd %d, "
9336           "waiting to read data", fd);
9337         err = tls_readmore(fd);
9338         if (err > 0) {
9339           goto retry;
9340 
9341         } else if (err == 0) {
9342           /* Still missing data after timeout. Simulate an EINTR and return.
9343            */
9344           xerrno = EINTR;
9345 
9346           /* If err < 0, i.e. some error from the select(), everything is
9347            * already in place; errno is properly set and this function
9348            * returns -1.
9349            */
9350           break;
9351         }
9352 
9353       case SSL_ERROR_WANT_WRITE:
9354         /* OpenSSL needs to write more data to the wire to finish the current
9355          * block, so we wait a little while for it.
9356          */
9357         pr_trace_msg(trace_channel, 17,
9358           "WANT_WRITE encountered while writing TLS data on fd %d, "
9359           "waiting to send data", fd);
9360         err = tls_writemore(fd);
9361         if (err > 0) {
9362           goto retry;
9363 
9364         } else if (err == 0) {
9365           /* Still missing data after timeout. Simulate an EINTR and return.
9366            */
9367           xerrno = EINTR;
9368 
9369           /* If err < 0, i.e. some error from the select(), everything is
9370            * already in place; errno is properly set and this function
9371            * returns -1.
9372            */
9373           break;
9374         }
9375 
9376       case SSL_ERROR_ZERO_RETURN:
9377         tls_log("read EOF from client");
9378         break;
9379 
9380       case SSL_ERROR_SSL:
9381       case SSL_ERROR_SYSCALL:
9382       default:
9383         tls_fatal_error(err, lineno);
9384         break;
9385     }
9386   }
9387 
9388   errno = xerrno;
9389   return count;
9390 }
9391 
9392 static int tls_seed_prng(void) {
9393   char *heapdata, stackdata[1024];
9394   static char rand_file[300];
9395   FILE *fp = NULL;
9396 
9397 #if OPENSSL_VERSION_NUMBER >= 0x00905100L
9398   if (RAND_status() == 1)
9399 
9400     /* PRNG already well-seeded. */
9401     return 0;
9402 #endif
9403 
9404   tls_log("PRNG not seeded with enough data, looking for entropy sources");
9405 
9406   /* If the device '/dev/urandom' is present, OpenSSL uses it by default.
9407    * Check if it's present, else we have to make random data ourselves.
9408    */
9409   fp = fopen("/dev/urandom", "r");
9410   if (fp != NULL) {
9411     fclose(fp);
9412 
9413     tls_log("device /dev/urandom is present, assuming OpenSSL will use that "
9414       "for PRNG data");
9415     return 0;
9416   }
9417 
9418   /* Lookup any configured TLSRandomSeed. */
9419   tls_rand_file = get_param_ptr(main_server->conf, "TLSRandomSeed", FALSE);
9420   if (tls_rand_file == NULL) {
9421     /* The ftpd's random file is (openssl-dir)/.rnd */
9422     memset(rand_file, '\0', sizeof(rand_file));
9423     pr_snprintf(rand_file, sizeof(rand_file)-1, "%s/.rnd",
9424       X509_get_default_cert_area());
9425     tls_rand_file = rand_file;
9426   }
9427 
9428 #if OPENSSL_VERSION_NUMBER >= 0x00905100L
9429   /* In OpenSSL 0.9.5 and later, specifying -1 here means "read the entire
9430    * file", which is exactly what we want.
9431    */
9432   if (RAND_load_file(tls_rand_file, -1) == 0) {
9433 #else
9434   /* In versions of OpenSSL prior to 0.9.5, we have to specify the amount of
9435    * bytes to read in.  Since RAND_write_file(3) typically writes 1K of data
9436    * out, we will read 1K bytes in.
9437    */
9438   if (RAND_load_file(tls_rand_file, 1024) != 1024) {
9439 #endif
9440     struct timeval tv;
9441     pid_t pid;
9442 
9443 #if OPENSSL_VERSION_NUMBER >= 0x00905100L
9444     tls_log("unable to load PRNG seed data from '%s': %s", tls_rand_file,
9445       tls_get_errors());
9446 #else
9447     tls_log("unable to load 1024 bytes of PRNG seed data from '%s': %s",
9448       tls_rand_file, tls_get_errors());
9449 #endif
9450 
9451     /* No random file found, create new seed. */
9452     gettimeofday(&tv, NULL);
9453     RAND_seed(&(tv.tv_sec), sizeof(tv.tv_sec));
9454     RAND_seed(&(tv.tv_usec), sizeof(tv.tv_usec));
9455 
9456     pid = getpid();
9457     RAND_seed(&pid, sizeof(pid_t));
9458     RAND_seed(stackdata, sizeof(stackdata));
9459 
9460     heapdata = malloc(sizeof(stackdata));
9461     if (heapdata != NULL) {
9462       RAND_seed(heapdata, sizeof(stackdata));
9463       free(heapdata);
9464     }
9465 
9466   } else {
9467     tls_log("loaded PRNG seed data from '%s'", tls_rand_file);
9468   }
9469 
9470 #if OPENSSL_VERSION_NUMBER >= 0x00905100L
9471   if (RAND_status() == 0) {
9472      /* PRNG still badly seeded. */
9473      return -1;
9474   }
9475 #endif
9476 
9477   return 0;
9478 }
9479 
9480 /* Note: these mappings should probably be added to the mod_tls docs.
9481  */
9482 
9483 static void tls_setup_cert_ext_environ(const char *env_prefix, X509 *cert) {
9484 
9485   /* NOTE: in the future, add ways of adding subjectAltName (and other
9486    * extensions?) to the environment.
9487    */
9488 
9489 #if 0
9490   int nexts = 0;
9491 
9492   nexts = X509_get_ext_count(cert);
9493   if (nexts > 0) {
9494     register int i;
9495 
9496     for (i = 0; i < nexts; i++) {
9497       X509_EXTENSION *ext;
9498       const char *extstr;
9499 
9500       ext = X509_get_ext(cert, i);
9501       extstr = OBJ_nid2sn(OBJ_obj2nid(X509_EXTENSION_get_object(ext)));
9502     }
9503   }
9504 #endif
9505 
9506   return;
9507 }
9508 
9509 /* Note: these mappings should probably be added to the mod_tls docs.
9510  *
9511  *   Name                    Short Name    NID
9512  *   ----                    ----------    ---
9513  *   countryName             C             NID_countryName
9514  *   commonName              CN            NID_commonName
9515  *   description             D             NID_description
9516  *   givenName               G             NID_givenName
9517  *   initials                I             NID_initials
9518  *   localityName            L             NID_localityName
9519  *   organizationName        O             NID_organizationName
9520  *   organizationalUnitName  OU            NID_organizationalUnitName
9521  *   stateOrProvinceName     ST            NID_stateOrProvinceName
9522  *   surname                 S             NID_surname
9523  *   title                   T             NID_title
9524  *   uniqueIdentifer         UID           NID_x500UniqueIdentifier
9525  *                                         (or NID_uniqueIdentifier, depending
9526  *                                         on OpenSSL version)
9527  *   email                   Email         NID_pkcs9_emailAddress
9528  */
9529 
9530 static void tls_setup_cert_dn_environ(const char *env_prefix, X509_NAME *name) {
9531   register int i;
9532   int nentries;
9533   char *k, *v;
9534 
9535 #if OPENSSL_VERSION_NUMBER >= 0x10100000L
9536   nentries = X509_NAME_entry_count(name);
9537 #else
9538   nentries = sk_X509_NAME_ENTRY_num(name->entries);
9539 #endif /* OpenSSL-1.1.x and later */
9540 
9541   for (i = 0; i < nentries; i++) {
9542     X509_NAME_ENTRY *entry;
9543     unsigned char *entry_data;
9544     int nid, entry_len;
9545 
9546     pr_signals_handle();
9547 
9548 #if OPENSSL_VERSION_NUMBER >= 0x10100000L
9549     entry = X509_NAME_get_entry(name, i);
9550     nid = OBJ_obj2nid(X509_NAME_ENTRY_get_object(entry));
9551     entry_data = ASN1_STRING_data(X509_NAME_ENTRY_get_data(entry));
9552     entry_len = ASN1_STRING_length(X509_NAME_ENTRY_get_data(entry));
9553 #else
9554     entry = sk_X509_NAME_ENTRY_value(name->entries, i);
9555     nid = OBJ_obj2nid(entry->object);
9556     entry_data = entry->value->data;
9557     entry_len = entry->value->length;
9558 #endif /* OpenSSL-1.1.x and later */
9559 
9560     switch (nid) {
9561       case NID_countryName:
9562         k = pstrcat(session.pool, env_prefix, "C", NULL);
9563         v = pstrndup(session.pool, (const char *) entry_data, entry_len);
9564         pr_env_set(session.pool, k, v);
9565         break;
9566 
9567       case NID_commonName:
9568         k = pstrcat(session.pool, env_prefix, "CN", NULL);
9569         v = pstrndup(session.pool, (const char *) entry_data, entry_len);
9570         pr_env_set(session.pool, k, v);
9571         break;
9572 
9573       case NID_description:
9574         k = pstrcat(main_server->pool, env_prefix, "D", NULL);
9575         v = pstrndup(session.pool, (const char *) entry_data, entry_len);
9576         pr_env_set(main_server->pool, k, v);
9577         break;
9578 
9579       case NID_givenName:
9580         k = pstrcat(main_server->pool, env_prefix, "G", NULL);
9581         v = pstrndup(session.pool, (const char *) entry_data, entry_len);
9582         pr_env_set(main_server->pool, k, v);
9583         break;
9584 
9585       case NID_initials:
9586         k = pstrcat(main_server->pool, env_prefix, "I", NULL);
9587         v = pstrndup(session.pool, (const char *) entry_data, entry_len);
9588         pr_env_set(main_server->pool, k, v);
9589         break;
9590 
9591       case NID_localityName:
9592         k = pstrcat(main_server->pool, env_prefix, "L", NULL);
9593         v = pstrndup(session.pool, (const char *) entry_data, entry_len);
9594         pr_env_set(main_server->pool, k, v);
9595         break;
9596 
9597       case NID_organizationName:
9598         k = pstrcat(main_server->pool, env_prefix, "O", NULL);
9599         v = pstrndup(session.pool, (const char *) entry_data, entry_len);
9600         pr_env_set(main_server->pool, k, v);
9601         break;
9602 
9603       case NID_organizationalUnitName:
9604         k = pstrcat(main_server->pool, env_prefix, "OU", NULL);
9605         v = pstrndup(session.pool, (const char *) entry_data, entry_len);
9606         pr_env_set(main_server->pool, k, v);
9607         break;
9608 
9609       case NID_stateOrProvinceName:
9610         k = pstrcat(main_server->pool, env_prefix, "ST", NULL);
9611         v = pstrndup(session.pool, (const char *) entry_data, entry_len);
9612         pr_env_set(main_server->pool, k, v);
9613         break;
9614 
9615       case NID_surname:
9616         k = pstrcat(main_server->pool, env_prefix, "S", NULL);
9617         v = pstrndup(session.pool, (const char *) entry_data, entry_len);
9618         pr_env_set(main_server->pool, k, v);
9619         break;
9620 
9621       case NID_title:
9622         k = pstrcat(main_server->pool, env_prefix, "T", NULL);
9623         v = pstrndup(session.pool, (const char *) entry_data, entry_len);
9624         pr_env_set(main_server->pool, k, v);
9625         break;
9626 
9627 #if OPENSSL_VERSION_NUMBER >= 0x00907000L
9628       case NID_x500UniqueIdentifier:
9629 #else
9630       case NID_uniqueIdentifier:
9631 #endif
9632         k = pstrcat(main_server->pool, env_prefix, "UID", NULL);
9633         v = pstrndup(session.pool, (const char *) entry_data, entry_len);
9634         pr_env_set(main_server->pool, k, v);
9635         break;
9636 
9637       case NID_pkcs9_emailAddress:
9638         k = pstrcat(main_server->pool, env_prefix, "Email", NULL);
9639         v = pstrndup(session.pool, (const char *) entry_data, entry_len);
9640         pr_env_set(main_server->pool, k, v);
9641         break;
9642 
9643       default:
9644         break;
9645     }
9646   }
9647 }
9648 
9649 static void tls_setup_cert_environ(pool *p, const char *env_prefix,
9650     X509 *cert) {
9651   char *data = NULL, *k, *v;
9652   long datalen = 0;
9653   BIO *bio = NULL;
9654 
9655   if (tls_opts & TLS_OPT_STD_ENV_VARS) {
9656     char buf[80] = {'\0'};
9657     ASN1_INTEGER *serial = X509_get_serialNumber(cert);
9658     X509_ALGOR *algo;
9659     X509_PUBKEY *pubkey;
9660 
9661     memset(buf, '\0', sizeof(buf));
9662     pr_snprintf(buf, sizeof(buf) - 1, "%lu", X509_get_version(cert) + 1);
9663     buf[sizeof(buf)-1] = '\0';
9664 
9665     k = pstrcat(p, env_prefix, "M_VERSION", NULL);
9666     v = pstrdup(p, buf);
9667     pr_env_set(p, k, v);
9668 
9669     if (serial->length < 4) {
9670       memset(buf, '\0', sizeof(buf));
9671       pr_snprintf(buf, sizeof(buf) - 1, "%lu", ASN1_INTEGER_get(serial));
9672       buf[sizeof(buf)-1] = '\0';
9673 
9674       k = pstrcat(p, env_prefix, "M_SERIAL", NULL);
9675       v = pstrdup(p, buf);
9676       pr_env_set(p, k, v);
9677 
9678     } else {
9679 
9680       /* NOTE: actually, the number is printable, I'm just being lazy. This
9681        * case is much harder to deal with, and not really worth the effort.
9682        */
9683       tls_log("%s", "certificate serial number not printable");
9684     }
9685 
9686     k = pstrcat(p, env_prefix, "S_DN", NULL);
9687     v = pstrdup(p, tls_x509_name_oneline(X509_get_subject_name(cert)));
9688     pr_env_set(p, k, v);
9689 
9690     tls_setup_cert_dn_environ(pstrcat(p, env_prefix, "S_DN_",
9691       NULL), X509_get_subject_name(cert));
9692 
9693     k = pstrcat(p, env_prefix, "I_DN", NULL);
9694     v = pstrdup(p, tls_x509_name_oneline(X509_get_issuer_name(cert)));
9695     pr_env_set(p, k, v);
9696 
9697     tls_setup_cert_dn_environ(pstrcat(p, env_prefix, "I_DN_", NULL),
9698       X509_get_issuer_name(cert));
9699 
9700     tls_setup_cert_ext_environ(pstrcat(p, env_prefix, "EXT_", NULL), cert);
9701 
9702     bio = BIO_new(BIO_s_mem());
9703     ASN1_TIME_print(bio, X509_get_notBefore(cert));
9704     datalen = BIO_get_mem_data(bio, &data);
9705     data[datalen] = '\0';
9706 
9707     k = pstrcat(p, env_prefix, "V_START", NULL);
9708     v = pstrdup(p, data);
9709     pr_env_set(p, k, v);
9710 
9711     BIO_free(bio);
9712 
9713     bio = BIO_new(BIO_s_mem());
9714     ASN1_TIME_print(bio, X509_get_notAfter(cert));
9715     datalen = BIO_get_mem_data(bio, &data);
9716     data[datalen] = '\0';
9717 
9718     k = pstrcat(p, env_prefix, "V_END", NULL);
9719     v = pstrdup(p, data);
9720     pr_env_set(p, k, v);
9721 
9722     BIO_free(bio);
9723 
9724     bio = BIO_new(BIO_s_mem());
9725 #if OPENSSL_VERSION_NUMBER >= 0x10100000L && \
9726     !defined(HAVE_LIBRESSL)
9727     X509_get0_signature(NULL, &algo, cert);
9728 #else
9729     algo = cert->cert_info->signature;
9730 #endif /* OpenSSL-1.1.x and later */
9731     i2a_ASN1_OBJECT(bio, algo->algorithm);
9732     datalen = BIO_get_mem_data(bio, &data);
9733     data[datalen] = '\0';
9734 
9735     k = pstrcat(p, env_prefix, "A_SIG", NULL);
9736     v = pstrdup(p, data);
9737     pr_env_set(p, k, v);
9738 
9739     BIO_free(bio);
9740 
9741     bio = BIO_new(BIO_s_mem());
9742 #if OPENSSL_VERSION_NUMBER >= 0x10100000L
9743     pubkey = X509_get_X509_PUBKEY(cert);
9744     X509_PUBKEY_get0_param(NULL, NULL, NULL, &algo, pubkey);
9745 #else
9746     pubkey = cert->cert_info->key;
9747     algo = pubkey->algor;
9748 #endif /* OpenSSL-1.1.x and later */
9749     i2a_ASN1_OBJECT(bio, algo->algorithm);
9750     datalen = BIO_get_mem_data(bio, &data);
9751     data[datalen] = '\0';
9752 
9753     k = pstrcat(p, env_prefix, "A_KEY", NULL);
9754     v = pstrdup(p, data);
9755     pr_env_set(p, k, v);
9756 
9757     BIO_free(bio);
9758   }
9759 
9760   bio = BIO_new(BIO_s_mem());
9761   PEM_write_bio_X509(bio, cert);
9762   datalen = BIO_get_mem_data(bio, &data);
9763   data[datalen] = '\0';
9764 
9765   k = pstrcat(p, env_prefix, "CERT", NULL);
9766   v = pstrdup(p, data);
9767   pr_env_set(p, k, v);
9768 
9769   BIO_free(bio);
9770 }
9771 
9772 static void tls_setup_environ(pool *p, SSL *ssl) {
9773   X509 *cert = NULL;
9774   STACK_OF(X509) *sk_cert_chain = NULL;
9775   char *k, *v;
9776 
9777   if (!(tls_opts & TLS_OPT_EXPORT_CERT_DATA) &&
9778       !(tls_opts & TLS_OPT_STD_ENV_VARS)) {
9779     return;
9780   }
9781 
9782   if (tls_opts & TLS_OPT_STD_ENV_VARS) {
9783     SSL_CIPHER *cipher = NULL;
9784     SSL_SESSION *ssl_session = NULL;
9785     const char *sni = NULL;
9786 
9787     k = pstrdup(p, "FTPS");
9788     v = pstrdup(p, "1");
9789     pr_env_set(p, k, v);
9790 
9791     k = pstrdup(p, "TLS_PROTOCOL");
9792     v = pstrdup(p, SSL_get_version(ssl));
9793     pr_env_set(p, k, v);
9794 
9795     /* Process the TLS session-related environ variable. */
9796     ssl_session = SSL_get_session(ssl);
9797     if (ssl_session) {
9798       const unsigned char *sess_data;
9799       unsigned int sess_datalen;
9800       char *sess_id;
9801 
9802 #if OPENSSL_VERSION_NUMBER >= 0x10100000L
9803       sess_data = SSL_SESSION_get_id(ssl_session, &sess_datalen);
9804 #else
9805       sess_datalen = ssl_session->session_id_length;
9806       sess_data = ssl_session->session_id;
9807 #endif /* OpenSSL-1.1.x and later */
9808 
9809       sess_id = pr_str_bin2hex(p, sess_data, sess_datalen,
9810         PR_STR_FL_HEX_USE_UC);
9811 
9812       k = pstrdup(p, "TLS_SESSION_ID");
9813       pr_env_set(p, k, sess_id);
9814     }
9815 
9816     /* Process the TLS cipher-related environ variables. */
9817     cipher = (SSL_CIPHER *) SSL_get_current_cipher(ssl);
9818     if (cipher) {
9819       char buf[10] = {'\0'};
9820       int cipher_bits_used = 0, cipher_bits_possible = 0;
9821 
9822       k = pstrdup(p, "TLS_CIPHER");
9823       v = pstrdup(p, SSL_CIPHER_get_name(cipher));
9824       pr_env_set(p, k, v);
9825 
9826       cipher_bits_used = SSL_CIPHER_get_bits(cipher, &cipher_bits_possible);
9827 
9828       if (cipher_bits_used < 56) {
9829         k = pstrdup(p, "TLS_CIPHER_EXPORT");
9830         v = pstrdup(p, "1");
9831         pr_env_set(p, k, v);
9832       }
9833 
9834       memset(buf, '\0', sizeof(buf));
9835       pr_snprintf(buf, sizeof(buf), "%d", cipher_bits_possible);
9836       buf[sizeof(buf)-1] = '\0';
9837 
9838       k = pstrdup(p, "TLS_CIPHER_KEYSIZE_POSSIBLE");
9839       v = pstrdup(p, buf);
9840       pr_env_set(p, k, v);
9841 
9842       memset(buf, '\0', sizeof(buf));
9843       pr_snprintf(buf, sizeof(buf), "%d", cipher_bits_used);
9844       buf[sizeof(buf)-1] = '\0';
9845 
9846       k = pstrdup(p, "TLS_CIPHER_KEYSIZE_USED");
9847       v = pstrdup(p, buf);
9848       pr_env_set(p, k, v);
9849     }
9850 
9851     sni = pr_table_get(session.notes, "mod_tls.sni", NULL);
9852     if (sni != NULL) {
9853       k = pstrdup(p, "TLS_SERVER_NAME");
9854       v = pstrdup(p, sni);
9855       pr_env_set(p, k, v);
9856     }
9857 
9858     k = pstrdup(p, "TLS_LIBRARY_VERSION");
9859     v = pstrdup(p, OPENSSL_VERSION_TEXT);
9860     pr_env_set(p, k, v);
9861   }
9862 
9863   sk_cert_chain = SSL_get_peer_cert_chain(ssl);
9864   if (sk_cert_chain) {
9865     register int i;
9866     char *data = NULL;
9867     long datalen = 0;
9868     BIO *bio = NULL;
9869 
9870     /* Adding TLS_CLIENT_CERT_CHAIN environ variables. */
9871     for (i = 0; i < sk_X509_num(sk_cert_chain); i++) {
9872       size_t klen = 256;
9873 
9874       pr_signals_handle();
9875 
9876       k = pcalloc(p, klen);
9877       pr_snprintf(k, klen - 1, "%s%u", "TLS_CLIENT_CERT_CHAIN", i + 1);
9878 
9879       bio = BIO_new(BIO_s_mem());
9880       PEM_write_bio_X509(bio, sk_X509_value(sk_cert_chain, i));
9881       datalen = BIO_get_mem_data(bio, &data);
9882       data[datalen] = '\0';
9883 
9884       v = pstrdup(p, data);
9885       pr_env_set(p, k, v);
9886 
9887       BIO_free(bio);
9888     }
9889   }
9890 
9891   /* Note: SSL_get_certificate() does NOT increment a reference counter,
9892    * so we do not call X509_free() on it.
9893    */
9894   cert = SSL_get_certificate(ssl);
9895   if (cert != NULL) {
9896     tls_setup_cert_environ(p, "TLS_SERVER_", cert);
9897 
9898   } else {
9899     tls_log("unable to set server certificate environ variables: "
9900       "Server certificate unavailable");
9901   }
9902 
9903   cert = SSL_get_peer_certificate(ssl);
9904   if (cert != NULL) {
9905     tls_setup_cert_environ(p, "TLS_CLIENT_", cert);
9906     X509_free(cert);
9907 
9908   } else {
9909     tls_log("unable to set client certificate environ variables: "
9910       "Client certificate unavailable");
9911   }
9912 }
9913 
9914 static void tls_setup_notes(pool *p, SSL *ssl) {
9915   SSL_CIPHER *cipher = NULL;
9916   const char *sni = NULL;
9917 
9918   (void) pr_table_add_dup(session.notes, "FTPS", "1", 0);
9919   (void) pr_table_add_dup(session.notes, "TLS_PROTOCOL", SSL_get_version(ssl),
9920     0);
9921 
9922   /* Process the TLS cipher-related values. */
9923   cipher = (SSL_CIPHER *) SSL_get_current_cipher(ssl);
9924   if (cipher != NULL) {
9925     (void) pr_table_add_dup(session.notes, "TLS_CIPHER",
9926       SSL_CIPHER_get_name(cipher), 0);
9927 
9928     sni = pr_table_get(session.notes, "mod_tls.sni", NULL);
9929     if (sni != NULL) {
9930       (void) pr_table_add_dup(session.notes, "TLS_SERVER_NAME", sni, 0);
9931     }
9932 
9933     (void) pr_table_add_dup(session.notes, "TLS_LIBRARY_VERSIONS",
9934       OPENSSL_VERSION_TEXT, 0);
9935   }
9936 }
9937 
9938 static int tls_verify_cb(int ok, X509_STORE_CTX *ctx) {
9939   config_rec *c;
9940   int verify_err = 0;
9941 
9942   /* We can configure the server to skip the peer's cert verification */
9943   if (!(tls_flags & TLS_SESS_VERIFY_CLIENT_REQUIRED) &&
9944       !(tls_flags & TLS_SESS_VERIFY_CLIENT_OPTIONAL)) {
9945     return 1;
9946   }
9947 
9948   c = find_config(main_server->conf, CONF_PARAM, "TLSVerifyOrder", FALSE);
9949   if (c) {
9950     register unsigned int i;
9951 
9952     for (i = 0; i < c->argc; i++) {
9953       char *mech = c->argv[i];
9954 
9955       if (strncasecmp(mech, "crl", 4) == 0) {
9956         ok = tls_verify_crl(ok, ctx);
9957         if (!ok) {
9958           break;
9959         }
9960 
9961       } else if (strncasecmp(mech, "ocsp", 5) == 0) {
9962         ok = tls_verify_ocsp(ok, ctx);
9963         if (!ok) {
9964           break;
9965         }
9966       }
9967     }
9968 
9969   } else {
9970     /* If no TLSVerifyOrder was specified, default to the old behavior of
9971      * always checking CRLs, if configured, and not paying attention to
9972      * any AIA attributes (i.e. no use of OCSP).
9973      */
9974     ok = tls_verify_crl(ok, ctx);
9975   }
9976 
9977   if (!ok) {
9978     X509 *cert;
9979     int ctx_error, depth;
9980 
9981     cert = X509_STORE_CTX_get_current_cert(ctx);
9982     depth = X509_STORE_CTX_get_error_depth(ctx);
9983 
9984 #if OPENSSL_VERSION_NUMBER >= 0x10100000L
9985     verify_err = X509_STORE_CTX_get_error(ctx);
9986 #else
9987     verify_err = ctx->error;
9988 #endif /* OpenSSL-1.1.x and later */
9989 
9990     tls_log("error: unable to verify certificate at depth %d", depth);
9991     tls_log("error: cert subject: %s", tls_x509_name_oneline(
9992       X509_get_subject_name(cert)));
9993     tls_log("error: cert issuer: %s", tls_x509_name_oneline(
9994       X509_get_issuer_name(cert)));
9995 
9996     /* Catch a too long certificate chain here. */
9997     if (depth > tls_verify_depth) {
9998       X509_STORE_CTX_set_error(ctx, X509_V_ERR_CERT_CHAIN_TOO_LONG);
9999     }
10000 
10001 #if OPENSSL_VERSION_NUMBER >= 0x10100000L
10002     ctx_error = X509_STORE_CTX_get_error(ctx);
10003 #else
10004     ctx_error = ctx->error;
10005 #endif /* OpenSSL-1.1.x and later */
10006 
10007     switch (ctx_error) {
10008       case X509_V_ERR_CERT_CHAIN_TOO_LONG:
10009       case X509_V_ERR_CERT_HAS_EXPIRED:
10010       case X509_V_ERR_CERT_REVOKED:
10011       case X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT:
10012       case X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN:
10013       case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY:
10014       case X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE:
10015       case X509_V_ERR_APPLICATION_VERIFICATION:
10016         tls_log("client certificate failed verification: %s",
10017           X509_verify_cert_error_string(ctx_error));
10018         ok = 0;
10019         break;
10020 
10021       case X509_V_ERR_INVALID_PURPOSE: {
10022         register int i;
10023         int count;
10024 
10025         tls_log("client certificate failed verification: %s",
10026           X509_verify_cert_error_string(ctx_error));
10027 
10028         count = X509_PURPOSE_get_count();
10029         for (i = 0; i < count; i++) {
10030           X509_PURPOSE *purp;
10031 
10032           purp = X509_PURPOSE_get0(i);
10033           tls_log("  purpose #%d: %s", i+1, X509_PURPOSE_get0_name(purp));
10034         }
10035 
10036         ok = 0;
10037         break;
10038       }
10039 
10040       default:
10041         tls_log("error verifying client certificate: [%d] %s",
10042           ctx_error, X509_verify_cert_error_string(ctx_error));
10043         ok = 0;
10044         break;
10045     }
10046   }
10047 
10048   if (ok) {
10049     pr_event_generate("mod_tls.verify-client", NULL);
10050 
10051   } else {
10052     pr_event_generate("mod_tls.verify-client-failed", &verify_err);
10053   }
10054 
10055   return ok;
10056 }
10057 
10058 /* This routine is (very much!) based on the work by Ralf S. Engelschall
10059  * <rse@engelshall.com>.  Comments by Ralf.
10060  */
10061 static int tls_verify_crl(int ok, X509_STORE_CTX *ctx) {
10062   register int i = 0;
10063   X509_NAME *subject = NULL, *issuer = NULL;
10064   X509 *xs = NULL;
10065   STACK_OF(X509_CRL) *crls = NULL;
10066   X509_STORE_CTX *store_ctx = NULL;
10067   int n, res;
10068 
10069   /* Unless a revocation store for CRLs was created we cannot do any
10070    * CRL-based verification, of course.
10071    */
10072   if (!tls_crl_store) {
10073     return ok;
10074   }
10075 
10076   tls_log("%s",
10077     "CRL store present, checking client certificate against configured CRLs");
10078 
10079   /* Determine certificate ingredients in advance. */
10080   xs = X509_STORE_CTX_get_current_cert(ctx);
10081 
10082   subject = X509_get_subject_name(xs);
10083   pr_trace_msg(trace_channel, 15,
10084     "verifying cert: subject = '%s'", tls_x509_name_oneline(subject));
10085 
10086   issuer = X509_get_issuer_name(xs);
10087   pr_trace_msg(trace_channel, 15,
10088     "verifying cert: issuer = '%s'", tls_x509_name_oneline(issuer));
10089 
10090   /* OpenSSL provides the general mechanism to deal with CRLs but does not
10091    * use them automatically when verifying certificates, so we do it
10092    * explicitly here. We will check the CRL for the currently checked
10093    * certificate, if there is such a CRL in the store.
10094    *
10095    * We come through this procedure for each certificate in the certificate
10096    * chain, starting with the root-CA's certificate. At each step we've to
10097    * both verify the signature on the CRL (to make sure it's a valid CRL)
10098    * and its revocation list (to make sure the current certificate isn't
10099    * revoked).  But because to check the signature on the CRL we need the
10100    * public key of the issuing CA certificate (which was already processed
10101    * one round before), we've a little problem. But we can both solve it and
10102    * at the same time optimize the processing by using the following
10103    * verification scheme (idea and code snippets borrowed from the GLOBUS
10104    * project):
10105    *
10106    * 1. We'll check the signature of a CRL in each step when we find a CRL
10107    *    through the _subject_ name of the current certificate. This CRL
10108    *    itself will be needed the first time in the next round, of course.
10109    *    But we do the signature processing one round before this where the
10110    *    public key of the CA is available.
10111    *
10112    * 2. We'll check the revocation list of a CRL in each step when
10113    *    we find a CRL through the _issuer_ name of the current certificate.
10114    *    This CRLs signature was then already verified one round before.
10115    *
10116    * This verification scheme allows a CA to revoke its own certificate as
10117    * well, of course.
10118    */
10119 
10120   /* Try to retrieve a CRL corresponding to the _subject_ of
10121    * the current certificate in order to verify its integrity.
10122    */
10123   store_ctx = X509_STORE_CTX_new();
10124 #if OPENSSL_VERSION_NUMBER > 0x000907000L
10125   if (X509_STORE_CTX_init(store_ctx, tls_crl_store, NULL, NULL) <= 0) {
10126     tls_log("error initializing CRL store context: %s", tls_get_errors());
10127     X509_STORE_CTX_free(store_ctx);
10128     return ok;
10129   }
10130 #else
10131   X509_STORE_CTX_init(store_ctx, tls_crl_store, NULL, NULL);
10132 #endif
10133 
10134 #if OPENSSL_VERSION_NUMBER >= 0x10100000L && \
10135     !defined(HAVE_LIBRESSL)
10136   crls = X509_STORE_CTX_get1_crls(store_ctx, issuer);
10137 #elif OPENSSL_VERSION_NUMBER >= 0x10000000L && \
10138       !defined(HAVE_LIBRESSL)
10139   crls = X509_STORE_get1_crls(store_ctx, issuer);
10140 #else
10141   /* Your OpenSSL is before 1.0.0.  You really need to upgrade. */
10142   crls = NULL;
10143 #endif /* OpenSSL-1.1.x and later */
10144   if (crls != NULL) {
10145     for (i = 0; i < sk_X509_CRL_num(crls); i++) {
10146       X509_CRL *crl = NULL;
10147       EVP_PKEY *pubkey;
10148       char buf[512];
10149       int len;
10150       BIO *b = BIO_new(BIO_s_mem());
10151 
10152       crl = sk_X509_CRL_value(crls, i);
10153       BIO_printf(b, "CA CRL: Issuer: ");
10154       X509_NAME_print(b, issuer, 0);
10155 
10156       BIO_printf(b, ", lastUpdate: ");
10157 #if OPENSSL_VERSION_NUMBER >= 0x10100000L
10158       ASN1_UTCTIME_print(b, X509_CRL_get_lastUpdate(crl));
10159 #else
10160       ASN1_UTCTIME_print(b, crl->crl->lastUpdate);
10161 #endif /* OpenSSL-1.1.x and later */
10162 
10163       BIO_printf(b, ", nextUpdate: ");
10164 #if OPENSSL_VERSION_NUMBER >= 0x10100000L
10165       ASN1_UTCTIME_print(b, X509_CRL_get_nextUpdate(crl));
10166 #else
10167       ASN1_UTCTIME_print(b, crl->crl->nextUpdate);
10168 #endif /* OpenSSL-1.1.x and later */
10169 
10170       len = BIO_read(b, buf, sizeof(buf) - 1);
10171       if ((size_t) len >= sizeof(buf)) {
10172         len = sizeof(buf)-1;
10173       }
10174       buf[len] = '\0';
10175 
10176       BIO_free(b);
10177       tls_log("%s", buf);
10178 
10179       pubkey = X509_get_pubkey(xs);
10180 
10181       /* Verify the signature on this CRL */
10182       res = X509_CRL_verify(crl, pubkey);
10183       if (pubkey) {
10184         EVP_PKEY_free(pubkey);
10185       }
10186 
10187       if (res <= 0) {
10188         tls_log("invalid signature on CRL: %s", tls_get_errors());
10189 
10190         X509_STORE_CTX_set_error(ctx, X509_V_ERR_CRL_SIGNATURE_FAILURE);
10191         sk_X509_CRL_free(crls);
10192         X509_STORE_CTX_cleanup(store_ctx);
10193         X509_STORE_CTX_free(store_ctx);
10194         return FALSE;
10195       }
10196 
10197       /* Check date of CRL to make sure it's not expired */
10198       res = X509_cmp_current_time(X509_CRL_get_nextUpdate(crl));
10199       if (res == 0) {
10200         tls_log("CRL has invalid nextUpdate field: %s", tls_get_errors());
10201 
10202         X509_STORE_CTX_set_error(ctx,
10203           X509_V_ERR_ERROR_IN_CRL_NEXT_UPDATE_FIELD);
10204         sk_X509_CRL_free(crls);
10205         X509_STORE_CTX_cleanup(store_ctx);
10206         X509_STORE_CTX_free(store_ctx);
10207         return FALSE;
10208       }
10209 
10210       if (res < 0) {
10211         /* XXX This is a bit draconian, rejecting all certificates if the CRL
10212          * has expired.  See also Bug#3216, about automatically reloading
10213          * the CRL file when it has expired.
10214          */
10215         tls_log("%s", "CRL is expired, revoking all certificates until an "
10216           "updated CRL is obtained");
10217 
10218         X509_STORE_CTX_set_error(ctx, X509_V_ERR_CRL_HAS_EXPIRED);
10219         sk_X509_CRL_free(crls);
10220         X509_STORE_CTX_cleanup(store_ctx);
10221         X509_STORE_CTX_free(store_ctx);
10222         return FALSE;
10223       }
10224     }
10225 
10226     sk_X509_CRL_free(crls);
10227     crls = NULL;
10228   }
10229 
10230   /* Try to retrieve a CRL corresponding to the _issuer_ of
10231    * the current certificate in order to check for revocation.
10232    */
10233 
10234 #if OPENSSL_VERSION_NUMBER >= 0x10100000L && \
10235     !defined(HAVE_LIBRESSL)
10236   crls = X509_STORE_CTX_get1_crls(store_ctx, subject);
10237 #elif OPENSSL_VERSION_NUMBER >= 0x10000000L && \
10238       !defined(HAVE_LIBRESSL)
10239   crls = X509_STORE_get1_crls(store_ctx, subject);
10240 #else
10241   /* Your OpenSSL is before 1.0.0.  You really need to upgrade. */
10242   crls = NULL;
10243 #endif /* OpenSSL-1.1.x and later */
10244   if (crls != NULL) {
10245     for (i = 0; i < sk_X509_CRL_num(crls); i++) {
10246       register int j;
10247       X509_CRL *crl;
10248 
10249       crl = sk_X509_CRL_value(crls, i);
10250 
10251       /* Check if the current certificate is revoked by this CRL */
10252       n = sk_X509_REVOKED_num(X509_CRL_get_REVOKED(crl));
10253       for (j = 0; j < n; j++) {
10254         X509_REVOKED *revoked;
10255         ASN1_INTEGER *sn;
10256 
10257         revoked = sk_X509_REVOKED_value(X509_CRL_get_REVOKED(crl), j);
10258         if (revoked == NULL) {
10259           continue;
10260         }
10261 #if OPENSSL_VERSION_NUMBER >= 0x10100000L && \
10262     !defined(HAVE_LIBRESSL)
10263         sn = X509_REVOKED_get0_serialNumber(revoked);
10264 #else
10265         sn = revoked->serialNumber;
10266 #endif /* OpenSSL-1.1.x and later */
10267 
10268         if (ASN1_INTEGER_cmp(sn, X509_get_serialNumber(xs)) == 0) {
10269           long serial = ASN1_INTEGER_get(sn);
10270           char *cp = tls_x509_name_oneline(issuer);
10271 
10272           tls_log("certificate with serial number %ld (0x%lX) revoked per CRL "
10273             "from issuer '%s'", serial, serial, cp ? cp : "(ERROR)");
10274 
10275           X509_STORE_CTX_set_error(ctx, X509_V_ERR_CERT_REVOKED);
10276           sk_X509_CRL_free(crls);
10277           X509_STORE_CTX_cleanup(store_ctx);
10278           X509_STORE_CTX_free(store_ctx);
10279           return FALSE;
10280         }
10281       }
10282     }
10283 
10284     sk_X509_CRL_free(crls);
10285   }
10286 
10287   X509_STORE_CTX_cleanup(store_ctx);
10288   X509_STORE_CTX_free(store_ctx);
10289   return ok;
10290 }
10291 
10292 #if OPENSSL_VERSION_NUMBER > 0x000907000L && defined(PR_USE_OPENSSL_OCSP)
10293 static int tls_verify_ocsp_url(X509_STORE_CTX *ctx, X509 *cert,
10294     const char *url) {
10295   BIO *conn;
10296   X509 *issuing_cert = NULL;
10297   X509_NAME *subj = NULL;
10298   X509_STORE *store = NULL;
10299   const char *subj_name;
10300   char *host = NULL, *port = NULL, *uri = NULL;
10301   int ok = FALSE, res = 0 , use_ssl = 0;
10302   int ocsp_status, ocsp_cert_status, ocsp_reason;
10303   OCSP_REQUEST *req = NULL;
10304   OCSP_RESPONSE *resp = NULL;
10305   OCSP_BASICRESP *basic_resp = NULL;
10306   SSL_CTX *ocsp_ssl_ctx = NULL;
10307 
10308   if (cert == NULL ||
10309       url == NULL) {
10310     return FALSE;
10311   }
10312 
10313   subj = X509_get_subject_name(cert);
10314   subj_name = tls_x509_name_oneline(subj);
10315 
10316   tls_log("checking OCSP URL '%s' for client cert '%s'", url, subj_name);
10317 
10318   /* Current OpenSSL implementation of OCSP_parse_url() guarantees that
10319    * host, port, and uri will never be NULL.  Nice.
10320    */
10321   if (OCSP_parse_url((char *) url, &host, &port, &uri, &use_ssl) != 1) {
10322     tls_log("error parsing OCSP URL '%s': %s", url, tls_get_errors());
10323     return FALSE;
10324   }
10325 
10326   tls_log("connecting to OCSP responder at host '%s', port '%s', URI '%s'%s",
10327     host, port, uri, use_ssl ? ", using SSL/TLS" : "");
10328 
10329   /* Connect to the OCSP responder indicated */
10330   conn = BIO_new_connect(host);
10331   if (conn == NULL) {
10332     tls_log("error creating connection BIO: %s", tls_get_errors());
10333 
10334     OPENSSL_free(host);
10335     OPENSSL_free(port);
10336     OPENSSL_free(uri);
10337 
10338     return FALSE;
10339   }
10340 
10341   BIO_set_conn_port(conn, port);
10342 
10343   /* If use_ssl is true, we need to a) create an SSL_CTX object to use, and
10344    * push it onto the BIO chain so that SSL/TLS actually happens.
10345    * When doing so, what version of SSL/TLS should we use?
10346    */
10347   if (use_ssl == 1) {
10348     BIO *ocsp_ssl_bio = NULL;
10349 
10350     /* Note: this code used openssl/apps/ocsp.c as a model. */
10351     ocsp_ssl_ctx = SSL_CTX_new(SSLv23_client_method());
10352     if (ocsp_ssl_ctx != NULL) {
10353       SSL_CTX_set_mode(ocsp_ssl_ctx, SSL_MODE_AUTO_RETRY);
10354 
10355       ocsp_ssl_bio = BIO_new_ssl(ocsp_ssl_ctx, 1);
10356       BIO_push(ocsp_ssl_bio, conn);
10357 
10358     } else {
10359       tls_log("error allocating SSL_CTX object for OCSP verification: %s",
10360         tls_get_errors());
10361     }
10362   }
10363 
10364   res = ocsp_connect(session.pool, conn, 0);
10365   if (res < 0) {
10366     tls_log("error connecting to OCSP URL '%s': %s", url, tls_get_errors());
10367 
10368     if (ocsp_ssl_ctx != NULL) {
10369       SSL_CTX_free(ocsp_ssl_ctx);
10370     }
10371 
10372     BIO_free_all(conn);
10373     OPENSSL_free(host);
10374     OPENSSL_free(port);
10375     OPENSSL_free(uri);
10376 
10377     /* XXX Should we give the client the benefit of the doubt, and allow
10378      * it to connect even though we can't talk to its OCSP responder?  Or
10379      * do we fail-close, and penalize the client if the OCSP responder is
10380      * down (e.g. for maintenance)?
10381      */
10382 
10383     return FALSE;
10384   }
10385 
10386   /* XXX Why are we querying the OCSP responder about the client cert's
10387    * issuing CA, rather than querying about the client cert itself?
10388    */
10389 
10390   res = X509_STORE_CTX_get1_issuer(&issuing_cert, ctx, cert);
10391   if (res != 1) {
10392     tls_log("error retrieving issuing cert for client cert '%s': %s",
10393       subj_name, tls_get_errors());
10394 
10395     if (ocsp_ssl_ctx != NULL) {
10396       SSL_CTX_free(ocsp_ssl_ctx);
10397     }
10398 
10399     BIO_free_all(conn);
10400     OPENSSL_free(host);
10401     OPENSSL_free(port);
10402     OPENSSL_free(uri);
10403 
10404     return FALSE;
10405   }
10406 
10407   req = ocsp_get_request(session.pool, cert, issuing_cert);
10408   if (req == NULL) {
10409     if (ocsp_ssl_ctx != NULL) {
10410       SSL_CTX_free(ocsp_ssl_ctx);
10411     }
10412 
10413     X509_free(issuing_cert);
10414     BIO_free_all(conn);
10415     OPENSSL_free(host);
10416     OPENSSL_free(port);
10417     OPENSSL_free(uri);
10418 
10419     return FALSE;
10420   }
10421 
10422 # if 0
10423   /* XXX ideally we would set the requestor name to the subject name of the
10424    * cert configured via TLS{DSA,RSA}CertificateFile here.
10425    */
10426   if (OCSP_request_set1_name(req, /* server cert X509_NAME subj name */) != 1) {
10427     tls_log("error adding requestor name '%s' to OCSP request: %s",
10428       requestor_name, tls_get_errors());
10429 
10430     if (ocsp_ssl_ctx != NULL) {
10431       SSL_CTX_free(ocsp_ssl_ctx);
10432     }
10433 
10434     OCSP_REQUEST_free(req);
10435     X509_free(issuing_cert);
10436     BIO_free_all(conn);
10437     OPENSSL_free(host);
10438     OPENSSL_free(port);
10439     OPENSSL_free(uri);
10440 
10441     return FALSE;
10442   }
10443 # endif
10444 
10445   if (tls_opts & TLS_OPT_ENABLE_DIAGS) {
10446     BIO *bio;
10447 
10448     bio = BIO_new(BIO_s_mem());
10449     if (bio != NULL) {
10450       if (OCSP_REQUEST_print(bio, req, 0) == 1) {
10451         char *data = NULL;
10452         long datalen;
10453 
10454         datalen = BIO_get_mem_data(bio, &data);
10455         if (data != NULL) {
10456           data[datalen] = '\0';
10457           tls_log("sending OCSP request (%ld bytes):\n%s", datalen, data);
10458         }
10459       }
10460 
10461       BIO_free(bio);
10462     }
10463   }
10464 
10465   resp = ocsp_send_request(session.pool, conn, host, uri, req, 0);
10466   if (resp == NULL) {
10467     tls_log("error receiving response from OCSP responder at '%s': %s", url,
10468       tls_get_errors());
10469 
10470     if (ocsp_ssl_ctx != NULL) {
10471       SSL_CTX_free(ocsp_ssl_ctx);
10472     }
10473 
10474     OCSP_REQUEST_free(req);
10475     X509_free(issuing_cert);
10476     BIO_free_all(conn);
10477     OPENSSL_free(host);
10478     OPENSSL_free(port);
10479     OPENSSL_free(uri);
10480 
10481     return FALSE;
10482   }
10483 
10484   if (tls_opts & TLS_OPT_ENABLE_DIAGS) {
10485     BIO *bio;
10486 
10487     bio = BIO_new(BIO_s_mem());
10488     if (bio != NULL) {
10489       if (OCSP_RESPONSE_print(bio, resp, 0) == 1) {
10490         char *data = NULL;
10491         long datalen;
10492 
10493         datalen = BIO_get_mem_data(bio, &data);
10494         if (data != NULL) {
10495           data[datalen] = '\0';
10496           tls_log("received OCSP response (%ld bytes):\n%s", datalen, data);
10497         }
10498       }
10499 
10500       BIO_free(bio);
10501     }
10502   }
10503 
10504   tls_log("checking response from OCSP responder at URL '%s' for client cert "
10505     "'%s'", url, subj_name);
10506 
10507   basic_resp = OCSP_response_get1_basic(resp);
10508   if (basic_resp == NULL) {
10509     tls_log("error retrieving basic response from OCSP responder at '%s': %s",
10510       url, tls_get_errors());
10511 
10512     if (ocsp_ssl_ctx != NULL) {
10513       SSL_CTX_free(ocsp_ssl_ctx);
10514     }
10515 
10516     OCSP_RESPONSE_free(resp);
10517     OCSP_REQUEST_free(req);
10518     X509_free(issuing_cert);
10519     BIO_free_all(conn);
10520     OPENSSL_free(host);
10521     OPENSSL_free(port);
10522     OPENSSL_free(uri);
10523 
10524     return FALSE;
10525   }
10526 
10527 #if OPENSSL_VERSION_NUMBER >= 0x10100000L && \
10528     !defined(HAVE_LIBRESSL)
10529   store = X509_STORE_CTX_get0_store(ctx);
10530 #else
10531   store = ctx->ctx;
10532 #endif /* OpenSSL-1.1.x and later */
10533   res = OCSP_basic_verify(basic_resp, NULL, store, 0);
10534   if (res != 1) {
10535     tls_log("error verifying basic response from OCSP responder at '%s': %s",
10536       url, tls_get_errors());
10537 
10538     if (ocsp_ssl_ctx != NULL) {
10539       SSL_CTX_free(ocsp_ssl_ctx);
10540     }
10541 
10542     OCSP_REQUEST_free(req);
10543     OCSP_BASICRESP_free(basic_resp);
10544     OCSP_RESPONSE_free(resp);
10545     X509_free(issuing_cert);
10546     BIO_free_all(conn);
10547     OPENSSL_free(host);
10548     OPENSSL_free(port);
10549     OPENSSL_free(uri);
10550 
10551     return FALSE;
10552   }
10553 
10554   /* Now that we have verified the response, we can check the response status.
10555    * If we only looked at the status first, then a malicious responder
10556    * could be tricking us, e.g.:
10557    *
10558    *  http://www.thoughtcrime.org/papers/ocsp-attack.pdf
10559    */
10560 
10561   ocsp_status = OCSP_response_status(resp);
10562   if (ocsp_status != OCSP_RESPONSE_STATUS_SUCCESSFUL) {
10563     tls_log("unable to verify client cert '%s' via OCSP responder at '%s': "
10564       "response status '%s' (%d)", subj_name, url,
10565       OCSP_response_status_str(ocsp_status), ocsp_status);
10566 
10567     if (ocsp_ssl_ctx != NULL) {
10568       SSL_CTX_free(ocsp_ssl_ctx);
10569     }
10570 
10571     OCSP_REQUEST_free(req);
10572     OCSP_BASICRESP_free(basic_resp);
10573     OCSP_RESPONSE_free(resp);
10574     X509_free(issuing_cert);
10575     BIO_free_all(conn);
10576     OPENSSL_free(host);
10577     OPENSSL_free(port);
10578     OPENSSL_free(uri);
10579 
10580     switch (ocsp_status) {
10581       case OCSP_RESPONSE_STATUS_MALFORMEDREQUEST:
10582       case OCSP_RESPONSE_STATUS_INTERNALERROR:
10583       case OCSP_RESPONSE_STATUS_SIGREQUIRED:
10584       case OCSP_RESPONSE_STATUS_UNAUTHORIZED:
10585       case OCSP_RESPONSE_STATUS_TRYLATER:
10586         /* XXX For now, for the above OCSP response reasons, give the client
10587          * the benefit of the doubt, since all of the above non-success
10588          * response codes indicate either a) an issue with the OCSP responder
10589          * outside of the client's control, or b) an issue with our OCSP
10590          * implementation (e.g. SIGREQUIRED, UNAUTHORIZED).
10591          */
10592         ok = TRUE;
10593         break;
10594 
10595       default:
10596         ok = FALSE;
10597     }
10598 
10599     return ok;
10600   }
10601 
10602   if (ocsp_check_cert_status(session.pool, cert, issuing_cert, basic_resp,
10603       &ocsp_cert_status, &ocsp_reason) < 0) {
10604     tls_log("unable to retrieve cert status from OCSP response: %s",
10605       tls_get_errors());
10606 
10607     if (ocsp_ssl_ctx != NULL) {
10608       SSL_CTX_free(ocsp_ssl_ctx);
10609     }
10610 
10611     OCSP_REQUEST_free(req);
10612     OCSP_BASICRESP_free(basic_resp);
10613     OCSP_RESPONSE_free(resp);
10614     X509_free(issuing_cert);
10615     BIO_free_all(conn);
10616     OPENSSL_free(host);
10617     OPENSSL_free(port);
10618     OPENSSL_free(uri);
10619 
10620     return FALSE;
10621   }
10622 
10623   tls_log("client cert '%s' has '%s' (%d) status according to OCSP responder "
10624     "at '%s'", subj_name, OCSP_cert_status_str(ocsp_cert_status),
10625     ocsp_cert_status, url);
10626 
10627   switch (ocsp_cert_status) {
10628     case V_OCSP_CERTSTATUS_GOOD:
10629       ok = TRUE;
10630       break;
10631 
10632     case V_OCSP_CERTSTATUS_REVOKED:
10633       tls_log("client cert '%s' has '%s' status due to: %s", subj_name,
10634         OCSP_cert_status_str(ocsp_status), OCSP_crl_reason_str(ocsp_reason));
10635       ok = FALSE;
10636       break;
10637 
10638     case V_OCSP_CERTSTATUS_UNKNOWN:
10639       /* If the client cert points to an OCSP responder which claims not to
10640        * know about the client cert, then we shouldn't trust that client
10641        * cert.  Otherwise, a client could present a cert pointing to an
10642        * OCSP responder which they KNOW won't know about the client cert,
10643        * and could then slip through the verification process.
10644        */
10645       ok = FALSE;
10646       break;
10647 
10648     default:
10649       ok = FALSE;
10650   }
10651 
10652   if (ocsp_ssl_ctx != NULL) {
10653     SSL_CTX_free(ocsp_ssl_ctx);
10654   }
10655 
10656   OCSP_REQUEST_free(req);
10657   OCSP_BASICRESP_free(basic_resp);
10658   OCSP_RESPONSE_free(resp);
10659   X509_free(issuing_cert);
10660   BIO_free_all(conn);
10661   OPENSSL_free(host);
10662   OPENSSL_free(port);
10663   OPENSSL_free(uri);
10664 
10665   return ok;
10666 }
10667 #endif
10668 
10669 static int tls_verify_ocsp(int ok, X509_STORE_CTX *ctx) {
10670 #if OPENSSL_VERSION_NUMBER > 0x000907000L && defined(PR_USE_OPENSSL_OCSP)
10671   register int i;
10672   X509 *cert;
10673   const char *subj;
10674   STACK_OF(ACCESS_DESCRIPTION) *descs;
10675   pool *tmp_pool = NULL;
10676   array_header *ocsp_urls = NULL;
10677 
10678   /* Set a default verification error here; it will be superseded as needed
10679    * later during the verification process.
10680    */
10681   X509_STORE_CTX_set_error(ctx, X509_V_ERR_APPLICATION_VERIFICATION);
10682 
10683   cert = X509_STORE_CTX_get_current_cert(ctx);
10684   if (cert == NULL) {
10685     return ok;
10686   }
10687 
10688   subj = tls_x509_name_oneline(X509_get_subject_name(cert));
10689 
10690   descs = X509_get_ext_d2i(cert, NID_info_access, NULL, NULL);
10691   if (descs == NULL) {
10692     tls_log("Client cert '%s' contained no AuthorityInfoAccess attribute, "
10693       "unable to verify via OCSP", subj);
10694     return ok;
10695   }
10696 
10697   for (i = 0; i < sk_ACCESS_DESCRIPTION_num(descs); i++) {
10698     ACCESS_DESCRIPTION *desc;
10699 
10700     desc = sk_ACCESS_DESCRIPTION_value(descs, i);
10701     if (OBJ_obj2nid(desc->method) == NID_ad_OCSP) {
10702       /* Found an OCSP AuthorityInfoAccess attribute */
10703 
10704       if (desc->location->type != GEN_URI) {
10705         /* Not a valid URI, ignore it. */
10706         continue;
10707       }
10708 
10709       /* Add this URL to the list of OCSP URLs to check. */
10710       if (ocsp_urls == NULL) {
10711         tmp_pool = make_sub_pool(session.pool);
10712         ocsp_urls = make_array(tmp_pool, 1, sizeof(char *));
10713       }
10714 
10715       *((char **) push_array(ocsp_urls)) = pstrdup(tmp_pool,
10716         (char *) desc->location->d.uniformResourceIdentifier->data);
10717     }
10718   }
10719 
10720   if (ocsp_urls == NULL) {
10721     tls_log("found no OCSP URLs in AuthorityInfoAccess attribute for client "
10722       "cert '%s', unable to verify via OCSP", subj);
10723     AUTHORITY_INFO_ACCESS_free(descs);
10724     return ok;
10725   }
10726 
10727   tls_log("found %u OCSP %s in AuthorityInfoAccess attribute for client cert "
10728     "'%s'", ocsp_urls->nelts, ocsp_urls->nelts != 1 ? "URLs" : "URL", subj);
10729 
10730   /* Check each of the URLs. */
10731   for (i = 0; i < (int) ocsp_urls->nelts; i++) {
10732     char *url = ((char **) ocsp_urls->elts)[i];
10733 
10734     ok = tls_verify_ocsp_url(ctx, cert, url);
10735     if (ok)
10736       break;
10737   }
10738 
10739   destroy_pool(tmp_pool);
10740   AUTHORITY_INFO_ACCESS_free(descs);
10741 
10742   return ok;
10743 #else
10744   return ok;
10745 #endif
10746 }
10747 
10748 static ssize_t tls_write(SSL *ssl, const void *buf, size_t len) {
10749   ssize_t count;
10750   int lineno, xerrno = 0;
10751 
10752   /* Help ensure we have a clean/trustable errno value. */
10753   errno = 0;
10754 
10755   lineno = __LINE__ + 1;
10756   count = SSL_write(ssl, buf, len);
10757   xerrno = errno;
10758 
10759   if (count < 0) {
10760     long err = SSL_get_error(ssl, count);
10761 
10762     /* write(2) returns only the generic error number -1 */
10763     count = -1;
10764 
10765     switch (err) {
10766       case SSL_ERROR_WANT_READ:
10767       case SSL_ERROR_WANT_WRITE:
10768         /* Simulate an EINTR in case OpenSSL wants to write more. */
10769         xerrno = EINTR;
10770         break;
10771 
10772       case SSL_ERROR_SSL:
10773       case SSL_ERROR_SYSCALL:
10774       default:
10775         tls_fatal_error(err, lineno);
10776         break;
10777     }
10778   }
10779 
10780   if (ssl != ctrl_ssl) {
10781     BIO *wbio;
10782     uint64_t now;
10783 
10784     (void) pr_gettimeofday_millis(&now);
10785     tls_data_adaptive_bytes_written_count += count;
10786     wbio = SSL_get_wbio(ssl);
10787 
10788     if (tls_data_adaptive_bytes_written_count >= TLS_DATA_ADAPTIVE_WRITE_BOOST_THRESHOLD) {
10789       /* Boost the buffer size if we've written more than the "boost"
10790        * threshold.
10791        */
10792       (void) BIO_set_write_buf_size(wbio,
10793         TLS_DATA_ADAPTIVE_WRITE_MAX_BUFFER_SIZE);
10794     }
10795 
10796     if (now > (tls_data_adaptive_bytes_written_ms + TLS_DATA_ADAPTIVE_WRITE_BOOST_INTERVAL_MS)) {
10797       /* If it's been longer than the boost interval since our last write,
10798        * then reset the buffer size to the smaller version, assuming
10799        * congestion (and thus closing of the TCP congestion window).
10800        */
10801       tls_data_adaptive_bytes_written_count = 0;
10802       (void) BIO_set_write_buf_size(wbio,
10803         TLS_DATA_ADAPTIVE_WRITE_MIN_BUFFER_SIZE);
10804     }
10805 
10806     tls_data_adaptive_bytes_written_ms = now;
10807   }
10808 
10809   errno = xerrno;
10810   return count;
10811 }
10812 
10813 static char *tls_x509_name_oneline(X509_NAME *x509_name) {
10814   static char buf[1024] = {'\0'};
10815 
10816   /* If we are using OpenSSL 0.9.6 or newer, we want to use
10817    * X509_NAME_print_ex() instead of X509_NAME_oneline().
10818    */
10819 
10820 #if OPENSSL_VERSION_NUMBER < 0x000906000L
10821   memset(&buf, '\0', sizeof(buf));
10822   return X509_NAME_oneline(x509_name, buf, sizeof(buf)-1);
10823 #else
10824 
10825   /* Sigh...do it the hard way. */
10826   BIO *mem = BIO_new(BIO_s_mem());
10827   char *data = NULL;
10828   long datalen = 0;
10829   int ok;
10830 
10831   ok = X509_NAME_print_ex(mem, x509_name, 0, XN_FLAG_ONELINE);
10832   if (ok) {
10833     datalen = BIO_get_mem_data(mem, &data);
10834 
10835     if (data) {
10836       memset(&buf, '\0', sizeof(buf));
10837 
10838       if ((size_t) datalen >= sizeof(buf)) {
10839         datalen = sizeof(buf)-1;
10840       }
10841 
10842       memcpy(buf, data, datalen);
10843 
10844       buf[datalen] = '\0';
10845       buf[sizeof(buf)-1] = '\0';
10846 
10847       BIO_free(mem);
10848       return buf;
10849     }
10850   }
10851 
10852   BIO_free(mem);
10853   return NULL;
10854 #endif /* OPENSSL_VERSION_NUMBER >= 0x000906000 */
10855 }
10856 
10857 /* Session cache API */
10858 
10859 struct tls_scache {
10860   struct tls_scache *next, *prev;
10861 
10862   const char *name;
10863   tls_sess_cache_t *cache;
10864 };
10865 
10866 static pool *tls_sess_cache_pool = NULL;
10867 static struct tls_scache *tls_sess_caches = NULL;
10868 static unsigned int tls_sess_ncaches = 0;
10869 
10870 int tls_sess_cache_register(const char *name, tls_sess_cache_t *cache) {
10871   struct tls_scache *sc;
10872 
10873   if (name == NULL ||
10874       cache == NULL) {
10875     errno = EINVAL;
10876     return -1;
10877   }
10878 
10879   if (tls_sess_cache_pool == NULL) {
10880     tls_sess_cache_pool = make_sub_pool(permanent_pool);
10881     pr_pool_tag(tls_sess_cache_pool, "TLS Session Cache API Pool");
10882   }
10883 
10884   /* Make sure this cache has not already been registered. */
10885   if (tls_sess_cache_get_cache(name) != NULL) {
10886     errno = EEXIST;
10887     return -1;
10888   }
10889 
10890   sc = pcalloc(tls_sess_cache_pool, sizeof(struct tls_scache));
10891 
10892   /* XXX Should this name string be dup'd from the tls_sess_cache_pool? */
10893   sc->name = name;
10894   cache->cache_name = pstrdup(tls_sess_cache_pool, name);
10895   sc->cache = cache;
10896 
10897   if (tls_sess_caches) {
10898     sc->next = tls_sess_caches;
10899 
10900   } else {
10901     sc->next = NULL;
10902   }
10903 
10904   tls_sess_caches = sc;
10905   tls_sess_ncaches++;
10906 
10907   return 0;
10908 }
10909 
10910 int tls_sess_cache_unregister(const char *name) {
10911   struct tls_scache *sc;
10912 
10913   if (name == NULL) {
10914     errno = EINVAL;
10915     return -1;
10916   }
10917 
10918   for (sc = tls_sess_caches; sc; sc = sc->next) {
10919     if (strcmp(sc->name, name) == 0) {
10920 
10921       if (sc->prev) {
10922         sc->prev->next = sc->next;
10923 
10924       } else {
10925         /* If prev is NULL, this is the head of the list. */
10926         tls_sess_caches = sc->next;
10927       }
10928 
10929       if (sc->next) {
10930         sc->next->prev = sc->prev;
10931       }
10932 
10933       sc->next = sc->prev = NULL;
10934       tls_sess_ncaches--;
10935 
10936       /* If the session cache being unregistered is in use, update the
10937        * session-cache-in-use pointer.
10938        */
10939       if (sc->cache == tls_sess_cache) {
10940         tls_sess_cache_close();
10941         tls_sess_cache = NULL;
10942       }
10943 
10944       /* NOTE: a counter should be kept of the number of unregistrations,
10945        * as the memory for a registration is not freed on unregistration.
10946        */
10947 
10948       return 0;
10949     }
10950   }
10951 
10952   errno = ENOENT;
10953   return -1;
10954 }
10955 
10956 static tls_sess_cache_t *tls_sess_cache_get_cache(const char *name) {
10957   struct tls_scache *sc;
10958 
10959   if (name == NULL) {
10960     errno = EINVAL;
10961     return NULL;
10962   }
10963 
10964   for (sc = tls_sess_caches; sc; sc = sc->next) {
10965     if (strcmp(sc->name, name) == 0) {
10966       return sc->cache;
10967     }
10968   }
10969 
10970   errno = ENOENT;
10971   return NULL;
10972 }
10973 
10974 static long tls_sess_cache_get_cache_mode(void) {
10975   if (tls_sess_cache == NULL) {
10976     return 0;
10977   }
10978 
10979   return tls_sess_cache->cache_mode;
10980 }
10981 
10982 static int tls_sess_cache_open(char *info, long timeout) {
10983   int res;
10984 
10985   if (tls_sess_cache == NULL) {
10986     errno = ENOSYS;
10987     return -1;
10988   }
10989 
10990   res = (tls_sess_cache->open)(tls_sess_cache, info, timeout);
10991   return res;
10992 }
10993 
10994 static int tls_sess_cache_close(void) {
10995   int res;
10996 
10997   if (tls_sess_cache == NULL) {
10998     errno = ENOSYS;
10999     return -1;
11000   }
11001 
11002   res = (tls_sess_cache->close)(tls_sess_cache);
11003   return res;
11004 }
11005 
11006 #ifdef PR_USE_CTRLS
11007 static int tls_sess_cache_clear(void) {
11008   int res;
11009 
11010   if (tls_sess_cache == NULL) {
11011     errno = ENOSYS;
11012     return -1;
11013   }
11014 
11015   res = (tls_sess_cache->clear)(tls_sess_cache);
11016   return res;
11017 }
11018 
11019 static int tls_sess_cache_remove(void) {
11020   int res;
11021 
11022   if (tls_sess_cache == NULL) {
11023     errno = ENOSYS;
11024     return -1;
11025   }
11026 
11027   res = (tls_sess_cache->remove)(tls_sess_cache);
11028   return res;
11029 }
11030 
11031 static void sess_cache_printf(void *ctrl, const char *fmt, ...) {
11032   char buf[PR_TUNABLE_BUFFER_SIZE];
11033   va_list msg;
11034 
11035   memset(buf, '\0', sizeof(buf));
11036 
11037   va_start(msg, fmt);
11038   pr_vsnprintf(buf, sizeof(buf), fmt, msg);
11039   va_end(msg);
11040 
11041   buf[sizeof(buf)-1] = '\0';
11042   pr_ctrls_add_response(ctrl, "%s", buf);
11043 }
11044 
11045 static int tls_sess_cache_status(pr_ctrls_t *ctrl, int flags) {
11046   int res = 0;
11047 
11048   if (tls_sess_cache != NULL) {
11049     res = (tls_sess_cache->status)(tls_sess_cache, sess_cache_printf, ctrl,
11050       flags);
11051     return res;
11052   }
11053 
11054   pr_ctrls_add_response(ctrl, "No TLSSessionCache configured");
11055   return res;
11056 }
11057 #endif /* PR_USE_CTRLS */
11058 
11059 /* OCSP response cache API */
11060 
11061 struct tls_ocache {
11062   struct tls_ocache *next, *prev;
11063 
11064   const char *name;
11065   tls_ocsp_cache_t *cache;
11066 };
11067 
11068 #if defined(PR_USE_OPENSSL_OCSP)
11069 static pool *tls_ocsp_cache_pool = NULL;
11070 static struct tls_ocache *tls_ocsp_caches = NULL;
11071 static unsigned int tls_ocsp_ncaches = 0;
11072 #endif /* PR_USE_OPENSSL_OCSP */
11073 
11074 int tls_ocsp_cache_register(const char *name, tls_ocsp_cache_t *cache) {
11075 #if defined(PR_USE_OPENSSL_OCSP)
11076   struct tls_ocache *oc;
11077 
11078   if (name == NULL ||
11079       cache == NULL) {
11080     errno = EINVAL;
11081     return -1;
11082   }
11083 
11084   if (tls_ocsp_cache_pool == NULL) {
11085     tls_ocsp_cache_pool = make_sub_pool(permanent_pool);
11086     pr_pool_tag(tls_ocsp_cache_pool, "TLS OCSP Response Cache API Pool");
11087   }
11088 
11089   /* Make sure this cache has not already been registered. */
11090   if (tls_ocsp_cache_get_cache(name) != NULL) {
11091     errno = EEXIST;
11092     return -1;
11093   }
11094 
11095   oc = pcalloc(tls_ocsp_cache_pool, sizeof(struct tls_ocache));
11096 
11097   /* XXX Should this name string be dup'd from the tls_ocsp_cache_pool? */
11098   oc->name = name;
11099   cache->cache_name = pstrdup(tls_ocsp_cache_pool, name);
11100   oc->cache = cache;
11101 
11102   if (tls_ocsp_caches != NULL) {
11103     oc->next = tls_ocsp_caches;
11104 
11105   } else {
11106     oc->next = NULL;
11107   }
11108 
11109   tls_ocsp_caches = oc;
11110   tls_ocsp_ncaches++;
11111 
11112   return 0;
11113 #else
11114   errno = ENOSYS;
11115   return -1;
11116 #endif /* PR_USE_OPENSSL_OCSP */
11117 }
11118 
11119 int tls_ocsp_cache_unregister(const char *name) {
11120 #if defined(PR_USE_OPENSSL_OCSP)
11121   struct tls_ocache *oc;
11122 
11123   if (name == NULL) {
11124     errno = EINVAL;
11125     return -1;
11126   }
11127 
11128   for (oc = tls_ocsp_caches; oc; oc = oc->next) {
11129     if (strcmp(oc->name, name) == 0) {
11130 
11131       if (oc->prev) {
11132         oc->prev->next = oc->next;
11133 
11134       } else {
11135         /* If prev is NULL, this is the head of the list. */
11136         tls_ocsp_caches = oc->next;
11137       }
11138 
11139       if (oc->next) {
11140         oc->next->prev = oc->prev;
11141       }
11142 
11143       oc->next = oc->prev = NULL;
11144       tls_ocsp_ncaches--;
11145 
11146       /* If the OCSP response cache being unregistered is in use, update the
11147        * ocsp-cache-in-use pointer.
11148        */
11149       if (oc->cache == tls_ocsp_cache) {
11150         tls_ocsp_cache_close();
11151         tls_ocsp_cache = NULL;
11152       }
11153 
11154       /* NOTE: a counter should be kept of the number of unregistrations,
11155        * as the memory for a registration is not freed on unregistration.
11156        */
11157 
11158       return 0;
11159     }
11160   }
11161 
11162   errno = ENOENT;
11163   return -1;
11164 #else
11165   errno = ENOSYS;
11166   return -1;
11167 #endif /* PR_USE_OPENSSL_OCSP */
11168 }
11169 
11170 static tls_ocsp_cache_t *tls_ocsp_cache_get_cache(const char *name) {
11171 #if defined(PR_USE_OPENSSL_OCSP)
11172   struct tls_ocache *oc;
11173 
11174   if (name == NULL) {
11175     errno = EINVAL;
11176     return NULL;
11177   }
11178 
11179   for (oc = tls_ocsp_caches; oc; oc = oc->next) {
11180     if (strcmp(oc->name, name) == 0) {
11181       return oc->cache;
11182     }
11183   }
11184 
11185   errno = ENOENT;
11186   return NULL;
11187 #else
11188   errno = ENOSYS;
11189   return NULL;
11190 #endif /* PR_USE_OPENSSL_OCSP */
11191 }
11192 
11193 static int tls_ocsp_cache_open(char *info) {
11194 #if defined(PR_USE_OPENSSL_OCSP)
11195   int res;
11196 
11197   if (tls_ocsp_cache == NULL) {
11198     errno = ENOSYS;
11199     return -1;
11200   }
11201 
11202   res = (tls_ocsp_cache->open)(tls_ocsp_cache, info);
11203   return res;
11204 #else
11205   errno = ENOSYS;
11206   return -1;
11207 #endif /* PR_USE_OPENSSL_OCSP */
11208 }
11209 
11210 static int tls_ocsp_cache_close(void) {
11211 #if defined(PR_USE_OPENSSL_OCSP)
11212   int res;
11213 
11214   if (tls_ocsp_cache == NULL) {
11215     errno = ENOSYS;
11216     return -1;
11217   }
11218 
11219   res = (tls_ocsp_cache->close)(tls_ocsp_cache);
11220   return res;
11221 #else
11222   errno = ENOSYS;
11223   return -1;
11224 #endif /* PR_USE_OPENSSL_OCSP */
11225 }
11226 
11227 #ifdef PR_USE_CTRLS
11228 static int tls_ocsp_cache_clear(void) {
11229 # if defined(PR_USE_OPENSSL_OCSP)
11230   int res;
11231 
11232   if (tls_ocsp_cache == NULL) {
11233     errno = ENOSYS;
11234     return -1;
11235   }
11236 
11237   res = (tls_ocsp_cache->clear)(tls_ocsp_cache);
11238   return res;
11239 # else
11240   errno = ENOSYS;
11241   return -1;
11242 # endif /* PR_USE_OPENSSL_OCSP */
11243 }
11244 
11245 static int tls_ocsp_cache_remove(void) {
11246 # if defined(PR_USE_OPENSSL_OCSP)
11247   int res;
11248 
11249   if (tls_ocsp_cache == NULL) {
11250     errno = ENOSYS;
11251     return -1;
11252   }
11253 
11254   res = (tls_ocsp_cache->remove)(tls_ocsp_cache);
11255   return res;
11256 # else
11257   errno = ENOSYS;
11258   return -1;
11259 # endif /* PR_USE_OPENSSL_OCSP */
11260 }
11261 
11262 # if defined(PR_USE_OPENSSL_OCSP)
11263 static void ocsp_cache_printf(void *ctrl, const char *fmt, ...) {
11264   char buf[PR_TUNABLE_BUFFER_SIZE];
11265   va_list msg;
11266 
11267   memset(buf, '\0', sizeof(buf));
11268 
11269   va_start(msg, fmt);
11270   pr_vsnprintf(buf, sizeof(buf), fmt, msg);
11271   va_end(msg);
11272 
11273   buf[sizeof(buf)-1] = '\0';
11274   pr_ctrls_add_response(ctrl, "%s", buf);
11275 }
11276 # endif /* PR_USE_OPENSSL_OCSP */
11277 
11278 static int tls_ocsp_cache_status(pr_ctrls_t *ctrl, int flags) {
11279 # if defined(PR_USE_OPENSSL_OCSP)
11280   int res = 0;
11281 
11282   if (tls_ocsp_cache != NULL) {
11283     res = (tls_ocsp_cache->status)(tls_ocsp_cache, ocsp_cache_printf, ctrl,
11284       flags);
11285     return res;
11286   }
11287 
11288   pr_ctrls_add_response(ctrl, "No TLSStaplingCache configured");
11289   return res;
11290 # else
11291   errno = ENOSYS;
11292   return -1;
11293 # endif /* PR_USE_OPENSSL_OCSP */
11294 }
11295 #endif /* PR_USE_CTRLS */
11296 
11297 /* Controls
11298  */
11299 
11300 #ifdef PR_USE_CTRLS
11301 static int tls_handle_sesscache_clear(pr_ctrls_t *ctrl, int reqargc,
11302     char **reqargv) {
11303   int res;
11304 
11305   res = tls_sess_cache_clear();
11306   if (res < 0) {
11307     pr_ctrls_add_response(ctrl,
11308       "tls sesscache: error clearing session cache: %s", strerror(errno));
11309 
11310   } else {
11311     pr_ctrls_add_response(ctrl, "tls sesscache: cleared %d %s from '%s' "
11312       "session cache", res, res != 1 ? "sessions" : "session",
11313       tls_sess_cache->cache_name);
11314     res = 0;
11315   }
11316 
11317   return res;
11318 }
11319 
11320 static int tls_handle_sesscache_info(pr_ctrls_t *ctrl, int reqargc,
11321     char **reqargv) {
11322   int flags = 0, optc, res;
11323   const char *opts = "v";
11324 
11325   pr_getopt_reset();
11326 
11327   while ((optc = getopt(reqargc, reqargv, opts)) != -1) {
11328     switch (optc) {
11329       case 'v':
11330         flags = TLS_SESS_CACHE_STATUS_FL_SHOW_SESSIONS;
11331         break;
11332 
11333       case '?':
11334         pr_ctrls_add_response(ctrl,
11335           "tls sesscache: unsupported parameter: '%s'", reqargv[1]);
11336         return -1;
11337     }
11338   }
11339 
11340   res = tls_sess_cache_status(ctrl, flags);
11341   if (res < 0) {
11342     pr_ctrls_add_response(ctrl,
11343       "tls sesscache: error obtaining session cache status: %s",
11344       strerror(errno));
11345 
11346   } else {
11347     res = 0;
11348   }
11349 
11350   return res;
11351 }
11352 
11353 static int tls_handle_sesscache_remove(pr_ctrls_t *ctrl, int reqargc,
11354     char **reqargv) {
11355   int res;
11356 
11357   res = tls_sess_cache_remove();
11358   if (res < 0) {
11359     pr_ctrls_add_response(ctrl,
11360       "tls sesscache: error removing session cache: %s", strerror(errno));
11361 
11362   } else {
11363     pr_ctrls_add_response(ctrl, "tls sesscache: removed '%s' session cache",
11364       tls_sess_cache->cache_name);
11365     res = 0;
11366   }
11367 
11368   return res;
11369 }
11370 
11371 static int tls_handle_sesscache(pr_ctrls_t *ctrl, int reqargc, char **reqargv) {
11372 
11373   /* Sanity check */
11374   if (reqargc == 0 ||
11375       reqargv == NULL) {
11376     pr_ctrls_add_response(ctrl, "tls sesscache: missing required parameters");
11377     return -1;
11378   }
11379 
11380   if (strncmp(reqargv[0], "info", 5) == 0) {
11381     /* Check the ACLs. */
11382     if (!pr_ctrls_check_acl(ctrl, tls_acttab, "info")) {
11383       pr_ctrls_add_response(ctrl, "access denied");
11384       return -1;
11385     }
11386 
11387     return tls_handle_sesscache_info(ctrl, reqargc, reqargv);
11388 
11389   } else if (strncmp(reqargv[0], "clear", 6) == 0) {
11390     /* Check the ACLs. */
11391     if (!pr_ctrls_check_acl(ctrl, tls_acttab, "clear")) {
11392       pr_ctrls_add_response(ctrl, "access denied");
11393       return -1;
11394     }
11395 
11396     return tls_handle_sesscache_clear(ctrl, reqargc, reqargv);
11397 
11398   } else if (strncmp(reqargv[0], "remove", 7) == 0) {
11399     /* Check the ACLs. */
11400     if (!pr_ctrls_check_acl(ctrl, tls_acttab, "remove")) {
11401       pr_ctrls_add_response(ctrl, "access denied");
11402       return -1;
11403     }
11404 
11405     return tls_handle_sesscache_remove(ctrl, reqargc, reqargv);
11406   }
11407 
11408   pr_ctrls_add_response(ctrl, "tls sesscache: unknown sesscache action: '%s'",
11409     reqargv[0]);
11410   return -1;
11411 }
11412 
11413 static int tls_handle_ocspcache_info(pr_ctrls_t *ctrl, int reqargc,
11414     char **reqargv) {
11415   int flags = 0, optc, res;
11416   const char *opts = "v";
11417 
11418   pr_getopt_reset();
11419 
11420   while ((optc = getopt(reqargc, reqargv, opts)) != -1) {
11421     switch (optc) {
11422       case '?':
11423         pr_ctrls_add_response(ctrl,
11424           "tls ocspcache: unsupported parameter: '%s'", reqargv[1]);
11425         return -1;
11426     }
11427   }
11428 
11429   res = tls_ocsp_cache_status(ctrl, flags);
11430   if (res < 0) {
11431     pr_ctrls_add_response(ctrl,
11432       "tls ocspcache: error obtaining OCSP cache status: %s",
11433       strerror(errno));
11434 
11435   } else {
11436     res = 0;
11437   }
11438 
11439   return res;
11440 }
11441 
11442 static int tls_handle_ocspcache_clear(pr_ctrls_t *ctrl, int reqargc,
11443     char **reqargv) {
11444   int res;
11445 
11446   res = tls_ocsp_cache_clear();
11447   if (res < 0) {
11448     pr_ctrls_add_response(ctrl,
11449       "tls ocspcache: error clearing OCSP cache: %s", strerror(errno));
11450 
11451   } else {
11452     pr_ctrls_add_response(ctrl, "tls ocspcache: cleared %d %s from '%s' "
11453       "OCSP cache", res, res != 1 ? "responses" : "response",
11454       tls_ocsp_cache->cache_name);
11455     res = 0;
11456   }
11457 
11458   return res;
11459 }
11460 
11461 static int tls_handle_ocspcache_remove(pr_ctrls_t *ctrl, int reqargc,
11462     char **reqargv) {
11463   int res;
11464 
11465   res = tls_ocsp_cache_remove();
11466   if (res < 0) {
11467     pr_ctrls_add_response(ctrl,
11468       "tls ocspcache: error removing OCSP cache: %s", strerror(errno));
11469 
11470   } else {
11471     pr_ctrls_add_response(ctrl, "tls sesscache: removed '%s' OCSP cache",
11472       tls_ocsp_cache->cache_name);
11473     res = 0;
11474   }
11475 
11476   return res;
11477 }
11478 
11479 static int tls_handle_ocspcache(pr_ctrls_t *ctrl, int reqargc, char **reqargv) {
11480   /* Sanity check */
11481   if (reqargc == 0 ||
11482       reqargv == NULL) {
11483     pr_ctrls_add_response(ctrl, "tls ocspcache: missing required parameters");
11484     return -1;
11485   }
11486 
11487   if (strncmp(reqargv[0], "info", 5) == 0) {
11488     /* Check the ACLs. */
11489     if (!pr_ctrls_check_acl(ctrl, tls_acttab, "info")) {
11490       pr_ctrls_add_response(ctrl, "access denied");
11491       return -1;
11492     }
11493 
11494     return tls_handle_ocspcache_info(ctrl, reqargc, reqargv);
11495 
11496   } else if (strncmp(reqargv[0], "clear", 6) == 0) {
11497     /* Check the ACLs. */
11498     if (!pr_ctrls_check_acl(ctrl, tls_acttab, "clear")) {
11499       pr_ctrls_add_response(ctrl, "access denied");
11500       return -1;
11501     }
11502 
11503     return tls_handle_ocspcache_clear(ctrl, reqargc, reqargv);
11504 
11505   } else if (strncmp(reqargv[0], "remove", 7) == 0) {
11506     /* Check the ACLs. */
11507     if (!pr_ctrls_check_acl(ctrl, tls_acttab, "remove")) {
11508       pr_ctrls_add_response(ctrl, "access denied");
11509       return -1;
11510     }
11511 
11512     return tls_handle_ocspcache_remove(ctrl, reqargc, reqargv);
11513   }
11514 
11515   pr_ctrls_add_response(ctrl, "tls ocspcache: unknown ocspcache action: '%s'",
11516     reqargv[0]);
11517   return -1;
11518 }
11519 
11520 /* Our main ftpdctl action handler */
11521 static int tls_handle_tls(pr_ctrls_t *ctrl, int reqargc, char **reqargv) {
11522 
11523   /* Sanity check */
11524   if (reqargc == 0 ||
11525       reqargv == NULL) {
11526     pr_ctrls_add_response(ctrl, "tls: missing required parameters");
11527     return -1;
11528   }
11529 
11530   if (strncmp(reqargv[0], "sesscache", 10) == 0) {
11531     /* Check the ACLs. */
11532     if (!pr_ctrls_check_acl(ctrl, tls_acttab, "sesscache")) {
11533       pr_ctrls_add_response(ctrl, "access denied");
11534       return -1;
11535     }
11536 
11537     return tls_handle_sesscache(ctrl, --reqargc, ++reqargv);
11538   }
11539 
11540   if (strncmp(reqargv[0], "ocspcache", 10) == 0) {
11541     /* Check the ACLs. */
11542     if (!pr_ctrls_check_acl(ctrl, tls_acttab, "ocspcache")) {
11543       pr_ctrls_add_response(ctrl, "access denied");
11544       return -1;
11545     }
11546 
11547     return tls_handle_ocspcache(ctrl, --reqargc, ++reqargv);
11548   }
11549 
11550   pr_ctrls_add_response(ctrl, "tls: unknown tls action: '%s'", reqargv[0]);
11551   return -1;
11552 }
11553 #endif
11554 
11555 /* TLSSessionCache callbacks
11556  */
11557 
11558 static int tls_sess_cache_add_sess_cb(SSL *ssl, SSL_SESSION *sess) {
11559   unsigned char *sess_id;
11560   unsigned int sess_id_len;
11561   int res;
11562   long expires;
11563 
11564   if (tls_sess_cache == NULL) {
11565     tls_log("unable to add session to session cache: %s", strerror(ENOSYS));
11566 
11567     SSL_SESSION_free(sess);
11568     return 1;
11569   }
11570 
11571   pr_trace_msg(trace_channel, 9, "adding new SSL session to '%s' cache",
11572     tls_sess_cache->cache_name);
11573 
11574   SSL_set_timeout(sess, tls_sess_cache->cache_timeout);
11575 
11576 #if OPENSSL_VERSION_NUMBER > 0x000908000L
11577   sess_id = (unsigned char *) SSL_SESSION_get_id(sess, &sess_id_len);
11578 #else
11579   /* XXX Directly accessing these fields cannot be a Good Thing. */
11580   sess_id = sess->session_id;
11581   sess_id_len = sess->session_id_length;
11582 #endif
11583 
11584   /* The expiration timestamp stored in the session cache is the
11585    * Unix epoch time, not an interval.
11586    */
11587   expires = SSL_SESSION_get_time(sess) + tls_sess_cache->cache_timeout;
11588 
11589   res = (tls_sess_cache->add)(tls_sess_cache, sess_id, sess_id_len, expires,
11590     sess);
11591   if (res < 0) {
11592     long cache_mode;
11593 
11594     tls_log("error adding session to '%s' cache: %s",
11595       tls_sess_cache->cache_name, strerror(errno));
11596 
11597     cache_mode = tls_sess_cache_get_cache_mode();
11598 #ifdef SSL_SESS_CACHE_NO_INTERNAL
11599     if (cache_mode & SSL_SESS_CACHE_NO_INTERNAL) {
11600       /* Call SSL_SESSION_free() here, and return 1.  We told OpenSSL that we
11601        * are the only cache, so failing to call SSL_SESSION_free() could
11602        * result in a memory leak.
11603        */
11604       SSL_SESSION_free(sess);
11605       return 1;
11606     }
11607 #endif /* !SSL_SESS_CACHE_NO_INTERNAL */
11608   }
11609 
11610   /* Return zero to indicate to OpenSSL that we have not called
11611    * SSL_SESSION_free().
11612    */
11613   return 0;
11614 }
11615 
11616 static SSL_SESSION *tls_sess_cache_get_sess_cb(SSL *ssl, unsigned char *id,
11617     int sess_id_len, int *do_copy) {
11618   SSL_SESSION *sess;
11619   const unsigned char *sess_id;
11620 
11621   pr_trace_msg(trace_channel, 9, "getting SSL session from '%s' cache",
11622     tls_sess_cache->cache_name);
11623 
11624   sess_id = id;
11625 
11626   /* Indicate to OpenSSL that the ref count should not be incremented
11627    * by setting the do_copy pointer to zero.
11628    */
11629   *do_copy = 0;
11630 
11631   /* The actual session_id_length field in the OpenSSL SSL_SESSION struct
11632    * is unsigned, not signed.  But for some reason, the expected callback
11633    * signature uses 'int', not 'unsigned int'.  Hopefully the implicit
11634    * cast below (our callback uses 'unsigned int') won't cause problems.
11635    * Just to be sure, check if OpenSSL is giving us a negative ID length.
11636    */
11637   if (sess_id_len <= 0) {
11638     tls_log("OpenSSL invoked TLS session cache 'get' callback with session "
11639       "ID length %d, returning null", sess_id_len);
11640     return NULL;
11641   }
11642 
11643   if (tls_sess_cache == NULL) {
11644     tls_log("unable to get session from session cache: %s", strerror(ENOSYS));
11645     return NULL;
11646   }
11647 
11648   sess = (tls_sess_cache->get)(tls_sess_cache, sess_id, sess_id_len);
11649   if (sess == NULL) {
11650     int xerrno = errno;
11651 
11652     pr_trace_msg(trace_channel, 5,
11653       "error retrieving session from '%s' cache: %s",
11654       tls_sess_cache->cache_name, strerror(xerrno));
11655     if (xerrno != ENOENT) {
11656       tls_log("error retrieving session from '%s' cache: %s",
11657         tls_sess_cache->cache_name, strerror(xerrno));
11658     }
11659   }
11660 
11661   return sess;
11662 }
11663 
11664 static void tls_sess_cache_delete_sess_cb(SSL_CTX *ctx, SSL_SESSION *sess) {
11665   unsigned char *sess_id;
11666   unsigned int sess_id_len;
11667   int res;
11668 
11669   if (tls_sess_cache == NULL) {
11670     tls_log("unable to remove session from session cache: %s",
11671       strerror(ENOSYS));
11672     return;
11673   }
11674 
11675   pr_trace_msg(trace_channel, 9, "removing SSL session from '%s' cache",
11676     tls_sess_cache->cache_name);
11677 
11678 #if OPENSSL_VERSION_NUMBER > 0x000908000L
11679   sess_id = (unsigned char *) SSL_SESSION_get_id(sess, &sess_id_len);
11680 #else
11681   /* XXX Directly accessing these fields cannot be a Good Thing. */
11682   sess_id = sess->session_id;
11683   sess_id_len = sess->session_id_length;
11684 #endif
11685 
11686   res = (tls_sess_cache->delete)(tls_sess_cache, sess_id, sess_id_len);
11687   if (res < 0) {
11688     tls_log("error removing session from '%s' cache: %s",
11689       tls_sess_cache->cache_name, strerror(errno));
11690   }
11691 
11692   return;
11693 }
11694 
11695 /* Ideally we would use the OPENSSL_NO_PSK macro.  However, to use this, we
11696  * would need to say "if !defined(OPENSSL_NO_PSK)".  And that does not work
11697  * as well for older OpenSSL installations, where that macro would not be
11698  * defined anyway.  So instead, we use the presence of another PSK-related
11699  * macro as a more reliable sentinel.
11700  */
11701 
11702 #if defined(PSK_MAX_PSK_LEN)
11703 /* PSK callbacks */
11704 
11705 static int set_random_bn(unsigned char *psk, unsigned int max_psklen) {
11706   BIGNUM *bn = NULL;
11707   int res = 0;
11708 
11709   bn = BN_new();
11710   if (BN_pseudo_rand(bn, max_psklen, 0, 0) != 1) {
11711     tls_log("error generating pseudo-random number: %s",
11712       ERR_error_string(ERR_get_error(), NULL));
11713   }
11714 
11715   res = BN_bn2bin(bn, psk);
11716   BN_free(bn);
11717 
11718   return res;
11719 }
11720 
11721 static unsigned int tls_lookup_psk(SSL *ssl, const char *identity,
11722     unsigned char *psk, unsigned int max_psklen) {
11723   const void *v = NULL;
11724   BIGNUM *bn = NULL;
11725   int bn_len = -1, res;
11726 
11727   if (identity == NULL) {
11728     tls_log("%s", "error: client did not provide PSK identity name, providing "
11729       "random fake PSK");
11730 
11731     res = set_random_bn(psk, max_psklen);
11732     return res;
11733   }
11734 
11735   pr_trace_msg(trace_channel, 5,
11736     "PSK lookup: identity '%s' requested", identity);
11737 
11738   if (tls_psks == NULL) {
11739     tls_log("warning: no pre-shared keys configured, providing random fake "
11740       "PSK for identity '%s'", identity);
11741 
11742     res = set_random_bn(psk, max_psklen);
11743     return res;
11744   }
11745 
11746   v = pr_table_get(tls_psks, identity, NULL);
11747   if (v == NULL) {
11748     tls_log("warning: requested PSK identity '%s' not configured, providing "
11749       "random fake PSK", identity);
11750 
11751     res = set_random_bn(psk, max_psklen);
11752     return res;
11753   }
11754 
11755   bn = (BIGNUM *) v;
11756   bn_len = BN_num_bytes(bn);
11757 
11758   if (bn_len > (int) max_psklen) {
11759     tls_log("warning: unable to use '%s' PSK: max buffer size (%u bytes) "
11760       "too small for key (%d bytes), providing random fake PSK", identity,
11761       max_psklen, bn_len);
11762 
11763     res = set_random_bn(psk, max_psklen);
11764     return res;
11765   }
11766 
11767   res = BN_bn2bin(bn, psk);
11768   if (res == 0) {
11769     tls_log("error converting PSK for identity '%s' to binary: %s",
11770       identity, tls_get_errors());
11771     return 0;
11772   }
11773 
11774   pr_trace_msg(trace_channel, 5,
11775     "found PSK (%d bytes) for identity '%s'", res, identity);
11776   return res;
11777 }
11778 
11779 #endif /* PSK_MAX_PSK_LEN */
11780 
11781 /* NetIO callbacks
11782  */
11783 
11784 static void tls_netio_abort_cb(pr_netio_stream_t *nstrm) {
11785   nstrm->strm_flags |= PR_NETIO_SESS_ABORT;
11786 }
11787 
11788 static int tls_netio_close_cb(pr_netio_stream_t *nstrm) {
11789   int res = 0;
11790   SSL *ssl = NULL;
11791 
11792   ssl = (SSL *) pr_table_get(nstrm->notes, TLS_NETIO_NOTE, NULL);
11793   if (ssl != NULL) {
11794     if (nstrm->strm_type == PR_NETIO_STRM_CTRL) {
11795       if (nstrm->strm_mode == PR_NETIO_IO_RD) {
11796         tls_ctrl_rd_nstrm = NULL;
11797 
11798       } else if (nstrm->strm_mode == PR_NETIO_IO_WR) {
11799         tls_ctrl_wr_nstrm = NULL;
11800 
11801         tls_end_sess(ssl, session.c, 0);
11802         tls_ctrl_netio = NULL;
11803         tls_flags &= ~TLS_SESS_ON_CTRL;
11804       }
11805     }
11806 
11807     if (nstrm->strm_type == PR_NETIO_STRM_DATA) {
11808       if (nstrm->strm_mode == PR_NETIO_IO_RD) {
11809         tls_data_rd_nstrm = NULL;
11810 
11811       } else if (nstrm->strm_mode == PR_NETIO_IO_WR) {
11812         tls_data_wr_nstrm = NULL;
11813 
11814         tls_end_sess(ssl, session.d, 0);
11815         tls_data_netio = NULL;
11816         tls_flags &= ~TLS_SESS_ON_DATA;
11817       }
11818     }
11819   }
11820 
11821   res = close(nstrm->strm_fd);
11822   nstrm->strm_fd = -1;
11823 
11824   return res;
11825 }
11826 
11827 static pr_netio_stream_t *tls_netio_open_cb(pr_netio_stream_t *nstrm, int fd,
11828     int mode) {
11829   nstrm->strm_fd = fd;
11830   nstrm->strm_mode = mode;
11831 
11832   /* Cache a pointer to this stream. */
11833   if (nstrm->strm_type == PR_NETIO_STRM_CTRL) {
11834     /* Note: We need to make this more generalized, so that mod_tls can be
11835      * used to open multiple different read/write control streams.  To do
11836      * so, we need a small (e.g. 4) array of pr_netio_stream_t pointers
11837      * for both read and write streams, and to iterate through them.  Need
11838      * iterate through and set strm_data appropriately in tls_accept(), too.
11839      *
11840      * This will needed to support FTPS connections to backend servers from
11841      * mod_proxy, for example.
11842      */
11843     if (nstrm->strm_mode == PR_NETIO_IO_RD) {
11844       if (tls_ctrl_rd_nstrm == NULL) {
11845         tls_ctrl_rd_nstrm = nstrm;
11846       }
11847     }
11848 
11849     if (nstrm->strm_mode == PR_NETIO_IO_WR) {
11850       if (tls_ctrl_wr_nstrm == NULL) {
11851         tls_ctrl_wr_nstrm = nstrm;
11852       }
11853     }
11854 
11855   } else if (nstrm->strm_type == PR_NETIO_STRM_DATA) {
11856     if (nstrm->strm_mode == PR_NETIO_IO_RD) {
11857       tls_data_rd_nstrm = nstrm;
11858     }
11859 
11860     if (nstrm->strm_mode == PR_NETIO_IO_WR) {
11861       tls_data_wr_nstrm = nstrm;
11862     }
11863 
11864     /* Note: from the FTP-TLS Draft 9.2:
11865      *
11866      *  It is quite reasonable for the server to insist that the data
11867      *  connection uses a TLS cached session.  This might be a cache of a
11868      *  previous data connection or of the control connection.  If this is
11869      *  the reason for the refusal to allow the data transfer then the
11870      *  '522' reply should indicate this.
11871      *
11872      * and, from 10.4:
11873      *
11874      *   If a server needs to have the connection protected then it will
11875      *   reply to the STOR/RETR/NLST/... command with a '522' indicating
11876      *   that the current state of the data connection protection level is
11877      *   not sufficient for that data transfer at that time.
11878      *
11879      * This points out the need for a module to be able to influence
11880      * command response codes in a more flexible manner...
11881      */
11882   }
11883 
11884   return nstrm;
11885 }
11886 
11887 static int tls_netio_poll_cb(pr_netio_stream_t *nstrm) {
11888   fd_set rfds, wfds;
11889   struct timeval tval;
11890 
11891   FD_ZERO(&rfds);
11892   FD_ZERO(&wfds);
11893 
11894   if (nstrm->strm_mode == PR_NETIO_IO_RD) {
11895     FD_SET(nstrm->strm_fd, &rfds);
11896 
11897   } else {
11898     FD_SET(nstrm->strm_fd, &wfds);
11899   }
11900 
11901   tval.tv_sec = (nstrm->strm_flags & PR_NETIO_SESS_INTR) ?
11902     nstrm->strm_interval : 10;
11903   tval.tv_usec = 0;
11904 
11905   return select(nstrm->strm_fd + 1, &rfds, &wfds, NULL, &tval);
11906 }
11907 
11908 static int tls_netio_postopen_cb(pr_netio_stream_t *nstrm) {
11909 
11910   /* If this is a data stream, and it's for writing, and TLS is required,
11911    * then do a TLS handshake.
11912    */
11913 
11914   if (nstrm->strm_type == PR_NETIO_STRM_DATA &&
11915       nstrm->strm_mode == PR_NETIO_IO_WR) {
11916 
11917     /* Enforce the "data" part of TLSRequired, if configured. */
11918     if (tls_required_on_data == 1 ||
11919         (tls_flags & TLS_SESS_NEED_DATA_PROT)) {
11920       SSL *ssl = NULL;
11921 
11922       /* XXX How to force 421 response code for failed secure FXP/SSCN? */
11923 
11924       /* Directory listings (LIST, MLSD, NLST) are ALWAYS handled in server
11925        * mode, regardless of SSCN mode.
11926        */
11927       if (session.curr_cmd_id == PR_CMD_LIST_ID ||
11928           session.curr_cmd_id == PR_CMD_MLSD_ID ||
11929           session.curr_cmd_id == PR_CMD_NLST_ID ||
11930           tls_sscn_mode == TLS_SSCN_MODE_SERVER) {
11931         X509 *ctrl_cert = NULL, *data_cert = NULL;
11932         uint64_t start_ms;
11933 
11934         pr_gettimeofday_millis(&start_ms);
11935 
11936         tls_data_need_init_handshake = TRUE;
11937         if (tls_accept(session.d, TRUE) < 0) {
11938           tls_log("%s",
11939             "unable to open data connection: TLS negotiation failed");
11940           session.d->xerrno = errno = EPERM;
11941           return -1;
11942         }
11943 
11944         if (pr_trace_get_level(timing_channel) >= 4) {
11945           unsigned long elapsed_ms;
11946           uint64_t finish_ms;
11947 
11948           pr_gettimeofday_millis(&finish_ms);
11949           elapsed_ms = (unsigned long) (finish_ms - start_ms);
11950 
11951           pr_trace_msg(timing_channel, 4,
11952             "TLS data handshake duration: %lu ms", elapsed_ms);
11953         }
11954 
11955         ssl = (SSL *) pr_table_get(nstrm->notes, TLS_NETIO_NOTE, NULL);
11956 
11957         /* Make sure that the certificate used, if any, for this data channel
11958          * handshake is the same as that used for the control channel handshake.
11959          * This may be too strict of a requirement, though.
11960          */
11961         ctrl_cert = SSL_get_peer_certificate(ctrl_ssl);
11962         data_cert = SSL_get_peer_certificate(ssl);
11963 
11964         if (ctrl_cert != NULL &&
11965             data_cert != NULL) {
11966           if (X509_cmp(ctrl_cert, data_cert)) {
11967             X509_free(ctrl_cert);
11968             X509_free(data_cert);
11969 
11970             /* Properly shutdown the TLS session. */
11971             tls_end_sess(ssl, session.d, 0);
11972             pr_table_remove(tls_data_rd_nstrm->notes, TLS_NETIO_NOTE, NULL);
11973             pr_table_remove(tls_data_wr_nstrm->notes, TLS_NETIO_NOTE, NULL);
11974 
11975             tls_log("%s", "unable to open data connection: control/data "
11976               "certificate mismatch");
11977 
11978             session.d->xerrno = errno = EPERM;
11979             return -1;
11980           }
11981 
11982           if (ctrl_cert) {
11983             X509_free(ctrl_cert);
11984           }
11985 
11986           if (data_cert) {
11987             X509_free(data_cert);
11988           }
11989         }
11990 
11991       } else if (tls_sscn_mode == TLS_SSCN_MODE_CLIENT) {
11992         tls_log("%s", "making TLS connection for data connection");
11993         if (tls_connect(session.d) < 0) {
11994           tls_log("%s",
11995             "unable to open data connection: TLS connection failed");
11996           session.d->xerrno = errno = EPERM;
11997           return -1;
11998         }
11999      }
12000 
12001 #if OPENSSL_VERSION_NUMBER < 0x0090702fL
12002       /* Make sure blinding is turned on. (For some reason, this only seems
12003        * to be allowed on SSL objects, not on SSL_CTX objects.  Bummer).
12004        */
12005       tls_blinding_on(ssl);
12006 #endif
12007 
12008       tls_flags |= TLS_SESS_ON_DATA;
12009     }
12010   }
12011 
12012   return 0;
12013 }
12014 
12015 static int tls_netio_read_cb(pr_netio_stream_t *nstrm, char *buf,
12016     size_t buflen) {
12017   SSL *ssl;
12018 
12019   ssl = (SSL *) pr_table_get(nstrm->notes, TLS_NETIO_NOTE, NULL);
12020   if (ssl != NULL) {
12021     BIO *rbio, *wbio;
12022     int bread = 0, bwritten = 0, xerrno = 0;
12023     ssize_t res = 0;
12024     unsigned long rbio_rbytes, rbio_wbytes, wbio_rbytes, wbio_wbytes;
12025 
12026     rbio = SSL_get_rbio(ssl);
12027     rbio_rbytes = BIO_number_read(rbio);
12028     rbio_wbytes = BIO_number_written(rbio);
12029 
12030     wbio = SSL_get_wbio(ssl);
12031     wbio_rbytes = BIO_number_read(wbio);
12032     wbio_wbytes = BIO_number_written(wbio);
12033 
12034     res = tls_read(ssl, buf, buflen);
12035     xerrno = errno;
12036 
12037     bread = (BIO_number_read(rbio) - rbio_rbytes) +
12038       (BIO_number_read(wbio) - wbio_rbytes);
12039     bwritten = (BIO_number_written(rbio) - rbio_wbytes) +
12040       (BIO_number_written(wbio) - wbio_wbytes);
12041 
12042     /* Manually update session.total_raw_in with the difference between
12043      * the raw bytes read in versus the non-SSL bytes read in, in order to
12044      * have %I be accurately represented for the raw traffic.
12045      */
12046     if (res > 0) {
12047       session.total_raw_in += (bread - res);
12048     }
12049 
12050     /* Manually update session.total_raw_out, in order to have %O be
12051      * accurately represented for the raw traffic.
12052      */
12053     if (bwritten > 0) {
12054       session.total_raw_out += bwritten;
12055     }
12056 
12057     errno = xerrno;
12058     return res;
12059   }
12060 
12061   return read(nstrm->strm_fd, buf, buflen);
12062 }
12063 
12064 static pr_netio_stream_t *tls_netio_reopen_cb(pr_netio_stream_t *nstrm, int fd,
12065     int mode) {
12066 
12067   if (nstrm->strm_fd != -1) {
12068     close(nstrm->strm_fd);
12069   }
12070 
12071   nstrm->strm_fd = fd;
12072   nstrm->strm_mode = mode;
12073 
12074   /* NOTE: a no-op? */
12075   return nstrm;
12076 }
12077 
12078 static int tls_netio_shutdown_cb(pr_netio_stream_t *nstrm, int how) {
12079 
12080   if (how == 1 ||
12081       how == 2) {
12082     /* Closing this stream for writing; we need to send the 'close_notify'
12083      * alert first, so that the client knows, at the application layer,
12084      * that the SSL/TLS session is shutting down.
12085      */
12086 
12087     if (nstrm->strm_mode == PR_NETIO_IO_WR &&
12088         (nstrm->strm_type == PR_NETIO_STRM_CTRL ||
12089          nstrm->strm_type == PR_NETIO_STRM_DATA)) {
12090       SSL *ssl;
12091 
12092       ssl = (SSL *) pr_table_get(nstrm->notes, TLS_NETIO_NOTE, NULL);
12093       if (ssl != NULL) {
12094         BIO *rbio, *wbio;
12095         int bread = 0, bwritten = 0;
12096         unsigned long rbio_rbytes, rbio_wbytes, wbio_rbytes, wbio_wbytes;
12097         conn_t *conn;
12098 
12099         rbio = SSL_get_rbio(ssl);
12100         rbio_rbytes = BIO_number_read(rbio);
12101         rbio_wbytes = BIO_number_written(rbio);
12102 
12103         wbio = SSL_get_wbio(ssl);
12104         wbio_rbytes = BIO_number_read(wbio);
12105         wbio_wbytes = BIO_number_written(wbio);
12106 
12107         if (!(SSL_get_shutdown(ssl) & SSL_SENT_SHUTDOWN)) {
12108 
12109           /* Disable any socket buffering (Nagle, TCP_CORK), so that the alert
12110            * is sent in a timely manner (avoiding TLS shutdown latency).
12111            */
12112           conn = (nstrm->strm_type == PR_NETIO_STRM_DATA) ? session.d :
12113             session.c;
12114           if (conn != NULL) {
12115             if (pr_inet_set_proto_nodelay(conn->pool, conn, 1) < 0) {
12116               pr_trace_msg(trace_channel, 9,
12117                 "error enabling TCP_NODELAY on conn: %s", strerror(errno));
12118             }
12119 
12120             if (pr_inet_set_proto_cork(conn->wfd, 0) < 0) {
12121               pr_trace_msg(trace_channel, 9,
12122                 "error disabling TCP_CORK on fd %d: %s", conn->wfd,
12123                 strerror(errno));
12124             }
12125           }
12126 
12127           /* We haven't sent a 'close_notify' alert yet; do so now. */
12128           SSL_shutdown(ssl);
12129         }
12130 
12131         bread = (BIO_number_read(rbio) - rbio_rbytes) +
12132           (BIO_number_read(wbio) - wbio_rbytes);
12133         bwritten = (BIO_number_written(rbio) - rbio_wbytes) +
12134           (BIO_number_written(wbio) - wbio_wbytes);
12135 
12136         /* Manually update session.total_raw_in/out, in order to have %I/%O be
12137          * accurately represented for the raw traffic.
12138          */
12139         if (bread > 0) {
12140           session.total_raw_in += bread;
12141         }
12142 
12143         if (bwritten > 0) {
12144           session.total_raw_out += bwritten;
12145         }
12146 
12147       } else {
12148         pr_trace_msg(trace_channel, 3,
12149           "no TLS found in stream notes for '%s'", TLS_NETIO_NOTE);
12150       }
12151     }
12152   }
12153 
12154   return shutdown(nstrm->strm_fd, how);
12155 }
12156 
12157 static int tls_netio_write_cb(pr_netio_stream_t *nstrm, char *buf,
12158     size_t buflen) {
12159   SSL *ssl;
12160 
12161   ssl = (SSL *) pr_table_get(nstrm->notes, TLS_NETIO_NOTE, NULL);
12162   if (ssl != NULL) {
12163     BIO *rbio, *wbio;
12164     int bread = 0, bwritten = 0, xerrno = 0;
12165     ssize_t res = 0;
12166     unsigned long rbio_rbytes, rbio_wbytes, wbio_rbytes, wbio_wbytes;
12167 
12168     rbio = SSL_get_rbio(ssl);
12169     rbio_rbytes = BIO_number_read(rbio);
12170     rbio_wbytes = BIO_number_written(rbio);
12171 
12172     wbio = SSL_get_wbio(ssl);
12173     wbio_rbytes = BIO_number_read(wbio);
12174     wbio_wbytes = BIO_number_written(wbio);
12175 
12176 #if OPENSSL_VERSION_NUMBER > 0x000907000L
12177     if (tls_data_renegotiate_limit &&
12178         session.xfer.total_bytes >= tls_data_renegotiate_limit
12179 
12180 #if OPENSSL_VERSION_NUMBER >= 0x009080cfL
12181         /* In OpenSSL-0.9.8l and later, SSL session renegotiations
12182          * (both client- and server-initiated) are automatically disabled.
12183          * Unless the admin explicitly configured support for
12184          * client-initiated renegotiations via the AllowClientRenegotiations
12185          * TLSOption, we can't request renegotiations ourselves.
12186          */
12187         && (tls_opts & TLS_OPT_ALLOW_CLIENT_RENEGOTIATIONS)
12188 #endif
12189       ) {
12190 
12191       tls_flags |= TLS_SESS_DATA_RENEGOTIATING;
12192 
12193       tls_log("requesting TLS renegotiation on data channel "
12194         "(%" PR_LU " KB data limit)",
12195         (pr_off_t) (tls_data_renegotiate_limit / 1024));
12196       SSL_renegotiate(ssl);
12197       /* SSL_do_handshake(ssl); */
12198 
12199       pr_timer_add(tls_renegotiate_timeout, -1, &tls_module,
12200         tls_renegotiate_timeout_cb, "SSL/TLS renegotiation");
12201     }
12202 #endif
12203 
12204     res = tls_write(ssl, buf, buflen);
12205     xerrno = errno;
12206 
12207     bread = (BIO_number_read(rbio) - rbio_rbytes) +
12208       (BIO_number_read(wbio) - wbio_rbytes);
12209     bwritten = (BIO_number_written(rbio) - rbio_wbytes) +
12210       (BIO_number_written(wbio) - wbio_wbytes);
12211 
12212     /* Manually update session.total_raw_in, in order to have %I be
12213      * accurately represented for the raw traffic.
12214      */
12215     if (bread > 0) {
12216       session.total_raw_in += bread;
12217     }
12218 
12219     /* Manually update session.total_raw_out with the difference between
12220      * the raw bytes written out versus the non-SSL bytes written out,
12221      * in order to have %) be accurately represented for the raw traffic.
12222      */
12223     if (res > 0) {
12224       session.total_raw_out += (bwritten - res);
12225     }
12226 
12227     errno = xerrno;
12228     return res;
12229   }
12230 
12231   return write(nstrm->strm_fd, buf, buflen);
12232 }
12233 
12234 static void tls_netio_install_ctrl(void) {
12235   pr_netio_t *netio;
12236 
12237   if (tls_ctrl_netio) {
12238     /* If we already have our ctrl netio, then it's been registered, and
12239      * we don't need to do anything more.
12240      */
12241     return;
12242   }
12243 
12244   tls_ctrl_netio = netio = pr_alloc_netio2(permanent_pool, &tls_module, NULL);
12245 
12246   netio->abort = tls_netio_abort_cb;
12247   netio->close = tls_netio_close_cb;
12248   netio->open = tls_netio_open_cb;
12249   netio->poll = tls_netio_poll_cb;
12250   netio->postopen = tls_netio_postopen_cb;
12251   netio->read = tls_netio_read_cb;
12252   netio->reopen = tls_netio_reopen_cb;
12253   netio->shutdown = tls_netio_shutdown_cb;
12254   netio->write = tls_netio_write_cb;
12255 
12256   pr_unregister_netio(PR_NETIO_STRM_CTRL);
12257 
12258   if (pr_register_netio(netio, PR_NETIO_STRM_CTRL) < 0) {
12259     pr_log_pri(PR_LOG_NOTICE, MOD_TLS_VERSION ": error registering netio: %s",
12260       strerror(errno));
12261   }
12262 }
12263 
12264 static void tls_netio_install_data(void) {
12265   pr_netio_t *netio = tls_data_netio ? tls_data_netio :
12266     (tls_data_netio = pr_alloc_netio2(session.pool ? session.pool :
12267     permanent_pool, &tls_module, NULL));
12268 
12269   netio->abort = tls_netio_abort_cb;
12270   netio->close = tls_netio_close_cb;
12271   netio->open = tls_netio_open_cb;
12272   netio->poll = tls_netio_poll_cb;
12273   netio->postopen = tls_netio_postopen_cb;
12274   netio->read = tls_netio_read_cb;
12275   netio->reopen = tls_netio_reopen_cb;
12276   netio->shutdown = tls_netio_shutdown_cb;
12277   netio->write = tls_netio_write_cb;
12278 
12279   pr_unregister_netio(PR_NETIO_STRM_DATA);
12280 
12281   if (pr_register_netio(netio, PR_NETIO_STRM_DATA) < 0) {
12282     pr_log_pri(PR_LOG_NOTICE, MOD_TLS_VERSION ": error registering netio: %s",
12283       strerror(errno));
12284   }
12285 }
12286 
12287 /* Logging functions
12288  */
12289 
12290 static void tls_closelog(void) {
12291 
12292   /* Sanity check */
12293   if (tls_logfd != -1) {
12294     close(tls_logfd);
12295     tls_logfd = -1;
12296   }
12297 
12298   return;
12299 }
12300 
12301 int tls_log(const char *fmt, ...) {
12302   va_list msg;
12303   int res;
12304 
12305   /* Sanity check */
12306   if (tls_logfd < 0) {
12307     return 0;
12308   }
12309 
12310   va_start(msg, fmt);
12311   res = pr_log_vwritefile(tls_logfd, MOD_TLS_VERSION, fmt, msg);
12312   va_end(msg);
12313 
12314   return res;
12315 }
12316 
12317 static int tls_openlog(void) {
12318   int res = 0, xerrno;
12319   char *path;
12320 
12321   /* Sanity checks */
12322   path = get_param_ptr(main_server->conf, "TLSLog", FALSE);
12323   if (path == NULL ||
12324       strncasecmp(path, "none", 5) == 0) {
12325     return 0;
12326   }
12327 
12328   pr_signals_block();
12329   PRIVS_ROOT
12330   res = pr_log_openfile(path, &tls_logfd, PR_LOG_SYSTEM_MODE);
12331   xerrno = errno;
12332   PRIVS_RELINQUISH
12333   pr_signals_unblock();
12334 
12335   errno = xerrno;
12336   return res;
12337 }
12338 
12339 /* Authentication handlers
12340  */
12341 
12342 /* This function does the main authentication work, and is called in the
12343  * normal course of events:
12344  *
12345  *   cmd->argv[0]: user name
12346  *   cmd->argv[1]: cleartext password
12347  */
12348 MODRET tls_authenticate(cmd_rec *cmd) {
12349   if (!tls_engine) {
12350     return PR_DECLINED(cmd);
12351   }
12352 
12353   /* Possible authentication combinations:
12354    *
12355    *  TLS handshake + passwd (default)
12356    *  TLS handshake + .tlslogin (passwd ignored)
12357    */
12358 
12359   if (tls_flags & TLS_SESS_ON_CTRL) {
12360     config_rec *c;
12361 
12362     if (tls_opts & TLS_OPT_ALLOW_DOT_LOGIN) {
12363       if (tls_dotlogin_allow(cmd->argv[0])) {
12364         tls_log("TLS/X509 .tlslogin check successful for user '%s'",
12365           (char *) cmd->argv[0]);
12366         pr_log_auth(PR_LOG_NOTICE, "USER %s: TLS/X509 .tlslogin authentication "
12367           "successful", (char *) cmd->argv[0]);
12368         session.auth_mech = "mod_tls.c";
12369         return mod_create_data(cmd, (void *) PR_AUTH_RFC2228_OK);
12370 
12371       } else {
12372         tls_log("TLS/X509 .tlslogin check failed for user '%s'",
12373           (char *) cmd->argv[0]);
12374       }
12375     }
12376 
12377     c = find_config(main_server->conf, CONF_PARAM, "TLSUserName", FALSE);
12378     if (c != NULL) {
12379       if (tls_cert_to_user(cmd->argv[0], c->argv[0])) {
12380         tls_log("TLS/X509 TLSUserName '%s' check successful for user '%s'",
12381           (char *) c->argv[0], (char *) cmd->argv[0]);
12382         pr_log_auth(PR_LOG_NOTICE,
12383           "USER %s: TLS/X509 TLSUserName authentication successful",
12384           (char *) cmd->argv[0]);
12385         session.auth_mech = "mod_tls.c";
12386         return mod_create_data(cmd, (void *) PR_AUTH_RFC2228_OK);
12387 
12388       } else {
12389         tls_log("TLS/X509 TLSUserName '%s' check failed for user '%s'",
12390           (char *) c->argv[0], (char *) cmd->argv[0]);
12391       }
12392     }
12393   }
12394 
12395   return PR_DECLINED(cmd);
12396 }
12397 
12398 /* This function is called only when UserPassword is involved, used to
12399  * override the configured password for a user.
12400  *
12401  *  cmd->argv[0]: hashed password (from proftpd.conf)
12402  *  cmd->argv[1]: user name
12403  *  cmd->argv[2]: cleartext password
12404  */
12405 MODRET tls_auth_check(cmd_rec *cmd) {
12406   if (!tls_engine)
12407     return PR_DECLINED(cmd);
12408 
12409   /* Possible authentication combinations:
12410    *
12411    *  TLS handshake + passwd (default)
12412    *  TLS handshake + .tlslogin (passwd ignored)
12413    */
12414 
12415   if (tls_flags & TLS_SESS_ON_CTRL) {
12416     config_rec *c;
12417 
12418     if (tls_opts & TLS_OPT_ALLOW_DOT_LOGIN) {
12419       if (tls_dotlogin_allow(cmd->argv[1])) {
12420         tls_log("TLS/X509 .tlslogin check successful for user '%s'",
12421           (char *) cmd->argv[0]);
12422         pr_log_auth(PR_LOG_NOTICE, "USER %s: TLS/X509 .tlslogin authentication "
12423           "successful", (char *) cmd->argv[1]);
12424         session.auth_mech = "mod_tls.c";
12425         return mod_create_data(cmd, (void *) PR_AUTH_RFC2228_OK);
12426 
12427       } else {
12428         tls_log("TLS/X509 .tlslogin check failed for user '%s'",
12429           (char *) cmd->argv[1]);
12430       }
12431     }
12432 
12433     c = find_config(main_server->conf, CONF_PARAM, "TLSUserName", FALSE);
12434     if (c != NULL) {
12435       if (tls_cert_to_user(cmd->argv[0], c->argv[0])) {
12436         tls_log("TLS/X509 TLSUserName '%s' check successful for user '%s'",
12437           (char *) c->argv[0], (char *) cmd->argv[0]);
12438         pr_log_auth(PR_LOG_NOTICE,
12439           "USER %s: TLS/X509 TLSUserName authentication successful",
12440           (char *) cmd->argv[0]);
12441         session.auth_mech = "mod_tls.c";
12442         return mod_create_data(cmd, (void *) PR_AUTH_RFC2228_OK);
12443 
12444       } else {
12445         tls_log("TLS/X509 TLSUserName '%s' check failed for user '%s'",
12446           (char *) c->argv[0], (char *) cmd->argv[0]);
12447       }
12448     }
12449   }
12450 
12451   return PR_DECLINED(cmd);
12452 }
12453 
12454 /* Command handlers
12455  */
12456 
12457 MODRET tls_any(cmd_rec *cmd) {
12458   if (!tls_engine)
12459     return PR_DECLINED(cmd);
12460 
12461   /* Some commands need not be hindered. */
12462   if (pr_cmd_cmp(cmd, PR_CMD_SYST_ID) == 0 ||
12463       pr_cmd_cmp(cmd, PR_CMD_AUTH_ID) == 0 ||
12464       pr_cmd_cmp(cmd, PR_CMD_FEAT_ID) == 0 ||
12465       pr_cmd_cmp(cmd, PR_CMD_HOST_ID) == 0 ||
12466       pr_cmd_cmp(cmd, PR_CMD_CLNT_ID) == 0 ||
12467       pr_cmd_cmp(cmd, PR_CMD_QUIT_ID) == 0) {
12468     return PR_DECLINED(cmd);
12469   }
12470 
12471   if (tls_required_on_auth == 1 &&
12472       !(tls_flags & TLS_SESS_ON_CTRL)) {
12473 
12474     if (!(tls_opts & TLS_OPT_ALLOW_PER_USER)) {
12475       if (pr_cmd_cmp(cmd, PR_CMD_USER_ID) == 0 ||
12476           pr_cmd_cmp(cmd, PR_CMD_PASS_ID) == 0 ||
12477           pr_cmd_cmp(cmd, PR_CMD_ACCT_ID) == 0) {
12478         tls_log("SSL/TLS required but absent for authentication, "
12479           "denying %s command", (char *) cmd->argv[0]);
12480         pr_response_add_err(R_550,
12481           _("SSL/TLS required on the control channel"));
12482 
12483         pr_cmd_set_errno(cmd, EPERM);
12484         errno = EPERM;
12485         return PR_ERROR(cmd);
12486       }
12487     }
12488   }
12489 
12490   if (tls_required_on_ctrl == 1 &&
12491       !(tls_flags & TLS_SESS_ON_CTRL)) {
12492 
12493     if (!(tls_opts & TLS_OPT_ALLOW_PER_USER)) {
12494       tls_log("SSL/TLS required but absent on control channel, "
12495         "denying %s command", (char *) cmd->argv[0]);
12496       pr_response_add_err(R_550, _("SSL/TLS required on the control channel"));
12497 
12498       pr_cmd_set_errno(cmd, EPERM);
12499       errno = EPERM;
12500       return PR_ERROR(cmd);
12501 
12502     } else {
12503 
12504       if (tls_authenticated &&
12505           *tls_authenticated == TRUE) {
12506         tls_log("SSL/TLS required but absent on control channel, "
12507           "denying %s command", (char *) cmd->argv[0]);
12508         pr_response_add_err(R_550,
12509           _("SSL/TLS required on the control channel"));
12510 
12511         pr_cmd_set_errno(cmd, EPERM);
12512         errno = EPERM;
12513         return PR_ERROR(cmd);
12514       }
12515     }
12516   }
12517 
12518   /* TLSRequired checks */
12519 
12520   if (tls_required_on_data == 1) {
12521     /* TLSRequired encompasses all data transfers for this session, the
12522      * client did not specify an appropriate PROT, and the command is one
12523      * which will trigger a data transfer...
12524      */
12525 
12526     if (!(tls_flags & TLS_SESS_NEED_DATA_PROT)) {
12527       if (pr_cmd_cmp(cmd, PR_CMD_APPE_ID) == 0 ||
12528           pr_cmd_cmp(cmd, PR_CMD_LIST_ID) == 0 ||
12529           pr_cmd_cmp(cmd, PR_CMD_MLSD_ID) == 0 ||
12530           pr_cmd_cmp(cmd, PR_CMD_NLST_ID) == 0 ||
12531           pr_cmd_cmp(cmd, PR_CMD_RETR_ID) == 0 ||
12532           pr_cmd_cmp(cmd, PR_CMD_STOR_ID) == 0 ||
12533           pr_cmd_cmp(cmd, PR_CMD_STOU_ID) == 0) {
12534         tls_log("SSL/TLS required but absent on data channel, "
12535           "denying %s command", (char *) cmd->argv[0]);
12536         pr_response_add_err(R_522, _("SSL/TLS required on the data channel"));
12537 
12538         pr_cmd_set_errno(cmd, EPERM);
12539         errno = EPERM;
12540         return PR_ERROR(cmd);
12541       }
12542     }
12543 
12544   } else {
12545 
12546     /* TLSRequired is not in effect for all data transfers for this session.
12547      * If this command will trigger a data transfer, check the current
12548      * context to see if there's a directory-level TLSRequired for data
12549      * transfers.
12550      *
12551      * XXX ideally, rather than using the current directory location, we'd
12552      * do the lookup based on the target location.
12553      */
12554 
12555     if (pr_cmd_cmp(cmd, PR_CMD_APPE_ID) == 0 ||
12556         pr_cmd_cmp(cmd, PR_CMD_LIST_ID) == 0 ||
12557         pr_cmd_cmp(cmd, PR_CMD_MLSD_ID) == 0 ||
12558         pr_cmd_cmp(cmd, PR_CMD_NLST_ID) == 0 ||
12559         pr_cmd_cmp(cmd, PR_CMD_RETR_ID) == 0 ||
12560         pr_cmd_cmp(cmd, PR_CMD_STOR_ID) == 0 ||
12561         pr_cmd_cmp(cmd, PR_CMD_STOU_ID) == 0) {
12562       config_rec *c;
12563 
12564       c = find_config(CURRENT_CONF, CONF_PARAM, "TLSRequired", FALSE);
12565       if (c) {
12566         int tls_required;
12567 
12568         tls_required = *((int *) c->argv[1]);
12569 
12570         if (tls_required == TRUE &&
12571             !(tls_flags & TLS_SESS_NEED_DATA_PROT)) {
12572           tls_log("%s command denied by TLSRequired in directory '%s'",
12573             (char *) cmd->argv[0],
12574             session.dir_config ? session.dir_config->name :
12575               session.anon_config ? session.anon_config->name :
12576               main_server->ServerName);
12577           pr_response_add_err(R_522, _("SSL/TLS required on the data channel"));
12578 
12579           pr_cmd_set_errno(cmd, EPERM);
12580           errno = EPERM;
12581           return PR_ERROR(cmd);
12582         }
12583       }
12584     }
12585   }
12586 
12587   return PR_DECLINED(cmd);
12588 }
12589 
12590 MODRET tls_auth(cmd_rec *cmd) {
12591   register unsigned int i = 0;
12592   char *mode;
12593 
12594   if (!tls_engine) {
12595     return PR_DECLINED(cmd);
12596   }
12597 
12598   /* If we already have protection on the control channel (i.e. AUTH has
12599    * already been sent by the client and handled), then reject this second
12600    * AUTH.  Clients that want to renegotiate can either use SSL/TLS's
12601    * renegotiation facilities, or disconnect and start over.
12602    */
12603   if (tls_flags & TLS_SESS_ON_CTRL) {
12604     tls_log("Unwilling to accept AUTH after AUTH for this session");
12605     pr_response_add_err(R_503, _("Unwilling to accept second AUTH"));
12606 
12607     pr_cmd_set_errno(cmd, EPERM);
12608     errno = EPERM;
12609     return PR_ERROR(cmd);
12610   }
12611 
12612   if (cmd->argc < 2) {
12613     pr_response_add_err(R_504, _("AUTH requires at least one argument"));
12614 
12615     pr_cmd_set_errno(cmd, EINVAL);
12616     errno = EINVAL;
12617     return PR_ERROR(cmd);
12618   }
12619 
12620   if (tls_flags & TLS_SESS_HAVE_CCC) {
12621     tls_log("Unwilling to accept AUTH after CCC for this session");
12622     pr_response_add_err(R_534, _("Unwilling to accept security parameters"));
12623 
12624     pr_cmd_set_errno(cmd, EPERM);
12625     errno = EPERM;
12626     return PR_ERROR(cmd);
12627   }
12628 
12629   /* CAN we even handle an AUTH command?  If we do not have the necessary
12630    * certificates, then we should indicate that we cannot.
12631    */
12632   if (tls_rsa_cert_file == NULL &&
12633       tls_dsa_cert_file == NULL &&
12634       tls_ec_cert_file == NULL &&
12635       tls_pkcs12_file == NULL) {
12636     tls_log("Unable to accept AUTH %s due to lack of certificates", cmd->arg);
12637     pr_response_add_err(R_431, _("Necessary security resource unavailable"));
12638 
12639     pr_cmd_set_errno(cmd, EPERM);
12640     errno = EPERM;
12641     return PR_ERROR(cmd);
12642   }
12643 
12644   /* Convert the parameter to upper case */
12645   mode = cmd->argv[1];
12646   for (i = 0; i < strlen(mode); i++) {
12647     mode[i] = toupper(mode[i]);
12648   }
12649 
12650   if (strncmp(mode, "TLS", 4) == 0 ||
12651       strncmp(mode, "TLS-C", 6) == 0) {
12652     uint64_t start_ms;
12653 
12654     pr_response_send(R_234, _("AUTH %s successful"), (char *) cmd->argv[1]);
12655     tls_log("%s", "TLS/TLS-C requested, starting TLS handshake");
12656 
12657     if (pr_trace_get_level(timing_channel) > 0) {
12658       pr_gettimeofday_millis(&start_ms);
12659     }
12660 
12661     pr_event_generate("mod_tls.ctrl-handshake", session.c);
12662     if (tls_accept(session.c, FALSE) < 0) {
12663       tls_log("%s", "TLS/TLS-C negotiation failed on control channel");
12664 
12665       if (tls_required_on_ctrl == 1) {
12666         pr_response_send(R_550, _("TLS handshake failed"));
12667         pr_session_disconnect(&tls_module, PR_SESS_DISCONNECT_CONFIG_ACL,
12668           "TLSRequired");
12669       }
12670 
12671       /* If we reach this point, the debug logging may show gibberish
12672        * commands from the client.  In reality, this gibberish is probably
12673        * more encrypted data from the client.
12674        */
12675       pr_response_send(R_550, _("TLS handshake failed"));
12676       pr_session_disconnect(&tls_module, PR_SESS_DISCONNECT_BY_APPLICATION,
12677         NULL);
12678     }
12679 
12680 #if OPENSSL_VERSION_NUMBER < 0x0090702fL
12681     /* Make sure blinding is turned on. (For some reason, this only seems
12682      * to be allowed on SSL objects, not on SSL_CTX objects.  Bummer).
12683      */
12684     tls_blinding_on(ctrl_ssl);
12685 #endif
12686 
12687     tls_flags |= TLS_SESS_ON_CTRL;
12688 
12689     if (pr_trace_get_level(timing_channel) >= 4) {
12690       unsigned long elapsed_ms;
12691       uint64_t finish_ms;
12692 
12693       pr_gettimeofday_millis(&finish_ms);
12694 
12695       elapsed_ms = (unsigned long) (finish_ms - session.connect_time_ms);
12696       pr_trace_msg(timing_channel, 4,
12697         "Time before TLS ctrl handshake: %lu ms", elapsed_ms);
12698 
12699       elapsed_ms = (unsigned long) (finish_ms - start_ms);
12700       pr_trace_msg(timing_channel, 4,
12701         "TLS ctrl handshake duration: %lu ms", elapsed_ms);
12702     }
12703 
12704   } else if (strncmp(mode, "SSL", 4) == 0 ||
12705              strncmp(mode, "TLS-P", 6) == 0) {
12706     uint64_t start_ms;
12707 
12708     pr_response_send(R_234, _("AUTH %s successful"), (char *) cmd->argv[1]);
12709     tls_log("%s", "SSL/TLS-P requested, starting TLS handshake");
12710 
12711     if (pr_trace_get_level(timing_channel) > 0) {
12712       pr_gettimeofday_millis(&start_ms);
12713     }
12714 
12715     if (tls_accept(session.c, FALSE) < 0) {
12716       tls_log("%s", "SSL/TLS-P negotiation failed on control channel");
12717 
12718       if (tls_required_on_ctrl == 1) {
12719         pr_response_send(R_550, _("TLS handshake failed"));
12720         pr_session_disconnect(&tls_module, PR_SESS_DISCONNECT_CONFIG_ACL,
12721           "TLSRequired");
12722       }
12723 
12724       /* If we reach this point, the debug logging may show gibberish
12725        * commands from the client.  In reality, this gibberish is probably
12726        * more encrypted data from the client.
12727        */
12728       pr_response_send(R_550, _("TLS handshake failed"));
12729       pr_session_disconnect(&tls_module, PR_SESS_DISCONNECT_BY_APPLICATION,
12730         NULL);
12731     }
12732 
12733 #if OPENSSL_VERSION_NUMBER < 0x0090702fL
12734     /* Make sure blinding is turned on. (For some reason, this only seems
12735      * to be allowed on SSL objects, not on SSL_CTX objects.  Bummer).
12736      */
12737     tls_blinding_on(ctrl_ssl);
12738 #endif
12739 
12740     tls_flags |= TLS_SESS_ON_CTRL;
12741     tls_flags |= TLS_SESS_NEED_DATA_PROT;
12742 
12743     if (pr_trace_get_level(timing_channel) >= 4) {
12744       unsigned long elapsed_ms;
12745       uint64_t finish_ms;
12746 
12747       pr_gettimeofday_millis(&finish_ms);
12748 
12749       elapsed_ms = (unsigned long) (finish_ms - session.connect_time_ms);
12750       pr_trace_msg(timing_channel, 4,
12751         "Time before TLS ctrl handshake: %lu ms", elapsed_ms);
12752 
12753       elapsed_ms = (unsigned long) (finish_ms - start_ms);
12754       pr_trace_msg(timing_channel, 4,
12755         "TLS ctrl handshake duration: %lu ms", elapsed_ms);
12756     }
12757 
12758   } else {
12759     tls_log("AUTH %s unsupported, declining", (char *) cmd->argv[1]);
12760 
12761     /* Allow other RFC2228 modules a chance a handling this command. */
12762     return PR_DECLINED(cmd);
12763   }
12764 
12765   pr_session_set_protocol("ftps");
12766   session.rfc2228_mech = "TLS";
12767 
12768   return PR_HANDLED(cmd);
12769 }
12770 
12771 MODRET tls_ccc(cmd_rec *cmd) {
12772 
12773   if (!tls_engine ||
12774       !session.rfc2228_mech ||
12775       strncmp(session.rfc2228_mech, "TLS", 4) != 0) {
12776     return PR_DECLINED(cmd);
12777   }
12778 
12779   if (!(tls_flags & TLS_SESS_ON_CTRL)) {
12780     pr_response_add_err(R_533,
12781       _("CCC not allowed on insecure control connection"));
12782 
12783     pr_cmd_set_errno(cmd, EPERM);
12784     errno = EPERM;
12785     return PR_ERROR(cmd);
12786   }
12787 
12788   if (tls_required_on_ctrl == 1) {
12789     pr_response_add_err(R_534, _("Unwilling to accept security parameters"));
12790     tls_log("%s: unwilling to accept security parameters: "
12791       "TLSRequired setting does not allow for unprotected control channel",
12792       (char *) cmd->argv[0]);
12793 
12794     pr_cmd_set_errno(cmd, EPERM);
12795     errno = EPERM;
12796     return PR_ERROR(cmd);
12797   }
12798 
12799   /* Check for <Limit> restrictions. */
12800   if (!dir_check(cmd->tmp_pool, cmd, G_NONE, session.cwd, NULL)) {
12801     pr_response_add_err(R_534, _("Unwilling to accept security parameters"));
12802     tls_log("%s: unwilling to accept security parameters",
12803       (char *) cmd->argv[0]);
12804 
12805     pr_cmd_set_errno(cmd, EPERM);
12806     errno = EPERM;
12807     return PR_ERROR(cmd);
12808   }
12809 
12810   tls_log("received CCC, clearing control channel protection");
12811 
12812   /* Send the OK response asynchronously; the spec dictates that the
12813    * response be sent prior to performing the TLS session shutdown.
12814    */
12815   pr_response_send_async(R_200, _("Clearing control channel protection"));
12816 
12817   /* Close the TLS session, but only one the control channel.
12818    * The data channel, if protected, should remain so.
12819    */
12820 
12821   tls_end_sess(ctrl_ssl, session.c, TLS_SHUTDOWN_FL_BIDIRECTIONAL);
12822   pr_table_remove(tls_ctrl_rd_nstrm->notes, TLS_NETIO_NOTE, NULL);
12823   pr_table_remove(tls_ctrl_wr_nstrm->notes, TLS_NETIO_NOTE, NULL);
12824   ctrl_ssl = NULL;
12825 
12826   /* Remove our NetIO for the control channel. */
12827   pr_unregister_netio(PR_NETIO_STRM_CTRL);
12828 
12829   tls_flags &= ~TLS_SESS_ON_CTRL;
12830   tls_flags |= TLS_SESS_HAVE_CCC;
12831 
12832   return PR_HANDLED(cmd);
12833 }
12834 
12835 MODRET tls_pbsz(cmd_rec *cmd) {
12836 
12837   if (!tls_engine ||
12838       !session.rfc2228_mech ||
12839       strncmp(session.rfc2228_mech, "TLS", 4) != 0)
12840     return PR_DECLINED(cmd);
12841 
12842   CHECK_CMD_ARGS(cmd, 2);
12843 
12844   if (!(tls_flags & TLS_SESS_ON_CTRL)) {
12845     pr_response_add_err(R_503,
12846       _("PBSZ not allowed on insecure control connection"));
12847 
12848     pr_cmd_set_errno(cmd, EPERM);
12849     errno = EPERM;
12850     return PR_ERROR(cmd);
12851   }
12852 
12853   /* We expect "PBSZ 0" */
12854   if (strncmp(cmd->argv[1], "0", 2) == 0) {
12855     pr_response_add(R_200, _("PBSZ 0 successful"));
12856 
12857   } else {
12858     pr_response_add(R_200, _("PBSZ=0 successful"));
12859   }
12860 
12861   tls_flags |= TLS_SESS_PBSZ_OK;
12862   return PR_HANDLED(cmd);
12863 }
12864 
12865 MODRET tls_post_auth(cmd_rec *cmd) {
12866   const char *sni = NULL;
12867   server_rec *named_server = NULL;
12868   cmd_rec *host_cmd = NULL;
12869 
12870   if (tls_engine == FALSE) {
12871     return PR_DECLINED(cmd);
12872   }
12873 
12874   /* We are specifically looking for SNI provided by the client during
12875    * a successful AUTH TLS handshake.
12876    */
12877   if (session.rfc2228_mech == NULL ||
12878       strncmp(session.rfc2228_mech, "TLS", 4) != 0) {
12879     return PR_DECLINED(cmd);
12880   }
12881 
12882   sni = pr_table_get(session.notes, "mod_tls.sni", NULL);
12883   if (sni == NULL) {
12884     /* No SNI provided. */
12885     return PR_DECLINED(cmd);
12886   }
12887 
12888   if (tls_opts & TLS_OPT_IGNORE_SNI) {
12889     return PR_DECLINED(cmd);
12890   }
12891 
12892   named_server = pr_namebind_get_server(sni, main_server->addr,
12893     session.c->local_port);
12894   if (named_server == NULL) {
12895     pr_trace_msg(trace_channel, 5,
12896       "client sent SNI '%s', but no matching host found", sni);
12897     return PR_DECLINED(cmd);
12898   }
12899 
12900   if (named_server == main_server) {
12901     return PR_DECLINED(cmd);
12902   }
12903 
12904   /* Set a session flag indicating that the main_server pointer changed. */
12905   pr_log_debug(DEBUG0,
12906     "Changing to server '%s' (ServerAlias %s) due to TLS SNI",
12907     named_server->ServerName, sni);
12908   session.prev_server = main_server;
12909   main_server = named_server;
12910 
12911   pr_event_generate("core.session-reinit", named_server);
12912 
12913   /* Now we need to inform the modules of the changed config, to let them
12914    * do their checks.
12915    */
12916 
12917   host_cmd = pr_cmd_alloc(cmd->tmp_pool, 2, pstrdup(cmd->tmp_pool, C_HOST), sni,
12918     NULL);
12919   pr_cmd_dispatch_phase(host_cmd, POST_CMD, 0);
12920   pr_cmd_dispatch_phase(host_cmd, LOG_CMD, 0);
12921   pr_response_clear(&resp_list);
12922 
12923   return PR_DECLINED(cmd);
12924 }
12925 
12926 MODRET tls_log_auth(cmd_rec *cmd) {
12927   if (tls_engine == FALSE) {
12928     return PR_DECLINED(cmd);
12929   }
12930 
12931   /* Ensure any sensitive passphrases are scrubbed. */
12932   (void) tls_lookup_pkey(main_server, FALSE, TRUE);
12933 
12934   return PR_DECLINED(cmd);
12935 }
12936 
12937 MODRET tls_post_pass(cmd_rec *cmd) {
12938   config_rec *protocols_config;
12939 
12940   if (tls_engine == FALSE) {
12941     return PR_DECLINED(cmd);
12942   }
12943 
12944   /* At this point, we can look up the Protocols config if the client has been
12945    * authenticated, which may have been tweaked via mod_ifsession's
12946    * user/group/class-specific sections.
12947    */
12948   protocols_config = find_config(main_server->conf, CONF_PARAM, "Protocols",
12949     FALSE);
12950 
12951   if (!(tls_opts & TLS_OPT_ALLOW_PER_USER) &&
12952       protocols_config == NULL) {
12953     return PR_DECLINED(cmd);
12954   }
12955 
12956   tls_authenticated = get_param_ptr(cmd->server->conf, "authenticated", FALSE);
12957 
12958   if (tls_authenticated &&
12959       *tls_authenticated == TRUE) {
12960     config_rec *c;
12961 
12962     c = find_config(TOPLEVEL_CONF, CONF_PARAM, "TLSRequired", FALSE);
12963     if (c) {
12964 
12965       /* Lookup the TLSRequired directive again in this context (which could be
12966        * <Anonymous>, for example, or modified by mod_ifsession).
12967        */
12968 
12969       tls_required_on_ctrl = *((int *) c->argv[0]);
12970       tls_required_on_data = *((int *) c->argv[1]);
12971       tls_required_on_auth = *((int *) c->argv[2]);
12972 
12973       /* We cannot return PR_ERROR for the PASS command at this point, since
12974        * this is a POST_CMD handler.  Instead, we will simply check the
12975        * TLSRequired policy, and if the current session does not make the
12976        * cut, well, then the session gets cut.
12977        */
12978       if ((tls_required_on_ctrl == 1 ||
12979            tls_required_on_auth == 1) &&
12980           (!(tls_flags & TLS_SESS_ON_CTRL))) {
12981         tls_log("SSL/TLS required but absent on control channel, "
12982           "disconnecting");
12983         pr_response_send(R_530, "%s", _("Login incorrect."));
12984         pr_session_disconnect(&tls_module, PR_SESS_DISCONNECT_CONFIG_ACL,
12985           "TLSRequired");
12986       }
12987     }
12988 
12989     if (protocols_config) {
12990       register unsigned int i;
12991       int allow_ftps = FALSE;
12992       array_header *protocols;
12993       char **elts;
12994 
12995       protocols = protocols_config->argv[0];
12996       elts = protocols->elts;
12997 
12998       /* We only want to check for 'ftps' in the configured Protocols list
12999        * if the RFC2228 mechanism is "TLS".
13000        */
13001       if (session.rfc2228_mech != NULL &&
13002           strncmp(session.rfc2228_mech, "TLS", 4) == 0) {
13003         for (i = 0; i < protocols->nelts; i++) {
13004           char *proto;
13005 
13006           proto = elts[i];
13007           if (proto != NULL) {
13008             if (strncasecmp(proto, "ftps", 5) == 0) {
13009               allow_ftps = TRUE;
13010               break;
13011             }
13012           }
13013         }
13014       }
13015 
13016       if (!allow_ftps) {
13017         tls_log("ftps protocol denied by Protocols config");
13018         pr_response_send(R_530, "%s", _("Login incorrect."));
13019         pr_session_disconnect(&tls_module, PR_SESS_DISCONNECT_CONFIG_ACL,
13020           "Denied by Protocols setting");
13021       }
13022     }
13023   }
13024 
13025   return PR_DECLINED(cmd);
13026 }
13027 
13028 MODRET tls_prot(cmd_rec *cmd) {
13029   char *prot;
13030 
13031   if (!tls_engine ||
13032       !session.rfc2228_mech ||
13033       strncmp(session.rfc2228_mech, "TLS", 4) != 0) {
13034     return PR_DECLINED(cmd);
13035   }
13036 
13037   CHECK_CMD_ARGS(cmd, 2);
13038 
13039   if (!(tls_flags & TLS_SESS_ON_CTRL) &&
13040       !(tls_flags & TLS_SESS_HAVE_CCC)) {
13041     pr_response_add_err(R_503,
13042       _("PROT not allowed on insecure control connection"));
13043 
13044     pr_cmd_set_errno(cmd, EPERM);
13045     errno = EPERM;
13046     return PR_ERROR(cmd);
13047   }
13048 
13049   /* In theory, we could enforce the RFC 4217 semantics, which require
13050    * that PBSZ be sent before the PROT command.
13051    *
13052    * However, some broken FTPS clients do not send PBSZ before PROT.  And,
13053    * in practice, since the PBSZ value for FTPS is ALWAYS zero, there is little
13054    * value in punishing users of these broken clients by refusing to work
13055    * with their client.
13056    *
13057    * Thus we've relaxed our PBSZ requirements, by acting as if PBSZ has been
13058    * sent already, even if it has not.  For now.
13059    */
13060 
13061   /* Check for <Limit> restrictions. */
13062   if (!dir_check(cmd->tmp_pool, cmd, G_NONE, session.cwd, NULL)) {
13063     pr_response_add_err(R_534, _("Unwilling to accept security parameters"));
13064     tls_log("%s: denied by <Limit> configuration", (char *) cmd->argv[0]);
13065 
13066     pr_cmd_set_errno(cmd, EPERM);
13067     errno = EPERM;
13068     return PR_ERROR(cmd);
13069   }
13070 
13071   /* Only PROT C or PROT P is valid with respect to SSL/TLS. */
13072   prot = cmd->argv[1];
13073   if (strncmp(prot, "C", 2) == 0) {
13074     char *mesg = "Protection set to Clear";
13075 
13076     if (tls_required_on_data != 1) {
13077       /* Only accept this if SSL/TLS is not required, by policy, on data
13078        * connections.
13079        */
13080       tls_flags &= ~TLS_SESS_NEED_DATA_PROT;
13081       pr_response_add(R_200, "%s", mesg);
13082       tls_log("%s", mesg);
13083 
13084     } else {
13085       pr_response_add_err(R_534, _("Unwilling to accept security parameters"));
13086       tls_log("%s: TLSRequired requires protection for data transfers",
13087         (char *) cmd->argv[0]);
13088       tls_log("%s: unwilling to accept security parameter (%s)",
13089         (char *) cmd->argv[0], prot);
13090 
13091       pr_cmd_set_errno(cmd, EPERM);
13092       errno = EPERM;
13093       return PR_ERROR(cmd);
13094     }
13095 
13096   } else if (strncmp(prot, "P", 2) == 0) {
13097     char *mesg = "Protection set to Private";
13098 
13099     if (tls_required_on_data != -1) {
13100       /* Only accept this if SSL/TLS is allowed, by policy, on data
13101        * connections.
13102        */
13103       tls_flags |= TLS_SESS_NEED_DATA_PROT;
13104       pr_response_add(R_200, "%s", mesg);
13105       tls_log("%s", mesg);
13106 
13107     } else {
13108       pr_response_add_err(R_534, _("Unwilling to accept security parameters"));
13109       tls_log("%s: TLSRequired does not allow protection for data transfers",
13110         (char *) cmd->argv[0]);
13111       tls_log("%s: unwilling to accept security parameter (%s)",
13112         (char *) cmd->argv[0], prot);
13113 
13114       pr_cmd_set_errno(cmd, EPERM);
13115       errno = EPERM;
13116       return PR_ERROR(cmd);
13117     }
13118 
13119   } else if (strncmp(prot, "S", 2) == 0 ||
13120              strncmp(prot, "E", 2) == 0) {
13121     pr_response_add_err(R_536, _("PROT %s unsupported"), prot);
13122 
13123     /* By the time the logic reaches this point, there must have been
13124      * an SSL/TLS session negotiated; other AUTH mechanisms will handle
13125      * things differently, and when they do, the logic of this handler
13126      * would not reach this point.  This means that it would not be impolite
13127      * to return ERROR here, rather than DECLINED: it shows that mod_tls
13128      * is handling the security mechanism, and that this module does not
13129      * allow for the unsupported PROT levels.
13130      */
13131 
13132     pr_cmd_set_errno(cmd, ENOSYS);
13133     errno = ENOSYS;
13134     return PR_ERROR(cmd);
13135 
13136   } else {
13137     pr_response_add_err(R_504, _("PROT %s unsupported"), prot);
13138 
13139     pr_cmd_set_errno(cmd, ENOSYS);
13140     errno = ENOSYS;
13141     return PR_ERROR(cmd);
13142   }
13143 
13144   tls_flags |= TLS_SESS_PBSZ_OK;
13145   return PR_HANDLED(cmd);
13146 }
13147 
13148 MODRET tls_sscn(cmd_rec *cmd) {
13149 
13150   if (tls_engine == FALSE ||
13151       session.rfc2228_mech == NULL ||
13152       strncmp(session.rfc2228_mech, "TLS", 4) != 0) {
13153     return PR_DECLINED(cmd);
13154   }
13155 
13156   if (cmd->argc > 2) {
13157     int xerrno = EINVAL;
13158 
13159     tls_log("denying malformed SSCN command: '%s %s'", (char *) cmd->argv[0],
13160       cmd->arg);
13161     pr_response_add_err(R_504, _("%s: %s"), (char *) cmd->argv[0],
13162       strerror(xerrno));
13163 
13164     pr_cmd_set_errno(cmd, xerrno);
13165     errno = xerrno;
13166     return PR_ERROR(cmd);
13167   }
13168 
13169   if (!dir_check(cmd->tmp_pool, cmd, cmd->group, session.cwd, NULL)) {
13170     int xerrno = EPERM;
13171 
13172     pr_log_debug(DEBUG8, "%s denied by <Limit> configuration",
13173       (char *) cmd->argv[0]);
13174     tls_log("%s denied by <Limit> configuration", (char *) cmd->argv[0]);
13175     pr_response_add_err(R_550, _("%s: %s"), (char *) cmd->argv[0],
13176       strerror(xerrno));
13177 
13178     pr_cmd_set_errno(cmd, xerrno);
13179     errno = xerrno;
13180     return PR_ERROR(cmd);
13181   }
13182 
13183   if (cmd->argc == 1) {
13184     /* Client is querying our SSCN mode. */
13185     pr_response_add(R_200, "%s:%s METHOD", (char *) cmd->argv[0],
13186       tls_sscn_mode == TLS_SSCN_MODE_SERVER ? "SERVER" : "CLIENT");
13187 
13188   } else {
13189     /* Parameter MUST be one of: "ON", "OFF. */
13190     if (strncmp(cmd->argv[1], "ON", 3) == 0) {
13191       tls_sscn_mode = TLS_SSCN_MODE_CLIENT;
13192       pr_response_add(R_200, "%s:CLIENT METHOD", (char *) cmd->argv[0]);
13193 
13194     } else if (strncmp(cmd->argv[1], "OFF", 4) == 0) {
13195       tls_sscn_mode = TLS_SSCN_MODE_SERVER;
13196       pr_response_add(R_200, "%s:SERVER METHOD", (char *) cmd->argv[0]);
13197 
13198     } else {
13199       int xerrno = EINVAL;
13200 
13201       tls_log("denying unsupported SSCN command: '%s %s'",
13202         (char *) cmd->argv[0], (char *) cmd->argv[1]);
13203       pr_response_add_err(R_501, _("%s: %s"), (char *) cmd->argv[0],
13204         strerror(xerrno));
13205 
13206       pr_cmd_set_errno(cmd, xerrno);
13207       errno = xerrno;
13208       return PR_ERROR(cmd);
13209     }
13210   }
13211 
13212   return PR_HANDLED(cmd);
13213 }
13214 
13215 /* Configuration handlers
13216  */
13217 
13218 /* usage: TLSCACertificateFile file */
13219 MODRET set_tlscacertfile(cmd_rec *cmd) {
13220   int res;
13221   char *path;
13222   SSL_CTX *ctx;
13223 
13224   CHECK_ARGS(cmd, 1);
13225   CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL);
13226 
13227   path = cmd->argv[1];
13228 
13229   PRIVS_ROOT
13230 
13231   ctx = SSL_CTX_new(SSLv23_server_method());
13232   if (ctx != NULL) {
13233     res = SSL_CTX_load_verify_locations(ctx, path, NULL);
13234     if (res != 1) {
13235       unsigned long err_code;
13236       const char *err_msg;
13237 
13238       PRIVS_RELINQUISH
13239 
13240       /* Unfortunately, if the specified path exists but does not contain
13241        * any certificate data, the error queue is not helpful.  Thanks,
13242        * OpenSSL.  Thus we have to peek first.
13243        */
13244       err_code = ERR_peek_error();
13245       if (err_code != 0) {
13246         err_msg = tls_get_errors2(cmd->tmp_pool);
13247 
13248       } else {
13249         err_msg = "file contained no certificate data";
13250       }
13251 
13252       CONF_ERROR(cmd, pstrcat(cmd->tmp_pool,
13253         "unable to use '", path, "': ", err_msg, NULL));
13254     }
13255 
13256     SSL_CTX_free(ctx);
13257 
13258   } else {
13259     res = file_exists2(cmd->tmp_pool, path);
13260     if (res == FALSE) {
13261       PRIVS_RELINQUISH
13262       CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, "'", path, "' does not exist",
13263         NULL));
13264     }
13265   }
13266 
13267   PRIVS_RELINQUISH
13268 
13269   if (*path != '/') {
13270     CONF_ERROR(cmd, "parameter must be an absolute path");
13271   }
13272 
13273   add_config_param_str(cmd->argv[0], 1, path);
13274   return PR_HANDLED(cmd);
13275 }
13276 
13277 /* usage: TLSCACertificatePath path */
13278 MODRET set_tlscacertpath(cmd_rec *cmd) {
13279   int res;
13280   char *path;
13281 
13282   CHECK_ARGS(cmd, 1);
13283   CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL);
13284 
13285   path = cmd->argv[1];
13286 
13287   PRIVS_ROOT
13288   res = dir_exists2(cmd->tmp_pool, path);
13289   PRIVS_RELINQUISH
13290 
13291   if (res == FALSE) {
13292     CONF_ERROR(cmd, "parameter must be a directory path");
13293   }
13294 
13295   if (*path != '/') {
13296     CONF_ERROR(cmd, "parameter must be an absolute path");
13297   }
13298 
13299   add_config_param_str(cmd->argv[0], 1, path);
13300   return PR_HANDLED(cmd);
13301 }
13302 
13303 /* usage: TLSCARevocationFile file */
13304 MODRET set_tlscacrlfile(cmd_rec *cmd) {
13305   int res;
13306   char *path;
13307   X509_STORE *store;
13308 
13309   CHECK_ARGS(cmd, 1);
13310   CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL);
13311 
13312   path = cmd->argv[1];
13313 
13314   PRIVS_ROOT
13315 
13316   store = X509_STORE_new();
13317   if (store != NULL) {
13318     res = X509_STORE_load_locations(store, path, NULL);
13319     if (res != 1) {
13320       unsigned long err_code;
13321       const char *err_msg;
13322 
13323       PRIVS_RELINQUISH
13324 
13325       /* Unfortunately, if the specified path exists but does not contain
13326        * any CRL data, the error queue is not helpful.  Thanks, OpenSSL.
13327        * Thus we have to peek first.
13328        */
13329       err_code = ERR_peek_error();
13330       if (err_code != 0) {
13331         err_msg = tls_get_errors2(cmd->tmp_pool);
13332 
13333       } else {
13334         err_msg = "file contained no CRL data";
13335       }
13336 
13337       CONF_ERROR(cmd, pstrcat(cmd->tmp_pool,
13338         "unable to use '", path, "': ", err_msg, NULL));
13339     }
13340 
13341     X509_STORE_free(store);
13342 
13343   } else {
13344     res = file_exists2(cmd->tmp_pool, path);
13345     if (res == FALSE) {
13346       PRIVS_RELINQUISH
13347       CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, "'", path, "' does not exist",
13348         NULL));
13349     }
13350   }
13351 
13352   PRIVS_RELINQUISH
13353 
13354   if (*path != '/') {
13355     CONF_ERROR(cmd, "parameter must be an absolute path");
13356   }
13357 
13358   add_config_param_str(cmd->argv[0], 1, path);
13359   return PR_HANDLED(cmd);
13360 }
13361 
13362 /* usage: TLSCARevocationPath path */
13363 MODRET set_tlscacrlpath(cmd_rec *cmd) {
13364   int res;
13365   char *path;
13366 
13367   CHECK_ARGS(cmd, 1);
13368   CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL);
13369 
13370   path = cmd->argv[1];
13371 
13372   PRIVS_ROOT
13373   res = dir_exists2(cmd->tmp_pool, path);
13374   PRIVS_RELINQUISH
13375 
13376   if (!res) {
13377     CONF_ERROR(cmd, "parameter must be a directory path");
13378   }
13379 
13380   if (*path != '/') {
13381     CONF_ERROR(cmd, "parameter must be an absolute path");
13382   }
13383 
13384   add_config_param_str(cmd->argv[0], 1, path);
13385   return PR_HANDLED(cmd);
13386 }
13387 
13388 /* usage: TLSCertificateChainFile file */
13389 MODRET set_tlscertchain(cmd_rec *cmd) {
13390   int res;
13391   char *path;
13392   SSL_CTX *ctx;
13393 
13394   CHECK_ARGS(cmd, 1);
13395   CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL);
13396 
13397   path = cmd->argv[1];
13398 
13399   PRIVS_ROOT
13400 
13401   ctx = SSL_CTX_new(SSLv23_server_method());
13402   if (ctx != NULL) {
13403     res = SSL_CTX_use_certificate_chain_file(ctx, path);
13404     if (res != 1) {
13405       unsigned long err_code;
13406       const char *err_msg;
13407 
13408       PRIVS_RELINQUISH
13409 
13410       /* Unfortunately, if the specified path exists but does not contain
13411        * any certificate data, the error queue is not helpful.  Thanks,
13412        * OpenSSL.  Thus we have to peek first.
13413        */
13414       err_code = ERR_peek_error();
13415       if (err_code != 0) {
13416         err_msg = tls_get_errors2(cmd->tmp_pool);
13417 
13418       } else {
13419         err_msg = "file contained no certificate data";
13420       }
13421 
13422       CONF_ERROR(cmd, pstrcat(cmd->tmp_pool,
13423         "unable to use '", path, "': ", err_msg, NULL));
13424     }
13425 
13426     SSL_CTX_free(ctx);
13427 
13428   } else {
13429     res = file_exists2(cmd->tmp_pool, path);
13430     if (res == FALSE) {
13431       PRIVS_RELINQUISH
13432       CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, "'", path, "' does not exist",
13433         NULL));
13434     }
13435   }
13436 
13437   PRIVS_RELINQUISH
13438 
13439   if (*path != '/') {
13440     CONF_ERROR(cmd, "parameter must be an absolute path");
13441   }
13442 
13443   add_config_param_str(cmd->argv[0], 1, path);
13444   return PR_HANDLED(cmd);
13445 }
13446 
13447 /* usage: TLSCipherSuite string */
13448 MODRET set_tlsciphersuite(cmd_rec *cmd) {
13449   config_rec *c = NULL;
13450   char *ciphersuite = NULL;
13451   SSL_CTX *ctx;
13452 
13453   CHECK_ARGS(cmd, 1);
13454   CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL);
13455 
13456   ciphersuite = cmd->argv[1];
13457   c = add_config_param(cmd->argv[0], 1, NULL);
13458 
13459   /* Make sure that EXPORT ciphers cannot be used, per Bug#4163. Note that
13460    * this breaks system profiles, so handle them specially.
13461    */
13462   if (strncmp(ciphersuite, "PROFILE=", 8) == 0) {
13463     ciphersuite = pstrdup(c->pool, ciphersuite);
13464 
13465   } else {
13466     ciphersuite = pstrcat(c->pool, "!EXPORT:", ciphersuite, NULL);
13467   }
13468 
13469   /* Check that our construct ciphersuite is acceptable. */
13470   ctx = SSL_CTX_new(SSLv23_server_method());
13471   if (ctx != NULL) {
13472     if (SSL_CTX_set_cipher_list(ctx, ciphersuite) != 1) {
13473       CONF_ERROR(cmd, pstrcat(cmd->tmp_pool,
13474         "unable to use ciphersuite '", ciphersuite, "': ",
13475         tls_get_errors2(cmd->tmp_pool), NULL));
13476     }
13477 
13478     SSL_CTX_free(ctx);
13479   }
13480 
13481   c->argv[0] = ciphersuite;
13482   return PR_HANDLED(cmd);
13483 }
13484 
13485 /* usage: TLSControlsACLs actions|all allow|deny user|group list */
13486 MODRET set_tlsctrlsacls(cmd_rec *cmd) {
13487 #ifdef PR_USE_CTRLS
13488   char *bad_action = NULL, **actions = NULL;
13489 
13490   CHECK_ARGS(cmd, 4);
13491   CHECK_CONF(cmd, CONF_ROOT);
13492 
13493   /* We can cheat here, and use the ctrls_parse_acl() routine to
13494    * separate the given string...
13495    */
13496   actions = ctrls_parse_acl(cmd->tmp_pool, cmd->argv[1]);
13497 
13498   /* Check the second parameter to make sure it is "allow" or "deny" */
13499   if (strncmp(cmd->argv[2], "allow", 6) != 0 &&
13500       strncmp(cmd->argv[2], "deny", 5) != 0) {
13501     CONF_ERROR(cmd, "second parameter must be 'allow' or 'deny'");
13502   }
13503 
13504   /* Check the third parameter to make sure it is "user" or "group" */
13505   if (strncmp(cmd->argv[3], "user", 5) != 0 &&
13506       strncmp(cmd->argv[3], "group", 6) != 0) {
13507     CONF_ERROR(cmd, "third parameter must be 'user' or 'group'");
13508   }
13509 
13510   bad_action = pr_ctrls_set_module_acls(tls_acttab, tls_act_pool, actions,
13511     cmd->argv[2], cmd->argv[3], cmd->argv[4]);
13512   if (bad_action != NULL) {
13513     CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, ": unknown action: '",
13514       bad_action, "'", NULL));
13515   }
13516 
13517   return PR_HANDLED(cmd);
13518 #else
13519   CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, "The ", cmd->argv[0],
13520     " directive requires Controls support (--enable-ctrls)", NULL));
13521 #endif /* PR_USE_CTRLS */
13522 }
13523 
13524 /* usage: TLSCryptoDevice driver|"ALL" */
13525 MODRET set_tlscryptodevice(cmd_rec *cmd) {
13526 #if OPENSSL_VERSION_NUMBER > 0x000907000L
13527   CHECK_ARGS(cmd, 1);
13528   CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL);
13529 
13530   (void) add_config_param_str(cmd->argv[0], 1, cmd->argv[1]);
13531 
13532   return PR_HANDLED(cmd);
13533 
13534 #else /* OpenSSL is too old for ENGINE support */
13535   CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, "The ", cmd->argv[0],
13536     "directive cannot be used on the system, as the OpenSSL version is too old",
13537     NULL));
13538 #endif
13539 }
13540 
13541 /* usage: TLSDHParamFile file */
13542 MODRET set_tlsdhparamfile(cmd_rec *cmd) {
13543   int res;
13544   char *path;
13545 
13546   CHECK_ARGS(cmd, 1);
13547   CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL);
13548 
13549   path = cmd->argv[1];
13550 
13551   PRIVS_ROOT
13552   res = file_exists2(cmd->tmp_pool, path);
13553   PRIVS_RELINQUISH
13554 
13555   if (res == FALSE) {
13556     CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, "'", path, "' does not exist",
13557       NULL));
13558   }
13559 
13560   if (*path != '/') {
13561     CONF_ERROR(cmd, "parameter must be an absolute path");
13562   }
13563 
13564   add_config_param_str(cmd->argv[0], 1, path);
13565   return PR_HANDLED(cmd);
13566 }
13567 
13568 /* usage: TLSDSACertificateFile file */
13569 MODRET set_tlsdsacertfile(cmd_rec *cmd) {
13570   char *path;
13571   const char *fingerprint, *errstr = NULL;
13572 
13573   CHECK_ARGS(cmd, 1);
13574   CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL);
13575 
13576   path = cmd->argv[1];
13577   if (*path != '/') {
13578     CONF_ERROR(cmd, "parameter must be an absolute path");
13579   }
13580 
13581   PRIVS_ROOT
13582   fingerprint = tls_get_fingerprint_from_file(cmd->tmp_pool, path, EVP_PKEY_DSA,
13583     &errstr);
13584   PRIVS_RELINQUISH
13585 
13586   if (fingerprint == NULL) {
13587     if (errstr == NULL) {
13588       errstr = "does not exist or does not contain a certificate";
13589     }
13590 
13591     CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, "unable to use '", path, "': ",
13592       errstr, NULL));
13593   }
13594 
13595   add_config_param_str(cmd->argv[0], 2, path, fingerprint);
13596   return PR_HANDLED(cmd);
13597 }
13598 
13599 /* usage: TLSDSACertificateKeyFile file */
13600 MODRET set_tlsdsakeyfile(cmd_rec *cmd) {
13601   int res;
13602   char *path;
13603   SSL_CTX *ctx;
13604 
13605   CHECK_ARGS(cmd, 1);
13606   CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL);
13607 
13608   path = cmd->argv[1];
13609 
13610   PRIVS_ROOT
13611 
13612   ctx = SSL_CTX_new(SSLv23_server_method());
13613   if (ctx != NULL) {
13614     /* Note that the configured key file might be passphrase-protected.  We
13615      * do not necessarily want to prompt for the passphrase here, so if that
13616      * is the error returned, it is an expected condition, and indicates that
13617      * the encoding of the key is acceptable.
13618      */
13619     SSL_CTX_set_default_passwd_cb(ctx, tls_keyfile_check_cb);
13620 
13621     res = SSL_CTX_use_PrivateKey_file(ctx, path, X509_FILETYPE_PEM);
13622     if (res != 1) {
13623       unsigned long err_code;
13624 
13625       err_code = ERR_peek_error();
13626       switch (ERR_GET_REASON(err_code)) {
13627         /* These are "expected" error codes from working with
13628          * passphrase-protected keys.
13629          */
13630         case EVP_R_BAD_DECRYPT:
13631         case PEM_R_BAD_PASSWORD_READ:
13632           break;
13633 
13634         default: {
13635           PRIVS_RELINQUISH
13636 
13637           CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, "unable to use '", path, "': ",
13638             tls_get_errors2(cmd->tmp_pool), NULL));
13639         }
13640       }
13641     }
13642 
13643     SSL_CTX_free(ctx);
13644 
13645   } else {
13646     res = file_exists2(cmd->tmp_pool, path);
13647     if (res == FALSE) {
13648       PRIVS_RELINQUISH
13649       CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, "'", path, "' does not exist",
13650         NULL));
13651     }
13652   }
13653 
13654   PRIVS_RELINQUISH
13655 
13656   if (*path != '/') {
13657     CONF_ERROR(cmd, "parameter must be an absolute path");
13658   }
13659 
13660   add_config_param_str(cmd->argv[0], 1, path);
13661   return PR_HANDLED(cmd);
13662 }
13663 
13664 /* usage: TLSECCertificateFile file */
13665 MODRET set_tlseccertfile(cmd_rec *cmd) {
13666 #ifdef PR_USE_OPENSSL_ECC
13667   char *path;
13668   const char *fingerprint, *errstr = NULL;
13669 
13670   CHECK_ARGS(cmd, 1);
13671   CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL);
13672 
13673   path = cmd->argv[1];
13674   if (*path != '/') {
13675     CONF_ERROR(cmd, "parameter must be an absolute path");
13676   }
13677 
13678   PRIVS_ROOT
13679   fingerprint = tls_get_fingerprint_from_file(cmd->tmp_pool, path, EVP_PKEY_EC,
13680     &errstr);
13681   PRIVS_RELINQUISH
13682 
13683   if (fingerprint == NULL) {
13684     CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, "'", path,
13685       "' does not exist or does not contain a certificate", NULL));
13686   }
13687 
13688   add_config_param_str(cmd->argv[0], 2, path, fingerprint);
13689   return PR_HANDLED(cmd);
13690 #else
13691   CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, "The ", (char *) cmd->argv[0],
13692     " directive cannot be used on this system, as your OpenSSL version "
13693     "does not have EC support", NULL));
13694 #endif /* PR_USE_OPENSSL_ECC */
13695 }
13696 
13697 /* usage: TLSECCertificateKeyFile file */
13698 MODRET set_tlseckeyfile(cmd_rec *cmd) {
13699 #ifdef PR_USE_OPENSSL_ECC
13700   int res;
13701   char *path;
13702   SSL_CTX *ctx;
13703 
13704   CHECK_ARGS(cmd, 1);
13705   CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL);
13706 
13707   path = cmd->argv[1];
13708 
13709   PRIVS_ROOT
13710 
13711   ctx = SSL_CTX_new(SSLv23_server_method());
13712   if (ctx != NULL) {
13713     /* Note that the configured key file might be passphrase-protected.  We
13714      * do not necessarily want to prompt for the passphrase here, so if that
13715      * is the error returned, it is an expected condition, and indicates that
13716      * the encoding of the key is acceptable.
13717      */
13718     SSL_CTX_set_default_passwd_cb(ctx, tls_keyfile_check_cb);
13719 
13720     res = SSL_CTX_use_PrivateKey_file(ctx, path, X509_FILETYPE_PEM);
13721     if (res != 1) {
13722       unsigned long err_code;
13723 
13724       err_code = ERR_peek_error();
13725       switch (ERR_GET_REASON(err_code)) {
13726         /* These are "expected" error codes from working with
13727          * passphrase-protected keys.
13728          */
13729         case EVP_R_BAD_DECRYPT:
13730         case PEM_R_BAD_PASSWORD_READ:
13731           break;
13732 
13733         default: {
13734           PRIVS_RELINQUISH
13735 
13736           CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, "unable to use '", path, "': ",
13737             tls_get_errors2(cmd->tmp_pool), NULL));
13738         }
13739       }
13740     }
13741 
13742     SSL_CTX_free(ctx);
13743 
13744   } else {
13745     res = file_exists2(cmd->tmp_pool, path);
13746     if (res == FALSE) {
13747       PRIVS_RELINQUISH
13748       CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, "'", path, "' does not exist",
13749         NULL));
13750     }
13751   }
13752 
13753   PRIVS_RELINQUISH
13754 
13755   if (*path != '/') {
13756     CONF_ERROR(cmd, "parameter must be an absolute path");
13757   }
13758 
13759   add_config_param_str(cmd->argv[0], 1, path);
13760   return PR_HANDLED(cmd);
13761 #else
13762   CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, "The ", (char *) cmd->argv[0],
13763     " directive cannot be used on this system, as your OpenSSL version "
13764     "does not have EC support", NULL));
13765 #endif /* PR_USE_OPENSSL_ECC */
13766 }
13767 
13768 /* usage: TLSECDHCurve name */
13769 MODRET set_tlsecdhcurve(cmd_rec *cmd) {
13770 #ifdef PR_USE_OPENSSL_ECC
13771   char *curve_names = NULL;
13772 # if defined(SSL_CTX_set1_curves_list)
13773   SSL_CTX *ctx = NULL;
13774 # else
13775   int curve_nid = -1;
13776   EC_KEY *ec_key = NULL;
13777 # endif /* No SSL_CTX_set1_curves_list; pre-OpenSSL 1.0.2 */
13778 
13779   CHECK_ARGS(cmd, 1);
13780   CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL);
13781 
13782   curve_names = cmd->argv[1];
13783 
13784 # if defined(SSL_CTX_set1_curves_list)
13785   if (strcasecmp(curve_names, "auto") != 0) {
13786     ctx = SSL_CTX_new(SSLv23_server_method());
13787   }
13788 
13789   if (ctx != NULL) {
13790     int res;
13791 
13792     res = SSL_CTX_set1_curves_list(ctx, curve_names);
13793     if (res != 1) {
13794       CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, "unable to use ECDH curves '",
13795         curve_names, "': ", tls_get_errors2(cmd->tmp_pool), NULL));
13796     }
13797 
13798     SSL_CTX_free(ctx);
13799   }
13800 
13801   (void) add_config_param_str(cmd->argv[0], 1, curve_names);
13802 
13803 # else
13804   /* The special-case handling of these curve names is copied from OpenSSL's
13805    * apps/ecparam.c code.
13806    */
13807 
13808   if (strcmp(curve_names, "secp192r1") == 0) {
13809     curve_nid = NID_X9_62_prime192v1;
13810 
13811   } else if (strcmp(curve_names, "secp256r1") == 0) {
13812     curve_nid = NID_X9_62_prime256v1;
13813 
13814   } else {
13815     curve_nid = OBJ_sn2nid(curve_names);
13816   }
13817 
13818   ec_key = EC_KEY_new_by_curve_name(curve_nid);
13819   if (ec_key == NULL) {
13820     char *err_str = "unknown/unsupported curve";
13821 
13822     if (curve_nid > 0) {
13823       err_str = ERR_error_string(ERR_get_error(), NULL);
13824     }
13825 
13826     if (strchr(curve_names, ':') != NULL) {
13827       CONF_ERROR(cmd, pstrcat(cmd->tmp_pool,
13828         "configuring multiple curves '", curve_names,
13829         "' not supported by OpenSSL version ", OPENSSL_VERSION_TEXT, NULL));
13830 
13831     } else {
13832       CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, "unable to create '", curve_names,
13833         "' EC curve: ", err_str, NULL));
13834     }
13835   }
13836 
13837   (void) add_config_param(cmd->argv[0], 1, ec_key);
13838 # endif /* pre-OpenSSL-1.0.2 */
13839 
13840   return PR_HANDLED(cmd);
13841 
13842 #else
13843   CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, "The ", cmd->argv[0],
13844     " directive cannot be used on this system, as your OpenSSL version "
13845     "does not have EC support", NULL));
13846 #endif /* PR_USE_OPENSSL_ECC */
13847 }
13848 
13849 /* usage: TLSEngine on|off */
13850 MODRET set_tlsengine(cmd_rec *cmd) {
13851   int engine = -1;
13852   config_rec *c = NULL;
13853 
13854   CHECK_ARGS(cmd, 1);
13855   CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL);
13856 
13857   engine = get_boolean(cmd, 1);
13858   if (engine == -1) {
13859     CONF_ERROR(cmd, "expected Boolean parameter");
13860   }
13861 
13862   c = add_config_param(cmd->argv[0], 1, NULL);
13863   c->argv[0] = pcalloc(c->pool, sizeof(unsigned char));
13864   *((unsigned char *) c->argv[0]) = engine;
13865 
13866   return PR_HANDLED(cmd);
13867 }
13868 
13869 /* usage: TLSLog file */
13870 MODRET set_tlslog(cmd_rec *cmd) {
13871   CHECK_ARGS(cmd, 1);
13872   CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL);
13873 
13874   add_config_param_str(cmd->argv[0], 1, cmd->argv[1]);
13875   return PR_HANDLED(cmd);
13876 }
13877 
13878 /* usage: TLSMasqueradeAddress ip-addr|dns-name */
13879 MODRET set_tlsmasqaddr(cmd_rec *cmd) {
13880   config_rec *c = NULL;
13881   const pr_netaddr_t *masq_addr = NULL;
13882   unsigned int addr_flags = PR_NETADDR_GET_ADDR_FL_INCL_DEVICE;
13883 
13884   CHECK_ARGS(cmd, 1);
13885   CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL);
13886 
13887   /* We can only masquerade as one address, so we don't need to know if the
13888    * given name might map to multiple addresses.
13889    */
13890   masq_addr = pr_netaddr_get_addr2(cmd->server->pool, cmd->argv[1], NULL,
13891     addr_flags);
13892   if (masq_addr == NULL) {
13893     return PR_ERROR_MSG(cmd, NULL, pstrcat(cmd->tmp_pool, cmd->argv[0],
13894       ": unable to resolve \"", cmd->argv[1], "\"", NULL));
13895   }
13896 
13897   c = add_config_param(cmd->argv[0], 2, (void *) masq_addr, NULL);
13898   c->argv[1] = pstrdup(c->pool, cmd->argv[1]);
13899 
13900   return PR_HANDLED(cmd);
13901 }
13902 
13903 /* usage: TLSNextProtocol on|off */
13904 MODRET set_tlsnextprotocol(cmd_rec *cmd) {
13905 #if !defined(OPENSSL_NO_TLSEXT)
13906   config_rec *c;
13907   int use_next_protocol = FALSE;
13908 
13909   CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL);
13910   CHECK_ARGS(cmd, 1);
13911 
13912   use_next_protocol = get_boolean(cmd, 1);
13913   if (use_next_protocol == -1) {
13914     CONF_ERROR(cmd, "expected Boolean parameter");
13915   }
13916 
13917   c = add_config_param(cmd->argv[0], 1, NULL);
13918   c->argv[0] = palloc(c->pool, sizeof(int));
13919   *((int *) c->argv[0]) = use_next_protocol;
13920   return PR_HANDLED(cmd);
13921 
13922 #else
13923   CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, "The ", cmd->argv[0],
13924     " directive cannot be used on this system, as your OpenSSL version "
13925     "does not have NPN/ALPN support", NULL));
13926 #endif /* !OPENSSL_NO_TLSEXT */
13927 }
13928 
13929 /* usage: TLSOptions opt1 opt2 ... */
13930 MODRET set_tlsoptions(cmd_rec *cmd) {
13931   config_rec *c = NULL;
13932   register unsigned int i = 0;
13933   unsigned long opts = 0UL;
13934 
13935   if (cmd->argc-1 == 0) {
13936     CONF_ERROR(cmd, "wrong number of parameters");
13937   }
13938 
13939   CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL);
13940 
13941   c = add_config_param(cmd->argv[0], 1, NULL);
13942 
13943   for (i = 1; i < cmd->argc; i++) {
13944     if (strcmp(cmd->argv[i], "AllowDotLogin") == 0) {
13945       opts |= TLS_OPT_ALLOW_DOT_LOGIN;
13946 
13947     } else if (strcmp(cmd->argv[i], "AllowPerUser") == 0) {
13948       opts |= TLS_OPT_ALLOW_PER_USER;
13949 
13950     } else if (strcmp(cmd->argv[i], "AllowWeakDH") == 0) {
13951       opts |= TLS_OPT_ALLOW_WEAK_DH;
13952 
13953     } else if (strcmp(cmd->argv[i], "AllowClientRenegotiation") == 0 ||
13954                strcmp(cmd->argv[i], "AllowClientRenegotiations") == 0) {
13955       opts |= TLS_OPT_ALLOW_CLIENT_RENEGOTIATIONS;
13956 
13957     } else if (strcmp(cmd->argv[i], "EnableDiags") == 0) {
13958       opts |= TLS_OPT_ENABLE_DIAGS;
13959 
13960     } else if (strcmp(cmd->argv[i], "ExportCertData") == 0) {
13961       opts |= TLS_OPT_EXPORT_CERT_DATA;
13962 
13963     } else if (strcmp(cmd->argv[i], "IgnoreSNI") == 0) {
13964       opts |= TLS_OPT_IGNORE_SNI;
13965 
13966     } else if (strcmp(cmd->argv[i], "NoCertRequest") == 0) {
13967       pr_log_debug(DEBUG0, MOD_TLS_VERSION
13968         ": NoCertRequest TLSOption is deprecated");
13969 
13970 #ifdef SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS
13971     } else if (strcmp(cmd->argv[i], "NoEmptyFragments") == 0) {
13972       /* Unlike the other TLSOptions, this option is handled slightly
13973        * differently, due to the fact that option affects the creation
13974        * of the SSL_CTX.
13975        *
13976        */
13977       tls_ssl_opts |= SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS;
13978 #else
13979       pr_log_pri(PR_LOG_NOTICE, MOD_TLS_VERSION ": TLSOption NoEmptyFragments not supported (OpenSSL version is too old)");
13980 #endif
13981 
13982     } else if (strcmp(cmd->argv[i], "NoSessionReuseRequired") == 0) {
13983       opts |= TLS_OPT_NO_SESSION_REUSE_REQUIRED;
13984 
13985     } else if (strcmp(cmd->argv[i], "StdEnvVars") == 0) {
13986       opts |= TLS_OPT_STD_ENV_VARS;
13987 
13988     } else if (strcmp(cmd->argv[i], "dNSNameRequired") == 0) {
13989       opts |= TLS_OPT_VERIFY_CERT_FQDN;
13990 
13991     } else if (strcmp(cmd->argv[i], "iPAddressRequired") == 0) {
13992       opts |= TLS_OPT_VERIFY_CERT_IP_ADDR;
13993 
13994     } else if (strcmp(cmd->argv[i], "UseImplicitSSL") == 0) {
13995       opts |= TLS_OPT_USE_IMPLICIT_SSL;
13996 
13997     } else if (strcmp(cmd->argv[i], "CommonNameRequired") == 0) {
13998       opts |= TLS_OPT_VERIFY_CERT_CN;
13999 
14000     } else if (strcmp(cmd->argv[i], "NoAutoECDH") == 0) {
14001       opts |= TLS_OPT_NO_AUTO_ECDH;
14002 
14003     } else {
14004       CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, ": unknown TLSOption '",
14005         cmd->argv[i], "'", NULL));
14006     }
14007   }
14008 
14009   c->argv[0] = pcalloc(c->pool, sizeof(unsigned long));
14010   *((unsigned long *) c->argv[0]) = opts;
14011 
14012   return PR_HANDLED(cmd);
14013 }
14014 
14015 /* usage: TLSPassPhraseProvider path */
14016 MODRET set_tlspassphraseprovider(cmd_rec *cmd) {
14017   struct stat st;
14018   char *path;
14019 
14020   CHECK_ARGS(cmd, 1);
14021   CHECK_CONF(cmd, CONF_ROOT);
14022 
14023   path = cmd->argv[1];
14024 
14025   if (*path != '/') {
14026     CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, "must be a full path: '", path, "'",
14027       NULL));
14028   }
14029 
14030   if (stat(path, &st) < 0) {
14031     CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, "error checking '", path, "': ",
14032       strerror(errno), NULL));
14033   }
14034 
14035   if (!S_ISREG(st.st_mode)) {
14036     CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, "unable to use '", path,
14037       ": Not a regular file", NULL));
14038   }
14039 
14040   tls_passphrase_provider = pstrdup(permanent_pool, path);
14041   return PR_HANDLED(cmd);
14042 }
14043 
14044 /* usage: TLSPKCS12File file */
14045 MODRET set_tlspkcs12file(cmd_rec *cmd) {
14046   int res;
14047   char *path;
14048 
14049   CHECK_ARGS(cmd, 1);
14050   CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL);
14051 
14052   path = cmd->argv[1];
14053 
14054   PRIVS_ROOT
14055   res = file_exists2(cmd->tmp_pool, path);
14056   PRIVS_RELINQUISH
14057 
14058   if (!res) {
14059     CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, "'", path, "' does not exist",
14060       NULL));
14061   }
14062 
14063   if (*path != '/') {
14064     CONF_ERROR(cmd, "parameter must be an absolute path");
14065   }
14066 
14067   add_config_param_str(cmd->argv[0], 1, path);
14068   return PR_HANDLED(cmd);
14069 }
14070 
14071 /* usage: TLSPreSharedKey name path */
14072 MODRET set_tlspresharedkey(cmd_rec *cmd) {
14073 #if defined(PSK_MAX_PSK_LEN)
14074   char *identity, *path;
14075   size_t identity_len, path_len;
14076 
14077   CHECK_ARGS(cmd, 2);
14078   CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL);
14079 
14080   identity = cmd->argv[1];
14081   path = cmd->argv[2];
14082 
14083   identity_len = strlen(identity);
14084   if (identity_len > PSK_MAX_IDENTITY_LEN) {
14085     char buf[32];
14086 
14087     memset(buf, '\0', sizeof(buf));
14088     pr_snprintf(buf, sizeof(buf)-1, "%u", (unsigned int) PSK_MAX_IDENTITY_LEN);
14089 
14090     CONF_ERROR(cmd, pstrcat(cmd->tmp_pool,
14091       "TLSPreSharedKey identity '", identity, "' exceed maximum length ",
14092       buf, path, NULL))
14093   }
14094 
14095   /* Ensure that the given path starts with "hex:", denoting the
14096    * format of the key at the given path.  Support for other formats, e.g.
14097    * bcrypt or somesuch, will be added later.
14098    */
14099   path_len = strlen(path);
14100   if (path_len < 5 ||
14101       strncmp(path, "hex:", 4) != 0) {
14102     CONF_ERROR(cmd, pstrcat(cmd->tmp_pool,
14103       "unsupported TLSPreSharedKey format: ", path, NULL))
14104   }
14105 
14106   (void) add_config_param_str(cmd->argv[0], 2, identity, path);
14107 #else
14108   pr_log_debug(DEBUG0,
14109     "%s is not supported by this build/version of OpenSSL, ignoring",
14110     (char *) cmd->argv[0]);
14111 #endif /* PSK_MAX_PSK_LEN */
14112 
14113   return PR_HANDLED(cmd);
14114 }
14115 
14116 /* usage: TLSProtocol version1 ... versionN */
14117 MODRET set_tlsprotocol(cmd_rec *cmd) {
14118   register unsigned int i;
14119   config_rec *c;
14120   unsigned int protocols = 0;
14121 
14122   if (cmd->argc-1 == 0) {
14123     CONF_ERROR(cmd, "wrong number of parameters");
14124   }
14125 
14126   CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL);
14127 
14128   if (strcasecmp(cmd->argv[1], "all") == 0) {
14129     /* We're in an additive/subtractive type of configuration. */
14130     protocols = TLS_PROTO_ALL;
14131 
14132     for (i = 2; i < cmd->argc; i++) {
14133       int disable = FALSE;
14134       char *proto_name;
14135 
14136       proto_name = cmd->argv[i];
14137 
14138       if (*proto_name == '+') {
14139         proto_name++;
14140 
14141       } else if (*proto_name == '-') {
14142         disable = TRUE;
14143         proto_name++;
14144 
14145       } else {
14146         /* Using the additive/subtractive approach requires a +/- prefix;
14147          * it's malformed without such prefaces.
14148          */
14149         CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, "missing required +/- prefix: ",
14150           proto_name, NULL));
14151       }
14152 
14153       if (strncasecmp(proto_name, "SSLv3", 6) == 0) {
14154         if (disable) {
14155           protocols &= ~TLS_PROTO_SSL_V3;
14156         } else {
14157           protocols |= TLS_PROTO_SSL_V3;
14158         }
14159 
14160       } else if (strncasecmp(proto_name, "TLSv1", 6) == 0 ||
14161                  strncasecmp(proto_name, "TLSv1.0", 8) == 0) {
14162         if (disable) {
14163           protocols &= ~TLS_PROTO_TLS_V1;
14164         } else {
14165           protocols |= TLS_PROTO_TLS_V1;
14166         }
14167 
14168       } else if (strncasecmp(proto_name, "TLSv1.1", 8) == 0) {
14169 #if OPENSSL_VERSION_NUMBER >= 0x10001000L
14170         if (disable) {
14171           protocols &= ~TLS_PROTO_TLS_V1_1;
14172         } else {
14173           protocols |= TLS_PROTO_TLS_V1_1;
14174         }
14175 #else
14176         CONF_ERROR(cmd, "Your OpenSSL installation does not support TLSv1.1");
14177 #endif /* OpenSSL 1.0.1 or later */
14178 
14179       } else if (strncasecmp(proto_name, "TLSv1.2", 8) == 0) {
14180 #if OPENSSL_VERSION_NUMBER >= 0x10001000L
14181         if (disable) {
14182           protocols &= ~TLS_PROTO_TLS_V1_2;
14183         } else {
14184           protocols |= TLS_PROTO_TLS_V1_2;
14185         }
14186 #else
14187         CONF_ERROR(cmd, "Your OpenSSL installation does not support TLSv1.2");
14188 #endif /* OpenSSL 1.0.1 or later */
14189 
14190       } else if (strncasecmp(proto_name, "TLSv1.3", 8) == 0) {
14191 #ifdef TLS1_3_VERSION
14192         if (disable) {
14193           protocols &= ~TLS_PROTO_TLS_V1_3;
14194         } else {
14195           protocols |= TLS_PROTO_TLS_V1_3;
14196         }
14197 #else
14198         CONF_ERROR(cmd, "Your OpenSSL installation does not support TLSv1.3");
14199 #endif /* OpenSSL 1.1.1 or later */
14200 
14201       } else {
14202         CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, "unknown protocol: '",
14203           cmd->argv[i], "'", NULL));
14204       }
14205     }
14206 
14207   } else {
14208     for (i = 1; i < cmd->argc; i++) {
14209       if (strncasecmp(cmd->argv[i], "SSLv23", 7) == 0) {
14210         protocols |= TLS_PROTO_SSL_V3;
14211         protocols |= TLS_PROTO_TLS_V1;
14212 #ifdef SSL_OP_NO_TLSv1_1
14213         protocols |= TLS_PROTO_TLS_V1_1;
14214 #endif
14215 #ifdef SSL_OP_NO_TLSv1_2
14216         protocols |= TLS_PROTO_TLS_V1_2;
14217 #endif
14218 #ifdef SSL_OP_NO_TLSv1_3
14219         protocols |= TLS_PROTO_TLS_V1_3;
14220 #endif
14221 
14222       } else if (strncasecmp(cmd->argv[i], "SSLv3", 6) == 0) {
14223         protocols |= TLS_PROTO_SSL_V3;
14224 
14225       } else if (strncasecmp(cmd->argv[i], "TLSv1", 6) == 0 ||
14226                  strncasecmp(cmd->argv[i], "TLSv1.0", 8) == 0) {
14227         protocols |= TLS_PROTO_TLS_V1;
14228 
14229       } else if (strncasecmp(cmd->argv[i], "TLSv1.1", 8) == 0) {
14230 #if OPENSSL_VERSION_NUMBER >= 0x10001000L
14231         protocols |= TLS_PROTO_TLS_V1_1;
14232 #else
14233         CONF_ERROR(cmd, "Your OpenSSL installation does not support TLSv1.1");
14234 #endif /* OpenSSL 1.0.1 or later */
14235 
14236       } else if (strncasecmp(cmd->argv[i], "TLSv1.2", 8) == 0) {
14237 #if OPENSSL_VERSION_NUMBER >= 0x10001000L
14238         protocols |= TLS_PROTO_TLS_V1_2;
14239 #else
14240         CONF_ERROR(cmd, "Your OpenSSL installation does not support TLSv1.2");
14241 #endif /* OpenSSL 1.0.1 or later */
14242 
14243       } else if (strncasecmp(cmd->argv[i], "TLSv1.3", 8) == 0) {
14244 #ifdef TLS1_3_VERSION
14245         protocols |= TLS_PROTO_TLS_V1_3;
14246 #else
14247         CONF_ERROR(cmd, "Your OpenSSL installation does not support TLSv1.3");
14248 #endif /* OpenSSL 1.1.1 or later */
14249 
14250       } else {
14251         CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, "unknown protocol: '",
14252           cmd->argv[i], "'", NULL));
14253       }
14254     }
14255   }
14256 
14257   c = add_config_param(cmd->argv[0], 1, NULL);
14258   c->argv[0] = palloc(c->pool, sizeof(unsigned int));
14259   *((unsigned int *) c->argv[0]) = protocols;
14260 
14261   return PR_HANDLED(cmd);
14262 }
14263 
14264 /* usage: TLSRandomSeed file */
14265 MODRET set_tlsrandseed(cmd_rec *cmd) {
14266   CHECK_ARGS(cmd, 1);
14267   CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL);
14268 
14269   add_config_param_str(cmd->argv[0], 1, cmd->argv[1]);
14270   return PR_HANDLED(cmd);
14271 }
14272 
14273 /* usage: TLSRenegotiate [ctrl nsecs] [data nbytes] */
14274 MODRET set_tlsrenegotiate(cmd_rec *cmd) {
14275 #if OPENSSL_VERSION_NUMBER > 0x000907000L
14276   register unsigned int i = 0;
14277   config_rec *c = NULL;
14278 
14279   if (cmd->argc-1 < 1 || cmd->argc-1 > 8)
14280     CONF_ERROR(cmd, "wrong number of parameters");
14281 
14282   CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL);
14283 
14284   if (strncasecmp(cmd->argv[1], "none", 5) == 0) {
14285     add_config_param(cmd->argv[0], 0);
14286     return PR_HANDLED(cmd);
14287   }
14288 
14289   c = add_config_param(cmd->argv[0], 4, NULL, NULL, NULL, NULL);
14290   c->argv[0] = pcalloc(c->pool, sizeof(int));
14291   *((int *) c->argv[0]) = 0;
14292   c->argv[1] = pcalloc(c->pool, sizeof(off_t));
14293   *((off_t *) c->argv[1]) = 0;
14294   c->argv[2] = pcalloc(c->pool, sizeof(int));
14295   *((int *) c->argv[2]) = 0;
14296   c->argv[3] = pcalloc(c->pool, sizeof(unsigned char));
14297   *((unsigned char *) c->argv[3]) = TRUE;
14298 
14299   for (i = 1; i < cmd->argc;) {
14300     if (strcmp(cmd->argv[i], "ctrl") == 0) {
14301       int secs = atoi(cmd->argv[i+1]);
14302 
14303       if (secs > 0) {
14304         *((int *) c->argv[0]) = secs;
14305 
14306       } else {
14307         CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, cmd->argv[i],
14308           " must be greater than zero: '", cmd->argv[i+1], "'", NULL));
14309       }
14310 
14311       i += 2;
14312 
14313     } else if (strcmp(cmd->argv[i], "data") == 0) {
14314       char *tmp = NULL;
14315       unsigned long kbytes = strtoul(cmd->argv[i+1], &tmp, 10);
14316 
14317       if (!(tmp && *tmp)) {
14318         *((off_t *) c->argv[1]) = (off_t) kbytes * 1024;
14319 
14320       } else {
14321         CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, cmd->argv[i],
14322           " must be greater than zero: '", cmd->argv[i+1], "'", NULL));
14323       }
14324 
14325       i += 2;
14326 
14327     } else if (strcmp(cmd->argv[i], "required") == 0) {
14328       int required;
14329 
14330       required = get_boolean(cmd, i+1);
14331       if (required != -1) {
14332         *((unsigned char *) c->argv[3]) = required;
14333 
14334       } else {
14335         CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, cmd->argv[i],
14336           " must be a Boolean value: '", cmd->argv[i+1], "'", NULL));
14337       }
14338 
14339       i += 2;
14340 
14341     } else if (strcmp(cmd->argv[i], "timeout") == 0) {
14342       int secs = atoi(cmd->argv[i+1]);
14343 
14344       if (secs > 0) {
14345         *((int *) c->argv[2]) = secs;
14346 
14347       } else {
14348         CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, cmd->argv[i],
14349           " must be greater than zero: '", cmd->argv[i+1], "'", NULL));
14350       }
14351 
14352       i += 2;
14353 
14354     } else {
14355       CONF_ERROR(cmd, pstrcat(cmd->tmp_pool,
14356         ": unknown TLSRenegotiate argument '", cmd->argv[i], "'", NULL));
14357     }
14358   }
14359 
14360   return PR_HANDLED(cmd);
14361 #else
14362   CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, " requires OpenSSL-0.9.7 or greater",
14363     NULL));
14364 #endif
14365 }
14366 
14367 /* usage: TLSRequired on|off|both|control|ctrl|[!]data|auth|auth+data */
14368 MODRET set_tlsrequired(cmd_rec *cmd) {
14369   int required = -1;
14370   int on_auth = 0, on_ctrl = 0, on_data = 0;
14371   config_rec *c = NULL;
14372 
14373   CHECK_ARGS(cmd, 1);
14374   CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL|CONF_ANON|CONF_DIR|
14375     CONF_DYNDIR);
14376 
14377   required = get_boolean(cmd, 1);
14378   if (required == -1) {
14379     if (strcmp(cmd->argv[1], "control") == 0 ||
14380         strcmp(cmd->argv[1], "ctrl") == 0) {
14381       on_auth = 1;
14382       on_ctrl = 1;
14383 
14384     } else if (strcmp(cmd->argv[1], "data") == 0) {
14385       on_data = 1;
14386 
14387     } else if (strcmp(cmd->argv[1], "!data") == 0) {
14388       on_data = -1;
14389 
14390     } else if (strcmp(cmd->argv[1], "both") == 0 ||
14391                strcmp(cmd->argv[1], "ctrl+data") == 0) {
14392       on_auth = 1;
14393       on_ctrl = 1;
14394       on_data = 1;
14395 
14396     } else if (strcmp(cmd->argv[1], "ctrl+!data") == 0) {
14397       on_auth = 1;
14398       on_ctrl = 1;
14399       on_data = -1;
14400 
14401     } else if (strcmp(cmd->argv[1], "auth") == 0) {
14402       on_auth = 1;
14403 
14404     } else if (strcmp(cmd->argv[1], "auth+data") == 0) {
14405       on_auth = 1;
14406       on_data = 1;
14407 
14408     } else if (strcmp(cmd->argv[1], "auth+!data") == 0) {
14409       on_auth = 1;
14410       on_data = -1;
14411 
14412     } else
14413       CONF_ERROR(cmd, "bad parameter");
14414 
14415   } else {
14416     if (required == TRUE) {
14417       on_auth = 1;
14418       on_ctrl = 1;
14419       on_data = 1;
14420     }
14421   }
14422 
14423   c = add_config_param(cmd->argv[0], 3, NULL, NULL, NULL);
14424   c->argv[0] = pcalloc(c->pool, sizeof(int));
14425   *((int *) c->argv[0]) = on_ctrl;
14426   c->argv[1] = pcalloc(c->pool, sizeof(int));
14427   *((int *) c->argv[1]) = on_data;
14428   c->argv[2] = pcalloc(c->pool, sizeof(int));
14429   *((int *) c->argv[2]) = on_auth;
14430 
14431   c->flags |= CF_MERGEDOWN;
14432 
14433   return PR_HANDLED(cmd);
14434 }
14435 
14436 /* usage: TLSRSACertificateFile file */
14437 MODRET set_tlsrsacertfile(cmd_rec *cmd) {
14438   char *path;
14439   const char *fingerprint, *errstr = NULL;
14440 
14441   CHECK_ARGS(cmd, 1);
14442   CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL);
14443 
14444   path = cmd->argv[1];
14445   if (*path != '/') {
14446     CONF_ERROR(cmd, "parameter must be an absolute path");
14447   }
14448 
14449   PRIVS_ROOT
14450   fingerprint = tls_get_fingerprint_from_file(cmd->tmp_pool, path, EVP_PKEY_RSA,
14451     &errstr);
14452   PRIVS_RELINQUISH
14453 
14454   if (fingerprint == NULL) {
14455     CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, "'", path,
14456       "' does not exist or does not contain a certificate", NULL));
14457   }
14458 
14459   add_config_param_str(cmd->argv[0], 2, path, fingerprint);
14460   return PR_HANDLED(cmd);
14461 }
14462 
14463 /* usage: TLSRSACertificateKeyFile file */
14464 MODRET set_tlsrsakeyfile(cmd_rec *cmd) {
14465   int res;
14466   char *path;
14467   SSL_CTX *ctx;
14468 
14469   CHECK_ARGS(cmd, 1);
14470   CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL);
14471 
14472   path = cmd->argv[1];
14473 
14474   PRIVS_ROOT
14475 
14476   ctx = SSL_CTX_new(SSLv23_server_method());
14477   if (ctx != NULL) {
14478     /* Note that the configured key file might be passphrase-protected.  We
14479      * do not necessarily want to prompt for the passphrase here, so if that
14480      * is the error returned, it is an expected condition, and indicates that
14481      * the encoding of the key is acceptable.
14482      */
14483     SSL_CTX_set_default_passwd_cb(ctx, tls_keyfile_check_cb);
14484 
14485     res = SSL_CTX_use_PrivateKey_file(ctx, path, X509_FILETYPE_PEM);
14486     if (res != 1) {
14487       unsigned long err_code;
14488 
14489       err_code = ERR_peek_error();
14490       switch (ERR_GET_REASON(err_code)) {
14491         /* These are "expected" error codes from working with
14492          * passphrase-protected keys.
14493          */
14494         case EVP_R_BAD_DECRYPT:
14495         case PEM_R_BAD_PASSWORD_READ:
14496           break;
14497 
14498         default: {
14499           PRIVS_RELINQUISH
14500 
14501           CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, "unable to use '", path, "': ",
14502             tls_get_errors2(cmd->tmp_pool), NULL));
14503         }
14504       }
14505     }
14506 
14507     SSL_CTX_free(ctx);
14508 
14509   } else {
14510     res = file_exists2(cmd->tmp_pool, path);
14511     if (res == FALSE) {
14512       PRIVS_RELINQUISH
14513       CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, "'", path, "' does not exist",
14514         NULL));
14515     }
14516   }
14517 
14518   PRIVS_RELINQUISH
14519 
14520   if (*path != '/') {
14521     CONF_ERROR(cmd, "parameter must be an absolute path");
14522   }
14523 
14524   add_config_param_str(cmd->argv[0], 1, path);
14525   return PR_HANDLED(cmd);
14526 }
14527 
14528 /* usage: TLSServerCipherPreference on|off */
14529 MODRET set_tlsservercipherpreference(cmd_rec *cmd) {
14530   int use_server_prefs = -1;
14531 #ifdef SSL_OP_CIPHER_SERVER_PREFERENCE
14532   config_rec *c = NULL;
14533 #endif
14534 
14535   CHECK_ARGS(cmd, 1);
14536   CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL);
14537 
14538   use_server_prefs = get_boolean(cmd, 1);
14539   if (use_server_prefs == -1) {
14540     CONF_ERROR(cmd, "expected Boolean parameter");
14541   }
14542 
14543 #ifdef SSL_OP_CIPHER_SERVER_PREFERENCE
14544   c = add_config_param(cmd->argv[0], 1, NULL);
14545   c->argv[0] = pcalloc(c->pool, sizeof(int));
14546   *((int *) c->argv[0]) = use_server_prefs;
14547 
14548 #else
14549   pr_log_debug(DEBUG0,
14550     "%s is not supported by this version of OpenSSL, ignoring",
14551     (char *) cmd->argv[0]);
14552 #endif /* SSL_OP_CIPHER_SERVER_PREFERENCE */
14553 
14554   return PR_HANDLED(cmd);
14555 }
14556 
14557 /* usage: TLSServerInfoFile path */
14558 MODRET set_tlsserverinfofile(cmd_rec *cmd) {
14559 #if !defined(OPENSSL_NO_TLSEXT) && OPENSSL_VERSION_NUMBER >= 0x10002000L
14560   char *path;
14561 
14562   CHECK_ARGS(cmd, 1);
14563   CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL);
14564 
14565   path = cmd->argv[1];
14566   if (*path != '/') {
14567     CONF_ERROR(cmd, "parameter must be an absolute path");
14568   }
14569 
14570   add_config_param_str(cmd->argv[0], 1, path);
14571 #else
14572   pr_log_debug(DEBUG0,
14573     "%s is not supported by this version of OpenSSL, ignoring",
14574     (char *) cmd->argv[0]);
14575 #endif /* OPENSSL_NO_TLSEXT */
14576 
14577   return PR_HANDLED(cmd);
14578 }
14579 
14580 /* usage: TLSSessionCache "off"|type:/info [timeout] */
14581 MODRET set_tlssessioncache(cmd_rec *cmd) {
14582   char *provider = NULL, *info = NULL;
14583   config_rec *c;
14584   long timeout = -1;
14585   int enabled = -1;
14586 
14587   if (cmd->argc < 2 ||
14588       cmd->argc > 3) {
14589     CONF_ERROR(cmd, "wrong number of parameters");
14590   }
14591 
14592   CHECK_CONF(cmd, CONF_ROOT);
14593 
14594   /* Has session caching been explicitly turned off? */
14595   enabled = get_boolean(cmd, 1);
14596   if (enabled != FALSE) {
14597     char *ptr;
14598 
14599     /* Separate the type/info parameter into pieces. */
14600     ptr = strchr(cmd->argv[1], ':');
14601     if (ptr == NULL) {
14602       CONF_ERROR(cmd, "badly formatted parameter");
14603     }
14604 
14605     *ptr = '\0';
14606     provider = cmd->argv[1];
14607     info = ptr + 1;
14608 
14609     /* Verify that the requested cache type has been registered. */
14610     if (strncmp(provider, "internal", 9) != 0) {
14611       if (tls_sess_cache_get_cache(provider) == NULL) {
14612         CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, "session cache type '",
14613         provider, "' not available", NULL));
14614       }
14615     }
14616   }
14617 
14618   if (cmd->argc == 3) {
14619     char *ptr = NULL;
14620 
14621     timeout = strtol(cmd->argv[2], &ptr, 10);
14622     if (ptr && *ptr) {
14623       CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, "'", cmd->argv[2],
14624         "' is not a valid timeout value", NULL));
14625     }
14626 
14627     if (timeout < 1) {
14628       CONF_ERROR(cmd, "timeout be greater than 1");
14629     }
14630 
14631   } else {
14632     /* Default timeout is 30 min (1800 secs). */
14633     timeout = 1800;
14634   }
14635 
14636   c = add_config_param(cmd->argv[0], 3, NULL, NULL, NULL);
14637   if (provider != NULL) {
14638     c->argv[0] = pstrdup(c->pool, provider);
14639   }
14640 
14641   if (info != NULL) {
14642     c->argv[1] = pstrdup(c->pool, info);
14643   }
14644 
14645   c->argv[2] = palloc(c->pool, sizeof(long));
14646   *((long *) c->argv[2]) = timeout;
14647 
14648   return PR_HANDLED(cmd);
14649 }
14650 
14651 /* usage: TLSSessionTicketKeys [age secs] [count num] */
14652 MODRET set_tlssessionticketkeys(cmd_rec *cmd) {
14653 #if defined(TLS_USE_SESSION_TICKETS)
14654   register unsigned int i;
14655   int max_age = -1, max_nkeys = -1;
14656   config_rec *c = NULL;
14657 
14658   if (cmd->argc != 3 &&
14659       cmd->argc != 5) {
14660     CONF_ERROR(cmd, "wrong number of parameters");
14661   }
14662 
14663   CHECK_CONF(cmd, CONF_ROOT);
14664 
14665   for (i = 1; i < cmd->argc; i++) {
14666     if (strcasecmp(cmd->argv[i], "age") == 0) {
14667       if (pr_str_get_duration(cmd->argv[i+1], &max_age) < 0) {
14668         CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, "error parsing age value '",
14669           cmd->argv[i+1], "': ", strerror(errno), NULL));
14670       }
14671 
14672       /* Note that we do not allow ticket keys to age out faster than 1
14673        * minute.  Less than that is a bit ridiculous, no?
14674        */
14675       if (max_age < 60) {
14676         CONF_ERROR(cmd, "max key age must be at least 60sec");
14677       }
14678 
14679       i++;
14680 
14681     } else if (strcasecmp(cmd->argv[i], "count") == 0) {
14682       max_nkeys = atoi(cmd->argv[i+1]);
14683       if (max_nkeys < 0) {
14684         CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, "error parsing count value '",
14685           cmd->argv[i+1], "': ", strerror(EINVAL), NULL));
14686       }
14687 
14688       /* Note that we need at least ONE ticket key for session tickets to
14689        * even work.
14690        */
14691       if (max_nkeys < 2) {
14692         CONF_ERROR(cmd, "max key count must be at least 1");
14693       }
14694 
14695       i++;
14696 
14697     } else {
14698       CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, "unknown parameter: ",
14699         (char *) cmd->argv[i], NULL));
14700     }
14701   }
14702 
14703   c = add_config_param(cmd->argv[0], 2, NULL, NULL);
14704   c->argv[0] = pcalloc(c->pool, sizeof(unsigned int));
14705   *((unsigned int *) c->argv[0]) = max_age;
14706   c->argv[1] = pcalloc(c->pool, sizeof(unsigned int));
14707   *((unsigned int *) c->argv[1]) = max_nkeys;
14708 
14709   return PR_HANDLED(cmd);
14710 #else
14711   CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, "The ", cmd->argv[0],
14712     " directive cannot be used on this system, as your OpenSSL version "
14713     "does not have session ticket support", NULL));
14714 #endif /* TLS_USE_SESSION_TICKETS */
14715 }
14716 
14717 /* usage; TLSSessionTickets on|off */
14718 MODRET set_tlssessiontickets(cmd_rec *cmd) {
14719 #if defined(TLS_USE_SESSION_TICKETS)
14720   int session_tickets = -1;
14721   config_rec *c = NULL;
14722 
14723   CHECK_ARGS(cmd, 1);
14724   CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL);
14725 
14726   session_tickets = get_boolean(cmd, 1);
14727   if (session_tickets == -1) {
14728     CONF_ERROR(cmd, "expected Boolean parameter");
14729   }
14730 
14731   c = add_config_param(cmd->argv[0], 1, NULL);
14732   c->argv[0] = pcalloc(c->pool, sizeof(int));
14733   *((int *) c->argv[0]) = session_tickets;
14734 
14735   return PR_HANDLED(cmd);
14736 #else
14737   CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, "The ", cmd->argv[0],
14738     " directive cannot be used on this system, as your OpenSSL version "
14739     "does not have session ticket support", NULL));
14740 #endif /* TLS_USE_SESSION_TICKETS */
14741 }
14742 
14743 /* usage: TLSStapling on|off */
14744 MODRET set_tlsstapling(cmd_rec *cmd) {
14745 #if defined(PR_USE_OPENSSL_OCSP)
14746   int stapling = -1;
14747   config_rec *c = NULL;
14748 
14749   CHECK_ARGS(cmd, 1);
14750   CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL);
14751 
14752   stapling = get_boolean(cmd, 1);
14753   if (stapling == -1) {
14754     CONF_ERROR(cmd, "expected Boolean parameter");
14755   }
14756 
14757   c = add_config_param(cmd->argv[0], 1, NULL);
14758   c->argv[0] = pcalloc(c->pool, sizeof(int));
14759   *((int *) c->argv[0]) = stapling;
14760 
14761   return PR_HANDLED(cmd);
14762 #else
14763   CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, "The ", cmd->argv[0],
14764     " directive cannot be used on this system, as your OpenSSL version "
14765     "does not have OCSP support", NULL));
14766 #endif /* PR_USE_OPENSSL_OCSP */
14767 }
14768 
14769 /* usage: TLSStaplingCache "off"|type:/info */
14770 MODRET set_tlsstaplingcache(cmd_rec *cmd) {
14771   char *provider = NULL, *info = NULL;
14772   config_rec *c;
14773   int enabled = -1;
14774 
14775   CHECK_ARGS(cmd, 1);
14776   CHECK_CONF(cmd, CONF_ROOT);
14777 
14778   /* Has OCSP response caching been explicitly turned off? */
14779   enabled = get_boolean(cmd, 1);
14780   if (enabled != FALSE) {
14781     char *ptr;
14782 
14783     /* Separate the type/info parameter into pieces. */
14784     ptr = strchr(cmd->argv[1], ':');
14785     if (ptr == NULL) {
14786       CONF_ERROR(cmd, "badly formatted parameter");
14787     }
14788 
14789     *ptr = '\0';
14790     provider = cmd->argv[1];
14791     info = ptr + 1;
14792 
14793     /* Verify that the requested cache type has been registered. */
14794     if (tls_ocsp_cache_get_cache(provider) == NULL) {
14795       CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, "OCSP stapling cache type '",
14796         provider, "' not available", NULL));
14797     }
14798   }
14799 
14800   c = add_config_param(cmd->argv[0], 2, NULL, NULL);
14801   if (provider != NULL) {
14802     c->argv[0] = pstrdup(c->pool, provider);
14803   }
14804 
14805   if (info != NULL) {
14806     c->argv[1] = pstrdup(c->pool, info);
14807   }
14808 
14809   return PR_HANDLED(cmd);
14810 }
14811 
14812 /* usage: TLSStaplingOptions opt1 opt2 ... */
14813 MODRET set_tlsstaplingoptions(cmd_rec *cmd) {
14814 #if defined(PR_USE_OPENSSL_OCSP)
14815   config_rec *c = NULL;
14816   register unsigned int i = 0;
14817   unsigned long opts = 0UL;
14818 
14819   if (cmd->argc-1 == 0) {
14820     CONF_ERROR(cmd, "wrong number of parameters");
14821   }
14822 
14823   CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL);
14824 
14825   c = add_config_param(cmd->argv[0], 1, NULL);
14826 
14827   for (i = 1; i < cmd->argc; i++) {
14828     if (strcmp(cmd->argv[i], "NoNonce") == 0) {
14829       opts |= TLS_STAPLING_OPT_NO_NONCE;
14830 
14831     } else if (strcmp(cmd->argv[i], "NoVerify") == 0) {
14832       opts |= TLS_STAPLING_OPT_NO_VERIFY;
14833 
14834     } else if (strcmp(cmd->argv[i], "NoFakeTryLater") == 0) {
14835       opts |= TLS_STAPLING_OPT_NO_FAKE_TRY_LATER;
14836 
14837     } else {
14838       CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, ": unknown TLSStaplingOption '",
14839         cmd->argv[i], "'", NULL));
14840     }
14841   }
14842 
14843   c->argv[0] = pcalloc(c->pool, sizeof(unsigned long));
14844   *((unsigned long *) c->argv[0]) = opts;
14845 #endif /* PR_USE_OPENSSL_OCSP */
14846 
14847   return PR_HANDLED(cmd);
14848 }
14849 
14850 /* usage: TLSStaplingResponder url */
14851 MODRET set_tlsstaplingresponder(cmd_rec *cmd) {
14852 #if defined(PR_USE_OPENSSL_OCSP)
14853   char *host = NULL, *port = NULL, *uri = NULL, *url;
14854   int use_ssl = 0;
14855 
14856   CHECK_ARGS(cmd, 1);
14857   CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL);
14858 
14859   url = cmd->argv[1];
14860   if (OCSP_parse_url(url, &host, &port, &uri, &use_ssl) != 1) {
14861     CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, "error parsing URL '", url, "': ",
14862       tls_get_errors(), NULL));
14863   }
14864 
14865   OPENSSL_free(host);
14866   OPENSSL_free(port);
14867   OPENSSL_free(uri);
14868 
14869   add_config_param_str(cmd->argv[0], 1, url);
14870 #endif /* PR_USE_OPENSSL_OCSP */
14871 
14872   return PR_HANDLED(cmd);
14873 }
14874 
14875 /* usage: TLSStaplingTimeout secs */
14876 MODRET set_tlsstaplingtimeout(cmd_rec *cmd) {
14877   int timeout = -1;
14878   config_rec *c = NULL;
14879 
14880   CHECK_ARGS(cmd, 1);
14881   CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL);
14882 
14883   if (pr_str_get_duration(cmd->argv[1], &timeout) < 0) {
14884     CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, "error parsing timeout value '",
14885       cmd->argv[1], "': ", strerror(errno), NULL));
14886   }
14887 
14888   c = add_config_param(cmd->argv[0], 1, NULL);
14889   c->argv[0] = pcalloc(c->pool, sizeof(unsigned int));
14890   *((unsigned int *) c->argv[0]) = timeout;
14891 
14892   return PR_HANDLED(cmd);
14893 }
14894 
14895 /* usage: TLSTimeoutHandshake secs */
14896 MODRET set_tlstimeouthandshake(cmd_rec *cmd) {
14897   int timeout = -1;
14898   config_rec *c = NULL;
14899 
14900   CHECK_ARGS(cmd, 1);
14901   CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL);
14902 
14903   if (pr_str_get_duration(cmd->argv[1], &timeout) < 0) {
14904     CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, "error parsing timeout value '",
14905       cmd->argv[1], "': ", strerror(errno), NULL));
14906   }
14907 
14908   c = add_config_param(cmd->argv[0], 1, NULL);
14909   c->argv[0] = pcalloc(c->pool, sizeof(unsigned int));
14910   *((unsigned int *) c->argv[0]) = timeout;
14911 
14912   return PR_HANDLED(cmd);
14913 }
14914 
14915 /* usage: TLSUserName CommonName|EmailSubjAltName|custom-oid */
14916 MODRET set_tlsusername(cmd_rec *cmd) {
14917   CHECK_ARGS(cmd, 1);
14918   CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL);
14919 
14920   /* Make sure the parameter is either "CommonName",
14921    * "EmailSubjAltName", or a custom OID.
14922    */
14923   if (strcmp(cmd->argv[1], "CommonName") != 0 &&
14924       strcmp(cmd->argv[1], "EmailSubjAltName") != 0) {
14925     register unsigned int i;
14926     char *param;
14927     size_t param_len;
14928 
14929     param = cmd->argv[1];
14930     param_len = strlen(param);
14931     for (i = 0; i < param_len; i++) {
14932       if (!PR_ISDIGIT(param[i]) &&
14933           param[i] != '.') {
14934         CONF_ERROR(cmd, "badly formatted OID parameter");
14935       }
14936     }
14937   }
14938 
14939   add_config_param_str(cmd->argv[0], 1, cmd->argv[1]);
14940   return PR_HANDLED(cmd);
14941 }
14942 
14943 /* usage: TLSVerifyClient on|off|optional */
14944 MODRET set_tlsverifyclient(cmd_rec *cmd) {
14945   int verify_client = -1;
14946   config_rec *c = NULL;
14947 
14948   CHECK_ARGS(cmd, 1);
14949   CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL);
14950 
14951   verify_client = get_boolean(cmd, 1);
14952   if (verify_client == -1) {
14953     if (strcasecmp(cmd->argv[1], "optional") != 0) {
14954       CONF_ERROR(cmd, "expected Boolean parameter");
14955     }
14956 
14957     verify_client = 2;
14958   }
14959 
14960   c = add_config_param(cmd->argv[0], 1, NULL);
14961   c->argv[0] = pcalloc(c->pool, sizeof(unsigned char));
14962   *((unsigned char *) c->argv[0]) = verify_client;
14963 
14964   return PR_HANDLED(cmd);
14965 }
14966 
14967 /* usage: TLSVerifyDepth depth */
14968 MODRET set_tlsverifydepth(cmd_rec *cmd) {
14969   int depth = -1;
14970   config_rec *c = NULL;
14971 
14972   CHECK_ARGS(cmd, 1);
14973   CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL);
14974 
14975   depth = atoi(cmd->argv[1]);
14976   if (depth < 0) {
14977     CONF_ERROR(cmd, "depth must be zero or greater");
14978   }
14979 
14980   c = add_config_param(cmd->argv[0], 1, NULL);
14981   c->argv[0] = pcalloc(c->pool, sizeof(int));
14982   *((int *) c->argv[0]) = depth;
14983 
14984   return PR_HANDLED(cmd);
14985 }
14986 
14987 /* usage: TLSVerifyOrder mech1 ... */
14988 MODRET set_tlsverifyorder(cmd_rec *cmd) {
14989   register unsigned int i = 0;
14990   config_rec *c = NULL;
14991 
14992   /* We only support two client cert verification mechanisms at the moment:
14993    * CRLs and OCSP.
14994    */
14995   if (cmd->argc-1 < 1 ||
14996       cmd->argc-1 > 2) {
14997     CONF_ERROR(cmd, "wrong number of parameters");
14998   }
14999 
15000   CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL);
15001 
15002   for (i = 1; i < cmd->argc; i++) {
15003     char *mech = cmd->argv[i];
15004 
15005     if (strncasecmp(mech, "crl", 4) != 0
15006 #if OPENSSL_VERSION_NUMBER > 0x000907000L
15007         && strncasecmp(mech, "ocsp", 5) != 0) {
15008 #else
15009         ) {
15010 #endif
15011       CONF_ERROR(cmd, pstrcat(cmd->tmp_pool,
15012         "unsupported verification mechanism '", mech, "' requested", NULL));
15013     }
15014   }
15015 
15016   c = add_config_param(cmd->argv[0], cmd->argc-1, NULL, NULL);
15017   for (i = 1; i < cmd->argc; i++) {
15018     char *mech = cmd->argv[i];
15019 
15020     if (strncasecmp(mech, "crl", 4) == 0) {
15021       c->argv[i-1] = pstrdup(c->pool, "crl");
15022 
15023 #if OPENSSL_VERSION_NUMBER > 0x000907000L
15024     } else if (strncasecmp(mech, "ocsp", 5) == 0) {
15025       c->argv[i-1] = pstrdup(c->pool, "ocsp");
15026 #endif
15027     }
15028   }
15029 
15030   return PR_HANDLED(cmd);
15031 }
15032 
15033 /* usage: TLSVerifyServer on|NoReverseDNS|off */
15034 MODRET set_tlsverifyserver(cmd_rec *cmd) {
15035   int setting = -1;
15036   config_rec *c = NULL;
15037 
15038   CHECK_ARGS(cmd, 1);
15039   CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL);
15040 
15041   setting = get_boolean(cmd, 1);
15042   if (setting == -1) {
15043     if (strcasecmp(cmd->argv[1], "NoReverseDNS") != 0) {
15044       CONF_ERROR(cmd, "expected Boolean parameter");
15045     }
15046 
15047     setting = 2;
15048   }
15049 
15050   c = add_config_param(cmd->argv[0], 1, NULL);
15051   c->argv[0] = pcalloc(c->pool, sizeof(int));
15052   *((int *) c->argv[0]) = setting;
15053 
15054   return PR_HANDLED(cmd);
15055 }
15056 
15057 /* Event handlers
15058  */
15059 
15060 #if defined(PR_SHARED_MODULE)
15061 static void tls_mod_unload_ev(const void *event_data, void *user_data) {
15062   if (strcmp("mod_tls.c", (const char *) event_data) == 0) {
15063     /* Unregister ourselves from all events. */
15064     pr_event_unregister(&tls_module, NULL, NULL);
15065 
15066     pr_timer_remove(-1, &tls_module);
15067 # if defined(TLS_USE_SESSION_TICKETS)
15068     scrub_ticket_keys();
15069 # endif /* TLS_USE_SESSION_TICKETS */
15070 
15071 # ifdef PR_USE_CTRLS
15072     /* Unregister any control actions. */
15073     pr_ctrls_unregister(&tls_module, "tls");
15074 
15075     destroy_pool(tls_act_pool);
15076     tls_act_pool = NULL;
15077 # endif /* PR_USE_CTRLS */
15078 
15079     /* Cleanup the OpenSSL stuff. */
15080     tls_cleanup(0);
15081 
15082     /* Unregister our NetIO handler for the control channel. */
15083     pr_unregister_netio(PR_NETIO_STRM_CTRL);
15084 
15085     if (tls_ctrl_netio) {
15086       destroy_pool(tls_ctrl_netio->pool);
15087       tls_ctrl_netio = NULL;
15088     }
15089 
15090     if (tls_data_netio) {
15091       destroy_pool(tls_data_netio->pool);
15092       tls_data_netio = NULL;
15093     }
15094 
15095     close(tls_logfd);
15096     tls_logfd = -1;
15097   }
15098 }
15099 #endif /* PR_SHARED_MODULE */
15100 
15101 static void tls_sess_reinit_ev(const void *event_data, void *user_data) {
15102   int res;
15103 
15104   /* If the client has already established a TLS session, then do nothing;
15105    * we cannot easily force a re-handshake using different credentials very
15106    * easily. (Right?)
15107    */
15108   if (session.rfc2228_mech != NULL) {
15109     pr_trace_msg(trace_channel, 17,
15110       "ignored 'core.session-reinit' event due to existing SSL session");
15111     return;
15112   }
15113 
15114   /* A HOST command changed the main_server pointer; reinitialize ourselves. */
15115 
15116   pr_event_unregister(&tls_module, "core.exit", tls_exit_ev);
15117   pr_event_unregister(&tls_module, "core.session-reinit", tls_sess_reinit_ev);
15118 
15119   tls_reset_state();
15120 
15121 /* XXX How to indicate, to sess_init. to NOT re-register the following event
15122  * listeners?
15123  *
15124  *
15125  * XXX How to indicate, to sess_init, to NOT re-add the pr_feat_add TLS
15126  * features.  Same for TLS HELP stuff.
15127  * ANSWER: Add unit tests for Feature API, Help API for adding duplicates;
15128  * ensure APIs detect and ignore such duplicates.
15129  */
15130 
15131   res = tls_sess_init();
15132   if (res < 0) {
15133     pr_session_disconnect(&tls_module, PR_SESS_DISCONNECT_SESSION_INIT_FAILED,
15134       NULL);
15135   }
15136 }
15137 
15138 /* Daemon PID */
15139 extern pid_t mpid;
15140 
15141 static void tls_shutdown_ev(const void *event_data, void *user_data) {
15142   if (mpid == getpid()) {
15143     tls_scrub_pkeys();
15144 #if defined(TLS_USE_SESSION_TICKETS)
15145     scrub_ticket_keys();
15146 #endif /* TLS_USE_SESSION_TICKETS */
15147     destroy_pool(tls_pool);
15148     tls_pool = NULL;
15149   }
15150 
15151   /* Write out a new RandomSeed file, for use later. */
15152   if (tls_rand_file) {
15153     int res;
15154 
15155     res = RAND_write_file(tls_rand_file);
15156     if (res < 0) {
15157       pr_log_pri(PR_LOG_WARNING, MOD_TLS_VERSION
15158         ": error writing PRNG seed data to '%s': %s", tls_rand_file,
15159         tls_get_errors());
15160 
15161     } else {
15162       pr_log_debug(DEBUG2, MOD_TLS_VERSION
15163         ": wrote %d bytes of PRNG seed data to '%s'", res, tls_rand_file);
15164     }
15165   }
15166 
15167   if (ssl_ctx != NULL) {
15168     SSL_CTX_free(ssl_ctx);
15169     ssl_ctx = NULL;
15170   }
15171 
15172   RAND_cleanup();
15173 }
15174 
15175 static void tls_restart_ev(const void *event_data, void *user_data) {
15176 #ifdef PR_USE_CTRLS
15177   register unsigned int i;
15178 #endif /* PR_USE_CTRLS */
15179 
15180   /* Note: We SHOULD scrub all of the mlock'd passphrases from memory here.
15181    * However, doing so would require that some outside agency, such as
15182    * a TLSPassPhraseProvider, provide those passphrases again.  And some
15183    * sites deem such providers insecure, but do have servers restarted due
15184    * to e.g. log rotation, without changing the passphrases/certs.  For
15185    * such sites, then, we will opportunistically scrub the pkeys later,
15186    * during the phase where such passphrases are obtained as needed;
15187    * see Bug#4260.
15188    */
15189 
15190 #ifdef PR_USE_CTRLS
15191   if (tls_act_pool != NULL) {
15192     destroy_pool(tls_act_pool);
15193     tls_act_pool = NULL;
15194   }
15195 
15196   tls_act_pool = make_sub_pool(permanent_pool);
15197   pr_pool_tag(tls_act_pool, "TLS Controls Pool");
15198 
15199   /* Re-create the controls ACLs. */
15200   for (i = 0; tls_acttab[i].act_action; i++) {
15201     tls_acttab[i].act_acl = palloc(tls_act_pool, sizeof(ctrls_acl_t));
15202     pr_ctrls_init_acl(tls_acttab[i].act_acl);
15203   }
15204 #endif /* PR_USE_CTRLS */
15205 
15206   tls_closelog();
15207 }
15208 
15209 static void tls_exit_ev(const void *event_data, void *user_data) {
15210 
15211   if (ssl_ctx != NULL) {
15212     time_t now;
15213 
15214     /* Help out with the TLS session cache grooming by flushing any
15215      * expired sessions out right now.  The client is closing its
15216      * connection to us anyway, so some additional latency here shouldn't
15217      * be noticed.  Right?
15218      */
15219     now = time(NULL);
15220     SSL_CTX_flush_sessions(ssl_ctx, (long) now);
15221   }
15222 
15223   /* If diags are enabled, log some OpenSSL stats. */
15224   if (ssl_ctx != NULL &&
15225       (tls_opts & TLS_OPT_ENABLE_DIAGS)) {
15226     long res;
15227 
15228     res = SSL_CTX_sess_accept(ssl_ctx);
15229     tls_log("[stat]: SSL/TLS sessions attempted: %ld", res);
15230 
15231     res = SSL_CTX_sess_accept_good(ssl_ctx);
15232     tls_log("[stat]: SSL/TLS sessions established: %ld", res);
15233 
15234     res = SSL_CTX_sess_accept_renegotiate(ssl_ctx);
15235     tls_log("[stat]: SSL/TLS sessions renegotiated: %ld", res);
15236 
15237     res = SSL_CTX_sess_hits(ssl_ctx);
15238     tls_log("[stat]: SSL/TLS sessions resumed: %ld", res);
15239 
15240     res = SSL_CTX_sess_number(ssl_ctx);
15241     tls_log("[stat]: SSL/TLS sessions in cache: %ld", res);
15242 
15243     res = SSL_CTX_sess_cb_hits(ssl_ctx);
15244     tls_log("[stat]: SSL/TLS session cache hits: %ld", res);
15245 
15246     res = SSL_CTX_sess_misses(ssl_ctx);
15247     tls_log("[stat]: SSL/TLS session cache misses: %ld", res);
15248 
15249     res = SSL_CTX_sess_timeouts(ssl_ctx);
15250     tls_log("[stat]: SSL/TLS session cache timeouts: %ld", res);
15251 
15252     res = SSL_CTX_sess_cache_full(ssl_ctx);
15253     tls_log("[stat]: SSL/TLS session cache size exceeded: %ld", res);
15254   }
15255 
15256   if (tls_sni_sess_tab != NULL) {
15257     (void) pr_table_empty(tls_sni_sess_tab);
15258     (void) pr_table_free(tls_sni_sess_tab);
15259     tls_sni_sess_tab = NULL;
15260   }
15261 
15262   if (tls_pkey != NULL) {
15263     tls_scrub_pkey(tls_pkey);
15264     tls_pkey = NULL;
15265   }
15266 
15267   /* OpenSSL cleanup */
15268   tls_cleanup(0);
15269 
15270   /* Done with the NetIO objects.  Note that we only really need to
15271    * destroy the data channel NetIO object; the control channel NetIO
15272    * object is allocated out of the permanent pool, in the daemon process,
15273    * and thus we have a read-only copy.
15274    */
15275 
15276   if (tls_ctrl_netio) {
15277     pr_unregister_netio(PR_NETIO_STRM_CTRL);
15278     destroy_pool(tls_ctrl_netio->pool);
15279     tls_ctrl_netio = NULL;
15280   }
15281 
15282   if (tls_data_netio) {
15283     pr_unregister_netio(PR_NETIO_STRM_DATA);
15284     destroy_pool(tls_data_netio->pool);
15285     tls_data_netio = NULL;
15286   }
15287 
15288   if (mpid != getpid()) {
15289     tls_scrub_pkeys();
15290   }
15291 
15292   tls_closelog();
15293   return;
15294 }
15295 
15296 static void tls_timeout_ev(const void *event_data, void *user_data) {
15297 
15298   if (session.c &&
15299       ctrl_ssl != NULL &&
15300       (tls_flags & TLS_SESS_ON_CTRL)) {
15301     /* Try to properly close the TLS session down on the control channel,
15302      * if there is one.
15303      */
15304     tls_end_sess(ctrl_ssl, session.c, 0);
15305     pr_table_remove(tls_ctrl_rd_nstrm->notes, TLS_NETIO_NOTE, NULL);
15306     pr_table_remove(tls_ctrl_wr_nstrm->notes, TLS_NETIO_NOTE, NULL);
15307     ctrl_ssl = NULL;
15308   }
15309 }
15310 
15311 static tls_pkey_t *tls_find_pkey(server_rec *s, int flags) {
15312   tls_pkey_t *k, *pkey = NULL;
15313 
15314   for (k = tls_pkey_list; k; k = k->next) {
15315     if (k->sid == s->sid) {
15316       switch (flags) {
15317         case TLS_PASSPHRASE_FL_RSA_KEY:
15318           if (k->rsa_pkey != NULL) {
15319             pkey = k;
15320           }
15321           break;
15322 
15323         case TLS_PASSPHRASE_FL_DSA_KEY:
15324           if (k->dsa_pkey != NULL) {
15325             pkey = k;
15326           }
15327           break;
15328 
15329         case TLS_PASSPHRASE_FL_EC_KEY:
15330 #ifdef PR_USE_OPENSSL_ECC
15331           if (k->ec_pkey != NULL) {
15332             pkey = k;
15333           }
15334 #endif /* PR_USE_OPENSSL_ECC */
15335           break;
15336 
15337         case TLS_PASSPHRASE_FL_PKCS12_PASSWD:
15338           if (k->pkcs12_passwd != NULL) {
15339             pkey = k;
15340           }
15341           break;
15342 
15343         default:
15344           break;
15345       }
15346 
15347       if (pkey != NULL) {
15348         break;
15349       }
15350     }
15351   }
15352 
15353   return pkey;
15354 }
15355 
15356 static tls_pkey_t *tls_get_key_passphrase(server_rec *s, const char *path,
15357     int flags) {
15358   int res, *pass_len = NULL;
15359   tls_pkey_t *k = NULL;
15360   const char *key_type = "unsupported";
15361   char buf[256], **key_data = NULL;
15362   void **key_ptr = NULL;
15363 
15364   switch (flags) {
15365     case TLS_PASSPHRASE_FL_RSA_KEY:
15366       key_type = "RSA";
15367       break;
15368 
15369     case TLS_PASSPHRASE_FL_DSA_KEY:
15370       key_type = "DSA";
15371       break;
15372 
15373     case TLS_PASSPHRASE_FL_EC_KEY:
15374       key_type = "EC";
15375       break;
15376 
15377     case TLS_PASSPHRASE_FL_PKCS12_PASSWD:
15378       key_type = "PKCS12";
15379       break;
15380 
15381     default:
15382       errno = EINVAL;
15383       return NULL;
15384   }
15385 
15386   pr_trace_msg(trace_channel, 14,
15387     "obtaining passphrase/password for %s cert for path %s", key_type, path);
15388 
15389   /* First see if we have an existing (and usable!) passphrase already
15390    * stored for this server/key type/path.
15391    */
15392   k = tls_find_pkey(s, flags);
15393   if (k != NULL) {
15394     /* Remove the key from the list; we will be adding this key, or another
15395      * one, back to the list in its place.
15396      */
15397     tls_remove_pkey(k);
15398 
15399     pr_trace_msg(trace_channel, 19,
15400       "FOUND existing %s pkey found for server ID %u (path %s)", key_type,
15401       s->sid, k->path);
15402 
15403     /* If this key is for the same path, consider it usable. */
15404     if (strcmp(path, k->path) == 0) {
15405       pr_trace_msg(trace_channel, 14,
15406         "reusing stored %s for %s certificate from path '%s'",
15407         flags != TLS_PASSPHRASE_FL_PKCS12_PASSWD ? "passphrase" : "password",
15408         key_type, path);
15409       return k;
15410     }
15411 
15412     /* Not for the same path?  Consider this key stale, and scrub it. */
15413     tls_scrub_pkey(k);
15414   }
15415 
15416   if (k == NULL) {
15417     pool *key_pool;
15418 
15419     key_pool = make_sub_pool(tls_pool);
15420     pr_pool_tag(key_pool, "Private Key Pool");
15421 
15422     k = pcalloc(key_pool, sizeof(tls_pkey_t));
15423     k->pool = key_pool;
15424   }
15425 
15426   k->pkeysz = PEM_BUFSIZE;
15427 
15428   switch (flags) {
15429     case TLS_PASSPHRASE_FL_RSA_KEY:
15430       key_data = &(k->rsa_pkey);
15431       key_ptr = &(k->rsa_pkey_ptr);
15432       pass_len = &(k->rsa_passlen);
15433       break;
15434 
15435     case TLS_PASSPHRASE_FL_DSA_KEY:
15436       key_data = &(k->dsa_pkey);
15437       key_ptr = &(k->dsa_pkey_ptr);
15438       pass_len = &(k->dsa_passlen);
15439       break;
15440 
15441     case TLS_PASSPHRASE_FL_EC_KEY:
15442 #ifdef PR_USE_OPENSSL_ECC
15443       key_data = &(k->ec_pkey);
15444       key_ptr = &(k->ec_pkey_ptr);
15445       pass_len = &(k->ec_passlen);
15446 #endif /* PR_USE_OPENSSL_ECC */
15447       break;
15448 
15449     case TLS_PASSPHRASE_FL_PKCS12_PASSWD:
15450       key_data = &(k->pkcs12_passwd);
15451       key_ptr = &(k->pkcs12_passwd_ptr);
15452       pass_len = &(k->pkcs12_passlen);
15453       break;
15454 
15455     default:
15456       errno = EINVAL;
15457       return NULL;
15458   }
15459 
15460   res = pr_snprintf(buf, sizeof(buf)-1, "%s %s for the %s#%d (%s) server: ",
15461     key_type, flags != TLS_PASSPHRASE_FL_PKCS12_PASSWD ? "key" : "password",
15462     pr_netaddr_get_ipstr(s->addr), s->ServerPort, s->ServerName);
15463   buf[res] = '\0';
15464   buf[sizeof(buf)-1] = '\0';
15465 
15466   *key_data = tls_get_page(PEM_BUFSIZE, key_ptr);
15467   if (*key_data == NULL) {
15468     pr_log_pri(PR_LOG_ALERT, MOD_TLS_VERSION ": Out of memory!");
15469     pr_session_disconnect(&tls_module, PR_SESS_DISCONNECT_NOMEM, NULL);
15470   }
15471 
15472   res = tls_get_passphrase(s, path, buf, *key_data, k->pkeysz-1, flags);
15473   if (res < 0) {
15474     const char *errors;
15475 
15476     errors = tls_get_errors();
15477     if (errors == NULL) {
15478       errors = "Not provided";
15479     }
15480 
15481     pr_trace_msg(trace_channel, 1, "error reading %s %s: %s", key_type,
15482       flags != TLS_PASSPHRASE_FL_PKCS12_PASSWD ? "passphrase" : "password",
15483       errors);
15484     pr_log_debug(DEBUG0, MOD_TLS_VERSION ": error reading %s %s: %s", key_type,
15485       flags != TLS_PASSPHRASE_FL_PKCS12_PASSWD ? "passphrase" : "password",
15486       errors);
15487 
15488     pr_log_pri(PR_LOG_ERR, MOD_TLS_VERSION
15489       ": unable to use %s certificate %sin '%s', exiting", key_type,
15490       flags != TLS_PASSPHRASE_FL_PKCS12_PASSWD ? "key " : "", path);
15491     pr_session_disconnect(&tls_module, PR_SESS_DISCONNECT_BY_APPLICATION, NULL);
15492   }
15493 
15494   *pass_len = res;
15495   k->path = strdup(path);
15496   k->sid = s->sid;
15497 
15498   return k;
15499 }
15500 
15501 static void tls_get_passphrases(void) {
15502   server_rec *s = NULL;
15503 
15504   for (s = (server_rec *) server_list->xas_list; s; s = s->next) {
15505     config_rec *rsa = NULL, *dsa = NULL, *ec = NULL, *pkcs12 = NULL;
15506     tls_pkey_t *k = NULL;
15507     const char *path;
15508 
15509     /* Find any TLS*CertificateKeyFile directives.  If they aren't present,
15510      * look for TLS*CertificateFile directives (when appropriate).
15511      */
15512     rsa = find_config(s->conf, CONF_PARAM, "TLSRSACertificateKeyFile", FALSE);
15513     if (rsa == NULL) {
15514       rsa = find_config(s->conf, CONF_PARAM, "TLSRSACertificateFile", FALSE);
15515     }
15516 
15517     dsa = find_config(s->conf, CONF_PARAM, "TLSDSACertificateKeyFile", FALSE);
15518     if (dsa == NULL) {
15519       dsa = find_config(s->conf, CONF_PARAM, "TLSDSACertificateFile", FALSE);
15520     }
15521 
15522     ec = find_config(s->conf, CONF_PARAM, "TLSECCertificateKeyFile", FALSE);
15523     if (ec == NULL) {
15524       ec = find_config(s->conf, CONF_PARAM, "TLSECCertificateFile", FALSE);
15525     }
15526 
15527     pkcs12 = find_config(s->conf, CONF_PARAM, "TLSPKCS12File", FALSE);
15528 
15529     if (rsa == NULL &&
15530         dsa == NULL &&
15531         ec == NULL &&
15532         pkcs12 == NULL) {
15533       continue;
15534     }
15535 
15536     if (rsa != NULL) {
15537       path = rsa->argv[0];
15538       k = tls_get_key_passphrase(s, path, TLS_PASSPHRASE_FL_RSA_KEY);
15539     }
15540 
15541     if (dsa != NULL) {
15542       path = dsa->argv[0];
15543       k = tls_get_key_passphrase(s, path, TLS_PASSPHRASE_FL_DSA_KEY);
15544     }
15545 
15546 #ifdef PR_USE_OPENSSL_ECC
15547     if (ec != NULL) {
15548       path = ec->argv[0];
15549       k = tls_get_key_passphrase(s, path, TLS_PASSPHRASE_FL_EC_KEY);
15550     }
15551 #endif /* PR_USE_OPENSSL_ECC */
15552 
15553     if (pkcs12 != NULL) {
15554       path = pkcs12->argv[0];
15555       k = tls_get_key_passphrase(s, path, TLS_PASSPHRASE_FL_PKCS12_PASSWD);
15556     }
15557 
15558     k->next = tls_pkey_list;
15559     tls_pkey_list = k;
15560     tls_npkeys++;
15561   }
15562 }
15563 
15564 static void tls_postparse_ev(const void *event_data, void *user_data) {
15565   server_rec *s = NULL;
15566 
15567   /* Check for incompatible configurations.  For example, configuring:
15568    *
15569    *  TLSOptions AllowPerUser
15570    *  TLSRequired auth
15571    *
15572    * cannot be supported; the AllowPerUser means that the requirement of
15573    * SSL/TLS protection during authentication cannot be enforced.
15574    */
15575 
15576   for (s = (server_rec *) server_list->xas_list; s; s = s->next) {
15577     unsigned long *opts;
15578     config_rec *toplevel_c = NULL, *other_c = NULL;
15579     int toplevel_auth_requires_ssl = FALSE, other_auth_requires_ssl = TRUE;
15580 
15581     opts = get_param_ptr(s->conf, "TLSOptions", FALSE);
15582     if (opts == NULL) {
15583       continue;
15584     }
15585 
15586     /* The purpose of this check is to watch for configurations such as:
15587      *
15588      *  <IfModule mod_tls.c>
15589      *    ...
15590      *    TLSRequired on
15591      *    ...
15592      *    TLSOptions AllowPerUser
15593      *    ...
15594      *  </IfModule>
15595      *
15596      * This policy cannot be enforced; we cannot require use of SSL/TLS
15597      * (specifically at authentication time, when we do NOT know the user)
15598      * AND also allow per-user SSL/TLS requirements.  It's a chicken-and-egg
15599      * problem.
15600      *
15601      * However, we DO want to allow configurations like:
15602      *
15603      *  <IfModule mod_tls.c>
15604      *    ...
15605      *    TLSRequired on
15606      *    ...
15607      *    TLSOptions AllowPerUser
15608      *    ...
15609      *  </IfModule>
15610      *
15611      *  <Anonymous ...>
15612      *    ...
15613      *    <IfModule mod_tls.c>
15614      *      TLSRequired off
15615      *    </IfModule>
15616      *  </Anonymous>
15617      *
15618      * Thus this check is a bit tricky.  We look first in this server_rec's
15619      * config list for a top-level TLSRequired setting.  If it is 'on' AND
15620      * if the AllowPerUser TLSOption is set, AND we find no other TLSRequired
15621      * configs deeper in the server_rec whose value is 'off', then log the
15622      * error and quit.  Otherwise, let things proceed.
15623      *
15624      * If the mod_ifsession module is present, skip this check as well; we
15625      * will not be able to suss out any TLSRequired settings which are
15626      * lurking in mod_ifsession's grasp until authentication time.
15627      *
15628      * I still regret adding support for the AllowPerUser TLSOption.  Users
15629      * just cannot seem to wrap their minds around the fact that the user
15630      * is not known at the time when the SSL/TLS session is done.  Sigh.
15631      */
15632 
15633     if (pr_module_exists("mod_ifsession.c")) {
15634       continue;
15635     }
15636 
15637     toplevel_c = find_config(s->conf, CONF_PARAM, "TLSRequired", FALSE);
15638     if (toplevel_c) {
15639       toplevel_auth_requires_ssl = *((int *) toplevel_c->argv[2]);
15640     }
15641 
15642     /* If this toplevel TLSRequired value is 'off', then we need check no
15643      * further.
15644      */
15645     if (!toplevel_auth_requires_ssl) {
15646       continue;
15647     }
15648 
15649     /* This time, we recurse deeper into the server_rec's configs.
15650      * We need only pay attention to settings we find in the CONF_DIR or
15651      * CONF_ANON config contexts.  And we need only look until we find such
15652      * a setting does not require SSL/TLS during authentication, for at that
15653      * point we know it is not a misconfiguration.
15654      */
15655     find_config_set_top(NULL);
15656     other_c = find_config(s->conf, CONF_PARAM, "TLSRequired", TRUE);
15657     while (other_c) {
15658       int auth_requires_ssl;
15659 
15660       pr_signals_handle();
15661 
15662       if (other_c->parent == NULL ||
15663           (other_c->parent->config_type != CONF_ANON &&
15664            other_c->parent->config_type != CONF_DIR)) {
15665         /* Not what we're looking for; continue on. */
15666         other_c = find_config_next(other_c, other_c->next, CONF_PARAM,
15667           "TLSRequired", TRUE);
15668         continue;
15669       }
15670 
15671       auth_requires_ssl = *((int *) other_c->argv[2]);
15672       if (!auth_requires_ssl) {
15673         other_auth_requires_ssl = FALSE;
15674         break;
15675       }
15676 
15677       other_c = find_config_next(other_c, other_c->next, CONF_PARAM,
15678         "TLSRequired", TRUE);
15679     }
15680 
15681     if ((*opts & TLS_OPT_ALLOW_PER_USER) &&
15682         toplevel_auth_requires_ssl == TRUE &&
15683         other_auth_requires_ssl == TRUE) {
15684       pr_log_pri(PR_LOG_NOTICE, MOD_TLS_VERSION ": Server %s: cannot enforce "
15685         "both 'TLSRequired auth' and 'TLSOptions AllowPerUser' at the "
15686         "same time", s->ServerName);
15687       pr_session_disconnect(&tls_module, PR_SESS_DISCONNECT_BAD_CONFIG, NULL);
15688     }
15689   }
15690 
15691   if (ServerType == SERVER_INETD) {
15692     if (tls_set_fips() < 0) {
15693       pr_log_pri(PR_LOG_NOTICE, MOD_TLS_VERSION
15694         ": error initialising FIPS");
15695       pr_session_disconnect(&tls_module, PR_SESS_DISCONNECT_BY_APPLICATION,
15696         NULL);
15697     }
15698   }
15699 
15700   /* Initialize the OpenSSL context. */
15701   ssl_ctx = tls_init_ctx(main_server);
15702   if (ssl_ctx == NULL) {
15703     pr_log_pri(PR_LOG_NOTICE, MOD_TLS_VERSION
15704       ": error initialising OpenSSL context");
15705     pr_session_disconnect(&tls_module, PR_SESS_DISCONNECT_BY_APPLICATION, NULL);
15706   }
15707 
15708   if (tls_seed_prng() < 0) {
15709     pr_log_debug(DEBUG1, MOD_TLS_VERSION ": unable to properly seed PRNG");
15710   }
15711 
15712   tls_pool = make_sub_pool(permanent_pool);
15713   pr_pool_tag(tls_pool, MOD_TLS_VERSION);
15714 
15715   tls_ctx_set_session_cache(main_server, ssl_ctx);
15716   tls_ctx_set_stapling_cache(main_server, ssl_ctx);
15717   tls_ctx_set_session_id_context(main_server, ssl_ctx);
15718 
15719   /* We can only get the passphrases for certs once OpenSSL has been
15720    * initialized.
15721    */
15722   tls_get_passphrases();
15723 
15724   /* Clean up the pkey list, scrubbing any stale/irrelevant keys. */
15725   tls_clean_pkeys();
15726 
15727   /* Install our control channel NetIO handlers.  This is done here
15728    * specifically because we need to cache a pointer to the nstrm that
15729    * is passed to the open callback().  Ideally we'd only install our
15730    * custom NetIO handlers if the appropriate AUTH command was given.
15731    * But by then, the open() callback will have already been called, and
15732    * we will not have a chance to get that nstrm pointer.
15733    */
15734   tls_netio_install_ctrl();
15735 }
15736 
15737 static void tls_lookup_dh_params(server_rec *s) {
15738   config_rec *c;
15739 
15740   c = find_config(s->conf, CONF_PARAM, "TLSDHParamFile", FALSE);
15741   while (c != NULL) {
15742     const char *path;
15743     FILE *fp;
15744     int xerrno;
15745 
15746     pr_signals_handle();
15747 
15748     path = c->argv[0];
15749 
15750     /* Load the DH params from the file. */
15751     PRIVS_ROOT
15752     fp = fopen(path, "r");
15753     xerrno = errno;
15754     PRIVS_RELINQUISH
15755 
15756     if (fp != NULL) {
15757       DH *dh;
15758 
15759       dh = PEM_read_DHparams(fp, NULL, NULL, NULL);
15760       if (dh != NULL) {
15761         if (tls_tmp_dhs == NULL) {
15762           tls_tmp_dhs = make_array(session.pool, 1, sizeof(DH *));
15763         }
15764       }
15765 
15766       while (dh != NULL) {
15767         pr_signals_handle();
15768         *((DH **) push_array(tls_tmp_dhs)) = dh;
15769         dh = PEM_read_DHparams(fp, NULL, NULL, NULL);
15770       }
15771 
15772       fclose(fp);
15773 
15774     } else {
15775       pr_log_debug(DEBUG3, MOD_TLS_VERSION
15776         ": unable to open TLSDHParamFile '%s': %s", path, strerror(xerrno));
15777     }
15778 
15779     c = find_config_next(c, c->next, CONF_PARAM, "TLSDHParamFile", FALSE);
15780   }
15781 }
15782 
15783 static void tls_lookup_psks(server_rec *s) {
15784 #if defined(PSK_MAX_PSK_LEN)
15785   config_rec *c;
15786 
15787   if (tls_psks != NULL) {
15788     pr_table_empty(tls_psks);
15789     pr_table_free(tls_psks);
15790     tls_psks = NULL;
15791   }
15792 
15793   c = find_config(s->conf, CONF_PARAM, "TLSPreSharedKey", FALSE);
15794   while (c != NULL) {
15795     register int i;
15796     char key_buf[PR_TUNABLE_BUFFER_SIZE], *identity, *path;
15797     int fd, key_len, valid_hex = TRUE, res, xerrno;
15798     struct stat st;
15799     BIGNUM *bn = NULL;
15800 
15801     pr_signals_handle();
15802 
15803     identity = c->argv[0];
15804     path = c->argv[1];
15805 
15806     /* Advance past the "hex:" format prefix. */
15807     path += 4;
15808 
15809     PRIVS_ROOT
15810     fd = open(path, O_RDONLY);
15811     xerrno = errno;
15812     PRIVS_RELINQUISH
15813 
15814     if (fd < 0) {
15815       pr_log_debug(DEBUG2, MOD_TLS_VERSION
15816         ": error opening TLSPreSharedKey file '%s': %s", path,
15817         strerror(xerrno));
15818       c = find_config_next(c, c->next, CONF_PARAM, "TLSPreSharedKey", FALSE);
15819       continue;
15820     }
15821 
15822     if (fstat(fd, &st) < 0) {
15823       pr_log_debug(DEBUG2, MOD_TLS_VERSION
15824         ": error checking TLSPreSharedKey file '%s': %s", path,
15825         strerror(errno));
15826       (void) close(fd);
15827       c = find_config_next(c, c->next, CONF_PARAM, "TLSPreSharedKey", FALSE);
15828       continue;
15829     }
15830 
15831     /* Check on the permissions of the file; skip it if the permissions
15832      * are too permissive, e.g. file is world-read/writable.
15833      */
15834     if (st.st_mode & S_IROTH) {
15835       pr_log_debug(DEBUG2, MOD_TLS_VERSION
15836         ": unable to use TLSPreSharedKey file '%s': file is world-readable",
15837         path);
15838       (void) close(fd);
15839       c = find_config_next(c, c->next, CONF_PARAM, "TLSPreSharedKey", FALSE);
15840       continue;
15841     }
15842 
15843     if (st.st_mode & S_IWOTH) {
15844       pr_log_debug(DEBUG2, MOD_TLS_VERSION
15845         ": unable to use TLSPreSharedKey file '%s': file is world-writable",
15846         path);
15847       (void) close(fd);
15848       c = find_config_next(c, c->next, CONF_PARAM, "TLSPreSharedKey", FALSE);
15849       continue;
15850     }
15851 
15852     /* Read the entire key into memory. */
15853     key_len = read(fd, key_buf, sizeof(key_buf)-1);
15854     (void) close(fd);
15855 
15856     if (key_len < 0) {
15857       pr_log_debug(DEBUG2, MOD_TLS_VERSION
15858         ": error reading TLSPreSharedKey file '%s': %s", path,
15859         strerror(xerrno));
15860       c = find_config_next(c, c->next, CONF_PARAM, "TLSPreSharedKey", FALSE);
15861       continue;
15862 
15863     } else if (key_len == 0) {
15864       pr_log_debug(DEBUG2, MOD_TLS_VERSION
15865         ": read zero bytes from TLSPreSharedKey file '%s', ignoring", path);
15866       c = find_config_next(c, c->next, CONF_PARAM, "TLSPreSharedKey", FALSE);
15867       continue;
15868 
15869     } else if (key_len < TLS_MIN_PSK_LEN) {
15870       pr_log_debug(DEBUG2, MOD_TLS_VERSION
15871         ": read %d bytes from TLSPreSharedKey file '%s', need at least %d "
15872         "bytes of key data, ignoring", key_len, path, TLS_MIN_PSK_LEN);
15873       c = find_config_next(c, c->next, CONF_PARAM, "TLSPreSharedKey", FALSE);
15874       continue;
15875     }
15876 
15877     key_buf[key_len] = '\0';
15878     key_buf[sizeof(key_buf)-1] = '\0';
15879 
15880     /* Ignore any trailing newlines. */
15881     if (key_buf[key_len-1] == '\n') {
15882       key_buf[key_len-1] = '\0';
15883       key_len--;
15884     }
15885 
15886     if (key_buf[key_len-1] == '\r') {
15887       key_buf[key_len-1] = '\0';
15888       key_len--;
15889     }
15890 
15891     /* Ensure that it is all hex encoded data */
15892     for (i = 0; i < key_len; i++) {
15893       if (PR_ISXDIGIT((int) key_buf[i]) == 0) {
15894         valid_hex = FALSE;
15895         break;
15896       }
15897     }
15898 
15899     if (valid_hex == FALSE) {
15900       pr_log_debug(DEBUG2, MOD_TLS_VERSION
15901         ": unable to use '%s': not a hex number", key_buf);
15902       c = find_config_next(c, c->next, CONF_PARAM, "TLSPreSharedKey", FALSE);
15903       continue;
15904     }
15905 
15906     res = BN_hex2bn(&bn, key_buf);
15907     if (res == 0) {
15908       pr_log_debug(DEBUG2, MOD_TLS_VERSION
15909         ": failed to convert '%s' to BIGNUM: %s", key_buf,
15910         tls_get_errors());
15911 
15912       if (bn != NULL) {
15913         BN_free(bn);
15914       }
15915 
15916       c = find_config_next(c, c->next, CONF_PARAM, "TLSPreSharedKey", FALSE);
15917       continue;
15918     }
15919 
15920     if (tls_psks == NULL) {
15921       tls_psks = pr_table_nalloc(session.pool, 0, 2);
15922     }
15923 
15924     if (pr_table_add(tls_psks, identity, bn, sizeof(BIGNUM *)) < 0) {
15925       pr_log_debug(DEBUG0, MOD_TLS_VERSION
15926         ": error stashing key for identity '%s': %s", identity,
15927         strerror(errno));
15928       BN_free(bn);
15929     }
15930 
15931     c = find_config_next(c, c->next, CONF_PARAM, "TLSPreSharedKey", FALSE);
15932   }
15933 #endif /* PSK_MAX_PSK_LEN */
15934 }
15935 
15936 static void tls_lookup_renegotiate(server_rec *s) {
15937 #if OPENSSL_VERSION_NUMBER > 0x000907000L
15938   config_rec *c = NULL;
15939 
15940   /* Lookup/process any configured TLSRenegotiate parameters. */
15941   c = find_config(s->conf, CONF_PARAM, "TLSRenegotiate", FALSE);
15942   if (c == NULL) {
15943     return;
15944   }
15945 
15946   if (c->argc == 0) {
15947     /* Disable all server-side requested renegotiations; clients can still
15948      * request renegotiations.
15949      */
15950     tls_ctrl_renegotiate_timeout = 0;
15951     tls_data_renegotiate_limit = 0;
15952     tls_renegotiate_timeout = 0;
15953     tls_renegotiate_required = FALSE;
15954 
15955   } else {
15956     int ctrl_timeout = *((int *) c->argv[0]);
15957     off_t data_limit = *((off_t *) c->argv[1]);
15958     int renegotiate_timeout = *((int *) c->argv[2]);
15959     unsigned char renegotiate_required = *((unsigned char *) c->argv[3]);
15960 
15961     if (data_limit > 0) {
15962       tls_data_renegotiate_limit = data_limit;
15963     }
15964 
15965     if (renegotiate_timeout > 0) {
15966       tls_renegotiate_timeout = renegotiate_timeout;
15967     }
15968 
15969     tls_renegotiate_required = renegotiate_required;
15970 
15971     /* Set any control channel renegotiation timers, if need be. */
15972     pr_timer_add(ctrl_timeout ? ctrl_timeout : tls_ctrl_renegotiate_timeout,
15973       -1, &tls_module, tls_ctrl_renegotiate_cb, "SSL/TLS renegotiation");
15974   }
15975 #endif
15976 }
15977 
15978 static void tls_lookup_stapling(server_rec *s) {
15979 #if defined(PR_USE_OPENSSL_OCSP)
15980   config_rec *c;
15981 
15982   /* Reset to defaults. */
15983   tls_stapling_opts = 0UL;
15984 
15985   c = find_config(s->conf, CONF_PARAM, "TLSStaplingOptions", FALSE);
15986   while (c != NULL) {
15987     unsigned long opts = 0;
15988 
15989     pr_signals_handle();
15990 
15991     opts = *((unsigned long *) c->argv[0]);
15992     tls_stapling_opts |= opts;
15993 
15994     c = find_config_next(c, c->next, CONF_PARAM, "TLSStaplingOptions", FALSE);
15995   }
15996 
15997   c = find_config(s->conf, CONF_PARAM, "TLSStaplingResponder", FALSE);
15998   if (c != NULL) {
15999     tls_stapling_responder = c->argv[0];
16000 
16001   } else {
16002     /* Reset to default. */
16003     tls_stapling_responder = NULL;
16004   }
16005 
16006   c = find_config(s->conf, CONF_PARAM, "TLSStaplingTimeout", FALSE);
16007   if (c != NULL) {
16008     tls_stapling_timeout = *((unsigned int *) c->argv[0]);
16009 
16010   } else {
16011     /* Reset the default. */
16012     tls_stapling_timeout = TLS_DEFAULT_STAPLING_TIMEOUT;
16013   }
16014 
16015   /* If a TLSStaplingCache has been configured, then TLSStapling should
16016    * be enabled by default.
16017    */
16018   if (tls_ocsp_cache != NULL) {
16019     tls_stapling = TRUE;
16020   }
16021 
16022   c = find_config(s->conf, CONF_PARAM, "TLSStapling", FALSE);
16023   if (c != NULL) {
16024     tls_stapling = *((int *) c->argv[0]);
16025 
16026   } else {
16027     /* Reset the default. */
16028     tls_stapling = FALSE;
16029   }
16030 #endif /* PR_USE_OPENSSL_OCSP */
16031 }
16032 
16033 static void tls_lookup_verify(server_rec *s) {
16034   config_rec *c;
16035 
16036   /* Clear client verification-related flags. */
16037   tls_flags &= ~TLS_SESS_VERIFY_CLIENT_REQUIRED;
16038   tls_flags &= ~TLS_SESS_VERIFY_CLIENT_OPTIONAL;
16039 
16040   /* TLSVerifyClient */
16041   c = find_config(s->conf, CONF_PARAM, "TLSVerifyClient", FALSE);
16042   if (c != NULL) {
16043     unsigned char verify_client;
16044 
16045     verify_client = *((unsigned char *) c->argv[0]);
16046     switch (verify_client) {
16047       case 0:
16048         break;
16049 
16050       case 1:
16051         tls_flags |= TLS_SESS_VERIFY_CLIENT_REQUIRED;
16052         break;
16053 
16054       case 2:
16055         tls_flags |= TLS_SESS_VERIFY_CLIENT_OPTIONAL;
16056         break;
16057 
16058       default:
16059         break;
16060     }
16061   }
16062 
16063   /* Clear server verification-related flags. */
16064   tls_flags &= ~TLS_SESS_VERIFY_SERVER_NO_DNS;
16065   tls_flags &= ~TLS_SESS_VERIFY_SERVER;
16066 
16067   /* TLSVerifyServer */
16068   c = find_config(s->conf, CONF_PARAM, "TLSVerifyServer", FALSE);
16069   if (c != NULL) {
16070     int setting;
16071 
16072     setting = *((int *) c->argv[0]);
16073     switch (setting) {
16074       case 2:
16075         tls_flags |= TLS_SESS_VERIFY_SERVER_NO_DNS;
16076         break;
16077 
16078       case 1:
16079         tls_flags |= TLS_SESS_VERIFY_SERVER;
16080         break;
16081     }
16082 
16083   } else {
16084     tls_flags |= TLS_SESS_VERIFY_SERVER;
16085   }
16086 
16087   /* If TLSVerifyClient/Server is on, look up the verification depth. */
16088   if (tls_flags & (TLS_SESS_VERIFY_CLIENT_REQUIRED|TLS_SESS_VERIFY_SERVER|TLS_SESS_VERIFY_SERVER_NO_DNS)) {
16089     int *depth = NULL;
16090 
16091     depth = get_param_ptr(s->conf, "TLSVerifyDepth", FALSE);
16092     if (depth != NULL) {
16093       tls_verify_depth = *depth;
16094 
16095     } else {
16096       /* Reset the default. */
16097       tls_verify_depth = TLS_DEFAULT_VERIFY_DEPTH;
16098     }
16099   }
16100 }
16101 
16102 static void tls_lookup_all(server_rec *s) {
16103   config_rec *c;
16104 
16105   /* TLSCACertificate{File,Path} */
16106   tls_ca_file = get_param_ptr(s->conf, "TLSCACertificateFile", FALSE);
16107   tls_ca_path = get_param_ptr(s->conf, "TLSCACertificatePath", FALSE);
16108 
16109   /* TLSCARevocation{File,Path} */
16110   tls_crl_file = get_param_ptr(s->conf, "TLSCARevocationFile", FALSE);
16111   tls_crl_path = get_param_ptr(s->conf, "TLSCARevocationPath", FALSE);
16112 
16113   /* TLSCertificateChainFile */
16114   tls_ca_chain = get_param_ptr(s->conf, "TLSCertificateChainFile", FALSE);
16115 
16116   /* TLS*CertificateFile.  Assume that, if no separate key files are configured,
16117    * the keys are in the same file as the corresponding certificate.
16118    */
16119   tls_dsa_cert_file = get_param_ptr(s->conf, "TLSDSACertificateFile", FALSE);
16120   tls_dsa_key_file = get_param_ptr(s->conf, "TLSDSACertificateKeyFile", FALSE);
16121   if (tls_dsa_key_file == NULL) {
16122     tls_dsa_key_file = tls_dsa_cert_file;
16123   }
16124 
16125   tls_ec_cert_file = get_param_ptr(s->conf, "TLSECCertificateFile", FALSE);
16126   tls_ec_key_file = get_param_ptr(s->conf, "TLSECCertificateKeyFile", FALSE);
16127   if (tls_ec_key_file == NULL) {
16128     tls_ec_key_file = tls_ec_cert_file;
16129   }
16130 
16131   tls_pkcs12_file = get_param_ptr(s->conf, "TLSPKCS12File", FALSE);
16132 
16133   tls_rsa_cert_file = get_param_ptr(s->conf, "TLSRSACertificateFile", FALSE);
16134   tls_rsa_key_file = get_param_ptr(s->conf, "TLSRSACertificateKeyFile", FALSE);
16135   if (tls_rsa_key_file == NULL) {
16136     tls_rsa_key_file = tls_rsa_cert_file;
16137   }
16138 
16139   /* TLSCipherSuite */
16140   tls_cipher_suite = get_param_ptr(s->conf, "TLSCipherSuite", FALSE);
16141   if (tls_cipher_suite == NULL) {
16142     tls_cipher_suite = TLS_DEFAULT_CIPHER_SUITE;
16143   }
16144 
16145   tls_lookup_dh_params(s);
16146 
16147   /* TLSECDHCurve */
16148 #if defined(PR_USE_OPENSSL_ECC)
16149   c = find_config(s->conf, CONF_PARAM, "TLSECDHCurve", FALSE);
16150   if (c != NULL) {
16151     tls_ecdh_curve = (void *) c->argv[0];
16152   } else {
16153 
16154     /* Reset the default. */
16155     tls_ecdh_curve = NULL;
16156   }
16157 #endif /* PR_USE_OPENSSL_ECC */
16158 
16159   /* TLSNextProtocol */
16160 #if !defined(OPENSSL_NO_TLSEXT)
16161   c = find_config(s->conf, CONF_PARAM, "TLSNextProtocol", FALSE);
16162   if (c != NULL) {
16163     tls_use_next_protocol = *((int *) c->argv[0]);
16164 
16165   } else {
16166     /* Reset the default. */
16167     tls_use_next_protocol = TRUE;
16168   }
16169 #endif /* !OPENSSL_NO_TLSEXT */
16170 
16171   /* TLSOptions */
16172   c = find_config(s->conf, CONF_PARAM, "TLSOptions", FALSE);
16173   while (c != NULL) {
16174     unsigned long opts = 0;
16175 
16176     pr_signals_handle();
16177 
16178     opts = *((unsigned long *) c->argv[0]);
16179     tls_opts |= opts;
16180 
16181     c = find_config_next(c, c->next, CONF_PARAM, "TLSOptions", FALSE);
16182   }
16183 
16184   /* If UseReverseDNS is set to off, disable TLS_OPT_VERIFY_CERT_FQDN. */
16185   if (!ServerUseReverseDNS &&
16186       ((tls_opts & TLS_OPT_VERIFY_CERT_FQDN) ||
16187        (tls_opts & TLS_OPT_VERIFY_CERT_CN))) {
16188 
16189     if (tls_opts & TLS_OPT_VERIFY_CERT_FQDN) {
16190       tls_opts &= ~TLS_OPT_VERIFY_CERT_FQDN;
16191       tls_log("%s", "reverse DNS off, disabling TLSOption dNSNameRequired");
16192     }
16193 
16194     if (tls_opts & TLS_OPT_VERIFY_CERT_CN) {
16195       tls_opts &= ~TLS_OPT_VERIFY_CERT_CN;
16196       tls_log("%s", "reverse DNS off, disabling TLSOption CommonNameRequired");
16197     }
16198   }
16199 
16200   /* TLSProtocol */
16201   c = find_config(s->conf, CONF_PARAM, "TLSProtocol", FALSE);
16202   if (c != NULL) {
16203     tls_protocol = *((unsigned int *) c->argv[0]);
16204 
16205   } else {
16206     /* Reset the default. */
16207     tls_protocol = TLS_PROTO_DEFAULT;
16208   }
16209 
16210   tls_lookup_psks(s);
16211 
16212   tls_lookup_renegotiate(s);
16213 
16214   /* TLSRequired */
16215   c = find_config(s->conf, CONF_PARAM, "TLSRequired", FALSE);
16216   if (c != NULL) {
16217     tls_required_on_ctrl = *((int *) c->argv[0]);
16218     tls_required_on_data = *((int *) c->argv[1]);
16219     tls_required_on_auth = *((int *) c->argv[2]);
16220 
16221   } else {
16222     /* Reset the default. */
16223     tls_required_on_ctrl = 0;
16224     tls_required_on_data = 0;
16225     tls_required_on_auth = 0;
16226   }
16227 
16228   /* TLSServerCipherPreference */
16229 #if defined(SSL_OP_CIPHER_SERVER_PREFERENCE)
16230   c = find_config(s->conf, CONF_PARAM, "TLSServerCipherPreference",
16231     FALSE);
16232   if (c != NULL) {
16233     tls_use_server_cipher_preference = *((int *) c->argv[0]);
16234 
16235   } else {
16236     /* Reset the default. */
16237     tls_use_server_cipher_preference = TRUE;
16238   }
16239 #endif /* SSL_OP_CIPHER_SERVER_PREFERENCE */
16240 
16241   /* TLSServerInfoFile */
16242 #if !defined(OPENSSL_NO_TLSEXT)
16243 # if OPENSSL_VERSION_NUMBER >= 0x10002000L && \
16244      !defined(HAVE_LIBRESSL)
16245   c = find_config(s->conf, CONF_PARAM, "TLSServerInfoFile", FALSE);
16246   if (c != NULL) {
16247     tls_serverinfo_file = c->argv[0];
16248 
16249   } else {
16250     /* Reset the default. */
16251     tls_serverinfo_file = NULL;
16252   }
16253 # endif /* OpenSSL-1.0.2 and later */
16254 #endif /* !OPENSSL_NO_TLSEXT */
16255 
16256   /* TLSSessionTickets */
16257 #if defined(TLS_USE_SESSION_TICKETS)
16258   c = find_config(s->conf, CONF_PARAM, "TLSSessionTickets", FALSE);
16259   if (c != NULL) {
16260     tls_use_session_tickets = *((int *) c->argv[0]);
16261 
16262   } else {
16263     /* Reset the default. */
16264     tls_use_session_tickets = FALSE;
16265   }
16266 #endif /* TLS_USE_SESSION_TICKETS */
16267 
16268   tls_lookup_stapling(s);
16269 
16270   /* TLSTimeoutHandshake */
16271   c = find_config(s->conf, CONF_PARAM, "TLSTimeoutHandshake", FALSE);
16272   if (c != NULL) {
16273     tls_handshake_timeout = *((unsigned int *) c->argv[0]);
16274 
16275   } else {
16276     /* Reset the default. */
16277     tls_handshake_timeout = TLS_DEFAULT_HANDSHAKE_TIMEOUT;
16278   }
16279 
16280   tls_lookup_verify(s);
16281 }
16282 
16283 /* SSL setters */
16284 
16285 static int tls_ssl_set_cert_chain(SSL *ssl) {
16286 #if OPENSSL_VERSION_NUMBER >= 0x10100000L && \
16287     !defined(HAVE_LIBRESSL)
16288   int res;
16289 
16290   if (tls_ca_chain == NULL) {
16291     return 0;
16292   }
16293 
16294   tls_log("adding certs from '%s' to SSL certificate chain", tls_ca_chain);
16295   PRIVS_ROOT
16296   res = SSL_use_certificate_chain_file(ssl, tls_ca_chain);
16297   PRIVS_RELINQUISH
16298 
16299   if (res != 1) {
16300     tls_log("unable to read certificate chain '%s': %s", tls_ca_chain,
16301       tls_get_errors());
16302     return -1;
16303   }
16304 #endif /* OpenSSL 1.1.x and later */
16305 
16306   return 0;
16307 }
16308 
16309 static int tls_ssl_set_ciphers(SSL *ssl) {
16310   SSL_set_cipher_list(ssl, tls_cipher_suite);
16311   return 0;
16312 }
16313 
16314 static int tls_ssl_set_crls(SSL *ssl) {
16315   return 0;
16316 }
16317 
16318 static int tls_ssl_set_ecdh_curve(SSL *ssl) {
16319 #if defined(PR_USE_OPENSSL_ECC)
16320 # if defined(SSL_CTX_set_ecdh_auto)
16321   if (tls_opts & TLS_OPT_NO_AUTO_ECDH) {
16322     SSL_set_ecdh_auto(ssl, 0);
16323   }
16324 # endif
16325 
16326   if (tls_ecdh_curve != NULL) {
16327 # if defined(SSL_CTX_set1_curves_list)
16328     char *curve_names;
16329 
16330     curve_names = tls_ecdh_curve;
16331     if (strcasecmp(curve_names, "auto") != 0) {
16332       SSL_set1_curves_list(ssl, curve_names);
16333     }
16334 # else
16335     const EC_KEY *ec_key;
16336 
16337     ec_key = tls_ecdh_curve;
16338     SSL_set_tmp_ecdh(ssl, ec_key);
16339 # endif /* pre OpenSSL-1.0.2 */
16340 
16341     SSL_set_options(ssl, SSL_OP_SINGLE_ECDH_USE);
16342   } else {
16343 # if OPENSSL_VERSION_NUMBER < 0x10100000L
16344     SSL_set_tmp_ecdh_callback(ssl, tls_ecdh_cb);
16345 # endif /* Before OpenSSL-1.1.x */
16346   }
16347 #endif /* PR_USE_OPENSS_ECC */
16348 
16349   return 0;
16350 }
16351 
16352 static int tls_ssl_set_psks(SSL *ssl) {
16353 #if defined(PSK_MAX_PSK_LEN)
16354   if (tls_psks == NULL ||
16355       pr_table_count(tls_psks) == 0) {
16356     SSL_set_psk_server_callback(ssl, NULL);
16357     return 0;
16358   }
16359 
16360   pr_trace_msg(trace_channel, 9,
16361     "enabling support for PSK identities (%d)", pr_table_count(tls_psks));
16362   SSL_set_psk_server_callback(ssl, tls_lookup_psk);
16363 #endif /* PSK_MAX_PSK_LEN */
16364 
16365   return 0;
16366 }
16367 
16368 static int tls_ssl_set_options(SSL *ssl) {
16369 
16370 #if OPENSSL_VERSION_NUMBER > 0x009080cfL
16371   SSL_clear_options(ssl, SSL_OP_CIPHER_SERVER_PREFERENCE);
16372 
16373   /* The OpenSSL team realized that the flag added in 0.9.8l, the
16374    * SSL3_FLAGS_ALLOW_UNSAFE_LEGACY_RENEGOTIATION flag, was a bad idea.
16375    * So in later versions, it was changed to a context flag,
16376    * SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION.
16377    */
16378   SSL_clear_options(ssl, SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION);
16379   if (tls_opts & TLS_OPT_ALLOW_CLIENT_RENEGOTIATIONS) {
16380     int ssl_opts;
16381 
16382     ssl_opts = SSL_get_options(ssl);
16383     ssl_opts |= SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION;
16384     SSL_set_options(ssl, ssl_opts);
16385   }
16386 #endif
16387 
16388 #if defined(SSL_OP_CIPHER_SERVER_PREFERENCE)
16389   if (tls_use_server_cipher_preference == TRUE) {
16390     int ssl_opts;
16391 
16392     ssl_opts = SSL_get_options(ssl);
16393     ssl_opts |= SSL_OP_CIPHER_SERVER_PREFERENCE;
16394     SSL_set_options(ssl, ssl_opts);
16395   }
16396 #endif /* SSL_OP_CIPHER_SERVER_PREFERENCE */
16397 
16398 #if OPENSSL_VERSION_NUMBER > 0x000907000L
16399   /* Install a callback for logging OpenSSL message information, if requested.
16400    */
16401   if (tls_opts & TLS_OPT_ENABLE_DIAGS) {
16402     tls_log("%s",
16403       "TLSOption EnableDiags enabled, setting diagnostics callback");
16404     SSL_set_msg_callback(ssl, tls_msg_cb);
16405 
16406   } else {
16407     SSL_set_msg_callback(ssl, NULL);
16408   }
16409 #endif
16410 
16411   return 0;
16412 }
16413 
16414 static int tls_ssl_set_next_protocol(SSL *ssl) {
16415 #if !defined(OPENSSL_NO_TLSEXT)
16416   register unsigned int i;
16417   const char *proto = TLS_DEFAULT_NEXT_PROTO;
16418   size_t encoded_protolen, proto_len;
16419   unsigned char *encoded_proto;
16420   struct tls_next_proto *next_proto;
16421   SSL_CTX *ctx;
16422 
16423   ctx = SSL_get_SSL_CTX(ssl);
16424 
16425   if (tls_use_next_protocol == FALSE) {
16426 # if defined(PR_USE_OPENSSL_NPN)
16427     SSL_CTX_set_next_protos_advertised_cb(ctx, NULL, NULL);
16428 # endif /* NPN */
16429 
16430 # if defined(PR_USE_OPENSSL_ALPN)
16431     SSL_CTX_set_alpn_select_cb(ctx, NULL, NULL);
16432 # endif /* ALPN */
16433 
16434     return 0;
16435   }
16436 
16437   proto_len = strlen(proto);
16438   encoded_protolen = proto_len + 1;
16439   encoded_proto = palloc(session.pool, encoded_protolen);
16440   encoded_proto[0] = proto_len;
16441   for (i = 0; i < proto_len; i++) {
16442     encoded_proto[i+1] = proto[i];
16443   }
16444 
16445   next_proto = palloc(session.pool, sizeof(struct tls_next_proto));
16446   next_proto->proto = pstrdup(session.pool, proto);
16447   next_proto->encoded_proto = encoded_proto;
16448   next_proto->encoded_protolen = encoded_protolen;
16449 
16450 # if defined(PR_USE_OPENSSL_NPN)
16451   SSL_CTX_set_next_protos_advertised_cb(ctx, tls_npn_advertised_cb, next_proto);
16452 # endif /* NPN */
16453 
16454 # if defined(PR_USE_OPENSSL_ALPN)
16455   SSL_CTX_set_alpn_select_cb(ctx, tls_alpn_select_cb, next_proto);
16456 # endif /* ALPN */
16457 #endif /* !OPENSSL_NO_TLSEXT */
16458 
16459   return 0;
16460 }
16461 
16462 static int tls_ssl_set_protocol(server_rec *s, SSL *ssl) {
16463   int all_proto, disabled_proto;
16464   unsigned int enabled_proto_count = 0;
16465   const char *enabled_proto_str = NULL;
16466 
16467   /* First, make sure ALL protocol versions are disabled by default. */
16468   all_proto = get_disabled_protocols(0);
16469   SSL_set_options(ssl, all_proto);
16470 
16471   disabled_proto = get_disabled_protocols(tls_protocol);
16472 
16473   /* Per the comments in <ssl/ssl.h>, SSL_CTX_set_options() uses |= on
16474    * the previous value.  This means we can easily OR in our new option
16475    * values with any previously set values.
16476    */
16477   enabled_proto_str = tls_get_proto_str(s->pool, tls_protocol,
16478     &enabled_proto_count);
16479 
16480   pr_log_debug(DEBUG8, MOD_TLS_VERSION ": supporting %s %s", enabled_proto_str,
16481     enabled_proto_count != 1 ? "protocols" : "protocol only");
16482 
16483   /* Now we clear all of the NO_ protocol version options EXCEPT for the
16484    * enabled versions.
16485    *
16486    * This is more convoluted than it should be, because of the expression
16487    * of enabled protocol versions via OP_NO_ negations, and bitmasking.
16488    */
16489 #if OPENSSL_VERSION_NUMBER > 0x000908000L
16490   SSL_clear_options(ssl, all_proto|disabled_proto);
16491 #endif
16492   SSL_set_options(ssl, disabled_proto);
16493 
16494   return 0;
16495 }
16496 
16497 static int tls_ssl_set_session_tickets(SSL *ssl) {
16498 #if defined(TLS_USE_SESSION_TICKETS) && \
16499     defined(SSL_OP_NO_TICKET)
16500   if (tls_use_session_tickets == TRUE) {
16501     /* Ensure that tickets are enabled in the SSL options. */
16502     SSL_clear_options(ssl, SSL_OP_NO_TICKET);
16503 
16504   } else {
16505 # ifdef TLS1_3_VERSION
16506     /* Disable session tickets unless it's a TLSv1.3 session. */
16507     if (SSL_version(ssl) != TLS1_3_VERSION) {
16508       SSL_set_options(ssl, SSL_OP_NO_TICKET);
16509     }
16510 # else
16511     /* Disable session tickets. */
16512     SSL_set_options(ssl, SSL_OP_NO_TICKET);
16513 # endif /* TLS1_3_VERSION */
16514   }
16515 #endif /* TLS_USE_SESSION_TICKETS and SSL_OP_NO_TICKET */
16516 
16517   return 0;
16518 }
16519 
16520 static int tls_ssl_set_verify(SSL *ssl) {
16521   int verify_mode = 0;
16522 
16523   if (tls_flags & TLS_SESS_VERIFY_CLIENT_OPTIONAL) {
16524     verify_mode = SSL_VERIFY_PEER;
16525   }
16526 
16527   if (tls_flags & TLS_SESS_VERIFY_CLIENT_REQUIRED) {
16528     /* If we are verifying clients, make sure the client sends a cert;
16529      * the protocol allows for the client to disregard a request for
16530      * its cert by the server.
16531      */
16532     verify_mode |= (SSL_VERIFY_PEER|SSL_VERIFY_FAIL_IF_NO_PEER_CERT);
16533   }
16534 
16535   if (verify_mode != 0) {
16536     SSL_set_verify(ssl, verify_mode, tls_verify_cb);
16537 
16538     /* Note: we add one to the configured depth purposefully.  As noted
16539      * in the OpenSSL man pages, the verification process will silently
16540      * stop at the configured depth, and the error messages ensuing will
16541      * be that of an incomplete certificate chain, rather than the
16542      * "chain too long" error that might be expected.  To log the "chain
16543      * too long" condition, we add one to the configured depth, and catch,
16544      * in the verify callback, the exceeding of the actual depth.
16545      */
16546     SSL_set_verify_depth(ssl, tls_verify_depth + 1);
16547   }
16548 
16549   return 0;
16550 }
16551 
16552 static int tls_ssl_set_session_id_context(server_rec *s, SSL *ssl) {
16553   SSL_SESSION *sess;
16554 
16555   /* Update the session ID context to use.  This is important; it ensures
16556    * that the session IDs for this particular vhost will differ from those
16557    * for another vhost.  An external TLS session cache will possibly
16558    * cache sessions from all vhosts together, and we need to keep them
16559    * separate.
16560    */
16561 
16562   pr_trace_msg(trace_channel, 19,
16563     "setting session ID context '%u' (%lu bytes) on SSL %p", s->sid,
16564     sizeof(s->sid), ssl);
16565   SSL_set_session_id_context(ssl, (unsigned char *) &(s->sid), sizeof(s->sid));
16566 
16567 #if defined(PR_USE_OPENSSL_SSL_SESSION_SET1_ID_CONTEXT)
16568   sess = SSL_get_session(ssl);
16569   if (sess != NULL) {
16570     pr_trace_msg(trace_channel, 19,
16571       "setting session ID context '%u' (%lu bytes) on SSL_SESSION %p (SSL %p)",
16572       s->sid, sizeof(s->sid), sess, ssl);
16573     SSL_SESSION_set1_id_context(sess, (unsigned char *) &(s->sid),
16574       sizeof(s->sid));
16575   }
16576 #endif
16577 
16578   return 0;
16579 }
16580 
16581 static char *get_sess_id_text(BIO *bio, unsigned char *id, unsigned int idsz) {
16582   register unsigned int i;
16583   char *data = NULL;
16584   long datalen;
16585 
16586   for (i = 0; i < idsz; i++) {
16587     BIO_printf(bio, "%02x", id[i]);
16588   }
16589 
16590   datalen = BIO_get_mem_data(bio, &data);
16591   if (data != NULL) {
16592     data[datalen] = '\0';
16593 
16594   } else {
16595     data = "UKNOWN";
16596   }
16597 
16598   return data;
16599 }
16600 
16601 static int tls_sni_sess_tab_add_cb(SSL *ssl, SSL_SESSION *sess) {
16602   unsigned char *sess_id;
16603   unsigned int sess_id_len;
16604   void *key;
16605 
16606 #if OPENSSL_VERSION_NUMBER > 0x000908000L
16607   sess_id = (unsigned char *) SSL_SESSION_get_id(sess, &sess_id_len);
16608 #else
16609   /* XXX Directly accessing these fields cannot be a Good Thing. */
16610   sess_id = sess->session_id;
16611   sess_id_len = sess->session_id_length;
16612 #endif
16613 
16614   key = pr_table_pcalloc(tls_sni_sess_tab, sess_id_len);
16615   memcpy(key, sess_id, sess_id_len);
16616 
16617   if (pr_table_kadd(tls_sni_sess_tab, key, (size_t) sess_id_len,
16618       sess, sizeof(sess)) < 0) {
16619     pr_trace_msg(trace_channel, 3, "error adding SSL_SESSION to SNI table: %s",
16620       strerror(errno));
16621     return 0;
16622   }
16623 
16624   if (pr_trace_get_level(trace_channel) >= 29) {
16625     BIO *bio;
16626     char *data = NULL;
16627     long datalen;
16628 
16629     bio = BIO_new(BIO_s_mem());
16630     SSL_SESSION_print(bio, sess);
16631 
16632     datalen = BIO_get_mem_data(bio, &data);
16633     if (data != NULL) {
16634       data[datalen] = '\0';
16635 
16636       pr_trace_msg(trace_channel, 29, "added session to SNI table:\n%.*s",
16637         (int) datalen, data);
16638     }
16639 
16640     BIO_free(bio);
16641 
16642   } else {
16643     BIO *bio;
16644     char *text;
16645 
16646     bio = BIO_new(BIO_s_mem());
16647     text = get_sess_id_text(bio, sess_id, sess_id_len);
16648     pr_trace_msg(trace_channel, 9, "added session (ID %s) to SNI table", text);
16649     BIO_free(bio);
16650   }
16651 
16652   return 0;
16653 }
16654 
16655 static SSL_SESSION *tls_sni_sess_tab_get_cb(SSL *ssl, unsigned char *sess_id,
16656     int sess_id_len, int *do_copy) {
16657   SSL_SESSION *sess = NULL;
16658   const void *val;
16659   BIO *bio;
16660   char *text;
16661 
16662   /* Indicate to OpenSSL that the ref count should not be incremented
16663    * by setting the do_copy pointer to zero.
16664    */
16665   *do_copy = 0;
16666 
16667   bio = BIO_new(BIO_s_mem());
16668   text = get_sess_id_text(bio, sess_id, sess_id_len);
16669   pr_trace_msg(trace_channel, 9, "getting session (ID %s) from SNI table",
16670     text);
16671 
16672   val = pr_table_kget(tls_sni_sess_tab, (const void *) sess_id,
16673     (size_t) sess_id_len, NULL);
16674   if (val == NULL) {
16675     pr_trace_msg(trace_channel, 9, "session (ID %s) not found in SNI table",
16676       text);
16677     BIO_free(bio);
16678 
16679     errno = ENOENT;
16680     return NULL;
16681   }
16682 
16683   sess = (SSL_SESSION *) val;
16684 
16685   if (pr_trace_get_level(trace_channel) >= 29) {
16686     char *data = NULL;
16687     long datalen;
16688 
16689     BIO_free(bio);
16690     bio = BIO_new(BIO_s_mem());
16691     SSL_SESSION_print(bio, sess);
16692 
16693     datalen = BIO_get_mem_data(bio, &data);
16694     if (data != NULL) {
16695       data[datalen] = '\0';
16696 
16697       pr_trace_msg(trace_channel, 29, "found session in SNI table:\n%.*s",
16698         (int) datalen, data);
16699     }
16700 
16701   } else {
16702     pr_trace_msg(trace_channel, 9, "found session (ID %s) in SNI table", text);
16703   }
16704 
16705   BIO_free(bio);
16706   return sess;
16707 }
16708 
16709 static void tls_sni_sess_tab_delete_cb(SSL_CTX *ctx, SSL_SESSION *sess) {
16710   unsigned char *sess_id;
16711   unsigned int sess_id_len;
16712   const void *val;
16713   BIO *bio;
16714   char *text;
16715 
16716 #if OPENSSL_VERSION_NUMBER > 0x000908000L
16717   sess_id = (unsigned char *) SSL_SESSION_get_id(sess, &sess_id_len);
16718 #else
16719   /* XXX Directly accessing these fields cannot be a Good Thing. */
16720   sess_id = sess->session_id;
16721   sess_id_len = sess->session_id_length;
16722 #endif
16723 
16724   bio = BIO_new(BIO_s_mem());
16725   text = get_sess_id_text(bio, sess_id, sess_id_len);
16726   pr_trace_msg(trace_channel, 9, "removing session (ID %s) from SNI table",
16727     text);
16728 
16729   val = pr_table_kremove(tls_sni_sess_tab, (const void *) sess_id,
16730     (size_t) sess_id_len, NULL);
16731   if (val == NULL) {
16732     if (errno == ENOENT) {
16733       pr_trace_msg(trace_channel, 9, "no session (ID %s) found in SNI table",
16734         text);
16735 
16736     } else {
16737       pr_trace_msg(trace_channel, 9,
16738         "error removing session (ID %s) from SNI table: %s", text,
16739           strerror(errno));
16740     }
16741   }
16742 
16743   BIO_free(bio);
16744 }
16745 
16746 static int tls_ssl_set_all(server_rec *s, SSL *ssl) {
16747   SSL_CTX *ctx = NULL;
16748   long cache_mode;
16749 
16750   /* This is the key to switching CAs, cert chains, etc for the SSL object
16751    * for SNI support: build an entirely new SSL_CTX, using the new/proper CAs
16752    * et al, and set that on the SSL object.
16753    */
16754   ctx = tls_init_ctx(s);
16755   if (ctx == NULL) {
16756     return -1;
16757   }
16758 
16759   pr_trace_msg(trace_channel, 19,
16760     "setting new SSL_CTX for future data transfers");
16761 
16762   /* Update the SSL_CTX for the possibly changed <VirtualHost> config.
16763    *
16764    * Even though our SSL has already been created from this SSL_CTX,
16765    * which means any SSL_CTX changes WILL NOT be conveyed to our SSL,
16766    * we update it for any data transfer SSL objects later.
16767    */
16768   if (tls_ctx_set_all(s, ctx) < 0) {
16769     return -1;
16770   }
16771 
16772   /* Copy the existing session cache settings into the new SSL_CTX. */
16773   cache_mode = SSL_CTX_get_session_cache_mode(ssl_ctx);
16774   SSL_CTX_set_session_cache_mode(ctx, cache_mode);
16775 
16776   if (cache_mode == SSL_SESS_CACHE_OFF) {
16777     /* Make sure we automatically relax the "SSL session reuse required
16778      * for data connections" requirement; to enforce such a requirement
16779      * TLS session caching MUST be enabled.  So if session caching has been
16780      * explicitly disabled, relax that policy as well.
16781      */
16782     tls_opts |= TLS_OPT_NO_SESSION_REUSE_REQUIRED;
16783   }
16784 
16785   /* Use an in-memory table-based session store to preserve sessions
16786    * across the SNI-mandated SSL_CTX changes, in order to preserve
16787    * session resumption for data transfers (Issue #924).
16788    *
16789    * Note that this is only necessary if a TLSSessionCache has not been
16790    * configured.
16791    */
16792 
16793   if (SSL_CTX_sess_get_new_cb(ssl_ctx) == NULL) {
16794     tls_sni_sess_tab = pr_table_alloc(session.pool, 0);
16795 
16796     /* Yes, it looks strange to be setting these callbacks on the old
16797      * SSL_CTX, the one we will be replacing with our new SNI SSL_CTX.
16798      *
16799      * However, that old SSL_CTX is preserved (and used!) in the SSL object
16800      * via the initial_ctx, and thus its callbacks are used when adding
16801      * sessions.  And later, for data transfers, the SNI SSL_CTX callbacks
16802      * will be used for session lookup.  Fun, huh?
16803      */
16804     SSL_CTX_sess_set_new_cb(ssl_ctx, tls_sni_sess_tab_add_cb);
16805     SSL_CTX_sess_set_get_cb(ssl_ctx, tls_sni_sess_tab_get_cb);
16806     SSL_CTX_sess_set_remove_cb(ssl_ctx, tls_sni_sess_tab_delete_cb);
16807   }
16808 
16809   SSL_CTX_sess_set_new_cb(ctx, SSL_CTX_sess_get_new_cb(ssl_ctx));
16810   SSL_CTX_sess_set_get_cb(ctx, SSL_CTX_sess_get_get_cb(ssl_ctx));
16811   SSL_CTX_sess_set_remove_cb(ctx, SSL_CTX_sess_get_remove_cb(ssl_ctx));
16812   SSL_CTX_set_timeout(ctx, SSL_CTX_get_timeout(ssl_ctx));
16813 
16814   /* We MUST update the session ID context for the current SSL before we
16815    * replace its SSL_CTX, due to logic in the SSL_set_SSL_CTX internals.
16816    */
16817   if (tls_ssl_set_session_id_context(s, ssl) < 0 ||
16818       tls_ctx_set_session_id_context(s, ctx) < 0) {
16819     return -1;
16820   }
16821 
16822   /* Inexplicable OpenSSL errors occur if the cert chain is updated after
16823    * calling SSL_set_SSL_CTX, so we do it beforehand.
16824    */
16825   if (tls_ssl_set_cert_chain(ssl) < 0) {
16826     return -1;
16827   }
16828 
16829 #if OPENSSL_VERSION_NUMBER > 0x009080cfL
16830   /* Note that it is important that we update the SSL with the new SSL_CTX
16831    * AFTER it has been provisioned.  That way, the new/changed certs in the
16832    * SSL_CTX will be properly copied/updated in the SSL object.
16833    */
16834   ctx = SSL_set_SSL_CTX(ssl, ctx);
16835 #endif
16836 
16837   if (ssl_ctx != NULL) {
16838     /* Try not to leak memory. */
16839     SSL_CTX_free(ssl_ctx);
16840   }
16841 
16842   ssl_ctx = ctx;
16843 
16844   pr_trace_msg(trace_channel, 19, "resetting SSL for ctrl connection");
16845 
16846   if (tls_ssl_set_ciphers(ssl) < 0) {
16847     return -1;
16848   }
16849 
16850   if (tls_ssl_set_crls(ssl) < 0) {
16851     return -1;
16852   }
16853 
16854   if (tls_ssl_set_ecdh_curve(ssl) < 0) {
16855     return -1;
16856   }
16857 
16858   if (tls_ssl_set_psks(ssl) < 0) {
16859     return -1;
16860   }
16861 
16862   if (tls_ssl_set_options(ssl) < 0) {
16863     return -1;
16864   }
16865 
16866   if (tls_ssl_set_next_protocol(ssl) < 0) {
16867     return -1;
16868   }
16869 
16870   if (tls_ssl_set_protocol(s, ssl) < 0) {
16871     return -1;
16872   }
16873 
16874   /* Note that we set this after setting the protocol versions, since the
16875    * supported protocol version flags will affect session tickets, due to
16876    * TLSv1.3' use of tickets.
16877    */
16878   if (tls_ssl_set_session_tickets(ssl) < 0) {
16879     return -1;
16880   }
16881 
16882   if (tls_ssl_set_verify(ssl) < 0) {
16883     return -1;
16884   }
16885 
16886   return 0;
16887 }
16888 
16889 /* SSL_CTX setters */
16890 
16891 static int tls_ctx_set_ca_certs(SSL_CTX *ctx) {
16892   if (tls_ca_file == NULL &&
16893       tls_ca_path == NULL) {
16894     /* Default to using locations set in the OpenSSL config file. */
16895     pr_trace_msg(trace_channel, 9,
16896       "using default OpenSSL verification locations (see $SSL_CERT_DIR "
16897       "environment variable)");
16898 
16899     if (SSL_CTX_set_default_verify_paths(ctx) != 1) {
16900       tls_log("error setting default verification locations: %s",
16901         tls_get_errors());
16902     }
16903 
16904     return 0;
16905   }
16906 
16907   /* Set the locations used for verifying certificates. */
16908   PRIVS_ROOT
16909   if (SSL_CTX_load_verify_locations(ctx, tls_ca_file, tls_ca_path) != 1) {
16910     PRIVS_RELINQUISH
16911 
16912     tls_log("unable to set CA verification using file '%s' or directory '%s': "
16913       "%s", tls_ca_file ? tls_ca_file : "(none)",
16914       tls_ca_path ? tls_ca_path : "(none)", tls_get_errors());
16915       return -1;
16916   }
16917   PRIVS_RELINQUISH
16918 
16919   if (tls_ca_file != NULL) {
16920     pr_trace_msg(trace_channel, 19, "using CA verification file '%s'",
16921       tls_ca_file);
16922   }
16923 
16924   if (tls_ca_path != NULL) {
16925     pr_trace_msg(trace_channel, 19, "using CA verification directory '%s'",
16926       tls_ca_path);
16927   }
16928 
16929   if (tls_ca_file != NULL) {
16930     STACK_OF(X509_NAME) *sk;
16931 
16932     /* Use SSL_load_client_CA_file() to load all of the CA certs (since
16933      * there can be more than one) from the TLSCACertificateFile.  The
16934      * entire list of CAs in that file will be present to the client as
16935      * the "acceptable client CA" list.
16936      */
16937 
16938     PRIVS_ROOT
16939     sk = SSL_load_client_CA_file(tls_ca_file);
16940     PRIVS_RELINQUISH
16941 
16942     if (sk != NULL) {
16943       SSL_CTX_set_client_CA_list(ctx, sk);
16944 
16945     } else {
16946       tls_log("unable to read certificates in '%s': %s", tls_ca_file,
16947         tls_get_errors());
16948     }
16949   }
16950 
16951   if (tls_ca_path != NULL) {
16952     DIR *cacertdir = NULL;
16953 
16954     PRIVS_ROOT
16955     cacertdir = opendir(tls_ca_path);
16956     PRIVS_RELINQUISH
16957 
16958     if (cacertdir != NULL) {
16959       struct dirent *cadent = NULL;
16960       pool *tmp_pool = make_sub_pool(permanent_pool);
16961 
16962       while ((cadent = readdir(cacertdir)) != NULL) {
16963         FILE *cacertf;
16964         char *cacertname;
16965 
16966         pr_signals_handle();
16967 
16968         /* Skip dot directories. */
16969         if (is_dotdir(cadent->d_name)) {
16970           continue;
16971         }
16972 
16973         cacertname = pdircat(tmp_pool, tls_ca_path, cadent->d_name, NULL);
16974 
16975         PRIVS_ROOT
16976         cacertf = fopen(cacertname, "r");
16977         PRIVS_RELINQUISH
16978 
16979         if (cacertf != NULL) {
16980           X509 *x509;
16981 
16982           x509 = PEM_read_X509(cacertf, NULL, NULL, NULL);
16983           if (x509 != NULL) {
16984             if (SSL_CTX_add_client_CA(ctx, x509) != 1) {
16985               tls_log("error adding '%s' to client CA list: %s", cacertname,
16986                 tls_get_errors());
16987             }
16988 
16989           } else {
16990             tls_log("unable to read '%s': %s", cacertname, tls_get_errors());
16991           }
16992 
16993           fclose(cacertf);
16994 
16995         } else {
16996           tls_log("unable to open '%s': %s", cacertname, strerror(errno));
16997         }
16998       }
16999 
17000       destroy_pool(tmp_pool);
17001       closedir(cacertdir);
17002 
17003     } else {
17004       tls_log("unable to add CAs in '%s': %s", tls_ca_path, strerror(errno));
17005     }
17006   }
17007 
17008   return 0;
17009 }
17010 
17011 static int tls_ctx_set_dsa_cert(SSL_CTX *ctx, X509 **dsa_cert) {
17012   X509 *cert;
17013   FILE *fh = NULL;
17014   int res, xerrno;
17015 
17016   if (tls_dsa_cert_file == NULL) {
17017     return 0;
17018   }
17019 
17020   PRIVS_ROOT
17021   fh = fopen(tls_dsa_cert_file, "r");
17022   xerrno = errno;
17023   if (fh == NULL) {
17024     PRIVS_RELINQUISH
17025     tls_log("error reading TLSDSACertificateFile '%s': %s", tls_dsa_cert_file,
17026       strerror(xerrno));
17027     errno = xerrno;
17028     return -1;
17029   }
17030 
17031   /* As the file may contain sensitive data, we do not want it lingering
17032    * around in stdio buffers.
17033    */
17034   (void) setvbuf(fh, NULL, _IONBF, 0);
17035 
17036   cert = read_cert(fh, ctx);
17037   if (cert == NULL) {
17038     PRIVS_RELINQUISH
17039     tls_log("error reading TLSDSACertificateFile '%s': %s", tls_dsa_cert_file,
17040       tls_get_errors());
17041     fclose(fh);
17042     return -1;
17043   }
17044 
17045   fclose(fh);
17046 
17047   /* SSL_CTX_use_certificate() will increment the refcount on cert, so we
17048    * can safely call X509_free() on it.  However, we need to keep that
17049    * pointer around until after the handling of a cert chain file.
17050    */
17051   res = SSL_CTX_use_certificate(ctx, cert);
17052   if (res <= 0) {
17053     PRIVS_RELINQUISH
17054 
17055     tls_log("error loading TLSDSACertificateFile '%s': %s", tls_dsa_cert_file,
17056       tls_get_errors());
17057     return -1;
17058   }
17059 
17060   *dsa_cert = cert;
17061   pr_trace_msg(trace_channel, 19, "loaded DSA server certificate from '%s'",
17062     tls_dsa_cert_file);
17063 
17064   if (tls_dsa_key_file != NULL) {
17065     if (tls_pkey) {
17066       tls_pkey->flags |= TLS_PKEY_USE_DSA;
17067       tls_pkey->flags &= ~(TLS_PKEY_USE_RSA|TLS_PKEY_USE_EC);
17068     }
17069 
17070     res = SSL_CTX_use_PrivateKey_file(ctx, tls_dsa_key_file, X509_FILETYPE_PEM);
17071     if (res <= 0) {
17072       PRIVS_RELINQUISH
17073 
17074       tls_log("error loading TLSDSACertificateKeyFile '%s': %s",
17075         tls_dsa_key_file, tls_get_errors());
17076       return -1;
17077     }
17078 
17079     res = SSL_CTX_check_private_key(ctx);
17080     if (res != 1) {
17081       PRIVS_RELINQUISH
17082 
17083       tls_log("error checking key from TLSDSACertificateKeyFile '%s': %s",
17084         tls_dsa_key_file, tls_get_errors());
17085       return -1;
17086     }
17087   }
17088   PRIVS_RELINQUISH
17089 
17090   return 0;
17091 }
17092 
17093 static int tls_ctx_set_ec_cert(SSL_CTX *ctx, X509 **ec_cert) {
17094 #if defined(PR_USE_OPENSSL_ECC)
17095   X509 *cert;
17096   FILE *fh = NULL;
17097   int res, xerrno;
17098 
17099   if (tls_ec_cert_file == NULL) {
17100     return 0;
17101   }
17102 
17103   PRIVS_ROOT
17104   fh = fopen(tls_ec_cert_file, "r");
17105   xerrno = errno;
17106   if (fh == NULL) {
17107     PRIVS_RELINQUISH
17108     tls_log("error reading TLSECCertificateFile '%s': %s", tls_ec_cert_file,
17109       strerror(xerrno));
17110     errno = xerrno;
17111     return -1;
17112   }
17113 
17114   /* As the file may contain sensitive data, we do not want it lingering
17115    * around in stdio buffers.
17116    */
17117   (void) setvbuf(fh, NULL, _IONBF, 0);
17118 
17119   cert = read_cert(fh, ctx);
17120   if (cert == NULL) {
17121     PRIVS_RELINQUISH
17122     tls_log("error reading TLSECCertificateFile '%s': %s", tls_ec_cert_file,
17123       tls_get_errors());
17124     fclose(fh);
17125     return -1;
17126   }
17127 
17128   fclose(fh);
17129 
17130   /* SSL_CTX_use_certificate() will increment the refcount on cert, so we
17131    * can safely call X509_free() on it.  However, we need to keep that
17132    * pointer around until after the handling of a cert chain file.
17133    */
17134   res = SSL_CTX_use_certificate(ctx, cert);
17135   if (res <= 0) {
17136     PRIVS_RELINQUISH
17137 
17138     tls_log("error loading TLSECCertificateFile '%s': %s", tls_ec_cert_file,
17139       tls_get_errors());
17140     return -1;
17141   }
17142 
17143   *ec_cert = cert;
17144   pr_trace_msg(trace_channel, 19, "loaded EC server certificate from '%s'",
17145     tls_ec_cert_file);
17146 
17147   if (tls_ec_key_file != NULL) {
17148     if (tls_pkey) {
17149       tls_pkey->flags |= TLS_PKEY_USE_EC;
17150       tls_pkey->flags &= ~(TLS_PKEY_USE_RSA|TLS_PKEY_USE_DSA);
17151     }
17152 
17153     res = SSL_CTX_use_PrivateKey_file(ctx, tls_ec_key_file, X509_FILETYPE_PEM);
17154     if (res <= 0) {
17155       PRIVS_RELINQUISH
17156 
17157       tls_log("error loading TLSECCertificateKeyFile '%s': %s",
17158         tls_ec_key_file, tls_get_errors());
17159       return -1;
17160     }
17161 
17162     res = SSL_CTX_check_private_key(ctx);
17163     if (res != 1) {
17164       PRIVS_RELINQUISH
17165 
17166       tls_log("error checking key from TLSECCertificateKeyFile '%s': %s",
17167         tls_ec_key_file, tls_get_errors());
17168       return -1;
17169     }
17170   }
17171 
17172   PRIVS_RELINQUISH
17173 #endif /* PR_USE_OPENSSL_ECC */
17174 
17175   return 0;
17176 }
17177 
17178 static int tls_ctx_set_pkcs12_cert(SSL_CTX *ctx, X509 **dsa_cert,
17179     X509 **ec_cert, X509 **rsa_cert) {
17180   PKCS12 *p12 = NULL;
17181   X509 *cert = NULL;
17182   EVP_PKEY *pkey = NULL;
17183   FILE *fh;
17184   int res, xerrno;
17185   char *passwd = "";
17186 
17187   if (tls_pkcs12_file == NULL) {
17188     return 0;
17189   }
17190 
17191   if (tls_pkey) {
17192     passwd = tls_pkey->pkcs12_passwd;
17193   }
17194 
17195   PRIVS_ROOT
17196   fh = fopen(tls_pkcs12_file, "r");
17197   xerrno = errno;
17198   if (fh == NULL) {
17199     PRIVS_RELINQUISH
17200 
17201     tls_log("error opening TLSPKCS12File '%s': %s", tls_pkcs12_file,
17202       strerror(xerrno));
17203     errno = xerrno;
17204     return -1;
17205   }
17206 
17207   /* As the file may contain sensitive data, we do not want it lingering
17208    * around in stdio buffers.
17209    */
17210   (void) setvbuf(fh, NULL, _IONBF, 0);
17211 
17212   /* Note that this should NOT fail; we will have already parsed the PKCS12
17213    * file, in order to get the password and key passphrases.
17214    */
17215   p12 = d2i_PKCS12_fp(fh, NULL);
17216   if (p12 == NULL) {
17217     PRIVS_RELINQUISH
17218 
17219     tls_log("error reading TLSPKCS12File '%s': %s", tls_pkcs12_file,
17220       tls_get_errors());
17221     fclose(fh);
17222     return -1;
17223   }
17224 
17225   fclose(fh);
17226 
17227   /* XXX Need to add support for any CA certs contained in the PKCS12 file. */
17228   if (PKCS12_parse(p12, passwd, &pkey, &cert, NULL) != 1) {
17229     PRIVS_RELINQUISH
17230 
17231     tls_log("error parsing info in TLSPKCS12File '%s': %s", tls_pkcs12_file,
17232       tls_get_errors());
17233 
17234     PKCS12_free(p12);
17235 
17236     if (cert != NULL) {
17237       X509_free(cert);
17238     }
17239 
17240     if (pkey != NULL) {
17241       EVP_PKEY_free(pkey);
17242     }
17243 
17244     return -1;
17245   }
17246 
17247   /* Note: You MIGHT be tempted to call SSL_CTX_check_private_key(ctx) here,
17248    * to make sure that the private key can be used.  But doing so will not
17249    * work as expected, and will error out with:
17250    *
17251    *  SSL_CTX_check_private_key:no certificate assigned
17252    *
17253    * To make PKCS#12 support work, do not make that call here.
17254    */
17255 
17256   res = SSL_CTX_use_certificate(ctx, cert);
17257   if (res <= 0) {
17258     PRIVS_RELINQUISH
17259 
17260     tls_log("error loading certificate from TLSPKCS12File '%s' %s",
17261       tls_pkcs12_file, tls_get_errors());
17262     PKCS12_free(p12);
17263 
17264     if (cert != NULL) {
17265       X509_free(cert);
17266     }
17267 
17268     if (pkey != NULL) {
17269       EVP_PKEY_free(pkey);
17270     }
17271 
17272     return -1;
17273   }
17274 
17275   if (pkey != NULL &&
17276       tls_pkey != NULL) {
17277     switch (get_pkey_type(pkey)) {
17278       case EVP_PKEY_RSA:
17279         tls_pkey->flags |= TLS_PKEY_USE_RSA;
17280         tls_pkey->flags &= ~(TLS_PKEY_USE_DSA|TLS_PKEY_USE_EC);
17281         break;
17282 
17283       case EVP_PKEY_DSA:
17284         tls_pkey->flags |= TLS_PKEY_USE_DSA;
17285         tls_pkey->flags &= ~(TLS_PKEY_USE_RSA|TLS_PKEY_USE_EC);
17286         break;
17287 
17288 #ifdef PR_USE_OPENSSL_ECC
17289       case EVP_PKEY_EC:
17290         tls_pkey->flags |= TLS_PKEY_USE_EC;
17291         tls_pkey->flags &= ~(TLS_PKEY_USE_RSA|TLS_PKEY_USE_DSA);
17292         break;
17293 #endif /* PR_USE_OPENSSL_ECC */
17294     }
17295   }
17296 
17297   res = SSL_CTX_use_PrivateKey(ctx, pkey);
17298   if (res <= 0) {
17299     PRIVS_RELINQUISH
17300 
17301     tls_log("error loading key from TLSPKCS12File '%s' %s", tls_pkcs12_file,
17302       tls_get_errors());
17303 
17304     PKCS12_free(p12);
17305 
17306     if (cert != NULL) {
17307       X509_free(cert);
17308     }
17309 
17310     if (pkey != NULL) {
17311       EVP_PKEY_free(pkey);
17312     }
17313 
17314     return -1;
17315   }
17316 
17317   res = SSL_CTX_check_private_key(ctx);
17318   if (res != 1) {
17319     PRIVS_RELINQUISH
17320 
17321     tls_log("error checking key from TLSPKCS12File '%s': %s", tls_pkcs12_file,
17322       tls_get_errors());
17323 
17324     PKCS12_free(p12);
17325 
17326     if (cert != NULL) {
17327       X509_free(cert);
17328     }
17329 
17330     if (pkey != NULL) {
17331       EVP_PKEY_free(pkey);
17332     }
17333 
17334     return -1;
17335   }
17336 
17337   /* SSL_CTX_use_certificate() will increment the refcount on cert, so we
17338    * can safely call X509_free() on it.  However, we need to keep that
17339    * pointer around until after the handling of a cert chain file.
17340    */
17341   if (pkey != NULL) {
17342     switch (get_pkey_type(pkey)) {
17343       case EVP_PKEY_RSA:
17344         *rsa_cert = cert;
17345         break;
17346 
17347       case EVP_PKEY_DSA:
17348         *dsa_cert = cert;
17349         break;
17350 
17351 #ifdef PR_USE_OPENSSL_ECC
17352       case EVP_PKEY_EC:
17353         *ec_cert = cert;
17354         break;
17355 #endif /* PR_USE_OPENSSL_ECC */
17356     }
17357   }
17358 
17359   if (pkey != NULL) {
17360     EVP_PKEY_free(pkey);
17361   }
17362 
17363   if (p12 != NULL) {
17364     PKCS12_free(p12);
17365   }
17366 
17367   PRIVS_RELINQUISH
17368 
17369   return 0;
17370 }
17371 
17372 static int tls_ctx_set_rsa_cert(SSL_CTX *ctx, X509 **rsa_cert) {
17373   X509 *cert;
17374   FILE *fh = NULL;
17375   int res, xerrno;
17376 
17377   if (tls_rsa_cert_file == NULL) {
17378     return 0;
17379   }
17380 
17381   PRIVS_ROOT
17382   fh = fopen(tls_rsa_cert_file, "r");
17383   xerrno = errno;
17384   if (fh == NULL) {
17385     PRIVS_RELINQUISH
17386     pr_log_pri(PR_LOG_DEBUG, MOD_TLS_VERSION
17387       ": error reading TLSRSACertificateFile '%s': %s", tls_rsa_cert_file,
17388       strerror(xerrno));
17389     errno = xerrno;
17390     return -1;
17391   }
17392 
17393   /* As the file may contain sensitive data, we do not want it lingering
17394    * around in stdio buffers.
17395    */
17396   (void) setvbuf(fh, NULL, _IONBF, 0);
17397 
17398   cert = read_cert(fh, ctx);
17399   if (cert == NULL) {
17400     PRIVS_RELINQUISH
17401     pr_log_pri(PR_LOG_NOTICE, MOD_TLS_VERSION
17402       ": error reading TLSRSACertificateFile '%s': %s", tls_rsa_cert_file,
17403       tls_get_errors());
17404     fclose(fh);
17405     return -1;
17406   }
17407 
17408   fclose(fh);
17409 
17410   /* SSL_CTX_use_certificate() will increment the refcount on cert, so we
17411    * can safely call X509_free() on it.  However, we need to keep that
17412    * pointer around until after the handling of a cert chain file.
17413    */
17414   res = SSL_CTX_use_certificate(ctx, cert);
17415   if (res <= 0) {
17416     PRIVS_RELINQUISH
17417 
17418     pr_log_pri(PR_LOG_NOTICE, MOD_TLS_VERSION
17419       ": error loading TLSRSACertificateFile '%s': %s", tls_rsa_cert_file,
17420       tls_get_errors());
17421     return -1;
17422   }
17423 
17424   *rsa_cert = cert;
17425   pr_trace_msg(trace_channel, 19, "loaded RSA server certificate from '%s'",
17426     tls_rsa_cert_file);
17427 
17428   if (tls_rsa_key_file != NULL) {
17429     if (tls_pkey) {
17430       tls_pkey->flags |= TLS_PKEY_USE_RSA;
17431       tls_pkey->flags &= ~(TLS_PKEY_USE_DSA|TLS_PKEY_USE_EC);
17432     }
17433 
17434     res = SSL_CTX_use_PrivateKey_file(ctx, tls_rsa_key_file, X509_FILETYPE_PEM);
17435     if (res <= 0) {
17436       const char *errors;
17437 
17438       PRIVS_RELINQUISH
17439       errors = tls_get_errors();
17440 
17441       pr_trace_msg(trace_channel, 3,
17442         "error loading TLSRSACertificateKeyFile '%s': %s", tls_rsa_key_file,
17443         errors);
17444       pr_log_pri(PR_LOG_NOTICE, MOD_TLS_VERSION
17445         ": error loading TLSRSACertificateKeyFile '%s': %s", tls_rsa_key_file,
17446         errors);
17447       return -1;
17448     }
17449 
17450     res = SSL_CTX_check_private_key(ctx);
17451     if (res != 1) {
17452       const char *errors;
17453 
17454       PRIVS_RELINQUISH
17455       errors = tls_get_errors();
17456 
17457       pr_trace_msg(trace_channel, 3,
17458         "error checking key from TLSRSACertificateKeyFile '%s': %s",
17459         tls_rsa_key_file, errors);
17460       pr_log_pri(PR_LOG_NOTICE, MOD_TLS_VERSION
17461         ": error checking key from TLSRSACertificateKeyFile '%s': %s",
17462         tls_rsa_key_file, errors);
17463       return -1;
17464     }
17465   }
17466   PRIVS_RELINQUISH
17467 
17468   return 0;
17469 }
17470 
17471 static int tls_ctx_set_cert_chain(SSL_CTX *ctx, X509 *dsa_cert, X509 *ec_cert,
17472     X509 *rsa_cert) {
17473 #if defined(SSL_CTRL_CHAIN_CERT)
17474   BIO *bio;
17475   X509 *cert;
17476   unsigned int count = 0;
17477 
17478   if (tls_ca_chain == NULL) {
17479     return 0;
17480   }
17481 
17482   PRIVS_ROOT
17483   bio = BIO_new_file(tls_ca_chain, "r");
17484   PRIVS_RELINQUISH
17485 
17486   if (bio == NULL) {
17487     tls_log("unable to read certificate chain '%s': %s", tls_ca_chain,
17488       tls_get_errors());
17489     return 0;
17490   }
17491 
17492   if (SSL_CTX_clear_chain_certs(ctx) != 1) {
17493     tls_log("error clearing SSL_CTX chain certs: %s", tls_get_errors());
17494     BIO_free(bio);
17495     return -1;
17496   }
17497 
17498   cert = PEM_read_bio_X509(bio, NULL, NULL, NULL);
17499   while (cert != NULL) {
17500     pr_signals_handle();
17501 
17502     if (rsa_cert != NULL) {
17503       /* Skip this cert if it is the same as the configured RSA server cert. */
17504       if (X509_cmp(rsa_cert, cert) == 0) {
17505         X509_free(cert);
17506         cert = PEM_read_bio_X509(bio, NULL, NULL, NULL);
17507         continue;
17508       }
17509     }
17510 
17511     if (dsa_cert != NULL) {
17512       /* Skip this cert if it is the same as the configured DSA server cert. */
17513       if (X509_cmp(dsa_cert, cert) == 0) {
17514         X509_free(cert);
17515         cert = PEM_read_bio_X509(bio, NULL, NULL, NULL);
17516         continue;
17517       }
17518     }
17519 
17520     if (ec_cert != NULL) {
17521       /* Skip this cert if it is the same as the configured EC server cert. */
17522       if (X509_cmp(ec_cert, cert) == 0) {
17523         X509_free(cert);
17524         cert = PEM_read_bio_X509(bio, NULL, NULL, NULL);
17525         continue;
17526       }
17527     }
17528 
17529     if (SSL_CTX_add1_chain_cert(ctx, cert) != 1) {
17530       tls_log("error adding cert to SSL_CTX certificate chain: %s",
17531         tls_get_errors());
17532       X509_free(cert);
17533       break;
17534     }
17535 
17536     count++;
17537     cert = PEM_read_bio_X509(bio, NULL, NULL, NULL);
17538   }
17539 
17540   BIO_free(bio);
17541   ERR_clear_error();
17542 
17543   tls_log("added %u certs from '%s' to SSL_CTX certificate chain", count,
17544     tls_ca_chain);
17545 #endif /* SSL_CTRL_CHAIN_CERT */
17546 
17547   return 0;
17548 }
17549 
17550 static int tls_ctx_set_certs(SSL_CTX *ctx, X509 **dsa_cert, X509 **ec_cert,
17551     X509 **rsa_cert) {
17552   if (tls_ctx_set_dsa_cert(ctx, dsa_cert) < 0 ||
17553       tls_ctx_set_ec_cert(ctx, ec_cert) < 0 ||
17554       tls_ctx_set_pkcs12_cert(ctx, dsa_cert, ec_cert, rsa_cert) < 0 ||
17555       tls_ctx_set_rsa_cert(ctx, rsa_cert) < 0) {
17556     return -1;
17557   }
17558 
17559   /* Log a warning if the server was badly misconfigured, and has no server
17560    * certs at all.  The client will probably see this situation as something
17561    * like:
17562    *
17563    *  error:14094410:SSL routines:SSL3_READ_BYTES:sslv3 alert handshake failure
17564    *
17565    * And the TLSLog will show the error as:
17566    *
17567    *  error:1408A0C1:SSL routines:SSL3_GET_CLIENT_HELLO:no shared cipher
17568    */
17569   if (tls_rsa_cert_file == NULL &&
17570       tls_dsa_cert_file == NULL &&
17571       tls_ec_cert_file == NULL &&
17572       tls_pkcs12_file == NULL) {
17573     tls_log("no TLSRSACertificateFile, TLSDSACertificateFile, "
17574       "TLSECCertificateFile, or TLSPKCS12File configured; "
17575       "unable to handle SSL/TLS connections");
17576     pr_log_pri(PR_LOG_NOTICE, MOD_TLS_VERSION
17577       ": no TLSRSACertificateFile, TLSDSACertificateFile, "
17578       "TLSECCertificateFile or TLSPKCS12File configured; "
17579       "unable to handle SSL/TLS connections");
17580   }
17581 
17582   return 0;
17583 }
17584 
17585 static int tls_ctx_set_ciphers(SSL_CTX *ctx) {
17586   SSL_CTX_set_cipher_list(ctx, tls_cipher_suite);
17587   return 0;
17588 }
17589 
17590 static int tls_ctx_set_crls(SSL_CTX *ctx) {
17591   if (tls_crl_file == NULL &&
17592       tls_crl_path == NULL) {
17593     return 0;
17594   }
17595 
17596   /* Set up the CRL. */
17597   tls_crl_store = X509_STORE_new();
17598   if (tls_crl_store == NULL) {
17599     tls_log("error creating CRL store: %s", tls_get_errors());
17600     return -1;
17601   }
17602 
17603   PRIVS_ROOT
17604   if (X509_STORE_load_locations(tls_crl_store, tls_crl_file,
17605       tls_crl_path) != 1) {
17606 
17607     if (tls_crl_file != NULL &&
17608         tls_crl_path == NULL) {
17609       tls_log("error loading TLSCARevocationFile '%s': %s", tls_crl_file,
17610         tls_get_errors());
17611 
17612     } else if (tls_crl_file == NULL &&
17613                tls_crl_path != NULL) {
17614       tls_log("error loading TLSCARevocationPath '%s': %s", tls_crl_path,
17615         tls_get_errors());
17616 
17617     } else {
17618       tls_log("error loading TLSCARevocationFile '%s', "
17619         "TLSCARevocationPath '%s': %s", tls_crl_file, tls_crl_path,
17620         tls_get_errors());
17621     }
17622   }
17623 
17624   PRIVS_RELINQUISH
17625   return 0;
17626 }
17627 
17628 static int tls_ctx_set_ecdh_curve(SSL_CTX *ctx) {
17629 #if defined(PR_USE_OPENSSL_ECC)
17630 # if defined(SSL_CTX_set_ecdh_auto)
17631   if (tls_opts & TLS_OPT_NO_AUTO_ECDH) {
17632     SSL_CTX_set_ecdh_auto(ctx, 0);
17633   }
17634 # endif
17635 
17636   if (tls_ecdh_curve != NULL) {
17637 # if defined(SSL_CTX_set1_curves_list)
17638     char *curve_names;
17639 
17640     curve_names = tls_ecdh_curve;
17641     if (strcasecmp(curve_names, "auto") != 0) {
17642       SSL_CTX_set1_curves_list(ctx, curve_names);
17643     }
17644 # else
17645     const EC_KEY *ec_key;
17646 
17647     ec_key = tls_ecdh_curve;
17648     SSL_CTX_set_tmp_ecdh(ctx, ec_key);
17649 # endif /* pre OpenSSL-1.0.2 */
17650 
17651     SSL_CTX_set_options(ctx, SSL_OP_SINGLE_ECDH_USE);
17652   } else {
17653 # if OPENSSL_VERSION_NUMBER < 0x10100000L
17654     SSL_CTX_set_tmp_ecdh_callback(ctx, tls_ecdh_cb);
17655 # endif /* Before OpenSSL-1.1.x */
17656   }
17657 #endif /* PR_USE_OPENSS_ECC */
17658 
17659   return 0;
17660 }
17661 
17662 static int tls_ctx_set_next_protocol(SSL_CTX *ctx) {
17663 #if !defined(OPENSSL_NO_TLSEXT)
17664   register unsigned int i;
17665   const char *proto = TLS_DEFAULT_NEXT_PROTO;
17666   size_t encoded_protolen, proto_len;
17667   unsigned char *encoded_proto;
17668   struct tls_next_proto *next_proto;
17669 
17670   if (tls_use_next_protocol == FALSE) {
17671     return 0;
17672   }
17673 
17674   proto_len = strlen(proto);
17675   encoded_protolen = proto_len + 1;
17676   encoded_proto = palloc(session.pool, encoded_protolen);
17677   encoded_proto[0] = proto_len;
17678   for (i = 0; i < proto_len; i++) {
17679     encoded_proto[i+1] = proto[i];
17680   }
17681 
17682   next_proto = palloc(session.pool, sizeof(struct tls_next_proto));
17683   next_proto->proto = pstrdup(session.pool, proto);
17684   next_proto->encoded_proto = encoded_proto;
17685   next_proto->encoded_protolen = encoded_protolen;
17686 
17687 # if defined(PR_USE_OPENSSL_NPN)
17688   SSL_CTX_set_next_protos_advertised_cb(ctx, tls_npn_advertised_cb, next_proto);
17689 # endif /* NPN */
17690 
17691 # if defined(PR_USE_OPENSSL_ALPN)
17692   SSL_CTX_set_alpn_select_cb(ctx, tls_alpn_select_cb, next_proto);
17693 # endif /* ALPN */
17694 #endif /* !OPENSSL_NO_TLSEXT */
17695 
17696   return 0;
17697 }
17698 
17699 static int tls_ctx_set_options(SSL_CTX *ctx) {
17700 #if OPENSSL_VERSION_NUMBER > 0x009080cfL
17701   /* The OpenSSL team realized that the flag added in 0.9.8l, the
17702    * SSL3_FLAGS_ALLOW_UNSAFE_LEGACY_RENEGOTIATION flag, was a bad idea.
17703    * So in later versions, it was changed to a context flag,
17704    * SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION.
17705    */
17706   if (tls_opts & TLS_OPT_ALLOW_CLIENT_RENEGOTIATIONS) {
17707     int ssl_opts;
17708 
17709     ssl_opts = SSL_CTX_get_options(ctx);
17710     ssl_opts |= SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION;
17711     SSL_CTX_set_options(ctx, ssl_opts);
17712   }
17713 #endif
17714 
17715 #if defined(SSL_OP_CIPHER_SERVER_PREFERENCE)
17716   if (tls_use_server_cipher_preference == TRUE) {
17717     int ssl_opts;
17718 
17719     ssl_opts = SSL_CTX_get_options(ctx);
17720     ssl_opts |= SSL_OP_CIPHER_SERVER_PREFERENCE;
17721     SSL_CTX_set_options(ctx, ssl_opts);
17722   }
17723 #endif /* SSL_OP_CIPHER_SERVER_PREFERENCE */
17724 
17725 #if OPENSSL_VERSION_NUMBER > 0x000907000L
17726   /* Install a callback for logging OpenSSL message information, if requested.
17727    */
17728   if (tls_opts & TLS_OPT_ENABLE_DIAGS) {
17729     tls_log("%s",
17730       "TLSOption EnableDiags enabled, setting diagnostics callback");
17731     SSL_CTX_set_msg_callback(ctx, tls_msg_cb);
17732   }
17733 #endif
17734 
17735   return 0;
17736 }
17737 
17738 static int tls_ctx_set_pkey(SSL_CTX *ctx) {
17739   if (tls_pkey != NULL) {
17740     SSL_CTX_set_default_passwd_cb(ctx, tls_pkey_cb);
17741     SSL_CTX_set_default_passwd_cb_userdata(ctx, (void *) tls_pkey);
17742   }
17743 
17744   return 0;
17745 }
17746 
17747 static int tls_ctx_set_protocol(server_rec *s, SSL_CTX *ctx) {
17748   int all_proto, disabled_proto;
17749   unsigned int enabled_proto_count = 0;
17750   const char *enabled_proto_str = NULL;
17751 
17752   /* First, make sure ALL protocol versions are disabled by default. */
17753   all_proto = get_disabled_protocols(0);
17754   SSL_CTX_set_options(ctx, all_proto);
17755 
17756   disabled_proto = get_disabled_protocols(tls_protocol);
17757 
17758   /* Per the comments in <ssl/ssl.h>, SSL_CTX_set_options() uses |= on
17759    * the previous value.  This means we can easily OR in our new option
17760    * values with any previously set values.
17761    */
17762   enabled_proto_str = tls_get_proto_str(s->pool, tls_protocol,
17763     &enabled_proto_count);
17764 
17765   pr_log_debug(DEBUG8, MOD_TLS_VERSION ": supporting %s %s", enabled_proto_str,
17766     enabled_proto_count != 1 ? "protocols" : "protocol only");
17767 
17768   /* Now we clear all of the NO_ protocol version options EXCEPT for the
17769    * enabled versions.
17770    *
17771    * This is more convoluted than it should be, because of the expression
17772    * of enabled protocol versions via OP_NO_ negations, and bitmasking.
17773    */
17774 #if OPENSSL_VERSION_NUMBER > 0x009080cfL
17775   SSL_CTX_clear_options(ctx, all_proto|disabled_proto);
17776 #endif
17777   SSL_CTX_set_options(ctx, disabled_proto);
17778 
17779   return 0;
17780 }
17781 
17782 static int tls_ctx_set_psks(SSL_CTX *ctx) {
17783 #if defined(PSK_MAX_PSK_LEN)
17784   if (tls_psks != NULL &&
17785       pr_table_count(tls_psks) > 0) {
17786     pr_trace_msg(trace_channel, 9,
17787       "enabling support for PSK identities (%d)", pr_table_count(tls_psks));
17788     SSL_CTX_set_psk_server_callback(ctx, tls_lookup_psk);
17789   }
17790 #endif /* PSK_MAX_PSK_LEN */
17791 
17792   return 0;
17793 }
17794 
17795 static int tls_ctx_set_serverinfo(SSL_CTX *ctx) {
17796 #if !defined(OPENSSL_NO_TLSEXT)
17797 # if OPENSSL_VERSION_NUMBER >= 0x10002000L && \
17798      !defined(HAVE_LIBRESSL)
17799   if (tls_serverinfo_file == NULL) {
17800     return 0;
17801   }
17802 
17803   if (SSL_CTX_use_serverinfo_file(ctx, tls_serverinfo_file) != 1) {
17804     tls_log("error setting server info using '%s': %s", tls_serverinfo_file,
17805       tls_get_errors());
17806   }
17807 # endif /* OpenSSL-1.0.2 and later */
17808 #endif /* !OPENSSL_NO_TLSEXT */
17809 
17810   return 0;
17811 }
17812 
17813 static int tls_ctx_set_session_id_context(server_rec *s, SSL_CTX *ctx) {
17814   /* Update the session ID context to use.  This is important; it ensures
17815    * that the session IDs for this particular vhost will differ from those
17816    * for another vhost.  An external TLS session cache will possibly
17817    * cache sessions from all vhosts together, and we need to keep them
17818    * separate.
17819    */
17820   pr_trace_msg(trace_channel, 19,
17821     "setting session ID context '%u' (%lu bytes) on SSL_CTX %p", s->sid,
17822     sizeof(s->sid), ctx);
17823   SSL_CTX_set_session_id_context(ctx, (unsigned char *) &(s->sid),
17824     sizeof(s->sid));
17825 
17826   return 0;
17827 }
17828 
17829 static int tls_ctx_set_session_cache(server_rec *s, SSL_CTX *ctx) {
17830   config_rec *c;
17831   const char *provider;
17832   long timeout;
17833 
17834   c = find_config(s->conf, CONF_PARAM, "TLSSessionCache", FALSE);
17835   if (c == NULL) {
17836     /* No explicit external session cache configured. */
17837 
17838 #if OPENSSL_VERSION_NUMBER > 0x000907000L
17839     /* If we support renegotiations, then make the cache lifetime be 10%
17840      * longer than the control connection renegotiation timer.
17841      */
17842     timeout = 15840;
17843 #else
17844     /* If we are not supporting reneogtiations because the OpenSSL version
17845      * is too old, then set the default cache lifetime to 30 minutes.
17846      */
17847     timeout = 1800;
17848 #endif /* OpenSSL older than 0.9.7. */
17849 
17850     /* Make sure that we enable OpenSSL internal caching, AND that the
17851      * cache timeout is longer than the default control channel
17852      * renegotiation.
17853      */
17854 
17855     SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_SERVER);
17856     SSL_CTX_set_timeout(ctx, timeout);
17857 
17858     return 0;
17859   }
17860 
17861   /* Look up and initialize the configured session cache provider. */
17862   provider = c->argv[0];
17863   timeout = *((long *) c->argv[2]);
17864 
17865   if (provider != NULL) {
17866     if (strncmp(provider, "internal", 9) != 0) {
17867       tls_sess_cache = tls_sess_cache_get_cache(provider);
17868 
17869       pr_log_debug(DEBUG8, MOD_TLS_VERSION ": opening '%s' TLSSessionCache",
17870         provider);
17871 
17872       if (tls_sess_cache_open(c->argv[1], timeout) == 0) {
17873         long cache_mode, cache_flags;
17874 
17875         cache_mode = SSL_SESS_CACHE_SERVER;
17876 
17877         /* We could force OpenSSL to use ONLY the configured external session
17878          * caching mechanism by using the SSL_SESS_CACHE_NO_INTERNAL mode flag
17879          * (available in OpenSSL 0.9.6h and later).
17880          *
17881          * However, consider the case where the serialized session data is
17882          * too large for the external cache, or the external cache refuses
17883          * to add the session for some reason.  If OpenSSL is using only our
17884          * external cache, that session is lost (which could cause problems
17885          * e.g. for later protected data transfers, which require that the
17886          * SSL session from the control connection be reused).
17887          *
17888          * If the external cache can be reasonably sure that session data
17889          * can be added, then the NO_INTERNAL flag is a good idea; it keeps
17890          * OpenSSL from allocating more memory than necessary.  Having both
17891          * an internal and an external cache of the same data is a bit
17892          * unresourceful.  Thus we ask the external cache mechanism what
17893          * additional cache mode flags to use.
17894          */
17895 
17896         cache_flags = tls_sess_cache_get_cache_mode();
17897         cache_mode |= cache_flags;
17898 
17899         SSL_CTX_set_session_cache_mode(ctx, cache_mode);
17900         SSL_CTX_set_timeout(ctx, timeout);
17901 
17902         SSL_CTX_sess_set_new_cb(ctx, tls_sess_cache_add_sess_cb);
17903         SSL_CTX_sess_set_get_cb(ctx, tls_sess_cache_get_sess_cb);
17904         SSL_CTX_sess_set_remove_cb(ctx, tls_sess_cache_delete_sess_cb);
17905 
17906       } else {
17907         pr_log_debug(DEBUG1, MOD_TLS_VERSION
17908           ": error opening '%s' TLSSessionCache: %s", provider,
17909           strerror(errno));
17910 
17911         /* Default to using OpenSSL's own internal session caching. */
17912         SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_SERVER);
17913       }
17914 
17915     } else {
17916       /* Default to using OpenSSL's own internal session caching. */
17917       SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_SERVER);
17918       SSL_CTX_set_timeout(ctx, timeout);
17919     }
17920 
17921   } else {
17922     /* SSL session caching has been explicitly turned off. */
17923 
17924     pr_log_debug(DEBUG3, MOD_TLS_VERSION
17925       ": TLSSessionCache off, disabling TLS session caching and setting "
17926       "NoSessionReuseRequired TLSOption");
17927 
17928     SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_OFF);
17929 
17930     /* Make sure we automatically relax the "SSL session reuse required
17931      * for data connections" requirement; to enforce such a requirement
17932      * TLS session caching MUST be enabled.  So if session caching has been
17933      * explicitly disabled, relax that policy as well.
17934      */
17935     tls_opts |= TLS_OPT_NO_SESSION_REUSE_REQUIRED;
17936   }
17937 
17938   return 0;
17939 }
17940 
17941 static int tls_ctx_set_session_tickets(SSL_CTX *ctx) {
17942 #if defined(TLS_USE_SESSION_TICKETS) && \
17943     defined(SSL_OP_NO_TICKET)
17944   if (tls_use_session_tickets == TRUE) {
17945     if (SSL_CTX_set_tlsext_ticket_key_cb(ctx, tls_ticket_key_cb) == 0) {
17946       pr_log_pri(PR_LOG_WARNING, MOD_TLS_VERSION
17947         ": mod_tls compiled with Session Ticket support, but linked to "
17948         "an OpenSSL library without tlsext support, therefore Session "
17949         "Tickets are not available");
17950     }
17951 
17952     /* Ensure that tickets are enabled in the SSL_CTX options. */
17953     SSL_CTX_clear_options(ctx, SSL_OP_NO_TICKET);
17954 
17955   } else {
17956 # ifdef TLS1_3_VERSION
17957     /* If we might handle TLSv1.3 sessions, we need the callback for session
17958      * resumption; TLSv1.3 prefers stateless session tickets vs stateful
17959      * server-side session IDs.
17960      */
17961     if (SSL_CTX_get_options(ctx) & SSL_OP_NO_TLSv1_3) {
17962       SSL_CTX_set_options(ctx, SSL_OP_NO_TICKET);
17963       SSL_CTX_set_tlsext_ticket_key_cb(ctx, NULL);
17964 
17965     } else {
17966       if (SSL_CTX_set_tlsext_ticket_key_cb(ctx, tls_ticket_key_cb) == 0) {
17967         pr_log_pri(PR_LOG_WARNING, MOD_TLS_VERSION
17968           ": mod_tls compiled with Session Ticket support, but linked to "
17969           "an OpenSSL library without tlsext support, therefore Session "
17970           "Tickets are not available");
17971       }
17972 
17973       SSL_CTX_clear_options(ctx, SSL_OP_NO_TICKET);
17974     }
17975 # else
17976     SSL_CTX_set_options(ctx, SSL_OP_NO_TICKET);
17977     SSL_CTX_set_tlsext_ticket_key_cb(ctx, NULL);
17978 # endif /* TLS1_3_VERSION */
17979   }
17980 #endif /* TLS_USE_SESSION_TICKETS and SSL_OP_NO_TICKET */
17981 
17982   return 0;
17983 }
17984 
17985 static int tls_ctx_set_stapling(SSL_CTX *ctx) {
17986 #if defined(PR_USE_OPENSSL_OCSP)
17987   SSL_CTX_set_tlsext_status_cb(ctx, tls_ocsp_cb);
17988   SSL_CTX_set_tlsext_status_arg(ctx, NULL);
17989 #endif /* PR_USE_OPENSSL_OCSP */
17990 
17991   return 0;
17992 }
17993 
17994 static int tls_ctx_set_stapling_cache(server_rec *s, SSL_CTX *ctx) {
17995 #if defined(PR_USE_OPENSSL_OCSP)
17996   config_rec *c;
17997   const char *provider;
17998 
17999   c = find_config(s->conf, CONF_PARAM, "TLSStaplingCache", FALSE);
18000   if (c == NULL) {
18001     return 0;
18002   }
18003 
18004   /* Look up and initialize the configured OCSP cache provider. */
18005   provider = c->argv[0];
18006 
18007   if (provider != NULL) {
18008     tls_ocsp_cache = tls_ocsp_cache_get_cache(provider);
18009 
18010     pr_log_debug(DEBUG8, MOD_TLS_VERSION ": opening '%s' TLSStaplingCache",
18011       provider);
18012 
18013     if (tls_ocsp_cache_open(c->argv[1]) < 0 &&
18014         errno != ENOSYS) {
18015       pr_log_debug(DEBUG1, MOD_TLS_VERSION
18016         ": error opening '%s' TLSStaplingCache: %s", provider,
18017         strerror(errno));
18018       tls_ocsp_cache = NULL;
18019     }
18020   }
18021 #endif /* PR_USE_OPENSSL_OCSP */
18022 
18023   return 0;
18024 }
18025 
18026 static int tls_ctx_set_verify(SSL_CTX *ctx) {
18027   int verify_mode = 0;
18028 
18029   if (tls_flags & TLS_SESS_VERIFY_CLIENT_OPTIONAL) {
18030     verify_mode = SSL_VERIFY_PEER;
18031   }
18032 
18033   if (tls_flags & TLS_SESS_VERIFY_CLIENT_REQUIRED) {
18034     /* If we are verifying clients, make sure the client sends a cert;
18035      * the protocol allows for the client to disregard a request for
18036      * its cert by the server.
18037      */
18038     verify_mode |= (SSL_VERIFY_PEER|SSL_VERIFY_FAIL_IF_NO_PEER_CERT);
18039   }
18040 
18041   if (verify_mode != 0) {
18042     SSL_CTX_set_verify(ctx, verify_mode, tls_verify_cb);
18043 
18044     /* Note: we add one to the configured depth purposefully.  As noted
18045      * in the OpenSSL man pages, the verification process will silently
18046      * stop at the configured depth, and the error messages ensuing will
18047      * be that of an incomplete certificate chain, rather than the
18048      * "chain too long" error that might be expected.  To log the "chain
18049      * too long" condition, we add one to the configured depth, and catch,
18050      * in the verify callback, the exceeding of the actual depth.
18051      */
18052     SSL_CTX_set_verify_depth(ctx, tls_verify_depth + 1);
18053   }
18054 
18055   return 0;
18056 }
18057 
18058 static int tls_ctx_set_all(server_rec *s, SSL_CTX *ctx) {
18059   X509 *dsa_cert = NULL, *ec_cert = NULL, *rsa_cert = NULL;
18060 
18061   if (tls_ctx_set_pkey(ctx) < 0) {
18062     return -1;
18063   }
18064 
18065   if (tls_ctx_set_ca_certs(ctx) < 0) {
18066     return -1;
18067   }
18068 
18069   if (tls_ctx_set_certs(ctx, &dsa_cert, &ec_cert, &rsa_cert) < 0) {
18070     return -1;
18071   }
18072 
18073   /* Handle a CertificateChainFile.  We need to do this here, after the
18074    * server cert has been loaded, so that we can decide whether the
18075    * CertificateChainFile contains another copy of the server cert (or not).
18076    */
18077   if (tls_ctx_set_cert_chain(ctx, dsa_cert, ec_cert, rsa_cert) < 0) {
18078     return -1;
18079   }
18080 
18081   if (dsa_cert != NULL) {
18082     X509_free(dsa_cert);
18083     dsa_cert = NULL;
18084   }
18085 
18086   if (ec_cert != NULL) {
18087     X509_free(ec_cert);
18088     ec_cert = NULL;
18089   }
18090 
18091   if (rsa_cert != NULL) {
18092     X509_free(rsa_cert);
18093     rsa_cert = NULL;
18094   }
18095 
18096   if (tls_ctx_set_ciphers(ctx) < 0) {
18097     return -1;
18098   }
18099 
18100   if (tls_ctx_set_crls(ctx) < 0) {
18101     return -1;
18102   }
18103 
18104   if (tls_ctx_set_ecdh_curve(ctx) < 0) {
18105     return -1;
18106   }
18107 
18108   if (tls_ctx_set_psks(ctx) < 0) {
18109     return -1;
18110   }
18111 
18112   if (tls_ctx_set_options(ctx) < 0) {
18113     return -1;
18114   }
18115 
18116   if (tls_ctx_set_next_protocol(ctx) < 0) {
18117     return -1;
18118   }
18119 
18120   if (tls_ctx_set_protocol(s, ctx) < 0) {
18121     return -1;
18122   }
18123 
18124   /* Note that we set this after setting the protocol versions, since the
18125    * supported protocol version flags will affect session tickets, due to
18126    * TLSv1.3' use of tickets.
18127    */
18128   if (tls_ctx_set_session_tickets(ctx) < 0) {
18129     return -1;
18130   }
18131 
18132   if (tls_ctx_set_serverinfo(ctx) < 0) {
18133     return -1;
18134   }
18135 
18136   if (tls_ctx_set_stapling(ctx) < 0) {
18137     return -1;
18138   }
18139 
18140   if (tls_ctx_set_verify(ctx) < 0) {
18141     return -1;
18142   }
18143 
18144   return 0;
18145 }
18146 
18147 /* Initialization routines
18148  */
18149 
18150 static int tls_init(void) {
18151   unsigned long openssl_version;
18152 
18153   /* Check that the OpenSSL headers used match the version of the
18154    * OpenSSL library used.
18155    *
18156    * For now, we only log if there is a difference.
18157    */
18158   openssl_version = SSLeay();
18159 
18160   if (openssl_version != OPENSSL_VERSION_NUMBER) {
18161     int unexpected_version_mismatch = TRUE;
18162 
18163     if (OPENSSL_VERSION_NUMBER >= 0x1000000fL) {
18164       /* OpenSSL versions after 1.0.0 try to maintain ABI compatibility.
18165        * So we will warn about header/library version mismatches only if
18166        * the library is older than the headers.
18167        */
18168       if (openssl_version >= OPENSSL_VERSION_NUMBER) {
18169         unexpected_version_mismatch = FALSE;
18170       }
18171     }
18172 
18173     if (unexpected_version_mismatch == TRUE) {
18174       pr_log_pri(PR_LOG_WARNING, MOD_TLS_VERSION
18175         ": compiled using OpenSSL version '%s' headers, but linked to "
18176         "OpenSSL version '%s' library", OPENSSL_VERSION_TEXT,
18177         SSLeay_version(SSLEAY_VERSION));
18178       tls_log("compiled using OpenSSL version '%s' headers, but linked to "
18179         "OpenSSL version '%s' library", OPENSSL_VERSION_TEXT,
18180         SSLeay_version(SSLEAY_VERSION));
18181     }
18182   }
18183 
18184   pr_log_debug(DEBUG2, MOD_TLS_VERSION ": using " OPENSSL_VERSION_TEXT);
18185 
18186 #if defined(PR_SHARED_MODULE)
18187   pr_event_register(&tls_module, "core.module-unload", tls_mod_unload_ev, NULL);
18188 #endif /* PR_SHARED_MODULE */
18189   pr_event_register(&tls_module, "core.postparse", tls_postparse_ev, NULL);
18190   pr_event_register(&tls_module, "core.restart", tls_restart_ev, NULL);
18191   pr_event_register(&tls_module, "core.shutdown", tls_shutdown_ev, NULL);
18192 
18193 #if OPENSSL_VERSION_NUMBER < 0x10100000L
18194   OPENSSL_config(NULL);
18195 #endif /* prior to OpenSSL-1.1.x */
18196   SSL_load_error_strings();
18197   SSL_library_init();
18198 
18199   /* It looks like calling OpenSSL_add_all_algorithms() is necessary for
18200    * handling some algorithms (e.g. PKCS12 files) which are NOT added by
18201    * just calling SSL_library_init().
18202    */
18203   ERR_load_crypto_strings();
18204   OpenSSL_add_all_algorithms();
18205 
18206 #ifdef PR_USE_CTRLS
18207   if (pr_ctrls_register(&tls_module, "tls", "query/tune mod_tls settings",
18208       tls_handle_tls) < 0) {
18209     pr_log_pri(PR_LOG_NOTICE, MOD_TLS_VERSION
18210       ": error registering 'tls' control: %s", strerror(errno));
18211 
18212   } else {
18213     register unsigned int i;
18214 
18215     tls_act_pool = make_sub_pool(permanent_pool);
18216     pr_pool_tag(tls_act_pool, "TLS Controls Pool");
18217 
18218     for (i = 0; tls_acttab[i].act_action; i++) {
18219       tls_acttab[i].act_acl = palloc(tls_act_pool, sizeof(ctrls_acl_t));
18220       pr_ctrls_init_acl(tls_acttab[i].act_acl);
18221     }
18222   }
18223 #endif /* PR_USE_CTRLS */
18224 
18225   return 0;
18226 }
18227 
18228 static int tls_sess_init(void) {
18229   int res = 0;
18230   unsigned char *tmp = NULL;
18231   config_rec *c = NULL;
18232 
18233 #if defined(TLS_USE_SESSION_TICKETS)
18234   lock_ticket_keys();
18235 #endif /* TLS_USE_SESSION_TICKETS */
18236 
18237   pr_event_register(&tls_module, "core.session-reinit", tls_sess_reinit_ev,
18238     NULL);
18239 
18240   /* First, check to see whether mod_tls is even enabled. */
18241   tmp = get_param_ptr(main_server->conf, "TLSEngine", FALSE);
18242   if (tmp != NULL &&
18243       *tmp == TRUE) {
18244     tls_engine = TRUE;
18245   }
18246 
18247   if (tls_engine == FALSE) {
18248     /* If we have no ServerAlias vhosts at all, then it is OK to clean up
18249      * all of the TLS/OpenSSL-related code from this process.  Otherwise,
18250      * a client MIGHT send a HOST command for a TLS-enabled vhost; if we
18251      * were to always cleanup OpenSSL here, that HOST command would inevitably
18252      * lead to a problem.
18253      */
18254 
18255     res = pr_namebind_count(main_server);
18256     if (res == 0) {
18257       /* No need for this module's control channel NetIO handlers anymore. */
18258       pr_unregister_netio(PR_NETIO_STRM_CTRL);
18259 
18260       /* No need for all the OpenSSL stuff in this process space, either. */
18261       tls_cleanup(TLS_CLEANUP_FL_SESS_INIT);
18262       tls_scrub_pkeys();
18263     }
18264 
18265     return 0;
18266   }
18267 
18268   /* Open the TLSLog, if configured */
18269   res = tls_openlog();
18270   if (res < 0) {
18271     if (res == -1) {
18272       pr_log_pri(PR_LOG_NOTICE, MOD_TLS_VERSION
18273         ": notice: unable to open TLSLog: %s", strerror(errno));
18274 
18275     } else if (res == PR_LOG_WRITABLE_DIR) {
18276       pr_log_pri(PR_LOG_WARNING, MOD_TLS_VERSION
18277         ": notice: unable to open TLSLog: parent directory is world-writable");
18278 
18279     } else if (res == PR_LOG_SYMLINK) {
18280       pr_log_pri(PR_LOG_WARNING, MOD_TLS_VERSION
18281         ": notice: unable to open TLSLog: cannot log to a symbolic link");
18282     }
18283   }
18284 
18285   tls_lookup_all(main_server);
18286 
18287   /* Check to see if a passphrase has been entered for this server. */
18288   tls_pkey = tls_lookup_pkey(main_server, TRUE, FALSE);
18289 
18290   if (tls_ctx_set_all(main_server, ssl_ctx) < 0) {
18291     tls_log("%s", "error initializing OpenSSL context for this session");
18292     return -1;
18293   }
18294 
18295 #if !defined(OPENSSL_NO_TLSEXT) && defined(TLSEXT_MAXLEN_host_name)
18296   SSL_CTX_set_tlsext_servername_callback(ssl_ctx, tls_sni_cb);
18297   SSL_CTX_set_tlsext_servername_arg(ssl_ctx, NULL);
18298 #endif /* !OPENSSL_NO_TLSEXT */
18299 
18300 #if defined(PR_USE_OPENSSL_SSL_SESSION_TICKET_CALLBACK)
18301   /* Generate random ticket appdata that will uniquely (hopefully) identify
18302    * this particular FTP session.
18303    *
18304    * Note that we only want to do this once, so that the identifying data
18305    * does not change across SNI/HOST.
18306    */
18307   if (tls_ctrl_ticket_appdatasz == 0) {
18308     tls_ctrl_ticket_appdatasz = tls_data_ticket_appdatasz = 32;
18309 
18310     if (tls_ctrl_ticket_appdata == NULL) {
18311       tls_ctrl_ticket_appdata = palloc(session.pool,
18312         tls_ctrl_ticket_appdatasz);
18313     }
18314 
18315     /* Allocate space for the data connection ticket appdata as well; we
18316      * only need one buffer for this.
18317      */
18318     if (tls_data_ticket_appdata == NULL) {
18319       tls_data_ticket_appdata = palloc(session.pool,
18320         tls_data_ticket_appdatasz);
18321     }
18322 
18323     if (RAND_bytes((unsigned char *) tls_ctrl_ticket_appdata,
18324         tls_ctrl_ticket_appdatasz) != 1) {
18325       tls_log("error generating %lu bytes of random ticket appdata: %s",
18326         (unsigned long) tls_ctrl_ticket_appdatasz, tls_get_errors());
18327       tls_ctrl_ticket_appdata_len = 0;
18328 
18329     } else {
18330       tls_ctrl_ticket_appdata_len = tls_ctrl_ticket_appdatasz;
18331     }
18332   }
18333 #endif /* PR_USE_OPENSSL_SSL_SESSION_TICKET_CALLBACK */
18334 
18335   /* We need to check for FIPS mode in the child process as well, in order
18336    * to re-seed the FIPS PRNG for this process ID.  Annoying, isn't it?
18337    */
18338   if (ServerType == SERVER_STANDALONE) {
18339     if (tls_set_fips() < 0) {
18340       return -1;
18341     }
18342   }
18343 
18344 #if OPENSSL_VERSION_NUMBER > 0x000907000L
18345   /* Handle any requested crypto accelerators/drivers. */
18346   c = find_config(main_server->conf, CONF_PARAM, "TLSCryptoDevice", FALSE);
18347   if (c != NULL) {
18348     tls_crypto_device = (const char *) c->argv[0];
18349 
18350     if (strncasecmp(tls_crypto_device, "ALL", 4) == 0) {
18351       /* Load all ENGINE implementations bundled with OpenSSL. */
18352       ENGINE_load_builtin_engines();
18353       ENGINE_register_all_complete();
18354 #if OPENSSL_VERSION_NUMBER < 0x10100000L
18355       OPENSSL_config(NULL);
18356 #endif /* prior to OpenSSL-1.1.x */
18357 
18358       tls_log("%s", "enabled all builtin crypto devices");
18359 
18360     } else {
18361       ENGINE *e;
18362 
18363       /* Load all ENGINE implementations bundled with OpenSSL. */
18364       ENGINE_load_builtin_engines();
18365 #if OPENSSL_VERSION_NUMBER < 0x10100000L
18366       OPENSSL_config(NULL);
18367 #endif /* prior to OpenSSL-1.1.x */
18368 
18369       e = ENGINE_by_id(tls_crypto_device);
18370       if (e != NULL) {
18371         if (ENGINE_init(e)) {
18372           if (ENGINE_set_default(e, ENGINE_METHOD_ALL)) {
18373             ENGINE_finish(e);
18374             ENGINE_free(e);
18375 
18376             tls_log("using TLSCryptoDevice '%s'", tls_crypto_device);
18377 
18378           } else {
18379             /* The requested driver could not be used as the default for
18380              * some odd reason.
18381              */
18382             tls_log("unable to register TLSCryptoDevice '%s' as the "
18383               "default: %s", tls_crypto_device, tls_get_errors());
18384 
18385             ENGINE_finish(e);
18386             ENGINE_free(e);
18387             e = NULL;
18388             tls_crypto_device = NULL;
18389           }
18390 
18391         } else {
18392           /* The requested driver could not be initialized. */
18393           tls_log("unable to initialize TLSCryptoDevice '%s': %s",
18394             tls_crypto_device, tls_get_errors());
18395 
18396           ENGINE_free(e);
18397           e = NULL;
18398           tls_crypto_device = NULL;
18399         }
18400 
18401       } else {
18402         /* The requested driver is not available. */
18403         tls_log("TLSCryptoDevice '%s' is not available", tls_crypto_device);
18404         tls_crypto_device = NULL;
18405       }
18406     }
18407   }
18408 #endif
18409 
18410   /* Install our data channel NetIO handlers. */
18411   tls_netio_install_data();
18412 
18413   pr_event_register(&tls_module, "core.exit", tls_exit_ev, NULL);
18414 
18415   /* There are several timeouts which can cause the client to be disconnected;
18416    * register a listener for them which can politely/cleanly shut the SSL/TLS
18417    * session down before the connection is closed.
18418    */
18419   pr_event_register(&tls_module, "core.timeout-idle", tls_timeout_ev, NULL);
18420   pr_event_register(&tls_module, "core.timeout-login", tls_timeout_ev, NULL);
18421   pr_event_register(&tls_module, "core.timeout-no-transfer", tls_timeout_ev,
18422     NULL);
18423   pr_event_register(&tls_module, "core.timeout-session", tls_timeout_ev, NULL);
18424   pr_event_register(&tls_module, "core.timeout-stalled", tls_timeout_ev, NULL);
18425 
18426   /* Add the additional features implemented by this module into the
18427    * list, to be displayed in response to a FEAT command.
18428    */
18429   pr_feat_add("AUTH TLS");
18430   pr_feat_add("CCC");
18431   pr_feat_add("PBSZ");
18432   pr_feat_add("PROT");
18433   pr_feat_add("SSCN");
18434 
18435   /* Add the commands handled by this module to the HELP list. */
18436   pr_help_add(C_AUTH, _("<sp> base64-data"), TRUE);
18437   pr_help_add(C_PBSZ, _("<sp> protection buffer size"), TRUE);
18438   pr_help_add(C_PROT, _("<sp> protection code"), TRUE);
18439 
18440   if (tls_opts & TLS_OPT_USE_IMPLICIT_SSL) {
18441     uint64_t start_ms;
18442 
18443     tls_log("%s", "TLSOption UseImplicitSSL in effect, starting SSL/TLS "
18444       "handshake");
18445 
18446     if (pr_trace_get_level(timing_channel) > 0) {
18447       pr_gettimeofday_millis(&start_ms);
18448     }
18449 
18450     if (tls_accept(session.c, FALSE) < 0) {
18451       tls_log("%s", "implicit SSL/TLS negotiation failed on control channel");
18452 
18453       errno = EACCES;
18454       return -1;
18455     }
18456 
18457     tls_flags |= TLS_SESS_ON_CTRL;
18458 
18459     if (tls_required_on_data != -1) {
18460       tls_flags |= TLS_SESS_NEED_DATA_PROT;
18461     }
18462 
18463     if (pr_trace_get_level(timing_channel) >= 4) {
18464       unsigned long elapsed_ms;
18465       uint64_t finish_ms;
18466 
18467       pr_gettimeofday_millis(&finish_ms);
18468 
18469       elapsed_ms = (unsigned long) (finish_ms - session.connect_time_ms);
18470       pr_trace_msg(timing_channel, 4,
18471         "Time before TLS ctrl handshake: %lu ms", elapsed_ms);
18472 
18473       elapsed_ms = (unsigned long) (finish_ms - start_ms);
18474       pr_trace_msg(timing_channel, 4,
18475         "TLS ctrl handshake duration: %lu ms", elapsed_ms);
18476     }
18477 
18478     pr_session_set_protocol("ftps");
18479     session.rfc2228_mech = "TLS";
18480   }
18481 
18482   return 0;
18483 }
18484 
18485 #ifdef PR_USE_CTRLS
18486 static ctrls_acttab_t tls_acttab[] = {
18487   { "clear", NULL, NULL, NULL },
18488   { "info", NULL, NULL, NULL },
18489   { "ocspcache", NULL, NULL, NULL },
18490   { "sesscache", NULL, NULL, NULL },
18491 
18492   { NULL, NULL, NULL, NULL }
18493 };
18494 
18495 #endif /* PR_USE_CTRLS */
18496 
18497 /* Module API tables
18498  */
18499 
18500 static conftable tls_conftab[] = {
18501   { "TLSCACertificateFile",	set_tlscacertfile,	NULL },
18502   { "TLSCACertificatePath",	set_tlscacertpath,	NULL },
18503   { "TLSCARevocationFile",      set_tlscacrlfile,       NULL },
18504   { "TLSCARevocationPath",      set_tlscacrlpath,       NULL },
18505   { "TLSCertificateChainFile",	set_tlscertchain,	NULL },
18506   { "TLSCipherSuite",		set_tlsciphersuite,	NULL },
18507   { "TLSControlsACLs",		set_tlsctrlsacls,	NULL },
18508   { "TLSCryptoDevice",		set_tlscryptodevice,	NULL },
18509   { "TLSDHParamFile",		set_tlsdhparamfile,	NULL },
18510   { "TLSDSACertificateFile",	set_tlsdsacertfile,	NULL },
18511   { "TLSDSACertificateKeyFile",	set_tlsdsakeyfile,	NULL },
18512   { "TLSECCertificateFile",	set_tlseccertfile,	NULL },
18513   { "TLSECCertificateKeyFile",	set_tlseckeyfile,	NULL },
18514   { "TLSECDHCurve",		set_tlsecdhcurve,	NULL },
18515   { "TLSEngine",		set_tlsengine,		NULL },
18516   { "TLSLog",			set_tlslog,		NULL },
18517   { "TLSMasqueradeAddress",	set_tlsmasqaddr,	NULL },
18518   { "TLSNextProtocol",		set_tlsnextprotocol,	NULL },
18519   { "TLSOptions",		set_tlsoptions,		NULL },
18520   { "TLSPassPhraseProvider",	set_tlspassphraseprovider, NULL },
18521   { "TLSPKCS12File", 		set_tlspkcs12file,	NULL },
18522   { "TLSPreSharedKey",		set_tlspresharedkey,	NULL },
18523   { "TLSProtocol",		set_tlsprotocol,	NULL },
18524   { "TLSRandomSeed",		set_tlsrandseed,	NULL },
18525   { "TLSRenegotiate",		set_tlsrenegotiate,	NULL },
18526   { "TLSRequired",		set_tlsrequired,	NULL },
18527   { "TLSRSACertificateFile",	set_tlsrsacertfile,	NULL },
18528   { "TLSRSACertificateKeyFile",	set_tlsrsakeyfile,	NULL },
18529   { "TLSServerCipherPreference",set_tlsservercipherpreference, NULL },
18530   { "TLSServerInfoFile",	set_tlsserverinfofile,	NULL },
18531   { "TLSSessionCache",		set_tlssessioncache,	NULL },
18532   { "TLSSessionTicketKeys",	set_tlssessionticketkeys, NULL },
18533   { "TLSSessionTickets",	set_tlssessiontickets,	NULL },
18534   { "TLSStapling",		set_tlsstapling,	NULL },
18535   { "TLSStaplingCache",		set_tlsstaplingcache,	NULL },
18536   { "TLSStaplingOptions",	set_tlsstaplingoptions,	NULL },
18537   { "TLSStaplingResponder",	set_tlsstaplingresponder, NULL },
18538   { "TLSStaplingTimeout",	set_tlsstaplingtimeout,	NULL },
18539   { "TLSTimeoutHandshake",	set_tlstimeouthandshake,NULL },
18540   { "TLSUserName",		set_tlsusername,	NULL },
18541   { "TLSVerifyClient",		set_tlsverifyclient,	NULL },
18542   { "TLSVerifyDepth",		set_tlsverifydepth,	NULL },
18543   { "TLSVerifyOrder",		set_tlsverifyorder,	NULL },
18544   { "TLSVerifyServer",		set_tlsverifyserver,	NULL },
18545   { NULL , NULL, NULL}
18546 };
18547 
18548 static cmdtable tls_cmdtab[] = {
18549   { PRE_CMD,	C_ANY,	G_NONE,	tls_any,	FALSE,	FALSE },
18550   { CMD,	C_AUTH,	G_NONE,	tls_auth,	FALSE,	FALSE,	CL_SEC },
18551   { CMD,	C_CCC,	G_NONE,	tls_ccc,	TRUE,	FALSE,	CL_SEC },
18552   { CMD,	C_PBSZ,	G_NONE,	tls_pbsz,	FALSE,	FALSE,	CL_SEC },
18553   { CMD,	C_PROT,	G_NONE,	tls_prot,	FALSE,	FALSE,	CL_SEC },
18554   { CMD,	"SSCN",	G_NONE,	tls_sscn,	TRUE,	FALSE,	CL_SEC },
18555   { POST_CMD,	C_PASS,	G_NONE,	tls_post_pass,	FALSE,	FALSE },
18556   { POST_CMD,	C_AUTH,	G_NONE,	tls_post_auth,	FALSE,	FALSE },
18557   { LOG_CMD,	C_AUTH,	G_NONE,	tls_log_auth,	FALSE,	FALSE },
18558   { LOG_CMD_ERR,C_AUTH,	G_NONE,	tls_log_auth,	FALSE,	FALSE },
18559   { 0,	NULL }
18560 };
18561 
18562 static authtable tls_authtab[] = {
18563   { 0, "auth",			tls_authenticate	},
18564   { 0, "check",			tls_auth_check		},
18565   { 0, "requires_pass",		tls_authenticate	},
18566   { 0, NULL }
18567 };
18568 
18569 module tls_module = {
18570 
18571   /* Always NULL */
18572   NULL, NULL,
18573 
18574   /* Module API version */
18575   0x20,
18576 
18577   /* Module name */
18578   "tls",
18579 
18580   /* Module configuration handler table */
18581   tls_conftab,
18582 
18583   /* Module command handler table */
18584   tls_cmdtab,
18585 
18586   /* Module authentication handler table */
18587   tls_authtab,
18588 
18589   /* Module initialization */
18590   tls_init,
18591 
18592   /* Session initialization */
18593   tls_sess_init,
18594 
18595   /* Module version */
18596   MOD_TLS_VERSION
18597 };
18598 
18599