Debian Codegraph @

src/ctx.c

raw
1 /*
2 * stunnel TLS offloading and load-balancing proxy
3 * Copyright (C) 1998-2026 Michal Trojnara <[email protected]>
4 *
5 * This program is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License as published by the
7 * Free Software Foundation; either version 2 of the License, or (at your
8 * option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
13 * See the GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, see <http://www.gnu.org/licenses>.
17 *
18 * Linking stunnel statically or dynamically with other modules is making
19 * a combined work based on stunnel. Thus, the terms and conditions of
20 * the GNU General Public License cover the whole combination.
21 *
22 * In addition, as a special exception, the copyright holder of stunnel
23 * gives you permission to combine stunnel with free software programs or
24 * libraries that are released under the GNU LGPL and with code included
25 * in the standard release of OpenSSL under the OpenSSL License (or
26 * modified versions of such code, with unchanged license). You may copy
27 * and distribute such a system following the terms of the GNU GPL for
28 * stunnel and the licenses of the other code concerned.
29 *
30 * Note that people who make modified versions of stunnel are not obligated
31 * to grant this special exception for their modified versions; it is their
32 * choice whether to do so. The GNU General Public License gives permission
33 * to release a modified version without this exception; this exception
34 * also makes it possible to release a modified version which carries
35 * forward this exception.
36 */
37
38 #include "prototypes.h"
39
40 #define MAX_ERRORS 10
41 #define MAX_ERROR_LEN 256
42
43 #if defined(__GNUC__) && defined(USE_WIN32)
44 #pragma GCC diagnostic ignored "-Wformat"
45 #endif /* defined(__GNUC__) && defined(USE_WIN32) */
46
47 SERVICE_OPTIONS *current_section=NULL;
48
49 #if OPENSSL_VERSION_NUMBER<0x10101000L
50 /* try an empty passphrase first */
51 static char cached_passwd[PEM_BUFSIZE]="";
52 static int cached_len=0;
53 #endif /* OpenSSL older than 1.1.1 */
54 typedef struct {
55 const char *password;
56 const char *prompt_info;
57 } PW_CB_DATA;
58
59 #if !defined(OPENSSL_NO_ENGINE) || OPENSSL_VERSION_NUMBER>=0x10101000L
60 UI_METHOD *ui_stunnel=NULL;
61 #endif /* !defined(OPENSSL_NO_ENGINE) || OPENSSL_VERSION_NUMBER>=0x10101000L */
62
63 #ifndef OPENSSL_NO_DH
64 DH *dh_params=NULL;
65 int dh_temp_params=0;
66 #endif /* OPENSSL_NO_DH */
67
68 /**************************************** prototypes */
69
70 /* SNI */
71 #ifndef OPENSSL_NO_TLSEXT
72 NOEXPORT int servername_cb(SSL *, int *, void *);
73 NOEXPORT int matches_wildcard(const char *, const char *);
74 #endif
75
76 /* DH/ECDH */
77 #ifndef OPENSSL_NO_DH
78 NOEXPORT int dh_init(SERVICE_OPTIONS *);
79 #if OPENSSL_VERSION_NUMBER>=0x10101000L
80 NOEXPORT DH *dh_load_from_store(const char *uri);
81 #else /* OpenSSL 1.1.1 or later */
82 NOEXPORT DH *dh_read(char *);
83 #endif /* OpenSSL 1.1.1 or later */
84 #endif /* OPENSSL_NO_DH */
85 #ifndef OPENSSL_NO_ECDH
86 NOEXPORT int ecdh_init(SERVICE_OPTIONS *);
87 #endif /* USE_ECDH */
88
89 /* configuration commands */
90 NOEXPORT int conf_init(SERVICE_OPTIONS *section);
91
92 /* authentication */
93 NOEXPORT int auth_init(SERVICE_OPTIONS *);
94 #ifndef OPENSSL_NO_PSK
95 NOEXPORT unsigned psk_client_callback(SSL *, const char *,
96 char *, unsigned, unsigned char *, unsigned);
97 NOEXPORT unsigned psk_server_callback(SSL *, const char *,
98 unsigned char *, unsigned);
99 #endif /* !defined(OPENSSL_NO_PSK) */
100
101 #if OPENSSL_VERSION_NUMBER>=0x10101000L
102 NOEXPORT int load_objects(SERVICE_OPTIONS *, int *, int *);
103 NOEXPORT int load_objects_from_store(SSL_CTX *, const char *, int *, int *);
104 #else /* OpenSSL 1.1.1 or later */
105 NOEXPORT int load_cert_file(SERVICE_OPTIONS *, const char *, int *);
106 NOEXPORT int load_key_file(SERVICE_OPTIONS *, const char *, int *);
107 NOEXPORT int pkcs12_extension(const char *);
108 NOEXPORT int load_pkcs12_file(SERVICE_OPTIONS *, const char *, int *, int *);
109 NOEXPORT int cache_passwd_get_cb(char *, int, int, void *);
110 NOEXPORT int cache_passwd_set_cb(char *, int, int, void *);
111 NOEXPORT void set_prompt(const char *);
112 #endif /* OpenSSL 1.1.1 or later */
113
114 #ifndef OPENSSL_NO_ENGINE
115 NOEXPORT int load_cert_engine(SERVICE_OPTIONS *, const char *, int *);
116 NOEXPORT int load_key_engine(SERVICE_OPTIONS *, const char *, int *);
117 #endif
118
119 NOEXPORT int ui_retry(void);
120
121 /* session tickets */
122 #if OPENSSL_VERSION_NUMBER >= 0x10101000L
123 NOEXPORT int generate_session_ticket_cb(SSL *, void *);
124 NOEXPORT int decrypt_session_ticket_cb(SSL *, SSL_SESSION *,
125 const unsigned char *, size_t, SSL_TICKET_STATUS, void *);
126 #endif /* OpenSSL 1.1.1 or later */
127
128 #if OPENSSL_VERSION_NUMBER>=0x10000000L
129 NOEXPORT int ssl_tlsext_ticket_key_cb(SSL *, unsigned char *,
130 unsigned char *, EVP_CIPHER_CTX *, HMAC_CTX *, int);
131 #endif /* OpenSSL 1.0.0 or later */
132
133 /* session callbacks */
134 NOEXPORT int sess_new_cb(SSL *, SSL_SESSION *);
135 NOEXPORT void new_chain(CLI *);
136 NOEXPORT void session_cache_save(CLI *, SSL_SESSION *);
137 #if OPENSSL_VERSION_NUMBER<0x10101000L
138 NOEXPORT SSL_SESSION *SSL_SESSION_dup(SSL_SESSION *);
139 #endif
140 NOEXPORT SSL_SESSION *sess_get_cb(SSL *,
141 #if OPENSSL_VERSION_NUMBER>=0x10100000L
142 const
143 #endif
144 unsigned char *, int, int *);
145 NOEXPORT void sess_remove_cb(SSL_CTX *, SSL_SESSION *);
146
147 /* sessiond interface */
148 NOEXPORT void cache_new(SSL *, SSL_SESSION *);
149 NOEXPORT SSL_SESSION *cache_get(SSL *, const unsigned char *, int);
150 NOEXPORT void cache_remove(SSL_CTX *, SSL_SESSION *);
151 NOEXPORT void cache_transfer(SSL_CTX *, const u_char, const long,
152 const u_char *, const size_t,
153 const u_char *, const size_t,
154 unsigned char **, size_t *);
155
156 /* info callbacks */
157 NOEXPORT void info_callback(const SSL *, int, int);
158
159 #ifndef OPENSSL_NO_TLS1_3
160 NOEXPORT char *compare_cipher_lists(STACK_OF(SSL_CIPHER) *, STACK_OF(SSL_CIPHER) *);
161 NOEXPORT char *get_tls13_cipher_list(STACK_OF(SSL_CIPHER) *);
162 #endif /* TLS 1.3 */
163
164 /**************************************** global initialization and cleanup */
165
166 #if !defined(OPENSSL_NO_ENGINE) || OPENSSL_VERSION_NUMBER>=0x10101000L
167
168 NOEXPORT void clear_cached_password(PW_CB_DATA *cb_data) {
169 char *previous=(char *)cb_data->password;
170
171 cb_data->password=NULL;
172 if(previous) {
173 OPENSSL_cleanse(previous, strlen(previous));
174 str_free(previous);
175 }
176 }
177
178 #if OPENSSL_VERSION_NUMBER>=0x10000000L
179 NOEXPORT char *ui_prompt_constructor(UI *ui,
180 const char *phrase_desc, const char *object_name) {
181 PW_CB_DATA *cb_data=UI_get0_user_data(ui);
182
183 if(!phrase_desc) {
184 if(cb_data->prompt_info && is_prefix(cb_data->prompt_info, "pkcs11:"))
185 phrase_desc="PIN";
186 else
187 phrase_desc="passphrase";
188 }
189 if(!object_name && cb_data)
190 object_name=cb_data->prompt_info;
191 return UI_construct_prompt(NULL, phrase_desc, object_name);
192 }
193 #endif /* OPENSSL_VERSION_NUMBER>=0x10000000L */
194
195 NOEXPORT int ui_caching_reader(UI *ui, UI_STRING *uis) {
196 PW_CB_DATA *cb_data=UI_get0_user_data(ui);
197 int (*reader)(UI *, UI_STRING *);
198
199 /* NOTE: NULL cb_data value indicates a password that is not supposed
200 * to be cached, such as a CKA_ALWAYS_AUTHENTICATE PIN in PKCS#11 */
201
202 /* return the cached password if available */
203 if(cb_data && cb_data->password) {
204 /* Set user_data password */
205 if(UI_set_result(ui, uis, cb_data->password) < 0)
206 s_log(LOG_DEBUG, "Failed to set the cached password");
207 else
208 return 1; /* OK */
209 }
210
211 reader=ui_get_reader();
212 if(reader) { /* invoke the UI if available */
213 const char *result;
214
215 if(!reader(ui, uis))
216 return 0; /* FAILED */
217 result=UI_get0_result_string(uis);
218
219 /* cache a non-empty result if storage is available */
220 if(result && *result && cb_data) {
221 clear_cached_password(cb_data);
222 cb_data->password=str_dup(result);
223 s_log(LOG_DEBUG, "Password cached");
224 }
225 } else { /* default to the empty password if we've got nothing better */
226 s_log(LOG_DEBUG, "No reader available, using empty password");
227 if(UI_set_result(ui, uis, "") < 0) {
228 s_log(LOG_DEBUG, "Failed to set empty password");
229 return 0; /* FAILED */
230 }
231 }
232
233 return 1; /* OK */
234 }
235
236 #endif /* !defined(OPENSSL_NO_ENGINE) || OPENSSL_VERSION_NUMBER>=0x10101000L */
237
238 int ctx_init(void) {
239 #ifndef OPENSSL_NO_DH
240 dh_params=get_dh2048();
241 if(!dh_params) {
242 s_log(LOG_ERR, "Failed to get default DH parameters");
243 return 1; /* FAILED */
244 }
245 #endif /* OPENSSL_NO_DH */
246 #if !defined(OPENSSL_NO_ENGINE) || OPENSSL_VERSION_NUMBER>=0x10101000L
247 ui_stunnel=UI_create_method("stunnel UI");
248 if(!ui_stunnel) {
249 ssl_error(NULL, "UI_create_method");
250 return 1; /* FAILED */
251 }
252 #if OPENSSL_VERSION_NUMBER>=0x10000000L
253 UI_method_set_prompt_constructor(ui_stunnel, ui_prompt_constructor);
254 #endif /* OPENSSL_VERSION_NUMBER>=0x10000000L */
255 UI_method_set_opener(ui_stunnel, ui_get_opener());
256 UI_method_set_writer(ui_stunnel, ui_get_writer());
257 UI_method_set_reader(ui_stunnel, ui_caching_reader);
258 UI_method_set_closer(ui_stunnel, ui_get_closer());
259 #endif /* !defined(OPENSSL_NO_ENGINE) || OPENSSL_VERSION_NUMBER>=0x10101000L */
260 return 0; /* SUCCESS */
261 }
262
263 void ctx_cleanup(void) {
264 #ifndef OPENSSL_NO_DH
265 DH_free(dh_params);
266 #endif
267 #if !defined(OPENSSL_NO_ENGINE) || OPENSSL_VERSION_NUMBER>=0x10101000L
268 UI_destroy_method(ui_stunnel);
269 #endif
270 }
271
272 /**************************************** initialize section->ctx */
273
274 #if OPENSSL_VERSION_NUMBER>=0x10100000L
275 typedef long unsigned SSL_OPTIONS_TYPE;
276 #else
277 typedef long SSL_OPTIONS_TYPE;
278 #endif
279
280 int context_init(SERVICE_OPTIONS *section) { /* init TLS context */
281 s_log(LOG_DEBUG, "Initializing context [%s]", section->servname);
282
283 /* create a new TLS context */
284 #if OPENSSL_VERSION_NUMBER>=0x30000000L
285 section->ctx=SSL_CTX_new_ex(NULL,
286 EVP_default_properties_is_fips_enabled(NULL) ?
287 "fips=yes" : "provider!=fips",
288 section->option.client ?
289 TLS_client_method() : TLS_server_method());
290 #elif OPENSSL_VERSION_NUMBER>=0x10100000L
291 section->ctx=SSL_CTX_new(section->option.client ?
292 TLS_client_method() : TLS_server_method());
293 #else /* OPENSSL_VERSION_NUMBER<0x10100000L */
294 section->ctx=SSL_CTX_new(section->option.client ?
295 section->client_method : section->server_method);
296 #endif
297 if(!section->ctx) {
298 ssl_error(NULL, "SSL_CTX_new");
299 return 1; /* FAILED */
300 }
301
302 /* set supported protocol versions */
303 #if OPENSSL_VERSION_NUMBER>=0x10100000L
304 if(section->min_proto_version &&
305 !SSL_CTX_set_min_proto_version(section->ctx,
306 section->min_proto_version)) {
307 s_log(LOG_ERR, "Failed to set the minimum protocol version 0x%X",
308 section->min_proto_version);
309 return 1; /* FAILED */
310 }
311 if(section->max_proto_version &&
312 !SSL_CTX_set_max_proto_version(section->ctx,
313 section->max_proto_version)) {
314 s_log(LOG_ERR, "Failed to set the maximum protocol version 0x%X",
315 section->max_proto_version);
316 return 1; /* FAILED */
317 }
318 #endif /* OPENSSL_VERSION_NUMBER>=0x10100000L */
319
320 /* allow callbacks to access their SERVICE_OPTIONS structure */
321 if(!SSL_CTX_set_ex_data(section->ctx, index_ssl_ctx_opt, section)) {
322 ssl_error(NULL, "SSL_CTX_set_ex_data");
323 return 1; /* FAILED */
324 }
325 current_section=section; /* setup current section for callbacks */
326
327 #if OPENSSL_VERSION_NUMBER>=0x10100000L
328 /* set the security level */
329 if(section->security_level>=0) {
330 /* set the user-specified value */
331 SSL_CTX_set_security_level(section->ctx, section->security_level);
332 s_log(LOG_INFO, "User-specified security level set: %d",
333 section->security_level);
334 } else if(SSL_CTX_get_security_level(section->ctx)<DEFAULT_SECURITY_LEVEL) {
335 /* set our default, as it is more secure than the OpenSSL default */
336 SSL_CTX_set_security_level(section->ctx, DEFAULT_SECURITY_LEVEL);
337 s_log(LOG_INFO, "stunnel default security level set: %d",
338 DEFAULT_SECURITY_LEVEL);
339 } else { /* our default is not more secure than the OpenSSL default */
340 s_log(LOG_INFO, "OpenSSL security level is used: %d",
341 SSL_CTX_get_security_level(section->ctx));
342 }
343 #endif /* OpenSSL 1.1.0 or later */
344
345 /* ciphers */
346 if(section->cipher_list) {
347 s_log(LOG_DEBUG, "Ciphers: %s", section->cipher_list);
348 if(!SSL_CTX_set_cipher_list(section->ctx, section->cipher_list)) {
349 ssl_error(NULL, "SSL_CTX_set_cipher_list");
350 return 1; /* FAILED */
351 }
352 }
353
354 #ifndef OPENSSL_NO_TLS1_3
355 /* ciphersuites */
356 if(section->ciphersuites) {
357 STACK_OF(SSL_CIPHER) *cipher_list, *tmp_cipher_list;
358 char *tls12_cipher_list, *tls13_cipher_list;
359
360 tmp_cipher_list=sk_SSL_CIPHER_dup(SSL_CTX_get_ciphers(section->ctx));
361 if(!SSL_CTX_set_ciphersuites(section->ctx, section->ciphersuites)) {
362 ssl_error(NULL, "SSL_CTX_set_ciphersuites");
363 return 1; /* FAILED */
364 }
365 cipher_list=SSL_CTX_get_ciphers(section->ctx);
366 tls12_cipher_list=compare_cipher_lists(tmp_cipher_list, cipher_list);
367 sk_SSL_CIPHER_free(tmp_cipher_list);
368 if(tls12_cipher_list) {
369 s_log(LOG_DEBUG, "TLSv1.2 and below ciphers: %s", tls12_cipher_list);
370 str_free(tls12_cipher_list);
371 }
372 tls13_cipher_list=get_tls13_cipher_list(cipher_list);
373 if(tls13_cipher_list) {
374 s_log(LOG_DEBUG, "TLSv1.3 ciphersuites: %s", tls13_cipher_list);
375 str_free(tls13_cipher_list);
376 }
377 }
378 #endif /* TLS 1.3 */
379
380 /* TLS options: configure the stunnel defaults first */
381 SSL_CTX_set_options(section->ctx, SSL_OP_NO_SSLv2|SSL_OP_NO_SSLv3);
382 /* no session ticket gets sent to the client at all in TLSv1.2
383 and below, but a stateful ticket will be sent in TLSv1.3 */
384 #ifdef SSL_OP_NO_TICKET
385 if(!section->option.client && !section->option.session_resume) {
386 SSL_CTX_set_options(section->ctx, SSL_OP_NO_TICKET);
387 }
388 #endif
389 #ifdef SSL_OP_NO_COMPRESSION
390 /* we implemented a better way to disable compression if needed */
391 SSL_CTX_clear_options(section->ctx, SSL_OP_NO_COMPRESSION);
392 #endif /* SSL_OP_NO_COMPRESSION */
393
394 /* TLS options: configure the user-specified values */
395 SSL_CTX_set_options(section->ctx,
396 (SSL_OPTIONS_TYPE)(section->ssl_options_set));
397 #if OPENSSL_VERSION_NUMBER>=0x009080dfL
398 SSL_CTX_clear_options(section->ctx,
399 (SSL_OPTIONS_TYPE)(section->ssl_options_clear));
400 #endif /* OpenSSL 0.9.8m or later */
401
402 /* TLS options: log the configured values */
403 #if OPENSSL_VERSION_NUMBER>=0x009080dfL
404 s_log(LOG_DEBUG,
405 "TLS options: 0x%" PRIX64 " (+0x%" PRIX64 ", -0x%" PRIX64 ")",
406 SSL_CTX_get_options(section->ctx),
407 section->ssl_options_set, section->ssl_options_clear);
408 #else /* OpenSSL older than 0.9.8m */
409 s_log(LOG_DEBUG, "TLS options: 0x%" PRIX64 " (+0x%" PRIX64 ")",
410 SSL_CTX_get_options(section->ctx), section->ssl_options_set);
411 #endif /* OpenSSL 0.9.8m or later */
412
413 /* initialize OpenSSL CONF options */
414 if(conf_init(section))
415 return 1; /* FAILED */
416
417 /* setup mode of operation for the TLS state machine */
418 #ifdef SSL_MODE_RELEASE_BUFFERS
419 SSL_CTX_set_mode(section->ctx,
420 SSL_MODE_ENABLE_PARTIAL_WRITE |
421 SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER |
422 SSL_MODE_RELEASE_BUFFERS);
423 #else
424 SSL_CTX_set_mode(section->ctx,
425 SSL_MODE_ENABLE_PARTIAL_WRITE |
426 SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
427 #endif
428
429 /* setup session tickets */
430 #if OPENSSL_VERSION_NUMBER >= 0x10101000L
431 SSL_CTX_set_session_ticket_cb(section->ctx, generate_session_ticket_cb,
432 decrypt_session_ticket_cb, NULL);
433 #endif /* OpenSSL 1.1.1 or later */
434
435 #if OPENSSL_VERSION_NUMBER>=0x10000000L
436 if((section->ticket_key)&&(section->ticket_mac))
437 SSL_CTX_set_tlsext_ticket_key_cb(section->ctx, ssl_tlsext_ticket_key_cb);
438 #endif /* OpenSSL 1.0.0 or later */
439
440 /* setup session cache */
441 if(!section->option.client) {
442 unsigned servname_len=(unsigned)strlen(section->servname);
443 if(servname_len>SSL_MAX_SSL_SESSION_ID_LENGTH)
444 servname_len=SSL_MAX_SSL_SESSION_ID_LENGTH;
445 #ifndef OPENSSL_NO_TLS1_3
446 /* suppress all tickets (stateful and stateless) in TLSv1.3 */
447 if(!section->option.session_resume && !SSL_CTX_set_num_tickets(section->ctx, 0)) {
448 ssl_error(NULL, "SSL_CTX_set_num_tickets");
449 return 1; /* FAILED */
450 }
451 #endif /* TLS 1.3 */
452 if(!SSL_CTX_set_session_id_context(section->ctx,
453 (unsigned char *)section->servname, servname_len)) {
454 ssl_error(NULL, "SSL_CTX_set_session_id_context");
455 return 1; /* FAILED */
456 }
457 }
458 if(section->option.session_resume) {
459 SSL_CTX_set_session_cache_mode(section->ctx,
460 SSL_SESS_CACHE_BOTH | SSL_SESS_CACHE_NO_INTERNAL_STORE);
461 } else {
462 SSL_CTX_set_session_cache_mode(section->ctx, SSL_SESS_CACHE_OFF);
463 }
464 s_log(LOG_INFO, "Session resumption %s", section->option.session_resume
465 ? "enabled" : "disabled");
466 SSL_CTX_sess_set_cache_size(section->ctx, section->session_size);
467 SSL_CTX_set_timeout(section->ctx, section->session_timeout);
468 SSL_CTX_sess_set_new_cb(section->ctx, sess_new_cb);
469 SSL_CTX_sess_set_get_cb(section->ctx, sess_get_cb);
470 SSL_CTX_sess_set_remove_cb(section->ctx, sess_remove_cb);
471
472 /* set info callback */
473 SSL_CTX_set_info_callback(section->ctx, info_callback);
474
475 /* load certificate and private key to be verified by the peer server */
476 if(auth_init(section))
477 return 1; /* FAILED */
478
479 /* initialize verification of the peer server certificate */
480 if(verify_init(section))
481 return 1; /* FAILED */
482
483 /* OCSP stapling */
484 #ifndef OPENSSL_NO_OCSP
485 if(ocsp_init(section))
486 return 1; /* FAILED */
487 #endif /* OPENSSL_NO_OCSP */
488
489 /* initialize the DH/ECDH key agreement */
490 #ifndef OPENSSL_NO_TLSEXT
491 if(!section->option.client)
492 SSL_CTX_set_tlsext_servername_callback(section->ctx, servername_cb);
493 #endif /* OPENSSL_NO_TLSEXT */
494 #ifndef OPENSSL_NO_DH
495 dh_init(section); /* ignore the result (errors are not critical) */
496 #endif /* OPENSSL_NO_DH */
497 #ifndef OPENSSL_NO_ECDH
498 if(ecdh_init(section))
499 return 1; /* FAILED */
500 #endif /* OPENSSL_NO_ECDH */
501
502 return 0; /* OK */
503 }
504
505 /**************************************** cleanup TLS context */
506
507 /*
508 * free anything allocate from context_init() and callbacks
509 * also free any cached data allocated in client.c
510 */
511 void context_cleanup(SERVICE_OPTIONS *section) {
512 if(section->servname) /* after options_defaults() */
513 s_log(LOG_DEBUG, "Cleaning up context [%s]", section->servname);
514
515 #ifndef OPENSSL_NO_OCSP
516 ocsp_cleanup(section);
517 #endif /* !defined(OPENSSL_NO_OCSP) */
518 str_free(section->chain);
519 if(section->session)
520 SSL_SESSION_free(section->session);
521 if(section->ctx)
522 SSL_CTX_free(section->ctx);
523 }
524
525 /**************************************** SNI callback */
526
527 #ifndef OPENSSL_NO_TLSEXT
528
529 NOEXPORT int servername_cb(SSL *ssl, int *ad, void *arg) {
530 const char *servername=SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
531 CLI *c=SSL_get_ex_data(ssl, index_ssl_cli);
532 SERVERNAME_LIST *list;
533
534 /* leave the alert type at SSL_AD_UNRECOGNIZED_NAME */
535 (void)ad; /* squash the unused parameter warning */
536 (void)arg; /* squash the unused parameter warning */
537
538 /* handle trivial cases first */
539 if(!c->opt->servername_list_head) {
540 s_log(LOG_DEBUG, "SNI: no virtual services defined");
541 return SSL_TLSEXT_ERR_OK;
542 }
543 if(!servername) {
544 s_log(LOG_NOTICE, "SNI: no servername received");
545 return SSL_TLSEXT_ERR_NOACK;
546 }
547
548 /* find a matching section */
549 s_log(LOG_INFO, "SNI: requested servername: %s", servername);
550 for(list=c->opt->servername_list_head; list; list=list->next)
551 if(matches_wildcard(servername, list->servername))
552 break;
553 if(!list) {
554 s_log(LOG_ERR, "SNI: no pattern matched servername: %s", servername);
555 return SSL_TLSEXT_ERR_OK;
556 }
557 s_log(LOG_DEBUG, "SNI: matched pattern: %s", list->servername);
558
559 /* switch to the new section */
560 #ifndef USE_FORK
561 service_up_ref(list->opt);
562 service_free(c->opt);
563 #endif
564 c->opt=list->opt;
565 SSL_set_SSL_CTX(ssl, c->opt->ctx);
566 SSL_set_verify(ssl, SSL_CTX_get_verify_mode(c->opt->ctx),
567 SSL_CTX_get_verify_callback(c->opt->ctx));
568 s_log(LOG_NOTICE, "SNI: switched to service [%s]", c->opt->servname);
569 #ifdef USE_LIBWRAP
570 libwrap_auth(c); /* retry on a service switch */
571 #endif /* USE_LIBWRAP */
572 return SSL_TLSEXT_ERR_OK;
573 }
574 /* TLSEXT callback return codes:
575 * - SSL_TLSEXT_ERR_OK
576 * - SSL_TLSEXT_ERR_ALERT_WARNING
577 * - SSL_TLSEXT_ERR_ALERT_FATAL
578 * - SSL_TLSEXT_ERR_NOACK */
579
580 NOEXPORT int matches_wildcard(const char *servername, const char *pattern) {
581 if(!servername || !pattern)
582 return 0;
583 if(*pattern=='*') { /* wildcard comparison */
584 ssize_t diff=(ssize_t)strlen(servername)-((ssize_t)strlen(pattern)-1);
585 if(diff<0) /* pattern longer than servername */
586 return 0;
587 return !strcasecmp(servername+diff, pattern+1);
588 } else { /* string comparison */
589 return !strcasecmp(servername, pattern);
590 }
591 }
592
593 #endif /* OPENSSL_NO_TLSEXT */
594
595 /**************************************** DH initialization */
596
597 #ifndef OPENSSL_NO_DH
598
599 #if OPENSSL_VERSION_NUMBER<0x10100000L
600
601 /* this is needed for dhparam.c generated with OpenSSL >= 1.1.0
602 * to be linked against the older versions */
603 int DH_set0_pqg(DH *dh, BIGNUM *p, BIGNUM *q, BIGNUM *g) {
604 if(!p || !g) /* q is optional */
605 return 0;
606 BN_free(dh->p);
607 BN_free(dh->q);
608 BN_free(dh->g);
609 dh->p=p;
610 dh->q=q;
611 dh->g=g;
612 if(q)
613 dh->length=BN_num_bits(q);
614 return 1;
615 }
616
617 NOEXPORT STACK_OF(SSL_CIPHER) *SSL_CTX_get_ciphers(const SSL_CTX *ctx) {
618 return ctx->cipher_list;
619 }
620
621 #endif /* OPENSSL_VERSION_NUMBER<0x10100000L */
622
623 NOEXPORT int dh_init(SERVICE_OPTIONS *section) {
624 DH *dh=NULL;
625 int i, n;
626 char description[128];
627 STACK_OF(SSL_CIPHER) *ciphers;
628 NAME_LIST *ptr;
629
630 section->option.dh_temp_params=0; /* disable by default */
631
632 /* check if DH is needed for this section */
633 if(section->option.client) {
634 s_log(LOG_INFO, "DH initialization skipped: client section");
635 return 0; /* OK */
636 }
637 ciphers=SSL_CTX_get_ciphers(section->ctx);
638 if(!ciphers)
639 return 1; /* ERROR (unlikely) */
640 n=sk_SSL_CIPHER_num(ciphers);
641 for(i=0; i<n; ++i) {
642 *description='\0';
643 SSL_CIPHER_description(sk_SSL_CIPHER_value(ciphers, i),
644 description, sizeof description);
645 /* s_log(LOG_INFO, "Ciphersuite: %s", description); */
646 if(strstr(description, " Kx=DH")) {
647 s_log(LOG_INFO, "DH initialization needed for %s",
648 SSL_CIPHER_get_name(sk_SSL_CIPHER_value(ciphers, i)));
649 break;
650 }
651 }
652 if(i==n) { /* no DH ciphers found */
653 s_log(LOG_INFO, "DH initialization skipped: no DH ciphersuites");
654 return 0; /* OK */
655 }
656
657 s_log(LOG_DEBUG, "DH initialization");
658 #ifndef OPENSSL_NO_ENGINE
659 if(!section->engine) /* cert is a file and not an identifier */
660 #endif
661 for(ptr=section->cert; ptr && !dh; ptr=ptr->next) {
662 #if OPENSSL_VERSION_NUMBER>=0x10101000L
663 dh=dh_load_from_store(ptr->name);
664 #else /* OpenSSL 1.1.1 or later */
665 dh=dh_read(ptr->name);
666 #endif /* OpenSSL 1.1.1 or later */
667 }
668 if(dh) {
669 SSL_CTX_set_tmp_dh(section->ctx, dh);
670 s_log(LOG_INFO, "%d-bit DH parameters loaded", 8*DH_size(dh));
671 DH_free(dh);
672 return 0; /* OK */
673 }
674 CRYPTO_THREAD_read_lock(stunnel_locks[LOCK_DH]);
675 SSL_CTX_set_tmp_dh(section->ctx, dh_params);
676 CRYPTO_THREAD_unlock(stunnel_locks[LOCK_DH]);
677 dh_temp_params=1; /* generate temporary DH parameters in cron */
678 section->option.dh_temp_params=1; /* update this section in cron */
679 s_log(LOG_INFO, "Using dynamic DH parameters");
680 return 0; /* OK */
681 }
682
683 #if OPENSSL_VERSION_NUMBER>=0x10101000L
684 NOEXPORT DH *dh_load_from_store(const char *uri)
685 {
686 DH *dh=NULL;
687 OSSL_STORE_CTX *store_ctx=NULL;
688
689 store_ctx=OSSL_STORE_open(uri, NULL, NULL, NULL, NULL);
690 if(!store_ctx)
691 return NULL;
692
693 while(!OSSL_STORE_eof(store_ctx)) {
694 OSSL_STORE_INFO *object=OSSL_STORE_load(store_ctx);
695
696 if(!object)
697 continue;
698 if(OSSL_STORE_INFO_get_type(object) == OSSL_STORE_INFO_PARAMS) {
699 EVP_PKEY *pkey=OSSL_STORE_INFO_get0_PARAMS(object);
700
701 if(pkey) {
702 dh=EVP_PKEY_get1_DH(pkey);
703 if(dh) {
704 OSSL_STORE_INFO_free(object);
705 break; /* found */
706 }
707 }
708 }
709 OSSL_STORE_INFO_free(object);
710 }
711 OSSL_STORE_close(store_ctx);
712 return dh;
713 }
714
715 #else /* OpenSSL 1.1.1 or later */
716 NOEXPORT DH *dh_read(char *cert) {
717 DH *dh;
718 BIO *bio;
719
720 if(!cert) {
721 s_log(LOG_DEBUG, "No certificate available to load DH parameters");
722 return NULL; /* FAILED */
723 }
724 bio=BIO_new_file(cert, "r");
725 if(!bio) {
726 ssl_error(NULL, "BIO_new_file");
727 return NULL; /* FAILED */
728 }
729 dh=PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
730 BIO_free(bio);
731 if(!dh) {
732 while(ERR_get_error())
733 ; /* OpenSSL error queue cleanup */
734 s_log(LOG_DEBUG, "Could not load DH parameters from %s", cert);
735 return NULL; /* FAILED */
736 }
737 s_log(LOG_DEBUG, "Using DH parameters from %s", cert);
738 return dh;
739 }
740 #endif /* OpenSSL 1.1.1 or later */
741
742 #endif /* OPENSSL_NO_DH */
743
744 /**************************************** ECDH initialization */
745
746 #ifndef OPENSSL_NO_ECDH
747
748 #if OPENSSL_VERSION_NUMBER < 0x10101000L
749 /* simplified version that only supports a single curve */
750 NOEXPORT int SSL_CTX_set1_groups_list(SSL_CTX *ctx, char *list) {
751 int nid;
752 EC_KEY *ecdh;
753
754 nid=OBJ_txt2nid(list);
755 if(nid==NID_undef) {
756 s_log(LOG_ERR, "Unsupported curve: %s", list);
757 return 0; /* FAILED */
758 }
759 ecdh=EC_KEY_new_by_curve_name(nid);
760 if(!ecdh) {
761 ssl_error(NULL, "EC_KEY_new_by_curve_name");
762 return 0; /* FAILED */
763 }
764 if(!SSL_CTX_set_tmp_ecdh(ctx, ecdh)) {
765 ssl_error(NULL, "SSL_CTX_set_tmp_ecdhSSL_CTX_set_tmp_ecdh");
766 EC_KEY_free(ecdh);
767 return 0; /* FAILED */
768 }
769 EC_KEY_free(ecdh);
770 return 1; /* OK */
771 }
772 #endif /* OpenSSL version < 1.1.1 */
773
774 NOEXPORT int ecdh_init(SERVICE_OPTIONS *section) {
775 s_log(LOG_DEBUG, "ECDH initialization");
776 if(!SSL_CTX_set1_groups_list(section->ctx, section->curves)) {
777 s_log(LOG_ERR, "Invalid groups list in 'curves'");
778 return 1; /* FAILED */
779 }
780 s_log(LOG_DEBUG, "ECDH initialized with curves %s", section->curves);
781 return 0; /* OK */
782 }
783
784 #endif /* OPENSSL_NO_ECDH */
785
786 /**************************************** initialize OpenSSL CONF */
787
788 NOEXPORT int conf_init(SERVICE_OPTIONS *section) {
789 #if OPENSSL_VERSION_NUMBER>=0x10002000L
790 SSL_CONF_CTX *cctx;
791 NAME_LIST *curr;
792 char *cmd, *param;
793
794 if(!section->config)
795 return 0; /* OK */
796 cctx=SSL_CONF_CTX_new();
797 if(!cctx) {
798 ssl_error(NULL, "SSL_CONF_CTX_new");
799 return 1; /* FAILED */
800 }
801 SSL_CONF_CTX_set_ssl_ctx(cctx, section->ctx);
802 SSL_CONF_CTX_set_flags(cctx, SSL_CONF_FLAG_FILE);
803 SSL_CONF_CTX_set_flags(cctx, section->option.client ?
804 SSL_CONF_FLAG_CLIENT : SSL_CONF_FLAG_SERVER);
805 SSL_CONF_CTX_set_flags(cctx, SSL_CONF_FLAG_CERTIFICATE);
806
807 for(curr=section->config; curr; curr=curr->next) {
808 cmd=str_dup(curr->name);
809 param=strchr(cmd, ':');
810 if(param)
811 *param++='\0';
812 switch(SSL_CONF_cmd(cctx, cmd, param)) {
813 case 2:
814 s_log(LOG_DEBUG, "OpenSSL config \"%s\" set to \"%s\"", cmd, param);
815 break;
816 case 1:
817 s_log(LOG_DEBUG, "OpenSSL config command \"%s\" executed", cmd);
818 break;
819 case -2:
820 s_log(LOG_ERR,
821 "OpenSSL config command \"%s\" was not recognised", cmd);
822 str_free(cmd);
823 SSL_CONF_CTX_free(cctx);
824 return 1; /* FAILED */
825 case -3:
826 s_log(LOG_ERR,
827 "OpenSSL config command \"%s\" requires a parameter", cmd);
828 str_free(cmd);
829 SSL_CONF_CTX_free(cctx);
830 return 1; /* FAILED */
831 default:
832 ssl_error(NULL, "SSL_CONF_cmd");
833 str_free(cmd);
834 SSL_CONF_CTX_free(cctx);
835 return 1; /* FAILED */
836 }
837 str_free(cmd);
838 }
839
840 if(!SSL_CONF_CTX_finish(cctx)) {
841 ssl_error(NULL, "SSL_CONF_CTX_finish");
842 SSL_CONF_CTX_free(cctx);
843 return 1; /* FAILED */
844 }
845 SSL_CONF_CTX_free(cctx);
846 #else /* OpenSSL earlier than 1.0.2 */
847 (void)section; /* squash the unused parameter warning */
848 #endif /* OpenSSL 1.0.2 or later */
849 return 0; /* OK */
850 }
851
852 /**************************************** initialize authentication */
853
854 NOEXPORT int auth_init(SERVICE_OPTIONS *section) {
855 int cert_needed=1, key_needed=1;
856 #if !defined(OPENSSL_NO_ENGINE) || OPENSSL_VERSION_NUMBER<0x10101000L
857 NAME_LIST *ptr;
858 #endif
859
860 /* initialize PSK */
861 #ifndef OPENSSL_NO_PSK
862 if(section->psk_keys) {
863 if(section->option.client)
864 SSL_CTX_set_psk_client_callback(section->ctx, psk_client_callback);
865 else
866 SSL_CTX_set_psk_server_callback(section->ctx, psk_server_callback);
867 }
868 #endif /* !defined(OPENSSL_NO_PSK) */
869
870 /* initialize the client cert engine */
871 #if !defined(OPENSSL_NO_ENGINE) && OPENSSL_VERSION_NUMBER>=0x0090809fL
872 /* SSL_CTX_set_client_cert_engine() was introduced in OpenSSL 0.9.8i */
873 if(section->option.client && section->engine) {
874 if(SSL_CTX_set_client_cert_engine(section->ctx, section->engine)) {
875 s_log(LOG_INFO, "Client certificate engine (%s) enabled",
876 ENGINE_get_id(section->engine));
877 } else { /* no client certificate functionality in this engine */
878 while(ERR_get_error())
879 ; /* OpenSSL error queue cleanup */
880 s_log(LOG_INFO, "Client certificate engine (%s) not supported",
881 ENGINE_get_id(section->engine));
882 }
883 }
884 #endif
885
886 /* certificate and private key are optional in client sections
887 * and in server sections using PSK authentication */
888 if(!section->cert) {
889 s_log(LOG_DEBUG, "No certificate specified");
890 return 0; /* OK */
891 }
892
893 /* load the certificate and private key */
894 #ifndef OPENSSL_NO_ENGINE
895 if(section->engine) { /* try to use the engine first */
896 (void)load_key_engine(section, section->key, &key_needed);
897 for(ptr=section->cert; ptr && cert_needed; ptr=ptr->next) {
898 (void)load_cert_engine(section, ptr->name, &cert_needed);
899 (void)load_key_engine(section, ptr->name, &key_needed);
900 }
901 }
902 #endif
903 #if OPENSSL_VERSION_NUMBER>=0x10101000L
904 if(load_objects(section, &cert_needed, &key_needed))
905 return 1; /* FAILED */
906 #else /* OpenSSL 1.1.1 or later */
907 (void)load_key_file(section, section->key, &key_needed);
908 for(ptr=section->cert; ptr; ptr=ptr->next) {
909 if(pkcs12_extension(ptr->name)) {
910 (void)load_pkcs12_file(section, ptr->name, &cert_needed, &key_needed);
911 } else {
912 (void)load_cert_file(section, ptr->name, &cert_needed);
913 (void)load_key_file(section, ptr->name, &key_needed);
914 }
915 }
916 #endif /* OpenSSL 1.1.1 or later */
917 if(cert_needed || key_needed) {
918 if(cert_needed)
919 s_log(LOG_ERR, "Failed to load certificate");
920 if(key_needed)
921 s_log(LOG_ERR, "Failed to load private key");
922 return 1; /* FAILED */
923 }
924
925 /* validate the private key against the certificate */
926 if(!SSL_CTX_check_private_key(section->ctx)) {
927 ssl_error(NULL, "Private key does not match the certificate");
928 return 1; /* FAILED */
929 }
930 s_log(LOG_DEBUG, "Private key check succeeded");
931 return 0; /* OK */
932 }
933
934 #ifndef OPENSSL_NO_PSK
935
936 NOEXPORT unsigned psk_client_callback(SSL *ssl, const char *hint,
937 char *identity, unsigned max_identity_len,
938 unsigned char *psk, unsigned max_psk_len) {
939 CLI *c;
940 size_t identity_len;
941
942 (void)hint; /* squash the unused parameter warning */
943 c=SSL_get_ex_data(ssl, index_ssl_cli);
944 if(!c->opt->psk_selected) {
945 s_log(LOG_ERR, "INTERNAL ERROR: No PSK identity selected");
946 return 0;
947 }
948 /* the source seems to have its buffer large enough for
949 * the trailing null character, but the manual page says
950 * nothing about it -- lets play safe */
951 identity_len=strlen(c->opt->psk_selected->identity)+1;
952 if(identity_len>max_identity_len) {
953 s_log(LOG_ERR, "PSK identity too long (%lu>%d bytes)",
954 (long unsigned)identity_len, max_psk_len);
955 return 0;
956 }
957 if(c->opt->psk_selected->key_len>max_psk_len) {
958 s_log(LOG_ERR, "PSK too long (%lu>%d bytes)",
959 (long unsigned)c->opt->psk_selected->key_len, max_psk_len);
960 return 0;
961 }
962 strcpy(identity, c->opt->psk_selected->identity);
963 memcpy(psk, c->opt->psk_selected->key_val, c->opt->psk_selected->key_len);
964 s_log(LOG_INFO, "PSK client configured for identity \"%s\"", identity);
965 return (unsigned)(c->opt->psk_selected->key_len);
966 }
967
968 NOEXPORT unsigned psk_server_callback(SSL *ssl, const char *identity,
969 unsigned char *psk, unsigned max_psk_len) {
970 CLI *c;
971 PSK_KEYS *found;
972
973 c=SSL_get_ex_data(ssl, index_ssl_cli);
974 found=psk_find(&c->opt->psk_sorted, identity);
975 if(!found) {
976 const char *c=identity;
977 while(*c && isprint((unsigned char)*c))
978 c++;
979 if(*c)
980 s_log(LOG_INFO, "PSK identity not found (session resumption?)");
981 else
982 s_log(LOG_INFO, "PSK identity not found: %s", identity);
983 return 0;
984 }
985 if(found->key_len>max_psk_len) {
986 s_log(LOG_ERR, "PSK too long (%u>%u)", found->key_len, max_psk_len);
987 return 0;
988 }
989 memcpy(psk, found->key_val, found->key_len);
990 s_log(LOG_NOTICE, "Key configured for PSK identity \"%s\"", identity);
991 c->flag.psk_found=1;
992 return found->key_len;
993 }
994
995 NOEXPORT int psk_compar(const void *a, const void *b) {
996 const PSK_KEYS *x=*(PSK_KEYS *const*)a, *y=*(PSK_KEYS *const*)b;
997
998 #if 0
999 s_log(LOG_DEBUG, "PSK cmp: %s %s", x->identity, y->identity);
1000 #endif
1001 return strcmp(x->identity, y->identity);
1002 }
1003
1004 void psk_sort(PSK_TABLE *table, PSK_KEYS *head) {
1005 PSK_KEYS *curr;
1006 size_t i;
1007
1008 table->num=0;
1009 for(curr=head; curr; curr=curr->next)
1010 ++table->num;
1011 s_log(LOG_INFO, "PSK identities: %lu retrieved",
1012 (long unsigned)table->num);
1013 table->val=str_alloc_detached(table->num*sizeof(PSK_KEYS *));
1014 for(curr=head, i=0; i<table->num; ++i) {
1015 table->val[i]=curr;
1016 curr=curr->next;
1017 }
1018 qsort(table->val, table->num, sizeof(PSK_KEYS *), psk_compar);
1019 #if 0
1020 for(i=0; i<table->num; ++i)
1021 s_log(LOG_DEBUG, "PSK table: %s", table->val[i]->identity);
1022 #endif
1023 }
1024
1025 PSK_KEYS *psk_find(const PSK_TABLE *table, const char *identity) {
1026 PSK_KEYS key, *ptr=&key, **ret;
1027
1028 key.identity=identity;
1029 ret=bsearch(&ptr,
1030 table->val, table->num, sizeof(PSK_KEYS *), psk_compar);
1031 return ret ? *ret : NULL;
1032 }
1033
1034 #endif /* !defined(OPENSSL_NO_PSK) */
1035
1036 #if OPENSSL_VERSION_NUMBER<0x10101000L
1037
1038 NOEXPORT int pkcs12_extension(const char *filename) {
1039 const char *ext=strrchr(filename, '.');
1040 return ext && (!strcasecmp(ext, ".p12") || !strcasecmp(ext, ".pfx"));
1041 }
1042
1043 NOEXPORT int load_pkcs12_file(SERVICE_OPTIONS *section, const char *file,
1044 int *cert_needed, int *key_needed) {
1045 size_t len;
1046 int i, success;
1047 BIO *bio=NULL;
1048 PKCS12 *p12=NULL;
1049 X509 *cert=NULL;
1050 STACK_OF(X509) *ca=NULL;
1051 EVP_PKEY *pkey=NULL;
1052 char pass[PEM_BUFSIZE];
1053
1054 if(!file || !cert_needed || !key_needed || !*key_needed)
1055 return 0; /* skip */
1056
1057 s_log(LOG_INFO, "Loading certificate and private key from file: %s", file);
1058 if(file_permissions(file))
1059 return 1; /* FAILED */
1060
1061 bio=BIO_new_file(file, "rb");
1062 if(!bio) {
1063 ssl_error(NULL, "BIO_new_file");
1064 return 1; /* FAILED */
1065 }
1066 p12=d2i_PKCS12_bio(bio, NULL);
1067 if(!p12) {
1068 ssl_error(NULL, "d2i_PKCS12_bio");
1069 BIO_free(bio);
1070 return 1; /* FAILED */
1071 }
1072 BIO_free(bio);
1073
1074 /* try the cached value first */
1075 set_prompt(file);
1076 len=(size_t)cache_passwd_get_cb(pass, sizeof pass, 0, NULL);
1077 if(len>=sizeof pass)
1078 len=sizeof pass-1;
1079 pass[len]='\0'; /* null-terminate */
1080 success=PKCS12_parse(p12, pass, &pkey, &cert, &ca);
1081
1082 /* invoke the UI */
1083 for(i=0; !success && i<3; i++) {
1084 if(!ui_retry())
1085 break;
1086 if(i>0)
1087 s_log(LOG_ERR, "Wrong passphrase: retrying");
1088
1089 /* invoke the UI on subsequent calls */
1090 len=(size_t)cache_passwd_set_cb(pass, sizeof pass, 0, NULL);
1091 if(len>=sizeof pass)
1092 len=sizeof pass-1;
1093 pass[len]='\0'; /* null-terminate */
1094 success=PKCS12_parse(p12, pass, &pkey, &cert, &ca);
1095 }
1096 if(!success) {
1097 ssl_error(NULL, "PKCS12_parse");
1098 PKCS12_free(p12);
1099 return 1; /* FAILED */
1100 }
1101
1102 PKCS12_free(p12);
1103
1104 if(!SSL_CTX_use_certificate(section->ctx, cert)) {
1105 ssl_error(NULL, "SSL_CTX_use_certificate");
1106 return 1; /* FAILED */
1107 }
1108 *cert_needed=0;
1109 if(!SSL_CTX_use_PrivateKey(section->ctx, pkey)) {
1110 ssl_error(NULL, "SSL_CTX_use_PrivateKey");
1111 return 1; /* FAILED */
1112 }
1113 *key_needed=0;
1114 #if OPENSSL_VERSION_NUMBER>=0x10002000L
1115 if(!SSL_CTX_set0_chain(section->ctx, ca)) {
1116 ssl_error(NULL, "SSL_CTX_set0_chain");
1117 return 1; /* FAILED */
1118 }
1119 #else /* OPENSSL_VERSION_NUMBER>=0x10002000L */
1120 /* FIXME: implement for OpenSSL older than 1.0.2 */
1121 #if 0
1122 /* struct cert_st is private, so the following code won't build */
1123 if(section->ctx->cert->key->chain)
1124 sk_X509_pop_free(section->ctx->cert->key->chain, X509_free);
1125 section->ctx->cert->key->chain=ca;
1126 #endif
1127 sk_X509_pop_free(ca, X509_free); /* just free the memory */
1128 #endif /* OPENSSL_VERSION_NUMBER>=0x10002000L */
1129 s_log(LOG_INFO, "Certificate and private key loaded from file: %s", file);
1130 return 0; /* OK */
1131 }
1132
1133 NOEXPORT int load_cert_file(SERVICE_OPTIONS *section, const char *file, int *cert_needed) {
1134 if(!file)
1135 return 0; /* skip */
1136
1137 if(cert_needed && *cert_needed) {
1138 s_log(LOG_INFO, "Loading certificate from file: %s", file);
1139 /* add the first certificate found in the file to the certificate store,
1140 * clear any existing chain associated with the current certificate of
1141 * ctx, and add the other certs to the store of chain certificates */
1142 if(!SSL_CTX_use_certificate_chain_file(section->ctx, file)) {
1143 ssl_error(NULL, "SSL_CTX_use_certificate_chain_file");
1144 return 1; /* FAILED */
1145 }
1146 *cert_needed=0;
1147 s_log(LOG_INFO, "Certificate loaded from file: %s", file);
1148 } else {
1149 #if OPENSSL_VERSION_NUMBER >= 0x10002000L
1150 X509 *ca;
1151 BIO *bio;
1152
1153 s_log(LOG_DEBUG, "Loading certificate chain from file: %s", file);
1154 bio=BIO_new_file(file, "rb");
1155 if(!bio) {
1156 ssl_error(NULL, "BIO_new_file");
1157 return 1; /* FAILED */
1158 }
1159 ca=X509_new();
1160 if(!ca) {
1161 ssl_error(NULL, "X509_new");
1162 BIO_free(bio);
1163 return 1; /* FAILED */
1164 }
1165 if(!PEM_read_bio_X509(bio, &ca, NULL, NULL)) {
1166 X509_free(ca);
1167 BIO_free(bio);
1168 ssl_error(NULL, "PEM_read_bio_X509");
1169 return 1; /* FAILED */
1170 }
1171 BIO_free(bio);
1172 if(!SSL_CTX_add1_chain_cert(section->ctx, ca)) {
1173 X509_free(ca);
1174 ssl_error(NULL, "SSL_CTX_add1_chain_cert");
1175 return 1; /* FAILED */
1176 }
1177 X509_free(ca);
1178 s_log(LOG_DEBUG, "Certificate chain loaded from file: %s", file);
1179 #else
1180 s_log(LOG_ERR, "Per-cert chain loading requires OpenSSL 1.0.2 or later");
1181 return 1; /* FAILED */
1182 #endif
1183 }
1184 return 0; /* OK */
1185 }
1186
1187 NOEXPORT int load_key_file(SERVICE_OPTIONS *section, const char *file, int *key_needed) {
1188 int i, success;
1189
1190 if(!file || !key_needed || !*key_needed)
1191 return 0; /* skip */
1192
1193 s_log(LOG_INFO, "Loading private key from file: %s", file);
1194 if(file_permissions(file))
1195 return 1; /* FAILED */
1196
1197 /* try the cached value first */
1198 set_prompt(file);
1199 SSL_CTX_set_default_passwd_cb(section->ctx, cache_passwd_get_cb);
1200 success=SSL_CTX_use_PrivateKey_file(section->ctx, file,
1201 SSL_FILETYPE_PEM);
1202 /* invoke the UI on subsequent calls */
1203 SSL_CTX_set_default_passwd_cb(section->ctx, cache_passwd_set_cb);
1204
1205 /* invoke the UI */
1206 for(i=0; !success && i<3; i++) {
1207 if(!ui_retry())
1208 break;
1209 if(i>0)
1210 s_log(LOG_ERR, "Wrong passphrase: retrying");
1211
1212 success=SSL_CTX_use_PrivateKey_file(section->ctx, file,
1213 SSL_FILETYPE_PEM);
1214 }
1215 if(!success) {
1216 ssl_error(NULL, "SSL_CTX_use_PrivateKey_file");
1217 return 1; /* FAILED */
1218 }
1219 *key_needed=0;
1220 s_log(LOG_INFO, "Private key loaded from file: %s", file);
1221 return 0; /* OK */
1222 }
1223
1224 #endif /* OpenSSL older than 1.1.1 */
1225
1226 #ifndef OPENSSL_NO_ENGINE
1227
1228 NOEXPORT int load_cert_engine(SERVICE_OPTIONS *section, const char *file, int *cert_needed) {
1229 X509 *cert;
1230
1231 if(!file || !cert_needed)
1232 return 0; /* skip */
1233
1234 s_log(LOG_INFO, "Loading certificate from engine ID: %s", file);
1235 cert=engine_get_cert(section->engine, file);
1236 if(!cert)
1237 return 1; /* FAILED */
1238 if(!SSL_CTX_use_certificate(section->ctx, cert)) {
1239 ssl_error(NULL, "SSL_CTX_use_certificate");
1240 X509_free(cert);
1241 return 1; /* FAILED */
1242 }
1243 s_log(LOG_INFO, "Certificate loaded from engine ID: %s", file);
1244 X509_free(cert);
1245 *cert_needed=0;
1246 return 0; /* OK */
1247 }
1248
1249 #endif /* !defined(OPENSSL_NO_ENGINE) */
1250
1251 #ifndef OPENSSL_NO_ENGINE
1252
1253 NOEXPORT int load_key_engine(SERVICE_OPTIONS *section, const char *file, int *key_needed) {
1254 int i;
1255 EVP_PKEY *pkey;
1256
1257 if(!file || !key_needed || !*key_needed)
1258 return 0; /* skip */
1259
1260 s_log(LOG_INFO, "Initializing private key on engine ID: %s", file);
1261
1262 /* do not use caching for engine PINs to prevent device lockout */
1263 SSL_CTX_set_default_passwd_cb(section->ctx, ui_passwd_cb);
1264
1265 for(i=0; i<3; i++) {
1266 pkey=ENGINE_load_private_key(section->engine, file,
1267 ui_stunnel, NULL);
1268 if(!pkey) {
1269 if(i<2 && ui_retry()) { /* wrong PIN */
1270 s_log(LOG_ERR, "Wrong PIN: retrying");
1271 continue;
1272 }
1273 ssl_error(NULL, "ENGINE_load_private_key");
1274 return 1; /* FAILED */
1275 }
1276 if(SSL_CTX_use_PrivateKey(section->ctx, pkey))
1277 break; /* success */
1278 ssl_error(NULL, "SSL_CTX_use_PrivateKey");
1279 return 1; /* FAILED */
1280 }
1281 s_log(LOG_INFO, "Private key initialized on engine ID: %s", file);
1282 *key_needed=0;
1283 return 0; /* OK */
1284 }
1285
1286 #endif /* !defined(OPENSSL_NO_ENGINE) */
1287
1288 #if OPENSSL_VERSION_NUMBER>=0x10101000L
1289
1290 NOEXPORT int load_objects(SERVICE_OPTIONS *section, int *cert_needed, int *key_needed) {
1291 NAME_LIST *ptr;
1292
1293 /* Try to open store from section->key resource and get the private key */
1294 if(!load_objects_from_store(section->ctx, section->key, NULL, key_needed))
1295 return 1; /* FAILED */
1296
1297 /* Iterate over the certificate resource list and load certificates/keys from each store */
1298 for(ptr=section->cert; ptr; ptr=ptr->next) {
1299 if(!load_objects_from_store(section->ctx, ptr->name, cert_needed, key_needed))
1300 return 1; /* FAILED */
1301 }
1302 return 0; /* OK */
1303 }
1304
1305 NOEXPORT int load_objects_from_store(SSL_CTX *ctx, const char *uri,
1306 int *cert_needed, int *key_needed) {
1307 static PW_CB_DATA cb_data={NULL, NULL};
1308 int i=0;
1309
1310 if(!uri)
1311 return 1; /* skip */
1312
1313 cb_data.prompt_info=uri;
1314 ERR_clear_error(); /* PROV_R_MISSING_CONFIG_DATA OpenSSL 3.5.0 */
1315 for(;;) {
1316 OSSL_STORE_CTX *store_ctx;
1317
1318 store_ctx=OSSL_STORE_open(uri, ui_stunnel, &cb_data, NULL, NULL);
1319 if(store_ctx) {
1320 while(!OSSL_STORE_eof(store_ctx)) {
1321 OSSL_STORE_INFO *object=OSSL_STORE_load(store_ctx);
1322 int store_type;
1323
1324 if(!object)
1325 continue;
1326 store_type=OSSL_STORE_INFO_get_type(object);
1327 switch(store_type) {
1328 case OSSL_STORE_INFO_PKEY:
1329 if(key_needed && *key_needed) { /* found the first private key */
1330 if(!SSL_CTX_use_PrivateKey(ctx,
1331 OSSL_STORE_INFO_get0_PKEY(object))) {
1332 ssl_error(NULL, "SSL_CTX_use_PrivateKey");
1333 OSSL_STORE_INFO_free(object);
1334 OSSL_STORE_close(store_ctx);
1335 return 0; /* FAILED */
1336 }
1337 s_log(LOG_INFO, "Private key loaded from: %s", uri);
1338 *key_needed=0;
1339 }
1340 /* skip any private keys after the first one was loaded */
1341 break;
1342 case OSSL_STORE_INFO_CERT:
1343 if(cert_needed && *cert_needed) { /* found the first certificate */
1344 if(!SSL_CTX_use_certificate(ctx,
1345 OSSL_STORE_INFO_get0_CERT(object))) {
1346 ssl_error(NULL, "SSL_CTX_use_certificate");
1347 OSSL_STORE_INFO_free(object);
1348 OSSL_STORE_close(store_ctx);
1349 return 0; /* FAILED */
1350 }
1351 s_log(LOG_INFO, "Certificate loaded from: %s", uri);
1352 *cert_needed=0;
1353 } else { /* found a subsequent certificate */
1354 /* add it to the certificate chain */
1355 if(!SSL_CTX_add1_chain_cert(ctx,
1356 OSSL_STORE_INFO_get0_CERT(object))) {
1357 ssl_error(NULL, "SSL_CTX_add1_chain_cert");
1358 OSSL_STORE_INFO_free(object);
1359 OSSL_STORE_close(store_ctx);
1360 return 0; /* FAILED */
1361 }
1362 }
1363 break;
1364 default:
1365 break; /* skip any other type */
1366 }
1367 OSSL_STORE_INFO_free(object);
1368 }
1369 OSSL_STORE_close(store_ctx);
1370 }
1371
1372 if((!key_needed || !*key_needed) && (!cert_needed || !*cert_needed)) {
1373 /* all done */
1374 ERR_clear_error();
1375 return 1; /* OK */
1376 }
1377
1378 /* this attempt has failed, so the cached password
1379 * should not be used for the next attempt */
1380 clear_cached_password(&cb_data);
1381 s_log(LOG_DEBUG, "Cached password cleared");
1382
1383 if(!ui_retry()) { /* process the error queue first */
1384 s_log(LOG_ERR, "Unrecoverable error: giving up");
1385 break;
1386 }
1387
1388 if(++i>=3) { /* allow up to 3 attempts */
1389 s_log(LOG_ERR, "Wrong password or PIN: giving up");
1390 break;
1391 }
1392
1393 s_log(LOG_WARNING, "Wrong password or PIN: retrying");
1394 }
1395 return 0; /* FAILED */
1396 }
1397
1398 #else /* OpenSSL 1.1.1 or later */
1399
1400 /* additional caching layer on top of ui_passwd_cb() */
1401
1402 /* retrieve the cached passwd */
1403 NOEXPORT int cache_passwd_get_cb(char *buf, int size,
1404 int rwflag, void *userdata) {
1405 int len=cached_len;
1406
1407 (void)rwflag; /* squash the unused parameter warning */
1408 (void)userdata; /* squash the unused parameter warning */
1409 if(len<0 || size<0) /* the API uses signed integers */
1410 return 0;
1411 if(len>size) /* truncate the returned data if needed */
1412 len=size;
1413 memcpy(buf, cached_passwd, (size_t)len);
1414 return len;
1415 }
1416
1417 /* cache the passwd retrieved from UI */
1418 NOEXPORT int cache_passwd_set_cb(char *buf, int size,
1419 int rwflag, void *userdata) {
1420 memset(cached_passwd, 0, sizeof cached_passwd);
1421 cached_len=ui_passwd_cb(cached_passwd, sizeof cached_passwd,
1422 rwflag, userdata);
1423 return cache_passwd_get_cb(buf, size, rwflag, userdata);
1424 }
1425
1426 NOEXPORT void set_prompt(const char *name) {
1427 char *prompt;
1428
1429 prompt=str_printf("Enter %s passphrase:", name);
1430 EVP_set_pw_prompt(prompt);
1431 str_free(prompt);
1432 }
1433
1434 #endif /* OpenSSL 1.1.1 or later */
1435
1436 NOEXPORT int ui_retry(void) {
1437 typedef struct {
1438 int lib;
1439 int reason;
1440 } retriable;
1441 const retriable retriables[]={
1442 {ERR_LIB_EVP /* 6 */, EVP_R_BAD_DECRYPT},
1443 {ERR_LIB_PEM /* 9 */, PEM_R_BAD_PASSWORD_READ},
1444 {ERR_LIB_PEM /* 9 */, PEM_R_BAD_DECRYPT},
1445 {ERR_LIB_ASN1 /* 13 */, -1},
1446 {ERR_LIB_PKCS12 /* 35 */, PKCS12_R_MAC_VERIFY_FAILURE},
1447 #ifdef ERR_LIB_DSO
1448 {ERR_LIB_DSO /* 37 */, -1},
1449 #endif
1450 {ERR_LIB_UI /* 40 */, UI_R_RESULT_TOO_LARGE},
1451 {ERR_LIB_UI /* 40 */, UI_R_RESULT_TOO_SMALL},
1452 #ifdef UI_R_PROCESSING_ERROR
1453 {ERR_LIB_UI /* 40 */, UI_R_PROCESSING_ERROR},
1454 #endif
1455 #ifdef ERR_LIB_OSSL_STORE /* OpenSSL 1.1.1 */
1456 {ERR_LIB_OSSL_STORE /* 44 */, OSSL_STORE_R_BAD_PASSWORD_READ},
1457 {ERR_LIB_OSSL_STORE /* 44 */, OSSL_STORE_R_ERROR_VERIFYING_PKCS12_MAC},
1458 #endif
1459 #ifdef ERR_LIB_PROV /* OpenSSL 3.0 */
1460 {ERR_LIB_PROV /* 57 */, PROV_R_BAD_DECRYPT},
1461 #endif
1462 /* libp11 hacks */
1463 {-1 /* libp11 */, 7 /* CKR_ARGUMENTS_BAD */},
1464 {-1 /* libp11 */, 0xa0 /* CKR_PIN_INCORRECT */},
1465 {0, 0}
1466 }, *r;
1467 char *errors[MAX_ERRORS];
1468 char *error_string;
1469 int i, retry=0;
1470
1471 error_string=str_alloc(MAX_ERROR_LEN);
1472 for(i=0; i<MAX_ERRORS; i++) {
1473 unsigned long err=0;
1474 int line=0, flags=0, lib, reason;
1475 const char *file=NULL, *func=NULL, *data=NULL;
1476
1477 /* pop an error from the error stack */
1478 #if OPENSSL_VERSION_NUMBER>=0x30000000L
1479 err=ERR_get_error_all(&file, &line, &func, &data, &flags);
1480 #else
1481 err=ERR_get_error_line(&file, &line);
1482 #endif
1483 if(!err)
1484 break;
1485
1486 /* save the error message for logging */
1487 ERR_error_string_n(err, error_string, MAX_ERROR_LEN);
1488 errors[i]=str_printf("ui_retry: %s%s%s:%d: %s%s%s",
1489 func && *func ? func : "",
1490 func && *func ? "@" : "",
1491 file, line, error_string,
1492 flags&ERR_TXT_STRING && data && *data ? ": " : "",
1493 flags&ERR_TXT_STRING && data && *data ? data : "");
1494
1495 /* check whether this error should be retried */
1496 if(retry)
1497 continue; /* just save the remaining error messages */
1498 lib=ERR_GET_LIB(err);
1499 reason=ERR_GET_REASON(err);
1500 for(r=retriables; r->lib && r->reason; r++) {
1501 if(reason!=r->reason && r->reason!=-1)
1502 continue;
1503 if(lib==r->lib) {
1504 s_log(LOG_DEBUG, "ui_retry: retrying on lib=%d reason=%d",
1505 lib, reason);
1506 retry=1;
1507 break;
1508 }
1509 if(r->lib==-1 && lib>=ERR_LIB_USER &&
1510 !strcmp(ERR_lib_error_string(err), "PKCS#11 module")) {
1511 s_log(LOG_DEBUG, "ui_retry: retrying on lib=PKCS#11 reason=%d",
1512 reason);
1513 retry=1;
1514 break;
1515 }
1516 }
1517 if(retry) /* we just decided to retry */
1518 continue;
1519 s_log(LOG_DEBUG, "ui_retry: giving up on lib=%d reason=%d",
1520 lib, reason);
1521 }
1522 str_free(error_string);
1523 ERR_clear_error(); /* in case more than MAX_ERRORS errors were collected */
1524
1525 if(i==0) { /* there was no error in the queue */
1526 s_log(LOG_ERR, "ui_retry: giving up: No error");
1527 } else { /* log and free the collected error messages */
1528 while(i-->0) {
1529 s_log(LOG_ERR, "%s", errors[i]);
1530 str_free(errors[i]);
1531 }
1532 }
1533
1534 return retry;
1535 }
1536
1537 /**************************************** session tickets */
1538
1539 #if OPENSSL_VERSION_NUMBER >= 0x10101000L
1540
1541 typedef struct {
1542 void *session_authenticated;
1543 #if 0
1544 SOCKADDR_UNION addr;
1545 #endif
1546 } TICKET_DATA;
1547
1548 NOEXPORT int generate_session_ticket_cb(SSL *ssl, void *arg) {
1549 SSL_SESSION *sess;
1550 TICKET_DATA ticket_data;
1551 #if 0
1552 SOCKADDR_UNION *addr;
1553 #endif
1554 int retval;
1555
1556 (void)arg; /* squash the unused parameter warning */
1557
1558 s_log(LOG_DEBUG, "Generate session ticket callback");
1559
1560 sess=SSL_get1_session(ssl);
1561 if(!sess)
1562 return 0;
1563 memset(&ticket_data, 0, sizeof(TICKET_DATA));
1564
1565 ticket_data.session_authenticated=
1566 SSL_SESSION_get_ex_data(sess, index_session_authenticated);
1567
1568 #if 0
1569 /* TODO: add remote_start() invocation here */
1570 CRYPTO_THREAD_read_lock(stunnel_locks[LOCK_ADDR]);
1571 addr=SSL_SESSION_get_ex_data(sess, index_session_connect_address);
1572 if(addr)
1573 memcpy(&ticket_data.addr, addr, (size_t)addr_len(addr));
1574 CRYPTO_THREAD_unlock(stunnel_locks[LOCK_ADDR]);
1575 #endif
1576
1577 retval=SSL_SESSION_set1_ticket_appdata(sess,
1578 &ticket_data, sizeof(TICKET_DATA));
1579 SSL_SESSION_free(sess);
1580 return retval;
1581 }
1582
1583 NOEXPORT int decrypt_session_ticket_cb(SSL *ssl, SSL_SESSION *sess,
1584 const unsigned char *keyname, size_t keyname_len,
1585 SSL_TICKET_STATUS status, void *arg) {
1586 TICKET_DATA *ticket_data;
1587 size_t ticket_len;
1588
1589 (void)ssl; /* squash the unused parameter warning */
1590 (void)keyname; /* squash the unused parameter warning */
1591 (void)keyname_len; /* squash the unused parameter warning */
1592 (void)arg; /* squash the unused parameter warning */
1593
1594 s_log(LOG_DEBUG, "Decrypt session ticket callback");
1595
1596 switch(status) {
1597 case SSL_TICKET_EMPTY:
1598 case SSL_TICKET_NO_DECRYPT:
1599 return SSL_TICKET_RETURN_IGNORE_RENEW;
1600 case SSL_TICKET_SUCCESS:
1601 case SSL_TICKET_SUCCESS_RENEW:
1602 break;
1603 default:
1604 return SSL_TICKET_RETURN_ABORT;
1605 }
1606
1607 if(!SSL_SESSION_get0_ticket_appdata(sess,
1608 (void **)&ticket_data, &ticket_len)) {
1609 s_log(LOG_WARNING, "Failed to get ticket application data");
1610 return SSL_TICKET_RETURN_IGNORE_RENEW;
1611 }
1612 if(!ticket_data) {
1613 s_log(LOG_WARNING, "Invalid ticket application data value");
1614 return SSL_TICKET_RETURN_IGNORE_RENEW;
1615 }
1616 if(ticket_len != sizeof(TICKET_DATA)) {
1617 s_log(LOG_WARNING, "Invalid ticket application data length");
1618 return SSL_TICKET_RETURN_IGNORE_RENEW;
1619 }
1620
1621 s_log(LOG_INFO, "Decrypted ticket for an authenticated session: %s",
1622 ticket_data->session_authenticated ? "yes" : "no");
1623 SSL_SESSION_set_ex_data(sess, index_session_authenticated,
1624 ticket_data->session_authenticated);
1625
1626 #if 0
1627 if(ticket_data->addr.sa.sa_family) {
1628 char *addr_txt;
1629 SOCKADDR_UNION *old_addr;
1630
1631 addr_txt=s_ntop(&ticket_data->addr, addr_len(&ticket_data->addr));
1632 s_log(LOG_INFO, "Decrypted ticket persistence address: %s", addr_txt);
1633 str_free(addr_txt);
1634 CRYPTO_THREAD_write_lock(stunnel_locks[LOCK_ADDR]);
1635 old_addr=SSL_SESSION_get_ex_data(sess, index_session_connect_address);
1636 if(SSL_SESSION_set_ex_data(sess, index_session_connect_address, &ticket_data->addr)) {
1637 CRYPTO_THREAD_unlock(stunnel_locks[LOCK_ADDR]);
1638 str_free(old_addr); /* NULL pointers are ignored */
1639 } else { /* failed to store ticket_data->addr */
1640 CRYPTO_THREAD_unlock(stunnel_locks[LOCK_ADDR]);
1641 ssl_error(c, "SSL_SESSION_set_ex_data");
1642 }
1643 } else {
1644 s_log(LOG_INFO, "Decrypted ticket did not include a persistence address");
1645 }
1646 #endif
1647
1648 switch(status) {
1649 case SSL_TICKET_SUCCESS:
1650 return SSL_TICKET_RETURN_USE;
1651 case SSL_TICKET_SUCCESS_RENEW:
1652 return SSL_TICKET_RETURN_USE_RENEW;
1653 }
1654 return SSL_TICKET_RETURN_ABORT; /* it should never get executed */
1655 }
1656 #endif
1657
1658 #if OPENSSL_VERSION_NUMBER>=0x10000000L
1659 NOEXPORT int ssl_tlsext_ticket_key_cb(SSL *ssl, unsigned char *key_name,
1660 unsigned char *iv, EVP_CIPHER_CTX *ctx, HMAC_CTX *hctx, int enc) {
1661 CLI *c;
1662 const EVP_CIPHER *cipher;
1663 int iv_len;
1664
1665 (void)key_name; /* squash the unused parameter warning */
1666 s_log(LOG_DEBUG, "Session ticket processing callback");
1667
1668 c=SSL_get_ex_data(ssl, index_ssl_cli);
1669 if(!HMAC_Init_ex(hctx, (const unsigned char *)(c->opt->ticket_mac->key_val),
1670 c->opt->ticket_mac->key_len, EVP_sha256(), NULL)) {
1671 s_log(LOG_ERR, "HMAC_Init_ex failed");
1672 return -1;
1673 }
1674 if(c->opt->ticket_key->key_len == 16)
1675 cipher=EVP_aes_128_cbc();
1676 else /* c->opt->ticket_key->key_len == 32 */
1677 cipher=EVP_aes_256_cbc();
1678 if(enc) { /* create new session */
1679 /* EVP_CIPHER_iv_length() returns 16 for either cipher EVP_aes_128_cbc() or EVP_aes_256_cbc() */
1680 iv_len=EVP_CIPHER_iv_length(cipher);
1681 if(RAND_bytes(iv, iv_len) <= 0) { /* RAND_bytes error */
1682 s_log(LOG_ERR, "RAND_bytes failed");
1683 return -1;
1684 }
1685 if(!EVP_EncryptInit_ex(ctx, cipher, NULL,
1686 (const unsigned char *)(c->opt->ticket_key->key_val), iv)) {
1687 s_log(LOG_ERR, "EVP_EncryptInit_ex failed");
1688 return -1;
1689 }
1690 } else /* retrieve session */
1691 if(!EVP_DecryptInit_ex(ctx, cipher, NULL,
1692 (const unsigned char *)(c->opt->ticket_key->key_val), iv)) {
1693 s_log(LOG_ERR, "EVP_DecryptInit_ex failed");
1694 return -1;
1695 }
1696 /* By default, in TLSv1.2 and below, a new session ticket */
1697 /* is not issued on a successful resumption. */
1698 /* In TLSv1.3 the default behaviour is to always issue a new ticket on resumption. */
1699 /* This behaviour can NOT be changed if this ticket key callback is in use! */
1700 if(strcmp(SSL_get_version(c->ssl), "TLSv1.3"))
1701 return 1; /* new session ticket is not issued */
1702 else
1703 return 2; /* session ticket should be replaced */
1704 }
1705 #endif /* OpenSSL 1.0.0 or later */
1706
1707 /**************************************** session callbacks */
1708
1709 NOEXPORT int sess_new_cb(SSL *ssl, SSL_SESSION *sess) {
1710 CLI *c;
1711
1712 s_log(LOG_DEBUG, "New session callback");
1713 c=SSL_get_ex_data(ssl, index_ssl_cli);
1714
1715 new_chain(c); /* new session -> we may have a new peer certificate chain */
1716
1717 session_cache_save(c, sess);
1718
1719 if(c->opt->option.sessiond)
1720 cache_new(ssl, sess);
1721
1722 print_session_id("Session id", sess);
1723
1724 return 0; /* the OpenSSL's manual is really bad -> use the source here */
1725 }
1726
1727 void print_session_id(const char *txt, SSL_SESSION *sess) {
1728 const unsigned char *session_id;
1729 unsigned int session_id_length;
1730 char session_id_txt[2*SSL_MAX_SSL_SESSION_ID_LENGTH+1];
1731
1732 session_id=SSL_SESSION_get_id(sess, &session_id_length);
1733 bin2hexstring(session_id, session_id_length,
1734 session_id_txt, sizeof session_id_txt);
1735 s_log(LOG_INFO, "%s: %s", txt, session_id_txt);
1736 }
1737
1738 NOEXPORT void new_chain(CLI *c) {
1739 BIO *bio;
1740 int i, len;
1741 X509 *peer_cert;
1742 STACK_OF(X509) *sk;
1743 char *chain;
1744
1745 if(c->opt->chain) /* already cached */
1746 return; /* this race condition is safe to ignore */
1747 bio=BIO_new(BIO_s_mem());
1748 if(!bio)
1749 return;
1750 sk=SSL_get_peer_cert_chain(c->ssl);
1751 for(i=0; sk && i<sk_X509_num(sk); i++) {
1752 peer_cert=sk_X509_value(sk, i);
1753 PEM_write_bio_X509(bio, peer_cert);
1754 }
1755 if(!sk || !c->opt->option.client) {
1756 peer_cert=SSL_get_peer_certificate(c->ssl);
1757 if(peer_cert) {
1758 PEM_write_bio_X509(bio, peer_cert);
1759 X509_free(peer_cert);
1760 }
1761 }
1762 len=BIO_pending(bio);
1763 if(len<=0) {
1764 s_log(LOG_INFO, "No peer certificate received");
1765 BIO_free(bio);
1766 return;
1767 }
1768 /* prevent automatic deallocation of the cached value */
1769 chain=str_alloc_detached((size_t)len+1);
1770 len=BIO_read(bio, chain, len);
1771 if(len<0) {
1772 s_log(LOG_ERR, "BIO_read failed");
1773 BIO_free(bio);
1774 str_free(chain);
1775 return;
1776 }
1777 chain[len]='\0';
1778 BIO_free(bio);
1779 c->opt->chain=chain; /* this race condition is safe to ignore */
1780 ui_new_chain(c->opt->section_number);
1781 s_log(LOG_DEBUG, "Peer certificate was cached (%d bytes)", len);
1782 }
1783
1784 /* cache client sessions */
1785 NOEXPORT void session_cache_save(CLI *c, SSL_SESSION *sess) {
1786 if(!c->opt->option.client || !sess)
1787 return;
1788
1789 #if OPENSSL_VERSION_NUMBER>=0x10101000L
1790 if(!SSL_SESSION_is_resumable(sess))
1791 return;
1792 #endif
1793
1794 CRYPTO_THREAD_write_lock(stunnel_locks[LOCK_SESSION]);
1795
1796 /* save per-destination client session */
1797 if(c->opt->connect_session) {
1798 if(c->opt->connect_session[c->idx])
1799 SSL_SESSION_free(c->opt->connect_session[c->idx]);
1800 c->opt->connect_session[c->idx]=SSL_SESSION_dup(sess);
1801 }
1802
1803 /* save fallback client session */
1804 if(c->opt->session)
1805 SSL_SESSION_free(c->opt->session);
1806 c->opt->session=SSL_SESSION_dup(sess);
1807
1808 CRYPTO_THREAD_unlock(stunnel_locks[LOCK_SESSION]);
1809 }
1810
1811 #if OPENSSL_VERSION_NUMBER<0x10101000L
1812 NOEXPORT SSL_SESSION *SSL_SESSION_dup(SSL_SESSION *src) {
1813 int der_len;
1814 unsigned char *der_data;
1815 unsigned char *tmp;
1816 const unsigned char *const_tmp;
1817 SSL_SESSION *dst;
1818
1819 der_len=i2d_SSL_SESSION(src, NULL);
1820 if(der_len<=0)
1821 return NULL;
1822 der_data=str_alloc((size_t)der_len);
1823 tmp=der_data;
1824 der_len=i2d_SSL_SESSION(src, &tmp);
1825 if(der_len<=0) {
1826 str_free(der_data);
1827 return NULL;
1828 }
1829 const_tmp=der_data;
1830 dst=d2i_SSL_SESSION(NULL, &const_tmp, der_len);
1831 str_free(der_data);
1832 return dst;
1833 }
1834 #endif
1835
1836 NOEXPORT SSL_SESSION *sess_get_cb(SSL *ssl,
1837 #if OPENSSL_VERSION_NUMBER>=0x10100000L
1838 const
1839 #endif
1840 unsigned char *key, int key_len, int *do_copy) {
1841 CLI *c;
1842
1843 s_log(LOG_DEBUG, "Get session callback");
1844 *do_copy=0; /* allow the session to be freed automatically */
1845 c=SSL_get_ex_data(ssl, index_ssl_cli);
1846 if(c->opt->option.sessiond)
1847 return cache_get(ssl, key, key_len);
1848 return NULL; /* no session to resume */
1849 }
1850
1851 NOEXPORT void sess_remove_cb(SSL_CTX *ctx, SSL_SESSION *sess) {
1852 SERVICE_OPTIONS *opt;
1853
1854 s_log(LOG_DEBUG, "Remove session callback");
1855 opt=SSL_CTX_get_ex_data(ctx, index_ssl_ctx_opt);
1856 if(opt->option.sessiond)
1857 cache_remove(ctx, sess);
1858 }
1859
1860 /**************************************** sessiond functionality */
1861
1862 #define CACHE_CMD_NEW 0x00
1863 #define CACHE_CMD_GET 0x01
1864 #define CACHE_CMD_REMOVE 0x02
1865 #define CACHE_RESP_ERR 0x80
1866 #define CACHE_RESP_OK 0x81
1867
1868 NOEXPORT void cache_new(SSL *ssl, SSL_SESSION *sess) {
1869 unsigned char *val, *val_tmp;
1870 ssize_t val_len;
1871 const unsigned char *session_id;
1872 unsigned int session_id_length;
1873
1874 val_len=i2d_SSL_SESSION(sess, NULL);
1875 val_tmp=val=str_alloc((size_t)val_len);
1876 i2d_SSL_SESSION(sess, &val_tmp);
1877
1878 session_id=SSL_SESSION_get_id(sess, &session_id_length);
1879 cache_transfer(SSL_get_SSL_CTX(ssl), CACHE_CMD_NEW,
1880 SSL_SESSION_get_timeout(sess),
1881 session_id, session_id_length, val, (size_t)val_len, NULL, NULL);
1882 str_free(val);
1883 }
1884
1885 NOEXPORT SSL_SESSION *cache_get(SSL *ssl,
1886 const unsigned char *key, int key_len) {
1887 unsigned char *val=NULL;
1888 const unsigned char *val_tmp=NULL;
1889 ssize_t val_len=0;
1890 SSL_SESSION *sess;
1891
1892 cache_transfer(SSL_get_SSL_CTX(ssl), CACHE_CMD_GET, 0,
1893 key, (size_t)key_len, NULL, 0, &val, (size_t *)&val_len);
1894 if(!val)
1895 return NULL;
1896 val_tmp=val;
1897 sess=d2i_SSL_SESSION(NULL, &val_tmp, (long)val_len);
1898 str_free(val);
1899 return sess;
1900 }
1901
1902 NOEXPORT void cache_remove(SSL_CTX *ctx, SSL_SESSION *sess) {
1903 const unsigned char *session_id;
1904 unsigned int session_id_length;
1905
1906 session_id=SSL_SESSION_get_id(sess, &session_id_length);
1907 cache_transfer(ctx, CACHE_CMD_REMOVE, 0,
1908 session_id, session_id_length, NULL, 0, NULL, NULL);
1909 }
1910
1911 #define MAX_VAL_LEN 512
1912 typedef struct {
1913 u_char version, type;
1914 u_short timeout;
1915 u_char key[SSL_MAX_SSL_SESSION_ID_LENGTH];
1916 u_char val[MAX_VAL_LEN];
1917 } CACHE_PACKET;
1918
1919 NOEXPORT void cache_transfer(SSL_CTX *ctx, const u_char type,
1920 const long timeout,
1921 const u_char *key, const size_t key_len,
1922 const u_char *val, const size_t val_len,
1923 unsigned char **ret, size_t *ret_len) {
1924 char session_id_txt[2*SSL_MAX_SSL_SESSION_ID_LENGTH+1];
1925 const char *type_description[]={"new", "get", "remove"};
1926 SOCKET s;
1927 ssize_t len;
1928 struct timeval t;
1929 CACHE_PACKET *packet;
1930 SERVICE_OPTIONS *section;
1931
1932 if(ret) /* set error as the default result if required */
1933 *ret=NULL;
1934
1935 /* log the request information */
1936 bin2hexstring(key, key_len, session_id_txt, sizeof session_id_txt);
1937 s_log(LOG_INFO,
1938 "cache_transfer: request=%s, timeout=%ld, id=%s, length=%lu",
1939 type_description[type], timeout, session_id_txt, (long unsigned)val_len);
1940
1941 /* allocate UDP packet buffer */
1942 if(key_len>SSL_MAX_SSL_SESSION_ID_LENGTH) {
1943 s_log(LOG_ERR, "cache_transfer: session id too big (%lu bytes)",
1944 (unsigned long)key_len);
1945 return;
1946 }
1947 if(val_len>MAX_VAL_LEN) {
1948 s_log(LOG_ERR, "cache_transfer: encoded session too big (%lu bytes)",
1949 (unsigned long)key_len);
1950 return;
1951 }
1952 packet=str_alloc(sizeof(CACHE_PACKET));
1953
1954 /* setup packet */
1955 packet->version=1;
1956 packet->type=type;
1957 packet->timeout=htons((u_short)(timeout<64800?timeout:64800));/* 18 hours */
1958 memcpy(packet->key, key, key_len);
1959 if(val && val_len) /* only check it to make code analysis tools happy */
1960 memcpy(packet->val, val, val_len);
1961
1962 /* create the socket */
1963 s=s_socket(AF_INET, SOCK_DGRAM, 0, 0, "cache_transfer: socket");
1964 if(s==INVALID_SOCKET) {
1965 str_free(packet);
1966 return;
1967 }
1968
1969 /* retrieve pointer to the section structure of this ctx */
1970 section=SSL_CTX_get_ex_data(ctx, index_ssl_ctx_opt);
1971 if(sendto(s, (void *)packet,
1972 #ifdef USE_WIN32
1973 (int)
1974 #endif
1975 (sizeof(CACHE_PACKET)-MAX_VAL_LEN+val_len),
1976 0, &section->sessiond_addr.sa,
1977 addr_len(&section->sessiond_addr))<0) {
1978 sockerror("cache_transfer: sendto");
1979 closesocket(s);
1980 str_free(packet);
1981 return;
1982 }
1983
1984 if(!ret || !ret_len) { /* no response is required */
1985 closesocket(s);
1986 str_free(packet);
1987 return;
1988 }
1989
1990 /* set recvfrom timeout to 200ms */
1991 t.tv_sec=0;
1992 t.tv_usec=200;
1993 if(setsockopt(s, SOL_SOCKET, SO_RCVTIMEO, (void *)&t, sizeof t)<0) {
1994 sockerror("cache_transfer: setsockopt SO_RCVTIMEO");
1995 closesocket(s);
1996 str_free(packet);
1997 return;
1998 }
1999
2000 /* retrieve response */
2001 len=recv(s, (void *)packet, sizeof(CACHE_PACKET), 0);
2002 closesocket(s);
2003 if(len<0) {
2004 int err=get_last_socket_error();
2005
2006 if(err==S_EWOULDBLOCK || (S_EWOULDBLOCK!=S_EAGAIN && err==S_EAGAIN))
2007 s_log(LOG_INFO, "cache_transfer: recv timeout");
2008 else
2009 sockerror("cache_transfer: recv");
2010 str_free(packet);
2011 return;
2012 }
2013
2014 /* parse results */
2015 if(len<(int)sizeof(CACHE_PACKET)-MAX_VAL_LEN || /* too short */
2016 packet->version!=1 || /* wrong version */
2017 safe_memcmp(packet->key, key, key_len)) { /* wrong session id */
2018 s_log(LOG_DEBUG, "cache_transfer: malformed packet received");
2019 str_free(packet);
2020 return;
2021 }
2022 if(packet->type!=CACHE_RESP_OK) {
2023 s_log(LOG_INFO, "cache_transfer: session not found");
2024 str_free(packet);
2025 return;
2026 }
2027 *ret_len=(size_t)len-(sizeof(CACHE_PACKET)-MAX_VAL_LEN);
2028 *ret=str_alloc(*ret_len);
2029 s_log(LOG_INFO, "cache_transfer: session found");
2030 memcpy(*ret, packet->val, *ret_len);
2031 str_free(packet);
2032 }
2033
2034 /**************************************** informational callback */
2035
2036 NOEXPORT void info_callback(const SSL *ssl, int where, int ret) {
2037 CLI *c;
2038 SSL_CTX *ctx;
2039 const char *state_string;
2040 #if OPENSSL_VERSION_NUMBER>=0x10100000L
2041 OSSL_HANDSHAKE_STATE state=SSL_get_state(ssl);
2042 #else
2043 int state=SSL_get_state((SSL *)ssl);
2044 #endif
2045
2046 c=SSL_get_ex_data(ssl, index_ssl_cli);
2047 if(!c) {
2048 s_log(LOG_ERR,
2049 "INTERNAL ERROR: info_callback() called without CLI, state=%x",
2050 state);
2051 return;
2052 }
2053 #if 0
2054 s_log(LOG_DEBUG, "state=%x", state);
2055 #endif
2056
2057 /* do not reset the TLS socket after a fatal alert */
2058 if(where & SSL_CB_ALERT && !strcmp(SSL_alert_type_string(ret), "F"))
2059 c->fatal_alert=1;
2060
2061 /* log the client certificate request (if received) */
2062 #ifndef SSL3_ST_CR_CERT_REQ_A
2063 if(state==TLS_ST_CR_CERT_REQ)
2064 #else
2065 if(state==SSL3_ST_CR_CERT_REQ_A)
2066 #endif
2067 print_CA_list("Received trusted client CA",
2068 SSL_get_client_CA_list(ssl));
2069 #ifndef SSL3_ST_CR_SRVR_DONE_A
2070 if(state==TLS_ST_CR_SRVR_DONE)
2071 #else
2072 if(state==SSL3_ST_CR_SRVR_DONE_A)
2073 #endif
2074 if(!SSL_get_client_CA_list(ssl))
2075 s_log(LOG_INFO, "Client certificate not requested");
2076
2077 /* prevent renegotiation DoS attack */
2078 if((where&SSL_CB_HANDSHAKE_DONE)
2079 && c->reneg_state==RENEG_INIT) {
2080 /* first (initial) handshake was completed, remember this,
2081 * so that further renegotiation attempts can be detected */
2082 c->reneg_state=RENEG_ESTABLISHED;
2083 } else if((where&SSL_CB_ACCEPT_LOOP)
2084 && c->reneg_state==RENEG_ESTABLISHED) {
2085 #ifndef SSL3_ST_SR_CLNT_HELLO_A
2086 if(state==TLS_ST_SR_CLNT_HELLO) {
2087 #else
2088 if(state==SSL3_ST_SR_CLNT_HELLO_A
2089 || state==SSL23_ST_SR_CLNT_HELLO_A) {
2090 #endif
2091 /* client hello received after initial handshake,
2092 * this means renegotiation -> mark it */
2093 c->reneg_state=RENEG_DETECTED;
2094 }
2095 }
2096
2097 if(c->opt->log_level<LOG_DEBUG)
2098 return; /* performance optimization: skip logging debug info */
2099
2100 if(where & SSL_CB_LOOP) {
2101 state_string=SSL_state_string_long(ssl);
2102 if(strcmp(state_string, "unknown state"))
2103 s_log(LOG_DEBUG, "TLS state (%s): %s",
2104 (where & SSL_ST_CONNECT) ? "connect" :
2105 (where & SSL_ST_ACCEPT) ? "accept" :
2106 "undefined", state_string);
2107 } else if(where & SSL_CB_ALERT) {
2108 s_log(LOG_DEBUG, "TLS alert (%s): %s: %s",
2109 (where & SSL_CB_READ) ? "read" : "write",
2110 SSL_alert_type_string_long(ret),
2111 SSL_alert_desc_string_long(ret));
2112 } else if(where==SSL_CB_HANDSHAKE_DONE) {
2113 ctx=SSL_get_SSL_CTX(ssl);
2114 if(c->opt->option.client) {
2115 s_log(LOG_DEBUG, "%6ld client connect(s) requested",
2116 SSL_CTX_sess_connect(ctx));
2117 s_log(LOG_DEBUG, "%6ld client connect(s) succeeded",
2118 SSL_CTX_sess_connect_good(ctx));
2119 s_log(LOG_DEBUG, "%6ld client renegotiation(s) requested",
2120 SSL_CTX_sess_connect_renegotiate(ctx));
2121 } else {
2122 s_log(LOG_DEBUG, "%6ld server accept(s) requested",
2123 SSL_CTX_sess_accept(ctx));
2124 s_log(LOG_DEBUG, "%6ld server accept(s) succeeded",
2125 SSL_CTX_sess_accept_good(ctx));
2126 s_log(LOG_DEBUG, "%6ld server renegotiation(s) requested",
2127 SSL_CTX_sess_accept_renegotiate(ctx));
2128 }
2129 /* according to the source it not only includes internal
2130 and external session caches, but also session tickets */
2131 s_log(LOG_DEBUG, "%6ld session reuse(s)",
2132 SSL_CTX_sess_hits(ctx));
2133 if(!c->opt->option.client) { /* server session cache stats */
2134 s_log(LOG_DEBUG, "%6ld internal session cache item(s)",
2135 SSL_CTX_sess_number(ctx));
2136 s_log(LOG_DEBUG, "%6ld internal session cache fill-up(s)",
2137 SSL_CTX_sess_cache_full(ctx));
2138 s_log(LOG_DEBUG, "%6ld internal session cache miss(es)",
2139 SSL_CTX_sess_misses(ctx));
2140 s_log(LOG_DEBUG, "%6ld external session cache hit(s)",
2141 SSL_CTX_sess_cb_hits(ctx));
2142 s_log(LOG_DEBUG, "%6ld expired session(s) retrieved",
2143 SSL_CTX_sess_timeouts(ctx));
2144 }
2145 }
2146 }
2147
2148 /**************************************** TLS error reporting */
2149
2150 void ssl_error(CLI *c, const char *txt) { /* OpenSSL error handler */
2151 char *errors[MAX_ERRORS];
2152 char *error_string;
2153 int i;
2154
2155 error_string=str_alloc(MAX_ERROR_LEN);
2156 for(i=0; i<MAX_ERRORS; i++) {
2157 unsigned long err=0;
2158 const char *file=NULL, *func=NULL, *data=NULL;
2159 int line=0, flags=0;
2160
2161 #if OPENSSL_VERSION_NUMBER>=0x30000000L
2162 err=ERR_get_error_all(&file, &line, &func, &data, &flags);
2163 #else
2164 err=ERR_get_error_line(&file, &line);
2165 #endif
2166 if(!err) {
2167 if(txt && i==0)
2168 errors[i++]=str_printf("%s: Peer suddenly disconnected", txt);
2169 break;
2170 }
2171
2172 ERR_error_string_n(err, error_string, MAX_ERROR_LEN);
2173 errors[i]=str_printf("%s: %s%s%s:%d: %s%s%s%s%s",
2174 txt && i==0 ? txt : "error queue",
2175 func && *func ? func : "",
2176 func && *func ? "@" : "",
2177 file, line, error_string,
2178 flags&ERR_TXT_STRING && data && *data ? ": " : "",
2179 flags&ERR_TXT_STRING && data && *data ? data : "",
2180 c && c->accepted_address && i==0 ? ": client " : "",
2181 c && c->accepted_address && i==0 ? c->accepted_address : "");
2182 }
2183 str_free(error_string);
2184 ERR_clear_error();
2185
2186 while(i-->0) {
2187 s_log(LOG_ERR, "%s", errors[i]);
2188 str_free(errors[i]);
2189 }
2190 }
2191
2192 /**************************************** ciphersuites */
2193 #ifndef OPENSSL_NO_TLS1_3
2194 NOEXPORT char *compare_cipher_lists(STACK_OF(SSL_CIPHER) *list1, STACK_OF(SSL_CIPHER) *list2) {
2195 char *result=NULL;
2196 size_t result_len=0;
2197 int i;
2198
2199 for(i=0; i<sk_SSL_CIPHER_num(list2); i++) {
2200 const SSL_CIPHER *cipher2=sk_SSL_CIPHER_value(list2, i);
2201 const char *cipher2_name=SSL_CIPHER_get_name(cipher2);
2202 int found=0;
2203
2204 for(int j=0; j<sk_SSL_CIPHER_num(list1); j++) {
2205 const SSL_CIPHER *cipher1=sk_SSL_CIPHER_value(list1, j);
2206 const char *cipher1_name=SSL_CIPHER_get_name(cipher1);
2207
2208 if(!strcmp(cipher2_name, cipher1_name)) {
2209 found=1;
2210 break;
2211 }
2212 }
2213 if(!found) {
2214 size_t name_len=strlen(cipher2_name);
2215
2216 result=str_realloc(result, result_len + name_len + 2); /* +2 for ':' and '\0' */
2217 if(result_len == 0) {
2218 strcpy(result, cipher2_name);
2219 } else {
2220 strcat(result, ":");
2221 strcat(result, cipher2_name);
2222 }
2223 result_len+=name_len + 1; /* +1 for ':' */
2224 }
2225 }
2226 return result;
2227 }
2228
2229 NOEXPORT char *get_tls13_cipher_list(STACK_OF(SSL_CIPHER) *list) {
2230 char *result=NULL;
2231 size_t result_len=0;
2232 int i;
2233
2234 for(i=0; i<sk_SSL_CIPHER_num(list); i++) {
2235 const SSL_CIPHER *cipher=sk_SSL_CIPHER_value(list, i);
2236
2237 if(!strcmp(SSL_CIPHER_get_version(cipher), "TLSv1.3")) {
2238 const char *cipher_name=SSL_CIPHER_get_name(cipher);
2239 size_t name_len=strlen(cipher_name);
2240
2241 result=str_realloc(result, result_len + name_len + 2); /* +2 for ':' and '\0' */
2242 if(result_len == 0) {
2243 strcpy(result, cipher_name);
2244 } else {
2245 strcat(result, ":");
2246 strcat(result, cipher_name);
2247 }
2248 result_len+=name_len + 1; /* +1 for ':' */
2249 }
2250 }
2251 return result;
2252 }
2253 #endif /* TLS 1.3 */
2254 /* end of ctx.c */