1 /* $OpenBSD: ssh-agent.c,v 1.257 2020/03/06 18:28:27 markus 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/param.h>
41 #include <sys/resource.h>
43 #include <sys/socket.h>
45 #ifdef HAVE_SYS_TIME_H
46 # include <sys/time.h>
51 #include "openbsd-compat/sys-queue.h"
54 #include <openssl/evp.h>
55 #include "openbsd-compat/openssl-compat.h"
91 #include "pathnames.h"
92 #include "ssh-pkcs11.h"
95 #ifndef DEFAULT_PROVIDER_WHITELIST
96 # define DEFAULT_PROVIDER_WHITELIST "/usr/lib*/*,/usr/local/lib*/*"
99 /* Maximum accepted message length */
100 #define AGENT_MAX_LEN (256*1024)
101 /* Maximum bytes to read from client socket */
102 #define AGENT_RBUF_LEN (4096)
113 struct sshbuf *input;
114 struct sshbuf *output;
115 struct sshbuf *request;
118 u_int sockets_alloc = 0;
119 SocketEntry *sockets = NULL;
121 typedef struct identity {
122 TAILQ_ENTRY(identity) next;
133 TAILQ_HEAD(idqueue, identity) idlist;
136 /* private key table */
137 struct idtable *idtab;
141 /* pid of shell == parent of agent */
142 pid_t parent_pid = -1;
143 time_t parent_alive_interval = 0;
145 /* pid of process for which cleanup_socket is applicable */
146 pid_t cleanup_pid = 0;
148 /* pathname and directory for AUTH_SOCKET */
149 char socket_name[PATH_MAX];
150 char socket_dir[PATH_MAX];
152 /* PKCS#11/Security key path whitelist */
153 static char *provider_whitelist;
157 #define LOCK_SALT_SIZE 16
158 #define LOCK_ROUNDS 1
160 u_char lock_pwhash[LOCK_SIZE];
161 u_char lock_salt[LOCK_SALT_SIZE];
163 extern char *__progname;
165 /* Default lifetime in seconds (0 == forever) */
166 static long lifetime = 0;
168 static int fingerprint_hash = SSH_FP_HASH_DEFAULT;
171 close_socket(SocketEntry *e)
175 e->type = AUTH_UNUSED;
176 sshbuf_free(e->input);
177 sshbuf_free(e->output);
178 sshbuf_free(e->request);
184 idtab = xcalloc(1, sizeof(*idtab));
185 TAILQ_INIT(&idtab->idlist);
190 free_identity(Identity *id)
192 sshkey_free(id->key);
195 free(id->sk_provider);
199 /* return matching private key for given public key */
201 lookup_identity(struct sshkey *key)
205 TAILQ_FOREACH(id, &idtab->idlist, next) {
206 if (sshkey_equal(key, id->key))
212 /* Check confirmation of keysign request */
214 confirm_key(Identity *id)
219 p = sshkey_fingerprint(id->key, fingerprint_hash, SSH_FP_DEFAULT);
221 ask_permission("Allow use of key %s?\nKey fingerprint %s.",
230 send_status(SocketEntry *e, int success)
234 if ((r = sshbuf_put_u32(e->output, 1)) != 0 ||
235 (r = sshbuf_put_u8(e->output, success ?
236 SSH_AGENT_SUCCESS : SSH_AGENT_FAILURE)) != 0)
237 fatal("%s: buffer error: %s", __func__, ssh_err(r));
240 /* send list of supported public keys to 'client' */
242 process_request_identities(SocketEntry *e)
248 if ((msg = sshbuf_new()) == NULL)
249 fatal("%s: sshbuf_new failed", __func__);
250 if ((r = sshbuf_put_u8(msg, SSH2_AGENT_IDENTITIES_ANSWER)) != 0 ||
251 (r = sshbuf_put_u32(msg, idtab->nentries)) != 0)
252 fatal("%s: buffer error: %s", __func__, ssh_err(r));
253 TAILQ_FOREACH(id, &idtab->idlist, next) {
254 if ((r = sshkey_puts_opts(id->key, msg, SSHKEY_SERIALIZE_INFO))
256 (r = sshbuf_put_cstring(msg, id->comment)) != 0) {
257 error("%s: put key/comment: %s", __func__,
262 if ((r = sshbuf_put_stringb(e->output, msg)) != 0)
263 fatal("%s: buffer error: %s", __func__, ssh_err(r));
269 agent_decode_alg(struct sshkey *key, u_int flags)
271 if (key->type == KEY_RSA) {
272 if (flags & SSH_AGENT_RSA_SHA2_256)
273 return "rsa-sha2-256";
274 else if (flags & SSH_AGENT_RSA_SHA2_512)
275 return "rsa-sha2-512";
276 } else if (key->type == KEY_RSA_CERT) {
277 if (flags & SSH_AGENT_RSA_SHA2_256)
278 return "rsa-sha2-256-cert-v01@openssh.com";
279 else if (flags & SSH_AGENT_RSA_SHA2_512)
280 return "rsa-sha2-512-cert-v01@openssh.com";
287 process_sign_request2(SocketEntry *e)
290 u_char *signature = NULL;
291 size_t dlen, slen = 0;
292 u_int compat = 0, flags;
296 struct sshkey *key = NULL;
298 struct notifier_ctx *notifier = NULL;
300 if ((msg = sshbuf_new()) == NULL)
301 fatal("%s: sshbuf_new failed", __func__);
302 if ((r = sshkey_froms(e->request, &key)) != 0 ||
303 (r = sshbuf_get_string_direct(e->request, &data, &dlen)) != 0 ||
304 (r = sshbuf_get_u32(e->request, &flags)) != 0) {
305 error("%s: couldn't parse request: %s", __func__, ssh_err(r));
309 if ((id = lookup_identity(key)) == NULL) {
310 verbose("%s: %s key not found", __func__, sshkey_type(key));
313 if (id->confirm && confirm_key(id) != 0) {
314 verbose("%s: user refused key", __func__);
317 if (sshkey_is_sk(id->key) &&
318 (id->key->sk_flags & SSH_SK_USER_PRESENCE_REQD)) {
319 if ((fp = sshkey_fingerprint(key, SSH_FP_HASH_DEFAULT,
320 SSH_FP_DEFAULT)) == NULL)
321 fatal("%s: fingerprint failed", __func__);
322 notifier = notify_start(0,
323 "Confirm user presence for key %s %s",
324 sshkey_type(id->key), fp);
326 if ((r = sshkey_sign(id->key, &signature, &slen,
327 data, dlen, agent_decode_alg(key, flags),
328 id->sk_provider, compat)) != 0) {
329 error("%s: sshkey_sign: %s", __func__, ssh_err(r));
335 notify_complete(notifier);
339 if ((r = sshbuf_put_u8(msg, SSH2_AGENT_SIGN_RESPONSE)) != 0 ||
340 (r = sshbuf_put_string(msg, signature, slen)) != 0)
341 fatal("%s: buffer error: %s", __func__, ssh_err(r));
342 } else if ((r = sshbuf_put_u8(msg, SSH_AGENT_FAILURE)) != 0)
343 fatal("%s: buffer error: %s", __func__, ssh_err(r));
345 if ((r = sshbuf_put_stringb(e->output, msg)) != 0)
346 fatal("%s: buffer error: %s", __func__, ssh_err(r));
354 process_remove_identity(SocketEntry *e)
357 struct sshkey *key = NULL;
360 if ((r = sshkey_froms(e->request, &key)) != 0) {
361 error("%s: get key: %s", __func__, ssh_err(r));
364 if ((id = lookup_identity(key)) == NULL) {
365 debug("%s: key not found", __func__);
368 /* We have this key, free it. */
369 if (idtab->nentries < 1)
370 fatal("%s: internal error: nentries %d",
371 __func__, idtab->nentries);
372 TAILQ_REMOVE(&idtab->idlist, id, next);
378 send_status(e, success);
382 process_remove_all_identities(SocketEntry *e)
386 /* Loop over all identities and clear the keys. */
387 for (id = TAILQ_FIRST(&idtab->idlist); id;
388 id = TAILQ_FIRST(&idtab->idlist)) {
389 TAILQ_REMOVE(&idtab->idlist, id, next);
393 /* Mark that there are no identities. */
400 /* removes expired keys and returns number of seconds until the next expiry */
404 time_t deadline = 0, now = monotime();
407 for (id = TAILQ_FIRST(&idtab->idlist); id; id = nxt) {
408 nxt = TAILQ_NEXT(id, next);
411 if (now >= id->death) {
412 debug("expiring key '%s'", id->comment);
413 TAILQ_REMOVE(&idtab->idlist, id, next);
417 deadline = (deadline == 0) ? id->death :
418 MINIMUM(deadline, id->death);
420 if (deadline == 0 || deadline <= now)
423 return (deadline - now);
427 process_add_identity(SocketEntry *e)
430 int success = 0, confirm = 0;
431 u_int seconds = 0, maxsign;
432 char *fp, *comment = NULL, *ext_name = NULL, *sk_provider = NULL;
433 char canonical_provider[PATH_MAX];
435 struct sshkey *k = NULL;
437 int r = SSH_ERR_INTERNAL_ERROR;
439 if ((r = sshkey_private_deserialize(e->request, &k)) != 0 ||
441 (r = sshbuf_get_cstring(e->request, &comment, NULL)) != 0) {
442 error("%s: decode private key: %s", __func__, ssh_err(r));
445 while (sshbuf_len(e->request)) {
446 if ((r = sshbuf_get_u8(e->request, &ctype)) != 0) {
447 error("%s: buffer error: %s", __func__, ssh_err(r));
451 case SSH_AGENT_CONSTRAIN_LIFETIME:
452 if ((r = sshbuf_get_u32(e->request, &seconds)) != 0) {
453 error("%s: bad lifetime constraint: %s",
454 __func__, ssh_err(r));
457 death = monotime() + seconds;
459 case SSH_AGENT_CONSTRAIN_CONFIRM:
462 case SSH_AGENT_CONSTRAIN_MAXSIGN:
463 if ((r = sshbuf_get_u32(e->request, &maxsign)) != 0) {
464 error("%s: bad maxsign constraint: %s",
465 __func__, ssh_err(r));
468 if ((r = sshkey_enable_maxsign(k, maxsign)) != 0) {
469 error("%s: cannot enable maxsign: %s",
470 __func__, ssh_err(r));
474 case SSH_AGENT_CONSTRAIN_EXTENSION:
475 if ((r = sshbuf_get_cstring(e->request,
476 &ext_name, NULL)) != 0) {
477 error("%s: cannot parse extension: %s",
478 __func__, ssh_err(r));
481 debug("%s: constraint ext %s", __func__, ext_name);
482 if (strcmp(ext_name, "sk-provider@openssh.com") == 0) {
483 if (sk_provider != NULL) {
484 error("%s already set", ext_name);
487 if ((r = sshbuf_get_cstring(e->request,
488 &sk_provider, NULL)) != 0) {
489 error("%s: cannot parse %s: %s",
490 __func__, ext_name, ssh_err(r));
494 error("%s: unsupported constraint \"%s\"",
501 error("%s: Unknown constraint %d", __func__, ctype);
505 sshbuf_reset(e->request);
511 if (sk_provider != NULL) {
512 if (!sshkey_is_sk(k)) {
513 error("Cannot add provider: %s is not an "
514 "authenticator-hosted key", sshkey_type(k));
518 if (strcasecmp(sk_provider, "internal") == 0) {
519 debug("%s: internal provider", __func__);
521 if (realpath(sk_provider, canonical_provider) == NULL) {
522 verbose("failed provider \"%.100s\": "
523 "realpath: %s", sk_provider,
529 sk_provider = xstrdup(canonical_provider);
530 if (match_pattern_list(sk_provider,
531 provider_whitelist, 0) != 1) {
532 error("Refusing add key: "
533 "provider %s not whitelisted", sk_provider);
539 if ((r = sshkey_shield_private(k)) != 0) {
540 error("%s: shield private key: %s", __func__, ssh_err(r));
545 if (lifetime && !death)
546 death = monotime() + lifetime;
547 if ((id = lookup_identity(k)) == NULL) {
548 id = xcalloc(1, sizeof(Identity));
549 TAILQ_INSERT_TAIL(&idtab->idlist, id, next);
550 /* Increment the number of identities. */
553 /* key state might have been updated */
554 sshkey_free(id->key);
556 free(id->sk_provider);
559 id->comment = comment;
561 id->confirm = confirm;
562 id->sk_provider = sk_provider;
564 if ((fp = sshkey_fingerprint(k, SSH_FP_HASH_DEFAULT,
565 SSH_FP_DEFAULT)) == NULL)
566 fatal("%s: sshkey_fingerprint failed", __func__);
567 debug("%s: add %s %s \"%.100s\" (life: %u) (confirm: %u) "
568 "(provider: %s)", __func__, sshkey_ssh_name(k), fp, comment,
569 seconds, confirm, sk_provider == NULL ? "none" : sk_provider);
572 send_status(e, success);
575 /* XXX todo: encrypt sensitive data with passphrase */
577 process_lock_agent(SocketEntry *e, int lock)
579 int r, success = 0, delay;
581 u_char passwdhash[LOCK_SIZE];
582 static u_int fail_count = 0;
586 * This is deliberately fatal: the user has requested that we lock,
587 * but we can't parse their request properly. The only safe thing to
590 if ((r = sshbuf_get_cstring(e->request, &passwd, &pwlen)) != 0)
591 fatal("%s: buffer error: %s", __func__, ssh_err(r));
593 debug("empty password not supported");
594 } else if (locked && !lock) {
595 if (bcrypt_pbkdf(passwd, pwlen, lock_salt, sizeof(lock_salt),
596 passwdhash, sizeof(passwdhash), LOCK_ROUNDS) < 0)
597 fatal("bcrypt_pbkdf");
598 if (timingsafe_bcmp(passwdhash, lock_pwhash, LOCK_SIZE) == 0) {
599 debug("agent unlocked");
602 explicit_bzero(lock_pwhash, sizeof(lock_pwhash));
605 /* delay in 0.1s increments up to 10s */
606 if (fail_count < 100)
608 delay = 100000 * fail_count;
609 debug("unlock failed, delaying %0.1lf seconds",
610 (double)delay/1000000);
613 explicit_bzero(passwdhash, sizeof(passwdhash));
614 } else if (!locked && lock) {
615 debug("agent locked");
617 arc4random_buf(lock_salt, sizeof(lock_salt));
618 if (bcrypt_pbkdf(passwd, pwlen, lock_salt, sizeof(lock_salt),
619 lock_pwhash, sizeof(lock_pwhash), LOCK_ROUNDS) < 0)
620 fatal("bcrypt_pbkdf");
623 freezero(passwd, pwlen);
624 send_status(e, success);
628 no_identities(SocketEntry *e)
633 if ((msg = sshbuf_new()) == NULL)
634 fatal("%s: sshbuf_new failed", __func__);
635 if ((r = sshbuf_put_u8(msg, SSH2_AGENT_IDENTITIES_ANSWER)) != 0 ||
636 (r = sshbuf_put_u32(msg, 0)) != 0 ||
637 (r = sshbuf_put_stringb(e->output, msg)) != 0)
638 fatal("%s: buffer error: %s", __func__, ssh_err(r));
644 process_add_smartcard_key(SocketEntry *e)
646 char *provider = NULL, *pin = NULL, canonical_provider[PATH_MAX];
647 char **comments = NULL;
648 int r, i, count = 0, success = 0, confirm = 0;
652 struct sshkey **keys = NULL, *k;
655 if ((r = sshbuf_get_cstring(e->request, &provider, NULL)) != 0 ||
656 (r = sshbuf_get_cstring(e->request, &pin, NULL)) != 0) {
657 error("%s: buffer error: %s", __func__, ssh_err(r));
661 while (sshbuf_len(e->request)) {
662 if ((r = sshbuf_get_u8(e->request, &type)) != 0) {
663 error("%s: buffer error: %s", __func__, ssh_err(r));
667 case SSH_AGENT_CONSTRAIN_LIFETIME:
668 if ((r = sshbuf_get_u32(e->request, &seconds)) != 0) {
669 error("%s: buffer error: %s",
670 __func__, ssh_err(r));
673 death = monotime() + seconds;
675 case SSH_AGENT_CONSTRAIN_CONFIRM:
679 error("%s: Unknown constraint type %d", __func__, type);
683 if (realpath(provider, canonical_provider) == NULL) {
684 verbose("failed PKCS#11 add of \"%.100s\": realpath: %s",
685 provider, strerror(errno));
688 if (match_pattern_list(canonical_provider, provider_whitelist, 0) != 1) {
689 verbose("refusing PKCS#11 add of \"%.100s\": "
690 "provider not whitelisted", canonical_provider);
693 debug("%s: add %.100s", __func__, canonical_provider);
694 if (lifetime && !death)
695 death = monotime() + lifetime;
697 count = pkcs11_add_provider(canonical_provider, pin, &keys, &comments);
698 for (i = 0; i < count; i++) {
700 if (lookup_identity(k) == NULL) {
701 id = xcalloc(1, sizeof(Identity));
703 keys[i] = NULL; /* transferred */
704 id->provider = xstrdup(canonical_provider);
705 if (*comments[i] != '\0') {
706 id->comment = comments[i];
707 comments[i] = NULL; /* transferred */
709 id->comment = xstrdup(canonical_provider);
712 id->confirm = confirm;
713 TAILQ_INSERT_TAIL(&idtab->idlist, id, next);
717 sshkey_free(keys[i]);
725 send_status(e, success);
729 process_remove_smartcard_key(SocketEntry *e)
731 char *provider = NULL, *pin = NULL, canonical_provider[PATH_MAX];
735 if ((r = sshbuf_get_cstring(e->request, &provider, NULL)) != 0 ||
736 (r = sshbuf_get_cstring(e->request, &pin, NULL)) != 0) {
737 error("%s: buffer error: %s", __func__, ssh_err(r));
742 if (realpath(provider, canonical_provider) == NULL) {
743 verbose("failed PKCS#11 add of \"%.100s\": realpath: %s",
744 provider, strerror(errno));
748 debug("%s: remove %.100s", __func__, canonical_provider);
749 for (id = TAILQ_FIRST(&idtab->idlist); id; id = nxt) {
750 nxt = TAILQ_NEXT(id, next);
751 /* Skip file--based keys */
752 if (id->provider == NULL)
754 if (!strcmp(canonical_provider, id->provider)) {
755 TAILQ_REMOVE(&idtab->idlist, id, next);
760 if (pkcs11_del_provider(canonical_provider) == 0)
763 error("%s: pkcs11_del_provider failed", __func__);
766 send_status(e, success);
768 #endif /* ENABLE_PKCS11 */
770 /* dispatch incoming messages */
773 process_message(u_int socknum)
781 if (socknum >= sockets_alloc) {
782 fatal("%s: socket number %u >= allocated %u",
783 __func__, socknum, sockets_alloc);
785 e = &sockets[socknum];
787 if (sshbuf_len(e->input) < 5)
788 return 0; /* Incomplete message header. */
789 cp = sshbuf_ptr(e->input);
790 msg_len = PEEK_U32(cp);
791 if (msg_len > AGENT_MAX_LEN) {
792 debug("%s: socket %u (fd=%d) message too long %u > %u",
793 __func__, socknum, e->fd, msg_len, AGENT_MAX_LEN);
796 if (sshbuf_len(e->input) < msg_len + 4)
797 return 0; /* Incomplete message body. */
799 /* move the current input to e->request */
800 sshbuf_reset(e->request);
801 if ((r = sshbuf_get_stringb(e->input, e->request)) != 0 ||
802 (r = sshbuf_get_u8(e->request, &type)) != 0) {
803 if (r == SSH_ERR_MESSAGE_INCOMPLETE ||
804 r == SSH_ERR_STRING_TOO_LARGE) {
805 debug("%s: buffer error: %s", __func__, ssh_err(r));
808 fatal("%s: buffer error: %s", __func__, ssh_err(r));
811 debug("%s: socket %u (fd=%d) type %d", __func__, socknum, e->fd, type);
813 /* check whether agent is locked */
814 if (locked && type != SSH_AGENTC_UNLOCK) {
815 sshbuf_reset(e->request);
817 case SSH2_AGENTC_REQUEST_IDENTITIES:
818 /* send empty lists */
822 /* send a fail message for all other request types */
829 case SSH_AGENTC_LOCK:
830 case SSH_AGENTC_UNLOCK:
831 process_lock_agent(e, type == SSH_AGENTC_LOCK);
833 case SSH_AGENTC_REMOVE_ALL_RSA_IDENTITIES:
834 process_remove_all_identities(e); /* safe for !WITH_SSH1 */
837 case SSH2_AGENTC_SIGN_REQUEST:
838 process_sign_request2(e);
840 case SSH2_AGENTC_REQUEST_IDENTITIES:
841 process_request_identities(e);
843 case SSH2_AGENTC_ADD_IDENTITY:
844 case SSH2_AGENTC_ADD_ID_CONSTRAINED:
845 process_add_identity(e);
847 case SSH2_AGENTC_REMOVE_IDENTITY:
848 process_remove_identity(e);
850 case SSH2_AGENTC_REMOVE_ALL_IDENTITIES:
851 process_remove_all_identities(e);
854 case SSH_AGENTC_ADD_SMARTCARD_KEY:
855 case SSH_AGENTC_ADD_SMARTCARD_KEY_CONSTRAINED:
856 process_add_smartcard_key(e);
858 case SSH_AGENTC_REMOVE_SMARTCARD_KEY:
859 process_remove_smartcard_key(e);
861 #endif /* ENABLE_PKCS11 */
863 /* Unknown message. Respond with failure. */
864 error("Unknown message %d", type);
865 sshbuf_reset(e->request);
873 new_socket(sock_type type, int fd)
875 u_int i, old_alloc, new_alloc;
882 for (i = 0; i < sockets_alloc; i++)
883 if (sockets[i].type == AUTH_UNUSED) {
885 if ((sockets[i].input = sshbuf_new()) == NULL)
886 fatal("%s: sshbuf_new failed", __func__);
887 if ((sockets[i].output = sshbuf_new()) == NULL)
888 fatal("%s: sshbuf_new failed", __func__);
889 if ((sockets[i].request = sshbuf_new()) == NULL)
890 fatal("%s: sshbuf_new failed", __func__);
891 sockets[i].type = type;
894 old_alloc = sockets_alloc;
895 new_alloc = sockets_alloc + 10;
896 sockets = xreallocarray(sockets, new_alloc, sizeof(sockets[0]));
897 for (i = old_alloc; i < new_alloc; i++)
898 sockets[i].type = AUTH_UNUSED;
899 sockets_alloc = new_alloc;
900 sockets[old_alloc].fd = fd;
901 if ((sockets[old_alloc].input = sshbuf_new()) == NULL)
902 fatal("%s: sshbuf_new failed", __func__);
903 if ((sockets[old_alloc].output = sshbuf_new()) == NULL)
904 fatal("%s: sshbuf_new failed", __func__);
905 if ((sockets[old_alloc].request = sshbuf_new()) == NULL)
906 fatal("%s: sshbuf_new failed", __func__);
907 sockets[old_alloc].type = type;
911 handle_socket_read(u_int socknum)
913 struct sockaddr_un sunaddr;
919 slen = sizeof(sunaddr);
920 fd = accept(sockets[socknum].fd, (struct sockaddr *)&sunaddr, &slen);
922 error("accept from AUTH_SOCKET: %s", strerror(errno));
925 if (getpeereid(fd, &euid, &egid) == -1) {
926 error("getpeereid %d failed: %s", fd, strerror(errno));
930 if ((euid != 0) && (getuid() != euid)) {
931 error("uid mismatch: peer euid %u != uid %u",
932 (u_int) euid, (u_int) getuid());
936 new_socket(AUTH_CONNECTION, fd);
941 handle_conn_read(u_int socknum)
943 char buf[AGENT_RBUF_LEN];
947 if ((len = read(sockets[socknum].fd, buf, sizeof(buf))) <= 0) {
949 if (errno == EAGAIN || errno == EINTR)
951 error("%s: read error on socket %u (fd %d): %s",
952 __func__, socknum, sockets[socknum].fd,
957 if ((r = sshbuf_put(sockets[socknum].input, buf, len)) != 0)
958 fatal("%s: buffer error: %s", __func__, ssh_err(r));
959 explicit_bzero(buf, sizeof(buf));
960 process_message(socknum);
965 handle_conn_write(u_int socknum)
970 if (sshbuf_len(sockets[socknum].output) == 0)
971 return 0; /* shouldn't happen */
972 if ((len = write(sockets[socknum].fd,
973 sshbuf_ptr(sockets[socknum].output),
974 sshbuf_len(sockets[socknum].output))) <= 0) {
976 if (errno == EAGAIN || errno == EINTR)
978 error("%s: read error on socket %u (fd %d): %s",
979 __func__, socknum, sockets[socknum].fd,
984 if ((r = sshbuf_consume(sockets[socknum].output, len)) != 0)
985 fatal("%s: buffer error: %s", __func__, ssh_err(r));
990 after_poll(struct pollfd *pfd, size_t npfd, u_int maxfds)
993 u_int socknum, activefds = npfd;
995 for (i = 0; i < npfd; i++) {
996 if (pfd[i].revents == 0)
998 /* Find sockets entry */
999 for (socknum = 0; socknum < sockets_alloc; socknum++) {
1000 if (sockets[socknum].type != AUTH_SOCKET &&
1001 sockets[socknum].type != AUTH_CONNECTION)
1003 if (pfd[i].fd == sockets[socknum].fd)
1006 if (socknum >= sockets_alloc) {
1007 error("%s: no socket for fd %d", __func__, pfd[i].fd);
1010 /* Process events */
1011 switch (sockets[socknum].type) {
1013 if ((pfd[i].revents & (POLLIN|POLLERR)) == 0)
1015 if (npfd > maxfds) {
1016 debug3("out of fds (active %u >= limit %u); "
1017 "skipping accept", activefds, maxfds);
1020 if (handle_socket_read(socknum) == 0)
1023 case AUTH_CONNECTION:
1024 if ((pfd[i].revents & (POLLIN|POLLERR)) != 0 &&
1025 handle_conn_read(socknum) != 0) {
1028 if ((pfd[i].revents & (POLLOUT|POLLHUP)) != 0 &&
1029 handle_conn_write(socknum) != 0) {
1032 fatal("activefds == 0 at close_sock");
1033 close_socket(&sockets[socknum]);
1045 prepare_poll(struct pollfd **pfdp, size_t *npfdp, int *timeoutp, u_int maxfds)
1047 struct pollfd *pfd = *pfdp;
1048 size_t i, j, npfd = 0;
1052 /* Count active sockets */
1053 for (i = 0; i < sockets_alloc; i++) {
1054 switch (sockets[i].type) {
1056 case AUTH_CONNECTION:
1062 fatal("Unknown socket type %d", sockets[i].type);
1066 if (npfd != *npfdp &&
1067 (pfd = recallocarray(pfd, *npfdp, npfd, sizeof(*pfd))) == NULL)
1068 fatal("%s: recallocarray failed", __func__);
1072 for (i = j = 0; i < sockets_alloc; i++) {
1073 switch (sockets[i].type) {
1075 if (npfd > maxfds) {
1076 debug3("out of fds (active %zu >= limit %u); "
1077 "skipping arming listener", npfd, maxfds);
1080 pfd[j].fd = sockets[i].fd;
1082 pfd[j].events = POLLIN;
1085 case AUTH_CONNECTION:
1086 pfd[j].fd = sockets[i].fd;
1089 * Only prepare to read if we can handle a full-size
1090 * input read buffer and enqueue a max size reply..
1092 if ((r = sshbuf_check_reserve(sockets[i].input,
1093 AGENT_RBUF_LEN)) == 0 &&
1094 (r = sshbuf_check_reserve(sockets[i].output,
1095 AGENT_MAX_LEN)) == 0)
1096 pfd[j].events = POLLIN;
1097 else if (r != SSH_ERR_NO_BUFFER_SPACE) {
1098 fatal("%s: buffer error: %s",
1099 __func__, ssh_err(r));
1101 if (sshbuf_len(sockets[i].output) > 0)
1102 pfd[j].events |= POLLOUT;
1109 deadline = reaper();
1110 if (parent_alive_interval != 0)
1111 deadline = (deadline == 0) ? parent_alive_interval :
1112 MINIMUM(deadline, parent_alive_interval);
1113 if (deadline == 0) {
1114 *timeoutp = -1; /* INFTIM */
1116 if (deadline > INT_MAX / 1000)
1117 *timeoutp = INT_MAX / 1000;
1119 *timeoutp = deadline * 1000;
1125 cleanup_socket(void)
1127 if (cleanup_pid != 0 && getpid() != cleanup_pid)
1129 debug("%s: cleanup", __func__);
1131 unlink(socket_name);
1145 cleanup_handler(int sig)
1148 #ifdef ENABLE_PKCS11
1155 check_parent_exists(void)
1158 * If our parent has exited then getppid() will return (pid_t)1,
1159 * so testing for that should be safe.
1161 if (parent_pid != -1 && getppid() != parent_pid) {
1162 /* printf("Parent has died - Authentication agent exiting.\n"); */
1172 "usage: ssh-agent [-c | -s] [-Dd] [-a bind_address] [-E fingerprint_hash]\n"
1173 " [-P provider_whitelist] [-t life] [command [arg ...]]\n"
1174 " ssh-agent [-c | -s] -k\n");
1179 main(int ac, char **av)
1181 int c_flag = 0, d_flag = 0, D_flag = 0, k_flag = 0, s_flag = 0;
1182 int sock, fd, ch, result, saved_errno;
1183 char *shell, *format, *pidstr, *agentsocket = NULL;
1184 #ifdef HAVE_SETRLIMIT
1188 extern char *optarg;
1190 char pidstrbuf[1 + 3 * sizeof pid];
1193 int timeout = -1; /* INFTIM */
1194 struct pollfd *pfd = NULL;
1198 /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
1205 platform_disable_tracing(0); /* strict=no */
1207 #ifdef RLIMIT_NOFILE
1208 if (getrlimit(RLIMIT_NOFILE, &rlim) == -1)
1209 fatal("%s: getrlimit: %s", __progname, strerror(errno));
1212 __progname = ssh_get_progname(av[0]);
1215 while ((ch = getopt(ac, av, "cDdksE:a:P:t:")) != -1) {
1218 fingerprint_hash = ssh_digest_alg_by_name(optarg);
1219 if (fingerprint_hash == -1)
1220 fatal("Invalid hash algorithm \"%s\"", optarg);
1231 if (provider_whitelist != NULL)
1232 fatal("-P option already specified");
1233 provider_whitelist = xstrdup(optarg);
1241 if (d_flag || D_flag)
1246 if (d_flag || D_flag)
1251 agentsocket = optarg;
1254 if ((lifetime = convtime(optarg)) == -1) {
1255 fprintf(stderr, "Invalid lifetime\n");
1266 if (ac > 0 && (c_flag || k_flag || s_flag || d_flag || D_flag))
1269 if (provider_whitelist == NULL)
1270 provider_whitelist = xstrdup(DEFAULT_PROVIDER_WHITELIST);
1272 if (ac == 0 && !c_flag && !s_flag) {
1273 shell = getenv("SHELL");
1274 if (shell != NULL && (len = strlen(shell)) > 2 &&
1275 strncmp(shell + len - 3, "csh", 3) == 0)
1279 const char *errstr = NULL;
1281 pidstr = getenv(SSH_AGENTPID_ENV_NAME);
1282 if (pidstr == NULL) {
1283 fprintf(stderr, "%s not set, cannot kill agent\n",
1284 SSH_AGENTPID_ENV_NAME);
1287 pid = (int)strtonum(pidstr, 2, INT_MAX, &errstr);
1290 "%s=\"%s\", which is not a good PID: %s\n",
1291 SSH_AGENTPID_ENV_NAME, pidstr, errstr);
1294 if (kill(pid, SIGTERM) == -1) {
1298 format = c_flag ? "unsetenv %s;\n" : "unset %s;\n";
1299 printf(format, SSH_AUTHSOCKET_ENV_NAME);
1300 printf(format, SSH_AGENTPID_ENV_NAME);
1301 printf("echo Agent pid %ld killed;\n", (long)pid);
1306 * Minimum file descriptors:
1307 * stdio (3) + listener (1) + syslog (1 maybe) + connection (1) +
1308 * a few spare for libc / stack protectors / sanitisers, etc.
1310 #define SSH_AGENT_MIN_FDS (3+1+1+1+4)
1311 if (rlim.rlim_cur < SSH_AGENT_MIN_FDS)
1312 fatal("%s: file descriptor rlimit %lld too low (minimum %u)",
1313 __progname, (long long)rlim.rlim_cur, SSH_AGENT_MIN_FDS);
1314 maxfds = rlim.rlim_cur - SSH_AGENT_MIN_FDS;
1316 parent_pid = getpid();
1318 if (agentsocket == NULL) {
1319 /* Create private directory for agent socket */
1320 mktemp_proto(socket_dir, sizeof(socket_dir));
1321 if (mkdtemp(socket_dir) == NULL) {
1322 perror("mkdtemp: private socket dir");
1325 snprintf(socket_name, sizeof socket_name, "%s/agent.%ld", socket_dir,
1328 /* Try to use specified agent socket */
1329 socket_dir[0] = '\0';
1330 strlcpy(socket_name, agentsocket, sizeof socket_name);
1334 * Create socket early so it will exist before command gets run from
1337 prev_mask = umask(0177);
1338 sock = unix_listener(socket_name, SSH_LISTEN_BACKLOG, 0);
1340 /* XXX - unix_listener() calls error() not perror() */
1341 *socket_name = '\0'; /* Don't unlink any existing file */
1347 * Fork, and have the parent execute the command, if any, or present
1348 * the socket data. The child continues as the authentication agent.
1350 if (D_flag || d_flag) {
1351 log_init(__progname,
1352 d_flag ? SYSLOG_LEVEL_DEBUG3 : SYSLOG_LEVEL_INFO,
1353 SYSLOG_FACILITY_AUTH, 1);
1354 format = c_flag ? "setenv %s %s;\n" : "%s=%s; export %s;\n";
1355 printf(format, SSH_AUTHSOCKET_ENV_NAME, socket_name,
1356 SSH_AUTHSOCKET_ENV_NAME);
1357 printf("echo Agent pid %ld;\n", (long)parent_pid);
1366 if (pid != 0) { /* Parent - execute the given command. */
1368 snprintf(pidstrbuf, sizeof pidstrbuf, "%ld", (long)pid);
1370 format = c_flag ? "setenv %s %s;\n" : "%s=%s; export %s;\n";
1371 printf(format, SSH_AUTHSOCKET_ENV_NAME, socket_name,
1372 SSH_AUTHSOCKET_ENV_NAME);
1373 printf(format, SSH_AGENTPID_ENV_NAME, pidstrbuf,
1374 SSH_AGENTPID_ENV_NAME);
1375 printf("echo Agent pid %ld;\n", (long)pid);
1378 if (setenv(SSH_AUTHSOCKET_ENV_NAME, socket_name, 1) == -1 ||
1379 setenv(SSH_AGENTPID_ENV_NAME, pidstrbuf, 1) == -1) {
1388 log_init(__progname, SYSLOG_LEVEL_INFO, SYSLOG_FACILITY_AUTH, 0);
1390 if (setsid() == -1) {
1391 error("setsid: %s", strerror(errno));
1396 if ((fd = open(_PATH_DEVNULL, O_RDWR, 0)) != -1) {
1397 /* XXX might close listen socket */
1398 (void)dup2(fd, STDIN_FILENO);
1399 (void)dup2(fd, STDOUT_FILENO);
1400 (void)dup2(fd, STDERR_FILENO);
1405 #ifdef HAVE_SETRLIMIT
1406 /* deny core dumps, since memory contains unencrypted private keys */
1407 rlim.rlim_cur = rlim.rlim_max = 0;
1408 if (setrlimit(RLIMIT_CORE, &rlim) == -1) {
1409 error("setrlimit RLIMIT_CORE: %s", strerror(errno));
1416 cleanup_pid = getpid();
1418 #ifdef ENABLE_PKCS11
1421 new_socket(AUTH_SOCKET, sock);
1423 parent_alive_interval = 10;
1425 ssh_signal(SIGPIPE, SIG_IGN);
1426 ssh_signal(SIGINT, (d_flag | D_flag) ? cleanup_handler : SIG_IGN);
1427 ssh_signal(SIGHUP, cleanup_handler);
1428 ssh_signal(SIGTERM, cleanup_handler);
1430 if (pledge("stdio rpath cpath unix id proc exec", NULL) == -1)
1431 fatal("%s: pledge: %s", __progname, strerror(errno));
1432 platform_pledge_agent();
1435 prepare_poll(&pfd, &npfd, &timeout, maxfds);
1436 result = poll(pfd, npfd, timeout);
1437 saved_errno = errno;
1438 if (parent_alive_interval != 0)
1439 check_parent_exists();
1440 (void) reaper(); /* remove expired keys */
1442 if (saved_errno == EINTR)
1444 fatal("poll: %s", strerror(saved_errno));
1445 } else if (result > 0)
1446 after_poll(pfd, npfd, maxfds);