]> asedeno.scripts.mit.edu Git - PuTTY.git/blob - unix/uxcons.c
Compile fix for GTK 3.18: avoid gtk_adjustment_changed().
[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 int askhk(void *frontend, const char *algname, const char *betteralgs,
268           void (*callback)(void *ctx, int result), void *ctx)
269 {
270     static const char msg[] =
271         "The first host key type we have stored for this server\n"
272         "is %s, which is below the configured warning threshold.\n"
273         "The server also provides the following types of host key\n"
274         "above the threshold, which we do not have stored:\n"
275         "%s\n"
276         "Continue with connection? (y/n) ";
277     static const char msg_batch[] =
278         "The first host key type we have stored for this server\n"
279         "is %s, which is below the configured warning threshold.\n"
280         "The server also provides the following types of host key\n"
281         "above the threshold, which we do not have stored:\n"
282         "%s\n"
283         "Connection abandoned.\n";
284     static const char abandoned[] = "Connection abandoned.\n";
285
286     char line[32];
287     struct termios cf;
288
289     premsg(&cf);
290     if (console_batch_mode) {
291         fprintf(stderr, msg_batch, algname, betteralgs);
292         return 0;
293     }
294
295     fprintf(stderr, msg, algname, betteralgs);
296     fflush(stderr);
297
298     {
299         struct termios oldmode, newmode;
300         tcgetattr(0, &oldmode);
301         newmode = oldmode;
302         newmode.c_lflag |= ECHO | ISIG | ICANON;
303         tcsetattr(0, TCSANOW, &newmode);
304         line[0] = '\0';
305         if (block_and_read(0, line, sizeof(line) - 1) <= 0)
306             /* handled below */;
307         tcsetattr(0, TCSANOW, &oldmode);
308     }
309
310     if (line[0] == 'y' || line[0] == 'Y') {
311         postmsg(&cf);
312         return 1;
313     } else {
314         fprintf(stderr, abandoned);
315         postmsg(&cf);
316         return 0;
317     }
318 }
319
320 /*
321  * Ask whether to wipe a session log file before writing to it.
322  * Returns 2 for wipe, 1 for append, 0 for cancel (don't log).
323  */
324 int askappend(void *frontend, Filename *filename,
325               void (*callback)(void *ctx, int result), void *ctx)
326 {
327     static const char msgtemplate[] =
328         "The session log file \"%.*s\" already exists.\n"
329         "You can overwrite it with a new session log,\n"
330         "append your session log to the end of it,\n"
331         "or disable session logging for this session.\n"
332         "Enter \"y\" to wipe the file, \"n\" to append to it,\n"
333         "or just press Return to disable logging.\n"
334         "Wipe the log file? (y/n, Return cancels logging) ";
335
336     static const char msgtemplate_batch[] =
337         "The session log file \"%.*s\" already exists.\n"
338         "Logging will not be enabled.\n";
339
340     char line[32];
341     struct termios cf;
342
343     premsg(&cf);
344     if (console_batch_mode) {
345         fprintf(stderr, msgtemplate_batch, FILENAME_MAX, filename->path);
346         fflush(stderr);
347         return 0;
348     }
349     fprintf(stderr, msgtemplate, FILENAME_MAX, filename->path);
350     fflush(stderr);
351
352     {
353         struct termios oldmode, newmode;
354         tcgetattr(0, &oldmode);
355         newmode = oldmode;
356         newmode.c_lflag |= ECHO | ISIG | ICANON;
357         tcsetattr(0, TCSANOW, &newmode);
358         line[0] = '\0';
359         if (block_and_read(0, line, sizeof(line) - 1) <= 0)
360             /* handled below */;
361         tcsetattr(0, TCSANOW, &oldmode);
362     }
363
364     postmsg(&cf);
365     if (line[0] == 'y' || line[0] == 'Y')
366         return 2;
367     else if (line[0] == 'n' || line[0] == 'N')
368         return 1;
369     else
370         return 0;
371 }
372
373 /*
374  * Warn about the obsolescent key file format.
375  * 
376  * Uniquely among these functions, this one does _not_ expect a
377  * frontend handle. This means that if PuTTY is ported to a
378  * platform which requires frontend handles, this function will be
379  * an anomaly. Fortunately, the problem it addresses will not have
380  * been present on that platform, so it can plausibly be
381  * implemented as an empty function.
382  */
383 void old_keyfile_warning(void)
384 {
385     static const char message[] =
386         "You are loading an SSH-2 private key which has an\n"
387         "old version of the file format. This means your key\n"
388         "file is not fully tamperproof. Future versions of\n"
389         "PuTTY may stop supporting this private key format,\n"
390         "so we recommend you convert your key to the new\n"
391         "format.\n"
392         "\n"
393         "Once the key is loaded into PuTTYgen, you can perform\n"
394         "this conversion simply by saving it again.\n";
395
396     struct termios cf;
397     premsg(&cf);
398     fputs(message, stderr);
399     postmsg(&cf);
400 }
401
402 void console_provide_logctx(void *logctx)
403 {
404     console_logctx = logctx;
405 }
406
407 void logevent(void *frontend, const char *string)
408 {
409     struct termios cf;
410     if ((flags & FLAG_STDERR) && (flags & FLAG_VERBOSE))
411         premsg(&cf);
412     if (console_logctx)
413         log_eventlog(console_logctx, string);
414     if ((flags & FLAG_STDERR) && (flags & FLAG_VERBOSE))
415         postmsg(&cf);
416 }
417
418 /*
419  * Special functions to read and print to the console for password
420  * prompts and the like. Uses /dev/tty or stdin/stderr, in that order
421  * of preference; also sanitises escape sequences out of the text, on
422  * the basis that it might have been sent by a hostile SSH server
423  * doing malicious keyboard-interactive.
424  */
425 static void console_open(FILE **outfp, int *infd)
426 {
427     int fd;
428
429     if ((fd = open("/dev/tty", O_RDWR)) >= 0) {
430         *infd = fd;
431         *outfp = fdopen(*infd, "w");
432     } else {
433         *infd = 0;
434         *outfp = stderr;
435     }
436 }
437 static void console_close(FILE *outfp, int infd)
438 {
439     if (outfp != stderr)
440         fclose(outfp);             /* will automatically close infd too */
441 }
442
443 static void console_prompt_text(FILE *outfp, const char *data, int len)
444 {
445     int i;
446
447     for (i = 0; i < len; i++)
448         if ((data[i] & 0x60) || (data[i] == '\n'))
449             fputc(data[i], outfp);
450     fflush(outfp);
451 }
452
453 int console_get_userpass_input(prompts_t *p, const unsigned char *in,
454                                int inlen)
455 {
456     size_t curr_prompt;
457     FILE *outfp = NULL;
458     int infd;
459
460     /*
461      * Zero all the results, in case we abort half-way through.
462      */
463     {
464         int i;
465         for (i = 0; i < p->n_prompts; i++)
466             prompt_set_result(p->prompts[i], "");
467     }
468
469     if (p->n_prompts && console_batch_mode)
470         return 0;
471
472     console_open(&outfp, &infd);
473
474     /*
475      * Preamble.
476      */
477     /* We only print the `name' caption if we have to... */
478     if (p->name_reqd && p->name) {
479         size_t l = strlen(p->name);
480         console_prompt_text(outfp, p->name, l);
481         if (p->name[l-1] != '\n')
482             console_prompt_text(outfp, "\n", 1);
483     }
484     /* ...but we always print any `instruction'. */
485     if (p->instruction) {
486         size_t l = strlen(p->instruction);
487         console_prompt_text(outfp, p->instruction, l);
488         if (p->instruction[l-1] != '\n')
489             console_prompt_text(outfp, "\n", 1);
490     }
491
492     for (curr_prompt = 0; curr_prompt < p->n_prompts; curr_prompt++) {
493
494         struct termios oldmode, newmode;
495         int len;
496         prompt_t *pr = p->prompts[curr_prompt];
497
498         tcgetattr(infd, &oldmode);
499         newmode = oldmode;
500         newmode.c_lflag |= ISIG | ICANON;
501         if (!pr->echo)
502             newmode.c_lflag &= ~ECHO;
503         else
504             newmode.c_lflag |= ECHO;
505         tcsetattr(infd, TCSANOW, &newmode);
506
507         console_prompt_text(outfp, pr->prompt, strlen(pr->prompt));
508
509         len = 0;
510         while (1) {
511             int ret;
512
513             prompt_ensure_result_size(pr, len * 5 / 4 + 512);
514             ret = read(infd, pr->result + len, pr->resultsize - len - 1);
515             if (ret <= 0) {
516                 len = -1;
517                 break;
518             }
519             len += ret;
520             if (pr->result[len - 1] == '\n') {
521                 len--;
522                 break;
523             }
524         }
525
526         tcsetattr(infd, TCSANOW, &oldmode);
527
528         if (!pr->echo)
529             console_prompt_text(outfp, "\n", 1);
530
531         if (len < 0) {
532             console_close(outfp, infd);
533             return 0;                  /* failure due to read error */
534         }
535
536         pr->result[len] = '\0';
537     }
538
539     console_close(outfp, infd);
540
541     return 1; /* success */
542 }
543
544 void frontend_keypress(void *handle)
545 {
546     /*
547      * This is nothing but a stub, in console code.
548      */
549     return;
550 }
551
552 int is_interactive(void)
553 {
554     return isatty(0);
555 }
556
557 /*
558  * X11-forwarding-related things suitable for console.
559  */
560
561 char *platform_get_x_display(void) {
562     return dupstr(getenv("DISPLAY"));
563 }