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