1 /* $OpenBSD: ssh-agent.c,v 1.231 2018/05/11 03:38:51 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)
109 struct sshbuf *input;
110 struct sshbuf *output;
111 struct sshbuf *request;
114 u_int sockets_alloc = 0;
115 SocketEntry *sockets = NULL;
117 typedef struct identity {
118 TAILQ_ENTRY(identity) next;
128 TAILQ_HEAD(idqueue, identity) idlist;
131 /* private key table */
132 struct idtable *idtab;
136 /* pid of shell == parent of agent */
137 pid_t parent_pid = -1;
138 time_t parent_alive_interval = 0;
140 /* pid of process for which cleanup_socket is applicable */
141 pid_t cleanup_pid = 0;
143 /* pathname and directory for AUTH_SOCKET */
144 char socket_name[PATH_MAX];
145 char socket_dir[PATH_MAX];
147 /* PKCS#11 path whitelist */
148 static char *pkcs11_whitelist;
152 #define LOCK_SALT_SIZE 16
153 #define LOCK_ROUNDS 1
155 u_char lock_pwhash[LOCK_SIZE];
156 u_char lock_salt[LOCK_SALT_SIZE];
158 extern char *__progname;
160 /* Default lifetime in seconds (0 == forever) */
161 static long lifetime = 0;
163 static int fingerprint_hash = SSH_FP_HASH_DEFAULT;
166 close_socket(SocketEntry *e)
170 e->type = AUTH_UNUSED;
171 sshbuf_free(e->input);
172 sshbuf_free(e->output);
173 sshbuf_free(e->request);
179 idtab = xcalloc(1, sizeof(*idtab));
180 TAILQ_INIT(&idtab->idlist);
185 free_identity(Identity *id)
187 sshkey_free(id->key);
193 /* return matching private key for given public key */
195 lookup_identity(struct sshkey *key)
199 TAILQ_FOREACH(id, &idtab->idlist, next) {
200 if (sshkey_equal(key, id->key))
206 /* Check confirmation of keysign request */
208 confirm_key(Identity *id)
213 p = sshkey_fingerprint(id->key, fingerprint_hash, SSH_FP_DEFAULT);
215 ask_permission("Allow use of key %s?\nKey fingerprint %s.",
224 send_status(SocketEntry *e, int success)
228 if ((r = sshbuf_put_u32(e->output, 1)) != 0 ||
229 (r = sshbuf_put_u8(e->output, success ?
230 SSH_AGENT_SUCCESS : SSH_AGENT_FAILURE)) != 0)
231 fatal("%s: buffer error: %s", __func__, ssh_err(r));
234 /* send list of supported public keys to 'client' */
236 process_request_identities(SocketEntry *e)
242 if ((msg = sshbuf_new()) == NULL)
243 fatal("%s: sshbuf_new failed", __func__);
244 if ((r = sshbuf_put_u8(msg, SSH2_AGENT_IDENTITIES_ANSWER)) != 0 ||
245 (r = sshbuf_put_u32(msg, idtab->nentries)) != 0)
246 fatal("%s: buffer error: %s", __func__, ssh_err(r));
247 TAILQ_FOREACH(id, &idtab->idlist, next) {
248 if ((r = sshkey_puts_opts(id->key, msg, SSHKEY_SERIALIZE_INFO))
250 (r = sshbuf_put_cstring(msg, id->comment)) != 0) {
251 error("%s: put key/comment: %s", __func__,
256 if ((r = sshbuf_put_stringb(e->output, msg)) != 0)
257 fatal("%s: buffer error: %s", __func__, ssh_err(r));
263 agent_decode_alg(struct sshkey *key, u_int flags)
265 if (key->type == KEY_RSA) {
266 if (flags & SSH_AGENT_RSA_SHA2_256)
267 return "rsa-sha2-256";
268 else if (flags & SSH_AGENT_RSA_SHA2_512)
269 return "rsa-sha2-512";
276 process_sign_request2(SocketEntry *e)
279 u_char *signature = NULL;
280 size_t dlen, slen = 0;
281 u_int compat = 0, flags;
284 struct sshkey *key = NULL;
287 if ((msg = sshbuf_new()) == NULL)
288 fatal("%s: sshbuf_new failed", __func__);
289 if ((r = sshkey_froms(e->request, &key)) != 0 ||
290 (r = sshbuf_get_string_direct(e->request, &data, &dlen)) != 0 ||
291 (r = sshbuf_get_u32(e->request, &flags)) != 0) {
292 error("%s: couldn't parse request: %s", __func__, ssh_err(r));
296 if ((id = lookup_identity(key)) == NULL) {
297 verbose("%s: %s key not found", __func__, sshkey_type(key));
300 if (id->confirm && confirm_key(id) != 0) {
301 verbose("%s: user refused key", __func__);
304 if ((r = sshkey_sign(id->key, &signature, &slen,
305 data, dlen, agent_decode_alg(key, flags), compat)) != 0) {
306 error("%s: sshkey_sign: %s", __func__, ssh_err(r));
314 if ((r = sshbuf_put_u8(msg, SSH2_AGENT_SIGN_RESPONSE)) != 0 ||
315 (r = sshbuf_put_string(msg, signature, slen)) != 0)
316 fatal("%s: buffer error: %s", __func__, ssh_err(r));
317 } else if ((r = sshbuf_put_u8(msg, SSH_AGENT_FAILURE)) != 0)
318 fatal("%s: buffer error: %s", __func__, ssh_err(r));
320 if ((r = sshbuf_put_stringb(e->output, msg)) != 0)
321 fatal("%s: buffer error: %s", __func__, ssh_err(r));
329 process_remove_identity(SocketEntry *e)
332 struct sshkey *key = NULL;
335 if ((r = sshkey_froms(e->request, &key)) != 0) {
336 error("%s: get key: %s", __func__, ssh_err(r));
339 if ((id = lookup_identity(key)) == NULL) {
340 debug("%s: key not found", __func__);
343 /* We have this key, free it. */
344 if (idtab->nentries < 1)
345 fatal("%s: internal error: nentries %d",
346 __func__, idtab->nentries);
347 TAILQ_REMOVE(&idtab->idlist, id, next);
353 send_status(e, success);
357 process_remove_all_identities(SocketEntry *e)
361 /* Loop over all identities and clear the keys. */
362 for (id = TAILQ_FIRST(&idtab->idlist); id;
363 id = TAILQ_FIRST(&idtab->idlist)) {
364 TAILQ_REMOVE(&idtab->idlist, id, next);
368 /* Mark that there are no identities. */
375 /* removes expired keys and returns number of seconds until the next expiry */
379 time_t deadline = 0, now = monotime();
382 for (id = TAILQ_FIRST(&idtab->idlist); id; id = nxt) {
383 nxt = TAILQ_NEXT(id, next);
386 if (now >= id->death) {
387 debug("expiring key '%s'", id->comment);
388 TAILQ_REMOVE(&idtab->idlist, id, next);
392 deadline = (deadline == 0) ? id->death :
393 MINIMUM(deadline, id->death);
395 if (deadline == 0 || deadline <= now)
398 return (deadline - now);
402 process_add_identity(SocketEntry *e)
405 int success = 0, confirm = 0;
406 u_int seconds, maxsign;
407 char *comment = NULL;
409 struct sshkey *k = NULL;
411 int r = SSH_ERR_INTERNAL_ERROR;
413 if ((r = sshkey_private_deserialize(e->request, &k)) != 0 ||
415 (r = sshbuf_get_cstring(e->request, &comment, NULL)) != 0) {
416 error("%s: decode private key: %s", __func__, ssh_err(r));
420 while (sshbuf_len(e->request)) {
421 if ((r = sshbuf_get_u8(e->request, &ctype)) != 0) {
422 error("%s: buffer error: %s", __func__, ssh_err(r));
426 case SSH_AGENT_CONSTRAIN_LIFETIME:
427 if ((r = sshbuf_get_u32(e->request, &seconds)) != 0) {
428 error("%s: bad lifetime constraint: %s",
429 __func__, ssh_err(r));
432 death = monotime() + seconds;
434 case SSH_AGENT_CONSTRAIN_CONFIRM:
437 case SSH_AGENT_CONSTRAIN_MAXSIGN:
438 if ((r = sshbuf_get_u32(e->request, &maxsign)) != 0) {
439 error("%s: bad maxsign constraint: %s",
440 __func__, ssh_err(r));
443 if ((r = sshkey_enable_maxsign(k, maxsign)) != 0) {
444 error("%s: cannot enable maxsign: %s",
445 __func__, ssh_err(r));
450 error("%s: Unknown constraint %d", __func__, ctype);
452 sshbuf_reset(e->request);
460 if (lifetime && !death)
461 death = monotime() + lifetime;
462 if ((id = lookup_identity(k)) == NULL) {
463 id = xcalloc(1, sizeof(Identity));
464 TAILQ_INSERT_TAIL(&idtab->idlist, id, next);
465 /* Increment the number of identities. */
468 /* key state might have been updated */
469 sshkey_free(id->key);
473 id->comment = comment;
475 id->confirm = confirm;
477 send_status(e, success);
480 /* XXX todo: encrypt sensitive data with passphrase */
482 process_lock_agent(SocketEntry *e, int lock)
484 int r, success = 0, delay;
486 u_char passwdhash[LOCK_SIZE];
487 static u_int fail_count = 0;
491 * This is deliberately fatal: the user has requested that we lock,
492 * but we can't parse their request properly. The only safe thing to
495 if ((r = sshbuf_get_cstring(e->request, &passwd, &pwlen)) != 0)
496 fatal("%s: buffer error: %s", __func__, ssh_err(r));
498 debug("empty password not supported");
499 } else if (locked && !lock) {
500 if (bcrypt_pbkdf(passwd, pwlen, lock_salt, sizeof(lock_salt),
501 passwdhash, sizeof(passwdhash), LOCK_ROUNDS) < 0)
502 fatal("bcrypt_pbkdf");
503 if (timingsafe_bcmp(passwdhash, lock_pwhash, LOCK_SIZE) == 0) {
504 debug("agent unlocked");
507 explicit_bzero(lock_pwhash, sizeof(lock_pwhash));
510 /* delay in 0.1s increments up to 10s */
511 if (fail_count < 100)
513 delay = 100000 * fail_count;
514 debug("unlock failed, delaying %0.1lf seconds",
515 (double)delay/1000000);
518 explicit_bzero(passwdhash, sizeof(passwdhash));
519 } else if (!locked && lock) {
520 debug("agent locked");
522 arc4random_buf(lock_salt, sizeof(lock_salt));
523 if (bcrypt_pbkdf(passwd, pwlen, lock_salt, sizeof(lock_salt),
524 lock_pwhash, sizeof(lock_pwhash), LOCK_ROUNDS) < 0)
525 fatal("bcrypt_pbkdf");
528 explicit_bzero(passwd, pwlen);
530 send_status(e, success);
534 no_identities(SocketEntry *e)
539 if ((msg = sshbuf_new()) == NULL)
540 fatal("%s: sshbuf_new failed", __func__);
541 if ((r = sshbuf_put_u8(msg, SSH2_AGENT_IDENTITIES_ANSWER)) != 0 ||
542 (r = sshbuf_put_u32(msg, 0)) != 0 ||
543 (r = sshbuf_put_stringb(e->output, msg)) != 0)
544 fatal("%s: buffer error: %s", __func__, ssh_err(r));
550 process_add_smartcard_key(SocketEntry *e)
552 char *provider = NULL, *pin = NULL, canonical_provider[PATH_MAX];
553 int r, i, count = 0, success = 0, confirm = 0;
557 struct sshkey **keys = NULL, *k;
560 if ((r = sshbuf_get_cstring(e->request, &provider, NULL)) != 0 ||
561 (r = sshbuf_get_cstring(e->request, &pin, NULL)) != 0) {
562 error("%s: buffer error: %s", __func__, ssh_err(r));
566 while (sshbuf_len(e->request)) {
567 if ((r = sshbuf_get_u8(e->request, &type)) != 0) {
568 error("%s: buffer error: %s", __func__, ssh_err(r));
572 case SSH_AGENT_CONSTRAIN_LIFETIME:
573 if ((r = sshbuf_get_u32(e->request, &seconds)) != 0) {
574 error("%s: buffer error: %s",
575 __func__, ssh_err(r));
578 death = monotime() + seconds;
580 case SSH_AGENT_CONSTRAIN_CONFIRM:
584 error("%s: Unknown constraint type %d", __func__, type);
588 if (realpath(provider, canonical_provider) == NULL) {
589 verbose("failed PKCS#11 add of \"%.100s\": realpath: %s",
590 provider, strerror(errno));
593 if (match_pattern_list(canonical_provider, pkcs11_whitelist, 0) != 1) {
594 verbose("refusing PKCS#11 add of \"%.100s\": "
595 "provider not whitelisted", canonical_provider);
598 debug("%s: add %.100s", __func__, canonical_provider);
599 if (lifetime && !death)
600 death = monotime() + lifetime;
602 count = pkcs11_add_provider(canonical_provider, pin, &keys);
603 for (i = 0; i < count; i++) {
605 if (lookup_identity(k) == NULL) {
606 id = xcalloc(1, sizeof(Identity));
608 id->provider = xstrdup(canonical_provider);
609 id->comment = xstrdup(canonical_provider); /* XXX */
611 id->confirm = confirm;
612 TAILQ_INSERT_TAIL(&idtab->idlist, id, next);
624 send_status(e, success);
628 process_remove_smartcard_key(SocketEntry *e)
630 char *provider = NULL, *pin = NULL, canonical_provider[PATH_MAX];
634 if ((r = sshbuf_get_cstring(e->request, &provider, NULL)) != 0 ||
635 (r = sshbuf_get_cstring(e->request, &pin, NULL)) != 0) {
636 error("%s: buffer error: %s", __func__, ssh_err(r));
641 if (realpath(provider, canonical_provider) == NULL) {
642 verbose("failed PKCS#11 add of \"%.100s\": realpath: %s",
643 provider, strerror(errno));
647 debug("%s: remove %.100s", __func__, canonical_provider);
648 for (id = TAILQ_FIRST(&idtab->idlist); id; id = nxt) {
649 nxt = TAILQ_NEXT(id, next);
650 /* Skip file--based keys */
651 if (id->provider == NULL)
653 if (!strcmp(canonical_provider, id->provider)) {
654 TAILQ_REMOVE(&idtab->idlist, id, next);
659 if (pkcs11_del_provider(canonical_provider) == 0)
662 error("%s: pkcs11_del_provider failed", __func__);
665 send_status(e, success);
667 #endif /* ENABLE_PKCS11 */
669 /* dispatch incoming messages */
672 process_message(u_int socknum)
680 if (socknum >= sockets_alloc) {
681 fatal("%s: socket number %u >= allocated %u",
682 __func__, socknum, sockets_alloc);
684 e = &sockets[socknum];
686 if (sshbuf_len(e->input) < 5)
687 return 0; /* Incomplete message header. */
688 cp = sshbuf_ptr(e->input);
689 msg_len = PEEK_U32(cp);
690 if (msg_len > AGENT_MAX_LEN) {
691 debug("%s: socket %u (fd=%d) message too long %u > %u",
692 __func__, socknum, e->fd, msg_len, AGENT_MAX_LEN);
695 if (sshbuf_len(e->input) < msg_len + 4)
696 return 0; /* Incomplete message body. */
698 /* move the current input to e->request */
699 sshbuf_reset(e->request);
700 if ((r = sshbuf_get_stringb(e->input, e->request)) != 0 ||
701 (r = sshbuf_get_u8(e->request, &type)) != 0) {
702 if (r == SSH_ERR_MESSAGE_INCOMPLETE ||
703 r == SSH_ERR_STRING_TOO_LARGE) {
704 debug("%s: buffer error: %s", __func__, ssh_err(r));
707 fatal("%s: buffer error: %s", __func__, ssh_err(r));
710 debug("%s: socket %u (fd=%d) type %d", __func__, socknum, e->fd, type);
712 /* check whether agent is locked */
713 if (locked && type != SSH_AGENTC_UNLOCK) {
714 sshbuf_reset(e->request);
716 case SSH2_AGENTC_REQUEST_IDENTITIES:
717 /* send empty lists */
721 /* send a fail message for all other request types */
728 case SSH_AGENTC_LOCK:
729 case SSH_AGENTC_UNLOCK:
730 process_lock_agent(e, type == SSH_AGENTC_LOCK);
732 case SSH_AGENTC_REMOVE_ALL_RSA_IDENTITIES:
733 process_remove_all_identities(e); /* safe for !WITH_SSH1 */
736 case SSH2_AGENTC_SIGN_REQUEST:
737 process_sign_request2(e);
739 case SSH2_AGENTC_REQUEST_IDENTITIES:
740 process_request_identities(e);
742 case SSH2_AGENTC_ADD_IDENTITY:
743 case SSH2_AGENTC_ADD_ID_CONSTRAINED:
744 process_add_identity(e);
746 case SSH2_AGENTC_REMOVE_IDENTITY:
747 process_remove_identity(e);
749 case SSH2_AGENTC_REMOVE_ALL_IDENTITIES:
750 process_remove_all_identities(e);
753 case SSH_AGENTC_ADD_SMARTCARD_KEY:
754 case SSH_AGENTC_ADD_SMARTCARD_KEY_CONSTRAINED:
755 process_add_smartcard_key(e);
757 case SSH_AGENTC_REMOVE_SMARTCARD_KEY:
758 process_remove_smartcard_key(e);
760 #endif /* ENABLE_PKCS11 */
762 /* Unknown message. Respond with failure. */
763 error("Unknown message %d", type);
764 sshbuf_reset(e->request);
772 new_socket(sock_type type, int fd)
774 u_int i, old_alloc, new_alloc;
781 for (i = 0; i < sockets_alloc; i++)
782 if (sockets[i].type == AUTH_UNUSED) {
784 if ((sockets[i].input = sshbuf_new()) == NULL)
785 fatal("%s: sshbuf_new failed", __func__);
786 if ((sockets[i].output = sshbuf_new()) == NULL)
787 fatal("%s: sshbuf_new failed", __func__);
788 if ((sockets[i].request = sshbuf_new()) == NULL)
789 fatal("%s: sshbuf_new failed", __func__);
790 sockets[i].type = type;
793 old_alloc = sockets_alloc;
794 new_alloc = sockets_alloc + 10;
795 sockets = xreallocarray(sockets, new_alloc, sizeof(sockets[0]));
796 for (i = old_alloc; i < new_alloc; i++)
797 sockets[i].type = AUTH_UNUSED;
798 sockets_alloc = new_alloc;
799 sockets[old_alloc].fd = fd;
800 if ((sockets[old_alloc].input = sshbuf_new()) == NULL)
801 fatal("%s: sshbuf_new failed", __func__);
802 if ((sockets[old_alloc].output = sshbuf_new()) == NULL)
803 fatal("%s: sshbuf_new failed", __func__);
804 if ((sockets[old_alloc].request = sshbuf_new()) == NULL)
805 fatal("%s: sshbuf_new failed", __func__);
806 sockets[old_alloc].type = type;
810 handle_socket_read(u_int socknum)
812 struct sockaddr_un sunaddr;
818 slen = sizeof(sunaddr);
819 fd = accept(sockets[socknum].fd, (struct sockaddr *)&sunaddr, &slen);
821 error("accept from AUTH_SOCKET: %s", strerror(errno));
824 if (getpeereid(fd, &euid, &egid) < 0) {
825 error("getpeereid %d failed: %s", fd, strerror(errno));
829 if ((euid != 0) && (getuid() != euid)) {
830 error("uid mismatch: peer euid %u != uid %u",
831 (u_int) euid, (u_int) getuid());
835 new_socket(AUTH_CONNECTION, fd);
840 handle_conn_read(u_int socknum)
846 if ((len = read(sockets[socknum].fd, buf, sizeof(buf))) <= 0) {
848 if (errno == EAGAIN || errno == EINTR)
850 error("%s: read error on socket %u (fd %d): %s",
851 __func__, socknum, sockets[socknum].fd,
856 if ((r = sshbuf_put(sockets[socknum].input, buf, len)) != 0)
857 fatal("%s: buffer error: %s", __func__, ssh_err(r));
858 explicit_bzero(buf, sizeof(buf));
859 process_message(socknum);
864 handle_conn_write(u_int socknum)
869 if (sshbuf_len(sockets[socknum].output) == 0)
870 return 0; /* shouldn't happen */
871 if ((len = write(sockets[socknum].fd,
872 sshbuf_ptr(sockets[socknum].output),
873 sshbuf_len(sockets[socknum].output))) <= 0) {
875 if (errno == EAGAIN || errno == EINTR)
877 error("%s: read error on socket %u (fd %d): %s",
878 __func__, socknum, sockets[socknum].fd,
883 if ((r = sshbuf_consume(sockets[socknum].output, len)) != 0)
884 fatal("%s: buffer error: %s", __func__, ssh_err(r));
889 after_poll(struct pollfd *pfd, size_t npfd, u_int maxfds)
892 u_int socknum, activefds = npfd;
894 for (i = 0; i < npfd; i++) {
895 if (pfd[i].revents == 0)
897 /* Find sockets entry */
898 for (socknum = 0; socknum < sockets_alloc; socknum++) {
899 if (sockets[socknum].type != AUTH_SOCKET &&
900 sockets[socknum].type != AUTH_CONNECTION)
902 if (pfd[i].fd == sockets[socknum].fd)
905 if (socknum >= sockets_alloc) {
906 error("%s: no socket for fd %d", __func__, pfd[i].fd);
910 switch (sockets[socknum].type) {
912 if ((pfd[i].revents & (POLLIN|POLLERR)) == 0)
915 debug3("out of fds (active %u >= limit %u); "
916 "skipping accept", activefds, maxfds);
919 if (handle_socket_read(socknum) == 0)
922 case AUTH_CONNECTION:
923 if ((pfd[i].revents & (POLLIN|POLLERR)) != 0 &&
924 handle_conn_read(socknum) != 0) {
927 if ((pfd[i].revents & (POLLOUT|POLLHUP)) != 0 &&
928 handle_conn_write(socknum) != 0) {
931 fatal("activefds == 0 at close_sock");
932 close_socket(&sockets[socknum]);
944 prepare_poll(struct pollfd **pfdp, size_t *npfdp, int *timeoutp, u_int maxfds)
946 struct pollfd *pfd = *pfdp;
947 size_t i, j, npfd = 0;
950 /* Count active sockets */
951 for (i = 0; i < sockets_alloc; i++) {
952 switch (sockets[i].type) {
954 case AUTH_CONNECTION:
960 fatal("Unknown socket type %d", sockets[i].type);
964 if (npfd != *npfdp &&
965 (pfd = recallocarray(pfd, *npfdp, npfd, sizeof(*pfd))) == NULL)
966 fatal("%s: recallocarray failed", __func__);
970 for (i = j = 0; i < sockets_alloc; i++) {
971 switch (sockets[i].type) {
974 debug3("out of fds (active %zu >= limit %u); "
975 "skipping arming listener", npfd, maxfds);
978 pfd[j].fd = sockets[i].fd;
980 pfd[j].events = POLLIN;
983 case AUTH_CONNECTION:
984 pfd[j].fd = sockets[i].fd;
986 /* XXX backoff when input buffer full */
987 pfd[j].events = POLLIN;
988 if (sshbuf_len(sockets[i].output) > 0)
989 pfd[j].events |= POLLOUT;
997 if (parent_alive_interval != 0)
998 deadline = (deadline == 0) ? parent_alive_interval :
999 MINIMUM(deadline, parent_alive_interval);
1000 if (deadline == 0) {
1001 *timeoutp = -1; /* INFTIM */
1003 if (deadline > INT_MAX / 1000)
1004 *timeoutp = INT_MAX / 1000;
1006 *timeoutp = deadline * 1000;
1012 cleanup_socket(void)
1014 if (cleanup_pid != 0 && getpid() != cleanup_pid)
1016 debug("%s: cleanup", __func__);
1018 unlink(socket_name);
1032 cleanup_handler(int sig)
1035 #ifdef ENABLE_PKCS11
1042 check_parent_exists(void)
1045 * If our parent has exited then getppid() will return (pid_t)1,
1046 * so testing for that should be safe.
1048 if (parent_pid != -1 && getppid() != parent_pid) {
1049 /* printf("Parent has died - Authentication agent exiting.\n"); */
1059 "usage: ssh-agent [-c | -s] [-Dd] [-a bind_address] [-E fingerprint_hash]\n"
1060 " [-P pkcs11_whitelist] [-t life] [command [arg ...]]\n"
1061 " ssh-agent [-c | -s] -k\n");
1066 main(int ac, char **av)
1068 int c_flag = 0, d_flag = 0, D_flag = 0, k_flag = 0, s_flag = 0;
1069 int sock, fd, ch, result, saved_errno;
1070 char *shell, *format, *pidstr, *agentsocket = NULL;
1071 #ifdef HAVE_SETRLIMIT
1075 extern char *optarg;
1077 char pidstrbuf[1 + 3 * sizeof pid];
1080 int timeout = -1; /* INFTIM */
1081 struct pollfd *pfd = NULL;
1085 ssh_malloc_init(); /* must be called before any mallocs */
1086 /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
1093 platform_disable_tracing(0); /* strict=no */
1095 if (getrlimit(RLIMIT_NOFILE, &rlim) == -1)
1096 fatal("%s: getrlimit: %s", __progname, strerror(errno));
1099 OpenSSL_add_all_algorithms();
1102 __progname = ssh_get_progname(av[0]);
1105 while ((ch = getopt(ac, av, "cDdksE:a:P:t:")) != -1) {
1108 fingerprint_hash = ssh_digest_alg_by_name(optarg);
1109 if (fingerprint_hash == -1)
1110 fatal("Invalid hash algorithm \"%s\"", optarg);
1121 if (pkcs11_whitelist != NULL)
1122 fatal("-P option already specified");
1123 pkcs11_whitelist = xstrdup(optarg);
1131 if (d_flag || D_flag)
1136 if (d_flag || D_flag)
1141 agentsocket = optarg;
1144 if ((lifetime = convtime(optarg)) == -1) {
1145 fprintf(stderr, "Invalid lifetime\n");
1156 if (ac > 0 && (c_flag || k_flag || s_flag || d_flag || D_flag))
1159 if (pkcs11_whitelist == NULL)
1160 pkcs11_whitelist = xstrdup(DEFAULT_PKCS11_WHITELIST);
1162 if (ac == 0 && !c_flag && !s_flag) {
1163 shell = getenv("SHELL");
1164 if (shell != NULL && (len = strlen(shell)) > 2 &&
1165 strncmp(shell + len - 3, "csh", 3) == 0)
1169 const char *errstr = NULL;
1171 pidstr = getenv(SSH_AGENTPID_ENV_NAME);
1172 if (pidstr == NULL) {
1173 fprintf(stderr, "%s not set, cannot kill agent\n",
1174 SSH_AGENTPID_ENV_NAME);
1177 pid = (int)strtonum(pidstr, 2, INT_MAX, &errstr);
1180 "%s=\"%s\", which is not a good PID: %s\n",
1181 SSH_AGENTPID_ENV_NAME, pidstr, errstr);
1184 if (kill(pid, SIGTERM) == -1) {
1188 format = c_flag ? "unsetenv %s;\n" : "unset %s;\n";
1189 printf(format, SSH_AUTHSOCKET_ENV_NAME);
1190 printf(format, SSH_AGENTPID_ENV_NAME);
1191 printf("echo Agent pid %ld killed;\n", (long)pid);
1196 * Minimum file descriptors:
1197 * stdio (3) + listener (1) + syslog (1 maybe) + connection (1) +
1198 * a few spare for libc / stack protectors / sanitisers, etc.
1200 #define SSH_AGENT_MIN_FDS (3+1+1+1+4)
1201 if (rlim.rlim_cur < SSH_AGENT_MIN_FDS)
1202 fatal("%s: file descriptior rlimit %lld too low (minimum %u)",
1203 __progname, (long long)rlim.rlim_cur, SSH_AGENT_MIN_FDS);
1204 maxfds = rlim.rlim_cur - SSH_AGENT_MIN_FDS;
1206 parent_pid = getpid();
1208 if (agentsocket == NULL) {
1209 /* Create private directory for agent socket */
1210 mktemp_proto(socket_dir, sizeof(socket_dir));
1211 if (mkdtemp(socket_dir) == NULL) {
1212 perror("mkdtemp: private socket dir");
1215 snprintf(socket_name, sizeof socket_name, "%s/agent.%ld", socket_dir,
1218 /* Try to use specified agent socket */
1219 socket_dir[0] = '\0';
1220 strlcpy(socket_name, agentsocket, sizeof socket_name);
1224 * Create socket early so it will exist before command gets run from
1227 prev_mask = umask(0177);
1228 sock = unix_listener(socket_name, SSH_LISTEN_BACKLOG, 0);
1230 /* XXX - unix_listener() calls error() not perror() */
1231 *socket_name = '\0'; /* Don't unlink any existing file */
1237 * Fork, and have the parent execute the command, if any, or present
1238 * the socket data. The child continues as the authentication agent.
1240 if (D_flag || d_flag) {
1241 log_init(__progname,
1242 d_flag ? SYSLOG_LEVEL_DEBUG3 : SYSLOG_LEVEL_INFO,
1243 SYSLOG_FACILITY_AUTH, 1);
1244 format = c_flag ? "setenv %s %s;\n" : "%s=%s; export %s;\n";
1245 printf(format, SSH_AUTHSOCKET_ENV_NAME, socket_name,
1246 SSH_AUTHSOCKET_ENV_NAME);
1247 printf("echo Agent pid %ld;\n", (long)parent_pid);
1256 if (pid != 0) { /* Parent - execute the given command. */
1258 snprintf(pidstrbuf, sizeof pidstrbuf, "%ld", (long)pid);
1260 format = c_flag ? "setenv %s %s;\n" : "%s=%s; export %s;\n";
1261 printf(format, SSH_AUTHSOCKET_ENV_NAME, socket_name,
1262 SSH_AUTHSOCKET_ENV_NAME);
1263 printf(format, SSH_AGENTPID_ENV_NAME, pidstrbuf,
1264 SSH_AGENTPID_ENV_NAME);
1265 printf("echo Agent pid %ld;\n", (long)pid);
1268 if (setenv(SSH_AUTHSOCKET_ENV_NAME, socket_name, 1) == -1 ||
1269 setenv(SSH_AGENTPID_ENV_NAME, pidstrbuf, 1) == -1) {
1278 log_init(__progname, SYSLOG_LEVEL_INFO, SYSLOG_FACILITY_AUTH, 0);
1280 if (setsid() == -1) {
1281 error("setsid: %s", strerror(errno));
1286 if ((fd = open(_PATH_DEVNULL, O_RDWR, 0)) != -1) {
1287 /* XXX might close listen socket */
1288 (void)dup2(fd, STDIN_FILENO);
1289 (void)dup2(fd, STDOUT_FILENO);
1290 (void)dup2(fd, STDERR_FILENO);
1295 #ifdef HAVE_SETRLIMIT
1296 /* deny core dumps, since memory contains unencrypted private keys */
1297 rlim.rlim_cur = rlim.rlim_max = 0;
1298 if (setrlimit(RLIMIT_CORE, &rlim) < 0) {
1299 error("setrlimit RLIMIT_CORE: %s", strerror(errno));
1306 cleanup_pid = getpid();
1308 #ifdef ENABLE_PKCS11
1311 new_socket(AUTH_SOCKET, sock);
1313 parent_alive_interval = 10;
1315 signal(SIGPIPE, SIG_IGN);
1316 signal(SIGINT, (d_flag | D_flag) ? cleanup_handler : SIG_IGN);
1317 signal(SIGHUP, cleanup_handler);
1318 signal(SIGTERM, cleanup_handler);
1320 if (pledge("stdio rpath cpath unix id proc exec", NULL) == -1)
1321 fatal("%s: pledge: %s", __progname, strerror(errno));
1322 platform_pledge_agent();
1325 prepare_poll(&pfd, &npfd, &timeout, maxfds);
1326 result = poll(pfd, npfd, timeout);
1327 saved_errno = errno;
1328 if (parent_alive_interval != 0)
1329 check_parent_exists();
1330 (void) reaper(); /* remove expired keys */
1332 if (saved_errno == EINTR)
1334 fatal("poll: %s", strerror(saved_errno));
1335 } else if (result > 0)
1336 after_poll(pfd, npfd, maxfds);