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