Debian Codegraph @

src/client.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 #ifndef SHUT_RD
41 #define SHUT_RD 0
42 #endif
43 #ifndef SHUT_WR
44 #define SHUT_WR 1
45 #endif
46 #ifndef SHUT_RDWR
47 #define SHUT_RDWR 2
48 #endif
49
50 NOEXPORT void client_try(CLI *);
51 NOEXPORT void exec_connect_loop(CLI *);
52 NOEXPORT void exec_connect_once(CLI *);
53 NOEXPORT void client_run(CLI *);
54 NOEXPORT void local_start(CLI *);
55 NOEXPORT void remote_start(CLI *);
56 NOEXPORT void ssl_start(CLI *);
57 NOEXPORT void session_cache_retrieve(CLI *);
58 #if OPENSSL_VERSION_NUMBER >= 0x10101000L
59 NOEXPORT void print_tmp_key(SSL *s);
60 #endif
61 NOEXPORT void print_cipher(CLI *);
62 NOEXPORT void transfer(CLI *);
63
64 NOEXPORT void auth_user(CLI *);
65 NOEXPORT SOCKET connect_local(CLI *);
66 #if !defined(USE_WIN32) && !defined(__vms)
67 NOEXPORT char **env_alloc(CLI *);
68 NOEXPORT void env_free(char **);
69 #endif
70 NOEXPORT SOCKET connect_remote(CLI *);
71 NOEXPORT void idx_cache_save(SSL_SESSION *, SOCKADDR_UNION *);
72 NOEXPORT unsigned idx_cache_retrieve(CLI *);
73 NOEXPORT void connect_setup(CLI *);
74 NOEXPORT int connect_init(CLI *, int);
75 NOEXPORT int redirect(CLI *);
76 NOEXPORT void print_bound_address(CLI *);
77 NOEXPORT void reset(SOCKET, const char *);
78 NOEXPORT void check_socket_error(CLI *, SOCKET, const char *);
79
80 /* allocate local data structure for the new thread */
81 CLI *alloc_client_session(SERVICE_OPTIONS *opt, SOCKET rfd, SOCKET wfd) {
82 static unsigned long long seq=0;
83 CLI *c;
84
85 c=str_alloc_detached(sizeof(CLI));
86 c->opt=opt;
87 c->local_rfd.fd=rfd;
88 c->local_wfd.fd=wfd;
89 c->seq=seq++;
90 c->rr=c->opt->rr++;
91 return c;
92 }
93
94 #if defined(USE_WIN32) || defined(USE_OS2)
95 unsigned __stdcall
96 #else
97 void *
98 #endif
99 client_thread(void *arg) {
100 CLI *c=arg;
101 #ifdef DEBUG_STACK_SIZE
102 size_t stack_size=c->opt->stack_size;
103 #endif
104
105 #ifdef USE_FORK
106 /* do not use signal pipe in child processes */
107 signal(SIGCHLD, SIG_IGN); /* ignore dead children */
108 signal(SIGHUP, SIG_DFL);
109 signal(SIGUSR1, SIG_DFL);
110 signal(SIGUSR2, SIG_DFL);
111 signal(SIGPIPE, SIG_IGN); /* ignore broken pipe */
112 signal(SIGTERM, SIG_DFL);
113 signal(SIGQUIT, SIG_DFL);
114 signal(SIGINT, SIG_DFL);
115 #endif /* USE_FORK */
116
117 /* make sure c->thread_* values are initialized */
118 CRYPTO_THREAD_read_lock(stunnel_locks[LOCK_THREAD_LIST]);
119 CRYPTO_THREAD_unlock(stunnel_locks[LOCK_THREAD_LIST]);
120
121 /* initialize */
122 c->tls=NULL; /* do not reuse */
123 tls_alloc(c, NULL, NULL);
124 #ifdef DEBUG_STACK_SIZE
125 stack_info(stack_size, 1); /* initialize */
126 #endif
127
128 /* execute */
129 client_main(c);
130
131 /* cleanup the thread */
132 #ifndef USE_FORK
133 CRYPTO_THREAD_write_lock(stunnel_locks[LOCK_THREAD_LIST]);
134 if(thread_head==c)
135 thread_head=c->thread_next;
136 if(c->thread_prev)
137 c->thread_prev->thread_next=c->thread_next;
138 if(c->thread_next)
139 c->thread_next->thread_prev=c->thread_prev;
140 #ifdef USE_PTHREAD
141 pthread_detach(c->thread_id);
142 #endif
143 #ifdef USE_WIN32
144 CloseHandle(c->thread_id);
145 #endif
146 CRYPTO_THREAD_unlock(stunnel_locks[LOCK_THREAD_LIST]);
147 #endif /* !USE_FORK */
148 client_free(c);
149 #ifdef DEBUG_STACK_SIZE
150 stack_info(stack_size, 0); /* display computed value */
151 #endif
152 str_stats(); /* client thread allocation tracking */
153 tls_cleanup();
154 /* s_log() is not allowed after tls_cleanup() */
155
156 /* terminate the thread */
157 #if defined(USE_WIN32) || defined(USE_OS2)
158 #if !defined(_WIN32_WCE)
159 _endthreadex(0);
160 #endif
161 return 0;
162 #else
163 #ifdef USE_UCONTEXT
164 s_poll_wait(NULL, 0, 0); /* wait on poll() */
165 #endif
166 return NULL;
167 #endif
168 }
169
170 #ifdef DEBUG_STACK_SIZE
171 void ignore_value(void *ptr) {
172 (void)ptr; /* squash the unused parameter warning */
173 }
174 #endif
175
176 void client_main(CLI *c) {
177 s_log(LOG_DEBUG, "Service [%s] started", c->opt->servname);
178 if(c->opt->exec_name && c->opt->connect_addr.names) {
179 if(c->opt->retry >= 0)
180 exec_connect_loop(c);
181 else
182 exec_connect_once(c);
183 } else {
184 client_run(c);
185 }
186 }
187
188 void client_free(CLI *c) {
189 #ifndef USE_FORK
190 service_free(c->opt);
191 #endif
192 str_free(c);
193 }
194
195 #ifdef __GNUC__
196 #if __GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6)
197 #pragma GCC diagnostic push
198 #endif /* __GNUC__>=4.6 */
199 #pragma GCC diagnostic ignored "-Wformat"
200 #pragma GCC diagnostic ignored "-Wformat-extra-args"
201 #endif /* __GNUC__ */
202 NOEXPORT void exec_connect_loop(CLI *c) {
203 unsigned long long seq=0;
204 const char *fresh_id=c->tls->id;
205 long retry;
206
207 do {
208 /* make sure c->tls->id is valid in str_printf() */
209 char *id=str_printf("%s_%llu", fresh_id, seq++);
210 str_detach(id);
211 c->tls->id=id;
212
213 exec_connect_once(c);
214 /* retry is asynchronously changed in the main thread,
215 * so we make sure to use the same value for both checks */
216 retry=c->opt->retry;
217 if(retry >= 0) {
218 s_log(LOG_INFO, "Retrying an exec+connect section");
219 /* c and id are detached, so it is safe to call str_stats() */
220 str_stats(); /* client thread allocation tracking */
221 if(retry)
222 s_poll_sleep((int)(retry/1000), (int)(retry%1000));
223 c->rr++;
224 }
225
226 /* make sure c->tls->id is valid in str_free() */
227 c->tls->id=fresh_id;
228 str_free(id);
229 } while(retry >= 0); /* retry is disabled on config reload */
230 }
231 #ifdef __GNUC__
232 #if __GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6)
233 #pragma GCC diagnostic pop
234 #endif /* __GNUC__>=4.6 */
235 #endif /* __GNUC__ */
236
237 /* exec+connect options specified together
238 * -> spawn a local program instead of stdio */
239 NOEXPORT void exec_connect_once(CLI *fresh_c) {
240 jmp_buf exception_buffer, *exception_backup;
241 /* connect_local() needs an unmodified copy of c each time */
242 CLI *c=str_alloc(sizeof(CLI));
243 memcpy(c, fresh_c, sizeof(CLI));
244
245 exception_backup=c->exception_pointer;
246 c->exception_pointer=&exception_buffer;
247 if(!setjmp(exception_buffer)) {
248 c->local_rfd.fd=c->local_wfd.fd=connect_local(c);
249 client_run(c);
250 }
251 c->exception_pointer=exception_backup;
252
253 str_free(c);
254 }
255
256 #ifdef __GNUC__
257 #if __GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6)
258 #pragma GCC diagnostic push
259 #endif /* __GNUC__>=4.6 */
260 #pragma GCC diagnostic ignored "-Wformat"
261 #pragma GCC diagnostic ignored "-Wformat-extra-args"
262 #endif /* __GNUC__ */
263 NOEXPORT void client_run(CLI *c) {
264 jmp_buf exception_buffer, *exception_backup;
265 int err, rst_remote, rst_local;
266 char *close_status;
267 #ifndef USE_FORK
268 int num;
269 #endif
270
271 #ifndef USE_FORK
272 #ifdef USE_OS_THREADS
273 CRYPTO_atomic_add(&num_clients, 1, &num, stunnel_locks[LOCK_CLIENTS]);
274 #else
275 num=++num_clients;
276 #endif
277 ui_clients(num);
278 #endif
279
280 /* initialize the client context */
281 c->remote_fd.fd=INVALID_SOCKET;
282 c->fd=INVALID_SOCKET;
283 c->ssl=NULL;
284 c->sock_bytes=c->ssl_bytes=0;
285 if(c->opt->option.client) {
286 c->sock_rfd=&(c->local_rfd);
287 c->sock_wfd=&(c->local_wfd);
288 c->ssl_rfd=c->ssl_wfd=&(c->remote_fd);
289 } else {
290 c->sock_rfd=c->sock_wfd=&(c->remote_fd);
291 c->ssl_rfd=&(c->local_rfd);
292 c->ssl_wfd=&(c->local_wfd);
293 }
294 c->fds=s_poll_alloc();
295 addrlist_clear(&c->connect_addr, 0);
296
297 /* try to process the request */
298 exception_backup=c->exception_pointer;
299 c->exception_pointer=&exception_buffer;
300 err=setjmp(exception_buffer);
301 if(!err) {
302 client_try(c);
303 }
304 c->exception_pointer=exception_backup;
305
306 /* plain socket is remote in the server mode */
307 rst_remote=err==1 && c->opt->option.reset &&
308 (!c->fatal_alert || !c->opt->option.client);
309 /* plain socket is local in the client mode */
310 rst_local=err==1 && c->opt->option.reset &&
311 (!c->fatal_alert || c->opt->option.client);
312 if(rst_remote && rst_local)
313 close_status="reset";
314 else if(rst_remote)
315 close_status="reset/closed";
316 else if(rst_local)
317 close_status="closed/reset";
318 else
319 close_status="closed";
320 s_log(LOG_NOTICE,
321 "Connection %s: %llu byte(s) sent to TLS, %llu byte(s) sent to socket",
322 close_status,
323 (unsigned long long)c->ssl_bytes, (unsigned long long)c->sock_bytes);
324 #ifdef USE_WIN32
325 if(capwin_hwnd && (rst_remote || rst_local)
326 && InterlockedExchange(&capwin_connectivity, 0))
327 PostMessage(capwin_hwnd, WM_CAPWIN_NET_DOWN, 0, 0);
328 #endif
329
330 /* cleanup temporary (e.g. IDENT) socket */
331 if(c->fd!=INVALID_SOCKET)
332 closesocket(c->fd);
333 c->fd=INVALID_SOCKET;
334
335 /* cleanup the TLS context */
336 if(c->ssl) { /* TLS initialized */
337 SSL_set_shutdown(c->ssl, SSL_SENT_SHUTDOWN|SSL_RECEIVED_SHUTDOWN);
338 SSL_free(c->ssl);
339 c->ssl=NULL;
340 #if OPENSSL_VERSION_NUMBER >= 0x10100006L
341 /* OpenSSL version >= 1.1.0-pre6 */
342 /* the function is no longer needed */
343 #elif OPENSSL_VERSION_NUMBER >= 0x10100004L
344 /* OpenSSL version 1.1.0-pre4 or 1.1.0-pre5 */
345 ERR_remove_thread_state();
346 #elif OPENSSL_VERSION_NUMBER >= 0x10000000L
347 /* OpenSSL version >= 1.0.0 */
348 ERR_remove_thread_state(NULL);
349 #else
350 /* OpenSSL version < 1.0.0 */
351 ERR_remove_state(0);
352 #endif
353 }
354
355 /* cleanup the remote socket */
356 if(c->remote_fd.fd!=INVALID_SOCKET) { /* remote socket initialized */
357 if(rst_remote && c->remote_fd.is_socket) /* reset */
358 reset(c->remote_fd.fd, "remote_fd");
359 #ifndef USE_UCONTEXT
360 set_nonblock(c->remote_fd.fd, 0);
361 #endif
362 closesocket(c->remote_fd.fd);
363 s_log(LOG_DEBUG, "Remote descriptor (FD=%ld) closed",
364 (long)c->remote_fd.fd);
365 c->remote_fd.fd=INVALID_SOCKET;
366 }
367
368 /* cleanup the local socket */
369 if(c->local_rfd.fd!=INVALID_SOCKET) { /* local socket initialized */
370 if(c->local_rfd.fd==c->local_wfd.fd) {
371 if(rst_local && c->local_rfd.is_socket)
372 reset(c->local_rfd.fd, "local_rfd/local_wfd");
373 #ifndef USE_UCONTEXT
374 set_nonblock(c->local_rfd.fd, 0);
375 #endif
376 closesocket(c->local_rfd.fd);
377 s_log(LOG_DEBUG, "Local descriptor (FD=%ld) closed",
378 (long)c->local_rfd.fd);
379 } else { /* stdin/stdout */
380 if(rst_local && c->local_rfd.is_socket)
381 reset(c->local_rfd.fd, "local_rfd");
382 if(rst_local && c->local_wfd.is_socket)
383 reset(c->local_wfd.fd, "local_wfd");
384 }
385 c->local_rfd.fd=c->local_wfd.fd=INVALID_SOCKET;
386 }
387
388 #ifdef USE_FORK
389 /* display child return code if it managed to arrive on time */
390 /* otherwise it will be retrieved by the init process and ignored */
391 if(c->opt->exec_name) /* 'exec' specified */
392 pid_status_hang("Child process"); /* null SIGCHLD handler was used */
393 s_log(LOG_DEBUG, "Service [%s] finished", c->opt->servname);
394 #else
395 #ifdef USE_OS_THREADS
396 CRYPTO_atomic_add(&num_clients, -1, &num, stunnel_locks[LOCK_CLIENTS]);
397 #else
398 num=--num_clients;
399 #endif
400 ui_clients(num);
401 s_log(LOG_DEBUG, "Service [%s] finished (%ld left)", c->opt->servname, num);
402 #endif
403
404 /* free the client context */
405 str_free(c->connect_addr.addr);
406 /* a client does not have its own local copy of
407 c->connect_addr.session and c->connect_addr.fd */
408 s_poll_free(c->fds);
409 str_free(c->accepted_address);
410 }
411 #ifdef __GNUC__
412 #if __GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6)
413 #pragma GCC diagnostic pop
414 #endif /* __GNUC__>=4.6 */
415 #endif /* __GNUC__ */
416
417 NOEXPORT void client_try(CLI *c) {
418 c->flag.redirect=0;
419 local_start(c);
420 if(c->opt->protocol_early)
421 c->opt->protocol_early(c);
422 if(c->opt->option.connect_before_ssl) {
423 remote_start(c);
424 if(c->opt->protocol_middle)
425 c->opt->protocol_middle(c);
426 ssl_start(c);
427 } else {
428 ssl_start(c);
429 if(c->opt->protocol_middle && !c->flag.redirect)
430 c->opt->protocol_middle(c);
431 remote_start(c);
432 }
433 if(c->opt->protocol_late && !c->flag.redirect)
434 c->opt->protocol_late(c);
435 transfer(c);
436 }
437
438 NOEXPORT void local_start(CLI *c) {
439 SOCKADDR_UNION addr;
440 socklen_t addr_len;
441
442 /* check if local_rfd is a socket and get peer address */
443 addr_len=sizeof(SOCKADDR_UNION);
444 c->local_rfd.is_socket=!getpeername(c->local_rfd.fd, &addr.sa, &addr_len);
445 if(c->local_rfd.is_socket) {
446 /* store the retrieved peer address */
447 memcpy(&c->peer_addr.sa, &addr.sa, (size_t)addr_len);
448 c->peer_addr_len=addr_len;
449 if(
450 #ifdef HAVE_STRUCT_SOCKADDR_UN
451 addr.sa.sa_family!=AF_UNIX &&
452 #endif
453 socket_options_set(c->opt, c->local_rfd.fd, 1)) {
454 s_log(LOG_WARNING, "Failed to set local socket options");
455 }
456 } else if(get_last_socket_error()!=S_ENOTSOCK) {
457 sockerror("getpeerbyname (local_rfd)");
458 throw_exception(c, 1);
459 }
460
461 /* check if local_wfd is a socket and get peer address */
462 if(c->local_rfd.fd==c->local_wfd.fd) {
463 c->local_wfd.is_socket=c->local_rfd.is_socket;
464 } else {
465 addr_len=sizeof(SOCKADDR_UNION);
466 c->local_wfd.is_socket=!getpeername(c->local_wfd.fd, &addr.sa, &addr_len);
467 if(c->local_wfd.is_socket) {
468 if(!c->local_rfd.is_socket) { /* not retrieved from rfd? */
469 /* store the retrieved peer address */
470 memcpy(&c->peer_addr.sa, &addr.sa, (size_t)addr_len);
471 c->peer_addr_len=addr_len;
472 }
473 if(
474 #ifdef HAVE_STRUCT_SOCKADDR_UN
475 addr.sa.sa_family!=AF_UNIX &&
476 #endif
477 socket_options_set(c->opt, c->local_wfd.fd, 1)) {
478 s_log(LOG_WARNING, "Failed to set local socket options");
479 }
480 } else if(get_last_socket_error()!=S_ENOTSOCK) {
481 sockerror("getpeerbyname (local_wfd)");
482 throw_exception(c, 1);
483 }
484 }
485
486 /* neither of local descriptors is a socket */
487 if(!c->local_rfd.is_socket && !c->local_wfd.is_socket) {
488 #ifndef USE_WIN32
489 if(c->opt->option.transparent_src) {
490 s_log(LOG_ERR, "Transparent source needs a socket");
491 throw_exception(c, 1);
492 }
493 #endif
494 s_log(LOG_NOTICE, "Service [%s] accepted connection", c->opt->servname);
495 return;
496 }
497
498 /* authenticate based on retrieved IP address of the client */
499 c->accepted_address=s_ntop(&c->peer_addr, c->peer_addr_len);
500 #ifdef USE_LIBWRAP
501 libwrap_auth(c);
502 #endif /* USE_LIBWRAP */
503 auth_user(c);
504 s_log(LOG_NOTICE, "Service [%s] accepted connection from %s",
505 c->opt->servname, c->accepted_address);
506 }
507
508 NOEXPORT void remote_start(CLI *c) {
509 /* where to bind connecting socket */
510 if(c->opt->option.local) /* outgoing interface */
511 c->bind_addr=&c->opt->source_addr;
512 #ifndef USE_WIN32
513 else if(c->opt->option.transparent_src)
514 c->bind_addr=&c->peer_addr;
515 #endif
516 else
517 c->bind_addr=NULL; /* don't bind */
518
519 /* setup c->remote_fd, now */
520 if(c->opt->exec_name && !c->opt->connect_addr.names && !c->flag.redirect)
521 c->remote_fd.fd=connect_local(c); /* not for exec+connect targets */
522 else
523 c->remote_fd.fd=connect_remote(c);
524
525 #ifndef USE_WIN32
526 if(c->opt->option.pty) { /* descriptor created with pty_allocate() */
527 c->remote_fd.is_socket=0;
528 } else
529 #endif
530 {
531 c->remote_fd.is_socket=1;
532 if(socket_options_set(c->opt, c->remote_fd.fd, 2))
533 s_log(LOG_WARNING, "Failed to set remote socket options");
534 }
535 s_log(LOG_DEBUG, "Remote descriptor (FD=%ld) initialized",
536 (long)c->remote_fd.fd);
537 }
538
539 NOEXPORT void ssl_start(CLI *c) {
540 int i, err;
541 SSL_SESSION *sess;
542 #if OPENSSL_VERSION_NUMBER < 0x10100000L
543 int unsafe_openssl;
544 #endif /* OpenSSL version < 1.1.0 */
545
546 c->ssl=SSL_new(c->opt->ctx);
547 if(!c->ssl) {
548 ssl_error(c, "SSL_new");
549 throw_exception(c, 1);
550 }
551 /* for callbacks */
552 if(!SSL_set_ex_data(c->ssl, index_ssl_cli, c)) {
553 ssl_error(c, "SSL_set_ex_data");
554 throw_exception(c, 1);
555 }
556 if(c->opt->option.client) {
557 #ifndef OPENSSL_NO_TLSEXT
558 #ifndef OPENSSL_NO_OCSP
559 if(!SSL_set_tlsext_status_type(c->ssl, TLSEXT_STATUSTYPE_ocsp)) {
560 ssl_error(c, "OCSP: SSL_set_tlsext_status_type");
561 throw_exception(c, 1);
562 }
563 #endif /* !defined(OPENSSL_NO_OCSP) */
564 /* c->opt->sni should always be initialized at this point,
565 * either explicitly with "sni"
566 * or implicitly with "protocolHost" or "connect" */
567 if(c->opt->sni && *c->opt->sni) {
568 s_log(LOG_INFO, "SNI: sending servername: %s", c->opt->sni);
569 if(!SSL_set_tlsext_host_name(c->ssl, c->opt->sni)) {
570 ssl_error(c, "SSL_set_tlsext_host_name");
571 throw_exception(c, 1);
572 }
573 } else { /* c->opt->sni was set to an empty value */
574 s_log(LOG_INFO, "SNI: extension disabled");
575 }
576 #endif
577 session_cache_retrieve(c);
578 SSL_set_fd(c->ssl, (int)c->remote_fd.fd);
579 SSL_set_connect_state(c->ssl);
580 } else { /* TLS server */
581 if(c->local_rfd.fd==c->local_wfd.fd)
582 SSL_set_fd(c->ssl, (int)c->local_rfd.fd);
583 else {
584 /* does it make sense to have TLS on STDIN/STDOUT? */
585 SSL_set_rfd(c->ssl, (int)c->local_rfd.fd);
586 SSL_set_wfd(c->ssl, (int)c->local_wfd.fd);
587 }
588 SSL_set_accept_state(c->ssl);
589 }
590
591 if(c->opt->option.require_cert)
592 s_log(LOG_INFO, "Peer certificate required");
593 else
594 s_log(LOG_INFO, "Peer certificate not required");
595
596 #if OPENSSL_VERSION_NUMBER < 0x10100000L
597 unsafe_openssl=OpenSSL_version_num()<0x0090810fL ||
598 (OpenSSL_version_num()>=0x10000000L &&
599 OpenSSL_version_num()<0x1000002fL);
600 #endif /* OpenSSL version < 1.1.0 */
601 while(1) {
602 /* critical section for OpenSSL version < 0.9.8p or 1.x.x < 1.0.0b *
603 * this critical section is a crude workaround for CVE-2010-3864 *
604 * see http://www.securityfocus.com/bid/44884 for details *
605 * alternative solution is to disable internal session caching *
606 * NOTE: this critical section also covers callbacks (e.g. OCSP) */
607 #if OPENSSL_VERSION_NUMBER < 0x10100000L
608 if(unsafe_openssl)
609 CRYPTO_THREAD_write_lock(stunnel_locks[LOCK_SSL]);
610 #endif /* OpenSSL version < 1.1.0 */
611
612 i=c->opt->option.client ? SSL_connect(c->ssl) : SSL_accept(c->ssl);
613
614 #if OPENSSL_VERSION_NUMBER < 0x10100000L
615 if(unsafe_openssl)
616 CRYPTO_THREAD_unlock(stunnel_locks[LOCK_SSL]);
617 #endif /* OpenSSL version < 1.1.0 */
618
619 err=SSL_get_error(c->ssl, i);
620 if(err==SSL_ERROR_NONE)
621 break; /* ok -> done */
622 if(err==SSL_ERROR_WANT_READ || err==SSL_ERROR_WANT_WRITE) {
623 s_poll_init(c->fds, 0);
624 s_poll_add(c->fds, c->ssl_rfd->fd,
625 err==SSL_ERROR_WANT_READ,
626 err==SSL_ERROR_WANT_WRITE);
627 switch(s_poll_wait(c->fds, c->opt->timeout_busy, 0)) {
628 case -1:
629 sockerror("ssl_start: s_poll_wait");
630 throw_exception(c, 1);
631 case 0:
632 s_log(LOG_INFO, "ssl_start: s_poll_wait:"
633 " TIMEOUTbusy exceeded: sending reset");
634 s_poll_dump(c->fds, LOG_DEBUG);
635 throw_exception(c, 1);
636 case 1:
637 break; /* OK */
638 default:
639 s_log(LOG_ERR, "ssl_start: s_poll_wait: unknown result");
640 throw_exception(c, 1);
641 }
642 continue; /* ok -> retry */
643 }
644 if(err==SSL_ERROR_SYSCALL) {
645 switch(get_last_socket_error()) {
646 case S_EINTR:
647 case S_EWOULDBLOCK:
648 #if S_EAGAIN!=S_EWOULDBLOCK
649 case S_EAGAIN:
650 #endif
651 continue;
652 }
653 sockerror(c->opt->option.client ? "SSL_connect" : "SSL_accept");
654 throw_exception(c, 1);
655 }
656 ssl_error(c, c->opt->option.client ? "SSL_connect" : "SSL_accept");
657 throw_exception(c, 1);
658 }
659 ERR_clear_error(); /* silence any cached errors */
660 print_cipher(c);
661 sess=SSL_get1_session(c->ssl);
662 if(sess) {
663 X509 *peer_cert=SSL_get_peer_certificate(c->ssl);
664 if(peer_cert) {
665 X509_free(peer_cert);
666 } else { /* no authentication was performed */
667 if(!SSL_SESSION_set_ex_data(sess,
668 index_session_authenticated, NULL)) {
669 ssl_error(c, "SSL_SESSION_set_ex_data");
670 SSL_SESSION_free(sess);
671 throw_exception(c, 1);
672 }
673 }
674 if(SSL_session_reused(c->ssl)) {
675 /* otherwise printed from sess_new_cb() */
676 print_session_id("Session id", sess);
677 } else { /* a new session was negotiated */
678 /* SSL_SESS_CACHE_NO_INTERNAL_STORE prevented automatic caching */
679 if(!c->opt->option.client)
680 SSL_CTX_add_session(c->opt->ctx, sess);
681 }
682 SSL_SESSION_free(sess);
683 } else if(c->opt->redirect_addr.names) {
684 s_log(LOG_ERR, "No session available for redirection");
685 throw_exception(c, 1);
686 }
687 c->flag.redirect=(unsigned)redirect(c)&1;
688 }
689
690 NOEXPORT void session_cache_retrieve(CLI *c) {
691 SSL_SESSION *sess=NULL;
692
693 CRYPTO_THREAD_read_lock(stunnel_locks[LOCK_SESSION]);
694 if(c->opt->connect_session) /* per-destination client session */
695 sess=c->opt->connect_session[c->idx];
696 if(!sess) /* either no per-destination cache or no session cached */
697 sess=c->opt->session; /* fallback session */
698 if(sess)
699 SSL_set_session(c->ssl, sess);
700 CRYPTO_THREAD_unlock(stunnel_locks[LOCK_SESSION]);
701
702 if(sess)
703 print_session_id("Attempting to resume", sess);
704 else
705 s_log(LOG_DEBUG, "No previous session to resume");
706 }
707
708 #if OPENSSL_VERSION_NUMBER >= 0x10101000L
709 NOEXPORT void print_tmp_key(SSL *s) {
710 EVP_PKEY *key;
711 long tmp_key_found;
712
713 #ifdef SSL_CTRL_GET_PEER_TMP_KEY
714 tmp_key_found=SSL_get_peer_tmp_key(s, &key);
715 #else
716 tmp_key_found=SSL_get_server_tmp_key(s, &key);
717 #endif
718 if(!tmp_key_found) {
719 s_log(LOG_INFO, "No peer temporary key received");
720 #if OPENSSL_VERSION_NUMBER>=0x30000000L
721 if(SSL_version(s) == TLS1_3_VERSION) {
722 s_log(LOG_INFO, "Negotiated TLSv1.3 group: %s",
723 SSL_group_to_name(s, (int)SSL_get_negotiated_group(s)));
724 }
725 #endif /* OPENSSL_VERSION_NUMBER>=0x30000000L */
726 return;
727 }
728 switch(EVP_PKEY_id(key)) {
729 #if OPENSSL_VERSION_NUMBER>=0x30000000L
730 case EVP_PKEY_KEYMGMT:
731 {
732 const char *keyname=EVP_PKEY_get0_type_name(key);
733
734 if(keyname)
735 s_log(LOG_INFO, "Peer temporary key: %s, %d bits",
736 keyname, EVP_PKEY_bits(key));
737 else
738 s_log(LOG_INFO, "Unable to determine temporary key type");
739 }
740 break;
741 #endif /* OPENSSL_VERSION_NUMBER>=0x30000000L */
742 case EVP_PKEY_RSA:
743 s_log(LOG_INFO, "Peer temporary key: RSA, %d bits", EVP_PKEY_bits(key));
744 break;
745 case EVP_PKEY_DH:
746 s_log(LOG_INFO, "Peer temporary key: DH, %d bits", EVP_PKEY_bits(key));
747 break;
748 #ifndef OPENSSL_NO_EC
749 case EVP_PKEY_EC:
750 {
751 EC_KEY *ec=EVP_PKEY_get1_EC_KEY(key);
752 int nid=EC_GROUP_get_curve_name(EC_KEY_get0_group(ec));
753 const char *cname=EC_curve_nid2nist(nid);
754
755 EC_KEY_free(ec);
756 if (cname == NULL)
757 cname=OBJ_nid2sn(nid);
758 s_log(LOG_INFO, "Peer temporary key: ECDH, %s, %d bits", cname, EVP_PKEY_bits(key));
759 }
760 break;
761 #endif
762 default:
763 {
764 int keyid=EVP_PKEY_id(key);
765
766 if(keyid != NID_undef)
767 s_log(LOG_INFO, "Peer temporary key: %s, %d bits",
768 OBJ_nid2sn(keyid), EVP_PKEY_bits(key));
769 else
770 s_log(LOG_INFO, "Unable to determine temporary key type");
771 }
772 }
773 EVP_PKEY_free(key);
774 }
775 #endif /* OpenSSL 1.1.1 or later */
776
777 NOEXPORT void print_cipher(CLI *c) { /* print negotiated cipher */
778 #if OPENSSL_VERSION_NUMBER >= 0x10101000L
779 const SSL_CIPHER *cipher;
780 #else
781 SSL_CIPHER *cipher;
782 #endif /* OpenSSL 1.1.1 or later */
783 #ifndef OPENSSL_NO_COMP
784 const COMP_METHOD *compression, *expansion;
785 #endif
786
787 if(c->opt->log_level<LOG_INFO) /* performance optimization */
788 return;
789
790 #ifndef OPENSSL_NO_PSK
791 if(c->flag.psk_found) {
792 if(c->opt->option.client) {
793 s_log(LOG_ERR, "INTERNAL ERROR: PSK found on a client");
794 } else {
795 s_log(LOG_INFO, "TLS accepted: PSK");
796 }
797 } else
798 #endif /* !defined(OPENSSL_NO_PSK) */
799 s_log(LOG_INFO, "TLS %s: %s",
800 c->opt->option.client ? "connected" : "accepted",
801 SSL_session_reused(c->ssl) ?
802 "previous session reused" : "new session negotiated");
803
804 cipher=(SSL_CIPHER *)SSL_get_current_cipher(c->ssl);
805 s_log(LOG_INFO, "%s ciphersuite: %s (%d-bit encryption)",
806 SSL_get_version(c->ssl), SSL_CIPHER_get_name(cipher),
807 SSL_CIPHER_get_bits(cipher, NULL));
808 #if OPENSSL_VERSION_NUMBER >= 0x10101000L
809 print_tmp_key(c->ssl);
810 #endif
811
812 #ifndef OPENSSL_NO_COMP
813 compression=SSL_get_current_compression(c->ssl);
814 expansion=SSL_get_current_expansion(c->ssl);
815 s_log(compression||expansion ? LOG_INFO : LOG_DEBUG,
816 "Compression: %s, expansion: %s",
817 compression ? SSL_COMP_get_name(compression) : "null",
818 expansion ? SSL_COMP_get_name(expansion) : "null");
819 #endif
820 }
821
822 /****************************** transfer data */
823 NOEXPORT void transfer(CLI *c) {
824 int timeout; /* s_poll_wait timeout in seconds */
825 int pending; /* either processed on unprocessed TLS data */
826 #if OPENSSL_VERSION_NUMBER >= 0x10100000L
827 int has_pending=0, prev_has_pending;
828 #endif
829 int watchdog=0; /* a counter to detect an infinite loop */
830 int err;
831 /* logical channels (not file descriptors!) open for read or write */
832 int sock_open_rd=1, sock_open_wr=1;
833 /* awaited conditions on TLS file descriptors */
834 int shutdown_wants_read=0, shutdown_wants_write=0;
835 int read_wants_read=0, read_wants_write=0;
836 int write_wants_read=0, write_wants_write=0;
837 /* actual conditions on file descriptors */
838 int sock_can_rd, sock_can_wr, ssl_can_rd, ssl_can_wr;
839 #ifdef USE_WIN32
840 unsigned long bytes;
841 #else
842 int bytes;
843 #endif
844
845 c->sock_ptr=c->ssl_ptr=0;
846
847 do { /* main loop of client data transfer */
848 /****************************** initialize *_wants_* */
849 read_wants_read|=!(SSL_get_shutdown(c->ssl)&SSL_RECEIVED_SHUTDOWN)
850 && c->ssl_ptr<BUFFSIZE && !read_wants_write;
851 write_wants_write|=!(SSL_get_shutdown(c->ssl)&SSL_SENT_SHUTDOWN)
852 && c->sock_ptr && !write_wants_read;
853
854 /****************************** setup c->fds structure */
855 s_poll_init(c->fds, 0); /* initialize the structure */
856 /* for plain socket open data stream = open file descriptor */
857 /* make sure to add each open socket to receive exceptions! */
858 if(sock_open_rd) /* only poll if the read file descriptor is open */
859 s_poll_add(c->fds, c->sock_rfd->fd, c->sock_ptr<BUFFSIZE, 0);
860 if(sock_open_wr) /* only poll if the write file descriptor is open */
861 s_poll_add(c->fds, c->sock_wfd->fd, 0, c->ssl_ptr>0);
862 /* poll TLS file descriptors unless TLS shutdown was completed */
863 if(SSL_get_shutdown(c->ssl)!=
864 (SSL_SENT_SHUTDOWN|SSL_RECEIVED_SHUTDOWN)) {
865 s_poll_add(c->fds, c->ssl_rfd->fd,
866 read_wants_read || write_wants_read || shutdown_wants_read, 0);
867 s_poll_add(c->fds, c->ssl_wfd->fd, 0,
868 read_wants_write || write_wants_write || shutdown_wants_write);
869 }
870
871 /****************************** wait for an event */
872 pending=SSL_pending(c->ssl);
873 #if OPENSSL_VERSION_NUMBER >= 0x10100000L
874 /* only attempt to process SSL_has_pending() data once */
875 prev_has_pending=has_pending;
876 has_pending=SSL_has_pending(c->ssl);
877 pending=pending || (has_pending && !prev_has_pending);
878 #endif
879 if(read_wants_read && pending) {
880 timeout=0; /* process any buffered data without delay */
881 } else if((sock_open_rd && /* both peers open */
882 !(SSL_get_shutdown(c->ssl)&SSL_RECEIVED_SHUTDOWN)) ||
883 c->ssl_ptr /* data buffered to write to socket */ ||
884 c->sock_ptr /* data buffered to write to TLS */) {
885 timeout=c->opt->timeout_idle;
886 } else {
887 timeout=c->opt->timeout_close;
888 }
889 err=s_poll_wait(c->fds, timeout, 0);
890 switch(err) {
891 case -1:
892 sockerror("transfer: s_poll_wait");
893 throw_exception(c, 1);
894 case 0: /* timeout */
895 if(read_wants_read && pending)
896 break;
897 if((sock_open_rd &&
898 !(SSL_get_shutdown(c->ssl)&SSL_RECEIVED_SHUTDOWN)) ||
899 c->ssl_ptr || c->sock_ptr) {
900 s_log(LOG_INFO, "transfer: s_poll_wait:"
901 " TIMEOUTidle exceeded: sending reset");
902 s_poll_dump(c->fds, LOG_DEBUG);
903 throw_exception(c, 1);
904 }
905 /* already closing connection */
906 s_log(LOG_ERR, "transfer: s_poll_wait:"
907 " TIMEOUTclose exceeded: closing");
908 s_poll_dump(c->fds, LOG_DEBUG);
909 return; /* OK */
910 }
911
912 /****************************** retrieve results from c->fds */
913 sock_can_rd=s_poll_canread(c->fds, c->sock_rfd->fd);
914 sock_can_wr=s_poll_canwrite(c->fds, c->sock_wfd->fd);
915 ssl_can_rd=s_poll_canread(c->fds, c->ssl_rfd->fd);
916 ssl_can_wr=s_poll_canwrite(c->fds, c->ssl_wfd->fd);
917
918 /****************************** identify exceptions */
919 if(c->sock_rfd->fd==c->sock_wfd->fd) {
920 check_socket_error(c, c->sock_rfd->fd, "socket fd");
921 } else {
922 check_socket_error(c, c->sock_rfd->fd, "socket rfd");
923 check_socket_error(c, c->sock_wfd->fd, "socket wfd");
924 }
925 if(c->ssl_rfd->fd==c->ssl_wfd->fd) {
926 check_socket_error(c, c->ssl_rfd->fd, "TLS fd");
927 } else {
928 check_socket_error(c, c->ssl_rfd->fd, "TLS rfd");
929 check_socket_error(c, c->ssl_wfd->fd, "TLS wfd");
930 }
931
932 /****************************** hangups without read or write */
933 if(!(sock_can_rd || sock_can_wr || ssl_can_rd || ssl_can_wr)) {
934 if(s_poll_hup(c->fds, c->sock_wfd->fd)) {
935 if(c->ssl_ptr) {
936 s_log(LOG_ERR,
937 "Write socket closed (HUP) with %ld unsent byte(s)",
938 (long)c->ssl_ptr);
939 throw_exception(c, 1); /* reset the sockets */
940 }
941 s_log(LOG_INFO, "Write socket closed (HUP)");
942 sock_open_wr=0;
943 }
944 if(s_poll_hup(c->fds, c->sock_rfd->fd)) {
945 s_log(LOG_INFO, "Read socket closed (HUP)");
946 sock_open_rd=0;
947 }
948 if(s_poll_hup(c->fds, c->ssl_rfd->fd) ||
949 s_poll_hup(c->fds, c->ssl_wfd->fd)) {
950 if(c->sock_ptr) {
951 s_log(LOG_ERR,
952 "TLS socket closed (HUP) with %ld unsent byte(s)",
953 (long)c->sock_ptr);
954 throw_exception(c, 1); /* reset the sockets */
955 }
956 s_log(LOG_INFO, "TLS socket closed (HUP)");
957 SSL_set_shutdown(c->ssl,
958 SSL_SENT_SHUTDOWN|SSL_RECEIVED_SHUTDOWN);
959 }
960 }
961
962 if(c->reneg_state==RENEG_DETECTED && !c->opt->option.renegotiation) {
963 s_log(LOG_ERR, "Aborting due to renegotiation request");
964 throw_exception(c, 1);
965 }
966
967 /****************************** send TLS close_notify alert */
968 if(shutdown_wants_read || shutdown_wants_write) {
969 int num=SSL_shutdown(c->ssl); /* send close_notify alert */
970 if(num<0) /* -1 - not completed */
971 err=SSL_get_error(c->ssl, num);
972 else /* 0 or 1 - success */
973 err=SSL_ERROR_NONE;
974 switch(err) {
975 case SSL_ERROR_NONE: /* the shutdown was successfully completed */
976 s_log(LOG_INFO, "SSL_shutdown successfully sent close_notify alert");
977 shutdown_wants_read=shutdown_wants_write=0;
978 break;
979 case SSL_ERROR_WANT_WRITE:
980 s_log(LOG_DEBUG, "SSL_shutdown returned WANT_WRITE: retrying");
981 shutdown_wants_read=0;
982 shutdown_wants_write=1;
983 break;
984 case SSL_ERROR_WANT_READ:
985 s_log(LOG_DEBUG, "SSL_shutdown returned WANT_READ: retrying");
986 shutdown_wants_read=1;
987 shutdown_wants_write=0;
988 break;
989 case SSL_ERROR_SSL: /* TLS error */
990 ssl_error(c, "SSL_shutdown");
991 throw_exception(c, 1);
992 case SSL_ERROR_ZERO_RETURN: /* received a close_notify alert */
993 SSL_set_shutdown(c->ssl, SSL_SENT_SHUTDOWN|SSL_RECEIVED_SHUTDOWN);
994 shutdown_wants_read=shutdown_wants_write=0;
995 break;
996 case SSL_ERROR_SYSCALL: /* socket error */
997 if(socket_needs_retry(c, "transfer: SSL_shutdown"))
998 break; /* a non-critical error: retry */
999 SSL_set_shutdown(c->ssl, SSL_SENT_SHUTDOWN|SSL_RECEIVED_SHUTDOWN);
1000 shutdown_wants_read=shutdown_wants_write=0;
1001 break;
1002 default:
1003 s_log(LOG_ERR, "SSL_shutdown/SSL_get_error returned %d", err);
1004 throw_exception(c, 1);
1005 }
1006 }
1007
1008 /****************************** write to socket */
1009 if(sock_open_wr && sock_can_wr) {
1010 ssize_t num=writesocket(c->sock_wfd->fd, c->ssl_buff, c->ssl_ptr);
1011 switch(num) {
1012 case -1: /* error */
1013 if(socket_needs_retry(c, "transfer: writesocket"))
1014 break; /* a non-critical error: retry */
1015 sock_open_rd=sock_open_wr=0;
1016 break;
1017 case 0: /* nothing was written: ignore */
1018 s_log(LOG_DEBUG, "writesocket returned 0");
1019 break; /* do not reset the watchdog */
1020 default:
1021 memmove(c->ssl_buff, c->ssl_buff+num, c->ssl_ptr-(size_t)num);
1022 c->ssl_ptr-=(size_t)num;
1023 memset(c->ssl_buff+c->ssl_ptr, 0, (size_t)num); /* paranoia */
1024 c->sock_bytes+=(size_t)num;
1025 watchdog=0; /* reset the watchdog */
1026 }
1027 }
1028
1029 /****************************** read from socket */
1030 if(sock_open_rd && sock_can_rd) {
1031 ssize_t num=readsocket(c->sock_rfd->fd,
1032 c->sock_buff+c->sock_ptr, BUFFSIZE-c->sock_ptr);
1033 switch(num) {
1034 case -1:
1035 if(socket_needs_retry(c, "transfer: readsocket"))
1036 break; /* a non-critical error: retry */
1037 sock_open_rd=sock_open_wr=0;
1038 break;
1039 case 0: /* close */
1040 s_log(LOG_INFO, "Read socket closed (readsocket)");
1041 sock_open_rd=0;
1042 break; /* do not reset the watchdog */
1043 default:
1044 c->sock_ptr+=(size_t)num;
1045 watchdog=0; /* reset the watchdog */
1046 }
1047 }
1048
1049 /****************************** update *_wants_* based on new *_ptr */
1050 /* this update is also required for SSL_pending() to be used */
1051 read_wants_read|=!(SSL_get_shutdown(c->ssl)&SSL_RECEIVED_SHUTDOWN)
1052 && c->ssl_ptr<BUFFSIZE && !read_wants_write;
1053 write_wants_write|=!(SSL_get_shutdown(c->ssl)&SSL_SENT_SHUTDOWN)
1054 && c->sock_ptr && !write_wants_read;
1055
1056 /****************************** write to TLS */
1057 if((write_wants_read && ssl_can_rd) ||
1058 (write_wants_write && ssl_can_wr)) {
1059 int num=SSL_write(c->ssl, c->sock_buff, (int)(c->sock_ptr));
1060 write_wants_read=0;
1061 write_wants_write=0;
1062 switch(err=SSL_get_error(c->ssl, num)) {
1063 case SSL_ERROR_NONE:
1064 if(num==0) { /* nothing was written: ignore */
1065 s_log(LOG_DEBUG, "SSL_write returned 0");
1066 } else {
1067 memmove(c->sock_buff, c->sock_buff+num,
1068 c->sock_ptr-(size_t)num);
1069 c->sock_ptr-=(size_t)num;
1070 memset(c->sock_buff+c->sock_ptr, 0, (size_t)num); /* PPD */
1071 c->ssl_bytes+=(size_t)num;
1072 watchdog=0; /* data transferred -> reset the watchdog */
1073 }
1074 break;
1075 case SSL_ERROR_WANT_WRITE: /* buffered data? */
1076 s_log(LOG_DEBUG, "SSL_write returned WANT_WRITE: retrying");
1077 write_wants_write=1;
1078 break;
1079 case SSL_ERROR_WANT_READ:
1080 s_log(LOG_DEBUG, "SSL_write returned WANT_READ: retrying");
1081 write_wants_read=1;
1082 break;
1083 case SSL_ERROR_WANT_X509_LOOKUP:
1084 s_log(LOG_DEBUG,
1085 "SSL_write returned WANT_X509_LOOKUP: retrying");
1086 break;
1087 case SSL_ERROR_SSL:
1088 ssl_error(c, "SSL_write");
1089 throw_exception(c, 1);
1090 case SSL_ERROR_ZERO_RETURN: /* a buffered close_notify alert */
1091 /* fall through */
1092 case SSL_ERROR_SYSCALL: /* socket error */
1093 if(socket_needs_retry(c, "transfer: SSL_write") && num)
1094 break; /* a non-critical error: retry */
1095 /* EOF -> buggy (e.g. Microsoft) peer:
1096 * TLS socket closed without close_notify alert */
1097 if(c->sock_ptr) { /* TODO: what about buffered data? */
1098 s_log(LOG_ERR,
1099 "TLS socket closed (SSL_write) with %ld unsent byte(s)",
1100 (long)c->sock_ptr);
1101 throw_exception(c, 1); /* reset the sockets */
1102 }
1103 s_log(LOG_INFO, "TLS socket closed (SSL_write)");
1104 SSL_set_shutdown(c->ssl, SSL_SENT_SHUTDOWN|SSL_RECEIVED_SHUTDOWN);
1105 break;
1106 default:
1107 s_log(LOG_ERR, "SSL_write/SSL_get_error returned %d", err);
1108 throw_exception(c, 1);
1109 }
1110 }
1111
1112 /****************************** read from TLS */
1113 if((read_wants_read && (ssl_can_rd || pending)) ||
1114 /* it may be possible to read some pending data after
1115 * writesocket() above made some room in c->ssl_buff */
1116 (read_wants_write && ssl_can_wr)) {
1117 int num=SSL_read(c->ssl, c->ssl_buff+c->ssl_ptr, (int)(BUFFSIZE-c->ssl_ptr));
1118 read_wants_read=0;
1119 read_wants_write=0;
1120 switch(err=SSL_get_error(c->ssl, num)) {
1121 case SSL_ERROR_NONE:
1122 if(num==0) { /* nothing was read: ignore */
1123 s_log(LOG_DEBUG, "SSL_read returned 0");
1124 } else {
1125 c->ssl_ptr+=(size_t)num;
1126 watchdog=0; /* data transferred -> reset the watchdog */
1127 }
1128 break;
1129 case SSL_ERROR_WANT_WRITE:
1130 s_log(LOG_DEBUG, "SSL_read returned WANT_WRITE: retrying");
1131 read_wants_write=1;
1132 break;
1133 case SSL_ERROR_WANT_READ: /* happens quite often */
1134 #if 0
1135 s_log(LOG_DEBUG, "SSL_read returned WANT_READ: retrying");
1136 #endif
1137 read_wants_read=1;
1138 break;
1139 case SSL_ERROR_WANT_X509_LOOKUP:
1140 s_log(LOG_DEBUG,
1141 "SSL_read returned WANT_X509_LOOKUP: retrying");
1142 break;
1143 case SSL_ERROR_SSL:
1144 #ifdef SSL_R_UNEXPECTED_EOF_WHILE_READING
1145 /* OpenSSL 3.0 changed the method of reporting socket EOF */
1146 if(ERR_GET_REASON(ERR_peek_error())==
1147 SSL_R_UNEXPECTED_EOF_WHILE_READING) {
1148 /* EOF -> buggy (e.g. Microsoft) peer:
1149 * TLS socket closed without close_notify alert */
1150 if(c->sock_ptr || write_wants_write) {
1151 s_log(LOG_ERR,
1152 "TLS socket closed (SSL_read) with %ld unsent byte(s)",
1153 (long)c->sock_ptr);
1154 throw_exception(c, 1); /* reset the sockets */
1155 }
1156 s_log(LOG_INFO, "TLS socket closed (SSL_read)");
1157 SSL_set_shutdown(c->ssl,
1158 SSL_SENT_SHUTDOWN|SSL_RECEIVED_SHUTDOWN);
1159 break;
1160 }
1161 #endif /* SSL_R_UNEXPECTED_EOF_WHILE_READING */
1162 ssl_error(c, "SSL_read");
1163 throw_exception(c, 1);
1164 case SSL_ERROR_ZERO_RETURN: /* received a close_notify alert */
1165 s_log(LOG_INFO, "TLS closed (SSL_read)");
1166 if(SSL_version(c->ssl)==SSL2_VERSION)
1167 SSL_set_shutdown(c->ssl,
1168 SSL_SENT_SHUTDOWN|SSL_RECEIVED_SHUTDOWN);
1169 break;
1170 case SSL_ERROR_SYSCALL:
1171 if(socket_needs_retry(c, "transfer: SSL_read") && num)
1172 break; /* a non-critical error: retry */
1173 /* EOF -> buggy (e.g. Microsoft) peer:
1174 * TLS socket closed without close_notify alert */
1175 if(c->sock_ptr || write_wants_write) {
1176 s_log(LOG_ERR,
1177 "TLS socket closed (SSL_read) with %ld unsent byte(s)",
1178 (long)c->sock_ptr);
1179 throw_exception(c, 1); /* reset the sockets */
1180 }
1181 s_log(LOG_INFO, "TLS socket closed (SSL_read)");
1182 SSL_set_shutdown(c->ssl,
1183 SSL_SENT_SHUTDOWN|SSL_RECEIVED_SHUTDOWN);
1184 break;
1185 default:
1186 s_log(LOG_ERR, "SSL_read/SSL_get_error returned %d", err);
1187 throw_exception(c, 1);
1188 }
1189 }
1190
1191 /****************************** check for hangup conditions */
1192 /* http://marc.info/?l=linux-man&m=128002066306087 */
1193 /* readsocket() must be the last sock_rfd operation before FIONREAD */
1194 if(sock_open_rd && s_poll_rdhup(c->fds, c->sock_rfd->fd) &&
1195 (ioctlsocket(c->sock_rfd->fd, FIONREAD, &bytes) || !bytes)) {
1196 s_log(LOG_INFO, "Read socket closed (read hangup)");
1197 sock_open_rd=0;
1198 }
1199 if(sock_open_wr && s_poll_hup(c->fds, c->sock_wfd->fd)) {
1200 if(c->ssl_ptr) {
1201 s_log(LOG_ERR,
1202 "Write socket closed (write hangup) with %ld unsent byte(s)",
1203 (long)c->ssl_ptr);
1204 throw_exception(c, 1); /* reset the sockets */
1205 }
1206 s_log(LOG_INFO, "Write socket closed (write hangup)");
1207 sock_open_wr=0;
1208 }
1209 /* SSL_read() must be the last ssl_rfd operation before FIONREAD */
1210 if(!(SSL_get_shutdown(c->ssl)&SSL_RECEIVED_SHUTDOWN) &&
1211 s_poll_rdhup(c->fds, c->ssl_rfd->fd) &&
1212 (ioctlsocket(c->ssl_rfd->fd, FIONREAD, &bytes) || !bytes)) {
1213 /* hangup -> buggy (e.g. Microsoft) peer:
1214 * TLS socket closed without close_notify alert */
1215 s_log(LOG_INFO, "TLS socket closed (read hangup)");
1216 SSL_set_shutdown(c->ssl,
1217 SSL_get_shutdown(c->ssl)|SSL_RECEIVED_SHUTDOWN);
1218 }
1219 if(!(SSL_get_shutdown(c->ssl)&SSL_SENT_SHUTDOWN) &&
1220 s_poll_hup(c->fds, c->ssl_wfd->fd)) {
1221 if(c->sock_ptr || write_wants_write) {
1222 s_log(LOG_ERR,
1223 "TLS socket closed (write hangup) with %ld unsent byte(s)",
1224 (long)c->sock_ptr);
1225 throw_exception(c, 1); /* reset the sockets */
1226 }
1227 s_log(LOG_INFO, "TLS socket closed (write hangup)");
1228 SSL_set_shutdown(c->ssl,
1229 SSL_get_shutdown(c->ssl)|SSL_SENT_SHUTDOWN);
1230 }
1231
1232 /****************************** check write shutdown conditions */
1233 if(sock_open_wr && SSL_get_shutdown(c->ssl)&SSL_RECEIVED_SHUTDOWN &&
1234 !c->ssl_ptr) {
1235 sock_open_wr=0; /* no further write allowed */
1236 if(!c->sock_wfd->is_socket) {
1237 s_log(LOG_DEBUG, "Closing the file descriptor");
1238 sock_open_rd=0; /* file descriptor is ready to be closed */
1239 } else if(!shutdown(c->sock_wfd->fd, SHUT_WR)) { /* send TCP FIN */
1240 s_log(LOG_DEBUG, "Sent socket write shutdown");
1241 } else {
1242 s_log(LOG_DEBUG, "Failed to send socket write shutdown");
1243 sock_open_rd=0; /* file descriptor is ready to be closed */
1244 }
1245 }
1246 if(!(SSL_get_shutdown(c->ssl)&SSL_SENT_SHUTDOWN) && !sock_open_rd &&
1247 !c->sock_ptr && !write_wants_write) {
1248 if(SSL_version(c->ssl)!=SSL2_VERSION) {
1249 s_log(LOG_DEBUG, "Sending close_notify alert");
1250 shutdown_wants_write=1;
1251 } else { /* no alerts in SSLv2, including the close_notify alert */
1252 s_log(LOG_DEBUG, "Closing SSLv2 socket");
1253 if(c->ssl_rfd->is_socket)
1254 shutdown(c->ssl_rfd->fd, SHUT_RD); /* notify the kernel */
1255 if(c->ssl_wfd->is_socket)
1256 shutdown(c->ssl_wfd->fd, SHUT_WR); /* send TCP FIN */
1257 /* notify the OpenSSL library */
1258 SSL_set_shutdown(c->ssl, SSL_SENT_SHUTDOWN|SSL_RECEIVED_SHUTDOWN);
1259 }
1260 }
1261
1262 /****************************** check watchdog */
1263 if(++watchdog>100) { /* loop executes without transferring any data */
1264 s_log(LOG_ERR,
1265 "transfer() loop executes not transferring any data");
1266 s_log(LOG_ERR,
1267 "please report the problem to [email protected]");
1268 stunnel_info(LOG_ERR);
1269 #if OPENSSL_VERSION_NUMBER >= 0x10100000L
1270 s_log(LOG_ERR, "protocol=%s, SSL_pending=%d, SSL_has_pending=%d",
1271 SSL_get_version(c->ssl),
1272 SSL_pending(c->ssl), SSL_has_pending(c->ssl));
1273 #else
1274 s_log(LOG_ERR, "protocol=%s, SSL_pending=%d",
1275 SSL_get_version(c->ssl), SSL_pending(c->ssl));
1276 #endif
1277 s_log(LOG_ERR, "sock_open_rd=%s, sock_open_wr=%s",
1278 sock_open_rd ? "Y" : "n", sock_open_wr ? "Y" : "n");
1279 s_log(LOG_ERR, "SSL_RECEIVED_SHUTDOWN=%s, SSL_SENT_SHUTDOWN=%s",
1280 (SSL_get_shutdown(c->ssl) & SSL_RECEIVED_SHUTDOWN) ? "Y" : "n",
1281 (SSL_get_shutdown(c->ssl) & SSL_SENT_SHUTDOWN) ? "Y" : "n");
1282 s_log(LOG_ERR, "sock_can_rd=%s, sock_can_wr=%s",
1283 sock_can_rd ? "Y" : "n", sock_can_wr ? "Y" : "n");
1284 s_log(LOG_ERR, "ssl_can_rd=%s, ssl_can_wr=%s",
1285 ssl_can_rd ? "Y" : "n", ssl_can_wr ? "Y" : "n");
1286 s_log(LOG_ERR, "read_wants_read=%s, read_wants_write=%s",
1287 read_wants_read ? "Y" : "n", read_wants_write ? "Y" : "n");
1288 s_log(LOG_ERR, "write_wants_read=%s, write_wants_write=%s",
1289 write_wants_read ? "Y" : "n", write_wants_write ? "Y" : "n");
1290 s_log(LOG_ERR, "shutdown_wants_read=%s, shutdown_wants_write=%s",
1291 shutdown_wants_read ? "Y" : "n",
1292 shutdown_wants_write ? "Y" : "n");
1293 s_log(LOG_ERR, "socket input buffer: %ld byte(s), "
1294 "TLS input buffer: %ld byte(s)",
1295 (long)c->sock_ptr, (long)c->ssl_ptr);
1296 throw_exception(c, 1);
1297 }
1298
1299 } while(sock_open_wr || !(SSL_get_shutdown(c->ssl)&SSL_SENT_SHUTDOWN) ||
1300 shutdown_wants_read || shutdown_wants_write);
1301 }
1302
1303 NOEXPORT void auth_user(CLI *c) {
1304 #ifndef _WIN32_WCE
1305 struct servent *s_ent; /* structure for getservbyname */
1306 #endif
1307 SOCKADDR_UNION ident; /* IDENT socket name */
1308 char *line, *type, *system, *user;
1309 unsigned remote_port, local_port;
1310
1311 if(!c->opt->username)
1312 return; /* -u option not specified */
1313 #ifdef HAVE_STRUCT_SOCKADDR_UN
1314 if(c->peer_addr.sa.sa_family==AF_UNIX) {
1315 s_log(LOG_INFO, "IDENT not supported on Unix sockets");
1316 return;
1317 }
1318 #endif
1319 c->fd=s_socket(c->peer_addr.sa.sa_family, SOCK_STREAM,
1320 0, 1, "socket (auth_user)");
1321 if(c->fd==INVALID_SOCKET)
1322 throw_exception(c, 1);
1323 memcpy(&ident, &c->peer_addr, (size_t)c->peer_addr_len);
1324 #ifndef _WIN32_WCE
1325 s_ent=getservbyname("auth", "tcp");
1326 if(s_ent) {
1327 ident.in.sin_port=(u_short)s_ent->s_port;
1328 } else
1329 #endif
1330 {
1331 s_log(LOG_WARNING, "Unknown service 'auth': using default 113");
1332 ident.in.sin_port=htons(113);
1333 }
1334 if(s_connect(c, &ident, addr_len(&ident), c->opt->timeout_connect))
1335 throw_exception(c, 1);
1336 s_log(LOG_DEBUG, "IDENT server connected");
1337 remote_port=ntohs(c->peer_addr.in.sin_port);
1338 local_port=(unsigned)(c->opt->local_addr.addr ?
1339 ntohs(c->opt->local_addr.addr[0].in.sin_port) : 0);
1340 fd_printf(c, c->fd, "%u , %u", remote_port, local_port);
1341 line=fd_getline(c, c->fd);
1342 closesocket(c->fd);
1343 c->fd=INVALID_SOCKET; /* avoid double close on cleanup */
1344 type=strchr(line, ':');
1345 if(!type) {
1346 s_log(LOG_ERR, "Malformed IDENT response");
1347 str_free(line);
1348 throw_exception(c, 1);
1349 }
1350 *type++='\0';
1351 system=strchr(type, ':');
1352 if(!system) {
1353 s_log(LOG_ERR, "Malformed IDENT response");
1354 str_free(line);
1355 throw_exception(c, 1);
1356 }
1357 *system++='\0';
1358 if(strcmp(type, " USERID ")) {
1359 s_log(LOG_ERR, "Incorrect IDENT response type");
1360 str_free(line);
1361 throw_exception(c, 1);
1362 }
1363 user=strchr(system, ':');
1364 if(!user) {
1365 s_log(LOG_ERR, "Malformed IDENT response");
1366 str_free(line);
1367 throw_exception(c, 1);
1368 }
1369 *user++='\0';
1370 while(*user==' ') /* skip leading spaces */
1371 ++user;
1372 if(strcmp(user, c->opt->username)) {
1373 s_log(LOG_ERR, "Connection from %s REFUSED by IDENT (user \"%s\")",
1374 c->accepted_address, user);
1375 str_free(line);
1376 throw_exception(c, 1);
1377 }
1378 s_log(LOG_INFO, "IDENT authentication passed");
1379 str_free(line);
1380 }
1381
1382 #if defined(_WIN32_WCE) || defined(__vms)
1383
1384 NOEXPORT int connect_local(CLI *c) { /* spawn local process */
1385 s_log(LOG_ERR, "Local mode is not supported on this platform");
1386 throw_exception(c, 1);
1387 return -1; /* some C compilers require a return value */
1388 }
1389
1390 #elif defined(USE_WIN32)
1391
1392 NOEXPORT SOCKET connect_local(CLI *c) { /* spawn local process */
1393 SOCKET fd[2];
1394 STARTUPINFO si;
1395 PROCESS_INFORMATION pi;
1396 LPTSTR name, args;
1397
1398 if(make_sockets(fd))
1399 throw_exception(c, 1);
1400 memset(&si, 0, sizeof si);
1401 si.cb=sizeof si;
1402 si.dwFlags=STARTF_USESHOWWINDOW|STARTF_USESTDHANDLES;
1403 si.wShowWindow=SW_HIDE;
1404 si.hStdInput=si.hStdOutput=si.hStdError=(HANDLE)fd[1];
1405 memset(&pi, 0, sizeof pi);
1406
1407 name=str2tstr(c->opt->exec_name);
1408 args=str2tstr(c->opt->exec_args);
1409 CreateProcess(name, args, NULL, NULL, TRUE, 0, NULL, NULL, &si, &pi);
1410 str_free(name);
1411 str_free(args);
1412
1413 closesocket(fd[1]);
1414 CloseHandle(pi.hProcess);
1415 CloseHandle(pi.hThread);
1416 return fd[0];
1417 }
1418
1419 #else /* standard Unix version */
1420
1421 NOEXPORT SOCKET connect_local(CLI *c) { /* spawn local process */
1422 int fd[2], pid;
1423 char **env;
1424 #ifdef HAVE_PTHREAD_SIGMASK
1425 sigset_t newmask;
1426 #endif
1427
1428 if(c->opt->option.pty) {
1429 char tty[64];
1430
1431 if(pty_allocate(fd, fd+1, tty))
1432 throw_exception(c, 1);
1433 s_log(LOG_DEBUG, "TTY=%s allocated", tty);
1434 } else
1435 if(make_sockets(fd))
1436 throw_exception(c, 1);
1437 set_nonblock(fd[1], 0); /* switch back to the blocking mode */
1438
1439 env=env_alloc(c);
1440 pid=fork();
1441 c->pid=(unsigned long)pid;
1442 switch(pid) {
1443 case -1: /* error */
1444 closesocket(fd[0]);
1445 closesocket(fd[1]);
1446 env_free(env);
1447 ioerror("fork");
1448 throw_exception(c, 1);
1449 case 0: /* child */
1450 /* the child is not allowed to play with thread-local storage */
1451 /* see http://linux.die.net/man/3/pthread_atfork for details */
1452 closesocket(fd[0]);
1453 /* dup2() does not copy FD_CLOEXEC flag */
1454 dup2(fd[1], 0);
1455 dup2(fd[1], 1);
1456 if(!c->opt->option.log_stderr)
1457 dup2(fd[1], 2);
1458 closesocket(fd[1]); /* not really needed due to FD_CLOEXEC */
1459 #ifdef HAVE_PTHREAD_SIGMASK
1460 sigemptyset(&newmask);
1461 sigprocmask(SIG_SETMASK, &newmask, NULL);
1462 #endif
1463 signal(SIGCHLD, SIG_DFL);
1464 signal(SIGHUP, SIG_DFL);
1465 signal(SIGUSR1, SIG_DFL);
1466 signal(SIGUSR2, SIG_DFL);
1467 signal(SIGPIPE, SIG_DFL);
1468 signal(SIGTERM, SIG_DFL);
1469 signal(SIGQUIT, SIG_DFL);
1470 signal(SIGINT, SIG_DFL);
1471 execve(c->opt->exec_name, c->opt->exec_args, env);
1472 _exit(1); /* failed, but there is no way to report an error here */
1473 default: /* parent */
1474 closesocket(fd[1]);
1475 env_free(env);
1476 s_log(LOG_INFO, "Local mode child started (PID=%lu)", c->pid);
1477 return fd[0];
1478 }
1479 }
1480
1481 char **env_alloc(CLI *c) {
1482 extern char **environ;
1483 char **env=NULL, **p;
1484 unsigned n=0; /* (n+2) keeps the list NULL-terminated */
1485 char *name, host[40], port[6];
1486 X509 *peer_cert;
1487
1488 if(!getnameinfo(&c->peer_addr.sa, c->peer_addr_len,
1489 host, 40, port, 6, NI_NUMERICHOST|NI_NUMERICSERV)) {
1490 /* just don't set these variables if getnameinfo() fails */
1491 env=str_realloc(env, (n+2)*sizeof(char *));
1492 env[n++]=str_printf("REMOTE_HOST=%s", host);
1493 env=str_realloc(env, (n+2)*sizeof(char *));
1494 env[n++]=str_printf("REMOTE_PORT=%s", port);
1495 if(c->opt->option.transparent_src) {
1496 #ifndef LIBDIR
1497 #define LIBDIR "."
1498 #endif
1499 #ifdef MACH64
1500 env=str_realloc(env, (n+2)*sizeof(char *));
1501 env[n++]=str_dup("LD_PRELOAD_32=" LIBDIR "/libstunnel.so");
1502 env=str_realloc(env, (n+2)*sizeof(char *));
1503 env[n++]=str_dup("LD_PRELOAD_64=" LIBDIR "/" MACH64 "/libstunnel.so");
1504 #elif defined(__osf) || defined(__osf__)
1505 /* for Tru64 _RLD_LIST is used instead */
1506 env=str_realloc(env, (n+2)*sizeof(char *));
1507 env[n++]=str_dup("_RLD_LIST=" LIBDIR "/libstunnel.so:DEFAULT");
1508 #else
1509 env=str_realloc(env, (n+2)*sizeof(char *));
1510 env[n++]=str_dup("LD_PRELOAD=" LIBDIR "/libstunnel.so");
1511 #endif
1512 }
1513 }
1514
1515 if(c->ssl) {
1516 peer_cert=SSL_get_peer_certificate(c->ssl);
1517 if(peer_cert) {
1518 name=X509_NAME2text(X509_get_subject_name(peer_cert));
1519 env=str_realloc(env, (n+2)*sizeof(char *));
1520 env[n++]=str_printf("SSL_CLIENT_DN=%s", name);
1521 str_free(name);
1522 name=X509_NAME2text(X509_get_issuer_name(peer_cert));
1523 env=str_realloc(env, (n+2)*sizeof(char *));
1524 env[n++]=str_printf("SSL_CLIENT_I_DN=%s", name);
1525 str_free(name);
1526 X509_free(peer_cert);
1527 }
1528 }
1529
1530 for(p=environ; *p; ++p) {
1531 env=str_realloc(env, (n+2)*sizeof(char *));
1532 env[n++]=str_dup(*p);
1533 }
1534
1535 return env;
1536 }
1537
1538 void env_free(char **env) {
1539 char **p;
1540
1541 for(p=env; *p; ++p)
1542 str_free(*p);
1543 str_free(env);
1544 }
1545
1546 #endif /* not USE_WIN32 or __vms */
1547
1548 /* connect remote host */
1549 NOEXPORT SOCKET connect_remote(CLI *c) {
1550 SOCKET fd;
1551 unsigned idx_start, idx_try;
1552
1553 connect_setup(c);
1554 switch(c->connect_addr.num) {
1555 case 0:
1556 s_log(LOG_ERR, "No remote host resolved");
1557 throw_exception(c, 1);
1558 case 1:
1559 idx_start=0;
1560 break;
1561 default:
1562 idx_start=idx_cache_retrieve(c);
1563 }
1564
1565 /* try to connect each host from the list */
1566 for(idx_try=0; idx_try<c->connect_addr.num; idx_try++) {
1567 c->idx=(idx_start+idx_try)%c->connect_addr.num;
1568 if(!connect_init(c, c->connect_addr.addr[c->idx].sa.sa_family) &&
1569 !s_connect(c, &c->connect_addr.addr[c->idx],
1570 addr_len(&c->connect_addr.addr[c->idx]),
1571 c->opt->timeout_connect)) {
1572 if(c->ssl) {
1573 SSL_SESSION *sess=SSL_get1_session(c->ssl);
1574 if(sess) {
1575 idx_cache_save(sess, &c->connect_addr.addr[c->idx]);
1576 SSL_SESSION_free(sess);
1577 }
1578 }
1579 print_bound_address(c);
1580 fd=c->fd;
1581 c->fd=INVALID_SOCKET;
1582 return fd; /* success! */
1583 }
1584 if(c->fd!=INVALID_SOCKET) {
1585 closesocket(c->fd);
1586 c->fd=INVALID_SOCKET;
1587 }
1588 }
1589 s_log(LOG_ERR, "No more addresses to connect");
1590 throw_exception(c, 1);
1591 return INVALID_SOCKET; /* some C compilers require a return value */
1592 }
1593
1594 NOEXPORT void idx_cache_save(SSL_SESSION *sess, SOCKADDR_UNION *cur_addr) {
1595 SOCKADDR_UNION *old_addr, *new_addr;
1596 socklen_t len;
1597 char *addr_txt;
1598 int ok;
1599
1600 /* make a copy of the address, so it may work with delayed resolver */
1601 len=addr_len(cur_addr);
1602 new_addr=str_alloc_detached((size_t)len);
1603 memcpy(new_addr, cur_addr, (size_t)len);
1604
1605 addr_txt=s_ntop(cur_addr, len);
1606 s_log(LOG_INFO, "persistence: %s cached", addr_txt);
1607 str_free(addr_txt);
1608
1609 CRYPTO_THREAD_write_lock(stunnel_locks[LOCK_ADDR]);
1610 old_addr=SSL_SESSION_get_ex_data(sess, index_session_connect_address);
1611 ok=SSL_SESSION_set_ex_data(sess, index_session_connect_address, new_addr);
1612 CRYPTO_THREAD_unlock(stunnel_locks[LOCK_ADDR]);
1613 if(ok) {
1614 str_free(old_addr); /* NULL pointers are ignored */
1615 } else { /* failed to store new_addr -> remove it */
1616 ssl_error(NULL, "SSL_SESSION_set_ex_data");
1617 str_free(new_addr); /* NULL pointers are ignored */
1618 }
1619 }
1620
1621 NOEXPORT unsigned idx_cache_retrieve(CLI *c) {
1622 unsigned i;
1623 SOCKADDR_UNION addr, *ptr;
1624 socklen_t len;
1625 char *addr_txt;
1626
1627 if(c->ssl && SSL_session_reused(c->ssl)) {
1628 SSL_SESSION *sess=SSL_get1_session(c->ssl);
1629 if(sess) {
1630 CRYPTO_THREAD_read_lock(stunnel_locks[LOCK_ADDR]);
1631 ptr=SSL_SESSION_get_ex_data(sess, index_session_connect_address);
1632 if(ptr) {
1633 len=addr_len(ptr);
1634 memcpy(&addr, ptr, (size_t)len);
1635 CRYPTO_THREAD_unlock(stunnel_locks[LOCK_ADDR]);
1636 SSL_SESSION_free(sess);
1637 /* address was copied, ptr itself is no longer valid */
1638 for(i=0; i<c->connect_addr.num; ++i) {
1639 if(addr_len(&c->connect_addr.addr[i])==len &&
1640 !memcmp(&c->connect_addr.addr[i],
1641 &addr, (size_t)len)) {
1642 addr_txt=s_ntop(&addr, len);
1643 s_log(LOG_INFO, "persistence: %s reused", addr_txt);
1644 str_free(addr_txt);
1645 return i;
1646 }
1647 }
1648 addr_txt=s_ntop(&addr, len);
1649 s_log(LOG_INFO, "persistence: %s not available", addr_txt);
1650 str_free(addr_txt);
1651 } else {
1652 CRYPTO_THREAD_unlock(stunnel_locks[LOCK_ADDR]);
1653 SSL_SESSION_free(sess);
1654 s_log(LOG_NOTICE, "persistence: No cached address found");
1655 }
1656 }
1657 }
1658
1659 if(c->opt->failover==FAILOVER_RR) {
1660 i=(c->connect_addr.start+c->rr)%c->connect_addr.num;
1661 s_log(LOG_INFO, "failover: round-robin, starting at entry #%d", i);
1662 } else {
1663 i=0;
1664 s_log(LOG_INFO, "failover: priority, starting at entry #0");
1665 }
1666 return i;
1667 }
1668
1669 NOEXPORT void connect_setup(CLI *c) {
1670 if(c->flag.redirect) { /* process "redirect" first */
1671 s_log(LOG_NOTICE, "Redirecting connection");
1672 /* c->connect_addr.addr may be allocated in protocol negotiations */
1673 str_free(c->connect_addr.addr);
1674 addrlist_dup(&c->connect_addr, &c->opt->redirect_addr);
1675 return;
1676 }
1677
1678 /* check if the address was already set in protocol negotiations */
1679 /* used by the following protocols: CONNECT, SOCKS */
1680 if(c->connect_addr.num)
1681 return;
1682
1683 /* transparent destination */
1684 if(c->opt->option.transparent_dst) {
1685 c->connect_addr.num=1;
1686 c->connect_addr.addr=str_alloc(sizeof(SOCKADDR_UNION));
1687 if(original_dst(c->local_rfd.fd, c->connect_addr.addr))
1688 throw_exception(c, 1);
1689 return;
1690 }
1691
1692 /* default "connect" target */
1693 addrlist_dup(&c->connect_addr, &c->opt->connect_addr);
1694 }
1695
1696 NOEXPORT int connect_init(CLI *c, int domain) {
1697 SOCKADDR_UNION bind_addr;
1698
1699 if(c->bind_addr) {
1700 /* setup bind_addr based on c->bind_addr */
1701 memcpy(&bind_addr, c->bind_addr, (size_t)addr_len(c->bind_addr));
1702 /* perform the initial sanity checks before creating a socket */
1703 if(bind_addr.sa.sa_family!=domain) {
1704 s_log(LOG_DEBUG, "Cannot assign an AF=%d address an AF=%d socket",
1705 bind_addr.sa.sa_family, domain);
1706 return 1; /* failure */
1707 }
1708 } else {
1709 /* only needed to avoid a warning in MSVC */
1710 memset(&bind_addr, 0, sizeof bind_addr);
1711 }
1712
1713 /* create a new socket */
1714 c->fd=s_socket(domain, SOCK_STREAM, 0, 1, "remote socket");
1715 if(c->fd==INVALID_SOCKET)
1716 return 1; /* failure */
1717 if(!c->bind_addr)
1718 return 0; /* success */
1719
1720 /* enable non-local bind if needed (and supported) */
1721 #ifndef USE_WIN32
1722 if(c->opt->option.transparent_src) {
1723 #if defined(__linux__)
1724 /* non-local bind on Linux */
1725 int on=1;
1726 if(setsockopt(c->fd, SOL_IP, IP_TRANSPARENT, &on, sizeof on)) {
1727 sockerror("setsockopt IP_TRANSPARENT");
1728 if(setsockopt(c->fd, SOL_IP, IP_FREEBIND, &on, sizeof on))
1729 sockerror("setsockopt IP_FREEBIND");
1730 else
1731 s_log(LOG_INFO, "IP_FREEBIND socket option set");
1732 } else
1733 s_log(LOG_INFO, "IP_TRANSPARENT socket option set");
1734 /* ignore the error to retain Linux 2.2 compatibility */
1735 /* the error will be handled by bind(), anyway */
1736 #elif defined(IP_BINDANY) && defined(IPV6_BINDANY)
1737 /* non-local bind on FreeBSD */
1738 int on=1;
1739 if(domain==AF_INET) { /* IPv4 */
1740 if(setsockopt(c->fd, IPPROTO_IP, IP_BINDANY, &on, sizeof on)) {
1741 sockerror("setsockopt IP_BINDANY");
1742 return 1; /* failure */
1743 }
1744 } else { /* IPv6 */
1745 if(setsockopt(c->fd, IPPROTO_IPV6, IPV6_BINDANY, &on, sizeof on)) {
1746 sockerror("setsockopt IPV6_BINDANY");
1747 return 1; /* failure */
1748 }
1749 }
1750 #else
1751 /* unsupported platform */
1752 /* FIXME: move this check to options.c */
1753 s_log(LOG_ERR, "Transparent proxy in remote mode is not supported"
1754 " on this platform");
1755 throw_exception(c, 1);
1756 #endif
1757 }
1758 #endif /* !defined(USE_WIN32) */
1759
1760 /* explicit local bind or transparent proxy */
1761 /* there is no need for a separate IPv6 logic here,
1762 * as port number is at the same offset in both structures */
1763 if(ntohs(bind_addr.in.sin_port)>=1024) { /* security check */
1764 /* this is currently only possible with transparent_src */
1765 if(!bind(c->fd, &bind_addr.sa, addr_len(&bind_addr))) {
1766 s_log(LOG_INFO, "bind succeeded on the original port");
1767 return 0; /* success */
1768 }
1769 if(get_last_socket_error()!=S_EADDRINUSE) {
1770 sockerror("bind (original port)");
1771 return 1; /* failure */
1772 }
1773 }
1774 bind_addr.in.sin_port=htons(0); /* retry with ephemeral port */
1775 if(!bind(c->fd, &bind_addr.sa, addr_len(&bind_addr))) {
1776 s_log(LOG_INFO, "bind succeeded on an ephemeral port");
1777 return 0; /* success */
1778 }
1779 sockerror("bind (ephemeral port)");
1780 return 1; /* failure */
1781 }
1782
1783 NOEXPORT int redirect(CLI *c) {
1784 SSL_SESSION *sess;
1785 void *ex_data;
1786
1787 if(!c->opt->redirect_addr.names)
1788 return 0; /* redirect not configured */
1789 if(!c->ssl)
1790 return 1; /* TLS not established -> always redirect */
1791 sess=SSL_get1_session(c->ssl);
1792 if(!sess)
1793 return 1; /* no TLS session -> always redirect */
1794 ex_data=SSL_SESSION_get_ex_data(sess, index_session_authenticated);
1795 SSL_SESSION_free(sess);
1796 return ex_data == NULL;
1797 }
1798
1799 NOEXPORT void print_bound_address(CLI *c) {
1800 char *txt;
1801 SOCKADDR_UNION addr;
1802 socklen_t addrlen=sizeof addr;
1803
1804 if(c->opt->log_level<LOG_NOTICE) /* performance optimization */
1805 return;
1806 memset(&addr, 0, (size_t)addrlen);
1807 if(getsockname(c->fd, (struct sockaddr *)&addr, &addrlen)) {
1808 sockerror("getsockname");
1809 return;
1810 }
1811 txt=s_ntop(&addr, addrlen);
1812 s_log(LOG_NOTICE,"Service [%s] connected remote server from %s",
1813 c->opt->servname, txt);
1814 str_free(txt);
1815 }
1816
1817 /* set lingering on a socket */
1818 NOEXPORT void reset(SOCKET fd, const char *txt) {
1819 struct linger l;
1820
1821 s_log(LOG_DEBUG, "%s reset (FD=%ld)", txt, (long)fd);
1822 l.l_onoff=1;
1823 l.l_linger=0;
1824 if(setsockopt(fd, SOL_SOCKET, SO_LINGER, (void *)&l, sizeof l)) {
1825 int err=get_last_socket_error();
1826 char *message=str_printf("setsockopt(SO_LINGER) on %s", txt);
1827
1828 log_error(LOG_INFO, err, message);
1829 str_free(message);
1830 }
1831 }
1832
1833 NOEXPORT void check_socket_error(CLI *c, SOCKET fd, const char *name) {
1834 if(s_poll_err(c->fds, fd)) {
1835 int err=get_socket_error(fd);
1836
1837 if(!err) {
1838 s_log(LOG_DEBUG, "Spurious s_poll exception on %s", name);
1839 } else if(err==S_EWOULDBLOCK || err==S_EAGAIN) {
1840 log_error(LOG_DEBUG, err, name);
1841 } else {
1842 log_error(LOG_ERR, err, name);
1843 /* throwing an exception here truncated connections
1844 * in stunnel versions 4.34 - 5.08 */
1845 /* throw_exception(c, 1); */
1846 }
1847 }
1848 }
1849
1850 void throw_exception(CLI *c, int v) {
1851 if(!c || !c->exception_pointer)
1852 fatal("No exception handler");
1853 longjmp(*c->exception_pointer, v);
1854 }
1855
1856 /* end of client.c */