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