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