Coverage Report

Created: 2026-08-13 07:14

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