1 /* $OpenBSD: ssh-agent.c,v 1.278 2021/04/03 06:18:41 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.
40 #include <sys/types.h>
41 #include <sys/param.h>
42 #include <sys/resource.h>
44 #include <sys/socket.h>
46 #ifdef HAVE_SYS_TIME_H
47 # include <sys/time.h>
52 #include "openbsd-compat/sys-queue.h"
55 #include <openssl/evp.h>
56 #include "openbsd-compat/openssl-compat.h"
93 #include "pathnames.h"
94 #include "ssh-pkcs11.h"
97 #ifndef DEFAULT_ALLOWED_PROVIDERS
98 # define DEFAULT_ALLOWED_PROVIDERS "/usr/lib*/*,/usr/local/lib*/*"
101 /* Maximum accepted message length */
102 #define AGENT_MAX_LEN (256*1024)
103 /* Maximum bytes to read from client socket */
104 #define AGENT_RBUF_LEN (4096)
112 typedef struct socket_entry {
115 struct sshbuf *input;
116 struct sshbuf *output;
117 struct sshbuf *request;
120 u_int sockets_alloc = 0;
121 SocketEntry *sockets = NULL;
123 typedef struct identity {
124 TAILQ_ENTRY(identity) next;
135 TAILQ_HEAD(idqueue, identity) idlist;
138 /* private key table */
139 struct idtable *idtab;
143 /* pid of shell == parent of agent */
144 pid_t parent_pid = -1;
145 time_t parent_alive_interval = 0;
147 /* pid of process for which cleanup_socket is applicable */
148 pid_t cleanup_pid = 0;
150 /* pathname and directory for AUTH_SOCKET */
151 char socket_name[PATH_MAX];
152 char socket_dir[PATH_MAX];
154 /* Pattern-list of allowed PKCS#11/Security key paths */
155 static char *allowed_providers;
159 #define LOCK_SALT_SIZE 16
160 #define LOCK_ROUNDS 1
162 u_char lock_pwhash[LOCK_SIZE];
163 u_char lock_salt[LOCK_SALT_SIZE];
165 extern char *__progname;
167 /* Default lifetime in seconds (0 == forever) */
168 static int lifetime = 0;
170 static int fingerprint_hash = SSH_FP_HASH_DEFAULT;
172 /* Refuse signing of non-SSH messages for web-origin FIDO keys */
173 static int restrict_websafe = 1;
176 * Client connection count; incremented in new_socket() and decremented in
177 * close_socket(). When it reaches 0, ssh-agent will exit. Since it is
178 * normally initialized to 1, it will never reach 0. However, if the -x
179 * option is specified, it is initialized to 0 in main(); in that case,
180 * ssh-agent will exit as soon as it has had at least one client but no
183 static int xcount = 1;
186 close_socket(SocketEntry *e)
190 if (e->type == AUTH_CONNECTION) {
191 debug("xcount %d -> %d", xcount, xcount - 1);
196 sshbuf_free(e->input);
197 sshbuf_free(e->output);
198 sshbuf_free(e->request);
199 memset(e, '\0', sizeof(*e));
201 e->type = AUTH_UNUSED;
209 idtab = xcalloc(1, sizeof(*idtab));
210 TAILQ_INIT(&idtab->idlist);
215 free_identity(Identity *id)
217 sshkey_free(id->key);
220 free(id->sk_provider);
224 /* return matching private key for given public key */
226 lookup_identity(struct sshkey *key)
230 TAILQ_FOREACH(id, &idtab->idlist, next) {
231 if (sshkey_equal(key, id->key))
237 /* Check confirmation of keysign request */
239 confirm_key(Identity *id, const char *extra)
244 p = sshkey_fingerprint(id->key, fingerprint_hash, SSH_FP_DEFAULT);
246 ask_permission("Allow use of key %s?\nKey fingerprint %s.%s%s",
248 extra == NULL ? "" : "\n", extra == NULL ? "" : extra))
256 send_status(SocketEntry *e, int success)
260 if ((r = sshbuf_put_u32(e->output, 1)) != 0 ||
261 (r = sshbuf_put_u8(e->output, success ?
262 SSH_AGENT_SUCCESS : SSH_AGENT_FAILURE)) != 0)
263 fatal_fr(r, "compose");
266 /* send list of supported public keys to 'client' */
268 process_request_identities(SocketEntry *e)
274 debug2_f("entering");
276 if ((msg = sshbuf_new()) == NULL)
277 fatal_f("sshbuf_new failed");
278 if ((r = sshbuf_put_u8(msg, SSH2_AGENT_IDENTITIES_ANSWER)) != 0 ||
279 (r = sshbuf_put_u32(msg, idtab->nentries)) != 0)
280 fatal_fr(r, "compose");
281 TAILQ_FOREACH(id, &idtab->idlist, next) {
282 if ((r = sshkey_puts_opts(id->key, msg,
283 SSHKEY_SERIALIZE_INFO)) != 0 ||
284 (r = sshbuf_put_cstring(msg, id->comment)) != 0) {
285 error_fr(r, "compose key/comment");
289 if ((r = sshbuf_put_stringb(e->output, msg)) != 0)
290 fatal_fr(r, "enqueue");
296 agent_decode_alg(struct sshkey *key, u_int flags)
298 if (key->type == KEY_RSA) {
299 if (flags & SSH_AGENT_RSA_SHA2_256)
300 return "rsa-sha2-256";
301 else if (flags & SSH_AGENT_RSA_SHA2_512)
302 return "rsa-sha2-512";
303 } else if (key->type == KEY_RSA_CERT) {
304 if (flags & SSH_AGENT_RSA_SHA2_256)
305 return "rsa-sha2-256-cert-v01@openssh.com";
306 else if (flags & SSH_AGENT_RSA_SHA2_512)
307 return "rsa-sha2-512-cert-v01@openssh.com";
313 * Attempt to parse the contents of a buffer as a SSH publickey userauth
314 * request, checking its contents for consistency and matching the embedded
315 * key against the one that is being used for signing.
316 * Note: does not modify msg buffer.
317 * Optionally extract the username and session ID from the request.
320 parse_userauth_request(struct sshbuf *msg, const struct sshkey *expected_key,
321 char **userp, struct sshbuf **sess_idp)
323 struct sshbuf *b = NULL, *sess_id = NULL;
324 char *user = NULL, *service = NULL, *method = NULL, *pkalg = NULL;
326 u_char t, sig_follows;
327 struct sshkey *mkey = NULL;
331 if (sess_idp != NULL)
333 if ((b = sshbuf_fromb(msg)) == NULL)
334 fatal_f("sshbuf_fromb");
336 /* SSH userauth request */
337 if ((r = sshbuf_froms(b, &sess_id)) != 0)
339 if (sshbuf_len(sess_id) == 0) {
340 r = SSH_ERR_INVALID_FORMAT;
343 if ((r = sshbuf_get_u8(b, &t)) != 0 || /* SSH2_MSG_USERAUTH_REQUEST */
344 (r = sshbuf_get_cstring(b, &user, NULL)) != 0 || /* server user */
345 (r = sshbuf_get_cstring(b, &service, NULL)) != 0 || /* service */
346 (r = sshbuf_get_cstring(b, &method, NULL)) != 0 || /* method */
347 (r = sshbuf_get_u8(b, &sig_follows)) != 0 || /* sig-follows */
348 (r = sshbuf_get_cstring(b, &pkalg, NULL)) != 0 || /* alg */
349 (r = sshkey_froms(b, &mkey)) != 0) /* key */
351 if (t != SSH2_MSG_USERAUTH_REQUEST ||
353 strcmp(service, "ssh-connection") != 0 ||
354 !sshkey_equal(expected_key, mkey) ||
355 sshkey_type_from_name(pkalg) != expected_key->type) {
356 r = SSH_ERR_INVALID_FORMAT;
359 if (strcmp(method, "publickey") != 0) {
360 r = SSH_ERR_INVALID_FORMAT;
363 if (sshbuf_len(b) != 0) {
364 r = SSH_ERR_INVALID_FORMAT;
369 debug3_f("well formed userauth");
374 if (sess_idp != NULL) {
380 sshbuf_free(sess_id);
390 * Attempt to parse the contents of a buffer as a SSHSIG signature request.
391 * Note: does not modify buffer.
394 parse_sshsig_request(struct sshbuf *msg)
399 if ((b = sshbuf_fromb(msg)) == NULL)
400 fatal_f("sshbuf_fromb");
402 if ((r = sshbuf_cmp(b, 0, "SSHSIG", 6)) != 0 ||
403 (r = sshbuf_consume(b, 6)) != 0 ||
404 (r = sshbuf_get_cstring(b, NULL, NULL)) != 0 || /* namespace */
405 (r = sshbuf_get_string_direct(b, NULL, NULL)) != 0 || /* reserved */
406 (r = sshbuf_get_cstring(b, NULL, NULL)) != 0 || /* hashalg */
407 (r = sshbuf_get_string_direct(b, NULL, NULL)) != 0) /* H(msg) */
409 if (sshbuf_len(b) != 0) {
410 r = SSH_ERR_INVALID_FORMAT;
421 * This function inspects a message to be signed by a FIDO key that has a
422 * web-like application string (i.e. one that does not begin with "ssh:".
423 * It checks that the message is one of those expected for SSH operations
424 * (pubkey userauth, sshsig, CA key signing) to exclude signing challenges
428 check_websafe_message_contents(struct sshkey *key, struct sshbuf *data)
430 if (parse_userauth_request(data, key, NULL, NULL) == 0) {
431 debug_f("signed data matches public key userauth request");
434 if (parse_sshsig_request(data) == 0) {
435 debug_f("signed data matches SSHSIG signature request");
439 /* XXX check CA signature operation */
441 error("web-origin key attempting to sign non-SSH message");
447 process_sign_request2(SocketEntry *e)
449 u_char *signature = NULL;
451 u_int compat = 0, flags;
454 struct sshbuf *msg = NULL, *data = NULL;
455 struct sshkey *key = NULL;
457 struct notifier_ctx *notifier = NULL;
461 if ((msg = sshbuf_new()) == NULL || (data = sshbuf_new()) == NULL)
462 fatal_f("sshbuf_new failed");
463 if ((r = sshkey_froms(e->request, &key)) != 0 ||
464 (r = sshbuf_get_stringb(e->request, data)) != 0 ||
465 (r = sshbuf_get_u32(e->request, &flags)) != 0) {
466 error_fr(r, "parse");
470 if ((id = lookup_identity(key)) == NULL) {
471 verbose_f("%s key not found", sshkey_type(key));
474 if (id->confirm && confirm_key(id, NULL) != 0) {
475 verbose_f("user refused key");
478 if (sshkey_is_sk(id->key)) {
479 if (strncmp(id->key->sk_application, "ssh:", 4) != 0 &&
480 !check_websafe_message_contents(key, data)) {
481 /* error already logged */
484 if ((id->key->sk_flags & SSH_SK_USER_PRESENCE_REQD)) {
485 if ((fp = sshkey_fingerprint(key, SSH_FP_HASH_DEFAULT,
486 SSH_FP_DEFAULT)) == NULL)
487 fatal_f("fingerprint failed");
488 notifier = notify_start(0,
489 "Confirm user presence for key %s %s",
490 sshkey_type(id->key), fp);
493 /* XXX support PIN required FIDO keys */
494 if ((r = sshkey_sign(id->key, &signature, &slen,
495 sshbuf_ptr(data), sshbuf_len(data), agent_decode_alg(key, flags),
496 id->sk_provider, NULL, compat)) != 0) {
497 error_fr(r, "sshkey_sign");
503 notify_complete(notifier, "User presence confirmed");
506 if ((r = sshbuf_put_u8(msg, SSH2_AGENT_SIGN_RESPONSE)) != 0 ||
507 (r = sshbuf_put_string(msg, signature, slen)) != 0)
508 fatal_fr(r, "compose");
509 } else if ((r = sshbuf_put_u8(msg, SSH_AGENT_FAILURE)) != 0)
510 fatal_fr(r, "compose failure");
512 if ((r = sshbuf_put_stringb(e->output, msg)) != 0)
513 fatal_fr(r, "enqueue");
524 process_remove_identity(SocketEntry *e)
527 struct sshkey *key = NULL;
530 debug2_f("entering");
531 if ((r = sshkey_froms(e->request, &key)) != 0) {
532 error_fr(r, "parse key");
535 if ((id = lookup_identity(key)) == NULL) {
536 debug_f("key not found");
539 /* We have this key, free it. */
540 if (idtab->nentries < 1)
541 fatal_f("internal error: nentries %d", idtab->nentries);
542 TAILQ_REMOVE(&idtab->idlist, id, next);
548 send_status(e, success);
552 process_remove_all_identities(SocketEntry *e)
556 debug2_f("entering");
557 /* Loop over all identities and clear the keys. */
558 for (id = TAILQ_FIRST(&idtab->idlist); id;
559 id = TAILQ_FIRST(&idtab->idlist)) {
560 TAILQ_REMOVE(&idtab->idlist, id, next);
564 /* Mark that there are no identities. */
571 /* removes expired keys and returns number of seconds until the next expiry */
575 time_t deadline = 0, now = monotime();
578 for (id = TAILQ_FIRST(&idtab->idlist); id; id = nxt) {
579 nxt = TAILQ_NEXT(id, next);
582 if (now >= id->death) {
583 debug("expiring key '%s'", id->comment);
584 TAILQ_REMOVE(&idtab->idlist, id, next);
588 deadline = (deadline == 0) ? id->death :
589 MINIMUM(deadline, id->death);
591 if (deadline == 0 || deadline <= now)
594 return (deadline - now);
598 parse_key_constraint_extension(struct sshbuf *m, char **sk_providerp)
600 char *ext_name = NULL;
603 if ((r = sshbuf_get_cstring(m, &ext_name, NULL)) != 0) {
604 error_fr(r, "parse constraint extension");
607 debug_f("constraint ext %s", ext_name);
608 if (strcmp(ext_name, "sk-provider@openssh.com") == 0) {
609 if (sk_providerp == NULL) {
610 error_f("%s not valid here", ext_name);
611 r = SSH_ERR_INVALID_FORMAT;
614 if (*sk_providerp != NULL) {
615 error_f("%s already set", ext_name);
616 r = SSH_ERR_INVALID_FORMAT;
619 if ((r = sshbuf_get_cstring(m, sk_providerp, NULL)) != 0) {
620 error_fr(r, "parse %s", ext_name);
624 error_f("unsupported constraint \"%s\"", ext_name);
625 r = SSH_ERR_FEATURE_UNSUPPORTED;
636 parse_key_constraints(struct sshbuf *m, struct sshkey *k, time_t *deathp,
637 u_int *secondsp, int *confirmp, char **sk_providerp)
641 u_int seconds, maxsign = 0;
643 while (sshbuf_len(m)) {
644 if ((r = sshbuf_get_u8(m, &ctype)) != 0) {
645 error_fr(r, "parse constraint type");
649 case SSH_AGENT_CONSTRAIN_LIFETIME:
651 error_f("lifetime already set");
652 r = SSH_ERR_INVALID_FORMAT;
655 if ((r = sshbuf_get_u32(m, &seconds)) != 0) {
656 error_fr(r, "parse lifetime constraint");
659 *deathp = monotime() + seconds;
662 case SSH_AGENT_CONSTRAIN_CONFIRM:
663 if (*confirmp != 0) {
664 error_f("confirm already set");
665 r = SSH_ERR_INVALID_FORMAT;
670 case SSH_AGENT_CONSTRAIN_MAXSIGN:
672 error_f("maxsign not valid here");
673 r = SSH_ERR_INVALID_FORMAT;
677 error_f("maxsign already set");
678 r = SSH_ERR_INVALID_FORMAT;
681 if ((r = sshbuf_get_u32(m, &maxsign)) != 0) {
682 error_fr(r, "parse maxsign constraint");
685 if ((r = sshkey_enable_maxsign(k, maxsign)) != 0) {
686 error_fr(r, "enable maxsign");
690 case SSH_AGENT_CONSTRAIN_EXTENSION:
691 if ((r = parse_key_constraint_extension(m,
693 goto out; /* error already logged */
696 error_f("Unknown constraint %d", ctype);
697 r = SSH_ERR_FEATURE_UNSUPPORTED;
708 process_add_identity(SocketEntry *e)
711 int success = 0, confirm = 0;
712 char *fp, *comment = NULL, *sk_provider = NULL;
713 char canonical_provider[PATH_MAX];
716 struct sshkey *k = NULL;
717 int r = SSH_ERR_INTERNAL_ERROR;
719 debug2_f("entering");
720 if ((r = sshkey_private_deserialize(e->request, &k)) != 0 ||
722 (r = sshbuf_get_cstring(e->request, &comment, NULL)) != 0) {
723 error_fr(r, "parse");
726 if (parse_key_constraints(e->request, k, &death, &seconds, &confirm,
727 &sk_provider) != 0) {
728 error_f("failed to parse constraints");
729 sshbuf_reset(e->request);
733 if (sk_provider != NULL) {
734 if (!sshkey_is_sk(k)) {
735 error("Cannot add provider: %s is not an "
736 "authenticator-hosted key", sshkey_type(k));
739 if (strcasecmp(sk_provider, "internal") == 0) {
740 debug_f("internal provider");
742 if (realpath(sk_provider, canonical_provider) == NULL) {
743 verbose("failed provider \"%.100s\": "
744 "realpath: %s", sk_provider,
749 sk_provider = xstrdup(canonical_provider);
750 if (match_pattern_list(sk_provider,
751 allowed_providers, 0) != 1) {
752 error("Refusing add key: "
753 "provider %s not allowed", sk_provider);
758 if ((r = sshkey_shield_private(k)) != 0) {
759 error_fr(r, "shield private");
762 if (lifetime && !death)
763 death = monotime() + lifetime;
764 if ((id = lookup_identity(k)) == NULL) {
765 id = xcalloc(1, sizeof(Identity));
766 TAILQ_INSERT_TAIL(&idtab->idlist, id, next);
767 /* Increment the number of identities. */
770 /* key state might have been updated */
771 sshkey_free(id->key);
773 free(id->sk_provider);
777 id->comment = comment;
779 id->confirm = confirm;
780 id->sk_provider = sk_provider;
782 if ((fp = sshkey_fingerprint(k, SSH_FP_HASH_DEFAULT,
783 SSH_FP_DEFAULT)) == NULL)
784 fatal_f("sshkey_fingerprint failed");
785 debug_f("add %s %s \"%.100s\" (life: %u) (confirm: %u) "
786 "(provider: %s)", sshkey_ssh_name(k), fp, comment, seconds,
787 confirm, sk_provider == NULL ? "none" : sk_provider);
798 send_status(e, success);
801 /* XXX todo: encrypt sensitive data with passphrase */
803 process_lock_agent(SocketEntry *e, int lock)
805 int r, success = 0, delay;
807 u_char passwdhash[LOCK_SIZE];
808 static u_int fail_count = 0;
811 debug2_f("entering");
813 * This is deliberately fatal: the user has requested that we lock,
814 * but we can't parse their request properly. The only safe thing to
817 if ((r = sshbuf_get_cstring(e->request, &passwd, &pwlen)) != 0)
818 fatal_fr(r, "parse");
820 debug("empty password not supported");
821 } else if (locked && !lock) {
822 if (bcrypt_pbkdf(passwd, pwlen, lock_salt, sizeof(lock_salt),
823 passwdhash, sizeof(passwdhash), LOCK_ROUNDS) < 0)
824 fatal("bcrypt_pbkdf");
825 if (timingsafe_bcmp(passwdhash, lock_pwhash, LOCK_SIZE) == 0) {
826 debug("agent unlocked");
829 explicit_bzero(lock_pwhash, sizeof(lock_pwhash));
832 /* delay in 0.1s increments up to 10s */
833 if (fail_count < 100)
835 delay = 100000 * fail_count;
836 debug("unlock failed, delaying %0.1lf seconds",
837 (double)delay/1000000);
840 explicit_bzero(passwdhash, sizeof(passwdhash));
841 } else if (!locked && lock) {
842 debug("agent locked");
844 arc4random_buf(lock_salt, sizeof(lock_salt));
845 if (bcrypt_pbkdf(passwd, pwlen, lock_salt, sizeof(lock_salt),
846 lock_pwhash, sizeof(lock_pwhash), LOCK_ROUNDS) < 0)
847 fatal("bcrypt_pbkdf");
850 freezero(passwd, pwlen);
851 send_status(e, success);
855 no_identities(SocketEntry *e)
860 if ((msg = sshbuf_new()) == NULL)
861 fatal_f("sshbuf_new failed");
862 if ((r = sshbuf_put_u8(msg, SSH2_AGENT_IDENTITIES_ANSWER)) != 0 ||
863 (r = sshbuf_put_u32(msg, 0)) != 0 ||
864 (r = sshbuf_put_stringb(e->output, msg)) != 0)
865 fatal_fr(r, "compose");
871 process_add_smartcard_key(SocketEntry *e)
873 char *provider = NULL, *pin = NULL, canonical_provider[PATH_MAX];
874 char **comments = NULL;
875 int r, i, count = 0, success = 0, confirm = 0;
878 struct sshkey **keys = NULL, *k;
881 debug2_f("entering");
882 if ((r = sshbuf_get_cstring(e->request, &provider, NULL)) != 0 ||
883 (r = sshbuf_get_cstring(e->request, &pin, NULL)) != 0) {
884 error_fr(r, "parse");
887 if (parse_key_constraints(e->request, NULL, &death, &seconds, &confirm,
889 error_f("failed to parse constraints");
892 if (realpath(provider, canonical_provider) == NULL) {
893 verbose("failed PKCS#11 add of \"%.100s\": realpath: %s",
894 provider, strerror(errno));
897 if (match_pattern_list(canonical_provider, allowed_providers, 0) != 1) {
898 verbose("refusing PKCS#11 add of \"%.100s\": "
899 "provider not allowed", canonical_provider);
902 debug_f("add %.100s", canonical_provider);
903 if (lifetime && !death)
904 death = monotime() + lifetime;
906 count = pkcs11_add_provider(canonical_provider, pin, &keys, &comments);
907 for (i = 0; i < count; i++) {
909 if (lookup_identity(k) == NULL) {
910 id = xcalloc(1, sizeof(Identity));
912 keys[i] = NULL; /* transferred */
913 id->provider = xstrdup(canonical_provider);
914 if (*comments[i] != '\0') {
915 id->comment = comments[i];
916 comments[i] = NULL; /* transferred */
918 id->comment = xstrdup(canonical_provider);
921 id->confirm = confirm;
922 TAILQ_INSERT_TAIL(&idtab->idlist, id, next);
926 /* XXX update constraints for existing keys */
927 sshkey_free(keys[i]);
935 send_status(e, success);
939 process_remove_smartcard_key(SocketEntry *e)
941 char *provider = NULL, *pin = NULL, canonical_provider[PATH_MAX];
945 debug2_f("entering");
946 if ((r = sshbuf_get_cstring(e->request, &provider, NULL)) != 0 ||
947 (r = sshbuf_get_cstring(e->request, &pin, NULL)) != 0) {
948 error_fr(r, "parse");
953 if (realpath(provider, canonical_provider) == NULL) {
954 verbose("failed PKCS#11 add of \"%.100s\": realpath: %s",
955 provider, strerror(errno));
959 debug_f("remove %.100s", canonical_provider);
960 for (id = TAILQ_FIRST(&idtab->idlist); id; id = nxt) {
961 nxt = TAILQ_NEXT(id, next);
962 /* Skip file--based keys */
963 if (id->provider == NULL)
965 if (!strcmp(canonical_provider, id->provider)) {
966 TAILQ_REMOVE(&idtab->idlist, id, next);
971 if (pkcs11_del_provider(canonical_provider) == 0)
974 error_f("pkcs11_del_provider failed");
977 send_status(e, success);
979 #endif /* ENABLE_PKCS11 */
982 * dispatch incoming message.
983 * returns 1 on success, 0 for incomplete messages or -1 on error.
986 process_message(u_int socknum)
994 if (socknum >= sockets_alloc)
995 fatal_f("sock %u >= allocated %u", socknum, sockets_alloc);
996 e = &sockets[socknum];
998 if (sshbuf_len(e->input) < 5)
999 return 0; /* Incomplete message header. */
1000 cp = sshbuf_ptr(e->input);
1001 msg_len = PEEK_U32(cp);
1002 if (msg_len > AGENT_MAX_LEN) {
1003 debug_f("socket %u (fd=%d) message too long %u > %u",
1004 socknum, e->fd, msg_len, AGENT_MAX_LEN);
1007 if (sshbuf_len(e->input) < msg_len + 4)
1008 return 0; /* Incomplete message body. */
1010 /* move the current input to e->request */
1011 sshbuf_reset(e->request);
1012 if ((r = sshbuf_get_stringb(e->input, e->request)) != 0 ||
1013 (r = sshbuf_get_u8(e->request, &type)) != 0) {
1014 if (r == SSH_ERR_MESSAGE_INCOMPLETE ||
1015 r == SSH_ERR_STRING_TOO_LARGE) {
1016 error_fr(r, "parse");
1019 fatal_fr(r, "parse");
1022 debug_f("socket %u (fd=%d) type %d", socknum, e->fd, type);
1024 /* check whether agent is locked */
1025 if (locked && type != SSH_AGENTC_UNLOCK) {
1026 sshbuf_reset(e->request);
1028 case SSH2_AGENTC_REQUEST_IDENTITIES:
1029 /* send empty lists */
1033 /* send a fail message for all other request types */
1040 case SSH_AGENTC_LOCK:
1041 case SSH_AGENTC_UNLOCK:
1042 process_lock_agent(e, type == SSH_AGENTC_LOCK);
1044 case SSH_AGENTC_REMOVE_ALL_RSA_IDENTITIES:
1045 process_remove_all_identities(e); /* safe for !WITH_SSH1 */
1048 case SSH2_AGENTC_SIGN_REQUEST:
1049 process_sign_request2(e);
1051 case SSH2_AGENTC_REQUEST_IDENTITIES:
1052 process_request_identities(e);
1054 case SSH2_AGENTC_ADD_IDENTITY:
1055 case SSH2_AGENTC_ADD_ID_CONSTRAINED:
1056 process_add_identity(e);
1058 case SSH2_AGENTC_REMOVE_IDENTITY:
1059 process_remove_identity(e);
1061 case SSH2_AGENTC_REMOVE_ALL_IDENTITIES:
1062 process_remove_all_identities(e);
1064 #ifdef ENABLE_PKCS11
1065 case SSH_AGENTC_ADD_SMARTCARD_KEY:
1066 case SSH_AGENTC_ADD_SMARTCARD_KEY_CONSTRAINED:
1067 process_add_smartcard_key(e);
1069 case SSH_AGENTC_REMOVE_SMARTCARD_KEY:
1070 process_remove_smartcard_key(e);
1072 #endif /* ENABLE_PKCS11 */
1074 /* Unknown message. Respond with failure. */
1075 error("Unknown message %d", type);
1076 sshbuf_reset(e->request);
1084 new_socket(sock_type type, int fd)
1086 u_int i, old_alloc, new_alloc;
1088 debug_f("type = %s", type == AUTH_CONNECTION ? "CONNECTION" :
1089 (type == AUTH_SOCKET ? "SOCKET" : "UNKNOWN"));
1090 if (type == AUTH_CONNECTION) {
1091 debug("xcount %d -> %d", xcount, xcount + 1);
1099 for (i = 0; i < sockets_alloc; i++)
1100 if (sockets[i].type == AUTH_UNUSED) {
1102 if ((sockets[i].input = sshbuf_new()) == NULL ||
1103 (sockets[i].output = sshbuf_new()) == NULL ||
1104 (sockets[i].request = sshbuf_new()) == NULL)
1105 fatal_f("sshbuf_new failed");
1106 sockets[i].type = type;
1109 old_alloc = sockets_alloc;
1110 new_alloc = sockets_alloc + 10;
1111 sockets = xrecallocarray(sockets, old_alloc, new_alloc,
1112 sizeof(sockets[0]));
1113 for (i = old_alloc; i < new_alloc; i++)
1114 sockets[i].type = AUTH_UNUSED;
1115 sockets_alloc = new_alloc;
1116 sockets[old_alloc].fd = fd;
1117 if ((sockets[old_alloc].input = sshbuf_new()) == NULL ||
1118 (sockets[old_alloc].output = sshbuf_new()) == NULL ||
1119 (sockets[old_alloc].request = sshbuf_new()) == NULL)
1120 fatal_f("sshbuf_new failed");
1121 sockets[old_alloc].type = type;
1125 handle_socket_read(u_int socknum)
1127 struct sockaddr_un sunaddr;
1133 slen = sizeof(sunaddr);
1134 fd = accept(sockets[socknum].fd, (struct sockaddr *)&sunaddr, &slen);
1136 error("accept from AUTH_SOCKET: %s", strerror(errno));
1139 if (getpeereid(fd, &euid, &egid) == -1) {
1140 error("getpeereid %d failed: %s", fd, strerror(errno));
1144 if ((euid != 0) && (getuid() != euid)) {
1145 error("uid mismatch: peer euid %u != uid %u",
1146 (u_int) euid, (u_int) getuid());
1150 new_socket(AUTH_CONNECTION, fd);
1155 handle_conn_read(u_int socknum)
1157 char buf[AGENT_RBUF_LEN];
1161 if ((len = read(sockets[socknum].fd, buf, sizeof(buf))) <= 0) {
1163 if (errno == EAGAIN || errno == EINTR)
1165 error_f("read error on socket %u (fd %d): %s",
1166 socknum, sockets[socknum].fd, strerror(errno));
1170 if ((r = sshbuf_put(sockets[socknum].input, buf, len)) != 0)
1171 fatal_fr(r, "compose");
1172 explicit_bzero(buf, sizeof(buf));
1174 if ((r = process_message(socknum)) == -1)
1183 handle_conn_write(u_int socknum)
1188 if (sshbuf_len(sockets[socknum].output) == 0)
1189 return 0; /* shouldn't happen */
1190 if ((len = write(sockets[socknum].fd,
1191 sshbuf_ptr(sockets[socknum].output),
1192 sshbuf_len(sockets[socknum].output))) <= 0) {
1194 if (errno == EAGAIN || errno == EINTR)
1196 error_f("read error on socket %u (fd %d): %s",
1197 socknum, sockets[socknum].fd, strerror(errno));
1201 if ((r = sshbuf_consume(sockets[socknum].output, len)) != 0)
1202 fatal_fr(r, "consume");
1207 after_poll(struct pollfd *pfd, size_t npfd, u_int maxfds)
1210 u_int socknum, activefds = npfd;
1212 for (i = 0; i < npfd; i++) {
1213 if (pfd[i].revents == 0)
1215 /* Find sockets entry */
1216 for (socknum = 0; socknum < sockets_alloc; socknum++) {
1217 if (sockets[socknum].type != AUTH_SOCKET &&
1218 sockets[socknum].type != AUTH_CONNECTION)
1220 if (pfd[i].fd == sockets[socknum].fd)
1223 if (socknum >= sockets_alloc) {
1224 error_f("no socket for fd %d", pfd[i].fd);
1227 /* Process events */
1228 switch (sockets[socknum].type) {
1230 if ((pfd[i].revents & (POLLIN|POLLERR)) == 0)
1232 if (npfd > maxfds) {
1233 debug3("out of fds (active %u >= limit %u); "
1234 "skipping accept", activefds, maxfds);
1237 if (handle_socket_read(socknum) == 0)
1240 case AUTH_CONNECTION:
1241 if ((pfd[i].revents & (POLLIN|POLLERR)) != 0 &&
1242 handle_conn_read(socknum) != 0) {
1245 if ((pfd[i].revents & (POLLOUT|POLLHUP)) != 0 &&
1246 handle_conn_write(socknum) != 0) {
1249 fatal("activefds == 0 at close_sock");
1250 close_socket(&sockets[socknum]);
1262 prepare_poll(struct pollfd **pfdp, size_t *npfdp, int *timeoutp, u_int maxfds)
1264 struct pollfd *pfd = *pfdp;
1265 size_t i, j, npfd = 0;
1269 /* Count active sockets */
1270 for (i = 0; i < sockets_alloc; i++) {
1271 switch (sockets[i].type) {
1273 case AUTH_CONNECTION:
1279 fatal("Unknown socket type %d", sockets[i].type);
1283 if (npfd != *npfdp &&
1284 (pfd = recallocarray(pfd, *npfdp, npfd, sizeof(*pfd))) == NULL)
1285 fatal_f("recallocarray failed");
1289 for (i = j = 0; i < sockets_alloc; i++) {
1290 switch (sockets[i].type) {
1292 if (npfd > maxfds) {
1293 debug3("out of fds (active %zu >= limit %u); "
1294 "skipping arming listener", npfd, maxfds);
1297 pfd[j].fd = sockets[i].fd;
1299 pfd[j].events = POLLIN;
1302 case AUTH_CONNECTION:
1303 pfd[j].fd = sockets[i].fd;
1306 * Only prepare to read if we can handle a full-size
1307 * input read buffer and enqueue a max size reply..
1309 if ((r = sshbuf_check_reserve(sockets[i].input,
1310 AGENT_RBUF_LEN)) == 0 &&
1311 (r = sshbuf_check_reserve(sockets[i].output,
1312 AGENT_MAX_LEN)) == 0)
1313 pfd[j].events = POLLIN;
1314 else if (r != SSH_ERR_NO_BUFFER_SPACE)
1315 fatal_fr(r, "reserve");
1316 if (sshbuf_len(sockets[i].output) > 0)
1317 pfd[j].events |= POLLOUT;
1324 deadline = reaper();
1325 if (parent_alive_interval != 0)
1326 deadline = (deadline == 0) ? parent_alive_interval :
1327 MINIMUM(deadline, parent_alive_interval);
1328 if (deadline == 0) {
1329 *timeoutp = -1; /* INFTIM */
1331 if (deadline > INT_MAX / 1000)
1332 *timeoutp = INT_MAX / 1000;
1334 *timeoutp = deadline * 1000;
1340 cleanup_socket(void)
1342 if (cleanup_pid != 0 && getpid() != cleanup_pid)
1346 unlink(socket_name);
1360 cleanup_handler(int sig)
1363 #ifdef ENABLE_PKCS11
1370 check_parent_exists(void)
1373 * If our parent has exited then getppid() will return (pid_t)1,
1374 * so testing for that should be safe.
1376 if (parent_pid != -1 && getppid() != parent_pid) {
1377 /* printf("Parent has died - Authentication agent exiting.\n"); */
1387 "usage: ssh-agent [-c | -s] [-Ddx] [-a bind_address] [-E fingerprint_hash]\n"
1388 " [-P allowed_providers] [-t life]\n"
1389 " ssh-agent [-a bind_address] [-E fingerprint_hash] [-P allowed_providers]\n"
1390 " [-t life] command [arg ...]\n"
1391 " ssh-agent [-c | -s] -k\n");
1396 main(int ac, char **av)
1398 int c_flag = 0, d_flag = 0, D_flag = 0, k_flag = 0, s_flag = 0;
1399 int sock, ch, result, saved_errno;
1400 char *shell, *format, *pidstr, *agentsocket = NULL;
1401 #ifdef HAVE_SETRLIMIT
1405 extern char *optarg;
1407 char pidstrbuf[1 + 3 * sizeof pid];
1410 int timeout = -1; /* INFTIM */
1411 struct pollfd *pfd = NULL;
1415 /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
1423 platform_disable_tracing(0); /* strict=no */
1425 #ifdef RLIMIT_NOFILE
1426 if (getrlimit(RLIMIT_NOFILE, &rlim) == -1)
1427 fatal("%s: getrlimit: %s", __progname, strerror(errno));
1430 __progname = ssh_get_progname(av[0]);
1433 while ((ch = getopt(ac, av, "cDdksE:a:O:P:t:x")) != -1) {
1436 fingerprint_hash = ssh_digest_alg_by_name(optarg);
1437 if (fingerprint_hash == -1)
1438 fatal("Invalid hash algorithm \"%s\"", optarg);
1449 if (strcmp(optarg, "no-restrict-websafe") == 0)
1450 restrict_websafe = 0;
1452 fatal("Unknown -O option");
1455 if (allowed_providers != NULL)
1456 fatal("-P option already specified");
1457 allowed_providers = xstrdup(optarg);
1465 if (d_flag || D_flag)
1470 if (d_flag || D_flag)
1475 agentsocket = optarg;
1478 if ((lifetime = convtime(optarg)) == -1) {
1479 fprintf(stderr, "Invalid lifetime\n");
1493 if (ac > 0 && (c_flag || k_flag || s_flag || d_flag || D_flag))
1496 if (allowed_providers == NULL)
1497 allowed_providers = xstrdup(DEFAULT_ALLOWED_PROVIDERS);
1499 if (ac == 0 && !c_flag && !s_flag) {
1500 shell = getenv("SHELL");
1501 if (shell != NULL && (len = strlen(shell)) > 2 &&
1502 strncmp(shell + len - 3, "csh", 3) == 0)
1506 const char *errstr = NULL;
1508 pidstr = getenv(SSH_AGENTPID_ENV_NAME);
1509 if (pidstr == NULL) {
1510 fprintf(stderr, "%s not set, cannot kill agent\n",
1511 SSH_AGENTPID_ENV_NAME);
1514 pid = (int)strtonum(pidstr, 2, INT_MAX, &errstr);
1517 "%s=\"%s\", which is not a good PID: %s\n",
1518 SSH_AGENTPID_ENV_NAME, pidstr, errstr);
1521 if (kill(pid, SIGTERM) == -1) {
1525 format = c_flag ? "unsetenv %s;\n" : "unset %s;\n";
1526 printf(format, SSH_AUTHSOCKET_ENV_NAME);
1527 printf(format, SSH_AGENTPID_ENV_NAME);
1528 printf("echo Agent pid %ld killed;\n", (long)pid);
1533 * Minimum file descriptors:
1534 * stdio (3) + listener (1) + syslog (1 maybe) + connection (1) +
1535 * a few spare for libc / stack protectors / sanitisers, etc.
1537 #define SSH_AGENT_MIN_FDS (3+1+1+1+4)
1538 if (rlim.rlim_cur < SSH_AGENT_MIN_FDS)
1539 fatal("%s: file descriptor rlimit %lld too low (minimum %u)",
1540 __progname, (long long)rlim.rlim_cur, SSH_AGENT_MIN_FDS);
1541 maxfds = rlim.rlim_cur - SSH_AGENT_MIN_FDS;
1543 parent_pid = getpid();
1545 if (agentsocket == NULL) {
1546 /* Create private directory for agent socket */
1547 mktemp_proto(socket_dir, sizeof(socket_dir));
1548 if (mkdtemp(socket_dir) == NULL) {
1549 perror("mkdtemp: private socket dir");
1552 snprintf(socket_name, sizeof socket_name, "%s/agent.%ld", socket_dir,
1555 /* Try to use specified agent socket */
1556 socket_dir[0] = '\0';
1557 strlcpy(socket_name, agentsocket, sizeof socket_name);
1561 * Create socket early so it will exist before command gets run from
1564 prev_mask = umask(0177);
1565 sock = unix_listener(socket_name, SSH_LISTEN_BACKLOG, 0);
1567 /* XXX - unix_listener() calls error() not perror() */
1568 *socket_name = '\0'; /* Don't unlink any existing file */
1574 * Fork, and have the parent execute the command, if any, or present
1575 * the socket data. The child continues as the authentication agent.
1577 if (D_flag || d_flag) {
1578 log_init(__progname,
1579 d_flag ? SYSLOG_LEVEL_DEBUG3 : SYSLOG_LEVEL_INFO,
1580 SYSLOG_FACILITY_AUTH, 1);
1581 format = c_flag ? "setenv %s %s;\n" : "%s=%s; export %s;\n";
1582 printf(format, SSH_AUTHSOCKET_ENV_NAME, socket_name,
1583 SSH_AUTHSOCKET_ENV_NAME);
1584 printf("echo Agent pid %ld;\n", (long)parent_pid);
1593 if (pid != 0) { /* Parent - execute the given command. */
1595 snprintf(pidstrbuf, sizeof pidstrbuf, "%ld", (long)pid);
1597 format = c_flag ? "setenv %s %s;\n" : "%s=%s; export %s;\n";
1598 printf(format, SSH_AUTHSOCKET_ENV_NAME, socket_name,
1599 SSH_AUTHSOCKET_ENV_NAME);
1600 printf(format, SSH_AGENTPID_ENV_NAME, pidstrbuf,
1601 SSH_AGENTPID_ENV_NAME);
1602 printf("echo Agent pid %ld;\n", (long)pid);
1605 if (setenv(SSH_AUTHSOCKET_ENV_NAME, socket_name, 1) == -1 ||
1606 setenv(SSH_AGENTPID_ENV_NAME, pidstrbuf, 1) == -1) {
1615 log_init(__progname, SYSLOG_LEVEL_INFO, SYSLOG_FACILITY_AUTH, 0);
1617 if (setsid() == -1) {
1618 error("setsid: %s", strerror(errno));
1623 if (stdfd_devnull(1, 1, 1) == -1)
1624 error_f("stdfd_devnull failed");
1626 #ifdef HAVE_SETRLIMIT
1627 /* deny core dumps, since memory contains unencrypted private keys */
1628 rlim.rlim_cur = rlim.rlim_max = 0;
1629 if (setrlimit(RLIMIT_CORE, &rlim) == -1) {
1630 error("setrlimit RLIMIT_CORE: %s", strerror(errno));
1637 cleanup_pid = getpid();
1639 #ifdef ENABLE_PKCS11
1642 new_socket(AUTH_SOCKET, sock);
1644 parent_alive_interval = 10;
1646 ssh_signal(SIGPIPE, SIG_IGN);
1647 ssh_signal(SIGINT, (d_flag | D_flag) ? cleanup_handler : SIG_IGN);
1648 ssh_signal(SIGHUP, cleanup_handler);
1649 ssh_signal(SIGTERM, cleanup_handler);
1651 if (pledge("stdio rpath cpath unix id proc exec", NULL) == -1)
1652 fatal("%s: pledge: %s", __progname, strerror(errno));
1653 platform_pledge_agent();
1656 prepare_poll(&pfd, &npfd, &timeout, maxfds);
1657 result = poll(pfd, npfd, timeout);
1658 saved_errno = errno;
1659 if (parent_alive_interval != 0)
1660 check_parent_exists();
1661 (void) reaper(); /* remove expired keys */
1663 if (saved_errno == EINTR)
1665 fatal("poll: %s", strerror(saved_errno));
1666 } else if (result > 0)
1667 after_poll(pfd, npfd, maxfds);