PageRenderTime 72ms CodeModel.GetById 29ms RepoModel.GetById 0ms app.codeStats 1ms

/FPEngine.cc

https://gitlab.com/g10h4ck/nmap-gsoc2015
C++ | 2740 lines | 1621 code | 377 blank | 742 comment | 515 complexity | 9aa7f4021b37f2b56eb6dc32b0a8b5ff MD5 | raw file
Possible License(s): BSD-3-Clause, GPL-2.0, Apache-2.0, LGPL-2.0, LGPL-2.1, MIT

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

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