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