PageRenderTime 51ms CodeModel.GetById 11ms RepoModel.GetById 0ms app.codeStats 1ms

/tcpip.cc

https://github.com/prakashgamit/nmap
C++ | 2172 lines | 1487 code | 296 blank | 389 comment | 391 complexity | c90b570ec8d1730377e5b53482654b22 MD5 | raw file
Possible License(s): BSD-3-Clause, GPL-2.0, LGPL-2.0, LGPL-2.1
  1. /***************************************************************************
  2. * tcpip.cc -- Various functions relating to low level TCP/IP handling, *
  3. * including sending raw packets, routing, printing packets, reading from *
  4. * libpcap, etc. *
  5. * *
  6. ***********************IMPORTANT NMAP LICENSE TERMS************************
  7. * *
  8. * The Nmap Security Scanner is (C) 1996-2013 Insecure.Com LLC. Nmap is *
  9. * also a registered trademark of Insecure.Com LLC. This program is free *
  10. * software; you may redistribute and/or modify it under the terms of the *
  11. * GNU General Public License as published by the Free Software *
  12. * Foundation; Version 2 ("GPL"), BUT ONLY WITH ALL OF THE CLARIFICATIONS *
  13. * AND EXCEPTIONS DESCRIBED HEREIN. This guarantees your right to use, *
  14. * modify, and redistribute this software under certain conditions. If *
  15. * you wish to embed Nmap technology into proprietary software, we sell *
  16. * alternative licenses (contact sales@nmap.com). Dozens of software *
  17. * vendors already license Nmap technology such as host discovery, port *
  18. * scanning, OS detection, version detection, and the Nmap Scripting *
  19. * Engine. *
  20. * *
  21. * Note that the GPL places important restrictions on "derivative works", *
  22. * yet it does not provide a detailed definition of that term. To avoid *
  23. * misunderstandings, we interpret that term as broadly as copyright law *
  24. * allows. For example, we consider an application to constitute a *
  25. * derivative work for the purpose of this license if it does any of the *
  26. * following with any software or content covered by this license *
  27. * ("Covered Software"): *
  28. * *
  29. * o Integrates source code from Covered Software. *
  30. * *
  31. * o Reads or includes copyrighted data files, such as Nmap's nmap-os-db *
  32. * or nmap-service-probes. *
  33. * *
  34. * o Is designed specifically to execute Covered Software and parse the *
  35. * results (as opposed to typical shell or execution-menu apps, which will *
  36. * execute anything you tell them to). *
  37. * *
  38. * o Includes Covered Software in a proprietary executable installer. The *
  39. * installers produced by InstallShield are an example of this. Including *
  40. * Nmap with other software in compressed or archival form does not *
  41. * trigger this provision, provided appropriate open source decompression *
  42. * or de-archiving software is widely available for no charge. For the *
  43. * purposes of this license, an installer is considered to include Covered *
  44. * Software even if it actually retrieves a copy of Covered Software from *
  45. * another source during runtime (such as by downloading it from the *
  46. * Internet). *
  47. * *
  48. * o Links (statically or dynamically) to a library which does any of the *
  49. * above. *
  50. * *
  51. * o Executes a helper program, module, or script to do any of the above. *
  52. * *
  53. * This list is not exclusive, but is meant to clarify our interpretation *
  54. * of derived works with some common examples. Other people may interpret *
  55. * the plain GPL differently, so we consider this a special exception to *
  56. * the GPL that we apply to Covered Software. Works which meet any of *
  57. * these conditions must conform to all of the terms of this license, *
  58. * particularly including the GPL Section 3 requirements of providing *
  59. * source code and allowing free redistribution of the work as a whole. *
  60. * *
  61. * As another special exception to the GPL terms, Insecure.Com LLC grants *
  62. * permission to link the code of this program with any version of the *
  63. * OpenSSL library which is distributed under a license identical to that *
  64. * listed in the included docs/licenses/OpenSSL.txt file, and distribute *
  65. * linked combinations including the two. *
  66. * *
  67. * Any redistribution of Covered Software, including any derived works, *
  68. * must obey and carry forward all of the terms of this license, including *
  69. * obeying all GPL rules and restrictions. For example, source code of *
  70. * the whole work must be provided and free redistribution must be *
  71. * allowed. All GPL references to "this License", are to be treated as *
  72. * including the terms and conditions of this license text as well. *
  73. * *
  74. * Because this license imposes special exceptions to the GPL, Covered *
  75. * Work may not be combined (even as part of a larger work) with plain GPL *
  76. * software. The terms, conditions, and exceptions of this license must *
  77. * be included as well. This license is incompatible with some other open *
  78. * source licenses as well. In some cases we can relicense portions of *
  79. * Nmap or grant special permissions to use it in other open source *
  80. * software. Please contact fyodor@nmap.org with any such requests. *
  81. * Similarly, we don't incorporate incompatible open source software into *
  82. * Covered Software without special permission from the copyright holders. *
  83. * *
  84. * If you have any questions about the licensing restrictions on using *
  85. * Nmap in other works, are happy to help. As mentioned above, we also *
  86. * offer alternative license to integrate Nmap into proprietary *
  87. * applications and appliances. These contracts have been sold to dozens *
  88. * of software vendors, and generally include a perpetual license as well *
  89. * as providing for priority support and updates. They also fund the *
  90. * continued development of Nmap. Please email sales@nmap.com for further *
  91. * information. *
  92. * *
  93. * If you have received a written license agreement or contract for *
  94. * Covered Software stating terms other than these, you may choose to use *
  95. * and redistribute Covered Software under those terms instead of these. *
  96. * *
  97. * Source is provided to this software because we believe users have a *
  98. * right to know exactly what a program is going to do before they run it. *
  99. * This also allows you to audit the software for security holes (none *
  100. * have been found so far). *
  101. * *
  102. * Source code also allows you to port Nmap to new platforms, fix bugs, *
  103. * and add new features. You are highly encouraged to send your changes *
  104. * to the dev@nmap.org mailing list for possible incorporation into the *
  105. * main distribution. By sending these changes to Fyodor or one of the *
  106. * Insecure.Org development mailing lists, or checking them into the Nmap *
  107. * source code repository, it is understood (unless you specify otherwise) *
  108. * that you are offering the Nmap Project (Insecure.Com LLC) the *
  109. * unlimited, non-exclusive right to reuse, modify, and relicense the *
  110. * code. Nmap will always be available Open Source, but this is important *
  111. * because the inability to relicense code has caused devastating problems *
  112. * for other Free Software projects (such as KDE and NASM). We also *
  113. * occasionally relicense the code to third parties as discussed above. *
  114. * If you wish to specify special license conditions of your *
  115. * contributions, just say so when you send them. *
  116. * *
  117. * This program is distributed in the hope that it will be useful, but *
  118. * WITHOUT ANY WARRANTY; without even the implied warranty of *
  119. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the Nmap *
  120. * license file for more details (it's in a COPYING file included with *
  121. * Nmap, and also available from https://svn.nmap.org/nmap/COPYING *
  122. * *
  123. ***************************************************************************/
  124. /* $Id$ */
  125. #ifdef WIN32
  126. #include "nmap_winconfig.h"
  127. #endif
  128. #include "nbase.h"
  129. #include "portreasons.h"
  130. #include <dnet.h>
  131. #include "tcpip.h"
  132. #include "NmapOps.h"
  133. #include "Target.h"
  134. #include "utils.h"
  135. #include "libnetutil/netutil.h"
  136. #include "struct_ip.h"
  137. #if HAVE_SYS_TIME_H
  138. #include <sys/time.h>
  139. #endif
  140. #if HAVE_UNISTD_H
  141. /* #include <sys/unistd.h> */
  142. #include <unistd.h>
  143. #endif
  144. #if HAVE_NETINET_IF_ETHER_H
  145. #ifndef NETINET_IF_ETHER_H
  146. #include <netinet/if_ether.h>
  147. #define NETINET_IF_ETHER_H
  148. #endif /* NETINET_IF_ETHER_H */
  149. #endif /* HAVE_NETINET_IF_ETHER_H */
  150. extern NmapOps o;
  151. #ifdef WIN32
  152. #include "pcap-int.h"
  153. #endif
  154. static PacketCounter PktCt;
  155. /* Create a raw socket and do things that always apply to raw sockets:
  156. * Set SO_BROADCAST.
  157. * Set IP_HDRINCL.
  158. * Bind to an interface with SO_BINDTODEVICE (if o.device is set).
  159. The socket is created with address family AF_INET, but may be usable for
  160. AF_INET6, depending on the operating system. */
  161. int nmap_raw_socket() {
  162. int rawsd;
  163. rawsd = socket(AF_INET, SOCK_RAW, IPPROTO_RAW);
  164. if (rawsd < 0)
  165. return rawsd;
  166. broadcast_socket(rawsd);
  167. #ifndef WIN32
  168. sethdrinclude(rawsd);
  169. #endif
  170. socket_bindtodevice(rawsd, o.device);
  171. return rawsd;
  172. }
  173. /* Fill buf (up to buflen -- truncate if necessary but always
  174. terminate) with a short representation of the packet stats.
  175. Returns buf. Aborts if there is a problem. */
  176. char *getFinalPacketStats(char *buf, int buflen) {
  177. char sendbytesasc[16], recvbytesasc[16];
  178. if (buflen <= 10 || !buf)
  179. fatal("%s called with woefully inadequate parameters", __func__);
  180. Snprintf(buf, buflen,
  181. #if WIN32
  182. "Raw packets sent: %I64u (%s) | Rcvd: %I64u (%s)",
  183. #else
  184. "Raw packets sent: %llu (%s) | Rcvd: %llu (%s)",
  185. #endif
  186. PktCt.sendPackets,
  187. format_bytecount(PktCt.sendBytes, sendbytesasc,
  188. sizeof(sendbytesasc)), PktCt.recvPackets,
  189. format_bytecount(PktCt.recvBytes, recvbytesasc,
  190. sizeof(recvbytesasc)));
  191. return buf;
  192. }
  193. /* Takes an ARP PACKET (not including ethernet header) and
  194. prints it if packet tracing is enabled. The
  195. direction must be PacketTrace::SENT or PacketTrace::RCVD .
  196. Optional 'now' argument makes this function slightly more
  197. efficient by avoiding a gettimeofday() call. */
  198. void PacketTrace::traceArp(pdirection pdir, const u8 *frame, u32 len,
  199. struct timeval *now) {
  200. struct timeval tv;
  201. char arpdesc[128];
  202. char who_has[INET_ADDRSTRLEN], tell[INET_ADDRSTRLEN];
  203. if (pdir == SENT) {
  204. PktCt.sendPackets++;
  205. PktCt.sendBytes += len;
  206. } else {
  207. PktCt.recvPackets++;
  208. PktCt.recvBytes += len;
  209. }
  210. if (!o.packetTrace())
  211. return;
  212. if (now)
  213. tv = *now;
  214. else
  215. gettimeofday(&tv, NULL);
  216. if (len < 28) {
  217. error("Packet tracer: Arp packets must be at least 28 bytes long. Should be exactly that length excl. ethernet padding.");
  218. return;
  219. }
  220. if (frame[7] == 1) { /* arp REQUEST */
  221. inet_ntop(AF_INET, frame + 24, who_has, sizeof(who_has));
  222. inet_ntop(AF_INET, frame + 14, tell, sizeof(tell));
  223. Snprintf(arpdesc, sizeof(arpdesc), "who-has %s tell %s", who_has, tell);
  224. } else { /* ARP REPLY */
  225. inet_ntop(AF_INET, frame + 14, who_has, sizeof(who_has));
  226. Snprintf(arpdesc, sizeof(arpdesc),
  227. "reply %s is-at %02X:%02X:%02X:%02X:%02X:%02X", who_has,
  228. frame[8], frame[9], frame[10], frame[11], frame[12],
  229. frame[13]);
  230. }
  231. log_write(LOG_STDOUT | LOG_NORMAL, "%s (%.4fs) ARP %s\n",
  232. (pdir == SENT) ? "SENT" : "RCVD",
  233. o.TimeSinceStart(&tv), arpdesc);
  234. return;
  235. }
  236. /* Takes a Neighbor Discovery packet and prints it if packet tracing is
  237. enabled. frame must point to the IPv6 header. */
  238. void PacketTrace::traceND(pdirection pdir, const u8 *frame, u32 len,
  239. struct timeval *now) {
  240. struct timeval tv;
  241. struct ip6_hdr *ip6;
  242. struct icmpv6_hdr *icmpv6;
  243. union icmpv6_msg *msg;
  244. size_t msg_len;
  245. const char *label;
  246. char src[INET6_ADDRSTRLEN], dst[INET6_ADDRSTRLEN];
  247. char who_has[INET6_ADDRSTRLEN], tgt_is[INET6_ADDRSTRLEN];
  248. char desc[128];
  249. if (pdir == SENT) {
  250. PktCt.sendPackets++;
  251. PktCt.sendBytes += len;
  252. } else {
  253. PktCt.recvPackets++;
  254. PktCt.recvBytes += len;
  255. }
  256. if (!o.packetTrace())
  257. return;
  258. if (now)
  259. tv = *now;
  260. else
  261. gettimeofday(&tv, NULL);
  262. if (len < sizeof(*ip6) + sizeof(*icmpv6)) {
  263. error("Packet tracer: ND packets must be at least %lu bytes long (is %lu).",
  264. (unsigned long) (sizeof(*ip6) + sizeof(*icmpv6)),
  265. (unsigned long) len);
  266. return;
  267. }
  268. ip6 = (struct ip6_hdr *) frame;
  269. icmpv6 = (struct icmpv6_hdr *) (frame + sizeof(*ip6));
  270. msg = (union icmpv6_msg *) (frame + sizeof(*ip6) + sizeof(*icmpv6));
  271. msg_len = frame + len - (u8 *) msg;
  272. if (icmpv6->icmpv6_type == ICMPV6_NEIGHBOR_SOLICITATION) {
  273. label = "neighbor solicitation";
  274. if (msg_len < 20) {
  275. Snprintf(desc, sizeof(desc), "packet too short");
  276. } else {
  277. inet_ntop(AF_INET6, &msg->nd.icmpv6_target, who_has, sizeof(who_has));
  278. Snprintf(desc, sizeof(desc), "who has %s", who_has);
  279. }
  280. } else if (icmpv6->icmpv6_type == ICMPV6_NEIGHBOR_ADVERTISEMENT) {
  281. label = "neighbor advertisement";
  282. if (msg_len < 28) {
  283. Snprintf(desc, sizeof(desc), "packet too short");
  284. } else if (msg->nd.icmpv6_option_length == 0 || msg->nd.icmpv6_option_type != 2) {
  285. /* We only handle target link-layer address in the first option. */
  286. Snprintf(desc, sizeof(desc), "no link-layer address");
  287. } else {
  288. inet_ntop(AF_INET6, &msg->nd.icmpv6_target, tgt_is, sizeof(tgt_is));
  289. Snprintf(desc, sizeof(desc), "%s is at %s",
  290. tgt_is, eth_ntoa(&msg->nd.icmpv6_mac));
  291. }
  292. } else {
  293. error("Unknown ICMPV6 type in %s.", __func__);
  294. return;
  295. }
  296. inet_ntop(AF_INET6, &ip6->ip6_src, src, sizeof(src));
  297. inet_ntop(AF_INET6, &ip6->ip6_dst, dst, sizeof(dst));
  298. log_write(LOG_STDOUT | LOG_NORMAL, "%s (%.4fs) %s %s > %s %s\n",
  299. (pdir == SENT) ? "SENT" : "RCVD",
  300. o.TimeSinceStart(&tv), label, src, dst, desc);
  301. return;
  302. }
  303. /* Returns a buffer of ASCII information about a packet that may look
  304. like "TCP 127.0.0.1:50923 > 127.0.0.1:3 S ttl=61 id=39516 iplen=40
  305. seq=625950769" or "ICMP PING (0/1) ttl=61 id=39516 iplen=40".
  306. IMPORTANT: This is a wrapper for function ippackethdrinfo(). Check
  307. nbase/nbase_net.c for details on the returned buffer. */
  308. static const char *nmap_format_ippacket(const u8 *packet, u32 len) {
  309. int detail = LOW_DETAIL;
  310. if (o.debugging == 2) {
  311. detail = MEDIUM_DETAIL;
  312. } else if (o.debugging >= 3) {
  313. detail = HIGH_DETAIL;
  314. }
  315. return ippackethdrinfo(packet, len, detail);
  316. }
  317. /* Takes an IP PACKET and prints it if packet tracing is enabled.
  318. 'packet' must point to the IPv4 header. The direction must be
  319. PacketTrace::SENT or PacketTrace::RCVD . Optional 'now' argument
  320. makes this function slightly more efficient by avoiding a gettimeofday()
  321. call. */
  322. void PacketTrace::trace(pdirection pdir, const u8 *packet, u32 len,
  323. struct timeval *now) {
  324. struct timeval tv;
  325. if (pdir == SENT) {
  326. PktCt.sendPackets++;
  327. PktCt.sendBytes += len;
  328. } else {
  329. PktCt.recvPackets++;
  330. PktCt.recvBytes += len;
  331. }
  332. if (!o.packetTrace())
  333. return;
  334. if (now)
  335. tv = *now;
  336. else
  337. gettimeofday(&tv, NULL);
  338. if (len < 20) {
  339. error("Packet tracer: tiny packet encountered");
  340. return;
  341. }
  342. log_write(LOG_STDOUT | LOG_NORMAL, "%s (%.4fs) %s\n",
  343. (pdir == SENT) ? "SENT" : "RCVD",
  344. o.TimeSinceStart(&tv), nmap_format_ippacket(packet, len));
  345. return;
  346. }
  347. /* Adds a trace entry when a connect() is attempted if packet tracing
  348. is enabled. Pass IPPROTO_TCP or IPPROTO_UDP as the protocol. The
  349. sock may be a sockaddr_in or sockaddr_in6. The return code of
  350. connect is passed in connectrc. If the return code is -1, get the
  351. errno and pass that as connect_errno. */
  352. void PacketTrace::traceConnect(u8 proto, const struct sockaddr *sock,
  353. int socklen, int connectrc,
  354. int connect_errno,
  355. const struct timeval *now) {
  356. struct sockaddr_in *sin = (struct sockaddr_in *) sock;
  357. #if HAVE_IPV6
  358. struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *) sock;
  359. #endif
  360. struct timeval tv;
  361. char errbuf[64] = "";
  362. char targetipstr[INET6_ADDRSTRLEN] = "";
  363. u16 targetport = 0;
  364. if (!o.packetTrace())
  365. return;
  366. if (now)
  367. tv = *now;
  368. else
  369. gettimeofday(&tv, NULL);
  370. assert(proto == IPPROTO_TCP || proto == IPPROTO_UDP);
  371. if (connectrc == 0) {
  372. Strncpy(errbuf, "Connected", sizeof(errbuf));
  373. }
  374. #if WIN32
  375. else if (connect_errno == WSAEWOULDBLOCK) {
  376. /* Special case for WSAEWOULDBLOCK. socket_strerror returns the unwieldy
  377. "A non-blocking socket operation could not be completed immediately." */
  378. Strncpy(errbuf, "Operation now in progress", sizeof(errbuf));
  379. }
  380. #endif
  381. else {
  382. Snprintf(errbuf, sizeof(errbuf), "%s", socket_strerror(connect_errno));
  383. }
  384. if (sin->sin_family == AF_INET) {
  385. if (inet_ntop(sin->sin_family, (char *) &sin->sin_addr, targetipstr,
  386. sizeof(targetipstr)) == NULL)
  387. fatal("Failed to convert target IPv4 address to presentation format!?!");
  388. targetport = ntohs(sin->sin_port);
  389. } else {
  390. #if HAVE_IPV6
  391. assert(sin->sin_family == AF_INET6);
  392. if (inet_ntop(sin->sin_family, (char *) &sin6->sin6_addr, targetipstr,
  393. sizeof(targetipstr)) == NULL)
  394. fatal("Failed to convert target IPv6 address to presentation format!?!");
  395. targetport = ntohs(sin6->sin6_port);
  396. #else
  397. assert(0);
  398. #endif
  399. }
  400. log_write(LOG_STDOUT | LOG_NORMAL,
  401. "CONN (%.4fs) %s localhost > %s:%d => %s\n",
  402. o.TimeSinceStart(&tv),
  403. (proto == IPPROTO_TCP) ? "TCP" : "UDP", targetipstr,
  404. targetport, errbuf);
  405. }
  406. /* Converts an IP address given in a sockaddr_storage to an IPv4 or
  407. IPv6 IP address string. Since a static buffer is returned, this is
  408. not thread-safe and can only be used once in calls like printf() */
  409. const char *inet_socktop(struct sockaddr_storage *ss) {
  410. static char buf[INET6_ADDRSTRLEN];
  411. struct sockaddr_in *sin = (struct sockaddr_in *) ss;
  412. #if HAVE_IPV6
  413. struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *) ss;
  414. #endif
  415. if (inet_ntop(sin->sin_family, (sin->sin_family == AF_INET) ?
  416. (char *) &sin->sin_addr :
  417. #if HAVE_IPV6
  418. (char *) &sin6->sin6_addr,
  419. #else
  420. (char *) NULL,
  421. #endif /* HAVE_IPV6 */
  422. buf, sizeof(buf)) == NULL) {
  423. fatal("Failed to convert target address to presentation format in %s!?! Error: %s", __func__, strerror(socket_errno()));
  424. }
  425. return buf;
  426. }
  427. /* Tries to resolve the given name (or literal IP) into a sockaddr structure.
  428. This function calls getaddrinfo and returns the same addrinfo linked list
  429. that getaddrinfo produces. Returns NULL for any error or failure to resolve.
  430. You need to call freeaddrinfo on the result if non-NULL. */
  431. struct addrinfo *resolve_all(const char *hostname, int pf) {
  432. struct addrinfo hints;
  433. struct addrinfo *result;
  434. int rc;
  435. memset(&hints, 0, sizeof(hints));
  436. hints.ai_family = pf;
  437. /* Otherwise we get multiple identical addresses with different socktypes. */
  438. hints.ai_socktype = SOCK_DGRAM;
  439. rc = getaddrinfo(hostname, NULL, &hints, &result);
  440. if (rc != 0)
  441. return NULL;
  442. return result;
  443. }
  444. /* Send a pre-built IPv4 packet. Handles fragmentation and whether to send with
  445. an ethernet handle or a socket. */
  446. static int send_ipv4_packet(int sd, const struct eth_nfo *eth,
  447. const struct sockaddr_in *dst,
  448. const u8 *packet, unsigned int packetlen) {
  449. struct ip *ip = (struct ip *) packet;
  450. int res;
  451. assert(packet);
  452. assert((int) packetlen > 0);
  453. /* Fragmentation requested && packet is bigger than MTU */
  454. if (o.fragscan && !(ntohs(ip->ip_off) & IP_DF) &&
  455. (packetlen - ip->ip_hl * 4 > (unsigned int) o.fragscan)) {
  456. res = send_frag_ip_packet(sd, eth, dst, packet, packetlen, o.fragscan);
  457. } else {
  458. res = send_ip_packet_eth_or_sd(sd, eth, dst, packet, packetlen);
  459. }
  460. if (res != -1)
  461. PacketTrace::trace(PacketTrace::SENT, packet, packetlen);
  462. return res;
  463. }
  464. static int send_ipv6_packet(int sd, const struct eth_nfo *eth,
  465. const struct sockaddr_in6 *dst,
  466. const u8 *packet, unsigned int packetlen) {
  467. int res;
  468. res = send_ipv6_packet_eth_or_sd(sd, eth, dst, packet, packetlen);
  469. if (res != -1)
  470. PacketTrace::trace(PacketTrace::SENT, packet, packetlen);
  471. return res;
  472. }
  473. int send_ip_packet(int sd, const struct eth_nfo *eth,
  474. const struct sockaddr_storage *dst,
  475. const u8 *packet, unsigned int packetlen) {
  476. struct ip *ip = (struct ip *) packet;
  477. /* Ensure there's enough to read ip->ip_v at least. */
  478. if (packetlen < 1)
  479. return -1;
  480. if (ip->ip_v == 4) {
  481. assert(dst->ss_family == AF_INET);
  482. return send_ipv4_packet(sd, eth, (struct sockaddr_in *) dst, packet, packetlen);
  483. } else if (ip->ip_v == 6) {
  484. assert(dst->ss_family == AF_INET6);
  485. return send_ipv6_packet(sd, eth, (struct sockaddr_in6 *) dst, packet, packetlen);
  486. }
  487. fatal("%s only understands IP versions 4 and 6 (got %u)", __func__, ip->ip_v);
  488. }
  489. /* Return an IPv4 pseudoheader checksum for the given protocol and data. Unlike
  490. ipv4_pseudoheader_cksum, this knows about STUPID_SOLARIS_CHECKSUM_BUG and
  491. takes care of o.badsum. */
  492. static u16 ipv4_cksum(const struct in_addr *src, const struct in_addr *dst,
  493. u8 proto, const void *data, u16 len) {
  494. u16 sum;
  495. #if STUPID_SOLARIS_CHECKSUM_BUG
  496. sum = len;
  497. #else
  498. sum = ipv4_pseudoheader_cksum(src, dst, proto, len, data);
  499. #endif
  500. if (o.badsum) {
  501. --sum;
  502. if (proto == IPPROTO_UDP && sum == 0)
  503. sum = 0xffff; // UDP checksum=0 means no checksum
  504. }
  505. return sum;
  506. }
  507. /* Return an IPv6 pseudoheader checksum for the given protocol and data. Unlike
  508. ipv6_pseudoheader_cksum, this takes care of o.badsum. */
  509. static u16 ipv6_cksum(const struct in6_addr *src, const struct in6_addr *dst,
  510. u8 nxt, const void *data, u16 len) {
  511. u16 sum;
  512. sum = ipv6_pseudoheader_cksum(src, dst, nxt, len, data);
  513. if (o.badsum) {
  514. --sum;
  515. if (nxt == IPPROTO_UDP && sum == 0)
  516. sum = 0xffff; // UDP checksum=0 means no checksum
  517. }
  518. return sum;
  519. }
  520. // fill ip header. no error check.
  521. // This function is also changing what's needed from host to network order.
  522. static inline int fill_ip_raw(struct ip *ip, int packetlen, const u8 *ipopt,
  523. int ipoptlen, int tos, int id,
  524. int off, int ttl, int p,
  525. const struct in_addr *ip_src,
  526. const struct in_addr *ip_dst) {
  527. ip->ip_v = 4;
  528. ip->ip_hl = 5 + (ipoptlen / 4);
  529. ip->ip_tos = tos;
  530. ip->ip_len = htons(packetlen);
  531. ip->ip_id = htons(id);
  532. ip->ip_off = htons(off);
  533. ip->ip_ttl = ttl;
  534. ip->ip_p = p;
  535. ip->ip_src.s_addr = ip_src->s_addr;
  536. ip->ip_dst.s_addr = ip_dst->s_addr;
  537. if (ipoptlen)
  538. memcpy((u8 *) ip + sizeof(struct ip), ipopt, ipoptlen);
  539. // ip options source routing hack:
  540. if (ipoptlen && o.ipopt_firsthop && o.ipopt_lasthop) {
  541. u8 *ipo = (u8 *) ip + sizeof(struct ip);
  542. struct in_addr *newdst = (struct in_addr *) &ipo[o.ipopt_firsthop];
  543. struct in_addr *olddst = (struct in_addr *) &ipo[o.ipopt_lasthop];
  544. // our destination is somewhere else :)
  545. ip->ip_dst.s_addr = newdst->s_addr;
  546. // and last hop should be destination
  547. olddst->s_addr = ip_dst->s_addr;
  548. }
  549. #if HAVE_IP_IP_SUM
  550. ip->ip_sum = 0;
  551. ip->ip_sum = in_cksum((unsigned short *) ip, sizeof(struct ip) + ipoptlen);
  552. #endif
  553. return (sizeof(struct ip) + ipoptlen);
  554. }
  555. /* Builds an IP packet (including an IP header) by packing the fields
  556. with the given information. It allocates a new buffer to store the
  557. packet contents, and then returns that buffer. The packet is not
  558. actually sent by this function. Caller must delete the buffer when
  559. finished with the packet. The packet length is returned in
  560. packetlen, which must be a valid int pointer. */
  561. u8 *build_ip_raw(const struct in_addr *source,
  562. const struct in_addr *victim, u8 proto, int ttl,
  563. u16 ipid, u8 tos, bool df, const u8 *ipopt, int ipoptlen,
  564. const char *data, u16 datalen, u32 *outpacketlen) {
  565. int packetlen = sizeof(struct ip) + ipoptlen + datalen;
  566. u8 *packet = (u8 *) safe_malloc(packetlen);
  567. struct ip *ip = (struct ip *) packet;
  568. static int myttl = 0;
  569. /* check that required fields are there and not too silly */
  570. assert(source);
  571. assert(victim);
  572. assert(ipoptlen % 4 == 0);
  573. /* Time to live */
  574. if (ttl == -1) {
  575. myttl = (get_random_uint() % 23) + 37;
  576. } else {
  577. myttl = ttl;
  578. }
  579. fill_ip_raw(ip, packetlen, ipopt, ipoptlen,
  580. tos, ipid, df ? IP_DF : 0, myttl, proto, source, victim);
  581. /* We should probably copy the data over too */
  582. if (data && datalen)
  583. memcpy((u8 *) ip + sizeof(struct ip) + ipoptlen, data, datalen);
  584. *outpacketlen = packetlen;
  585. return packet;
  586. }
  587. u8 *build_ipv6_raw(const struct in6_addr *source,
  588. const struct in6_addr *victim, u8 tc, u32 flowlabel,
  589. u8 nextheader, int hoplimit,
  590. const char *data, u16 datalen, u32 *outpacketlen) {
  591. u8 *packet;
  592. assert(source != NULL);
  593. assert(victim != NULL);
  594. if (hoplimit == -1)
  595. hoplimit = (get_random_uint() % 23) + 37;
  596. *outpacketlen = sizeof(struct ip6_hdr) + datalen;
  597. packet = (u8 *) safe_malloc(*outpacketlen);
  598. ip6_pack_hdr(packet, tc, flowlabel, datalen, nextheader, hoplimit, *source, *victim);
  599. memcpy(packet + sizeof(struct ip6_hdr), data, datalen);
  600. return packet;
  601. }
  602. /* Build a TCP packet (no IP header). Sets tcp->th_sum to 0 so it can be filled
  603. in by a function with knowledge of the higher-level pseudoheader. */
  604. static u8 *build_tcp(u16 sport, u16 dport, u32 seq, u32 ack, u8 reserved,
  605. u8 flags, u16 window, u16 urp,
  606. const u8 *tcpopt, int tcpoptlen,
  607. const char *data, u16 datalen, u32 *packetlen) {
  608. struct tcp_hdr *tcp;
  609. u8 *packet;
  610. if (tcpoptlen % 4 != 0)
  611. fatal("%s called with an option length argument of %d which is illegal because it is not divisible by 4. Just add \\0 padding to the end.", __func__, tcpoptlen);
  612. *packetlen = sizeof(*tcp) + tcpoptlen + datalen;
  613. packet = (u8 *) safe_malloc(*packetlen);
  614. tcp = (struct tcp_hdr *) packet;
  615. memset(tcp, 0, sizeof(*tcp));
  616. tcp->th_sport = htons(sport);
  617. tcp->th_dport = htons(dport);
  618. if (seq)
  619. tcp->th_seq = htonl(seq);
  620. else if (flags & TH_SYN)
  621. get_random_bytes(&(tcp->th_seq), 4);
  622. if (ack)
  623. tcp->th_ack = htonl(ack);
  624. if (reserved)
  625. tcp->th_x2 = reserved & 0x0F;
  626. tcp->th_off = 5 + (tcpoptlen / 4); /* words */
  627. tcp->th_flags = flags;
  628. if (window)
  629. tcp->th_win = htons(window);
  630. else
  631. tcp->th_win = htons(1024); /* Who cares */
  632. if (urp)
  633. tcp->th_urp = htons(urp);
  634. /* And the options */
  635. if (tcpoptlen)
  636. memcpy(packet + sizeof(*tcp), tcpopt, tcpoptlen);
  637. /* We should probably copy the data over too */
  638. if (data && datalen)
  639. memcpy(packet + sizeof(*tcp) + tcpoptlen, data, datalen);
  640. tcp->th_sum = 0;
  641. return packet;
  642. }
  643. /* Builds a TCP packet (including an IP header) by packing the fields
  644. with the given information. It allocates a new buffer to store the
  645. packet contents, and then returns that buffer. The packet is not
  646. actually sent by this function. Caller must delete the buffer when
  647. finished with the packet. The packet length is returned in
  648. packetlen, which must be a valid int pointer. */
  649. u8 *build_tcp_raw(const struct in_addr *source,
  650. const struct in_addr *victim, int ttl, u16 ipid, u8 tos,
  651. bool df, const u8 *ipopt, int ipoptlen, u16 sport, u16 dport,
  652. u32 seq, u32 ack, u8 reserved, u8 flags, u16 window,
  653. u16 urp, const u8 *tcpopt, int tcpoptlen, const char *data,
  654. u16 datalen, u32 *packetlen) {
  655. struct tcp_hdr *tcp;
  656. u32 tcplen;
  657. u8 *ip;
  658. tcp = (struct tcp_hdr *) build_tcp(sport, dport, seq, ack, reserved, flags,
  659. window, urp, tcpopt, tcpoptlen, data, datalen, &tcplen);
  660. tcp->th_sum = ipv4_cksum(source, victim, IPPROTO_TCP, tcp, tcplen);
  661. ip = build_ip_raw(source, victim, IPPROTO_TCP, ttl, ipid, tos, df,
  662. ipopt, ipoptlen, (char *) tcp, tcplen, packetlen);
  663. free(tcp);
  664. return ip;
  665. }
  666. /* Builds a TCP packet (including an IPv6 header) by packing the fields
  667. with the given information. It allocates a new buffer to store the
  668. packet contents, and then returns that buffer. The packet is not
  669. actually sent by this function. Caller must delete the buffer when
  670. finished with the packet. The packet length is returned in
  671. packetlen, which must be a valid int pointer. */
  672. u8 *build_tcp_raw_ipv6(const struct in6_addr *source,
  673. const struct in6_addr *victim, u8 tc, u32 flowlabel,
  674. u8 hoplimit, u16 sport, u16 dport, u32 seq, u32 ack,
  675. u8 reserved, u8 flags, u16 window, u16 urp,
  676. const u8 *tcpopt, int tcpoptlen, const char *data,
  677. u16 datalen, u32 *packetlen) {
  678. struct tcp_hdr *tcp;
  679. u32 tcplen;
  680. u8 *ipv6;
  681. tcp = (struct tcp_hdr *) build_tcp(sport, dport, seq, ack, reserved, flags,
  682. window, urp, tcpopt, tcpoptlen, data, datalen, &tcplen);
  683. tcp->th_sum = ipv6_cksum(source, victim, IPPROTO_TCP, tcp, tcplen);
  684. ipv6 = build_ipv6_raw(source, victim, tc, flowlabel, IPPROTO_TCP, hoplimit,
  685. (char *) tcp, tcplen, packetlen);
  686. free(tcp);
  687. return ipv6;
  688. }
  689. /* You need to call sethdrinclude(sd) on the sending sd before calling this */
  690. int send_tcp_raw(int sd, const struct eth_nfo *eth,
  691. const struct in_addr *source,
  692. const struct in_addr *victim, int ttl, bool df,
  693. u8 *ipops, int ipoptlen, u16 sport, u16 dport, u32 seq,
  694. u32 ack, u8 reserved, u8 flags, u16 window, u16 urp,
  695. u8 *options, int optlen, const char *data, u16 datalen) {
  696. struct sockaddr_storage dst;
  697. struct sockaddr_in *dst_in;
  698. unsigned int packetlen;
  699. int res = -1;
  700. u8 *packet = build_tcp_raw(source, victim,
  701. ttl, get_random_u16(), IP_TOS_DEFAULT, df,
  702. ipops, ipoptlen,
  703. sport, dport,
  704. seq, ack, reserved, flags, window, urp,
  705. options, optlen,
  706. data, datalen, &packetlen);
  707. if (!packet)
  708. return -1;
  709. memset(&dst, 0, sizeof(dst));
  710. dst_in = (struct sockaddr_in *) &dst;
  711. dst_in->sin_family = AF_INET;
  712. dst_in->sin_addr = *victim;
  713. res = send_ip_packet(sd, eth, &dst, packet, packetlen);
  714. free(packet);
  715. return res;
  716. }
  717. int send_tcp_raw_decoys(int sd, const struct eth_nfo *eth,
  718. const struct in_addr *victim,
  719. int ttl, bool df,
  720. u8 *ipopt, int ipoptlen,
  721. u16 sport, u16 dport,
  722. u32 seq, u32 ack, u8 reserved, u8 flags,
  723. u16 window, u16 urp, u8 *options, int optlen,
  724. const char *data, u16 datalen) {
  725. int decoy;
  726. for (decoy = 0; decoy < o.numdecoys; decoy++)
  727. if (send_tcp_raw(sd, eth,
  728. &o.decoys[decoy], victim,
  729. ttl, df,
  730. ipopt, ipoptlen,
  731. sport, dport,
  732. seq, ack, reserved, flags, window, urp,
  733. options, optlen, data, datalen) == -1)
  734. return -1;
  735. return 0;
  736. }
  737. /* Build a UDP packet (no IP header). Sets udp->uh_sum to 0 so it can be filled
  738. in by a function with knowledge of the higher-level pseudoheader. */
  739. static u8 *build_udp(u16 sport, u16 dport, const char *data, u16 datalen,
  740. u32 *packetlen) {
  741. struct udp_hdr *udp;
  742. u8 *packet;
  743. *packetlen = sizeof(*udp) + datalen;
  744. packet = (u8 *) safe_malloc(*packetlen);
  745. udp = (struct udp_hdr *) packet;
  746. memset(udp, 0, sizeof(*udp));
  747. udp->uh_sport = htons(sport);
  748. udp->uh_dport = htons(dport);
  749. udp->uh_ulen = htons(*packetlen);
  750. if (data && datalen)
  751. memcpy(packet + sizeof(*udp), data, datalen);
  752. udp->uh_sum = 0;
  753. return packet;
  754. }
  755. /* Builds a UDP packet (including an IP header) by packing the fields
  756. with the given information. It allocates a new buffer to store the
  757. packet contents, and then returns that buffer. The packet is not
  758. actually sent by this function. Caller must delete the buffer when
  759. finished with the packet. The packet length is returned in
  760. packetlen, which must be a valid int pointer. */
  761. u8 *build_udp_raw(const struct in_addr *source, const struct in_addr *victim,
  762. int ttl, u16 ipid, u8 tos, bool df,
  763. u8 *ipopt, int ipoptlen,
  764. u16 sport, u16 dport,
  765. const char *data, u16 datalen, u32 *packetlen) {
  766. struct udp_hdr *udp;
  767. u32 udplen;
  768. u8 *ip;
  769. udp = (struct udp_hdr *) build_udp(sport, dport, data, datalen, &udplen);
  770. udp->uh_sum = ipv4_cksum(source, victim, IPPROTO_UDP, udp, udplen);
  771. ip = build_ip_raw(source, victim, IPPROTO_UDP, ttl, ipid, tos, df,
  772. ipopt, ipoptlen, (char *) udp, udplen, packetlen);
  773. free(udp);
  774. return ip;
  775. }
  776. /* Builds a UDP packet (including an IPv6 header) by packing the fields
  777. with the given information. It allocates a new buffer to store the
  778. packet contents, and then returns that buffer. The packet is not
  779. actually sent by this function. Caller must delete the buffer when
  780. finished with the packet. The packet length is returned in
  781. packetlen, which must be a valid int pointer. */
  782. u8 *build_udp_raw_ipv6(const struct in6_addr *source,
  783. const struct in6_addr *victim, u8 tc, u32 flowlabel,
  784. u8 hoplimit, u16 sport, u16 dport,
  785. const char *data, u16 datalen, u32 *packetlen) {
  786. struct udp_hdr *udp;
  787. u32 udplen;
  788. u8 *ipv6;
  789. udp = (struct udp_hdr *) build_udp(sport, dport, data, datalen, &udplen);
  790. udp->uh_sum = ipv6_cksum(source, victim, IPPROTO_UDP, udp, udplen);
  791. ipv6 = build_ipv6_raw(source, victim, tc, flowlabel, IPPROTO_UDP, hoplimit,
  792. (char *) udp, udplen, packetlen);
  793. free(udp);
  794. return ipv6;
  795. }
  796. int send_udp_raw(int sd, const struct eth_nfo *eth,
  797. struct in_addr *source, const struct in_addr *victim,
  798. int ttl, u16 ipid,
  799. u8 *ipopt, int ipoptlen,
  800. u16 sport, u16 dport, const char *data, u16 datalen) {
  801. struct sockaddr_storage dst;
  802. struct sockaddr_in *dst_in;
  803. unsigned int packetlen;
  804. int res = -1;
  805. u8 *packet = build_udp_raw(source, victim,
  806. ttl, ipid, IP_TOS_DEFAULT, false,
  807. ipopt, ipoptlen,
  808. sport, dport,
  809. data, datalen, &packetlen);
  810. if (!packet)
  811. return -1;
  812. memset(&dst, 0, sizeof(dst));
  813. dst_in = (struct sockaddr_in *) &dst;
  814. dst_in->sin_family = AF_INET;
  815. dst_in->sin_addr = *victim;
  816. res = send_ip_packet(sd, eth, &dst, packet, packetlen);
  817. free(packet);
  818. return res;
  819. }
  820. int send_udp_raw_decoys(int sd, const struct eth_nfo *eth,
  821. const struct in_addr *victim,
  822. int ttl, u16 ipid,
  823. u8 *ipops, int ipoptlen,
  824. u16 sport, u16 dport, const char *data, u16 datalen) {
  825. int decoy;
  826. for (decoy = 0; decoy < o.numdecoys; decoy++)
  827. if (send_udp_raw(sd, eth, &o.decoys[decoy], victim,
  828. ttl, ipid, ipops, ipoptlen,
  829. sport, dport, data, datalen) == -1)
  830. return -1;
  831. return 0;
  832. }
  833. /* Build an SCTP packet (no IP header). */
  834. static u8 *build_sctp(u16 sport, u16 dport, u32 vtag,
  835. const char *chunks, int chunkslen,
  836. const char *data, u16 datalen,
  837. u32 *packetlen) {
  838. struct sctp_hdr *sctp;
  839. u8 *packet;
  840. *packetlen = sizeof(*sctp) + chunkslen + datalen;
  841. packet = (u8 *) safe_malloc(*packetlen);
  842. sctp = (struct sctp_hdr *) packet;
  843. sctp->sh_sport = htons(sport);
  844. sctp->sh_dport = htons(dport);
  845. sctp->sh_sum = 0;
  846. sctp->sh_vtag = htonl(vtag);
  847. if (chunks)
  848. memcpy(packet + sizeof(*sctp), chunks, chunkslen);
  849. if (data)
  850. memcpy(packet + sizeof(*sctp) + chunkslen, data, datalen);
  851. /* RFC 2960 originally defined Adler32 checksums, which was later
  852. * revised to CRC32C in RFC 3309 and RFC 4960 respectively.
  853. * Nmap uses CRC32C by default, unless --adler32 is given. */
  854. if (o.adler32)
  855. sctp->sh_sum = htonl(nbase_adler32(packet, *packetlen));
  856. else
  857. sctp->sh_sum = htonl(nbase_crc32c(packet, *packetlen));
  858. if (o.badsum)
  859. --sctp->sh_sum;
  860. return packet;
  861. }
  862. /* Builds an SCTP packet (including an IP header) by packing the fields
  863. with the given information. It allocates a new buffer to store the
  864. packet contents, and then returns that buffer. The packet is not
  865. actually sent by this function. Caller must delete the buffer when
  866. finished with the packet. The packet length is returned in
  867. packetlen, which must be a valid int pointer. */
  868. u8 *build_sctp_raw(const struct in_addr *source,
  869. const struct in_addr *victim, int ttl, u16 ipid,
  870. u8 tos, bool df, u8 *ipopt, int ipoptlen, u16 sport,
  871. u16 dport, u32 vtag, char *chunks, int chunkslen,
  872. const char *data, u16 datalen, u32 *packetlen) {
  873. u8 *ip, *sctp;
  874. u32 sctplen;
  875. sctp = build_sctp(sport, dport, vtag, chunks, chunkslen, data, datalen, &sctplen);
  876. ip = build_ip_raw(source, victim, IPPROTO_SCTP, ttl, ipid, tos, df,
  877. ipopt, ipoptlen, (char *) sctp, sctplen, packetlen);
  878. free(sctp);
  879. return ip;
  880. }
  881. u8 *build_sctp_raw_ipv6(const struct in6_addr *source,
  882. const struct in6_addr *victim, u8 tc, u32 flowlabel,
  883. u8 hoplimit, u16 sport, u16 dport, u32 vtag,
  884. char *chunks, int chunkslen, const char *data, u16 datalen,
  885. u32 *packetlen) {
  886. u8 *ipv6, *sctp;
  887. u32 sctplen;
  888. sctp = build_sctp(sport, dport, vtag, chunks, chunkslen, data, datalen, &sctplen);
  889. ipv6 = build_ipv6_raw(source, victim, tc, flowlabel, IPPROTO_SCTP, hoplimit,
  890. (char *) sctp, sctplen, packetlen);
  891. free(sctp);
  892. return ipv6;
  893. }
  894. /* Builds an ICMP packet (including an IP header) by packing the fields
  895. with the given information. It allocates a new buffer to store the
  896. packet contents, and then returns that buffer. The packet is not
  897. actually sent by this function. Caller must delete the buffer when
  898. finished with the packet. The packet length is returned in
  899. packetlen, which must be a valid int pointer. The id/seq will be converted
  900. to network byte order (if it differs from HBO) */
  901. u8 *build_icmp_raw(const struct in_addr *source,
  902. const struct in_addr *victim, int ttl, u16 ipid,
  903. u8 tos, bool df, u8 *ipopt, int ipoptlen, u16 seq,
  904. unsigned short id, u8 ptype, u8 pcode, const char *data,
  905. u16 datalen, u32 *packetlen) {
  906. struct ppkt {
  907. u8 type;
  908. u8 code;
  909. u16 checksum;
  910. u16 id;
  911. u16 seq;
  912. u8 data[1500]; /* Note -- first 4-12 bytes can be used for ICMP header */
  913. } pingpkt;
  914. u8 *datastart = pingpkt.data;
  915. /* dlen is the amount of space remaining in the data buffer; it may be reduced
  916. depending on type. */
  917. int dlen = sizeof(pingpkt.data);
  918. int icmplen = 0;
  919. char *ping = (char *) &pingpkt;
  920. pingpkt.type = ptype;
  921. pingpkt.code = pcode;
  922. if (ptype == 8) {
  923. /* echo request */
  924. icmplen = 8;
  925. } else if (ptype == 13 && pcode == 0) {
  926. /* ICMP timestamp req */
  927. icmplen = 20;
  928. memset(datastart, 0, 12);
  929. datastart += 12;
  930. dlen -= 12;
  931. } else if (ptype == 17 && pcode == 0) {
  932. /* icmp netmask req */
  933. icmplen = 12;
  934. memset(datastart, 0, 4);
  935. datastart += 4;
  936. dlen -= 4;
  937. } else {
  938. fatal("Unknown icmp type/code (%d/%d) in %s", ptype, pcode, __func__);
  939. }
  940. /* Copy the data over too */
  941. if (datalen > 0) {
  942. icmplen += MIN(dlen, datalen);
  943. if (data == NULL)
  944. memset(datastart, 0, MIN(dlen, datalen));
  945. else
  946. memcpy(datastart, data, MIN(dlen, datalen));
  947. }
  948. /* Fill out the ping packet. All the ICMP types handled by this function have
  949. the id and seq fields. */
  950. pingpkt.id = htons(id);
  951. pingpkt.seq = htons(seq);
  952. pingpkt.checksum = 0;
  953. pingpkt.checksum = in_cksum((unsigned short *) ping, icmplen);
  954. if (o.badsum)
  955. --pingpkt.checksum;
  956. return build_ip_raw(source, victim, IPPROTO_ICMP, ttl, ipid, tos, df,
  957. ipopt, ipoptlen, ping, icmplen, packetlen);
  958. }
  959. /* Builds an ICMPv6 packet (including an IPv6 header). */
  960. u8 *build_icmpv6_raw(const struct in6_addr *source,
  961. const struct in6_addr *victim, u8 tc, u32 flowlabel,
  962. u8 hoplimit, u16 seq, u16 id, u8 ptype, u8 pcode,
  963. const char *data, u16 datalen, u32 *packetlen) {
  964. char *packet;
  965. struct icmpv6_hdr *icmpv6;
  966. union icmpv6_msg *msg;
  967. unsigned int icmplen;
  968. u8 *ipv6;
  969. packet = (char *) safe_malloc(sizeof(*icmpv6) + sizeof(*msg) + datalen);
  970. icmpv6 = (struct icmpv6_hdr *) packet;
  971. msg = (union icmpv6_msg *) (packet + sizeof(*icmpv6));
  972. icmplen = sizeof(*icmpv6);
  973. icmpv6->icmpv6_type = ptype;
  974. icmpv6->icmpv6_code = pcode;
  975. if (ptype == ICMPV6_ECHO) {
  976. msg->echo.icmpv6_seq = htons(seq);
  977. msg->echo.icmpv6_id = htons(id);
  978. icmplen += sizeof(msg->echo);
  979. }
  980. /* At this point icmplen <= sizeof(*icmpv6) + sizeof(*msg). */
  981. memcpy(packet + icmplen, data, datalen);
  982. icmplen += datalen;
  983. icmpv6->icmpv6_cksum = 0;
  984. icmpv6->icmpv6_cksum = ipv6_pseudoheader_cksum(source, victim,
  985. IPPROTO_ICMPV6, icmplen, icmpv6);
  986. if (o.badsum)
  987. icmpv6->icmpv6_cksum--;
  988. ipv6 = build_ipv6_raw(source, victim, tc, flowlabel, IPPROTO_ICMPV6, hoplimit,
  989. packet, icmplen, packetlen);
  990. free(packet);
  991. return ipv6;
  992. }
  993. /* Builds an IGMP packet (including an IP header) by packing the fields
  994. with the given information. It allocates a new buffer to store the
  995. packet contents, and then returns that buffer. The packet is not
  996. actually sent by this function. Caller must delete the buffer when
  997. finished with the packet. The packet length is returned in packetlen,
  998. which must be a valid int pointer. */
  999. u8 *build_igmp_raw(const struct in_addr *source,
  1000. const struct in_addr *victim, int ttl, u16 ipid,
  1001. u8 tos, bool df, u8 *ipopt, int ipoptlen, u8 ptype,
  1002. u8 pcode, const char *data, u16 datalen, u32 *packetlen) {
  1003. struct {
  1004. u8 igmp_type;
  1005. u8 igmp_code;
  1006. u16 igmp_cksum;
  1007. u32 var; /* changes between types, unused. usually group address. */
  1008. u8 data[1500];
  1009. } igmp;
  1010. u32 *datastart = (u32 *) igmp.data;
  1011. int dlen = sizeof(igmp.data);
  1012. int igmplen = 0;
  1013. char *pkt = (char *) &igmp;
  1014. igmp.igmp_type = ptype;
  1015. igmp.igmp_code = pcode;
  1016. if (ptype == 0x11) {
  1017. /* Membership Query */
  1018. igmplen = 8;
  1019. } else if (ptype == 0x12) {
  1020. /* v1 Membership Report */
  1021. igmplen = 8;
  1022. } else if (ptype == 0x16) {
  1023. /* v2 Membership Report */
  1024. igmplen = 8;
  1025. } else if (ptype == 0x17) {
  1026. /* v2 Leave Group */
  1027. igmplen = 8;
  1028. } else if (ptype == 0x22) {
  1029. /* v3 Membership Report */
  1030. igmplen = 8;
  1031. } else {
  1032. fatal("Unknown igmp type (%d) in %s", ptype, __func__);
  1033. }
  1034. if (datalen > 0) {
  1035. igmplen += MIN(dlen, datalen);
  1036. if (data == NULL)
  1037. memset(datastart, 0, MIN(dlen, datalen));
  1038. else
  1039. memcpy(datastart, data, MIN(dlen, datalen));
  1040. }
  1041. igmp.igmp_cksum = 0;
  1042. igmp.igmp_cksum = in_cksum((unsigned short *) pkt, igmplen);
  1043. if (o.badsum)
  1044. --igmp.igmp_cksum;
  1045. return build_ip_raw(source, victim, IPPROTO_IGMP, ttl, ipid, tos, df,
  1046. ipopt, ipoptlen, pkt, igmplen, packetlen);
  1047. }
  1048. /* A simple function I wrote to help in debugging, shows the important fields
  1049. of a TCP packet*/
  1050. int readtcppacket(const u8 *packet, int readdata) {
  1051. struct ip *ip = (struct ip *) packet;
  1052. struct tcp_hdr *tcp = (struct tcp_hdr *) (packet + sizeof(struct ip));
  1053. const unsigned char *data = packet + sizeof(struct ip) + sizeof(struct tcp_hdr);
  1054. int tot_len;
  1055. struct in_addr bullshit, bullshit2;
  1056. char sourcehost[16];
  1057. int i;
  1058. int realfrag = 0;
  1059. if (!packet) {
  1060. error("%s: packet is NULL!", __func__);
  1061. return -1;
  1062. }
  1063. bullshit.s_addr = ip->ip_src.s_addr;
  1064. bullshit2.s_addr = ip->ip_dst.s_addr;
  1065. realfrag = htons(ntohs(ip->ip_off) & IP_OFFMASK);
  1066. tot_len = htons(ip->ip_len);
  1067. strncpy(sourcehost, inet_ntoa(bullshit), 16);
  1068. i = 4 * (ntohs(ip->ip_hl) + ntohs(tcp->th_off));
  1069. if (ip->ip_p == IPPROTO_TCP) {
  1070. if (realfrag)
  1071. log_write(LOG_PLAIN, "Packet is fragmented, offset field: %u\n",
  1072. realfrag);
  1073. else {
  1074. log_write(LOG_PLAIN,
  1075. "TCP packet: %s:%d -> %s:%d (total: %d bytes)\n",
  1076. sourcehost, ntohs(tcp->th_sport), inet_ntoa(bullshit2),
  1077. ntohs(tcp->th_dport), tot_len);
  1078. log_write(LOG_PLAIN, "Flags: ");
  1079. if (!tcp->th_flags)
  1080. log_write(LOG_PLAIN, "(none)");
  1081. if (tcp->th_flags & TH_RST)
  1082. log_write(LOG_PLAIN, "RST ");
  1083. if (tcp->th_flags & TH_SYN)
  1084. log_write(LOG_PLAIN, "SYN ");
  1085. if (tcp->th_flags & TH_ACK)
  1086. log_write(LOG_PLAIN, "ACK ");
  1087. if (tcp->th_flags & TH_PUSH)
  1088. log_write(LOG_PLAIN, "PSH ");
  1089. if (tcp->th_flags & TH_FIN)
  1090. log_write(LOG_PLAIN, "FIN ");
  1091. if (tcp->th_flags & TH_URG)
  1092. log_write(LOG_PLAIN, "URG ");
  1093. log_write(LOG_PLAIN, "\n");
  1094. log_write(LOG_PLAIN, "ipid: %hu ttl: %hu ", ntohs(ip->ip_id),
  1095. ip->ip_ttl);
  1096. if (tcp->th_flags & (TH_SYN | TH_ACK))
  1097. log_write(LOG_PLAIN, "Seq: %u\tAck: %u\n",
  1098. (unsigned int) ntohl(tcp->th_seq),
  1099. (unsigned int) ntohl(tcp->th_ack));
  1100. else if (tcp->th_flags & TH_SYN)
  1101. log_write(LOG_PLAIN, "Seq: %u\n",
  1102. (unsigned int) ntohl(tcp->th_seq));
  1103. else if (tcp->th_flags & TH_ACK)
  1104. log_write(LOG_PLAIN, "Ack: %u\n",
  1105. (unsigned int) ntohl(tcp->th_ack));
  1106. }
  1107. }
  1108. if (readdata && i < tot_len) {
  1109. log_write(LOG_PLAIN, "Data portion:\n");
  1110. while (i < tot_len) {
  1111. log_write(LOG_PLAIN, "%2X%c", data[i], ((i + 1) % 16) ? ' ' : '\n');
  1112. i++;
  1113. }
  1114. log_write(LOG_PLAIN, "\n");
  1115. }
  1116. return 0;
  1117. }
  1118. /* A simple function I wrote to help in debugging, shows the important fields
  1119. of a UDP packet*/
  1120. int readudppacket(const u8 *packet, int readdata) {
  1121. struct ip *ip = (struct ip *) packet;
  1122. struct udp_hdr *udp = (struct udp_hdr *) (packet + sizeof(struct ip));
  1123. const unsigned char *data = packet + sizeof(struct ip) + sizeof(struct udp_hdr);
  1124. int tot_len;
  1125. struct in_addr bullshit, bullshit2;
  1126. char sourcehost[16];
  1127. int i;
  1128. int realfrag = 0;
  1129. if (!packet) {
  1130. error("%s: packet is NULL!", __func__);
  1131. return -1;
  1132. }
  1133. bullshit.s_addr = ip->ip_src.s_addr;
  1134. bullshit2.s_addr = ip->ip_dst.s_addr;
  1135. realfrag = htons(ntohs(ip->ip_off) & IP_OFFMASK);
  1136. tot_len = htons(ip->ip_len);
  1137. strncpy(sourcehost, inet_ntoa(bullshit), 16);
  1138. i = 4 * (ntohs(ip->ip_hl)) + 8;
  1139. if (ip->ip_p == IPPROTO_UDP) {
  1140. if (realfrag)
  1141. log_write(LOG_PLAIN, "Packet is fragmented, offset field: %u\n",
  1142. realfrag);
  1143. else {
  1144. log_write(LOG_PLAIN,
  1145. "UDP packet: %s:%d -> %s:%d (total: %d bytes)\n",
  1146. sourcehost, ntohs(udp->uh_sport), inet_ntoa(bullshit2),
  1147. ntohs(udp->uh_dport), tot_len);
  1148. log_write(LOG_PLAIN, "ttl: %hu ", ip->ip_ttl);
  1149. }
  1150. }
  1151. if (readdata && i < tot_len) {
  1152. log_write(LOG_PLAIN, "Data portion:\n");
  1153. while (i < tot_len) {
  1154. log_write(LOG_PLAIN, "%2X%c", data[i], ((i + 1) % 16) ? ' ' : '\n');
  1155. i++;
  1156. }
  1157. log_write(LOG_PLAIN, "\n");
  1158. }
  1159. return 0;
  1160. }
  1161. /* Used by validatepkt() to validate the TCP header (including option lengths).
  1162. The options checked are MSS, WScale, SackOK, Sack, and Timestamp. */
  1163. static bool validateTCPhdr(u8 *tcpc, unsigned len) {
  1164. struct tcp_hdr *tcp = (struct tcp_hdr *) tcpc;
  1165. unsigned hdrlen, optlen;
  1166. hdrlen = tcp->th_off * 4;
  1167. /* Check header length */
  1168. if (hdrlen > len || hdrlen < sizeof(struct tcp_hdr))
  1169. return false;
  1170. /* Get to the options */
  1171. tcpc += sizeof(struct tcp_hdr);
  1172. optlen = hdrlen - sizeof(struct tcp_hdr);
  1173. while (optlen > 0) {
  1174. switch (*tcpc) {
  1175. case 2: /* MSS */
  1176. if (optlen < 4)
  1177. return false;
  1178. optlen -= 4;
  1179. tcpc += 4;
  1180. break;
  1181. case 3: /* Window Scale */
  1182. if (optlen < 3)
  1183. return false;
  1184. optlen -= 3;
  1185. tcpc += 3;
  1186. break;
  1187. case 4: /* SACK Permitted */
  1188. if (optlen < 2)
  1189. return false;
  1190. optlen -= 2;
  1191. tcpc += 2;
  1192. break;
  1193. case 5: /* SACK */
  1194. if (optlen < *++tcpc)
  1195. return false;
  1196. if (!(*tcpc - 2) || ((*tcpc - 2) % 8))
  1197. return false;
  1198. optlen -= *tcpc;
  1199. tcpc += (*tcpc - 1);
  1200. break;
  1201. case 8: /* Timestamp */
  1202. if (optlen < 10)
  1203. return false;
  1204. optlen -= 10;
  1205. tcpc += 10;
  1206. break;
  1207. default:
  1208. optlen--;
  1209. tcpc++;
  1210. break;
  1211. }
  1212. }
  1213. return true;
  1214. }
  1215. /* Used by readip_pcap() to validate an IP packet. It checks to make sure:
  1216. *
  1217. * 1) there is enough room for an IP header in the amount of bytes read
  1218. * 2) the IP version number is correct
  1219. * 3) the IP length fields are at least as big as the standard header
  1220. * 4) the IP packet received isn't a fragment, or is the initial fragment
  1221. * 5) that next level headers seem reasonable (e.g. validateTCPhdr())
  1222. *
  1223. * Checking the IP total length (iplen) to see if its at least as large as the
  1224. * number of bytes read (len) does not work because things like the Ethernet
  1225. * CRC also get captured and are counted in len. However, since the IP total
  1226. * length field can't be trusted, we use len instead of iplen when doing any
  1227. * further checks on lengths. readip_pcap fixes the length on it's end if we
  1228. * read more than the IP header says we should have so as to not pass garbage
  1229. * data to the caller.
  1230. */
  1231. static bool validatepkt(u8 *ipc, unsigned *len) {
  1232. struct ip *ip = (struct ip *) ipc;
  1233. const void *data;
  1234. unsigned int datalen, iplen;
  1235. u8 hdr;
  1236. if (*len < 1) {
  1237. if (o.debugging >= 3)
  1238. error("Rejecting tiny, supposed IP packet (size %u)", *len);
  1239. return false;
  1240. }
  1241. if (ip->ip_v == 4) {
  1242. unsigned fragoff, iplen;
  1243. datalen = *len;
  1244. data = ipv4_get_data(ip, &datalen);
  1245. if (data == NULL) {
  1246. if (o.debugging >= 3)
  1247. error("Rejecting IP packet because of invalid length");
  1248. return false;
  1249. }
  1250. iplen = ntohs(ip->ip_len);
  1251. fragoff = 8 * (ntohs(ip->ip_off) & IP_OFFMASK);
  1252. if (fragoff) {
  1253. if (o.debugging >= 3)
  1254. error("Rejecting IP fragment (offset %u)", fragoff);
  1255. return false;
  1256. }
  1257. /* OK, since the IP header has been validated, we don't want to tell
  1258. * the caller they have more packet than they really have. This can
  1259. * be caused by the Ethernet CRC trailer being counted, for example. */
  1260. if (*len > iplen)
  1261. *len = iplen;
  1262. hdr = ip->ip_p;
  1263. } else if (ip->ip_v == 6) {
  1264. const struct ip6_hdr *ip6 = (struct ip6_hdr *) ipc;
  1265. datalen = *len;
  1266. data = ipv6_get_data(ip6, &datalen, &hdr);
  1267. if (data == NULL) {
  1268. if (o.debugging >= 3)
  1269. error("Rejecting IP packet because of invalid length");
  1270. return false;
  1271. }
  1272. iplen = ntohs(ip6->ip6_plen);
  1273. if (datalen > iplen)
  1274. *len -= datalen - iplen;
  1275. } else {
  1276. if (o.debugging >= 3)
  1277. error("Rejecting IP packet because of invalid version number %u", ip->ip_v);
  1278. return false;
  1279. }
  1280. switch (hdr) {
  1281. case IPPROTO_TCP:
  1282. if (datalen < sizeof(struct tcp_hdr)) {
  1283. if (o.debugging >= 3)
  1284. error("Rejecting TCP packet because of incomplete header");
  1285. return false;
  1286. }
  1287. if (!validateTCPhdr((u8 *) data, datalen)) {
  1288. if (o.debugging >= 3)
  1289. error("Rejecting TCP packet because of bad TCP header");
  1290. return false;
  1291. }
  1292. break;
  1293. case IPPROTO_UDP:
  1294. if (datalen < sizeof(struct udp_hdr)) {
  1295. if (o.debugging >= 3)
  1296. error("Rejecting UDP packet because of incomplete header");
  1297. return false;
  1298. }
  1299. break;
  1300. default:
  1301. break;
  1302. }
  1303. return true;
  1304. }
  1305. /* Read an IP packet using libpcap . We return the packet and take
  1306. a pcap descriptor and a pointer to the packet length (which we set
  1307. in the function. If you want a maximum length returned, you
  1308. should specify that in pcap_open_live() */
  1309. /* to_usec is the timeout period in microseconds -- use 0 to skip the
  1310. test and -1 to block forever. Note that we don't interrupt pcap, so
  1311. low values (and 0) degenerate to the timeout specified
  1312. in pcap_open_live() */
  1313. /* If rcvdtime is non-null and a packet is returned, rcvd will be
  1314. filled with the time that packet was captured from the wire by
  1315. pcap. If linknfo is not NULL, linknfo->headerlen and
  1316. linknfo->header will be filled with the appropriate values. */
  1317. /* Specifying true for validate will enable validity checks against the
  1318. received IP packet. See validatepkt() for a list of checks. */
  1319. char *readipv4_pcap(pcap_t *pd, unsigned int *len, long to_usec,
  1320. struct timeval *rcvdtime, struct link_header *linknfo,
  1321. bool validate) {
  1322. char *buf;
  1323. buf = readip_pcap(pd, len, to_usec, rcvdtime, linknfo, validate);
  1324. if (buf != NULL) {
  1325. struct ip *ip;
  1326. ip = (struct ip *) buf;
  1327. if (*len < 1 || ip->ip_v != 4)
  1328. return NULL;
  1329. }
  1330. return buf;
  1331. }
  1332. char *readip_pcap(pcap_t *pd, unsigned int *len, long to_usec,
  1333. struct timeval *rcvdtime, struct link_header *linknfo, bool validate) {
  1334. unsigned int offset = 0;
  1335. struct pcap_pkthdr head;
  1336. char *p;
  1337. int datalink;
  1338. int timedout = 0;
  1339. struct timeval tv_start, tv_end;
  1340. static char *alignedbuf = NULL;
  1341. static unsigned int alignedbufsz = 0;
  1342. static int warning = 0;
  1343. if (linknfo) {
  1344. memset(linknfo, 0, sizeof(*linknfo));
  1345. }
  1346. if (!pd)
  1347. fatal("NULL packet device passed to %s", __func__);
  1348. if (to_usec < 0) {
  1349. if (!warning) {
  1350. warning = 1;
  1351. error("WARNING: Negative timeout value (%lu) passed to %s() -- using 0", to_usec, __func__);
  1352. }
  1353. to_usec = 0;
  1354. }
  1355. /* New packet capture device, need to recompute offset */
  1356. if ((datalink = pcap_datalink(pd)) < 0)
  1357. fatal("Cannot obtain datalink information: %s", pcap_geterr(pd));
  1358. /* NOTE: IF A NEW OFFSET EVER EXCEEDS THE CURRENT MAX (24), ADJUST
  1359. MAX_LINK_HEADERSZ in libnetutil/netutil.h */
  1360. switch (datalink) {
  1361. case DLT_EN10MB:
  1362. offset = 14;
  1363. break;
  1364. case DLT_IEEE802:
  1365. offset = 22;
  1366. break;
  1367. #ifdef __amigaos__
  1368. case DLT_MIAMI:
  1369. offset = 16;
  1370. break;
  1371. #endif
  1372. #ifdef DLT_LOOP
  1373. case DLT_LOOP:
  1374. #endif
  1375. case DLT_NULL:
  1376. offset = 4;
  1377. break;
  1378. case DLT_SLIP:
  1379. #ifdef DLT_SLIP_BSDOS
  1380. case DLT_SLIP_BSDOS:
  1381. #endif
  1382. #if (FREEBSD || OPENBSD || NETBSD || BSDI || MACOSX)
  1383. offset = 16;
  1384. #else
  1385. offset = 24; /* Anyone use this??? */
  1386. #endif
  1387. break;
  1388. case DLT_PPP:
  1389. #ifdef DLT_PPP_BSDOS
  1390. case DLT_PPP_BSDOS:
  1391. #endif
  1392. #ifdef DLT_PPP_SERIAL
  1393. case DLT_PPP_SERIAL:
  1394. #endif
  1395. #ifdef DLT_PPP_ETHER
  1396. case DLT_PPP_ETHER:
  1397. #endif
  1398. #if (FREEBSD || OPENBSD || NETBSD || BSDI || MACOSX)
  1399. offset = 4;
  1400. #else
  1401. #ifdef SOLARIS
  1402. offset = 8;
  1403. #else
  1404. offset = 24; /* Anyone use this? */
  1405. #endif /* ifdef solaris */
  1406. #endif /* if freebsd || openbsd || netbsd || bsdi */
  1407. break;
  1408. case DLT_RAW:
  1409. offset = 0;
  1410. break;
  1411. case DLT_FDDI:
  1412. offset = 21;
  1413. break;
  1414. #ifdef DLT_ENC
  1415. case DLT_ENC:
  1416. offset = 12;
  1417. break;
  1418. #endif /* DLT_ENC */
  1419. #ifdef DLT_LINUX_SLL
  1420. case DLT_LINUX_SLL:
  1421. offset = 16;
  1422. break;
  1423. #endif
  1424. #ifdef DLT_IPNET
  1425. case DLT_IPNET:
  1426. offset = 24;
  1427. break;
  1428. #endif
  1429. default:
  1430. p = (char *) pcap_next(pd, &head);
  1431. if (head.caplen == 0) {
  1432. /* Lets sleep a brief time and try again to increase the chance of seeing
  1433. a real packet ... */
  1434. usleep(500000);
  1435. p = (char *) pcap_next(pd, &head);
  1436. }
  1437. if (head.caplen > 100000) {
  1438. fatal("FATAL: %s: bogus caplen from libpcap (%d) on interface type %d", __func__, head.caplen, datalink);
  1439. }
  1440. error("FATAL: Unknown datalink type (%d). Caplen: %d; Packet:", datalink, head.caplen);
  1441. nmap_hexdump((unsigned char *) p, head.caplen);
  1442. exit(1);
  1443. }
  1444. if (to_usec > 0) {
  1445. gettimeofday(&tv_start, NULL);
  1446. }
  1447. do {
  1448. #ifdef WIN32
  1449. long to_left;
  1450. if (to_usec > 0) {
  1451. gettimeofday(&tv_end, NULL);
  1452. to_left = MAX(1, (to_usec - TIMEVAL_SUBTRACT(tv_end, tv_start)) / 1000);
  1453. } else {
  1454. to_left = 1;
  1455. }
  1456. // Set the timeout (BUGBUG: this is cheating)
  1457. PacketSetReadTimeout(pd->adapter, to_left);
  1458. #endif
  1459. p = NULL;
  1460. /* It may be that protecting this with !pcap_selectable_fd_one_to_one is not
  1461. necessary, that it is always safe to do a nonblocking read in this way on
  1462. all platforms. But I have only tested it on Solaris. */
  1463. if (!pcap_selectable_fd_one_to_one()) {
  1464. int rc, nonblock;
  1465. nonblock = pcap_getnonblock(pd, NULL);
  1466. assert(nonblock == 0);
  1467. rc = pcap_setnonblock(pd, 1, NULL);
  1468. assert(rc == 0);
  1469. p = (char *) pcap_next(pd, &head);
  1470. rc = pcap_setnonblock(pd, nonblock, NULL);
  1471. assert(rc == 0);
  1472. }
  1473. if (p == NULL) {
  1474. /* Nonblocking pcap_next didn't get anything. */
  1475. if (pcap_select(pd, to_usec) == 0)
  1476. timedout = 1;
  1477. else
  1478. p = (char *) pcap_next(pd, &head);
  1479. }
  1480. if (p) {
  1481. if (head.caplen <= offset) {
  1482. *len = 0;
  1483. return NULL;
  1484. }
  1485. if (offset && linknfo) {
  1486. linknfo->datalinktype = datalink;
  1487. linknfo->headerlen = offset;
  1488. assert(offset <= MAX_LINK_HEADERSZ);
  1489. memcpy(linknfo->header, p, MIN(sizeof(linknfo->header), offset));
  1490. }
  1491. p += offset;
  1492. }
  1493. if (!p) {
  1494. /* Should we timeout? */
  1495. if (to_usec == 0) {
  1496. timedout = 1;
  1497. } else if (to_usec > 0) {
  1498. gettimeofday(&tv_end, NULL);
  1499. if (TIMEVAL_SUBTRACT(tv_end, tv_start) >= to_usec) {
  1500. timedout = 1;
  1501. }
  1502. }
  1503. }
  1504. } while (!timedout && (!p));
  1505. if (timedout) {
  1506. *len = 0;
  1507. return NULL;
  1508. }
  1509. *len = head.caplen - offset;
  1510. if (*len > alignedbufsz) {
  1511. alignedbuf = (char *) safe_realloc(alignedbuf, *len);
  1512. alignedbufsz = *len;
  1513. }
  1514. memcpy(alignedbuf, p, *len);
  1515. if (validate) {
  1516. /* Let's see if this packet passes inspection.. */
  1517. if (!validatepkt((u8 *) alignedbuf, len)) {
  1518. *len = 0;
  1519. return NULL;
  1520. }
  1521. }
  1522. // printf("Just got a packet at %li,%li\n", head.ts.tv_sec, head.ts.tv_usec);
  1523. if (rcvdtime) {
  1524. // FIXME: I eventually need to figure out why Windows head.ts time is sometimes BEFORE the time I
  1525. // sent the packet (which is according to gettimeofday() in nbase). For now, I will sadly have to
  1526. // use gettimeofday() for Windows in this case
  1527. // Actually I now allow .05 discrepancy. So maybe this isn't needed. I'll comment out for now.
  1528. // Nope: it is still needed at least for Windows. Sometimes the time from he pcap header is a
  1529. // COUPLE SECONDS before the gettimeofday() results :(.
  1530. #if defined(WIN32) || defined(__amigaos__)
  1531. gettimeofday(&tv_end, NULL);
  1532. *rcvdtime = tv_end;
  1533. #else
  1534. rcvdtime->tv_sec = head.ts.tv_sec;
  1535. rcvdtime->tv_usec = head.ts.tv_usec;
  1536. assert(head.ts.tv_sec);
  1537. #endif
  1538. }
  1539. if (rcvdtime)
  1540. PacketTrace::trace(PacketTrace::RCVD, (u8 *) alignedbuf, *len,
  1541. rcvdtime);
  1542. else
  1543. PacketTrace::trace(PacketTrace::RCVD, (u8 *) alignedbuf, *len);
  1544. return alignedbuf;
  1545. }
  1546. /* Attempts to read one IPv6 Neighbor Solicitation reply packet from the pcap
  1547. descriptor pd. If it receives one, fills in sendermac (must pass
  1548. in 6 bytes), senderIP, and rcvdtime (can be NULL if you don't care)
  1549. and returns 1. If it times out and reads no Neighbor Advertisement, returns
  1550. 0. to_usec is the timeout period in microseconds. Use 0 to avoid
  1551. blocking to the extent possible. Returns -1 or exits if there is
  1552. an error. The last parameter is a pointer to a callback function
  1553. that can be used for packet tracing. This is intended to be used
  1554. by Nmap only. Any other calling this should pass NULL instead. */
  1555. int read_na_pcap(pcap_t *pd, u8 *sendermac, struct sockaddr_in6 *senderIP, long to_usec,
  1556. struct timeval *rcvdtime, bool *has_mac) {
  1557. struct ip *ip_tmp;
  1558. struct icmpv6_hdr *icmp6_header;
  1559. struct icmpv6_msg_nd *na;
  1560. struct timeval tv_start, tv_end;
  1561. const void *data = NULL;
  1562. unsigned int datalen;
  1563. static int warning = 0;
  1564. int timedout = 0;
  1565. struct abstract_ip_hdr hdr;
  1566. struct link_header linknfo;
  1567. if (to_usec < 0) {
  1568. if (!warning) {
  1569. warning = 1;
  1570. error("WARNING: Negative timeout value (%lu) passed to %s() -- using 0", to_usec, __func__);
  1571. }
  1572. to_usec = 0;
  1573. }
  1574. if (to_usec > 0) {
  1575. gettimeofday(&tv_start, NULL);
  1576. }
  1577. do {
  1578. ip_tmp = (struct ip *) readip_pcap(pd, &datalen, to_usec, rcvdtime, &linknfo, true);
  1579. if (ip_tmp) { //Check Neighbor Advertisement Packet.
  1580. /* OK, we got a packet. Most packet validity tests are taken care
  1581. * of in readip_pcap, so this is simple
  1582. */
  1583. data = ip_get_data(ip_tmp, &datalen, &hdr);
  1584. if (data == NULL)
  1585. continue;
  1586. if (hdr.proto == IPPROTO_ICMPV6) {
  1587. icmp6_header = (struct icmpv6_hdr *)data;
  1588. na = (struct icmpv6_msg_nd *) ((unsigned char*)data + ICMPV6_HDR_LEN);
  1589. if (icmp6_header->icmpv6_type == ICMPV6_NEIGHBOR_ADVERTISEMENT &&
  1590. icmp6_header->icmpv6_code == 0) {
  1591. //Set target IPv6 address
  1592. senderIP->sin6_family = AF_INET6;
  1593. memcpy(&senderIP->sin6_addr.s6_addr, &na->icmpv6_target, 16);
  1594. //Set MAC
  1595. if (datalen == ICMPV6_HDR_LEN + sizeof(struct icmpv6_msg_nd)) {
  1596. if (na->icmpv6_option_type == 2 && na->icmpv6_option_length == 1) {
  1597. *has_mac = true;
  1598. memcpy(sendermac, &na->icmpv6_mac, 6);
  1599. }
  1600. } else {
  1601. *has_mac = false;
  1602. }
  1603. }
  1604. }
  1605. } else {
  1606. /* Should we timeout? */
  1607. if (to_usec == 0) {
  1608. timedout = 1;
  1609. } else if (to_usec > 0) {
  1610. gettimeofday(&tv_end, NULL);
  1611. if (TIMEVAL_SUBTRACT(tv_end, tv_start) >= to_usec) {
  1612. timedout = 1;
  1613. }
  1614. }
  1615. }
  1616. } while (!timedout && !ip_tmp);
  1617. if (timedout)
  1618. return 0;
  1619. return 1;
  1620. }
  1621. // Returns whether the packet receive time value obtained from libpcap
  1622. // (and thus by readip_pcap()) should be considered valid. When
  1623. // invalid (Windows and Amiga), readip_pcap returns the time you called it.
  1624. bool pcap_recv_timeval_valid() {
  1625. #if defined(WIN32) || defined(__amigaos__)
  1626. return false;
  1627. #else
  1628. return true;
  1629. #endif
  1630. }
  1631. /* Prints stats from a pcap descriptor (number of received and dropped
  1632. packets). */
  1633. void pcap_print_stats(int logt, pcap_t *pd) {
  1634. struct pcap_stat stat;
  1635. assert(pd != NULL);
  1636. if (pcap_stats(pd, &stat) < 0) {
  1637. error("%s: %s", __func__, pcap_geterr(pd));
  1638. return;
  1639. }
  1640. log_write(logt, "pcap stats: %u packets received by filter, %u dropped by kernel.\n", stat.ps_recv, stat.ps_drop);
  1641. }
  1642. /* This function tries to determine the target's ethernet MAC address
  1643. from a received packet as follows:
  1644. 1) If linkhdr is an ethernet header, grab the src mac (otherwise give up)
  1645. 2) If overwrite is 0 and a MAC is already set for this target, give up.
  1646. 3) If the packet source address is not the target, give up.
  1647. 4) Use the routing table to try to determine rather target is
  1648. directly connected to the src host running Nmap. If it is, set the MAC.
  1649. This function returns 0 if it ends up setting the MAC, nonzero otherwise. */
  1650. int setTargetMACIfAvailable(Target *target, struct link_header *linkhdr,
  1651. const struct sockaddr_storage *src, int overwrite) {
  1652. struct sockaddr_storage addr;
  1653. size_t addr_len;
  1654. if (!linkhdr || !target || !src)
  1655. return 1;
  1656. if (linkhdr->datalinktype != DLT_EN10MB || linkhdr->headerlen != 14)
  1657. return 2;
  1658. if (!overwrite && target->MACAddress())
  1659. return 3;
  1660. addr_len = sizeof(addr);
  1661. target->TargetSockAddr(&addr, &addr_len);
  1662. if (sockaddr_storage_cmp(src, &addr) != 0)
  1663. return 4;
  1664. /* Sometimes bogus MAC address still gets through, like during some localhost scans */
  1665. if (memcmp(linkhdr->header + 6, "\0\0\0\0\0\0", 6) == 0)
  1666. return 5;
  1667. if (target->ifType() == devt_ethernet && target->directlyConnected()) {
  1668. /* Yay! This MAC address seems valid */
  1669. target->setMACAddress(linkhdr->header + 6);
  1670. return 0;
  1671. }
  1672. return 5;
  1673. }
  1674. /* This function ensures that the next hop MAC address for a target is
  1675. filled in. This address is the target's own MAC if it is directly
  1676. connected, and the next hop mac otherwise. Returns true if the
  1677. address is set when the function ends, false if not. This function
  1678. firt checks if it is already set, if not it tries the arp cache,
  1679. and if that fails it sends an ARP request itself. This should be
  1680. called after an ARP scan if many directly connected machines are
  1681. involved. setDirectlyConnected() (whether true or false) should
  1682. have already been called on target before this. The target device
  1683. and src mac address should also already be set. */
  1684. bool setTargetNextHopMAC(Target *target) {
  1685. struct sockaddr_storage targetss;
  1686. size_t sslen;
  1687. u8 mac[6];
  1688. if (target->ifType() != devt_ethernet)
  1689. return false; /* Duh. */
  1690. /* First check if we already have it, duh. */
  1691. if (target->NextHopMACAddress())
  1692. return true;
  1693. /* For connected machines, it is the same as the target addy */
  1694. if (target->directlyConnected() && target->MACAddress()) {
  1695. target->setNextHopMACAddress(target->MACAddress());
  1696. return true;
  1697. }
  1698. if (target->directlyConnected()) {
  1699. target->TargetSockAddr(&targetss, &sslen);
  1700. } else {
  1701. if (!target->nextHop(&targetss, &sslen))
  1702. fatal("%s: Failed to determine nextHop to target", __func__);
  1703. }
  1704. if (getNextHopMAC(target->deviceFullName(), target->SrcMACAddress(), target->SourceSockAddr(), &targetss, mac)) {
  1705. target->setNextHopMACAddress(mac);
  1706. return true;
  1707. }
  1708. /* I'm afraid that we couldn't find it! Maybe it doesn't exist? */
  1709. return false;
  1710. }
  1711. /* Like to getTargetNextHopMAC(), but for arbitrary hosts (not Targets) */
  1712. bool getNextHopMAC(const char *iface, const u8 *srcmac, const struct sockaddr_storage *srcss,
  1713. const struct sockaddr_storage *dstss, u8 *dstmac) {
  1714. arp_t *a;
  1715. struct arp_entry ae;
  1716. /* First, let us check the Nmap arp cache ... */
  1717. if (mac_cache_get(dstss, dstmac))
  1718. return true;
  1719. /* Maybe the system ARP cache will be more helpful */
  1720. a = arp_open();
  1721. addr_ston((sockaddr *) dstss, &ae.arp_pa);
  1722. if (arp_get(a, &ae) == 0) {
  1723. mac_cache_set(dstss, ae.arp_ha.addr_eth.data);
  1724. memcpy(dstmac, ae.arp_ha.addr_eth.data, 6);
  1725. arp_close(a);
  1726. return true;
  1727. }
  1728. arp_close(a);
  1729. /* OK, the last choice is to send our own damn ARP request (and
  1730. retransmissions if necessary) to determine the MAC */
  1731. if (dstss->ss_family == AF_INET) {
  1732. if (doArp(iface, srcmac, srcss, dstss, dstmac, PacketTrace::traceArp)) {
  1733. mac_cache_set(dstss, dstmac);
  1734. return true;
  1735. }
  1736. } else if (dstss->ss_family == AF_INET6) {
  1737. if (doND(iface, srcmac, srcss, dstss, dstmac, PacketTrace::traceND)) {
  1738. mac_cache_set(dstss, dstmac);
  1739. return true;
  1740. }
  1741. }
  1742. return false;
  1743. }
  1744. pcap_if_t *getpcapinterfaces() {
  1745. #ifndef WIN32
  1746. return NULL;
  1747. #endif
  1748. pcap_if_t *p_ifaces;
  1749. if ((pcap_findalldevs(&p_ifaces, NULL)) == -1) {
  1750. fatal("pcap_findalldevs() : Cannot retrieve pcap interfaces");
  1751. return NULL;
  1752. }
  1753. return p_ifaces;
  1754. }
  1755. int nmap_route_dst(const struct sockaddr_storage *dst, struct route_nfo *rnfo) {
  1756. struct sockaddr_storage spoofss;
  1757. size_t spoofsslen;
  1758. if (o.spoofsource) {
  1759. o.SourceSockAddr(&spoofss, &spoofsslen);
  1760. return route_dst(dst, rnfo, o.device, &spoofss);
  1761. } else {
  1762. return route_dst(dst, rnfo, o.device, NULL);
  1763. }
  1764. }
  1765. /* Maximize the receive buffer of a socket descriptor (up to 500K) */
  1766. void max_rcvbuf(int sd) {
  1767. int optval = 524288; /* 2^19 */
  1768. recvfrom6_t optlen = sizeof(int);
  1769. #ifndef WIN32
  1770. if (setsockopt (sd, SOL_SOCKET, SO_RCVBUF, (const char *) &optval, optlen))
  1771. if (o.debugging)
  1772. perror("Problem setting large socket receive buffer");
  1773. if (o.debugging) {
  1774. getsockopt(sd, SOL_SOCKET, SO_RCVBUF, (char *) &optval, &optlen);
  1775. log_write(LOG_STDOUT, "Our buffer size is now %d\n", optval);
  1776. }
  1777. #endif /* WIN32 */
  1778. }
  1779. /* Give broadcast permission to a socket */
  1780. void broadcast_socket(int sd) {
  1781. int one = 1;
  1782. #ifdef WIN32
  1783. if (sd == 501)
  1784. return;
  1785. #endif
  1786. if (setsockopt (sd, SOL_SOCKET, SO_BROADCAST, (const char *) &one, sizeof(int)) != 0) {
  1787. error("Failed to secure socket broadcasting permission");
  1788. perror("setsockopt");
  1789. }
  1790. }
  1791. /* Do a receive (recv()) on a socket and stick the results (up to
  1792. len) into buf . Give up after 'seconds'. Returns the number of
  1793. bytes read (or -1 in the case of an error. It only does one recv
  1794. (it will not keep going until len bytes are read). If timedout is
  1795. not NULL, it will be set to zero (no timeout occured) or 1 (it
  1796. did). */
  1797. int recvtime(int sd, char *buf, int len, int seconds, int *timedout) {
  1798. int res;
  1799. struct timeval timeout;
  1800. fd_set readfd;
  1801. timeout.tv_sec = seconds;
  1802. timeout.tv_usec = 0;
  1803. FD_ZERO(&readfd);
  1804. FD_SET(sd, &readfd);
  1805. if (timedout)
  1806. *timedout = 0;
  1807. res = select(sd + 1, &readfd, NULL, NULL, &timeout);
  1808. if (res > 0) {
  1809. res = recv(sd, buf, len, 0);
  1810. if (res >= 0)
  1811. return res;
  1812. gh_perror("recv in %s", __func__);
  1813. return 0;
  1814. } else if (!res) {
  1815. if (timedout)
  1816. *timedout = 1;
  1817. return 0;
  1818. }
  1819. gh_perror("select() in %s", __func__);
  1820. return -1;
  1821. }
  1822. /* Examines the given tcp packet and obtains the TCP timestamp option
  1823. information if available. Note that the CALLER must ensure that
  1824. "tcp" contains a valid header (in particular the th_off must be the
  1825. true packet length and tcp must contain it). If a valid timestamp
  1826. option is found in the header, nonzero is returned and the
  1827. 'timestamp' and 'echots' parameters are filled in with the
  1828. appropriate value (if non-null). Otherwise 0 is returned and the
  1829. parameters (if non-null) are filled with 0. Remember that the
  1830. correct way to check for errors is to look at the return value
  1831. since a zero ts or echots could possibly be valid. */
  1832. int gettcpopt_ts(struct tcp_hdr *tcp, u32 *timestamp, u32 *echots) {
  1833. unsigned char *p;
  1834. int len = 0;
  1835. int op;
  1836. int oplen;
  1837. /* first we find where the tcp options start ... */
  1838. p = ((unsigned char *) tcp) + 20;
  1839. len = 4 * tcp->th_off - 20;
  1840. while (len > 0 && *p != 0 /* TCPOPT_EOL */ ) {
  1841. op = *p++;
  1842. if (op == 0 /* TCPOPT_EOL */ )
  1843. break;
  1844. if (op == 1 /* TCPOPT_NOP */ ) {
  1845. len--;
  1846. continue;
  1847. }
  1848. oplen = *p++;
  1849. if (oplen < 2)
  1850. break; /* No infinite loops, please */
  1851. if (oplen > len)
  1852. break; /* Not enough space */
  1853. if (op == 8 /* TCPOPT_TIMESTAMP */ && oplen == 10) {
  1854. /* Legitimate ts option */
  1855. if (timestamp) {
  1856. memcpy((char *) timestamp, p, 4);
  1857. *timestamp = ntohl(*timestamp);
  1858. }
  1859. p += 4;
  1860. if (echots) {
  1861. memcpy((char *) echots, p, 4);
  1862. *echots = ntohl(*echots);
  1863. }
  1864. return 1;
  1865. }
  1866. len -= oplen;
  1867. p += oplen - 2;
  1868. }
  1869. /* Didn't find anything */
  1870. if (timestamp)
  1871. *timestamp = 0;
  1872. if (echots)
  1873. *echots = 0;
  1874. return 0;
  1875. }