PageRenderTime 36ms CodeModel.GetById 16ms 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
  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 between the sender and receiver, the sender SHOULD set
  1086. * RTO <- 3 seconds */
  1087. this->rto = OSSCAN_INITIAL_RTO;
  1088. this->rttvar = -1;
  1089. this->srtt = -1;
  1090. this->begin_time.tv_sec = 0;
  1091. this->begin_time.tv_usec = 0;
  1092. }
  1093. /* Returns the IP address of the target associated with the FPHost in
  1094. * struct sockaddr_storage format. */
  1095. const struct sockaddr_storage *FPHost::getTargetAddress() {
  1096. return this->target_host->TargetSockAddr();
  1097. }
  1098. /* Marks one probe as unanswerable, making the fingerprint incomplete and
  1099. * ineligible for submission */
  1100. void FPHost::fail_one_probe() {
  1101. this->probes_unanswered++;
  1102. this->incomplete_fp = true;
  1103. }
  1104. /* Accesses the Target object associated with the FPHost to extract the port
  1105. * numbers to be used in OS detection. In particular it extracts:
  1106. *
  1107. * - An open TCP port.
  1108. * - A closed TCP port.
  1109. * - A closed UDP port.
  1110. *
  1111. * When not enough information is found in the Target, the necessary port
  1112. * numbers are generated randomly. */
  1113. int FPHost::choose_osscan_ports() {
  1114. Port *tport = NULL;
  1115. Port port;
  1116. /* Choose an open TCP port: First, check if the host already has a
  1117. * FingerPrintResults object that defines an open port. */
  1118. if (this->target_host->FPR != NULL && this->target_host->FPR->osscan_opentcpport > 0) {
  1119. this->open_port_tcp = this->target_host->FPR->osscan_opentcpport;
  1120. /* Otherwise, get the first open port that we've found open */
  1121. } else if ((tport = this->target_host->ports.nextPort(NULL, &port, IPPROTO_TCP, PORT_OPEN))) {
  1122. this->open_port_tcp = tport->portno;
  1123. /* If it is zero, let's try another one if there is one */
  1124. if (tport->portno == 0) {
  1125. if ((tport = this->target_host->ports.nextPort(tport, &port, IPPROTO_TCP, PORT_OPEN)))
  1126. this->open_port_tcp = tport->portno;
  1127. }
  1128. this->target_host->FPR->osscan_opentcpport = this->open_port_tcp;
  1129. } else {
  1130. /* If we don't have an open port, set it to -1 so we don't send probes that
  1131. * target TCP open ports */
  1132. this->open_port_tcp = -1;
  1133. }
  1134. /* Choose a closed TCP port. */
  1135. if (this->target_host->FPR != NULL && this->target_host->FPR->osscan_closedtcpport > 0) {
  1136. this->closed_port_tcp = this->target_host->FPR->osscan_closedtcpport;
  1137. } else if ((tport = this->target_host->ports.nextPort(NULL, &port, IPPROTO_TCP, PORT_CLOSED))) {
  1138. this->closed_port_tcp = tport->portno;
  1139. /* If it is zero, let's try another one if there is one */
  1140. if (tport->portno == 0)
  1141. if ((tport = this->target_host->ports.nextPort(tport, &port, IPPROTO_TCP, PORT_CLOSED)))
  1142. this->closed_port_tcp = tport->portno;
  1143. this->target_host->FPR->osscan_closedtcpport = this->closed_port_tcp;
  1144. } else if ((tport = this->target_host->ports.nextPort(NULL, &port, IPPROTO_TCP, PORT_UNFILTERED))) {
  1145. /* Well, we will settle for unfiltered */
  1146. this->closed_port_tcp = tport->portno;
  1147. /* But again we'd prefer not to have zero */
  1148. if (tport->portno == 0)
  1149. if ((tport = this->target_host->ports.nextPort(tport, &port, IPPROTO_TCP, PORT_UNFILTERED)))
  1150. this->closed_port_tcp = tport->portno;
  1151. } else {
  1152. /* If we don't have a closed port, set it to -1 so we don't send probes that
  1153. * target TCP closed ports. */
  1154. this->closed_port_tcp = -1;
  1155. }
  1156. /* Closed UDP port */
  1157. if (this->target_host->FPR != NULL && this->target_host->FPR->osscan_closedudpport > 0) {
  1158. this->closed_port_udp = this->target_host->FPR->osscan_closedudpport;
  1159. } else if ((tport = this->target_host->ports.nextPort(NULL, &port, IPPROTO_UDP, PORT_CLOSED))) {
  1160. this->closed_port_udp = tport->portno;
  1161. /* Not zero, if possible */
  1162. if (tport->portno == 0)
  1163. if ((tport = this->target_host->ports.nextPort(tport, &port, IPPROTO_UDP, PORT_CLOSED)))
  1164. this->closed_port_udp = tport->portno;
  1165. this->target_host->FPR->osscan_closedudpport = this->closed_port_udp;
  1166. } else if ((tport = this->target_host->ports.nextPort(NULL, &port, IPPROTO_UDP, PORT_UNFILTERED))) {
  1167. /* Well, we will settle for unfiltered */
  1168. this->closed_port_udp = tport->portno;
  1169. /* But not zero, please */
  1170. if (tport->portno == 0)
  1171. if ((tport = this->target_host->ports.nextPort(NULL, &port, IPPROTO_UDP, PORT_UNFILTERED)))
  1172. this->closed_port_udp = tport->portno;
  1173. } else {
  1174. /* Pick one at random. Shrug. */
  1175. this->closed_port_udp = (get_random_uint() % 14781) + 30000;
  1176. }
  1177. this->tcpSeqBase = get_random_u32();
  1178. this->tcp_port_base = o.magic_port_set ? o.magic_port : o.magic_port + get_random_u8();
  1179. this->udp_port_base = o.magic_port_set ? o.magic_port : o.magic_port + get_random_u8();
  1180. this->icmp_seq_counter = 0;
  1181. return OP_SUCCESS;
  1182. }
  1183. /* This method is called whenever we receive a response to a probe. It
  1184. * recomputes the host's retransmission timer based on the new RTT measure.
  1185. * @param measured_rtt_usecs is the new RTT observation in MICROseconds.
  1186. * @param retransmission indicates whether the observed RTT correspond to
  1187. * a packet that was transmitted more than once or not. It is used to
  1188. * avoid using RTT samples obtained from retransmissions (Karn's algorithm) */
  1189. int FPHost::update_RTO(int measured_rtt_usecs, bool retransmission) {
  1190. /* RFC 2988: TCP MUST use Karn's algorithm [KP87] for taking RTT samples. That
  1191. * is, RTT samples MUST NOT be made using segments that were
  1192. * retransmitted (and thus for which it is ambiguous whether the reply
  1193. * was for the first instance of the packet or a later instance).*/
  1194. if (retransmission == true)
  1195. return OP_SUCCESS;
  1196. /* RFC 2988: When the first RTT measurement R is made, the host MUST set
  1197. *
  1198. * SRTT <- R
  1199. * RTTVAR <- R/2
  1200. * RTO <- SRTT + max (G, K*RTTVAR)
  1201. *
  1202. * where K = 4, and G is the clock granularity.. */
  1203. if (this->srtt == -1 && this->rttvar == -1) {
  1204. this->srtt = measured_rtt_usecs;
  1205. this->rttvar = measured_rtt_usecs/2;
  1206. this->rto = this->srtt + MAX(500000, 4*this->rttvar); /* Assume a granularity of 1/2 sec */
  1207. } else {
  1208. /* RFC 2988: When a subsequent RTT measurement R' is made, a host MUST set
  1209. *
  1210. * RTTVAR <- (1 - beta) * RTTVAR + beta * |SRTT - R'|
  1211. * SRTT <- (1 - alpha) * SRTT + alpha * R'
  1212. *
  1213. * The above SHOULD be computed using alpha = 1/8 and beta = 1/4.
  1214. * After the computation, a host MUST update
  1215. *
  1216. * RTO <- SRTT + max (G, K*RTTVAR)
  1217. */
  1218. this->rttvar = ((1.0 - 0.25) * this->rttvar) + (0.25 * ABS(this->srtt - measured_rtt_usecs));
  1219. this->srtt = ((1.0 - 0.125) * this->srtt) + (0.125 * measured_rtt_usecs);
  1220. this->rto = this->srtt + MAX(500000, 4*this->rttvar);
  1221. }
  1222. /* RFC 2988: Whenever RTO is computed, if it is less than 1 second then the RTO
  1223. * SHOULD be rounded up to 1 second.
  1224. * [NOTE: In Nmap we find this excessive, so we set a minimum of 100ms
  1225. * (100,000 usecs). It may seem aggressive but waiting too long can cause
  1226. * the engine to fail to detect drops until many probes later on extremely
  1227. * low-latency networks (such as localhost scans). */
  1228. if (this->rto < (MIN_RTT_TIMEOUT*1000))
  1229. this->rto = (MIN_RTT_TIMEOUT*1000);
  1230. return this->rto;
  1231. }
  1232. /******************************************************************************
  1233. * Implementation of class FPHost6. *
  1234. ******************************************************************************/
  1235. FPHost6::FPHost6(Target *tgt, FPNetworkControl *fpnc) {
  1236. this->init(tgt, fpnc);
  1237. return;
  1238. }
  1239. FPHost6::~FPHost6() {
  1240. this->reset();
  1241. }
  1242. void FPHost6::reset() {
  1243. this->__reset();
  1244. for (unsigned int i = 0; i < NUM_FP_PROBES_IPv6; i++) {
  1245. this->fp_probes[i].reset();
  1246. if (this->fp_responses[i]) {
  1247. delete this->fp_responses[i];
  1248. this->fp_responses[i] = NULL;
  1249. }
  1250. }
  1251. }
  1252. void FPHost6::init(Target *tgt, FPNetworkControl *fpnc) {
  1253. this->target_host = tgt;
  1254. this->netctl = fpnc;
  1255. this->total_probes = 0;
  1256. this->timed_probes = 0;
  1257. /* Set state in the supplied Target */
  1258. if (this->target_host->FPR == NULL)
  1259. this->target_host->FPR = new FingerPrintResultsIPv6;
  1260. this->target_host->osscanSetFlag(OS_PERF);
  1261. /* Choose TCP/UDP ports for the probes. */
  1262. this->choose_osscan_ports();
  1263. /* Build the list of OS detection probes */
  1264. this->build_probe_list();
  1265. for (unsigned int i = 0; i < NUM_FP_PROBES_IPv6; i++)
  1266. this->fp_responses[i] = NULL;
  1267. for (unsigned int i = 0; i < NUM_FP_TIMEDPROBES_IPv6; i++)
  1268. this->aux_resp[i] = NULL;
  1269. }
  1270. /* Get the hop limit encapsulated in an ICMPv6 error reply. Return -1 if it
  1271. * can't be found. */
  1272. static int get_encapsulated_hoplimit(const PacketElement *pe) {
  1273. /* Check that it's IPv6. */
  1274. if (pe == NULL || pe->protocol_id() != HEADER_TYPE_IPv6)
  1275. return -1;
  1276. /* Find the ICMPv6 payload. */
  1277. pe = pe->getNextElement();
  1278. for (; pe != NULL; pe = pe->getNextElement()) {
  1279. if (pe->protocol_id() == HEADER_TYPE_ICMPv6)
  1280. break;
  1281. }
  1282. if (pe == NULL)
  1283. return -1;
  1284. /* Check that encapsulated is IPv6. */
  1285. pe = pe->getNextElement();
  1286. if (pe == NULL || pe->protocol_id() != HEADER_TYPE_IPv6)
  1287. return -1;
  1288. return ((IPv6Header *) pe)->getHopLimit();
  1289. }
  1290. void FPHost6::finish() {
  1291. /* These probes are likely to get an ICMPv6 error (allowing us to calculate
  1292. distance. */
  1293. const char * const DISTANCE_PROBE_NAMES[] = { "IE2", "NI", "U1" };
  1294. int distance = -1;
  1295. int hoplimit_distance = -1;
  1296. enum dist_calc_method distance_calculation_method = DIST_METHOD_NONE;
  1297. unsigned int i;
  1298. /* Calculate distance based on hop limit difference. */
  1299. for (i = 0; i < NELEMS(DISTANCE_PROBE_NAMES); i++) {
  1300. const FPProbe *probe;
  1301. const FPResponse *resp;
  1302. const PacketElement *probe_pe;
  1303. PacketElement *resp_pe;
  1304. int sent_ttl, rcvd_ttl;
  1305. const char *probe_name;
  1306. probe_name = DISTANCE_PROBE_NAMES[i];
  1307. probe = this->getProbe(probe_name);
  1308. resp = this->getResponse(probe_name);
  1309. if (probe == NULL || resp == NULL)
  1310. continue;
  1311. probe_pe = probe->getPacket();
  1312. if (probe_pe->protocol_id() != HEADER_TYPE_IPv6)
  1313. continue;
  1314. sent_ttl = ((IPv6Header *) probe_pe)->getHopLimit();
  1315. resp_pe = PacketParser::split(resp->buf, resp->len);
  1316. assert(resp_pe != NULL);
  1317. rcvd_ttl = get_encapsulated_hoplimit(resp_pe);
  1318. if (rcvd_ttl != -1) {
  1319. if (o.debugging > 1) {
  1320. log_write(LOG_PLAIN, "Hop limit distance from %s probe: %d - %d + 1 == %d\n",
  1321. probe_name, sent_ttl, rcvd_ttl, sent_ttl - rcvd_ttl + 1);
  1322. }
  1323. /* Set only if not already set. */
  1324. if (hoplimit_distance == -1)
  1325. hoplimit_distance = sent_ttl - rcvd_ttl + 1;
  1326. /* Special case: for the U1 probe, mark that we found the port closed. */
  1327. if (this->target_host->FPR->osscan_closedudpport == -1 && strcmp(probe_name, "U1") == 0) {
  1328. const PacketElement *udp;
  1329. u16 portno;
  1330. udp = probe_pe->getNextElement();
  1331. assert(udp != NULL);
  1332. assert(udp->protocol_id() == HEADER_TYPE_UDP);
  1333. portno = ((UDPHeader *) udp)->getDestinationPort();
  1334. this->target_host->FPR->osscan_closedudpport = portno;
  1335. }
  1336. }
  1337. PacketParser::freePacketChain(resp_pe);
  1338. }
  1339. if (islocalhost(this->target_host->TargetSockAddr())) {
  1340. /* scanning localhost */
  1341. distance = 0;
  1342. distance_calculation_method = DIST_METHOD_LOCALHOST;
  1343. } else if (this->target_host->directlyConnected()) {
  1344. /* on the same network segment */
  1345. distance = 1;
  1346. distance_calculation_method = DIST_METHOD_DIRECT;
  1347. } else if (hoplimit_distance != -1) {
  1348. distance = hoplimit_distance;
  1349. distance_calculation_method = DIST_METHOD_ICMP;
  1350. }
  1351. this->target_host->distance = this->target_host->FPR->distance = distance;
  1352. this->target_host->distance_calculation_method =
  1353. this->target_host->FPR->distance_calculation_method =
  1354. distance_calculation_method;
  1355. }
  1356. struct tcp_desc {
  1357. const char *id;
  1358. u16 win;
  1359. u8 flags;
  1360. u16 dstport;
  1361. u16 urgptr;
  1362. const char *opts;
  1363. unsigned int optslen;
  1364. };
  1365. static u8 get_hoplimit() {
  1366. if (o.ttl != -1)
  1367. return o.ttl;
  1368. else
  1369. return (get_random_uint() % 23) + 37;
  1370. }
  1371. static IPv6Header *make_tcp(const struct sockaddr_in6 *src,
  1372. const struct sockaddr_in6 *dst,
  1373. u32 fl, u16 win, u32 seq, u32 ack, u8 flags, u16 srcport, u16 dstport,
  1374. u16 urgptr, const char *opts, unsigned int optslen) {
  1375. IPv6Header *ip6;
  1376. TCPHeader *tcp;
  1377. /* Allocate an instance of the protocol headers */
  1378. ip6 = new IPv6Header();
  1379. tcp = new TCPHeader();
  1380. ip6->setSourceAddress(src->sin6_addr);
  1381. ip6->setDestinationAddress(dst->sin6_addr);
  1382. ip6->setFlowLabel(fl);
  1383. ip6->setHopLimit(get_hoplimit());
  1384. ip6->setNextHeader("TCP");
  1385. ip6->setNextElement(tcp);
  1386. tcp->setWindow(win);
  1387. tcp->setSeq(seq);
  1388. tcp->setAck(ack);
  1389. tcp->setFlags(flags);
  1390. tcp->setSourcePort(srcport);
  1391. tcp->setDestinationPort(dstport);
  1392. tcp->setUrgPointer(urgptr);
  1393. tcp->setOptions((u8 *) opts, optslen);
  1394. ip6->setPayloadLength(tcp->getLen());
  1395. tcp->setSum();
  1396. return ip6;
  1397. }
  1398. /* This method generates the list of OS detection probes to be sent to the
  1399. * target. It also sets up the list of responses. It is defined private
  1400. * because it is called by the constructor when the class is instantiated. */
  1401. int FPHost6::build_probe_list() {
  1402. #define OPEN 1
  1403. #define CLSD 0
  1404. /* TCP Options:
  1405. * S1-S6: six sequencing probes.
  1406. * TECN: ECN probe.
  1407. * T2-T7: other non-sequencing probes.
  1408. *
  1409. * option 0: WScale (10), Nop, MSS (1460), Timestamp, SackP
  1410. * option 1: MSS (1400), WScale (0), SackP, T(0xFFFFFFFF,0x0), EOL
  1411. * option 2: T(0xFFFFFFFF, 0x0), Nop, Nop, WScale (5), Nop, MSS (640)
  1412. * option 3: SackP, T(0xFFFFFFFF,0x0), WScale (10), EOL
  1413. * option 4: MSS (536), SackP, T(0xFFFFFFFF,0x0), WScale (10), EOL
  1414. * option 5: MSS (265), SackP, T(0xFFFFFFFF,0x0)
  1415. * option 6: WScale (10), Nop, MSS (1460), SackP, Nop, Nop
  1416. * option 7-11: WScale (10), Nop, MSS (265), T(0xFFFFFFFF,0x0), SackP
  1417. * option 12: WScale (15), Nop, MSS (265), T(0xFFFFFFFF,0x0), SackP */
  1418. const struct tcp_desc TCP_DESCS[] = {
  1419. { "S1", 1, 0x02, OPEN, 0,
  1420. "\x03\x03\x0A\x01\x02\x04\x05\xb4\x08\x0A\xff\xff\xff\xff\x00\x00\x00\x00\x04\x02", 20 },
  1421. { "S2", 63, 0x02, OPEN, 0,
  1422. "\x02\x04\x05\x78\x03\x03\x00\x04\x02\x08\x0A\xff\xff\xff\xff\x00\x00\x00\x00\x00", 20 },
  1423. { "S3", 4, 0x02, OPEN, 0,
  1424. "\x08\x0A\xff\xff\xff\xff\x00\x00\x00\x00\x01\x01\x03\x03\x05\x01\x02\x04\x02\x80", 20 },
  1425. { "S4", 4, 0x02, OPEN, 0,
  1426. "\x04\x02\x08\x0A\xff\xff\xff\xff\x00\x00\x00\x00\x03\x03\x0A\x00", 16 },
  1427. { "S5", 16, 0x02, OPEN, 0,
  1428. "\x02\x04\x02\x18\x04\x02\x08\x0A\xff\xff\xff\xff\x00\x00\x00\x00\x03\x03\x0A\x00", 20 },
  1429. { "S6", 512, 0x02, OPEN, 0,
  1430. "\x02\x04\x01\x09\x04\x02\x08\x0A\xff\xff\xff\xff\x00\x00\x00\x00", 16 },
  1431. { "TECN", 3, 0xc2, OPEN, 63477,
  1432. "\x03\x03\x0A\x01\x02\x04\x05\xb4\x04\x02\x01\x01", 12 },
  1433. { "T2", 128, 0x00, OPEN, 0,
  1434. "\x03\x03\x0A\x01\x02\x04\x01\x09\x08\x0A\xff\xff\xff\xff\x00\x00\x00\x00\x04\x02", 20 },
  1435. { "T3", 256, 0x2b, OPEN, 0,
  1436. "\x03\x03\x0A\x01\x02\x04\x01\x09\x08\x0A\xff\xff\xff\xff\x00\x00\x00\x00\x04\x02", 20 },
  1437. { "T4", 1024, 0x10, OPEN, 0,
  1438. "\x03\x03\x0A\x01\x02\x04\x01\x09\x08\x0A\xff\xff\xff\xff\x00\x00\x00\x00\x04\x02", 20 },
  1439. { "T5", 31337, 0x02, CLSD, 0,
  1440. "\x03\x03\x0A\x01\x02\x04\x01\x09\x08\x0A\xff\xff\xff\xff\x00\x00\x00\x00\x04\x02", 20 },
  1441. { "T6", 32768, 0x10, CLSD, 0,
  1442. "\x03\x03\x0A\x01\x02\x04\x01\x09\x08\x0A\xff\xff\xff\xff\x00\x00\x00\x00\x04\x02", 20 },
  1443. { "T7", 65535, 0x29, CLSD, 0,
  1444. "\x03\x03\x0f\x01\x02\x04\x01\x09\x08\x0A\xff\xff\xff\xff\x00\x00\x00\x00\x04\x02", 20 },
  1445. };
  1446. sockaddr_storage ss;
  1447. size_t slen = 0;
  1448. sockaddr_in6 *ss6 = (sockaddr_in6 *)&ss;
  1449. IPv6Header *ip6;
  1450. ICMPv6Header *icmp6;
  1451. UDPHeader *udp;
  1452. DestOptsHeader *dstopts;
  1453. RoutingHeader *routing;
  1454. HopByHopHeader *hopbyhop1, *hopbyhop2;
  1455. RawData *payload;
  1456. unsigned int i;
  1457. char payloadbuf[300];
  1458. assert(this->target_host != NULL);
  1459. /* Set timed TCP probes */
  1460. for (i = 0; i < NUM_FP_PROBES_IPv6_TCP && i < NUM_FP_TIMEDPROBES_IPv6; i++) {
  1461. /* If the probe is targeted to a TCP port and we don't have
  1462. * any port number for that particular state, skip the probe. */
  1463. if (TCP_DESCS[i].dstport == OPEN && this->open_port_tcp < 0)
  1464. continue;
  1465. if (TCP_DESCS[i].dstport == CLSD && this->closed_port_tcp < 0)
  1466. continue;
  1467. ip6 = make_tcp((struct sockaddr_in6 *) this->target_host->SourceSockAddr(),
  1468. (struct sockaddr_in6 *) this->target_host->TargetSockAddr(),
  1469. OSDETECT_FLOW_LABEL, TCP_DESCS[i].win, this->tcpSeqBase + i, get_random_u32(),
  1470. TCP_DESCS[i].flags, this->tcp_port_base + i,
  1471. TCP_DESCS[i].dstport == OPEN ? this->open_port_tcp : this->closed_port_tcp,
  1472. TCP_DESCS[i].urgptr, TCP_DESCS[i].opts, TCP_DESCS[i].optslen);
  1473. /* Store the probe in the list so we can send it later */
  1474. this->fp_probes[this->total_probes].host = this;
  1475. this->fp_probes[this->total_probes].setPacket(ip6);
  1476. this->fp_probes[this->total_probes].setProbeID(TCP_DESCS[i].id);
  1477. this->fp_probes[this->total_probes].setEthernet(this->target_host->SrcMACAddress(), this->target_host->NextHopMACAddress(), this->target_host->deviceName());
  1478. /* Mark as a timed probe. */
  1479. this->fp_probes[this->total_probes].setTimed();
  1480. this->timed_probes++;
  1481. this->total_probes++;
  1482. }
  1483. /* Set ICMPv6 probes */
  1484. memset(payloadbuf, 0, 120);
  1485. /* ICMP Probe #1: Echo Request with hop-by-hop options */
  1486. /* This one immediately follows the timed seq TCP probes, to allow testing for
  1487. shared flow label sequence. */
  1488. ip6 = new IPv6Header();
  1489. icmp6 = new ICMPv6Header();
  1490. hopbyhop1 = new HopByHopHeader();
  1491. payload = new RawData();
  1492. this->target_host->SourceSockAddr(&ss, &slen);
  1493. ip6->setSourceAddress(ss6->sin6_addr);
  1494. this->target_host->TargetSockAddr(&ss, &slen);
  1495. ip6->setDestinationAddress(ss6->sin6_addr);
  1496. ip6->setFlowLabel(OSDETECT_FLOW_LABEL);
  1497. ip6->setHopLimit(get_hoplimit());
  1498. ip6->setNextHeader((u8) HEADER_TYPE_IPv6_HOPOPT);
  1499. ip6->setNextElement(hopbyhop1);
  1500. hopbyhop1->setNextHeader(HEADER_TYPE_ICMPv6);
  1501. hopbyhop1->setNextElement(icmp6);
  1502. icmp6->setNextElement(payload);
  1503. payload->store((u8 *) payloadbuf, 120);
  1504. icmp6->setType(ICMPv6_ECHO);
  1505. icmp6->setCode(9); // But is supposed to be 0.
  1506. icmp6->setIdentifier(0xabcd);
  1507. icmp6->setSequence(this->icmp_seq_counter++);
  1508. icmp6->setTargetAddress(ss6->sin6_addr); // Should still contain target's addr
  1509. ip6->setPayloadLength();
  1510. icmp6->setSum();
  1511. this->fp_probes[this->total_probes].host = this;
  1512. this->fp_probes[this->total_probes].setPacket(ip6);
  1513. this->fp_probes[this->total_probes].setProbeID("IE1");
  1514. this->fp_probes[this->total_probes].setEthernet(this->target_host->SrcMACAddress(), this->target_host->NextHopMACAddress(), this->target_host->deviceName());
  1515. this->total_probes++;
  1516. /* ICMP Probe #2: Echo Request with badly ordered extension headers */
  1517. ip6 = new IPv6Header();
  1518. hopbyhop1 = new HopByHopHeader();
  1519. dstopts = new DestOptsHeader();
  1520. routing = new RoutingHeader();
  1521. hopbyhop2 = new HopByHopHeader();
  1522. icmp6 = new ICMPv6Header();
  1523. payload = new RawData();
  1524. this->target_host->SourceSockAddr(&ss, &slen);
  1525. ip6->setSourceAddress(ss6->sin6_addr);
  1526. this->target_host->TargetSockAddr(&ss, &slen);
  1527. ip6->setDestinationAddress(ss6->sin6_addr);
  1528. ip6->setFlowLabel(OSDETECT_FLOW_LABEL);
  1529. ip6->setHopLimit(get_hoplimit());
  1530. ip6->setNextHeader((u8) HEADER_TYPE_IPv6_HOPOPT);
  1531. ip6->setNextElement(hopbyhop1);
  1532. hopbyhop1->setNextHeader(HEADER_TYPE_IPv6_OPTS);
  1533. hopbyhop1->setNextElement(dstopts);
  1534. dstopts->setNextHeader(HEADER_TYPE_IPv6_ROUTE);
  1535. dstopts->setNextElement(routing);
  1536. routing->setNextHeader(HEADER_TYPE_IPv6_HOPOPT);
  1537. routing->setNextElement(hopbyhop2);
  1538. hopbyhop2->setNextHeader(HEADER_TYPE_ICMPv6);
  1539. hopbyhop2->setNextElement(icmp6);
  1540. icmp6->setType(ICMPv6_ECHO);
  1541. icmp6->setCode(0);
  1542. icmp6->setIdentifier(0xabcd);
  1543. icmp6->setSequence(this->icmp_seq_counter++);
  1544. icmp6->setTargetAddress(ss6->sin6_addr); // Should still contain target's addr
  1545. ip6->setPayloadLength();
  1546. icmp6->setSum();
  1547. this->fp_probes[this->total_probes].host = this;
  1548. this->fp_probes[this->total_probes].setPacket(ip6);
  1549. this->fp_probes[this->total_probes].setProbeID("IE2");
  1550. this->fp_probes[this->total_probes].setEthernet(this->target_host->SrcMACAddress(), this->target_host->NextHopMACAddress(), this->target_host->deviceName());
  1551. this->total_probes++;
  1552. /* ICMP Probe #3: Node Info Query (IPv4 addresses) */
  1553. ip6 = new IPv6Header();
  1554. icmp6 = new ICMPv6Header();
  1555. this->target_host->SourceSockAddr(&ss, &slen);
  1556. ip6->setSourceAddress(ss6->sin6_addr);
  1557. this->target_host->TargetSockAddr(&ss, &slen);
  1558. ip6->setDestinationAddress(ss6->sin6_addr);
  1559. ip6->setFlowLabel(OSDETECT_FLOW_LABEL);
  1560. ip6->setHopLimit(get_hoplimit());
  1561. ip6->setNextHeader("ICMPv6");
  1562. ip6->setNextElement(icmp6);
  1563. icmp6->setNextElement(payload);
  1564. payload->store((u8 *) &ss6->sin6_addr, IP6_ADDR_LEN);
  1565. icmp6->setType(ICMPv6_NODEINFOQUERY);
  1566. icmp6->setCode(ICMPv6_NODEINFOQUERY_IPv6ADDR);
  1567. icmp6->setQtype(NI_QTYPE_IPv4ADDRS);
  1568. icmp6->setA();
  1569. icmp6->setNonce((u8 *) "\x01\x02\x03\x04\x05\x06\x07\x0a");
  1570. icmp6->setSum();
  1571. ip6->setPayloadLength();
  1572. this->fp_probes[this->total_probes].host = this;
  1573. this->fp_probes[this->total_probes].setPacket(ip6);
  1574. this->fp_probes[this->total_probes].setProbeID("NI");
  1575. this->fp_probes[this->total_probes].setEthernet(this->target_host->SrcMACAddress(), this->target_host->NextHopMACAddress(), this->target_host->deviceName());
  1576. this->total_probes++;
  1577. /* ICMP Probe #4: Neighbor Solicitation. (only sent to on-link targets) */
  1578. if (this->target_host->directlyConnected()) {
  1579. ip6 = new IPv6Header();
  1580. icmp6 = new ICMPv6Header();
  1581. this->target_host->SourceSockAddr(&ss, &slen);
  1582. ip6->setSourceAddress(ss6->sin6_addr);
  1583. this->target_host->TargetSockAddr(&ss, &slen);
  1584. ip6->setDestinationAddress(ss6->sin6_addr);
  1585. ip6->setFlowLabel(OSDETECT_FLOW_LABEL);
  1586. /* RFC 2461 section 7.1.1: "A node MUST silently discard any received
  1587. Neighbor Solicitation messages that do not satisfy all of the following
  1588. validity checks: - The IP Hop Limit field has a value of 255 ... */
  1589. ip6->setHopLimit(255);
  1590. ip6->setNextHeader("ICMPv6");
  1591. ip6->setNextElement(icmp6);
  1592. icmp6->setType(ICMPv6_NGHBRSOLICIT);
  1593. icmp6->setCode(0);
  1594. icmp6->setTargetAddress(ss6->sin6_addr); // Should still contain target's addr
  1595. icmp6->setSum();
  1596. ip6->setPayloadLength();
  1597. this->fp_probes[this->total_probes].host = this;
  1598. this->fp_probes[this->total_probes].setPacket(ip6);
  1599. this->fp_probes[this->total_probes].setProbeID("NS");
  1600. this->fp_probes[this->total_probes].setEthernet(this->target_host->SrcMACAddress(), this->target_host->NextHopMACAddress(), this->target_host->deviceName());
  1601. this->total_probes++;
  1602. }
  1603. /* Set UDP probes */
  1604. memset(payloadbuf, 0x43, 300);
  1605. ip6 = new IPv6Header();
  1606. udp = new UDPHeader();
  1607. payload = new RawData();
  1608. this->target_host->SourceSockAddr(&ss, &slen);
  1609. ip6->setSourceAddress(ss6->sin6_addr);
  1610. this->target_host->TargetSockAddr(&ss, &slen);
  1611. ip6->setDestinationAddress(ss6->sin6_addr);
  1612. ip6->setFlowLabel(OSDETECT_FLOW_LABEL);
  1613. ip6->setHopLimit(get_hoplimit());
  1614. ip6->setNextHeader("UDP");
  1615. ip6->setNextElement(udp);
  1616. udp->setSourcePort(this->udp_port_base);
  1617. udp->setDestinationPort(this->closed_port_udp);
  1618. payload->store((u8 *) payloadbuf, 300);
  1619. udp->setNextElement(payload);
  1620. udp->setTotalLength();
  1621. udp->setSum();
  1622. ip6->setPayloadLength(udp->getLen());
  1623. this->fp_probes[this->total_probes].host = this;
  1624. this->fp_probes[this->total_probes].setPacket(ip6);
  1625. this->fp_probes[this->total_probes].setProbeID("U1");
  1626. this->fp_probes[this->total_probes].setEthernet(this->target_host->SrcMACAddress(), this->target_host->NextHopMACAddress(), this->target_host->deviceName());
  1627. this->total_probes++;
  1628. /* Set TECN probe */
  1629. if ((TCP_DESCS[i].dstport == OPEN && this->open_port_tcp >= 0)
  1630. || (TCP_DESCS[i].dstport == CLSD && this->closed_port_tcp >= 0)) {
  1631. ip6 = make_tcp((struct sockaddr_in6 *) this->target_host->SourceSockAddr(),
  1632. (struct sockaddr_in6 *) this->target_host->TargetSockAddr(),
  1633. OSDETECT_FLOW_LABEL, TCP_DESCS[i].win, this->tcpSeqBase + i, 0,
  1634. TCP_DESCS[i].flags, tcp_port_base + i,
  1635. TCP_DESCS[i].dstport == OPEN ? this->open_port_tcp : this->closed_port_tcp,
  1636. TCP_DESCS[i].urgptr, TCP_DESCS[i].opts, TCP_DESCS[i].optslen);
  1637. /* Store the probe in the list so we can send it later */
  1638. this->fp_probes[this->total_probes].host = this;
  1639. this->fp_probes[this->total_probes].setPacket(ip6);
  1640. this->fp_probes[this->total_probes].setProbeID(TCP_DESCS[i].id);
  1641. this->fp_probes[this->total_probes].setEthernet(this->target_host->SrcMACAddress(), this->target_host->NextHopMACAddress(), this->target_host->deviceName());
  1642. this->total_probes++;
  1643. }
  1644. i++;
  1645. /* Set untimed TCP probes */
  1646. for (; i < NUM_FP_PROBES_IPv6_TCP; i++) {
  1647. /* If the probe is targeted to a TCP port and we don't have
  1648. * any port number for that particular state, skip the probe. */
  1649. if (TCP_DESCS[i].dstport == OPEN && this->open_port_tcp < 0)
  1650. continue;
  1651. if (TCP_DESCS[i].dstport == CLSD && this->closed_port_tcp < 0)
  1652. continue;
  1653. ip6 = make_tcp((struct sockaddr_in6 *) this->target_host->SourceSockAddr(),
  1654. (struct sockaddr_in6 *) this->target_host->TargetSockAddr(),
  1655. OSDETECT_FLOW_LABEL, TCP_DESCS[i].win, this->tcpSeqBase + i, get_random_u32(),
  1656. TCP_DESCS[i].flags, tcp_port_base + i,
  1657. TCP_DESCS[i].dstport == OPEN ? this->open_port_tcp : this->closed_port_tcp,
  1658. TCP_DESCS[i].urgptr, TCP_DESCS[i].opts, TCP_DESCS[i].optslen);
  1659. /* Store the probe in the list so we can send it later */
  1660. this->fp_probes[this->total_probes].host = this;
  1661. this->fp_probes[this->total_probes].setPacket(ip6);
  1662. this->fp_probes[this->total_probes].setProbeID(TCP_DESCS[i].id);
  1663. this->fp_probes[this->total_probes].setEthernet(this->target_host->SrcMACAddress(), this->target_host->NextHopMACAddress(), this->target_host->deviceName());
  1664. this->total_probes++;
  1665. }
  1666. return OP_SUCCESS;
  1667. }
  1668. /* Indicates whether the OS detection process has finished for this host.
  1669. * Note that when "true" is returned the caller cannot assume that the host
  1670. * has been accurately fingerprinted, only that the OS detection process
  1671. * was carried out. In other words, when true is returned it means that the
  1672. * fingerprinting engine sent all OS detection probes, performed the necessary
  1673. * retransmission and attempted to capture the target's replies. In order to
  1674. * check if the detection was successful (if we actually know what OS the target
  1675. * is running), the status() method should be used. */
  1676. bool FPHost6::done() {
  1677. if (this->probes_sent == this->total_probes) {
  1678. if (this->probes_answered + this->probes_unanswered == this->total_probes)
  1679. return true;
  1680. }
  1681. return false;
  1682. }
  1683. /* Asks the host to schedule the transmission of probes (if they need to do so).
  1684. * This method is called repeatedly by the FPEngine to make the host request
  1685. * the probe transmissions that it needs. From the hosts point of view, it
  1686. * determines if new transmissions need to be scheduled based on the number
  1687. * of probes sent, the number of answers received, etc. Also, in order to
  1688. * transmit a packet, the network controller must approve it (hosts may not
  1689. * be able to send packets any time they want due to congestion control
  1690. * restrictions). */
  1691. int FPHost6::schedule() {
  1692. struct timeval now;
  1693. unsigned int timed_probes_answered = 0;
  1694. unsigned int timed_probes_timedout = 0;
  1695. /* The first time we are asked to schedule a packet, register ourselves in
  1696. * the network controller so it can call us back when packets that match our
  1697. * target are captured. */
  1698. if (this->netctl_registered == false && this->netctl != NULL) {
  1699. this->netctl->register_caller(this);
  1700. this->netctl_registered = true;
  1701. }
  1702. /* Make sure we have things to do, otherwise, just return. */
  1703. if (this->detection_done || (this->probes_answered + this->probes_unanswered == this->total_probes)) {
  1704. /* Update our internal state to indicate we have finished */
  1705. if (!this->detection_done)
  1706. this->set_done_and_wrap_up();
  1707. return OP_SUCCESS;
  1708. }
  1709. /* If we have not yet sent the timed probes (and we have timed probes to send)
  1710. * request permission from the network controller and schedule the transmission
  1711. * for all of them, 100ms apart from each other. We don't want all the hosts
  1712. * to schedule their transmission for the same exact time so we add a random
  1713. * offset (between 0 and 100ms) to the first transmission. All subsequent
  1714. * ones are sent 100ms apart from the first. Note that if we did not find
  1715. * and open port, then we just don't send the timed probes. */
  1716. if (this->timed_probes > 0 && this->timedprobes_sent == false) {
  1717. if (o.debugging > 3)
  1718. log_write(LOG_PLAIN, "[%s] %u Tx slots requested\n", this->target_host->targetipstr(), this->timed_probes);
  1719. if (this->netctl->request_slots(this->timed_probes) == true) {
  1720. if (o.debugging > 3)
  1721. log_write(LOG_PLAIN, "[%s] Slots granted!\n", this->target_host->targetipstr());
  1722. this->timedprobes_sent = true;
  1723. int whentostart = get_random_u16()%100;
  1724. for (size_t i = 0; i < this->timed_probes; i++) {
  1725. this->netctl->scheduleProbe(&(this->fp_probes[i]), whentostart + i*100);
  1726. this->probes_sent++;
  1727. }
  1728. return OP_SUCCESS;
  1729. }
  1730. if (o.debugging > 3)
  1731. log_write(LOG_PLAIN, "[%s] Slots denied.\n", this->target_host->targetipstr());
  1732. return OP_FAILURE;
  1733. } else if (this->timed_probes > 0 && this->timedprobes_sent && this->fp_probes[this->timed_probes - 1].getTimeSent().tv_sec == 0) {
  1734. /* If the sent time for the last timed probe has not been set, it means
  1735. * that we haven't sent all the timed probes yet, so we don't schedule
  1736. * any other probes, we just wait until our schedule() gets called again.
  1737. * We do this because we don't want to mess with the target's stack
  1738. * in the middle of our timed probes. Otherwise, we can screw up the
  1739. * TCP sequence generation tests, etc. We also get here when timed probes
  1740. * suffer a retransmission. In that case, we also stop sending packets
  1741. * to our target until we have sent all of them. */
  1742. if (o.debugging > 3)
  1743. log_write(LOG_PLAIN, "[%s] Waiting for all timed probes to be sent...\n", this->target_host->targetipstr());
  1744. return OP_FAILURE;
  1745. } else {
  1746. /* If we get here it means that either we have sent all the timed probes or
  1747. * we don't even have to send them (because no open port was found).
  1748. * At this point if we have other probes to transmit, schedule the next one.
  1749. * Also, check for timedout probes so we can retransmit one of them. */
  1750. if (o.debugging > 3 && this->timed_probes > 0 && this->probes_sent == this->timed_probes)
  1751. log_write(LOG_PLAIN, "[%s] All timed probes have been sent.\n", this->target_host->targetipstr());
  1752. if (this->probes_sent < this->total_probes) {
  1753. if (this->netctl->request_slots(1) == true) {
  1754. if (o.debugging > 3)
  1755. log_write(LOG_PLAIN, "[%s] Scheduling probe %s\n", this->target_host->targetipstr(), this->fp_probes[this->probes_sent].getProbeID());
  1756. this->netctl->scheduleProbe(&(this->fp_probes[this->probes_sent]), 0);
  1757. this->probes_sent++;
  1758. } else {
  1759. if (o.debugging > 3)
  1760. log_write(LOG_PLAIN, "[%s] Can't schedule probe %s\n", this->target_host->targetipstr(), this->fp_probes[this->probes_sent].getProbeID());
  1761. }
  1762. }
  1763. /**************************************************************************
  1764. * PROBE TIMEOUT HANDLING *
  1765. **************************************************************************/
  1766. if (o.debugging > 3)
  1767. log_write(LOG_PLAIN, "[%s] Checking for regular probe timeouts...\n", this->target_host->targetipstr());
  1768. /* Determine if some regular probe (not timed probes) has timedout. In that
  1769. * case, choose some outstanding probe to retransmit. */
  1770. gettimeofday(&now, NULL);
  1771. for (unsigned int i = this->timed_probes; i < this->probes_sent; i++) {
  1772. /* Skip probes that have already been answered */
  1773. if (this->fp_responses[i]) {
  1774. continue;
  1775. }
  1776. /* Skip probes that we have scheduled but have not been yet transmitted */
  1777. if (this->fp_probes[i].getTimeSent().tv_sec == 0)
  1778. continue;
  1779. /* Skip probes for which we didn't get a response after all
  1780. * retransmissions. */
  1781. if (this->fp_probes[i].probeFailed()) {
  1782. continue;
  1783. }
  1784. /* Check if the probe timedout */
  1785. if (TIMEVAL_SUBTRACT(now, this->fp_probes[i].getTimeSent()) >= this->rto) {
  1786. /* If we have reached the maximum number of retransmissions, mark the
  1787. * probe as failed. Otherwise, schedule its transmission. */
  1788. if (this->fp_probes[i].getRetransmissions() >= o.maxOSTries()) {
  1789. if (o.debugging > 3) {
  1790. log_write(LOG_PLAIN, "[%s] Probe #%d (%s) failed after %d retransmissions.\n",
  1791. this->target_host->targetipstr(), i, this->fp_probes[i].getProbeID(),
  1792. this->fp_probes[i].getRetransmissions());
  1793. }
  1794. this->fp_probes[i].setFailed();
  1795. /* Let the network controller know that we don't expect a response
  1796. * for the probe anymore so the number of outstanding probes is
  1797. * reduced and the effective window is incremented. */
  1798. this->netctl->cc_report_final_timeout();
  1799. /* Also, increase our unanswered counter so we can later decide
  1800. * if the process has finished. */
  1801. this->probes_unanswered++;
  1802. continue;
  1803. /* Otherwise, retransmit the packet.*/
  1804. } else {
  1805. /* Note that we do not request permission to re-transmit (we don't
  1806. * call request_slots(). In TCP one can retransmit timedout
  1807. * probes even when CWND is zero, as CWND only applies for new packets. */
  1808. if (o.debugging > 3) {
  1809. log_write(LOG_PLAIN, "[%s] Retransmitting probe #%d (%s) (retransmitted %d times already).\n",
  1810. this->target_host->targetipstr(), i, this->fp_probes[i].getProbeID(),
  1811. this->fp_probes[i].getRetransmissions());
  1812. }
  1813. this->fp_probes[i].incrementRetransmissions();
  1814. this->netctl->scheduleProbe(&(this->fp_probes[i]), 0);
  1815. break;
  1816. }
  1817. }
  1818. }
  1819. /* Now let's check the state of the timed probes. We iterate over the list
  1820. * of timed probes to count how many have been answered and how many have
  1821. * timed out. If answered + timeout == total_timed_probes, it's time to
  1822. * retransmit them. */
  1823. /* Make sure we are actually sending timed probes. */
  1824. if (this->timed_probes <= 0)
  1825. return OP_SUCCESS;
  1826. bool timed_failed = false;
  1827. if (o.debugging > 3)
  1828. log_write(LOG_PLAIN, "[%s] Checking for timed probe timeouts...\n", this->target_host->targetipstr());
  1829. for (unsigned int i = 0; i < this->timed_probes; i++) {
  1830. assert(this->fp_probes[i].isTimed());
  1831. /* Skip probes that have already been answered, but count how many of
  1832. * them are there. */
  1833. if (this->fp_responses[i]) {
  1834. timed_probes_answered++;
  1835. continue;
  1836. }
  1837. /* If there is some timed probe for which we have already scheduled its
  1838. * retransmission but it hasn't been sent yet, break the loop. We don't
  1839. * have to worry about retransmitting these probes yet.*/
  1840. if (this->fp_probes[i].getTimeSent().tv_sec == 0)
  1841. return OP_SUCCESS;
  1842. /* If we got a total timeout for any of the timed probes, we shouldn't
  1843. * attempt more retransmissions. We set a flag to indicate that but we
  1844. * still stay in the loop because we want to mark as "failed" any other
  1845. * probes we have not yet checked. */
  1846. if (this->fp_probes[i].probeFailed()) {
  1847. timed_failed = true;
  1848. continue;
  1849. }
  1850. /* Now check if the timed probe has timed out. If it suffered a total
  1851. * time out (max retransmissions done and still no answer) then mark
  1852. * it as such. Otherwise, count it so we can retransmit the whole
  1853. * group of timed probes later if appropriate. */
  1854. if (TIMEVAL_SUBTRACT(now, this->fp_probes[i].getTimeSent()) >= this->rto) {
  1855. if (o.debugging > 3) {
  1856. log_write(LOG_PLAIN, "[%s] timed probe %d (%s) timedout\n",
  1857. this->target_host->targetipstr(), i, this->fp_probes[i].getProbeID());
  1858. }
  1859. if (this->fp_probes[i].getRetransmissions() >= o.maxOSTries()) {
  1860. if (o.debugging > 3)
  1861. log_write(LOG_PLAIN, "[%s] Timed probe #%d (%s) failed after %d retransmissions.\n", this->target_host->targetipstr(), i, this->fp_probes[i].getProbeID(), this->fp_probes[i].getRetransmissions());
  1862. this->fp_probes[i].setFailed();
  1863. /* Let the network controller know that we don't expect a response
  1864. * for the probe anymore so the number of outstanding probes is
  1865. * reduced and the effective window is incremented. */
  1866. this->netctl->cc_report_final_timeout();
  1867. /* Also, increase our unanswered counter so we can later decide
  1868. * if the process has finished. */
  1869. this->probes_unanswered++;
  1870. } else {
  1871. if (o.debugging > 3)
  1872. log_write(LOG_PLAIN, "[%s] Timed probe #%d (%s) has timed out (%d retransmissions done).\n", this->target_host->targetipstr(), i, this->fp_probes[i].getProbeID(), this->fp_probes[i].getRetransmissions());
  1873. timed_probes_timedout++;
  1874. }
  1875. }
  1876. }
  1877. if (o.debugging > 3)
  1878. log_write(LOG_PLAIN, "[%s] Timed_probes=%d, answered=%u, timedout=%u\n", this->target_host->targetipstr(), this->timed_probes, timed_probes_answered, timed_probes_timedout);
  1879. /* If the probe that has timed out is a "timed probe" it means that
  1880. * we need to retransmit all timed probes, not only this one. For
  1881. * that, we wait until all timed probes have either timed out or
  1882. * been responded. When that happens, we do the following:
  1883. * 1) Store the responses we have received the last time we sent
  1884. * the timed probes in an aux array (this->aux_resp).
  1885. * 2) Clear the responses to the timed probes from the main
  1886. * response array (this->fp_responses).
  1887. * 3) Schedule the retransmission of all timed probes, 100ms apart. */
  1888. if (this->timed_probes > 0 && timed_failed == false && timed_probes_timedout > 0 && (timed_probes_answered + timed_probes_timedout == this->timed_probes)) {
  1889. /* Count the number of responses we have now and the number
  1890. * of responses we stored in the aux buffer last time. */
  1891. unsigned int responses_stored = 0;
  1892. unsigned int responses_now = 0;
  1893. for (unsigned int j = 0; j < this->timed_probes; j++) {
  1894. if (this->aux_resp[j] != NULL)
  1895. responses_stored++;
  1896. if (this->fp_responses[j] != NULL)
  1897. responses_now++;
  1898. }
  1899. /* If now we have more responses than before, copy our current
  1900. * set of responses to the aux array. Otherwise, just
  1901. * delete the current set of responses. */
  1902. for (unsigned int k = 0; k < this->timed_probes; k++) {
  1903. if (responses_now > responses_stored) {
  1904. /* Free previous allocations */
  1905. if (this->aux_resp[k] != NULL) {
  1906. delete this->aux_resp[k];
  1907. }
  1908. /* Move the current response to the aux array */
  1909. this->aux_resp[k] = this->fp_responses[k];
  1910. this->fp_responses[k] = NULL;
  1911. } else {
  1912. delete this->fp_responses[k];
  1913. this->fp_responses[k] = NULL;
  1914. }
  1915. }
  1916. /* Update answer count because now we expect new answers to the timed probes. */
  1917. assert(((int)this->probes_answered - (int)timed_probes_answered) >= 0);
  1918. this->probes_answered-= timed_probes_answered;
  1919. if (o.debugging > 3)
  1920. log_write(LOG_PLAIN, "[%s] Adjusting answer count: before=%d, after=%d\n", this->target_host->targetipstr(), this->probes_answered + timed_probes_answered, this->probes_answered);
  1921. /* Finally do the actual retransmission. Like the first time,
  1922. * we schedule them 100ms apart, starting at same random point
  1923. * between right now and 99ms. */
  1924. int whentostart = get_random_u16()%100;
  1925. for (size_t l = 0; l < this->timed_probes; l++) {
  1926. this->fp_probes[l].incrementRetransmissions();
  1927. this->netctl->scheduleProbe(&(this->fp_probes[l]), whentostart + l*100);
  1928. }
  1929. if (o.debugging > 3 && this->timed_probes > 0)
  1930. log_write(LOG_PLAIN, "[%s] Retransmitting timed probes (rcvd_before=%u, rcvd_now=%u times=%d).\n", this->target_host->targetipstr(), responses_stored, responses_now, this->fp_probes[0].getRetransmissions());
  1931. /* Reset our local counters. */
  1932. timed_probes_answered = 0;
  1933. timed_probes_timedout = 0;
  1934. }
  1935. }
  1936. return OP_FAILURE;
  1937. }
  1938. /* This method is called when we detect that the OS detection process for this
  1939. * host is completed. It basically updates the host's internal state to
  1940. * indicate that the processed finished and unregisters the host from the
  1941. * network controller so we don't get any more callbacks. Here we also handle
  1942. * the special case of the retransmitted "timed probes". When we have to
  1943. * retransmit such probes, we usually have two sets of responses: the ones we
  1944. * got for the last retransmission, and the ones we got in the best try before
  1945. * that. So what we have to do is to decide which set is the best and discard
  1946. * the other one.*/
  1947. int FPHost6::set_done_and_wrap_up() {
  1948. assert(this->probes_answered + this->probes_unanswered == this->total_probes);
  1949. /* Inform the network controller that we do not wish to continue
  1950. * receiving callbacks (it could happen if the system had some other
  1951. * connections established with the target) */
  1952. this->netctl->unregister_caller(this);
  1953. /* Set up an internal flag to indicate we have finished */
  1954. this->detection_done = true;
  1955. /* Check the state of the timed probe retransmissions. In particular if we
  1956. * retransmitted timed probes, we should have two sets of responses,
  1957. * the ones we got last time we retransmitted, and the best set of responses
  1958. * we got out of all previous retransmissions but the last one. So now, we
  1959. * determine which set is the best and discard the other one. Btw, none of
  1960. * these loops run if timed_probes == 0, so it's safe in all cases. */
  1961. /* First count the number of responses in each set. */
  1962. unsigned int stored = 0;
  1963. unsigned int current = 0;
  1964. for (unsigned int i = 0; i < this->timed_probes; i++) {
  1965. if (this->aux_resp[i] != NULL)
  1966. stored++;
  1967. if (this->fp_responses[i] != NULL)
  1968. current++;
  1969. }
  1970. /* If we got more responses in a previous try, use them and get rid of
  1971. * the current ones. */
  1972. if (stored > current) {
  1973. for (unsigned int i = 0; i < this->timed_probes; i++) {
  1974. if (this->fp_responses[i] != NULL)
  1975. delete this->fp_responses[i];
  1976. this->fp_responses[i] = this->aux_resp[i];
  1977. this->aux_resp[i] = NULL;
  1978. }
  1979. /* Otherwise, get rid of the stored responses, use the current set */
  1980. } else {
  1981. for (unsigned int i = 0; i < this->timed_probes; i++) {
  1982. if (this->aux_resp[i] != NULL) {
  1983. delete this->aux_resp[i];
  1984. this->aux_resp[i] = NULL;
  1985. }
  1986. }
  1987. }
  1988. return OP_SUCCESS;
  1989. }
  1990. /* This function is called by the network controller every time a packet of
  1991. * interest is captured. A "packet of interest" is a packet whose source
  1992. * address matches the IP address of the target associated with the FPHost
  1993. * instance. Inside the method, the received packet is processed in order to
  1994. * determine if it corresponds to a response to a previous FPProbe sent to
  1995. * that target. If the packet is a proper response, it will be stored for
  1996. * later processing, as it is part of the target's stack fingerprint. Returns
  1997. * a positive integer when the supplied packet could be successfully matched with
  1998. * a previously sent probe. The returned value indicates how many times the
  1999. * probe was sent before getting a reply: a return value of 1 means that we
  2000. * got a normal reply, value two means that we had to retransmit the packet
  2001. * once to get the reply, and so on. A return value of zero is a special case
  2002. * that indicates that the supplied packet is a response to a timed probed
  2003. * for which we already had received a reply in the past. This is necessary
  2004. * because we need to indicate the network controller that this is not a normal
  2005. * response to a retransmitted probe, and so, it should not be used to alter
  2006. * congestion control parameters. A negative return value indicates that the
  2007. * supplied packet is not a response to any probe sent by this host. */
  2008. int FPHost6::callback(const u8 *pkt, size_t pkt_len, const struct timeval *tv) {
  2009. PacketElement *rcvd = NULL;
  2010. /* Dummy packet to ensure destruction of rcvd. */
  2011. FPPacket dummy;
  2012. bool match_found = false;
  2013. int times_tx = 0;
  2014. /* Make sure we still expect callbacks */
  2015. if (this->detection_done)
  2016. return -1;
  2017. if (o.debugging > 3)
  2018. log_write(LOG_PLAIN, "[%s] Captured %lu bytes\n", this->target_host->targetipstr(), (unsigned long)pkt_len);
  2019. /* Convert the ugly raw buffer into a nice chain of PacketElement objects, so
  2020. * it's easier to parse the captured packet */
  2021. if ((rcvd = PacketParser::split(pkt, pkt_len, false)) == NULL)
  2022. return -2;
  2023. dummy.setPacket(rcvd);
  2024. /* Iterate over the list of sent probes and determine if the captured
  2025. * packet is a response to one of them. */
  2026. for (unsigned int i = 0; i < this->probes_sent; i++) {
  2027. /* Skip probes for which we already got a response */
  2028. if (this->fp_responses[i])
  2029. continue;
  2030. /* See if the received packet is a response to a probe */
  2031. if (this->fp_probes[i].isResponse(rcvd)) {
  2032. struct timeval now, time_sent;
  2033. gettimeofday(&now, NULL);
  2034. this->fp_responses[i] = new FPResponse(this->fp_probes[i].getProbeID(),
  2035. pkt, pkt_len, fp_probes[i].getTimeSent(), *tv);
  2036. this->fp_probes[i].incrementReplies();
  2037. match_found = true;
  2038. /* If the response that we've received is for a timed probe, we
  2039. * need to do a special handling. We don't want to report that
  2040. * we've received a response after N retransmissions because we
  2041. * may have re-sent the packet even if we got a response in the past.
  2042. * This happens when one of the timed probes times out and we
  2043. * retransmit all of them. We don't want the network controller to
  2044. * think there is congestion, so we only return the number of
  2045. * retransmissions if we didn't get a response before and we did now. */
  2046. if (this->fp_probes[i].isTimed() && this->fp_probes[i].getRetransmissions() > 0 && this->fp_probes[i].getReplies() > 1) {
  2047. times_tx = 0; // Special case.
  2048. } else {
  2049. times_tx = this->fp_probes[i].getRetransmissions()+1;
  2050. }
  2051. this->probes_answered++;
  2052. /* Recompute the Retransmission Timeout based on this new RTT observation. */
  2053. time_sent = this->fp_probes[i].getTimeSent();
  2054. assert(time_sent.tv_sec > 0);
  2055. this->update_RTO(TIMEVAL_SUBTRACT(now, time_sent), this->fp_probes[i].getRetransmissions() != 0);
  2056. break;
  2057. }
  2058. }
  2059. if (match_found) {
  2060. if (o.packetTrace()) {
  2061. log_write(LOG_PLAIN, "RCVD ");
  2062. rcvd->print(stdout, LOW_DETAIL);
  2063. log_write(LOG_PLAIN, "\n");
  2064. }
  2065. /* Here, check if with this match we completed the OS detection */
  2066. if (this->probes_answered + this->probes_unanswered == this->total_probes) {
  2067. /* Update our internal state to indicate we have finished */
  2068. this->set_done_and_wrap_up();
  2069. }
  2070. /* Return the number of times that the packet was transmitted before
  2071. * getting the reply. */
  2072. return times_tx;
  2073. } else {
  2074. return -3;
  2075. }
  2076. }
  2077. const FPProbe *FPHost6::getProbe(const char *id) {
  2078. unsigned int i;
  2079. for (i = 0; i < NUM_FP_PROBES_IPv6; i++) {
  2080. if (!this->fp_probes[i].is_set())
  2081. continue;
  2082. if (strcmp(this->fp_probes[i].getProbeID(), id) == 0)
  2083. return &this->fp_probes[i];
  2084. }
  2085. return NULL;
  2086. }
  2087. const FPResponse *FPHost6::getResponse(const char *id) {
  2088. unsigned int i;
  2089. for (i = 0; i < NUM_FP_PROBES_IPv6; i++) {
  2090. if (this->fp_responses[i] == NULL)
  2091. continue;
  2092. if (strcmp(this->fp_responses[i]->probe_id, id) == 0)
  2093. return this->fp_responses[i];
  2094. }
  2095. return NULL;
  2096. }
  2097. /******************************************************************************
  2098. * Implementation of class FPPacket. *
  2099. ******************************************************************************/
  2100. FPPacket::FPPacket() {
  2101. this->pkt = NULL;
  2102. this->__reset();
  2103. }
  2104. FPPacket::~FPPacket() {
  2105. this->__reset();
  2106. }
  2107. /* Resets all internal state, freeing any previously stored packets */
  2108. void FPPacket::__reset() {
  2109. this->link_eth = false;
  2110. memset(&(this->eth_hdr), 0, sizeof(struct eth_nfo));
  2111. PacketElement *me = this->pkt, *aux = NULL;
  2112. while (me != NULL) {
  2113. aux = me->getNextElement();
  2114. delete me;
  2115. me = aux;
  2116. }
  2117. this->pkt = NULL;
  2118. memset(&this->pkt_time, 0, sizeof(struct timeval));
  2119. }
  2120. /* Returns true if the FPPacket has been associated with a packet (through a
  2121. * call to setPacket(). This is equivalent to the following conditional:
  2122. * fppacket.getPacket() != NULL */
  2123. bool FPPacket::is_set() const {
  2124. if (this->pkt != NULL)
  2125. return true;
  2126. else
  2127. return false;
  2128. }
  2129. /* Associates de FPPacket instance with the first protocol header of a networkj
  2130. * packet. Such header may be linked to others through the setNextElement()
  2131. * mechanism. Note that FPPacket does NOT make a copy of the contents of the
  2132. * supplied pointer, it just stores the memory address. Therefore, the caller
  2133. * MUST ensure that the supplied pointer remains valid during the lifetime of
  2134. * the FPPacket instance.
  2135. *
  2136. * After calling this function, the FPPacket takes ownership of pkt and will
  2137. * delete pkt in its destructor. */
  2138. int FPPacket::setPacket(PacketElement *pkt) {
  2139. assert(pkt != NULL);
  2140. this->pkt = pkt;
  2141. return OP_SUCCESS;
  2142. }
  2143. /* Returns a newly allocated byte array with packet contents. The caller is
  2144. * responsible for freeing the buffer. */
  2145. u8 *FPPacket::getPacketBuffer(size_t *pkt_len) const {
  2146. u8 *pkt_buff;
  2147. pkt_buff = (u8 *)safe_malloc(this->pkt->getLen());
  2148. this->pkt->dumpToBinaryBuffer(pkt_buff, this->pkt->getLen());
  2149. *pkt_len = (size_t)this->pkt->getLen();
  2150. return pkt_buff;
  2151. }
  2152. /* Returns a pointer to first header of the packet associated with the FPPacket
  2153. * instance. Note that this method will return NULL unless a previous call to
  2154. * setPacket() has been made. */
  2155. const PacketElement *FPPacket::getPacket() const {
  2156. return this->pkt;
  2157. }
  2158. /* Returns the length of the packet associated with the FPPacket instance. Note
  2159. * that this method will return zero unless an actual packet was associated
  2160. * with the FPPacket object through a call to setPacket(). */
  2161. size_t FPPacket::getLength() const {
  2162. if (this->pkt != NULL)
  2163. return this->pkt->getLen();
  2164. else
  2165. return 0;
  2166. }
  2167. /* This method associates some link layer information with the packet. If
  2168. * sending at the ethernet level is not required, just call it passing NULL
  2169. * values, like this: instance.setEthernet(NULL, NULL, NULL);
  2170. * Otherwise, pass the source address, the next hop address and the name of
  2171. * the network interface the packet should be injected through. */
  2172. int FPPacket::setEthernet(const u8 *src_mac, const u8 *dst_mac, const char *devname) {
  2173. if (src_mac == NULL || dst_mac == NULL) {
  2174. memset(&(this->eth_hdr), 0, sizeof(struct eth_nfo));
  2175. this->link_eth = false;
  2176. return OP_FAILURE;
  2177. }
  2178. memcpy(this->eth_hdr.srcmac, src_mac, 6);
  2179. memcpy(this->eth_hdr.dstmac, dst_mac, 6);
  2180. this->link_eth = true;
  2181. if (devname != NULL) {
  2182. strncpy(this->eth_hdr.devname, devname, sizeof(this->eth_hdr.devname)-1);
  2183. if ((this->eth_hdr.ethsd = eth_open_cached(devname)) == NULL)
  2184. fatal("%s: Failed to open ethernet device (%s)", __func__, devname);
  2185. } else {
  2186. this->eth_hdr.devname[0] = '\0';
  2187. this->eth_hdr.ethsd = NULL;
  2188. }
  2189. return OP_SUCCESS;
  2190. }
  2191. /* Returns an eth_nfo structure that contains the necessary parameters to
  2192. * allow the transmission of the packet at the Ethernet level. Note that
  2193. * such structure is only returned if a previous call to setEthernet() has
  2194. * been made. If it hasn't, this means that the packet should be sent at
  2195. * the IP layer, and only NULL will be returned. */
  2196. const struct eth_nfo *FPPacket::getEthernet() const {
  2197. if (this->link_eth == true)
  2198. return &(this->eth_hdr);
  2199. else
  2200. return NULL;
  2201. }
  2202. /* Sets the internal time holder to the current time. */
  2203. int FPPacket::setTime(const struct timeval *tv) {
  2204. if (tv != NULL) {
  2205. this->pkt_time = *tv;
  2206. return 0;
  2207. } else {
  2208. return gettimeofday(&this->pkt_time, NULL);
  2209. }
  2210. }
  2211. /* Returns the value of the internal time holder */
  2212. struct timeval FPPacket::getTime() const {
  2213. return this->pkt_time;
  2214. }
  2215. /* Sets the internal time holder to zero. */
  2216. int FPPacket::resetTime() {
  2217. memset(&this->pkt_time, 0, sizeof(struct timeval));
  2218. return OP_SUCCESS;
  2219. }
  2220. /******************************************************************************
  2221. * Implementation of class FPProbe. *
  2222. ******************************************************************************/
  2223. FPProbe::FPProbe() {
  2224. this->probe_id = NULL;
  2225. this->host = NULL;
  2226. this->reset();
  2227. }
  2228. FPProbe::~FPProbe() {
  2229. if (this->probe_id != NULL)
  2230. free(this->probe_id);
  2231. }
  2232. void FPProbe::reset() {
  2233. this->probe_no = 0;
  2234. this->retransmissions = 0;
  2235. this->times_replied = 0;
  2236. this->failed = false;
  2237. this->timed = false;
  2238. if (this->probe_id != NULL)
  2239. free(this->probe_id);
  2240. this->probe_id = NULL;
  2241. /* Also call FPPacket::__reset() to free any existing packet information */
  2242. this->__reset();
  2243. }
  2244. /* Returns true if the supplied packet is a response to this FPProbe. This
  2245. * method handles IPv4, IPv6, ICMPv4, ICMPv6, TCP and UDP. Basically it uses
  2246. * PacketParser::is_response(). Check there for a list of matched packets and
  2247. * some usage examples.*/
  2248. bool FPProbe::isResponse(PacketElement *rcvd) {
  2249. /* If we don't have a record of even sending this probe, no packet can be a
  2250. response. */
  2251. if (this->pkt_time.tv_sec == 0 && this->pkt_time.tv_usec == 0)
  2252. return false;
  2253. return PacketParser::is_response(this->pkt, rcvd);
  2254. }
  2255. /* Store this probe's textual identifier. Note that this method makes a copy
  2256. * of the supplied string, so you can safely change its contents without
  2257. * affecting the object's state. */
  2258. int FPProbe::setProbeID(const char *id) {
  2259. this->probe_id = strdup(id);
  2260. return OP_SUCCESS;
  2261. }
  2262. /* Returns a pointer to probe's textual identifier. */
  2263. const char *FPProbe::getProbeID() const {
  2264. return this->probe_id;
  2265. }
  2266. /* Returns the number of times the probe has been scheduled for retransmission. */
  2267. int FPProbe::getRetransmissions() const {
  2268. return this->retransmissions;
  2269. }
  2270. /* Increment the number of times the probe has been scheduled for retransmission
  2271. * by one unit. It returns the current value of the retransmission counter. */
  2272. int FPProbe::incrementRetransmissions() {
  2273. this->retransmissions++;
  2274. return this->retransmissions;
  2275. }
  2276. /* Returns the number of times the probe has been replied. This applies for
  2277. * timed probes, which may be retransmitted even if we got a reply (because
  2278. * another timed probe timeout and we had to retransmit all of them to keep
  2279. * the timing accurate). */
  2280. int FPProbe::getReplies() const {
  2281. return this->times_replied;
  2282. }
  2283. /* Increment the number of times the probe has been replied. It returns the
  2284. * current value of the reply counter. */
  2285. int FPProbe::incrementReplies() {
  2286. this->times_replied++;
  2287. return this->times_replied;
  2288. }
  2289. /* Sets the time at which the probe was sent */
  2290. int FPProbe::setTimeSent() {
  2291. return this->setTime();
  2292. }
  2293. /* Returns the time at which te packet was sent */
  2294. struct timeval FPProbe::getTimeSent() const {
  2295. return this->getTime();
  2296. }
  2297. /* Sets the time at which the probe was sent to zero. */
  2298. int FPProbe::resetTimeSent() {
  2299. return this->resetTime();
  2300. }
  2301. /* Returns true if this FPProbe did not receive any response after all
  2302. * necessary retransmissions. When it returns true, callers should not
  2303. * attempt to change the state of the FPProbe. */
  2304. bool FPProbe::probeFailed() const {
  2305. return this->failed;
  2306. }
  2307. /* This method should be called when the probe has been retransmitted as many
  2308. * times as we could and it still timed out without a response. Once this
  2309. * method is called, the state is irreversible (unless a call to FPProbe::reset()
  2310. * is made, in which case all internal state disappears) */
  2311. int FPProbe::setFailed() {
  2312. this->failed = true;
  2313. return OP_SUCCESS;
  2314. }
  2315. /* Returns true if the probe is one of the "timed probes". */
  2316. bool FPProbe::isTimed() const {
  2317. return this->timed;
  2318. }
  2319. /* Marks the probe as "timed". This is used to indicate that this probe has
  2320. * specific timing requirements (it must be sent exactly 100ms after the
  2321. * previous probe)., */
  2322. int FPProbe::setTimed() {
  2323. this->timed = true;
  2324. return OP_SUCCESS;
  2325. }
  2326. /******************************************************************************
  2327. * Implementation of class FPResponse. *
  2328. ******************************************************************************/
  2329. FPResponse::FPResponse(const char *probe_id, const u8 *buf, size_t len,
  2330. struct timeval senttime, struct timeval rcvdtime) {
  2331. this->probe_id = string_pool_insert(probe_id);
  2332. this->buf = (u8 *) safe_malloc(len);
  2333. memcpy(this->buf, buf, len);
  2334. this->len = len;
  2335. this->senttime = senttime;
  2336. this->rcvdtime = rcvdtime;
  2337. }
  2338. FPResponse::~FPResponse() {
  2339. free(buf);
  2340. }
  2341. /******************************************************************************
  2342. * Nsock handler wrappers. *
  2343. ******************************************************************************/
  2344. /* This handler is a wrapper for the FPNetworkControl::probe_transmission_handler()
  2345. * method. We need this because C++ does not allow to use class methods as
  2346. * callback functions for things like signal() or the Nsock lib. */
  2347. void probe_transmission_handler_wrapper(nsock_pool nsp, nsock_event nse, void *arg) {
  2348. global_netctl.probe_transmission_handler(nsp, nse, arg);
  2349. return;
  2350. }
  2351. /* This handler is a wrapper for the FPNetworkControl:response_reception_handler()
  2352. * method. We need this because C++ does not allow to use class methods as
  2353. * callback functions for things like signal() or the Nsock lib. */
  2354. void response_reception_handler_wrapper(nsock_pool nsp, nsock_event nse, void *arg) {
  2355. global_netctl.response_reception_handler(nsp, nse, arg);
  2356. return;
  2357. }