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