1 /* $OpenBSD: misc.c,v 1.107 2016/11/30 00:28:31 dtucker Exp $ */ 2 /* 3 * Copyright (c) 2000 Markus Friedl. All rights reserved. 4 * Copyright (c) 2005,2006 Damien Miller. All rights reserved. 5 * 6 * Redistribution and use in source and binary forms, with or without 7 * modification, are permitted provided that the following conditions 8 * are met: 9 * 1. Redistributions of source code must retain the above copyright 10 * notice, this list of conditions and the following disclaimer. 11 * 2. Redistributions in binary form must reproduce the above copyright 12 * notice, this list of conditions and the following disclaimer in the 13 * documentation and/or other materials provided with the distribution. 14 * 15 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR 16 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES 17 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. 18 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, 19 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT 20 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 21 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 22 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 23 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF 24 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 25 */ 26 27 #include "includes.h" 28 29 #include <sys/types.h> 30 #include <sys/ioctl.h> 31 #include <sys/socket.h> 32 #include <sys/sysctl.h> 33 #include <sys/time.h> 34 #include <sys/un.h> 35 36 #include <limits.h> 37 #include <stdarg.h> 38 #include <stdio.h> 39 #include <stdlib.h> 40 #include <string.h> 41 #include <time.h> 42 #include <unistd.h> 43 44 #include <netinet/in.h> 45 #include <netinet/in_systm.h> 46 #include <netinet/ip.h> 47 #include <netinet/tcp.h> 48 49 #include <ctype.h> 50 #include <errno.h> 51 #include <fcntl.h> 52 #include <netdb.h> 53 #ifdef HAVE_PATHS_H 54 # include <paths.h> 55 #include <pwd.h> 56 #endif 57 #ifdef SSH_TUN_OPENBSD 58 #include <net/if.h> 59 #endif 60 61 #include "xmalloc.h" 62 #include "misc.h" 63 #include "log.h" 64 #include "ssh.h" 65 66 /* remove newline at end of string */ 67 char * 68 chop(char *s) 69 { 70 char *t = s; 71 while (*t) { 72 if (*t == '\n' || *t == '\r') { 73 *t = '\0'; 74 return s; 75 } 76 t++; 77 } 78 return s; 79 80 } 81 82 /* set/unset filedescriptor to non-blocking */ 83 int 84 set_nonblock(int fd) 85 { 86 int val; 87 88 val = fcntl(fd, F_GETFL); 89 if (val < 0) { 90 error("fcntl(%d, F_GETFL): %s", fd, strerror(errno)); 91 return (-1); 92 } 93 if (val & O_NONBLOCK) { 94 debug3("fd %d is O_NONBLOCK", fd); 95 return (0); 96 } 97 debug2("fd %d setting O_NONBLOCK", fd); 98 val |= O_NONBLOCK; 99 if (fcntl(fd, F_SETFL, val) == -1) { 100 debug("fcntl(%d, F_SETFL, O_NONBLOCK): %s", fd, 101 strerror(errno)); 102 return (-1); 103 } 104 return (0); 105 } 106 107 int 108 unset_nonblock(int fd) 109 { 110 int val; 111 112 val = fcntl(fd, F_GETFL); 113 if (val < 0) { 114 error("fcntl(%d, F_GETFL): %s", fd, strerror(errno)); 115 return (-1); 116 } 117 if (!(val & O_NONBLOCK)) { 118 debug3("fd %d is not O_NONBLOCK", fd); 119 return (0); 120 } 121 debug("fd %d clearing O_NONBLOCK", fd); 122 val &= ~O_NONBLOCK; 123 if (fcntl(fd, F_SETFL, val) == -1) { 124 debug("fcntl(%d, F_SETFL, ~O_NONBLOCK): %s", 125 fd, strerror(errno)); 126 return (-1); 127 } 128 return (0); 129 } 130 131 const char * 132 ssh_gai_strerror(int gaierr) 133 { 134 if (gaierr == EAI_SYSTEM && errno != 0) 135 return strerror(errno); 136 return gai_strerror(gaierr); 137 } 138 139 /* disable nagle on socket */ 140 void 141 set_nodelay(int fd) 142 { 143 int opt; 144 socklen_t optlen; 145 146 optlen = sizeof opt; 147 if (getsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &opt, &optlen) == -1) { 148 debug("getsockopt TCP_NODELAY: %.100s", strerror(errno)); 149 return; 150 } 151 if (opt == 1) { 152 debug2("fd %d is TCP_NODELAY", fd); 153 return; 154 } 155 opt = 1; 156 debug2("fd %d setting TCP_NODELAY", fd); 157 if (setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &opt, sizeof opt) == -1) 158 error("setsockopt TCP_NODELAY: %.100s", strerror(errno)); 159 } 160 161 /* Characters considered whitespace in strsep calls. */ 162 #define WHITESPACE " \t\r\n" 163 #define QUOTE "\"" 164 165 /* return next token in configuration line */ 166 char * 167 strdelim(char **s) 168 { 169 char *old; 170 int wspace = 0; 171 172 if (*s == NULL) 173 return NULL; 174 175 old = *s; 176 177 *s = strpbrk(*s, WHITESPACE QUOTE "="); 178 if (*s == NULL) 179 return (old); 180 181 if (*s[0] == '\"') { 182 memmove(*s, *s + 1, strlen(*s)); /* move nul too */ 183 /* Find matching quote */ 184 if ((*s = strpbrk(*s, QUOTE)) == NULL) { 185 return (NULL); /* no matching quote */ 186 } else { 187 *s[0] = '\0'; 188 *s += strspn(*s + 1, WHITESPACE) + 1; 189 return (old); 190 } 191 } 192 193 /* Allow only one '=' to be skipped */ 194 if (*s[0] == '=') 195 wspace = 1; 196 *s[0] = '\0'; 197 198 /* Skip any extra whitespace after first token */ 199 *s += strspn(*s + 1, WHITESPACE) + 1; 200 if (*s[0] == '=' && !wspace) 201 *s += strspn(*s + 1, WHITESPACE) + 1; 202 203 return (old); 204 } 205 206 struct passwd * 207 pwcopy(struct passwd *pw) 208 { 209 struct passwd *copy = xcalloc(1, sizeof(*copy)); 210 211 copy->pw_name = xstrdup(pw->pw_name); 212 copy->pw_passwd = xstrdup(pw->pw_passwd); 213 #ifdef HAVE_STRUCT_PASSWD_PW_GECOS 214 copy->pw_gecos = xstrdup(pw->pw_gecos); 215 #endif 216 copy->pw_uid = pw->pw_uid; 217 copy->pw_gid = pw->pw_gid; 218 #ifdef HAVE_STRUCT_PASSWD_PW_EXPIRE 219 copy->pw_expire = pw->pw_expire; 220 #endif 221 #ifdef HAVE_STRUCT_PASSWD_PW_CHANGE 222 copy->pw_change = pw->pw_change; 223 #endif 224 #ifdef HAVE_STRUCT_PASSWD_PW_CLASS 225 copy->pw_class = xstrdup(pw->pw_class); 226 #endif 227 copy->pw_dir = xstrdup(pw->pw_dir); 228 copy->pw_shell = xstrdup(pw->pw_shell); 229 return copy; 230 } 231 232 /* 233 * Convert ASCII string to TCP/IP port number. 234 * Port must be >=0 and <=65535. 235 * Return -1 if invalid. 236 */ 237 int 238 a2port(const char *s) 239 { 240 long long port; 241 const char *errstr; 242 243 port = strtonum(s, 0, 65535, &errstr); 244 if (errstr != NULL) 245 return -1; 246 return (int)port; 247 } 248 249 int 250 a2tun(const char *s, int *remote) 251 { 252 const char *errstr = NULL; 253 char *sp, *ep; 254 int tun; 255 256 if (remote != NULL) { 257 *remote = SSH_TUNID_ANY; 258 sp = xstrdup(s); 259 if ((ep = strchr(sp, ':')) == NULL) { 260 free(sp); 261 return (a2tun(s, NULL)); 262 } 263 ep[0] = '\0'; ep++; 264 *remote = a2tun(ep, NULL); 265 tun = a2tun(sp, NULL); 266 free(sp); 267 return (*remote == SSH_TUNID_ERR ? *remote : tun); 268 } 269 270 if (strcasecmp(s, "any") == 0) 271 return (SSH_TUNID_ANY); 272 273 tun = strtonum(s, 0, SSH_TUNID_MAX, &errstr); 274 if (errstr != NULL) 275 return (SSH_TUNID_ERR); 276 277 return (tun); 278 } 279 280 #define SECONDS 1 281 #define MINUTES (SECONDS * 60) 282 #define HOURS (MINUTES * 60) 283 #define DAYS (HOURS * 24) 284 #define WEEKS (DAYS * 7) 285 286 /* 287 * Convert a time string into seconds; format is 288 * a sequence of: 289 * time[qualifier] 290 * 291 * Valid time qualifiers are: 292 * <none> seconds 293 * s|S seconds 294 * m|M minutes 295 * h|H hours 296 * d|D days 297 * w|W weeks 298 * 299 * Examples: 300 * 90m 90 minutes 301 * 1h30m 90 minutes 302 * 2d 2 days 303 * 1w 1 week 304 * 305 * Return -1 if time string is invalid. 306 */ 307 long 308 convtime(const char *s) 309 { 310 long total, secs; 311 const char *p; 312 char *endp; 313 314 errno = 0; 315 total = 0; 316 p = s; 317 318 if (p == NULL || *p == '\0') 319 return -1; 320 321 while (*p) { 322 secs = strtol(p, &endp, 10); 323 if (p == endp || 324 (errno == ERANGE && (secs == LONG_MIN || secs == LONG_MAX)) || 325 secs < 0) 326 return -1; 327 328 switch (*endp++) { 329 case '\0': 330 endp--; 331 break; 332 case 's': 333 case 'S': 334 break; 335 case 'm': 336 case 'M': 337 secs *= MINUTES; 338 break; 339 case 'h': 340 case 'H': 341 secs *= HOURS; 342 break; 343 case 'd': 344 case 'D': 345 secs *= DAYS; 346 break; 347 case 'w': 348 case 'W': 349 secs *= WEEKS; 350 break; 351 default: 352 return -1; 353 } 354 total += secs; 355 if (total < 0) 356 return -1; 357 p = endp; 358 } 359 360 return total; 361 } 362 363 /* 364 * Returns a standardized host+port identifier string. 365 * Caller must free returned string. 366 */ 367 char * 368 put_host_port(const char *host, u_short port) 369 { 370 char *hoststr; 371 372 if (port == 0 || port == SSH_DEFAULT_PORT) 373 return(xstrdup(host)); 374 if (asprintf(&hoststr, "[%s]:%d", host, (int)port) < 0) 375 fatal("put_host_port: asprintf: %s", strerror(errno)); 376 debug3("put_host_port: %s", hoststr); 377 return hoststr; 378 } 379 380 /* 381 * Search for next delimiter between hostnames/addresses and ports. 382 * Argument may be modified (for termination). 383 * Returns *cp if parsing succeeds. 384 * *cp is set to the start of the next delimiter, if one was found. 385 * If this is the last field, *cp is set to NULL. 386 */ 387 char * 388 hpdelim(char **cp) 389 { 390 char *s, *old; 391 392 if (cp == NULL || *cp == NULL) 393 return NULL; 394 395 old = s = *cp; 396 if (*s == '[') { 397 if ((s = strchr(s, ']')) == NULL) 398 return NULL; 399 else 400 s++; 401 } else if ((s = strpbrk(s, ":/")) == NULL) 402 s = *cp + strlen(*cp); /* skip to end (see first case below) */ 403 404 switch (*s) { 405 case '\0': 406 *cp = NULL; /* no more fields*/ 407 break; 408 409 case ':': 410 case '/': 411 *s = '\0'; /* terminate */ 412 *cp = s + 1; 413 break; 414 415 default: 416 return NULL; 417 } 418 419 return old; 420 } 421 422 char * 423 cleanhostname(char *host) 424 { 425 if (*host == '[' && host[strlen(host) - 1] == ']') { 426 host[strlen(host) - 1] = '\0'; 427 return (host + 1); 428 } else 429 return host; 430 } 431 432 char * 433 colon(char *cp) 434 { 435 int flag = 0; 436 437 if (*cp == ':') /* Leading colon is part of file name. */ 438 return NULL; 439 if (*cp == '[') 440 flag = 1; 441 442 for (; *cp; ++cp) { 443 if (*cp == '@' && *(cp+1) == '[') 444 flag = 1; 445 if (*cp == ']' && *(cp+1) == ':' && flag) 446 return (cp+1); 447 if (*cp == ':' && !flag) 448 return (cp); 449 if (*cp == '/') 450 return NULL; 451 } 452 return NULL; 453 } 454 455 /* 456 * Parse a [user@]host[:port] string. 457 * Caller must free returned user and host. 458 * Any of the pointer return arguments may be NULL (useful for syntax checking). 459 * If user was not specified then *userp will be set to NULL. 460 * If port was not specified then *portp will be -1. 461 * Returns 0 on success, -1 on failure. 462 */ 463 int 464 parse_user_host_port(const char *s, char **userp, char **hostp, int *portp) 465 { 466 char *sdup, *cp, *tmp; 467 char *user = NULL, *host = NULL; 468 int port = -1, ret = -1; 469 470 if (userp != NULL) 471 *userp = NULL; 472 if (hostp != NULL) 473 *hostp = NULL; 474 if (portp != NULL) 475 *portp = -1; 476 477 if ((sdup = tmp = strdup(s)) == NULL) 478 return -1; 479 /* Extract optional username */ 480 if ((cp = strchr(tmp, '@')) != NULL) { 481 *cp = '\0'; 482 if (*tmp == '\0') 483 goto out; 484 if ((user = strdup(tmp)) == NULL) 485 goto out; 486 tmp = cp + 1; 487 } 488 /* Extract mandatory hostname */ 489 if ((cp = hpdelim(&tmp)) == NULL || *cp == '\0') 490 goto out; 491 host = xstrdup(cleanhostname(cp)); 492 /* Convert and verify optional port */ 493 if (tmp != NULL && *tmp != '\0') { 494 if ((port = a2port(tmp)) <= 0) 495 goto out; 496 } 497 /* Success */ 498 if (userp != NULL) { 499 *userp = user; 500 user = NULL; 501 } 502 if (hostp != NULL) { 503 *hostp = host; 504 host = NULL; 505 } 506 if (portp != NULL) 507 *portp = port; 508 ret = 0; 509 out: 510 free(sdup); 511 free(user); 512 free(host); 513 return ret; 514 } 515 516 /* function to assist building execv() arguments */ 517 void 518 addargs(arglist *args, char *fmt, ...) 519 { 520 va_list ap; 521 char *cp; 522 u_int nalloc; 523 int r; 524 525 va_start(ap, fmt); 526 r = vasprintf(&cp, fmt, ap); 527 va_end(ap); 528 if (r == -1) 529 fatal("addargs: argument too long"); 530 531 nalloc = args->nalloc; 532 if (args->list == NULL) { 533 nalloc = 32; 534 args->num = 0; 535 } else if (args->num+2 >= nalloc) 536 nalloc *= 2; 537 538 args->list = xreallocarray(args->list, nalloc, sizeof(char *)); 539 args->nalloc = nalloc; 540 args->list[args->num++] = cp; 541 args->list[args->num] = NULL; 542 } 543 544 void 545 replacearg(arglist *args, u_int which, char *fmt, ...) 546 { 547 va_list ap; 548 char *cp; 549 int r; 550 551 va_start(ap, fmt); 552 r = vasprintf(&cp, fmt, ap); 553 va_end(ap); 554 if (r == -1) 555 fatal("replacearg: argument too long"); 556 557 if (which >= args->num) 558 fatal("replacearg: tried to replace invalid arg %d >= %d", 559 which, args->num); 560 free(args->list[which]); 561 args->list[which] = cp; 562 } 563 564 void 565 freeargs(arglist *args) 566 { 567 u_int i; 568 569 if (args->list != NULL) { 570 for (i = 0; i < args->num; i++) 571 free(args->list[i]); 572 free(args->list); 573 args->nalloc = args->num = 0; 574 args->list = NULL; 575 } 576 } 577 578 /* 579 * Expands tildes in the file name. Returns data allocated by xmalloc. 580 * Warning: this calls getpw*. 581 */ 582 char * 583 tilde_expand_filename(const char *filename, uid_t uid) 584 { 585 const char *path, *sep; 586 char user[128], *ret; 587 struct passwd *pw; 588 u_int len, slash; 589 590 if (*filename != '~') 591 return (xstrdup(filename)); 592 filename++; 593 594 path = strchr(filename, '/'); 595 if (path != NULL && path > filename) { /* ~user/path */ 596 slash = path - filename; 597 if (slash > sizeof(user) - 1) 598 fatal("tilde_expand_filename: ~username too long"); 599 memcpy(user, filename, slash); 600 user[slash] = '\0'; 601 if ((pw = getpwnam(user)) == NULL) 602 fatal("tilde_expand_filename: No such user %s", user); 603 } else if ((pw = getpwuid(uid)) == NULL) /* ~/path */ 604 fatal("tilde_expand_filename: No such uid %ld", (long)uid); 605 606 /* Make sure directory has a trailing '/' */ 607 len = strlen(pw->pw_dir); 608 if (len == 0 || pw->pw_dir[len - 1] != '/') 609 sep = "/"; 610 else 611 sep = ""; 612 613 /* Skip leading '/' from specified path */ 614 if (path != NULL) 615 filename = path + 1; 616 617 if (xasprintf(&ret, "%s%s%s", pw->pw_dir, sep, filename) >= PATH_MAX) 618 fatal("tilde_expand_filename: Path too long"); 619 620 return (ret); 621 } 622 623 /* 624 * Expand a string with a set of %[char] escapes. A number of escapes may be 625 * specified as (char *escape_chars, char *replacement) pairs. The list must 626 * be terminated by a NULL escape_char. Returns replaced string in memory 627 * allocated by xmalloc. 628 */ 629 char * 630 percent_expand(const char *string, ...) 631 { 632 #define EXPAND_MAX_KEYS 16 633 u_int num_keys, i, j; 634 struct { 635 const char *key; 636 const char *repl; 637 } keys[EXPAND_MAX_KEYS]; 638 char buf[4096]; 639 va_list ap; 640 641 /* Gather keys */ 642 va_start(ap, string); 643 for (num_keys = 0; num_keys < EXPAND_MAX_KEYS; num_keys++) { 644 keys[num_keys].key = va_arg(ap, char *); 645 if (keys[num_keys].key == NULL) 646 break; 647 keys[num_keys].repl = va_arg(ap, char *); 648 if (keys[num_keys].repl == NULL) 649 fatal("%s: NULL replacement", __func__); 650 } 651 if (num_keys == EXPAND_MAX_KEYS && va_arg(ap, char *) != NULL) 652 fatal("%s: too many keys", __func__); 653 va_end(ap); 654 655 /* Expand string */ 656 *buf = '\0'; 657 for (i = 0; *string != '\0'; string++) { 658 if (*string != '%') { 659 append: 660 buf[i++] = *string; 661 if (i >= sizeof(buf)) 662 fatal("%s: string too long", __func__); 663 buf[i] = '\0'; 664 continue; 665 } 666 string++; 667 /* %% case */ 668 if (*string == '%') 669 goto append; 670 if (*string == '\0') 671 fatal("%s: invalid format", __func__); 672 for (j = 0; j < num_keys; j++) { 673 if (strchr(keys[j].key, *string) != NULL) { 674 i = strlcat(buf, keys[j].repl, sizeof(buf)); 675 if (i >= sizeof(buf)) 676 fatal("%s: string too long", __func__); 677 break; 678 } 679 } 680 if (j >= num_keys) 681 fatal("%s: unknown key %%%c", __func__, *string); 682 } 683 return (xstrdup(buf)); 684 #undef EXPAND_MAX_KEYS 685 } 686 687 /* 688 * Read an entire line from a public key file into a static buffer, discarding 689 * lines that exceed the buffer size. Returns 0 on success, -1 on failure. 690 */ 691 int 692 read_keyfile_line(FILE *f, const char *filename, char *buf, size_t bufsz, 693 u_long *lineno) 694 { 695 while (fgets(buf, bufsz, f) != NULL) { 696 if (buf[0] == '\0') 697 continue; 698 (*lineno)++; 699 if (buf[strlen(buf) - 1] == '\n' || feof(f)) { 700 return 0; 701 } else { 702 debug("%s: %s line %lu exceeds size limit", __func__, 703 filename, *lineno); 704 /* discard remainder of line */ 705 while (fgetc(f) != '\n' && !feof(f)) 706 ; /* nothing */ 707 } 708 } 709 return -1; 710 } 711 712 int 713 tun_open(int tun, int mode) 714 { 715 #if defined(CUSTOM_SYS_TUN_OPEN) 716 return (sys_tun_open(tun, mode)); 717 #elif defined(SSH_TUN_OPENBSD) 718 struct ifreq ifr; 719 char name[100]; 720 int fd = -1, sock; 721 const char *tunbase = "tun"; 722 723 if (mode == SSH_TUNMODE_ETHERNET) 724 tunbase = "tap"; 725 726 /* Open the tunnel device */ 727 if (tun <= SSH_TUNID_MAX) { 728 snprintf(name, sizeof(name), "/dev/%s%d", tunbase, tun); 729 fd = open(name, O_RDWR); 730 } else if (tun == SSH_TUNID_ANY) { 731 for (tun = 100; tun >= 0; tun--) { 732 snprintf(name, sizeof(name), "/dev/%s%d", 733 tunbase, tun); 734 if ((fd = open(name, O_RDWR)) >= 0) 735 break; 736 } 737 } else { 738 debug("%s: invalid tunnel %u", __func__, tun); 739 return -1; 740 } 741 742 if (fd < 0) { 743 debug("%s: %s open: %s", __func__, name, strerror(errno)); 744 return -1; 745 } 746 747 debug("%s: %s mode %d fd %d", __func__, name, mode, fd); 748 749 /* Bring interface up if it is not already */ 750 snprintf(ifr.ifr_name, sizeof(ifr.ifr_name), "%s%d", tunbase, tun); 751 if ((sock = socket(PF_UNIX, SOCK_STREAM, 0)) == -1) 752 goto failed; 753 754 if (ioctl(sock, SIOCGIFFLAGS, &ifr) == -1) { 755 debug("%s: get interface %s flags: %s", __func__, 756 ifr.ifr_name, strerror(errno)); 757 goto failed; 758 } 759 760 if (!(ifr.ifr_flags & IFF_UP)) { 761 ifr.ifr_flags |= IFF_UP; 762 if (ioctl(sock, SIOCSIFFLAGS, &ifr) == -1) { 763 debug("%s: activate interface %s: %s", __func__, 764 ifr.ifr_name, strerror(errno)); 765 goto failed; 766 } 767 } 768 769 close(sock); 770 return fd; 771 772 failed: 773 if (fd >= 0) 774 close(fd); 775 if (sock >= 0) 776 close(sock); 777 return -1; 778 #else 779 error("Tunnel interfaces are not supported on this platform"); 780 return (-1); 781 #endif 782 } 783 784 void 785 sanitise_stdfd(void) 786 { 787 int nullfd, dupfd; 788 789 if ((nullfd = dupfd = open(_PATH_DEVNULL, O_RDWR)) == -1) { 790 fprintf(stderr, "Couldn't open /dev/null: %s\n", 791 strerror(errno)); 792 exit(1); 793 } 794 while (++dupfd <= STDERR_FILENO) { 795 /* Only populate closed fds. */ 796 if (fcntl(dupfd, F_GETFL) == -1 && errno == EBADF) { 797 if (dup2(nullfd, dupfd) == -1) { 798 fprintf(stderr, "dup2: %s\n", strerror(errno)); 799 exit(1); 800 } 801 } 802 } 803 if (nullfd > STDERR_FILENO) 804 close(nullfd); 805 } 806 807 char * 808 tohex(const void *vp, size_t l) 809 { 810 const u_char *p = (const u_char *)vp; 811 char b[3], *r; 812 size_t i, hl; 813 814 if (l > 65536) 815 return xstrdup("tohex: length > 65536"); 816 817 hl = l * 2 + 1; 818 r = xcalloc(1, hl); 819 for (i = 0; i < l; i++) { 820 snprintf(b, sizeof(b), "%02x", p[i]); 821 strlcat(r, b, hl); 822 } 823 return (r); 824 } 825 826 u_int64_t 827 get_u64(const void *vp) 828 { 829 const u_char *p = (const u_char *)vp; 830 u_int64_t v; 831 832 v = (u_int64_t)p[0] << 56; 833 v |= (u_int64_t)p[1] << 48; 834 v |= (u_int64_t)p[2] << 40; 835 v |= (u_int64_t)p[3] << 32; 836 v |= (u_int64_t)p[4] << 24; 837 v |= (u_int64_t)p[5] << 16; 838 v |= (u_int64_t)p[6] << 8; 839 v |= (u_int64_t)p[7]; 840 841 return (v); 842 } 843 844 u_int32_t 845 get_u32(const void *vp) 846 { 847 const u_char *p = (const u_char *)vp; 848 u_int32_t v; 849 850 v = (u_int32_t)p[0] << 24; 851 v |= (u_int32_t)p[1] << 16; 852 v |= (u_int32_t)p[2] << 8; 853 v |= (u_int32_t)p[3]; 854 855 return (v); 856 } 857 858 u_int32_t 859 get_u32_le(const void *vp) 860 { 861 const u_char *p = (const u_char *)vp; 862 u_int32_t v; 863 864 v = (u_int32_t)p[0]; 865 v |= (u_int32_t)p[1] << 8; 866 v |= (u_int32_t)p[2] << 16; 867 v |= (u_int32_t)p[3] << 24; 868 869 return (v); 870 } 871 872 u_int16_t 873 get_u16(const void *vp) 874 { 875 const u_char *p = (const u_char *)vp; 876 u_int16_t v; 877 878 v = (u_int16_t)p[0] << 8; 879 v |= (u_int16_t)p[1]; 880 881 return (v); 882 } 883 884 void 885 put_u64(void *vp, u_int64_t v) 886 { 887 u_char *p = (u_char *)vp; 888 889 p[0] = (u_char)(v >> 56) & 0xff; 890 p[1] = (u_char)(v >> 48) & 0xff; 891 p[2] = (u_char)(v >> 40) & 0xff; 892 p[3] = (u_char)(v >> 32) & 0xff; 893 p[4] = (u_char)(v >> 24) & 0xff; 894 p[5] = (u_char)(v >> 16) & 0xff; 895 p[6] = (u_char)(v >> 8) & 0xff; 896 p[7] = (u_char)v & 0xff; 897 } 898 899 void 900 put_u32(void *vp, u_int32_t v) 901 { 902 u_char *p = (u_char *)vp; 903 904 p[0] = (u_char)(v >> 24) & 0xff; 905 p[1] = (u_char)(v >> 16) & 0xff; 906 p[2] = (u_char)(v >> 8) & 0xff; 907 p[3] = (u_char)v & 0xff; 908 } 909 910 void 911 put_u32_le(void *vp, u_int32_t v) 912 { 913 u_char *p = (u_char *)vp; 914 915 p[0] = (u_char)v & 0xff; 916 p[1] = (u_char)(v >> 8) & 0xff; 917 p[2] = (u_char)(v >> 16) & 0xff; 918 p[3] = (u_char)(v >> 24) & 0xff; 919 } 920 921 void 922 put_u16(void *vp, u_int16_t v) 923 { 924 u_char *p = (u_char *)vp; 925 926 p[0] = (u_char)(v >> 8) & 0xff; 927 p[1] = (u_char)v & 0xff; 928 } 929 930 void 931 ms_subtract_diff(struct timeval *start, int *ms) 932 { 933 struct timeval diff, finish; 934 935 gettimeofday(&finish, NULL); 936 timersub(&finish, start, &diff); 937 *ms -= (diff.tv_sec * 1000) + (diff.tv_usec / 1000); 938 } 939 940 void 941 ms_to_timeval(struct timeval *tv, int ms) 942 { 943 if (ms < 0) 944 ms = 0; 945 tv->tv_sec = ms / 1000; 946 tv->tv_usec = (ms % 1000) * 1000; 947 } 948 949 time_t 950 monotime(void) 951 { 952 #if defined(HAVE_CLOCK_GETTIME) && \ 953 (defined(CLOCK_MONOTONIC) || defined(CLOCK_BOOTTIME)) 954 struct timespec ts; 955 static int gettime_failed = 0; 956 957 if (!gettime_failed) { 958 #if defined(CLOCK_BOOTTIME) 959 if (clock_gettime(CLOCK_BOOTTIME, &ts) == 0) 960 return (ts.tv_sec); 961 #endif 962 #if defined(CLOCK_MONOTONIC) 963 if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) 964 return (ts.tv_sec); 965 #endif 966 debug3("clock_gettime: %s", strerror(errno)); 967 gettime_failed = 1; 968 } 969 #endif /* HAVE_CLOCK_GETTIME && (CLOCK_MONOTONIC || CLOCK_BOOTTIME */ 970 971 return time(NULL); 972 } 973 974 double 975 monotime_double(void) 976 { 977 #if defined(HAVE_CLOCK_GETTIME) && \ 978 (defined(CLOCK_MONOTONIC) || defined(CLOCK_BOOTTIME)) 979 struct timespec ts; 980 static int gettime_failed = 0; 981 982 if (!gettime_failed) { 983 #if defined(CLOCK_BOOTTIME) 984 if (clock_gettime(CLOCK_BOOTTIME, &ts) == 0) 985 return (ts.tv_sec + (double)ts.tv_nsec / 1000000000); 986 #endif 987 #if defined(CLOCK_MONOTONIC) 988 if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) 989 return (ts.tv_sec + (double)ts.tv_nsec / 1000000000); 990 #endif 991 debug3("clock_gettime: %s", strerror(errno)); 992 gettime_failed = 1; 993 } 994 #endif /* HAVE_CLOCK_GETTIME && (CLOCK_MONOTONIC || CLOCK_BOOTTIME */ 995 996 return (double)time(NULL); 997 } 998 999 void 1000 bandwidth_limit_init(struct bwlimit *bw, u_int64_t kbps, size_t buflen) 1001 { 1002 bw->buflen = buflen; 1003 bw->rate = kbps; 1004 bw->thresh = bw->rate; 1005 bw->lamt = 0; 1006 timerclear(&bw->bwstart); 1007 timerclear(&bw->bwend); 1008 } 1009 1010 /* Callback from read/write loop to insert bandwidth-limiting delays */ 1011 void 1012 bandwidth_limit(struct bwlimit *bw, size_t read_len) 1013 { 1014 u_int64_t waitlen; 1015 struct timespec ts, rm; 1016 1017 if (!timerisset(&bw->bwstart)) { 1018 gettimeofday(&bw->bwstart, NULL); 1019 return; 1020 } 1021 1022 bw->lamt += read_len; 1023 if (bw->lamt < bw->thresh) 1024 return; 1025 1026 gettimeofday(&bw->bwend, NULL); 1027 timersub(&bw->bwend, &bw->bwstart, &bw->bwend); 1028 if (!timerisset(&bw->bwend)) 1029 return; 1030 1031 bw->lamt *= 8; 1032 waitlen = (double)1000000L * bw->lamt / bw->rate; 1033 1034 bw->bwstart.tv_sec = waitlen / 1000000L; 1035 bw->bwstart.tv_usec = waitlen % 1000000L; 1036 1037 if (timercmp(&bw->bwstart, &bw->bwend, >)) { 1038 timersub(&bw->bwstart, &bw->bwend, &bw->bwend); 1039 1040 /* Adjust the wait time */ 1041 if (bw->bwend.tv_sec) { 1042 bw->thresh /= 2; 1043 if (bw->thresh < bw->buflen / 4) 1044 bw->thresh = bw->buflen / 4; 1045 } else if (bw->bwend.tv_usec < 10000) { 1046 bw->thresh *= 2; 1047 if (bw->thresh > bw->buflen * 8) 1048 bw->thresh = bw->buflen * 8; 1049 } 1050 1051 TIMEVAL_TO_TIMESPEC(&bw->bwend, &ts); 1052 while (nanosleep(&ts, &rm) == -1) { 1053 if (errno != EINTR) 1054 break; 1055 ts = rm; 1056 } 1057 } 1058 1059 bw->lamt = 0; 1060 gettimeofday(&bw->bwstart, NULL); 1061 } 1062 1063 /* Make a template filename for mk[sd]temp() */ 1064 void 1065 mktemp_proto(char *s, size_t len) 1066 { 1067 const char *tmpdir; 1068 int r; 1069 1070 if ((tmpdir = getenv("TMPDIR")) != NULL) { 1071 r = snprintf(s, len, "%s/ssh-XXXXXXXXXXXX", tmpdir); 1072 if (r > 0 && (size_t)r < len) 1073 return; 1074 } 1075 r = snprintf(s, len, "/tmp/ssh-XXXXXXXXXXXX"); 1076 if (r < 0 || (size_t)r >= len) 1077 fatal("%s: template string too short", __func__); 1078 } 1079 1080 static const struct { 1081 const char *name; 1082 int value; 1083 } ipqos[] = { 1084 { "af11", IPTOS_DSCP_AF11 }, 1085 { "af12", IPTOS_DSCP_AF12 }, 1086 { "af13", IPTOS_DSCP_AF13 }, 1087 { "af21", IPTOS_DSCP_AF21 }, 1088 { "af22", IPTOS_DSCP_AF22 }, 1089 { "af23", IPTOS_DSCP_AF23 }, 1090 { "af31", IPTOS_DSCP_AF31 }, 1091 { "af32", IPTOS_DSCP_AF32 }, 1092 { "af33", IPTOS_DSCP_AF33 }, 1093 { "af41", IPTOS_DSCP_AF41 }, 1094 { "af42", IPTOS_DSCP_AF42 }, 1095 { "af43", IPTOS_DSCP_AF43 }, 1096 { "cs0", IPTOS_DSCP_CS0 }, 1097 { "cs1", IPTOS_DSCP_CS1 }, 1098 { "cs2", IPTOS_DSCP_CS2 }, 1099 { "cs3", IPTOS_DSCP_CS3 }, 1100 { "cs4", IPTOS_DSCP_CS4 }, 1101 { "cs5", IPTOS_DSCP_CS5 }, 1102 { "cs6", IPTOS_DSCP_CS6 }, 1103 { "cs7", IPTOS_DSCP_CS7 }, 1104 { "ef", IPTOS_DSCP_EF }, 1105 { "lowdelay", IPTOS_LOWDELAY }, 1106 { "throughput", IPTOS_THROUGHPUT }, 1107 { "reliability", IPTOS_RELIABILITY }, 1108 { NULL, -1 } 1109 }; 1110 1111 int 1112 parse_ipqos(const char *cp) 1113 { 1114 u_int i; 1115 char *ep; 1116 long val; 1117 1118 if (cp == NULL) 1119 return -1; 1120 for (i = 0; ipqos[i].name != NULL; i++) { 1121 if (strcasecmp(cp, ipqos[i].name) == 0) 1122 return ipqos[i].value; 1123 } 1124 /* Try parsing as an integer */ 1125 val = strtol(cp, &ep, 0); 1126 if (*cp == '\0' || *ep != '\0' || val < 0 || val > 255) 1127 return -1; 1128 return val; 1129 } 1130 1131 const char * 1132 iptos2str(int iptos) 1133 { 1134 int i; 1135 static char iptos_str[sizeof "0xff"]; 1136 1137 for (i = 0; ipqos[i].name != NULL; i++) { 1138 if (ipqos[i].value == iptos) 1139 return ipqos[i].name; 1140 } 1141 snprintf(iptos_str, sizeof iptos_str, "0x%02x", iptos); 1142 return iptos_str; 1143 } 1144 1145 void 1146 lowercase(char *s) 1147 { 1148 for (; *s; s++) 1149 *s = tolower((u_char)*s); 1150 } 1151 1152 int 1153 unix_listener(const char *path, int backlog, int unlink_first) 1154 { 1155 struct sockaddr_un sunaddr; 1156 int saved_errno, sock; 1157 1158 memset(&sunaddr, 0, sizeof(sunaddr)); 1159 sunaddr.sun_family = AF_UNIX; 1160 if (strlcpy(sunaddr.sun_path, path, sizeof(sunaddr.sun_path)) >= sizeof(sunaddr.sun_path)) { 1161 error("%s: \"%s\" too long for Unix domain socket", __func__, 1162 path); 1163 errno = ENAMETOOLONG; 1164 return -1; 1165 } 1166 1167 sock = socket(PF_UNIX, SOCK_STREAM, 0); 1168 if (sock < 0) { 1169 saved_errno = errno; 1170 error("socket: %.100s", strerror(errno)); 1171 errno = saved_errno; 1172 return -1; 1173 } 1174 if (unlink_first == 1) { 1175 if (unlink(path) != 0 && errno != ENOENT) 1176 error("unlink(%s): %.100s", path, strerror(errno)); 1177 } 1178 if (bind(sock, (struct sockaddr *)&sunaddr, sizeof(sunaddr)) < 0) { 1179 saved_errno = errno; 1180 error("bind: %.100s", strerror(errno)); 1181 close(sock); 1182 error("%s: cannot bind to path: %s", __func__, path); 1183 errno = saved_errno; 1184 return -1; 1185 } 1186 if (listen(sock, backlog) < 0) { 1187 saved_errno = errno; 1188 error("listen: %.100s", strerror(errno)); 1189 close(sock); 1190 unlink(path); 1191 error("%s: cannot listen on path: %s", __func__, path); 1192 errno = saved_errno; 1193 return -1; 1194 } 1195 return sock; 1196 } 1197 1198 void 1199 sock_set_v6only(int s) 1200 { 1201 #if defined(IPV6_V6ONLY) && !defined(__OpenBSD__) 1202 int on = 1; 1203 1204 debug3("%s: set socket %d IPV6_V6ONLY", __func__, s); 1205 if (setsockopt(s, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof(on)) == -1) 1206 error("setsockopt IPV6_V6ONLY: %s", strerror(errno)); 1207 #endif 1208 } 1209 1210 /* 1211 * Compares two strings that maybe be NULL. Returns non-zero if strings 1212 * are both NULL or are identical, returns zero otherwise. 1213 */ 1214 static int 1215 strcmp_maybe_null(const char *a, const char *b) 1216 { 1217 if ((a == NULL && b != NULL) || (a != NULL && b == NULL)) 1218 return 0; 1219 if (a != NULL && strcmp(a, b) != 0) 1220 return 0; 1221 return 1; 1222 } 1223 1224 /* 1225 * Compare two forwards, returning non-zero if they are identical or 1226 * zero otherwise. 1227 */ 1228 int 1229 forward_equals(const struct Forward *a, const struct Forward *b) 1230 { 1231 if (strcmp_maybe_null(a->listen_host, b->listen_host) == 0) 1232 return 0; 1233 if (a->listen_port != b->listen_port) 1234 return 0; 1235 if (strcmp_maybe_null(a->listen_path, b->listen_path) == 0) 1236 return 0; 1237 if (strcmp_maybe_null(a->connect_host, b->connect_host) == 0) 1238 return 0; 1239 if (a->connect_port != b->connect_port) 1240 return 0; 1241 if (strcmp_maybe_null(a->connect_path, b->connect_path) == 0) 1242 return 0; 1243 /* allocated_port and handle are not checked */ 1244 return 1; 1245 } 1246 1247 static int 1248 ipport_reserved(void) 1249 { 1250 #if __FreeBSD__ 1251 int old, ret; 1252 size_t len = sizeof(old); 1253 1254 ret = sysctlbyname("net.inet.ip.portrange.reservedhigh", 1255 &old, &len, NULL, 0); 1256 if (ret == 0) 1257 return (old + 1); 1258 #endif 1259 return (IPPORT_RESERVED); 1260 } 1261 1262 /* returns 1 if bind to specified port by specified user is permitted */ 1263 int 1264 bind_permitted(int port, uid_t uid) 1265 { 1266 1267 if (port < ipport_reserved() && uid != 0) 1268 return 0; 1269 return 1; 1270 } 1271 1272 /* returns 1 if process is already daemonized, 0 otherwise */ 1273 int 1274 daemonized(void) 1275 { 1276 int fd; 1277 1278 if ((fd = open(_PATH_TTY, O_RDONLY | O_NOCTTY)) >= 0) { 1279 close(fd); 1280 return 0; /* have controlling terminal */ 1281 } 1282 if (getppid() != 1) 1283 return 0; /* parent is not init */ 1284 if (getsid(0) != getpid()) 1285 return 0; /* not session leader */ 1286 debug3("already daemonized"); 1287 return 1; 1288 } 1289