PageRenderTime 95ms CodeModel.GetById 21ms 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
  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_STDOUT, "%s pingprobe type %s is inappropriate for this scan type; resetting.\n", target->targetipstr(), pspectype2ascii(target->pingprobe.type));
  1164. memset(&target->pingprobe, 0, sizeof(target->pingprobe));
  1165. target->pingprobe_state = PORT_UNKNOWN;
  1166. }
  1167. }
  1168. HostScanStats::~HostScanStats() {
  1169. std::list<UltraProbe *>::iterator probeI, next;
  1170. /* Move any hosts from the bench to probes_outstanding for easier deletion */
  1171. for (probeI = probes_outstanding.begin(); probeI != probes_outstanding.end();
  1172. probeI = next) {
  1173. next = probeI;
  1174. next++;
  1175. destroyOutstandingProbe(probeI);
  1176. }
  1177. }
  1178. /* Called whenever a probe is sent to this host. Takes care of updating scan
  1179. delay and rate limiting variables. */
  1180. void HostScanStats::probeSent(unsigned int nbytes) {
  1181. lastprobe_sent = USI->now;
  1182. /* Update group variables. */
  1183. USI->gstats->probeSent(nbytes);
  1184. }
  1185. /* How long I am currently willing to wait for a probe response before
  1186. considering it timed out. Uses the host values from target if they
  1187. are available, otherwise from gstats. Results returned in
  1188. MICROseconds. */
  1189. unsigned long HostScanStats::probeTimeout() {
  1190. if (target->to.srtt > 0) {
  1191. /* We have at least one timing value to use. Good enough, I suppose */
  1192. return target->to.timeout;
  1193. } else if (USI->gstats->to.srtt > 0) {
  1194. /* OK, we'll use this one instead */
  1195. return USI->gstats->to.timeout;
  1196. } else {
  1197. return target->to.timeout; /* It comes with a default */
  1198. }
  1199. }
  1200. /* How long I'll wait until completely giving up on a probe.
  1201. Timedout probes are often marked as such (and sometimes
  1202. considered a drop), but kept in the list just in case they come
  1203. really late. But after probeExpireTime(), I don't waste time
  1204. keeping them around. Give in MICROseconds. The expiry time can
  1205. depend on the type of probe. Pass NULL to get the default time. */
  1206. unsigned long HostScanStats::probeExpireTime(const UltraProbe *probe) {
  1207. if (probe == NULL || probe->type == UltraProbe::UP_CONNECT)
  1208. /* timedout probes close socket -- late resp. impossible */
  1209. return probeTimeout();
  1210. else
  1211. /* Wait a bit longer after probeTimeout. */
  1212. return MIN(10000000, probeTimeout() * 10);
  1213. }
  1214. /* Returns OK if sending a new probe to this host is OK (to avoid
  1215. flooding). If when is non-NULL, fills it with the time that sending
  1216. will be OK assuming no pending probes are resolved by responses
  1217. (call it again if they do). when will become now if it returns
  1218. true. */
  1219. bool HostScanStats::sendOK(struct timeval *when) {
  1220. struct ultra_timing_vals tmng;
  1221. std::list<UltraProbe *>::iterator probeI;
  1222. struct timeval probe_to, earliest_to, sendTime;
  1223. long tdiff;
  1224. if (target->timedOut(&USI->now) || completed()) {
  1225. if (when)
  1226. *when = USI->now;
  1227. return false;
  1228. }
  1229. /* If the group stats say we need to send a probe to enforce a minimum
  1230. scanning rate, then we need to step up and send a probe. */
  1231. if (o.min_packet_send_rate != 0.0) {
  1232. if (TIMEVAL_SUBTRACT(USI->gstats->send_no_later_than, USI->now) <= 0) {
  1233. if (when)
  1234. *when = USI->now;
  1235. return true;
  1236. }
  1237. }
  1238. if (rld.rld_waiting) {
  1239. if (TIMEVAL_AFTER(rld.rld_waittime, USI->now)) {
  1240. if (when)
  1241. *when = rld.rld_waittime;
  1242. return false;
  1243. } else {
  1244. if (when)
  1245. *when = USI->now;
  1246. return true;
  1247. }
  1248. }
  1249. if (sdn.delayms) {
  1250. if (TIMEVAL_MSEC_SUBTRACT(USI->now, lastprobe_sent) < (int) sdn.delayms) {
  1251. if (when) {
  1252. TIMEVAL_MSEC_ADD(*when, lastprobe_sent, sdn.delayms);
  1253. }
  1254. return false;
  1255. }
  1256. }
  1257. getTiming(&tmng);
  1258. if (tmng.cwnd >= num_probes_active + .5 &&
  1259. (freshPortsLeft() || num_probes_waiting_retransmit || !retry_stack.empty())) {
  1260. if (when)
  1261. *when = USI->now;
  1262. return true;
  1263. }
  1264. if (!when)
  1265. return false;
  1266. TIMEVAL_MSEC_ADD(earliest_to, USI->now, 10000);
  1267. // Any timeouts coming up?
  1268. for (probeI = probes_outstanding.begin(); probeI != probes_outstanding.end();
  1269. probeI++) {
  1270. if (!(*probeI)->timedout) {
  1271. TIMEVAL_MSEC_ADD(probe_to, (*probeI)->sent, probeTimeout() / 1000);
  1272. if (TIMEVAL_SUBTRACT(probe_to, earliest_to) < 0) {
  1273. earliest_to = probe_to;
  1274. }
  1275. }
  1276. }
  1277. // Will any scan delay affect this?
  1278. if (sdn.delayms) {
  1279. TIMEVAL_MSEC_ADD(sendTime, lastprobe_sent, sdn.delayms);
  1280. if (TIMEVAL_BEFORE(sendTime, USI->now))
  1281. sendTime = USI->now;
  1282. tdiff = TIMEVAL_MSEC_SUBTRACT(earliest_to, sendTime);
  1283. /* Timeouts previous to the sendTime requirement are pointless,
  1284. and those later than sendTime are not needed if we can send a
  1285. new packet at sendTime */
  1286. if (tdiff < 0) {
  1287. earliest_to = sendTime;
  1288. } else {
  1289. getTiming(&tmng);
  1290. if (tdiff > 0 && tmng.cwnd > num_probes_active + .5) {
  1291. earliest_to = sendTime;
  1292. }
  1293. }
  1294. }
  1295. *when = earliest_to;
  1296. return false;
  1297. }
  1298. /* If there are pending probe timeouts, fills in when with the time of
  1299. the earliest one and returns true. Otherwise returns false and
  1300. puts now in when. */
  1301. bool HostScanStats::nextTimeout(struct timeval *when) {
  1302. struct timeval probe_to, earliest_to;
  1303. std::list<UltraProbe *>::iterator probeI;
  1304. bool firstgood = true;
  1305. assert(when);
  1306. memset(&probe_to, 0, sizeof(probe_to));
  1307. memset(&earliest_to, 0, sizeof(earliest_to));
  1308. for (probeI = probes_outstanding.begin(); probeI != probes_outstanding.end();
  1309. probeI++) {
  1310. if (!(*probeI)->timedout) {
  1311. TIMEVAL_ADD(probe_to, (*probeI)->sent, probeTimeout());
  1312. if (firstgood || TIMEVAL_SUBTRACT(probe_to, earliest_to) < 0) {
  1313. earliest_to = probe_to;
  1314. firstgood = false;
  1315. }
  1316. }
  1317. }
  1318. *when = (firstgood) ? USI->now : earliest_to;
  1319. return (firstgood) ? false : true;
  1320. }
  1321. /* gives the maximum try number (try numbers start at zero and
  1322. increments for each retransmission) that may be used, based on
  1323. the scan type, observed network reliability, timing mode, etc.
  1324. This may change during the scan based on network traffic. If
  1325. capped is not null, it will be filled with true if the tryno is
  1326. at its upper limit. That often calls for a warning to be issued,
  1327. and marking of remaining timedout ports firewalled or whatever is
  1328. appropriate. If mayincrease is non-NULL, it is set to whether
  1329. the allowedTryno may increase again. If it is false, any probes
  1330. which have reached the given limit may be dealth with. */
  1331. unsigned int HostScanStats::allowedTryno(bool *capped, bool *mayincrease) {
  1332. std::list<UltraProbe *>::iterator probeI;
  1333. UltraProbe *probe = NULL;
  1334. bool allfinished = true;
  1335. unsigned int maxval = 0;
  1336. /* TODO: This should perhaps differ by scan type. */
  1337. maxval = MAX(1, max_successful_tryno + 1);
  1338. if (maxval > USI->perf.tryno_cap) {
  1339. if (capped)
  1340. *capped = true;
  1341. maxval = USI->perf.tryno_cap;
  1342. tryno_mayincrease = false; /* It never exceeds the cap */
  1343. } else if (capped) *capped = false;
  1344. /* Decide if the tryno can possibly increase. */
  1345. if (tryno_mayincrease && num_probes_active == 0 && freshPortsLeft() == 0) {
  1346. /* If every outstanding probe is timedout and at maxval, then no further
  1347. retransmits are necessary. */
  1348. for (probeI = probes_outstanding.begin();
  1349. probeI != probes_outstanding.end(); probeI++) {
  1350. probe = *probeI;
  1351. assert(probe->timedout);
  1352. if (!probe->retransmitted && !probe->isPing() && probe->tryno < maxval) {
  1353. /* Needs at least one more retransmit. */
  1354. allfinished = false;
  1355. break;
  1356. }
  1357. }
  1358. if (allfinished)
  1359. tryno_mayincrease = false;
  1360. }
  1361. if (mayincrease)
  1362. *mayincrease = tryno_mayincrease;
  1363. return maxval;
  1364. }
  1365. UltraScanInfo::UltraScanInfo() {
  1366. }
  1367. UltraScanInfo::~UltraScanInfo() {
  1368. while (!incompleteHosts.empty()) {
  1369. delete incompleteHosts.front();
  1370. incompleteHosts.pop_front();
  1371. }
  1372. while (!completedHosts.empty()) {
  1373. delete completedHosts.front();
  1374. completedHosts.pop_front();
  1375. }
  1376. delete gstats;
  1377. delete SPM;
  1378. if (rawsd >= 0) {
  1379. close(rawsd);
  1380. rawsd = -1;
  1381. }
  1382. if (pd) {
  1383. pcap_close(pd);
  1384. pd = NULL;
  1385. }
  1386. if (ethsd) {
  1387. ethsd = NULL; /* NO need to eth_close it due to caching */
  1388. }
  1389. }
  1390. /* Returns true if this scan is a "raw" scan. A raw scan is ont that requires a
  1391. raw socket or ethernet handle to send, or a pcap sniffer to receive.
  1392. Basically, any scan type except pure TCP connect scans are raw. */
  1393. bool UltraScanInfo::isRawScan() {
  1394. return scantype != CONNECT_SCAN
  1395. && (tcp_scan || udp_scan || sctp_scan || prot_scan || ping_scan_arp || ping_scan_nd
  1396. || (ping_scan && (ptech.rawicmpscan || ptech.rawtcpscan || ptech.rawudpscan
  1397. || ptech.rawsctpscan || ptech.rawprotoscan)));
  1398. }
  1399. /* A circular buffer of the incompleteHosts. nextIncompleteHost() gives
  1400. the next one. The first time it is called, it will give the
  1401. first host in the list. If incompleteHosts is empty, returns
  1402. NULL. */
  1403. HostScanStats *UltraScanInfo::nextIncompleteHost() {
  1404. HostScanStats *nxt;
  1405. if (incompleteHosts.empty())
  1406. return NULL;
  1407. nxt = *nextI;
  1408. nextI++;
  1409. if (nextI == incompleteHosts.end())
  1410. nextI = incompleteHosts.begin();
  1411. return nxt;
  1412. }
  1413. /* Return a number between 0.0 and 1.0 inclusive indicating how much of the scan
  1414. is done. */
  1415. double UltraScanInfo::getCompletionFraction() {
  1416. std::list<HostScanStats *>::iterator hostI;
  1417. double total;
  1418. /* Add 1 for each completed host. */
  1419. total = gstats->numtargets - numIncompleteHosts();
  1420. /* Get the completion fraction for each incomplete host. */
  1421. for (hostI = incompleteHosts.begin(); hostI != incompleteHosts.end(); hostI++) {
  1422. HostScanStats *host = *hostI;
  1423. int maxtries = host->allowedTryno(NULL, NULL) + 1;
  1424. double thishostpercdone;
  1425. // This is inexact (maxtries - 1) because numprobes_sent includes
  1426. // at least one try of ports_finished.
  1427. thishostpercdone = host->ports_finished * (maxtries - 1) + host->numprobes_sent;
  1428. thishostpercdone /= maxtries * gstats->numprobes;
  1429. if (thishostpercdone >= 0.9999)
  1430. thishostpercdone = 0.9999;
  1431. total += thishostpercdone;
  1432. }
  1433. return total / gstats->numtargets;
  1434. }
  1435. /* Initialize the state for ports that don't receive a response in all the
  1436. targets. */
  1437. static void set_default_port_state(std::vector<Target *> &targets, stype scantype) {
  1438. std::vector<Target *>::iterator target;
  1439. for (target = targets.begin(); target != targets.end(); target++) {
  1440. switch (scantype) {
  1441. case SYN_SCAN:
  1442. case ACK_SCAN:
  1443. case WINDOW_SCAN:
  1444. case CONNECT_SCAN:
  1445. (*target)->ports.setDefaultPortState(IPPROTO_TCP, PORT_FILTERED);
  1446. break;
  1447. case SCTP_INIT_SCAN:
  1448. (*target)->ports.setDefaultPortState(IPPROTO_SCTP, PORT_FILTERED);
  1449. break;
  1450. case NULL_SCAN:
  1451. case FIN_SCAN:
  1452. case MAIMON_SCAN:
  1453. case XMAS_SCAN:
  1454. (*target)->ports.setDefaultPortState(IPPROTO_TCP, PORT_OPENFILTERED);
  1455. break;
  1456. case UDP_SCAN:
  1457. (*target)->ports.setDefaultPortState(IPPROTO_UDP, PORT_OPENFILTERED);
  1458. break;
  1459. case IPPROT_SCAN:
  1460. (*target)->ports.setDefaultPortState(IPPROTO_IP, PORT_OPENFILTERED);
  1461. break;
  1462. case SCTP_COOKIE_ECHO_SCAN:
  1463. (*target)->ports.setDefaultPortState(IPPROTO_SCTP, PORT_OPENFILTERED);
  1464. break;
  1465. case PING_SCAN:
  1466. case PING_SCAN_ARP:
  1467. case PING_SCAN_ND:
  1468. break;
  1469. default:
  1470. fatal("Unexpected scan type found in %s()", __func__);
  1471. }
  1472. }
  1473. }
  1474. /* Order of initializations in this function CAN BE IMPORTANT, so be careful
  1475. mucking with it. */
  1476. void UltraScanInfo::Init(std::vector<Target *> &Targets, struct scan_lists *pts, stype scantp) {
  1477. unsigned int targetno = 0;
  1478. HostScanStats *hss;
  1479. int num_timedout = 0;
  1480. gettimeofday(&now, NULL);
  1481. ports = pts;
  1482. seqmask = get_random_u32();
  1483. scantype = scantp;
  1484. SPM = new ScanProgressMeter(scantype2str(scantype));
  1485. send_rate_meter.start(&now);
  1486. tcp_scan = udp_scan = sctp_scan = prot_scan = false;
  1487. ping_scan = noresp_open_scan = ping_scan_arp = ping_scan_nd = false;
  1488. memset((char *) &ptech, 0, sizeof(ptech));
  1489. switch (scantype) {
  1490. case FIN_SCAN:
  1491. case XMAS_SCAN:
  1492. case MAIMON_SCAN:
  1493. case NULL_SCAN:
  1494. noresp_open_scan = true;
  1495. case ACK_SCAN:
  1496. case CONNECT_SCAN:
  1497. case SYN_SCAN:
  1498. case WINDOW_SCAN:
  1499. tcp_scan = true;
  1500. break;
  1501. case UDP_SCAN:
  1502. noresp_open_scan = true;
  1503. udp_scan = true;
  1504. break;
  1505. case SCTP_INIT_SCAN:
  1506. case SCTP_COOKIE_ECHO_SCAN:
  1507. sctp_scan = true;
  1508. break;
  1509. case IPPROT_SCAN:
  1510. noresp_open_scan = true;
  1511. prot_scan = true;
  1512. break;
  1513. case PING_SCAN:
  1514. ping_scan = true;
  1515. /* What kind of pings are we doing? */
  1516. if (o.pingtype & (PINGTYPE_ICMP_PING | PINGTYPE_ICMP_MASK | PINGTYPE_ICMP_TS))
  1517. ptech.rawicmpscan = 1;
  1518. if (o.pingtype & PINGTYPE_UDP)
  1519. ptech.rawudpscan = 1;
  1520. if (o.pingtype & PINGTYPE_SCTP_INIT)
  1521. ptech.rawsctpscan = 1;
  1522. if (o.pingtype & PINGTYPE_TCP) {
  1523. if (o.isr00t)
  1524. ptech.rawtcpscan = 1;
  1525. else
  1526. ptech.connecttcpscan = 1;
  1527. }
  1528. if (o.pingtype & PINGTYPE_PROTO)
  1529. ptech.rawprotoscan = 1;
  1530. if (o.pingtype & PINGTYPE_CONNECTTCP)
  1531. ptech.connecttcpscan = 1;
  1532. break;
  1533. case PING_SCAN_ARP:
  1534. ping_scan = true;
  1535. ping_scan_arp = true;
  1536. break;
  1537. case PING_SCAN_ND:
  1538. ping_scan = true;
  1539. ping_scan_nd = true;
  1540. break;
  1541. default:
  1542. break;
  1543. }
  1544. set_default_port_state(Targets, scantype);
  1545. perf.init();
  1546. /* Keep a completed host around for a standard TCP MSL (2 min) */
  1547. completedHostLifetime = 120000;
  1548. memset(&lastCompletedHostRemoval, 0, sizeof(lastCompletedHostRemoval));
  1549. for (targetno = 0; targetno < Targets.size(); targetno++) {
  1550. if (Targets[targetno]->timedOut(&now)) {
  1551. num_timedout++;
  1552. continue;
  1553. }
  1554. hss = new HostScanStats(Targets[targetno], this);
  1555. incompleteHosts.push_back(hss);
  1556. }
  1557. numInitialTargets = Targets.size();
  1558. nextI = incompleteHosts.begin();
  1559. gstats = new GroupScanStats(this); /* Peeks at several elements in USI - careful of order */
  1560. gstats->num_hosts_timedout += num_timedout;
  1561. pd = NULL;
  1562. rawsd = -1;
  1563. ethsd = NULL;
  1564. /* See if we need an ethernet handle or raw socket. Basically, it's if we
  1565. aren't doing a TCP connect scan, or if we're doing a ping scan that
  1566. requires it. */
  1567. if (isRawScan()) {
  1568. if (ping_scan_arp || (ping_scan_nd && o.sendpref != PACKET_SEND_IP_STRONG) || ((o.sendpref & PACKET_SEND_ETH) &&
  1569. Targets[0]->ifType() == devt_ethernet)) {
  1570. /* We'll send ethernet packets with dnet */
  1571. ethsd = eth_open_cached(Targets[0]->deviceName());
  1572. if (ethsd == NULL)
  1573. fatal("dnet: Failed to open device %s", Targets[0]->deviceName());
  1574. rawsd = -1;
  1575. } else {
  1576. #ifdef WIN32
  1577. win32_fatal_raw_sockets(Targets[0]->deviceName());
  1578. #endif
  1579. rawsd = nmap_raw_socket();
  1580. if (rawsd < 0)
  1581. pfatal("socket troubles in %s", __func__);
  1582. /* We do not wan't to unblock the socket since we want to wait
  1583. if kernel send buffers fill up rather than get ENOBUF, and
  1584. we won't be receiving on the socket anyway
  1585. unblock_socket(rawsd);*/
  1586. ethsd = NULL;
  1587. }
  1588. }
  1589. }
  1590. /* Return the total number of probes that may be sent to each host. This never
  1591. changes after initialization. */
  1592. unsigned int UltraScanInfo::numProbesPerHost() {
  1593. unsigned int numprobes = 0;
  1594. if (tcp_scan) {
  1595. numprobes = ports->tcp_count;
  1596. } else if (udp_scan) {
  1597. numprobes = ports->udp_count;
  1598. } else if (sctp_scan) {
  1599. numprobes = ports->sctp_count;
  1600. } else if (prot_scan) {
  1601. numprobes = ports->prot_count;
  1602. } else if (ping_scan_arp) {
  1603. numprobes = 1;
  1604. } else if (ping_scan_nd) {
  1605. numprobes = 1;
  1606. } else if (ping_scan) {
  1607. numprobes = 0;
  1608. if (ptech.rawtcpscan) {
  1609. if (o.pingtype & PINGTYPE_TCP_USE_ACK)
  1610. numprobes += ports->ack_ping_count;
  1611. if (o.pingtype & PINGTYPE_TCP_USE_SYN)
  1612. numprobes += ports->syn_ping_count;
  1613. }
  1614. if (ptech.rawudpscan)
  1615. numprobes += ports->udp_ping_count;
  1616. if (ptech.rawsctpscan)
  1617. numprobes += ports->sctp_ping_count;
  1618. if (ptech.rawicmpscan) {
  1619. if (o.pingtype & PINGTYPE_ICMP_PING)
  1620. numprobes++;
  1621. if (o.pingtype & PINGTYPE_ICMP_MASK)
  1622. numprobes++;
  1623. if (o.pingtype & PINGTYPE_ICMP_TS)
  1624. numprobes++;
  1625. }
  1626. if (ptech.rawprotoscan)
  1627. numprobes += ports->proto_ping_count;
  1628. if (ptech.connecttcpscan)
  1629. numprobes += ports->syn_ping_count;
  1630. } else assert(0);
  1631. return numprobes;
  1632. }
  1633. /* Consults with the group stats, and the hstats for every
  1634. incomplete hosts to determine whether any probes may be sent.
  1635. Returns true if they can be sent immediately. If when is
  1636. non-NULL, it is filled with the next possible time that probes
  1637. can be sent, assuming no probe responses are received (call it
  1638. again if they are). when will be now, if the function returns
  1639. true */
  1640. bool UltraScanInfo::sendOK(struct timeval *when) {
  1641. struct timeval lowhtime = {0};
  1642. struct timeval tmptv;
  1643. std::list<HostScanStats *>::iterator host;
  1644. bool ggood = false;
  1645. bool thisHostGood = false;
  1646. bool foundgood = false;
  1647. ggood = gstats->sendOK(when);
  1648. if (!ggood) {
  1649. if (when) {
  1650. lowhtime = *when;
  1651. // Can't do anything until global is OK - means packet receipt
  1652. // or probe timeout.
  1653. for (host = incompleteHosts.begin(); host != incompleteHosts.end();
  1654. host++) {
  1655. if ((*host)->nextTimeout(&tmptv)) {
  1656. if (TIMEVAL_SUBTRACT(tmptv, lowhtime) < 0)
  1657. lowhtime = tmptv;
  1658. }
  1659. }
  1660. *when = lowhtime;
  1661. }
  1662. } else {
  1663. for (host = incompleteHosts.begin(); host != incompleteHosts.end(); host++) {
  1664. thisHostGood = (*host)->sendOK(&tmptv);
  1665. if (ggood && thisHostGood) {
  1666. lowhtime = tmptv;
  1667. foundgood = true;
  1668. break;
  1669. }
  1670. if (!foundgood || TIMEVAL_SUBTRACT(lowhtime, tmptv) > 0) {
  1671. lowhtime = tmptv;
  1672. foundgood = true;
  1673. }
  1674. }
  1675. assert(foundgood);
  1676. }
  1677. /* Defer to the group stats if they need a shorter delay to enforce a minimum
  1678. packet sending rate. */
  1679. if (o.min_packet_send_rate != 0.0) {
  1680. if (TIMEVAL_MSEC_SUBTRACT(gstats->send_no_later_than, lowhtime) < 0)
  1681. lowhtime = gstats->send_no_later_than;
  1682. }
  1683. if (TIMEVAL_MSEC_SUBTRACT(lowhtime, now) < 0)
  1684. lowhtime = now;
  1685. if (when)
  1686. *when = lowhtime;
  1687. return (TIMEVAL_MSEC_SUBTRACT(lowhtime, now) == 0) ? true : false;
  1688. }
  1689. /* Find a HostScanStats by its IP address in the incomplete and completed lists.
  1690. Returns NULL if none are found. */
  1691. HostScanStats *UltraScanInfo::findHost(struct sockaddr_storage *ss) {
  1692. std::list<HostScanStats *>::iterator hss;
  1693. struct sockaddr_storage target_addr;
  1694. size_t target_addr_len;
  1695. for (hss = incompleteHosts.begin(); hss != incompleteHosts.end(); hss++) {
  1696. target_addr_len = sizeof(target_addr);
  1697. (*hss)->target->TargetSockAddr(&target_addr, &target_addr_len);
  1698. if (sockaddr_storage_cmp(&target_addr, ss) == 0) {
  1699. if (o.debugging > 2)
  1700. log_write(LOG_STDOUT, "Found %s in incomplete hosts list.\n", (*hss)->target->targetipstr());
  1701. return *hss;
  1702. }
  1703. }
  1704. for (hss = completedHosts.begin(); hss != completedHosts.end(); hss++) {
  1705. target_addr_len = sizeof(target_addr);
  1706. (*hss)->target->TargetSockAddr(&target_addr, &target_addr_len);
  1707. if (sockaddr_storage_cmp(&target_addr, ss) == 0) {
  1708. if (o.debugging > 2)
  1709. log_write(LOG_STDOUT, "Found %s in completed hosts list.\n", (*hss)->target->targetipstr());
  1710. return *hss;
  1711. }
  1712. }
  1713. return NULL;
  1714. }
  1715. bool UltraScanInfo::numIncompleteHostsLessThan(unsigned int n) {
  1716. std::list<HostScanStats *>::iterator hostI;
  1717. unsigned int count;
  1718. count = 0;
  1719. hostI = incompleteHosts.begin();
  1720. while (count < n && hostI != incompleteHosts.end()) {
  1721. hostI++;
  1722. count++;
  1723. }
  1724. return count < n;
  1725. }
  1726. static bool pingprobe_is_better(const probespec *new_probe, int new_state,
  1727. const probespec *old_probe, int old_state);
  1728. /* Removes any hosts that have completed their scans from the incompleteHosts
  1729. list, and remove any hosts from completedHosts which have exceeded their
  1730. lifetime. Returns the number of hosts removed. */
  1731. int UltraScanInfo::removeCompletedHosts() {
  1732. std::list<HostScanStats *>::iterator hostI, nxt;
  1733. HostScanStats *hss = NULL;
  1734. int hostsRemoved = 0;
  1735. bool timedout = false;
  1736. /* We don't want to run this all of the time */
  1737. if ((unsigned) TIMEVAL_MSEC_SUBTRACT(now, lastCompletedHostRemoval) > completedHostLifetime / 2) {
  1738. for (hostI = completedHosts.begin(); hostI != completedHosts.end(); hostI = nxt) {
  1739. nxt = hostI;
  1740. nxt++;
  1741. hss = (*hostI);
  1742. /* Keep it if it's our port scan ping host */
  1743. if (hss == gstats->pinghost)
  1744. continue;
  1745. if ((unsigned) TIMEVAL_MSEC_SUBTRACT(now, hss->completiontime) > completedHostLifetime) {
  1746. completedHosts.erase(hostI);
  1747. hostsRemoved++;
  1748. }
  1749. }
  1750. lastCompletedHostRemoval = now;
  1751. }
  1752. for (hostI = incompleteHosts.begin(); hostI != incompleteHosts.end();
  1753. hostI = nxt) {
  1754. nxt = hostI;
  1755. nxt++;
  1756. hss = *hostI;
  1757. timedout = hss->target->timedOut(&now);
  1758. if (hss->completed() || timedout) {
  1759. /* A host to remove! First adjust nextI appropriately */
  1760. if (nextI == hostI && incompleteHosts.size() > 1) {
  1761. nextI++;
  1762. if (nextI == incompleteHosts.end())
  1763. nextI = incompleteHosts.begin();
  1764. }
  1765. if (o.verbose && gstats->numprobes > 50) {
  1766. int remain = incompleteHosts.size() - 1;
  1767. if (remain && !timedout)
  1768. log_write(LOG_STDOUT, "Completed %s against %s in %.2fs (%d %s)\n",
  1769. scantype2str(scantype), hss->target->targetipstr(),
  1770. TIMEVAL_MSEC_SUBTRACT(now, SPM->begin) / 1000.0, remain,
  1771. (remain == 1) ? "host left" : "hosts left");
  1772. else if (timedout)
  1773. log_write(LOG_STDOUT, "%s timed out during %s (%d %s)\n",
  1774. hss->target->targetipstr(), scantype2str(scantype), remain,
  1775. (remain == 1) ? "host left" : "hosts left");
  1776. }
  1777. if (o.debugging > 2) {
  1778. unsigned int num_outstanding_probes;
  1779. num_outstanding_probes = hss->num_probes_outstanding();
  1780. log_write(LOG_PLAIN, "Moving %s to completed hosts list with %d outstanding %s.\n",
  1781. hss->target->targetipstr(), num_outstanding_probes,
  1782. num_outstanding_probes == 1 ? "probe" : "probes");
  1783. if (o.debugging > 3) {
  1784. char tmpbuf[64];
  1785. std::list<UltraProbe *>::iterator iter;
  1786. for (iter = hss->probes_outstanding.begin(); iter != hss->probes_outstanding.end(); iter++)
  1787. log_write(LOG_PLAIN, "* %s\n", probespec2ascii((probespec *) (*iter)->pspec(), tmpbuf, sizeof(tmpbuf)));
  1788. }
  1789. }
  1790. hss->completiontime = now;
  1791. completedHosts.push_front(hss);
  1792. incompleteHosts.erase(hostI);
  1793. hostsRemoved++;
  1794. /* Consider making this host the new global ping host during its
  1795. retirement in the completed hosts list. */
  1796. HostScanStats *pinghost = gstats->pinghost;
  1797. if ((pinghost == NULL && hss->target->pingprobe.type != PS_NONE)
  1798. || (pinghost != NULL && pinghost->num_probes_active == 0
  1799. && !pingprobe_is_better(&pinghost->target->pingprobe, pinghost->target->pingprobe_state, &hss->target->pingprobe, hss->target->pingprobe_state))) {
  1800. if (o.debugging > 1)
  1801. log_write(LOG_PLAIN, "Changing global ping host to %s.\n", hss->target->targetipstr());
  1802. gstats->pinghost = hss;
  1803. }
  1804. if (timedout)
  1805. gstats->num_hosts_timedout++;
  1806. hss->target->stopTimeOutClock(&now);
  1807. }
  1808. }
  1809. return hostsRemoved;
  1810. }
  1811. /* Determines an ideal number of hosts to be scanned (port scan, os
  1812. scan, version detection, etc.) in parallel after the ping scan is
  1813. completed. This is a balance between efficiency (more hosts in
  1814. parallel often reduces scan time per host) and results latency (you
  1815. need to wait for all hosts to finish before Nmap can spit out the
  1816. results). Memory consumption usually also increases with the
  1817. number of hosts scanned in parallel, though rarely to significant
  1818. levels. */
  1819. int determineScanGroupSize(int hosts_scanned_so_far,
  1820. struct scan_lists *ports) {
  1821. int groupsize = 16;
  1822. if (o.UDPScan())
  1823. groupsize = 128;
  1824. else if (o.SCTPScan())
  1825. groupsize = 128;
  1826. else if (o.TCPScan()) {
  1827. groupsize = MAX(1024 / (ports->tcp_count ? ports->tcp_count : 1), 64);
  1828. if (ports->tcp_count > 1000 && o.timing_level <= 4) {
  1829. int quickgroupsz = 4;
  1830. if (o.timing_level == 4)
  1831. quickgroupsz = 8;
  1832. if (hosts_scanned_so_far == 0)
  1833. groupsize = quickgroupsz; // Give quick results for the very first batch
  1834. else if (hosts_scanned_so_far == quickgroupsz &&
  1835. groupsize > quickgroupsz * 2)
  1836. /* account for initial quick-scan to keep us aligned
  1837. on common network boundaries (e.g. /24) */
  1838. groupsize -= quickgroupsz;
  1839. }
  1840. }
  1841. groupsize = box(o.minHostGroupSz(), o.maxHostGroupSz(), groupsize);
  1842. return groupsize;
  1843. }
  1844. /* Initialize the ultra_timing_vals structure timing. The utt must be
  1845. TIMING_HOST or TIMING_GROUP. If you happen to have the current
  1846. time handy, pass it as now, otherwise pass NULL */
  1847. static void init_ultra_timing_vals(ultra_timing_vals *timing,
  1848. enum ultra_timing_type utt,
  1849. int num_hosts_in_group,
  1850. struct ultra_scan_performance_vars *perf,
  1851. struct timeval *now) {
  1852. timing->cwnd = (utt == TIMING_HOST) ? perf->host_initial_cwnd : perf->group_initial_cwnd;
  1853. timing->ssthresh = perf->initial_ssthresh; /* Will be reduced if any packets are dropped anyway */
  1854. timing->num_replies_expected = 0;
  1855. timing->num_replies_received = 0;
  1856. timing->num_updates = 0;
  1857. if (now)
  1858. timing->last_drop = *now;
  1859. else gettimeofday(&timing->last_drop, NULL);
  1860. }
  1861. /* Returns the next probe to try against target. Supports many
  1862. different types of probes (see probespec structure). Returns 0 and
  1863. fills in pspec if there is a new probe, -1 if there are none
  1864. left. */
  1865. static int get_next_target_probe(UltraScanInfo *USI, HostScanStats *hss,
  1866. probespec *pspec) {
  1867. assert(pspec);
  1868. if (USI->tcp_scan) {
  1869. if (hss->next_portidx >= USI->ports->tcp_count)
  1870. return -1;
  1871. if (USI->scantype == CONNECT_SCAN)
  1872. pspec->type = PS_CONNECTTCP;
  1873. else
  1874. pspec->type = PS_TCP;
  1875. pspec->proto = IPPROTO_TCP;
  1876. pspec->pd.tcp.dport = USI->ports->tcp_ports[hss->next_portidx++];
  1877. if (USI->scantype == CONNECT_SCAN)
  1878. pspec->pd.tcp.flags = TH_SYN;
  1879. else if (o.scanflags != -1)
  1880. pspec->pd.tcp.flags = o.scanflags;
  1881. else {
  1882. switch (USI->scantype) {
  1883. case SYN_SCAN:
  1884. pspec->pd.tcp.flags = TH_SYN;
  1885. break;
  1886. case ACK_SCAN:
  1887. pspec->pd.tcp.flags = TH_ACK;
  1888. break;
  1889. case XMAS_SCAN:
  1890. pspec->pd.tcp.flags = TH_FIN | TH_URG | TH_PUSH;
  1891. break;
  1892. case NULL_SCAN:
  1893. pspec->pd.tcp.flags = 0;
  1894. break;
  1895. case FIN_SCAN:
  1896. pspec->pd.tcp.flags = TH_FIN;
  1897. break;
  1898. case MAIMON_SCAN:
  1899. pspec->pd.tcp.flags = TH_FIN | TH_ACK;
  1900. break;
  1901. case WINDOW_SCAN:
  1902. pspec->pd.tcp.flags = TH_ACK;
  1903. break;
  1904. default:
  1905. assert(0);
  1906. break;
  1907. }
  1908. }
  1909. return 0;
  1910. } else if (USI->udp_scan) {
  1911. if (hss->next_portidx >= USI->ports->udp_count)
  1912. return -1;
  1913. pspec->type = PS_UDP;
  1914. pspec->proto = IPPROTO_UDP;
  1915. pspec->pd.udp.dport = USI->ports->udp_ports[hss->next_portidx++];
  1916. return 0;
  1917. } else if (USI->sctp_scan) {
  1918. if (hss->next_portidx >= USI->ports->sctp_count)
  1919. return -1;
  1920. pspec->type = PS_SCTP;
  1921. pspec->proto = IPPROTO_SCTP;
  1922. pspec->pd.sctp.dport = USI->ports->sctp_ports[hss->next_portidx++];
  1923. switch (USI->scantype) {
  1924. case SCTP_INIT_SCAN:
  1925. pspec->pd.sctp.chunktype = SCTP_INIT;
  1926. break;
  1927. case SCTP_COOKIE_ECHO_SCAN:
  1928. pspec->pd.sctp.chunktype = SCTP_COOKIE_ECHO;
  1929. break;
  1930. default:
  1931. assert(0);
  1932. }
  1933. return 0;
  1934. } else if (USI->prot_scan) {
  1935. if (hss->next_portidx >= USI->ports->prot_count)
  1936. return -1;
  1937. pspec->type = PS_PROTO;
  1938. pspec->proto = USI->ports->prots[hss->next_portidx++];
  1939. return 0;
  1940. } else if (USI->ping_scan_arp) {
  1941. if (hss->sent_arp)
  1942. return -1;
  1943. pspec->type = PS_ARP;
  1944. hss->sent_arp = true;
  1945. return 0;
  1946. } else if (USI->ping_scan_nd) {
  1947. if (hss->sent_arp)
  1948. return -1;
  1949. pspec->type = PS_ND;
  1950. hss->sent_arp = true;
  1951. return 0;
  1952. } else if (USI->ping_scan) {
  1953. /* This is ordered to try probes of higher effectiveness first:
  1954. -PE -PS -PA -PP -PU
  1955. -PA is slightly better than -PS when combined with -PE, but give -PS an
  1956. edge because it is less likely to be dropped by firewalls. */
  1957. if (USI->ptech.rawicmpscan) {
  1958. if (hss->target->af() == AF_INET6) {
  1959. pspec->type = PS_ICMPV6;
  1960. pspec->proto = IPPROTO_ICMPV6;
  1961. if ((o.pingtype & PINGTYPE_ICMP_PING) && !hss->sent_icmp_ping) {
  1962. hss->sent_icmp_ping = true;
  1963. pspec->pd.icmp.type = ICMPV6_ECHO;
  1964. pspec->pd.icmp.code = 0;
  1965. return 0;
  1966. }
  1967. }
  1968. pspec->type = PS_ICMP;
  1969. pspec->proto = IPPROTO_ICMP;
  1970. if ((o.pingtype & PINGTYPE_ICMP_PING) && !hss->sent_icmp_ping) {
  1971. hss->sent_icmp_ping = true;
  1972. pspec->pd.icmp.type = ICMP_ECHO;
  1973. pspec->pd.icmp.code = 0;
  1974. return 0;
  1975. }
  1976. }
  1977. if (USI->ptech.rawtcpscan) {
  1978. pspec->type = PS_TCP;
  1979. pspec->proto = IPPROTO_TCP;
  1980. if ((o.pingtype & PINGTYPE_TCP_USE_SYN)
  1981. && hss->next_synportpingidx < USI->ports->syn_ping_count) {
  1982. pspec->pd.tcp.dport = USI->ports->syn_ping_ports[hss->next_synportpingidx++];
  1983. pspec->pd.tcp.flags = TH_SYN;
  1984. return 0;
  1985. }
  1986. if ((o.pingtype & PINGTYPE_TCP_USE_ACK)
  1987. && hss->next_ackportpingidx < USI->ports->ack_ping_count) {
  1988. pspec->pd.tcp.dport = USI->ports->ack_ping_ports[hss->next_ackportpingidx++];
  1989. pspec->pd.tcp.flags = TH_ACK;
  1990. return 0;
  1991. }
  1992. }
  1993. if (USI->ptech.rawicmpscan) {
  1994. pspec->type = PS_ICMP;
  1995. pspec->proto = IPPROTO_ICMP;
  1996. if ((o.pingtype & PINGTYPE_ICMP_TS) && !hss->sent_icmp_ts) {
  1997. hss->sent_icmp_ts = true;
  1998. pspec->pd.icmp.type = ICMP_TSTAMP;
  1999. pspec->pd.icmp.code = 0;
  2000. return 0;
  2001. }
  2002. }
  2003. if (USI->ptech.rawudpscan && hss->next_udpportpingidx < USI->ports->udp_ping_count) {
  2004. pspec->type = PS_UDP;
  2005. pspec->proto = IPPROTO_UDP;
  2006. pspec->pd.udp.dport = USI->ports->udp_ping_ports[hss->next_udpportpingidx++];
  2007. return 0;
  2008. }
  2009. if (USI->ptech.rawsctpscan && hss->next_sctpportpingidx < USI->ports->sctp_ping_count) {
  2010. pspec->type = PS_SCTP;
  2011. pspec->proto = IPPROTO_SCTP;
  2012. pspec->pd.sctp.dport = USI->ports->sctp_ping_ports[hss->next_sctpportpingidx++];
  2013. pspec->pd.sctp.chunktype = SCTP_INIT;
  2014. return 0;
  2015. }
  2016. if (USI->ptech.rawprotoscan) {
  2017. pspec->type = PS_PROTO;
  2018. pspec->proto = USI->ports->proto_ping_ports[hss->next_protoportpingidx++];
  2019. return 0;
  2020. }
  2021. if (USI->ptech.connecttcpscan && hss->next_synportpingidx < USI->ports->syn_ping_count) {
  2022. pspec->type = PS_CONNECTTCP;
  2023. pspec->proto = IPPROTO_TCP;
  2024. pspec->pd.tcp.dport = USI->ports->syn_ping_ports[hss->next_synportpingidx++];
  2025. pspec->pd.tcp.flags = TH_SYN;
  2026. return 0;
  2027. }
  2028. if (USI->ptech.rawicmpscan) {
  2029. pspec->type = PS_ICMP;
  2030. pspec->proto = IPPROTO_ICMP;
  2031. if ((o.pingtype & PINGTYPE_ICMP_MASK) && !hss->sent_icmp_mask) {
  2032. hss->sent_icmp_mask = true;
  2033. pspec->pd.icmp.type = ICMP_MASK;
  2034. pspec->pd.icmp.code = 0;
  2035. return 0;
  2036. }
  2037. }
  2038. }
  2039. assert(0); /* TODO: need to handle other protocols */
  2040. return -1;
  2041. }
  2042. /* Returns the number of ports remaining to probe */
  2043. int HostScanStats::freshPortsLeft() {
  2044. if (USI->tcp_scan) {
  2045. if (next_portidx >= USI->ports->tcp_count)
  2046. return 0;
  2047. return USI->ports->tcp_count - next_portidx;
  2048. } else if (USI->udp_scan) {
  2049. if (next_portidx >= USI->ports->udp_count)
  2050. return 0;
  2051. return USI->ports->udp_count - next_portidx;
  2052. } else if (USI->sctp_scan) {
  2053. if (next_portidx >= USI->ports->sctp_count)
  2054. return 0;
  2055. return USI->ports->sctp_count - next_portidx;
  2056. } else if (USI->prot_scan) {
  2057. if (next_portidx >= USI->ports->prot_count)
  2058. return 0;
  2059. return USI->ports->prot_count - next_portidx;
  2060. } else if (USI->ping_scan_arp) {
  2061. if (sent_arp)
  2062. return 0;
  2063. return 1;
  2064. } else if (USI->ping_scan_nd) {
  2065. if (sent_arp)
  2066. return 0;
  2067. return 1;
  2068. } else if (USI->ping_scan) {
  2069. unsigned int num_probes = 0;
  2070. if (USI->ptech.rawtcpscan) {
  2071. if ((o.pingtype & PINGTYPE_TCP_USE_ACK)
  2072. && next_ackportpingidx < USI->ports->ack_ping_count)
  2073. num_probes += USI->ports->ack_ping_count - next_ackportpingidx;
  2074. if ((o.pingtype & PINGTYPE_TCP_USE_SYN)
  2075. && next_synportpingidx < USI->ports->syn_ping_count)
  2076. num_probes += USI->ports->syn_ping_count - next_synportpingidx;
  2077. }
  2078. if (USI->ptech.rawudpscan && next_udpportpingidx < USI->ports->udp_ping_count)
  2079. num_probes += USI->ports->udp_ping_count - next_udpportpingidx;
  2080. if (USI->ptech.rawsctpscan && next_sctpportpingidx < USI->ports->sctp_ping_count)
  2081. num_probes += USI->ports->sctp_ping_count - next_sctpportpingidx;
  2082. if (USI->ptech.rawicmpscan) {
  2083. if ((o.pingtype & PINGTYPE_ICMP_PING) && !sent_icmp_ping)
  2084. num_probes++;
  2085. if ((o.pingtype & PINGTYPE_ICMP_MASK) && !sent_icmp_mask)
  2086. num_probes++;
  2087. if ((o.pingtype & PINGTYPE_ICMP_TS) && !sent_icmp_ts)
  2088. num_probes++;
  2089. }
  2090. if (USI->ptech.rawprotoscan)
  2091. num_probes += USI->ports->proto_ping_count - next_protoportpingidx;
  2092. if (USI->ptech.connecttcpscan && next_synportpingidx < USI->ports->syn_ping_count)
  2093. num_probes += USI->ports->syn_ping_count - next_synportpingidx;
  2094. return num_probes;
  2095. }
  2096. assert(0);
  2097. return 0;
  2098. }
  2099. /* Removes a probe from probes_outstanding, adjusts HSS and USS
  2100. active probe stats accordingly, then deletes the probe. */
  2101. void HostScanStats::destroyOutstandingProbe(std::list<UltraProbe *>::iterator probeI) {
  2102. UltraProbe *probe = *probeI;
  2103. assert(!probes_outstanding.empty());
  2104. if (!probe->timedout) {
  2105. assert(num_probes_active > 0);
  2106. num_probes_active--;
  2107. assert(USI->gstats->num_probes_active > 0);
  2108. USI->gstats->num_probes_active--;
  2109. }
  2110. if (!probe->isPing() && probe->timedout && !probe->retransmitted) {
  2111. assert(num_probes_waiting_retransmit > 0);
  2112. num_probes_waiting_retransmit--;
  2113. }
  2114. /* Remove it from scan watch lists, if it exists on them. */
  2115. if (probe->type == UltraProbe::UP_CONNECT && probe->CP()->sd > 0)
  2116. USI->gstats->CSI->clearSD(probe->CP()->sd);
  2117. probes_outstanding.erase(probeI);
  2118. delete probe;
  2119. }
  2120. /* Removes all probes from probes_outstanding using
  2121. destroyOutstandingProbe. This is used in ping scan to quit waiting
  2122. for responses once a host is known to be up. Invalidates iterators
  2123. pointing into probes_outstanding. */
  2124. void HostScanStats::destroyAllOutstandingProbes() {
  2125. while (!probes_outstanding.empty())
  2126. destroyOutstandingProbe(probes_outstanding.begin());
  2127. }
  2128. /* Adjust host and group timeouts (struct timeout_info) based on a received
  2129. packet. If rcvdtime is NULL, nothing is updated.
  2130. This function is called for every probe response received, in order to keep
  2131. an accurate timeout estimate. ultrascan_adjust_timing, on the other hand, is
  2132. not called when a response is not useful for adjusting other timing
  2133. variables. */
  2134. static void ultrascan_adjust_timeouts(UltraScanInfo *USI, HostScanStats *hss,
  2135. UltraProbe *probe,
  2136. struct timeval *rcvdtime) {
  2137. if (rcvdtime == NULL)
  2138. return;
  2139. adjust_timeouts2(&(probe->sent), rcvdtime, &(hss->target->to));
  2140. adjust_timeouts2(&(probe->sent), rcvdtime, &(USI->gstats->to));
  2141. USI->gstats->lastrcvd = hss->lastrcvd = *rcvdtime;
  2142. }
  2143. /* Adjust host and group congestion control variables (struct ultra_timing_vals)
  2144. and host send delay (struct send_delay_nfo) based on a received packet. Use
  2145. rcvdtime == NULL to indicate that you have given up on a probe and want to
  2146. count this as a DROPPED PACKET. */
  2147. static void ultrascan_adjust_timing(UltraScanInfo *USI, HostScanStats *hss,
  2148. UltraProbe *probe,
  2149. struct timeval *rcvdtime) {
  2150. int ping_magnifier = (probe->isPing()) ? USI->perf.ping_magnifier : 1;
  2151. USI->gstats->timing.num_replies_expected++;
  2152. USI->gstats->timing.num_updates++;
  2153. hss->timing.num_replies_expected++;
  2154. hss->timing.num_updates++;
  2155. /* Notice a drop if
  2156. 1) We get a response to a retransmitted probe (meaning the first reply was
  2157. dropped), or
  2158. 2) We got no response to a timing ping. */
  2159. if ((probe->tryno > 0 && rcvdtime != NULL)
  2160. || (probe->isPing() && rcvdtime == NULL)) {
  2161. if (o.debugging > 1)
  2162. log_write(LOG_PLAIN, "Ultrascan DROPPED %sprobe packet to %s detected\n", probe->isPing() ? "PING " : "", hss->target->targetipstr());
  2163. // Drops often come in big batches, but we only want one decrease per batch.
  2164. if (TIMEVAL_AFTER(probe->sent, hss->timing.last_drop))
  2165. hss->timing.drop(hss->num_probes_active, &USI->perf, &USI->now);
  2166. if (TIMEVAL_AFTER(probe->sent, USI->gstats->timing.last_drop))
  2167. USI->gstats->timing.drop_group(USI->gstats->num_probes_active, &USI->perf, &USI->now);
  2168. }
  2169. /* If !probe->isPing() and rcvdtime == NULL, do nothing. */
  2170. /* Increase the window for a positive reply. This can overlap with case (1)
  2171. above. */
  2172. if (rcvdtime != NULL) {
  2173. USI->gstats->timing.ack(&USI->perf, ping_magnifier);
  2174. hss->timing.ack(&USI->perf, ping_magnifier);
  2175. }
  2176. /* If packet drops are particularly bad, enforce a delay between
  2177. packet sends (useful for cases such as UDP scan where responses
  2178. are frequently rate limited by dest machines or firewalls) */
  2179. /* First we decide whether this packet counts as a drop for send
  2180. delay calculation purposes. This statement means if (a ping since last boost failed, or the previous packet was both sent after the last boost and dropped) */
  2181. if ((probe->isPing() && rcvdtime == NULL && TIMEVAL_AFTER(probe->sent, hss->sdn.last_boost)) ||
  2182. (probe->tryno > 0 && rcvdtime != NULL && TIMEVAL_AFTER(probe->prevSent, hss->sdn.last_boost))) {
  2183. hss->sdn.droppedRespSinceDelayChanged++;
  2184. // printf("SDELAY: increasing drops to %d (good: %d; tryno: %d, sent: %.4fs; prevSent: %.4fs, last_boost: %.4fs\n", hss->sdn.droppedRespSinceDelayChanged, hss->sdn.goodRespSinceDelayChanged, probe->tryno, o.TimeSinceStartMS(&probe->sent) / 1000.0, o.TimeSinceStartMS(&probe->prevSent) / 1000.0, o.TimeSinceStartMS(&hss->sdn.last_boost) / 1000.0);
  2185. } else if (rcvdtime) {
  2186. hss->sdn.goodRespSinceDelayChanged++;
  2187. // printf("SDELAY: increasing good to %d (bad: %d)\n", hss->sdn.goodRespSinceDelayChanged, hss->sdn.droppedRespSinceDelayChanged);
  2188. }
  2189. /* Now change the send delay if necessary */
  2190. unsigned int oldgood = hss->sdn.goodRespSinceDelayChanged;
  2191. unsigned int oldbad = hss->sdn.droppedRespSinceDelayChanged;
  2192. double threshold = (o.timing_level >= 4) ? 0.40 : 0.30;
  2193. if (oldbad > 10 && (oldbad / ((double) oldbad + oldgood) > threshold)) {
  2194. unsigned int olddelay = hss->sdn.delayms;
  2195. hss->boostScanDelay();
  2196. if (o.verbose && hss->sdn.delayms != olddelay)
  2197. log_write(LOG_PLAIN, "Increasing send delay for %s from %d to %d due to %d out of %d dropped probes since last increase.\n",
  2198. hss->target->targetipstr(), olddelay, hss->sdn.delayms, oldbad,
  2199. oldbad + oldgood);
  2200. }
  2201. }
  2202. /* Mark an outstanding probe as timedout. Adjusts stats
  2203. accordingly. For connect scans, this closes the socket. */
  2204. void HostScanStats::markProbeTimedout(std::list<UltraProbe *>::iterator probeI) {
  2205. UltraProbe *probe = *probeI;
  2206. assert(!probe->timedout);
  2207. assert(!probe->retransmitted);
  2208. probe->timedout = true;
  2209. assert(num_probes_active > 0);
  2210. num_probes_active--;
  2211. assert(USI->gstats->num_probes_active > 0);
  2212. USI->gstats->num_probes_active--;
  2213. ultrascan_adjust_timing(USI, this, probe, NULL);
  2214. if (!probe->isPing())
  2215. /* I'll leave it in the queue in case some response ever does come */
  2216. num_probes_waiting_retransmit++;
  2217. if (probe->type == UltraProbe::UP_CONNECT && probe->CP()->sd >= 0 ) {
  2218. /* Free the socket as that is a valuable resource, though it is a shame
  2219. late responses will not be permitted */
  2220. USI->gstats->CSI->clearSD(probe->CP()->sd);
  2221. close(probe->CP()->sd);
  2222. probe->CP()->sd = -1;
  2223. }
  2224. }
  2225. bool HostScanStats::completed() {
  2226. /* If there are probes active or awaiting retransmission, we are not done. */
  2227. if (num_probes_active != 0 || num_probes_waiting_retransmit != 0
  2228. || !probe_bench.empty() || !retry_stack.empty()) {
  2229. return false;
  2230. }
  2231. /* With ping scan, we are done once we know the host is up or down. */
  2232. if (USI->ping_scan && ((target->flags & HOST_UP)
  2233. || (target->flags & HOST_DOWN) || target->weird_responses)) {
  2234. return true;
  2235. }
  2236. /* With other types of scan, we are done when there are no more ports to
  2237. probe. */
  2238. return freshPortsLeft() == 0;
  2239. }
  2240. /* The try number or ping sequence number can be encoded into a TCP SEQ or ACK
  2241. field. This returns a 32-bit number which encodes both of these values along
  2242. with a simple checksum. Decoding is done by seq32_decode. */
  2243. static u32 seq32_encode(UltraScanInfo *USI, unsigned int trynum,
  2244. unsigned int pingseq) {
  2245. u32 seq;
  2246. u16 nfo;
  2247. /* We'll let trynum and pingseq each be 8 bits. */
  2248. nfo = (pingseq << 8) + trynum;
  2249. /* Mirror the data to ensure it is reconstructed correctly. */
  2250. seq = (nfo << 16) + nfo;
  2251. /* Obfuscate it a little */
  2252. seq = seq ^ USI->seqmask;
  2253. return seq;
  2254. }
  2255. /* Undoes seq32_encode. This extracts a try number and a port number from a
  2256. 32-bit value. Returns true if the checksum is correct, false otherwise. */
  2257. static bool seq32_decode(const UltraScanInfo *USI, u32 seq,
  2258. unsigned int *trynum, unsigned int *pingseq) {
  2259. if (trynum)
  2260. *trynum = 0;
  2261. if (pingseq)
  2262. *pingseq = 0;
  2263. /* Undo the mask xor. */
  2264. seq = seq ^ USI->seqmask;
  2265. /* Check that both sides are the same. */
  2266. if ((seq >> 16) != (seq & 0xFFFF))
  2267. return false;
  2268. if (trynum)
  2269. *trynum = seq & 0xFF;
  2270. if (pingseq)
  2271. *pingseq = (seq & 0xFF00) >> 8;
  2272. return true;
  2273. }
  2274. /* The try number or ping sequence number can be encoded in the source port
  2275. number. This returns a new port number that contains a try number or ping
  2276. sequence number encoded into the given port number. trynum and pingseq may
  2277. not both be non-zero. Decoding is done by sport_decode. */
  2278. static u16 sport_encode(UltraScanInfo *USI, u16 base_portno, unsigned int trynum,
  2279. unsigned int pingseq) {
  2280. u16 portno;
  2281. /* trynum and pingseq both being non-zero is not currently supported. */
  2282. assert(trynum == 0 || pingseq == 0);
  2283. portno = base_portno;
  2284. if (pingseq > 0) {
  2285. /* Encode the pingseq. trynum = 0. */
  2286. portno += USI->perf.tryno_cap + pingseq;
  2287. } else {
  2288. /* Encode the trynum. pingseq = 0. */
  2289. portno += trynum;
  2290. }
  2291. return portno;
  2292. }
  2293. /* Undoes sport_encode. This extracts a try number and ping sequence number from
  2294. a port number given a "base" port number (the one given to
  2295. sport_encode). Returns true if the decoded values seem reasonable, false
  2296. otherwise. */
  2297. static bool sport_decode(const UltraScanInfo *USI, u16 base_portno, u16 portno,
  2298. unsigned int *trynum, unsigned int *pingseq) {
  2299. unsigned int t;
  2300. t = portno - base_portno;
  2301. if (t > USI->perf.tryno_cap + 256) {
  2302. return false;
  2303. } else if (t > USI->perf.tryno_cap) {
  2304. /* The ping sequence number was encoded. */
  2305. if (pingseq)
  2306. *pingseq = t - USI->perf.tryno_cap;
  2307. if (trynum)
  2308. *trynum = 0;
  2309. } else {
  2310. /* The try number was encoded. */
  2311. if (pingseq)
  2312. *pingseq = 0;
  2313. if (trynum)
  2314. *trynum = t;
  2315. }
  2316. return true;
  2317. }
  2318. static bool icmp_probe_match(const UltraScanInfo *USI, const UltraProbe *probe,
  2319. const struct ppkt *ping,
  2320. const struct sockaddr_storage *target_src,
  2321. const struct sockaddr_storage *src,
  2322. const struct sockaddr_storage *dst,
  2323. u8 proto,
  2324. u32 ipid) {
  2325. /* Check if it is ICMP or ICMPV6. */
  2326. if (probe->protocol() != IPPROTO_ICMPV6 && probe->protocol() != IPPROTO_ICMP)
  2327. return false;
  2328. /* Ensure the connection info matches. */
  2329. if (sockaddr_storage_cmp(target_src, dst) != 0)
  2330. return false;
  2331. /* Don't match a timestamp request with an echo reply, for example. */
  2332. if (proto == IPPROTO_ICMP &&
  2333. ((ping->type == 0 && probe->pspec()->pd.icmp.type != 8) ||
  2334. (ping->type == 14 && probe->pspec()->pd.icmp.type != 13) ||
  2335. (ping->type == 18 && probe->pspec()->pd.icmp.type != 17)))
  2336. return false;
  2337. if (proto == IPPROTO_ICMPV6 &&
  2338. (ping->type == 129 && probe->pspec()->pd.icmpv6.type != 128))
  2339. return false;
  2340. /* Sometimes we get false results when scanning localhost with
  2341. -p- because we scan localhost with src port = dst port and
  2342. see our outgoing packet and think it is a response. */
  2343. if (probe->dport() == probe->sport() &&
  2344. sockaddr_storage_cmp(src, dst) == 0 &&
  2345. probe->ipid() == ipid)
  2346. return false; /* We saw the packet we ourselves sent */
  2347. /* Check that the randomly-generated ping ident matches. */
  2348. if (ntohs(ping->id) != probe->icmpid())
  2349. return false;
  2350. return true;
  2351. }
  2352. static bool tcp_probe_match(const UltraScanInfo *USI, const UltraProbe *probe,
  2353. const HostScanStats *hss, const struct tcp_hdr *tcp,
  2354. const struct sockaddr_storage *src, const struct sockaddr_storage *dst,
  2355. u32 ipid) {
  2356. const struct probespec_tcpdata *probedata;
  2357. struct sockaddr_storage srcaddr;
  2358. size_t srcaddr_len;
  2359. unsigned int tryno, pingseq;
  2360. bool goodseq;
  2361. if (probe->protocol() != IPPROTO_TCP)
  2362. return false;
  2363. srcaddr_len = sizeof(srcaddr);
  2364. hss->target->SourceSockAddr(&srcaddr, &srcaddr_len);
  2365. /* Ensure the connection info matches. */
  2366. if (probe->dport() != ntohs(tcp->th_sport)
  2367. || probe->sport() != ntohs(tcp->th_dport)
  2368. || sockaddr_storage_cmp(&srcaddr, dst) != 0)
  2369. return false;
  2370. tryno = 0;
  2371. pingseq = 0;
  2372. if (o.magic_port_set) {
  2373. /* We are looking to recover the tryno and pingseq of the probe, which are
  2374. encoded in the ACK field for probes with the ACK flag set and in the SEQ
  2375. field for all other probes. According to RFC 793, section 3.9, under
  2376. "SEGMENT ARRIVES", it's supposed to work like this: If our probe had ACK
  2377. set, our ACK number is reflected in the response's SEQ field. If our
  2378. probe had SYN or FIN set (and not ACK), then our SEQ is one less than the
  2379. returned ACK value because SYN and FIN consume a sequence number (section
  2380. 3.3). Otherwise, our SEQ is the returned ACK.
  2381. However, nmap-os-db shows that these assumptions can't be relied on, so
  2382. we try all three possibilities for each probe. */
  2383. goodseq = seq32_decode(USI, ntohl(tcp->th_ack) - 1, &tryno, &pingseq)
  2384. || seq32_decode(USI, ntohl(tcp->th_ack), &tryno, &pingseq)
  2385. || seq32_decode(USI, ntohl(tcp->th_seq), &tryno, &pingseq);
  2386. } else {
  2387. /* Get the values from the destination port (our source port). */
  2388. sport_decode(USI, base_port, ntohs(tcp->th_dport), &tryno, &pingseq);
  2389. goodseq = true;
  2390. }
  2391. if (!goodseq) {
  2392. /* Connection info matches, but there was a nonsensical tryno/pingseq. */
  2393. if (o.debugging)
  2394. log_write(LOG_PLAIN, "Bad Sequence number from host %s.\n", inet_ntop_ez(src, sizeof(*src)));
  2395. return false;
  2396. }
  2397. /* Make sure that trynum and pingseq match the values in the probe. */
  2398. if (!probe->check_tryno_pingseq(tryno, pingseq))
  2399. return false;
  2400. /* Make sure we are matching up the right kind of probe, otherwise just the
  2401. ports, address, tryno, and pingseq can be ambiguous, between a SYN and an
  2402. ACK probe during a -PS80 -PA80 scan for example. A SYN/ACK can only be
  2403. matched to a SYN probe. */
  2404. probedata = &probe->pspec()->pd.tcp;
  2405. if ((tcp->th_flags & (TH_SYN | TH_ACK)) == (TH_SYN | TH_ACK)
  2406. && !(probedata->flags & TH_SYN)) {
  2407. return false;
  2408. }
  2409. /* Sometimes we get false results when scanning localhost with -p- because we
  2410. scan localhost with src port = dst port and see our outgoing packet and
  2411. think it is a response. */
  2412. if (probe->dport() == probe->sport()
  2413. && sockaddr_storage_cmp(src, dst) == 0
  2414. && probe->ipid() == ipid)
  2415. return false;
  2416. return true;
  2417. }
  2418. /* This function provides the proper cwnd and ssthresh to use. It may
  2419. differ from versions in timing member var because when no responses
  2420. have been received for this host, may look at others in the group.
  2421. For CHANGING this host's timing, use the timing memberval
  2422. instead. */
  2423. void HostScanStats::getTiming(struct ultra_timing_vals *tmng) {
  2424. assert(tmng);
  2425. /* Use the per-host value if a pingport has been found or very few probes
  2426. have been sent */
  2427. if (target->pingprobe.type != PS_NONE || numprobes_sent < 80) {
  2428. *tmng = timing;
  2429. return;
  2430. }
  2431. /* Otherwise, use the global cwnd stats if it has sufficient responses */
  2432. if (USI->gstats->timing.num_updates > 1) {
  2433. *tmng = USI->gstats->timing;
  2434. return;
  2435. }
  2436. /* Last resort is to use canned values */
  2437. tmng->cwnd = USI->perf.host_initial_cwnd;
  2438. tmng->ssthresh = USI->perf.initial_ssthresh;
  2439. tmng->num_updates = 0;
  2440. return;
  2441. }
  2442. /* Define a score for a ping probe, for the purposes of deciding whether one
  2443. probe should be preferred to another. The order, from most preferred to least
  2444. preferred, is
  2445. Raw TCP/SCTP (not filtered, not SYN/INIT to an open port)
  2446. ICMP information queries (echo request, timestamp request, netmask req)
  2447. ARP/ND
  2448. Raw TCP/SCTP (SYN/INIT to an open port)
  2449. UDP, IP protocol, or other ICMP (including filtered TCP/SCTP)
  2450. TCP connect
  2451. Anything else
  2452. Raw TCP SYN / SCTP INIT to an open port is given a low preference because of the
  2453. risk of SYN flooding (this is the only case where the port state is considered).
  2454. The probe passed to this function is assumed to have received a positive
  2455. response, that is, it should not have set a port state just by timing out. */
  2456. static unsigned int pingprobe_score(const probespec *pspec, int state) {
  2457. unsigned int score;
  2458. switch (pspec->type) {
  2459. case PS_TCP:
  2460. if (state == PORT_FILTERED) /* Received an ICMP error. */
  2461. score = 2;
  2462. else if (pspec->pd.tcp.flags == TH_SYN && (state == PORT_OPEN || state == PORT_UNKNOWN))
  2463. score = 3;
  2464. else
  2465. score = 6;
  2466. break;
  2467. case PS_SCTP:
  2468. if (state == PORT_FILTERED) /* Received an ICMP error. */
  2469. score = 2;
  2470. else if (state == PORT_OPEN || state == PORT_UNKNOWN)
  2471. score = 3;
  2472. else
  2473. score = 6;
  2474. break;
  2475. case PS_ICMP:
  2476. if (pspec->pd.icmp.type == ICMP_ECHO || pspec->pd.icmp.type == ICMP_MASK || pspec->pd.icmp.type == ICMP_TSTAMP)
  2477. score = 5;
  2478. else
  2479. score = 2;
  2480. break;
  2481. case PS_ARP:
  2482. case PS_ND:
  2483. score = 4;
  2484. break;
  2485. case PS_UDP:
  2486. case PS_PROTO:
  2487. score = 2;
  2488. break;
  2489. case PS_CONNECTTCP:
  2490. score = 1;
  2491. break;
  2492. case PS_NONE:
  2493. default:
  2494. score = 0;
  2495. break;
  2496. }
  2497. return score;
  2498. }
  2499. /* Return true if new_probe and new_state define a better ping probe, as defined
  2500. by pingprobe_score, than do old_probe and old_state. */
  2501. static bool pingprobe_is_better(const probespec *new_probe, int new_state,
  2502. const probespec *old_probe, int old_state) {
  2503. return pingprobe_score(new_probe, new_state) > pingprobe_score(old_probe, old_state);
  2504. }
  2505. static bool ultrascan_host_pspec_update(UltraScanInfo *USI, HostScanStats *hss,
  2506. const probespec *pspec, int newstate);
  2507. /* Like ultrascan_port_probe_update(), except it is called with just a
  2508. probespec rather than a whole UltraProbe. Returns true if the port
  2509. was added or at least the state was changed. */
  2510. static bool ultrascan_port_pspec_update(UltraScanInfo *USI,
  2511. HostScanStats *hss,
  2512. const probespec *pspec,
  2513. int newstate) {
  2514. u16 portno = 0;
  2515. u8 proto = 0;
  2516. int oldstate = PORT_TESTING;
  2517. /* Whether no response means a port is open */
  2518. bool noresp_open_scan = USI->noresp_open_scan;
  2519. if (USI->prot_scan) {
  2520. proto = IPPROTO_IP;
  2521. portno = pspec->proto;
  2522. } else if (pspec->type == PS_TCP || pspec->type == PS_CONNECTTCP) {
  2523. proto = IPPROTO_TCP;
  2524. portno = pspec->pd.tcp.dport;
  2525. } else if (pspec->type == PS_UDP) {
  2526. proto = IPPROTO_UDP;
  2527. portno = pspec->pd.udp.dport;
  2528. } else if (pspec->type == PS_SCTP) {
  2529. proto = IPPROTO_SCTP;
  2530. portno = pspec->pd.sctp.dport;
  2531. } else assert(0);
  2532. if (hss->target->ports.portIsDefault(portno, proto)) {
  2533. oldstate = PORT_TESTING;
  2534. hss->ports_finished++;
  2535. } else {
  2536. oldstate = hss->target->ports.getPortState(portno, proto);
  2537. }
  2538. /* printf("TCP port %hu has changed from state %s to %s!\n", portno, statenum2str(oldstate), statenum2str(newstate)); */
  2539. switch (oldstate) {
  2540. /* TODO: I need more code here to determine when a state should
  2541. be overridden, for example PORT_OPEN trumps PORT_FILTERED
  2542. in a SYN scan, but not necessarily for UDP scan */
  2543. case PORT_TESTING:
  2544. /* Brand new port -- add it to the list */
  2545. hss->target->ports.setPortState(portno, proto, newstate);
  2546. break;
  2547. case PORT_OPEN:
  2548. if (newstate != PORT_OPEN) {
  2549. if (noresp_open_scan) {
  2550. hss->target->ports.setPortState(portno, proto, newstate);
  2551. } /* Otherwise The old open takes precendence */
  2552. }
  2553. break;
  2554. case PORT_CLOSED:
  2555. if (newstate != PORT_CLOSED) {
  2556. if (!noresp_open_scan && newstate != PORT_FILTERED)
  2557. hss->target->ports.setPortState(portno, proto, newstate);
  2558. }
  2559. break;
  2560. case PORT_FILTERED:
  2561. if (newstate != PORT_FILTERED) {
  2562. if (!noresp_open_scan || newstate != PORT_OPEN)
  2563. hss->target->ports.setPortState(portno, proto, newstate);
  2564. }
  2565. break;
  2566. case PORT_UNFILTERED:
  2567. /* This could happen in an ACK scan if I receive a RST and then an
  2568. ICMP filtered message. I'm gonna stick with unfiltered in that
  2569. case. I'll change it if the new state is open or closed,
  2570. though I don't expect that to ever happen */
  2571. if (newstate == PORT_OPEN || newstate == PORT_CLOSED)
  2572. hss->target->ports.setPortState(portno, proto, newstate);
  2573. break;
  2574. case PORT_OPENFILTERED:
  2575. if (newstate != PORT_OPENFILTERED) {
  2576. hss->target->ports.setPortState(portno, proto, newstate);
  2577. }
  2578. break;
  2579. default:
  2580. fatal("Unexpected port state: %d\n", oldstate);
  2581. break;
  2582. }
  2583. return oldstate != newstate;
  2584. }
  2585. /* Boost the scan delay for this host, usually because too many packet
  2586. drops were detected. */
  2587. void HostScanStats::boostScanDelay() {
  2588. unsigned int maxAllowed = USI->tcp_scan ? o.maxTCPScanDelay() :
  2589. USI->udp_scan ? o.maxUDPScanDelay() :
  2590. o.maxSCTPScanDelay();
  2591. if (sdn.delayms == 0)
  2592. sdn.delayms = (USI->udp_scan) ? 50 : 5; // In many cases, a pcap wait takes a minimum of 80ms, so this matters little :(
  2593. else sdn.delayms = MIN(sdn.delayms * 2, MAX(sdn.delayms, 1000));
  2594. sdn.delayms = MIN(sdn.delayms, maxAllowed);
  2595. sdn.last_boost = USI->now;
  2596. sdn.droppedRespSinceDelayChanged = 0;
  2597. sdn.goodRespSinceDelayChanged = 0;
  2598. }
  2599. /* Dismiss all probe attempts on bench -- hosts are marked down and ports will
  2600. be set to whatever the default port state is for the scan. */
  2601. void HostScanStats::dismissBench() {
  2602. if (probe_bench.empty())
  2603. return;
  2604. while (!probe_bench.empty()) {
  2605. if (USI->ping_scan)
  2606. ultrascan_host_pspec_update(USI, this, &probe_bench.back(), HOST_DOWN);
  2607. /* Nothing to do if !USI->ping_scan. ultrascan_port_pspec_update would
  2608. allocate a Port object but we rely on the default port state to save
  2609. memory. */
  2610. probe_bench.pop_back();
  2611. }
  2612. bench_tryno = 0;
  2613. }
  2614. /* Move all members of bench to retry_stack for probe retransmission */
  2615. void HostScanStats::retransmitBench() {
  2616. if (probe_bench.empty())
  2617. return;
  2618. /* Move all contents of probe_bench to the end of retry_stack, updating retry_stack_tries accordingly */
  2619. retry_stack.insert(retry_stack.end(), probe_bench.begin(), probe_bench.end());
  2620. retry_stack_tries.insert(retry_stack_tries.end(), probe_bench.size(),
  2621. bench_tryno);
  2622. assert(retry_stack.size() == retry_stack_tries.size());
  2623. probe_bench.erase(probe_bench.begin(), probe_bench.end());
  2624. bench_tryno = 0;
  2625. }
  2626. /* Moves the given probe from the probes_outstanding list, to
  2627. probe_bench, and decrements num_probes_waiting_retransmit
  2628. accordingly */
  2629. void HostScanStats::moveProbeToBench(std::list<UltraProbe *>::iterator probeI) {
  2630. UltraProbe *probe = *probeI;
  2631. if (!probe_bench.empty())
  2632. assert(bench_tryno == probe->tryno);
  2633. else {
  2634. bench_tryno = probe->tryno;
  2635. probe_bench.reserve(128);
  2636. }
  2637. probe_bench.push_back(*probe->pspec());
  2638. probes_outstanding.erase(probeI);
  2639. num_probes_waiting_retransmit--;
  2640. delete probe;
  2641. }
  2642. /* Called when a ping response is discovered. If adjust_timing is false, timing
  2643. stats are not updated. */
  2644. static void ultrascan_ping_update(UltraScanInfo *USI, HostScanStats *hss,
  2645. std::list<UltraProbe *>::iterator probeI,
  2646. struct timeval *rcvdtime,
  2647. bool adjust_timing = true) {
  2648. ultrascan_adjust_timeouts(USI, hss, *probeI, rcvdtime);
  2649. if (adjust_timing)
  2650. ultrascan_adjust_timing(USI, hss, *probeI, rcvdtime);
  2651. hss->destroyOutstandingProbe(probeI);
  2652. }
  2653. static const char *readhoststate(int state) {
  2654. switch (state) {
  2655. case HOST_UNKNOWN:
  2656. return "UNKNOWN";
  2657. case HOST_UP:
  2658. return "HOST_UP";
  2659. case HOST_DOWN:
  2660. return "HOST_DOWN";
  2661. default:
  2662. return "COMBO";
  2663. }
  2664. return NULL;
  2665. }
  2666. /* Update state of the host in hss based on its current state and newstate.
  2667. Returns true if the state was changed. */
  2668. static bool ultrascan_host_pspec_update(UltraScanInfo *USI, HostScanStats *hss,
  2669. const probespec *pspec, int newstate) {
  2670. unsigned int oldstate = hss->target->flags;
  2671. /* If the host is already up, ignore any further updates. */
  2672. if (hss->target->flags != HOST_UP) {
  2673. assert(newstate == HOST_UP || newstate == HOST_DOWN);
  2674. hss->target->flags = newstate;
  2675. }
  2676. return hss->target->flags != oldstate;
  2677. }
  2678. /* Called when a new status is determined for host in hss (eg. it is
  2679. found to be up or down by a ping/ping_arp scan. The probe that led
  2680. to this new decision is in probeI. This function needs to update
  2681. timing information and other stats as appropriate. If
  2682. adjust_timing_hint is false, packet stats are not updated. */
  2683. static void ultrascan_host_probe_update(UltraScanInfo *USI, HostScanStats *hss,
  2684. std::list<UltraProbe *>::iterator probeI,
  2685. int newstate, struct timeval *rcvdtime,
  2686. bool adjust_timing_hint = true) {
  2687. UltraProbe *probe = *probeI;
  2688. if (o.debugging > 1) {
  2689. struct timeval tv;
  2690. gettimeofday(&tv, NULL);
  2691. log_write(LOG_STDOUT, "%s called for machine %s state %s -> %s (trynum %d time: %ld)\n", __func__, hss->target->targetipstr(), readhoststate(hss->target->flags), readhoststate(newstate), probe->tryno, (long) TIMEVAL_SUBTRACT(tv, probe->sent));
  2692. }
  2693. ultrascan_host_pspec_update(USI, hss, probe->pspec(), newstate);
  2694. ultrascan_adjust_timeouts(USI, hss, probe, rcvdtime);
  2695. /* Decide whether to adjust timing. We and together a bunch of conditions.
  2696. First, don't adjust timing if adjust_timing_hint is false. */
  2697. bool adjust_timing = adjust_timing_hint;
  2698. bool adjust_ping = adjust_timing_hint;
  2699. /* If we got a response that meant "down", then it was an ICMP error. These
  2700. are often rate-limited (RFC 1812) or generated by a different host. We only
  2701. allow such responses to increase, not decrease, scanning speed by
  2702. disallowing drops (probe->tryno > 0), and we don't allow changing the ping
  2703. probe to something that's likely to get dropped. */
  2704. if (rcvdtime != NULL && newstate == HOST_DOWN) {
  2705. if (probe->tryno > 0) {
  2706. if (adjust_timing && o.debugging > 1)
  2707. log_write(LOG_PLAIN, "Response for %s means new state is down; not adjusting timing.\n", hss->target->targetipstr());
  2708. adjust_timing = false;
  2709. }
  2710. adjust_ping = false;
  2711. }
  2712. if (adjust_timing)
  2713. ultrascan_adjust_timing(USI, hss, probe, rcvdtime);
  2714. /* If this probe received a positive response, consider making it the new
  2715. timing ping probe. */
  2716. if (rcvdtime != NULL && adjust_ping
  2717. && pingprobe_is_better(probe->pspec(), PORT_UNKNOWN, &hss->target->pingprobe, hss->target->pingprobe_state)) {
  2718. if (o.debugging > 1) {
  2719. char buf[64];
  2720. probespec2ascii(probe->pspec(), buf, sizeof(buf));
  2721. log_write(LOG_PLAIN, "Changing ping technique for %s to %s\n", hss->target->targetipstr(), buf);
  2722. }
  2723. hss->target->pingprobe = *probe->pspec();
  2724. hss->target->pingprobe_state = PORT_UNKNOWN;
  2725. }
  2726. hss->destroyOutstandingProbe(probeI);
  2727. }
  2728. /* This function is called when a new status is determined for a port.
  2729. the port in the probeI of host hss is now in newstate. This
  2730. function needs to update timing information, other stats, and the
  2731. Nmap port state table as appropriate. If rcvdtime is NULL or we got
  2732. unimportant packet, packet stats are not updated. If you don't have an
  2733. UltraProbe list iterator, you may need to call ultrascan_port_psec_update()
  2734. instead. If adjust_timing_hint is false, packet stats are not
  2735. updated. */
  2736. static void ultrascan_port_probe_update(UltraScanInfo *USI, HostScanStats *hss,
  2737. std::list<UltraProbe *>::iterator probeI,
  2738. int newstate, struct timeval *rcvdtime,
  2739. bool adjust_timing_hint = true) {
  2740. UltraProbe *probe = *probeI;
  2741. const probespec *pspec = probe->pspec();
  2742. ultrascan_port_pspec_update(USI, hss, pspec, newstate);
  2743. ultrascan_adjust_timeouts(USI, hss, probe, rcvdtime);
  2744. /* Decide whether to adjust timing. We and together a bunch of conditions.
  2745. First, don't adjust timing if adjust_timing_hint is false. */
  2746. bool adjust_timing = adjust_timing_hint;
  2747. bool adjust_ping = adjust_timing_hint;
  2748. /* If we got a response that meant "filtered", then it was an ICMP error.
  2749. These are often rate-limited (RFC 1812) or generated by a different host.
  2750. We only allow such responses to increase, not decrease, scanning speed by
  2751. not considering drops (probe->tryno > 0), and we don't allow changing the
  2752. ping probe to something that's likely to get dropped. */
  2753. if (rcvdtime != NULL && newstate == PORT_FILTERED && !USI->noresp_open_scan) {
  2754. if (probe->tryno > 0) {
  2755. if (adjust_timing && o.debugging > 1)
  2756. log_write(LOG_PLAIN, "Response for %s means new state is filtered; not adjusting timing.\n", hss->target->targetipstr());
  2757. adjust_timing = false;
  2758. }
  2759. adjust_ping = false;
  2760. }
  2761. /* Do not slow down if
  2762. 1) we are in --defeat-rst-ratelimit mode
  2763. 2) the new state is closed
  2764. 3) this is not a UDP scan (other scans where noresp_open_scan is true
  2765. aren't possible with the --defeat-rst-ratelimit option)
  2766. We don't care if it's closed because of a RST or a timeout
  2767. because they both mean the same thing. */
  2768. if (rcvdtime != NULL
  2769. && o.defeat_rst_ratelimit && newstate == PORT_CLOSED
  2770. && !USI->noresp_open_scan) {
  2771. if (probe->tryno > 0)
  2772. adjust_timing = false;
  2773. adjust_ping = false;
  2774. }
  2775. if (adjust_timing) {
  2776. ultrascan_adjust_timing(USI, hss, probe, rcvdtime);
  2777. if (rcvdtime != NULL && probe->tryno > hss->max_successful_tryno) {
  2778. /* We got a positive response to a higher tryno than we've seen so far. */
  2779. hss->max_successful_tryno = probe->tryno;
  2780. if (o.debugging)
  2781. log_write(LOG_STDOUT, "Increased max_successful_tryno for %s to %d (packet drop)\n", hss->target->targetipstr(), hss->max_successful_tryno);
  2782. if (hss->max_successful_tryno > ((o.timing_level >= 4) ? 4 : 3)) {
  2783. unsigned int olddelay = hss->sdn.delayms;
  2784. hss->boostScanDelay();
  2785. if (o.verbose && hss->sdn.delayms != olddelay)
  2786. log_write(LOG_STDOUT, "Increasing send delay for %s from %d to %d due to max_successful_tryno increase to %d\n",
  2787. hss->target->targetipstr(), olddelay, hss->sdn.delayms,
  2788. hss->max_successful_tryno);
  2789. }
  2790. }
  2791. }
  2792. /* If this probe received a positive response, consider making it the new
  2793. timing ping probe. */
  2794. if (rcvdtime != NULL && adjust_ping
  2795. && pingprobe_is_better(probe->pspec(), newstate, &hss->target->pingprobe, hss->target->pingprobe_state)) {
  2796. if (o.debugging > 1) {
  2797. char buf[64];
  2798. probespec2ascii(probe->pspec(), buf, sizeof(buf));
  2799. log_write(LOG_PLAIN, "Changing ping technique for %s to %s\n", hss->target->targetipstr(), buf);
  2800. }
  2801. hss->target->pingprobe = *probe->pspec();
  2802. hss->target->pingprobe_state = newstate;
  2803. }
  2804. hss->destroyOutstandingProbe(probeI);
  2805. }
  2806. /* Set the socket lingering so we will RST connections instead of wasting
  2807. bandwidth with the four-step close. Set the source address if needed. Bind to
  2808. a specific interface if needed. */
  2809. static void init_socket(int sd) {
  2810. static int bind_failed = 0;
  2811. struct linger l;
  2812. struct sockaddr_storage ss;
  2813. size_t sslen;
  2814. l.l_onoff = 1;
  2815. l.l_linger = 0;
  2816. if (setsockopt(sd, SOL_SOCKET, SO_LINGER, (const char *) &l, sizeof(l)) != 0) {
  2817. error("Problem setting socket SO_LINGER, errno: %d", socket_errno());
  2818. perror("setsockopt");
  2819. }
  2820. if (o.spoofsource && !bind_failed) {
  2821. o.SourceSockAddr(&ss, &sslen);
  2822. if (bind(sd, (struct sockaddr*)&ss, sslen) != 0) {
  2823. error("%s: Problem binding source address (%s), errno: %d", __func__, inet_socktop(&ss), socket_errno());
  2824. perror("bind");
  2825. bind_failed = 1;
  2826. }
  2827. }
  2828. errno = 0;
  2829. if (!socket_bindtodevice(sd, o.device)) {
  2830. /* EPERM is expected when not running as root. */
  2831. if (errno != EPERM) {
  2832. error("Problem binding to interface %s, errno: %d", o.device, socket_errno());
  2833. perror("socket_bindtodevice");
  2834. }
  2835. }
  2836. }
  2837. /* If this is NOT a ping probe, set pingseq to 0. Otherwise it will be the
  2838. ping sequence number (they start at 1). The probe sent is returned. */
  2839. static UltraProbe *sendConnectScanProbe(UltraScanInfo *USI, HostScanStats *hss,
  2840. u16 destport, u8 tryno, u8 pingseq) {
  2841. UltraProbe *probe = new UltraProbe();
  2842. std::list<UltraProbe *>::iterator probeI;
  2843. static bool connecterror = false;
  2844. int rc;
  2845. int connect_errno = 0;
  2846. struct sockaddr_storage sock;
  2847. struct sockaddr_in *sin = (struct sockaddr_in *) &sock;
  2848. #if HAVE_IPV6
  2849. struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *) &sock;
  2850. #endif
  2851. size_t socklen;
  2852. ConnectProbe *CP;
  2853. probe->tryno = tryno;
  2854. probe->pingseq = pingseq;
  2855. /* First build the probe */
  2856. probe->setConnect(destport);
  2857. CP = probe->CP();
  2858. /* Initiate the connection */
  2859. CP->sd = socket(o.af(), SOCK_STREAM, IPPROTO_TCP);
  2860. if (CP->sd == -1)
  2861. pfatal("Socket creation in %s", __func__);
  2862. unblock_socket(CP->sd);
  2863. init_socket(CP->sd);
  2864. set_ttl(CP->sd, o.ttl);
  2865. if (o.ipoptionslen)
  2866. set_ipoptions(CP->sd, o.ipoptions, o.ipoptionslen);
  2867. if (hss->target->TargetSockAddr(&sock, &socklen) != 0) {
  2868. fatal("Failed to get target socket address in %s", __func__);
  2869. }
  2870. if (sin->sin_family == AF_INET)
  2871. sin->sin_port = htons(probe->pspec()->pd.tcp.dport);
  2872. #if HAVE_IPV6
  2873. else sin6->sin6_port = htons(probe->pspec()->pd.tcp.dport);
  2874. #endif
  2875. probe->sent = USI->now;
  2876. /* We don't record a byte count for connect probes. */
  2877. hss->probeSent(0);
  2878. rc = connect(CP->sd, (struct sockaddr *)&sock, socklen);
  2879. gettimeofday(&USI->now, NULL);
  2880. if (rc == -1)
  2881. connect_errno = socket_errno();
  2882. PacketTrace::traceConnect(IPPROTO_TCP, (sockaddr *) &sock, socklen, rc,
  2883. connect_errno, &USI->now);
  2884. /* This counts as probe being sent, so update structures */
  2885. hss->probes_outstanding.push_back(probe);
  2886. probeI = hss->probes_outstanding.end();
  2887. probeI--;
  2888. USI->gstats->num_probes_active++;
  2889. hss->num_probes_active++;
  2890. /* It would be convenient if the connect() call would never succeed
  2891. or permanantly fail here, so related code cood all be localized
  2892. elsewhere. But the reality is that connect() MAY be finished now. */
  2893. if (rc != -1) {
  2894. /* Connection succeeded! */
  2895. if (USI->ping_scan) {
  2896. ultrascan_host_probe_update(USI, hss, probeI, HOST_UP, &USI->now);
  2897. /* If the host is up, we can forget our other probes. */
  2898. hss->destroyAllOutstandingProbes();
  2899. } else if (probe->isPing())
  2900. ultrascan_ping_update(USI, hss, probeI, &USI->now);
  2901. else
  2902. ultrascan_port_probe_update(USI, hss, probeI, PORT_OPEN, &USI->now);
  2903. probe = NULL;
  2904. } else if (connect_errno == EINPROGRESS || connect_errno == EAGAIN) {
  2905. USI->gstats->CSI->watchSD(CP->sd);
  2906. } else {
  2907. int host_state = HOST_UNKNOWN, port_state = PORT_UNKNOWN;
  2908. switch (connect_errno) {
  2909. /* This can happen on localhost, successful/failing connection immediately
  2910. in non-blocking mode. */
  2911. case ECONNREFUSED:
  2912. host_state = HOST_UP;
  2913. port_state = PORT_CLOSED;
  2914. hss->target->reason.reason_id = ER_CONREFUSED;
  2915. break;
  2916. case ENETUNREACH:
  2917. if (o.debugging)
  2918. log_write(LOG_STDOUT, "Got ENETUNREACH from %s connect()\n", __func__);
  2919. host_state = HOST_DOWN;
  2920. hss->target->reason.reason_id = ER_NETUNREACH;
  2921. break;
  2922. case EACCES:
  2923. if (o.debugging)
  2924. log_write(LOG_STDOUT, "Got EACCES from %s connect()\n", __func__);
  2925. host_state = HOST_DOWN;
  2926. hss->target->reason.reason_id = ER_ACCES;
  2927. break;
  2928. default:
  2929. if (!connecterror) {
  2930. connecterror = true;
  2931. fprintf(stderr, "Strange error from connect (%d):", connect_errno);
  2932. fflush(stdout);
  2933. fflush(stderr);
  2934. perror("");
  2935. }
  2936. host_state = HOST_DOWN;
  2937. hss->target->reason.reason_id = ER_UNKNOWN;
  2938. }
  2939. if (probe->isPing()) {
  2940. ultrascan_ping_update(USI, hss, probeI, &USI->now);
  2941. } else if (USI->ping_scan && host_state != HOST_UNKNOWN) {
  2942. ultrascan_host_probe_update(USI, hss, probeI, host_state, &USI->now);
  2943. if (host_state == HOST_UP)
  2944. hss->destroyAllOutstandingProbes();
  2945. } else if (!USI->ping_scan && port_state != PORT_UNKNOWN) {
  2946. ultrascan_port_probe_update(USI, hss, probeI, port_state, &USI->now);
  2947. } else {
  2948. hss->destroyOutstandingProbe(probeI);
  2949. }
  2950. probe = NULL;
  2951. }
  2952. gettimeofday(&USI->now, NULL);
  2953. return probe;
  2954. }
  2955. /* If this is NOT a ping probe, set pingseq to 0. Otherwise it will be the
  2956. ping sequence number (they start at 1). The probe sent is returned. */
  2957. static UltraProbe *sendArpScanProbe(UltraScanInfo *USI, HostScanStats *hss,
  2958. u8 tryno, u8 pingseq) {
  2959. int rc;
  2960. UltraProbe *probe = new UltraProbe();
  2961. /* 3 cheers for libdnet header files */
  2962. u8 frame[ETH_HDR_LEN + ARP_HDR_LEN + ARP_ETHIP_LEN];
  2963. eth_pack_hdr(frame, ETH_ADDR_BROADCAST, *hss->target->SrcMACAddress(),
  2964. ETH_TYPE_ARP);
  2965. arp_pack_hdr_ethip(frame + ETH_HDR_LEN, ARP_OP_REQUEST,
  2966. *hss->target->SrcMACAddress(), *hss->target->v4sourceip(),
  2967. ETH_ADDR_BROADCAST, *hss->target->v4hostip());
  2968. gettimeofday(&USI->now, NULL);
  2969. probe->sent = USI->now;
  2970. hss->probeSent(sizeof(frame));
  2971. if ((rc = eth_send(USI->ethsd, frame, sizeof(frame))) != sizeof(frame)) {
  2972. int err = socket_errno();
  2973. error("WARNING: eth_send of ARP packet returned %i rather than expected %d (errno=%i: %s)", rc, (int) sizeof(frame), err, strerror(err));
  2974. }
  2975. PacketTrace::traceArp(PacketTrace::SENT, (u8 *) frame + ETH_HDR_LEN, sizeof(frame) - ETH_HDR_LEN, &USI->now);
  2976. probe->tryno = tryno;
  2977. probe->pingseq = pingseq;
  2978. /* First build the probe */
  2979. probe->setARP(frame, sizeof(frame));
  2980. /* Now that the probe has been sent, add it to the Queue for this host */
  2981. hss->probes_outstanding.push_back(probe);
  2982. USI->gstats->num_probes_active++;
  2983. hss->num_probes_active++;
  2984. gettimeofday(&USI->now, NULL);
  2985. return probe;
  2986. }
  2987. static UltraProbe *sendNDScanProbe(UltraScanInfo *USI, HostScanStats *hss,
  2988. u8 tryno, u8 pingseq) {
  2989. UltraProbe *probe = new UltraProbe();
  2990. struct eth_nfo eth;
  2991. struct eth_nfo *ethptr = NULL;
  2992. u8 *packet = NULL;
  2993. u32 packetlen = 0;
  2994. struct in6_addr ns_dst_ip6;
  2995. ns_dst_ip6 = *hss->target->v6hostip();
  2996. if (USI->ethsd) {
  2997. unsigned char ns_dst_mac[6] = {0x33, 0x33, 0xff};
  2998. ns_dst_mac[3] = ns_dst_ip6.s6_addr[13];
  2999. ns_dst_mac[4] = ns_dst_ip6.s6_addr[14];
  3000. ns_dst_mac[5] = ns_dst_ip6.s6_addr[15];
  3001. memcpy(eth.srcmac, hss->target->SrcMACAddress(), 6);
  3002. memcpy(eth.dstmac, ns_dst_mac, 6);
  3003. eth.ethsd = USI->ethsd;
  3004. eth.devname[0] = '\0';
  3005. ethptr = &eth;
  3006. }
  3007. unsigned char multicast_prefix[13] = {0};
  3008. multicast_prefix[0] = 0xff;
  3009. multicast_prefix[1] = 0x02;
  3010. multicast_prefix[11] = 0x1;
  3011. multicast_prefix[12] = 0xff;
  3012. memcpy(&ns_dst_ip6, multicast_prefix, sizeof(multicast_prefix));
  3013. struct sockaddr_storage source;
  3014. struct sockaddr_in6 *sin6;
  3015. size_t source_len;
  3016. source_len = sizeof(source);
  3017. hss->target->SourceSockAddr(&source, &source_len);
  3018. sin6 = (struct sockaddr_in6 *) &source;
  3019. struct icmpv6_msg_nd ns_msg;
  3020. ns_msg.icmpv6_flags = htons(0);
  3021. memcpy(&ns_msg.icmpv6_target, hss->target->v6hostip(), IP6_ADDR_LEN);
  3022. ns_msg.icmpv6_option_type = 1;
  3023. ns_msg.icmpv6_option_length = 1;
  3024. memcpy(&ns_msg.icmpv6_mac, hss->target->SrcMACAddress(), ETH_ADDR_LEN);
  3025. packet = build_icmpv6_raw(&sin6->sin6_addr, &ns_dst_ip6,
  3026. 0, 0, o.ttl, 0, 0, ICMPV6_NEIGHBOR_SOLICITATION,
  3027. 0, (char *)&ns_msg, sizeof(ns_msg),
  3028. &packetlen);
  3029. probe->sent = USI->now;
  3030. hss->probeSent(packetlen);
  3031. send_ip_packet(USI->rawsd, ethptr, hss->target->TargetSockAddr(), packet, packetlen);
  3032. probe->tryno = tryno;
  3033. probe->pingseq = pingseq;
  3034. /* First build the probe */
  3035. probe->setND(packet, packetlen);
  3036. free(packet);
  3037. /* Now that the probe has been sent, add it to the Queue for this host */
  3038. hss->probes_outstanding.push_back(probe);
  3039. USI->gstats->num_probes_active++;
  3040. hss->num_probes_active++;
  3041. gettimeofday(&USI->now, NULL);
  3042. return probe;
  3043. }
  3044. /* Build an appropriate protocol scan (-sO) probe for the given source and
  3045. destination addresses and protocol. src and dst must be of the same address
  3046. family. Returns NULL on error. */
  3047. static u8 *build_protoscan_packet(const struct sockaddr_storage *src,
  3048. const struct sockaddr_storage *dst, u8 proto, u16 sport, u32 *packetlen) {
  3049. u16 icmp_ident, ipid;
  3050. u8 *packet;
  3051. packet = NULL;
  3052. *packetlen = 0;
  3053. ipid = get_random_u16();
  3054. /* Some hosts do not respond to ICMP requests if the identifier is 0. */
  3055. icmp_ident = (get_random_u16() % 0xffff) + 1;
  3056. assert(src->ss_family == dst->ss_family);
  3057. if (src->ss_family == AF_INET) {
  3058. const struct sockaddr_in *src_in, *dst_in;
  3059. src_in = (struct sockaddr_in *) src;
  3060. dst_in = (struct sockaddr_in *) dst;
  3061. switch (proto) {
  3062. case IPPROTO_TCP:
  3063. packet = build_tcp_raw(&src_in->sin_addr, &dst_in->sin_addr,
  3064. o.ttl, ipid, IP_TOS_DEFAULT, false, o.ipoptions, o.ipoptionslen,
  3065. sport, DEFAULT_TCP_PROBE_PORT, get_random_u32(), get_random_u32(), 0, TH_ACK, 0, 0, NULL, 0,
  3066. o.extra_payload, o.extra_payload_length, packetlen);
  3067. break;
  3068. case IPPROTO_ICMP:
  3069. packet = build_icmp_raw(&src_in->sin_addr, &dst_in->sin_addr,
  3070. o.ttl, ipid, IP_TOS_DEFAULT, false, o.ipoptions, o.ipoptionslen,
  3071. 0, icmp_ident, 8, 0,
  3072. o.extra_payload, o.extra_payload_length, packetlen);
  3073. break;
  3074. case IPPROTO_IGMP:
  3075. packet = build_igmp_raw(&src_in->sin_addr, &dst_in->sin_addr,
  3076. o.ttl, ipid, IP_TOS_DEFAULT, false, o.ipoptions, o.ipoptionslen,
  3077. 0x11, 0,
  3078. o.extra_payload, o.extra_payload_length, packetlen);
  3079. break;
  3080. case IPPROTO_UDP:
  3081. packet = build_udp_raw(&src_in->sin_addr, &dst_in->sin_addr,
  3082. o.ttl, ipid, IP_TOS_DEFAULT, false, o.ipoptions, o.ipoptionslen,
  3083. sport, DEFAULT_UDP_PROBE_PORT,
  3084. o.extra_payload, o.extra_payload_length, packetlen);
  3085. break;
  3086. case IPPROTO_SCTP: {
  3087. struct sctp_chunkhdr_init chunk;
  3088. sctp_pack_chunkhdr_init(&chunk, SCTP_INIT, 0, sizeof(chunk),
  3089. get_random_u32() /*itag*/, 32768, 10, 2048, get_random_u32() /*itsn*/);
  3090. packet = build_sctp_raw(&src_in->sin_addr, &dst_in->sin_addr,
  3091. o.ttl, ipid, IP_TOS_DEFAULT, false, o.ipoptions, o.ipoptionslen,
  3092. sport, DEFAULT_SCTP_PROBE_PORT, 0UL, (char*) &chunk, sizeof(chunk),
  3093. o.extra_payload, o.extra_payload_length, packetlen);
  3094. }
  3095. break;
  3096. default:
  3097. packet = build_ip_raw(&src_in->sin_addr, &dst_in->sin_addr,
  3098. proto,
  3099. o.ttl, ipid, IP_TOS_DEFAULT, false, o.ipoptions, o.ipoptionslen,
  3100. o.extra_payload, o.extra_payload_length, packetlen);
  3101. break;
  3102. }
  3103. } else if (src->ss_family == AF_INET6) {
  3104. const struct sockaddr_in6 *src_in6, *dst_in6;
  3105. src_in6 = (struct sockaddr_in6 *) src;
  3106. dst_in6 = (struct sockaddr_in6 *) dst;
  3107. switch (proto) {
  3108. case IPPROTO_TCP:
  3109. packet = build_tcp_raw_ipv6(&src_in6->sin6_addr, &dst_in6->sin6_addr,
  3110. 0, ipid, o.ttl,
  3111. sport, DEFAULT_TCP_PROBE_PORT, get_random_u32(), get_random_u32(), 0, TH_ACK, 0, 0, NULL, 0,
  3112. o.extra_payload, o.extra_payload_length, packetlen);
  3113. break;
  3114. case IPPROTO_ICMPV6:
  3115. packet = build_icmpv6_raw(&src_in6->sin6_addr, &dst_in6->sin6_addr,
  3116. 0, ipid, o.ttl,
  3117. 0, icmp_ident, ICMPV6_ECHO, ICMPV6_ECHOREPLY,
  3118. o.extra_payload, o.extra_payload_length, packetlen);
  3119. break;
  3120. case IPPROTO_UDP:
  3121. packet = build_udp_raw_ipv6(&src_in6->sin6_addr, &dst_in6->sin6_addr,
  3122. 0, ipid, o.ttl,
  3123. sport, DEFAULT_UDP_PROBE_PORT,
  3124. o.extra_payload, o.extra_payload_length, packetlen);
  3125. break;
  3126. case IPPROTO_SCTP: {
  3127. struct sctp_chunkhdr_init chunk;
  3128. sctp_pack_chunkhdr_init(&chunk, SCTP_INIT, 0, sizeof(chunk),
  3129. get_random_u32() /*itag*/, 32768, 10, 2048, get_random_u32() /*itsn*/);
  3130. packet = build_sctp_raw_ipv6(&src_in6->sin6_addr, &dst_in6->sin6_addr,
  3131. 0, ipid, o.ttl,
  3132. sport, DEFAULT_SCTP_PROBE_PORT, 0UL, (char*) &chunk, sizeof(chunk),
  3133. o.extra_payload, o.extra_payload_length, packetlen);
  3134. }
  3135. break;
  3136. default:
  3137. packet = build_ipv6_raw(&src_in6->sin6_addr, &dst_in6->sin6_addr,
  3138. 0, ipid, proto, o.ttl,
  3139. o.extra_payload, o.extra_payload_length, packetlen);
  3140. break;
  3141. }
  3142. }
  3143. return packet;
  3144. }
  3145. /* If this is NOT a ping probe, set pingseq to 0. Otherwise it will be the
  3146. ping sequence number (they start at 1). The probe sent is returned.
  3147. This function also handles the sending of decoys. There is no fine-grained
  3148. control of this; all decoys are sent at once on one call of this function.
  3149. This means that decoys do not honor any scan delay and may violate congestion
  3150. control limits. */
  3151. static UltraProbe *sendIPScanProbe(UltraScanInfo *USI, HostScanStats *hss,
  3152. const probespec *pspec, u8 tryno, u8 pingseq) {
  3153. u8 *packet = NULL;
  3154. u32 packetlen = 0;
  3155. UltraProbe *probe = new UltraProbe();
  3156. int decoy = 0;
  3157. u32 seq = 0;
  3158. u32 ack = 0;
  3159. u16 sport;
  3160. u16 ipid = get_random_u16();
  3161. struct eth_nfo eth;
  3162. struct eth_nfo *ethptr = NULL;
  3163. u8 *tcpops = NULL;
  3164. u16 tcpopslen = 0;
  3165. u32 vtag = 0;
  3166. char *chunk = NULL;
  3167. int chunklen = 0;
  3168. /* Some hosts do not respond to ICMP requests if the identifier is 0. */
  3169. u16 icmp_ident = (get_random_u16() % 0xffff) + 1;
  3170. if (USI->ethsd) {
  3171. memcpy(eth.srcmac, hss->target->SrcMACAddress(), 6);
  3172. memcpy(eth.dstmac, hss->target->NextHopMACAddress(), 6);
  3173. eth.ethsd = USI->ethsd;
  3174. eth.devname[0] = '\0';
  3175. ethptr = &eth;
  3176. }
  3177. if (o.magic_port_set)
  3178. sport = o.magic_port;
  3179. else
  3180. sport = sport_encode(USI, base_port, tryno, pingseq);
  3181. probe->tryno = tryno;
  3182. probe->pingseq = pingseq;
  3183. /* First build the probe */
  3184. if (pspec->type == PS_TCP) {
  3185. assert(USI->scantype != CONNECT_SCAN);
  3186. /* Normally we encode the tryno and pingseq in the SEQ field, because that
  3187. comes back (possibly incremented) in the ACK field of responses. But if
  3188. our probe has the ACK flag set, the response reflects our own ACK number
  3189. instead. */
  3190. if (pspec->pd.tcp.flags & TH_ACK)
  3191. ack = seq32_encode(USI, tryno, pingseq);
  3192. else
  3193. seq = seq32_encode(USI, tryno, pingseq);
  3194. if (pspec->pd.tcp.flags & TH_SYN) {
  3195. tcpops = (u8 *) "\x02\x04\x05\xb4";
  3196. tcpopslen = 4;
  3197. }
  3198. if (hss->target->af() == AF_INET) {
  3199. for (decoy = 0; decoy < o.numdecoys; decoy++) {
  3200. packet = build_tcp_raw(&o.decoys[decoy], hss->target->v4hostip(),
  3201. o.ttl, ipid, IP_TOS_DEFAULT, false,
  3202. o.ipoptions, o.ipoptionslen,
  3203. sport, pspec->pd.tcp.dport,
  3204. seq, ack, 0, pspec->pd.tcp.flags, 0, 0,
  3205. tcpops, tcpopslen,
  3206. o.extra_payload, o.extra_payload_length,
  3207. &packetlen);
  3208. if (decoy == o.decoyturn) {
  3209. probe->setIP(packet, packetlen, pspec);
  3210. probe->sent = USI->now;
  3211. }
  3212. hss->probeSent(packetlen);
  3213. send_ip_packet(USI->rawsd, ethptr, hss->target->TargetSockAddr(), packet, packetlen);
  3214. free(packet);
  3215. }
  3216. } else if (hss->target->af() == AF_INET6) {
  3217. struct sockaddr_storage source;
  3218. struct sockaddr_in6 *sin6;
  3219. size_t source_len;
  3220. source_len = sizeof(source);
  3221. hss->target->SourceSockAddr(&source, &source_len);
  3222. sin6 = (struct sockaddr_in6 *) &source;
  3223. packet = build_tcp_raw_ipv6(&sin6->sin6_addr, hss->target->v6hostip(),
  3224. 0, 0, o.ttl, sport, pspec->pd.tcp.dport,
  3225. seq, ack, 0, pspec->pd.tcp.flags, 0, 0,
  3226. tcpops, tcpopslen,
  3227. o.extra_payload, o.extra_payload_length,
  3228. &packetlen);
  3229. probe->setIP(packet, packetlen, pspec);
  3230. probe->sent = USI->now;
  3231. hss->probeSent(packetlen);
  3232. send_ip_packet(USI->rawsd, ethptr, hss->target->TargetSockAddr(), packet, packetlen);
  3233. free(packet);
  3234. }
  3235. } else if (pspec->type == PS_UDP) {
  3236. const char *payload;
  3237. size_t payload_length;
  3238. payload = get_udp_payload(pspec->pd.udp.dport, &payload_length);
  3239. if (hss->target->af() == AF_INET) {
  3240. for (decoy = 0; decoy < o.numdecoys; decoy++) {
  3241. packet = build_udp_raw(&o.decoys[decoy], hss->target->v4hostip(),
  3242. o.ttl, ipid, IP_TOS_DEFAULT, false,
  3243. o.ipoptions, o.ipoptionslen,
  3244. sport, pspec->pd.udp.dport,
  3245. (char *) payload, payload_length,
  3246. &packetlen);
  3247. if (decoy == o.decoyturn) {
  3248. probe->setIP(packet, packetlen, pspec);
  3249. probe->sent = USI->now;
  3250. }
  3251. hss->probeSent(packetlen);
  3252. send_ip_packet(USI->rawsd, ethptr, hss->target->TargetSockAddr(), packet, packetlen);
  3253. free(packet);
  3254. }
  3255. } else if (hss->target->af() == AF_INET6) {
  3256. struct sockaddr_storage source;
  3257. struct sockaddr_in6 *sin6;
  3258. size_t source_len;
  3259. source_len = sizeof(source);
  3260. hss->target->SourceSockAddr(&source, &source_len);
  3261. sin6 = (struct sockaddr_in6 *) &source;
  3262. packet = build_udp_raw_ipv6(&sin6->sin6_addr, hss->target->v6hostip(),
  3263. 0, 0, o.ttl, sport, pspec->pd.tcp.dport,
  3264. (char *) payload, payload_length,
  3265. &packetlen);
  3266. probe->setIP(packet, packetlen, pspec);
  3267. probe->sent = USI->now;
  3268. hss->probeSent(packetlen);
  3269. send_ip_packet(USI->rawsd, ethptr, hss->target->TargetSockAddr(), packet, packetlen);
  3270. free(packet);
  3271. }
  3272. } else if (pspec->type == PS_SCTP) {
  3273. switch (pspec->pd.sctp.chunktype) {
  3274. case SCTP_INIT:
  3275. chunklen = sizeof(struct sctp_chunkhdr_init);
  3276. chunk = (char*)safe_malloc(chunklen);
  3277. sctp_pack_chunkhdr_init(chunk, SCTP_INIT, 0, chunklen,
  3278. get_random_u32()/*itag*/,
  3279. 32768, 10, 2048,
  3280. get_random_u32()/*itsn*/);
  3281. vtag = 0;
  3282. break;
  3283. case SCTP_COOKIE_ECHO:
  3284. chunklen = sizeof(struct sctp_chunkhdr_cookie_echo) + 4;
  3285. chunk = (char*)safe_malloc(chunklen);
  3286. *((u32*)((char*)chunk + sizeof(struct sctp_chunkhdr_cookie_echo))) =
  3287. get_random_u32();
  3288. sctp_pack_chunkhdr_cookie_echo(chunk, SCTP_COOKIE_ECHO, 0, chunklen);
  3289. vtag = get_random_u32();
  3290. break;
  3291. default:
  3292. assert(0);
  3293. }
  3294. if (hss->target->af() == AF_INET) {
  3295. for (decoy = 0; decoy < o.numdecoys; decoy++) {
  3296. packet = build_sctp_raw(&o.decoys[decoy], hss->target->v4hostip(),
  3297. o.ttl, ipid, IP_TOS_DEFAULT, false,
  3298. o.ipoptions, o.ipoptionslen,
  3299. sport, pspec->pd.sctp.dport,
  3300. vtag, chunk, chunklen,
  3301. o.extra_payload, o.extra_payload_length,
  3302. &packetlen);
  3303. if (decoy == o.decoyturn) {
  3304. probe->setIP(packet, packetlen, pspec);
  3305. probe->sent = USI->now;
  3306. }
  3307. hss->probeSent(packetlen);
  3308. send_ip_packet(USI->rawsd, ethptr, hss->target->TargetSockAddr(), packet, packetlen);
  3309. free(packet);
  3310. }
  3311. } else if (hss->target->af() == AF_INET6) {
  3312. struct sockaddr_storage source;
  3313. struct sockaddr_in6 *sin6;
  3314. size_t source_len;
  3315. source_len = sizeof(source);
  3316. hss->target->SourceSockAddr(&source, &source_len);
  3317. sin6 = (struct sockaddr_in6 *) &source;
  3318. packet = build_sctp_raw_ipv6(&sin6->sin6_addr, hss->target->v6hostip(),
  3319. 0, 0, o.ttl, sport, pspec->pd.sctp.dport,
  3320. vtag, chunk, chunklen,
  3321. o.extra_payload, o.extra_payload_length,
  3322. &packetlen);
  3323. probe->setIP(packet, packetlen, pspec);
  3324. probe->sent = USI->now;
  3325. hss->probeSent(packetlen);
  3326. send_ip_packet(USI->rawsd, ethptr, hss->target->TargetSockAddr(), packet, packetlen);
  3327. free(packet);
  3328. }
  3329. free(chunk);
  3330. } else if (pspec->type == PS_PROTO) {
  3331. if (hss->target->af() == AF_INET) {
  3332. struct sockaddr_storage ss;
  3333. struct sockaddr_in *sin;
  3334. sin = (struct sockaddr_in *) &ss;
  3335. sin->sin_family = AF_INET;
  3336. for (decoy = 0; decoy < o.numdecoys; decoy++) {
  3337. sin->sin_addr = o.decoys[decoy];
  3338. packet = build_protoscan_packet(&ss, hss->target->TargetSockAddr(),
  3339. pspec->proto, sport, &packetlen);
  3340. assert(packet != NULL);
  3341. if (decoy == o.decoyturn) {
  3342. probe->setIP(packet, packetlen, pspec);
  3343. probe->sent = USI->now;
  3344. }
  3345. hss->probeSent(packetlen);
  3346. send_ip_packet(USI->rawsd, ethptr, hss->target->TargetSockAddr(), packet, packetlen);
  3347. free(packet);
  3348. }
  3349. } else if (hss->target->af() == AF_INET6) {
  3350. packet = build_protoscan_packet(hss->target->SourceSockAddr(), hss->target->TargetSockAddr(),
  3351. pspec->proto, sport, &packetlen);
  3352. assert(packet != NULL);
  3353. probe->setIP(packet, packetlen, pspec);
  3354. probe->sent = USI->now;
  3355. hss->probeSent(packetlen);
  3356. send_ip_packet(USI->rawsd, ethptr, hss->target->TargetSockAddr(), packet, packetlen);
  3357. free(packet);
  3358. }
  3359. } else if (pspec->type == PS_ICMP) {
  3360. for (decoy = 0; decoy < o.numdecoys; decoy++) {
  3361. packet = build_icmp_raw(&o.decoys[decoy], hss->target->v4hostip(),
  3362. o.ttl, ipid, IP_TOS_DEFAULT, false,
  3363. o.ipoptions, o.ipoptionslen,
  3364. 0, icmp_ident, pspec->pd.icmp.type, pspec->pd.icmp.code,
  3365. o.extra_payload, o.extra_payload_length,
  3366. &packetlen);
  3367. if (decoy == o.decoyturn) {
  3368. probe->setIP(packet, packetlen, pspec);
  3369. probe->sent = USI->now;
  3370. }
  3371. hss->probeSent(packetlen);
  3372. send_ip_packet(USI->rawsd, ethptr, hss->target->TargetSockAddr(), packet, packetlen);
  3373. free(packet);
  3374. }
  3375. } else if (pspec->type == PS_ICMPV6) {
  3376. struct sockaddr_storage source;
  3377. struct sockaddr_in6 *sin6;
  3378. size_t source_len;
  3379. source_len = sizeof(source);
  3380. hss->target->SourceSockAddr(&source, &source_len);
  3381. sin6 = (struct sockaddr_in6 *) &source;
  3382. packet = build_icmpv6_raw(&sin6->sin6_addr, hss->target->v6hostip(),
  3383. 0, 0, o.ttl, 0, icmp_ident, pspec->pd.icmpv6.type,
  3384. pspec->pd.icmpv6.code, o.extra_payload,
  3385. o.extra_payload_length,
  3386. &packetlen);
  3387. probe->setIP(packet, packetlen, pspec);
  3388. probe->sent = USI->now;
  3389. hss->probeSent(packetlen);
  3390. send_ip_packet(USI->rawsd, ethptr, hss->target->TargetSockAddr(), packet, packetlen);
  3391. free(packet);
  3392. } else assert(0);
  3393. /* Now that the probe has been sent, add it to the Queue for this host */
  3394. hss->probes_outstanding.push_back(probe);
  3395. USI->gstats->num_probes_active++;
  3396. hss->num_probes_active++;
  3397. gettimeofday(&USI->now, NULL);
  3398. return probe;
  3399. }
  3400. static void sendNextScanProbe(UltraScanInfo *USI, HostScanStats *hss) {
  3401. probespec pspec;
  3402. if (get_next_target_probe(USI, hss, &pspec) == -1) {
  3403. fatal("%s: No more probes! Error in Nmap.", __func__);
  3404. }
  3405. hss->numprobes_sent++;
  3406. USI->gstats->probes_sent++;
  3407. if (pspec.type == PS_ARP)
  3408. sendArpScanProbe(USI, hss, 0, 0);
  3409. else if (pspec.type == PS_ND)
  3410. sendNDScanProbe(USI, hss, 0, 0);
  3411. else if (pspec.type == PS_CONNECTTCP)
  3412. sendConnectScanProbe(USI, hss, pspec.pd.tcp.dport, 0, 0);
  3413. else if (pspec.type == PS_TCP || pspec.type == PS_UDP
  3414. || pspec.type == PS_SCTP || pspec.type == PS_PROTO
  3415. || pspec.type == PS_ICMP || pspec.type == PS_ICMPV6)
  3416. sendIPScanProbe(USI, hss, &pspec, 0, 0);
  3417. else
  3418. assert(0);
  3419. }
  3420. static void sendNextRetryStackProbe(UltraScanInfo *USI, HostScanStats *hss) {
  3421. assert(!hss->retry_stack.empty());
  3422. probespec pspec;
  3423. u8 pspec_tries;
  3424. hss->numprobes_sent++;
  3425. USI->gstats->probes_sent++;
  3426. pspec = hss->retry_stack.back();
  3427. hss->retry_stack.pop_back();
  3428. pspec_tries = hss->retry_stack_tries.back();
  3429. hss->retry_stack_tries.pop_back();
  3430. if (pspec.type == PS_CONNECTTCP)
  3431. sendConnectScanProbe(USI, hss, pspec.pd.tcp.dport, pspec_tries + 1, 0);
  3432. else {
  3433. assert(pspec.type != PS_ARP && pspec.type != PS_ND);
  3434. sendIPScanProbe(USI, hss, &pspec, pspec_tries + 1, 0);
  3435. }
  3436. }
  3437. static void doAnyNewProbes(UltraScanInfo *USI) {
  3438. HostScanStats *hss, *unableToSend;
  3439. gettimeofday(&USI->now, NULL);
  3440. /* Loop around the list of incomplete hosts and send a probe to each if
  3441. appropriate. Stop once we've been all the way through the list without
  3442. sending a probe. */
  3443. unableToSend = NULL;
  3444. hss = USI->nextIncompleteHost();
  3445. while (hss != NULL && hss != unableToSend && USI->gstats->sendOK(NULL)) {
  3446. if (hss->freshPortsLeft() && hss->sendOK(NULL)) {
  3447. sendNextScanProbe(USI, hss);
  3448. unableToSend = NULL;
  3449. } else if (unableToSend == NULL) {
  3450. /* Mark this as the first host we were not able to send to so we can break
  3451. when we see it again. */
  3452. unableToSend = hss;
  3453. }
  3454. hss = USI->nextIncompleteHost();
  3455. }
  3456. }
  3457. static void doAnyRetryStackRetransmits(UltraScanInfo *USI) {
  3458. HostScanStats *hss, *unableToSend;
  3459. gettimeofday(&USI->now, NULL);
  3460. /* Loop around the list of incomplete hosts and send a probe to each if
  3461. appropriate. Stop once we've been all the way through the list without
  3462. sending a probe. */
  3463. unableToSend = NULL;
  3464. hss = USI->nextIncompleteHost();
  3465. while (hss != NULL && hss != unableToSend && USI->gstats->sendOK(NULL)) {
  3466. if (!hss->retry_stack.empty() && hss->sendOK(NULL)) {
  3467. sendNextRetryStackProbe(USI, hss);
  3468. unableToSend = NULL;
  3469. } else if (unableToSend == NULL) {
  3470. /* Mark this as the first host we were not able to send to so we can break
  3471. when we see it again. */
  3472. unableToSend = hss;
  3473. }
  3474. hss = USI->nextIncompleteHost();
  3475. }
  3476. }
  3477. /* Sends a ping probe to the host. Assumes that caller has already
  3478. checked that sending is OK w/congestion control and that pingprobe is
  3479. available */
  3480. static void sendPingProbe(UltraScanInfo *USI, HostScanStats *hss) {
  3481. if (o.debugging > 1) {
  3482. char tmpbuf[64];
  3483. log_write(LOG_PLAIN, "Ultrascan PING SENT to %s [%s]\n", hss->target->targetipstr(),
  3484. probespec2ascii(&hss->target->pingprobe, tmpbuf, sizeof(tmpbuf)));
  3485. }
  3486. if (hss->target->pingprobe.type == PS_CONNECTTCP) {
  3487. sendConnectScanProbe(USI, hss, hss->target->pingprobe.pd.tcp.dport, 0,
  3488. hss->nextPingSeq(true));
  3489. } else if (hss->target->pingprobe.type == PS_TCP || hss->target->pingprobe.type == PS_UDP
  3490. || hss->target->pingprobe.type == PS_SCTP || hss->target->pingprobe.type == PS_PROTO
  3491. || hss->target->pingprobe.type == PS_ICMP) {
  3492. sendIPScanProbe(USI, hss, &hss->target->pingprobe, 0, hss->nextPingSeq(true));
  3493. } else if (hss->target->pingprobe.type == PS_ARP) {
  3494. sendArpScanProbe(USI, hss, 0, hss->nextPingSeq(true));
  3495. } else if (hss->target->pingprobe.type == PS_ND) {
  3496. sendNDScanProbe(USI, hss, 0, hss->nextPingSeq(true));
  3497. } else {
  3498. assert(0);
  3499. }
  3500. USI->gstats->probes_sent++;
  3501. }
  3502. static void sendGlobalPingProbe(UltraScanInfo *USI) {
  3503. HostScanStats *hss;
  3504. hss = USI->gstats->pinghost;
  3505. assert(hss != NULL);
  3506. if (o.debugging > 1) {
  3507. char tmpbuf[64];
  3508. log_write(LOG_PLAIN, "Ultrascan GLOBAL PING SENT to %s [%s]\n", hss->target->targetipstr(),
  3509. probespec2ascii(&hss->target->pingprobe, tmpbuf, sizeof(tmpbuf)));
  3510. }
  3511. sendPingProbe(USI, hss);
  3512. }
  3513. static void doAnyPings(UltraScanInfo *USI) {
  3514. std::list<HostScanStats *>::iterator hostI;
  3515. HostScanStats *hss = NULL;
  3516. gettimeofday(&USI->now, NULL);
  3517. /* First single host pings */
  3518. for (hostI = USI->incompleteHosts.begin();
  3519. hostI != USI->incompleteHosts.end(); hostI++) {
  3520. hss = *hostI;
  3521. if (hss->target->pingprobe.type != PS_NONE &&
  3522. hss->rld.rld_waiting == false &&
  3523. hss->numprobes_sent >= hss->lastping_sent_numprobes + 10 &&
  3524. TIMEVAL_SUBTRACT(USI->now, hss->lastrcvd) > USI->perf.pingtime &&
  3525. TIMEVAL_SUBTRACT(USI->now, hss->lastping_sent) > USI->perf.pingtime &&
  3526. USI->gstats->sendOK(NULL) && hss->sendOK(NULL)) {
  3527. sendPingProbe(USI, hss);
  3528. hss->lastping_sent = USI->now;
  3529. hss->lastping_sent_numprobes = hss->numprobes_sent;
  3530. }
  3531. }
  3532. /* Next come global pings. We never send more than one of these at at time. */
  3533. if (USI->gstats->pinghost != NULL &&
  3534. USI->gstats->pinghost->target->pingprobe.type != PS_NONE &&
  3535. USI->gstats->pinghost->num_probes_active == 0 &&
  3536. USI->gstats->probes_sent >= USI->gstats->lastping_sent_numprobes + 20 &&
  3537. TIMEVAL_SUBTRACT(USI->now, USI->gstats->lastrcvd) > USI->perf.pingtime &&
  3538. TIMEVAL_SUBTRACT(USI->now, USI->gstats->lastping_sent) > USI->perf.pingtime &&
  3539. USI->gstats->sendOK(NULL)) {
  3540. sendGlobalPingProbe(USI);
  3541. USI->gstats->lastping_sent = USI->now;
  3542. USI->gstats->lastping_sent_numprobes = USI->gstats->probes_sent;
  3543. }
  3544. }
  3545. /* Retransmit one probe that has presumably been timed out. Only does
  3546. retransmission, does not mark the probe timed out and such. */
  3547. static void retransmitProbe(UltraScanInfo *USI, HostScanStats *hss,
  3548. UltraProbe *probe) {
  3549. UltraProbe *newProbe = NULL;
  3550. if (probe->type == UltraProbe::UP_IP) {
  3551. if (USI->prot_scan || USI->ptech.rawprotoscan)
  3552. newProbe = sendIPScanProbe(USI, hss, probe->pspec(), probe->tryno + 1, 0);
  3553. else if (probe->protocol() == IPPROTO_TCP) {
  3554. newProbe = sendIPScanProbe(USI, hss, probe->pspec(), probe->tryno + 1, 0);
  3555. } else if (probe->protocol() == IPPROTO_UDP) {
  3556. newProbe = sendIPScanProbe(USI, hss, probe->pspec(), probe->tryno + 1, 0);
  3557. } else if (probe->protocol() == IPPROTO_SCTP) {
  3558. newProbe = sendIPScanProbe(USI, hss, probe->pspec(), probe->tryno + 1, 0);
  3559. } else if (probe->protocol() == IPPROTO_ICMP || probe->protocol() == IPPROTO_ICMPV6) {
  3560. newProbe = sendIPScanProbe(USI, hss, probe->pspec(), probe->tryno + 1, 0);
  3561. } else {
  3562. assert(0);
  3563. }
  3564. } else if (probe->type == UltraProbe::UP_CONNECT) {
  3565. newProbe = sendConnectScanProbe(USI, hss, probe->pspec()->pd.tcp.dport, probe->tryno + 1, 0);
  3566. } else if (probe->type == UltraProbe::UP_ARP) {
  3567. newProbe = sendArpScanProbe(USI, hss, probe->tryno + 1, 0);
  3568. } else if (probe->type == UltraProbe::UP_ND) {
  3569. newProbe = sendNDScanProbe(USI, hss, probe->tryno + 1, 0);
  3570. } else {
  3571. /* TODO: Support any other probe types */
  3572. fatal("%s: unsupported probe type %d", __func__, probe->type);
  3573. }
  3574. if (newProbe)
  3575. newProbe->prevSent = probe->sent;
  3576. probe->retransmitted = true;
  3577. assert(hss->num_probes_waiting_retransmit > 0);
  3578. hss->num_probes_waiting_retransmit--;
  3579. hss->numprobes_sent++;
  3580. USI->gstats->probes_sent++;
  3581. }
  3582. /* Go through the ProbeQueue of each host, identify any
  3583. timed out probes, then try to retransmit them as appropriate */
  3584. static void doAnyOutstandingRetransmits(UltraScanInfo *USI) {
  3585. std::list<HostScanStats *>::iterator hostI;
  3586. std::list<UltraProbe *>::iterator probeI;
  3587. /* A cache of the last processed probe from each host, to avoid re-examining a
  3588. bunch of probes to find the next one that needs to be retransmitted. */
  3589. std::map<HostScanStats *, std::list<UltraProbe *>::iterator> probe_cache;
  3590. HostScanStats *host = NULL;
  3591. UltraProbe *probe = NULL;
  3592. int retrans = 0; /* Number of retransmissions during a loop */
  3593. unsigned int maxtries;
  3594. struct timeval tv_start = {0};
  3595. gettimeofday(&USI->now, NULL);
  3596. if (o.debugging)
  3597. tv_start = USI->now;
  3598. /* Loop until we get through all the hosts without a retransmit or we're not
  3599. OK to send any more. */
  3600. do {
  3601. retrans = 0;
  3602. for (hostI = USI->incompleteHosts.begin();
  3603. hostI != USI->incompleteHosts.end() && USI->gstats->sendOK(NULL);
  3604. hostI++) {
  3605. host = *hostI;
  3606. /* Skip this host if it has nothing to send. */
  3607. if ((host->num_probes_active == 0
  3608. && host->num_probes_waiting_retransmit == 0))
  3609. continue;
  3610. if (!host->sendOK(NULL))
  3611. continue;
  3612. assert(!host->probes_outstanding.empty());
  3613. /* Initialize the probe cache if necessary. */
  3614. if (probe_cache.find(host) == probe_cache.end())
  3615. probe_cache[host] = host->probes_outstanding.end();
  3616. /* Restore the probe iterator from the cache. */
  3617. probeI = probe_cache[host];
  3618. maxtries = host->allowedTryno(NULL, NULL);
  3619. do {
  3620. probeI--;
  3621. probe = *probeI;
  3622. if (probe->timedout && !probe->retransmitted &&
  3623. maxtries > probe->tryno && !probe->isPing()) {
  3624. /* For rate limit detection, we delay the first time a new tryno
  3625. is seen, as long as we are scanning at least 2 ports */
  3626. if (probe->tryno + 1 > (int) host->rld.max_tryno_sent &&
  3627. USI->gstats->numprobes > 1) {
  3628. host->rld.max_tryno_sent = probe->tryno + 1;
  3629. host->rld.rld_waiting = true;
  3630. TIMEVAL_MSEC_ADD(host->rld.rld_waittime, USI->now, 1000);
  3631. } else {
  3632. host->rld.rld_waiting = false;
  3633. retransmitProbe(USI, host, probe);
  3634. retrans++;
  3635. }
  3636. break; /* I only do one probe per host for now to spread load */
  3637. }
  3638. } while (probeI != host->probes_outstanding.begin());
  3639. /* Wrap the probe iterator around. */
  3640. if (probeI == host->probes_outstanding.begin())
  3641. probeI = host->probes_outstanding.end();
  3642. /* Cache the probe iterator. */
  3643. probe_cache[host] = probeI;
  3644. }
  3645. } while (USI->gstats->sendOK(NULL) && retrans != 0);
  3646. gettimeofday(&USI->now, NULL);
  3647. if (o.debugging) {
  3648. long tv_diff = TIMEVAL_MSEC_SUBTRACT(USI->now, tv_start);
  3649. if (tv_diff > 30)
  3650. log_write(LOG_PLAIN, "%s took %lims\n", __func__, tv_diff);
  3651. }
  3652. }
  3653. /* Print occasional remaining time estimates, as well as
  3654. debugging information */
  3655. static void printAnyStats(UltraScanInfo *USI) {
  3656. std::list<HostScanStats *>::iterator hostI;
  3657. HostScanStats *hss;
  3658. struct ultra_timing_vals hosttm;
  3659. /* Print debugging states for each host being scanned */
  3660. if (o.debugging > 2) {
  3661. log_write(LOG_PLAIN, "**TIMING STATS** (%.4fs): IP, probes active/freshportsleft/retry_stack/outstanding/retranwait/onbench, cwnd/ssthresh/delay, timeout/srtt/rttvar/\n", o.TimeSinceStart());
  3662. log_write(LOG_PLAIN, " Groupstats (%d/%d incomplete): %d/*/*/*/*/* %.2f/%d/* %d/%d/%d\n",
  3663. USI->numIncompleteHosts(), USI->numInitialHosts(),
  3664. USI->gstats->num_probes_active, USI->gstats->timing.cwnd,
  3665. USI->gstats->timing.ssthresh, USI->gstats->to.timeout,
  3666. USI->gstats->to.srtt, USI->gstats->to.rttvar);
  3667. if (o.debugging > 3) {
  3668. for (hostI = USI->incompleteHosts.begin();
  3669. hostI != USI->incompleteHosts.end(); hostI++) {
  3670. hss = *hostI;
  3671. hss->getTiming(&hosttm);
  3672. log_write(LOG_PLAIN, " %s: %d/%d/%d/%d/%d/%d %.2f/%d/%d %li/%d/%d\n", hss->target->targetipstr(),
  3673. hss->num_probes_active, hss->freshPortsLeft(),
  3674. (int) hss->retry_stack.size(),
  3675. hss->num_probes_outstanding(),
  3676. hss->num_probes_waiting_retransmit, (int) hss->probe_bench.size(),
  3677. hosttm.cwnd, hosttm.ssthresh, hss->sdn.delayms,
  3678. hss->probeTimeout(), hss->target->to.srtt,
  3679. hss->target->to.rttvar);
  3680. }
  3681. }
  3682. USI->log_current_rates(LOG_PLAIN);
  3683. USI->log_overall_rates(LOG_PLAIN);
  3684. }
  3685. if (USI->SPM->mayBePrinted(&USI->now))
  3686. USI->SPM->printStatsIfNecessary(USI->getCompletionFraction(), &USI->now);
  3687. }
  3688. /* Does a select() call and handles all of the results. This handles both host
  3689. discovery (ping) scans and port scans. Even if stime is now, it tries a very
  3690. quick select() just in case. Returns true if at least one good result
  3691. (generally a port state change) is found, false if it times out instead */
  3692. static bool do_one_select_round(UltraScanInfo *USI, struct timeval *stime) {
  3693. fd_set fds_rtmp, fds_wtmp, fds_xtmp;
  3694. int selectres;
  3695. struct timeval timeout;
  3696. int timeleft;
  3697. ConnectScanInfo *CSI = USI->gstats->CSI;
  3698. int sd;
  3699. std::list<HostScanStats *>::iterator hostI;
  3700. HostScanStats *host;
  3701. std::list<UltraProbe *>::iterator probeI, nextProbeI;
  3702. UltraProbe *probe = NULL;
  3703. unsigned int listsz;
  3704. unsigned int probenum;
  3705. int newportstate = PORT_UNKNOWN;
  3706. int newhoststate = HOST_UNKNOWN;
  3707. int optval;
  3708. recvfrom6_t optlen = sizeof(int);
  3709. int numGoodSD = 0;
  3710. int err = 0;
  3711. reason_t current_reason = ER_NORESPONSE;
  3712. do {
  3713. timeleft = TIMEVAL_MSEC_SUBTRACT(*stime, USI->now);
  3714. if (timeleft < 0)
  3715. timeleft = 0;
  3716. fds_rtmp = USI->gstats->CSI->fds_read;
  3717. fds_wtmp = USI->gstats->CSI->fds_write;
  3718. fds_xtmp = USI->gstats->CSI->fds_except;
  3719. timeout.tv_sec = timeleft / 1000;
  3720. timeout.tv_usec = (timeleft % 1000) * 1000;
  3721. if (CSI->numSDs) {
  3722. selectres = select(CSI->maxValidSD + 1, &fds_rtmp, &fds_wtmp,
  3723. &fds_xtmp, &timeout);
  3724. err = socket_errno();
  3725. } else {
  3726. /* Apparently Windows returns an WSAEINVAL if you select without watching any SDs. Lame. We'll usleep instead in that case */
  3727. usleep(timeleft * 1000);
  3728. selectres = 0;
  3729. }
  3730. } while (selectres == -1 && err == EINTR);
  3731. gettimeofday(&USI->now, NULL);
  3732. if (selectres == -1)
  3733. pfatal("select failed in %s()", __func__);
  3734. if (!selectres)
  3735. return false;
  3736. /* Yay! Got at least one response back -- loop through outstanding probes
  3737. and find the relevant ones. Note the peculiar structure of the loop--we
  3738. iterate through both incompleteHosts and completedHosts, because global
  3739. timing pings are sent to hosts in completedHosts. */
  3740. std::list<HostScanStats *>::iterator incompleteHostI, completedHostI;
  3741. incompleteHostI = USI->incompleteHosts.begin();
  3742. completedHostI = USI->completedHosts.begin();
  3743. while ((incompleteHostI != USI->incompleteHosts.end()
  3744. || completedHostI != USI->completedHosts.end())
  3745. && numGoodSD < selectres) {
  3746. if (incompleteHostI != USI->incompleteHosts.end())
  3747. hostI = incompleteHostI++;
  3748. else
  3749. hostI = completedHostI++;
  3750. host = *hostI;
  3751. if (host->num_probes_active == 0)
  3752. continue;
  3753. nextProbeI = probeI = host->probes_outstanding.end();
  3754. listsz = host->num_probes_outstanding();
  3755. if (listsz)
  3756. nextProbeI--;
  3757. for (probenum = 0; probenum < listsz && numGoodSD < selectres; probenum++) {
  3758. probeI = nextProbeI;
  3759. if (probeI != host->probes_outstanding.begin())
  3760. nextProbeI--;
  3761. probe = *probeI;
  3762. /* Assume that we will adjust timing when a response is received. */
  3763. bool adjust_timing = true;
  3764. assert(probe->type == UltraProbe::UP_CONNECT);
  3765. sd = probe->CP()->sd;
  3766. /* Let see if anything has happened! */
  3767. if (sd >= 0 && (FD_ISSET(sd, &fds_rtmp) || FD_ISSET(sd, &fds_wtmp) ||
  3768. FD_ISSET(sd, &fds_xtmp))) {
  3769. numGoodSD++;
  3770. newportstate = PORT_UNKNOWN;
  3771. if (getsockopt(sd, SOL_SOCKET, SO_ERROR, (char *) &optval,
  3772. &optlen) != 0)
  3773. optval = socket_errno(); /* Stupid Solaris ... */
  3774. switch (optval) {
  3775. case 0:
  3776. newhoststate = HOST_UP;
  3777. newportstate = PORT_OPEN;
  3778. current_reason = ER_CONACCEPT;
  3779. break;
  3780. case EACCES:
  3781. /* Apparently this can be caused by dest unreachable admin
  3782. prohibited messages sent back, at least from IPv6
  3783. hosts */
  3784. newhoststate = HOST_DOWN;
  3785. newportstate = PORT_FILTERED;
  3786. current_reason = ER_ADMINPROHIBITED;
  3787. break;
  3788. case ECONNREFUSED:
  3789. newhoststate = HOST_UP;
  3790. newportstate = PORT_CLOSED;
  3791. current_reason = ER_CONREFUSED;
  3792. break;
  3793. case EAGAIN:
  3794. log_write(LOG_STDOUT, "Machine %s MIGHT actually be listening on probe port %d\n", host->target->targetipstr(), USI->ports->syn_ping_ports[probe->dport()]);
  3795. /* Fall through. */
  3796. #ifdef WIN32
  3797. case WSAENOTCONN:
  3798. #endif
  3799. newhoststate = HOST_UP;
  3800. current_reason = ER_CONACCEPT;
  3801. break;
  3802. #ifdef ENOPROTOOPT
  3803. case ENOPROTOOPT:
  3804. #endif
  3805. case EHOSTUNREACH:
  3806. newhoststate = HOST_DOWN;
  3807. newportstate = PORT_FILTERED;
  3808. current_reason = ER_HOSTUNREACH;
  3809. break;
  3810. #ifdef WIN32
  3811. case WSAEADDRNOTAVAIL:
  3812. #endif
  3813. case ETIMEDOUT:
  3814. case EHOSTDOWN:
  3815. newhoststate = HOST_DOWN;
  3816. /* It could be the host is down, or it could be firewalled. We
  3817. will go on the safe side & assume port is closed ... on second
  3818. thought, lets go firewalled! and see if it causes any trouble */
  3819. newportstate = PORT_FILTERED;
  3820. current_reason = ER_NORESPONSE;
  3821. break;
  3822. case ENETUNREACH:
  3823. newhoststate = HOST_DOWN;
  3824. newportstate = PORT_FILTERED;
  3825. current_reason = ER_NETUNREACH;
  3826. break;
  3827. case ENETDOWN:
  3828. case ENETRESET:
  3829. case ECONNABORTED:
  3830. fatal("Strange SO_ERROR from connection to %s (%d - '%s') -- bailing scan", host->target->targetipstr(), optval, strerror(optval));
  3831. break;
  3832. default:
  3833. error("Strange read error from %s (%d - '%s')", host->target->targetipstr(), optval, strerror(optval));
  3834. break;
  3835. }
  3836. if (USI->ping_scan && newhoststate != HOST_UNKNOWN) {
  3837. if (probe->isPing())
  3838. ultrascan_ping_update(USI, host, probeI, &USI->now, adjust_timing);
  3839. else {
  3840. ultrascan_host_probe_update(USI, host, probeI, newhoststate, &USI->now, adjust_timing);
  3841. host->target->reason.reason_id = current_reason;
  3842. }
  3843. } else if (!USI->ping_scan && newportstate != PORT_UNKNOWN) {
  3844. if (probe->isPing())
  3845. ultrascan_ping_update(USI, host, probeI, &USI->now, adjust_timing);
  3846. else {
  3847. /* Save these values so we can use them after
  3848. ultrascan_port_probe_update deletes probe. */
  3849. u8 protocol = probe->protocol();
  3850. u16 dport = probe->dport();
  3851. ultrascan_port_probe_update(USI, host, probeI, newportstate, &USI->now, adjust_timing);
  3852. host->target->ports.setStateReason(dport, protocol, current_reason, 0, NULL);
  3853. }
  3854. }
  3855. }
  3856. }
  3857. }
  3858. return numGoodSD;
  3859. }
  3860. /* Tries to get one *good* (finishes a probe) ARP response with pcap
  3861. by the (absolute) time given in stime. Even if stime is now, try
  3862. an ultra-quick pcap read just in case. Returns true if a "good"
  3863. result was found, false if it timed out instead. */
  3864. static bool get_arp_result(UltraScanInfo *USI, struct timeval *stime) {
  3865. long to_usec;
  3866. int rc;
  3867. u8 rcvdmac[6];
  3868. struct in_addr rcvdIP;
  3869. struct timeval rcvdtime;
  3870. bool timedout = false;
  3871. struct sockaddr_in sin;
  3872. HostScanStats *hss = NULL;
  3873. std::list<UltraProbe *>::iterator probeI;
  3874. int gotone = 0;
  3875. gettimeofday(&USI->now, NULL);
  3876. do {
  3877. to_usec = TIMEVAL_SUBTRACT(*stime, USI->now);
  3878. if (to_usec < 2000)
  3879. to_usec = 2000;
  3880. rc = read_arp_reply_pcap(USI->pd, rcvdmac, &rcvdIP, to_usec, &rcvdtime, PacketTrace::traceArp);
  3881. gettimeofday(&USI->now, NULL);
  3882. if (rc == -1)
  3883. fatal("Received -1 response from read_arp_reply_pcap");
  3884. if (rc == 0) {
  3885. if (TIMEVAL_SUBTRACT(*stime, USI->now) < 0) {
  3886. timedout = true;
  3887. break;
  3888. } else {
  3889. continue;
  3890. }
  3891. }
  3892. if (rc == 1) {
  3893. if (TIMEVAL_SUBTRACT(USI->now, *stime) > 200000) {
  3894. /* While packets are still being received, I'll be generous
  3895. and give an extra 1/5 sec. But we have to draw the line
  3896. somewhere. Hopefully this response will be a keeper so it
  3897. won't matter. */
  3898. timedout = true;
  3899. }
  3900. /* Yay, I got one. Find whether I asked for it */
  3901. /* Search for this host on the incomplete list */
  3902. memset(&sin, 0, sizeof(sin));
  3903. sin.sin_addr.s_addr = rcvdIP.s_addr;
  3904. sin.sin_family = AF_INET;
  3905. hss = USI->findHost((struct sockaddr_storage *) &sin);
  3906. if (!hss)
  3907. continue;
  3908. /* Add found HW address for target */
  3909. hss->target->setMACAddress(rcvdmac);
  3910. hss->target->reason.reason_id = ER_ARPRESPONSE;
  3911. if (hss->probes_outstanding.empty()) {
  3912. continue;
  3913. /* TODO: I suppose I should really mark the @@# host as up */
  3914. }
  3915. probeI = hss->probes_outstanding.end();
  3916. probeI--;
  3917. ultrascan_host_probe_update(USI, hss, probeI, HOST_UP, &rcvdtime);
  3918. /* Now that we know the host is up, we can forget our other probes. */
  3919. hss->destroyAllOutstandingProbes();
  3920. /* TODO: Set target mac */
  3921. gotone = 1;
  3922. // printf("Marked host %s as up!", hss->target->NameIP());
  3923. break;
  3924. }
  3925. } while (!timedout);
  3926. return gotone;
  3927. }
  3928. static bool get_ns_result(UltraScanInfo *USI, struct timeval *stime) {
  3929. long to_usec;
  3930. int rc;
  3931. u8 rcvdmac[6];
  3932. struct sockaddr_in6 rcvdIP;
  3933. struct timeval rcvdtime;
  3934. bool timedout = false;
  3935. bool has_mac = false;
  3936. struct sockaddr_in6 sin6;
  3937. HostScanStats *hss = NULL;
  3938. std::list<UltraProbe *>::iterator probeI;
  3939. int gotone = 0;
  3940. gettimeofday(&USI->now, NULL);
  3941. do {
  3942. to_usec = TIMEVAL_SUBTRACT(*stime, USI->now);
  3943. if (to_usec < 2000)
  3944. to_usec = 2000;
  3945. rc = read_na_pcap(USI->pd, rcvdmac, &rcvdIP, to_usec, &rcvdtime, &has_mac);
  3946. gettimeofday(&USI->now, NULL);
  3947. if (rc == -1)
  3948. fatal("Received -1 response from read_arp_reply_pcap");
  3949. if (rc == 0) {
  3950. if (TIMEVAL_SUBTRACT(*stime, USI->now) < 0) {
  3951. timedout = true;
  3952. break;
  3953. } else {
  3954. continue;
  3955. }
  3956. }
  3957. if (rc == 1) {
  3958. if (TIMEVAL_SUBTRACT(USI->now, *stime) > 200000) {
  3959. /* While packets are still being received, I'll be generous
  3960. and give an extra 1/5 sec. But we have to draw the line
  3961. somewhere. Hopefully this response will be a keeper so it
  3962. won't matter. */
  3963. timedout = true;
  3964. }
  3965. /* Yay, I got one. Find whether I asked for it */
  3966. /* Search for this host on the incomplete list */
  3967. memset(&sin6, 0, sizeof(sin6));
  3968. sin6.sin6_addr = rcvdIP.sin6_addr;
  3969. sin6.sin6_family = AF_INET6;
  3970. hss = USI->findHost((struct sockaddr_storage *) &sin6);
  3971. if (!hss)
  3972. continue;
  3973. /* Add found HW address for target */
  3974. /* A Neighbor Advertisement packet may not include the Target link-layer address. */
  3975. if (has_mac)
  3976. hss->target->setMACAddress(rcvdmac);
  3977. hss->target->reason.reason_id = ER_NDRESPONSE;
  3978. if (hss->probes_outstanding.empty()) {
  3979. continue;
  3980. /* TODO: I suppose I should really mark the @@# host as up */
  3981. }
  3982. probeI = hss->probes_outstanding.end();
  3983. probeI--;
  3984. ultrascan_host_probe_update(USI, hss, probeI, HOST_UP, &rcvdtime);
  3985. /* Now that we know the host is up, we can forget our other probes. */
  3986. hss->destroyAllOutstandingProbes();
  3987. /* TODO: Set target mac */
  3988. gotone = 1;
  3989. // printf("Marked host %s as up!", hss->target->NameIP());
  3990. break;
  3991. }
  3992. } while (!timedout);
  3993. return gotone;
  3994. }
  3995. /* Tries to get one *good* (finishes a probe) pcap response by the
  3996. (absolute) time given in stime. Even if stime is now, try an
  3997. ultra-quick pcap read just in case. Returns true if a "good" result
  3998. was found, false if it timed out instead. */
  3999. static bool get_pcap_result(UltraScanInfo *USI, struct timeval *stime) {
  4000. bool goodone = false;
  4001. bool timedout = false;
  4002. bool adjust_timing = true;
  4003. struct timeval rcvdtime;
  4004. struct link_header linkhdr;
  4005. unsigned int bytes;
  4006. long to_usec;
  4007. HostScanStats *hss = NULL;
  4008. std::list<UltraProbe *>::iterator probeI;
  4009. UltraProbe *probe = NULL;
  4010. int newstate = PORT_UNKNOWN;
  4011. unsigned int probenum;
  4012. unsigned int listsz;
  4013. /* Static so that we can detect an ICMP response now, then add it later when
  4014. the icmp probe is made */
  4015. static bool protoscanicmphack = false;
  4016. static struct sockaddr_storage protoscanicmphackaddy;
  4017. reason_t current_reason = ER_NORESPONSE;
  4018. struct sockaddr_storage reason_sip = { AF_UNSPEC };
  4019. const void *data = NULL;
  4020. unsigned int datalen;
  4021. struct abstract_ip_hdr hdr;
  4022. gettimeofday(&USI->now, NULL);
  4023. do {
  4024. struct ip *ip_tmp;
  4025. to_usec = TIMEVAL_SUBTRACT(*stime, USI->now);
  4026. if (to_usec < 2000)
  4027. to_usec = 2000;
  4028. ip_tmp = (struct ip *) readip_pcap(USI->pd, &bytes, to_usec, &rcvdtime, &linkhdr, true);
  4029. gettimeofday(&USI->now, NULL);
  4030. if (!ip_tmp && TIMEVAL_SUBTRACT(*stime, USI->now) < 0) {
  4031. timedout = true;
  4032. break;
  4033. } else if (!ip_tmp)
  4034. continue;
  4035. if (TIMEVAL_SUBTRACT(USI->now, *stime) > 200000) {
  4036. /* While packets are still being received, I'll be generous and give
  4037. an extra 1/5 sec. But we have to draw the line somewhere */
  4038. timedout = true;
  4039. }
  4040. struct sockaddr_storage target_src, target_dst;
  4041. size_t ss_len;
  4042. datalen = bytes;
  4043. data = ip_get_data(ip_tmp, &datalen, &hdr);
  4044. if (data == NULL)
  4045. continue;
  4046. if (USI->prot_scan) {
  4047. hss = USI->findHost(&hdr.src);
  4048. if (hss) {
  4049. setTargetMACIfAvailable(hss->target, &linkhdr, &hdr.src, 0);
  4050. if (hdr.proto == IPPROTO_ICMP) {
  4051. protoscanicmphack = true;
  4052. protoscanicmphackaddy = hdr.src;
  4053. } else {
  4054. probeI = hss->probes_outstanding.end();
  4055. listsz = hss->num_probes_outstanding();
  4056. goodone = false;
  4057. for (probenum = 0; probenum < listsz && !goodone; probenum++) {
  4058. probeI--;
  4059. probe = *probeI;
  4060. if (probe->protocol() == hdr.proto) {
  4061. /* if this is our probe we sent to localhost, then it doesn't count! */
  4062. if (sockaddr_storage_cmp(&hdr.src, &hdr.dst) == 0 &&
  4063. probe->ipid() == hdr.ipid)
  4064. break;
  4065. /* We got a packet from the dst host in the protocol we looked for, and
  4066. it wasn't our probe to ourselves, so it must be open */
  4067. newstate = PORT_OPEN;
  4068. current_reason = ER_PROTORESPONSE;
  4069. goodone = true;
  4070. }
  4071. }
  4072. }
  4073. }
  4074. }
  4075. if (hdr.proto == IPPROTO_TCP && !USI->prot_scan) {
  4076. struct tcp_hdr *tcp = (struct tcp_hdr *) data;
  4077. /* Now ensure this host is even in the incomplete list */
  4078. hss = USI->findHost(&hdr.src);
  4079. if (!hss)
  4080. continue; // Not from a host that interests us
  4081. setTargetMACIfAvailable(hss->target, &linkhdr, &hdr.src, 0);
  4082. probeI = hss->probes_outstanding.end();
  4083. listsz = hss->num_probes_outstanding();
  4084. goodone = false;
  4085. /* Find the probe that provoked this response. */
  4086. for (probenum = 0; probenum < listsz && !goodone; probenum++) {
  4087. probeI--;
  4088. probe = *probeI;
  4089. if (!tcp_probe_match(USI, probe, hss, tcp, &hdr.src, &hdr.dst, hdr.ipid))
  4090. continue;
  4091. if (!probe->isPing()) {
  4092. /* Now that response has been matched to a probe, I interpret it */
  4093. if (USI->scantype == SYN_SCAN && (tcp->th_flags & (TH_SYN | TH_ACK)) == (TH_SYN | TH_ACK)) {
  4094. /* Yeah! An open port */
  4095. newstate = PORT_OPEN;
  4096. current_reason = ER_SYNACK;
  4097. } else if (tcp->th_flags & TH_RST) {
  4098. current_reason = ER_RESETPEER;
  4099. if (USI->scantype == WINDOW_SCAN ) {
  4100. newstate = (tcp->th_win) ? PORT_OPEN : PORT_CLOSED;
  4101. } else if (USI->scantype == ACK_SCAN) {
  4102. newstate = PORT_UNFILTERED;
  4103. } else newstate = PORT_CLOSED;
  4104. } else if (USI->scantype == SYN_SCAN && (tcp->th_flags & TH_SYN)) {
  4105. /* A SYN from a TCP Split Handshake - http://nmap.org/misc/split-handshake.pdf - open port */
  4106. newstate = PORT_OPEN;
  4107. current_reason = ER_SYN;
  4108. } else {
  4109. if (o.debugging)
  4110. error("Received scan response with unexpected TCP flags: %d", tcp->th_flags);
  4111. break;
  4112. }
  4113. }
  4114. goodone = true;
  4115. }
  4116. } else if (hdr.proto == IPPROTO_SCTP && !USI->prot_scan) {
  4117. struct sctp_hdr *sctp = (struct sctp_hdr *) data;
  4118. struct dnet_sctp_chunkhdr *chunk = (struct dnet_sctp_chunkhdr *) ((u8 *) sctp + 12);
  4119. /* Now ensure this host is even in the incomplete list */
  4120. hss = USI->findHost(&hdr.src);
  4121. if (!hss)
  4122. continue; // Not from a host that interests us
  4123. setTargetMACIfAvailable(hss->target, &linkhdr, &hdr.src, 0);
  4124. probeI = hss->probes_outstanding.end();
  4125. listsz = hss->num_probes_outstanding();
  4126. goodone = false;
  4127. ss_len = sizeof(target_src);
  4128. hss->target->SourceSockAddr(&target_src, &ss_len);
  4129. /* Find the probe that provoked this response. */
  4130. for (probenum = 0; probenum < listsz && !goodone; probenum++) {
  4131. probeI--;
  4132. probe = *probeI;
  4133. if (probe->protocol() != IPPROTO_SCTP)
  4134. continue;
  4135. /* Ensure the connection info matches. */
  4136. if (probe->dport() != ntohs(sctp->sh_sport)
  4137. || probe->sport() != ntohs(sctp->sh_dport)
  4138. || sockaddr_storage_cmp(&target_src, &hdr.dst) != 0)
  4139. continue;
  4140. /* Sometimes we get false results when scanning localhost with
  4141. -p- because we scan localhost with src port = dst port and
  4142. see our outgoing packet and think it is a response. */
  4143. if (probe->dport() == probe->sport() &&
  4144. sockaddr_storage_cmp(&hdr.src, &hdr.dst) == 0 &&
  4145. probe->ipid() == hdr.ipid)
  4146. continue; /* We saw the packet we ourselves sent */
  4147. if (!probe->isPing()) {
  4148. /* Now that response has been matched to a probe, I interpret it */
  4149. if (USI->scantype == SCTP_INIT_SCAN) {
  4150. if (chunk->sch_type == SCTP_INIT_ACK) {
  4151. newstate = PORT_OPEN;
  4152. current_reason = ER_INITACK;
  4153. } else if (chunk->sch_type == SCTP_ABORT) {
  4154. newstate = PORT_CLOSED;
  4155. current_reason = ER_ABORT;
  4156. } else {
  4157. if (o.debugging)
  4158. error("Received response with unexpected SCTP chunks: %02x",
  4159. chunk->sch_type);
  4160. break;
  4161. }
  4162. } else if (USI->scantype == SCTP_COOKIE_ECHO_SCAN) {
  4163. if (chunk->sch_type == SCTP_ABORT) {
  4164. newstate = PORT_CLOSED;
  4165. current_reason = ER_ABORT;
  4166. } else {
  4167. if (o.debugging)
  4168. error("Received response with unexpected SCTP chunks: %02x",
  4169. chunk->sch_type);
  4170. break;
  4171. }
  4172. }
  4173. }
  4174. goodone = true;
  4175. }
  4176. } else if (hdr.proto == IPPROTO_ICMP) {
  4177. const void *encaps_data;
  4178. unsigned int encaps_len;
  4179. struct abstract_ip_hdr encaps_hdr;
  4180. struct icmp *icmp = NULL;
  4181. icmp = (struct icmp *) data;
  4182. if (datalen < 8)
  4183. continue;
  4184. if (icmp->icmp_type != 3 && icmp->icmp_type != 11)
  4185. continue;
  4186. encaps_len = datalen - 8;
  4187. encaps_data = ip_get_data((char *) data + 8, &encaps_len, &encaps_hdr);
  4188. if (encaps_data == NULL ||
  4189. /* UDP hdr, or TCP hdr up to seq #, or SCTP hdr up to vtag */
  4190. ((USI->tcp_scan || USI->udp_scan || USI->sctp_scan) && encaps_len < 8)
  4191. /* prot scan has no headers coming back, so we don't reserve the
  4192. 8 xtra bytes */
  4193. ) {
  4194. if (o.debugging)
  4195. error("Received short ICMP packet (%u bytes)", datalen);
  4196. continue;
  4197. }
  4198. /* Make sure the protocol is right */
  4199. if (USI->tcp_scan && encaps_hdr.proto != IPPROTO_TCP)
  4200. continue;
  4201. if (USI->udp_scan && encaps_hdr.proto != IPPROTO_UDP)
  4202. continue;
  4203. if (USI->sctp_scan && encaps_hdr.proto != IPPROTO_SCTP)
  4204. continue;
  4205. /* ensure this packet relates to a packet to the host
  4206. we are scanning ... */
  4207. hss = USI->findHost(&encaps_hdr.dst);
  4208. if (!hss)
  4209. continue; // Not from a host that interests us
  4210. probeI = hss->probes_outstanding.end();
  4211. listsz = hss->num_probes_outstanding();
  4212. ss_len = sizeof(target_src);
  4213. hss->target->SourceSockAddr(&target_src, &ss_len);
  4214. ss_len = sizeof(target_dst);
  4215. hss->target->TargetSockAddr(&target_dst, &ss_len);
  4216. goodone = false;
  4217. /* Find the matching probe */
  4218. for (probenum = 0; probenum < listsz && !goodone; probenum++) {
  4219. probeI--;
  4220. probe = *probeI;
  4221. if (probe->protocol() != encaps_hdr.proto ||
  4222. sockaddr_storage_cmp(&target_src, &encaps_hdr.src) != 0 ||
  4223. sockaddr_storage_cmp(&target_dst, &encaps_hdr.dst) != 0)
  4224. continue;
  4225. if (encaps_hdr.proto == IPPROTO_TCP && !USI->prot_scan) {
  4226. struct tcp_hdr *tcp = (struct tcp_hdr *) encaps_data;
  4227. if (ntohs(tcp->th_sport) != probe->sport() ||
  4228. ntohs(tcp->th_dport) != probe->dport() ||
  4229. ntohl(tcp->th_seq) != probe->tcpseq())
  4230. continue;
  4231. } else if (encaps_hdr.proto == IPPROTO_SCTP && !USI->prot_scan) {
  4232. struct sctp_hdr *sctp = (struct sctp_hdr *) encaps_data;
  4233. if (ntohs(sctp->sh_sport) != probe->sport() ||
  4234. ntohs(sctp->sh_dport) != probe->dport() ||
  4235. ntohl(sctp->sh_vtag) != probe->sctpvtag())
  4236. continue;
  4237. } else if (encaps_hdr.proto == IPPROTO_UDP && !USI->prot_scan) {
  4238. /* TODO: IPID verification */
  4239. struct udp_hdr *udp = (struct udp_hdr *) encaps_data;
  4240. if (ntohs(udp->uh_sport) != probe->sport() ||
  4241. ntohs(udp->uh_dport) != probe->dport())
  4242. continue;
  4243. } else if (!USI->prot_scan) {
  4244. assert(0);
  4245. }
  4246. if (icmp->icmp_type == 3) {
  4247. switch (icmp->icmp_code) {
  4248. case 0: /* Network unreachable */
  4249. newstate = PORT_FILTERED;
  4250. break;
  4251. case 1: /* Host Unreachable */
  4252. newstate = PORT_FILTERED;
  4253. break;
  4254. case 2: /* protocol unreachable */
  4255. if (USI->scantype == IPPROT_SCAN &&
  4256. sockaddr_storage_cmp(&target_dst, &hdr.src) == 0) {
  4257. newstate = PORT_CLOSED;
  4258. } else
  4259. newstate = PORT_FILTERED;
  4260. break;
  4261. case 3: /* Port unreach */
  4262. if (USI->scantype == UDP_SCAN &&
  4263. sockaddr_storage_cmp(&target_dst, &hdr.src) == 0)
  4264. newstate = PORT_CLOSED;
  4265. else if (USI->scantype == IPPROT_SCAN &&
  4266. sockaddr_storage_cmp(&target_dst, &hdr.src) == 0)
  4267. newstate = PORT_OPEN;
  4268. else
  4269. newstate = PORT_FILTERED;
  4270. break;
  4271. case 9: /* dest. net admin prohibited */
  4272. case 10: /* dest host admin prohibited */
  4273. case 13: /* communication admin. prohibited */
  4274. newstate = PORT_FILTERED;
  4275. break;
  4276. default:
  4277. error("Unexpected ICMP type/code 3/%d unreachable packet:\n",
  4278. icmp->icmp_code);
  4279. nmap_hexdump((unsigned char *)icmp, datalen);
  4280. break;
  4281. }
  4282. current_reason = icmp_to_reason(hdr.proto, icmp->icmp_type, icmp->icmp_code);
  4283. if (newstate == PORT_UNKNOWN)
  4284. break;
  4285. goodone = true;
  4286. }
  4287. else if (icmp->icmp_type == 11) { /* ICMP Time Exceeded */
  4288. newstate = PORT_FILTERED;
  4289. current_reason = icmp_to_reason(hdr.proto, icmp->icmp_type, icmp->icmp_code);
  4290. goodone = true;
  4291. }
  4292. }
  4293. } else if (hdr.proto == IPPROTO_ICMPV6) {
  4294. const void *encaps_data;
  4295. unsigned int encaps_len;
  4296. struct abstract_ip_hdr encaps_hdr;
  4297. const struct icmpv6_hdr *icmpv6;
  4298. icmpv6 = (struct icmpv6_hdr *) data;
  4299. if (datalen < 8)
  4300. continue;
  4301. if (!(icmpv6->icmpv6_type == ICMPV6_UNREACH || icmpv6->icmpv6_type == ICMPV6_PARAMPROBLEM))
  4302. continue;
  4303. encaps_len = datalen - 8;
  4304. encaps_data = ip_get_data_any((char *) data + 8, &encaps_len, &encaps_hdr);
  4305. if (encaps_data == NULL ||
  4306. /* UDP hdr, or TCP hdr up to seq #, or SCTP hdr up to vtag */
  4307. ((USI->tcp_scan || USI->udp_scan || USI->sctp_scan) && encaps_len < 8)
  4308. /* prot scan has no headers coming back, so we don't reserve the
  4309. 8 xtra bytes */
  4310. ) {
  4311. if (o.debugging)
  4312. error("Received short ICMPv6 packet (%u bytes)", datalen);
  4313. continue;
  4314. }
  4315. /* Make sure the protocol is right */
  4316. if (USI->tcp_scan && encaps_hdr.proto != IPPROTO_TCP)
  4317. continue;
  4318. if (USI->udp_scan && encaps_hdr.proto != IPPROTO_UDP)
  4319. continue;
  4320. if (USI->sctp_scan && encaps_hdr.proto != IPPROTO_SCTP)
  4321. continue;
  4322. /* ensure this packet relates to a packet to the host
  4323. we are scanning ... */
  4324. hss = USI->findHost(&encaps_hdr.dst);
  4325. if (!hss)
  4326. continue; // Not from a host that interests us
  4327. probeI = hss->probes_outstanding.end();
  4328. listsz = hss->num_probes_outstanding();
  4329. ss_len = sizeof(target_src);
  4330. hss->target->SourceSockAddr(&target_src, &ss_len);
  4331. ss_len = sizeof(target_dst);
  4332. hss->target->TargetSockAddr(&target_dst, &ss_len);
  4333. goodone = false;
  4334. /* Find the matching probe */
  4335. for (probenum = 0; probenum < listsz && !goodone; probenum++) {
  4336. probeI--;
  4337. probe = *probeI;
  4338. if (probe->protocol() != encaps_hdr.proto ||
  4339. sockaddr_storage_cmp(&target_src, &encaps_hdr.src) != 0 ||
  4340. sockaddr_storage_cmp(&target_dst, &encaps_hdr.dst) != 0)
  4341. continue;
  4342. if (encaps_hdr.proto == IPPROTO_TCP && !USI->prot_scan) {
  4343. struct tcp_hdr *tcp = (struct tcp_hdr *) encaps_data;
  4344. if (ntohs(tcp->th_sport) != probe->sport() ||
  4345. ntohs(tcp->th_dport) != probe->dport() ||
  4346. ntohl(tcp->th_seq) != probe->tcpseq())
  4347. continue;
  4348. } else if (encaps_hdr.proto == IPPROTO_SCTP && !USI->prot_scan) {
  4349. struct sctp_hdr *sctp = (struct sctp_hdr *) encaps_data;
  4350. if (ntohs(sctp->sh_sport) != probe->sport() ||
  4351. ntohs(sctp->sh_dport) != probe->dport() ||
  4352. ntohl(sctp->sh_vtag) != probe->sctpvtag())
  4353. continue;
  4354. } else if (encaps_hdr.proto == IPPROTO_UDP && !USI->prot_scan) {
  4355. /* TODO: IPID verification */
  4356. struct udp_hdr *udp = (struct udp_hdr *) encaps_data;
  4357. if (ntohs(udp->uh_sport) != probe->sport() ||
  4358. ntohs(udp->uh_dport) != probe->dport())
  4359. continue;
  4360. } else if (!USI->prot_scan) {
  4361. assert(0);
  4362. }
  4363. if (icmpv6->icmpv6_type == ICMPV6_UNREACH) {
  4364. switch (icmpv6->icmpv6_code) {
  4365. case ICMPV6_UNREACH_NOROUTE:
  4366. current_reason = ER_NOROUTE;
  4367. newstate = PORT_FILTERED;
  4368. break;
  4369. case ICMPV6_UNREACH_PROHIB:
  4370. current_reason = ER_ADMINPROHIBITED;
  4371. newstate = PORT_FILTERED;
  4372. break;
  4373. case ICMPV6_UNREACH_SCOPE:
  4374. current_reason = ER_BEYONDSCOPE;
  4375. newstate = PORT_FILTERED;
  4376. break;
  4377. case ICMPV6_UNREACH_ADDR:
  4378. current_reason = ER_HOSTUNREACH;
  4379. newstate = PORT_FILTERED;
  4380. break;
  4381. case ICMPV6_UNREACH_FILTER_PROHIB:
  4382. current_reason = ER_ADMINPROHIBITED;
  4383. newstate = PORT_FILTERED;
  4384. break;
  4385. case ICMPV6_UNREACH_REJECT_ROUTE:
  4386. current_reason = ER_REJECTROUTE;
  4387. newstate = PORT_FILTERED;
  4388. break;
  4389. case ICMPV6_UNREACH_PORT:
  4390. current_reason = ER_PORTUNREACH;
  4391. if (USI->scantype == UDP_SCAN &&
  4392. sockaddr_storage_cmp(&target_dst, &hdr.src) == 0)
  4393. newstate = PORT_CLOSED;
  4394. else if (USI->scantype == IPPROT_SCAN &&
  4395. sockaddr_storage_cmp(&target_dst, &hdr.src) == 0)
  4396. newstate = PORT_OPEN;
  4397. else
  4398. newstate = PORT_FILTERED;
  4399. break;
  4400. default:
  4401. error("Unexpected ICMPv6 type/code %d/%d unreachable packet:\n",
  4402. icmpv6->icmpv6_type, icmpv6->icmpv6_code);
  4403. nmap_hexdump((unsigned char *)icmpv6, datalen);
  4404. break;
  4405. }
  4406. } else if (icmpv6->icmpv6_type == ICMPV6_PARAMPROBLEM) {
  4407. switch (icmpv6->icmpv6_code) {
  4408. case ICMPV6_PARAMPROBLEM_FIELD:
  4409. /* "Erroneous header field encountered" means it was understood,
  4410. just invalid. */
  4411. newstate = PORT_OPEN;
  4412. break;
  4413. case ICMPV6_PARAMPROBLEM_NEXTHEADER:
  4414. if (USI->scantype == IPPROT_SCAN &&
  4415. sockaddr_storage_cmp(&target_dst, &hdr.src) == 0) {
  4416. newstate = PORT_CLOSED;
  4417. } else {
  4418. newstate = PORT_FILTERED;
  4419. }
  4420. break;
  4421. default:
  4422. error("Unexpected ICMPv6 type/code %d/%d unreachable packet:\n",
  4423. icmpv6->icmpv6_type, icmpv6->icmpv6_code);
  4424. nmap_hexdump((unsigned char *)icmpv6, datalen);
  4425. break;
  4426. }
  4427. } else {
  4428. error("Unexpected ICMPv6 type/code %d/%d unreachable packet:\n",
  4429. icmpv6->icmpv6_type, icmpv6->icmpv6_code);
  4430. nmap_hexdump((unsigned char *)icmpv6, datalen);
  4431. break;
  4432. }
  4433. current_reason = icmp_to_reason(hdr.proto, icmpv6->icmpv6_type, icmpv6->icmpv6_code);
  4434. if (newstate == PORT_UNKNOWN)
  4435. break;
  4436. goodone = true;
  4437. }
  4438. } else if (hdr.proto == IPPROTO_UDP && !USI->prot_scan) {
  4439. struct udp_hdr *udp = (struct udp_hdr *) data;
  4440. /* Search for this host on the incomplete list */
  4441. hss = USI->findHost(&hdr.src);
  4442. if (!hss)
  4443. continue; // Not from a host that interests us
  4444. probeI = hss->probes_outstanding.end();
  4445. listsz = hss->num_probes_outstanding();
  4446. ss_len = sizeof(target_src);
  4447. hss->target->SourceSockAddr(&target_src, &ss_len);
  4448. goodone = false;
  4449. for (probenum = 0; probenum < listsz && !goodone; probenum++) {
  4450. probeI--;
  4451. probe = *probeI;
  4452. newstate = PORT_UNKNOWN;
  4453. if (probe->protocol() != IPPROTO_UDP)
  4454. continue;
  4455. /* Ensure the connection info matches. */
  4456. if (probe->dport() != ntohs(udp->uh_sport) ||
  4457. probe->sport() != ntohs(udp->uh_dport) ||
  4458. sockaddr_storage_cmp(&target_src, &hdr.dst) != 0)
  4459. continue;
  4460. /* Sometimes we get false results when scanning localhost with
  4461. -p- because we scan localhost with src port = dst port and
  4462. see our outgoing packet and think it is a response. */
  4463. if (probe->dport() == probe->sport() &&
  4464. sockaddr_storage_cmp(&hdr.src, &hdr.dst) == 0 &&
  4465. probe->ipid() == hdr.ipid)
  4466. continue; /* We saw the packet we ourselves sent */
  4467. newstate = PORT_OPEN;
  4468. current_reason = ER_UDPRESPONSE;
  4469. goodone = true;
  4470. }
  4471. } else continue; /* Unexpected protocol */
  4472. } while (!goodone && !timedout);
  4473. if (goodone) {
  4474. struct sockaddr_storage target_dst;
  4475. size_t ss_len;
  4476. ss_len = sizeof(target_dst);
  4477. hss->target->TargetSockAddr(&target_dst, &ss_len);
  4478. if (sockaddr_storage_cmp(&hdr.src, &target_dst) == 0)
  4479. reason_sip.ss_family = AF_UNSPEC;
  4480. else
  4481. reason_sip = hdr.src;
  4482. if (probe->isPing())
  4483. ultrascan_ping_update(USI, hss, probeI, &rcvdtime, adjust_timing);
  4484. else {
  4485. /* Save these values so we can use them after ultrascan_port_probe_update
  4486. deletes probe. */
  4487. u8 protocol = probe->protocol();
  4488. u16 dport = probe->dport();
  4489. ultrascan_port_probe_update(USI, hss, probeI, newstate, &rcvdtime, adjust_timing);
  4490. if (USI->prot_scan)
  4491. hss->target->ports.setStateReason(protocol, IPPROTO_IP,
  4492. current_reason, hdr.ttl, &reason_sip);
  4493. else
  4494. hss->target->ports.setStateReason(dport, protocol,
  4495. current_reason, hdr.ttl, &reason_sip);
  4496. }
  4497. }
  4498. /* If protoicmphack is true, we are doing an IP proto scan and
  4499. discovered that ICMP is open. This has to be done separately
  4500. because an ICMP response ALSO frequently shows that some other
  4501. protocol is closed/filtered. So we let that other protocol stuff
  4502. go first, then handle it here */
  4503. if (protoscanicmphack) {
  4504. hss = USI->findHost((struct sockaddr_storage *) &protoscanicmphackaddy);
  4505. if (hss) {
  4506. probeI = hss->probes_outstanding.end();
  4507. listsz = hss->num_probes_outstanding();
  4508. for (probenum = 0; probenum < listsz; probenum++) {
  4509. probeI--;
  4510. probe = *probeI;
  4511. if (probe->protocol() == IPPROTO_ICMP) {
  4512. if (probe->isPing())
  4513. ultrascan_ping_update(USI, hss, probeI, &rcvdtime, adjust_timing);
  4514. else {
  4515. struct icmp *icmp = (struct icmp *) data;
  4516. ultrascan_port_probe_update(USI, hss, probeI, PORT_OPEN, &rcvdtime, adjust_timing);
  4517. if (sockaddr_storage_cmp(&hdr.src, &protoscanicmphackaddy) == 0)
  4518. reason_sip.ss_family = AF_UNSPEC;
  4519. else
  4520. reason_sip = hdr.src;
  4521. if (!icmp->icmp_code && !icmp->icmp_type)
  4522. hss->target->ports.setStateReason(IPPROTO_ICMP, IPPROTO_IP, ER_ECHOREPLY,
  4523. hdr.ttl, &reason_sip);
  4524. else
  4525. hss->target->ports.setStateReason(IPPROTO_ICMP, IPPROTO_IP, icmp_to_reason(hdr.proto, icmp->icmp_type, icmp->icmp_code),
  4526. hdr.ttl, &reason_sip);
  4527. }
  4528. if (!goodone)
  4529. goodone = true;
  4530. break;
  4531. }
  4532. }
  4533. protoscanicmphack = false;
  4534. }
  4535. }
  4536. return goodone;
  4537. }
  4538. /* Tries to get one *good* (finishes a probe) pcap response to a host discovery
  4539. (ping) probe by the (absolute) time given in stime. Even if stime is now,
  4540. try an ultra-quick pcap read just in case. Returns true if a "good" result
  4541. was found, false if it timed out instead. */
  4542. static int get_ping_pcap_result(UltraScanInfo *USI, struct timeval *stime) {
  4543. bool goodone = false;
  4544. bool timedout = false;
  4545. bool adjust_timing = true;
  4546. struct timeval rcvdtime;
  4547. struct link_header linkhdr;
  4548. struct ip *ip_tmp;
  4549. unsigned int bytes;
  4550. struct ppkt *ping;
  4551. long to_usec;
  4552. HostScanStats *hss = NULL;
  4553. std::list<UltraProbe *>::iterator probeI;
  4554. UltraProbe *probe = NULL;
  4555. unsigned int trynum = 0;
  4556. int newstate = HOST_UNKNOWN;
  4557. unsigned int probenum;
  4558. unsigned int listsz;
  4559. reason_t current_reason = ER_NORESPONSE;
  4560. struct sockaddr_storage target_src, target_dst;
  4561. size_t ss_len;
  4562. const void *data = NULL;
  4563. unsigned int datalen;
  4564. struct abstract_ip_hdr hdr;
  4565. do {
  4566. to_usec = TIMEVAL_SUBTRACT(*stime, USI->now);
  4567. if (to_usec < 2000)
  4568. to_usec = 2000;
  4569. ip_tmp = (struct ip *) readip_pcap(USI->pd, &bytes, to_usec, &rcvdtime,
  4570. &linkhdr, true);
  4571. gettimeofday(&USI->now, NULL);
  4572. if (!ip_tmp) {
  4573. if (TIMEVAL_SUBTRACT(*stime, USI->now) < 0) {
  4574. timedout = true;
  4575. break;
  4576. } else {
  4577. continue;
  4578. }
  4579. }
  4580. if (TIMEVAL_SUBTRACT(USI->now, *stime) > 200000) {
  4581. /* While packets are still being received, I'll be generous and give
  4582. an extra 1/5 sec. But we have to draw the line somewhere */
  4583. timedout = true;
  4584. }
  4585. /* OK, we got a packet. Most packet validity tests are taken care
  4586. * of in readip_pcap, so this is simple
  4587. */
  4588. datalen = bytes;
  4589. data = ip_get_data(ip_tmp, &datalen, &hdr);
  4590. if (data == NULL)
  4591. continue;
  4592. /* First check if it is ICMP, TCP, or UDP */
  4593. if (hdr.proto == IPPROTO_ICMP || hdr.proto == IPPROTO_ICMPV6) {
  4594. /* if it is our response */
  4595. ping = (struct ppkt *) data;
  4596. if (bytes < 8U) {
  4597. if (!ip_tmp->ip_off)
  4598. error("Supposed ping packet is only %d bytes long!", bytes);
  4599. continue;
  4600. }
  4601. current_reason = icmp_to_reason(hdr.proto, ping->type, ping->code);
  4602. /* Echo reply, Timestamp reply, or Address Mask Reply. RFCs 792 and 950. */
  4603. /* ICMPv6 Echo reply */
  4604. if (USI->ptech.rawicmpscan
  4605. && ((hdr.proto == IPPROTO_ICMP && (ping->type == 0 || ping->type == 14 || ping->type == 18))
  4606. || (hdr.proto == IPPROTO_ICMPV6 && ping->type == 129))) {
  4607. hss = USI->findHost(&hdr.src);
  4608. if (!hss)
  4609. continue; // Not from a host that interests us
  4610. setTargetMACIfAvailable(hss->target, &linkhdr, &hdr.src, 0);
  4611. probeI = hss->probes_outstanding.end();
  4612. listsz = hss->num_probes_outstanding();
  4613. ss_len = sizeof(target_src);
  4614. hss->target->SourceSockAddr(&target_src, &ss_len);
  4615. /* A check for weird_responses is needed here. This is not currently
  4616. possible because we don't have a good way to look up the original
  4617. target of an ICMP probe based on the response. (massping encoded an
  4618. array index in the ICMP sequence, which won't work here.) Once we've
  4619. found the host that sent the probe that elicited the response, the
  4620. test for weird_responses is
  4621. if (sending_host->v4host().s_addr != ip->ip_src.s_addr)
  4622. hss->target->weird_responses++;
  4623. (That is, the target that sent the probe is not the same one that
  4624. sent the response.)
  4625. */
  4626. goodone = false;
  4627. /* Find the probe that provoked this response. */
  4628. for (probenum = 0; probenum < listsz && !goodone; probenum++) {
  4629. probeI--;
  4630. probe = *probeI;
  4631. if (!icmp_probe_match(USI, probe, ping, &target_src, &hdr.src, &hdr.dst, hdr.proto, hdr.ipid))
  4632. continue;
  4633. goodone = true;
  4634. newstate = HOST_UP;
  4635. if (o.debugging)
  4636. log_write(LOG_STDOUT, "We got a ping packet back from %s: id = %d seq = %d checksum = %d\n", inet_ntop_ez(&hdr.src, sizeof(hdr.src)), ping->id, ping->seq, ping->checksum);
  4637. }
  4638. }
  4639. // For ICMP, the reply of TCP/UDP/ICMP packets can be Destination unreachable, source quench, or time exceeded
  4640. /* For ICMPv6, the reply of TCP/UDP/ICMPV6 packets can be Destination Unreachable,
  4641. * Packet Too Big, Time Exceeded and Parameter Problem.*/
  4642. else if ((hdr.proto == IPPROTO_ICMP && (ping->type == 3 || ping->type
  4643. == 4 || ping->type == 11))
  4644. || (hdr.proto == IPPROTO_ICMPV6 && (ping->type == 1 || ping->type == 2
  4645. || ping->type == 3 || ping->type == 4))) {
  4646. const void *encaps_data;
  4647. unsigned int encaps_len;
  4648. struct abstract_ip_hdr encaps_hdr;
  4649. if (datalen < 8)
  4650. continue;
  4651. encaps_len = datalen - 8;
  4652. encaps_data = ip_get_data((char *) data + 8, &encaps_len, &encaps_hdr);
  4653. if (encaps_data == NULL ||
  4654. /* UDP hdr, or TCP hdr up to seq #, or SCTP hdr up to vtag */
  4655. ((USI->tcp_scan || USI->udp_scan || USI->sctp_scan) && encaps_len < 8)
  4656. /* prot scan has no headers coming back, so we don't reserve the
  4657. 8 xtra bytes */
  4658. ) {
  4659. if (o.debugging)
  4660. error("Received short ICMP or ICMPv6 packet (%u bytes)", datalen);
  4661. continue;
  4662. }
  4663. /* Bail out early if possible. */
  4664. if (!USI->ptech.rawprotoscan) {
  4665. if (encaps_hdr.proto == IPPROTO_ICMP && !USI->ptech.rawicmpscan)
  4666. continue;
  4667. if (encaps_hdr.proto == IPPROTO_ICMPV6 && !USI->ptech.rawicmpscan)
  4668. continue;
  4669. if (encaps_hdr.proto == IPPROTO_TCP && !USI->ptech.rawtcpscan)
  4670. continue;
  4671. if (encaps_hdr.proto == IPPROTO_UDP && !USI->ptech.rawudpscan)
  4672. continue;
  4673. if (encaps_hdr.proto == IPPROTO_SCTP && !USI->ptech.rawsctpscan)
  4674. continue;
  4675. }
  4676. hss = USI->findHost(&encaps_hdr.dst);
  4677. if (!hss)
  4678. continue; // Not referring to a host that interests us
  4679. setTargetMACIfAvailable(hss->target, &linkhdr, &encaps_hdr.dst, 0);
  4680. probeI = hss->probes_outstanding.end();
  4681. listsz = hss->num_probes_outstanding();
  4682. ss_len = sizeof(target_src);
  4683. hss->target->SourceSockAddr(&target_src, &ss_len);
  4684. ss_len = sizeof(target_dst);
  4685. hss->target->TargetSockAddr(&target_dst, &ss_len);
  4686. /* Find the probe that provoked this response. */
  4687. for (probenum = 0; probenum < listsz; probenum++) {
  4688. probeI--;
  4689. probe = *probeI;
  4690. if (probe->protocol() != encaps_hdr.proto ||
  4691. sockaddr_storage_cmp(&target_src, &hdr.dst) != 0 ||
  4692. sockaddr_storage_cmp(&target_src, &encaps_hdr.src) != 0 ||
  4693. sockaddr_storage_cmp(&target_dst, &encaps_hdr.dst) != 0)
  4694. continue;
  4695. if ((encaps_hdr.proto == IPPROTO_ICMP || encaps_hdr.proto == IPPROTO_ICMPV6)
  4696. && USI->ptech.rawicmpscan) {
  4697. /* The response was based on a ping packet we sent */
  4698. } else if (encaps_hdr.proto == IPPROTO_TCP && USI->ptech.rawtcpscan) {
  4699. struct tcp_hdr *tcp = (struct tcp_hdr *) encaps_data;
  4700. if (probe->dport() != ntohs(tcp->th_dport) ||
  4701. probe->sport() != ntohs(tcp->th_sport) ||
  4702. probe->tcpseq() != ntohl(tcp->th_seq))
  4703. continue;
  4704. } else if (encaps_hdr.proto == IPPROTO_UDP && USI->ptech.rawudpscan) {
  4705. struct udp_hdr *udp = (struct udp_hdr *) encaps_data;
  4706. if (probe->dport() != ntohs(udp->uh_dport) ||
  4707. probe->sport() != ntohs(udp->uh_sport))
  4708. continue;
  4709. } else if (encaps_hdr.proto == IPPROTO_SCTP && USI->ptech.rawsctpscan) {
  4710. struct sctp_hdr *sctp = (struct sctp_hdr *) encaps_data;
  4711. if (probe->dport() != ntohs(sctp->sh_dport) ||
  4712. probe->sport() != ntohs(sctp->sh_sport) ||
  4713. probe->sctpvtag() != ntohl(sctp->sh_vtag))
  4714. continue;
  4715. } else if (USI->ptech.rawprotoscan) {
  4716. /* Success; we already know that the address and protocol match. */
  4717. } else {
  4718. assert(0);
  4719. }
  4720. /* If we made it this far, we found it. We don't yet know if it's
  4721. going to change a host state (goodone) or not. */
  4722. break;
  4723. }
  4724. /* Did we fail to find a probe? */
  4725. if (probenum >= listsz)
  4726. continue;
  4727. if ((hdr.proto == IPPROTO_ICMP && ping->type == 3)
  4728. || (hdr.proto == IPPROTO_ICMPV6 && ping->type == 1)) {
  4729. /* Destination unreachable. */
  4730. if (sockaddr_storage_cmp(&target_dst, &hdr.src) == 0) {
  4731. /* The ICMP or ICMPv6 error came directly from the target, so it's up. */
  4732. goodone = true;
  4733. newstate = HOST_UP;
  4734. } else {
  4735. goodone = true;
  4736. newstate = HOST_DOWN;
  4737. }
  4738. if (o.debugging) {
  4739. if ((hdr.proto == IPPROTO_ICMP && ping->code == 3)
  4740. || (hdr.proto == IPPROTO_ICMPV6 && ping->code == 4))
  4741. log_write(LOG_STDOUT, "Got port unreachable for %s\n", hss->target->targetipstr());
  4742. else
  4743. log_write(LOG_STDOUT, "Got destination unreachable for %s\n", hss->target->targetipstr());
  4744. }
  4745. } else if ((hdr.proto == IPPROTO_ICMP && ping->type == 11)
  4746. || (hdr.proto == IPPROTO_ICMPV6 && ping->type == 3)) {
  4747. if (o.debugging)
  4748. log_write(LOG_STDOUT, "Got Time Exceeded for %s\n", hss->target->targetipstr());
  4749. goodone = 1;
  4750. newstate = HOST_DOWN;
  4751. /* I don't want anything to do with timing this. */
  4752. adjust_timing = false;
  4753. } else if (hdr.proto == IPPROTO_ICMP && ping->type == 4) {
  4754. if (o.debugging)
  4755. log_write(LOG_STDOUT, "Got ICMP source quench\n");
  4756. usleep(50000);
  4757. } else if (hdr.proto == IPPROTO_ICMPV6 && ping->type == 4) {
  4758. if (o.debugging)
  4759. log_write(LOG_STDOUT, "Got ICMPv6 Parameter Problem\n");
  4760. } else if (hdr.proto == IPPROTO_ICMP) {
  4761. if (o.debugging) {
  4762. log_write(LOG_STDOUT, "Got ICMP message type %d code %d\n",
  4763. ping->type, ping->code);
  4764. }
  4765. } else if (hdr.proto == IPPROTO_ICMPV6) {
  4766. if (o.debugging)
  4767. log_write(LOG_STDOUT, "Got ICMPv6 message type %d code %d\n",
  4768. ping->type, ping->code);
  4769. }
  4770. }
  4771. } else if (hdr.proto == IPPROTO_TCP && USI->ptech.rawtcpscan) {
  4772. struct tcp_hdr *tcp = (struct tcp_hdr *) data;
  4773. /* Check that the packet has useful flags. */
  4774. if (!(tcp->th_flags & TH_RST)
  4775. && ((tcp->th_flags & (TH_SYN | TH_ACK)) != (TH_SYN | TH_ACK)))
  4776. continue;
  4777. /* Now ensure this host is even in the incomplete list */
  4778. hss = USI->findHost(&hdr.src);
  4779. if (!hss)
  4780. continue; // Not from a host that interests us
  4781. setTargetMACIfAvailable(hss->target, &linkhdr, &hdr.src, 0);
  4782. probeI = hss->probes_outstanding.end();
  4783. listsz = hss->num_probes_outstanding();
  4784. goodone = false;
  4785. /* Find the probe that provoked this response. */
  4786. for (probenum = 0; probenum < listsz && !goodone; probenum++) {
  4787. probeI--;
  4788. probe = *probeI;
  4789. if (!tcp_probe_match(USI, probe, hss, tcp, &hdr.src, &hdr.dst, hdr.ipid))
  4790. continue;
  4791. goodone = true;
  4792. newstate = HOST_UP;
  4793. /* Fill out the reason. */
  4794. if (o.pingtype & PINGTYPE_TCP_USE_SYN) {
  4795. if (tcp->th_flags & TH_RST) {
  4796. current_reason = ER_RESETPEER;
  4797. } else if ((tcp->th_flags & (TH_SYN | TH_ACK)) == (TH_SYN | TH_ACK)) {
  4798. current_reason = ER_SYNACK;
  4799. }
  4800. } else if (o.pingtype & PINGTYPE_TCP_USE_ACK) {
  4801. if (tcp->th_flags & TH_RST)
  4802. current_reason = ER_RESETPEER;
  4803. }
  4804. if (o.debugging)
  4805. log_write(LOG_STDOUT, "We got a TCP ping packet back from %s port %hu (trynum = %d)\n", inet_ntop_ez(&hdr.src, sizeof(hdr.src)), ntohs(tcp->th_sport), trynum);
  4806. }
  4807. } else if (hdr.proto == IPPROTO_UDP && USI->ptech.rawudpscan) {
  4808. struct udp_hdr *udp = (struct udp_hdr *) data;
  4809. /* Search for this host on the incomplete list */
  4810. hss = USI->findHost(&hdr.src);
  4811. if (!hss)
  4812. continue; // Not from a host that interests us
  4813. probeI = hss->probes_outstanding.end();
  4814. listsz = hss->num_probes_outstanding();
  4815. goodone = false;
  4816. ss_len = sizeof(target_src);
  4817. hss->target->SourceSockAddr(&target_src, &ss_len);
  4818. for (probenum = 0; probenum < listsz && !goodone; probenum++) {
  4819. probeI--;
  4820. probe = *probeI;
  4821. if (o.af() != AF_INET || probe->protocol() != IPPROTO_UDP)
  4822. continue;
  4823. /* Ensure the connection info matches. */
  4824. if (probe->dport() != ntohs(udp->uh_sport) ||
  4825. probe->sport() != ntohs(udp->uh_dport) ||
  4826. sockaddr_storage_cmp(&target_src, &hdr.dst) != 0)
  4827. continue;
  4828. /* Replace this with a call to probe_check_trynum_pingseq or similar. */
  4829. if (o.magic_port_set) {
  4830. trynum = probe->tryno;
  4831. } else {
  4832. sport_decode(USI, base_port, ntohs(udp->uh_dport), &trynum, NULL);
  4833. }
  4834. /* Sometimes we get false results when scanning localhost with
  4835. -p- because we scan localhost with src port = dst port and
  4836. see our outgoing packet and think it is a response. */
  4837. if (probe->dport() == probe->sport() &&
  4838. sockaddr_storage_cmp(&hdr.src, &hdr.dst) == 0 &&
  4839. probe->ipid() == hdr.ipid)
  4840. continue; /* We saw the packet we ourselves sent */
  4841. goodone = true;
  4842. newstate = HOST_UP;
  4843. current_reason = ER_UDPRESPONSE;
  4844. if (o.debugging)
  4845. log_write(LOG_STDOUT, "In response to UDP-ping, we got UDP packet back from %s port %hu (trynum = %d)\n", inet_ntop_ez(&hdr.src, sizeof(hdr.src)), htons(udp->uh_sport), trynum);
  4846. }
  4847. } else if (hdr.proto == IPPROTO_SCTP && USI->ptech.rawsctpscan) {
  4848. struct sctp_hdr *sctp = (struct sctp_hdr *) data;
  4849. struct dnet_sctp_chunkhdr *chunk =
  4850. (struct dnet_sctp_chunkhdr *) ((u8 *) sctp + 12);
  4851. /* Search for this host on the incomplete list */
  4852. hss = USI->findHost(&hdr.src);
  4853. if (!hss)
  4854. continue; // Not from a host that interests us
  4855. probeI = hss->probes_outstanding.end();
  4856. listsz = hss->num_probes_outstanding();
  4857. goodone = false;
  4858. ss_len = sizeof(target_dst);
  4859. hss->target->SourceSockAddr(&target_src, &ss_len);
  4860. for (probenum = 0; probenum < listsz && !goodone; probenum++) {
  4861. probeI--;
  4862. probe = *probeI;
  4863. if (o.af() != AF_INET || probe->protocol() != IPPROTO_SCTP)
  4864. continue;
  4865. /* Ensure the connection info matches. */
  4866. if (probe->dport() != ntohs(sctp->sh_sport) ||
  4867. probe->sport() != ntohs(sctp->sh_dport) ||
  4868. sockaddr_storage_cmp(&target_src, &hdr.dst) != 0)
  4869. continue;
  4870. /* Sometimes we get false results when scanning localhost with
  4871. -p- because we scan localhost with src port = dst port and
  4872. see our outgoing packet and think it is a response. */
  4873. if (probe->dport() == probe->sport() &&
  4874. sockaddr_storage_cmp(&hdr.src, &hdr.dst) == 0 &&
  4875. probe->ipid() == hdr.ipid)
  4876. continue; /* We saw the packet we ourselves sent */
  4877. goodone = true;
  4878. newstate = HOST_UP;
  4879. if (chunk->sch_type == SCTP_INIT_ACK) {
  4880. current_reason = ER_INITACK;
  4881. } else if (chunk->sch_type == SCTP_ABORT) {
  4882. current_reason = ER_ABORT;
  4883. } else {
  4884. current_reason = ER_UNKNOWN;
  4885. if (o.debugging)
  4886. log_write(LOG_STDOUT, "Received scan response with unexpected SCTP chunks: n/a");
  4887. }
  4888. }
  4889. } else if (!USI->ptech.rawprotoscan) {
  4890. if (o.debugging > 2)
  4891. error("Received packet with protocol %d; ignoring.", hdr.proto);
  4892. }
  4893. /* Check for a protocol reply */
  4894. if (!goodone && USI->ptech.rawprotoscan) {
  4895. hss = USI->findHost(&hdr.src);
  4896. if (!hss)
  4897. continue;
  4898. setTargetMACIfAvailable(hss->target, &linkhdr, &hdr.src, 0);
  4899. probeI = hss->probes_outstanding.end();
  4900. listsz = hss->num_probes_outstanding();
  4901. goodone = false;
  4902. for (probenum = 0; probenum < listsz && !goodone; probenum++) {
  4903. probeI--;
  4904. probe = *probeI;
  4905. if (probe->protocol() == hdr.proto) {
  4906. /* if this is our probe we sent to localhost, then it doesn't count! */
  4907. if (sockaddr_storage_cmp(&hdr.src, &hdr.dst) == 0 &&
  4908. probe->ipid() == hdr.ipid)
  4909. break;
  4910. newstate = HOST_UP;
  4911. current_reason = ER_PROTORESPONSE;
  4912. goodone = true;
  4913. }
  4914. }
  4915. }
  4916. } while (!goodone && !timedout);
  4917. if (goodone && newstate != HOST_UNKNOWN) {
  4918. struct sockaddr_storage target_dst;
  4919. size_t ss_len;
  4920. ss_len = sizeof(target_dst);
  4921. hss->target->TargetSockAddr(&target_dst, &ss_len);
  4922. if (probe->isPing())
  4923. ultrascan_ping_update(USI, hss, probeI, &USI->now, adjust_timing);
  4924. else {
  4925. ultrascan_host_probe_update(USI, hss, probeI, newstate, &rcvdtime, adjust_timing);
  4926. /* If the host is up, we can forget our other probes. */
  4927. if (newstate == HOST_UP)
  4928. hss->destroyAllOutstandingProbes();
  4929. if (newstate == HOST_UP && data)
  4930. setTargetMACIfAvailable(hss->target, &linkhdr, &hdr.src, 0);
  4931. hss->target->reason.reason_id = current_reason;
  4932. hss->target->reason.ttl = hdr.ttl;
  4933. if (sockaddr_storage_cmp(&hdr.src, &target_dst) != 0) {
  4934. hss->target->reason.set_ip_addr(&hdr.src);
  4935. }
  4936. }
  4937. }
  4938. return 0;
  4939. }
  4940. static void waitForResponses(UltraScanInfo *USI) {
  4941. struct timeval stime;
  4942. bool gotone;
  4943. gettimeofday(&USI->now, NULL);
  4944. USI->gstats->last_wait = USI->now;
  4945. USI->gstats->probes_sent_at_last_wait = USI->gstats->probes_sent;
  4946. do {
  4947. gotone = false;
  4948. USI->sendOK(&stime);
  4949. if (USI->ping_scan_arp) {
  4950. gotone = get_arp_result(USI, &stime);
  4951. } else if (USI->ping_scan_nd) {
  4952. gotone = get_ns_result(USI, &stime);
  4953. } else if (USI->ping_scan) {
  4954. if (USI->pd)
  4955. gotone = get_ping_pcap_result(USI, &stime);
  4956. if (!gotone && USI->ptech.connecttcpscan)
  4957. gotone = do_one_select_round(USI, &stime);
  4958. } else if (USI->pd) {
  4959. gotone = get_pcap_result(USI, &stime);
  4960. } else if (USI->scantype == CONNECT_SCAN) {
  4961. gotone = do_one_select_round(USI, &stime);
  4962. } else assert(0);
  4963. } while (gotone && USI->gstats->num_probes_active > 0);
  4964. gettimeofday(&USI->now, NULL);
  4965. USI->gstats->last_wait = USI->now;
  4966. }
  4967. /* Initiate libpcap or some other sniffer as appropriate to be able to catch
  4968. responses */
  4969. static void begin_sniffer(UltraScanInfo *USI, std::vector<Target *> &Targets) {
  4970. std::string pcap_filter = "";
  4971. /* 20 IPv6 addresses is max (45 byte addy + 14 (" or src host ")) * 20 == 1180 */
  4972. std::string dst_hosts = "";
  4973. unsigned int len = 0;
  4974. unsigned int targetno;
  4975. bool doIndividual = Targets.size() <= 20; // Don't bother IP limits if scanning huge # of hosts
  4976. if (!USI->isRawScan())
  4977. return; /* No sniffer needed! */
  4978. if (doIndividual) {
  4979. for (targetno = 0; targetno < Targets.size(); targetno++) {
  4980. dst_hosts += (targetno == 0) ? "" : " or ";
  4981. dst_hosts += "src host ";
  4982. dst_hosts += Targets[targetno]->targetipstr();
  4983. }
  4984. }
  4985. if ((USI->pd = my_pcap_open_live(Targets[0]->deviceName(), 256, (o.spoofsource) ? 1 : 0, pcap_selectable_fd_valid() ? 200 : 2)) == NULL)
  4986. fatal("%s", PCAP_OPEN_ERRMSG);
  4987. if (USI->ping_scan_arp) {
  4988. /* Some OSs including Windows 7 and Solaris 10 have been seen to send their
  4989. ARP replies to the broadcast address, not to the (unicast) address that
  4990. the request came from, therefore listening for ARP packets directed to
  4991. us is not enough. Look inside the ARP reply at the target address field
  4992. instead. The filter string will look like
  4993. arp and arp[18:4] = 0xAABBCCDD and arp[22:2] = 0xEEFF */
  4994. char macstring[2 * ETH_ADDR_LEN + 1];
  4995. const u8 *mac = Targets[0]->SrcMACAddress();
  4996. assert(mac);
  4997. len = Snprintf(macstring, sizeof(macstring), "%02X%02X%02X%02X%02X%02X",
  4998. mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);
  4999. if (len != sizeof(macstring) - 1)
  5000. fatal("macstring length is %d, should be %u", len, (unsigned)(sizeof(macstring) - 1));
  5001. /* First four bytes of MAC. */
  5002. pcap_filter = "arp and arp[18:4] = 0x";
  5003. pcap_filter.append(macstring, 0, 4 * 2);
  5004. /* Last two bytes. */
  5005. pcap_filter += " and arp[22:2] = 0x";
  5006. pcap_filter.append(macstring, 4 * 2, 2 * 2);
  5007. //its not arp, so lets check if for a protocol scan.
  5008. } else if (USI->ping_scan_nd) {
  5009. /* Libpcap: IPv6 upper-layer protocol is not supported by proto[x] */
  5010. /* Grab the ICMPv6 type using ip6[X:Y] syntax. This works only if there are no
  5011. extension headers (top-level nh is IPPROTO_ICMPV6). */
  5012. const u8 *srcmac = Targets[0]->SrcMACAddress();
  5013. assert(srcmac);
  5014. char filterstr[256];
  5015. Snprintf(filterstr, 256, "icmp6 and ip6[6:1] = %u and ip6[40:1] = %u",
  5016. IPPROTO_ICMPV6, ICMPV6_NEIGHBOR_ADVERTISEMENT);
  5017. pcap_filter.append(filterstr);
  5018. } else if (USI->prot_scan || (USI->ping_scan && USI->ptech.rawprotoscan)) {
  5019. struct sockaddr_storage source;
  5020. size_t source_len;
  5021. source_len = sizeof(source);
  5022. Targets[0]->SourceSockAddr(&source, &source_len);
  5023. if (doIndividual) {
  5024. pcap_filter = "dst host ";
  5025. pcap_filter += inet_ntop_ez(&source, sizeof(source));
  5026. pcap_filter += " and (icmp or icmp6 or (";
  5027. pcap_filter += dst_hosts;
  5028. pcap_filter += "))";
  5029. } else {
  5030. pcap_filter = "dst host ";
  5031. pcap_filter += inet_ntop_ez(&source, sizeof(source));
  5032. }
  5033. } else if (USI->tcp_scan || USI->udp_scan || USI->sctp_scan || USI->ping_scan) {
  5034. struct sockaddr_storage source;
  5035. size_t source_len;
  5036. source_len = sizeof(source);
  5037. Targets[0]->SourceSockAddr(&source, &source_len);
  5038. /* Handle udp, tcp and sctp with one filter. */
  5039. if (doIndividual) {
  5040. pcap_filter = "dst host ";
  5041. pcap_filter += inet_ntop_ez(&source, sizeof(source));
  5042. pcap_filter += " and (icmp or icmp6 or ((tcp or udp or sctp) and (";
  5043. pcap_filter += dst_hosts;
  5044. pcap_filter += ")))";
  5045. } else {
  5046. pcap_filter = "dst host ";
  5047. pcap_filter += inet_ntop_ez(&source, sizeof(source));
  5048. pcap_filter += " and (icmp or icmp6 or tcp or udp or sctp)";
  5049. }
  5050. } else {
  5051. assert(0);
  5052. }
  5053. if (o.debugging)
  5054. log_write(LOG_PLAIN, "Packet capture filter (device %s): %s\n", Targets[0]->deviceFullName(), pcap_filter.c_str());
  5055. set_pcap_filter(Targets[0]->deviceFullName(), USI->pd, pcap_filter.c_str());
  5056. /* pcap_setnonblock(USI->pd, 1, NULL); */
  5057. return;
  5058. }
  5059. /* Go through the data structures, making appropriate changes (such as expiring
  5060. probes, noting when hosts are complete, etc. */
  5061. static void processData(UltraScanInfo *USI) {
  5062. std::list<HostScanStats *>::iterator hostI;
  5063. std::list<UltraProbe *>::iterator probeI, nextProbeI;
  5064. HostScanStats *host = NULL;
  5065. UltraProbe *probe = NULL;
  5066. unsigned int maxtries = 0;
  5067. int expire_us = 0;
  5068. bool tryno_capped = false, tryno_mayincrease = false;
  5069. struct timeval tv_start = {0};
  5070. gettimeofday(&USI->now, NULL);
  5071. if (o.debugging)
  5072. tv_start = USI->now;
  5073. /* First go through hosts and remove any completed ones from incompleteHosts */
  5074. USI->removeCompletedHosts();
  5075. if (USI->incompleteHostsEmpty())
  5076. return;
  5077. /* Run through probe lists to:
  5078. 1) Mark timedout entries as such
  5079. 2) Remove long-expired and retransmitted entries
  5080. 3) Detect if we are done (we may just have a bunch of probes
  5081. sitting around waiting to see if another round of
  5082. retransmissions will be required).
  5083. */
  5084. for (hostI = USI->incompleteHosts.begin();
  5085. hostI != USI->incompleteHosts.end(); hostI++) {
  5086. host = *hostI;
  5087. /* Look for timedout or long expired entries */
  5088. maxtries = host->allowedTryno(&tryno_capped, &tryno_mayincrease);
  5089. /* Should we dump everyone off the bench? */
  5090. if (!host->probe_bench.empty()) {
  5091. if (maxtries == host->bench_tryno && !tryno_mayincrease) {
  5092. /* We'll never need to retransmit these suckers! So they can
  5093. be treated as done */
  5094. host->dismissBench();
  5095. } else if (maxtries > host->bench_tryno) {
  5096. // These fellows may be retransmitted now that maxtries has increased
  5097. host->retransmitBench();
  5098. }
  5099. }
  5100. for (probeI = host->probes_outstanding.begin();
  5101. probeI != host->probes_outstanding.end(); probeI = nextProbeI) {
  5102. nextProbeI = probeI;
  5103. nextProbeI++;
  5104. probe = *probeI;
  5105. // give up completely after this long
  5106. expire_us = host->probeExpireTime(probe);
  5107. if (!probe->timedout && TIMEVAL_SUBTRACT(USI->now, probe->sent) >
  5108. (long) host->probeTimeout()) {
  5109. host->markProbeTimedout(probeI);
  5110. /* Once we've timed out a probe, skip it for this round of processData.
  5111. We don't want it to move to the bench or anything until the other
  5112. functions have had a chance to see that it's timed out. In
  5113. particular, timing out a probe may mean that the tryno can no longer
  5114. increase, which would make the logic below incorrect. */
  5115. continue;
  5116. }
  5117. if (!probe->isPing() && probe->timedout && !probe->retransmitted) {
  5118. if (!tryno_mayincrease && probe->tryno >= maxtries) {
  5119. if (tryno_capped && !host->retry_capped_warned) {
  5120. log_write(LOG_PLAIN, "Warning: %s giving up on port because"
  5121. " retransmission cap hit (%d).\n", host->target->targetipstr(),
  5122. probe->tryno);
  5123. host->retry_capped_warned = true;
  5124. }
  5125. if (USI->ping_scan) {
  5126. ultrascan_host_probe_update(USI, host, probeI, HOST_DOWN, NULL);
  5127. if (host->target->reason.reason_id == ER_UNKNOWN)
  5128. host->target->reason.reason_id = ER_NORESPONSE;
  5129. } else {
  5130. /* No ultrascan_port_probe_update because that allocates a Port
  5131. object; the default port state as set by setDefaultPortState
  5132. handles these no-response ports. */
  5133. host->destroyOutstandingProbe(probeI);
  5134. }
  5135. continue;
  5136. } else if (probe->tryno >= maxtries &&
  5137. TIMEVAL_SUBTRACT(USI->now, probe->sent) > expire_us) {
  5138. assert(probe->tryno == maxtries);
  5139. /* Move it to the bench until it is needed (maxtries
  5140. increases or is capped */
  5141. host->moveProbeToBench(probeI);
  5142. continue;
  5143. }
  5144. }
  5145. if ((probe->isPing() || (probe->timedout && probe->retransmitted)) &&
  5146. TIMEVAL_SUBTRACT(USI->now, probe->sent) > expire_us) {
  5147. host->destroyOutstandingProbe(probeI);
  5148. continue;
  5149. }
  5150. }
  5151. }
  5152. /* In case any hosts were completed during this run */
  5153. USI->removeCompletedHosts();
  5154. /* Check for expired global pings. */
  5155. HostScanStats *pinghost = USI->gstats->pinghost;
  5156. if (pinghost != NULL) {
  5157. for (probeI = pinghost->probes_outstanding.begin();
  5158. probeI != pinghost->probes_outstanding.end();
  5159. probeI = nextProbeI) {
  5160. nextProbeI = probeI;
  5161. nextProbeI++;
  5162. /* If a global ping probe times out, we want to get rid of it so a new
  5163. host can take its place. */
  5164. if ((*probeI)->isPing()
  5165. && TIMEVAL_SUBTRACT(USI->now, (*probeI)->sent) > (long) pinghost->probeTimeout()) {
  5166. if (o.debugging)
  5167. log_write(LOG_STDOUT, "Destroying timed-out global ping from %s.\n", pinghost->target->targetipstr());
  5168. /* ultrascan_ping_update destroys the probe. */
  5169. ultrascan_ping_update(USI, pinghost, probeI, NULL);
  5170. }
  5171. }
  5172. }
  5173. gettimeofday(&USI->now, NULL);
  5174. if (o.debugging) {
  5175. long tv_diff = TIMEVAL_MSEC_SUBTRACT(USI->now, tv_start);
  5176. if (tv_diff > 30)
  5177. log_write(LOG_PLAIN, "%s took %lims\n", __func__, tv_diff);
  5178. }
  5179. }
  5180. /* Start the timeout clocks of any targets that aren't already timedout */
  5181. static void startTimeOutClocks(std::vector<Target *> &Targets) {
  5182. struct timeval tv;
  5183. std::vector<Target *>::iterator hostI;
  5184. gettimeofday(&tv, NULL);
  5185. for (hostI = Targets.begin(); hostI != Targets.end(); hostI++) {
  5186. if (!(*hostI)->timedOut(NULL))
  5187. (*hostI)->startTimeOutClock(&tv);
  5188. }
  5189. }
  5190. /* 3rd generation Nmap scanning function. Handles most Nmap port scan types.
  5191. The parameter to gives group timing information, and if it is not NULL,
  5192. changed timing information will be stored in it when the function returns. It
  5193. exists so timing can be shared across invocations of this function. If to is
  5194. NULL (its default value), a default timeout_info will be used. */
  5195. void ultra_scan(std::vector<Target *> &Targets, struct scan_lists *ports,
  5196. stype scantype, struct timeout_info *to) {
  5197. o.current_scantype = scantype;
  5198. increment_base_port();
  5199. init_payloads(); /* Load up _all_ payloads into a mapped table */
  5200. if (Targets.size() == 0) {
  5201. return;
  5202. }
  5203. #ifdef WIN32
  5204. if (scantype != CONNECT_SCAN && Targets[0]->ifType() == devt_loopback) {
  5205. log_write(LOG_STDOUT, "Skipping %s against %s because Windows does not support scanning your own machine (localhost) this way.\n", scantype2str(scantype), Targets[0]->NameIP());
  5206. return;
  5207. }
  5208. #endif
  5209. // Set the variable for status printing
  5210. o.numhosts_scanning = Targets.size();
  5211. startTimeOutClocks(Targets);
  5212. UltraScanInfo USI(Targets, ports, scantype);
  5213. /* Use the requested timeouts. */
  5214. if (to != NULL)
  5215. USI.gstats->to = *to;
  5216. if (o.verbose) {
  5217. char targetstr[128];
  5218. bool plural = (Targets.size() != 1);
  5219. if (!plural) {
  5220. (*(Targets.begin()))->NameIP(targetstr, sizeof(targetstr));
  5221. } else Snprintf(targetstr, sizeof(targetstr), "%d hosts", (int) Targets.size());
  5222. log_write(LOG_STDOUT, "Scanning %s [%d port%s%s]\n", targetstr, USI.gstats->numprobes, (USI.gstats->numprobes != 1) ? "s" : "", plural ? "/host" : "");
  5223. }
  5224. begin_sniffer(&USI, Targets);
  5225. while (!USI.incompleteHostsEmpty()) {
  5226. doAnyPings(&USI);
  5227. doAnyOutstandingRetransmits(&USI); // Retransmits from probes_outstanding
  5228. /* Retransmits from retry_stack -- goes after OutstandingRetransmits for
  5229. memory consumption reasons */
  5230. doAnyRetryStackRetransmits(&USI);
  5231. doAnyNewProbes(&USI);
  5232. gettimeofday(&USI.now, NULL);
  5233. // printf("TRACE: Finished doAnyNewProbes() at %.4fs\n", o.TimeSinceStartMS(&USI.now) / 1000.0);
  5234. printAnyStats(&USI);
  5235. waitForResponses(&USI);
  5236. gettimeofday(&USI.now, NULL);
  5237. // printf("TRACE: Finished waitForResponses() at %.4fs\n", o.TimeSinceStartMS(&USI.now) / 1000.0);
  5238. processData(&USI);
  5239. if (keyWasPressed()) {
  5240. // This prints something like
  5241. // SYN Stealth Scan Timing: About 1.14% done; ETC: 15:01 (0:43:23 remaining);
  5242. USI.SPM->printStats(USI.getCompletionFraction(), NULL);
  5243. if (o.debugging) {
  5244. /* Don't update when getting the current rates, otherwise we can get
  5245. anomalies (rates are too low) from having just done a potentially
  5246. long waitForResponses without sending any packets. */
  5247. USI.log_current_rates(LOG_STDOUT, false);
  5248. }
  5249. log_flush(LOG_STDOUT);
  5250. }
  5251. }
  5252. USI.send_rate_meter.stop(&USI.now);
  5253. /* Save the computed timeouts. */
  5254. if (to != NULL)
  5255. *to = USI.gstats->to;
  5256. if (o.verbose) {
  5257. char additional_info[128];
  5258. if (USI.gstats->num_hosts_timedout == 0)
  5259. if (USI.ping_scan) {
  5260. Snprintf(additional_info, sizeof(additional_info), "%lu total hosts",
  5261. (unsigned long) Targets.size());
  5262. } else {
  5263. Snprintf(additional_info, sizeof(additional_info), "%lu total ports",
  5264. (unsigned long) USI.gstats->numprobes * Targets.size());
  5265. }
  5266. else Snprintf(additional_info, sizeof(additional_info), "%d %s timed out",
  5267. USI.gstats->num_hosts_timedout,
  5268. (USI.gstats->num_hosts_timedout == 1) ? "host" : "hosts");
  5269. USI.SPM->endTask(NULL, additional_info);
  5270. }
  5271. if (o.debugging)
  5272. USI.log_overall_rates(LOG_STDOUT);
  5273. if (o.debugging > 2 && USI.pd != NULL)
  5274. pcap_print_stats(LOG_PLAIN, USI.pd);
  5275. }
  5276. /* FTP bounce attack scan. This function is rather lame and should be
  5277. rewritten. But I don't think it is used much anyway. If I'm going to
  5278. allow FTP bounce scan, I should really allow SOCKS proxy scan. */
  5279. void bounce_scan(Target *target, u16 *portarray, int numports,
  5280. struct ftpinfo *ftp) {
  5281. o.current_scantype = BOUNCE_SCAN;
  5282. time_t starttime;
  5283. int res , sd = ftp->sd, i = 0;
  5284. const char *t = (const char *)target->v4hostip();
  5285. int retriesleft = FTP_RETRIES;
  5286. char recvbuf[2048];
  5287. char targetstr[20];
  5288. char command[512];
  5289. char hostname[1200];
  5290. unsigned short portno, p1, p2;
  5291. int timedout;
  5292. if (numports == 0)
  5293. return; /* nothing to scan for */
  5294. Snprintf(targetstr, 20, "%d,%d,%d,%d,", UC(t[0]), UC(t[1]), UC(t[2]), UC(t[3]));
  5295. starttime = time(NULL);
  5296. if (o.verbose || o.debugging) {
  5297. struct tm *tm = localtime(&starttime);
  5298. assert(tm);
  5299. log_write(LOG_STDOUT, "Initiating TCP FTP bounce scan against %s at %02d:%02d\n", target->NameIP(hostname, sizeof(hostname)), tm->tm_hour, tm->tm_min );
  5300. }
  5301. for (i = 0; i < numports; i++) {
  5302. /* Check for timeout */
  5303. if (target->timedOut(NULL))
  5304. return;
  5305. portno = htons(portarray[i]);
  5306. p1 = ((unsigned char *) &portno)[0];
  5307. p2 = ((unsigned char *) &portno)[1];
  5308. Snprintf(command, 512, "PORT %s%i,%i\r\n", targetstr, p1, p2);
  5309. if (o.debugging)
  5310. log_write(LOG_STDOUT, "Attempting command: %s", command);
  5311. if (send(sd, command, strlen(command), 0) < 0 ) {
  5312. gh_perror("send in %s", __func__);
  5313. if (retriesleft) {
  5314. if (o.verbose || o.debugging)
  5315. log_write(LOG_STDOUT, "Our FTP proxy server hung up on us! retrying\n");
  5316. retriesleft--;
  5317. close(sd);
  5318. ftp->sd = ftp_anon_connect(ftp);
  5319. if (ftp->sd < 0)
  5320. return;
  5321. sd = ftp->sd;
  5322. i--;
  5323. } else {
  5324. error("Our socket descriptor is dead and we are out of retries. Giving up.");
  5325. close(sd);
  5326. ftp->sd = -1;
  5327. return;
  5328. }
  5329. } else { /* Our send is good */
  5330. res = recvtime(sd, recvbuf, 2048, 15, NULL);
  5331. if (res <= 0) {
  5332. perror("recv problem from FTP bounce server");
  5333. } else { /* our recv is good */
  5334. recvbuf[res] = '\0';
  5335. if (o.debugging)
  5336. log_write(LOG_STDOUT, "result of port query on port %i: %s",
  5337. portarray[i], recvbuf);
  5338. if (recvbuf[0] == '5') {
  5339. if (portarray[i] > 1023) {
  5340. fatal("Your FTP bounce server sucks, it won't let us feed bogus ports!");
  5341. } else {
  5342. error("Your FTP bounce server doesn't allow privileged ports, skipping them.");
  5343. while (i < numports && portarray[i] < 1024) i++;
  5344. if (!portarray[i]) {
  5345. fatal("And you didn't want to scan any unpriviliged ports. Giving up.");
  5346. }
  5347. }
  5348. } else { /* Not an error message */
  5349. if (send(sd, "LIST\r\n", 6, 0) > 0 ) {
  5350. res = recvtime(sd, recvbuf, 2048, 12, &timedout);
  5351. if (res < 0) {
  5352. perror("recv problem from FTP bounce server");
  5353. } else if (res == 0) {
  5354. if (timedout)
  5355. target->ports.setPortState(portarray[i], IPPROTO_TCP, PORT_FILTERED);
  5356. else target->ports.setPortState(portarray[i], IPPROTO_TCP, PORT_CLOSED);
  5357. } else {
  5358. recvbuf[res] = '\0';
  5359. if (o.debugging)
  5360. log_write(LOG_STDOUT, "result of LIST: %s", recvbuf);
  5361. if (!strncmp(recvbuf, "500", 3)) {
  5362. /* fuck, we are not aligned properly */
  5363. if (o.verbose || o.debugging)
  5364. error("FTP command misalignment detected ... correcting.");
  5365. res = recvtime(sd, recvbuf, 2048, 10, NULL);
  5366. }
  5367. if (recvbuf[0] == '1' || recvbuf[0] == '2') {
  5368. target->ports.setPortState(portarray[i], IPPROTO_TCP, PORT_OPEN);
  5369. if (recvbuf[0] == '1') {
  5370. res = recvtime(sd, recvbuf, 2048, 5, NULL);
  5371. if (res < 0)
  5372. perror("recv problem from FTP bounce server");
  5373. else {
  5374. recvbuf[res] = '\0';
  5375. if (res > 0) {
  5376. if (o.debugging)
  5377. log_write(LOG_STDOUT, "nxt line: %s", recvbuf);
  5378. if (recvbuf[0] == '4' && recvbuf[1] == '2' && recvbuf[2] == '6') {
  5379. target->ports.forgetPort(portarray[i], IPPROTO_TCP);
  5380. if (o.debugging || o.verbose)
  5381. log_write(LOG_STDOUT, "Changed my mind about port %i\n", portarray[i]);
  5382. }
  5383. }
  5384. }
  5385. }
  5386. } else {
  5387. /* This means the port is closed ... */
  5388. target->ports.setPortState(portarray[i], IPPROTO_TCP, PORT_CLOSED);
  5389. }
  5390. }
  5391. }
  5392. }
  5393. }
  5394. }
  5395. }
  5396. if (o.debugging || o.verbose)
  5397. log_write(LOG_STDOUT, "Scanned %d ports in %ld seconds via the Bounce scan.\n",
  5398. numports, (long) time(NULL) - starttime);
  5399. return;
  5400. }