blob: 1e660b02181ef366ff4e059c7a977044a97cd8e5 [file] [log] [blame]
djm@openbsd.org7c856852018-03-03 03:15:51 +00001/* $OpenBSD: misc.c,v 1.125 2018/03/03 03:15:51 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>
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"
72#include "uidswap.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 */
Damien Miller61c51502000-08-18 14:01:04 +1000242char *
243strdelim(char **s)
244{
djm@openbsd.org713d9cb2018-03-02 03:02:11 +0000245 char *old, *cp;
Damien Miller61c51502000-08-18 14:01:04 +1000246 int wspace = 0;
247
248 if (*s == NULL)
249 return NULL;
250
251 old = *s;
252
Damien Miller306d1182006-03-15 12:05:59 +1100253 *s = strpbrk(*s, 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 */
djm@openbsd.org713d9cb2018-03-02 03:02:11 +0000259
Damien Miller306d1182006-03-15 12:05:59 +1100260 /* Find matching quote */
djm@openbsd.org713d9cb2018-03-02 03:02:11 +0000261 for (cp = *s; ; cp++) {
262 if (*cp == '\0')
263 return NULL; /* no matching quote */
264 if (*cp == '\\') {
265 /* Escape sequence */
266 if (cp[1] == '\"' || cp[1] == '\'' ||
267 cp[1] == '\\') {
268 memmove(cp, cp + 1, strlen(cp));
269 continue;
270 }
271 return NULL; /* invalid escape */
272 } else if (*cp == '\"') {
273 *(cp++) = '\0';
274 *s += strspn(cp, WHITESPACE);
275 return old;
276 }
Damien Miller306d1182006-03-15 12:05:59 +1100277 }
278 }
279
Damien Miller61c51502000-08-18 14:01:04 +1000280 /* Allow only one '=' to be skipped */
281 if (*s[0] == '=')
282 wspace = 1;
283 *s[0] = '\0';
284
Damien Miller306d1182006-03-15 12:05:59 +1100285 /* Skip any extra whitespace after first token */
Damien Miller61c51502000-08-18 14:01:04 +1000286 *s += strspn(*s + 1, WHITESPACE) + 1;
287 if (*s[0] == '=' && !wspace)
288 *s += strspn(*s + 1, WHITESPACE) + 1;
289
290 return (old);
291}
Kevin Stevesb6e773a2001-02-04 13:20:36 +0000292
Ben Lindstrom086cf212001-03-05 05:56:40 +0000293struct passwd *
294pwcopy(struct passwd *pw)
295{
Damien Miller07d86be2006-03-26 14:19:21 +1100296 struct passwd *copy = xcalloc(1, sizeof(*copy));
Ben Lindstrom40304422001-03-05 06:22:01 +0000297
Ben Lindstrom086cf212001-03-05 05:56:40 +0000298 copy->pw_name = xstrdup(pw->pw_name);
299 copy->pw_passwd = xstrdup(pw->pw_passwd);
Damien Miller6332da22013-04-23 14:25:52 +1000300#ifdef HAVE_STRUCT_PASSWD_PW_GECOS
Ben Lindstrom40304422001-03-05 06:22:01 +0000301 copy->pw_gecos = xstrdup(pw->pw_gecos);
Damien Miller6332da22013-04-23 14:25:52 +1000302#endif
Ben Lindstrom086cf212001-03-05 05:56:40 +0000303 copy->pw_uid = pw->pw_uid;
304 copy->pw_gid = pw->pw_gid;
Damien Miller6332da22013-04-23 14:25:52 +1000305#ifdef HAVE_STRUCT_PASSWD_PW_EXPIRE
Ben Lindstrom3af4d462001-06-21 03:11:27 +0000306 copy->pw_expire = pw->pw_expire;
Kevin Steves82456952001-06-22 21:14:18 +0000307#endif
Damien Miller6332da22013-04-23 14:25:52 +1000308#ifdef HAVE_STRUCT_PASSWD_PW_CHANGE
Ben Lindstrom3af4d462001-06-21 03:11:27 +0000309 copy->pw_change = pw->pw_change;
Kevin Steves82456952001-06-22 21:14:18 +0000310#endif
Damien Miller6332da22013-04-23 14:25:52 +1000311#ifdef HAVE_STRUCT_PASSWD_PW_CLASS
Ben Lindstrom086cf212001-03-05 05:56:40 +0000312 copy->pw_class = xstrdup(pw->pw_class);
Ben Lindstrom0f68db42001-03-05 07:57:09 +0000313#endif
Ben Lindstrom086cf212001-03-05 05:56:40 +0000314 copy->pw_dir = xstrdup(pw->pw_dir);
315 copy->pw_shell = xstrdup(pw->pw_shell);
316 return copy;
317}
318
Ben Lindstrom4cc240d2001-07-04 04:46:56 +0000319/*
320 * Convert ASCII string to TCP/IP port number.
Damien Miller3dc71ad2009-01-28 16:31:22 +1100321 * Port must be >=0 and <=65535.
322 * Return -1 if invalid.
Ben Lindstrom4cc240d2001-07-04 04:46:56 +0000323 */
324int
325a2port(const char *s)
Ben Lindstrom19066a12001-04-12 23:39:26 +0000326{
Damien Miller3dc71ad2009-01-28 16:31:22 +1100327 long long port;
328 const char *errstr;
Ben Lindstrom19066a12001-04-12 23:39:26 +0000329
Damien Miller3dc71ad2009-01-28 16:31:22 +1100330 port = strtonum(s, 0, 65535, &errstr);
331 if (errstr != NULL)
332 return -1;
333 return (int)port;
Ben Lindstrom19066a12001-04-12 23:39:26 +0000334}
335
Damien Millerd27b9472005-12-13 19:29:02 +1100336int
337a2tun(const char *s, int *remote)
338{
339 const char *errstr = NULL;
340 char *sp, *ep;
341 int tun;
342
343 if (remote != NULL) {
Damien Miller7b58e802005-12-13 19:33:19 +1100344 *remote = SSH_TUNID_ANY;
Damien Millerd27b9472005-12-13 19:29:02 +1100345 sp = xstrdup(s);
346 if ((ep = strchr(sp, ':')) == NULL) {
Darren Tuckera627d422013-06-02 07:31:17 +1000347 free(sp);
Damien Millerd27b9472005-12-13 19:29:02 +1100348 return (a2tun(s, NULL));
349 }
350 ep[0] = '\0'; ep++;
351 *remote = a2tun(ep, NULL);
352 tun = a2tun(sp, NULL);
Darren Tuckera627d422013-06-02 07:31:17 +1000353 free(sp);
Damien Miller7b58e802005-12-13 19:33:19 +1100354 return (*remote == SSH_TUNID_ERR ? *remote : tun);
Damien Millerd27b9472005-12-13 19:29:02 +1100355 }
356
357 if (strcasecmp(s, "any") == 0)
Damien Miller7b58e802005-12-13 19:33:19 +1100358 return (SSH_TUNID_ANY);
Damien Millerd27b9472005-12-13 19:29:02 +1100359
Damien Miller7b58e802005-12-13 19:33:19 +1100360 tun = strtonum(s, 0, SSH_TUNID_MAX, &errstr);
361 if (errstr != NULL)
362 return (SSH_TUNID_ERR);
Damien Millerd27b9472005-12-13 19:29:02 +1100363
364 return (tun);
365}
366
Ben Lindstrom1bda4c82001-06-05 19:59:08 +0000367#define SECONDS 1
368#define MINUTES (SECONDS * 60)
369#define HOURS (MINUTES * 60)
370#define DAYS (HOURS * 24)
371#define WEEKS (DAYS * 7)
372
Ben Lindstrom4cc240d2001-07-04 04:46:56 +0000373/*
374 * Convert a time string into seconds; format is
375 * a sequence of:
376 * time[qualifier]
377 *
378 * Valid time qualifiers are:
379 * <none> seconds
380 * s|S seconds
381 * m|M minutes
382 * h|H hours
383 * d|D days
384 * w|W weeks
385 *
386 * Examples:
387 * 90m 90 minutes
388 * 1h30m 90 minutes
389 * 2d 2 days
390 * 1w 1 week
391 *
392 * Return -1 if time string is invalid.
393 */
394long
395convtime(const char *s)
Ben Lindstrom1bda4c82001-06-05 19:59:08 +0000396{
dtucker@openbsd.orgf5746b42017-03-14 00:25:03 +0000397 long total, secs, multiplier = 1;
Ben Lindstrom1bda4c82001-06-05 19:59:08 +0000398 const char *p;
399 char *endp;
400
401 errno = 0;
402 total = 0;
403 p = s;
404
405 if (p == NULL || *p == '\0')
406 return -1;
407
408 while (*p) {
409 secs = strtol(p, &endp, 10);
410 if (p == endp ||
411 (errno == ERANGE && (secs == LONG_MIN || secs == LONG_MAX)) ||
412 secs < 0)
413 return -1;
414
415 switch (*endp++) {
416 case '\0':
417 endp--;
Damien Miller69b72032006-03-26 14:02:35 +1100418 break;
Ben Lindstrom1bda4c82001-06-05 19:59:08 +0000419 case 's':
420 case 'S':
421 break;
422 case 'm':
423 case 'M':
dtucker@openbsd.orgf5746b42017-03-14 00:25:03 +0000424 multiplier = MINUTES;
Ben Lindstrom1bda4c82001-06-05 19:59:08 +0000425 break;
426 case 'h':
427 case 'H':
dtucker@openbsd.orgf5746b42017-03-14 00:25:03 +0000428 multiplier = HOURS;
Ben Lindstrom1bda4c82001-06-05 19:59:08 +0000429 break;
430 case 'd':
431 case 'D':
dtucker@openbsd.orgf5746b42017-03-14 00:25:03 +0000432 multiplier = DAYS;
Ben Lindstrom1bda4c82001-06-05 19:59:08 +0000433 break;
434 case 'w':
435 case 'W':
dtucker@openbsd.orgf5746b42017-03-14 00:25:03 +0000436 multiplier = WEEKS;
Ben Lindstrom1bda4c82001-06-05 19:59:08 +0000437 break;
438 default:
439 return -1;
440 }
dtucker@openbsd.orgc6774d22017-03-14 00:55:37 +0000441 if (secs >= LONG_MAX / multiplier)
dtucker@openbsd.orgf5746b42017-03-14 00:25:03 +0000442 return -1;
443 secs *= multiplier;
dtucker@openbsd.orgc6774d22017-03-14 00:55:37 +0000444 if (total >= LONG_MAX - secs)
dtucker@openbsd.orgf5746b42017-03-14 00:25:03 +0000445 return -1;
Ben Lindstrom1bda4c82001-06-05 19:59:08 +0000446 total += secs;
447 if (total < 0)
448 return -1;
449 p = endp;
450 }
451
452 return total;
453}
454
Damien Millerf91ee4c2005-03-01 21:24:33 +1100455/*
Darren Tuckerda345532006-07-10 23:04:19 +1000456 * Returns a standardized host+port identifier string.
457 * Caller must free returned string.
458 */
459char *
460put_host_port(const char *host, u_short port)
461{
462 char *hoststr;
463
464 if (port == 0 || port == SSH_DEFAULT_PORT)
465 return(xstrdup(host));
466 if (asprintf(&hoststr, "[%s]:%d", host, (int)port) < 0)
467 fatal("put_host_port: asprintf: %s", strerror(errno));
468 debug3("put_host_port: %s", hoststr);
469 return hoststr;
470}
471
472/*
Damien Millerf91ee4c2005-03-01 21:24:33 +1100473 * Search for next delimiter between hostnames/addresses and ports.
474 * Argument may be modified (for termination).
475 * Returns *cp if parsing succeeds.
millert@openbsd.org887669e2017-10-21 23:06:24 +0000476 * *cp is set to the start of the next field, if one was found.
477 * The delimiter char, if present, is stored in delim.
Damien Millerf91ee4c2005-03-01 21:24:33 +1100478 * If this is the last field, *cp is set to NULL.
479 */
millert@openbsd.org887669e2017-10-21 23:06:24 +0000480static char *
481hpdelim2(char **cp, char *delim)
Damien Millerf91ee4c2005-03-01 21:24:33 +1100482{
483 char *s, *old;
484
485 if (cp == NULL || *cp == NULL)
486 return NULL;
487
488 old = s = *cp;
489 if (*s == '[') {
490 if ((s = strchr(s, ']')) == NULL)
491 return NULL;
492 else
493 s++;
494 } else if ((s = strpbrk(s, ":/")) == NULL)
495 s = *cp + strlen(*cp); /* skip to end (see first case below) */
496
497 switch (*s) {
498 case '\0':
499 *cp = NULL; /* no more fields*/
500 break;
Darren Tucker47eede72005-03-14 23:08:12 +1100501
Damien Millerf91ee4c2005-03-01 21:24:33 +1100502 case ':':
503 case '/':
millert@openbsd.org887669e2017-10-21 23:06:24 +0000504 if (delim != NULL)
505 *delim = *s;
Damien Millerf91ee4c2005-03-01 21:24:33 +1100506 *s = '\0'; /* terminate */
507 *cp = s + 1;
508 break;
Darren Tucker47eede72005-03-14 23:08:12 +1100509
Damien Millerf91ee4c2005-03-01 21:24:33 +1100510 default:
511 return NULL;
512 }
513
514 return old;
515}
516
Ben Lindstrom4529b702001-05-03 23:39:53 +0000517char *
millert@openbsd.org887669e2017-10-21 23:06:24 +0000518hpdelim(char **cp)
519{
520 return hpdelim2(cp, NULL);
521}
522
523char *
Ben Lindstrom4529b702001-05-03 23:39:53 +0000524cleanhostname(char *host)
525{
526 if (*host == '[' && host[strlen(host) - 1] == ']') {
527 host[strlen(host) - 1] = '\0';
528 return (host + 1);
529 } else
530 return host;
531}
532
533char *
534colon(char *cp)
535{
536 int flag = 0;
537
538 if (*cp == ':') /* Leading colon is part of file name. */
Damien Miller2e774462010-06-26 09:30:47 +1000539 return NULL;
Ben Lindstrom4529b702001-05-03 23:39:53 +0000540 if (*cp == '[')
541 flag = 1;
542
543 for (; *cp; ++cp) {
544 if (*cp == '@' && *(cp+1) == '[')
545 flag = 1;
546 if (*cp == ']' && *(cp+1) == ':' && flag)
547 return (cp+1);
548 if (*cp == ':' && !flag)
549 return (cp);
550 if (*cp == '/')
Damien Miller2e774462010-06-26 09:30:47 +1000551 return NULL;
Ben Lindstrom4529b702001-05-03 23:39:53 +0000552 }
Damien Miller2e774462010-06-26 09:30:47 +1000553 return NULL;
Ben Lindstrom4529b702001-05-03 23:39:53 +0000554}
555
djm@openbsd.orged877ef2016-07-15 00:24:30 +0000556/*
millert@openbsd.org887669e2017-10-21 23:06:24 +0000557 * Parse a [user@]host:[path] string.
558 * Caller must free returned user, host and path.
559 * Any of the pointer return arguments may be NULL (useful for syntax checking).
560 * If user was not specified then *userp will be set to NULL.
561 * If host was not specified then *hostp will be set to NULL.
562 * If path was not specified then *pathp will be set to ".".
563 * Returns 0 on success, -1 on failure.
564 */
565int
566parse_user_host_path(const char *s, char **userp, char **hostp, char **pathp)
567{
568 char *user = NULL, *host = NULL, *path = NULL;
569 char *sdup, *tmp;
570 int ret = -1;
571
572 if (userp != NULL)
573 *userp = NULL;
574 if (hostp != NULL)
575 *hostp = NULL;
576 if (pathp != NULL)
577 *pathp = NULL;
578
millert@openbsd.orgb9903ee2017-10-24 19:41:45 +0000579 sdup = xstrdup(s);
millert@openbsd.org887669e2017-10-21 23:06:24 +0000580
581 /* Check for remote syntax: [user@]host:[path] */
582 if ((tmp = colon(sdup)) == NULL)
583 goto out;
584
585 /* Extract optional path */
586 *tmp++ = '\0';
587 if (*tmp == '\0')
588 tmp = ".";
589 path = xstrdup(tmp);
590
591 /* Extract optional user and mandatory host */
592 tmp = strrchr(sdup, '@');
593 if (tmp != NULL) {
594 *tmp++ = '\0';
595 host = xstrdup(cleanhostname(tmp));
596 if (*sdup != '\0')
597 user = xstrdup(sdup);
598 } else {
599 host = xstrdup(cleanhostname(sdup));
600 user = NULL;
601 }
602
603 /* Success */
604 if (userp != NULL) {
605 *userp = user;
606 user = NULL;
607 }
608 if (hostp != NULL) {
609 *hostp = host;
610 host = NULL;
millert@openbsd.orgb9903ee2017-10-24 19:41:45 +0000611 }
millert@openbsd.org887669e2017-10-21 23:06:24 +0000612 if (pathp != NULL) {
613 *pathp = path;
614 path = NULL;
millert@openbsd.orgb9903ee2017-10-24 19:41:45 +0000615 }
millert@openbsd.org887669e2017-10-21 23:06:24 +0000616 ret = 0;
617out:
618 free(sdup);
619 free(user);
620 free(host);
621 free(path);
622 return ret;
623}
624
625/*
djm@openbsd.orged877ef2016-07-15 00:24:30 +0000626 * Parse a [user@]host[:port] string.
627 * Caller must free returned user and host.
628 * Any of the pointer return arguments may be NULL (useful for syntax checking).
629 * If user was not specified then *userp will be set to NULL.
630 * If port was not specified then *portp will be -1.
631 * Returns 0 on success, -1 on failure.
632 */
633int
634parse_user_host_port(const char *s, char **userp, char **hostp, int *portp)
635{
636 char *sdup, *cp, *tmp;
637 char *user = NULL, *host = NULL;
638 int port = -1, ret = -1;
639
640 if (userp != NULL)
641 *userp = NULL;
642 if (hostp != NULL)
643 *hostp = NULL;
644 if (portp != NULL)
645 *portp = -1;
646
647 if ((sdup = tmp = strdup(s)) == NULL)
648 return -1;
649 /* Extract optional username */
millert@openbsd.org887669e2017-10-21 23:06:24 +0000650 if ((cp = strrchr(tmp, '@')) != NULL) {
djm@openbsd.orged877ef2016-07-15 00:24:30 +0000651 *cp = '\0';
652 if (*tmp == '\0')
653 goto out;
654 if ((user = strdup(tmp)) == NULL)
655 goto out;
656 tmp = cp + 1;
657 }
658 /* Extract mandatory hostname */
659 if ((cp = hpdelim(&tmp)) == NULL || *cp == '\0')
660 goto out;
661 host = xstrdup(cleanhostname(cp));
662 /* Convert and verify optional port */
663 if (tmp != NULL && *tmp != '\0') {
664 if ((port = a2port(tmp)) <= 0)
665 goto out;
666 }
667 /* Success */
668 if (userp != NULL) {
669 *userp = user;
670 user = NULL;
671 }
672 if (hostp != NULL) {
673 *hostp = host;
674 host = NULL;
675 }
676 if (portp != NULL)
677 *portp = port;
678 ret = 0;
679 out:
680 free(sdup);
681 free(user);
682 free(host);
683 return ret;
684}
685
millert@openbsd.org887669e2017-10-21 23:06:24 +0000686/*
687 * Converts a two-byte hex string to decimal.
688 * Returns the decimal value or -1 for invalid input.
689 */
690static int
691hexchar(const char *s)
692{
693 unsigned char result[2];
694 int i;
695
696 for (i = 0; i < 2; i++) {
697 if (s[i] >= '0' && s[i] <= '9')
698 result[i] = (unsigned char)(s[i] - '0');
699 else if (s[i] >= 'a' && s[i] <= 'f')
700 result[i] = (unsigned char)(s[i] - 'a') + 10;
701 else if (s[i] >= 'A' && s[i] <= 'F')
702 result[i] = (unsigned char)(s[i] - 'A') + 10;
703 else
704 return -1;
705 }
706 return (result[0] << 4) | result[1];
707}
708
709/*
710 * Decode an url-encoded string.
711 * Returns a newly allocated string on success or NULL on failure.
712 */
713static char *
714urldecode(const char *src)
715{
716 char *ret, *dst;
717 int ch;
718
719 ret = xmalloc(strlen(src) + 1);
720 for (dst = ret; *src != '\0'; src++) {
721 switch (*src) {
722 case '+':
723 *dst++ = ' ';
724 break;
725 case '%':
726 if (!isxdigit((unsigned char)src[1]) ||
727 !isxdigit((unsigned char)src[2]) ||
728 (ch = hexchar(src + 1)) == -1) {
729 free(ret);
730 return NULL;
731 }
732 *dst++ = ch;
733 src += 2;
734 break;
735 default:
736 *dst++ = *src;
737 break;
738 }
739 }
740 *dst = '\0';
741
742 return ret;
743}
744
745/*
746 * Parse an (scp|ssh|sftp)://[user@]host[:port][/path] URI.
747 * See https://tools.ietf.org/html/draft-ietf-secsh-scp-sftp-ssh-uri-04
748 * Either user or path may be url-encoded (but not host or port).
749 * Caller must free returned user, host and path.
750 * Any of the pointer return arguments may be NULL (useful for syntax checking)
751 * but the scheme must always be specified.
752 * If user was not specified then *userp will be set to NULL.
753 * If port was not specified then *portp will be -1.
754 * If path was not specified then *pathp will be set to NULL.
755 * Returns 0 on success, 1 if non-uri/wrong scheme, -1 on error/invalid uri.
756 */
757int
758parse_uri(const char *scheme, const char *uri, char **userp, char **hostp,
759 int *portp, char **pathp)
760{
761 char *uridup, *cp, *tmp, ch;
762 char *user = NULL, *host = NULL, *path = NULL;
763 int port = -1, ret = -1;
764 size_t len;
765
766 len = strlen(scheme);
767 if (strncmp(uri, scheme, len) != 0 || strncmp(uri + len, "://", 3) != 0)
768 return 1;
769 uri += len + 3;
770
771 if (userp != NULL)
772 *userp = NULL;
773 if (hostp != NULL)
774 *hostp = NULL;
775 if (portp != NULL)
776 *portp = -1;
777 if (pathp != NULL)
778 *pathp = NULL;
779
780 uridup = tmp = xstrdup(uri);
781
782 /* Extract optional ssh-info (username + connection params) */
783 if ((cp = strchr(tmp, '@')) != NULL) {
784 char *delim;
785
786 *cp = '\0';
787 /* Extract username and connection params */
788 if ((delim = strchr(tmp, ';')) != NULL) {
789 /* Just ignore connection params for now */
790 *delim = '\0';
791 }
792 if (*tmp == '\0') {
793 /* Empty username */
794 goto out;
795 }
796 if ((user = urldecode(tmp)) == NULL)
797 goto out;
798 tmp = cp + 1;
799 }
800
801 /* Extract mandatory hostname */
802 if ((cp = hpdelim2(&tmp, &ch)) == NULL || *cp == '\0')
803 goto out;
804 host = xstrdup(cleanhostname(cp));
805 if (!valid_domain(host, 0, NULL))
806 goto out;
807
808 if (tmp != NULL && *tmp != '\0') {
809 if (ch == ':') {
810 /* Convert and verify port. */
811 if ((cp = strchr(tmp, '/')) != NULL)
812 *cp = '\0';
813 if ((port = a2port(tmp)) <= 0)
814 goto out;
815 tmp = cp ? cp + 1 : NULL;
816 }
817 if (tmp != NULL && *tmp != '\0') {
818 /* Extract optional path */
819 if ((path = urldecode(tmp)) == NULL)
820 goto out;
821 }
822 }
823
824 /* Success */
825 if (userp != NULL) {
826 *userp = user;
827 user = NULL;
828 }
829 if (hostp != NULL) {
830 *hostp = host;
831 host = NULL;
832 }
833 if (portp != NULL)
834 *portp = port;
835 if (pathp != NULL) {
836 *pathp = path;
837 path = NULL;
838 }
839 ret = 0;
840 out:
841 free(uridup);
842 free(user);
843 free(host);
844 free(path);
845 return ret;
846}
847
Ben Lindstrom4cc240d2001-07-04 04:46:56 +0000848/* function to assist building execv() arguments */
Ben Lindstrom387c4722001-05-08 20:27:25 +0000849void
850addargs(arglist *args, char *fmt, ...)
851{
852 va_list ap;
Damien Miller3eec6b72006-01-31 21:49:27 +1100853 char *cp;
Darren Tuckerc7a6fc42004-08-13 21:18:00 +1000854 u_int nalloc;
Damien Miller3eec6b72006-01-31 21:49:27 +1100855 int r;
Ben Lindstrom387c4722001-05-08 20:27:25 +0000856
857 va_start(ap, fmt);
Damien Miller3eec6b72006-01-31 21:49:27 +1100858 r = vasprintf(&cp, fmt, ap);
Ben Lindstrom387c4722001-05-08 20:27:25 +0000859 va_end(ap);
Damien Miller3eec6b72006-01-31 21:49:27 +1100860 if (r == -1)
861 fatal("addargs: argument too long");
Ben Lindstrom387c4722001-05-08 20:27:25 +0000862
Darren Tuckerfb16b242003-09-22 21:04:23 +1000863 nalloc = args->nalloc;
Ben Lindstrom387c4722001-05-08 20:27:25 +0000864 if (args->list == NULL) {
Darren Tuckerfb16b242003-09-22 21:04:23 +1000865 nalloc = 32;
Ben Lindstrom387c4722001-05-08 20:27:25 +0000866 args->num = 0;
Darren Tuckerfb16b242003-09-22 21:04:23 +1000867 } else if (args->num+2 >= nalloc)
868 nalloc *= 2;
Ben Lindstrom387c4722001-05-08 20:27:25 +0000869
deraadt@openbsd.org9e509d42017-05-31 09:15:42 +0000870 args->list = xrecallocarray(args->list, args->nalloc, nalloc, sizeof(char *));
Darren Tuckerfb16b242003-09-22 21:04:23 +1000871 args->nalloc = nalloc;
Damien Miller3eec6b72006-01-31 21:49:27 +1100872 args->list[args->num++] = cp;
Ben Lindstrom387c4722001-05-08 20:27:25 +0000873 args->list[args->num] = NULL;
874}
Darren Tucker22cc7412004-12-06 22:47:41 +1100875
Damien Miller3eec6b72006-01-31 21:49:27 +1100876void
877replacearg(arglist *args, u_int which, char *fmt, ...)
878{
879 va_list ap;
880 char *cp;
881 int r;
882
883 va_start(ap, fmt);
884 r = vasprintf(&cp, fmt, ap);
885 va_end(ap);
886 if (r == -1)
887 fatal("replacearg: argument too long");
888
889 if (which >= args->num)
890 fatal("replacearg: tried to replace invalid arg %d >= %d",
891 which, args->num);
Darren Tuckera627d422013-06-02 07:31:17 +1000892 free(args->list[which]);
Damien Miller3eec6b72006-01-31 21:49:27 +1100893 args->list[which] = cp;
894}
895
896void
897freeargs(arglist *args)
898{
899 u_int i;
900
901 if (args->list != NULL) {
902 for (i = 0; i < args->num; i++)
Darren Tuckera627d422013-06-02 07:31:17 +1000903 free(args->list[i]);
904 free(args->list);
Damien Miller3eec6b72006-01-31 21:49:27 +1100905 args->nalloc = args->num = 0;
906 args->list = NULL;
907 }
908}
909
Darren Tucker22cc7412004-12-06 22:47:41 +1100910/*
Damien Miller5fd38c02005-05-26 12:02:14 +1000911 * Expands tildes in the file name. Returns data allocated by xmalloc.
912 * Warning: this calls getpw*.
913 */
914char *
915tilde_expand_filename(const char *filename, uid_t uid)
916{
Darren Tucker2ca51bf2013-05-16 20:22:46 +1000917 const char *path, *sep;
918 char user[128], *ret;
Damien Miller5fd38c02005-05-26 12:02:14 +1000919 struct passwd *pw;
Damien Millereccb9de2005-06-17 12:59:34 +1000920 u_int len, slash;
Damien Miller5fd38c02005-05-26 12:02:14 +1000921
922 if (*filename != '~')
923 return (xstrdup(filename));
924 filename++;
925
926 path = strchr(filename, '/');
927 if (path != NULL && path > filename) { /* ~user/path */
Damien Millereccb9de2005-06-17 12:59:34 +1000928 slash = path - filename;
929 if (slash > sizeof(user) - 1)
Damien Miller5fd38c02005-05-26 12:02:14 +1000930 fatal("tilde_expand_filename: ~username too long");
Damien Millereccb9de2005-06-17 12:59:34 +1000931 memcpy(user, filename, slash);
932 user[slash] = '\0';
Damien Miller5fd38c02005-05-26 12:02:14 +1000933 if ((pw = getpwnam(user)) == NULL)
934 fatal("tilde_expand_filename: No such user %s", user);
935 } else if ((pw = getpwuid(uid)) == NULL) /* ~/path */
Darren Tucker7517b5b2008-06-13 14:48:59 +1000936 fatal("tilde_expand_filename: No such uid %ld", (long)uid);
Damien Miller5fd38c02005-05-26 12:02:14 +1000937
Damien Miller5fd38c02005-05-26 12:02:14 +1000938 /* Make sure directory has a trailing '/' */
939 len = strlen(pw->pw_dir);
Darren Tucker026d9db2013-05-16 20:23:52 +1000940 if (len == 0 || pw->pw_dir[len - 1] != '/')
Darren Tucker2ca51bf2013-05-16 20:22:46 +1000941 sep = "/";
942 else
943 sep = "";
Damien Miller5fd38c02005-05-26 12:02:14 +1000944
945 /* Skip leading '/' from specified path */
946 if (path != NULL)
947 filename = path + 1;
Darren Tucker2ca51bf2013-05-16 20:22:46 +1000948
deraadt@openbsd.org2ae4f332015-01-16 06:40:12 +0000949 if (xasprintf(&ret, "%s%s%s", pw->pw_dir, sep, filename) >= PATH_MAX)
Damien Miller5fd38c02005-05-26 12:02:14 +1000950 fatal("tilde_expand_filename: Path too long");
951
Darren Tucker2ca51bf2013-05-16 20:22:46 +1000952 return (ret);
Damien Miller5fd38c02005-05-26 12:02:14 +1000953}
954
955/*
Damien Miller6476cad2005-06-16 13:18:34 +1000956 * Expand a string with a set of %[char] escapes. A number of escapes may be
957 * specified as (char *escape_chars, char *replacement) pairs. The list must
Darren Tuckerbee73d52005-07-14 17:05:02 +1000958 * be terminated by a NULL escape_char. Returns replaced string in memory
Damien Miller6476cad2005-06-16 13:18:34 +1000959 * allocated by xmalloc.
960 */
961char *
962percent_expand(const char *string, ...)
963{
964#define EXPAND_MAX_KEYS 16
Darren Tucker70d87692010-01-08 18:49:16 +1100965 u_int num_keys, i, j;
Damien Miller6476cad2005-06-16 13:18:34 +1000966 struct {
967 const char *key;
968 const char *repl;
969 } keys[EXPAND_MAX_KEYS];
Damien Miller6476cad2005-06-16 13:18:34 +1000970 char buf[4096];
971 va_list ap;
972
973 /* Gather keys */
974 va_start(ap, string);
975 for (num_keys = 0; num_keys < EXPAND_MAX_KEYS; num_keys++) {
976 keys[num_keys].key = va_arg(ap, char *);
977 if (keys[num_keys].key == NULL)
978 break;
979 keys[num_keys].repl = va_arg(ap, char *);
980 if (keys[num_keys].repl == NULL)
Darren Tucker70d87692010-01-08 18:49:16 +1100981 fatal("%s: NULL replacement", __func__);
Damien Miller6476cad2005-06-16 13:18:34 +1000982 }
Darren Tucker70d87692010-01-08 18:49:16 +1100983 if (num_keys == EXPAND_MAX_KEYS && va_arg(ap, char *) != NULL)
984 fatal("%s: too many keys", __func__);
Damien Miller6476cad2005-06-16 13:18:34 +1000985 va_end(ap);
986
Damien Miller6476cad2005-06-16 13:18:34 +1000987 /* Expand string */
988 *buf = '\0';
989 for (i = 0; *string != '\0'; string++) {
990 if (*string != '%') {
991 append:
992 buf[i++] = *string;
993 if (i >= sizeof(buf))
Darren Tucker70d87692010-01-08 18:49:16 +1100994 fatal("%s: string too long", __func__);
Damien Miller6476cad2005-06-16 13:18:34 +1000995 buf[i] = '\0';
996 continue;
997 }
998 string++;
Darren Tucker70d87692010-01-08 18:49:16 +1100999 /* %% case */
Damien Miller6476cad2005-06-16 13:18:34 +10001000 if (*string == '%')
1001 goto append;
tobias@openbsd.org8b56e592015-12-04 21:51:06 +00001002 if (*string == '\0')
1003 fatal("%s: invalid format", __func__);
Damien Miller6476cad2005-06-16 13:18:34 +10001004 for (j = 0; j < num_keys; j++) {
1005 if (strchr(keys[j].key, *string) != NULL) {
1006 i = strlcat(buf, keys[j].repl, sizeof(buf));
1007 if (i >= sizeof(buf))
Darren Tucker70d87692010-01-08 18:49:16 +11001008 fatal("%s: string too long", __func__);
Damien Miller6476cad2005-06-16 13:18:34 +10001009 break;
1010 }
1011 }
1012 if (j >= num_keys)
Darren Tucker70d87692010-01-08 18:49:16 +11001013 fatal("%s: unknown key %%%c", __func__, *string);
Damien Miller6476cad2005-06-16 13:18:34 +10001014 }
1015 return (xstrdup(buf));
1016#undef EXPAND_MAX_KEYS
1017}
1018
1019/*
Darren Tucker22cc7412004-12-06 22:47:41 +11001020 * Read an entire line from a public key file into a static buffer, discarding
1021 * lines that exceed the buffer size. Returns 0 on success, -1 on failure.
1022 */
1023int
1024read_keyfile_line(FILE *f, const char *filename, char *buf, size_t bufsz,
Darren Tuckerf0f90982004-12-11 13:39:50 +11001025 u_long *lineno)
Darren Tucker22cc7412004-12-06 22:47:41 +11001026{
1027 while (fgets(buf, bufsz, f) != NULL) {
Damien Miller3ca8b772007-01-05 16:24:47 +11001028 if (buf[0] == '\0')
1029 continue;
Darren Tucker22cc7412004-12-06 22:47:41 +11001030 (*lineno)++;
1031 if (buf[strlen(buf) - 1] == '\n' || feof(f)) {
1032 return 0;
1033 } else {
Darren Tuckerf0f90982004-12-11 13:39:50 +11001034 debug("%s: %s line %lu exceeds size limit", __func__,
1035 filename, *lineno);
Darren Tucker22cc7412004-12-06 22:47:41 +11001036 /* discard remainder of line */
Darren Tucker47eede72005-03-14 23:08:12 +11001037 while (fgetc(f) != '\n' && !feof(f))
Darren Tucker22cc7412004-12-06 22:47:41 +11001038 ; /* nothing */
1039 }
1040 }
1041 return -1;
1042}
Damien Miller13390022005-07-06 09:44:19 +10001043
Damien Millerd27b9472005-12-13 19:29:02 +11001044int
djm@openbsd.orgb7548b12017-10-23 05:08:00 +00001045tun_open(int tun, int mode, char **ifname)
Damien Millerd27b9472005-12-13 19:29:02 +11001046{
Damien Miller62a31c92005-12-13 20:44:13 +11001047#if defined(CUSTOM_SYS_TUN_OPEN)
djm@openbsd.orgb7548b12017-10-23 05:08:00 +00001048 return (sys_tun_open(tun, mode, ifname));
Damien Miller2dcddbf2006-01-01 19:47:05 +11001049#elif defined(SSH_TUN_OPENBSD)
Damien Miller7b58e802005-12-13 19:33:19 +11001050 struct ifreq ifr;
Damien Millerd27b9472005-12-13 19:29:02 +11001051 char name[100];
Damien Miller7b58e802005-12-13 19:33:19 +11001052 int fd = -1, sock;
sthen@openbsd.orga820a862015-10-24 08:34:09 +00001053 const char *tunbase = "tun";
1054
djm@openbsd.orgb7548b12017-10-23 05:08:00 +00001055 if (ifname != NULL)
1056 *ifname = NULL;
1057
sthen@openbsd.orga820a862015-10-24 08:34:09 +00001058 if (mode == SSH_TUNMODE_ETHERNET)
1059 tunbase = "tap";
Damien Millerd27b9472005-12-13 19:29:02 +11001060
Damien Miller7b58e802005-12-13 19:33:19 +11001061 /* Open the tunnel device */
1062 if (tun <= SSH_TUNID_MAX) {
sthen@openbsd.orga820a862015-10-24 08:34:09 +00001063 snprintf(name, sizeof(name), "/dev/%s%d", tunbase, tun);
Damien Miller7b58e802005-12-13 19:33:19 +11001064 fd = open(name, O_RDWR);
1065 } else if (tun == SSH_TUNID_ANY) {
1066 for (tun = 100; tun >= 0; tun--) {
sthen@openbsd.orga820a862015-10-24 08:34:09 +00001067 snprintf(name, sizeof(name), "/dev/%s%d",
1068 tunbase, tun);
Damien Miller7b58e802005-12-13 19:33:19 +11001069 if ((fd = open(name, O_RDWR)) >= 0)
1070 break;
Damien Millerd27b9472005-12-13 19:29:02 +11001071 }
1072 } else {
Damien Millera210d522006-01-02 23:40:30 +11001073 debug("%s: invalid tunnel %u", __func__, tun);
djm@openbsd.org2905d6f2015-10-07 00:54:06 +00001074 return -1;
Damien Millerd27b9472005-12-13 19:29:02 +11001075 }
Damien Miller7b58e802005-12-13 19:33:19 +11001076
1077 if (fd < 0) {
djm@openbsd.org2905d6f2015-10-07 00:54:06 +00001078 debug("%s: %s open: %s", __func__, name, strerror(errno));
1079 return -1;
Damien Miller7b58e802005-12-13 19:33:19 +11001080 }
1081
1082 debug("%s: %s mode %d fd %d", __func__, name, mode, fd);
1083
sthen@openbsd.orga820a862015-10-24 08:34:09 +00001084 /* Bring interface up if it is not already */
1085 snprintf(ifr.ifr_name, sizeof(ifr.ifr_name), "%s%d", tunbase, tun);
1086 if ((sock = socket(PF_UNIX, SOCK_STREAM, 0)) == -1)
Damien Miller7b58e802005-12-13 19:33:19 +11001087 goto failed;
1088
djm@openbsd.org2905d6f2015-10-07 00:54:06 +00001089 if (ioctl(sock, SIOCGIFFLAGS, &ifr) == -1) {
1090 debug("%s: get interface %s flags: %s", __func__,
1091 ifr.ifr_name, strerror(errno));
Damien Miller7b58e802005-12-13 19:33:19 +11001092 goto failed;
djm@openbsd.org2905d6f2015-10-07 00:54:06 +00001093 }
Damien Millera1d9a182006-01-02 23:41:21 +11001094
djm@openbsd.org2905d6f2015-10-07 00:54:06 +00001095 if (!(ifr.ifr_flags & IFF_UP)) {
1096 ifr.ifr_flags |= IFF_UP;
1097 if (ioctl(sock, SIOCSIFFLAGS, &ifr) == -1) {
1098 debug("%s: activate interface %s: %s", __func__,
1099 ifr.ifr_name, strerror(errno));
1100 goto failed;
1101 }
1102 }
Damien Miller7b58e802005-12-13 19:33:19 +11001103
djm@openbsd.orgb7548b12017-10-23 05:08:00 +00001104 if (ifname != NULL)
1105 *ifname = xstrdup(ifr.ifr_name);
1106
Damien Miller7b58e802005-12-13 19:33:19 +11001107 close(sock);
djm@openbsd.org2905d6f2015-10-07 00:54:06 +00001108 return fd;
Damien Miller7b58e802005-12-13 19:33:19 +11001109
1110 failed:
1111 if (fd >= 0)
1112 close(fd);
1113 if (sock >= 0)
1114 close(sock);
djm@openbsd.org2905d6f2015-10-07 00:54:06 +00001115 return -1;
Damien Miller62a31c92005-12-13 20:44:13 +11001116#else
1117 error("Tunnel interfaces are not supported on this platform");
1118 return (-1);
1119#endif
Damien Millerd27b9472005-12-13 19:29:02 +11001120}
1121
Darren Tuckerce321d82005-10-03 18:11:24 +10001122void
1123sanitise_stdfd(void)
1124{
Damien Miller72c5b7d2006-01-06 14:50:44 +11001125 int nullfd, dupfd;
Darren Tuckerce321d82005-10-03 18:11:24 +10001126
Damien Miller72c5b7d2006-01-06 14:50:44 +11001127 if ((nullfd = dupfd = open(_PATH_DEVNULL, O_RDWR)) == -1) {
Damien Miller9eab9562009-02-22 08:47:02 +11001128 fprintf(stderr, "Couldn't open /dev/null: %s\n",
1129 strerror(errno));
Darren Tuckerce321d82005-10-03 18:11:24 +10001130 exit(1);
1131 }
krw@openbsd.org574def02016-04-02 14:37:42 +00001132 while (++dupfd <= STDERR_FILENO) {
1133 /* Only populate closed fds. */
1134 if (fcntl(dupfd, F_GETFL) == -1 && errno == EBADF) {
1135 if (dup2(nullfd, dupfd) == -1) {
1136 fprintf(stderr, "dup2: %s\n", strerror(errno));
1137 exit(1);
1138 }
Darren Tuckerce321d82005-10-03 18:11:24 +10001139 }
Darren Tuckerce321d82005-10-03 18:11:24 +10001140 }
krw@openbsd.org574def02016-04-02 14:37:42 +00001141 if (nullfd > STDERR_FILENO)
Darren Tuckerce321d82005-10-03 18:11:24 +10001142 close(nullfd);
1143}
1144
Damien Miller13390022005-07-06 09:44:19 +10001145char *
Damien Miller3f941882006-03-31 23:13:02 +11001146tohex(const void *vp, size_t l)
Damien Miller13390022005-07-06 09:44:19 +10001147{
Damien Miller3f941882006-03-31 23:13:02 +11001148 const u_char *p = (const u_char *)vp;
Damien Miller13390022005-07-06 09:44:19 +10001149 char b[3], *r;
Damien Miller3f941882006-03-31 23:13:02 +11001150 size_t i, hl;
1151
1152 if (l > 65536)
1153 return xstrdup("tohex: length > 65536");
Damien Miller13390022005-07-06 09:44:19 +10001154
1155 hl = l * 2 + 1;
Damien Miller07d86be2006-03-26 14:19:21 +11001156 r = xcalloc(1, hl);
Damien Miller13390022005-07-06 09:44:19 +10001157 for (i = 0; i < l; i++) {
Damien Miller3f941882006-03-31 23:13:02 +11001158 snprintf(b, sizeof(b), "%02x", p[i]);
Damien Miller13390022005-07-06 09:44:19 +10001159 strlcat(r, b, hl);
1160 }
1161 return (r);
1162}
1163
Damien Miller3f941882006-03-31 23:13:02 +11001164u_int64_t
1165get_u64(const void *vp)
1166{
1167 const u_char *p = (const u_char *)vp;
1168 u_int64_t v;
1169
1170 v = (u_int64_t)p[0] << 56;
1171 v |= (u_int64_t)p[1] << 48;
1172 v |= (u_int64_t)p[2] << 40;
1173 v |= (u_int64_t)p[3] << 32;
1174 v |= (u_int64_t)p[4] << 24;
1175 v |= (u_int64_t)p[5] << 16;
1176 v |= (u_int64_t)p[6] << 8;
1177 v |= (u_int64_t)p[7];
1178
1179 return (v);
1180}
1181
1182u_int32_t
1183get_u32(const void *vp)
1184{
1185 const u_char *p = (const u_char *)vp;
1186 u_int32_t v;
1187
1188 v = (u_int32_t)p[0] << 24;
1189 v |= (u_int32_t)p[1] << 16;
1190 v |= (u_int32_t)p[2] << 8;
1191 v |= (u_int32_t)p[3];
1192
1193 return (v);
1194}
1195
Damien Miller88856692014-04-20 13:33:19 +10001196u_int32_t
1197get_u32_le(const void *vp)
1198{
1199 const u_char *p = (const u_char *)vp;
1200 u_int32_t v;
1201
1202 v = (u_int32_t)p[0];
1203 v |= (u_int32_t)p[1] << 8;
1204 v |= (u_int32_t)p[2] << 16;
1205 v |= (u_int32_t)p[3] << 24;
1206
1207 return (v);
1208}
1209
Damien Miller3f941882006-03-31 23:13:02 +11001210u_int16_t
1211get_u16(const void *vp)
1212{
1213 const u_char *p = (const u_char *)vp;
1214 u_int16_t v;
1215
1216 v = (u_int16_t)p[0] << 8;
1217 v |= (u_int16_t)p[1];
1218
1219 return (v);
1220}
1221
1222void
1223put_u64(void *vp, u_int64_t v)
1224{
1225 u_char *p = (u_char *)vp;
1226
1227 p[0] = (u_char)(v >> 56) & 0xff;
1228 p[1] = (u_char)(v >> 48) & 0xff;
1229 p[2] = (u_char)(v >> 40) & 0xff;
1230 p[3] = (u_char)(v >> 32) & 0xff;
1231 p[4] = (u_char)(v >> 24) & 0xff;
1232 p[5] = (u_char)(v >> 16) & 0xff;
1233 p[6] = (u_char)(v >> 8) & 0xff;
1234 p[7] = (u_char)v & 0xff;
1235}
1236
1237void
1238put_u32(void *vp, u_int32_t v)
1239{
1240 u_char *p = (u_char *)vp;
1241
1242 p[0] = (u_char)(v >> 24) & 0xff;
1243 p[1] = (u_char)(v >> 16) & 0xff;
1244 p[2] = (u_char)(v >> 8) & 0xff;
1245 p[3] = (u_char)v & 0xff;
1246}
1247
Damien Miller88856692014-04-20 13:33:19 +10001248void
1249put_u32_le(void *vp, u_int32_t v)
1250{
1251 u_char *p = (u_char *)vp;
1252
1253 p[0] = (u_char)v & 0xff;
1254 p[1] = (u_char)(v >> 8) & 0xff;
1255 p[2] = (u_char)(v >> 16) & 0xff;
1256 p[3] = (u_char)(v >> 24) & 0xff;
1257}
Damien Miller3f941882006-03-31 23:13:02 +11001258
1259void
1260put_u16(void *vp, u_int16_t v)
1261{
1262 u_char *p = (u_char *)vp;
1263
1264 p[0] = (u_char)(v >> 8) & 0xff;
1265 p[1] = (u_char)v & 0xff;
1266}
Darren Tucker3fc464e2008-06-13 06:42:45 +10001267
1268void
1269ms_subtract_diff(struct timeval *start, int *ms)
1270{
1271 struct timeval diff, finish;
1272
dtucker@openbsd.org@openbsd.org5db6fbf2017-11-25 06:46:22 +00001273 monotime_tv(&finish);
1274 timersub(&finish, start, &diff);
Darren Tucker3fc464e2008-06-13 06:42:45 +10001275 *ms -= (diff.tv_sec * 1000) + (diff.tv_usec / 1000);
1276}
1277
1278void
1279ms_to_timeval(struct timeval *tv, int ms)
1280{
1281 if (ms < 0)
1282 ms = 0;
1283 tv->tv_sec = ms / 1000;
1284 tv->tv_usec = (ms % 1000) * 1000;
1285}
1286
dtucker@openbsd.org@openbsd.org5db6fbf2017-11-25 06:46:22 +00001287void
1288monotime_ts(struct timespec *ts)
Darren Tuckerb759c9c2013-06-02 07:46:16 +10001289{
dtucker@openbsd.org@openbsd.org5db6fbf2017-11-25 06:46:22 +00001290 struct timeval tv;
1291#if defined(HAVE_CLOCK_GETTIME) && (defined(CLOCK_BOOTTIME) || \
1292 defined(CLOCK_MONOTONIC) || defined(CLOCK_REALTIME))
Darren Tucker94396b72013-08-08 11:52:37 +10001293 static int gettime_failed = 0;
Darren Tuckerb759c9c2013-06-02 07:46:16 +10001294
Darren Tucker94396b72013-08-08 11:52:37 +10001295 if (!gettime_failed) {
dtucker@openbsd.org@openbsd.org5db6fbf2017-11-25 06:46:22 +00001296# ifdef CLOCK_BOOTTIME
1297 if (clock_gettime(CLOCK_BOOTTIME, ts) == 0)
1298 return;
1299# endif /* CLOCK_BOOTTIME */
1300# ifdef CLOCK_MONOTONIC
1301 if (clock_gettime(CLOCK_MONOTONIC, ts) == 0)
1302 return;
1303# endif /* CLOCK_MONOTONIC */
1304# ifdef CLOCK_REALTIME
1305 /* Not monotonic, but we're almost out of options here. */
1306 if (clock_gettime(CLOCK_REALTIME, ts) == 0)
1307 return;
1308# endif /* CLOCK_REALTIME */
Darren Tucker94396b72013-08-08 11:52:37 +10001309 debug3("clock_gettime: %s", strerror(errno));
1310 gettime_failed = 1;
1311 }
dtucker@openbsd.org@openbsd.org5db6fbf2017-11-25 06:46:22 +00001312#endif /* HAVE_CLOCK_GETTIME && (BOOTTIME || MONOTONIC || REALTIME) */
1313 gettimeofday(&tv, NULL);
1314 ts->tv_sec = tv.tv_sec;
1315 ts->tv_nsec = (long)tv.tv_usec * 1000;
1316}
Darren Tucker94396b72013-08-08 11:52:37 +10001317
dtucker@openbsd.org@openbsd.org5db6fbf2017-11-25 06:46:22 +00001318void
1319monotime_tv(struct timeval *tv)
1320{
1321 struct timespec ts;
1322
1323 monotime_ts(&ts);
1324 tv->tv_sec = ts.tv_sec;
1325 tv->tv_usec = ts.tv_nsec / 1000;
1326}
1327
1328time_t
1329monotime(void)
1330{
1331 struct timespec ts;
1332
1333 monotime_ts(&ts);
1334 return ts.tv_sec;
Darren Tuckerb759c9c2013-06-02 07:46:16 +10001335}
1336
dtucker@openbsd.orgb8d4eaf2016-03-02 22:42:40 +00001337double
1338monotime_double(void)
1339{
1340 struct timespec ts;
1341
dtucker@openbsd.org@openbsd.org5db6fbf2017-11-25 06:46:22 +00001342 monotime_ts(&ts);
1343 return ts.tv_sec + ((double)ts.tv_nsec / 1000000000);
dtucker@openbsd.orgb8d4eaf2016-03-02 22:42:40 +00001344}
1345
Damien Miller65e42f82010-09-24 22:15:11 +10001346void
1347bandwidth_limit_init(struct bwlimit *bw, u_int64_t kbps, size_t buflen)
1348{
1349 bw->buflen = buflen;
1350 bw->rate = kbps;
1351 bw->thresh = bw->rate;
1352 bw->lamt = 0;
1353 timerclear(&bw->bwstart);
1354 timerclear(&bw->bwend);
1355}
1356
1357/* Callback from read/write loop to insert bandwidth-limiting delays */
1358void
1359bandwidth_limit(struct bwlimit *bw, size_t read_len)
1360{
1361 u_int64_t waitlen;
1362 struct timespec ts, rm;
1363
1364 if (!timerisset(&bw->bwstart)) {
dtucker@openbsd.org@openbsd.org5db6fbf2017-11-25 06:46:22 +00001365 monotime_tv(&bw->bwstart);
Damien Miller65e42f82010-09-24 22:15:11 +10001366 return;
1367 }
1368
1369 bw->lamt += read_len;
1370 if (bw->lamt < bw->thresh)
1371 return;
1372
dtucker@openbsd.org@openbsd.org5db6fbf2017-11-25 06:46:22 +00001373 monotime_tv(&bw->bwend);
Damien Miller65e42f82010-09-24 22:15:11 +10001374 timersub(&bw->bwend, &bw->bwstart, &bw->bwend);
1375 if (!timerisset(&bw->bwend))
1376 return;
1377
1378 bw->lamt *= 8;
1379 waitlen = (double)1000000L * bw->lamt / bw->rate;
1380
1381 bw->bwstart.tv_sec = waitlen / 1000000L;
1382 bw->bwstart.tv_usec = waitlen % 1000000L;
1383
1384 if (timercmp(&bw->bwstart, &bw->bwend, >)) {
1385 timersub(&bw->bwstart, &bw->bwend, &bw->bwend);
1386
1387 /* Adjust the wait time */
1388 if (bw->bwend.tv_sec) {
1389 bw->thresh /= 2;
1390 if (bw->thresh < bw->buflen / 4)
1391 bw->thresh = bw->buflen / 4;
1392 } else if (bw->bwend.tv_usec < 10000) {
1393 bw->thresh *= 2;
1394 if (bw->thresh > bw->buflen * 8)
1395 bw->thresh = bw->buflen * 8;
1396 }
1397
1398 TIMEVAL_TO_TIMESPEC(&bw->bwend, &ts);
1399 while (nanosleep(&ts, &rm) == -1) {
1400 if (errno != EINTR)
1401 break;
1402 ts = rm;
1403 }
1404 }
1405
1406 bw->lamt = 0;
dtucker@openbsd.org@openbsd.org5db6fbf2017-11-25 06:46:22 +00001407 monotime_tv(&bw->bwstart);
Damien Miller65e42f82010-09-24 22:15:11 +10001408}
Damien Miller0dac6fb2010-11-20 15:19:38 +11001409
Damien Miller2cd62932010-12-01 11:50:35 +11001410/* Make a template filename for mk[sd]temp() */
1411void
1412mktemp_proto(char *s, size_t len)
1413{
1414 const char *tmpdir;
1415 int r;
1416
1417 if ((tmpdir = getenv("TMPDIR")) != NULL) {
1418 r = snprintf(s, len, "%s/ssh-XXXXXXXXXXXX", tmpdir);
1419 if (r > 0 && (size_t)r < len)
1420 return;
1421 }
1422 r = snprintf(s, len, "/tmp/ssh-XXXXXXXXXXXX");
1423 if (r < 0 || (size_t)r >= len)
1424 fatal("%s: template string too short", __func__);
1425}
1426
Damien Miller0dac6fb2010-11-20 15:19:38 +11001427static const struct {
1428 const char *name;
1429 int value;
1430} ipqos[] = {
djm@openbsd.org51676ec2017-07-23 23:37:02 +00001431 { "none", INT_MAX }, /* can't use 0 here; that's CS0 */
Damien Miller0dac6fb2010-11-20 15:19:38 +11001432 { "af11", IPTOS_DSCP_AF11 },
1433 { "af12", IPTOS_DSCP_AF12 },
1434 { "af13", IPTOS_DSCP_AF13 },
Damien Miller2918e032011-09-22 21:34:35 +10001435 { "af21", IPTOS_DSCP_AF21 },
Damien Miller0dac6fb2010-11-20 15:19:38 +11001436 { "af22", IPTOS_DSCP_AF22 },
1437 { "af23", IPTOS_DSCP_AF23 },
1438 { "af31", IPTOS_DSCP_AF31 },
1439 { "af32", IPTOS_DSCP_AF32 },
1440 { "af33", IPTOS_DSCP_AF33 },
1441 { "af41", IPTOS_DSCP_AF41 },
1442 { "af42", IPTOS_DSCP_AF42 },
1443 { "af43", IPTOS_DSCP_AF43 },
1444 { "cs0", IPTOS_DSCP_CS0 },
1445 { "cs1", IPTOS_DSCP_CS1 },
1446 { "cs2", IPTOS_DSCP_CS2 },
1447 { "cs3", IPTOS_DSCP_CS3 },
1448 { "cs4", IPTOS_DSCP_CS4 },
1449 { "cs5", IPTOS_DSCP_CS5 },
1450 { "cs6", IPTOS_DSCP_CS6 },
1451 { "cs7", IPTOS_DSCP_CS7 },
1452 { "ef", IPTOS_DSCP_EF },
1453 { "lowdelay", IPTOS_LOWDELAY },
1454 { "throughput", IPTOS_THROUGHPUT },
1455 { "reliability", IPTOS_RELIABILITY },
1456 { NULL, -1 }
1457};
1458
1459int
1460parse_ipqos(const char *cp)
1461{
1462 u_int i;
1463 char *ep;
1464 long val;
1465
1466 if (cp == NULL)
1467 return -1;
1468 for (i = 0; ipqos[i].name != NULL; i++) {
1469 if (strcasecmp(cp, ipqos[i].name) == 0)
1470 return ipqos[i].value;
1471 }
1472 /* Try parsing as an integer */
1473 val = strtol(cp, &ep, 0);
1474 if (*cp == '\0' || *ep != '\0' || val < 0 || val > 255)
1475 return -1;
1476 return val;
1477}
1478
Damien Miller91475862011-05-05 14:14:34 +10001479const char *
1480iptos2str(int iptos)
1481{
1482 int i;
1483 static char iptos_str[sizeof "0xff"];
1484
1485 for (i = 0; ipqos[i].name != NULL; i++) {
1486 if (ipqos[i].value == iptos)
1487 return ipqos[i].name;
1488 }
1489 snprintf(iptos_str, sizeof iptos_str, "0x%02x", iptos);
1490 return iptos_str;
1491}
Damien Millere9fc72e2013-10-15 12:14:12 +11001492
1493void
1494lowercase(char *s)
1495{
1496 for (; *s; s++)
1497 *s = tolower((u_char)*s);
1498}
Damien Miller7acefbb2014-07-18 14:11:24 +10001499
1500int
1501unix_listener(const char *path, int backlog, int unlink_first)
1502{
1503 struct sockaddr_un sunaddr;
1504 int saved_errno, sock;
1505
1506 memset(&sunaddr, 0, sizeof(sunaddr));
1507 sunaddr.sun_family = AF_UNIX;
djm@openbsd.org155072f2017-12-08 02:13:02 +00001508 if (strlcpy(sunaddr.sun_path, path,
1509 sizeof(sunaddr.sun_path)) >= sizeof(sunaddr.sun_path)) {
1510 error("%s: path \"%s\" too long for Unix domain socket",
1511 __func__, path);
Damien Miller7acefbb2014-07-18 14:11:24 +10001512 errno = ENAMETOOLONG;
1513 return -1;
1514 }
1515
1516 sock = socket(PF_UNIX, SOCK_STREAM, 0);
1517 if (sock < 0) {
1518 saved_errno = errno;
djm@openbsd.org155072f2017-12-08 02:13:02 +00001519 error("%s: socket: %.100s", __func__, strerror(errno));
Damien Miller7acefbb2014-07-18 14:11:24 +10001520 errno = saved_errno;
1521 return -1;
1522 }
1523 if (unlink_first == 1) {
1524 if (unlink(path) != 0 && errno != ENOENT)
1525 error("unlink(%s): %.100s", path, strerror(errno));
1526 }
1527 if (bind(sock, (struct sockaddr *)&sunaddr, sizeof(sunaddr)) < 0) {
1528 saved_errno = errno;
djm@openbsd.org155072f2017-12-08 02:13:02 +00001529 error("%s: cannot bind to path %s: %s",
1530 __func__, path, strerror(errno));
djm@openbsd.orgfd4eeee2017-12-08 02:14:33 +00001531 close(sock);
Damien Miller7acefbb2014-07-18 14:11:24 +10001532 errno = saved_errno;
1533 return -1;
1534 }
1535 if (listen(sock, backlog) < 0) {
1536 saved_errno = errno;
djm@openbsd.org155072f2017-12-08 02:13:02 +00001537 error("%s: cannot listen on path %s: %s",
1538 __func__, path, strerror(errno));
djm@openbsd.orgfd4eeee2017-12-08 02:14:33 +00001539 close(sock);
1540 unlink(path);
Damien Miller7acefbb2014-07-18 14:11:24 +10001541 errno = saved_errno;
1542 return -1;
1543 }
1544 return sock;
1545}
Damien Miller46878022014-08-30 03:29:19 +10001546
Damien Miller04ee0f82009-11-18 17:48:30 +11001547void
1548sock_set_v6only(int s)
1549{
Damien Millerd86a3ba2015-12-09 09:18:45 +11001550#if defined(IPV6_V6ONLY) && !defined(__OpenBSD__)
Damien Miller04ee0f82009-11-18 17:48:30 +11001551 int on = 1;
1552
1553 debug3("%s: set socket %d IPV6_V6ONLY", __func__, s);
1554 if (setsockopt(s, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof(on)) == -1)
1555 error("setsockopt IPV6_V6ONLY: %s", strerror(errno));
1556#endif
1557}
djm@openbsd.org0ccbd5e2016-04-06 06:42:17 +00001558
1559/*
1560 * Compares two strings that maybe be NULL. Returns non-zero if strings
1561 * are both NULL or are identical, returns zero otherwise.
1562 */
1563static int
1564strcmp_maybe_null(const char *a, const char *b)
1565{
1566 if ((a == NULL && b != NULL) || (a != NULL && b == NULL))
1567 return 0;
1568 if (a != NULL && strcmp(a, b) != 0)
1569 return 0;
1570 return 1;
1571}
1572
1573/*
1574 * Compare two forwards, returning non-zero if they are identical or
1575 * zero otherwise.
1576 */
1577int
1578forward_equals(const struct Forward *a, const struct Forward *b)
1579{
1580 if (strcmp_maybe_null(a->listen_host, b->listen_host) == 0)
1581 return 0;
1582 if (a->listen_port != b->listen_port)
1583 return 0;
1584 if (strcmp_maybe_null(a->listen_path, b->listen_path) == 0)
1585 return 0;
1586 if (strcmp_maybe_null(a->connect_host, b->connect_host) == 0)
1587 return 0;
1588 if (a->connect_port != b->connect_port)
1589 return 0;
1590 if (strcmp_maybe_null(a->connect_path, b->connect_path) == 0)
1591 return 0;
1592 /* allocated_port and handle are not checked */
1593 return 1;
1594}
1595
dtucker@openbsd.org1c4ef0b2016-10-23 22:04:05 +00001596/* returns 1 if bind to specified port by specified user is permitted */
1597int
1598bind_permitted(int port, uid_t uid)
1599{
1600 if (port < IPPORT_RESERVED && uid != 0)
1601 return 0;
1602 return 1;
1603}
dtucker@openbsd.org7fc47662016-11-30 00:28:31 +00001604
1605/* returns 1 if process is already daemonized, 0 otherwise */
1606int
1607daemonized(void)
1608{
1609 int fd;
1610
1611 if ((fd = open(_PATH_TTY, O_RDONLY | O_NOCTTY)) >= 0) {
1612 close(fd);
1613 return 0; /* have controlling terminal */
1614 }
1615 if (getppid() != 1)
1616 return 0; /* parent is not init */
1617 if (getsid(0) != getpid())
1618 return 0; /* not session leader */
1619 debug3("already daemonized");
1620 return 1;
1621}
djm@openbsd.orgde4ae072017-08-18 05:36:45 +00001622
1623
1624/*
1625 * Splits 's' into an argument vector. Handles quoted string and basic
1626 * escape characters (\\, \", \'). Caller must free the argument vector
1627 * and its members.
1628 */
1629int
1630argv_split(const char *s, int *argcp, char ***argvp)
1631{
1632 int r = SSH_ERR_INTERNAL_ERROR;
1633 int argc = 0, quote, i, j;
1634 char *arg, **argv = xcalloc(1, sizeof(*argv));
1635
1636 *argvp = NULL;
1637 *argcp = 0;
1638
1639 for (i = 0; s[i] != '\0'; i++) {
1640 /* Skip leading whitespace */
1641 if (s[i] == ' ' || s[i] == '\t')
1642 continue;
1643
1644 /* Start of a token */
1645 quote = 0;
1646 if (s[i] == '\\' &&
1647 (s[i + 1] == '\'' || s[i + 1] == '\"' || s[i + 1] == '\\'))
1648 i++;
1649 else if (s[i] == '\'' || s[i] == '"')
1650 quote = s[i++];
1651
1652 argv = xreallocarray(argv, (argc + 2), sizeof(*argv));
1653 arg = argv[argc++] = xcalloc(1, strlen(s + i) + 1);
1654 argv[argc] = NULL;
1655
1656 /* Copy the token in, removing escapes */
1657 for (j = 0; s[i] != '\0'; i++) {
1658 if (s[i] == '\\') {
1659 if (s[i + 1] == '\'' ||
1660 s[i + 1] == '\"' ||
1661 s[i + 1] == '\\') {
1662 i++; /* Skip '\' */
1663 arg[j++] = s[i];
1664 } else {
1665 /* Unrecognised escape */
1666 arg[j++] = s[i];
1667 }
1668 } else if (quote == 0 && (s[i] == ' ' || s[i] == '\t'))
1669 break; /* done */
1670 else if (quote != 0 && s[i] == quote)
1671 break; /* done */
1672 else
1673 arg[j++] = s[i];
1674 }
1675 if (s[i] == '\0') {
1676 if (quote != 0) {
1677 /* Ran out of string looking for close quote */
1678 r = SSH_ERR_INVALID_FORMAT;
1679 goto out;
1680 }
1681 break;
1682 }
1683 }
1684 /* Success */
1685 *argcp = argc;
1686 *argvp = argv;
1687 argc = 0;
1688 argv = NULL;
1689 r = 0;
1690 out:
1691 if (argc != 0 && argv != NULL) {
1692 for (i = 0; i < argc; i++)
1693 free(argv[i]);
1694 free(argv);
1695 }
1696 return r;
1697}
1698
1699/*
1700 * Reassemble an argument vector into a string, quoting and escaping as
1701 * necessary. Caller must free returned string.
1702 */
1703char *
1704argv_assemble(int argc, char **argv)
1705{
1706 int i, j, ws, r;
1707 char c, *ret;
1708 struct sshbuf *buf, *arg;
1709
1710 if ((buf = sshbuf_new()) == NULL || (arg = sshbuf_new()) == NULL)
1711 fatal("%s: sshbuf_new failed", __func__);
1712
1713 for (i = 0; i < argc; i++) {
1714 ws = 0;
1715 sshbuf_reset(arg);
1716 for (j = 0; argv[i][j] != '\0'; j++) {
1717 r = 0;
1718 c = argv[i][j];
1719 switch (c) {
1720 case ' ':
1721 case '\t':
1722 ws = 1;
1723 r = sshbuf_put_u8(arg, c);
1724 break;
1725 case '\\':
1726 case '\'':
1727 case '"':
1728 if ((r = sshbuf_put_u8(arg, '\\')) != 0)
1729 break;
1730 /* FALLTHROUGH */
1731 default:
1732 r = sshbuf_put_u8(arg, c);
1733 break;
1734 }
1735 if (r != 0)
1736 fatal("%s: sshbuf_put_u8: %s",
1737 __func__, ssh_err(r));
1738 }
1739 if ((i != 0 && (r = sshbuf_put_u8(buf, ' ')) != 0) ||
1740 (ws != 0 && (r = sshbuf_put_u8(buf, '"')) != 0) ||
1741 (r = sshbuf_putb(buf, arg)) != 0 ||
1742 (ws != 0 && (r = sshbuf_put_u8(buf, '"')) != 0))
1743 fatal("%s: buffer error: %s", __func__, ssh_err(r));
1744 }
1745 if ((ret = malloc(sshbuf_len(buf) + 1)) == NULL)
1746 fatal("%s: malloc failed", __func__);
1747 memcpy(ret, sshbuf_ptr(buf), sshbuf_len(buf));
1748 ret[sshbuf_len(buf)] = '\0';
1749 sshbuf_free(buf);
1750 sshbuf_free(arg);
1751 return ret;
1752}
1753
djm@openbsd.orgde4ae072017-08-18 05:36:45 +00001754/* Returns 0 if pid exited cleanly, non-zero otherwise */
1755int
djm@openbsd.orgb074c3c2017-08-18 05:48:04 +00001756exited_cleanly(pid_t pid, const char *tag, const char *cmd, int quiet)
djm@openbsd.orgde4ae072017-08-18 05:36:45 +00001757{
1758 int status;
1759
1760 while (waitpid(pid, &status, 0) == -1) {
1761 if (errno != EINTR) {
1762 error("%s: waitpid: %s", tag, strerror(errno));
1763 return -1;
1764 }
1765 }
1766 if (WIFSIGNALED(status)) {
1767 error("%s %s exited on signal %d", tag, cmd, WTERMSIG(status));
1768 return -1;
1769 } else if (WEXITSTATUS(status) != 0) {
djm@openbsd.orgb074c3c2017-08-18 05:48:04 +00001770 do_log2(quiet ? SYSLOG_LEVEL_DEBUG1 : SYSLOG_LEVEL_INFO,
1771 "%s %s failed, status %d", tag, cmd, WEXITSTATUS(status));
djm@openbsd.orgde4ae072017-08-18 05:36:45 +00001772 return -1;
1773 }
1774 return 0;
1775}
1776
1777/*
1778 * Check a given path for security. This is defined as all components
1779 * of the path to the file must be owned by either the owner of
1780 * of the file or root and no directories must be group or world writable.
1781 *
1782 * XXX Should any specific check be done for sym links ?
1783 *
1784 * Takes a file name, its stat information (preferably from fstat() to
1785 * avoid races), the uid of the expected owner, their home directory and an
1786 * error buffer plus max size as arguments.
1787 *
1788 * Returns 0 on success and -1 on failure
1789 */
1790int
1791safe_path(const char *name, struct stat *stp, const char *pw_dir,
1792 uid_t uid, char *err, size_t errlen)
1793{
1794 char buf[PATH_MAX], homedir[PATH_MAX];
1795 char *cp;
1796 int comparehome = 0;
1797 struct stat st;
1798
1799 if (realpath(name, buf) == NULL) {
1800 snprintf(err, errlen, "realpath %s failed: %s", name,
1801 strerror(errno));
1802 return -1;
1803 }
1804 if (pw_dir != NULL && realpath(pw_dir, homedir) != NULL)
1805 comparehome = 1;
1806
1807 if (!S_ISREG(stp->st_mode)) {
1808 snprintf(err, errlen, "%s is not a regular file", buf);
1809 return -1;
1810 }
1811 if ((!platform_sys_dir_uid(stp->st_uid) && stp->st_uid != uid) ||
1812 (stp->st_mode & 022) != 0) {
1813 snprintf(err, errlen, "bad ownership or modes for file %s",
1814 buf);
1815 return -1;
1816 }
1817
1818 /* for each component of the canonical path, walking upwards */
1819 for (;;) {
1820 if ((cp = dirname(buf)) == NULL) {
1821 snprintf(err, errlen, "dirname() failed");
1822 return -1;
1823 }
1824 strlcpy(buf, cp, sizeof(buf));
1825
1826 if (stat(buf, &st) < 0 ||
1827 (!platform_sys_dir_uid(st.st_uid) && st.st_uid != uid) ||
1828 (st.st_mode & 022) != 0) {
1829 snprintf(err, errlen,
1830 "bad ownership or modes for directory %s", buf);
1831 return -1;
1832 }
1833
1834 /* If are past the homedir then we can stop */
1835 if (comparehome && strcmp(homedir, buf) == 0)
1836 break;
1837
1838 /*
1839 * dirname should always complete with a "/" path,
1840 * but we can be paranoid and check for "." too
1841 */
1842 if ((strcmp("/", buf) == 0) || (strcmp(".", buf) == 0))
1843 break;
1844 }
1845 return 0;
1846}
1847
1848/*
1849 * Version of safe_path() that accepts an open file descriptor to
1850 * avoid races.
1851 *
1852 * Returns 0 on success and -1 on failure
1853 */
1854int
1855safe_path_fd(int fd, const char *file, struct passwd *pw,
1856 char *err, size_t errlen)
1857{
1858 struct stat st;
1859
1860 /* check the open file to avoid races */
1861 if (fstat(fd, &st) < 0) {
1862 snprintf(err, errlen, "cannot stat file %s: %s",
1863 file, strerror(errno));
1864 return -1;
1865 }
1866 return safe_path(file, &st, pw->pw_dir, pw->pw_uid, err, errlen);
1867}
1868
1869/*
1870 * Sets the value of the given variable in the environment. If the variable
1871 * already exists, its value is overridden.
1872 */
1873void
1874child_set_env(char ***envp, u_int *envsizep, const char *name,
1875 const char *value)
1876{
1877 char **env;
1878 u_int envsize;
1879 u_int i, namelen;
1880
1881 if (strchr(name, '=') != NULL) {
1882 error("Invalid environment variable \"%.100s\"", name);
1883 return;
1884 }
1885
1886 /*
1887 * If we're passed an uninitialized list, allocate a single null
1888 * entry before continuing.
1889 */
1890 if (*envp == NULL && *envsizep == 0) {
1891 *envp = xmalloc(sizeof(char *));
1892 *envp[0] = NULL;
1893 *envsizep = 1;
1894 }
1895
1896 /*
1897 * Find the slot where the value should be stored. If the variable
1898 * already exists, we reuse the slot; otherwise we append a new slot
1899 * at the end of the array, expanding if necessary.
1900 */
1901 env = *envp;
1902 namelen = strlen(name);
1903 for (i = 0; env[i]; i++)
1904 if (strncmp(env[i], name, namelen) == 0 && env[i][namelen] == '=')
1905 break;
1906 if (env[i]) {
1907 /* Reuse the slot. */
1908 free(env[i]);
1909 } else {
1910 /* New variable. Expand if necessary. */
1911 envsize = *envsizep;
1912 if (i >= envsize - 1) {
1913 if (envsize >= 1000)
1914 fatal("child_set_env: too many env vars");
1915 envsize += 50;
1916 env = (*envp) = xreallocarray(env, envsize, sizeof(char *));
1917 *envsizep = envsize;
1918 }
1919 /* Need to set the NULL pointer at end of array beyond the new slot. */
1920 env[i + 1] = NULL;
1921 }
1922
1923 /* Allocate space and format the variable in the appropriate slot. */
djm@openbsd.org7c856852018-03-03 03:15:51 +00001924 /* XXX xasprintf */
djm@openbsd.orgde4ae072017-08-18 05:36:45 +00001925 env[i] = xmalloc(strlen(name) + 1 + strlen(value) + 1);
1926 snprintf(env[i], strlen(name) + 1 + strlen(value) + 1, "%s=%s", name, value);
1927}
1928
millert@openbsd.org887669e2017-10-21 23:06:24 +00001929/*
1930 * Check and optionally lowercase a domain name, also removes trailing '.'
1931 * Returns 1 on success and 0 on failure, storing an error message in errstr.
1932 */
1933int
1934valid_domain(char *name, int makelower, const char **errstr)
1935{
1936 size_t i, l = strlen(name);
1937 u_char c, last = '\0';
1938 static char errbuf[256];
1939
1940 if (l == 0) {
1941 strlcpy(errbuf, "empty domain name", sizeof(errbuf));
1942 goto bad;
1943 }
1944 if (!isalpha((u_char)name[0]) && !isdigit((u_char)name[0])) {
1945 snprintf(errbuf, sizeof(errbuf), "domain name \"%.100s\" "
1946 "starts with invalid character", name);
1947 goto bad;
1948 }
1949 for (i = 0; i < l; i++) {
1950 c = tolower((u_char)name[i]);
1951 if (makelower)
1952 name[i] = (char)c;
1953 if (last == '.' && c == '.') {
1954 snprintf(errbuf, sizeof(errbuf), "domain name "
1955 "\"%.100s\" contains consecutive separators", name);
1956 goto bad;
1957 }
1958 if (c != '.' && c != '-' && !isalnum(c) &&
1959 c != '_') /* technically invalid, but common */ {
1960 snprintf(errbuf, sizeof(errbuf), "domain name "
1961 "\"%.100s\" contains invalid characters", name);
1962 goto bad;
1963 }
1964 last = c;
1965 }
1966 if (name[l - 1] == '.')
1967 name[l - 1] = '\0';
1968 if (errstr != NULL)
1969 *errstr = NULL;
1970 return 1;
1971bad:
1972 if (errstr != NULL)
1973 *errstr = errbuf;
1974 return 0;
1975}
dtucker@openbsd.org609d96b2017-12-05 23:59:47 +00001976
1977const char *
1978atoi_err(const char *nptr, int *val)
1979{
1980 const char *errstr = NULL;
1981 long long num;
1982
1983 if (nptr == NULL || *nptr == '\0')
1984 return "missing";
1985 num = strtonum(nptr, 0, INT_MAX, &errstr);
1986 if (errstr == NULL)
1987 *val = (int)num;
1988 return errstr;
1989}