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