blob: ae4d29b84c2edf6596aabae155e89cd259a6fdbb [file] [log] [blame]
dtucker@openbsd.org73ddb252018-07-27 05:13:02 +00001/* $OpenBSD: misc.c,v 1.131 2018/07/27 05:13:02 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
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>
Damien Miller8ec8c3e2006-07-10 20:35:38 +100053
Damien Millere9fc72e2013-10-15 12:14:12 +110054#include <ctype.h>
Darren Tucker39972492006-07-12 22:22:46 +100055#include <errno.h>
Damien Miller57cf6382006-07-10 21:13:46 +100056#include <fcntl.h>
Darren Tucker4abde772007-12-29 02:43:51 +110057#include <netdb.h>
Damien Miller03e20032006-03-15 11:16:59 +110058#ifdef HAVE_PATHS_H
Damien Millera9263d02006-03-15 11:18:26 +110059# include <paths.h>
Damien Miller9f2abc42006-07-10 20:53:08 +100060#include <pwd.h>
Damien Miller03e20032006-03-15 11:16:59 +110061#endif
Damien Miller3beb8522006-01-02 23:40:10 +110062#ifdef SSH_TUN_OPENBSD
63#include <net/if.h>
64#endif
Damien Miller61c51502000-08-18 14:01:04 +100065
Damien Millerd7834352006-08-05 12:39:39 +100066#include "xmalloc.h"
Kevin Stevesb6e773a2001-02-04 13:20:36 +000067#include "misc.h"
Ben Lindstrom226cfa02001-01-22 05:34:40 +000068#include "log.h"
Darren Tuckerda345532006-07-10 23:04:19 +100069#include "ssh.h"
djm@openbsd.orgde4ae072017-08-18 05:36:45 +000070#include "sshbuf.h"
71#include "ssherr.h"
Damien Miller07949bf2017-08-23 20:13:18 +100072#include "platform.h"
Damien Miller61c51502000-08-18 14:01:04 +100073
Ben Lindstrom4cc240d2001-07-04 04:46:56 +000074/* remove newline at end of string */
Damien Miller61c51502000-08-18 14:01:04 +100075char *
76chop(char *s)
77{
78 char *t = s;
79 while (*t) {
Ben Lindstrom1c37c6a2001-12-06 18:00:18 +000080 if (*t == '\n' || *t == '\r') {
Damien Miller61c51502000-08-18 14:01:04 +100081 *t = '\0';
82 return s;
83 }
84 t++;
85 }
86 return s;
87
88}
89
Ben Lindstrom4cc240d2001-07-04 04:46:56 +000090/* set/unset filedescriptor to non-blocking */
Damien Miller232711f2004-06-15 10:35:30 +100091int
Damien Miller61c51502000-08-18 14:01:04 +100092set_nonblock(int fd)
93{
94 int val;
Ben Lindstromc93e84c2001-05-12 00:08:37 +000095
krw@openbsd.org574def02016-04-02 14:37:42 +000096 val = fcntl(fd, F_GETFL);
Damien Miller61c51502000-08-18 14:01:04 +100097 if (val < 0) {
krw@openbsd.org574def02016-04-02 14:37:42 +000098 error("fcntl(%d, F_GETFL): %s", fd, strerror(errno));
Damien Miller232711f2004-06-15 10:35:30 +100099 return (-1);
Damien Miller61c51502000-08-18 14:01:04 +1000100 }
Damien Miller69b69aa2000-10-28 14:19:58 +1100101 if (val & O_NONBLOCK) {
Damien Miller232711f2004-06-15 10:35:30 +1000102 debug3("fd %d is O_NONBLOCK", fd);
103 return (0);
Damien Miller69b69aa2000-10-28 14:19:58 +1100104 }
Damien Milleref095ce2003-05-14 13:41:39 +1000105 debug2("fd %d setting O_NONBLOCK", fd);
Damien Miller61c51502000-08-18 14:01:04 +1000106 val |= O_NONBLOCK;
Damien Miller232711f2004-06-15 10:35:30 +1000107 if (fcntl(fd, F_SETFL, val) == -1) {
108 debug("fcntl(%d, F_SETFL, O_NONBLOCK): %s", fd,
109 strerror(errno));
110 return (-1);
111 }
112 return (0);
Damien Miller61c51502000-08-18 14:01:04 +1000113}
114
Damien Miller232711f2004-06-15 10:35:30 +1000115int
Ben Lindstromc93e84c2001-05-12 00:08:37 +0000116unset_nonblock(int fd)
117{
118 int val;
119
krw@openbsd.org574def02016-04-02 14:37:42 +0000120 val = fcntl(fd, F_GETFL);
Ben Lindstromc93e84c2001-05-12 00:08:37 +0000121 if (val < 0) {
krw@openbsd.org574def02016-04-02 14:37:42 +0000122 error("fcntl(%d, F_GETFL): %s", fd, strerror(errno));
Damien Miller232711f2004-06-15 10:35:30 +1000123 return (-1);
Ben Lindstromc93e84c2001-05-12 00:08:37 +0000124 }
125 if (!(val & O_NONBLOCK)) {
Damien Miller232711f2004-06-15 10:35:30 +1000126 debug3("fd %d is not O_NONBLOCK", fd);
127 return (0);
Ben Lindstromc93e84c2001-05-12 00:08:37 +0000128 }
Ben Lindstrom352b1c22001-06-21 03:04:37 +0000129 debug("fd %d clearing O_NONBLOCK", fd);
Ben Lindstromc93e84c2001-05-12 00:08:37 +0000130 val &= ~O_NONBLOCK;
Damien Miller232711f2004-06-15 10:35:30 +1000131 if (fcntl(fd, F_SETFL, val) == -1) {
132 debug("fcntl(%d, F_SETFL, ~O_NONBLOCK): %s",
Ben Lindstrom84fcb312002-03-05 01:48:09 +0000133 fd, strerror(errno));
Damien Miller232711f2004-06-15 10:35:30 +1000134 return (-1);
135 }
136 return (0);
Ben Lindstromc93e84c2001-05-12 00:08:37 +0000137}
138
Darren Tucker4abde772007-12-29 02:43:51 +1100139const char *
140ssh_gai_strerror(int gaierr)
141{
Damien Miller7313fc92013-07-18 16:13:19 +1000142 if (gaierr == EAI_SYSTEM && errno != 0)
Darren Tucker912428c2008-01-01 20:33:35 +1100143 return strerror(errno);
144 return gai_strerror(gaierr);
Darren Tucker4abde772007-12-29 02:43:51 +1100145}
146
Damien Miller398e1cf2002-02-05 11:52:13 +1100147/* disable nagle on socket */
148void
149set_nodelay(int fd)
150{
Ben Lindstrome86de512002-03-05 01:28:14 +0000151 int opt;
152 socklen_t optlen;
Damien Miller398e1cf2002-02-05 11:52:13 +1100153
Ben Lindstrom1ebd7a52002-02-26 18:12:51 +0000154 optlen = sizeof opt;
155 if (getsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &opt, &optlen) == -1) {
Darren Tucker6db8f932003-11-03 20:07:14 +1100156 debug("getsockopt TCP_NODELAY: %.100s", strerror(errno));
Ben Lindstrom1ebd7a52002-02-26 18:12:51 +0000157 return;
158 }
159 if (opt == 1) {
160 debug2("fd %d is TCP_NODELAY", fd);
161 return;
162 }
163 opt = 1;
Ben Lindstrom1d568f92002-12-23 02:44:36 +0000164 debug2("fd %d setting TCP_NODELAY", fd);
Ben Lindstrom1ebd7a52002-02-26 18:12:51 +0000165 if (setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &opt, sizeof opt) == -1)
Damien Miller398e1cf2002-02-05 11:52:13 +1100166 error("setsockopt TCP_NODELAY: %.100s", strerror(errno));
167}
168
djm@openbsd.orgacf559e2017-10-25 00:15:35 +0000169/* Allow local port reuse in TIME_WAIT */
170int
171set_reuseaddr(int fd)
172{
173 int on = 1;
174
175 if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)) == -1) {
176 error("setsockopt SO_REUSEADDR fd %d: %s", fd, strerror(errno));
177 return -1;
178 }
179 return 0;
180}
181
djm@openbsd.org35eb33f2017-10-25 00:17:08 +0000182/* Get/set routing domain */
183char *
184get_rdomain(int fd)
185{
Damien Miller43c29bb2017-10-25 13:10:59 +1100186#if defined(HAVE_SYS_GET_RDOMAIN)
187 return sys_get_rdomain(fd);
188#elif defined(__OpenBSD__)
djm@openbsd.org35eb33f2017-10-25 00:17:08 +0000189 int rtable;
190 char *ret;
191 socklen_t len = sizeof(rtable);
192
193 if (getsockopt(fd, SOL_SOCKET, SO_RTABLE, &rtable, &len) == -1) {
194 error("Failed to get routing domain for fd %d: %s",
195 fd, strerror(errno));
196 return NULL;
197 }
198 xasprintf(&ret, "%d", rtable);
199 return ret;
Damien Miller43c29bb2017-10-25 13:10:59 +1100200#else /* defined(__OpenBSD__) */
201 return NULL;
202#endif
djm@openbsd.org35eb33f2017-10-25 00:17:08 +0000203}
204
djm@openbsd.orgacf559e2017-10-25 00:15:35 +0000205int
206set_rdomain(int fd, const char *name)
207{
Damien Miller43c29bb2017-10-25 13:10:59 +1100208#if defined(HAVE_SYS_SET_RDOMAIN)
209 return sys_set_rdomain(fd, name);
210#elif defined(__OpenBSD__)
djm@openbsd.orgacf559e2017-10-25 00:15:35 +0000211 int rtable;
212 const char *errstr;
213
214 if (name == NULL)
215 return 0; /* default table */
216
217 rtable = (int)strtonum(name, 0, 255, &errstr);
218 if (errstr != NULL) {
219 /* Shouldn't happen */
220 error("Invalid routing domain \"%s\": %s", name, errstr);
221 return -1;
222 }
223 if (setsockopt(fd, SOL_SOCKET, SO_RTABLE,
224 &rtable, sizeof(rtable)) == -1) {
225 error("Failed to set routing domain %d on fd %d: %s",
226 rtable, fd, strerror(errno));
227 return -1;
228 }
229 return 0;
Damien Miller43c29bb2017-10-25 13:10:59 +1100230#else /* defined(__OpenBSD__) */
231 error("Setting routing domain is not supported on this platform");
232 return -1;
233#endif
djm@openbsd.orgacf559e2017-10-25 00:15:35 +0000234}
235
Damien Miller61c51502000-08-18 14:01:04 +1000236/* Characters considered whitespace in strsep calls. */
237#define WHITESPACE " \t\r\n"
Damien Miller306d1182006-03-15 12:05:59 +1100238#define QUOTE "\""
Damien Miller61c51502000-08-18 14:01:04 +1000239
Ben Lindstrom4cc240d2001-07-04 04:46:56 +0000240/* return next token in configuration line */
djm@openbsd.org7082bb52018-06-09 03:01:12 +0000241static char *
242strdelim_internal(char **s, int split_equals)
Damien Miller61c51502000-08-18 14:01:04 +1000243{
djm@openbsd.orgc7c458e2018-03-07 23:53:08 +0000244 char *old;
Damien Miller61c51502000-08-18 14:01:04 +1000245 int wspace = 0;
246
247 if (*s == NULL)
248 return NULL;
249
250 old = *s;
251
djm@openbsd.org7082bb52018-06-09 03:01:12 +0000252 *s = strpbrk(*s,
253 split_equals ? WHITESPACE QUOTE "=" : WHITESPACE QUOTE);
Damien Miller61c51502000-08-18 14:01:04 +1000254 if (*s == NULL)
255 return (old);
256
Damien Miller306d1182006-03-15 12:05:59 +1100257 if (*s[0] == '\"') {
258 memmove(*s, *s + 1, strlen(*s)); /* move nul too */
259 /* Find matching quote */
djm@openbsd.orgc7c458e2018-03-07 23:53:08 +0000260 if ((*s = strpbrk(*s, QUOTE)) == NULL) {
261 return (NULL); /* no matching quote */
262 } else {
263 *s[0] = '\0';
264 *s += strspn(*s + 1, WHITESPACE) + 1;
265 return (old);
Damien Miller306d1182006-03-15 12:05:59 +1100266 }
267 }
268
Damien Miller61c51502000-08-18 14:01:04 +1000269 /* Allow only one '=' to be skipped */
djm@openbsd.org7082bb52018-06-09 03:01:12 +0000270 if (split_equals && *s[0] == '=')
Damien Miller61c51502000-08-18 14:01:04 +1000271 wspace = 1;
272 *s[0] = '\0';
273
Damien Miller306d1182006-03-15 12:05:59 +1100274 /* Skip any extra whitespace after first token */
Damien Miller61c51502000-08-18 14:01:04 +1000275 *s += strspn(*s + 1, WHITESPACE) + 1;
djm@openbsd.org7082bb52018-06-09 03:01:12 +0000276 if (split_equals && *s[0] == '=' && !wspace)
Damien Miller61c51502000-08-18 14:01:04 +1000277 *s += strspn(*s + 1, WHITESPACE) + 1;
278
279 return (old);
280}
Kevin Stevesb6e773a2001-02-04 13:20:36 +0000281
djm@openbsd.org7082bb52018-06-09 03:01:12 +0000282/*
283 * Return next token in configuration line; splts on whitespace or a
284 * single '=' character.
285 */
286char *
287strdelim(char **s)
288{
289 return strdelim_internal(s, 1);
290}
291
292/*
293 * Return next token in configuration line; splts on whitespace only.
294 */
295char *
296strdelimw(char **s)
297{
298 return strdelim_internal(s, 0);
299}
300
Ben Lindstrom086cf212001-03-05 05:56:40 +0000301struct passwd *
302pwcopy(struct passwd *pw)
303{
Damien Miller07d86be2006-03-26 14:19:21 +1100304 struct passwd *copy = xcalloc(1, sizeof(*copy));
Ben Lindstrom40304422001-03-05 06:22:01 +0000305
Ben Lindstrom086cf212001-03-05 05:56:40 +0000306 copy->pw_name = xstrdup(pw->pw_name);
307 copy->pw_passwd = xstrdup(pw->pw_passwd);
Damien Miller6332da22013-04-23 14:25:52 +1000308#ifdef HAVE_STRUCT_PASSWD_PW_GECOS
Ben Lindstrom40304422001-03-05 06:22:01 +0000309 copy->pw_gecos = xstrdup(pw->pw_gecos);
Damien Miller6332da22013-04-23 14:25:52 +1000310#endif
Ben Lindstrom086cf212001-03-05 05:56:40 +0000311 copy->pw_uid = pw->pw_uid;
312 copy->pw_gid = pw->pw_gid;
Damien Miller6332da22013-04-23 14:25:52 +1000313#ifdef HAVE_STRUCT_PASSWD_PW_EXPIRE
Ben Lindstrom3af4d462001-06-21 03:11:27 +0000314 copy->pw_expire = pw->pw_expire;
Kevin Steves82456952001-06-22 21:14:18 +0000315#endif
Damien Miller6332da22013-04-23 14:25:52 +1000316#ifdef HAVE_STRUCT_PASSWD_PW_CHANGE
Ben Lindstrom3af4d462001-06-21 03:11:27 +0000317 copy->pw_change = pw->pw_change;
Kevin Steves82456952001-06-22 21:14:18 +0000318#endif
Damien Miller6332da22013-04-23 14:25:52 +1000319#ifdef HAVE_STRUCT_PASSWD_PW_CLASS
Ben Lindstrom086cf212001-03-05 05:56:40 +0000320 copy->pw_class = xstrdup(pw->pw_class);
Ben Lindstrom0f68db42001-03-05 07:57:09 +0000321#endif
Ben Lindstrom086cf212001-03-05 05:56:40 +0000322 copy->pw_dir = xstrdup(pw->pw_dir);
323 copy->pw_shell = xstrdup(pw->pw_shell);
324 return copy;
325}
326
Ben Lindstrom4cc240d2001-07-04 04:46:56 +0000327/*
328 * Convert ASCII string to TCP/IP port number.
Damien Miller3dc71ad2009-01-28 16:31:22 +1100329 * Port must be >=0 and <=65535.
330 * Return -1 if invalid.
Ben Lindstrom4cc240d2001-07-04 04:46:56 +0000331 */
332int
333a2port(const char *s)
Ben Lindstrom19066a12001-04-12 23:39:26 +0000334{
Damien Miller3dc71ad2009-01-28 16:31:22 +1100335 long long port;
336 const char *errstr;
Ben Lindstrom19066a12001-04-12 23:39:26 +0000337
Damien Miller3dc71ad2009-01-28 16:31:22 +1100338 port = strtonum(s, 0, 65535, &errstr);
339 if (errstr != NULL)
340 return -1;
341 return (int)port;
Ben Lindstrom19066a12001-04-12 23:39:26 +0000342}
343
Damien Millerd27b9472005-12-13 19:29:02 +1100344int
345a2tun(const char *s, int *remote)
346{
347 const char *errstr = NULL;
348 char *sp, *ep;
349 int tun;
350
351 if (remote != NULL) {
Damien Miller7b58e802005-12-13 19:33:19 +1100352 *remote = SSH_TUNID_ANY;
Damien Millerd27b9472005-12-13 19:29:02 +1100353 sp = xstrdup(s);
354 if ((ep = strchr(sp, ':')) == NULL) {
Darren Tuckera627d422013-06-02 07:31:17 +1000355 free(sp);
Damien Millerd27b9472005-12-13 19:29:02 +1100356 return (a2tun(s, NULL));
357 }
358 ep[0] = '\0'; ep++;
359 *remote = a2tun(ep, NULL);
360 tun = a2tun(sp, NULL);
Darren Tuckera627d422013-06-02 07:31:17 +1000361 free(sp);
Damien Miller7b58e802005-12-13 19:33:19 +1100362 return (*remote == SSH_TUNID_ERR ? *remote : tun);
Damien Millerd27b9472005-12-13 19:29:02 +1100363 }
364
365 if (strcasecmp(s, "any") == 0)
Damien Miller7b58e802005-12-13 19:33:19 +1100366 return (SSH_TUNID_ANY);
Damien Millerd27b9472005-12-13 19:29:02 +1100367
Damien Miller7b58e802005-12-13 19:33:19 +1100368 tun = strtonum(s, 0, SSH_TUNID_MAX, &errstr);
369 if (errstr != NULL)
370 return (SSH_TUNID_ERR);
Damien Millerd27b9472005-12-13 19:29:02 +1100371
372 return (tun);
373}
374
Ben Lindstrom1bda4c82001-06-05 19:59:08 +0000375#define SECONDS 1
376#define MINUTES (SECONDS * 60)
377#define HOURS (MINUTES * 60)
378#define DAYS (HOURS * 24)
379#define WEEKS (DAYS * 7)
380
Ben Lindstrom4cc240d2001-07-04 04:46:56 +0000381/*
382 * Convert a time string into seconds; format is
383 * a sequence of:
384 * time[qualifier]
385 *
386 * Valid time qualifiers are:
387 * <none> seconds
388 * s|S seconds
389 * m|M minutes
390 * h|H hours
391 * d|D days
392 * w|W weeks
393 *
394 * Examples:
395 * 90m 90 minutes
396 * 1h30m 90 minutes
397 * 2d 2 days
398 * 1w 1 week
399 *
400 * Return -1 if time string is invalid.
401 */
402long
403convtime(const char *s)
Ben Lindstrom1bda4c82001-06-05 19:59:08 +0000404{
dtucker@openbsd.orgf5746b42017-03-14 00:25:03 +0000405 long total, secs, multiplier = 1;
Ben Lindstrom1bda4c82001-06-05 19:59:08 +0000406 const char *p;
407 char *endp;
408
409 errno = 0;
410 total = 0;
411 p = s;
412
413 if (p == NULL || *p == '\0')
414 return -1;
415
416 while (*p) {
417 secs = strtol(p, &endp, 10);
418 if (p == endp ||
419 (errno == ERANGE && (secs == LONG_MIN || secs == LONG_MAX)) ||
420 secs < 0)
421 return -1;
422
423 switch (*endp++) {
424 case '\0':
425 endp--;
Damien Miller69b72032006-03-26 14:02:35 +1100426 break;
Ben Lindstrom1bda4c82001-06-05 19:59:08 +0000427 case 's':
428 case 'S':
429 break;
430 case 'm':
431 case 'M':
dtucker@openbsd.orgf5746b42017-03-14 00:25:03 +0000432 multiplier = MINUTES;
Ben Lindstrom1bda4c82001-06-05 19:59:08 +0000433 break;
434 case 'h':
435 case 'H':
dtucker@openbsd.orgf5746b42017-03-14 00:25:03 +0000436 multiplier = HOURS;
Ben Lindstrom1bda4c82001-06-05 19:59:08 +0000437 break;
438 case 'd':
439 case 'D':
dtucker@openbsd.orgf5746b42017-03-14 00:25:03 +0000440 multiplier = DAYS;
Ben Lindstrom1bda4c82001-06-05 19:59:08 +0000441 break;
442 case 'w':
443 case 'W':
dtucker@openbsd.orgf5746b42017-03-14 00:25:03 +0000444 multiplier = WEEKS;
Ben Lindstrom1bda4c82001-06-05 19:59:08 +0000445 break;
446 default:
447 return -1;
448 }
dtucker@openbsd.orgc6774d22017-03-14 00:55:37 +0000449 if (secs >= LONG_MAX / multiplier)
dtucker@openbsd.orgf5746b42017-03-14 00:25:03 +0000450 return -1;
451 secs *= multiplier;
dtucker@openbsd.orgc6774d22017-03-14 00:55:37 +0000452 if (total >= LONG_MAX - secs)
dtucker@openbsd.orgf5746b42017-03-14 00:25:03 +0000453 return -1;
Ben Lindstrom1bda4c82001-06-05 19:59:08 +0000454 total += secs;
455 if (total < 0)
456 return -1;
457 p = endp;
458 }
459
460 return total;
461}
462
Damien Millerf91ee4c2005-03-01 21:24:33 +1100463/*
Darren Tuckerda345532006-07-10 23:04:19 +1000464 * Returns a standardized host+port identifier string.
465 * Caller must free returned string.
466 */
467char *
468put_host_port(const char *host, u_short port)
469{
470 char *hoststr;
471
472 if (port == 0 || port == SSH_DEFAULT_PORT)
473 return(xstrdup(host));
474 if (asprintf(&hoststr, "[%s]:%d", host, (int)port) < 0)
475 fatal("put_host_port: asprintf: %s", strerror(errno));
476 debug3("put_host_port: %s", hoststr);
477 return hoststr;
478}
479
480/*
Damien Millerf91ee4c2005-03-01 21:24:33 +1100481 * Search for next delimiter between hostnames/addresses and ports.
482 * Argument may be modified (for termination).
483 * Returns *cp if parsing succeeds.
millert@openbsd.org887669e2017-10-21 23:06:24 +0000484 * *cp is set to the start of the next field, if one was found.
485 * The delimiter char, if present, is stored in delim.
Damien Millerf91ee4c2005-03-01 21:24:33 +1100486 * If this is the last field, *cp is set to NULL.
487 */
millert@openbsd.org887669e2017-10-21 23:06:24 +0000488static char *
489hpdelim2(char **cp, char *delim)
Damien Millerf91ee4c2005-03-01 21:24:33 +1100490{
491 char *s, *old;
492
493 if (cp == NULL || *cp == NULL)
494 return NULL;
495
496 old = s = *cp;
497 if (*s == '[') {
498 if ((s = strchr(s, ']')) == NULL)
499 return NULL;
500 else
501 s++;
502 } else if ((s = strpbrk(s, ":/")) == NULL)
503 s = *cp + strlen(*cp); /* skip to end (see first case below) */
504
505 switch (*s) {
506 case '\0':
507 *cp = NULL; /* no more fields*/
508 break;
Darren Tucker47eede72005-03-14 23:08:12 +1100509
Damien Millerf91ee4c2005-03-01 21:24:33 +1100510 case ':':
511 case '/':
millert@openbsd.org887669e2017-10-21 23:06:24 +0000512 if (delim != NULL)
513 *delim = *s;
Damien Millerf91ee4c2005-03-01 21:24:33 +1100514 *s = '\0'; /* terminate */
515 *cp = s + 1;
516 break;
Darren Tucker47eede72005-03-14 23:08:12 +1100517
Damien Millerf91ee4c2005-03-01 21:24:33 +1100518 default:
519 return NULL;
520 }
521
522 return old;
523}
524
Ben Lindstrom4529b702001-05-03 23:39:53 +0000525char *
millert@openbsd.org887669e2017-10-21 23:06:24 +0000526hpdelim(char **cp)
527{
528 return hpdelim2(cp, NULL);
529}
530
531char *
Ben Lindstrom4529b702001-05-03 23:39:53 +0000532cleanhostname(char *host)
533{
534 if (*host == '[' && host[strlen(host) - 1] == ']') {
535 host[strlen(host) - 1] = '\0';
536 return (host + 1);
537 } else
538 return host;
539}
540
541char *
542colon(char *cp)
543{
544 int flag = 0;
545
546 if (*cp == ':') /* Leading colon is part of file name. */
Damien Miller2e774462010-06-26 09:30:47 +1000547 return NULL;
Ben Lindstrom4529b702001-05-03 23:39:53 +0000548 if (*cp == '[')
549 flag = 1;
550
551 for (; *cp; ++cp) {
552 if (*cp == '@' && *(cp+1) == '[')
553 flag = 1;
554 if (*cp == ']' && *(cp+1) == ':' && flag)
555 return (cp+1);
556 if (*cp == ':' && !flag)
557 return (cp);
558 if (*cp == '/')
Damien Miller2e774462010-06-26 09:30:47 +1000559 return NULL;
Ben Lindstrom4529b702001-05-03 23:39:53 +0000560 }
Damien Miller2e774462010-06-26 09:30:47 +1000561 return NULL;
Ben Lindstrom4529b702001-05-03 23:39:53 +0000562}
563
djm@openbsd.orged877ef2016-07-15 00:24:30 +0000564/*
millert@openbsd.org887669e2017-10-21 23:06:24 +0000565 * Parse a [user@]host:[path] string.
566 * Caller must free returned user, host and path.
567 * Any of the pointer return arguments may be NULL (useful for syntax checking).
568 * If user was not specified then *userp will be set to NULL.
569 * If host was not specified then *hostp will be set to NULL.
570 * If path was not specified then *pathp will be set to ".".
571 * Returns 0 on success, -1 on failure.
572 */
573int
574parse_user_host_path(const char *s, char **userp, char **hostp, char **pathp)
575{
576 char *user = NULL, *host = NULL, *path = NULL;
577 char *sdup, *tmp;
578 int ret = -1;
579
580 if (userp != NULL)
581 *userp = NULL;
582 if (hostp != NULL)
583 *hostp = NULL;
584 if (pathp != NULL)
585 *pathp = NULL;
586
millert@openbsd.orgb9903ee2017-10-24 19:41:45 +0000587 sdup = xstrdup(s);
millert@openbsd.org887669e2017-10-21 23:06:24 +0000588
589 /* Check for remote syntax: [user@]host:[path] */
590 if ((tmp = colon(sdup)) == NULL)
591 goto out;
592
593 /* Extract optional path */
594 *tmp++ = '\0';
595 if (*tmp == '\0')
596 tmp = ".";
597 path = xstrdup(tmp);
598
599 /* Extract optional user and mandatory host */
600 tmp = strrchr(sdup, '@');
601 if (tmp != NULL) {
602 *tmp++ = '\0';
603 host = xstrdup(cleanhostname(tmp));
604 if (*sdup != '\0')
605 user = xstrdup(sdup);
606 } else {
607 host = xstrdup(cleanhostname(sdup));
608 user = NULL;
609 }
610
611 /* Success */
612 if (userp != NULL) {
613 *userp = user;
614 user = NULL;
615 }
616 if (hostp != NULL) {
617 *hostp = host;
618 host = NULL;
millert@openbsd.orgb9903ee2017-10-24 19:41:45 +0000619 }
millert@openbsd.org887669e2017-10-21 23:06:24 +0000620 if (pathp != NULL) {
621 *pathp = path;
622 path = NULL;
millert@openbsd.orgb9903ee2017-10-24 19:41:45 +0000623 }
millert@openbsd.org887669e2017-10-21 23:06:24 +0000624 ret = 0;
625out:
626 free(sdup);
627 free(user);
628 free(host);
629 free(path);
630 return ret;
631}
632
633/*
djm@openbsd.orged877ef2016-07-15 00:24:30 +0000634 * Parse a [user@]host[:port] string.
635 * Caller must free returned user and host.
636 * Any of the pointer return arguments may be NULL (useful for syntax checking).
637 * If user was not specified then *userp will be set to NULL.
638 * If port was not specified then *portp will be -1.
639 * Returns 0 on success, -1 on failure.
640 */
641int
642parse_user_host_port(const char *s, char **userp, char **hostp, int *portp)
643{
644 char *sdup, *cp, *tmp;
645 char *user = NULL, *host = NULL;
646 int port = -1, ret = -1;
647
648 if (userp != NULL)
649 *userp = NULL;
650 if (hostp != NULL)
651 *hostp = NULL;
652 if (portp != NULL)
653 *portp = -1;
654
655 if ((sdup = tmp = strdup(s)) == NULL)
656 return -1;
657 /* Extract optional username */
millert@openbsd.org887669e2017-10-21 23:06:24 +0000658 if ((cp = strrchr(tmp, '@')) != NULL) {
djm@openbsd.orged877ef2016-07-15 00:24:30 +0000659 *cp = '\0';
660 if (*tmp == '\0')
661 goto out;
662 if ((user = strdup(tmp)) == NULL)
663 goto out;
664 tmp = cp + 1;
665 }
666 /* Extract mandatory hostname */
667 if ((cp = hpdelim(&tmp)) == NULL || *cp == '\0')
668 goto out;
669 host = xstrdup(cleanhostname(cp));
670 /* Convert and verify optional port */
671 if (tmp != NULL && *tmp != '\0') {
672 if ((port = a2port(tmp)) <= 0)
673 goto out;
674 }
675 /* Success */
676 if (userp != NULL) {
677 *userp = user;
678 user = NULL;
679 }
680 if (hostp != NULL) {
681 *hostp = host;
682 host = NULL;
683 }
684 if (portp != NULL)
685 *portp = port;
686 ret = 0;
687 out:
688 free(sdup);
689 free(user);
690 free(host);
691 return ret;
692}
693
millert@openbsd.org887669e2017-10-21 23:06:24 +0000694/*
695 * Converts a two-byte hex string to decimal.
696 * Returns the decimal value or -1 for invalid input.
697 */
698static int
699hexchar(const char *s)
700{
701 unsigned char result[2];
702 int i;
703
704 for (i = 0; i < 2; i++) {
705 if (s[i] >= '0' && s[i] <= '9')
706 result[i] = (unsigned char)(s[i] - '0');
707 else if (s[i] >= 'a' && s[i] <= 'f')
708 result[i] = (unsigned char)(s[i] - 'a') + 10;
709 else if (s[i] >= 'A' && s[i] <= 'F')
710 result[i] = (unsigned char)(s[i] - 'A') + 10;
711 else
712 return -1;
713 }
714 return (result[0] << 4) | result[1];
715}
716
717/*
718 * Decode an url-encoded string.
719 * Returns a newly allocated string on success or NULL on failure.
720 */
721static char *
722urldecode(const char *src)
723{
724 char *ret, *dst;
725 int ch;
726
727 ret = xmalloc(strlen(src) + 1);
728 for (dst = ret; *src != '\0'; src++) {
729 switch (*src) {
730 case '+':
731 *dst++ = ' ';
732 break;
733 case '%':
734 if (!isxdigit((unsigned char)src[1]) ||
735 !isxdigit((unsigned char)src[2]) ||
736 (ch = hexchar(src + 1)) == -1) {
737 free(ret);
738 return NULL;
739 }
740 *dst++ = ch;
741 src += 2;
742 break;
743 default:
744 *dst++ = *src;
745 break;
746 }
747 }
748 *dst = '\0';
749
750 return ret;
751}
752
753/*
754 * Parse an (scp|ssh|sftp)://[user@]host[:port][/path] URI.
755 * See https://tools.ietf.org/html/draft-ietf-secsh-scp-sftp-ssh-uri-04
756 * Either user or path may be url-encoded (but not host or port).
757 * Caller must free returned user, host and path.
758 * Any of the pointer return arguments may be NULL (useful for syntax checking)
759 * but the scheme must always be specified.
760 * If user was not specified then *userp will be set to NULL.
761 * If port was not specified then *portp will be -1.
762 * If path was not specified then *pathp will be set to NULL.
763 * Returns 0 on success, 1 if non-uri/wrong scheme, -1 on error/invalid uri.
764 */
765int
766parse_uri(const char *scheme, const char *uri, char **userp, char **hostp,
767 int *portp, char **pathp)
768{
769 char *uridup, *cp, *tmp, ch;
770 char *user = NULL, *host = NULL, *path = NULL;
771 int port = -1, ret = -1;
772 size_t len;
773
774 len = strlen(scheme);
775 if (strncmp(uri, scheme, len) != 0 || strncmp(uri + len, "://", 3) != 0)
776 return 1;
777 uri += len + 3;
778
779 if (userp != NULL)
780 *userp = NULL;
781 if (hostp != NULL)
782 *hostp = NULL;
783 if (portp != NULL)
784 *portp = -1;
785 if (pathp != NULL)
786 *pathp = NULL;
787
788 uridup = tmp = xstrdup(uri);
789
790 /* Extract optional ssh-info (username + connection params) */
791 if ((cp = strchr(tmp, '@')) != NULL) {
792 char *delim;
793
794 *cp = '\0';
795 /* Extract username and connection params */
796 if ((delim = strchr(tmp, ';')) != NULL) {
797 /* Just ignore connection params for now */
798 *delim = '\0';
799 }
800 if (*tmp == '\0') {
801 /* Empty username */
802 goto out;
803 }
804 if ((user = urldecode(tmp)) == NULL)
805 goto out;
806 tmp = cp + 1;
807 }
808
809 /* Extract mandatory hostname */
810 if ((cp = hpdelim2(&tmp, &ch)) == NULL || *cp == '\0')
811 goto out;
812 host = xstrdup(cleanhostname(cp));
813 if (!valid_domain(host, 0, NULL))
814 goto out;
815
816 if (tmp != NULL && *tmp != '\0') {
817 if (ch == ':') {
818 /* Convert and verify port. */
819 if ((cp = strchr(tmp, '/')) != NULL)
820 *cp = '\0';
821 if ((port = a2port(tmp)) <= 0)
822 goto out;
823 tmp = cp ? cp + 1 : NULL;
824 }
825 if (tmp != NULL && *tmp != '\0') {
826 /* Extract optional path */
827 if ((path = urldecode(tmp)) == NULL)
828 goto out;
829 }
830 }
831
832 /* Success */
833 if (userp != NULL) {
834 *userp = user;
835 user = NULL;
836 }
837 if (hostp != NULL) {
838 *hostp = host;
839 host = NULL;
840 }
841 if (portp != NULL)
842 *portp = port;
843 if (pathp != NULL) {
844 *pathp = path;
845 path = NULL;
846 }
847 ret = 0;
848 out:
849 free(uridup);
850 free(user);
851 free(host);
852 free(path);
853 return ret;
854}
855
Ben Lindstrom4cc240d2001-07-04 04:46:56 +0000856/* function to assist building execv() arguments */
Ben Lindstrom387c4722001-05-08 20:27:25 +0000857void
858addargs(arglist *args, char *fmt, ...)
859{
860 va_list ap;
Damien Miller3eec6b72006-01-31 21:49:27 +1100861 char *cp;
Darren Tuckerc7a6fc42004-08-13 21:18:00 +1000862 u_int nalloc;
Damien Miller3eec6b72006-01-31 21:49:27 +1100863 int r;
Ben Lindstrom387c4722001-05-08 20:27:25 +0000864
865 va_start(ap, fmt);
Damien Miller3eec6b72006-01-31 21:49:27 +1100866 r = vasprintf(&cp, fmt, ap);
Ben Lindstrom387c4722001-05-08 20:27:25 +0000867 va_end(ap);
Damien Miller3eec6b72006-01-31 21:49:27 +1100868 if (r == -1)
869 fatal("addargs: argument too long");
Ben Lindstrom387c4722001-05-08 20:27:25 +0000870
Darren Tuckerfb16b242003-09-22 21:04:23 +1000871 nalloc = args->nalloc;
Ben Lindstrom387c4722001-05-08 20:27:25 +0000872 if (args->list == NULL) {
Darren Tuckerfb16b242003-09-22 21:04:23 +1000873 nalloc = 32;
Ben Lindstrom387c4722001-05-08 20:27:25 +0000874 args->num = 0;
Darren Tuckerfb16b242003-09-22 21:04:23 +1000875 } else if (args->num+2 >= nalloc)
876 nalloc *= 2;
Ben Lindstrom387c4722001-05-08 20:27:25 +0000877
deraadt@openbsd.org9e509d42017-05-31 09:15:42 +0000878 args->list = xrecallocarray(args->list, args->nalloc, nalloc, sizeof(char *));
Darren Tuckerfb16b242003-09-22 21:04:23 +1000879 args->nalloc = nalloc;
Damien Miller3eec6b72006-01-31 21:49:27 +1100880 args->list[args->num++] = cp;
Ben Lindstrom387c4722001-05-08 20:27:25 +0000881 args->list[args->num] = NULL;
882}
Darren Tucker22cc7412004-12-06 22:47:41 +1100883
Damien Miller3eec6b72006-01-31 21:49:27 +1100884void
885replacearg(arglist *args, u_int which, char *fmt, ...)
886{
887 va_list ap;
888 char *cp;
889 int r;
890
891 va_start(ap, fmt);
892 r = vasprintf(&cp, fmt, ap);
893 va_end(ap);
894 if (r == -1)
895 fatal("replacearg: argument too long");
896
897 if (which >= args->num)
898 fatal("replacearg: tried to replace invalid arg %d >= %d",
899 which, args->num);
Darren Tuckera627d422013-06-02 07:31:17 +1000900 free(args->list[which]);
Damien Miller3eec6b72006-01-31 21:49:27 +1100901 args->list[which] = cp;
902}
903
904void
905freeargs(arglist *args)
906{
907 u_int i;
908
909 if (args->list != NULL) {
910 for (i = 0; i < args->num; i++)
Darren Tuckera627d422013-06-02 07:31:17 +1000911 free(args->list[i]);
912 free(args->list);
Damien Miller3eec6b72006-01-31 21:49:27 +1100913 args->nalloc = args->num = 0;
914 args->list = NULL;
915 }
916}
917
Darren Tucker22cc7412004-12-06 22:47:41 +1100918/*
Damien Miller5fd38c02005-05-26 12:02:14 +1000919 * Expands tildes in the file name. Returns data allocated by xmalloc.
920 * Warning: this calls getpw*.
921 */
922char *
923tilde_expand_filename(const char *filename, uid_t uid)
924{
Darren Tucker2ca51bf2013-05-16 20:22:46 +1000925 const char *path, *sep;
926 char user[128], *ret;
Damien Miller5fd38c02005-05-26 12:02:14 +1000927 struct passwd *pw;
Damien Millereccb9de2005-06-17 12:59:34 +1000928 u_int len, slash;
Damien Miller5fd38c02005-05-26 12:02:14 +1000929
930 if (*filename != '~')
931 return (xstrdup(filename));
932 filename++;
933
934 path = strchr(filename, '/');
935 if (path != NULL && path > filename) { /* ~user/path */
Damien Millereccb9de2005-06-17 12:59:34 +1000936 slash = path - filename;
937 if (slash > sizeof(user) - 1)
Damien Miller5fd38c02005-05-26 12:02:14 +1000938 fatal("tilde_expand_filename: ~username too long");
Damien Millereccb9de2005-06-17 12:59:34 +1000939 memcpy(user, filename, slash);
940 user[slash] = '\0';
Damien Miller5fd38c02005-05-26 12:02:14 +1000941 if ((pw = getpwnam(user)) == NULL)
942 fatal("tilde_expand_filename: No such user %s", user);
943 } else if ((pw = getpwuid(uid)) == NULL) /* ~/path */
Darren Tucker7517b5b2008-06-13 14:48:59 +1000944 fatal("tilde_expand_filename: No such uid %ld", (long)uid);
Damien Miller5fd38c02005-05-26 12:02:14 +1000945
Damien Miller5fd38c02005-05-26 12:02:14 +1000946 /* Make sure directory has a trailing '/' */
947 len = strlen(pw->pw_dir);
Darren Tucker026d9db2013-05-16 20:23:52 +1000948 if (len == 0 || pw->pw_dir[len - 1] != '/')
Darren Tucker2ca51bf2013-05-16 20:22:46 +1000949 sep = "/";
950 else
951 sep = "";
Damien Miller5fd38c02005-05-26 12:02:14 +1000952
953 /* Skip leading '/' from specified path */
954 if (path != NULL)
955 filename = path + 1;
Darren Tucker2ca51bf2013-05-16 20:22:46 +1000956
deraadt@openbsd.org2ae4f332015-01-16 06:40:12 +0000957 if (xasprintf(&ret, "%s%s%s", pw->pw_dir, sep, filename) >= PATH_MAX)
Damien Miller5fd38c02005-05-26 12:02:14 +1000958 fatal("tilde_expand_filename: Path too long");
959
Darren Tucker2ca51bf2013-05-16 20:22:46 +1000960 return (ret);
Damien Miller5fd38c02005-05-26 12:02:14 +1000961}
962
963/*
Damien Miller6476cad2005-06-16 13:18:34 +1000964 * Expand a string with a set of %[char] escapes. A number of escapes may be
965 * specified as (char *escape_chars, char *replacement) pairs. The list must
Darren Tuckerbee73d52005-07-14 17:05:02 +1000966 * be terminated by a NULL escape_char. Returns replaced string in memory
Damien Miller6476cad2005-06-16 13:18:34 +1000967 * allocated by xmalloc.
968 */
969char *
970percent_expand(const char *string, ...)
971{
972#define EXPAND_MAX_KEYS 16
Darren Tucker70d87692010-01-08 18:49:16 +1100973 u_int num_keys, i, j;
Damien Miller6476cad2005-06-16 13:18:34 +1000974 struct {
975 const char *key;
976 const char *repl;
977 } keys[EXPAND_MAX_KEYS];
Damien Miller6476cad2005-06-16 13:18:34 +1000978 char buf[4096];
979 va_list ap;
980
981 /* Gather keys */
982 va_start(ap, string);
983 for (num_keys = 0; num_keys < EXPAND_MAX_KEYS; num_keys++) {
984 keys[num_keys].key = va_arg(ap, char *);
985 if (keys[num_keys].key == NULL)
986 break;
987 keys[num_keys].repl = va_arg(ap, char *);
988 if (keys[num_keys].repl == NULL)
Darren Tucker70d87692010-01-08 18:49:16 +1100989 fatal("%s: NULL replacement", __func__);
Damien Miller6476cad2005-06-16 13:18:34 +1000990 }
Darren Tucker70d87692010-01-08 18:49:16 +1100991 if (num_keys == EXPAND_MAX_KEYS && va_arg(ap, char *) != NULL)
992 fatal("%s: too many keys", __func__);
Damien Miller6476cad2005-06-16 13:18:34 +1000993 va_end(ap);
994
Damien Miller6476cad2005-06-16 13:18:34 +1000995 /* Expand string */
996 *buf = '\0';
997 for (i = 0; *string != '\0'; string++) {
998 if (*string != '%') {
999 append:
1000 buf[i++] = *string;
1001 if (i >= sizeof(buf))
Darren Tucker70d87692010-01-08 18:49:16 +11001002 fatal("%s: string too long", __func__);
Damien Miller6476cad2005-06-16 13:18:34 +10001003 buf[i] = '\0';
1004 continue;
1005 }
1006 string++;
Darren Tucker70d87692010-01-08 18:49:16 +11001007 /* %% case */
Damien Miller6476cad2005-06-16 13:18:34 +10001008 if (*string == '%')
1009 goto append;
tobias@openbsd.org8b56e592015-12-04 21:51:06 +00001010 if (*string == '\0')
1011 fatal("%s: invalid format", __func__);
Damien Miller6476cad2005-06-16 13:18:34 +10001012 for (j = 0; j < num_keys; j++) {
1013 if (strchr(keys[j].key, *string) != NULL) {
1014 i = strlcat(buf, keys[j].repl, sizeof(buf));
1015 if (i >= sizeof(buf))
Darren Tucker70d87692010-01-08 18:49:16 +11001016 fatal("%s: string too long", __func__);
Damien Miller6476cad2005-06-16 13:18:34 +10001017 break;
1018 }
1019 }
1020 if (j >= num_keys)
Darren Tucker70d87692010-01-08 18:49:16 +11001021 fatal("%s: unknown key %%%c", __func__, *string);
Damien Miller6476cad2005-06-16 13:18:34 +10001022 }
1023 return (xstrdup(buf));
1024#undef EXPAND_MAX_KEYS
1025}
1026
Damien Millerd27b9472005-12-13 19:29:02 +11001027int
djm@openbsd.orgb7548b12017-10-23 05:08:00 +00001028tun_open(int tun, int mode, char **ifname)
Damien Millerd27b9472005-12-13 19:29:02 +11001029{
Damien Miller62a31c92005-12-13 20:44:13 +11001030#if defined(CUSTOM_SYS_TUN_OPEN)
djm@openbsd.orgb7548b12017-10-23 05:08:00 +00001031 return (sys_tun_open(tun, mode, ifname));
Damien Miller2dcddbf2006-01-01 19:47:05 +11001032#elif defined(SSH_TUN_OPENBSD)
Damien Miller7b58e802005-12-13 19:33:19 +11001033 struct ifreq ifr;
Damien Millerd27b9472005-12-13 19:29:02 +11001034 char name[100];
Damien Miller7b58e802005-12-13 19:33:19 +11001035 int fd = -1, sock;
sthen@openbsd.orga820a862015-10-24 08:34:09 +00001036 const char *tunbase = "tun";
1037
djm@openbsd.orgb7548b12017-10-23 05:08:00 +00001038 if (ifname != NULL)
1039 *ifname = NULL;
1040
sthen@openbsd.orga820a862015-10-24 08:34:09 +00001041 if (mode == SSH_TUNMODE_ETHERNET)
1042 tunbase = "tap";
Damien Millerd27b9472005-12-13 19:29:02 +11001043
Damien Miller7b58e802005-12-13 19:33:19 +11001044 /* Open the tunnel device */
1045 if (tun <= SSH_TUNID_MAX) {
sthen@openbsd.orga820a862015-10-24 08:34:09 +00001046 snprintf(name, sizeof(name), "/dev/%s%d", tunbase, tun);
Damien Miller7b58e802005-12-13 19:33:19 +11001047 fd = open(name, O_RDWR);
1048 } else if (tun == SSH_TUNID_ANY) {
1049 for (tun = 100; tun >= 0; tun--) {
sthen@openbsd.orga820a862015-10-24 08:34:09 +00001050 snprintf(name, sizeof(name), "/dev/%s%d",
1051 tunbase, tun);
Damien Miller7b58e802005-12-13 19:33:19 +11001052 if ((fd = open(name, O_RDWR)) >= 0)
1053 break;
Damien Millerd27b9472005-12-13 19:29:02 +11001054 }
1055 } else {
Damien Millera210d522006-01-02 23:40:30 +11001056 debug("%s: invalid tunnel %u", __func__, tun);
djm@openbsd.org2905d6f2015-10-07 00:54:06 +00001057 return -1;
Damien Millerd27b9472005-12-13 19:29:02 +11001058 }
Damien Miller7b58e802005-12-13 19:33:19 +11001059
1060 if (fd < 0) {
djm@openbsd.org2905d6f2015-10-07 00:54:06 +00001061 debug("%s: %s open: %s", __func__, name, strerror(errno));
1062 return -1;
Damien Miller7b58e802005-12-13 19:33:19 +11001063 }
1064
1065 debug("%s: %s mode %d fd %d", __func__, name, mode, fd);
1066
sthen@openbsd.orga820a862015-10-24 08:34:09 +00001067 /* Bring interface up if it is not already */
1068 snprintf(ifr.ifr_name, sizeof(ifr.ifr_name), "%s%d", tunbase, tun);
1069 if ((sock = socket(PF_UNIX, SOCK_STREAM, 0)) == -1)
Damien Miller7b58e802005-12-13 19:33:19 +11001070 goto failed;
1071
djm@openbsd.org2905d6f2015-10-07 00:54:06 +00001072 if (ioctl(sock, SIOCGIFFLAGS, &ifr) == -1) {
1073 debug("%s: get interface %s flags: %s", __func__,
1074 ifr.ifr_name, strerror(errno));
Damien Miller7b58e802005-12-13 19:33:19 +11001075 goto failed;
djm@openbsd.org2905d6f2015-10-07 00:54:06 +00001076 }
Damien Millera1d9a182006-01-02 23:41:21 +11001077
djm@openbsd.org2905d6f2015-10-07 00:54:06 +00001078 if (!(ifr.ifr_flags & IFF_UP)) {
1079 ifr.ifr_flags |= IFF_UP;
1080 if (ioctl(sock, SIOCSIFFLAGS, &ifr) == -1) {
1081 debug("%s: activate interface %s: %s", __func__,
1082 ifr.ifr_name, strerror(errno));
1083 goto failed;
1084 }
1085 }
Damien Miller7b58e802005-12-13 19:33:19 +11001086
djm@openbsd.orgb7548b12017-10-23 05:08:00 +00001087 if (ifname != NULL)
1088 *ifname = xstrdup(ifr.ifr_name);
1089
Damien Miller7b58e802005-12-13 19:33:19 +11001090 close(sock);
djm@openbsd.org2905d6f2015-10-07 00:54:06 +00001091 return fd;
Damien Miller7b58e802005-12-13 19:33:19 +11001092
1093 failed:
1094 if (fd >= 0)
1095 close(fd);
1096 if (sock >= 0)
1097 close(sock);
djm@openbsd.org2905d6f2015-10-07 00:54:06 +00001098 return -1;
Damien Miller62a31c92005-12-13 20:44:13 +11001099#else
1100 error("Tunnel interfaces are not supported on this platform");
1101 return (-1);
1102#endif
Damien Millerd27b9472005-12-13 19:29:02 +11001103}
1104
Darren Tuckerce321d82005-10-03 18:11:24 +10001105void
1106sanitise_stdfd(void)
1107{
Damien Miller72c5b7d2006-01-06 14:50:44 +11001108 int nullfd, dupfd;
Darren Tuckerce321d82005-10-03 18:11:24 +10001109
Damien Miller72c5b7d2006-01-06 14:50:44 +11001110 if ((nullfd = dupfd = open(_PATH_DEVNULL, O_RDWR)) == -1) {
Damien Miller9eab9562009-02-22 08:47:02 +11001111 fprintf(stderr, "Couldn't open /dev/null: %s\n",
1112 strerror(errno));
Darren Tuckerce321d82005-10-03 18:11:24 +10001113 exit(1);
1114 }
krw@openbsd.org574def02016-04-02 14:37:42 +00001115 while (++dupfd <= STDERR_FILENO) {
1116 /* Only populate closed fds. */
1117 if (fcntl(dupfd, F_GETFL) == -1 && errno == EBADF) {
1118 if (dup2(nullfd, dupfd) == -1) {
1119 fprintf(stderr, "dup2: %s\n", strerror(errno));
1120 exit(1);
1121 }
Darren Tuckerce321d82005-10-03 18:11:24 +10001122 }
Darren Tuckerce321d82005-10-03 18:11:24 +10001123 }
krw@openbsd.org574def02016-04-02 14:37:42 +00001124 if (nullfd > STDERR_FILENO)
Darren Tuckerce321d82005-10-03 18:11:24 +10001125 close(nullfd);
1126}
1127
Damien Miller13390022005-07-06 09:44:19 +10001128char *
Damien Miller3f941882006-03-31 23:13:02 +11001129tohex(const void *vp, size_t l)
Damien Miller13390022005-07-06 09:44:19 +10001130{
Damien Miller3f941882006-03-31 23:13:02 +11001131 const u_char *p = (const u_char *)vp;
Damien Miller13390022005-07-06 09:44:19 +10001132 char b[3], *r;
Damien Miller3f941882006-03-31 23:13:02 +11001133 size_t i, hl;
1134
1135 if (l > 65536)
1136 return xstrdup("tohex: length > 65536");
Damien Miller13390022005-07-06 09:44:19 +10001137
1138 hl = l * 2 + 1;
Damien Miller07d86be2006-03-26 14:19:21 +11001139 r = xcalloc(1, hl);
Damien Miller13390022005-07-06 09:44:19 +10001140 for (i = 0; i < l; i++) {
Damien Miller3f941882006-03-31 23:13:02 +11001141 snprintf(b, sizeof(b), "%02x", p[i]);
Damien Miller13390022005-07-06 09:44:19 +10001142 strlcat(r, b, hl);
1143 }
1144 return (r);
1145}
1146
Damien Miller3f941882006-03-31 23:13:02 +11001147u_int64_t
1148get_u64(const void *vp)
1149{
1150 const u_char *p = (const u_char *)vp;
1151 u_int64_t v;
1152
1153 v = (u_int64_t)p[0] << 56;
1154 v |= (u_int64_t)p[1] << 48;
1155 v |= (u_int64_t)p[2] << 40;
1156 v |= (u_int64_t)p[3] << 32;
1157 v |= (u_int64_t)p[4] << 24;
1158 v |= (u_int64_t)p[5] << 16;
1159 v |= (u_int64_t)p[6] << 8;
1160 v |= (u_int64_t)p[7];
1161
1162 return (v);
1163}
1164
1165u_int32_t
1166get_u32(const void *vp)
1167{
1168 const u_char *p = (const u_char *)vp;
1169 u_int32_t v;
1170
1171 v = (u_int32_t)p[0] << 24;
1172 v |= (u_int32_t)p[1] << 16;
1173 v |= (u_int32_t)p[2] << 8;
1174 v |= (u_int32_t)p[3];
1175
1176 return (v);
1177}
1178
Damien Miller88856692014-04-20 13:33:19 +10001179u_int32_t
1180get_u32_le(const void *vp)
1181{
1182 const u_char *p = (const u_char *)vp;
1183 u_int32_t v;
1184
1185 v = (u_int32_t)p[0];
1186 v |= (u_int32_t)p[1] << 8;
1187 v |= (u_int32_t)p[2] << 16;
1188 v |= (u_int32_t)p[3] << 24;
1189
1190 return (v);
1191}
1192
Damien Miller3f941882006-03-31 23:13:02 +11001193u_int16_t
1194get_u16(const void *vp)
1195{
1196 const u_char *p = (const u_char *)vp;
1197 u_int16_t v;
1198
1199 v = (u_int16_t)p[0] << 8;
1200 v |= (u_int16_t)p[1];
1201
1202 return (v);
1203}
1204
1205void
1206put_u64(void *vp, u_int64_t v)
1207{
1208 u_char *p = (u_char *)vp;
1209
1210 p[0] = (u_char)(v >> 56) & 0xff;
1211 p[1] = (u_char)(v >> 48) & 0xff;
1212 p[2] = (u_char)(v >> 40) & 0xff;
1213 p[3] = (u_char)(v >> 32) & 0xff;
1214 p[4] = (u_char)(v >> 24) & 0xff;
1215 p[5] = (u_char)(v >> 16) & 0xff;
1216 p[6] = (u_char)(v >> 8) & 0xff;
1217 p[7] = (u_char)v & 0xff;
1218}
1219
1220void
1221put_u32(void *vp, u_int32_t v)
1222{
1223 u_char *p = (u_char *)vp;
1224
1225 p[0] = (u_char)(v >> 24) & 0xff;
1226 p[1] = (u_char)(v >> 16) & 0xff;
1227 p[2] = (u_char)(v >> 8) & 0xff;
1228 p[3] = (u_char)v & 0xff;
1229}
1230
Damien Miller88856692014-04-20 13:33:19 +10001231void
1232put_u32_le(void *vp, u_int32_t v)
1233{
1234 u_char *p = (u_char *)vp;
1235
1236 p[0] = (u_char)v & 0xff;
1237 p[1] = (u_char)(v >> 8) & 0xff;
1238 p[2] = (u_char)(v >> 16) & 0xff;
1239 p[3] = (u_char)(v >> 24) & 0xff;
1240}
Damien Miller3f941882006-03-31 23:13:02 +11001241
1242void
1243put_u16(void *vp, u_int16_t v)
1244{
1245 u_char *p = (u_char *)vp;
1246
1247 p[0] = (u_char)(v >> 8) & 0xff;
1248 p[1] = (u_char)v & 0xff;
1249}
Darren Tucker3fc464e2008-06-13 06:42:45 +10001250
1251void
1252ms_subtract_diff(struct timeval *start, int *ms)
1253{
1254 struct timeval diff, finish;
1255
dtucker@openbsd.org@openbsd.org5db6fbf2017-11-25 06:46:22 +00001256 monotime_tv(&finish);
1257 timersub(&finish, start, &diff);
Darren Tucker3fc464e2008-06-13 06:42:45 +10001258 *ms -= (diff.tv_sec * 1000) + (diff.tv_usec / 1000);
1259}
1260
1261void
1262ms_to_timeval(struct timeval *tv, int ms)
1263{
1264 if (ms < 0)
1265 ms = 0;
1266 tv->tv_sec = ms / 1000;
1267 tv->tv_usec = (ms % 1000) * 1000;
1268}
1269
dtucker@openbsd.org@openbsd.org5db6fbf2017-11-25 06:46:22 +00001270void
1271monotime_ts(struct timespec *ts)
Darren Tuckerb759c9c2013-06-02 07:46:16 +10001272{
dtucker@openbsd.org@openbsd.org5db6fbf2017-11-25 06:46:22 +00001273 struct timeval tv;
1274#if defined(HAVE_CLOCK_GETTIME) && (defined(CLOCK_BOOTTIME) || \
1275 defined(CLOCK_MONOTONIC) || defined(CLOCK_REALTIME))
Darren Tucker94396b72013-08-08 11:52:37 +10001276 static int gettime_failed = 0;
Darren Tuckerb759c9c2013-06-02 07:46:16 +10001277
Darren Tucker94396b72013-08-08 11:52:37 +10001278 if (!gettime_failed) {
dtucker@openbsd.org@openbsd.org5db6fbf2017-11-25 06:46:22 +00001279# ifdef CLOCK_BOOTTIME
1280 if (clock_gettime(CLOCK_BOOTTIME, ts) == 0)
1281 return;
1282# endif /* CLOCK_BOOTTIME */
1283# ifdef CLOCK_MONOTONIC
1284 if (clock_gettime(CLOCK_MONOTONIC, ts) == 0)
1285 return;
1286# endif /* CLOCK_MONOTONIC */
1287# ifdef CLOCK_REALTIME
1288 /* Not monotonic, but we're almost out of options here. */
1289 if (clock_gettime(CLOCK_REALTIME, ts) == 0)
1290 return;
1291# endif /* CLOCK_REALTIME */
Darren Tucker94396b72013-08-08 11:52:37 +10001292 debug3("clock_gettime: %s", strerror(errno));
1293 gettime_failed = 1;
1294 }
dtucker@openbsd.org@openbsd.org5db6fbf2017-11-25 06:46:22 +00001295#endif /* HAVE_CLOCK_GETTIME && (BOOTTIME || MONOTONIC || REALTIME) */
1296 gettimeofday(&tv, NULL);
1297 ts->tv_sec = tv.tv_sec;
1298 ts->tv_nsec = (long)tv.tv_usec * 1000;
1299}
Darren Tucker94396b72013-08-08 11:52:37 +10001300
dtucker@openbsd.org@openbsd.org5db6fbf2017-11-25 06:46:22 +00001301void
1302monotime_tv(struct timeval *tv)
1303{
1304 struct timespec ts;
1305
1306 monotime_ts(&ts);
1307 tv->tv_sec = ts.tv_sec;
1308 tv->tv_usec = ts.tv_nsec / 1000;
1309}
1310
1311time_t
1312monotime(void)
1313{
1314 struct timespec ts;
1315
1316 monotime_ts(&ts);
1317 return ts.tv_sec;
Darren Tuckerb759c9c2013-06-02 07:46:16 +10001318}
1319
dtucker@openbsd.orgb8d4eaf2016-03-02 22:42:40 +00001320double
1321monotime_double(void)
1322{
1323 struct timespec ts;
1324
dtucker@openbsd.org@openbsd.org5db6fbf2017-11-25 06:46:22 +00001325 monotime_ts(&ts);
1326 return ts.tv_sec + ((double)ts.tv_nsec / 1000000000);
dtucker@openbsd.orgb8d4eaf2016-03-02 22:42:40 +00001327}
1328
Damien Miller65e42f82010-09-24 22:15:11 +10001329void
1330bandwidth_limit_init(struct bwlimit *bw, u_int64_t kbps, size_t buflen)
1331{
1332 bw->buflen = buflen;
1333 bw->rate = kbps;
1334 bw->thresh = bw->rate;
1335 bw->lamt = 0;
1336 timerclear(&bw->bwstart);
1337 timerclear(&bw->bwend);
1338}
1339
1340/* Callback from read/write loop to insert bandwidth-limiting delays */
1341void
1342bandwidth_limit(struct bwlimit *bw, size_t read_len)
1343{
1344 u_int64_t waitlen;
1345 struct timespec ts, rm;
1346
1347 if (!timerisset(&bw->bwstart)) {
dtucker@openbsd.org@openbsd.org5db6fbf2017-11-25 06:46:22 +00001348 monotime_tv(&bw->bwstart);
Damien Miller65e42f82010-09-24 22:15:11 +10001349 return;
1350 }
1351
1352 bw->lamt += read_len;
1353 if (bw->lamt < bw->thresh)
1354 return;
1355
dtucker@openbsd.org@openbsd.org5db6fbf2017-11-25 06:46:22 +00001356 monotime_tv(&bw->bwend);
Damien Miller65e42f82010-09-24 22:15:11 +10001357 timersub(&bw->bwend, &bw->bwstart, &bw->bwend);
1358 if (!timerisset(&bw->bwend))
1359 return;
1360
1361 bw->lamt *= 8;
1362 waitlen = (double)1000000L * bw->lamt / bw->rate;
1363
1364 bw->bwstart.tv_sec = waitlen / 1000000L;
1365 bw->bwstart.tv_usec = waitlen % 1000000L;
1366
1367 if (timercmp(&bw->bwstart, &bw->bwend, >)) {
1368 timersub(&bw->bwstart, &bw->bwend, &bw->bwend);
1369
1370 /* Adjust the wait time */
1371 if (bw->bwend.tv_sec) {
1372 bw->thresh /= 2;
1373 if (bw->thresh < bw->buflen / 4)
1374 bw->thresh = bw->buflen / 4;
1375 } else if (bw->bwend.tv_usec < 10000) {
1376 bw->thresh *= 2;
1377 if (bw->thresh > bw->buflen * 8)
1378 bw->thresh = bw->buflen * 8;
1379 }
1380
1381 TIMEVAL_TO_TIMESPEC(&bw->bwend, &ts);
1382 while (nanosleep(&ts, &rm) == -1) {
1383 if (errno != EINTR)
1384 break;
1385 ts = rm;
1386 }
1387 }
1388
1389 bw->lamt = 0;
dtucker@openbsd.org@openbsd.org5db6fbf2017-11-25 06:46:22 +00001390 monotime_tv(&bw->bwstart);
Damien Miller65e42f82010-09-24 22:15:11 +10001391}
Damien Miller0dac6fb2010-11-20 15:19:38 +11001392
Damien Miller2cd62932010-12-01 11:50:35 +11001393/* Make a template filename for mk[sd]temp() */
1394void
1395mktemp_proto(char *s, size_t len)
1396{
1397 const char *tmpdir;
1398 int r;
1399
1400 if ((tmpdir = getenv("TMPDIR")) != NULL) {
1401 r = snprintf(s, len, "%s/ssh-XXXXXXXXXXXX", tmpdir);
1402 if (r > 0 && (size_t)r < len)
1403 return;
1404 }
1405 r = snprintf(s, len, "/tmp/ssh-XXXXXXXXXXXX");
1406 if (r < 0 || (size_t)r >= len)
1407 fatal("%s: template string too short", __func__);
1408}
1409
Damien Miller0dac6fb2010-11-20 15:19:38 +11001410static const struct {
1411 const char *name;
1412 int value;
1413} ipqos[] = {
djm@openbsd.org51676ec2017-07-23 23:37:02 +00001414 { "none", INT_MAX }, /* can't use 0 here; that's CS0 */
Damien Miller0dac6fb2010-11-20 15:19:38 +11001415 { "af11", IPTOS_DSCP_AF11 },
1416 { "af12", IPTOS_DSCP_AF12 },
1417 { "af13", IPTOS_DSCP_AF13 },
Damien Miller2918e032011-09-22 21:34:35 +10001418 { "af21", IPTOS_DSCP_AF21 },
Damien Miller0dac6fb2010-11-20 15:19:38 +11001419 { "af22", IPTOS_DSCP_AF22 },
1420 { "af23", IPTOS_DSCP_AF23 },
1421 { "af31", IPTOS_DSCP_AF31 },
1422 { "af32", IPTOS_DSCP_AF32 },
1423 { "af33", IPTOS_DSCP_AF33 },
1424 { "af41", IPTOS_DSCP_AF41 },
1425 { "af42", IPTOS_DSCP_AF42 },
1426 { "af43", IPTOS_DSCP_AF43 },
1427 { "cs0", IPTOS_DSCP_CS0 },
1428 { "cs1", IPTOS_DSCP_CS1 },
1429 { "cs2", IPTOS_DSCP_CS2 },
1430 { "cs3", IPTOS_DSCP_CS3 },
1431 { "cs4", IPTOS_DSCP_CS4 },
1432 { "cs5", IPTOS_DSCP_CS5 },
1433 { "cs6", IPTOS_DSCP_CS6 },
1434 { "cs7", IPTOS_DSCP_CS7 },
1435 { "ef", IPTOS_DSCP_EF },
1436 { "lowdelay", IPTOS_LOWDELAY },
1437 { "throughput", IPTOS_THROUGHPUT },
1438 { "reliability", IPTOS_RELIABILITY },
1439 { NULL, -1 }
1440};
1441
1442int
1443parse_ipqos(const char *cp)
1444{
1445 u_int i;
1446 char *ep;
1447 long val;
1448
1449 if (cp == NULL)
1450 return -1;
1451 for (i = 0; ipqos[i].name != NULL; i++) {
1452 if (strcasecmp(cp, ipqos[i].name) == 0)
1453 return ipqos[i].value;
1454 }
1455 /* Try parsing as an integer */
1456 val = strtol(cp, &ep, 0);
1457 if (*cp == '\0' || *ep != '\0' || val < 0 || val > 255)
1458 return -1;
1459 return val;
1460}
1461
Damien Miller91475862011-05-05 14:14:34 +10001462const char *
1463iptos2str(int iptos)
1464{
1465 int i;
1466 static char iptos_str[sizeof "0xff"];
1467
1468 for (i = 0; ipqos[i].name != NULL; i++) {
1469 if (ipqos[i].value == iptos)
1470 return ipqos[i].name;
1471 }
1472 snprintf(iptos_str, sizeof iptos_str, "0x%02x", iptos);
1473 return iptos_str;
1474}
Damien Millere9fc72e2013-10-15 12:14:12 +11001475
1476void
1477lowercase(char *s)
1478{
1479 for (; *s; s++)
1480 *s = tolower((u_char)*s);
1481}
Damien Miller7acefbb2014-07-18 14:11:24 +10001482
1483int
1484unix_listener(const char *path, int backlog, int unlink_first)
1485{
1486 struct sockaddr_un sunaddr;
1487 int saved_errno, sock;
1488
1489 memset(&sunaddr, 0, sizeof(sunaddr));
1490 sunaddr.sun_family = AF_UNIX;
djm@openbsd.org155072f2017-12-08 02:13:02 +00001491 if (strlcpy(sunaddr.sun_path, path,
1492 sizeof(sunaddr.sun_path)) >= sizeof(sunaddr.sun_path)) {
1493 error("%s: path \"%s\" too long for Unix domain socket",
1494 __func__, path);
Damien Miller7acefbb2014-07-18 14:11:24 +10001495 errno = ENAMETOOLONG;
1496 return -1;
1497 }
1498
1499 sock = socket(PF_UNIX, SOCK_STREAM, 0);
1500 if (sock < 0) {
1501 saved_errno = errno;
djm@openbsd.org155072f2017-12-08 02:13:02 +00001502 error("%s: socket: %.100s", __func__, strerror(errno));
Damien Miller7acefbb2014-07-18 14:11:24 +10001503 errno = saved_errno;
1504 return -1;
1505 }
1506 if (unlink_first == 1) {
1507 if (unlink(path) != 0 && errno != ENOENT)
1508 error("unlink(%s): %.100s", path, strerror(errno));
1509 }
1510 if (bind(sock, (struct sockaddr *)&sunaddr, sizeof(sunaddr)) < 0) {
1511 saved_errno = errno;
djm@openbsd.org155072f2017-12-08 02:13:02 +00001512 error("%s: cannot bind to path %s: %s",
1513 __func__, path, strerror(errno));
djm@openbsd.orgfd4eeee2017-12-08 02:14:33 +00001514 close(sock);
Damien Miller7acefbb2014-07-18 14:11:24 +10001515 errno = saved_errno;
1516 return -1;
1517 }
1518 if (listen(sock, backlog) < 0) {
1519 saved_errno = errno;
djm@openbsd.org155072f2017-12-08 02:13:02 +00001520 error("%s: cannot listen on path %s: %s",
1521 __func__, path, strerror(errno));
djm@openbsd.orgfd4eeee2017-12-08 02:14:33 +00001522 close(sock);
1523 unlink(path);
Damien Miller7acefbb2014-07-18 14:11:24 +10001524 errno = saved_errno;
1525 return -1;
1526 }
1527 return sock;
1528}
Damien Miller46878022014-08-30 03:29:19 +10001529
Damien Miller04ee0f82009-11-18 17:48:30 +11001530void
1531sock_set_v6only(int s)
1532{
Damien Millerd86a3ba2015-12-09 09:18:45 +11001533#if defined(IPV6_V6ONLY) && !defined(__OpenBSD__)
Damien Miller04ee0f82009-11-18 17:48:30 +11001534 int on = 1;
1535
1536 debug3("%s: set socket %d IPV6_V6ONLY", __func__, s);
1537 if (setsockopt(s, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof(on)) == -1)
1538 error("setsockopt IPV6_V6ONLY: %s", strerror(errno));
1539#endif
1540}
djm@openbsd.org0ccbd5e2016-04-06 06:42:17 +00001541
1542/*
1543 * Compares two strings that maybe be NULL. Returns non-zero if strings
1544 * are both NULL or are identical, returns zero otherwise.
1545 */
1546static int
1547strcmp_maybe_null(const char *a, const char *b)
1548{
1549 if ((a == NULL && b != NULL) || (a != NULL && b == NULL))
1550 return 0;
1551 if (a != NULL && strcmp(a, b) != 0)
1552 return 0;
1553 return 1;
1554}
1555
1556/*
1557 * Compare two forwards, returning non-zero if they are identical or
1558 * zero otherwise.
1559 */
1560int
1561forward_equals(const struct Forward *a, const struct Forward *b)
1562{
1563 if (strcmp_maybe_null(a->listen_host, b->listen_host) == 0)
1564 return 0;
1565 if (a->listen_port != b->listen_port)
1566 return 0;
1567 if (strcmp_maybe_null(a->listen_path, b->listen_path) == 0)
1568 return 0;
1569 if (strcmp_maybe_null(a->connect_host, b->connect_host) == 0)
1570 return 0;
1571 if (a->connect_port != b->connect_port)
1572 return 0;
1573 if (strcmp_maybe_null(a->connect_path, b->connect_path) == 0)
1574 return 0;
1575 /* allocated_port and handle are not checked */
1576 return 1;
1577}
1578
dtucker@openbsd.org7fc47662016-11-30 00:28:31 +00001579/* returns 1 if process is already daemonized, 0 otherwise */
1580int
1581daemonized(void)
1582{
1583 int fd;
1584
1585 if ((fd = open(_PATH_TTY, O_RDONLY | O_NOCTTY)) >= 0) {
1586 close(fd);
1587 return 0; /* have controlling terminal */
1588 }
1589 if (getppid() != 1)
1590 return 0; /* parent is not init */
1591 if (getsid(0) != getpid())
1592 return 0; /* not session leader */
1593 debug3("already daemonized");
1594 return 1;
1595}
djm@openbsd.orgde4ae072017-08-18 05:36:45 +00001596
1597
1598/*
1599 * Splits 's' into an argument vector. Handles quoted string and basic
1600 * escape characters (\\, \", \'). Caller must free the argument vector
1601 * and its members.
1602 */
1603int
1604argv_split(const char *s, int *argcp, char ***argvp)
1605{
1606 int r = SSH_ERR_INTERNAL_ERROR;
1607 int argc = 0, quote, i, j;
1608 char *arg, **argv = xcalloc(1, sizeof(*argv));
1609
1610 *argvp = NULL;
1611 *argcp = 0;
1612
1613 for (i = 0; s[i] != '\0'; i++) {
1614 /* Skip leading whitespace */
1615 if (s[i] == ' ' || s[i] == '\t')
1616 continue;
1617
1618 /* Start of a token */
1619 quote = 0;
1620 if (s[i] == '\\' &&
1621 (s[i + 1] == '\'' || s[i + 1] == '\"' || s[i + 1] == '\\'))
1622 i++;
1623 else if (s[i] == '\'' || s[i] == '"')
1624 quote = s[i++];
1625
1626 argv = xreallocarray(argv, (argc + 2), sizeof(*argv));
1627 arg = argv[argc++] = xcalloc(1, strlen(s + i) + 1);
1628 argv[argc] = NULL;
1629
1630 /* Copy the token in, removing escapes */
1631 for (j = 0; s[i] != '\0'; i++) {
1632 if (s[i] == '\\') {
1633 if (s[i + 1] == '\'' ||
1634 s[i + 1] == '\"' ||
1635 s[i + 1] == '\\') {
1636 i++; /* Skip '\' */
1637 arg[j++] = s[i];
1638 } else {
1639 /* Unrecognised escape */
1640 arg[j++] = s[i];
1641 }
1642 } else if (quote == 0 && (s[i] == ' ' || s[i] == '\t'))
1643 break; /* done */
1644 else if (quote != 0 && s[i] == quote)
1645 break; /* done */
1646 else
1647 arg[j++] = s[i];
1648 }
1649 if (s[i] == '\0') {
1650 if (quote != 0) {
1651 /* Ran out of string looking for close quote */
1652 r = SSH_ERR_INVALID_FORMAT;
1653 goto out;
1654 }
1655 break;
1656 }
1657 }
1658 /* Success */
1659 *argcp = argc;
1660 *argvp = argv;
1661 argc = 0;
1662 argv = NULL;
1663 r = 0;
1664 out:
1665 if (argc != 0 && argv != NULL) {
1666 for (i = 0; i < argc; i++)
1667 free(argv[i]);
1668 free(argv);
1669 }
1670 return r;
1671}
1672
1673/*
1674 * Reassemble an argument vector into a string, quoting and escaping as
1675 * necessary. Caller must free returned string.
1676 */
1677char *
1678argv_assemble(int argc, char **argv)
1679{
1680 int i, j, ws, r;
1681 char c, *ret;
1682 struct sshbuf *buf, *arg;
1683
1684 if ((buf = sshbuf_new()) == NULL || (arg = sshbuf_new()) == NULL)
1685 fatal("%s: sshbuf_new failed", __func__);
1686
1687 for (i = 0; i < argc; i++) {
1688 ws = 0;
1689 sshbuf_reset(arg);
1690 for (j = 0; argv[i][j] != '\0'; j++) {
1691 r = 0;
1692 c = argv[i][j];
1693 switch (c) {
1694 case ' ':
1695 case '\t':
1696 ws = 1;
1697 r = sshbuf_put_u8(arg, c);
1698 break;
1699 case '\\':
1700 case '\'':
1701 case '"':
1702 if ((r = sshbuf_put_u8(arg, '\\')) != 0)
1703 break;
1704 /* FALLTHROUGH */
1705 default:
1706 r = sshbuf_put_u8(arg, c);
1707 break;
1708 }
1709 if (r != 0)
1710 fatal("%s: sshbuf_put_u8: %s",
1711 __func__, ssh_err(r));
1712 }
1713 if ((i != 0 && (r = sshbuf_put_u8(buf, ' ')) != 0) ||
1714 (ws != 0 && (r = sshbuf_put_u8(buf, '"')) != 0) ||
1715 (r = sshbuf_putb(buf, arg)) != 0 ||
1716 (ws != 0 && (r = sshbuf_put_u8(buf, '"')) != 0))
1717 fatal("%s: buffer error: %s", __func__, ssh_err(r));
1718 }
1719 if ((ret = malloc(sshbuf_len(buf) + 1)) == NULL)
1720 fatal("%s: malloc failed", __func__);
1721 memcpy(ret, sshbuf_ptr(buf), sshbuf_len(buf));
1722 ret[sshbuf_len(buf)] = '\0';
1723 sshbuf_free(buf);
1724 sshbuf_free(arg);
1725 return ret;
1726}
1727
djm@openbsd.orgde4ae072017-08-18 05:36:45 +00001728/* Returns 0 if pid exited cleanly, non-zero otherwise */
1729int
djm@openbsd.orgb074c3c2017-08-18 05:48:04 +00001730exited_cleanly(pid_t pid, const char *tag, const char *cmd, int quiet)
djm@openbsd.orgde4ae072017-08-18 05:36:45 +00001731{
1732 int status;
1733
1734 while (waitpid(pid, &status, 0) == -1) {
1735 if (errno != EINTR) {
1736 error("%s: waitpid: %s", tag, strerror(errno));
1737 return -1;
1738 }
1739 }
1740 if (WIFSIGNALED(status)) {
1741 error("%s %s exited on signal %d", tag, cmd, WTERMSIG(status));
1742 return -1;
1743 } else if (WEXITSTATUS(status) != 0) {
djm@openbsd.orgb074c3c2017-08-18 05:48:04 +00001744 do_log2(quiet ? SYSLOG_LEVEL_DEBUG1 : SYSLOG_LEVEL_INFO,
1745 "%s %s failed, status %d", tag, cmd, WEXITSTATUS(status));
djm@openbsd.orgde4ae072017-08-18 05:36:45 +00001746 return -1;
1747 }
1748 return 0;
1749}
1750
1751/*
1752 * Check a given path for security. This is defined as all components
1753 * of the path to the file must be owned by either the owner of
1754 * of the file or root and no directories must be group or world writable.
1755 *
1756 * XXX Should any specific check be done for sym links ?
1757 *
1758 * Takes a file name, its stat information (preferably from fstat() to
1759 * avoid races), the uid of the expected owner, their home directory and an
1760 * error buffer plus max size as arguments.
1761 *
1762 * Returns 0 on success and -1 on failure
1763 */
1764int
1765safe_path(const char *name, struct stat *stp, const char *pw_dir,
1766 uid_t uid, char *err, size_t errlen)
1767{
1768 char buf[PATH_MAX], homedir[PATH_MAX];
1769 char *cp;
1770 int comparehome = 0;
1771 struct stat st;
1772
1773 if (realpath(name, buf) == NULL) {
1774 snprintf(err, errlen, "realpath %s failed: %s", name,
1775 strerror(errno));
1776 return -1;
1777 }
1778 if (pw_dir != NULL && realpath(pw_dir, homedir) != NULL)
1779 comparehome = 1;
1780
1781 if (!S_ISREG(stp->st_mode)) {
1782 snprintf(err, errlen, "%s is not a regular file", buf);
1783 return -1;
1784 }
1785 if ((!platform_sys_dir_uid(stp->st_uid) && stp->st_uid != uid) ||
1786 (stp->st_mode & 022) != 0) {
1787 snprintf(err, errlen, "bad ownership or modes for file %s",
1788 buf);
1789 return -1;
1790 }
1791
1792 /* for each component of the canonical path, walking upwards */
1793 for (;;) {
1794 if ((cp = dirname(buf)) == NULL) {
1795 snprintf(err, errlen, "dirname() failed");
1796 return -1;
1797 }
1798 strlcpy(buf, cp, sizeof(buf));
1799
1800 if (stat(buf, &st) < 0 ||
1801 (!platform_sys_dir_uid(st.st_uid) && st.st_uid != uid) ||
1802 (st.st_mode & 022) != 0) {
1803 snprintf(err, errlen,
1804 "bad ownership or modes for directory %s", buf);
1805 return -1;
1806 }
1807
1808 /* If are past the homedir then we can stop */
1809 if (comparehome && strcmp(homedir, buf) == 0)
1810 break;
1811
1812 /*
1813 * dirname should always complete with a "/" path,
1814 * but we can be paranoid and check for "." too
1815 */
1816 if ((strcmp("/", buf) == 0) || (strcmp(".", buf) == 0))
1817 break;
1818 }
1819 return 0;
1820}
1821
1822/*
1823 * Version of safe_path() that accepts an open file descriptor to
1824 * avoid races.
1825 *
1826 * Returns 0 on success and -1 on failure
1827 */
1828int
1829safe_path_fd(int fd, const char *file, struct passwd *pw,
1830 char *err, size_t errlen)
1831{
1832 struct stat st;
1833
1834 /* check the open file to avoid races */
1835 if (fstat(fd, &st) < 0) {
1836 snprintf(err, errlen, "cannot stat file %s: %s",
1837 file, strerror(errno));
1838 return -1;
1839 }
1840 return safe_path(file, &st, pw->pw_dir, pw->pw_uid, err, errlen);
1841}
1842
1843/*
1844 * Sets the value of the given variable in the environment. If the variable
1845 * already exists, its value is overridden.
1846 */
1847void
1848child_set_env(char ***envp, u_int *envsizep, const char *name,
1849 const char *value)
1850{
1851 char **env;
1852 u_int envsize;
1853 u_int i, namelen;
1854
1855 if (strchr(name, '=') != NULL) {
1856 error("Invalid environment variable \"%.100s\"", name);
1857 return;
1858 }
1859
1860 /*
1861 * If we're passed an uninitialized list, allocate a single null
1862 * entry before continuing.
1863 */
1864 if (*envp == NULL && *envsizep == 0) {
1865 *envp = xmalloc(sizeof(char *));
1866 *envp[0] = NULL;
1867 *envsizep = 1;
1868 }
1869
1870 /*
1871 * Find the slot where the value should be stored. If the variable
1872 * already exists, we reuse the slot; otherwise we append a new slot
1873 * at the end of the array, expanding if necessary.
1874 */
1875 env = *envp;
1876 namelen = strlen(name);
1877 for (i = 0; env[i]; i++)
1878 if (strncmp(env[i], name, namelen) == 0 && env[i][namelen] == '=')
1879 break;
1880 if (env[i]) {
1881 /* Reuse the slot. */
1882 free(env[i]);
1883 } else {
1884 /* New variable. Expand if necessary. */
1885 envsize = *envsizep;
1886 if (i >= envsize - 1) {
1887 if (envsize >= 1000)
1888 fatal("child_set_env: too many env vars");
1889 envsize += 50;
1890 env = (*envp) = xreallocarray(env, envsize, sizeof(char *));
1891 *envsizep = envsize;
1892 }
1893 /* Need to set the NULL pointer at end of array beyond the new slot. */
1894 env[i + 1] = NULL;
1895 }
1896
1897 /* Allocate space and format the variable in the appropriate slot. */
djm@openbsd.org7c856852018-03-03 03:15:51 +00001898 /* XXX xasprintf */
djm@openbsd.orgde4ae072017-08-18 05:36:45 +00001899 env[i] = xmalloc(strlen(name) + 1 + strlen(value) + 1);
1900 snprintf(env[i], strlen(name) + 1 + strlen(value) + 1, "%s=%s", name, value);
1901}
1902
millert@openbsd.org887669e2017-10-21 23:06:24 +00001903/*
1904 * Check and optionally lowercase a domain name, also removes trailing '.'
1905 * Returns 1 on success and 0 on failure, storing an error message in errstr.
1906 */
1907int
1908valid_domain(char *name, int makelower, const char **errstr)
1909{
1910 size_t i, l = strlen(name);
1911 u_char c, last = '\0';
1912 static char errbuf[256];
1913
1914 if (l == 0) {
1915 strlcpy(errbuf, "empty domain name", sizeof(errbuf));
1916 goto bad;
1917 }
1918 if (!isalpha((u_char)name[0]) && !isdigit((u_char)name[0])) {
1919 snprintf(errbuf, sizeof(errbuf), "domain name \"%.100s\" "
1920 "starts with invalid character", name);
1921 goto bad;
1922 }
1923 for (i = 0; i < l; i++) {
1924 c = tolower((u_char)name[i]);
1925 if (makelower)
1926 name[i] = (char)c;
1927 if (last == '.' && c == '.') {
1928 snprintf(errbuf, sizeof(errbuf), "domain name "
1929 "\"%.100s\" contains consecutive separators", name);
1930 goto bad;
1931 }
1932 if (c != '.' && c != '-' && !isalnum(c) &&
1933 c != '_') /* technically invalid, but common */ {
1934 snprintf(errbuf, sizeof(errbuf), "domain name "
1935 "\"%.100s\" contains invalid characters", name);
1936 goto bad;
1937 }
1938 last = c;
1939 }
1940 if (name[l - 1] == '.')
1941 name[l - 1] = '\0';
1942 if (errstr != NULL)
1943 *errstr = NULL;
1944 return 1;
1945bad:
1946 if (errstr != NULL)
1947 *errstr = errbuf;
1948 return 0;
1949}
dtucker@openbsd.org609d96b2017-12-05 23:59:47 +00001950
1951const char *
1952atoi_err(const char *nptr, int *val)
1953{
1954 const char *errstr = NULL;
1955 long long num;
1956
1957 if (nptr == NULL || *nptr == '\0')
1958 return "missing";
1959 num = strtonum(nptr, 0, INT_MAX, &errstr);
1960 if (errstr == NULL)
1961 *val = (int)num;
1962 return errstr;
1963}
djm@openbsd.orgbf0fbf22018-03-12 00:52:01 +00001964
1965int
1966parse_absolute_time(const char *s, uint64_t *tp)
1967{
1968 struct tm tm;
1969 time_t tt;
1970 char buf[32], *fmt;
1971
1972 *tp = 0;
1973
1974 /*
1975 * POSIX strptime says "The application shall ensure that there
1976 * is white-space or other non-alphanumeric characters between
1977 * any two conversion specifications" so arrange things this way.
1978 */
1979 switch (strlen(s)) {
1980 case 8: /* YYYYMMDD */
1981 fmt = "%Y-%m-%d";
1982 snprintf(buf, sizeof(buf), "%.4s-%.2s-%.2s", s, s + 4, s + 6);
1983 break;
1984 case 12: /* YYYYMMDDHHMM */
1985 fmt = "%Y-%m-%dT%H:%M";
1986 snprintf(buf, sizeof(buf), "%.4s-%.2s-%.2sT%.2s:%.2s",
1987 s, s + 4, s + 6, s + 8, s + 10);
1988 break;
1989 case 14: /* YYYYMMDDHHMMSS */
1990 fmt = "%Y-%m-%dT%H:%M:%S";
1991 snprintf(buf, sizeof(buf), "%.4s-%.2s-%.2sT%.2s:%.2s:%.2s",
1992 s, s + 4, s + 6, s + 8, s + 10, s + 12);
1993 break;
1994 default:
1995 return SSH_ERR_INVALID_FORMAT;
1996 }
1997
1998 memset(&tm, 0, sizeof(tm));
1999 if (strptime(buf, fmt, &tm) == NULL)
2000 return SSH_ERR_INVALID_FORMAT;
2001 if ((tt = mktime(&tm)) < 0)
2002 return SSH_ERR_INVALID_FORMAT;
2003 /* success */
2004 *tp = (uint64_t)tt;
2005 return 0;
2006}
2007
2008void
2009format_absolute_time(uint64_t t, char *buf, size_t len)
2010{
2011 time_t tt = t > INT_MAX ? INT_MAX : t; /* XXX revisit in 2038 :P */
2012 struct tm tm;
2013
2014 localtime_r(&tt, &tm);
2015 strftime(buf, len, "%Y-%m-%dT%H:%M:%S", &tm);
2016}