xref: /openssl/apps/lib/s_socket.c (revision 23b795d3)
1 /*
2  * Copyright 1995-2024 The OpenSSL Project Authors. All Rights Reserved.
3  *
4  * Licensed under the Apache License 2.0 (the "License").  You may not use
5  * this file except in compliance with the License.  You can obtain a copy
6  * in the file LICENSE in the source distribution or at
7  * https://www.openssl.org/source/license.html
8  */
9 
10 /* socket-related functions used by s_client and s_server */
11 #include <stdio.h>
12 #include <stdlib.h>
13 #include <string.h>
14 #include <errno.h>
15 #include <signal.h>
16 #include <openssl/opensslconf.h>
17 
18 /*
19  * With IPv6, it looks like Digital has mixed up the proper order of
20  * recursive header file inclusion, resulting in the compiler complaining
21  * that u_int isn't defined, but only if _POSIX_C_SOURCE is defined, which is
22  * needed to have fileno() declared correctly...  So let's define u_int
23  */
24 #if defined(OPENSSL_SYS_VMS_DECC) && !defined(__U_INT)
25 # define __U_INT
26 typedef unsigned int u_int;
27 #endif
28 
29 #ifdef _WIN32
30 # include <process.h>
31 
32 /* MSVC renamed some POSIX functions to have an underscore prefix. */
33 # ifdef _MSC_VER
34 #  define getpid _getpid
35 # endif
36 #endif
37 
38 #ifndef OPENSSL_NO_SOCK
39 
40 # include "internal/e_os.h"
41 # include "apps.h"
42 # include "s_apps.h"
43 # include "internal/sockets.h" /* for openssl_fdset() */
44 
45 # include <openssl/bio.h>
46 # include <openssl/err.h>
47 
48 /* Keep track of our peer's address for the cookie callback */
49 BIO_ADDR *ourpeer = NULL;
50 
51 /*
52  * init_client - helper routine to set up socket communication
53  * @sock: pointer to storage of resulting socket.
54  * @host: the hostname or path (for AF_UNIX) to connect to.
55  * @port: the port to connect to (ignored for AF_UNIX).
56  * @bindhost: source host or path (for AF_UNIX).
57  * @bindport: source port (ignored for AF_UNIX).
58  * @family: desired socket family, may be AF_INET, AF_INET6, AF_UNIX or
59  *  AF_UNSPEC
60  * @type: socket type, must be SOCK_STREAM or SOCK_DGRAM
61  * @protocol: socket protocol, e.g. IPPROTO_TCP or IPPROTO_UDP (or 0 for any)
62  * @tfo: flag to enable TCP Fast Open
63  * @doconn: whether we should call BIO_connect() on the socket
64  * @ba_ret: BIO_ADDR for the remote peer, to be freed by caller
65  *
66  * This will create a socket and use it to connect to a host:port, or if
67  * family == AF_UNIX, to the path found in host.
68  *
69  * If the host has more than one address, it will try them one by one until
70  * a successful connection is established.  The resulting socket will be
71  * found in *sock on success, it will be given INVALID_SOCKET otherwise.
72  *
73  * Returns 1 on success, 0 on failure.
74  */
init_client(int * sock,const char * host,const char * port,const char * bindhost,const char * bindport,int family,int type,int protocol,int tfo,int doconn,BIO_ADDR ** ba_ret)75 int init_client(int *sock, const char *host, const char *port,
76                 const char *bindhost, const char *bindport,
77                 int family, int type, int protocol, int tfo, int doconn,
78                 BIO_ADDR **ba_ret)
79 {
80     BIO_ADDRINFO *res = NULL;
81     BIO_ADDRINFO *bindaddr = NULL;
82     const BIO_ADDRINFO *ai = NULL;
83     const BIO_ADDRINFO *bi = NULL;
84     int found = 0;
85     int ret;
86     int options = 0;
87 
88     if (BIO_sock_init() != 1)
89         return 0;
90 
91     ret = BIO_lookup_ex(host, port, BIO_LOOKUP_CLIENT, family, type, protocol,
92                         &res);
93     if (ret == 0) {
94         ERR_print_errors(bio_err);
95         return 0;
96     }
97 
98     if (bindhost != NULL || bindport != NULL) {
99         ret = BIO_lookup_ex(bindhost, bindport, BIO_LOOKUP_CLIENT,
100                             family, type, protocol, &bindaddr);
101         if (ret == 0) {
102             ERR_print_errors (bio_err);
103             goto out;
104         }
105     }
106 
107     ret = 0;
108     for (ai = res; ai != NULL; ai = BIO_ADDRINFO_next(ai)) {
109         /* Admittedly, these checks are quite paranoid, we should not get
110          * anything in the BIO_ADDRINFO chain that we haven't
111          * asked for. */
112         OPENSSL_assert((family == AF_UNSPEC
113                         || family == BIO_ADDRINFO_family(ai))
114                        && (type == 0 || type == BIO_ADDRINFO_socktype(ai))
115                        && (protocol == 0
116                            || protocol == BIO_ADDRINFO_protocol(ai)));
117 
118         if (bindaddr != NULL) {
119             for (bi = bindaddr; bi != NULL; bi = BIO_ADDRINFO_next(bi)) {
120                 if (BIO_ADDRINFO_family(bi) == BIO_ADDRINFO_family(ai))
121                     break;
122             }
123             if (bi == NULL)
124                 continue;
125             ++found;
126         }
127 
128         *sock = BIO_socket(BIO_ADDRINFO_family(ai), BIO_ADDRINFO_socktype(ai),
129                            BIO_ADDRINFO_protocol(ai), 0);
130         if (*sock == INVALID_SOCKET) {
131             /* Maybe the kernel doesn't support the socket family, even if
132              * BIO_lookup() added it in the returned result...
133              */
134             continue;
135         }
136 
137         if (bi != NULL) {
138             if (!BIO_bind(*sock, BIO_ADDRINFO_address(bi),
139                           BIO_SOCK_REUSEADDR)) {
140                 BIO_closesocket(*sock);
141                 *sock = INVALID_SOCKET;
142                 break;
143             }
144         }
145 
146 #ifndef OPENSSL_NO_SCTP
147         if (protocol == IPPROTO_SCTP) {
148             /*
149              * For SCTP we have to set various options on the socket prior to
150              * connecting. This is done automatically by BIO_new_dgram_sctp().
151              * We don't actually need the created BIO though so we free it again
152              * immediately.
153              */
154             BIO *tmpbio = BIO_new_dgram_sctp(*sock, BIO_NOCLOSE);
155 
156             if (tmpbio == NULL) {
157                 ERR_print_errors(bio_err);
158                 return 0;
159             }
160             BIO_free(tmpbio);
161         }
162 #endif
163         if (BIO_ADDRINFO_protocol(ai) == IPPROTO_TCP) {
164             options |= BIO_SOCK_NODELAY;
165             if (tfo)
166                 options |= BIO_SOCK_TFO;
167         }
168 
169         if (doconn && !BIO_connect(*sock, BIO_ADDRINFO_address(ai), options)) {
170             BIO_closesocket(*sock);
171             *sock = INVALID_SOCKET;
172             continue;
173         }
174 
175         /* Save the address */
176         if (tfo || !doconn)
177             *ba_ret = BIO_ADDR_dup(BIO_ADDRINFO_address(ai));
178 
179         /* Success, don't try any more addresses */
180         break;
181     }
182 
183     if (*sock == INVALID_SOCKET) {
184         if (bindaddr != NULL && !found) {
185             BIO_printf(bio_err, "Can't bind %saddress for %s%s%s\n",
186 #ifdef AF_INET6
187                        BIO_ADDRINFO_family(res) == AF_INET6 ? "IPv6 " :
188 #endif
189                        BIO_ADDRINFO_family(res) == AF_INET ? "IPv4 " :
190                        BIO_ADDRINFO_family(res) == AF_UNIX ? "unix " : "",
191                        bindhost != NULL ? bindhost : "",
192                        bindport != NULL ? ":" : "",
193                        bindport != NULL ? bindport : "");
194             ERR_clear_error();
195             ret = 0;
196         }
197         ERR_print_errors(bio_err);
198     } else {
199         char *hostname = NULL;
200 
201         hostname = BIO_ADDR_hostname_string(BIO_ADDRINFO_address(ai), 1);
202         if (hostname != NULL) {
203             BIO_printf(bio_err, "Connecting to %s\n", hostname);
204             OPENSSL_free(hostname);
205         }
206         /* Remove any stale errors from previous connection attempts */
207         ERR_clear_error();
208         ret = 1;
209     }
210 out:
211     if (bindaddr != NULL) {
212         BIO_ADDRINFO_free (bindaddr);
213     }
214     BIO_ADDRINFO_free(res);
215     return ret;
216 }
217 
get_sock_info_address(int asock,char ** hostname,char ** service)218 void get_sock_info_address(int asock, char **hostname, char **service)
219 {
220     union BIO_sock_info_u info;
221 
222     if (hostname != NULL)
223         *hostname = NULL;
224     if (service != NULL)
225         *service = NULL;
226 
227     if ((info.addr = BIO_ADDR_new()) != NULL
228             && BIO_sock_info(asock, BIO_SOCK_INFO_ADDRESS, &info)) {
229         if (hostname != NULL)
230             *hostname = BIO_ADDR_hostname_string(info.addr, 1);
231         if (service != NULL)
232             *service = BIO_ADDR_service_string(info.addr, 1);
233     }
234     BIO_ADDR_free(info.addr);
235 }
236 
report_server_accept(BIO * out,int asock,int with_address,int with_pid)237 int report_server_accept(BIO *out, int asock, int with_address, int with_pid)
238 {
239     int success = 1;
240 
241     if (BIO_printf(out, "ACCEPT") <= 0)
242         return 0;
243     if (with_address) {
244         char *hostname, *service;
245 
246         get_sock_info_address(asock, &hostname, &service);
247         success = hostname != NULL && service != NULL;
248         if (success)
249             success = BIO_printf(out,
250                                  strchr(hostname, ':') == NULL
251                                  ? /* IPv4 */ " %s:%s"
252                                  : /* IPv6 */ " [%s]:%s",
253                                  hostname, service) > 0;
254         else
255             (void)BIO_printf(out, "unknown:error\n");
256         OPENSSL_free(hostname);
257         OPENSSL_free(service);
258     }
259     if (with_pid)
260         success *= BIO_printf(out, " PID=%d", getpid()) > 0;
261     success *= BIO_printf(out, "\n") > 0;
262     (void)BIO_flush(out);
263 
264     return success;
265 }
266 
267 /*
268  * do_server - helper routine to perform a server operation
269  * @accept_sock: pointer to storage of resulting socket.
270  * @host: the hostname or path (for AF_UNIX) to connect to.
271  * @port: the port to connect to (ignored for AF_UNIX).
272  * @family: desired socket family, may be AF_INET, AF_INET6, AF_UNIX or
273  *  AF_UNSPEC
274  * @type: socket type, must be SOCK_STREAM or SOCK_DGRAM
275  * @cb: pointer to a function that receives the accepted socket and
276  *  should perform the communication with the connecting client.
277  * @context: pointer to memory that's passed verbatim to the cb function.
278  * @naccept: number of times an incoming connect should be accepted.  If -1,
279  *  unlimited number.
280  *
281  * This will create a socket and use it to listen to a host:port, or if
282  * family == AF_UNIX, to the path found in host, then start accepting
283  * incoming connections and run cb on the resulting socket.
284  *
285  * 0 on failure, something other on success.
286  */
do_server(int * accept_sock,const char * host,const char * port,int family,int type,int protocol,do_server_cb cb,unsigned char * context,int naccept,BIO * bio_s_out,int tfo)287 int do_server(int *accept_sock, const char *host, const char *port,
288               int family, int type, int protocol, do_server_cb cb,
289               unsigned char *context, int naccept, BIO *bio_s_out,
290               int tfo)
291 {
292     int asock = 0;
293     int sock;
294     int i;
295     BIO_ADDRINFO *res = NULL;
296     const BIO_ADDRINFO *next;
297     int sock_family, sock_type, sock_protocol, sock_port;
298     const BIO_ADDR *sock_address;
299     int sock_family_fallback = AF_UNSPEC;
300     const BIO_ADDR *sock_address_fallback = NULL;
301     int sock_options = BIO_SOCK_REUSEADDR;
302     int ret = 0;
303 
304     if (BIO_sock_init() != 1)
305         return 0;
306 
307     if (!BIO_lookup_ex(host, port, BIO_LOOKUP_SERVER, family, type, protocol,
308                        &res)) {
309         ERR_print_errors(bio_err);
310         return 0;
311     }
312 
313     /* Admittedly, these checks are quite paranoid, we should not get
314      * anything in the BIO_ADDRINFO chain that we haven't asked for */
315     OPENSSL_assert((family == AF_UNSPEC || family == BIO_ADDRINFO_family(res))
316                    && (type == 0 || type == BIO_ADDRINFO_socktype(res))
317                    && (protocol == 0 || protocol == BIO_ADDRINFO_protocol(res)));
318 
319     sock_family = BIO_ADDRINFO_family(res);
320     sock_type = BIO_ADDRINFO_socktype(res);
321     sock_protocol = BIO_ADDRINFO_protocol(res);
322     sock_address = BIO_ADDRINFO_address(res);
323     next = BIO_ADDRINFO_next(res);
324     if (tfo && sock_type == SOCK_STREAM)
325         sock_options |= BIO_SOCK_TFO;
326 #ifdef AF_INET6
327     if (sock_family == AF_INET6)
328         sock_options |= BIO_SOCK_V6_ONLY;
329     if (next != NULL
330             && BIO_ADDRINFO_socktype(next) == sock_type
331             && BIO_ADDRINFO_protocol(next) == sock_protocol) {
332         if (sock_family == AF_INET
333                 && BIO_ADDRINFO_family(next) == AF_INET6) {
334             /* In case AF_INET6 is returned but not supported by the
335              * kernel, retry with the first detected address family */
336             sock_family_fallback = sock_family;
337             sock_address_fallback = sock_address;
338             sock_family = AF_INET6;
339             sock_address = BIO_ADDRINFO_address(next);
340         } else if (sock_family == AF_INET6
341                    && BIO_ADDRINFO_family(next) == AF_INET) {
342             sock_options &= ~BIO_SOCK_V6_ONLY;
343         }
344     }
345 #endif
346 
347     asock = BIO_socket(sock_family, sock_type, sock_protocol, 0);
348     if (asock == INVALID_SOCKET && sock_family_fallback != AF_UNSPEC) {
349         asock = BIO_socket(sock_family_fallback, sock_type, sock_protocol, 0);
350         sock_address = sock_address_fallback;
351     }
352     if (asock == INVALID_SOCKET
353         || !BIO_listen(asock, sock_address, sock_options)) {
354         BIO_ADDRINFO_free(res);
355         ERR_print_errors(bio_err);
356         if (asock != INVALID_SOCKET)
357             BIO_closesocket(asock);
358         goto end;
359     }
360 
361 #ifndef OPENSSL_NO_SCTP
362     if (protocol == IPPROTO_SCTP) {
363         /*
364          * For SCTP we have to set various options on the socket prior to
365          * accepting. This is done automatically by BIO_new_dgram_sctp().
366          * We don't actually need the created BIO though so we free it again
367          * immediately.
368          */
369         BIO *tmpbio = BIO_new_dgram_sctp(asock, BIO_NOCLOSE);
370 
371         if (tmpbio == NULL) {
372             BIO_closesocket(asock);
373             ERR_print_errors(bio_err);
374             goto end;
375         }
376         BIO_free(tmpbio);
377     }
378 #endif
379 
380     sock_port = BIO_ADDR_rawport(sock_address);
381 
382     BIO_ADDRINFO_free(res);
383     res = NULL;
384 
385     if (!report_server_accept(bio_s_out, asock, sock_port == 0, 0)) {
386         BIO_closesocket(asock);
387         ERR_print_errors(bio_err);
388         goto end;
389     }
390 
391     if (accept_sock != NULL)
392         *accept_sock = asock;
393     for (;;) {
394         char sink[64];
395         struct timeval timeout;
396         fd_set readfds;
397 
398         if (type == SOCK_STREAM) {
399             BIO_ADDR_free(ourpeer);
400             ourpeer = BIO_ADDR_new();
401             if (ourpeer == NULL) {
402                 BIO_closesocket(asock);
403                 ERR_print_errors(bio_err);
404                 goto end;
405             }
406             do {
407                 sock = BIO_accept_ex(asock, ourpeer, 0);
408             } while (sock < 0 && BIO_sock_should_retry(sock));
409             if (sock < 0) {
410                 ERR_print_errors(bio_err);
411                 BIO_closesocket(asock);
412                 break;
413             }
414             BIO_set_tcp_ndelay(sock, 1);
415             i = (*cb)(sock, type, protocol, context);
416 
417             /*
418              * If we ended with an alert being sent, but still with data in the
419              * network buffer to be read, then calling BIO_closesocket() will
420              * result in a TCP-RST being sent. On some platforms (notably
421              * Windows) then this will result in the peer immediately abandoning
422              * the connection including any buffered alert data before it has
423              * had a chance to be read. Shutting down the sending side first,
424              * and then closing the socket sends TCP-FIN first followed by
425              * TCP-RST. This seems to allow the peer to read the alert data.
426              */
427             shutdown(sock, 1); /* SHUT_WR */
428             /*
429              * We just said we have nothing else to say, but it doesn't mean
430              * that the other side has nothing. It's even recommended to
431              * consume incoming data. [In testing context this ensures that
432              * alerts are passed on...]
433              */
434             timeout.tv_sec = 0;
435             timeout.tv_usec = 500000;  /* some extreme round-trip */
436             do {
437                 FD_ZERO(&readfds);
438                 openssl_fdset(sock, &readfds);
439             } while (select(sock + 1, &readfds, NULL, NULL, &timeout) > 0
440                      && readsocket(sock, sink, sizeof(sink)) > 0);
441 
442             BIO_closesocket(sock);
443         } else {
444             i = (*cb)(asock, type, protocol, context);
445         }
446 
447         if (naccept != -1)
448             naccept--;
449         if (i < 0 || naccept == 0) {
450             BIO_closesocket(asock);
451             ret = i;
452             break;
453         }
454     }
455  end:
456 # ifdef AF_UNIX
457     if (family == AF_UNIX)
458         unlink(host);
459 # endif
460     BIO_ADDR_free(ourpeer);
461     ourpeer = NULL;
462     return ret;
463 }
464 
do_ssl_shutdown(SSL * ssl)465 void do_ssl_shutdown(SSL *ssl)
466 {
467     int ret;
468 
469     do {
470         /* We only do unidirectional shutdown */
471         ret = SSL_shutdown(ssl);
472         if (ret < 0) {
473             switch (SSL_get_error(ssl, ret)) {
474             case SSL_ERROR_WANT_READ:
475             case SSL_ERROR_WANT_WRITE:
476             case SSL_ERROR_WANT_ASYNC:
477             case SSL_ERROR_WANT_ASYNC_JOB:
478                 /* We just do busy waiting. Nothing clever */
479                 continue;
480             }
481             ret = 0;
482         }
483     } while (ret < 0);
484 }
485 
486 #endif  /* OPENSSL_NO_SOCK */
487