Coverage Report

Created: 2025-10-28 06:17

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