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