[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.148

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