]> asedeno.scripts.mit.edu Git - PuTTY.git/blob - unix/uxcons.c
Omit the conf_launchable check in pterm Duplicate Session.
[PuTTY.git] / unix / uxcons.c
1 /*
2  * uxcons.c: various interactive-prompt routines shared between the
3  * Unix console PuTTY tools
4  */
5
6 #include <stdio.h>
7 #include <stdlib.h>
8 #include <stdarg.h>
9 #include <assert.h>
10 #include <errno.h>
11
12 #include <termios.h>
13 #include <unistd.h>
14 #include <fcntl.h>
15
16 #include "putty.h"
17 #include "storage.h"
18 #include "ssh.h"
19
20 int console_batch_mode = FALSE;
21
22 static void *console_logctx = NULL;
23
24 static struct termios orig_termios_stderr;
25 static int stderr_is_a_tty;
26
27 void stderr_tty_init()
28 {
29     /* Ensure that if stderr is a tty, we can get it back to a sane state. */
30     if ((flags & FLAG_STDERR_TTY) && isatty(STDERR_FILENO)) {
31         stderr_is_a_tty = TRUE;
32         tcgetattr(STDERR_FILENO, &orig_termios_stderr);
33     }
34 }
35
36 void premsg(struct termios *cf)
37 {
38     if (stderr_is_a_tty) {
39         tcgetattr(STDERR_FILENO, cf);
40         tcsetattr(STDERR_FILENO, TCSADRAIN, &orig_termios_stderr);
41     }
42 }
43 void postmsg(struct termios *cf)
44 {
45     if (stderr_is_a_tty)
46         tcsetattr(STDERR_FILENO, TCSADRAIN, cf);
47 }
48
49 /*
50  * Clean up and exit.
51  */
52 void cleanup_exit(int code)
53 {
54     /*
55      * Clean up.
56      */
57     sk_cleanup();
58     random_save_seed();
59     exit(code);
60 }
61
62 void set_busy_status(void *frontend, int status)
63 {
64 }
65
66 void update_specials_menu(void *frontend)
67 {
68 }
69
70 void notify_remote_exit(void *frontend)
71 {
72 }
73
74 void timer_change_notify(unsigned long next)
75 {
76 }
77
78 /*
79  * Wrapper around Unix read(2), suitable for use on a file descriptor
80  * that's been set into nonblocking mode. Handles EAGAIN/EWOULDBLOCK
81  * by means of doing a one-fd select and then trying again; all other
82  * errors (including errors from select) are returned to the caller.
83  */
84 static int block_and_read(int fd, void *buf, size_t len)
85 {
86     int ret;
87
88     while ((ret = read(fd, buf, len)) < 0 && (
89 #ifdef EAGAIN
90                (errno == EAGAIN) ||
91 #endif
92 #ifdef EWOULDBLOCK
93                (errno == EWOULDBLOCK) ||
94 #endif
95                0)) {
96
97         fd_set rfds;
98         FD_ZERO(&rfds);
99         FD_SET(fd, &rfds);
100         ret = select(fd+1, &rfds, NULL, NULL, NULL);
101         assert(ret != 0);
102         if (ret < 0)
103             return ret;
104         assert(FD_ISSET(fd, &rfds));
105     }
106
107     return ret;
108 }
109
110 int verify_ssh_host_key(void *frontend, char *host, int port,
111                         const char *keytype, char *keystr, char *fingerprint,
112                         void (*callback)(void *ctx, int result), void *ctx)
113 {
114     int ret;
115
116     static const char absentmsg_batch[] =
117         "The server's host key is not cached. You have no guarantee\n"
118         "that the server is the computer you think it is.\n"
119         "The server's %s key fingerprint is:\n"
120         "%s\n"
121         "Connection abandoned.\n";
122     static const char absentmsg[] =
123         "The server's host key is not cached. You have no guarantee\n"
124         "that the server is the computer you think it is.\n"
125         "The server's %s key fingerprint is:\n"
126         "%s\n"
127         "If you trust this host, enter \"y\" to add the key to\n"
128         "PuTTY's cache and carry on connecting.\n"
129         "If you want to carry on connecting just once, without\n"
130         "adding the key to the cache, enter \"n\".\n"
131         "If you do not trust this host, press Return to abandon the\n"
132         "connection.\n"
133         "Store key in cache? (y/n) ";
134
135     static const char wrongmsg_batch[] =
136         "WARNING - POTENTIAL SECURITY BREACH!\n"
137         "The server's host key does not match the one PuTTY has\n"
138         "cached. This means that either the server administrator\n"
139         "has changed the host key, or you have actually connected\n"
140         "to another computer pretending to be the server.\n"
141         "The new %s key fingerprint is:\n"
142         "%s\n"
143         "Connection abandoned.\n";
144     static const char wrongmsg[] =
145         "WARNING - POTENTIAL SECURITY BREACH!\n"
146         "The server's host key does not match the one PuTTY has\n"
147         "cached. This means that either the server administrator\n"
148         "has changed the host key, or you have actually connected\n"
149         "to another computer pretending to be the server.\n"
150         "The new %s key fingerprint is:\n"
151         "%s\n"
152         "If you were expecting this change and trust the new key,\n"
153         "enter \"y\" to update PuTTY's cache and continue connecting.\n"
154         "If you want to carry on connecting but without updating\n"
155         "the cache, enter \"n\".\n"
156         "If you want to abandon the connection completely, press\n"
157         "Return to cancel. Pressing Return is the ONLY guaranteed\n"
158         "safe choice.\n"
159         "Update cached key? (y/n, Return cancels connection) ";
160
161     static const char abandoned[] = "Connection abandoned.\n";
162
163     char line[32];
164     struct termios cf;
165
166     /*
167      * Verify the key.
168      */
169     ret = verify_host_key(host, port, keytype, keystr);
170
171     if (ret == 0)                      /* success - key matched OK */
172         return 1;
173
174     premsg(&cf);
175     if (ret == 2) {                    /* key was different */
176         if (console_batch_mode) {
177             fprintf(stderr, wrongmsg_batch, keytype, fingerprint);
178             return 0;
179         }
180         fprintf(stderr, wrongmsg, keytype, fingerprint);
181         fflush(stderr);
182     }
183     if (ret == 1) {                    /* key was absent */
184         if (console_batch_mode) {
185             fprintf(stderr, absentmsg_batch, keytype, fingerprint);
186             return 0;
187         }
188         fprintf(stderr, absentmsg, keytype, fingerprint);
189         fflush(stderr);
190     }
191
192     {
193         struct termios oldmode, newmode;
194         tcgetattr(0, &oldmode);
195         newmode = oldmode;
196         newmode.c_lflag |= ECHO | ISIG | ICANON;
197         tcsetattr(0, TCSANOW, &newmode);
198         line[0] = '\0';
199         if (block_and_read(0, line, sizeof(line) - 1) <= 0)
200             /* handled below */;
201         tcsetattr(0, TCSANOW, &oldmode);
202     }
203
204     if (line[0] != '\0' && line[0] != '\r' && line[0] != '\n') {
205         if (line[0] == 'y' || line[0] == 'Y')
206             store_host_key(host, port, keytype, keystr);
207         postmsg(&cf);
208         return 1;
209     } else {
210         fprintf(stderr, abandoned);
211         postmsg(&cf);
212         return 0;
213     }
214 }
215
216 /*
217  * Ask whether the selected algorithm is acceptable (since it was
218  * below the configured 'warn' threshold).
219  */
220 int askalg(void *frontend, const char *algtype, const char *algname,
221            void (*callback)(void *ctx, int result), void *ctx)
222 {
223     static const char msg[] =
224         "The first %s supported by the server is\n"
225         "%s, which is below the configured warning threshold.\n"
226         "Continue with connection? (y/n) ";
227     static const char msg_batch[] =
228         "The first %s supported by the server is\n"
229         "%s, which is below the configured warning threshold.\n"
230         "Connection abandoned.\n";
231     static const char abandoned[] = "Connection abandoned.\n";
232
233     char line[32];
234     struct termios cf;
235
236     premsg(&cf);
237     if (console_batch_mode) {
238         fprintf(stderr, msg_batch, algtype, algname);
239         return 0;
240     }
241
242     fprintf(stderr, msg, algtype, algname);
243     fflush(stderr);
244
245     {
246         struct termios oldmode, newmode;
247         tcgetattr(0, &oldmode);
248         newmode = oldmode;
249         newmode.c_lflag |= ECHO | ISIG | ICANON;
250         tcsetattr(0, TCSANOW, &newmode);
251         line[0] = '\0';
252         if (block_and_read(0, line, sizeof(line) - 1) <= 0)
253             /* handled below */;
254         tcsetattr(0, TCSANOW, &oldmode);
255     }
256
257     if (line[0] == 'y' || line[0] == 'Y') {
258         postmsg(&cf);
259         return 1;
260     } else {
261         fprintf(stderr, abandoned);
262         postmsg(&cf);
263         return 0;
264     }
265 }
266
267 /*
268  * Ask whether to wipe a session log file before writing to it.
269  * Returns 2 for wipe, 1 for append, 0 for cancel (don't log).
270  */
271 int askappend(void *frontend, Filename *filename,
272               void (*callback)(void *ctx, int result), void *ctx)
273 {
274     static const char msgtemplate[] =
275         "The session log file \"%.*s\" already exists.\n"
276         "You can overwrite it with a new session log,\n"
277         "append your session log to the end of it,\n"
278         "or disable session logging for this session.\n"
279         "Enter \"y\" to wipe the file, \"n\" to append to it,\n"
280         "or just press Return to disable logging.\n"
281         "Wipe the log file? (y/n, Return cancels logging) ";
282
283     static const char msgtemplate_batch[] =
284         "The session log file \"%.*s\" already exists.\n"
285         "Logging will not be enabled.\n";
286
287     char line[32];
288     struct termios cf;
289
290     premsg(&cf);
291     if (console_batch_mode) {
292         fprintf(stderr, msgtemplate_batch, FILENAME_MAX, filename->path);
293         fflush(stderr);
294         return 0;
295     }
296     fprintf(stderr, msgtemplate, FILENAME_MAX, filename->path);
297     fflush(stderr);
298
299     {
300         struct termios oldmode, newmode;
301         tcgetattr(0, &oldmode);
302         newmode = oldmode;
303         newmode.c_lflag |= ECHO | ISIG | ICANON;
304         tcsetattr(0, TCSANOW, &newmode);
305         line[0] = '\0';
306         if (block_and_read(0, line, sizeof(line) - 1) <= 0)
307             /* handled below */;
308         tcsetattr(0, TCSANOW, &oldmode);
309     }
310
311     postmsg(&cf);
312     if (line[0] == 'y' || line[0] == 'Y')
313         return 2;
314     else if (line[0] == 'n' || line[0] == 'N')
315         return 1;
316     else
317         return 0;
318 }
319
320 /*
321  * Warn about the obsolescent key file format.
322  * 
323  * Uniquely among these functions, this one does _not_ expect a
324  * frontend handle. This means that if PuTTY is ported to a
325  * platform which requires frontend handles, this function will be
326  * an anomaly. Fortunately, the problem it addresses will not have
327  * been present on that platform, so it can plausibly be
328  * implemented as an empty function.
329  */
330 void old_keyfile_warning(void)
331 {
332     static const char message[] =
333         "You are loading an SSH-2 private key which has an\n"
334         "old version of the file format. This means your key\n"
335         "file is not fully tamperproof. Future versions of\n"
336         "PuTTY may stop supporting this private key format,\n"
337         "so we recommend you convert your key to the new\n"
338         "format.\n"
339         "\n"
340         "Once the key is loaded into PuTTYgen, you can perform\n"
341         "this conversion simply by saving it again.\n";
342
343     struct termios cf;
344     premsg(&cf);
345     fputs(message, stderr);
346     postmsg(&cf);
347 }
348
349 void console_provide_logctx(void *logctx)
350 {
351     console_logctx = logctx;
352 }
353
354 void logevent(void *frontend, const char *string)
355 {
356     struct termios cf;
357     if ((flags & FLAG_STDERR) && (flags & FLAG_VERBOSE))
358         premsg(&cf);
359     if (console_logctx)
360         log_eventlog(console_logctx, string);
361     if ((flags & FLAG_STDERR) && (flags & FLAG_VERBOSE))
362         postmsg(&cf);
363 }
364
365 /*
366  * Special functions to read and print to the console for password
367  * prompts and the like. Uses /dev/tty or stdin/stderr, in that order
368  * of preference; also sanitises escape sequences out of the text, on
369  * the basis that it might have been sent by a hostile SSH server
370  * doing malicious keyboard-interactive.
371  */
372 static void console_open(FILE **outfp, int *infd)
373 {
374     int fd;
375
376     if ((fd = open("/dev/tty", O_RDWR)) >= 0) {
377         *infd = fd;
378         *outfp = fdopen(*infd, "w");
379     } else {
380         *infd = 0;
381         *outfp = stderr;
382     }
383 }
384 static void console_close(FILE *outfp, int infd)
385 {
386     if (outfp != stderr)
387         fclose(outfp);             /* will automatically close infd too */
388 }
389
390 static void console_prompt_text(FILE *outfp, const char *data, int len)
391 {
392     int i;
393
394     for (i = 0; i < len; i++)
395         if ((data[i] & 0x60) || (data[i] == '\n'))
396             fputc(data[i], outfp);
397     fflush(outfp);
398 }
399
400 int console_get_userpass_input(prompts_t *p, const unsigned char *in,
401                                int inlen)
402 {
403     size_t curr_prompt;
404     FILE *outfp = NULL;
405     int infd;
406
407     /*
408      * Zero all the results, in case we abort half-way through.
409      */
410     {
411         int i;
412         for (i = 0; i < p->n_prompts; i++)
413             prompt_set_result(p->prompts[i], "");
414     }
415
416     if (p->n_prompts && console_batch_mode)
417         return 0;
418
419     console_open(&outfp, &infd);
420
421     /*
422      * Preamble.
423      */
424     /* We only print the `name' caption if we have to... */
425     if (p->name_reqd && p->name) {
426         size_t l = strlen(p->name);
427         console_prompt_text(outfp, p->name, l);
428         if (p->name[l-1] != '\n')
429             console_prompt_text(outfp, "\n", 1);
430     }
431     /* ...but we always print any `instruction'. */
432     if (p->instruction) {
433         size_t l = strlen(p->instruction);
434         console_prompt_text(outfp, p->instruction, l);
435         if (p->instruction[l-1] != '\n')
436             console_prompt_text(outfp, "\n", 1);
437     }
438
439     for (curr_prompt = 0; curr_prompt < p->n_prompts; curr_prompt++) {
440
441         struct termios oldmode, newmode;
442         int len;
443         prompt_t *pr = p->prompts[curr_prompt];
444
445         tcgetattr(infd, &oldmode);
446         newmode = oldmode;
447         newmode.c_lflag |= ISIG | ICANON;
448         if (!pr->echo)
449             newmode.c_lflag &= ~ECHO;
450         else
451             newmode.c_lflag |= ECHO;
452         tcsetattr(infd, TCSANOW, &newmode);
453
454         console_prompt_text(outfp, pr->prompt, strlen(pr->prompt));
455
456         len = 0;
457         while (1) {
458             int ret;
459
460             prompt_ensure_result_size(pr, len * 5 / 4 + 512);
461             ret = read(infd, pr->result + len, pr->resultsize - len - 1);
462             if (ret <= 0) {
463                 len = -1;
464                 break;
465             }
466             len += ret;
467             if (pr->result[len - 1] == '\n') {
468                 len--;
469                 break;
470             }
471         }
472
473         tcsetattr(infd, TCSANOW, &oldmode);
474
475         if (!pr->echo)
476             console_prompt_text(outfp, "\n", 1);
477
478         if (len < 0) {
479             console_close(outfp, infd);
480             return 0;                  /* failure due to read error */
481         }
482
483         pr->result[len] = '\0';
484     }
485
486     console_close(outfp, infd);
487
488     return 1; /* success */
489 }
490
491 void frontend_keypress(void *handle)
492 {
493     /*
494      * This is nothing but a stub, in console code.
495      */
496     return;
497 }
498
499 int is_interactive(void)
500 {
501     return isatty(0);
502 }
503
504 /*
505  * X11-forwarding-related things suitable for console.
506  */
507
508 char *platform_get_x_display(void) {
509     return dupstr(getenv("DISPLAY"));
510 }