1 /* $OpenBSD: misc.c,v 1.197 2024/09/25 01:24:04 djm Exp $ */
2 /*
3 * Copyright (c) 2000 Markus Friedl. All rights reserved.
4 * Copyright (c) 2005-2020 Damien Miller. All rights reserved.
5 * Copyright (c) 2004 Henning Brauer <henning@openbsd.org>
6 *
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.
10 *
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.
18 */
19
20
21 #include "includes.h"
22
23 #include <sys/types.h>
24 #include <sys/ioctl.h>
25 #include <sys/mman.h>
26 #include <sys/socket.h>
27 #include <sys/stat.h>
28 #include <sys/time.h>
29 #include <sys/wait.h>
30 #include <sys/un.h>
31
32 #include <limits.h>
33 #ifdef HAVE_LIBGEN_H
34 # include <libgen.h>
35 #endif
36 #ifdef HAVE_POLL_H
37 #include <poll.h>
38 #endif
39 #ifdef HAVE_NLIST_H
40 #include <nlist.h>
41 #endif
42 #include <signal.h>
43 #include <stdarg.h>
44 #include <stdio.h>
45 #ifdef HAVE_STDINT_H
46 # include <stdint.h>
47 #endif
48 #include <stdlib.h>
49 #include <string.h>
50 #include <time.h>
51 #include <unistd.h>
52
53 #include <netinet/in.h>
54 #include <netinet/in_systm.h>
55 #include <netinet/ip.h>
56 #include <netinet/tcp.h>
57 #include <arpa/inet.h>
58
59 #include <ctype.h>
60 #include <errno.h>
61 #include <fcntl.h>
62 #include <netdb.h>
63 #ifdef HAVE_PATHS_H
64 # include <paths.h>
65 #include <pwd.h>
66 #include <grp.h>
67 #endif
68 #ifdef SSH_TUN_OPENBSD
69 #include <net/if.h>
70 #endif
71
72 #include "xmalloc.h"
73 #include "misc.h"
74 #include "log.h"
75 #include "ssh.h"
76 #include "sshbuf.h"
77 #include "ssherr.h"
78 #include "platform.h"
79
80 /* remove newline at end of string */
81 char *
chop(char * s)82 chop(char *s)
83 {
84 char *t = s;
85 while (*t) {
86 if (*t == '\n' || *t == '\r') {
87 *t = '\0';
88 return s;
89 }
90 t++;
91 }
92 return s;
93
94 }
95
96 /* remove whitespace from end of string */
97 void
rtrim(char * s)98 rtrim(char *s)
99 {
100 size_t i;
101
102 if ((i = strlen(s)) == 0)
103 return;
104 for (i--; i > 0; i--) {
105 if (isspace((unsigned char)s[i]))
106 s[i] = '\0';
107 }
108 }
109
110 /*
111 * returns pointer to character after 'prefix' in 's' or otherwise NULL
112 * if the prefix is not present.
113 */
114 const char *
strprefix(const char * s,const char * prefix,int ignorecase)115 strprefix(const char *s, const char *prefix, int ignorecase)
116 {
117 size_t prefixlen;
118
119 if ((prefixlen = strlen(prefix)) == 0)
120 return s;
121 if (ignorecase) {
122 if (strncasecmp(s, prefix, prefixlen) != 0)
123 return NULL;
124 } else {
125 if (strncmp(s, prefix, prefixlen) != 0)
126 return NULL;
127 }
128 return s + prefixlen;
129 }
130
131 /* set/unset filedescriptor to non-blocking */
132 int
set_nonblock(int fd)133 set_nonblock(int fd)
134 {
135 int val;
136
137 val = fcntl(fd, F_GETFL);
138 if (val == -1) {
139 error("fcntl(%d, F_GETFL): %s", fd, strerror(errno));
140 return (-1);
141 }
142 if (val & O_NONBLOCK) {
143 debug3("fd %d is O_NONBLOCK", fd);
144 return (0);
145 }
146 debug2("fd %d setting O_NONBLOCK", fd);
147 val |= O_NONBLOCK;
148 if (fcntl(fd, F_SETFL, val) == -1) {
149 debug("fcntl(%d, F_SETFL, O_NONBLOCK): %s", fd,
150 strerror(errno));
151 return (-1);
152 }
153 return (0);
154 }
155
156 int
unset_nonblock(int fd)157 unset_nonblock(int fd)
158 {
159 int val;
160
161 val = fcntl(fd, F_GETFL);
162 if (val == -1) {
163 error("fcntl(%d, F_GETFL): %s", fd, strerror(errno));
164 return (-1);
165 }
166 if (!(val & O_NONBLOCK)) {
167 debug3("fd %d is not O_NONBLOCK", fd);
168 return (0);
169 }
170 debug("fd %d clearing O_NONBLOCK", fd);
171 val &= ~O_NONBLOCK;
172 if (fcntl(fd, F_SETFL, val) == -1) {
173 debug("fcntl(%d, F_SETFL, ~O_NONBLOCK): %s",
174 fd, strerror(errno));
175 return (-1);
176 }
177 return (0);
178 }
179
180 const char *
ssh_gai_strerror(int gaierr)181 ssh_gai_strerror(int gaierr)
182 {
183 if (gaierr == EAI_SYSTEM && errno != 0)
184 return strerror(errno);
185 return gai_strerror(gaierr);
186 }
187
188 /* disable nagle on socket */
189 void
set_nodelay(int fd)190 set_nodelay(int fd)
191 {
192 int opt;
193 socklen_t optlen;
194
195 optlen = sizeof opt;
196 if (getsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &opt, &optlen) == -1) {
197 debug("getsockopt TCP_NODELAY: %.100s", strerror(errno));
198 return;
199 }
200 if (opt == 1) {
201 debug2("fd %d is TCP_NODELAY", fd);
202 return;
203 }
204 opt = 1;
205 debug2("fd %d setting TCP_NODELAY", fd);
206 if (setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &opt, sizeof opt) == -1)
207 error("setsockopt TCP_NODELAY: %.100s", strerror(errno));
208 }
209
210 /* Allow local port reuse in TIME_WAIT */
211 int
set_reuseaddr(int fd)212 set_reuseaddr(int fd)
213 {
214 int on = 1;
215
216 if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)) == -1) {
217 error("setsockopt SO_REUSEADDR fd %d: %s", fd, strerror(errno));
218 return -1;
219 }
220 return 0;
221 }
222
223 /* Get/set routing domain */
224 char *
get_rdomain(int fd)225 get_rdomain(int fd)
226 {
227 #if defined(HAVE_SYS_GET_RDOMAIN)
228 return sys_get_rdomain(fd);
229 #elif defined(__OpenBSD__)
230 int rtable;
231 char *ret;
232 socklen_t len = sizeof(rtable);
233
234 if (getsockopt(fd, SOL_SOCKET, SO_RTABLE, &rtable, &len) == -1) {
235 error("Failed to get routing domain for fd %d: %s",
236 fd, strerror(errno));
237 return NULL;
238 }
239 xasprintf(&ret, "%d", rtable);
240 return ret;
241 #else /* defined(__OpenBSD__) */
242 return NULL;
243 #endif
244 }
245
246 int
set_rdomain(int fd,const char * name)247 set_rdomain(int fd, const char *name)
248 {
249 #if defined(HAVE_SYS_SET_RDOMAIN)
250 return sys_set_rdomain(fd, name);
251 #elif defined(__OpenBSD__)
252 int rtable;
253 const char *errstr;
254
255 if (name == NULL)
256 return 0; /* default table */
257
258 rtable = (int)strtonum(name, 0, 255, &errstr);
259 if (errstr != NULL) {
260 /* Shouldn't happen */
261 error("Invalid routing domain \"%s\": %s", name, errstr);
262 return -1;
263 }
264 if (setsockopt(fd, SOL_SOCKET, SO_RTABLE,
265 &rtable, sizeof(rtable)) == -1) {
266 error("Failed to set routing domain %d on fd %d: %s",
267 rtable, fd, strerror(errno));
268 return -1;
269 }
270 return 0;
271 #else /* defined(__OpenBSD__) */
272 error("Setting routing domain is not supported on this platform");
273 return -1;
274 #endif
275 }
276
277 int
get_sock_af(int fd)278 get_sock_af(int fd)
279 {
280 struct sockaddr_storage to;
281 socklen_t tolen = sizeof(to);
282
283 memset(&to, 0, sizeof(to));
284 if (getsockname(fd, (struct sockaddr *)&to, &tolen) == -1)
285 return -1;
286 #ifdef IPV4_IN_IPV6
287 if (to.ss_family == AF_INET6 &&
288 IN6_IS_ADDR_V4MAPPED(&((struct sockaddr_in6 *)&to)->sin6_addr))
289 return AF_INET;
290 #endif
291 return to.ss_family;
292 }
293
294 void
set_sock_tos(int fd,int tos)295 set_sock_tos(int fd, int tos)
296 {
297 #ifndef IP_TOS_IS_BROKEN
298 int af;
299
300 switch ((af = get_sock_af(fd))) {
301 case -1:
302 /* assume not a socket */
303 break;
304 case AF_INET:
305 # ifdef IP_TOS
306 debug3_f("set socket %d IP_TOS 0x%02x", fd, tos);
307 if (setsockopt(fd, IPPROTO_IP, IP_TOS,
308 &tos, sizeof(tos)) == -1) {
309 error("setsockopt socket %d IP_TOS %d: %s",
310 fd, tos, strerror(errno));
311 }
312 # endif /* IP_TOS */
313 break;
314 case AF_INET6:
315 # ifdef IPV6_TCLASS
316 debug3_f("set socket %d IPV6_TCLASS 0x%02x", fd, tos);
317 if (setsockopt(fd, IPPROTO_IPV6, IPV6_TCLASS,
318 &tos, sizeof(tos)) == -1) {
319 error("setsockopt socket %d IPV6_TCLASS %d: %s",
320 fd, tos, strerror(errno));
321 }
322 # endif /* IPV6_TCLASS */
323 break;
324 default:
325 debug2_f("unsupported socket family %d", af);
326 break;
327 }
328 #endif /* IP_TOS_IS_BROKEN */
329 }
330
331 /*
332 * Wait up to *timeoutp milliseconds for events on fd. Updates
333 * *timeoutp with time remaining.
334 * Returns 0 if fd ready or -1 on timeout or error (see errno).
335 */
336 static int
waitfd(int fd,int * timeoutp,short events,volatile sig_atomic_t * stop)337 waitfd(int fd, int *timeoutp, short events, volatile sig_atomic_t *stop)
338 {
339 struct pollfd pfd;
340 struct timespec timeout;
341 int oerrno, r;
342 sigset_t nsigset, osigset;
343
344 if (timeoutp && *timeoutp == -1)
345 timeoutp = NULL;
346 pfd.fd = fd;
347 pfd.events = events;
348 ptimeout_init(&timeout);
349 if (timeoutp != NULL)
350 ptimeout_deadline_ms(&timeout, *timeoutp);
351 if (stop != NULL)
352 sigfillset(&nsigset);
353 for (; timeoutp == NULL || *timeoutp >= 0;) {
354 if (stop != NULL) {
355 sigprocmask(SIG_BLOCK, &nsigset, &osigset);
356 if (*stop) {
357 sigprocmask(SIG_SETMASK, &osigset, NULL);
358 errno = EINTR;
359 return -1;
360 }
361 }
362 r = ppoll(&pfd, 1, ptimeout_get_tsp(&timeout),
363 stop != NULL ? &osigset : NULL);
364 oerrno = errno;
365 if (stop != NULL)
366 sigprocmask(SIG_SETMASK, &osigset, NULL);
367 if (timeoutp)
368 *timeoutp = ptimeout_get_ms(&timeout);
369 errno = oerrno;
370 if (r > 0)
371 return 0;
372 else if (r == -1 && errno != EAGAIN && errno != EINTR)
373 return -1;
374 else if (r == 0)
375 break;
376 }
377 /* timeout */
378 errno = ETIMEDOUT;
379 return -1;
380 }
381
382 /*
383 * Wait up to *timeoutp milliseconds for fd to be readable. Updates
384 * *timeoutp with time remaining.
385 * Returns 0 if fd ready or -1 on timeout or error (see errno).
386 */
387 int
waitrfd(int fd,int * timeoutp,volatile sig_atomic_t * stop)388 waitrfd(int fd, int *timeoutp, volatile sig_atomic_t *stop) {
389 return waitfd(fd, timeoutp, POLLIN, stop);
390 }
391
392 /*
393 * Attempt a non-blocking connect(2) to the specified address, waiting up to
394 * *timeoutp milliseconds for the connection to complete. If the timeout is
395 * <=0, then wait indefinitely.
396 *
397 * Returns 0 on success or -1 on failure.
398 */
399 int
timeout_connect(int sockfd,const struct sockaddr * serv_addr,socklen_t addrlen,int * timeoutp)400 timeout_connect(int sockfd, const struct sockaddr *serv_addr,
401 socklen_t addrlen, int *timeoutp)
402 {
403 int optval = 0;
404 socklen_t optlen = sizeof(optval);
405
406 /* No timeout: just do a blocking connect() */
407 if (timeoutp == NULL || *timeoutp <= 0)
408 return connect(sockfd, serv_addr, addrlen);
409
410 set_nonblock(sockfd);
411 for (;;) {
412 if (connect(sockfd, serv_addr, addrlen) == 0) {
413 /* Succeeded already? */
414 unset_nonblock(sockfd);
415 return 0;
416 } else if (errno == EINTR)
417 continue;
418 else if (errno != EINPROGRESS)
419 return -1;
420 break;
421 }
422
423 if (waitfd(sockfd, timeoutp, POLLIN | POLLOUT, NULL) == -1)
424 return -1;
425
426 /* Completed or failed */
427 if (getsockopt(sockfd, SOL_SOCKET, SO_ERROR, &optval, &optlen) == -1) {
428 debug("getsockopt: %s", strerror(errno));
429 return -1;
430 }
431 if (optval != 0) {
432 errno = optval;
433 return -1;
434 }
435 unset_nonblock(sockfd);
436 return 0;
437 }
438
439 /* Characters considered whitespace in strsep calls. */
440 #define WHITESPACE " \t\r\n"
441 #define QUOTE "\""
442
443 /* return next token in configuration line */
444 static char *
strdelim_internal(char ** s,int split_equals)445 strdelim_internal(char **s, int split_equals)
446 {
447 char *old;
448 int wspace = 0;
449
450 if (*s == NULL)
451 return NULL;
452
453 old = *s;
454
455 *s = strpbrk(*s,
456 split_equals ? WHITESPACE QUOTE "=" : WHITESPACE QUOTE);
457 if (*s == NULL)
458 return (old);
459
460 if (*s[0] == '\"') {
461 memmove(*s, *s + 1, strlen(*s)); /* move nul too */
462 /* Find matching quote */
463 if ((*s = strpbrk(*s, QUOTE)) == NULL) {
464 return (NULL); /* no matching quote */
465 } else {
466 *s[0] = '\0';
467 *s += strspn(*s + 1, WHITESPACE) + 1;
468 return (old);
469 }
470 }
471
472 /* Allow only one '=' to be skipped */
473 if (split_equals && *s[0] == '=')
474 wspace = 1;
475 *s[0] = '\0';
476
477 /* Skip any extra whitespace after first token */
478 *s += strspn(*s + 1, WHITESPACE) + 1;
479 if (split_equals && *s[0] == '=' && !wspace)
480 *s += strspn(*s + 1, WHITESPACE) + 1;
481
482 return (old);
483 }
484
485 /*
486 * Return next token in configuration line; splts on whitespace or a
487 * single '=' character.
488 */
489 char *
strdelim(char ** s)490 strdelim(char **s)
491 {
492 return strdelim_internal(s, 1);
493 }
494
495 /*
496 * Return next token in configuration line; splts on whitespace only.
497 */
498 char *
strdelimw(char ** s)499 strdelimw(char **s)
500 {
501 return strdelim_internal(s, 0);
502 }
503
504 struct passwd *
pwcopy(struct passwd * pw)505 pwcopy(struct passwd *pw)
506 {
507 struct passwd *copy = xcalloc(1, sizeof(*copy));
508
509 copy->pw_name = xstrdup(pw->pw_name);
510 copy->pw_passwd = xstrdup(pw->pw_passwd == NULL ? "*" : pw->pw_passwd);
511 #ifdef HAVE_STRUCT_PASSWD_PW_GECOS
512 copy->pw_gecos = xstrdup(pw->pw_gecos);
513 #endif
514 copy->pw_uid = pw->pw_uid;
515 copy->pw_gid = pw->pw_gid;
516 #ifdef HAVE_STRUCT_PASSWD_PW_EXPIRE
517 copy->pw_expire = pw->pw_expire;
518 #endif
519 #ifdef HAVE_STRUCT_PASSWD_PW_CHANGE
520 copy->pw_change = pw->pw_change;
521 #endif
522 #ifdef HAVE_STRUCT_PASSWD_PW_CLASS
523 copy->pw_class = xstrdup(pw->pw_class);
524 #endif
525 copy->pw_dir = xstrdup(pw->pw_dir);
526 copy->pw_shell = xstrdup(pw->pw_shell);
527 return copy;
528 }
529
530 /*
531 * Convert ASCII string to TCP/IP port number.
532 * Port must be >=0 and <=65535.
533 * Return -1 if invalid.
534 */
535 int
a2port(const char * s)536 a2port(const char *s)
537 {
538 struct servent *se;
539 long long port;
540 const char *errstr;
541
542 port = strtonum(s, 0, 65535, &errstr);
543 if (errstr == NULL)
544 return (int)port;
545 if ((se = getservbyname(s, "tcp")) != NULL)
546 return ntohs(se->s_port);
547 return -1;
548 }
549
550 int
a2tun(const char * s,int * remote)551 a2tun(const char *s, int *remote)
552 {
553 const char *errstr = NULL;
554 char *sp, *ep;
555 int tun;
556
557 if (remote != NULL) {
558 *remote = SSH_TUNID_ANY;
559 sp = xstrdup(s);
560 if ((ep = strchr(sp, ':')) == NULL) {
561 free(sp);
562 return (a2tun(s, NULL));
563 }
564 ep[0] = '\0'; ep++;
565 *remote = a2tun(ep, NULL);
566 tun = a2tun(sp, NULL);
567 free(sp);
568 return (*remote == SSH_TUNID_ERR ? *remote : tun);
569 }
570
571 if (strcasecmp(s, "any") == 0)
572 return (SSH_TUNID_ANY);
573
574 tun = strtonum(s, 0, SSH_TUNID_MAX, &errstr);
575 if (errstr != NULL)
576 return (SSH_TUNID_ERR);
577
578 return (tun);
579 }
580
581 #define SECONDS 1
582 #define MINUTES (SECONDS * 60)
583 #define HOURS (MINUTES * 60)
584 #define DAYS (HOURS * 24)
585 #define WEEKS (DAYS * 7)
586
587 static char *
scandigits(char * s)588 scandigits(char *s)
589 {
590 while (isdigit((unsigned char)*s))
591 s++;
592 return s;
593 }
594
595 /*
596 * Convert a time string into seconds; format is
597 * a sequence of:
598 * time[qualifier]
599 *
600 * Valid time qualifiers are:
601 * <none> seconds
602 * s|S seconds
603 * m|M minutes
604 * h|H hours
605 * d|D days
606 * w|W weeks
607 *
608 * Examples:
609 * 90m 90 minutes
610 * 1h30m 90 minutes
611 * 2d 2 days
612 * 1w 1 week
613 *
614 * Return -1 if time string is invalid.
615 */
616 int
convtime(const char * s)617 convtime(const char *s)
618 {
619 int secs, total = 0, multiplier;
620 char *p, *os, *np, c = 0;
621 const char *errstr;
622
623 if (s == NULL || *s == '\0')
624 return -1;
625 p = os = strdup(s); /* deal with const */
626 if (os == NULL)
627 return -1;
628
629 while (*p) {
630 np = scandigits(p);
631 if (np) {
632 c = *np;
633 *np = '\0';
634 }
635 secs = (int)strtonum(p, 0, INT_MAX, &errstr);
636 if (errstr)
637 goto fail;
638 *np = c;
639
640 multiplier = 1;
641 switch (c) {
642 case '\0':
643 np--; /* back up */
644 break;
645 case 's':
646 case 'S':
647 break;
648 case 'm':
649 case 'M':
650 multiplier = MINUTES;
651 break;
652 case 'h':
653 case 'H':
654 multiplier = HOURS;
655 break;
656 case 'd':
657 case 'D':
658 multiplier = DAYS;
659 break;
660 case 'w':
661 case 'W':
662 multiplier = WEEKS;
663 break;
664 default:
665 goto fail;
666 }
667 if (secs > INT_MAX / multiplier)
668 goto fail;
669 secs *= multiplier;
670 if (total > INT_MAX - secs)
671 goto fail;
672 total += secs;
673 if (total < 0)
674 goto fail;
675 p = ++np;
676 }
677 free(os);
678 return total;
679 fail:
680 free(os);
681 return -1;
682 }
683
684 #define TF_BUFS 8
685 #define TF_LEN 9
686
687 const char *
fmt_timeframe(time_t t)688 fmt_timeframe(time_t t)
689 {
690 char *buf;
691 static char tfbuf[TF_BUFS][TF_LEN]; /* ring buffer */
692 static int idx = 0;
693 unsigned int sec, min, hrs, day;
694 unsigned long long week;
695
696 buf = tfbuf[idx++];
697 if (idx == TF_BUFS)
698 idx = 0;
699
700 week = t;
701
702 sec = week % 60;
703 week /= 60;
704 min = week % 60;
705 week /= 60;
706 hrs = week % 24;
707 week /= 24;
708 day = week % 7;
709 week /= 7;
710
711 if (week > 0)
712 snprintf(buf, TF_LEN, "%02lluw%01ud%02uh", week, day, hrs);
713 else if (day > 0)
714 snprintf(buf, TF_LEN, "%01ud%02uh%02um", day, hrs, min);
715 else
716 snprintf(buf, TF_LEN, "%02u:%02u:%02u", hrs, min, sec);
717
718 return (buf);
719 }
720
721 /*
722 * Returns a standardized host+port identifier string.
723 * Caller must free returned string.
724 */
725 char *
put_host_port(const char * host,u_short port)726 put_host_port(const char *host, u_short port)
727 {
728 char *hoststr;
729
730 if (port == 0 || port == SSH_DEFAULT_PORT)
731 return(xstrdup(host));
732 if (asprintf(&hoststr, "[%s]:%d", host, (int)port) == -1)
733 fatal("put_host_port: asprintf: %s", strerror(errno));
734 debug3("put_host_port: %s", hoststr);
735 return hoststr;
736 }
737
738 /*
739 * Search for next delimiter between hostnames/addresses and ports.
740 * Argument may be modified (for termination).
741 * Returns *cp if parsing succeeds.
742 * *cp is set to the start of the next field, if one was found.
743 * The delimiter char, if present, is stored in delim.
744 * If this is the last field, *cp is set to NULL.
745 */
746 char *
hpdelim2(char ** cp,char * delim)747 hpdelim2(char **cp, char *delim)
748 {
749 char *s, *old;
750
751 if (cp == NULL || *cp == NULL)
752 return NULL;
753
754 old = s = *cp;
755 if (*s == '[') {
756 if ((s = strchr(s, ']')) == NULL)
757 return NULL;
758 else
759 s++;
760 } else if ((s = strpbrk(s, ":/")) == NULL)
761 s = *cp + strlen(*cp); /* skip to end (see first case below) */
762
763 switch (*s) {
764 case '\0':
765 *cp = NULL; /* no more fields*/
766 break;
767
768 case ':':
769 case '/':
770 if (delim != NULL)
771 *delim = *s;
772 *s = '\0'; /* terminate */
773 *cp = s + 1;
774 break;
775
776 default:
777 return NULL;
778 }
779
780 return old;
781 }
782
783 /* The common case: only accept colon as delimiter. */
784 char *
hpdelim(char ** cp)785 hpdelim(char **cp)
786 {
787 char *r, delim = '\0';
788
789 r = hpdelim2(cp, &delim);
790 if (delim == '/')
791 return NULL;
792 return r;
793 }
794
795 char *
cleanhostname(char * host)796 cleanhostname(char *host)
797 {
798 if (*host == '[' && host[strlen(host) - 1] == ']') {
799 host[strlen(host) - 1] = '\0';
800 return (host + 1);
801 } else
802 return host;
803 }
804
805 char *
colon(char * cp)806 colon(char *cp)
807 {
808 int flag = 0;
809
810 if (*cp == ':') /* Leading colon is part of file name. */
811 return NULL;
812 if (*cp == '[')
813 flag = 1;
814
815 for (; *cp; ++cp) {
816 if (*cp == '@' && *(cp+1) == '[')
817 flag = 1;
818 if (*cp == ']' && *(cp+1) == ':' && flag)
819 return (cp+1);
820 if (*cp == ':' && !flag)
821 return (cp);
822 if (*cp == '/')
823 return NULL;
824 }
825 return NULL;
826 }
827
828 /*
829 * Parse a [user@]host:[path] string.
830 * Caller must free returned user, host and path.
831 * Any of the pointer return arguments may be NULL (useful for syntax checking).
832 * If user was not specified then *userp will be set to NULL.
833 * If host was not specified then *hostp will be set to NULL.
834 * If path was not specified then *pathp will be set to ".".
835 * Returns 0 on success, -1 on failure.
836 */
837 int
parse_user_host_path(const char * s,char ** userp,char ** hostp,char ** pathp)838 parse_user_host_path(const char *s, char **userp, char **hostp, char **pathp)
839 {
840 char *user = NULL, *host = NULL, *path = NULL;
841 char *sdup, *tmp;
842 int ret = -1;
843
844 if (userp != NULL)
845 *userp = NULL;
846 if (hostp != NULL)
847 *hostp = NULL;
848 if (pathp != NULL)
849 *pathp = NULL;
850
851 sdup = xstrdup(s);
852
853 /* Check for remote syntax: [user@]host:[path] */
854 if ((tmp = colon(sdup)) == NULL)
855 goto out;
856
857 /* Extract optional path */
858 *tmp++ = '\0';
859 if (*tmp == '\0')
860 tmp = ".";
861 path = xstrdup(tmp);
862
863 /* Extract optional user and mandatory host */
864 tmp = strrchr(sdup, '@');
865 if (tmp != NULL) {
866 *tmp++ = '\0';
867 host = xstrdup(cleanhostname(tmp));
868 if (*sdup != '\0')
869 user = xstrdup(sdup);
870 } else {
871 host = xstrdup(cleanhostname(sdup));
872 user = NULL;
873 }
874
875 /* Success */
876 if (userp != NULL) {
877 *userp = user;
878 user = NULL;
879 }
880 if (hostp != NULL) {
881 *hostp = host;
882 host = NULL;
883 }
884 if (pathp != NULL) {
885 *pathp = path;
886 path = NULL;
887 }
888 ret = 0;
889 out:
890 free(sdup);
891 free(user);
892 free(host);
893 free(path);
894 return ret;
895 }
896
897 /*
898 * Parse a [user@]host[:port] string.
899 * Caller must free returned user and host.
900 * Any of the pointer return arguments may be NULL (useful for syntax checking).
901 * If user was not specified then *userp will be set to NULL.
902 * If port was not specified then *portp will be -1.
903 * Returns 0 on success, -1 on failure.
904 */
905 int
parse_user_host_port(const char * s,char ** userp,char ** hostp,int * portp)906 parse_user_host_port(const char *s, char **userp, char **hostp, int *portp)
907 {
908 char *sdup, *cp, *tmp;
909 char *user = NULL, *host = NULL;
910 int port = -1, ret = -1;
911
912 if (userp != NULL)
913 *userp = NULL;
914 if (hostp != NULL)
915 *hostp = NULL;
916 if (portp != NULL)
917 *portp = -1;
918
919 if ((sdup = tmp = strdup(s)) == NULL)
920 return -1;
921 /* Extract optional username */
922 if ((cp = strrchr(tmp, '@')) != NULL) {
923 *cp = '\0';
924 if (*tmp == '\0')
925 goto out;
926 if ((user = strdup(tmp)) == NULL)
927 goto out;
928 tmp = cp + 1;
929 }
930 /* Extract mandatory hostname */
931 if ((cp = hpdelim(&tmp)) == NULL || *cp == '\0')
932 goto out;
933 host = xstrdup(cleanhostname(cp));
934 /* Convert and verify optional port */
935 if (tmp != NULL && *tmp != '\0') {
936 if ((port = a2port(tmp)) <= 0)
937 goto out;
938 }
939 /* Success */
940 if (userp != NULL) {
941 *userp = user;
942 user = NULL;
943 }
944 if (hostp != NULL) {
945 *hostp = host;
946 host = NULL;
947 }
948 if (portp != NULL)
949 *portp = port;
950 ret = 0;
951 out:
952 free(sdup);
953 free(user);
954 free(host);
955 return ret;
956 }
957
958 /*
959 * Converts a two-byte hex string to decimal.
960 * Returns the decimal value or -1 for invalid input.
961 */
962 static int
hexchar(const char * s)963 hexchar(const char *s)
964 {
965 unsigned char result[2];
966 int i;
967
968 for (i = 0; i < 2; i++) {
969 if (s[i] >= '0' && s[i] <= '9')
970 result[i] = (unsigned char)(s[i] - '0');
971 else if (s[i] >= 'a' && s[i] <= 'f')
972 result[i] = (unsigned char)(s[i] - 'a') + 10;
973 else if (s[i] >= 'A' && s[i] <= 'F')
974 result[i] = (unsigned char)(s[i] - 'A') + 10;
975 else
976 return -1;
977 }
978 return (result[0] << 4) | result[1];
979 }
980
981 /*
982 * Decode an url-encoded string.
983 * Returns a newly allocated string on success or NULL on failure.
984 */
985 static char *
urldecode(const char * src)986 urldecode(const char *src)
987 {
988 char *ret, *dst;
989 int ch;
990 size_t srclen;
991
992 if ((srclen = strlen(src)) >= SIZE_MAX)
993 fatal_f("input too large");
994 ret = xmalloc(srclen + 1);
995 for (dst = ret; *src != '\0'; src++) {
996 switch (*src) {
997 case '+':
998 *dst++ = ' ';
999 break;
1000 case '%':
1001 if (!isxdigit((unsigned char)src[1]) ||
1002 !isxdigit((unsigned char)src[2]) ||
1003 (ch = hexchar(src + 1)) == -1) {
1004 free(ret);
1005 return NULL;
1006 }
1007 *dst++ = ch;
1008 src += 2;
1009 break;
1010 default:
1011 *dst++ = *src;
1012 break;
1013 }
1014 }
1015 *dst = '\0';
1016
1017 return ret;
1018 }
1019
1020 /*
1021 * Parse an (scp|ssh|sftp)://[user@]host[:port][/path] URI.
1022 * See https://tools.ietf.org/html/draft-ietf-secsh-scp-sftp-ssh-uri-04
1023 * Either user or path may be url-encoded (but not host or port).
1024 * Caller must free returned user, host and path.
1025 * Any of the pointer return arguments may be NULL (useful for syntax checking)
1026 * but the scheme must always be specified.
1027 * If user was not specified then *userp will be set to NULL.
1028 * If port was not specified then *portp will be -1.
1029 * If path was not specified then *pathp will be set to NULL.
1030 * Returns 0 on success, 1 if non-uri/wrong scheme, -1 on error/invalid uri.
1031 */
1032 int
parse_uri(const char * scheme,const char * uri,char ** userp,char ** hostp,int * portp,char ** pathp)1033 parse_uri(const char *scheme, const char *uri, char **userp, char **hostp,
1034 int *portp, char **pathp)
1035 {
1036 char *uridup, *cp, *tmp, ch;
1037 char *user = NULL, *host = NULL, *path = NULL;
1038 int port = -1, ret = -1;
1039 size_t len;
1040
1041 len = strlen(scheme);
1042 if (strncmp(uri, scheme, len) != 0 || strncmp(uri + len, "://", 3) != 0)
1043 return 1;
1044 uri += len + 3;
1045
1046 if (userp != NULL)
1047 *userp = NULL;
1048 if (hostp != NULL)
1049 *hostp = NULL;
1050 if (portp != NULL)
1051 *portp = -1;
1052 if (pathp != NULL)
1053 *pathp = NULL;
1054
1055 uridup = tmp = xstrdup(uri);
1056
1057 /* Extract optional ssh-info (username + connection params) */
1058 if ((cp = strchr(tmp, '@')) != NULL) {
1059 char *delim;
1060
1061 *cp = '\0';
1062 /* Extract username and connection params */
1063 if ((delim = strchr(tmp, ';')) != NULL) {
1064 /* Just ignore connection params for now */
1065 *delim = '\0';
1066 }
1067 if (*tmp == '\0') {
1068 /* Empty username */
1069 goto out;
1070 }
1071 if ((user = urldecode(tmp)) == NULL)
1072 goto out;
1073 tmp = cp + 1;
1074 }
1075
1076 /* Extract mandatory hostname */
1077 if ((cp = hpdelim2(&tmp, &ch)) == NULL || *cp == '\0')
1078 goto out;
1079 host = xstrdup(cleanhostname(cp));
1080 if (!valid_domain(host, 0, NULL))
1081 goto out;
1082
1083 if (tmp != NULL && *tmp != '\0') {
1084 if (ch == ':') {
1085 /* Convert and verify port. */
1086 if ((cp = strchr(tmp, '/')) != NULL)
1087 *cp = '\0';
1088 if ((port = a2port(tmp)) <= 0)
1089 goto out;
1090 tmp = cp ? cp + 1 : NULL;
1091 }
1092 if (tmp != NULL && *tmp != '\0') {
1093 /* Extract optional path */
1094 if ((path = urldecode(tmp)) == NULL)
1095 goto out;
1096 }
1097 }
1098
1099 /* Success */
1100 if (userp != NULL) {
1101 *userp = user;
1102 user = NULL;
1103 }
1104 if (hostp != NULL) {
1105 *hostp = host;
1106 host = NULL;
1107 }
1108 if (portp != NULL)
1109 *portp = port;
1110 if (pathp != NULL) {
1111 *pathp = path;
1112 path = NULL;
1113 }
1114 ret = 0;
1115 out:
1116 free(uridup);
1117 free(user);
1118 free(host);
1119 free(path);
1120 return ret;
1121 }
1122
1123 /* function to assist building execv() arguments */
1124 void
addargs(arglist * args,char * fmt,...)1125 addargs(arglist *args, char *fmt, ...)
1126 {
1127 va_list ap;
1128 char *cp;
1129 u_int nalloc;
1130 int r;
1131
1132 va_start(ap, fmt);
1133 r = vasprintf(&cp, fmt, ap);
1134 va_end(ap);
1135 if (r == -1)
1136 fatal_f("argument too long");
1137
1138 nalloc = args->nalloc;
1139 if (args->list == NULL) {
1140 nalloc = 32;
1141 args->num = 0;
1142 } else if (args->num > (256 * 1024))
1143 fatal_f("too many arguments");
1144 else if (args->num >= args->nalloc)
1145 fatal_f("arglist corrupt");
1146 else if (args->num+2 >= nalloc)
1147 nalloc *= 2;
1148
1149 args->list = xrecallocarray(args->list, args->nalloc,
1150 nalloc, sizeof(char *));
1151 args->nalloc = nalloc;
1152 args->list[args->num++] = cp;
1153 args->list[args->num] = NULL;
1154 }
1155
1156 void
replacearg(arglist * args,u_int which,char * fmt,...)1157 replacearg(arglist *args, u_int which, char *fmt, ...)
1158 {
1159 va_list ap;
1160 char *cp;
1161 int r;
1162
1163 va_start(ap, fmt);
1164 r = vasprintf(&cp, fmt, ap);
1165 va_end(ap);
1166 if (r == -1)
1167 fatal_f("argument too long");
1168 if (args->list == NULL || args->num >= args->nalloc)
1169 fatal_f("arglist corrupt");
1170
1171 if (which >= args->num)
1172 fatal_f("tried to replace invalid arg %d >= %d",
1173 which, args->num);
1174 free(args->list[which]);
1175 args->list[which] = cp;
1176 }
1177
1178 void
freeargs(arglist * args)1179 freeargs(arglist *args)
1180 {
1181 u_int i;
1182
1183 if (args == NULL)
1184 return;
1185 if (args->list != NULL && args->num < args->nalloc) {
1186 for (i = 0; i < args->num; i++)
1187 free(args->list[i]);
1188 free(args->list);
1189 }
1190 args->nalloc = args->num = 0;
1191 args->list = NULL;
1192 }
1193
1194 /*
1195 * Expands tildes in the file name. Returns data allocated by xmalloc.
1196 * Warning: this calls getpw*.
1197 */
1198 int
tilde_expand(const char * filename,uid_t uid,char ** retp)1199 tilde_expand(const char *filename, uid_t uid, char **retp)
1200 {
1201 char *ocopy = NULL, *copy, *s = NULL;
1202 const char *path = NULL, *user = NULL;
1203 struct passwd *pw;
1204 size_t len;
1205 int ret = -1, r, slash;
1206
1207 *retp = NULL;
1208 if (*filename != '~') {
1209 *retp = xstrdup(filename);
1210 return 0;
1211 }
1212 ocopy = copy = xstrdup(filename + 1);
1213
1214 if (*copy == '\0') /* ~ */
1215 path = NULL;
1216 else if (*copy == '/') {
1217 copy += strspn(copy, "/");
1218 if (*copy == '\0')
1219 path = NULL; /* ~/ */
1220 else
1221 path = copy; /* ~/path */
1222 } else {
1223 user = copy;
1224 if ((path = strchr(copy, '/')) != NULL) {
1225 copy[path - copy] = '\0';
1226 path++;
1227 path += strspn(path, "/");
1228 if (*path == '\0') /* ~user/ */
1229 path = NULL;
1230 /* else ~user/path */
1231 }
1232 /* else ~user */
1233 }
1234 if (user != NULL) {
1235 if ((pw = getpwnam(user)) == NULL) {
1236 error_f("No such user %s", user);
1237 goto out;
1238 }
1239 } else if ((pw = getpwuid(uid)) == NULL) {
1240 error_f("No such uid %ld", (long)uid);
1241 goto out;
1242 }
1243
1244 /* Make sure directory has a trailing '/' */
1245 slash = (len = strlen(pw->pw_dir)) == 0 || pw->pw_dir[len - 1] != '/';
1246
1247 if ((r = xasprintf(&s, "%s%s%s", pw->pw_dir,
1248 slash ? "/" : "", path != NULL ? path : "")) <= 0) {
1249 error_f("xasprintf failed");
1250 goto out;
1251 }
1252 if (r >= PATH_MAX) {
1253 error_f("Path too long");
1254 goto out;
1255 }
1256 /* success */
1257 ret = 0;
1258 *retp = s;
1259 s = NULL;
1260 out:
1261 free(s);
1262 free(ocopy);
1263 return ret;
1264 }
1265
1266 char *
tilde_expand_filename(const char * filename,uid_t uid)1267 tilde_expand_filename(const char *filename, uid_t uid)
1268 {
1269 char *ret;
1270
1271 if (tilde_expand(filename, uid, &ret) != 0)
1272 cleanup_exit(255);
1273 return ret;
1274 }
1275
1276 /*
1277 * Expand a string with a set of %[char] escapes and/or ${ENVIRONMENT}
1278 * substitutions. A number of escapes may be specified as
1279 * (char *escape_chars, char *replacement) pairs. The list must be terminated
1280 * by a NULL escape_char. Returns replaced string in memory allocated by
1281 * xmalloc which the caller must free.
1282 */
1283 static char *
vdollar_percent_expand(int * parseerror,int dollar,int percent,const char * string,va_list ap)1284 vdollar_percent_expand(int *parseerror, int dollar, int percent,
1285 const char *string, va_list ap)
1286 {
1287 #define EXPAND_MAX_KEYS 64
1288 u_int num_keys = 0, i;
1289 struct {
1290 const char *key;
1291 const char *repl;
1292 } keys[EXPAND_MAX_KEYS];
1293 struct sshbuf *buf;
1294 int r, missingvar = 0;
1295 char *ret = NULL, *var, *varend, *val;
1296 size_t len;
1297
1298 if ((buf = sshbuf_new()) == NULL)
1299 fatal_f("sshbuf_new failed");
1300 if (parseerror == NULL)
1301 fatal_f("null parseerror arg");
1302 *parseerror = 1;
1303
1304 /* Gather keys if we're doing percent expansion. */
1305 if (percent) {
1306 for (num_keys = 0; num_keys < EXPAND_MAX_KEYS; num_keys++) {
1307 keys[num_keys].key = va_arg(ap, char *);
1308 if (keys[num_keys].key == NULL)
1309 break;
1310 keys[num_keys].repl = va_arg(ap, char *);
1311 if (keys[num_keys].repl == NULL) {
1312 fatal_f("NULL replacement for token %s",
1313 keys[num_keys].key);
1314 }
1315 }
1316 if (num_keys == EXPAND_MAX_KEYS && va_arg(ap, char *) != NULL)
1317 fatal_f("too many keys");
1318 if (num_keys == 0)
1319 fatal_f("percent expansion without token list");
1320 }
1321
1322 /* Expand string */
1323 for (i = 0; *string != '\0'; string++) {
1324 /* Optionally process ${ENVIRONMENT} expansions. */
1325 if (dollar && string[0] == '$' && string[1] == '{') {
1326 string += 2; /* skip over '${' */
1327 if ((varend = strchr(string, '}')) == NULL) {
1328 error_f("environment variable '%s' missing "
1329 "closing '}'", string);
1330 goto out;
1331 }
1332 len = varend - string;
1333 if (len == 0) {
1334 error_f("zero-length environment variable");
1335 goto out;
1336 }
1337 var = xmalloc(len + 1);
1338 (void)strlcpy(var, string, len + 1);
1339 if ((val = getenv(var)) == NULL) {
1340 error_f("env var ${%s} has no value", var);
1341 missingvar = 1;
1342 } else {
1343 debug3_f("expand ${%s} -> '%s'", var, val);
1344 if ((r = sshbuf_put(buf, val, strlen(val))) !=0)
1345 fatal_fr(r, "sshbuf_put ${}");
1346 }
1347 free(var);
1348 string += len;
1349 continue;
1350 }
1351
1352 /*
1353 * Process percent expansions if we have a list of TOKENs.
1354 * If we're not doing percent expansion everything just gets
1355 * appended here.
1356 */
1357 if (*string != '%' || !percent) {
1358 append:
1359 if ((r = sshbuf_put_u8(buf, *string)) != 0)
1360 fatal_fr(r, "sshbuf_put_u8 %%");
1361 continue;
1362 }
1363 string++;
1364 /* %% case */
1365 if (*string == '%')
1366 goto append;
1367 if (*string == '\0') {
1368 error_f("invalid format");
1369 goto out;
1370 }
1371 for (i = 0; i < num_keys; i++) {
1372 if (strchr(keys[i].key, *string) != NULL) {
1373 if ((r = sshbuf_put(buf, keys[i].repl,
1374 strlen(keys[i].repl))) != 0)
1375 fatal_fr(r, "sshbuf_put %%-repl");
1376 break;
1377 }
1378 }
1379 if (i >= num_keys) {
1380 error_f("unknown key %%%c", *string);
1381 goto out;
1382 }
1383 }
1384 if (!missingvar && (ret = sshbuf_dup_string(buf)) == NULL)
1385 fatal_f("sshbuf_dup_string failed");
1386 *parseerror = 0;
1387 out:
1388 sshbuf_free(buf);
1389 return *parseerror ? NULL : ret;
1390 #undef EXPAND_MAX_KEYS
1391 }
1392
1393 /*
1394 * Expand only environment variables.
1395 * Note that although this function is variadic like the other similar
1396 * functions, any such arguments will be unused.
1397 */
1398
1399 char *
dollar_expand(int * parseerr,const char * string,...)1400 dollar_expand(int *parseerr, const char *string, ...)
1401 {
1402 char *ret;
1403 int err;
1404 va_list ap;
1405
1406 va_start(ap, string);
1407 ret = vdollar_percent_expand(&err, 1, 0, string, ap);
1408 va_end(ap);
1409 if (parseerr != NULL)
1410 *parseerr = err;
1411 return ret;
1412 }
1413
1414 /*
1415 * Returns expanded string or NULL if a specified environment variable is
1416 * not defined, or calls fatal if the string is invalid.
1417 */
1418 char *
percent_expand(const char * string,...)1419 percent_expand(const char *string, ...)
1420 {
1421 char *ret;
1422 int err;
1423 va_list ap;
1424
1425 va_start(ap, string);
1426 ret = vdollar_percent_expand(&err, 0, 1, string, ap);
1427 va_end(ap);
1428 if (err)
1429 fatal_f("failed");
1430 return ret;
1431 }
1432
1433 /*
1434 * Returns expanded string or NULL if a specified environment variable is
1435 * not defined, or calls fatal if the string is invalid.
1436 */
1437 char *
percent_dollar_expand(const char * string,...)1438 percent_dollar_expand(const char *string, ...)
1439 {
1440 char *ret;
1441 int err;
1442 va_list ap;
1443
1444 va_start(ap, string);
1445 ret = vdollar_percent_expand(&err, 1, 1, string, ap);
1446 va_end(ap);
1447 if (err)
1448 fatal_f("failed");
1449 return ret;
1450 }
1451
1452 int
tun_open(int tun,int mode,char ** ifname)1453 tun_open(int tun, int mode, char **ifname)
1454 {
1455 #if defined(CUSTOM_SYS_TUN_OPEN)
1456 return (sys_tun_open(tun, mode, ifname));
1457 #elif defined(SSH_TUN_OPENBSD)
1458 struct ifreq ifr;
1459 char name[100];
1460 int fd = -1, sock;
1461 const char *tunbase = "tun";
1462
1463 if (ifname != NULL)
1464 *ifname = NULL;
1465
1466 if (mode == SSH_TUNMODE_ETHERNET)
1467 tunbase = "tap";
1468
1469 /* Open the tunnel device */
1470 if (tun <= SSH_TUNID_MAX) {
1471 snprintf(name, sizeof(name), "/dev/%s%d", tunbase, tun);
1472 fd = open(name, O_RDWR);
1473 } else if (tun == SSH_TUNID_ANY) {
1474 for (tun = 100; tun >= 0; tun--) {
1475 snprintf(name, sizeof(name), "/dev/%s%d",
1476 tunbase, tun);
1477 if ((fd = open(name, O_RDWR)) >= 0)
1478 break;
1479 }
1480 } else {
1481 debug_f("invalid tunnel %u", tun);
1482 return -1;
1483 }
1484
1485 if (fd == -1) {
1486 debug_f("%s open: %s", name, strerror(errno));
1487 return -1;
1488 }
1489
1490 debug_f("%s mode %d fd %d", name, mode, fd);
1491
1492 /* Bring interface up if it is not already */
1493 snprintf(ifr.ifr_name, sizeof(ifr.ifr_name), "%s%d", tunbase, tun);
1494 if ((sock = socket(PF_UNIX, SOCK_STREAM, 0)) == -1)
1495 goto failed;
1496
1497 if (ioctl(sock, SIOCGIFFLAGS, &ifr) == -1) {
1498 debug_f("get interface %s flags: %s", ifr.ifr_name,
1499 strerror(errno));
1500 goto failed;
1501 }
1502
1503 if (!(ifr.ifr_flags & IFF_UP)) {
1504 ifr.ifr_flags |= IFF_UP;
1505 if (ioctl(sock, SIOCSIFFLAGS, &ifr) == -1) {
1506 debug_f("activate interface %s: %s", ifr.ifr_name,
1507 strerror(errno));
1508 goto failed;
1509 }
1510 }
1511
1512 if (ifname != NULL)
1513 *ifname = xstrdup(ifr.ifr_name);
1514
1515 close(sock);
1516 return fd;
1517
1518 failed:
1519 if (fd >= 0)
1520 close(fd);
1521 if (sock >= 0)
1522 close(sock);
1523 return -1;
1524 #else
1525 error("Tunnel interfaces are not supported on this platform");
1526 return (-1);
1527 #endif
1528 }
1529
1530 void
sanitise_stdfd(void)1531 sanitise_stdfd(void)
1532 {
1533 int nullfd, dupfd;
1534
1535 if ((nullfd = dupfd = open(_PATH_DEVNULL, O_RDWR)) == -1) {
1536 fprintf(stderr, "Couldn't open /dev/null: %s\n",
1537 strerror(errno));
1538 exit(1);
1539 }
1540 while (++dupfd <= STDERR_FILENO) {
1541 /* Only populate closed fds. */
1542 if (fcntl(dupfd, F_GETFL) == -1 && errno == EBADF) {
1543 if (dup2(nullfd, dupfd) == -1) {
1544 fprintf(stderr, "dup2: %s\n", strerror(errno));
1545 exit(1);
1546 }
1547 }
1548 }
1549 if (nullfd > STDERR_FILENO)
1550 close(nullfd);
1551 }
1552
1553 char *
tohex(const void * vp,size_t l)1554 tohex(const void *vp, size_t l)
1555 {
1556 const u_char *p = (const u_char *)vp;
1557 char b[3], *r;
1558 size_t i, hl;
1559
1560 if (l > 65536)
1561 return xstrdup("tohex: length > 65536");
1562
1563 hl = l * 2 + 1;
1564 r = xcalloc(1, hl);
1565 for (i = 0; i < l; i++) {
1566 snprintf(b, sizeof(b), "%02x", p[i]);
1567 strlcat(r, b, hl);
1568 }
1569 return (r);
1570 }
1571
1572 /*
1573 * Extend string *sp by the specified format. If *sp is not NULL (or empty),
1574 * then the separator 'sep' will be prepended before the formatted arguments.
1575 * Extended strings are heap allocated.
1576 */
1577 void
xextendf(char ** sp,const char * sep,const char * fmt,...)1578 xextendf(char **sp, const char *sep, const char *fmt, ...)
1579 {
1580 va_list ap;
1581 char *tmp1, *tmp2;
1582
1583 va_start(ap, fmt);
1584 xvasprintf(&tmp1, fmt, ap);
1585 va_end(ap);
1586
1587 if (*sp == NULL || **sp == '\0') {
1588 free(*sp);
1589 *sp = tmp1;
1590 return;
1591 }
1592 xasprintf(&tmp2, "%s%s%s", *sp, sep == NULL ? "" : sep, tmp1);
1593 free(tmp1);
1594 free(*sp);
1595 *sp = tmp2;
1596 }
1597
1598
1599 u_int64_t
get_u64(const void * vp)1600 get_u64(const void *vp)
1601 {
1602 const u_char *p = (const u_char *)vp;
1603 u_int64_t v;
1604
1605 v = (u_int64_t)p[0] << 56;
1606 v |= (u_int64_t)p[1] << 48;
1607 v |= (u_int64_t)p[2] << 40;
1608 v |= (u_int64_t)p[3] << 32;
1609 v |= (u_int64_t)p[4] << 24;
1610 v |= (u_int64_t)p[5] << 16;
1611 v |= (u_int64_t)p[6] << 8;
1612 v |= (u_int64_t)p[7];
1613
1614 return (v);
1615 }
1616
1617 u_int32_t
get_u32(const void * vp)1618 get_u32(const void *vp)
1619 {
1620 const u_char *p = (const u_char *)vp;
1621 u_int32_t v;
1622
1623 v = (u_int32_t)p[0] << 24;
1624 v |= (u_int32_t)p[1] << 16;
1625 v |= (u_int32_t)p[2] << 8;
1626 v |= (u_int32_t)p[3];
1627
1628 return (v);
1629 }
1630
1631 u_int32_t
get_u32_le(const void * vp)1632 get_u32_le(const void *vp)
1633 {
1634 const u_char *p = (const u_char *)vp;
1635 u_int32_t v;
1636
1637 v = (u_int32_t)p[0];
1638 v |= (u_int32_t)p[1] << 8;
1639 v |= (u_int32_t)p[2] << 16;
1640 v |= (u_int32_t)p[3] << 24;
1641
1642 return (v);
1643 }
1644
1645 u_int16_t
get_u16(const void * vp)1646 get_u16(const void *vp)
1647 {
1648 const u_char *p = (const u_char *)vp;
1649 u_int16_t v;
1650
1651 v = (u_int16_t)p[0] << 8;
1652 v |= (u_int16_t)p[1];
1653
1654 return (v);
1655 }
1656
1657 void
put_u64(void * vp,u_int64_t v)1658 put_u64(void *vp, u_int64_t v)
1659 {
1660 u_char *p = (u_char *)vp;
1661
1662 p[0] = (u_char)(v >> 56) & 0xff;
1663 p[1] = (u_char)(v >> 48) & 0xff;
1664 p[2] = (u_char)(v >> 40) & 0xff;
1665 p[3] = (u_char)(v >> 32) & 0xff;
1666 p[4] = (u_char)(v >> 24) & 0xff;
1667 p[5] = (u_char)(v >> 16) & 0xff;
1668 p[6] = (u_char)(v >> 8) & 0xff;
1669 p[7] = (u_char)v & 0xff;
1670 }
1671
1672 void
put_u32(void * vp,u_int32_t v)1673 put_u32(void *vp, u_int32_t v)
1674 {
1675 u_char *p = (u_char *)vp;
1676
1677 p[0] = (u_char)(v >> 24) & 0xff;
1678 p[1] = (u_char)(v >> 16) & 0xff;
1679 p[2] = (u_char)(v >> 8) & 0xff;
1680 p[3] = (u_char)v & 0xff;
1681 }
1682
1683 void
put_u32_le(void * vp,u_int32_t v)1684 put_u32_le(void *vp, u_int32_t v)
1685 {
1686 u_char *p = (u_char *)vp;
1687
1688 p[0] = (u_char)v & 0xff;
1689 p[1] = (u_char)(v >> 8) & 0xff;
1690 p[2] = (u_char)(v >> 16) & 0xff;
1691 p[3] = (u_char)(v >> 24) & 0xff;
1692 }
1693
1694 void
put_u16(void * vp,u_int16_t v)1695 put_u16(void *vp, u_int16_t v)
1696 {
1697 u_char *p = (u_char *)vp;
1698
1699 p[0] = (u_char)(v >> 8) & 0xff;
1700 p[1] = (u_char)v & 0xff;
1701 }
1702
1703 void
ms_subtract_diff(struct timeval * start,int * ms)1704 ms_subtract_diff(struct timeval *start, int *ms)
1705 {
1706 struct timeval diff, finish;
1707
1708 monotime_tv(&finish);
1709 timersub(&finish, start, &diff);
1710 *ms -= (diff.tv_sec * 1000) + (diff.tv_usec / 1000);
1711 }
1712
1713 void
ms_to_timespec(struct timespec * ts,int ms)1714 ms_to_timespec(struct timespec *ts, int ms)
1715 {
1716 if (ms < 0)
1717 ms = 0;
1718 ts->tv_sec = ms / 1000;
1719 ts->tv_nsec = (ms % 1000) * 1000 * 1000;
1720 }
1721
1722 void
monotime_ts(struct timespec * ts)1723 monotime_ts(struct timespec *ts)
1724 {
1725 struct timeval tv;
1726 #if defined(HAVE_CLOCK_GETTIME) && (defined(CLOCK_BOOTTIME) || \
1727 defined(CLOCK_MONOTONIC) || defined(CLOCK_REALTIME))
1728 static int gettime_failed = 0;
1729
1730 if (!gettime_failed) {
1731 # ifdef CLOCK_BOOTTIME
1732 if (clock_gettime(CLOCK_BOOTTIME, ts) == 0)
1733 return;
1734 # endif /* CLOCK_BOOTTIME */
1735 # ifdef CLOCK_MONOTONIC
1736 if (clock_gettime(CLOCK_MONOTONIC, ts) == 0)
1737 return;
1738 # endif /* CLOCK_MONOTONIC */
1739 # ifdef CLOCK_REALTIME
1740 /* Not monotonic, but we're almost out of options here. */
1741 if (clock_gettime(CLOCK_REALTIME, ts) == 0)
1742 return;
1743 # endif /* CLOCK_REALTIME */
1744 debug3("clock_gettime: %s", strerror(errno));
1745 gettime_failed = 1;
1746 }
1747 #endif /* HAVE_CLOCK_GETTIME && (BOOTTIME || MONOTONIC || REALTIME) */
1748 gettimeofday(&tv, NULL);
1749 ts->tv_sec = tv.tv_sec;
1750 ts->tv_nsec = (long)tv.tv_usec * 1000;
1751 }
1752
1753 void
monotime_tv(struct timeval * tv)1754 monotime_tv(struct timeval *tv)
1755 {
1756 struct timespec ts;
1757
1758 monotime_ts(&ts);
1759 tv->tv_sec = ts.tv_sec;
1760 tv->tv_usec = ts.tv_nsec / 1000;
1761 }
1762
1763 time_t
monotime(void)1764 monotime(void)
1765 {
1766 struct timespec ts;
1767
1768 monotime_ts(&ts);
1769 return ts.tv_sec;
1770 }
1771
1772 double
monotime_double(void)1773 monotime_double(void)
1774 {
1775 struct timespec ts;
1776
1777 monotime_ts(&ts);
1778 return ts.tv_sec + ((double)ts.tv_nsec / 1000000000);
1779 }
1780
1781 void
bandwidth_limit_init(struct bwlimit * bw,u_int64_t kbps,size_t buflen)1782 bandwidth_limit_init(struct bwlimit *bw, u_int64_t kbps, size_t buflen)
1783 {
1784 bw->buflen = buflen;
1785 bw->rate = kbps;
1786 bw->thresh = buflen;
1787 bw->lamt = 0;
1788 timerclear(&bw->bwstart);
1789 timerclear(&bw->bwend);
1790 }
1791
1792 /* Callback from read/write loop to insert bandwidth-limiting delays */
1793 void
bandwidth_limit(struct bwlimit * bw,size_t read_len)1794 bandwidth_limit(struct bwlimit *bw, size_t read_len)
1795 {
1796 u_int64_t waitlen;
1797 struct timespec ts, rm;
1798
1799 bw->lamt += read_len;
1800 if (!timerisset(&bw->bwstart)) {
1801 monotime_tv(&bw->bwstart);
1802 return;
1803 }
1804 if (bw->lamt < bw->thresh)
1805 return;
1806
1807 monotime_tv(&bw->bwend);
1808 timersub(&bw->bwend, &bw->bwstart, &bw->bwend);
1809 if (!timerisset(&bw->bwend))
1810 return;
1811
1812 bw->lamt *= 8;
1813 waitlen = (double)1000000L * bw->lamt / bw->rate;
1814
1815 bw->bwstart.tv_sec = waitlen / 1000000L;
1816 bw->bwstart.tv_usec = waitlen % 1000000L;
1817
1818 if (timercmp(&bw->bwstart, &bw->bwend, >)) {
1819 timersub(&bw->bwstart, &bw->bwend, &bw->bwend);
1820
1821 /* Adjust the wait time */
1822 if (bw->bwend.tv_sec) {
1823 bw->thresh /= 2;
1824 if (bw->thresh < bw->buflen / 4)
1825 bw->thresh = bw->buflen / 4;
1826 } else if (bw->bwend.tv_usec < 10000) {
1827 bw->thresh *= 2;
1828 if (bw->thresh > bw->buflen * 8)
1829 bw->thresh = bw->buflen * 8;
1830 }
1831
1832 TIMEVAL_TO_TIMESPEC(&bw->bwend, &ts);
1833 while (nanosleep(&ts, &rm) == -1) {
1834 if (errno != EINTR)
1835 break;
1836 ts = rm;
1837 }
1838 }
1839
1840 bw->lamt = 0;
1841 monotime_tv(&bw->bwstart);
1842 }
1843
1844 /* Make a template filename for mk[sd]temp() */
1845 void
mktemp_proto(char * s,size_t len)1846 mktemp_proto(char *s, size_t len)
1847 {
1848 const char *tmpdir;
1849 int r;
1850
1851 if ((tmpdir = getenv("TMPDIR")) != NULL) {
1852 r = snprintf(s, len, "%s/ssh-XXXXXXXXXXXX", tmpdir);
1853 if (r > 0 && (size_t)r < len)
1854 return;
1855 }
1856 r = snprintf(s, len, "/tmp/ssh-XXXXXXXXXXXX");
1857 if (r < 0 || (size_t)r >= len)
1858 fatal_f("template string too short");
1859 }
1860
1861 static const struct {
1862 const char *name;
1863 int value;
1864 } ipqos[] = {
1865 { "none", INT_MAX }, /* can't use 0 here; that's CS0 */
1866 { "af11", IPTOS_DSCP_AF11 },
1867 { "af12", IPTOS_DSCP_AF12 },
1868 { "af13", IPTOS_DSCP_AF13 },
1869 { "af21", IPTOS_DSCP_AF21 },
1870 { "af22", IPTOS_DSCP_AF22 },
1871 { "af23", IPTOS_DSCP_AF23 },
1872 { "af31", IPTOS_DSCP_AF31 },
1873 { "af32", IPTOS_DSCP_AF32 },
1874 { "af33", IPTOS_DSCP_AF33 },
1875 { "af41", IPTOS_DSCP_AF41 },
1876 { "af42", IPTOS_DSCP_AF42 },
1877 { "af43", IPTOS_DSCP_AF43 },
1878 { "cs0", IPTOS_DSCP_CS0 },
1879 { "cs1", IPTOS_DSCP_CS1 },
1880 { "cs2", IPTOS_DSCP_CS2 },
1881 { "cs3", IPTOS_DSCP_CS3 },
1882 { "cs4", IPTOS_DSCP_CS4 },
1883 { "cs5", IPTOS_DSCP_CS5 },
1884 { "cs6", IPTOS_DSCP_CS6 },
1885 { "cs7", IPTOS_DSCP_CS7 },
1886 { "ef", IPTOS_DSCP_EF },
1887 { "le", IPTOS_DSCP_LE },
1888 { "lowdelay", IPTOS_LOWDELAY },
1889 { "throughput", IPTOS_THROUGHPUT },
1890 { "reliability", IPTOS_RELIABILITY },
1891 { NULL, -1 }
1892 };
1893
1894 int
parse_ipqos(const char * cp)1895 parse_ipqos(const char *cp)
1896 {
1897 const char *errstr;
1898 u_int i;
1899 int val;
1900
1901 if (cp == NULL)
1902 return -1;
1903 for (i = 0; ipqos[i].name != NULL; i++) {
1904 if (strcasecmp(cp, ipqos[i].name) == 0)
1905 return ipqos[i].value;
1906 }
1907 /* Try parsing as an integer */
1908 val = (int)strtonum(cp, 0, 255, &errstr);
1909 if (errstr)
1910 return -1;
1911 return val;
1912 }
1913
1914 const char *
iptos2str(int iptos)1915 iptos2str(int iptos)
1916 {
1917 int i;
1918 static char iptos_str[sizeof "0xff"];
1919
1920 for (i = 0; ipqos[i].name != NULL; i++) {
1921 if (ipqos[i].value == iptos)
1922 return ipqos[i].name;
1923 }
1924 snprintf(iptos_str, sizeof iptos_str, "0x%02x", iptos);
1925 return iptos_str;
1926 }
1927
1928 void
lowercase(char * s)1929 lowercase(char *s)
1930 {
1931 for (; *s; s++)
1932 *s = tolower((u_char)*s);
1933 }
1934
1935 int
unix_listener(const char * path,int backlog,int unlink_first)1936 unix_listener(const char *path, int backlog, int unlink_first)
1937 {
1938 struct sockaddr_un sunaddr;
1939 int saved_errno, sock;
1940
1941 memset(&sunaddr, 0, sizeof(sunaddr));
1942 sunaddr.sun_family = AF_UNIX;
1943 if (strlcpy(sunaddr.sun_path, path,
1944 sizeof(sunaddr.sun_path)) >= sizeof(sunaddr.sun_path)) {
1945 error_f("path \"%s\" too long for Unix domain socket", path);
1946 errno = ENAMETOOLONG;
1947 return -1;
1948 }
1949
1950 sock = socket(PF_UNIX, SOCK_STREAM, 0);
1951 if (sock == -1) {
1952 saved_errno = errno;
1953 error_f("socket: %.100s", strerror(errno));
1954 errno = saved_errno;
1955 return -1;
1956 }
1957 if (unlink_first == 1) {
1958 if (unlink(path) != 0 && errno != ENOENT)
1959 error("unlink(%s): %.100s", path, strerror(errno));
1960 }
1961 if (bind(sock, (struct sockaddr *)&sunaddr, sizeof(sunaddr)) == -1) {
1962 saved_errno = errno;
1963 error_f("cannot bind to path %s: %s", path, strerror(errno));
1964 close(sock);
1965 errno = saved_errno;
1966 return -1;
1967 }
1968 if (listen(sock, backlog) == -1) {
1969 saved_errno = errno;
1970 error_f("cannot listen on path %s: %s", path, strerror(errno));
1971 close(sock);
1972 unlink(path);
1973 errno = saved_errno;
1974 return -1;
1975 }
1976 return sock;
1977 }
1978
1979 void
sock_set_v6only(int s)1980 sock_set_v6only(int s)
1981 {
1982 #if defined(IPV6_V6ONLY) && !defined(__OpenBSD__)
1983 int on = 1;
1984
1985 debug3("%s: set socket %d IPV6_V6ONLY", __func__, s);
1986 if (setsockopt(s, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof(on)) == -1)
1987 error("setsockopt IPV6_V6ONLY: %s", strerror(errno));
1988 #endif
1989 }
1990
1991 /*
1992 * Compares two strings that maybe be NULL. Returns non-zero if strings
1993 * are both NULL or are identical, returns zero otherwise.
1994 */
1995 static int
strcmp_maybe_null(const char * a,const char * b)1996 strcmp_maybe_null(const char *a, const char *b)
1997 {
1998 if ((a == NULL && b != NULL) || (a != NULL && b == NULL))
1999 return 0;
2000 if (a != NULL && strcmp(a, b) != 0)
2001 return 0;
2002 return 1;
2003 }
2004
2005 /*
2006 * Compare two forwards, returning non-zero if they are identical or
2007 * zero otherwise.
2008 */
2009 int
forward_equals(const struct Forward * a,const struct Forward * b)2010 forward_equals(const struct Forward *a, const struct Forward *b)
2011 {
2012 if (strcmp_maybe_null(a->listen_host, b->listen_host) == 0)
2013 return 0;
2014 if (a->listen_port != b->listen_port)
2015 return 0;
2016 if (strcmp_maybe_null(a->listen_path, b->listen_path) == 0)
2017 return 0;
2018 if (strcmp_maybe_null(a->connect_host, b->connect_host) == 0)
2019 return 0;
2020 if (a->connect_port != b->connect_port)
2021 return 0;
2022 if (strcmp_maybe_null(a->connect_path, b->connect_path) == 0)
2023 return 0;
2024 /* allocated_port and handle are not checked */
2025 return 1;
2026 }
2027
2028 /* returns port number, FWD_PERMIT_ANY_PORT or -1 on error */
2029 int
permitopen_port(const char * p)2030 permitopen_port(const char *p)
2031 {
2032 int port;
2033
2034 if (strcmp(p, "*") == 0)
2035 return FWD_PERMIT_ANY_PORT;
2036 if ((port = a2port(p)) > 0)
2037 return port;
2038 return -1;
2039 }
2040
2041 /* returns 1 if process is already daemonized, 0 otherwise */
2042 int
daemonized(void)2043 daemonized(void)
2044 {
2045 int fd;
2046
2047 if ((fd = open(_PATH_TTY, O_RDONLY | O_NOCTTY)) >= 0) {
2048 close(fd);
2049 return 0; /* have controlling terminal */
2050 }
2051 if (getppid() != 1)
2052 return 0; /* parent is not init */
2053 if (getsid(0) != getpid())
2054 return 0; /* not session leader */
2055 debug3("already daemonized");
2056 return 1;
2057 }
2058
2059 /*
2060 * Splits 's' into an argument vector. Handles quoted string and basic
2061 * escape characters (\\, \", \'). Caller must free the argument vector
2062 * and its members.
2063 */
2064 int
argv_split(const char * s,int * argcp,char *** argvp,int terminate_on_comment)2065 argv_split(const char *s, int *argcp, char ***argvp, int terminate_on_comment)
2066 {
2067 int r = SSH_ERR_INTERNAL_ERROR;
2068 int argc = 0, quote, i, j;
2069 char *arg, **argv = xcalloc(1, sizeof(*argv));
2070
2071 *argvp = NULL;
2072 *argcp = 0;
2073
2074 for (i = 0; s[i] != '\0'; i++) {
2075 /* Skip leading whitespace */
2076 if (s[i] == ' ' || s[i] == '\t')
2077 continue;
2078 if (terminate_on_comment && s[i] == '#')
2079 break;
2080 /* Start of a token */
2081 quote = 0;
2082
2083 argv = xreallocarray(argv, (argc + 2), sizeof(*argv));
2084 arg = argv[argc++] = xcalloc(1, strlen(s + i) + 1);
2085 argv[argc] = NULL;
2086
2087 /* Copy the token in, removing escapes */
2088 for (j = 0; s[i] != '\0'; i++) {
2089 if (s[i] == '\\') {
2090 if (s[i + 1] == '\'' ||
2091 s[i + 1] == '\"' ||
2092 s[i + 1] == '\\' ||
2093 (quote == 0 && s[i + 1] == ' ')) {
2094 i++; /* Skip '\' */
2095 arg[j++] = s[i];
2096 } else {
2097 /* Unrecognised escape */
2098 arg[j++] = s[i];
2099 }
2100 } else if (quote == 0 && (s[i] == ' ' || s[i] == '\t'))
2101 break; /* done */
2102 else if (quote == 0 && (s[i] == '\"' || s[i] == '\''))
2103 quote = s[i]; /* quote start */
2104 else if (quote != 0 && s[i] == quote)
2105 quote = 0; /* quote end */
2106 else
2107 arg[j++] = s[i];
2108 }
2109 if (s[i] == '\0') {
2110 if (quote != 0) {
2111 /* Ran out of string looking for close quote */
2112 r = SSH_ERR_INVALID_FORMAT;
2113 goto out;
2114 }
2115 break;
2116 }
2117 }
2118 /* Success */
2119 *argcp = argc;
2120 *argvp = argv;
2121 argc = 0;
2122 argv = NULL;
2123 r = 0;
2124 out:
2125 if (argc != 0 && argv != NULL) {
2126 for (i = 0; i < argc; i++)
2127 free(argv[i]);
2128 free(argv);
2129 }
2130 return r;
2131 }
2132
2133 /*
2134 * Reassemble an argument vector into a string, quoting and escaping as
2135 * necessary. Caller must free returned string.
2136 */
2137 char *
argv_assemble(int argc,char ** argv)2138 argv_assemble(int argc, char **argv)
2139 {
2140 int i, j, ws, r;
2141 char c, *ret;
2142 struct sshbuf *buf, *arg;
2143
2144 if ((buf = sshbuf_new()) == NULL || (arg = sshbuf_new()) == NULL)
2145 fatal_f("sshbuf_new failed");
2146
2147 for (i = 0; i < argc; i++) {
2148 ws = 0;
2149 sshbuf_reset(arg);
2150 for (j = 0; argv[i][j] != '\0'; j++) {
2151 r = 0;
2152 c = argv[i][j];
2153 switch (c) {
2154 case ' ':
2155 case '\t':
2156 ws = 1;
2157 r = sshbuf_put_u8(arg, c);
2158 break;
2159 case '\\':
2160 case '\'':
2161 case '"':
2162 if ((r = sshbuf_put_u8(arg, '\\')) != 0)
2163 break;
2164 /* FALLTHROUGH */
2165 default:
2166 r = sshbuf_put_u8(arg, c);
2167 break;
2168 }
2169 if (r != 0)
2170 fatal_fr(r, "sshbuf_put_u8");
2171 }
2172 if ((i != 0 && (r = sshbuf_put_u8(buf, ' ')) != 0) ||
2173 (ws != 0 && (r = sshbuf_put_u8(buf, '"')) != 0) ||
2174 (r = sshbuf_putb(buf, arg)) != 0 ||
2175 (ws != 0 && (r = sshbuf_put_u8(buf, '"')) != 0))
2176 fatal_fr(r, "assemble");
2177 }
2178 if ((ret = malloc(sshbuf_len(buf) + 1)) == NULL)
2179 fatal_f("malloc failed");
2180 memcpy(ret, sshbuf_ptr(buf), sshbuf_len(buf));
2181 ret[sshbuf_len(buf)] = '\0';
2182 sshbuf_free(buf);
2183 sshbuf_free(arg);
2184 return ret;
2185 }
2186
2187 char *
argv_next(int * argcp,char *** argvp)2188 argv_next(int *argcp, char ***argvp)
2189 {
2190 char *ret = (*argvp)[0];
2191
2192 if (*argcp > 0 && ret != NULL) {
2193 (*argcp)--;
2194 (*argvp)++;
2195 }
2196 return ret;
2197 }
2198
2199 void
argv_consume(int * argcp)2200 argv_consume(int *argcp)
2201 {
2202 *argcp = 0;
2203 }
2204
2205 void
argv_free(char ** av,int ac)2206 argv_free(char **av, int ac)
2207 {
2208 int i;
2209
2210 if (av == NULL)
2211 return;
2212 for (i = 0; i < ac; i++)
2213 free(av[i]);
2214 free(av);
2215 }
2216
2217 /* Returns 0 if pid exited cleanly, non-zero otherwise */
2218 int
exited_cleanly(pid_t pid,const char * tag,const char * cmd,int quiet)2219 exited_cleanly(pid_t pid, const char *tag, const char *cmd, int quiet)
2220 {
2221 int status;
2222
2223 while (waitpid(pid, &status, 0) == -1) {
2224 if (errno != EINTR) {
2225 error("%s waitpid: %s", tag, strerror(errno));
2226 return -1;
2227 }
2228 }
2229 if (WIFSIGNALED(status)) {
2230 error("%s %s exited on signal %d", tag, cmd, WTERMSIG(status));
2231 return -1;
2232 } else if (WEXITSTATUS(status) != 0) {
2233 do_log2(quiet ? SYSLOG_LEVEL_DEBUG1 : SYSLOG_LEVEL_INFO,
2234 "%s %s failed, status %d", tag, cmd, WEXITSTATUS(status));
2235 return -1;
2236 }
2237 return 0;
2238 }
2239
2240 /*
2241 * Check a given path for security. This is defined as all components
2242 * of the path to the file must be owned by either the owner of
2243 * of the file or root and no directories must be group or world writable.
2244 *
2245 * XXX Should any specific check be done for sym links ?
2246 *
2247 * Takes a file name, its stat information (preferably from fstat() to
2248 * avoid races), the uid of the expected owner, their home directory and an
2249 * error buffer plus max size as arguments.
2250 *
2251 * Returns 0 on success and -1 on failure
2252 */
2253 int
safe_path(const char * name,struct stat * stp,const char * pw_dir,uid_t uid,char * err,size_t errlen)2254 safe_path(const char *name, struct stat *stp, const char *pw_dir,
2255 uid_t uid, char *err, size_t errlen)
2256 {
2257 char buf[PATH_MAX], homedir[PATH_MAX];
2258 char *cp;
2259 int comparehome = 0;
2260 struct stat st;
2261
2262 if (realpath(name, buf) == NULL) {
2263 snprintf(err, errlen, "realpath %s failed: %s", name,
2264 strerror(errno));
2265 return -1;
2266 }
2267 if (pw_dir != NULL && realpath(pw_dir, homedir) != NULL)
2268 comparehome = 1;
2269
2270 if (!S_ISREG(stp->st_mode)) {
2271 snprintf(err, errlen, "%s is not a regular file", buf);
2272 return -1;
2273 }
2274 if ((!platform_sys_dir_uid(stp->st_uid) && stp->st_uid != uid) ||
2275 (stp->st_mode & 022) != 0) {
2276 snprintf(err, errlen, "bad ownership or modes for file %s",
2277 buf);
2278 return -1;
2279 }
2280
2281 /* for each component of the canonical path, walking upwards */
2282 for (;;) {
2283 if ((cp = dirname(buf)) == NULL) {
2284 snprintf(err, errlen, "dirname() failed");
2285 return -1;
2286 }
2287 strlcpy(buf, cp, sizeof(buf));
2288
2289 if (stat(buf, &st) == -1 ||
2290 (!platform_sys_dir_uid(st.st_uid) && st.st_uid != uid) ||
2291 (st.st_mode & 022) != 0) {
2292 snprintf(err, errlen,
2293 "bad ownership or modes for directory %s", buf);
2294 return -1;
2295 }
2296
2297 /* If are past the homedir then we can stop */
2298 if (comparehome && strcmp(homedir, buf) == 0)
2299 break;
2300
2301 /*
2302 * dirname should always complete with a "/" path,
2303 * but we can be paranoid and check for "." too
2304 */
2305 if ((strcmp("/", buf) == 0) || (strcmp(".", buf) == 0))
2306 break;
2307 }
2308 return 0;
2309 }
2310
2311 /*
2312 * Version of safe_path() that accepts an open file descriptor to
2313 * avoid races.
2314 *
2315 * Returns 0 on success and -1 on failure
2316 */
2317 int
safe_path_fd(int fd,const char * file,struct passwd * pw,char * err,size_t errlen)2318 safe_path_fd(int fd, const char *file, struct passwd *pw,
2319 char *err, size_t errlen)
2320 {
2321 struct stat st;
2322
2323 /* check the open file to avoid races */
2324 if (fstat(fd, &st) == -1) {
2325 snprintf(err, errlen, "cannot stat file %s: %s",
2326 file, strerror(errno));
2327 return -1;
2328 }
2329 return safe_path(file, &st, pw->pw_dir, pw->pw_uid, err, errlen);
2330 }
2331
2332 /*
2333 * Sets the value of the given variable in the environment. If the variable
2334 * already exists, its value is overridden.
2335 */
2336 void
child_set_env(char *** envp,u_int * envsizep,const char * name,const char * value)2337 child_set_env(char ***envp, u_int *envsizep, const char *name,
2338 const char *value)
2339 {
2340 char **env;
2341 u_int envsize;
2342 u_int i, namelen;
2343
2344 if (strchr(name, '=') != NULL) {
2345 error("Invalid environment variable \"%.100s\"", name);
2346 return;
2347 }
2348
2349 /*
2350 * If we're passed an uninitialized list, allocate a single null
2351 * entry before continuing.
2352 */
2353 if ((*envp == NULL) != (*envsizep == 0))
2354 fatal_f("environment size mismatch");
2355 if (*envp == NULL && *envsizep == 0) {
2356 *envp = xmalloc(sizeof(char *));
2357 *envp[0] = NULL;
2358 *envsizep = 1;
2359 }
2360
2361 /*
2362 * Find the slot where the value should be stored. If the variable
2363 * already exists, we reuse the slot; otherwise we append a new slot
2364 * at the end of the array, expanding if necessary.
2365 */
2366 env = *envp;
2367 namelen = strlen(name);
2368 for (i = 0; env[i]; i++)
2369 if (strncmp(env[i], name, namelen) == 0 && env[i][namelen] == '=')
2370 break;
2371 if (env[i]) {
2372 /* Reuse the slot. */
2373 free(env[i]);
2374 } else {
2375 /* New variable. Expand if necessary. */
2376 envsize = *envsizep;
2377 if (i >= envsize - 1) {
2378 if (envsize >= 1000)
2379 fatal("child_set_env: too many env vars");
2380 envsize += 50;
2381 env = (*envp) = xreallocarray(env, envsize, sizeof(char *));
2382 *envsizep = envsize;
2383 }
2384 /* Need to set the NULL pointer at end of array beyond the new slot. */
2385 env[i + 1] = NULL;
2386 }
2387
2388 /* Allocate space and format the variable in the appropriate slot. */
2389 /* XXX xasprintf */
2390 env[i] = xmalloc(strlen(name) + 1 + strlen(value) + 1);
2391 snprintf(env[i], strlen(name) + 1 + strlen(value) + 1, "%s=%s", name, value);
2392 }
2393
2394 /*
2395 * Check and optionally lowercase a domain name, also removes trailing '.'
2396 * Returns 1 on success and 0 on failure, storing an error message in errstr.
2397 */
2398 int
valid_domain(char * name,int makelower,const char ** errstr)2399 valid_domain(char *name, int makelower, const char **errstr)
2400 {
2401 size_t i, l = strlen(name);
2402 u_char c, last = '\0';
2403 static char errbuf[256];
2404
2405 if (l == 0) {
2406 strlcpy(errbuf, "empty domain name", sizeof(errbuf));
2407 goto bad;
2408 }
2409 if (!isalpha((u_char)name[0]) && !isdigit((u_char)name[0])) {
2410 snprintf(errbuf, sizeof(errbuf), "domain name \"%.100s\" "
2411 "starts with invalid character", name);
2412 goto bad;
2413 }
2414 for (i = 0; i < l; i++) {
2415 c = tolower((u_char)name[i]);
2416 if (makelower)
2417 name[i] = (char)c;
2418 if (last == '.' && c == '.') {
2419 snprintf(errbuf, sizeof(errbuf), "domain name "
2420 "\"%.100s\" contains consecutive separators", name);
2421 goto bad;
2422 }
2423 if (c != '.' && c != '-' && !isalnum(c) &&
2424 c != '_') /* technically invalid, but common */ {
2425 snprintf(errbuf, sizeof(errbuf), "domain name "
2426 "\"%.100s\" contains invalid characters", name);
2427 goto bad;
2428 }
2429 last = c;
2430 }
2431 if (name[l - 1] == '.')
2432 name[l - 1] = '\0';
2433 if (errstr != NULL)
2434 *errstr = NULL;
2435 return 1;
2436 bad:
2437 if (errstr != NULL)
2438 *errstr = errbuf;
2439 return 0;
2440 }
2441
2442 /*
2443 * Verify that a environment variable name (not including initial '$') is
2444 * valid; consisting of one or more alphanumeric or underscore characters only.
2445 * Returns 1 on valid, 0 otherwise.
2446 */
2447 int
valid_env_name(const char * name)2448 valid_env_name(const char *name)
2449 {
2450 const char *cp;
2451
2452 if (name[0] == '\0')
2453 return 0;
2454 for (cp = name; *cp != '\0'; cp++) {
2455 if (!isalnum((u_char)*cp) && *cp != '_')
2456 return 0;
2457 }
2458 return 1;
2459 }
2460
2461 const char *
atoi_err(const char * nptr,int * val)2462 atoi_err(const char *nptr, int *val)
2463 {
2464 const char *errstr = NULL;
2465
2466 if (nptr == NULL || *nptr == '\0')
2467 return "missing";
2468 *val = strtonum(nptr, 0, INT_MAX, &errstr);
2469 return errstr;
2470 }
2471
2472 int
parse_absolute_time(const char * s,uint64_t * tp)2473 parse_absolute_time(const char *s, uint64_t *tp)
2474 {
2475 struct tm tm;
2476 time_t tt;
2477 char buf[32], *fmt;
2478 const char *cp;
2479 size_t l;
2480 int is_utc = 0;
2481
2482 *tp = 0;
2483
2484 l = strlen(s);
2485 if (l > 1 && strcasecmp(s + l - 1, "Z") == 0) {
2486 is_utc = 1;
2487 l--;
2488 } else if (l > 3 && strcasecmp(s + l - 3, "UTC") == 0) {
2489 is_utc = 1;
2490 l -= 3;
2491 }
2492 /*
2493 * POSIX strptime says "The application shall ensure that there
2494 * is white-space or other non-alphanumeric characters between
2495 * any two conversion specifications" so arrange things this way.
2496 */
2497 switch (l) {
2498 case 8: /* YYYYMMDD */
2499 fmt = "%Y-%m-%d";
2500 snprintf(buf, sizeof(buf), "%.4s-%.2s-%.2s", s, s + 4, s + 6);
2501 break;
2502 case 12: /* YYYYMMDDHHMM */
2503 fmt = "%Y-%m-%dT%H:%M";
2504 snprintf(buf, sizeof(buf), "%.4s-%.2s-%.2sT%.2s:%.2s",
2505 s, s + 4, s + 6, s + 8, s + 10);
2506 break;
2507 case 14: /* YYYYMMDDHHMMSS */
2508 fmt = "%Y-%m-%dT%H:%M:%S";
2509 snprintf(buf, sizeof(buf), "%.4s-%.2s-%.2sT%.2s:%.2s:%.2s",
2510 s, s + 4, s + 6, s + 8, s + 10, s + 12);
2511 break;
2512 default:
2513 return SSH_ERR_INVALID_FORMAT;
2514 }
2515
2516 memset(&tm, 0, sizeof(tm));
2517 if ((cp = strptime(buf, fmt, &tm)) == NULL || *cp != '\0')
2518 return SSH_ERR_INVALID_FORMAT;
2519 if (is_utc) {
2520 if ((tt = timegm(&tm)) < 0)
2521 return SSH_ERR_INVALID_FORMAT;
2522 } else {
2523 if ((tt = mktime(&tm)) < 0)
2524 return SSH_ERR_INVALID_FORMAT;
2525 }
2526 /* success */
2527 *tp = (uint64_t)tt;
2528 return 0;
2529 }
2530
2531 void
format_absolute_time(uint64_t t,char * buf,size_t len)2532 format_absolute_time(uint64_t t, char *buf, size_t len)
2533 {
2534 time_t tt = t > SSH_TIME_T_MAX ? SSH_TIME_T_MAX : t;
2535 struct tm tm;
2536
2537 localtime_r(&tt, &tm);
2538 strftime(buf, len, "%Y-%m-%dT%H:%M:%S", &tm);
2539 }
2540
2541 /*
2542 * Parse a "pattern=interval" clause (e.g. a ChannelTimeout).
2543 * Returns 0 on success or non-zero on failure.
2544 * Caller must free *typep.
2545 */
2546 int
parse_pattern_interval(const char * s,char ** typep,int * secsp)2547 parse_pattern_interval(const char *s, char **typep, int *secsp)
2548 {
2549 char *cp, *sdup;
2550 int secs;
2551
2552 if (typep != NULL)
2553 *typep = NULL;
2554 if (secsp != NULL)
2555 *secsp = 0;
2556 if (s == NULL)
2557 return -1;
2558 sdup = xstrdup(s);
2559
2560 if ((cp = strchr(sdup, '=')) == NULL || cp == sdup) {
2561 free(sdup);
2562 return -1;
2563 }
2564 *cp++ = '\0';
2565 if ((secs = convtime(cp)) < 0) {
2566 free(sdup);
2567 return -1;
2568 }
2569 /* success */
2570 if (typep != NULL)
2571 *typep = xstrdup(sdup);
2572 if (secsp != NULL)
2573 *secsp = secs;
2574 free(sdup);
2575 return 0;
2576 }
2577
2578 /* check if path is absolute */
2579 int
path_absolute(const char * path)2580 path_absolute(const char *path)
2581 {
2582 return (*path == '/') ? 1 : 0;
2583 }
2584
2585 void
skip_space(char ** cpp)2586 skip_space(char **cpp)
2587 {
2588 char *cp;
2589
2590 for (cp = *cpp; *cp == ' ' || *cp == '\t'; cp++)
2591 ;
2592 *cpp = cp;
2593 }
2594
2595 /* authorized_key-style options parsing helpers */
2596
2597 /*
2598 * Match flag 'opt' in *optsp, and if allow_negate is set then also match
2599 * 'no-opt'. Returns -1 if option not matched, 1 if option matches or 0
2600 * if negated option matches.
2601 * If the option or negated option matches, then *optsp is updated to
2602 * point to the first character after the option.
2603 */
2604 int
opt_flag(const char * opt,int allow_negate,const char ** optsp)2605 opt_flag(const char *opt, int allow_negate, const char **optsp)
2606 {
2607 size_t opt_len = strlen(opt);
2608 const char *opts = *optsp;
2609 int negate = 0;
2610
2611 if (allow_negate && strncasecmp(opts, "no-", 3) == 0) {
2612 opts += 3;
2613 negate = 1;
2614 }
2615 if (strncasecmp(opts, opt, opt_len) == 0) {
2616 *optsp = opts + opt_len;
2617 return negate ? 0 : 1;
2618 }
2619 return -1;
2620 }
2621
2622 char *
opt_dequote(const char ** sp,const char ** errstrp)2623 opt_dequote(const char **sp, const char **errstrp)
2624 {
2625 const char *s = *sp;
2626 char *ret;
2627 size_t i;
2628
2629 *errstrp = NULL;
2630 if (*s != '"') {
2631 *errstrp = "missing start quote";
2632 return NULL;
2633 }
2634 s++;
2635 if ((ret = malloc(strlen((s)) + 1)) == NULL) {
2636 *errstrp = "memory allocation failed";
2637 return NULL;
2638 }
2639 for (i = 0; *s != '\0' && *s != '"';) {
2640 if (s[0] == '\\' && s[1] == '"')
2641 s++;
2642 ret[i++] = *s++;
2643 }
2644 if (*s == '\0') {
2645 *errstrp = "missing end quote";
2646 free(ret);
2647 return NULL;
2648 }
2649 ret[i] = '\0';
2650 s++;
2651 *sp = s;
2652 return ret;
2653 }
2654
2655 int
opt_match(const char ** opts,const char * term)2656 opt_match(const char **opts, const char *term)
2657 {
2658 if (strncasecmp((*opts), term, strlen(term)) == 0 &&
2659 (*opts)[strlen(term)] == '=') {
2660 *opts += strlen(term) + 1;
2661 return 1;
2662 }
2663 return 0;
2664 }
2665
2666 void
opt_array_append2(const char * file,const int line,const char * directive,char *** array,int ** iarray,u_int * lp,const char * s,int i)2667 opt_array_append2(const char *file, const int line, const char *directive,
2668 char ***array, int **iarray, u_int *lp, const char *s, int i)
2669 {
2670
2671 if (*lp >= INT_MAX)
2672 fatal("%s line %d: Too many %s entries", file, line, directive);
2673
2674 if (iarray != NULL) {
2675 *iarray = xrecallocarray(*iarray, *lp, *lp + 1,
2676 sizeof(**iarray));
2677 (*iarray)[*lp] = i;
2678 }
2679
2680 *array = xrecallocarray(*array, *lp, *lp + 1, sizeof(**array));
2681 (*array)[*lp] = xstrdup(s);
2682 (*lp)++;
2683 }
2684
2685 void
opt_array_append(const char * file,const int line,const char * directive,char *** array,u_int * lp,const char * s)2686 opt_array_append(const char *file, const int line, const char *directive,
2687 char ***array, u_int *lp, const char *s)
2688 {
2689 opt_array_append2(file, line, directive, array, NULL, lp, s, 0);
2690 }
2691
2692 void
opt_array_free2(char ** array,int ** iarray,u_int l)2693 opt_array_free2(char **array, int **iarray, u_int l)
2694 {
2695 u_int i;
2696
2697 if (array == NULL || l == 0)
2698 return;
2699 for (i = 0; i < l; i++)
2700 free(array[i]);
2701 free(array);
2702 free(iarray);
2703 }
2704
2705 sshsig_t
ssh_signal(int signum,sshsig_t handler)2706 ssh_signal(int signum, sshsig_t handler)
2707 {
2708 struct sigaction sa, osa;
2709
2710 /* mask all other signals while in handler */
2711 memset(&sa, 0, sizeof(sa));
2712 sa.sa_handler = handler;
2713 sigfillset(&sa.sa_mask);
2714 #if defined(SA_RESTART) && !defined(NO_SA_RESTART)
2715 if (signum != SIGALRM)
2716 sa.sa_flags = SA_RESTART;
2717 #endif
2718 if (sigaction(signum, &sa, &osa) == -1) {
2719 debug3("sigaction(%s): %s", strsignal(signum), strerror(errno));
2720 return SIG_ERR;
2721 }
2722 return osa.sa_handler;
2723 }
2724
2725 int
stdfd_devnull(int do_stdin,int do_stdout,int do_stderr)2726 stdfd_devnull(int do_stdin, int do_stdout, int do_stderr)
2727 {
2728 int devnull, ret = 0;
2729
2730 if ((devnull = open(_PATH_DEVNULL, O_RDWR)) == -1) {
2731 error_f("open %s: %s", _PATH_DEVNULL,
2732 strerror(errno));
2733 return -1;
2734 }
2735 if ((do_stdin && dup2(devnull, STDIN_FILENO) == -1) ||
2736 (do_stdout && dup2(devnull, STDOUT_FILENO) == -1) ||
2737 (do_stderr && dup2(devnull, STDERR_FILENO) == -1)) {
2738 error_f("dup2: %s", strerror(errno));
2739 ret = -1;
2740 }
2741 if (devnull > STDERR_FILENO)
2742 close(devnull);
2743 return ret;
2744 }
2745
2746 /*
2747 * Runs command in a subprocess with a minimal environment.
2748 * Returns pid on success, 0 on failure.
2749 * The child stdout and stderr maybe captured, left attached or sent to
2750 * /dev/null depending on the contents of flags.
2751 * "tag" is prepended to log messages.
2752 * NB. "command" is only used for logging; the actual command executed is
2753 * av[0].
2754 */
2755 pid_t
subprocess(const char * tag,const char * command,int ac,char ** av,FILE ** child,u_int flags,struct passwd * pw,privdrop_fn * drop_privs,privrestore_fn * restore_privs)2756 subprocess(const char *tag, const char *command,
2757 int ac, char **av, FILE **child, u_int flags,
2758 struct passwd *pw, privdrop_fn *drop_privs, privrestore_fn *restore_privs)
2759 {
2760 FILE *f = NULL;
2761 struct stat st;
2762 int fd, devnull, p[2], i;
2763 pid_t pid;
2764 char *cp, errmsg[512];
2765 u_int nenv = 0;
2766 char **env = NULL;
2767
2768 /* If dropping privs, then must specify user and restore function */
2769 if (drop_privs != NULL && (pw == NULL || restore_privs == NULL)) {
2770 error("%s: inconsistent arguments", tag); /* XXX fatal? */
2771 return 0;
2772 }
2773 if (pw == NULL && (pw = getpwuid(getuid())) == NULL) {
2774 error("%s: no user for current uid", tag);
2775 return 0;
2776 }
2777 if (child != NULL)
2778 *child = NULL;
2779
2780 debug3_f("%s command \"%s\" running as %s (flags 0x%x)",
2781 tag, command, pw->pw_name, flags);
2782
2783 /* Check consistency */
2784 if ((flags & SSH_SUBPROCESS_STDOUT_DISCARD) != 0 &&
2785 (flags & SSH_SUBPROCESS_STDOUT_CAPTURE) != 0) {
2786 error_f("inconsistent flags");
2787 return 0;
2788 }
2789 if (((flags & SSH_SUBPROCESS_STDOUT_CAPTURE) == 0) != (child == NULL)) {
2790 error_f("inconsistent flags/output");
2791 return 0;
2792 }
2793
2794 /*
2795 * If executing an explicit binary, then verify the it exists
2796 * and appears safe-ish to execute
2797 */
2798 if (!path_absolute(av[0])) {
2799 error("%s path is not absolute", tag);
2800 return 0;
2801 }
2802 if (drop_privs != NULL)
2803 drop_privs(pw);
2804 if (stat(av[0], &st) == -1) {
2805 error("Could not stat %s \"%s\": %s", tag,
2806 av[0], strerror(errno));
2807 goto restore_return;
2808 }
2809 if ((flags & SSH_SUBPROCESS_UNSAFE_PATH) == 0 &&
2810 safe_path(av[0], &st, NULL, 0, errmsg, sizeof(errmsg)) != 0) {
2811 error("Unsafe %s \"%s\": %s", tag, av[0], errmsg);
2812 goto restore_return;
2813 }
2814 /* Prepare to keep the child's stdout if requested */
2815 if (pipe(p) == -1) {
2816 error("%s: pipe: %s", tag, strerror(errno));
2817 restore_return:
2818 if (restore_privs != NULL)
2819 restore_privs();
2820 return 0;
2821 }
2822 if (restore_privs != NULL)
2823 restore_privs();
2824
2825 switch ((pid = fork())) {
2826 case -1: /* error */
2827 error("%s: fork: %s", tag, strerror(errno));
2828 close(p[0]);
2829 close(p[1]);
2830 return 0;
2831 case 0: /* child */
2832 /* Prepare a minimal environment for the child. */
2833 if ((flags & SSH_SUBPROCESS_PRESERVE_ENV) == 0) {
2834 nenv = 5;
2835 env = xcalloc(sizeof(*env), nenv);
2836 child_set_env(&env, &nenv, "PATH", _PATH_STDPATH);
2837 child_set_env(&env, &nenv, "USER", pw->pw_name);
2838 child_set_env(&env, &nenv, "LOGNAME", pw->pw_name);
2839 child_set_env(&env, &nenv, "HOME", pw->pw_dir);
2840 if ((cp = getenv("LANG")) != NULL)
2841 child_set_env(&env, &nenv, "LANG", cp);
2842 }
2843
2844 for (i = 1; i < NSIG; i++)
2845 ssh_signal(i, SIG_DFL);
2846
2847 if ((devnull = open(_PATH_DEVNULL, O_RDWR)) == -1) {
2848 error("%s: open %s: %s", tag, _PATH_DEVNULL,
2849 strerror(errno));
2850 _exit(1);
2851 }
2852 if (dup2(devnull, STDIN_FILENO) == -1) {
2853 error("%s: dup2: %s", tag, strerror(errno));
2854 _exit(1);
2855 }
2856
2857 /* Set up stdout as requested; leave stderr in place for now. */
2858 fd = -1;
2859 if ((flags & SSH_SUBPROCESS_STDOUT_CAPTURE) != 0)
2860 fd = p[1];
2861 else if ((flags & SSH_SUBPROCESS_STDOUT_DISCARD) != 0)
2862 fd = devnull;
2863 if (fd != -1 && dup2(fd, STDOUT_FILENO) == -1) {
2864 error("%s: dup2: %s", tag, strerror(errno));
2865 _exit(1);
2866 }
2867 closefrom(STDERR_FILENO + 1);
2868
2869 if (geteuid() == 0 &&
2870 initgroups(pw->pw_name, pw->pw_gid) == -1) {
2871 error("%s: initgroups(%s, %u): %s", tag,
2872 pw->pw_name, (u_int)pw->pw_gid, strerror(errno));
2873 _exit(1);
2874 }
2875 if (setresgid(pw->pw_gid, pw->pw_gid, pw->pw_gid) == -1) {
2876 error("%s: setresgid %u: %s", tag, (u_int)pw->pw_gid,
2877 strerror(errno));
2878 _exit(1);
2879 }
2880 if (setresuid(pw->pw_uid, pw->pw_uid, pw->pw_uid) == -1) {
2881 error("%s: setresuid %u: %s", tag, (u_int)pw->pw_uid,
2882 strerror(errno));
2883 _exit(1);
2884 }
2885 /* stdin is pointed to /dev/null at this point */
2886 if ((flags & SSH_SUBPROCESS_STDOUT_DISCARD) != 0 &&
2887 dup2(STDIN_FILENO, STDERR_FILENO) == -1) {
2888 error("%s: dup2: %s", tag, strerror(errno));
2889 _exit(1);
2890 }
2891 if (env != NULL)
2892 execve(av[0], av, env);
2893 else
2894 execv(av[0], av);
2895 error("%s %s \"%s\": %s", tag, env == NULL ? "execv" : "execve",
2896 command, strerror(errno));
2897 _exit(127);
2898 default: /* parent */
2899 break;
2900 }
2901
2902 close(p[1]);
2903 if ((flags & SSH_SUBPROCESS_STDOUT_CAPTURE) == 0)
2904 close(p[0]);
2905 else if ((f = fdopen(p[0], "r")) == NULL) {
2906 error("%s: fdopen: %s", tag, strerror(errno));
2907 close(p[0]);
2908 /* Don't leave zombie child */
2909 kill(pid, SIGTERM);
2910 while (waitpid(pid, NULL, 0) == -1 && errno == EINTR)
2911 ;
2912 return 0;
2913 }
2914 /* Success */
2915 debug3_f("%s pid %ld", tag, (long)pid);
2916 if (child != NULL)
2917 *child = f;
2918 return pid;
2919 }
2920
2921 const char *
lookup_env_in_list(const char * env,char * const * envs,size_t nenvs)2922 lookup_env_in_list(const char *env, char * const *envs, size_t nenvs)
2923 {
2924 size_t i, envlen;
2925
2926 envlen = strlen(env);
2927 for (i = 0; i < nenvs; i++) {
2928 if (strncmp(envs[i], env, envlen) == 0 &&
2929 envs[i][envlen] == '=') {
2930 return envs[i] + envlen + 1;
2931 }
2932 }
2933 return NULL;
2934 }
2935
2936 const char *
lookup_setenv_in_list(const char * env,char * const * envs,size_t nenvs)2937 lookup_setenv_in_list(const char *env, char * const *envs, size_t nenvs)
2938 {
2939 char *name, *cp;
2940 const char *ret;
2941
2942 name = xstrdup(env);
2943 if ((cp = strchr(name, '=')) == NULL) {
2944 free(name);
2945 return NULL; /* not env=val */
2946 }
2947 *cp = '\0';
2948 ret = lookup_env_in_list(name, envs, nenvs);
2949 free(name);
2950 return ret;
2951 }
2952
2953 /*
2954 * Helpers for managing poll(2)/ppoll(2) timeouts
2955 * Will remember the earliest deadline and return it for use in poll/ppoll.
2956 */
2957
2958 /* Initialise a poll/ppoll timeout with an indefinite deadline */
2959 void
ptimeout_init(struct timespec * pt)2960 ptimeout_init(struct timespec *pt)
2961 {
2962 /*
2963 * Deliberately invalid for ppoll(2).
2964 * Will be converted to NULL in ptimeout_get_tspec() later.
2965 */
2966 pt->tv_sec = -1;
2967 pt->tv_nsec = 0;
2968 }
2969
2970 /* Specify a poll/ppoll deadline of at most 'sec' seconds */
2971 void
ptimeout_deadline_sec(struct timespec * pt,long sec)2972 ptimeout_deadline_sec(struct timespec *pt, long sec)
2973 {
2974 if (pt->tv_sec == -1 || pt->tv_sec >= sec) {
2975 pt->tv_sec = sec;
2976 pt->tv_nsec = 0;
2977 }
2978 }
2979
2980 /* Specify a poll/ppoll deadline of at most 'p' (timespec) */
2981 static void
ptimeout_deadline_tsp(struct timespec * pt,struct timespec * p)2982 ptimeout_deadline_tsp(struct timespec *pt, struct timespec *p)
2983 {
2984 if (pt->tv_sec == -1 || timespeccmp(pt, p, >=))
2985 *pt = *p;
2986 }
2987
2988 /* Specify a poll/ppoll deadline of at most 'ms' milliseconds */
2989 void
ptimeout_deadline_ms(struct timespec * pt,long ms)2990 ptimeout_deadline_ms(struct timespec *pt, long ms)
2991 {
2992 struct timespec p;
2993
2994 p.tv_sec = ms / 1000;
2995 p.tv_nsec = (ms % 1000) * 1000000;
2996 ptimeout_deadline_tsp(pt, &p);
2997 }
2998
2999 /* Specify a poll/ppoll deadline at wall clock monotime 'when' (timespec) */
3000 void
ptimeout_deadline_monotime_tsp(struct timespec * pt,struct timespec * when)3001 ptimeout_deadline_monotime_tsp(struct timespec *pt, struct timespec *when)
3002 {
3003 struct timespec now, t;
3004
3005 monotime_ts(&now);
3006
3007 if (timespeccmp(&now, when, >=)) {
3008 /* 'when' is now or in the past. Timeout ASAP */
3009 pt->tv_sec = 0;
3010 pt->tv_nsec = 0;
3011 } else {
3012 timespecsub(when, &now, &t);
3013 ptimeout_deadline_tsp(pt, &t);
3014 }
3015 }
3016
3017 /* Specify a poll/ppoll deadline at wall clock monotime 'when' */
3018 void
ptimeout_deadline_monotime(struct timespec * pt,time_t when)3019 ptimeout_deadline_monotime(struct timespec *pt, time_t when)
3020 {
3021 struct timespec t;
3022
3023 t.tv_sec = when;
3024 t.tv_nsec = 0;
3025 ptimeout_deadline_monotime_tsp(pt, &t);
3026 }
3027
3028 /* Get a poll(2) timeout value in milliseconds */
3029 int
ptimeout_get_ms(struct timespec * pt)3030 ptimeout_get_ms(struct timespec *pt)
3031 {
3032 if (pt->tv_sec == -1)
3033 return -1;
3034 if (pt->tv_sec >= (INT_MAX - (pt->tv_nsec / 1000000)) / 1000)
3035 return INT_MAX;
3036 return (pt->tv_sec * 1000) + (pt->tv_nsec / 1000000);
3037 }
3038
3039 /* Get a ppoll(2) timeout value as a timespec pointer */
3040 struct timespec *
ptimeout_get_tsp(struct timespec * pt)3041 ptimeout_get_tsp(struct timespec *pt)
3042 {
3043 return pt->tv_sec == -1 ? NULL : pt;
3044 }
3045
3046 /* Returns non-zero if a timeout has been set (i.e. is not indefinite) */
3047 int
ptimeout_isset(struct timespec * pt)3048 ptimeout_isset(struct timespec *pt)
3049 {
3050 return pt->tv_sec != -1;
3051 }
3052
3053 /*
3054 * Returns zero if the library at 'path' contains symbol 's', nonzero
3055 * otherwise.
3056 */
3057 int
lib_contains_symbol(const char * path,const char * s)3058 lib_contains_symbol(const char *path, const char *s)
3059 {
3060 #ifdef HAVE_NLIST_H
3061 struct nlist nl[2];
3062 int ret = -1, r;
3063
3064 memset(nl, 0, sizeof(nl));
3065 nl[0].n_name = xstrdup(s);
3066 nl[1].n_name = NULL;
3067 if ((r = nlist(path, nl)) == -1) {
3068 error_f("nlist failed for %s", path);
3069 goto out;
3070 }
3071 if (r != 0 || nl[0].n_value == 0 || nl[0].n_type == 0) {
3072 error_f("library %s does not contain symbol %s", path, s);
3073 goto out;
3074 }
3075 /* success */
3076 ret = 0;
3077 out:
3078 free(nl[0].n_name);
3079 return ret;
3080 #else /* HAVE_NLIST_H */
3081 int fd, ret = -1;
3082 struct stat st;
3083 void *m = NULL;
3084 size_t sz = 0;
3085
3086 memset(&st, 0, sizeof(st));
3087 if ((fd = open(path, O_RDONLY)) < 0) {
3088 error_f("open %s: %s", path, strerror(errno));
3089 return -1;
3090 }
3091 if (fstat(fd, &st) != 0) {
3092 error_f("fstat %s: %s", path, strerror(errno));
3093 goto out;
3094 }
3095 if (!S_ISREG(st.st_mode)) {
3096 error_f("%s is not a regular file", path);
3097 goto out;
3098 }
3099 if (st.st_size < 0 ||
3100 (size_t)st.st_size < strlen(s) ||
3101 st.st_size >= INT_MAX/2) {
3102 error_f("%s bad size %lld", path, (long long)st.st_size);
3103 goto out;
3104 }
3105 sz = (size_t)st.st_size;
3106 if ((m = mmap(NULL, sz, PROT_READ, MAP_PRIVATE, fd, 0)) == MAP_FAILED ||
3107 m == NULL) {
3108 error_f("mmap %s: %s", path, strerror(errno));
3109 goto out;
3110 }
3111 if (memmem(m, sz, s, strlen(s)) == NULL) {
3112 error_f("%s does not contain expected string %s", path, s);
3113 goto out;
3114 }
3115 /* success */
3116 ret = 0;
3117 out:
3118 if (m != NULL && m != MAP_FAILED)
3119 munmap(m, sz);
3120 close(fd);
3121 return ret;
3122 #endif /* HAVE_NLIST_H */
3123 }
3124
3125 int
signal_is_crash(int sig)3126 signal_is_crash(int sig)
3127 {
3128 switch (sig) {
3129 case SIGSEGV:
3130 case SIGBUS:
3131 case SIGTRAP:
3132 case SIGSYS:
3133 case SIGFPE:
3134 case SIGILL:
3135 case SIGABRT:
3136 return 1;
3137 }
3138 return 0;
3139 }
3140