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