1 /* $OpenBSD: misc.c,v 1.181 2023/03/03 02:37:58 dtucker Exp $ */ 2 /* 3 * Copyright (c) 2000 Markus Friedl. All rights reserved. 4 * Copyright (c) 2005-2020 Damien Miller. All rights reserved. 5 * Copyright (c) 2004 Henning Brauer <henning@openbsd.org> 6 * 7 * Permission to use, copy, modify, and distribute this software for any 8 * purpose with or without fee is hereby granted, provided that the above 9 * copyright notice and this permission notice appear in all copies. 10 * 11 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES 12 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF 13 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR 14 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES 15 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN 16 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF 17 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. 18 */ 19 20 21 #include <sys/types.h> 22 #include <sys/ioctl.h> 23 #include <sys/socket.h> 24 #include <sys/stat.h> 25 #include <sys/time.h> 26 #include <sys/wait.h> 27 #include <sys/un.h> 28 29 #include <net/if.h> 30 #include <netinet/in.h> 31 #include <netinet/ip.h> 32 #include <netinet/tcp.h> 33 #include <arpa/inet.h> 34 35 #include <ctype.h> 36 #include <errno.h> 37 #include <fcntl.h> 38 #include <netdb.h> 39 #include <paths.h> 40 #include <pwd.h> 41 #include <libgen.h> 42 #include <limits.h> 43 #include <poll.h> 44 #include <signal.h> 45 #include <stdarg.h> 46 #include <stdio.h> 47 #include <stdlib.h> 48 #include <string.h> 49 #include <unistd.h> 50 51 #include "xmalloc.h" 52 #include "misc.h" 53 #include "log.h" 54 #include "ssh.h" 55 #include "sshbuf.h" 56 #include "ssherr.h" 57 58 /* remove newline at end of string */ 59 char * 60 chop(char *s) 61 { 62 char *t = s; 63 while (*t) { 64 if (*t == '\n' || *t == '\r') { 65 *t = '\0'; 66 return s; 67 } 68 t++; 69 } 70 return s; 71 72 } 73 74 /* remove whitespace from end of string */ 75 void 76 rtrim(char *s) 77 { 78 size_t i; 79 80 if ((i = strlen(s)) == 0) 81 return; 82 for (i--; i > 0; i--) { 83 if (isspace((unsigned char)s[i])) 84 s[i] = '\0'; 85 } 86 } 87 88 /* set/unset filedescriptor to non-blocking */ 89 int 90 set_nonblock(int fd) 91 { 92 int val; 93 94 val = fcntl(fd, F_GETFL); 95 if (val == -1) { 96 error("fcntl(%d, F_GETFL): %s", fd, strerror(errno)); 97 return (-1); 98 } 99 if (val & O_NONBLOCK) { 100 debug3("fd %d is O_NONBLOCK", fd); 101 return (0); 102 } 103 debug2("fd %d setting O_NONBLOCK", fd); 104 val |= O_NONBLOCK; 105 if (fcntl(fd, F_SETFL, val) == -1) { 106 debug("fcntl(%d, F_SETFL, O_NONBLOCK): %s", fd, 107 strerror(errno)); 108 return (-1); 109 } 110 return (0); 111 } 112 113 int 114 unset_nonblock(int fd) 115 { 116 int val; 117 118 val = fcntl(fd, F_GETFL); 119 if (val == -1) { 120 error("fcntl(%d, F_GETFL): %s", fd, strerror(errno)); 121 return (-1); 122 } 123 if (!(val & O_NONBLOCK)) { 124 debug3("fd %d is not O_NONBLOCK", fd); 125 return (0); 126 } 127 debug("fd %d clearing O_NONBLOCK", fd); 128 val &= ~O_NONBLOCK; 129 if (fcntl(fd, F_SETFL, val) == -1) { 130 debug("fcntl(%d, F_SETFL, ~O_NONBLOCK): %s", 131 fd, strerror(errno)); 132 return (-1); 133 } 134 return (0); 135 } 136 137 const char * 138 ssh_gai_strerror(int gaierr) 139 { 140 if (gaierr == EAI_SYSTEM && errno != 0) 141 return strerror(errno); 142 return gai_strerror(gaierr); 143 } 144 145 /* disable nagle on socket */ 146 void 147 set_nodelay(int fd) 148 { 149 int opt; 150 socklen_t optlen; 151 152 optlen = sizeof opt; 153 if (getsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &opt, &optlen) == -1) { 154 debug("getsockopt TCP_NODELAY: %.100s", strerror(errno)); 155 return; 156 } 157 if (opt == 1) { 158 debug2("fd %d is TCP_NODELAY", fd); 159 return; 160 } 161 opt = 1; 162 debug2("fd %d setting TCP_NODELAY", fd); 163 if (setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &opt, sizeof opt) == -1) 164 error("setsockopt TCP_NODELAY: %.100s", strerror(errno)); 165 } 166 167 /* Allow local port reuse in TIME_WAIT */ 168 int 169 set_reuseaddr(int fd) 170 { 171 int on = 1; 172 173 if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)) == -1) { 174 error("setsockopt SO_REUSEADDR fd %d: %s", fd, strerror(errno)); 175 return -1; 176 } 177 return 0; 178 } 179 180 /* Get/set routing domain */ 181 char * 182 get_rdomain(int fd) 183 { 184 int rtable; 185 char *ret; 186 socklen_t len = sizeof(rtable); 187 188 if (getsockopt(fd, SOL_SOCKET, SO_RTABLE, &rtable, &len) == -1) { 189 error("Failed to get routing domain for fd %d: %s", 190 fd, strerror(errno)); 191 return NULL; 192 } 193 xasprintf(&ret, "%d", rtable); 194 return ret; 195 } 196 197 int 198 set_rdomain(int fd, const char *name) 199 { 200 int rtable; 201 const char *errstr; 202 203 if (name == NULL) 204 return 0; /* default table */ 205 206 rtable = (int)strtonum(name, 0, 255, &errstr); 207 if (errstr != NULL) { 208 /* Shouldn't happen */ 209 error("Invalid routing domain \"%s\": %s", name, errstr); 210 return -1; 211 } 212 if (setsockopt(fd, SOL_SOCKET, SO_RTABLE, 213 &rtable, sizeof(rtable)) == -1) { 214 error("Failed to set routing domain %d on fd %d: %s", 215 rtable, fd, strerror(errno)); 216 return -1; 217 } 218 return 0; 219 } 220 221 int 222 get_sock_af(int fd) 223 { 224 struct sockaddr_storage to; 225 socklen_t tolen = sizeof(to); 226 227 memset(&to, 0, sizeof(to)); 228 if (getsockname(fd, (struct sockaddr *)&to, &tolen) == -1) 229 return -1; 230 return to.ss_family; 231 } 232 233 void 234 set_sock_tos(int fd, int tos) 235 { 236 int af; 237 238 switch ((af = get_sock_af(fd))) { 239 case -1: 240 /* assume not a socket */ 241 break; 242 case AF_INET: 243 debug3_f("set socket %d IP_TOS 0x%02x", fd, tos); 244 if (setsockopt(fd, IPPROTO_IP, IP_TOS, 245 &tos, sizeof(tos)) == -1) { 246 error("setsockopt socket %d IP_TOS %d: %s", 247 fd, tos, strerror(errno)); 248 } 249 break; 250 case AF_INET6: 251 debug3_f("set socket %d IPV6_TCLASS 0x%02x", fd, tos); 252 if (setsockopt(fd, IPPROTO_IPV6, IPV6_TCLASS, 253 &tos, sizeof(tos)) == -1) { 254 error("setsockopt socket %d IPV6_TCLASS %d: %s", 255 fd, tos, strerror(errno)); 256 } 257 break; 258 default: 259 debug2_f("unsupported socket family %d", af); 260 break; 261 } 262 } 263 264 /* 265 * Wait up to *timeoutp milliseconds for events on fd. Updates 266 * *timeoutp with time remaining. 267 * Returns 0 if fd ready or -1 on timeout or error (see errno). 268 */ 269 static int 270 waitfd(int fd, int *timeoutp, short events) 271 { 272 struct pollfd pfd; 273 struct timeval t_start; 274 int oerrno, r; 275 276 pfd.fd = fd; 277 pfd.events = events; 278 for (; *timeoutp >= 0;) { 279 monotime_tv(&t_start); 280 r = poll(&pfd, 1, *timeoutp); 281 oerrno = errno; 282 ms_subtract_diff(&t_start, timeoutp); 283 errno = oerrno; 284 if (r > 0) 285 return 0; 286 else if (r == -1 && errno != EAGAIN && errno != EINTR) 287 return -1; 288 else if (r == 0) 289 break; 290 } 291 /* timeout */ 292 errno = ETIMEDOUT; 293 return -1; 294 } 295 296 /* 297 * Wait up to *timeoutp milliseconds for fd to be readable. Updates 298 * *timeoutp with time remaining. 299 * Returns 0 if fd ready or -1 on timeout or error (see errno). 300 */ 301 int 302 waitrfd(int fd, int *timeoutp) { 303 return waitfd(fd, timeoutp, POLLIN); 304 } 305 306 /* 307 * Attempt a non-blocking connect(2) to the specified address, waiting up to 308 * *timeoutp milliseconds for the connection to complete. If the timeout is 309 * <=0, then wait indefinitely. 310 * 311 * Returns 0 on success or -1 on failure. 312 */ 313 int 314 timeout_connect(int sockfd, const struct sockaddr *serv_addr, 315 socklen_t addrlen, int *timeoutp) 316 { 317 int optval = 0; 318 socklen_t optlen = sizeof(optval); 319 320 /* No timeout: just do a blocking connect() */ 321 if (timeoutp == NULL || *timeoutp <= 0) 322 return connect(sockfd, serv_addr, addrlen); 323 324 set_nonblock(sockfd); 325 for (;;) { 326 if (connect(sockfd, serv_addr, addrlen) == 0) { 327 /* Succeeded already? */ 328 unset_nonblock(sockfd); 329 return 0; 330 } else if (errno == EINTR) 331 continue; 332 else if (errno != EINPROGRESS) 333 return -1; 334 break; 335 } 336 337 if (waitfd(sockfd, timeoutp, POLLIN | POLLOUT) == -1) 338 return -1; 339 340 /* Completed or failed */ 341 if (getsockopt(sockfd, SOL_SOCKET, SO_ERROR, &optval, &optlen) == -1) { 342 debug("getsockopt: %s", strerror(errno)); 343 return -1; 344 } 345 if (optval != 0) { 346 errno = optval; 347 return -1; 348 } 349 unset_nonblock(sockfd); 350 return 0; 351 } 352 353 /* Characters considered whitespace in strsep calls. */ 354 #define WHITESPACE " \t\r\n" 355 #define QUOTE "\"" 356 357 /* return next token in configuration line */ 358 static char * 359 strdelim_internal(char **s, int split_equals) 360 { 361 char *old; 362 int wspace = 0; 363 364 if (*s == NULL) 365 return NULL; 366 367 old = *s; 368 369 *s = strpbrk(*s, 370 split_equals ? WHITESPACE QUOTE "=" : WHITESPACE QUOTE); 371 if (*s == NULL) 372 return (old); 373 374 if (*s[0] == '\"') { 375 memmove(*s, *s + 1, strlen(*s)); /* move nul too */ 376 /* Find matching quote */ 377 if ((*s = strpbrk(*s, QUOTE)) == NULL) { 378 return (NULL); /* no matching quote */ 379 } else { 380 *s[0] = '\0'; 381 *s += strspn(*s + 1, WHITESPACE) + 1; 382 return (old); 383 } 384 } 385 386 /* Allow only one '=' to be skipped */ 387 if (split_equals && *s[0] == '=') 388 wspace = 1; 389 *s[0] = '\0'; 390 391 /* Skip any extra whitespace after first token */ 392 *s += strspn(*s + 1, WHITESPACE) + 1; 393 if (split_equals && *s[0] == '=' && !wspace) 394 *s += strspn(*s + 1, WHITESPACE) + 1; 395 396 return (old); 397 } 398 399 /* 400 * Return next token in configuration line; splts on whitespace or a 401 * single '=' character. 402 */ 403 char * 404 strdelim(char **s) 405 { 406 return strdelim_internal(s, 1); 407 } 408 409 /* 410 * Return next token in configuration line; splts on whitespace only. 411 */ 412 char * 413 strdelimw(char **s) 414 { 415 return strdelim_internal(s, 0); 416 } 417 418 struct passwd * 419 pwcopy(struct passwd *pw) 420 { 421 struct passwd *copy = xcalloc(1, sizeof(*copy)); 422 423 copy->pw_name = xstrdup(pw->pw_name); 424 copy->pw_passwd = xstrdup(pw->pw_passwd); 425 copy->pw_gecos = xstrdup(pw->pw_gecos); 426 copy->pw_uid = pw->pw_uid; 427 copy->pw_gid = pw->pw_gid; 428 copy->pw_expire = pw->pw_expire; 429 copy->pw_change = pw->pw_change; 430 copy->pw_class = xstrdup(pw->pw_class); 431 copy->pw_dir = xstrdup(pw->pw_dir); 432 copy->pw_shell = xstrdup(pw->pw_shell); 433 return copy; 434 } 435 436 /* 437 * Convert ASCII string to TCP/IP port number. 438 * Port must be >=0 and <=65535. 439 * Return -1 if invalid. 440 */ 441 int 442 a2port(const char *s) 443 { 444 struct servent *se; 445 long long port; 446 const char *errstr; 447 448 port = strtonum(s, 0, 65535, &errstr); 449 if (errstr == NULL) 450 return (int)port; 451 if ((se = getservbyname(s, "tcp")) != NULL) 452 return ntohs(se->s_port); 453 return -1; 454 } 455 456 int 457 a2tun(const char *s, int *remote) 458 { 459 const char *errstr = NULL; 460 char *sp, *ep; 461 int tun; 462 463 if (remote != NULL) { 464 *remote = SSH_TUNID_ANY; 465 sp = xstrdup(s); 466 if ((ep = strchr(sp, ':')) == NULL) { 467 free(sp); 468 return (a2tun(s, NULL)); 469 } 470 ep[0] = '\0'; ep++; 471 *remote = a2tun(ep, NULL); 472 tun = a2tun(sp, NULL); 473 free(sp); 474 return (*remote == SSH_TUNID_ERR ? *remote : tun); 475 } 476 477 if (strcasecmp(s, "any") == 0) 478 return (SSH_TUNID_ANY); 479 480 tun = strtonum(s, 0, SSH_TUNID_MAX, &errstr); 481 if (errstr != NULL) 482 return (SSH_TUNID_ERR); 483 484 return (tun); 485 } 486 487 #define SECONDS 1 488 #define MINUTES (SECONDS * 60) 489 #define HOURS (MINUTES * 60) 490 #define DAYS (HOURS * 24) 491 #define WEEKS (DAYS * 7) 492 493 /* 494 * Convert a time string into seconds; format is 495 * a sequence of: 496 * time[qualifier] 497 * 498 * Valid time qualifiers are: 499 * <none> seconds 500 * s|S seconds 501 * m|M minutes 502 * h|H hours 503 * d|D days 504 * w|W weeks 505 * 506 * Examples: 507 * 90m 90 minutes 508 * 1h30m 90 minutes 509 * 2d 2 days 510 * 1w 1 week 511 * 512 * Return -1 if time string is invalid. 513 */ 514 int 515 convtime(const char *s) 516 { 517 long total, secs, multiplier; 518 const char *p; 519 char *endp; 520 521 errno = 0; 522 total = 0; 523 p = s; 524 525 if (p == NULL || *p == '\0') 526 return -1; 527 528 while (*p) { 529 secs = strtol(p, &endp, 10); 530 if (p == endp || 531 (errno == ERANGE && (secs == INT_MIN || secs == INT_MAX)) || 532 secs < 0) 533 return -1; 534 535 multiplier = 1; 536 switch (*endp++) { 537 case '\0': 538 endp--; 539 break; 540 case 's': 541 case 'S': 542 break; 543 case 'm': 544 case 'M': 545 multiplier = MINUTES; 546 break; 547 case 'h': 548 case 'H': 549 multiplier = HOURS; 550 break; 551 case 'd': 552 case 'D': 553 multiplier = DAYS; 554 break; 555 case 'w': 556 case 'W': 557 multiplier = WEEKS; 558 break; 559 default: 560 return -1; 561 } 562 if (secs > INT_MAX / multiplier) 563 return -1; 564 secs *= multiplier; 565 if (total > INT_MAX - secs) 566 return -1; 567 total += secs; 568 if (total < 0) 569 return -1; 570 p = endp; 571 } 572 573 return total; 574 } 575 576 #define TF_BUFS 8 577 #define TF_LEN 9 578 579 const char * 580 fmt_timeframe(time_t t) 581 { 582 char *buf; 583 static char tfbuf[TF_BUFS][TF_LEN]; /* ring buffer */ 584 static int idx = 0; 585 unsigned int sec, min, hrs, day; 586 unsigned long long week; 587 588 buf = tfbuf[idx++]; 589 if (idx == TF_BUFS) 590 idx = 0; 591 592 week = t; 593 594 sec = week % 60; 595 week /= 60; 596 min = week % 60; 597 week /= 60; 598 hrs = week % 24; 599 week /= 24; 600 day = week % 7; 601 week /= 7; 602 603 if (week > 0) 604 snprintf(buf, TF_LEN, "%02lluw%01ud%02uh", week, day, hrs); 605 else if (day > 0) 606 snprintf(buf, TF_LEN, "%01ud%02uh%02um", day, hrs, min); 607 else 608 snprintf(buf, TF_LEN, "%02u:%02u:%02u", hrs, min, sec); 609 610 return (buf); 611 } 612 613 /* 614 * Returns a standardized host+port identifier string. 615 * Caller must free returned string. 616 */ 617 char * 618 put_host_port(const char *host, u_short port) 619 { 620 char *hoststr; 621 622 if (port == 0 || port == SSH_DEFAULT_PORT) 623 return(xstrdup(host)); 624 if (asprintf(&hoststr, "[%s]:%d", host, (int)port) == -1) 625 fatal("put_host_port: asprintf: %s", strerror(errno)); 626 debug3("put_host_port: %s", hoststr); 627 return hoststr; 628 } 629 630 /* 631 * Search for next delimiter between hostnames/addresses and ports. 632 * Argument may be modified (for termination). 633 * Returns *cp if parsing succeeds. 634 * *cp is set to the start of the next field, if one was found. 635 * The delimiter char, if present, is stored in delim. 636 * If this is the last field, *cp is set to NULL. 637 */ 638 char * 639 hpdelim2(char **cp, char *delim) 640 { 641 char *s, *old; 642 643 if (cp == NULL || *cp == NULL) 644 return NULL; 645 646 old = s = *cp; 647 if (*s == '[') { 648 if ((s = strchr(s, ']')) == NULL) 649 return NULL; 650 else 651 s++; 652 } else if ((s = strpbrk(s, ":/")) == NULL) 653 s = *cp + strlen(*cp); /* skip to end (see first case below) */ 654 655 switch (*s) { 656 case '\0': 657 *cp = NULL; /* no more fields*/ 658 break; 659 660 case ':': 661 case '/': 662 if (delim != NULL) 663 *delim = *s; 664 *s = '\0'; /* terminate */ 665 *cp = s + 1; 666 break; 667 668 default: 669 return NULL; 670 } 671 672 return old; 673 } 674 675 /* The common case: only accept colon as delimiter. */ 676 char * 677 hpdelim(char **cp) 678 { 679 char *r, delim = '\0'; 680 681 r = hpdelim2(cp, &delim); 682 if (delim == '/') 683 return NULL; 684 return r; 685 } 686 687 char * 688 cleanhostname(char *host) 689 { 690 if (*host == '[' && host[strlen(host) - 1] == ']') { 691 host[strlen(host) - 1] = '\0'; 692 return (host + 1); 693 } else 694 return host; 695 } 696 697 char * 698 colon(char *cp) 699 { 700 int flag = 0; 701 702 if (*cp == ':') /* Leading colon is part of file name. */ 703 return NULL; 704 if (*cp == '[') 705 flag = 1; 706 707 for (; *cp; ++cp) { 708 if (*cp == '@' && *(cp+1) == '[') 709 flag = 1; 710 if (*cp == ']' && *(cp+1) == ':' && flag) 711 return (cp+1); 712 if (*cp == ':' && !flag) 713 return (cp); 714 if (*cp == '/') 715 return NULL; 716 } 717 return NULL; 718 } 719 720 /* 721 * Parse a [user@]host:[path] string. 722 * Caller must free returned user, host and path. 723 * Any of the pointer return arguments may be NULL (useful for syntax checking). 724 * If user was not specified then *userp will be set to NULL. 725 * If host was not specified then *hostp will be set to NULL. 726 * If path was not specified then *pathp will be set to ".". 727 * Returns 0 on success, -1 on failure. 728 */ 729 int 730 parse_user_host_path(const char *s, char **userp, char **hostp, char **pathp) 731 { 732 char *user = NULL, *host = NULL, *path = NULL; 733 char *sdup, *tmp; 734 int ret = -1; 735 736 if (userp != NULL) 737 *userp = NULL; 738 if (hostp != NULL) 739 *hostp = NULL; 740 if (pathp != NULL) 741 *pathp = NULL; 742 743 sdup = xstrdup(s); 744 745 /* Check for remote syntax: [user@]host:[path] */ 746 if ((tmp = colon(sdup)) == NULL) 747 goto out; 748 749 /* Extract optional path */ 750 *tmp++ = '\0'; 751 if (*tmp == '\0') 752 tmp = "."; 753 path = xstrdup(tmp); 754 755 /* Extract optional user and mandatory host */ 756 tmp = strrchr(sdup, '@'); 757 if (tmp != NULL) { 758 *tmp++ = '\0'; 759 host = xstrdup(cleanhostname(tmp)); 760 if (*sdup != '\0') 761 user = xstrdup(sdup); 762 } else { 763 host = xstrdup(cleanhostname(sdup)); 764 user = NULL; 765 } 766 767 /* Success */ 768 if (userp != NULL) { 769 *userp = user; 770 user = NULL; 771 } 772 if (hostp != NULL) { 773 *hostp = host; 774 host = NULL; 775 } 776 if (pathp != NULL) { 777 *pathp = path; 778 path = NULL; 779 } 780 ret = 0; 781 out: 782 free(sdup); 783 free(user); 784 free(host); 785 free(path); 786 return ret; 787 } 788 789 /* 790 * Parse a [user@]host[:port] string. 791 * Caller must free returned user and host. 792 * Any of the pointer return arguments may be NULL (useful for syntax checking). 793 * If user was not specified then *userp will be set to NULL. 794 * If port was not specified then *portp will be -1. 795 * Returns 0 on success, -1 on failure. 796 */ 797 int 798 parse_user_host_port(const char *s, char **userp, char **hostp, int *portp) 799 { 800 char *sdup, *cp, *tmp; 801 char *user = NULL, *host = NULL; 802 int port = -1, ret = -1; 803 804 if (userp != NULL) 805 *userp = NULL; 806 if (hostp != NULL) 807 *hostp = NULL; 808 if (portp != NULL) 809 *portp = -1; 810 811 if ((sdup = tmp = strdup(s)) == NULL) 812 return -1; 813 /* Extract optional username */ 814 if ((cp = strrchr(tmp, '@')) != NULL) { 815 *cp = '\0'; 816 if (*tmp == '\0') 817 goto out; 818 if ((user = strdup(tmp)) == NULL) 819 goto out; 820 tmp = cp + 1; 821 } 822 /* Extract mandatory hostname */ 823 if ((cp = hpdelim(&tmp)) == NULL || *cp == '\0') 824 goto out; 825 host = xstrdup(cleanhostname(cp)); 826 /* Convert and verify optional port */ 827 if (tmp != NULL && *tmp != '\0') { 828 if ((port = a2port(tmp)) <= 0) 829 goto out; 830 } 831 /* Success */ 832 if (userp != NULL) { 833 *userp = user; 834 user = NULL; 835 } 836 if (hostp != NULL) { 837 *hostp = host; 838 host = NULL; 839 } 840 if (portp != NULL) 841 *portp = port; 842 ret = 0; 843 out: 844 free(sdup); 845 free(user); 846 free(host); 847 return ret; 848 } 849 850 /* 851 * Converts a two-byte hex string to decimal. 852 * Returns the decimal value or -1 for invalid input. 853 */ 854 static int 855 hexchar(const char *s) 856 { 857 unsigned char result[2]; 858 int i; 859 860 for (i = 0; i < 2; i++) { 861 if (s[i] >= '0' && s[i] <= '9') 862 result[i] = (unsigned char)(s[i] - '0'); 863 else if (s[i] >= 'a' && s[i] <= 'f') 864 result[i] = (unsigned char)(s[i] - 'a') + 10; 865 else if (s[i] >= 'A' && s[i] <= 'F') 866 result[i] = (unsigned char)(s[i] - 'A') + 10; 867 else 868 return -1; 869 } 870 return (result[0] << 4) | result[1]; 871 } 872 873 /* 874 * Decode an url-encoded string. 875 * Returns a newly allocated string on success or NULL on failure. 876 */ 877 static char * 878 urldecode(const char *src) 879 { 880 char *ret, *dst; 881 int ch; 882 883 ret = xmalloc(strlen(src) + 1); 884 for (dst = ret; *src != '\0'; src++) { 885 switch (*src) { 886 case '+': 887 *dst++ = ' '; 888 break; 889 case '%': 890 if (!isxdigit((unsigned char)src[1]) || 891 !isxdigit((unsigned char)src[2]) || 892 (ch = hexchar(src + 1)) == -1) { 893 free(ret); 894 return NULL; 895 } 896 *dst++ = ch; 897 src += 2; 898 break; 899 default: 900 *dst++ = *src; 901 break; 902 } 903 } 904 *dst = '\0'; 905 906 return ret; 907 } 908 909 /* 910 * Parse an (scp|ssh|sftp)://[user@]host[:port][/path] URI. 911 * See https://tools.ietf.org/html/draft-ietf-secsh-scp-sftp-ssh-uri-04 912 * Either user or path may be url-encoded (but not host or port). 913 * Caller must free returned user, host and path. 914 * Any of the pointer return arguments may be NULL (useful for syntax checking) 915 * but the scheme must always be specified. 916 * If user was not specified then *userp will be set to NULL. 917 * If port was not specified then *portp will be -1. 918 * If path was not specified then *pathp will be set to NULL. 919 * Returns 0 on success, 1 if non-uri/wrong scheme, -1 on error/invalid uri. 920 */ 921 int 922 parse_uri(const char *scheme, const char *uri, char **userp, char **hostp, 923 int *portp, char **pathp) 924 { 925 char *uridup, *cp, *tmp, ch; 926 char *user = NULL, *host = NULL, *path = NULL; 927 int port = -1, ret = -1; 928 size_t len; 929 930 len = strlen(scheme); 931 if (strncmp(uri, scheme, len) != 0 || strncmp(uri + len, "://", 3) != 0) 932 return 1; 933 uri += len + 3; 934 935 if (userp != NULL) 936 *userp = NULL; 937 if (hostp != NULL) 938 *hostp = NULL; 939 if (portp != NULL) 940 *portp = -1; 941 if (pathp != NULL) 942 *pathp = NULL; 943 944 uridup = tmp = xstrdup(uri); 945 946 /* Extract optional ssh-info (username + connection params) */ 947 if ((cp = strchr(tmp, '@')) != NULL) { 948 char *delim; 949 950 *cp = '\0'; 951 /* Extract username and connection params */ 952 if ((delim = strchr(tmp, ';')) != NULL) { 953 /* Just ignore connection params for now */ 954 *delim = '\0'; 955 } 956 if (*tmp == '\0') { 957 /* Empty username */ 958 goto out; 959 } 960 if ((user = urldecode(tmp)) == NULL) 961 goto out; 962 tmp = cp + 1; 963 } 964 965 /* Extract mandatory hostname */ 966 if ((cp = hpdelim2(&tmp, &ch)) == NULL || *cp == '\0') 967 goto out; 968 host = xstrdup(cleanhostname(cp)); 969 if (!valid_domain(host, 0, NULL)) 970 goto out; 971 972 if (tmp != NULL && *tmp != '\0') { 973 if (ch == ':') { 974 /* Convert and verify port. */ 975 if ((cp = strchr(tmp, '/')) != NULL) 976 *cp = '\0'; 977 if ((port = a2port(tmp)) <= 0) 978 goto out; 979 tmp = cp ? cp + 1 : NULL; 980 } 981 if (tmp != NULL && *tmp != '\0') { 982 /* Extract optional path */ 983 if ((path = urldecode(tmp)) == NULL) 984 goto out; 985 } 986 } 987 988 /* Success */ 989 if (userp != NULL) { 990 *userp = user; 991 user = NULL; 992 } 993 if (hostp != NULL) { 994 *hostp = host; 995 host = NULL; 996 } 997 if (portp != NULL) 998 *portp = port; 999 if (pathp != NULL) { 1000 *pathp = path; 1001 path = NULL; 1002 } 1003 ret = 0; 1004 out: 1005 free(uridup); 1006 free(user); 1007 free(host); 1008 free(path); 1009 return ret; 1010 } 1011 1012 /* function to assist building execv() arguments */ 1013 void 1014 addargs(arglist *args, char *fmt, ...) 1015 { 1016 va_list ap; 1017 char *cp; 1018 u_int nalloc; 1019 int r; 1020 1021 va_start(ap, fmt); 1022 r = vasprintf(&cp, fmt, ap); 1023 va_end(ap); 1024 if (r == -1) 1025 fatal_f("argument too long"); 1026 1027 nalloc = args->nalloc; 1028 if (args->list == NULL) { 1029 nalloc = 32; 1030 args->num = 0; 1031 } else if (args->num > (256 * 1024)) 1032 fatal_f("too many arguments"); 1033 else if (args->num >= args->nalloc) 1034 fatal_f("arglist corrupt"); 1035 else if (args->num+2 >= nalloc) 1036 nalloc *= 2; 1037 1038 args->list = xrecallocarray(args->list, args->nalloc, 1039 nalloc, sizeof(char *)); 1040 args->nalloc = nalloc; 1041 args->list[args->num++] = cp; 1042 args->list[args->num] = NULL; 1043 } 1044 1045 void 1046 replacearg(arglist *args, u_int which, char *fmt, ...) 1047 { 1048 va_list ap; 1049 char *cp; 1050 int r; 1051 1052 va_start(ap, fmt); 1053 r = vasprintf(&cp, fmt, ap); 1054 va_end(ap); 1055 if (r == -1) 1056 fatal_f("argument too long"); 1057 if (args->list == NULL || args->num >= args->nalloc) 1058 fatal_f("arglist corrupt"); 1059 1060 if (which >= args->num) 1061 fatal_f("tried to replace invalid arg %d >= %d", 1062 which, args->num); 1063 free(args->list[which]); 1064 args->list[which] = cp; 1065 } 1066 1067 void 1068 freeargs(arglist *args) 1069 { 1070 u_int i; 1071 1072 if (args == NULL) 1073 return; 1074 if (args->list != NULL && args->num < args->nalloc) { 1075 for (i = 0; i < args->num; i++) 1076 free(args->list[i]); 1077 free(args->list); 1078 } 1079 args->nalloc = args->num = 0; 1080 args->list = NULL; 1081 } 1082 1083 /* 1084 * Expands tildes in the file name. Returns data allocated by xmalloc. 1085 * Warning: this calls getpw*. 1086 */ 1087 int 1088 tilde_expand(const char *filename, uid_t uid, char **retp) 1089 { 1090 char *ocopy = NULL, *copy, *s = NULL; 1091 const char *path = NULL, *user = NULL; 1092 struct passwd *pw; 1093 size_t len; 1094 int ret = -1, r, slash; 1095 1096 *retp = NULL; 1097 if (*filename != '~') { 1098 *retp = xstrdup(filename); 1099 return 0; 1100 } 1101 ocopy = copy = xstrdup(filename + 1); 1102 1103 if (*copy == '\0') /* ~ */ 1104 path = NULL; 1105 else if (*copy == '/') { 1106 copy += strspn(copy, "/"); 1107 if (*copy == '\0') 1108 path = NULL; /* ~/ */ 1109 else 1110 path = copy; /* ~/path */ 1111 } else { 1112 user = copy; 1113 if ((path = strchr(copy, '/')) != NULL) { 1114 copy[path - copy] = '\0'; 1115 path++; 1116 path += strspn(path, "/"); 1117 if (*path == '\0') /* ~user/ */ 1118 path = NULL; 1119 /* else ~user/path */ 1120 } 1121 /* else ~user */ 1122 } 1123 if (user != NULL) { 1124 if ((pw = getpwnam(user)) == NULL) { 1125 error_f("No such user %s", user); 1126 goto out; 1127 } 1128 } else if ((pw = getpwuid(uid)) == NULL) { 1129 error_f("No such uid %ld", (long)uid); 1130 goto out; 1131 } 1132 1133 /* Make sure directory has a trailing '/' */ 1134 slash = (len = strlen(pw->pw_dir)) == 0 || pw->pw_dir[len - 1] != '/'; 1135 1136 if ((r = xasprintf(&s, "%s%s%s", pw->pw_dir, 1137 slash ? "/" : "", path != NULL ? path : "")) <= 0) { 1138 error_f("xasprintf failed"); 1139 goto out; 1140 } 1141 if (r >= PATH_MAX) { 1142 error_f("Path too long"); 1143 goto out; 1144 } 1145 /* success */ 1146 ret = 0; 1147 *retp = s; 1148 s = NULL; 1149 out: 1150 free(s); 1151 free(ocopy); 1152 return ret; 1153 } 1154 1155 char * 1156 tilde_expand_filename(const char *filename, uid_t uid) 1157 { 1158 char *ret; 1159 1160 if (tilde_expand(filename, uid, &ret) != 0) 1161 cleanup_exit(255); 1162 return ret; 1163 } 1164 1165 /* 1166 * Expand a string with a set of %[char] escapes and/or ${ENVIRONMENT} 1167 * substitutions. A number of escapes may be specified as 1168 * (char *escape_chars, char *replacement) pairs. The list must be terminated 1169 * by a NULL escape_char. Returns replaced string in memory allocated by 1170 * xmalloc which the caller must free. 1171 */ 1172 static char * 1173 vdollar_percent_expand(int *parseerror, int dollar, int percent, 1174 const char *string, va_list ap) 1175 { 1176 #define EXPAND_MAX_KEYS 16 1177 u_int num_keys = 0, i; 1178 struct { 1179 const char *key; 1180 const char *repl; 1181 } keys[EXPAND_MAX_KEYS]; 1182 struct sshbuf *buf; 1183 int r, missingvar = 0; 1184 char *ret = NULL, *var, *varend, *val; 1185 size_t len; 1186 1187 if ((buf = sshbuf_new()) == NULL) 1188 fatal_f("sshbuf_new failed"); 1189 if (parseerror == NULL) 1190 fatal_f("null parseerror arg"); 1191 *parseerror = 1; 1192 1193 /* Gather keys if we're doing percent expansion. */ 1194 if (percent) { 1195 for (num_keys = 0; num_keys < EXPAND_MAX_KEYS; num_keys++) { 1196 keys[num_keys].key = va_arg(ap, char *); 1197 if (keys[num_keys].key == NULL) 1198 break; 1199 keys[num_keys].repl = va_arg(ap, char *); 1200 if (keys[num_keys].repl == NULL) { 1201 fatal_f("NULL replacement for token %s", 1202 keys[num_keys].key); 1203 } 1204 } 1205 if (num_keys == EXPAND_MAX_KEYS && va_arg(ap, char *) != NULL) 1206 fatal_f("too many keys"); 1207 if (num_keys == 0) 1208 fatal_f("percent expansion without token list"); 1209 } 1210 1211 /* Expand string */ 1212 for (i = 0; *string != '\0'; string++) { 1213 /* Optionally process ${ENVIRONMENT} expansions. */ 1214 if (dollar && string[0] == '$' && string[1] == '{') { 1215 string += 2; /* skip over '${' */ 1216 if ((varend = strchr(string, '}')) == NULL) { 1217 error_f("environment variable '%s' missing " 1218 "closing '}'", string); 1219 goto out; 1220 } 1221 len = varend - string; 1222 if (len == 0) { 1223 error_f("zero-length environment variable"); 1224 goto out; 1225 } 1226 var = xmalloc(len + 1); 1227 (void)strlcpy(var, string, len + 1); 1228 if ((val = getenv(var)) == NULL) { 1229 error_f("env var ${%s} has no value", var); 1230 missingvar = 1; 1231 } else { 1232 debug3_f("expand ${%s} -> '%s'", var, val); 1233 if ((r = sshbuf_put(buf, val, strlen(val))) !=0) 1234 fatal_fr(r, "sshbuf_put ${}"); 1235 } 1236 free(var); 1237 string += len; 1238 continue; 1239 } 1240 1241 /* 1242 * Process percent expansions if we have a list of TOKENs. 1243 * If we're not doing percent expansion everything just gets 1244 * appended here. 1245 */ 1246 if (*string != '%' || !percent) { 1247 append: 1248 if ((r = sshbuf_put_u8(buf, *string)) != 0) 1249 fatal_fr(r, "sshbuf_put_u8 %%"); 1250 continue; 1251 } 1252 string++; 1253 /* %% case */ 1254 if (*string == '%') 1255 goto append; 1256 if (*string == '\0') { 1257 error_f("invalid format"); 1258 goto out; 1259 } 1260 for (i = 0; i < num_keys; i++) { 1261 if (strchr(keys[i].key, *string) != NULL) { 1262 if ((r = sshbuf_put(buf, keys[i].repl, 1263 strlen(keys[i].repl))) != 0) 1264 fatal_fr(r, "sshbuf_put %%-repl"); 1265 break; 1266 } 1267 } 1268 if (i >= num_keys) { 1269 error_f("unknown key %%%c", *string); 1270 goto out; 1271 } 1272 } 1273 if (!missingvar && (ret = sshbuf_dup_string(buf)) == NULL) 1274 fatal_f("sshbuf_dup_string failed"); 1275 *parseerror = 0; 1276 out: 1277 sshbuf_free(buf); 1278 return *parseerror ? NULL : ret; 1279 #undef EXPAND_MAX_KEYS 1280 } 1281 1282 /* 1283 * Expand only environment variables. 1284 * Note that although this function is variadic like the other similar 1285 * functions, any such arguments will be unused. 1286 */ 1287 1288 char * 1289 dollar_expand(int *parseerr, const char *string, ...) 1290 { 1291 char *ret; 1292 int err; 1293 va_list ap; 1294 1295 va_start(ap, string); 1296 ret = vdollar_percent_expand(&err, 1, 0, string, ap); 1297 va_end(ap); 1298 if (parseerr != NULL) 1299 *parseerr = err; 1300 return ret; 1301 } 1302 1303 /* 1304 * Returns expanded string or NULL if a specified environment variable is 1305 * not defined, or calls fatal if the string is invalid. 1306 */ 1307 char * 1308 percent_expand(const char *string, ...) 1309 { 1310 char *ret; 1311 int err; 1312 va_list ap; 1313 1314 va_start(ap, string); 1315 ret = vdollar_percent_expand(&err, 0, 1, string, ap); 1316 va_end(ap); 1317 if (err) 1318 fatal_f("failed"); 1319 return ret; 1320 } 1321 1322 /* 1323 * Returns expanded string or NULL if a specified environment variable is 1324 * not defined, or calls fatal if the string is invalid. 1325 */ 1326 char * 1327 percent_dollar_expand(const char *string, ...) 1328 { 1329 char *ret; 1330 int err; 1331 va_list ap; 1332 1333 va_start(ap, string); 1334 ret = vdollar_percent_expand(&err, 1, 1, string, ap); 1335 va_end(ap); 1336 if (err) 1337 fatal_f("failed"); 1338 return ret; 1339 } 1340 1341 int 1342 tun_open(int tun, int mode, char **ifname) 1343 { 1344 struct ifreq ifr; 1345 char name[100]; 1346 int fd = -1, sock; 1347 const char *tunbase = "tun"; 1348 1349 if (ifname != NULL) 1350 *ifname = NULL; 1351 1352 if (mode == SSH_TUNMODE_ETHERNET) 1353 tunbase = "tap"; 1354 1355 /* Open the tunnel device */ 1356 if (tun <= SSH_TUNID_MAX) { 1357 snprintf(name, sizeof(name), "/dev/%s%d", tunbase, tun); 1358 fd = open(name, O_RDWR); 1359 } else if (tun == SSH_TUNID_ANY) { 1360 for (tun = 100; tun >= 0; tun--) { 1361 snprintf(name, sizeof(name), "/dev/%s%d", 1362 tunbase, tun); 1363 if ((fd = open(name, O_RDWR)) >= 0) 1364 break; 1365 } 1366 } else { 1367 debug_f("invalid tunnel %u", tun); 1368 return -1; 1369 } 1370 1371 if (fd == -1) { 1372 debug_f("%s open: %s", name, strerror(errno)); 1373 return -1; 1374 } 1375 1376 debug_f("%s mode %d fd %d", name, mode, fd); 1377 1378 /* Bring interface up if it is not already */ 1379 snprintf(ifr.ifr_name, sizeof(ifr.ifr_name), "%s%d", tunbase, tun); 1380 if ((sock = socket(PF_UNIX, SOCK_STREAM, 0)) == -1) 1381 goto failed; 1382 1383 if (ioctl(sock, SIOCGIFFLAGS, &ifr) == -1) { 1384 debug_f("get interface %s flags: %s", ifr.ifr_name, 1385 strerror(errno)); 1386 goto failed; 1387 } 1388 1389 if (!(ifr.ifr_flags & IFF_UP)) { 1390 ifr.ifr_flags |= IFF_UP; 1391 if (ioctl(sock, SIOCSIFFLAGS, &ifr) == -1) { 1392 debug_f("activate interface %s: %s", ifr.ifr_name, 1393 strerror(errno)); 1394 goto failed; 1395 } 1396 } 1397 1398 if (ifname != NULL) 1399 *ifname = xstrdup(ifr.ifr_name); 1400 1401 close(sock); 1402 return fd; 1403 1404 failed: 1405 if (fd >= 0) 1406 close(fd); 1407 if (sock >= 0) 1408 close(sock); 1409 return -1; 1410 } 1411 1412 void 1413 sanitise_stdfd(void) 1414 { 1415 int nullfd, dupfd; 1416 1417 if ((nullfd = dupfd = open(_PATH_DEVNULL, O_RDWR)) == -1) { 1418 fprintf(stderr, "Couldn't open /dev/null: %s\n", 1419 strerror(errno)); 1420 exit(1); 1421 } 1422 while (++dupfd <= STDERR_FILENO) { 1423 /* Only populate closed fds. */ 1424 if (fcntl(dupfd, F_GETFL) == -1 && errno == EBADF) { 1425 if (dup2(nullfd, dupfd) == -1) { 1426 fprintf(stderr, "dup2: %s\n", strerror(errno)); 1427 exit(1); 1428 } 1429 } 1430 } 1431 if (nullfd > STDERR_FILENO) 1432 close(nullfd); 1433 } 1434 1435 char * 1436 tohex(const void *vp, size_t l) 1437 { 1438 const u_char *p = (const u_char *)vp; 1439 char b[3], *r; 1440 size_t i, hl; 1441 1442 if (l > 65536) 1443 return xstrdup("tohex: length > 65536"); 1444 1445 hl = l * 2 + 1; 1446 r = xcalloc(1, hl); 1447 for (i = 0; i < l; i++) { 1448 snprintf(b, sizeof(b), "%02x", p[i]); 1449 strlcat(r, b, hl); 1450 } 1451 return (r); 1452 } 1453 1454 /* 1455 * Extend string *sp by the specified format. If *sp is not NULL (or empty), 1456 * then the separator 'sep' will be prepended before the formatted arguments. 1457 * Extended strings are heap allocated. 1458 */ 1459 void 1460 xextendf(char **sp, const char *sep, const char *fmt, ...) 1461 { 1462 va_list ap; 1463 char *tmp1, *tmp2; 1464 1465 va_start(ap, fmt); 1466 xvasprintf(&tmp1, fmt, ap); 1467 va_end(ap); 1468 1469 if (*sp == NULL || **sp == '\0') { 1470 free(*sp); 1471 *sp = tmp1; 1472 return; 1473 } 1474 xasprintf(&tmp2, "%s%s%s", *sp, sep == NULL ? "" : sep, tmp1); 1475 free(tmp1); 1476 free(*sp); 1477 *sp = tmp2; 1478 } 1479 1480 1481 u_int64_t 1482 get_u64(const void *vp) 1483 { 1484 const u_char *p = (const u_char *)vp; 1485 u_int64_t v; 1486 1487 v = (u_int64_t)p[0] << 56; 1488 v |= (u_int64_t)p[1] << 48; 1489 v |= (u_int64_t)p[2] << 40; 1490 v |= (u_int64_t)p[3] << 32; 1491 v |= (u_int64_t)p[4] << 24; 1492 v |= (u_int64_t)p[5] << 16; 1493 v |= (u_int64_t)p[6] << 8; 1494 v |= (u_int64_t)p[7]; 1495 1496 return (v); 1497 } 1498 1499 u_int32_t 1500 get_u32(const void *vp) 1501 { 1502 const u_char *p = (const u_char *)vp; 1503 u_int32_t v; 1504 1505 v = (u_int32_t)p[0] << 24; 1506 v |= (u_int32_t)p[1] << 16; 1507 v |= (u_int32_t)p[2] << 8; 1508 v |= (u_int32_t)p[3]; 1509 1510 return (v); 1511 } 1512 1513 u_int32_t 1514 get_u32_le(const void *vp) 1515 { 1516 const u_char *p = (const u_char *)vp; 1517 u_int32_t v; 1518 1519 v = (u_int32_t)p[0]; 1520 v |= (u_int32_t)p[1] << 8; 1521 v |= (u_int32_t)p[2] << 16; 1522 v |= (u_int32_t)p[3] << 24; 1523 1524 return (v); 1525 } 1526 1527 u_int16_t 1528 get_u16(const void *vp) 1529 { 1530 const u_char *p = (const u_char *)vp; 1531 u_int16_t v; 1532 1533 v = (u_int16_t)p[0] << 8; 1534 v |= (u_int16_t)p[1]; 1535 1536 return (v); 1537 } 1538 1539 void 1540 put_u64(void *vp, u_int64_t v) 1541 { 1542 u_char *p = (u_char *)vp; 1543 1544 p[0] = (u_char)(v >> 56) & 0xff; 1545 p[1] = (u_char)(v >> 48) & 0xff; 1546 p[2] = (u_char)(v >> 40) & 0xff; 1547 p[3] = (u_char)(v >> 32) & 0xff; 1548 p[4] = (u_char)(v >> 24) & 0xff; 1549 p[5] = (u_char)(v >> 16) & 0xff; 1550 p[6] = (u_char)(v >> 8) & 0xff; 1551 p[7] = (u_char)v & 0xff; 1552 } 1553 1554 void 1555 put_u32(void *vp, u_int32_t v) 1556 { 1557 u_char *p = (u_char *)vp; 1558 1559 p[0] = (u_char)(v >> 24) & 0xff; 1560 p[1] = (u_char)(v >> 16) & 0xff; 1561 p[2] = (u_char)(v >> 8) & 0xff; 1562 p[3] = (u_char)v & 0xff; 1563 } 1564 1565 void 1566 put_u32_le(void *vp, u_int32_t v) 1567 { 1568 u_char *p = (u_char *)vp; 1569 1570 p[0] = (u_char)v & 0xff; 1571 p[1] = (u_char)(v >> 8) & 0xff; 1572 p[2] = (u_char)(v >> 16) & 0xff; 1573 p[3] = (u_char)(v >> 24) & 0xff; 1574 } 1575 1576 void 1577 put_u16(void *vp, u_int16_t v) 1578 { 1579 u_char *p = (u_char *)vp; 1580 1581 p[0] = (u_char)(v >> 8) & 0xff; 1582 p[1] = (u_char)v & 0xff; 1583 } 1584 1585 void 1586 ms_subtract_diff(struct timeval *start, int *ms) 1587 { 1588 struct timeval diff, finish; 1589 1590 monotime_tv(&finish); 1591 timersub(&finish, start, &diff); 1592 *ms -= (diff.tv_sec * 1000) + (diff.tv_usec / 1000); 1593 } 1594 1595 void 1596 ms_to_timespec(struct timespec *ts, int ms) 1597 { 1598 if (ms < 0) 1599 ms = 0; 1600 ts->tv_sec = ms / 1000; 1601 ts->tv_nsec = (ms % 1000) * 1000 * 1000; 1602 } 1603 1604 void 1605 monotime_ts(struct timespec *ts) 1606 { 1607 if (clock_gettime(CLOCK_MONOTONIC, ts) != 0) 1608 fatal("clock_gettime: %s", strerror(errno)); 1609 } 1610 1611 void 1612 monotime_tv(struct timeval *tv) 1613 { 1614 struct timespec ts; 1615 1616 monotime_ts(&ts); 1617 tv->tv_sec = ts.tv_sec; 1618 tv->tv_usec = ts.tv_nsec / 1000; 1619 } 1620 1621 time_t 1622 monotime(void) 1623 { 1624 struct timespec ts; 1625 1626 monotime_ts(&ts); 1627 return (ts.tv_sec); 1628 } 1629 1630 double 1631 monotime_double(void) 1632 { 1633 struct timespec ts; 1634 1635 monotime_ts(&ts); 1636 return (double)ts.tv_sec + (double)ts.tv_nsec / 1000000000.0; 1637 } 1638 1639 void 1640 bandwidth_limit_init(struct bwlimit *bw, u_int64_t kbps, size_t buflen) 1641 { 1642 bw->buflen = buflen; 1643 bw->rate = kbps; 1644 bw->thresh = buflen; 1645 bw->lamt = 0; 1646 timerclear(&bw->bwstart); 1647 timerclear(&bw->bwend); 1648 } 1649 1650 /* Callback from read/write loop to insert bandwidth-limiting delays */ 1651 void 1652 bandwidth_limit(struct bwlimit *bw, size_t read_len) 1653 { 1654 u_int64_t waitlen; 1655 struct timespec ts, rm; 1656 1657 bw->lamt += read_len; 1658 if (!timerisset(&bw->bwstart)) { 1659 monotime_tv(&bw->bwstart); 1660 return; 1661 } 1662 if (bw->lamt < bw->thresh) 1663 return; 1664 1665 monotime_tv(&bw->bwend); 1666 timersub(&bw->bwend, &bw->bwstart, &bw->bwend); 1667 if (!timerisset(&bw->bwend)) 1668 return; 1669 1670 bw->lamt *= 8; 1671 waitlen = (double)1000000L * bw->lamt / bw->rate; 1672 1673 bw->bwstart.tv_sec = waitlen / 1000000L; 1674 bw->bwstart.tv_usec = waitlen % 1000000L; 1675 1676 if (timercmp(&bw->bwstart, &bw->bwend, >)) { 1677 timersub(&bw->bwstart, &bw->bwend, &bw->bwend); 1678 1679 /* Adjust the wait time */ 1680 if (bw->bwend.tv_sec) { 1681 bw->thresh /= 2; 1682 if (bw->thresh < bw->buflen / 4) 1683 bw->thresh = bw->buflen / 4; 1684 } else if (bw->bwend.tv_usec < 10000) { 1685 bw->thresh *= 2; 1686 if (bw->thresh > bw->buflen * 8) 1687 bw->thresh = bw->buflen * 8; 1688 } 1689 1690 TIMEVAL_TO_TIMESPEC(&bw->bwend, &ts); 1691 while (nanosleep(&ts, &rm) == -1) { 1692 if (errno != EINTR) 1693 break; 1694 ts = rm; 1695 } 1696 } 1697 1698 bw->lamt = 0; 1699 monotime_tv(&bw->bwstart); 1700 } 1701 1702 /* Make a template filename for mk[sd]temp() */ 1703 void 1704 mktemp_proto(char *s, size_t len) 1705 { 1706 const char *tmpdir; 1707 int r; 1708 1709 if ((tmpdir = getenv("TMPDIR")) != NULL) { 1710 r = snprintf(s, len, "%s/ssh-XXXXXXXXXXXX", tmpdir); 1711 if (r > 0 && (size_t)r < len) 1712 return; 1713 } 1714 r = snprintf(s, len, "/tmp/ssh-XXXXXXXXXXXX"); 1715 if (r < 0 || (size_t)r >= len) 1716 fatal_f("template string too short"); 1717 } 1718 1719 static const struct { 1720 const char *name; 1721 int value; 1722 } ipqos[] = { 1723 { "none", INT_MAX }, /* can't use 0 here; that's CS0 */ 1724 { "af11", IPTOS_DSCP_AF11 }, 1725 { "af12", IPTOS_DSCP_AF12 }, 1726 { "af13", IPTOS_DSCP_AF13 }, 1727 { "af21", IPTOS_DSCP_AF21 }, 1728 { "af22", IPTOS_DSCP_AF22 }, 1729 { "af23", IPTOS_DSCP_AF23 }, 1730 { "af31", IPTOS_DSCP_AF31 }, 1731 { "af32", IPTOS_DSCP_AF32 }, 1732 { "af33", IPTOS_DSCP_AF33 }, 1733 { "af41", IPTOS_DSCP_AF41 }, 1734 { "af42", IPTOS_DSCP_AF42 }, 1735 { "af43", IPTOS_DSCP_AF43 }, 1736 { "cs0", IPTOS_DSCP_CS0 }, 1737 { "cs1", IPTOS_DSCP_CS1 }, 1738 { "cs2", IPTOS_DSCP_CS2 }, 1739 { "cs3", IPTOS_DSCP_CS3 }, 1740 { "cs4", IPTOS_DSCP_CS4 }, 1741 { "cs5", IPTOS_DSCP_CS5 }, 1742 { "cs6", IPTOS_DSCP_CS6 }, 1743 { "cs7", IPTOS_DSCP_CS7 }, 1744 { "ef", IPTOS_DSCP_EF }, 1745 { "le", IPTOS_DSCP_LE }, 1746 { "lowdelay", IPTOS_LOWDELAY }, 1747 { "throughput", IPTOS_THROUGHPUT }, 1748 { "reliability", IPTOS_RELIABILITY }, 1749 { NULL, -1 } 1750 }; 1751 1752 int 1753 parse_ipqos(const char *cp) 1754 { 1755 u_int i; 1756 char *ep; 1757 long val; 1758 1759 if (cp == NULL) 1760 return -1; 1761 for (i = 0; ipqos[i].name != NULL; i++) { 1762 if (strcasecmp(cp, ipqos[i].name) == 0) 1763 return ipqos[i].value; 1764 } 1765 /* Try parsing as an integer */ 1766 val = strtol(cp, &ep, 0); 1767 if (*cp == '\0' || *ep != '\0' || val < 0 || val > 255) 1768 return -1; 1769 return val; 1770 } 1771 1772 const char * 1773 iptos2str(int iptos) 1774 { 1775 int i; 1776 static char iptos_str[sizeof "0xff"]; 1777 1778 for (i = 0; ipqos[i].name != NULL; i++) { 1779 if (ipqos[i].value == iptos) 1780 return ipqos[i].name; 1781 } 1782 snprintf(iptos_str, sizeof iptos_str, "0x%02x", iptos); 1783 return iptos_str; 1784 } 1785 1786 void 1787 lowercase(char *s) 1788 { 1789 for (; *s; s++) 1790 *s = tolower((u_char)*s); 1791 } 1792 1793 int 1794 unix_listener(const char *path, int backlog, int unlink_first) 1795 { 1796 struct sockaddr_un sunaddr; 1797 int saved_errno, sock; 1798 1799 memset(&sunaddr, 0, sizeof(sunaddr)); 1800 sunaddr.sun_family = AF_UNIX; 1801 if (strlcpy(sunaddr.sun_path, path, 1802 sizeof(sunaddr.sun_path)) >= sizeof(sunaddr.sun_path)) { 1803 error_f("path \"%s\" too long for Unix domain socket", path); 1804 errno = ENAMETOOLONG; 1805 return -1; 1806 } 1807 1808 sock = socket(PF_UNIX, SOCK_STREAM, 0); 1809 if (sock == -1) { 1810 saved_errno = errno; 1811 error_f("socket: %.100s", strerror(errno)); 1812 errno = saved_errno; 1813 return -1; 1814 } 1815 if (unlink_first == 1) { 1816 if (unlink(path) != 0 && errno != ENOENT) 1817 error("unlink(%s): %.100s", path, strerror(errno)); 1818 } 1819 if (bind(sock, (struct sockaddr *)&sunaddr, sizeof(sunaddr)) == -1) { 1820 saved_errno = errno; 1821 error_f("cannot bind to path %s: %s", path, strerror(errno)); 1822 close(sock); 1823 errno = saved_errno; 1824 return -1; 1825 } 1826 if (listen(sock, backlog) == -1) { 1827 saved_errno = errno; 1828 error_f("cannot listen on path %s: %s", path, strerror(errno)); 1829 close(sock); 1830 unlink(path); 1831 errno = saved_errno; 1832 return -1; 1833 } 1834 return sock; 1835 } 1836 1837 /* 1838 * Compares two strings that maybe be NULL. Returns non-zero if strings 1839 * are both NULL or are identical, returns zero otherwise. 1840 */ 1841 static int 1842 strcmp_maybe_null(const char *a, const char *b) 1843 { 1844 if ((a == NULL && b != NULL) || (a != NULL && b == NULL)) 1845 return 0; 1846 if (a != NULL && strcmp(a, b) != 0) 1847 return 0; 1848 return 1; 1849 } 1850 1851 /* 1852 * Compare two forwards, returning non-zero if they are identical or 1853 * zero otherwise. 1854 */ 1855 int 1856 forward_equals(const struct Forward *a, const struct Forward *b) 1857 { 1858 if (strcmp_maybe_null(a->listen_host, b->listen_host) == 0) 1859 return 0; 1860 if (a->listen_port != b->listen_port) 1861 return 0; 1862 if (strcmp_maybe_null(a->listen_path, b->listen_path) == 0) 1863 return 0; 1864 if (strcmp_maybe_null(a->connect_host, b->connect_host) == 0) 1865 return 0; 1866 if (a->connect_port != b->connect_port) 1867 return 0; 1868 if (strcmp_maybe_null(a->connect_path, b->connect_path) == 0) 1869 return 0; 1870 /* allocated_port and handle are not checked */ 1871 return 1; 1872 } 1873 1874 /* returns 1 if process is already daemonized, 0 otherwise */ 1875 int 1876 daemonized(void) 1877 { 1878 int fd; 1879 1880 if ((fd = open(_PATH_TTY, O_RDONLY | O_NOCTTY)) >= 0) { 1881 close(fd); 1882 return 0; /* have controlling terminal */ 1883 } 1884 if (getppid() != 1) 1885 return 0; /* parent is not init */ 1886 if (getsid(0) != getpid()) 1887 return 0; /* not session leader */ 1888 debug3("already daemonized"); 1889 return 1; 1890 } 1891 1892 /* 1893 * Splits 's' into an argument vector. Handles quoted string and basic 1894 * escape characters (\\, \", \'). Caller must free the argument vector 1895 * and its members. 1896 */ 1897 int 1898 argv_split(const char *s, int *argcp, char ***argvp, int terminate_on_comment) 1899 { 1900 int r = SSH_ERR_INTERNAL_ERROR; 1901 int argc = 0, quote, i, j; 1902 char *arg, **argv = xcalloc(1, sizeof(*argv)); 1903 1904 *argvp = NULL; 1905 *argcp = 0; 1906 1907 for (i = 0; s[i] != '\0'; i++) { 1908 /* Skip leading whitespace */ 1909 if (s[i] == ' ' || s[i] == '\t') 1910 continue; 1911 if (terminate_on_comment && s[i] == '#') 1912 break; 1913 /* Start of a token */ 1914 quote = 0; 1915 1916 argv = xreallocarray(argv, (argc + 2), sizeof(*argv)); 1917 arg = argv[argc++] = xcalloc(1, strlen(s + i) + 1); 1918 argv[argc] = NULL; 1919 1920 /* Copy the token in, removing escapes */ 1921 for (j = 0; s[i] != '\0'; i++) { 1922 if (s[i] == '\\') { 1923 if (s[i + 1] == '\'' || 1924 s[i + 1] == '\"' || 1925 s[i + 1] == '\\' || 1926 (quote == 0 && s[i + 1] == ' ')) { 1927 i++; /* Skip '\' */ 1928 arg[j++] = s[i]; 1929 } else { 1930 /* Unrecognised escape */ 1931 arg[j++] = s[i]; 1932 } 1933 } else if (quote == 0 && (s[i] == ' ' || s[i] == '\t')) 1934 break; /* done */ 1935 else if (quote == 0 && (s[i] == '\"' || s[i] == '\'')) 1936 quote = s[i]; /* quote start */ 1937 else if (quote != 0 && s[i] == quote) 1938 quote = 0; /* quote end */ 1939 else 1940 arg[j++] = s[i]; 1941 } 1942 if (s[i] == '\0') { 1943 if (quote != 0) { 1944 /* Ran out of string looking for close quote */ 1945 r = SSH_ERR_INVALID_FORMAT; 1946 goto out; 1947 } 1948 break; 1949 } 1950 } 1951 /* Success */ 1952 *argcp = argc; 1953 *argvp = argv; 1954 argc = 0; 1955 argv = NULL; 1956 r = 0; 1957 out: 1958 if (argc != 0 && argv != NULL) { 1959 for (i = 0; i < argc; i++) 1960 free(argv[i]); 1961 free(argv); 1962 } 1963 return r; 1964 } 1965 1966 /* 1967 * Reassemble an argument vector into a string, quoting and escaping as 1968 * necessary. Caller must free returned string. 1969 */ 1970 char * 1971 argv_assemble(int argc, char **argv) 1972 { 1973 int i, j, ws, r; 1974 char c, *ret; 1975 struct sshbuf *buf, *arg; 1976 1977 if ((buf = sshbuf_new()) == NULL || (arg = sshbuf_new()) == NULL) 1978 fatal_f("sshbuf_new failed"); 1979 1980 for (i = 0; i < argc; i++) { 1981 ws = 0; 1982 sshbuf_reset(arg); 1983 for (j = 0; argv[i][j] != '\0'; j++) { 1984 r = 0; 1985 c = argv[i][j]; 1986 switch (c) { 1987 case ' ': 1988 case '\t': 1989 ws = 1; 1990 r = sshbuf_put_u8(arg, c); 1991 break; 1992 case '\\': 1993 case '\'': 1994 case '"': 1995 if ((r = sshbuf_put_u8(arg, '\\')) != 0) 1996 break; 1997 /* FALLTHROUGH */ 1998 default: 1999 r = sshbuf_put_u8(arg, c); 2000 break; 2001 } 2002 if (r != 0) 2003 fatal_fr(r, "sshbuf_put_u8"); 2004 } 2005 if ((i != 0 && (r = sshbuf_put_u8(buf, ' ')) != 0) || 2006 (ws != 0 && (r = sshbuf_put_u8(buf, '"')) != 0) || 2007 (r = sshbuf_putb(buf, arg)) != 0 || 2008 (ws != 0 && (r = sshbuf_put_u8(buf, '"')) != 0)) 2009 fatal_fr(r, "assemble"); 2010 } 2011 if ((ret = malloc(sshbuf_len(buf) + 1)) == NULL) 2012 fatal_f("malloc failed"); 2013 memcpy(ret, sshbuf_ptr(buf), sshbuf_len(buf)); 2014 ret[sshbuf_len(buf)] = '\0'; 2015 sshbuf_free(buf); 2016 sshbuf_free(arg); 2017 return ret; 2018 } 2019 2020 char * 2021 argv_next(int *argcp, char ***argvp) 2022 { 2023 char *ret = (*argvp)[0]; 2024 2025 if (*argcp > 0 && ret != NULL) { 2026 (*argcp)--; 2027 (*argvp)++; 2028 } 2029 return ret; 2030 } 2031 2032 void 2033 argv_consume(int *argcp) 2034 { 2035 *argcp = 0; 2036 } 2037 2038 void 2039 argv_free(char **av, int ac) 2040 { 2041 int i; 2042 2043 if (av == NULL) 2044 return; 2045 for (i = 0; i < ac; i++) 2046 free(av[i]); 2047 free(av); 2048 } 2049 2050 /* Returns 0 if pid exited cleanly, non-zero otherwise */ 2051 int 2052 exited_cleanly(pid_t pid, const char *tag, const char *cmd, int quiet) 2053 { 2054 int status; 2055 2056 while (waitpid(pid, &status, 0) == -1) { 2057 if (errno != EINTR) { 2058 error("%s waitpid: %s", tag, strerror(errno)); 2059 return -1; 2060 } 2061 } 2062 if (WIFSIGNALED(status)) { 2063 error("%s %s exited on signal %d", tag, cmd, WTERMSIG(status)); 2064 return -1; 2065 } else if (WEXITSTATUS(status) != 0) { 2066 do_log2(quiet ? SYSLOG_LEVEL_DEBUG1 : SYSLOG_LEVEL_INFO, 2067 "%s %s failed, status %d", tag, cmd, WEXITSTATUS(status)); 2068 return -1; 2069 } 2070 return 0; 2071 } 2072 2073 /* 2074 * Check a given path for security. This is defined as all components 2075 * of the path to the file must be owned by either the owner of 2076 * of the file or root and no directories must be group or world writable. 2077 * 2078 * XXX Should any specific check be done for sym links ? 2079 * 2080 * Takes a file name, its stat information (preferably from fstat() to 2081 * avoid races), the uid of the expected owner, their home directory and an 2082 * error buffer plus max size as arguments. 2083 * 2084 * Returns 0 on success and -1 on failure 2085 */ 2086 int 2087 safe_path(const char *name, struct stat *stp, const char *pw_dir, 2088 uid_t uid, char *err, size_t errlen) 2089 { 2090 char buf[PATH_MAX], homedir[PATH_MAX]; 2091 char *cp; 2092 int comparehome = 0; 2093 struct stat st; 2094 2095 if (realpath(name, buf) == NULL) { 2096 snprintf(err, errlen, "realpath %s failed: %s", name, 2097 strerror(errno)); 2098 return -1; 2099 } 2100 if (pw_dir != NULL && realpath(pw_dir, homedir) != NULL) 2101 comparehome = 1; 2102 2103 if (!S_ISREG(stp->st_mode)) { 2104 snprintf(err, errlen, "%s is not a regular file", buf); 2105 return -1; 2106 } 2107 if ((stp->st_uid != 0 && stp->st_uid != uid) || 2108 (stp->st_mode & 022) != 0) { 2109 snprintf(err, errlen, "bad ownership or modes for file %s", 2110 buf); 2111 return -1; 2112 } 2113 2114 /* for each component of the canonical path, walking upwards */ 2115 for (;;) { 2116 if ((cp = dirname(buf)) == NULL) { 2117 snprintf(err, errlen, "dirname() failed"); 2118 return -1; 2119 } 2120 strlcpy(buf, cp, sizeof(buf)); 2121 2122 if (stat(buf, &st) == -1 || 2123 (st.st_uid != 0 && st.st_uid != uid) || 2124 (st.st_mode & 022) != 0) { 2125 snprintf(err, errlen, 2126 "bad ownership or modes for directory %s", buf); 2127 return -1; 2128 } 2129 2130 /* If are past the homedir then we can stop */ 2131 if (comparehome && strcmp(homedir, buf) == 0) 2132 break; 2133 2134 /* 2135 * dirname should always complete with a "/" path, 2136 * but we can be paranoid and check for "." too 2137 */ 2138 if ((strcmp("/", buf) == 0) || (strcmp(".", buf) == 0)) 2139 break; 2140 } 2141 return 0; 2142 } 2143 2144 /* 2145 * Version of safe_path() that accepts an open file descriptor to 2146 * avoid races. 2147 * 2148 * Returns 0 on success and -1 on failure 2149 */ 2150 int 2151 safe_path_fd(int fd, const char *file, struct passwd *pw, 2152 char *err, size_t errlen) 2153 { 2154 struct stat st; 2155 2156 /* check the open file to avoid races */ 2157 if (fstat(fd, &st) == -1) { 2158 snprintf(err, errlen, "cannot stat file %s: %s", 2159 file, strerror(errno)); 2160 return -1; 2161 } 2162 return safe_path(file, &st, pw->pw_dir, pw->pw_uid, err, errlen); 2163 } 2164 2165 /* 2166 * Sets the value of the given variable in the environment. If the variable 2167 * already exists, its value is overridden. 2168 */ 2169 void 2170 child_set_env(char ***envp, u_int *envsizep, const char *name, 2171 const char *value) 2172 { 2173 char **env; 2174 u_int envsize; 2175 u_int i, namelen; 2176 2177 if (strchr(name, '=') != NULL) { 2178 error("Invalid environment variable \"%.100s\"", name); 2179 return; 2180 } 2181 2182 /* 2183 * Find the slot where the value should be stored. If the variable 2184 * already exists, we reuse the slot; otherwise we append a new slot 2185 * at the end of the array, expanding if necessary. 2186 */ 2187 env = *envp; 2188 namelen = strlen(name); 2189 for (i = 0; env[i]; i++) 2190 if (strncmp(env[i], name, namelen) == 0 && env[i][namelen] == '=') 2191 break; 2192 if (env[i]) { 2193 /* Reuse the slot. */ 2194 free(env[i]); 2195 } else { 2196 /* New variable. Expand if necessary. */ 2197 envsize = *envsizep; 2198 if (i >= envsize - 1) { 2199 if (envsize >= 1000) 2200 fatal("child_set_env: too many env vars"); 2201 envsize += 50; 2202 env = (*envp) = xreallocarray(env, envsize, sizeof(char *)); 2203 *envsizep = envsize; 2204 } 2205 /* Need to set the NULL pointer at end of array beyond the new slot. */ 2206 env[i + 1] = NULL; 2207 } 2208 2209 /* Allocate space and format the variable in the appropriate slot. */ 2210 /* XXX xasprintf */ 2211 env[i] = xmalloc(strlen(name) + 1 + strlen(value) + 1); 2212 snprintf(env[i], strlen(name) + 1 + strlen(value) + 1, "%s=%s", name, value); 2213 } 2214 2215 /* 2216 * Check and optionally lowercase a domain name, also removes trailing '.' 2217 * Returns 1 on success and 0 on failure, storing an error message in errstr. 2218 */ 2219 int 2220 valid_domain(char *name, int makelower, const char **errstr) 2221 { 2222 size_t i, l = strlen(name); 2223 u_char c, last = '\0'; 2224 static char errbuf[256]; 2225 2226 if (l == 0) { 2227 strlcpy(errbuf, "empty domain name", sizeof(errbuf)); 2228 goto bad; 2229 } 2230 if (!isalpha((u_char)name[0]) && !isdigit((u_char)name[0])) { 2231 snprintf(errbuf, sizeof(errbuf), "domain name \"%.100s\" " 2232 "starts with invalid character", name); 2233 goto bad; 2234 } 2235 for (i = 0; i < l; i++) { 2236 c = tolower((u_char)name[i]); 2237 if (makelower) 2238 name[i] = (char)c; 2239 if (last == '.' && c == '.') { 2240 snprintf(errbuf, sizeof(errbuf), "domain name " 2241 "\"%.100s\" contains consecutive separators", name); 2242 goto bad; 2243 } 2244 if (c != '.' && c != '-' && !isalnum(c) && 2245 c != '_') /* technically invalid, but common */ { 2246 snprintf(errbuf, sizeof(errbuf), "domain name " 2247 "\"%.100s\" contains invalid characters", name); 2248 goto bad; 2249 } 2250 last = c; 2251 } 2252 if (name[l - 1] == '.') 2253 name[l - 1] = '\0'; 2254 if (errstr != NULL) 2255 *errstr = NULL; 2256 return 1; 2257 bad: 2258 if (errstr != NULL) 2259 *errstr = errbuf; 2260 return 0; 2261 } 2262 2263 /* 2264 * Verify that a environment variable name (not including initial '$') is 2265 * valid; consisting of one or more alphanumeric or underscore characters only. 2266 * Returns 1 on valid, 0 otherwise. 2267 */ 2268 int 2269 valid_env_name(const char *name) 2270 { 2271 const char *cp; 2272 2273 if (name[0] == '\0') 2274 return 0; 2275 for (cp = name; *cp != '\0'; cp++) { 2276 if (!isalnum((u_char)*cp) && *cp != '_') 2277 return 0; 2278 } 2279 return 1; 2280 } 2281 2282 const char * 2283 atoi_err(const char *nptr, int *val) 2284 { 2285 const char *errstr = NULL; 2286 long long num; 2287 2288 if (nptr == NULL || *nptr == '\0') 2289 return "missing"; 2290 num = strtonum(nptr, 0, INT_MAX, &errstr); 2291 if (errstr == NULL) 2292 *val = (int)num; 2293 return errstr; 2294 } 2295 2296 int 2297 parse_absolute_time(const char *s, uint64_t *tp) 2298 { 2299 struct tm tm; 2300 time_t tt; 2301 char buf[32], *fmt; 2302 const char *cp; 2303 size_t l; 2304 int is_utc = 0; 2305 2306 *tp = 0; 2307 2308 l = strlen(s); 2309 if (l > 1 && strcasecmp(s + l - 1, "Z") == 0) { 2310 is_utc = 1; 2311 l--; 2312 } else if (l > 3 && strcasecmp(s + l - 3, "UTC") == 0) { 2313 is_utc = 1; 2314 l -= 3; 2315 } 2316 /* 2317 * POSIX strptime says "The application shall ensure that there 2318 * is white-space or other non-alphanumeric characters between 2319 * any two conversion specifications" so arrange things this way. 2320 */ 2321 switch (l) { 2322 case 8: /* YYYYMMDD */ 2323 fmt = "%Y-%m-%d"; 2324 snprintf(buf, sizeof(buf), "%.4s-%.2s-%.2s", s, s + 4, s + 6); 2325 break; 2326 case 12: /* YYYYMMDDHHMM */ 2327 fmt = "%Y-%m-%dT%H:%M"; 2328 snprintf(buf, sizeof(buf), "%.4s-%.2s-%.2sT%.2s:%.2s", 2329 s, s + 4, s + 6, s + 8, s + 10); 2330 break; 2331 case 14: /* YYYYMMDDHHMMSS */ 2332 fmt = "%Y-%m-%dT%H:%M:%S"; 2333 snprintf(buf, sizeof(buf), "%.4s-%.2s-%.2sT%.2s:%.2s:%.2s", 2334 s, s + 4, s + 6, s + 8, s + 10, s + 12); 2335 break; 2336 default: 2337 return SSH_ERR_INVALID_FORMAT; 2338 } 2339 2340 memset(&tm, 0, sizeof(tm)); 2341 if ((cp = strptime(buf, fmt, &tm)) == NULL || *cp != '\0') 2342 return SSH_ERR_INVALID_FORMAT; 2343 if (is_utc) { 2344 if ((tt = timegm(&tm)) < 0) 2345 return SSH_ERR_INVALID_FORMAT; 2346 } else { 2347 if ((tt = mktime(&tm)) < 0) 2348 return SSH_ERR_INVALID_FORMAT; 2349 } 2350 /* success */ 2351 *tp = (uint64_t)tt; 2352 return 0; 2353 } 2354 2355 void 2356 format_absolute_time(uint64_t t, char *buf, size_t len) 2357 { 2358 time_t tt = t > SSH_TIME_T_MAX ? SSH_TIME_T_MAX : t; 2359 struct tm tm; 2360 2361 localtime_r(&tt, &tm); 2362 strftime(buf, len, "%Y-%m-%dT%H:%M:%S", &tm); 2363 } 2364 2365 /* check if path is absolute */ 2366 int 2367 path_absolute(const char *path) 2368 { 2369 return (*path == '/') ? 1 : 0; 2370 } 2371 2372 void 2373 skip_space(char **cpp) 2374 { 2375 char *cp; 2376 2377 for (cp = *cpp; *cp == ' ' || *cp == '\t'; cp++) 2378 ; 2379 *cpp = cp; 2380 } 2381 2382 /* authorized_key-style options parsing helpers */ 2383 2384 /* 2385 * Match flag 'opt' in *optsp, and if allow_negate is set then also match 2386 * 'no-opt'. Returns -1 if option not matched, 1 if option matches or 0 2387 * if negated option matches. 2388 * If the option or negated option matches, then *optsp is updated to 2389 * point to the first character after the option. 2390 */ 2391 int 2392 opt_flag(const char *opt, int allow_negate, const char **optsp) 2393 { 2394 size_t opt_len = strlen(opt); 2395 const char *opts = *optsp; 2396 int negate = 0; 2397 2398 if (allow_negate && strncasecmp(opts, "no-", 3) == 0) { 2399 opts += 3; 2400 negate = 1; 2401 } 2402 if (strncasecmp(opts, opt, opt_len) == 0) { 2403 *optsp = opts + opt_len; 2404 return negate ? 0 : 1; 2405 } 2406 return -1; 2407 } 2408 2409 char * 2410 opt_dequote(const char **sp, const char **errstrp) 2411 { 2412 const char *s = *sp; 2413 char *ret; 2414 size_t i; 2415 2416 *errstrp = NULL; 2417 if (*s != '"') { 2418 *errstrp = "missing start quote"; 2419 return NULL; 2420 } 2421 s++; 2422 if ((ret = malloc(strlen((s)) + 1)) == NULL) { 2423 *errstrp = "memory allocation failed"; 2424 return NULL; 2425 } 2426 for (i = 0; *s != '\0' && *s != '"';) { 2427 if (s[0] == '\\' && s[1] == '"') 2428 s++; 2429 ret[i++] = *s++; 2430 } 2431 if (*s == '\0') { 2432 *errstrp = "missing end quote"; 2433 free(ret); 2434 return NULL; 2435 } 2436 ret[i] = '\0'; 2437 s++; 2438 *sp = s; 2439 return ret; 2440 } 2441 2442 int 2443 opt_match(const char **opts, const char *term) 2444 { 2445 if (strncasecmp((*opts), term, strlen(term)) == 0 && 2446 (*opts)[strlen(term)] == '=') { 2447 *opts += strlen(term) + 1; 2448 return 1; 2449 } 2450 return 0; 2451 } 2452 2453 void 2454 opt_array_append2(const char *file, const int line, const char *directive, 2455 char ***array, int **iarray, u_int *lp, const char *s, int i) 2456 { 2457 2458 if (*lp >= INT_MAX) 2459 fatal("%s line %d: Too many %s entries", file, line, directive); 2460 2461 if (iarray != NULL) { 2462 *iarray = xrecallocarray(*iarray, *lp, *lp + 1, 2463 sizeof(**iarray)); 2464 (*iarray)[*lp] = i; 2465 } 2466 2467 *array = xrecallocarray(*array, *lp, *lp + 1, sizeof(**array)); 2468 (*array)[*lp] = xstrdup(s); 2469 (*lp)++; 2470 } 2471 2472 void 2473 opt_array_append(const char *file, const int line, const char *directive, 2474 char ***array, u_int *lp, const char *s) 2475 { 2476 opt_array_append2(file, line, directive, array, NULL, lp, s, 0); 2477 } 2478 2479 sshsig_t 2480 ssh_signal(int signum, sshsig_t handler) 2481 { 2482 struct sigaction sa, osa; 2483 2484 /* mask all other signals while in handler */ 2485 memset(&sa, 0, sizeof(sa)); 2486 sa.sa_handler = handler; 2487 sigfillset(&sa.sa_mask); 2488 if (signum != SIGALRM) 2489 sa.sa_flags = SA_RESTART; 2490 if (sigaction(signum, &sa, &osa) == -1) { 2491 debug3("sigaction(%s): %s", strsignal(signum), strerror(errno)); 2492 return SIG_ERR; 2493 } 2494 return osa.sa_handler; 2495 } 2496 2497 int 2498 stdfd_devnull(int do_stdin, int do_stdout, int do_stderr) 2499 { 2500 int devnull, ret = 0; 2501 2502 if ((devnull = open(_PATH_DEVNULL, O_RDWR)) == -1) { 2503 error_f("open %s: %s", _PATH_DEVNULL, 2504 strerror(errno)); 2505 return -1; 2506 } 2507 if ((do_stdin && dup2(devnull, STDIN_FILENO) == -1) || 2508 (do_stdout && dup2(devnull, STDOUT_FILENO) == -1) || 2509 (do_stderr && dup2(devnull, STDERR_FILENO) == -1)) { 2510 error_f("dup2: %s", strerror(errno)); 2511 ret = -1; 2512 } 2513 if (devnull > STDERR_FILENO) 2514 close(devnull); 2515 return ret; 2516 } 2517 2518 /* 2519 * Runs command in a subprocess with a minimal environment. 2520 * Returns pid on success, 0 on failure. 2521 * The child stdout and stderr maybe captured, left attached or sent to 2522 * /dev/null depending on the contents of flags. 2523 * "tag" is prepended to log messages. 2524 * NB. "command" is only used for logging; the actual command executed is 2525 * av[0]. 2526 */ 2527 pid_t 2528 subprocess(const char *tag, const char *command, 2529 int ac, char **av, FILE **child, u_int flags, 2530 struct passwd *pw, privdrop_fn *drop_privs, privrestore_fn *restore_privs) 2531 { 2532 FILE *f = NULL; 2533 struct stat st; 2534 int fd, devnull, p[2], i; 2535 pid_t pid; 2536 char *cp, errmsg[512]; 2537 u_int nenv = 0; 2538 char **env = NULL; 2539 2540 /* If dropping privs, then must specify user and restore function */ 2541 if (drop_privs != NULL && (pw == NULL || restore_privs == NULL)) { 2542 error("%s: inconsistent arguments", tag); /* XXX fatal? */ 2543 return 0; 2544 } 2545 if (pw == NULL && (pw = getpwuid(getuid())) == NULL) { 2546 error("%s: no user for current uid", tag); 2547 return 0; 2548 } 2549 if (child != NULL) 2550 *child = NULL; 2551 2552 debug3_f("%s command \"%s\" running as %s (flags 0x%x)", 2553 tag, command, pw->pw_name, flags); 2554 2555 /* Check consistency */ 2556 if ((flags & SSH_SUBPROCESS_STDOUT_DISCARD) != 0 && 2557 (flags & SSH_SUBPROCESS_STDOUT_CAPTURE) != 0) { 2558 error_f("inconsistent flags"); 2559 return 0; 2560 } 2561 if (((flags & SSH_SUBPROCESS_STDOUT_CAPTURE) == 0) != (child == NULL)) { 2562 error_f("inconsistent flags/output"); 2563 return 0; 2564 } 2565 2566 /* 2567 * If executing an explicit binary, then verify the it exists 2568 * and appears safe-ish to execute 2569 */ 2570 if (!path_absolute(av[0])) { 2571 error("%s path is not absolute", tag); 2572 return 0; 2573 } 2574 if (drop_privs != NULL) 2575 drop_privs(pw); 2576 if (stat(av[0], &st) == -1) { 2577 error("Could not stat %s \"%s\": %s", tag, 2578 av[0], strerror(errno)); 2579 goto restore_return; 2580 } 2581 if ((flags & SSH_SUBPROCESS_UNSAFE_PATH) == 0 && 2582 safe_path(av[0], &st, NULL, 0, errmsg, sizeof(errmsg)) != 0) { 2583 error("Unsafe %s \"%s\": %s", tag, av[0], errmsg); 2584 goto restore_return; 2585 } 2586 /* Prepare to keep the child's stdout if requested */ 2587 if (pipe(p) == -1) { 2588 error("%s: pipe: %s", tag, strerror(errno)); 2589 restore_return: 2590 if (restore_privs != NULL) 2591 restore_privs(); 2592 return 0; 2593 } 2594 if (restore_privs != NULL) 2595 restore_privs(); 2596 2597 switch ((pid = fork())) { 2598 case -1: /* error */ 2599 error("%s: fork: %s", tag, strerror(errno)); 2600 close(p[0]); 2601 close(p[1]); 2602 return 0; 2603 case 0: /* child */ 2604 /* Prepare a minimal environment for the child. */ 2605 if ((flags & SSH_SUBPROCESS_PRESERVE_ENV) == 0) { 2606 nenv = 5; 2607 env = xcalloc(sizeof(*env), nenv); 2608 child_set_env(&env, &nenv, "PATH", _PATH_STDPATH); 2609 child_set_env(&env, &nenv, "USER", pw->pw_name); 2610 child_set_env(&env, &nenv, "LOGNAME", pw->pw_name); 2611 child_set_env(&env, &nenv, "HOME", pw->pw_dir); 2612 if ((cp = getenv("LANG")) != NULL) 2613 child_set_env(&env, &nenv, "LANG", cp); 2614 } 2615 2616 for (i = 1; i < NSIG; i++) 2617 ssh_signal(i, SIG_DFL); 2618 2619 if ((devnull = open(_PATH_DEVNULL, O_RDWR)) == -1) { 2620 error("%s: open %s: %s", tag, _PATH_DEVNULL, 2621 strerror(errno)); 2622 _exit(1); 2623 } 2624 if (dup2(devnull, STDIN_FILENO) == -1) { 2625 error("%s: dup2: %s", tag, strerror(errno)); 2626 _exit(1); 2627 } 2628 2629 /* Set up stdout as requested; leave stderr in place for now. */ 2630 fd = -1; 2631 if ((flags & SSH_SUBPROCESS_STDOUT_CAPTURE) != 0) 2632 fd = p[1]; 2633 else if ((flags & SSH_SUBPROCESS_STDOUT_DISCARD) != 0) 2634 fd = devnull; 2635 if (fd != -1 && dup2(fd, STDOUT_FILENO) == -1) { 2636 error("%s: dup2: %s", tag, strerror(errno)); 2637 _exit(1); 2638 } 2639 closefrom(STDERR_FILENO + 1); 2640 2641 if (geteuid() == 0 && 2642 initgroups(pw->pw_name, pw->pw_gid) == -1) { 2643 error("%s: initgroups(%s, %u): %s", tag, 2644 pw->pw_name, (u_int)pw->pw_gid, strerror(errno)); 2645 _exit(1); 2646 } 2647 if (setresgid(pw->pw_gid, pw->pw_gid, pw->pw_gid) == -1) { 2648 error("%s: setresgid %u: %s", tag, (u_int)pw->pw_gid, 2649 strerror(errno)); 2650 _exit(1); 2651 } 2652 if (setresuid(pw->pw_uid, pw->pw_uid, pw->pw_uid) == -1) { 2653 error("%s: setresuid %u: %s", tag, (u_int)pw->pw_uid, 2654 strerror(errno)); 2655 _exit(1); 2656 } 2657 /* stdin is pointed to /dev/null at this point */ 2658 if ((flags & SSH_SUBPROCESS_STDOUT_DISCARD) != 0 && 2659 dup2(STDIN_FILENO, STDERR_FILENO) == -1) { 2660 error("%s: dup2: %s", tag, strerror(errno)); 2661 _exit(1); 2662 } 2663 if (env != NULL) 2664 execve(av[0], av, env); 2665 else 2666 execv(av[0], av); 2667 error("%s %s \"%s\": %s", tag, env == NULL ? "execv" : "execve", 2668 command, strerror(errno)); 2669 _exit(127); 2670 default: /* parent */ 2671 break; 2672 } 2673 2674 close(p[1]); 2675 if ((flags & SSH_SUBPROCESS_STDOUT_CAPTURE) == 0) 2676 close(p[0]); 2677 else if ((f = fdopen(p[0], "r")) == NULL) { 2678 error("%s: fdopen: %s", tag, strerror(errno)); 2679 close(p[0]); 2680 /* Don't leave zombie child */ 2681 kill(pid, SIGTERM); 2682 while (waitpid(pid, NULL, 0) == -1 && errno == EINTR) 2683 ; 2684 return 0; 2685 } 2686 /* Success */ 2687 debug3_f("%s pid %ld", tag, (long)pid); 2688 if (child != NULL) 2689 *child = f; 2690 return pid; 2691 } 2692 2693 const char * 2694 lookup_env_in_list(const char *env, char * const *envs, size_t nenvs) 2695 { 2696 size_t i, envlen; 2697 2698 envlen = strlen(env); 2699 for (i = 0; i < nenvs; i++) { 2700 if (strncmp(envs[i], env, envlen) == 0 && 2701 envs[i][envlen] == '=') { 2702 return envs[i] + envlen + 1; 2703 } 2704 } 2705 return NULL; 2706 } 2707 2708 const char * 2709 lookup_setenv_in_list(const char *env, char * const *envs, size_t nenvs) 2710 { 2711 char *name, *cp; 2712 const char *ret; 2713 2714 name = xstrdup(env); 2715 if ((cp = strchr(name, '=')) == NULL) { 2716 free(name); 2717 return NULL; /* not env=val */ 2718 } 2719 *cp = '\0'; 2720 ret = lookup_env_in_list(name, envs, nenvs); 2721 free(name); 2722 return ret; 2723 } 2724 2725 /* 2726 * Helpers for managing poll(2)/ppoll(2) timeouts 2727 * Will remember the earliest deadline and return it for use in poll/ppoll. 2728 */ 2729 2730 /* Initialise a poll/ppoll timeout with an indefinite deadline */ 2731 void 2732 ptimeout_init(struct timespec *pt) 2733 { 2734 /* 2735 * Deliberately invalid for ppoll(2). 2736 * Will be converted to NULL in ptimeout_get_tspec() later. 2737 */ 2738 pt->tv_sec = -1; 2739 pt->tv_nsec = 0; 2740 } 2741 2742 /* Specify a poll/ppoll deadline of at most 'sec' seconds */ 2743 void 2744 ptimeout_deadline_sec(struct timespec *pt, long sec) 2745 { 2746 if (pt->tv_sec == -1 || pt->tv_sec >= sec) { 2747 pt->tv_sec = sec; 2748 pt->tv_nsec = 0; 2749 } 2750 } 2751 2752 /* Specify a poll/ppoll deadline of at most 'p' (timespec) */ 2753 static void 2754 ptimeout_deadline_tsp(struct timespec *pt, struct timespec *p) 2755 { 2756 if (pt->tv_sec == -1 || timespeccmp(pt, p, >=)) 2757 *pt = *p; 2758 } 2759 2760 /* Specify a poll/ppoll deadline of at most 'ms' milliseconds */ 2761 void 2762 ptimeout_deadline_ms(struct timespec *pt, long ms) 2763 { 2764 struct timespec p; 2765 2766 p.tv_sec = ms / 1000; 2767 p.tv_nsec = (ms % 1000) * 1000000; 2768 ptimeout_deadline_tsp(pt, &p); 2769 } 2770 2771 /* Specify a poll/ppoll deadline at wall clock monotime 'when' */ 2772 void 2773 ptimeout_deadline_monotime(struct timespec *pt, time_t when) 2774 { 2775 struct timespec now, t; 2776 2777 t.tv_sec = when; 2778 t.tv_nsec = 0; 2779 monotime_ts(&now); 2780 2781 if (timespeccmp(&now, &t, >=)) 2782 ptimeout_deadline_sec(pt, 0); 2783 else { 2784 timespecsub(&t, &now, &t); 2785 ptimeout_deadline_tsp(pt, &t); 2786 } 2787 } 2788 2789 /* Get a poll(2) timeout value in milliseconds */ 2790 int 2791 ptimeout_get_ms(struct timespec *pt) 2792 { 2793 if (pt->tv_sec == -1) 2794 return -1; 2795 if (pt->tv_sec >= (INT_MAX - (pt->tv_nsec / 1000000)) / 1000) 2796 return INT_MAX; 2797 return (pt->tv_sec * 1000) + (pt->tv_nsec / 1000000); 2798 } 2799 2800 /* Get a ppoll(2) timeout value as a timespec pointer */ 2801 struct timespec * 2802 ptimeout_get_tsp(struct timespec *pt) 2803 { 2804 return pt->tv_sec == -1 ? NULL : pt; 2805 } 2806 2807 /* Returns non-zero if a timeout has been set (i.e. is not indefinite) */ 2808 int 2809 ptimeout_isset(struct timespec *pt) 2810 { 2811 return pt->tv_sec != -1; 2812 } 2813