5 * Author: Tatu Ylonen <ylo@cs.hut.fi>
7 * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
10 * Created: Mon Jul 10 22:08:59 1995 ylo
12 * Functions for reading passphrases and passwords.
22 /* Saved old terminal mode for read_passphrase. */
23 static struct termios saved_tio;
25 /* Old interrupt signal handler for read_passphrase. */
26 static void (*old_handler) (int sig) = NULL;
28 /* Interrupt signal handler for read_passphrase. */
33 /* Restore terminal modes. */
34 tcsetattr(fileno(stdin), TCSANOW, &saved_tio);
35 /* Restore the old signal handler. */
36 signal(sig, old_handler);
37 /* Resend the signal, with the old handler. */
41 /* Reads a passphrase from /dev/tty with echo turned off. Returns the
42 passphrase (allocated with xmalloc). Exits if EOF is encountered.
43 The passphrase if read from stdin if from_stdin is true (as is the
44 case with ssh-keygen). */
47 read_passphrase(const char *prompt, int from_stdin)
56 /* Read the passphrase from /dev/tty to make it possible
57 to ask it even when stdin has been redirected. */
58 f = fopen("/dev/tty", "r");
60 /* No controlling terminal and no DISPLAY. Nowhere to read. */
61 fprintf(stderr, "You have no controlling tty and no DISPLAY. Cannot read passphrase.\n");
66 /* Display the prompt (on stderr because stdout might be redirected). */
68 fprintf(stderr, "%s", prompt);
71 /* Get terminal modes. */
72 tcgetattr(fileno(f), &tio);
74 /* Save signal handler and set the new handler. */
75 old_handler = signal(SIGINT, intr_handler);
77 /* Set new terminal modes disabling all echo. */
78 tio.c_lflag &= ~(ECHO | ECHOE | ECHOK | ECHONL);
79 tcsetattr(fileno(f), TCSANOW, &tio);
81 /* Read the passphrase from the terminal. */
82 if (fgets(buf, sizeof(buf), f) == NULL) {
83 /* Got EOF. Just exit. */
84 /* Restore terminal modes. */
85 tcsetattr(fileno(f), TCSANOW, &saved_tio);
86 /* Restore the signal handler. */
87 signal(SIGINT, old_handler);
88 /* Print a newline (the prompt probably didn\'t have one). */
89 fprintf(stderr, "\n");
95 /* Restore terminal modes. */
96 tcsetattr(fileno(f), TCSANOW, &saved_tio);
97 /* Restore the signal handler. */
98 (void) signal(SIGINT, old_handler);
99 /* Remove newline from the passphrase. */
100 if (strchr(buf, '\n'))
101 *strchr(buf, '\n') = 0;
102 /* Allocate a copy of the passphrase. */
104 /* Clear the buffer so we don\'t leave copies of the passphrase
106 memset(buf, 0, sizeof(buf));
107 /* Print a newline since the prompt probably didn\'t have one. */
108 fprintf(stderr, "\n");
109 /* Close the file. */