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

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