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