PageRenderTime 64ms CodeModel.GetById 24ms RepoModel.GetById 0ms app.codeStats 1ms

/FPEngine.cc

https://github.com/prakashgamit/nmap
C++ | 2693 lines | 1584 code | 372 blank | 737 comment | 494 complexity | e408f849bd72ee4e7f09dd652d820b7a MD5 | raw file
Possible License(s): BSD-3-Clause, GPL-2.0, LGPL-2.0, LGPL-2.1

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

  1. /***************************************************************************
  2. * FPEngine.cc -- Routines used for IPv6 OS detection via TCP/IP *
  3. * fingerprinting. * For more information on how this works in Nmap, see *
  4. * http://nmap.org/osdetect/ *
  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. #include "FPEngine.h"
  126. #include "Target.h"
  127. #include "NmapOps.h"
  128. #include "nmap_error.h"
  129. #include "osscan.h"
  130. #include "libnetutil/npacket.h"
  131. #include "linear.h"
  132. extern NmapOps o;
  133. /******************************************************************************
  134. * Globals. *
  135. ******************************************************************************/
  136. /* This is the global network controller. FPHost classes use it to request
  137. * network resources and schedule packet transmissions. */
  138. FPNetworkControl global_netctl;
  139. /******************************************************************************
  140. * Implementation of class FPNetworkControl. *
  141. ******************************************************************************/
  142. FPNetworkControl::FPNetworkControl() {
  143. memset(&this->nsp, 0, sizeof(nsock_pool));
  144. memset(&this->pcap_nsi, 0, sizeof(pcap_nsi));
  145. memset(&this->pcap_ev_id, 0, sizeof(nsock_event_id));
  146. this->nsock_init = false;
  147. this->rawsd = -1;
  148. this->probes_sent = 0;
  149. this->responses_recv = 0;
  150. this->probes_timedout = 0;
  151. this->cc_cwnd = 0;
  152. this->cc_ssthresh = 0;
  153. }
  154. FPNetworkControl::~FPNetworkControl() {
  155. if (this->nsock_init) {
  156. nsock_event_cancel(this->nsp, this->pcap_ev_id, 0);
  157. nsp_delete(this->nsp);
  158. this->nsock_init = false;
  159. }
  160. }
  161. /* (Re)-Initialize object's state (default parameter setup and nsock
  162. * initialization). */
  163. void FPNetworkControl::init(const char *ifname, devtype iftype) {
  164. /* Init congestion control parameters */
  165. this->cc_init();
  166. /* If there was a previous nsock pool, delete it */
  167. if (this->pcap_nsi) {
  168. nsi_delete(this->pcap_nsi, NSOCK_PENDING_SILENT);
  169. }
  170. if (this->nsock_init) {
  171. nsock_event_cancel(this->nsp, this->pcap_ev_id, 0);
  172. nsp_delete(this->nsp);
  173. }
  174. /* Create a new nsock pool */
  175. if ((this->nsp = nsp_new(NULL)) == NULL)
  176. fatal("Unable to obtain an Nsock pool");
  177. nsock_set_log_function(this->nsp, nmap_nsock_stderr_logger);
  178. nmap_adjust_loglevel(this->nsp, o.packetTrace());
  179. nsp_setdevice(nsp, o.device);
  180. if (o.proxy_chain)
  181. nsp_set_proxychain(this->nsp, o.proxy_chain);
  182. /* Allow broadcast addresses */
  183. nsp_setbroadcast(this->nsp, 1);
  184. /* Allocate an NSI for packet capture */
  185. this->pcap_nsi = nsi_new(this->nsp, NULL);
  186. this->first_pcap_scheduled = false;
  187. /* Flag it as already initialized so we free this nsp next time */
  188. this->nsock_init = true;
  189. /* Obtain raw socket or check that we can obtain an eth descriptor. */
  190. if ((o.sendpref & PACKET_SEND_ETH) && iftype == devt_ethernet && ifname != NULL) {
  191. /* We don't need to store the eth handler because FPProbes come with a
  192. * suitable one (FPProbes::getEthernet()), we just attempt to obtain one
  193. * to see if it fails. */
  194. if (eth_open_cached(ifname) == NULL)
  195. fatal("dnet: failed to open device %s", ifname);
  196. this->rawsd = -1;
  197. } else {
  198. #ifdef WIN32
  199. win32_fatal_raw_sockets(ifname);
  200. #endif
  201. if (this->rawsd >= 0)
  202. close(this->rawsd);
  203. rawsd = nmap_raw_socket();
  204. if (rawsd < 0)
  205. pfatal("Couldn't obtain raw socket in %s", __func__);
  206. }
  207. /* De-register existing callers */
  208. while (this->callers.size() > 0) {
  209. this->callers.pop_back();
  210. }
  211. return;
  212. }
  213. /* This function initializes the controller's congestion control parameters.
  214. * The network controller uses TCP's Slow Start and Congestion Avoidance
  215. * algorithms from RFC 5681 (slightly modified for convenience).
  216. *
  217. * As the OS detection process does not open full TCP connections, we can't just
  218. * use ACKs (or the lack of ACKs) to increase or decrease the congestion window
  219. * so we use probe responses. Every time we get a response to an OS detection
  220. * probe, we treat it as if it was a TCP ACK in TCP's congestion control.
  221. *
  222. * Note that the initial Congestion Window is set to the number of timed
  223. * probes that we send to each target. This is necessary since we need to
  224. * know for sure that we can send that many packets in order to transmit them.
  225. * Otherwise, we could fail to deliver the probes 100ms apart. */
  226. int FPNetworkControl::cc_init() {
  227. this->probes_sent = 0;
  228. this->responses_recv = 0;
  229. this->probes_timedout = 0;
  230. this->cc_cwnd = OSSCAN_INITIAL_CWND;
  231. this->cc_ssthresh = OSSCAN_INITIAL_SSTHRESH;
  232. return OP_SUCCESS;
  233. }
  234. /* This method is used to indicate that we have scheduled the transmission of
  235. * one or more packets. This is used in congestion control to determine the
  236. * number of outstanding probes (number of probes sent but not answered yet)
  237. * and therefore, the effective transmission window. @param pkts indicates the
  238. * number of packets that were scheduled. Returns OP_SUCCESS on success and
  239. * OP_FAILURE in case of error. */
  240. int FPNetworkControl::cc_update_sent(int pkts = 1) {
  241. if (pkts <= 0)
  242. return OP_FAILURE;
  243. this->probes_sent+=pkts;
  244. return OP_SUCCESS;
  245. }
  246. /* This method is used to indicate that a drop has occurred. In TCP, drops are
  247. * detected by the absence of an ACK. However, we can't use that, since it is
  248. * very likely that our targets do not respond to some of our OS detection
  249. * probes intentionally. For this reason, we consider that a drop has occurred
  250. * when we receive a response for a probe that has already suffered one
  251. * retransmission (first transmission got dropped in transit, some later
  252. * transmission made it to the host and it responded). So when we detect a drop
  253. * we do the same as TCP, adjust the congestion window and the slow start
  254. * threshold. */
  255. int FPNetworkControl::cc_report_drop() {
  256. /* FROM RFC 5681
  257. When a TCP sender detects segment loss using the retransmission timer
  258. and the given segment has not yet been resent by way of the
  259. retransmission timer, the value of ssthresh MUST be set to no more
  260. than the value given in equation (4):
  261. ssthresh = max (FlightSize / 2, 2*SMSS) (4)
  262. where, as discussed above, FlightSize is the amount of outstanding
  263. data in the network.
  264. On the other hand, when a TCP sender detects segment loss using the
  265. retransmission timer and the given segment has already been
  266. retransmitted by way of the retransmission timer at least once, the
  267. value of ssthresh is held constant.
  268. */
  269. int probes_outstanding = this->probes_sent - this->responses_recv - this->probes_timedout;
  270. this->cc_ssthresh = MAX(probes_outstanding, OSSCAN_INITIAL_CWND);
  271. this->cc_cwnd = OSSCAN_INITIAL_CWND;
  272. return OP_SUCCESS;
  273. }
  274. /* This method is used to indicate that a response to a previous probe was
  275. * received. For us this is like getting and ACK in TCP congestion control, so
  276. * we update the congestion window (increase by one packet if we are in slow
  277. * start or increase it by a small percentage of a packet if we are in
  278. * congestion avoidance). */
  279. int FPNetworkControl::cc_update_received() {
  280. this->responses_recv++;
  281. /* If we are in Slow Start, increment congestion window by one packet.
  282. * (Note that we treat probe responses the same way TCP CC treats ACKs). */
  283. if (this->cc_cwnd < this->cc_ssthresh) {
  284. this->cc_cwnd += 1;
  285. /* Otherwise we are in Congestion Avoidance and CWND is incremented slowly,
  286. * approximately one packet per RTT */
  287. } else {
  288. this->cc_cwnd = this->cc_cwnd + 1/this->cc_cwnd;
  289. }
  290. if (o.debugging > 3) {
  291. log_write(LOG_PLAIN, "[FPNetworkControl] Congestion Control Parameters: cwnd=%f ssthresh=%f sent=%d recv=%d tout=%d outstanding=%d\n",
  292. this->cc_cwnd, this->cc_ssthresh, this->probes_sent, this->responses_recv, this->probes_timedout,
  293. this->probes_sent - this->responses_recv - this->probes_timedout);
  294. }
  295. return OP_SUCCESS;
  296. }
  297. /* This method is public and can be called by FPHosts to inform the controller
  298. * that a probe has experienced a final timeout. In other words, that no
  299. * response was received for the probe after doing the necessary retransmissions
  300. * and waiting for the RTO. This is used to decrease the number of outstanding
  301. * probes. Otherwise, if no host responded to the probes, the effective
  302. * transmission window could reach zero and prevent new probes from being sent,
  303. * clogging the engine. */
  304. int FPNetworkControl::cc_report_final_timeout() {
  305. this->probes_timedout++;
  306. return OP_SUCCESS;
  307. }
  308. /* This method is used by FPHosts to request permission to transmit a number of
  309. * probes. Permission is granted if the current congestion window allows the
  310. * transmission of new probes. It returns true if permission is granted and
  311. * false if it is denied. */
  312. bool FPNetworkControl::request_slots(size_t num_packets) {
  313. int probes_outstanding = this->probes_sent - this->responses_recv - this->probes_timedout;
  314. if (o.debugging > 3)
  315. log_write(LOG_PLAIN, "[FPNetworkControl] Slot request for %u packets. ProbesOutstanding=%d cwnd=%f ssthresh=%f\n",
  316. (unsigned int)num_packets, probes_outstanding, this->cc_cwnd, this->cc_ssthresh);
  317. /* If we still have room for more outstanding probes, let the caller
  318. * schedule transmissions. */
  319. if ((probes_outstanding + num_packets) <= this->cc_cwnd) {
  320. this->cc_update_sent(num_packets);
  321. return true;
  322. }
  323. return false;
  324. }
  325. /* This method lets FPHosts register themselves in the network controller so
  326. * the controller can call them back every time a packet they are interested
  327. * in is captured.*/
  328. int FPNetworkControl::register_caller(FPHost *newcaller) {
  329. this->callers.push_back(newcaller);
  330. return OP_SUCCESS;
  331. }
  332. /* This method lets FPHosts unregister themselves in the network controller so
  333. * the controller does not call them back again. This is called by hosts that
  334. * have already finished their OS detection. */
  335. int FPNetworkControl::unregister_caller(FPHost *oldcaller) {
  336. for (size_t i = 0; i < this->callers.size(); i++) {
  337. if (this->callers[i] == oldcaller) {
  338. this->callers.erase(this->callers.begin() + i);
  339. return OP_SUCCESS;
  340. }
  341. }
  342. return OP_FAILURE;
  343. }
  344. /* This method gets the controller ready for packet capture. Basically it
  345. * obtains a pcap descriptor from nsock and sets an appropriate BPF filter. */
  346. int FPNetworkControl::setup_sniffer(const char *iface, const char *bpf_filter) {
  347. char pcapdev[128];
  348. int rc;
  349. #ifdef WIN32
  350. /* Nmap normally uses device names obtained through dnet for interfaces, but
  351. Pcap has its own naming system. So the conversion is done here */
  352. if (!DnetName2PcapName(iface, pcapdev, sizeof(pcapdev))) {
  353. /* Oh crap -- couldn't find the corresponding dev apparently. Let's just go
  354. with what we have then ... */
  355. Strncpy(pcapdev, iface, sizeof(pcapdev));
  356. }
  357. #else
  358. Strncpy(pcapdev, iface, sizeof(pcapdev));
  359. #endif
  360. /* Obtain a pcap descriptor */
  361. rc = nsock_pcap_open(this->nsp, this->pcap_nsi, pcapdev, 8192, 0, bpf_filter);
  362. if (rc)
  363. fatal("Error opening capture device %s\n", pcapdev);
  364. /* Store the pcap NSI inside the pool so we can retrieve it inside a callback */
  365. nsp_setud(this->nsp, (void *)&(this->pcap_nsi));
  366. return OP_SUCCESS;
  367. }
  368. /* This method makes the controller process pending events (like packet
  369. * transmissions or packet captures). */
  370. void FPNetworkControl::handle_events() {
  371. nmap_adjust_loglevel(nsp, o.packetTrace());
  372. nsock_loop(nsp, 50);
  373. }
  374. /* This method lets FPHosts to schedule the transmission of an OS detection
  375. * probe. It takes an FPProbe pointer and the amount of milliseconds the
  376. * controller should wait before injecting the probe into the wire. */
  377. int FPNetworkControl::scheduleProbe(FPProbe *pkt, int in_msecs_time) {
  378. nsock_timer_create(this->nsp, probe_transmission_handler_wrapper, in_msecs_time, (void*)pkt);
  379. return OP_SUCCESS;
  380. }
  381. /* This is the handler for packet transmission. It is called by nsock whenever a timer expires,
  382. * which means that a new packet needs to be transmitted. Note that this method is not
  383. * called directly by Nsock but by the wrapper function probe_transmission_handler_wrapper().
  384. * The reason for that is because C++ does not allow to use class methods as callback
  385. * functions, so this is a small hack to make that happen. */
  386. void FPNetworkControl::probe_transmission_handler(nsock_pool nsp, nsock_event nse, void *arg) {
  387. assert(nsp_getud(nsp) != NULL);
  388. nsock_iod nsi_pcap = *((nsock_iod *)nsp_getud(nsp));
  389. enum nse_status status = nse_status(nse);
  390. enum nse_type type = nse_type(nse);
  391. FPProbe *myprobe = (FPProbe *)arg;
  392. u8 *buf;
  393. size_t len;
  394. if (status == NSE_STATUS_SUCCESS) {
  395. switch(type) {
  396. /* Timer events mean that we need to send a packet. */
  397. case NSE_TYPE_TIMER:
  398. /* The first time a packet is sent, we schedule a pcap event. After that
  399. * we don't have to worry since the response reception handler schedules
  400. * a new capture event for each captured packet. */
  401. if (!this->first_pcap_scheduled) {
  402. this->pcap_ev_id = nsock_pcap_read_packet(nsp, nsi_pcap, response_reception_handler_wrapper, -1, NULL);
  403. this->first_pcap_scheduled = true;
  404. }
  405. buf = myprobe->getPacketBuffer(&len);
  406. /* Send the packet*/
  407. assert(myprobe->host != NULL);
  408. if (send_ip_packet(this->rawsd, myprobe->getEthernet(), myprobe->host->getTargetAddress(), buf, len) == -1) {
  409. pfatal("Unable to send packet in %s", __func__);
  410. }
  411. myprobe->setTimeSent();
  412. free(buf);
  413. break;
  414. default:
  415. fatal("Unexpected Nsock event in probe_transmission_handler()");
  416. break;
  417. } /* switch(type) */
  418. } else if (status == NSE_STATUS_EOF) {
  419. if (o.debugging)
  420. log_write(LOG_PLAIN, "probe_transmission_handler(): EOF\n");
  421. } else if (status == NSE_STATUS_ERROR || status == NSE_STATUS_PROXYERROR) {
  422. if (o.debugging)
  423. log_write(LOG_PLAIN, "probe_transmission_handler(): %s failed: %s\n", nse_type2str(type), strerror(socket_errno()));
  424. } else if (status == NSE_STATUS_TIMEOUT) {
  425. if (o.debugging)
  426. log_write(LOG_PLAIN, "probe_transmission_handler(): %s timeout: %s\n", nse_type2str(type), strerror(socket_errno()));
  427. } else if (status == NSE_STATUS_CANCELLED) {
  428. if (o.debugging)
  429. log_write(LOG_PLAIN, "probe_transmission_handler(): %s canceled: %s\n", nse_type2str(type), strerror(socket_errno()));
  430. } else if (status == NSE_STATUS_KILL) {
  431. if (o.debugging)
  432. log_write(LOG_PLAIN, "probe_transmission_handler(): %s killed: %s\n", nse_type2str(type), strerror(socket_errno()));
  433. } else {
  434. if (o.debugging)
  435. log_write(LOG_PLAIN, "probe_transmission_handler(): Unknown status code %d\n", status);
  436. }
  437. return;
  438. }
  439. /* This is the handler for packet capture. It is called by nsock whenever libpcap
  440. * captures a packet from the network interface. This method basically captures
  441. * the packet, extracts its source IP address and tries to find an FPHost that
  442. * is targeting such address. If it does, it passes the packet to that FPHost
  443. * via callback() so the FPHost can determine if the packet is actually the
  444. * response to a FPProbe that it sent before. Note that this method is not
  445. * called directly by Nsock but by the wrapper function
  446. * response_reception_handler_wrapper(). See doc in probe_transmission_handler()
  447. * for details. */
  448. void FPNetworkControl::response_reception_handler(nsock_pool nsp, nsock_event nse, void *arg) {
  449. nsock_iod nsi = nse_iod(nse);
  450. enum nse_status status = nse_status(nse);
  451. enum nse_type type = nse_type(nse);
  452. const u8 *rcvd_pkt = NULL; /* Points to the captured packet */
  453. size_t rcvd_pkt_len = 0; /* Lenght of the captured packet */
  454. struct timeval pcaptime; /* Time the packet was captured */
  455. struct sockaddr_storage sent_ss;
  456. struct sockaddr_storage rcvd_ss;
  457. struct sockaddr_in *rcvd_ss4 = (struct sockaddr_in *)&rcvd_ss;
  458. struct sockaddr_in6 *rcvd_ss6 = (struct sockaddr_in6 *)&rcvd_ss;
  459. memset(&rcvd_ss, 0, sizeof(struct sockaddr_storage));
  460. IPv4Header ip4;
  461. IPv6Header ip6;
  462. int res = -1;
  463. struct timeval tv;
  464. gettimeofday(&tv, NULL);
  465. if (status == NSE_STATUS_SUCCESS) {
  466. switch(type) {
  467. case NSE_TYPE_PCAP_READ:
  468. /* Schedule a new pcap read operation */
  469. this->pcap_ev_id = nsock_pcap_read_packet(nsp, nsi, response_reception_handler_wrapper, -1, NULL);
  470. /* Get captured packet */
  471. nse_readpcap(nse, NULL, NULL, &rcvd_pkt, &rcvd_pkt_len, NULL, &pcaptime);
  472. /* Extract the packet's source address */
  473. ip4.storeRecvData(rcvd_pkt, rcvd_pkt_len);
  474. if (ip4.validate() != OP_FAILURE && ip4.getVersion() == 4) {
  475. ip4.getSourceAddress(&(rcvd_ss4->sin_addr));
  476. rcvd_ss4->sin_family = AF_INET;
  477. } else {
  478. ip6.storeRecvData(rcvd_pkt, rcvd_pkt_len);
  479. if (ip6.validate() != OP_FAILURE && ip6.getVersion() == 6) {
  480. ip6.getSourceAddress(&(rcvd_ss6->sin6_addr));
  481. rcvd_ss6->sin6_family = AF_INET6;
  482. } else {
  483. /* If we get here it means that the received packet is not
  484. * IPv4 or IPv6 so we just discard it returning. */
  485. return;
  486. }
  487. }
  488. /* Check if we have a caller that expects packets from this sender */
  489. for (size_t i = 0; i < this->callers.size(); i++) {
  490. /* Obtain the target address */
  491. sent_ss = *this->callers[i]->getTargetAddress();
  492. /* Check that the received packet is of the same address family */
  493. if (sent_ss.ss_family != rcvd_ss.ss_family)
  494. continue;
  495. /* Check that the captured packet's source address matches the
  496. * target address. If it matches, pass the received packet
  497. * to the appropriate FPHost object through callback(). */
  498. if (sockaddr_storage_equal(&rcvd_ss, &sent_ss)) {
  499. if ((res = this->callers[i]->callback(rcvd_pkt, rcvd_pkt_len, &tv)) >= 0) {
  500. /* If callback() returns >=0 it means that the packet we've just
  501. * passed was successfully matched with a previous probe. Now
  502. * update the count of received packets (so we can determine how
  503. * many outstanding packets are out there). Note that we only do
  504. * that if callback() returned >0 because 0 is a special case: a
  505. * reply to a retransmitted timed probe that was already replied
  506. * to in the past. We don't want to count replies to the same probe
  507. * more than once, so that's why we only update when res > 0. */
  508. if (res > 0)
  509. this->cc_update_received();
  510. /* When the callback returns more than 1 it means that the packet
  511. * was sent more than once before being answered. This means that
  512. * we experienced congestion (first transmission got dropped), so
  513. * we update our CC parameters to deal with the congestion. */
  514. if (res > 1) {
  515. this->cc_report_drop();
  516. }
  517. }
  518. return;
  519. }
  520. }
  521. break;
  522. default:
  523. fatal("Unexpected Nsock event in response_reception_handler()");
  524. break;
  525. } /* switch(type) */
  526. } else if (status == NSE_STATUS_EOF) {
  527. if (o.debugging)
  528. log_write(LOG_PLAIN, "response_reception_handler(): EOF\n");
  529. } else if (status == NSE_STATUS_ERROR || NSE_STATUS_PROXYERROR) {
  530. if (o.debugging)
  531. log_write(LOG_PLAIN, "response_reception_handler(): %s failed: %s\n", nse_type2str(type), strerror(socket_errno()));
  532. } else if (status == NSE_STATUS_TIMEOUT) {
  533. if (o.debugging)
  534. log_write(LOG_PLAIN, "response_reception_handler(): %s timeout: %s\n", nse_type2str(type), strerror(socket_errno()));
  535. } else if (status == NSE_STATUS_CANCELLED) {
  536. if (o.debugging)
  537. log_write(LOG_PLAIN, "response_reception_handler(): %s canceled: %s\n", nse_type2str(type), strerror(socket_errno()));
  538. } else if (status == NSE_STATUS_KILL) {
  539. if (o.debugging)
  540. log_write(LOG_PLAIN, "response_reception_handler(): %s killed: %s\n", nse_type2str(type), strerror(socket_errno()));
  541. } else {
  542. if (o.debugging)
  543. log_write(LOG_PLAIN, "response_reception_handler(): Unknown status code %d\n", status);
  544. }
  545. return;
  546. }
  547. /******************************************************************************
  548. * Implementation of class FPEngine. *
  549. ******************************************************************************/
  550. FPEngine::FPEngine() {
  551. this->osgroup_size = OSSCAN_GROUP_SIZE;
  552. }
  553. FPEngine::~FPEngine() {
  554. }
  555. /* Returns a suitable BPF filter for the OS detection. If less than 20 targets
  556. * are passed, the filter contains an explicit list of target addresses. It
  557. * looks similar to this:
  558. *
  559. * dst host fe80::250:56ff:fec0:1 and (src host fe80::20c:29ff:feb0:2316 or src host fe80::20c:29ff:fe9f:5bc2)
  560. *
  561. * When more than 20 targets are passed, a generic filter based on the source
  562. * address is used. The returned filter looks something like:
  563. *
  564. * dst host fe80::250:56ff:fec0:1
  565. */
  566. const char *FPEngine::bpf_filter(std::vector<Target *> &Targets) {
  567. static char pcap_filter[2048];
  568. /* 20 IPv6 addresses is max (46 byte addy + 14 (" or src host ")) * 20 == 1200 */
  569. char dst_hosts[1220];
  570. int filterlen = 0;
  571. int len = 0;
  572. unsigned int targetno;
  573. memset(pcap_filter, 0, sizeof(pcap_filter));
  574. /* If we have 20 or less targets, build a list of addresses so we can set
  575. * an explicit BPF filter */
  576. if (Targets.size() <= 20) {
  577. for (targetno = 0; targetno < Targets.size(); targetno++) {
  578. len = Snprintf(dst_hosts + filterlen,
  579. sizeof(dst_hosts) - filterlen,
  580. "%ssrc host %s", (targetno == 0)? "" : " or ",
  581. Targets[targetno]->targetipstr());
  582. if (len < 0 || len + filterlen >= (int) sizeof(dst_hosts))
  583. fatal("ran out of space in dst_hosts");
  584. filterlen += len;
  585. }
  586. if (len < 0 || len + filterlen >= (int) sizeof(dst_hosts))
  587. fatal("ran out of space in dst_hosts");
  588. len = Snprintf(pcap_filter, sizeof(pcap_filter), "dst host %s and (%s)",
  589. Targets[0]->sourceipstr(), dst_hosts);
  590. } else {
  591. len = Snprintf(pcap_filter, sizeof(pcap_filter), "dst host %s", Targets[0]->sourceipstr());
  592. }
  593. if (len < 0 || len >= (int) sizeof(pcap_filter))
  594. fatal("ran out of space in pcap filter");
  595. return pcap_filter;
  596. }
  597. /******************************************************************************
  598. * Implementation of class FPEngine6. *
  599. ******************************************************************************/
  600. FPEngine6::FPEngine6() {
  601. }
  602. FPEngine6::~FPEngine6() {
  603. }
  604. /* From FPModel.cc. */
  605. extern struct model FPModel;
  606. extern double FPscale[][2];
  607. extern double FPmean[][659];
  608. extern double FPvariance[][659];
  609. extern FingerMatch FPmatches[];
  610. /* Not all operating systems allow setting the flow label in outgoing packets;
  611. notably all Unixes other than Linux when using raw sockets. This function
  612. finds out whether the flow labels we set are likely really being sent.
  613. Otherwise, the operating system is probably filling in 0. Compare to the
  614. logic in send_ipv6_packet_eth_or_sd. */
  615. static bool can_set_flow_label(const struct eth_nfo *eth) {
  616. if (eth != NULL)
  617. return true;
  618. #if HAVE_IPV6_IPPROTO_RAW
  619. return true;
  620. #else
  621. return false;
  622. #endif
  623. }
  624. void FPHost6::fill_FPR(FingerPrintResultsIPv6 *FPR) {
  625. unsigned int i;
  626. FPR->begin_time = this->begin_time;
  627. for (i = 0; i < sizeof(this->fp_responses) / sizeof(this->fp_responses[0]); i++) {
  628. const FPResponse *resp;
  629. resp = this->fp_responses[i];
  630. if (resp != NULL) {
  631. FPR->fp_responses[i] = new FPResponse(resp->probe_id, resp->buf, resp->len,
  632. resp->senttime, resp->rcvdtime);
  633. }
  634. }
  635. /* Were we actually able to set the flow label? */
  636. FPR->flow_label = 0;
  637. for (i = 0; i < sizeof(this->fp_probes) / sizeof(this->fp_probes[0]); i++) {
  638. const FPProbe& probe = fp_probes[0];
  639. if (probe.is_set()) {
  640. if (can_set_flow_label(probe.getEthernet()))
  641. FPR->flow_label = OSDETECT_FLOW_LABEL;
  642. break;
  643. }
  644. }
  645. }
  646. static const IPv6Header *find_ipv6(const PacketElement *pe) {
  647. while (pe != NULL && pe->protocol_id() != HEADER_TYPE_IPv6)
  648. pe = pe->getNextElement();
  649. return (IPv6Header *) pe;
  650. }
  651. static const TCPHeader *find_tcp(const PacketElement *pe) {
  652. while (pe != NULL && pe->protocol_id() != HEADER_TYPE_TCP)
  653. pe = pe->getNextElement();
  654. return (TCPHeader *) pe;
  655. }
  656. static double vectorize_plen(const PacketElement *pe) {
  657. const IPv6Header *ipv6;
  658. ipv6 = find_ipv6(pe);
  659. if (ipv6 == NULL)
  660. return -1;
  661. else
  662. return ipv6->getPayloadLength();
  663. }
  664. static double vectorize_tc(const PacketElement *pe) {
  665. const IPv6Header *ipv6;
  666. ipv6 = find_ipv6(pe);
  667. if (ipv6 == NULL)
  668. return -1;
  669. else
  670. return ipv6->getTrafficClass();
  671. }
  672. static double vectorize_isr(std::map<std::string, FPPacket>& resps) {
  673. const char * const SEQ_PROBE_NAMES[] = {"S1", "S2", "S3", "S4", "S5", "S6"};
  674. u32 seqs[NELEMS(SEQ_PROBE_NAMES)];
  675. struct timeval times[NELEMS(SEQ_PROBE_NAMES)];
  676. unsigned int i, j;
  677. double sum, t;
  678. j = 0;
  679. for (i = 0; i < NELEMS(SEQ_PROBE_NAMES); i++) {
  680. const char *probe_name;
  681. const FPPacket *fp;
  682. const TCPHeader *tcp;
  683. std::map<std::string, FPPacket>::iterator it;
  684. probe_name = SEQ_PROBE_NAMES[i];
  685. it = resps.find(probe_name);
  686. if (it == resps.end())
  687. continue;
  688. fp = &it->second;
  689. tcp = find_tcp(fp->getPacket());
  690. if (tcp == NULL)
  691. continue;
  692. seqs[j] = tcp->getSeq();
  693. times[j] = fp->getTime();
  694. j++;
  695. }
  696. if (j < 2)
  697. return -1;
  698. sum = 0.0;
  699. for (i = 0; i < j - 1; i++)
  700. sum += seqs[i + 1] - seqs[i];
  701. t = TIMEVAL_FSEC_SUBTRACT(times[j - 1], times[0]);
  702. return sum / t;
  703. }
  704. static struct feature_node *vectorize(const FingerPrintResultsIPv6 *FPR) {
  705. const char * const IPV6_PROBE_NAMES[] = {"S1", "S2", "S3", "S4", "S5", "S6", "IE1", "IE2", "NS", "U1", "TECN", "T2", "T3", "T4", "T5", "T6", "T7"};
  706. const char * const TCP_PROBE_NAMES[] = {"S1", "S2", "S3", "S4", "S5", "S6", "TECN", "T2", "T3", "T4", "T5", "T6", "T7"};
  707. unsigned int nr_feature, i, idx;
  708. struct feature_node *features;
  709. std::map<std::string, FPPacket> resps;
  710. for (i = 0; i < NUM_FP_PROBES_IPv6; i++) {
  711. PacketElement *pe;
  712. if (FPR->fp_responses[i] == NULL)
  713. continue;
  714. pe = PacketParser::split(FPR->fp_responses[i]->buf, FPR->fp_responses[i]->len);
  715. assert(pe != NULL);
  716. resps[FPR->fp_responses[i]->probe_id].setPacket(pe);
  717. resps[FPR->fp_responses[i]->probe_id].setTime(&FPR->fp_responses[i]->senttime);
  718. }
  719. nr_feature = get_nr_feature(&FPModel);
  720. features = new feature_node[nr_feature + 1];
  721. for (i = 0; i < nr_feature; i++) {
  722. features[i].index = i + 1;
  723. features[i].value = -1;
  724. }
  725. features[i].index = -1;
  726. idx = 0;
  727. for (i = 0; i < NELEMS(IPV6_PROBE_NAMES); i++) {
  728. const char *probe_name;
  729. probe_name = IPV6_PROBE_NAMES[i];
  730. features[idx++].value = vectorize_plen(resps[probe_name].getPacket());
  731. features[idx++].value = vectorize_tc(resps[probe_name].getPacket());
  732. }
  733. /* TCP features */
  734. features[idx++].value = vectorize_isr(resps);
  735. for (i = 0; i < NELEMS(TCP_PROBE_NAMES); i++) {
  736. const char *probe_name;
  737. const TCPHeader *tcp;
  738. u16 flags;
  739. u16 mask;
  740. unsigned int j;
  741. int mss;
  742. int sackok;
  743. int wscale;
  744. probe_name = TCP_PROBE_NAMES[i];
  745. mss = -1;
  746. sackok = -1;
  747. wscale = -1;
  748. tcp = find_tcp(resps[probe_name].getPacket());
  749. if (tcp == NULL) {
  750. /* 48 TCP features. */
  751. idx += 48;
  752. continue;
  753. }
  754. features[idx++].value = tcp->getWindow();
  755. flags = tcp->getFlags16();
  756. for (mask = 0x001; mask <= 0x800; mask <<= 1)
  757. features[idx++].value = (flags & mask) != 0;
  758. for (j = 0; j < 16; j++) {
  759. nping_tcp_opt_t opt;
  760. opt = tcp->getOption(j);
  761. if (opt.value == NULL)
  762. break;
  763. features[idx++].value = opt.type;
  764. /* opt.len includes the two (type, len) bytes. */
  765. if (opt.type == TCPOPT_MSS && opt.len == 4 && mss == -1)
  766. mss = ntohs(*(u16 *) opt.value);
  767. else if (opt.type == TCPOPT_SACKOK && opt.len == 2 && sackok == -1)
  768. sackok = 1;
  769. else if (opt.type == TCPOPT_WSCALE && opt.len == 3 && wscale == -1)
  770. wscale = *(u8 *) opt.value;
  771. }
  772. for (; j < 16; j++)
  773. idx++;
  774. for (j = 0; j < 16; j++) {
  775. nping_tcp_opt_t opt;
  776. opt = tcp->getOption(j);
  777. if (opt.value == NULL)
  778. break;
  779. features[idx++].value = opt.len;
  780. }
  781. for (; j < 16; j++)
  782. idx++;
  783. features[idx++].value = mss;
  784. features[idx++].value = sackok;
  785. features[idx++].value = wscale;
  786. }
  787. assert(idx == nr_feature);
  788. if (o.debugging > 2) {
  789. log_write(LOG_PLAIN, "v = {");
  790. for (i = 0; i < nr_feature; i++)
  791. log_write(LOG_PLAIN, "%.16g, ", features[i].value);
  792. log_write(LOG_PLAIN, "};\n");
  793. }
  794. return features;
  795. }
  796. static void apply_scale(struct feature_node *features, unsigned int num_features,
  797. const double (*scale)[2]) {
  798. unsigned int i;
  799. for (i = 0; i < num_features; i++) {
  800. double val = features[i].value;
  801. if (val < 0)
  802. continue;
  803. val = (val + scale[i][0]) * scale[i][1];
  804. features[i].value = val;
  805. }
  806. }
  807. /* (label, prob) pairs for purpose of sorting. */
  808. struct label_prob {
  809. int label;
  810. double prob;
  811. };
  812. int label_prob_cmp(const void *a, const void *b) {
  813. const struct label_prob *la, *lb;
  814. la = (struct label_prob *) a;
  815. lb = (struct label_prob *) b;
  816. /* Sort descending. */
  817. if (la->prob > lb->prob)
  818. return -1;
  819. else if (la->prob < lb->prob)
  820. return 1;
  821. else
  822. return 0;
  823. }
  824. /* Return a measure of how much the given feature vector differs from the other
  825. members of the class given by label.
  826. This can be thought of as the distance from the given feature vector to the
  827. mean of the class in multidimensional space, after scaling. Each dimension is
  828. further scaled by the inverse of the sample variance of that feature. This is
  829. an approximation of the Mahalanobis distance
  830. (https://en.wikipedia.org/wiki/Mahalanobis_distance), which normally uses a
  831. full covariance matrix of the features. If we take the features to be
  832. pairwise independent (which they are not), then the covariance matrix is just
  833. the diagonal matrix containing per-feature variances, leading to the same
  834. calculation as is done below. Using only the per-feature variances rather
  835. than covariance matrices is to save space; it requires only n entries per
  836. class rather than n^2, where n is the length of a feature vector.
  837. It happens often that a feature's variance is undefined (because there is
  838. only one example in the class) or zero (because there are two identical
  839. values for that feature). Both these cases are mapped to zero by train.py,
  840. and we handle them the same way: by using a small default variance. This will
  841. tend to make small differences count a lot (because we probably want this
  842. fingerprint in order to expand the class), while still allowing near-perfect
  843. matches to match. */
  844. static double novelty_of(const struct feature_node *features, int label) {
  845. const double *means, *variances;
  846. int i, nr_feature;
  847. double sum;
  848. nr_feature = get_nr_feature(&FPModel);
  849. assert(0 <= label);
  850. assert(label < nr_feature);
  851. means = FPmean[label];
  852. variances = FPvariance[label];
  853. sum = 0.0;
  854. for (i = 0; i < nr_feature; i++) {
  855. double d, v;
  856. assert(i + 1 == features[i].index);
  857. d = features[i].value - means[i];
  858. v = variances[i];
  859. if (v == 0.0) {
  860. /* No variance? It means that samples were identical. Substitute a default
  861. variance. This will tend to make novelty large in these cases, which
  862. will hopefully encourage for submissions for this class. */
  863. v = 0.01;
  864. }
  865. sum += d * d / v;
  866. }
  867. return sqrt(sum);
  868. }
  869. static void classify(FingerPrintResultsIPv6 *FPR) {
  870. int nr_class, i;
  871. struct feature_node *features;
  872. double *values;
  873. struct label_prob *labels;
  874. nr_class = get_nr_class(&FPModel);
  875. features = vectorize(FPR);
  876. values = new double[nr_class];
  877. labels = new struct label_prob[nr_class];
  878. apply_scale(features, get_nr_feature(&FPModel), FPscale);
  879. predict_values(&FPModel, features, values);
  880. for (i = 0; i < nr_class; i++) {
  881. labels[i].label = i;
  882. labels[i].prob = 1.0 / (1.0 + exp(-values[i]));
  883. }
  884. qsort(labels, nr_class, sizeof(labels[0]), label_prob_cmp);
  885. for (i = 0; i < nr_class && i < MAX_FP_RESULTS; i++) {
  886. FPR->matches[i] = &o.os_labels_ipv6[labels[i].label];
  887. FPR->accuracy[i] = labels[i].prob;
  888. FPR->num_matches = i + 1;
  889. if (labels[i].prob >= 0.90 * labels[0].prob)
  890. FPR->num_perfect_matches = i + 1;
  891. if (o.debugging > 2) {
  892. printf("%7.4f %7.4f %3u %s\n", FPR->accuracy[i] * 100,
  893. novelty_of(features, labels[i].label), labels[i].label, FPR->matches[i]->OS_name);
  894. }
  895. }
  896. if (FPR->num_perfect_matches == 0) {
  897. FPR->overall_results = OSSCAN_NOMATCHES;
  898. } else if (FPR->num_perfect_matches == 1) {
  899. double novelty;
  900. novelty = novelty_of(features, labels[0].label);
  901. if (o.debugging > 1)
  902. log_write(LOG_PLAIN, "Novelty of closest match is %.3f.\n", novelty);
  903. if (novelty < FP_NOVELTY_THRESHOLD) {
  904. FPR->overall_results = OSSCAN_SUCCESS;
  905. } else {
  906. if (o.debugging > 0) {
  907. log_write(LOG_PLAIN, "Novelty of closest match is %.3f > %.3f; ignoring.\n",
  908. novelty, FP_NOVELTY_THRESHOLD);
  909. }
  910. FPR->overall_results = OSSCAN_NOMATCHES;
  911. FPR->num_perfect_matches = 0;
  912. }
  913. } else {
  914. FPR->overall_results = OSSCAN_NOMATCHES;
  915. FPR->num_perfect_matches = 0;
  916. }
  917. delete[] features;
  918. delete[] values;
  919. delete[] labels;
  920. }
  921. /* This method is the core of the FPEngine class. It takes a list of IPv6
  922. * targets that need to be fingerprinted. The method handles the whole
  923. * fingerprinting process, sending probes, collecting responses, analyzing
  924. * results and matching fingerprints. If everything goes well, the internal
  925. * state of the supplied target objects will be modified to reflect the results
  926. * of the */
  927. int FPEngine6::os_scan(std::vector<Target *> &Targets) {
  928. bool osscan_done = false;
  929. const char *bpf_filter = NULL;
  930. std::vector<FPHost6 *> curr_hosts; /* Hosts currently doing OS detection */
  931. std::vector<FPHost6 *> done_hosts; /* Hosts for which we already did OSdetect */
  932. std::vector<FPHost6 *> left_hosts; /* Hosts we have not yet started with */
  933. struct timeval begin_time;
  934. if (o.debugging)
  935. log_write(LOG_PLAIN, "Starting IPv6 OS Scan...\n");
  936. /* Initialize variables, timers, etc. */
  937. gettimeofday(&begin_time, NULL);
  938. global_netctl.init(Targets[0]->deviceName(), Targets[0]->ifType());
  939. for (size_t i = 0; i < Targets.size(); i++) {
  940. if (o.debugging > 3) {
  941. log_write(LOG_PLAIN, "[FPEngine] Allocating FPHost6 for %s %s\n",
  942. Targets[i]->targetipstr(), Targets[i]->sourceipstr());
  943. }
  944. FPHost6 *newhost = new FPHost6(Targets[i], &global_netctl);
  945. newhost->begin_time = begin_time;
  946. fphosts.push_back(newhost);
  947. }
  948. /* Build the BPF filter */
  949. bpf_filter = this->bpf_filter(Targets);
  950. if (o.debugging)
  951. log_write(LOG_PLAIN, "[FPEngine] Interface=%s BPF:%s\n", Targets[0]->deviceName(), bpf_filter);
  952. /* Set up the sniffer */
  953. global_netctl.setup_sniffer(Targets[0]->deviceName(), bpf_filter);
  954. /* Divide the targets into two groups, the ones we are going to start
  955. * processing, and the ones we leave for later. */
  956. for (size_t i = 0; i < Targets.size() && i < this->osgroup_size; i++) {
  957. curr_hosts.push_back(fphosts[i]);
  958. }
  959. for (size_t i = curr_hosts.size(); i < Targets.size(); i++) {
  960. left_hosts.push_back(fphosts[i]);
  961. }
  962. /* Do the OS detection rounds */
  963. while (!osscan_done) {
  964. osscan_done = true; /* It will remain true only when all hosts are .done() */
  965. if (o.debugging > 3) {
  966. log_write(LOG_PLAIN, "[FPEngine] CurrHosts=%d, LeftHosts=%d, DoneHosts=%d\n",
  967. (int) curr_hosts.size(), (int) left_hosts.size(), (int) done_hosts.size());
  968. }
  969. /* Go through the list of hosts and ask them to schedule their probes */
  970. for (unsigned int i = 0; i < curr_hosts.size(); i++) {
  971. /* If the host is not done yet, call schedule() to let it schedule
  972. * new probes, retransmissions, etc. */
  973. if (!curr_hosts[i]->done()) {
  974. osscan_done = false;
  975. curr_hosts[i]->schedule();
  976. if (o.debugging > 3)
  977. log_write(LOG_PLAIN, "[FPEngine] CurrHost #%u not done\n", i);
  978. /* If the host is done, take it out of the curr_hosts group and add it
  979. * to the done_hosts group. If we still have hosts left in the left_hosts
  980. * group, take the first one and insert it into curr_hosts. This way we
  981. * always have a full working group of hosts (unless we ran out of hosts,
  982. * of course). */
  983. } else {
  984. if (o.debugging > 3)
  985. log_write(LOG_PLAIN, "[FPEngine] CurrHost #%u done\n", i);
  986. if (o.debugging > 3)
  987. log_write(LOG_PLAIN, "[FPEngine] Moving done host %u to the done_hosts list\n", i);
  988. done_hosts.push_back(curr_hosts[i]);
  989. curr_hosts.erase(curr_hosts.begin() + i);
  990. /* If we still have hosts left, add one to the current group */
  991. if (left_hosts.size() > 0) {
  992. if (o.debugging > 3)
  993. log_write(LOG_PLAIN, "[FPEngine] Inserting one new hosts in the curr_hosts list.\n");
  994. curr_hosts.push_back(left_hosts[0]);
  995. left_hosts.erase(left_hosts.begin());
  996. osscan_done = false;
  997. }
  998. i--; /* Decrement i so we don't miss the host that is now in the
  999. * position of the host we've just removed from the list */
  1000. }
  1001. }
  1002. /* Handle scheduled events */
  1003. global_netctl.handle_events();
  1004. }
  1005. /* Once we've finished with all fphosts, check which ones were correctly
  1006. * fingerprinted, and update the Target objects. */
  1007. for (size_t i = 0; i < this->fphosts.size(); i++) {
  1008. fphosts[i]->finish();
  1009. fphosts[i]->fill_FPR((FingerPrintResultsIPv6 *) Targets[i]->FPR);
  1010. classify((FingerPrintResultsIPv6 *) Targets[i]->FPR);
  1011. }
  1012. /* Cleanup and return */
  1013. while (this->fphosts.size() > 0) {
  1014. FPHost6 *tmp = fphosts.back();
  1015. delete tmp;
  1016. fphosts.pop_back();
  1017. }
  1018. if (o.debugging)
  1019. log_write(LOG_PLAIN, "IPv6 OS Scan completed.\n");
  1020. return OP_SUCCESS;
  1021. }
  1022. /******************************************************************************
  1023. * Implementation of class FPHost. *
  1024. ******************************************************************************/
  1025. FPHost::FPHost() {
  1026. this->__reset();
  1027. }
  1028. FPHost::~FPHost() {
  1029. }
  1030. void FPHost::__reset() {
  1031. this->total_probes = 0;
  1032. this->timed_probes = 0;
  1033. this->probes_sent = 0;
  1034. this->probes_answered = 0;
  1035. this->probes_unanswered = 0;
  1036. this->detection_done = false;
  1037. this->timedprobes_sent = false;
  1038. this->target_host = NULL;
  1039. this->netctl = NULL;
  1040. this->netctl_registered = false;
  1041. this->tcpSeqBase = 0;
  1042. this->open_port_tcp = -1;
  1043. this->closed_port_tcp = -1;
  1044. this->closed_port_udp = -1;
  1045. this->tcp_port_base = -1;
  1046. this->udp_port_base = -1;
  1047. /* Retransmission time-out parameters.
  1048. *
  1049. * From RFC 2988:
  1050. * Until a round-trip time (RTT) measurement has been made for a segment
  1051. * sent between the sender and receiver, the sender SHOULD set
  1052. * RTO <- 3 seconds */
  1053. this->rto = OSSCAN_INITIAL_RTO;
  1054. this->rttvar = -1;
  1055. this->srtt = -1;
  1056. this->begin_time.tv_sec = 0;
  1057. this->begin_time.tv_usec = 0;
  1058. }
  1059. /* Returns the IP address of the target associated with the FPHost in
  1060. * stuct sockaddr_storage format. */
  1061. const struct sockaddr_storage *FPHost::getTargetAddress() {
  1062. return this->target_host->TargetSockAddr();
  1063. }
  1064. /* Accesses the Target object associated with the FPHost to extract the port
  1065. * numbers to be used in OS detection. In particular it extracts:
  1066. *
  1067. * - An open TCP port.
  1068. * - A closed TCP port.
  1069. * - A closed UDP port.
  1070. *
  1071. * When not enough information is found in the Target, the neccessary port
  1072. * numbers are generated randomly. */
  1073. int FPHost::choose_osscan_ports() {
  1074. Port *tport = NULL;
  1075. Port port;
  1076. /* Choose an open TCP port: First, check if the host already has a
  1077. * FingerPrintResults object that defines an open port. */
  1078. if (this->target_host->FPR != NULL && this->target_host->FPR->osscan_opentcpport > 0) {
  1079. this->open_port_tcp = this->target_host->FPR->osscan_opentcpport;
  1080. /* Otherwise, get the first open port that we've…

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