1 /***************************************************************************
2  * nmap_tty.cc -- Handles runtime interaction with Nmap, so you can        *
3  * increase verbosity/debugging or obtain a status line upon request.      *
4  *                                                                         *
5  ***********************IMPORTANT NMAP LICENSE TERMS************************
6  *                                                                         *
7  * The Nmap Security Scanner is (C) 1996-2020 Insecure.Com LLC ("The Nmap  *
8  * Project"). Nmap is also a registered trademark of the Nmap Project.     *
9  *                                                                         *
10  * This program is distributed under the terms of the Nmap Public Source   *
11  * License (NPSL). The exact license text applying to a particular Nmap    *
12  * release or source code control revision is contained in the LICENSE     *
13  * file distributed with that version of Nmap or source code control       *
14  * revision. More Nmap copyright/legal information is available from       *
15  * https://nmap.org/book/man-legal.html, and further information on the    *
16  * NPSL license itself can be found at https://nmap.org/npsl. This header  *
17  * summarizes some key points from the Nmap license, but is no substitute  *
18  * for the actual license text.                                            *
19  *                                                                         *
20  * Nmap is generally free for end users to download and use themselves,    *
21  * including commercial use. It is available from https://nmap.org.        *
22  *                                                                         *
23  * The Nmap license generally prohibits companies from using and           *
24  * redistributing Nmap in commercial products, but we sell a special Nmap  *
25  * OEM Edition with a more permissive license and special features for     *
26  * this purpose. See https://nmap.org/oem                                  *
27  *                                                                         *
28  * If you have received a written Nmap license agreement or contract       *
29  * stating terms other than these (such as an Nmap OEM license), you may   *
30  * choose to use and redistribute Nmap under those terms instead.          *
31  *                                                                         *
32  * The official Nmap Windows builds include the Npcap software             *
33  * (https://npcap.org) for packet capture and transmission. It is under    *
34  * separate license terms which forbid redistribution without special      *
35  * permission. So the official Nmap Windows builds may not be              *
36  * redistributed without special permission (such as an Nmap OEM           *
37  * license).                                                               *
38  *                                                                         *
39  * Source is provided to this software because we believe users have a     *
40  * right to know exactly what a program is going to do before they run it. *
41  * This also allows you to audit the software for security holes.          *
42  *                                                                         *
43  * Source code also allows you to port Nmap to new platforms, fix bugs,    *
44  * and add new features.  You are highly encouraged to submit your         *
45  * changes as a Github PR or by email to the dev@nmap.org mailing list     *
46  * for possible incorporation into the main distribution. Unless you       *
47  * specify otherwise, it is understood that you are offering us very       *
48  * broad rights to use your submissions as described in the Nmap Public    *
49  * Source License Contributor Agreement. This is important because we      *
50  * fund the project by selling licenses with various terms, and also       *
51  * because the inability to relicense code has caused devastating          *
52  * problems for other Free Software projects (such as KDE and NASM).       *
53  *                                                                         *
54  * The free version of Nmap is distributed in the hope that it will be     *
55  * useful, but WITHOUT ANY WARRANTY; without even the implied warranty of  *
56  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. Warranties,        *
57  * indemnification and commercial support are all available through the    *
58  * Npcap OEM program--see https://nmap.org/oem.                            *
59  *                                                                         *
60  ***************************************************************************/
61 
62 #ifndef WIN32
63 #include "nmap_config.h"
64 #endif
65 
66 #include "nmap.h"
67 
68 #include <sys/types.h>
69 #if HAVE_SYS_STAT_H
70 #include <sys/stat.h>
71 #endif
72 #if HAVE_FCNTL_H
73 #include <fcntl.h>
74 #endif
75 #if HAVE_TERMIOS_H
76 #include <termios.h>
77 #endif
78 #if HAVE_UNISTD_H
79 #include <unistd.h>
80 #endif
81 #include <stdlib.h>
82 
83 #if TIME_WITH_SYS_TIME
84 # include <sys/time.h>
85 # include <time.h>
86 #else
87 # if HAVE_SYS_TIME_H
88 #  include <sys/time.h>
89 # else
90 #  include <time.h>
91 # endif
92 #endif
93 
94 #include "nmap_tty.h"
95 #include "NmapOps.h"
96 
97 extern NmapOps o;
98 
99 #ifdef WIN32
100 #include <conio.h>
101 
102 // Microsoft's runtime makes this fairly simple. :)
tty_init()103 void tty_init() { return; }
tty_getchar()104 static int tty_getchar() { return _kbhit() ? _getch() : -1; }
tty_done()105 static void tty_done() { return; }
106 
tty_flush(void)107 static void tty_flush(void)
108 {
109         static HANDLE stdinput = GetStdHandle(STD_INPUT_HANDLE);
110 
111         FlushConsoleInputBuffer(stdinput);
112 }
113 
114 #else  //!win32
115 #include <signal.h>
116 #if !defined(O_NONBLOCK) && defined(O_NDELAY)
117 #define O_NONBLOCK			O_NDELAY
118 #endif
119 
120 #ifdef __CYGWIN32__
121 #include <string.h>
122 #include <sys/socket.h>
123 #ifndef __CYGWIN__
124 extern int tcgetattr(int fd, struct termios *termios_p);
125 extern int tcsetattr(int fd, int actions, struct termios *termios_p);
126 #endif
127 #endif
128 
129 static int tty_fd = 0;
130 static struct termios saved_ti;
131 
tty_getchar()132 static int tty_getchar()
133 {
134         int c, numChars;
135 #ifdef __CYGWIN32__
136         fd_set set;
137         struct timeval tv;
138 #endif
139 
140         if (tty_fd && tcgetpgrp(tty_fd) == getpgrp()) {
141 
142         // This is so that when the terminal has been disconnected, it will be
143         // reconnected when possible. If it slows things down, just remove it
144         // tty_init();
145 
146 #ifdef __CYGWIN32__
147                 FD_ZERO(&set); FD_SET(tty_fd, &set);
148                 tv.tv_sec = 0; tv.tv_usec = 0;
149                 if (select(tty_fd + 1, &set, NULL, NULL, &tv) <= 0)
150                         return -1;
151 #endif
152                 c = 0;
153                 numChars = read(tty_fd, &c, 1);
154                 if (numChars > 0) return c;
155         }
156 
157         return -1;
158 }
159 
tty_done()160 static void tty_done()
161 {
162         if (!tty_fd) return;
163 
164         tcsetattr(tty_fd, TCSANOW, &saved_ti);
165 
166         close(tty_fd);
167         tty_fd = 0;
168 }
169 
tty_flush(void)170 static void tty_flush(void)
171 {
172         /* we don't need to test for tty_fd==0 here because
173          * this isn't called unless we succeeded
174          */
175 
176         tcflush(tty_fd, TCIFLUSH);
177 }
178 
install_handler(int signo,void (* handler)(int signo))179 static void install_handler(int signo, void (*handler) (int signo))
180 {
181         struct sigaction sa;
182         sa.sa_handler = handler;
183         sigfillset(&sa.sa_mask); /* block all signals during handler execution */
184         sa.sa_flags = 0;
185         sigaction(signo, &sa, NULL);
186 }
187 
shutdown_clean(int signo)188 static void shutdown_clean(int signo)
189 {
190         sigset_t set;
191 
192 /* We reinstall the default handler and call tty_done */
193         install_handler(signo, SIG_DFL);
194         tty_done();
195 
196 /* Unblock signo and raise it (thus allowing the default handler to occur) */
197         sigemptyset(&set);
198         sigaddset(&set, signo);
199         sigprocmask(SIG_UNBLOCK, &set, NULL);
200         raise(signo); /* This _should_ kill us */
201         _exit(EXIT_FAILURE); /* If it does not */
202 }
203 
install_all_handlers()204 static void install_all_handlers() {
205         install_handler(SIGINT, shutdown_clean);
206         install_handler(SIGTERM, shutdown_clean);
207         install_handler(SIGQUIT, shutdown_clean);
208 }
209 
210 /*
211  * Initializes the terminal for unbuffered non-blocking input. Also
212  * registers tty_done() via atexit().  You need to call this before
213  * you ever call keyWasPressed().
214  */
tty_init()215 void tty_init()
216 {
217         struct termios ti;
218 
219         if(o.noninteractive)
220                 return;
221 
222         install_all_handlers();
223 
224         if (tty_fd)
225                 return;
226 
227         if ((tty_fd = open("/dev/tty", O_RDONLY | O_NONBLOCK)) < 0) return;
228 
229 #ifndef __CYGWIN32__
230         if (tcgetpgrp(tty_fd) != getpgrp()) {
231                 close(tty_fd); return;
232         }
233 #endif
234 
235         tcgetattr(tty_fd, &ti);
236         saved_ti = ti;
237         ti.c_lflag &= ~(ICANON | ECHO);
238         ti.c_cc[VMIN] = 1;
239         ti.c_cc[VTIME] = 0;
240         tcsetattr(tty_fd, TCSANOW, &ti);
241 
242         atexit(tty_done);
243 }
244 
245 #endif  //!win32
246 
247 /* Catches all of the predefined
248    keypresses and interpret them, and it will also tell you if you
249    should print anything. A value of true being returned means a
250    nonstandard key has been pressed and the calling method should
251    print a status message */
keyWasPressed()252 bool keyWasPressed()
253 {
254   /* Where we keep the automatic stats printing schedule. */
255   static struct timeval stats_time = { 0 };
256   int c;
257 
258   if (o.noninteractive)
259     return false;
260 
261   if ((c = tty_getchar()) >= 0) {
262     tty_flush(); /* flush input queue */
263 
264     // printf("You pressed key '%c'!\n", c);
265     if (c == 'v') {
266        if (o.verbose < 10) o.verbose++;
267        log_write(LOG_STDOUT, "Verbosity Increased to %d.\n", o.verbose);
268     } else if (c == 'V') {
269        if (o.verbose > 0) o.verbose--;
270        log_write(LOG_STDOUT, "Verbosity Decreased to %d.\n", o.verbose);
271     } else if (c == 'd') {
272        if (o.debugging < 10) o.debugging++;
273        log_write(LOG_STDOUT, "Debugging Increased to %d.\n", o.debugging);
274     } else if (c == 'D') {
275        if (o.debugging > 0) o.debugging--;
276        log_write(LOG_STDOUT, "Debugging Decreased to %d.\n", o.debugging);
277     } else if (c == 'p') {
278        o.setPacketTrace(true);
279        log_write(LOG_STDOUT, "Packet Tracing enabled.\n");
280     } else if (c == 'P') {
281        o.setPacketTrace(false);
282        log_write(LOG_STDOUT, "Packet Tracing disabled.\n");
283     } else if (c == '?') {
284       log_write(LOG_STDOUT,
285                 "Interactive keyboard commands:\n"
286                 "?               Display this information\n"
287                 "v/V             Increase/decrease verbosity\n"
288                 "d/D             Increase/decrease debugging\n"
289                 "p/P             Enable/disable packet tracing\n"
290                 "anything else   Print status\n"
291                 "More help: https://nmap.org/book/man-runtime-interaction.html\n");
292     } else {
293        printStatusMessage();
294        return true;
295     }
296   }
297 
298   /* Check if we need to print a status update according to the --stats-every
299      option. */
300   if (o.stats_interval != 0.0) {
301     struct timeval now;
302 
303     gettimeofday(&now, NULL);
304     if (stats_time.tv_sec == 0) {
305       /* Initialize the scheduled stats time. */
306       stats_time = *o.getStartTime();
307       TIMEVAL_ADD(stats_time, stats_time, (time_t) (o.stats_interval * 1000000));
308     }
309 
310     if (TIMEVAL_AFTER(now, stats_time)) {
311       /* Advance to the next print time. */
312       TIMEVAL_ADD(stats_time, stats_time, (time_t) (o.stats_interval * 1000000));
313       /* If it's still in the past, catch it up to the present,
314        * plus half a second to avoid double-printing without any progress. */
315       if (TIMEVAL_AFTER(now, stats_time))
316         TIMEVAL_MSEC_ADD(stats_time, now, 500);
317       printStatusMessage();
318       /* Instruct the caller to print status too. */
319       return true;
320     }
321   }
322 
323   return false;
324 }
325