1 /* 2 * TCP/IP or UDP/IP networking functions 3 * 4 * Copyright The Mbed TLS Contributors 5 * SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later 6 */ 7 8 /* Enable definition of getaddrinfo() even when compiling with -std=c99. Must 9 * be set before mbedtls_config.h, which pulls in glibc's features.h indirectly. 10 * Harmless on other platforms. */ 11 #ifndef _POSIX_C_SOURCE 12 #define _POSIX_C_SOURCE 200112L 13 #endif 14 #ifndef _XOPEN_SOURCE 15 #define _XOPEN_SOURCE 600 /* sockaddr_storage */ 16 #endif 17 18 #include "common.h" 19 20 #if defined(MBEDTLS_NET_C) 21 22 #if !defined(unix) && !defined(__unix__) && !defined(__unix) && \ 23 !defined(__APPLE__) && !defined(_WIN32) && !defined(__QNXNTO__) && \ 24 !defined(__HAIKU__) && !defined(__midipix__) 25 #error "This module only works on Unix and Windows, see MBEDTLS_NET_C in mbedtls_config.h" 26 #endif 27 28 #include "mbedtls/platform.h" 29 30 #include "mbedtls/net_sockets.h" 31 #include "mbedtls/error.h" 32 33 #include <string.h> 34 35 #if (defined(_WIN32) || defined(_WIN32_WCE)) && !defined(EFIX64) && \ 36 !defined(EFI32) 37 38 #define IS_EINTR(ret) ((ret) == WSAEINTR) 39 40 #include <ws2tcpip.h> 41 42 #include <winsock2.h> 43 #include <windows.h> 44 #if (_WIN32_WINNT < 0x0501) 45 #include <wspiapi.h> 46 #endif 47 48 #if defined(_MSC_VER) 49 #if defined(_WIN32_WCE) 50 #pragma comment( lib, "ws2.lib" ) 51 #else 52 #pragma comment( lib, "ws2_32.lib" ) 53 #endif 54 #endif /* _MSC_VER */ 55 56 #define read(fd, buf, len) recv(fd, (char *) (buf), (int) (len), 0) 57 #define write(fd, buf, len) send(fd, (char *) (buf), (int) (len), 0) 58 #define close(fd) closesocket(fd) 59 60 static int wsa_init_done = 0; 61 62 #else /* ( _WIN32 || _WIN32_WCE ) && !EFIX64 && !EFI32 */ 63 64 #include <sys/types.h> 65 #include <sys/socket.h> 66 #include <netinet/in.h> 67 #include <arpa/inet.h> 68 #include <sys/time.h> 69 #include <unistd.h> 70 #include <signal.h> 71 #include <fcntl.h> 72 #include <netdb.h> 73 #include <errno.h> 74 75 #define IS_EINTR(ret) ((ret) == EINTR) 76 #define SOCKET int 77 78 #endif /* ( _WIN32 || _WIN32_WCE ) && !EFIX64 && !EFI32 */ 79 80 /* Some MS functions want int and MSVC warns if we pass size_t, 81 * but the standard functions use socklen_t, so cast only for MSVC */ 82 #if defined(_MSC_VER) 83 #define MSVC_INT_CAST (int) 84 #else 85 #define MSVC_INT_CAST 86 #endif 87 88 #include <stdio.h> 89 90 #if defined(MBEDTLS_HAVE_TIME) 91 #include <time.h> 92 #endif 93 94 #include <stdint.h> 95 96 /* 97 * Prepare for using the sockets interface 98 */ 99 static int net_prepare(void) 100 { 101 #if (defined(_WIN32) || defined(_WIN32_WCE)) && !defined(EFIX64) && \ 102 !defined(EFI32) 103 WSADATA wsaData; 104 105 if (wsa_init_done == 0) { 106 if (WSAStartup(MAKEWORD(2, 0), &wsaData) != 0) { 107 return MBEDTLS_ERR_NET_SOCKET_FAILED; 108 } 109 110 wsa_init_done = 1; 111 } 112 #else 113 #if !defined(EFIX64) && !defined(EFI32) 114 signal(SIGPIPE, SIG_IGN); 115 #endif 116 #endif 117 return 0; 118 } 119 120 /* 121 * Return 0 if the file descriptor is valid, an error otherwise. 122 * If for_select != 0, check whether the file descriptor is within the range 123 * allowed for fd_set used for the FD_xxx macros and the select() function. 124 */ 125 static int check_fd(int fd, int for_select) 126 { 127 if (fd < 0) { 128 return MBEDTLS_ERR_NET_INVALID_CONTEXT; 129 } 130 131 #if (defined(_WIN32) || defined(_WIN32_WCE)) && !defined(EFIX64) && \ 132 !defined(EFI32) 133 (void) for_select; 134 #else 135 /* A limitation of select() is that it only works with file descriptors 136 * that are strictly less than FD_SETSIZE. This is a limitation of the 137 * fd_set type. Error out early, because attempting to call FD_SET on a 138 * large file descriptor is a buffer overflow on typical platforms. */ 139 if (for_select && fd >= FD_SETSIZE) { 140 return MBEDTLS_ERR_NET_POLL_FAILED; 141 } 142 #endif 143 144 return 0; 145 } 146 147 /* 148 * Initialize a context 149 */ 150 void mbedtls_net_init(mbedtls_net_context *ctx) 151 { 152 ctx->fd = -1; 153 } 154 155 /* 156 * Initiate a TCP connection with host:port and the given protocol 157 */ 158 int mbedtls_net_connect(mbedtls_net_context *ctx, const char *host, 159 const char *port, int proto) 160 { 161 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; 162 struct addrinfo hints, *addr_list, *cur; 163 164 if ((ret = net_prepare()) != 0) { 165 return ret; 166 } 167 168 /* Do name resolution with both IPv6 and IPv4 */ 169 memset(&hints, 0, sizeof(hints)); 170 hints.ai_family = AF_UNSPEC; 171 hints.ai_socktype = proto == MBEDTLS_NET_PROTO_UDP ? SOCK_DGRAM : SOCK_STREAM; 172 hints.ai_protocol = proto == MBEDTLS_NET_PROTO_UDP ? IPPROTO_UDP : IPPROTO_TCP; 173 174 if (getaddrinfo(host, port, &hints, &addr_list) != 0) { 175 return MBEDTLS_ERR_NET_UNKNOWN_HOST; 176 } 177 178 /* Try the sockaddrs until a connection succeeds */ 179 ret = MBEDTLS_ERR_NET_UNKNOWN_HOST; 180 for (cur = addr_list; cur != NULL; cur = cur->ai_next) { 181 ctx->fd = (int) socket(cur->ai_family, cur->ai_socktype, 182 cur->ai_protocol); 183 if (ctx->fd < 0) { 184 ret = MBEDTLS_ERR_NET_SOCKET_FAILED; 185 continue; 186 } 187 188 if (connect(ctx->fd, cur->ai_addr, MSVC_INT_CAST cur->ai_addrlen) == 0) { 189 ret = 0; 190 break; 191 } 192 193 close(ctx->fd); 194 ret = MBEDTLS_ERR_NET_CONNECT_FAILED; 195 } 196 197 freeaddrinfo(addr_list); 198 199 return ret; 200 } 201 202 /* 203 * Create a listening socket on bind_ip:port 204 */ 205 int mbedtls_net_bind(mbedtls_net_context *ctx, const char *bind_ip, const char *port, int proto) 206 { 207 int n, ret; 208 struct addrinfo hints, *addr_list, *cur; 209 210 if ((ret = net_prepare()) != 0) { 211 return ret; 212 } 213 214 /* Bind to IPv6 and/or IPv4, but only in the desired protocol */ 215 memset(&hints, 0, sizeof(hints)); 216 hints.ai_family = AF_UNSPEC; 217 hints.ai_socktype = proto == MBEDTLS_NET_PROTO_UDP ? SOCK_DGRAM : SOCK_STREAM; 218 hints.ai_protocol = proto == MBEDTLS_NET_PROTO_UDP ? IPPROTO_UDP : IPPROTO_TCP; 219 if (bind_ip == NULL) { 220 hints.ai_flags = AI_PASSIVE; 221 } 222 223 if (getaddrinfo(bind_ip, port, &hints, &addr_list) != 0) { 224 return MBEDTLS_ERR_NET_UNKNOWN_HOST; 225 } 226 227 /* Try the sockaddrs until a binding succeeds */ 228 ret = MBEDTLS_ERR_NET_UNKNOWN_HOST; 229 for (cur = addr_list; cur != NULL; cur = cur->ai_next) { 230 ctx->fd = (int) socket(cur->ai_family, cur->ai_socktype, 231 cur->ai_protocol); 232 if (ctx->fd < 0) { 233 ret = MBEDTLS_ERR_NET_SOCKET_FAILED; 234 continue; 235 } 236 237 n = 1; 238 if (setsockopt(ctx->fd, SOL_SOCKET, SO_REUSEADDR, 239 (const char *) &n, sizeof(n)) != 0) { 240 close(ctx->fd); 241 ret = MBEDTLS_ERR_NET_SOCKET_FAILED; 242 continue; 243 } 244 245 if (bind(ctx->fd, cur->ai_addr, MSVC_INT_CAST cur->ai_addrlen) != 0) { 246 close(ctx->fd); 247 ret = MBEDTLS_ERR_NET_BIND_FAILED; 248 continue; 249 } 250 251 /* Listen only makes sense for TCP */ 252 if (proto == MBEDTLS_NET_PROTO_TCP) { 253 if (listen(ctx->fd, MBEDTLS_NET_LISTEN_BACKLOG) != 0) { 254 close(ctx->fd); 255 ret = MBEDTLS_ERR_NET_LISTEN_FAILED; 256 continue; 257 } 258 } 259 260 /* Bind was successful */ 261 ret = 0; 262 break; 263 } 264 265 freeaddrinfo(addr_list); 266 267 return ret; 268 269 } 270 271 #if (defined(_WIN32) || defined(_WIN32_WCE)) && !defined(EFIX64) && \ 272 !defined(EFI32) 273 /* 274 * Check if the requested operation would be blocking on a non-blocking socket 275 * and thus 'failed' with a negative return value. 276 */ 277 static int net_would_block(const mbedtls_net_context *ctx) 278 { 279 ((void) ctx); 280 return WSAGetLastError() == WSAEWOULDBLOCK; 281 } 282 #else 283 /* 284 * Check if the requested operation would be blocking on a non-blocking socket 285 * and thus 'failed' with a negative return value. 286 * 287 * Note: on a blocking socket this function always returns 0! 288 */ 289 static int net_would_block(const mbedtls_net_context *ctx) 290 { 291 int err = errno; 292 293 /* 294 * Never return 'WOULD BLOCK' on a blocking socket 295 */ 296 if ((fcntl(ctx->fd, F_GETFL) & O_NONBLOCK) != O_NONBLOCK) { 297 errno = err; 298 return 0; 299 } 300 301 switch (errno = err) { 302 #if defined EAGAIN 303 case EAGAIN: 304 #endif 305 #if defined EWOULDBLOCK && EWOULDBLOCK != EAGAIN 306 case EWOULDBLOCK: 307 #endif 308 return 1; 309 } 310 return 0; 311 } 312 #endif /* ( _WIN32 || _WIN32_WCE ) && !EFIX64 && !EFI32 */ 313 314 /* 315 * Accept a connection from a remote client 316 */ 317 int mbedtls_net_accept(mbedtls_net_context *bind_ctx, 318 mbedtls_net_context *client_ctx, 319 void *client_ip, size_t buf_size, size_t *cip_len) 320 { 321 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; 322 int type; 323 324 struct sockaddr_storage client_addr; 325 326 #if defined(__socklen_t_defined) || defined(_SOCKLEN_T) || \ 327 defined(_SOCKLEN_T_DECLARED) || defined(__DEFINED_socklen_t) || \ 328 defined(socklen_t) || (defined(_POSIX_VERSION) && _POSIX_VERSION >= 200112L) 329 socklen_t n = (socklen_t) sizeof(client_addr); 330 socklen_t type_len = (socklen_t) sizeof(type); 331 #else 332 int n = (int) sizeof(client_addr); 333 int type_len = (int) sizeof(type); 334 #endif 335 336 /* Is this a TCP or UDP socket? */ 337 if (getsockopt(bind_ctx->fd, SOL_SOCKET, SO_TYPE, 338 (void *) &type, &type_len) != 0 || 339 (type != SOCK_STREAM && type != SOCK_DGRAM)) { 340 return MBEDTLS_ERR_NET_ACCEPT_FAILED; 341 } 342 343 if (type == SOCK_STREAM) { 344 /* TCP: actual accept() */ 345 ret = client_ctx->fd = (int) accept(bind_ctx->fd, 346 (struct sockaddr *) &client_addr, &n); 347 } else { 348 /* UDP: wait for a message, but keep it in the queue */ 349 char buf[1] = { 0 }; 350 351 ret = (int) recvfrom(bind_ctx->fd, buf, sizeof(buf), MSG_PEEK, 352 (struct sockaddr *) &client_addr, &n); 353 354 #if defined(_WIN32) 355 if (ret == SOCKET_ERROR && 356 WSAGetLastError() == WSAEMSGSIZE) { 357 /* We know buf is too small, thanks, just peeking here */ 358 ret = 0; 359 } 360 #endif 361 } 362 363 if (ret < 0) { 364 if (net_would_block(bind_ctx) != 0) { 365 return MBEDTLS_ERR_SSL_WANT_READ; 366 } 367 368 return MBEDTLS_ERR_NET_ACCEPT_FAILED; 369 } 370 371 /* UDP: hijack the listening socket to communicate with the client, 372 * then bind a new socket to accept new connections */ 373 if (type != SOCK_STREAM) { 374 struct sockaddr_storage local_addr; 375 int one = 1; 376 377 if (connect(bind_ctx->fd, (struct sockaddr *) &client_addr, n) != 0) { 378 return MBEDTLS_ERR_NET_ACCEPT_FAILED; 379 } 380 381 client_ctx->fd = bind_ctx->fd; 382 bind_ctx->fd = -1; /* In case we exit early */ 383 384 n = sizeof(struct sockaddr_storage); 385 if (getsockname(client_ctx->fd, 386 (struct sockaddr *) &local_addr, &n) != 0 || 387 (bind_ctx->fd = (int) socket(local_addr.ss_family, 388 SOCK_DGRAM, IPPROTO_UDP)) < 0 || 389 setsockopt(bind_ctx->fd, SOL_SOCKET, SO_REUSEADDR, 390 (const char *) &one, sizeof(one)) != 0) { 391 return MBEDTLS_ERR_NET_SOCKET_FAILED; 392 } 393 394 if (bind(bind_ctx->fd, (struct sockaddr *) &local_addr, n) != 0) { 395 return MBEDTLS_ERR_NET_BIND_FAILED; 396 } 397 } 398 399 if (client_ip != NULL) { 400 if (client_addr.ss_family == AF_INET) { 401 struct sockaddr_in *addr4 = (struct sockaddr_in *) &client_addr; 402 *cip_len = sizeof(addr4->sin_addr.s_addr); 403 404 if (buf_size < *cip_len) { 405 return MBEDTLS_ERR_NET_BUFFER_TOO_SMALL; 406 } 407 408 memcpy(client_ip, &addr4->sin_addr.s_addr, *cip_len); 409 } else { 410 struct sockaddr_in6 *addr6 = (struct sockaddr_in6 *) &client_addr; 411 *cip_len = sizeof(addr6->sin6_addr.s6_addr); 412 413 if (buf_size < *cip_len) { 414 return MBEDTLS_ERR_NET_BUFFER_TOO_SMALL; 415 } 416 417 memcpy(client_ip, &addr6->sin6_addr.s6_addr, *cip_len); 418 } 419 } 420 421 return 0; 422 } 423 424 /* 425 * Set the socket blocking or non-blocking 426 */ 427 int mbedtls_net_set_block(mbedtls_net_context *ctx) 428 { 429 #if (defined(_WIN32) || defined(_WIN32_WCE)) && !defined(EFIX64) && \ 430 !defined(EFI32) 431 u_long n = 0; 432 return ioctlsocket(ctx->fd, FIONBIO, &n); 433 #else 434 return fcntl(ctx->fd, F_SETFL, fcntl(ctx->fd, F_GETFL) & ~O_NONBLOCK); 435 #endif 436 } 437 438 int mbedtls_net_set_nonblock(mbedtls_net_context *ctx) 439 { 440 #if (defined(_WIN32) || defined(_WIN32_WCE)) && !defined(EFIX64) && \ 441 !defined(EFI32) 442 u_long n = 1; 443 return ioctlsocket(ctx->fd, FIONBIO, &n); 444 #else 445 return fcntl(ctx->fd, F_SETFL, fcntl(ctx->fd, F_GETFL) | O_NONBLOCK); 446 #endif 447 } 448 449 /* 450 * Check if data is available on the socket 451 */ 452 453 int mbedtls_net_poll(mbedtls_net_context *ctx, uint32_t rw, uint32_t timeout) 454 { 455 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; 456 struct timeval tv; 457 458 fd_set read_fds; 459 fd_set write_fds; 460 461 int fd = ctx->fd; 462 463 ret = check_fd(fd, 1); 464 if (ret != 0) { 465 return ret; 466 } 467 468 #if defined(__has_feature) 469 #if __has_feature(memory_sanitizer) 470 /* Ensure that memory sanitizers consider read_fds and write_fds as 471 * initialized even on platforms such as Glibc/x86_64 where FD_ZERO 472 * is implemented in assembly. */ 473 memset(&read_fds, 0, sizeof(read_fds)); 474 memset(&write_fds, 0, sizeof(write_fds)); 475 #endif 476 #endif 477 478 FD_ZERO(&read_fds); 479 if (rw & MBEDTLS_NET_POLL_READ) { 480 rw &= ~MBEDTLS_NET_POLL_READ; 481 FD_SET((SOCKET) fd, &read_fds); 482 } 483 484 FD_ZERO(&write_fds); 485 if (rw & MBEDTLS_NET_POLL_WRITE) { 486 rw &= ~MBEDTLS_NET_POLL_WRITE; 487 FD_SET((SOCKET) fd, &write_fds); 488 } 489 490 if (rw != 0) { 491 return MBEDTLS_ERR_NET_BAD_INPUT_DATA; 492 } 493 494 tv.tv_sec = timeout / 1000; 495 tv.tv_usec = (timeout % 1000) * 1000; 496 497 do { 498 ret = select(fd + 1, &read_fds, &write_fds, NULL, 499 timeout == (uint32_t) -1 ? NULL : &tv); 500 } while (IS_EINTR(ret)); 501 502 if (ret < 0) { 503 return MBEDTLS_ERR_NET_POLL_FAILED; 504 } 505 506 ret = 0; 507 if (FD_ISSET(fd, &read_fds)) { 508 ret |= MBEDTLS_NET_POLL_READ; 509 } 510 if (FD_ISSET(fd, &write_fds)) { 511 ret |= MBEDTLS_NET_POLL_WRITE; 512 } 513 514 return ret; 515 } 516 517 /* 518 * Portable usleep helper 519 */ 520 void mbedtls_net_usleep(unsigned long usec) 521 { 522 #if defined(_WIN32) 523 Sleep((usec + 999) / 1000); 524 #else 525 struct timeval tv; 526 tv.tv_sec = usec / 1000000; 527 #if defined(__unix__) || defined(__unix) || \ 528 (defined(__APPLE__) && defined(__MACH__)) 529 tv.tv_usec = (suseconds_t) usec % 1000000; 530 #else 531 tv.tv_usec = usec % 1000000; 532 #endif 533 select(0, NULL, NULL, NULL, &tv); 534 #endif 535 } 536 537 /* 538 * Read at most 'len' characters 539 */ 540 int mbedtls_net_recv(void *ctx, unsigned char *buf, size_t len) 541 { 542 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; 543 int fd = ((mbedtls_net_context *) ctx)->fd; 544 545 ret = check_fd(fd, 0); 546 if (ret != 0) { 547 return ret; 548 } 549 550 ret = (int) read(fd, buf, len); 551 552 if (ret < 0) { 553 if (net_would_block(ctx) != 0) { 554 return MBEDTLS_ERR_SSL_WANT_READ; 555 } 556 557 #if (defined(_WIN32) || defined(_WIN32_WCE)) && !defined(EFIX64) && \ 558 !defined(EFI32) 559 if (WSAGetLastError() == WSAECONNRESET) { 560 return MBEDTLS_ERR_NET_CONN_RESET; 561 } 562 #else 563 if (errno == EPIPE || errno == ECONNRESET) { 564 return MBEDTLS_ERR_NET_CONN_RESET; 565 } 566 567 if (errno == EINTR) { 568 return MBEDTLS_ERR_SSL_WANT_READ; 569 } 570 #endif 571 572 return MBEDTLS_ERR_NET_RECV_FAILED; 573 } 574 575 return ret; 576 } 577 578 /* 579 * Read at most 'len' characters, blocking for at most 'timeout' ms 580 */ 581 int mbedtls_net_recv_timeout(void *ctx, unsigned char *buf, 582 size_t len, uint32_t timeout) 583 { 584 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; 585 struct timeval tv; 586 fd_set read_fds; 587 int fd = ((mbedtls_net_context *) ctx)->fd; 588 589 ret = check_fd(fd, 1); 590 if (ret != 0) { 591 return ret; 592 } 593 594 FD_ZERO(&read_fds); 595 FD_SET((SOCKET) fd, &read_fds); 596 597 tv.tv_sec = timeout / 1000; 598 tv.tv_usec = (timeout % 1000) * 1000; 599 600 ret = select(fd + 1, &read_fds, NULL, NULL, timeout == 0 ? NULL : &tv); 601 602 /* Zero fds ready means we timed out */ 603 if (ret == 0) { 604 return MBEDTLS_ERR_SSL_TIMEOUT; 605 } 606 607 if (ret < 0) { 608 #if (defined(_WIN32) || defined(_WIN32_WCE)) && !defined(EFIX64) && \ 609 !defined(EFI32) 610 if (WSAGetLastError() == WSAEINTR) { 611 return MBEDTLS_ERR_SSL_WANT_READ; 612 } 613 #else 614 if (errno == EINTR) { 615 return MBEDTLS_ERR_SSL_WANT_READ; 616 } 617 #endif 618 619 return MBEDTLS_ERR_NET_RECV_FAILED; 620 } 621 622 /* This call will not block */ 623 return mbedtls_net_recv(ctx, buf, len); 624 } 625 626 /* 627 * Write at most 'len' characters 628 */ 629 int mbedtls_net_send(void *ctx, const unsigned char *buf, size_t len) 630 { 631 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; 632 int fd = ((mbedtls_net_context *) ctx)->fd; 633 634 ret = check_fd(fd, 0); 635 if (ret != 0) { 636 return ret; 637 } 638 639 ret = (int) write(fd, buf, len); 640 641 if (ret < 0) { 642 if (net_would_block(ctx) != 0) { 643 return MBEDTLS_ERR_SSL_WANT_WRITE; 644 } 645 646 #if (defined(_WIN32) || defined(_WIN32_WCE)) && !defined(EFIX64) && \ 647 !defined(EFI32) 648 if (WSAGetLastError() == WSAECONNRESET) { 649 return MBEDTLS_ERR_NET_CONN_RESET; 650 } 651 #else 652 if (errno == EPIPE || errno == ECONNRESET) { 653 return MBEDTLS_ERR_NET_CONN_RESET; 654 } 655 656 if (errno == EINTR) { 657 return MBEDTLS_ERR_SSL_WANT_WRITE; 658 } 659 #endif 660 661 return MBEDTLS_ERR_NET_SEND_FAILED; 662 } 663 664 return ret; 665 } 666 667 /* 668 * Close the connection 669 */ 670 void mbedtls_net_close(mbedtls_net_context *ctx) 671 { 672 if (ctx->fd == -1) { 673 return; 674 } 675 676 close(ctx->fd); 677 678 ctx->fd = -1; 679 } 680 681 /* 682 * Gracefully close the connection 683 */ 684 void mbedtls_net_free(mbedtls_net_context *ctx) 685 { 686 if (ctx == NULL || ctx->fd == -1) { 687 return; 688 } 689 690 shutdown(ctx->fd, 2); 691 close(ctx->fd); 692 693 ctx->fd = -1; 694 } 695 696 #endif /* MBEDTLS_NET_C */ 697