Coverage Report

Created: 2025-08-29 06:46

/src/openssh/ssh-agent.c
Line
Count
Source (jump to first uncovered line)
1
/* $OpenBSD: ssh-agent.c,v 1.313 2025/08/29 03:50:38 djm Exp $ */
2
/*
3
 * Author: Tatu Ylonen <ylo@cs.hut.fi>
4
 * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
5
 *                    All rights reserved
6
 * The authentication agent program.
7
 *
8
 * As far as I am concerned, the code I have written for this software
9
 * can be used freely for any purpose.  Any derived versions of this
10
 * software must be clearly marked as such, and if the derived work is
11
 * incompatible with the protocol description in the RFC file, it must be
12
 * called by a name other than "ssh" or "Secure Shell".
13
 *
14
 * Copyright (c) 2000, 2001 Markus Friedl.  All rights reserved.
15
 *
16
 * Redistribution and use in source and binary forms, with or without
17
 * modification, are permitted provided that the following conditions
18
 * are met:
19
 * 1. Redistributions of source code must retain the above copyright
20
 *    notice, this list of conditions and the following disclaimer.
21
 * 2. Redistributions in binary form must reproduce the above copyright
22
 *    notice, this list of conditions and the following disclaimer in the
23
 *    documentation and/or other materials provided with the distribution.
24
 *
25
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
26
 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
27
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
28
 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
29
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
30
 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
31
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
32
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
33
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
34
 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
35
 */
36
37
#include "includes.h"
38
39
#include <sys/types.h>
40
#include <sys/resource.h>
41
#include <sys/stat.h>
42
#include <sys/socket.h>
43
#include <sys/wait.h>
44
#ifdef HAVE_SYS_TIME_H
45
# include <sys/time.h>
46
#endif
47
#ifdef HAVE_SYS_UN_H
48
# include <sys/un.h>
49
#endif
50
#include "openbsd-compat/sys-queue.h"
51
52
#ifdef WITH_OPENSSL
53
#include <openssl/evp.h>
54
#include "openbsd-compat/openssl-compat.h"
55
#endif
56
57
#include <errno.h>
58
#include <fcntl.h>
59
#include <limits.h>
60
#ifdef HAVE_PATHS_H
61
# include <paths.h>
62
#endif
63
#ifdef HAVE_POLL_H
64
# include <poll.h>
65
#endif
66
#include <signal.h>
67
#include <stdarg.h>
68
#include <stdio.h>
69
#include <stdlib.h>
70
#include <time.h>
71
#include <string.h>
72
#include <unistd.h>
73
#ifdef HAVE_UTIL_H
74
# include <util.h>
75
#endif
76
77
#include "xmalloc.h"
78
#include "ssh.h"
79
#include "ssh2.h"
80
#include "sshbuf.h"
81
#include "sshkey.h"
82
#include "authfd.h"
83
#include "log.h"
84
#include "misc.h"
85
#include "digest.h"
86
#include "ssherr.h"
87
#include "match.h"
88
#include "msg.h"
89
#include "pathnames.h"
90
#include "ssh-pkcs11.h"
91
#include "sk-api.h"
92
#include "myproposal.h"
93
94
#ifndef DEFAULT_ALLOWED_PROVIDERS
95
0
# define DEFAULT_ALLOWED_PROVIDERS "/usr/lib*/*,/usr/local/lib*/*"
96
#endif
97
#ifndef DEFAULT_WEBSAFE_ALLOWLIST
98
0
# define DEFAULT_WEBSAFE_ALLOWLIST "ssh:*"
99
#endif
100
101
/* Maximum accepted message length */
102
36.4k
#define AGENT_MAX_LEN   (256*1024)
103
/* Maximum bytes to read from client socket */
104
0
#define AGENT_RBUF_LEN    (4096)
105
/* Maximum number of recorded session IDs/hostkeys per connection */
106
0
#define AGENT_MAX_SESSION_IDS   16
107
/* Maximum size of session ID */
108
0
#define AGENT_MAX_SID_LEN   128
109
/* Maximum number of destination constraints to accept on a key */
110
0
#define AGENT_MAX_DEST_CONSTRAINTS  1024
111
/* Maximum number of associated certificate constraints to accept on a key */
112
0
#define AGENT_MAX_EXT_CERTS   1024
113
114
/* XXX store hostkey_sid in a refcounted tree */
115
116
typedef enum {
117
  AUTH_UNUSED = 0,
118
  AUTH_SOCKET = 1,
119
  AUTH_CONNECTION = 2,
120
} sock_type;
121
122
struct hostkey_sid {
123
  struct sshkey *key;
124
  struct sshbuf *sid;
125
  int forwarded;
126
};
127
128
typedef struct socket_entry {
129
  int fd;
130
  sock_type type;
131
  struct sshbuf *input;
132
  struct sshbuf *output;
133
  struct sshbuf *request;
134
  size_t nsession_ids;
135
  struct hostkey_sid *session_ids;
136
  int session_bind_attempted;
137
} SocketEntry;
138
139
u_int sockets_alloc = 0;
140
SocketEntry *sockets = NULL;
141
142
typedef struct identity {
143
  TAILQ_ENTRY(identity) next;
144
  struct sshkey *key;
145
  char *comment;
146
  char *provider;
147
  time_t death;
148
  u_int confirm;
149
  char *sk_provider;
150
  struct dest_constraint *dest_constraints;
151
  size_t ndest_constraints;
152
} Identity;
153
154
struct idtable {
155
  int nentries;
156
  TAILQ_HEAD(idqueue, identity) idlist;
157
};
158
159
/* private key table */
160
struct idtable *idtab;
161
162
int max_fd = 0;
163
164
/* pid of shell == parent of agent */
165
pid_t parent_pid = -1;
166
time_t parent_alive_interval = 0;
167
168
static sig_atomic_t signalled_exit;
169
static sig_atomic_t signalled_keydrop;
170
171
/* pid of process for which cleanup_socket is applicable */
172
pid_t cleanup_pid = 0;
173
174
/* pathname and directory for AUTH_SOCKET */
175
char socket_name[PATH_MAX];
176
char socket_dir[PATH_MAX];
177
178
/* Pattern-list of allowed PKCS#11/Security key paths */
179
static char *allowed_providers;
180
181
/*
182
 * Allows PKCS11 providers or SK keys that use non-internal providers to
183
 * be added over a remote connection (identified by session-bind@openssh.com).
184
 */
185
static int remote_add_provider;
186
187
/* locking */
188
3.11k
#define LOCK_SIZE 32
189
#define LOCK_SALT_SIZE  16
190
3.11k
#define LOCK_ROUNDS 1
191
int locked = 0;
192
u_char lock_pwhash[LOCK_SIZE];
193
u_char lock_salt[LOCK_SALT_SIZE];
194
195
extern char *__progname;
196
197
/* Default lifetime in seconds (0 == forever) */
198
static int lifetime = 0;
199
200
static int fingerprint_hash = SSH_FP_HASH_DEFAULT;
201
202
/* Refuse signing of non-SSH messages for web-origin FIDO keys */
203
static int restrict_websafe = 1;
204
static char *websafe_allowlist;
205
206
static void
207
close_socket(SocketEntry *e)
208
664
{
209
664
  size_t i;
210
211
664
  close(e->fd);
212
664
  sshbuf_free(e->input);
213
664
  sshbuf_free(e->output);
214
664
  sshbuf_free(e->request);
215
664
  for (i = 0; i < e->nsession_ids; i++) {
216
0
    sshkey_free(e->session_ids[i].key);
217
0
    sshbuf_free(e->session_ids[i].sid);
218
0
  }
219
664
  free(e->session_ids);
220
664
  memset(e, '\0', sizeof(*e));
221
664
  e->fd = -1;
222
664
  e->type = AUTH_UNUSED;
223
664
}
224
225
static void
226
idtab_init(void)
227
664
{
228
664
  idtab = xcalloc(1, sizeof(*idtab));
229
664
  TAILQ_INIT(&idtab->idlist);
230
664
  idtab->nentries = 0;
231
664
}
232
233
static void
234
free_dest_constraint_hop(struct dest_constraint_hop *dch)
235
0
{
236
0
  u_int i;
237
238
0
  if (dch == NULL)
239
0
    return;
240
0
  free(dch->user);
241
0
  free(dch->hostname);
242
0
  for (i = 0; i < dch->nkeys; i++)
243
0
    sshkey_free(dch->keys[i]);
244
0
  free(dch->keys);
245
0
  free(dch->key_is_ca);
246
0
}
247
248
static void
249
free_dest_constraints(struct dest_constraint *dcs, size_t ndcs)
250
6.66k
{
251
6.66k
  size_t i;
252
253
6.66k
  for (i = 0; i < ndcs; i++) {
254
0
    free_dest_constraint_hop(&dcs[i].from);
255
0
    free_dest_constraint_hop(&dcs[i].to);
256
0
  }
257
6.66k
  free(dcs);
258
6.66k
}
259
260
#ifdef ENABLE_PKCS11
261
static void
262
dup_dest_constraint_hop(const struct dest_constraint_hop *dch,
263
    struct dest_constraint_hop *out)
264
0
{
265
0
  u_int i;
266
0
  int r;
267
268
0
  out->user = dch->user == NULL ? NULL : xstrdup(dch->user);
269
0
  out->hostname = dch->hostname == NULL ? NULL : xstrdup(dch->hostname);
270
0
  out->is_ca = dch->is_ca;
271
0
  out->nkeys = dch->nkeys;
272
0
  out->keys = out->nkeys == 0 ? NULL :
273
0
      xcalloc(out->nkeys, sizeof(*out->keys));
274
0
  out->key_is_ca = out->nkeys == 0 ? NULL :
275
0
      xcalloc(out->nkeys, sizeof(*out->key_is_ca));
276
0
  for (i = 0; i < dch->nkeys; i++) {
277
0
    if (dch->keys[i] != NULL &&
278
0
        (r = sshkey_from_private(dch->keys[i],
279
0
        &(out->keys[i]))) != 0)
280
0
      fatal_fr(r, "copy key");
281
0
    out->key_is_ca[i] = dch->key_is_ca[i];
282
0
  }
283
0
}
284
285
static struct dest_constraint *
286
dup_dest_constraints(const struct dest_constraint *dcs, size_t ndcs)
287
0
{
288
0
  size_t i;
289
0
  struct dest_constraint *ret;
290
291
0
  if (ndcs == 0)
292
0
    return NULL;
293
0
  ret = xcalloc(ndcs, sizeof(*ret));
294
0
  for (i = 0; i < ndcs; i++) {
295
0
    dup_dest_constraint_hop(&dcs[i].from, &ret[i].from);
296
0
    dup_dest_constraint_hop(&dcs[i].to, &ret[i].to);
297
0
  }
298
0
  return ret;
299
0
}
300
#endif /* ENABLE_PKCS11 */
301
302
#ifdef DEBUG_CONSTRAINTS
303
static void
304
dump_dest_constraint_hop(const struct dest_constraint_hop *dch)
305
{
306
  u_int i;
307
  char *fp;
308
309
  debug_f("user %s hostname %s is_ca %d nkeys %u",
310
      dch->user == NULL ? "(null)" : dch->user,
311
      dch->hostname == NULL ? "(null)" : dch->hostname,
312
      dch->is_ca, dch->nkeys);
313
  for (i = 0; i < dch->nkeys; i++) {
314
    fp = NULL;
315
    if (dch->keys[i] != NULL &&
316
        (fp = sshkey_fingerprint(dch->keys[i],
317
        SSH_FP_HASH_DEFAULT, SSH_FP_DEFAULT)) == NULL)
318
      fatal_f("fingerprint failed");
319
    debug_f("key %u/%u: %s%s%s key_is_ca %d", i, dch->nkeys,
320
        dch->keys[i] == NULL ? "" : sshkey_ssh_name(dch->keys[i]),
321
        dch->keys[i] == NULL ? "" : " ",
322
        dch->keys[i] == NULL ? "none" : fp,
323
        dch->key_is_ca[i]);
324
    free(fp);
325
  }
326
}
327
#endif /* DEBUG_CONSTRAINTS */
328
329
static void
330
dump_dest_constraints(const char *context,
331
    const struct dest_constraint *dcs, size_t ndcs)
332
40
{
333
#ifdef DEBUG_CONSTRAINTS
334
  size_t i;
335
336
  debug_f("%s: %zu constraints", context, ndcs);
337
  for (i = 0; i < ndcs; i++) {
338
    debug_f("constraint %zu / %zu: from: ", i, ndcs);
339
    dump_dest_constraint_hop(&dcs[i].from);
340
    debug_f("constraint %zu / %zu: to: ", i, ndcs);
341
    dump_dest_constraint_hop(&dcs[i].to);
342
  }
343
  debug_f("done for %s", context);
344
#endif /* DEBUG_CONSTRAINTS */
345
40
}
346
347
static void
348
free_identity(Identity *id)
349
6.64k
{
350
6.64k
  sshkey_free(id->key);
351
6.64k
  free(id->provider);
352
6.64k
  free(id->comment);
353
6.64k
  free(id->sk_provider);
354
6.64k
  free_dest_constraints(id->dest_constraints, id->ndest_constraints);
355
6.64k
  free(id);
356
6.64k
}
357
358
/*
359
 * Match 'key' against the key/CA list in a destination constraint hop
360
 * Returns 0 on success or -1 otherwise.
361
 */
362
static int
363
match_key_hop(const char *tag, const struct sshkey *key,
364
    const struct dest_constraint_hop *dch)
365
0
{
366
0
  const char *reason = NULL;
367
0
  const char *hostname = dch->hostname ? dch->hostname : "(ORIGIN)";
368
0
  u_int i;
369
0
  char *fp;
370
371
0
  if (key == NULL)
372
0
    return -1;
373
  /* XXX logspam */
374
0
  if ((fp = sshkey_fingerprint(key, SSH_FP_HASH_DEFAULT,
375
0
      SSH_FP_DEFAULT)) == NULL)
376
0
    fatal_f("fingerprint failed");
377
0
  debug3_f("%s: entering hostname %s, requested key %s %s, %u keys avail",
378
0
      tag, hostname, sshkey_type(key), fp, dch->nkeys);
379
0
  free(fp);
380
0
  for (i = 0; i < dch->nkeys; i++) {
381
0
    if (dch->keys[i] == NULL)
382
0
      return -1;
383
    /* XXX logspam */
384
0
    if ((fp = sshkey_fingerprint(dch->keys[i], SSH_FP_HASH_DEFAULT,
385
0
        SSH_FP_DEFAULT)) == NULL)
386
0
      fatal_f("fingerprint failed");
387
0
    debug3_f("%s: key %u: %s%s %s", tag, i,
388
0
        dch->key_is_ca[i] ? "CA " : "",
389
0
        sshkey_type(dch->keys[i]), fp);
390
0
    free(fp);
391
0
    if (!sshkey_is_cert(key)) {
392
      /* plain key */
393
0
      if (dch->key_is_ca[i] ||
394
0
          !sshkey_equal(key, dch->keys[i]))
395
0
        continue;
396
0
      return 0;
397
0
    }
398
    /* certificate */
399
0
    if (!dch->key_is_ca[i])
400
0
      continue;
401
0
    if (key->cert == NULL || key->cert->signature_key == NULL)
402
0
      return -1; /* shouldn't happen */
403
0
    if (!sshkey_equal(key->cert->signature_key, dch->keys[i]))
404
0
      continue;
405
0
    if (sshkey_cert_check_host(key, hostname, 1,
406
0
        SSH_ALLOWED_CA_SIGALGS, &reason) != 0) {
407
0
      debug_f("cert %s / hostname %s rejected: %s",
408
0
          key->cert->key_id, hostname, reason);
409
0
      continue;
410
0
    }
411
0
    return 0;
412
0
  }
413
0
  return -1;
414
0
}
415
416
/* Check destination constraints on an identity against the hostkey/user */
417
static int
418
permitted_by_dest_constraints(const struct sshkey *fromkey,
419
    const struct sshkey *tokey, Identity *id, const char *user,
420
    const char **hostnamep)
421
0
{
422
0
  size_t i;
423
0
  struct dest_constraint *d;
424
425
0
  if (hostnamep != NULL)
426
0
    *hostnamep = NULL;
427
0
  for (i = 0; i < id->ndest_constraints; i++) {
428
0
    d = id->dest_constraints + i;
429
    /* XXX remove logspam */
430
0
    debug2_f("constraint %zu %s%s%s (%u keys) > %s%s%s (%u keys)",
431
0
        i, d->from.user ? d->from.user : "",
432
0
        d->from.user ? "@" : "",
433
0
        d->from.hostname ? d->from.hostname : "(ORIGIN)",
434
0
        d->from.nkeys,
435
0
        d->to.user ? d->to.user : "", d->to.user ? "@" : "",
436
0
        d->to.hostname ? d->to.hostname : "(ANY)", d->to.nkeys);
437
438
    /* Match 'from' key */
439
0
    if (fromkey == NULL) {
440
      /* We are matching the first hop */
441
0
      if (d->from.hostname != NULL || d->from.nkeys != 0)
442
0
        continue;
443
0
    } else if (match_key_hop("from", fromkey, &d->from) != 0)
444
0
      continue;
445
446
    /* Match 'to' key */
447
0
    if (tokey != NULL && match_key_hop("to", tokey, &d->to) != 0)
448
0
      continue;
449
450
    /* Match user if specified */
451
0
    if (d->to.user != NULL && user != NULL &&
452
0
        !match_pattern(user, d->to.user))
453
0
      continue;
454
455
    /* successfully matched this constraint */
456
0
    if (hostnamep != NULL)
457
0
      *hostnamep = d->to.hostname;
458
0
    debug2_f("allowed for hostname %s",
459
0
        d->to.hostname == NULL ? "*" : d->to.hostname);
460
0
    return 0;
461
0
  }
462
  /* no match */
463
0
  debug2_f("%s identity \"%s\" not permitted for this destination",
464
0
      sshkey_type(id->key), id->comment);
465
0
  return -1;
466
0
}
467
468
/*
469
 * Check whether hostkeys on a SocketEntry and the optionally specified user
470
 * are permitted by the destination constraints on the Identity.
471
 * Returns 0 on success or -1 otherwise.
472
 */
473
static int
474
identity_permitted(Identity *id, SocketEntry *e, char *user,
475
    const char **forward_hostnamep, const char **last_hostnamep)
476
40
{
477
40
  size_t i;
478
40
  const char **hp;
479
40
  struct hostkey_sid *hks;
480
40
  const struct sshkey *fromkey = NULL;
481
40
  const char *test_user;
482
40
  char *fp1, *fp2;
483
484
  /* XXX remove logspam */
485
40
  debug3_f("entering: key %s comment \"%s\", %zu socket bindings, "
486
40
      "%zu constraints", sshkey_type(id->key), id->comment,
487
40
      e->nsession_ids, id->ndest_constraints);
488
40
  if (id->ndest_constraints == 0)
489
40
    return 0; /* unconstrained */
490
0
  if (e->session_bind_attempted && e->nsession_ids == 0) {
491
0
    error_f("previous session bind failed on socket");
492
0
    return -1;
493
0
  }
494
0
  if (e->nsession_ids == 0)
495
0
    return 0; /* local use */
496
  /*
497
   * Walk through the hops recorded by session_id and try to find a
498
   * constraint that satisfies each.
499
   */
500
0
  for (i = 0; i < e->nsession_ids; i++) {
501
0
    hks = e->session_ids + i;
502
0
    if (hks->key == NULL)
503
0
      fatal_f("internal error: no bound key");
504
    /* XXX remove logspam */
505
0
    fp1 = fp2 = NULL;
506
0
    if (fromkey != NULL &&
507
0
        (fp1 = sshkey_fingerprint(fromkey, SSH_FP_HASH_DEFAULT,
508
0
        SSH_FP_DEFAULT)) == NULL)
509
0
      fatal_f("fingerprint failed");
510
0
    if ((fp2 = sshkey_fingerprint(hks->key, SSH_FP_HASH_DEFAULT,
511
0
        SSH_FP_DEFAULT)) == NULL)
512
0
      fatal_f("fingerprint failed");
513
0
    debug3_f("socketentry fd=%d, entry %zu %s, "
514
0
        "from hostkey %s %s to user %s hostkey %s %s",
515
0
        e->fd, i, hks->forwarded ? "FORWARD" : "AUTH",
516
0
        fromkey ? sshkey_type(fromkey) : "(ORIGIN)",
517
0
        fromkey ? fp1 : "", user ? user : "(ANY)",
518
0
        sshkey_type(hks->key), fp2);
519
0
    free(fp1);
520
0
    free(fp2);
521
    /*
522
     * Record the hostnames for the initial forwarding and
523
     * the final destination.
524
     */
525
0
    hp = NULL;
526
0
    if (i == e->nsession_ids - 1)
527
0
      hp = last_hostnamep;
528
0
    else if (i == 0)
529
0
      hp = forward_hostnamep;
530
    /* Special handling for final recorded binding */
531
0
    test_user = NULL;
532
0
    if (i == e->nsession_ids - 1) {
533
      /* Can only check user at final hop */
534
0
      test_user = user;
535
      /*
536
       * user is only presented for signature requests.
537
       * If this is the case, make sure last binding is not
538
       * for a forwarding.
539
       */
540
0
      if (hks->forwarded && user != NULL) {
541
0
        error_f("tried to sign on forwarding hop");
542
0
        return -1;
543
0
      }
544
0
    } else if (!hks->forwarded) {
545
0
      error_f("tried to forward though signing bind");
546
0
      return -1;
547
0
    }
548
0
    if (permitted_by_dest_constraints(fromkey, hks->key, id,
549
0
        test_user, hp) != 0)
550
0
      return -1;
551
0
    fromkey = hks->key;
552
0
  }
553
  /*
554
   * Another special case: if the last bound session ID was for a
555
   * forwarding, and this function is not being called to check a sign
556
   * request (i.e. no 'user' supplied), then only permit the key if
557
   * there is a permission that would allow it to be used at another
558
   * destination. This hides keys that are allowed to be used to
559
   * authenticate *to* a host but not permitted for *use* beyond it.
560
   */
561
0
  hks = &e->session_ids[e->nsession_ids - 1];
562
0
  if (hks->forwarded && user == NULL &&
563
0
      permitted_by_dest_constraints(hks->key, NULL, id,
564
0
      NULL, NULL) != 0) {
565
0
    debug3_f("key permitted at host but not after");
566
0
    return -1;
567
0
  }
568
569
  /* success */
570
0
  return 0;
571
0
}
572
573
static int
574
socket_is_remote(SocketEntry *e)
575
0
{
576
0
  return e->session_bind_attempted || (e->nsession_ids != 0);
577
0
}
578
579
/* return matching private key for given public key */
580
static Identity *
581
lookup_identity(struct sshkey *key)
582
0
{
583
0
  Identity *id;
584
585
0
  TAILQ_FOREACH(id, &idtab->idlist, next) {
586
0
    if (sshkey_equal(key, id->key))
587
0
      return (id);
588
0
  }
589
0
  return (NULL);
590
0
}
591
592
/* Check confirmation of keysign request */
593
static int
594
confirm_key(Identity *id, const char *extra)
595
0
{
596
0
  char *p;
597
0
  int ret = -1;
598
599
0
  p = sshkey_fingerprint(id->key, fingerprint_hash, SSH_FP_DEFAULT);
600
0
  if (p != NULL &&
601
0
      ask_permission("Allow use of key %s?\nKey fingerprint %s.%s%s",
602
0
      id->comment, p,
603
0
      extra == NULL ? "" : "\n", extra == NULL ? "" : extra))
604
0
    ret = 0;
605
0
  free(p);
606
607
0
  return (ret);
608
0
}
609
610
static void
611
send_status(SocketEntry *e, int success)
612
11.7k
{
613
11.7k
  int r;
614
615
11.7k
  if ((r = sshbuf_put_u32(e->output, 1)) != 0 ||
616
11.7k
      (r = sshbuf_put_u8(e->output, success ?
617
11.7k
      SSH_AGENT_SUCCESS : SSH_AGENT_FAILURE)) != 0)
618
0
    fatal_fr(r, "compose");
619
11.7k
}
620
621
/* send list of supported public keys to 'client' */
622
static void
623
process_request_identities(SocketEntry *e)
624
4
{
625
4
  Identity *id;
626
4
  struct sshbuf *msg, *keys;
627
4
  int r;
628
4
  u_int i = 0, nentries = 0;
629
4
  char *fp;
630
631
4
  debug2_f("entering");
632
633
4
  if ((msg = sshbuf_new()) == NULL || (keys = sshbuf_new()) == NULL)
634
0
    fatal_f("sshbuf_new failed");
635
40
  TAILQ_FOREACH(id, &idtab->idlist, next) {
636
40
    if ((fp = sshkey_fingerprint(id->key, SSH_FP_HASH_DEFAULT,
637
40
        SSH_FP_DEFAULT)) == NULL)
638
0
      fatal_f("fingerprint failed");
639
40
    debug_f("key %u / %u: %s %s", i++, idtab->nentries,
640
40
        sshkey_ssh_name(id->key), fp);
641
40
    dump_dest_constraints(__func__,
642
40
        id->dest_constraints, id->ndest_constraints);
643
40
    free(fp);
644
    /* identity not visible, don't include in response */
645
40
    if (identity_permitted(id, e, NULL, NULL, NULL) != 0)
646
0
      continue;
647
40
    if ((r = sshkey_puts(id->key, keys)) != 0 ||
648
40
        (r = sshbuf_put_cstring(keys, id->comment)) != 0) {
649
0
      error_fr(r, "compose key/comment");
650
0
      continue;
651
0
    }
652
40
    nentries++;
653
40
  }
654
4
  debug2_f("replying with %u allowed of %u available keys",
655
4
      nentries, idtab->nentries);
656
4
  if ((r = sshbuf_put_u8(msg, SSH2_AGENT_IDENTITIES_ANSWER)) != 0 ||
657
4
      (r = sshbuf_put_u32(msg, nentries)) != 0 ||
658
4
      (r = sshbuf_putb(msg, keys)) != 0)
659
0
    fatal_fr(r, "compose");
660
4
  if ((r = sshbuf_put_stringb(e->output, msg)) != 0)
661
0
    fatal_fr(r, "enqueue");
662
4
  sshbuf_free(msg);
663
4
  sshbuf_free(keys);
664
4
}
665
666
667
static char *
668
agent_decode_alg(struct sshkey *key, u_int flags)
669
0
{
670
0
  if (key->type == KEY_RSA) {
671
0
    if (flags & SSH_AGENT_RSA_SHA2_256)
672
0
      return "rsa-sha2-256";
673
0
    else if (flags & SSH_AGENT_RSA_SHA2_512)
674
0
      return "rsa-sha2-512";
675
0
  } else if (key->type == KEY_RSA_CERT) {
676
0
    if (flags & SSH_AGENT_RSA_SHA2_256)
677
0
      return "rsa-sha2-256-cert-v01@openssh.com";
678
0
    else if (flags & SSH_AGENT_RSA_SHA2_512)
679
0
      return "rsa-sha2-512-cert-v01@openssh.com";
680
0
  }
681
0
  return NULL;
682
0
}
683
684
/*
685
 * Attempt to parse the contents of a buffer as a SSH publickey userauth
686
 * request, checking its contents for consistency and matching the embedded
687
 * key against the one that is being used for signing.
688
 * Note: does not modify msg buffer.
689
 * Optionally extract the username, session ID and/or hostkey from the request.
690
 */
691
static int
692
parse_userauth_request(struct sshbuf *msg, const struct sshkey *expected_key,
693
    char **userp, struct sshbuf **sess_idp, struct sshkey **hostkeyp)
694
0
{
695
0
  struct sshbuf *b = NULL, *sess_id = NULL;
696
0
  char *user = NULL, *service = NULL, *method = NULL, *pkalg = NULL;
697
0
  int r;
698
0
  u_char t, sig_follows;
699
0
  struct sshkey *mkey = NULL, *hostkey = NULL;
700
701
0
  if (userp != NULL)
702
0
    *userp = NULL;
703
0
  if (sess_idp != NULL)
704
0
    *sess_idp = NULL;
705
0
  if (hostkeyp != NULL)
706
0
    *hostkeyp = NULL;
707
0
  if ((b = sshbuf_fromb(msg)) == NULL)
708
0
    fatal_f("sshbuf_fromb");
709
710
  /* SSH userauth request */
711
0
  if ((r = sshbuf_froms(b, &sess_id)) != 0)
712
0
    goto out;
713
0
  if (sshbuf_len(sess_id) == 0) {
714
0
    r = SSH_ERR_INVALID_FORMAT;
715
0
    goto out;
716
0
  }
717
0
  if ((r = sshbuf_get_u8(b, &t)) != 0 || /* SSH2_MSG_USERAUTH_REQUEST */
718
0
      (r = sshbuf_get_cstring(b, &user, NULL)) != 0 || /* server user */
719
0
      (r = sshbuf_get_cstring(b, &service, NULL)) != 0 || /* service */
720
0
      (r = sshbuf_get_cstring(b, &method, NULL)) != 0 || /* method */
721
0
      (r = sshbuf_get_u8(b, &sig_follows)) != 0 || /* sig-follows */
722
0
      (r = sshbuf_get_cstring(b, &pkalg, NULL)) != 0 || /* alg */
723
0
      (r = sshkey_froms(b, &mkey)) != 0) /* key */
724
0
    goto out;
725
0
  if (t != SSH2_MSG_USERAUTH_REQUEST ||
726
0
      sig_follows != 1 ||
727
0
      strcmp(service, "ssh-connection") != 0 ||
728
0
      !sshkey_equal(expected_key, mkey) ||
729
0
      sshkey_type_from_name(pkalg) != expected_key->type) {
730
0
    r = SSH_ERR_INVALID_FORMAT;
731
0
    goto out;
732
0
  }
733
0
  if (strcmp(method, "publickey-hostbound-v00@openssh.com") == 0) {
734
0
    if ((r = sshkey_froms(b, &hostkey)) != 0)
735
0
      goto out;
736
0
  } else if (strcmp(method, "publickey") != 0) {
737
0
    r = SSH_ERR_INVALID_FORMAT;
738
0
    goto out;
739
0
  }
740
0
  if (sshbuf_len(b) != 0) {
741
0
    r = SSH_ERR_INVALID_FORMAT;
742
0
    goto out;
743
0
  }
744
  /* success */
745
0
  r = 0;
746
0
  debug3_f("well formed userauth");
747
0
  if (userp != NULL) {
748
0
    *userp = user;
749
0
    user = NULL;
750
0
  }
751
0
  if (sess_idp != NULL) {
752
0
    *sess_idp = sess_id;
753
0
    sess_id = NULL;
754
0
  }
755
0
  if (hostkeyp != NULL) {
756
0
    *hostkeyp = hostkey;
757
0
    hostkey = NULL;
758
0
  }
759
0
 out:
760
0
  sshbuf_free(b);
761
0
  sshbuf_free(sess_id);
762
0
  free(user);
763
0
  free(service);
764
0
  free(method);
765
0
  free(pkalg);
766
0
  sshkey_free(mkey);
767
0
  sshkey_free(hostkey);
768
0
  return r;
769
0
}
770
771
/*
772
 * Attempt to parse the contents of a buffer as a SSHSIG signature request.
773
 * Note: does not modify buffer.
774
 */
775
static int
776
parse_sshsig_request(struct sshbuf *msg)
777
0
{
778
0
  int r;
779
0
  struct sshbuf *b;
780
781
0
  if ((b = sshbuf_fromb(msg)) == NULL)
782
0
    fatal_f("sshbuf_fromb");
783
784
0
  if ((r = sshbuf_cmp(b, 0, "SSHSIG", 6)) != 0 ||
785
0
      (r = sshbuf_consume(b, 6)) != 0 ||
786
0
      (r = sshbuf_get_cstring(b, NULL, NULL)) != 0 || /* namespace */
787
0
      (r = sshbuf_get_string_direct(b, NULL, NULL)) != 0 || /* reserved */
788
0
      (r = sshbuf_get_cstring(b, NULL, NULL)) != 0 || /* hashalg */
789
0
      (r = sshbuf_get_string_direct(b, NULL, NULL)) != 0) /* H(msg) */
790
0
    goto out;
791
0
  if (sshbuf_len(b) != 0) {
792
0
    r = SSH_ERR_INVALID_FORMAT;
793
0
    goto out;
794
0
  }
795
  /* success */
796
0
  r = 0;
797
0
 out:
798
0
  sshbuf_free(b);
799
0
  return r;
800
0
}
801
802
/*
803
 * This function inspects a message to be signed by a FIDO key that has a
804
 * web-like application string (i.e. one that does not begin with "ssh:".
805
 * It checks that the message is one of those expected for SSH operations
806
 * (pubkey userauth, sshsig, CA key signing) to exclude signing challenges
807
 * for the web.
808
 */
809
static int
810
check_websafe_message_contents(struct sshkey *key, struct sshbuf *data)
811
0
{
812
0
  if (parse_userauth_request(data, key, NULL, NULL, NULL) == 0) {
813
0
    debug_f("signed data matches public key userauth request");
814
0
    return 1;
815
0
  }
816
0
  if (parse_sshsig_request(data) == 0) {
817
0
    debug_f("signed data matches SSHSIG signature request");
818
0
    return 1;
819
0
  }
820
821
  /* XXX check CA signature operation */
822
823
0
  error("web-origin key attempting to sign non-SSH message");
824
0
  return 0;
825
0
}
826
827
static int
828
buf_equal(const struct sshbuf *a, const struct sshbuf *b)
829
0
{
830
0
  if (sshbuf_ptr(a) == NULL || sshbuf_ptr(b) == NULL)
831
0
    return SSH_ERR_INVALID_ARGUMENT;
832
0
  if (sshbuf_len(a) != sshbuf_len(b))
833
0
    return SSH_ERR_INVALID_FORMAT;
834
0
  if (timingsafe_bcmp(sshbuf_ptr(a), sshbuf_ptr(b), sshbuf_len(a)) != 0)
835
0
    return SSH_ERR_INVALID_FORMAT;
836
0
  return 0;
837
0
}
838
839
/* ssh2 only */
840
static void
841
process_sign_request2(SocketEntry *e)
842
34
{
843
34
  u_char *signature = NULL;
844
34
  size_t slen = 0;
845
34
  u_int compat = 0, flags;
846
34
  int r, ok = -1, retried = 0;
847
34
  char *fp = NULL, *pin = NULL, *prompt = NULL;
848
34
  char *user = NULL, *sig_dest = NULL;
849
34
  const char *fwd_host = NULL, *dest_host = NULL;
850
34
  struct sshbuf *msg = NULL, *data = NULL, *sid = NULL;
851
34
  struct sshkey *key = NULL, *hostkey = NULL;
852
34
  struct identity *id;
853
34
  struct notifier_ctx *notifier = NULL;
854
855
34
  debug_f("entering");
856
857
34
  if ((msg = sshbuf_new()) == NULL || (data = sshbuf_new()) == NULL)
858
0
    fatal_f("sshbuf_new failed");
859
34
  if ((r = sshkey_froms(e->request, &key)) != 0 ||
860
34
      (r = sshbuf_get_stringb(e->request, data)) != 0 ||
861
34
      (r = sshbuf_get_u32(e->request, &flags)) != 0) {
862
34
    error_fr(r, "parse");
863
34
    goto send;
864
34
  }
865
866
0
  if ((id = lookup_identity(key)) == NULL) {
867
0
    verbose_f("%s key not found", sshkey_type(key));
868
0
    goto send;
869
0
  }
870
0
  if ((fp = sshkey_fingerprint(key, SSH_FP_HASH_DEFAULT,
871
0
      SSH_FP_DEFAULT)) == NULL)
872
0
    fatal_f("fingerprint failed");
873
874
0
  if (id->ndest_constraints != 0) {
875
0
    if (e->nsession_ids == 0) {
876
0
      logit_f("refusing use of destination-constrained key "
877
0
          "to sign on unbound connection");
878
0
      goto send;
879
0
    }
880
0
    if (parse_userauth_request(data, key, &user, &sid,
881
0
        &hostkey) != 0) {
882
0
      logit_f("refusing use of destination-constrained key "
883
0
         "to sign an unidentified signature");
884
0
      goto send;
885
0
    }
886
    /* XXX logspam */
887
0
    debug_f("user=%s", user);
888
0
    if (identity_permitted(id, e, user, &fwd_host, &dest_host) != 0)
889
0
      goto send;
890
    /* XXX display fwd_host/dest_host in askpass UI */
891
    /*
892
     * Ensure that the session ID is the most recent one
893
     * registered on the socket - it should have been bound by
894
     * ssh immediately before userauth.
895
     */
896
0
    if (buf_equal(sid,
897
0
        e->session_ids[e->nsession_ids - 1].sid) != 0) {
898
0
      error_f("unexpected session ID (%zu listed) on "
899
0
          "signature request for target user %s with "
900
0
          "key %s %s", e->nsession_ids, user,
901
0
          sshkey_type(id->key), fp);
902
0
      goto send;
903
0
    }
904
    /*
905
     * Ensure that the hostkey embedded in the signature matches
906
     * the one most recently bound to the socket. An exception is
907
     * made for the initial forwarding hop.
908
     */
909
0
    if (e->nsession_ids > 1 && hostkey == NULL) {
910
0
      error_f("refusing use of destination-constrained key: "
911
0
          "no hostkey recorded in signature for forwarded "
912
0
          "connection");
913
0
      goto send;
914
0
    }
915
0
    if (hostkey != NULL && !sshkey_equal(hostkey,
916
0
        e->session_ids[e->nsession_ids - 1].key)) {
917
0
      error_f("refusing use of destination-constrained key: "
918
0
          "mismatch between hostkey in request and most "
919
0
          "recently bound session");
920
0
      goto send;
921
0
    }
922
0
    xasprintf(&sig_dest, "public key authentication request for "
923
0
        "user \"%s\" to listed host", user);
924
0
  }
925
0
  if (id->confirm && confirm_key(id, sig_dest) != 0) {
926
0
    verbose_f("user refused key");
927
0
    goto send;
928
0
  }
929
0
  if (sshkey_is_sk(id->key)) {
930
0
    if (restrict_websafe &&
931
0
        match_pattern_list(id->key->sk_application,
932
0
        websafe_allowlist, 0) != 1 &&
933
0
        !check_websafe_message_contents(key, data)) {
934
      /* error already logged */
935
0
      goto send;
936
0
    }
937
0
    if (id->key->sk_flags & SSH_SK_USER_PRESENCE_REQD) {
938
0
      notifier = notify_start(0,
939
0
          "Confirm user presence for key %s %s%s%s",
940
0
          sshkey_type(id->key), fp,
941
0
          sig_dest == NULL ? "" : "\n",
942
0
          sig_dest == NULL ? "" : sig_dest);
943
0
    }
944
0
  }
945
0
 retry_pin:
946
0
  if ((r = sshkey_sign(id->key, &signature, &slen,
947
0
      sshbuf_ptr(data), sshbuf_len(data), agent_decode_alg(key, flags),
948
0
      id->sk_provider, pin, compat)) != 0) {
949
0
    debug_fr(r, "sshkey_sign");
950
0
    if (pin == NULL && !retried && sshkey_is_sk(id->key) &&
951
0
        r == SSH_ERR_KEY_WRONG_PASSPHRASE) {
952
0
      notify_complete(notifier, NULL);
953
0
      notifier = NULL;
954
      /* XXX include sig_dest */
955
0
      xasprintf(&prompt, "Enter PIN%sfor %s key %s: ",
956
0
          (id->key->sk_flags & SSH_SK_USER_PRESENCE_REQD) ?
957
0
          " and confirm user presence " : " ",
958
0
          sshkey_type(id->key), fp);
959
0
      pin = read_passphrase(prompt, RP_USE_ASKPASS);
960
0
      retried = 1;
961
0
      goto retry_pin;
962
0
    }
963
0
    error_fr(r, "sshkey_sign");
964
0
    goto send;
965
0
  }
966
  /* Success */
967
0
  ok = 0;
968
0
  debug_f("good signature");
969
34
 send:
970
34
  notify_complete(notifier, "User presence confirmed");
971
972
34
  if (ok == 0) {
973
0
    if ((r = sshbuf_put_u8(msg, SSH2_AGENT_SIGN_RESPONSE)) != 0 ||
974
0
        (r = sshbuf_put_string(msg, signature, slen)) != 0)
975
0
      fatal_fr(r, "compose");
976
34
  } else if ((r = sshbuf_put_u8(msg, SSH_AGENT_FAILURE)) != 0)
977
0
    fatal_fr(r, "compose failure");
978
979
34
  if ((r = sshbuf_put_stringb(e->output, msg)) != 0)
980
0
    fatal_fr(r, "enqueue");
981
982
34
  sshbuf_free(sid);
983
34
  sshbuf_free(data);
984
34
  sshbuf_free(msg);
985
34
  sshkey_free(key);
986
34
  sshkey_free(hostkey);
987
34
  free(fp);
988
34
  free(signature);
989
34
  free(sig_dest);
990
34
  free(user);
991
34
  free(prompt);
992
34
  if (pin != NULL)
993
0
    freezero(pin, strlen(pin));
994
34
}
995
996
/* shared */
997
static void
998
process_remove_identity(SocketEntry *e)
999
5
{
1000
5
  int r, success = 0;
1001
5
  struct sshkey *key = NULL;
1002
5
  Identity *id;
1003
1004
5
  debug2_f("entering");
1005
5
  if ((r = sshkey_froms(e->request, &key)) != 0) {
1006
5
    error_fr(r, "parse key");
1007
5
    goto done;
1008
5
  }
1009
0
  if ((id = lookup_identity(key)) == NULL) {
1010
0
    debug_f("key not found");
1011
0
    goto done;
1012
0
  }
1013
  /* identity not visible, cannot be removed */
1014
0
  if (identity_permitted(id, e, NULL, NULL, NULL) != 0)
1015
0
    goto done; /* error already logged */
1016
  /* We have this key, free it. */
1017
0
  if (idtab->nentries < 1)
1018
0
    fatal_f("internal error: nentries %d", idtab->nentries);
1019
0
  TAILQ_REMOVE(&idtab->idlist, id, next);
1020
0
  free_identity(id);
1021
0
  idtab->nentries--;
1022
0
  success = 1;
1023
5
 done:
1024
5
  sshkey_free(key);
1025
5
  send_status(e, success);
1026
5
}
1027
1028
static void
1029
remove_all_identities(void)
1030
2
{
1031
2
  Identity *id;
1032
1033
2
  debug2_f("entering");
1034
  /* Loop over all identities and clear the keys. */
1035
22
  for (id = TAILQ_FIRST(&idtab->idlist); id;
1036
20
      id = TAILQ_FIRST(&idtab->idlist)) {
1037
20
    TAILQ_REMOVE(&idtab->idlist, id, next);
1038
20
    free_identity(id);
1039
20
  }
1040
1041
  /* Mark that there are no identities. */
1042
2
  idtab->nentries = 0;
1043
2
}
1044
1045
static void
1046
process_remove_all_identities(SocketEntry *e)
1047
2
{
1048
2
  remove_all_identities();
1049
1050
  /* Send success. */
1051
2
  send_status(e, 1);
1052
2
}
1053
1054
/* removes expired keys and returns number of seconds until the next expiry */
1055
static time_t
1056
reaper(void)
1057
0
{
1058
0
  time_t deadline = 0, now = monotime();
1059
0
  Identity *id, *nxt;
1060
1061
0
  for (id = TAILQ_FIRST(&idtab->idlist); id; id = nxt) {
1062
0
    nxt = TAILQ_NEXT(id, next);
1063
0
    if (id->death == 0)
1064
0
      continue;
1065
0
    if (now >= id->death) {
1066
0
      debug("expiring key '%s'", id->comment);
1067
0
      TAILQ_REMOVE(&idtab->idlist, id, next);
1068
0
      free_identity(id);
1069
0
      idtab->nentries--;
1070
0
    } else
1071
0
      deadline = (deadline == 0) ? id->death :
1072
0
          MINIMUM(deadline, id->death);
1073
0
  }
1074
0
  if (deadline == 0 || deadline <= now)
1075
0
    return 0;
1076
0
  else
1077
0
    return (deadline - now);
1078
0
}
1079
1080
static int
1081
parse_dest_constraint_hop(struct sshbuf *b, struct dest_constraint_hop *dch)
1082
0
{
1083
0
  u_char key_is_ca;
1084
0
  size_t elen = 0;
1085
0
  int r;
1086
0
  struct sshkey *k = NULL;
1087
0
  char *fp;
1088
1089
0
  memset(dch, '\0', sizeof(*dch));
1090
0
  if ((r = sshbuf_get_cstring(b, &dch->user, NULL)) != 0 ||
1091
0
      (r = sshbuf_get_cstring(b, &dch->hostname, NULL)) != 0 ||
1092
0
      (r = sshbuf_get_string_direct(b, NULL, &elen)) != 0) {
1093
0
    error_fr(r, "parse");
1094
0
    goto out;
1095
0
  }
1096
0
  if (elen != 0) {
1097
0
    error_f("unsupported extensions (len %zu)", elen);
1098
0
    r = SSH_ERR_FEATURE_UNSUPPORTED;
1099
0
    goto out;
1100
0
  }
1101
0
  if (*dch->hostname == '\0') {
1102
0
    free(dch->hostname);
1103
0
    dch->hostname = NULL;
1104
0
  }
1105
0
  if (*dch->user == '\0') {
1106
0
    free(dch->user);
1107
0
    dch->user = NULL;
1108
0
  }
1109
0
  while (sshbuf_len(b) != 0) {
1110
0
    dch->keys = xrecallocarray(dch->keys, dch->nkeys,
1111
0
        dch->nkeys + 1, sizeof(*dch->keys));
1112
0
    dch->key_is_ca = xrecallocarray(dch->key_is_ca, dch->nkeys,
1113
0
        dch->nkeys + 1, sizeof(*dch->key_is_ca));
1114
0
    if ((r = sshkey_froms(b, &k)) != 0 ||
1115
0
        (r = sshbuf_get_u8(b, &key_is_ca)) != 0)
1116
0
      goto out;
1117
0
    if ((fp = sshkey_fingerprint(k, SSH_FP_HASH_DEFAULT,
1118
0
        SSH_FP_DEFAULT)) == NULL)
1119
0
      fatal_f("fingerprint failed");
1120
0
    debug3_f("%s%s%s: adding %skey %s %s",
1121
0
        dch->user == NULL ? "" : dch->user,
1122
0
        dch->user == NULL ? "" : "@",
1123
0
        dch->hostname, key_is_ca ? "CA " : "", sshkey_type(k), fp);
1124
0
    free(fp);
1125
0
    dch->keys[dch->nkeys] = k;
1126
0
    dch->key_is_ca[dch->nkeys] = key_is_ca != 0;
1127
0
    dch->nkeys++;
1128
0
    k = NULL; /* transferred */
1129
0
  }
1130
  /* success */
1131
0
  r = 0;
1132
0
 out:
1133
0
  sshkey_free(k);
1134
0
  return r;
1135
0
}
1136
1137
static int
1138
parse_dest_constraint(struct sshbuf *m, struct dest_constraint *dc)
1139
0
{
1140
0
  struct sshbuf *b = NULL, *frombuf = NULL, *tobuf = NULL;
1141
0
  int r;
1142
0
  size_t elen = 0;
1143
1144
0
  debug3_f("entering");
1145
1146
0
  memset(dc, '\0', sizeof(*dc));
1147
0
  if ((r = sshbuf_froms(m, &b)) != 0 ||
1148
0
      (r = sshbuf_froms(b, &frombuf)) != 0 ||
1149
0
      (r = sshbuf_froms(b, &tobuf)) != 0 ||
1150
0
      (r = sshbuf_get_string_direct(b, NULL, &elen)) != 0) {
1151
0
    error_fr(r, "parse");
1152
0
    goto out;
1153
0
  }
1154
0
  if ((r = parse_dest_constraint_hop(frombuf, &dc->from)) != 0 ||
1155
0
      (r = parse_dest_constraint_hop(tobuf, &dc->to)) != 0)
1156
0
    goto out; /* already logged */
1157
0
  if (elen != 0) {
1158
0
    error_f("unsupported extensions (len %zu)", elen);
1159
0
    r = SSH_ERR_FEATURE_UNSUPPORTED;
1160
0
    goto out;
1161
0
  }
1162
0
  debug2_f("parsed %s (%u keys) > %s%s%s (%u keys)",
1163
0
      dc->from.hostname ? dc->from.hostname : "(ORIGIN)", dc->from.nkeys,
1164
0
      dc->to.user ? dc->to.user : "", dc->to.user ? "@" : "",
1165
0
      dc->to.hostname ? dc->to.hostname : "(ANY)", dc->to.nkeys);
1166
  /* check consistency */
1167
0
  if ((dc->from.hostname == NULL) != (dc->from.nkeys == 0) ||
1168
0
      dc->from.user != NULL) {
1169
0
    error_f("inconsistent \"from\" specification");
1170
0
    r = SSH_ERR_INVALID_FORMAT;
1171
0
    goto out;
1172
0
  }
1173
0
  if (dc->to.hostname == NULL || dc->to.nkeys == 0) {
1174
0
    error_f("incomplete \"to\" specification");
1175
0
    r = SSH_ERR_INVALID_FORMAT;
1176
0
    goto out;
1177
0
  }
1178
  /* success */
1179
0
  r = 0;
1180
0
 out:
1181
0
  sshbuf_free(b);
1182
0
  sshbuf_free(frombuf);
1183
0
  sshbuf_free(tobuf);
1184
0
  return r;
1185
0
}
1186
1187
static int
1188
parse_key_constraint_extension(struct sshbuf *m, char **sk_providerp,
1189
    struct dest_constraint **dcsp, size_t *ndcsp, int *cert_onlyp,
1190
    struct sshkey ***certs, size_t *ncerts)
1191
0
{
1192
0
  char *ext_name = NULL;
1193
0
  int r;
1194
0
  struct sshbuf *b = NULL;
1195
0
  u_char v;
1196
0
  struct sshkey *k;
1197
1198
0
  if ((r = sshbuf_get_cstring(m, &ext_name, NULL)) != 0) {
1199
0
    error_fr(r, "parse constraint extension");
1200
0
    goto out;
1201
0
  }
1202
0
  debug_f("constraint ext %s", ext_name);
1203
0
  if (strcmp(ext_name, "sk-provider@openssh.com") == 0) {
1204
0
    if (sk_providerp == NULL) {
1205
0
      error_f("%s not valid here", ext_name);
1206
0
      r = SSH_ERR_INVALID_FORMAT;
1207
0
      goto out;
1208
0
    }
1209
0
    if (*sk_providerp != NULL) {
1210
0
      error_f("%s already set", ext_name);
1211
0
      r = SSH_ERR_INVALID_FORMAT;
1212
0
      goto out;
1213
0
    }
1214
0
    if ((r = sshbuf_get_cstring(m, sk_providerp, NULL)) != 0) {
1215
0
      error_fr(r, "parse %s", ext_name);
1216
0
      goto out;
1217
0
    }
1218
0
  } else if (strcmp(ext_name,
1219
0
      "restrict-destination-v00@openssh.com") == 0) {
1220
0
    if (*dcsp != NULL) {
1221
0
      error_f("%s already set", ext_name);
1222
0
      r = SSH_ERR_INVALID_FORMAT;
1223
0
      goto out;
1224
0
    }
1225
0
    if ((r = sshbuf_froms(m, &b)) != 0) {
1226
0
      error_fr(r, "parse %s outer", ext_name);
1227
0
      goto out;
1228
0
    }
1229
0
    while (sshbuf_len(b) != 0) {
1230
0
      if (*ndcsp >= AGENT_MAX_DEST_CONSTRAINTS) {
1231
0
        error_f("too many %s constraints", ext_name);
1232
0
        r = SSH_ERR_INVALID_FORMAT;
1233
0
        goto out;
1234
0
      }
1235
0
      *dcsp = xrecallocarray(*dcsp, *ndcsp, *ndcsp + 1,
1236
0
          sizeof(**dcsp));
1237
0
      if ((r = parse_dest_constraint(b,
1238
0
          *dcsp + (*ndcsp)++)) != 0)
1239
0
        goto out; /* error already logged */
1240
0
    }
1241
0
  } else if (strcmp(ext_name,
1242
0
      "associated-certs-v00@openssh.com") == 0) {
1243
0
    if (certs == NULL || ncerts == NULL || cert_onlyp == NULL) {
1244
0
      error_f("%s not valid here", ext_name);
1245
0
      r = SSH_ERR_INVALID_FORMAT;
1246
0
      goto out;
1247
0
    }
1248
0
    if (*certs != NULL) {
1249
0
      error_f("%s already set", ext_name);
1250
0
      r = SSH_ERR_INVALID_FORMAT;
1251
0
      goto out;
1252
0
    }
1253
0
    if ((r = sshbuf_get_u8(m, &v)) != 0 ||
1254
0
        (r = sshbuf_froms(m, &b)) != 0) {
1255
0
      error_fr(r, "parse %s", ext_name);
1256
0
      goto out;
1257
0
    }
1258
0
    *cert_onlyp = v != 0;
1259
0
    while (sshbuf_len(b) != 0) {
1260
0
      if (*ncerts >= AGENT_MAX_EXT_CERTS) {
1261
0
        error_f("too many %s constraints", ext_name);
1262
0
        r = SSH_ERR_INVALID_FORMAT;
1263
0
        goto out;
1264
0
      }
1265
0
      *certs = xrecallocarray(*certs, *ncerts, *ncerts + 1,
1266
0
          sizeof(**certs));
1267
0
      if ((r = sshkey_froms(b, &k)) != 0) {
1268
0
        error_fr(r, "parse key");
1269
0
        goto out;
1270
0
      }
1271
0
      (*certs)[(*ncerts)++] = k;
1272
0
    }
1273
0
  } else {
1274
0
    error_f("unsupported constraint \"%s\"", ext_name);
1275
0
    r = SSH_ERR_FEATURE_UNSUPPORTED;
1276
0
    goto out;
1277
0
  }
1278
  /* success */
1279
0
  r = 0;
1280
0
 out:
1281
0
  free(ext_name);
1282
0
  sshbuf_free(b);
1283
0
  return r;
1284
0
}
1285
1286
static int
1287
parse_key_constraints(struct sshbuf *m, struct sshkey *k, time_t *deathp,
1288
    u_int *secondsp, int *confirmp, char **sk_providerp,
1289
    struct dest_constraint **dcsp, size_t *ndcsp,
1290
    int *cert_onlyp, size_t *ncerts, struct sshkey ***certs)
1291
0
{
1292
0
  u_char ctype;
1293
0
  int r;
1294
0
  u_int seconds;
1295
1296
0
  while (sshbuf_len(m)) {
1297
0
    if ((r = sshbuf_get_u8(m, &ctype)) != 0) {
1298
0
      error_fr(r, "parse constraint type");
1299
0
      goto out;
1300
0
    }
1301
0
    switch (ctype) {
1302
0
    case SSH_AGENT_CONSTRAIN_LIFETIME:
1303
0
      if (*deathp != 0) {
1304
0
        error_f("lifetime already set");
1305
0
        r = SSH_ERR_INVALID_FORMAT;
1306
0
        goto out;
1307
0
      }
1308
0
      if ((r = sshbuf_get_u32(m, &seconds)) != 0) {
1309
0
        error_fr(r, "parse lifetime constraint");
1310
0
        goto out;
1311
0
      }
1312
0
      *deathp = monotime() + seconds;
1313
0
      *secondsp = seconds;
1314
0
      break;
1315
0
    case SSH_AGENT_CONSTRAIN_CONFIRM:
1316
0
      if (*confirmp != 0) {
1317
0
        error_f("confirm already set");
1318
0
        r = SSH_ERR_INVALID_FORMAT;
1319
0
        goto out;
1320
0
      }
1321
0
      *confirmp = 1;
1322
0
      break;
1323
0
    case SSH_AGENT_CONSTRAIN_EXTENSION:
1324
0
      if ((r = parse_key_constraint_extension(m,
1325
0
          sk_providerp, dcsp, ndcsp,
1326
0
          cert_onlyp, certs, ncerts)) != 0)
1327
0
        goto out; /* error already logged */
1328
0
      break;
1329
0
    default:
1330
0
      error_f("Unknown constraint %d", ctype);
1331
0
      r = SSH_ERR_FEATURE_UNSUPPORTED;
1332
0
      goto out;
1333
0
    }
1334
0
  }
1335
  /* success */
1336
0
  r = 0;
1337
0
 out:
1338
0
  return r;
1339
0
}
1340
1341
static void
1342
process_add_identity(SocketEntry *e)
1343
8
{
1344
8
  Identity *id;
1345
8
  int success = 0, confirm = 0;
1346
8
  char *fp, *comment = NULL, *sk_provider = NULL;
1347
8
  char canonical_provider[PATH_MAX];
1348
8
  time_t death = 0;
1349
8
  u_int seconds = 0;
1350
8
  struct dest_constraint *dest_constraints = NULL;
1351
8
  size_t ndest_constraints = 0;
1352
8
  struct sshkey *k = NULL;
1353
8
  int r = SSH_ERR_INTERNAL_ERROR;
1354
1355
8
  debug2_f("entering");
1356
8
  if ((r = sshkey_private_deserialize(e->request, &k)) != 0 ||
1357
8
      k == NULL ||
1358
8
      (r = sshbuf_get_cstring(e->request, &comment, NULL)) != 0) {
1359
8
    error_fr(r, "parse");
1360
8
    goto out;
1361
8
  }
1362
0
  if (parse_key_constraints(e->request, k, &death, &seconds, &confirm,
1363
0
      &sk_provider, &dest_constraints, &ndest_constraints,
1364
0
      NULL, NULL, NULL) != 0) {
1365
0
    error_f("failed to parse constraints");
1366
0
    sshbuf_reset(e->request);
1367
0
    goto out;
1368
0
  }
1369
0
  dump_dest_constraints(__func__, dest_constraints, ndest_constraints);
1370
1371
0
  if (sk_provider != NULL) {
1372
0
    if (!sshkey_is_sk(k)) {
1373
0
      error("Cannot add provider: %s is not an "
1374
0
          "authenticator-hosted key", sshkey_type(k));
1375
0
      goto out;
1376
0
    }
1377
0
    if (strcasecmp(sk_provider, "internal") == 0) {
1378
0
      debug_f("internal provider");
1379
0
    } else {
1380
0
      if (socket_is_remote(e) && !remote_add_provider) {
1381
0
        verbose("failed add of SK provider \"%.100s\": "
1382
0
            "remote addition of providers is disabled",
1383
0
            sk_provider);
1384
0
        goto out;
1385
0
      }
1386
0
      if (realpath(sk_provider, canonical_provider) == NULL) {
1387
0
        verbose("failed provider \"%.100s\": "
1388
0
            "realpath: %s", sk_provider,
1389
0
            strerror(errno));
1390
0
        goto out;
1391
0
      }
1392
0
      free(sk_provider);
1393
0
      sk_provider = xstrdup(canonical_provider);
1394
0
      if (match_pattern_list(sk_provider,
1395
0
          allowed_providers, 0) != 1) {
1396
0
        error("Refusing add key: "
1397
0
            "provider %s not allowed", sk_provider);
1398
0
        goto out;
1399
0
      }
1400
0
    }
1401
0
  }
1402
0
  if ((r = sshkey_shield_private(k)) != 0) {
1403
0
    error_fr(r, "shield private");
1404
0
    goto out;
1405
0
  }
1406
0
  if (lifetime && !death)
1407
0
    death = monotime() + lifetime;
1408
0
  if ((id = lookup_identity(k)) == NULL) {
1409
0
    id = xcalloc(1, sizeof(Identity));
1410
0
    TAILQ_INSERT_TAIL(&idtab->idlist, id, next);
1411
    /* Increment the number of identities. */
1412
0
    idtab->nentries++;
1413
0
  } else {
1414
    /* identity not visible, do not update */
1415
0
    if (identity_permitted(id, e, NULL, NULL, NULL) != 0)
1416
0
      goto out; /* error already logged */
1417
    /* key state might have been updated */
1418
0
    sshkey_free(id->key);
1419
0
    free(id->comment);
1420
0
    free(id->sk_provider);
1421
0
    free_dest_constraints(id->dest_constraints,
1422
0
        id->ndest_constraints);
1423
0
  }
1424
  /* success */
1425
0
  id->key = k;
1426
0
  id->comment = comment;
1427
0
  id->death = death;
1428
0
  id->confirm = confirm;
1429
0
  id->sk_provider = sk_provider;
1430
0
  id->dest_constraints = dest_constraints;
1431
0
  id->ndest_constraints = ndest_constraints;
1432
1433
0
  if ((fp = sshkey_fingerprint(k, SSH_FP_HASH_DEFAULT,
1434
0
      SSH_FP_DEFAULT)) == NULL)
1435
0
    fatal_f("sshkey_fingerprint failed");
1436
0
  debug_f("add %s %s \"%.100s\" (life: %u) (confirm: %u) "
1437
0
      "(provider: %s) (destination constraints: %zu)",
1438
0
      sshkey_ssh_name(k), fp, comment, seconds, confirm,
1439
0
      sk_provider == NULL ? "none" : sk_provider, ndest_constraints);
1440
0
  free(fp);
1441
  /* transferred */
1442
0
  k = NULL;
1443
0
  comment = NULL;
1444
0
  sk_provider = NULL;
1445
0
  dest_constraints = NULL;
1446
0
  ndest_constraints = 0;
1447
0
  success = 1;
1448
8
 out:
1449
8
  free(sk_provider);
1450
8
  free(comment);
1451
8
  sshkey_free(k);
1452
8
  free_dest_constraints(dest_constraints, ndest_constraints);
1453
8
  send_status(e, success);
1454
8
}
1455
1456
/* XXX todo: encrypt sensitive data with passphrase */
1457
static void
1458
process_lock_agent(SocketEntry *e, int lock)
1459
6.34k
{
1460
6.34k
  int r, success = 0, delay;
1461
6.34k
  char *passwd;
1462
6.34k
  u_char passwdhash[LOCK_SIZE];
1463
6.34k
  static u_int fail_count = 0;
1464
6.34k
  size_t pwlen;
1465
1466
6.34k
  debug2_f("entering");
1467
  /*
1468
   * This is deliberately fatal: the user has requested that we lock,
1469
   * but we can't parse their request properly. The only safe thing to
1470
   * do is abort.
1471
   */
1472
6.34k
  if ((r = sshbuf_get_cstring(e->request, &passwd, &pwlen)) != 0)
1473
0
    fatal_fr(r, "parse");
1474
6.34k
  if (pwlen == 0) {
1475
3.22k
    debug("empty password not supported");
1476
3.22k
  } else if (locked && !lock) {
1477
3.11k
    if (bcrypt_pbkdf(passwd, pwlen, lock_salt, sizeof(lock_salt),
1478
3.11k
        passwdhash, sizeof(passwdhash), LOCK_ROUNDS) < 0)
1479
0
      fatal("bcrypt_pbkdf");
1480
3.11k
    if (timingsafe_bcmp(passwdhash, lock_pwhash, LOCK_SIZE) == 0) {
1481
0
      debug("agent unlocked");
1482
0
      locked = 0;
1483
0
      fail_count = 0;
1484
0
      explicit_bzero(lock_pwhash, sizeof(lock_pwhash));
1485
0
      success = 1;
1486
3.11k
    } else {
1487
      /* delay in 0.1s increments up to 10s */
1488
3.11k
      if (fail_count < 100)
1489
100
        fail_count++;
1490
3.11k
      delay = 100000 * fail_count;
1491
3.11k
      debug("unlock failed, delaying %0.1lf seconds",
1492
3.11k
          (double)delay/1000000);
1493
      // usleep(delay);
1494
3.11k
    }
1495
3.11k
    explicit_bzero(passwdhash, sizeof(passwdhash));
1496
3.11k
  } else if (!locked && lock) {
1497
1
    debug("agent locked");
1498
1
    locked = 1;
1499
1
    arc4random_buf(lock_salt, sizeof(lock_salt));
1500
1
    if (bcrypt_pbkdf(passwd, pwlen, lock_salt, sizeof(lock_salt),
1501
1
        lock_pwhash, sizeof(lock_pwhash), LOCK_ROUNDS) < 0)
1502
0
      fatal("bcrypt_pbkdf");
1503
1
    success = 1;
1504
1
  }
1505
6.34k
  freezero(passwd, pwlen);
1506
6.34k
  send_status(e, success);
1507
6.34k
}
1508
1509
static void
1510
no_identities(SocketEntry *e)
1511
7.07k
{
1512
7.07k
  struct sshbuf *msg;
1513
7.07k
  int r;
1514
1515
7.07k
  if ((msg = sshbuf_new()) == NULL)
1516
0
    fatal_f("sshbuf_new failed");
1517
7.07k
  if ((r = sshbuf_put_u8(msg, SSH2_AGENT_IDENTITIES_ANSWER)) != 0 ||
1518
7.07k
      (r = sshbuf_put_u32(msg, 0)) != 0 ||
1519
7.07k
      (r = sshbuf_put_stringb(e->output, msg)) != 0)
1520
0
    fatal_fr(r, "compose");
1521
7.07k
  sshbuf_free(msg);
1522
7.07k
}
1523
1524
#ifdef ENABLE_PKCS11
1525
/* Add an identity to idlist; takes ownership of 'key' and 'comment' */
1526
static void
1527
add_p11_identity(struct sshkey *key, char *comment, const char *provider,
1528
    time_t death, u_int confirm, struct dest_constraint *dest_constraints,
1529
    size_t ndest_constraints)
1530
0
{
1531
0
  Identity *id;
1532
1533
0
  if (lookup_identity(key) != NULL) {
1534
0
    sshkey_free(key);
1535
0
    free(comment);
1536
0
    return;
1537
0
  }
1538
0
  id = xcalloc(1, sizeof(Identity));
1539
0
  id->key = key;
1540
0
  id->comment = comment;
1541
0
  id->provider = xstrdup(provider);
1542
0
  id->death = death;
1543
0
  id->confirm = confirm;
1544
0
  id->dest_constraints = dup_dest_constraints(dest_constraints,
1545
0
      ndest_constraints);
1546
0
  id->ndest_constraints = ndest_constraints;
1547
0
  TAILQ_INSERT_TAIL(&idtab->idlist, id, next);
1548
0
  idtab->nentries++;
1549
0
}
1550
1551
static void
1552
process_add_smartcard_key(SocketEntry *e)
1553
17
{
1554
17
  char *provider = NULL, *pin = NULL, canonical_provider[PATH_MAX];
1555
17
  char **comments = NULL;
1556
17
  int r, i, count = 0, success = 0, confirm = 0;
1557
17
  u_int seconds = 0;
1558
17
  time_t death = 0;
1559
17
  struct sshkey **keys = NULL, *k;
1560
17
  struct dest_constraint *dest_constraints = NULL;
1561
17
  size_t j, ndest_constraints = 0, ncerts = 0;
1562
17
  struct sshkey **certs = NULL;
1563
17
  int cert_only = 0;
1564
1565
17
  debug2_f("entering");
1566
17
  if ((r = sshbuf_get_cstring(e->request, &provider, NULL)) != 0 ||
1567
17
      (r = sshbuf_get_cstring(e->request, &pin, NULL)) != 0) {
1568
17
    error_fr(r, "parse");
1569
17
    goto send;
1570
17
  }
1571
0
  if (parse_key_constraints(e->request, NULL, &death, &seconds, &confirm,
1572
0
      NULL, &dest_constraints, &ndest_constraints, &cert_only,
1573
0
      &ncerts, &certs) != 0) {
1574
0
    error_f("failed to parse constraints");
1575
0
    goto send;
1576
0
  }
1577
0
  dump_dest_constraints(__func__, dest_constraints, ndest_constraints);
1578
0
  if (socket_is_remote(e) && !remote_add_provider) {
1579
0
    verbose("failed PKCS#11 add of \"%.100s\": remote addition of "
1580
0
        "providers is disabled", provider);
1581
0
    goto send;
1582
0
  }
1583
0
  if (realpath(provider, canonical_provider) == NULL) {
1584
0
    verbose("failed PKCS#11 add of \"%.100s\": realpath: %s",
1585
0
        provider, strerror(errno));
1586
0
    goto send;
1587
0
  }
1588
0
  if (match_pattern_list(canonical_provider, allowed_providers, 0) != 1) {
1589
0
    verbose("refusing PKCS#11 add of \"%.100s\": "
1590
0
        "provider not allowed", canonical_provider);
1591
0
    goto send;
1592
0
  }
1593
0
  debug_f("add %.100s", canonical_provider);
1594
0
  if (lifetime && !death)
1595
0
    death = monotime() + lifetime;
1596
1597
0
  count = pkcs11_add_provider(canonical_provider, pin, &keys, &comments);
1598
0
  for (i = 0; i < count; i++) {
1599
0
    if (comments[i] == NULL || comments[i][0] == '\0') {
1600
0
      free(comments[i]);
1601
0
      comments[i] = xstrdup(canonical_provider);
1602
0
    }
1603
0
    for (j = 0; j < ncerts; j++) {
1604
0
      if (!sshkey_is_cert(certs[j]))
1605
0
        continue;
1606
0
      if (!sshkey_equal_public(keys[i], certs[j]))
1607
0
        continue;
1608
0
      if (pkcs11_make_cert(keys[i], certs[j], &k) != 0)
1609
0
        continue;
1610
0
      add_p11_identity(k, xstrdup(comments[i]),
1611
0
          canonical_provider, death, confirm,
1612
0
          dest_constraints, ndest_constraints);
1613
0
      success = 1;
1614
0
    }
1615
0
    if (!cert_only && lookup_identity(keys[i]) == NULL) {
1616
0
      add_p11_identity(keys[i], comments[i],
1617
0
          canonical_provider, death, confirm,
1618
0
          dest_constraints, ndest_constraints);
1619
0
      keys[i] = NULL;   /* transferred */
1620
0
      comments[i] = NULL; /* transferred */
1621
0
      success = 1;
1622
0
    }
1623
    /* XXX update constraints for existing keys */
1624
0
    sshkey_free(keys[i]);
1625
0
    free(comments[i]);
1626
0
  }
1627
17
send:
1628
17
  free(pin);
1629
17
  free(provider);
1630
17
  free(keys);
1631
17
  free(comments);
1632
17
  free_dest_constraints(dest_constraints, ndest_constraints);
1633
17
  for (j = 0; j < ncerts; j++)
1634
0
    sshkey_free(certs[j]);
1635
17
  free(certs);
1636
17
  send_status(e, success);
1637
17
}
1638
1639
static void
1640
process_remove_smartcard_key(SocketEntry *e)
1641
20
{
1642
20
  char *provider = NULL, *pin = NULL, canonical_provider[PATH_MAX];
1643
20
  int r, success = 0;
1644
20
  Identity *id, *nxt;
1645
1646
20
  debug2_f("entering");
1647
20
  if ((r = sshbuf_get_cstring(e->request, &provider, NULL)) != 0 ||
1648
20
      (r = sshbuf_get_cstring(e->request, &pin, NULL)) != 0) {
1649
20
    error_fr(r, "parse");
1650
20
    goto send;
1651
20
  }
1652
0
  free(pin);
1653
1654
0
  if (realpath(provider, canonical_provider) == NULL) {
1655
0
    verbose("failed PKCS#11 add of \"%.100s\": realpath: %s",
1656
0
        provider, strerror(errno));
1657
0
    goto send;
1658
0
  }
1659
1660
0
  debug_f("remove %.100s", canonical_provider);
1661
0
  for (id = TAILQ_FIRST(&idtab->idlist); id; id = nxt) {
1662
0
    nxt = TAILQ_NEXT(id, next);
1663
    /* Skip file--based keys */
1664
0
    if (id->provider == NULL)
1665
0
      continue;
1666
0
    if (!strcmp(canonical_provider, id->provider)) {
1667
0
      TAILQ_REMOVE(&idtab->idlist, id, next);
1668
0
      free_identity(id);
1669
0
      idtab->nentries--;
1670
0
    }
1671
0
  }
1672
0
  if (pkcs11_del_provider(canonical_provider) == 0)
1673
0
    success = 1;
1674
0
  else
1675
0
    error_f("pkcs11_del_provider failed");
1676
20
send:
1677
20
  free(provider);
1678
20
  send_status(e, success);
1679
20
}
1680
#endif /* ENABLE_PKCS11 */
1681
1682
static int
1683
process_ext_session_bind(SocketEntry *e)
1684
0
{
1685
0
  int r, sid_match, key_match;
1686
0
  struct sshkey *key = NULL;
1687
0
  struct sshbuf *sid = NULL, *sig = NULL;
1688
0
  char *fp = NULL;
1689
0
  size_t i;
1690
0
  u_char fwd = 0;
1691
1692
0
  debug2_f("entering");
1693
0
  e->session_bind_attempted = 1;
1694
0
  if ((r = sshkey_froms(e->request, &key)) != 0 ||
1695
0
      (r = sshbuf_froms(e->request, &sid)) != 0 ||
1696
0
      (r = sshbuf_froms(e->request, &sig)) != 0 ||
1697
0
      (r = sshbuf_get_u8(e->request, &fwd)) != 0) {
1698
0
    error_fr(r, "parse");
1699
0
    goto out;
1700
0
  }
1701
0
  if (sshbuf_len(sid) > AGENT_MAX_SID_LEN) {
1702
0
    error_f("session ID too long");
1703
0
    goto out;
1704
0
  }
1705
0
  if ((fp = sshkey_fingerprint(key, SSH_FP_HASH_DEFAULT,
1706
0
      SSH_FP_DEFAULT)) == NULL)
1707
0
    fatal_f("fingerprint failed");
1708
  /* check signature with hostkey on session ID */
1709
0
  if ((r = sshkey_verify(key, sshbuf_ptr(sig), sshbuf_len(sig),
1710
0
      sshbuf_ptr(sid), sshbuf_len(sid), NULL, 0, NULL)) != 0) {
1711
0
    error_fr(r, "sshkey_verify for %s %s", sshkey_type(key), fp);
1712
0
    goto out;
1713
0
  }
1714
  /* check whether sid/key already recorded */
1715
0
  for (i = 0; i < e->nsession_ids; i++) {
1716
0
    if (!e->session_ids[i].forwarded) {
1717
0
      error_f("attempt to bind session ID to socket "
1718
0
          "previously bound for authentication attempt");
1719
0
      r = -1;
1720
0
      goto out;
1721
0
    }
1722
0
    sid_match = buf_equal(sid, e->session_ids[i].sid) == 0;
1723
0
    key_match = sshkey_equal(key, e->session_ids[i].key);
1724
0
    if (sid_match && key_match) {
1725
0
      debug_f("session ID already recorded for %s %s",
1726
0
          sshkey_type(key), fp);
1727
0
      r = 0;
1728
0
      goto out;
1729
0
    } else if (sid_match) {
1730
0
      error_f("session ID recorded against different key "
1731
0
          "for %s %s", sshkey_type(key), fp);
1732
0
      r = -1;
1733
0
      goto out;
1734
0
    }
1735
    /*
1736
     * new sid with previously-seen key can happen, e.g. multiple
1737
     * connections to the same host.
1738
     */
1739
0
  }
1740
  /* record new key/sid */
1741
0
  if (e->nsession_ids >= AGENT_MAX_SESSION_IDS) {
1742
0
    error_f("too many session IDs recorded");
1743
0
    r = -1;
1744
0
    goto out;
1745
0
  }
1746
0
  e->session_ids = xrecallocarray(e->session_ids, e->nsession_ids,
1747
0
      e->nsession_ids + 1, sizeof(*e->session_ids));
1748
0
  i = e->nsession_ids++;
1749
0
  debug_f("recorded %s %s (slot %zu of %d)", sshkey_type(key), fp, i,
1750
0
      AGENT_MAX_SESSION_IDS);
1751
0
  e->session_ids[i].key = key;
1752
0
  e->session_ids[i].forwarded = fwd != 0;
1753
0
  key = NULL; /* transferred */
1754
  /* can't transfer sid; it's refcounted and scoped to request's life */
1755
0
  if ((e->session_ids[i].sid = sshbuf_new()) == NULL)
1756
0
    fatal_f("sshbuf_new");
1757
0
  if ((r = sshbuf_putb(e->session_ids[i].sid, sid)) != 0)
1758
0
    fatal_fr(r, "sshbuf_putb session ID");
1759
  /* success */
1760
0
  r = 0;
1761
0
 out:
1762
0
  free(fp);
1763
0
  sshkey_free(key);
1764
0
  sshbuf_free(sid);
1765
0
  sshbuf_free(sig);
1766
0
  return r == 0 ? 1 : 0;
1767
0
}
1768
1769
static void
1770
process_extension(SocketEntry *e)
1771
3
{
1772
3
  int r, success = 0;
1773
3
  char *name;
1774
1775
3
  debug2_f("entering");
1776
3
  if ((r = sshbuf_get_cstring(e->request, &name, NULL)) != 0) {
1777
2
    error_fr(r, "parse");
1778
2
    goto send;
1779
2
  }
1780
1
  if (strcmp(name, "session-bind@openssh.com") == 0)
1781
0
    success = process_ext_session_bind(e);
1782
1
  else
1783
1
    debug_f("unsupported extension \"%s\"", name);
1784
1
  free(name);
1785
3
send:
1786
3
  send_status(e, success);
1787
3
}
1788
/*
1789
 * dispatch incoming message.
1790
 * returns 1 on success, 0 for incomplete messages or -1 on error.
1791
 */
1792
static int
1793
process_message(u_int socknum)
1794
36.6k
{
1795
36.6k
  u_int msg_len;
1796
36.6k
  u_char type;
1797
36.6k
  const u_char *cp;
1798
36.6k
  int r;
1799
36.6k
  SocketEntry *e;
1800
1801
36.6k
  if (socknum >= sockets_alloc)
1802
0
    fatal_f("sock %u >= allocated %u", socknum, sockets_alloc);
1803
36.6k
  e = &sockets[socknum];
1804
1805
36.6k
  if (sshbuf_len(e->input) < 5)
1806
122
    return 0;    /* Incomplete message header. */
1807
36.4k
  cp = sshbuf_ptr(e->input);
1808
36.4k
  msg_len = PEEK_U32(cp);
1809
36.4k
  if (msg_len > AGENT_MAX_LEN) {
1810
163
    debug_f("socket %u (fd=%d) message too long %u > %u",
1811
163
        socknum, e->fd, msg_len, AGENT_MAX_LEN);
1812
163
    return -1;
1813
163
  }
1814
36.3k
  if (sshbuf_len(e->input) < msg_len + 4)
1815
77
    return 0;    /* Incomplete message body. */
1816
1817
  /* move the current input to e->request */
1818
36.2k
  sshbuf_reset(e->request);
1819
36.2k
  if ((r = sshbuf_get_stringb(e->input, e->request)) != 0 ||
1820
36.2k
      (r = sshbuf_get_u8(e->request, &type)) != 0) {
1821
17.3k
    if (r == SSH_ERR_MESSAGE_INCOMPLETE ||
1822
17.3k
        r == SSH_ERR_STRING_TOO_LARGE) {
1823
17.3k
      error_fr(r, "parse");
1824
17.3k
      return -1;
1825
17.3k
    }
1826
17.3k
    fatal_fr(r, "parse");
1827
17.3k
  }
1828
1829
18.8k
  debug_f("socket %u (fd=%d) type %d", socknum, e->fd, type);
1830
1831
  /* check whether agent is locked */
1832
18.8k
  if (locked && type != SSH_AGENTC_UNLOCK) {
1833
12.4k
    sshbuf_reset(e->request);
1834
12.4k
    switch (type) {
1835
7.07k
    case SSH2_AGENTC_REQUEST_IDENTITIES:
1836
      /* send empty lists */
1837
7.07k
      no_identities(e);
1838
7.07k
      break;
1839
5.36k
    default:
1840
      /* send a fail message for all other request types */
1841
5.36k
      send_status(e, 0);
1842
12.4k
    }
1843
12.4k
    return 1;
1844
12.4k
  }
1845
1846
6.43k
  switch (type) {
1847
2
  case SSH_AGENTC_LOCK:
1848
6.34k
  case SSH_AGENTC_UNLOCK:
1849
6.34k
    process_lock_agent(e, type == SSH_AGENTC_LOCK);
1850
6.34k
    break;
1851
1
  case SSH_AGENTC_REMOVE_ALL_RSA_IDENTITIES:
1852
1
    process_remove_all_identities(e); /* safe for !WITH_SSH1 */
1853
1
    break;
1854
  /* ssh2 */
1855
34
  case SSH2_AGENTC_SIGN_REQUEST:
1856
34
    process_sign_request2(e);
1857
34
    break;
1858
4
  case SSH2_AGENTC_REQUEST_IDENTITIES:
1859
4
    process_request_identities(e);
1860
4
    break;
1861
5
  case SSH2_AGENTC_ADD_IDENTITY:
1862
8
  case SSH2_AGENTC_ADD_ID_CONSTRAINED:
1863
8
    process_add_identity(e);
1864
8
    break;
1865
5
  case SSH2_AGENTC_REMOVE_IDENTITY:
1866
5
    process_remove_identity(e);
1867
5
    break;
1868
1
  case SSH2_AGENTC_REMOVE_ALL_IDENTITIES:
1869
1
    process_remove_all_identities(e);
1870
1
    break;
1871
0
#ifdef ENABLE_PKCS11
1872
11
  case SSH_AGENTC_ADD_SMARTCARD_KEY:
1873
17
  case SSH_AGENTC_ADD_SMARTCARD_KEY_CONSTRAINED:
1874
17
    process_add_smartcard_key(e);
1875
17
    break;
1876
20
  case SSH_AGENTC_REMOVE_SMARTCARD_KEY:
1877
20
    process_remove_smartcard_key(e);
1878
20
    break;
1879
0
#endif /* ENABLE_PKCS11 */
1880
3
  case SSH_AGENTC_EXTENSION:
1881
3
    process_extension(e);
1882
3
    break;
1883
4
  default:
1884
    /* Unknown message.  Respond with failure. */
1885
4
    error("Unknown message %d", type);
1886
4
    sshbuf_reset(e->request);
1887
4
    send_status(e, 0);
1888
4
    break;
1889
6.43k
  }
1890
6.43k
  return 1;
1891
6.43k
}
1892
1893
static void
1894
new_socket(sock_type type, int fd)
1895
664
{
1896
664
  u_int i, old_alloc, new_alloc;
1897
1898
664
  debug_f("type = %s", type == AUTH_CONNECTION ? "CONNECTION" :
1899
664
      (type == AUTH_SOCKET ? "SOCKET" : "UNKNOWN"));
1900
664
  set_nonblock(fd);
1901
1902
664
  if (fd > max_fd)
1903
1
    max_fd = fd;
1904
1905
664
  for (i = 0; i < sockets_alloc; i++)
1906
0
    if (sockets[i].type == AUTH_UNUSED) {
1907
0
      sockets[i].fd = fd;
1908
0
      if ((sockets[i].input = sshbuf_new()) == NULL ||
1909
0
          (sockets[i].output = sshbuf_new()) == NULL ||
1910
0
          (sockets[i].request = sshbuf_new()) == NULL)
1911
0
        fatal_f("sshbuf_new failed");
1912
0
      sockets[i].type = type;
1913
0
      return;
1914
0
    }
1915
664
  old_alloc = sockets_alloc;
1916
664
  new_alloc = sockets_alloc + 10;
1917
664
  sockets = xrecallocarray(sockets, old_alloc, new_alloc,
1918
664
      sizeof(sockets[0]));
1919
7.30k
  for (i = old_alloc; i < new_alloc; i++)
1920
6.64k
    sockets[i].type = AUTH_UNUSED;
1921
664
  sockets_alloc = new_alloc;
1922
664
  sockets[old_alloc].fd = fd;
1923
664
  if ((sockets[old_alloc].input = sshbuf_new()) == NULL ||
1924
664
      (sockets[old_alloc].output = sshbuf_new()) == NULL ||
1925
664
      (sockets[old_alloc].request = sshbuf_new()) == NULL)
1926
0
    fatal_f("sshbuf_new failed");
1927
664
  sockets[old_alloc].type = type;
1928
664
}
1929
1930
static int
1931
handle_socket_read(u_int socknum)
1932
0
{
1933
0
  struct sockaddr_un sunaddr;
1934
0
  socklen_t slen;
1935
0
  uid_t euid;
1936
0
  gid_t egid;
1937
0
  int fd;
1938
1939
0
  slen = sizeof(sunaddr);
1940
0
  fd = accept(sockets[socknum].fd, (struct sockaddr *)&sunaddr, &slen);
1941
0
  if (fd == -1) {
1942
0
    error("accept from AUTH_SOCKET: %s", strerror(errno));
1943
0
    return -1;
1944
0
  }
1945
0
  if (getpeereid(fd, &euid, &egid) == -1) {
1946
0
    error("getpeereid %d failed: %s", fd, strerror(errno));
1947
0
    close(fd);
1948
0
    return -1;
1949
0
  }
1950
0
  if ((euid != 0) && (getuid() != euid)) {
1951
0
    error("uid mismatch: peer euid %u != uid %u",
1952
0
        (u_int) euid, (u_int) getuid());
1953
0
    close(fd);
1954
0
    return -1;
1955
0
  }
1956
0
  new_socket(AUTH_CONNECTION, fd);
1957
0
  return 0;
1958
0
}
1959
1960
static int
1961
handle_conn_read(u_int socknum)
1962
0
{
1963
0
  char buf[AGENT_RBUF_LEN];
1964
0
  ssize_t len;
1965
0
  int r;
1966
1967
0
  if ((len = read(sockets[socknum].fd, buf, sizeof(buf))) <= 0) {
1968
0
    if (len == -1) {
1969
0
      if (errno == EAGAIN || errno == EINTR)
1970
0
        return 0;
1971
0
      error_f("read error on socket %u (fd %d): %s",
1972
0
          socknum, sockets[socknum].fd, strerror(errno));
1973
0
    }
1974
0
    return -1;
1975
0
  }
1976
0
  if ((r = sshbuf_put(sockets[socknum].input, buf, len)) != 0)
1977
0
    fatal_fr(r, "compose");
1978
0
  explicit_bzero(buf, sizeof(buf));
1979
0
  for (;;) {
1980
0
    if ((r = process_message(socknum)) == -1)
1981
0
      return -1;
1982
0
    else if (r == 0)
1983
0
      break;
1984
0
  }
1985
0
  return 0;
1986
0
}
1987
1988
static int
1989
handle_conn_write(u_int socknum)
1990
0
{
1991
0
  ssize_t len;
1992
0
  int r;
1993
1994
0
  if (sshbuf_len(sockets[socknum].output) == 0)
1995
0
    return 0; /* shouldn't happen */
1996
0
  if ((len = write(sockets[socknum].fd,
1997
0
      sshbuf_ptr(sockets[socknum].output),
1998
0
      sshbuf_len(sockets[socknum].output))) <= 0) {
1999
0
    if (len == -1) {
2000
0
      if (errno == EAGAIN || errno == EINTR)
2001
0
        return 0;
2002
0
      error_f("read error on socket %u (fd %d): %s",
2003
0
          socknum, sockets[socknum].fd, strerror(errno));
2004
0
    }
2005
0
    return -1;
2006
0
  }
2007
0
  if ((r = sshbuf_consume(sockets[socknum].output, len)) != 0)
2008
0
    fatal_fr(r, "consume");
2009
0
  return 0;
2010
0
}
2011
2012
static void
2013
after_poll(struct pollfd *pfd, size_t npfd, u_int maxfds)
2014
0
{
2015
0
  size_t i;
2016
0
  u_int socknum, activefds = npfd;
2017
2018
0
  for (i = 0; i < npfd; i++) {
2019
0
    if (pfd[i].revents == 0)
2020
0
      continue;
2021
    /* Find sockets entry */
2022
0
    for (socknum = 0; socknum < sockets_alloc; socknum++) {
2023
0
      if (sockets[socknum].type != AUTH_SOCKET &&
2024
0
          sockets[socknum].type != AUTH_CONNECTION)
2025
0
        continue;
2026
0
      if (pfd[i].fd == sockets[socknum].fd)
2027
0
        break;
2028
0
    }
2029
0
    if (socknum >= sockets_alloc) {
2030
0
      error_f("no socket for fd %d", pfd[i].fd);
2031
0
      continue;
2032
0
    }
2033
    /* Process events */
2034
0
    switch (sockets[socknum].type) {
2035
0
    case AUTH_SOCKET:
2036
0
      if ((pfd[i].revents & (POLLIN|POLLERR)) == 0)
2037
0
        break;
2038
0
      if (npfd > maxfds) {
2039
0
        debug3("out of fds (active %u >= limit %u); "
2040
0
            "skipping accept", activefds, maxfds);
2041
0
        break;
2042
0
      }
2043
0
      if (handle_socket_read(socknum) == 0)
2044
0
        activefds++;
2045
0
      break;
2046
0
    case AUTH_CONNECTION:
2047
0
      if ((pfd[i].revents & (POLLIN|POLLHUP|POLLERR)) != 0 &&
2048
0
          handle_conn_read(socknum) != 0)
2049
0
        goto close_sock;
2050
0
      if ((pfd[i].revents & (POLLOUT|POLLHUP)) != 0 &&
2051
0
          handle_conn_write(socknum) != 0) {
2052
0
 close_sock:
2053
0
        if (activefds == 0)
2054
0
          fatal("activefds == 0 at close_sock");
2055
0
        close_socket(&sockets[socknum]);
2056
0
        activefds--;
2057
0
        break;
2058
0
      }
2059
0
      break;
2060
0
    default:
2061
0
      break;
2062
0
    }
2063
0
  }
2064
0
}
2065
2066
static int
2067
prepare_poll(struct pollfd **pfdp, size_t *npfdp, struct timespec *timeoutp, u_int maxfds)
2068
0
{
2069
0
  struct pollfd *pfd = *pfdp;
2070
0
  size_t i, j, npfd = 0;
2071
0
  time_t deadline;
2072
0
  int r;
2073
2074
  /* Count active sockets */
2075
0
  for (i = 0; i < sockets_alloc; i++) {
2076
0
    switch (sockets[i].type) {
2077
0
    case AUTH_SOCKET:
2078
0
    case AUTH_CONNECTION:
2079
0
      npfd++;
2080
0
      break;
2081
0
    case AUTH_UNUSED:
2082
0
      break;
2083
0
    default:
2084
0
      fatal("Unknown socket type %d", sockets[i].type);
2085
0
      break;
2086
0
    }
2087
0
  }
2088
0
  if (npfd != *npfdp &&
2089
0
      (pfd = recallocarray(pfd, *npfdp, npfd, sizeof(*pfd))) == NULL)
2090
0
    fatal_f("recallocarray failed");
2091
0
  *pfdp = pfd;
2092
0
  *npfdp = npfd;
2093
2094
0
  for (i = j = 0; i < sockets_alloc; i++) {
2095
0
    switch (sockets[i].type) {
2096
0
    case AUTH_SOCKET:
2097
0
      if (npfd > maxfds) {
2098
0
        debug3("out of fds (active %zu >= limit %u); "
2099
0
            "skipping arming listener", npfd, maxfds);
2100
0
        break;
2101
0
      }
2102
0
      pfd[j].fd = sockets[i].fd;
2103
0
      pfd[j].revents = 0;
2104
0
      pfd[j].events = POLLIN;
2105
0
      j++;
2106
0
      break;
2107
0
    case AUTH_CONNECTION:
2108
0
      pfd[j].fd = sockets[i].fd;
2109
0
      pfd[j].revents = 0;
2110
      /*
2111
       * Only prepare to read if we can handle a full-size
2112
       * input read buffer and enqueue a max size reply..
2113
       */
2114
0
      if ((r = sshbuf_check_reserve(sockets[i].input,
2115
0
          AGENT_RBUF_LEN)) == 0 &&
2116
0
          (r = sshbuf_check_reserve(sockets[i].output,
2117
0
          AGENT_MAX_LEN)) == 0)
2118
0
        pfd[j].events = POLLIN;
2119
0
      else if (r != SSH_ERR_NO_BUFFER_SPACE)
2120
0
        fatal_fr(r, "reserve");
2121
0
      if (sshbuf_len(sockets[i].output) > 0)
2122
0
        pfd[j].events |= POLLOUT;
2123
0
      j++;
2124
0
      break;
2125
0
    default:
2126
0
      break;
2127
0
    }
2128
0
  }
2129
0
  deadline = reaper();
2130
0
  if (parent_alive_interval != 0)
2131
0
    deadline = (deadline == 0) ? parent_alive_interval :
2132
0
        MINIMUM(deadline, parent_alive_interval);
2133
0
  if (deadline != 0)
2134
0
    ptimeout_deadline_sec(timeoutp, deadline);
2135
0
  return (1);
2136
0
}
2137
2138
static void
2139
cleanup_socket(void)
2140
0
{
2141
0
  if (cleanup_pid != 0 && getpid() != cleanup_pid)
2142
0
    return;
2143
0
  debug_f("cleanup");
2144
0
  if (socket_name[0])
2145
0
    unlink(socket_name);
2146
0
  if (socket_dir[0])
2147
0
    rmdir(socket_dir);
2148
0
}
2149
2150
void
2151
cleanup_exit(int i)
2152
0
{
2153
0
  cleanup_socket();
2154
0
#ifdef ENABLE_PKCS11
2155
0
  pkcs11_terminate();
2156
0
#endif
2157
0
  _exit(i);
2158
0
}
2159
2160
static void
2161
cleanup_handler(int sig)
2162
0
{
2163
0
  signalled_exit = sig;
2164
0
}
2165
2166
static void
2167
keydrop_handler(int sig)
2168
0
{
2169
0
  signalled_keydrop = sig;
2170
0
}
2171
2172
static void
2173
check_parent_exists(void)
2174
0
{
2175
  /*
2176
   * If our parent has exited then getppid() will return (pid_t)1,
2177
   * so testing for that should be safe.
2178
   */
2179
0
  if (parent_pid != -1 && getppid() != parent_pid) {
2180
    /* printf("Parent has died - Authentication agent exiting.\n"); */
2181
0
    cleanup_socket();
2182
0
    _exit(2);
2183
0
  }
2184
0
}
2185
2186
static void
2187
usage(void)
2188
0
{
2189
0
  fprintf(stderr,
2190
0
      "usage: ssh-agent [-c | -s] [-DdTU] [-a bind_address] [-E fingerprint_hash]\n"
2191
0
      "                 [-O option] [-P allowed_providers] [-t life]\n"
2192
0
      "       ssh-agent [-TU] [-a bind_address] [-E fingerprint_hash] [-O option]\n"
2193
0
      "                 [-P allowed_providers] [-t life] command [arg ...]\n"
2194
0
      "       ssh-agent [-c | -s] -k\n"
2195
0
      "       ssh-agent -u\n");
2196
0
  exit(1);
2197
0
}
2198
2199
int
2200
main(int ac, char **av)
2201
0
{
2202
0
  int c_flag = 0, d_flag = 0, D_flag = 0, k_flag = 0;
2203
0
  int s_flag = 0, T_flag = 0, u_flag = 0, U_flag = 0;
2204
0
  int sock = -1, ch, result, saved_errno;
2205
0
  char *homedir = NULL, *shell, *format, *pidstr, *agentsocket = NULL;
2206
0
  char *fdstr;
2207
0
  const char *errstr = NULL;
2208
0
  const char *ccp;
2209
0
#ifdef HAVE_SETRLIMIT
2210
0
  struct rlimit rlim;
2211
0
#endif
2212
0
  extern int optind;
2213
0
  extern char *optarg;
2214
0
  pid_t pid;
2215
0
  char pidstrbuf[1 + 3 * sizeof pid];
2216
0
  size_t len;
2217
0
  mode_t prev_mask;
2218
0
  struct timespec timeout;
2219
0
  struct pollfd *pfd = NULL;
2220
0
  size_t npfd = 0;
2221
0
  u_int maxfds;
2222
0
  sigset_t nsigset, osigset;
2223
0
  int socket_activated = 0;
2224
2225
  /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
2226
0
  sanitise_stdfd();
2227
2228
  /* drop */
2229
0
  (void)setegid(getgid());
2230
0
  (void)setgid(getgid());
2231
2232
0
  platform_disable_tracing(0);  /* strict=no */
2233
2234
0
#ifdef RLIMIT_NOFILE
2235
0
  if (getrlimit(RLIMIT_NOFILE, &rlim) == -1)
2236
0
    fatal("%s: getrlimit: %s", __progname, strerror(errno));
2237
0
#endif
2238
2239
0
  __progname = ssh_get_progname(av[0]);
2240
0
  seed_rng();
2241
2242
0
  while ((ch = getopt(ac, av, "cDdksTuUE:a:O:P:t:")) != -1) {
2243
0
    switch (ch) {
2244
0
    case 'E':
2245
0
      fingerprint_hash = ssh_digest_alg_by_name(optarg);
2246
0
      if (fingerprint_hash == -1)
2247
0
        fatal("Invalid hash algorithm \"%s\"", optarg);
2248
0
      break;
2249
0
    case 'c':
2250
0
      if (s_flag)
2251
0
        usage();
2252
0
      c_flag++;
2253
0
      break;
2254
0
    case 'k':
2255
0
      k_flag++;
2256
0
      break;
2257
0
    case 'O':
2258
0
      if (strcmp(optarg, "no-restrict-websafe") == 0)
2259
0
        restrict_websafe = 0;
2260
0
      else if (strcmp(optarg, "allow-remote-pkcs11") == 0)
2261
0
        remote_add_provider = 1;
2262
0
      else if ((ccp = strprefix(optarg,
2263
0
          "websafe-allow=", 0)) != NULL) {
2264
0
        if (websafe_allowlist != NULL)
2265
0
          fatal("websafe-allow already set");
2266
0
        websafe_allowlist = xstrdup(ccp);
2267
0
      } else
2268
0
        fatal("Unknown -O option");
2269
0
      break;
2270
0
    case 'P':
2271
0
      if (allowed_providers != NULL)
2272
0
        fatal("-P option already specified");
2273
0
      allowed_providers = xstrdup(optarg);
2274
0
      break;
2275
0
    case 's':
2276
0
      if (c_flag)
2277
0
        usage();
2278
0
      s_flag++;
2279
0
      break;
2280
0
    case 'd':
2281
0
      if (d_flag || D_flag)
2282
0
        usage();
2283
0
      d_flag++;
2284
0
      break;
2285
0
    case 'D':
2286
0
      if (d_flag || D_flag)
2287
0
        usage();
2288
0
      D_flag++;
2289
0
      break;
2290
0
    case 'a':
2291
0
      agentsocket = optarg;
2292
0
      break;
2293
0
    case 't':
2294
0
      if ((lifetime = convtime(optarg)) == -1) {
2295
0
        fprintf(stderr, "Invalid lifetime\n");
2296
0
        usage();
2297
0
      }
2298
0
      break;
2299
0
    case 'T':
2300
0
      T_flag++;
2301
0
      break;
2302
0
    case 'u':
2303
0
      u_flag++;
2304
0
      break;
2305
0
    case 'U':
2306
0
      U_flag++;
2307
0
      break;
2308
0
    default:
2309
0
      usage();
2310
0
    }
2311
0
  }
2312
0
  ac -= optind;
2313
0
  av += optind;
2314
2315
0
  if (ac > 0 &&
2316
0
      (c_flag || k_flag || s_flag || d_flag || D_flag || u_flag))
2317
0
    usage();
2318
2319
0
  log_init(__progname,
2320
0
      d_flag ? SYSLOG_LEVEL_DEBUG3 : SYSLOG_LEVEL_INFO,
2321
0
      SYSLOG_FACILITY_AUTH, 1);
2322
2323
0
  if (allowed_providers == NULL)
2324
0
    allowed_providers = xstrdup(DEFAULT_ALLOWED_PROVIDERS);
2325
0
  if (websafe_allowlist == NULL)
2326
0
    websafe_allowlist = xstrdup(DEFAULT_WEBSAFE_ALLOWLIST);
2327
2328
0
  if (ac == 0 && !c_flag && !s_flag) {
2329
0
    shell = getenv("SHELL");
2330
0
    if (shell != NULL && (len = strlen(shell)) > 2 &&
2331
0
        strncmp(shell + len - 3, "csh", 3) == 0)
2332
0
      c_flag = 1;
2333
0
  }
2334
0
  if (k_flag) {
2335
0
    pidstr = getenv(SSH_AGENTPID_ENV_NAME);
2336
0
    if (pidstr == NULL) {
2337
0
      fprintf(stderr, "%s not set, cannot kill agent\n",
2338
0
          SSH_AGENTPID_ENV_NAME);
2339
0
      exit(1);
2340
0
    }
2341
0
    pid = (int)strtonum(pidstr, 2, INT_MAX, &errstr);
2342
0
    if (errstr) {
2343
0
      fprintf(stderr,
2344
0
          "%s=\"%s\", which is not a good PID: %s\n",
2345
0
          SSH_AGENTPID_ENV_NAME, pidstr, errstr);
2346
0
      exit(1);
2347
0
    }
2348
0
    if (kill(pid, SIGTERM) == -1) {
2349
0
      perror("kill");
2350
0
      exit(1);
2351
0
    }
2352
0
    format = c_flag ? "unsetenv %s;\n" : "unset %s;\n";
2353
0
    printf(format, SSH_AUTHSOCKET_ENV_NAME);
2354
0
    printf(format, SSH_AGENTPID_ENV_NAME);
2355
0
    printf("echo Agent pid %ld killed;\n", (long)pid);
2356
0
    exit(0);
2357
0
  }
2358
0
  if (u_flag) {
2359
0
    if ((homedir = get_homedir()) == NULL)
2360
0
      fatal("Couldn't determine home directory");
2361
0
    agent_cleanup_stale(homedir, u_flag > 1);
2362
0
    printf("Deleted stale agent sockets in ~/%s\n",
2363
0
        _PATH_SSH_AGENT_SOCKET_DIR);
2364
0
    exit(0);
2365
0
  }
2366
2367
  /*
2368
   * Minimum file descriptors:
2369
   * stdio (3) + listener (1) + syslog (1 maybe) + connection (1) +
2370
   * a few spare for libc / stack protectors / sanitisers, etc.
2371
   */
2372
0
#define SSH_AGENT_MIN_FDS (3+1+1+1+4)
2373
0
  if (rlim.rlim_cur < SSH_AGENT_MIN_FDS)
2374
0
    fatal("%s: file descriptor rlimit %lld too low (minimum %u)",
2375
0
        __progname, (long long)rlim.rlim_cur, SSH_AGENT_MIN_FDS);
2376
0
  maxfds = rlim.rlim_cur - SSH_AGENT_MIN_FDS;
2377
2378
0
  parent_pid = getpid();
2379
2380
  /* Has the socket been provided via socket activation? */
2381
0
  if (agentsocket == NULL && ac == 0 && (d_flag || D_flag) &&
2382
0
      (pidstr = getenv("LISTEN_PID")) != NULL &&
2383
0
      (fdstr = getenv("LISTEN_FDS")) != NULL) {
2384
0
    if (strcmp(fdstr, "1") != 0) {
2385
0
      fatal("unexpected LISTEN_FDS contents "
2386
0
          "(want: \"1\" got\"%s\"", fdstr);
2387
0
    }
2388
0
    if (fcntl(3, F_GETFL) == -1)
2389
0
      fatal("LISTEN_FDS set but fd 3 unavailable");
2390
0
    pid = (int)strtonum(pidstr, 1, INT_MAX, &errstr);
2391
0
    if (errstr != NULL)
2392
0
      fatal("invalid LISTEN_PID: %s", errstr);
2393
0
    if (pid != getpid())
2394
0
      fatal("bad LISTEN_PID: %d vs pid %d", pid, getpid());
2395
0
    debug("using socket activation on fd=3");
2396
0
    sock = 3;
2397
0
    socket_activated = 1;
2398
0
  }
2399
2400
0
  if (sock == -1 && agentsocket == NULL && !T_flag) {
2401
    /* Default case: ~/.ssh/agent/[socket] */
2402
0
    if ((homedir = get_homedir()) == NULL)
2403
0
      fatal("Couldn't determine home directory");
2404
0
    if (!U_flag)
2405
0
      agent_cleanup_stale(homedir, 0);
2406
0
    if (agent_listener(homedir, "agent", &sock, &agentsocket) != 0)
2407
0
      fatal_f("Couldn't prepare agent socket");
2408
0
    if (strlcpy(socket_name, agentsocket,
2409
0
        sizeof(socket_name)) >= sizeof(socket_name)) {
2410
0
      fatal_f("Socket path \"%s\" too long",
2411
0
          agentsocket);
2412
0
    }
2413
0
    free(homedir);
2414
0
    free(agentsocket);
2415
0
    agentsocket = NULL;
2416
0
  } else if (sock == -1) {
2417
0
    if (T_flag) {
2418
      /*
2419
       * Create private directory for agent socket
2420
       * in $TMPDIR.
2421
       */
2422
0
      mktemp_proto(socket_dir, sizeof(socket_dir));
2423
0
      if (mkdtemp(socket_dir) == NULL) {
2424
0
        perror("mkdtemp: private socket dir");
2425
0
        exit(1);
2426
0
      }
2427
0
      snprintf(socket_name, sizeof(socket_name),
2428
0
          "%s/agent.%ld", socket_dir, (long)parent_pid);
2429
0
    } else {
2430
      /* Try to use specified agent socket */
2431
0
      socket_dir[0] = '\0';
2432
0
      if (strlcpy(socket_name, agentsocket,
2433
0
         sizeof(socket_name)) >= sizeof(socket_name)) {
2434
0
        fatal_f("Socket path \"%s\" too long",
2435
0
            agentsocket);
2436
0
      }
2437
0
    }
2438
    /* Listen on socket */
2439
0
    prev_mask = umask(0177);
2440
0
    if ((sock = unix_listener(socket_name,
2441
0
        SSH_LISTEN_BACKLOG, 0)) < 0) {
2442
0
      *socket_name = '\0'; /* Don't unlink existing file */
2443
0
      cleanup_exit(1);
2444
0
    }
2445
0
    umask(prev_mask);
2446
0
  }
2447
2448
0
  closefrom(sock == -1 ? STDERR_FILENO + 1 : sock + 1);
2449
2450
  /*
2451
   * Create socket early so it will exist before command gets run from
2452
   * the parent.
2453
   */
2454
0
  if (sock == -1) {
2455
0
    prev_mask = umask(0177);
2456
0
    sock = unix_listener(socket_name, SSH_LISTEN_BACKLOG, 0);
2457
0
    if (sock < 0) {
2458
      /* XXX - unix_listener() calls error() not perror() */
2459
0
      *socket_name = '\0'; /* Don't unlink existing file */
2460
0
      cleanup_exit(1);
2461
0
    }
2462
0
    umask(prev_mask);
2463
0
  }
2464
2465
  /*
2466
   * Fork, and have the parent execute the command, if any, or present
2467
   * the socket data.  The child continues as the authentication agent.
2468
   */
2469
0
  if (D_flag || d_flag) {
2470
0
    log_init(__progname,
2471
0
        d_flag ? SYSLOG_LEVEL_DEBUG3 : SYSLOG_LEVEL_INFO,
2472
0
        SYSLOG_FACILITY_AUTH, 1);
2473
0
    if (socket_name[0] != '\0') {
2474
0
      format = c_flag ?
2475
0
          "setenv %s %s;\n" : "%s=%s; export %s;\n";
2476
0
      printf(format, SSH_AUTHSOCKET_ENV_NAME, socket_name,
2477
0
          SSH_AUTHSOCKET_ENV_NAME);
2478
0
      printf("echo Agent pid %ld;\n", (long)parent_pid);
2479
0
      fflush(stdout);
2480
0
    }
2481
0
    goto skip;
2482
0
  }
2483
0
  pid = fork();
2484
0
  if (pid == -1) {
2485
0
    perror("fork");
2486
0
    cleanup_exit(1);
2487
0
  }
2488
0
  if (pid != 0) {   /* Parent - execute the given command. */
2489
0
    close(sock);
2490
0
    snprintf(pidstrbuf, sizeof pidstrbuf, "%ld", (long)pid);
2491
0
    if (ac == 0) {
2492
0
      format = c_flag ? "setenv %s %s;\n" : "%s=%s; export %s;\n";
2493
0
      printf(format, SSH_AUTHSOCKET_ENV_NAME, socket_name,
2494
0
          SSH_AUTHSOCKET_ENV_NAME);
2495
0
      printf(format, SSH_AGENTPID_ENV_NAME, pidstrbuf,
2496
0
          SSH_AGENTPID_ENV_NAME);
2497
0
      printf("echo Agent pid %ld;\n", (long)pid);
2498
0
      exit(0);
2499
0
    }
2500
0
    if (setenv(SSH_AUTHSOCKET_ENV_NAME, socket_name, 1) == -1 ||
2501
0
        setenv(SSH_AGENTPID_ENV_NAME, pidstrbuf, 1) == -1) {
2502
0
      perror("setenv");
2503
0
      exit(1);
2504
0
    }
2505
0
    execvp(av[0], av);
2506
0
    perror(av[0]);
2507
0
    exit(1);
2508
0
  }
2509
  /* child */
2510
0
  log_init(__progname, SYSLOG_LEVEL_INFO, SYSLOG_FACILITY_AUTH, 0);
2511
2512
0
  if (setsid() == -1) {
2513
0
    error("setsid: %s", strerror(errno));
2514
0
    cleanup_exit(1);
2515
0
  }
2516
2517
0
  (void)chdir("/");
2518
0
  if (stdfd_devnull(1, 1, 1) == -1)
2519
0
    error_f("stdfd_devnull failed");
2520
2521
0
#ifdef HAVE_SETRLIMIT
2522
  /* deny core dumps, since memory contains unencrypted private keys */
2523
0
  rlim.rlim_cur = rlim.rlim_max = 0;
2524
0
  if (setrlimit(RLIMIT_CORE, &rlim) == -1) {
2525
0
    error("setrlimit RLIMIT_CORE: %s", strerror(errno));
2526
0
    cleanup_exit(1);
2527
0
  }
2528
0
#endif
2529
2530
0
skip:
2531
2532
0
  cleanup_pid = getpid();
2533
2534
0
#ifdef ENABLE_PKCS11
2535
0
  pkcs11_init(0);
2536
0
#endif
2537
0
  new_socket(AUTH_SOCKET, sock);
2538
0
  if (ac > 0)
2539
0
    parent_alive_interval = 10;
2540
0
  idtab_init();
2541
0
  ssh_signal(SIGPIPE, SIG_IGN);
2542
0
  ssh_signal(SIGINT, (d_flag | D_flag) ? cleanup_handler : SIG_IGN);
2543
0
  ssh_signal(SIGHUP, cleanup_handler);
2544
0
  ssh_signal(SIGTERM, cleanup_handler);
2545
0
  ssh_signal(SIGUSR1, keydrop_handler);
2546
2547
0
  sigemptyset(&nsigset);
2548
0
  sigaddset(&nsigset, SIGINT);
2549
0
  sigaddset(&nsigset, SIGHUP);
2550
0
  sigaddset(&nsigset, SIGTERM);
2551
0
  sigaddset(&nsigset, SIGUSR1);
2552
2553
0
  if (pledge("stdio rpath cpath unix id proc exec", NULL) == -1)
2554
0
    fatal("%s: pledge: %s", __progname, strerror(errno));
2555
0
  platform_pledge_agent();
2556
2557
0
  while (1) {
2558
0
    sigprocmask(SIG_BLOCK, &nsigset, &osigset);
2559
0
    if (signalled_exit != 0) {
2560
0
      logit("exiting on signal %d", (int)signalled_exit);
2561
0
      cleanup_exit((signalled_exit == SIGTERM &&
2562
0
          socket_activated) ? 0 : 2);
2563
0
    }
2564
0
    if (signalled_keydrop) {
2565
0
      logit("signal %d received; removing all keys",
2566
0
          (int)signalled_keydrop);
2567
0
      remove_all_identities();
2568
0
      signalled_keydrop = 0;
2569
0
    }
2570
0
    ptimeout_init(&timeout);
2571
0
    prepare_poll(&pfd, &npfd, &timeout, maxfds);
2572
0
    result = ppoll(pfd, npfd, ptimeout_get_tsp(&timeout), &osigset);
2573
0
    sigprocmask(SIG_SETMASK, &osigset, NULL);
2574
0
    saved_errno = errno;
2575
0
    if (parent_alive_interval != 0)
2576
0
      check_parent_exists();
2577
0
    (void) reaper();  /* remove expired keys */
2578
0
    if (result == -1) {
2579
0
      if (saved_errno == EINTR)
2580
0
        continue;
2581
0
      fatal("poll: %s", strerror(saved_errno));
2582
0
    } else if (result > 0)
2583
0
      after_poll(pfd, npfd, maxfds);
2584
0
  }
2585
  /* NOTREACHED */
2586
0
}