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