Coverage Report

Created: 2024-07-27 06:19

/src/openssh/misc.c
Line
Count
Source (jump to first uncovered line)
1
/* $OpenBSD: misc.c,v 1.196 2024/06/06 17:15:25 djm Exp $ */
2
/*
3
 * Copyright (c) 2000 Markus Friedl.  All rights reserved.
4
 * Copyright (c) 2005-2020 Damien Miller.  All rights reserved.
5
 * Copyright (c) 2004 Henning Brauer <henning@openbsd.org>
6
 *
7
 * Permission to use, copy, modify, and distribute this software for any
8
 * purpose with or without fee is hereby granted, provided that the above
9
 * copyright notice and this permission notice appear in all copies.
10
 *
11
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
12
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
13
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
14
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
15
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
16
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
17
 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
18
 */
19
20
21
#include "includes.h"
22
23
#include <sys/types.h>
24
#include <sys/ioctl.h>
25
#include <sys/mman.h>
26
#include <sys/socket.h>
27
#include <sys/stat.h>
28
#include <sys/time.h>
29
#include <sys/wait.h>
30
#include <sys/un.h>
31
32
#include <limits.h>
33
#ifdef HAVE_LIBGEN_H
34
# include <libgen.h>
35
#endif
36
#ifdef HAVE_POLL_H
37
#include <poll.h>
38
#endif
39
#ifdef HAVE_NLIST_H
40
#include <nlist.h>
41
#endif
42
#include <signal.h>
43
#include <stdarg.h>
44
#include <stdio.h>
45
#ifdef HAVE_STDINT_H
46
# include <stdint.h>
47
#endif
48
#include <stdlib.h>
49
#include <string.h>
50
#include <time.h>
51
#include <unistd.h>
52
53
#include <netinet/in.h>
54
#include <netinet/in_systm.h>
55
#include <netinet/ip.h>
56
#include <netinet/tcp.h>
57
#include <arpa/inet.h>
58
59
#include <ctype.h>
60
#include <errno.h>
61
#include <fcntl.h>
62
#include <netdb.h>
63
#ifdef HAVE_PATHS_H
64
# include <paths.h>
65
#include <pwd.h>
66
#include <grp.h>
67
#endif
68
#ifdef SSH_TUN_OPENBSD
69
#include <net/if.h>
70
#endif
71
72
#include "xmalloc.h"
73
#include "misc.h"
74
#include "log.h"
75
#include "ssh.h"
76
#include "sshbuf.h"
77
#include "ssherr.h"
78
#include "platform.h"
79
80
/* remove newline at end of string */
81
char *
82
chop(char *s)
83
0
{
84
0
  char *t = s;
85
0
  while (*t) {
86
0
    if (*t == '\n' || *t == '\r') {
87
0
      *t = '\0';
88
0
      return s;
89
0
    }
90
0
    t++;
91
0
  }
92
0
  return s;
93
94
0
}
95
96
/* remove whitespace from end of string */
97
void
98
rtrim(char *s)
99
0
{
100
0
  size_t i;
101
102
0
  if ((i = strlen(s)) == 0)
103
0
    return;
104
0
  for (i--; i > 0; i--) {
105
0
    if (isspace((unsigned char)s[i]))
106
0
      s[i] = '\0';
107
0
  }
108
0
}
109
110
/* set/unset filedescriptor to non-blocking */
111
int
112
set_nonblock(int fd)
113
1.24k
{
114
1.24k
  int val;
115
116
1.24k
  val = fcntl(fd, F_GETFL);
117
1.24k
  if (val == -1) {
118
0
    error("fcntl(%d, F_GETFL): %s", fd, strerror(errno));
119
0
    return (-1);
120
0
  }
121
1.24k
  if (val & O_NONBLOCK) {
122
1.24k
    debug3("fd %d is O_NONBLOCK", fd);
123
1.24k
    return (0);
124
1.24k
  }
125
1
  debug2("fd %d setting O_NONBLOCK", fd);
126
1
  val |= O_NONBLOCK;
127
1
  if (fcntl(fd, F_SETFL, val) == -1) {
128
0
    debug("fcntl(%d, F_SETFL, O_NONBLOCK): %s", fd,
129
0
        strerror(errno));
130
0
    return (-1);
131
0
  }
132
1
  return (0);
133
1
}
134
135
int
136
unset_nonblock(int fd)
137
0
{
138
0
  int val;
139
140
0
  val = fcntl(fd, F_GETFL);
141
0
  if (val == -1) {
142
0
    error("fcntl(%d, F_GETFL): %s", fd, strerror(errno));
143
0
    return (-1);
144
0
  }
145
0
  if (!(val & O_NONBLOCK)) {
146
0
    debug3("fd %d is not O_NONBLOCK", fd);
147
0
    return (0);
148
0
  }
149
0
  debug("fd %d clearing O_NONBLOCK", fd);
150
0
  val &= ~O_NONBLOCK;
151
0
  if (fcntl(fd, F_SETFL, val) == -1) {
152
0
    debug("fcntl(%d, F_SETFL, ~O_NONBLOCK): %s",
153
0
        fd, strerror(errno));
154
0
    return (-1);
155
0
  }
156
0
  return (0);
157
0
}
158
159
const char *
160
ssh_gai_strerror(int gaierr)
161
0
{
162
0
  if (gaierr == EAI_SYSTEM && errno != 0)
163
0
    return strerror(errno);
164
0
  return gai_strerror(gaierr);
165
0
}
166
167
/* disable nagle on socket */
168
void
169
set_nodelay(int fd)
170
0
{
171
0
  int opt;
172
0
  socklen_t optlen;
173
174
0
  optlen = sizeof opt;
175
0
  if (getsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &opt, &optlen) == -1) {
176
0
    debug("getsockopt TCP_NODELAY: %.100s", strerror(errno));
177
0
    return;
178
0
  }
179
0
  if (opt == 1) {
180
0
    debug2("fd %d is TCP_NODELAY", fd);
181
0
    return;
182
0
  }
183
0
  opt = 1;
184
0
  debug2("fd %d setting TCP_NODELAY", fd);
185
0
  if (setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &opt, sizeof opt) == -1)
186
0
    error("setsockopt TCP_NODELAY: %.100s", strerror(errno));
187
0
}
188
189
/* Allow local port reuse in TIME_WAIT */
190
int
191
set_reuseaddr(int fd)
192
0
{
193
0
  int on = 1;
194
195
0
  if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)) == -1) {
196
0
    error("setsockopt SO_REUSEADDR fd %d: %s", fd, strerror(errno));
197
0
    return -1;
198
0
  }
199
0
  return 0;
200
0
}
201
202
/* Get/set routing domain */
203
char *
204
get_rdomain(int fd)
205
0
{
206
0
#if defined(HAVE_SYS_GET_RDOMAIN)
207
0
  return sys_get_rdomain(fd);
208
#elif defined(__OpenBSD__)
209
  int rtable;
210
  char *ret;
211
  socklen_t len = sizeof(rtable);
212
213
  if (getsockopt(fd, SOL_SOCKET, SO_RTABLE, &rtable, &len) == -1) {
214
    error("Failed to get routing domain for fd %d: %s",
215
        fd, strerror(errno));
216
    return NULL;
217
  }
218
  xasprintf(&ret, "%d", rtable);
219
  return ret;
220
#else /* defined(__OpenBSD__) */
221
  return NULL;
222
#endif
223
0
}
224
225
int
226
set_rdomain(int fd, const char *name)
227
0
{
228
0
#if defined(HAVE_SYS_SET_RDOMAIN)
229
0
  return sys_set_rdomain(fd, name);
230
#elif defined(__OpenBSD__)
231
  int rtable;
232
  const char *errstr;
233
234
  if (name == NULL)
235
    return 0; /* default table */
236
237
  rtable = (int)strtonum(name, 0, 255, &errstr);
238
  if (errstr != NULL) {
239
    /* Shouldn't happen */
240
    error("Invalid routing domain \"%s\": %s", name, errstr);
241
    return -1;
242
  }
243
  if (setsockopt(fd, SOL_SOCKET, SO_RTABLE,
244
      &rtable, sizeof(rtable)) == -1) {
245
    error("Failed to set routing domain %d on fd %d: %s",
246
        rtable, fd, strerror(errno));
247
    return -1;
248
  }
249
  return 0;
250
#else /* defined(__OpenBSD__) */
251
  error("Setting routing domain is not supported on this platform");
252
  return -1;
253
#endif
254
0
}
255
256
int
257
get_sock_af(int fd)
258
0
{
259
0
  struct sockaddr_storage to;
260
0
  socklen_t tolen = sizeof(to);
261
262
0
  memset(&to, 0, sizeof(to));
263
0
  if (getsockname(fd, (struct sockaddr *)&to, &tolen) == -1)
264
0
    return -1;
265
0
#ifdef IPV4_IN_IPV6
266
0
  if (to.ss_family == AF_INET6 &&
267
0
      IN6_IS_ADDR_V4MAPPED(&((struct sockaddr_in6 *)&to)->sin6_addr))
268
0
    return AF_INET;
269
0
#endif
270
0
  return to.ss_family;
271
0
}
272
273
void
274
set_sock_tos(int fd, int tos)
275
0
{
276
0
#ifndef IP_TOS_IS_BROKEN
277
0
  int af;
278
279
0
  switch ((af = get_sock_af(fd))) {
280
0
  case -1:
281
    /* assume not a socket */
282
0
    break;
283
0
  case AF_INET:
284
0
# ifdef IP_TOS
285
0
    debug3_f("set socket %d IP_TOS 0x%02x", fd, tos);
286
0
    if (setsockopt(fd, IPPROTO_IP, IP_TOS,
287
0
        &tos, sizeof(tos)) == -1) {
288
0
      error("setsockopt socket %d IP_TOS %d: %s",
289
0
          fd, tos, strerror(errno));
290
0
    }
291
0
# endif /* IP_TOS */
292
0
    break;
293
0
  case AF_INET6:
294
0
# ifdef IPV6_TCLASS
295
0
    debug3_f("set socket %d IPV6_TCLASS 0x%02x", fd, tos);
296
0
    if (setsockopt(fd, IPPROTO_IPV6, IPV6_TCLASS,
297
0
        &tos, sizeof(tos)) == -1) {
298
0
      error("setsockopt socket %d IPV6_TCLASS %d: %s",
299
0
          fd, tos, strerror(errno));
300
0
    }
301
0
# endif /* IPV6_TCLASS */
302
0
    break;
303
0
  default:
304
0
    debug2_f("unsupported socket family %d", af);
305
0
    break;
306
0
  }
307
0
#endif /* IP_TOS_IS_BROKEN */
308
0
}
309
310
/*
311
 * Wait up to *timeoutp milliseconds for events on fd. Updates
312
 * *timeoutp with time remaining.
313
 * Returns 0 if fd ready or -1 on timeout or error (see errno).
314
 */
315
static int
316
waitfd(int fd, int *timeoutp, short events, volatile sig_atomic_t *stop)
317
0
{
318
0
  struct pollfd pfd;
319
0
  struct timespec timeout;
320
0
  int oerrno, r;
321
0
  sigset_t nsigset, osigset;
322
323
0
  if (timeoutp && *timeoutp == -1)
324
0
    timeoutp = NULL;
325
0
  pfd.fd = fd;
326
0
  pfd.events = events;
327
0
  ptimeout_init(&timeout);
328
0
  if (timeoutp != NULL)
329
0
    ptimeout_deadline_ms(&timeout, *timeoutp);
330
0
  if (stop != NULL)
331
0
    sigfillset(&nsigset);
332
0
  for (; timeoutp == NULL || *timeoutp >= 0;) {
333
0
    if (stop != NULL) {
334
0
      sigprocmask(SIG_BLOCK, &nsigset, &osigset);
335
0
      if (*stop) {
336
0
        sigprocmask(SIG_SETMASK, &osigset, NULL);
337
0
        errno = EINTR;
338
0
        return -1;
339
0
      }
340
0
    }
341
0
    r = ppoll(&pfd, 1, ptimeout_get_tsp(&timeout),
342
0
        stop != NULL ? &osigset : NULL);
343
0
    oerrno = errno;
344
0
    if (stop != NULL)
345
0
      sigprocmask(SIG_SETMASK, &osigset, NULL);
346
0
    if (timeoutp)
347
0
      *timeoutp = ptimeout_get_ms(&timeout);
348
0
    errno = oerrno;
349
0
    if (r > 0)
350
0
      return 0;
351
0
    else if (r == -1 && errno != EAGAIN && errno != EINTR)
352
0
      return -1;
353
0
    else if (r == 0)
354
0
      break;
355
0
  }
356
  /* timeout */
357
0
  errno = ETIMEDOUT;
358
0
  return -1;
359
0
}
360
361
/*
362
 * Wait up to *timeoutp milliseconds for fd to be readable. Updates
363
 * *timeoutp with time remaining.
364
 * Returns 0 if fd ready or -1 on timeout or error (see errno).
365
 */
366
int
367
0
waitrfd(int fd, int *timeoutp, volatile sig_atomic_t *stop) {
368
0
  return waitfd(fd, timeoutp, POLLIN, stop);
369
0
}
370
371
/*
372
 * Attempt a non-blocking connect(2) to the specified address, waiting up to
373
 * *timeoutp milliseconds for the connection to complete. If the timeout is
374
 * <=0, then wait indefinitely.
375
 *
376
 * Returns 0 on success or -1 on failure.
377
 */
378
int
379
timeout_connect(int sockfd, const struct sockaddr *serv_addr,
380
    socklen_t addrlen, int *timeoutp)
381
0
{
382
0
  int optval = 0;
383
0
  socklen_t optlen = sizeof(optval);
384
385
  /* No timeout: just do a blocking connect() */
386
0
  if (timeoutp == NULL || *timeoutp <= 0)
387
0
    return connect(sockfd, serv_addr, addrlen);
388
389
0
  set_nonblock(sockfd);
390
0
  for (;;) {
391
0
    if (connect(sockfd, serv_addr, addrlen) == 0) {
392
      /* Succeeded already? */
393
0
      unset_nonblock(sockfd);
394
0
      return 0;
395
0
    } else if (errno == EINTR)
396
0
      continue;
397
0
    else if (errno != EINPROGRESS)
398
0
      return -1;
399
0
    break;
400
0
  }
401
402
0
  if (waitfd(sockfd, timeoutp, POLLIN | POLLOUT, NULL) == -1)
403
0
    return -1;
404
405
  /* Completed or failed */
406
0
  if (getsockopt(sockfd, SOL_SOCKET, SO_ERROR, &optval, &optlen) == -1) {
407
0
    debug("getsockopt: %s", strerror(errno));
408
0
    return -1;
409
0
  }
410
0
  if (optval != 0) {
411
0
    errno = optval;
412
0
    return -1;
413
0
  }
414
0
  unset_nonblock(sockfd);
415
0
  return 0;
416
0
}
417
418
/* Characters considered whitespace in strsep calls. */
419
0
#define WHITESPACE " \t\r\n"
420
0
#define QUOTE "\""
421
422
/* return next token in configuration line */
423
static char *
424
strdelim_internal(char **s, int split_equals)
425
0
{
426
0
  char *old;
427
0
  int wspace = 0;
428
429
0
  if (*s == NULL)
430
0
    return NULL;
431
432
0
  old = *s;
433
434
0
  *s = strpbrk(*s,
435
0
      split_equals ? WHITESPACE QUOTE "=" : WHITESPACE QUOTE);
436
0
  if (*s == NULL)
437
0
    return (old);
438
439
0
  if (*s[0] == '\"') {
440
0
    memmove(*s, *s + 1, strlen(*s)); /* move nul too */
441
    /* Find matching quote */
442
0
    if ((*s = strpbrk(*s, QUOTE)) == NULL) {
443
0
      return (NULL);    /* no matching quote */
444
0
    } else {
445
0
      *s[0] = '\0';
446
0
      *s += strspn(*s + 1, WHITESPACE) + 1;
447
0
      return (old);
448
0
    }
449
0
  }
450
451
  /* Allow only one '=' to be skipped */
452
0
  if (split_equals && *s[0] == '=')
453
0
    wspace = 1;
454
0
  *s[0] = '\0';
455
456
  /* Skip any extra whitespace after first token */
457
0
  *s += strspn(*s + 1, WHITESPACE) + 1;
458
0
  if (split_equals && *s[0] == '=' && !wspace)
459
0
    *s += strspn(*s + 1, WHITESPACE) + 1;
460
461
0
  return (old);
462
0
}
463
464
/*
465
 * Return next token in configuration line; splts on whitespace or a
466
 * single '=' character.
467
 */
468
char *
469
strdelim(char **s)
470
0
{
471
0
  return strdelim_internal(s, 1);
472
0
}
473
474
/*
475
 * Return next token in configuration line; splts on whitespace only.
476
 */
477
char *
478
strdelimw(char **s)
479
0
{
480
0
  return strdelim_internal(s, 0);
481
0
}
482
483
struct passwd *
484
pwcopy(struct passwd *pw)
485
0
{
486
0
  struct passwd *copy = xcalloc(1, sizeof(*copy));
487
488
0
  copy->pw_name = xstrdup(pw->pw_name);
489
0
  copy->pw_passwd = xstrdup(pw->pw_passwd == NULL ? "*" : pw->pw_passwd);
490
0
#ifdef HAVE_STRUCT_PASSWD_PW_GECOS
491
0
  copy->pw_gecos = xstrdup(pw->pw_gecos);
492
0
#endif
493
0
  copy->pw_uid = pw->pw_uid;
494
0
  copy->pw_gid = pw->pw_gid;
495
#ifdef HAVE_STRUCT_PASSWD_PW_EXPIRE
496
  copy->pw_expire = pw->pw_expire;
497
#endif
498
#ifdef HAVE_STRUCT_PASSWD_PW_CHANGE
499
  copy->pw_change = pw->pw_change;
500
#endif
501
#ifdef HAVE_STRUCT_PASSWD_PW_CLASS
502
  copy->pw_class = xstrdup(pw->pw_class);
503
#endif
504
0
  copy->pw_dir = xstrdup(pw->pw_dir);
505
0
  copy->pw_shell = xstrdup(pw->pw_shell);
506
0
  return copy;
507
0
}
508
509
/*
510
 * Convert ASCII string to TCP/IP port number.
511
 * Port must be >=0 and <=65535.
512
 * Return -1 if invalid.
513
 */
514
int
515
a2port(const char *s)
516
1.40k
{
517
1.40k
  struct servent *se;
518
1.40k
  long long port;
519
1.40k
  const char *errstr;
520
521
1.40k
  port = strtonum(s, 0, 65535, &errstr);
522
1.40k
  if (errstr == NULL)
523
1.18k
    return (int)port;
524
220
  if ((se = getservbyname(s, "tcp")) != NULL)
525
0
    return ntohs(se->s_port);
526
220
  return -1;
527
220
}
528
529
int
530
a2tun(const char *s, int *remote)
531
916
{
532
916
  const char *errstr = NULL;
533
916
  char *sp, *ep;
534
916
  int tun;
535
536
916
  if (remote != NULL) {
537
0
    *remote = SSH_TUNID_ANY;
538
0
    sp = xstrdup(s);
539
0
    if ((ep = strchr(sp, ':')) == NULL) {
540
0
      free(sp);
541
0
      return (a2tun(s, NULL));
542
0
    }
543
0
    ep[0] = '\0'; ep++;
544
0
    *remote = a2tun(ep, NULL);
545
0
    tun = a2tun(sp, NULL);
546
0
    free(sp);
547
0
    return (*remote == SSH_TUNID_ERR ? *remote : tun);
548
0
  }
549
550
916
  if (strcasecmp(s, "any") == 0)
551
194
    return (SSH_TUNID_ANY);
552
553
722
  tun = strtonum(s, 0, SSH_TUNID_MAX, &errstr);
554
722
  if (errstr != NULL)
555
254
    return (SSH_TUNID_ERR);
556
557
468
  return (tun);
558
722
}
559
560
0
#define SECONDS   1
561
0
#define MINUTES   (SECONDS * 60)
562
0
#define HOURS   (MINUTES * 60)
563
0
#define DAYS    (HOURS * 24)
564
0
#define WEEKS   (DAYS * 7)
565
566
static char *
567
scandigits(char *s)
568
0
{
569
0
  while (isdigit((unsigned char)*s))
570
0
    s++;
571
0
  return s;
572
0
}
573
574
/*
575
 * Convert a time string into seconds; format is
576
 * a sequence of:
577
 *      time[qualifier]
578
 *
579
 * Valid time qualifiers are:
580
 *      <none>  seconds
581
 *      s|S     seconds
582
 *      m|M     minutes
583
 *      h|H     hours
584
 *      d|D     days
585
 *      w|W     weeks
586
 *
587
 * Examples:
588
 *      90m     90 minutes
589
 *      1h30m   90 minutes
590
 *      2d      2 days
591
 *      1w      1 week
592
 *
593
 * Return -1 if time string is invalid.
594
 */
595
int
596
convtime(const char *s)
597
0
{
598
0
  int secs, total = 0, multiplier;
599
0
  char *p, *os, *np, c = 0;
600
0
  const char *errstr;
601
602
0
  if (s == NULL || *s == '\0')
603
0
    return -1;
604
0
  p = os = strdup(s); /* deal with const */
605
0
  if (os == NULL)
606
0
    return -1;
607
608
0
  while (*p) {
609
0
    np = scandigits(p);
610
0
    if (np) {
611
0
      c = *np;
612
0
      *np = '\0';
613
0
    }
614
0
    secs = (int)strtonum(p, 0, INT_MAX, &errstr);
615
0
    if (errstr)
616
0
      goto fail;
617
0
    *np = c;
618
619
0
    multiplier = 1;
620
0
    switch (c) {
621
0
    case '\0':
622
0
      np--; /* back up */
623
0
      break;
624
0
    case 's':
625
0
    case 'S':
626
0
      break;
627
0
    case 'm':
628
0
    case 'M':
629
0
      multiplier = MINUTES;
630
0
      break;
631
0
    case 'h':
632
0
    case 'H':
633
0
      multiplier = HOURS;
634
0
      break;
635
0
    case 'd':
636
0
    case 'D':
637
0
      multiplier = DAYS;
638
0
      break;
639
0
    case 'w':
640
0
    case 'W':
641
0
      multiplier = WEEKS;
642
0
      break;
643
0
    default:
644
0
      goto fail;
645
0
    }
646
0
    if (secs > INT_MAX / multiplier)
647
0
      goto fail;
648
0
    secs *= multiplier;
649
0
    if  (total > INT_MAX - secs)
650
0
      goto fail;
651
0
    total += secs;
652
0
    if (total < 0)
653
0
      goto fail;
654
0
    p = ++np;
655
0
  }
656
0
  free(os);
657
0
  return total;
658
0
fail:
659
0
  free(os);
660
0
  return -1;
661
0
}
662
663
0
#define TF_BUFS 8
664
0
#define TF_LEN  9
665
666
const char *
667
fmt_timeframe(time_t t)
668
0
{
669
0
  char    *buf;
670
0
  static char  tfbuf[TF_BUFS][TF_LEN];  /* ring buffer */
671
0
  static int   idx = 0;
672
0
  unsigned int   sec, min, hrs, day;
673
0
  unsigned long long  week;
674
675
0
  buf = tfbuf[idx++];
676
0
  if (idx == TF_BUFS)
677
0
    idx = 0;
678
679
0
  week = t;
680
681
0
  sec = week % 60;
682
0
  week /= 60;
683
0
  min = week % 60;
684
0
  week /= 60;
685
0
  hrs = week % 24;
686
0
  week /= 24;
687
0
  day = week % 7;
688
0
  week /= 7;
689
690
0
  if (week > 0)
691
0
    snprintf(buf, TF_LEN, "%02lluw%01ud%02uh", week, day, hrs);
692
0
  else if (day > 0)
693
0
    snprintf(buf, TF_LEN, "%01ud%02uh%02um", day, hrs, min);
694
0
  else
695
0
    snprintf(buf, TF_LEN, "%02u:%02u:%02u", hrs, min, sec);
696
697
0
  return (buf);
698
0
}
699
700
/*
701
 * Returns a standardized host+port identifier string.
702
 * Caller must free returned string.
703
 */
704
char *
705
put_host_port(const char *host, u_short port)
706
0
{
707
0
  char *hoststr;
708
709
0
  if (port == 0 || port == SSH_DEFAULT_PORT)
710
0
    return(xstrdup(host));
711
0
  if (asprintf(&hoststr, "[%s]:%d", host, (int)port) == -1)
712
0
    fatal("put_host_port: asprintf: %s", strerror(errno));
713
0
  debug3("put_host_port: %s", hoststr);
714
0
  return hoststr;
715
0
}
716
717
/*
718
 * Search for next delimiter between hostnames/addresses and ports.
719
 * Argument may be modified (for termination).
720
 * Returns *cp if parsing succeeds.
721
 * *cp is set to the start of the next field, if one was found.
722
 * The delimiter char, if present, is stored in delim.
723
 * If this is the last field, *cp is set to NULL.
724
 */
725
char *
726
hpdelim2(char **cp, char *delim)
727
88.7k
{
728
88.7k
  char *s, *old;
729
730
88.7k
  if (cp == NULL || *cp == NULL)
731
0
    return NULL;
732
733
88.7k
  old = s = *cp;
734
88.7k
  if (*s == '[') {
735
196
    if ((s = strchr(s, ']')) == NULL)
736
1
      return NULL;
737
195
    else
738
195
      s++;
739
88.5k
  } else if ((s = strpbrk(s, ":/")) == NULL)
740
29
    s = *cp + strlen(*cp); /* skip to end (see first case below) */
741
742
88.7k
  switch (*s) {
743
37
  case '\0':
744
37
    *cp = NULL; /* no more fields*/
745
37
    break;
746
747
88.3k
  case ':':
748
88.7k
  case '/':
749
88.7k
    if (delim != NULL)
750
0
      *delim = *s;
751
88.7k
    *s = '\0';  /* terminate */
752
88.7k
    *cp = s + 1;
753
88.7k
    break;
754
755
1
  default:
756
1
    return NULL;
757
88.7k
  }
758
759
88.7k
  return old;
760
88.7k
}
761
762
/* The common case: only accept colon as delimiter. */
763
char *
764
hpdelim(char **cp)
765
0
{
766
0
  char *r, delim = '\0';
767
768
0
  r =  hpdelim2(cp, &delim);
769
0
  if (delim == '/')
770
0
    return NULL;
771
0
  return r;
772
0
}
773
774
char *
775
cleanhostname(char *host)
776
0
{
777
0
  if (*host == '[' && host[strlen(host) - 1] == ']') {
778
0
    host[strlen(host) - 1] = '\0';
779
0
    return (host + 1);
780
0
  } else
781
0
    return host;
782
0
}
783
784
char *
785
colon(char *cp)
786
0
{
787
0
  int flag = 0;
788
789
0
  if (*cp == ':')   /* Leading colon is part of file name. */
790
0
    return NULL;
791
0
  if (*cp == '[')
792
0
    flag = 1;
793
794
0
  for (; *cp; ++cp) {
795
0
    if (*cp == '@' && *(cp+1) == '[')
796
0
      flag = 1;
797
0
    if (*cp == ']' && *(cp+1) == ':' && flag)
798
0
      return (cp+1);
799
0
    if (*cp == ':' && !flag)
800
0
      return (cp);
801
0
    if (*cp == '/')
802
0
      return NULL;
803
0
  }
804
0
  return NULL;
805
0
}
806
807
/*
808
 * Parse a [user@]host:[path] string.
809
 * Caller must free returned user, host and path.
810
 * Any of the pointer return arguments may be NULL (useful for syntax checking).
811
 * If user was not specified then *userp will be set to NULL.
812
 * If host was not specified then *hostp will be set to NULL.
813
 * If path was not specified then *pathp will be set to ".".
814
 * Returns 0 on success, -1 on failure.
815
 */
816
int
817
parse_user_host_path(const char *s, char **userp, char **hostp, char **pathp)
818
0
{
819
0
  char *user = NULL, *host = NULL, *path = NULL;
820
0
  char *sdup, *tmp;
821
0
  int ret = -1;
822
823
0
  if (userp != NULL)
824
0
    *userp = NULL;
825
0
  if (hostp != NULL)
826
0
    *hostp = NULL;
827
0
  if (pathp != NULL)
828
0
    *pathp = NULL;
829
830
0
  sdup = xstrdup(s);
831
832
  /* Check for remote syntax: [user@]host:[path] */
833
0
  if ((tmp = colon(sdup)) == NULL)
834
0
    goto out;
835
836
  /* Extract optional path */
837
0
  *tmp++ = '\0';
838
0
  if (*tmp == '\0')
839
0
    tmp = ".";
840
0
  path = xstrdup(tmp);
841
842
  /* Extract optional user and mandatory host */
843
0
  tmp = strrchr(sdup, '@');
844
0
  if (tmp != NULL) {
845
0
    *tmp++ = '\0';
846
0
    host = xstrdup(cleanhostname(tmp));
847
0
    if (*sdup != '\0')
848
0
      user = xstrdup(sdup);
849
0
  } else {
850
0
    host = xstrdup(cleanhostname(sdup));
851
0
    user = NULL;
852
0
  }
853
854
  /* Success */
855
0
  if (userp != NULL) {
856
0
    *userp = user;
857
0
    user = NULL;
858
0
  }
859
0
  if (hostp != NULL) {
860
0
    *hostp = host;
861
0
    host = NULL;
862
0
  }
863
0
  if (pathp != NULL) {
864
0
    *pathp = path;
865
0
    path = NULL;
866
0
  }
867
0
  ret = 0;
868
0
out:
869
0
  free(sdup);
870
0
  free(user);
871
0
  free(host);
872
0
  free(path);
873
0
  return ret;
874
0
}
875
876
/*
877
 * Parse a [user@]host[:port] string.
878
 * Caller must free returned user and host.
879
 * Any of the pointer return arguments may be NULL (useful for syntax checking).
880
 * If user was not specified then *userp will be set to NULL.
881
 * If port was not specified then *portp will be -1.
882
 * Returns 0 on success, -1 on failure.
883
 */
884
int
885
parse_user_host_port(const char *s, char **userp, char **hostp, int *portp)
886
0
{
887
0
  char *sdup, *cp, *tmp;
888
0
  char *user = NULL, *host = NULL;
889
0
  int port = -1, ret = -1;
890
891
0
  if (userp != NULL)
892
0
    *userp = NULL;
893
0
  if (hostp != NULL)
894
0
    *hostp = NULL;
895
0
  if (portp != NULL)
896
0
    *portp = -1;
897
898
0
  if ((sdup = tmp = strdup(s)) == NULL)
899
0
    return -1;
900
  /* Extract optional username */
901
0
  if ((cp = strrchr(tmp, '@')) != NULL) {
902
0
    *cp = '\0';
903
0
    if (*tmp == '\0')
904
0
      goto out;
905
0
    if ((user = strdup(tmp)) == NULL)
906
0
      goto out;
907
0
    tmp = cp + 1;
908
0
  }
909
  /* Extract mandatory hostname */
910
0
  if ((cp = hpdelim(&tmp)) == NULL || *cp == '\0')
911
0
    goto out;
912
0
  host = xstrdup(cleanhostname(cp));
913
  /* Convert and verify optional port */
914
0
  if (tmp != NULL && *tmp != '\0') {
915
0
    if ((port = a2port(tmp)) <= 0)
916
0
      goto out;
917
0
  }
918
  /* Success */
919
0
  if (userp != NULL) {
920
0
    *userp = user;
921
0
    user = NULL;
922
0
  }
923
0
  if (hostp != NULL) {
924
0
    *hostp = host;
925
0
    host = NULL;
926
0
  }
927
0
  if (portp != NULL)
928
0
    *portp = port;
929
0
  ret = 0;
930
0
 out:
931
0
  free(sdup);
932
0
  free(user);
933
0
  free(host);
934
0
  return ret;
935
0
}
936
937
/*
938
 * Converts a two-byte hex string to decimal.
939
 * Returns the decimal value or -1 for invalid input.
940
 */
941
static int
942
hexchar(const char *s)
943
0
{
944
0
  unsigned char result[2];
945
0
  int i;
946
947
0
  for (i = 0; i < 2; i++) {
948
0
    if (s[i] >= '0' && s[i] <= '9')
949
0
      result[i] = (unsigned char)(s[i] - '0');
950
0
    else if (s[i] >= 'a' && s[i] <= 'f')
951
0
      result[i] = (unsigned char)(s[i] - 'a') + 10;
952
0
    else if (s[i] >= 'A' && s[i] <= 'F')
953
0
      result[i] = (unsigned char)(s[i] - 'A') + 10;
954
0
    else
955
0
      return -1;
956
0
  }
957
0
  return (result[0] << 4) | result[1];
958
0
}
959
960
/*
961
 * Decode an url-encoded string.
962
 * Returns a newly allocated string on success or NULL on failure.
963
 */
964
static char *
965
urldecode(const char *src)
966
0
{
967
0
  char *ret, *dst;
968
0
  int ch;
969
0
  size_t srclen;
970
971
0
  if ((srclen = strlen(src)) >= SIZE_MAX)
972
0
    fatal_f("input too large");
973
0
  ret = xmalloc(srclen + 1);
974
0
  for (dst = ret; *src != '\0'; src++) {
975
0
    switch (*src) {
976
0
    case '+':
977
0
      *dst++ = ' ';
978
0
      break;
979
0
    case '%':
980
0
      if (!isxdigit((unsigned char)src[1]) ||
981
0
          !isxdigit((unsigned char)src[2]) ||
982
0
          (ch = hexchar(src + 1)) == -1) {
983
0
        free(ret);
984
0
        return NULL;
985
0
      }
986
0
      *dst++ = ch;
987
0
      src += 2;
988
0
      break;
989
0
    default:
990
0
      *dst++ = *src;
991
0
      break;
992
0
    }
993
0
  }
994
0
  *dst = '\0';
995
996
0
  return ret;
997
0
}
998
999
/*
1000
 * Parse an (scp|ssh|sftp)://[user@]host[:port][/path] URI.
1001
 * See https://tools.ietf.org/html/draft-ietf-secsh-scp-sftp-ssh-uri-04
1002
 * Either user or path may be url-encoded (but not host or port).
1003
 * Caller must free returned user, host and path.
1004
 * Any of the pointer return arguments may be NULL (useful for syntax checking)
1005
 * but the scheme must always be specified.
1006
 * If user was not specified then *userp will be set to NULL.
1007
 * If port was not specified then *portp will be -1.
1008
 * If path was not specified then *pathp will be set to NULL.
1009
 * Returns 0 on success, 1 if non-uri/wrong scheme, -1 on error/invalid uri.
1010
 */
1011
int
1012
parse_uri(const char *scheme, const char *uri, char **userp, char **hostp,
1013
    int *portp, char **pathp)
1014
0
{
1015
0
  char *uridup, *cp, *tmp, ch;
1016
0
  char *user = NULL, *host = NULL, *path = NULL;
1017
0
  int port = -1, ret = -1;
1018
0
  size_t len;
1019
1020
0
  len = strlen(scheme);
1021
0
  if (strncmp(uri, scheme, len) != 0 || strncmp(uri + len, "://", 3) != 0)
1022
0
    return 1;
1023
0
  uri += len + 3;
1024
1025
0
  if (userp != NULL)
1026
0
    *userp = NULL;
1027
0
  if (hostp != NULL)
1028
0
    *hostp = NULL;
1029
0
  if (portp != NULL)
1030
0
    *portp = -1;
1031
0
  if (pathp != NULL)
1032
0
    *pathp = NULL;
1033
1034
0
  uridup = tmp = xstrdup(uri);
1035
1036
  /* Extract optional ssh-info (username + connection params) */
1037
0
  if ((cp = strchr(tmp, '@')) != NULL) {
1038
0
    char *delim;
1039
1040
0
    *cp = '\0';
1041
    /* Extract username and connection params */
1042
0
    if ((delim = strchr(tmp, ';')) != NULL) {
1043
      /* Just ignore connection params for now */
1044
0
      *delim = '\0';
1045
0
    }
1046
0
    if (*tmp == '\0') {
1047
      /* Empty username */
1048
0
      goto out;
1049
0
    }
1050
0
    if ((user = urldecode(tmp)) == NULL)
1051
0
      goto out;
1052
0
    tmp = cp + 1;
1053
0
  }
1054
1055
  /* Extract mandatory hostname */
1056
0
  if ((cp = hpdelim2(&tmp, &ch)) == NULL || *cp == '\0')
1057
0
    goto out;
1058
0
  host = xstrdup(cleanhostname(cp));
1059
0
  if (!valid_domain(host, 0, NULL))
1060
0
    goto out;
1061
1062
0
  if (tmp != NULL && *tmp != '\0') {
1063
0
    if (ch == ':') {
1064
      /* Convert and verify port. */
1065
0
      if ((cp = strchr(tmp, '/')) != NULL)
1066
0
        *cp = '\0';
1067
0
      if ((port = a2port(tmp)) <= 0)
1068
0
        goto out;
1069
0
      tmp = cp ? cp + 1 : NULL;
1070
0
    }
1071
0
    if (tmp != NULL && *tmp != '\0') {
1072
      /* Extract optional path */
1073
0
      if ((path = urldecode(tmp)) == NULL)
1074
0
        goto out;
1075
0
    }
1076
0
  }
1077
1078
  /* Success */
1079
0
  if (userp != NULL) {
1080
0
    *userp = user;
1081
0
    user = NULL;
1082
0
  }
1083
0
  if (hostp != NULL) {
1084
0
    *hostp = host;
1085
0
    host = NULL;
1086
0
  }
1087
0
  if (portp != NULL)
1088
0
    *portp = port;
1089
0
  if (pathp != NULL) {
1090
0
    *pathp = path;
1091
0
    path = NULL;
1092
0
  }
1093
0
  ret = 0;
1094
0
 out:
1095
0
  free(uridup);
1096
0
  free(user);
1097
0
  free(host);
1098
0
  free(path);
1099
0
  return ret;
1100
0
}
1101
1102
/* function to assist building execv() arguments */
1103
void
1104
addargs(arglist *args, char *fmt, ...)
1105
0
{
1106
0
  va_list ap;
1107
0
  char *cp;
1108
0
  u_int nalloc;
1109
0
  int r;
1110
1111
0
  va_start(ap, fmt);
1112
0
  r = vasprintf(&cp, fmt, ap);
1113
0
  va_end(ap);
1114
0
  if (r == -1)
1115
0
    fatal_f("argument too long");
1116
1117
0
  nalloc = args->nalloc;
1118
0
  if (args->list == NULL) {
1119
0
    nalloc = 32;
1120
0
    args->num = 0;
1121
0
  } else if (args->num > (256 * 1024))
1122
0
    fatal_f("too many arguments");
1123
0
  else if (args->num >= args->nalloc)
1124
0
    fatal_f("arglist corrupt");
1125
0
  else if (args->num+2 >= nalloc)
1126
0
    nalloc *= 2;
1127
1128
0
  args->list = xrecallocarray(args->list, args->nalloc,
1129
0
      nalloc, sizeof(char *));
1130
0
  args->nalloc = nalloc;
1131
0
  args->list[args->num++] = cp;
1132
0
  args->list[args->num] = NULL;
1133
0
}
1134
1135
void
1136
replacearg(arglist *args, u_int which, char *fmt, ...)
1137
0
{
1138
0
  va_list ap;
1139
0
  char *cp;
1140
0
  int r;
1141
1142
0
  va_start(ap, fmt);
1143
0
  r = vasprintf(&cp, fmt, ap);
1144
0
  va_end(ap);
1145
0
  if (r == -1)
1146
0
    fatal_f("argument too long");
1147
0
  if (args->list == NULL || args->num >= args->nalloc)
1148
0
    fatal_f("arglist corrupt");
1149
1150
0
  if (which >= args->num)
1151
0
    fatal_f("tried to replace invalid arg %d >= %d",
1152
0
        which, args->num);
1153
0
  free(args->list[which]);
1154
0
  args->list[which] = cp;
1155
0
}
1156
1157
void
1158
freeargs(arglist *args)
1159
0
{
1160
0
  u_int i;
1161
1162
0
  if (args == NULL)
1163
0
    return;
1164
0
  if (args->list != NULL && args->num < args->nalloc) {
1165
0
    for (i = 0; i < args->num; i++)
1166
0
      free(args->list[i]);
1167
0
    free(args->list);
1168
0
  }
1169
0
  args->nalloc = args->num = 0;
1170
0
  args->list = NULL;
1171
0
}
1172
1173
/*
1174
 * Expands tildes in the file name.  Returns data allocated by xmalloc.
1175
 * Warning: this calls getpw*.
1176
 */
1177
int
1178
tilde_expand(const char *filename, uid_t uid, char **retp)
1179
0
{
1180
0
  char *ocopy = NULL, *copy, *s = NULL;
1181
0
  const char *path = NULL, *user = NULL;
1182
0
  struct passwd *pw;
1183
0
  size_t len;
1184
0
  int ret = -1, r, slash;
1185
1186
0
  *retp = NULL;
1187
0
  if (*filename != '~') {
1188
0
    *retp = xstrdup(filename);
1189
0
    return 0;
1190
0
  }
1191
0
  ocopy = copy = xstrdup(filename + 1);
1192
1193
0
  if (*copy == '\0')       /* ~ */
1194
0
    path = NULL;
1195
0
  else if (*copy == '/') {
1196
0
    copy += strspn(copy, "/");
1197
0
    if (*copy == '\0')
1198
0
      path = NULL;     /* ~/ */
1199
0
    else
1200
0
      path = copy;     /* ~/path */
1201
0
  } else {
1202
0
    user = copy;
1203
0
    if ((path = strchr(copy, '/')) != NULL) {
1204
0
      copy[path - copy] = '\0';
1205
0
      path++;
1206
0
      path += strspn(path, "/");
1207
0
      if (*path == '\0')   /* ~user/ */
1208
0
        path = NULL;
1209
      /* else        ~user/path */
1210
0
    }
1211
    /* else         ~user */
1212
0
  }
1213
0
  if (user != NULL) {
1214
0
    if ((pw = getpwnam(user)) == NULL) {
1215
0
      error_f("No such user %s", user);
1216
0
      goto out;
1217
0
    }
1218
0
  } else if ((pw = getpwuid(uid)) == NULL) {
1219
0
    error_f("No such uid %ld", (long)uid);
1220
0
    goto out;
1221
0
  }
1222
1223
  /* Make sure directory has a trailing '/' */
1224
0
  slash = (len = strlen(pw->pw_dir)) == 0 || pw->pw_dir[len - 1] != '/';
1225
1226
0
  if ((r = xasprintf(&s, "%s%s%s", pw->pw_dir,
1227
0
      slash ? "/" : "", path != NULL ? path : "")) <= 0) {
1228
0
    error_f("xasprintf failed");
1229
0
    goto out;
1230
0
  }
1231
0
  if (r >= PATH_MAX) {
1232
0
    error_f("Path too long");
1233
0
    goto out;
1234
0
  }
1235
  /* success */
1236
0
  ret = 0;
1237
0
  *retp = s;
1238
0
  s = NULL;
1239
0
 out:
1240
0
  free(s);
1241
0
  free(ocopy);
1242
0
  return ret;
1243
0
}
1244
1245
char *
1246
tilde_expand_filename(const char *filename, uid_t uid)
1247
0
{
1248
0
  char *ret;
1249
1250
0
  if (tilde_expand(filename, uid, &ret) != 0)
1251
0
    cleanup_exit(255);
1252
0
  return ret;
1253
0
}
1254
1255
/*
1256
 * Expand a string with a set of %[char] escapes and/or ${ENVIRONMENT}
1257
 * substitutions.  A number of escapes may be specified as
1258
 * (char *escape_chars, char *replacement) pairs. The list must be terminated
1259
 * by a NULL escape_char. Returns replaced string in memory allocated by
1260
 * xmalloc which the caller must free.
1261
 */
1262
static char *
1263
vdollar_percent_expand(int *parseerror, int dollar, int percent,
1264
    const char *string, va_list ap)
1265
0
{
1266
0
#define EXPAND_MAX_KEYS 64
1267
0
  u_int num_keys = 0, i;
1268
0
  struct {
1269
0
    const char *key;
1270
0
    const char *repl;
1271
0
  } keys[EXPAND_MAX_KEYS];
1272
0
  struct sshbuf *buf;
1273
0
  int r, missingvar = 0;
1274
0
  char *ret = NULL, *var, *varend, *val;
1275
0
  size_t len;
1276
1277
0
  if ((buf = sshbuf_new()) == NULL)
1278
0
    fatal_f("sshbuf_new failed");
1279
0
  if (parseerror == NULL)
1280
0
    fatal_f("null parseerror arg");
1281
0
  *parseerror = 1;
1282
1283
  /* Gather keys if we're doing percent expansion. */
1284
0
  if (percent) {
1285
0
    for (num_keys = 0; num_keys < EXPAND_MAX_KEYS; num_keys++) {
1286
0
      keys[num_keys].key = va_arg(ap, char *);
1287
0
      if (keys[num_keys].key == NULL)
1288
0
        break;
1289
0
      keys[num_keys].repl = va_arg(ap, char *);
1290
0
      if (keys[num_keys].repl == NULL) {
1291
0
        fatal_f("NULL replacement for token %s",
1292
0
            keys[num_keys].key);
1293
0
      }
1294
0
    }
1295
0
    if (num_keys == EXPAND_MAX_KEYS && va_arg(ap, char *) != NULL)
1296
0
      fatal_f("too many keys");
1297
0
    if (num_keys == 0)
1298
0
      fatal_f("percent expansion without token list");
1299
0
  }
1300
1301
  /* Expand string */
1302
0
  for (i = 0; *string != '\0'; string++) {
1303
    /* Optionally process ${ENVIRONMENT} expansions. */
1304
0
    if (dollar && string[0] == '$' && string[1] == '{') {
1305
0
      string += 2;  /* skip over '${' */
1306
0
      if ((varend = strchr(string, '}')) == NULL) {
1307
0
        error_f("environment variable '%s' missing "
1308
0
            "closing '}'", string);
1309
0
        goto out;
1310
0
      }
1311
0
      len = varend - string;
1312
0
      if (len == 0) {
1313
0
        error_f("zero-length environment variable");
1314
0
        goto out;
1315
0
      }
1316
0
      var = xmalloc(len + 1);
1317
0
      (void)strlcpy(var, string, len + 1);
1318
0
      if ((val = getenv(var)) == NULL) {
1319
0
        error_f("env var ${%s} has no value", var);
1320
0
        missingvar = 1;
1321
0
      } else {
1322
0
        debug3_f("expand ${%s} -> '%s'", var, val);
1323
0
        if ((r = sshbuf_put(buf, val, strlen(val))) !=0)
1324
0
          fatal_fr(r, "sshbuf_put ${}");
1325
0
      }
1326
0
      free(var);
1327
0
      string += len;
1328
0
      continue;
1329
0
    }
1330
1331
    /*
1332
     * Process percent expansions if we have a list of TOKENs.
1333
     * If we're not doing percent expansion everything just gets
1334
     * appended here.
1335
     */
1336
0
    if (*string != '%' || !percent) {
1337
0
 append:
1338
0
      if ((r = sshbuf_put_u8(buf, *string)) != 0)
1339
0
        fatal_fr(r, "sshbuf_put_u8 %%");
1340
0
      continue;
1341
0
    }
1342
0
    string++;
1343
    /* %% case */
1344
0
    if (*string == '%')
1345
0
      goto append;
1346
0
    if (*string == '\0') {
1347
0
      error_f("invalid format");
1348
0
      goto out;
1349
0
    }
1350
0
    for (i = 0; i < num_keys; i++) {
1351
0
      if (strchr(keys[i].key, *string) != NULL) {
1352
0
        if ((r = sshbuf_put(buf, keys[i].repl,
1353
0
            strlen(keys[i].repl))) != 0)
1354
0
          fatal_fr(r, "sshbuf_put %%-repl");
1355
0
        break;
1356
0
      }
1357
0
    }
1358
0
    if (i >= num_keys) {
1359
0
      error_f("unknown key %%%c", *string);
1360
0
      goto out;
1361
0
    }
1362
0
  }
1363
0
  if (!missingvar && (ret = sshbuf_dup_string(buf)) == NULL)
1364
0
    fatal_f("sshbuf_dup_string failed");
1365
0
  *parseerror = 0;
1366
0
 out:
1367
0
  sshbuf_free(buf);
1368
0
  return *parseerror ? NULL : ret;
1369
0
#undef EXPAND_MAX_KEYS
1370
0
}
1371
1372
/*
1373
 * Expand only environment variables.
1374
 * Note that although this function is variadic like the other similar
1375
 * functions, any such arguments will be unused.
1376
 */
1377
1378
char *
1379
dollar_expand(int *parseerr, const char *string, ...)
1380
0
{
1381
0
  char *ret;
1382
0
  int err;
1383
0
  va_list ap;
1384
1385
0
  va_start(ap, string);
1386
0
  ret = vdollar_percent_expand(&err, 1, 0, string, ap);
1387
0
  va_end(ap);
1388
0
  if (parseerr != NULL)
1389
0
    *parseerr = err;
1390
0
  return ret;
1391
0
}
1392
1393
/*
1394
 * Returns expanded string or NULL if a specified environment variable is
1395
 * not defined, or calls fatal if the string is invalid.
1396
 */
1397
char *
1398
percent_expand(const char *string, ...)
1399
0
{
1400
0
  char *ret;
1401
0
  int err;
1402
0
  va_list ap;
1403
1404
0
  va_start(ap, string);
1405
0
  ret = vdollar_percent_expand(&err, 0, 1, string, ap);
1406
0
  va_end(ap);
1407
0
  if (err)
1408
0
    fatal_f("failed");
1409
0
  return ret;
1410
0
}
1411
1412
/*
1413
 * Returns expanded string or NULL if a specified environment variable is
1414
 * not defined, or calls fatal if the string is invalid.
1415
 */
1416
char *
1417
percent_dollar_expand(const char *string, ...)
1418
0
{
1419
0
  char *ret;
1420
0
  int err;
1421
0
  va_list ap;
1422
1423
0
  va_start(ap, string);
1424
0
  ret = vdollar_percent_expand(&err, 1, 1, string, ap);
1425
0
  va_end(ap);
1426
0
  if (err)
1427
0
    fatal_f("failed");
1428
0
  return ret;
1429
0
}
1430
1431
int
1432
tun_open(int tun, int mode, char **ifname)
1433
0
{
1434
0
#if defined(CUSTOM_SYS_TUN_OPEN)
1435
0
  return (sys_tun_open(tun, mode, ifname));
1436
#elif defined(SSH_TUN_OPENBSD)
1437
  struct ifreq ifr;
1438
  char name[100];
1439
  int fd = -1, sock;
1440
  const char *tunbase = "tun";
1441
1442
  if (ifname != NULL)
1443
    *ifname = NULL;
1444
1445
  if (mode == SSH_TUNMODE_ETHERNET)
1446
    tunbase = "tap";
1447
1448
  /* Open the tunnel device */
1449
  if (tun <= SSH_TUNID_MAX) {
1450
    snprintf(name, sizeof(name), "/dev/%s%d", tunbase, tun);
1451
    fd = open(name, O_RDWR);
1452
  } else if (tun == SSH_TUNID_ANY) {
1453
    for (tun = 100; tun >= 0; tun--) {
1454
      snprintf(name, sizeof(name), "/dev/%s%d",
1455
          tunbase, tun);
1456
      if ((fd = open(name, O_RDWR)) >= 0)
1457
        break;
1458
    }
1459
  } else {
1460
    debug_f("invalid tunnel %u", tun);
1461
    return -1;
1462
  }
1463
1464
  if (fd == -1) {
1465
    debug_f("%s open: %s", name, strerror(errno));
1466
    return -1;
1467
  }
1468
1469
  debug_f("%s mode %d fd %d", name, mode, fd);
1470
1471
  /* Bring interface up if it is not already */
1472
  snprintf(ifr.ifr_name, sizeof(ifr.ifr_name), "%s%d", tunbase, tun);
1473
  if ((sock = socket(PF_UNIX, SOCK_STREAM, 0)) == -1)
1474
    goto failed;
1475
1476
  if (ioctl(sock, SIOCGIFFLAGS, &ifr) == -1) {
1477
    debug_f("get interface %s flags: %s", ifr.ifr_name,
1478
        strerror(errno));
1479
    goto failed;
1480
  }
1481
1482
  if (!(ifr.ifr_flags & IFF_UP)) {
1483
    ifr.ifr_flags |= IFF_UP;
1484
    if (ioctl(sock, SIOCSIFFLAGS, &ifr) == -1) {
1485
      debug_f("activate interface %s: %s", ifr.ifr_name,
1486
          strerror(errno));
1487
      goto failed;
1488
    }
1489
  }
1490
1491
  if (ifname != NULL)
1492
    *ifname = xstrdup(ifr.ifr_name);
1493
1494
  close(sock);
1495
  return fd;
1496
1497
 failed:
1498
  if (fd >= 0)
1499
    close(fd);
1500
  if (sock >= 0)
1501
    close(sock);
1502
  return -1;
1503
#else
1504
  error("Tunnel interfaces are not supported on this platform");
1505
  return (-1);
1506
#endif
1507
0
}
1508
1509
void
1510
sanitise_stdfd(void)
1511
0
{
1512
0
  int nullfd, dupfd;
1513
1514
0
  if ((nullfd = dupfd = open(_PATH_DEVNULL, O_RDWR)) == -1) {
1515
0
    fprintf(stderr, "Couldn't open /dev/null: %s\n",
1516
0
        strerror(errno));
1517
0
    exit(1);
1518
0
  }
1519
0
  while (++dupfd <= STDERR_FILENO) {
1520
    /* Only populate closed fds. */
1521
0
    if (fcntl(dupfd, F_GETFL) == -1 && errno == EBADF) {
1522
0
      if (dup2(nullfd, dupfd) == -1) {
1523
0
        fprintf(stderr, "dup2: %s\n", strerror(errno));
1524
0
        exit(1);
1525
0
      }
1526
0
    }
1527
0
  }
1528
0
  if (nullfd > STDERR_FILENO)
1529
0
    close(nullfd);
1530
0
}
1531
1532
char *
1533
tohex(const void *vp, size_t l)
1534
2.10k
{
1535
2.10k
  const u_char *p = (const u_char *)vp;
1536
2.10k
  char b[3], *r;
1537
2.10k
  size_t i, hl;
1538
1539
2.10k
  if (l > 65536)
1540
0
    return xstrdup("tohex: length > 65536");
1541
1542
2.10k
  hl = l * 2 + 1;
1543
2.10k
  r = xcalloc(1, hl);
1544
101k
  for (i = 0; i < l; i++) {
1545
99.2k
    snprintf(b, sizeof(b), "%02x", p[i]);
1546
99.2k
    strlcat(r, b, hl);
1547
99.2k
  }
1548
2.10k
  return (r);
1549
2.10k
}
1550
1551
/*
1552
 * Extend string *sp by the specified format. If *sp is not NULL (or empty),
1553
 * then the separator 'sep' will be prepended before the formatted arguments.
1554
 * Extended strings are heap allocated.
1555
 */
1556
void
1557
xextendf(char **sp, const char *sep, const char *fmt, ...)
1558
0
{
1559
0
  va_list ap;
1560
0
  char *tmp1, *tmp2;
1561
1562
0
  va_start(ap, fmt);
1563
0
  xvasprintf(&tmp1, fmt, ap);
1564
0
  va_end(ap);
1565
1566
0
  if (*sp == NULL || **sp == '\0') {
1567
0
    free(*sp);
1568
0
    *sp = tmp1;
1569
0
    return;
1570
0
  }
1571
0
  xasprintf(&tmp2, "%s%s%s", *sp, sep == NULL ? "" : sep, tmp1);
1572
0
  free(tmp1);
1573
0
  free(*sp);
1574
0
  *sp = tmp2;
1575
0
}
1576
1577
1578
u_int64_t
1579
get_u64(const void *vp)
1580
0
{
1581
0
  const u_char *p = (const u_char *)vp;
1582
0
  u_int64_t v;
1583
1584
0
  v  = (u_int64_t)p[0] << 56;
1585
0
  v |= (u_int64_t)p[1] << 48;
1586
0
  v |= (u_int64_t)p[2] << 40;
1587
0
  v |= (u_int64_t)p[3] << 32;
1588
0
  v |= (u_int64_t)p[4] << 24;
1589
0
  v |= (u_int64_t)p[5] << 16;
1590
0
  v |= (u_int64_t)p[6] << 8;
1591
0
  v |= (u_int64_t)p[7];
1592
1593
0
  return (v);
1594
0
}
1595
1596
u_int32_t
1597
get_u32(const void *vp)
1598
226k
{
1599
226k
  const u_char *p = (const u_char *)vp;
1600
226k
  u_int32_t v;
1601
1602
226k
  v  = (u_int32_t)p[0] << 24;
1603
226k
  v |= (u_int32_t)p[1] << 16;
1604
226k
  v |= (u_int32_t)p[2] << 8;
1605
226k
  v |= (u_int32_t)p[3];
1606
1607
226k
  return (v);
1608
226k
}
1609
1610
u_int32_t
1611
get_u32_le(const void *vp)
1612
3.60M
{
1613
3.60M
  const u_char *p = (const u_char *)vp;
1614
3.60M
  u_int32_t v;
1615
1616
3.60M
  v  = (u_int32_t)p[0];
1617
3.60M
  v |= (u_int32_t)p[1] << 8;
1618
3.60M
  v |= (u_int32_t)p[2] << 16;
1619
3.60M
  v |= (u_int32_t)p[3] << 24;
1620
1621
3.60M
  return (v);
1622
3.60M
}
1623
1624
u_int16_t
1625
get_u16(const void *vp)
1626
0
{
1627
0
  const u_char *p = (const u_char *)vp;
1628
0
  u_int16_t v;
1629
1630
0
  v  = (u_int16_t)p[0] << 8;
1631
0
  v |= (u_int16_t)p[1];
1632
1633
0
  return (v);
1634
0
}
1635
1636
void
1637
put_u64(void *vp, u_int64_t v)
1638
100k
{
1639
100k
  u_char *p = (u_char *)vp;
1640
1641
100k
  p[0] = (u_char)(v >> 56) & 0xff;
1642
100k
  p[1] = (u_char)(v >> 48) & 0xff;
1643
100k
  p[2] = (u_char)(v >> 40) & 0xff;
1644
100k
  p[3] = (u_char)(v >> 32) & 0xff;
1645
100k
  p[4] = (u_char)(v >> 24) & 0xff;
1646
100k
  p[5] = (u_char)(v >> 16) & 0xff;
1647
100k
  p[6] = (u_char)(v >> 8) & 0xff;
1648
100k
  p[7] = (u_char)v & 0xff;
1649
100k
}
1650
1651
void
1652
put_u32(void *vp, u_int32_t v)
1653
413k
{
1654
413k
  u_char *p = (u_char *)vp;
1655
1656
413k
  p[0] = (u_char)(v >> 24) & 0xff;
1657
413k
  p[1] = (u_char)(v >> 16) & 0xff;
1658
413k
  p[2] = (u_char)(v >> 8) & 0xff;
1659
413k
  p[3] = (u_char)v & 0xff;
1660
413k
}
1661
1662
void
1663
put_u32_le(void *vp, u_int32_t v)
1664
0
{
1665
0
  u_char *p = (u_char *)vp;
1666
1667
0
  p[0] = (u_char)v & 0xff;
1668
0
  p[1] = (u_char)(v >> 8) & 0xff;
1669
0
  p[2] = (u_char)(v >> 16) & 0xff;
1670
0
  p[3] = (u_char)(v >> 24) & 0xff;
1671
0
}
1672
1673
void
1674
put_u16(void *vp, u_int16_t v)
1675
0
{
1676
0
  u_char *p = (u_char *)vp;
1677
1678
0
  p[0] = (u_char)(v >> 8) & 0xff;
1679
0
  p[1] = (u_char)v & 0xff;
1680
0
}
1681
1682
void
1683
ms_subtract_diff(struct timeval *start, int *ms)
1684
0
{
1685
0
  struct timeval diff, finish;
1686
1687
0
  monotime_tv(&finish);
1688
0
  timersub(&finish, start, &diff);
1689
0
  *ms -= (diff.tv_sec * 1000) + (diff.tv_usec / 1000);
1690
0
}
1691
1692
void
1693
ms_to_timespec(struct timespec *ts, int ms)
1694
0
{
1695
0
  if (ms < 0)
1696
0
    ms = 0;
1697
0
  ts->tv_sec = ms / 1000;
1698
0
  ts->tv_nsec = (ms % 1000) * 1000 * 1000;
1699
0
}
1700
1701
void
1702
monotime_ts(struct timespec *ts)
1703
630
{
1704
630
  struct timeval tv;
1705
630
#if defined(HAVE_CLOCK_GETTIME) && (defined(CLOCK_BOOTTIME) || \
1706
630
    defined(CLOCK_MONOTONIC) || defined(CLOCK_REALTIME))
1707
630
  static int gettime_failed = 0;
1708
1709
630
  if (!gettime_failed) {
1710
630
# ifdef CLOCK_BOOTTIME
1711
630
    if (clock_gettime(CLOCK_BOOTTIME, ts) == 0)
1712
630
      return;
1713
0
# endif /* CLOCK_BOOTTIME */
1714
0
# ifdef CLOCK_MONOTONIC
1715
0
    if (clock_gettime(CLOCK_MONOTONIC, ts) == 0)
1716
0
      return;
1717
0
# endif /* CLOCK_MONOTONIC */
1718
0
# ifdef CLOCK_REALTIME
1719
    /* Not monotonic, but we're almost out of options here. */
1720
0
    if (clock_gettime(CLOCK_REALTIME, ts) == 0)
1721
0
      return;
1722
0
# endif /* CLOCK_REALTIME */
1723
0
    debug3("clock_gettime: %s", strerror(errno));
1724
0
    gettime_failed = 1;
1725
0
  }
1726
0
#endif /* HAVE_CLOCK_GETTIME && (BOOTTIME || MONOTONIC || REALTIME) */
1727
0
  gettimeofday(&tv, NULL);
1728
0
  ts->tv_sec = tv.tv_sec;
1729
0
  ts->tv_nsec = (long)tv.tv_usec * 1000;
1730
0
}
1731
1732
void
1733
monotime_tv(struct timeval *tv)
1734
0
{
1735
0
  struct timespec ts;
1736
1737
0
  monotime_ts(&ts);
1738
0
  tv->tv_sec = ts.tv_sec;
1739
0
  tv->tv_usec = ts.tv_nsec / 1000;
1740
0
}
1741
1742
time_t
1743
monotime(void)
1744
630
{
1745
630
  struct timespec ts;
1746
1747
630
  monotime_ts(&ts);
1748
630
  return ts.tv_sec;
1749
630
}
1750
1751
double
1752
monotime_double(void)
1753
0
{
1754
0
  struct timespec ts;
1755
1756
0
  monotime_ts(&ts);
1757
0
  return ts.tv_sec + ((double)ts.tv_nsec / 1000000000);
1758
0
}
1759
1760
void
1761
bandwidth_limit_init(struct bwlimit *bw, u_int64_t kbps, size_t buflen)
1762
0
{
1763
0
  bw->buflen = buflen;
1764
0
  bw->rate = kbps;
1765
0
  bw->thresh = buflen;
1766
0
  bw->lamt = 0;
1767
0
  timerclear(&bw->bwstart);
1768
0
  timerclear(&bw->bwend);
1769
0
}
1770
1771
/* Callback from read/write loop to insert bandwidth-limiting delays */
1772
void
1773
bandwidth_limit(struct bwlimit *bw, size_t read_len)
1774
0
{
1775
0
  u_int64_t waitlen;
1776
0
  struct timespec ts, rm;
1777
1778
0
  bw->lamt += read_len;
1779
0
  if (!timerisset(&bw->bwstart)) {
1780
0
    monotime_tv(&bw->bwstart);
1781
0
    return;
1782
0
  }
1783
0
  if (bw->lamt < bw->thresh)
1784
0
    return;
1785
1786
0
  monotime_tv(&bw->bwend);
1787
0
  timersub(&bw->bwend, &bw->bwstart, &bw->bwend);
1788
0
  if (!timerisset(&bw->bwend))
1789
0
    return;
1790
1791
0
  bw->lamt *= 8;
1792
0
  waitlen = (double)1000000L * bw->lamt / bw->rate;
1793
1794
0
  bw->bwstart.tv_sec = waitlen / 1000000L;
1795
0
  bw->bwstart.tv_usec = waitlen % 1000000L;
1796
1797
0
  if (timercmp(&bw->bwstart, &bw->bwend, >)) {
1798
0
    timersub(&bw->bwstart, &bw->bwend, &bw->bwend);
1799
1800
    /* Adjust the wait time */
1801
0
    if (bw->bwend.tv_sec) {
1802
0
      bw->thresh /= 2;
1803
0
      if (bw->thresh < bw->buflen / 4)
1804
0
        bw->thresh = bw->buflen / 4;
1805
0
    } else if (bw->bwend.tv_usec < 10000) {
1806
0
      bw->thresh *= 2;
1807
0
      if (bw->thresh > bw->buflen * 8)
1808
0
        bw->thresh = bw->buflen * 8;
1809
0
    }
1810
1811
0
    TIMEVAL_TO_TIMESPEC(&bw->bwend, &ts);
1812
0
    while (nanosleep(&ts, &rm) == -1) {
1813
0
      if (errno != EINTR)
1814
0
        break;
1815
0
      ts = rm;
1816
0
    }
1817
0
  }
1818
1819
0
  bw->lamt = 0;
1820
0
  monotime_tv(&bw->bwstart);
1821
0
}
1822
1823
/* Make a template filename for mk[sd]temp() */
1824
void
1825
mktemp_proto(char *s, size_t len)
1826
0
{
1827
0
  const char *tmpdir;
1828
0
  int r;
1829
1830
0
  if ((tmpdir = getenv("TMPDIR")) != NULL) {
1831
0
    r = snprintf(s, len, "%s/ssh-XXXXXXXXXXXX", tmpdir);
1832
0
    if (r > 0 && (size_t)r < len)
1833
0
      return;
1834
0
  }
1835
0
  r = snprintf(s, len, "/tmp/ssh-XXXXXXXXXXXX");
1836
0
  if (r < 0 || (size_t)r >= len)
1837
0
    fatal_f("template string too short");
1838
0
}
1839
1840
static const struct {
1841
  const char *name;
1842
  int value;
1843
} ipqos[] = {
1844
  { "none", INT_MAX },    /* can't use 0 here; that's CS0 */
1845
  { "af11", IPTOS_DSCP_AF11 },
1846
  { "af12", IPTOS_DSCP_AF12 },
1847
  { "af13", IPTOS_DSCP_AF13 },
1848
  { "af21", IPTOS_DSCP_AF21 },
1849
  { "af22", IPTOS_DSCP_AF22 },
1850
  { "af23", IPTOS_DSCP_AF23 },
1851
  { "af31", IPTOS_DSCP_AF31 },
1852
  { "af32", IPTOS_DSCP_AF32 },
1853
  { "af33", IPTOS_DSCP_AF33 },
1854
  { "af41", IPTOS_DSCP_AF41 },
1855
  { "af42", IPTOS_DSCP_AF42 },
1856
  { "af43", IPTOS_DSCP_AF43 },
1857
  { "cs0", IPTOS_DSCP_CS0 },
1858
  { "cs1", IPTOS_DSCP_CS1 },
1859
  { "cs2", IPTOS_DSCP_CS2 },
1860
  { "cs3", IPTOS_DSCP_CS3 },
1861
  { "cs4", IPTOS_DSCP_CS4 },
1862
  { "cs5", IPTOS_DSCP_CS5 },
1863
  { "cs6", IPTOS_DSCP_CS6 },
1864
  { "cs7", IPTOS_DSCP_CS7 },
1865
  { "ef", IPTOS_DSCP_EF },
1866
  { "le", IPTOS_DSCP_LE },
1867
  { "lowdelay", IPTOS_LOWDELAY },
1868
  { "throughput", IPTOS_THROUGHPUT },
1869
  { "reliability", IPTOS_RELIABILITY },
1870
  { NULL, -1 }
1871
};
1872
1873
int
1874
parse_ipqos(const char *cp)
1875
0
{
1876
0
  const char *errstr;
1877
0
  u_int i;
1878
0
  int val;
1879
1880
0
  if (cp == NULL)
1881
0
    return -1;
1882
0
  for (i = 0; ipqos[i].name != NULL; i++) {
1883
0
    if (strcasecmp(cp, ipqos[i].name) == 0)
1884
0
      return ipqos[i].value;
1885
0
  }
1886
  /* Try parsing as an integer */
1887
0
  val = (int)strtonum(cp, 0, 255, &errstr);
1888
0
  if (errstr)
1889
0
    return -1;
1890
0
  return val;
1891
0
}
1892
1893
const char *
1894
iptos2str(int iptos)
1895
0
{
1896
0
  int i;
1897
0
  static char iptos_str[sizeof "0xff"];
1898
1899
0
  for (i = 0; ipqos[i].name != NULL; i++) {
1900
0
    if (ipqos[i].value == iptos)
1901
0
      return ipqos[i].name;
1902
0
  }
1903
0
  snprintf(iptos_str, sizeof iptos_str, "0x%02x", iptos);
1904
0
  return iptos_str;
1905
0
}
1906
1907
void
1908
lowercase(char *s)
1909
0
{
1910
0
  for (; *s; s++)
1911
0
    *s = tolower((u_char)*s);
1912
0
}
1913
1914
int
1915
unix_listener(const char *path, int backlog, int unlink_first)
1916
0
{
1917
0
  struct sockaddr_un sunaddr;
1918
0
  int saved_errno, sock;
1919
1920
0
  memset(&sunaddr, 0, sizeof(sunaddr));
1921
0
  sunaddr.sun_family = AF_UNIX;
1922
0
  if (strlcpy(sunaddr.sun_path, path,
1923
0
      sizeof(sunaddr.sun_path)) >= sizeof(sunaddr.sun_path)) {
1924
0
    error_f("path \"%s\" too long for Unix domain socket", path);
1925
0
    errno = ENAMETOOLONG;
1926
0
    return -1;
1927
0
  }
1928
1929
0
  sock = socket(PF_UNIX, SOCK_STREAM, 0);
1930
0
  if (sock == -1) {
1931
0
    saved_errno = errno;
1932
0
    error_f("socket: %.100s", strerror(errno));
1933
0
    errno = saved_errno;
1934
0
    return -1;
1935
0
  }
1936
0
  if (unlink_first == 1) {
1937
0
    if (unlink(path) != 0 && errno != ENOENT)
1938
0
      error("unlink(%s): %.100s", path, strerror(errno));
1939
0
  }
1940
0
  if (bind(sock, (struct sockaddr *)&sunaddr, sizeof(sunaddr)) == -1) {
1941
0
    saved_errno = errno;
1942
0
    error_f("cannot bind to path %s: %s", path, strerror(errno));
1943
0
    close(sock);
1944
0
    errno = saved_errno;
1945
0
    return -1;
1946
0
  }
1947
0
  if (listen(sock, backlog) == -1) {
1948
0
    saved_errno = errno;
1949
0
    error_f("cannot listen on path %s: %s", path, strerror(errno));
1950
0
    close(sock);
1951
0
    unlink(path);
1952
0
    errno = saved_errno;
1953
0
    return -1;
1954
0
  }
1955
0
  return sock;
1956
0
}
1957
1958
void
1959
sock_set_v6only(int s)
1960
0
{
1961
0
#if defined(IPV6_V6ONLY) && !defined(__OpenBSD__)
1962
0
  int on = 1;
1963
1964
0
  debug3("%s: set socket %d IPV6_V6ONLY", __func__, s);
1965
0
  if (setsockopt(s, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof(on)) == -1)
1966
0
    error("setsockopt IPV6_V6ONLY: %s", strerror(errno));
1967
0
#endif
1968
0
}
1969
1970
/*
1971
 * Compares two strings that maybe be NULL. Returns non-zero if strings
1972
 * are both NULL or are identical, returns zero otherwise.
1973
 */
1974
static int
1975
strcmp_maybe_null(const char *a, const char *b)
1976
0
{
1977
0
  if ((a == NULL && b != NULL) || (a != NULL && b == NULL))
1978
0
    return 0;
1979
0
  if (a != NULL && strcmp(a, b) != 0)
1980
0
    return 0;
1981
0
  return 1;
1982
0
}
1983
1984
/*
1985
 * Compare two forwards, returning non-zero if they are identical or
1986
 * zero otherwise.
1987
 */
1988
int
1989
forward_equals(const struct Forward *a, const struct Forward *b)
1990
0
{
1991
0
  if (strcmp_maybe_null(a->listen_host, b->listen_host) == 0)
1992
0
    return 0;
1993
0
  if (a->listen_port != b->listen_port)
1994
0
    return 0;
1995
0
  if (strcmp_maybe_null(a->listen_path, b->listen_path) == 0)
1996
0
    return 0;
1997
0
  if (strcmp_maybe_null(a->connect_host, b->connect_host) == 0)
1998
0
    return 0;
1999
0
  if (a->connect_port != b->connect_port)
2000
0
    return 0;
2001
0
  if (strcmp_maybe_null(a->connect_path, b->connect_path) == 0)
2002
0
    return 0;
2003
  /* allocated_port and handle are not checked */
2004
0
  return 1;
2005
0
}
2006
2007
/* returns port number, FWD_PERMIT_ANY_PORT or -1 on error */
2008
int
2009
permitopen_port(const char *p)
2010
0
{
2011
0
  int port;
2012
2013
0
  if (strcmp(p, "*") == 0)
2014
0
    return FWD_PERMIT_ANY_PORT;
2015
0
  if ((port = a2port(p)) > 0)
2016
0
    return port;
2017
0
  return -1;
2018
0
}
2019
2020
/* returns 1 if process is already daemonized, 0 otherwise */
2021
int
2022
daemonized(void)
2023
0
{
2024
0
  int fd;
2025
2026
0
  if ((fd = open(_PATH_TTY, O_RDONLY | O_NOCTTY)) >= 0) {
2027
0
    close(fd);
2028
0
    return 0; /* have controlling terminal */
2029
0
  }
2030
0
  if (getppid() != 1)
2031
0
    return 0; /* parent is not init */
2032
0
  if (getsid(0) != getpid())
2033
0
    return 0; /* not session leader */
2034
0
  debug3("already daemonized");
2035
0
  return 1;
2036
0
}
2037
2038
/*
2039
 * Splits 's' into an argument vector. Handles quoted string and basic
2040
 * escape characters (\\, \", \'). Caller must free the argument vector
2041
 * and its members.
2042
 */
2043
int
2044
argv_split(const char *s, int *argcp, char ***argvp, int terminate_on_comment)
2045
0
{
2046
0
  int r = SSH_ERR_INTERNAL_ERROR;
2047
0
  int argc = 0, quote, i, j;
2048
0
  char *arg, **argv = xcalloc(1, sizeof(*argv));
2049
2050
0
  *argvp = NULL;
2051
0
  *argcp = 0;
2052
2053
0
  for (i = 0; s[i] != '\0'; i++) {
2054
    /* Skip leading whitespace */
2055
0
    if (s[i] == ' ' || s[i] == '\t')
2056
0
      continue;
2057
0
    if (terminate_on_comment && s[i] == '#')
2058
0
      break;
2059
    /* Start of a token */
2060
0
    quote = 0;
2061
2062
0
    argv = xreallocarray(argv, (argc + 2), sizeof(*argv));
2063
0
    arg = argv[argc++] = xcalloc(1, strlen(s + i) + 1);
2064
0
    argv[argc] = NULL;
2065
2066
    /* Copy the token in, removing escapes */
2067
0
    for (j = 0; s[i] != '\0'; i++) {
2068
0
      if (s[i] == '\\') {
2069
0
        if (s[i + 1] == '\'' ||
2070
0
            s[i + 1] == '\"' ||
2071
0
            s[i + 1] == '\\' ||
2072
0
            (quote == 0 && s[i + 1] == ' ')) {
2073
0
          i++; /* Skip '\' */
2074
0
          arg[j++] = s[i];
2075
0
        } else {
2076
          /* Unrecognised escape */
2077
0
          arg[j++] = s[i];
2078
0
        }
2079
0
      } else if (quote == 0 && (s[i] == ' ' || s[i] == '\t'))
2080
0
        break; /* done */
2081
0
      else if (quote == 0 && (s[i] == '\"' || s[i] == '\''))
2082
0
        quote = s[i]; /* quote start */
2083
0
      else if (quote != 0 && s[i] == quote)
2084
0
        quote = 0; /* quote end */
2085
0
      else
2086
0
        arg[j++] = s[i];
2087
0
    }
2088
0
    if (s[i] == '\0') {
2089
0
      if (quote != 0) {
2090
        /* Ran out of string looking for close quote */
2091
0
        r = SSH_ERR_INVALID_FORMAT;
2092
0
        goto out;
2093
0
      }
2094
0
      break;
2095
0
    }
2096
0
  }
2097
  /* Success */
2098
0
  *argcp = argc;
2099
0
  *argvp = argv;
2100
0
  argc = 0;
2101
0
  argv = NULL;
2102
0
  r = 0;
2103
0
 out:
2104
0
  if (argc != 0 && argv != NULL) {
2105
0
    for (i = 0; i < argc; i++)
2106
0
      free(argv[i]);
2107
0
    free(argv);
2108
0
  }
2109
0
  return r;
2110
0
}
2111
2112
/*
2113
 * Reassemble an argument vector into a string, quoting and escaping as
2114
 * necessary. Caller must free returned string.
2115
 */
2116
char *
2117
argv_assemble(int argc, char **argv)
2118
0
{
2119
0
  int i, j, ws, r;
2120
0
  char c, *ret;
2121
0
  struct sshbuf *buf, *arg;
2122
2123
0
  if ((buf = sshbuf_new()) == NULL || (arg = sshbuf_new()) == NULL)
2124
0
    fatal_f("sshbuf_new failed");
2125
2126
0
  for (i = 0; i < argc; i++) {
2127
0
    ws = 0;
2128
0
    sshbuf_reset(arg);
2129
0
    for (j = 0; argv[i][j] != '\0'; j++) {
2130
0
      r = 0;
2131
0
      c = argv[i][j];
2132
0
      switch (c) {
2133
0
      case ' ':
2134
0
      case '\t':
2135
0
        ws = 1;
2136
0
        r = sshbuf_put_u8(arg, c);
2137
0
        break;
2138
0
      case '\\':
2139
0
      case '\'':
2140
0
      case '"':
2141
0
        if ((r = sshbuf_put_u8(arg, '\\')) != 0)
2142
0
          break;
2143
        /* FALLTHROUGH */
2144
0
      default:
2145
0
        r = sshbuf_put_u8(arg, c);
2146
0
        break;
2147
0
      }
2148
0
      if (r != 0)
2149
0
        fatal_fr(r, "sshbuf_put_u8");
2150
0
    }
2151
0
    if ((i != 0 && (r = sshbuf_put_u8(buf, ' ')) != 0) ||
2152
0
        (ws != 0 && (r = sshbuf_put_u8(buf, '"')) != 0) ||
2153
0
        (r = sshbuf_putb(buf, arg)) != 0 ||
2154
0
        (ws != 0 && (r = sshbuf_put_u8(buf, '"')) != 0))
2155
0
      fatal_fr(r, "assemble");
2156
0
  }
2157
0
  if ((ret = malloc(sshbuf_len(buf) + 1)) == NULL)
2158
0
    fatal_f("malloc failed");
2159
0
  memcpy(ret, sshbuf_ptr(buf), sshbuf_len(buf));
2160
0
  ret[sshbuf_len(buf)] = '\0';
2161
0
  sshbuf_free(buf);
2162
0
  sshbuf_free(arg);
2163
0
  return ret;
2164
0
}
2165
2166
char *
2167
argv_next(int *argcp, char ***argvp)
2168
0
{
2169
0
  char *ret = (*argvp)[0];
2170
2171
0
  if (*argcp > 0 && ret != NULL) {
2172
0
    (*argcp)--;
2173
0
    (*argvp)++;
2174
0
  }
2175
0
  return ret;
2176
0
}
2177
2178
void
2179
argv_consume(int *argcp)
2180
0
{
2181
0
  *argcp = 0;
2182
0
}
2183
2184
void
2185
argv_free(char **av, int ac)
2186
0
{
2187
0
  int i;
2188
2189
0
  if (av == NULL)
2190
0
    return;
2191
0
  for (i = 0; i < ac; i++)
2192
0
    free(av[i]);
2193
0
  free(av);
2194
0
}
2195
2196
/* Returns 0 if pid exited cleanly, non-zero otherwise */
2197
int
2198
exited_cleanly(pid_t pid, const char *tag, const char *cmd, int quiet)
2199
0
{
2200
0
  int status;
2201
2202
0
  while (waitpid(pid, &status, 0) == -1) {
2203
0
    if (errno != EINTR) {
2204
0
      error("%s waitpid: %s", tag, strerror(errno));
2205
0
      return -1;
2206
0
    }
2207
0
  }
2208
0
  if (WIFSIGNALED(status)) {
2209
0
    error("%s %s exited on signal %d", tag, cmd, WTERMSIG(status));
2210
0
    return -1;
2211
0
  } else if (WEXITSTATUS(status) != 0) {
2212
0
    do_log2(quiet ? SYSLOG_LEVEL_DEBUG1 : SYSLOG_LEVEL_INFO,
2213
0
        "%s %s failed, status %d", tag, cmd, WEXITSTATUS(status));
2214
0
    return -1;
2215
0
  }
2216
0
  return 0;
2217
0
}
2218
2219
/*
2220
 * Check a given path for security. This is defined as all components
2221
 * of the path to the file must be owned by either the owner of
2222
 * of the file or root and no directories must be group or world writable.
2223
 *
2224
 * XXX Should any specific check be done for sym links ?
2225
 *
2226
 * Takes a file name, its stat information (preferably from fstat() to
2227
 * avoid races), the uid of the expected owner, their home directory and an
2228
 * error buffer plus max size as arguments.
2229
 *
2230
 * Returns 0 on success and -1 on failure
2231
 */
2232
int
2233
safe_path(const char *name, struct stat *stp, const char *pw_dir,
2234
    uid_t uid, char *err, size_t errlen)
2235
0
{
2236
0
  char buf[PATH_MAX], homedir[PATH_MAX];
2237
0
  char *cp;
2238
0
  int comparehome = 0;
2239
0
  struct stat st;
2240
2241
0
  if (realpath(name, buf) == NULL) {
2242
0
    snprintf(err, errlen, "realpath %s failed: %s", name,
2243
0
        strerror(errno));
2244
0
    return -1;
2245
0
  }
2246
0
  if (pw_dir != NULL && realpath(pw_dir, homedir) != NULL)
2247
0
    comparehome = 1;
2248
2249
0
  if (!S_ISREG(stp->st_mode)) {
2250
0
    snprintf(err, errlen, "%s is not a regular file", buf);
2251
0
    return -1;
2252
0
  }
2253
0
  if ((!platform_sys_dir_uid(stp->st_uid) && stp->st_uid != uid) ||
2254
0
      (stp->st_mode & 022) != 0) {
2255
0
    snprintf(err, errlen, "bad ownership or modes for file %s",
2256
0
        buf);
2257
0
    return -1;
2258
0
  }
2259
2260
  /* for each component of the canonical path, walking upwards */
2261
0
  for (;;) {
2262
0
    if ((cp = dirname(buf)) == NULL) {
2263
0
      snprintf(err, errlen, "dirname() failed");
2264
0
      return -1;
2265
0
    }
2266
0
    strlcpy(buf, cp, sizeof(buf));
2267
2268
0
    if (stat(buf, &st) == -1 ||
2269
0
        (!platform_sys_dir_uid(st.st_uid) && st.st_uid != uid) ||
2270
0
        (st.st_mode & 022) != 0) {
2271
0
      snprintf(err, errlen,
2272
0
          "bad ownership or modes for directory %s", buf);
2273
0
      return -1;
2274
0
    }
2275
2276
    /* If are past the homedir then we can stop */
2277
0
    if (comparehome && strcmp(homedir, buf) == 0)
2278
0
      break;
2279
2280
    /*
2281
     * dirname should always complete with a "/" path,
2282
     * but we can be paranoid and check for "." too
2283
     */
2284
0
    if ((strcmp("/", buf) == 0) || (strcmp(".", buf) == 0))
2285
0
      break;
2286
0
  }
2287
0
  return 0;
2288
0
}
2289
2290
/*
2291
 * Version of safe_path() that accepts an open file descriptor to
2292
 * avoid races.
2293
 *
2294
 * Returns 0 on success and -1 on failure
2295
 */
2296
int
2297
safe_path_fd(int fd, const char *file, struct passwd *pw,
2298
    char *err, size_t errlen)
2299
0
{
2300
0
  struct stat st;
2301
2302
  /* check the open file to avoid races */
2303
0
  if (fstat(fd, &st) == -1) {
2304
0
    snprintf(err, errlen, "cannot stat file %s: %s",
2305
0
        file, strerror(errno));
2306
0
    return -1;
2307
0
  }
2308
0
  return safe_path(file, &st, pw->pw_dir, pw->pw_uid, err, errlen);
2309
0
}
2310
2311
/*
2312
 * Sets the value of the given variable in the environment.  If the variable
2313
 * already exists, its value is overridden.
2314
 */
2315
void
2316
child_set_env(char ***envp, u_int *envsizep, const char *name,
2317
  const char *value)
2318
0
{
2319
0
  char **env;
2320
0
  u_int envsize;
2321
0
  u_int i, namelen;
2322
2323
0
  if (strchr(name, '=') != NULL) {
2324
0
    error("Invalid environment variable \"%.100s\"", name);
2325
0
    return;
2326
0
  }
2327
2328
  /*
2329
   * If we're passed an uninitialized list, allocate a single null
2330
   * entry before continuing.
2331
   */
2332
0
  if ((*envp == NULL) != (*envsizep == 0))
2333
0
    fatal_f("environment size mismatch");
2334
0
  if (*envp == NULL && *envsizep == 0) {
2335
0
    *envp = xmalloc(sizeof(char *));
2336
0
    *envp[0] = NULL;
2337
0
    *envsizep = 1;
2338
0
  }
2339
2340
  /*
2341
   * Find the slot where the value should be stored.  If the variable
2342
   * already exists, we reuse the slot; otherwise we append a new slot
2343
   * at the end of the array, expanding if necessary.
2344
   */
2345
0
  env = *envp;
2346
0
  namelen = strlen(name);
2347
0
  for (i = 0; env[i]; i++)
2348
0
    if (strncmp(env[i], name, namelen) == 0 && env[i][namelen] == '=')
2349
0
      break;
2350
0
  if (env[i]) {
2351
    /* Reuse the slot. */
2352
0
    free(env[i]);
2353
0
  } else {
2354
    /* New variable.  Expand if necessary. */
2355
0
    envsize = *envsizep;
2356
0
    if (i >= envsize - 1) {
2357
0
      if (envsize >= 1000)
2358
0
        fatal("child_set_env: too many env vars");
2359
0
      envsize += 50;
2360
0
      env = (*envp) = xreallocarray(env, envsize, sizeof(char *));
2361
0
      *envsizep = envsize;
2362
0
    }
2363
    /* Need to set the NULL pointer at end of array beyond the new slot. */
2364
0
    env[i + 1] = NULL;
2365
0
  }
2366
2367
  /* Allocate space and format the variable in the appropriate slot. */
2368
  /* XXX xasprintf */
2369
0
  env[i] = xmalloc(strlen(name) + 1 + strlen(value) + 1);
2370
0
  snprintf(env[i], strlen(name) + 1 + strlen(value) + 1, "%s=%s", name, value);
2371
0
}
2372
2373
/*
2374
 * Check and optionally lowercase a domain name, also removes trailing '.'
2375
 * Returns 1 on success and 0 on failure, storing an error message in errstr.
2376
 */
2377
int
2378
valid_domain(char *name, int makelower, const char **errstr)
2379
0
{
2380
0
  size_t i, l = strlen(name);
2381
0
  u_char c, last = '\0';
2382
0
  static char errbuf[256];
2383
2384
0
  if (l == 0) {
2385
0
    strlcpy(errbuf, "empty domain name", sizeof(errbuf));
2386
0
    goto bad;
2387
0
  }
2388
0
  if (!isalpha((u_char)name[0]) && !isdigit((u_char)name[0])) {
2389
0
    snprintf(errbuf, sizeof(errbuf), "domain name \"%.100s\" "
2390
0
        "starts with invalid character", name);
2391
0
    goto bad;
2392
0
  }
2393
0
  for (i = 0; i < l; i++) {
2394
0
    c = tolower((u_char)name[i]);
2395
0
    if (makelower)
2396
0
      name[i] = (char)c;
2397
0
    if (last == '.' && c == '.') {
2398
0
      snprintf(errbuf, sizeof(errbuf), "domain name "
2399
0
          "\"%.100s\" contains consecutive separators", name);
2400
0
      goto bad;
2401
0
    }
2402
0
    if (c != '.' && c != '-' && !isalnum(c) &&
2403
0
        c != '_') /* technically invalid, but common */ {
2404
0
      snprintf(errbuf, sizeof(errbuf), "domain name "
2405
0
          "\"%.100s\" contains invalid characters", name);
2406
0
      goto bad;
2407
0
    }
2408
0
    last = c;
2409
0
  }
2410
0
  if (name[l - 1] == '.')
2411
0
    name[l - 1] = '\0';
2412
0
  if (errstr != NULL)
2413
0
    *errstr = NULL;
2414
0
  return 1;
2415
0
bad:
2416
0
  if (errstr != NULL)
2417
0
    *errstr = errbuf;
2418
0
  return 0;
2419
0
}
2420
2421
/*
2422
 * Verify that a environment variable name (not including initial '$') is
2423
 * valid; consisting of one or more alphanumeric or underscore characters only.
2424
 * Returns 1 on valid, 0 otherwise.
2425
 */
2426
int
2427
valid_env_name(const char *name)
2428
32.0k
{
2429
32.0k
  const char *cp;
2430
2431
32.0k
  if (name[0] == '\0')
2432
7
    return 0;
2433
66.8k
  for (cp = name; *cp != '\0'; cp++) {
2434
34.7k
    if (!isalnum((u_char)*cp) && *cp != '_')
2435
12
      return 0;
2436
34.7k
  }
2437
32.0k
  return 1;
2438
32.0k
}
2439
2440
const char *
2441
atoi_err(const char *nptr, int *val)
2442
0
{
2443
0
  const char *errstr = NULL;
2444
2445
0
  if (nptr == NULL || *nptr == '\0')
2446
0
    return "missing";
2447
0
  *val = strtonum(nptr, 0, INT_MAX, &errstr);
2448
0
  return errstr;
2449
0
}
2450
2451
int
2452
parse_absolute_time(const char *s, uint64_t *tp)
2453
2.90k
{
2454
2.90k
  struct tm tm;
2455
2.90k
  time_t tt;
2456
2.90k
  char buf[32], *fmt;
2457
2.90k
  const char *cp;
2458
2.90k
  size_t l;
2459
2.90k
  int is_utc = 0;
2460
2461
2.90k
  *tp = 0;
2462
2463
2.90k
  l = strlen(s);
2464
2.90k
  if (l > 1 && strcasecmp(s + l - 1, "Z") == 0) {
2465
552
    is_utc = 1;
2466
552
    l--;
2467
2.35k
  } else if (l > 3 && strcasecmp(s + l - 3, "UTC") == 0) {
2468
197
    is_utc = 1;
2469
197
    l -= 3;
2470
197
  }
2471
  /*
2472
   * POSIX strptime says "The application shall ensure that there
2473
   * is white-space or other non-alphanumeric characters between
2474
   * any two conversion specifications" so arrange things this way.
2475
   */
2476
2.90k
  switch (l) {
2477
2.10k
  case 8: /* YYYYMMDD */
2478
2.10k
    fmt = "%Y-%m-%d";
2479
2.10k
    snprintf(buf, sizeof(buf), "%.4s-%.2s-%.2s", s, s + 4, s + 6);
2480
2.10k
    break;
2481
308
  case 12: /* YYYYMMDDHHMM */
2482
308
    fmt = "%Y-%m-%dT%H:%M";
2483
308
    snprintf(buf, sizeof(buf), "%.4s-%.2s-%.2sT%.2s:%.2s",
2484
308
        s, s + 4, s + 6, s + 8, s + 10);
2485
308
    break;
2486
297
  case 14: /* YYYYMMDDHHMMSS */
2487
297
    fmt = "%Y-%m-%dT%H:%M:%S";
2488
297
    snprintf(buf, sizeof(buf), "%.4s-%.2s-%.2sT%.2s:%.2s:%.2s",
2489
297
        s, s + 4, s + 6, s + 8, s + 10, s + 12);
2490
297
    break;
2491
195
  default:
2492
195
    return SSH_ERR_INVALID_FORMAT;
2493
2.90k
  }
2494
2495
2.71k
  memset(&tm, 0, sizeof(tm));
2496
2.71k
  if ((cp = strptime(buf, fmt, &tm)) == NULL || *cp != '\0')
2497
28
    return SSH_ERR_INVALID_FORMAT;
2498
2.68k
  if (is_utc) {
2499
727
    if ((tt = timegm(&tm)) < 0)
2500
94
      return SSH_ERR_INVALID_FORMAT;
2501
1.95k
  } else {
2502
1.95k
    if ((tt = mktime(&tm)) < 0)
2503
99
      return SSH_ERR_INVALID_FORMAT;
2504
1.95k
  }
2505
  /* success */
2506
2.49k
  *tp = (uint64_t)tt;
2507
2.49k
  return 0;
2508
2.68k
}
2509
2510
void
2511
format_absolute_time(uint64_t t, char *buf, size_t len)
2512
0
{
2513
0
  time_t tt = t > SSH_TIME_T_MAX ? SSH_TIME_T_MAX : t;
2514
0
  struct tm tm;
2515
2516
0
  localtime_r(&tt, &tm);
2517
0
  strftime(buf, len, "%Y-%m-%dT%H:%M:%S", &tm);
2518
0
}
2519
2520
/*
2521
 * Parse a "pattern=interval" clause (e.g. a ChannelTimeout).
2522
 * Returns 0 on success or non-zero on failure.
2523
 * Caller must free *typep.
2524
 */
2525
int
2526
parse_pattern_interval(const char *s, char **typep, int *secsp)
2527
0
{
2528
0
  char *cp, *sdup;
2529
0
  int secs;
2530
2531
0
  if (typep != NULL)
2532
0
    *typep = NULL;
2533
0
  if (secsp != NULL)
2534
0
    *secsp = 0;
2535
0
  if (s == NULL)
2536
0
    return -1;
2537
0
  sdup = xstrdup(s);
2538
2539
0
  if ((cp = strchr(sdup, '=')) == NULL || cp == sdup) {
2540
0
    free(sdup);
2541
0
    return -1;
2542
0
  }
2543
0
  *cp++ = '\0';
2544
0
  if ((secs = convtime(cp)) < 0) {
2545
0
    free(sdup);
2546
0
    return -1;
2547
0
  }
2548
  /* success */
2549
0
  if (typep != NULL)
2550
0
    *typep = xstrdup(sdup);
2551
0
  if (secsp != NULL)
2552
0
    *secsp = secs;
2553
0
  free(sdup);
2554
0
  return 0;
2555
0
}
2556
2557
/* check if path is absolute */
2558
int
2559
path_absolute(const char *path)
2560
0
{
2561
0
  return (*path == '/') ? 1 : 0;
2562
0
}
2563
2564
void
2565
skip_space(char **cpp)
2566
0
{
2567
0
  char *cp;
2568
2569
0
  for (cp = *cpp; *cp == ' ' || *cp == '\t'; cp++)
2570
0
    ;
2571
0
  *cpp = cp;
2572
0
}
2573
2574
/* authorized_key-style options parsing helpers */
2575
2576
/*
2577
 * Match flag 'opt' in *optsp, and if allow_negate is set then also match
2578
 * 'no-opt'. Returns -1 if option not matched, 1 if option matches or 0
2579
 * if negated option matches.
2580
 * If the option or negated option matches, then *optsp is updated to
2581
 * point to the first character after the option.
2582
 */
2583
int
2584
opt_flag(const char *opt, int allow_negate, const char **optsp)
2585
1.13M
{
2586
1.13M
  size_t opt_len = strlen(opt);
2587
1.13M
  const char *opts = *optsp;
2588
1.13M
  int negate = 0;
2589
2590
1.13M
  if (allow_negate && strncasecmp(opts, "no-", 3) == 0) {
2591
227
    opts += 3;
2592
227
    negate = 1;
2593
227
  }
2594
1.13M
  if (strncasecmp(opts, opt, opt_len) == 0) {
2595
1.97k
    *optsp = opts + opt_len;
2596
1.97k
    return negate ? 0 : 1;
2597
1.97k
  }
2598
1.13M
  return -1;
2599
1.13M
}
2600
2601
char *
2602
opt_dequote(const char **sp, const char **errstrp)
2603
124k
{
2604
124k
  const char *s = *sp;
2605
124k
  char *ret;
2606
124k
  size_t i;
2607
2608
124k
  *errstrp = NULL;
2609
124k
  if (*s != '"') {
2610
54
    *errstrp = "missing start quote";
2611
54
    return NULL;
2612
54
  }
2613
124k
  s++;
2614
124k
  if ((ret = malloc(strlen((s)) + 1)) == NULL) {
2615
0
    *errstrp = "memory allocation failed";
2616
0
    return NULL;
2617
0
  }
2618
5.64M
  for (i = 0; *s != '\0' && *s != '"';) {
2619
5.52M
    if (s[0] == '\\' && s[1] == '"')
2620
388
      s++;
2621
5.52M
    ret[i++] = *s++;
2622
5.52M
  }
2623
124k
  if (*s == '\0') {
2624
96
    *errstrp = "missing end quote";
2625
96
    free(ret);
2626
96
    return NULL;
2627
96
  }
2628
124k
  ret[i] = '\0';
2629
124k
  s++;
2630
124k
  *sp = s;
2631
124k
  return ret;
2632
124k
}
2633
2634
int
2635
opt_match(const char **opts, const char *term)
2636
737k
{
2637
737k
  if (strncasecmp((*opts), term, strlen(term)) == 0 &&
2638
737k
      (*opts)[strlen(term)] == '=') {
2639
124k
    *opts += strlen(term) + 1;
2640
124k
    return 1;
2641
124k
  }
2642
612k
  return 0;
2643
737k
}
2644
2645
void
2646
opt_array_append2(const char *file, const int line, const char *directive,
2647
    char ***array, int **iarray, u_int *lp, const char *s, int i)
2648
0
{
2649
2650
0
  if (*lp >= INT_MAX)
2651
0
    fatal("%s line %d: Too many %s entries", file, line, directive);
2652
2653
0
  if (iarray != NULL) {
2654
0
    *iarray = xrecallocarray(*iarray, *lp, *lp + 1,
2655
0
        sizeof(**iarray));
2656
0
    (*iarray)[*lp] = i;
2657
0
  }
2658
2659
0
  *array = xrecallocarray(*array, *lp, *lp + 1, sizeof(**array));
2660
0
  (*array)[*lp] = xstrdup(s);
2661
0
  (*lp)++;
2662
0
}
2663
2664
void
2665
opt_array_append(const char *file, const int line, const char *directive,
2666
    char ***array, u_int *lp, const char *s)
2667
0
{
2668
0
  opt_array_append2(file, line, directive, array, NULL, lp, s, 0);
2669
0
}
2670
2671
void
2672
opt_array_free2(char **array, int **iarray, u_int l)
2673
0
{
2674
0
  u_int i;
2675
2676
0
  if (array == NULL || l == 0)
2677
0
    return;
2678
0
  for (i = 0; i < l; i++)
2679
0
    free(array[i]);
2680
0
  free(array);
2681
0
  free(iarray);
2682
0
}
2683
2684
sshsig_t
2685
ssh_signal(int signum, sshsig_t handler)
2686
0
{
2687
0
  struct sigaction sa, osa;
2688
2689
  /* mask all other signals while in handler */
2690
0
  memset(&sa, 0, sizeof(sa));
2691
0
  sa.sa_handler = handler;
2692
0
  sigfillset(&sa.sa_mask);
2693
0
#if defined(SA_RESTART) && !defined(NO_SA_RESTART)
2694
0
  if (signum != SIGALRM)
2695
0
    sa.sa_flags = SA_RESTART;
2696
0
#endif
2697
0
  if (sigaction(signum, &sa, &osa) == -1) {
2698
0
    debug3("sigaction(%s): %s", strsignal(signum), strerror(errno));
2699
0
    return SIG_ERR;
2700
0
  }
2701
0
  return osa.sa_handler;
2702
0
}
2703
2704
int
2705
stdfd_devnull(int do_stdin, int do_stdout, int do_stderr)
2706
0
{
2707
0
  int devnull, ret = 0;
2708
2709
0
  if ((devnull = open(_PATH_DEVNULL, O_RDWR)) == -1) {
2710
0
    error_f("open %s: %s", _PATH_DEVNULL,
2711
0
        strerror(errno));
2712
0
    return -1;
2713
0
  }
2714
0
  if ((do_stdin && dup2(devnull, STDIN_FILENO) == -1) ||
2715
0
      (do_stdout && dup2(devnull, STDOUT_FILENO) == -1) ||
2716
0
      (do_stderr && dup2(devnull, STDERR_FILENO) == -1)) {
2717
0
    error_f("dup2: %s", strerror(errno));
2718
0
    ret = -1;
2719
0
  }
2720
0
  if (devnull > STDERR_FILENO)
2721
0
    close(devnull);
2722
0
  return ret;
2723
0
}
2724
2725
/*
2726
 * Runs command in a subprocess with a minimal environment.
2727
 * Returns pid on success, 0 on failure.
2728
 * The child stdout and stderr maybe captured, left attached or sent to
2729
 * /dev/null depending on the contents of flags.
2730
 * "tag" is prepended to log messages.
2731
 * NB. "command" is only used for logging; the actual command executed is
2732
 * av[0].
2733
 */
2734
pid_t
2735
subprocess(const char *tag, const char *command,
2736
    int ac, char **av, FILE **child, u_int flags,
2737
    struct passwd *pw, privdrop_fn *drop_privs, privrestore_fn *restore_privs)
2738
0
{
2739
0
  FILE *f = NULL;
2740
0
  struct stat st;
2741
0
  int fd, devnull, p[2], i;
2742
0
  pid_t pid;
2743
0
  char *cp, errmsg[512];
2744
0
  u_int nenv = 0;
2745
0
  char **env = NULL;
2746
2747
  /* If dropping privs, then must specify user and restore function */
2748
0
  if (drop_privs != NULL && (pw == NULL || restore_privs == NULL)) {
2749
0
    error("%s: inconsistent arguments", tag); /* XXX fatal? */
2750
0
    return 0;
2751
0
  }
2752
0
  if (pw == NULL && (pw = getpwuid(getuid())) == NULL) {
2753
0
    error("%s: no user for current uid", tag);
2754
0
    return 0;
2755
0
  }
2756
0
  if (child != NULL)
2757
0
    *child = NULL;
2758
2759
0
  debug3_f("%s command \"%s\" running as %s (flags 0x%x)",
2760
0
      tag, command, pw->pw_name, flags);
2761
2762
  /* Check consistency */
2763
0
  if ((flags & SSH_SUBPROCESS_STDOUT_DISCARD) != 0 &&
2764
0
      (flags & SSH_SUBPROCESS_STDOUT_CAPTURE) != 0) {
2765
0
    error_f("inconsistent flags");
2766
0
    return 0;
2767
0
  }
2768
0
  if (((flags & SSH_SUBPROCESS_STDOUT_CAPTURE) == 0) != (child == NULL)) {
2769
0
    error_f("inconsistent flags/output");
2770
0
    return 0;
2771
0
  }
2772
2773
  /*
2774
   * If executing an explicit binary, then verify the it exists
2775
   * and appears safe-ish to execute
2776
   */
2777
0
  if (!path_absolute(av[0])) {
2778
0
    error("%s path is not absolute", tag);
2779
0
    return 0;
2780
0
  }
2781
0
  if (drop_privs != NULL)
2782
0
    drop_privs(pw);
2783
0
  if (stat(av[0], &st) == -1) {
2784
0
    error("Could not stat %s \"%s\": %s", tag,
2785
0
        av[0], strerror(errno));
2786
0
    goto restore_return;
2787
0
  }
2788
0
  if ((flags & SSH_SUBPROCESS_UNSAFE_PATH) == 0 &&
2789
0
      safe_path(av[0], &st, NULL, 0, errmsg, sizeof(errmsg)) != 0) {
2790
0
    error("Unsafe %s \"%s\": %s", tag, av[0], errmsg);
2791
0
    goto restore_return;
2792
0
  }
2793
  /* Prepare to keep the child's stdout if requested */
2794
0
  if (pipe(p) == -1) {
2795
0
    error("%s: pipe: %s", tag, strerror(errno));
2796
0
 restore_return:
2797
0
    if (restore_privs != NULL)
2798
0
      restore_privs();
2799
0
    return 0;
2800
0
  }
2801
0
  if (restore_privs != NULL)
2802
0
    restore_privs();
2803
2804
0
  switch ((pid = fork())) {
2805
0
  case -1: /* error */
2806
0
    error("%s: fork: %s", tag, strerror(errno));
2807
0
    close(p[0]);
2808
0
    close(p[1]);
2809
0
    return 0;
2810
0
  case 0: /* child */
2811
    /* Prepare a minimal environment for the child. */
2812
0
    if ((flags & SSH_SUBPROCESS_PRESERVE_ENV) == 0) {
2813
0
      nenv = 5;
2814
0
      env = xcalloc(sizeof(*env), nenv);
2815
0
      child_set_env(&env, &nenv, "PATH", _PATH_STDPATH);
2816
0
      child_set_env(&env, &nenv, "USER", pw->pw_name);
2817
0
      child_set_env(&env, &nenv, "LOGNAME", pw->pw_name);
2818
0
      child_set_env(&env, &nenv, "HOME", pw->pw_dir);
2819
0
      if ((cp = getenv("LANG")) != NULL)
2820
0
        child_set_env(&env, &nenv, "LANG", cp);
2821
0
    }
2822
2823
0
    for (i = 1; i < NSIG; i++)
2824
0
      ssh_signal(i, SIG_DFL);
2825
2826
0
    if ((devnull = open(_PATH_DEVNULL, O_RDWR)) == -1) {
2827
0
      error("%s: open %s: %s", tag, _PATH_DEVNULL,
2828
0
          strerror(errno));
2829
0
      _exit(1);
2830
0
    }
2831
0
    if (dup2(devnull, STDIN_FILENO) == -1) {
2832
0
      error("%s: dup2: %s", tag, strerror(errno));
2833
0
      _exit(1);
2834
0
    }
2835
2836
    /* Set up stdout as requested; leave stderr in place for now. */
2837
0
    fd = -1;
2838
0
    if ((flags & SSH_SUBPROCESS_STDOUT_CAPTURE) != 0)
2839
0
      fd = p[1];
2840
0
    else if ((flags & SSH_SUBPROCESS_STDOUT_DISCARD) != 0)
2841
0
      fd = devnull;
2842
0
    if (fd != -1 && dup2(fd, STDOUT_FILENO) == -1) {
2843
0
      error("%s: dup2: %s", tag, strerror(errno));
2844
0
      _exit(1);
2845
0
    }
2846
0
    closefrom(STDERR_FILENO + 1);
2847
2848
0
    if (geteuid() == 0 &&
2849
0
        initgroups(pw->pw_name, pw->pw_gid) == -1) {
2850
0
      error("%s: initgroups(%s, %u): %s", tag,
2851
0
          pw->pw_name, (u_int)pw->pw_gid, strerror(errno));
2852
0
      _exit(1);
2853
0
    }
2854
0
    if (setresgid(pw->pw_gid, pw->pw_gid, pw->pw_gid) == -1) {
2855
0
      error("%s: setresgid %u: %s", tag, (u_int)pw->pw_gid,
2856
0
          strerror(errno));
2857
0
      _exit(1);
2858
0
    }
2859
0
    if (setresuid(pw->pw_uid, pw->pw_uid, pw->pw_uid) == -1) {
2860
0
      error("%s: setresuid %u: %s", tag, (u_int)pw->pw_uid,
2861
0
          strerror(errno));
2862
0
      _exit(1);
2863
0
    }
2864
    /* stdin is pointed to /dev/null at this point */
2865
0
    if ((flags & SSH_SUBPROCESS_STDOUT_DISCARD) != 0 &&
2866
0
        dup2(STDIN_FILENO, STDERR_FILENO) == -1) {
2867
0
      error("%s: dup2: %s", tag, strerror(errno));
2868
0
      _exit(1);
2869
0
    }
2870
0
    if (env != NULL)
2871
0
      execve(av[0], av, env);
2872
0
    else
2873
0
      execv(av[0], av);
2874
0
    error("%s %s \"%s\": %s", tag, env == NULL ? "execv" : "execve",
2875
0
        command, strerror(errno));
2876
0
    _exit(127);
2877
0
  default: /* parent */
2878
0
    break;
2879
0
  }
2880
2881
0
  close(p[1]);
2882
0
  if ((flags & SSH_SUBPROCESS_STDOUT_CAPTURE) == 0)
2883
0
    close(p[0]);
2884
0
  else if ((f = fdopen(p[0], "r")) == NULL) {
2885
0
    error("%s: fdopen: %s", tag, strerror(errno));
2886
0
    close(p[0]);
2887
    /* Don't leave zombie child */
2888
0
    kill(pid, SIGTERM);
2889
0
    while (waitpid(pid, NULL, 0) == -1 && errno == EINTR)
2890
0
      ;
2891
0
    return 0;
2892
0
  }
2893
  /* Success */
2894
0
  debug3_f("%s pid %ld", tag, (long)pid);
2895
0
  if (child != NULL)
2896
0
    *child = f;
2897
0
  return pid;
2898
0
}
2899
2900
const char *
2901
lookup_env_in_list(const char *env, char * const *envs, size_t nenvs)
2902
0
{
2903
0
  size_t i, envlen;
2904
2905
0
  envlen = strlen(env);
2906
0
  for (i = 0; i < nenvs; i++) {
2907
0
    if (strncmp(envs[i], env, envlen) == 0 &&
2908
0
        envs[i][envlen] == '=') {
2909
0
      return envs[i] + envlen + 1;
2910
0
    }
2911
0
  }
2912
0
  return NULL;
2913
0
}
2914
2915
const char *
2916
lookup_setenv_in_list(const char *env, char * const *envs, size_t nenvs)
2917
0
{
2918
0
  char *name, *cp;
2919
0
  const char *ret;
2920
2921
0
  name = xstrdup(env);
2922
0
  if ((cp = strchr(name, '=')) == NULL) {
2923
0
    free(name);
2924
0
    return NULL; /* not env=val */
2925
0
  }
2926
0
  *cp = '\0';
2927
0
  ret = lookup_env_in_list(name, envs, nenvs);
2928
0
  free(name);
2929
0
  return ret;
2930
0
}
2931
2932
/*
2933
 * Helpers for managing poll(2)/ppoll(2) timeouts
2934
 * Will remember the earliest deadline and return it for use in poll/ppoll.
2935
 */
2936
2937
/* Initialise a poll/ppoll timeout with an indefinite deadline */
2938
void
2939
ptimeout_init(struct timespec *pt)
2940
0
{
2941
  /*
2942
   * Deliberately invalid for ppoll(2).
2943
   * Will be converted to NULL in ptimeout_get_tspec() later.
2944
   */
2945
0
  pt->tv_sec = -1;
2946
0
  pt->tv_nsec = 0;
2947
0
}
2948
2949
/* Specify a poll/ppoll deadline of at most 'sec' seconds */
2950
void
2951
ptimeout_deadline_sec(struct timespec *pt, long sec)
2952
0
{
2953
0
  if (pt->tv_sec == -1 || pt->tv_sec >= sec) {
2954
0
    pt->tv_sec = sec;
2955
0
    pt->tv_nsec = 0;
2956
0
  }
2957
0
}
2958
2959
/* Specify a poll/ppoll deadline of at most 'p' (timespec) */
2960
static void
2961
ptimeout_deadline_tsp(struct timespec *pt, struct timespec *p)
2962
0
{
2963
0
  if (pt->tv_sec == -1 || timespeccmp(pt, p, >=))
2964
0
    *pt = *p;
2965
0
}
2966
2967
/* Specify a poll/ppoll deadline of at most 'ms' milliseconds */
2968
void
2969
ptimeout_deadline_ms(struct timespec *pt, long ms)
2970
0
{
2971
0
  struct timespec p;
2972
2973
0
  p.tv_sec = ms / 1000;
2974
0
  p.tv_nsec = (ms % 1000) * 1000000;
2975
0
  ptimeout_deadline_tsp(pt, &p);
2976
0
}
2977
2978
/* Specify a poll/ppoll deadline at wall clock monotime 'when' (timespec) */
2979
void
2980
ptimeout_deadline_monotime_tsp(struct timespec *pt, struct timespec *when)
2981
0
{
2982
0
  struct timespec now, t;
2983
2984
0
  monotime_ts(&now);
2985
2986
0
  if (timespeccmp(&now, when, >=)) {
2987
    /* 'when' is now or in the past. Timeout ASAP */
2988
0
    pt->tv_sec = 0;
2989
0
    pt->tv_nsec = 0;
2990
0
  } else {
2991
0
    timespecsub(when, &now, &t);
2992
0
    ptimeout_deadline_tsp(pt, &t);
2993
0
  }
2994
0
}
2995
2996
/* Specify a poll/ppoll deadline at wall clock monotime 'when' */
2997
void
2998
ptimeout_deadline_monotime(struct timespec *pt, time_t when)
2999
0
{
3000
0
  struct timespec t;
3001
3002
0
  t.tv_sec = when;
3003
0
  t.tv_nsec = 0;
3004
0
  ptimeout_deadline_monotime_tsp(pt, &t);
3005
0
}
3006
3007
/* Get a poll(2) timeout value in milliseconds */
3008
int
3009
ptimeout_get_ms(struct timespec *pt)
3010
0
{
3011
0
  if (pt->tv_sec == -1)
3012
0
    return -1;
3013
0
  if (pt->tv_sec >= (INT_MAX - (pt->tv_nsec / 1000000)) / 1000)
3014
0
    return INT_MAX;
3015
0
  return (pt->tv_sec * 1000) + (pt->tv_nsec / 1000000);
3016
0
}
3017
3018
/* Get a ppoll(2) timeout value as a timespec pointer */
3019
struct timespec *
3020
ptimeout_get_tsp(struct timespec *pt)
3021
0
{
3022
0
  return pt->tv_sec == -1 ? NULL : pt;
3023
0
}
3024
3025
/* Returns non-zero if a timeout has been set (i.e. is not indefinite) */
3026
int
3027
ptimeout_isset(struct timespec *pt)
3028
0
{
3029
0
  return pt->tv_sec != -1;
3030
0
}
3031
3032
/*
3033
 * Returns zero if the library at 'path' contains symbol 's', nonzero
3034
 * otherwise.
3035
 */
3036
int
3037
lib_contains_symbol(const char *path, const char *s)
3038
0
{
3039
#ifdef HAVE_NLIST_H
3040
  struct nlist nl[2];
3041
  int ret = -1, r;
3042
3043
  memset(nl, 0, sizeof(nl));
3044
  nl[0].n_name = xstrdup(s);
3045
  nl[1].n_name = NULL;
3046
  if ((r = nlist(path, nl)) == -1) {
3047
    error_f("nlist failed for %s", path);
3048
    goto out;
3049
  }
3050
  if (r != 0 || nl[0].n_value == 0 || nl[0].n_type == 0) {
3051
    error_f("library %s does not contain symbol %s", path, s);
3052
    goto out;
3053
  }
3054
  /* success */
3055
  ret = 0;
3056
 out:
3057
  free(nl[0].n_name);
3058
  return ret;
3059
#else /* HAVE_NLIST_H */
3060
0
  int fd, ret = -1;
3061
0
  struct stat st;
3062
0
  void *m = NULL;
3063
0
  size_t sz = 0;
3064
3065
0
  memset(&st, 0, sizeof(st));
3066
0
  if ((fd = open(path, O_RDONLY)) < 0) {
3067
0
    error_f("open %s: %s", path, strerror(errno));
3068
0
    return -1;
3069
0
  }
3070
0
  if (fstat(fd, &st) != 0) {
3071
0
    error_f("fstat %s: %s", path, strerror(errno));
3072
0
    goto out;
3073
0
  }
3074
0
  if (!S_ISREG(st.st_mode)) {
3075
0
    error_f("%s is not a regular file", path);
3076
0
    goto out;
3077
0
  }
3078
0
  if (st.st_size < 0 ||
3079
0
      (size_t)st.st_size < strlen(s) ||
3080
0
      st.st_size >= INT_MAX/2) {
3081
0
    error_f("%s bad size %lld", path, (long long)st.st_size);
3082
0
    goto out;
3083
0
  }
3084
0
  sz = (size_t)st.st_size;
3085
0
  if ((m = mmap(NULL, sz, PROT_READ, MAP_PRIVATE, fd, 0)) == MAP_FAILED ||
3086
0
      m == NULL) {
3087
0
    error_f("mmap %s: %s", path, strerror(errno));
3088
0
    goto out;
3089
0
  }
3090
0
  if (memmem(m, sz, s, strlen(s)) == NULL) {
3091
0
    error_f("%s does not contain expected string %s", path, s);
3092
0
    goto out;
3093
0
  }
3094
  /* success */
3095
0
  ret = 0;
3096
0
 out:
3097
0
  if (m != NULL && m != MAP_FAILED)
3098
0
    munmap(m, sz);
3099
0
  close(fd);
3100
0
  return ret;
3101
0
#endif /* HAVE_NLIST_H */
3102
0
}
3103
3104
int
3105
signal_is_crash(int sig)
3106
0
{
3107
0
  switch (sig) {
3108
0
  case SIGSEGV:
3109
0
  case SIGBUS:
3110
0
  case SIGTRAP:
3111
0
  case SIGSYS:
3112
0
  case SIGFPE:
3113
0
  case SIGILL:
3114
0
  case SIGABRT:
3115
0
    return 1;
3116
0
  }
3117
0
  return 0;
3118
0
}