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