2 * Unix Pageant, more or less similar to ssh-agent.
12 #include <sys/types.h>
17 #define PUTTY_DO_GLOBALS /* actually _define_ globals */
23 SockAddr unix_sock_addr(const char *path);
24 Socket new_unix_listener(SockAddr listenaddr, Plug plug);
26 void fatalbox(char *p, ...)
29 fprintf(stderr, "FATAL ERROR: ");
31 vfprintf(stderr, p, ap);
36 void modalfatalbox(char *p, ...)
39 fprintf(stderr, "FATAL ERROR: ");
41 vfprintf(stderr, p, ap);
46 void nonfatal(char *p, ...)
49 fprintf(stderr, "ERROR: ");
51 vfprintf(stderr, p, ap);
55 void connection_fatal(void *frontend, char *p, ...)
58 fprintf(stderr, "FATAL ERROR: ");
60 vfprintf(stderr, p, ap);
65 void cmdline_error(char *p, ...)
68 fprintf(stderr, "pageant: ");
70 vfprintf(stderr, p, ap);
76 FILE *pageant_logfp = NULL;
77 void pageant_log(void *ctx, const char *fmt, va_list ap)
82 fprintf(pageant_logfp, "pageant: ");
83 vfprintf(pageant_logfp, fmt, ap);
84 fprintf(pageant_logfp, "\n");
88 * In Pageant our selects are synchronous, so these functions are
91 int uxsel_input_add(int fd, int rwx) { return 0; }
92 void uxsel_input_remove(int id) { }
97 void random_save_seed(void) {}
98 void random_destroy_seed(void) {}
99 void noise_ultralight(unsigned long data) {}
100 char *platform_default_s(const char *name) { return NULL; }
101 int platform_default_i(const char *name, int def) { return def; }
102 FontSpec *platform_default_fontspec(const char *name) { return fontspec_new(""); }
103 Filename *platform_default_filename(const char *name) { return filename_from_str(""); }
104 char *x_get_default(const char *key) { return NULL; }
105 void log_eventlog(void *handle, const char *event) {}
108 * Short description of parameters.
110 static void usage(void)
112 printf("Pageant: SSH agent\n");
118 static void version(void)
120 printf("pageant: %s\n", ver);
124 void keylist_update(void)
126 /* Nothing needs doing in Unix Pageant */
129 #define PAGEANT_DIR_PREFIX "/tmp/pageant"
131 const char *const appname = "Pageant";
133 static int time_to_die = FALSE;
135 /* Stub functions to permit linking against x11fwd.c. These never get
136 * used, because in LIFE_X11 mode we connect to the X server using a
137 * straightforward Socket and don't try to create an ersatz SSH
139 int sshfwd_write(struct ssh_channel *c, char *data, int len) { return 0; }
140 void sshfwd_write_eof(struct ssh_channel *c) { }
141 void sshfwd_unclean_close(struct ssh_channel *c, const char *err) { }
142 void sshfwd_unthrottle(struct ssh_channel *c, int bufsize) {}
143 Conf *sshfwd_get_conf(struct ssh_channel *c) { return NULL; }
144 void sshfwd_x11_sharing_handover(struct ssh_channel *c,
145 void *share_cs, void *share_chan,
146 const char *peer_addr, int peer_port,
147 int endian, int protomajor, int protominor,
148 const void *initial_data, int initial_len) {}
149 void sshfwd_x11_is_local(struct ssh_channel *c) {}
152 * These functions are part of the plug for our connection to the X
153 * display, so they do get called. They needn't actually do anything,
154 * except that x11_closing has to signal back to the main loop that
155 * it's time to terminate.
157 static void x11_log(Plug p, int type, SockAddr addr, int port,
158 const char *error_msg, int error_code) {}
159 static int x11_receive(Plug plug, int urgent, char *data, int len) {return 0;}
160 static void x11_sent(Plug plug, int bufsize) {}
161 static int x11_closing(Plug plug, const char *error_msg, int error_code,
167 struct X11Connection {
168 const struct plug_function_table *fn;
172 void pageant_print_env(int pid)
174 printf("SSH_AUTH_SOCK=%s; export SSH_AUTH_SOCK;\n"
175 "SSH_AGENT_PID=%d; export SSH_AGENT_PID;\n",
176 socketname, (int)pid);
179 void pageant_fork_and_print_env(int retain_tty)
185 } else if (pid != 0) {
186 pageant_print_env(pid);
191 * Having forked off, we now daemonise ourselves as best we can.
192 * It's good practice in general to setsid() ourself out of any
193 * process group we didn't want to be part of, and to chdir("/")
194 * to avoid holding any directories open that we don't need in
195 * case someone wants to umount them; also, we should definitely
196 * close standard output (because it will very likely be pointing
197 * at a pipe from which some parent process is trying to read our
198 * environment variable dump, so if we hold open another copy of
199 * it then that process will never finish reading). We close
200 * standard input too on general principles, but not standard
201 * error, since we might need to shout a panicky error message
204 if (chdir("/") < 0) {
205 /* should there be an error condition, nothing we can do about
211 /* Get out of our previous process group, to avoid being
212 * blasted by passing signals. But keep our controlling tty,
213 * so we can keep checking to see if we still have one. */
216 /* Do that, but also leave our entire session and detach from
217 * the controlling tty (if any). */
224 void sigchld(int signum)
226 if (write(signalpipe[1], "x", 1) <= 0)
227 /* not much we can do about it */;
230 #define TTY_LIFE_POLL_INTERVAL (TICKSPERSEC * 30)
231 void *dummy_timer_ctx;
232 static void tty_life_timer(void *ctx, unsigned long now)
234 schedule_timer(TTY_LIFE_POLL_INTERVAL, tty_life_timer, &dummy_timer_ctx);
241 KEYACT_CLIENT_DEL_ALL,
243 KEYACT_CLIENT_PUBLIC_OPENSSH,
246 struct cmdline_key_action {
247 struct cmdline_key_action *next;
249 const char *filename;
252 int is_agent_action(keyact action)
254 return action == KEYACT_AGENT_LOAD;
257 struct cmdline_key_action *keyact_head = NULL, *keyact_tail = NULL;
259 void add_keyact(keyact action, const char *filename)
261 struct cmdline_key_action *a = snew(struct cmdline_key_action);
263 a->filename = filename;
266 keyact_tail->next = a;
272 char **exec_args = NULL;
274 LIFE_UNSPEC, LIFE_X11, LIFE_TTY, LIFE_DEBUG, LIFE_PERM, LIFE_EXEC
275 } life = LIFE_UNSPEC;
276 const char *display = NULL;
278 static char *askpass(const char *comment)
280 prompts_t *p = new_prompts(NULL);
284 * FIXME: if we don't have a terminal, and have to do this by X11,
285 * there's a big missing piece.
288 p->to_server = FALSE;
289 p->name = dupstr("Pageant passphrase prompt");
291 dupprintf("Enter passphrase to load key '%s': ", comment),
293 ret = console_get_userpass_input(p, NULL, 0);
297 perror("pageant: unable to read passphrase");
301 char *passphrase = dupstr(p->prompts[0]->result);
307 static int unix_add_keyfile(const char *filename_str)
309 Filename *filename = filename_from_str(filename_str);
316 * Try without a passphrase.
318 status = pageant_add_keyfile(filename, NULL, &err);
319 if (status == PAGEANT_ACTION_OK) {
321 } else if (status == PAGEANT_ACTION_FAILURE) {
322 fprintf(stderr, "pageant: %s: %s\n", filename_str, err);
329 * And now try prompting for a passphrase.
332 char *passphrase = askpass(err);
338 status = pageant_add_keyfile(filename, passphrase, &err);
340 smemclr(passphrase, strlen(passphrase));
344 if (status == PAGEANT_ACTION_OK) {
346 } else if (status == PAGEANT_ACTION_FAILURE) {
347 fprintf(stderr, "pageant: %s: %s\n", filename_str, err);
356 filename_free(filename);
360 void key_list_callback(void *ctx, const char *fingerprint,
361 const char *comment, struct pageant_pubkey *key)
363 printf("%s %s\n", fingerprint, comment);
366 struct key_find_ctx {
368 int match_fp, match_comment;
369 struct pageant_pubkey *found;
373 int match_fingerprint_string(const char *string, const char *fingerprint)
377 /* Find the hash in the fingerprint string. It'll be the word at the end. */
378 hash = strrchr(fingerprint, ' ');
382 /* Now see if the search string is a prefix of the full hash,
383 * neglecting colons and case differences. */
385 while (*string == ':') string++;
386 while (*hash == ':') hash++;
389 if (tolower((unsigned char)*string) != tolower((unsigned char)*hash))
396 void key_find_callback(void *vctx, const char *fingerprint,
397 const char *comment, struct pageant_pubkey *key)
399 struct key_find_ctx *ctx = (struct key_find_ctx *)vctx;
401 if ((ctx->match_comment && !strcmp(ctx->string, comment)) ||
402 (ctx->match_fp && match_fingerprint_string(ctx->string, fingerprint)))
405 ctx->found = pageant_pubkey_copy(key);
410 struct pageant_pubkey *find_key(const char *string, char **retstr)
412 struct key_find_ctx actx, *ctx = &actx;
413 struct pageant_pubkey key_in, *key_ret;
414 int try_file = TRUE, try_fp = TRUE, try_comment = TRUE;
415 int file_errors = FALSE;
418 * Trim off disambiguating prefixes telling us how to interpret
419 * the provided string.
421 if (!strncmp(string, "file:", 5)) {
423 try_fp = try_comment = FALSE;
424 file_errors = TRUE; /* also report failure to load the file */
425 } else if (!strncmp(string, "comment:", 8)) {
427 try_file = try_fp = FALSE;
428 } else if (!strncmp(string, "fp:", 3)) {
430 try_file = try_comment = FALSE;
431 } else if (!strncmp(string, "fingerprint:", 12)) {
433 try_file = try_comment = FALSE;
437 * Try interpreting the string as a key file name.
440 Filename *fn = filename_from_str(string);
441 int keytype = key_type(fn);
442 if (keytype == SSH_KEYTYPE_SSH1 ||
443 keytype == SSH_KEYTYPE_SSH1_PUBLIC) {
446 if (!rsakey_pubblob(fn, &key_in.blob, &key_in.bloblen,
449 *retstr = dupprintf("unable to load file '%s': %s",
457 * If we've successfully loaded the file, stop here - we
458 * already have a key blob and need not go to the agent to
461 key_in.ssh_version = 1;
462 key_ret = pageant_pubkey_copy(&key_in);
466 } else if (keytype == SSH_KEYTYPE_SSH2 ||
467 keytype == SSH_KEYTYPE_SSH2_PUBLIC_RFC4716 ||
468 keytype == SSH_KEYTYPE_SSH2_PUBLIC_OPENSSH) {
471 if ((key_in.blob = ssh2_userkey_loadpub(fn, NULL,
473 NULL, &error)) == NULL) {
475 *retstr = dupprintf("unable to load file '%s': %s",
483 * If we've successfully loaded the file, stop here - we
484 * already have a key blob and need not go to the agent to
487 key_in.ssh_version = 2;
488 key_ret = pageant_pubkey_copy(&key_in);
494 *retstr = dupprintf("unable to load key file '%s': %s",
495 string, key_type_to_str(keytype));
504 * Failing that, go through the keys in the agent, and match
505 * against fingerprints and comments as appropriate.
507 ctx->string = string;
508 ctx->match_fp = try_fp;
509 ctx->match_comment = try_comment;
512 if (pageant_enum_keys(key_find_callback, ctx, retstr) ==
513 PAGEANT_ACTION_FAILURE)
516 if (ctx->nfound == 0) {
517 *retstr = dupstr("no key matched");
520 } else if (ctx->nfound > 1) {
521 *retstr = dupstr("multiple keys matched");
523 pageant_pubkey_free(ctx->found);
531 void run_client(void)
533 const struct cmdline_key_action *act;
534 struct pageant_pubkey *key;
538 if (!agent_exists()) {
539 fprintf(stderr, "pageant: no agent running to talk to\n");
543 for (act = keyact_head; act; act = act->next) {
544 switch (act->action) {
545 case KEYACT_CLIENT_ADD:
546 if (!unix_add_keyfile(act->filename))
549 case KEYACT_CLIENT_LIST:
550 if (pageant_enum_keys(key_list_callback, NULL, &retstr) ==
551 PAGEANT_ACTION_FAILURE) {
552 fprintf(stderr, "pageant: listing keys: %s\n", retstr);
557 case KEYACT_CLIENT_DEL:
559 if (!(key = find_key(act->filename, &retstr)) ||
560 pageant_delete_key(key, &retstr) == PAGEANT_ACTION_FAILURE) {
561 fprintf(stderr, "pageant: deleting key '%s': %s\n",
562 act->filename, retstr);
567 pageant_pubkey_free(key);
569 case KEYACT_CLIENT_PUBLIC_OPENSSH:
570 case KEYACT_CLIENT_PUBLIC:
572 if (!(key = find_key(act->filename, &retstr))) {
573 fprintf(stderr, "pageant: finding key '%s': %s\n",
574 act->filename, retstr);
578 FILE *fp = stdout; /* FIXME: add a -o option? */
580 if (key->ssh_version == 1) {
582 memset(&rkey, 0, sizeof(rkey));
583 rkey.comment = dupstr(key->comment);
584 makekey(key->blob, key->bloblen, &rkey, NULL, 0);
585 ssh1_write_pubkey(fp, &rkey);
588 ssh2_write_pubkey(fp, key->comment, key->blob,key->bloblen,
589 (act->action == KEYACT_CLIENT_PUBLIC ?
590 SSH_KEYTYPE_SSH2_PUBLIC_RFC4716 :
591 SSH_KEYTYPE_SSH2_PUBLIC_OPENSSH));
593 pageant_pubkey_free(key);
596 case KEYACT_CLIENT_DEL_ALL:
597 if (pageant_delete_all_keys(&retstr) == PAGEANT_ACTION_FAILURE) {
598 fprintf(stderr, "pageant: deleting all keys: %s\n", retstr);
604 assert(0 && "Invalid client action found");
615 char *username, *socketdir;
616 struct pageant_listen_state *pl;
621 int i, fdcount, fdsize, fdstate;
622 int termination_pid = -1;
625 const struct cmdline_key_action *act;
628 fdcount = fdsize = 0;
633 * Start by loading any keys provided on the command line.
635 for (act = keyact_head; act; act = act->next) {
636 assert(act->action == KEYACT_AGENT_LOAD);
637 if (!unix_add_keyfile(act->filename))
644 * Set up a listening socket and run Pageant on it.
646 username = get_username();
647 socketdir = dupprintf("%s.%s", PAGEANT_DIR_PREFIX, username);
649 assert(*socketdir == '/');
650 if ((err = make_dir_and_check_ours(socketdir)) != NULL) {
651 fprintf(stderr, "pageant: %s: %s\n", socketdir, err);
654 socketname = dupprintf("%s/pageant.%d", socketdir, (int)getpid());
655 pl = pageant_listener_new();
656 sock = new_unix_listener(unix_sock_addr(socketname), (Plug)pl);
657 if ((err = sk_socket_error(sock)) != NULL) {
658 fprintf(stderr, "pageant: %s: %s\n", socketname, err);
661 pageant_listener_got_socket(pl, sock);
664 conf_set_int(conf, CONF_proxy_type, PROXY_NONE);
667 * Lifetime preparations.
669 signalpipe[0] = signalpipe[1] = -1;
670 if (life == LIFE_X11) {
671 struct X11Display *disp;
675 struct X11Connection *conn;
677 static const struct plug_function_table fn_table = {
686 display = getenv("DISPLAY");
688 fprintf(stderr, "pageant: no DISPLAY for -X mode\n");
691 disp = x11_setup_display(display, conf);
693 conn = snew(struct X11Connection);
694 conn->fn = &fn_table;
695 s = new_connection(sk_addr_dup(disp->addr),
696 disp->realhost, disp->port,
697 0, 1, 0, 0, (Plug)conn, conf);
698 if ((err = sk_socket_error(s)) != NULL) {
699 fprintf(stderr, "pageant: unable to connect to X server: %s", err);
702 greeting = x11_make_greeting('B', 11, 0, disp->localauthproto,
704 disp->localauthdatalen,
705 NULL, 0, &greetinglen);
706 sk_write(s, greeting, greetinglen);
707 smemclr(greeting, greetinglen);
710 pageant_fork_and_print_env(FALSE);
711 } else if (life == LIFE_TTY) {
712 schedule_timer(TTY_LIFE_POLL_INTERVAL,
713 tty_life_timer, &dummy_timer_ctx);
714 pageant_fork_and_print_env(TRUE);
715 } else if (life == LIFE_PERM) {
716 pageant_fork_and_print_env(FALSE);
717 } else if (life == LIFE_DEBUG) {
718 pageant_print_env(getpid());
719 pageant_logfp = stdout;
720 } else if (life == LIFE_EXEC) {
726 * Set up the pipe we'll use to tell us about SIGCHLD.
728 if (pipe(signalpipe) < 0) {
732 putty_signal(SIGCHLD, sigchld);
738 } else if (pid == 0) {
739 setenv("SSH_AUTH_SOCK", socketname, TRUE);
740 setenv("SSH_AGENT_PID", dupprintf("%d", (int)agentpid), TRUE);
741 execvp(exec_args[0], exec_args);
745 termination_pid = pid;
750 * Now we've decided on our logging arrangements, pass them on to
753 pageant_listener_set_logfn(pl, NULL, pageant_logfp ? pageant_log : NULL);
755 now = GETTICKCOUNT();
757 while (!time_to_die) {
758 fd_set rset, wset, xset;
769 if (signalpipe[0] >= 0) {
770 FD_SET_MAX(signalpipe[0], maxfd, rset);
773 /* Count the currently active fds. */
775 for (fd = first_fd(&fdstate, &rwx); fd >= 0;
776 fd = next_fd(&fdstate, &rwx)) i++;
778 /* Expand the fdlist buffer if necessary. */
781 fdlist = sresize(fdlist, fdsize, int);
785 * Add all currently open fds to the select sets, and store
786 * them in fdlist as well.
789 for (fd = first_fd(&fdstate, &rwx); fd >= 0;
790 fd = next_fd(&fdstate, &rwx)) {
791 fdlist[fdcount++] = fd;
793 FD_SET_MAX(fd, maxfd, rset);
795 FD_SET_MAX(fd, maxfd, wset);
797 FD_SET_MAX(fd, maxfd, xset);
800 if (toplevel_callback_pending()) {
804 ret = select(maxfd, &rset, &wset, &xset, &tv);
805 } else if (run_timers(now, &next)) {
811 now = GETTICKCOUNT();
812 if (now - then > next - then)
816 tv.tv_sec = ticks / 1000;
817 tv.tv_usec = ticks % 1000 * 1000;
818 ret = select(maxfd, &rset, &wset, &xset, &tv);
822 now = GETTICKCOUNT();
824 ret = select(maxfd, &rset, &wset, &xset, NULL);
827 if (ret < 0 && errno == EINTR)
835 if (life == LIFE_TTY) {
837 * Every time we wake up (whether it was due to tty_timer
838 * elapsing or for any other reason), poll to see if we
839 * still have a controlling terminal. If we don't, then
840 * our containing tty session has ended, so it's time to
841 * clean up and leave.
843 int fd = open("/dev/tty", O_RDONLY);
845 if (errno != ENXIO) {
846 perror("/dev/tty: open");
856 for (i = 0; i < fdcount; i++) {
859 * We must process exceptional notifications before
860 * ordinary readability ones, or we may go straight
861 * past the urgent marker.
863 if (FD_ISSET(fd, &xset))
864 select_result(fd, 4);
865 if (FD_ISSET(fd, &rset))
866 select_result(fd, 1);
867 if (FD_ISSET(fd, &wset))
868 select_result(fd, 2);
871 if (signalpipe[0] >= 0 && FD_ISSET(signalpipe[0], &rset)) {
873 if (read(signalpipe[0], c, 1) <= 0)
875 /* ignore its value; it'll be `x' */
879 pid = waitpid(-1, &status, WNOHANG);
882 if (pid == termination_pid)
887 run_toplevel_callbacks();
891 * When we come here, we're terminating, and should clean up our
892 * Unix socket file if possible.
894 if (unlink(socketname) < 0) {
895 fprintf(stderr, "pageant: %s: %s\n", socketname, strerror(errno));
900 int main(int argc, char **argv)
902 int doing_opts = TRUE;
903 keyact curr_keyact = KEYACT_AGENT_LOAD;
906 * Process the command line.
910 if (*p == '-' && doing_opts) {
911 if (!strcmp(p, "-V") || !strcmp(p, "--version")) {
913 } else if (!strcmp(p, "--help")) {
916 } else if (!strcmp(p, "-v")) {
917 pageant_logfp = stderr;
918 } else if (!strcmp(p, "-a")) {
919 curr_keyact = KEYACT_CLIENT_ADD;
920 } else if (!strcmp(p, "-d")) {
921 curr_keyact = KEYACT_CLIENT_DEL;
922 } else if (!strcmp(p, "-D")) {
923 add_keyact(KEYACT_CLIENT_DEL_ALL, NULL);
924 } else if (!strcmp(p, "-l")) {
925 add_keyact(KEYACT_CLIENT_LIST, NULL);
926 } else if (!strcmp(p, "--public")) {
927 curr_keyact = KEYACT_CLIENT_PUBLIC;
928 } else if (!strcmp(p, "--public-openssh")) {
929 curr_keyact = KEYACT_CLIENT_PUBLIC_OPENSSH;
930 } else if (!strcmp(p, "-X")) {
932 } else if (!strcmp(p, "-T")) {
934 } else if (!strcmp(p, "--debug")) {
936 } else if (!strcmp(p, "--permanent")) {
938 } else if (!strcmp(p, "--exec")) {
940 /* Now all subsequent arguments go to the exec command. */
943 argc = 0; /* force end of option processing */
945 fprintf(stderr, "pageant: expected a command "
949 } else if (!strcmp(p, "--")) {
954 * Non-option arguments (apart from those after --exec,
955 * which are treated specially above) are interpreted as
956 * the names of private key files to either add or delete
959 add_keyact(curr_keyact, p);
963 if (life == LIFE_EXEC && !exec_args) {
964 fprintf(stderr, "pageant: expected a command with --exec\n");
969 * Block SIGPIPE, so that we'll get EPIPE individually on
970 * particular network connections that go wrong.
972 putty_signal(SIGPIPE, SIG_IGN);
978 * Now distinguish our two main running modes. Either we're
979 * actually starting up an agent, in which case we should have a
980 * lifetime mode, and no key actions of KEYACT_CLIENT_* type; or
981 * else we're contacting an existing agent to add or remove keys,
982 * in which case we should have no lifetime mode, and no key
983 * actions of KEYACT_AGENT_* type.
986 int has_agent_actions = FALSE;
987 int has_client_actions = FALSE;
988 int has_lifetime = FALSE;
989 const struct cmdline_key_action *act;
991 for (act = keyact_head; act; act = act->next) {
992 if (is_agent_action(act->action))
993 has_agent_actions = TRUE;
995 has_client_actions = TRUE;
997 if (life != LIFE_UNSPEC)
1000 if (has_lifetime && has_client_actions) {
1001 fprintf(stderr, "pageant: client key actions (-a, -d, -D, -l, -L)"
1002 " do not go with an agent lifetime option\n");
1005 if (!has_lifetime && has_agent_actions) {
1006 fprintf(stderr, "pageant: expected an agent lifetime option with"
1007 " bare key file arguments\n");
1010 if (!has_lifetime && !has_client_actions) {
1011 fprintf(stderr, "pageant: expected an agent lifetime option"
1012 " or a client key action\n");
1018 } else if (has_client_actions) {