PageRenderTime 52ms CodeModel.GetById 18ms RepoModel.GetById 1ms app.codeStats 0ms

/tcpip.cc

https://github.com/prakashgamit/nmap
C++ | 2172 lines | 1487 code | 296 blank | 389 comment | 391 complexity | c90b570ec8d1730377e5b53482654b22 MD5 | raw file
Possible License(s): BSD-3-Clause, GPL-2.0, LGPL-2.0, LGPL-2.1

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-2013 Insecure.Com LLC. Nmap is *
  9. * also a registered trademark of Insecure.Com LLC. This program is free *
  10. * software; you may redistribute and/or modify it under the terms of the *
  11. * GNU General Public License as published by the Free Software *
  12. * Foundation; Version 2 ("GPL"), BUT ONLY WITH ALL OF THE CLARIFICATIONS *
  13. * AND EXCEPTIONS DESCRIBED HEREIN. This guarantees your right to use, *
  14. * modify, and redistribute this software under certain conditions. If *
  15. * you wish to embed Nmap technology into proprietary software, we sell *
  16. * alternative licenses (contact sales@nmap.com). Dozens of software *
  17. * vendors already license Nmap technology such as host discovery, port *
  18. * scanning, OS detection, version detection, and the Nmap Scripting *
  19. * Engine. *
  20. * *
  21. * Note that the GPL places important restrictions on "derivative works", *
  22. * yet it does not provide a detailed definition of that term. To avoid *
  23. * misunderstandings, we interpret that term as broadly as copyright law *
  24. * allows. For example, we consider an application to constitute a *
  25. * derivative work for the purpose of this license if it does any of the *
  26. * following with any software or content covered by this license *
  27. * ("Covered Software"): *
  28. * *
  29. * o Integrates source code from Covered Software. *
  30. * *
  31. * o Reads or includes copyrighted data files, such as Nmap's nmap-os-db *
  32. * or nmap-service-probes. *
  33. * *
  34. * o Is designed specifically to execute Covered Software and parse the *
  35. * results (as opposed to typical shell or execution-menu apps, which will *
  36. * execute anything you tell them to). *
  37. * *
  38. * o Includes Covered Software in a proprietary executable installer. The *
  39. * installers produced by InstallShield are an example of this. Including *
  40. * Nmap with other software in compressed or archival form does not *
  41. * trigger this provision, provided appropriate open source decompression *
  42. * or de-archiving software is widely available for no charge. For the *
  43. * purposes of this license, an installer is considered to include Covered *
  44. * Software even if it actually retrieves a copy of Covered Software from *
  45. * another source during runtime (such as by downloading it from the *
  46. * Internet). *
  47. * *
  48. * o Links (statically or dynamically) to a library which does any of the *
  49. * above. *
  50. * *
  51. * o Executes a helper program, module, or script to do any of the above. *
  52. * *
  53. * This list is not exclusive, but is meant to clarify our interpretation *
  54. * of derived works with some common examples. Other people may interpret *
  55. * the plain GPL differently, so we consider this a special exception to *
  56. * the GPL that we apply to Covered Software. Works which meet any of *
  57. * these conditions must conform to all of the terms of this license, *
  58. * particularly including the GPL Section 3 requirements of providing *
  59. * source code and allowing free redistribution of the work as a whole. *
  60. * *
  61. * As another special exception to the GPL terms, Insecure.Com LLC grants *
  62. * permission to link the code of this program with any version of the *
  63. * OpenSSL library which is distributed under a license identical to that *
  64. * listed in the included docs/licenses/OpenSSL.txt file, and distribute *
  65. * linked combinations including the two. *
  66. * *
  67. * Any redistribution of Covered Software, including any derived works, *
  68. * must obey and carry forward all of the terms of this license, including *
  69. * obeying all GPL rules and restrictions. For example, source code of *
  70. * the whole work must be provided and free redistribution must be *
  71. * allowed. All GPL references to "this License", are to be treated as *
  72. * including the terms and conditions of this license text as well. *
  73. * *
  74. * Because this license imposes special exceptions to the GPL, Covered *
  75. * Work may not be combined (even as part of a larger work) with plain GPL *
  76. * software. The terms, conditions, and exceptions of this license must *
  77. * be included as well. This license is incompatible with some other open *
  78. * source licenses as well. In some cases we can relicense portions of *
  79. * Nmap or grant special permissions to use it in other open source *
  80. * software. Please contact fyodor@nmap.org with any such requests. *
  81. * Similarly, we don't incorporate incompatible open source software into *
  82. * Covered Software without special permission from the copyright holders. *
  83. * *
  84. * If you have any questions about the licensing restrictions on using *
  85. * Nmap in other works, are happy to help. As mentioned above, we also *
  86. * offer alternative license to integrate Nmap into proprietary *
  87. * applications and appliances. These contracts have been sold to dozens *
  88. * of software vendors, and generally include a perpetual license as well *
  89. * as providing for priority support and updates. They also fund the *
  90. * continued development of Nmap. Please email sales@nmap.com for further *
  91. * information. *
  92. * *
  93. * If you have received a written license agreement or contract for *
  94. * Covered Software stating terms other than these, you may choose to use *
  95. * and redistribute Covered Software under those terms instead of these. *
  96. * *
  97. * Source is provided to this software because we believe users have a *
  98. * right to know exactly what a program is going to do before they run it. *
  99. * This also allows you to audit the software for security holes (none *
  100. * have been found so far). *
  101. * *
  102. * Source code also allows you to port Nmap to new platforms, fix bugs, *
  103. * and add new features. You are highly encouraged to send your changes *
  104. * to the dev@nmap.org mailing list for possible incorporation into the *
  105. * main distribution. By sending these changes to Fyodor or one of the *
  106. * Insecure.Org development mailing lists, or checking them into the Nmap *
  107. * source code repository, it is understood (unless you specify otherwise) *
  108. * that you are offering the Nmap Project (Insecure.Com LLC) the *
  109. * unlimited, non-exclusive right to reuse, modify, and relicense the *
  110. * code. Nmap will always be available Open Source, but this is important *
  111. * because the inability to relicense code has caused devastating problems *
  112. * for other Free Software projects (such as KDE and NASM). We also *
  113. * occasionally relicense the code to third parties as discussed above. *
  114. * If you wish to specify special license conditions of your *
  115. * contributions, just say so when you send them. *
  116. * *
  117. * This program is distributed in the hope that it will be useful, but *
  118. * WITHOUT ANY WARRANTY; without even the implied warranty of *
  119. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the Nmap *
  120. * license file for more details (it's in a COPYING file included with *
  121. * Nmap, and also available from https://svn.nmap.org/nmap/COPYING *
  122. * *
  123. ***************************************************************************/
  124. /* $Id$ */
  125. #ifdef WIN32
  126. #include "nmap_winconfig.h"
  127. #endif
  128. #include "nbase.h"
  129. #include "portreasons.h"
  130. #include <dnet.h>
  131. #include "tcpip.h"
  132. #include "NmapOps.h"
  133. #include "Target.h"
  134. #include "utils.h"
  135. #include "libnetutil/netutil.h"
  136. #include "struct_ip.h"
  137. #if HAVE_SYS_TIME_H
  138. #include <sys/time.h>
  139. #endif
  140. #if HAVE_UNISTD_H
  141. /* #include <sys/unistd.h> */
  142. #include <unistd.h>
  143. #endif
  144. #if HAVE_NETINET_IF_ETHER_H
  145. #ifndef NETINET_IF_ETHER_H
  146. #include <netinet/if_ether.h>
  147. #define NETINET_IF_ETHER_H
  148. #endif /* NETINET_IF_ETHER_H */
  149. #endif /* HAVE_NETINET_IF_ETHER_H */
  150. extern NmapOps o;
  151. #ifdef WIN32
  152. #include "pcap-int.h"
  153. #endif
  154. static PacketCounter PktCt;
  155. /* Create a raw socket and do things that always apply to raw sockets:
  156. * Set SO_BROADCAST.
  157. * Set IP_HDRINCL.
  158. * Bind to an interface with SO_BINDTODEVICE (if o.device is set).
  159. The socket is created with address family AF_INET, but may be usable for
  160. AF_INET6, depending on the operating system. */
  161. int nmap_raw_socket() {
  162. int rawsd;
  163. rawsd = socket(AF_INET, SOCK_RAW, IPPROTO_RAW);
  164. if (rawsd < 0)
  165. return rawsd;
  166. broadcast_socket(rawsd);
  167. #ifndef WIN32
  168. sethdrinclude(rawsd);
  169. #endif
  170. socket_bindtodevice(rawsd, o.device);
  171. return rawsd;
  172. }
  173. /* Fill buf (up to buflen -- truncate if necessary but always
  174. terminate) with a short representation of the packet stats.
  175. Returns buf. Aborts if there is a problem. */
  176. char *getFinalPacketStats(char *buf, int buflen) {
  177. char sendbytesasc[16], recvbytesasc[16];
  178. if (buflen <= 10 || !buf)
  179. fatal("%s called with woefully inadequate parameters", __func__);
  180. Snprintf(buf, buflen,
  181. #if WIN32
  182. "Raw packets sent: %I64u (%s) | Rcvd: %I64u (%s)",
  183. #else
  184. "Raw packets sent: %llu (%s) | Rcvd: %llu (%s)",
  185. #endif
  186. PktCt.sendPackets,
  187. format_bytecount(PktCt.sendBytes, sendbytesasc,
  188. sizeof(sendbytesasc)), PktCt.recvPackets,
  189. format_bytecount(PktCt.recvBytes, recvbytesasc,
  190. sizeof(recvbytesasc)));
  191. return buf;
  192. }
  193. /* Takes an ARP PACKET (not including ethernet header) and
  194. prints it if packet tracing is enabled. The
  195. direction must be PacketTrace::SENT or PacketTrace::RCVD .
  196. Optional 'now' argument makes this function slightly more
  197. efficient by avoiding a gettimeofday() call. */
  198. void PacketTrace::traceArp(pdirection pdir, const u8 *frame, u32 len,
  199. struct timeval *now) {
  200. struct timeval tv;
  201. char arpdesc[128];
  202. char who_has[INET_ADDRSTRLEN], tell[INET_ADDRSTRLEN];
  203. if (pdir == SENT) {
  204. PktCt.sendPackets++;
  205. PktCt.sendBytes += len;
  206. } else {
  207. PktCt.recvPackets++;
  208. PktCt.recvBytes += len;
  209. }
  210. if (!o.packetTrace())
  211. return;
  212. if (now)
  213. tv = *now;
  214. else
  215. gettimeofday(&tv, NULL);
  216. if (len < 28) {
  217. error("Packet tracer: Arp packets must be at least 28 bytes long. Should be exactly that length excl. ethernet padding.");
  218. return;
  219. }
  220. if (frame[7] == 1) { /* arp REQUEST */
  221. inet_ntop(AF_INET, frame + 24, who_has, sizeof(who_has));
  222. inet_ntop(AF_INET, frame + 14, tell, sizeof(tell));
  223. Snprintf(arpdesc, sizeof(arpdesc), "who-has %s tell %s", who_has, tell);
  224. } else { /* ARP REPLY */
  225. inet_ntop(AF_INET, frame + 14, who_has, sizeof(who_has));
  226. Snprintf(arpdesc, sizeof(arpdesc),
  227. "reply %s is-at %02X:%02X:%02X:%02X:%02X:%02X", who_has,
  228. frame[8], frame[9], frame[10], frame[11], frame[12],
  229. frame[13]);
  230. }
  231. log_write(LOG_STDOUT | LOG_NORMAL, "%s (%.4fs) ARP %s\n",
  232. (pdir == SENT) ? "SENT" : "RCVD",
  233. o.TimeSinceStart(&tv), arpdesc);
  234. return;
  235. }
  236. /* Takes a Neighbor Discovery packet and prints it if packet tracing is
  237. enabled. frame must point to the IPv6 header. */
  238. void PacketTrace::traceND(pdirection pdir, const u8 *frame, u32 len,
  239. struct timeval *now) {
  240. struct timeval tv;
  241. struct ip6_hdr *ip6;
  242. struct icmpv6_hdr *icmpv6;
  243. union icmpv6_msg *msg;
  244. size_t msg_len;
  245. const char *label;
  246. char src[INET6_ADDRSTRLEN], dst[INET6_ADDRSTRLEN];
  247. char who_has[INET6_ADDRSTRLEN], tgt_is[INET6_ADDRSTRLEN];
  248. char desc[128];
  249. if (pdir == SENT) {
  250. PktCt.sendPackets++;
  251. PktCt.sendBytes += len;
  252. } else {
  253. PktCt.recvPackets++;
  254. PktCt.recvBytes += len;
  255. }
  256. if (!o.packetTrace())
  257. return;
  258. if (now)
  259. tv = *now;
  260. else
  261. gettimeofday(&tv, NULL);
  262. if (len < sizeof(*ip6) + sizeof(*icmpv6)) {
  263. error("Packet tracer: ND packets must be at least %lu bytes long (is %lu).",
  264. (unsigned long) (sizeof(*ip6) + sizeof(*icmpv6)),
  265. (unsigned long) len);
  266. return;
  267. }
  268. ip6 = (struct ip6_hdr *) frame;
  269. icmpv6 = (struct icmpv6_hdr *) (frame + sizeof(*ip6));
  270. msg = (union icmpv6_msg *) (frame + sizeof(*ip6) + sizeof(*icmpv6));
  271. msg_len = frame + len - (u8 *) msg;
  272. if (icmpv6->icmpv6_type == ICMPV6_NEIGHBOR_SOLICITATION) {
  273. label = "neighbor solicitation";
  274. if (msg_len < 20) {
  275. Snprintf(desc, sizeof(desc), "packet too short");
  276. } else {
  277. inet_ntop(AF_INET6, &msg->nd.icmpv6_target, who_has, sizeof(who_has));
  278. Snprintf(desc, sizeof(desc), "who has %s", who_has);
  279. }
  280. } else if (icmpv6->icmpv6_type == ICMPV6_NEIGHBOR_ADVERTISEMENT) {
  281. label = "neighbor advertisement";
  282. if (msg_len < 28) {
  283. Snprintf(desc, sizeof(desc), "packet too short");
  284. } else if (msg->nd.icmpv6_option_length == 0 || msg->nd.icmpv6_option_type != 2) {
  285. /* We only handle target link-layer address in the first option. */
  286. Snprintf(desc, sizeof(desc), "no link-layer address");
  287. } else {
  288. inet_ntop(AF_INET6, &msg->nd.icmpv6_target, tgt_is, sizeof(tgt_is));
  289. Snprintf(desc, sizeof(desc), "%s is at %s",
  290. tgt_is, eth_ntoa(&msg->nd.icmpv6_mac));
  291. }
  292. } else {
  293. error("Unknown ICMPV6 type in %s.", __func__);
  294. return;
  295. }
  296. inet_ntop(AF_INET6, &ip6->ip6_src, src, sizeof(src));
  297. inet_ntop(AF_INET6, &ip6->ip6_dst, dst, sizeof(dst));
  298. log_write(LOG_STDOUT | LOG_NORMAL, "%s (%.4fs) %s %s > %s %s\n",
  299. (pdir == SENT) ? "SENT" : "RCVD",
  300. o.TimeSinceStart(&tv), label, src, dst, desc);
  301. return;
  302. }
  303. /* Returns a buffer of ASCII information about a packet that may look
  304. like "TCP 127.0.0.1:50923 > 127.0.0.1:3 S ttl=61 id=39516 iplen=40
  305. seq=625950769" or "ICMP PING (0/1) ttl=61 id=39516 iplen=40".
  306. IMPORTANT: This is a wrapper for function ippackethdrinfo(). Check
  307. nbase/nbase_net.c for details on the returned buffer. */
  308. static const char *nmap_format_ippacket(const u8 *packet, u32 len) {
  309. int detail = LOW_DETAIL;
  310. if (o.debugging == 2) {
  311. detail = MEDIUM_DETAIL;
  312. } else if (o.debugging >= 3) {
  313. detail = HIGH_DETAIL;
  314. }
  315. return ippackethdrinfo(packet, len, detail);
  316. }
  317. /* Takes an IP PACKET and prints it if packet tracing is enabled.
  318. 'packet' must point to the IPv4 header. The direction must be
  319. PacketTrace::SENT or PacketTrace::RCVD . Optional 'now' argument
  320. makes this function slightly more efficient by avoiding a gettimeofday()
  321. call. */
  322. void PacketTrace::trace(pdirection pdir, const u8 *packet, u32 len,
  323. struct timeval *now) {
  324. struct timeval tv;
  325. if (pdir == SENT) {
  326. PktCt.sendPackets++;
  327. PktCt.sendBytes += len;
  328. } else {
  329. PktCt.recvPackets++;
  330. PktCt.recvBytes += len;
  331. }
  332. if (!o.packetTrace())
  333. return;
  334. if (now)
  335. tv = *now;
  336. else
  337. gettimeofday(&tv, NULL);
  338. if (len < 20) {
  339. error("Packet tracer: tiny packet encountered");
  340. return;
  341. }
  342. log_write(LOG_STDOUT | LOG_NORMAL, "%s (%.4fs) %s\n",
  343. (pdir == SENT) ? "SENT" : "RCVD",
  344. o.TimeSinceStart(&tv), nmap_format_ippacket(packet, len));
  345. return;
  346. }
  347. /* Adds a trace entry when a connect() is attempted if packet tracing
  348. is enabled. Pass IPPROTO_TCP or IPPROTO_UDP as the protocol. The
  349. sock may be a sockaddr_in or sockaddr_in6. The return code of
  350. connect is passed in connectrc. If the return code is -1, get the
  351. errno and pass that as connect_errno. */
  352. void PacketTrace::traceConnect(u8 proto, const struct sockaddr *sock,
  353. int socklen, int connectrc,
  354. int connect_errno,
  355. const struct timeval *now) {
  356. struct sockaddr_in *sin = (struct sockaddr_in *) sock;
  357. #if HAVE_IPV6
  358. struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *) sock;
  359. #endif
  360. struct timeval tv;
  361. char errbuf[64] = "";
  362. char targetipstr[INET6_ADDRSTRLEN] = "";
  363. u16 targetport = 0;
  364. if (!o.packetTrace())
  365. return;
  366. if (now)
  367. tv = *now;
  368. else
  369. gettimeofday(&tv, NULL);
  370. assert(proto == IPPROTO_TCP || proto == IPPROTO_UDP);
  371. if (connectrc == 0) {
  372. Strncpy(errbuf, "Connected", sizeof(errbuf));
  373. }
  374. #if WIN32
  375. else if (connect_errno == WSAEWOULDBLOCK) {
  376. /* Special case for WSAEWOULDBLOCK. socket_strerror returns the unwieldy
  377. "A non-blocking socket operation could not be completed immediately." */
  378. Strncpy(errbuf, "Operation now in progress", sizeof(errbuf));
  379. }
  380. #endif
  381. else {
  382. Snprintf(errbuf, sizeof(errbuf), "%s", socket_strerror(connect_errno));
  383. }
  384. if (sin->sin_family == AF_INET) {
  385. if (inet_ntop(sin->sin_family, (char *) &sin->sin_addr, targetipstr,
  386. sizeof(targetipstr)) == NULL)
  387. fatal("Failed to convert target IPv4 address to presentation format!?!");
  388. targetport = ntohs(sin->sin_port);
  389. } else {
  390. #if HAVE_IPV6
  391. assert(sin->sin_family == AF_INET6);
  392. if (inet_ntop(sin->sin_family, (char *) &sin6->sin6_addr, targetipstr,
  393. sizeof(targetipstr)) == NULL)
  394. fatal("Failed to convert target IPv6 address to presentation format!?!");
  395. targetport = ntohs(sin6->sin6_port);
  396. #else
  397. assert(0);
  398. #endif
  399. }
  400. log_write(LOG_STDOUT | LOG_NORMAL,
  401. "CONN (%.4fs) %s localhost > %s:%d => %s\n",
  402. o.TimeSinceStart(&tv),
  403. (proto == IPPROTO_TCP) ? "TCP" : "UDP", targetipstr,
  404. targetport, errbuf);
  405. }
  406. /* Converts an IP address given in a sockaddr_storage to an IPv4 or
  407. IPv6 IP address string. Since a static buffer is returned, this is
  408. not thread-safe and can only be used once in calls like printf() */
  409. const char *inet_socktop(struct sockaddr_storage *ss) {
  410. static char buf[INET6_ADDRSTRLEN];
  411. struct sockaddr_in *sin = (struct sockaddr_in *) ss;
  412. #if HAVE_IPV6
  413. struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *) ss;
  414. #endif
  415. if (inet_ntop(sin->sin_family, (sin->sin_family == AF_INET) ?
  416. (char *) &sin->sin_addr :
  417. #if HAVE_IPV6
  418. (char *) &sin6->sin6_addr,
  419. #else
  420. (char *) NULL,
  421. #endif /* HAVE_IPV6 */
  422. buf, sizeof(buf)) == NULL) {
  423. fatal("Failed to convert target address to presentation format in %s!?! Error: %s", __func__, strerror(socket_errno()));
  424. }
  425. return buf;
  426. }
  427. /* Tries to resolve the given name (or literal IP) into a sockaddr structure.
  428. This function calls getaddrinfo and returns the same addrinfo linked list
  429. that getaddrinfo produces. Returns NULL for any error or failure to resolve.
  430. You need to call freeaddrinfo on the result if non-NULL. */
  431. struct addrinfo *resolve_all(const char *hostname, int pf) {
  432. struct addrinfo hints;
  433. struct addrinfo *result;
  434. int rc;
  435. memset(&hints, 0, sizeof(hints));
  436. hints.ai_family = pf;
  437. /* Otherwise we get multiple identical addresses with different socktypes. */
  438. hints.ai_socktype = SOCK_DGRAM;
  439. rc = getaddrinfo(hostname, NULL, &hints, &result);
  440. if (rc != 0)
  441. return NULL;
  442. return result;
  443. }
  444. /* Send a pre-built IPv4 packet. Handles fragmentation and whether to send with
  445. an ethernet handle or a socket. */
  446. static int send_ipv4_packet(int sd, const struct eth_nfo *eth,
  447. const struct sockaddr_in *dst,
  448. const u8 *packet, unsigned int packetlen) {
  449. struct ip *ip = (struct ip *) packet;
  450. int res;
  451. assert(packet);
  452. assert((int) packetlen > 0);
  453. /* Fragmentation requested && packet is bigger than MTU */
  454. if (o.fragscan && !(ntohs(ip->ip_off) & IP_DF) &&
  455. (packetlen - ip->ip_hl * 4 > (unsigned int) o.fragscan)) {
  456. res = send_frag_ip_packet(sd, eth, dst, packet, packetlen, o.fragscan);
  457. } else {
  458. res = send_ip_packet_eth_or_sd(sd, eth, dst, packet, packetlen);
  459. }
  460. if (res != -1)
  461. PacketTrace::trace(PacketTrace::SENT, packet, packetlen);
  462. return res;
  463. }
  464. static int send_ipv6_packet(int sd, const struct eth_nfo *eth,
  465. const struct sockaddr_in6 *dst,
  466. const u8 *packet, unsigned int packetlen) {
  467. int res;
  468. res = send_ipv6_packet_eth_or_sd(sd, eth, dst, packet, packetlen);
  469. if (res != -1)
  470. PacketTrace::trace(PacketTrace::SENT, packet, packetlen);
  471. return res;
  472. }
  473. int send_ip_packet(int sd, const struct eth_nfo *eth,
  474. const struct sockaddr_storage *dst,
  475. const u8 *packet, unsigned int packetlen) {
  476. struct ip *ip = (struct ip *) packet;
  477. /* Ensure there's enough to read ip->ip_v at least. */
  478. if (packetlen < 1)
  479. return -1;
  480. if (ip->ip_v == 4) {
  481. assert(dst->ss_family == AF_INET);
  482. return send_ipv4_packet(sd, eth, (struct sockaddr_in *) dst, packet, packetlen);
  483. } else if (ip->ip_v == 6) {
  484. assert(dst->ss_family == AF_INET6);
  485. return send_ipv6_packet(sd, eth, (struct sockaddr_in6 *) dst, packet, packetlen);
  486. }
  487. fatal("%s only understands IP versions 4 and 6 (got %u)", __func__, ip->ip_v);
  488. }
  489. /* Return an IPv4 pseudoheader checksum for the given protocol and data. Unlike
  490. ipv4_pseudoheader_cksum, this knows about STUPID_SOLARIS_CHECKSUM_BUG and
  491. takes care of o.badsum. */
  492. static u16 ipv4_cksum(const struct in_addr *src, const struct in_addr *dst,
  493. u8 proto, const void *data, u16 len) {
  494. u16 sum;
  495. #if STUPID_SOLARIS_CHECKSUM_BUG
  496. sum = len;
  497. #else
  498. sum = ipv4_pseudoheader_cksum(src, dst, proto, len, data);
  499. #endif
  500. if (o.badsum) {
  501. --sum;
  502. if (proto == IPPROTO_UDP && sum == 0)
  503. sum = 0xffff; // UDP checksum=0 means no checksum
  504. }
  505. return sum;
  506. }
  507. /* Return an IPv6 pseudoheader checksum for the given protocol and data. Unlike
  508. ipv6_pseudoheader_cksum, this takes care of o.badsum. */
  509. static u16 ipv6_cksum(const struct in6_addr *src, const struct in6_addr *dst,
  510. u8 nxt, const void *data, u16 len) {
  511. u16 sum;
  512. sum = ipv6_pseudoheader_cksum(src, dst, nxt, len, data);
  513. if (o.badsum) {
  514. --sum;
  515. if (nxt == IPPROTO_UDP && sum == 0)
  516. sum = 0xffff; // UDP checksum=0 means no checksum
  517. }
  518. return sum;
  519. }
  520. // fill ip header. no error check.
  521. // This function is also changing what's needed from host to network order.
  522. static inline int fill_ip_raw(struct ip *ip, int packetlen, const u8 *ipopt,
  523. int ipoptlen, int tos, int id,
  524. int off, int ttl, int p,
  525. const struct in_addr *ip_src,
  526. const struct in_addr *ip_dst) {
  527. ip->ip_v = 4;
  528. ip->ip_hl = 5 + (ipoptlen / 4);
  529. ip->ip_tos = tos;
  530. ip->ip_len = htons(packetlen);
  531. ip->ip_id = htons(id);
  532. ip->ip_off = htons(off);
  533. ip->ip_ttl = ttl;
  534. ip->ip_p = p;
  535. ip->ip_src.s_addr = ip_src->s_addr;
  536. ip->ip_dst.s_addr = ip_dst->s_addr;
  537. if (ipoptlen)
  538. memcpy((u8 *) ip + sizeof(struct ip), ipopt, ipoptlen);
  539. // ip options source routing hack:
  540. if (ipoptlen && o.ipopt_firsthop && o.ipopt_lasthop) {
  541. u8 *ipo = (u8 *) ip + sizeof(struct ip);
  542. struct in_addr *newdst = (struct in_addr *) &ipo[o.ipopt_firsthop];
  543. struct in_addr *olddst = (struct in_addr *) &ipo[o.ipopt_lasthop];
  544. // our destination is somewhere else :)
  545. ip->ip_dst.s_addr = newdst->s_addr;
  546. // and last hop should be destination
  547. olddst->s_addr = ip_dst->s_addr;
  548. }
  549. #if HAVE_IP_IP_SUM
  550. ip->ip_sum = 0;
  551. ip->ip_sum = in_cksum((unsigned short *) ip, sizeof(struct ip) + ipoptlen);
  552. #endif
  553. return (sizeof(struct ip) + ipoptlen);
  554. }
  555. /* Builds an IP packet (including an IP header) by packing the fields
  556. with the given information. It allocates a new buffer to store the
  557. packet contents, and then returns that buffer. The packet is not
  558. actually sent by this function. Caller must delete the buffer when
  559. finished with the packet. The packet length is returned in
  560. packetlen, which must be a valid int pointer. */
  561. u8 *build_ip_raw(const struct in_addr *source,
  562. const struct in_addr *victim, u8 proto, int ttl,
  563. u16 ipid, u8 tos, bool df, const u8 *ipopt, int ipoptlen,
  564. const char *data, u16 datalen, u32 *outpacketlen) {
  565. int packetlen = sizeof(struct ip) + ipoptlen + datalen;
  566. u8 *packet = (u8 *) safe_malloc(packetlen);
  567. struct ip *ip = (struct ip *) packet;
  568. static int myttl = 0;
  569. /* check that required fields are there and not too silly */
  570. assert(source);
  571. assert(victim);
  572. assert(ipoptlen % 4 == 0);
  573. /* Time to live */
  574. if (ttl == -1) {
  575. myttl = (get_random_uint() % 23) + 37;
  576. } else {
  577. myttl = ttl;
  578. }
  579. fill_ip_raw(ip, packetlen, ipopt, ipoptlen,
  580. tos, ipid, df ? IP_DF : 0, myttl, proto, source, victim);
  581. /* We should probably copy the data over too */
  582. if (data && datalen)
  583. memcpy((u8 *) ip + sizeof(struct ip) + ipoptlen, data, datalen);
  584. *outpacketlen = packetlen;
  585. return packet;
  586. }
  587. u8 *build_ipv6_raw(const struct in6_addr *source,
  588. const struct in6_addr *victim, u8 tc, u32 flowlabel,
  589. u8 nextheader, int hoplimit,
  590. const char *data, u16 datalen, u32 *outpacketlen) {
  591. u8 *packet;
  592. assert(source != NULL);
  593. assert(victim != NULL);
  594. if (hoplimit == -1)
  595. hoplimit = (get_random_uint() % 23) + 37;
  596. *outpacketlen = sizeof(struct ip6_hdr) + datalen;
  597. packet = (u8 *) safe_malloc(*outpacketlen);
  598. ip6_pack_hdr(packet, tc, flowlabel, datalen, nextheader, hoplimit, *source, *victim);
  599. memcpy(packet + sizeof(struct ip6_hdr), data, datalen);
  600. return packet;
  601. }
  602. /* Build a TCP packet (no IP header). Sets tcp->th_sum to 0 so it can be filled
  603. in by a function with knowledge of the higher-level pseudoheader. */
  604. static u8 *build_tcp(u16 sport, u16 dport, u32 seq, u32 ack, u8 reserved,
  605. u8 flags, u16 window, u16 urp,
  606. const u8 *tcpopt, int tcpoptlen,
  607. const char *data, u16 datalen, u32 *packetlen) {
  608. struct tcp_hdr *tcp;
  609. u8 *packet;
  610. if (tcpoptlen % 4 != 0)
  611. fatal("%s called with an option length argument of %d which is illegal because it is not divisible by 4. Just add \\0 padding to the end.", __func__, tcpoptlen);
  612. *packetlen = sizeof(*tcp) + tcpoptlen + datalen;
  613. packet = (u8 *) safe_malloc(*packetlen);
  614. tcp = (struct tcp_hdr *) packet;
  615. memset(tcp, 0, sizeof(*tcp));
  616. tcp->th_sport = htons(sport);
  617. tcp->th_dport = htons(dport);
  618. if (seq)
  619. tcp->th_seq = htonl(seq);
  620. else if (flags & TH_SYN)
  621. get_random_bytes(&(tcp->th_seq), 4);
  622. if (ack)
  623. tcp->th_ack = htonl(ack);
  624. if (reserved)
  625. tcp->th_x2 = reserved & 0x0F;
  626. tcp->th_off = 5 + (tcpoptlen / 4); /* words */
  627. tcp->th_flags = flags;
  628. if (window)
  629. tcp->th_win = htons(window);
  630. else
  631. tcp->th_win = htons(1024); /* Who cares */
  632. if (urp)
  633. tcp->th_urp = htons(urp);
  634. /* And the options */
  635. if (tcpoptlen)
  636. memcpy(packet + sizeof(*tcp), tcpopt, tcpoptlen);
  637. /* We should probably copy the data over too */
  638. if (data && datalen)
  639. memcpy(packet + sizeof(*tcp) + tcpoptlen, data, datalen);
  640. tcp->th_sum = 0;
  641. return packet;
  642. }
  643. /* Builds a TCP packet (including an IP header) by packing the fields
  644. with the given information. It allocates a new buffer to store the
  645. packet contents, and then returns that buffer. The packet is not
  646. actually sent by this function. Caller must delete the buffer when
  647. finished with the packet. The packet length is returned in
  648. packetlen, which must be a valid int pointer. */
  649. u8 *build_tcp_raw(const struct in_addr *source,
  650. const struct in_addr *victim, int ttl, u16 ipid, u8 tos,
  651. bool df, const u8 *ipopt, int ipoptlen, u16 sport, u16 dport,
  652. u32 seq, u32 ack, u8 reserved, u8 flags, u16 window,
  653. u16 urp, const u8 *tcpopt, int tcpoptlen, const char *data,
  654. u16 datalen, u32 *packetlen) {
  655. struct tcp_hdr *tcp;
  656. u32 tcplen;
  657. u8 *ip;
  658. tcp = (struct tcp_hdr *) build_tcp(sport, dport, seq, ack, reserved, flags,
  659. window, urp, tcpopt, tcpoptlen, data, datalen, &tcplen);
  660. tcp->th_sum = ipv4_cksum(source, victim, IPPROTO_TCP, tcp, tcplen);
  661. ip = build_ip_raw(source, victim, IPPROTO_TCP, ttl, ipid, tos, df,
  662. ipopt, ipoptlen, (char *) tcp, tcplen, packetlen);
  663. free(tcp);
  664. return ip;
  665. }
  666. /* Builds a TCP packet (including an IPv6 header) by packing the fields
  667. with the given information. It allocates a new buffer to store the
  668. packet contents, and then returns that buffer. The packet is not
  669. actually sent by this function. Caller must delete the buffer when
  670. finished with the packet. The packet length is returned in
  671. packetlen, which must be a valid int pointer. */
  672. u8 *build_tcp_raw_ipv6(const struct in6_addr *source,
  673. const struct in6_addr *victim, u8 tc, u32 flowlabel,
  674. u8 hoplimit, u16 sport, u16 dport, u32 seq, u32 ack,
  675. u8 reserved, u8 flags, u16 window, u16 urp,
  676. const u8 *tcpopt, int tcpoptlen, const char *data,
  677. u16 datalen, u32 *packetlen) {
  678. struct tcp_hdr *tcp;
  679. u32 tcplen;
  680. u8 *ipv6;
  681. tcp = (struct tcp_hdr *) build_tcp(sport, dport, seq, ack, reserved, flags,
  682. window, urp, tcpopt, tcpoptlen, data, datalen, &tcplen);
  683. tcp->th_sum = ipv6_cksum(source, victim, IPPROTO_TCP, tcp, tcplen);
  684. ipv6 = build_ipv6_raw(source, victim, tc, flowlabel, IPPROTO_TCP, hoplimit,
  685. (char *) tcp, tcplen, packetlen);
  686. free(tcp);
  687. return ipv6;
  688. }
  689. /* You need to call sethdrinclude(sd) on the sending sd before calling this */
  690. int send_tcp_raw(int sd, const struct eth_nfo *eth,
  691. const struct in_addr *source,
  692. const struct in_addr *victim, int ttl, bool df,
  693. u8 *ipops, int ipoptlen, u16 sport, u16 dport, u32 seq,
  694. u32 ack, u8 reserved, u8 flags, u16 window, u16 urp,
  695. u8 *options, int optlen, const char *data, u16 datalen) {
  696. struct sockaddr_storage dst;
  697. struct sockaddr_in *dst_in;
  698. unsigned int packetlen;
  699. int res = -1;
  700. u8 *packet = build_tcp_raw(source, victim,
  701. ttl, get_random_u16(), IP_TOS_DEFAULT, df,
  702. ipops, ipoptlen,
  703. sport, dport,
  704. seq, ack, reserved, flags, window, urp,
  705. options, optlen,
  706. data, datalen, &packetlen);
  707. if (!packet)
  708. return -1;
  709. memset(&dst, 0, sizeof(dst));
  710. dst_in = (struct sockaddr_in *) &dst;
  711. dst_in->sin_family = AF_INET;
  712. dst_in->sin_addr = *victim;
  713. res = send_ip_packet(sd, eth, &dst, packet, packetlen);
  714. free(packet);
  715. return res;
  716. }
  717. int send_tcp_raw_decoys(int sd, const struct eth_nfo *eth,
  718. const struct in_addr *victim,
  719. int ttl, bool df,
  720. u8 *ipopt, int ipoptlen,
  721. u16 sport, u16 dport,
  722. u32 seq, u32 ack, u8 reserved, u8 flags,
  723. u16 window, u16 urp, u8 *options, int optlen,
  724. const char *data, u16 datalen) {
  725. int decoy;
  726. for (decoy = 0; decoy < o.numdecoys; decoy++)
  727. if (send_tcp_raw(sd, eth,
  728. &o.decoys[decoy], victim,
  729. ttl, df,
  730. ipopt, ipoptlen,
  731. sport, dport,
  732. seq, ack, reserved, flags, window, urp,
  733. options, optlen, data, datalen) == -1)
  734. return -1;
  735. return 0;
  736. }
  737. /* Build a UDP packet (no IP header). Sets udp->uh_sum to 0 so it can be filled
  738. in by a function with knowledge of the higher-level pseudoheader. */
  739. static u8 *build_udp(u16 sport, u16 dport, const char *data, u16 datalen,
  740. u32 *packetlen) {
  741. struct udp_hdr *udp;
  742. u8 *packet;
  743. *packetlen = sizeof(*udp) + datalen;
  744. packet = (u8 *) safe_malloc(*packetlen);
  745. udp = (struct udp_hdr *) packet;
  746. memset(udp, 0, sizeof(*udp));
  747. udp->uh_sport = htons(sport);
  748. udp->uh_dport = htons(dport);
  749. udp->uh_ulen = htons(*packetlen);
  750. if (data && datalen)
  751. memcpy(packet + sizeof(*udp), data, datalen);
  752. udp->uh_sum = 0;
  753. return packet;
  754. }
  755. /* Builds a UDP packet (including an IP header) by packing the fields
  756. with the given information. It allocates a new buffer to store the
  757. packet contents, and then returns that buffer. The packet is not
  758. actually sent by this function. Caller must delete the buffer when
  759. finished with the packet. The packet length is returned in
  760. packetlen, which must be a valid int pointer. */
  761. u8 *build_udp_raw(const struct in_addr *source, const struct in_addr *victim,
  762. int ttl, u16 ipid, u8 tos, bool df,
  763. u8 *ipopt, int ipoptlen,
  764. u16 sport, u16 dport,
  765. const char *data, u16 datalen, u32 *packetlen) {
  766. struct udp_hdr *udp;
  767. u32 udplen;
  768. u8 *ip;
  769. udp = (struct udp_hdr *) build_udp(sport, dport, data, datalen, &udplen);
  770. udp->uh_sum = ipv4_cksum(source, victim, IPPROTO_UDP, udp, udplen);
  771. ip = build_ip_raw(source, victim, IPPROTO_UDP, ttl, ipid, tos, df,
  772. ipopt, ipoptlen, (char *) udp, udplen, packetlen);
  773. free(udp);
  774. return ip;
  775. }
  776. /* Builds a UDP packet (including an IPv6 header) by packing the fields
  777. with the given information. It allocates a new buffer to store the
  778. packet contents, and then returns that buffer. The packet is not
  779. actually sent by this function. Caller must delete the buffer when
  780. finished with the packet. The packet length is returned in
  781. packetlen, which must be a valid int pointer. */
  782. u8 *build_udp_raw_ipv6(const struct in6_addr *source,
  783. const struct in6_addr *victim, u8 tc, u32 flowlabel,
  784. u8 hoplimit, u16 sport, u16 dport,
  785. const char *data, u16 datalen, u32 *packetlen) {
  786. struct udp_hdr *udp;
  787. u32 udplen;
  788. u8 *ipv6;
  789. udp = (struct udp_hdr *) build_udp(sport, dport, data, datalen, &udplen);
  790. udp->uh_sum = ipv6_cksum(source, victim, IPPROTO_UDP, udp, udplen);
  791. ipv6 = build_ipv6_raw(source, victim, tc, flowlabel, IPPROTO_UDP, hoplimit,
  792. (char *) udp, udplen, packetlen);
  793. free(udp);
  794. return ipv6;
  795. }
  796. int send_udp_raw(int sd, const struct eth_nfo *eth,
  797. struct in_addr *source, const struct in_addr *victim,
  798. int ttl, u16 ipid,
  799. u8 *ipopt, int ipoptlen,
  800. u16 sport, u16 dport, const char *data, u16 datalen) {
  801. struct sockaddr_storage dst;
  802. struct sockaddr_in *dst_in;
  803. unsigned int packetlen;
  804. int res = -1;
  805. u8 *packet = build_udp_raw(source, victim,
  806. ttl, ipid, IP_TOS_DEFAULT, false,
  807. ipopt, ipoptlen,
  808. sport, dport,
  809. data, datalen, &packetlen);
  810. if (!packet)
  811. return -1;
  812. memset(&dst, 0, sizeof(dst));
  813. dst_in = (struct sockaddr_in *) &dst;
  814. dst_in->sin_family = AF_INET;
  815. dst_in->sin_addr = *victim;
  816. res = send_ip_packet(sd, eth, &dst, packet, packetlen);
  817. free(packet);
  818. return res;
  819. }
  820. int send_udp_raw_decoys(int sd, const struct eth_nfo *eth,
  821. const struct in_addr *victim,
  822. int ttl, u16 ipid,
  823. u8 *ipops, int ipoptlen,
  824. u16 sport, u16 dport, const char *data, u16 datalen) {
  825. int decoy;
  826. for (decoy = 0; decoy < o.numdecoys; decoy++)
  827. if (send_udp_raw(sd, eth, &o.decoys[decoy], victim,
  828. ttl, ipid, ipops, ipoptlen,
  829. sport, dport, data, datalen) == -1)
  830. return -1;
  831. return 0;
  832. }
  833. /* Build an SCTP packet (no IP header). */
  834. static u8 *build_sctp(u16 sport, u16 dport, u32 vtag,
  835. const char *chunks, int chunkslen,
  836. const char *data, u16 datalen,
  837. u32 *packetlen) {
  838. struct sctp_hdr *sctp;
  839. u8 *packet;
  840. *packetlen = sizeof(*sctp) + chunkslen + datalen;
  841. packet = (u8 *) safe_malloc(*packetlen);
  842. sctp = (struct sctp_hdr *) packet;
  843. sctp->sh_sport = htons(sport);
  844. sctp->sh_dport = htons(dport);
  845. sctp->sh_sum = 0;
  846. sctp->sh_vtag = htonl(vtag);
  847. if (chunks)
  848. memcpy(packet + sizeof(*sctp), chunks, chunkslen);
  849. if (data)
  850. memcpy(packet + sizeof(*sctp) + chunkslen, data, datalen);
  851. /* RFC 2960 originally defined Adler32 checksums, which was later
  852. * revised to CRC32C in RFC 3309 and RFC 4960 respectively.
  853. * Nmap uses CRC32C by default, unless --adler32 is given. */
  854. if (o.adler32)
  855. sctp->sh_sum = htonl(nbase_adler32(packet, *packetlen));
  856. else
  857. sctp->sh_sum = htonl(nbase_crc32c(packet, *packetlen));
  858. if (o.badsum)
  859. --sctp->sh_sum;
  860. return packet;
  861. }
  862. /* Builds an SCTP packet (including an IP header) by packing the fields
  863. with the given information. It allocates a new buffer to store the
  864. packet contents, and then returns that buffer. The packet is not
  865. actually sent by this function. Caller must delete the buffer when
  866. finished with the packet. The packet length is returned in
  867. packetlen, which must be a valid int pointer. */
  868. u8 *build_sctp_raw(const struct in_addr *source,
  869. const struct in_addr *victim, int ttl, u16 ipid,
  870. u8 tos, bool df, u8 *ipopt, int ipoptlen, u16 sport,
  871. u16 dport, u32 vtag, char *chunks, int chunkslen,
  872. const char *data, u16 datalen, u32 *packetlen) {
  873. u8 *ip, *sctp;
  874. u32 sctplen;
  875. sctp = build_sctp(sport, dport, vtag, chunks, chunkslen, data, datalen, &sctplen);
  876. ip = build_ip_raw(source, victim, IPPROTO_SCTP, ttl, ipid, tos, df,
  877. ipopt, ipoptlen, (char *) sctp, sctplen, packetlen);
  878. free(sctp);
  879. return ip;
  880. }
  881. u8 *build_sctp_raw_ipv6(const struct in6_addr *source,
  882. const struct in6_addr *victim, u8 tc, u32 flowlabel,
  883. u8 hoplimit, u16 sport, u16 dport, u32 vtag,
  884. char *chunks, int chunkslen, const char *data, u16 datalen,
  885. u32 *packetlen) {
  886. u8 *ipv6, *sctp;
  887. u32 sctplen;
  888. sctp = build_sctp(sport, dport, vtag, chunks, chunkslen, data, datalen, &sctplen);
  889. ipv6 = build_ipv6_raw(source, victim, tc, flowlabel, IPPROTO_SCTP, hoplimit,
  890. (char *) sctp, sctplen, packetlen);
  891. free(sctp);
  892. return ipv6;
  893. }
  894. /* Builds an ICMP packet (including an IP header) by packing the fields
  895. with the given information. It allocates a new buffer to store the
  896. packet contents, and then returns that buffer. The packet is not
  897. actually sent by this function. Caller must delete the buffer when
  898. finished with the packet. The packet length is returned in
  899. packetlen, which must be a valid int pointer. The id/seq will be converted
  900. to network byte order (if it differs from HBO) */
  901. u8 *build_icmp_raw(const struct in_addr *source,
  902. const struct in_addr *victim, int ttl, u16 ipid,
  903. u8 tos, bool df, u8 *ipopt, int ipoptlen, u16 seq,
  904. unsigned short id, u8 ptype, u8 pcode, const char *data,
  905. u16 datalen, u32 *packetlen) {
  906. struct ppkt {
  907. u8 type;
  908. u8 code;
  909. u16 checksum;
  910. u16 id;
  911. u16 seq;
  912. u8 data[1500]; /* Note -- first 4-12 bytes can be used for ICMP header */
  913. } pingpkt;
  914. u8 *datastart = pingpkt.data;
  915. /* dlen is the amount of space remaining in the data buffer; it may be reduced
  916. depending on type. */
  917. int dlen = sizeof(pingpkt.data);
  918. int icmplen = 0;
  919. char *ping = (char *) &pingpkt;
  920. pingpkt.type = ptype;
  921. pingpkt.code = pcode;
  922. if (ptype == 8) {
  923. /* echo request */
  924. icmplen = 8;
  925. } else if (ptype == 13 && pcode == 0) {
  926. /* ICMP timestamp req */
  927. icmplen = 20;
  928. memset(datastart, 0, 12);
  929. datastart += 12;
  930. dlen -= 12;
  931. } else if (ptype == 17 && pcode == 0) {
  932. /* icmp netmask req */
  933. icmplen = 12;
  934. memset(datastart, 0, 4);
  935. datastart += 4;
  936. dlen -= 4;
  937. } else {
  938. fatal("Unknown icmp type/code (%d/%d) in %s", ptype, pcode, __func__);
  939. }
  940. /* Copy the data over too */
  941. if (datalen > 0) {
  942. icmplen += MIN(dlen, datalen);
  943. if (data == NULL)
  944. memset(datastart, 0, MIN(dlen, datalen));
  945. else
  946. memcpy(datastart, data, MIN(dlen, datalen));
  947. }
  948. /* Fill out the ping packet. All the ICMP types handled by this function have
  949. the id and seq fields. */
  950. pingpkt.id = htons(id);
  951. pingpkt.seq = htons(seq);
  952. pingpkt.checksum = 0;
  953. pingpkt.checksum = in_cksum((unsigned short *) ping, icmplen);
  954. if (o.badsum)
  955. --pingpkt.checksum;
  956. return build_ip_raw(source, victim, IPPROTO_ICMP, ttl, ipid, tos, df,
  957. ipopt, ipoptlen, ping, icmplen, packetlen);
  958. }
  959. /* Builds an ICMPv6 packet (including an IPv6 header). */
  960. u8 *build_icmpv6_raw(const struct in6_addr *source,
  961. const struct in6_addr *victim, u8 tc, u32 flowlabel,
  962. u8 hoplimit, u16 seq, u16 id, u8 ptype, u8 pcode,
  963. const char *data, u16 datalen, u32 *packetlen) {
  964. char *packet;
  965. struct icmpv6_hdr *icmpv6;
  966. union icmpv6_msg *msg;
  967. unsigned int icmplen;
  968. u8 *ipv6;
  969. packet = (char *) safe_malloc(sizeof(*icmpv6) + sizeof(*msg) + datalen);
  970. icmpv6 = (struct icmpv6_hdr *) packet;
  971. msg = (union icmpv6_msg *) (packet + sizeof(*icmpv6));
  972. icmplen = sizeof(*icmpv6);
  973. icmpv6->icmpv6_type = ptype;
  974. icmpv6->icmpv6_code = pcode;
  975. if (ptype == ICMPV6_ECHO) {
  976. msg->echo.icmpv6_seq = htons(seq);
  977. msg->echo.icmpv6_id = htons(id);
  978. icmplen += sizeof(msg->echo);
  979. }
  980. /* At this point icmplen <= sizeof(*icmpv6) + sizeof(*msg). */
  981. memcpy(packet + icmplen, data, datalen);
  982. icmplen += datalen;
  983. icmpv6->icmpv6_cksum = 0;
  984. icmpv6->icmpv6_cksum = ipv6_pseudoheader_cksum(source, victim,
  985. IPPROTO_ICMPV6, icmplen, icmpv6);
  986. if (o.badsum)
  987. icmpv6->icmpv6_cksum--;
  988. ipv6 = build_ipv6_raw(source, victim, tc, flowlabel, IPPROTO_ICMPV6, hoplimit,
  989. packet, icmplen, packetlen);
  990. free(packet);
  991. return ipv6;
  992. }
  993. /* Builds an IGMP packet (including an IP header) by packing the fields
  994. with the given information. It allocates a new buffer to store the
  995. packet contents, and then returns that buffer. The packet is not
  996. actually sent by this function. Caller must delete the buffer when
  997. finished with the packet. The packet length is returned in packetlen,
  998. which must be a valid int pointer. */
  999. u8 *build_igmp_raw(const struct in_addr *source,
  1000. const struct in_addr *victim, int ttl, u16 ipid,
  1001. u8 tos, bool df, u8 *ipopt, int ipoptlen, u8 ptype,
  1002. u8 pcode, const char *data, u16 datalen, u32 *packetlen) {
  1003. struct {
  1004. u8 igmp_type;
  1005. u8 igmp_code;
  1006. u16 igmp_cksum;
  1007. u32 var; /* changes between types, unused. usually group address. */
  1008. u8 data[1500];
  1009. } igmp;
  1010. u32 *datastart = (u32 *) igmp.data;
  1011. int dlen = sizeof(igmp.data);
  1012. int igmplen = 0;
  1013. char *pkt = (char *) &igmp;
  1014. igmp.igmp_type = ptype;
  1015. igmp.igmp_code = pcode;
  1016. if (ptype == 0x11) {
  1017. /* Membership Query */
  1018. igmplen = 8;
  1019. } else if (ptype == 0x12) {
  1020. /* v1 Membership Report */
  1021. igmplen = 8;
  1022. } else if (ptype == 0x16) {
  1023. /* v2 Membership Report */
  1024. igmplen = 8;
  1025. } else if (ptype == 0x17) {
  1026. /* v2 Leave Group */
  1027. igmplen = 8;
  1028. } else if (ptype == 0x22) {
  1029. /* v3 Membership Report */
  1030. igmplen = 8;
  1031. } else {
  1032. fatal("Unknown igmp type (%d) in %s", ptype, __func__);
  1033. }
  1034. if (datalen > 0) {
  1035. igmplen += MIN(dlen, datalen);
  1036. if (data == NULL)
  1037. memset(datastart, 0, MIN(dlen, datalen));
  1038. else
  1039. memcpy(datastart, data, MIN(dlen, datalen));
  1040. }
  1041. igmp.igmp_cksum = 0;
  1042. igmp.igmp_cksum = in_cksum((unsigned short *) pkt, igmplen);
  1043. if (o.badsum)
  1044. --igmp.igmp_cksum;
  1045. return build_ip_raw(source, victim, IPPROTO_IGMP, ttl, ipid, tos, df,
  1046. ipopt, ipoptlen, pkt, igmplen, packetlen);
  1047. }
  1048. /* A simple function I wrote to help in debugging, shows the important fields
  1049. of a TCP packet*/
  1050. int readtcppacket(const u8 *packet, int readdata) {
  1051. struct ip *ip = (struct ip *) packet;
  1052. struct tcp_hdr *tcp = (struct tcp_hdr *) (packet + sizeof(struct ip));
  1053. const unsigned char *data = packet + sizeof(struct ip) + sizeof(struct tcp_hdr);
  1054. int tot_len;
  1055. struct in_addr bullshit, bullshit2;
  1056. char sourcehost[16];
  1057. int i;
  1058. int realfrag = 0;
  1059. if (!packet) {
  1060. error("%s: packet is NULL!", __func__);
  1061. return -1;
  1062. }
  1063. bullshit.s_addr = ip->ip_src.s_addr;
  1064. bullshit2.s_addr = ip->ip_dst.s_addr;
  1065. realfrag = htons(ntohs(ip->ip_off) & IP_OFFMASK);
  1066. tot_len = htons(ip->ip_len);
  1067. strncpy(sourcehost, inet_ntoa(bullshit), 16);
  1068. i = 4 * (ntohs(ip->ip_hl) + ntohs(tcp->th_off));
  1069. if (ip->ip_p == IPPROTO_TCP) {
  1070. if (realfrag)
  1071. log_write(LOG_PLAIN, "Packet is fragmented, offset field: %u\n",
  1072. realfrag);
  1073. else {
  1074. log_write(LOG_PLAIN,
  1075. "TCP packet: %s:%d -> %s:%d (total: %d bytes)\n",
  1076. sourcehost, ntohs(tcp->th_sport), inet_ntoa(bullshit2),
  1077. ntohs(tcp->th_dport), tot_len);
  1078. log_write(LOG_PLAIN, "Flags: ");
  1079. if (!tcp->th_flags)
  1080. log_write(LOG_PLAIN, "(none)");
  1081. if (tcp->th_flags & TH_RST)
  1082. log_write(LOG_PLAIN, "RST ");
  1083. if (tcp->th_flags & TH_SYN)
  1084. log_write(LOG_PLAIN, "SYN ");
  1085. if (tcp->th_flags & TH_ACK)
  1086. log_write(LOG_PLAIN, "ACK ");
  1087. if (tcp->th_flags & TH_PUSH)
  1088. log_write(LOG_PLAIN, "PSH ");
  1089. if (tcp->th_flags & TH_FIN)
  1090. log_write(LOG_PLAIN, "FIN ");
  1091. if (tcp->th_flags & TH_URG)
  1092. log_write(LOG_PLAIN, "URG ");
  1093. log_write(LOG_PLAIN, "\n");
  1094. log_write(LOG_PLAIN, "ipid: %hu ttl: %hu ", ntohs(ip->ip_id),
  1095. ip->ip_ttl);
  1096. if (tcp->th_flags & (TH_SYN | TH_ACK))
  1097. log_write(LOG_PLAIN, "Seq: %u\tAck: %u\n",
  1098. (unsigned int) ntohl(tcp->th_seq),
  1099. (unsigned int) ntohl(tcp->th_ack));
  1100. else if (tcp->th_flags & TH_SYN)
  1101. log_write(LOG_PLAIN, "Seq: %u\n",
  1102. (unsigned int) ntohl(tcp->th_seq));
  1103. else if (tcp->th_flags & TH_ACK)
  1104. log_write(LOG_PLAIN, "Ack: %u\n",
  1105. (unsigned int) ntohl(tcp->th_ack));
  1106. }
  1107. }
  1108. if (readdata && i < tot_len) {
  1109. log_write(LOG_PLAIN, "Data portion:\n");
  1110. while (i < tot_len) {
  1111. log_write(LOG_PLAIN, "%2X%c", data[i], ((i + 1) % 16) ? ' ' : '\n');
  1112. i++;
  1113. }
  1114. log_write(LOG_PLAIN, "\n");
  1115. }
  1116. return 0;
  1117. }
  1118. /* A simple function I wrote to help in debugging, shows the important fields
  1119. of a UDP packet*/
  1120. int readudppacket(const u8 *packet, int readdata) {
  1121. struct ip *ip = (struct ip *) packet;
  1122. struct udp_hdr *udp = (struct udp_hdr *) (packet + sizeof(struct ip));
  1123. const unsigned char *data = packet + sizeof(struct ip) + sizeof(struct udp_hdr);
  1124. int tot_len;
  1125. struct in_addr bullshit, bullshit2;
  1126. char sourcehost[16];
  1127. int i;
  1128. int realfrag = 0;
  1129. if (!packet) {
  1130. error("%s: packet is NULL!", __func__);
  1131. return -1;
  1132. }
  1133. bullshit.s_addr = ip->ip_src.s_addr;
  1134. bullshit2.s_addr = ip->ip_dst.s_addr;
  1135. realfrag = htons(ntohs(ip->ip_off) & IP_OFFMASK);
  1136. tot_len = htons(ip->ip_len);
  1137. strncpy(sourcehost, inet_ntoa(bullshit), 16);
  1138. i = 4 * (ntohs(ip->ip_hl)) + 8;
  1139. if (ip->ip_p == IPPROTO_UDP) {
  1140. if (realfrag)
  1141. log_write(LOG_PLAIN, "Packet is fragmented, offset field: %u\n",
  1142. realfrag);
  1143. else {
  1144. log_write(LOG_PLAIN,
  1145. "UDP packet: %s:%d -> %s:%d (total: %d bytes)\n",
  1146. sourcehost, ntohs(udp->uh_sport), inet_ntoa(bullshit2),
  1147. ntohs(udp->uh_dport), tot_len);
  1148. log_write(LOG_PLAIN, "ttl: %hu ", ip->ip_ttl);
  1149. }
  1150. }
  1151. if (readdata && i < tot_len) {
  1152. log_write(LOG_PLAIN, "Data portion:\n");
  1153. while (i < tot_len) {
  1154. log_write(LOG_PLAIN, "%2X%c", data[i], ((i + 1) % 16)

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