blob: cfd32729ac7a50de28551186f2e1da03dc8b1dd2 [file] [log] [blame]
Greg Hartman9768ca42017-06-22 20:49:52 -07001/* $OpenBSD: misc.c,v 1.109 2017/03/14 00:55:37 dtucker Exp $ */
Greg Hartmanbd77cf72015-02-25 13:21:06 -08002/*
3 * Copyright (c) 2000 Markus Friedl. All rights reserved.
4 * Copyright (c) 2005,2006 Damien Miller. All rights reserved.
5 *
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions
8 * are met:
9 * 1. Redistributions of source code must retain the above copyright
10 * notice, this list of conditions and the following disclaimer.
11 * 2. Redistributions in binary form must reproduce the above copyright
12 * notice, this list of conditions and the following disclaimer in the
13 * documentation and/or other materials provided with the distribution.
14 *
15 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
16 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
17 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
18 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
19 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
20 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
21 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
22 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
23 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
24 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
25 */
26
27#include "includes.h"
28
29#include <sys/types.h>
30#include <sys/ioctl.h>
31#include <sys/socket.h>
Greg Hartman9768ca42017-06-22 20:49:52 -070032#include <sys/time.h>
Adam Langleyd0592972015-03-30 14:49:51 -070033#include <sys/un.h>
Greg Hartmanbd77cf72015-02-25 13:21:06 -080034
Adam Langleyd0592972015-03-30 14:49:51 -070035#include <limits.h>
Greg Hartmanbd77cf72015-02-25 13:21:06 -080036#include <stdarg.h>
37#include <stdio.h>
38#include <stdlib.h>
39#include <string.h>
40#include <time.h>
41#include <unistd.h>
42
43#include <netinet/in.h>
44#include <netinet/in_systm.h>
45#include <netinet/ip.h>
46#include <netinet/tcp.h>
47
Adam Langleyd0592972015-03-30 14:49:51 -070048#include <ctype.h>
Greg Hartmanbd77cf72015-02-25 13:21:06 -080049#include <errno.h>
50#include <fcntl.h>
51#include <netdb.h>
52#ifdef HAVE_PATHS_H
53# include <paths.h>
54#include <pwd.h>
55#endif
56#ifdef SSH_TUN_OPENBSD
57#include <net/if.h>
58#endif
59
60#include "xmalloc.h"
61#include "misc.h"
62#include "log.h"
63#include "ssh.h"
64
65/* remove newline at end of string */
66char *
67chop(char *s)
68{
69 char *t = s;
70 while (*t) {
71 if (*t == '\n' || *t == '\r') {
72 *t = '\0';
73 return s;
74 }
75 t++;
76 }
77 return s;
78
79}
80
81/* set/unset filedescriptor to non-blocking */
82int
83set_nonblock(int fd)
84{
85 int val;
86
Greg Hartman9768ca42017-06-22 20:49:52 -070087 val = fcntl(fd, F_GETFL);
Greg Hartmanbd77cf72015-02-25 13:21:06 -080088 if (val < 0) {
Greg Hartman9768ca42017-06-22 20:49:52 -070089 error("fcntl(%d, F_GETFL): %s", fd, strerror(errno));
Greg Hartmanbd77cf72015-02-25 13:21:06 -080090 return (-1);
91 }
92 if (val & O_NONBLOCK) {
93 debug3("fd %d is O_NONBLOCK", fd);
94 return (0);
95 }
96 debug2("fd %d setting O_NONBLOCK", fd);
97 val |= O_NONBLOCK;
98 if (fcntl(fd, F_SETFL, val) == -1) {
99 debug("fcntl(%d, F_SETFL, O_NONBLOCK): %s", fd,
100 strerror(errno));
101 return (-1);
102 }
103 return (0);
104}
105
106int
107unset_nonblock(int fd)
108{
109 int val;
110
Greg Hartman9768ca42017-06-22 20:49:52 -0700111 val = fcntl(fd, F_GETFL);
Greg Hartmanbd77cf72015-02-25 13:21:06 -0800112 if (val < 0) {
Greg Hartman9768ca42017-06-22 20:49:52 -0700113 error("fcntl(%d, F_GETFL): %s", fd, strerror(errno));
Greg Hartmanbd77cf72015-02-25 13:21:06 -0800114 return (-1);
115 }
116 if (!(val & O_NONBLOCK)) {
117 debug3("fd %d is not O_NONBLOCK", fd);
118 return (0);
119 }
120 debug("fd %d clearing O_NONBLOCK", fd);
121 val &= ~O_NONBLOCK;
122 if (fcntl(fd, F_SETFL, val) == -1) {
123 debug("fcntl(%d, F_SETFL, ~O_NONBLOCK): %s",
124 fd, strerror(errno));
125 return (-1);
126 }
127 return (0);
128}
129
130const char *
131ssh_gai_strerror(int gaierr)
132{
Adam Langleyd0592972015-03-30 14:49:51 -0700133 if (gaierr == EAI_SYSTEM && errno != 0)
Greg Hartmanbd77cf72015-02-25 13:21:06 -0800134 return strerror(errno);
135 return gai_strerror(gaierr);
136}
137
138/* disable nagle on socket */
139void
140set_nodelay(int fd)
141{
142 int opt;
143 socklen_t optlen;
144
145 optlen = sizeof opt;
146 if (getsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &opt, &optlen) == -1) {
147 debug("getsockopt TCP_NODELAY: %.100s", strerror(errno));
148 return;
149 }
150 if (opt == 1) {
151 debug2("fd %d is TCP_NODELAY", fd);
152 return;
153 }
154 opt = 1;
155 debug2("fd %d setting TCP_NODELAY", fd);
156 if (setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &opt, sizeof opt) == -1)
157 error("setsockopt TCP_NODELAY: %.100s", strerror(errno));
158}
159
160/* Characters considered whitespace in strsep calls. */
161#define WHITESPACE " \t\r\n"
162#define QUOTE "\""
163
164/* return next token in configuration line */
165char *
166strdelim(char **s)
167{
168 char *old;
169 int wspace = 0;
170
171 if (*s == NULL)
172 return NULL;
173
174 old = *s;
175
176 *s = strpbrk(*s, WHITESPACE QUOTE "=");
177 if (*s == NULL)
178 return (old);
179
180 if (*s[0] == '\"') {
181 memmove(*s, *s + 1, strlen(*s)); /* move nul too */
182 /* Find matching quote */
183 if ((*s = strpbrk(*s, QUOTE)) == NULL) {
184 return (NULL); /* no matching quote */
185 } else {
186 *s[0] = '\0';
187 *s += strspn(*s + 1, WHITESPACE) + 1;
188 return (old);
189 }
190 }
191
192 /* Allow only one '=' to be skipped */
193 if (*s[0] == '=')
194 wspace = 1;
195 *s[0] = '\0';
196
197 /* Skip any extra whitespace after first token */
198 *s += strspn(*s + 1, WHITESPACE) + 1;
199 if (*s[0] == '=' && !wspace)
200 *s += strspn(*s + 1, WHITESPACE) + 1;
201
202 return (old);
203}
204
205struct passwd *
206pwcopy(struct passwd *pw)
207{
208 struct passwd *copy = xcalloc(1, sizeof(*copy));
209
210 copy->pw_name = xstrdup(pw->pw_name);
Greg Hartman9768ca42017-06-22 20:49:52 -0700211 copy->pw_passwd = xstrdup(pw->pw_passwd);
Adam Langleyd0592972015-03-30 14:49:51 -0700212#ifdef HAVE_STRUCT_PASSWD_PW_GECOS
Greg Hartmanbd77cf72015-02-25 13:21:06 -0800213 copy->pw_gecos = xstrdup(pw->pw_gecos);
214#endif
215 copy->pw_uid = pw->pw_uid;
216 copy->pw_gid = pw->pw_gid;
Adam Langleyd0592972015-03-30 14:49:51 -0700217#ifdef HAVE_STRUCT_PASSWD_PW_EXPIRE
Greg Hartmanbd77cf72015-02-25 13:21:06 -0800218 copy->pw_expire = pw->pw_expire;
219#endif
Adam Langleyd0592972015-03-30 14:49:51 -0700220#ifdef HAVE_STRUCT_PASSWD_PW_CHANGE
Greg Hartmanbd77cf72015-02-25 13:21:06 -0800221 copy->pw_change = pw->pw_change;
222#endif
Adam Langleyd0592972015-03-30 14:49:51 -0700223#ifdef HAVE_STRUCT_PASSWD_PW_CLASS
Greg Hartmanbd77cf72015-02-25 13:21:06 -0800224 copy->pw_class = xstrdup(pw->pw_class);
225#endif
226 copy->pw_dir = xstrdup(pw->pw_dir);
227 copy->pw_shell = xstrdup(pw->pw_shell);
228 return copy;
229}
230
231/*
232 * Convert ASCII string to TCP/IP port number.
233 * Port must be >=0 and <=65535.
234 * Return -1 if invalid.
235 */
236int
237a2port(const char *s)
238{
239 long long port;
240 const char *errstr;
241
242 port = strtonum(s, 0, 65535, &errstr);
243 if (errstr != NULL)
244 return -1;
245 return (int)port;
246}
247
248int
249a2tun(const char *s, int *remote)
250{
251 const char *errstr = NULL;
252 char *sp, *ep;
253 int tun;
254
255 if (remote != NULL) {
256 *remote = SSH_TUNID_ANY;
257 sp = xstrdup(s);
258 if ((ep = strchr(sp, ':')) == NULL) {
Adam Langleyd0592972015-03-30 14:49:51 -0700259 free(sp);
Greg Hartmanbd77cf72015-02-25 13:21:06 -0800260 return (a2tun(s, NULL));
261 }
262 ep[0] = '\0'; ep++;
263 *remote = a2tun(ep, NULL);
264 tun = a2tun(sp, NULL);
Adam Langleyd0592972015-03-30 14:49:51 -0700265 free(sp);
Greg Hartmanbd77cf72015-02-25 13:21:06 -0800266 return (*remote == SSH_TUNID_ERR ? *remote : tun);
267 }
268
269 if (strcasecmp(s, "any") == 0)
270 return (SSH_TUNID_ANY);
271
272 tun = strtonum(s, 0, SSH_TUNID_MAX, &errstr);
273 if (errstr != NULL)
274 return (SSH_TUNID_ERR);
275
276 return (tun);
277}
278
279#define SECONDS 1
280#define MINUTES (SECONDS * 60)
281#define HOURS (MINUTES * 60)
282#define DAYS (HOURS * 24)
283#define WEEKS (DAYS * 7)
284
285/*
286 * Convert a time string into seconds; format is
287 * a sequence of:
288 * time[qualifier]
289 *
290 * Valid time qualifiers are:
291 * <none> seconds
292 * s|S seconds
293 * m|M minutes
294 * h|H hours
295 * d|D days
296 * w|W weeks
297 *
298 * Examples:
299 * 90m 90 minutes
300 * 1h30m 90 minutes
301 * 2d 2 days
302 * 1w 1 week
303 *
304 * Return -1 if time string is invalid.
305 */
306long
307convtime(const char *s)
308{
Greg Hartman9768ca42017-06-22 20:49:52 -0700309 long total, secs, multiplier = 1;
Greg Hartmanbd77cf72015-02-25 13:21:06 -0800310 const char *p;
311 char *endp;
312
313 errno = 0;
314 total = 0;
315 p = s;
316
317 if (p == NULL || *p == '\0')
318 return -1;
319
320 while (*p) {
321 secs = strtol(p, &endp, 10);
322 if (p == endp ||
323 (errno == ERANGE && (secs == LONG_MIN || secs == LONG_MAX)) ||
324 secs < 0)
325 return -1;
326
327 switch (*endp++) {
328 case '\0':
329 endp--;
330 break;
331 case 's':
332 case 'S':
333 break;
334 case 'm':
335 case 'M':
Greg Hartman9768ca42017-06-22 20:49:52 -0700336 multiplier = MINUTES;
Greg Hartmanbd77cf72015-02-25 13:21:06 -0800337 break;
338 case 'h':
339 case 'H':
Greg Hartman9768ca42017-06-22 20:49:52 -0700340 multiplier = HOURS;
Greg Hartmanbd77cf72015-02-25 13:21:06 -0800341 break;
342 case 'd':
343 case 'D':
Greg Hartman9768ca42017-06-22 20:49:52 -0700344 multiplier = DAYS;
Greg Hartmanbd77cf72015-02-25 13:21:06 -0800345 break;
346 case 'w':
347 case 'W':
Greg Hartman9768ca42017-06-22 20:49:52 -0700348 multiplier = WEEKS;
Greg Hartmanbd77cf72015-02-25 13:21:06 -0800349 break;
350 default:
351 return -1;
352 }
Greg Hartman9768ca42017-06-22 20:49:52 -0700353 if (secs >= LONG_MAX / multiplier)
354 return -1;
355 secs *= multiplier;
356 if (total >= LONG_MAX - secs)
357 return -1;
Greg Hartmanbd77cf72015-02-25 13:21:06 -0800358 total += secs;
359 if (total < 0)
360 return -1;
361 p = endp;
362 }
363
364 return total;
365}
366
367/*
368 * Returns a standardized host+port identifier string.
369 * Caller must free returned string.
370 */
371char *
372put_host_port(const char *host, u_short port)
373{
374 char *hoststr;
375
376 if (port == 0 || port == SSH_DEFAULT_PORT)
377 return(xstrdup(host));
378 if (asprintf(&hoststr, "[%s]:%d", host, (int)port) < 0)
379 fatal("put_host_port: asprintf: %s", strerror(errno));
380 debug3("put_host_port: %s", hoststr);
381 return hoststr;
382}
383
384/*
385 * Search for next delimiter between hostnames/addresses and ports.
386 * Argument may be modified (for termination).
387 * Returns *cp if parsing succeeds.
388 * *cp is set to the start of the next delimiter, if one was found.
389 * If this is the last field, *cp is set to NULL.
390 */
391char *
392hpdelim(char **cp)
393{
394 char *s, *old;
395
396 if (cp == NULL || *cp == NULL)
397 return NULL;
398
399 old = s = *cp;
400 if (*s == '[') {
401 if ((s = strchr(s, ']')) == NULL)
402 return NULL;
403 else
404 s++;
405 } else if ((s = strpbrk(s, ":/")) == NULL)
406 s = *cp + strlen(*cp); /* skip to end (see first case below) */
407
408 switch (*s) {
409 case '\0':
410 *cp = NULL; /* no more fields*/
411 break;
412
413 case ':':
414 case '/':
415 *s = '\0'; /* terminate */
416 *cp = s + 1;
417 break;
418
419 default:
420 return NULL;
421 }
422
423 return old;
424}
425
426char *
427cleanhostname(char *host)
428{
429 if (*host == '[' && host[strlen(host) - 1] == ']') {
430 host[strlen(host) - 1] = '\0';
431 return (host + 1);
432 } else
433 return host;
434}
435
436char *
437colon(char *cp)
438{
439 int flag = 0;
440
441 if (*cp == ':') /* Leading colon is part of file name. */
442 return NULL;
443 if (*cp == '[')
444 flag = 1;
445
446 for (; *cp; ++cp) {
447 if (*cp == '@' && *(cp+1) == '[')
448 flag = 1;
449 if (*cp == ']' && *(cp+1) == ':' && flag)
450 return (cp+1);
451 if (*cp == ':' && !flag)
452 return (cp);
453 if (*cp == '/')
454 return NULL;
455 }
456 return NULL;
457}
458
Greg Hartman9768ca42017-06-22 20:49:52 -0700459/*
460 * Parse a [user@]host[:port] string.
461 * Caller must free returned user and host.
462 * Any of the pointer return arguments may be NULL (useful for syntax checking).
463 * If user was not specified then *userp will be set to NULL.
464 * If port was not specified then *portp will be -1.
465 * Returns 0 on success, -1 on failure.
466 */
467int
468parse_user_host_port(const char *s, char **userp, char **hostp, int *portp)
469{
470 char *sdup, *cp, *tmp;
471 char *user = NULL, *host = NULL;
472 int port = -1, ret = -1;
473
474 if (userp != NULL)
475 *userp = NULL;
476 if (hostp != NULL)
477 *hostp = NULL;
478 if (portp != NULL)
479 *portp = -1;
480
481 if ((sdup = tmp = strdup(s)) == NULL)
482 return -1;
483 /* Extract optional username */
484 if ((cp = strchr(tmp, '@')) != NULL) {
485 *cp = '\0';
486 if (*tmp == '\0')
487 goto out;
488 if ((user = strdup(tmp)) == NULL)
489 goto out;
490 tmp = cp + 1;
491 }
492 /* Extract mandatory hostname */
493 if ((cp = hpdelim(&tmp)) == NULL || *cp == '\0')
494 goto out;
495 host = xstrdup(cleanhostname(cp));
496 /* Convert and verify optional port */
497 if (tmp != NULL && *tmp != '\0') {
498 if ((port = a2port(tmp)) <= 0)
499 goto out;
500 }
501 /* Success */
502 if (userp != NULL) {
503 *userp = user;
504 user = NULL;
505 }
506 if (hostp != NULL) {
507 *hostp = host;
508 host = NULL;
509 }
510 if (portp != NULL)
511 *portp = port;
512 ret = 0;
513 out:
514 free(sdup);
515 free(user);
516 free(host);
517 return ret;
518}
519
Greg Hartmanbd77cf72015-02-25 13:21:06 -0800520/* function to assist building execv() arguments */
521void
522addargs(arglist *args, char *fmt, ...)
523{
524 va_list ap;
525 char *cp;
526 u_int nalloc;
527 int r;
528
529 va_start(ap, fmt);
530 r = vasprintf(&cp, fmt, ap);
531 va_end(ap);
532 if (r == -1)
533 fatal("addargs: argument too long");
534
535 nalloc = args->nalloc;
536 if (args->list == NULL) {
537 nalloc = 32;
538 args->num = 0;
539 } else if (args->num+2 >= nalloc)
540 nalloc *= 2;
541
Greg Hartmanccacbc92016-02-03 09:59:44 -0800542 args->list = xreallocarray(args->list, nalloc, sizeof(char *));
Greg Hartmanbd77cf72015-02-25 13:21:06 -0800543 args->nalloc = nalloc;
544 args->list[args->num++] = cp;
545 args->list[args->num] = NULL;
546}
547
548void
549replacearg(arglist *args, u_int which, char *fmt, ...)
550{
551 va_list ap;
552 char *cp;
553 int r;
554
555 va_start(ap, fmt);
556 r = vasprintf(&cp, fmt, ap);
557 va_end(ap);
558 if (r == -1)
559 fatal("replacearg: argument too long");
560
561 if (which >= args->num)
562 fatal("replacearg: tried to replace invalid arg %d >= %d",
563 which, args->num);
Adam Langleyd0592972015-03-30 14:49:51 -0700564 free(args->list[which]);
Greg Hartmanbd77cf72015-02-25 13:21:06 -0800565 args->list[which] = cp;
566}
567
568void
569freeargs(arglist *args)
570{
571 u_int i;
572
573 if (args->list != NULL) {
574 for (i = 0; i < args->num; i++)
Adam Langleyd0592972015-03-30 14:49:51 -0700575 free(args->list[i]);
576 free(args->list);
Greg Hartmanbd77cf72015-02-25 13:21:06 -0800577 args->nalloc = args->num = 0;
578 args->list = NULL;
579 }
580}
581
582/*
583 * Expands tildes in the file name. Returns data allocated by xmalloc.
584 * Warning: this calls getpw*.
585 */
586char *
587tilde_expand_filename(const char *filename, uid_t uid)
588{
Adam Langleyd0592972015-03-30 14:49:51 -0700589 const char *path, *sep;
590 char user[128], *ret;
Greg Hartmanbd77cf72015-02-25 13:21:06 -0800591 struct passwd *pw;
592 u_int len, slash;
593
594 if (*filename != '~')
595 return (xstrdup(filename));
596 filename++;
597
598 path = strchr(filename, '/');
599 if (path != NULL && path > filename) { /* ~user/path */
600 slash = path - filename;
601 if (slash > sizeof(user) - 1)
602 fatal("tilde_expand_filename: ~username too long");
603 memcpy(user, filename, slash);
604 user[slash] = '\0';
605 if ((pw = getpwnam(user)) == NULL)
606 fatal("tilde_expand_filename: No such user %s", user);
607 } else if ((pw = getpwuid(uid)) == NULL) /* ~/path */
608 fatal("tilde_expand_filename: No such uid %ld", (long)uid);
609
Greg Hartmanbd77cf72015-02-25 13:21:06 -0800610 /* Make sure directory has a trailing '/' */
611 len = strlen(pw->pw_dir);
Adam Langleyd0592972015-03-30 14:49:51 -0700612 if (len == 0 || pw->pw_dir[len - 1] != '/')
613 sep = "/";
614 else
615 sep = "";
Greg Hartmanbd77cf72015-02-25 13:21:06 -0800616
617 /* Skip leading '/' from specified path */
618 if (path != NULL)
619 filename = path + 1;
Adam Langleyd0592972015-03-30 14:49:51 -0700620
621 if (xasprintf(&ret, "%s%s%s", pw->pw_dir, sep, filename) >= PATH_MAX)
Greg Hartmanbd77cf72015-02-25 13:21:06 -0800622 fatal("tilde_expand_filename: Path too long");
623
Adam Langleyd0592972015-03-30 14:49:51 -0700624 return (ret);
Greg Hartmanbd77cf72015-02-25 13:21:06 -0800625}
626
627/*
628 * Expand a string with a set of %[char] escapes. A number of escapes may be
629 * specified as (char *escape_chars, char *replacement) pairs. The list must
630 * be terminated by a NULL escape_char. Returns replaced string in memory
631 * allocated by xmalloc.
632 */
633char *
634percent_expand(const char *string, ...)
635{
636#define EXPAND_MAX_KEYS 16
637 u_int num_keys, i, j;
638 struct {
639 const char *key;
640 const char *repl;
641 } keys[EXPAND_MAX_KEYS];
642 char buf[4096];
643 va_list ap;
644
645 /* Gather keys */
646 va_start(ap, string);
647 for (num_keys = 0; num_keys < EXPAND_MAX_KEYS; num_keys++) {
648 keys[num_keys].key = va_arg(ap, char *);
649 if (keys[num_keys].key == NULL)
650 break;
651 keys[num_keys].repl = va_arg(ap, char *);
652 if (keys[num_keys].repl == NULL)
653 fatal("%s: NULL replacement", __func__);
654 }
655 if (num_keys == EXPAND_MAX_KEYS && va_arg(ap, char *) != NULL)
656 fatal("%s: too many keys", __func__);
657 va_end(ap);
658
659 /* Expand string */
660 *buf = '\0';
661 for (i = 0; *string != '\0'; string++) {
662 if (*string != '%') {
663 append:
664 buf[i++] = *string;
665 if (i >= sizeof(buf))
666 fatal("%s: string too long", __func__);
667 buf[i] = '\0';
668 continue;
669 }
670 string++;
671 /* %% case */
672 if (*string == '%')
673 goto append;
Greg Hartman9768ca42017-06-22 20:49:52 -0700674 if (*string == '\0')
675 fatal("%s: invalid format", __func__);
Greg Hartmanbd77cf72015-02-25 13:21:06 -0800676 for (j = 0; j < num_keys; j++) {
677 if (strchr(keys[j].key, *string) != NULL) {
678 i = strlcat(buf, keys[j].repl, sizeof(buf));
679 if (i >= sizeof(buf))
680 fatal("%s: string too long", __func__);
681 break;
682 }
683 }
684 if (j >= num_keys)
685 fatal("%s: unknown key %%%c", __func__, *string);
686 }
687 return (xstrdup(buf));
688#undef EXPAND_MAX_KEYS
689}
690
691/*
692 * Read an entire line from a public key file into a static buffer, discarding
693 * lines that exceed the buffer size. Returns 0 on success, -1 on failure.
694 */
695int
696read_keyfile_line(FILE *f, const char *filename, char *buf, size_t bufsz,
697 u_long *lineno)
698{
699 while (fgets(buf, bufsz, f) != NULL) {
700 if (buf[0] == '\0')
701 continue;
702 (*lineno)++;
703 if (buf[strlen(buf) - 1] == '\n' || feof(f)) {
704 return 0;
705 } else {
706 debug("%s: %s line %lu exceeds size limit", __func__,
707 filename, *lineno);
708 /* discard remainder of line */
709 while (fgetc(f) != '\n' && !feof(f))
710 ; /* nothing */
711 }
712 }
713 return -1;
714}
715
716int
717tun_open(int tun, int mode)
718{
719#if defined(CUSTOM_SYS_TUN_OPEN)
720 return (sys_tun_open(tun, mode));
721#elif defined(SSH_TUN_OPENBSD)
722 struct ifreq ifr;
723 char name[100];
724 int fd = -1, sock;
Greg Hartman9768ca42017-06-22 20:49:52 -0700725 const char *tunbase = "tun";
726
727 if (mode == SSH_TUNMODE_ETHERNET)
728 tunbase = "tap";
Greg Hartmanbd77cf72015-02-25 13:21:06 -0800729
730 /* Open the tunnel device */
731 if (tun <= SSH_TUNID_MAX) {
Greg Hartman9768ca42017-06-22 20:49:52 -0700732 snprintf(name, sizeof(name), "/dev/%s%d", tunbase, tun);
Greg Hartmanbd77cf72015-02-25 13:21:06 -0800733 fd = open(name, O_RDWR);
734 } else if (tun == SSH_TUNID_ANY) {
735 for (tun = 100; tun >= 0; tun--) {
Greg Hartman9768ca42017-06-22 20:49:52 -0700736 snprintf(name, sizeof(name), "/dev/%s%d",
737 tunbase, tun);
Greg Hartmanbd77cf72015-02-25 13:21:06 -0800738 if ((fd = open(name, O_RDWR)) >= 0)
739 break;
740 }
741 } else {
742 debug("%s: invalid tunnel %u", __func__, tun);
Greg Hartman9768ca42017-06-22 20:49:52 -0700743 return -1;
Greg Hartmanbd77cf72015-02-25 13:21:06 -0800744 }
745
746 if (fd < 0) {
Greg Hartman9768ca42017-06-22 20:49:52 -0700747 debug("%s: %s open: %s", __func__, name, strerror(errno));
748 return -1;
Greg Hartmanbd77cf72015-02-25 13:21:06 -0800749 }
750
751 debug("%s: %s mode %d fd %d", __func__, name, mode, fd);
752
Greg Hartman9768ca42017-06-22 20:49:52 -0700753 /* Bring interface up if it is not already */
754 snprintf(ifr.ifr_name, sizeof(ifr.ifr_name), "%s%d", tunbase, tun);
Greg Hartmanbd77cf72015-02-25 13:21:06 -0800755 if ((sock = socket(PF_UNIX, SOCK_STREAM, 0)) == -1)
756 goto failed;
757
Greg Hartman9768ca42017-06-22 20:49:52 -0700758 if (ioctl(sock, SIOCGIFFLAGS, &ifr) == -1) {
759 debug("%s: get interface %s flags: %s", __func__,
760 ifr.ifr_name, strerror(errno));
Greg Hartmanbd77cf72015-02-25 13:21:06 -0800761 goto failed;
Greg Hartman9768ca42017-06-22 20:49:52 -0700762 }
Greg Hartmanbd77cf72015-02-25 13:21:06 -0800763
Greg Hartman9768ca42017-06-22 20:49:52 -0700764 if (!(ifr.ifr_flags & IFF_UP)) {
765 ifr.ifr_flags |= IFF_UP;
766 if (ioctl(sock, SIOCSIFFLAGS, &ifr) == -1) {
767 debug("%s: activate interface %s: %s", __func__,
768 ifr.ifr_name, strerror(errno));
769 goto failed;
770 }
771 }
Greg Hartmanbd77cf72015-02-25 13:21:06 -0800772
773 close(sock);
Greg Hartman9768ca42017-06-22 20:49:52 -0700774 return fd;
Greg Hartmanbd77cf72015-02-25 13:21:06 -0800775
776 failed:
777 if (fd >= 0)
778 close(fd);
779 if (sock >= 0)
780 close(sock);
Greg Hartman9768ca42017-06-22 20:49:52 -0700781 return -1;
Greg Hartmanbd77cf72015-02-25 13:21:06 -0800782#else
783 error("Tunnel interfaces are not supported on this platform");
784 return (-1);
785#endif
786}
787
788void
789sanitise_stdfd(void)
790{
791 int nullfd, dupfd;
792
793 if ((nullfd = dupfd = open(_PATH_DEVNULL, O_RDWR)) == -1) {
794 fprintf(stderr, "Couldn't open /dev/null: %s\n",
795 strerror(errno));
796 exit(1);
797 }
Greg Hartman9768ca42017-06-22 20:49:52 -0700798 while (++dupfd <= STDERR_FILENO) {
799 /* Only populate closed fds. */
800 if (fcntl(dupfd, F_GETFL) == -1 && errno == EBADF) {
801 if (dup2(nullfd, dupfd) == -1) {
802 fprintf(stderr, "dup2: %s\n", strerror(errno));
803 exit(1);
804 }
Greg Hartmanbd77cf72015-02-25 13:21:06 -0800805 }
806 }
Greg Hartman9768ca42017-06-22 20:49:52 -0700807 if (nullfd > STDERR_FILENO)
Greg Hartmanbd77cf72015-02-25 13:21:06 -0800808 close(nullfd);
809}
810
811char *
812tohex(const void *vp, size_t l)
813{
814 const u_char *p = (const u_char *)vp;
815 char b[3], *r;
816 size_t i, hl;
817
818 if (l > 65536)
819 return xstrdup("tohex: length > 65536");
820
821 hl = l * 2 + 1;
822 r = xcalloc(1, hl);
823 for (i = 0; i < l; i++) {
824 snprintf(b, sizeof(b), "%02x", p[i]);
825 strlcat(r, b, hl);
826 }
827 return (r);
828}
829
830u_int64_t
831get_u64(const void *vp)
832{
833 const u_char *p = (const u_char *)vp;
834 u_int64_t v;
835
836 v = (u_int64_t)p[0] << 56;
837 v |= (u_int64_t)p[1] << 48;
838 v |= (u_int64_t)p[2] << 40;
839 v |= (u_int64_t)p[3] << 32;
840 v |= (u_int64_t)p[4] << 24;
841 v |= (u_int64_t)p[5] << 16;
842 v |= (u_int64_t)p[6] << 8;
843 v |= (u_int64_t)p[7];
844
845 return (v);
846}
847
848u_int32_t
849get_u32(const void *vp)
850{
851 const u_char *p = (const u_char *)vp;
852 u_int32_t v;
853
854 v = (u_int32_t)p[0] << 24;
855 v |= (u_int32_t)p[1] << 16;
856 v |= (u_int32_t)p[2] << 8;
857 v |= (u_int32_t)p[3];
858
859 return (v);
860}
861
Adam Langleyd0592972015-03-30 14:49:51 -0700862u_int32_t
863get_u32_le(const void *vp)
864{
865 const u_char *p = (const u_char *)vp;
866 u_int32_t v;
867
868 v = (u_int32_t)p[0];
869 v |= (u_int32_t)p[1] << 8;
870 v |= (u_int32_t)p[2] << 16;
871 v |= (u_int32_t)p[3] << 24;
872
873 return (v);
874}
875
Greg Hartmanbd77cf72015-02-25 13:21:06 -0800876u_int16_t
877get_u16(const void *vp)
878{
879 const u_char *p = (const u_char *)vp;
880 u_int16_t v;
881
882 v = (u_int16_t)p[0] << 8;
883 v |= (u_int16_t)p[1];
884
885 return (v);
886}
887
888void
889put_u64(void *vp, u_int64_t v)
890{
891 u_char *p = (u_char *)vp;
892
893 p[0] = (u_char)(v >> 56) & 0xff;
894 p[1] = (u_char)(v >> 48) & 0xff;
895 p[2] = (u_char)(v >> 40) & 0xff;
896 p[3] = (u_char)(v >> 32) & 0xff;
897 p[4] = (u_char)(v >> 24) & 0xff;
898 p[5] = (u_char)(v >> 16) & 0xff;
899 p[6] = (u_char)(v >> 8) & 0xff;
900 p[7] = (u_char)v & 0xff;
901}
902
903void
904put_u32(void *vp, u_int32_t v)
905{
906 u_char *p = (u_char *)vp;
907
908 p[0] = (u_char)(v >> 24) & 0xff;
909 p[1] = (u_char)(v >> 16) & 0xff;
910 p[2] = (u_char)(v >> 8) & 0xff;
911 p[3] = (u_char)v & 0xff;
912}
913
Adam Langleyd0592972015-03-30 14:49:51 -0700914void
915put_u32_le(void *vp, u_int32_t v)
916{
917 u_char *p = (u_char *)vp;
918
919 p[0] = (u_char)v & 0xff;
920 p[1] = (u_char)(v >> 8) & 0xff;
921 p[2] = (u_char)(v >> 16) & 0xff;
922 p[3] = (u_char)(v >> 24) & 0xff;
923}
Greg Hartmanbd77cf72015-02-25 13:21:06 -0800924
925void
926put_u16(void *vp, u_int16_t v)
927{
928 u_char *p = (u_char *)vp;
929
930 p[0] = (u_char)(v >> 8) & 0xff;
931 p[1] = (u_char)v & 0xff;
932}
933
934void
935ms_subtract_diff(struct timeval *start, int *ms)
936{
937 struct timeval diff, finish;
938
939 gettimeofday(&finish, NULL);
940 timersub(&finish, start, &diff);
941 *ms -= (diff.tv_sec * 1000) + (diff.tv_usec / 1000);
942}
943
944void
945ms_to_timeval(struct timeval *tv, int ms)
946{
947 if (ms < 0)
948 ms = 0;
949 tv->tv_sec = ms / 1000;
950 tv->tv_usec = (ms % 1000) * 1000;
951}
952
Adam Langleyd0592972015-03-30 14:49:51 -0700953time_t
954monotime(void)
955{
956#if defined(HAVE_CLOCK_GETTIME) && \
957 (defined(CLOCK_MONOTONIC) || defined(CLOCK_BOOTTIME))
958 struct timespec ts;
959 static int gettime_failed = 0;
960
961 if (!gettime_failed) {
962#if defined(CLOCK_BOOTTIME)
963 if (clock_gettime(CLOCK_BOOTTIME, &ts) == 0)
964 return (ts.tv_sec);
965#endif
966#if defined(CLOCK_MONOTONIC)
967 if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0)
968 return (ts.tv_sec);
969#endif
970 debug3("clock_gettime: %s", strerror(errno));
971 gettime_failed = 1;
972 }
973#endif /* HAVE_CLOCK_GETTIME && (CLOCK_MONOTONIC || CLOCK_BOOTTIME */
974
975 return time(NULL);
976}
977
Greg Hartman9768ca42017-06-22 20:49:52 -0700978double
979monotime_double(void)
980{
981#if defined(HAVE_CLOCK_GETTIME) && \
982 (defined(CLOCK_MONOTONIC) || defined(CLOCK_BOOTTIME))
983 struct timespec ts;
984 static int gettime_failed = 0;
985
986 if (!gettime_failed) {
987#if defined(CLOCK_BOOTTIME)
988 if (clock_gettime(CLOCK_BOOTTIME, &ts) == 0)
989 return (ts.tv_sec + (double)ts.tv_nsec / 1000000000);
990#endif
991#if defined(CLOCK_MONOTONIC)
992 if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0)
993 return (ts.tv_sec + (double)ts.tv_nsec / 1000000000);
994#endif
995 debug3("clock_gettime: %s", strerror(errno));
996 gettime_failed = 1;
997 }
998#endif /* HAVE_CLOCK_GETTIME && (CLOCK_MONOTONIC || CLOCK_BOOTTIME */
999
1000 return (double)time(NULL);
1001}
1002
Greg Hartmanbd77cf72015-02-25 13:21:06 -08001003void
1004bandwidth_limit_init(struct bwlimit *bw, u_int64_t kbps, size_t buflen)
1005{
1006 bw->buflen = buflen;
1007 bw->rate = kbps;
1008 bw->thresh = bw->rate;
1009 bw->lamt = 0;
1010 timerclear(&bw->bwstart);
1011 timerclear(&bw->bwend);
1012}
1013
1014/* Callback from read/write loop to insert bandwidth-limiting delays */
1015void
1016bandwidth_limit(struct bwlimit *bw, size_t read_len)
1017{
1018 u_int64_t waitlen;
1019 struct timespec ts, rm;
1020
1021 if (!timerisset(&bw->bwstart)) {
1022 gettimeofday(&bw->bwstart, NULL);
1023 return;
1024 }
1025
1026 bw->lamt += read_len;
1027 if (bw->lamt < bw->thresh)
1028 return;
1029
1030 gettimeofday(&bw->bwend, NULL);
1031 timersub(&bw->bwend, &bw->bwstart, &bw->bwend);
1032 if (!timerisset(&bw->bwend))
1033 return;
1034
1035 bw->lamt *= 8;
1036 waitlen = (double)1000000L * bw->lamt / bw->rate;
1037
1038 bw->bwstart.tv_sec = waitlen / 1000000L;
1039 bw->bwstart.tv_usec = waitlen % 1000000L;
1040
1041 if (timercmp(&bw->bwstart, &bw->bwend, >)) {
1042 timersub(&bw->bwstart, &bw->bwend, &bw->bwend);
1043
1044 /* Adjust the wait time */
1045 if (bw->bwend.tv_sec) {
1046 bw->thresh /= 2;
1047 if (bw->thresh < bw->buflen / 4)
1048 bw->thresh = bw->buflen / 4;
1049 } else if (bw->bwend.tv_usec < 10000) {
1050 bw->thresh *= 2;
1051 if (bw->thresh > bw->buflen * 8)
1052 bw->thresh = bw->buflen * 8;
1053 }
1054
1055 TIMEVAL_TO_TIMESPEC(&bw->bwend, &ts);
1056 while (nanosleep(&ts, &rm) == -1) {
1057 if (errno != EINTR)
1058 break;
1059 ts = rm;
1060 }
1061 }
1062
1063 bw->lamt = 0;
1064 gettimeofday(&bw->bwstart, NULL);
1065}
1066
1067/* Make a template filename for mk[sd]temp() */
1068void
1069mktemp_proto(char *s, size_t len)
1070{
1071 const char *tmpdir;
1072 int r;
1073
1074 if ((tmpdir = getenv("TMPDIR")) != NULL) {
1075 r = snprintf(s, len, "%s/ssh-XXXXXXXXXXXX", tmpdir);
1076 if (r > 0 && (size_t)r < len)
1077 return;
1078 }
1079 r = snprintf(s, len, "/tmp/ssh-XXXXXXXXXXXX");
1080 if (r < 0 || (size_t)r >= len)
1081 fatal("%s: template string too short", __func__);
1082}
1083
1084static const struct {
1085 const char *name;
1086 int value;
1087} ipqos[] = {
1088 { "af11", IPTOS_DSCP_AF11 },
1089 { "af12", IPTOS_DSCP_AF12 },
1090 { "af13", IPTOS_DSCP_AF13 },
Adam Langleyd0592972015-03-30 14:49:51 -07001091 { "af21", IPTOS_DSCP_AF21 },
Greg Hartmanbd77cf72015-02-25 13:21:06 -08001092 { "af22", IPTOS_DSCP_AF22 },
1093 { "af23", IPTOS_DSCP_AF23 },
1094 { "af31", IPTOS_DSCP_AF31 },
1095 { "af32", IPTOS_DSCP_AF32 },
1096 { "af33", IPTOS_DSCP_AF33 },
1097 { "af41", IPTOS_DSCP_AF41 },
1098 { "af42", IPTOS_DSCP_AF42 },
1099 { "af43", IPTOS_DSCP_AF43 },
1100 { "cs0", IPTOS_DSCP_CS0 },
1101 { "cs1", IPTOS_DSCP_CS1 },
1102 { "cs2", IPTOS_DSCP_CS2 },
1103 { "cs3", IPTOS_DSCP_CS3 },
1104 { "cs4", IPTOS_DSCP_CS4 },
1105 { "cs5", IPTOS_DSCP_CS5 },
1106 { "cs6", IPTOS_DSCP_CS6 },
1107 { "cs7", IPTOS_DSCP_CS7 },
1108 { "ef", IPTOS_DSCP_EF },
1109 { "lowdelay", IPTOS_LOWDELAY },
1110 { "throughput", IPTOS_THROUGHPUT },
1111 { "reliability", IPTOS_RELIABILITY },
1112 { NULL, -1 }
1113};
1114
1115int
1116parse_ipqos(const char *cp)
1117{
1118 u_int i;
1119 char *ep;
1120 long val;
1121
1122 if (cp == NULL)
1123 return -1;
1124 for (i = 0; ipqos[i].name != NULL; i++) {
1125 if (strcasecmp(cp, ipqos[i].name) == 0)
1126 return ipqos[i].value;
1127 }
1128 /* Try parsing as an integer */
1129 val = strtol(cp, &ep, 0);
1130 if (*cp == '\0' || *ep != '\0' || val < 0 || val > 255)
1131 return -1;
1132 return val;
1133}
1134
1135const char *
1136iptos2str(int iptos)
1137{
1138 int i;
1139 static char iptos_str[sizeof "0xff"];
1140
1141 for (i = 0; ipqos[i].name != NULL; i++) {
1142 if (ipqos[i].value == iptos)
1143 return ipqos[i].name;
1144 }
1145 snprintf(iptos_str, sizeof iptos_str, "0x%02x", iptos);
1146 return iptos_str;
1147}
Adam Langleyd0592972015-03-30 14:49:51 -07001148
1149void
1150lowercase(char *s)
1151{
1152 for (; *s; s++)
1153 *s = tolower((u_char)*s);
1154}
1155
1156int
1157unix_listener(const char *path, int backlog, int unlink_first)
1158{
1159 struct sockaddr_un sunaddr;
1160 int saved_errno, sock;
1161
1162 memset(&sunaddr, 0, sizeof(sunaddr));
1163 sunaddr.sun_family = AF_UNIX;
1164 if (strlcpy(sunaddr.sun_path, path, sizeof(sunaddr.sun_path)) >= sizeof(sunaddr.sun_path)) {
1165 error("%s: \"%s\" too long for Unix domain socket", __func__,
1166 path);
1167 errno = ENAMETOOLONG;
1168 return -1;
1169 }
1170
1171 sock = socket(PF_UNIX, SOCK_STREAM, 0);
1172 if (sock < 0) {
1173 saved_errno = errno;
1174 error("socket: %.100s", strerror(errno));
1175 errno = saved_errno;
1176 return -1;
1177 }
1178 if (unlink_first == 1) {
1179 if (unlink(path) != 0 && errno != ENOENT)
1180 error("unlink(%s): %.100s", path, strerror(errno));
1181 }
1182 if (bind(sock, (struct sockaddr *)&sunaddr, sizeof(sunaddr)) < 0) {
1183 saved_errno = errno;
1184 error("bind: %.100s", strerror(errno));
1185 close(sock);
1186 error("%s: cannot bind to path: %s", __func__, path);
1187 errno = saved_errno;
1188 return -1;
1189 }
1190 if (listen(sock, backlog) < 0) {
1191 saved_errno = errno;
1192 error("listen: %.100s", strerror(errno));
1193 close(sock);
1194 unlink(path);
1195 error("%s: cannot listen on path: %s", __func__, path);
1196 errno = saved_errno;
1197 return -1;
1198 }
1199 return sock;
1200}
1201
Greg Hartmanbd77cf72015-02-25 13:21:06 -08001202void
1203sock_set_v6only(int s)
1204{
Greg Hartman9768ca42017-06-22 20:49:52 -07001205#if defined(IPV6_V6ONLY) && !defined(__OpenBSD__)
Greg Hartmanbd77cf72015-02-25 13:21:06 -08001206 int on = 1;
1207
1208 debug3("%s: set socket %d IPV6_V6ONLY", __func__, s);
1209 if (setsockopt(s, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof(on)) == -1)
1210 error("setsockopt IPV6_V6ONLY: %s", strerror(errno));
1211#endif
1212}
Greg Hartman9768ca42017-06-22 20:49:52 -07001213
1214/*
1215 * Compares two strings that maybe be NULL. Returns non-zero if strings
1216 * are both NULL or are identical, returns zero otherwise.
1217 */
1218static int
1219strcmp_maybe_null(const char *a, const char *b)
1220{
1221 if ((a == NULL && b != NULL) || (a != NULL && b == NULL))
1222 return 0;
1223 if (a != NULL && strcmp(a, b) != 0)
1224 return 0;
1225 return 1;
1226}
1227
1228/*
1229 * Compare two forwards, returning non-zero if they are identical or
1230 * zero otherwise.
1231 */
1232int
1233forward_equals(const struct Forward *a, const struct Forward *b)
1234{
1235 if (strcmp_maybe_null(a->listen_host, b->listen_host) == 0)
1236 return 0;
1237 if (a->listen_port != b->listen_port)
1238 return 0;
1239 if (strcmp_maybe_null(a->listen_path, b->listen_path) == 0)
1240 return 0;
1241 if (strcmp_maybe_null(a->connect_host, b->connect_host) == 0)
1242 return 0;
1243 if (a->connect_port != b->connect_port)
1244 return 0;
1245 if (strcmp_maybe_null(a->connect_path, b->connect_path) == 0)
1246 return 0;
1247 /* allocated_port and handle are not checked */
1248 return 1;
1249}
1250
1251/* returns 1 if bind to specified port by specified user is permitted */
1252int
1253bind_permitted(int port, uid_t uid)
1254{
1255 if (port < IPPORT_RESERVED && uid != 0)
1256 return 0;
1257 return 1;
1258}
1259
1260/* returns 1 if process is already daemonized, 0 otherwise */
1261int
1262daemonized(void)
1263{
1264 int fd;
1265
1266 if ((fd = open(_PATH_TTY, O_RDONLY | O_NOCTTY)) >= 0) {
1267 close(fd);
1268 return 0; /* have controlling terminal */
1269 }
1270 if (getppid() != 1)
1271 return 0; /* parent is not init */
1272 if (getsid(0) != getpid())
1273 return 0; /* not session leader */
1274 debug3("already daemonized");
1275 return 1;
1276}