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