1 
2 /***************************************************************************
3  * NmapOps.h -- The NmapOps class contains global options, mostly based on *
4  * user-provided command-line settings.                                    *
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: NmapOps.h 38078 2020-10-02 16:12:22Z dmiller $ */
64 
65 #ifndef NMAP_OPS_H
66 #define NMAP_OPS_H
67 
68 #include "nmap.h" /* MAX_DECOYS */
69 #include "scan_lists.h"
70 #include "output.h" /* LOG_NUM_FILES */
71 #include <nbase.h>
72 #include <nsock.h>
73 #include <string>
74 #include <map>
75 #include <vector>
76 
77 struct FingerPrintDB;
78 struct FingerMatch;
79 
80 class NmapOps {
81  public:
82   NmapOps();
83   ~NmapOps();
84   void ReInit(); // Reinitialize the class to default state
setaf(int af)85   void setaf(int af) { addressfamily = af; }
af()86   int af() { return addressfamily; }
87   // no setpf() because it is based on setaf() values
88   int pf();
89   /* Returns 0 for success, nonzero if no source has been set or any other
90      failure */
91   int SourceSockAddr(struct sockaddr_storage *ss, size_t *ss_len);
92   /* Returns a const pointer to the source address if set, or NULL if unset. */
93   const struct sockaddr_storage *SourceSockAddr() const;
94   /* Note that it is OK to pass in a sockaddr_in or sockaddr_in6 casted
95      to sockaddr_storage */
96   void setSourceSockAddr(struct sockaddr_storage *ss, size_t ss_len);
97 
98 // The time this obj. was instantiated   or last ReInit()ed.
getStartTime()99   const struct timeval *getStartTime() { return &start_time; }
100   // Number of seconds since getStartTime().  The current time is an
101   // optional argument to avoid an extra gettimeofday() call.
102   float TimeSinceStart(const struct timeval *now=NULL);
103 
104 
105 
106   bool TCPScan(); /* Returns true if at least one chosen scan type is TCP */
107   bool UDPScan(); /* Returns true if at least one chosen scan type is UDP */
108   bool SCTPScan(); /* Returns true if at least one chosen scan type is SCTP */
109 
110   /* Returns true if at least one chosen scan type uses raw packets.
111      It does not currently cover cases such as TCP SYN ping scan which
112      can go either way based on whether the user is root or IPv6 is
113      being used.  It will return false in those cases where a RawScan
114      is not necessarily used. */
115   bool RawScan();
116   void ValidateOptions(); /* Checks that the options given are
117                              reasonable and consistent.  If they aren't, the
118                              function may bail out of Nmap or make small
119                              adjustments (quietly or with a warning to the
120                              user). */
121   int isr00t;
122   /* Whether we have pcap functions (can be false on Windows). */
123   bool have_pcap;
124   u8 debugging;
125   bool resuming;
126 
127 #define PACKET_SEND_NOPREF 1
128 #define PACKET_SEND_ETH_WEAK 2
129 #define PACKET_SEND_ETH_STRONG 4
130 #define PACKET_SEND_ETH 6
131 #define PACKET_SEND_IP_WEAK 8
132 #define PACKET_SEND_IP_STRONG 16
133 #define PACKET_SEND_IP 24
134 
135   /* How should we send raw IP packets?  Nmap can generally use either
136      ethernet or raw ip sockets.  Which is better depends on platform
137      and goals.  A _STRONG preference means that Nmap should use the
138      preferred method whenever it is possible (obviously it isn't
139      always possible -- sending ethernet frames won't work over a PPP
140      connection).  This is useful when the other type doesn't work at
141      all.  A _WEAK preference means that Nmap may use the other type
142      where it is substantially more efficient to do so. For example,
143      Nmap will still do an ARP ping scan of a local network even when
144      the pref is SEND_IP_WEAK */
145   int sendpref;
packetTrace()146   bool packetTrace() { return (debugging >= 3)? true : pTrace;  }
versionTrace()147   bool versionTrace() { return packetTrace()? true : vTrace;  }
148 #ifndef NOLUA
scriptTrace()149   bool scriptTrace() { return packetTrace()? true : scripttrace; }
150 #endif
151   // Note that packetTrace may turn on at high debug levels even if
152   // setPacketTrace(false) has been called
setPacketTrace(bool pt)153   void setPacketTrace(bool pt) { pTrace = pt;  }
setVersionTrace(bool vt)154   void setVersionTrace(bool vt) { vTrace = vt;  }
openOnly()155   bool openOnly() { return open_only; }
setOpenOnly(bool oo)156   void setOpenOnly(bool oo) { open_only = oo; }
157   u8 verbose;
158   /* The requested minimum packet sending rate, or 0.0 if unset. */
159   float min_packet_send_rate;
160   /* The requested maximum packet sending rate, or 0.0 if unset. */
161   float max_packet_send_rate;
162   /* The requested auto stats printing interval, or 0.0 if unset. */
163   float stats_interval;
164   bool randomize_hosts;
165   bool randomize_ports;
166   bool spoofsource; /* -S used */
167   bool fastscan;
168   char device[64];
169   int ping_group_sz;
170   bool nogcc; /* Turn off group congestion control with --nogcc */
171   bool generate_random_ips; /* -iR option */
172   FingerPrintDB *reference_FPs; /* Used in the new OS scan system. */
173   std::vector<FingerMatch> os_labels_ipv6;
174   u16 magic_port; /* The source port set by -g or --source-port. */
175   bool magic_port_set; /* Was this set by user? */
176 
177   /* Scan timing/politeness issues */
178   int timing_level; // 0-5, corresponding to Paranoid, Sneaky, Polite, Normal, Aggressive, Insane
179   int max_parallelism; // 0 means it has not been set
180   int min_parallelism; // 0 means it has not been set
181   double topportlevel; // -1 means it has not been set
182 
183   /* The maximum number of OS detection (gen2) tries we will make
184      without any matches before giving up on a host.  We may well give
185      up after fewer tries anyway, particularly if the target isn't
186      ideal for unknown fingerprint submissions */
maxOSTries()187   int maxOSTries() { return max_os_tries; }
188   void setMaxOSTries(int mot);
189 
190   /* These functions retrieve and set the Round Trip Time timeouts, in
191    milliseconds.  The set versions do extra processing to insure sane
192    values and to adjust each other to insure consistence (e.g. that
193    max is always at least as high as min) */
maxRttTimeout()194   int maxRttTimeout() { return max_rtt_timeout; }
minRttTimeout()195   int minRttTimeout() { return min_rtt_timeout; }
initialRttTimeout()196   int initialRttTimeout() { return initial_rtt_timeout; }
197   void setMaxRttTimeout(int rtt);
198   void setMinRttTimeout(int rtt);
199   void setInitialRttTimeout(int rtt);
200   void setMaxRetransmissions(int max_retransmit);
getMaxRetransmissions()201   unsigned int getMaxRetransmissions() { return max_retransmissions; }
202 
203   /* Similar functions for Host group size */
minHostGroupSz()204   int minHostGroupSz() { return min_host_group_sz; }
maxHostGroupSz()205   int maxHostGroupSz() { return max_host_group_sz; }
206   void setMinHostGroupSz(unsigned int sz);
207   void setMaxHostGroupSz(unsigned int sz);
maxTCPScanDelay()208   unsigned int maxTCPScanDelay() { return max_tcp_scan_delay; }
maxUDPScanDelay()209   unsigned int maxUDPScanDelay() { return max_udp_scan_delay; }
maxSCTPScanDelay()210   unsigned int maxSCTPScanDelay() { return max_sctp_scan_delay; }
setMaxTCPScanDelay(unsigned int delayMS)211   void setMaxTCPScanDelay(unsigned int delayMS) { max_tcp_scan_delay = delayMS; }
setMaxUDPScanDelay(unsigned int delayMS)212   void setMaxUDPScanDelay(unsigned int delayMS) { max_udp_scan_delay = delayMS; }
setMaxSCTPScanDelay(unsigned int delayMS)213   void setMaxSCTPScanDelay(unsigned int delayMS) { max_sctp_scan_delay = delayMS; }
214 
215   /* Sets the Name of the XML stylesheet to be printed in XML output.
216      If this is never called, a default stylesheet distributed with
217      Nmap is used.  If you call it with NULL as the xslname, no
218      stylesheet line is printed. */
219   void setXSLStyleSheet(const char *xslname);
220   /* Returns the full path or URL that should be printed in the XML
221      output xml-stylesheet element.  Returns NULL if the whole element
222      should be skipped */
223   char *XSLStyleSheet();
224 
225   /* Sets the spoofed MAC address */
226   void setSpoofMACAddress(u8 *mac_data);
227   /* Gets the spoofed MAC address, but returns NULL if it hasn't been set */
spoofMACAddress()228   const u8 *spoofMACAddress() { return spoof_mac_set? spoof_mac : NULL; }
229 
230   unsigned int max_ips_to_scan; // Used for Random input (-iR) to specify how
231                        // many IPs to try before stopping. 0 means unlimited.
232   int extra_payload_length; /* These two are for --data-length op */
233   char *extra_payload;
234   unsigned long host_timeout;
235   /* Delay between probes, in milliseconds */
236   unsigned int scan_delay;
237   bool open_only;
238 
239   int scanflags; /* if not -1, this value should dictate the TCP flags
240                     for the core portscanning routine (eg to change a
241                     FIN scan into a PSH scan.  Sort of a hack, but can
242                     be very useful sometimes. */
243 
244   bool defeat_rst_ratelimit; /* Solaris 9 rate-limits RSTs so scanning is very
245             slow against it. If we don't distinguish between closed and filtered ports,
246             we can get the list of open ports very fast */
247 
248   bool defeat_icmp_ratelimit; /* If a host rate-limits ICMP responses, then scanning
249             is very slow against it. This option prevents Nmap to adjust timing
250             when it changes the port's state because of ICMP response, as the latter
251             might be rate-limited. Doing so we can get scan results faster. */
252 
253   struct sockaddr_storage resume_ip; /* The last IP in the log file if user
254                                requested --restore .  Otherwise
255                                resume_ip.ss_family == AF_UNSPEC.  Also
256                                Target::next_target will eventually set it
257                                to AF_UNSPEC. */
258 
259   // Version Detection Options
260   bool override_excludeports;
261   int version_intensity;
262 
263   struct sockaddr_storage decoys[MAX_DECOYS];
264   bool osscan_limit; /* Skip OS Scan if no open or no closed TCP ports */
265   bool osscan_guess;   /* Be more aggressive in guessing OS type */
266   int numdecoys;
267   int decoyturn;
268   bool osscan;
269   bool servicescan;
270   int pingtype;
271   int listscan;
272   int fragscan; /* 0 or MTU (without IPv4 header size) */
273   int ackscan;
274   int bouncescan;
275   int connectscan;
276   int finscan;
277   int idlescan;
278   char* idleProxy; /* The idle host used to "Proxy" an idle scan */
279   int ipprotscan;
280   int maimonscan;
281   int nullscan;
282   int synscan;
283   int udpscan;
284   int sctpinitscan;
285   int sctpcookieechoscan;
286   int windowscan;
287   int xmasscan;
288   bool noresolve;
289   bool noportscan;
290   bool append_output; /* Append to any output files rather than overwrite */
291   FILE *logfd[LOG_NUM_FILES];
292   FILE *nmap_stdout; /* Nmap standard output */
293   int ttl; // Time to live
294   bool badsum;
295   char *datadir;
296   /* A map from abstract data file names like "nmap-services" and "nmap-os-db"
297      to paths which have been requested by the user. nmap_fetchfile will return
298      the file names defined in this map instead of searching for a matching
299      file. */
300   std::map<std::string, std::string> requested_data_files;
301   /* A map from data file names to the paths at which they were actually found.
302      Only files that were actually read should be in this map. */
303   std::map<std::string, std::string> loaded_data_files;
304   bool mass_dns;
305   bool always_resolve;
306   bool resolve_all;
307   char *dns_servers;
308 
309   /* Do IPv4 ARP or IPv6 ND scan of directly connected Ethernet hosts, even if
310      non-ARP host discovery options are used? This is normally more efficient,
311      not only because ARP/ND scan is faster, but because we need the MAC
312      addresses provided by ARP or ND scan in order to do IP-based host discovery
313      anyway. But when a network uses proxy ARP, all hosts will appear to be up
314      unless you do an IP host discovery on them. This option is true by default. */
315   bool implicitARPPing;
316 
317   // If true, write <os><osclass/><osmatch/></os> as in xmloutputversion 1.03
318   // rather than <os><osmatch><osclass/></osmatch></os> as in 1.04 and later.
319   bool deprecated_xml_osclass;
320 
321   bool traceroute;
322   bool reason;
323   bool adler32;
324   FILE *excludefd;
325   char *exclude_spec;
326   FILE *inputfd;
327   char *portlist; /* Ports list specified by user */
328   char *exclude_portlist; /* exclude-ports list specified by user */
329 
330   nsock_proxychain proxy_chain;
331   bool discovery_ignore_rst; /* host discovery should not consider TCP RST packet responses as a live asset */
332 
333 #ifndef NOLUA
334   bool script;
335   char *scriptargs;
336   char *scriptargsfile;
337   bool scriptversion;
338   bool scripttrace;
339   bool scriptupdatedb;
340   bool scripthelp;
341   double scripttimeout;
342   void chooseScripts(char* argument);
343   std::vector<std::string> chosenScripts;
344 #endif
345 
346   /* ip options used in build_*_raw() */
347   u8 *ipoptions;
348   int ipoptionslen;
349   int ipopt_firsthop;	// offset in ipoptions where is first hop for source/strict routing
350   int ipopt_lasthop;	// offset in ipoptions where is space for targets ip for source/strict routing
351 
352   // Statistics Options set in nmap.cc
353   unsigned int numhosts_scanned;
354   unsigned int numhosts_up;
355   int numhosts_scanning;
356   stype current_scantype;
357   bool noninteractive;
358 
359   bool release_memory;	/* suggest to release memory before quitting. used to find memory leaks. */
360  private:
361   int max_os_tries;
362   int max_rtt_timeout;
363   int min_rtt_timeout;
364   int initial_rtt_timeout;
365   unsigned int max_retransmissions;
366   unsigned int max_tcp_scan_delay;
367   unsigned int max_udp_scan_delay;
368   unsigned int max_sctp_scan_delay;
369   unsigned int min_host_group_sz;
370   unsigned int max_host_group_sz;
371   void Initialize();
372   int addressfamily; /*  Address family:  AF_INET or AF_INET6 */
373   struct sockaddr_storage sourcesock;
374   size_t sourcesocklen;
375   struct timeval start_time;
376   bool pTrace; // Whether packet tracing has been enabled
377   bool vTrace; // Whether version tracing has been enabled
378   bool xsl_stylesheet_set;
379   char *xsl_stylesheet;
380   u8 spoof_mac[6];
381   bool spoof_mac_set;
382 };
383 
384 #endif
385