Coverage Report

Created: 2025-11-01 06:05

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