1 /*
2  *   stunnel       TLS offloading and load-balancing proxy
3  *   Copyright (C) 1998-2021 Michal Trojnara <Michal.Trojnara@stunnel.org>
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 "common.h"
39 #include "prototypes.h"
40 
41 SERVICE_OPTIONS *current_section=NULL;
42 
43 /* try an empty passphrase first */
44 static char cached_passwd[PEM_BUFSIZE]="";
45 static int cached_len=0;
46 
47 #ifndef OPENSSL_NO_DH
48 DH *dh_params=NULL;
49 int dh_temp_params=0;
50 #endif /* OPENSSL_NO_DH */
51 
52 /**************************************** prototypes */
53 
54 /* SNI */
55 #ifndef OPENSSL_NO_TLSEXT
56 NOEXPORT int servername_cb(SSL *, int *, void *);
57 NOEXPORT int matches_wildcard(const char *, const char *);
58 #endif
59 
60 /* DH/ECDH */
61 #ifndef OPENSSL_NO_DH
62 NOEXPORT int dh_init(SERVICE_OPTIONS *);
63 NOEXPORT DH *dh_read(char *);
64 #endif /* OPENSSL_NO_DH */
65 #ifndef OPENSSL_NO_ECDH
66 NOEXPORT int ecdh_init(SERVICE_OPTIONS *);
67 #endif /* USE_ECDH */
68 
69 /* configuration commands */
70 NOEXPORT int conf_init(SERVICE_OPTIONS *section);
71 
72 /* authentication */
73 NOEXPORT int auth_init(SERVICE_OPTIONS *);
74 #ifndef OPENSSL_NO_PSK
75 NOEXPORT unsigned psk_client_callback(SSL *, const char *,
76     char *, unsigned, unsigned char *, unsigned);
77 NOEXPORT unsigned psk_server_callback(SSL *, const char *,
78     unsigned char *, unsigned);
79 #endif /* !defined(OPENSSL_NO_PSK) */
80 NOEXPORT int load_cert_file(SERVICE_OPTIONS *);
81 NOEXPORT int load_key_file(SERVICE_OPTIONS *);
82 NOEXPORT int pkcs12_extension(const char *);
83 NOEXPORT int load_pkcs12_file(SERVICE_OPTIONS *);
84 #ifndef OPENSSL_NO_ENGINE
85 NOEXPORT int load_cert_engine(SERVICE_OPTIONS *);
86 NOEXPORT int load_key_engine(SERVICE_OPTIONS *);
87 #endif
88 NOEXPORT int cache_passwd_get_cb(char *, int, int, void *);
89 NOEXPORT int cache_passwd_set_cb(char *, int, int, void *);
90 NOEXPORT void set_prompt(const char *);
91 NOEXPORT int ui_retry();
92 
93 /* session tickets */
94 #if OPENSSL_VERSION_NUMBER >= 0x10101000L
95 NOEXPORT int generate_session_ticket_cb(SSL *, void *);
96 NOEXPORT int decrypt_session_ticket_cb(SSL *, SSL_SESSION *,
97     const unsigned char *, size_t, SSL_TICKET_STATUS, void *);
98 #endif /* OpenSSL 1.1.1 or later */
99 
100 #if OPENSSL_VERSION_NUMBER>=0x10000000L
101 NOEXPORT int ssl_tlsext_ticket_key_cb(SSL *, unsigned char *,
102     unsigned char *, EVP_CIPHER_CTX *, HMAC_CTX *, int);
103 #endif /* OpenSSL 1.0.0 or later */
104 
105 /* session callbacks */
106 NOEXPORT int sess_new_cb(SSL *, SSL_SESSION *);
107 NOEXPORT void new_chain(CLI *);
108 NOEXPORT void session_cache_save(CLI *, SSL_SESSION *);
109 NOEXPORT SSL_SESSION *sess_get_cb(SSL *,
110 #if OPENSSL_VERSION_NUMBER>=0x10100000L
111     const
112 #endif
113     unsigned char *, int, int *);
114 NOEXPORT void sess_remove_cb(SSL_CTX *, SSL_SESSION *);
115 
116 /* sessiond interface */
117 NOEXPORT void cache_new(SSL *, SSL_SESSION *);
118 NOEXPORT SSL_SESSION *cache_get(SSL *, const unsigned char *, int);
119 NOEXPORT void cache_remove(SSL_CTX *, SSL_SESSION *);
120 NOEXPORT void cache_transfer(SSL_CTX *, const u_char, const long,
121     const u_char *, const size_t,
122     const u_char *, const size_t,
123     unsigned char **, size_t *);
124 
125 /* info callbacks */
126 NOEXPORT void info_callback(const SSL *, int, int);
127 
128 NOEXPORT void sslerror_queue(void);
129 NOEXPORT void sslerror_log(unsigned long, const char *, int, char *);
130 
131 /**************************************** initialize section->ctx */
132 
133 #if OPENSSL_VERSION_NUMBER>=0x10100000L
134 typedef long unsigned SSL_OPTIONS_TYPE;
135 #else
136 typedef long SSL_OPTIONS_TYPE;
137 #endif
138 
context_init(SERVICE_OPTIONS * section)139 int context_init(SERVICE_OPTIONS *section) { /* init TLS context */
140     /* create a new TLS context */
141 #if OPENSSL_VERSION_NUMBER>=0x10100000L
142     if(section->option.client)
143         section->ctx=SSL_CTX_new(TLS_client_method());
144     else /* server mode */
145         section->ctx=SSL_CTX_new(TLS_server_method());
146     if(!SSL_CTX_set_min_proto_version(section->ctx,
147             section->min_proto_version)) {
148         s_log(LOG_ERR, "Failed to set the minimum protocol version 0x%X",
149             section->min_proto_version);
150         return 1; /* FAILED */
151     }
152     if(!SSL_CTX_set_max_proto_version(section->ctx,
153             section->max_proto_version)) {
154         s_log(LOG_ERR, "Failed to set the maximum protocol version 0x%X",
155             section->max_proto_version);
156         return 1; /* FAILED */
157     }
158 #else /* OPENSSL_VERSION_NUMBER<0x10100000L */
159     if(section->option.client)
160         section->ctx=SSL_CTX_new(section->client_method);
161     else /* server mode */
162         section->ctx=SSL_CTX_new(section->server_method);
163 #endif /* OPENSSL_VERSION_NUMBER<0x10100000L */
164     if(!section->ctx) {
165         sslerror("SSL_CTX_new");
166         return 1; /* FAILED */
167     }
168 
169     /* allow callbacks to access their SERVICE_OPTIONS structure */
170     if(!SSL_CTX_set_ex_data(section->ctx, index_ssl_ctx_opt, section)) {
171         sslerror("SSL_CTX_set_ex_data");
172         return 1; /* FAILED */
173     }
174     current_section=section; /* setup current section for callbacks */
175 
176 #if OPENSSL_VERSION_NUMBER>=0x10100000L
177     /* set the security level */
178     if(section->security_level>=0) {
179         /* set the user-specified value */
180         SSL_CTX_set_security_level(section->ctx, section->security_level);
181         s_log(LOG_INFO, "User-specified security level set: %d",
182             section->security_level);
183     } else if(SSL_CTX_get_security_level(section->ctx)<DEFAULT_SECURITY_LEVEL) {
184         /* set our default, as it is more secure than the OpenSSL default */
185         SSL_CTX_set_security_level(section->ctx, DEFAULT_SECURITY_LEVEL);
186         s_log(LOG_INFO, "stunnel default security level set: %d",
187             DEFAULT_SECURITY_LEVEL);
188     } else { /* our default is not more secure than the OpenSSL default */
189         s_log(LOG_INFO, "OpenSSL security level is used: %d",
190             SSL_CTX_get_security_level(section->ctx));
191     }
192 #endif /* OpenSSL 1.1.0 or later */
193 
194     /* ciphers */
195     if(section->cipher_list) {
196         s_log(LOG_DEBUG, "Ciphers: %s", section->cipher_list);
197         if(!SSL_CTX_set_cipher_list(section->ctx, section->cipher_list)) {
198             sslerror("SSL_CTX_set_cipher_list");
199             return 1; /* FAILED */
200         }
201     }
202 
203 #ifndef OPENSSL_NO_TLS1_3
204     /* ciphersuites */
205     if(section->ciphersuites) {
206         s_log(LOG_DEBUG, "TLSv1.3 ciphersuites: %s", section->ciphersuites);
207         if(!SSL_CTX_set_ciphersuites(section->ctx, section->ciphersuites)) {
208             sslerror("SSL_CTX_set_ciphersuites");
209             return 1; /* FAILED */
210         }
211     }
212 #endif /* TLS 1.3 */
213 
214     /* TLS options: configure the stunnel defaults first */
215     SSL_CTX_set_options(section->ctx, SSL_OP_NO_SSLv2|SSL_OP_NO_SSLv3);
216     /* no session ticket gets sent to the client at all in TLSv1.2
217        and below, but a stateful ticket will be sent in TLSv1.3 */
218     if(!section->option.client && !section->option.session_resume) {
219         SSL_CTX_set_options(section->ctx, SSL_OP_NO_TICKET);
220     }
221 #ifdef SSL_OP_NO_COMPRESSION
222     /* we implemented a better way to disable compression if needed */
223     SSL_CTX_clear_options(section->ctx, SSL_OP_NO_COMPRESSION);
224 #endif /* SSL_OP_NO_COMPRESSION */
225 
226     /* TLS options: configure the user-specified values */
227     SSL_CTX_set_options(section->ctx,
228         (SSL_OPTIONS_TYPE)(section->ssl_options_set));
229 #if OPENSSL_VERSION_NUMBER>=0x009080dfL
230     SSL_CTX_clear_options(section->ctx,
231         (SSL_OPTIONS_TYPE)(section->ssl_options_clear));
232 #endif /* OpenSSL 0.9.8m or later */
233 
234     /* TLS options: log the configured values */
235 #if OPENSSL_VERSION_NUMBER>=0x009080dfL
236     s_log(LOG_DEBUG, "TLS options: 0x%08lX (+0x%08lX, -0x%08lX)",
237         SSL_CTX_get_options(section->ctx),
238         section->ssl_options_set, section->ssl_options_clear);
239 #else /* OpenSSL older than 0.9.8m */
240     s_log(LOG_DEBUG, "TLS options: 0x%08lX (+0x%08lX)",
241         SSL_CTX_get_options(section->ctx), section->ssl_options_set);
242 #endif /* OpenSSL 0.9.8m or later */
243 
244     /* initialize OpenSSL CONF options */
245     if(conf_init(section))
246         return 1; /* FAILED */
247 
248     /* setup mode of operation for the TLS state machine */
249 #ifdef SSL_MODE_RELEASE_BUFFERS
250     SSL_CTX_set_mode(section->ctx,
251         SSL_MODE_ENABLE_PARTIAL_WRITE |
252         SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER |
253         SSL_MODE_RELEASE_BUFFERS);
254 #else
255     SSL_CTX_set_mode(section->ctx,
256         SSL_MODE_ENABLE_PARTIAL_WRITE |
257         SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
258 #endif
259 
260     /* setup session tickets */
261 #if OPENSSL_VERSION_NUMBER >= 0x10101000L
262     SSL_CTX_set_session_ticket_cb(section->ctx, generate_session_ticket_cb,
263         decrypt_session_ticket_cb, NULL);
264 #endif /* OpenSSL 1.1.1 or later */
265 
266 #if OPENSSL_VERSION_NUMBER>=0x10000000L
267     if((section->ticket_key)&&(section->ticket_mac))
268         SSL_CTX_set_tlsext_ticket_key_cb(section->ctx, ssl_tlsext_ticket_key_cb);
269 #endif /* OpenSSL 1.0.0 or later */
270 
271     /* setup session cache */
272     if(!section->option.client) {
273         unsigned servname_len=(unsigned)strlen(section->servname);
274         if(servname_len>SSL_MAX_SSL_SESSION_ID_LENGTH)
275             servname_len=SSL_MAX_SSL_SESSION_ID_LENGTH;
276 #ifndef OPENSSL_NO_TLS1_3
277         /* suppress all tickets (stateful and stateless) in TLSv1.3 */
278         if(!section->option.session_resume && !SSL_CTX_set_num_tickets(section->ctx, 0)) {
279             sslerror("SSL_CTX_set_num_tickets");
280             return 1; /* FAILED */
281         }
282 #endif /* TLS 1.3 */
283         if(!SSL_CTX_set_session_id_context(section->ctx,
284                 (unsigned char *)section->servname, servname_len)) {
285             sslerror("SSL_CTX_set_session_id_context");
286             return 1; /* FAILED */
287         }
288     }
289     if(section->option.session_resume) {
290         SSL_CTX_set_session_cache_mode(section->ctx,
291             SSL_SESS_CACHE_BOTH | SSL_SESS_CACHE_NO_INTERNAL_STORE);
292     } else {
293         SSL_CTX_set_session_cache_mode(section->ctx, SSL_SESS_CACHE_OFF);
294     }
295     s_log(LOG_INFO, "Session resumption %s", section->option.session_resume
296         ? "enabled" : "disabled");
297     SSL_CTX_sess_set_cache_size(section->ctx, section->session_size);
298     SSL_CTX_set_timeout(section->ctx, section->session_timeout);
299     SSL_CTX_sess_set_new_cb(section->ctx, sess_new_cb);
300     SSL_CTX_sess_set_get_cb(section->ctx, sess_get_cb);
301     SSL_CTX_sess_set_remove_cb(section->ctx, sess_remove_cb);
302 
303     /* set info callback */
304     SSL_CTX_set_info_callback(section->ctx, info_callback);
305 
306     /* load certificate and private key to be verified by the peer server */
307     if(auth_init(section))
308         return 1; /* FAILED */
309 
310     /* initialize verification of the peer server certificate */
311     if(verify_init(section))
312         return 1; /* FAILED */
313 
314     /* initialize the DH/ECDH key agreement */
315 #ifndef OPENSSL_NO_TLSEXT
316     if(!section->option.client)
317         SSL_CTX_set_tlsext_servername_callback(section->ctx, servername_cb);
318 #endif /* OPENSSL_NO_TLSEXT */
319 #ifndef OPENSSL_NO_DH
320     dh_init(section); /* ignore the result (errors are not critical) */
321 #endif /* OPENSSL_NO_DH */
322 #ifndef OPENSSL_NO_ECDH
323     ecdh_init(section); /* ignore the result (errors are not critical) */
324 #endif /* OPENSSL_NO_ECDH */
325 
326     return 0; /* OK */
327 }
328 
329 /**************************************** SNI callback */
330 
331 #ifndef OPENSSL_NO_TLSEXT
332 
servername_cb(SSL * ssl,int * ad,void * arg)333 NOEXPORT int servername_cb(SSL *ssl, int *ad, void *arg) {
334     const char *servername=SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
335     CLI *c=SSL_get_ex_data(ssl, index_ssl_cli);
336     SERVERNAME_LIST *list;
337 
338     /* leave the alert type at SSL_AD_UNRECOGNIZED_NAME */
339     (void)ad; /* squash the unused parameter warning */
340     (void)arg; /* squash the unused parameter warning */
341 
342     /* handle trivial cases first */
343     if(!c->opt->servername_list_head) {
344         s_log(LOG_DEBUG, "SNI: no virtual services defined");
345         return SSL_TLSEXT_ERR_OK;
346     }
347     if(!servername) {
348         s_log(LOG_NOTICE, "SNI: no servername received");
349         return SSL_TLSEXT_ERR_NOACK;
350     }
351 
352     /* find a matching section */
353     s_log(LOG_INFO, "SNI: requested servername: %s", servername);
354     for(list=c->opt->servername_list_head; list; list=list->next)
355         if(matches_wildcard(servername, list->servername))
356             break;
357     if(!list) {
358         s_log(LOG_ERR, "SNI: no pattern matched servername: %s", servername);
359         return SSL_TLSEXT_ERR_OK;
360     }
361     s_log(LOG_DEBUG, "SNI: matched pattern: %s", list->servername);
362 
363     /* switch to the new section */
364 #ifndef USE_FORK
365     service_up_ref(list->opt);
366     service_free(c->opt);
367 #endif
368     c->opt=list->opt;
369     SSL_set_SSL_CTX(ssl, c->opt->ctx);
370     SSL_set_verify(ssl, SSL_CTX_get_verify_mode(c->opt->ctx),
371         SSL_CTX_get_verify_callback(c->opt->ctx));
372     s_log(LOG_NOTICE, "SNI: switched to service [%s]", c->opt->servname);
373 #ifdef USE_LIBWRAP
374     libwrap_auth(c); /* retry on a service switch */
375 #endif /* USE_LIBWRAP */
376     return SSL_TLSEXT_ERR_OK;
377 }
378 /* TLSEXT callback return codes:
379  *  - SSL_TLSEXT_ERR_OK
380  *  - SSL_TLSEXT_ERR_ALERT_WARNING
381  *  - SSL_TLSEXT_ERR_ALERT_FATAL
382  *  - SSL_TLSEXT_ERR_NOACK */
383 
matches_wildcard(const char * servername,const char * pattern)384 NOEXPORT int matches_wildcard(const char *servername, const char *pattern) {
385     if(!servername || !pattern)
386         return 0;
387     if(*pattern=='*') { /* wildcard comparison */
388         ssize_t diff=(ssize_t)strlen(servername)-((ssize_t)strlen(pattern)-1);
389         if(diff<0) /* pattern longer than servername */
390             return 0;
391         return !strcasecmp(servername+diff, pattern+1);
392     } else { /* string comparison */
393         return !strcasecmp(servername, pattern);
394     }
395 }
396 
397 #endif /* OPENSSL_NO_TLSEXT */
398 
399 /**************************************** DH initialization */
400 
401 #ifndef OPENSSL_NO_DH
402 
403 #if OPENSSL_VERSION_NUMBER<0x10100000L || defined(LIBRESSL_VERSION_NUMBER)
STACK_OF(SSL_CIPHER)404 NOEXPORT STACK_OF(SSL_CIPHER) *SSL_CTX_get_ciphers(const SSL_CTX *ctx) {
405     return ctx->cipher_list;
406 }
407 #endif
408 
dh_init(SERVICE_OPTIONS * section)409 NOEXPORT int dh_init(SERVICE_OPTIONS *section) {
410     DH *dh=NULL;
411     int i, n;
412     char description[128];
413     STACK_OF(SSL_CIPHER) *ciphers;
414 
415     section->option.dh_temp_params=0; /* disable by default */
416 
417     /* check if DH is needed for this section */
418     if(section->option.client) {
419         s_log(LOG_INFO, "DH initialization skipped: client section");
420         return 0; /* OK */
421     }
422     ciphers=SSL_CTX_get_ciphers(section->ctx);
423     if(!ciphers)
424         return 1; /* ERROR (unlikely) */
425     n=sk_SSL_CIPHER_num(ciphers);
426     for(i=0; i<n; ++i) {
427         *description='\0';
428         SSL_CIPHER_description(sk_SSL_CIPHER_value(ciphers, i),
429             description, sizeof description);
430         /* s_log(LOG_INFO, "Ciphersuite: %s", description); */
431         if(strstr(description, " Kx=DH")) {
432             s_log(LOG_INFO, "DH initialization needed for %s",
433                 SSL_CIPHER_get_name(sk_SSL_CIPHER_value(ciphers, i)));
434             break;
435         }
436     }
437     if(i==n) { /* no DH ciphers found */
438         s_log(LOG_INFO, "DH initialization skipped: no DH ciphersuites");
439         return 0; /* OK */
440     }
441 
442     s_log(LOG_DEBUG, "DH initialization");
443 #ifndef OPENSSL_NO_ENGINE
444     if(!section->engine) /* cert is a file and not an identifier */
445 #endif
446         dh=dh_read(section->cert);
447     if(dh) {
448         SSL_CTX_set_tmp_dh(section->ctx, dh);
449         s_log(LOG_INFO, "%d-bit DH parameters loaded", 8*DH_size(dh));
450         DH_free(dh);
451         return 0; /* OK */
452     }
453     CRYPTO_THREAD_read_lock(stunnel_locks[LOCK_DH]);
454     SSL_CTX_set_tmp_dh(section->ctx, dh_params);
455     CRYPTO_THREAD_unlock(stunnel_locks[LOCK_DH]);
456     dh_temp_params=1; /* generate temporary DH parameters in cron */
457     section->option.dh_temp_params=1; /* update this section in cron */
458     s_log(LOG_INFO, "Using dynamic DH parameters");
459     return 0; /* OK */
460 }
461 
dh_read(char * cert)462 NOEXPORT DH *dh_read(char *cert) {
463     DH *dh;
464     BIO *bio;
465 
466     if(!cert) {
467         s_log(LOG_DEBUG, "No certificate available to load DH parameters");
468         return NULL; /* FAILED */
469     }
470     bio=BIO_new_file(cert, "r");
471     if(!bio) {
472         sslerror("BIO_new_file");
473         return NULL; /* FAILED */
474     }
475     dh=PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
476     BIO_free(bio);
477     if(!dh) {
478         while(ERR_get_error())
479             ; /* OpenSSL error queue cleanup */
480         s_log(LOG_DEBUG, "Could not load DH parameters from %s", cert);
481         return NULL; /* FAILED */
482     }
483     s_log(LOG_DEBUG, "Using DH parameters from %s", cert);
484     return dh;
485 }
486 
487 #endif /* OPENSSL_NO_DH */
488 
489 /**************************************** ECDH initialization */
490 
491 #ifndef OPENSSL_NO_ECDH
492 
493 #if OPENSSL_VERSION_NUMBER < 0x10101000L
494 /* simplified version that only supports a single curve */
SSL_CTX_set1_groups_list(SSL_CTX * ctx,char * list)495 NOEXPORT int SSL_CTX_set1_groups_list(SSL_CTX *ctx, char *list) {
496     int nid;
497     EC_KEY *ecdh;
498 
499     nid=OBJ_txt2nid(list);
500     if(nid==NID_undef) {
501         s_log(LOG_ERR, "Unsupported curve: %s", list);
502         return 0; /* FAILED */
503     }
504     ecdh=EC_KEY_new_by_curve_name(nid);
505     if(!ecdh) {
506         sslerror("EC_KEY_new_by_curve_name");
507         return 0; /* FAILED */
508     }
509     if(!SSL_CTX_set_tmp_ecdh(ctx, ecdh)) {
510         sslerror("SSL_CTX_set_tmp_ecdhSSL_CTX_set_tmp_ecdh");
511         EC_KEY_free(ecdh);
512         return 0; /* FAILED */
513     }
514     EC_KEY_free(ecdh);
515     return 1; /* OK */
516 }
517 #endif /* OpenSSL version < 1.1.1 */
518 
ecdh_init(SERVICE_OPTIONS * section)519 NOEXPORT int ecdh_init(SERVICE_OPTIONS *section) {
520     s_log(LOG_DEBUG, "ECDH initialization");
521     if(!SSL_CTX_set1_groups_list(section->ctx, section->curves)) {
522 #if OPENSSL_VERSION_NUMBER >= 0x10101000L
523         sslerror("SSL_CTX_set1_groups_list");
524 #endif /* OpenSSL version >= 1.1.1 */
525         return 1; /* FAILED */
526     }
527     s_log(LOG_DEBUG, "ECDH initialized with curves %s", section->curves);
528     return 0; /* OK */
529 }
530 
531 #endif /* OPENSSL_NO_ECDH */
532 
533 /**************************************** initialize OpenSSL CONF */
534 
conf_init(SERVICE_OPTIONS * section)535 NOEXPORT int conf_init(SERVICE_OPTIONS *section) {
536 #if OPENSSL_VERSION_NUMBER>=0x10002000L && !defined(LIBRESSL_VERSION_NUMBER)
537     SSL_CONF_CTX *cctx;
538     NAME_LIST *curr;
539     char *cmd, *param;
540 
541     if(!section->config)
542         return 0; /* OK */
543     cctx=SSL_CONF_CTX_new();
544     if(!cctx) {
545         sslerror("SSL_CONF_CTX_new");
546         return 1; /* FAILED */
547     }
548     SSL_CONF_CTX_set_ssl_ctx(cctx, section->ctx);
549     SSL_CONF_CTX_set_flags(cctx, SSL_CONF_FLAG_FILE);
550     SSL_CONF_CTX_set_flags(cctx, section->option.client ?
551         SSL_CONF_FLAG_CLIENT : SSL_CONF_FLAG_SERVER);
552     SSL_CONF_CTX_set_flags(cctx, SSL_CONF_FLAG_CERTIFICATE);
553 
554     for(curr=section->config; curr; curr=curr->next) {
555         cmd=str_dup(curr->name);
556         param=strchr(cmd, ':');
557         if(param)
558             *param++='\0';
559         switch(SSL_CONF_cmd(cctx, cmd, param)) {
560         case 2:
561             s_log(LOG_DEBUG, "OpenSSL config \"%s\" set to \"%s\"", cmd, param);
562             break;
563         case 1:
564             s_log(LOG_DEBUG, "OpenSSL config command \"%s\" executed", cmd);
565             break;
566         case -2:
567             s_log(LOG_ERR,
568                 "OpenSSL config command \"%s\" was not recognised", cmd);
569             str_free(cmd);
570             SSL_CONF_CTX_free(cctx);
571             return 1; /* FAILED */
572         case -3:
573             s_log(LOG_ERR,
574                 "OpenSSL config command \"%s\" requires a parameter", cmd);
575             str_free(cmd);
576             SSL_CONF_CTX_free(cctx);
577             return 1; /* FAILED */
578         default:
579             sslerror("SSL_CONF_cmd");
580             str_free(cmd);
581             SSL_CONF_CTX_free(cctx);
582             return 1; /* FAILED */
583         }
584         str_free(cmd);
585     }
586 
587     if(!SSL_CONF_CTX_finish(cctx)) {
588         sslerror("SSL_CONF_CTX_finish");
589         SSL_CONF_CTX_free(cctx);
590         return 1; /* FAILED */
591     }
592     SSL_CONF_CTX_free(cctx);
593 #else /* OpenSSL earlier than 1.0.2 */
594     (void)section; /* squash the unused parameter warning */
595 #endif /* OpenSSL 1.0.2 or later */
596     return 0; /* OK */
597 }
598 
599 /**************************************** initialize authentication */
600 
auth_init(SERVICE_OPTIONS * section)601 NOEXPORT int auth_init(SERVICE_OPTIONS *section) {
602     int cert_needed=1, key_needed=1;
603 
604     /* initialize PSK */
605 #ifndef OPENSSL_NO_PSK
606     if(section->psk_keys) {
607         if(section->option.client)
608             SSL_CTX_set_psk_client_callback(section->ctx, psk_client_callback);
609         else
610             SSL_CTX_set_psk_server_callback(section->ctx, psk_server_callback);
611     }
612 #endif /* !defined(OPENSSL_NO_PSK) */
613 
614     /* initialize the client cert engine */
615 #if !defined(OPENSSL_NO_ENGINE) && OPENSSL_VERSION_NUMBER>=0x0090809fL
616     /* SSL_CTX_set_client_cert_engine() was introduced in OpenSSL 0.9.8i */
617     if(section->option.client && section->engine) {
618         if(SSL_CTX_set_client_cert_engine(section->ctx, section->engine)) {
619             s_log(LOG_INFO, "Client certificate engine (%s) enabled",
620                 ENGINE_get_id(section->engine));
621         } else { /* no client certificate functionality in this engine */
622             while(ERR_get_error())
623                 ; /* OpenSSL error queue cleanup */
624             s_log(LOG_INFO, "Client certificate engine (%s) not supported",
625                 ENGINE_get_id(section->engine));
626         }
627     }
628 #endif
629 
630     /* load the certificate and private key */
631     if(!section->cert || !section->key) {
632         s_log(LOG_DEBUG, "No certificate or private key specified");
633         return 0; /* OK */
634     }
635 #ifndef OPENSSL_NO_ENGINE
636     if(section->engine) { /* try to use the engine first */
637         cert_needed=load_cert_engine(section);
638         key_needed=load_key_engine(section);
639     }
640 #endif
641     if (cert_needed && pkcs12_extension(section->cert)) {
642         if (load_pkcs12_file(section)) {
643             return 1; /* FAILED */
644         }
645         cert_needed=key_needed=0; /* don't load any PEM files */
646     }
647     if(cert_needed && load_cert_file(section))
648         return 1; /* FAILED */
649     if(key_needed && load_key_file(section))
650         return 1; /* FAILED */
651 
652     /* validate the private key against the certificate */
653     if(!SSL_CTX_check_private_key(section->ctx)) {
654         sslerror("Private key does not match the certificate");
655         return 1; /* FAILED */
656     }
657     s_log(LOG_DEBUG, "Private key check succeeded");
658     return 0; /* OK */
659 }
660 
661 #ifndef OPENSSL_NO_PSK
662 
psk_client_callback(SSL * ssl,const char * hint,char * identity,unsigned max_identity_len,unsigned char * psk,unsigned max_psk_len)663 NOEXPORT unsigned psk_client_callback(SSL *ssl, const char *hint,
664     char *identity, unsigned max_identity_len,
665     unsigned char *psk, unsigned max_psk_len) {
666     CLI *c;
667     size_t identity_len;
668 
669     (void)hint; /* squash the unused parameter warning */
670     c=SSL_get_ex_data(ssl, index_ssl_cli);
671     if(!c->opt->psk_selected) {
672         s_log(LOG_ERR, "INTERNAL ERROR: No PSK identity selected");
673         return 0;
674     }
675     /* the source seems to have its buffer large enough for
676      * the trailing null character, but the manual page says
677      * nothing about it -- lets play safe */
678     identity_len=strlen(c->opt->psk_selected->identity)+1;
679     if(identity_len>max_identity_len) {
680         s_log(LOG_ERR, "PSK identity too long (%lu>%d bytes)",
681             (long unsigned)identity_len, max_psk_len);
682         return 0;
683     }
684     if(c->opt->psk_selected->key_len>max_psk_len) {
685         s_log(LOG_ERR, "PSK too long (%lu>%d bytes)",
686             (long unsigned)c->opt->psk_selected->key_len, max_psk_len);
687         return 0;
688     }
689     strcpy(identity, c->opt->psk_selected->identity);
690     memcpy(psk, c->opt->psk_selected->key_val, c->opt->psk_selected->key_len);
691     s_log(LOG_INFO, "PSK client configured for identity \"%s\"", identity);
692     return (unsigned)(c->opt->psk_selected->key_len);
693 }
694 
psk_server_callback(SSL * ssl,const char * identity,unsigned char * psk,unsigned max_psk_len)695 NOEXPORT unsigned psk_server_callback(SSL *ssl, const char *identity,
696     unsigned char *psk, unsigned max_psk_len) {
697     CLI *c;
698     PSK_KEYS *found;
699 
700     c=SSL_get_ex_data(ssl, index_ssl_cli);
701     found=psk_find(&c->opt->psk_sorted, identity);
702     if(!found) {
703         s_log(LOG_INFO, "PSK identity not found (session resumption?)");
704         return 0;
705     }
706     if(found->key_len>max_psk_len) {
707         s_log(LOG_ERR, "PSK too long (%u>%u)", found->key_len, max_psk_len);
708         return 0;
709     }
710     memcpy(psk, found->key_val, found->key_len);
711     s_log(LOG_NOTICE, "Key configured for PSK identity \"%s\"", identity);
712     c->flag.psk=1;
713     return found->key_len;
714 }
715 
psk_compar(const void * a,const void * b)716 NOEXPORT int psk_compar(const void *a, const void *b) {
717     PSK_KEYS *x=*(PSK_KEYS **)a, *y=*(PSK_KEYS **)b;
718 
719 #if 0
720     s_log(LOG_DEBUG, "PSK cmp: %s %s", x->identity, y->identity);
721 #endif
722     return strcmp(x->identity, y->identity);
723 }
724 
psk_sort(PSK_TABLE * table,PSK_KEYS * head)725 void psk_sort(PSK_TABLE *table, PSK_KEYS *head) {
726     PSK_KEYS *curr;
727     size_t i;
728 
729     table->num=0;
730     for(curr=head; curr; curr=curr->next)
731         ++table->num;
732     s_log(LOG_INFO, "PSK identities: %lu retrieved",
733         (long unsigned)table->num);
734     table->val=str_alloc_detached(table->num*sizeof(PSK_KEYS *));
735     for(curr=head, i=0; i<table->num; ++i) {
736         table->val[i]=curr;
737         curr=curr->next;
738     }
739     qsort(table->val, table->num, sizeof(PSK_KEYS *), psk_compar);
740 #if 0
741     for(i=0; i<table->num; ++i)
742         s_log(LOG_DEBUG, "PSK table: %s", table->val[i]->identity);
743 #endif
744 }
745 
psk_find(const PSK_TABLE * table,const char * identity)746 PSK_KEYS *psk_find(const PSK_TABLE *table, const char *identity) {
747     PSK_KEYS key, *ptr=&key, **ret;
748 
749     key.identity=(char *)identity;
750     ret=bsearch(&ptr,
751         table->val, table->num, sizeof(PSK_KEYS *), psk_compar);
752     return ret ? *ret : NULL;
753 }
754 
755 #endif /* !defined(OPENSSL_NO_PSK) */
756 
pkcs12_extension(const char * filename)757 NOEXPORT int pkcs12_extension(const char *filename) {
758     const char *ext=strrchr(filename, '.');
759     return ext && (!strcasecmp(ext, ".p12") || !strcasecmp(ext, ".pfx"));
760 }
761 
load_pkcs12_file(SERVICE_OPTIONS * section)762 NOEXPORT int load_pkcs12_file(SERVICE_OPTIONS *section) {
763     size_t len;
764     int i, success;
765     BIO *bio=NULL;
766     PKCS12 *p12=NULL;
767     X509 *cert=NULL;
768     STACK_OF(X509) *ca=NULL;
769     EVP_PKEY *pkey=NULL;
770     char pass[PEM_BUFSIZE];
771 
772     s_log(LOG_INFO, "Loading certificate and private key from file: %s",
773         section->cert);
774     if(file_permissions(section->cert))
775         return 1; /* FAILED */
776 
777     bio=BIO_new_file(section->cert, "rb");
778     if(!bio) {
779         sslerror("BIO_new_file");
780         return 1; /* FAILED */
781     }
782     p12=d2i_PKCS12_bio(bio, NULL);
783     if(!p12) {
784         sslerror("d2i_PKCS12_bio");
785         BIO_free(bio);
786         return 1; /* FAILED */
787     }
788     BIO_free(bio);
789 
790     /* try the cached value first */
791     set_prompt(section->cert);
792     len=(size_t)cache_passwd_get_cb(pass, sizeof pass, 0, NULL);
793     if(len>=sizeof pass)
794         len=sizeof pass-1;
795     pass[len]='\0'; /* null-terminate */
796     success=PKCS12_parse(p12, pass, &pkey, &cert, &ca);
797 
798     /* invoke the UI */
799     for(i=0; !success && i<3; i++) {
800         if(!ui_retry())
801             break;
802         if(i==0) { /* silence the cached attempt */
803             ERR_clear_error();
804         } else {
805             sslerror_queue(); /* dump the error queue */
806             s_log(LOG_ERR, "Wrong passphrase: retrying");
807         }
808         /* invoke the UI on subsequent calls */
809         len=(size_t)cache_passwd_set_cb(pass, sizeof pass, 0, NULL);
810         if(len>=sizeof pass)
811             len=sizeof pass-1;
812         pass[len]='\0'; /* null-terminate */
813         success=PKCS12_parse(p12, pass, &pkey, &cert, &ca);
814     }
815     if(!success) {
816         sslerror("PKCS12_parse");
817         PKCS12_free(p12);
818         return 1; /* FAILED */
819     }
820 
821     PKCS12_free(p12);
822 
823     if(!SSL_CTX_use_certificate(section->ctx, cert)) {
824         sslerror("SSL_CTX_use_certificate");
825         return 1; /* FAILED */
826     }
827     if(!SSL_CTX_use_PrivateKey(section->ctx, pkey)) {
828         sslerror("SSL_CTX_use_PrivateKey");
829         return 1; /* FAILED */
830     }
831     s_log(LOG_INFO, "Certificate and private key loaded from file: %s",
832         section->cert);
833     return 0; /* OK */
834 }
835 
load_cert_file(SERVICE_OPTIONS * section)836 NOEXPORT int load_cert_file(SERVICE_OPTIONS *section) {
837     s_log(LOG_INFO, "Loading certificate from file: %s", section->cert);
838     if(!SSL_CTX_use_certificate_chain_file(section->ctx, section->cert)) {
839         sslerror("SSL_CTX_use_certificate_chain_file");
840         return 1; /* FAILED */
841     }
842     s_log(LOG_INFO, "Certificate loaded from file: %s", section->cert);
843     return 0; /* OK */
844 }
845 
load_key_file(SERVICE_OPTIONS * section)846 NOEXPORT int load_key_file(SERVICE_OPTIONS *section) {
847     int i, success;
848 
849     s_log(LOG_INFO, "Loading private key from file: %s", section->key);
850     if(file_permissions(section->key))
851         return 1; /* FAILED */
852 
853     /* try the cached value first */
854     set_prompt(section->key);
855     SSL_CTX_set_default_passwd_cb(section->ctx, cache_passwd_get_cb);
856     success=SSL_CTX_use_PrivateKey_file(section->ctx, section->key,
857         SSL_FILETYPE_PEM);
858     /* invoke the UI on subsequent calls */
859     SSL_CTX_set_default_passwd_cb(section->ctx, cache_passwd_set_cb);
860 
861     /* invoke the UI */
862     for(i=0; !success && i<3; i++) {
863         if(!ui_retry())
864             break;
865         if(i==0) { /* silence the cached attempt */
866             ERR_clear_error();
867         } else {
868             sslerror_queue(); /* dump the error queue */
869             s_log(LOG_ERR, "Wrong passphrase: retrying");
870         }
871         success=SSL_CTX_use_PrivateKey_file(section->ctx, section->key,
872             SSL_FILETYPE_PEM);
873     }
874     if(!success) {
875         sslerror("SSL_CTX_use_PrivateKey_file");
876         return 1; /* FAILED */
877     }
878     s_log(LOG_INFO, "Private key loaded from file: %s", section->key);
879     return 0; /* OK */
880 }
881 
882 #ifndef OPENSSL_NO_ENGINE
883 
load_cert_engine(SERVICE_OPTIONS * section)884 NOEXPORT int load_cert_engine(SERVICE_OPTIONS *section) {
885     struct {
886         const char *id;
887         X509 *cert;
888     } parms;
889 
890     s_log(LOG_INFO, "Loading certificate from engine ID: %s", section->cert);
891     parms.id=section->cert;
892     parms.cert=NULL;
893     ENGINE_ctrl_cmd(section->engine, "LOAD_CERT_CTRL", 0, &parms, NULL, 1);
894     if(!parms.cert) {
895         sslerror("ENGINE_ctrl_cmd");
896         return 1; /* FAILED */
897     }
898     if(!SSL_CTX_use_certificate(section->ctx, parms.cert)) {
899         sslerror("SSL_CTX_use_certificate");
900         return 1; /* FAILED */
901     }
902     s_log(LOG_INFO, "Certificate loaded from engine ID: %s", section->cert);
903     return 0; /* OK */
904 }
905 
ui_stunnel()906 UI_METHOD *ui_stunnel() {
907     static UI_METHOD *ui_method=NULL;
908 
909     if(ui_method) /* already initialized */
910         return ui_method;
911     ui_method=UI_create_method("stunnel UI");
912     if(!ui_method) {
913         sslerror("UI_create_method");
914         return NULL;
915     }
916     UI_method_set_opener(ui_method, ui_get_opener());
917     UI_method_set_writer(ui_method, ui_get_writer());
918     UI_method_set_reader(ui_method, ui_get_reader());
919     UI_method_set_closer(ui_method, ui_get_closer());
920     return ui_method;
921 }
922 
load_key_engine(SERVICE_OPTIONS * section)923 NOEXPORT int load_key_engine(SERVICE_OPTIONS *section) {
924     int i;
925     EVP_PKEY *pkey;
926 
927     s_log(LOG_INFO, "Initializing private key on engine ID: %s", section->key);
928 
929     /* do not use caching for engine PINs to prevent device lockout */
930     SSL_CTX_set_default_passwd_cb(section->ctx, ui_passwd_cb);
931 
932     for(i=0; i<3; i++) {
933         pkey=ENGINE_load_private_key(section->engine, section->key,
934             ui_stunnel(), NULL);
935         if(!pkey) {
936             if(i<2 && ui_retry()) { /* wrong PIN */
937                 sslerror_queue(); /* dump the error queue */
938                 s_log(LOG_ERR, "Wrong PIN: retrying");
939                 continue;
940             }
941             sslerror("ENGINE_load_private_key");
942             return 1; /* FAILED */
943         }
944         if(SSL_CTX_use_PrivateKey(section->ctx, pkey))
945             break; /* success */
946         sslerror("SSL_CTX_use_PrivateKey");
947         return 1; /* FAILED */
948     }
949     s_log(LOG_INFO, "Private key initialized on engine ID: %s", section->key);
950     return 0; /* OK */
951 }
952 
953 #endif /* !defined(OPENSSL_NO_ENGINE) */
954 
955 /* additional caching layer on top of ui_passwd_cb() */
956 
957 /* retrieve the cached passwd */
cache_passwd_get_cb(char * buf,int size,int rwflag,void * userdata)958 NOEXPORT int cache_passwd_get_cb(char *buf, int size,
959         int rwflag, void *userdata) {
960     int len=cached_len;
961 
962     (void)rwflag; /* squash the unused parameter warning */
963     (void)userdata; /* squash the unused parameter warning */
964     if(len<0 || size<0) /* the API uses signed integers */
965         return 0;
966     if(len>size) /* truncate the returned data if needed */
967         len=size;
968     memcpy(buf, cached_passwd, (size_t)len);
969     return len;
970 }
971 
972 /* cache the passwd retrieved from UI */
cache_passwd_set_cb(char * buf,int size,int rwflag,void * userdata)973 NOEXPORT int cache_passwd_set_cb(char *buf, int size,
974         int rwflag, void *userdata) {
975     memset(cached_passwd, 0, sizeof cached_passwd);
976     cached_len=ui_passwd_cb(cached_passwd, sizeof cached_passwd,
977         rwflag, userdata);
978     return cache_passwd_get_cb(buf, size, rwflag, userdata);
979 }
980 
set_prompt(const char * name)981 NOEXPORT void set_prompt(const char *name) {
982     char *prompt;
983 
984     prompt=str_printf("Enter %s pass phrase:", name);
985     EVP_set_pw_prompt(prompt);
986     str_free(prompt);
987 }
988 
ui_retry()989 NOEXPORT int ui_retry() {
990     unsigned long err=ERR_peek_error();
991 
992     switch(ERR_GET_LIB(err)) {
993     case ERR_LIB_ASN1:
994         return 1;
995     case ERR_LIB_PKCS12:
996         switch(ERR_GET_REASON(err)) {
997         case PKCS12_R_MAC_VERIFY_FAILURE:
998             return 1;
999         default:
1000             return 0;
1001         }
1002     case ERR_LIB_EVP:
1003         switch(ERR_GET_REASON(err)) {
1004         case EVP_R_BAD_DECRYPT:
1005             return 1;
1006         default:
1007             return 0;
1008         }
1009     case ERR_LIB_PEM:
1010         switch(ERR_GET_REASON(err)) {
1011         case PEM_R_BAD_PASSWORD_READ:
1012             return 1;
1013         default:
1014             return 0;
1015         }
1016     case ERR_LIB_UI:
1017         switch(ERR_GET_REASON(err)) {
1018         case UI_R_RESULT_TOO_LARGE:
1019         case UI_R_RESULT_TOO_SMALL:
1020 #ifdef UI_R_PROCESSING_ERROR
1021         case UI_R_PROCESSING_ERROR:
1022 #endif
1023             return 1;
1024         default:
1025             return 0;
1026         }
1027     case ERR_LIB_USER: /* PKCS#11 hacks */
1028         switch(ERR_GET_REASON(err)) {
1029         case 7UL: /* CKR_ARGUMENTS_BAD */
1030         case 0xa0UL: /* CKR_PIN_INCORRECT */
1031             return 1;
1032         default:
1033             return 0;
1034         }
1035     default:
1036         return 0;
1037     }
1038 }
1039 
1040 /**************************************** session tickets */
1041 
1042 #if OPENSSL_VERSION_NUMBER >= 0x10101000L
1043 
1044 typedef struct {
1045     void *session_authenticated;
1046 #if 0
1047     SOCKADDR_UNION addr;
1048 #endif
1049 } TICKET_DATA;
1050 
generate_session_ticket_cb(SSL * ssl,void * arg)1051 NOEXPORT int generate_session_ticket_cb(SSL *ssl, void *arg) {
1052     SSL_SESSION *sess;
1053     TICKET_DATA ticket_data;
1054 #if 0
1055     SOCKADDR_UNION *addr;
1056 #endif
1057     int retval;
1058 
1059     (void)arg; /* squash the unused parameter warning */
1060 
1061     s_log(LOG_DEBUG, "Generate session ticket callback");
1062 
1063     sess=SSL_get1_session(ssl);
1064     if(!sess)
1065         return 0;
1066     memset(&ticket_data, 0, sizeof(TICKET_DATA));
1067 
1068     ticket_data.session_authenticated=
1069         SSL_SESSION_get_ex_data(sess, index_session_authenticated);
1070 
1071 #if 0
1072     /* TODO: add remote_start() invocation here */
1073     CRYPTO_THREAD_read_lock(stunnel_locks[LOCK_ADDR]);
1074     addr=SSL_SESSION_get_ex_data(sess, index_session_connect_address);
1075     if(addr)
1076         memcpy(&ticket_data.addr, addr, (size_t)addr_len(addr));
1077     CRYPTO_THREAD_unlock(stunnel_locks[LOCK_ADDR]);
1078 #endif
1079 
1080     retval=SSL_SESSION_set1_ticket_appdata(sess,
1081         &ticket_data, sizeof(TICKET_DATA));
1082     SSL_SESSION_free(sess);
1083     return retval;
1084 }
1085 
decrypt_session_ticket_cb(SSL * ssl,SSL_SESSION * sess,const unsigned char * keyname,size_t keyname_len,SSL_TICKET_STATUS status,void * arg)1086 NOEXPORT int decrypt_session_ticket_cb(SSL *ssl, SSL_SESSION *sess,
1087         const unsigned char *keyname, size_t keyname_len,
1088         SSL_TICKET_STATUS status, void *arg) {
1089     TICKET_DATA *ticket_data;
1090     size_t ticket_len;
1091 
1092     (void)ssl; /* squash the unused parameter warning */
1093     (void)keyname; /* squash the unused parameter warning */
1094     (void)keyname_len; /* squash the unused parameter warning */
1095     (void)arg; /* squash the unused parameter warning */
1096 
1097     s_log(LOG_DEBUG, "Decrypt session ticket callback");
1098 
1099     switch(status) {
1100     case SSL_TICKET_EMPTY:
1101     case SSL_TICKET_NO_DECRYPT:
1102         return SSL_TICKET_RETURN_IGNORE_RENEW;
1103     case SSL_TICKET_SUCCESS:
1104     case SSL_TICKET_SUCCESS_RENEW:
1105         break;
1106     default:
1107         return SSL_TICKET_RETURN_ABORT;
1108     }
1109 
1110     if(!SSL_SESSION_get0_ticket_appdata(sess,
1111             (void **)&ticket_data, &ticket_len)) {
1112         s_log(LOG_WARNING, "Failed to get ticket application data");
1113         return SSL_TICKET_RETURN_IGNORE_RENEW;
1114     }
1115     if(!ticket_data) {
1116         s_log(LOG_WARNING, "Invalid ticket application data value");
1117         return SSL_TICKET_RETURN_IGNORE_RENEW;
1118     }
1119     if(ticket_len != sizeof(TICKET_DATA)) {
1120         s_log(LOG_WARNING, "Invalid ticket application data length");
1121         return SSL_TICKET_RETURN_IGNORE_RENEW;
1122     }
1123 
1124     s_log(LOG_INFO, "Decrypted ticket for an authenticated session: %s",
1125         ticket_data->session_authenticated ? "yes" : "no");
1126     SSL_SESSION_set_ex_data(sess, index_session_authenticated,
1127         ticket_data->session_authenticated);
1128 
1129 #if 0
1130     if(ticket_data->addr.sa.sa_family) {
1131         char *addr_txt;
1132         SOCKADDR_UNION *old_addr;
1133 
1134         addr_txt=s_ntop(&ticket_data->addr, addr_len(&ticket_data->addr));
1135         s_log(LOG_INFO, "Decrypted ticket persistence address: %s", addr_txt);
1136         str_free(addr_txt);
1137         CRYPTO_THREAD_write_lock(stunnel_locks[LOCK_ADDR]);
1138         old_addr=SSL_SESSION_get_ex_data(sess, index_session_connect_address);
1139         if(SSL_SESSION_set_ex_data(sess, index_session_connect_address, &ticket_data->addr)) {
1140             CRYPTO_THREAD_unlock(stunnel_locks[LOCK_ADDR]);
1141             str_free(old_addr); /* NULL pointers are ignored */
1142         } else { /* failed to store ticket_data->addr */
1143             CRYPTO_THREAD_unlock(stunnel_locks[LOCK_ADDR]);
1144             sslerror("SSL_SESSION_set_ex_data");
1145         }
1146     } else {
1147         s_log(LOG_INFO, "Decrypted ticket did not include a persistence address");
1148     }
1149 #endif
1150 
1151     switch(status) {
1152     case SSL_TICKET_SUCCESS:
1153         return SSL_TICKET_RETURN_USE;
1154     case SSL_TICKET_SUCCESS_RENEW:
1155         return SSL_TICKET_RETURN_USE_RENEW;
1156     }
1157     return SSL_TICKET_RETURN_ABORT; /* it should never get executed */
1158 }
1159 #endif
1160 
1161 #if OPENSSL_VERSION_NUMBER>=0x10000000L
ssl_tlsext_ticket_key_cb(SSL * ssl,unsigned char * key_name,unsigned char * iv,EVP_CIPHER_CTX * ctx,HMAC_CTX * hctx,int enc)1162 NOEXPORT int ssl_tlsext_ticket_key_cb(SSL *ssl, unsigned char *key_name,
1163         unsigned char *iv, EVP_CIPHER_CTX *ctx, HMAC_CTX *hctx, int enc) {
1164     CLI *c;
1165     const EVP_CIPHER *cipher;
1166     int iv_len;
1167 
1168     (void)key_name; /* squash the unused parameter warning */
1169     s_log(LOG_DEBUG, "Session ticket processing callback");
1170 
1171     c=SSL_get_ex_data(ssl, index_ssl_cli);
1172     if(!HMAC_Init_ex(hctx, (const unsigned char *)(c->opt->ticket_mac->key_val),
1173         c->opt->ticket_mac->key_len, EVP_sha256(), NULL)) {
1174         s_log(LOG_ERR, "HMAC_Init_ex failed");
1175         return -1;
1176     }
1177     if(c->opt->ticket_key->key_len == 16)
1178         cipher=EVP_aes_128_cbc();
1179     else /* c->opt->ticket_key->key_len == 32 */
1180         cipher=EVP_aes_256_cbc();
1181     if(enc) { /* create new session */
1182         /* EVP_CIPHER_iv_length() returns 16 for either cipher EVP_aes_128_cbc() or EVP_aes_256_cbc() */
1183         iv_len=EVP_CIPHER_iv_length(cipher);
1184         if(RAND_bytes(iv, iv_len) <= 0) { /* RAND_bytes error */
1185             s_log(LOG_ERR, "RAND_bytes failed");
1186             return -1;
1187         }
1188         if(!EVP_EncryptInit_ex(ctx, cipher, NULL,
1189             (const unsigned char *)(c->opt->ticket_key->key_val), iv)) {
1190             s_log(LOG_ERR, "EVP_EncryptInit_ex failed");
1191             return -1;
1192         }
1193     } else /* retrieve session */
1194         if(!EVP_DecryptInit_ex(ctx, cipher, NULL,
1195             (const unsigned char *)(c->opt->ticket_key->key_val), iv)) {
1196             s_log(LOG_ERR, "EVP_DecryptInit_ex failed");
1197             return -1;
1198         }
1199     /* By default, in TLSv1.2 and below, a new session ticket */
1200     /* is not issued on a successful resumption. */
1201     /* In TLSv1.3 the default behaviour is to always issue a new ticket on resumption. */
1202     /* This behaviour can NOT be changed if this ticket key callback is in use! */
1203     if(strcmp(SSL_get_version(c->ssl), "TLSv1.3"))
1204         return 1; /* new session ticket is not issued */
1205     else
1206         return 2; /* session ticket should be replaced */
1207 }
1208 #endif /* OpenSSL 1.0.0 or later */
1209 
1210 /**************************************** session callbacks */
1211 
sess_new_cb(SSL * ssl,SSL_SESSION * sess)1212 NOEXPORT int sess_new_cb(SSL *ssl, SSL_SESSION *sess) {
1213     CLI *c;
1214 
1215     s_log(LOG_DEBUG, "New session callback");
1216     c=SSL_get_ex_data(ssl, index_ssl_cli);
1217 
1218     new_chain(c); /* new session -> we may have a new peer certificate chain */
1219 
1220     if(c->opt->option.client)
1221         session_cache_save(c, sess);
1222 
1223     if(c->opt->option.sessiond)
1224         cache_new(ssl, sess);
1225 
1226     print_session_id(sess);
1227 
1228     return 0; /* the OpenSSL's manual is really bad -> use the source here */
1229 }
1230 
1231 #if OPENSSL_VERSION_NUMBER<0x0090800fL
SSL_SESSION_get_id(const SSL_SESSION * s,unsigned int * len)1232 NOEXPORT const unsigned char *SSL_SESSION_get_id(const SSL_SESSION *s,
1233         unsigned int *len) {
1234     if(len)
1235         *len=s->session_id_length;
1236     return (const unsigned char *)s->session_id;
1237 }
1238 #endif
1239 
print_session_id(SSL_SESSION * sess)1240 void print_session_id(SSL_SESSION *sess) {
1241     const unsigned char *session_id;
1242     unsigned int session_id_length;
1243     char session_id_txt[2*SSL_MAX_SSL_SESSION_ID_LENGTH+1];
1244 
1245     session_id=SSL_SESSION_get_id(sess, &session_id_length);
1246     bin2hexstring(session_id, session_id_length,
1247         session_id_txt, sizeof session_id_txt);
1248     s_log(LOG_INFO, "Session id: %s", session_id_txt);
1249 }
1250 
new_chain(CLI * c)1251 NOEXPORT void new_chain(CLI *c) {
1252     BIO *bio;
1253     int i, len;
1254     X509 *peer_cert;
1255     STACK_OF(X509) *sk;
1256     char *chain;
1257 
1258     if(c->opt->chain) /* already cached */
1259         return; /* this race condition is safe to ignore */
1260     bio=BIO_new(BIO_s_mem());
1261     if(!bio)
1262         return;
1263     sk=SSL_get_peer_cert_chain(c->ssl);
1264     for(i=0; sk && i<sk_X509_num(sk); i++) {
1265         peer_cert=sk_X509_value(sk, i);
1266         PEM_write_bio_X509(bio, peer_cert);
1267     }
1268     if(!sk || !c->opt->option.client) {
1269         peer_cert=SSL_get_peer_certificate(c->ssl);
1270         if(peer_cert) {
1271             PEM_write_bio_X509(bio, peer_cert);
1272             X509_free(peer_cert);
1273         }
1274     }
1275     len=BIO_pending(bio);
1276     if(len<=0) {
1277         s_log(LOG_INFO, "No peer certificate received");
1278         BIO_free(bio);
1279         return;
1280     }
1281     /* prevent automatic deallocation of the cached value */
1282     chain=str_alloc_detached((size_t)len+1);
1283     len=BIO_read(bio, chain, len);
1284     if(len<0) {
1285         s_log(LOG_ERR, "BIO_read failed");
1286         BIO_free(bio);
1287         str_free(chain);
1288         return;
1289     }
1290     chain[len]='\0';
1291     BIO_free(bio);
1292     c->opt->chain=chain; /* this race condition is safe to ignore */
1293     ui_new_chain(c->opt->section_number);
1294     s_log(LOG_DEBUG, "Peer certificate was cached (%d bytes)", len);
1295 }
1296 
1297 /* cache client sessions */
session_cache_save(CLI * c,SSL_SESSION * sess)1298 NOEXPORT void session_cache_save(CLI *c, SSL_SESSION *sess) {
1299     SSL_SESSION *old;
1300 
1301 #if OPENSSL_VERSION_NUMBER>=0x10100000L
1302     SSL_SESSION_up_ref(sess);
1303 #else
1304     sess=SSL_get1_session(c->ssl);
1305 #endif
1306 
1307     CRYPTO_THREAD_write_lock(stunnel_locks[LOCK_SESSION]);
1308     if(c->opt->option.delayed_lookup) {
1309         old=c->opt->session;
1310         c->opt->session=sess;
1311     } else { /* per-destination client cache */
1312         if(c->opt->connect_session) {
1313             old=c->opt->connect_session[c->idx];
1314             c->opt->connect_session[c->idx]=sess;
1315         } else {
1316             s_log(LOG_ERR, "INTERNAL ERROR: Uninitialized client session cache");
1317             old=NULL;
1318         }
1319     }
1320     CRYPTO_THREAD_unlock(stunnel_locks[LOCK_SESSION]);
1321 
1322     if(old)
1323         SSL_SESSION_free(old);
1324 }
1325 
sess_get_cb(SSL * ssl,const unsigned char * key,int key_len,int * do_copy)1326 NOEXPORT SSL_SESSION *sess_get_cb(SSL *ssl,
1327 #if OPENSSL_VERSION_NUMBER>=0x10100000L
1328         const
1329 #endif
1330         unsigned char *key, int key_len, int *do_copy) {
1331     CLI *c;
1332 
1333     s_log(LOG_DEBUG, "Get session callback");
1334     *do_copy=0; /* allow the session to be freed automatically */
1335     c=SSL_get_ex_data(ssl, index_ssl_cli);
1336     if(c->opt->option.sessiond)
1337         return cache_get(ssl, key, key_len);
1338     return NULL; /* no session to resume */
1339 }
1340 
sess_remove_cb(SSL_CTX * ctx,SSL_SESSION * sess)1341 NOEXPORT void sess_remove_cb(SSL_CTX *ctx, SSL_SESSION *sess) {
1342     SERVICE_OPTIONS *opt;
1343 
1344     s_log(LOG_DEBUG, "Remove session callback");
1345     opt=SSL_CTX_get_ex_data(ctx, index_ssl_ctx_opt);
1346     if(opt->option.sessiond)
1347         cache_remove(ctx, sess);
1348 }
1349 
1350 /**************************************** sessiond functionality */
1351 
1352 #define CACHE_CMD_NEW     0x00
1353 #define CACHE_CMD_GET     0x01
1354 #define CACHE_CMD_REMOVE  0x02
1355 #define CACHE_RESP_ERR    0x80
1356 #define CACHE_RESP_OK     0x81
1357 
cache_new(SSL * ssl,SSL_SESSION * sess)1358 NOEXPORT void cache_new(SSL *ssl, SSL_SESSION *sess) {
1359     unsigned char *val, *val_tmp;
1360     ssize_t val_len;
1361     const unsigned char *session_id;
1362     unsigned int session_id_length;
1363 
1364     val_len=i2d_SSL_SESSION(sess, NULL);
1365     val_tmp=val=str_alloc((size_t)val_len);
1366     i2d_SSL_SESSION(sess, &val_tmp);
1367 
1368     session_id=SSL_SESSION_get_id(sess, &session_id_length);
1369     cache_transfer(SSL_get_SSL_CTX(ssl), CACHE_CMD_NEW,
1370         SSL_SESSION_get_timeout(sess),
1371         session_id, session_id_length, val, (size_t)val_len, NULL, NULL);
1372     str_free(val);
1373 }
1374 
cache_get(SSL * ssl,const unsigned char * key,int key_len)1375 NOEXPORT SSL_SESSION *cache_get(SSL *ssl,
1376         const unsigned char *key, int key_len) {
1377     unsigned char *val=NULL, *val_tmp=NULL;
1378     ssize_t val_len=0;
1379     SSL_SESSION *sess;
1380 
1381     cache_transfer(SSL_get_SSL_CTX(ssl), CACHE_CMD_GET, 0,
1382         key, (size_t)key_len, NULL, 0, &val, (size_t *)&val_len);
1383     if(!val)
1384         return NULL;
1385     val_tmp=val;
1386     sess=d2i_SSL_SESSION(NULL,
1387 #if OPENSSL_VERSION_NUMBER>=0x0090707fL
1388         (const unsigned char **)
1389 #endif /* OpenSSL version >= 0.9.7g */
1390         &val_tmp, (long)val_len);
1391     str_free(val);
1392     return sess;
1393 }
1394 
cache_remove(SSL_CTX * ctx,SSL_SESSION * sess)1395 NOEXPORT void cache_remove(SSL_CTX *ctx, SSL_SESSION *sess) {
1396     const unsigned char *session_id;
1397     unsigned int session_id_length;
1398 
1399     session_id=SSL_SESSION_get_id(sess, &session_id_length);
1400     cache_transfer(ctx, CACHE_CMD_REMOVE, 0,
1401         session_id, session_id_length, NULL, 0, NULL, NULL);
1402 }
1403 
1404 #define MAX_VAL_LEN 512
1405 typedef struct {
1406     u_char version, type;
1407     u_short timeout;
1408     u_char key[SSL_MAX_SSL_SESSION_ID_LENGTH];
1409     u_char val[MAX_VAL_LEN];
1410 } CACHE_PACKET;
1411 
cache_transfer(SSL_CTX * ctx,const u_char type,const long timeout,const u_char * key,const size_t key_len,const u_char * val,const size_t val_len,unsigned char ** ret,size_t * ret_len)1412 NOEXPORT void cache_transfer(SSL_CTX *ctx, const u_char type,
1413         const long timeout,
1414         const u_char *key, const size_t key_len,
1415         const u_char *val, const size_t val_len,
1416         unsigned char **ret, size_t *ret_len) {
1417     char session_id_txt[2*SSL_MAX_SSL_SESSION_ID_LENGTH+1];
1418     const char *type_description[]={"new", "get", "remove"};
1419     SOCKET s;
1420     ssize_t len;
1421     struct timeval t;
1422     CACHE_PACKET *packet;
1423     SERVICE_OPTIONS *section;
1424 
1425     if(ret) /* set error as the default result if required */
1426         *ret=NULL;
1427 
1428     /* log the request information */
1429     bin2hexstring(key, key_len, session_id_txt, sizeof session_id_txt);
1430     s_log(LOG_INFO,
1431         "cache_transfer: request=%s, timeout=%ld, id=%s, length=%lu",
1432         type_description[type], timeout, session_id_txt, (long unsigned)val_len);
1433 
1434     /* allocate UDP packet buffer */
1435     if(key_len>SSL_MAX_SSL_SESSION_ID_LENGTH) {
1436         s_log(LOG_ERR, "cache_transfer: session id too big (%lu bytes)",
1437             (unsigned long)key_len);
1438         return;
1439     }
1440     if(val_len>MAX_VAL_LEN) {
1441         s_log(LOG_ERR, "cache_transfer: encoded session too big (%lu bytes)",
1442             (unsigned long)key_len);
1443         return;
1444     }
1445     packet=str_alloc(sizeof(CACHE_PACKET));
1446 
1447     /* setup packet */
1448     packet->version=1;
1449     packet->type=type;
1450     packet->timeout=htons((u_short)(timeout<64800?timeout:64800));/* 18 hours */
1451     memcpy(packet->key, key, key_len);
1452     if(val && val_len) /* only check it to make code analysis tools happy */
1453         memcpy(packet->val, val, val_len);
1454 
1455     /* create the socket */
1456     s=s_socket(AF_INET, SOCK_DGRAM, 0, 0, "cache_transfer: socket");
1457     if(s==INVALID_SOCKET) {
1458         str_free(packet);
1459         return;
1460     }
1461 
1462     /* retrieve pointer to the section structure of this ctx */
1463     section=SSL_CTX_get_ex_data(ctx, index_ssl_ctx_opt);
1464     if(sendto(s, (void *)packet,
1465 #ifdef USE_WIN32
1466             (int)
1467 #endif
1468             (sizeof(CACHE_PACKET)-MAX_VAL_LEN+val_len),
1469             0, &section->sessiond_addr.sa,
1470             addr_len(&section->sessiond_addr))<0) {
1471         sockerror("cache_transfer: sendto");
1472         closesocket(s);
1473         str_free(packet);
1474         return;
1475     }
1476 
1477     if(!ret || !ret_len) { /* no response is required */
1478         closesocket(s);
1479         str_free(packet);
1480         return;
1481     }
1482 
1483     /* set recvfrom timeout to 200ms */
1484     t.tv_sec=0;
1485     t.tv_usec=200;
1486     if(setsockopt(s, SOL_SOCKET, SO_RCVTIMEO, (void *)&t, sizeof t)<0) {
1487         sockerror("cache_transfer: setsockopt SO_RCVTIMEO");
1488         closesocket(s);
1489         str_free(packet);
1490         return;
1491     }
1492 
1493     /* retrieve response */
1494     len=recv(s, (void *)packet, sizeof(CACHE_PACKET), 0);
1495     closesocket(s);
1496     if(len<0) {
1497         if(get_last_socket_error()==S_EWOULDBLOCK ||
1498                 get_last_socket_error()==S_EAGAIN)
1499             s_log(LOG_INFO, "cache_transfer: recv timeout");
1500         else
1501             sockerror("cache_transfer: recv");
1502         str_free(packet);
1503         return;
1504     }
1505 
1506     /* parse results */
1507     if(len<(int)sizeof(CACHE_PACKET)-MAX_VAL_LEN || /* too short */
1508             packet->version!=1 || /* wrong version */
1509             safe_memcmp(packet->key, key, key_len)) { /* wrong session id */
1510         s_log(LOG_DEBUG, "cache_transfer: malformed packet received");
1511         str_free(packet);
1512         return;
1513     }
1514     if(packet->type!=CACHE_RESP_OK) {
1515         s_log(LOG_INFO, "cache_transfer: session not found");
1516         str_free(packet);
1517         return;
1518     }
1519     *ret_len=(size_t)len-(sizeof(CACHE_PACKET)-MAX_VAL_LEN);
1520     *ret=str_alloc(*ret_len);
1521     s_log(LOG_INFO, "cache_transfer: session found");
1522     memcpy(*ret, packet->val, *ret_len);
1523     str_free(packet);
1524 }
1525 
1526 /**************************************** informational callback */
1527 
info_callback(const SSL * ssl,int where,int ret)1528 NOEXPORT void info_callback(const SSL *ssl, int where, int ret) {
1529     CLI *c;
1530     SSL_CTX *ctx;
1531     const char *state_string;
1532 
1533     c=SSL_get_ex_data((SSL *)ssl, index_ssl_cli);
1534     if(c) {
1535 #if OPENSSL_VERSION_NUMBER>=0x10100000L
1536         OSSL_HANDSHAKE_STATE state=SSL_get_state(ssl);
1537 #else
1538         int state=SSL_get_state((SSL *)ssl);
1539 #endif
1540 
1541 #if 0
1542         s_log(LOG_DEBUG, "state = %x", state);
1543 #endif
1544 
1545         /* log the client certificate request (if received) */
1546 #ifndef SSL3_ST_CR_CERT_REQ_A
1547         if(state==TLS_ST_CR_CERT_REQ)
1548 #else
1549         if(state==SSL3_ST_CR_CERT_REQ_A)
1550 #endif
1551             print_client_CA_list(SSL_get_client_CA_list((SSL *)ssl));
1552 #ifndef SSL3_ST_CR_SRVR_DONE_A
1553         if(state==TLS_ST_CR_SRVR_DONE)
1554 #else
1555         if(state==SSL3_ST_CR_SRVR_DONE_A)
1556 #endif
1557             if(!SSL_get_client_CA_list((SSL *)ssl))
1558                 s_log(LOG_INFO, "Client certificate not requested");
1559 
1560         /* prevent renegotiation DoS attack */
1561         if((where&SSL_CB_HANDSHAKE_DONE)
1562                 && c->reneg_state==RENEG_INIT) {
1563             /* first (initial) handshake was completed, remember this,
1564              * so that further renegotiation attempts can be detected */
1565             c->reneg_state=RENEG_ESTABLISHED;
1566         } else if((where&SSL_CB_ACCEPT_LOOP)
1567                 && c->reneg_state==RENEG_ESTABLISHED) {
1568 #ifndef SSL3_ST_SR_CLNT_HELLO_A
1569             if(state==TLS_ST_SR_CLNT_HELLO) {
1570 #else
1571             if(state==SSL3_ST_SR_CLNT_HELLO_A
1572                     || state==SSL23_ST_SR_CLNT_HELLO_A) {
1573 #endif
1574                 /* client hello received after initial handshake,
1575                  * this means renegotiation -> mark it */
1576                 c->reneg_state=RENEG_DETECTED;
1577             }
1578         }
1579 
1580         if(c->opt->log_level<LOG_DEBUG) /* performance optimization */
1581             return;
1582     }
1583 
1584     if(where & SSL_CB_LOOP) {
1585         state_string=SSL_state_string_long(ssl);
1586         if(strcmp(state_string, "unknown state"))
1587             s_log(LOG_DEBUG, "TLS state (%s): %s",
1588                 (where & SSL_ST_CONNECT) ? "connect" :
1589                 (where & SSL_ST_ACCEPT) ? "accept" :
1590                 "undefined", state_string);
1591     } else if(where & SSL_CB_ALERT) {
1592         s_log(LOG_DEBUG, "TLS alert (%s): %s: %s",
1593             (where & SSL_CB_READ) ? "read" : "write",
1594             SSL_alert_type_string_long(ret),
1595             SSL_alert_desc_string_long(ret));
1596     } else if(where==SSL_CB_HANDSHAKE_DONE) {
1597         ctx=SSL_get_SSL_CTX((SSL *)ssl);
1598         if(c->opt->option.client) {
1599             s_log(LOG_DEBUG, "%6ld client connect(s) requested",
1600                 SSL_CTX_sess_connect(ctx));
1601             s_log(LOG_DEBUG, "%6ld client connect(s) succeeded",
1602                 SSL_CTX_sess_connect_good(ctx));
1603             s_log(LOG_DEBUG, "%6ld client renegotiation(s) requested",
1604                 SSL_CTX_sess_connect_renegotiate(ctx));
1605         } else {
1606             s_log(LOG_DEBUG, "%6ld server accept(s) requested",
1607                 SSL_CTX_sess_accept(ctx));
1608             s_log(LOG_DEBUG, "%6ld server accept(s) succeeded",
1609                 SSL_CTX_sess_accept_good(ctx));
1610             s_log(LOG_DEBUG, "%6ld server renegotiation(s) requested",
1611                 SSL_CTX_sess_accept_renegotiate(ctx));
1612         }
1613         /* according to the source it not only includes internal
1614            and external session caches, but also session tickets */
1615         s_log(LOG_DEBUG, "%6ld session reuse(s)",
1616             SSL_CTX_sess_hits(ctx));
1617         if(!c->opt->option.client) { /* server session cache stats */
1618             s_log(LOG_DEBUG, "%6ld internal session cache item(s)",
1619                 SSL_CTX_sess_number(ctx));
1620             s_log(LOG_DEBUG, "%6ld internal session cache fill-up(s)",
1621                 SSL_CTX_sess_cache_full(ctx));
1622             s_log(LOG_DEBUG, "%6ld internal session cache miss(es)",
1623                 SSL_CTX_sess_misses(ctx));
1624             s_log(LOG_DEBUG, "%6ld external session cache hit(s)",
1625                 SSL_CTX_sess_cb_hits(ctx));
1626             s_log(LOG_DEBUG, "%6ld expired session(s) retrieved",
1627                 SSL_CTX_sess_timeouts(ctx));
1628         }
1629     }
1630 }
1631 
1632 /**************************************** TLS error reporting */
1633 
1634 void sslerror(char *txt) { /* OpenSSL error handler */
1635     unsigned long err;
1636     const char *file;
1637     int line;
1638 
1639     err=ERR_get_error_line(&file, &line);
1640     if(err) {
1641         sslerror_queue();
1642         sslerror_log(err, file, line, txt);
1643     } else {
1644         s_log(LOG_ERR, "%s: Peer suddenly disconnected", txt);
1645     }
1646 }
1647 
1648 NOEXPORT void sslerror_queue(void) { /* recursive dump of the error queue */
1649     unsigned long err;
1650     const char *file;
1651     int line;
1652 
1653     err=ERR_get_error_line(&file, &line);
1654     if(err) {
1655         sslerror_queue();
1656         sslerror_log(err, file, line, "error queue");
1657     }
1658 }
1659 
1660 NOEXPORT void sslerror_log(unsigned long err,
1661         const char *file, int line, char *txt) {
1662     char *str;
1663 
1664     str=str_alloc(256);
1665     ERR_error_string_n(err, str, 256);
1666     s_log(LOG_ERR, "%s: %s:%d: %s", txt, file, line, str);
1667     str_free(str);
1668 }
1669 
1670 /* end of ctx.c */
1671