1 /* $OpenBSD: ssh-agent.c,v 1.300 2023/07/19 13:56:33 djm Exp $ */
3 * Author: Tatu Ylonen <ylo@cs.hut.fi>
4 * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
6 * The authentication agent program.
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".
14 * Copyright (c) 2000, 2001 Markus Friedl. All rights reserved.
16 * Redistribution and use in source and binary forms, with or without
17 * modification, are permitted provided that the following conditions
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.
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.
39 #include <sys/types.h>
40 #include <sys/resource.h>
42 #include <sys/socket.h>
44 #ifdef HAVE_SYS_TIME_H
45 # include <sys/time.h>
50 #include "openbsd-compat/sys-queue.h"
53 #include <openssl/evp.h>
54 #include "openbsd-compat/openssl-compat.h"
89 #include "pathnames.h"
90 #include "ssh-pkcs11.h"
92 #include "myproposal.h"
94 #ifndef DEFAULT_ALLOWED_PROVIDERS
95 # define DEFAULT_ALLOWED_PROVIDERS "/usr/lib*/*,/usr/local/lib*/*"
98 /* Maximum accepted message length */
99 #define AGENT_MAX_LEN (256*1024)
100 /* Maximum bytes to read from client socket */
101 #define AGENT_RBUF_LEN (4096)
102 /* Maximum number of recorded session IDs/hostkeys per connection */
103 #define AGENT_MAX_SESSION_IDS 16
104 /* Maximum size of session ID */
105 #define AGENT_MAX_SID_LEN 128
106 /* Maximum number of destination constraints to accept on a key */
107 #define AGENT_MAX_DEST_CONSTRAINTS 1024
109 /* XXX store hostkey_sid in a refcounted tree */
123 typedef struct socket_entry {
126 struct sshbuf *input;
127 struct sshbuf *output;
128 struct sshbuf *request;
130 struct hostkey_sid *session_ids;
133 u_int sockets_alloc = 0;
134 SocketEntry *sockets = NULL;
136 typedef struct identity {
137 TAILQ_ENTRY(identity) next;
144 struct dest_constraint *dest_constraints;
145 size_t ndest_constraints;
150 TAILQ_HEAD(idqueue, identity) idlist;
153 /* private key table */
154 struct idtable *idtab;
158 /* pid of shell == parent of agent */
159 pid_t parent_pid = -1;
160 time_t parent_alive_interval = 0;
162 /* pid of process for which cleanup_socket is applicable */
163 pid_t cleanup_pid = 0;
165 /* pathname and directory for AUTH_SOCKET */
166 char socket_name[PATH_MAX];
167 char socket_dir[PATH_MAX];
169 /* Pattern-list of allowed PKCS#11/Security key paths */
170 static char *allowed_providers;
173 * Allows PKCS11 providers or SK keys that use non-internal providers to
174 * be added over a remote connection (identified by session-bind@openssh.com).
176 static int remote_add_provider;
180 #define LOCK_SALT_SIZE 16
181 #define LOCK_ROUNDS 1
183 u_char lock_pwhash[LOCK_SIZE];
184 u_char lock_salt[LOCK_SALT_SIZE];
186 extern char *__progname;
188 /* Default lifetime in seconds (0 == forever) */
189 static int lifetime = 0;
191 static int fingerprint_hash = SSH_FP_HASH_DEFAULT;
193 /* Refuse signing of non-SSH messages for web-origin FIDO keys */
194 static int restrict_websafe = 1;
197 * Client connection count; incremented in new_socket() and decremented in
198 * close_socket(). When it reaches 0, ssh-agent will exit. Since it is
199 * normally initialized to 1, it will never reach 0. However, if the -x
200 * option is specified, it is initialized to 0 in main(); in that case,
201 * ssh-agent will exit as soon as it has had at least one client but no
204 static int xcount = 1;
207 close_socket(SocketEntry *e)
212 if (e->type == AUTH_CONNECTION) {
213 debug("xcount %d -> %d", xcount, xcount - 1);
218 sshbuf_free(e->input);
219 sshbuf_free(e->output);
220 sshbuf_free(e->request);
221 for (i = 0; i < e->nsession_ids; i++) {
222 sshkey_free(e->session_ids[i].key);
223 sshbuf_free(e->session_ids[i].sid);
225 free(e->session_ids);
226 memset(e, '\0', sizeof(*e));
228 e->type = AUTH_UNUSED;
236 idtab = xcalloc(1, sizeof(*idtab));
237 TAILQ_INIT(&idtab->idlist);
242 free_dest_constraint_hop(struct dest_constraint_hop *dch)
250 for (i = 0; i < dch->nkeys; i++)
251 sshkey_free(dch->keys[i]);
253 free(dch->key_is_ca);
257 free_dest_constraints(struct dest_constraint *dcs, size_t ndcs)
261 for (i = 0; i < ndcs; i++) {
262 free_dest_constraint_hop(&dcs[i].from);
263 free_dest_constraint_hop(&dcs[i].to);
269 free_identity(Identity *id)
271 sshkey_free(id->key);
274 free(id->sk_provider);
275 free_dest_constraints(id->dest_constraints, id->ndest_constraints);
280 * Match 'key' against the key/CA list in a destination constraint hop
281 * Returns 0 on success or -1 otherwise.
284 match_key_hop(const char *tag, const struct sshkey *key,
285 const struct dest_constraint_hop *dch)
287 const char *reason = NULL;
288 const char *hostname = dch->hostname ? dch->hostname : "(ORIGIN)";
295 if ((fp = sshkey_fingerprint(key, SSH_FP_HASH_DEFAULT,
296 SSH_FP_DEFAULT)) == NULL)
297 fatal_f("fingerprint failed");
298 debug3_f("%s: entering hostname %s, requested key %s %s, %u keys avail",
299 tag, hostname, sshkey_type(key), fp, dch->nkeys);
301 for (i = 0; i < dch->nkeys; i++) {
302 if (dch->keys[i] == NULL)
305 if ((fp = sshkey_fingerprint(dch->keys[i], SSH_FP_HASH_DEFAULT,
306 SSH_FP_DEFAULT)) == NULL)
307 fatal_f("fingerprint failed");
308 debug3_f("%s: key %u: %s%s %s", tag, i,
309 dch->key_is_ca[i] ? "CA " : "",
310 sshkey_type(dch->keys[i]), fp);
312 if (!sshkey_is_cert(key)) {
314 if (dch->key_is_ca[i] ||
315 !sshkey_equal(key, dch->keys[i]))
320 if (!dch->key_is_ca[i])
322 if (key->cert == NULL || key->cert->signature_key == NULL)
323 return -1; /* shouldn't happen */
324 if (!sshkey_equal(key->cert->signature_key, dch->keys[i]))
326 if (sshkey_cert_check_host(key, hostname, 1,
327 SSH_ALLOWED_CA_SIGALGS, &reason) != 0) {
328 debug_f("cert %s / hostname %s rejected: %s",
329 key->cert->key_id, hostname, reason);
337 /* Check destination constraints on an identity against the hostkey/user */
339 permitted_by_dest_constraints(const struct sshkey *fromkey,
340 const struct sshkey *tokey, Identity *id, const char *user,
341 const char **hostnamep)
344 struct dest_constraint *d;
346 if (hostnamep != NULL)
348 for (i = 0; i < id->ndest_constraints; i++) {
349 d = id->dest_constraints + i;
350 /* XXX remove logspam */
351 debug2_f("constraint %zu %s%s%s (%u keys) > %s%s%s (%u keys)",
352 i, d->from.user ? d->from.user : "",
353 d->from.user ? "@" : "",
354 d->from.hostname ? d->from.hostname : "(ORIGIN)",
356 d->to.user ? d->to.user : "", d->to.user ? "@" : "",
357 d->to.hostname ? d->to.hostname : "(ANY)", d->to.nkeys);
359 /* Match 'from' key */
360 if (fromkey == NULL) {
361 /* We are matching the first hop */
362 if (d->from.hostname != NULL || d->from.nkeys != 0)
364 } else if (match_key_hop("from", fromkey, &d->from) != 0)
368 if (tokey != NULL && match_key_hop("to", tokey, &d->to) != 0)
371 /* Match user if specified */
372 if (d->to.user != NULL && user != NULL &&
373 !match_pattern(user, d->to.user))
376 /* successfully matched this constraint */
377 if (hostnamep != NULL)
378 *hostnamep = d->to.hostname;
379 debug2_f("allowed for hostname %s",
380 d->to.hostname == NULL ? "*" : d->to.hostname);
384 debug2_f("%s identity \"%s\" not permitted for this destination",
385 sshkey_type(id->key), id->comment);
390 * Check whether hostkeys on a SocketEntry and the optionally specified user
391 * are permitted by the destination constraints on the Identity.
392 * Returns 0 on success or -1 otherwise.
395 identity_permitted(Identity *id, SocketEntry *e, char *user,
396 const char **forward_hostnamep, const char **last_hostnamep)
400 struct hostkey_sid *hks;
401 const struct sshkey *fromkey = NULL;
402 const char *test_user;
405 /* XXX remove logspam */
406 debug3_f("entering: key %s comment \"%s\", %zu socket bindings, "
407 "%zu constraints", sshkey_type(id->key), id->comment,
408 e->nsession_ids, id->ndest_constraints);
409 if (id->ndest_constraints == 0)
410 return 0; /* unconstrained */
411 if (e->nsession_ids == 0)
412 return 0; /* local use */
414 * Walk through the hops recorded by session_id and try to find a
415 * constraint that satisfies each.
417 for (i = 0; i < e->nsession_ids; i++) {
418 hks = e->session_ids + i;
419 if (hks->key == NULL)
420 fatal_f("internal error: no bound key");
421 /* XXX remove logspam */
423 if (fromkey != NULL &&
424 (fp1 = sshkey_fingerprint(fromkey, SSH_FP_HASH_DEFAULT,
425 SSH_FP_DEFAULT)) == NULL)
426 fatal_f("fingerprint failed");
427 if ((fp2 = sshkey_fingerprint(hks->key, SSH_FP_HASH_DEFAULT,
428 SSH_FP_DEFAULT)) == NULL)
429 fatal_f("fingerprint failed");
430 debug3_f("socketentry fd=%d, entry %zu %s, "
431 "from hostkey %s %s to user %s hostkey %s %s",
432 e->fd, i, hks->forwarded ? "FORWARD" : "AUTH",
433 fromkey ? sshkey_type(fromkey) : "(ORIGIN)",
434 fromkey ? fp1 : "", user ? user : "(ANY)",
435 sshkey_type(hks->key), fp2);
439 * Record the hostnames for the initial forwarding and
440 * the final destination.
443 if (i == e->nsession_ids - 1)
446 hp = forward_hostnamep;
447 /* Special handling for final recorded binding */
449 if (i == e->nsession_ids - 1) {
450 /* Can only check user at final hop */
453 * user is only presented for signature requests.
454 * If this is the case, make sure last binding is not
457 if (hks->forwarded && user != NULL) {
458 error_f("tried to sign on forwarding hop");
461 } else if (!hks->forwarded) {
462 error_f("tried to forward though signing bind");
465 if (permitted_by_dest_constraints(fromkey, hks->key, id,
471 * Another special case: if the last bound session ID was for a
472 * forwarding, and this function is not being called to check a sign
473 * request (i.e. no 'user' supplied), then only permit the key if
474 * there is a permission that would allow it to be used at another
475 * destination. This hides keys that are allowed to be used to
476 * authenticate *to* a host but not permitted for *use* beyond it.
478 hks = &e->session_ids[e->nsession_ids - 1];
479 if (hks->forwarded && user == NULL &&
480 permitted_by_dest_constraints(hks->key, NULL, id,
482 debug3_f("key permitted at host but not after");
490 /* return matching private key for given public key */
492 lookup_identity(struct sshkey *key)
496 TAILQ_FOREACH(id, &idtab->idlist, next) {
497 if (sshkey_equal(key, id->key))
503 /* Check confirmation of keysign request */
505 confirm_key(Identity *id, const char *extra)
510 p = sshkey_fingerprint(id->key, fingerprint_hash, SSH_FP_DEFAULT);
512 ask_permission("Allow use of key %s?\nKey fingerprint %s.%s%s",
514 extra == NULL ? "" : "\n", extra == NULL ? "" : extra))
522 send_status(SocketEntry *e, int success)
526 if ((r = sshbuf_put_u32(e->output, 1)) != 0 ||
527 (r = sshbuf_put_u8(e->output, success ?
528 SSH_AGENT_SUCCESS : SSH_AGENT_FAILURE)) != 0)
529 fatal_fr(r, "compose");
532 /* send list of supported public keys to 'client' */
534 process_request_identities(SocketEntry *e)
537 struct sshbuf *msg, *keys;
541 debug2_f("entering");
543 if ((msg = sshbuf_new()) == NULL || (keys = sshbuf_new()) == NULL)
544 fatal_f("sshbuf_new failed");
545 TAILQ_FOREACH(id, &idtab->idlist, next) {
546 /* identity not visible, don't include in response */
547 if (identity_permitted(id, e, NULL, NULL, NULL) != 0)
549 if ((r = sshkey_puts_opts(id->key, keys,
550 SSHKEY_SERIALIZE_INFO)) != 0 ||
551 (r = sshbuf_put_cstring(keys, id->comment)) != 0) {
552 error_fr(r, "compose key/comment");
557 debug2_f("replying with %u allowed of %u available keys",
558 nentries, idtab->nentries);
559 if ((r = sshbuf_put_u8(msg, SSH2_AGENT_IDENTITIES_ANSWER)) != 0 ||
560 (r = sshbuf_put_u32(msg, nentries)) != 0 ||
561 (r = sshbuf_putb(msg, keys)) != 0)
562 fatal_fr(r, "compose");
563 if ((r = sshbuf_put_stringb(e->output, msg)) != 0)
564 fatal_fr(r, "enqueue");
571 agent_decode_alg(struct sshkey *key, u_int flags)
573 if (key->type == KEY_RSA) {
574 if (flags & SSH_AGENT_RSA_SHA2_256)
575 return "rsa-sha2-256";
576 else if (flags & SSH_AGENT_RSA_SHA2_512)
577 return "rsa-sha2-512";
578 } else if (key->type == KEY_RSA_CERT) {
579 if (flags & SSH_AGENT_RSA_SHA2_256)
580 return "rsa-sha2-256-cert-v01@openssh.com";
581 else if (flags & SSH_AGENT_RSA_SHA2_512)
582 return "rsa-sha2-512-cert-v01@openssh.com";
588 * Attempt to parse the contents of a buffer as a SSH publickey userauth
589 * request, checking its contents for consistency and matching the embedded
590 * key against the one that is being used for signing.
591 * Note: does not modify msg buffer.
592 * Optionally extract the username, session ID and/or hostkey from the request.
595 parse_userauth_request(struct sshbuf *msg, const struct sshkey *expected_key,
596 char **userp, struct sshbuf **sess_idp, struct sshkey **hostkeyp)
598 struct sshbuf *b = NULL, *sess_id = NULL;
599 char *user = NULL, *service = NULL, *method = NULL, *pkalg = NULL;
601 u_char t, sig_follows;
602 struct sshkey *mkey = NULL, *hostkey = NULL;
606 if (sess_idp != NULL)
608 if (hostkeyp != NULL)
610 if ((b = sshbuf_fromb(msg)) == NULL)
611 fatal_f("sshbuf_fromb");
613 /* SSH userauth request */
614 if ((r = sshbuf_froms(b, &sess_id)) != 0)
616 if (sshbuf_len(sess_id) == 0) {
617 r = SSH_ERR_INVALID_FORMAT;
620 if ((r = sshbuf_get_u8(b, &t)) != 0 || /* SSH2_MSG_USERAUTH_REQUEST */
621 (r = sshbuf_get_cstring(b, &user, NULL)) != 0 || /* server user */
622 (r = sshbuf_get_cstring(b, &service, NULL)) != 0 || /* service */
623 (r = sshbuf_get_cstring(b, &method, NULL)) != 0 || /* method */
624 (r = sshbuf_get_u8(b, &sig_follows)) != 0 || /* sig-follows */
625 (r = sshbuf_get_cstring(b, &pkalg, NULL)) != 0 || /* alg */
626 (r = sshkey_froms(b, &mkey)) != 0) /* key */
628 if (t != SSH2_MSG_USERAUTH_REQUEST ||
630 strcmp(service, "ssh-connection") != 0 ||
631 !sshkey_equal(expected_key, mkey) ||
632 sshkey_type_from_name(pkalg) != expected_key->type) {
633 r = SSH_ERR_INVALID_FORMAT;
636 if (strcmp(method, "publickey-hostbound-v00@openssh.com") == 0) {
637 if ((r = sshkey_froms(b, &hostkey)) != 0)
639 } else if (strcmp(method, "publickey") != 0) {
640 r = SSH_ERR_INVALID_FORMAT;
643 if (sshbuf_len(b) != 0) {
644 r = SSH_ERR_INVALID_FORMAT;
649 debug3_f("well formed userauth");
654 if (sess_idp != NULL) {
658 if (hostkeyp != NULL) {
664 sshbuf_free(sess_id);
670 sshkey_free(hostkey);
675 * Attempt to parse the contents of a buffer as a SSHSIG signature request.
676 * Note: does not modify buffer.
679 parse_sshsig_request(struct sshbuf *msg)
684 if ((b = sshbuf_fromb(msg)) == NULL)
685 fatal_f("sshbuf_fromb");
687 if ((r = sshbuf_cmp(b, 0, "SSHSIG", 6)) != 0 ||
688 (r = sshbuf_consume(b, 6)) != 0 ||
689 (r = sshbuf_get_cstring(b, NULL, NULL)) != 0 || /* namespace */
690 (r = sshbuf_get_string_direct(b, NULL, NULL)) != 0 || /* reserved */
691 (r = sshbuf_get_cstring(b, NULL, NULL)) != 0 || /* hashalg */
692 (r = sshbuf_get_string_direct(b, NULL, NULL)) != 0) /* H(msg) */
694 if (sshbuf_len(b) != 0) {
695 r = SSH_ERR_INVALID_FORMAT;
706 * This function inspects a message to be signed by a FIDO key that has a
707 * web-like application string (i.e. one that does not begin with "ssh:".
708 * It checks that the message is one of those expected for SSH operations
709 * (pubkey userauth, sshsig, CA key signing) to exclude signing challenges
713 check_websafe_message_contents(struct sshkey *key, struct sshbuf *data)
715 if (parse_userauth_request(data, key, NULL, NULL, NULL) == 0) {
716 debug_f("signed data matches public key userauth request");
719 if (parse_sshsig_request(data) == 0) {
720 debug_f("signed data matches SSHSIG signature request");
724 /* XXX check CA signature operation */
726 error("web-origin key attempting to sign non-SSH message");
731 buf_equal(const struct sshbuf *a, const struct sshbuf *b)
733 if (sshbuf_ptr(a) == NULL || sshbuf_ptr(b) == NULL)
734 return SSH_ERR_INVALID_ARGUMENT;
735 if (sshbuf_len(a) != sshbuf_len(b))
736 return SSH_ERR_INVALID_FORMAT;
737 if (timingsafe_bcmp(sshbuf_ptr(a), sshbuf_ptr(b), sshbuf_len(a)) != 0)
738 return SSH_ERR_INVALID_FORMAT;
744 process_sign_request2(SocketEntry *e)
746 u_char *signature = NULL;
748 u_int compat = 0, flags;
749 int r, ok = -1, retried = 0;
750 char *fp = NULL, *pin = NULL, *prompt = NULL;
751 char *user = NULL, *sig_dest = NULL;
752 const char *fwd_host = NULL, *dest_host = NULL;
753 struct sshbuf *msg = NULL, *data = NULL, *sid = NULL;
754 struct sshkey *key = NULL, *hostkey = NULL;
756 struct notifier_ctx *notifier = NULL;
760 if ((msg = sshbuf_new()) == NULL || (data = sshbuf_new()) == NULL)
761 fatal_f("sshbuf_new failed");
762 if ((r = sshkey_froms(e->request, &key)) != 0 ||
763 (r = sshbuf_get_stringb(e->request, data)) != 0 ||
764 (r = sshbuf_get_u32(e->request, &flags)) != 0) {
765 error_fr(r, "parse");
769 if ((id = lookup_identity(key)) == NULL) {
770 verbose_f("%s key not found", sshkey_type(key));
773 if ((fp = sshkey_fingerprint(key, SSH_FP_HASH_DEFAULT,
774 SSH_FP_DEFAULT)) == NULL)
775 fatal_f("fingerprint failed");
777 if (id->ndest_constraints != 0) {
778 if (e->nsession_ids == 0) {
779 logit_f("refusing use of destination-constrained key "
780 "to sign on unbound connection");
783 if (parse_userauth_request(data, key, &user, &sid,
785 logit_f("refusing use of destination-constrained key "
786 "to sign an unidentified signature");
790 debug_f("user=%s", user);
791 if (identity_permitted(id, e, user, &fwd_host, &dest_host) != 0)
793 /* XXX display fwd_host/dest_host in askpass UI */
795 * Ensure that the session ID is the most recent one
796 * registered on the socket - it should have been bound by
797 * ssh immediately before userauth.
800 e->session_ids[e->nsession_ids - 1].sid) != 0) {
801 error_f("unexpected session ID (%zu listed) on "
802 "signature request for target user %s with "
803 "key %s %s", e->nsession_ids, user,
804 sshkey_type(id->key), fp);
808 * Ensure that the hostkey embedded in the signature matches
809 * the one most recently bound to the socket. An exception is
810 * made for the initial forwarding hop.
812 if (e->nsession_ids > 1 && hostkey == NULL) {
813 error_f("refusing use of destination-constrained key: "
814 "no hostkey recorded in signature for forwarded "
818 if (hostkey != NULL && !sshkey_equal(hostkey,
819 e->session_ids[e->nsession_ids - 1].key)) {
820 error_f("refusing use of destination-constrained key: "
821 "mismatch between hostkey in request and most "
822 "recently bound session");
825 xasprintf(&sig_dest, "public key authentication request for "
826 "user \"%s\" to listed host", user);
828 if (id->confirm && confirm_key(id, sig_dest) != 0) {
829 verbose_f("user refused key");
832 if (sshkey_is_sk(id->key)) {
833 if (restrict_websafe &&
834 strncmp(id->key->sk_application, "ssh:", 4) != 0 &&
835 !check_websafe_message_contents(key, data)) {
836 /* error already logged */
839 if (id->key->sk_flags & SSH_SK_USER_PRESENCE_REQD) {
840 notifier = notify_start(0,
841 "Confirm user presence for key %s %s%s%s",
842 sshkey_type(id->key), fp,
843 sig_dest == NULL ? "" : "\n",
844 sig_dest == NULL ? "" : sig_dest);
848 if ((r = sshkey_sign(id->key, &signature, &slen,
849 sshbuf_ptr(data), sshbuf_len(data), agent_decode_alg(key, flags),
850 id->sk_provider, pin, compat)) != 0) {
851 debug_fr(r, "sshkey_sign");
852 if (pin == NULL && !retried && sshkey_is_sk(id->key) &&
853 r == SSH_ERR_KEY_WRONG_PASSPHRASE) {
854 notify_complete(notifier, NULL);
856 /* XXX include sig_dest */
857 xasprintf(&prompt, "Enter PIN%sfor %s key %s: ",
858 (id->key->sk_flags & SSH_SK_USER_PRESENCE_REQD) ?
859 " and confirm user presence " : " ",
860 sshkey_type(id->key), fp);
861 pin = read_passphrase(prompt, RP_USE_ASKPASS);
865 error_fr(r, "sshkey_sign");
870 debug_f("good signature");
872 notify_complete(notifier, "User presence confirmed");
875 if ((r = sshbuf_put_u8(msg, SSH2_AGENT_SIGN_RESPONSE)) != 0 ||
876 (r = sshbuf_put_string(msg, signature, slen)) != 0)
877 fatal_fr(r, "compose");
878 } else if ((r = sshbuf_put_u8(msg, SSH_AGENT_FAILURE)) != 0)
879 fatal_fr(r, "compose failure");
881 if ((r = sshbuf_put_stringb(e->output, msg)) != 0)
882 fatal_fr(r, "enqueue");
888 sshkey_free(hostkey);
895 freezero(pin, strlen(pin));
900 process_remove_identity(SocketEntry *e)
903 struct sshkey *key = NULL;
906 debug2_f("entering");
907 if ((r = sshkey_froms(e->request, &key)) != 0) {
908 error_fr(r, "parse key");
911 if ((id = lookup_identity(key)) == NULL) {
912 debug_f("key not found");
915 /* identity not visible, cannot be removed */
916 if (identity_permitted(id, e, NULL, NULL, NULL) != 0)
917 goto done; /* error already logged */
918 /* We have this key, free it. */
919 if (idtab->nentries < 1)
920 fatal_f("internal error: nentries %d", idtab->nentries);
921 TAILQ_REMOVE(&idtab->idlist, id, next);
927 send_status(e, success);
931 process_remove_all_identities(SocketEntry *e)
935 debug2_f("entering");
936 /* Loop over all identities and clear the keys. */
937 for (id = TAILQ_FIRST(&idtab->idlist); id;
938 id = TAILQ_FIRST(&idtab->idlist)) {
939 TAILQ_REMOVE(&idtab->idlist, id, next);
943 /* Mark that there are no identities. */
950 /* removes expired keys and returns number of seconds until the next expiry */
954 time_t deadline = 0, now = monotime();
957 for (id = TAILQ_FIRST(&idtab->idlist); id; id = nxt) {
958 nxt = TAILQ_NEXT(id, next);
961 if (now >= id->death) {
962 debug("expiring key '%s'", id->comment);
963 TAILQ_REMOVE(&idtab->idlist, id, next);
967 deadline = (deadline == 0) ? id->death :
968 MINIMUM(deadline, id->death);
970 if (deadline == 0 || deadline <= now)
973 return (deadline - now);
977 parse_dest_constraint_hop(struct sshbuf *b, struct dest_constraint_hop *dch)
982 struct sshkey *k = NULL;
985 memset(dch, '\0', sizeof(*dch));
986 if ((r = sshbuf_get_cstring(b, &dch->user, NULL)) != 0 ||
987 (r = sshbuf_get_cstring(b, &dch->hostname, NULL)) != 0 ||
988 (r = sshbuf_get_string_direct(b, NULL, &elen)) != 0) {
989 error_fr(r, "parse");
993 error_f("unsupported extensions (len %zu)", elen);
994 r = SSH_ERR_FEATURE_UNSUPPORTED;
997 if (*dch->hostname == '\0') {
999 dch->hostname = NULL;
1001 if (*dch->user == '\0') {
1005 while (sshbuf_len(b) != 0) {
1006 dch->keys = xrecallocarray(dch->keys, dch->nkeys,
1007 dch->nkeys + 1, sizeof(*dch->keys));
1008 dch->key_is_ca = xrecallocarray(dch->key_is_ca, dch->nkeys,
1009 dch->nkeys + 1, sizeof(*dch->key_is_ca));
1010 if ((r = sshkey_froms(b, &k)) != 0 ||
1011 (r = sshbuf_get_u8(b, &key_is_ca)) != 0)
1013 if ((fp = sshkey_fingerprint(k, SSH_FP_HASH_DEFAULT,
1014 SSH_FP_DEFAULT)) == NULL)
1015 fatal_f("fingerprint failed");
1016 debug3_f("%s%s%s: adding %skey %s %s",
1017 dch->user == NULL ? "" : dch->user,
1018 dch->user == NULL ? "" : "@",
1019 dch->hostname, key_is_ca ? "CA " : "", sshkey_type(k), fp);
1021 dch->keys[dch->nkeys] = k;
1022 dch->key_is_ca[dch->nkeys] = key_is_ca != 0;
1024 k = NULL; /* transferred */
1034 parse_dest_constraint(struct sshbuf *m, struct dest_constraint *dc)
1036 struct sshbuf *b = NULL, *frombuf = NULL, *tobuf = NULL;
1040 debug3_f("entering");
1042 memset(dc, '\0', sizeof(*dc));
1043 if ((r = sshbuf_froms(m, &b)) != 0 ||
1044 (r = sshbuf_froms(b, &frombuf)) != 0 ||
1045 (r = sshbuf_froms(b, &tobuf)) != 0 ||
1046 (r = sshbuf_get_string_direct(b, NULL, &elen)) != 0) {
1047 error_fr(r, "parse");
1050 if ((r = parse_dest_constraint_hop(frombuf, &dc->from)) != 0 ||
1051 (r = parse_dest_constraint_hop(tobuf, &dc->to)) != 0)
1052 goto out; /* already logged */
1054 error_f("unsupported extensions (len %zu)", elen);
1055 r = SSH_ERR_FEATURE_UNSUPPORTED;
1058 debug2_f("parsed %s (%u keys) > %s%s%s (%u keys)",
1059 dc->from.hostname ? dc->from.hostname : "(ORIGIN)", dc->from.nkeys,
1060 dc->to.user ? dc->to.user : "", dc->to.user ? "@" : "",
1061 dc->to.hostname ? dc->to.hostname : "(ANY)", dc->to.nkeys);
1062 /* check consistency */
1063 if ((dc->from.hostname == NULL) != (dc->from.nkeys == 0) ||
1064 dc->from.user != NULL) {
1065 error_f("inconsistent \"from\" specification");
1066 r = SSH_ERR_INVALID_FORMAT;
1069 if (dc->to.hostname == NULL || dc->to.nkeys == 0) {
1070 error_f("incomplete \"to\" specification");
1071 r = SSH_ERR_INVALID_FORMAT;
1078 sshbuf_free(frombuf);
1084 parse_key_constraint_extension(struct sshbuf *m, char **sk_providerp,
1085 struct dest_constraint **dcsp, size_t *ndcsp)
1087 char *ext_name = NULL;
1089 struct sshbuf *b = NULL;
1091 if ((r = sshbuf_get_cstring(m, &ext_name, NULL)) != 0) {
1092 error_fr(r, "parse constraint extension");
1095 debug_f("constraint ext %s", ext_name);
1096 if (strcmp(ext_name, "sk-provider@openssh.com") == 0) {
1097 if (sk_providerp == NULL) {
1098 error_f("%s not valid here", ext_name);
1099 r = SSH_ERR_INVALID_FORMAT;
1102 if (*sk_providerp != NULL) {
1103 error_f("%s already set", ext_name);
1104 r = SSH_ERR_INVALID_FORMAT;
1107 if ((r = sshbuf_get_cstring(m, sk_providerp, NULL)) != 0) {
1108 error_fr(r, "parse %s", ext_name);
1111 } else if (strcmp(ext_name,
1112 "restrict-destination-v00@openssh.com") == 0) {
1113 if (*dcsp != NULL) {
1114 error_f("%s already set", ext_name);
1117 if ((r = sshbuf_froms(m, &b)) != 0) {
1118 error_fr(r, "parse %s outer", ext_name);
1121 while (sshbuf_len(b) != 0) {
1122 if (*ndcsp >= AGENT_MAX_DEST_CONSTRAINTS) {
1123 error_f("too many %s constraints", ext_name);
1126 *dcsp = xrecallocarray(*dcsp, *ndcsp, *ndcsp + 1,
1128 if ((r = parse_dest_constraint(b,
1129 *dcsp + (*ndcsp)++)) != 0)
1130 goto out; /* error already logged */
1133 error_f("unsupported constraint \"%s\"", ext_name);
1134 r = SSH_ERR_FEATURE_UNSUPPORTED;
1146 parse_key_constraints(struct sshbuf *m, struct sshkey *k, time_t *deathp,
1147 u_int *secondsp, int *confirmp, char **sk_providerp,
1148 struct dest_constraint **dcsp, size_t *ndcsp)
1152 u_int seconds, maxsign = 0;
1154 while (sshbuf_len(m)) {
1155 if ((r = sshbuf_get_u8(m, &ctype)) != 0) {
1156 error_fr(r, "parse constraint type");
1160 case SSH_AGENT_CONSTRAIN_LIFETIME:
1162 error_f("lifetime already set");
1163 r = SSH_ERR_INVALID_FORMAT;
1166 if ((r = sshbuf_get_u32(m, &seconds)) != 0) {
1167 error_fr(r, "parse lifetime constraint");
1170 *deathp = monotime() + seconds;
1171 *secondsp = seconds;
1173 case SSH_AGENT_CONSTRAIN_CONFIRM:
1174 if (*confirmp != 0) {
1175 error_f("confirm already set");
1176 r = SSH_ERR_INVALID_FORMAT;
1181 case SSH_AGENT_CONSTRAIN_MAXSIGN:
1183 error_f("maxsign not valid here");
1184 r = SSH_ERR_INVALID_FORMAT;
1188 error_f("maxsign already set");
1189 r = SSH_ERR_INVALID_FORMAT;
1192 if ((r = sshbuf_get_u32(m, &maxsign)) != 0) {
1193 error_fr(r, "parse maxsign constraint");
1196 if ((r = sshkey_enable_maxsign(k, maxsign)) != 0) {
1197 error_fr(r, "enable maxsign");
1201 case SSH_AGENT_CONSTRAIN_EXTENSION:
1202 if ((r = parse_key_constraint_extension(m,
1203 sk_providerp, dcsp, ndcsp)) != 0)
1204 goto out; /* error already logged */
1207 error_f("Unknown constraint %d", ctype);
1208 r = SSH_ERR_FEATURE_UNSUPPORTED;
1219 process_add_identity(SocketEntry *e)
1222 int success = 0, confirm = 0;
1223 char *fp, *comment = NULL, *sk_provider = NULL;
1224 char canonical_provider[PATH_MAX];
1227 struct dest_constraint *dest_constraints = NULL;
1228 size_t ndest_constraints = 0;
1229 struct sshkey *k = NULL;
1230 int r = SSH_ERR_INTERNAL_ERROR;
1232 debug2_f("entering");
1233 if ((r = sshkey_private_deserialize(e->request, &k)) != 0 ||
1235 (r = sshbuf_get_cstring(e->request, &comment, NULL)) != 0) {
1236 error_fr(r, "parse");
1239 if (parse_key_constraints(e->request, k, &death, &seconds, &confirm,
1240 &sk_provider, &dest_constraints, &ndest_constraints) != 0) {
1241 error_f("failed to parse constraints");
1242 sshbuf_reset(e->request);
1246 if (sk_provider != NULL) {
1247 if (!sshkey_is_sk(k)) {
1248 error("Cannot add provider: %s is not an "
1249 "authenticator-hosted key", sshkey_type(k));
1252 if (strcasecmp(sk_provider, "internal") == 0) {
1253 debug_f("internal provider");
1255 if (e->nsession_ids != 0 && !remote_add_provider) {
1256 verbose("failed add of SK provider \"%.100s\": "
1257 "remote addition of providers is disabled",
1261 if (realpath(sk_provider, canonical_provider) == NULL) {
1262 verbose("failed provider \"%.100s\": "
1263 "realpath: %s", sk_provider,
1268 sk_provider = xstrdup(canonical_provider);
1269 if (match_pattern_list(sk_provider,
1270 allowed_providers, 0) != 1) {
1271 error("Refusing add key: "
1272 "provider %s not allowed", sk_provider);
1277 if ((r = sshkey_shield_private(k)) != 0) {
1278 error_fr(r, "shield private");
1281 if (lifetime && !death)
1282 death = monotime() + lifetime;
1283 if ((id = lookup_identity(k)) == NULL) {
1284 id = xcalloc(1, sizeof(Identity));
1285 TAILQ_INSERT_TAIL(&idtab->idlist, id, next);
1286 /* Increment the number of identities. */
1289 /* identity not visible, do not update */
1290 if (identity_permitted(id, e, NULL, NULL, NULL) != 0)
1291 goto out; /* error already logged */
1292 /* key state might have been updated */
1293 sshkey_free(id->key);
1295 free(id->sk_provider);
1296 free_dest_constraints(id->dest_constraints,
1297 id->ndest_constraints);
1301 id->comment = comment;
1303 id->confirm = confirm;
1304 id->sk_provider = sk_provider;
1305 id->dest_constraints = dest_constraints;
1306 id->ndest_constraints = ndest_constraints;
1308 if ((fp = sshkey_fingerprint(k, SSH_FP_HASH_DEFAULT,
1309 SSH_FP_DEFAULT)) == NULL)
1310 fatal_f("sshkey_fingerprint failed");
1311 debug_f("add %s %s \"%.100s\" (life: %u) (confirm: %u) "
1312 "(provider: %s) (destination constraints: %zu)",
1313 sshkey_ssh_name(k), fp, comment, seconds, confirm,
1314 sk_provider == NULL ? "none" : sk_provider, ndest_constraints);
1320 dest_constraints = NULL;
1321 ndest_constraints = 0;
1327 free_dest_constraints(dest_constraints, ndest_constraints);
1328 send_status(e, success);
1331 /* XXX todo: encrypt sensitive data with passphrase */
1333 process_lock_agent(SocketEntry *e, int lock)
1335 int r, success = 0, delay;
1337 u_char passwdhash[LOCK_SIZE];
1338 static u_int fail_count = 0;
1341 debug2_f("entering");
1343 * This is deliberately fatal: the user has requested that we lock,
1344 * but we can't parse their request properly. The only safe thing to
1347 if ((r = sshbuf_get_cstring(e->request, &passwd, &pwlen)) != 0)
1348 fatal_fr(r, "parse");
1350 debug("empty password not supported");
1351 } else if (locked && !lock) {
1352 if (bcrypt_pbkdf(passwd, pwlen, lock_salt, sizeof(lock_salt),
1353 passwdhash, sizeof(passwdhash), LOCK_ROUNDS) < 0)
1354 fatal("bcrypt_pbkdf");
1355 if (timingsafe_bcmp(passwdhash, lock_pwhash, LOCK_SIZE) == 0) {
1356 debug("agent unlocked");
1359 explicit_bzero(lock_pwhash, sizeof(lock_pwhash));
1362 /* delay in 0.1s increments up to 10s */
1363 if (fail_count < 100)
1365 delay = 100000 * fail_count;
1366 debug("unlock failed, delaying %0.1lf seconds",
1367 (double)delay/1000000);
1370 explicit_bzero(passwdhash, sizeof(passwdhash));
1371 } else if (!locked && lock) {
1372 debug("agent locked");
1374 arc4random_buf(lock_salt, sizeof(lock_salt));
1375 if (bcrypt_pbkdf(passwd, pwlen, lock_salt, sizeof(lock_salt),
1376 lock_pwhash, sizeof(lock_pwhash), LOCK_ROUNDS) < 0)
1377 fatal("bcrypt_pbkdf");
1380 freezero(passwd, pwlen);
1381 send_status(e, success);
1385 no_identities(SocketEntry *e)
1390 if ((msg = sshbuf_new()) == NULL)
1391 fatal_f("sshbuf_new failed");
1392 if ((r = sshbuf_put_u8(msg, SSH2_AGENT_IDENTITIES_ANSWER)) != 0 ||
1393 (r = sshbuf_put_u32(msg, 0)) != 0 ||
1394 (r = sshbuf_put_stringb(e->output, msg)) != 0)
1395 fatal_fr(r, "compose");
1399 #ifdef ENABLE_PKCS11
1401 process_add_smartcard_key(SocketEntry *e)
1403 char *provider = NULL, *pin = NULL, canonical_provider[PATH_MAX];
1404 char **comments = NULL;
1405 int r, i, count = 0, success = 0, confirm = 0;
1408 struct sshkey **keys = NULL, *k;
1410 struct dest_constraint *dest_constraints = NULL;
1411 size_t ndest_constraints = 0;
1413 debug2_f("entering");
1414 if ((r = sshbuf_get_cstring(e->request, &provider, NULL)) != 0 ||
1415 (r = sshbuf_get_cstring(e->request, &pin, NULL)) != 0) {
1416 error_fr(r, "parse");
1419 if (parse_key_constraints(e->request, NULL, &death, &seconds, &confirm,
1420 NULL, &dest_constraints, &ndest_constraints) != 0) {
1421 error_f("failed to parse constraints");
1424 if (e->nsession_ids != 0 && !remote_add_provider) {
1425 verbose("failed PKCS#11 add of \"%.100s\": remote addition of "
1426 "providers is disabled", provider);
1429 if (realpath(provider, canonical_provider) == NULL) {
1430 verbose("failed PKCS#11 add of \"%.100s\": realpath: %s",
1431 provider, strerror(errno));
1434 if (match_pattern_list(canonical_provider, allowed_providers, 0) != 1) {
1435 verbose("refusing PKCS#11 add of \"%.100s\": "
1436 "provider not allowed", canonical_provider);
1439 debug_f("add %.100s", canonical_provider);
1440 if (lifetime && !death)
1441 death = monotime() + lifetime;
1443 count = pkcs11_add_provider(canonical_provider, pin, &keys, &comments);
1444 for (i = 0; i < count; i++) {
1446 if (lookup_identity(k) == NULL) {
1447 id = xcalloc(1, sizeof(Identity));
1449 keys[i] = NULL; /* transferred */
1450 id->provider = xstrdup(canonical_provider);
1451 if (*comments[i] != '\0') {
1452 id->comment = comments[i];
1453 comments[i] = NULL; /* transferred */
1455 id->comment = xstrdup(canonical_provider);
1458 id->confirm = confirm;
1459 id->dest_constraints = dest_constraints;
1460 id->ndest_constraints = ndest_constraints;
1461 dest_constraints = NULL; /* transferred */
1462 ndest_constraints = 0;
1463 TAILQ_INSERT_TAIL(&idtab->idlist, id, next);
1467 /* XXX update constraints for existing keys */
1468 sshkey_free(keys[i]);
1476 free_dest_constraints(dest_constraints, ndest_constraints);
1477 send_status(e, success);
1481 process_remove_smartcard_key(SocketEntry *e)
1483 char *provider = NULL, *pin = NULL, canonical_provider[PATH_MAX];
1487 debug2_f("entering");
1488 if ((r = sshbuf_get_cstring(e->request, &provider, NULL)) != 0 ||
1489 (r = sshbuf_get_cstring(e->request, &pin, NULL)) != 0) {
1490 error_fr(r, "parse");
1495 if (realpath(provider, canonical_provider) == NULL) {
1496 verbose("failed PKCS#11 add of \"%.100s\": realpath: %s",
1497 provider, strerror(errno));
1501 debug_f("remove %.100s", canonical_provider);
1502 for (id = TAILQ_FIRST(&idtab->idlist); id; id = nxt) {
1503 nxt = TAILQ_NEXT(id, next);
1504 /* Skip file--based keys */
1505 if (id->provider == NULL)
1507 if (!strcmp(canonical_provider, id->provider)) {
1508 TAILQ_REMOVE(&idtab->idlist, id, next);
1513 if (pkcs11_del_provider(canonical_provider) == 0)
1516 error_f("pkcs11_del_provider failed");
1519 send_status(e, success);
1521 #endif /* ENABLE_PKCS11 */
1524 process_ext_session_bind(SocketEntry *e)
1526 int r, sid_match, key_match;
1527 struct sshkey *key = NULL;
1528 struct sshbuf *sid = NULL, *sig = NULL;
1533 debug2_f("entering");
1534 if ((r = sshkey_froms(e->request, &key)) != 0 ||
1535 (r = sshbuf_froms(e->request, &sid)) != 0 ||
1536 (r = sshbuf_froms(e->request, &sig)) != 0 ||
1537 (r = sshbuf_get_u8(e->request, &fwd)) != 0) {
1538 error_fr(r, "parse");
1541 if ((fp = sshkey_fingerprint(key, SSH_FP_HASH_DEFAULT,
1542 SSH_FP_DEFAULT)) == NULL)
1543 fatal_f("fingerprint failed");
1544 /* check signature with hostkey on session ID */
1545 if ((r = sshkey_verify(key, sshbuf_ptr(sig), sshbuf_len(sig),
1546 sshbuf_ptr(sid), sshbuf_len(sid), NULL, 0, NULL)) != 0) {
1547 error_fr(r, "sshkey_verify for %s %s", sshkey_type(key), fp);
1550 /* check whether sid/key already recorded */
1551 for (i = 0; i < e->nsession_ids; i++) {
1552 if (!e->session_ids[i].forwarded) {
1553 error_f("attempt to bind session ID to socket "
1554 "previously bound for authentication attempt");
1558 sid_match = buf_equal(sid, e->session_ids[i].sid) == 0;
1559 key_match = sshkey_equal(key, e->session_ids[i].key);
1560 if (sid_match && key_match) {
1561 debug_f("session ID already recorded for %s %s",
1562 sshkey_type(key), fp);
1565 } else if (sid_match) {
1566 error_f("session ID recorded against different key "
1567 "for %s %s", sshkey_type(key), fp);
1572 * new sid with previously-seen key can happen, e.g. multiple
1573 * connections to the same host.
1576 /* record new key/sid */
1577 if (e->nsession_ids >= AGENT_MAX_SESSION_IDS) {
1578 error_f("too many session IDs recorded");
1581 e->session_ids = xrecallocarray(e->session_ids, e->nsession_ids,
1582 e->nsession_ids + 1, sizeof(*e->session_ids));
1583 i = e->nsession_ids++;
1584 debug_f("recorded %s %s (slot %zu of %d)", sshkey_type(key), fp, i,
1585 AGENT_MAX_SESSION_IDS);
1586 e->session_ids[i].key = key;
1587 e->session_ids[i].forwarded = fwd != 0;
1588 key = NULL; /* transferred */
1589 /* can't transfer sid; it's refcounted and scoped to request's life */
1590 if ((e->session_ids[i].sid = sshbuf_new()) == NULL)
1591 fatal_f("sshbuf_new");
1592 if ((r = sshbuf_putb(e->session_ids[i].sid, sid)) != 0)
1593 fatal_fr(r, "sshbuf_putb session ID");
1601 return r == 0 ? 1 : 0;
1605 process_extension(SocketEntry *e)
1610 debug2_f("entering");
1611 if ((r = sshbuf_get_cstring(e->request, &name, NULL)) != 0) {
1612 error_fr(r, "parse");
1615 if (strcmp(name, "session-bind@openssh.com") == 0)
1616 success = process_ext_session_bind(e);
1618 debug_f("unsupported extension \"%s\"", name);
1621 send_status(e, success);
1624 * dispatch incoming message.
1625 * returns 1 on success, 0 for incomplete messages or -1 on error.
1628 process_message(u_int socknum)
1636 if (socknum >= sockets_alloc)
1637 fatal_f("sock %u >= allocated %u", socknum, sockets_alloc);
1638 e = &sockets[socknum];
1640 if (sshbuf_len(e->input) < 5)
1641 return 0; /* Incomplete message header. */
1642 cp = sshbuf_ptr(e->input);
1643 msg_len = PEEK_U32(cp);
1644 if (msg_len > AGENT_MAX_LEN) {
1645 debug_f("socket %u (fd=%d) message too long %u > %u",
1646 socknum, e->fd, msg_len, AGENT_MAX_LEN);
1649 if (sshbuf_len(e->input) < msg_len + 4)
1650 return 0; /* Incomplete message body. */
1652 /* move the current input to e->request */
1653 sshbuf_reset(e->request);
1654 if ((r = sshbuf_get_stringb(e->input, e->request)) != 0 ||
1655 (r = sshbuf_get_u8(e->request, &type)) != 0) {
1656 if (r == SSH_ERR_MESSAGE_INCOMPLETE ||
1657 r == SSH_ERR_STRING_TOO_LARGE) {
1658 error_fr(r, "parse");
1661 fatal_fr(r, "parse");
1664 debug_f("socket %u (fd=%d) type %d", socknum, e->fd, type);
1666 /* check whether agent is locked */
1667 if (locked && type != SSH_AGENTC_UNLOCK) {
1668 sshbuf_reset(e->request);
1670 case SSH2_AGENTC_REQUEST_IDENTITIES:
1671 /* send empty lists */
1675 /* send a fail message for all other request types */
1682 case SSH_AGENTC_LOCK:
1683 case SSH_AGENTC_UNLOCK:
1684 process_lock_agent(e, type == SSH_AGENTC_LOCK);
1686 case SSH_AGENTC_REMOVE_ALL_RSA_IDENTITIES:
1687 process_remove_all_identities(e); /* safe for !WITH_SSH1 */
1690 case SSH2_AGENTC_SIGN_REQUEST:
1691 process_sign_request2(e);
1693 case SSH2_AGENTC_REQUEST_IDENTITIES:
1694 process_request_identities(e);
1696 case SSH2_AGENTC_ADD_IDENTITY:
1697 case SSH2_AGENTC_ADD_ID_CONSTRAINED:
1698 process_add_identity(e);
1700 case SSH2_AGENTC_REMOVE_IDENTITY:
1701 process_remove_identity(e);
1703 case SSH2_AGENTC_REMOVE_ALL_IDENTITIES:
1704 process_remove_all_identities(e);
1706 #ifdef ENABLE_PKCS11
1707 case SSH_AGENTC_ADD_SMARTCARD_KEY:
1708 case SSH_AGENTC_ADD_SMARTCARD_KEY_CONSTRAINED:
1709 process_add_smartcard_key(e);
1711 case SSH_AGENTC_REMOVE_SMARTCARD_KEY:
1712 process_remove_smartcard_key(e);
1714 #endif /* ENABLE_PKCS11 */
1715 case SSH_AGENTC_EXTENSION:
1716 process_extension(e);
1719 /* Unknown message. Respond with failure. */
1720 error("Unknown message %d", type);
1721 sshbuf_reset(e->request);
1729 new_socket(sock_type type, int fd)
1731 u_int i, old_alloc, new_alloc;
1733 debug_f("type = %s", type == AUTH_CONNECTION ? "CONNECTION" :
1734 (type == AUTH_SOCKET ? "SOCKET" : "UNKNOWN"));
1735 if (type == AUTH_CONNECTION) {
1736 debug("xcount %d -> %d", xcount, xcount + 1);
1744 for (i = 0; i < sockets_alloc; i++)
1745 if (sockets[i].type == AUTH_UNUSED) {
1747 if ((sockets[i].input = sshbuf_new()) == NULL ||
1748 (sockets[i].output = sshbuf_new()) == NULL ||
1749 (sockets[i].request = sshbuf_new()) == NULL)
1750 fatal_f("sshbuf_new failed");
1751 sockets[i].type = type;
1754 old_alloc = sockets_alloc;
1755 new_alloc = sockets_alloc + 10;
1756 sockets = xrecallocarray(sockets, old_alloc, new_alloc,
1757 sizeof(sockets[0]));
1758 for (i = old_alloc; i < new_alloc; i++)
1759 sockets[i].type = AUTH_UNUSED;
1760 sockets_alloc = new_alloc;
1761 sockets[old_alloc].fd = fd;
1762 if ((sockets[old_alloc].input = sshbuf_new()) == NULL ||
1763 (sockets[old_alloc].output = sshbuf_new()) == NULL ||
1764 (sockets[old_alloc].request = sshbuf_new()) == NULL)
1765 fatal_f("sshbuf_new failed");
1766 sockets[old_alloc].type = type;
1770 handle_socket_read(u_int socknum)
1772 struct sockaddr_un sunaddr;
1778 slen = sizeof(sunaddr);
1779 fd = accept(sockets[socknum].fd, (struct sockaddr *)&sunaddr, &slen);
1781 error("accept from AUTH_SOCKET: %s", strerror(errno));
1784 if (getpeereid(fd, &euid, &egid) == -1) {
1785 error("getpeereid %d failed: %s", fd, strerror(errno));
1789 if ((euid != 0) && (getuid() != euid)) {
1790 error("uid mismatch: peer euid %u != uid %u",
1791 (u_int) euid, (u_int) getuid());
1795 new_socket(AUTH_CONNECTION, fd);
1800 handle_conn_read(u_int socknum)
1802 char buf[AGENT_RBUF_LEN];
1806 if ((len = read(sockets[socknum].fd, buf, sizeof(buf))) <= 0) {
1808 if (errno == EAGAIN || errno == EINTR)
1810 error_f("read error on socket %u (fd %d): %s",
1811 socknum, sockets[socknum].fd, strerror(errno));
1815 if ((r = sshbuf_put(sockets[socknum].input, buf, len)) != 0)
1816 fatal_fr(r, "compose");
1817 explicit_bzero(buf, sizeof(buf));
1819 if ((r = process_message(socknum)) == -1)
1828 handle_conn_write(u_int socknum)
1833 if (sshbuf_len(sockets[socknum].output) == 0)
1834 return 0; /* shouldn't happen */
1835 if ((len = write(sockets[socknum].fd,
1836 sshbuf_ptr(sockets[socknum].output),
1837 sshbuf_len(sockets[socknum].output))) <= 0) {
1839 if (errno == EAGAIN || errno == EINTR)
1841 error_f("read error on socket %u (fd %d): %s",
1842 socknum, sockets[socknum].fd, strerror(errno));
1846 if ((r = sshbuf_consume(sockets[socknum].output, len)) != 0)
1847 fatal_fr(r, "consume");
1852 after_poll(struct pollfd *pfd, size_t npfd, u_int maxfds)
1855 u_int socknum, activefds = npfd;
1857 for (i = 0; i < npfd; i++) {
1858 if (pfd[i].revents == 0)
1860 /* Find sockets entry */
1861 for (socknum = 0; socknum < sockets_alloc; socknum++) {
1862 if (sockets[socknum].type != AUTH_SOCKET &&
1863 sockets[socknum].type != AUTH_CONNECTION)
1865 if (pfd[i].fd == sockets[socknum].fd)
1868 if (socknum >= sockets_alloc) {
1869 error_f("no socket for fd %d", pfd[i].fd);
1872 /* Process events */
1873 switch (sockets[socknum].type) {
1875 if ((pfd[i].revents & (POLLIN|POLLERR)) == 0)
1877 if (npfd > maxfds) {
1878 debug3("out of fds (active %u >= limit %u); "
1879 "skipping accept", activefds, maxfds);
1882 if (handle_socket_read(socknum) == 0)
1885 case AUTH_CONNECTION:
1886 if ((pfd[i].revents & (POLLIN|POLLHUP|POLLERR)) != 0 &&
1887 handle_conn_read(socknum) != 0)
1889 if ((pfd[i].revents & (POLLOUT|POLLHUP)) != 0 &&
1890 handle_conn_write(socknum) != 0) {
1893 fatal("activefds == 0 at close_sock");
1894 close_socket(&sockets[socknum]);
1906 prepare_poll(struct pollfd **pfdp, size_t *npfdp, int *timeoutp, u_int maxfds)
1908 struct pollfd *pfd = *pfdp;
1909 size_t i, j, npfd = 0;
1913 /* Count active sockets */
1914 for (i = 0; i < sockets_alloc; i++) {
1915 switch (sockets[i].type) {
1917 case AUTH_CONNECTION:
1923 fatal("Unknown socket type %d", sockets[i].type);
1927 if (npfd != *npfdp &&
1928 (pfd = recallocarray(pfd, *npfdp, npfd, sizeof(*pfd))) == NULL)
1929 fatal_f("recallocarray failed");
1933 for (i = j = 0; i < sockets_alloc; i++) {
1934 switch (sockets[i].type) {
1936 if (npfd > maxfds) {
1937 debug3("out of fds (active %zu >= limit %u); "
1938 "skipping arming listener", npfd, maxfds);
1941 pfd[j].fd = sockets[i].fd;
1943 pfd[j].events = POLLIN;
1946 case AUTH_CONNECTION:
1947 pfd[j].fd = sockets[i].fd;
1950 * Only prepare to read if we can handle a full-size
1951 * input read buffer and enqueue a max size reply..
1953 if ((r = sshbuf_check_reserve(sockets[i].input,
1954 AGENT_RBUF_LEN)) == 0 &&
1955 (r = sshbuf_check_reserve(sockets[i].output,
1956 AGENT_MAX_LEN)) == 0)
1957 pfd[j].events = POLLIN;
1958 else if (r != SSH_ERR_NO_BUFFER_SPACE)
1959 fatal_fr(r, "reserve");
1960 if (sshbuf_len(sockets[i].output) > 0)
1961 pfd[j].events |= POLLOUT;
1968 deadline = reaper();
1969 if (parent_alive_interval != 0)
1970 deadline = (deadline == 0) ? parent_alive_interval :
1971 MINIMUM(deadline, parent_alive_interval);
1972 if (deadline == 0) {
1973 *timeoutp = -1; /* INFTIM */
1975 if (deadline > INT_MAX / 1000)
1976 *timeoutp = INT_MAX / 1000;
1978 *timeoutp = deadline * 1000;
1984 cleanup_socket(void)
1986 if (cleanup_pid != 0 && getpid() != cleanup_pid)
1990 unlink(socket_name);
2003 cleanup_handler(int sig)
2006 #ifdef ENABLE_PKCS11
2013 check_parent_exists(void)
2016 * If our parent has exited then getppid() will return (pid_t)1,
2017 * so testing for that should be safe.
2019 if (parent_pid != -1 && getppid() != parent_pid) {
2020 /* printf("Parent has died - Authentication agent exiting.\n"); */
2030 "usage: ssh-agent [-c | -s] [-Ddx] [-a bind_address] [-E fingerprint_hash]\n"
2031 " [-O option] [-P allowed_providers] [-t life]\n"
2032 " ssh-agent [-a bind_address] [-E fingerprint_hash] [-O option]\n"
2033 " [-P allowed_providers] [-t life] command [arg ...]\n"
2034 " ssh-agent [-c | -s] -k\n");
2039 main(int ac, char **av)
2041 int c_flag = 0, d_flag = 0, D_flag = 0, k_flag = 0, s_flag = 0;
2042 int sock, ch, result, saved_errno;
2043 char *shell, *format, *pidstr, *agentsocket = NULL;
2044 #ifdef HAVE_SETRLIMIT
2048 extern char *optarg;
2050 char pidstrbuf[1 + 3 * sizeof pid];
2053 int timeout = -1; /* INFTIM */
2054 struct pollfd *pfd = NULL;
2058 /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
2062 (void)setegid(getgid());
2063 (void)setgid(getgid());
2066 platform_disable_tracing(0); /* strict=no */
2068 #ifdef RLIMIT_NOFILE
2069 if (getrlimit(RLIMIT_NOFILE, &rlim) == -1)
2070 fatal("%s: getrlimit: %s", __progname, strerror(errno));
2073 __progname = ssh_get_progname(av[0]);
2076 while ((ch = getopt(ac, av, "cDdksE:a:O:P:t:x")) != -1) {
2079 fingerprint_hash = ssh_digest_alg_by_name(optarg);
2080 if (fingerprint_hash == -1)
2081 fatal("Invalid hash algorithm \"%s\"", optarg);
2092 if (strcmp(optarg, "no-restrict-websafe") == 0)
2093 restrict_websafe = 0;
2094 else if (strcmp(optarg, "allow-remote-pkcs11") == 0)
2095 remote_add_provider = 1;
2097 fatal("Unknown -O option");
2100 if (allowed_providers != NULL)
2101 fatal("-P option already specified");
2102 allowed_providers = xstrdup(optarg);
2110 if (d_flag || D_flag)
2115 if (d_flag || D_flag)
2120 agentsocket = optarg;
2123 if ((lifetime = convtime(optarg)) == -1) {
2124 fprintf(stderr, "Invalid lifetime\n");
2138 if (ac > 0 && (c_flag || k_flag || s_flag || d_flag || D_flag))
2141 if (allowed_providers == NULL)
2142 allowed_providers = xstrdup(DEFAULT_ALLOWED_PROVIDERS);
2144 if (ac == 0 && !c_flag && !s_flag) {
2145 shell = getenv("SHELL");
2146 if (shell != NULL && (len = strlen(shell)) > 2 &&
2147 strncmp(shell + len - 3, "csh", 3) == 0)
2151 const char *errstr = NULL;
2153 pidstr = getenv(SSH_AGENTPID_ENV_NAME);
2154 if (pidstr == NULL) {
2155 fprintf(stderr, "%s not set, cannot kill agent\n",
2156 SSH_AGENTPID_ENV_NAME);
2159 pid = (int)strtonum(pidstr, 2, INT_MAX, &errstr);
2162 "%s=\"%s\", which is not a good PID: %s\n",
2163 SSH_AGENTPID_ENV_NAME, pidstr, errstr);
2166 if (kill(pid, SIGTERM) == -1) {
2170 format = c_flag ? "unsetenv %s;\n" : "unset %s;\n";
2171 printf(format, SSH_AUTHSOCKET_ENV_NAME);
2172 printf(format, SSH_AGENTPID_ENV_NAME);
2173 printf("echo Agent pid %ld killed;\n", (long)pid);
2178 * Minimum file descriptors:
2179 * stdio (3) + listener (1) + syslog (1 maybe) + connection (1) +
2180 * a few spare for libc / stack protectors / sanitisers, etc.
2182 #define SSH_AGENT_MIN_FDS (3+1+1+1+4)
2183 if (rlim.rlim_cur < SSH_AGENT_MIN_FDS)
2184 fatal("%s: file descriptor rlimit %lld too low (minimum %u)",
2185 __progname, (long long)rlim.rlim_cur, SSH_AGENT_MIN_FDS);
2186 maxfds = rlim.rlim_cur - SSH_AGENT_MIN_FDS;
2188 parent_pid = getpid();
2190 if (agentsocket == NULL) {
2191 /* Create private directory for agent socket */
2192 mktemp_proto(socket_dir, sizeof(socket_dir));
2193 if (mkdtemp(socket_dir) == NULL) {
2194 perror("mkdtemp: private socket dir");
2197 snprintf(socket_name, sizeof socket_name, "%s/agent.%ld", socket_dir,
2200 /* Try to use specified agent socket */
2201 socket_dir[0] = '\0';
2202 strlcpy(socket_name, agentsocket, sizeof socket_name);
2206 * Create socket early so it will exist before command gets run from
2209 prev_mask = umask(0177);
2210 sock = unix_listener(socket_name, SSH_LISTEN_BACKLOG, 0);
2212 /* XXX - unix_listener() calls error() not perror() */
2213 *socket_name = '\0'; /* Don't unlink any existing file */
2219 * Fork, and have the parent execute the command, if any, or present
2220 * the socket data. The child continues as the authentication agent.
2222 if (D_flag || d_flag) {
2223 log_init(__progname,
2224 d_flag ? SYSLOG_LEVEL_DEBUG3 : SYSLOG_LEVEL_INFO,
2225 SYSLOG_FACILITY_AUTH, 1);
2226 format = c_flag ? "setenv %s %s;\n" : "%s=%s; export %s;\n";
2227 printf(format, SSH_AUTHSOCKET_ENV_NAME, socket_name,
2228 SSH_AUTHSOCKET_ENV_NAME);
2229 printf("echo Agent pid %ld;\n", (long)parent_pid);
2238 if (pid != 0) { /* Parent - execute the given command. */
2240 snprintf(pidstrbuf, sizeof pidstrbuf, "%ld", (long)pid);
2242 format = c_flag ? "setenv %s %s;\n" : "%s=%s; export %s;\n";
2243 printf(format, SSH_AUTHSOCKET_ENV_NAME, socket_name,
2244 SSH_AUTHSOCKET_ENV_NAME);
2245 printf(format, SSH_AGENTPID_ENV_NAME, pidstrbuf,
2246 SSH_AGENTPID_ENV_NAME);
2247 printf("echo Agent pid %ld;\n", (long)pid);
2250 if (setenv(SSH_AUTHSOCKET_ENV_NAME, socket_name, 1) == -1 ||
2251 setenv(SSH_AGENTPID_ENV_NAME, pidstrbuf, 1) == -1) {
2260 log_init(__progname, SYSLOG_LEVEL_INFO, SYSLOG_FACILITY_AUTH, 0);
2262 if (setsid() == -1) {
2263 error("setsid: %s", strerror(errno));
2268 if (stdfd_devnull(1, 1, 1) == -1)
2269 error_f("stdfd_devnull failed");
2271 #ifdef HAVE_SETRLIMIT
2272 /* deny core dumps, since memory contains unencrypted private keys */
2273 rlim.rlim_cur = rlim.rlim_max = 0;
2274 if (setrlimit(RLIMIT_CORE, &rlim) == -1) {
2275 error("setrlimit RLIMIT_CORE: %s", strerror(errno));
2282 cleanup_pid = getpid();
2284 #ifdef ENABLE_PKCS11
2287 new_socket(AUTH_SOCKET, sock);
2289 parent_alive_interval = 10;
2291 ssh_signal(SIGPIPE, SIG_IGN);
2292 ssh_signal(SIGINT, (d_flag | D_flag) ? cleanup_handler : SIG_IGN);
2293 ssh_signal(SIGHUP, cleanup_handler);
2294 ssh_signal(SIGTERM, cleanup_handler);
2296 if (pledge("stdio rpath cpath unix id proc exec", NULL) == -1)
2297 fatal("%s: pledge: %s", __progname, strerror(errno));
2298 platform_pledge_agent();
2301 prepare_poll(&pfd, &npfd, &timeout, maxfds);
2302 result = poll(pfd, npfd, timeout);
2303 saved_errno = errno;
2304 if (parent_alive_interval != 0)
2305 check_parent_exists();
2306 (void) reaper(); /* remove expired keys */
2308 if (saved_errno == EINTR)
2310 fatal("poll: %s", strerror(saved_errno));
2311 } else if (result > 0)
2312 after_poll(pfd, npfd, maxfds);