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

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