blob: 009e02bc55c11d500c22f78066ee46748f574d57 [file] [log] [blame]
dtucker@openbsd.orgd05ea252019-01-23 21:50:56 +00001/* $OpenBSD: misc.c,v 1.137 2019/01/23 21:50:56 dtucker Exp $ */
Damien Millere4340be2000-09-16 13:29:08 +11002/*
3 * Copyright (c) 2000 Markus Friedl. All rights reserved.
Damien Miller3f941882006-03-31 23:13:02 +11004 * Copyright (c) 2005,2006 Damien Miller. All rights reserved.
Damien Millere4340be2000-09-16 13:29:08 +11005 *
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
Damien Miller61c51502000-08-18 14:01:04 +100027#include "includes.h"
Damien Miller17e91c02006-03-15 11:28:34 +110028
Damien Miller9f2abc42006-07-10 20:53:08 +100029#include <sys/types.h>
Damien Millerd7834352006-08-05 12:39:39 +100030#include <sys/ioctl.h>
Damien Miller8ec8c3e2006-07-10 20:35:38 +100031#include <sys/socket.h>
djm@openbsd.orgde4ae072017-08-18 05:36:45 +000032#include <sys/stat.h>
dtucker@openbsd.org65a3c0d2016-01-20 09:22:39 +000033#include <sys/time.h>
djm@openbsd.orgde4ae072017-08-18 05:36:45 +000034#include <sys/wait.h>
Damien Miller7acefbb2014-07-18 14:11:24 +100035#include <sys/un.h>
Damien Miller8ec8c3e2006-07-10 20:35:38 +100036
deraadt@openbsd.org2ae4f332015-01-16 06:40:12 +000037#include <limits.h>
djm@openbsd.orgde4ae072017-08-18 05:36:45 +000038#ifdef HAVE_LIBGEN_H
39# include <libgen.h>
40#endif
djm@openbsd.org0a843d92018-12-27 03:25:24 +000041#include <poll.h>
djm@openbsd.orgde4ae072017-08-18 05:36:45 +000042#include <signal.h>
Darren Tucker5d196262006-07-12 22:15:16 +100043#include <stdarg.h>
Damien Millera7a73ee2006-08-05 11:37:59 +100044#include <stdio.h>
Damien Millere7a1e5c2006-08-05 11:34:19 +100045#include <stdlib.h>
Damien Millere3476ed2006-07-24 14:13:33 +100046#include <string.h>
Damien Miller1708cb72011-01-13 12:21:34 +110047#include <time.h>
Damien Millere6b3b612006-07-24 14:01:23 +100048#include <unistd.h>
Darren Tucker5d196262006-07-12 22:15:16 +100049
Damien Miller8ec8c3e2006-07-10 20:35:38 +100050#include <netinet/in.h>
Damien Miller0dac6fb2010-11-20 15:19:38 +110051#include <netinet/in_systm.h>
52#include <netinet/ip.h>
Damien Miller3a4051e2006-03-15 11:19:42 +110053#include <netinet/tcp.h>
naddy@openbsd.org25813332018-10-05 14:26:09 +000054#include <arpa/inet.h>
Damien Miller8ec8c3e2006-07-10 20:35:38 +100055
Damien Millere9fc72e2013-10-15 12:14:12 +110056#include <ctype.h>
Darren Tucker39972492006-07-12 22:22:46 +100057#include <errno.h>
Damien Miller57cf6382006-07-10 21:13:46 +100058#include <fcntl.h>
Darren Tucker4abde772007-12-29 02:43:51 +110059#include <netdb.h>
Damien Miller03e20032006-03-15 11:16:59 +110060#ifdef HAVE_PATHS_H
Damien Millera9263d02006-03-15 11:18:26 +110061# include <paths.h>
Damien Miller9f2abc42006-07-10 20:53:08 +100062#include <pwd.h>
Damien Miller03e20032006-03-15 11:16:59 +110063#endif
Damien Miller3beb8522006-01-02 23:40:10 +110064#ifdef SSH_TUN_OPENBSD
65#include <net/if.h>
66#endif
Damien Miller61c51502000-08-18 14:01:04 +100067
Damien Millerd7834352006-08-05 12:39:39 +100068#include "xmalloc.h"
Kevin Stevesb6e773a2001-02-04 13:20:36 +000069#include "misc.h"
Ben Lindstrom226cfa02001-01-22 05:34:40 +000070#include "log.h"
Darren Tuckerda345532006-07-10 23:04:19 +100071#include "ssh.h"
djm@openbsd.orgde4ae072017-08-18 05:36:45 +000072#include "sshbuf.h"
73#include "ssherr.h"
Damien Miller07949bf2017-08-23 20:13:18 +100074#include "platform.h"
Damien Miller61c51502000-08-18 14:01:04 +100075
Ben Lindstrom4cc240d2001-07-04 04:46:56 +000076/* remove newline at end of string */
Damien Miller61c51502000-08-18 14:01:04 +100077char *
78chop(char *s)
79{
80 char *t = s;
81 while (*t) {
Ben Lindstrom1c37c6a2001-12-06 18:00:18 +000082 if (*t == '\n' || *t == '\r') {
Damien Miller61c51502000-08-18 14:01:04 +100083 *t = '\0';
84 return s;
85 }
86 t++;
87 }
88 return s;
89
90}
91
Ben Lindstrom4cc240d2001-07-04 04:46:56 +000092/* set/unset filedescriptor to non-blocking */
Damien Miller232711f2004-06-15 10:35:30 +100093int
Damien Miller61c51502000-08-18 14:01:04 +100094set_nonblock(int fd)
95{
96 int val;
Ben Lindstromc93e84c2001-05-12 00:08:37 +000097
krw@openbsd.org574def02016-04-02 14:37:42 +000098 val = fcntl(fd, F_GETFL);
Damien Miller61c51502000-08-18 14:01:04 +100099 if (val < 0) {
krw@openbsd.org574def02016-04-02 14:37:42 +0000100 error("fcntl(%d, F_GETFL): %s", fd, strerror(errno));
Damien Miller232711f2004-06-15 10:35:30 +1000101 return (-1);
Damien Miller61c51502000-08-18 14:01:04 +1000102 }
Damien Miller69b69aa2000-10-28 14:19:58 +1100103 if (val & O_NONBLOCK) {
Damien Miller232711f2004-06-15 10:35:30 +1000104 debug3("fd %d is O_NONBLOCK", fd);
105 return (0);
Damien Miller69b69aa2000-10-28 14:19:58 +1100106 }
Damien Milleref095ce2003-05-14 13:41:39 +1000107 debug2("fd %d setting O_NONBLOCK", fd);
Damien Miller61c51502000-08-18 14:01:04 +1000108 val |= O_NONBLOCK;
Damien Miller232711f2004-06-15 10:35:30 +1000109 if (fcntl(fd, F_SETFL, val) == -1) {
110 debug("fcntl(%d, F_SETFL, O_NONBLOCK): %s", fd,
111 strerror(errno));
112 return (-1);
113 }
114 return (0);
Damien Miller61c51502000-08-18 14:01:04 +1000115}
116
Damien Miller232711f2004-06-15 10:35:30 +1000117int
Ben Lindstromc93e84c2001-05-12 00:08:37 +0000118unset_nonblock(int fd)
119{
120 int val;
121
krw@openbsd.org574def02016-04-02 14:37:42 +0000122 val = fcntl(fd, F_GETFL);
Ben Lindstromc93e84c2001-05-12 00:08:37 +0000123 if (val < 0) {
krw@openbsd.org574def02016-04-02 14:37:42 +0000124 error("fcntl(%d, F_GETFL): %s", fd, strerror(errno));
Damien Miller232711f2004-06-15 10:35:30 +1000125 return (-1);
Ben Lindstromc93e84c2001-05-12 00:08:37 +0000126 }
127 if (!(val & O_NONBLOCK)) {
Damien Miller232711f2004-06-15 10:35:30 +1000128 debug3("fd %d is not O_NONBLOCK", fd);
129 return (0);
Ben Lindstromc93e84c2001-05-12 00:08:37 +0000130 }
Ben Lindstrom352b1c22001-06-21 03:04:37 +0000131 debug("fd %d clearing O_NONBLOCK", fd);
Ben Lindstromc93e84c2001-05-12 00:08:37 +0000132 val &= ~O_NONBLOCK;
Damien Miller232711f2004-06-15 10:35:30 +1000133 if (fcntl(fd, F_SETFL, val) == -1) {
134 debug("fcntl(%d, F_SETFL, ~O_NONBLOCK): %s",
Ben Lindstrom84fcb312002-03-05 01:48:09 +0000135 fd, strerror(errno));
Damien Miller232711f2004-06-15 10:35:30 +1000136 return (-1);
137 }
138 return (0);
Ben Lindstromc93e84c2001-05-12 00:08:37 +0000139}
140
Darren Tucker4abde772007-12-29 02:43:51 +1100141const char *
142ssh_gai_strerror(int gaierr)
143{
Damien Miller7313fc92013-07-18 16:13:19 +1000144 if (gaierr == EAI_SYSTEM && errno != 0)
Darren Tucker912428c2008-01-01 20:33:35 +1100145 return strerror(errno);
146 return gai_strerror(gaierr);
Darren Tucker4abde772007-12-29 02:43:51 +1100147}
148
Damien Miller398e1cf2002-02-05 11:52:13 +1100149/* disable nagle on socket */
150void
151set_nodelay(int fd)
152{
Ben Lindstrome86de512002-03-05 01:28:14 +0000153 int opt;
154 socklen_t optlen;
Damien Miller398e1cf2002-02-05 11:52:13 +1100155
Ben Lindstrom1ebd7a52002-02-26 18:12:51 +0000156 optlen = sizeof opt;
157 if (getsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &opt, &optlen) == -1) {
Darren Tucker6db8f932003-11-03 20:07:14 +1100158 debug("getsockopt TCP_NODELAY: %.100s", strerror(errno));
Ben Lindstrom1ebd7a52002-02-26 18:12:51 +0000159 return;
160 }
161 if (opt == 1) {
162 debug2("fd %d is TCP_NODELAY", fd);
163 return;
164 }
165 opt = 1;
Ben Lindstrom1d568f92002-12-23 02:44:36 +0000166 debug2("fd %d setting TCP_NODELAY", fd);
Ben Lindstrom1ebd7a52002-02-26 18:12:51 +0000167 if (setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &opt, sizeof opt) == -1)
Damien Miller398e1cf2002-02-05 11:52:13 +1100168 error("setsockopt TCP_NODELAY: %.100s", strerror(errno));
169}
170
djm@openbsd.orgacf559e2017-10-25 00:15:35 +0000171/* Allow local port reuse in TIME_WAIT */
172int
173set_reuseaddr(int fd)
174{
175 int on = 1;
176
177 if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)) == -1) {
178 error("setsockopt SO_REUSEADDR fd %d: %s", fd, strerror(errno));
179 return -1;
180 }
181 return 0;
182}
183
djm@openbsd.org35eb33f2017-10-25 00:17:08 +0000184/* Get/set routing domain */
185char *
186get_rdomain(int fd)
187{
Damien Miller43c29bb2017-10-25 13:10:59 +1100188#if defined(HAVE_SYS_GET_RDOMAIN)
189 return sys_get_rdomain(fd);
190#elif defined(__OpenBSD__)
djm@openbsd.org35eb33f2017-10-25 00:17:08 +0000191 int rtable;
192 char *ret;
193 socklen_t len = sizeof(rtable);
194
195 if (getsockopt(fd, SOL_SOCKET, SO_RTABLE, &rtable, &len) == -1) {
196 error("Failed to get routing domain for fd %d: %s",
197 fd, strerror(errno));
198 return NULL;
199 }
200 xasprintf(&ret, "%d", rtable);
201 return ret;
Damien Miller43c29bb2017-10-25 13:10:59 +1100202#else /* defined(__OpenBSD__) */
203 return NULL;
204#endif
djm@openbsd.org35eb33f2017-10-25 00:17:08 +0000205}
206
djm@openbsd.orgacf559e2017-10-25 00:15:35 +0000207int
208set_rdomain(int fd, const char *name)
209{
Damien Miller43c29bb2017-10-25 13:10:59 +1100210#if defined(HAVE_SYS_SET_RDOMAIN)
211 return sys_set_rdomain(fd, name);
212#elif defined(__OpenBSD__)
djm@openbsd.orgacf559e2017-10-25 00:15:35 +0000213 int rtable;
214 const char *errstr;
215
216 if (name == NULL)
217 return 0; /* default table */
218
219 rtable = (int)strtonum(name, 0, 255, &errstr);
220 if (errstr != NULL) {
221 /* Shouldn't happen */
222 error("Invalid routing domain \"%s\": %s", name, errstr);
223 return -1;
224 }
225 if (setsockopt(fd, SOL_SOCKET, SO_RTABLE,
226 &rtable, sizeof(rtable)) == -1) {
227 error("Failed to set routing domain %d on fd %d: %s",
228 rtable, fd, strerror(errno));
229 return -1;
230 }
231 return 0;
Damien Miller43c29bb2017-10-25 13:10:59 +1100232#else /* defined(__OpenBSD__) */
233 error("Setting routing domain is not supported on this platform");
234 return -1;
235#endif
djm@openbsd.orgacf559e2017-10-25 00:15:35 +0000236}
237
djm@openbsd.org0a843d92018-12-27 03:25:24 +0000238/*
239 * Wait up to *timeoutp milliseconds for fd to be readable. Updates
240 * *timeoutp with time remaining.
241 * Returns 0 if fd ready or -1 on timeout or error (see errno).
242 */
243int
244waitrfd(int fd, int *timeoutp)
245{
246 struct pollfd pfd;
247 struct timeval t_start;
248 int oerrno, r;
249
250 monotime_tv(&t_start);
251 pfd.fd = fd;
252 pfd.events = POLLIN;
253 for (; *timeoutp >= 0;) {
254 r = poll(&pfd, 1, *timeoutp);
255 oerrno = errno;
256 ms_subtract_diff(&t_start, timeoutp);
257 errno = oerrno;
258 if (r > 0)
259 return 0;
260 else if (r == -1 && errno != EAGAIN)
261 return -1;
262 else if (r == 0)
263 break;
264 }
265 /* timeout */
266 errno = ETIMEDOUT;
267 return -1;
268}
269
270/*
271 * Attempt a non-blocking connect(2) to the specified address, waiting up to
272 * *timeoutp milliseconds for the connection to complete. If the timeout is
273 * <=0, then wait indefinitely.
274 *
275 * Returns 0 on success or -1 on failure.
276 */
277int
278timeout_connect(int sockfd, const struct sockaddr *serv_addr,
279 socklen_t addrlen, int *timeoutp)
280{
281 int optval = 0;
282 socklen_t optlen = sizeof(optval);
283
284 /* No timeout: just do a blocking connect() */
285 if (timeoutp == NULL || *timeoutp <= 0)
286 return connect(sockfd, serv_addr, addrlen);
287
288 set_nonblock(sockfd);
289 if (connect(sockfd, serv_addr, addrlen) == 0) {
290 /* Succeeded already? */
291 unset_nonblock(sockfd);
292 return 0;
293 } else if (errno != EINPROGRESS)
294 return -1;
295
296 if (waitrfd(sockfd, timeoutp) == -1)
297 return -1;
298
299 /* Completed or failed */
300 if (getsockopt(sockfd, SOL_SOCKET, SO_ERROR, &optval, &optlen) == -1) {
301 debug("getsockopt: %s", strerror(errno));
302 return -1;
303 }
304 if (optval != 0) {
305 errno = optval;
306 return -1;
307 }
308 unset_nonblock(sockfd);
309 return 0;
310}
311
Damien Miller61c51502000-08-18 14:01:04 +1000312/* Characters considered whitespace in strsep calls. */
313#define WHITESPACE " \t\r\n"
Damien Miller306d1182006-03-15 12:05:59 +1100314#define QUOTE "\""
Damien Miller61c51502000-08-18 14:01:04 +1000315
Ben Lindstrom4cc240d2001-07-04 04:46:56 +0000316/* return next token in configuration line */
djm@openbsd.org7082bb52018-06-09 03:01:12 +0000317static char *
318strdelim_internal(char **s, int split_equals)
Damien Miller61c51502000-08-18 14:01:04 +1000319{
djm@openbsd.orgc7c458e2018-03-07 23:53:08 +0000320 char *old;
Damien Miller61c51502000-08-18 14:01:04 +1000321 int wspace = 0;
322
323 if (*s == NULL)
324 return NULL;
325
326 old = *s;
327
djm@openbsd.org7082bb52018-06-09 03:01:12 +0000328 *s = strpbrk(*s,
329 split_equals ? WHITESPACE QUOTE "=" : WHITESPACE QUOTE);
Damien Miller61c51502000-08-18 14:01:04 +1000330 if (*s == NULL)
331 return (old);
332
Damien Miller306d1182006-03-15 12:05:59 +1100333 if (*s[0] == '\"') {
334 memmove(*s, *s + 1, strlen(*s)); /* move nul too */
335 /* Find matching quote */
djm@openbsd.orgc7c458e2018-03-07 23:53:08 +0000336 if ((*s = strpbrk(*s, QUOTE)) == NULL) {
337 return (NULL); /* no matching quote */
338 } else {
339 *s[0] = '\0';
340 *s += strspn(*s + 1, WHITESPACE) + 1;
341 return (old);
Damien Miller306d1182006-03-15 12:05:59 +1100342 }
343 }
344
Damien Miller61c51502000-08-18 14:01:04 +1000345 /* Allow only one '=' to be skipped */
djm@openbsd.org7082bb52018-06-09 03:01:12 +0000346 if (split_equals && *s[0] == '=')
Damien Miller61c51502000-08-18 14:01:04 +1000347 wspace = 1;
348 *s[0] = '\0';
349
Damien Miller306d1182006-03-15 12:05:59 +1100350 /* Skip any extra whitespace after first token */
Damien Miller61c51502000-08-18 14:01:04 +1000351 *s += strspn(*s + 1, WHITESPACE) + 1;
djm@openbsd.org7082bb52018-06-09 03:01:12 +0000352 if (split_equals && *s[0] == '=' && !wspace)
Damien Miller61c51502000-08-18 14:01:04 +1000353 *s += strspn(*s + 1, WHITESPACE) + 1;
354
355 return (old);
356}
Kevin Stevesb6e773a2001-02-04 13:20:36 +0000357
djm@openbsd.org7082bb52018-06-09 03:01:12 +0000358/*
359 * Return next token in configuration line; splts on whitespace or a
360 * single '=' character.
361 */
362char *
363strdelim(char **s)
364{
365 return strdelim_internal(s, 1);
366}
367
368/*
369 * Return next token in configuration line; splts on whitespace only.
370 */
371char *
372strdelimw(char **s)
373{
374 return strdelim_internal(s, 0);
375}
376
Ben Lindstrom086cf212001-03-05 05:56:40 +0000377struct passwd *
378pwcopy(struct passwd *pw)
379{
Damien Miller07d86be2006-03-26 14:19:21 +1100380 struct passwd *copy = xcalloc(1, sizeof(*copy));
Ben Lindstrom40304422001-03-05 06:22:01 +0000381
Ben Lindstrom086cf212001-03-05 05:56:40 +0000382 copy->pw_name = xstrdup(pw->pw_name);
383 copy->pw_passwd = xstrdup(pw->pw_passwd);
Damien Miller6332da22013-04-23 14:25:52 +1000384#ifdef HAVE_STRUCT_PASSWD_PW_GECOS
Ben Lindstrom40304422001-03-05 06:22:01 +0000385 copy->pw_gecos = xstrdup(pw->pw_gecos);
Damien Miller6332da22013-04-23 14:25:52 +1000386#endif
Ben Lindstrom086cf212001-03-05 05:56:40 +0000387 copy->pw_uid = pw->pw_uid;
388 copy->pw_gid = pw->pw_gid;
Damien Miller6332da22013-04-23 14:25:52 +1000389#ifdef HAVE_STRUCT_PASSWD_PW_EXPIRE
Ben Lindstrom3af4d462001-06-21 03:11:27 +0000390 copy->pw_expire = pw->pw_expire;
Kevin Steves82456952001-06-22 21:14:18 +0000391#endif
Damien Miller6332da22013-04-23 14:25:52 +1000392#ifdef HAVE_STRUCT_PASSWD_PW_CHANGE
Ben Lindstrom3af4d462001-06-21 03:11:27 +0000393 copy->pw_change = pw->pw_change;
Kevin Steves82456952001-06-22 21:14:18 +0000394#endif
Damien Miller6332da22013-04-23 14:25:52 +1000395#ifdef HAVE_STRUCT_PASSWD_PW_CLASS
Ben Lindstrom086cf212001-03-05 05:56:40 +0000396 copy->pw_class = xstrdup(pw->pw_class);
Ben Lindstrom0f68db42001-03-05 07:57:09 +0000397#endif
Ben Lindstrom086cf212001-03-05 05:56:40 +0000398 copy->pw_dir = xstrdup(pw->pw_dir);
399 copy->pw_shell = xstrdup(pw->pw_shell);
400 return copy;
401}
402
Ben Lindstrom4cc240d2001-07-04 04:46:56 +0000403/*
404 * Convert ASCII string to TCP/IP port number.
Damien Miller3dc71ad2009-01-28 16:31:22 +1100405 * Port must be >=0 and <=65535.
406 * Return -1 if invalid.
Ben Lindstrom4cc240d2001-07-04 04:46:56 +0000407 */
408int
409a2port(const char *s)
Ben Lindstrom19066a12001-04-12 23:39:26 +0000410{
naddy@openbsd.org25813332018-10-05 14:26:09 +0000411 struct servent *se;
Damien Miller3dc71ad2009-01-28 16:31:22 +1100412 long long port;
413 const char *errstr;
Ben Lindstrom19066a12001-04-12 23:39:26 +0000414
Damien Miller3dc71ad2009-01-28 16:31:22 +1100415 port = strtonum(s, 0, 65535, &errstr);
naddy@openbsd.org25813332018-10-05 14:26:09 +0000416 if (errstr == NULL)
417 return (int)port;
418 if ((se = getservbyname(s, "tcp")) != NULL)
419 return ntohs(se->s_port);
420 return -1;
Ben Lindstrom19066a12001-04-12 23:39:26 +0000421}
422
Damien Millerd27b9472005-12-13 19:29:02 +1100423int
424a2tun(const char *s, int *remote)
425{
426 const char *errstr = NULL;
427 char *sp, *ep;
428 int tun;
429
430 if (remote != NULL) {
Damien Miller7b58e802005-12-13 19:33:19 +1100431 *remote = SSH_TUNID_ANY;
Damien Millerd27b9472005-12-13 19:29:02 +1100432 sp = xstrdup(s);
433 if ((ep = strchr(sp, ':')) == NULL) {
Darren Tuckera627d422013-06-02 07:31:17 +1000434 free(sp);
Damien Millerd27b9472005-12-13 19:29:02 +1100435 return (a2tun(s, NULL));
436 }
437 ep[0] = '\0'; ep++;
438 *remote = a2tun(ep, NULL);
439 tun = a2tun(sp, NULL);
Darren Tuckera627d422013-06-02 07:31:17 +1000440 free(sp);
Damien Miller7b58e802005-12-13 19:33:19 +1100441 return (*remote == SSH_TUNID_ERR ? *remote : tun);
Damien Millerd27b9472005-12-13 19:29:02 +1100442 }
443
444 if (strcasecmp(s, "any") == 0)
Damien Miller7b58e802005-12-13 19:33:19 +1100445 return (SSH_TUNID_ANY);
Damien Millerd27b9472005-12-13 19:29:02 +1100446
Damien Miller7b58e802005-12-13 19:33:19 +1100447 tun = strtonum(s, 0, SSH_TUNID_MAX, &errstr);
448 if (errstr != NULL)
449 return (SSH_TUNID_ERR);
Damien Millerd27b9472005-12-13 19:29:02 +1100450
451 return (tun);
452}
453
Ben Lindstrom1bda4c82001-06-05 19:59:08 +0000454#define SECONDS 1
455#define MINUTES (SECONDS * 60)
456#define HOURS (MINUTES * 60)
457#define DAYS (HOURS * 24)
458#define WEEKS (DAYS * 7)
459
Ben Lindstrom4cc240d2001-07-04 04:46:56 +0000460/*
461 * Convert a time string into seconds; format is
462 * a sequence of:
463 * time[qualifier]
464 *
465 * Valid time qualifiers are:
466 * <none> seconds
467 * s|S seconds
468 * m|M minutes
469 * h|H hours
470 * d|D days
471 * w|W weeks
472 *
473 * Examples:
474 * 90m 90 minutes
475 * 1h30m 90 minutes
476 * 2d 2 days
477 * 1w 1 week
478 *
479 * Return -1 if time string is invalid.
480 */
481long
482convtime(const char *s)
Ben Lindstrom1bda4c82001-06-05 19:59:08 +0000483{
dtucker@openbsd.orgf5746b42017-03-14 00:25:03 +0000484 long total, secs, multiplier = 1;
Ben Lindstrom1bda4c82001-06-05 19:59:08 +0000485 const char *p;
486 char *endp;
487
488 errno = 0;
489 total = 0;
490 p = s;
491
492 if (p == NULL || *p == '\0')
493 return -1;
494
495 while (*p) {
496 secs = strtol(p, &endp, 10);
497 if (p == endp ||
498 (errno == ERANGE && (secs == LONG_MIN || secs == LONG_MAX)) ||
499 secs < 0)
500 return -1;
501
502 switch (*endp++) {
503 case '\0':
504 endp--;
Damien Miller69b72032006-03-26 14:02:35 +1100505 break;
Ben Lindstrom1bda4c82001-06-05 19:59:08 +0000506 case 's':
507 case 'S':
508 break;
509 case 'm':
510 case 'M':
dtucker@openbsd.orgf5746b42017-03-14 00:25:03 +0000511 multiplier = MINUTES;
Ben Lindstrom1bda4c82001-06-05 19:59:08 +0000512 break;
513 case 'h':
514 case 'H':
dtucker@openbsd.orgf5746b42017-03-14 00:25:03 +0000515 multiplier = HOURS;
Ben Lindstrom1bda4c82001-06-05 19:59:08 +0000516 break;
517 case 'd':
518 case 'D':
dtucker@openbsd.orgf5746b42017-03-14 00:25:03 +0000519 multiplier = DAYS;
Ben Lindstrom1bda4c82001-06-05 19:59:08 +0000520 break;
521 case 'w':
522 case 'W':
dtucker@openbsd.orgf5746b42017-03-14 00:25:03 +0000523 multiplier = WEEKS;
Ben Lindstrom1bda4c82001-06-05 19:59:08 +0000524 break;
525 default:
526 return -1;
527 }
dtucker@openbsd.orgc6774d22017-03-14 00:55:37 +0000528 if (secs >= LONG_MAX / multiplier)
dtucker@openbsd.orgf5746b42017-03-14 00:25:03 +0000529 return -1;
530 secs *= multiplier;
dtucker@openbsd.orgc6774d22017-03-14 00:55:37 +0000531 if (total >= LONG_MAX - secs)
dtucker@openbsd.orgf5746b42017-03-14 00:25:03 +0000532 return -1;
Ben Lindstrom1bda4c82001-06-05 19:59:08 +0000533 total += secs;
534 if (total < 0)
535 return -1;
536 p = endp;
537 }
538
539 return total;
540}
541
Damien Millerf91ee4c2005-03-01 21:24:33 +1100542/*
Darren Tuckerda345532006-07-10 23:04:19 +1000543 * Returns a standardized host+port identifier string.
544 * Caller must free returned string.
545 */
546char *
547put_host_port(const char *host, u_short port)
548{
549 char *hoststr;
550
551 if (port == 0 || port == SSH_DEFAULT_PORT)
552 return(xstrdup(host));
553 if (asprintf(&hoststr, "[%s]:%d", host, (int)port) < 0)
554 fatal("put_host_port: asprintf: %s", strerror(errno));
555 debug3("put_host_port: %s", hoststr);
556 return hoststr;
557}
558
559/*
Damien Millerf91ee4c2005-03-01 21:24:33 +1100560 * Search for next delimiter between hostnames/addresses and ports.
561 * Argument may be modified (for termination).
562 * Returns *cp if parsing succeeds.
millert@openbsd.org887669e2017-10-21 23:06:24 +0000563 * *cp is set to the start of the next field, if one was found.
564 * The delimiter char, if present, is stored in delim.
Damien Millerf91ee4c2005-03-01 21:24:33 +1100565 * If this is the last field, *cp is set to NULL.
566 */
dtucker@openbsd.orgd05ea252019-01-23 21:50:56 +0000567char *
millert@openbsd.org887669e2017-10-21 23:06:24 +0000568hpdelim2(char **cp, char *delim)
Damien Millerf91ee4c2005-03-01 21:24:33 +1100569{
570 char *s, *old;
571
572 if (cp == NULL || *cp == NULL)
573 return NULL;
574
575 old = s = *cp;
576 if (*s == '[') {
577 if ((s = strchr(s, ']')) == NULL)
578 return NULL;
579 else
580 s++;
581 } else if ((s = strpbrk(s, ":/")) == NULL)
582 s = *cp + strlen(*cp); /* skip to end (see first case below) */
583
584 switch (*s) {
585 case '\0':
586 *cp = NULL; /* no more fields*/
587 break;
Darren Tucker47eede72005-03-14 23:08:12 +1100588
Damien Millerf91ee4c2005-03-01 21:24:33 +1100589 case ':':
590 case '/':
millert@openbsd.org887669e2017-10-21 23:06:24 +0000591 if (delim != NULL)
592 *delim = *s;
Damien Millerf91ee4c2005-03-01 21:24:33 +1100593 *s = '\0'; /* terminate */
594 *cp = s + 1;
595 break;
Darren Tucker47eede72005-03-14 23:08:12 +1100596
Damien Millerf91ee4c2005-03-01 21:24:33 +1100597 default:
598 return NULL;
599 }
600
601 return old;
602}
603
Ben Lindstrom4529b702001-05-03 23:39:53 +0000604char *
millert@openbsd.org887669e2017-10-21 23:06:24 +0000605hpdelim(char **cp)
606{
607 return hpdelim2(cp, NULL);
608}
609
610char *
Ben Lindstrom4529b702001-05-03 23:39:53 +0000611cleanhostname(char *host)
612{
613 if (*host == '[' && host[strlen(host) - 1] == ']') {
614 host[strlen(host) - 1] = '\0';
615 return (host + 1);
616 } else
617 return host;
618}
619
620char *
621colon(char *cp)
622{
623 int flag = 0;
624
625 if (*cp == ':') /* Leading colon is part of file name. */
Damien Miller2e774462010-06-26 09:30:47 +1000626 return NULL;
Ben Lindstrom4529b702001-05-03 23:39:53 +0000627 if (*cp == '[')
628 flag = 1;
629
630 for (; *cp; ++cp) {
631 if (*cp == '@' && *(cp+1) == '[')
632 flag = 1;
633 if (*cp == ']' && *(cp+1) == ':' && flag)
634 return (cp+1);
635 if (*cp == ':' && !flag)
636 return (cp);
637 if (*cp == '/')
Damien Miller2e774462010-06-26 09:30:47 +1000638 return NULL;
Ben Lindstrom4529b702001-05-03 23:39:53 +0000639 }
Damien Miller2e774462010-06-26 09:30:47 +1000640 return NULL;
Ben Lindstrom4529b702001-05-03 23:39:53 +0000641}
642
djm@openbsd.orged877ef2016-07-15 00:24:30 +0000643/*
millert@openbsd.org887669e2017-10-21 23:06:24 +0000644 * Parse a [user@]host:[path] string.
645 * Caller must free returned user, host and path.
646 * Any of the pointer return arguments may be NULL (useful for syntax checking).
647 * If user was not specified then *userp will be set to NULL.
648 * If host was not specified then *hostp will be set to NULL.
649 * If path was not specified then *pathp will be set to ".".
650 * Returns 0 on success, -1 on failure.
651 */
652int
653parse_user_host_path(const char *s, char **userp, char **hostp, char **pathp)
654{
655 char *user = NULL, *host = NULL, *path = NULL;
656 char *sdup, *tmp;
657 int ret = -1;
658
659 if (userp != NULL)
660 *userp = NULL;
661 if (hostp != NULL)
662 *hostp = NULL;
663 if (pathp != NULL)
664 *pathp = NULL;
665
millert@openbsd.orgb9903ee2017-10-24 19:41:45 +0000666 sdup = xstrdup(s);
millert@openbsd.org887669e2017-10-21 23:06:24 +0000667
668 /* Check for remote syntax: [user@]host:[path] */
669 if ((tmp = colon(sdup)) == NULL)
670 goto out;
671
672 /* Extract optional path */
673 *tmp++ = '\0';
674 if (*tmp == '\0')
675 tmp = ".";
676 path = xstrdup(tmp);
677
678 /* Extract optional user and mandatory host */
679 tmp = strrchr(sdup, '@');
680 if (tmp != NULL) {
681 *tmp++ = '\0';
682 host = xstrdup(cleanhostname(tmp));
683 if (*sdup != '\0')
684 user = xstrdup(sdup);
685 } else {
686 host = xstrdup(cleanhostname(sdup));
687 user = NULL;
688 }
689
690 /* Success */
691 if (userp != NULL) {
692 *userp = user;
693 user = NULL;
694 }
695 if (hostp != NULL) {
696 *hostp = host;
697 host = NULL;
millert@openbsd.orgb9903ee2017-10-24 19:41:45 +0000698 }
millert@openbsd.org887669e2017-10-21 23:06:24 +0000699 if (pathp != NULL) {
700 *pathp = path;
701 path = NULL;
millert@openbsd.orgb9903ee2017-10-24 19:41:45 +0000702 }
millert@openbsd.org887669e2017-10-21 23:06:24 +0000703 ret = 0;
704out:
705 free(sdup);
706 free(user);
707 free(host);
708 free(path);
709 return ret;
710}
711
712/*
djm@openbsd.orged877ef2016-07-15 00:24:30 +0000713 * Parse a [user@]host[:port] string.
714 * Caller must free returned user and host.
715 * Any of the pointer return arguments may be NULL (useful for syntax checking).
716 * If user was not specified then *userp will be set to NULL.
717 * If port was not specified then *portp will be -1.
718 * Returns 0 on success, -1 on failure.
719 */
720int
721parse_user_host_port(const char *s, char **userp, char **hostp, int *portp)
722{
723 char *sdup, *cp, *tmp;
724 char *user = NULL, *host = NULL;
725 int port = -1, ret = -1;
726
727 if (userp != NULL)
728 *userp = NULL;
729 if (hostp != NULL)
730 *hostp = NULL;
731 if (portp != NULL)
732 *portp = -1;
733
734 if ((sdup = tmp = strdup(s)) == NULL)
735 return -1;
736 /* Extract optional username */
millert@openbsd.org887669e2017-10-21 23:06:24 +0000737 if ((cp = strrchr(tmp, '@')) != NULL) {
djm@openbsd.orged877ef2016-07-15 00:24:30 +0000738 *cp = '\0';
739 if (*tmp == '\0')
740 goto out;
741 if ((user = strdup(tmp)) == NULL)
742 goto out;
743 tmp = cp + 1;
744 }
745 /* Extract mandatory hostname */
746 if ((cp = hpdelim(&tmp)) == NULL || *cp == '\0')
747 goto out;
748 host = xstrdup(cleanhostname(cp));
749 /* Convert and verify optional port */
750 if (tmp != NULL && *tmp != '\0') {
751 if ((port = a2port(tmp)) <= 0)
752 goto out;
753 }
754 /* Success */
755 if (userp != NULL) {
756 *userp = user;
757 user = NULL;
758 }
759 if (hostp != NULL) {
760 *hostp = host;
761 host = NULL;
762 }
763 if (portp != NULL)
764 *portp = port;
765 ret = 0;
766 out:
767 free(sdup);
768 free(user);
769 free(host);
770 return ret;
771}
772
millert@openbsd.org887669e2017-10-21 23:06:24 +0000773/*
774 * Converts a two-byte hex string to decimal.
775 * Returns the decimal value or -1 for invalid input.
776 */
777static int
778hexchar(const char *s)
779{
780 unsigned char result[2];
781 int i;
782
783 for (i = 0; i < 2; i++) {
784 if (s[i] >= '0' && s[i] <= '9')
785 result[i] = (unsigned char)(s[i] - '0');
786 else if (s[i] >= 'a' && s[i] <= 'f')
787 result[i] = (unsigned char)(s[i] - 'a') + 10;
788 else if (s[i] >= 'A' && s[i] <= 'F')
789 result[i] = (unsigned char)(s[i] - 'A') + 10;
790 else
791 return -1;
792 }
793 return (result[0] << 4) | result[1];
794}
795
796/*
797 * Decode an url-encoded string.
798 * Returns a newly allocated string on success or NULL on failure.
799 */
800static char *
801urldecode(const char *src)
802{
803 char *ret, *dst;
804 int ch;
805
806 ret = xmalloc(strlen(src) + 1);
807 for (dst = ret; *src != '\0'; src++) {
808 switch (*src) {
809 case '+':
810 *dst++ = ' ';
811 break;
812 case '%':
813 if (!isxdigit((unsigned char)src[1]) ||
814 !isxdigit((unsigned char)src[2]) ||
815 (ch = hexchar(src + 1)) == -1) {
816 free(ret);
817 return NULL;
818 }
819 *dst++ = ch;
820 src += 2;
821 break;
822 default:
823 *dst++ = *src;
824 break;
825 }
826 }
827 *dst = '\0';
828
829 return ret;
830}
831
832/*
833 * Parse an (scp|ssh|sftp)://[user@]host[:port][/path] URI.
834 * See https://tools.ietf.org/html/draft-ietf-secsh-scp-sftp-ssh-uri-04
835 * Either user or path may be url-encoded (but not host or port).
836 * Caller must free returned user, host and path.
837 * Any of the pointer return arguments may be NULL (useful for syntax checking)
838 * but the scheme must always be specified.
839 * If user was not specified then *userp will be set to NULL.
840 * If port was not specified then *portp will be -1.
841 * If path was not specified then *pathp will be set to NULL.
842 * Returns 0 on success, 1 if non-uri/wrong scheme, -1 on error/invalid uri.
843 */
844int
845parse_uri(const char *scheme, const char *uri, char **userp, char **hostp,
846 int *portp, char **pathp)
847{
848 char *uridup, *cp, *tmp, ch;
849 char *user = NULL, *host = NULL, *path = NULL;
850 int port = -1, ret = -1;
851 size_t len;
852
853 len = strlen(scheme);
854 if (strncmp(uri, scheme, len) != 0 || strncmp(uri + len, "://", 3) != 0)
855 return 1;
856 uri += len + 3;
857
858 if (userp != NULL)
859 *userp = NULL;
860 if (hostp != NULL)
861 *hostp = NULL;
862 if (portp != NULL)
863 *portp = -1;
864 if (pathp != NULL)
865 *pathp = NULL;
866
867 uridup = tmp = xstrdup(uri);
868
869 /* Extract optional ssh-info (username + connection params) */
870 if ((cp = strchr(tmp, '@')) != NULL) {
871 char *delim;
872
873 *cp = '\0';
874 /* Extract username and connection params */
875 if ((delim = strchr(tmp, ';')) != NULL) {
876 /* Just ignore connection params for now */
877 *delim = '\0';
878 }
879 if (*tmp == '\0') {
880 /* Empty username */
881 goto out;
882 }
883 if ((user = urldecode(tmp)) == NULL)
884 goto out;
885 tmp = cp + 1;
886 }
887
888 /* Extract mandatory hostname */
889 if ((cp = hpdelim2(&tmp, &ch)) == NULL || *cp == '\0')
890 goto out;
891 host = xstrdup(cleanhostname(cp));
892 if (!valid_domain(host, 0, NULL))
893 goto out;
894
895 if (tmp != NULL && *tmp != '\0') {
896 if (ch == ':') {
897 /* Convert and verify port. */
898 if ((cp = strchr(tmp, '/')) != NULL)
899 *cp = '\0';
900 if ((port = a2port(tmp)) <= 0)
901 goto out;
902 tmp = cp ? cp + 1 : NULL;
903 }
904 if (tmp != NULL && *tmp != '\0') {
905 /* Extract optional path */
906 if ((path = urldecode(tmp)) == NULL)
907 goto out;
908 }
909 }
910
911 /* Success */
912 if (userp != NULL) {
913 *userp = user;
914 user = NULL;
915 }
916 if (hostp != NULL) {
917 *hostp = host;
918 host = NULL;
919 }
920 if (portp != NULL)
921 *portp = port;
922 if (pathp != NULL) {
923 *pathp = path;
924 path = NULL;
925 }
926 ret = 0;
927 out:
928 free(uridup);
929 free(user);
930 free(host);
931 free(path);
932 return ret;
933}
934
Ben Lindstrom4cc240d2001-07-04 04:46:56 +0000935/* function to assist building execv() arguments */
Ben Lindstrom387c4722001-05-08 20:27:25 +0000936void
937addargs(arglist *args, char *fmt, ...)
938{
939 va_list ap;
Damien Miller3eec6b72006-01-31 21:49:27 +1100940 char *cp;
Darren Tuckerc7a6fc42004-08-13 21:18:00 +1000941 u_int nalloc;
Damien Miller3eec6b72006-01-31 21:49:27 +1100942 int r;
Ben Lindstrom387c4722001-05-08 20:27:25 +0000943
944 va_start(ap, fmt);
Damien Miller3eec6b72006-01-31 21:49:27 +1100945 r = vasprintf(&cp, fmt, ap);
Ben Lindstrom387c4722001-05-08 20:27:25 +0000946 va_end(ap);
Damien Miller3eec6b72006-01-31 21:49:27 +1100947 if (r == -1)
948 fatal("addargs: argument too long");
Ben Lindstrom387c4722001-05-08 20:27:25 +0000949
Darren Tuckerfb16b242003-09-22 21:04:23 +1000950 nalloc = args->nalloc;
Ben Lindstrom387c4722001-05-08 20:27:25 +0000951 if (args->list == NULL) {
Darren Tuckerfb16b242003-09-22 21:04:23 +1000952 nalloc = 32;
Ben Lindstrom387c4722001-05-08 20:27:25 +0000953 args->num = 0;
Darren Tuckerfb16b242003-09-22 21:04:23 +1000954 } else if (args->num+2 >= nalloc)
955 nalloc *= 2;
Ben Lindstrom387c4722001-05-08 20:27:25 +0000956
deraadt@openbsd.org9e509d42017-05-31 09:15:42 +0000957 args->list = xrecallocarray(args->list, args->nalloc, nalloc, sizeof(char *));
Darren Tuckerfb16b242003-09-22 21:04:23 +1000958 args->nalloc = nalloc;
Damien Miller3eec6b72006-01-31 21:49:27 +1100959 args->list[args->num++] = cp;
Ben Lindstrom387c4722001-05-08 20:27:25 +0000960 args->list[args->num] = NULL;
961}
Darren Tucker22cc7412004-12-06 22:47:41 +1100962
Damien Miller3eec6b72006-01-31 21:49:27 +1100963void
964replacearg(arglist *args, u_int which, char *fmt, ...)
965{
966 va_list ap;
967 char *cp;
968 int r;
969
970 va_start(ap, fmt);
971 r = vasprintf(&cp, fmt, ap);
972 va_end(ap);
973 if (r == -1)
974 fatal("replacearg: argument too long");
975
976 if (which >= args->num)
977 fatal("replacearg: tried to replace invalid arg %d >= %d",
978 which, args->num);
Darren Tuckera627d422013-06-02 07:31:17 +1000979 free(args->list[which]);
Damien Miller3eec6b72006-01-31 21:49:27 +1100980 args->list[which] = cp;
981}
982
983void
984freeargs(arglist *args)
985{
986 u_int i;
987
988 if (args->list != NULL) {
989 for (i = 0; i < args->num; i++)
Darren Tuckera627d422013-06-02 07:31:17 +1000990 free(args->list[i]);
991 free(args->list);
Damien Miller3eec6b72006-01-31 21:49:27 +1100992 args->nalloc = args->num = 0;
993 args->list = NULL;
994 }
995}
996
Darren Tucker22cc7412004-12-06 22:47:41 +1100997/*
Damien Miller5fd38c02005-05-26 12:02:14 +1000998 * Expands tildes in the file name. Returns data allocated by xmalloc.
999 * Warning: this calls getpw*.
1000 */
1001char *
1002tilde_expand_filename(const char *filename, uid_t uid)
1003{
Darren Tucker2ca51bf2013-05-16 20:22:46 +10001004 const char *path, *sep;
1005 char user[128], *ret;
Damien Miller5fd38c02005-05-26 12:02:14 +10001006 struct passwd *pw;
Damien Millereccb9de2005-06-17 12:59:34 +10001007 u_int len, slash;
Damien Miller5fd38c02005-05-26 12:02:14 +10001008
1009 if (*filename != '~')
1010 return (xstrdup(filename));
1011 filename++;
1012
1013 path = strchr(filename, '/');
1014 if (path != NULL && path > filename) { /* ~user/path */
Damien Millereccb9de2005-06-17 12:59:34 +10001015 slash = path - filename;
1016 if (slash > sizeof(user) - 1)
Damien Miller5fd38c02005-05-26 12:02:14 +10001017 fatal("tilde_expand_filename: ~username too long");
Damien Millereccb9de2005-06-17 12:59:34 +10001018 memcpy(user, filename, slash);
1019 user[slash] = '\0';
Damien Miller5fd38c02005-05-26 12:02:14 +10001020 if ((pw = getpwnam(user)) == NULL)
1021 fatal("tilde_expand_filename: No such user %s", user);
1022 } else if ((pw = getpwuid(uid)) == NULL) /* ~/path */
Darren Tucker7517b5b2008-06-13 14:48:59 +10001023 fatal("tilde_expand_filename: No such uid %ld", (long)uid);
Damien Miller5fd38c02005-05-26 12:02:14 +10001024
Damien Miller5fd38c02005-05-26 12:02:14 +10001025 /* Make sure directory has a trailing '/' */
1026 len = strlen(pw->pw_dir);
Darren Tucker026d9db2013-05-16 20:23:52 +10001027 if (len == 0 || pw->pw_dir[len - 1] != '/')
Darren Tucker2ca51bf2013-05-16 20:22:46 +10001028 sep = "/";
1029 else
1030 sep = "";
Damien Miller5fd38c02005-05-26 12:02:14 +10001031
1032 /* Skip leading '/' from specified path */
1033 if (path != NULL)
1034 filename = path + 1;
Darren Tucker2ca51bf2013-05-16 20:22:46 +10001035
deraadt@openbsd.org2ae4f332015-01-16 06:40:12 +00001036 if (xasprintf(&ret, "%s%s%s", pw->pw_dir, sep, filename) >= PATH_MAX)
Damien Miller5fd38c02005-05-26 12:02:14 +10001037 fatal("tilde_expand_filename: Path too long");
1038
Darren Tucker2ca51bf2013-05-16 20:22:46 +10001039 return (ret);
Damien Miller5fd38c02005-05-26 12:02:14 +10001040}
1041
1042/*
Damien Miller6476cad2005-06-16 13:18:34 +10001043 * Expand a string with a set of %[char] escapes. A number of escapes may be
1044 * specified as (char *escape_chars, char *replacement) pairs. The list must
Darren Tuckerbee73d52005-07-14 17:05:02 +10001045 * be terminated by a NULL escape_char. Returns replaced string in memory
Damien Miller6476cad2005-06-16 13:18:34 +10001046 * allocated by xmalloc.
1047 */
1048char *
1049percent_expand(const char *string, ...)
1050{
1051#define EXPAND_MAX_KEYS 16
Darren Tucker70d87692010-01-08 18:49:16 +11001052 u_int num_keys, i, j;
Damien Miller6476cad2005-06-16 13:18:34 +10001053 struct {
1054 const char *key;
1055 const char *repl;
1056 } keys[EXPAND_MAX_KEYS];
Damien Miller6476cad2005-06-16 13:18:34 +10001057 char buf[4096];
1058 va_list ap;
1059
1060 /* Gather keys */
1061 va_start(ap, string);
1062 for (num_keys = 0; num_keys < EXPAND_MAX_KEYS; num_keys++) {
1063 keys[num_keys].key = va_arg(ap, char *);
1064 if (keys[num_keys].key == NULL)
1065 break;
1066 keys[num_keys].repl = va_arg(ap, char *);
1067 if (keys[num_keys].repl == NULL)
Darren Tucker70d87692010-01-08 18:49:16 +11001068 fatal("%s: NULL replacement", __func__);
Damien Miller6476cad2005-06-16 13:18:34 +10001069 }
Darren Tucker70d87692010-01-08 18:49:16 +11001070 if (num_keys == EXPAND_MAX_KEYS && va_arg(ap, char *) != NULL)
1071 fatal("%s: too many keys", __func__);
Damien Miller6476cad2005-06-16 13:18:34 +10001072 va_end(ap);
1073
Damien Miller6476cad2005-06-16 13:18:34 +10001074 /* Expand string */
1075 *buf = '\0';
1076 for (i = 0; *string != '\0'; string++) {
1077 if (*string != '%') {
1078 append:
1079 buf[i++] = *string;
1080 if (i >= sizeof(buf))
Darren Tucker70d87692010-01-08 18:49:16 +11001081 fatal("%s: string too long", __func__);
Damien Miller6476cad2005-06-16 13:18:34 +10001082 buf[i] = '\0';
1083 continue;
1084 }
1085 string++;
Darren Tucker70d87692010-01-08 18:49:16 +11001086 /* %% case */
Damien Miller6476cad2005-06-16 13:18:34 +10001087 if (*string == '%')
1088 goto append;
tobias@openbsd.org8b56e592015-12-04 21:51:06 +00001089 if (*string == '\0')
1090 fatal("%s: invalid format", __func__);
Damien Miller6476cad2005-06-16 13:18:34 +10001091 for (j = 0; j < num_keys; j++) {
1092 if (strchr(keys[j].key, *string) != NULL) {
1093 i = strlcat(buf, keys[j].repl, sizeof(buf));
1094 if (i >= sizeof(buf))
Darren Tucker70d87692010-01-08 18:49:16 +11001095 fatal("%s: string too long", __func__);
Damien Miller6476cad2005-06-16 13:18:34 +10001096 break;
1097 }
1098 }
1099 if (j >= num_keys)
Darren Tucker70d87692010-01-08 18:49:16 +11001100 fatal("%s: unknown key %%%c", __func__, *string);
Damien Miller6476cad2005-06-16 13:18:34 +10001101 }
1102 return (xstrdup(buf));
1103#undef EXPAND_MAX_KEYS
1104}
1105
Damien Millerd27b9472005-12-13 19:29:02 +11001106int
djm@openbsd.orgb7548b12017-10-23 05:08:00 +00001107tun_open(int tun, int mode, char **ifname)
Damien Millerd27b9472005-12-13 19:29:02 +11001108{
Damien Miller62a31c92005-12-13 20:44:13 +11001109#if defined(CUSTOM_SYS_TUN_OPEN)
djm@openbsd.orgb7548b12017-10-23 05:08:00 +00001110 return (sys_tun_open(tun, mode, ifname));
Damien Miller2dcddbf2006-01-01 19:47:05 +11001111#elif defined(SSH_TUN_OPENBSD)
Damien Miller7b58e802005-12-13 19:33:19 +11001112 struct ifreq ifr;
Damien Millerd27b9472005-12-13 19:29:02 +11001113 char name[100];
Damien Miller7b58e802005-12-13 19:33:19 +11001114 int fd = -1, sock;
sthen@openbsd.orga820a862015-10-24 08:34:09 +00001115 const char *tunbase = "tun";
1116
djm@openbsd.orgb7548b12017-10-23 05:08:00 +00001117 if (ifname != NULL)
1118 *ifname = NULL;
1119
sthen@openbsd.orga820a862015-10-24 08:34:09 +00001120 if (mode == SSH_TUNMODE_ETHERNET)
1121 tunbase = "tap";
Damien Millerd27b9472005-12-13 19:29:02 +11001122
Damien Miller7b58e802005-12-13 19:33:19 +11001123 /* Open the tunnel device */
1124 if (tun <= SSH_TUNID_MAX) {
sthen@openbsd.orga820a862015-10-24 08:34:09 +00001125 snprintf(name, sizeof(name), "/dev/%s%d", tunbase, tun);
Damien Miller7b58e802005-12-13 19:33:19 +11001126 fd = open(name, O_RDWR);
1127 } else if (tun == SSH_TUNID_ANY) {
1128 for (tun = 100; tun >= 0; tun--) {
sthen@openbsd.orga820a862015-10-24 08:34:09 +00001129 snprintf(name, sizeof(name), "/dev/%s%d",
1130 tunbase, tun);
Damien Miller7b58e802005-12-13 19:33:19 +11001131 if ((fd = open(name, O_RDWR)) >= 0)
1132 break;
Damien Millerd27b9472005-12-13 19:29:02 +11001133 }
1134 } else {
Damien Millera210d522006-01-02 23:40:30 +11001135 debug("%s: invalid tunnel %u", __func__, tun);
djm@openbsd.org2905d6f2015-10-07 00:54:06 +00001136 return -1;
Damien Millerd27b9472005-12-13 19:29:02 +11001137 }
Damien Miller7b58e802005-12-13 19:33:19 +11001138
1139 if (fd < 0) {
djm@openbsd.org2905d6f2015-10-07 00:54:06 +00001140 debug("%s: %s open: %s", __func__, name, strerror(errno));
1141 return -1;
Damien Miller7b58e802005-12-13 19:33:19 +11001142 }
1143
1144 debug("%s: %s mode %d fd %d", __func__, name, mode, fd);
1145
sthen@openbsd.orga820a862015-10-24 08:34:09 +00001146 /* Bring interface up if it is not already */
1147 snprintf(ifr.ifr_name, sizeof(ifr.ifr_name), "%s%d", tunbase, tun);
1148 if ((sock = socket(PF_UNIX, SOCK_STREAM, 0)) == -1)
Damien Miller7b58e802005-12-13 19:33:19 +11001149 goto failed;
1150
djm@openbsd.org2905d6f2015-10-07 00:54:06 +00001151 if (ioctl(sock, SIOCGIFFLAGS, &ifr) == -1) {
1152 debug("%s: get interface %s flags: %s", __func__,
1153 ifr.ifr_name, strerror(errno));
Damien Miller7b58e802005-12-13 19:33:19 +11001154 goto failed;
djm@openbsd.org2905d6f2015-10-07 00:54:06 +00001155 }
Damien Millera1d9a182006-01-02 23:41:21 +11001156
djm@openbsd.org2905d6f2015-10-07 00:54:06 +00001157 if (!(ifr.ifr_flags & IFF_UP)) {
1158 ifr.ifr_flags |= IFF_UP;
1159 if (ioctl(sock, SIOCSIFFLAGS, &ifr) == -1) {
1160 debug("%s: activate interface %s: %s", __func__,
1161 ifr.ifr_name, strerror(errno));
1162 goto failed;
1163 }
1164 }
Damien Miller7b58e802005-12-13 19:33:19 +11001165
djm@openbsd.orgb7548b12017-10-23 05:08:00 +00001166 if (ifname != NULL)
1167 *ifname = xstrdup(ifr.ifr_name);
1168
Damien Miller7b58e802005-12-13 19:33:19 +11001169 close(sock);
djm@openbsd.org2905d6f2015-10-07 00:54:06 +00001170 return fd;
Damien Miller7b58e802005-12-13 19:33:19 +11001171
1172 failed:
1173 if (fd >= 0)
1174 close(fd);
1175 if (sock >= 0)
1176 close(sock);
djm@openbsd.org2905d6f2015-10-07 00:54:06 +00001177 return -1;
Damien Miller62a31c92005-12-13 20:44:13 +11001178#else
1179 error("Tunnel interfaces are not supported on this platform");
1180 return (-1);
1181#endif
Damien Millerd27b9472005-12-13 19:29:02 +11001182}
1183
Darren Tuckerce321d82005-10-03 18:11:24 +10001184void
1185sanitise_stdfd(void)
1186{
Damien Miller72c5b7d2006-01-06 14:50:44 +11001187 int nullfd, dupfd;
Darren Tuckerce321d82005-10-03 18:11:24 +10001188
Damien Miller72c5b7d2006-01-06 14:50:44 +11001189 if ((nullfd = dupfd = open(_PATH_DEVNULL, O_RDWR)) == -1) {
Damien Miller9eab9562009-02-22 08:47:02 +11001190 fprintf(stderr, "Couldn't open /dev/null: %s\n",
1191 strerror(errno));
Darren Tuckerce321d82005-10-03 18:11:24 +10001192 exit(1);
1193 }
krw@openbsd.org574def02016-04-02 14:37:42 +00001194 while (++dupfd <= STDERR_FILENO) {
1195 /* Only populate closed fds. */
1196 if (fcntl(dupfd, F_GETFL) == -1 && errno == EBADF) {
1197 if (dup2(nullfd, dupfd) == -1) {
1198 fprintf(stderr, "dup2: %s\n", strerror(errno));
1199 exit(1);
1200 }
Darren Tuckerce321d82005-10-03 18:11:24 +10001201 }
Darren Tuckerce321d82005-10-03 18:11:24 +10001202 }
krw@openbsd.org574def02016-04-02 14:37:42 +00001203 if (nullfd > STDERR_FILENO)
Darren Tuckerce321d82005-10-03 18:11:24 +10001204 close(nullfd);
1205}
1206
Damien Miller13390022005-07-06 09:44:19 +10001207char *
Damien Miller3f941882006-03-31 23:13:02 +11001208tohex(const void *vp, size_t l)
Damien Miller13390022005-07-06 09:44:19 +10001209{
Damien Miller3f941882006-03-31 23:13:02 +11001210 const u_char *p = (const u_char *)vp;
Damien Miller13390022005-07-06 09:44:19 +10001211 char b[3], *r;
Damien Miller3f941882006-03-31 23:13:02 +11001212 size_t i, hl;
1213
1214 if (l > 65536)
1215 return xstrdup("tohex: length > 65536");
Damien Miller13390022005-07-06 09:44:19 +10001216
1217 hl = l * 2 + 1;
Damien Miller07d86be2006-03-26 14:19:21 +11001218 r = xcalloc(1, hl);
Damien Miller13390022005-07-06 09:44:19 +10001219 for (i = 0; i < l; i++) {
Damien Miller3f941882006-03-31 23:13:02 +11001220 snprintf(b, sizeof(b), "%02x", p[i]);
Damien Miller13390022005-07-06 09:44:19 +10001221 strlcat(r, b, hl);
1222 }
1223 return (r);
1224}
1225
Damien Miller3f941882006-03-31 23:13:02 +11001226u_int64_t
1227get_u64(const void *vp)
1228{
1229 const u_char *p = (const u_char *)vp;
1230 u_int64_t v;
1231
1232 v = (u_int64_t)p[0] << 56;
1233 v |= (u_int64_t)p[1] << 48;
1234 v |= (u_int64_t)p[2] << 40;
1235 v |= (u_int64_t)p[3] << 32;
1236 v |= (u_int64_t)p[4] << 24;
1237 v |= (u_int64_t)p[5] << 16;
1238 v |= (u_int64_t)p[6] << 8;
1239 v |= (u_int64_t)p[7];
1240
1241 return (v);
1242}
1243
1244u_int32_t
1245get_u32(const void *vp)
1246{
1247 const u_char *p = (const u_char *)vp;
1248 u_int32_t v;
1249
1250 v = (u_int32_t)p[0] << 24;
1251 v |= (u_int32_t)p[1] << 16;
1252 v |= (u_int32_t)p[2] << 8;
1253 v |= (u_int32_t)p[3];
1254
1255 return (v);
1256}
1257
Damien Miller88856692014-04-20 13:33:19 +10001258u_int32_t
1259get_u32_le(const void *vp)
1260{
1261 const u_char *p = (const u_char *)vp;
1262 u_int32_t v;
1263
1264 v = (u_int32_t)p[0];
1265 v |= (u_int32_t)p[1] << 8;
1266 v |= (u_int32_t)p[2] << 16;
1267 v |= (u_int32_t)p[3] << 24;
1268
1269 return (v);
1270}
1271
Damien Miller3f941882006-03-31 23:13:02 +11001272u_int16_t
1273get_u16(const void *vp)
1274{
1275 const u_char *p = (const u_char *)vp;
1276 u_int16_t v;
1277
1278 v = (u_int16_t)p[0] << 8;
1279 v |= (u_int16_t)p[1];
1280
1281 return (v);
1282}
1283
1284void
1285put_u64(void *vp, u_int64_t v)
1286{
1287 u_char *p = (u_char *)vp;
1288
1289 p[0] = (u_char)(v >> 56) & 0xff;
1290 p[1] = (u_char)(v >> 48) & 0xff;
1291 p[2] = (u_char)(v >> 40) & 0xff;
1292 p[3] = (u_char)(v >> 32) & 0xff;
1293 p[4] = (u_char)(v >> 24) & 0xff;
1294 p[5] = (u_char)(v >> 16) & 0xff;
1295 p[6] = (u_char)(v >> 8) & 0xff;
1296 p[7] = (u_char)v & 0xff;
1297}
1298
1299void
1300put_u32(void *vp, u_int32_t v)
1301{
1302 u_char *p = (u_char *)vp;
1303
1304 p[0] = (u_char)(v >> 24) & 0xff;
1305 p[1] = (u_char)(v >> 16) & 0xff;
1306 p[2] = (u_char)(v >> 8) & 0xff;
1307 p[3] = (u_char)v & 0xff;
1308}
1309
Damien Miller88856692014-04-20 13:33:19 +10001310void
1311put_u32_le(void *vp, u_int32_t v)
1312{
1313 u_char *p = (u_char *)vp;
1314
1315 p[0] = (u_char)v & 0xff;
1316 p[1] = (u_char)(v >> 8) & 0xff;
1317 p[2] = (u_char)(v >> 16) & 0xff;
1318 p[3] = (u_char)(v >> 24) & 0xff;
1319}
Damien Miller3f941882006-03-31 23:13:02 +11001320
1321void
1322put_u16(void *vp, u_int16_t v)
1323{
1324 u_char *p = (u_char *)vp;
1325
1326 p[0] = (u_char)(v >> 8) & 0xff;
1327 p[1] = (u_char)v & 0xff;
1328}
Darren Tucker3fc464e2008-06-13 06:42:45 +10001329
1330void
1331ms_subtract_diff(struct timeval *start, int *ms)
1332{
1333 struct timeval diff, finish;
1334
dtucker@openbsd.org@openbsd.org5db6fbf2017-11-25 06:46:22 +00001335 monotime_tv(&finish);
1336 timersub(&finish, start, &diff);
Darren Tucker3fc464e2008-06-13 06:42:45 +10001337 *ms -= (diff.tv_sec * 1000) + (diff.tv_usec / 1000);
1338}
1339
1340void
1341ms_to_timeval(struct timeval *tv, int ms)
1342{
1343 if (ms < 0)
1344 ms = 0;
1345 tv->tv_sec = ms / 1000;
1346 tv->tv_usec = (ms % 1000) * 1000;
1347}
1348
dtucker@openbsd.org@openbsd.org5db6fbf2017-11-25 06:46:22 +00001349void
1350monotime_ts(struct timespec *ts)
Darren Tuckerb759c9c2013-06-02 07:46:16 +10001351{
dtucker@openbsd.org@openbsd.org5db6fbf2017-11-25 06:46:22 +00001352 struct timeval tv;
1353#if defined(HAVE_CLOCK_GETTIME) && (defined(CLOCK_BOOTTIME) || \
1354 defined(CLOCK_MONOTONIC) || defined(CLOCK_REALTIME))
Darren Tucker94396b72013-08-08 11:52:37 +10001355 static int gettime_failed = 0;
Darren Tuckerb759c9c2013-06-02 07:46:16 +10001356
Darren Tucker94396b72013-08-08 11:52:37 +10001357 if (!gettime_failed) {
dtucker@openbsd.org@openbsd.org5db6fbf2017-11-25 06:46:22 +00001358# ifdef CLOCK_BOOTTIME
1359 if (clock_gettime(CLOCK_BOOTTIME, ts) == 0)
1360 return;
1361# endif /* CLOCK_BOOTTIME */
1362# ifdef CLOCK_MONOTONIC
1363 if (clock_gettime(CLOCK_MONOTONIC, ts) == 0)
1364 return;
1365# endif /* CLOCK_MONOTONIC */
1366# ifdef CLOCK_REALTIME
1367 /* Not monotonic, but we're almost out of options here. */
1368 if (clock_gettime(CLOCK_REALTIME, ts) == 0)
1369 return;
1370# endif /* CLOCK_REALTIME */
Darren Tucker94396b72013-08-08 11:52:37 +10001371 debug3("clock_gettime: %s", strerror(errno));
1372 gettime_failed = 1;
1373 }
dtucker@openbsd.org@openbsd.org5db6fbf2017-11-25 06:46:22 +00001374#endif /* HAVE_CLOCK_GETTIME && (BOOTTIME || MONOTONIC || REALTIME) */
1375 gettimeofday(&tv, NULL);
1376 ts->tv_sec = tv.tv_sec;
1377 ts->tv_nsec = (long)tv.tv_usec * 1000;
1378}
Darren Tucker94396b72013-08-08 11:52:37 +10001379
dtucker@openbsd.org@openbsd.org5db6fbf2017-11-25 06:46:22 +00001380void
1381monotime_tv(struct timeval *tv)
1382{
1383 struct timespec ts;
1384
1385 monotime_ts(&ts);
1386 tv->tv_sec = ts.tv_sec;
1387 tv->tv_usec = ts.tv_nsec / 1000;
1388}
1389
1390time_t
1391monotime(void)
1392{
1393 struct timespec ts;
1394
1395 monotime_ts(&ts);
1396 return ts.tv_sec;
Darren Tuckerb759c9c2013-06-02 07:46:16 +10001397}
1398
dtucker@openbsd.orgb8d4eaf2016-03-02 22:42:40 +00001399double
1400monotime_double(void)
1401{
1402 struct timespec ts;
1403
dtucker@openbsd.org@openbsd.org5db6fbf2017-11-25 06:46:22 +00001404 monotime_ts(&ts);
1405 return ts.tv_sec + ((double)ts.tv_nsec / 1000000000);
dtucker@openbsd.orgb8d4eaf2016-03-02 22:42:40 +00001406}
1407
Damien Miller65e42f82010-09-24 22:15:11 +10001408void
1409bandwidth_limit_init(struct bwlimit *bw, u_int64_t kbps, size_t buflen)
1410{
1411 bw->buflen = buflen;
1412 bw->rate = kbps;
dtucker@openbsd.org434b5872018-12-07 04:36:09 +00001413 bw->thresh = buflen;
Damien Miller65e42f82010-09-24 22:15:11 +10001414 bw->lamt = 0;
1415 timerclear(&bw->bwstart);
1416 timerclear(&bw->bwend);
dtucker@openbsd.org434b5872018-12-07 04:36:09 +00001417}
Damien Miller65e42f82010-09-24 22:15:11 +10001418
1419/* Callback from read/write loop to insert bandwidth-limiting delays */
1420void
1421bandwidth_limit(struct bwlimit *bw, size_t read_len)
1422{
1423 u_int64_t waitlen;
1424 struct timespec ts, rm;
1425
dtucker@openbsd.org434b5872018-12-07 04:36:09 +00001426 bw->lamt += read_len;
Damien Miller65e42f82010-09-24 22:15:11 +10001427 if (!timerisset(&bw->bwstart)) {
dtucker@openbsd.org@openbsd.org5db6fbf2017-11-25 06:46:22 +00001428 monotime_tv(&bw->bwstart);
Damien Miller65e42f82010-09-24 22:15:11 +10001429 return;
1430 }
Damien Miller65e42f82010-09-24 22:15:11 +10001431 if (bw->lamt < bw->thresh)
1432 return;
1433
dtucker@openbsd.org@openbsd.org5db6fbf2017-11-25 06:46:22 +00001434 monotime_tv(&bw->bwend);
Damien Miller65e42f82010-09-24 22:15:11 +10001435 timersub(&bw->bwend, &bw->bwstart, &bw->bwend);
1436 if (!timerisset(&bw->bwend))
1437 return;
1438
1439 bw->lamt *= 8;
1440 waitlen = (double)1000000L * bw->lamt / bw->rate;
1441
1442 bw->bwstart.tv_sec = waitlen / 1000000L;
1443 bw->bwstart.tv_usec = waitlen % 1000000L;
1444
1445 if (timercmp(&bw->bwstart, &bw->bwend, >)) {
1446 timersub(&bw->bwstart, &bw->bwend, &bw->bwend);
1447
1448 /* Adjust the wait time */
1449 if (bw->bwend.tv_sec) {
1450 bw->thresh /= 2;
1451 if (bw->thresh < bw->buflen / 4)
1452 bw->thresh = bw->buflen / 4;
1453 } else if (bw->bwend.tv_usec < 10000) {
1454 bw->thresh *= 2;
1455 if (bw->thresh > bw->buflen * 8)
1456 bw->thresh = bw->buflen * 8;
1457 }
1458
1459 TIMEVAL_TO_TIMESPEC(&bw->bwend, &ts);
1460 while (nanosleep(&ts, &rm) == -1) {
1461 if (errno != EINTR)
1462 break;
1463 ts = rm;
1464 }
1465 }
1466
1467 bw->lamt = 0;
dtucker@openbsd.org@openbsd.org5db6fbf2017-11-25 06:46:22 +00001468 monotime_tv(&bw->bwstart);
Damien Miller65e42f82010-09-24 22:15:11 +10001469}
Damien Miller0dac6fb2010-11-20 15:19:38 +11001470
Damien Miller2cd62932010-12-01 11:50:35 +11001471/* Make a template filename for mk[sd]temp() */
1472void
1473mktemp_proto(char *s, size_t len)
1474{
1475 const char *tmpdir;
1476 int r;
1477
1478 if ((tmpdir = getenv("TMPDIR")) != NULL) {
1479 r = snprintf(s, len, "%s/ssh-XXXXXXXXXXXX", tmpdir);
1480 if (r > 0 && (size_t)r < len)
1481 return;
1482 }
1483 r = snprintf(s, len, "/tmp/ssh-XXXXXXXXXXXX");
1484 if (r < 0 || (size_t)r >= len)
1485 fatal("%s: template string too short", __func__);
1486}
1487
Damien Miller0dac6fb2010-11-20 15:19:38 +11001488static const struct {
1489 const char *name;
1490 int value;
1491} ipqos[] = {
djm@openbsd.org51676ec2017-07-23 23:37:02 +00001492 { "none", INT_MAX }, /* can't use 0 here; that's CS0 */
Damien Miller0dac6fb2010-11-20 15:19:38 +11001493 { "af11", IPTOS_DSCP_AF11 },
1494 { "af12", IPTOS_DSCP_AF12 },
1495 { "af13", IPTOS_DSCP_AF13 },
Damien Miller2918e032011-09-22 21:34:35 +10001496 { "af21", IPTOS_DSCP_AF21 },
Damien Miller0dac6fb2010-11-20 15:19:38 +11001497 { "af22", IPTOS_DSCP_AF22 },
1498 { "af23", IPTOS_DSCP_AF23 },
1499 { "af31", IPTOS_DSCP_AF31 },
1500 { "af32", IPTOS_DSCP_AF32 },
1501 { "af33", IPTOS_DSCP_AF33 },
1502 { "af41", IPTOS_DSCP_AF41 },
1503 { "af42", IPTOS_DSCP_AF42 },
1504 { "af43", IPTOS_DSCP_AF43 },
1505 { "cs0", IPTOS_DSCP_CS0 },
1506 { "cs1", IPTOS_DSCP_CS1 },
1507 { "cs2", IPTOS_DSCP_CS2 },
1508 { "cs3", IPTOS_DSCP_CS3 },
1509 { "cs4", IPTOS_DSCP_CS4 },
1510 { "cs5", IPTOS_DSCP_CS5 },
1511 { "cs6", IPTOS_DSCP_CS6 },
1512 { "cs7", IPTOS_DSCP_CS7 },
1513 { "ef", IPTOS_DSCP_EF },
1514 { "lowdelay", IPTOS_LOWDELAY },
1515 { "throughput", IPTOS_THROUGHPUT },
1516 { "reliability", IPTOS_RELIABILITY },
1517 { NULL, -1 }
1518};
1519
1520int
1521parse_ipqos(const char *cp)
1522{
1523 u_int i;
1524 char *ep;
1525 long val;
1526
1527 if (cp == NULL)
1528 return -1;
1529 for (i = 0; ipqos[i].name != NULL; i++) {
1530 if (strcasecmp(cp, ipqos[i].name) == 0)
1531 return ipqos[i].value;
1532 }
1533 /* Try parsing as an integer */
1534 val = strtol(cp, &ep, 0);
1535 if (*cp == '\0' || *ep != '\0' || val < 0 || val > 255)
1536 return -1;
1537 return val;
1538}
1539
Damien Miller91475862011-05-05 14:14:34 +10001540const char *
1541iptos2str(int iptos)
1542{
1543 int i;
1544 static char iptos_str[sizeof "0xff"];
1545
1546 for (i = 0; ipqos[i].name != NULL; i++) {
1547 if (ipqos[i].value == iptos)
1548 return ipqos[i].name;
1549 }
1550 snprintf(iptos_str, sizeof iptos_str, "0x%02x", iptos);
1551 return iptos_str;
1552}
Damien Millere9fc72e2013-10-15 12:14:12 +11001553
1554void
1555lowercase(char *s)
1556{
1557 for (; *s; s++)
1558 *s = tolower((u_char)*s);
1559}
Damien Miller7acefbb2014-07-18 14:11:24 +10001560
1561int
1562unix_listener(const char *path, int backlog, int unlink_first)
1563{
1564 struct sockaddr_un sunaddr;
1565 int saved_errno, sock;
1566
1567 memset(&sunaddr, 0, sizeof(sunaddr));
1568 sunaddr.sun_family = AF_UNIX;
djm@openbsd.org155072f2017-12-08 02:13:02 +00001569 if (strlcpy(sunaddr.sun_path, path,
1570 sizeof(sunaddr.sun_path)) >= sizeof(sunaddr.sun_path)) {
1571 error("%s: path \"%s\" too long for Unix domain socket",
1572 __func__, path);
Damien Miller7acefbb2014-07-18 14:11:24 +10001573 errno = ENAMETOOLONG;
1574 return -1;
1575 }
1576
1577 sock = socket(PF_UNIX, SOCK_STREAM, 0);
1578 if (sock < 0) {
1579 saved_errno = errno;
djm@openbsd.org155072f2017-12-08 02:13:02 +00001580 error("%s: socket: %.100s", __func__, strerror(errno));
Damien Miller7acefbb2014-07-18 14:11:24 +10001581 errno = saved_errno;
1582 return -1;
1583 }
1584 if (unlink_first == 1) {
1585 if (unlink(path) != 0 && errno != ENOENT)
1586 error("unlink(%s): %.100s", path, strerror(errno));
1587 }
1588 if (bind(sock, (struct sockaddr *)&sunaddr, sizeof(sunaddr)) < 0) {
1589 saved_errno = errno;
djm@openbsd.org155072f2017-12-08 02:13:02 +00001590 error("%s: cannot bind to path %s: %s",
1591 __func__, path, strerror(errno));
djm@openbsd.orgfd4eeee2017-12-08 02:14:33 +00001592 close(sock);
Damien Miller7acefbb2014-07-18 14:11:24 +10001593 errno = saved_errno;
1594 return -1;
1595 }
1596 if (listen(sock, backlog) < 0) {
1597 saved_errno = errno;
djm@openbsd.org155072f2017-12-08 02:13:02 +00001598 error("%s: cannot listen on path %s: %s",
1599 __func__, path, strerror(errno));
djm@openbsd.orgfd4eeee2017-12-08 02:14:33 +00001600 close(sock);
1601 unlink(path);
Damien Miller7acefbb2014-07-18 14:11:24 +10001602 errno = saved_errno;
1603 return -1;
1604 }
1605 return sock;
1606}
Damien Miller46878022014-08-30 03:29:19 +10001607
Damien Miller04ee0f82009-11-18 17:48:30 +11001608void
1609sock_set_v6only(int s)
1610{
Damien Millerd86a3ba2015-12-09 09:18:45 +11001611#if defined(IPV6_V6ONLY) && !defined(__OpenBSD__)
Damien Miller04ee0f82009-11-18 17:48:30 +11001612 int on = 1;
1613
1614 debug3("%s: set socket %d IPV6_V6ONLY", __func__, s);
1615 if (setsockopt(s, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof(on)) == -1)
1616 error("setsockopt IPV6_V6ONLY: %s", strerror(errno));
1617#endif
1618}
djm@openbsd.org0ccbd5e2016-04-06 06:42:17 +00001619
1620/*
1621 * Compares two strings that maybe be NULL. Returns non-zero if strings
1622 * are both NULL or are identical, returns zero otherwise.
1623 */
1624static int
1625strcmp_maybe_null(const char *a, const char *b)
1626{
1627 if ((a == NULL && b != NULL) || (a != NULL && b == NULL))
1628 return 0;
1629 if (a != NULL && strcmp(a, b) != 0)
1630 return 0;
1631 return 1;
1632}
1633
1634/*
1635 * Compare two forwards, returning non-zero if they are identical or
1636 * zero otherwise.
1637 */
1638int
1639forward_equals(const struct Forward *a, const struct Forward *b)
1640{
1641 if (strcmp_maybe_null(a->listen_host, b->listen_host) == 0)
1642 return 0;
1643 if (a->listen_port != b->listen_port)
1644 return 0;
1645 if (strcmp_maybe_null(a->listen_path, b->listen_path) == 0)
1646 return 0;
1647 if (strcmp_maybe_null(a->connect_host, b->connect_host) == 0)
1648 return 0;
1649 if (a->connect_port != b->connect_port)
1650 return 0;
1651 if (strcmp_maybe_null(a->connect_path, b->connect_path) == 0)
1652 return 0;
1653 /* allocated_port and handle are not checked */
1654 return 1;
1655}
1656
dtucker@openbsd.org7fc47662016-11-30 00:28:31 +00001657/* returns 1 if process is already daemonized, 0 otherwise */
1658int
1659daemonized(void)
1660{
1661 int fd;
1662
1663 if ((fd = open(_PATH_TTY, O_RDONLY | O_NOCTTY)) >= 0) {
1664 close(fd);
1665 return 0; /* have controlling terminal */
1666 }
1667 if (getppid() != 1)
1668 return 0; /* parent is not init */
1669 if (getsid(0) != getpid())
1670 return 0; /* not session leader */
1671 debug3("already daemonized");
1672 return 1;
1673}
djm@openbsd.orgde4ae072017-08-18 05:36:45 +00001674
1675
1676/*
1677 * Splits 's' into an argument vector. Handles quoted string and basic
1678 * escape characters (\\, \", \'). Caller must free the argument vector
1679 * and its members.
1680 */
1681int
1682argv_split(const char *s, int *argcp, char ***argvp)
1683{
1684 int r = SSH_ERR_INTERNAL_ERROR;
1685 int argc = 0, quote, i, j;
1686 char *arg, **argv = xcalloc(1, sizeof(*argv));
1687
1688 *argvp = NULL;
1689 *argcp = 0;
1690
1691 for (i = 0; s[i] != '\0'; i++) {
1692 /* Skip leading whitespace */
1693 if (s[i] == ' ' || s[i] == '\t')
1694 continue;
1695
1696 /* Start of a token */
1697 quote = 0;
1698 if (s[i] == '\\' &&
1699 (s[i + 1] == '\'' || s[i + 1] == '\"' || s[i + 1] == '\\'))
1700 i++;
1701 else if (s[i] == '\'' || s[i] == '"')
1702 quote = s[i++];
1703
1704 argv = xreallocarray(argv, (argc + 2), sizeof(*argv));
1705 arg = argv[argc++] = xcalloc(1, strlen(s + i) + 1);
1706 argv[argc] = NULL;
1707
1708 /* Copy the token in, removing escapes */
1709 for (j = 0; s[i] != '\0'; i++) {
1710 if (s[i] == '\\') {
1711 if (s[i + 1] == '\'' ||
1712 s[i + 1] == '\"' ||
1713 s[i + 1] == '\\') {
1714 i++; /* Skip '\' */
1715 arg[j++] = s[i];
1716 } else {
1717 /* Unrecognised escape */
1718 arg[j++] = s[i];
1719 }
1720 } else if (quote == 0 && (s[i] == ' ' || s[i] == '\t'))
1721 break; /* done */
1722 else if (quote != 0 && s[i] == quote)
1723 break; /* done */
1724 else
1725 arg[j++] = s[i];
1726 }
1727 if (s[i] == '\0') {
1728 if (quote != 0) {
1729 /* Ran out of string looking for close quote */
1730 r = SSH_ERR_INVALID_FORMAT;
1731 goto out;
1732 }
1733 break;
1734 }
1735 }
1736 /* Success */
1737 *argcp = argc;
1738 *argvp = argv;
1739 argc = 0;
1740 argv = NULL;
1741 r = 0;
1742 out:
1743 if (argc != 0 && argv != NULL) {
1744 for (i = 0; i < argc; i++)
1745 free(argv[i]);
1746 free(argv);
1747 }
1748 return r;
1749}
1750
1751/*
1752 * Reassemble an argument vector into a string, quoting and escaping as
1753 * necessary. Caller must free returned string.
1754 */
1755char *
1756argv_assemble(int argc, char **argv)
1757{
1758 int i, j, ws, r;
1759 char c, *ret;
1760 struct sshbuf *buf, *arg;
1761
1762 if ((buf = sshbuf_new()) == NULL || (arg = sshbuf_new()) == NULL)
1763 fatal("%s: sshbuf_new failed", __func__);
1764
1765 for (i = 0; i < argc; i++) {
1766 ws = 0;
1767 sshbuf_reset(arg);
1768 for (j = 0; argv[i][j] != '\0'; j++) {
1769 r = 0;
1770 c = argv[i][j];
1771 switch (c) {
1772 case ' ':
1773 case '\t':
1774 ws = 1;
1775 r = sshbuf_put_u8(arg, c);
1776 break;
1777 case '\\':
1778 case '\'':
1779 case '"':
1780 if ((r = sshbuf_put_u8(arg, '\\')) != 0)
1781 break;
1782 /* FALLTHROUGH */
1783 default:
1784 r = sshbuf_put_u8(arg, c);
1785 break;
1786 }
1787 if (r != 0)
1788 fatal("%s: sshbuf_put_u8: %s",
1789 __func__, ssh_err(r));
1790 }
1791 if ((i != 0 && (r = sshbuf_put_u8(buf, ' ')) != 0) ||
1792 (ws != 0 && (r = sshbuf_put_u8(buf, '"')) != 0) ||
1793 (r = sshbuf_putb(buf, arg)) != 0 ||
1794 (ws != 0 && (r = sshbuf_put_u8(buf, '"')) != 0))
1795 fatal("%s: buffer error: %s", __func__, ssh_err(r));
1796 }
1797 if ((ret = malloc(sshbuf_len(buf) + 1)) == NULL)
1798 fatal("%s: malloc failed", __func__);
1799 memcpy(ret, sshbuf_ptr(buf), sshbuf_len(buf));
1800 ret[sshbuf_len(buf)] = '\0';
1801 sshbuf_free(buf);
1802 sshbuf_free(arg);
1803 return ret;
1804}
1805
djm@openbsd.orgde4ae072017-08-18 05:36:45 +00001806/* Returns 0 if pid exited cleanly, non-zero otherwise */
1807int
djm@openbsd.orgb074c3c2017-08-18 05:48:04 +00001808exited_cleanly(pid_t pid, const char *tag, const char *cmd, int quiet)
djm@openbsd.orgde4ae072017-08-18 05:36:45 +00001809{
1810 int status;
1811
1812 while (waitpid(pid, &status, 0) == -1) {
1813 if (errno != EINTR) {
1814 error("%s: waitpid: %s", tag, strerror(errno));
1815 return -1;
1816 }
1817 }
1818 if (WIFSIGNALED(status)) {
1819 error("%s %s exited on signal %d", tag, cmd, WTERMSIG(status));
1820 return -1;
1821 } else if (WEXITSTATUS(status) != 0) {
djm@openbsd.orgb074c3c2017-08-18 05:48:04 +00001822 do_log2(quiet ? SYSLOG_LEVEL_DEBUG1 : SYSLOG_LEVEL_INFO,
1823 "%s %s failed, status %d", tag, cmd, WEXITSTATUS(status));
djm@openbsd.orgde4ae072017-08-18 05:36:45 +00001824 return -1;
1825 }
1826 return 0;
1827}
1828
1829/*
1830 * Check a given path for security. This is defined as all components
1831 * of the path to the file must be owned by either the owner of
1832 * of the file or root and no directories must be group or world writable.
1833 *
1834 * XXX Should any specific check be done for sym links ?
1835 *
1836 * Takes a file name, its stat information (preferably from fstat() to
1837 * avoid races), the uid of the expected owner, their home directory and an
1838 * error buffer plus max size as arguments.
1839 *
1840 * Returns 0 on success and -1 on failure
1841 */
1842int
1843safe_path(const char *name, struct stat *stp, const char *pw_dir,
1844 uid_t uid, char *err, size_t errlen)
1845{
1846 char buf[PATH_MAX], homedir[PATH_MAX];
1847 char *cp;
1848 int comparehome = 0;
1849 struct stat st;
1850
1851 if (realpath(name, buf) == NULL) {
1852 snprintf(err, errlen, "realpath %s failed: %s", name,
1853 strerror(errno));
1854 return -1;
1855 }
1856 if (pw_dir != NULL && realpath(pw_dir, homedir) != NULL)
1857 comparehome = 1;
1858
1859 if (!S_ISREG(stp->st_mode)) {
1860 snprintf(err, errlen, "%s is not a regular file", buf);
1861 return -1;
1862 }
1863 if ((!platform_sys_dir_uid(stp->st_uid) && stp->st_uid != uid) ||
1864 (stp->st_mode & 022) != 0) {
1865 snprintf(err, errlen, "bad ownership or modes for file %s",
1866 buf);
1867 return -1;
1868 }
1869
1870 /* for each component of the canonical path, walking upwards */
1871 for (;;) {
1872 if ((cp = dirname(buf)) == NULL) {
1873 snprintf(err, errlen, "dirname() failed");
1874 return -1;
1875 }
1876 strlcpy(buf, cp, sizeof(buf));
1877
1878 if (stat(buf, &st) < 0 ||
1879 (!platform_sys_dir_uid(st.st_uid) && st.st_uid != uid) ||
1880 (st.st_mode & 022) != 0) {
1881 snprintf(err, errlen,
1882 "bad ownership or modes for directory %s", buf);
1883 return -1;
1884 }
1885
1886 /* If are past the homedir then we can stop */
1887 if (comparehome && strcmp(homedir, buf) == 0)
1888 break;
1889
1890 /*
1891 * dirname should always complete with a "/" path,
1892 * but we can be paranoid and check for "." too
1893 */
1894 if ((strcmp("/", buf) == 0) || (strcmp(".", buf) == 0))
1895 break;
1896 }
1897 return 0;
1898}
1899
1900/*
1901 * Version of safe_path() that accepts an open file descriptor to
1902 * avoid races.
1903 *
1904 * Returns 0 on success and -1 on failure
1905 */
1906int
1907safe_path_fd(int fd, const char *file, struct passwd *pw,
1908 char *err, size_t errlen)
1909{
1910 struct stat st;
1911
1912 /* check the open file to avoid races */
1913 if (fstat(fd, &st) < 0) {
1914 snprintf(err, errlen, "cannot stat file %s: %s",
1915 file, strerror(errno));
1916 return -1;
1917 }
1918 return safe_path(file, &st, pw->pw_dir, pw->pw_uid, err, errlen);
1919}
1920
1921/*
1922 * Sets the value of the given variable in the environment. If the variable
1923 * already exists, its value is overridden.
1924 */
1925void
1926child_set_env(char ***envp, u_int *envsizep, const char *name,
1927 const char *value)
1928{
1929 char **env;
1930 u_int envsize;
1931 u_int i, namelen;
1932
1933 if (strchr(name, '=') != NULL) {
1934 error("Invalid environment variable \"%.100s\"", name);
1935 return;
1936 }
1937
1938 /*
1939 * If we're passed an uninitialized list, allocate a single null
1940 * entry before continuing.
1941 */
1942 if (*envp == NULL && *envsizep == 0) {
1943 *envp = xmalloc(sizeof(char *));
1944 *envp[0] = NULL;
1945 *envsizep = 1;
1946 }
1947
1948 /*
1949 * Find the slot where the value should be stored. If the variable
1950 * already exists, we reuse the slot; otherwise we append a new slot
1951 * at the end of the array, expanding if necessary.
1952 */
1953 env = *envp;
1954 namelen = strlen(name);
1955 for (i = 0; env[i]; i++)
1956 if (strncmp(env[i], name, namelen) == 0 && env[i][namelen] == '=')
1957 break;
1958 if (env[i]) {
1959 /* Reuse the slot. */
1960 free(env[i]);
1961 } else {
1962 /* New variable. Expand if necessary. */
1963 envsize = *envsizep;
1964 if (i >= envsize - 1) {
1965 if (envsize >= 1000)
1966 fatal("child_set_env: too many env vars");
1967 envsize += 50;
1968 env = (*envp) = xreallocarray(env, envsize, sizeof(char *));
1969 *envsizep = envsize;
1970 }
1971 /* Need to set the NULL pointer at end of array beyond the new slot. */
1972 env[i + 1] = NULL;
1973 }
1974
1975 /* Allocate space and format the variable in the appropriate slot. */
djm@openbsd.org7c856852018-03-03 03:15:51 +00001976 /* XXX xasprintf */
djm@openbsd.orgde4ae072017-08-18 05:36:45 +00001977 env[i] = xmalloc(strlen(name) + 1 + strlen(value) + 1);
1978 snprintf(env[i], strlen(name) + 1 + strlen(value) + 1, "%s=%s", name, value);
1979}
1980
millert@openbsd.org887669e2017-10-21 23:06:24 +00001981/*
1982 * Check and optionally lowercase a domain name, also removes trailing '.'
1983 * Returns 1 on success and 0 on failure, storing an error message in errstr.
1984 */
1985int
1986valid_domain(char *name, int makelower, const char **errstr)
1987{
1988 size_t i, l = strlen(name);
1989 u_char c, last = '\0';
1990 static char errbuf[256];
1991
1992 if (l == 0) {
1993 strlcpy(errbuf, "empty domain name", sizeof(errbuf));
1994 goto bad;
1995 }
1996 if (!isalpha((u_char)name[0]) && !isdigit((u_char)name[0])) {
1997 snprintf(errbuf, sizeof(errbuf), "domain name \"%.100s\" "
1998 "starts with invalid character", name);
1999 goto bad;
2000 }
2001 for (i = 0; i < l; i++) {
2002 c = tolower((u_char)name[i]);
2003 if (makelower)
2004 name[i] = (char)c;
2005 if (last == '.' && c == '.') {
2006 snprintf(errbuf, sizeof(errbuf), "domain name "
2007 "\"%.100s\" contains consecutive separators", name);
2008 goto bad;
2009 }
2010 if (c != '.' && c != '-' && !isalnum(c) &&
2011 c != '_') /* technically invalid, but common */ {
2012 snprintf(errbuf, sizeof(errbuf), "domain name "
2013 "\"%.100s\" contains invalid characters", name);
2014 goto bad;
2015 }
2016 last = c;
2017 }
2018 if (name[l - 1] == '.')
2019 name[l - 1] = '\0';
2020 if (errstr != NULL)
2021 *errstr = NULL;
2022 return 1;
2023bad:
2024 if (errstr != NULL)
2025 *errstr = errbuf;
2026 return 0;
2027}
dtucker@openbsd.org609d96b2017-12-05 23:59:47 +00002028
djm@openbsd.org5eff5b82018-10-03 06:38:35 +00002029/*
2030 * Verify that a environment variable name (not including initial '$') is
2031 * valid; consisting of one or more alphanumeric or underscore characters only.
2032 * Returns 1 on valid, 0 otherwise.
2033 */
2034int
2035valid_env_name(const char *name)
2036{
2037 const char *cp;
2038
2039 if (name[0] == '\0')
2040 return 0;
2041 for (cp = name; *cp != '\0'; cp++) {
2042 if (!isalnum((u_char)*cp) && *cp != '_')
2043 return 0;
2044 }
2045 return 1;
2046}
2047
dtucker@openbsd.org609d96b2017-12-05 23:59:47 +00002048const char *
2049atoi_err(const char *nptr, int *val)
2050{
2051 const char *errstr = NULL;
2052 long long num;
2053
2054 if (nptr == NULL || *nptr == '\0')
2055 return "missing";
2056 num = strtonum(nptr, 0, INT_MAX, &errstr);
2057 if (errstr == NULL)
2058 *val = (int)num;
2059 return errstr;
2060}
djm@openbsd.orgbf0fbf22018-03-12 00:52:01 +00002061
2062int
2063parse_absolute_time(const char *s, uint64_t *tp)
2064{
2065 struct tm tm;
2066 time_t tt;
2067 char buf[32], *fmt;
2068
2069 *tp = 0;
2070
2071 /*
2072 * POSIX strptime says "The application shall ensure that there
2073 * is white-space or other non-alphanumeric characters between
2074 * any two conversion specifications" so arrange things this way.
2075 */
2076 switch (strlen(s)) {
2077 case 8: /* YYYYMMDD */
2078 fmt = "%Y-%m-%d";
2079 snprintf(buf, sizeof(buf), "%.4s-%.2s-%.2s", s, s + 4, s + 6);
2080 break;
2081 case 12: /* YYYYMMDDHHMM */
2082 fmt = "%Y-%m-%dT%H:%M";
2083 snprintf(buf, sizeof(buf), "%.4s-%.2s-%.2sT%.2s:%.2s",
2084 s, s + 4, s + 6, s + 8, s + 10);
2085 break;
2086 case 14: /* YYYYMMDDHHMMSS */
2087 fmt = "%Y-%m-%dT%H:%M:%S";
2088 snprintf(buf, sizeof(buf), "%.4s-%.2s-%.2sT%.2s:%.2s:%.2s",
2089 s, s + 4, s + 6, s + 8, s + 10, s + 12);
2090 break;
2091 default:
2092 return SSH_ERR_INVALID_FORMAT;
2093 }
2094
2095 memset(&tm, 0, sizeof(tm));
2096 if (strptime(buf, fmt, &tm) == NULL)
2097 return SSH_ERR_INVALID_FORMAT;
2098 if ((tt = mktime(&tm)) < 0)
2099 return SSH_ERR_INVALID_FORMAT;
2100 /* success */
2101 *tp = (uint64_t)tt;
2102 return 0;
2103}
2104
2105void
2106format_absolute_time(uint64_t t, char *buf, size_t len)
2107{
2108 time_t tt = t > INT_MAX ? INT_MAX : t; /* XXX revisit in 2038 :P */
2109 struct tm tm;
2110
2111 localtime_r(&tt, &tm);
2112 strftime(buf, len, "%Y-%m-%dT%H:%M:%S", &tm);
2113}
djm@openbsd.org2a358622018-11-16 03:26:01 +00002114
2115/* check if path is absolute */
2116int
2117path_absolute(const char *path)
2118{
2119 return (*path == '/') ? 1 : 0;
2120}