1 /***************************************************************************
2 * nmap.cc -- Currently handles some of Nmap's port scanning features as *
3 * well as the command line user interface. Note that the actual main() *
4 * function is in main.cc *
5 * *
6 ***********************IMPORTANT NMAP LICENSE TERMS************************
7 * *
8 * The Nmap Security Scanner is (C) 1996-2020 Insecure.Com LLC ("The Nmap *
9 * Project"). Nmap is also a registered trademark of the Nmap Project. *
10 * *
11 * This program is distributed under the terms of the Nmap Public Source *
12 * License (NPSL). The exact license text applying to a particular Nmap *
13 * release or source code control revision is contained in the LICENSE *
14 * file distributed with that version of Nmap or source code control *
15 * revision. More Nmap copyright/legal information is available from *
16 * https://nmap.org/book/man-legal.html, and further information on the *
17 * NPSL license itself can be found at https://nmap.org/npsl. This header *
18 * summarizes some key points from the Nmap license, but is no substitute *
19 * for the actual license text. *
20 * *
21 * Nmap is generally free for end users to download and use themselves, *
22 * including commercial use. It is available from https://nmap.org. *
23 * *
24 * The Nmap license generally prohibits companies from using and *
25 * redistributing Nmap in commercial products, but we sell a special Nmap *
26 * OEM Edition with a more permissive license and special features for *
27 * this purpose. See https://nmap.org/oem *
28 * *
29 * If you have received a written Nmap license agreement or contract *
30 * stating terms other than these (such as an Nmap OEM license), you may *
31 * choose to use and redistribute Nmap under those terms instead. *
32 * *
33 * The official Nmap Windows builds include the Npcap software *
34 * (https://npcap.org) for packet capture and transmission. It is under *
35 * separate license terms which forbid redistribution without special *
36 * permission. So the official Nmap Windows builds may not be *
37 * redistributed without special permission (such as an Nmap OEM *
38 * license). *
39 * *
40 * Source is provided to this software because we believe users have a *
41 * right to know exactly what a program is going to do before they run it. *
42 * This also allows you to audit the software for security holes. *
43 * *
44 * Source code also allows you to port Nmap to new platforms, fix bugs, *
45 * and add new features. You are highly encouraged to submit your *
46 * changes as a Github PR or by email to the dev@nmap.org mailing list *
47 * for possible incorporation into the main distribution. Unless you *
48 * specify otherwise, it is understood that you are offering us very *
49 * broad rights to use your submissions as described in the Nmap Public *
50 * Source License Contributor Agreement. This is important because we *
51 * fund the project by selling licenses with various terms, and also *
52 * because the inability to relicense code has caused devastating *
53 * problems for other Free Software projects (such as KDE and NASM). *
54 * *
55 * The free version of Nmap is distributed in the hope that it will be *
56 * useful, but WITHOUT ANY WARRANTY; without even the implied warranty of *
57 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. Warranties, *
58 * indemnification and commercial support are all available through the *
59 * Npcap OEM program--see https://nmap.org/oem. *
60 * *
61 ***************************************************************************/
62
63 /* $Id: nmap.cc 38096 2020-10-09 22:18:58Z dmiller $ */
64
65 #ifdef WIN32
66 #include "winfix.h"
67 /* This name collides in the following include. */
68 #undef PS_NONE
69 #include <shlobj.h>
70 #endif
71
72 #include <getopt.h>
73 #include "nmap.h"
74 #include "osscan.h"
75 #include "scan_engine.h"
76 #include "FPEngine.h"
77 #include "idle_scan.h"
78 #include "NmapOps.h"
79 #include "MACLookup.h"
80 #include "traceroute.h"
81 #include "nmap_tty.h"
82 #include "nmap_ftp.h"
83 #include "services.h"
84 #include "targets.h"
85 #include "tcpip.h"
86 #include "NewTargets.h"
87 #include "Target.h"
88 #include "service_scan.h"
89 #include "charpool.h"
90 #include "nmap_error.h"
91 #include "utils.h"
92 #include "xml.h"
93 #include "scan_lists.h"
94
95 #ifndef NOLUA
96 #include "nse_main.h"
97 #endif
98
99 #ifdef HAVE_SIGNAL
100 #include <signal.h>
101 #endif
102
103 #include <fcntl.h>
104
105 #ifdef HAVE_PWD_H
106 #include <pwd.h>
107 #endif
108
109 #ifndef IPPROTO_SCTP
110 #include "libnetutil/netutil.h"
111 #endif
112
113 #if HAVE_OPENSSL
114 #include <openssl/opensslv.h>
115 #endif
116
117 #if HAVE_LIBSSH2
118 #include <libssh2.h>
119 #endif
120
121 #if HAVE_LIBZ
122 #include <zlib.h>
123 #endif
124
125 /* To get the version number only. */
126 #ifdef WIN32
127 #include "libdnet-stripped/include/dnet_winconfig.h"
128 #else
129 #include "libdnet-stripped/include/config.h"
130 #endif
131 #define DNET_VERSION VERSION
132
133 #ifdef LINUX
134 /* Check for Windows Subsystem for Linux (WSL) */
135 #include <sys/utsname.h>
136 #endif
137
138 #include <string>
139 #include <sstream>
140 #include <vector>
141
142 /* global options */
143 extern char *optarg;
144 extern int optind;
145 extern NmapOps o; /* option structure */
146
147 static void display_nmap_version();
148
149 /* A mechanism to save argv[0] for code that requires that. */
150 static const char *program_name = NULL;
151
set_program_name(const char * name)152 void set_program_name(const char *name) {
153 program_name = name;
154 }
155
get_program_name(void)156 static const char *get_program_name(void) {
157 return program_name;
158 }
159
160 /* parse the --scanflags argument. It can be a number >=0 or a string consisting of TCP flag names like "URGPSHFIN". Returns -1 if the argument is invalid. */
parse_scanflags(char * arg)161 static int parse_scanflags(char *arg) {
162 int flagval = 0;
163 char *end = NULL;
164
165 if (isdigit((int) (unsigned char) arg[0])) {
166 flagval = strtol(arg, &end, 0);
167 if (*end || flagval < 0 || flagval > 255)
168 return -1;
169 } else {
170 if (strcasestr(arg, "FIN"))
171 flagval |= TH_FIN;
172 if (strcasestr(arg, "SYN"))
173 flagval |= TH_SYN;
174 if (strcasestr(arg, "RST") || strcasestr(arg, "RESET"))
175 flagval |= TH_RST;
176 if (strcasestr(arg, "PSH") || strcasestr(arg, "PUSH"))
177 flagval |= TH_PUSH;
178 if (strcasestr(arg, "ACK"))
179 flagval |= TH_ACK;
180 if (strcasestr(arg, "URG"))
181 flagval |= TH_URG;
182 if (strcasestr(arg, "ECE"))
183 flagval |= TH_ECE;
184 if (strcasestr(arg, "CWR"))
185 flagval |= TH_CWR;
186 if (strcasestr(arg, "ALL"))
187 flagval = 255;
188 if (strcasestr(arg, "NONE"))
189 flagval = 0;
190 }
191 return flagval;
192 }
193
printusage()194 static void printusage() {
195
196 printf("%s %s ( %s )\n"
197 "Usage: nmap [Scan Type(s)] [Options] {target specification}\n"
198 "TARGET SPECIFICATION:\n"
199 " Can pass hostnames, IP addresses, networks, etc.\n"
200 " Ex: scanme.nmap.org, microsoft.com/24, 192.168.0.1; 10.0.0-255.1-254\n"
201 " -iL <inputfilename>: Input from list of hosts/networks\n"
202 " -iR <num hosts>: Choose random targets\n"
203 " --exclude <host1[,host2][,host3],...>: Exclude hosts/networks\n"
204 " --excludefile <exclude_file>: Exclude list from file\n"
205 "HOST DISCOVERY:\n"
206 " -sL: List Scan - simply list targets to scan\n"
207 " -sn: Ping Scan - disable port scan\n"
208 " -Pn: Treat all hosts as online -- skip host discovery\n"
209 " -PS/PA/PU/PY[portlist]: TCP SYN/ACK, UDP or SCTP discovery to given ports\n"
210 " -PE/PP/PM: ICMP echo, timestamp, and netmask request discovery probes\n"
211 " -PO[protocol list]: IP Protocol Ping\n"
212 " -n/-R: Never do DNS resolution/Always resolve [default: sometimes]\n"
213 " --dns-servers <serv1[,serv2],...>: Specify custom DNS servers\n"
214 " --system-dns: Use OS's DNS resolver\n"
215 " --traceroute: Trace hop path to each host\n"
216 "SCAN TECHNIQUES:\n"
217 " -sS/sT/sA/sW/sM: TCP SYN/Connect()/ACK/Window/Maimon scans\n"
218 " -sU: UDP Scan\n"
219 " -sN/sF/sX: TCP Null, FIN, and Xmas scans\n"
220 " --scanflags <flags>: Customize TCP scan flags\n"
221 " -sI <zombie host[:probeport]>: Idle scan\n"
222 " -sY/sZ: SCTP INIT/COOKIE-ECHO scans\n"
223 " -sO: IP protocol scan\n"
224 " -b <FTP relay host>: FTP bounce scan\n"
225 "PORT SPECIFICATION AND SCAN ORDER:\n"
226 " -p <port ranges>: Only scan specified ports\n"
227 " Ex: -p22; -p1-65535; -p U:53,111,137,T:21-25,80,139,8080,S:9\n"
228 " --exclude-ports <port ranges>: Exclude the specified ports from scanning\n"
229 " -F: Fast mode - Scan fewer ports than the default scan\n"
230 " -r: Scan ports consecutively - don't randomize\n"
231 " --top-ports <number>: Scan <number> most common ports\n"
232 " --port-ratio <ratio>: Scan ports more common than <ratio>\n"
233 "SERVICE/VERSION DETECTION:\n"
234 " -sV: Probe open ports to determine service/version info\n"
235 " --version-intensity <level>: Set from 0 (light) to 9 (try all probes)\n"
236 " --version-light: Limit to most likely probes (intensity 2)\n"
237 " --version-all: Try every single probe (intensity 9)\n"
238 " --version-trace: Show detailed version scan activity (for debugging)\n"
239 #ifndef NOLUA
240 "SCRIPT SCAN:\n"
241 " -sC: equivalent to --script=default\n"
242 " --script=<Lua scripts>: <Lua scripts> is a comma separated list of\n"
243 " directories, script-files or script-categories\n"
244 " --script-args=<n1=v1,[n2=v2,...]>: provide arguments to scripts\n"
245 " --script-args-file=filename: provide NSE script args in a file\n"
246 " --script-trace: Show all data sent and received\n"
247 " --script-updatedb: Update the script database.\n"
248 " --script-help=<Lua scripts>: Show help about scripts.\n"
249 " <Lua scripts> is a comma-separated list of script-files or\n"
250 " script-categories.\n"
251 #endif
252 "OS DETECTION:\n"
253 " -O: Enable OS detection\n"
254 " --osscan-limit: Limit OS detection to promising targets\n"
255 " --osscan-guess: Guess OS more aggressively\n"
256 "TIMING AND PERFORMANCE:\n"
257 " Options which take <time> are in seconds, or append 'ms' (milliseconds),\n"
258 " 's' (seconds), 'm' (minutes), or 'h' (hours) to the value (e.g. 30m).\n"
259 " -T<0-5>: Set timing template (higher is faster)\n"
260 " --min-hostgroup/max-hostgroup <size>: Parallel host scan group sizes\n"
261 " --min-parallelism/max-parallelism <numprobes>: Probe parallelization\n"
262 " --min-rtt-timeout/max-rtt-timeout/initial-rtt-timeout <time>: Specifies\n"
263 " probe round trip time.\n"
264 " --max-retries <tries>: Caps number of port scan probe retransmissions.\n"
265 " --host-timeout <time>: Give up on target after this long\n"
266 " --scan-delay/--max-scan-delay <time>: Adjust delay between probes\n"
267 " --min-rate <number>: Send packets no slower than <number> per second\n"
268 " --max-rate <number>: Send packets no faster than <number> per second\n"
269 "FIREWALL/IDS EVASION AND SPOOFING:\n"
270 " -f; --mtu <val>: fragment packets (optionally w/given MTU)\n"
271 " -D <decoy1,decoy2[,ME],...>: Cloak a scan with decoys\n"
272 " -S <IP_Address>: Spoof source address\n"
273 " -e <iface>: Use specified interface\n"
274 " -g/--source-port <portnum>: Use given port number\n"
275 " --proxies <url1,[url2],...>: Relay connections through HTTP/SOCKS4 proxies\n"
276 " --data <hex string>: Append a custom payload to sent packets\n"
277 " --data-string <string>: Append a custom ASCII string to sent packets\n"
278 " --data-length <num>: Append random data to sent packets\n"
279 " --ip-options <options>: Send packets with specified ip options\n"
280 " --ttl <val>: Set IP time-to-live field\n"
281 " --spoof-mac <mac address/prefix/vendor name>: Spoof your MAC address\n"
282 " --badsum: Send packets with a bogus TCP/UDP/SCTP checksum\n"
283 "OUTPUT:\n"
284 " -oN/-oX/-oS/-oG <file>: Output scan in normal, XML, s|<rIpt kIddi3,\n"
285 " and Grepable format, respectively, to the given filename.\n"
286 " -oA <basename>: Output in the three major formats at once\n"
287 " -v: Increase verbosity level (use -vv or more for greater effect)\n"
288 " -d: Increase debugging level (use -dd or more for greater effect)\n"
289 " --reason: Display the reason a port is in a particular state\n"
290 " --open: Only show open (or possibly open) ports\n"
291 " --packet-trace: Show all packets sent and received\n"
292 " --iflist: Print host interfaces and routes (for debugging)\n"
293 " --append-output: Append to rather than clobber specified output files\n"
294 " --resume <filename>: Resume an aborted scan\n"
295 " --stylesheet <path/URL>: XSL stylesheet to transform XML output to HTML\n"
296 " --webxml: Reference stylesheet from Nmap.Org for more portable XML\n"
297 " --no-stylesheet: Prevent associating of XSL stylesheet w/XML output\n"
298 "MISC:\n"
299 " -6: Enable IPv6 scanning\n"
300 " -A: Enable OS detection, version detection, script scanning, and traceroute\n"
301 " --datadir <dirname>: Specify custom Nmap data file location\n"
302 " --send-eth/--send-ip: Send using raw ethernet frames or IP packets\n"
303 " --privileged: Assume that the user is fully privileged\n"
304 " --unprivileged: Assume the user lacks raw socket privileges\n"
305 " -V: Print version number\n"
306 " -h: Print this help summary page.\n"
307 "EXAMPLES:\n"
308 " nmap -v -A scanme.nmap.org\n"
309 " nmap -v -sn 192.168.0.0/16 10.0.0.0/8\n"
310 " nmap -v -iR 10000 -Pn -p 80\n"
311 "SEE THE MAN PAGE (https://nmap.org/book/man.html) FOR MORE OPTIONS AND EXAMPLES\n", NMAP_NAME, NMAP_VERSION, NMAP_URL);
312 }
313
314 #ifdef WIN32
check_setugid(void)315 static void check_setugid(void) {
316 }
317 #else
318 /* Show a warning when running setuid or setgid, as this allows code execution
319 (for example NSE scripts) as the owner/group. */
check_setugid(void)320 static void check_setugid(void) {
321 if (getuid() != geteuid())
322 error("WARNING: Running Nmap setuid, as you are doing, is a major security risk.\n");
323 if (getgid() != getegid())
324 error("WARNING: Running Nmap setgid, as you are doing, is a major security risk.\n");
325 }
326 #endif
327
insert_port_into_merge_list(unsigned short * mlist,int * merged_port_count,unsigned short p)328 static void insert_port_into_merge_list(unsigned short *mlist,
329 int *merged_port_count,
330 unsigned short p) {
331 int i;
332 // make sure the port isn't already in the list
333 for (i = 0; i < *merged_port_count; i++) {
334 if (mlist[i] == p) {
335 return;
336 }
337 }
338 mlist[*merged_port_count] = p;
339 (*merged_port_count)++;
340 }
341
merge_port_lists(unsigned short * port_list1,int count1,unsigned short * port_list2,int count2,int * merged_port_count)342 static unsigned short *merge_port_lists(unsigned short *port_list1, int count1,
343 unsigned short *port_list2, int count2,
344 int *merged_port_count) {
345 int i;
346 unsigned short *merged_port_list = NULL;
347
348 *merged_port_count = 0;
349
350 merged_port_list =
351 (unsigned short *) safe_zalloc((count1 + count2) * sizeof(unsigned short));
352
353 for (i = 0; i < count1; i++) {
354 insert_port_into_merge_list(merged_port_list,
355 merged_port_count,
356 port_list1[i]);
357 }
358 for (i = 0; i < count2; i++) {
359 insert_port_into_merge_list(merged_port_list,
360 merged_port_count,
361 port_list2[i]);
362 }
363
364 // if there were duplicate ports then we can save some memory
365 if (*merged_port_count < (count1 + count2)) {
366 merged_port_list = (unsigned short*)
367 safe_realloc(merged_port_list,
368 (*merged_port_count) * sizeof(unsigned short));
369 }
370
371 return merged_port_list;
372 }
373
validate_scan_lists(scan_lists & vports,NmapOps & vo)374 void validate_scan_lists(scan_lists &vports, NmapOps &vo) {
375 if (vo.pingtype == PINGTYPE_UNKNOWN) {
376 if (vo.isr00t) {
377 if (vo.pf() == PF_INET) {
378 vo.pingtype = DEFAULT_IPV4_PING_TYPES;
379 } else {
380 vo.pingtype = DEFAULT_IPV6_PING_TYPES;
381 }
382 getpts_simple(DEFAULT_PING_ACK_PORT_SPEC, SCAN_TCP_PORT,
383 &vports.ack_ping_ports, &vports.ack_ping_count);
384 getpts_simple(DEFAULT_PING_SYN_PORT_SPEC, SCAN_TCP_PORT,
385 &vports.syn_ping_ports, &vports.syn_ping_count);
386 } else {
387 vo.pingtype = PINGTYPE_TCP; // if nonr00t
388 getpts_simple(DEFAULT_PING_CONNECT_PORT_SPEC, SCAN_TCP_PORT,
389 &vports.syn_ping_ports, &vports.syn_ping_count);
390 }
391 }
392
393 if ((vo.pingtype & PINGTYPE_TCP) && (!vo.isr00t)) {
394 // We will have to do a connect() style ping
395 // Pretend we wanted SYN probes all along.
396 if (vports.ack_ping_count > 0) {
397 // Combine the ACK and SYN ping port lists since they both reduce to
398 // SYN probes in this case
399 unsigned short *merged_port_list;
400 int merged_port_count;
401
402 merged_port_list = merge_port_lists(
403 vports.syn_ping_ports, vports.syn_ping_count,
404 vports.ack_ping_ports, vports.ack_ping_count,
405 &merged_port_count);
406
407 // clean up a bit
408 free(vports.syn_ping_ports);
409 free(vports.ack_ping_ports);
410
411 vports.syn_ping_count = merged_port_count;
412 vports.syn_ping_ports = merged_port_list;
413 vports.ack_ping_count = 0;
414 vports.ack_ping_ports = NULL;
415 }
416 vo.pingtype &= ~PINGTYPE_TCP_USE_ACK;
417 vo.pingtype |= PINGTYPE_TCP_USE_SYN;
418 }
419
420 if (!vo.isr00t) {
421 if (vo.pingtype & (PINGTYPE_ICMP_PING | PINGTYPE_ICMP_MASK | PINGTYPE_ICMP_TS)) {
422 error("Warning: You are not root -- using TCP pingscan rather than ICMP");
423 vo.pingtype = PINGTYPE_TCP;
424 if (vports.syn_ping_count == 0) {
425 getpts_simple(DEFAULT_TCP_PROBE_PORT_SPEC, SCAN_TCP_PORT, &vports.syn_ping_ports, &vports.syn_ping_count);
426 assert(vports.syn_ping_count > 0);
427 }
428 }
429 }
430 }
431
432 struct ftpinfo ftp = get_default_ftpinfo();
433
434 /* A list of targets to be displayed by the --route-dst debugging option. */
435 static std::vector<std::string> route_dst_hosts;
436
437 struct scan_lists ports = { 0 };
438
439 /* This struct is used is a temporary storage place that holds options that
440 can't be correctly parsed and interpreted before the entire command line has
441 been read. Examples are -6 and -S. Trying to set the source address without
442 knowing the address family first could result in a failure if you pass an
443 IPv6 address and the address family is still IPv4. */
444 static struct delayed_options {
445 public:
delayed_optionsdelayed_options446 delayed_options() {
447 this->pre_max_parallelism = -1;
448 this->pre_scan_delay = -1;
449 this->pre_max_scan_delay = -1;
450 this->pre_init_rtt_timeout = -1;
451 this->pre_min_rtt_timeout = -1;
452 this->pre_max_rtt_timeout = -1;
453 this->pre_max_retries = -1;
454 this->pre_host_timeout = -1;
455 #ifndef NOLUA
456 this->pre_scripttimeout = -1;
457 #endif
458 this->iflist = false;
459 this->advanced = false;
460 this->af = AF_UNSPEC;
461 this->decoys = false;
462 this->raw_scan_options = false;
463 }
464
465 // Pre-specified timing parameters.
466 // These are stored here during the parsing of the arguments so that we can
467 // set the defaults specified by any timing template options (-T2, etc) BEFORE
468 // any of these. In other words, these always take precedence over the templates.
469 int pre_max_parallelism, pre_scan_delay, pre_max_scan_delay;
470 int pre_init_rtt_timeout, pre_min_rtt_timeout, pre_max_rtt_timeout;
471 int pre_max_retries;
472 long pre_host_timeout;
473 #ifndef NOLUA
474 double pre_scripttimeout;
475 #endif
476 char *machinefilename, *kiddiefilename, *normalfilename, *xmlfilename;
477 bool iflist, decoys, advanced, raw_scan_options;
478 char *exclude_spec, *exclude_file;
479 char *spoofSource, *decoy_arguments;
480 const char *spoofmac;
481 int af;
482 std::vector<std::string> verbose_out;
483
warn_deprecateddelayed_options484 void warn_deprecated (const char *given, const char *replacement) {
485 std::ostringstream os;
486 os << "Warning: The -" << given << " option is deprecated. Please use -" << replacement;
487 this->verbose_out.push_back(os.str());
488 }
489
490 } delayed_options;
491
492 struct tm local_time;
493
test_file_name(const char * filename,const char * option)494 static void test_file_name(const char *filename, const char *option) {
495 if (filename[0] == '-' && filename[1] != '\0') {
496 fatal("Output filename begins with '-'. Try '-%s ./%s' if you really want it to be named as such.", option, filename);
497 } else if (strcmp(option, "o") == 0 && strchr("NAXGS", filename[0])) {
498 fatal("You are using a deprecated option in a dangerous way. Did you mean: -o%c %s", filename[0], filename + 1);
499 } else if (filename[0] == '-' && strcmp(option,"oA") == 0) {
500 fatal("Cannot display multiple output types to stdout.");
501 }
502 }
503
parse_options(int argc,char ** argv)504 void parse_options(int argc, char **argv) {
505 char *p;
506 int arg;
507 long l;
508 double d;
509 char *endptr = NULL;
510 char errstr[256];
511 int option_index;
512 #ifdef WORDS_BIGENDIAN
513 int k[]={2037345391,1935892846,0,1279608146,1331241034,1162758985,1314070817,554303488,1869291630,1768383852};
514 #else
515 int k[]={1869377401,1851876211,0,1380271436,1243633999,1229672005,555832142,2593,1847618415,1818584937};
516 #endif
517
518 struct option long_options[] = {
519 {"version", no_argument, 0, 'V'},
520 {"verbose", no_argument, 0, 'v'},
521 {"datadir", required_argument, 0, 0},
522 {"servicedb", required_argument, 0, 0},
523 {"versiondb", required_argument, 0, 0},
524 {"debug", optional_argument, 0, 'd'},
525 {"help", no_argument, 0, 'h'},
526 {"iflist", no_argument, 0, 0},
527 {"release-memory", no_argument, 0, 0},
528 {"nogcc", no_argument, 0, 0},
529 {"max-os-tries", required_argument, 0, 0},
530 {"max-parallelism", required_argument, 0, 'M'},
531 {"min-parallelism", required_argument, 0, 0},
532 {"timing", required_argument, 0, 'T'},
533 {"max-rtt-timeout", required_argument, 0, 0},
534 {"min-rtt-timeout", required_argument, 0, 0},
535 {"initial-rtt-timeout", required_argument, 0, 0},
536 {"excludefile", required_argument, 0, 0},
537 {"exclude", required_argument, 0, 0},
538 {"max-hostgroup", required_argument, 0, 0},
539 {"min-hostgroup", required_argument, 0, 0},
540 {"open", no_argument, 0, 0},
541 {"scanflags", required_argument, 0, 0},
542 {"defeat-rst-ratelimit", no_argument, 0, 0},
543 {"defeat-icmp-ratelimit", no_argument, 0, 0},
544 {"host-timeout", required_argument, 0, 0},
545 {"scan-delay", required_argument, 0, 0},
546 {"max-scan-delay", required_argument, 0, 0},
547 {"max-retries", required_argument, 0, 0},
548 {"oA", required_argument, 0, 0},
549 {"oN", required_argument, 0, 0},
550 {"oM", required_argument, 0, 0},
551 {"oG", required_argument, 0, 0},
552 {"oS", required_argument, 0, 0},
553 {"oH", required_argument, 0, 0},
554 {"oX", required_argument, 0, 0},
555 {"iL", required_argument, 0, 0},
556 {"iR", required_argument, 0, 0},
557 {"sI", required_argument, 0, 0},
558 {"source-port", required_argument, 0, 'g'},
559 {"randomize-hosts", no_argument, 0, 0},
560 {"nsock-engine", required_argument, 0, 0},
561 {"proxies", required_argument, 0, 0},
562 {"proxy", required_argument, 0, 0},
563 {"discovery-ignore-rst", no_argument, 0, 0},
564 {"osscan-limit", no_argument, 0, 0}, /* skip OSScan if no open ports */
565 {"osscan-guess", no_argument, 0, 0}, /* More guessing flexibility */
566 {"fuzzy", no_argument, 0, 0}, /* Alias for osscan_guess */
567 {"packet-trace", no_argument, 0, 0}, /* Display all packets sent/rcv */
568 {"version-trace", no_argument, 0, 0}, /* Display -sV related activity */
569 {"data", required_argument, 0, 0},
570 {"data-string", required_argument, 0, 0},
571 {"data-length", required_argument, 0, 0},
572 {"send-eth", no_argument, 0, 0},
573 {"send-ip", no_argument, 0, 0},
574 {"stylesheet", required_argument, 0, 0},
575 {"no-stylesheet", no_argument, 0, 0},
576 {"webxml", no_argument, 0, 0},
577 {"rH", no_argument, 0, 0},
578 {"vv", no_argument, 0, 0},
579 {"ff", no_argument, 0, 0},
580 {"privileged", no_argument, 0, 0},
581 {"unprivileged", no_argument, 0, 0},
582 {"mtu", required_argument, 0, 0},
583 {"append-output", no_argument, 0, 0},
584 {"noninteractive", no_argument, 0, 0},
585 {"spoof-mac", required_argument, 0, 0},
586 {"thc", no_argument, 0, 0},
587 {"badsum", no_argument, 0, 0},
588 {"ttl", required_argument, 0, 0}, /* Time to live */
589 {"traceroute", no_argument, 0, 0},
590 {"reason", no_argument, 0, 0},
591 {"allports", no_argument, 0, 0},
592 {"version-intensity", required_argument, 0, 0},
593 {"version-light", no_argument, 0, 0},
594 {"version-all", no_argument, 0, 0},
595 {"system-dns", no_argument, 0, 0},
596 {"resolve-all", no_argument, 0, 0},
597 {"log-errors", no_argument, 0, 0},
598 {"deprecated-xml-osclass", no_argument, 0, 0},
599 {(char*)k, no_argument, 0, 0},
600 {"dns-servers", required_argument, 0, 0},
601 {"port-ratio", required_argument, 0, 0},
602 {"exclude-ports", required_argument, 0, 0},
603 {"top-ports", required_argument, 0, 0},
604 #ifndef NOLUA
605 {"script", required_argument, 0, 0},
606 {"script-trace", no_argument, 0, 0},
607 {"script-updatedb", no_argument, 0, 0},
608 {"script-args", required_argument, 0, 0},
609 {"script-args-file", required_argument, 0, 0},
610 {"script-help", required_argument, 0, 0},
611 {"script-timeout", required_argument, 0, 0},
612 #endif
613 {"ip-options", required_argument, 0, 0},
614 {"min-rate", required_argument, 0, 0},
615 {"max-rate", required_argument, 0, 0},
616 {"adler32", no_argument, 0, 0},
617 {"stats-every", required_argument, 0, 0},
618 {"disable-arp-ping", no_argument, 0, 0},
619 {"route-dst", required_argument, 0, 0},
620 {"resume", required_argument, 0, 0},
621 {0, 0, 0, 0}
622 };
623
624 /* OK, lets parse these args! */
625 optind = 1; /* so it can be called multiple times */
626 while ((arg = getopt_long_only(argc, argv, "46Ab:D:d::e:Ffg:hIi:M:m:nO::o:P::p:qRrS:s::T:Vv::", long_options, &option_index)) != EOF) {
627 switch (arg) {
628 case 0:
629 #ifndef NOLUA
630 if (strcmp(long_options[option_index].name, "script") == 0) {
631 o.script = true;
632 o.chooseScripts(optarg);
633 } else if (strcmp(long_options[option_index].name, "script-args") == 0) {
634 o.scriptargs = strdup(optarg);
635 } else if (strcmp(long_options[option_index].name, "script-args-file") == 0) {
636 o.scriptargsfile = strdup(optarg);
637 } else if (strcmp(long_options[option_index].name, "script-trace") == 0) {
638 o.scripttrace = true;
639 } else if (strcmp(long_options[option_index].name, "script-updatedb") == 0) {
640 o.scriptupdatedb = true;
641 } else if (strcmp(long_options[option_index].name, "script-help") == 0) {
642 o.scripthelp = true;
643 o.chooseScripts(optarg);
644 } else if (strcmp(long_options[option_index].name, "script-timeout") == 0) {
645 d = tval2secs(optarg);
646 if (d < 0 || d > LONG_MAX)
647 fatal("Bogus --script-timeout argument specified");
648 delayed_options.pre_scripttimeout = d;
649 } else
650 #endif
651 if (strcmp(long_options[option_index].name, "max-os-tries") == 0) {
652 l = atoi(optarg);
653 if (l < 1 || l > 50)
654 fatal("Bogus --max-os-tries argument specified, must be between 1 and 50 (inclusive)");
655 o.setMaxOSTries(l);
656 } else if (strcmp(long_options[option_index].name, "max-rtt-timeout") == 0) {
657 l = tval2msecs(optarg);
658 if (l < 5)
659 fatal("Bogus --max-rtt-timeout argument specified, must be at least 5ms");
660 if (l >= 50 * 1000 && tval_unit(optarg) == NULL)
661 fatal("Since April 2010, the default unit for --max-rtt-timeout is seconds, so your time of \"%s\" is %g seconds. Use \"%sms\" for %g milliseconds.", optarg, l / 1000.0, optarg, l / 1000.0);
662 if (l < 20)
663 error("WARNING: You specified a round-trip time timeout (%ld ms) that is EXTRAORDINARILY SMALL. Accuracy may suffer.", l);
664 delayed_options.pre_max_rtt_timeout = l;
665 } else if (strcmp(long_options[option_index].name, "min-rtt-timeout") == 0) {
666 l = tval2msecs(optarg);
667 if (l < 0)
668 fatal("Bogus --min-rtt-timeout argument specified");
669 if (l >= 50 * 1000 && tval_unit(optarg) == NULL)
670 fatal("Since April 2010, the default unit for --min-rtt-timeout is seconds, so your time of \"%s\" is %g seconds. Use \"%sms\" for %g milliseconds.", optarg, l / 1000.0, optarg, l / 1000.0);
671 delayed_options.pre_min_rtt_timeout = l;
672 } else if (strcmp(long_options[option_index].name, "initial-rtt-timeout") == 0) {
673 l = tval2msecs(optarg);
674 if (l <= 0)
675 fatal("Bogus --initial-rtt-timeout argument specified. Must be positive");
676 if (l >= 50 * 1000 && tval_unit(optarg) == NULL)
677 fatal("Since April 2010, the default unit for --initial-rtt-timeout is seconds, so your time of \"%s\" is %g seconds. Use \"%sms\" for %g milliseconds.", optarg, l / 1000.0, optarg, l / 1000.0);
678 delayed_options.pre_init_rtt_timeout = l;
679 } else if (strcmp(long_options[option_index].name, "excludefile") == 0) {
680 delayed_options.exclude_file = strdup(optarg);
681 } else if (strcmp(long_options[option_index].name, "exclude") == 0) {
682 delayed_options.exclude_spec = strdup(optarg);
683 } else if (strcmp(long_options[option_index].name, "max-hostgroup") == 0) {
684 o.setMaxHostGroupSz(atoi(optarg));
685 } else if (strcmp(long_options[option_index].name, "min-hostgroup") == 0) {
686 o.setMinHostGroupSz(atoi(optarg));
687 if (atoi(optarg) > 100)
688 error("Warning: You specified a highly aggressive --min-hostgroup.");
689 } else if (strcmp(long_options[option_index].name, "open") == 0) {
690 o.setOpenOnly(true);
691 // If they only want open, don't spend extra time (potentially) distinguishing closed from filtered.
692 o.defeat_rst_ratelimit = true;
693 } else if (strcmp(long_options[option_index].name, "scanflags") == 0) {
694 delayed_options.raw_scan_options = true;
695 o.scanflags = parse_scanflags(optarg);
696 if (o.scanflags < 0) {
697 fatal("--scanflags option must be a number between 0 and 255 (inclusive) or a string like \"URGPSHFIN\".");
698 }
699 } else if (strcmp(long_options[option_index].name, "iflist") == 0) {
700 delayed_options.iflist = true;
701 } else if (strcmp(long_options[option_index].name, "nogcc") == 0) {
702 o.nogcc = true;
703 } else if (strcmp(long_options[option_index].name, "release-memory") == 0) {
704 o.release_memory = true;
705 } else if (strcmp(long_options[option_index].name, "min-parallelism") == 0) {
706 o.min_parallelism = atoi(optarg);
707 if (o.min_parallelism < 1)
708 fatal("Argument to --min-parallelism must be at least 1!");
709 if (o.min_parallelism > 100) {
710 error("Warning: Your --min-parallelism option is pretty high! This can hurt reliability.");
711 }
712 } else if (strcmp(long_options[option_index].name, "host-timeout") == 0) {
713 l = tval2msecs(optarg);
714 if (l <= 0)
715 fatal("Bogus --host-timeout argument specified");
716 if (l >= 10000 * 1000 && tval_unit(optarg) == NULL)
717 fatal("Since April 2010, the default unit for --host-timeout is seconds, so your time of \"%s\" is %.1f hours. If this is what you want, use \"%ss\".", optarg, l / 1000.0 / 60 / 60, optarg);
718 delayed_options.pre_host_timeout = l;
719 } else if (strcmp(long_options[option_index].name, "ttl") == 0) {
720 delayed_options.raw_scan_options = true;
721 o.ttl = atoi(optarg);
722 if (o.ttl < 0 || o.ttl > 255) {
723 fatal("ttl option must be a number between 0 and 255 (inclusive)");
724 }
725 } else if (strcmp(long_options[option_index].name, "datadir") == 0) {
726 o.datadir = strdup(optarg);
727 } else if (strcmp(long_options[option_index].name, "servicedb") == 0) {
728 o.requested_data_files["nmap-services"] = optarg;
729 o.fastscan = true;
730 } else if (strcmp(long_options[option_index].name, "versiondb") == 0) {
731 o.requested_data_files["nmap-service-probes"] = optarg;
732 } else if (strcmp(long_options[option_index].name, "append-output") == 0) {
733 o.append_output = true;
734 } else if (strcmp(long_options[option_index].name, "noninteractive") == 0) {
735 o.noninteractive = true;
736 } else if (strcmp(long_options[option_index].name, "spoof-mac") == 0) {
737 /* I need to deal with this later, once I'm sure that I have output
738 files set up, --datadir, etc. */
739 delayed_options.spoofmac = optarg;
740 delayed_options.raw_scan_options = true;
741 } else if (strcmp(long_options[option_index].name, "allports") == 0) {
742 o.override_excludeports = true;
743 } else if (strcmp(long_options[option_index].name, "version-intensity") == 0) {
744 o.version_intensity = atoi(optarg);
745 if (o.version_intensity < 0 || o.version_intensity > 9)
746 fatal("version-intensity must be between 0 and 9");
747 } else if (strcmp(long_options[option_index].name, "version-light") == 0) {
748 o.version_intensity = 2;
749 } else if (strcmp(long_options[option_index].name, "version-all") == 0) {
750 o.version_intensity = 9;
751 } else if (strcmp(long_options[option_index].name, "scan-delay") == 0) {
752 l = tval2msecs(optarg);
753 if (l < 0)
754 fatal("Bogus --scan-delay argument specified.");
755 if (l >= 100 * 1000 && tval_unit(optarg) == NULL)
756 fatal("Since April 2010, the default unit for --scan-delay is seconds, so your time of \"%s\" is %.1f minutes. Use \"%sms\" for %g milliseconds.", optarg, l / 1000.0 / 60, optarg, l / 1000.0);
757 delayed_options.pre_scan_delay = l;
758 } else if (strcmp(long_options[option_index].name, "defeat-rst-ratelimit") == 0) {
759 o.defeat_rst_ratelimit = true;
760 } else if (strcmp(long_options[option_index].name, "defeat-icmp-ratelimit") == 0) {
761 o.defeat_icmp_ratelimit = true;
762 } else if (strcmp(long_options[option_index].name, "max-scan-delay") == 0) {
763 l = tval2msecs(optarg);
764 if (l < 0)
765 fatal("Bogus --max-scan-delay argument specified.");
766 if (l >= 100 * 1000 && tval_unit(optarg) == NULL)
767 fatal("Since April 2010, the default unit for --max-scan-delay is seconds, so your time of \"%s\" is %.1f minutes. If this is what you want, use \"%ss\".", optarg, l / 1000.0 / 60, optarg);
768 delayed_options.pre_max_scan_delay = l;
769 } else if (strcmp(long_options[option_index].name, "max-retries") == 0) {
770 delayed_options.pre_max_retries = atoi(optarg);
771 if (delayed_options.pre_max_retries < 0)
772 fatal("max-retries must be positive");
773 } else if (strcmp(long_options[option_index].name, "randomize-hosts") == 0
774 || strcmp(long_options[option_index].name, "rH") == 0) {
775 o.randomize_hosts = true;
776 o.ping_group_sz = PING_GROUP_SZ * 4;
777 } else if (strcmp(long_options[option_index].name, "nsock-engine") == 0) {
778 if (nsock_set_default_engine(optarg) < 0)
779 fatal("Unknown or non-available engine: %s", optarg);
780 } else if ((strcmp(long_options[option_index].name, "proxies") == 0) || (strcmp(long_options[option_index].name, "proxy") == 0)) {
781 if (nsock_proxychain_new(optarg, &o.proxy_chain, NULL) < 0)
782 fatal("Invalid proxy chain specification");
783 } else if (strcmp(long_options[option_index].name, "discovery-ignore-rst") == 0) {
784 o.discovery_ignore_rst = true;
785 } else if (strcmp(long_options[option_index].name, "osscan-limit") == 0) {
786 o.osscan_limit = true;
787 } else if (strcmp(long_options[option_index].name, "osscan-guess") == 0
788 || strcmp(long_options[option_index].name, "fuzzy") == 0) {
789 o.osscan_guess = true;
790 } else if (strcmp(long_options[option_index].name, "packet-trace") == 0) {
791 o.setPacketTrace(true);
792 #ifndef NOLUA
793 o.scripttrace = true;
794 #endif
795 } else if (strcmp(long_options[option_index].name, "version-trace") == 0) {
796 o.setVersionTrace(true);
797 o.debugging++;
798 } else if (strcmp(long_options[option_index].name, "data") == 0) {
799 delayed_options.raw_scan_options = true;
800 if (o.extra_payload)
801 fatal("Can't use the --data option(s) multiple times, or together.");
802 u8 *tempbuff=NULL;
803 size_t len=0;
804 if( (tempbuff=parse_hex_string(optarg, &len))==NULL)
805 fatal("Invalid hex string specified");
806 else {
807 o.extra_payload_length = len;
808 o.extra_payload = (char *) safe_malloc(o.extra_payload_length);
809 memcpy(o.extra_payload, tempbuff, len);
810 }
811 if (o.extra_payload_length > 1400) /* 1500 - IP with opts - TCP with opts. */
812 error("WARNING: Payloads bigger than 1400 bytes may not be sent successfully.");
813 } else if (strcmp(long_options[option_index].name, "data-string") == 0) {
814 delayed_options.raw_scan_options = true;
815 if (o.extra_payload)
816 fatal("Can't use the --data option(s) multiple times, or together.");
817 o.extra_payload_length = strlen(optarg);
818 if (o.extra_payload_length < 0 || o.extra_payload_length > MAX_PAYLOAD_ALLOWED)
819 fatal("string length must be between 0 and %d", MAX_PAYLOAD_ALLOWED);
820 if (o.extra_payload_length > 1400) /* 1500 - IP with opts - TCP with opts. */
821 error("WARNING: Payloads bigger than 1400 bytes may not be sent successfully.");
822 o.extra_payload = strdup(optarg);
823 } else if (strcmp(long_options[option_index].name, "data-length") == 0) {
824 delayed_options.raw_scan_options = true;
825 if (o.extra_payload)
826 fatal("Can't use the --data option(s) multiple times, or together.");
827 o.extra_payload_length = (int)strtol(optarg, NULL, 10);
828 if (o.extra_payload_length < 0 || o.extra_payload_length > MAX_PAYLOAD_ALLOWED)
829 fatal("data-length must be between 0 and %d", MAX_PAYLOAD_ALLOWED);
830 if (o.extra_payload_length > 1400) /* 1500 - IP with opts - TCP with opts. */
831 error("WARNING: Payloads bigger than 1400 bytes may not be sent successfully.");
832 o.extra_payload = (char *) safe_malloc(MAX(o.extra_payload_length, 1));
833 get_random_bytes(o.extra_payload, o.extra_payload_length);
834 } else if (strcmp(long_options[option_index].name, "send-eth") == 0) {
835 o.sendpref = PACKET_SEND_ETH_STRONG;
836 } else if (strcmp(long_options[option_index].name, "send-ip") == 0) {
837 o.sendpref = PACKET_SEND_IP_STRONG;
838 } else if (strcmp(long_options[option_index].name, "stylesheet") == 0) {
839 o.setXSLStyleSheet(optarg);
840 } else if (strcmp(long_options[option_index].name, "no-stylesheet") == 0) {
841 o.setXSLStyleSheet(NULL);
842 } else if (strcmp(long_options[option_index].name, "system-dns") == 0) {
843 o.mass_dns = false;
844 } else if (strcmp(long_options[option_index].name, "dns-servers") == 0) {
845 o.dns_servers = strdup(optarg);
846 } else if (strcmp(long_options[option_index].name, "resolve-all") == 0) {
847 o.resolve_all = true;
848 } else if (strcmp(long_options[option_index].name, "log-errors") == 0) {
849 /*Nmap Log errors is deprecated and is now always enabled by default.
850 This option is left in so as to not break anybody's scanning scripts.
851 However it does nothing*/
852 } else if (strcmp(long_options[option_index].name, "deprecated-xml-osclass") == 0) {
853 o.deprecated_xml_osclass = true;
854 } else if (strcmp(long_options[option_index].name, (char*)k) == 0) {
855 log_write(LOG_STDOUT, "%s", (char*)(k+3));
856 delayed_options.advanced = true;
857 } else if (strcmp(long_options[option_index].name, "webxml") == 0) {
858 o.setXSLStyleSheet("https://svn.nmap.org/nmap/docs/nmap.xsl");
859 } else if (strcmp(long_options[option_index].name, "oN") == 0) {
860 test_file_name(optarg, long_options[option_index].name);
861 delayed_options.normalfilename = logfilename(optarg, &local_time);
862 } else if (strcmp(long_options[option_index].name, "oG") == 0
863 || strcmp(long_options[option_index].name, "oM") == 0) {
864 test_file_name(optarg, long_options[option_index].name);
865 delayed_options.machinefilename = logfilename(optarg, &local_time);
866 if (long_options[option_index].name[1] == 'M')
867 delayed_options.warn_deprecated("oM", "oG");
868 } else if (strcmp(long_options[option_index].name, "oS") == 0) {
869 test_file_name(optarg, long_options[option_index].name);
870 delayed_options.kiddiefilename = logfilename(optarg, &local_time);
871 } else if (strcmp(long_options[option_index].name, "oH") == 0) {
872 fatal("HTML output is not directly supported, though Nmap includes an XSL for transforming XML output into HTML. See the man page.");
873 } else if (strcmp(long_options[option_index].name, "oX") == 0) {
874 test_file_name(optarg, long_options[option_index].name);
875 delayed_options.xmlfilename = logfilename(optarg, &local_time);
876 } else if (strcmp(long_options[option_index].name, "oA") == 0) {
877 char buf[MAXPATHLEN];
878 test_file_name(optarg, long_options[option_index].name);
879 Snprintf(buf, sizeof(buf), "%s.nmap", logfilename(optarg, &local_time));
880 delayed_options.normalfilename = strdup(buf);
881 Snprintf(buf, sizeof(buf), "%s.gnmap", logfilename(optarg, &local_time));
882 delayed_options.machinefilename = strdup(buf);
883 Snprintf(buf, sizeof(buf), "%s.xml", logfilename(optarg, &local_time));
884 delayed_options.xmlfilename = strdup(buf);
885 } else if (strcmp(long_options[option_index].name, "thc") == 0) {
886 log_write(LOG_STDOUT, "!!Greets to Van Hauser, Plasmoid, Skyper and the rest of THC!!\n");
887 exit(0);
888 } else if (strcmp(long_options[option_index].name, "badsum") == 0) {
889 delayed_options.raw_scan_options = true;
890 o.badsum = true;
891 } else if (strcmp(long_options[option_index].name, "iL") == 0) {
892 if (o.inputfd) {
893 fatal("Only one input filename allowed");
894 }
895 if (!strcmp(optarg, "-")) {
896 o.inputfd = stdin;
897 } else {
898 o.inputfd = fopen(optarg, "r");
899 if (!o.inputfd) {
900 fatal("Failed to open input file %s for reading", optarg);
901 }
902 }
903 } else if (strcmp(long_options[option_index].name, "iR") == 0) {
904 o.generate_random_ips = true;
905 o.max_ips_to_scan = strtoul(optarg, &endptr, 10);
906 if (*endptr != '\0') {
907 fatal("ERROR: -iR argument must be the maximum number of random IPs you wish to scan (use 0 for unlimited)");
908 }
909 } else if (strcmp(long_options[option_index].name, "sI") == 0) {
910 o.idlescan = 1;
911 o.idleProxy = strdup(optarg);
912 if (strlen(o.idleProxy) > FQDN_LEN) {
913 fatal("ERROR: -sI argument must be less than %d characters", FQDN_LEN);
914 }
915 } else if (strcmp(long_options[option_index].name, "vv") == 0) {
916 /* Compatibility hack ... ugly */
917 o.verbose += 2;
918 if (o.verbose > 10) o.verbose = 10;
919 } else if (strcmp(long_options[option_index].name, "ff") == 0) {
920 delayed_options.raw_scan_options = true;
921 o.fragscan += 16;
922 } else if (strcmp(long_options[option_index].name, "privileged") == 0) {
923 o.isr00t = 1;
924 } else if (strcmp(long_options[option_index].name, "unprivileged") == 0) {
925 o.isr00t = 0;
926 } else if (strcmp(long_options[option_index].name, "mtu") == 0) {
927 delayed_options.raw_scan_options = true;
928 o.fragscan = atoi(optarg);
929 if (o.fragscan <= 0 || o.fragscan % 8 != 0)
930 fatal("Data payload MTU must be >0 and multiple of 8");
931 } else if (strcmp(long_options[option_index].name, "port-ratio") == 0) {
932 char *ptr;
933 o.topportlevel = strtod(optarg, &ptr);
934 if (!ptr || o.topportlevel < 0 || o.topportlevel >= 1)
935 fatal("--port-ratio should be between [0 and 1)");
936 } else if (strcmp(long_options[option_index].name, "exclude-ports") == 0) {
937 if (o.exclude_portlist)
938 fatal("Only 1 --exclude-ports option allowed, separate multiple ranges with commas.");
939 o.exclude_portlist = strdup(optarg);
940 } else if (strcmp(long_options[option_index].name, "top-ports") == 0) {
941 char *ptr;
942 o.topportlevel = strtod(optarg, &ptr);
943 if (!ptr || o.topportlevel < 1 || ((double)((int)o.topportlevel)) != o.topportlevel)
944 fatal("--top-ports should be an integer 1 or greater");
945 } else if (strcmp(long_options[option_index].name, "ip-options") == 0) {
946 delayed_options.raw_scan_options = true;
947 o.ipoptions = (u8*) safe_malloc(4 * 10 + 1);
948 if ((o.ipoptionslen = parse_ip_options(optarg, o.ipoptions, 4 * 10 + 1, &o.ipopt_firsthop, &o.ipopt_lasthop, errstr, sizeof(errstr))) == OP_FAILURE)
949 fatal("%s", errstr);
950 if (o.ipoptionslen > 4 * 10)
951 fatal("Ip options can't be more than 40 bytes long");
952 if (o.ipoptionslen % 4 != 0)
953 fatal("Ip options must be multiple of 4 (read length is %i bytes)", o.ipoptionslen);
954 } else if (strcmp(long_options[option_index].name, "traceroute") == 0) {
955 o.traceroute = true;
956 } else if (strcmp(long_options[option_index].name, "reason") == 0) {
957 o.reason = true;
958 } else if (strcmp(long_options[option_index].name, "min-rate") == 0) {
959 if (sscanf(optarg, "%f", &o.min_packet_send_rate) != 1 || o.min_packet_send_rate <= 0.0)
960 fatal("Argument to --min-rate must be a positive floating-point number");
961 } else if (strcmp(long_options[option_index].name, "max-rate") == 0) {
962 if (sscanf(optarg, "%f", &o.max_packet_send_rate) != 1 || o.max_packet_send_rate <= 0.0)
963 fatal("Argument to --max-rate must be a positive floating-point number");
964 } else if (strcmp(long_options[option_index].name, "adler32") == 0) {
965 o.adler32 = true;
966 } else if (strcmp(long_options[option_index].name, "stats-every") == 0) {
967 d = tval2secs(optarg);
968 if (d < 0 || d > LONG_MAX)
969 fatal("Bogus --stats-every argument specified");
970 o.stats_interval = d;
971 } else if (strcmp(long_options[option_index].name, "disable-arp-ping") == 0) {
972 o.implicitARPPing = false;
973 } else if (strcmp(long_options[option_index].name, "route-dst") == 0) {
974 /* The --route-dst debugging option: push these on a list to be
975 resolved later after options like -6 and -S have been parsed. */
976 route_dst_hosts.push_back(optarg);
977 } else if (strcmp(long_options[option_index].name, "resume") == 0) {
978 fatal("Cannot use --resume with other options. Usage: nmap --resume <filename>");
979 } else {
980 fatal("Unknown long option (%s) given@#!$#$", long_options[option_index].name);
981 }
982 break;
983 case '4':
984 /* This is basically useless for now, but serves as a placeholder to
985 * ensure that -4 is a valid option */
986 if (delayed_options.af == AF_INET6) {
987 fatal("Cannot use both -4 and -6 in one scan.");
988 }
989 delayed_options.af = AF_INET;
990 break;
991 case '6':
992 #if !HAVE_IPV6
993 fatal("I am afraid IPv6 is not available because your host doesn't support it or you chose to compile Nmap w/o IPv6 support.");
994 #else
995 if (delayed_options.af == AF_INET) {
996 fatal("Cannot use both -4 and -6 in one scan.");
997 }
998 delayed_options.af = AF_INET6;
999 #endif /* !HAVE_IPV6 */
1000 break;
1001 case 'A':
1002 delayed_options.advanced = true;
1003 break;
1004 case 'b':
1005 o.bouncescan++;
1006 if (parse_bounce_argument(&ftp, optarg) < 0) {
1007 fatal("Your argument to -b is b0rked. Use the normal url style: user:pass@server:port or just use server and use default anon login\n Use -h for help");
1008 }
1009 break;
1010 case 'D':
1011 delayed_options.raw_scan_options = true;
1012 delayed_options.decoy_arguments = optarg;
1013 break;
1014 case 'd':
1015 if (optarg && isdigit(optarg[0])) {
1016 int i = atoi(optarg);
1017 o.debugging = o.verbose = box(0, 10, i);
1018 } else {
1019 const char *p;
1020 if (o.debugging < 10) o.debugging++;
1021 if (o.verbose < 10) o.verbose++;
1022 for (p = optarg != NULL ? optarg : ""; *p == 'd'; p++) {
1023 if (o.debugging < 10) o.debugging++;
1024 if (o.verbose < 10) o.verbose++;
1025 }
1026 if (*p != '\0')
1027 fatal("Invalid argument to -d: \"%s\".", optarg);
1028 }
1029 o.reason = true;
1030 break;
1031 case 'e':
1032 Strncpy(o.device, optarg, sizeof(o.device));
1033 break;
1034 case 'F':
1035 o.fastscan = true;
1036 break;
1037 case 'f':
1038 delayed_options.raw_scan_options = true;
1039 o.fragscan += 8;
1040 break;
1041 case 'g':
1042 delayed_options.raw_scan_options = true;
1043 o.magic_port = atoi(optarg);
1044 o.magic_port_set = true;
1045 if (o.magic_port == 0)
1046 error("WARNING: a source port of zero may not work on all systems.");
1047 break;
1048 case 'h':
1049 printusage();
1050 exit(0);
1051 break;
1052 case '?':
1053 error("See the output of nmap -h for a summary of options.");
1054 exit(-1);
1055 break;
1056 case 'I':
1057 error("WARNING: identscan (-I) no longer supported. Ignoring -I");
1058 break;
1059 // o.identscan++; break;
1060 case 'i':
1061 delayed_options.warn_deprecated("i", "iL");
1062 if (o.inputfd) {
1063 fatal("Only one input filename allowed");
1064 }
1065 if (!strcmp(optarg, "-")) {
1066 o.inputfd = stdin;
1067 } else {
1068 o.inputfd = fopen(optarg, "r");
1069 if (!o.inputfd) {
1070 fatal("Failed to open input file %s for reading", optarg);
1071 }
1072 }
1073 break;
1074 case 'M':
1075 delayed_options.pre_max_parallelism = atoi(optarg);
1076 if (delayed_options.pre_max_parallelism < 1)
1077 fatal("Argument to -M must be at least 1!");
1078 if (delayed_options.pre_max_parallelism > 900)
1079 error("Warning: Your max-parallelism (-M) option is extraordinarily high, which can hurt reliability");
1080 break;
1081 case 'm':
1082 delayed_options.warn_deprecated("m", "oG");
1083 test_file_name(optarg, "oG");
1084 delayed_options.machinefilename = logfilename(optarg, &local_time);
1085 break;
1086 case 'n':
1087 o.noresolve = true;
1088 break;
1089 case 'O':
1090 if (!optarg || *optarg == '2')
1091 o.osscan = true;
1092 else if (*optarg == '1')
1093 fatal("First-generation OS detection (-O1) is no longer supported. Use -O instead.");
1094 else
1095 fatal("Unknown argument to -O.");
1096 break;
1097 case 'o':
1098 delayed_options.warn_deprecated("o", "oN");
1099 test_file_name(optarg, "o");
1100 delayed_options.normalfilename = logfilename(optarg, &local_time);
1101 break;
1102 case 'P':
1103 if (!optarg) {
1104 delayed_options.warn_deprecated("P", "PE");
1105 o.pingtype |= PINGTYPE_ICMP_PING;
1106 }
1107 else if (*optarg == '\0' || *optarg == 'I' || *optarg == 'E') {
1108 if (*optarg != 'E') {
1109 char buf[4];
1110 Snprintf(buf, 3, "P%c", *optarg);
1111 delayed_options.warn_deprecated(buf, "PE");
1112 }
1113 o.pingtype |= PINGTYPE_ICMP_PING;
1114 }
1115 else if (*optarg == 'M')
1116 o.pingtype |= PINGTYPE_ICMP_MASK;
1117 else if (*optarg == 'P')
1118 o.pingtype |= PINGTYPE_ICMP_TS;
1119 else if (*optarg == 'n' || *optarg == '0' || *optarg == 'N' || *optarg == 'D') {
1120 if (*optarg != 'n') {
1121 char buf[4];
1122 Snprintf(buf, 3, "P%c", *optarg);
1123 delayed_options.warn_deprecated(buf, "Pn");
1124 }
1125 error("Host discovery disabled (-Pn). All addresses will be marked 'up' and scan times will be slower.");
1126 o.pingtype |= PINGTYPE_NONE;
1127 }
1128 else if (*optarg == 'R') {
1129 if (o.verbose > 0)
1130 error("The -PR option is deprecated. ARP scan is always done when possible.");
1131 }
1132 else if (*optarg == 'S') {
1133 if (ports.syn_ping_count > 0)
1134 fatal("Only one -PS option is allowed. Combine port ranges with commas.");
1135 o.pingtype |= (PINGTYPE_TCP | PINGTYPE_TCP_USE_SYN);
1136 if (*(optarg + 1) != '\0') {
1137 getpts_simple(optarg + 1, SCAN_TCP_PORT, &ports.syn_ping_ports, &ports.syn_ping_count);
1138 if (ports.syn_ping_count <= 0)
1139 fatal("Bogus argument to -PS: %s", optarg + 1);
1140 } else {
1141 getpts_simple(DEFAULT_TCP_PROBE_PORT_SPEC, SCAN_TCP_PORT, &ports.syn_ping_ports, &ports.syn_ping_count);
1142 assert(ports.syn_ping_count > 0);
1143 }
1144 } else if (*optarg == 'T' || *optarg == 'A') {
1145 if (ports.ack_ping_count > 0)
1146 fatal("Only one -PB, -PA, or -PT option is allowed. Combine port ranges with commas.");
1147 /* validate_scan_lists takes case of changing this to
1148 to SYN if not root or if IPv6. */
1149 o.pingtype |= (PINGTYPE_TCP | PINGTYPE_TCP_USE_ACK);
1150 if (*(optarg + 1) != '\0') {
1151 getpts_simple(optarg + 1, SCAN_TCP_PORT, &ports.ack_ping_ports, &ports.ack_ping_count);
1152 if (ports.ack_ping_count <= 0)
1153 fatal("Bogus argument to -PA: %s", optarg + 1);
1154 } else {
1155 getpts_simple(DEFAULT_TCP_PROBE_PORT_SPEC, SCAN_TCP_PORT, &ports.ack_ping_ports, &ports.ack_ping_count);
1156 assert(ports.ack_ping_count > 0);
1157 }
1158 } else if (*optarg == 'U') {
1159 if (ports.udp_ping_count > 0)
1160 fatal("Only one -PU option is allowed. Combine port ranges with commas.");
1161 o.pingtype |= (PINGTYPE_UDP);
1162 if (*(optarg + 1) != '\0') {
1163 getpts_simple(optarg + 1, SCAN_UDP_PORT, &ports.udp_ping_ports, &ports.udp_ping_count);
1164 if (ports.udp_ping_count <= 0)
1165 fatal("Bogus argument to -PU: %s", optarg + 1);
1166 } else {
1167 getpts_simple(DEFAULT_UDP_PROBE_PORT_SPEC, SCAN_UDP_PORT, &ports.udp_ping_ports, &ports.udp_ping_count);
1168 assert(ports.udp_ping_count > 0);
1169 }
1170 } else if (*optarg == 'Y') {
1171 if (ports.sctp_ping_count > 0)
1172 fatal("Only one -PY option is allowed. Combine port ranges with commas.");
1173 o.pingtype |= (PINGTYPE_SCTP_INIT);
1174 if (*(optarg + 1) != '\0') {
1175 getpts_simple(optarg + 1, SCAN_SCTP_PORT, &ports.sctp_ping_ports, &ports.sctp_ping_count);
1176 if (ports.sctp_ping_count <= 0)
1177 fatal("Bogus argument to -PY: %s", optarg + 1);
1178 } else {
1179 getpts_simple(DEFAULT_SCTP_PROBE_PORT_SPEC, SCAN_SCTP_PORT, &ports.sctp_ping_ports, &ports.sctp_ping_count);
1180 assert(ports.sctp_ping_count > 0);
1181 }
1182 } else if (*optarg == 'B') {
1183 if (ports.ack_ping_count > 0)
1184 fatal("Only one -PB, -PA, or -PT option is allowed. Combine port ranges with commas.");
1185 o.pingtype = DEFAULT_IPV4_PING_TYPES;
1186 if (*(optarg + 1) != '\0') {
1187 getpts_simple(optarg + 1, SCAN_TCP_PORT, &ports.ack_ping_ports, &ports.ack_ping_count);
1188 if (ports.ack_ping_count <= 0)
1189 fatal("Bogus argument to -PB: %s", optarg + 1);
1190 } else {
1191 getpts_simple(DEFAULT_TCP_PROBE_PORT_SPEC, SCAN_TCP_PORT, &ports.ack_ping_ports, &ports.ack_ping_count);
1192 assert(ports.ack_ping_count > 0);
1193 }
1194 } else if (*optarg == 'O') {
1195 if (ports.proto_ping_count > 0)
1196 fatal("Only one -PO option is allowed. Combine protocol ranges with commas.");
1197 o.pingtype |= PINGTYPE_PROTO;
1198 if (*(optarg + 1) != '\0') {
1199 getpts_simple(optarg + 1, SCAN_PROTOCOLS, &ports.proto_ping_ports, &ports.proto_ping_count);
1200 if (ports.proto_ping_count <= 0)
1201 fatal("Bogus argument to -PO: %s", optarg + 1);
1202 } else {
1203 getpts_simple(DEFAULT_PROTO_PROBE_PORT_SPEC, SCAN_PROTOCOLS, &ports.proto_ping_ports, &ports.proto_ping_count);
1204 assert(ports.proto_ping_count > 0);
1205 }
1206 } else {
1207 fatal("Illegal Argument to -P, use -Pn, -PE, -PS, -PA, -PP, -PM, -PU, -PY, or -PO");
1208 }
1209 break;
1210 case 'p':
1211 if (o.portlist)
1212 fatal("Only 1 -p option allowed, separate multiple ranges with commas.");
1213 o.portlist = strdup(optarg);
1214 break;
1215 case 'R':
1216 o.always_resolve = true;
1217 break;
1218 case 'r':
1219 o.randomize_ports = false;
1220 break;
1221 case 'S':
1222 if (o.spoofsource)
1223 fatal("You can only use the source option once! Use -D <decoy1> -D <decoy2> etc. for decoys\n");
1224 delayed_options.spoofSource = strdup(optarg);
1225 delayed_options.raw_scan_options = true;
1226 o.spoofsource = true;
1227 break;
1228 case 's':
1229 if (!optarg || !*optarg) {
1230 printusage();
1231 error("An option is required for -s, most common are -sT (tcp scan), -sS (SYN scan), -sF (FIN scan), -sU (UDP scan) and -sn (Ping scan)");
1232 exit(-1);
1233 }
1234 p = optarg;
1235 while (*p) {
1236 switch (*p) {
1237 case 'P':
1238 delayed_options.warn_deprecated("sP", "sn");
1239 case 'n':
1240 o.noportscan = true;
1241 break;
1242 case 'A':
1243 o.ackscan = true;
1244 break;
1245 case 'B':
1246 fatal("No scan type 'B', did you mean bounce scan (-b)?");
1247 break;
1248 #ifndef NOLUA
1249 case 'C':
1250 o.script = true;
1251 break;
1252 #endif
1253 case 'F':
1254 o.finscan = 1;
1255 break;
1256 case 'L':
1257 o.listscan = true;
1258 o.noportscan = true;
1259 o.pingtype |= PINGTYPE_NONE;
1260 break;
1261 case 'M':
1262 o.maimonscan = 1;
1263 break;
1264 case 'N':
1265 o.nullscan = 1;
1266 break;
1267 case 'O':
1268 o.ipprotscan = 1;
1269 break;
1270 /* Alias for -sV since March 2011. */
1271 case 'R':
1272 o.servicescan = true;
1273 delayed_options.warn_deprecated("sR", "sV");
1274 error("WARNING: -sR is now an alias for -sV and activates version detection as well as RPC scan.");
1275 break;
1276 case 'S':
1277 o.synscan = 1;
1278 break;
1279 case 'T':
1280 o.connectscan = 1;
1281 break;
1282 case 'U':
1283 o.udpscan++;
1284 break;
1285 case 'V':
1286 o.servicescan = true;
1287 break;
1288 case 'W':
1289 o.windowscan = 1;
1290 break;
1291 case 'X':
1292 o.xmasscan++;
1293 break;
1294 case 'Y':
1295 o.sctpinitscan = 1;
1296 break;
1297 case 'Z':
1298 o.sctpcookieechoscan = 1;
1299 break;
1300 default:
1301 printusage();
1302 error("Scantype %c not supported\n", *p);
1303 exit(-1);
1304 break;
1305 }
1306 p++;
1307 }
1308 break;
1309 case 'T':
1310 p=optarg+1;*p=*p>'5'?*p:*(p-1)!=*p?'\0':*(p-1)='\0'==(*p-'1')?(error("%s",(char*)(k+8)),'5'):*p;
1311 if (*optarg == '0' || (strcasecmp(optarg, "Paranoid") == 0)) {
1312 o.timing_level = 0;
1313 o.max_parallelism = 1;
1314 o.scan_delay = 300000;
1315 o.setInitialRttTimeout(300000);
1316 } else if (*optarg == '1' || (strcasecmp(optarg, "Sneaky") == 0)) {
1317 o.timing_level = 1;
1318 o.max_parallelism = 1;
1319 o.scan_delay = 15000;
1320 o.setInitialRttTimeout(15000);
1321 } else if (*optarg == '2' || (strcasecmp(optarg, "Polite") == 0)) {
1322 o.timing_level = 2;
1323 o.max_parallelism = 1;
1324 o.scan_delay = 400;
1325 } else if (*optarg == '3' || (strcasecmp(optarg, "Normal") == 0)) {
1326 // Default timing, see NmapOps.cc
1327 } else if (*optarg == '4' || (strcasecmp(optarg, "Aggressive") == 0)) {
1328 o.timing_level = 4;
1329 o.setMinRttTimeout(100);
1330 o.setMaxRttTimeout(1250);
1331 o.setInitialRttTimeout(500);
1332 o.setMaxTCPScanDelay(10);
1333 o.setMaxSCTPScanDelay(10);
1334 o.setMaxRetransmissions(6);
1335 } else if (*optarg == '5' || (strcasecmp(optarg, "Insane") == 0)) {
1336 o.timing_level = 5;
1337 o.setMinRttTimeout(50);
1338 o.setMaxRttTimeout(300);
1339 o.setInitialRttTimeout(250);
1340 o.host_timeout = 900000;
1341 o.setMaxTCPScanDelay(5);
1342 o.setMaxSCTPScanDelay(5);
1343 o.setMaxRetransmissions(2);
1344 #ifndef NOLUA
1345 o.scripttimeout = 600; // 10 minutes
1346 #endif
1347 } else {
1348 fatal("Unknown timing mode (-T argument). Use either \"Paranoid\", \"Sneaky\", \"Polite\", \"Normal\", \"Aggressive\", \"Insane\" or a number from 0 (Paranoid) to 5 (Insane)");
1349 }
1350 break;
1351 case 'V':
1352 #ifdef WIN32
1353 /* For pcap_get_version, since we need to get the correct Npcap/WinPcap
1354 * DLL loaded */
1355 win_init();
1356 #endif
1357 display_nmap_version();
1358 exit(0);
1359 break;
1360 case 'v':
1361 if (optarg && isdigit(optarg[0])) {
1362 int i = atoi(optarg);
1363 o.verbose = box(0, 10, i);
1364 if (o.verbose == 0) {
1365 o.nmap_stdout = fopen(DEVNULL, "w");
1366 if (!o.nmap_stdout)
1367 fatal("Could not assign %s to stdout for writing", DEVNULL);
1368 }
1369 } else {
1370 const char *p;
1371 if (o.verbose < 10) o.verbose++;
1372 for (p = optarg != NULL ? optarg : ""; *p == 'v'; p++)
1373 if (o.verbose < 10) o.verbose++;
1374 if (*p != '\0')
1375 fatal("Invalid argument to -v: \"%s\".", optarg);
1376 }
1377 break;
1378 }
1379 }
1380
1381 }
1382
apply_delayed_options()1383 void apply_delayed_options() {
1384 int i;
1385 char tbuf[128];
1386 struct sockaddr_storage ss;
1387 size_t sslen;
1388
1389 // Default IPv4
1390 o.setaf(delayed_options.af == AF_UNSPEC ? AF_INET : delayed_options.af);
1391
1392 if (o.verbose > 0) {
1393 for (std::vector<std::string>::iterator it = delayed_options.verbose_out.begin(); it != delayed_options.verbose_out.end(); ++it) {
1394 error("%s", it->c_str());
1395 }
1396 }
1397 delayed_options.verbose_out.clear();
1398
1399 if (delayed_options.advanced) {
1400 o.servicescan = true;
1401 #ifndef NOLUA
1402 o.script = true;
1403 #endif
1404 if (o.isr00t) {
1405 o.osscan = true;
1406 o.traceroute = true;
1407 }
1408 }
1409 if (o.spoofsource) {
1410 int rc = resolve(delayed_options.spoofSource, 0, &ss, &sslen, o.af());
1411 if (rc != 0) {
1412 fatal("Failed to resolve/decode supposed %s source address \"%s\": %s",
1413 (o.af() == AF_INET) ? "IPv4" : "IPv6", delayed_options.spoofSource,
1414 gai_strerror(rc));
1415 }
1416 o.setSourceSockAddr(&ss, sslen);
1417 }
1418 // After the arguments are fully processed we now make any of the timing
1419 // tweaks the user might've specified:
1420 if (delayed_options.pre_max_parallelism != -1)
1421 o.max_parallelism = delayed_options.pre_max_parallelism;
1422 if (delayed_options.pre_scan_delay != -1) {
1423 o.scan_delay = delayed_options.pre_scan_delay;
1424 if (o.scan_delay > o.maxTCPScanDelay())
1425 o.setMaxTCPScanDelay(o.scan_delay);
1426 if (o.scan_delay > o.maxUDPScanDelay())
1427 o.setMaxUDPScanDelay(o.scan_delay);
1428 if (o.scan_delay > o.maxSCTPScanDelay())
1429 o.setMaxSCTPScanDelay(o.scan_delay);
1430 if (delayed_options.pre_max_parallelism != -1 || o.min_parallelism != 0)
1431 error("Warning: --min-parallelism and --max-parallelism are ignored with --scan-delay.");
1432 }
1433 if (delayed_options.pre_max_scan_delay != -1) {
1434 o.setMaxTCPScanDelay(delayed_options.pre_max_scan_delay);
1435 o.setMaxUDPScanDelay(delayed_options.pre_max_scan_delay);
1436 o.setMaxSCTPScanDelay(delayed_options.pre_max_scan_delay);
1437 }
1438 if (delayed_options.pre_init_rtt_timeout != -1)
1439 o.setInitialRttTimeout(delayed_options.pre_init_rtt_timeout);
1440 if (delayed_options.pre_min_rtt_timeout != -1)
1441 o.setMinRttTimeout(delayed_options.pre_min_rtt_timeout);
1442 if (delayed_options.pre_max_rtt_timeout != -1)
1443 o.setMaxRttTimeout(delayed_options.pre_max_rtt_timeout);
1444 if (delayed_options.pre_max_retries != -1)
1445 o.setMaxRetransmissions(delayed_options.pre_max_retries);
1446 if (delayed_options.pre_host_timeout != -1)
1447 o.host_timeout = delayed_options.pre_host_timeout;
1448 #ifndef NOLUA
1449 if (delayed_options.pre_scripttimeout != -1)
1450 o.scripttimeout = delayed_options.pre_scripttimeout;
1451 #endif
1452
1453
1454 if (o.osscan) {
1455 if (o.af() == AF_INET)
1456 o.reference_FPs = parse_fingerprint_reference_file("nmap-os-db");
1457 else if (o.af() == AF_INET6)
1458 o.os_labels_ipv6 = load_fp_matches();
1459 }
1460
1461 // Must check and change this before validate_scan_lists
1462 if (o.pingtype & PINGTYPE_NONE)
1463 o.pingtype = PINGTYPE_NONE;
1464
1465 validate_scan_lists(ports, o);
1466 o.ValidateOptions();
1467
1468 // print ip options
1469 if ((o.debugging || o.packetTrace()) && o.ipoptionslen) {
1470 char buf[256]; // 256 > 5*40
1471 bintohexstr(buf, sizeof(buf), (char*) o.ipoptions, o.ipoptionslen);
1472 if (o.ipoptionslen >= 8) // at least one ip address
1473 log_write(LOG_STDOUT, "Binary ip options to be send:\n%s", buf);
1474 log_write(LOG_STDOUT, "Parsed ip options to be send:\n%s\n",
1475 format_ip_options(o.ipoptions, o.ipoptionslen));
1476 }
1477
1478 /* Open the log files, now that we know whether the user wants them appended
1479 or overwritten */
1480 if (delayed_options.normalfilename) {
1481 log_open(LOG_NORMAL, o.append_output, delayed_options.normalfilename);
1482 free(delayed_options.normalfilename);
1483 }
1484 if (delayed_options.machinefilename) {
1485 log_open(LOG_MACHINE, o.append_output, delayed_options.machinefilename);
1486 free(delayed_options.machinefilename);
1487 }
1488 if (delayed_options.kiddiefilename) {
1489 log_open(LOG_SKID, o.append_output, delayed_options.kiddiefilename);
1490 free(delayed_options.kiddiefilename);
1491 }
1492 if (delayed_options.xmlfilename) {
1493 log_open(LOG_XML, o.append_output, delayed_options.xmlfilename);
1494 free(delayed_options.xmlfilename);
1495 }
1496
1497 if (o.verbose > 1)
1498 o.reason = true;
1499
1500 // ISO 8601 date/time -- http://www.cl.cam.ac.uk/~mgk25/iso-time.html
1501 if (strftime(tbuf, sizeof(tbuf), "%Y-%m-%d %H:%M %Z", &local_time) <= 0)
1502 fatal("Unable to properly format time");
1503 log_write(LOG_STDOUT | LOG_SKID, "Starting %s %s ( %s ) at %s\n", NMAP_NAME, NMAP_VERSION, NMAP_URL, tbuf);
1504 if (o.verbose) {
1505 if (local_time.tm_mon == 8 && local_time.tm_mday == 1) {
1506 unsigned int a = (local_time.tm_year - 97)%100;
1507 log_write(LOG_STDOUT | LOG_SKID, "Happy %d%s Birthday to Nmap, may it live to be %d!\n", local_time.tm_year - 97,(a>=11&&a<=13?"th":(a%10==1?"st":(a%10==2?"nd":(a%10==3?"rd":"th")))), local_time.tm_year + 3);
1508 } else if (local_time.tm_mon == 11 && local_time.tm_mday == 25) {
1509 log_write(LOG_STDOUT | LOG_SKID, "Nmap wishes you a merry Christmas! Specify -sX for Xmas Scan (https://nmap.org/book/man-port-scanning-techniques.html).\n");
1510 }
1511 }
1512
1513 #ifndef NOLUA
1514 if (o.scripthelp) {
1515 /* Special-case open_nse for --script-help only. */
1516 open_nse();
1517 exit(0);
1518 }
1519 #endif
1520
1521 if (o.traceroute && !o.isr00t)
1522 fatal("Traceroute has to be run as root");
1523 if (o.traceroute && o.idlescan)
1524 fatal("Traceroute does not support idle scan");
1525
1526 if ((o.noportscan) && (o.portlist || o.fastscan))
1527 fatal("You cannot use -F (fast scan) or -p (explicit port selection) when not doing a port scan");
1528
1529 if (o.portlist && o.fastscan)
1530 fatal("You cannot use -F (fast scan) with -p (explicit port selection) but see --top-ports and --port-ratio to fast scan a range of ports");
1531
1532 if (o.ipprotscan) {
1533 if (o.portlist)
1534 getpts(o.portlist, &ports);
1535 else
1536 getpts((char *) (o.fastscan ? "[P:0-]" : "0-"), &ports); // Default protocols to scan
1537 } else if (!o.noportscan) {
1538 if (o.portlist) {
1539 for (const char *p=o.portlist; *p != '\0'; p++) {
1540 if (*(p+1) == ':') {
1541 switch(*p) {
1542 case 'T':
1543 if (!o.TCPScan()) {
1544 error("WARNING: Your ports include \"T:\" but you haven't specified any TCP scan type.");
1545 }
1546 break;
1547 case 'U':
1548 if (!o.UDPScan()) {
1549 error("WARNING: Your ports include \"U:\" but you haven't specified UDP scan with -sU.");
1550 }
1551 break;
1552 case 'S':
1553 if (!o.SCTPScan()) {
1554 error("WARNING: Your ports include \"S:\" but you haven't specified any SCTP scan type.");
1555 }
1556 break;
1557 case 'P':
1558 if (!o.ipprotscan) {
1559 error("WARNING: Your ports include \"P:\" but you haven't specified IP Protocol scan with -sO.");
1560 }
1561 break;
1562 default:
1563 break;
1564 }
1565 }
1566 }
1567 }
1568 gettoppts(o.topportlevel, o.portlist, &ports, o.exclude_portlist);
1569 }
1570
1571 // Uncomment the following line to use the common lisp port spec test suite
1572 //printf("port spec: (%d %d %d %d)\n", ports.tcp_count, ports.udp_count, ports.sctp_count, ports.prot_count); exit(0);
1573
1574 #ifdef WIN32
1575 if (o.sendpref & PACKET_SEND_IP) {
1576 error("WARNING: raw IP (rather than raw ethernet) packet sending attempted on Windows. This probably won't work. Consider --send-eth next time.");
1577 }
1578 #endif
1579 if (delayed_options.spoofmac) {
1580 u8 mac_data[6];
1581 int pos = 0; /* Next index of mac_data to fill in */
1582 char tmphex[3];
1583 /* A zero means set it all randomly. Anything that is all digits
1584 or colons is treated as a prefix, with remaining characters for
1585 the 6-byte MAC (if any) chosen randomly. Otherwise, it is
1586 treated as a vendor string for lookup in nmap-mac-prefixes */
1587 if (strcmp(delayed_options.spoofmac, "0") == 0) {
1588 pos = 0;
1589 } else {
1590 const char *p = delayed_options.spoofmac;
1591 while (*p) {
1592 if (*p == ':')
1593 p++;
1594 if (isxdigit((int) (unsigned char) *p) && isxdigit((int) (unsigned char) * (p + 1))) {
1595 if (pos >= 6)
1596 fatal("Bogus --spoof-mac value encountered (%s) -- only up to 6 bytes permitted", delayed_options.spoofmac);
1597 tmphex[0] = *p;
1598 tmphex[1] = *(p + 1);
1599 tmphex[2] = '\0';
1600 mac_data[pos] = (u8) strtol(tmphex, NULL, 16);
1601 pos++;
1602 p += 2;
1603 } else break;
1604 }
1605 if (*p) {
1606 /* Failed to parse it as a MAC prefix -- treating as a vendor substring instead */
1607 if (!MACCorp2Prefix(delayed_options.spoofmac, mac_data))
1608 fatal("Could not parse as a prefix nor find as a vendor substring the given --spoof-mac argument: %s. If you are giving hex digits, there must be an even number of them.", delayed_options.spoofmac);
1609 pos = 3;
1610 }
1611 }
1612 if (pos < 6) {
1613 get_random_bytes(mac_data + pos, 6 - pos);
1614 }
1615 /* Got the new MAC! */
1616 const char *vend = MACPrefix2Corp(mac_data);
1617 log_write(LOG_PLAIN,
1618 "Spoofing MAC address %02X:%02X:%02X:%02X:%02X:%02X (%s)\n",
1619 mac_data[0], mac_data[1], mac_data[2], mac_data[3], mac_data[4],
1620 mac_data[5], vend ? vend : "No registered vendor");
1621 o.setSpoofMACAddress(mac_data);
1622
1623 /* If they want to spoof the MAC address, we should at least make
1624 some effort to actually send raw ethernet frames rather than IP
1625 packets (which would use the real IP */
1626 if (o.sendpref != PACKET_SEND_IP_STRONG)
1627 o.sendpref = PACKET_SEND_ETH_STRONG;
1628 }
1629
1630 /* Warn if setuid/setgid. */
1631 check_setugid();
1632
1633 /* Remove any ports that are in the exclusion list */
1634 removepts(o.exclude_portlist, &ports);
1635
1636 /* By now, we've got our port lists. Give the user a warning if no
1637 * ports are specified for the type of scan being requested. Other things
1638 * (such as OS ident scan) might break cause no ports were specified, but
1639 * we've given our warning...
1640 */
1641 if ((o.TCPScan()) && ports.tcp_count == 0)
1642 error("WARNING: a TCP scan type was requested, but no tcp ports were specified. Skipping this scan type.");
1643 if (o.SCTPScan() && ports.sctp_count == 0)
1644 error("WARNING: a SCTP scan type was requested, but no sctp ports were specified. Skipping this scan type.");
1645 if (o.UDPScan() && ports.udp_count == 0)
1646 error("WARNING: UDP scan was requested, but no udp ports were specified. Skipping this scan type.");
1647 if (o.ipprotscan && ports.prot_count == 0)
1648 error("WARNING: protocol scan was requested, but no protocols were specified to be scanned. Skipping this scan type.");
1649
1650 if (o.pingtype & PINGTYPE_TCP && ports.syn_ping_count+ports.ack_ping_count == 0)
1651 error("WARNING: a TCP ping scan was requested, but after excluding requested TCP ports, none remain. Skipping this scan type.");
1652 if (o.pingtype & PINGTYPE_UDP && ports.udp_ping_count == 0)
1653 error("WARNING: a UDP ping scan was requested, but after excluding requested UDP ports, none remain. Skipping this scan type.");
1654 if (o.pingtype & PINGTYPE_SCTP_INIT && ports.sctp_ping_count == 0)
1655 error("WARNING: a SCTP ping scan was requested, but after excluding requested SCTP ports, none remain. Skipping this scan type.");
1656 if (o.pingtype & PINGTYPE_PROTO && ports.proto_ping_count == 0)
1657 error("WARNING: a IP Protocol ping scan was requested, but after excluding requested protocols, none remain. Skipping this scan type.");
1658
1659
1660 /* We need to find what interface to route through if:
1661 * --None have been specified AND
1662 * --We are root and doing tcp ping OR
1663 * --We are doing a raw sock scan and NOT pinging anyone */
1664 if (o.SourceSockAddr() && !*o.device) {
1665 if (ipaddr2devname(o.device, o.SourceSockAddr()) != 0) {
1666 fatal("Could not figure out what device to send the packet out on with the source address you gave me! If you are trying to sp00f your scan, this is normal, just give the -e eth0 or -e ppp0 or whatever. Otherwise you can still use -e, but I find it kind of fishy.");
1667 }
1668 }
1669
1670 if (*o.device && !o.SourceSockAddr()) {
1671 struct sockaddr_storage tmpsock;
1672 memset(&tmpsock, 0, sizeof(tmpsock));
1673 if (devname2ipaddr(o.device, &tmpsock) == -1) {
1674 fatal("I cannot figure out what source address to use for device %s, does it even exist?", o.device);
1675 }
1676 o.setSourceSockAddr(&tmpsock, sizeof(tmpsock));
1677 }
1678
1679 if (delayed_options.exclude_file) {
1680 o.excludefd = fopen(delayed_options.exclude_file, "r");
1681 if (!o.excludefd)
1682 fatal("Failed to open exclude file %s for reading", delayed_options.exclude_file);
1683 free(delayed_options.exclude_file);
1684 }
1685 o.exclude_spec = delayed_options.exclude_spec;
1686
1687 if (delayed_options.decoy_arguments) {
1688 char *p = delayed_options.decoy_arguments, *q;
1689 do {
1690 q = strchr(p, ',');
1691 if (q)
1692 *q = '\0';
1693 if (!strcasecmp(p, "me")) {
1694 if (o.decoyturn != -1)
1695 fatal("Can only use 'ME' as a decoy once.\n");
1696 o.decoyturn = o.numdecoys++;
1697 } else if (!strcasecmp(p, "rnd") || !strncasecmp(p, "rnd:", 4)) {
1698 if (delayed_options.af == AF_INET6)
1699 fatal("Random decoys can only be used with IPv4");
1700 int i = 1;
1701
1702 /* 'rnd:' is allowed and just gives them one */
1703 if (strlen(p) > 4)
1704 i = atoi(&p[4]);
1705
1706 if (i < 1)
1707 fatal("Bad 'rnd' decoy \"%s\"", p);
1708
1709 if (o.numdecoys + i >= MAX_DECOYS - 1)
1710 fatal("You are only allowed %d decoys (if you need more redefine MAX_DECOYS in nmap.h)", MAX_DECOYS);
1711
1712 while (i--) {
1713 do {
1714 ((struct sockaddr_in *)&o.decoys[o.numdecoys])->sin_addr.s_addr = get_random_u32();
1715 } while (ip_is_reserved(&((struct sockaddr_in *)&o.decoys[o.numdecoys])->sin_addr));
1716 o.numdecoys++;
1717 }
1718 } else {
1719 if (o.numdecoys >= MAX_DECOYS - 1)
1720 fatal("You are only allowed %d decoys (if you need more redefine MAX_DECOYS in nmap.h)", MAX_DECOYS);
1721
1722 /* Try to resolve it */
1723 struct sockaddr_storage decoytemp;
1724 size_t decoytemplen = sizeof(struct sockaddr_storage);
1725 int rc;
1726 if (delayed_options.af == AF_INET6){
1727 rc = resolve(p, 0, (sockaddr_storage*)&decoytemp, &decoytemplen, AF_INET6);
1728 }
1729 else
1730 rc = resolve(p, 0, (sockaddr_storage*)&decoytemp, &decoytemplen, AF_INET);
1731 if (rc != 0)
1732 fatal("Failed to resolve decoy host \"%s\": %s", p, gai_strerror(rc));
1733 o.decoys[o.numdecoys] = decoytemp;
1734 o.numdecoys++;
1735 }
1736 if (q) {
1737 *q = ',';
1738 p = q + 1;
1739 }
1740 } while (q);
1741 }
1742 /* Set up host address also in array of decoys! */
1743 if (o.decoyturn == -1) {
1744 o.decoyturn = (o.numdecoys == 0) ? 0 : get_random_uint() % o.numdecoys;
1745 o.numdecoys++;
1746 for (i = o.numdecoys - 1; i > o.decoyturn; i--)
1747 o.decoys[i] = o.decoys[i - 1];
1748 }
1749
1750 if (delayed_options.raw_scan_options && (!o.isr00t || o.connectscan)) {
1751 error("You have specified some options that require raw socket access.\n"
1752 "These options will not be honored %s.",
1753 o.isr00t ? "for TCP Connect scan" : "without the necessary privileges");
1754 }
1755 }
1756
1757 // Free some global memory allocations.
1758 // This is used for detecting memory leaks.
nmap_free_mem()1759 void nmap_free_mem() {
1760 PortList::freePortMap();
1761 cp_free();
1762 free_services();
1763 AllProbes::service_scan_free();
1764 traceroute_hop_cache_clear();
1765 nsock_set_default_engine(NULL);
1766 }
1767
nmap_main(int argc,char * argv[])1768 int nmap_main(int argc, char *argv[]) {
1769 int i;
1770 std::vector<Target *> Targets;
1771 time_t now;
1772 struct hostent *target = NULL;
1773 time_t timep;
1774 char mytime[128];
1775 struct addrset *exclude_group;
1776 #ifndef NOLUA
1777 /* Only NSE scripts can add targets */
1778 NewTargets *new_targets = NULL;
1779 /* Pre-Scan and Post-Scan script results datastructure */
1780 ScriptResults *script_scan_results = NULL;
1781 #endif
1782 unsigned int ideal_scan_group_sz = 0;
1783 Target *currenths;
1784 char myname[FQDN_LEN + 1];
1785 int sourceaddrwarning = 0; /* Have we warned them yet about unguessable
1786 source addresses? */
1787 unsigned int targetno;
1788 char hostname[FQDN_LEN + 1] = "";
1789 struct sockaddr_storage ss;
1790 size_t sslen;
1791 int err;
1792
1793 #ifdef LINUX
1794 /* Check for WSL and warn that things may not go well. */
1795 struct utsname uts;
1796 if (!uname(&uts)) {
1797 if (strstr(uts.release, "Microsoft") != NULL) {
1798 error("Warning: %s may not work correctly on Windows Subsystem for Linux.\n"
1799 "For best performance and accuracy, use the native Windows build from %s/download.html#windows.",
1800 NMAP_NAME, NMAP_URL);
1801 }
1802 }
1803 #endif
1804
1805 tzset();
1806 now = time(NULL);
1807 err = n_localtime(&now, &local_time);
1808 if (err) {
1809 fatal("n_localtime failed: %s", strerror(err));
1810 }
1811
1812 if (argc < 2){
1813 printusage();
1814 exit(-1);
1815 }
1816
1817 Targets.reserve(100);
1818 #ifdef WIN32
1819 win_pre_init();
1820 #endif
1821
1822 parse_options(argc, argv);
1823
1824 if (o.debugging)
1825 nbase_set_log(fatal, error);
1826 else
1827 nbase_set_log(fatal, NULL);
1828
1829
1830 tty_init(); // Put the keyboard in raw mode
1831
1832 #ifdef WIN32
1833 // Must come after parse_options because of --unprivileged
1834 // Must come before apply_delayed_options because it sets o.isr00t
1835 win_init();
1836 #endif
1837
1838 apply_delayed_options();
1839
1840 for (unsigned int i = 0; i < route_dst_hosts.size(); i++) {
1841 const char *dst;
1842 struct sockaddr_storage ss;
1843 struct route_nfo rnfo;
1844 size_t sslen;
1845 int rc;
1846
1847 dst = route_dst_hosts[i].c_str();
1848 rc = resolve(dst, 0, &ss, &sslen, o.af());
1849 if (rc != 0)
1850 fatal("Can't resolve %s: %s.", dst, gai_strerror(rc));
1851
1852 printf("%s\n", inet_ntop_ez(&ss, sslen));
1853
1854 if (!route_dst(&ss, &rnfo, o.device, o.SourceSockAddr())) {
1855 printf("Can't route %s (%s).", dst, inet_ntop_ez(&ss, sslen));
1856 } else {
1857 printf("%s %s", rnfo.ii.devname, rnfo.ii.devfullname);
1858 printf(" srcaddr %s", inet_ntop_ez(&rnfo.srcaddr, sizeof(rnfo.srcaddr)));
1859 if (rnfo.direct_connect)
1860 printf(" direct");
1861 else
1862 printf(" nexthop %s", inet_ntop_ez(&rnfo.nexthop, sizeof(rnfo.nexthop)));
1863 }
1864 printf("\n");
1865 }
1866 route_dst_hosts.clear();
1867
1868 if (delayed_options.iflist) {
1869 print_iflist();
1870 exit(0);
1871 }
1872
1873 /* If he wants to bounce off of an FTP site, that site better damn well be reachable! */
1874 if (o.bouncescan) {
1875 if (!inet_pton(AF_INET, ftp.server_name, &ftp.server)) {
1876 if ((target = gethostbyname(ftp.server_name)))
1877 memcpy(&ftp.server, target->h_addr_list[0], 4);
1878 else {
1879 fatal("Failed to resolve FTP bounce proxy hostname/IP: %s",
1880 ftp.server_name);
1881 }
1882 } else if (o.verbose) {
1883 log_write(LOG_STDOUT, "Resolved FTP bounce attack proxy to %s (%s).\n",
1884 ftp.server_name, inet_ntoa(ftp.server));
1885 }
1886 }
1887 fflush(stdout);
1888 fflush(stderr);
1889
1890 timep = time(NULL);
1891 err = n_ctime(mytime, sizeof(mytime), &timep);
1892 if (err) {
1893 fatal("n_ctime failed: %s", strerror(err));
1894 }
1895 chomp(mytime);
1896
1897 if (!o.resuming) {
1898 /* Brief info in case they forget what was scanned */
1899 char *xslfname = o.XSLStyleSheet();
1900 xml_start_document("nmaprun");
1901 if (xslfname) {
1902 xml_open_pi("xml-stylesheet");
1903 xml_attribute("href", "%s", xslfname);
1904 xml_attribute("type", "text/xsl");
1905 xml_close_pi();
1906 xml_newline();
1907 }
1908
1909 xml_start_comment();
1910 xml_write_escaped(" %s %s scan initiated %s as: %s ", NMAP_NAME, NMAP_VERSION, mytime, join_quoted(argv, argc).c_str());
1911 xml_end_comment();
1912 xml_newline();
1913
1914 xml_open_start_tag("nmaprun");
1915 xml_attribute("scanner", "nmap");
1916 xml_attribute("args", "%s", join_quoted(argv, argc).c_str());
1917 xml_attribute("start", "%lu", (unsigned long) timep);
1918 xml_attribute("startstr", "%s", mytime);
1919 xml_attribute("version", "%s", NMAP_VERSION);
1920 xml_attribute("xmloutputversion", NMAP_XMLOUTPUTVERSION);
1921 xml_close_start_tag();
1922 xml_newline();
1923
1924 output_xml_scaninfo_records(&ports);
1925
1926 xml_open_start_tag("verbose");
1927 xml_attribute("level", "%d", o.verbose);
1928 xml_close_empty_tag();
1929 xml_newline();
1930 xml_open_start_tag("debugging");
1931 xml_attribute("level", "%d", o.debugging);
1932 xml_close_empty_tag();
1933 xml_newline();
1934 } else {
1935 xml_start_tag("nmaprun", false);
1936 }
1937
1938 log_write(LOG_NORMAL | LOG_MACHINE, "# ");
1939 log_write(LOG_NORMAL | LOG_MACHINE, "%s %s scan initiated %s as: %s", NMAP_NAME, NMAP_VERSION, mytime, join_quoted(argv, argc).c_str());
1940 log_write(LOG_NORMAL | LOG_MACHINE, "\n");
1941
1942 /* Before we randomize the ports scanned, lets output them to machine
1943 parseable output */
1944 if (o.verbose)
1945 output_ports_to_machine_parseable_output(&ports);
1946
1947 #if defined(HAVE_SIGNAL) && defined(SIGPIPE)
1948 signal(SIGPIPE, SIG_IGN); /* ignore SIGPIPE so our program doesn't crash because
1949 of it, but we really shouldn't get an unexpected
1950 SIGPIPE */
1951 #endif
1952
1953 if (o.max_parallelism && (i = max_sd()) && i < o.max_parallelism) {
1954 error("WARNING: Your specified max_parallel_sockets of %d, but your system says it might only give us %d. Trying anyway", o.max_parallelism, i);
1955 }
1956
1957 if (o.debugging > 1)
1958 log_write(LOG_STDOUT, "The max # of sockets we are using is: %d\n", o.max_parallelism);
1959
1960 // At this point we should fully know our timing parameters
1961 if (o.debugging) {
1962 log_write(LOG_PLAIN, "--------------- Timing report ---------------\n");
1963 log_write(LOG_PLAIN, " hostgroups: min %d, max %d\n", o.minHostGroupSz(), o.maxHostGroupSz());
1964 log_write(LOG_PLAIN, " rtt-timeouts: init %d, min %d, max %d\n", o.initialRttTimeout(), o.minRttTimeout(), o.maxRttTimeout());
1965 log_write(LOG_PLAIN, " max-scan-delay: TCP %d, UDP %d, SCTP %d\n", o.maxTCPScanDelay(), o.maxUDPScanDelay(), o.maxSCTPScanDelay());
1966 log_write(LOG_PLAIN, " parallelism: min %d, max %d\n", o.min_parallelism, o.max_parallelism);
1967 log_write(LOG_PLAIN, " max-retries: %d, host-timeout: %ld\n", o.getMaxRetransmissions(), o.host_timeout);
1968 log_write(LOG_PLAIN, " min-rate: %g, max-rate: %g\n", o.min_packet_send_rate, o.max_packet_send_rate);
1969 log_write(LOG_PLAIN, "---------------------------------------------\n");
1970 }
1971
1972 /* Before we randomize the ports scanned, we must initialize PortList class. */
1973 if (o.ipprotscan)
1974 PortList::initializePortMap(IPPROTO_IP, ports.prots, ports.prot_count);
1975 if (o.TCPScan())
1976 PortList::initializePortMap(IPPROTO_TCP, ports.tcp_ports, ports.tcp_count);
1977 if (o.UDPScan())
1978 PortList::initializePortMap(IPPROTO_UDP, ports.udp_ports, ports.udp_count);
1979 if (o.SCTPScan())
1980 PortList::initializePortMap(IPPROTO_SCTP, ports.sctp_ports, ports.sctp_count);
1981
1982 if (o.randomize_ports) {
1983 if (ports.tcp_count) {
1984 shortfry(ports.tcp_ports, ports.tcp_count);
1985 // move a few more common ports closer to the beginning to speed scan
1986 random_port_cheat(ports.tcp_ports, ports.tcp_count);
1987 }
1988 if (ports.udp_count)
1989 shortfry(ports.udp_ports, ports.udp_count);
1990 if (ports.sctp_count)
1991 shortfry(ports.sctp_ports, ports.sctp_count);
1992 if (ports.prot_count)
1993 shortfry(ports.prots, ports.prot_count);
1994 }
1995
1996 exclude_group = addrset_new();
1997
1998 /* lets load our exclude list */
1999 if (o.excludefd != NULL) {
2000 load_exclude_file(exclude_group, o.excludefd);
2001 fclose(o.excludefd);
2002 }
2003 if (o.exclude_spec != NULL) {
2004 load_exclude_string(exclude_group, o.exclude_spec);
2005 }
2006
2007 if (o.debugging > 3)
2008 dumpExclude(exclude_group);
2009
2010 #ifndef NOLUA
2011 if (o.scriptupdatedb) {
2012 o.max_ips_to_scan = o.numhosts_scanned; // disable warnings?
2013 }
2014 if (o.servicescan)
2015 o.scriptversion = true;
2016 if (o.scriptversion || o.script || o.scriptupdatedb)
2017 open_nse();
2018
2019 /* Run the script pre-scanning phase */
2020 if (o.script) {
2021 new_targets = NewTargets::get();
2022 script_scan_results = get_script_scan_results_obj();
2023 script_scan(Targets, SCRIPT_PRE_SCAN);
2024 printscriptresults(script_scan_results, SCRIPT_PRE_SCAN);
2025 while (!script_scan_results->empty()) {
2026 script_scan_results->front().clear();
2027 script_scan_results->pop_front();
2028 }
2029 }
2030 #endif
2031
2032 if (o.ping_group_sz < o.minHostGroupSz())
2033 o.ping_group_sz = o.minHostGroupSz();
2034 HostGroupState hstate(o.ping_group_sz, o.randomize_hosts, argc, (const char **) argv);
2035
2036 do {
2037 ideal_scan_group_sz = determineScanGroupSize(o.numhosts_scanned, &ports);
2038
2039 while (Targets.size() < ideal_scan_group_sz) {
2040 o.current_scantype = HOST_DISCOVERY;
2041 currenths = nexthost(&hstate, exclude_group, &ports, o.pingtype);
2042 if (!currenths)
2043 break;
2044
2045 if (currenths->flags & HOST_UP && !o.listscan)
2046 o.numhosts_up++;
2047
2048 if ((o.noportscan && !o.traceroute
2049 #ifndef NOLUA
2050 && !o.script
2051 #endif
2052 ) || o.listscan) {
2053 /* We're done with the hosts */
2054 if (currenths->flags & HOST_UP || (o.verbose && !o.openOnly())) {
2055 xml_start_tag("host");
2056 write_host_header(currenths);
2057 printmacinfo(currenths);
2058 // if (currenths->flags & HOST_UP)
2059 // log_write(LOG_PLAIN,"\n");
2060 printtimes(currenths);
2061 xml_end_tag();
2062 xml_newline();
2063 log_flush_all();
2064 }
2065 delete currenths;
2066 o.numhosts_scanned++;
2067 if (!o.max_ips_to_scan || o.max_ips_to_scan > o.numhosts_scanned + Targets.size())
2068 continue;
2069 else
2070 break;
2071 }
2072
2073 if (o.spoofsource) {
2074 o.SourceSockAddr(&ss, &sslen);
2075 currenths->setSourceSockAddr(&ss, sslen);
2076 }
2077
2078 /* I used to check that !currenths->weird_responses, but in some
2079 rare cases, such IPs CAN be port successfully scanned and even
2080 connected to */
2081 if (!(currenths->flags & HOST_UP)) {
2082 if (o.verbose && (!o.openOnly() || currenths->ports.hasOpenPorts())) {
2083 xml_start_tag("host");
2084 write_host_header(currenths);
2085 xml_end_tag();
2086 xml_newline();
2087 }
2088 delete currenths;
2089 o.numhosts_scanned++;
2090 if (!o.max_ips_to_scan || o.max_ips_to_scan > o.numhosts_scanned + Targets.size())
2091 continue;
2092 else
2093 break;
2094 }
2095
2096 if (o.RawScan()) {
2097 if (currenths->SourceSockAddr(NULL, NULL) != 0) {
2098 if (o.SourceSockAddr(&ss, &sslen) == 0) {
2099 currenths->setSourceSockAddr(&ss, sslen);
2100 } else {
2101 if (gethostname(myname, FQDN_LEN) ||
2102 resolve(myname, 0, &ss, &sslen, o.af()) != 0)
2103 fatal("Cannot get hostname! Try using -S <my_IP_address> or -e <interface to scan through>\n");
2104
2105 o.setSourceSockAddr(&ss, sslen);
2106 currenths->setSourceSockAddr(&ss, sslen);
2107 if (! sourceaddrwarning) {
2108 error("WARNING: We could not determine for sure which interface to use, so we are guessing %s . If this is wrong, use -S <my_IP_address>.",
2109 inet_socktop(&ss));
2110 sourceaddrwarning = 1;
2111 }
2112 }
2113 }
2114
2115 if (!currenths->deviceName())
2116 fatal("Do not have appropriate device name for target");
2117
2118 /* Hosts in a group need to be somewhat homogeneous. Put this host in
2119 the next group if necessary. See target_needs_new_hostgroup for the
2120 details of when we need to split. */
2121 if (Targets.size() && target_needs_new_hostgroup(&Targets[0], Targets.size(), currenths)) {
2122 returnhost(&hstate);
2123 o.numhosts_up--;
2124 break;
2125 }
2126 o.decoys[o.decoyturn] = currenths->source();
2127 }
2128 Targets.push_back(currenths);
2129 }
2130
2131 if (Targets.size() == 0)
2132 break; /* Couldn't find any more targets */
2133
2134 // Set the variable for status printing
2135 o.numhosts_scanning = Targets.size();
2136
2137 // Our source must be set in decoy list because nexthost() call can
2138 // change it (that issue really should be fixed when possible)
2139 if (o.RawScan())
2140 o.decoys[o.decoyturn] = Targets[0]->source();
2141
2142 /* I now have the group for scanning in the Targets vector */
2143
2144 if (!o.noportscan) {
2145 // Ultra_scan sets o.scantype for us so we don't have to worry
2146 if (o.synscan)
2147 ultra_scan(Targets, &ports, SYN_SCAN);
2148
2149 if (o.ackscan)
2150 ultra_scan(Targets, &ports, ACK_SCAN);
2151
2152 if (o.windowscan)
2153 ultra_scan(Targets, &ports, WINDOW_SCAN);
2154
2155 if (o.finscan)
2156 ultra_scan(Targets, &ports, FIN_SCAN);
2157
2158 if (o.xmasscan)
2159 ultra_scan(Targets, &ports, XMAS_SCAN);
2160
2161 if (o.nullscan)
2162 ultra_scan(Targets, &ports, NULL_SCAN);
2163
2164 if (o.maimonscan)
2165 ultra_scan(Targets, &ports, MAIMON_SCAN);
2166
2167 if (o.udpscan)
2168 ultra_scan(Targets, &ports, UDP_SCAN);
2169
2170 if (o.connectscan)
2171 ultra_scan(Targets, &ports, CONNECT_SCAN);
2172
2173 if (o.sctpinitscan)
2174 ultra_scan(Targets, &ports, SCTP_INIT_SCAN);
2175
2176 if (o.sctpcookieechoscan)
2177 ultra_scan(Targets, &ports, SCTP_COOKIE_ECHO_SCAN);
2178
2179 if (o.ipprotscan)
2180 ultra_scan(Targets, &ports, IPPROT_SCAN);
2181
2182 /* These lame functions can only handle one target at a time */
2183 if (o.idlescan) {
2184 for (targetno = 0; targetno < Targets.size(); targetno++) {
2185 o.current_scantype = IDLE_SCAN;
2186 keyWasPressed(); // Check if a status message should be printed
2187 idle_scan(Targets[targetno], ports.tcp_ports,
2188 ports.tcp_count, o.idleProxy, &ports);
2189 }
2190 }
2191 if (o.bouncescan) {
2192 for (targetno = 0; targetno < Targets.size(); targetno++) {
2193 o.current_scantype = BOUNCE_SCAN;
2194 keyWasPressed(); // Check if a status message should be printed
2195 if (ftp.sd <= 0)
2196 ftp_anon_connect(&ftp);
2197 if (ftp.sd > 0)
2198 bounce_scan(Targets[targetno], ports.tcp_ports, ports.tcp_count, &ftp);
2199 }
2200 }
2201
2202 if (o.servicescan) {
2203 o.current_scantype = SERVICE_SCAN;
2204 service_scan(Targets);
2205 }
2206 }
2207
2208 if (o.osscan) {
2209 OSScan os_engine;
2210 os_engine.os_scan(Targets);
2211 }
2212
2213 if (o.traceroute)
2214 traceroute(Targets);
2215
2216 #ifndef NOLUA
2217 if (o.script || o.scriptversion) {
2218 script_scan(Targets, SCRIPT_SCAN);
2219 }
2220 #endif
2221
2222 for (targetno = 0; targetno < Targets.size(); targetno++) {
2223 currenths = Targets[targetno];
2224 /* Now I can do the output and such for each host */
2225 if (currenths->timedOut(NULL)) {
2226 xml_open_start_tag("host");
2227 xml_attribute("starttime", "%lu", (unsigned long) currenths->StartTime());
2228 xml_attribute("endtime", "%lu", (unsigned long) currenths->EndTime());
2229 xml_close_start_tag();
2230 write_host_header(currenths);
2231 xml_end_tag(); /* host */
2232 xml_newline();
2233 log_write(LOG_PLAIN, "Skipping host %s due to host timeout\n",
2234 currenths->NameIP(hostname, sizeof(hostname)));
2235 log_write(LOG_MACHINE, "Host: %s (%s)\tStatus: Timeout\n",
2236 currenths->targetipstr(), currenths->HostName());
2237 } else {
2238 /* --open means don't show any hosts without open ports. */
2239 if (o.openOnly() && !currenths->ports.hasOpenPorts())
2240 continue;
2241
2242 xml_open_start_tag("host");
2243 xml_attribute("starttime", "%lu", (unsigned long) currenths->StartTime());
2244 xml_attribute("endtime", "%lu", (unsigned long) currenths->EndTime());
2245 xml_close_start_tag();
2246 write_host_header(currenths);
2247 printportoutput(currenths, ¤ths->ports);
2248 printmacinfo(currenths);
2249 printosscanoutput(currenths);
2250 printserviceinfooutput(currenths);
2251 #ifndef NOLUA
2252 printhostscriptresults(currenths);
2253 #endif
2254 if (o.traceroute)
2255 printtraceroute(currenths);
2256 printtimes(currenths);
2257 log_write(LOG_PLAIN | LOG_MACHINE, "\n");
2258 xml_end_tag(); /* host */
2259 xml_newline();
2260 }
2261 }
2262 log_flush_all();
2263
2264 o.numhosts_scanned += Targets.size();
2265
2266 /* Free all of the Targets */
2267 while (!Targets.empty()) {
2268 currenths = Targets.back();
2269 delete currenths;
2270 Targets.pop_back();
2271 }
2272 o.numhosts_scanning = 0;
2273 } while (!o.max_ips_to_scan || o.max_ips_to_scan > o.numhosts_scanned);
2274
2275 #ifndef NOLUA
2276 if (o.script) {
2277 script_scan(Targets, SCRIPT_POST_SCAN);
2278 printscriptresults(script_scan_results, SCRIPT_POST_SCAN);
2279 while (!script_scan_results->empty()) {
2280 script_scan_results->front().clear();
2281 script_scan_results->pop_front();
2282 }
2283 delete new_targets;
2284 new_targets = NULL;
2285 }
2286 #endif
2287
2288 addrset_free(exclude_group);
2289
2290 if (o.inputfd != NULL)
2291 fclose(o.inputfd);
2292
2293 printdatafilepaths();
2294
2295 printfinaloutput();
2296
2297 free_scan_lists(&ports);
2298
2299 eth_close_cached();
2300
2301 if (o.release_memory) {
2302 nmap_free_mem();
2303 }
2304 return 0;
2305 }
2306
2307 /* Reads in a (normal or machine format) Nmap log file and gathers enough
2308 state to allow Nmap to continue where it left off. The important things
2309 it must gather are:
2310 1) The last host completed
2311 2) The command arguments
2312 */
2313
gather_logfile_resumption_state(char * fname,int * myargc,char *** myargv)2314 int gather_logfile_resumption_state(char *fname, int *myargc, char ***myargv) {
2315 char *filestr;
2316 s64 filelen;
2317 char nmap_arg_buffer[4096]; /* roughly aligned with arg_parse limit */
2318 struct sockaddr_storage *lastip = &o.resume_ip;
2319 int af = AF_INET; // default without -6 is ipv4
2320 size_t sslen;
2321 char *p, *q, *found, *lastipstr; /* I love C! */
2322 /* We mmap it read/write since we will change the last char to a newline if it is not already */
2323 filestr = mmapfile(fname, &filelen, O_RDWR);
2324 if (!filestr) {
2325 pfatal("Could not mmap() %s file", fname);
2326 }
2327
2328 if (filelen < 20) {
2329 fatal("Output file %s is too short -- no use resuming", fname);
2330 }
2331
2332 /* For now we terminate it with a NUL, but we will terminate the file with
2333 a '\n' later */
2334 filestr[filelen - 1] = '\0';
2335
2336 /* First goal is to find the nmap args */
2337 if ((p = strstr(filestr, " as: ")))
2338 p += 5;
2339 else
2340 fatal("Unable to parse supposed log file %s. Are you sure this is an Nmap output file?", fname);
2341 /* Skip the program name */
2342 while (*p && !isspace((int) (unsigned char) *p)){
2343 if (*p == '"' || *p == '\'') {
2344 /* Quoted, so find the matching quote.
2345 * TODO:Doesn't handle escaped quotes, but we don't generate them either. */
2346 p = strchr(p+1, *p);
2347 if (!p) {
2348 fatal("Unable to parse supposed log file %s: unclosed quote.", fname);
2349 }
2350 }
2351 else if (!strncasecmp(p, """, 6)) {
2352 /* We do XML unescaping later, but this is just special case of quoted
2353 * program name. */
2354 do {
2355 p = strstr(p+1, "&");
2356 if (!p) {
2357 fatal("Unable to parse supposed log file %s: unclosed quote.", fname);
2358 }
2359 } while (strncasecmp(p, """, 6));
2360 /* Only skip to the ';', because another increment happens below. */
2361 p += 5;
2362 }
2363 p++;
2364 }
2365 if (!*p)
2366 fatal("Unable to parse supposed log file %s. Sorry", fname);
2367 p++; /* Skip the space between program name and first arg */
2368 if (*p == '\n' || !*p)
2369 fatal("Unable to parse supposed log file %s. Sorry", fname);
2370
2371 q = strchr(p, '\n');
2372 if (!q || ((unsigned int) (q - p) >= sizeof(nmap_arg_buffer) - 32))
2373 fatal("Unable to parse supposed log file %s. Perhaps the Nmap execution had not finished at least one host? In that case there is no use \"resuming\"", fname);
2374
2375 strncpy(nmap_arg_buffer, "nmap --append-output ", sizeof(nmap_arg_buffer));
2376 if ((q - p) + 21 + 1 >= (int) sizeof(nmap_arg_buffer))
2377 fatal("0verfl0w");
2378 memcpy(nmap_arg_buffer + 21, p, q - p);
2379 nmap_arg_buffer[21 + q - p] = '\0';
2380
2381 q = strstr(nmap_arg_buffer, "-->");
2382 if (q) {
2383 *q = '\0';
2384 char *unescaped = xml_unescape(nmap_arg_buffer);
2385 if (sizeof(nmap_arg_buffer) < strlen(unescaped) + 1)
2386 fatal("0verfl0w");
2387 memcpy(nmap_arg_buffer, unescaped, strlen(unescaped) + 1);
2388 free(unescaped);
2389 }
2390
2391 if (strstr(nmap_arg_buffer, "--randomize-hosts") != NULL) {
2392 error("WARNING: You are attempting to resume a scan which used --randomize-hosts. Some hosts in the last randomized batch may be missed and others may be repeated once");
2393 }
2394
2395 *myargc = arg_parse(nmap_arg_buffer, myargv);
2396 if (*myargc == -1) {
2397 fatal("Unable to parse supposed log file %s. Sorry", fname);
2398 }
2399
2400 for (int i=0; i < *myargc; i++) {
2401 if (!strncmp("-4", (*myargv)[i], 2)) {
2402 af = AF_INET;
2403 }
2404 else if (!strncmp("-6", (*myargv)[i], 2)) {
2405 af = AF_INET6;
2406 }
2407 }
2408
2409 /* Now it is time to figure out the last IP that was scanned */
2410 q = p;
2411 found = NULL;
2412 /* Lets see if its a grepable log first (-oG) */
2413 while ((q = strstr(q, "\nHost: ")))
2414 found = q = q + 7;
2415
2416 if (found) {
2417 q = strchr(found, ' ');
2418 if (!q)
2419 fatal("Unable to parse supposed log file %s. Sorry", fname);
2420 *q = '\0';
2421 if (resolve_numeric(found, 0, lastip, &sslen, af) != 0)
2422 fatal("Unable to parse ip (%s) in supposed log file %s. Sorry", found, fname);
2423 *q = ' ';
2424 } else {
2425 /* Let's see if it's an XML log (-oX) */
2426 q = p;
2427 found = NULL;
2428 while ((q = strstr(q, "\n<address addr=\""))) {
2429 q += 16;
2430 found = strchr(q, '"');
2431 if (!found)
2432 fatal("Unable to parse supposed log file %s. Sorry", fname);
2433 if ((af == AF_INET && !strncmp("\" addrtype=\"ipv4\"", found, 17))
2434 || (af == AF_INET6 && !strncmp("\" addrtype=\"ipv6\"", found, 17))) {
2435 found = q;
2436 }
2437 }
2438 if (found) {
2439 q = strchr(found, '"');
2440 if (!q)
2441 fatal("Unable to parse supposed log file %s. Sorry", fname);
2442 *q = '\0';
2443 if (resolve_numeric(found, 0, lastip, &sslen, af) != 0)
2444 fatal("Unable to parse ip (%s) supposed log file %s. Sorry", found, fname);
2445 *q = '"';
2446 } else {
2447 /* OK, I guess (hope) it is a normal log then (-oN) */
2448 q = p;
2449 found = NULL;
2450 while ((q = strstr(q, "\nNmap scan report for ")))
2451 found = q = q + 22;
2452
2453 /* There may be some later IPs of the form :
2454 "Nmap scan report for florence (x.x.7.10)" (dns reverse lookup)
2455 or "Nmap scan report for x.x.7.10".
2456 */
2457 if (found) {
2458 q = strchr(found, '\n');
2459 if (!q)
2460 fatal("Unable to parse supposed log file %s. Sorry", fname);
2461 *q = '\0';
2462 p = strchr(found, '(');
2463 if (!p) { /* No DNS reverse lookup, found should already contain IP */
2464 lastipstr = strdup(found);
2465 } else { /* DNS reverse lookup, IP is between parentheses */
2466 *q = '\n';
2467 q--;
2468 *q = '\0';
2469 lastipstr = strdup(p + 1);
2470 }
2471 *q = p ? ')' : '\n'; /* recover changed chars */
2472 if (resolve_numeric(lastipstr, 0, lastip, &sslen, af) != 0)
2473 fatal("Unable to parse ip (%s) in supposed log file %s. Sorry", lastipstr, fname);
2474 free(lastipstr);
2475 } else {
2476 error("Warning: You asked for --resume but it doesn't look like any hosts in the log file were successfully scanned. Starting from the beginning.");
2477 lastip->ss_family = AF_UNSPEC;
2478 }
2479 }
2480 }
2481
2482 /* Ensure the log file ends with a newline */
2483 filestr[filelen - 1] = '\n';
2484 if (munmap(filestr, filelen) != 0)
2485 gh_perror("%s: error in munmap(%p, %ld)", __func__, filestr, filelen);
2486
2487 return 0;
2488 }
2489
2490
executable_dir(const char * argv0)2491 static char *executable_dir(const char *argv0) {
2492 char *path, *dir;
2493
2494 path = executable_path(argv0);
2495 if (path == NULL)
2496 return NULL;
2497 dir = path_get_dirname(path);
2498 free(path);
2499
2500 return dir;
2501 }
2502
2503 /* Returns true if the two given filenames refer to the same file. (Have the
2504 same device and inode number.) */
same_file(const char * filename_a,const char * filename_b)2505 static bool same_file(const char *filename_a, const char *filename_b) {
2506 struct stat stat_a, stat_b;
2507
2508 if (stat(filename_a, &stat_a) == -1)
2509 return false;
2510 if (stat(filename_b, &stat_b) == -1)
2511 return false;
2512
2513 return stat_a.st_dev == stat_b.st_dev && stat_a.st_ino == stat_b.st_ino;
2514 }
2515
2516 static int nmap_fetchfile_sub(char *filename_returned, int bufferlen, const char *file);
2517
2518 /* Search for a file in the standard data file locations. The result is stored
2519 in filename_returned, which must point to an allocated buffer of at least
2520 bufferlen bytes. Returns true iff the search should be considered finished
2521 (i.e., the caller shouldn't try to search anywhere else for the file).
2522
2523 Options like --servicedb and --versiondb set explicit locations for
2524 individual data files. If any of these were used those locations are checked
2525 first, and no other locations are checked.
2526
2527 After that, the following directories are searched in order:
2528 * --datadir
2529 * $NMAPDIR environment variable
2530 * User's home Nmap directory:
2531 - [Windows] %APPDATA%\nmap
2532 - [Non-Windows] ~/.nmap
2533 * The directory containing the nmap binary
2534 * [Non-Windows only]:
2535 - The directory containing the nmap binary plus "../share/nmap"
2536 - NMAPDATADIR (usually $prefix/share/nmap)
2537 */
nmap_fetchfile(char * filename_returned,int bufferlen,const char * file)2538 int nmap_fetchfile(char *filename_returned, int bufferlen, const char *file) {
2539 std::map<std::string, std::string>::iterator iter;
2540 int res;
2541
2542 /* Check the map of requested data file names. */
2543 iter = o.requested_data_files.find(file);
2544 if (iter != o.requested_data_files.end()) {
2545 Strncpy(filename_returned, iter->second.c_str(), bufferlen);
2546 /* If a special file name was requested, we must not return any other file
2547 name. Return a positive result even if the file doesn't exist or is not
2548 readable. It is the caller's responsibility to report the error if the
2549 file can't be accessed. */
2550 res = file_is_readable(filename_returned);
2551 return res != 0 ? res : 1;
2552 }
2553
2554 res = nmap_fetchfile_sub(filename_returned, bufferlen, file);
2555
2556 return res;
2557 }
2558
2559 #ifdef WIN32
nmap_fetchfile_userdir(char * buf,size_t buflen,const char * file)2560 static int nmap_fetchfile_userdir(char *buf, size_t buflen, const char *file) {
2561 char appdata[MAX_PATH];
2562 int res;
2563
2564 if (SHGetFolderPath(NULL, CSIDL_APPDATA, NULL, SHGFP_TYPE_CURRENT, appdata) != S_OK)
2565 return 0;
2566 res = Snprintf(buf, buflen, "%s\\nmap\\%s", appdata, file);
2567 if (res <= 0 || res >= buflen)
2568 return 0;
2569
2570 return file_is_readable(buf);
2571 }
2572 #else
nmap_fetchfile_userdir_uid(char * buf,size_t buflen,const char * file,int uid)2573 static int nmap_fetchfile_userdir_uid(char *buf, size_t buflen, const char *file, int uid) {
2574 struct passwd *pw;
2575 int res;
2576
2577 pw = getpwuid(uid);
2578 if (pw == NULL)
2579 return 0;
2580 res = Snprintf(buf, buflen, "%s/.nmap/%s", pw->pw_dir, file);
2581 if (res <= 0 || (size_t) res >= buflen)
2582 return 0;
2583
2584 return file_is_readable(buf);
2585 }
2586
nmap_fetchfile_userdir(char * buf,size_t buflen,const char * file)2587 static int nmap_fetchfile_userdir(char *buf, size_t buflen, const char *file) {
2588 int res;
2589
2590 res = nmap_fetchfile_userdir_uid(buf, buflen, file, getuid());
2591 if (res != 0)
2592 return res;
2593
2594 if (getuid() != geteuid()) {
2595 res = nmap_fetchfile_userdir_uid(buf, buflen, file, geteuid());
2596 if (res != 0)
2597 return res;
2598 }
2599
2600 return 0;
2601 }
2602 #endif
2603
nmap_fetchfile_sub(char * filename_returned,int bufferlen,const char * file)2604 static int nmap_fetchfile_sub(char *filename_returned, int bufferlen, const char *file) {
2605 char *dirptr;
2606 int res;
2607 int foundsomething = 0;
2608 char dot_buffer[512];
2609 static int warningcount = 0;
2610
2611 if (o.datadir) {
2612 res = Snprintf(filename_returned, bufferlen, "%s/%s", o.datadir, file);
2613 if (res > 0 && res < bufferlen) {
2614 foundsomething = file_is_readable(filename_returned);
2615 }
2616 }
2617
2618 if (!foundsomething && (dirptr = getenv("NMAPDIR"))) {
2619 res = Snprintf(filename_returned, bufferlen, "%s/%s", dirptr, file);
2620 if (res > 0 && res < bufferlen) {
2621 foundsomething = file_is_readable(filename_returned);
2622 }
2623 }
2624
2625 if (!foundsomething)
2626 foundsomething = nmap_fetchfile_userdir(filename_returned, bufferlen, file);
2627
2628 const char *argv0;
2629 char *dir;
2630
2631 argv0 = get_program_name();
2632 assert(argv0 != NULL);
2633 dir = executable_dir(argv0);
2634
2635 if (dir != NULL) {
2636 if (!foundsomething) { /* Try the nMap directory */
2637 res = Snprintf(filename_returned, bufferlen, "%s/%s", dir, file);
2638 if (res > 0 && res < bufferlen) {
2639 foundsomething = file_is_readable(filename_returned);
2640 }
2641 }
2642 #ifndef WIN32
2643 if (!foundsomething) {
2644 res = Snprintf(filename_returned, bufferlen, "%s/../share/nmap/%s", dir, file);
2645 if (res > 0 && res < bufferlen) {
2646 foundsomething = file_is_readable(filename_returned);
2647 }
2648 }
2649 #endif
2650 free(dir);
2651 }
2652
2653 #ifndef WIN32
2654 if (!foundsomething) {
2655 res = Snprintf(filename_returned, bufferlen, "%s/%s", NMAPDATADIR, file);
2656 if (res > 0 && res < bufferlen) {
2657 foundsomething = file_is_readable(filename_returned);
2658 }
2659 }
2660 #endif
2661
2662 if (foundsomething && (*filename_returned != '.')) {
2663 res = Snprintf(dot_buffer, sizeof(dot_buffer), "./%s", file);
2664 if (res > 0 && res < bufferlen) {
2665 if (file_is_readable(dot_buffer) && !same_file(filename_returned, dot_buffer)) {
2666 #ifdef WIN32
2667 if (warningcount++ < 1 && o.debugging)
2668 #else
2669 if (warningcount++ < 1)
2670 #endif
2671 error("Warning: File %s exists, but Nmap is using %s for security and consistency reasons. set NMAPDIR=. to give priority to files in your local directory (may affect the other data files too).", dot_buffer, filename_returned);
2672 }
2673 }
2674 }
2675
2676 if (foundsomething && o.debugging > 1)
2677 log_write(LOG_PLAIN, "Fetchfile found %s\n", filename_returned);
2678
2679 return foundsomething;
2680
2681 }
2682
2683 /* Extracts a whitespace-separated word from a string. Returns a zero-length
2684 string if there are too few words. */
get_word(const char * str,unsigned int n)2685 static std::string get_word(const char *str, unsigned int n) {
2686 const char *p, *q;
2687 unsigned int i;
2688
2689 p = str;
2690 for (i = 0; *p != '\0' && i <= n; i++) {
2691 while (isspace((int) (unsigned char) *p))
2692 p++;
2693 q = p;
2694 while (*q != '\0' && !isspace((int) (unsigned char) *q))
2695 q++;
2696 if (i == n)
2697 return std::string(p, q - p);
2698 p = q;
2699 }
2700
2701 return std::string();
2702 }
2703
2704 /* Helper for display_nmap_version. Tries to extract a word (presumably a
2705 version number) from a string, but if that fails, returns the whole string
2706 enclosed in parentheses as a failsafe. */
get_word_or_quote(const char * str,unsigned int n)2707 static std::string get_word_or_quote(const char *str, unsigned int n) {
2708 std::string word;
2709
2710 word = get_word(str, n);
2711 if (word.length() == 0)
2712 word = std::string("(") + str + std::string(")");
2713
2714 return word;
2715 }
2716
display_nmap_version()2717 static void display_nmap_version() {
2718 std::vector<std::string> with, without;
2719 unsigned int i;
2720
2721 #ifndef NOLUA
2722 #ifdef LUA_INCLUDED
2723 with.push_back(std::string("nmap-liblua-") + get_word_or_quote(LUA_RELEASE, 1));
2724 #else
2725 with.push_back(std::string("liblua-") + get_word_or_quote(LUA_RELEASE, 1));
2726 #endif
2727 #else
2728 without.push_back("liblua");
2729 #endif
2730
2731 #if HAVE_OPENSSL
2732 with.push_back(std::string("openssl-") + get_word_or_quote(OPENSSL_VERSION_TEXT, 1));
2733 #else
2734 without.push_back("openssl");
2735 #endif
2736
2737 #if HAVE_LIBSSH2
2738 #ifdef LIBSSH2_INCLUDED
2739 with.push_back(std::string("nmap-libssh2-") + get_word_or_quote(LIBSSH2_VERSION, 0));
2740 #else
2741 with.push_back(std::string("libssh2-") + get_word_or_quote(LIBSSH2_VERSION, 0));
2742 #endif
2743 #else
2744 without.push_back("libssh2");
2745 #endif
2746
2747 #if HAVE_LIBZ
2748 #ifdef ZLIB_INCLUDED
2749 with.push_back(std::string("nmap-libz-") + get_word_or_quote(ZLIB_VERSION, 0));
2750 #else
2751 with.push_back(std::string("libz-") + get_word_or_quote(ZLIB_VERSION, 0));
2752 #endif
2753 #else
2754 without.push_back("libz");
2755 #endif
2756
2757 #ifdef PCRE_INCLUDED
2758 with.push_back(std::string("nmap-libpcre-") + get_word_or_quote(pcre_version(), 0));
2759 #else
2760 with.push_back(std::string("libpcre-") + get_word_or_quote(pcre_version(), 0));
2761 #endif
2762
2763 #ifdef WIN32
2764 if (o.have_pcap) {
2765 const char *pcap_version = pcap_lib_version();
2766 const char *pcap_num = strpbrk(pcap_version, "0123456789");
2767 if (pcap_num == NULL)
2768 pcap_num = "(unknown)";
2769 std::string pcap_num_str (pcap_num, strcspn(pcap_num, ","));
2770 with.push_back(get_word_or_quote(pcap_version, 0) + std::string("-") + pcap_num_str);
2771 }
2772 #else
2773 const char *pcap_version = pcap_lib_version();
2774 std::string pcap_num_str = get_word_or_quote(pcap_version, 2);
2775 with.push_back(
2776 #ifdef PCAP_INCLUDED
2777 std::string("nmap-") +
2778 #endif
2779 get_word_or_quote(pcap_version, 0) + std::string("-") + pcap_num_str);
2780 #endif
2781
2782 #ifdef DNET_INCLUDED
2783 with.push_back(std::string("nmap-libdnet-") + DNET_VERSION);
2784 #else
2785 with.push_back(std::string("libdnet-") + DNET_VERSION);
2786 #endif
2787
2788 #if HAVE_IPV6
2789 with.push_back("ipv6");
2790 #else
2791 without.push_back("ipv6");
2792 #endif
2793
2794 log_write(LOG_STDOUT, "%s version %s ( %s )\n", NMAP_NAME, NMAP_VERSION, NMAP_URL);
2795 log_write(LOG_STDOUT, "Platform: %s\n", NMAP_PLATFORM);
2796 log_write(LOG_STDOUT, "Compiled with:");
2797 for (i = 0; i < with.size(); i++)
2798 log_write(LOG_STDOUT, " %s", with[i].c_str());
2799 log_write(LOG_STDOUT, "\n");
2800 log_write(LOG_STDOUT, "Compiled without:");
2801 for (i = 0; i < without.size(); i++)
2802 log_write(LOG_STDOUT, " %s", without[i].c_str());
2803 log_write(LOG_STDOUT, "\n");
2804 log_write(LOG_STDOUT, "Available nsock engines: %s\n", nsock_list_engines());
2805 }
2806