blob: 874dcc8a2344685fc1118133ab3dabfc9c424339 [file] [log] [blame]
djm@openbsd.orgbf0fbf22018-03-12 00:52:01 +00001/* $OpenBSD: misc.c,v 1.127 2018/03/12 00:52:01 djm Exp $ */
Damien Millere4340be2000-09-16 13:29:08 +11002/*
3 * Copyright (c) 2000 Markus Friedl. All rights reserved.
Damien Miller3f941882006-03-31 23:13:02 +11004 * Copyright (c) 2005,2006 Damien Miller. All rights reserved.
Damien Millere4340be2000-09-16 13:29:08 +11005 *
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions
8 * are met:
9 * 1. Redistributions of source code must retain the above copyright
10 * notice, this list of conditions and the following disclaimer.
11 * 2. Redistributions in binary form must reproduce the above copyright
12 * notice, this list of conditions and the following disclaimer in the
13 * documentation and/or other materials provided with the distribution.
14 *
15 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
16 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
17 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
18 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
19 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
20 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
21 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
22 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
23 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
24 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
25 */
26
Damien Miller61c51502000-08-18 14:01:04 +100027#include "includes.h"
Damien Miller17e91c02006-03-15 11:28:34 +110028
Damien Miller9f2abc42006-07-10 20:53:08 +100029#include <sys/types.h>
Damien Millerd7834352006-08-05 12:39:39 +100030#include <sys/ioctl.h>
Damien Miller8ec8c3e2006-07-10 20:35:38 +100031#include <sys/socket.h>
djm@openbsd.orgde4ae072017-08-18 05:36:45 +000032#include <sys/stat.h>
dtucker@openbsd.org65a3c0d2016-01-20 09:22:39 +000033#include <sys/time.h>
djm@openbsd.orgde4ae072017-08-18 05:36:45 +000034#include <sys/wait.h>
Damien Miller7acefbb2014-07-18 14:11:24 +100035#include <sys/un.h>
Damien Miller8ec8c3e2006-07-10 20:35:38 +100036
deraadt@openbsd.org2ae4f332015-01-16 06:40:12 +000037#include <limits.h>
djm@openbsd.orgde4ae072017-08-18 05:36:45 +000038#ifdef HAVE_LIBGEN_H
39# include <libgen.h>
40#endif
41#include <signal.h>
Darren Tucker5d196262006-07-12 22:15:16 +100042#include <stdarg.h>
Damien Millera7a73ee2006-08-05 11:37:59 +100043#include <stdio.h>
Damien Millere7a1e5c2006-08-05 11:34:19 +100044#include <stdlib.h>
Damien Millere3476ed2006-07-24 14:13:33 +100045#include <string.h>
Damien Miller1708cb72011-01-13 12:21:34 +110046#include <time.h>
Damien Millere6b3b612006-07-24 14:01:23 +100047#include <unistd.h>
Darren Tucker5d196262006-07-12 22:15:16 +100048
Damien Miller8ec8c3e2006-07-10 20:35:38 +100049#include <netinet/in.h>
Damien Miller0dac6fb2010-11-20 15:19:38 +110050#include <netinet/in_systm.h>
51#include <netinet/ip.h>
Damien Miller3a4051e2006-03-15 11:19:42 +110052#include <netinet/tcp.h>
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.orgc7c458e2018-03-07 23:53:08 +0000245 char *old;
Damien Miller61c51502000-08-18 14:01:04 +1000246 int wspace = 0;
247
248 if (*s == NULL)
249 return NULL;
250
251 old = *s;
252
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 */
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 */
270 if (*s[0] == '=')
271 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;
276 if (*s[0] == '=' && !wspace)
277 *s += strspn(*s + 1, WHITESPACE) + 1;
278
279 return (old);
280}
Kevin Stevesb6e773a2001-02-04 13:20:36 +0000281
Ben Lindstrom086cf212001-03-05 05:56:40 +0000282struct passwd *
283pwcopy(struct passwd *pw)
284{
Damien Miller07d86be2006-03-26 14:19:21 +1100285 struct passwd *copy = xcalloc(1, sizeof(*copy));
Ben Lindstrom40304422001-03-05 06:22:01 +0000286
Ben Lindstrom086cf212001-03-05 05:56:40 +0000287 copy->pw_name = xstrdup(pw->pw_name);
288 copy->pw_passwd = xstrdup(pw->pw_passwd);
Damien Miller6332da22013-04-23 14:25:52 +1000289#ifdef HAVE_STRUCT_PASSWD_PW_GECOS
Ben Lindstrom40304422001-03-05 06:22:01 +0000290 copy->pw_gecos = xstrdup(pw->pw_gecos);
Damien Miller6332da22013-04-23 14:25:52 +1000291#endif
Ben Lindstrom086cf212001-03-05 05:56:40 +0000292 copy->pw_uid = pw->pw_uid;
293 copy->pw_gid = pw->pw_gid;
Damien Miller6332da22013-04-23 14:25:52 +1000294#ifdef HAVE_STRUCT_PASSWD_PW_EXPIRE
Ben Lindstrom3af4d462001-06-21 03:11:27 +0000295 copy->pw_expire = pw->pw_expire;
Kevin Steves82456952001-06-22 21:14:18 +0000296#endif
Damien Miller6332da22013-04-23 14:25:52 +1000297#ifdef HAVE_STRUCT_PASSWD_PW_CHANGE
Ben Lindstrom3af4d462001-06-21 03:11:27 +0000298 copy->pw_change = pw->pw_change;
Kevin Steves82456952001-06-22 21:14:18 +0000299#endif
Damien Miller6332da22013-04-23 14:25:52 +1000300#ifdef HAVE_STRUCT_PASSWD_PW_CLASS
Ben Lindstrom086cf212001-03-05 05:56:40 +0000301 copy->pw_class = xstrdup(pw->pw_class);
Ben Lindstrom0f68db42001-03-05 07:57:09 +0000302#endif
Ben Lindstrom086cf212001-03-05 05:56:40 +0000303 copy->pw_dir = xstrdup(pw->pw_dir);
304 copy->pw_shell = xstrdup(pw->pw_shell);
305 return copy;
306}
307
Ben Lindstrom4cc240d2001-07-04 04:46:56 +0000308/*
309 * Convert ASCII string to TCP/IP port number.
Damien Miller3dc71ad2009-01-28 16:31:22 +1100310 * Port must be >=0 and <=65535.
311 * Return -1 if invalid.
Ben Lindstrom4cc240d2001-07-04 04:46:56 +0000312 */
313int
314a2port(const char *s)
Ben Lindstrom19066a12001-04-12 23:39:26 +0000315{
Damien Miller3dc71ad2009-01-28 16:31:22 +1100316 long long port;
317 const char *errstr;
Ben Lindstrom19066a12001-04-12 23:39:26 +0000318
Damien Miller3dc71ad2009-01-28 16:31:22 +1100319 port = strtonum(s, 0, 65535, &errstr);
320 if (errstr != NULL)
321 return -1;
322 return (int)port;
Ben Lindstrom19066a12001-04-12 23:39:26 +0000323}
324
Damien Millerd27b9472005-12-13 19:29:02 +1100325int
326a2tun(const char *s, int *remote)
327{
328 const char *errstr = NULL;
329 char *sp, *ep;
330 int tun;
331
332 if (remote != NULL) {
Damien Miller7b58e802005-12-13 19:33:19 +1100333 *remote = SSH_TUNID_ANY;
Damien Millerd27b9472005-12-13 19:29:02 +1100334 sp = xstrdup(s);
335 if ((ep = strchr(sp, ':')) == NULL) {
Darren Tuckera627d422013-06-02 07:31:17 +1000336 free(sp);
Damien Millerd27b9472005-12-13 19:29:02 +1100337 return (a2tun(s, NULL));
338 }
339 ep[0] = '\0'; ep++;
340 *remote = a2tun(ep, NULL);
341 tun = a2tun(sp, NULL);
Darren Tuckera627d422013-06-02 07:31:17 +1000342 free(sp);
Damien Miller7b58e802005-12-13 19:33:19 +1100343 return (*remote == SSH_TUNID_ERR ? *remote : tun);
Damien Millerd27b9472005-12-13 19:29:02 +1100344 }
345
346 if (strcasecmp(s, "any") == 0)
Damien Miller7b58e802005-12-13 19:33:19 +1100347 return (SSH_TUNID_ANY);
Damien Millerd27b9472005-12-13 19:29:02 +1100348
Damien Miller7b58e802005-12-13 19:33:19 +1100349 tun = strtonum(s, 0, SSH_TUNID_MAX, &errstr);
350 if (errstr != NULL)
351 return (SSH_TUNID_ERR);
Damien Millerd27b9472005-12-13 19:29:02 +1100352
353 return (tun);
354}
355
Ben Lindstrom1bda4c82001-06-05 19:59:08 +0000356#define SECONDS 1
357#define MINUTES (SECONDS * 60)
358#define HOURS (MINUTES * 60)
359#define DAYS (HOURS * 24)
360#define WEEKS (DAYS * 7)
361
Ben Lindstrom4cc240d2001-07-04 04:46:56 +0000362/*
363 * Convert a time string into seconds; format is
364 * a sequence of:
365 * time[qualifier]
366 *
367 * Valid time qualifiers are:
368 * <none> seconds
369 * s|S seconds
370 * m|M minutes
371 * h|H hours
372 * d|D days
373 * w|W weeks
374 *
375 * Examples:
376 * 90m 90 minutes
377 * 1h30m 90 minutes
378 * 2d 2 days
379 * 1w 1 week
380 *
381 * Return -1 if time string is invalid.
382 */
383long
384convtime(const char *s)
Ben Lindstrom1bda4c82001-06-05 19:59:08 +0000385{
dtucker@openbsd.orgf5746b42017-03-14 00:25:03 +0000386 long total, secs, multiplier = 1;
Ben Lindstrom1bda4c82001-06-05 19:59:08 +0000387 const char *p;
388 char *endp;
389
390 errno = 0;
391 total = 0;
392 p = s;
393
394 if (p == NULL || *p == '\0')
395 return -1;
396
397 while (*p) {
398 secs = strtol(p, &endp, 10);
399 if (p == endp ||
400 (errno == ERANGE && (secs == LONG_MIN || secs == LONG_MAX)) ||
401 secs < 0)
402 return -1;
403
404 switch (*endp++) {
405 case '\0':
406 endp--;
Damien Miller69b72032006-03-26 14:02:35 +1100407 break;
Ben Lindstrom1bda4c82001-06-05 19:59:08 +0000408 case 's':
409 case 'S':
410 break;
411 case 'm':
412 case 'M':
dtucker@openbsd.orgf5746b42017-03-14 00:25:03 +0000413 multiplier = MINUTES;
Ben Lindstrom1bda4c82001-06-05 19:59:08 +0000414 break;
415 case 'h':
416 case 'H':
dtucker@openbsd.orgf5746b42017-03-14 00:25:03 +0000417 multiplier = HOURS;
Ben Lindstrom1bda4c82001-06-05 19:59:08 +0000418 break;
419 case 'd':
420 case 'D':
dtucker@openbsd.orgf5746b42017-03-14 00:25:03 +0000421 multiplier = DAYS;
Ben Lindstrom1bda4c82001-06-05 19:59:08 +0000422 break;
423 case 'w':
424 case 'W':
dtucker@openbsd.orgf5746b42017-03-14 00:25:03 +0000425 multiplier = WEEKS;
Ben Lindstrom1bda4c82001-06-05 19:59:08 +0000426 break;
427 default:
428 return -1;
429 }
dtucker@openbsd.orgc6774d22017-03-14 00:55:37 +0000430 if (secs >= LONG_MAX / multiplier)
dtucker@openbsd.orgf5746b42017-03-14 00:25:03 +0000431 return -1;
432 secs *= multiplier;
dtucker@openbsd.orgc6774d22017-03-14 00:55:37 +0000433 if (total >= LONG_MAX - secs)
dtucker@openbsd.orgf5746b42017-03-14 00:25:03 +0000434 return -1;
Ben Lindstrom1bda4c82001-06-05 19:59:08 +0000435 total += secs;
436 if (total < 0)
437 return -1;
438 p = endp;
439 }
440
441 return total;
442}
443
Damien Millerf91ee4c2005-03-01 21:24:33 +1100444/*
Darren Tuckerda345532006-07-10 23:04:19 +1000445 * Returns a standardized host+port identifier string.
446 * Caller must free returned string.
447 */
448char *
449put_host_port(const char *host, u_short port)
450{
451 char *hoststr;
452
453 if (port == 0 || port == SSH_DEFAULT_PORT)
454 return(xstrdup(host));
455 if (asprintf(&hoststr, "[%s]:%d", host, (int)port) < 0)
456 fatal("put_host_port: asprintf: %s", strerror(errno));
457 debug3("put_host_port: %s", hoststr);
458 return hoststr;
459}
460
461/*
Damien Millerf91ee4c2005-03-01 21:24:33 +1100462 * Search for next delimiter between hostnames/addresses and ports.
463 * Argument may be modified (for termination).
464 * Returns *cp if parsing succeeds.
millert@openbsd.org887669e2017-10-21 23:06:24 +0000465 * *cp is set to the start of the next field, if one was found.
466 * The delimiter char, if present, is stored in delim.
Damien Millerf91ee4c2005-03-01 21:24:33 +1100467 * If this is the last field, *cp is set to NULL.
468 */
millert@openbsd.org887669e2017-10-21 23:06:24 +0000469static char *
470hpdelim2(char **cp, char *delim)
Damien Millerf91ee4c2005-03-01 21:24:33 +1100471{
472 char *s, *old;
473
474 if (cp == NULL || *cp == NULL)
475 return NULL;
476
477 old = s = *cp;
478 if (*s == '[') {
479 if ((s = strchr(s, ']')) == NULL)
480 return NULL;
481 else
482 s++;
483 } else if ((s = strpbrk(s, ":/")) == NULL)
484 s = *cp + strlen(*cp); /* skip to end (see first case below) */
485
486 switch (*s) {
487 case '\0':
488 *cp = NULL; /* no more fields*/
489 break;
Darren Tucker47eede72005-03-14 23:08:12 +1100490
Damien Millerf91ee4c2005-03-01 21:24:33 +1100491 case ':':
492 case '/':
millert@openbsd.org887669e2017-10-21 23:06:24 +0000493 if (delim != NULL)
494 *delim = *s;
Damien Millerf91ee4c2005-03-01 21:24:33 +1100495 *s = '\0'; /* terminate */
496 *cp = s + 1;
497 break;
Darren Tucker47eede72005-03-14 23:08:12 +1100498
Damien Millerf91ee4c2005-03-01 21:24:33 +1100499 default:
500 return NULL;
501 }
502
503 return old;
504}
505
Ben Lindstrom4529b702001-05-03 23:39:53 +0000506char *
millert@openbsd.org887669e2017-10-21 23:06:24 +0000507hpdelim(char **cp)
508{
509 return hpdelim2(cp, NULL);
510}
511
512char *
Ben Lindstrom4529b702001-05-03 23:39:53 +0000513cleanhostname(char *host)
514{
515 if (*host == '[' && host[strlen(host) - 1] == ']') {
516 host[strlen(host) - 1] = '\0';
517 return (host + 1);
518 } else
519 return host;
520}
521
522char *
523colon(char *cp)
524{
525 int flag = 0;
526
527 if (*cp == ':') /* Leading colon is part of file name. */
Damien Miller2e774462010-06-26 09:30:47 +1000528 return NULL;
Ben Lindstrom4529b702001-05-03 23:39:53 +0000529 if (*cp == '[')
530 flag = 1;
531
532 for (; *cp; ++cp) {
533 if (*cp == '@' && *(cp+1) == '[')
534 flag = 1;
535 if (*cp == ']' && *(cp+1) == ':' && flag)
536 return (cp+1);
537 if (*cp == ':' && !flag)
538 return (cp);
539 if (*cp == '/')
Damien Miller2e774462010-06-26 09:30:47 +1000540 return NULL;
Ben Lindstrom4529b702001-05-03 23:39:53 +0000541 }
Damien Miller2e774462010-06-26 09:30:47 +1000542 return NULL;
Ben Lindstrom4529b702001-05-03 23:39:53 +0000543}
544
djm@openbsd.orged877ef2016-07-15 00:24:30 +0000545/*
millert@openbsd.org887669e2017-10-21 23:06:24 +0000546 * Parse a [user@]host:[path] string.
547 * Caller must free returned user, host and path.
548 * Any of the pointer return arguments may be NULL (useful for syntax checking).
549 * If user was not specified then *userp will be set to NULL.
550 * If host was not specified then *hostp will be set to NULL.
551 * If path was not specified then *pathp will be set to ".".
552 * Returns 0 on success, -1 on failure.
553 */
554int
555parse_user_host_path(const char *s, char **userp, char **hostp, char **pathp)
556{
557 char *user = NULL, *host = NULL, *path = NULL;
558 char *sdup, *tmp;
559 int ret = -1;
560
561 if (userp != NULL)
562 *userp = NULL;
563 if (hostp != NULL)
564 *hostp = NULL;
565 if (pathp != NULL)
566 *pathp = NULL;
567
millert@openbsd.orgb9903ee2017-10-24 19:41:45 +0000568 sdup = xstrdup(s);
millert@openbsd.org887669e2017-10-21 23:06:24 +0000569
570 /* Check for remote syntax: [user@]host:[path] */
571 if ((tmp = colon(sdup)) == NULL)
572 goto out;
573
574 /* Extract optional path */
575 *tmp++ = '\0';
576 if (*tmp == '\0')
577 tmp = ".";
578 path = xstrdup(tmp);
579
580 /* Extract optional user and mandatory host */
581 tmp = strrchr(sdup, '@');
582 if (tmp != NULL) {
583 *tmp++ = '\0';
584 host = xstrdup(cleanhostname(tmp));
585 if (*sdup != '\0')
586 user = xstrdup(sdup);
587 } else {
588 host = xstrdup(cleanhostname(sdup));
589 user = NULL;
590 }
591
592 /* Success */
593 if (userp != NULL) {
594 *userp = user;
595 user = NULL;
596 }
597 if (hostp != NULL) {
598 *hostp = host;
599 host = NULL;
millert@openbsd.orgb9903ee2017-10-24 19:41:45 +0000600 }
millert@openbsd.org887669e2017-10-21 23:06:24 +0000601 if (pathp != NULL) {
602 *pathp = path;
603 path = NULL;
millert@openbsd.orgb9903ee2017-10-24 19:41:45 +0000604 }
millert@openbsd.org887669e2017-10-21 23:06:24 +0000605 ret = 0;
606out:
607 free(sdup);
608 free(user);
609 free(host);
610 free(path);
611 return ret;
612}
613
614/*
djm@openbsd.orged877ef2016-07-15 00:24:30 +0000615 * Parse a [user@]host[:port] string.
616 * Caller must free returned user and host.
617 * Any of the pointer return arguments may be NULL (useful for syntax checking).
618 * If user was not specified then *userp will be set to NULL.
619 * If port was not specified then *portp will be -1.
620 * Returns 0 on success, -1 on failure.
621 */
622int
623parse_user_host_port(const char *s, char **userp, char **hostp, int *portp)
624{
625 char *sdup, *cp, *tmp;
626 char *user = NULL, *host = NULL;
627 int port = -1, ret = -1;
628
629 if (userp != NULL)
630 *userp = NULL;
631 if (hostp != NULL)
632 *hostp = NULL;
633 if (portp != NULL)
634 *portp = -1;
635
636 if ((sdup = tmp = strdup(s)) == NULL)
637 return -1;
638 /* Extract optional username */
millert@openbsd.org887669e2017-10-21 23:06:24 +0000639 if ((cp = strrchr(tmp, '@')) != NULL) {
djm@openbsd.orged877ef2016-07-15 00:24:30 +0000640 *cp = '\0';
641 if (*tmp == '\0')
642 goto out;
643 if ((user = strdup(tmp)) == NULL)
644 goto out;
645 tmp = cp + 1;
646 }
647 /* Extract mandatory hostname */
648 if ((cp = hpdelim(&tmp)) == NULL || *cp == '\0')
649 goto out;
650 host = xstrdup(cleanhostname(cp));
651 /* Convert and verify optional port */
652 if (tmp != NULL && *tmp != '\0') {
653 if ((port = a2port(tmp)) <= 0)
654 goto out;
655 }
656 /* Success */
657 if (userp != NULL) {
658 *userp = user;
659 user = NULL;
660 }
661 if (hostp != NULL) {
662 *hostp = host;
663 host = NULL;
664 }
665 if (portp != NULL)
666 *portp = port;
667 ret = 0;
668 out:
669 free(sdup);
670 free(user);
671 free(host);
672 return ret;
673}
674
millert@openbsd.org887669e2017-10-21 23:06:24 +0000675/*
676 * Converts a two-byte hex string to decimal.
677 * Returns the decimal value or -1 for invalid input.
678 */
679static int
680hexchar(const char *s)
681{
682 unsigned char result[2];
683 int i;
684
685 for (i = 0; i < 2; i++) {
686 if (s[i] >= '0' && s[i] <= '9')
687 result[i] = (unsigned char)(s[i] - '0');
688 else if (s[i] >= 'a' && s[i] <= 'f')
689 result[i] = (unsigned char)(s[i] - 'a') + 10;
690 else if (s[i] >= 'A' && s[i] <= 'F')
691 result[i] = (unsigned char)(s[i] - 'A') + 10;
692 else
693 return -1;
694 }
695 return (result[0] << 4) | result[1];
696}
697
698/*
699 * Decode an url-encoded string.
700 * Returns a newly allocated string on success or NULL on failure.
701 */
702static char *
703urldecode(const char *src)
704{
705 char *ret, *dst;
706 int ch;
707
708 ret = xmalloc(strlen(src) + 1);
709 for (dst = ret; *src != '\0'; src++) {
710 switch (*src) {
711 case '+':
712 *dst++ = ' ';
713 break;
714 case '%':
715 if (!isxdigit((unsigned char)src[1]) ||
716 !isxdigit((unsigned char)src[2]) ||
717 (ch = hexchar(src + 1)) == -1) {
718 free(ret);
719 return NULL;
720 }
721 *dst++ = ch;
722 src += 2;
723 break;
724 default:
725 *dst++ = *src;
726 break;
727 }
728 }
729 *dst = '\0';
730
731 return ret;
732}
733
734/*
735 * Parse an (scp|ssh|sftp)://[user@]host[:port][/path] URI.
736 * See https://tools.ietf.org/html/draft-ietf-secsh-scp-sftp-ssh-uri-04
737 * Either user or path may be url-encoded (but not host or port).
738 * Caller must free returned user, host and path.
739 * Any of the pointer return arguments may be NULL (useful for syntax checking)
740 * but the scheme must always be specified.
741 * If user was not specified then *userp will be set to NULL.
742 * If port was not specified then *portp will be -1.
743 * If path was not specified then *pathp will be set to NULL.
744 * Returns 0 on success, 1 if non-uri/wrong scheme, -1 on error/invalid uri.
745 */
746int
747parse_uri(const char *scheme, const char *uri, char **userp, char **hostp,
748 int *portp, char **pathp)
749{
750 char *uridup, *cp, *tmp, ch;
751 char *user = NULL, *host = NULL, *path = NULL;
752 int port = -1, ret = -1;
753 size_t len;
754
755 len = strlen(scheme);
756 if (strncmp(uri, scheme, len) != 0 || strncmp(uri + len, "://", 3) != 0)
757 return 1;
758 uri += len + 3;
759
760 if (userp != NULL)
761 *userp = NULL;
762 if (hostp != NULL)
763 *hostp = NULL;
764 if (portp != NULL)
765 *portp = -1;
766 if (pathp != NULL)
767 *pathp = NULL;
768
769 uridup = tmp = xstrdup(uri);
770
771 /* Extract optional ssh-info (username + connection params) */
772 if ((cp = strchr(tmp, '@')) != NULL) {
773 char *delim;
774
775 *cp = '\0';
776 /* Extract username and connection params */
777 if ((delim = strchr(tmp, ';')) != NULL) {
778 /* Just ignore connection params for now */
779 *delim = '\0';
780 }
781 if (*tmp == '\0') {
782 /* Empty username */
783 goto out;
784 }
785 if ((user = urldecode(tmp)) == NULL)
786 goto out;
787 tmp = cp + 1;
788 }
789
790 /* Extract mandatory hostname */
791 if ((cp = hpdelim2(&tmp, &ch)) == NULL || *cp == '\0')
792 goto out;
793 host = xstrdup(cleanhostname(cp));
794 if (!valid_domain(host, 0, NULL))
795 goto out;
796
797 if (tmp != NULL && *tmp != '\0') {
798 if (ch == ':') {
799 /* Convert and verify port. */
800 if ((cp = strchr(tmp, '/')) != NULL)
801 *cp = '\0';
802 if ((port = a2port(tmp)) <= 0)
803 goto out;
804 tmp = cp ? cp + 1 : NULL;
805 }
806 if (tmp != NULL && *tmp != '\0') {
807 /* Extract optional path */
808 if ((path = urldecode(tmp)) == NULL)
809 goto out;
810 }
811 }
812
813 /* Success */
814 if (userp != NULL) {
815 *userp = user;
816 user = NULL;
817 }
818 if (hostp != NULL) {
819 *hostp = host;
820 host = NULL;
821 }
822 if (portp != NULL)
823 *portp = port;
824 if (pathp != NULL) {
825 *pathp = path;
826 path = NULL;
827 }
828 ret = 0;
829 out:
830 free(uridup);
831 free(user);
832 free(host);
833 free(path);
834 return ret;
835}
836
Ben Lindstrom4cc240d2001-07-04 04:46:56 +0000837/* function to assist building execv() arguments */
Ben Lindstrom387c4722001-05-08 20:27:25 +0000838void
839addargs(arglist *args, char *fmt, ...)
840{
841 va_list ap;
Damien Miller3eec6b72006-01-31 21:49:27 +1100842 char *cp;
Darren Tuckerc7a6fc42004-08-13 21:18:00 +1000843 u_int nalloc;
Damien Miller3eec6b72006-01-31 21:49:27 +1100844 int r;
Ben Lindstrom387c4722001-05-08 20:27:25 +0000845
846 va_start(ap, fmt);
Damien Miller3eec6b72006-01-31 21:49:27 +1100847 r = vasprintf(&cp, fmt, ap);
Ben Lindstrom387c4722001-05-08 20:27:25 +0000848 va_end(ap);
Damien Miller3eec6b72006-01-31 21:49:27 +1100849 if (r == -1)
850 fatal("addargs: argument too long");
Ben Lindstrom387c4722001-05-08 20:27:25 +0000851
Darren Tuckerfb16b242003-09-22 21:04:23 +1000852 nalloc = args->nalloc;
Ben Lindstrom387c4722001-05-08 20:27:25 +0000853 if (args->list == NULL) {
Darren Tuckerfb16b242003-09-22 21:04:23 +1000854 nalloc = 32;
Ben Lindstrom387c4722001-05-08 20:27:25 +0000855 args->num = 0;
Darren Tuckerfb16b242003-09-22 21:04:23 +1000856 } else if (args->num+2 >= nalloc)
857 nalloc *= 2;
Ben Lindstrom387c4722001-05-08 20:27:25 +0000858
deraadt@openbsd.org9e509d42017-05-31 09:15:42 +0000859 args->list = xrecallocarray(args->list, args->nalloc, nalloc, sizeof(char *));
Darren Tuckerfb16b242003-09-22 21:04:23 +1000860 args->nalloc = nalloc;
Damien Miller3eec6b72006-01-31 21:49:27 +1100861 args->list[args->num++] = cp;
Ben Lindstrom387c4722001-05-08 20:27:25 +0000862 args->list[args->num] = NULL;
863}
Darren Tucker22cc7412004-12-06 22:47:41 +1100864
Damien Miller3eec6b72006-01-31 21:49:27 +1100865void
866replacearg(arglist *args, u_int which, char *fmt, ...)
867{
868 va_list ap;
869 char *cp;
870 int r;
871
872 va_start(ap, fmt);
873 r = vasprintf(&cp, fmt, ap);
874 va_end(ap);
875 if (r == -1)
876 fatal("replacearg: argument too long");
877
878 if (which >= args->num)
879 fatal("replacearg: tried to replace invalid arg %d >= %d",
880 which, args->num);
Darren Tuckera627d422013-06-02 07:31:17 +1000881 free(args->list[which]);
Damien Miller3eec6b72006-01-31 21:49:27 +1100882 args->list[which] = cp;
883}
884
885void
886freeargs(arglist *args)
887{
888 u_int i;
889
890 if (args->list != NULL) {
891 for (i = 0; i < args->num; i++)
Darren Tuckera627d422013-06-02 07:31:17 +1000892 free(args->list[i]);
893 free(args->list);
Damien Miller3eec6b72006-01-31 21:49:27 +1100894 args->nalloc = args->num = 0;
895 args->list = NULL;
896 }
897}
898
Darren Tucker22cc7412004-12-06 22:47:41 +1100899/*
Damien Miller5fd38c02005-05-26 12:02:14 +1000900 * Expands tildes in the file name. Returns data allocated by xmalloc.
901 * Warning: this calls getpw*.
902 */
903char *
904tilde_expand_filename(const char *filename, uid_t uid)
905{
Darren Tucker2ca51bf2013-05-16 20:22:46 +1000906 const char *path, *sep;
907 char user[128], *ret;
Damien Miller5fd38c02005-05-26 12:02:14 +1000908 struct passwd *pw;
Damien Millereccb9de2005-06-17 12:59:34 +1000909 u_int len, slash;
Damien Miller5fd38c02005-05-26 12:02:14 +1000910
911 if (*filename != '~')
912 return (xstrdup(filename));
913 filename++;
914
915 path = strchr(filename, '/');
916 if (path != NULL && path > filename) { /* ~user/path */
Damien Millereccb9de2005-06-17 12:59:34 +1000917 slash = path - filename;
918 if (slash > sizeof(user) - 1)
Damien Miller5fd38c02005-05-26 12:02:14 +1000919 fatal("tilde_expand_filename: ~username too long");
Damien Millereccb9de2005-06-17 12:59:34 +1000920 memcpy(user, filename, slash);
921 user[slash] = '\0';
Damien Miller5fd38c02005-05-26 12:02:14 +1000922 if ((pw = getpwnam(user)) == NULL)
923 fatal("tilde_expand_filename: No such user %s", user);
924 } else if ((pw = getpwuid(uid)) == NULL) /* ~/path */
Darren Tucker7517b5b2008-06-13 14:48:59 +1000925 fatal("tilde_expand_filename: No such uid %ld", (long)uid);
Damien Miller5fd38c02005-05-26 12:02:14 +1000926
Damien Miller5fd38c02005-05-26 12:02:14 +1000927 /* Make sure directory has a trailing '/' */
928 len = strlen(pw->pw_dir);
Darren Tucker026d9db2013-05-16 20:23:52 +1000929 if (len == 0 || pw->pw_dir[len - 1] != '/')
Darren Tucker2ca51bf2013-05-16 20:22:46 +1000930 sep = "/";
931 else
932 sep = "";
Damien Miller5fd38c02005-05-26 12:02:14 +1000933
934 /* Skip leading '/' from specified path */
935 if (path != NULL)
936 filename = path + 1;
Darren Tucker2ca51bf2013-05-16 20:22:46 +1000937
deraadt@openbsd.org2ae4f332015-01-16 06:40:12 +0000938 if (xasprintf(&ret, "%s%s%s", pw->pw_dir, sep, filename) >= PATH_MAX)
Damien Miller5fd38c02005-05-26 12:02:14 +1000939 fatal("tilde_expand_filename: Path too long");
940
Darren Tucker2ca51bf2013-05-16 20:22:46 +1000941 return (ret);
Damien Miller5fd38c02005-05-26 12:02:14 +1000942}
943
944/*
Damien Miller6476cad2005-06-16 13:18:34 +1000945 * Expand a string with a set of %[char] escapes. A number of escapes may be
946 * specified as (char *escape_chars, char *replacement) pairs. The list must
Darren Tuckerbee73d52005-07-14 17:05:02 +1000947 * be terminated by a NULL escape_char. Returns replaced string in memory
Damien Miller6476cad2005-06-16 13:18:34 +1000948 * allocated by xmalloc.
949 */
950char *
951percent_expand(const char *string, ...)
952{
953#define EXPAND_MAX_KEYS 16
Darren Tucker70d87692010-01-08 18:49:16 +1100954 u_int num_keys, i, j;
Damien Miller6476cad2005-06-16 13:18:34 +1000955 struct {
956 const char *key;
957 const char *repl;
958 } keys[EXPAND_MAX_KEYS];
Damien Miller6476cad2005-06-16 13:18:34 +1000959 char buf[4096];
960 va_list ap;
961
962 /* Gather keys */
963 va_start(ap, string);
964 for (num_keys = 0; num_keys < EXPAND_MAX_KEYS; num_keys++) {
965 keys[num_keys].key = va_arg(ap, char *);
966 if (keys[num_keys].key == NULL)
967 break;
968 keys[num_keys].repl = va_arg(ap, char *);
969 if (keys[num_keys].repl == NULL)
Darren Tucker70d87692010-01-08 18:49:16 +1100970 fatal("%s: NULL replacement", __func__);
Damien Miller6476cad2005-06-16 13:18:34 +1000971 }
Darren Tucker70d87692010-01-08 18:49:16 +1100972 if (num_keys == EXPAND_MAX_KEYS && va_arg(ap, char *) != NULL)
973 fatal("%s: too many keys", __func__);
Damien Miller6476cad2005-06-16 13:18:34 +1000974 va_end(ap);
975
Damien Miller6476cad2005-06-16 13:18:34 +1000976 /* Expand string */
977 *buf = '\0';
978 for (i = 0; *string != '\0'; string++) {
979 if (*string != '%') {
980 append:
981 buf[i++] = *string;
982 if (i >= sizeof(buf))
Darren Tucker70d87692010-01-08 18:49:16 +1100983 fatal("%s: string too long", __func__);
Damien Miller6476cad2005-06-16 13:18:34 +1000984 buf[i] = '\0';
985 continue;
986 }
987 string++;
Darren Tucker70d87692010-01-08 18:49:16 +1100988 /* %% case */
Damien Miller6476cad2005-06-16 13:18:34 +1000989 if (*string == '%')
990 goto append;
tobias@openbsd.org8b56e592015-12-04 21:51:06 +0000991 if (*string == '\0')
992 fatal("%s: invalid format", __func__);
Damien Miller6476cad2005-06-16 13:18:34 +1000993 for (j = 0; j < num_keys; j++) {
994 if (strchr(keys[j].key, *string) != NULL) {
995 i = strlcat(buf, keys[j].repl, sizeof(buf));
996 if (i >= sizeof(buf))
Darren Tucker70d87692010-01-08 18:49:16 +1100997 fatal("%s: string too long", __func__);
Damien Miller6476cad2005-06-16 13:18:34 +1000998 break;
999 }
1000 }
1001 if (j >= num_keys)
Darren Tucker70d87692010-01-08 18:49:16 +11001002 fatal("%s: unknown key %%%c", __func__, *string);
Damien Miller6476cad2005-06-16 13:18:34 +10001003 }
1004 return (xstrdup(buf));
1005#undef EXPAND_MAX_KEYS
1006}
1007
1008/*
Darren Tucker22cc7412004-12-06 22:47:41 +11001009 * Read an entire line from a public key file into a static buffer, discarding
1010 * lines that exceed the buffer size. Returns 0 on success, -1 on failure.
1011 */
1012int
1013read_keyfile_line(FILE *f, const char *filename, char *buf, size_t bufsz,
Darren Tuckerf0f90982004-12-11 13:39:50 +11001014 u_long *lineno)
Darren Tucker22cc7412004-12-06 22:47:41 +11001015{
1016 while (fgets(buf, bufsz, f) != NULL) {
Damien Miller3ca8b772007-01-05 16:24:47 +11001017 if (buf[0] == '\0')
1018 continue;
Darren Tucker22cc7412004-12-06 22:47:41 +11001019 (*lineno)++;
1020 if (buf[strlen(buf) - 1] == '\n' || feof(f)) {
1021 return 0;
1022 } else {
Darren Tuckerf0f90982004-12-11 13:39:50 +11001023 debug("%s: %s line %lu exceeds size limit", __func__,
1024 filename, *lineno);
Darren Tucker22cc7412004-12-06 22:47:41 +11001025 /* discard remainder of line */
Darren Tucker47eede72005-03-14 23:08:12 +11001026 while (fgetc(f) != '\n' && !feof(f))
Darren Tucker22cc7412004-12-06 22:47:41 +11001027 ; /* nothing */
1028 }
1029 }
1030 return -1;
1031}
Damien Miller13390022005-07-06 09:44:19 +10001032
Damien Millerd27b9472005-12-13 19:29:02 +11001033int
djm@openbsd.orgb7548b12017-10-23 05:08:00 +00001034tun_open(int tun, int mode, char **ifname)
Damien Millerd27b9472005-12-13 19:29:02 +11001035{
Damien Miller62a31c92005-12-13 20:44:13 +11001036#if defined(CUSTOM_SYS_TUN_OPEN)
djm@openbsd.orgb7548b12017-10-23 05:08:00 +00001037 return (sys_tun_open(tun, mode, ifname));
Damien Miller2dcddbf2006-01-01 19:47:05 +11001038#elif defined(SSH_TUN_OPENBSD)
Damien Miller7b58e802005-12-13 19:33:19 +11001039 struct ifreq ifr;
Damien Millerd27b9472005-12-13 19:29:02 +11001040 char name[100];
Damien Miller7b58e802005-12-13 19:33:19 +11001041 int fd = -1, sock;
sthen@openbsd.orga820a862015-10-24 08:34:09 +00001042 const char *tunbase = "tun";
1043
djm@openbsd.orgb7548b12017-10-23 05:08:00 +00001044 if (ifname != NULL)
1045 *ifname = NULL;
1046
sthen@openbsd.orga820a862015-10-24 08:34:09 +00001047 if (mode == SSH_TUNMODE_ETHERNET)
1048 tunbase = "tap";
Damien Millerd27b9472005-12-13 19:29:02 +11001049
Damien Miller7b58e802005-12-13 19:33:19 +11001050 /* Open the tunnel device */
1051 if (tun <= SSH_TUNID_MAX) {
sthen@openbsd.orga820a862015-10-24 08:34:09 +00001052 snprintf(name, sizeof(name), "/dev/%s%d", tunbase, tun);
Damien Miller7b58e802005-12-13 19:33:19 +11001053 fd = open(name, O_RDWR);
1054 } else if (tun == SSH_TUNID_ANY) {
1055 for (tun = 100; tun >= 0; tun--) {
sthen@openbsd.orga820a862015-10-24 08:34:09 +00001056 snprintf(name, sizeof(name), "/dev/%s%d",
1057 tunbase, tun);
Damien Miller7b58e802005-12-13 19:33:19 +11001058 if ((fd = open(name, O_RDWR)) >= 0)
1059 break;
Damien Millerd27b9472005-12-13 19:29:02 +11001060 }
1061 } else {
Damien Millera210d522006-01-02 23:40:30 +11001062 debug("%s: invalid tunnel %u", __func__, tun);
djm@openbsd.org2905d6f2015-10-07 00:54:06 +00001063 return -1;
Damien Millerd27b9472005-12-13 19:29:02 +11001064 }
Damien Miller7b58e802005-12-13 19:33:19 +11001065
1066 if (fd < 0) {
djm@openbsd.org2905d6f2015-10-07 00:54:06 +00001067 debug("%s: %s open: %s", __func__, name, strerror(errno));
1068 return -1;
Damien Miller7b58e802005-12-13 19:33:19 +11001069 }
1070
1071 debug("%s: %s mode %d fd %d", __func__, name, mode, fd);
1072
sthen@openbsd.orga820a862015-10-24 08:34:09 +00001073 /* Bring interface up if it is not already */
1074 snprintf(ifr.ifr_name, sizeof(ifr.ifr_name), "%s%d", tunbase, tun);
1075 if ((sock = socket(PF_UNIX, SOCK_STREAM, 0)) == -1)
Damien Miller7b58e802005-12-13 19:33:19 +11001076 goto failed;
1077
djm@openbsd.org2905d6f2015-10-07 00:54:06 +00001078 if (ioctl(sock, SIOCGIFFLAGS, &ifr) == -1) {
1079 debug("%s: get interface %s flags: %s", __func__,
1080 ifr.ifr_name, strerror(errno));
Damien Miller7b58e802005-12-13 19:33:19 +11001081 goto failed;
djm@openbsd.org2905d6f2015-10-07 00:54:06 +00001082 }
Damien Millera1d9a182006-01-02 23:41:21 +11001083
djm@openbsd.org2905d6f2015-10-07 00:54:06 +00001084 if (!(ifr.ifr_flags & IFF_UP)) {
1085 ifr.ifr_flags |= IFF_UP;
1086 if (ioctl(sock, SIOCSIFFLAGS, &ifr) == -1) {
1087 debug("%s: activate interface %s: %s", __func__,
1088 ifr.ifr_name, strerror(errno));
1089 goto failed;
1090 }
1091 }
Damien Miller7b58e802005-12-13 19:33:19 +11001092
djm@openbsd.orgb7548b12017-10-23 05:08:00 +00001093 if (ifname != NULL)
1094 *ifname = xstrdup(ifr.ifr_name);
1095
Damien Miller7b58e802005-12-13 19:33:19 +11001096 close(sock);
djm@openbsd.org2905d6f2015-10-07 00:54:06 +00001097 return fd;
Damien Miller7b58e802005-12-13 19:33:19 +11001098
1099 failed:
1100 if (fd >= 0)
1101 close(fd);
1102 if (sock >= 0)
1103 close(sock);
djm@openbsd.org2905d6f2015-10-07 00:54:06 +00001104 return -1;
Damien Miller62a31c92005-12-13 20:44:13 +11001105#else
1106 error("Tunnel interfaces are not supported on this platform");
1107 return (-1);
1108#endif
Damien Millerd27b9472005-12-13 19:29:02 +11001109}
1110
Darren Tuckerce321d82005-10-03 18:11:24 +10001111void
1112sanitise_stdfd(void)
1113{
Damien Miller72c5b7d2006-01-06 14:50:44 +11001114 int nullfd, dupfd;
Darren Tuckerce321d82005-10-03 18:11:24 +10001115
Damien Miller72c5b7d2006-01-06 14:50:44 +11001116 if ((nullfd = dupfd = open(_PATH_DEVNULL, O_RDWR)) == -1) {
Damien Miller9eab9562009-02-22 08:47:02 +11001117 fprintf(stderr, "Couldn't open /dev/null: %s\n",
1118 strerror(errno));
Darren Tuckerce321d82005-10-03 18:11:24 +10001119 exit(1);
1120 }
krw@openbsd.org574def02016-04-02 14:37:42 +00001121 while (++dupfd <= STDERR_FILENO) {
1122 /* Only populate closed fds. */
1123 if (fcntl(dupfd, F_GETFL) == -1 && errno == EBADF) {
1124 if (dup2(nullfd, dupfd) == -1) {
1125 fprintf(stderr, "dup2: %s\n", strerror(errno));
1126 exit(1);
1127 }
Darren Tuckerce321d82005-10-03 18:11:24 +10001128 }
Darren Tuckerce321d82005-10-03 18:11:24 +10001129 }
krw@openbsd.org574def02016-04-02 14:37:42 +00001130 if (nullfd > STDERR_FILENO)
Darren Tuckerce321d82005-10-03 18:11:24 +10001131 close(nullfd);
1132}
1133
Damien Miller13390022005-07-06 09:44:19 +10001134char *
Damien Miller3f941882006-03-31 23:13:02 +11001135tohex(const void *vp, size_t l)
Damien Miller13390022005-07-06 09:44:19 +10001136{
Damien Miller3f941882006-03-31 23:13:02 +11001137 const u_char *p = (const u_char *)vp;
Damien Miller13390022005-07-06 09:44:19 +10001138 char b[3], *r;
Damien Miller3f941882006-03-31 23:13:02 +11001139 size_t i, hl;
1140
1141 if (l > 65536)
1142 return xstrdup("tohex: length > 65536");
Damien Miller13390022005-07-06 09:44:19 +10001143
1144 hl = l * 2 + 1;
Damien Miller07d86be2006-03-26 14:19:21 +11001145 r = xcalloc(1, hl);
Damien Miller13390022005-07-06 09:44:19 +10001146 for (i = 0; i < l; i++) {
Damien Miller3f941882006-03-31 23:13:02 +11001147 snprintf(b, sizeof(b), "%02x", p[i]);
Damien Miller13390022005-07-06 09:44:19 +10001148 strlcat(r, b, hl);
1149 }
1150 return (r);
1151}
1152
Damien Miller3f941882006-03-31 23:13:02 +11001153u_int64_t
1154get_u64(const void *vp)
1155{
1156 const u_char *p = (const u_char *)vp;
1157 u_int64_t v;
1158
1159 v = (u_int64_t)p[0] << 56;
1160 v |= (u_int64_t)p[1] << 48;
1161 v |= (u_int64_t)p[2] << 40;
1162 v |= (u_int64_t)p[3] << 32;
1163 v |= (u_int64_t)p[4] << 24;
1164 v |= (u_int64_t)p[5] << 16;
1165 v |= (u_int64_t)p[6] << 8;
1166 v |= (u_int64_t)p[7];
1167
1168 return (v);
1169}
1170
1171u_int32_t
1172get_u32(const void *vp)
1173{
1174 const u_char *p = (const u_char *)vp;
1175 u_int32_t v;
1176
1177 v = (u_int32_t)p[0] << 24;
1178 v |= (u_int32_t)p[1] << 16;
1179 v |= (u_int32_t)p[2] << 8;
1180 v |= (u_int32_t)p[3];
1181
1182 return (v);
1183}
1184
Damien Miller88856692014-04-20 13:33:19 +10001185u_int32_t
1186get_u32_le(const void *vp)
1187{
1188 const u_char *p = (const u_char *)vp;
1189 u_int32_t v;
1190
1191 v = (u_int32_t)p[0];
1192 v |= (u_int32_t)p[1] << 8;
1193 v |= (u_int32_t)p[2] << 16;
1194 v |= (u_int32_t)p[3] << 24;
1195
1196 return (v);
1197}
1198
Damien Miller3f941882006-03-31 23:13:02 +11001199u_int16_t
1200get_u16(const void *vp)
1201{
1202 const u_char *p = (const u_char *)vp;
1203 u_int16_t v;
1204
1205 v = (u_int16_t)p[0] << 8;
1206 v |= (u_int16_t)p[1];
1207
1208 return (v);
1209}
1210
1211void
1212put_u64(void *vp, u_int64_t v)
1213{
1214 u_char *p = (u_char *)vp;
1215
1216 p[0] = (u_char)(v >> 56) & 0xff;
1217 p[1] = (u_char)(v >> 48) & 0xff;
1218 p[2] = (u_char)(v >> 40) & 0xff;
1219 p[3] = (u_char)(v >> 32) & 0xff;
1220 p[4] = (u_char)(v >> 24) & 0xff;
1221 p[5] = (u_char)(v >> 16) & 0xff;
1222 p[6] = (u_char)(v >> 8) & 0xff;
1223 p[7] = (u_char)v & 0xff;
1224}
1225
1226void
1227put_u32(void *vp, u_int32_t v)
1228{
1229 u_char *p = (u_char *)vp;
1230
1231 p[0] = (u_char)(v >> 24) & 0xff;
1232 p[1] = (u_char)(v >> 16) & 0xff;
1233 p[2] = (u_char)(v >> 8) & 0xff;
1234 p[3] = (u_char)v & 0xff;
1235}
1236
Damien Miller88856692014-04-20 13:33:19 +10001237void
1238put_u32_le(void *vp, u_int32_t v)
1239{
1240 u_char *p = (u_char *)vp;
1241
1242 p[0] = (u_char)v & 0xff;
1243 p[1] = (u_char)(v >> 8) & 0xff;
1244 p[2] = (u_char)(v >> 16) & 0xff;
1245 p[3] = (u_char)(v >> 24) & 0xff;
1246}
Damien Miller3f941882006-03-31 23:13:02 +11001247
1248void
1249put_u16(void *vp, u_int16_t v)
1250{
1251 u_char *p = (u_char *)vp;
1252
1253 p[0] = (u_char)(v >> 8) & 0xff;
1254 p[1] = (u_char)v & 0xff;
1255}
Darren Tucker3fc464e2008-06-13 06:42:45 +10001256
1257void
1258ms_subtract_diff(struct timeval *start, int *ms)
1259{
1260 struct timeval diff, finish;
1261
dtucker@openbsd.org@openbsd.org5db6fbf2017-11-25 06:46:22 +00001262 monotime_tv(&finish);
1263 timersub(&finish, start, &diff);
Darren Tucker3fc464e2008-06-13 06:42:45 +10001264 *ms -= (diff.tv_sec * 1000) + (diff.tv_usec / 1000);
1265}
1266
1267void
1268ms_to_timeval(struct timeval *tv, int ms)
1269{
1270 if (ms < 0)
1271 ms = 0;
1272 tv->tv_sec = ms / 1000;
1273 tv->tv_usec = (ms % 1000) * 1000;
1274}
1275
dtucker@openbsd.org@openbsd.org5db6fbf2017-11-25 06:46:22 +00001276void
1277monotime_ts(struct timespec *ts)
Darren Tuckerb759c9c2013-06-02 07:46:16 +10001278{
dtucker@openbsd.org@openbsd.org5db6fbf2017-11-25 06:46:22 +00001279 struct timeval tv;
1280#if defined(HAVE_CLOCK_GETTIME) && (defined(CLOCK_BOOTTIME) || \
1281 defined(CLOCK_MONOTONIC) || defined(CLOCK_REALTIME))
Darren Tucker94396b72013-08-08 11:52:37 +10001282 static int gettime_failed = 0;
Darren Tuckerb759c9c2013-06-02 07:46:16 +10001283
Darren Tucker94396b72013-08-08 11:52:37 +10001284 if (!gettime_failed) {
dtucker@openbsd.org@openbsd.org5db6fbf2017-11-25 06:46:22 +00001285# ifdef CLOCK_BOOTTIME
1286 if (clock_gettime(CLOCK_BOOTTIME, ts) == 0)
1287 return;
1288# endif /* CLOCK_BOOTTIME */
1289# ifdef CLOCK_MONOTONIC
1290 if (clock_gettime(CLOCK_MONOTONIC, ts) == 0)
1291 return;
1292# endif /* CLOCK_MONOTONIC */
1293# ifdef CLOCK_REALTIME
1294 /* Not monotonic, but we're almost out of options here. */
1295 if (clock_gettime(CLOCK_REALTIME, ts) == 0)
1296 return;
1297# endif /* CLOCK_REALTIME */
Darren Tucker94396b72013-08-08 11:52:37 +10001298 debug3("clock_gettime: %s", strerror(errno));
1299 gettime_failed = 1;
1300 }
dtucker@openbsd.org@openbsd.org5db6fbf2017-11-25 06:46:22 +00001301#endif /* HAVE_CLOCK_GETTIME && (BOOTTIME || MONOTONIC || REALTIME) */
1302 gettimeofday(&tv, NULL);
1303 ts->tv_sec = tv.tv_sec;
1304 ts->tv_nsec = (long)tv.tv_usec * 1000;
1305}
Darren Tucker94396b72013-08-08 11:52:37 +10001306
dtucker@openbsd.org@openbsd.org5db6fbf2017-11-25 06:46:22 +00001307void
1308monotime_tv(struct timeval *tv)
1309{
1310 struct timespec ts;
1311
1312 monotime_ts(&ts);
1313 tv->tv_sec = ts.tv_sec;
1314 tv->tv_usec = ts.tv_nsec / 1000;
1315}
1316
1317time_t
1318monotime(void)
1319{
1320 struct timespec ts;
1321
1322 monotime_ts(&ts);
1323 return ts.tv_sec;
Darren Tuckerb759c9c2013-06-02 07:46:16 +10001324}
1325
dtucker@openbsd.orgb8d4eaf2016-03-02 22:42:40 +00001326double
1327monotime_double(void)
1328{
1329 struct timespec ts;
1330
dtucker@openbsd.org@openbsd.org5db6fbf2017-11-25 06:46:22 +00001331 monotime_ts(&ts);
1332 return ts.tv_sec + ((double)ts.tv_nsec / 1000000000);
dtucker@openbsd.orgb8d4eaf2016-03-02 22:42:40 +00001333}
1334
Damien Miller65e42f82010-09-24 22:15:11 +10001335void
1336bandwidth_limit_init(struct bwlimit *bw, u_int64_t kbps, size_t buflen)
1337{
1338 bw->buflen = buflen;
1339 bw->rate = kbps;
1340 bw->thresh = bw->rate;
1341 bw->lamt = 0;
1342 timerclear(&bw->bwstart);
1343 timerclear(&bw->bwend);
1344}
1345
1346/* Callback from read/write loop to insert bandwidth-limiting delays */
1347void
1348bandwidth_limit(struct bwlimit *bw, size_t read_len)
1349{
1350 u_int64_t waitlen;
1351 struct timespec ts, rm;
1352
1353 if (!timerisset(&bw->bwstart)) {
dtucker@openbsd.org@openbsd.org5db6fbf2017-11-25 06:46:22 +00001354 monotime_tv(&bw->bwstart);
Damien Miller65e42f82010-09-24 22:15:11 +10001355 return;
1356 }
1357
1358 bw->lamt += read_len;
1359 if (bw->lamt < bw->thresh)
1360 return;
1361
dtucker@openbsd.org@openbsd.org5db6fbf2017-11-25 06:46:22 +00001362 monotime_tv(&bw->bwend);
Damien Miller65e42f82010-09-24 22:15:11 +10001363 timersub(&bw->bwend, &bw->bwstart, &bw->bwend);
1364 if (!timerisset(&bw->bwend))
1365 return;
1366
1367 bw->lamt *= 8;
1368 waitlen = (double)1000000L * bw->lamt / bw->rate;
1369
1370 bw->bwstart.tv_sec = waitlen / 1000000L;
1371 bw->bwstart.tv_usec = waitlen % 1000000L;
1372
1373 if (timercmp(&bw->bwstart, &bw->bwend, >)) {
1374 timersub(&bw->bwstart, &bw->bwend, &bw->bwend);
1375
1376 /* Adjust the wait time */
1377 if (bw->bwend.tv_sec) {
1378 bw->thresh /= 2;
1379 if (bw->thresh < bw->buflen / 4)
1380 bw->thresh = bw->buflen / 4;
1381 } else if (bw->bwend.tv_usec < 10000) {
1382 bw->thresh *= 2;
1383 if (bw->thresh > bw->buflen * 8)
1384 bw->thresh = bw->buflen * 8;
1385 }
1386
1387 TIMEVAL_TO_TIMESPEC(&bw->bwend, &ts);
1388 while (nanosleep(&ts, &rm) == -1) {
1389 if (errno != EINTR)
1390 break;
1391 ts = rm;
1392 }
1393 }
1394
1395 bw->lamt = 0;
dtucker@openbsd.org@openbsd.org5db6fbf2017-11-25 06:46:22 +00001396 monotime_tv(&bw->bwstart);
Damien Miller65e42f82010-09-24 22:15:11 +10001397}
Damien Miller0dac6fb2010-11-20 15:19:38 +11001398
Damien Miller2cd62932010-12-01 11:50:35 +11001399/* Make a template filename for mk[sd]temp() */
1400void
1401mktemp_proto(char *s, size_t len)
1402{
1403 const char *tmpdir;
1404 int r;
1405
1406 if ((tmpdir = getenv("TMPDIR")) != NULL) {
1407 r = snprintf(s, len, "%s/ssh-XXXXXXXXXXXX", tmpdir);
1408 if (r > 0 && (size_t)r < len)
1409 return;
1410 }
1411 r = snprintf(s, len, "/tmp/ssh-XXXXXXXXXXXX");
1412 if (r < 0 || (size_t)r >= len)
1413 fatal("%s: template string too short", __func__);
1414}
1415
Damien Miller0dac6fb2010-11-20 15:19:38 +11001416static const struct {
1417 const char *name;
1418 int value;
1419} ipqos[] = {
djm@openbsd.org51676ec2017-07-23 23:37:02 +00001420 { "none", INT_MAX }, /* can't use 0 here; that's CS0 */
Damien Miller0dac6fb2010-11-20 15:19:38 +11001421 { "af11", IPTOS_DSCP_AF11 },
1422 { "af12", IPTOS_DSCP_AF12 },
1423 { "af13", IPTOS_DSCP_AF13 },
Damien Miller2918e032011-09-22 21:34:35 +10001424 { "af21", IPTOS_DSCP_AF21 },
Damien Miller0dac6fb2010-11-20 15:19:38 +11001425 { "af22", IPTOS_DSCP_AF22 },
1426 { "af23", IPTOS_DSCP_AF23 },
1427 { "af31", IPTOS_DSCP_AF31 },
1428 { "af32", IPTOS_DSCP_AF32 },
1429 { "af33", IPTOS_DSCP_AF33 },
1430 { "af41", IPTOS_DSCP_AF41 },
1431 { "af42", IPTOS_DSCP_AF42 },
1432 { "af43", IPTOS_DSCP_AF43 },
1433 { "cs0", IPTOS_DSCP_CS0 },
1434 { "cs1", IPTOS_DSCP_CS1 },
1435 { "cs2", IPTOS_DSCP_CS2 },
1436 { "cs3", IPTOS_DSCP_CS3 },
1437 { "cs4", IPTOS_DSCP_CS4 },
1438 { "cs5", IPTOS_DSCP_CS5 },
1439 { "cs6", IPTOS_DSCP_CS6 },
1440 { "cs7", IPTOS_DSCP_CS7 },
1441 { "ef", IPTOS_DSCP_EF },
1442 { "lowdelay", IPTOS_LOWDELAY },
1443 { "throughput", IPTOS_THROUGHPUT },
1444 { "reliability", IPTOS_RELIABILITY },
1445 { NULL, -1 }
1446};
1447
1448int
1449parse_ipqos(const char *cp)
1450{
1451 u_int i;
1452 char *ep;
1453 long val;
1454
1455 if (cp == NULL)
1456 return -1;
1457 for (i = 0; ipqos[i].name != NULL; i++) {
1458 if (strcasecmp(cp, ipqos[i].name) == 0)
1459 return ipqos[i].value;
1460 }
1461 /* Try parsing as an integer */
1462 val = strtol(cp, &ep, 0);
1463 if (*cp == '\0' || *ep != '\0' || val < 0 || val > 255)
1464 return -1;
1465 return val;
1466}
1467
Damien Miller91475862011-05-05 14:14:34 +10001468const char *
1469iptos2str(int iptos)
1470{
1471 int i;
1472 static char iptos_str[sizeof "0xff"];
1473
1474 for (i = 0; ipqos[i].name != NULL; i++) {
1475 if (ipqos[i].value == iptos)
1476 return ipqos[i].name;
1477 }
1478 snprintf(iptos_str, sizeof iptos_str, "0x%02x", iptos);
1479 return iptos_str;
1480}
Damien Millere9fc72e2013-10-15 12:14:12 +11001481
1482void
1483lowercase(char *s)
1484{
1485 for (; *s; s++)
1486 *s = tolower((u_char)*s);
1487}
Damien Miller7acefbb2014-07-18 14:11:24 +10001488
1489int
1490unix_listener(const char *path, int backlog, int unlink_first)
1491{
1492 struct sockaddr_un sunaddr;
1493 int saved_errno, sock;
1494
1495 memset(&sunaddr, 0, sizeof(sunaddr));
1496 sunaddr.sun_family = AF_UNIX;
djm@openbsd.org155072f2017-12-08 02:13:02 +00001497 if (strlcpy(sunaddr.sun_path, path,
1498 sizeof(sunaddr.sun_path)) >= sizeof(sunaddr.sun_path)) {
1499 error("%s: path \"%s\" too long for Unix domain socket",
1500 __func__, path);
Damien Miller7acefbb2014-07-18 14:11:24 +10001501 errno = ENAMETOOLONG;
1502 return -1;
1503 }
1504
1505 sock = socket(PF_UNIX, SOCK_STREAM, 0);
1506 if (sock < 0) {
1507 saved_errno = errno;
djm@openbsd.org155072f2017-12-08 02:13:02 +00001508 error("%s: socket: %.100s", __func__, strerror(errno));
Damien Miller7acefbb2014-07-18 14:11:24 +10001509 errno = saved_errno;
1510 return -1;
1511 }
1512 if (unlink_first == 1) {
1513 if (unlink(path) != 0 && errno != ENOENT)
1514 error("unlink(%s): %.100s", path, strerror(errno));
1515 }
1516 if (bind(sock, (struct sockaddr *)&sunaddr, sizeof(sunaddr)) < 0) {
1517 saved_errno = errno;
djm@openbsd.org155072f2017-12-08 02:13:02 +00001518 error("%s: cannot bind to path %s: %s",
1519 __func__, path, strerror(errno));
djm@openbsd.orgfd4eeee2017-12-08 02:14:33 +00001520 close(sock);
Damien Miller7acefbb2014-07-18 14:11:24 +10001521 errno = saved_errno;
1522 return -1;
1523 }
1524 if (listen(sock, backlog) < 0) {
1525 saved_errno = errno;
djm@openbsd.org155072f2017-12-08 02:13:02 +00001526 error("%s: cannot listen on path %s: %s",
1527 __func__, path, strerror(errno));
djm@openbsd.orgfd4eeee2017-12-08 02:14:33 +00001528 close(sock);
1529 unlink(path);
Damien Miller7acefbb2014-07-18 14:11:24 +10001530 errno = saved_errno;
1531 return -1;
1532 }
1533 return sock;
1534}
Damien Miller46878022014-08-30 03:29:19 +10001535
Damien Miller04ee0f82009-11-18 17:48:30 +11001536void
1537sock_set_v6only(int s)
1538{
Damien Millerd86a3ba2015-12-09 09:18:45 +11001539#if defined(IPV6_V6ONLY) && !defined(__OpenBSD__)
Damien Miller04ee0f82009-11-18 17:48:30 +11001540 int on = 1;
1541
1542 debug3("%s: set socket %d IPV6_V6ONLY", __func__, s);
1543 if (setsockopt(s, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof(on)) == -1)
1544 error("setsockopt IPV6_V6ONLY: %s", strerror(errno));
1545#endif
1546}
djm@openbsd.org0ccbd5e2016-04-06 06:42:17 +00001547
1548/*
1549 * Compares two strings that maybe be NULL. Returns non-zero if strings
1550 * are both NULL or are identical, returns zero otherwise.
1551 */
1552static int
1553strcmp_maybe_null(const char *a, const char *b)
1554{
1555 if ((a == NULL && b != NULL) || (a != NULL && b == NULL))
1556 return 0;
1557 if (a != NULL && strcmp(a, b) != 0)
1558 return 0;
1559 return 1;
1560}
1561
1562/*
1563 * Compare two forwards, returning non-zero if they are identical or
1564 * zero otherwise.
1565 */
1566int
1567forward_equals(const struct Forward *a, const struct Forward *b)
1568{
1569 if (strcmp_maybe_null(a->listen_host, b->listen_host) == 0)
1570 return 0;
1571 if (a->listen_port != b->listen_port)
1572 return 0;
1573 if (strcmp_maybe_null(a->listen_path, b->listen_path) == 0)
1574 return 0;
1575 if (strcmp_maybe_null(a->connect_host, b->connect_host) == 0)
1576 return 0;
1577 if (a->connect_port != b->connect_port)
1578 return 0;
1579 if (strcmp_maybe_null(a->connect_path, b->connect_path) == 0)
1580 return 0;
1581 /* allocated_port and handle are not checked */
1582 return 1;
1583}
1584
dtucker@openbsd.org1c4ef0b2016-10-23 22:04:05 +00001585/* returns 1 if bind to specified port by specified user is permitted */
1586int
1587bind_permitted(int port, uid_t uid)
1588{
1589 if (port < IPPORT_RESERVED && uid != 0)
1590 return 0;
1591 return 1;
1592}
dtucker@openbsd.org7fc47662016-11-30 00:28:31 +00001593
1594/* returns 1 if process is already daemonized, 0 otherwise */
1595int
1596daemonized(void)
1597{
1598 int fd;
1599
1600 if ((fd = open(_PATH_TTY, O_RDONLY | O_NOCTTY)) >= 0) {
1601 close(fd);
1602 return 0; /* have controlling terminal */
1603 }
1604 if (getppid() != 1)
1605 return 0; /* parent is not init */
1606 if (getsid(0) != getpid())
1607 return 0; /* not session leader */
1608 debug3("already daemonized");
1609 return 1;
1610}
djm@openbsd.orgde4ae072017-08-18 05:36:45 +00001611
1612
1613/*
1614 * Splits 's' into an argument vector. Handles quoted string and basic
1615 * escape characters (\\, \", \'). Caller must free the argument vector
1616 * and its members.
1617 */
1618int
1619argv_split(const char *s, int *argcp, char ***argvp)
1620{
1621 int r = SSH_ERR_INTERNAL_ERROR;
1622 int argc = 0, quote, i, j;
1623 char *arg, **argv = xcalloc(1, sizeof(*argv));
1624
1625 *argvp = NULL;
1626 *argcp = 0;
1627
1628 for (i = 0; s[i] != '\0'; i++) {
1629 /* Skip leading whitespace */
1630 if (s[i] == ' ' || s[i] == '\t')
1631 continue;
1632
1633 /* Start of a token */
1634 quote = 0;
1635 if (s[i] == '\\' &&
1636 (s[i + 1] == '\'' || s[i + 1] == '\"' || s[i + 1] == '\\'))
1637 i++;
1638 else if (s[i] == '\'' || s[i] == '"')
1639 quote = s[i++];
1640
1641 argv = xreallocarray(argv, (argc + 2), sizeof(*argv));
1642 arg = argv[argc++] = xcalloc(1, strlen(s + i) + 1);
1643 argv[argc] = NULL;
1644
1645 /* Copy the token in, removing escapes */
1646 for (j = 0; s[i] != '\0'; i++) {
1647 if (s[i] == '\\') {
1648 if (s[i + 1] == '\'' ||
1649 s[i + 1] == '\"' ||
1650 s[i + 1] == '\\') {
1651 i++; /* Skip '\' */
1652 arg[j++] = s[i];
1653 } else {
1654 /* Unrecognised escape */
1655 arg[j++] = s[i];
1656 }
1657 } else if (quote == 0 && (s[i] == ' ' || s[i] == '\t'))
1658 break; /* done */
1659 else if (quote != 0 && s[i] == quote)
1660 break; /* done */
1661 else
1662 arg[j++] = s[i];
1663 }
1664 if (s[i] == '\0') {
1665 if (quote != 0) {
1666 /* Ran out of string looking for close quote */
1667 r = SSH_ERR_INVALID_FORMAT;
1668 goto out;
1669 }
1670 break;
1671 }
1672 }
1673 /* Success */
1674 *argcp = argc;
1675 *argvp = argv;
1676 argc = 0;
1677 argv = NULL;
1678 r = 0;
1679 out:
1680 if (argc != 0 && argv != NULL) {
1681 for (i = 0; i < argc; i++)
1682 free(argv[i]);
1683 free(argv);
1684 }
1685 return r;
1686}
1687
1688/*
1689 * Reassemble an argument vector into a string, quoting and escaping as
1690 * necessary. Caller must free returned string.
1691 */
1692char *
1693argv_assemble(int argc, char **argv)
1694{
1695 int i, j, ws, r;
1696 char c, *ret;
1697 struct sshbuf *buf, *arg;
1698
1699 if ((buf = sshbuf_new()) == NULL || (arg = sshbuf_new()) == NULL)
1700 fatal("%s: sshbuf_new failed", __func__);
1701
1702 for (i = 0; i < argc; i++) {
1703 ws = 0;
1704 sshbuf_reset(arg);
1705 for (j = 0; argv[i][j] != '\0'; j++) {
1706 r = 0;
1707 c = argv[i][j];
1708 switch (c) {
1709 case ' ':
1710 case '\t':
1711 ws = 1;
1712 r = sshbuf_put_u8(arg, c);
1713 break;
1714 case '\\':
1715 case '\'':
1716 case '"':
1717 if ((r = sshbuf_put_u8(arg, '\\')) != 0)
1718 break;
1719 /* FALLTHROUGH */
1720 default:
1721 r = sshbuf_put_u8(arg, c);
1722 break;
1723 }
1724 if (r != 0)
1725 fatal("%s: sshbuf_put_u8: %s",
1726 __func__, ssh_err(r));
1727 }
1728 if ((i != 0 && (r = sshbuf_put_u8(buf, ' ')) != 0) ||
1729 (ws != 0 && (r = sshbuf_put_u8(buf, '"')) != 0) ||
1730 (r = sshbuf_putb(buf, arg)) != 0 ||
1731 (ws != 0 && (r = sshbuf_put_u8(buf, '"')) != 0))
1732 fatal("%s: buffer error: %s", __func__, ssh_err(r));
1733 }
1734 if ((ret = malloc(sshbuf_len(buf) + 1)) == NULL)
1735 fatal("%s: malloc failed", __func__);
1736 memcpy(ret, sshbuf_ptr(buf), sshbuf_len(buf));
1737 ret[sshbuf_len(buf)] = '\0';
1738 sshbuf_free(buf);
1739 sshbuf_free(arg);
1740 return ret;
1741}
1742
djm@openbsd.orgde4ae072017-08-18 05:36:45 +00001743/* Returns 0 if pid exited cleanly, non-zero otherwise */
1744int
djm@openbsd.orgb074c3c2017-08-18 05:48:04 +00001745exited_cleanly(pid_t pid, const char *tag, const char *cmd, int quiet)
djm@openbsd.orgde4ae072017-08-18 05:36:45 +00001746{
1747 int status;
1748
1749 while (waitpid(pid, &status, 0) == -1) {
1750 if (errno != EINTR) {
1751 error("%s: waitpid: %s", tag, strerror(errno));
1752 return -1;
1753 }
1754 }
1755 if (WIFSIGNALED(status)) {
1756 error("%s %s exited on signal %d", tag, cmd, WTERMSIG(status));
1757 return -1;
1758 } else if (WEXITSTATUS(status) != 0) {
djm@openbsd.orgb074c3c2017-08-18 05:48:04 +00001759 do_log2(quiet ? SYSLOG_LEVEL_DEBUG1 : SYSLOG_LEVEL_INFO,
1760 "%s %s failed, status %d", tag, cmd, WEXITSTATUS(status));
djm@openbsd.orgde4ae072017-08-18 05:36:45 +00001761 return -1;
1762 }
1763 return 0;
1764}
1765
1766/*
1767 * Check a given path for security. This is defined as all components
1768 * of the path to the file must be owned by either the owner of
1769 * of the file or root and no directories must be group or world writable.
1770 *
1771 * XXX Should any specific check be done for sym links ?
1772 *
1773 * Takes a file name, its stat information (preferably from fstat() to
1774 * avoid races), the uid of the expected owner, their home directory and an
1775 * error buffer plus max size as arguments.
1776 *
1777 * Returns 0 on success and -1 on failure
1778 */
1779int
1780safe_path(const char *name, struct stat *stp, const char *pw_dir,
1781 uid_t uid, char *err, size_t errlen)
1782{
1783 char buf[PATH_MAX], homedir[PATH_MAX];
1784 char *cp;
1785 int comparehome = 0;
1786 struct stat st;
1787
1788 if (realpath(name, buf) == NULL) {
1789 snprintf(err, errlen, "realpath %s failed: %s", name,
1790 strerror(errno));
1791 return -1;
1792 }
1793 if (pw_dir != NULL && realpath(pw_dir, homedir) != NULL)
1794 comparehome = 1;
1795
1796 if (!S_ISREG(stp->st_mode)) {
1797 snprintf(err, errlen, "%s is not a regular file", buf);
1798 return -1;
1799 }
1800 if ((!platform_sys_dir_uid(stp->st_uid) && stp->st_uid != uid) ||
1801 (stp->st_mode & 022) != 0) {
1802 snprintf(err, errlen, "bad ownership or modes for file %s",
1803 buf);
1804 return -1;
1805 }
1806
1807 /* for each component of the canonical path, walking upwards */
1808 for (;;) {
1809 if ((cp = dirname(buf)) == NULL) {
1810 snprintf(err, errlen, "dirname() failed");
1811 return -1;
1812 }
1813 strlcpy(buf, cp, sizeof(buf));
1814
1815 if (stat(buf, &st) < 0 ||
1816 (!platform_sys_dir_uid(st.st_uid) && st.st_uid != uid) ||
1817 (st.st_mode & 022) != 0) {
1818 snprintf(err, errlen,
1819 "bad ownership or modes for directory %s", buf);
1820 return -1;
1821 }
1822
1823 /* If are past the homedir then we can stop */
1824 if (comparehome && strcmp(homedir, buf) == 0)
1825 break;
1826
1827 /*
1828 * dirname should always complete with a "/" path,
1829 * but we can be paranoid and check for "." too
1830 */
1831 if ((strcmp("/", buf) == 0) || (strcmp(".", buf) == 0))
1832 break;
1833 }
1834 return 0;
1835}
1836
1837/*
1838 * Version of safe_path() that accepts an open file descriptor to
1839 * avoid races.
1840 *
1841 * Returns 0 on success and -1 on failure
1842 */
1843int
1844safe_path_fd(int fd, const char *file, struct passwd *pw,
1845 char *err, size_t errlen)
1846{
1847 struct stat st;
1848
1849 /* check the open file to avoid races */
1850 if (fstat(fd, &st) < 0) {
1851 snprintf(err, errlen, "cannot stat file %s: %s",
1852 file, strerror(errno));
1853 return -1;
1854 }
1855 return safe_path(file, &st, pw->pw_dir, pw->pw_uid, err, errlen);
1856}
1857
1858/*
1859 * Sets the value of the given variable in the environment. If the variable
1860 * already exists, its value is overridden.
1861 */
1862void
1863child_set_env(char ***envp, u_int *envsizep, const char *name,
1864 const char *value)
1865{
1866 char **env;
1867 u_int envsize;
1868 u_int i, namelen;
1869
1870 if (strchr(name, '=') != NULL) {
1871 error("Invalid environment variable \"%.100s\"", name);
1872 return;
1873 }
1874
1875 /*
1876 * If we're passed an uninitialized list, allocate a single null
1877 * entry before continuing.
1878 */
1879 if (*envp == NULL && *envsizep == 0) {
1880 *envp = xmalloc(sizeof(char *));
1881 *envp[0] = NULL;
1882 *envsizep = 1;
1883 }
1884
1885 /*
1886 * Find the slot where the value should be stored. If the variable
1887 * already exists, we reuse the slot; otherwise we append a new slot
1888 * at the end of the array, expanding if necessary.
1889 */
1890 env = *envp;
1891 namelen = strlen(name);
1892 for (i = 0; env[i]; i++)
1893 if (strncmp(env[i], name, namelen) == 0 && env[i][namelen] == '=')
1894 break;
1895 if (env[i]) {
1896 /* Reuse the slot. */
1897 free(env[i]);
1898 } else {
1899 /* New variable. Expand if necessary. */
1900 envsize = *envsizep;
1901 if (i >= envsize - 1) {
1902 if (envsize >= 1000)
1903 fatal("child_set_env: too many env vars");
1904 envsize += 50;
1905 env = (*envp) = xreallocarray(env, envsize, sizeof(char *));
1906 *envsizep = envsize;
1907 }
1908 /* Need to set the NULL pointer at end of array beyond the new slot. */
1909 env[i + 1] = NULL;
1910 }
1911
1912 /* Allocate space and format the variable in the appropriate slot. */
djm@openbsd.org7c856852018-03-03 03:15:51 +00001913 /* XXX xasprintf */
djm@openbsd.orgde4ae072017-08-18 05:36:45 +00001914 env[i] = xmalloc(strlen(name) + 1 + strlen(value) + 1);
1915 snprintf(env[i], strlen(name) + 1 + strlen(value) + 1, "%s=%s", name, value);
1916}
1917
millert@openbsd.org887669e2017-10-21 23:06:24 +00001918/*
1919 * Check and optionally lowercase a domain name, also removes trailing '.'
1920 * Returns 1 on success and 0 on failure, storing an error message in errstr.
1921 */
1922int
1923valid_domain(char *name, int makelower, const char **errstr)
1924{
1925 size_t i, l = strlen(name);
1926 u_char c, last = '\0';
1927 static char errbuf[256];
1928
1929 if (l == 0) {
1930 strlcpy(errbuf, "empty domain name", sizeof(errbuf));
1931 goto bad;
1932 }
1933 if (!isalpha((u_char)name[0]) && !isdigit((u_char)name[0])) {
1934 snprintf(errbuf, sizeof(errbuf), "domain name \"%.100s\" "
1935 "starts with invalid character", name);
1936 goto bad;
1937 }
1938 for (i = 0; i < l; i++) {
1939 c = tolower((u_char)name[i]);
1940 if (makelower)
1941 name[i] = (char)c;
1942 if (last == '.' && c == '.') {
1943 snprintf(errbuf, sizeof(errbuf), "domain name "
1944 "\"%.100s\" contains consecutive separators", name);
1945 goto bad;
1946 }
1947 if (c != '.' && c != '-' && !isalnum(c) &&
1948 c != '_') /* technically invalid, but common */ {
1949 snprintf(errbuf, sizeof(errbuf), "domain name "
1950 "\"%.100s\" contains invalid characters", name);
1951 goto bad;
1952 }
1953 last = c;
1954 }
1955 if (name[l - 1] == '.')
1956 name[l - 1] = '\0';
1957 if (errstr != NULL)
1958 *errstr = NULL;
1959 return 1;
1960bad:
1961 if (errstr != NULL)
1962 *errstr = errbuf;
1963 return 0;
1964}
dtucker@openbsd.org609d96b2017-12-05 23:59:47 +00001965
1966const char *
1967atoi_err(const char *nptr, int *val)
1968{
1969 const char *errstr = NULL;
1970 long long num;
1971
1972 if (nptr == NULL || *nptr == '\0')
1973 return "missing";
1974 num = strtonum(nptr, 0, INT_MAX, &errstr);
1975 if (errstr == NULL)
1976 *val = (int)num;
1977 return errstr;
1978}
djm@openbsd.orgbf0fbf22018-03-12 00:52:01 +00001979
1980int
1981parse_absolute_time(const char *s, uint64_t *tp)
1982{
1983 struct tm tm;
1984 time_t tt;
1985 char buf[32], *fmt;
1986
1987 *tp = 0;
1988
1989 /*
1990 * POSIX strptime says "The application shall ensure that there
1991 * is white-space or other non-alphanumeric characters between
1992 * any two conversion specifications" so arrange things this way.
1993 */
1994 switch (strlen(s)) {
1995 case 8: /* YYYYMMDD */
1996 fmt = "%Y-%m-%d";
1997 snprintf(buf, sizeof(buf), "%.4s-%.2s-%.2s", s, s + 4, s + 6);
1998 break;
1999 case 12: /* YYYYMMDDHHMM */
2000 fmt = "%Y-%m-%dT%H:%M";
2001 snprintf(buf, sizeof(buf), "%.4s-%.2s-%.2sT%.2s:%.2s",
2002 s, s + 4, s + 6, s + 8, s + 10);
2003 break;
2004 case 14: /* YYYYMMDDHHMMSS */
2005 fmt = "%Y-%m-%dT%H:%M:%S";
2006 snprintf(buf, sizeof(buf), "%.4s-%.2s-%.2sT%.2s:%.2s:%.2s",
2007 s, s + 4, s + 6, s + 8, s + 10, s + 12);
2008 break;
2009 default:
2010 return SSH_ERR_INVALID_FORMAT;
2011 }
2012
2013 memset(&tm, 0, sizeof(tm));
2014 if (strptime(buf, fmt, &tm) == NULL)
2015 return SSH_ERR_INVALID_FORMAT;
2016 if ((tt = mktime(&tm)) < 0)
2017 return SSH_ERR_INVALID_FORMAT;
2018 /* success */
2019 *tp = (uint64_t)tt;
2020 return 0;
2021}
2022
2023void
2024format_absolute_time(uint64_t t, char *buf, size_t len)
2025{
2026 time_t tt = t > INT_MAX ? INT_MAX : t; /* XXX revisit in 2038 :P */
2027 struct tm tm;
2028
2029 localtime_r(&tt, &tm);
2030 strftime(buf, len, "%Y-%m-%dT%H:%M:%S", &tm);
2031}