1 /*
2 * Copyright 1995-2021 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 *
68 * This will create a socket and use it to connect to a host:port, or if
69 * family == AF_UNIX, to the path found in host.
70 *
71 * If the host has more than one address, it will try them one by one until
72 * a successful connection is established. The resulting socket will be
73 * found in *sock on success, it will be given INVALID_SOCKET otherwise.
74 *
75 * Returns 1 on success, 0 on failure.
76 */
init_client(int * sock,const char * host,const char * port,const char * bindhost,const char * bindport,int family,int type,int protocol)77 int init_client(int *sock, const char *host, const char *port,
78 const char *bindhost, const char *bindport,
79 int family, int type, int protocol)
80 {
81 BIO_ADDRINFO *res = NULL;
82 BIO_ADDRINFO *bindaddr = NULL;
83 const BIO_ADDRINFO *ai = NULL;
84 const BIO_ADDRINFO *bi = NULL;
85 int found = 0;
86 int ret;
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
164 if (!BIO_connect(*sock, BIO_ADDRINFO_address(ai),
165 protocol == IPPROTO_TCP ? BIO_SOCK_NODELAY : 0)) {
166 BIO_closesocket(*sock);
167 *sock = INVALID_SOCKET;
168 continue;
169 }
170
171 /* Success, don't try any more addresses */
172 break;
173 }
174
175 if (*sock == INVALID_SOCKET) {
176 if (bindaddr != NULL && !found) {
177 BIO_printf(bio_err, "Can't bind %saddress for %s%s%s\n",
178 #ifdef AF_INET6
179 BIO_ADDRINFO_family(res) == AF_INET6 ? "IPv6 " :
180 #endif
181 BIO_ADDRINFO_family(res) == AF_INET ? "IPv4 " :
182 BIO_ADDRINFO_family(res) == AF_UNIX ? "unix " : "",
183 bindhost != NULL ? bindhost : "",
184 bindport != NULL ? ":" : "",
185 bindport != NULL ? bindport : "");
186 ERR_clear_error();
187 ret = 0;
188 }
189 ERR_print_errors(bio_err);
190 } else {
191 char *hostname = NULL;
192
193 hostname = BIO_ADDR_hostname_string(BIO_ADDRINFO_address(ai), 1);
194 if (hostname != NULL) {
195 BIO_printf(bio_out, "Connecting to %s\n", hostname);
196 OPENSSL_free(hostname);
197 }
198 /* Remove any stale errors from previous connection attempts */
199 ERR_clear_error();
200 ret = 1;
201 }
202 out:
203 if (bindaddr != NULL) {
204 BIO_ADDRINFO_free (bindaddr);
205 }
206 BIO_ADDRINFO_free(res);
207 return ret;
208 }
209
report_server_accept(BIO * out,int asock,int with_address,int with_pid)210 int report_server_accept(BIO *out, int asock, int with_address, int with_pid)
211 {
212 int success = 1;
213
214 if (BIO_printf(out, "ACCEPT") <= 0)
215 return 0;
216 if (with_address) {
217 union BIO_sock_info_u info;
218 char *hostname = NULL;
219 char *service = NULL;
220
221 if ((info.addr = BIO_ADDR_new()) != NULL
222 && BIO_sock_info(asock, BIO_SOCK_INFO_ADDRESS, &info)
223 && (hostname = BIO_ADDR_hostname_string(info.addr, 1)) != NULL
224 && (service = BIO_ADDR_service_string(info.addr, 1)) != NULL) {
225 success = BIO_printf(out,
226 strchr(hostname, ':') == NULL
227 ? /* IPv4 */ " %s:%s"
228 : /* IPv6 */ " [%s]:%s",
229 hostname, service) > 0;
230 } else {
231 (void)BIO_printf(out, "unknown:error\n");
232 success = 0;
233 }
234 OPENSSL_free(hostname);
235 OPENSSL_free(service);
236 BIO_ADDR_free(info.addr);
237 }
238 if (with_pid)
239 success = success && BIO_printf(out, " PID=%d", getpid()) > 0;
240 success = success && BIO_printf(out, "\n") > 0;
241 (void)BIO_flush(out);
242
243 return success;
244 }
245
246 /*
247 * do_server - helper routine to perform a server operation
248 * @accept_sock: pointer to storage of resulting socket.
249 * @host: the host name or path (for AF_UNIX) to connect to.
250 * @port: the port to connect to (ignored for AF_UNIX).
251 * @family: desired socket family, may be AF_INET, AF_INET6, AF_UNIX or
252 * AF_UNSPEC
253 * @type: socket type, must be SOCK_STREAM or SOCK_DGRAM
254 * @cb: pointer to a function that receives the accepted socket and
255 * should perform the communication with the connecting client.
256 * @context: pointer to memory that's passed verbatim to the cb function.
257 * @naccept: number of times an incoming connect should be accepted. If -1,
258 * unlimited number.
259 *
260 * This will create a socket and use it to listen to a host:port, or if
261 * family == AF_UNIX, to the path found in host, then start accepting
262 * incoming connections and run cb on the resulting socket.
263 *
264 * 0 on failure, something other on success.
265 */
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)266 int do_server(int *accept_sock, const char *host, const char *port,
267 int family, int type, int protocol, do_server_cb cb,
268 unsigned char *context, int naccept, BIO *bio_s_out)
269 {
270 int asock = 0;
271 int sock;
272 int i;
273 BIO_ADDRINFO *res = NULL;
274 const BIO_ADDRINFO *next;
275 int sock_family, sock_type, sock_protocol, sock_port;
276 const BIO_ADDR *sock_address;
277 int sock_family_fallback = AF_UNSPEC;
278 const BIO_ADDR *sock_address_fallback = NULL;
279 int sock_options = BIO_SOCK_REUSEADDR;
280 int ret = 0;
281
282 if (BIO_sock_init() != 1)
283 return 0;
284
285 if (!BIO_lookup_ex(host, port, BIO_LOOKUP_SERVER, family, type, protocol,
286 &res)) {
287 ERR_print_errors(bio_err);
288 return 0;
289 }
290
291 /* Admittedly, these checks are quite paranoid, we should not get
292 * anything in the BIO_ADDRINFO chain that we haven't asked for */
293 OPENSSL_assert((family == AF_UNSPEC || family == BIO_ADDRINFO_family(res))
294 && (type == 0 || type == BIO_ADDRINFO_socktype(res))
295 && (protocol == 0 || protocol == BIO_ADDRINFO_protocol(res)));
296
297 sock_family = BIO_ADDRINFO_family(res);
298 sock_type = BIO_ADDRINFO_socktype(res);
299 sock_protocol = BIO_ADDRINFO_protocol(res);
300 sock_address = BIO_ADDRINFO_address(res);
301 next = BIO_ADDRINFO_next(res);
302 #ifdef AF_INET6
303 if (sock_family == AF_INET6)
304 sock_options |= BIO_SOCK_V6_ONLY;
305 if (next != NULL
306 && BIO_ADDRINFO_socktype(next) == sock_type
307 && BIO_ADDRINFO_protocol(next) == sock_protocol) {
308 if (sock_family == AF_INET
309 && BIO_ADDRINFO_family(next) == AF_INET6) {
310 /* In case AF_INET6 is returned but not supported by the
311 * kernel, retry with the first detected address family */
312 sock_family_fallback = sock_family;
313 sock_address_fallback = sock_address;
314 sock_family = AF_INET6;
315 sock_address = BIO_ADDRINFO_address(next);
316 } else if (sock_family == AF_INET6
317 && BIO_ADDRINFO_family(next) == AF_INET) {
318 sock_options &= ~BIO_SOCK_V6_ONLY;
319 }
320 }
321 #endif
322
323 asock = BIO_socket(sock_family, sock_type, sock_protocol, 0);
324 if (asock == INVALID_SOCKET && sock_family_fallback != AF_UNSPEC) {
325 asock = BIO_socket(sock_family_fallback, sock_type, sock_protocol, 0);
326 sock_address = sock_address_fallback;
327 }
328 if (asock == INVALID_SOCKET
329 || !BIO_listen(asock, sock_address, sock_options)) {
330 BIO_ADDRINFO_free(res);
331 ERR_print_errors(bio_err);
332 if (asock != INVALID_SOCKET)
333 BIO_closesocket(asock);
334 goto end;
335 }
336
337 #ifndef OPENSSL_NO_SCTP
338 if (protocol == IPPROTO_SCTP) {
339 /*
340 * For SCTP we have to set various options on the socket prior to
341 * accepting. This is done automatically by BIO_new_dgram_sctp().
342 * We don't actually need the created BIO though so we free it again
343 * immediately.
344 */
345 BIO *tmpbio = BIO_new_dgram_sctp(asock, BIO_NOCLOSE);
346
347 if (tmpbio == NULL) {
348 BIO_closesocket(asock);
349 ERR_print_errors(bio_err);
350 goto end;
351 }
352 BIO_free(tmpbio);
353 }
354 #endif
355
356 sock_port = BIO_ADDR_rawport(sock_address);
357
358 BIO_ADDRINFO_free(res);
359 res = NULL;
360
361 if (!report_server_accept(bio_s_out, asock, sock_port == 0, 0)) {
362 BIO_closesocket(asock);
363 ERR_print_errors(bio_err);
364 goto end;
365 }
366
367 if (accept_sock != NULL)
368 *accept_sock = asock;
369 for (;;) {
370 char sink[64];
371 struct timeval timeout;
372 fd_set readfds;
373
374 if (type == SOCK_STREAM) {
375 BIO_ADDR_free(ourpeer);
376 ourpeer = BIO_ADDR_new();
377 if (ourpeer == NULL) {
378 BIO_closesocket(asock);
379 ERR_print_errors(bio_err);
380 goto end;
381 }
382 do {
383 sock = BIO_accept_ex(asock, ourpeer, 0);
384 } while (sock < 0 && BIO_sock_should_retry(sock));
385 if (sock < 0) {
386 ERR_print_errors(bio_err);
387 BIO_closesocket(asock);
388 break;
389 }
390 BIO_set_tcp_ndelay(sock, 1);
391 i = (*cb)(sock, type, protocol, context);
392
393 /*
394 * If we ended with an alert being sent, but still with data in the
395 * network buffer to be read, then calling BIO_closesocket() will
396 * result in a TCP-RST being sent. On some platforms (notably
397 * Windows) then this will result in the peer immediately abandoning
398 * the connection including any buffered alert data before it has
399 * had a chance to be read. Shutting down the sending side first,
400 * and then closing the socket sends TCP-FIN first followed by
401 * TCP-RST. This seems to allow the peer to read the alert data.
402 */
403 shutdown(sock, 1); /* SHUT_WR */
404 /*
405 * We just said we have nothing else to say, but it doesn't mean
406 * that the other side has nothing. It's even recommended to
407 * consume incoming data. [In testing context this ensures that
408 * alerts are passed on...]
409 */
410 timeout.tv_sec = 0;
411 timeout.tv_usec = 500000; /* some extreme round-trip */
412 do {
413 FD_ZERO(&readfds);
414 openssl_fdset(sock, &readfds);
415 } while (select(sock + 1, &readfds, NULL, NULL, &timeout) > 0
416 && readsocket(sock, sink, sizeof(sink)) > 0);
417
418 BIO_closesocket(sock);
419 } else {
420 i = (*cb)(asock, type, protocol, context);
421 }
422
423 if (naccept != -1)
424 naccept--;
425 if (i < 0 || naccept == 0) {
426 BIO_closesocket(asock);
427 ret = i;
428 break;
429 }
430 }
431 end:
432 # ifdef AF_UNIX
433 if (family == AF_UNIX)
434 unlink(host);
435 # endif
436 BIO_ADDR_free(ourpeer);
437 ourpeer = NULL;
438 return ret;
439 }
440
do_ssl_shutdown(SSL * ssl)441 void do_ssl_shutdown(SSL *ssl)
442 {
443 int ret;
444
445 do {
446 /* We only do unidirectional shutdown */
447 ret = SSL_shutdown(ssl);
448 if (ret < 0) {
449 switch (SSL_get_error(ssl, ret)) {
450 case SSL_ERROR_WANT_READ:
451 case SSL_ERROR_WANT_WRITE:
452 case SSL_ERROR_WANT_ASYNC:
453 case SSL_ERROR_WANT_ASYNC_JOB:
454 /* We just do busy waiting. Nothing clever */
455 continue;
456 }
457 ret = 0;
458 }
459 } while (ret < 0);
460 }
461
462 #endif /* OPENSSL_NO_SOCK */
463