PageRenderTime 70ms CodeModel.GetById 28ms RepoModel.GetById 0ms app.codeStats 2ms

/scan_engine.cc

https://github.com/prakashgamit/nmap
C++ | 5982 lines | 4366 code | 577 blank | 1039 comment | 1703 complexity | 3a58e591348b4976ae70c3d885b87bb6 MD5 | raw file
Possible License(s): BSD-3-Clause, GPL-2.0, LGPL-2.0, LGPL-2.1

Large files files are truncated, but you can click here to view the full file

  1. /***************************************************************************
  2. * scan_engine.cc -- Includes much of the "engine" functions for scanning, *
  3. * such as ultra_scan. It also includes dependant functions such as those *
  4. * for collecting SYN/connect scan responses. *
  5. * *
  6. ***********************IMPORTANT NMAP LICENSE TERMS************************
  7. * *
  8. * The Nmap Security Scanner is (C) 1996-2013 Insecure.Com LLC. Nmap is *
  9. * also a registered trademark of Insecure.Com LLC. This program is free *
  10. * software; you may redistribute and/or modify it under the terms of the *
  11. * GNU General Public License as published by the Free Software *
  12. * Foundation; Version 2 ("GPL"), BUT ONLY WITH ALL OF THE CLARIFICATIONS *
  13. * AND EXCEPTIONS DESCRIBED HEREIN. This guarantees your right to use, *
  14. * modify, and redistribute this software under certain conditions. If *
  15. * you wish to embed Nmap technology into proprietary software, we sell *
  16. * alternative licenses (contact sales@nmap.com). Dozens of software *
  17. * vendors already license Nmap technology such as host discovery, port *
  18. * scanning, OS detection, version detection, and the Nmap Scripting *
  19. * Engine. *
  20. * *
  21. * Note that the GPL places important restrictions on "derivative works", *
  22. * yet it does not provide a detailed definition of that term. To avoid *
  23. * misunderstandings, we interpret that term as broadly as copyright law *
  24. * allows. For example, we consider an application to constitute a *
  25. * derivative work for the purpose of this license if it does any of the *
  26. * following with any software or content covered by this license *
  27. * ("Covered Software"): *
  28. * *
  29. * o Integrates source code from Covered Software. *
  30. * *
  31. * o Reads or includes copyrighted data files, such as Nmap's nmap-os-db *
  32. * or nmap-service-probes. *
  33. * *
  34. * o Is designed specifically to execute Covered Software and parse the *
  35. * results (as opposed to typical shell or execution-menu apps, which will *
  36. * execute anything you tell them to). *
  37. * *
  38. * o Includes Covered Software in a proprietary executable installer. The *
  39. * installers produced by InstallShield are an example of this. Including *
  40. * Nmap with other software in compressed or archival form does not *
  41. * trigger this provision, provided appropriate open source decompression *
  42. * or de-archiving software is widely available for no charge. For the *
  43. * purposes of this license, an installer is considered to include Covered *
  44. * Software even if it actually retrieves a copy of Covered Software from *
  45. * another source during runtime (such as by downloading it from the *
  46. * Internet). *
  47. * *
  48. * o Links (statically or dynamically) to a library which does any of the *
  49. * above. *
  50. * *
  51. * o Executes a helper program, module, or script to do any of the above. *
  52. * *
  53. * This list is not exclusive, but is meant to clarify our interpretation *
  54. * of derived works with some common examples. Other people may interpret *
  55. * the plain GPL differently, so we consider this a special exception to *
  56. * the GPL that we apply to Covered Software. Works which meet any of *
  57. * these conditions must conform to all of the terms of this license, *
  58. * particularly including the GPL Section 3 requirements of providing *
  59. * source code and allowing free redistribution of the work as a whole. *
  60. * *
  61. * As another special exception to the GPL terms, Insecure.Com LLC grants *
  62. * permission to link the code of this program with any version of the *
  63. * OpenSSL library which is distributed under a license identical to that *
  64. * listed in the included docs/licenses/OpenSSL.txt file, and distribute *
  65. * linked combinations including the two. *
  66. * *
  67. * Any redistribution of Covered Software, including any derived works, *
  68. * must obey and carry forward all of the terms of this license, including *
  69. * obeying all GPL rules and restrictions. For example, source code of *
  70. * the whole work must be provided and free redistribution must be *
  71. * allowed. All GPL references to "this License", are to be treated as *
  72. * including the terms and conditions of this license text as well. *
  73. * *
  74. * Because this license imposes special exceptions to the GPL, Covered *
  75. * Work may not be combined (even as part of a larger work) with plain GPL *
  76. * software. The terms, conditions, and exceptions of this license must *
  77. * be included as well. This license is incompatible with some other open *
  78. * source licenses as well. In some cases we can relicense portions of *
  79. * Nmap or grant special permissions to use it in other open source *
  80. * software. Please contact fyodor@nmap.org with any such requests. *
  81. * Similarly, we don't incorporate incompatible open source software into *
  82. * Covered Software without special permission from the copyright holders. *
  83. * *
  84. * If you have any questions about the licensing restrictions on using *
  85. * Nmap in other works, are happy to help. As mentioned above, we also *
  86. * offer alternative license to integrate Nmap into proprietary *
  87. * applications and appliances. These contracts have been sold to dozens *
  88. * of software vendors, and generally include a perpetual license as well *
  89. * as providing for priority support and updates. They also fund the *
  90. * continued development of Nmap. Please email sales@nmap.com for further *
  91. * information. *
  92. * *
  93. * If you have received a written license agreement or contract for *
  94. * Covered Software stating terms other than these, you may choose to use *
  95. * and redistribute Covered Software under those terms instead of these. *
  96. * *
  97. * Source is provided to this software because we believe users have a *
  98. * right to know exactly what a program is going to do before they run it. *
  99. * This also allows you to audit the software for security holes (none *
  100. * have been found so far). *
  101. * *
  102. * Source code also allows you to port Nmap to new platforms, fix bugs, *
  103. * and add new features. You are highly encouraged to send your changes *
  104. * to the dev@nmap.org mailing list for possible incorporation into the *
  105. * main distribution. By sending these changes to Fyodor or one of the *
  106. * Insecure.Org development mailing lists, or checking them into the Nmap *
  107. * source code repository, it is understood (unless you specify otherwise) *
  108. * that you are offering the Nmap Project (Insecure.Com LLC) the *
  109. * unlimited, non-exclusive right to reuse, modify, and relicense the *
  110. * code. Nmap will always be available Open Source, but this is important *
  111. * because the inability to relicense code has caused devastating problems *
  112. * for other Free Software projects (such as KDE and NASM). We also *
  113. * occasionally relicense the code to third parties as discussed above. *
  114. * If you wish to specify special license conditions of your *
  115. * contributions, just say so when you send them. *
  116. * *
  117. * This program is distributed in the hope that it will be useful, but *
  118. * WITHOUT ANY WARRANTY; without even the implied warranty of *
  119. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the Nmap *
  120. * license file for more details (it's in a COPYING file included with *
  121. * Nmap, and also available from https://svn.nmap.org/nmap/COPYING *
  122. * *
  123. ***************************************************************************/
  124. /* $Id$ */
  125. #ifdef WIN32
  126. #include "nmap_winconfig.h"
  127. #endif
  128. #include "portreasons.h"
  129. #include <dnet.h>
  130. #include "scan_engine.h"
  131. #include "timing.h"
  132. #include "NmapOps.h"
  133. #include "nmap_tty.h"
  134. #include "payload.h"
  135. #include "Target.h"
  136. #include "targets.h"
  137. #include "utils.h"
  138. #include "struct_ip.h"
  139. #include <math.h>
  140. #include <list>
  141. #include <map>
  142. extern NmapOps o;
  143. class UltraScanInfo;
  144. /* We encode per-probe information like the tryno and pingseq in the source
  145. port, for protocols that use ports. (Except when o.magic_port_set is
  146. true--then we honor the requested source port.) The tryno and pingseq are
  147. encoded as offsets from base_port, a base source port number (see
  148. sport_encode and sport_decode). To avoid interpreting a late response from a
  149. previous invocation of ultra_scan as a response for the same port in the
  150. current invocation, we increase base_port by a healthy amount designed to be
  151. greater than any offset likely to be used by a probe, each time ultra_scan is
  152. run.
  153. If we don't increase the base port, then there is the risk of something like
  154. the following happening:
  155. 1. Nmap sends an ICMP echo and a TCP ACK probe to port 80 for host discovery.
  156. 2. Nmap receives an ICMP echo reply and marks the host up.
  157. 3. Nmap sends a TCP SYN probe to port 80 for port scanning.
  158. 4. Nmap finally receives a delayed TCP RST in response to its earlier ACK
  159. probe, and wrongly marks port 80 as closed. */
  160. static u16 base_port;
  161. /* Clamp n to the range [min, max) in a modular fashion. */
  162. static int mod_offset(int n, int min, int max) {
  163. assert(min < max);
  164. n = (n - min) % (max - min);
  165. if (n < 0)
  166. n += max - min;
  167. return n + min;
  168. }
  169. /* Change base_port to a new number in a safe port range that is unlikely to
  170. conflict with nearby past or future invocations of ultra_scan. */
  171. static void increment_base_port() {
  172. static bool initialized = false;
  173. if (!initialized) {
  174. base_port = mod_offset(get_random_uint(), 33000, 65536 - 256);
  175. initialized = true;
  176. } else {
  177. base_port = mod_offset(base_port + 256, 33000, 65536 - 256);
  178. }
  179. }
  180. /* A few extra performance tuning parameters specific to ultra_scan. */
  181. struct ultra_scan_performance_vars : public scan_performance_vars {
  182. /* When a successful ping response comes back, it counts as this many
  183. "normal" responses, because the fact that pings are necessary means
  184. we aren't getting much input. */
  185. int ping_magnifier;
  186. /* Try to send a scanping if no response has been received from a target host
  187. in this many usecs */
  188. int pingtime;
  189. unsigned int tryno_cap; /* The maximum trynumber (starts at zero) allowed */
  190. void init() {
  191. scan_performance_vars::init();
  192. ping_magnifier = 3;
  193. ping_magnifier = 3;
  194. pingtime = 1250000;
  195. tryno_cap = o.getMaxRetransmissions();
  196. }
  197. };
  198. static const char *pspectype2ascii(int type) {
  199. switch (type) {
  200. case PS_NONE:
  201. return "NONE";
  202. case PS_TCP:
  203. return "TCP";
  204. case PS_UDP:
  205. return "UDP";
  206. case PS_SCTP:
  207. return "SCTP";
  208. case PS_PROTO:
  209. return "IP Proto";
  210. case PS_ICMP:
  211. return "ICMP";
  212. case PS_ARP:
  213. return "ARP";
  214. case PS_ICMPV6:
  215. return "ICMPv6";
  216. case PS_ND:
  217. return "ND";
  218. case PS_CONNECTTCP:
  219. return "connect";
  220. default:
  221. fatal("%s: Unknown type: %d", __func__, type);
  222. }
  223. return ""; // Unreached
  224. }
  225. struct ppkt { /* Beginning of ICMP Echo/Timestamp header */
  226. u8 type;
  227. u8 code;
  228. u16 checksum;
  229. u16 id;
  230. u16 seq;
  231. };
  232. class ConnectProbe {
  233. public:
  234. ConnectProbe();
  235. ~ConnectProbe();
  236. int sd; /* Socket descriptor used for connection. -1 if not valid. */
  237. };
  238. struct IPExtraProbeData_icmp {
  239. u16 ident;
  240. };
  241. struct IPExtraProbeData_tcp {
  242. u16 sport;
  243. u32 seq; /* host byte order (like the other fields */
  244. };
  245. struct IPExtraProbeData_udp {
  246. u16 sport;
  247. };
  248. struct IPExtraProbeData_sctp {
  249. u16 sport;
  250. u32 vtag;
  251. };
  252. struct IPExtraProbeData {
  253. u16 ipid; /* host byte order */
  254. union {
  255. struct IPExtraProbeData_icmp icmp;
  256. struct IPExtraProbeData_tcp tcp;
  257. struct IPExtraProbeData_udp udp;
  258. struct IPExtraProbeData_sctp sctp;
  259. } pd;
  260. };
  261. /* At least for now, I'll just use this like a struct and access
  262. all the data members directly */
  263. class UltraProbe {
  264. public:
  265. UltraProbe();
  266. ~UltraProbe();
  267. enum UPType { UP_UNSET, UP_IP, UP_CONNECT, UP_ARP, UP_ND } type; /* The type of probe this is */
  268. /* Sets this UltraProbe as type UP_IP and creates & initializes the
  269. internal IPProbe. The relevent probespec is necessary for setIP
  270. because pspec.type is ambiguous with just the ippacket (e.g. a
  271. tcp packet could be PS_PROTO or PS_TCP). */
  272. void setIP(u8 *ippacket, u32 iplen, const probespec *pspec);
  273. /* Sets this UltraProbe as type UP_CONNECT, preparing to connect to given
  274. port number*/
  275. void setConnect(u16 portno);
  276. /* Pass an arp packet, including ethernet header. Must be 42bytes */
  277. void setARP(u8 *arppkt, u32 arplen);
  278. void setND(u8 *ndpkt, u32 ndlen);
  279. // The 4 accessors below all return in HOST BYTE ORDER
  280. // source port used if TCP, UDP or SCTP
  281. u16 sport() const {
  282. switch (mypspec.proto) {
  283. case IPPROTO_TCP:
  284. return probes.IP.pd.tcp.sport;
  285. case IPPROTO_UDP:
  286. return probes.IP.pd.udp.sport;
  287. case IPPROTO_SCTP:
  288. return probes.IP.pd.sctp.sport;
  289. default:
  290. return 0;
  291. }
  292. /* not reached */
  293. }
  294. // destination port used if TCP, UDP or SCTP
  295. u16 dport() const {
  296. switch (mypspec.proto) {
  297. case IPPROTO_TCP:
  298. return mypspec.pd.tcp.dport;
  299. case IPPROTO_UDP:
  300. return mypspec.pd.udp.dport;
  301. case IPPROTO_SCTP:
  302. return mypspec.pd.sctp.dport;
  303. default:
  304. /* dport() can get called for other protos if we
  305. * get ICMP responses during IP proto scans. */
  306. return 0;
  307. }
  308. /* not reached */
  309. }
  310. u16 ipid() const {
  311. return probes.IP.ipid;
  312. }
  313. u16 icmpid() const; // ICMP ident if protocol is ICMP
  314. u32 tcpseq() const; // TCP sequence number if protocol is TCP
  315. u32 sctpvtag() const; // SCTP vtag if protocol is SCTP
  316. /* Number, such as IPPROTO_TCP, IPPROTO_UDP, etc. */
  317. u8 protocol() const {
  318. return mypspec.proto;
  319. }
  320. ConnectProbe *CP() {
  321. return probes.CP; // if type == UP_CONNECT
  322. }
  323. // Arpprobe removed because not used.
  324. // ArpProbe *AP() { return probes.AP; } // if UP_ARP
  325. // Returns the protocol number, such as IPPROTO_TCP, or IPPROTO_UDP, by
  326. // reading the appropriate fields of the probespec.
  327. /* Get general details about the probe */
  328. const probespec *pspec() const {
  329. return &mypspec;
  330. }
  331. /* Returns true if the given tryno and pingseq match those within this
  332. probe. */
  333. bool check_tryno_pingseq(unsigned int tryno, unsigned int pingseq) const {
  334. return (pingseq == 0 && tryno == this->tryno) || (pingseq > 0 && pingseq == this->pingseq);
  335. }
  336. u8 tryno; /* Try (retransmission) number of this probe */
  337. u8 pingseq; /* 0 if this is not a scanping. Otherwise a posative ping seq#. */
  338. /* If true, probe is considered no longer active due to timeout, but it
  339. may be kept around a while, just in case a reply comes late */
  340. bool timedout;
  341. /* A packet may be timedout for a while before being retransmitted due to
  342. packet sending rate limitations */
  343. bool retransmitted;
  344. struct timeval sent;
  345. /* Time the previous probe was sent, if this is a retransmit (tryno > 0) */
  346. struct timeval prevSent;
  347. bool isPing() {
  348. return pingseq > 0;
  349. }
  350. private:
  351. probespec mypspec; /* Filled in by the appropriate set* function */
  352. union {
  353. IPExtraProbeData IP;
  354. ConnectProbe *CP;
  355. // ArpProbe *AP;
  356. } probes;
  357. };
  358. /* Global info for the connect scan */
  359. class ConnectScanInfo {
  360. public:
  361. ConnectScanInfo();
  362. ~ConnectScanInfo();
  363. /* Watch a socket descriptor (add to fd_sets and maxValidSD). Returns
  364. true if the SD was absent from the list, false if you tried to
  365. watch an SD that was already being watched. */
  366. bool watchSD(int sd);
  367. /* Clear SD from the fd_sets and maxValidSD. Returns true if the SD
  368. was in the list, false if you tried to clear an sd that wasn't
  369. there in the first place. */
  370. bool clearSD(int sd);
  371. int maxValidSD; /* The maximum socket descriptor in any of the fd_sets */
  372. fd_set fds_read;
  373. fd_set fds_write;
  374. fd_set fds_except;
  375. int numSDs; /* Number of socket descriptors being watched */
  376. int maxSocketsAllowed; /* No more than this many sockets may be created @once */
  377. };
  378. class HostScanStats;
  379. /* These are ultra_scan() statistics for the whole group of Targets */
  380. class GroupScanStats {
  381. public:
  382. struct timeval timeout; /* The time at which we abort the scan */
  383. /* Most recent host tested for sendability */
  384. struct sockaddr_storage latestip;
  385. GroupScanStats(UltraScanInfo *UltraSI);
  386. ~GroupScanStats();
  387. void probeSent(unsigned int nbytes);
  388. /* Returns true if the GLOBAL system says that sending is OK. */
  389. bool sendOK(struct timeval *when);
  390. /* Total # of probes outstanding (active) for all Hosts */
  391. int num_probes_active;
  392. UltraScanInfo *USI; /* The USI which contains this GSS. Use for at least
  393. getting the current time w/o gettimeofday() */
  394. struct ultra_timing_vals timing;
  395. struct timeout_info to; /* Group-wide packet rtt/timeout info */
  396. int numtargets; /* Total # of targets scanned -- includes finished and incomplete hosts */
  397. int numprobes; /* Number of probes/ports scanned on each host */
  398. /* The last time waitForResponses finished (initialized to GSS creation time */
  399. int probes_sent; /* Number of probes sent in total. This DOES include pings and retransmissions */
  400. /* The most recently received probe response time -- initialized to scan
  401. start time. */
  402. struct timeval lastrcvd;
  403. /* The time the most recent ping was sent (initialized to scan begin time) */
  404. struct timeval lastping_sent;
  405. /* Value of numprobes_sent at lastping_sent time -- to ensure that we don't
  406. send too many pings when probes are going slowly. */
  407. int lastping_sent_numprobes;
  408. /* These two variables control minimum- and maximum-rate sending (--min-rate
  409. and --max-rate). send_no_earlier_than is for --max-rate and
  410. send_no_later_than is for --min-rate; they have effect only when the
  411. respective command-line option is given. An attempt is made to keep the
  412. sending rate within the interval, however for send_no_later_than it is not
  413. guaranteed. */
  414. struct timeval send_no_earlier_than;
  415. struct timeval send_no_later_than;
  416. /* The host to which global pings are sent. This is kept updated to be the
  417. most recent host that was found up. */
  418. HostScanStats *pinghost;
  419. struct timeval last_wait;
  420. int probes_sent_at_last_wait;
  421. // number of hosts that timed out during scan, or were already timedout
  422. int num_hosts_timedout;
  423. ConnectScanInfo *CSI;
  424. };
  425. struct send_delay_nfo {
  426. unsigned int delayms; /* Milliseconds to delay between probes */
  427. /* The number of successful and dropped probes since the last time the delay
  428. was changed. The ratio controls when the rate drops. */
  429. unsigned int goodRespSinceDelayChanged;
  430. unsigned int droppedRespSinceDelayChanged;
  431. struct timeval last_boost; /* Most recent time of increase to delayms. Init to creation time. */
  432. };
  433. /* To test for rate limiting, there is a delay in sending the first packet
  434. of a certain retransmission number. These values help track that. */
  435. struct rate_limit_detection_nfo {
  436. unsigned int max_tryno_sent; /* What is the max tryno we have sent so far (starts at 0) */
  437. bool rld_waiting; /* Are we currently waiting due to RLD? */
  438. struct timeval rld_waittime; /* if RLD waiting, when can we send? */
  439. };
  440. /* The ultra_scan() statistics that apply to individual target hosts in a
  441. group */
  442. class HostScanStats {
  443. public:
  444. Target *target; /* A copy of the Target that these stats refer to. */
  445. HostScanStats(Target *t, UltraScanInfo *UltraSI);
  446. ~HostScanStats();
  447. int freshPortsLeft(); /* Returns the number of ports remaining to probe */
  448. int next_portidx; /* Index of the next port to probe in the relevent
  449. ports array in USI.ports */
  450. bool sent_arp; /* Has an ARP probe been sent for the target yet? */
  451. /* massping state. */
  452. /* The index of the next ACK port in o.ping_ackprobes to probe during ping
  453. scan. */
  454. int next_ackportpingidx;
  455. /* The index of the next SYN port in o.ping_synprobes to probe during ping
  456. scan. */
  457. int next_synportpingidx;
  458. /* The index of the next UDP port in o.ping_udpprobes to probe during ping
  459. scan. */
  460. int next_udpportpingidx;
  461. /* The index of the next SCTP port in o.ping_protoprobes to probe during ping
  462. scan. */
  463. int next_sctpportpingidx;
  464. /* The index of the next IP protocol in o.ping_protoprobes to probe during ping
  465. scan. */
  466. int next_protoportpingidx;
  467. /* Whether we have sent an ICMP echo request. */
  468. bool sent_icmp_ping;
  469. /* Whether we have sent an ICMP address mask request. */
  470. bool sent_icmp_mask;
  471. /* Whether we have sent an ICMP timestamp request. */
  472. bool sent_icmp_ts;
  473. /* Have we warned that we've given up on a port for this host yet? Only one
  474. port per host is reported. */
  475. bool retry_capped_warned;
  476. void probeSent(unsigned int nbytes);
  477. /* How long I am currently willing to wait for a probe response
  478. before considering it timed out. Uses the host values from
  479. target if they are available, otherwise from gstats. Results
  480. returned in MICROseconds. */
  481. unsigned long probeTimeout();
  482. /* How long I'll wait until completely giving up on a probe.
  483. Timedout probes are often marked as such (and sometimes
  484. considered a drop), but kept in the list juts in case they come
  485. really late. But after probeExpireTime(), I don't waste time
  486. keeping them around. Give in MICROseconds */
  487. unsigned long probeExpireTime(const UltraProbe *probe);
  488. /* Returns OK if sending a new probe to this host is OK (to avoid
  489. flooding). If when is non-NULL, fills it with the time that sending
  490. will be OK assuming no pending probes are resolved by responses
  491. (call it again if they do). when will become now if it returns
  492. true. */
  493. bool sendOK(struct timeval *when);
  494. /* If there are pending probe timeouts, fills in when with the time of
  495. the earliest one and returns true. Otherwise returns false and
  496. puts now in when. */
  497. bool nextTimeout(struct timeval *when);
  498. UltraScanInfo *USI; /* The USI which contains this HSS */
  499. /* Removes a probe from probes_outstanding, adjusts HSS and USS
  500. active probe stats accordingly, then deletes the probe. */
  501. void destroyOutstandingProbe(std::list<UltraProbe *>::iterator probeI);
  502. /* Removes all probes from probes_outstanding using
  503. destroyOutstandingProbe. This is used in ping scan to quit waiting
  504. for responses once a host is known to be up. Invalidates iterators
  505. pointing into probes_outstanding. */
  506. void destroyAllOutstandingProbes();
  507. /* Mark an outstanding probe as timedout. Adjusts stats
  508. accordingly. For connect scans, this closes the socket. */
  509. void markProbeTimedout(std::list<UltraProbe *>::iterator probeI);
  510. /* New (active) probes are appended to the end of this list. When a
  511. host times out, it will be marked as such, but may hang around on
  512. the list for a while just in case a response comes in. So use
  513. num_probes_active to learn how many active (not timed out) probes
  514. are outstanding. Probes on the bench (reached the current
  515. maximum tryno and expired) are not counted in
  516. probes_outstanding. */
  517. std::list<UltraProbe *> probes_outstanding;
  518. /* The number of probes in probes_outstanding, minus the inactive (timed out) ones */
  519. unsigned int num_probes_active;
  520. /* Probes timed out but not yet retransmitted because of congestion
  521. control limits or because more retransmits may not be
  522. necessary. Note that probes on probe_bench are not included
  523. in this value. */
  524. unsigned int num_probes_waiting_retransmit;
  525. unsigned int num_probes_outstanding() {
  526. return probes_outstanding.size();
  527. }
  528. /* The bench is a stock of probes (compacted into just the
  529. probespec) that have met the current maximum tryno, and are on
  530. ice until that tryno increases (so we can retransmit again), or
  531. solidifies (so we can mark the port firewalled or whatever). The
  532. tryno of benh members is bench_tryno. If the maximum tryno
  533. increases, everyone on the bench is moved to the retry_stack.
  534. */
  535. std::vector<probespec> probe_bench;
  536. unsigned int bench_tryno; /* # tryno of probes on the bench */
  537. /* The retry_stack are probespecs that were on the bench but are now
  538. slated to be retried. It is kept sorted such that probes with highest
  539. retry counts are on top, ready to be taken first. */
  540. std::vector<probespec> retry_stack;
  541. /* retry_stack_tries MUST BE KEPT IN SYNC WITH retry_stack.
  542. retry_stack_tries[i] is the number of completed retries for the
  543. probe in retry_stack[i] */
  544. std::vector<u8> retry_stack_tries;
  545. /* tryno of probes on the retry queue */
  546. /* Moves the given probe from the probes_outstanding list, to
  547. probe_bench, and decrements num_probes_waiting_retransmit accordingly */
  548. void moveProbeToBench(std::list<UltraProbe *>::iterator probeI);
  549. /* Dismiss all probe attempts on bench -- the ports are marked
  550. 'filtered' or whatever is appropriate for having no response */
  551. void dismissBench();
  552. /* Move all members of bench to retry_stack for probe retransmission */
  553. void retransmitBench();
  554. bool completed(); /* Whether or not the scan of this Target has completed */
  555. struct timeval completiontime; /* When this Target completed */
  556. /* This function provides the proper cwnd and ssthresh to use. It
  557. may differ from versions in timing member var because when no
  558. responses have been received for this host, may look at others in
  559. the group. For CHANGING this host's timing, use the timing
  560. memberval instead. */
  561. void getTiming(struct ultra_timing_vals *tmng);
  562. struct ultra_timing_vals timing;
  563. /* The most recently received probe response time -- initialized to scan start time. */
  564. struct timeval lastrcvd;
  565. struct timeval lastping_sent; /* The time the most recent ping was sent (initialized to scan begin time) */
  566. /* Value of numprobes_sent at lastping_sent time -- to ensure that we
  567. don't send too many pings when probes are going slowly. */
  568. int lastping_sent_numprobes;
  569. struct timeval lastprobe_sent; /* Most recent probe send (including pings) by host. Init to scan begin time. */
  570. /* gives the maximum try number (try numbers start at zero and
  571. increments for each retransmission) that may be used, based on
  572. the scan type, observed network reliability, timing mode, etc.
  573. This may change during the scan based on network traffic. If
  574. capped is not null, it will be filled with true if the tryno is
  575. at its upper limit. That often calls for a warning to be issued,
  576. and marking of remaining timedout ports firewalled or whatever is
  577. appropriate. If mayincrease is non-NULL, it is set to whether
  578. the allowedTryno may increase again. If it is false, any probes
  579. which have reached the given limit may be dealth with. */
  580. unsigned int allowedTryno(bool *capped, bool *mayincrease);
  581. /* Provides the next ping sequence number. This starts at one, goes
  582. up to 255, then wraps around back to 1. If inc is true, it is
  583. incremented. Otherwise you just get a peek at what the next one
  584. will be. */
  585. u8 nextPingSeq(bool inc = true) {
  586. u8 ret = nxtpseq;
  587. if (inc) {
  588. nxtpseq++;
  589. if (nxtpseq == 0)
  590. nxtpseq++;
  591. }
  592. return ret;
  593. }
  594. /* This is the highest try number that has produced useful results
  595. (such as port status change). */
  596. unsigned int max_successful_tryno;
  597. /* This starts as true because tryno may increase based on results, but
  598. it becomes false if it becomes clear that tryno will not increase
  599. further during the scan */
  600. bool tryno_mayincrease;
  601. int ports_finished; /* The number of ports of this host that have been determined */
  602. int numprobes_sent; /* Number of port probes (not counting pings, but counting retransmits) sent to this host */
  603. /* Boost the scan delay for this host, usually because too many packet
  604. drops were detected. */
  605. void boostScanDelay();
  606. struct send_delay_nfo sdn;
  607. struct rate_limit_detection_nfo rld;
  608. private:
  609. u8 nxtpseq; /* the next scanping sequence number to use */
  610. };
  611. class UltraScanInfo {
  612. public:
  613. UltraScanInfo();
  614. UltraScanInfo(std::vector<Target *> &Targets, struct scan_lists *pts, stype scantype) {
  615. Init(Targets, pts, scantype);
  616. }
  617. ~UltraScanInfo();
  618. /* Must call Init if you create object with default constructor */
  619. void Init(std::vector<Target *> &Targets, struct scan_lists *pts, stype scantp);
  620. unsigned int numProbesPerHost();
  621. /* Consults with the group stats, and the hstats for every
  622. incomplete hosts to determine whether any probes may be sent.
  623. Returns true if they can be sent immediately. If when is non-NULL,
  624. it is filled with the next possible time that probes can be sent
  625. (which will be now, if the function returns true */
  626. bool sendOK(struct timeval *tv);
  627. stype scantype;
  628. bool tcp_scan; /* scantype is a type of TCP scan */
  629. bool udp_scan;
  630. bool sctp_scan; /* scantype is a type of SCTP scan */
  631. bool prot_scan;
  632. bool ping_scan; /* Includes trad. ping scan & arp scan */
  633. bool ping_scan_arp; /* ONLY includes arp ping scan */
  634. bool ping_scan_nd; /* ONLY includes ND ping scan */
  635. bool noresp_open_scan; /* Whether no response means a port is open */
  636. /* massping state. */
  637. /* If ping_scan is true (unless ping_scan_arp is also true), this is the set
  638. of ping techniques to use (ICMP, raw ICMP, TCP connect, raw TCP, or raw
  639. UDP). */
  640. struct {
  641. unsigned int rawicmpscan: 1,
  642. connecttcpscan: 1,
  643. rawtcpscan: 1,
  644. rawudpscan: 1,
  645. rawsctpscan: 1,
  646. rawprotoscan: 1;
  647. } ptech;
  648. bool isRawScan();
  649. struct timeval now; /* Updated after potentially meaningful delays. This can
  650. be used to save a call to gettimeofday() */
  651. GroupScanStats *gstats;
  652. struct ultra_scan_performance_vars perf;
  653. /* A circular buffer of the incompleteHosts. nextIncompleteHost() gives
  654. the next one. The first time it is called, it will give the
  655. first host in the list. If incompleteHosts is empty, returns
  656. NULL. */
  657. HostScanStats *nextIncompleteHost();
  658. /* Removes any hosts that have completed their scans from the incompleteHosts
  659. list, and remove any hosts from completedHosts which have exceeded their
  660. lifetime. Returns the number of hosts removed. */
  661. int removeCompletedHosts();
  662. /* Find a HostScanStats by its IP address in the incomplete and completed
  663. lists. Returns NULL if none are found. */
  664. HostScanStats *findHost(struct sockaddr_storage *ss);
  665. double getCompletionFraction();
  666. unsigned int numIncompleteHosts() {
  667. return incompleteHosts.size();
  668. }
  669. /* Call this instead of checking for numIncompleteHosts() == 0 because it
  670. avoids a potential traversal of the list to find the size. */
  671. bool incompleteHostsEmpty() {
  672. return incompleteHosts.empty();
  673. }
  674. bool numIncompleteHostsLessThan(unsigned int n);
  675. unsigned int numInitialHosts() {
  676. return numInitialTargets;
  677. }
  678. void log_overall_rates(int logt) {
  679. log_write(logt, "Overall sending rates: %.2f packets / s", send_rate_meter.getOverallPacketRate(&now));
  680. if (send_rate_meter.getNumBytes() > 0)
  681. log_write(logt, ", %.2f bytes / s", send_rate_meter.getOverallByteRate(&now));
  682. log_write(logt, ".\n");
  683. }
  684. void log_current_rates(int logt, bool update = true) {
  685. log_write(logt, "Current sending rates: %.2f packets / s", send_rate_meter.getCurrentPacketRate(&now, update));
  686. if (send_rate_meter.getNumBytes() > 0)
  687. log_write(logt, ", %.2f bytes / s", send_rate_meter.getCurrentByteRate(&now));
  688. log_write(logt, ".\n");
  689. }
  690. /* Any function which messes with (removes elements from)
  691. incompleteHosts may have to manipulate nextI */
  692. std::list<HostScanStats *> incompleteHosts;
  693. /* Hosts are moved from incompleteHosts to completedHosts as they are
  694. completed. We keep them around because sometimes responses come back very
  695. late, after we consider a host completed. */
  696. std::list<HostScanStats *> completedHosts;
  697. /* How long (in msecs) we keep a host in completedHosts */
  698. unsigned int completedHostLifetime;
  699. /* The last time we went through completedHosts to remove hosts */
  700. struct timeval lastCompletedHostRemoval;
  701. ScanProgressMeter *SPM;
  702. PacketRateMeter send_rate_meter;
  703. struct scan_lists *ports;
  704. int rawsd; /* raw socket descriptor */
  705. pcap_t *pd;
  706. eth_t *ethsd;
  707. u32 seqmask; /* This mask value is used to encode values in sequence
  708. numbers. It is set randomly in UltraScanInfo::Init() */
  709. private:
  710. unsigned int numInitialTargets;
  711. std::list<HostScanStats *>::iterator nextI;
  712. };
  713. /* Whether this is storing timing stats for a whole group or an
  714. individual host */
  715. enum ultra_timing_type { TIMING_HOST, TIMING_GROUP };
  716. /* Initialize the ultra_timing_vals structure timing. The utt must be
  717. TIMING_HOST or TIMING_GROUP. If you happen to have the current
  718. time handy, pass it as now, otherwise pass NULL */
  719. static void init_ultra_timing_vals(ultra_timing_vals *timing,
  720. enum ultra_timing_type utt,
  721. int num_hosts_in_group,
  722. struct ultra_scan_performance_vars *perf,
  723. struct timeval *now);
  724. /* Take a buffer, buf, of size bufsz (64 bytes is sufficient) and
  725. writes a short description of the probe (arg1) into buf. It also returns
  726. buf. */
  727. static char *probespec2ascii(const probespec *pspec, char *buf, unsigned int bufsz) {
  728. char flagbuf[32];
  729. char *f;
  730. switch (pspec->type) {
  731. case PS_TCP:
  732. if (!pspec->pd.tcp.flags) {
  733. Strncpy(flagbuf, "(none)", sizeof(flagbuf));
  734. } else {
  735. f = flagbuf;
  736. if (pspec->pd.tcp.flags & TH_SYN)
  737. *f++ = 'S';
  738. if (pspec->pd.tcp.flags & TH_FIN)
  739. *f++ = 'F';
  740. if (pspec->pd.tcp.flags & TH_RST)
  741. *f++ = 'R';
  742. if (pspec->pd.tcp.flags & TH_PUSH)
  743. *f++ = 'P';
  744. if (pspec->pd.tcp.flags & TH_ACK)
  745. *f++ = 'A';
  746. if (pspec->pd.tcp.flags & TH_URG)
  747. *f++ = 'U';
  748. if (pspec->pd.tcp.flags & TH_ECE)
  749. *f++ = 'E'; /* rfc 2481/3168 */
  750. if (pspec->pd.tcp.flags & TH_CWR)
  751. *f++ = 'C'; /* rfc 2481/3168 */
  752. *f++ = '\0';
  753. }
  754. Snprintf(buf, bufsz, "tcp to port %hu; flags: %s", pspec->pd.tcp.dport, flagbuf);
  755. break;
  756. case PS_UDP:
  757. Snprintf(buf, bufsz, "udp to port %hu", pspec->pd.udp.dport);
  758. break;
  759. case PS_SCTP:
  760. switch (pspec->pd.sctp.chunktype) {
  761. case SCTP_INIT:
  762. Strncpy(flagbuf, "INIT", sizeof(flagbuf));
  763. break;
  764. case SCTP_COOKIE_ECHO:
  765. Strncpy(flagbuf, "COOKIE-ECHO", sizeof(flagbuf));
  766. break;
  767. default:
  768. Strncpy(flagbuf, "(unknown)", sizeof(flagbuf));
  769. }
  770. Snprintf(buf, bufsz, "sctp to port %hu; chunk: %s", pspec->pd.sctp.dport,
  771. flagbuf);
  772. break;
  773. case PS_PROTO:
  774. Snprintf(buf, bufsz, "protocol %u", (unsigned int) pspec->proto);
  775. break;
  776. case PS_ICMP:
  777. Snprintf(buf, bufsz, "icmp type %d code %d",
  778. pspec->pd.icmp.type, pspec->pd.icmp.code);
  779. break;
  780. case PS_ARP:
  781. Snprintf(buf, bufsz, "ARP");
  782. break;
  783. case PS_ICMPV6:
  784. Snprintf(buf, bufsz, "icmpv6 type %d code %d",
  785. pspec->pd.icmpv6.type, pspec->pd.icmpv6.code);
  786. break;
  787. case PS_ND:
  788. Snprintf(buf, bufsz, "ND");
  789. break;
  790. case PS_CONNECTTCP:
  791. Snprintf(buf, bufsz, "connect to port %hu", pspec->pd.tcp.dport);
  792. break;
  793. default:
  794. fatal("Unexpected %s type encountered", __func__);
  795. break;
  796. }
  797. return buf;
  798. }
  799. ConnectProbe::ConnectProbe() {
  800. sd = -1;
  801. }
  802. ConnectProbe::~ConnectProbe() {
  803. if (sd > 0)
  804. close(sd);
  805. sd = -1;
  806. }
  807. UltraProbe::UltraProbe() {
  808. type = UP_UNSET;
  809. tryno = 0;
  810. timedout = false;
  811. retransmitted = false;
  812. pingseq = 0;
  813. mypspec.type = PS_NONE;
  814. memset(&sent, 0, sizeof(prevSent));
  815. memset(&prevSent, 0, sizeof(prevSent));
  816. }
  817. UltraProbe::~UltraProbe() {
  818. if (type == UP_CONNECT)
  819. delete probes.CP;
  820. }
  821. /* Pass an arp packet, including ethernet header. Must be 42bytes */
  822. void UltraProbe::setARP(u8 *arppkt, u32 arplen) {
  823. type = UP_ARP;
  824. mypspec.type = PS_ARP;
  825. return;
  826. }
  827. void UltraProbe::setND(u8 *ndpkt, u32 ndlen) {
  828. type = UP_ND;
  829. mypspec.type = PS_ND;
  830. return;
  831. }
  832. /* Sets this UltraProbe as type UP_IP and creates & initializes the
  833. internal IPProbe. The relevent probespec is necessary for setIP
  834. because pspec.type is ambiguous with just the ippacket (e.g. a
  835. tcp packet could be PS_PROTO or PS_TCP). */
  836. void UltraProbe::setIP(u8 *ippacket, u32 len, const probespec *pspec) {
  837. struct ip *ip = (struct ip *) ippacket;
  838. struct tcp_hdr *tcp = NULL;
  839. struct udp_hdr *udp = NULL;
  840. struct sctp_hdr *sctp = NULL;
  841. struct ppkt *icmp = NULL;
  842. const void *data;
  843. u8 hdr;
  844. type = UP_IP;
  845. if (ip->ip_v == 4) {
  846. data = ipv4_get_data(ip, &len);
  847. assert(data != NULL);
  848. assert(len + ip->ip_hl * 4 == (u32) ntohs(ip->ip_len));
  849. probes.IP.ipid = ntohs(ip->ip_id);
  850. hdr = ip->ip_p;
  851. } else if (ip->ip_v == 6) {
  852. const struct ip6_hdr *ip6 = (struct ip6_hdr *) ippacket;
  853. data = ipv6_get_data_any(ip6, &len, &hdr);
  854. assert(data != NULL);
  855. assert(len == (u32) ntohs(ip6->ip6_plen));
  856. probes.IP.ipid = ntohl(ip6->ip6_flow & IP6_FLOWLABEL_MASK) & 0xFFFF;
  857. hdr = ip6->ip6_nxt;
  858. } else {
  859. fatal("Bogus packet passed to %s -- only IP packets allowed", __func__);
  860. }
  861. if (hdr == IPPROTO_TCP) {
  862. assert(len >= 20);
  863. tcp = (struct tcp_hdr *) data;
  864. probes.IP.pd.tcp.sport = ntohs(tcp->th_sport);
  865. probes.IP.pd.tcp.seq = ntohl(tcp->th_seq);
  866. } else if (hdr == IPPROTO_UDP) {
  867. assert(len >= 8);
  868. udp = (struct udp_hdr *) data;
  869. probes.IP.pd.udp.sport = ntohs(udp->uh_sport);
  870. } else if (hdr == IPPROTO_SCTP) {
  871. assert(len >= 12);
  872. sctp = (struct sctp_hdr *) data;
  873. probes.IP.pd.sctp.sport = ntohs(sctp->sh_sport);
  874. probes.IP.pd.sctp.vtag = ntohl(sctp->sh_vtag);
  875. } else if (hdr == IPPROTO_ICMP) {
  876. icmp = (struct ppkt *) data;
  877. probes.IP.pd.icmp.ident = ntohs(icmp->id);
  878. }
  879. mypspec = *pspec;
  880. return;
  881. }
  882. u16 UltraProbe::icmpid() const {
  883. assert(mypspec.proto == IPPROTO_ICMP);
  884. return probes.IP.pd.icmp.ident;
  885. }
  886. u32 UltraProbe::tcpseq() const {
  887. if (mypspec.proto == IPPROTO_TCP)
  888. return probes.IP.pd.tcp.seq;
  889. else
  890. fatal("Bogus seq number request to %s -- type is %s", __func__,
  891. pspectype2ascii(mypspec.type));
  892. return 0; // Unreached
  893. }
  894. u32 UltraProbe::sctpvtag() const {
  895. assert(mypspec.proto == IPPROTO_SCTP);
  896. return probes.IP.pd.sctp.vtag;
  897. }
  898. /* Sets this UltraProbe as type UP_CONNECT, preparing to connect to given
  899. port number*/
  900. void UltraProbe::setConnect(u16 portno) {
  901. type = UP_CONNECT;
  902. probes.CP = new ConnectProbe();
  903. mypspec.type = PS_CONNECTTCP;
  904. mypspec.proto = IPPROTO_TCP;
  905. mypspec.pd.tcp.dport = portno;
  906. mypspec.pd.tcp.flags = TH_SYN;
  907. }
  908. ConnectScanInfo::ConnectScanInfo() {
  909. maxValidSD = -1;
  910. numSDs = 0;
  911. if (o.max_parallelism > 0) {
  912. maxSocketsAllowed = o.max_parallelism;
  913. } else {
  914. /* Subtracting 10 from max_sd accounts for
  915. stdin
  916. stdout
  917. stderr
  918. /dev/tty
  919. /var/run/utmpx, which is opened on Mac OS X at least
  920. -oG log file
  921. -oN log file
  922. -oS log file
  923. -oX log file
  924. perhaps another we've forgotten. */
  925. maxSocketsAllowed = max_sd() - 10;
  926. if (maxSocketsAllowed < 5)
  927. maxSocketsAllowed = 5;
  928. }
  929. maxSocketsAllowed = MIN(maxSocketsAllowed, FD_SETSIZE - 10);
  930. FD_ZERO(&fds_read);
  931. FD_ZERO(&fds_write);
  932. FD_ZERO(&fds_except);
  933. }
  934. /* Nothing really to do here. */
  935. ConnectScanInfo::~ConnectScanInfo() {}
  936. /* Watch a socket descriptor (add to fd_sets and maxValidSD). Returns
  937. true if the SD was absent from the list, false if you tried to
  938. watch an SD that was already being watched. */
  939. bool ConnectScanInfo::watchSD(int sd) {
  940. assert(sd >= 0);
  941. if (!FD_ISSET(sd, &fds_read)) {
  942. CHECKED_FD_SET(sd, &fds_read);
  943. CHECKED_FD_SET(sd, &fds_write);
  944. CHECKED_FD_SET(sd, &fds_except);
  945. numSDs++;
  946. if (sd > maxValidSD)
  947. maxValidSD = sd;
  948. return true;
  949. } else {
  950. return false;
  951. }
  952. }
  953. /* Clear SD from the fd_sets and maxValidSD. Returns true if the SD
  954. was in the list, false if you tried to clear an sd that wasn't
  955. there in the first place. */
  956. bool ConnectScanInfo::clearSD(int sd) {
  957. assert(sd >= 0);
  958. if (FD_ISSET(sd, &fds_read)) {
  959. CHECKED_FD_CLR(sd, &fds_read);
  960. CHECKED_FD_CLR(sd, &fds_write);
  961. CHECKED_FD_CLR(sd, &fds_except);
  962. assert(numSDs > 0);
  963. numSDs--;
  964. if (sd == maxValidSD)
  965. maxValidSD--;
  966. return true;
  967. } else {
  968. return false;
  969. }
  970. }
  971. GroupScanStats::GroupScanStats(UltraScanInfo *UltraSI) {
  972. memset(&latestip, 0, sizeof(latestip));
  973. memset(&timeout, 0, sizeof(timeout));
  974. USI = UltraSI;
  975. init_ultra_timing_vals(&timing, TIMING_GROUP, USI->numIncompleteHosts(), &(USI->perf), &USI->now);
  976. initialize_timeout_info(&to);
  977. /* Default timout should be much lower for arp */
  978. if (USI->ping_scan_arp)
  979. to.timeout = MAX(o.minRttTimeout(), MIN(o.initialRttTimeout(), INITIAL_ARP_RTT_TIMEOUT)) * 1000;
  980. num_probes_active = 0;
  981. numtargets = USI->numIncompleteHosts(); // They are all incomplete at the beginning
  982. numprobes = USI->numProbesPerHost();
  983. if (USI->scantype == CONNECT_SCAN || USI->ptech.connecttcpscan)
  984. CSI = new ConnectScanInfo;
  985. else CSI = NULL;
  986. probes_sent = probes_sent_at_last_wait = 0;
  987. lastping_sent = lastrcvd = USI->now;
  988. send_no_earlier_than = USI->now;
  989. send_no_later_than = USI->now;
  990. lastping_sent_numprobes = 0;
  991. pinghost = NULL;
  992. gettimeofday(&last_wait, NULL);
  993. num_hosts_timedout = 0;
  994. }
  995. GroupScanStats::~GroupScanStats() {
  996. delete CSI;
  997. }
  998. /* Called whenever a probe is sent to any host. Should only be called by
  999. HostScanStats::probeSent. */
  1000. void GroupScanStats::probeSent(unsigned int nbytes) {
  1001. USI->send_rate_meter.update(nbytes, &USI->now);
  1002. /* Find a new scheduling interval for minimum- and maximum-rate sending.
  1003. Recall that these have effect only when --min-rate or --max-rate is
  1004. given. */
  1005. TIMEVAL_ADD(send_no_earlier_than, send_no_earlier_than,
  1006. (time_t) (1000000.0 / o.max_packet_send_rate));
  1007. /* Allow send_no_earlier_than to slip into the past. This allows the sending
  1008. scheduler to catch up and make up for delays in other parts of the scan
  1009. engine. If we were to update send_no_earlier_than to the present the
  1010. sending rate could be much less than the maximum requested, even if the
  1011. connection is capable of the maximum. */
  1012. if (TIMEVAL_SUBTRACT(send_no_later_than, USI->now) > 0) {
  1013. /* The next scheduled send is in the future. That means there's slack time
  1014. during which the sending rate could drop. Pull the time back to the
  1015. present to prevent that. */
  1016. send_no_later_than = USI->now;
  1017. }
  1018. TIMEVAL_ADD(send_no_later_than, send_no_later_than,
  1019. (time_t) (1000000.0 / o.min_packet_send_rate));
  1020. }
  1021. /* Returns true if the GLOBAL system says that sending is OK.*/
  1022. bool GroupScanStats::sendOK(struct timeval *when) {
  1023. int recentsends;
  1024. /* In case it's not okay to send, arbitrarily say to check back in one
  1025. second. */
  1026. if (when)
  1027. TIMEVAL_MSEC_ADD(*when, USI->now, 1000);
  1028. if ((USI->scantype == CONNECT_SCAN || USI->ptech.connecttcpscan)
  1029. && CSI->numSDs >= CSI->maxSocketsAllowed)
  1030. return false;
  1031. /* We need to stop sending if it has been a long time since
  1032. the last listen call, at least for systems such as Windoze that
  1033. don't give us a proper pcap time. Also for connect scans, since
  1034. we don't get an exact response time with them either. */
  1035. recentsends = USI->gstats->probes_sent - USI->gstats->probes_sent_at_last_wait;
  1036. if (recentsends > 0 &&
  1037. (USI->scantype == CONNECT_SCAN || USI->ptech.connecttcpscan || !pcap_recv_timeval_valid())) {
  1038. int to_ms = (int) MAX(to.srtt * .75 / 1000, 50);
  1039. if (TIMEVAL_MSEC_SUBTRACT(USI->now, last_wait) > to_ms)
  1040. return false;
  1041. }
  1042. /* Enforce a maximum scanning rate, if necessary. If it's too early to send,
  1043. return false. If not, mark now as a good time to send and allow the
  1044. congestion control to override it. */
  1045. if (o.max_packet_send_rate != 0.0) {
  1046. if (TIMEVAL_SUBTRACT(send_no_earlier_than, USI->now) > 0) {
  1047. if (when)
  1048. *when = send_no_earlier_than;
  1049. return false;
  1050. } else {
  1051. if (when)
  1052. *when = USI->now;
  1053. }
  1054. }
  1055. /* Enforce a minimum scanning rate, if necessary. If we're ahead of schedule,
  1056. record the time of the next scheduled send and submit to congestion
  1057. control. If we're behind schedule, return true to indicate that we need to
  1058. send right now. */
  1059. if (o.min_packet_send_rate != 0.0) {
  1060. if (TIMEVAL_SUBTRACT(send_no_later_than, USI->now) > 0) {
  1061. if (when)
  1062. *when = send_no_later_than;
  1063. } else {
  1064. if (when)
  1065. *when = USI->now;
  1066. return true;
  1067. }
  1068. }
  1069. /* There are good arguments for limiting the number of probes sent
  1070. between waits even when we do get appropriate receive times. For
  1071. example, overflowing the pcap receive buffer with responses is no
  1072. fun. On one of my Linux boxes, it seems to hold about 113
  1073. responses when I scan localhost. And half of those are the @#$#
  1074. sends being received. I think I'll put a limit of 50 sends per
  1075. wait */
  1076. if (recentsends >= 50)
  1077. return false;
  1078. /* In case the user specifically asked for no group congestion control */
  1079. if (o.nogcc) {
  1080. if (when)
  1081. *when = USI->now;
  1082. return true;
  1083. }
  1084. /* When there is only one target left, let the host congestion
  1085. stuff deal with it. */
  1086. if (USI->numIncompleteHostsLessThan(2)) {
  1087. if (when)
  1088. *when = USI->now;
  1089. return true;
  1090. }
  1091. if (timing.cwnd >= num_probes_active + 0.5) {
  1092. if (when)
  1093. *when = USI->now;
  1094. return true;
  1095. }
  1096. return false;
  1097. }
  1098. /* Return true if pingprobe is an appropriate ping probe for the currently
  1099. running scan. Because ping probes persist between host discovery and port
  1100. scanning stages, it's possible to have a ping probe that is not relevant for
  1101. the scan type, or won't be caught by the pcap filters. Examples of
  1102. inappropriate ping probes are an ARP ping for a TCP scan, or a raw SYN ping
  1103. for a connect scan. */
  1104. static bool pingprobe_is_appropriate(const UltraScanInfo *USI,
  1105. const probespec *pingprobe) {
  1106. switch (pingprobe->type) {
  1107. case(PS_NONE):
  1108. return true;
  1109. case(PS_CONNECTTCP):
  1110. return USI->scantype == CONNECT_SCAN || (USI->ping_scan && USI->ptech.connecttcpscan);
  1111. case(PS_TCP):
  1112. case(PS_UDP):
  1113. case(PS_SCTP):
  1114. return (USI->tcp_scan && USI->scantype != CONNECT_SCAN) ||
  1115. USI->udp_scan ||
  1116. USI->sctp_scan ||
  1117. (USI->ping_scan && (USI->ptech.rawtcpscan || USI->ptech.rawudpscan || USI->ptech.rawsctpscan));
  1118. case(PS_PROTO):
  1119. return USI->prot_scan || (USI->ping_scan && USI->ptech.rawprotoscan);
  1120. case(PS_ICMP):
  1121. return ((USI->ping_scan && !USI->ping_scan_arp ) || pingprobe->pd.icmp.type == 3);
  1122. case(PS_ARP):
  1123. return USI->ping_scan_arp;
  1124. case(PS_ND):
  1125. return USI->ping_scan_nd;
  1126. }
  1127. return false;
  1128. }
  1129. HostScanStats::HostScanStats(Target *t, UltraScanInfo *UltraSI) {
  1130. target = t;
  1131. USI = UltraSI;
  1132. next_portidx = 0;
  1133. sent_arp = false;
  1134. next_ackportpingidx = 0;
  1135. next_synportpingidx = 0;
  1136. next_udpportpingidx = 0;
  1137. next_sctpportpingidx = 0;
  1138. next_protoportpingidx = 0;
  1139. sent_icmp_ping = false;
  1140. sent_icmp_mask = false;
  1141. sent_icmp_ts = false;
  1142. retry_capped_warned = false;
  1143. num_probes_active = 0;
  1144. num_probes_waiting_retransmit = 0;
  1145. lastping_sent = lastprobe_sent = lastrcvd = USI->now;
  1146. lastping_sent_numprobes = 0;
  1147. nxtpseq = 1;
  1148. max_successful_tryno = 0;
  1149. tryno_mayincrease = true;
  1150. ports_finished = 0;
  1151. numprobes_sent = 0;
  1152. memset(&completiontime, 0, sizeof(completiontime));
  1153. init_ultra_timing_vals(&timing, TIMING_HOST, 1, &(USI->perf), &USI->now);
  1154. bench_tryno = 0;
  1155. memset(&sdn, 0, sizeof(sdn));
  1156. sdn.last_boost = USI->now;
  1157. sdn.delayms = o.scan_delay;
  1158. rld.max_tryno_sent = 0;
  1159. rld.rld_waiting = false;
  1160. rld.rld_waittime = USI->now;
  1161. if (!pingprobe_is_appropriate(USI, &target->pingprobe)) {
  1162. if (o.debugging > 1)
  1163. log_write(LOG

Large files files are truncated, but you can click here to view the full file