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 int have_controlling_tty(void)
274 int fd = open("/dev/tty", O_RDONLY);
276 if (errno != ENXIO) {
277 perror("/dev/tty: open");
287 char **exec_args = NULL;
289 LIFE_UNSPEC, LIFE_X11, LIFE_TTY, LIFE_DEBUG, LIFE_PERM, LIFE_EXEC
290 } life = LIFE_UNSPEC;
291 const char *display = NULL;
293 static char *askpass(const char *comment)
295 prompts_t *p = new_prompts(NULL);
299 * FIXME: if we don't have a terminal, and have to do this by X11,
300 * there's a big missing piece.
303 p->to_server = FALSE;
304 p->name = dupstr("Pageant passphrase prompt");
306 dupprintf("Enter passphrase to load key '%s': ", comment),
308 ret = console_get_userpass_input(p, NULL, 0);
312 perror("pageant: unable to read passphrase");
316 char *passphrase = dupstr(p->prompts[0]->result);
322 static int unix_add_keyfile(const char *filename_str)
324 Filename *filename = filename_from_str(filename_str);
331 * Try without a passphrase.
333 status = pageant_add_keyfile(filename, NULL, &err);
334 if (status == PAGEANT_ACTION_OK) {
336 } else if (status == PAGEANT_ACTION_FAILURE) {
337 fprintf(stderr, "pageant: %s: %s\n", filename_str, err);
344 * And now try prompting for a passphrase.
347 char *passphrase = askpass(err);
353 status = pageant_add_keyfile(filename, passphrase, &err);
355 smemclr(passphrase, strlen(passphrase));
359 if (status == PAGEANT_ACTION_OK) {
361 } else if (status == PAGEANT_ACTION_FAILURE) {
362 fprintf(stderr, "pageant: %s: %s\n", filename_str, err);
371 filename_free(filename);
375 void key_list_callback(void *ctx, const char *fingerprint,
376 const char *comment, struct pageant_pubkey *key)
378 printf("%s %s\n", fingerprint, comment);
381 struct key_find_ctx {
383 int match_fp, match_comment;
384 struct pageant_pubkey *found;
388 int match_fingerprint_string(const char *string, const char *fingerprint)
392 /* Find the hash in the fingerprint string. It'll be the word at the end. */
393 hash = strrchr(fingerprint, ' ');
397 /* Now see if the search string is a prefix of the full hash,
398 * neglecting colons and case differences. */
400 while (*string == ':') string++;
401 while (*hash == ':') hash++;
404 if (tolower((unsigned char)*string) != tolower((unsigned char)*hash))
411 void key_find_callback(void *vctx, const char *fingerprint,
412 const char *comment, struct pageant_pubkey *key)
414 struct key_find_ctx *ctx = (struct key_find_ctx *)vctx;
416 if ((ctx->match_comment && !strcmp(ctx->string, comment)) ||
417 (ctx->match_fp && match_fingerprint_string(ctx->string, fingerprint)))
420 ctx->found = pageant_pubkey_copy(key);
425 struct pageant_pubkey *find_key(const char *string, char **retstr)
427 struct key_find_ctx actx, *ctx = &actx;
428 struct pageant_pubkey key_in, *key_ret;
429 int try_file = TRUE, try_fp = TRUE, try_comment = TRUE;
430 int file_errors = FALSE;
433 * Trim off disambiguating prefixes telling us how to interpret
434 * the provided string.
436 if (!strncmp(string, "file:", 5)) {
438 try_fp = try_comment = FALSE;
439 file_errors = TRUE; /* also report failure to load the file */
440 } else if (!strncmp(string, "comment:", 8)) {
442 try_file = try_fp = FALSE;
443 } else if (!strncmp(string, "fp:", 3)) {
445 try_file = try_comment = FALSE;
446 } else if (!strncmp(string, "fingerprint:", 12)) {
448 try_file = try_comment = FALSE;
452 * Try interpreting the string as a key file name.
455 Filename *fn = filename_from_str(string);
456 int keytype = key_type(fn);
457 if (keytype == SSH_KEYTYPE_SSH1 ||
458 keytype == SSH_KEYTYPE_SSH1_PUBLIC) {
461 if (!rsakey_pubblob(fn, &key_in.blob, &key_in.bloblen,
464 *retstr = dupprintf("unable to load file '%s': %s",
472 * If we've successfully loaded the file, stop here - we
473 * already have a key blob and need not go to the agent to
476 key_in.ssh_version = 1;
477 key_ret = pageant_pubkey_copy(&key_in);
481 } else if (keytype == SSH_KEYTYPE_SSH2 ||
482 keytype == SSH_KEYTYPE_SSH2_PUBLIC_RFC4716 ||
483 keytype == SSH_KEYTYPE_SSH2_PUBLIC_OPENSSH) {
486 if ((key_in.blob = ssh2_userkey_loadpub(fn, NULL,
488 NULL, &error)) == NULL) {
490 *retstr = dupprintf("unable to load file '%s': %s",
498 * If we've successfully loaded the file, stop here - we
499 * already have a key blob and need not go to the agent to
502 key_in.ssh_version = 2;
503 key_ret = pageant_pubkey_copy(&key_in);
509 *retstr = dupprintf("unable to load key file '%s': %s",
510 string, key_type_to_str(keytype));
519 * Failing that, go through the keys in the agent, and match
520 * against fingerprints and comments as appropriate.
522 ctx->string = string;
523 ctx->match_fp = try_fp;
524 ctx->match_comment = try_comment;
527 if (pageant_enum_keys(key_find_callback, ctx, retstr) ==
528 PAGEANT_ACTION_FAILURE)
531 if (ctx->nfound == 0) {
532 *retstr = dupstr("no key matched");
535 } else if (ctx->nfound > 1) {
536 *retstr = dupstr("multiple keys matched");
538 pageant_pubkey_free(ctx->found);
546 void run_client(void)
548 const struct cmdline_key_action *act;
549 struct pageant_pubkey *key;
553 if (!agent_exists()) {
554 fprintf(stderr, "pageant: no agent running to talk to\n");
558 for (act = keyact_head; act; act = act->next) {
559 switch (act->action) {
560 case KEYACT_CLIENT_ADD:
561 if (!unix_add_keyfile(act->filename))
564 case KEYACT_CLIENT_LIST:
565 if (pageant_enum_keys(key_list_callback, NULL, &retstr) ==
566 PAGEANT_ACTION_FAILURE) {
567 fprintf(stderr, "pageant: listing keys: %s\n", retstr);
572 case KEYACT_CLIENT_DEL:
574 if (!(key = find_key(act->filename, &retstr)) ||
575 pageant_delete_key(key, &retstr) == PAGEANT_ACTION_FAILURE) {
576 fprintf(stderr, "pageant: deleting key '%s': %s\n",
577 act->filename, retstr);
582 pageant_pubkey_free(key);
584 case KEYACT_CLIENT_PUBLIC_OPENSSH:
585 case KEYACT_CLIENT_PUBLIC:
587 if (!(key = find_key(act->filename, &retstr))) {
588 fprintf(stderr, "pageant: finding key '%s': %s\n",
589 act->filename, retstr);
593 FILE *fp = stdout; /* FIXME: add a -o option? */
595 if (key->ssh_version == 1) {
597 memset(&rkey, 0, sizeof(rkey));
598 rkey.comment = dupstr(key->comment);
599 makekey(key->blob, key->bloblen, &rkey, NULL, 0);
600 ssh1_write_pubkey(fp, &rkey);
603 ssh2_write_pubkey(fp, key->comment, key->blob,key->bloblen,
604 (act->action == KEYACT_CLIENT_PUBLIC ?
605 SSH_KEYTYPE_SSH2_PUBLIC_RFC4716 :
606 SSH_KEYTYPE_SSH2_PUBLIC_OPENSSH));
608 pageant_pubkey_free(key);
611 case KEYACT_CLIENT_DEL_ALL:
612 if (pageant_delete_all_keys(&retstr) == PAGEANT_ACTION_FAILURE) {
613 fprintf(stderr, "pageant: deleting all keys: %s\n", retstr);
619 assert(0 && "Invalid client action found");
630 char *username, *socketdir;
631 struct pageant_listen_state *pl;
636 int i, fdcount, fdsize, fdstate;
637 int termination_pid = -1;
640 const struct cmdline_key_action *act;
643 fdcount = fdsize = 0;
648 * Start by loading any keys provided on the command line.
650 for (act = keyact_head; act; act = act->next) {
651 assert(act->action == KEYACT_AGENT_LOAD);
652 if (!unix_add_keyfile(act->filename))
659 * Set up a listening socket and run Pageant on it.
661 username = get_username();
662 socketdir = dupprintf("%s.%s", PAGEANT_DIR_PREFIX, username);
664 assert(*socketdir == '/');
665 if ((err = make_dir_and_check_ours(socketdir)) != NULL) {
666 fprintf(stderr, "pageant: %s: %s\n", socketdir, err);
669 socketname = dupprintf("%s/pageant.%d", socketdir, (int)getpid());
670 pl = pageant_listener_new();
671 sock = new_unix_listener(unix_sock_addr(socketname), (Plug)pl);
672 if ((err = sk_socket_error(sock)) != NULL) {
673 fprintf(stderr, "pageant: %s: %s\n", socketname, err);
676 pageant_listener_got_socket(pl, sock);
679 conf_set_int(conf, CONF_proxy_type, PROXY_NONE);
682 * Lifetime preparations.
684 signalpipe[0] = signalpipe[1] = -1;
685 if (life == LIFE_X11) {
686 struct X11Display *disp;
690 struct X11Connection *conn;
692 static const struct plug_function_table fn_table = {
701 display = getenv("DISPLAY");
703 fprintf(stderr, "pageant: no DISPLAY for -X mode\n");
706 disp = x11_setup_display(display, conf);
708 conn = snew(struct X11Connection);
709 conn->fn = &fn_table;
710 s = new_connection(sk_addr_dup(disp->addr),
711 disp->realhost, disp->port,
712 0, 1, 0, 0, (Plug)conn, conf);
713 if ((err = sk_socket_error(s)) != NULL) {
714 fprintf(stderr, "pageant: unable to connect to X server: %s", err);
717 greeting = x11_make_greeting('B', 11, 0, disp->localauthproto,
719 disp->localauthdatalen,
720 NULL, 0, &greetinglen);
721 sk_write(s, greeting, greetinglen);
722 smemclr(greeting, greetinglen);
725 pageant_fork_and_print_env(FALSE);
726 } else if (life == LIFE_TTY) {
727 schedule_timer(TTY_LIFE_POLL_INTERVAL,
728 tty_life_timer, &dummy_timer_ctx);
729 pageant_fork_and_print_env(TRUE);
730 } else if (life == LIFE_PERM) {
731 pageant_fork_and_print_env(FALSE);
732 } else if (life == LIFE_DEBUG) {
733 pageant_print_env(getpid());
734 pageant_logfp = stdout;
735 } else if (life == LIFE_EXEC) {
741 * Set up the pipe we'll use to tell us about SIGCHLD.
743 if (pipe(signalpipe) < 0) {
747 putty_signal(SIGCHLD, sigchld);
753 } else if (pid == 0) {
754 setenv("SSH_AUTH_SOCK", socketname, TRUE);
755 setenv("SSH_AGENT_PID", dupprintf("%d", (int)agentpid), TRUE);
756 execvp(exec_args[0], exec_args);
760 termination_pid = pid;
765 * Now we've decided on our logging arrangements, pass them on to
768 pageant_listener_set_logfn(pl, NULL, pageant_logfp ? pageant_log : NULL);
770 now = GETTICKCOUNT();
772 while (!time_to_die) {
773 fd_set rset, wset, xset;
784 if (signalpipe[0] >= 0) {
785 FD_SET_MAX(signalpipe[0], maxfd, rset);
788 /* Count the currently active fds. */
790 for (fd = first_fd(&fdstate, &rwx); fd >= 0;
791 fd = next_fd(&fdstate, &rwx)) i++;
793 /* Expand the fdlist buffer if necessary. */
796 fdlist = sresize(fdlist, fdsize, int);
800 * Add all currently open fds to the select sets, and store
801 * them in fdlist as well.
804 for (fd = first_fd(&fdstate, &rwx); fd >= 0;
805 fd = next_fd(&fdstate, &rwx)) {
806 fdlist[fdcount++] = fd;
808 FD_SET_MAX(fd, maxfd, rset);
810 FD_SET_MAX(fd, maxfd, wset);
812 FD_SET_MAX(fd, maxfd, xset);
815 if (toplevel_callback_pending()) {
819 ret = select(maxfd, &rset, &wset, &xset, &tv);
820 } else if (run_timers(now, &next)) {
826 now = GETTICKCOUNT();
827 if (now - then > next - then)
831 tv.tv_sec = ticks / 1000;
832 tv.tv_usec = ticks % 1000 * 1000;
833 ret = select(maxfd, &rset, &wset, &xset, &tv);
837 now = GETTICKCOUNT();
839 ret = select(maxfd, &rset, &wset, &xset, NULL);
842 if (ret < 0 && errno == EINTR)
850 if (life == LIFE_TTY) {
852 * Every time we wake up (whether it was due to tty_timer
853 * elapsing or for any other reason), poll to see if we
854 * still have a controlling terminal. If we don't, then
855 * our containing tty session has ended, so it's time to
856 * clean up and leave.
858 if (!have_controlling_tty()) {
864 for (i = 0; i < fdcount; i++) {
867 * We must process exceptional notifications before
868 * ordinary readability ones, or we may go straight
869 * past the urgent marker.
871 if (FD_ISSET(fd, &xset))
872 select_result(fd, 4);
873 if (FD_ISSET(fd, &rset))
874 select_result(fd, 1);
875 if (FD_ISSET(fd, &wset))
876 select_result(fd, 2);
879 if (signalpipe[0] >= 0 && FD_ISSET(signalpipe[0], &rset)) {
881 if (read(signalpipe[0], c, 1) <= 0)
883 /* ignore its value; it'll be `x' */
887 pid = waitpid(-1, &status, WNOHANG);
890 if (pid == termination_pid)
895 run_toplevel_callbacks();
899 * When we come here, we're terminating, and should clean up our
900 * Unix socket file if possible.
902 if (unlink(socketname) < 0) {
903 fprintf(stderr, "pageant: %s: %s\n", socketname, strerror(errno));
908 int main(int argc, char **argv)
910 int doing_opts = TRUE;
911 keyact curr_keyact = KEYACT_AGENT_LOAD;
914 * Process the command line.
918 if (*p == '-' && doing_opts) {
919 if (!strcmp(p, "-V") || !strcmp(p, "--version")) {
921 } else if (!strcmp(p, "--help")) {
924 } else if (!strcmp(p, "-v")) {
925 pageant_logfp = stderr;
926 } else if (!strcmp(p, "-a")) {
927 curr_keyact = KEYACT_CLIENT_ADD;
928 } else if (!strcmp(p, "-d")) {
929 curr_keyact = KEYACT_CLIENT_DEL;
930 } else if (!strcmp(p, "-D")) {
931 add_keyact(KEYACT_CLIENT_DEL_ALL, NULL);
932 } else if (!strcmp(p, "-l")) {
933 add_keyact(KEYACT_CLIENT_LIST, NULL);
934 } else if (!strcmp(p, "--public")) {
935 curr_keyact = KEYACT_CLIENT_PUBLIC;
936 } else if (!strcmp(p, "--public-openssh")) {
937 curr_keyact = KEYACT_CLIENT_PUBLIC_OPENSSH;
938 } else if (!strcmp(p, "-X")) {
940 } else if (!strcmp(p, "-T")) {
942 } else if (!strcmp(p, "--debug")) {
944 } else if (!strcmp(p, "--permanent")) {
946 } else if (!strcmp(p, "--exec")) {
948 /* Now all subsequent arguments go to the exec command. */
951 argc = 0; /* force end of option processing */
953 fprintf(stderr, "pageant: expected a command "
957 } else if (!strcmp(p, "--")) {
962 * Non-option arguments (apart from those after --exec,
963 * which are treated specially above) are interpreted as
964 * the names of private key files to either add or delete
967 add_keyact(curr_keyact, p);
971 if (life == LIFE_EXEC && !exec_args) {
972 fprintf(stderr, "pageant: expected a command with --exec\n");
977 * Block SIGPIPE, so that we'll get EPIPE individually on
978 * particular network connections that go wrong.
980 putty_signal(SIGPIPE, SIG_IGN);
986 * Now distinguish our two main running modes. Either we're
987 * actually starting up an agent, in which case we should have a
988 * lifetime mode, and no key actions of KEYACT_CLIENT_* type; or
989 * else we're contacting an existing agent to add or remove keys,
990 * in which case we should have no lifetime mode, and no key
991 * actions of KEYACT_AGENT_* type.
994 int has_agent_actions = FALSE;
995 int has_client_actions = FALSE;
996 int has_lifetime = FALSE;
997 const struct cmdline_key_action *act;
999 for (act = keyact_head; act; act = act->next) {
1000 if (is_agent_action(act->action))
1001 has_agent_actions = TRUE;
1003 has_client_actions = TRUE;
1005 if (life != LIFE_UNSPEC)
1006 has_lifetime = TRUE;
1008 if (has_lifetime && has_client_actions) {
1009 fprintf(stderr, "pageant: client key actions (-a, -d, -D, -l, -L)"
1010 " do not go with an agent lifetime option\n");
1013 if (!has_lifetime && has_agent_actions) {
1014 fprintf(stderr, "pageant: expected an agent lifetime option with"
1015 " bare key file arguments\n");
1018 if (!has_lifetime && !has_client_actions) {
1019 fprintf(stderr, "pageant: expected an agent lifetime option"
1020 " or a client key action\n");
1026 } else if (has_client_actions) {