1 /* $OpenBSD: ssh-agent.c,v 1.233 2019/01/22 22:58:50 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/param.h>
41 #include <sys/resource.h>
43 #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"
90 #include "ssh-pkcs11.h"
93 #ifndef DEFAULT_PKCS11_WHITELIST
94 # define DEFAULT_PKCS11_WHITELIST "/usr/lib*/*,/usr/local/lib*/*"
97 /* Maximum accepted message length */
98 #define AGENT_MAX_LEN (256*1024)
99 /* Maximum bytes to read from client socket */
100 #define AGENT_RBUF_LEN (4096)
111 struct sshbuf *input;
112 struct sshbuf *output;
113 struct sshbuf *request;
116 u_int sockets_alloc = 0;
117 SocketEntry *sockets = NULL;
119 typedef struct identity {
120 TAILQ_ENTRY(identity) next;
130 TAILQ_HEAD(idqueue, identity) idlist;
133 /* private key table */
134 struct idtable *idtab;
138 /* pid of shell == parent of agent */
139 pid_t parent_pid = -1;
140 time_t parent_alive_interval = 0;
142 /* pid of process for which cleanup_socket is applicable */
143 pid_t cleanup_pid = 0;
145 /* pathname and directory for AUTH_SOCKET */
146 char socket_name[PATH_MAX];
147 char socket_dir[PATH_MAX];
149 /* PKCS#11 path whitelist */
150 static char *pkcs11_whitelist;
154 #define LOCK_SALT_SIZE 16
155 #define LOCK_ROUNDS 1
157 u_char lock_pwhash[LOCK_SIZE];
158 u_char lock_salt[LOCK_SALT_SIZE];
160 extern char *__progname;
162 /* Default lifetime in seconds (0 == forever) */
163 static long lifetime = 0;
165 static int fingerprint_hash = SSH_FP_HASH_DEFAULT;
168 close_socket(SocketEntry *e)
172 e->type = AUTH_UNUSED;
173 sshbuf_free(e->input);
174 sshbuf_free(e->output);
175 sshbuf_free(e->request);
181 idtab = xcalloc(1, sizeof(*idtab));
182 TAILQ_INIT(&idtab->idlist);
187 free_identity(Identity *id)
189 sshkey_free(id->key);
195 /* return matching private key for given public key */
197 lookup_identity(struct sshkey *key)
201 TAILQ_FOREACH(id, &idtab->idlist, next) {
202 if (sshkey_equal(key, id->key))
208 /* Check confirmation of keysign request */
210 confirm_key(Identity *id)
215 p = sshkey_fingerprint(id->key, fingerprint_hash, SSH_FP_DEFAULT);
217 ask_permission("Allow use of key %s?\nKey fingerprint %s.",
226 send_status(SocketEntry *e, int success)
230 if ((r = sshbuf_put_u32(e->output, 1)) != 0 ||
231 (r = sshbuf_put_u8(e->output, success ?
232 SSH_AGENT_SUCCESS : SSH_AGENT_FAILURE)) != 0)
233 fatal("%s: buffer error: %s", __func__, ssh_err(r));
236 /* send list of supported public keys to 'client' */
238 process_request_identities(SocketEntry *e)
244 if ((msg = sshbuf_new()) == NULL)
245 fatal("%s: sshbuf_new failed", __func__);
246 if ((r = sshbuf_put_u8(msg, SSH2_AGENT_IDENTITIES_ANSWER)) != 0 ||
247 (r = sshbuf_put_u32(msg, idtab->nentries)) != 0)
248 fatal("%s: buffer error: %s", __func__, ssh_err(r));
249 TAILQ_FOREACH(id, &idtab->idlist, next) {
250 if ((r = sshkey_puts_opts(id->key, msg, SSHKEY_SERIALIZE_INFO))
252 (r = sshbuf_put_cstring(msg, id->comment)) != 0) {
253 error("%s: put key/comment: %s", __func__,
258 if ((r = sshbuf_put_stringb(e->output, msg)) != 0)
259 fatal("%s: buffer error: %s", __func__, ssh_err(r));
265 agent_decode_alg(struct sshkey *key, u_int flags)
267 if (key->type == KEY_RSA) {
268 if (flags & SSH_AGENT_RSA_SHA2_256)
269 return "rsa-sha2-256";
270 else if (flags & SSH_AGENT_RSA_SHA2_512)
271 return "rsa-sha2-512";
278 process_sign_request2(SocketEntry *e)
281 u_char *signature = NULL;
282 size_t dlen, slen = 0;
283 u_int compat = 0, flags;
286 struct sshkey *key = NULL;
289 if ((msg = sshbuf_new()) == NULL)
290 fatal("%s: sshbuf_new failed", __func__);
291 if ((r = sshkey_froms(e->request, &key)) != 0 ||
292 (r = sshbuf_get_string_direct(e->request, &data, &dlen)) != 0 ||
293 (r = sshbuf_get_u32(e->request, &flags)) != 0) {
294 error("%s: couldn't parse request: %s", __func__, ssh_err(r));
298 if ((id = lookup_identity(key)) == NULL) {
299 verbose("%s: %s key not found", __func__, sshkey_type(key));
302 if (id->confirm && confirm_key(id) != 0) {
303 verbose("%s: user refused key", __func__);
306 if ((r = sshkey_sign(id->key, &signature, &slen,
307 data, dlen, agent_decode_alg(key, flags), compat)) != 0) {
308 error("%s: sshkey_sign: %s", __func__, ssh_err(r));
316 if ((r = sshbuf_put_u8(msg, SSH2_AGENT_SIGN_RESPONSE)) != 0 ||
317 (r = sshbuf_put_string(msg, signature, slen)) != 0)
318 fatal("%s: buffer error: %s", __func__, ssh_err(r));
319 } else if ((r = sshbuf_put_u8(msg, SSH_AGENT_FAILURE)) != 0)
320 fatal("%s: buffer error: %s", __func__, ssh_err(r));
322 if ((r = sshbuf_put_stringb(e->output, msg)) != 0)
323 fatal("%s: buffer error: %s", __func__, ssh_err(r));
331 process_remove_identity(SocketEntry *e)
334 struct sshkey *key = NULL;
337 if ((r = sshkey_froms(e->request, &key)) != 0) {
338 error("%s: get key: %s", __func__, ssh_err(r));
341 if ((id = lookup_identity(key)) == NULL) {
342 debug("%s: key not found", __func__);
345 /* We have this key, free it. */
346 if (idtab->nentries < 1)
347 fatal("%s: internal error: nentries %d",
348 __func__, idtab->nentries);
349 TAILQ_REMOVE(&idtab->idlist, id, next);
355 send_status(e, success);
359 process_remove_all_identities(SocketEntry *e)
363 /* Loop over all identities and clear the keys. */
364 for (id = TAILQ_FIRST(&idtab->idlist); id;
365 id = TAILQ_FIRST(&idtab->idlist)) {
366 TAILQ_REMOVE(&idtab->idlist, id, next);
370 /* Mark that there are no identities. */
377 /* removes expired keys and returns number of seconds until the next expiry */
381 time_t deadline = 0, now = monotime();
384 for (id = TAILQ_FIRST(&idtab->idlist); id; id = nxt) {
385 nxt = TAILQ_NEXT(id, next);
388 if (now >= id->death) {
389 debug("expiring key '%s'", id->comment);
390 TAILQ_REMOVE(&idtab->idlist, id, next);
394 deadline = (deadline == 0) ? id->death :
395 MINIMUM(deadline, id->death);
397 if (deadline == 0 || deadline <= now)
400 return (deadline - now);
404 process_add_identity(SocketEntry *e)
407 int success = 0, confirm = 0;
408 u_int seconds, maxsign;
409 char *comment = NULL;
411 struct sshkey *k = NULL;
413 int r = SSH_ERR_INTERNAL_ERROR;
415 if ((r = sshkey_private_deserialize(e->request, &k)) != 0 ||
417 (r = sshbuf_get_cstring(e->request, &comment, NULL)) != 0) {
418 error("%s: decode private key: %s", __func__, ssh_err(r));
422 while (sshbuf_len(e->request)) {
423 if ((r = sshbuf_get_u8(e->request, &ctype)) != 0) {
424 error("%s: buffer error: %s", __func__, ssh_err(r));
428 case SSH_AGENT_CONSTRAIN_LIFETIME:
429 if ((r = sshbuf_get_u32(e->request, &seconds)) != 0) {
430 error("%s: bad lifetime constraint: %s",
431 __func__, ssh_err(r));
434 death = monotime() + seconds;
436 case SSH_AGENT_CONSTRAIN_CONFIRM:
439 case SSH_AGENT_CONSTRAIN_MAXSIGN:
440 if ((r = sshbuf_get_u32(e->request, &maxsign)) != 0) {
441 error("%s: bad maxsign constraint: %s",
442 __func__, ssh_err(r));
445 if ((r = sshkey_enable_maxsign(k, maxsign)) != 0) {
446 error("%s: cannot enable maxsign: %s",
447 __func__, ssh_err(r));
452 error("%s: Unknown constraint %d", __func__, ctype);
454 sshbuf_reset(e->request);
462 if (lifetime && !death)
463 death = monotime() + lifetime;
464 if ((id = lookup_identity(k)) == NULL) {
465 id = xcalloc(1, sizeof(Identity));
466 TAILQ_INSERT_TAIL(&idtab->idlist, id, next);
467 /* Increment the number of identities. */
470 /* key state might have been updated */
471 sshkey_free(id->key);
475 id->comment = comment;
477 id->confirm = confirm;
479 send_status(e, success);
482 /* XXX todo: encrypt sensitive data with passphrase */
484 process_lock_agent(SocketEntry *e, int lock)
486 int r, success = 0, delay;
488 u_char passwdhash[LOCK_SIZE];
489 static u_int fail_count = 0;
493 * This is deliberately fatal: the user has requested that we lock,
494 * but we can't parse their request properly. The only safe thing to
497 if ((r = sshbuf_get_cstring(e->request, &passwd, &pwlen)) != 0)
498 fatal("%s: buffer error: %s", __func__, ssh_err(r));
500 debug("empty password not supported");
501 } else if (locked && !lock) {
502 if (bcrypt_pbkdf(passwd, pwlen, lock_salt, sizeof(lock_salt),
503 passwdhash, sizeof(passwdhash), LOCK_ROUNDS) < 0)
504 fatal("bcrypt_pbkdf");
505 if (timingsafe_bcmp(passwdhash, lock_pwhash, LOCK_SIZE) == 0) {
506 debug("agent unlocked");
509 explicit_bzero(lock_pwhash, sizeof(lock_pwhash));
512 /* delay in 0.1s increments up to 10s */
513 if (fail_count < 100)
515 delay = 100000 * fail_count;
516 debug("unlock failed, delaying %0.1lf seconds",
517 (double)delay/1000000);
520 explicit_bzero(passwdhash, sizeof(passwdhash));
521 } else if (!locked && lock) {
522 debug("agent locked");
524 arc4random_buf(lock_salt, sizeof(lock_salt));
525 if (bcrypt_pbkdf(passwd, pwlen, lock_salt, sizeof(lock_salt),
526 lock_pwhash, sizeof(lock_pwhash), LOCK_ROUNDS) < 0)
527 fatal("bcrypt_pbkdf");
530 explicit_bzero(passwd, pwlen);
532 send_status(e, success);
536 no_identities(SocketEntry *e)
541 if ((msg = sshbuf_new()) == NULL)
542 fatal("%s: sshbuf_new failed", __func__);
543 if ((r = sshbuf_put_u8(msg, SSH2_AGENT_IDENTITIES_ANSWER)) != 0 ||
544 (r = sshbuf_put_u32(msg, 0)) != 0 ||
545 (r = sshbuf_put_stringb(e->output, msg)) != 0)
546 fatal("%s: buffer error: %s", __func__, ssh_err(r));
552 process_add_smartcard_key(SocketEntry *e)
554 char *provider = NULL, *pin = NULL, canonical_provider[PATH_MAX];
555 int r, i, count = 0, success = 0, confirm = 0;
559 struct sshkey **keys = NULL, *k;
562 if ((r = sshbuf_get_cstring(e->request, &provider, NULL)) != 0 ||
563 (r = sshbuf_get_cstring(e->request, &pin, NULL)) != 0) {
564 error("%s: buffer error: %s", __func__, ssh_err(r));
568 while (sshbuf_len(e->request)) {
569 if ((r = sshbuf_get_u8(e->request, &type)) != 0) {
570 error("%s: buffer error: %s", __func__, ssh_err(r));
574 case SSH_AGENT_CONSTRAIN_LIFETIME:
575 if ((r = sshbuf_get_u32(e->request, &seconds)) != 0) {
576 error("%s: buffer error: %s",
577 __func__, ssh_err(r));
580 death = monotime() + seconds;
582 case SSH_AGENT_CONSTRAIN_CONFIRM:
586 error("%s: Unknown constraint type %d", __func__, type);
590 if (realpath(provider, canonical_provider) == NULL) {
591 verbose("failed PKCS#11 add of \"%.100s\": realpath: %s",
592 provider, strerror(errno));
595 if (match_pattern_list(canonical_provider, pkcs11_whitelist, 0) != 1) {
596 verbose("refusing PKCS#11 add of \"%.100s\": "
597 "provider not whitelisted", canonical_provider);
600 debug("%s: add %.100s", __func__, canonical_provider);
601 if (lifetime && !death)
602 death = monotime() + lifetime;
604 count = pkcs11_add_provider(canonical_provider, pin, &keys);
605 for (i = 0; i < count; i++) {
607 if (lookup_identity(k) == NULL) {
608 id = xcalloc(1, sizeof(Identity));
610 id->provider = xstrdup(canonical_provider);
611 id->comment = xstrdup(canonical_provider); /* XXX */
613 id->confirm = confirm;
614 TAILQ_INSERT_TAIL(&idtab->idlist, id, next);
626 send_status(e, success);
630 process_remove_smartcard_key(SocketEntry *e)
632 char *provider = NULL, *pin = NULL, canonical_provider[PATH_MAX];
636 if ((r = sshbuf_get_cstring(e->request, &provider, NULL)) != 0 ||
637 (r = sshbuf_get_cstring(e->request, &pin, NULL)) != 0) {
638 error("%s: buffer error: %s", __func__, ssh_err(r));
643 if (realpath(provider, canonical_provider) == NULL) {
644 verbose("failed PKCS#11 add of \"%.100s\": realpath: %s",
645 provider, strerror(errno));
649 debug("%s: remove %.100s", __func__, canonical_provider);
650 for (id = TAILQ_FIRST(&idtab->idlist); id; id = nxt) {
651 nxt = TAILQ_NEXT(id, next);
652 /* Skip file--based keys */
653 if (id->provider == NULL)
655 if (!strcmp(canonical_provider, id->provider)) {
656 TAILQ_REMOVE(&idtab->idlist, id, next);
661 if (pkcs11_del_provider(canonical_provider) == 0)
664 error("%s: pkcs11_del_provider failed", __func__);
667 send_status(e, success);
669 #endif /* ENABLE_PKCS11 */
671 /* dispatch incoming messages */
674 process_message(u_int socknum)
682 if (socknum >= sockets_alloc) {
683 fatal("%s: socket number %u >= allocated %u",
684 __func__, socknum, sockets_alloc);
686 e = &sockets[socknum];
688 if (sshbuf_len(e->input) < 5)
689 return 0; /* Incomplete message header. */
690 cp = sshbuf_ptr(e->input);
691 msg_len = PEEK_U32(cp);
692 if (msg_len > AGENT_MAX_LEN) {
693 debug("%s: socket %u (fd=%d) message too long %u > %u",
694 __func__, socknum, e->fd, msg_len, AGENT_MAX_LEN);
697 if (sshbuf_len(e->input) < msg_len + 4)
698 return 0; /* Incomplete message body. */
700 /* move the current input to e->request */
701 sshbuf_reset(e->request);
702 if ((r = sshbuf_get_stringb(e->input, e->request)) != 0 ||
703 (r = sshbuf_get_u8(e->request, &type)) != 0) {
704 if (r == SSH_ERR_MESSAGE_INCOMPLETE ||
705 r == SSH_ERR_STRING_TOO_LARGE) {
706 debug("%s: buffer error: %s", __func__, ssh_err(r));
709 fatal("%s: buffer error: %s", __func__, ssh_err(r));
712 debug("%s: socket %u (fd=%d) type %d", __func__, socknum, e->fd, type);
714 /* check whether agent is locked */
715 if (locked && type != SSH_AGENTC_UNLOCK) {
716 sshbuf_reset(e->request);
718 case SSH2_AGENTC_REQUEST_IDENTITIES:
719 /* send empty lists */
723 /* send a fail message for all other request types */
730 case SSH_AGENTC_LOCK:
731 case SSH_AGENTC_UNLOCK:
732 process_lock_agent(e, type == SSH_AGENTC_LOCK);
734 case SSH_AGENTC_REMOVE_ALL_RSA_IDENTITIES:
735 process_remove_all_identities(e); /* safe for !WITH_SSH1 */
738 case SSH2_AGENTC_SIGN_REQUEST:
739 process_sign_request2(e);
741 case SSH2_AGENTC_REQUEST_IDENTITIES:
742 process_request_identities(e);
744 case SSH2_AGENTC_ADD_IDENTITY:
745 case SSH2_AGENTC_ADD_ID_CONSTRAINED:
746 process_add_identity(e);
748 case SSH2_AGENTC_REMOVE_IDENTITY:
749 process_remove_identity(e);
751 case SSH2_AGENTC_REMOVE_ALL_IDENTITIES:
752 process_remove_all_identities(e);
755 case SSH_AGENTC_ADD_SMARTCARD_KEY:
756 case SSH_AGENTC_ADD_SMARTCARD_KEY_CONSTRAINED:
757 process_add_smartcard_key(e);
759 case SSH_AGENTC_REMOVE_SMARTCARD_KEY:
760 process_remove_smartcard_key(e);
762 #endif /* ENABLE_PKCS11 */
764 /* Unknown message. Respond with failure. */
765 error("Unknown message %d", type);
766 sshbuf_reset(e->request);
774 new_socket(sock_type type, int fd)
776 u_int i, old_alloc, new_alloc;
783 for (i = 0; i < sockets_alloc; i++)
784 if (sockets[i].type == AUTH_UNUSED) {
786 if ((sockets[i].input = sshbuf_new()) == NULL)
787 fatal("%s: sshbuf_new failed", __func__);
788 if ((sockets[i].output = sshbuf_new()) == NULL)
789 fatal("%s: sshbuf_new failed", __func__);
790 if ((sockets[i].request = sshbuf_new()) == NULL)
791 fatal("%s: sshbuf_new failed", __func__);
792 sockets[i].type = type;
795 old_alloc = sockets_alloc;
796 new_alloc = sockets_alloc + 10;
797 sockets = xreallocarray(sockets, new_alloc, sizeof(sockets[0]));
798 for (i = old_alloc; i < new_alloc; i++)
799 sockets[i].type = AUTH_UNUSED;
800 sockets_alloc = new_alloc;
801 sockets[old_alloc].fd = fd;
802 if ((sockets[old_alloc].input = sshbuf_new()) == NULL)
803 fatal("%s: sshbuf_new failed", __func__);
804 if ((sockets[old_alloc].output = sshbuf_new()) == NULL)
805 fatal("%s: sshbuf_new failed", __func__);
806 if ((sockets[old_alloc].request = sshbuf_new()) == NULL)
807 fatal("%s: sshbuf_new failed", __func__);
808 sockets[old_alloc].type = type;
812 handle_socket_read(u_int socknum)
814 struct sockaddr_un sunaddr;
820 slen = sizeof(sunaddr);
821 fd = accept(sockets[socknum].fd, (struct sockaddr *)&sunaddr, &slen);
823 error("accept from AUTH_SOCKET: %s", strerror(errno));
826 if (getpeereid(fd, &euid, &egid) < 0) {
827 error("getpeereid %d failed: %s", fd, strerror(errno));
831 if ((euid != 0) && (getuid() != euid)) {
832 error("uid mismatch: peer euid %u != uid %u",
833 (u_int) euid, (u_int) getuid());
837 new_socket(AUTH_CONNECTION, fd);
842 handle_conn_read(u_int socknum)
844 char buf[AGENT_RBUF_LEN];
848 if ((len = read(sockets[socknum].fd, buf, sizeof(buf))) <= 0) {
850 if (errno == EAGAIN || errno == EINTR)
852 error("%s: read error on socket %u (fd %d): %s",
853 __func__, socknum, sockets[socknum].fd,
858 if ((r = sshbuf_put(sockets[socknum].input, buf, len)) != 0)
859 fatal("%s: buffer error: %s", __func__, ssh_err(r));
860 explicit_bzero(buf, sizeof(buf));
861 process_message(socknum);
866 handle_conn_write(u_int socknum)
871 if (sshbuf_len(sockets[socknum].output) == 0)
872 return 0; /* shouldn't happen */
873 if ((len = write(sockets[socknum].fd,
874 sshbuf_ptr(sockets[socknum].output),
875 sshbuf_len(sockets[socknum].output))) <= 0) {
877 if (errno == EAGAIN || errno == EINTR)
879 error("%s: read error on socket %u (fd %d): %s",
880 __func__, socknum, sockets[socknum].fd,
885 if ((r = sshbuf_consume(sockets[socknum].output, len)) != 0)
886 fatal("%s: buffer error: %s", __func__, ssh_err(r));
891 after_poll(struct pollfd *pfd, size_t npfd, u_int maxfds)
894 u_int socknum, activefds = npfd;
896 for (i = 0; i < npfd; i++) {
897 if (pfd[i].revents == 0)
899 /* Find sockets entry */
900 for (socknum = 0; socknum < sockets_alloc; socknum++) {
901 if (sockets[socknum].type != AUTH_SOCKET &&
902 sockets[socknum].type != AUTH_CONNECTION)
904 if (pfd[i].fd == sockets[socknum].fd)
907 if (socknum >= sockets_alloc) {
908 error("%s: no socket for fd %d", __func__, pfd[i].fd);
912 switch (sockets[socknum].type) {
914 if ((pfd[i].revents & (POLLIN|POLLERR)) == 0)
917 debug3("out of fds (active %u >= limit %u); "
918 "skipping accept", activefds, maxfds);
921 if (handle_socket_read(socknum) == 0)
924 case AUTH_CONNECTION:
925 if ((pfd[i].revents & (POLLIN|POLLERR)) != 0 &&
926 handle_conn_read(socknum) != 0) {
929 if ((pfd[i].revents & (POLLOUT|POLLHUP)) != 0 &&
930 handle_conn_write(socknum) != 0) {
933 fatal("activefds == 0 at close_sock");
934 close_socket(&sockets[socknum]);
946 prepare_poll(struct pollfd **pfdp, size_t *npfdp, int *timeoutp, u_int maxfds)
948 struct pollfd *pfd = *pfdp;
949 size_t i, j, npfd = 0;
953 /* Count active sockets */
954 for (i = 0; i < sockets_alloc; i++) {
955 switch (sockets[i].type) {
957 case AUTH_CONNECTION:
963 fatal("Unknown socket type %d", sockets[i].type);
967 if (npfd != *npfdp &&
968 (pfd = recallocarray(pfd, *npfdp, npfd, sizeof(*pfd))) == NULL)
969 fatal("%s: recallocarray failed", __func__);
973 for (i = j = 0; i < sockets_alloc; i++) {
974 switch (sockets[i].type) {
977 debug3("out of fds (active %zu >= limit %u); "
978 "skipping arming listener", npfd, maxfds);
981 pfd[j].fd = sockets[i].fd;
983 pfd[j].events = POLLIN;
986 case AUTH_CONNECTION:
987 pfd[j].fd = sockets[i].fd;
990 * Only prepare to read if we can handle a full-size
991 * input read buffer and enqueue a max size reply..
993 if ((r = sshbuf_check_reserve(sockets[i].input,
994 AGENT_RBUF_LEN)) == 0 &&
995 (r = sshbuf_check_reserve(sockets[i].output,
996 AGENT_MAX_LEN)) == 0)
997 pfd[j].events = POLLIN;
998 else if (r != SSH_ERR_NO_BUFFER_SPACE) {
999 fatal("%s: buffer error: %s",
1000 __func__, ssh_err(r));
1002 if (sshbuf_len(sockets[i].output) > 0)
1003 pfd[j].events |= POLLOUT;
1010 deadline = reaper();
1011 if (parent_alive_interval != 0)
1012 deadline = (deadline == 0) ? parent_alive_interval :
1013 MINIMUM(deadline, parent_alive_interval);
1014 if (deadline == 0) {
1015 *timeoutp = -1; /* INFTIM */
1017 if (deadline > INT_MAX / 1000)
1018 *timeoutp = INT_MAX / 1000;
1020 *timeoutp = deadline * 1000;
1026 cleanup_socket(void)
1028 if (cleanup_pid != 0 && getpid() != cleanup_pid)
1030 debug("%s: cleanup", __func__);
1032 unlink(socket_name);
1046 cleanup_handler(int sig)
1049 #ifdef ENABLE_PKCS11
1056 check_parent_exists(void)
1059 * If our parent has exited then getppid() will return (pid_t)1,
1060 * so testing for that should be safe.
1062 if (parent_pid != -1 && getppid() != parent_pid) {
1063 /* printf("Parent has died - Authentication agent exiting.\n"); */
1073 "usage: ssh-agent [-c | -s] [-Dd] [-a bind_address] [-E fingerprint_hash]\n"
1074 " [-P pkcs11_whitelist] [-t life] [command [arg ...]]\n"
1075 " ssh-agent [-c | -s] -k\n");
1080 main(int ac, char **av)
1082 int c_flag = 0, d_flag = 0, D_flag = 0, k_flag = 0, s_flag = 0;
1083 int sock, fd, ch, result, saved_errno;
1084 char *shell, *format, *pidstr, *agentsocket = NULL;
1085 #ifdef HAVE_SETRLIMIT
1089 extern char *optarg;
1091 char pidstrbuf[1 + 3 * sizeof pid];
1094 int timeout = -1; /* INFTIM */
1095 struct pollfd *pfd = NULL;
1099 ssh_malloc_init(); /* must be called before any mallocs */
1100 /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
1107 platform_disable_tracing(0); /* strict=no */
1109 if (getrlimit(RLIMIT_NOFILE, &rlim) == -1)
1110 fatal("%s: getrlimit: %s", __progname, strerror(errno));
1112 __progname = ssh_get_progname(av[0]);
1115 while ((ch = getopt(ac, av, "cDdksE:a:P:t:")) != -1) {
1118 fingerprint_hash = ssh_digest_alg_by_name(optarg);
1119 if (fingerprint_hash == -1)
1120 fatal("Invalid hash algorithm \"%s\"", optarg);
1131 if (pkcs11_whitelist != NULL)
1132 fatal("-P option already specified");
1133 pkcs11_whitelist = xstrdup(optarg);
1141 if (d_flag || D_flag)
1146 if (d_flag || D_flag)
1151 agentsocket = optarg;
1154 if ((lifetime = convtime(optarg)) == -1) {
1155 fprintf(stderr, "Invalid lifetime\n");
1166 if (ac > 0 && (c_flag || k_flag || s_flag || d_flag || D_flag))
1169 if (pkcs11_whitelist == NULL)
1170 pkcs11_whitelist = xstrdup(DEFAULT_PKCS11_WHITELIST);
1172 if (ac == 0 && !c_flag && !s_flag) {
1173 shell = getenv("SHELL");
1174 if (shell != NULL && (len = strlen(shell)) > 2 &&
1175 strncmp(shell + len - 3, "csh", 3) == 0)
1179 const char *errstr = NULL;
1181 pidstr = getenv(SSH_AGENTPID_ENV_NAME);
1182 if (pidstr == NULL) {
1183 fprintf(stderr, "%s not set, cannot kill agent\n",
1184 SSH_AGENTPID_ENV_NAME);
1187 pid = (int)strtonum(pidstr, 2, INT_MAX, &errstr);
1190 "%s=\"%s\", which is not a good PID: %s\n",
1191 SSH_AGENTPID_ENV_NAME, pidstr, errstr);
1194 if (kill(pid, SIGTERM) == -1) {
1198 format = c_flag ? "unsetenv %s;\n" : "unset %s;\n";
1199 printf(format, SSH_AUTHSOCKET_ENV_NAME);
1200 printf(format, SSH_AGENTPID_ENV_NAME);
1201 printf("echo Agent pid %ld killed;\n", (long)pid);
1206 * Minimum file descriptors:
1207 * stdio (3) + listener (1) + syslog (1 maybe) + connection (1) +
1208 * a few spare for libc / stack protectors / sanitisers, etc.
1210 #define SSH_AGENT_MIN_FDS (3+1+1+1+4)
1211 if (rlim.rlim_cur < SSH_AGENT_MIN_FDS)
1212 fatal("%s: file descriptor rlimit %lld too low (minimum %u)",
1213 __progname, (long long)rlim.rlim_cur, SSH_AGENT_MIN_FDS);
1214 maxfds = rlim.rlim_cur - SSH_AGENT_MIN_FDS;
1216 parent_pid = getpid();
1218 if (agentsocket == NULL) {
1219 /* Create private directory for agent socket */
1220 mktemp_proto(socket_dir, sizeof(socket_dir));
1221 if (mkdtemp(socket_dir) == NULL) {
1222 perror("mkdtemp: private socket dir");
1225 snprintf(socket_name, sizeof socket_name, "%s/agent.%ld", socket_dir,
1228 /* Try to use specified agent socket */
1229 socket_dir[0] = '\0';
1230 strlcpy(socket_name, agentsocket, sizeof socket_name);
1234 * Create socket early so it will exist before command gets run from
1237 prev_mask = umask(0177);
1238 sock = unix_listener(socket_name, SSH_LISTEN_BACKLOG, 0);
1240 /* XXX - unix_listener() calls error() not perror() */
1241 *socket_name = '\0'; /* Don't unlink any existing file */
1247 * Fork, and have the parent execute the command, if any, or present
1248 * the socket data. The child continues as the authentication agent.
1250 if (D_flag || d_flag) {
1251 log_init(__progname,
1252 d_flag ? SYSLOG_LEVEL_DEBUG3 : SYSLOG_LEVEL_INFO,
1253 SYSLOG_FACILITY_AUTH, 1);
1254 format = c_flag ? "setenv %s %s;\n" : "%s=%s; export %s;\n";
1255 printf(format, SSH_AUTHSOCKET_ENV_NAME, socket_name,
1256 SSH_AUTHSOCKET_ENV_NAME);
1257 printf("echo Agent pid %ld;\n", (long)parent_pid);
1266 if (pid != 0) { /* Parent - execute the given command. */
1268 snprintf(pidstrbuf, sizeof pidstrbuf, "%ld", (long)pid);
1270 format = c_flag ? "setenv %s %s;\n" : "%s=%s; export %s;\n";
1271 printf(format, SSH_AUTHSOCKET_ENV_NAME, socket_name,
1272 SSH_AUTHSOCKET_ENV_NAME);
1273 printf(format, SSH_AGENTPID_ENV_NAME, pidstrbuf,
1274 SSH_AGENTPID_ENV_NAME);
1275 printf("echo Agent pid %ld;\n", (long)pid);
1278 if (setenv(SSH_AUTHSOCKET_ENV_NAME, socket_name, 1) == -1 ||
1279 setenv(SSH_AGENTPID_ENV_NAME, pidstrbuf, 1) == -1) {
1288 log_init(__progname, SYSLOG_LEVEL_INFO, SYSLOG_FACILITY_AUTH, 0);
1290 if (setsid() == -1) {
1291 error("setsid: %s", strerror(errno));
1296 if ((fd = open(_PATH_DEVNULL, O_RDWR, 0)) != -1) {
1297 /* XXX might close listen socket */
1298 (void)dup2(fd, STDIN_FILENO);
1299 (void)dup2(fd, STDOUT_FILENO);
1300 (void)dup2(fd, STDERR_FILENO);
1305 #ifdef HAVE_SETRLIMIT
1306 /* deny core dumps, since memory contains unencrypted private keys */
1307 rlim.rlim_cur = rlim.rlim_max = 0;
1308 if (setrlimit(RLIMIT_CORE, &rlim) < 0) {
1309 error("setrlimit RLIMIT_CORE: %s", strerror(errno));
1316 cleanup_pid = getpid();
1318 #ifdef ENABLE_PKCS11
1321 new_socket(AUTH_SOCKET, sock);
1323 parent_alive_interval = 10;
1325 signal(SIGPIPE, SIG_IGN);
1326 signal(SIGINT, (d_flag | D_flag) ? cleanup_handler : SIG_IGN);
1327 signal(SIGHUP, cleanup_handler);
1328 signal(SIGTERM, cleanup_handler);
1330 if (pledge("stdio rpath cpath unix id proc exec", NULL) == -1)
1331 fatal("%s: pledge: %s", __progname, strerror(errno));
1332 platform_pledge_agent();
1335 prepare_poll(&pfd, &npfd, &timeout, maxfds);
1336 result = poll(pfd, npfd, timeout);
1337 saved_errno = errno;
1338 if (parent_alive_interval != 0)
1339 check_parent_exists();
1340 (void) reaper(); /* remove expired keys */
1342 if (saved_errno == EINTR)
1344 fatal("poll: %s", strerror(saved_errno));
1345 } else if (result > 0)
1346 after_poll(pfd, npfd, maxfds);