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

1.74    ! stevesk     1: /* $OpenBSD: misc.c,v 1.73 2009/11/20 03:24:07 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.61      stevesk    30: #include <sys/param.h>
1.38      stevesk    31:
                     32: #include <net/if.h>
1.53      stevesk    33: #include <netinet/in.h>
1.44      stevesk    34: #include <netinet/tcp.h>
1.43      stevesk    35:
1.58      stevesk    36: #include <errno.h>
1.55      stevesk    37: #include <fcntl.h>
1.66      dtucker    38: #include <netdb.h>
1.43      stevesk    39: #include <paths.h>
1.54      stevesk    40: #include <pwd.h>
1.57      stevesk    41: #include <stdarg.h>
1.63      stevesk    42: #include <stdio.h>
1.62      stevesk    43: #include <stdlib.h>
1.60      stevesk    44: #include <string.h>
1.59      stevesk    45: #include <unistd.h>
1.1       markus     46:
1.64      deraadt    47: #include "xmalloc.h"
1.1       markus     48: #include "misc.h"
                     49: #include "log.h"
1.56      dtucker    50: #include "ssh.h"
1.1       markus     51:
1.12      markus     52: /* remove newline at end of string */
1.1       markus     53: char *
                     54: chop(char *s)
                     55: {
                     56:        char *t = s;
                     57:        while (*t) {
1.13      deraadt    58:                if (*t == '\n' || *t == '\r') {
1.1       markus     59:                        *t = '\0';
                     60:                        return s;
                     61:                }
                     62:                t++;
                     63:        }
                     64:        return s;
                     65:
                     66: }
                     67:
1.12      markus     68: /* set/unset filedescriptor to non-blocking */
1.24      djm        69: int
1.1       markus     70: set_nonblock(int fd)
                     71: {
                     72:        int val;
1.8       markus     73:
1.1       markus     74:        val = fcntl(fd, F_GETFL, 0);
                     75:        if (val < 0) {
                     76:                error("fcntl(%d, F_GETFL, 0): %s", fd, strerror(errno));
1.24      djm        77:                return (-1);
1.1       markus     78:        }
                     79:        if (val & O_NONBLOCK) {
1.24      djm        80:                debug3("fd %d is O_NONBLOCK", fd);
                     81:                return (0);
1.1       markus     82:        }
1.21      markus     83:        debug2("fd %d setting O_NONBLOCK", fd);
1.1       markus     84:        val |= O_NONBLOCK;
1.24      djm        85:        if (fcntl(fd, F_SETFL, val) == -1) {
                     86:                debug("fcntl(%d, F_SETFL, O_NONBLOCK): %s", fd,
                     87:                    strerror(errno));
                     88:                return (-1);
                     89:        }
                     90:        return (0);
1.8       markus     91: }
                     92:
1.24      djm        93: int
1.8       markus     94: unset_nonblock(int fd)
                     95: {
                     96:        int val;
                     97:
                     98:        val = fcntl(fd, F_GETFL, 0);
                     99:        if (val < 0) {
                    100:                error("fcntl(%d, F_GETFL, 0): %s", fd, strerror(errno));
1.24      djm       101:                return (-1);
1.8       markus    102:        }
                    103:        if (!(val & O_NONBLOCK)) {
1.24      djm       104:                debug3("fd %d is not O_NONBLOCK", fd);
                    105:                return (0);
1.8       markus    106:        }
1.10      markus    107:        debug("fd %d clearing O_NONBLOCK", fd);
1.8       markus    108:        val &= ~O_NONBLOCK;
1.24      djm       109:        if (fcntl(fd, F_SETFL, val) == -1) {
                    110:                debug("fcntl(%d, F_SETFL, ~O_NONBLOCK): %s",
1.18      markus    111:                    fd, strerror(errno));
1.24      djm       112:                return (-1);
                    113:        }
                    114:        return (0);
1.66      dtucker   115: }
                    116:
                    117: const char *
                    118: ssh_gai_strerror(int gaierr)
                    119: {
1.67      dtucker   120:        if (gaierr == EAI_SYSTEM)
                    121:                return strerror(errno);
                    122:        return gai_strerror(gaierr);
1.15      stevesk   123: }
                    124:
                    125: /* disable nagle on socket */
                    126: void
                    127: set_nodelay(int fd)
                    128: {
1.17      stevesk   129:        int opt;
                    130:        socklen_t optlen;
1.15      stevesk   131:
1.16      stevesk   132:        optlen = sizeof opt;
                    133:        if (getsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &opt, &optlen) == -1) {
1.23      markus    134:                debug("getsockopt TCP_NODELAY: %.100s", strerror(errno));
1.16      stevesk   135:                return;
                    136:        }
                    137:        if (opt == 1) {
                    138:                debug2("fd %d is TCP_NODELAY", fd);
                    139:                return;
                    140:        }
                    141:        opt = 1;
1.20      markus    142:        debug2("fd %d setting TCP_NODELAY", fd);
1.16      stevesk   143:        if (setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &opt, sizeof opt) == -1)
1.15      stevesk   144:                error("setsockopt TCP_NODELAY: %.100s", strerror(errno));
1.72      reyk      145: }
                    146:
                    147: /* open a socket in the specified routing domain */
                    148: int
                    149: socket_rdomain(int domain, int type, int protocol, int rdomain)
                    150: {
                    151:        int sock, ipproto = IPPROTO_IP;
                    152:
                    153:        if ((sock = socket(domain, type, protocol)) == -1)
                    154:                return (-1);
                    155:
                    156:        if (rdomain == -1)
                    157:                return (sock);
                    158:
                    159:        switch (domain) {
                    160:        case AF_INET6:
                    161:                ipproto = IPPROTO_IPV6;
                    162:                /* FALLTHROUGH */
                    163:        case AF_INET:
                    164:                debug2("socket %d af %d setting rdomain %d",
                    165:                    sock, domain, rdomain);
                    166:                if (setsockopt(sock, ipproto, SO_RDOMAIN, &rdomain,
                    167:                    sizeof(rdomain)) == -1) {
                    168:                        debug("setsockopt SO_RDOMAIN: %.100s",
                    169:                            strerror(errno));
                    170:                        close(sock);
                    171:                        return (-1);
                    172:                }
                    173:                break;
                    174:        default:
                    175:                debug("socket %d af %d does not support rdomain %d",
                    176:                    sock, domain, rdomain);
                    177:                close(sock);
                    178:                return (-1);
                    179:        }
                    180:
                    181:        return (sock);
1.1       markus    182: }
                    183:
                    184: /* Characters considered whitespace in strsep calls. */
                    185: #define WHITESPACE " \t\r\n"
1.46      dtucker   186: #define QUOTE  "\""
1.1       markus    187:
1.12      markus    188: /* return next token in configuration line */
1.1       markus    189: char *
                    190: strdelim(char **s)
                    191: {
                    192:        char *old;
                    193:        int wspace = 0;
                    194:
                    195:        if (*s == NULL)
                    196:                return NULL;
                    197:
                    198:        old = *s;
                    199:
1.46      dtucker   200:        *s = strpbrk(*s, WHITESPACE QUOTE "=");
1.1       markus    201:        if (*s == NULL)
                    202:                return (old);
                    203:
1.46      dtucker   204:        if (*s[0] == '\"') {
                    205:                memmove(*s, *s + 1, strlen(*s)); /* move nul too */
                    206:                /* Find matching quote */
                    207:                if ((*s = strpbrk(*s, QUOTE)) == NULL) {
                    208:                        return (NULL);          /* no matching quote */
                    209:                } else {
                    210:                        *s[0] = '\0';
                    211:                        return (old);
                    212:                }
                    213:        }
                    214:
1.1       markus    215:        /* Allow only one '=' to be skipped */
                    216:        if (*s[0] == '=')
                    217:                wspace = 1;
                    218:        *s[0] = '\0';
                    219:
1.46      dtucker   220:        /* Skip any extra whitespace after first token */
1.1       markus    221:        *s += strspn(*s + 1, WHITESPACE) + 1;
                    222:        if (*s[0] == '=' && !wspace)
                    223:                *s += strspn(*s + 1, WHITESPACE) + 1;
                    224:
                    225:        return (old);
1.2       markus    226: }
                    227:
                    228: struct passwd *
                    229: pwcopy(struct passwd *pw)
                    230: {
1.49      djm       231:        struct passwd *copy = xcalloc(1, sizeof(*copy));
1.4       deraadt   232:
1.2       markus    233:        copy->pw_name = xstrdup(pw->pw_name);
                    234:        copy->pw_passwd = xstrdup(pw->pw_passwd);
1.4       deraadt   235:        copy->pw_gecos = xstrdup(pw->pw_gecos);
1.2       markus    236:        copy->pw_uid = pw->pw_uid;
                    237:        copy->pw_gid = pw->pw_gid;
1.11      markus    238:        copy->pw_expire = pw->pw_expire;
                    239:        copy->pw_change = pw->pw_change;
1.2       markus    240:        copy->pw_class = xstrdup(pw->pw_class);
                    241:        copy->pw_dir = xstrdup(pw->pw_dir);
                    242:        copy->pw_shell = xstrdup(pw->pw_shell);
                    243:        return copy;
1.5       stevesk   244: }
                    245:
1.12      markus    246: /*
                    247:  * Convert ASCII string to TCP/IP port number.
1.70      djm       248:  * Port must be >=0 and <=65535.
                    249:  * Return -1 if invalid.
1.12      markus    250:  */
                    251: int
                    252: a2port(const char *s)
1.5       stevesk   253: {
1.70      djm       254:        long long port;
                    255:        const char *errstr;
1.5       stevesk   256:
1.70      djm       257:        port = strtonum(s, 0, 65535, &errstr);
                    258:        if (errstr != NULL)
                    259:                return -1;
                    260:        return (int)port;
1.74    ! stevesk   261: }
        !           262:
        !           263: int
        !           264: a2rdomain(const char *s)
        !           265: {
        !           266:        long long rdomain;
        !           267:        const char *errstr;
        !           268:
        !           269:        rdomain = strtonum(s, 0, RT_TABLEID_MAX, &errstr);
        !           270:        if (errstr != NULL)
        !           271:                return -1;
        !           272:        return (int)rdomain;
1.9       stevesk   273: }
                    274:
1.36      reyk      275: int
                    276: a2tun(const char *s, int *remote)
                    277: {
                    278:        const char *errstr = NULL;
                    279:        char *sp, *ep;
                    280:        int tun;
                    281:
                    282:        if (remote != NULL) {
1.37      reyk      283:                *remote = SSH_TUNID_ANY;
1.36      reyk      284:                sp = xstrdup(s);
                    285:                if ((ep = strchr(sp, ':')) == NULL) {
                    286:                        xfree(sp);
                    287:                        return (a2tun(s, NULL));
                    288:                }
                    289:                ep[0] = '\0'; ep++;
                    290:                *remote = a2tun(ep, NULL);
                    291:                tun = a2tun(sp, NULL);
                    292:                xfree(sp);
1.37      reyk      293:                return (*remote == SSH_TUNID_ERR ? *remote : tun);
1.36      reyk      294:        }
                    295:
                    296:        if (strcasecmp(s, "any") == 0)
1.37      reyk      297:                return (SSH_TUNID_ANY);
1.36      reyk      298:
1.37      reyk      299:        tun = strtonum(s, 0, SSH_TUNID_MAX, &errstr);
                    300:        if (errstr != NULL)
                    301:                return (SSH_TUNID_ERR);
1.36      reyk      302:
                    303:        return (tun);
                    304: }
                    305:
1.9       stevesk   306: #define SECONDS                1
                    307: #define MINUTES                (SECONDS * 60)
                    308: #define HOURS          (MINUTES * 60)
                    309: #define DAYS           (HOURS * 24)
                    310: #define WEEKS          (DAYS * 7)
                    311:
1.12      markus    312: /*
                    313:  * Convert a time string into seconds; format is
                    314:  * a sequence of:
                    315:  *      time[qualifier]
                    316:  *
                    317:  * Valid time qualifiers are:
                    318:  *      <none>  seconds
                    319:  *      s|S     seconds
                    320:  *      m|M     minutes
                    321:  *      h|H     hours
                    322:  *      d|D     days
                    323:  *      w|W     weeks
                    324:  *
                    325:  * Examples:
                    326:  *      90m     90 minutes
                    327:  *      1h30m   90 minutes
                    328:  *      2d      2 days
                    329:  *      1w      1 week
                    330:  *
                    331:  * Return -1 if time string is invalid.
                    332:  */
                    333: long
                    334: convtime(const char *s)
1.9       stevesk   335: {
                    336:        long total, secs;
                    337:        const char *p;
                    338:        char *endp;
                    339:
                    340:        errno = 0;
                    341:        total = 0;
                    342:        p = s;
                    343:
                    344:        if (p == NULL || *p == '\0')
                    345:                return -1;
                    346:
                    347:        while (*p) {
                    348:                secs = strtol(p, &endp, 10);
                    349:                if (p == endp ||
                    350:                    (errno == ERANGE && (secs == LONG_MIN || secs == LONG_MAX)) ||
                    351:                    secs < 0)
                    352:                        return -1;
                    353:
                    354:                switch (*endp++) {
                    355:                case '\0':
                    356:                        endp--;
1.48      deraadt   357:                        break;
1.9       stevesk   358:                case 's':
                    359:                case 'S':
                    360:                        break;
                    361:                case 'm':
                    362:                case 'M':
                    363:                        secs *= MINUTES;
                    364:                        break;
                    365:                case 'h':
                    366:                case 'H':
                    367:                        secs *= HOURS;
                    368:                        break;
                    369:                case 'd':
                    370:                case 'D':
                    371:                        secs *= DAYS;
                    372:                        break;
                    373:                case 'w':
                    374:                case 'W':
                    375:                        secs *= WEEKS;
                    376:                        break;
                    377:                default:
                    378:                        return -1;
                    379:                }
                    380:                total += secs;
                    381:                if (total < 0)
                    382:                        return -1;
                    383:                p = endp;
                    384:        }
                    385:
                    386:        return total;
1.56      dtucker   387: }
                    388:
                    389: /*
                    390:  * Returns a standardized host+port identifier string.
                    391:  * Caller must free returned string.
                    392:  */
                    393: char *
                    394: put_host_port(const char *host, u_short port)
                    395: {
                    396:        char *hoststr;
                    397:
                    398:        if (port == 0 || port == SSH_DEFAULT_PORT)
                    399:                return(xstrdup(host));
                    400:        if (asprintf(&hoststr, "[%s]:%d", host, (int)port) < 0)
                    401:                fatal("put_host_port: asprintf: %s", strerror(errno));
                    402:        debug3("put_host_port: %s", hoststr);
                    403:        return hoststr;
1.28      djm       404: }
                    405:
                    406: /*
                    407:  * Search for next delimiter between hostnames/addresses and ports.
                    408:  * Argument may be modified (for termination).
                    409:  * Returns *cp if parsing succeeds.
                    410:  * *cp is set to the start of the next delimiter, if one was found.
                    411:  * If this is the last field, *cp is set to NULL.
                    412:  */
                    413: char *
                    414: hpdelim(char **cp)
                    415: {
                    416:        char *s, *old;
                    417:
                    418:        if (cp == NULL || *cp == NULL)
                    419:                return NULL;
                    420:
                    421:        old = s = *cp;
                    422:        if (*s == '[') {
                    423:                if ((s = strchr(s, ']')) == NULL)
                    424:                        return NULL;
                    425:                else
                    426:                        s++;
                    427:        } else if ((s = strpbrk(s, ":/")) == NULL)
                    428:                s = *cp + strlen(*cp); /* skip to end (see first case below) */
                    429:
                    430:        switch (*s) {
                    431:        case '\0':
                    432:                *cp = NULL;     /* no more fields*/
                    433:                break;
1.29      deraadt   434:
1.28      djm       435:        case ':':
                    436:        case '/':
                    437:                *s = '\0';      /* terminate */
                    438:                *cp = s + 1;
                    439:                break;
1.29      deraadt   440:
1.28      djm       441:        default:
                    442:                return NULL;
                    443:        }
                    444:
                    445:        return old;
1.6       mouring   446: }
                    447:
                    448: char *
                    449: cleanhostname(char *host)
                    450: {
                    451:        if (*host == '[' && host[strlen(host) - 1] == ']') {
                    452:                host[strlen(host) - 1] = '\0';
                    453:                return (host + 1);
                    454:        } else
                    455:                return host;
                    456: }
                    457:
                    458: char *
                    459: colon(char *cp)
                    460: {
                    461:        int flag = 0;
                    462:
                    463:        if (*cp == ':')         /* Leading colon is part of file name. */
                    464:                return (0);
                    465:        if (*cp == '[')
                    466:                flag = 1;
                    467:
                    468:        for (; *cp; ++cp) {
                    469:                if (*cp == '@' && *(cp+1) == '[')
                    470:                        flag = 1;
                    471:                if (*cp == ']' && *(cp+1) == ':' && flag)
                    472:                        return (cp+1);
                    473:                if (*cp == ':' && !flag)
                    474:                        return (cp);
                    475:                if (*cp == '/')
                    476:                        return (0);
                    477:        }
                    478:        return (0);
1.7       mouring   479: }
                    480:
1.12      markus    481: /* function to assist building execv() arguments */
1.7       mouring   482: void
                    483: addargs(arglist *args, char *fmt, ...)
                    484: {
                    485:        va_list ap;
1.42      djm       486:        char *cp;
1.25      avsm      487:        u_int nalloc;
1.42      djm       488:        int r;
1.7       mouring   489:
                    490:        va_start(ap, fmt);
1.42      djm       491:        r = vasprintf(&cp, fmt, ap);
1.7       mouring   492:        va_end(ap);
1.42      djm       493:        if (r == -1)
                    494:                fatal("addargs: argument too long");
1.7       mouring   495:
1.22      markus    496:        nalloc = args->nalloc;
1.7       mouring   497:        if (args->list == NULL) {
1.22      markus    498:                nalloc = 32;
1.7       mouring   499:                args->num = 0;
1.22      markus    500:        } else if (args->num+2 >= nalloc)
                    501:                nalloc *= 2;
1.7       mouring   502:
1.50      djm       503:        args->list = xrealloc(args->list, nalloc, sizeof(char *));
1.22      markus    504:        args->nalloc = nalloc;
1.42      djm       505:        args->list[args->num++] = cp;
1.7       mouring   506:        args->list[args->num] = NULL;
1.42      djm       507: }
                    508:
                    509: void
                    510: replacearg(arglist *args, u_int which, char *fmt, ...)
                    511: {
                    512:        va_list ap;
                    513:        char *cp;
                    514:        int r;
                    515:
                    516:        va_start(ap, fmt);
                    517:        r = vasprintf(&cp, fmt, ap);
                    518:        va_end(ap);
                    519:        if (r == -1)
                    520:                fatal("replacearg: argument too long");
                    521:
                    522:        if (which >= args->num)
                    523:                fatal("replacearg: tried to replace invalid arg %d >= %d",
                    524:                    which, args->num);
                    525:        xfree(args->list[which]);
                    526:        args->list[which] = cp;
                    527: }
                    528:
                    529: void
                    530: freeargs(arglist *args)
                    531: {
                    532:        u_int i;
                    533:
                    534:        if (args->list != NULL) {
                    535:                for (i = 0; i < args->num; i++)
                    536:                        xfree(args->list[i]);
                    537:                xfree(args->list);
                    538:                args->nalloc = args->num = 0;
                    539:                args->list = NULL;
                    540:        }
1.30      djm       541: }
                    542:
                    543: /*
                    544:  * Expands tildes in the file name.  Returns data allocated by xmalloc.
                    545:  * Warning: this calls getpw*.
                    546:  */
                    547: char *
                    548: tilde_expand_filename(const char *filename, uid_t uid)
                    549: {
                    550:        const char *path;
                    551:        char user[128], ret[MAXPATHLEN];
                    552:        struct passwd *pw;
1.32      djm       553:        u_int len, slash;
1.30      djm       554:
                    555:        if (*filename != '~')
                    556:                return (xstrdup(filename));
                    557:        filename++;
                    558:
                    559:        path = strchr(filename, '/');
                    560:        if (path != NULL && path > filename) {          /* ~user/path */
1.32      djm       561:                slash = path - filename;
                    562:                if (slash > sizeof(user) - 1)
1.30      djm       563:                        fatal("tilde_expand_filename: ~username too long");
1.32      djm       564:                memcpy(user, filename, slash);
                    565:                user[slash] = '\0';
1.30      djm       566:                if ((pw = getpwnam(user)) == NULL)
                    567:                        fatal("tilde_expand_filename: No such user %s", user);
                    568:        } else if ((pw = getpwuid(uid)) == NULL)        /* ~/path */
1.69      dtucker   569:                fatal("tilde_expand_filename: No such uid %ld", (long)uid);
1.30      djm       570:
                    571:        if (strlcpy(ret, pw->pw_dir, sizeof(ret)) >= sizeof(ret))
                    572:                fatal("tilde_expand_filename: Path too long");
                    573:
                    574:        /* Make sure directory has a trailing '/' */
                    575:        len = strlen(pw->pw_dir);
                    576:        if ((len == 0 || pw->pw_dir[len - 1] != '/') &&
                    577:            strlcat(ret, "/", sizeof(ret)) >= sizeof(ret))
                    578:                fatal("tilde_expand_filename: Path too long");
                    579:
                    580:        /* Skip leading '/' from specified path */
                    581:        if (path != NULL)
                    582:                filename = path + 1;
                    583:        if (strlcat(ret, filename, sizeof(ret)) >= sizeof(ret))
                    584:                fatal("tilde_expand_filename: Path too long");
                    585:
                    586:        return (xstrdup(ret));
1.31      djm       587: }
                    588:
                    589: /*
                    590:  * Expand a string with a set of %[char] escapes. A number of escapes may be
                    591:  * specified as (char *escape_chars, char *replacement) pairs. The list must
1.34      dtucker   592:  * be terminated by a NULL escape_char. Returns replaced string in memory
1.31      djm       593:  * allocated by xmalloc.
                    594:  */
                    595: char *
                    596: percent_expand(const char *string, ...)
                    597: {
                    598: #define EXPAND_MAX_KEYS        16
1.73      djm       599:        u_int num_keys, i, j;
1.31      djm       600:        struct {
                    601:                const char *key;
                    602:                const char *repl;
                    603:        } keys[EXPAND_MAX_KEYS];
                    604:        char buf[4096];
                    605:        va_list ap;
                    606:
                    607:        /* Gather keys */
                    608:        va_start(ap, string);
                    609:        for (num_keys = 0; num_keys < EXPAND_MAX_KEYS; num_keys++) {
                    610:                keys[num_keys].key = va_arg(ap, char *);
                    611:                if (keys[num_keys].key == NULL)
                    612:                        break;
                    613:                keys[num_keys].repl = va_arg(ap, char *);
                    614:                if (keys[num_keys].repl == NULL)
1.73      djm       615:                        fatal("%s: NULL replacement", __func__);
1.31      djm       616:        }
1.73      djm       617:        if (num_keys == EXPAND_MAX_KEYS && va_arg(ap, char *) != NULL)
                    618:                fatal("%s: too many keys", __func__);
1.31      djm       619:        va_end(ap);
                    620:
                    621:        /* Expand string */
                    622:        *buf = '\0';
                    623:        for (i = 0; *string != '\0'; string++) {
                    624:                if (*string != '%') {
                    625:  append:
                    626:                        buf[i++] = *string;
                    627:                        if (i >= sizeof(buf))
1.73      djm       628:                                fatal("%s: string too long", __func__);
1.31      djm       629:                        buf[i] = '\0';
                    630:                        continue;
                    631:                }
                    632:                string++;
1.73      djm       633:                /* %% case */
1.31      djm       634:                if (*string == '%')
                    635:                        goto append;
                    636:                for (j = 0; j < num_keys; j++) {
                    637:                        if (strchr(keys[j].key, *string) != NULL) {
                    638:                                i = strlcat(buf, keys[j].repl, sizeof(buf));
                    639:                                if (i >= sizeof(buf))
1.73      djm       640:                                        fatal("%s: string too long", __func__);
1.31      djm       641:                                break;
                    642:                        }
                    643:                }
                    644:                if (j >= num_keys)
1.73      djm       645:                        fatal("%s: unknown key %%%c", __func__, *string);
1.31      djm       646:        }
                    647:        return (xstrdup(buf));
                    648: #undef EXPAND_MAX_KEYS
1.26      dtucker   649: }
                    650:
                    651: /*
                    652:  * Read an entire line from a public key file into a static buffer, discarding
                    653:  * lines that exceed the buffer size.  Returns 0 on success, -1 on failure.
                    654:  */
                    655: int
                    656: read_keyfile_line(FILE *f, const char *filename, char *buf, size_t bufsz,
1.27      dtucker   657:    u_long *lineno)
1.26      dtucker   658: {
                    659:        while (fgets(buf, bufsz, f) != NULL) {
1.65      ray       660:                if (buf[0] == '\0')
                    661:                        continue;
1.26      dtucker   662:                (*lineno)++;
                    663:                if (buf[strlen(buf) - 1] == '\n' || feof(f)) {
                    664:                        return 0;
                    665:                } else {
1.27      dtucker   666:                        debug("%s: %s line %lu exceeds size limit", __func__,
                    667:                            filename, *lineno);
1.26      dtucker   668:                        /* discard remainder of line */
1.29      deraadt   669:                        while (fgetc(f) != '\n' && !feof(f))
1.26      dtucker   670:                                ;       /* nothing */
                    671:                }
                    672:        }
                    673:        return -1;
1.36      reyk      674: }
                    675:
                    676: int
1.37      reyk      677: tun_open(int tun, int mode)
1.36      reyk      678: {
1.37      reyk      679:        struct ifreq ifr;
1.36      reyk      680:        char name[100];
1.37      reyk      681:        int fd = -1, sock;
1.36      reyk      682:
1.37      reyk      683:        /* Open the tunnel device */
                    684:        if (tun <= SSH_TUNID_MAX) {
1.36      reyk      685:                snprintf(name, sizeof(name), "/dev/tun%d", tun);
1.37      reyk      686:                fd = open(name, O_RDWR);
                    687:        } else if (tun == SSH_TUNID_ANY) {
                    688:                for (tun = 100; tun >= 0; tun--) {
                    689:                        snprintf(name, sizeof(name), "/dev/tun%d", tun);
                    690:                        if ((fd = open(name, O_RDWR)) >= 0)
                    691:                                break;
1.36      reyk      692:                }
                    693:        } else {
1.39      stevesk   694:                debug("%s: invalid tunnel %u", __func__, tun);
1.37      reyk      695:                return (-1);
                    696:        }
                    697:
                    698:        if (fd < 0) {
                    699:                debug("%s: %s open failed: %s", __func__, name, strerror(errno));
                    700:                return (-1);
1.36      reyk      701:        }
1.37      reyk      702:
                    703:        debug("%s: %s mode %d fd %d", __func__, name, mode, fd);
                    704:
                    705:        /* Set the tunnel device operation mode */
                    706:        snprintf(ifr.ifr_name, sizeof(ifr.ifr_name), "tun%d", tun);
                    707:        if ((sock = socket(PF_UNIX, SOCK_STREAM, 0)) == -1)
                    708:                goto failed;
                    709:
                    710:        if (ioctl(sock, SIOCGIFFLAGS, &ifr) == -1)
                    711:                goto failed;
1.40      reyk      712:
                    713:        /* Set interface mode */
                    714:        ifr.ifr_flags &= ~IFF_UP;
                    715:        if (mode == SSH_TUNMODE_ETHERNET)
1.37      reyk      716:                ifr.ifr_flags |= IFF_LINK0;
1.40      reyk      717:        else
                    718:                ifr.ifr_flags &= ~IFF_LINK0;
                    719:        if (ioctl(sock, SIOCSIFFLAGS, &ifr) == -1)
                    720:                goto failed;
                    721:
                    722:        /* Bring interface up */
1.37      reyk      723:        ifr.ifr_flags |= IFF_UP;
                    724:        if (ioctl(sock, SIOCSIFFLAGS, &ifr) == -1)
                    725:                goto failed;
                    726:
                    727:        close(sock);
                    728:        return (fd);
                    729:
                    730:  failed:
                    731:        if (fd >= 0)
                    732:                close(fd);
                    733:        if (sock >= 0)
                    734:                close(sock);
                    735:        debug("%s: failed to set %s mode %d: %s", __func__, name,
                    736:            mode, strerror(errno));
1.36      reyk      737:        return (-1);
1.35      djm       738: }
                    739:
                    740: void
                    741: sanitise_stdfd(void)
                    742: {
1.41      djm       743:        int nullfd, dupfd;
1.35      djm       744:
1.41      djm       745:        if ((nullfd = dupfd = open(_PATH_DEVNULL, O_RDWR)) == -1) {
1.71      tobias    746:                fprintf(stderr, "Couldn't open /dev/null: %s\n",
                    747:                    strerror(errno));
1.35      djm       748:                exit(1);
                    749:        }
1.41      djm       750:        while (++dupfd <= 2) {
                    751:                /* Only clobber closed fds */
                    752:                if (fcntl(dupfd, F_GETFL, 0) >= 0)
                    753:                        continue;
                    754:                if (dup2(nullfd, dupfd) == -1) {
1.71      tobias    755:                        fprintf(stderr, "dup2: %s\n", strerror(errno));
1.35      djm       756:                        exit(1);
                    757:                }
                    758:        }
                    759:        if (nullfd > 2)
                    760:                close(nullfd);
1.1       markus    761: }
1.33      djm       762:
                    763: char *
1.52      djm       764: tohex(const void *vp, size_t l)
1.33      djm       765: {
1.52      djm       766:        const u_char *p = (const u_char *)vp;
1.33      djm       767:        char b[3], *r;
1.52      djm       768:        size_t i, hl;
                    769:
                    770:        if (l > 65536)
                    771:                return xstrdup("tohex: length > 65536");
1.33      djm       772:
                    773:        hl = l * 2 + 1;
1.49      djm       774:        r = xcalloc(1, hl);
1.33      djm       775:        for (i = 0; i < l; i++) {
1.52      djm       776:                snprintf(b, sizeof(b), "%02x", p[i]);
1.33      djm       777:                strlcat(r, b, hl);
                    778:        }
                    779:        return (r);
                    780: }
                    781:
1.52      djm       782: u_int64_t
                    783: get_u64(const void *vp)
                    784: {
                    785:        const u_char *p = (const u_char *)vp;
                    786:        u_int64_t v;
                    787:
                    788:        v  = (u_int64_t)p[0] << 56;
                    789:        v |= (u_int64_t)p[1] << 48;
                    790:        v |= (u_int64_t)p[2] << 40;
                    791:        v |= (u_int64_t)p[3] << 32;
                    792:        v |= (u_int64_t)p[4] << 24;
                    793:        v |= (u_int64_t)p[5] << 16;
                    794:        v |= (u_int64_t)p[6] << 8;
                    795:        v |= (u_int64_t)p[7];
                    796:
                    797:        return (v);
                    798: }
                    799:
                    800: u_int32_t
                    801: get_u32(const void *vp)
                    802: {
                    803:        const u_char *p = (const u_char *)vp;
                    804:        u_int32_t v;
                    805:
                    806:        v  = (u_int32_t)p[0] << 24;
                    807:        v |= (u_int32_t)p[1] << 16;
                    808:        v |= (u_int32_t)p[2] << 8;
                    809:        v |= (u_int32_t)p[3];
                    810:
                    811:        return (v);
                    812: }
                    813:
                    814: u_int16_t
                    815: get_u16(const void *vp)
                    816: {
                    817:        const u_char *p = (const u_char *)vp;
                    818:        u_int16_t v;
                    819:
                    820:        v  = (u_int16_t)p[0] << 8;
                    821:        v |= (u_int16_t)p[1];
                    822:
                    823:        return (v);
                    824: }
                    825:
                    826: void
                    827: put_u64(void *vp, u_int64_t v)
                    828: {
                    829:        u_char *p = (u_char *)vp;
                    830:
                    831:        p[0] = (u_char)(v >> 56) & 0xff;
                    832:        p[1] = (u_char)(v >> 48) & 0xff;
                    833:        p[2] = (u_char)(v >> 40) & 0xff;
                    834:        p[3] = (u_char)(v >> 32) & 0xff;
                    835:        p[4] = (u_char)(v >> 24) & 0xff;
                    836:        p[5] = (u_char)(v >> 16) & 0xff;
                    837:        p[6] = (u_char)(v >> 8) & 0xff;
                    838:        p[7] = (u_char)v & 0xff;
                    839: }
                    840:
                    841: void
                    842: put_u32(void *vp, u_int32_t v)
                    843: {
                    844:        u_char *p = (u_char *)vp;
                    845:
                    846:        p[0] = (u_char)(v >> 24) & 0xff;
                    847:        p[1] = (u_char)(v >> 16) & 0xff;
                    848:        p[2] = (u_char)(v >> 8) & 0xff;
                    849:        p[3] = (u_char)v & 0xff;
                    850: }
                    851:
                    852:
                    853: void
                    854: put_u16(void *vp, u_int16_t v)
                    855: {
                    856:        u_char *p = (u_char *)vp;
                    857:
                    858:        p[0] = (u_char)(v >> 8) & 0xff;
                    859:        p[1] = (u_char)v & 0xff;
                    860: }
1.68      dtucker   861:
                    862: void
                    863: ms_subtract_diff(struct timeval *start, int *ms)
                    864: {
                    865:        struct timeval diff, finish;
                    866:
                    867:        gettimeofday(&finish, NULL);
                    868:        timersub(&finish, start, &diff);
                    869:        *ms -= (diff.tv_sec * 1000) + (diff.tv_usec / 1000);
                    870: }
                    871:
                    872: void
                    873: ms_to_timeval(struct timeval *tv, int ms)
                    874: {
                    875:        if (ms < 0)
                    876:                ms = 0;
                    877:        tv->tv_sec = ms / 1000;
                    878:        tv->tv_usec = (ms % 1000) * 1000;
                    879: }
                    880: