blob: dd74c8d458748e8902684877574d8afb173adedd [file] [log] [blame]
djm@openbsd.org2a358622018-11-16 03:26:01 +00001/* $OpenBSD: misc.c,v 1.134 2018/11/16 03:26:01 djm 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
41#include <signal.h>
Darren Tucker5d196262006-07-12 22:15:16 +100042#include <stdarg.h>
Damien Millera7a73ee2006-08-05 11:37:59 +100043#include <stdio.h>
Damien Millere7a1e5c2006-08-05 11:34:19 +100044#include <stdlib.h>
Damien Millere3476ed2006-07-24 14:13:33 +100045#include <string.h>
Damien Miller1708cb72011-01-13 12:21:34 +110046#include <time.h>
Damien Millere6b3b612006-07-24 14:01:23 +100047#include <unistd.h>
Darren Tucker5d196262006-07-12 22:15:16 +100048
Damien Miller8ec8c3e2006-07-10 20:35:38 +100049#include <netinet/in.h>
Damien Miller0dac6fb2010-11-20 15:19:38 +110050#include <netinet/in_systm.h>
51#include <netinet/ip.h>
Damien Miller3a4051e2006-03-15 11:19:42 +110052#include <netinet/tcp.h>
naddy@openbsd.org25813332018-10-05 14:26:09 +000053#include <arpa/inet.h>
Damien Miller8ec8c3e2006-07-10 20:35:38 +100054
Damien Millere9fc72e2013-10-15 12:14:12 +110055#include <ctype.h>
Darren Tucker39972492006-07-12 22:22:46 +100056#include <errno.h>
Damien Miller57cf6382006-07-10 21:13:46 +100057#include <fcntl.h>
Darren Tucker4abde772007-12-29 02:43:51 +110058#include <netdb.h>
Damien Miller03e20032006-03-15 11:16:59 +110059#ifdef HAVE_PATHS_H
Damien Millera9263d02006-03-15 11:18:26 +110060# include <paths.h>
Damien Miller9f2abc42006-07-10 20:53:08 +100061#include <pwd.h>
Damien Miller03e20032006-03-15 11:16:59 +110062#endif
Damien Miller3beb8522006-01-02 23:40:10 +110063#ifdef SSH_TUN_OPENBSD
64#include <net/if.h>
65#endif
Damien Miller61c51502000-08-18 14:01:04 +100066
Damien Millerd7834352006-08-05 12:39:39 +100067#include "xmalloc.h"
Kevin Stevesb6e773a2001-02-04 13:20:36 +000068#include "misc.h"
Ben Lindstrom226cfa02001-01-22 05:34:40 +000069#include "log.h"
Darren Tuckerda345532006-07-10 23:04:19 +100070#include "ssh.h"
djm@openbsd.orgde4ae072017-08-18 05:36:45 +000071#include "sshbuf.h"
72#include "ssherr.h"
Damien Miller07949bf2017-08-23 20:13:18 +100073#include "platform.h"
Damien Miller61c51502000-08-18 14:01:04 +100074
Ben Lindstrom4cc240d2001-07-04 04:46:56 +000075/* remove newline at end of string */
Damien Miller61c51502000-08-18 14:01:04 +100076char *
77chop(char *s)
78{
79 char *t = s;
80 while (*t) {
Ben Lindstrom1c37c6a2001-12-06 18:00:18 +000081 if (*t == '\n' || *t == '\r') {
Damien Miller61c51502000-08-18 14:01:04 +100082 *t = '\0';
83 return s;
84 }
85 t++;
86 }
87 return s;
88
89}
90
Ben Lindstrom4cc240d2001-07-04 04:46:56 +000091/* set/unset filedescriptor to non-blocking */
Damien Miller232711f2004-06-15 10:35:30 +100092int
Damien Miller61c51502000-08-18 14:01:04 +100093set_nonblock(int fd)
94{
95 int val;
Ben Lindstromc93e84c2001-05-12 00:08:37 +000096
krw@openbsd.org574def02016-04-02 14:37:42 +000097 val = fcntl(fd, F_GETFL);
Damien Miller61c51502000-08-18 14:01:04 +100098 if (val < 0) {
krw@openbsd.org574def02016-04-02 14:37:42 +000099 error("fcntl(%d, F_GETFL): %s", fd, strerror(errno));
Damien Miller232711f2004-06-15 10:35:30 +1000100 return (-1);
Damien Miller61c51502000-08-18 14:01:04 +1000101 }
Damien Miller69b69aa2000-10-28 14:19:58 +1100102 if (val & O_NONBLOCK) {
Damien Miller232711f2004-06-15 10:35:30 +1000103 debug3("fd %d is O_NONBLOCK", fd);
104 return (0);
Damien Miller69b69aa2000-10-28 14:19:58 +1100105 }
Damien Milleref095ce2003-05-14 13:41:39 +1000106 debug2("fd %d setting O_NONBLOCK", fd);
Damien Miller61c51502000-08-18 14:01:04 +1000107 val |= O_NONBLOCK;
Damien Miller232711f2004-06-15 10:35:30 +1000108 if (fcntl(fd, F_SETFL, val) == -1) {
109 debug("fcntl(%d, F_SETFL, O_NONBLOCK): %s", fd,
110 strerror(errno));
111 return (-1);
112 }
113 return (0);
Damien Miller61c51502000-08-18 14:01:04 +1000114}
115
Damien Miller232711f2004-06-15 10:35:30 +1000116int
Ben Lindstromc93e84c2001-05-12 00:08:37 +0000117unset_nonblock(int fd)
118{
119 int val;
120
krw@openbsd.org574def02016-04-02 14:37:42 +0000121 val = fcntl(fd, F_GETFL);
Ben Lindstromc93e84c2001-05-12 00:08:37 +0000122 if (val < 0) {
krw@openbsd.org574def02016-04-02 14:37:42 +0000123 error("fcntl(%d, F_GETFL): %s", fd, strerror(errno));
Damien Miller232711f2004-06-15 10:35:30 +1000124 return (-1);
Ben Lindstromc93e84c2001-05-12 00:08:37 +0000125 }
126 if (!(val & O_NONBLOCK)) {
Damien Miller232711f2004-06-15 10:35:30 +1000127 debug3("fd %d is not O_NONBLOCK", fd);
128 return (0);
Ben Lindstromc93e84c2001-05-12 00:08:37 +0000129 }
Ben Lindstrom352b1c22001-06-21 03:04:37 +0000130 debug("fd %d clearing O_NONBLOCK", fd);
Ben Lindstromc93e84c2001-05-12 00:08:37 +0000131 val &= ~O_NONBLOCK;
Damien Miller232711f2004-06-15 10:35:30 +1000132 if (fcntl(fd, F_SETFL, val) == -1) {
133 debug("fcntl(%d, F_SETFL, ~O_NONBLOCK): %s",
Ben Lindstrom84fcb312002-03-05 01:48:09 +0000134 fd, strerror(errno));
Damien Miller232711f2004-06-15 10:35:30 +1000135 return (-1);
136 }
137 return (0);
Ben Lindstromc93e84c2001-05-12 00:08:37 +0000138}
139
Darren Tucker4abde772007-12-29 02:43:51 +1100140const char *
141ssh_gai_strerror(int gaierr)
142{
Damien Miller7313fc92013-07-18 16:13:19 +1000143 if (gaierr == EAI_SYSTEM && errno != 0)
Darren Tucker912428c2008-01-01 20:33:35 +1100144 return strerror(errno);
145 return gai_strerror(gaierr);
Darren Tucker4abde772007-12-29 02:43:51 +1100146}
147
Damien Miller398e1cf2002-02-05 11:52:13 +1100148/* disable nagle on socket */
149void
150set_nodelay(int fd)
151{
Ben Lindstrome86de512002-03-05 01:28:14 +0000152 int opt;
153 socklen_t optlen;
Damien Miller398e1cf2002-02-05 11:52:13 +1100154
Ben Lindstrom1ebd7a52002-02-26 18:12:51 +0000155 optlen = sizeof opt;
156 if (getsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &opt, &optlen) == -1) {
Darren Tucker6db8f932003-11-03 20:07:14 +1100157 debug("getsockopt TCP_NODELAY: %.100s", strerror(errno));
Ben Lindstrom1ebd7a52002-02-26 18:12:51 +0000158 return;
159 }
160 if (opt == 1) {
161 debug2("fd %d is TCP_NODELAY", fd);
162 return;
163 }
164 opt = 1;
Ben Lindstrom1d568f92002-12-23 02:44:36 +0000165 debug2("fd %d setting TCP_NODELAY", fd);
Ben Lindstrom1ebd7a52002-02-26 18:12:51 +0000166 if (setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &opt, sizeof opt) == -1)
Damien Miller398e1cf2002-02-05 11:52:13 +1100167 error("setsockopt TCP_NODELAY: %.100s", strerror(errno));
168}
169
djm@openbsd.orgacf559e2017-10-25 00:15:35 +0000170/* Allow local port reuse in TIME_WAIT */
171int
172set_reuseaddr(int fd)
173{
174 int on = 1;
175
176 if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)) == -1) {
177 error("setsockopt SO_REUSEADDR fd %d: %s", fd, strerror(errno));
178 return -1;
179 }
180 return 0;
181}
182
djm@openbsd.org35eb33f2017-10-25 00:17:08 +0000183/* Get/set routing domain */
184char *
185get_rdomain(int fd)
186{
Damien Miller43c29bb2017-10-25 13:10:59 +1100187#if defined(HAVE_SYS_GET_RDOMAIN)
188 return sys_get_rdomain(fd);
189#elif defined(__OpenBSD__)
djm@openbsd.org35eb33f2017-10-25 00:17:08 +0000190 int rtable;
191 char *ret;
192 socklen_t len = sizeof(rtable);
193
194 if (getsockopt(fd, SOL_SOCKET, SO_RTABLE, &rtable, &len) == -1) {
195 error("Failed to get routing domain for fd %d: %s",
196 fd, strerror(errno));
197 return NULL;
198 }
199 xasprintf(&ret, "%d", rtable);
200 return ret;
Damien Miller43c29bb2017-10-25 13:10:59 +1100201#else /* defined(__OpenBSD__) */
202 return NULL;
203#endif
djm@openbsd.org35eb33f2017-10-25 00:17:08 +0000204}
205
djm@openbsd.orgacf559e2017-10-25 00:15:35 +0000206int
207set_rdomain(int fd, const char *name)
208{
Damien Miller43c29bb2017-10-25 13:10:59 +1100209#if defined(HAVE_SYS_SET_RDOMAIN)
210 return sys_set_rdomain(fd, name);
211#elif defined(__OpenBSD__)
djm@openbsd.orgacf559e2017-10-25 00:15:35 +0000212 int rtable;
213 const char *errstr;
214
215 if (name == NULL)
216 return 0; /* default table */
217
218 rtable = (int)strtonum(name, 0, 255, &errstr);
219 if (errstr != NULL) {
220 /* Shouldn't happen */
221 error("Invalid routing domain \"%s\": %s", name, errstr);
222 return -1;
223 }
224 if (setsockopt(fd, SOL_SOCKET, SO_RTABLE,
225 &rtable, sizeof(rtable)) == -1) {
226 error("Failed to set routing domain %d on fd %d: %s",
227 rtable, fd, strerror(errno));
228 return -1;
229 }
230 return 0;
Damien Miller43c29bb2017-10-25 13:10:59 +1100231#else /* defined(__OpenBSD__) */
232 error("Setting routing domain is not supported on this platform");
233 return -1;
234#endif
djm@openbsd.orgacf559e2017-10-25 00:15:35 +0000235}
236
Damien Miller61c51502000-08-18 14:01:04 +1000237/* Characters considered whitespace in strsep calls. */
238#define WHITESPACE " \t\r\n"
Damien Miller306d1182006-03-15 12:05:59 +1100239#define QUOTE "\""
Damien Miller61c51502000-08-18 14:01:04 +1000240
Ben Lindstrom4cc240d2001-07-04 04:46:56 +0000241/* return next token in configuration line */
djm@openbsd.org7082bb52018-06-09 03:01:12 +0000242static char *
243strdelim_internal(char **s, int split_equals)
Damien Miller61c51502000-08-18 14:01:04 +1000244{
djm@openbsd.orgc7c458e2018-03-07 23:53:08 +0000245 char *old;
Damien Miller61c51502000-08-18 14:01:04 +1000246 int wspace = 0;
247
248 if (*s == NULL)
249 return NULL;
250
251 old = *s;
252
djm@openbsd.org7082bb52018-06-09 03:01:12 +0000253 *s = strpbrk(*s,
254 split_equals ? WHITESPACE QUOTE "=" : WHITESPACE QUOTE);
Damien Miller61c51502000-08-18 14:01:04 +1000255 if (*s == NULL)
256 return (old);
257
Damien Miller306d1182006-03-15 12:05:59 +1100258 if (*s[0] == '\"') {
259 memmove(*s, *s + 1, strlen(*s)); /* move nul too */
260 /* Find matching quote */
djm@openbsd.orgc7c458e2018-03-07 23:53:08 +0000261 if ((*s = strpbrk(*s, QUOTE)) == NULL) {
262 return (NULL); /* no matching quote */
263 } else {
264 *s[0] = '\0';
265 *s += strspn(*s + 1, WHITESPACE) + 1;
266 return (old);
Damien Miller306d1182006-03-15 12:05:59 +1100267 }
268 }
269
Damien Miller61c51502000-08-18 14:01:04 +1000270 /* Allow only one '=' to be skipped */
djm@openbsd.org7082bb52018-06-09 03:01:12 +0000271 if (split_equals && *s[0] == '=')
Damien Miller61c51502000-08-18 14:01:04 +1000272 wspace = 1;
273 *s[0] = '\0';
274
Damien Miller306d1182006-03-15 12:05:59 +1100275 /* Skip any extra whitespace after first token */
Damien Miller61c51502000-08-18 14:01:04 +1000276 *s += strspn(*s + 1, WHITESPACE) + 1;
djm@openbsd.org7082bb52018-06-09 03:01:12 +0000277 if (split_equals && *s[0] == '=' && !wspace)
Damien Miller61c51502000-08-18 14:01:04 +1000278 *s += strspn(*s + 1, WHITESPACE) + 1;
279
280 return (old);
281}
Kevin Stevesb6e773a2001-02-04 13:20:36 +0000282
djm@openbsd.org7082bb52018-06-09 03:01:12 +0000283/*
284 * Return next token in configuration line; splts on whitespace or a
285 * single '=' character.
286 */
287char *
288strdelim(char **s)
289{
290 return strdelim_internal(s, 1);
291}
292
293/*
294 * Return next token in configuration line; splts on whitespace only.
295 */
296char *
297strdelimw(char **s)
298{
299 return strdelim_internal(s, 0);
300}
301
Ben Lindstrom086cf212001-03-05 05:56:40 +0000302struct passwd *
303pwcopy(struct passwd *pw)
304{
Damien Miller07d86be2006-03-26 14:19:21 +1100305 struct passwd *copy = xcalloc(1, sizeof(*copy));
Ben Lindstrom40304422001-03-05 06:22:01 +0000306
Ben Lindstrom086cf212001-03-05 05:56:40 +0000307 copy->pw_name = xstrdup(pw->pw_name);
308 copy->pw_passwd = xstrdup(pw->pw_passwd);
Damien Miller6332da22013-04-23 14:25:52 +1000309#ifdef HAVE_STRUCT_PASSWD_PW_GECOS
Ben Lindstrom40304422001-03-05 06:22:01 +0000310 copy->pw_gecos = xstrdup(pw->pw_gecos);
Damien Miller6332da22013-04-23 14:25:52 +1000311#endif
Ben Lindstrom086cf212001-03-05 05:56:40 +0000312 copy->pw_uid = pw->pw_uid;
313 copy->pw_gid = pw->pw_gid;
Damien Miller6332da22013-04-23 14:25:52 +1000314#ifdef HAVE_STRUCT_PASSWD_PW_EXPIRE
Ben Lindstrom3af4d462001-06-21 03:11:27 +0000315 copy->pw_expire = pw->pw_expire;
Kevin Steves82456952001-06-22 21:14:18 +0000316#endif
Damien Miller6332da22013-04-23 14:25:52 +1000317#ifdef HAVE_STRUCT_PASSWD_PW_CHANGE
Ben Lindstrom3af4d462001-06-21 03:11:27 +0000318 copy->pw_change = pw->pw_change;
Kevin Steves82456952001-06-22 21:14:18 +0000319#endif
Damien Miller6332da22013-04-23 14:25:52 +1000320#ifdef HAVE_STRUCT_PASSWD_PW_CLASS
Ben Lindstrom086cf212001-03-05 05:56:40 +0000321 copy->pw_class = xstrdup(pw->pw_class);
Ben Lindstrom0f68db42001-03-05 07:57:09 +0000322#endif
Ben Lindstrom086cf212001-03-05 05:56:40 +0000323 copy->pw_dir = xstrdup(pw->pw_dir);
324 copy->pw_shell = xstrdup(pw->pw_shell);
325 return copy;
326}
327
Ben Lindstrom4cc240d2001-07-04 04:46:56 +0000328/*
329 * Convert ASCII string to TCP/IP port number.
Damien Miller3dc71ad2009-01-28 16:31:22 +1100330 * Port must be >=0 and <=65535.
331 * Return -1 if invalid.
Ben Lindstrom4cc240d2001-07-04 04:46:56 +0000332 */
333int
334a2port(const char *s)
Ben Lindstrom19066a12001-04-12 23:39:26 +0000335{
naddy@openbsd.org25813332018-10-05 14:26:09 +0000336 struct servent *se;
Damien Miller3dc71ad2009-01-28 16:31:22 +1100337 long long port;
338 const char *errstr;
Ben Lindstrom19066a12001-04-12 23:39:26 +0000339
Damien Miller3dc71ad2009-01-28 16:31:22 +1100340 port = strtonum(s, 0, 65535, &errstr);
naddy@openbsd.org25813332018-10-05 14:26:09 +0000341 if (errstr == NULL)
342 return (int)port;
343 if ((se = getservbyname(s, "tcp")) != NULL)
344 return ntohs(se->s_port);
345 return -1;
Ben Lindstrom19066a12001-04-12 23:39:26 +0000346}
347
Damien Millerd27b9472005-12-13 19:29:02 +1100348int
349a2tun(const char *s, int *remote)
350{
351 const char *errstr = NULL;
352 char *sp, *ep;
353 int tun;
354
355 if (remote != NULL) {
Damien Miller7b58e802005-12-13 19:33:19 +1100356 *remote = SSH_TUNID_ANY;
Damien Millerd27b9472005-12-13 19:29:02 +1100357 sp = xstrdup(s);
358 if ((ep = strchr(sp, ':')) == NULL) {
Darren Tuckera627d422013-06-02 07:31:17 +1000359 free(sp);
Damien Millerd27b9472005-12-13 19:29:02 +1100360 return (a2tun(s, NULL));
361 }
362 ep[0] = '\0'; ep++;
363 *remote = a2tun(ep, NULL);
364 tun = a2tun(sp, NULL);
Darren Tuckera627d422013-06-02 07:31:17 +1000365 free(sp);
Damien Miller7b58e802005-12-13 19:33:19 +1100366 return (*remote == SSH_TUNID_ERR ? *remote : tun);
Damien Millerd27b9472005-12-13 19:29:02 +1100367 }
368
369 if (strcasecmp(s, "any") == 0)
Damien Miller7b58e802005-12-13 19:33:19 +1100370 return (SSH_TUNID_ANY);
Damien Millerd27b9472005-12-13 19:29:02 +1100371
Damien Miller7b58e802005-12-13 19:33:19 +1100372 tun = strtonum(s, 0, SSH_TUNID_MAX, &errstr);
373 if (errstr != NULL)
374 return (SSH_TUNID_ERR);
Damien Millerd27b9472005-12-13 19:29:02 +1100375
376 return (tun);
377}
378
Ben Lindstrom1bda4c82001-06-05 19:59:08 +0000379#define SECONDS 1
380#define MINUTES (SECONDS * 60)
381#define HOURS (MINUTES * 60)
382#define DAYS (HOURS * 24)
383#define WEEKS (DAYS * 7)
384
Ben Lindstrom4cc240d2001-07-04 04:46:56 +0000385/*
386 * Convert a time string into seconds; format is
387 * a sequence of:
388 * time[qualifier]
389 *
390 * Valid time qualifiers are:
391 * <none> seconds
392 * s|S seconds
393 * m|M minutes
394 * h|H hours
395 * d|D days
396 * w|W weeks
397 *
398 * Examples:
399 * 90m 90 minutes
400 * 1h30m 90 minutes
401 * 2d 2 days
402 * 1w 1 week
403 *
404 * Return -1 if time string is invalid.
405 */
406long
407convtime(const char *s)
Ben Lindstrom1bda4c82001-06-05 19:59:08 +0000408{
dtucker@openbsd.orgf5746b42017-03-14 00:25:03 +0000409 long total, secs, multiplier = 1;
Ben Lindstrom1bda4c82001-06-05 19:59:08 +0000410 const char *p;
411 char *endp;
412
413 errno = 0;
414 total = 0;
415 p = s;
416
417 if (p == NULL || *p == '\0')
418 return -1;
419
420 while (*p) {
421 secs = strtol(p, &endp, 10);
422 if (p == endp ||
423 (errno == ERANGE && (secs == LONG_MIN || secs == LONG_MAX)) ||
424 secs < 0)
425 return -1;
426
427 switch (*endp++) {
428 case '\0':
429 endp--;
Damien Miller69b72032006-03-26 14:02:35 +1100430 break;
Ben Lindstrom1bda4c82001-06-05 19:59:08 +0000431 case 's':
432 case 'S':
433 break;
434 case 'm':
435 case 'M':
dtucker@openbsd.orgf5746b42017-03-14 00:25:03 +0000436 multiplier = MINUTES;
Ben Lindstrom1bda4c82001-06-05 19:59:08 +0000437 break;
438 case 'h':
439 case 'H':
dtucker@openbsd.orgf5746b42017-03-14 00:25:03 +0000440 multiplier = HOURS;
Ben Lindstrom1bda4c82001-06-05 19:59:08 +0000441 break;
442 case 'd':
443 case 'D':
dtucker@openbsd.orgf5746b42017-03-14 00:25:03 +0000444 multiplier = DAYS;
Ben Lindstrom1bda4c82001-06-05 19:59:08 +0000445 break;
446 case 'w':
447 case 'W':
dtucker@openbsd.orgf5746b42017-03-14 00:25:03 +0000448 multiplier = WEEKS;
Ben Lindstrom1bda4c82001-06-05 19:59:08 +0000449 break;
450 default:
451 return -1;
452 }
dtucker@openbsd.orgc6774d22017-03-14 00:55:37 +0000453 if (secs >= LONG_MAX / multiplier)
dtucker@openbsd.orgf5746b42017-03-14 00:25:03 +0000454 return -1;
455 secs *= multiplier;
dtucker@openbsd.orgc6774d22017-03-14 00:55:37 +0000456 if (total >= LONG_MAX - secs)
dtucker@openbsd.orgf5746b42017-03-14 00:25:03 +0000457 return -1;
Ben Lindstrom1bda4c82001-06-05 19:59:08 +0000458 total += secs;
459 if (total < 0)
460 return -1;
461 p = endp;
462 }
463
464 return total;
465}
466
Damien Millerf91ee4c2005-03-01 21:24:33 +1100467/*
Darren Tuckerda345532006-07-10 23:04:19 +1000468 * Returns a standardized host+port identifier string.
469 * Caller must free returned string.
470 */
471char *
472put_host_port(const char *host, u_short port)
473{
474 char *hoststr;
475
476 if (port == 0 || port == SSH_DEFAULT_PORT)
477 return(xstrdup(host));
478 if (asprintf(&hoststr, "[%s]:%d", host, (int)port) < 0)
479 fatal("put_host_port: asprintf: %s", strerror(errno));
480 debug3("put_host_port: %s", hoststr);
481 return hoststr;
482}
483
484/*
Damien Millerf91ee4c2005-03-01 21:24:33 +1100485 * Search for next delimiter between hostnames/addresses and ports.
486 * Argument may be modified (for termination).
487 * Returns *cp if parsing succeeds.
millert@openbsd.org887669e2017-10-21 23:06:24 +0000488 * *cp is set to the start of the next field, if one was found.
489 * The delimiter char, if present, is stored in delim.
Damien Millerf91ee4c2005-03-01 21:24:33 +1100490 * If this is the last field, *cp is set to NULL.
491 */
millert@openbsd.org887669e2017-10-21 23:06:24 +0000492static char *
493hpdelim2(char **cp, char *delim)
Damien Millerf91ee4c2005-03-01 21:24:33 +1100494{
495 char *s, *old;
496
497 if (cp == NULL || *cp == NULL)
498 return NULL;
499
500 old = s = *cp;
501 if (*s == '[') {
502 if ((s = strchr(s, ']')) == NULL)
503 return NULL;
504 else
505 s++;
506 } else if ((s = strpbrk(s, ":/")) == NULL)
507 s = *cp + strlen(*cp); /* skip to end (see first case below) */
508
509 switch (*s) {
510 case '\0':
511 *cp = NULL; /* no more fields*/
512 break;
Darren Tucker47eede72005-03-14 23:08:12 +1100513
Damien Millerf91ee4c2005-03-01 21:24:33 +1100514 case ':':
515 case '/':
millert@openbsd.org887669e2017-10-21 23:06:24 +0000516 if (delim != NULL)
517 *delim = *s;
Damien Millerf91ee4c2005-03-01 21:24:33 +1100518 *s = '\0'; /* terminate */
519 *cp = s + 1;
520 break;
Darren Tucker47eede72005-03-14 23:08:12 +1100521
Damien Millerf91ee4c2005-03-01 21:24:33 +1100522 default:
523 return NULL;
524 }
525
526 return old;
527}
528
Ben Lindstrom4529b702001-05-03 23:39:53 +0000529char *
millert@openbsd.org887669e2017-10-21 23:06:24 +0000530hpdelim(char **cp)
531{
532 return hpdelim2(cp, NULL);
533}
534
535char *
Ben Lindstrom4529b702001-05-03 23:39:53 +0000536cleanhostname(char *host)
537{
538 if (*host == '[' && host[strlen(host) - 1] == ']') {
539 host[strlen(host) - 1] = '\0';
540 return (host + 1);
541 } else
542 return host;
543}
544
545char *
546colon(char *cp)
547{
548 int flag = 0;
549
550 if (*cp == ':') /* Leading colon is part of file name. */
Damien Miller2e774462010-06-26 09:30:47 +1000551 return NULL;
Ben Lindstrom4529b702001-05-03 23:39:53 +0000552 if (*cp == '[')
553 flag = 1;
554
555 for (; *cp; ++cp) {
556 if (*cp == '@' && *(cp+1) == '[')
557 flag = 1;
558 if (*cp == ']' && *(cp+1) == ':' && flag)
559 return (cp+1);
560 if (*cp == ':' && !flag)
561 return (cp);
562 if (*cp == '/')
Damien Miller2e774462010-06-26 09:30:47 +1000563 return NULL;
Ben Lindstrom4529b702001-05-03 23:39:53 +0000564 }
Damien Miller2e774462010-06-26 09:30:47 +1000565 return NULL;
Ben Lindstrom4529b702001-05-03 23:39:53 +0000566}
567
djm@openbsd.orged877ef2016-07-15 00:24:30 +0000568/*
millert@openbsd.org887669e2017-10-21 23:06:24 +0000569 * Parse a [user@]host:[path] string.
570 * Caller must free returned user, host and path.
571 * Any of the pointer return arguments may be NULL (useful for syntax checking).
572 * If user was not specified then *userp will be set to NULL.
573 * If host was not specified then *hostp will be set to NULL.
574 * If path was not specified then *pathp will be set to ".".
575 * Returns 0 on success, -1 on failure.
576 */
577int
578parse_user_host_path(const char *s, char **userp, char **hostp, char **pathp)
579{
580 char *user = NULL, *host = NULL, *path = NULL;
581 char *sdup, *tmp;
582 int ret = -1;
583
584 if (userp != NULL)
585 *userp = NULL;
586 if (hostp != NULL)
587 *hostp = NULL;
588 if (pathp != NULL)
589 *pathp = NULL;
590
millert@openbsd.orgb9903ee2017-10-24 19:41:45 +0000591 sdup = xstrdup(s);
millert@openbsd.org887669e2017-10-21 23:06:24 +0000592
593 /* Check for remote syntax: [user@]host:[path] */
594 if ((tmp = colon(sdup)) == NULL)
595 goto out;
596
597 /* Extract optional path */
598 *tmp++ = '\0';
599 if (*tmp == '\0')
600 tmp = ".";
601 path = xstrdup(tmp);
602
603 /* Extract optional user and mandatory host */
604 tmp = strrchr(sdup, '@');
605 if (tmp != NULL) {
606 *tmp++ = '\0';
607 host = xstrdup(cleanhostname(tmp));
608 if (*sdup != '\0')
609 user = xstrdup(sdup);
610 } else {
611 host = xstrdup(cleanhostname(sdup));
612 user = NULL;
613 }
614
615 /* Success */
616 if (userp != NULL) {
617 *userp = user;
618 user = NULL;
619 }
620 if (hostp != NULL) {
621 *hostp = host;
622 host = NULL;
millert@openbsd.orgb9903ee2017-10-24 19:41:45 +0000623 }
millert@openbsd.org887669e2017-10-21 23:06:24 +0000624 if (pathp != NULL) {
625 *pathp = path;
626 path = NULL;
millert@openbsd.orgb9903ee2017-10-24 19:41:45 +0000627 }
millert@openbsd.org887669e2017-10-21 23:06:24 +0000628 ret = 0;
629out:
630 free(sdup);
631 free(user);
632 free(host);
633 free(path);
634 return ret;
635}
636
637/*
djm@openbsd.orged877ef2016-07-15 00:24:30 +0000638 * Parse a [user@]host[:port] string.
639 * Caller must free returned user and host.
640 * Any of the pointer return arguments may be NULL (useful for syntax checking).
641 * If user was not specified then *userp will be set to NULL.
642 * If port was not specified then *portp will be -1.
643 * Returns 0 on success, -1 on failure.
644 */
645int
646parse_user_host_port(const char *s, char **userp, char **hostp, int *portp)
647{
648 char *sdup, *cp, *tmp;
649 char *user = NULL, *host = NULL;
650 int port = -1, ret = -1;
651
652 if (userp != NULL)
653 *userp = NULL;
654 if (hostp != NULL)
655 *hostp = NULL;
656 if (portp != NULL)
657 *portp = -1;
658
659 if ((sdup = tmp = strdup(s)) == NULL)
660 return -1;
661 /* Extract optional username */
millert@openbsd.org887669e2017-10-21 23:06:24 +0000662 if ((cp = strrchr(tmp, '@')) != NULL) {
djm@openbsd.orged877ef2016-07-15 00:24:30 +0000663 *cp = '\0';
664 if (*tmp == '\0')
665 goto out;
666 if ((user = strdup(tmp)) == NULL)
667 goto out;
668 tmp = cp + 1;
669 }
670 /* Extract mandatory hostname */
671 if ((cp = hpdelim(&tmp)) == NULL || *cp == '\0')
672 goto out;
673 host = xstrdup(cleanhostname(cp));
674 /* Convert and verify optional port */
675 if (tmp != NULL && *tmp != '\0') {
676 if ((port = a2port(tmp)) <= 0)
677 goto out;
678 }
679 /* Success */
680 if (userp != NULL) {
681 *userp = user;
682 user = NULL;
683 }
684 if (hostp != NULL) {
685 *hostp = host;
686 host = NULL;
687 }
688 if (portp != NULL)
689 *portp = port;
690 ret = 0;
691 out:
692 free(sdup);
693 free(user);
694 free(host);
695 return ret;
696}
697
millert@openbsd.org887669e2017-10-21 23:06:24 +0000698/*
699 * Converts a two-byte hex string to decimal.
700 * Returns the decimal value or -1 for invalid input.
701 */
702static int
703hexchar(const char *s)
704{
705 unsigned char result[2];
706 int i;
707
708 for (i = 0; i < 2; i++) {
709 if (s[i] >= '0' && s[i] <= '9')
710 result[i] = (unsigned char)(s[i] - '0');
711 else if (s[i] >= 'a' && s[i] <= 'f')
712 result[i] = (unsigned char)(s[i] - 'a') + 10;
713 else if (s[i] >= 'A' && s[i] <= 'F')
714 result[i] = (unsigned char)(s[i] - 'A') + 10;
715 else
716 return -1;
717 }
718 return (result[0] << 4) | result[1];
719}
720
721/*
722 * Decode an url-encoded string.
723 * Returns a newly allocated string on success or NULL on failure.
724 */
725static char *
726urldecode(const char *src)
727{
728 char *ret, *dst;
729 int ch;
730
731 ret = xmalloc(strlen(src) + 1);
732 for (dst = ret; *src != '\0'; src++) {
733 switch (*src) {
734 case '+':
735 *dst++ = ' ';
736 break;
737 case '%':
738 if (!isxdigit((unsigned char)src[1]) ||
739 !isxdigit((unsigned char)src[2]) ||
740 (ch = hexchar(src + 1)) == -1) {
741 free(ret);
742 return NULL;
743 }
744 *dst++ = ch;
745 src += 2;
746 break;
747 default:
748 *dst++ = *src;
749 break;
750 }
751 }
752 *dst = '\0';
753
754 return ret;
755}
756
757/*
758 * Parse an (scp|ssh|sftp)://[user@]host[:port][/path] URI.
759 * See https://tools.ietf.org/html/draft-ietf-secsh-scp-sftp-ssh-uri-04
760 * Either user or path may be url-encoded (but not host or port).
761 * Caller must free returned user, host and path.
762 * Any of the pointer return arguments may be NULL (useful for syntax checking)
763 * but the scheme must always be specified.
764 * If user was not specified then *userp will be set to NULL.
765 * If port was not specified then *portp will be -1.
766 * If path was not specified then *pathp will be set to NULL.
767 * Returns 0 on success, 1 if non-uri/wrong scheme, -1 on error/invalid uri.
768 */
769int
770parse_uri(const char *scheme, const char *uri, char **userp, char **hostp,
771 int *portp, char **pathp)
772{
773 char *uridup, *cp, *tmp, ch;
774 char *user = NULL, *host = NULL, *path = NULL;
775 int port = -1, ret = -1;
776 size_t len;
777
778 len = strlen(scheme);
779 if (strncmp(uri, scheme, len) != 0 || strncmp(uri + len, "://", 3) != 0)
780 return 1;
781 uri += len + 3;
782
783 if (userp != NULL)
784 *userp = NULL;
785 if (hostp != NULL)
786 *hostp = NULL;
787 if (portp != NULL)
788 *portp = -1;
789 if (pathp != NULL)
790 *pathp = NULL;
791
792 uridup = tmp = xstrdup(uri);
793
794 /* Extract optional ssh-info (username + connection params) */
795 if ((cp = strchr(tmp, '@')) != NULL) {
796 char *delim;
797
798 *cp = '\0';
799 /* Extract username and connection params */
800 if ((delim = strchr(tmp, ';')) != NULL) {
801 /* Just ignore connection params for now */
802 *delim = '\0';
803 }
804 if (*tmp == '\0') {
805 /* Empty username */
806 goto out;
807 }
808 if ((user = urldecode(tmp)) == NULL)
809 goto out;
810 tmp = cp + 1;
811 }
812
813 /* Extract mandatory hostname */
814 if ((cp = hpdelim2(&tmp, &ch)) == NULL || *cp == '\0')
815 goto out;
816 host = xstrdup(cleanhostname(cp));
817 if (!valid_domain(host, 0, NULL))
818 goto out;
819
820 if (tmp != NULL && *tmp != '\0') {
821 if (ch == ':') {
822 /* Convert and verify port. */
823 if ((cp = strchr(tmp, '/')) != NULL)
824 *cp = '\0';
825 if ((port = a2port(tmp)) <= 0)
826 goto out;
827 tmp = cp ? cp + 1 : NULL;
828 }
829 if (tmp != NULL && *tmp != '\0') {
830 /* Extract optional path */
831 if ((path = urldecode(tmp)) == NULL)
832 goto out;
833 }
834 }
835
836 /* Success */
837 if (userp != NULL) {
838 *userp = user;
839 user = NULL;
840 }
841 if (hostp != NULL) {
842 *hostp = host;
843 host = NULL;
844 }
845 if (portp != NULL)
846 *portp = port;
847 if (pathp != NULL) {
848 *pathp = path;
849 path = NULL;
850 }
851 ret = 0;
852 out:
853 free(uridup);
854 free(user);
855 free(host);
856 free(path);
857 return ret;
858}
859
Ben Lindstrom4cc240d2001-07-04 04:46:56 +0000860/* function to assist building execv() arguments */
Ben Lindstrom387c4722001-05-08 20:27:25 +0000861void
862addargs(arglist *args, char *fmt, ...)
863{
864 va_list ap;
Damien Miller3eec6b72006-01-31 21:49:27 +1100865 char *cp;
Darren Tuckerc7a6fc42004-08-13 21:18:00 +1000866 u_int nalloc;
Damien Miller3eec6b72006-01-31 21:49:27 +1100867 int r;
Ben Lindstrom387c4722001-05-08 20:27:25 +0000868
869 va_start(ap, fmt);
Damien Miller3eec6b72006-01-31 21:49:27 +1100870 r = vasprintf(&cp, fmt, ap);
Ben Lindstrom387c4722001-05-08 20:27:25 +0000871 va_end(ap);
Damien Miller3eec6b72006-01-31 21:49:27 +1100872 if (r == -1)
873 fatal("addargs: argument too long");
Ben Lindstrom387c4722001-05-08 20:27:25 +0000874
Darren Tuckerfb16b242003-09-22 21:04:23 +1000875 nalloc = args->nalloc;
Ben Lindstrom387c4722001-05-08 20:27:25 +0000876 if (args->list == NULL) {
Darren Tuckerfb16b242003-09-22 21:04:23 +1000877 nalloc = 32;
Ben Lindstrom387c4722001-05-08 20:27:25 +0000878 args->num = 0;
Darren Tuckerfb16b242003-09-22 21:04:23 +1000879 } else if (args->num+2 >= nalloc)
880 nalloc *= 2;
Ben Lindstrom387c4722001-05-08 20:27:25 +0000881
deraadt@openbsd.org9e509d42017-05-31 09:15:42 +0000882 args->list = xrecallocarray(args->list, args->nalloc, nalloc, sizeof(char *));
Darren Tuckerfb16b242003-09-22 21:04:23 +1000883 args->nalloc = nalloc;
Damien Miller3eec6b72006-01-31 21:49:27 +1100884 args->list[args->num++] = cp;
Ben Lindstrom387c4722001-05-08 20:27:25 +0000885 args->list[args->num] = NULL;
886}
Darren Tucker22cc7412004-12-06 22:47:41 +1100887
Damien Miller3eec6b72006-01-31 21:49:27 +1100888void
889replacearg(arglist *args, u_int which, char *fmt, ...)
890{
891 va_list ap;
892 char *cp;
893 int r;
894
895 va_start(ap, fmt);
896 r = vasprintf(&cp, fmt, ap);
897 va_end(ap);
898 if (r == -1)
899 fatal("replacearg: argument too long");
900
901 if (which >= args->num)
902 fatal("replacearg: tried to replace invalid arg %d >= %d",
903 which, args->num);
Darren Tuckera627d422013-06-02 07:31:17 +1000904 free(args->list[which]);
Damien Miller3eec6b72006-01-31 21:49:27 +1100905 args->list[which] = cp;
906}
907
908void
909freeargs(arglist *args)
910{
911 u_int i;
912
913 if (args->list != NULL) {
914 for (i = 0; i < args->num; i++)
Darren Tuckera627d422013-06-02 07:31:17 +1000915 free(args->list[i]);
916 free(args->list);
Damien Miller3eec6b72006-01-31 21:49:27 +1100917 args->nalloc = args->num = 0;
918 args->list = NULL;
919 }
920}
921
Darren Tucker22cc7412004-12-06 22:47:41 +1100922/*
Damien Miller5fd38c02005-05-26 12:02:14 +1000923 * Expands tildes in the file name. Returns data allocated by xmalloc.
924 * Warning: this calls getpw*.
925 */
926char *
927tilde_expand_filename(const char *filename, uid_t uid)
928{
Darren Tucker2ca51bf2013-05-16 20:22:46 +1000929 const char *path, *sep;
930 char user[128], *ret;
Damien Miller5fd38c02005-05-26 12:02:14 +1000931 struct passwd *pw;
Damien Millereccb9de2005-06-17 12:59:34 +1000932 u_int len, slash;
Damien Miller5fd38c02005-05-26 12:02:14 +1000933
934 if (*filename != '~')
935 return (xstrdup(filename));
936 filename++;
937
938 path = strchr(filename, '/');
939 if (path != NULL && path > filename) { /* ~user/path */
Damien Millereccb9de2005-06-17 12:59:34 +1000940 slash = path - filename;
941 if (slash > sizeof(user) - 1)
Damien Miller5fd38c02005-05-26 12:02:14 +1000942 fatal("tilde_expand_filename: ~username too long");
Damien Millereccb9de2005-06-17 12:59:34 +1000943 memcpy(user, filename, slash);
944 user[slash] = '\0';
Damien Miller5fd38c02005-05-26 12:02:14 +1000945 if ((pw = getpwnam(user)) == NULL)
946 fatal("tilde_expand_filename: No such user %s", user);
947 } else if ((pw = getpwuid(uid)) == NULL) /* ~/path */
Darren Tucker7517b5b2008-06-13 14:48:59 +1000948 fatal("tilde_expand_filename: No such uid %ld", (long)uid);
Damien Miller5fd38c02005-05-26 12:02:14 +1000949
Damien Miller5fd38c02005-05-26 12:02:14 +1000950 /* Make sure directory has a trailing '/' */
951 len = strlen(pw->pw_dir);
Darren Tucker026d9db2013-05-16 20:23:52 +1000952 if (len == 0 || pw->pw_dir[len - 1] != '/')
Darren Tucker2ca51bf2013-05-16 20:22:46 +1000953 sep = "/";
954 else
955 sep = "";
Damien Miller5fd38c02005-05-26 12:02:14 +1000956
957 /* Skip leading '/' from specified path */
958 if (path != NULL)
959 filename = path + 1;
Darren Tucker2ca51bf2013-05-16 20:22:46 +1000960
deraadt@openbsd.org2ae4f332015-01-16 06:40:12 +0000961 if (xasprintf(&ret, "%s%s%s", pw->pw_dir, sep, filename) >= PATH_MAX)
Damien Miller5fd38c02005-05-26 12:02:14 +1000962 fatal("tilde_expand_filename: Path too long");
963
Darren Tucker2ca51bf2013-05-16 20:22:46 +1000964 return (ret);
Damien Miller5fd38c02005-05-26 12:02:14 +1000965}
966
967/*
Damien Miller6476cad2005-06-16 13:18:34 +1000968 * Expand a string with a set of %[char] escapes. A number of escapes may be
969 * specified as (char *escape_chars, char *replacement) pairs. The list must
Darren Tuckerbee73d52005-07-14 17:05:02 +1000970 * be terminated by a NULL escape_char. Returns replaced string in memory
Damien Miller6476cad2005-06-16 13:18:34 +1000971 * allocated by xmalloc.
972 */
973char *
974percent_expand(const char *string, ...)
975{
976#define EXPAND_MAX_KEYS 16
Darren Tucker70d87692010-01-08 18:49:16 +1100977 u_int num_keys, i, j;
Damien Miller6476cad2005-06-16 13:18:34 +1000978 struct {
979 const char *key;
980 const char *repl;
981 } keys[EXPAND_MAX_KEYS];
Damien Miller6476cad2005-06-16 13:18:34 +1000982 char buf[4096];
983 va_list ap;
984
985 /* Gather keys */
986 va_start(ap, string);
987 for (num_keys = 0; num_keys < EXPAND_MAX_KEYS; num_keys++) {
988 keys[num_keys].key = va_arg(ap, char *);
989 if (keys[num_keys].key == NULL)
990 break;
991 keys[num_keys].repl = va_arg(ap, char *);
992 if (keys[num_keys].repl == NULL)
Darren Tucker70d87692010-01-08 18:49:16 +1100993 fatal("%s: NULL replacement", __func__);
Damien Miller6476cad2005-06-16 13:18:34 +1000994 }
Darren Tucker70d87692010-01-08 18:49:16 +1100995 if (num_keys == EXPAND_MAX_KEYS && va_arg(ap, char *) != NULL)
996 fatal("%s: too many keys", __func__);
Damien Miller6476cad2005-06-16 13:18:34 +1000997 va_end(ap);
998
Damien Miller6476cad2005-06-16 13:18:34 +1000999 /* Expand string */
1000 *buf = '\0';
1001 for (i = 0; *string != '\0'; string++) {
1002 if (*string != '%') {
1003 append:
1004 buf[i++] = *string;
1005 if (i >= sizeof(buf))
Darren Tucker70d87692010-01-08 18:49:16 +11001006 fatal("%s: string too long", __func__);
Damien Miller6476cad2005-06-16 13:18:34 +10001007 buf[i] = '\0';
1008 continue;
1009 }
1010 string++;
Darren Tucker70d87692010-01-08 18:49:16 +11001011 /* %% case */
Damien Miller6476cad2005-06-16 13:18:34 +10001012 if (*string == '%')
1013 goto append;
tobias@openbsd.org8b56e592015-12-04 21:51:06 +00001014 if (*string == '\0')
1015 fatal("%s: invalid format", __func__);
Damien Miller6476cad2005-06-16 13:18:34 +10001016 for (j = 0; j < num_keys; j++) {
1017 if (strchr(keys[j].key, *string) != NULL) {
1018 i = strlcat(buf, keys[j].repl, sizeof(buf));
1019 if (i >= sizeof(buf))
Darren Tucker70d87692010-01-08 18:49:16 +11001020 fatal("%s: string too long", __func__);
Damien Miller6476cad2005-06-16 13:18:34 +10001021 break;
1022 }
1023 }
1024 if (j >= num_keys)
Darren Tucker70d87692010-01-08 18:49:16 +11001025 fatal("%s: unknown key %%%c", __func__, *string);
Damien Miller6476cad2005-06-16 13:18:34 +10001026 }
1027 return (xstrdup(buf));
1028#undef EXPAND_MAX_KEYS
1029}
1030
Damien Millerd27b9472005-12-13 19:29:02 +11001031int
djm@openbsd.orgb7548b12017-10-23 05:08:00 +00001032tun_open(int tun, int mode, char **ifname)
Damien Millerd27b9472005-12-13 19:29:02 +11001033{
Damien Miller62a31c92005-12-13 20:44:13 +11001034#if defined(CUSTOM_SYS_TUN_OPEN)
djm@openbsd.orgb7548b12017-10-23 05:08:00 +00001035 return (sys_tun_open(tun, mode, ifname));
Damien Miller2dcddbf2006-01-01 19:47:05 +11001036#elif defined(SSH_TUN_OPENBSD)
Damien Miller7b58e802005-12-13 19:33:19 +11001037 struct ifreq ifr;
Damien Millerd27b9472005-12-13 19:29:02 +11001038 char name[100];
Damien Miller7b58e802005-12-13 19:33:19 +11001039 int fd = -1, sock;
sthen@openbsd.orga820a862015-10-24 08:34:09 +00001040 const char *tunbase = "tun";
1041
djm@openbsd.orgb7548b12017-10-23 05:08:00 +00001042 if (ifname != NULL)
1043 *ifname = NULL;
1044
sthen@openbsd.orga820a862015-10-24 08:34:09 +00001045 if (mode == SSH_TUNMODE_ETHERNET)
1046 tunbase = "tap";
Damien Millerd27b9472005-12-13 19:29:02 +11001047
Damien Miller7b58e802005-12-13 19:33:19 +11001048 /* Open the tunnel device */
1049 if (tun <= SSH_TUNID_MAX) {
sthen@openbsd.orga820a862015-10-24 08:34:09 +00001050 snprintf(name, sizeof(name), "/dev/%s%d", tunbase, tun);
Damien Miller7b58e802005-12-13 19:33:19 +11001051 fd = open(name, O_RDWR);
1052 } else if (tun == SSH_TUNID_ANY) {
1053 for (tun = 100; tun >= 0; tun--) {
sthen@openbsd.orga820a862015-10-24 08:34:09 +00001054 snprintf(name, sizeof(name), "/dev/%s%d",
1055 tunbase, tun);
Damien Miller7b58e802005-12-13 19:33:19 +11001056 if ((fd = open(name, O_RDWR)) >= 0)
1057 break;
Damien Millerd27b9472005-12-13 19:29:02 +11001058 }
1059 } else {
Damien Millera210d522006-01-02 23:40:30 +11001060 debug("%s: invalid tunnel %u", __func__, tun);
djm@openbsd.org2905d6f2015-10-07 00:54:06 +00001061 return -1;
Damien Millerd27b9472005-12-13 19:29:02 +11001062 }
Damien Miller7b58e802005-12-13 19:33:19 +11001063
1064 if (fd < 0) {
djm@openbsd.org2905d6f2015-10-07 00:54:06 +00001065 debug("%s: %s open: %s", __func__, name, strerror(errno));
1066 return -1;
Damien Miller7b58e802005-12-13 19:33:19 +11001067 }
1068
1069 debug("%s: %s mode %d fd %d", __func__, name, mode, fd);
1070
sthen@openbsd.orga820a862015-10-24 08:34:09 +00001071 /* Bring interface up if it is not already */
1072 snprintf(ifr.ifr_name, sizeof(ifr.ifr_name), "%s%d", tunbase, tun);
1073 if ((sock = socket(PF_UNIX, SOCK_STREAM, 0)) == -1)
Damien Miller7b58e802005-12-13 19:33:19 +11001074 goto failed;
1075
djm@openbsd.org2905d6f2015-10-07 00:54:06 +00001076 if (ioctl(sock, SIOCGIFFLAGS, &ifr) == -1) {
1077 debug("%s: get interface %s flags: %s", __func__,
1078 ifr.ifr_name, strerror(errno));
Damien Miller7b58e802005-12-13 19:33:19 +11001079 goto failed;
djm@openbsd.org2905d6f2015-10-07 00:54:06 +00001080 }
Damien Millera1d9a182006-01-02 23:41:21 +11001081
djm@openbsd.org2905d6f2015-10-07 00:54:06 +00001082 if (!(ifr.ifr_flags & IFF_UP)) {
1083 ifr.ifr_flags |= IFF_UP;
1084 if (ioctl(sock, SIOCSIFFLAGS, &ifr) == -1) {
1085 debug("%s: activate interface %s: %s", __func__,
1086 ifr.ifr_name, strerror(errno));
1087 goto failed;
1088 }
1089 }
Damien Miller7b58e802005-12-13 19:33:19 +11001090
djm@openbsd.orgb7548b12017-10-23 05:08:00 +00001091 if (ifname != NULL)
1092 *ifname = xstrdup(ifr.ifr_name);
1093
Damien Miller7b58e802005-12-13 19:33:19 +11001094 close(sock);
djm@openbsd.org2905d6f2015-10-07 00:54:06 +00001095 return fd;
Damien Miller7b58e802005-12-13 19:33:19 +11001096
1097 failed:
1098 if (fd >= 0)
1099 close(fd);
1100 if (sock >= 0)
1101 close(sock);
djm@openbsd.org2905d6f2015-10-07 00:54:06 +00001102 return -1;
Damien Miller62a31c92005-12-13 20:44:13 +11001103#else
1104 error("Tunnel interfaces are not supported on this platform");
1105 return (-1);
1106#endif
Damien Millerd27b9472005-12-13 19:29:02 +11001107}
1108
Darren Tuckerce321d82005-10-03 18:11:24 +10001109void
1110sanitise_stdfd(void)
1111{
Damien Miller72c5b7d2006-01-06 14:50:44 +11001112 int nullfd, dupfd;
Darren Tuckerce321d82005-10-03 18:11:24 +10001113
Damien Miller72c5b7d2006-01-06 14:50:44 +11001114 if ((nullfd = dupfd = open(_PATH_DEVNULL, O_RDWR)) == -1) {
Damien Miller9eab9562009-02-22 08:47:02 +11001115 fprintf(stderr, "Couldn't open /dev/null: %s\n",
1116 strerror(errno));
Darren Tuckerce321d82005-10-03 18:11:24 +10001117 exit(1);
1118 }
krw@openbsd.org574def02016-04-02 14:37:42 +00001119 while (++dupfd <= STDERR_FILENO) {
1120 /* Only populate closed fds. */
1121 if (fcntl(dupfd, F_GETFL) == -1 && errno == EBADF) {
1122 if (dup2(nullfd, dupfd) == -1) {
1123 fprintf(stderr, "dup2: %s\n", strerror(errno));
1124 exit(1);
1125 }
Darren Tuckerce321d82005-10-03 18:11:24 +10001126 }
Darren Tuckerce321d82005-10-03 18:11:24 +10001127 }
krw@openbsd.org574def02016-04-02 14:37:42 +00001128 if (nullfd > STDERR_FILENO)
Darren Tuckerce321d82005-10-03 18:11:24 +10001129 close(nullfd);
1130}
1131
Damien Miller13390022005-07-06 09:44:19 +10001132char *
Damien Miller3f941882006-03-31 23:13:02 +11001133tohex(const void *vp, size_t l)
Damien Miller13390022005-07-06 09:44:19 +10001134{
Damien Miller3f941882006-03-31 23:13:02 +11001135 const u_char *p = (const u_char *)vp;
Damien Miller13390022005-07-06 09:44:19 +10001136 char b[3], *r;
Damien Miller3f941882006-03-31 23:13:02 +11001137 size_t i, hl;
1138
1139 if (l > 65536)
1140 return xstrdup("tohex: length > 65536");
Damien Miller13390022005-07-06 09:44:19 +10001141
1142 hl = l * 2 + 1;
Damien Miller07d86be2006-03-26 14:19:21 +11001143 r = xcalloc(1, hl);
Damien Miller13390022005-07-06 09:44:19 +10001144 for (i = 0; i < l; i++) {
Damien Miller3f941882006-03-31 23:13:02 +11001145 snprintf(b, sizeof(b), "%02x", p[i]);
Damien Miller13390022005-07-06 09:44:19 +10001146 strlcat(r, b, hl);
1147 }
1148 return (r);
1149}
1150
Damien Miller3f941882006-03-31 23:13:02 +11001151u_int64_t
1152get_u64(const void *vp)
1153{
1154 const u_char *p = (const u_char *)vp;
1155 u_int64_t v;
1156
1157 v = (u_int64_t)p[0] << 56;
1158 v |= (u_int64_t)p[1] << 48;
1159 v |= (u_int64_t)p[2] << 40;
1160 v |= (u_int64_t)p[3] << 32;
1161 v |= (u_int64_t)p[4] << 24;
1162 v |= (u_int64_t)p[5] << 16;
1163 v |= (u_int64_t)p[6] << 8;
1164 v |= (u_int64_t)p[7];
1165
1166 return (v);
1167}
1168
1169u_int32_t
1170get_u32(const void *vp)
1171{
1172 const u_char *p = (const u_char *)vp;
1173 u_int32_t v;
1174
1175 v = (u_int32_t)p[0] << 24;
1176 v |= (u_int32_t)p[1] << 16;
1177 v |= (u_int32_t)p[2] << 8;
1178 v |= (u_int32_t)p[3];
1179
1180 return (v);
1181}
1182
Damien Miller88856692014-04-20 13:33:19 +10001183u_int32_t
1184get_u32_le(const void *vp)
1185{
1186 const u_char *p = (const u_char *)vp;
1187 u_int32_t v;
1188
1189 v = (u_int32_t)p[0];
1190 v |= (u_int32_t)p[1] << 8;
1191 v |= (u_int32_t)p[2] << 16;
1192 v |= (u_int32_t)p[3] << 24;
1193
1194 return (v);
1195}
1196
Damien Miller3f941882006-03-31 23:13:02 +11001197u_int16_t
1198get_u16(const void *vp)
1199{
1200 const u_char *p = (const u_char *)vp;
1201 u_int16_t v;
1202
1203 v = (u_int16_t)p[0] << 8;
1204 v |= (u_int16_t)p[1];
1205
1206 return (v);
1207}
1208
1209void
1210put_u64(void *vp, u_int64_t v)
1211{
1212 u_char *p = (u_char *)vp;
1213
1214 p[0] = (u_char)(v >> 56) & 0xff;
1215 p[1] = (u_char)(v >> 48) & 0xff;
1216 p[2] = (u_char)(v >> 40) & 0xff;
1217 p[3] = (u_char)(v >> 32) & 0xff;
1218 p[4] = (u_char)(v >> 24) & 0xff;
1219 p[5] = (u_char)(v >> 16) & 0xff;
1220 p[6] = (u_char)(v >> 8) & 0xff;
1221 p[7] = (u_char)v & 0xff;
1222}
1223
1224void
1225put_u32(void *vp, u_int32_t v)
1226{
1227 u_char *p = (u_char *)vp;
1228
1229 p[0] = (u_char)(v >> 24) & 0xff;
1230 p[1] = (u_char)(v >> 16) & 0xff;
1231 p[2] = (u_char)(v >> 8) & 0xff;
1232 p[3] = (u_char)v & 0xff;
1233}
1234
Damien Miller88856692014-04-20 13:33:19 +10001235void
1236put_u32_le(void *vp, u_int32_t v)
1237{
1238 u_char *p = (u_char *)vp;
1239
1240 p[0] = (u_char)v & 0xff;
1241 p[1] = (u_char)(v >> 8) & 0xff;
1242 p[2] = (u_char)(v >> 16) & 0xff;
1243 p[3] = (u_char)(v >> 24) & 0xff;
1244}
Damien Miller3f941882006-03-31 23:13:02 +11001245
1246void
1247put_u16(void *vp, u_int16_t v)
1248{
1249 u_char *p = (u_char *)vp;
1250
1251 p[0] = (u_char)(v >> 8) & 0xff;
1252 p[1] = (u_char)v & 0xff;
1253}
Darren Tucker3fc464e2008-06-13 06:42:45 +10001254
1255void
1256ms_subtract_diff(struct timeval *start, int *ms)
1257{
1258 struct timeval diff, finish;
1259
dtucker@openbsd.org@openbsd.org5db6fbf2017-11-25 06:46:22 +00001260 monotime_tv(&finish);
1261 timersub(&finish, start, &diff);
Darren Tucker3fc464e2008-06-13 06:42:45 +10001262 *ms -= (diff.tv_sec * 1000) + (diff.tv_usec / 1000);
1263}
1264
1265void
1266ms_to_timeval(struct timeval *tv, int ms)
1267{
1268 if (ms < 0)
1269 ms = 0;
1270 tv->tv_sec = ms / 1000;
1271 tv->tv_usec = (ms % 1000) * 1000;
1272}
1273
dtucker@openbsd.org@openbsd.org5db6fbf2017-11-25 06:46:22 +00001274void
1275monotime_ts(struct timespec *ts)
Darren Tuckerb759c9c2013-06-02 07:46:16 +10001276{
dtucker@openbsd.org@openbsd.org5db6fbf2017-11-25 06:46:22 +00001277 struct timeval tv;
1278#if defined(HAVE_CLOCK_GETTIME) && (defined(CLOCK_BOOTTIME) || \
1279 defined(CLOCK_MONOTONIC) || defined(CLOCK_REALTIME))
Darren Tucker94396b72013-08-08 11:52:37 +10001280 static int gettime_failed = 0;
Darren Tuckerb759c9c2013-06-02 07:46:16 +10001281
Darren Tucker94396b72013-08-08 11:52:37 +10001282 if (!gettime_failed) {
dtucker@openbsd.org@openbsd.org5db6fbf2017-11-25 06:46:22 +00001283# ifdef CLOCK_BOOTTIME
1284 if (clock_gettime(CLOCK_BOOTTIME, ts) == 0)
1285 return;
1286# endif /* CLOCK_BOOTTIME */
1287# ifdef CLOCK_MONOTONIC
1288 if (clock_gettime(CLOCK_MONOTONIC, ts) == 0)
1289 return;
1290# endif /* CLOCK_MONOTONIC */
1291# ifdef CLOCK_REALTIME
1292 /* Not monotonic, but we're almost out of options here. */
1293 if (clock_gettime(CLOCK_REALTIME, ts) == 0)
1294 return;
1295# endif /* CLOCK_REALTIME */
Darren Tucker94396b72013-08-08 11:52:37 +10001296 debug3("clock_gettime: %s", strerror(errno));
1297 gettime_failed = 1;
1298 }
dtucker@openbsd.org@openbsd.org5db6fbf2017-11-25 06:46:22 +00001299#endif /* HAVE_CLOCK_GETTIME && (BOOTTIME || MONOTONIC || REALTIME) */
1300 gettimeofday(&tv, NULL);
1301 ts->tv_sec = tv.tv_sec;
1302 ts->tv_nsec = (long)tv.tv_usec * 1000;
1303}
Darren Tucker94396b72013-08-08 11:52:37 +10001304
dtucker@openbsd.org@openbsd.org5db6fbf2017-11-25 06:46:22 +00001305void
1306monotime_tv(struct timeval *tv)
1307{
1308 struct timespec ts;
1309
1310 monotime_ts(&ts);
1311 tv->tv_sec = ts.tv_sec;
1312 tv->tv_usec = ts.tv_nsec / 1000;
1313}
1314
1315time_t
1316monotime(void)
1317{
1318 struct timespec ts;
1319
1320 monotime_ts(&ts);
1321 return ts.tv_sec;
Darren Tuckerb759c9c2013-06-02 07:46:16 +10001322}
1323
dtucker@openbsd.orgb8d4eaf2016-03-02 22:42:40 +00001324double
1325monotime_double(void)
1326{
1327 struct timespec ts;
1328
dtucker@openbsd.org@openbsd.org5db6fbf2017-11-25 06:46:22 +00001329 monotime_ts(&ts);
1330 return ts.tv_sec + ((double)ts.tv_nsec / 1000000000);
dtucker@openbsd.orgb8d4eaf2016-03-02 22:42:40 +00001331}
1332
Damien Miller65e42f82010-09-24 22:15:11 +10001333void
1334bandwidth_limit_init(struct bwlimit *bw, u_int64_t kbps, size_t buflen)
1335{
1336 bw->buflen = buflen;
1337 bw->rate = kbps;
1338 bw->thresh = bw->rate;
1339 bw->lamt = 0;
1340 timerclear(&bw->bwstart);
1341 timerclear(&bw->bwend);
1342}
1343
1344/* Callback from read/write loop to insert bandwidth-limiting delays */
1345void
1346bandwidth_limit(struct bwlimit *bw, size_t read_len)
1347{
1348 u_int64_t waitlen;
1349 struct timespec ts, rm;
1350
1351 if (!timerisset(&bw->bwstart)) {
dtucker@openbsd.org@openbsd.org5db6fbf2017-11-25 06:46:22 +00001352 monotime_tv(&bw->bwstart);
Damien Miller65e42f82010-09-24 22:15:11 +10001353 return;
1354 }
1355
1356 bw->lamt += read_len;
1357 if (bw->lamt < bw->thresh)
1358 return;
1359
dtucker@openbsd.org@openbsd.org5db6fbf2017-11-25 06:46:22 +00001360 monotime_tv(&bw->bwend);
Damien Miller65e42f82010-09-24 22:15:11 +10001361 timersub(&bw->bwend, &bw->bwstart, &bw->bwend);
1362 if (!timerisset(&bw->bwend))
1363 return;
1364
1365 bw->lamt *= 8;
1366 waitlen = (double)1000000L * bw->lamt / bw->rate;
1367
1368 bw->bwstart.tv_sec = waitlen / 1000000L;
1369 bw->bwstart.tv_usec = waitlen % 1000000L;
1370
1371 if (timercmp(&bw->bwstart, &bw->bwend, >)) {
1372 timersub(&bw->bwstart, &bw->bwend, &bw->bwend);
1373
1374 /* Adjust the wait time */
1375 if (bw->bwend.tv_sec) {
1376 bw->thresh /= 2;
1377 if (bw->thresh < bw->buflen / 4)
1378 bw->thresh = bw->buflen / 4;
1379 } else if (bw->bwend.tv_usec < 10000) {
1380 bw->thresh *= 2;
1381 if (bw->thresh > bw->buflen * 8)
1382 bw->thresh = bw->buflen * 8;
1383 }
1384
1385 TIMEVAL_TO_TIMESPEC(&bw->bwend, &ts);
1386 while (nanosleep(&ts, &rm) == -1) {
1387 if (errno != EINTR)
1388 break;
1389 ts = rm;
1390 }
1391 }
1392
1393 bw->lamt = 0;
dtucker@openbsd.org@openbsd.org5db6fbf2017-11-25 06:46:22 +00001394 monotime_tv(&bw->bwstart);
Damien Miller65e42f82010-09-24 22:15:11 +10001395}
Damien Miller0dac6fb2010-11-20 15:19:38 +11001396
Damien Miller2cd62932010-12-01 11:50:35 +11001397/* Make a template filename for mk[sd]temp() */
1398void
1399mktemp_proto(char *s, size_t len)
1400{
1401 const char *tmpdir;
1402 int r;
1403
1404 if ((tmpdir = getenv("TMPDIR")) != NULL) {
1405 r = snprintf(s, len, "%s/ssh-XXXXXXXXXXXX", tmpdir);
1406 if (r > 0 && (size_t)r < len)
1407 return;
1408 }
1409 r = snprintf(s, len, "/tmp/ssh-XXXXXXXXXXXX");
1410 if (r < 0 || (size_t)r >= len)
1411 fatal("%s: template string too short", __func__);
1412}
1413
Damien Miller0dac6fb2010-11-20 15:19:38 +11001414static const struct {
1415 const char *name;
1416 int value;
1417} ipqos[] = {
djm@openbsd.org51676ec2017-07-23 23:37:02 +00001418 { "none", INT_MAX }, /* can't use 0 here; that's CS0 */
Damien Miller0dac6fb2010-11-20 15:19:38 +11001419 { "af11", IPTOS_DSCP_AF11 },
1420 { "af12", IPTOS_DSCP_AF12 },
1421 { "af13", IPTOS_DSCP_AF13 },
Damien Miller2918e032011-09-22 21:34:35 +10001422 { "af21", IPTOS_DSCP_AF21 },
Damien Miller0dac6fb2010-11-20 15:19:38 +11001423 { "af22", IPTOS_DSCP_AF22 },
1424 { "af23", IPTOS_DSCP_AF23 },
1425 { "af31", IPTOS_DSCP_AF31 },
1426 { "af32", IPTOS_DSCP_AF32 },
1427 { "af33", IPTOS_DSCP_AF33 },
1428 { "af41", IPTOS_DSCP_AF41 },
1429 { "af42", IPTOS_DSCP_AF42 },
1430 { "af43", IPTOS_DSCP_AF43 },
1431 { "cs0", IPTOS_DSCP_CS0 },
1432 { "cs1", IPTOS_DSCP_CS1 },
1433 { "cs2", IPTOS_DSCP_CS2 },
1434 { "cs3", IPTOS_DSCP_CS3 },
1435 { "cs4", IPTOS_DSCP_CS4 },
1436 { "cs5", IPTOS_DSCP_CS5 },
1437 { "cs6", IPTOS_DSCP_CS6 },
1438 { "cs7", IPTOS_DSCP_CS7 },
1439 { "ef", IPTOS_DSCP_EF },
1440 { "lowdelay", IPTOS_LOWDELAY },
1441 { "throughput", IPTOS_THROUGHPUT },
1442 { "reliability", IPTOS_RELIABILITY },
1443 { NULL, -1 }
1444};
1445
1446int
1447parse_ipqos(const char *cp)
1448{
1449 u_int i;
1450 char *ep;
1451 long val;
1452
1453 if (cp == NULL)
1454 return -1;
1455 for (i = 0; ipqos[i].name != NULL; i++) {
1456 if (strcasecmp(cp, ipqos[i].name) == 0)
1457 return ipqos[i].value;
1458 }
1459 /* Try parsing as an integer */
1460 val = strtol(cp, &ep, 0);
1461 if (*cp == '\0' || *ep != '\0' || val < 0 || val > 255)
1462 return -1;
1463 return val;
1464}
1465
Damien Miller91475862011-05-05 14:14:34 +10001466const char *
1467iptos2str(int iptos)
1468{
1469 int i;
1470 static char iptos_str[sizeof "0xff"];
1471
1472 for (i = 0; ipqos[i].name != NULL; i++) {
1473 if (ipqos[i].value == iptos)
1474 return ipqos[i].name;
1475 }
1476 snprintf(iptos_str, sizeof iptos_str, "0x%02x", iptos);
1477 return iptos_str;
1478}
Damien Millere9fc72e2013-10-15 12:14:12 +11001479
1480void
1481lowercase(char *s)
1482{
1483 for (; *s; s++)
1484 *s = tolower((u_char)*s);
1485}
Damien Miller7acefbb2014-07-18 14:11:24 +10001486
1487int
1488unix_listener(const char *path, int backlog, int unlink_first)
1489{
1490 struct sockaddr_un sunaddr;
1491 int saved_errno, sock;
1492
1493 memset(&sunaddr, 0, sizeof(sunaddr));
1494 sunaddr.sun_family = AF_UNIX;
djm@openbsd.org155072f2017-12-08 02:13:02 +00001495 if (strlcpy(sunaddr.sun_path, path,
1496 sizeof(sunaddr.sun_path)) >= sizeof(sunaddr.sun_path)) {
1497 error("%s: path \"%s\" too long for Unix domain socket",
1498 __func__, path);
Damien Miller7acefbb2014-07-18 14:11:24 +10001499 errno = ENAMETOOLONG;
1500 return -1;
1501 }
1502
1503 sock = socket(PF_UNIX, SOCK_STREAM, 0);
1504 if (sock < 0) {
1505 saved_errno = errno;
djm@openbsd.org155072f2017-12-08 02:13:02 +00001506 error("%s: socket: %.100s", __func__, strerror(errno));
Damien Miller7acefbb2014-07-18 14:11:24 +10001507 errno = saved_errno;
1508 return -1;
1509 }
1510 if (unlink_first == 1) {
1511 if (unlink(path) != 0 && errno != ENOENT)
1512 error("unlink(%s): %.100s", path, strerror(errno));
1513 }
1514 if (bind(sock, (struct sockaddr *)&sunaddr, sizeof(sunaddr)) < 0) {
1515 saved_errno = errno;
djm@openbsd.org155072f2017-12-08 02:13:02 +00001516 error("%s: cannot bind to path %s: %s",
1517 __func__, path, strerror(errno));
djm@openbsd.orgfd4eeee2017-12-08 02:14:33 +00001518 close(sock);
Damien Miller7acefbb2014-07-18 14:11:24 +10001519 errno = saved_errno;
1520 return -1;
1521 }
1522 if (listen(sock, backlog) < 0) {
1523 saved_errno = errno;
djm@openbsd.org155072f2017-12-08 02:13:02 +00001524 error("%s: cannot listen on path %s: %s",
1525 __func__, path, strerror(errno));
djm@openbsd.orgfd4eeee2017-12-08 02:14:33 +00001526 close(sock);
1527 unlink(path);
Damien Miller7acefbb2014-07-18 14:11:24 +10001528 errno = saved_errno;
1529 return -1;
1530 }
1531 return sock;
1532}
Damien Miller46878022014-08-30 03:29:19 +10001533
Damien Miller04ee0f82009-11-18 17:48:30 +11001534void
1535sock_set_v6only(int s)
1536{
Damien Millerd86a3ba2015-12-09 09:18:45 +11001537#if defined(IPV6_V6ONLY) && !defined(__OpenBSD__)
Damien Miller04ee0f82009-11-18 17:48:30 +11001538 int on = 1;
1539
1540 debug3("%s: set socket %d IPV6_V6ONLY", __func__, s);
1541 if (setsockopt(s, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof(on)) == -1)
1542 error("setsockopt IPV6_V6ONLY: %s", strerror(errno));
1543#endif
1544}
djm@openbsd.org0ccbd5e2016-04-06 06:42:17 +00001545
1546/*
1547 * Compares two strings that maybe be NULL. Returns non-zero if strings
1548 * are both NULL or are identical, returns zero otherwise.
1549 */
1550static int
1551strcmp_maybe_null(const char *a, const char *b)
1552{
1553 if ((a == NULL && b != NULL) || (a != NULL && b == NULL))
1554 return 0;
1555 if (a != NULL && strcmp(a, b) != 0)
1556 return 0;
1557 return 1;
1558}
1559
1560/*
1561 * Compare two forwards, returning non-zero if they are identical or
1562 * zero otherwise.
1563 */
1564int
1565forward_equals(const struct Forward *a, const struct Forward *b)
1566{
1567 if (strcmp_maybe_null(a->listen_host, b->listen_host) == 0)
1568 return 0;
1569 if (a->listen_port != b->listen_port)
1570 return 0;
1571 if (strcmp_maybe_null(a->listen_path, b->listen_path) == 0)
1572 return 0;
1573 if (strcmp_maybe_null(a->connect_host, b->connect_host) == 0)
1574 return 0;
1575 if (a->connect_port != b->connect_port)
1576 return 0;
1577 if (strcmp_maybe_null(a->connect_path, b->connect_path) == 0)
1578 return 0;
1579 /* allocated_port and handle are not checked */
1580 return 1;
1581}
1582
dtucker@openbsd.org7fc47662016-11-30 00:28:31 +00001583/* returns 1 if process is already daemonized, 0 otherwise */
1584int
1585daemonized(void)
1586{
1587 int fd;
1588
1589 if ((fd = open(_PATH_TTY, O_RDONLY | O_NOCTTY)) >= 0) {
1590 close(fd);
1591 return 0; /* have controlling terminal */
1592 }
1593 if (getppid() != 1)
1594 return 0; /* parent is not init */
1595 if (getsid(0) != getpid())
1596 return 0; /* not session leader */
1597 debug3("already daemonized");
1598 return 1;
1599}
djm@openbsd.orgde4ae072017-08-18 05:36:45 +00001600
1601
1602/*
1603 * Splits 's' into an argument vector. Handles quoted string and basic
1604 * escape characters (\\, \", \'). Caller must free the argument vector
1605 * and its members.
1606 */
1607int
1608argv_split(const char *s, int *argcp, char ***argvp)
1609{
1610 int r = SSH_ERR_INTERNAL_ERROR;
1611 int argc = 0, quote, i, j;
1612 char *arg, **argv = xcalloc(1, sizeof(*argv));
1613
1614 *argvp = NULL;
1615 *argcp = 0;
1616
1617 for (i = 0; s[i] != '\0'; i++) {
1618 /* Skip leading whitespace */
1619 if (s[i] == ' ' || s[i] == '\t')
1620 continue;
1621
1622 /* Start of a token */
1623 quote = 0;
1624 if (s[i] == '\\' &&
1625 (s[i + 1] == '\'' || s[i + 1] == '\"' || s[i + 1] == '\\'))
1626 i++;
1627 else if (s[i] == '\'' || s[i] == '"')
1628 quote = s[i++];
1629
1630 argv = xreallocarray(argv, (argc + 2), sizeof(*argv));
1631 arg = argv[argc++] = xcalloc(1, strlen(s + i) + 1);
1632 argv[argc] = NULL;
1633
1634 /* Copy the token in, removing escapes */
1635 for (j = 0; s[i] != '\0'; i++) {
1636 if (s[i] == '\\') {
1637 if (s[i + 1] == '\'' ||
1638 s[i + 1] == '\"' ||
1639 s[i + 1] == '\\') {
1640 i++; /* Skip '\' */
1641 arg[j++] = s[i];
1642 } else {
1643 /* Unrecognised escape */
1644 arg[j++] = s[i];
1645 }
1646 } else if (quote == 0 && (s[i] == ' ' || s[i] == '\t'))
1647 break; /* done */
1648 else if (quote != 0 && s[i] == quote)
1649 break; /* done */
1650 else
1651 arg[j++] = s[i];
1652 }
1653 if (s[i] == '\0') {
1654 if (quote != 0) {
1655 /* Ran out of string looking for close quote */
1656 r = SSH_ERR_INVALID_FORMAT;
1657 goto out;
1658 }
1659 break;
1660 }
1661 }
1662 /* Success */
1663 *argcp = argc;
1664 *argvp = argv;
1665 argc = 0;
1666 argv = NULL;
1667 r = 0;
1668 out:
1669 if (argc != 0 && argv != NULL) {
1670 for (i = 0; i < argc; i++)
1671 free(argv[i]);
1672 free(argv);
1673 }
1674 return r;
1675}
1676
1677/*
1678 * Reassemble an argument vector into a string, quoting and escaping as
1679 * necessary. Caller must free returned string.
1680 */
1681char *
1682argv_assemble(int argc, char **argv)
1683{
1684 int i, j, ws, r;
1685 char c, *ret;
1686 struct sshbuf *buf, *arg;
1687
1688 if ((buf = sshbuf_new()) == NULL || (arg = sshbuf_new()) == NULL)
1689 fatal("%s: sshbuf_new failed", __func__);
1690
1691 for (i = 0; i < argc; i++) {
1692 ws = 0;
1693 sshbuf_reset(arg);
1694 for (j = 0; argv[i][j] != '\0'; j++) {
1695 r = 0;
1696 c = argv[i][j];
1697 switch (c) {
1698 case ' ':
1699 case '\t':
1700 ws = 1;
1701 r = sshbuf_put_u8(arg, c);
1702 break;
1703 case '\\':
1704 case '\'':
1705 case '"':
1706 if ((r = sshbuf_put_u8(arg, '\\')) != 0)
1707 break;
1708 /* FALLTHROUGH */
1709 default:
1710 r = sshbuf_put_u8(arg, c);
1711 break;
1712 }
1713 if (r != 0)
1714 fatal("%s: sshbuf_put_u8: %s",
1715 __func__, ssh_err(r));
1716 }
1717 if ((i != 0 && (r = sshbuf_put_u8(buf, ' ')) != 0) ||
1718 (ws != 0 && (r = sshbuf_put_u8(buf, '"')) != 0) ||
1719 (r = sshbuf_putb(buf, arg)) != 0 ||
1720 (ws != 0 && (r = sshbuf_put_u8(buf, '"')) != 0))
1721 fatal("%s: buffer error: %s", __func__, ssh_err(r));
1722 }
1723 if ((ret = malloc(sshbuf_len(buf) + 1)) == NULL)
1724 fatal("%s: malloc failed", __func__);
1725 memcpy(ret, sshbuf_ptr(buf), sshbuf_len(buf));
1726 ret[sshbuf_len(buf)] = '\0';
1727 sshbuf_free(buf);
1728 sshbuf_free(arg);
1729 return ret;
1730}
1731
djm@openbsd.orgde4ae072017-08-18 05:36:45 +00001732/* Returns 0 if pid exited cleanly, non-zero otherwise */
1733int
djm@openbsd.orgb074c3c2017-08-18 05:48:04 +00001734exited_cleanly(pid_t pid, const char *tag, const char *cmd, int quiet)
djm@openbsd.orgde4ae072017-08-18 05:36:45 +00001735{
1736 int status;
1737
1738 while (waitpid(pid, &status, 0) == -1) {
1739 if (errno != EINTR) {
1740 error("%s: waitpid: %s", tag, strerror(errno));
1741 return -1;
1742 }
1743 }
1744 if (WIFSIGNALED(status)) {
1745 error("%s %s exited on signal %d", tag, cmd, WTERMSIG(status));
1746 return -1;
1747 } else if (WEXITSTATUS(status) != 0) {
djm@openbsd.orgb074c3c2017-08-18 05:48:04 +00001748 do_log2(quiet ? SYSLOG_LEVEL_DEBUG1 : SYSLOG_LEVEL_INFO,
1749 "%s %s failed, status %d", tag, cmd, WEXITSTATUS(status));
djm@openbsd.orgde4ae072017-08-18 05:36:45 +00001750 return -1;
1751 }
1752 return 0;
1753}
1754
1755/*
1756 * Check a given path for security. This is defined as all components
1757 * of the path to the file must be owned by either the owner of
1758 * of the file or root and no directories must be group or world writable.
1759 *
1760 * XXX Should any specific check be done for sym links ?
1761 *
1762 * Takes a file name, its stat information (preferably from fstat() to
1763 * avoid races), the uid of the expected owner, their home directory and an
1764 * error buffer plus max size as arguments.
1765 *
1766 * Returns 0 on success and -1 on failure
1767 */
1768int
1769safe_path(const char *name, struct stat *stp, const char *pw_dir,
1770 uid_t uid, char *err, size_t errlen)
1771{
1772 char buf[PATH_MAX], homedir[PATH_MAX];
1773 char *cp;
1774 int comparehome = 0;
1775 struct stat st;
1776
1777 if (realpath(name, buf) == NULL) {
1778 snprintf(err, errlen, "realpath %s failed: %s", name,
1779 strerror(errno));
1780 return -1;
1781 }
1782 if (pw_dir != NULL && realpath(pw_dir, homedir) != NULL)
1783 comparehome = 1;
1784
1785 if (!S_ISREG(stp->st_mode)) {
1786 snprintf(err, errlen, "%s is not a regular file", buf);
1787 return -1;
1788 }
1789 if ((!platform_sys_dir_uid(stp->st_uid) && stp->st_uid != uid) ||
1790 (stp->st_mode & 022) != 0) {
1791 snprintf(err, errlen, "bad ownership or modes for file %s",
1792 buf);
1793 return -1;
1794 }
1795
1796 /* for each component of the canonical path, walking upwards */
1797 for (;;) {
1798 if ((cp = dirname(buf)) == NULL) {
1799 snprintf(err, errlen, "dirname() failed");
1800 return -1;
1801 }
1802 strlcpy(buf, cp, sizeof(buf));
1803
1804 if (stat(buf, &st) < 0 ||
1805 (!platform_sys_dir_uid(st.st_uid) && st.st_uid != uid) ||
1806 (st.st_mode & 022) != 0) {
1807 snprintf(err, errlen,
1808 "bad ownership or modes for directory %s", buf);
1809 return -1;
1810 }
1811
1812 /* If are past the homedir then we can stop */
1813 if (comparehome && strcmp(homedir, buf) == 0)
1814 break;
1815
1816 /*
1817 * dirname should always complete with a "/" path,
1818 * but we can be paranoid and check for "." too
1819 */
1820 if ((strcmp("/", buf) == 0) || (strcmp(".", buf) == 0))
1821 break;
1822 }
1823 return 0;
1824}
1825
1826/*
1827 * Version of safe_path() that accepts an open file descriptor to
1828 * avoid races.
1829 *
1830 * Returns 0 on success and -1 on failure
1831 */
1832int
1833safe_path_fd(int fd, const char *file, struct passwd *pw,
1834 char *err, size_t errlen)
1835{
1836 struct stat st;
1837
1838 /* check the open file to avoid races */
1839 if (fstat(fd, &st) < 0) {
1840 snprintf(err, errlen, "cannot stat file %s: %s",
1841 file, strerror(errno));
1842 return -1;
1843 }
1844 return safe_path(file, &st, pw->pw_dir, pw->pw_uid, err, errlen);
1845}
1846
1847/*
1848 * Sets the value of the given variable in the environment. If the variable
1849 * already exists, its value is overridden.
1850 */
1851void
1852child_set_env(char ***envp, u_int *envsizep, const char *name,
1853 const char *value)
1854{
1855 char **env;
1856 u_int envsize;
1857 u_int i, namelen;
1858
1859 if (strchr(name, '=') != NULL) {
1860 error("Invalid environment variable \"%.100s\"", name);
1861 return;
1862 }
1863
1864 /*
1865 * If we're passed an uninitialized list, allocate a single null
1866 * entry before continuing.
1867 */
1868 if (*envp == NULL && *envsizep == 0) {
1869 *envp = xmalloc(sizeof(char *));
1870 *envp[0] = NULL;
1871 *envsizep = 1;
1872 }
1873
1874 /*
1875 * Find the slot where the value should be stored. If the variable
1876 * already exists, we reuse the slot; otherwise we append a new slot
1877 * at the end of the array, expanding if necessary.
1878 */
1879 env = *envp;
1880 namelen = strlen(name);
1881 for (i = 0; env[i]; i++)
1882 if (strncmp(env[i], name, namelen) == 0 && env[i][namelen] == '=')
1883 break;
1884 if (env[i]) {
1885 /* Reuse the slot. */
1886 free(env[i]);
1887 } else {
1888 /* New variable. Expand if necessary. */
1889 envsize = *envsizep;
1890 if (i >= envsize - 1) {
1891 if (envsize >= 1000)
1892 fatal("child_set_env: too many env vars");
1893 envsize += 50;
1894 env = (*envp) = xreallocarray(env, envsize, sizeof(char *));
1895 *envsizep = envsize;
1896 }
1897 /* Need to set the NULL pointer at end of array beyond the new slot. */
1898 env[i + 1] = NULL;
1899 }
1900
1901 /* Allocate space and format the variable in the appropriate slot. */
djm@openbsd.org7c856852018-03-03 03:15:51 +00001902 /* XXX xasprintf */
djm@openbsd.orgde4ae072017-08-18 05:36:45 +00001903 env[i] = xmalloc(strlen(name) + 1 + strlen(value) + 1);
1904 snprintf(env[i], strlen(name) + 1 + strlen(value) + 1, "%s=%s", name, value);
1905}
1906
millert@openbsd.org887669e2017-10-21 23:06:24 +00001907/*
1908 * Check and optionally lowercase a domain name, also removes trailing '.'
1909 * Returns 1 on success and 0 on failure, storing an error message in errstr.
1910 */
1911int
1912valid_domain(char *name, int makelower, const char **errstr)
1913{
1914 size_t i, l = strlen(name);
1915 u_char c, last = '\0';
1916 static char errbuf[256];
1917
1918 if (l == 0) {
1919 strlcpy(errbuf, "empty domain name", sizeof(errbuf));
1920 goto bad;
1921 }
1922 if (!isalpha((u_char)name[0]) && !isdigit((u_char)name[0])) {
1923 snprintf(errbuf, sizeof(errbuf), "domain name \"%.100s\" "
1924 "starts with invalid character", name);
1925 goto bad;
1926 }
1927 for (i = 0; i < l; i++) {
1928 c = tolower((u_char)name[i]);
1929 if (makelower)
1930 name[i] = (char)c;
1931 if (last == '.' && c == '.') {
1932 snprintf(errbuf, sizeof(errbuf), "domain name "
1933 "\"%.100s\" contains consecutive separators", name);
1934 goto bad;
1935 }
1936 if (c != '.' && c != '-' && !isalnum(c) &&
1937 c != '_') /* technically invalid, but common */ {
1938 snprintf(errbuf, sizeof(errbuf), "domain name "
1939 "\"%.100s\" contains invalid characters", name);
1940 goto bad;
1941 }
1942 last = c;
1943 }
1944 if (name[l - 1] == '.')
1945 name[l - 1] = '\0';
1946 if (errstr != NULL)
1947 *errstr = NULL;
1948 return 1;
1949bad:
1950 if (errstr != NULL)
1951 *errstr = errbuf;
1952 return 0;
1953}
dtucker@openbsd.org609d96b2017-12-05 23:59:47 +00001954
djm@openbsd.org5eff5b82018-10-03 06:38:35 +00001955/*
1956 * Verify that a environment variable name (not including initial '$') is
1957 * valid; consisting of one or more alphanumeric or underscore characters only.
1958 * Returns 1 on valid, 0 otherwise.
1959 */
1960int
1961valid_env_name(const char *name)
1962{
1963 const char *cp;
1964
1965 if (name[0] == '\0')
1966 return 0;
1967 for (cp = name; *cp != '\0'; cp++) {
1968 if (!isalnum((u_char)*cp) && *cp != '_')
1969 return 0;
1970 }
1971 return 1;
1972}
1973
dtucker@openbsd.org609d96b2017-12-05 23:59:47 +00001974const char *
1975atoi_err(const char *nptr, int *val)
1976{
1977 const char *errstr = NULL;
1978 long long num;
1979
1980 if (nptr == NULL || *nptr == '\0')
1981 return "missing";
1982 num = strtonum(nptr, 0, INT_MAX, &errstr);
1983 if (errstr == NULL)
1984 *val = (int)num;
1985 return errstr;
1986}
djm@openbsd.orgbf0fbf22018-03-12 00:52:01 +00001987
1988int
1989parse_absolute_time(const char *s, uint64_t *tp)
1990{
1991 struct tm tm;
1992 time_t tt;
1993 char buf[32], *fmt;
1994
1995 *tp = 0;
1996
1997 /*
1998 * POSIX strptime says "The application shall ensure that there
1999 * is white-space or other non-alphanumeric characters between
2000 * any two conversion specifications" so arrange things this way.
2001 */
2002 switch (strlen(s)) {
2003 case 8: /* YYYYMMDD */
2004 fmt = "%Y-%m-%d";
2005 snprintf(buf, sizeof(buf), "%.4s-%.2s-%.2s", s, s + 4, s + 6);
2006 break;
2007 case 12: /* YYYYMMDDHHMM */
2008 fmt = "%Y-%m-%dT%H:%M";
2009 snprintf(buf, sizeof(buf), "%.4s-%.2s-%.2sT%.2s:%.2s",
2010 s, s + 4, s + 6, s + 8, s + 10);
2011 break;
2012 case 14: /* YYYYMMDDHHMMSS */
2013 fmt = "%Y-%m-%dT%H:%M:%S";
2014 snprintf(buf, sizeof(buf), "%.4s-%.2s-%.2sT%.2s:%.2s:%.2s",
2015 s, s + 4, s + 6, s + 8, s + 10, s + 12);
2016 break;
2017 default:
2018 return SSH_ERR_INVALID_FORMAT;
2019 }
2020
2021 memset(&tm, 0, sizeof(tm));
2022 if (strptime(buf, fmt, &tm) == NULL)
2023 return SSH_ERR_INVALID_FORMAT;
2024 if ((tt = mktime(&tm)) < 0)
2025 return SSH_ERR_INVALID_FORMAT;
2026 /* success */
2027 *tp = (uint64_t)tt;
2028 return 0;
2029}
2030
2031void
2032format_absolute_time(uint64_t t, char *buf, size_t len)
2033{
2034 time_t tt = t > INT_MAX ? INT_MAX : t; /* XXX revisit in 2038 :P */
2035 struct tm tm;
2036
2037 localtime_r(&tt, &tm);
2038 strftime(buf, len, "%Y-%m-%dT%H:%M:%S", &tm);
2039}
djm@openbsd.org2a358622018-11-16 03:26:01 +00002040
2041/* check if path is absolute */
2042int
2043path_absolute(const char *path)
2044{
2045 return (*path == '/') ? 1 : 0;
2046}