PageRenderTime 53ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 1ms

/tcpip.cc

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