PageRenderTime 72ms CodeModel.GetById 25ms 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

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

  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.…

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