PageRenderTime 45ms CodeModel.GetById 15ms RepoModel.GetById 0ms app.codeStats 1ms

/traceroute.cc

https://github.com/prakashgamit/nmap
C++ | 1651 lines | 1172 code | 198 blank | 281 comment | 424 complexity | 930358e34a88ec48e0cafbf847f62a15 MD5 | raw file
Possible License(s): BSD-3-Clause, GPL-2.0, LGPL-2.0, LGPL-2.1

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

  1. /***************************************************************************
  2. * traceroute.cc -- Parallel multi-protocol traceroute feature *
  3. * *
  4. ***********************IMPORTANT NMAP LICENSE TERMS************************
  5. * *
  6. * The Nmap Security Scanner is (C) 1996-2013 Insecure.Com LLC. Nmap is *
  7. * also a registered trademark of Insecure.Com LLC. This program is free *
  8. * software; you may redistribute and/or modify it under the terms of the *
  9. * GNU General Public License as published by the Free Software *
  10. * Foundation; Version 2 ("GPL"), BUT ONLY WITH ALL OF THE CLARIFICATIONS *
  11. * AND EXCEPTIONS DESCRIBED HEREIN. This guarantees your right to use, *
  12. * modify, and redistribute this software under certain conditions. If *
  13. * you wish to embed Nmap technology into proprietary software, we sell *
  14. * alternative licenses (contact sales@nmap.com). Dozens of software *
  15. * vendors already license Nmap technology such as host discovery, port *
  16. * scanning, OS detection, version detection, and the Nmap Scripting *
  17. * Engine. *
  18. * *
  19. * Note that the GPL places important restrictions on "derivative works", *
  20. * yet it does not provide a detailed definition of that term. To avoid *
  21. * misunderstandings, we interpret that term as broadly as copyright law *
  22. * allows. For example, we consider an application to constitute a *
  23. * derivative work for the purpose of this license if it does any of the *
  24. * following with any software or content covered by this license *
  25. * ("Covered Software"): *
  26. * *
  27. * o Integrates source code from Covered Software. *
  28. * *
  29. * o Reads or includes copyrighted data files, such as Nmap's nmap-os-db *
  30. * or nmap-service-probes. *
  31. * *
  32. * o Is designed specifically to execute Covered Software and parse the *
  33. * results (as opposed to typical shell or execution-menu apps, which will *
  34. * execute anything you tell them to). *
  35. * *
  36. * o Includes Covered Software in a proprietary executable installer. The *
  37. * installers produced by InstallShield are an example of this. Including *
  38. * Nmap with other software in compressed or archival form does not *
  39. * trigger this provision, provided appropriate open source decompression *
  40. * or de-archiving software is widely available for no charge. For the *
  41. * purposes of this license, an installer is considered to include Covered *
  42. * Software even if it actually retrieves a copy of Covered Software from *
  43. * another source during runtime (such as by downloading it from the *
  44. * Internet). *
  45. * *
  46. * o Links (statically or dynamically) to a library which does any of the *
  47. * above. *
  48. * *
  49. * o Executes a helper program, module, or script to do any of the above. *
  50. * *
  51. * This list is not exclusive, but is meant to clarify our interpretation *
  52. * of derived works with some common examples. Other people may interpret *
  53. * the plain GPL differently, so we consider this a special exception to *
  54. * the GPL that we apply to Covered Software. Works which meet any of *
  55. * these conditions must conform to all of the terms of this license, *
  56. * particularly including the GPL Section 3 requirements of providing *
  57. * source code and allowing free redistribution of the work as a whole. *
  58. * *
  59. * As another special exception to the GPL terms, Insecure.Com LLC grants *
  60. * permission to link the code of this program with any version of the *
  61. * OpenSSL library which is distributed under a license identical to that *
  62. * listed in the included docs/licenses/OpenSSL.txt file, and distribute *
  63. * linked combinations including the two. *
  64. * *
  65. * Any redistribution of Covered Software, including any derived works, *
  66. * must obey and carry forward all of the terms of this license, including *
  67. * obeying all GPL rules and restrictions. For example, source code of *
  68. * the whole work must be provided and free redistribution must be *
  69. * allowed. All GPL references to "this License", are to be treated as *
  70. * including the terms and conditions of this license text as well. *
  71. * *
  72. * Because this license imposes special exceptions to the GPL, Covered *
  73. * Work may not be combined (even as part of a larger work) with plain GPL *
  74. * software. The terms, conditions, and exceptions of this license must *
  75. * be included as well. This license is incompatible with some other open *
  76. * source licenses as well. In some cases we can relicense portions of *
  77. * Nmap or grant special permissions to use it in other open source *
  78. * software. Please contact fyodor@nmap.org with any such requests. *
  79. * Similarly, we don't incorporate incompatible open source software into *
  80. * Covered Software without special permission from the copyright holders. *
  81. * *
  82. * If you have any questions about the licensing restrictions on using *
  83. * Nmap in other works, are happy to help. As mentioned above, we also *
  84. * offer alternative license to integrate Nmap into proprietary *
  85. * applications and appliances. These contracts have been sold to dozens *
  86. * of software vendors, and generally include a perpetual license as well *
  87. * as providing for priority support and updates. They also fund the *
  88. * continued development of Nmap. Please email sales@nmap.com for further *
  89. * information. *
  90. * *
  91. * If you have received a written license agreement or contract for *
  92. * Covered Software stating terms other than these, you may choose to use *
  93. * and redistribute Covered Software under those terms instead of these. *
  94. * *
  95. * Source is provided to this software because we believe users have a *
  96. * right to know exactly what a program is going to do before they run it. *
  97. * This also allows you to audit the software for security holes (none *
  98. * have been found so far). *
  99. * *
  100. * Source code also allows you to port Nmap to new platforms, fix bugs, *
  101. * and add new features. You are highly encouraged to send your changes *
  102. * to the dev@nmap.org mailing list for possible incorporation into the *
  103. * main distribution. By sending these changes to Fyodor or one of the *
  104. * Insecure.Org development mailing lists, or checking them into the Nmap *
  105. * source code repository, it is understood (unless you specify otherwise) *
  106. * that you are offering the Nmap Project (Insecure.Com LLC) the *
  107. * unlimited, non-exclusive right to reuse, modify, and relicense the *
  108. * code. Nmap will always be available Open Source, but this is important *
  109. * because the inability to relicense code has caused devastating problems *
  110. * for other Free Software projects (such as KDE and NASM). We also *
  111. * occasionally relicense the code to third parties as discussed above. *
  112. * If you wish to specify special license conditions of your *
  113. * contributions, just say so when you send them. *
  114. * *
  115. * This program is distributed in the hope that it will be useful, but *
  116. * WITHOUT ANY WARRANTY; without even the implied warranty of *
  117. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the Nmap *
  118. * license file for more details (it's in a COPYING file included with *
  119. * Nmap, and also available from https://svn.nmap.org/nmap/COPYING *
  120. * *
  121. ***************************************************************************/
  122. /*
  123. Traceroute for Nmap. This traceroute is faster than a traditional traceroute
  124. because it sends several probes in parallel and detects shared traces.
  125. The algorithm works by sending probes with varying TTL values and waiting for
  126. TTL_EXCEEDED messages. As intermediate hops are discovered, they are entered
  127. into a global hop cache that is shared between targets and across host groups.
  128. When a hop is discovered and is found to be already in the cache, the trace for
  129. that target is linked into the cached trace and there is no need to try lower
  130. TTLs. The process results in the building of a tree of Hop structures.
  131. The order in which probes are sent does not matter to the accuracy of the
  132. algorithm but it does matter to the speed. The sooner a shared trace can be
  133. detected, and the higher the TTL at which it is detected, the fewer probes need
  134. to be sent. The ideal situation is to start sending probes with a TTL equal to
  135. the true distance and count downward from there. In that case it may only be
  136. necessary to send two probes per target: one at the distance of the target to
  137. get a response, and one at distance - 1 to get a cache hit. When the distance
  138. isn't known in advance, the algorithm arbitrarily starts at a TTL of 10 and
  139. counts downward, then counts upward from 11 until it reaches the target. So a
  140. typical trace may look like
  141. TTL 10 -> TTL_EXCEEDED
  142. TTL 9 -> TTL_EXCEEDED
  143. TTL 8 -> TTL_EXCEEDED
  144. TTL 7 -> cache hit
  145. TTL 11 -> TTL_EXCEEDED
  146. TTL 12 -> TTL_EXCEEDED
  147. TTL 13 -> SYN/ACK, or whatever is the target's response to the probe
  148. The output for this host would then say "Hops 1-7 are the same as for ...".
  149. The detection of shared traces rests on the assumption that all paths going
  150. through a router at a certain TTL will be identical up to and including the
  151. router. This assumption is not always true. Even if two targets are each one hop
  152. past router X at TTL 10, packets may follow different paths to each host (and
  153. those paths may even change over time). This traceroute algorithm will be fooled
  154. by such a situation, and will report that the paths are identical up to
  155. router X. The only way to be sure is to do a complete trace for each target
  156. individually.
  157. */
  158. #include "nmap_dns.h"
  159. #include "nmap_error.h"
  160. #include "nmap_tty.h"
  161. #include "osscan2.h"
  162. #include "payload.h"
  163. #include "timing.h"
  164. #include "NmapOps.h"
  165. #include "Target.h"
  166. #include "struct_ip.h"
  167. #include <dnet.h>
  168. #include <algorithm>
  169. #include <list>
  170. #include <map>
  171. #include <set>
  172. #include <vector>
  173. extern NmapOps o;
  174. /* The highest TTL we go up to if the target itself doesn't respond. */
  175. #define MAX_TTL 30
  176. #define MAX_OUTSTANDING_PROBES 10
  177. #define MAX_RESENDS 2
  178. /* In milliseconds. */
  179. #define PROBE_TIMEOUT 1000
  180. /* If the hop cache (including timed-out hops) is bigger than this after a
  181. round, the hop is cleared and rebuilt from scratch. */
  182. #define MAX_HOP_CACHE_SIZE 1000
  183. struct Hop;
  184. class HostState;
  185. class Probe;
  186. /* An object of this class is a (TTL, address) pair that uniquely identifies a
  187. hop. Hops in the hop_cache are indexed by this type. */
  188. struct HopIdent {
  189. u8 ttl;
  190. struct sockaddr_storage addr;
  191. HopIdent(u8 ttl, const struct sockaddr_storage &addr) {
  192. this->addr = addr;
  193. this->ttl = ttl;
  194. }
  195. bool operator<(const struct HopIdent &other) const {
  196. if (ttl < other.ttl)
  197. return true;
  198. else if (ttl > other.ttl)
  199. return false;
  200. else
  201. return sockaddr_storage_cmp(&addr, &other.addr) < 0;
  202. }
  203. };
  204. /* A global random token used to distinguish this traceroute's probes from
  205. those of other traceroutes possibly running on the same machine. */
  206. static u16 global_id;
  207. /* A global cache of known hops, indexed by TTL and address. */
  208. static std::map<struct HopIdent, Hop *> hop_cache;
  209. /* A list of timedout hops, which are not kept in hop_cache, so we can delete
  210. all hops on occasion. */
  211. static std::list<Hop *> timedout_hops;
  212. /* The TTL at which we start sending probes if we don't have a distance
  213. estimate. This is updated after each host group on the assumption that hosts
  214. across groups will not differ much in distance. Having this closer to the
  215. true distance makes the trace faster but is not needed for accuracy. */
  216. static u8 initial_ttl = 10;
  217. static struct timeval get_now(struct timeval *now = NULL);
  218. static const char *ss_to_string(const struct sockaddr_storage *ss);
  219. struct Hop {
  220. Hop *parent;
  221. struct sockaddr_storage tag;
  222. /* When addr.ss_family == 0, this hop represents a timeout. */
  223. struct sockaddr_storage addr;
  224. u8 ttl;
  225. float rtt; /* In milliseconds. */
  226. std::string hostname;
  227. Hop() {
  228. this->parent = NULL;
  229. this->addr.ss_family = 0;
  230. this->ttl = 0;
  231. this->rtt = -1.0;
  232. this->tag.ss_family = 0;
  233. }
  234. Hop(u8 ttl, const struct sockaddr_storage &addr, float rtt) {
  235. this->parent = NULL;
  236. this->addr = addr;
  237. this->ttl = ttl;
  238. this->rtt = rtt;
  239. this->tag.ss_family = 0;
  240. }
  241. };
  242. class HostState {
  243. public:
  244. enum counting_state { COUNTING_DOWN, COUNTING_UP };
  245. Target *target;
  246. /* A bitmap of TTLs that have been sent, to avoid duplicates when we switch
  247. around the order counting up or down. */
  248. std::vector<bool> sent_ttls;
  249. u8 current_ttl;
  250. enum counting_state state;
  251. /* If nonzero, the known hop distance to the target. */
  252. int reached_target;
  253. struct probespec pspec;
  254. std::list<Probe *> unanswered_probes;
  255. std::list<Probe *> active_probes;
  256. std::list<Probe *> pending_resends;
  257. Hop *hops;
  258. HostState(Target *target);
  259. ~HostState();
  260. bool has_more_probes() const;
  261. bool is_finished() const;
  262. bool send_next_probe(int rawsd, eth_t *ethsd);
  263. void next_ttl();
  264. void count_up();
  265. int cancel_probe(std::list<Probe *>::iterator it);
  266. int cancel_probes_below(u8 ttl);
  267. int cancel_probes_above(u8 ttl);
  268. Hop *insert_hop(u8 ttl, const struct sockaddr_storage *addr, float rtt);
  269. void link_to(Hop *hop);
  270. double completion_fraction() const;
  271. private:
  272. void child_parent_ttl(u8 ttl, Hop **child, Hop **parent);
  273. static u8 distance_guess(const Target *target);
  274. static struct probespec get_probe(const Target *target);
  275. };
  276. class Probe {
  277. private:
  278. /* This is incremented with each instantiated probe. */
  279. static u16 token_counter;
  280. unsigned int num_resends;
  281. public:
  282. HostState *host;
  283. struct probespec pspec;
  284. u8 ttl;
  285. /* The token is used to match up probe replies. */
  286. u16 token;
  287. struct timeval sent_time;
  288. Probe(HostState *host, struct probespec pspec, u8 ttl);
  289. virtual ~Probe();
  290. void send(int rawsd, eth_t *ethsd, struct timeval *now = NULL);
  291. void resend(int rawsd, eth_t *ethsd, struct timeval *now = NULL);
  292. bool is_timedout(struct timeval *now = NULL) const;
  293. bool may_resend() const;
  294. virtual unsigned char *build_packet(const struct sockaddr_storage *source,
  295. u32 *len) const = 0;
  296. static Probe *make(HostState *host, struct probespec pspec, u8 ttl);
  297. };
  298. u16 Probe::token_counter = 0x0000;
  299. class TracerouteState {
  300. public:
  301. std::list<HostState *> active_hosts;
  302. /* The next send time for enforcing scan delay. */
  303. struct timeval next_send_time;
  304. TracerouteState(std::vector<Target *> &targets);
  305. ~TracerouteState();
  306. void send_new_probes();
  307. void read_replies(long timeout);
  308. void cull_timeouts();
  309. void remove_finished_hosts();
  310. void resolve_hops();
  311. void transfer_hops();
  312. double completion_fraction() const;
  313. private:
  314. eth_t *ethsd;
  315. int rawsd;
  316. pcap_t *pd;
  317. int num_active_probes;
  318. std::vector<HostState *> hosts;
  319. std::list<HostState *>::iterator next_sending_host;
  320. void next_active_host();
  321. Probe *lookup_probe(const struct sockaddr_storage *target_addr, u16 token);
  322. void set_host_hop(HostState *host, u8 ttl,
  323. const struct sockaddr_storage *from_addr, float rtt);
  324. void set_host_hop_timedout(HostState *host, u8 ttl);
  325. };
  326. static Hop *merge_hops(const struct sockaddr_storage *tag, Hop *a, Hop *b);
  327. static Hop *hop_cache_lookup(u8 ttl, const struct sockaddr_storage *addr);
  328. static void hop_cache_insert(Hop *hop);
  329. static unsigned int hop_cache_size();
  330. HostState::HostState(Target *target) : sent_ttls(MAX_TTL + 1, false) {
  331. this->target = target;
  332. current_ttl = MIN(MAX(1, HostState::distance_guess(target)), MAX_TTL);
  333. state = HostState::COUNTING_DOWN;
  334. reached_target = 0;
  335. pspec = HostState::get_probe(target);
  336. hops = NULL;
  337. }
  338. HostState::~HostState() {
  339. /* active_probes and pending_resends are subsets of unanswered_probes, so we
  340. delete the allocated probes in unanswered_probes only. */
  341. while (!unanswered_probes.empty()) {
  342. delete *unanswered_probes.begin();
  343. unanswered_probes.pop_front();
  344. }
  345. while (!active_probes.empty())
  346. active_probes.pop_front();
  347. while (!pending_resends.empty())
  348. pending_resends.pop_front();
  349. }
  350. bool HostState::has_more_probes() const {
  351. /* We are done if we are counting up and
  352. 1. we've reached and exceeded the target, or
  353. 2. we've exceeded MAX_TTL. */
  354. return !(state == HostState::COUNTING_UP
  355. && ((reached_target > 0 && current_ttl >= reached_target)
  356. || current_ttl > MAX_TTL));
  357. }
  358. bool HostState::is_finished() const {
  359. return !this->has_more_probes()
  360. && active_probes.empty() && pending_resends.empty();
  361. }
  362. bool HostState::send_next_probe(int rawsd, eth_t *ethsd) {
  363. Probe *probe;
  364. /* Do a resend if possible. */
  365. if (!pending_resends.empty()) {
  366. probe = pending_resends.front();
  367. pending_resends.pop_front();
  368. active_probes.push_back(probe);
  369. probe->resend(rawsd, ethsd);
  370. return true;
  371. }
  372. this->next_ttl();
  373. if (!this->has_more_probes())
  374. return false;
  375. probe = Probe::make(this, pspec, current_ttl);
  376. unanswered_probes.push_back(probe);
  377. active_probes.push_back(probe);
  378. probe->send(rawsd, ethsd);
  379. sent_ttls[current_ttl] = true;
  380. return true;
  381. }
  382. /* Find the next TTL we should send to. */
  383. void HostState::next_ttl() {
  384. assert(current_ttl > 0);
  385. if (state == HostState::COUNTING_DOWN) {
  386. while (current_ttl > 1 && sent_ttls[current_ttl])
  387. current_ttl--;
  388. if (current_ttl == 1)
  389. state = HostState::COUNTING_UP;
  390. }
  391. /* Note no "else". */
  392. if (state == HostState::COUNTING_UP) {
  393. while (current_ttl <= MAX_TTL && sent_ttls[current_ttl])
  394. current_ttl++;
  395. }
  396. }
  397. int HostState::cancel_probe(std::list<Probe *>::iterator it) {
  398. int count;
  399. count = active_probes.size();
  400. active_probes.remove(*it);
  401. count -= active_probes.size();
  402. pending_resends.remove(*it);
  403. delete *it;
  404. unanswered_probes.erase(it);
  405. return count;
  406. }
  407. int HostState::cancel_probes_below(u8 ttl) {
  408. std::list<Probe *>::iterator it, next;
  409. int count;
  410. count = 0;
  411. for (it = unanswered_probes.begin(); it != unanswered_probes.end(); it = next) {
  412. next = it;
  413. next++;
  414. if ((*it)->ttl < ttl)
  415. count += this->cancel_probe(it);
  416. }
  417. return count;
  418. }
  419. int HostState::cancel_probes_above(u8 ttl) {
  420. std::list<Probe *>::iterator it, next;
  421. int count;
  422. count = 0;
  423. for (it = unanswered_probes.begin(); it != unanswered_probes.end(); it = next) {
  424. next = it;
  425. next++;
  426. if ((*it)->ttl > ttl)
  427. count += this->cancel_probe(it);
  428. }
  429. return count;
  430. }
  431. Hop *HostState::insert_hop(u8 ttl, const struct sockaddr_storage *addr,
  432. float rtt) {
  433. Hop *hop, *prev, *p;
  434. this->child_parent_ttl(ttl, &prev, &p);
  435. if (p != NULL && p->ttl == ttl) {
  436. hop = p;
  437. /* Collision with the same TTL and a different address. */
  438. if (hop->addr.ss_family == 0) {
  439. /* Hit a timed-out hop. Fill in the missing address and RTT. */
  440. hop->addr = *addr;
  441. hop->rtt = rtt;
  442. } else {
  443. if (o.debugging) {
  444. log_write(LOG_STDOUT, "Found existing %s", ss_to_string(&hop->addr));
  445. log_write(LOG_STDOUT, " while inserting %s at TTL %d for %s\n",
  446. ss_to_string(addr), ttl, target->targetipstr());
  447. }
  448. }
  449. } else {
  450. hop = new Hop(ttl, *addr, rtt);
  451. hop->parent = p;
  452. if (prev == NULL) {
  453. size_t sslen;
  454. this->hops = hop;
  455. sslen = sizeof(hop->tag);
  456. target->TargetSockAddr(&hop->tag, &sslen);
  457. } else {
  458. prev->parent = hop;
  459. hop->tag = prev->tag;
  460. }
  461. hop_cache_insert(hop);
  462. }
  463. return hop;
  464. }
  465. void HostState::link_to(Hop *hop) {
  466. Hop *prev, *p;
  467. this->child_parent_ttl(hop->ttl, &prev, &p);
  468. if (hop == p) {
  469. /* Already linked for this host. This can happen a reply for a higher TTL
  470. results in a merge, and later a reply for a lower TTL comes back. */
  471. return;
  472. }
  473. if (o.debugging > 1) {
  474. log_write(LOG_STDOUT, "Merging traces below TTL %d for %s",
  475. hop->ttl, ss_to_string(&hop->tag));
  476. log_write(LOG_STDOUT, " and %s\n", target->targetipstr());
  477. }
  478. hop = merge_hops(&hop->tag, hop, p);
  479. if (prev == NULL)
  480. this->hops = hop;
  481. else
  482. prev->parent = hop;
  483. }
  484. double HostState::completion_fraction() const {
  485. std::vector<bool>::iterator it;
  486. unsigned int i, n;
  487. if (this->is_finished())
  488. return 1.0;
  489. n = 0;
  490. for (i = 0; i < sent_ttls.size(); i++) {
  491. if (sent_ttls[i])
  492. n++;
  493. }
  494. return (double) n / sent_ttls.size();
  495. }
  496. void HostState::child_parent_ttl(u8 ttl, Hop **child, Hop **parent) {
  497. *child = NULL;
  498. *parent = this->hops;
  499. while (*parent != NULL && (*parent)->ttl > ttl) {
  500. *child = *parent;
  501. *parent = (*parent)->parent;
  502. }
  503. }
  504. u8 HostState::distance_guess(const Target *target) {
  505. /* Use the distance from OS detection if we have it. */
  506. if (target->distance != -1)
  507. return target->distance;
  508. else
  509. /* initial_ttl is a variable with file-level scope. */
  510. return initial_ttl;
  511. }
  512. /* Get the probe that will be used for the traceroute. This is the
  513. highest-quality probe found in ping or port scanning, or ICMP echo if no
  514. responsive probe is known. */
  515. struct probespec HostState::get_probe(const Target *target) {
  516. struct probespec probe;
  517. probe = target->pingprobe;
  518. if (target->af() == AF_INET &&
  519. (probe.type == PS_TCP || probe.type == PS_UDP || probe.type == PS_SCTP || probe.type == PS_ICMP)) {
  520. /* Nothing needed. */
  521. } else if (target->af() == AF_INET6 &&
  522. (probe.type == PS_TCP || probe.type == PS_UDP || probe.type == PS_SCTP || probe.type == PS_ICMPV6)) {
  523. /* Nothing needed. */
  524. } else if (probe.type == PS_PROTO) {
  525. /* If this is an IP protocol probe, fill in some fields for some common
  526. protocols. We cheat and store them in the TCP-, UDP-, SCTP- and
  527. ICMP-specific fields. */
  528. if (probe.proto == IPPROTO_TCP) {
  529. probe.pd.tcp.flags = TH_ACK;
  530. probe.pd.tcp.dport = get_random_u16();
  531. } else if (probe.proto == IPPROTO_UDP) {
  532. probe.pd.udp.dport = get_random_u16();
  533. } else if (probe.proto == IPPROTO_SCTP) {
  534. probe.pd.sctp.dport = get_random_u16();
  535. } else if (probe.proto == IPPROTO_ICMP) {
  536. probe.pd.icmp.type = ICMP_ECHO;
  537. } else if (probe.proto == IPPROTO_ICMPV6) {
  538. probe.pd.icmp.type = ICMPV6_ECHO;
  539. } else {
  540. fatal("Unknown protocol %d", probe.proto);
  541. }
  542. } else {
  543. /* No responsive probe known? The user probably skipped both ping and
  544. port scan. Guess ICMP echo as the most likely to get a response. */
  545. if (target->af() == AF_INET) {
  546. probe.type = PS_ICMP;
  547. probe.proto = IPPROTO_ICMP;
  548. probe.pd.icmp.type = ICMP_ECHO;
  549. probe.pd.icmp.code = 0;
  550. } else if (target->af() == AF_INET6) {
  551. probe.type = PS_ICMPV6;
  552. probe.proto = IPPROTO_ICMPV6;
  553. probe.pd.icmp.type = ICMPV6_ECHO;
  554. probe.pd.icmp.code = 0;
  555. } else {
  556. fatal("Unknown address family %d", target->af());
  557. }
  558. }
  559. return probe;
  560. }
  561. Probe::Probe(HostState *host, struct probespec pspec, u8 ttl) {
  562. this->host = host;
  563. this->pspec = pspec;
  564. this->ttl = ttl;
  565. token = Probe::token_counter++;
  566. sent_time.tv_sec = 0;
  567. sent_time.tv_usec = 0;
  568. num_resends = 0;
  569. }
  570. Probe::~Probe() {
  571. }
  572. void Probe::send(int rawsd, eth_t *ethsd, struct timeval *now) {
  573. struct eth_nfo eth;
  574. struct eth_nfo *ethp;
  575. int decoy;
  576. /* Set up the Ethernet handle if we're using that. */
  577. if (ethsd != NULL) {
  578. memcpy(eth.srcmac, host->target->SrcMACAddress(), 6);
  579. memcpy(eth.dstmac, host->target->NextHopMACAddress(), 6);
  580. eth.ethsd = ethsd;
  581. eth.devname[0] = '\0';
  582. ethp = &eth;
  583. } else {
  584. ethp = NULL;
  585. }
  586. for (decoy = 0; decoy < o.numdecoys; decoy++) {
  587. struct sockaddr_storage source;
  588. size_t source_len;
  589. unsigned char *packet;
  590. u32 packetlen;
  591. if (decoy == o.decoyturn) {
  592. source_len = sizeof(source);
  593. host->target->SourceSockAddr(&source, &source_len);
  594. sent_time = get_now(now);
  595. } else {
  596. if (o.af() == AF_INET) {
  597. struct sockaddr_in *sin;
  598. sin = (struct sockaddr_in *) &source;
  599. sin->sin_family = AF_INET;
  600. sin->sin_addr = o.decoys[decoy];
  601. } else {
  602. /* Decoys are IPv4-only. */
  603. continue;
  604. }
  605. }
  606. packet = this->build_packet(&source, &packetlen);
  607. send_ip_packet(rawsd, ethp, host->target->TargetSockAddr(), packet, packetlen);
  608. free(packet);
  609. }
  610. }
  611. void Probe::resend(int rawsd, eth_t *ethsd, struct timeval *now) {
  612. num_resends++;
  613. this->send(rawsd, ethsd, now);
  614. }
  615. bool Probe::is_timedout(struct timeval *now) const {
  616. struct timeval tv;
  617. tv = get_now(now);
  618. return TIMEVAL_MSEC_SUBTRACT(tv, sent_time) > PROBE_TIMEOUT;
  619. }
  620. bool Probe::may_resend() const {
  621. return num_resends < MIN(o.getMaxRetransmissions(), MAX_RESENDS);
  622. }
  623. /* Probe is an abstract class with a missing build_packet method. These concrete
  624. subclasses implement the method for different probe types. */
  625. class ICMPProbe : public Probe
  626. {
  627. public:
  628. ICMPProbe(HostState *host, struct probespec pspec, u8 ttl)
  629. : Probe(host, pspec, ttl) {
  630. }
  631. unsigned char *build_packet(const struct sockaddr_storage *source, u32 *len) const {
  632. const struct sockaddr_in *sin;
  633. assert(source->ss_family == AF_INET);
  634. sin = (struct sockaddr_in *) source;
  635. return build_icmp_raw(&sin->sin_addr, host->target->v4hostip(), ttl,
  636. 0x0000, 0x00, false, NULL, 0, token, global_id,
  637. pspec.pd.icmp.type, pspec.pd.icmp.code,
  638. o.extra_payload, o.extra_payload_length, len);
  639. }
  640. };
  641. class TCPProbe : public Probe
  642. {
  643. public:
  644. TCPProbe(HostState *host, struct probespec pspec, u8 ttl)
  645. : Probe(host, pspec, ttl) {
  646. }
  647. unsigned char *build_packet(const struct sockaddr_storage *source, u32 *len) const {
  648. const char *tcpopts;
  649. int tcpoptslen;
  650. u32 ack;
  651. tcpopts = NULL;
  652. tcpoptslen = 0;
  653. ack = 0;
  654. if ((pspec.pd.tcp.flags & TH_SYN) == TH_SYN) {
  655. /* MSS 1460 bytes. */
  656. tcpopts = "\x02\x04\x05\xb4";
  657. tcpoptslen = 4;
  658. } else if ((pspec.pd.tcp.flags & TH_ACK) == TH_ACK) {
  659. ack = get_random_u32();
  660. }
  661. /* For TCP we encode the token in the source port. */
  662. if (source->ss_family == AF_INET) {
  663. const struct sockaddr_in *sin = (struct sockaddr_in *) source;
  664. return build_tcp_raw(&sin->sin_addr, host->target->v4hostip(), ttl,
  665. get_random_u16(), get_random_u8(), false, NULL, 0,
  666. token ^ global_id, pspec.pd.tcp.dport, get_random_u32(), ack, 0x00,
  667. pspec.pd.tcp.flags, get_random_u16(), 0, (const u8 *) tcpopts, tcpoptslen,
  668. o.extra_payload, o.extra_payload_length, len);
  669. } else if (source->ss_family == AF_INET6) {
  670. const struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *) source;
  671. return build_tcp_raw_ipv6(&sin6->sin6_addr, host->target->v6hostip(),
  672. 0, 0, ttl,
  673. token ^ global_id, pspec.pd.tcp.dport, get_random_u32(), ack, 0x00,
  674. pspec.pd.tcp.flags, get_random_u16(), 0, (const u8 *) tcpopts, tcpoptslen,
  675. o.extra_payload, o.extra_payload_length, len);
  676. } else {
  677. fatal("Unknown address family %u in %s.", source->ss_family, __func__);
  678. }
  679. }
  680. };
  681. class UDPProbe : public Probe
  682. {
  683. public:
  684. UDPProbe(HostState *host, struct probespec pspec, u8 ttl)
  685. : Probe(host, pspec, ttl) {
  686. }
  687. unsigned char *build_packet(const struct sockaddr_storage *source, u32 *len) const {
  688. const char *payload;
  689. size_t payload_length;
  690. payload = get_udp_payload(pspec.pd.udp.dport, &payload_length);
  691. /* For UDP we encode the token in the source port. */
  692. if (source->ss_family == AF_INET) {
  693. const struct sockaddr_in *sin = (struct sockaddr_in *) source;
  694. return build_udp_raw(&sin->sin_addr, host->target->v4hostip(), ttl,
  695. get_random_u16(), get_random_u8(), false, NULL, 0,
  696. token ^ global_id, pspec.pd.udp.dport,
  697. payload, payload_length, len);
  698. } else if (source->ss_family == AF_INET6) {
  699. const struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *) source;
  700. return build_udp_raw_ipv6(&sin6->sin6_addr, host->target->v6hostip(),
  701. 0, 0, ttl,
  702. token ^ global_id, pspec.pd.udp.dport,
  703. payload, payload_length, len);
  704. } else {
  705. fatal("Unknown address family %u in %s.", source->ss_family, __func__);
  706. }
  707. }
  708. };
  709. class SCTPProbe : public Probe
  710. {
  711. public:
  712. SCTPProbe(HostState *host, struct probespec pspec, u8 ttl)
  713. : Probe(host, pspec, ttl) {
  714. }
  715. unsigned char *build_packet(const struct sockaddr_storage *source, u32 *len) const {
  716. struct sctp_chunkhdr_init chunk;
  717. sctp_pack_chunkhdr_init(&chunk, SCTP_INIT, 0, sizeof(chunk),
  718. get_random_u32() /*itag*/, 32768, 10, 2048, get_random_u32() /*itsn*/);
  719. if (source->ss_family == AF_INET) {
  720. const struct sockaddr_in *sin = (struct sockaddr_in *) source;
  721. return build_sctp_raw(&sin->sin_addr, host->target->v4hostip(), ttl,
  722. get_random_u16(), get_random_u8(), false, NULL, 0,
  723. token ^ global_id, pspec.pd.sctp.dport, 0UL,
  724. (char *) &chunk, sizeof(chunk),
  725. o.extra_payload, o.extra_payload_length, len);
  726. } else if (source->ss_family == AF_INET6) {
  727. const struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *) source;
  728. return build_sctp_raw_ipv6(&sin6->sin6_addr, host->target->v6hostip(),
  729. 0, 0, ttl,
  730. token ^ global_id, pspec.pd.sctp.dport, 0UL,
  731. (char *) &chunk, sizeof(chunk),
  732. o.extra_payload, o.extra_payload_length, len);
  733. } else {
  734. fatal("Unknown address family %u in %s.", source->ss_family, __func__);
  735. }
  736. }
  737. };
  738. class IPProtoProbe : public Probe
  739. {
  740. public:
  741. IPProtoProbe(HostState *host, struct probespec pspec, u8 ttl)
  742. : Probe(host, pspec, ttl) {
  743. }
  744. unsigned char *build_packet(const struct sockaddr_storage *source, u32 *len) const {
  745. /* For IP proto scan the token is put in the IP ID or flow label. */
  746. if (source->ss_family == AF_INET) {
  747. const struct sockaddr_in *sin = (struct sockaddr_in *) source;
  748. return build_ip_raw(&sin->sin_addr, host->target->v4hostip(), pspec.proto, ttl,
  749. token ^ global_id, get_random_u8(), false, NULL, 0,
  750. o.extra_payload, o.extra_payload_length, len);
  751. } else if (source->ss_family == AF_INET6) {
  752. const struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *) source;
  753. return build_ipv6_raw(&sin6->sin6_addr, host->target->v6hostip(),
  754. 0, token ^ global_id, pspec.proto, ttl,
  755. o.extra_payload, o.extra_payload_length, len);
  756. } else {
  757. fatal("Unknown address family %u in %s.", source->ss_family, __func__);
  758. }
  759. }
  760. };
  761. class ICMPv6Probe : public Probe
  762. {
  763. public:
  764. ICMPv6Probe(HostState *host, struct probespec pspec, u8 ttl)
  765. : Probe(host, pspec, ttl) {
  766. }
  767. unsigned char *build_packet(const struct sockaddr_storage *source, u32 *len) const {
  768. const struct sockaddr_in6 *sin6;
  769. assert(source->ss_family == AF_INET6);
  770. sin6 = (struct sockaddr_in6 *) source;
  771. return build_icmpv6_raw(&sin6->sin6_addr, host->target->v6hostip(), 0x00, 0x0000,
  772. ttl, token, global_id, pspec.pd.icmp.type, pspec.pd.icmp.code,
  773. o.extra_payload, o.extra_payload_length, len);
  774. }
  775. };
  776. Probe *Probe::make(HostState *host, struct probespec pspec, u8 ttl)
  777. {
  778. if (pspec.type == PS_ICMP || (pspec.type == PS_PROTO && pspec.proto == IPPROTO_ICMP))
  779. return new ICMPProbe(host, pspec, ttl);
  780. else if (pspec.type == PS_TCP || (pspec.type == PS_PROTO && pspec.proto == IPPROTO_TCP))
  781. return new TCPProbe(host, pspec, ttl);
  782. else if (pspec.type == PS_UDP || (pspec.type == PS_PROTO && pspec.proto == IPPROTO_UDP))
  783. return new UDPProbe(host, pspec, ttl);
  784. else if (pspec.type == PS_SCTP || (pspec.type == PS_PROTO && pspec.proto == IPPROTO_SCTP))
  785. return new SCTPProbe(host, pspec, ttl);
  786. else if (pspec.type == PS_PROTO)
  787. return new IPProtoProbe(host, pspec, ttl);
  788. else if (pspec.type == PS_ICMPV6)
  789. return new ICMPv6Probe(host, pspec, ttl);
  790. else
  791. fatal("Unknown probespec type in traceroute");
  792. return NULL;
  793. }
  794. TracerouteState::TracerouteState(std::vector<Target *> &targets) {
  795. std::vector<Target *>::iterator it;
  796. struct sockaddr_storage srcaddr;
  797. size_t sslen;
  798. char pcap_filter[128];
  799. int n;
  800. assert(targets.size() > 0);
  801. if ((o.sendpref & PACKET_SEND_ETH) && targets[0]->ifType() == devt_ethernet) {
  802. ethsd = eth_open_cached(targets[0]->deviceName());
  803. if (ethsd == NULL)
  804. fatal("dnet: failed to open device %s", targets[0]->deviceName());
  805. rawsd = -1;
  806. } else {
  807. #ifdef WIN32
  808. win32_fatal_raw_sockets(targets[0]->deviceName());
  809. #endif
  810. rawsd = nmap_raw_socket();
  811. if (rawsd < 0)
  812. pfatal("traceroute: socket troubles");
  813. ethsd = NULL;
  814. }
  815. /* Assume that all the targets share the same device. */
  816. if((pd=my_pcap_open_live(targets[0]->deviceName(), 128, o.spoofsource, 2))==NULL)
  817. fatal("%s", PCAP_OPEN_ERRMSG);
  818. sslen = sizeof(srcaddr);
  819. targets[0]->SourceSockAddr(&srcaddr, &sslen);
  820. n = Snprintf(pcap_filter, sizeof(pcap_filter), "(ip or ip6) and dst host %s",
  821. ss_to_string(&srcaddr));
  822. assert(n < (int) sizeof(pcap_filter));
  823. set_pcap_filter(targets[0]->deviceFullName(), pd, pcap_filter);
  824. if (o.debugging)
  825. log_write(LOG_STDOUT, "Packet capture filter (device %s): %s\n", targets[0]->deviceFullName(), pcap_filter);
  826. for (it = targets.begin(); it != targets.end(); it++) {
  827. HostState *state = new HostState(*it);
  828. hosts.push_back(state);
  829. active_hosts.push_back(state);
  830. }
  831. num_active_probes = 0;
  832. next_sending_host = active_hosts.begin();
  833. next_send_time = get_now();
  834. }
  835. TracerouteState::~TracerouteState() {
  836. std::vector<HostState *>::iterator it;
  837. if (rawsd != -1)
  838. close(rawsd);
  839. pcap_close(pd);
  840. for (it = hosts.begin(); it != hosts.end(); it++)
  841. delete *it;
  842. }
  843. void TracerouteState::next_active_host() {
  844. assert(next_sending_host != active_hosts.end());
  845. next_sending_host++;
  846. if (next_sending_host == active_hosts.end())
  847. next_sending_host = active_hosts.begin();
  848. }
  849. void TracerouteState::send_new_probes() {
  850. std::list<HostState *>::iterator failed_host;
  851. struct timeval now;
  852. now = get_now();
  853. assert(!active_hosts.empty());
  854. failed_host = active_hosts.end();
  855. while (next_sending_host != failed_host
  856. && num_active_probes < MAX_OUTSTANDING_PROBES
  857. && !TIMEVAL_BEFORE(now, next_send_time)) {
  858. if ((*next_sending_host)->send_next_probe(rawsd, ethsd)) {
  859. num_active_probes++;
  860. TIMEVAL_MSEC_ADD(next_send_time, next_send_time, o.scan_delay);
  861. if (TIMEVAL_BEFORE(next_send_time, now))
  862. next_send_time = now;
  863. failed_host = active_hosts.end();
  864. } else if (failed_host == active_hosts.end()) {
  865. failed_host = next_sending_host;
  866. }
  867. next_active_host();
  868. }
  869. }
  870. static Hop *hop_cache_lookup(u8 ttl, const struct sockaddr_storage *addr) {
  871. std::map<struct HopIdent, Hop *>::iterator it;
  872. HopIdent ident(ttl, *addr);
  873. it = hop_cache.find(ident);
  874. if (it == hop_cache.end())
  875. return NULL;
  876. else
  877. return it->second;
  878. }
  879. static void hop_cache_insert(Hop *hop) {
  880. if (hop->addr.ss_family == 0) {
  881. timedout_hops.push_back(hop);
  882. } else {
  883. hop_cache[HopIdent(hop->ttl, hop->addr)] = hop;
  884. }
  885. }
  886. static unsigned int hop_cache_size() {
  887. return hop_cache.size() + timedout_hops.size();
  888. }
  889. void traceroute_hop_cache_clear() {
  890. std::map<struct HopIdent, Hop *>::iterator map_iter;
  891. std::list<Hop *>::iterator list_iter;
  892. for (map_iter = hop_cache.begin(); map_iter != hop_cache.end(); map_iter++)
  893. delete map_iter->second;
  894. hop_cache.clear();
  895. for (list_iter = timedout_hops.begin(); list_iter != timedout_hops.end(); list_iter++)
  896. delete *list_iter;
  897. timedout_hops.clear();
  898. }
  899. /* Merge two hop chains together and return the head of the merged chain. This
  900. is done when a cache hit finds that two targets share the same intermediate
  901. hop; rather than doing a full trace for each target, one is linked to the
  902. other. "Merged" means that, for example, if chain a has an hop at TTL 3 and
  903. chain b has one for TTL 2, the merged chain will include both. Usually, the
  904. chains will not have hops at the same TTL (that implies different routes to
  905. the same host), but see the next paragraph for what we do when that happens.
  906. Each hop in the merged chain will be tagged with the given tag.
  907. There are many cases that must be handled correctly by this function: a and b
  908. may be equal; either may be NULL; a and b may be disjoint chains or may be
  909. joined somewhere. The biggest difficulty is when both of the chains have a
  910. hop with the same TTL but a different address. When this happens we
  911. arbitrarily choose one of the hops to unlink, on the presumption that any
  912. route through the same intermediate host at a given TTL should be the same
  913. and that differences aren't meaningful. (This has the same effect as if we
  914. were to send probes strictly serially, because then there would be no parent
  915. hops to potentially conflict, even if in fact they would if traced to
  916. completion.) */
  917. static Hop *merge_hops(const struct sockaddr_storage *tag, Hop *a, Hop *b) {
  918. Hop head, *p;
  919. p = &head;
  920. while (a != NULL && b != NULL && a != b) {
  921. Hop **next;
  922. if (a->ttl > b->ttl) {
  923. next = &a;
  924. } else if (b->ttl > a->ttl) {
  925. next = &b;
  926. } else {
  927. Hop **discard, *parent;
  928. if (b->addr.ss_family == 0) {
  929. next = &a;
  930. discard = &b;
  931. } else if (a->addr.ss_family == 0) {
  932. next = &b;
  933. discard = &a;
  934. } else {
  935. next = &a;
  936. discard = &b;
  937. if (o.debugging) {
  938. log_write(LOG_STDOUT, "Warning: %s", ss_to_string(&(*next)->addr));
  939. log_write(LOG_STDOUT, " doesn't match %s at TTL %d;",
  940. ss_to_string(&(*discard)->addr), a->ttl);
  941. log_write(LOG_STDOUT, " arbitrarily discarding %s\n",
  942. ss_to_string(&(*discard)->addr));
  943. }
  944. }
  945. parent = (*discard)->parent;
  946. *discard = parent;
  947. }
  948. p->parent = *next;
  949. p->tag = *tag;
  950. p = p->parent;
  951. *next = (*next)->parent;
  952. }
  953. /* At most one branch of this is taken, even when a == b. */
  954. if (a != NULL)
  955. p->parent = a;
  956. else if (b != NULL)
  957. p->parent = b;
  958. for ( ; p != NULL; p = p->parent)
  959. p->tag = *tag;
  960. return head.parent;
  961. }
  962. /* Record a hop at the given TTL for the given host. This takes care of linking
  963. the hop into the host's chain as well as into the global hop tree. */
  964. void TracerouteState::set_host_hop(HostState *host, u8 ttl,
  965. const struct sockaddr_storage *from_addr, float rtt) {
  966. Hop *hop;
  967. if (o.debugging > 1) {
  968. log_write(LOG_STDOUT, "Set hop %s TTL %d to %s RTT %.2f ms\n",
  969. host->target->targetipstr(), ttl, ss_to_string(from_addr), rtt);
  970. }
  971. hop = hop_cache_lookup(ttl, from_addr);
  972. if (hop == NULL) {
  973. /* A new hop, never before seen with this address and TTL. Add it to the
  974. host's chain and to the global cache. */
  975. hop = host->insert_hop(ttl, from_addr, rtt);
  976. } else {
  977. /* An existing hop at this address and TTL. Link this host's chain to it. */
  978. if (o.debugging > 1) {
  979. log_write(LOG_STDOUT, "Traceroute cache hit %s TTL %d while tracing",
  980. ss_to_string(&hop->addr), hop->ttl);
  981. log_write(LOG_STDOUT, " %s TTL %d\n", host->target->targetipstr(), ttl);
  982. }
  983. host->link_to(hop);
  984. if (host->state == HostState::COUNTING_DOWN) {
  985. /* Hit the cache going down. Seek to the end of the chain. If we have the
  986. tag for the last node, we take responsibility for finishing the trace.
  987. Otherwise, start counting up. */
  988. struct sockaddr_storage addr;
  989. size_t sslen;
  990. while (hop->parent != NULL) {
  991. hop = hop->parent;
  992. /* No need to re-probe any merged hops. */
  993. host->sent_ttls[hop->ttl] = true;
  994. }
  995. sslen = sizeof(addr);
  996. host->target->TargetSockAddr(&addr, &sslen);
  997. if (sockaddr_storage_equal(&hop->tag, &addr)) {
  998. if (o.debugging > 1) {
  999. log_write(LOG_STDOUT, "%s continuing trace from TTL %d\n",
  1000. host->target->targetipstr(), host->current_ttl);
  1001. }
  1002. } else {
  1003. host->state = HostState::COUNTING_UP;
  1004. num_active_probes -= host->cancel_probes_below(ttl);
  1005. }
  1006. }
  1007. }
  1008. }
  1009. /* Record that a hop at the given TTL for the given host timed out. */
  1010. void TracerouteState::set_host_hop_timedout(HostState *host, u8 ttl) {
  1011. static struct sockaddr_storage EMPTY_ADDR = { 0 };
  1012. host->insert_hop(ttl, &EMPTY_ADDR, -1.0);
  1013. }
  1014. struct Reply {
  1015. struct timeval rcvdtime;
  1016. struct sockaddr_storage from_addr;
  1017. struct sockaddr_storage target_addr;
  1018. u8 ttl;
  1019. u16 token;
  1020. };
  1021. static bool parse_encapsulated_reply(const void *ip, unsigned len, Reply *reply) {
  1022. struct abstract_ip_hdr hdr;
  1023. const void *data;
  1024. data = ip_get_data(ip, &len, &hdr);
  1025. if (data == NULL)
  1026. return false;
  1027. if (hdr.version == 4 && hdr.proto == IPPROTO_ICMP) {
  1028. const struct icmp *icmp = (const struct icmp *) data;
  1029. if (len < 8 || ntohs(icmp->icmp_id) != global_id)
  1030. return false;
  1031. reply->token = ntohs(icmp->icmp_seq);
  1032. } else if (hdr.version == 6 && hdr.proto == IPPROTO_ICMPV6) {
  1033. const struct icmpv6_msg_echo *echo = (struct icmpv6_msg_echo *) ((char *) data + sizeof(struct icmpv6_hdr));
  1034. if (len < 8 || ntohs(echo->icmpv6_id) != global_id)
  1035. return false;
  1036. reply->token = ntohs(echo->icmpv6_seq);
  1037. } else if (hdr.proto == IPPROTO_TCP) {
  1038. const struct tcp_hdr *tcp = (const struct tcp_hdr *) data;
  1039. if (len < 2)
  1040. return false;
  1041. reply->token = ntohs(tcp->th_sport) ^ global_id;
  1042. } else if (hdr.proto == IPPROTO_UDP) {
  1043. const struct udp_hdr *udp = (const struct udp_hdr *) data;
  1044. if (len < 2)
  1045. return false;
  1046. reply->token = ntohs(udp->uh_sport) ^ global_id;
  1047. } else if (hdr.proto == IPPROTO_SCTP) {
  1048. const struct sctp_hdr *sctp = (const struct sctp_hdr *) data;
  1049. if (len < 2)
  1050. return false;
  1051. reply->token = ntohs(sctp->sh_sport) ^ global_id;
  1052. } else {
  1053. if (len < 6)
  1054. return false;
  1055. /* Check IP ID for proto scan. */
  1056. reply->token = hdr.ipid ^ global_id;
  1057. }
  1058. reply->target_addr = hdr.dst;
  1059. return true;
  1060. }
  1061. static bool decode_reply(const void *ip, unsigned int len, Reply *reply) {
  1062. struct abstract_ip_hdr hdr;
  1063. const void *data;
  1064. data = ip_get_data(ip, &len, &hdr);
  1065. if (data == NULL)
  1066. return false;
  1067. reply->from_addr = hdr.src;
  1068. if (hdr.version == 4 && hdr.proto == IPPROTO_ICMP) {
  1069. /* ICMP responses comprise all the TTL exceeded messages we expect from all
  1070. probe types, as well as actual replies from ICMP probes. */
  1071. const struct icmp_hdr *icmp = (const struct icmp_hdr *) data;
  1072. if (len < 8)
  1073. return false;
  1074. if ((icmp->icmp_type == ICMP_TIMEXCEED
  1075. && icmp->icmp_code == ICMP_TIMEXCEED_INTRANS)
  1076. || icmp->icmp_type == ICMP_UNREACH) {
  1077. /* Get the encapsulated IP packet. */
  1078. const void *encaps = icmp_get_data(icmp, &len);
  1079. if (encaps == NULL)
  1080. return false;
  1081. return parse_encapsulated_reply(encaps, len, reply);
  1082. } else if (icmp->icmp_type == ICMP_ECHOREPLY
  1083. || icmp->icmp_type == ICMP_MASKREPLY
  1084. || icmp->icmp_type == ICMP_TSTAMPREPLY) {
  1085. /* Need this alternate form of header for icmp_id and icmp_seq. */
  1086. const struct icmp *icmp = (const struct icmp *) data;
  1087. if (ntohs(icmp->icmp_id) != global_id)
  1088. return false;
  1089. reply->token = ntohs(icmp->icmp_seq);
  1090. /* Reply came directly from the target. */
  1091. reply->target_addr = reply->from_addr;
  1092. } else {
  1093. return false;
  1094. }
  1095. } else if (hdr.version == 6 && hdr.proto == IP_PROTO_ICMPV6) {
  1096. /* ICMPv6 responses comprise all the TTL exceeded messages we expect from
  1097. all probe types, as well as actual replies from ICMP probes. */
  1098. const struct icmpv6_hdr *icmpv6 = (const struct icmpv6_hdr *) data;
  1099. if (len < 2)
  1100. return false;
  1101. /* TIMEXCEED, UNREACH */
  1102. if ((icmpv6->icmpv6_type == ICMPV6_TIMEXCEED
  1103. && icmpv6->icmpv6_code == ICMPV6_TIMEXCEED_INTRANS)
  1104. || icmpv6->icmpv6_type == ICMPV6_UNREACH) {
  1105. /* Get the encapsulated IP packet. */
  1106. const void *encaps = icmpv6_get_data(icmpv6, &len);
  1107. if (encaps == NULL)
  1108. return false;
  1109. return parse_encapsulated_reply(encaps, len, reply);
  1110. } else if (icmpv6->icmpv6_type == ICMPV6_ECHOREPLY) {
  1111. /* MASKREPLY, TSTAMPREPLY */
  1112. const struct icmpv6_msg_echo *echo;
  1113. if (len < sizeof(*icmpv6) + 4)
  1114. return false;
  1115. echo = (struct icmpv6_msg_echo *) ((char *) icmpv6 + sizeof(*icmpv6));
  1116. if (ntohs(echo->icmpv6_id) != global_id)
  1117. return false;
  1118. reply->token = ntohs(echo->icmpv6_seq);
  1119. /* Reply came directly from the target. */
  1120. reply->target_addr = reply->from_addr;
  1121. } else {
  1122. return false;
  1123. }
  1124. } else if (hdr.proto == IPPROTO_TCP) {
  1125. const struct tcp_hdr *tcp = (const struct tcp_hdr *) data;
  1126. if (len < 4)
  1127. return false;
  1128. reply->token = ntohs(tcp->th_dport) ^ global_id;
  1129. reply->target_addr = reply->from_addr;
  1130. } else if (hdr.proto == IPPROTO_UDP) {
  1131. const struct udp_hdr *udp = (const struct udp_hdr *) data;
  1132. if (len < 4)
  1133. return false;
  1134. reply->token = ntohs(udp->uh_dport) ^ global_id;
  1135. reply->target_addr = reply->from_addr;
  1136. } else if (hdr.proto == IPPROTO_SCTP) {
  1137. const struct sctp_hdr *sctp = (const struct sctp_hdr *) data;
  1138. if (len < 4)
  1139. return false;
  1140. reply->token = ntohs(sctp->sh_dport) ^ global_id;
  1141. reply->target_addr = reply->from_addr;
  1142. } else {
  1143. return false;
  1144. }
  1145. return true;
  1146. }
  1147. static bool read_reply(Reply *reply, pcap_t *pd, long timeout) {
  1148. const struct ip *ip;
  1149. unsigned int iplen;
  1150. struct link_header linkhdr;
  1151. ip = (struct ip *) readip_pcap(pd, &iplen, timeout, &reply->rcvdtime, &linkhdr, true);
  1152. if (ip == NULL)
  1153. return false;
  1154. if (ip->ip_v == 4 || ip->ip_v == 6)
  1155. return decode_reply(ip, iplen, reply);
  1156. else
  1157. return false;
  1158. }
  1159. void TracerouteState::read_replies(long timeout) {
  1160. struct sockaddr_storage ss;
  1161. struct timeval now;
  1162. size_t sslen;
  1163. Reply reply;
  1164. assert(timeout / 1000 <= (long) o.scan_delay);
  1165. timeout = MAX(timeout, 10000);
  1166. now = get_now();
  1167. while (timeout > 0 && read_reply(&reply, pd, timeout)) {
  1168. std::list<Probe *>::iterator it;
  1169. struct timeval oldnow;
  1170. HostState *host;
  1171. Probe *probe;
  1172. float rtt;
  1173. oldnow = now;
  1174. now = get_now();
  1175. timeout -= TIMEVAL_SUBTRACT(now, oldnow);
  1176. probe = this->lookup_probe(&reply.target_addr, reply.token);
  1177. if (probe == NULL)
  1178. continue;
  1179. host = probe->host;
  1180. sslen = sizeof(ss);
  1181. host->target->TargetSockAddr(&ss, &sslen);
  1182. if (sockaddr_storage_equal(&ss, &reply.from_addr)) {
  1183. adjust_timeouts2(&probe->sent_time, &reply.rcvdtime, &host->target->to);
  1184. if (host->reached_target == 0 || probe->ttl < host->reached_target)
  1185. host->reached_target = probe->ttl;
  1186. if (host->state == HostState::COUNTING_DOWN) {
  1187. /* If this probe was past the target, skip ahead to what we think the
  1188. actual distance is. */
  1189. int distance = get_initial_ttl_guess(reply.ttl) - reply.ttl + 1;
  1190. if (distance > 0 && distance < host->current_ttl)
  1191. host->current_ttl = MIN(distance, MAX_TTL);
  1192. }
  1193. num_active_probes -= host->cancel_probes_above(probe->ttl);
  1194. }
  1195. rtt = TIMEVAL_SUBTRACT(reply.rcvdtime, probe->sent_time) / 1000.0;
  1196. set_host_hop(host, probe->ttl, &reply.from_addr, rtt);
  1197. it = find(host->unanswered_probes.begin(), host->unanswered_probes.end(), probe);
  1198. num_active_probes -= host->cancel_probe(it);
  1199. }
  1200. }
  1201. void TracerouteState::cull_timeouts() {
  1202. std::list<HostState *>::iterator host_iter;
  1203. struct timeval now;
  1204. now = get_now();
  1205. for (host_iter = active_hosts.begin(); host_iter != active_hosts.end(); host_iter++) {
  1206. while (!(*host_iter)->active_probes.empty()
  1207. && (*host_iter)->active_probes.front()->is_timedout(&now)) {
  1208. Probe *probe;
  1209. probe = (*host_iter)->active_probes.front();
  1210. if (o.debugging > 1) {
  1211. log_write(LOG_STDOUT, "Traceroute probe to %s TTL %d timed out\n",
  1212. probe->host->target->targetipstr(), probe->ttl);
  1213. }
  1214. set_host_hop_timedout(*host_iter, probe->ttl);
  1215. (*host_iter)->active_probes.pop_front();
  1216. num_active_probes--;
  1217. if

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