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

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