[BACK]Return to misc.c CVS log [TXT][DIR] Up to [local] / src / usr.bin / ssh

Annotation of src/usr.bin/ssh/misc.c, Revision 1.173

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