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