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