PageRenderTime 85ms CodeModel.GetById 25ms RepoModel.GetById 0ms app.codeStats 0ms

/libnetutil/netutil.cc

https://github.com/prakashgamit/nmap
C++ | 4671 lines | 3245 code | 641 blank | 785 comment | 1020 complexity | 317df23bea9b4a37bd50dc77d57fada7 MD5 | raw file
Possible License(s): BSD-3-Clause, GPL-2.0, LGPL-2.0, LGPL-2.1
  1. /***************************************************************************
  2. * netutil.cc *
  3. * *
  4. ***********************IMPORTANT NMAP LICENSE TERMS************************
  5. * *
  6. * The Nmap Security Scanner is (C) 1996-2013 Insecure.Com LLC. Nmap is *
  7. * also a registered trademark of Insecure.Com LLC. This program is free *
  8. * software; you may redistribute and/or modify it under the terms of the *
  9. * GNU General Public License as published by the Free Software *
  10. * Foundation; Version 2 ("GPL"), BUT ONLY WITH ALL OF THE CLARIFICATIONS *
  11. * AND EXCEPTIONS DESCRIBED HEREIN. This guarantees your right to use, *
  12. * modify, and redistribute this software under certain conditions. If *
  13. * you wish to embed Nmap technology into proprietary software, we sell *
  14. * alternative licenses (contact sales@nmap.com). Dozens of software *
  15. * vendors already license Nmap technology such as host discovery, port *
  16. * scanning, OS detection, version detection, and the Nmap Scripting *
  17. * Engine. *
  18. * *
  19. * Note that the GPL places important restrictions on "derivative works", *
  20. * yet it does not provide a detailed definition of that term. To avoid *
  21. * misunderstandings, we interpret that term as broadly as copyright law *
  22. * allows. For example, we consider an application to constitute a *
  23. * derivative work for the purpose of this license if it does any of the *
  24. * following with any software or content covered by this license *
  25. * ("Covered Software"): *
  26. * *
  27. * o Integrates source code from Covered Software. *
  28. * *
  29. * o Reads or includes copyrighted data files, such as Nmap's nmap-os-db *
  30. * or nmap-service-probes. *
  31. * *
  32. * o Is designed specifically to execute Covered Software and parse the *
  33. * results (as opposed to typical shell or execution-menu apps, which will *
  34. * execute anything you tell them to). *
  35. * *
  36. * o Includes Covered Software in a proprietary executable installer. The *
  37. * installers produced by InstallShield are an example of this. Including *
  38. * Nmap with other software in compressed or archival form does not *
  39. * trigger this provision, provided appropriate open source decompression *
  40. * or de-archiving software is widely available for no charge. For the *
  41. * purposes of this license, an installer is considered to include Covered *
  42. * Software even if it actually retrieves a copy of Covered Software from *
  43. * another source during runtime (such as by downloading it from the *
  44. * Internet). *
  45. * *
  46. * o Links (statically or dynamically) to a library which does any of the *
  47. * above. *
  48. * *
  49. * o Executes a helper program, module, or script to do any of the above. *
  50. * *
  51. * This list is not exclusive, but is meant to clarify our interpretation *
  52. * of derived works with some common examples. Other people may interpret *
  53. * the plain GPL differently, so we consider this a special exception to *
  54. * the GPL that we apply to Covered Software. Works which meet any of *
  55. * these conditions must conform to all of the terms of this license, *
  56. * particularly including the GPL Section 3 requirements of providing *
  57. * source code and allowing free redistribution of the work as a whole. *
  58. * *
  59. * As another special exception to the GPL terms, Insecure.Com LLC grants *
  60. * permission to link the code of this program with any version of the *
  61. * OpenSSL library which is distributed under a license identical to that *
  62. * listed in the included docs/licenses/OpenSSL.txt file, and distribute *
  63. * linked combinations including the two. *
  64. * *
  65. * Any redistribution of Covered Software, including any derived works, *
  66. * must obey and carry forward all of the terms of this license, including *
  67. * obeying all GPL rules and restrictions. For example, source code of *
  68. * the whole work must be provided and free redistribution must be *
  69. * allowed. All GPL references to "this License", are to be treated as *
  70. * including the terms and conditions of this license text as well. *
  71. * *
  72. * Because this license imposes special exceptions to the GPL, Covered *
  73. * Work may not be combined (even as part of a larger work) with plain GPL *
  74. * software. The terms, conditions, and exceptions of this license must *
  75. * be included as well. This license is incompatible with some other open *
  76. * source licenses as well. In some cases we can relicense portions of *
  77. * Nmap or grant special permissions to use it in other open source *
  78. * software. Please contact fyodor@nmap.org with any such requests. *
  79. * Similarly, we don't incorporate incompatible open source software into *
  80. * Covered Software without special permission from the copyright holders. *
  81. * *
  82. * If you have any questions about the licensing restrictions on using *
  83. * Nmap in other works, are happy to help. As mentioned above, we also *
  84. * offer alternative license to integrate Nmap into proprietary *
  85. * applications and appliances. These contracts have been sold to dozens *
  86. * of software vendors, and generally include a perpetual license as well *
  87. * as providing for priority support and updates. They also fund the *
  88. * continued development of Nmap. Please email sales@nmap.com for further *
  89. * information. *
  90. * *
  91. * If you have received a written license agreement or contract for *
  92. * Covered Software stating terms other than these, you may choose to use *
  93. * and redistribute Covered Software under those terms instead of these. *
  94. * *
  95. * Source is provided to this software because we believe users have a *
  96. * right to know exactly what a program is going to do before they run it. *
  97. * This also allows you to audit the software for security holes (none *
  98. * have been found so far). *
  99. * *
  100. * Source code also allows you to port Nmap to new platforms, fix bugs, *
  101. * and add new features. You are highly encouraged to send your changes *
  102. * to the dev@nmap.org mailing list for possible incorporation into the *
  103. * main distribution. By sending these changes to Fyodor or one of the *
  104. * Insecure.Org development mailing lists, or checking them into the Nmap *
  105. * source code repository, it is understood (unless you specify otherwise) *
  106. * that you are offering the Nmap Project (Insecure.Com LLC) the *
  107. * unlimited, non-exclusive right to reuse, modify, and relicense the *
  108. * code. Nmap will always be available Open Source, but this is important *
  109. * because the inability to relicense code has caused devastating problems *
  110. * for other Free Software projects (such as KDE and NASM). We also *
  111. * occasionally relicense the code to third parties as discussed above. *
  112. * If you wish to specify special license conditions of your *
  113. * contributions, just say so when you send them. *
  114. * *
  115. * This program is distributed in the hope that it will be useful, but *
  116. * WITHOUT ANY WARRANTY; without even the implied warranty of *
  117. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the Nmap *
  118. * license file for more details (it's in a COPYING file included with *
  119. * Nmap, and also available from https://svn.nmap.org/nmap/COPYING *
  120. * *
  121. ***************************************************************************/
  122. /* Since OS X 10.7, we must declare whether we expect RFC 2292 or RFC 3542
  123. behavior from <netinet6/in6.h>. */
  124. #define __APPLE_USE_RFC_3542
  125. #if HAVE_CONFIG_H
  126. #include "../nmap_config.h"
  127. #endif
  128. #include "nbase.h"
  129. #ifdef WIN32
  130. #include "mswin32/winclude.h"
  131. #include "pcap-int.h"
  132. #else
  133. #include <sys/ioctl.h>
  134. #endif
  135. #include <assert.h>
  136. #include <errno.h>
  137. #include <sys/types.h>
  138. #if HAVE_SYS_SOCKET_H
  139. #include <sys/socket.h>
  140. #endif
  141. #if HAVE_SYS_SOCKIO_H
  142. #include <sys/sockio.h> /* SIOCGIFCONF for Solaris */
  143. #endif
  144. /* Define CMSG_* symbols for Solaris 9 and earlier. See
  145. http://wiki.opencsw.org/porting-faq#toc10. */
  146. #if defined(__sun) || defined(__sun__)
  147. # ifndef CMSG_ALIGN
  148. # ifdef __sun__
  149. # define CMSG_ALIGN(len) _CMSG_DATA_ALIGN (len)
  150. # else
  151. /* aligning to sizeof (long) is assumed to be portable (fd.o#40235) */
  152. # define CMSG_ALIGN(len) (((len) + sizeof (long) - 1) & ~(sizeof (long) - 1))
  153. # endif
  154. # endif
  155. # ifndef CMSG_SPACE
  156. # define CMSG_SPACE(len) (CMSG_ALIGN (sizeof (struct cmsghdr)) + CMSG_ALIGN (len))
  157. # endif
  158. # ifndef CMSG_LEN
  159. # define CMSG_LEN(len) (CMSG_ALIGN (sizeof (struct cmsghdr)) + (len))
  160. # endif
  161. #endif /* Solaris */
  162. #if HAVE_NETINET_IN_H
  163. #include <netinet/in.h>
  164. #endif
  165. #ifdef HAVE_LINUX_RTNETLINK_H
  166. #include <linux/rtnetlink.h>
  167. #endif
  168. #ifndef NETINET_IN_SYSTM_H /* This guarding is needed for at least some versions of OpenBSD */
  169. #include <netinet/in_systm.h>
  170. #define NETINET_IN_SYSTM_H
  171. #endif
  172. #include "netutil.h"
  173. #if HAVE_NET_IF_H
  174. #ifndef NET_IF_H /* This guarding is needed for at least some versions of OpenBSD */
  175. #include <net/if.h>
  176. #define NET_IF_H
  177. #endif
  178. #endif
  179. #ifndef NETINET_IP_H /* This guarding is needed for at least some versions of OpenBSD */
  180. #include <netinet/ip.h>
  181. #define NETINET_IP_H
  182. #endif
  183. #include <net/if_arp.h>
  184. #if HAVE_SYS_RESOURCE_H
  185. #include <sys/resource.h>
  186. #endif
  187. #define NBASE_MAX_ERR_STR_LEN 1024 /* Max length of an error message */
  188. /** Print fatal error messages to stderr and then exits. A newline
  189. character is printed automatically after the supplied text.
  190. * @warning This function does not return because it calls exit() */
  191. void netutil_fatal(const char *str, ...){
  192. va_list list;
  193. char errstr[NBASE_MAX_ERR_STR_LEN];
  194. memset(errstr,0, NBASE_MAX_ERR_STR_LEN);
  195. va_start(list, str);
  196. fflush(stdout);
  197. /* Print error msg to strerr */
  198. vfprintf(stderr, str, list);
  199. fprintf(stderr,"\n");
  200. va_end(list);
  201. exit(EXIT_FAILURE);
  202. } /* End of fatal() */
  203. /** Print error messages to stderr and then return. A newline
  204. character is printed automatically after the supplied text.*/
  205. int netutil_error(const char *str, ...){
  206. va_list list;
  207. char errstr[NBASE_MAX_ERR_STR_LEN];
  208. memset(errstr,0, NBASE_MAX_ERR_STR_LEN);
  209. va_start(list, str);
  210. fflush(stdout);
  211. /* Print error msg to strerr */
  212. vfprintf(stderr, str, list);
  213. fprintf(stderr,"\n");
  214. va_end(list);
  215. return 0;
  216. } /* End of error() */
  217. /* This function converts zero-terminated 'txt' string to binary 'data'.
  218. It is used to parse user input for ip options. Some examples of possible input
  219. strings and results:
  220. '\x01*2\xA2' -> [0x01,0x01,0xA2] // with 'x' number is parsed in hex
  221. '\01\01\255' -> [0x01,0x01,0xFF] // without 'x' its in decimal
  222. '\x01\x00*2' -> [0x01,0x00,0x00] // '*' is copying char
  223. 'R' -> Record Route with 9 slots
  224. 'S 192.168.0.1 172.16.0.1' -> Strict Route with 2 slots
  225. 'L 192.168.0.1 172.16.0.1' -> Loose Route with 2 slots
  226. 'T' -> Record Timestamp with 9 slots
  227. 'U' -> Record Timestamp and Ip Address with 4 slots
  228. On success, the function returns the length of the final binary
  229. options stored in "data". In case of error, OP_FAILURE is returned
  230. and the "errstr" buffer is filled with an error message
  231. (unless it's NULL). Note that the returned error message does NOT
  232. contain a newline character at the end. */
  233. int parse_ip_options(const char *txt, u8 *data, int datalen, int* firsthopoff, int* lasthopoff, char *errstr, size_t errstrlen){
  234. enum{
  235. NONE = 0,
  236. SLASH = 1,
  237. MUL = 2,
  238. RR = 3,
  239. TIME = 4,
  240. } s = NONE;
  241. char *n, lc;
  242. const char *c = txt;
  243. u8 *d = data;
  244. int i,j;
  245. int base = 10;
  246. u8 *dataend = &data[datalen];
  247. u8 *len = NULL;
  248. char buf[32];
  249. memset(data, 0, datalen);
  250. int sourcerouting = 0;
  251. long strtolbyte = 0; // used to check strtol() return boundaries
  252. for(;*c;c++){
  253. switch(s){
  254. case SLASH:
  255. // parse \x00 string
  256. if(*c == 'x'){// just ignore this char
  257. base = 16;
  258. break;
  259. }
  260. if(isxdigit(*c)){
  261. strtolbyte = strtol(c, &n, base);
  262. if((strtolbyte < 0) || (strtolbyte > 255)){
  263. if(errstr) Snprintf(errstr, errstrlen, "invalid ipv4 address format");
  264. return OP_FAILURE;
  265. }
  266. *d++ = (u8) strtolbyte;
  267. c = n-1;
  268. }else{
  269. if(errstr) Snprintf(errstr, errstrlen, "not a digit after '\\'");
  270. return OP_FAILURE;
  271. }
  272. s = NONE;
  273. break;
  274. case MUL:
  275. if(d==data){
  276. if(errstr) Snprintf(errstr, errstrlen, "nothing before '*' char");
  277. return OP_FAILURE;
  278. }
  279. i = strtol(c, &n, 10);
  280. if(i<2){
  281. if(errstr) Snprintf(errstr, errstrlen, "bad number after '*'");
  282. return OP_FAILURE;
  283. }
  284. c = n-1; // move current txt pointer
  285. lc = *(d-1); // last char, we'll copy this
  286. for(j=1; j<i; j++){
  287. *d++ = lc;
  288. if(d == dataend) // check for overflow
  289. goto after;
  290. }
  291. s = NONE;
  292. break;
  293. case RR:
  294. if(*c==' ' || *c==',')
  295. break;
  296. n = buf;
  297. while((*c=='.' || (*c>='0' && *c<='9')) && n-buf <= ((int)sizeof(buf)-1))
  298. *n++ = *c++;
  299. *n = '\0'; c--;
  300. if(d+4>=dataend){
  301. if(errstr) Snprintf(errstr, errstrlen, "Buffer too small. Or input data too big :)");
  302. return OP_FAILURE;
  303. }
  304. i = inet_pton(AF_INET, buf, d);
  305. if(i<1){
  306. if(errstr) Snprintf(errstr, errstrlen, "Not a valid ipv4 address '%s'",buf);
  307. return OP_FAILURE;
  308. }
  309. // remember offset of first hop
  310. if(sourcerouting && !*firsthopoff)
  311. *firsthopoff = d - data;
  312. d+=4;
  313. if(*len<37)
  314. *len += 4;
  315. break;
  316. case TIME:
  317. if(errstr) Snprintf(errstr, errstrlen, "No more arguments allowed!");
  318. return OP_FAILURE;
  319. default:
  320. switch(*c){
  321. case '\\':s = SLASH;base=10;break;
  322. case '*':s = MUL;break;
  323. case 'R':
  324. case 'S':
  325. case 'L':
  326. if(d != data){
  327. if(errstr) Snprintf(errstr, errstrlen, "This option can't be used in that way");
  328. return OP_FAILURE;
  329. }
  330. *d++ = '\x01';//NOP
  331. switch(*c){
  332. case 'R':*d++ = 7;break;
  333. case 'S':*d++ = 137; sourcerouting=1; break;
  334. case 'L':*d++ = 131; sourcerouting=1; break;
  335. }
  336. len = d;
  337. *d++ = (*c=='R')? 39 : 3; // length: 3+4*9 bytes
  338. *d++ = 4; //pointer
  339. s = RR;
  340. break;
  341. case 'T':
  342. case 'U':
  343. if(d != data){
  344. if(errstr) Snprintf(errstr, errstrlen, "This option can't be used in that way");
  345. return OP_FAILURE;
  346. }
  347. *d++ = 68; // option type
  348. len = d;
  349. *d++ = (*c=='U') ? 36 : 40; // length: 3+4*9 bytes or 4+4*9 bytes
  350. *d++ = 5; // pointer
  351. *d++ = (*c=='U') ? 1 : 0; // flag: address and Time fields
  352. s = TIME;
  353. break;
  354. default://*d++ = *c;
  355. if(errstr) Snprintf(errstr, errstrlen, "Bad character in ip option '%c'",*c);
  356. return OP_FAILURE;
  357. }
  358. }
  359. if(d == dataend)
  360. break;
  361. assert(d<dataend);
  362. }
  363. if(sourcerouting){
  364. if(*len<37){
  365. *len+=4;
  366. *lasthopoff = d - data;
  367. *d++ = 0;*d++ = 0;*d++ = 0;*d++ = 0;
  368. }else{
  369. if(errstr) Snprintf(errstr, errstrlen, "When using source routing you must leave at least one slot for target's ip.");
  370. return OP_FAILURE;
  371. }
  372. }
  373. if(s == RR)
  374. return(*len+1); // because we inject NOP before
  375. if(s == TIME)
  376. return(*len);
  377. after:
  378. return(d - data);
  379. }
  380. /* Internal helper for resolve and resolve_numeric. addl_flags is ored into
  381. hints.ai_flags, so you can add AI_NUMERICHOST. */
  382. static int resolve_internal(const char *hostname, unsigned short port,
  383. struct sockaddr_storage *ss, size_t *sslen, int af, int addl_flags) {
  384. struct addrinfo hints;
  385. struct addrinfo *result;
  386. char portbuf[16];
  387. int rc;
  388. assert(hostname);
  389. assert(ss);
  390. assert(sslen);
  391. memset(&hints, 0, sizeof(hints));
  392. hints.ai_family = af;
  393. hints.ai_socktype = SOCK_DGRAM;
  394. hints.ai_flags |= addl_flags;
  395. /* Make the port number a string to give to getaddrinfo. */
  396. rc = Snprintf(portbuf, sizeof(portbuf), "%hu", port);
  397. assert(rc >= 0 && (size_t) rc < sizeof(portbuf));
  398. rc = getaddrinfo(hostname, portbuf, &hints, &result);
  399. if (rc != 0)
  400. return rc;
  401. if (result == NULL)
  402. return EAI_NONAME;
  403. assert(result->ai_addrlen > 0 && result->ai_addrlen <= (int) sizeof(struct sockaddr_storage));
  404. *sslen = result->ai_addrlen;
  405. memcpy(ss, result->ai_addr, *sslen);
  406. freeaddrinfo(result);
  407. return 0;
  408. }
  409. /* Resolves the given hostname or IP address with getaddrinfo, and stores the
  410. first result (if any) in *ss and *sslen. The value of port will be set in the
  411. appropriate place in *ss; set to 0 if you don't care. af may be AF_UNSPEC, in
  412. which case getaddrinfo may return e.g. both IPv4 and IPv6 results; which one
  413. is first depends on the system configuration. Returns 0 on success, or a
  414. getaddrinfo return code (suitable for passing to gai_strerror) on failure.
  415. *ss and *sslen are always defined when this function returns 0. */
  416. int resolve(const char *hostname, unsigned short port,
  417. struct sockaddr_storage *ss, size_t *sslen, int af) {
  418. return resolve_internal(hostname, port, ss, sslen, af, 0);
  419. }
  420. /* As resolve, but do not do DNS resolution of hostnames; the first argument
  421. must be the string representation of a numeric IP address. */
  422. int resolve_numeric(const char *ip, unsigned short port,
  423. struct sockaddr_storage *ss, size_t *sslen, int af) {
  424. return resolve_internal(ip, port, ss, sslen, af, AI_NUMERICHOST);
  425. }
  426. /*
  427. * Returns 1 if this is a reserved IP address, where "reserved" means
  428. * either a private address, non-routable address, or even a non-reserved
  429. * but unassigned address which has an extremely high probability of being
  430. * black-holed.
  431. *
  432. * We try to optimize speed when ordering the tests. This optimization
  433. * assumes that all byte values are equally likely in the input.
  434. *
  435. * Check
  436. * <http://www.iana.org/assignments/ipv4-address-space/ipv4-address-space.txt>
  437. * for the most recent assigments and
  438. * <http://www.cymru.com/Documents/bogon-bn-nonagg.txt> for bogon
  439. * netblocks.
  440. */
  441. int ip_is_reserved(struct in_addr *ip)
  442. {
  443. char *ipc = (char *) &(ip->s_addr);
  444. unsigned char i1 = ipc[0], i2 = ipc[1], i3 = ipc[2]; /* i4 not currently used - , i4 = ipc[3]; */
  445. /* do all the /7's and /8's with a big switch statement, hopefully the
  446. * compiler will be able to optimize this a little better using a jump table
  447. * or what have you
  448. */
  449. switch (i1)
  450. {
  451. case 0: /* 000/8 is IANA reserved */
  452. case 6: /* USA Army ISC */
  453. case 7: /* used for BGP protocol */
  454. case 10: /* the infamous 10.0.0.0/8 */
  455. case 55: /* misc. U.S.A. Armed forces */
  456. case 127: /* 127/8 is reserved for loopback */
  457. return 1;
  458. default:
  459. break;
  460. }
  461. /* 172.16.0.0/12 is reserved for private nets by RFC1819 */
  462. if (i1 == 172 && i2 >= 16 && i2 <= 31)
  463. return 1;
  464. /* 192.0.2.0/24 is reserved for documentation and examples (RFC5737) */
  465. /* 192.88.99.0/24 is used as 6to4 Relay anycast prefix by RFC3068 */
  466. /* 192.168.0.0/16 is reserved for private nets by RFC1819 */
  467. if (i1 == 192) {
  468. if (i2 == 0 && i3 == 2)
  469. return 1;
  470. if (i2 == 88 && i3 == 99)
  471. return 1;
  472. if (i2 == 168)
  473. return 1;
  474. }
  475. /* 198.18.0.0/15 is used for benchmark tests by RFC2544 */
  476. /* 198.51.100.0/24 is reserved for documentation (RFC5737) */
  477. if (i1 == 198) {
  478. if (i2 == 18 || i2 == 19)
  479. return 1;
  480. if (i2 == 51 && i3 == 100)
  481. return 1;
  482. }
  483. /* 169.254.0.0/16 is reserved for DHCP clients seeking addresses */
  484. if (i1 == 169 && i2 == 254)
  485. return 1;
  486. /* 203.0.113.0/24 is reserved for documentation (RFC5737) */
  487. if (i1 == 203 && i2 == 0 && i3 == 113)
  488. return 1;
  489. /* 224-239/8 is all multicast stuff */
  490. /* 240-255/8 is IANA reserved */
  491. if (i1 >= 224)
  492. return 1;
  493. return 0;
  494. }
  495. /* A trivial functon that maintains a cache of IP to MAC Address
  496. entries. If the command is MACCACHE_GET, this func looks for the
  497. IPv4 address in ss and fills in the 'mac' parameter and returns
  498. true if it is found. Otherwise (not found), the function returns
  499. false. If the command is MACCACHE_SET, the function adds an entry
  500. with the given ip (ss) and mac address. An existing entry for the
  501. IP ss will be overwritten with the new MAC address. true is always
  502. returned for the set command. */
  503. #define MACCACHE_GET 1
  504. #define MACCACHE_SET 2
  505. static int do_mac_cache(int command, const struct sockaddr_storage *ss, u8 *mac) {
  506. struct MacCache {
  507. struct sockaddr_storage ip;
  508. u8 mac[6];
  509. };
  510. static struct MacCache *Cache = NULL;
  511. static int MacCapacity = 0;
  512. static int MacCacheSz = 0;
  513. int i;
  514. if (command == MACCACHE_GET) {
  515. for (i = 0; i < MacCacheSz; i++) {
  516. if (sockaddr_storage_cmp(&Cache[i].ip, ss) == 0) {
  517. memcpy(mac, Cache[i].mac, 6);
  518. return 1;
  519. }
  520. }
  521. return 0;
  522. }
  523. assert(command == MACCACHE_SET);
  524. if (MacCacheSz == MacCapacity) {
  525. if (MacCapacity == 0)
  526. MacCapacity = 32;
  527. else
  528. MacCapacity <<= 2;
  529. Cache = (struct MacCache *) safe_realloc(Cache, MacCapacity * sizeof(struct MacCache));
  530. }
  531. /* Ensure that it isn't already there ... */
  532. for (i = 0; i < MacCacheSz; i++) {
  533. if (sockaddr_storage_cmp(&Cache[i].ip, ss) == 0) {
  534. memcpy(Cache[i].mac, mac, 6);
  535. return 1;
  536. }
  537. }
  538. /* Add it to the end of the list */
  539. memcpy(&Cache[i].ip, ss, sizeof(struct sockaddr_storage));
  540. memcpy(Cache[i].mac, mac, 6);
  541. MacCacheSz++;
  542. return 1;
  543. }
  544. /* A couple of trivial functions that maintain a cache of IP to MAC
  545. * Address entries. Function mac_cache_get() looks for the IPv4 address
  546. * in ss and fills in the 'mac' parameter and returns true if it is
  547. * found. Otherwise (not found), the function returns false.
  548. * Function mac_cache_set() adds an entry with the given ip (ss) and
  549. * mac address. An existing entry for the IP ss will be overwritten
  550. * with the new MAC address. mac_cache_set() always returns true.
  551. * WARNING: The caller must ensure that the supplied "ss" is of family
  552. * AF_INET. Otherwise the function will return 0 and there would be
  553. * no way for the caller to tell tell the difference between an error
  554. * or a cache miss.*/
  555. int mac_cache_get(const struct sockaddr_storage *ss, u8 *mac){
  556. return do_mac_cache(MACCACHE_GET, ss, mac);
  557. }
  558. int mac_cache_set(const struct sockaddr_storage *ss, u8 *mac){
  559. return do_mac_cache(MACCACHE_SET, ss, mac);
  560. }
  561. /* Standard BSD internet checksum routine. Uses libdnet helper functions. */
  562. unsigned short in_cksum(u16 *ptr,int nbytes) {
  563. int sum;
  564. sum = ip_cksum_add(ptr, nbytes, 0);
  565. return ip_cksum_carry(sum);
  566. return 0;
  567. }
  568. /* Return true iff this Next Header type is an extension header we must skip to
  569. get to the upper-layer header. Types for which neither this function nor
  570. ipv6_is_upperlayer return true are unknown and could be either. */
  571. static int ipv6_is_extension_header(u8 type)
  572. {
  573. switch (type) {
  574. case IP_PROTO_HOPOPTS:
  575. case IP_PROTO_DSTOPTS:
  576. case IP_PROTO_ROUTING:
  577. case IP_PROTO_FRAGMENT:
  578. /*
  579. case IP_PROTO_ESP:
  580. case IP_PROTO_AH:
  581. */
  582. return 1;
  583. default:
  584. return 0;
  585. }
  586. }
  587. /* Return true iff this Next Header type is a known upper-layer protocol, one
  588. that isn't followed by any more headers. Types for which neither this
  589. function nor ipv6_is_upperlayer return true are unknown and could be
  590. either. */
  591. static int ipv6_is_upperlayer(u8 type)
  592. {
  593. switch (type) {
  594. case IP_PROTO_NONE:
  595. case IP_PROTO_TCP:
  596. case IP_PROTO_UDP:
  597. case IP_PROTO_ICMP:
  598. case IP_PROTO_ICMPV6:
  599. case IP_PROTO_SCTP:
  600. return 1;
  601. default:
  602. return 0;
  603. }
  604. }
  605. /* upperlayer_only controls whether we require a known upper-layer protocol at
  606. the end of the chain, or return the last readable header even if it is not an
  607. upper-layer protocol (may even be another extension header). */
  608. static const void *ipv6_get_data_primitive(const struct ip6_hdr *ip6,
  609. unsigned int *len, u8 *nxt, bool upperlayer_only)
  610. {
  611. const unsigned char *p, *end;
  612. if (*len < sizeof(*ip6))
  613. return NULL;
  614. p = (unsigned char *) ip6;
  615. end = p + *len;
  616. *nxt = ip6->ip6_nxt;
  617. p += sizeof(*ip6);
  618. while (p < end && ipv6_is_extension_header(*nxt)) {
  619. if (p + 2 > end)
  620. return NULL;
  621. *nxt = *p;
  622. p += (*(p + 1) + 1) * 8;
  623. }
  624. *len = end - p;
  625. if (upperlayer_only && !ipv6_is_upperlayer(*nxt))
  626. return NULL;
  627. return (char *) p;
  628. }
  629. static const void *ip_get_data_primitive(const void *packet, unsigned int *len,
  630. struct abstract_ip_hdr *hdr, bool upperlayer_only) {
  631. const struct ip *ip;
  632. ip = (struct ip *) packet;
  633. if (*len >= 20 && ip->ip_v == 4) {
  634. struct sockaddr_in *sin;
  635. hdr->version = 4;
  636. sin = (struct sockaddr_in *) &hdr->src;
  637. memset(&hdr->src, 0, sizeof(hdr->src));
  638. sin->sin_family = AF_INET;
  639. sin->sin_addr.s_addr = ip->ip_src.s_addr;
  640. sin = (struct sockaddr_in *) &hdr->dst;
  641. memset(&hdr->dst, 0, sizeof(hdr->dst));
  642. sin->sin_family = AF_INET;
  643. sin->sin_addr.s_addr = ip->ip_dst.s_addr;
  644. hdr->proto = ip->ip_p;
  645. hdr->ttl = ip->ip_ttl;
  646. hdr->ipid = ntohs(ip->ip_id);
  647. return ipv4_get_data(ip, len);
  648. } else if (*len >= 40 && ip->ip_v == 6) {
  649. const struct ip6_hdr *ip6 = (struct ip6_hdr *) ip;
  650. struct sockaddr_in6 *sin6;
  651. hdr->version = 6;
  652. sin6 = (struct sockaddr_in6 *) &hdr->src;
  653. memset(&hdr->src, 0, sizeof(hdr->src));
  654. sin6->sin6_family = AF_INET6;
  655. memcpy(&sin6->sin6_addr, &ip6->ip6_src, IP6_ADDR_LEN);
  656. sin6 = (struct sockaddr_in6 *) &hdr->dst;
  657. memset(&hdr->dst, 0, sizeof(hdr->dst));
  658. sin6->sin6_family = AF_INET6;
  659. memcpy(&sin6->sin6_addr, &ip6->ip6_dst, IP6_ADDR_LEN);
  660. hdr->ttl = ip6->ip6_hlim;
  661. /* abstract_hdr.ipid is limited to 16 bits. */
  662. hdr->ipid = (u16) ntohl(ip6->ip6_flow & IP6_FLOWLABEL_MASK);
  663. return ipv6_get_data_primitive(ip6, len, &hdr->proto, upperlayer_only);
  664. }
  665. return NULL;
  666. }
  667. /* Find the beginning of the data payload in the IP packet beginning at packet.
  668. Returns the beginning of the payload, updates *len to be the length of the
  669. payload, and fills in hdr if successful. Otherwise returns NULL and *hdr is
  670. undefined. */
  671. const void *ip_get_data(const void *packet, unsigned int *len,
  672. struct abstract_ip_hdr *hdr) {
  673. return ip_get_data_primitive(packet, len, hdr, true);
  674. }
  675. /* As ip_get_data, except that it doesn't insist that the payload be a known
  676. upper-layer protocol. This can matter in IPv6 where the last element of a nh
  677. chain may be a protocol we don't know about. */
  678. const void *ip_get_data_any(const void *packet, unsigned int *len,
  679. struct abstract_ip_hdr *hdr) {
  680. return ip_get_data_primitive(packet, len, hdr, false);
  681. }
  682. /* Get the upper-layer protocol from an IPv4 packet. */
  683. const void *ipv4_get_data(const struct ip *ip, unsigned int *len)
  684. {
  685. unsigned int header_len;
  686. if (*len < 20)
  687. return NULL;
  688. header_len = ip->ip_hl * 4;
  689. if (header_len < sizeof(*ip))
  690. return NULL;
  691. if (header_len > *len)
  692. return NULL;
  693. *len -= header_len;
  694. return (char *) ip + header_len;
  695. }
  696. /* Get the upper-layer protocol from an IPv6 packet. This skips over known
  697. extension headers. The length of the upper-layer payload is stored in *len.
  698. The protocol is stored in *nxt. Returns NULL in case of error. */
  699. const void *ipv6_get_data(const struct ip6_hdr *ip6, unsigned int *len, u8 *nxt)
  700. {
  701. return ipv6_get_data_primitive(ip6, len, nxt, true);
  702. }
  703. /* Get the protocol payload from an IPv6 packet. This skips over known extension
  704. headers. It differs from ipv6_get_data in that it will return a result even
  705. if the final header is not a known upper-layer protocol. */
  706. const void *ipv6_get_data_any(const struct ip6_hdr *ip6, unsigned int *len, u8 *nxt)
  707. {
  708. return ipv6_get_data_primitive(ip6, len, nxt, false);
  709. }
  710. const void *icmp_get_data(const struct icmp_hdr *icmp, unsigned int *len)
  711. {
  712. unsigned int header_len;
  713. if (icmp->icmp_type == ICMP_TIMEXCEED || icmp->icmp_type == ICMP_UNREACH)
  714. header_len = 8;
  715. else
  716. netutil_fatal("%s passed ICMP packet with unhandled type %d", __func__, icmp->icmp_type);
  717. if (header_len > *len)
  718. return NULL;
  719. *len -= header_len;
  720. return (char *) icmp + header_len;
  721. }
  722. const void *icmpv6_get_data(const struct icmpv6_hdr *icmpv6, unsigned int *len)
  723. {
  724. unsigned int header_len;
  725. if (icmpv6->icmpv6_type == ICMPV6_TIMEXCEED || icmpv6->icmpv6_type == ICMPV6_UNREACH)
  726. header_len = 8;
  727. else
  728. netutil_fatal("%s passed ICMPv6 packet with unhandled type %d", __func__, icmpv6->icmpv6_type);
  729. if (header_len > *len)
  730. return NULL;
  731. *len -= header_len;
  732. return (char *) icmpv6 + header_len;
  733. }
  734. /* Calculate the Internet checksum of some given data concatentated with the
  735. IPv4 pseudo-header. See RFC 1071 and TCP/IP Illustrated sections 3.2, 11.3,
  736. and 17.3. */
  737. unsigned short ipv4_pseudoheader_cksum(const struct in_addr *src,
  738. const struct in_addr *dst, u8 proto, u16 len, const void *hstart) {
  739. struct pseudo {
  740. struct in_addr src;
  741. struct in_addr dst;
  742. u8 zero;
  743. u8 proto;
  744. u16 length;
  745. } hdr;
  746. int sum;
  747. hdr.src = *src;
  748. hdr.dst = *dst;
  749. hdr.zero = 0;
  750. hdr.proto = proto;
  751. hdr.length = htons(len);
  752. /* Get the ones'-complement sum of the pseudo-header. */
  753. sum = ip_cksum_add(&hdr, sizeof(hdr), 0);
  754. /* Add it to the sum of the packet. */
  755. sum = ip_cksum_add(hstart, len, sum);
  756. /* Fold in the carry, take the complement, and return. */
  757. return ip_cksum_carry(sum);
  758. }
  759. /* Calculate the Internet checksum of some given data concatenated with the
  760. IPv6 pseudo-header. See RFC 2460 section 8.1. */
  761. u16 ipv6_pseudoheader_cksum(const struct in6_addr *src,
  762. const struct in6_addr *dst, u8 nxt, u32 len, const void *hstart) {
  763. struct {
  764. struct in6_addr src;
  765. struct in6_addr dst;
  766. u32 length;
  767. u8 z0, z1, z2;
  768. u8 nxt;
  769. } hdr;
  770. int sum;
  771. hdr.src = *src;
  772. hdr.dst = *dst;
  773. hdr.z0 = hdr.z1 = hdr.z2 = 0;
  774. hdr.length = htonl(len);
  775. hdr.nxt = nxt;
  776. sum = ip_cksum_add(&hdr, sizeof(hdr), 0);
  777. sum = ip_cksum_add(hstart, len, sum);
  778. /* RFC 2460: "Unlike IPv4, when UDP packets are originated by an IPv6 node,
  779. the UDP checksum is not optional. That is, whenever originating a UDP
  780. packet, an IPv6 node must compute a UDP checksum over the packet and the
  781. pseudo-header, and, if that computation yields a result of zero, it must be
  782. changed to hex FFFF for placement in the UDP header." */
  783. if (nxt == IP_PROTO_UDP && sum == 0)
  784. sum = 0xFFFF;
  785. return ip_cksum_carry(sum);
  786. }
  787. void sethdrinclude(int sd) {
  788. #ifdef IP_HDRINCL
  789. int one = 1;
  790. setsockopt(sd, IPPROTO_IP, IP_HDRINCL, (const char *) &one, sizeof(one));
  791. #endif
  792. }
  793. void set_ipoptions(int sd, void *opts, size_t optslen) {
  794. #ifdef IP_OPTIONS
  795. if (sd == -1)
  796. return;
  797. setsockopt(sd, IPPROTO_IP, IP_OPTIONS, (const char *) opts, optslen);
  798. #endif
  799. }
  800. void set_ttl(int sd, int ttl) {
  801. #ifdef IP_TTL
  802. if (sd == -1)
  803. return;
  804. setsockopt(sd, IPPROTO_IP, IP_TTL, (const char *) &ttl, sizeof ttl);
  805. #endif
  806. }
  807. /* Other than WIN32, what these systems have in common is that they use BPF for
  808. packet capture. (Solaris 10 and earlier used DLPI and had valid selectable
  809. fds.) */
  810. #if defined(WIN32) || defined(MACOSX) || (defined(FREEBSD) && (__FreeBSD_version < 500000) || defined(SOLARIS_BPF_PCAP_CAPTURE))
  811. /* Returns whether the system supports pcap_get_selectable_fd() properly */
  812. int pcap_selectable_fd_valid() {
  813. return 0;
  814. }
  815. /* Call this instead of pcap_get_selectable_fd directly (or your code
  816. won't compile on Windows). On systems which don't seem to support
  817. the pcap_get_selectable_fd() function properly, returns -1,
  818. otherwise simply calls pcap_selectable_fd and returns the
  819. results. If you just want to test whether the function is supported,
  820. use pcap_selectable_fd_valid() instead. */
  821. int my_pcap_get_selectable_fd(pcap_t *p) {
  822. return -1;
  823. }
  824. #else
  825. int pcap_selectable_fd_valid() {
  826. return 1;
  827. }
  828. int my_pcap_get_selectable_fd(pcap_t *p) {
  829. return pcap_get_selectable_fd(p);
  830. }
  831. #endif
  832. /* Are we guaranteed to be able to read exactly one frame for each time the pcap
  833. fd is selectable? If not, it's possible for the fd to become selectable, then
  834. for pcap_dispatch to buffer two or more frames, and return only the first one
  835. Because select doesn't know about pcap's buffer, the fd does not become
  836. selectable again, even though another pcap_next would succeed. On these
  837. platforms, we must do a non-blocking read from the fd before doing a select
  838. on the fd.
  839. It is guaranteed that if pcap_selectable_fd_valid() is false, then so is the
  840. return value of this function. */
  841. int pcap_selectable_fd_one_to_one() {
  842. #ifdef SOLARIS
  843. return 0;
  844. #endif
  845. return pcap_selectable_fd_valid();
  846. }
  847. /* returns -1 if we can't use select() on the pcap device, 0 for timeout, and
  848. * >0 for success. If select() fails we bail out because it couldn't work with
  849. * the file descriptor we got from my_pcap_get_selectable_fd()
  850. */
  851. int pcap_select(pcap_t *p, struct timeval *timeout) {
  852. int fd, ret;
  853. fd_set rfds;
  854. if ((fd = my_pcap_get_selectable_fd(p)) == -1)
  855. return -1;
  856. FD_ZERO(&rfds);
  857. FD_SET(fd, &rfds);
  858. do {
  859. errno = 0;
  860. ret = select(fd + 1, &rfds, NULL, NULL, timeout);
  861. if (ret == -1) {
  862. if (errno == EINTR)
  863. netutil_error("%s: %s", __func__, strerror(errno));
  864. else
  865. netutil_fatal("Your system does not support select()ing on pcap devices (%s). PLEASE REPORT THIS ALONG WITH DETAILED SYSTEM INFORMATION TO THE nmap-dev MAILING LIST!", strerror(errno));
  866. }
  867. } while (ret == -1);
  868. return ret;
  869. }
  870. int pcap_select(pcap_t *p, long usecs) {
  871. struct timeval tv;
  872. tv.tv_sec = usecs / 1000000;
  873. tv.tv_usec = usecs % 1000000;
  874. return pcap_select(p, &tv);
  875. }
  876. /* These two are for eth_open_cached() and eth_close_cached() */
  877. static char etht_cache_device_name[64];
  878. static eth_t *etht_cache_device = NULL;
  879. /* A simple function that caches the eth_t from dnet for one device,
  880. to avoid opening, closing, and re-opening it thousands of tims. If
  881. you give a different device, this function will close the first
  882. one. Thus this should never be used by programs that need to deal
  883. with multiple devices at once. In addition, you MUST NEVER
  884. eth_close() A DEVICE OBTAINED FROM THIS FUNCTION. Instead, you can
  885. call eth_close_cached() to close whichever device (if any) is
  886. cached. Returns NULL if it fails to open the device. */
  887. eth_t *eth_open_cached(const char *device) {
  888. if (!device)
  889. netutil_fatal("%s() called with NULL device name!", __func__);
  890. if (!*device)
  891. netutil_fatal("%s() called with empty device name!", __func__);
  892. if (strcmp(device, etht_cache_device_name) == 0) {
  893. /* Yay, we have it cached. */
  894. return etht_cache_device;
  895. }
  896. if (*etht_cache_device_name) {
  897. eth_close(etht_cache_device);
  898. etht_cache_device_name[0] = '\0';
  899. etht_cache_device = NULL;
  900. }
  901. etht_cache_device = eth_open(device);
  902. if (etht_cache_device)
  903. Strncpy(etht_cache_device_name, device,
  904. sizeof(etht_cache_device_name));
  905. return etht_cache_device;
  906. }
  907. /* See the description for eth_open_cached */
  908. void eth_close_cached() {
  909. if (etht_cache_device) {
  910. eth_close(etht_cache_device);
  911. etht_cache_device = NULL;
  912. etht_cache_device_name[0] = '\0';
  913. }
  914. return;
  915. }
  916. /* Takes a protocol number like IPPROTO_TCP, IPPROTO_UDP, IPPROTO_IP,
  917. * etc, and returns an ASCII representation (or the string "unknown" if
  918. * it doesn't recognize the number). If uppercase is non zero, the
  919. * returned value will be in uppercase letters, otherwise it'll be
  920. * in lowercase */
  921. const char *proto2ascii_case(u8 proto, int uppercase) {
  922. switch (proto) {
  923. case IPPROTO_TCP:
  924. return uppercase ? "TCP" : "tcp";
  925. break;
  926. case IPPROTO_UDP:
  927. return uppercase ? "UDP" : "udp";
  928. break;
  929. case IPPROTO_SCTP:
  930. return uppercase ? "SCTP" : "sctp";
  931. break;
  932. case IPPROTO_IP:
  933. return uppercase ? "IP" : "ip";
  934. break;
  935. #ifdef IPPROTO_ICMP
  936. case IPPROTO_ICMP:
  937. return uppercase ? "ICMP" : "icmp";
  938. break;
  939. #endif
  940. #ifdef IPPROTO_IPV6
  941. case IPPROTO_IPV6:
  942. return uppercase ? "IPv6" : "ipv6";
  943. break;
  944. #endif
  945. #ifdef IPPROTO_ICMPV6
  946. case IPPROTO_ICMPV6:
  947. return uppercase ? "ICMPv6" : "icmpv6";
  948. break;
  949. #endif
  950. #ifdef IPPROTO_GRE
  951. case IPPROTO_GRE: // Generic Routing Encapsulation
  952. return uppercase ? "GRE" : "gre";
  953. break;
  954. #endif
  955. #ifdef IPPROTO_ESP
  956. case IPPROTO_ESP: // Encapsulating Security Payload (IPSec)
  957. return uppercase ? "IPSec/ESP" : "ipsec/esp";
  958. break;
  959. #endif
  960. #ifdef IPPROTO_AH
  961. case IPPROTO_AH: // Authentication Header (IPSec)
  962. return uppercase ? "IPSec/AH" : "ipsec/ah";
  963. break;
  964. #endif
  965. default:
  966. return uppercase ? "UNKNOWN" : "unknown";
  967. }
  968. return NULL; // Unreached
  969. }
  970. const char *proto2ascii_lowercase(u8 proto) {
  971. return proto2ascii_case(proto, 0);
  972. }
  973. const char *proto2ascii_uppercase(u8 proto) {
  974. return proto2ascii_case(proto, 1);
  975. }
  976. /* Get an ASCII information about a tcp option which is pointed by
  977. optp, with a length of len. The result is stored in the result
  978. buffer. The result may look like "<mss 1452,sackOK,timestamp
  979. 45848914 0,nop,wscale 7>" */
  980. void tcppacketoptinfo(u8 *optp, int len, char *result, int bufsize) {
  981. assert(optp);
  982. assert(result);
  983. char *p, ch;
  984. u8 *q;
  985. int opcode;
  986. u16 tmpshort;
  987. u32 tmpword1, tmpword2;
  988. unsigned int i=0;
  989. p = result;
  990. *p = '\0';
  991. q = optp;
  992. ch = '<';
  993. while (len > 0 && bufsize > 2) {
  994. Snprintf(p, bufsize, "%c", ch);
  995. bufsize--;
  996. p++;
  997. opcode = *q++;
  998. if (!opcode) { /* End of List */
  999. Snprintf(p, bufsize, "eol");
  1000. bufsize -= strlen(p);
  1001. p += strlen(p);
  1002. len--;
  1003. } else if (opcode == 1) { /* No Op */
  1004. Snprintf(p, bufsize, "nop");
  1005. bufsize -= strlen(p);
  1006. p += strlen(p);
  1007. len--;
  1008. } else if (opcode == 2) { /* MSS */
  1009. if (len < 4)
  1010. break; /* MSS has 4 bytes */
  1011. q++;
  1012. memcpy(&tmpshort, q, 2);
  1013. Snprintf(p, bufsize, "mss %hu", (unsigned short) ntohs(tmpshort));
  1014. bufsize -= strlen(p);
  1015. p += strlen(p);
  1016. q += 2;
  1017. len -= 4;
  1018. } else if (opcode == 3) { /* Window Scale */
  1019. if (len < 3)
  1020. break; /* Window Scale option has 3 bytes */
  1021. q++;
  1022. Snprintf(p, bufsize, "wscale %u", *q);
  1023. bufsize -= strlen(p);
  1024. p += strlen(p);
  1025. q++;
  1026. len -= 3;
  1027. } else if (opcode == 4) { /* SACK permitted */
  1028. if (len < 2)
  1029. break; /* SACK permitted option has 2 bytes */
  1030. Snprintf(p, bufsize, "sackOK");
  1031. bufsize -= strlen(p);
  1032. p += strlen(p);
  1033. q++;
  1034. len -= 2;
  1035. } else if (opcode == 5) { /* SACK */
  1036. unsigned sackoptlen = *q;
  1037. if ((unsigned) len < sackoptlen)
  1038. break;
  1039. /* This would break parsing, so it's best to just give up */
  1040. if (sackoptlen < 2)
  1041. break;
  1042. q++;
  1043. if ((sackoptlen - 2) == 0 || ((sackoptlen - 2) % 8 != 0)) {
  1044. Snprintf(p, bufsize, "malformed sack");
  1045. bufsize -= strlen(p);
  1046. p += strlen(p);
  1047. } else {
  1048. Snprintf(p, bufsize, "sack %d ", (sackoptlen - 2) / 8);
  1049. bufsize -= strlen(p);
  1050. p += strlen(p);
  1051. for (i = 0; i < sackoptlen - 2; i += 8) {
  1052. memcpy(&tmpword1, q + i, 4);
  1053. memcpy(&tmpword2, q + i + 4, 4);
  1054. Snprintf(p, bufsize, "{%u:%u}", tmpword1, tmpword2);
  1055. bufsize -= strlen(p);
  1056. p += strlen(p);
  1057. }
  1058. }
  1059. q += sackoptlen - 2;
  1060. len -= sackoptlen;
  1061. } else if (opcode == 8) { /* Timestamp */
  1062. if (len < 10)
  1063. break; /* Timestamp option has 10 bytes */
  1064. q++;
  1065. memcpy(&tmpword1, q, 4);
  1066. memcpy(&tmpword2, q + 4, 4);
  1067. Snprintf(p, bufsize, "timestamp %lu %lu", (unsigned long) ntohl(tmpword1),
  1068. (unsigned long) ntohl(tmpword2));
  1069. bufsize -= strlen(p);
  1070. p += strlen(p);
  1071. q += 8;
  1072. len -= 10;
  1073. }
  1074. ch = ',';
  1075. }
  1076. if (len > 0) {
  1077. *result = '\0';
  1078. return;
  1079. }
  1080. Snprintf(p, bufsize, ">");
  1081. }
  1082. /* A trivial function used with qsort to sort the routes by netmask and metric */
  1083. static int routecmp(const void *a, const void *b) {
  1084. struct sys_route *r1 = (struct sys_route *) a;
  1085. struct sys_route *r2 = (struct sys_route *) b;
  1086. if (r1->dest.ss_family < r2->dest.ss_family)
  1087. return -1;
  1088. else if (r1->dest.ss_family > r2->dest.ss_family)
  1089. return 1;
  1090. if (r1->netmask_bits < r2->netmask_bits)
  1091. return 1;
  1092. else if (r1->netmask_bits > r2->netmask_bits)
  1093. return -1;
  1094. if (r1->metric < r2->metric)
  1095. return -1;
  1096. else if (r1->metric > r2->metric)
  1097. return 1;
  1098. /* Compare addresses of equal elements to make the sort stable, as suggested
  1099. by the Glibc manual. */
  1100. if (a < b)
  1101. return -1;
  1102. else if (a > b)
  1103. return 1;
  1104. else
  1105. return 0;
  1106. }
  1107. /* Convert an address to a string and back again. The first parsing step
  1108. eliminates magical OS-specific syntax, for example on OS X, fe80:4::X:X:X:X
  1109. becomes "fe80::X:X:X:X" (the "4" in this case is another way of writing the
  1110. zone ID, like "%en0"; i.e., in this case en0 is interface number 4). This
  1111. must be done before e.g. comparing addresses by netmask. */
  1112. static int canonicalize_address(const struct sockaddr_storage *ss,
  1113. struct sockaddr_storage *output) {
  1114. char canonical_ip_string[NI_MAXHOST];
  1115. struct addrinfo hints;
  1116. struct addrinfo *ai;
  1117. int rc;
  1118. /* Convert address to string. */
  1119. rc = getnameinfo((struct sockaddr *) ss, sizeof(*ss),
  1120. canonical_ip_string, sizeof(canonical_ip_string), NULL, 0, NI_NUMERICHOST);
  1121. if (rc != 0) {
  1122. /* Don't care. */
  1123. *output = *ss;
  1124. return 0;
  1125. }
  1126. memset(&hints, 0, sizeof(hints));
  1127. hints.ai_family = ss->ss_family;
  1128. hints.ai_socktype = SOCK_DGRAM;
  1129. hints.ai_flags |= AI_NUMERICHOST;
  1130. rc = getaddrinfo(canonical_ip_string, NULL, &hints, &ai);
  1131. if (rc != 0 || ai == NULL)
  1132. return -1;
  1133. assert(ai->ai_addrlen > 0 && ai->ai_addrlen <= (int) sizeof(*output));
  1134. memcpy(output, ai->ai_addr, ai->ai_addrlen);
  1135. freeaddrinfo(ai);
  1136. return 0;
  1137. }
  1138. static int collect_dnet_interfaces(const struct intf_entry *entry, void *arg) {
  1139. struct dnet_collector_route_nfo *dcrn = (struct dnet_collector_route_nfo *) arg;
  1140. bool primary_done;
  1141. unsigned int num_aliases_done;
  1142. struct sockaddr_storage tmpss;
  1143. int rc;
  1144. primary_done = false;
  1145. num_aliases_done = 0;
  1146. while (!primary_done || num_aliases_done < entry->intf_alias_num) {
  1147. /* Make sure we have room for the new route */
  1148. if (dcrn->numifaces >= dcrn->capacity) {
  1149. dcrn->capacity <<= 2;
  1150. dcrn->ifaces = (struct interface_info *) safe_realloc(dcrn->ifaces,
  1151. dcrn->capacity * sizeof(struct interface_info));
  1152. }
  1153. /* The first time through the loop we add the primary interface record.
  1154. After that we add the aliases one at a time. */
  1155. if (!primary_done) {
  1156. if (addr_ntos(&entry->intf_addr, (struct sockaddr *) &tmpss) == -1) {
  1157. dcrn->ifaces[dcrn->numifaces].addr.ss_family = 0;
  1158. } else {
  1159. rc = canonicalize_address(&tmpss, &dcrn->ifaces[dcrn->numifaces].addr);
  1160. assert(rc == 0);
  1161. }
  1162. dcrn->ifaces[dcrn->numifaces].netmask_bits = entry->intf_addr.addr_bits;
  1163. primary_done = true;
  1164. } else if (num_aliases_done < entry->intf_alias_num) {
  1165. if (addr_ntos(&entry->intf_alias_addrs[num_aliases_done], (struct sockaddr *) &tmpss) == -1) {
  1166. dcrn->ifaces[dcrn->numifaces].addr.ss_family = 0;
  1167. } else {
  1168. rc = canonicalize_address(&tmpss, &dcrn->ifaces[dcrn->numifaces].addr);
  1169. assert(rc == 0);
  1170. }
  1171. dcrn->ifaces[dcrn->numifaces].netmask_bits = entry->intf_alias_addrs[num_aliases_done].addr_bits;
  1172. num_aliases_done++;
  1173. }
  1174. /* OK, address/netmask found. Let's get the name */
  1175. Strncpy(dcrn->ifaces[dcrn->numifaces].devname, entry->intf_name,
  1176. sizeof(dcrn->ifaces[dcrn->numifaces].devname));
  1177. Strncpy(dcrn->ifaces[dcrn->numifaces].devfullname, entry->intf_name,
  1178. sizeof(dcrn->ifaces[dcrn->numifaces].devfullname));
  1179. /* Interface type */
  1180. if (entry->intf_type == INTF_TYPE_ETH && (entry->intf_flags & INTF_FLAG_NOARP) == 0) {
  1181. dcrn->ifaces[dcrn->numifaces].device_type = devt_ethernet;
  1182. /* Collect the MAC address since this is ethernet */
  1183. memcpy(dcrn->ifaces[dcrn->numifaces].mac, &entry->intf_link_addr.addr_eth.data, 6);
  1184. } else if (entry->intf_type == INTF_TYPE_LOOPBACK) {
  1185. dcrn->ifaces[dcrn->numifaces].device_type = devt_loopback;
  1186. } else if (entry->intf_type == INTF_TYPE_TUN) {
  1187. dcrn->ifaces[dcrn->numifaces].device_type = devt_p2p;
  1188. } else {
  1189. dcrn->ifaces[dcrn->numifaces].device_type = devt_other;
  1190. }
  1191. dcrn->ifaces[dcrn->numifaces].ifindex = entry->intf_index;
  1192. dcrn->ifaces[dcrn->numifaces].mtu = entry->intf_mtu;
  1193. /* Is the interface up and running? */
  1194. dcrn->ifaces[dcrn->numifaces].device_up = (entry->intf_flags & INTF_FLAG_UP) ? true : false;
  1195. /* For the rest of the information, we must open the interface directly ... */
  1196. dcrn->numifaces++;
  1197. }
  1198. return 0;
  1199. }
  1200. /* Get a list of interfaces using dnet and intf_loop. */
  1201. static struct interface_info *getinterfaces_dnet(int *howmany, char *errstr, size_t errstrlen) {
  1202. struct dnet_collector_route_nfo dcrn;
  1203. intf_t *it;
  1204. dcrn.routes = NULL;
  1205. dcrn.numroutes = 0;
  1206. dcrn.numifaces = 0;
  1207. assert(howmany);
  1208. /* Initialize the interface array. */
  1209. dcrn.capacity = 16;
  1210. dcrn.ifaces = (struct interface_info *) safe_zalloc(sizeof(struct interface_info) * dcrn.capacity);
  1211. it = intf_open();
  1212. if (!it){
  1213. if(errstr) Snprintf(errstr, errstrlen, "%s: intf_open() failed", __func__);
  1214. *howmany=-1;
  1215. return NULL;
  1216. }
  1217. if (intf_loop(it, collect_dnet_interfaces, &dcrn) != 0){
  1218. if(errstr) Snprintf(errstr, errstrlen, "%s: intf_loop() failed", __func__);
  1219. *howmany=-1;
  1220. return NULL;
  1221. }
  1222. intf_close(it);
  1223. *howmany = dcrn.numifaces;
  1224. return dcrn.ifaces;
  1225. }
  1226. /* Returns an allocated array of struct interface_info representing the
  1227. available interfaces. The number of interfaces is returned in *howmany. This
  1228. function just does caching of results; the real work is done in
  1229. getinterfaces_dnet().
  1230. On error, NULL is returned, howmany is set to -1 and the supplied
  1231. error buffer "errstr", if not NULL, will contain an error message. */
  1232. struct interface_info *getinterfaces(int *howmany, char *errstr, size_t errstrlen) {
  1233. static int initialized = 0;
  1234. static struct interface_info *mydevs;
  1235. static int numifaces = 0;
  1236. if (!initialized) {
  1237. mydevs = getinterfaces_dnet(&numifaces, errstr, errstrlen);
  1238. initialized = 1;
  1239. }
  1240. /* These will propagate any error produced in getinterfaces_xxxx() to
  1241. * the caller. */
  1242. if (howmany)
  1243. *howmany = numifaces;
  1244. return mydevs;
  1245. }
  1246. /* The 'dev' passed in must be at least 32 bytes long. Returns 0 on success. */
  1247. int ipaddr2devname(char *dev, const struct sockaddr_storage *addr) {
  1248. struct interface_info *ifaces;
  1249. int numifaces;
  1250. int i;
  1251. ifaces = getinterfaces(&numifaces, NULL, 0);
  1252. if (ifaces == NULL)
  1253. return -1;
  1254. for (i = 0; i < numifaces; i++) {
  1255. if (sockaddr_storage_cmp(&ifaces[i].addr, addr) == 0) {
  1256. Strncpy(dev, ifaces[i].devname, 32);
  1257. return 0;
  1258. }
  1259. }
  1260. return -1;
  1261. }
  1262. int devname2ipaddr(char *dev, struct sockaddr_storage *addr) {
  1263. struct interface_info *mydevs;
  1264. int numdevs;
  1265. int i;
  1266. mydevs = getinterfaces(&numdevs, NULL, 0);
  1267. if (!mydevs)
  1268. return -1;
  1269. for (i = 0; i < numdevs; i++) {
  1270. if (!strcmp(dev, mydevs[i].devfullname)) {
  1271. *addr = mydevs[i].addr;
  1272. return 0;
  1273. }
  1274. }
  1275. return -1;
  1276. }
  1277. /* Looks for an interface with the given name (iname) and address
  1278. family type, and returns the corresponding interface_info if found.
  1279. Will accept a match of devname or devfullname. Returns NULL if
  1280. none found */
  1281. struct interface_info *getInterfaceByName(const char *iname, int af) {
  1282. struct interface_info *ifaces;
  1283. int numifaces = 0;
  1284. int ifnum;
  1285. ifaces = getinterfaces(&numifaces, NULL, 0);
  1286. for (ifnum = 0; ifnum < numifaces; ifnum++) {
  1287. if ((strcmp(ifaces[ifnum].devfullname, iname) == 0 ||
  1288. strcmp(ifaces[ifnum].devname, iname) == 0) &&
  1289. ifaces[ifnum].addr.ss_family == af)
  1290. return &ifaces[ifnum];
  1291. }
  1292. return NULL;
  1293. }
  1294. int sockaddr_equal(const struct sockaddr_storage *a,
  1295. const struct sockaddr_storage *b) {
  1296. if (a->ss_family == AF_INET && b->ss_family == AF_INET) {
  1297. struct sockaddr_in *sa, *sb;
  1298. sa = (struct sockaddr_in *) a;
  1299. sb = (struct sockaddr_in *) b;
  1300. return sa->sin_addr.s_addr == sb->sin_addr.s_addr;
  1301. } if (a->ss_family == AF_INET6 && b->ss_family == AF_INET6) {
  1302. struct sockaddr_in6 *sa, *sb;
  1303. sa = (struct sockaddr_in6 *) a;
  1304. sb = (struct sockaddr_in6 *) b;
  1305. return memcmp(sa->sin6_addr.s6_addr, sb->sin6_addr.s6_addr, sizeof(sa->sin6_addr.s6_addr)) == 0;
  1306. }
  1307. return 0;
  1308. }
  1309. int sockaddr_equal_netmask(const struct sockaddr_storage *a,
  1310. const struct sockaddr_storage *b, u16 nbits) {
  1311. unsigned char netmask[IP6_ADDR_LEN];
  1312. addr_btom(nbits, netmask, sizeof(netmask));
  1313. if (a->ss_family == AF_INET && b->ss_family == AF_INET) {
  1314. struct in_addr *sa, *sb, *sn;
  1315. sa = &((struct sockaddr_in *) a)->sin_addr;
  1316. sb = &((struct sockaddr_in *) b)->sin_addr;
  1317. sn = (struct in_addr *) netmask;
  1318. return (sa->s_addr & sn->s_addr) == (sb->s_addr & sn->s_addr);
  1319. } else if (a->ss_family == AF_INET6 && b->ss_family == AF_INET6) {
  1320. struct in6_addr *sa, *sb, *sn;
  1321. unsigned int i;
  1322. sa = &((struct sockaddr_in6 *) a)->sin6_addr;
  1323. sb = &((struct sockaddr_in6 *) b)->sin6_addr;
  1324. sn = (struct in6_addr *) netmask;
  1325. for (i = 0; i < sizeof(sa->s6_addr); i++) {
  1326. if ((sa->s6_addr[i] & sn->s6_addr[i]) != (sb->s6_addr[i] & sn->s6_addr[i])) {
  1327. return 0;
  1328. }
  1329. }
  1330. return 1;
  1331. }
  1332. return 0;
  1333. }
  1334. int sockaddr_equal_zero(const struct sockaddr_storage *s) {
  1335. if (s->ss_family == AF_INET) {
  1336. const struct sockaddr_in *sin;
  1337. sin = (struct sockaddr_in *) s;
  1338. return sin->sin_addr.s_addr == 0;
  1339. } if (s->ss_family == AF_INET6) {
  1340. const struct sockaddr_in6 *sin6;
  1341. sin6 = (struct sockaddr_in6 *) s;
  1342. return memcmp(sin6->sin6_addr.s6_addr, IP6_ADDR_UNSPEC, IP6_ADDR_LEN) == 0;
  1343. }
  1344. return 0;
  1345. }
  1346. /* This is a helper for getsysroutes_dnet. Once the table of routes is in
  1347. place, this function assigns each to an interface and removes any routes
  1348. that can't be assigned. */
  1349. static struct dnet_collector_route_nfo *sysroutes_dnet_find_interfaces(struct dnet_collector_route_nfo *dcrn)
  1350. {
  1351. struct interface_info *ifaces;
  1352. int numifaces = 0;
  1353. int i, j;
  1354. int changed=0;
  1355. if( (ifaces=getinterfaces(&numifaces, NULL, 0))==NULL )
  1356. return NULL;
  1357. for (i = 0; i < dcrn->numroutes; i++) {
  1358. if (dcrn->routes[i].device != NULL)
  1359. continue;
  1360. /* First we match up routes whose gateway or destination address
  1361. directly matches the address of an interface. */
  1362. struct sys_route *route = &dcrn->routes[i];
  1363. struct sockaddr_storage *routeaddr;
  1364. /* First see if the gateway was set */
  1365. if (sockaddr_equal_zero(&route->gw))
  1366. routeaddr = &dcrn->routes[i].dest;
  1367. else
  1368. routeaddr = &dcrn->routes[i].gw;
  1369. for (j = 0; j < numifaces; j++) {
  1370. if (sockaddr_equal_netmask(&ifaces[j].addr, routeaddr, ifaces[j].netmask_bits)) {
  1371. dcrn->routes[i].device = &ifaces[j];
  1372. break;
  1373. }
  1374. }
  1375. }
  1376. /* Find any remaining routes that don't yet have an interface, and try to
  1377. match them up with the interface of another route. This handles "two-step"
  1378. routes like sometimes exist with PPP, where the gateway address of the
  1379. default route doesn't match an interface address, but the gateway address
  1380. goes through another route that does have an interface. */
  1381. do {
  1382. changed = 0;
  1383. for (i = 0; i < dcrn->numroutes; i++) {
  1384. if (dcrn->routes[i].device != NULL)
  1385. continue;
  1386. /* Does this route's gateway go through another route with an assigned
  1387. interface? */
  1388. for (j = 0; j < dcrn->numroutes; j++) {
  1389. if (sockaddr_equal(&dcrn->routes[i].gw, &dcrn->routes[j].dest)
  1390. && dcrn->routes[j].device != NULL) {
  1391. dcrn->routes[i].device = dcrn->routes[j].device;
  1392. changed = 1;
  1393. }
  1394. }
  1395. }
  1396. } while (changed);
  1397. /* Cull any routes that still don't have an interface. */
  1398. i = 0;
  1399. while (i < dcrn->numroutes) {
  1400. if (dcrn->routes[i].device == NULL) {
  1401. char destbuf[INET6_ADDRSTRLEN];
  1402. char gwbuf[INET6_ADDRSTRLEN];
  1403. strncpy(destbuf, inet_ntop_ez(&dcrn->routes[i].dest, sizeof(dcrn->routes[i].dest)), sizeof(destbuf));
  1404. strncpy(gwbuf, inet_ntop_ez(&dcrn->routes[i].gw, sizeof(dcrn->routes[i].gw)), sizeof(gwbuf));
  1405. /*
  1406. netutil_error("WARNING: Unable to find appropriate interface for system route to %s/%u gw %s",
  1407. destbuf, dcrn->routes[i].netmask_bits, gwbuf);
  1408. */
  1409. /* Remove this entry from the table. */
  1410. memmove(dcrn->routes + i, dcrn->routes + i + 1, sizeof(dcrn->routes[0]) * (dcrn->numroutes - i - 1));
  1411. dcrn->numroutes--;
  1412. } else {
  1413. i++;
  1414. }
  1415. }
  1416. return dcrn;
  1417. }
  1418. /* This is the callback for the call to route_loop in getsysroutes_dnet. It
  1419. takes a route entry and adds it into the dnet_collector_route_nfo struct. */
  1420. static int collect_dnet_routes(const struct route_entry *entry, void *arg) {
  1421. struct dnet_collector_route_nfo *dcrn = (struct dnet_collector_route_nfo *) arg;
  1422. /* Make sure we have room for the new route */
  1423. if (dcrn->numroutes >= dcrn->capacity) {
  1424. dcrn->capacity <<= 2;
  1425. dcrn->routes = (struct sys_route *) safe_realloc(dcrn->routes, dcrn->capacity * sizeof(struct sys_route));
  1426. }
  1427. /* Now for the important business */
  1428. addr_ntos(&entry->route_dst, (struct sockaddr *) &dcrn->routes[dcrn->numroutes].dest);
  1429. dcrn->routes[dcrn->numroutes].netmask_bits = entry->route_dst.addr_bits;
  1430. addr_ntos(&entry->route_gw, (struct sockaddr *) &dcrn->routes[dcrn->numroutes].gw);
  1431. dcrn->routes[dcrn->numroutes].metric = entry->metric;
  1432. dcrn->routes[dcrn->numroutes].device = getInterfaceByName(entry->intf_name, dcrn->routes[dcrn->numroutes].dest.ss_family);
  1433. dcrn->numroutes++;
  1434. return 0;
  1435. }
  1436. /* Read system routes via libdnet. */
  1437. static struct sys_route *getsysroutes_dnet(int *howmany, char *errstr, size_t errstrlen) {
  1438. struct dnet_collector_route_nfo dcrn;
  1439. dcrn.capacity = 128;
  1440. dcrn.routes = (struct sys_route *) safe_zalloc(dcrn.capacity * sizeof(struct sys_route));
  1441. dcrn.numroutes = 0;
  1442. dcrn.ifaces = NULL;
  1443. dcrn.numifaces = 0;
  1444. assert(howmany);
  1445. route_t *dr = route_open();
  1446. if (!dr){
  1447. if(errstr) Snprintf(errstr, errstrlen, "%s: route_open() failed", __func__);
  1448. *howmany=-1;
  1449. return NULL;
  1450. }
  1451. if (route_loop(dr, collect_dnet_routes, &dcrn) != 0) {
  1452. if(errstr) Snprintf(errstr, errstrlen, "%s: route_loop() failed", __func__);
  1453. *howmany=-1;
  1454. return NULL;
  1455. }
  1456. route_close(dr);
  1457. /* Now match up the routes to interfaces. */
  1458. if( sysroutes_dnet_find_interfaces(&dcrn) == NULL ){
  1459. if(errstr) Snprintf(errstr, errstrlen, "%s: sysroutes_dnet_find_interfaces() failed", __func__);
  1460. return NULL;
  1461. }
  1462. *howmany = dcrn.numroutes;
  1463. return dcrn.routes;
  1464. }
  1465. /* Parse the system routing table, converting each route into a
  1466. sys_route entry. Returns an array of sys_routes. numroutes is set
  1467. to the number of routes in the array. The routing table is only
  1468. read the first time this is called -- later results are cached.
  1469. The returned route array is sorted by netmask with the most
  1470. specific matches first.
  1471. On error, NULL is returned, howmany is set to -1 and the supplied
  1472. error buffer "errstr", if not NULL, will contain an error message. */
  1473. struct sys_route *getsysroutes(int *howmany, char *errstr, size_t errstrlen) {
  1474. static struct sys_route *routes = NULL;
  1475. static int numroutes = 0;
  1476. assert(howmany);
  1477. if (routes != NULL) {
  1478. /* We have it cached. */
  1479. *howmany = numroutes;
  1480. return routes;
  1481. }
  1482. routes = getsysroutes_dnet(howmany, errstr, errstrlen);
  1483. /* Check if we managed to get the routes and sort them if we did */
  1484. if(routes==NULL){
  1485. *howmany=-1;
  1486. return NULL;
  1487. }else{
  1488. numroutes = *howmany;
  1489. /* Ensure that the route array is sorted by netmask and metric */
  1490. qsort(routes, numroutes, sizeof(routes[0]), routecmp);
  1491. }
  1492. return routes;
  1493. }
  1494. /* Tries to determine whether the supplied address corresponds to
  1495. * localhost. (eg: the address is something like 127.x.x.x, the address
  1496. * matches one of the local network interfaces' address, etc).
  1497. * Returns 1 if the address is thought to be localhost and 0 otherwise */
  1498. int islocalhost(const struct sockaddr_storage *ss) {
  1499. char dev[128];
  1500. struct sockaddr_in *sin = NULL;
  1501. struct sockaddr_in6 *sin6 = NULL;
  1502. if (ss->ss_family == AF_INET){
  1503. sin = (struct sockaddr_in *) ss;
  1504. /* If it is 0.0.0.0 or starts with 127 then it is probably localhost. */
  1505. if ((sin->sin_addr.s_addr & htonl(0xFF000000)) == htonl(0x7F000000))
  1506. return 1;
  1507. if (!(sin->sin_addr.s_addr))
  1508. return 1;
  1509. } else {
  1510. sin6 = (struct sockaddr_in6 *) ss;
  1511. /* If it is ::0 or ::1 then it is probably localhost. */
  1512. if (memcmp(&(sin6->sin6_addr), IP6_ADDR_UNSPEC, IP6_ADDR_LEN) == 0)
  1513. return 1;
  1514. if (memcmp(&(sin6->sin6_addr), IP6_ADDR_LOOPBACK, IP6_ADDR_LEN) == 0)
  1515. return 1;
  1516. }
  1517. /* If it is the same addy as a local interface, then it is
  1518. probably localhost */
  1519. if (ipaddr2devname(dev, ss) != -1)
  1520. return 1;
  1521. /* OK, so to a first approximation, this addy is probably not
  1522. localhost */
  1523. return 0;
  1524. }
  1525. /* Determines whether the supplied address corresponds to a private,
  1526. * non-Internet-routable address. See RFC1918 for details.
  1527. * Returns 1 if the address is private or 0 otherwise. */
  1528. int isipprivate(const struct sockaddr_storage *addr) {
  1529. const struct sockaddr_in *sin;
  1530. char *ipc;
  1531. unsigned char i1, i2;
  1532. if (!addr)
  1533. return 0;
  1534. if (addr->ss_family != AF_INET)
  1535. return 0;
  1536. sin = (struct sockaddr_in *) addr;
  1537. ipc = (char *) &(sin->sin_addr.s_addr);
  1538. i1 = ipc[0];
  1539. i2 = ipc[1];
  1540. /* 10.0.0.0/8 */
  1541. if (i1 == 10)
  1542. return 1;
  1543. /* 172.16.0.0/12 */
  1544. if (i1 == 172 && i2 >= 16 && i2 <= 31)
  1545. return 1;
  1546. /* 192.168.0.0/16 */
  1547. if (i1 == 192 && i2 == 168)
  1548. return 1;
  1549. return 0;
  1550. }
  1551. char *nexthdrtoa(u8 nextheader, int acronym){
  1552. static char buffer[129];
  1553. memset(buffer, 0, 129);
  1554. switch(nextheader){
  1555. case 0:
  1556. if(acronym)
  1557. strncpy(buffer, "HOPOPT", 128);
  1558. else
  1559. strncpy(buffer, "IPv6 Hop-by-Hop Option", 128);
  1560. break;
  1561. case 1:
  1562. if(acronym)
  1563. strncpy(buffer, "ICMP", 128);
  1564. else
  1565. strncpy(buffer, "Internet Control Message", 128);
  1566. break;
  1567. case 2:
  1568. if(acronym)
  1569. strncpy(buffer, "IGMP", 128);
  1570. else
  1571. strncpy(buffer, "Internet Group Management", 128);
  1572. break;
  1573. case 4:
  1574. if(acronym)
  1575. strncpy(buffer, "IP", 128);
  1576. else
  1577. strncpy(buffer, "IP in IP (encapsulation)", 128);
  1578. break;
  1579. case 6:
  1580. if(acronym)
  1581. strncpy(buffer, "TCP", 128);
  1582. else
  1583. strncpy(buffer, "Transmission Control Protocol", 128);
  1584. break;
  1585. case 8:
  1586. if(acronym)
  1587. strncpy(buffer, "EGP", 128);
  1588. else
  1589. strncpy(buffer, "Exterior Gateway Protocol", 128);
  1590. break;
  1591. case 9:
  1592. if(acronym)
  1593. strncpy(buffer, "IGP", 128);
  1594. else
  1595. strncpy(buffer, "Interior Gateway Protocol", 128);
  1596. break;
  1597. case 17:
  1598. if(acronym)
  1599. strncpy(buffer, "UDP", 128);
  1600. else
  1601. strncpy(buffer, "User Datagram", 128);
  1602. break;
  1603. case 41:
  1604. if(acronym)
  1605. strncpy(buffer, "IPv6", 128);
  1606. else
  1607. strncpy(buffer, "Internet Protocol version 6", 128);
  1608. break;
  1609. case 43:
  1610. if(acronym)
  1611. strncpy(buffer, "IPv6-Route", 128);
  1612. else
  1613. strncpy(buffer, "Routing Header for IPv6", 128);
  1614. break;
  1615. case 44:
  1616. if(acronym)
  1617. strncpy(buffer, "IPv6-Frag", 128);
  1618. else
  1619. strncpy(buffer, "Fragment Header for IPv6", 128);
  1620. break;
  1621. case 50:
  1622. if(acronym)
  1623. strncpy(buffer, "ESP", 128);
  1624. else
  1625. strncpy(buffer, "Encap Security Payload", 128);
  1626. break;
  1627. case 51:
  1628. if(acronym)
  1629. strncpy(buffer, "AH", 128);
  1630. else
  1631. strncpy(buffer, "Authentication Header", 128);
  1632. break;
  1633. case 55:
  1634. if(acronym)
  1635. strncpy(buffer, "MOBILE", 128);
  1636. else
  1637. strncpy(buffer, "IP Mobility", 128);
  1638. break;
  1639. case 58:
  1640. if(acronym)
  1641. strncpy(buffer, "IPv6-ICMP", 128);
  1642. else
  1643. strncpy(buffer, "ICMP for IPv6", 128);
  1644. break;
  1645. case 59:
  1646. if(acronym)
  1647. strncpy(buffer, "IPv6-NoNxt", 128);
  1648. else
  1649. strncpy(buffer, "No Next Header for IPv6", 128);
  1650. break;
  1651. case 60:
  1652. if(acronym)
  1653. strncpy(buffer, "IPv6-Opts", 128);
  1654. else
  1655. strncpy(buffer, "Destination Options for IPv6", 128);
  1656. break;
  1657. case 70:
  1658. if(acronym)
  1659. strncpy(buffer, "VISA", 128);
  1660. else
  1661. strncpy(buffer, "VISA Protocol", 128);
  1662. break;
  1663. case 88:
  1664. if(acronym)
  1665. strncpy(buffer, "EIGRP", 128);
  1666. else
  1667. strncpy(buffer, "Enhanced Interior Gateway Routing Protocol ", 128);
  1668. break;
  1669. case 94:
  1670. if(acronym)
  1671. strncpy(buffer, "IPIP", 128);
  1672. else
  1673. strncpy(buffer, "IP-within-IP Encapsulation Protocol", 128);
  1674. break;
  1675. case 132:
  1676. if(acronym)
  1677. strncpy(buffer, "SCTP", 128);
  1678. else
  1679. strncpy(buffer, "Stream Control Transmission Protocol", 128);
  1680. break;
  1681. case 133:
  1682. if(acronym)
  1683. strncpy(buffer, "FC", 128);
  1684. else
  1685. strncpy(buffer, "Fibre Channel", 128);
  1686. break;
  1687. case 135:
  1688. if(acronym)
  1689. strncpy(buffer, "MH", 128);
  1690. else
  1691. strncpy(buffer, "Mobility Header", 128);
  1692. break;
  1693. } /* End of switch */
  1694. return buffer;
  1695. } /* End of nexthdrtoa() */
  1696. /* TODO: Needs refactoring */
  1697. static inline char* STRAPP(const char *fmt, ...) {
  1698. static char buf[256];
  1699. static int bp;
  1700. int left = (int)sizeof(buf)-bp;
  1701. if(!fmt){
  1702. bp = 0;
  1703. return(buf);
  1704. }
  1705. if (left <= 0)
  1706. return buf;
  1707. va_list ap;
  1708. va_start(ap, fmt);
  1709. bp += Vsnprintf (buf+bp, left, fmt, ap);
  1710. va_end(ap);
  1711. return(buf);
  1712. }
  1713. /* TODO: Needs refactoring */
  1714. #define HEXDUMP -2
  1715. #define UNKNOWN -1
  1716. #define BREAK() \
  1717. {option_type = HEXDUMP; break;}
  1718. #define CHECK(tt) \
  1719. if(tt >= option_end) \
  1720. {option_type = HEXDUMP; break;}
  1721. /* Takes binary data found in the IP Options field of an IPv4 packet
  1722. * and returns a string containing an ASCII description of the options
  1723. * found. The function returns a pointer to a static buffer that
  1724. * subsequent calls will overwrite. On error, NULL is returned. */
  1725. char *format_ip_options(const u8* ipopt, int ipoptlen) {
  1726. char ipstring[32];
  1727. int option_type = UNKNOWN;// option type
  1728. int option_len = 0; // option length
  1729. int option_pt = 0; // option pointer
  1730. int option_fl = 0; // option flag
  1731. const u8 *tptr; // temp pointer
  1732. u32 *tint; // temp int
  1733. int option_sta = 0; // option start offset
  1734. int option_end = 0; // option end offset
  1735. int pt = 0; // current offset
  1736. // clear buffer
  1737. STRAPP(NULL,NULL);
  1738. if(!ipoptlen)
  1739. return(NULL);
  1740. while(pt<ipoptlen){ // for every char in ipopt
  1741. // read ip option header
  1742. if(option_type == UNKNOWN) {
  1743. option_sta = pt;
  1744. option_type = ipopt[pt++];
  1745. if(option_type != 0 && option_type != 1) { // should we be interested in length field?
  1746. if(pt >= ipoptlen) // no more chars
  1747. {option_type = HEXDUMP;pt--; option_end = 255; continue;} // no length field, hex dump to the end
  1748. option_len = ipopt[pt++];
  1749. // end must not be greater than length
  1750. option_end = MIN(option_sta + option_len, ipoptlen);
  1751. // end must not be smaller than current position
  1752. option_end = MAX(option_end, option_sta+2);
  1753. }
  1754. }
  1755. switch(option_type) {
  1756. case 0: // IPOPT_END
  1757. STRAPP(" EOL", NULL);
  1758. option_type = UNKNOWN;
  1759. break;
  1760. case 1: // IPOPT_NOP
  1761. STRAPP(" NOP", NULL);
  1762. option_type = UNKNOWN;
  1763. break;
  1764. /* case 130: // IPOPT_SECURITY
  1765. option_type=-1;
  1766. break;*/
  1767. case 131: // IPOPT_LSRR -> Loose Source and Record Route
  1768. case 137: // IPOPT_SSRR -> Strict Source and Record Route
  1769. case 7: // IPOPT_RR -> Record Route
  1770. if(pt - option_sta == 2) {
  1771. STRAPP(" %s%s{", (option_type==131)?"LS":(option_type==137)?"SS":"", "RR");
  1772. // option pointer
  1773. CHECK(pt);
  1774. option_pt = ipopt[pt++];
  1775. if(option_pt%4 != 0 || (option_sta + option_pt-1)>option_end || option_pt<4) //bad or too big pointer
  1776. STRAPP(" [bad ptr=%02i]", option_pt);
  1777. }
  1778. if(pt - option_sta > 2) { // ip's
  1779. int i, s = (option_pt)%4;
  1780. // if pointer is mangled, fix it. it's max 3 bytes wrong
  1781. CHECK(pt+3);
  1782. for(i=0; i<s; i++)
  1783. STRAPP("\\x%02x", ipopt[pt++]);
  1784. option_pt -= i;
  1785. // okay, now we can start printing ip's
  1786. CHECK(pt+3);
  1787. tptr = &ipopt[pt]; pt+=4;
  1788. if(inet_ntop(AF_INET, (char *) tptr, ipstring, sizeof(ipstring)) == NULL){
  1789. return NULL;
  1790. }
  1791. STRAPP("%c%s",(pt-3-option_sta)==option_pt?'#':' ', ipstring);
  1792. if(pt == option_end)
  1793. STRAPP("%s",(pt-option_sta)==(option_pt-1)?"#":""); // pointer in the end?
  1794. }else BREAK();
  1795. break;
  1796. case 68: // IPOPT_TS -> Internet Timestamp
  1797. if(pt - option_sta == 2){
  1798. STRAPP(" TM{");
  1799. // pointer
  1800. CHECK(pt);
  1801. option_pt = ipopt[pt++];
  1802. // bad or too big pointer
  1803. if(option_pt%4 != 1 || (option_sta + option_pt-1)>option_end || option_pt<5)
  1804. STRAPP(" [bad ptr=%02i]", option_pt);
  1805. // flags + overflow
  1806. CHECK(pt);
  1807. option_fl = ipopt[pt++];
  1808. if((option_fl&0x0C) || (option_fl&0x03)==2)
  1809. STRAPP(" [bad flags=\\x%01hhx]", option_fl&0x0F);
  1810. STRAPP("[%i hosts not recorded]", option_fl>>4);
  1811. option_fl &= 0x03;
  1812. }
  1813. if(pt - option_sta > 2) {// ip's
  1814. int i, s = (option_pt+3)%(option_fl==0?4:8);
  1815. // if pointer is mangled, fix it. it's max 3 bytes wrong
  1816. CHECK(pt+(option_fl==0?3:7));
  1817. for(i=0; i<s; i++)
  1818. STRAPP("\\x%02x", ipopt[pt++]);
  1819. option_pt-=i;
  1820. // print pt
  1821. STRAPP("%c",(pt+1-option_sta)==option_pt?'#':' ');
  1822. // okay, first grab ip.
  1823. if(option_fl!=0){
  1824. CHECK(pt+3);
  1825. tptr = &ipopt[pt]; pt+=4;
  1826. if(inet_ntop(AF_INET, (char *) tptr, ipstring, sizeof(ipstring)) == NULL){
  1827. return NULL;
  1828. }
  1829. STRAPP("%s@", ipstring);
  1830. }
  1831. CHECK(pt+3);
  1832. tint = (u32*)&ipopt[pt]; pt+=4;
  1833. STRAPP("%lu", (unsigned long) ntohl(*tint));
  1834. if(pt == option_end)
  1835. STRAPP("%s",(pt-option_sta)==(option_pt-1)?"#":" ");
  1836. }else BREAK();
  1837. break;
  1838. case 136: // IPOPT_SATID -> (SANET) Stream Identifier
  1839. if(pt - option_sta == 2){
  1840. u16 *sh;
  1841. STRAPP(" SI{",NULL);
  1842. // length
  1843. if(option_sta+option_len > ipoptlen || option_len!=4)
  1844. STRAPP("[bad len %02i]", option_len);
  1845. // stream id
  1846. CHECK(pt+1);
  1847. sh = (u16*) &ipopt[pt]; pt+=2;
  1848. option_pt = ntohs(*sh);
  1849. STRAPP("id=%hu", (unsigned short) option_pt);
  1850. if(pt != option_end)
  1851. BREAK();
  1852. }else BREAK();
  1853. break;
  1854. case UNKNOWN:
  1855. default:
  1856. // we read option_type and option_len, print them.
  1857. STRAPP(" ??{\\x%02hhx\\x%02hhx", option_type, option_len);
  1858. // check option_end once more:
  1859. if(option_len < ipoptlen)
  1860. option_end = MIN(MAX(option_sta+option_len, option_sta+2),ipoptlen);
  1861. else
  1862. option_end = 255;
  1863. option_type = HEXDUMP;
  1864. break;
  1865. case HEXDUMP:
  1866. assert(pt<=option_end);
  1867. if(pt == option_end){
  1868. STRAPP("}",NULL);
  1869. option_type=-1;
  1870. break;
  1871. }
  1872. STRAPP("\\x%02hhx", ipopt[pt++]);
  1873. break;
  1874. }
  1875. if(pt == option_end && option_type != UNKNOWN) {
  1876. STRAPP("}",NULL);
  1877. option_type = UNKNOWN;
  1878. }
  1879. } // while
  1880. if(option_type != UNKNOWN)
  1881. STRAPP("}");
  1882. return(STRAPP("",NULL));
  1883. }
  1884. #undef CHECK
  1885. #undef BREAK
  1886. #undef UNKNOWN
  1887. #undef HEXDUMP
  1888. /* Returns a buffer of ASCII information about an IP packet that may
  1889. * look like "TCP 127.0.0.1:50923 > 127.0.0.1:3 S ttl=61 id=39516
  1890. * iplen=40 seq=625950769" or "ICMP PING (0/1) ttl=61 id=39516 iplen=40".
  1891. * Returned buffer is static so it is NOT safe to call this in
  1892. * multi-threaded environments without appropriate sync protection, or
  1893. * call it twice in the same sentence (eg: as two printf parameters).
  1894. * Obviously, the caller should never attempt to free() the buffer. The
  1895. * returned buffer is guaranteed to be NULL-terminated but no
  1896. * assumptions should be made concerning its length.
  1897. *
  1898. * The function knows IPv4, IPv6, TCP, UDP, SCTP, ICMP, and ICMPv6.
  1899. *
  1900. * The output has three different levels of detail. Parameter "detail"
  1901. * determines how verbose the output should be. It should take one of
  1902. * the following values:
  1903. *
  1904. * LOW_DETAIL (0x01): Traditional output.
  1905. * MEDIUM_DETAIL (0x02): More verbose than traditional.
  1906. * HIGH_DETAIL (0x03): Contents of virtually every field of the
  1907. * protocol headers .
  1908. */
  1909. const char *ippackethdrinfo(const u8 *packet, u32 len, int detail) {
  1910. struct abstract_ip_hdr hdr;
  1911. const u8 *data;
  1912. unsigned int datalen;
  1913. struct tcp_hdr *tcp = NULL; /* TCP header structure. */
  1914. struct udp_hdr *udp = NULL; /* UDP header structure. */
  1915. struct sctp_hdr *sctp = NULL; /* SCTP header structure. */
  1916. static char protoinfo[1024] = ""; /* Stores final info string. */
  1917. char ipinfo[512] = ""; /* Temp info about IP. */
  1918. char icmpinfo[512] = ""; /* Temp info about ICMP. */
  1919. char icmptype[128] = ""; /* Temp info about ICMP type & code */
  1920. char icmpfields[256] = ""; /* Temp info for various ICMP fields */
  1921. char fragnfo[64] = ""; /* Temp info about fragmentation. */
  1922. char srchost[INET6_ADDRSTRLEN] = ""; /* Src IP in dot-decimal notation. */
  1923. char dsthost[INET6_ADDRSTRLEN] = ""; /* Dst IP in dot-decimal notation. */
  1924. char *p = NULL; /* Aux pointer. */
  1925. int frag_off = 0; /* To compute IP fragment offset. */
  1926. int more_fragments = 0; /* True if IP MF flag is set. */
  1927. int dont_fragment = 0; /* True if IP DF flag is set. */
  1928. int reserved_flag = 0; /* True if IP Reserved flag is set. */
  1929. datalen = len;
  1930. data = (u8 *) ip_get_data_any(packet, &datalen, &hdr);
  1931. if (data == NULL)
  1932. return "BOGUS! Can't parse supposed IP packet";
  1933. /* Ensure we end up with a valid detail number */
  1934. if (detail != LOW_DETAIL && detail != MEDIUM_DETAIL && detail != HIGH_DETAIL)
  1935. detail = LOW_DETAIL;
  1936. /* IP INFORMATION ************************************************************/
  1937. if (hdr.version == 4) { /* IPv4 */
  1938. const struct ip *ip;
  1939. const struct sockaddr_in *sin;
  1940. ip = (struct ip *) packet;
  1941. /* Obtain IP source and destination info */
  1942. sin = (struct sockaddr_in *) &hdr.src;
  1943. inet_ntop(AF_INET, &sin->sin_addr.s_addr, srchost, sizeof(srchost));
  1944. sin = (struct sockaddr_in *) &hdr.dst;
  1945. inet_ntop(AF_INET, &sin->sin_addr.s_addr, dsthost, sizeof(dsthost));
  1946. /* Compute fragment offset and check if flags are set */
  1947. frag_off = 8 * (ntohs(ip->ip_off) & 8191) /* 2^13 - 1 */;
  1948. more_fragments = ntohs(ip->ip_off) & IP_MF;
  1949. dont_fragment = ntohs(ip->ip_off) & IP_DF;
  1950. reserved_flag = ntohs(ip->ip_off) & IP_RF;
  1951. /* Is this a fragmented packet? is it the last fragment? */
  1952. if (frag_off || more_fragments) {
  1953. Snprintf(fragnfo, sizeof(fragnfo), " frag offset=%d%s", frag_off, more_fragments ? "+" : "");
  1954. }
  1955. /* Create a string with information relevant to the specified level of detail */
  1956. if (detail == LOW_DETAIL) {
  1957. Snprintf(ipinfo, sizeof(ipinfo), "ttl=%d id=%hu iplen=%hu%s %s%s%s",
  1958. ip->ip_ttl, (unsigned short) ntohs(ip->ip_id), (unsigned short) ntohs(ip->ip_len), fragnfo,
  1959. ip->ip_hl==5?"":"ipopts={",
  1960. ip->ip_hl==5?"":format_ip_options((u8*) ip + sizeof(struct ip), MIN((unsigned)(ip->ip_hl-5)*4,len-sizeof(struct ip))),
  1961. ip->ip_hl==5?"":"}");
  1962. } else if (detail == MEDIUM_DETAIL) {
  1963. Snprintf(ipinfo, sizeof(ipinfo), "ttl=%d id=%hu proto=%d csum=0x%04x iplen=%hu%s %s%s%s",
  1964. ip->ip_ttl, (unsigned short) ntohs(ip->ip_id),
  1965. ip->ip_p, ntohs(ip->ip_sum),
  1966. (unsigned short) ntohs(ip->ip_len), fragnfo,
  1967. ip->ip_hl==5?"":"ipopts={",
  1968. ip->ip_hl==5?"":format_ip_options((u8*) ip + sizeof(struct ip), MIN((unsigned)(ip->ip_hl-5)*4,len-sizeof(struct ip))),
  1969. ip->ip_hl==5?"":"}");
  1970. } else if (detail == HIGH_DETAIL) {
  1971. Snprintf(ipinfo, sizeof(ipinfo), "ver=%d ihl=%d tos=0x%02x iplen=%hu id=%hu%s%s%s%s foff=%d%s ttl=%d proto=%d csum=0x%04x%s%s%s",
  1972. ip->ip_v, ip->ip_hl,
  1973. ip->ip_tos, (unsigned short) ntohs(ip->ip_len),
  1974. (unsigned short) ntohs(ip->ip_id),
  1975. (reserved_flag||dont_fragment||more_fragments) ? " flg=" : "",
  1976. (reserved_flag)? "x" : "",
  1977. (dont_fragment)? "D" : "",
  1978. (more_fragments)? "M": "",
  1979. frag_off, (more_fragments) ? "+" : "",
  1980. ip->ip_ttl, ip->ip_p,
  1981. ntohs(ip->ip_sum),
  1982. ip->ip_hl==5?"":" ipopts={",
  1983. ip->ip_hl==5?"":format_ip_options((u8*) ip + sizeof(struct ip), MIN((unsigned)(ip->ip_hl-5)*4,len-sizeof(struct ip))),
  1984. ip->ip_hl==5?"":"}");
  1985. }
  1986. } else { /* IPv6 */
  1987. const struct ip6_hdr *ip6;
  1988. const struct sockaddr_in6 *sin6;
  1989. ip6 = (struct ip6_hdr *) packet;
  1990. /* Obtain IP source and destination info */
  1991. sin6 = (struct sockaddr_in6 *) &hdr.src;
  1992. inet_ntop(AF_INET6, sin6->sin6_addr.s6_addr, srchost, sizeof(srchost));
  1993. sin6 = (struct sockaddr_in6 *) &hdr.dst;
  1994. inet_ntop(AF_INET6, sin6->sin6_addr.s6_addr, dsthost, sizeof(dsthost));
  1995. /* Obtain flow label and traffic class */
  1996. u32 flow = ntohl(ip6->ip6_flow);
  1997. u32 ip6_fl = flow & 0x000fffff;
  1998. u32 ip6_tc = (flow & 0x0ff00000) >> 20;
  1999. /* Create a string with information relevant to the specified level of detail */
  2000. if (detail == LOW_DETAIL) {
  2001. Snprintf(ipinfo, sizeof(ipinfo), "hopl=%d flow=%x payloadlen=%hu",
  2002. ip6->ip6_hlim, ip6_fl, (unsigned short) ntohs(ip6->ip6_plen));
  2003. } else if (detail == MEDIUM_DETAIL) {
  2004. Snprintf(ipinfo, sizeof(ipinfo), "hopl=%d tclass=%d flow=%x payloadlen=%hu",
  2005. ip6->ip6_hlim, ip6_tc, ip6_fl, (unsigned short) ntohs(ip6->ip6_plen));
  2006. } else if (detail==HIGH_DETAIL) {
  2007. Snprintf(ipinfo, sizeof(ipinfo), "ver=6, tclass=%x flow=%x payloadlen=%hu nh=%s hopl=%d ",
  2008. ip6_tc, ip6_fl, (unsigned short) ntohs(ip6->ip6_plen),
  2009. nexthdrtoa(ip6->ip6_nxt, 1), ip6->ip6_hlim);
  2010. }
  2011. }
  2012. /* TCP INFORMATION ***********************************************************/
  2013. if (hdr.proto == IPPROTO_TCP) {
  2014. char tflags[10];
  2015. char tcpinfo[64] = "";
  2016. char buf[32];
  2017. char tcpoptinfo[256] = "";
  2018. tcp = (struct tcp_hdr *) data;
  2019. /* Let's parse the TCP header. The following code is very ugly because we
  2020. * have to deal with a lot of different situations. We don't want to
  2021. * segfault so we have to check every length and every bound to ensure we
  2022. * don't read past the packet. We cannot even trust the contents of the
  2023. * received packet because, for example, an IPv4 header may state it
  2024. * carries a TCP packet but may actually carry nothing at all.
  2025. *
  2026. * So we distinguish 4 situations. I know the first two are weird but they
  2027. * were there when I modified this code so I left them there just in
  2028. * case.
  2029. * 1. IP datagram is very small or is a fragment where we are missing
  2030. * the first part of the TCP header
  2031. * 2. IP datagram is a fragment and although we are missing the first
  2032. * 8 bytes of the TCP header, we have the rest of it (or some of
  2033. * the rest of it)
  2034. * 3. IP datagram is NOT a fragment but we don't have the full TCP
  2035. * header, we are missing some bytes.
  2036. * 4. IP datagram is NOT a fragment and we have at least a full 20
  2037. * byte TCP header.
  2038. */
  2039. /* CASE 1: where we don't have the first 8 bytes of the TCP header because
  2040. * either the fragment belongs to somewhere past that or the IP contains
  2041. * less than 8 bytes. This also includes empty IP packets that say they
  2042. * contain a TCP packet. */
  2043. if (frag_off > 8 || datalen < 8) {
  2044. Snprintf(protoinfo, sizeof(protoinfo), "TCP %s:?? > %s:?? ?? %s (incomplete)",
  2045. srchost, dsthost, ipinfo);
  2046. }
  2047. /* CASE 2: where we are missing the first 8 bytes of the TCP header but we
  2048. * have, at least, the next 8 bytes so we can see the ACK number, the
  2049. * flags and window size. */
  2050. else if (frag_off == 8 && datalen >= 8) {
  2051. tcp = (struct tcp_hdr *)((u8 *) tcp - frag_off); // ugly?
  2052. /* TCP Flags */
  2053. p = tflags;
  2054. /* These are basically in tcpdump order */
  2055. if (tcp->th_flags & TH_SYN)
  2056. *p++ = 'S';
  2057. if (tcp->th_flags & TH_FIN)
  2058. *p++ = 'F';
  2059. if (tcp->th_flags & TH_RST)
  2060. *p++ = 'R';
  2061. if (tcp->th_flags & TH_PUSH)
  2062. *p++ = 'P';
  2063. if (tcp->th_flags & TH_ACK) {
  2064. *p++ = 'A';
  2065. Snprintf(tcpinfo, sizeof(tcpinfo), " ack=%lu",
  2066. (unsigned long) ntohl(tcp->th_ack));
  2067. }
  2068. if (tcp->th_flags & TH_URG)
  2069. *p++ = 'U';
  2070. if (tcp->th_flags & TH_ECE)
  2071. *p++ = 'E'; /* rfc 2481/3168 */
  2072. if (tcp->th_flags & TH_CWR)
  2073. *p++ = 'C'; /* rfc 2481/3168 */
  2074. *p++ = '\0';
  2075. /* TCP Options */
  2076. if ((u32) tcp->th_off * 4 > sizeof(struct tcp_hdr)) {
  2077. if (datalen < (u32) tcp->th_off * 4 - frag_off) {
  2078. Snprintf(tcpoptinfo, sizeof(tcpoptinfo), "option incomplete");
  2079. } else {
  2080. tcppacketoptinfo((u8*) tcp + sizeof(struct tcp_hdr),
  2081. tcp->th_off*4 - sizeof(struct tcp_hdr),
  2082. tcpoptinfo, sizeof(tcpoptinfo));
  2083. }
  2084. }
  2085. /* Create a string with TCP information relevant to the specified level of detail */
  2086. if (detail == LOW_DETAIL) {
  2087. Snprintf(protoinfo, sizeof(protoinfo), "TCP %s:?? > %s:?? %s %s %s %s",
  2088. srchost, dsthost, tflags, ipinfo, tcpinfo, tcpoptinfo);
  2089. } else if (detail == MEDIUM_DETAIL) {
  2090. Snprintf(protoinfo, sizeof(protoinfo), "TCP %s:?? > %s:?? %s ack=%lu win=%hu %s IP [%s]",
  2091. srchost, dsthost, tflags,
  2092. (unsigned long) ntohl(tcp->th_ack), (unsigned short) ntohs(tcp->th_win),
  2093. tcpoptinfo, ipinfo);
  2094. } else if (detail == HIGH_DETAIL) {
  2095. if (datalen >= 12) { /* We have at least bytes 8-20 */
  2096. Snprintf(protoinfo, sizeof(protoinfo), "TCP [%s:?? > %s:?? %s seq=%lu ack=%lu off=%d res=%d win=%hu csum=0x%04X urp=%hu%s%s] IP [%s]",
  2097. srchost, dsthost, tflags,
  2098. (unsigned long) ntohl(tcp->th_seq),
  2099. (unsigned long) ntohl(tcp->th_ack),
  2100. (u8)tcp->th_off, (u8)tcp->th_x2, (unsigned short) ntohs(tcp->th_win),
  2101. ntohs(tcp->th_sum), (unsigned short) ntohs(tcp->th_urp),
  2102. (tcpoptinfo[0]!='\0') ? " " : "",
  2103. tcpoptinfo, ipinfo);
  2104. } else { /* We only have bytes 8-16 */
  2105. Snprintf(protoinfo, sizeof(protoinfo), "TCP %s:?? > %s:?? %s ack=%lu win=%hu %s IP [%s]",
  2106. srchost, dsthost, tflags,
  2107. (unsigned long) ntohl(tcp->th_ack), (unsigned short) ntohs(tcp->th_win),
  2108. tcpoptinfo, ipinfo);
  2109. }
  2110. }
  2111. }
  2112. /* CASE 3: where the IP packet is not a fragment but for some reason, we
  2113. * don't have the entire TCP header, just part of it.*/
  2114. else if (datalen > 0 && datalen < 20) {
  2115. /* We only have the first 32 bits: source and dst port */
  2116. if (datalen >= 4 && datalen < 8) {
  2117. Snprintf(protoinfo, sizeof(protoinfo), "TCP %s:%hu > %s:%hu ?? (incomplete) %s",
  2118. srchost, (unsigned short) ntohs(tcp->th_sport), dsthost, (unsigned short) ntohs(tcp->th_dport), ipinfo);
  2119. }
  2120. /* We only have the first 64 bits: ports and seq number */
  2121. if (datalen >= 8 && datalen < 12) {
  2122. Snprintf(tcpinfo, sizeof(tcpinfo), "TCP %s:%hu > %s:%hu ?? seq=%lu (incomplete) %s",
  2123. srchost, (unsigned short) ntohs(tcp->th_sport), dsthost,
  2124. (unsigned short) ntohs(tcp->th_dport), (unsigned long) ntohl(tcp->th_seq), ipinfo);
  2125. }
  2126. /* We only have the first 96 bits: ports, seq and ack number */
  2127. if (datalen >= 12 && datalen < 16) {
  2128. if (detail == LOW_DETAIL) { /* We don't print ACK in low detail */
  2129. Snprintf(tcpinfo, sizeof(tcpinfo), "TCP %s:%hu > %s:%hu seq=%lu (incomplete), %s",
  2130. srchost, (unsigned short) ntohs(tcp->th_sport), dsthost,
  2131. (unsigned short) ntohs(tcp->th_dport), (unsigned long) ntohl(tcp->th_seq), ipinfo);
  2132. } else {
  2133. Snprintf(tcpinfo, sizeof(tcpinfo), "TCP [%s:%hu > %s:%hu seq=%lu ack=%lu (incomplete)] IP [%s]",
  2134. srchost, (unsigned short) ntohs(tcp->th_sport), dsthost,
  2135. (unsigned short) ntohs(tcp->th_dport), (unsigned long) ntohl(tcp->th_seq),
  2136. (unsigned long) ntohl(tcp->th_ack), ipinfo);
  2137. }
  2138. }
  2139. /* We are missing the last 32 bits (checksum and urgent pointer) */
  2140. if (datalen >= 16 && datalen < 20) {
  2141. p = tflags;
  2142. /* These are basically in tcpdump order */
  2143. if (tcp->th_flags & TH_SYN)
  2144. *p++ = 'S';
  2145. if (tcp->th_flags & TH_FIN)
  2146. *p++ = 'F';
  2147. if (tcp->th_flags & TH_RST)
  2148. *p++ = 'R';
  2149. if (tcp->th_flags & TH_PUSH)
  2150. *p++ = 'P';
  2151. if (tcp->th_flags & TH_ACK) {
  2152. *p++ = 'A';
  2153. Snprintf(buf, sizeof(buf), " ack=%lu",
  2154. (unsigned long) ntohl(tcp->th_ack));
  2155. strncat(tcpinfo, buf, sizeof(tcpinfo) - strlen(tcpinfo) - 1);
  2156. }
  2157. if (tcp->th_flags & TH_URG)
  2158. *p++ = 'U';
  2159. if (tcp->th_flags & TH_ECE)
  2160. *p++ = 'E'; /* rfc 2481/3168 */
  2161. if (tcp->th_flags & TH_CWR)
  2162. *p++ = 'C'; /* rfc 2481/3168 */
  2163. *p++ = '\0';
  2164. /* Create a string with TCP information relevant to the specified level of detail */
  2165. if (detail == LOW_DETAIL) { /* We don't print ACK in low detail */
  2166. Snprintf(protoinfo, sizeof(protoinfo), "TCP %s:%hu > %s:%hu %s %s seq=%lu win=%hu (incomplete)",
  2167. srchost, (unsigned short) ntohs(tcp->th_sport), dsthost, (unsigned short) ntohs(tcp->th_dport),
  2168. tflags, ipinfo, (unsigned long) ntohl(tcp->th_seq),
  2169. (unsigned short) ntohs(tcp->th_win));
  2170. } else if (detail == MEDIUM_DETAIL) {
  2171. Snprintf(protoinfo, sizeof(protoinfo), "TCP [%s:%hu > %s:%hu %s seq=%lu ack=%lu win=%hu (incomplete)] IP [%s]",
  2172. srchost, (unsigned short) ntohs(tcp->th_sport), dsthost, (unsigned short) ntohs(tcp->th_dport),
  2173. tflags, (unsigned long) ntohl(tcp->th_seq),
  2174. (unsigned long) ntohl(tcp->th_ack),
  2175. (unsigned short) ntohs(tcp->th_win), ipinfo);
  2176. } else if (detail == HIGH_DETAIL) {
  2177. Snprintf(protoinfo, sizeof(protoinfo), "TCP [%s:%hu > %s:%hu %s seq=%lu ack=%lu off=%d res=%d win=%hu (incomplete)] IP [%s]",
  2178. srchost, (unsigned short) ntohs(tcp->th_sport),
  2179. dsthost, (unsigned short) ntohs(tcp->th_dport),
  2180. tflags, (unsigned long) ntohl(tcp->th_seq),
  2181. (unsigned long) ntohl(tcp->th_ack),
  2182. (u8)tcp->th_off, (u8)tcp->th_x2, (unsigned short) ntohs(tcp->th_win),
  2183. ipinfo);
  2184. }
  2185. }
  2186. }
  2187. /* CASE 4: where we (finally!) have a full 20 byte TCP header so we can
  2188. * safely print all fields */
  2189. else if (datalen >= 20) {
  2190. /* TCP Flags */
  2191. p = tflags;
  2192. /* These are basically in tcpdump order */
  2193. if (tcp->th_flags & TH_SYN)
  2194. *p++ = 'S';
  2195. if (tcp->th_flags & TH_FIN)
  2196. *p++ = 'F';
  2197. if (tcp->th_flags & TH_RST)
  2198. *p++ = 'R';
  2199. if (tcp->th_flags & TH_PUSH)
  2200. *p++ = 'P';
  2201. if (tcp->th_flags & TH_ACK) {
  2202. *p++ = 'A';
  2203. Snprintf(buf, sizeof(buf), " ack=%lu",
  2204. (unsigned long) ntohl(tcp->th_ack));
  2205. strncat(tcpinfo, buf, sizeof(tcpinfo) - strlen(tcpinfo) - 1);
  2206. }
  2207. if (tcp->th_flags & TH_URG)
  2208. *p++ = 'U';
  2209. if (tcp->th_flags & TH_ECE)
  2210. *p++ = 'E'; /* rfc 2481/3168 */
  2211. if (tcp->th_flags & TH_CWR)
  2212. *p++ = 'C'; /* rfc 2481/3168 */
  2213. *p++ = '\0';
  2214. /* TCP Options */
  2215. if ((u32) tcp->th_off * 4 > sizeof(struct tcp_hdr)) {
  2216. if (datalen < (unsigned int) tcp->th_off * 4) {
  2217. Snprintf(tcpoptinfo, sizeof(tcpoptinfo), "option incomplete");
  2218. } else {
  2219. tcppacketoptinfo((u8*) tcp + sizeof(struct tcp_hdr),
  2220. tcp->th_off*4 - sizeof(struct tcp_hdr),
  2221. tcpoptinfo, sizeof(tcpoptinfo));
  2222. }
  2223. }
  2224. /* Rest of header fields */
  2225. if (detail == LOW_DETAIL) {
  2226. Snprintf(protoinfo, sizeof(protoinfo), "TCP %s:%hu > %s:%hu %s %s seq=%lu win=%hu %s",
  2227. srchost, (unsigned short) ntohs(tcp->th_sport), dsthost, (unsigned short) ntohs(tcp->th_dport),
  2228. tflags, ipinfo, (unsigned long) ntohl(tcp->th_seq),
  2229. (unsigned short) ntohs(tcp->th_win), tcpoptinfo);
  2230. } else if (detail == MEDIUM_DETAIL) {
  2231. Snprintf(protoinfo, sizeof(protoinfo), "TCP [%s:%hu > %s:%hu %s seq=%lu win=%hu csum=0x%04X%s%s] IP [%s]",
  2232. srchost, (unsigned short) ntohs(tcp->th_sport), dsthost, (unsigned short) ntohs(tcp->th_dport),
  2233. tflags, (unsigned long) ntohl(tcp->th_seq),
  2234. (unsigned short) ntohs(tcp->th_win), (unsigned short) ntohs(tcp->th_sum),
  2235. (tcpoptinfo[0]!='\0') ? " " : "",
  2236. tcpoptinfo, ipinfo);
  2237. } else if (detail == HIGH_DETAIL) {
  2238. Snprintf(protoinfo, sizeof(protoinfo), "TCP [%s:%hu > %s:%hu %s seq=%lu ack=%lu off=%d res=%d win=%hu csum=0x%04X urp=%hu%s%s] IP [%s]",
  2239. srchost, (unsigned short) ntohs(tcp->th_sport),
  2240. dsthost, (unsigned short) ntohs(tcp->th_dport),
  2241. tflags, (unsigned long) ntohl(tcp->th_seq),
  2242. (unsigned long) ntohl(tcp->th_ack),
  2243. (u8)tcp->th_off, (u8)tcp->th_x2, (unsigned short) ntohs(tcp->th_win),
  2244. ntohs(tcp->th_sum), (unsigned short) ntohs(tcp->th_urp),
  2245. (tcpoptinfo[0]!='\0') ? " " : "",
  2246. tcpoptinfo, ipinfo);
  2247. }
  2248. } else{
  2249. /* If the packet does not fall into any other category, then we have a
  2250. really screwed-up packet. */
  2251. Snprintf(protoinfo, sizeof(protoinfo), "TCP %s:?? > %s:?? ?? %s (invalid TCP)",
  2252. srchost, dsthost, ipinfo);
  2253. }
  2254. /* UDP INFORMATION ***********************************************************/
  2255. } else if (hdr.proto == IPPROTO_UDP && frag_off) {
  2256. Snprintf(protoinfo, sizeof(protoinfo), "UDP %s:?? > %s:?? fragment %s (incomplete)",
  2257. srchost, dsthost, ipinfo);
  2258. } else if (hdr.proto == IPPROTO_UDP) {
  2259. udp = (struct udp_hdr *) data;
  2260. /* TODO: See if we can segfault if we receive a fragmented packet whose IP packet does not say a thing about fragmentation */
  2261. if (detail == LOW_DETAIL) {
  2262. Snprintf(protoinfo, sizeof(protoinfo), "UDP %s:%hu > %s:%hu %s",
  2263. srchost, (unsigned short) ntohs(udp->uh_sport), dsthost, (unsigned short) ntohs(udp->uh_dport),
  2264. ipinfo);
  2265. } else if (detail == MEDIUM_DETAIL) {
  2266. Snprintf(protoinfo, sizeof(protoinfo), "UDP [%s:%hu > %s:%hu csum=0x%04X] IP [%s]",
  2267. srchost, (unsigned short) ntohs(udp->uh_sport), dsthost, (unsigned short) ntohs(udp->uh_dport), ntohs(udp->uh_sum),
  2268. ipinfo);
  2269. } else if (detail == HIGH_DETAIL) {
  2270. Snprintf(protoinfo, sizeof(protoinfo), "UDP [%s:%hu > %s:%hu len=%hu csum=0x%04X] IP [%s]",
  2271. srchost, (unsigned short) ntohs(udp->uh_sport), dsthost, (unsigned short) ntohs(udp->uh_dport),
  2272. (unsigned short) ntohs(udp->uh_ulen), ntohs(udp->uh_sum),
  2273. ipinfo);
  2274. }
  2275. /* SCTP INFORMATION **********************************************************/
  2276. } else if (hdr.proto == IPPROTO_SCTP && frag_off) {
  2277. Snprintf(protoinfo, sizeof(protoinfo), "SCTP %s:?? > %s:?? fragment %s (incomplete)",
  2278. srchost, dsthost, ipinfo);
  2279. } else if (hdr.proto == IPPROTO_SCTP) {
  2280. sctp = (struct sctp_hdr *) data;
  2281. if (detail == LOW_DETAIL) {
  2282. Snprintf(protoinfo, sizeof(protoinfo), "SCTP %s:%hu > %s:%hu %s",
  2283. srchost, (unsigned short) ntohs(sctp->sh_sport), dsthost, (unsigned short) ntohs(sctp->sh_dport),
  2284. ipinfo);
  2285. } else if (detail == MEDIUM_DETAIL) {
  2286. Snprintf(protoinfo, sizeof(protoinfo), "SCTP [%s:%hu > %s:%hu csum=0x%08x] IP [%s]",
  2287. srchost, (unsigned short) ntohs(sctp->sh_sport), dsthost, (unsigned short) ntohs(sctp->sh_dport), ntohl(sctp->sh_sum),
  2288. ipinfo);
  2289. } else if (detail == HIGH_DETAIL) {
  2290. Snprintf(protoinfo, sizeof(protoinfo), "SCTP [%s:%hu > %s:%hu vtag=%lu csum=0x%08x] IP [%s]",
  2291. srchost, (unsigned short) ntohs(sctp->sh_sport), dsthost, (unsigned short) ntohs(sctp->sh_dport),
  2292. (unsigned long) ntohl(sctp->sh_vtag), ntohl(sctp->sh_sum),
  2293. ipinfo);
  2294. }
  2295. /* ICMP INFORMATION **********************************************************/
  2296. } else if (hdr.proto == IPPROTO_ICMP && frag_off) {
  2297. Snprintf(protoinfo, sizeof(protoinfo), "ICMP %s > %s fragment %s (incomplete)",
  2298. srchost, dsthost, ipinfo);
  2299. } else if (hdr.proto == IPPROTO_ICMP) {
  2300. struct ip *ip2; /* Points to the IP datagram carried by some ICMP messages */
  2301. char *ip2dst; /* Dest IP in caried IP datagram */
  2302. u16 *nextmtu = NULL; /* Store next hop MTU when ICMP==Frag required */
  2303. char auxbuff[128]; /* Aux buffer */
  2304. struct icmp_packet{ /* Generic ICMP struct */
  2305. u8 type;
  2306. u8 code;
  2307. u16 checksum;
  2308. u8 data[128];
  2309. }*icmppkt;
  2310. struct ppkt { /* Beginning of ICMP Echo/Timestamp header */
  2311. u8 type;
  2312. u8 code;
  2313. u16 checksum;
  2314. u16 id;
  2315. u16 seq;
  2316. } *ping = NULL;
  2317. struct icmp_redir{
  2318. u8 type;
  2319. u8 code;
  2320. u16 checksum;
  2321. u32 addr;
  2322. } *icmpredir = NULL;
  2323. struct icmp_router{
  2324. u8 type;
  2325. u8 code;
  2326. u16 checksum;
  2327. u8 addrs;
  2328. u8 addrlen;
  2329. u16 lifetime;
  2330. } *icmprouter = NULL;
  2331. struct icmp_param{
  2332. u8 type;
  2333. u8 code;
  2334. u16 checksum;
  2335. u8 pnt;
  2336. u8 unused;
  2337. u16 unused2;
  2338. } *icmpparam = NULL;
  2339. struct icmp_tstamp{
  2340. u8 type;
  2341. u8 code;
  2342. u16 checksum;
  2343. u16 id;
  2344. u16 seq;
  2345. u32 orig;
  2346. u32 recv;
  2347. u32 trans;
  2348. } *icmptstamp = NULL;
  2349. struct icmp_amask{
  2350. u8 type;
  2351. u8 code;
  2352. u16 checksum;
  2353. u16 id;
  2354. u16 seq;
  2355. u32 mask;
  2356. } *icmpmask = NULL;
  2357. /* Compute the ICMP minimum length. */
  2358. unsigned pktlen = 8;
  2359. /* We need the ICMP packet to be at least 8 bytes long */
  2360. if (pktlen > datalen)
  2361. goto icmpbad;
  2362. ping = (struct ppkt *) data;
  2363. icmppkt = (struct icmp_packet *) data;
  2364. switch(icmppkt->type) {
  2365. /* Echo Reply **************************/
  2366. case 0:
  2367. strcpy(icmptype, "Echo reply");
  2368. Snprintf(icmpfields, sizeof(icmpfields), "id=%hu seq=%hu", (unsigned short) ntohs(ping->id), (unsigned short) ntohs(ping->seq));
  2369. break;
  2370. /* Destination Unreachable *************/
  2371. case 3:
  2372. /* Point to the start of the original datagram */
  2373. ip2 = (struct ip *) (data + 8);
  2374. /* Check we have a full IP datagram included in the ICMP message */
  2375. pktlen += MAX( (ip2->ip_hl * 4), 20);
  2376. if (pktlen > datalen) {
  2377. if (datalen == 8) {
  2378. Snprintf(icmptype, sizeof icmptype, "Destination unreachable%s",
  2379. (detail!=LOW_DETAIL)? " (original datagram missing)" : "");
  2380. } else {
  2381. Snprintf(icmptype, sizeof icmptype, "Destination unreachable%s",
  2382. (detail!=LOW_DETAIL)? " (part of original datagram missing)" : "");
  2383. }
  2384. goto icmpbad;
  2385. }
  2386. /* Basic check to ensure we have an IPv4 datagram attached */
  2387. /* TODO: We should actually check the datagram checksum to
  2388. * see if it validates becuase just checking the version number
  2389. * is not enough. On average, if we get random data 1 out of
  2390. * 16 (2^4bits) times we will have value 4. */
  2391. if ((ip2->ip_v != 4) || ((ip2->ip_hl * 4) < 20) || ((ip2->ip_hl * 4) > 60)) {
  2392. Snprintf(icmptype, sizeof icmptype, "Destination unreachable (bogus original datagram)");
  2393. goto icmpbad;
  2394. } else {
  2395. /* We have the original datagram + the first 8 bytes of the
  2396. * transport layer header */
  2397. if (pktlen + 8 < datalen) {
  2398. tcp = (struct tcp_hdr *) ((char *) ip2 + (ip2->ip_hl * 4));
  2399. udp = (struct udp_hdr *) ((char *) ip2 + (ip2->ip_hl * 4));
  2400. sctp = (struct sctp_hdr *) ((char *) ip2 + (ip2->ip_hl * 4));
  2401. }
  2402. }
  2403. /* Determine the IP the original datagram was sent to */
  2404. ip2dst = inet_ntoa(ip2->ip_dst);
  2405. /* Determine type of Destination unreachable from the code value */
  2406. switch (icmppkt->code) {
  2407. case 0:
  2408. Snprintf(icmptype, sizeof icmptype, "Network %s unreachable", ip2dst);
  2409. break;
  2410. case 1:
  2411. Snprintf(icmptype, sizeof icmptype, "Host %s unreachable", ip2dst);
  2412. break;
  2413. case 2:
  2414. Snprintf(icmptype, sizeof icmptype, "Protocol %u unreachable", ip2->ip_p);
  2415. break;
  2416. case 3:
  2417. if (pktlen + 8 < datalen) {
  2418. if (ip2->ip_p == IPPROTO_UDP && udp)
  2419. Snprintf(icmptype, sizeof icmptype, "Port %hu unreachable", (unsigned short) ntohs(udp->uh_dport));
  2420. else if (ip2->ip_p == IPPROTO_TCP && tcp)
  2421. Snprintf(icmptype, sizeof icmptype, "Port %hu unreachable", (unsigned short) ntohs(tcp->th_dport));
  2422. else if (ip2->ip_p == IPPROTO_SCTP && sctp)
  2423. Snprintf(icmptype, sizeof icmptype, "Port %hu unreachable", (unsigned short) ntohs(sctp->sh_dport));
  2424. else
  2425. Snprintf(icmptype, sizeof icmptype, "Port unreachable (unknown protocol %u)", ip2->ip_p);
  2426. }
  2427. else
  2428. strcpy(icmptype, "Port unreachable");
  2429. break;
  2430. case 4:
  2431. strcpy(icmptype, "Fragmentation required");
  2432. nextmtu = (u16 *)(&(icmppkt->data[6]));
  2433. Snprintf(icmpfields, sizeof(icmpfields), "Next-Hop-MTU=%hu", (unsigned short) ntohs(*nextmtu));
  2434. break;
  2435. case 5:
  2436. strcpy(icmptype, "Source route failed");
  2437. break;
  2438. case 6:
  2439. Snprintf(icmptype, sizeof icmptype, "Destination network %s unknown", ip2dst);
  2440. break;
  2441. case 7:
  2442. Snprintf(icmptype, sizeof icmptype, "Destination host %s unknown", ip2dst);
  2443. break;
  2444. case 8:
  2445. strcpy(icmptype, "Source host isolated");
  2446. break;
  2447. case 9:
  2448. Snprintf(icmptype, sizeof icmptype, "Destination network %s administratively prohibited", ip2dst);
  2449. break;
  2450. case 10:
  2451. Snprintf(icmptype, sizeof icmptype, "Destination host %s administratively prohibited", ip2dst);
  2452. break;
  2453. case 11:
  2454. Snprintf(icmptype, sizeof icmptype, "Network %s unreachable for TOS", ip2dst);
  2455. break;
  2456. case 12:
  2457. Snprintf(icmptype, sizeof icmptype, "Host %s unreachable for TOS", ip2dst);
  2458. break;
  2459. case 13:
  2460. strcpy(icmptype, "Communication administratively prohibited by filtering");
  2461. break;
  2462. case 14:
  2463. strcpy(icmptype, "Host precedence violation");
  2464. break;
  2465. case 15:
  2466. strcpy(icmptype, "Precedence cutoff in effect");
  2467. break;
  2468. default:
  2469. strcpy(icmptype, "Destination unreachable (unknown code)");
  2470. break;
  2471. } /* End of ICMP Code switch */
  2472. break;
  2473. /* Source Quench ***********************/
  2474. case 4:
  2475. strcpy(icmptype, "Source quench");
  2476. break;
  2477. /* Redirect ****************************/
  2478. case 5:
  2479. if (ping->code == 0)
  2480. strcpy(icmptype, "Network redirect");
  2481. else if (ping->code == 1)
  2482. strcpy(icmptype, "Host redirect");
  2483. else
  2484. strcpy(icmptype, "Redirect (unknown code)");
  2485. icmpredir = (struct icmp_redir *) icmppkt;
  2486. inet_ntop(AF_INET, &icmpredir->addr, auxbuff, sizeof(auxbuff));
  2487. Snprintf(icmpfields, sizeof(icmpfields), "addr=%s", auxbuff);
  2488. break;
  2489. /* Echo Request ************************/
  2490. case 8:
  2491. strcpy(icmptype, "Echo request");
  2492. Snprintf(icmpfields, sizeof(icmpfields), "id=%hu seq=%hu", (unsigned short) ntohs(ping->id), (unsigned short) ntohs(ping->seq));
  2493. break;
  2494. /* Router Advertisement ****************/
  2495. case 9:
  2496. if (icmppkt->code == 16)
  2497. strcpy(icmptype, "Router advertisement (Mobile Agent Only)");
  2498. else
  2499. strcpy(icmptype, "Router advertisement");
  2500. icmprouter = (struct icmp_router *) icmppkt;
  2501. Snprintf(icmpfields, sizeof(icmpfields), "addrs=%u addrlen=%u lifetime=%hu",
  2502. icmprouter->addrs,
  2503. icmprouter->addrlen,
  2504. (unsigned short) ntohs(icmprouter->lifetime));
  2505. break;
  2506. /* Router Solicitation *****************/
  2507. case 10:
  2508. strcpy(icmptype, "Router solicitation");
  2509. break;
  2510. /* Time Exceeded ***********************/
  2511. case 11:
  2512. if (icmppkt->code == 0)
  2513. strcpy(icmptype, "TTL=0 during transit");
  2514. else if (icmppkt->code == 1)
  2515. strcpy(icmptype, "TTL=0 during reassembly");
  2516. else
  2517. strcpy(icmptype, "TTL exceeded (unknown code)");
  2518. break;
  2519. /* Parameter Problem *******************/
  2520. case 12:
  2521. if (ping->code == 0)
  2522. strcpy(icmptype, "Parameter problem (pointer indicates error)");
  2523. else if (ping->code == 1)
  2524. strcpy(icmptype, "Parameter problem (option missing)");
  2525. else if (ping->code == 2)
  2526. strcpy(icmptype, "Parameter problem (bad length)");
  2527. else
  2528. strcpy(icmptype, "Parameter problem (unknown code)");
  2529. icmpparam = (struct icmp_param *) icmppkt;
  2530. Snprintf(icmpfields, sizeof(icmpfields), "pointer=%d", icmpparam->pnt);
  2531. break;
  2532. /* Timestamp Request/Reply *************/
  2533. case 13:
  2534. case 14:
  2535. Snprintf(icmptype, sizeof(icmptype), "Timestamp %s", (icmppkt->type == 13)? "request" : "reply");
  2536. icmptstamp = (struct icmp_tstamp *) icmppkt;
  2537. Snprintf(icmpfields, sizeof(icmpfields), "id=%hu seq=%hu orig=%lu recv=%lu trans=%lu",
  2538. (unsigned short) ntohs(icmptstamp->id), (unsigned short) ntohs(icmptstamp->seq),
  2539. (unsigned long) ntohl(icmptstamp->orig),
  2540. (unsigned long) ntohl(icmptstamp->recv),
  2541. (unsigned long) ntohl(icmptstamp->trans));
  2542. break;
  2543. /* Information Request *****************/
  2544. case 15:
  2545. strcpy(icmptype, "Information request");
  2546. Snprintf(icmpfields, sizeof(icmpfields), "id=%hu seq=%hu", (unsigned short) ntohs(ping->id), (unsigned short) ntohs(ping->seq));
  2547. break;
  2548. /* Information Reply *******************/
  2549. case 16:
  2550. strcpy(icmptype, "Information reply");
  2551. Snprintf(icmpfields, sizeof(icmpfields), "id=%hu seq=%hu", (unsigned short) ntohs(ping->id), (unsigned short) ntohs(ping->seq));
  2552. break;
  2553. /* Netmask Request/Reply ***************/
  2554. case 17:
  2555. case 18:
  2556. Snprintf(icmptype, sizeof(icmptype), "Address mask %s", (icmppkt->type == 17)? "request" : "reply");
  2557. icmpmask = (struct icmp_amask *) icmppkt;
  2558. inet_ntop(AF_INET, &icmpmask->mask, auxbuff, sizeof(auxbuff));
  2559. Snprintf(icmpfields, sizeof(icmpfields), "id=%u seq=%u mask=%s",
  2560. (unsigned short) ntohs(ping->id), (unsigned short) ntohs(ping->seq), auxbuff);
  2561. break;
  2562. /* Traceroute **************************/
  2563. case 30:
  2564. strcpy(icmptype, "Traceroute");
  2565. break;
  2566. /* Domain Name Request *****************/
  2567. case 37:
  2568. strcpy(icmptype, "Domain name request");
  2569. break;
  2570. /* Domain Name Reply *******************/
  2571. case 38:
  2572. strcpy(icmptype, "Domain name reply");
  2573. break;
  2574. /* Security ****************************/
  2575. case 40:
  2576. strcpy(icmptype, "Security failures"); /* rfc 2521 */
  2577. break;
  2578. default:
  2579. strcpy(icmptype, "Unknown type"); break;
  2580. break;
  2581. } /* End of ICMP Type switch */
  2582. if (pktlen > datalen) {
  2583. icmpbad:
  2584. if (ping) {
  2585. /* We still have this information */
  2586. Snprintf(protoinfo, sizeof(protoinfo), "ICMP %s > %s %s (type=%d/code=%d) %s",
  2587. srchost, dsthost, icmptype, ping->type, ping->code, ipinfo);
  2588. } else {
  2589. Snprintf(protoinfo, sizeof(protoinfo), "ICMP %s > %s [??] %s",
  2590. srchost, dsthost, ipinfo);
  2591. }
  2592. } else {
  2593. if (ping)
  2594. sprintf(icmpinfo,"type=%d/code=%d", ping->type, ping->code);
  2595. else
  2596. strncpy(icmpinfo,"type=?/code=?", sizeof(icmpinfo));
  2597. Snprintf(protoinfo, sizeof(protoinfo), "ICMP [%s > %s %s (%s) %s] IP [%s]",
  2598. srchost, dsthost, icmptype, icmpinfo, icmpfields, ipinfo);
  2599. }
  2600. /* UNKNOWN PROTOCOL **********************************************************/
  2601. } else if (hdr.proto == IPPROTO_ICMPV6) {
  2602. const struct icmpv6_hdr *icmpv6;
  2603. icmpv6 = (struct icmpv6_hdr *) data;
  2604. Snprintf(protoinfo, sizeof(protoinfo), "ICMPv6 (%d) %s > %s (type=%d/code=%d) %s",
  2605. hdr.proto, srchost, dsthost,
  2606. icmpv6->icmpv6_type, icmpv6->icmpv6_code, ipinfo);
  2607. } else {
  2608. const char *hdrstr;
  2609. hdrstr = nexthdrtoa(hdr.proto, 1);
  2610. if (hdrstr == NULL || *hdrstr == '\0') {
  2611. Snprintf(protoinfo, sizeof(protoinfo), "Unknown protocol (%d) %s > %s: %s",
  2612. hdr.proto, srchost, dsthost, ipinfo);
  2613. } else {
  2614. Snprintf(protoinfo, sizeof(protoinfo), "%s (%d) %s > %s: %s",
  2615. hdrstr, hdr.proto, srchost, dsthost, ipinfo);
  2616. }
  2617. }
  2618. return protoinfo;
  2619. }
  2620. #ifdef HAVE_LINUX_RTNETLINK_H
  2621. /* Fill in a sockaddr_storage given an address family and raw address. */
  2622. static int set_sockaddr(struct sockaddr_storage *ss, int af, void *data) {
  2623. struct sockaddr_in *sin;
  2624. struct sockaddr_in6 *sin6;
  2625. ss->ss_family = af;
  2626. if (af == AF_INET) {
  2627. sin = (struct sockaddr_in *) ss;
  2628. memcpy(&sin->sin_addr.s_addr, data, IP_ADDR_LEN);
  2629. } else if (af == AF_INET6) {
  2630. sin6 = (struct sockaddr_in6 *) ss;
  2631. memcpy(sin6->sin6_addr.s6_addr, data, IP6_ADDR_LEN);
  2632. } else {
  2633. return -1;
  2634. }
  2635. return 0;
  2636. }
  2637. /* Add rtattrs to a netlink message specifying a source or destination address.
  2638. rta_type must be RTA_SRC or RTA_DST. This function adds either 1 or 2
  2639. rtattrs: it always adds either an RTA_SRC or RTA_DST, depending on rta_type.
  2640. If ifindex is not 0, it is the index of the interface to use. The function
  2641. adds either RTA_OIF if rta_type is RTA_DST, and either of ifindex and
  2642. sin6_scope_id is nonzero. */
  2643. static void add_rtattr_addr(struct nlmsghdr *nlmsg,
  2644. struct rtattr **rtattr, unsigned int *len,
  2645. unsigned char rta_type,
  2646. const struct sockaddr_storage *ss,
  2647. int ifindex) {
  2648. struct rtmsg *rtmsg;
  2649. const void *addr;
  2650. size_t addrlen;
  2651. assert(rta_type == RTA_SRC || rta_type == RTA_DST);
  2652. if (rta_type == RTA_SRC) {
  2653. /* Ignore the interface specification if we are setting an RTA_SRC attribute
  2654. (it may still get set by the scope_id below). */
  2655. ifindex = 0;
  2656. }
  2657. if (ss->ss_family == AF_INET) {
  2658. addr = &((struct sockaddr_in *) ss)->sin_addr.s_addr;
  2659. addrlen = IP_ADDR_LEN;
  2660. } else if (ss->ss_family == AF_INET6) {
  2661. const struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *) ss;
  2662. addr = sin6->sin6_addr.s6_addr;
  2663. addrlen = IP6_ADDR_LEN;
  2664. if (ifindex == 0)
  2665. ifindex = sin6->sin6_scope_id;
  2666. } else {
  2667. netutil_fatal("%s: unknown address family %d", __func__, ss->ss_family);
  2668. }
  2669. rtmsg = (struct rtmsg *) (nlmsg + 1);
  2670. if (rta_type == RTA_SRC)
  2671. rtmsg->rtm_src_len = addrlen * 8;
  2672. else
  2673. rtmsg->rtm_dst_len = addrlen * 8;
  2674. /* Add an rtattr for the address. */
  2675. (*rtattr)->rta_type = rta_type;
  2676. (*rtattr)->rta_len = RTA_LENGTH(addrlen);
  2677. assert(RTA_OK(*rtattr, *len));
  2678. memcpy(RTA_DATA(*rtattr), addr, addrlen);
  2679. nlmsg->nlmsg_len = NLMSG_ALIGN(nlmsg->nlmsg_len) + (*rtattr)->rta_len;
  2680. *rtattr = RTA_NEXT(*rtattr, *len);
  2681. /* Specific interface (sin6_scope_id) requested? */
  2682. if (ifindex > 0) {
  2683. /* Add an rtattr for the interface. */
  2684. if (rta_type == RTA_SRC)
  2685. (*rtattr)->rta_type = RTA_IIF;
  2686. else
  2687. (*rtattr)->rta_type = RTA_OIF;
  2688. (*rtattr)->rta_len = RTA_LENGTH(sizeof(uint32_t));
  2689. assert(RTA_OK(*rtattr, *len));
  2690. *(uint32_t *) RTA_DATA(*rtattr) = ifindex;
  2691. nlmsg->nlmsg_len = NLMSG_ALIGN(nlmsg->nlmsg_len) + (*rtattr)->rta_len;
  2692. *rtattr = RTA_NEXT(*rtattr, *len);
  2693. }
  2694. }
  2695. /* Does route_dst using the Linux-specific rtnetlink interface. See rtnetlink(3)
  2696. and rtnetlink(7). */
  2697. static int route_dst_netlink(const struct sockaddr_storage *dst,
  2698. struct route_nfo *rnfo, const char *device,
  2699. const struct sockaddr_storage *spoofss) {
  2700. struct sockaddr_nl snl;
  2701. struct msghdr msg;
  2702. struct iovec iov;
  2703. struct nlmsghdr *nlmsg;
  2704. struct rtmsg *rtmsg;
  2705. struct rtattr *rtattr;
  2706. int intf_index;
  2707. unsigned char buf[512];
  2708. unsigned int len;
  2709. int fd, rc;
  2710. fd = socket(AF_NETLINK, SOCK_RAW, NETLINK_ROUTE);
  2711. if (fd == -1)
  2712. netutil_fatal("%s: cannot create AF_NETLINK socket: %s", __func__, strerror(errno));
  2713. memset(&snl, 0, sizeof(snl));
  2714. snl.nl_family = AF_NETLINK;
  2715. rc = bind(fd, (struct sockaddr *) &snl, sizeof(snl));
  2716. if (rc == -1)
  2717. netutil_fatal("%s: cannot bind AF_NETLINK socket: %s", __func__, strerror(errno));
  2718. struct interface_info *ii;
  2719. ii = NULL;
  2720. intf_index = 0;
  2721. if (device != NULL && device[0] != '\0') {
  2722. ii = getInterfaceByName(device, dst->ss_family);
  2723. if (ii == NULL)
  2724. netutil_fatal("Could not find interface %s which was specified by -e", device);
  2725. intf_index = ii->ifindex;
  2726. }
  2727. memset(buf, 0, sizeof(buf));
  2728. nlmsg = (struct nlmsghdr *) buf;
  2729. nlmsg->nlmsg_len = NLMSG_LENGTH(sizeof(*rtmsg));
  2730. assert(nlmsg->nlmsg_len <= sizeof(buf));
  2731. nlmsg->nlmsg_flags = NLM_F_REQUEST;
  2732. nlmsg->nlmsg_type = RTM_GETROUTE;
  2733. rtmsg = (struct rtmsg *) (nlmsg + 1);
  2734. rtmsg->rtm_family = dst->ss_family;
  2735. rtattr = RTM_RTA(rtmsg);
  2736. len = sizeof(buf) - ((unsigned char *) RTM_RTA(rtmsg) - buf);
  2737. /* Add rtattrs for destination address and interface. */
  2738. add_rtattr_addr(nlmsg, &rtattr, &len, RTA_DST, dst, intf_index);
  2739. if (spoofss != NULL) {
  2740. /* Add rtattrs for source address and interface. */
  2741. add_rtattr_addr(nlmsg, &rtattr, &len, RTA_SRC, spoofss, intf_index);
  2742. }
  2743. iov.iov_base = nlmsg;
  2744. iov.iov_len = nlmsg->nlmsg_len;
  2745. memset(&msg, 0, sizeof(msg));
  2746. msg.msg_name = &snl;
  2747. msg.msg_namelen = sizeof(snl);
  2748. msg.msg_iov = &iov;
  2749. msg.msg_iovlen = 1;
  2750. rc = sendmsg(fd, &msg, 0);
  2751. if (rc == -1)
  2752. netutil_fatal("%s: cannot sendmsg: %s", __func__, strerror(errno));
  2753. iov.iov_base = buf;
  2754. iov.iov_len = sizeof(buf);
  2755. len = recvmsg(fd, &msg, 0);
  2756. if (len <= 0)
  2757. netutil_fatal("%s: cannot recvmsg: %s", __func__, strerror(errno));
  2758. close(fd);
  2759. if (nlmsg->nlmsg_len < sizeof(*nlmsg) || (unsigned int) len < NLMSG_LENGTH(sizeof(*nlmsg)))
  2760. netutil_fatal("%s: wrong size reply in recvmsg", __func__);
  2761. len -= NLMSG_LENGTH(sizeof(*nlmsg));
  2762. /* See rtnetlink(7). Anything matching this route is actually unroutable. */
  2763. if (rtmsg->rtm_type == RTN_UNREACHABLE)
  2764. return 0;
  2765. /* Default values to be possibly overridden. */
  2766. rnfo->direct_connect = 1;
  2767. rnfo->nexthop.ss_family = AF_UNSPEC;
  2768. rnfo->srcaddr.ss_family = AF_UNSPEC;
  2769. if (spoofss != NULL)
  2770. rnfo->srcaddr = *spoofss;
  2771. for (rtattr = RTM_RTA(rtmsg); RTA_OK(rtattr, len); rtattr = RTA_NEXT(rtattr, len)) {
  2772. if (rtattr->rta_type == RTA_GATEWAY) {
  2773. rc = set_sockaddr(&rnfo->nexthop, dst->ss_family, RTA_DATA(rtattr));
  2774. assert(rc != -1);
  2775. /* Don't consider it directly connected if nexthop != dst. */
  2776. if (!sockaddr_storage_equal(dst, &rnfo->nexthop))
  2777. rnfo->direct_connect = 0;
  2778. } else if (rtattr->rta_type == RTA_OIF && ii == NULL) {
  2779. char namebuf[IFNAMSIZ];
  2780. char *p;
  2781. int intf_index;
  2782. intf_index = *(int *) RTA_DATA(rtattr);
  2783. p = if_indextoname(intf_index, namebuf);
  2784. assert(p != NULL);
  2785. ii = getInterfaceByName(namebuf, dst->ss_family);
  2786. if (ii == NULL)
  2787. ii = getInterfaceByName(namebuf, AF_UNSPEC);
  2788. if (ii == NULL)
  2789. netutil_fatal("%s: can't find interface \"%s\"", __func__, namebuf);
  2790. } else if (rtattr->rta_type == RTA_PREFSRC && rnfo->srcaddr.ss_family == AF_UNSPEC) {
  2791. rc = set_sockaddr(&rnfo->srcaddr, dst->ss_family, RTA_DATA(rtattr));
  2792. assert(rc != -1);
  2793. }
  2794. }
  2795. if (ii != NULL) {
  2796. rnfo->ii = *ii;
  2797. return 1;
  2798. } else {
  2799. return 0;
  2800. }
  2801. }
  2802. #else
  2803. static struct interface_info *find_loopback_iface(struct interface_info *ifaces,
  2804. int numifaces) {
  2805. int i;
  2806. for (i = 0; i < numifaces; i++) {
  2807. if (ifaces[i].device_type == devt_loopback)
  2808. return &ifaces[i];
  2809. }
  2810. return NULL;
  2811. }
  2812. /* Get the source address for routing to dst by creating a socket and asking the
  2813. operating system for the local address. */
  2814. static int get_srcaddr(const struct sockaddr_storage *dst,
  2815. struct sockaddr_storage *src)
  2816. {
  2817. static const unsigned short DUMMY_PORT = 1234;
  2818. struct sockaddr_storage dst_dummy;
  2819. size_t dst_dummy_len;
  2820. socklen_t len;
  2821. int fd, rc;
  2822. fd = socket(dst->ss_family, SOCK_DGRAM, 0);
  2823. if (fd == -1)
  2824. netutil_fatal("%s: can't create socket: %s", __func__, socket_strerror(socket_errno()));
  2825. dst_dummy = *dst;
  2826. if (dst_dummy.ss_family == AF_INET) {
  2827. struct sockaddr_in *sin = (struct sockaddr_in *) &dst_dummy;
  2828. sin->sin_port = htons(DUMMY_PORT);
  2829. dst_dummy_len = sizeof(*sin);
  2830. } else if (dst_dummy.ss_family == AF_INET6) {
  2831. struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *) &dst_dummy;
  2832. sin6->sin6_port = htons(DUMMY_PORT);
  2833. dst_dummy_len = sizeof(*sin6);
  2834. } else {
  2835. goto bail;
  2836. }
  2837. rc = connect(fd, (struct sockaddr *) &dst_dummy, dst_dummy_len);
  2838. if (rc == -1) {
  2839. netutil_error("%s: can't connect socket: %s", __func__, socket_strerror(socket_errno()));
  2840. if (dst->ss_family == AF_INET6) {
  2841. struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *) &dst_dummy;
  2842. if (sin6->sin6_scope_id == 0)
  2843. netutil_error("Do you need an IPv6 zone ID suffix (e.g. %%eth0 or %%1)?");
  2844. }
  2845. goto bail;
  2846. }
  2847. len = sizeof(*src);
  2848. rc = getsockname(fd, (struct sockaddr *) src, &len);
  2849. if (rc == -1)
  2850. netutil_fatal("%s: can't getsockname: %s", __func__, socket_strerror(socket_errno()));
  2851. close(fd);
  2852. return 0;
  2853. bail:
  2854. close(fd);
  2855. return -1;
  2856. }
  2857. static char *lookup_ifindex(unsigned int index, int af, char *namebuf, size_t len) {
  2858. intf_t *it;
  2859. struct intf_entry entry;
  2860. int rc;
  2861. it = intf_open();
  2862. assert(it != NULL);
  2863. entry.intf_len = sizeof(entry);
  2864. rc = intf_get_index(it, &entry, af, index);
  2865. intf_close(it);
  2866. if (rc == -1)
  2867. return NULL;
  2868. Strncpy(namebuf, entry.intf_name, len);
  2869. return namebuf;
  2870. }
  2871. static int route_dst_generic(const struct sockaddr_storage *dst,
  2872. struct route_nfo *rnfo, const char *device,
  2873. const struct sockaddr_storage *spoofss) {
  2874. struct interface_info *ifaces;
  2875. struct interface_info *iface;
  2876. int numifaces = 0;
  2877. struct sys_route *routes;
  2878. int numroutes = 0;
  2879. int i;
  2880. char namebuf[32];
  2881. char errstr[256];
  2882. errstr[0]='\0';
  2883. if (!dst)
  2884. netutil_fatal("%s passed a NULL dst address", __func__);
  2885. if(spoofss!=NULL){
  2886. /* Throughout the rest of this function we only change rnfo->srcaddr if the source isnt spoofed */
  2887. memcpy(&rnfo->srcaddr, spoofss, sizeof(rnfo->srcaddr));
  2888. /* The device corresponding to this spoofed address should already have been set elsewhere. */
  2889. assert(device!=NULL && device[0]!='\0');
  2890. }
  2891. if (device == NULL || device[0] == '\0') {
  2892. /* Check if there is an interface scope on the address which we must use. */
  2893. if (dst->ss_family == AF_INET6) {
  2894. const struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *) dst;
  2895. if (sin6->sin6_scope_id > 0) {
  2896. device = lookup_ifindex(sin6->sin6_scope_id, sin6->sin6_family, namebuf, sizeof(namebuf));
  2897. if (device == NULL) {
  2898. netutil_error("Could not find interface with index %u", (unsigned int) sin6->sin6_scope_id);
  2899. return 0;
  2900. }
  2901. }
  2902. }
  2903. }
  2904. if (device!=NULL && device[0]!='\0'){
  2905. iface = getInterfaceByName(device, dst->ss_family);
  2906. if (!iface)
  2907. netutil_fatal("Could not find interface %s", device);
  2908. } else {
  2909. iface = NULL;
  2910. }
  2911. if((routes=getsysroutes(&numroutes, errstr, sizeof(errstr)))==NULL)
  2912. netutil_fatal("%s: Failed to obtain system routes: %s", __func__, errstr);
  2913. if((ifaces=getinterfaces(&numifaces, errstr, sizeof(errstr)))==NULL)
  2914. netutil_fatal("%s: Failed to obtain system interfaces: %s", __func__, errstr);
  2915. /* First check if dst is one of the localhost's own addresses. We need to use
  2916. a localhost device for these. */
  2917. for (i = 0; i < numifaces; i++) {
  2918. struct interface_info *loopback;
  2919. if (!sockaddr_equal(dst, &ifaces[i].addr))
  2920. continue;
  2921. if (ifaces[i].device_type == devt_loopback)
  2922. loopback = &ifaces[i];
  2923. else
  2924. loopback = find_loopback_iface(ifaces, numifaces);
  2925. if (loopback == NULL)
  2926. /* Hmmm ... no localhost -- move on to the routing table. */
  2927. break;
  2928. if (iface != NULL && strcmp(loopback->devname, iface->devname) != 0)
  2929. continue;
  2930. if (iface == NULL && !loopback->device_up)
  2931. continue;
  2932. rnfo->ii = *loopback;
  2933. rnfo->direct_connect = 1;
  2934. /* But the source address we want to use is the target address. */
  2935. if (!spoofss) {
  2936. if (get_srcaddr(dst, &rnfo->srcaddr) == -1)
  2937. rnfo->srcaddr = rnfo->ii.addr;
  2938. }
  2939. return 1;
  2940. }
  2941. /* Go through the routing table and take the first match. getsysroutes sorts
  2942. so more-specific routes come first. */
  2943. for (i = 0; i < numroutes; i++) {
  2944. if (!sockaddr_equal_netmask(dst, &routes[i].dest, routes[i].netmask_bits))
  2945. continue;
  2946. /* Ignore routes that aren't on the device we specified. */
  2947. if (iface != NULL && strcmp(routes[i].device->devname, iface->devname) != 0)
  2948. continue;
  2949. if (iface == NULL && !routes[i].device->device_up)
  2950. continue;
  2951. rnfo->ii = *routes[i].device;
  2952. /* At this point we don't whether this route is direct or indirect ("G" flag
  2953. in netstat). We guess that a route is direct when the gateway address is
  2954. 0.0.0.0 or ::, when it exactly matches the interface address, or when it
  2955. exactly matches the destination address. */
  2956. rnfo->direct_connect = (sockaddr_equal_zero(&routes[i].gw) ||
  2957. sockaddr_equal(&routes[i].gw, &routes[i].device->addr) ||
  2958. sockaddr_equal(&routes[i].gw, dst));
  2959. if (!spoofss) {
  2960. if (get_srcaddr(dst, &rnfo->srcaddr) == -1)
  2961. rnfo->srcaddr = rnfo->ii.addr;
  2962. }
  2963. rnfo->nexthop = routes[i].gw;
  2964. return 1;
  2965. }
  2966. /* No match on routes. Try interfaces directly. */
  2967. for (i = 0; i < numifaces; i++) {
  2968. if (!sockaddr_equal_netmask(dst, &ifaces[i].addr, ifaces[i].netmask_bits))
  2969. continue;
  2970. if (iface != NULL && strcmp(ifaces[i].devname, iface->devname) != 0)
  2971. continue;
  2972. if (iface == NULL && !ifaces[i].device_up)
  2973. continue;
  2974. rnfo->ii = ifaces[i];
  2975. rnfo->direct_connect = 1;
  2976. if (!spoofss) {
  2977. if (get_srcaddr(dst, &rnfo->srcaddr) == -1)
  2978. rnfo->srcaddr = rnfo->ii.addr;
  2979. }
  2980. return 1;
  2981. }
  2982. return 0;
  2983. }
  2984. #endif
  2985. /* Takes a destination address (dst) and tries to determine the
  2986. * source address and interface necessary to route to this address.
  2987. * If no route is found, 0 is returned and "rnfo" is undefined. If
  2988. * a route is found, 1 is returned and "rnfo" is filled in with all
  2989. * of the routing details. If the source address needs to be spoofed,
  2990. * it should be passed through "spoofss" (otherwise NULL should be
  2991. * specified), along with a suitable network device (parameter "device").
  2992. * Even if spoofss is NULL, if user specified a network device with -e,
  2993. * it should still be passed. Note that it's OK to pass either NULL or
  2994. * an empty string as the "device", as long as spoofss==NULL. */
  2995. int route_dst(const struct sockaddr_storage *dst, struct route_nfo *rnfo,
  2996. const char *device, const struct sockaddr_storage *spoofss) {
  2997. #ifdef HAVE_LINUX_RTNETLINK_H
  2998. return route_dst_netlink(dst, rnfo, device, spoofss);
  2999. #else
  3000. return route_dst_generic(dst, rnfo, device, spoofss);
  3001. #endif
  3002. }
  3003. /* Wrapper for system function sendto(), which retries a few times when
  3004. * the call fails. It also prints informational messages about the
  3005. * errors encountered. It returns the number of bytes sent or -1 in
  3006. * case of error. */
  3007. int Sendto(const char *functionname, int sd,
  3008. const unsigned char *packet, int len, unsigned int flags,
  3009. struct sockaddr *to, int tolen) {
  3010. int res;
  3011. int retries = 0;
  3012. int sleeptime = 0;
  3013. static int numerrors = 0;
  3014. do {
  3015. if ((res = sendto(sd, (const char *) packet, len, flags, to, tolen)) == -1) {
  3016. int err = socket_errno();
  3017. numerrors++;
  3018. if(numerrors <= 10) {
  3019. netutil_error("sendto in %s: sendto(%d, packet, %d, 0, %s, %d) => %s",
  3020. functionname, sd, len, inet_ntop_ez((struct sockaddr_storage *) to, sizeof(struct sockaddr_storage)), tolen,
  3021. strerror(err));
  3022. netutil_error("Offending packet: %s", ippackethdrinfo(packet, len, LOW_DETAIL));
  3023. if (numerrors == 10) {
  3024. netutil_error("Omitting future %s error messages now that %d have been shown. Use -d2 if you really want to see them.", __func__, numerrors);
  3025. }
  3026. }
  3027. #if WIN32
  3028. return -1;
  3029. #else
  3030. if (retries > 2)
  3031. return -1;
  3032. /* For these enumerated errors, we sleep and try again. */
  3033. if (!(err == ENOBUFS || err == ENOMEM))
  3034. return -1;
  3035. sleeptime = 15 * (1 << (2 * retries));
  3036. netutil_error("Sleeping %d seconds then retrying", sleeptime);
  3037. fflush(stderr);
  3038. sleep(sleeptime);
  3039. #endif
  3040. }
  3041. retries++;
  3042. } while (res == -1);
  3043. return res;
  3044. }
  3045. /* Send an IP packet over an ethernet handle. */
  3046. int send_ip_packet_eth(const struct eth_nfo *eth, const u8 *packet, unsigned int packetlen) {
  3047. eth_t *ethsd;
  3048. u8 *eth_frame;
  3049. int res;
  3050. eth_frame = (u8 *) safe_malloc(14 + packetlen);
  3051. memcpy(eth_frame + 14, packet, packetlen);
  3052. eth_pack_hdr(eth_frame, eth->dstmac, eth->srcmac, ETH_TYPE_IP);
  3053. if (!eth->ethsd) {
  3054. ethsd = eth_open_cached(eth->devname);
  3055. if (!ethsd)
  3056. netutil_fatal("%s: Failed to open ethernet device (%s)", __func__, eth->devname);
  3057. } else {
  3058. ethsd = eth->ethsd;
  3059. }
  3060. res = eth_send(ethsd, eth_frame, 14 + packetlen);
  3061. /* No need to close ethsd due to caching */
  3062. free(eth_frame);
  3063. return res;
  3064. }
  3065. /* Send an IP packet over a raw socket. */
  3066. int send_ip_packet_sd(int sd, const struct sockaddr_in *dst,
  3067. const u8 *packet, unsigned int packetlen) {
  3068. struct sockaddr_in sock;
  3069. struct ip *ip = (struct ip *) packet;
  3070. struct tcp_hdr *tcp;
  3071. struct udp_hdr *udp;
  3072. int res;
  3073. assert(sd >= 0);
  3074. sock = *dst;
  3075. /* It is bogus that I need the address and port info when sending a RAW IP
  3076. packet, but it doesn't seem to work w/o them */
  3077. if (packetlen >= 20) {
  3078. if (ip->ip_p == IPPROTO_TCP
  3079. && packetlen >= (unsigned int) ip->ip_hl * 4 + 20) {
  3080. tcp = (struct tcp_hdr *) ((u8 *) ip + ip->ip_hl * 4);
  3081. sock.sin_port = tcp->th_dport;
  3082. } else if (ip->ip_p == IPPROTO_UDP
  3083. && packetlen >= (unsigned int) ip->ip_hl * 4 + 8) {
  3084. udp = (struct udp_hdr *) ((u8 *) ip + ip->ip_hl * 4);
  3085. sock.sin_port = udp->uh_dport;
  3086. }
  3087. }
  3088. /* Equally bogus is that the IP total len and IP fragment offset
  3089. fields need to be in host byte order on certain BSD variants. I
  3090. must deal with it here rather than when building the packet,
  3091. because they should be in NBO when I'm sending over raw
  3092. ethernet */
  3093. #if FREEBSD || BSDI || NETBSD || DEC || MACOSX
  3094. ip->ip_len = ntohs(ip->ip_len);
  3095. ip->ip_off = ntohs(ip->ip_off);
  3096. #endif
  3097. res = Sendto("send_ip_packet_sd", sd, packet, packetlen, 0,
  3098. (struct sockaddr *) &sock,
  3099. (int) sizeof(struct sockaddr_in));
  3100. /* Undo the byte order switching. */
  3101. #if FREEBSD || BSDI || NETBSD || DEC || MACOSX
  3102. ip->ip_len = htons(ip->ip_len);
  3103. ip->ip_off = htons(ip->ip_off);
  3104. #endif
  3105. return res;
  3106. }
  3107. /* Sends the supplied pre-built IPv4 packet. The packet is sent through
  3108. * the raw socket "sd" if "eth" is NULL. Otherwise, it gets sent at raw
  3109. * ethernet level. */
  3110. int send_ip_packet_eth_or_sd(int sd, const struct eth_nfo *eth,
  3111. const struct sockaddr_in *dst,
  3112. const u8 *packet, unsigned int packetlen) {
  3113. if(eth)
  3114. return send_ip_packet_eth(eth, packet, packetlen);
  3115. else
  3116. return send_ip_packet_sd(sd, dst, packet, packetlen);
  3117. }
  3118. /* Create and send all fragments of a pre-built IPv4 packet
  3119. * Minimal MTU for IPv4 is 68 and maximal IPv4 header size is 60
  3120. * which gives us a right to cut TCP header after 8th byte
  3121. * (shouldn't we inflate the header to 60 bytes too?) */
  3122. int send_frag_ip_packet(int sd, const struct eth_nfo *eth,
  3123. const struct sockaddr_in *dst,
  3124. const u8 *packet, unsigned int packetlen, u32 mtu) {
  3125. struct ip *ip = (struct ip *) packet;
  3126. int headerlen = ip->ip_hl * 4; // better than sizeof(struct ip)
  3127. u32 datalen = packetlen - headerlen;
  3128. int fdatalen = 0, res = 0;
  3129. int fragment=0;
  3130. assert(headerlen <= (int) packetlen);
  3131. assert(headerlen >= 20 && headerlen <= 60); // sanity check (RFC791)
  3132. assert(mtu > 0 && mtu % 8 == 0); // otherwise, we couldn't set Fragment offset (ip->ip_off) correctly
  3133. if (datalen <= mtu) {
  3134. netutil_error("Warning: fragmentation (mtu=%lu) requested but the payload is too small already (%lu)", (unsigned long)mtu, (unsigned long)datalen);
  3135. return send_ip_packet_eth_or_sd(sd, eth, dst, packet, packetlen);
  3136. }
  3137. u8 *fpacket = (u8 *) safe_malloc(headerlen + mtu);
  3138. memcpy(fpacket, packet, headerlen + mtu);
  3139. ip = (struct ip *) fpacket;
  3140. // create fragments and send them
  3141. for (fragment = 1; fragment * mtu < datalen + mtu; fragment++) {
  3142. fdatalen = (fragment * mtu <= datalen ? mtu : datalen % mtu);
  3143. ip->ip_len = htons(headerlen + fdatalen);
  3144. ip->ip_off = htons((fragment - 1) * mtu / 8);
  3145. if ((fragment - 1) * mtu + fdatalen < datalen)
  3146. ip->ip_off |= htons(IP_MF);
  3147. #if HAVE_IP_IP_SUM
  3148. ip->ip_sum = 0;
  3149. ip->ip_sum = in_cksum((unsigned short *) ip, headerlen);
  3150. #endif
  3151. if (fragment > 1) // copy data payload
  3152. memcpy(fpacket + headerlen,
  3153. packet + headerlen + (fragment - 1) * mtu, fdatalen);
  3154. res = send_ip_packet_eth_or_sd(sd, eth, dst, fpacket, ntohs(ip->ip_len));
  3155. if (res == -1)
  3156. break;
  3157. }
  3158. free(fpacket);
  3159. return res;
  3160. }
  3161. /* There are three ways to send a raw IPv6 packet.
  3162. send_ipv6_eth works when the device is Ethernet. (Unfortunately IPv6-in-IPv4
  3163. tunnels are not.) We can control all header fields and extension headers.
  3164. send_ipv6_ipproto_raw must be used when IPPROTO_RAW sockets include the IP
  3165. header, like IP_HDRINCL for IPv4. This is non-standard but is the case on
  3166. Linux. (On other platforms, IPPROTO_RAW has no special meaning and just
  3167. stands for protocol 255.) We can control all header fields and extension
  3168. headers. This method uses only one raw socket for all sends.
  3169. send_ipv6_ip must be used when IPPROTO_RAW sockets do not include the IP
  3170. header. Through standard function calls we can control all header fields
  3171. except for the flow label. This method needs one raw socket for every
  3172. protocol. (More precisely, one socket per distinct Next Header value.)
  3173. */
  3174. /* Send an IPv6 packet over an Ethernet handle. */
  3175. static int send_ipv6_eth(const struct eth_nfo *eth, const u8 *packet, unsigned int packetlen) {
  3176. eth_t *ethsd;
  3177. struct eth_hdr *eth_frame;
  3178. u8 *copy;
  3179. int res;
  3180. copy = (u8 *) safe_malloc(packetlen + sizeof(*eth_frame));
  3181. memcpy(copy + sizeof(*eth_frame), packet, packetlen);
  3182. eth_frame = (struct eth_hdr *) copy;
  3183. eth_pack_hdr(eth_frame, eth->dstmac, eth->srcmac, ETH_TYPE_IPV6);
  3184. if (!eth->ethsd) {
  3185. ethsd = eth_open_cached(eth->devname);
  3186. if (!ethsd)
  3187. netutil_fatal("%s: Failed to open ethernet device (%s)", __func__, eth->devname);
  3188. } else {
  3189. ethsd = eth->ethsd;
  3190. }
  3191. res = eth_send(ethsd, eth_frame, sizeof(*eth_frame) + packetlen);
  3192. /* No need to close ethsd due to caching */
  3193. free(eth_frame);
  3194. return res;
  3195. }
  3196. #if HAVE_IPV6_IPPROTO_RAW
  3197. /* Send an IPv6 packet over a raw socket, on platforms where IPPROTO_RAW implies
  3198. IP_HDRINCL-like behavior. */
  3199. static int send_ipv6_ipproto_raw(const struct sockaddr_in6 *dst,
  3200. const unsigned char *packet, unsigned int packetlen) {
  3201. int sd, n;
  3202. sd = -1;
  3203. n = -1;
  3204. sd = socket(AF_INET6, SOCK_RAW, IPPROTO_RAW);
  3205. if (sd == -1) {
  3206. perror("socket");
  3207. goto bail;
  3208. }
  3209. n = Sendto(__func__, sd, packet, packetlen, 0, (struct sockaddr *) dst, sizeof(*dst));
  3210. bail:
  3211. if (sd != -1)
  3212. close(sd);
  3213. return n;
  3214. }
  3215. #elif !WIN32
  3216. /* Add an ancillary cmsghdr data block to the list of blocks in a msghdr.
  3217. The list is stored in msg->msg_control, which is dynamically allocated
  3218. and reallocated as needed. It must be freed after this function returns.
  3219. msg->msg_controllen is also modified by this function. Returns -1 in case of
  3220. error or 0 otherwise. */
  3221. static int add_ancillary(struct msghdr *msg, int level, int type,
  3222. const void *data, size_t len)
  3223. {
  3224. struct cmsghdr *cm;
  3225. void *p;
  3226. p = realloc(msg->msg_control, msg->msg_controllen + CMSG_SPACE(len));
  3227. if (p == NULL)
  3228. return -1;
  3229. msg->msg_control = p;
  3230. cm = (struct cmsghdr *) ((char *) msg->msg_control + msg->msg_controllen);
  3231. msg->msg_controllen += CMSG_SPACE(len);
  3232. cm->cmsg_len = CMSG_LEN(len);
  3233. cm->cmsg_level = level;
  3234. cm->cmsg_type = type;
  3235. memcpy(CMSG_DATA(cm), data, len);
  3236. return 0;
  3237. }
  3238. static int exthdr_type_to_cmsg_type(uint8_t type) {
  3239. switch (type) {
  3240. /* These are the only extension headers we can set directly through a
  3241. msghdr. */
  3242. case 0:
  3243. return IPV6_HOPOPTS;
  3244. case 43:
  3245. return IPV6_RTHDR;
  3246. case 60:
  3247. return IPV6_DSTOPTS;
  3248. default:
  3249. return -1;
  3250. }
  3251. }
  3252. static const unsigned char *add_exthdr_ancillary(struct msghdr *msg,
  3253. const unsigned char *p, size_t len, unsigned char *proto) {
  3254. unsigned char nxt;
  3255. size_t extlen;
  3256. int cmsg_type;
  3257. cmsg_type = exthdr_type_to_cmsg_type(*proto);
  3258. if (cmsg_type == -1)
  3259. return NULL;
  3260. if (len < 2)
  3261. return NULL;
  3262. nxt = *p;
  3263. extlen = (*(p + 1) + 1) * 8;
  3264. if (len < extlen)
  3265. return NULL;
  3266. if (add_ancillary(msg, IPPROTO_IPV6, cmsg_type, p, extlen) == -1)
  3267. return NULL;
  3268. *proto = nxt;
  3269. return p + extlen;
  3270. }
  3271. /* Send an IPv6 packet over a raw socket. This function can control all header
  3272. fields except the flow label (and the payload length can only be controlled
  3273. indirectly through the length of the payload).
  3274. For most extension header types, we initialize the socket with the given
  3275. protocol, which causes the Next Header field to match when the packet is set.
  3276. This allows stuffing arbitrary data into extension headers. However, for a
  3277. few well-known headers (like Destination and Routing options), this fails
  3278. with EPROTOTYPE because there are specialized functions to add these headers
  3279. using the IPv6 socket API. These do not offer as much control because they
  3280. are controlled by the OS, and may be reordered, for example. */
  3281. static int send_ipv6_ip(const struct sockaddr_in6 *dst,
  3282. const unsigned char *packet, size_t packetlen) {
  3283. struct msghdr msg;
  3284. struct iovec iov;
  3285. const unsigned char *end;
  3286. struct ip6_hdr *hdr;
  3287. unsigned char nxt;
  3288. int tclass, hoplimit;
  3289. int sd;
  3290. int n;
  3291. sd = -1;
  3292. n = -1;
  3293. /* Set up sendmsg data structure. iov is filled in below. */
  3294. msg.msg_name = (void *) dst;
  3295. msg.msg_namelen = sizeof(*dst);
  3296. msg.msg_iov = &iov;
  3297. msg.msg_iovlen = 1;
  3298. msg.msg_control = NULL;
  3299. msg.msg_controllen = 0;
  3300. msg.msg_flags = 0;
  3301. if (packetlen < sizeof(*hdr))
  3302. return -1;
  3303. hdr = (struct ip6_hdr *) packet;
  3304. /* This can also be set with setsockopt(IPPROTO_IPV6, IPV6_TCLASS). */
  3305. #ifdef IPV6_TCLASS
  3306. tclass = ntohl(hdr->ip6_flow & IP6_FLOWINFO_MASK) >> 20;
  3307. if (add_ancillary(&msg, IPPROTO_IPV6,
  3308. IPV6_TCLASS, &tclass, sizeof(tclass)) == -1) {
  3309. goto bail;
  3310. }
  3311. #endif
  3312. /* This can also be set with setsockopt(IPPROTO_IPV6, IPV6_UNICAST_HOPS). */
  3313. hoplimit = hdr->ip6_hlim;
  3314. if (add_ancillary(&msg, IPPROTO_IPV6,
  3315. IPV6_HOPLIMIT, &hoplimit, sizeof(hoplimit)) == -1) {
  3316. goto bail;
  3317. }
  3318. /* The Next Header field is set when the socket is created. The payload
  3319. length is set in the call to sendmsg. There's no way to set the flow
  3320. label. */
  3321. /* We must loop until we find a nh value acceptable to the operating system
  3322. (one that can be passed as the third parameter to socket). In my tests on
  3323. OS X, you get EPROTOTYPE "Protocol wrong type for socket" for
  3324. 43 routing
  3325. 44 fragment
  3326. 50 ESP
  3327. 51 AH
  3328. 60 DSTOPT
  3329. 108 IPcomp
  3330. Some of these we are able to handle with ancillary data. When that's
  3331. possible, we skip over the header, add the ancillary data, and try again
  3332. with the next header. */
  3333. end = packet + packetlen;
  3334. packet += sizeof(*hdr);
  3335. nxt = hdr->ip6_nxt;
  3336. for (;;) {
  3337. errno = 0;
  3338. sd = socket(AF_INET6, SOCK_RAW, nxt);
  3339. if (!(sd == -1 && errno == EPROTOTYPE))
  3340. break;
  3341. packet = add_exthdr_ancillary(&msg, packet, end - packet, &nxt);
  3342. if (packet == NULL) {
  3343. netutil_error("Can't add extension header %u as ancillary data", nxt);
  3344. goto bail;
  3345. }
  3346. }
  3347. if (sd == -1) {
  3348. perror("socket");
  3349. goto bail;
  3350. }
  3351. assert(packet <= end);
  3352. iov.iov_base = (unsigned char *) packet;
  3353. iov.iov_len = end - packet;
  3354. n = sendmsg(sd, &msg, 0);
  3355. if (n == -1)
  3356. perror("sendmsg");
  3357. bail:
  3358. free(msg.msg_control);
  3359. if (sd != -1)
  3360. close(sd);
  3361. return n;
  3362. }
  3363. #endif
  3364. /* For now, the sd argument is ignored. */
  3365. int send_ipv6_packet_eth_or_sd(int sd, const struct eth_nfo *eth,
  3366. const struct sockaddr_in6 *dst, const u8 *packet, unsigned int packetlen) {
  3367. if (eth != NULL) {
  3368. return send_ipv6_eth(eth, packet, packetlen);
  3369. } else {
  3370. #if HAVE_IPV6_IPPROTO_RAW
  3371. return send_ipv6_ipproto_raw(dst, packet, packetlen);
  3372. #elif !WIN32
  3373. return send_ipv6_ip(dst, packet, packetlen);
  3374. #endif
  3375. }
  3376. return -1;
  3377. }
  3378. #ifdef WIN32
  3379. /* Convert a dnet interface name into the long pcap style. This also caches the
  3380. data to speed things up. Fills out pcapdev (up to pcapdevlen) and returns
  3381. true if it finds anything. Otherwise returns false. This is only necessary
  3382. on Windows. */
  3383. int DnetName2PcapName(const char *dnetdev, char *pcapdev, int pcapdevlen) {
  3384. static struct NameCorrelationCache {
  3385. char dnetd[64];
  3386. char pcapd[128];
  3387. } *NCC = NULL;
  3388. static int NCCsz = 0;
  3389. static int NCCcapacity = 0;
  3390. int i;
  3391. char tmpdev[128];
  3392. // Init the cache if not done yet
  3393. if (!NCC) {
  3394. NCCcapacity = 5;
  3395. NCC =
  3396. (struct NameCorrelationCache *) safe_zalloc(NCCcapacity *
  3397. sizeof(*NCC));
  3398. NCCsz = 0;
  3399. }
  3400. // First check if the name is already in the cache
  3401. for (i = 0; i < NCCsz; i++) {
  3402. if (strcmp(NCC[i].dnetd, dnetdev) == 0) {
  3403. Strncpy(pcapdev, NCC[i].pcapd, pcapdevlen);
  3404. return 1;
  3405. }
  3406. }
  3407. // OK, so it isn't in the cache. Let's ask dnet for it.
  3408. /* Converts a dnet interface name (ifname) to its pcap equivalent, which is stored in
  3409. pcapdev (up to a length of pcapdevlen). Returns 0 and fills in pcapdev if successful. */
  3410. if (eth_get_pcap_devname(dnetdev, tmpdev, sizeof(tmpdev)) != 0)
  3411. return 0;
  3412. // We've got it. Let's add it to the cache
  3413. if (NCCsz >= NCCcapacity) {
  3414. NCCcapacity <<= 2;
  3415. NCC =
  3416. (struct NameCorrelationCache *) safe_realloc(NCC,
  3417. NCCcapacity *
  3418. sizeof(*NCC));
  3419. }
  3420. Strncpy(NCC[NCCsz].dnetd, dnetdev, sizeof(NCC[0].dnetd));
  3421. Strncpy(NCC[NCCsz].pcapd, tmpdev, sizeof(NCC[0].pcapd));
  3422. NCCsz++;
  3423. Strncpy(pcapdev, tmpdev, pcapdevlen);
  3424. return 1;
  3425. }
  3426. #endif
  3427. /* Compute exponential sleep time for my_pcap_open_live(). Returned
  3428. * value is 5 to the times-th power (5^times) */
  3429. static unsigned int compute_sleep_time(unsigned int times){
  3430. unsigned int i=0;
  3431. unsigned int result=1;
  3432. for(i=0; i<times; i++)
  3433. result*=5;
  3434. return result;
  3435. }
  3436. /* This function is used to obtain a packet capture handle to look at
  3437. * packets on the network. It is actually a wrapper for libpcap's
  3438. * pcap_open_live() that takes care of compatibility issues and error
  3439. * checking. The function attempts to open the device up to three times.
  3440. * If the call does not succeed the third time, NULL is returned. */
  3441. pcap_t *my_pcap_open_live(const char *device, int snaplen, int promisc, int to_ms){
  3442. char err0r[PCAP_ERRBUF_SIZE];
  3443. pcap_t *pt;
  3444. char pcapdev[128];
  3445. unsigned int failed = 0;
  3446. assert(device != NULL);
  3447. #ifdef WIN32
  3448. /* Nmap normally uses device names obtained through dnet for interfaces, but
  3449. Pcap has its own naming system. So the conversion is done here */
  3450. if (!DnetName2PcapName(device, pcapdev, sizeof(pcapdev))) {
  3451. /* Oh crap -- couldn't find the corresponding dev apparently. Let's just go
  3452. with what we have then ... */
  3453. Strncpy(pcapdev, device, sizeof(pcapdev));
  3454. }
  3455. #else
  3456. Strncpy(pcapdev, device, sizeof(pcapdev));
  3457. #endif
  3458. do {
  3459. pt = pcap_open_live(pcapdev, snaplen, promisc, to_ms, err0r);
  3460. if (!pt) {
  3461. failed++;
  3462. if (failed >= 3) {
  3463. return NULL;
  3464. } else {
  3465. netutil_error("pcap_open_live(%s, %d, %d, %d) FAILED. Reported error: %s. Will wait %d seconds then retry.", pcapdev, snaplen, promisc, to_ms, err0r, compute_sleep_time(failed));
  3466. }
  3467. sleep( compute_sleep_time(failed) );
  3468. }
  3469. } while (!pt);
  3470. #ifdef WIN32
  3471. /* We want any responses back ASAP */
  3472. pcap_setmintocopy(pt, 1);
  3473. #endif
  3474. return pt;
  3475. }
  3476. /* Set a pcap filter */
  3477. void set_pcap_filter(const char *device, pcap_t *pd, const char *bpf, ...) {
  3478. va_list ap;
  3479. char buf[3072];
  3480. struct bpf_program fcode;
  3481. va_start(ap, bpf);
  3482. if (Vsnprintf(buf, sizeof(buf), bpf, ap) >= (int) sizeof(buf))
  3483. netutil_fatal("%s called with too-large filter arg\n", __func__);
  3484. va_end(ap);
  3485. if (pcap_compile(pd, &fcode, buf, 0, 0) < 0)
  3486. netutil_fatal("Error compiling our pcap filter: %s", pcap_geterr(pd));
  3487. if (pcap_setfilter(pd, &fcode) < 0)
  3488. netutil_fatal("Failed to set the pcap filter: %s\n", pcap_geterr(pd));
  3489. pcap_freecode(&fcode);
  3490. }
  3491. /* Return the data offset for the given datalink. This function understands the
  3492. datalink types DLT_EN10MB and DLT_LINUX_SLL. Returns -1 on error. */
  3493. int datalink_offset(int datalink)
  3494. {
  3495. if (datalink == DLT_EN10MB)
  3496. return ETH_HDR_LEN;
  3497. else if (datalink == DLT_LINUX_SLL)
  3498. /* The datalink type is Linux "cooked" sockets. See pcap-linktype(7). */
  3499. return 16;
  3500. else
  3501. return -1;
  3502. }
  3503. /* Common subroutine for reading ARP and NS responses. Input parameters are pd,
  3504. to_usec, and accept_callback. If a received frame passes accept_callback,
  3505. then the output parameters p, head, rcvdtime, datalink, and offset are filled
  3506. in, and the function returns 1. If no frame passes before the timeout, then
  3507. the function returns 0 and the output parameters are undefined. */
  3508. static int read_reply_pcap(pcap_t *pd, long to_usec,
  3509. bool (*accept_callback)(const unsigned char *, const struct pcap_pkthdr *, int, size_t),
  3510. unsigned char **p, struct pcap_pkthdr *head, struct timeval *rcvdtime,
  3511. int *datalink, size_t *offset)
  3512. {
  3513. static int warning = 0;
  3514. int timedout = 0;
  3515. int badcounter = 0;
  3516. struct timeval tv_start, tv_end;
  3517. int ioffset;
  3518. if (!pd)
  3519. netutil_fatal("NULL packet device passed to %s", __func__);
  3520. if (to_usec < 0) {
  3521. if (!warning) {
  3522. warning = 1;
  3523. netutil_error("WARNING: Negative timeout value (%lu) passed to %s() -- using 0", to_usec, __func__);
  3524. }
  3525. to_usec = 0;
  3526. }
  3527. /* New packet capture device, need to recompute offset */
  3528. if ((*datalink = pcap_datalink(pd)) < 0)
  3529. netutil_fatal("Cannot obtain datalink information: %s", pcap_geterr(pd));
  3530. ioffset = datalink_offset(*datalink);
  3531. if (ioffset < 0)
  3532. netutil_fatal("datalink_offset failed for type %d (DLT_EN10MB = %d, DLT_LINUX_SLL = %d)", *datalink, DLT_EN10MB, DLT_LINUX_SLL);
  3533. *offset = (unsigned int) ioffset;
  3534. if (to_usec > 0) {
  3535. gettimeofday(&tv_start, NULL);
  3536. }
  3537. do {
  3538. #ifdef WIN32
  3539. if (to_usec == 0) {
  3540. PacketSetReadTimeout(pd->adapter, 1);
  3541. } else {
  3542. gettimeofday(&tv_end, NULL);
  3543. long to_left =
  3544. MAX(1, (to_usec - TIMEVAL_SUBTRACT(tv_end, tv_start)) / 1000);
  3545. // Set the timeout (BUGBUG: this is cheating)
  3546. PacketSetReadTimeout(pd->adapter, to_left);
  3547. }
  3548. #endif
  3549. *p = NULL;
  3550. /* It may be that protecting this with !pcap_selectable_fd_one_to_one is not
  3551. necessary, that it is always safe to do a nonblocking read in this way on
  3552. all platforms. But I have only tested it on Solaris. */
  3553. if (!pcap_selectable_fd_one_to_one()) {
  3554. int rc, nonblock;
  3555. nonblock = pcap_getnonblock(pd, NULL);
  3556. assert(nonblock == 0);
  3557. rc = pcap_setnonblock(pd, 1, NULL);
  3558. assert(rc == 0);
  3559. *p = (u8 *) pcap_next(pd, head);
  3560. rc = pcap_setnonblock(pd, nonblock, NULL);
  3561. assert(rc == 0);
  3562. }
  3563. if (*p == NULL) {
  3564. /* Nonblocking pcap_next didn't get anything. */
  3565. if (pcap_select(pd, to_usec) == 0)
  3566. timedout = 1;
  3567. else
  3568. *p = (u8 *) pcap_next(pd, head);
  3569. }
  3570. if (*p != NULL && accept_callback(*p, head, *datalink, *offset)) {
  3571. break;
  3572. } else if (*p == NULL) {
  3573. /* Should we timeout? */
  3574. if (to_usec == 0) {
  3575. timedout = 1;
  3576. } else if (to_usec > 0) {
  3577. gettimeofday(&tv_end, NULL);
  3578. if (TIMEVAL_SUBTRACT(tv_end, tv_start) >= to_usec) {
  3579. timedout = 1;
  3580. }
  3581. }
  3582. } else {
  3583. /* We'll be a bit patient if we're getting actual packets back, but
  3584. not indefinitely so */
  3585. if (badcounter++ > 50)
  3586. timedout = 1;
  3587. }
  3588. } while (!timedout);
  3589. if (timedout)
  3590. return 0;
  3591. if (rcvdtime) {
  3592. // FIXME: I eventually need to figure out why Windows head.ts time is sometimes BEFORE the time I
  3593. // sent the packet (which is according to gettimeofday() in nbase). For now, I will sadly have to
  3594. // use gettimeofday() for Windows in this case
  3595. // Actually I now allow .05 discrepancy. So maybe this isn't needed. I'll comment out for now.
  3596. // Nope: it is still needed at least for Windows. Sometimes the time from he pcap header is a
  3597. // COUPLE SECONDS before the gettimeofday() results :(.
  3598. #if defined(WIN32) || defined(__amigaos__)
  3599. gettimeofday(&tv_end, NULL);
  3600. *rcvdtime = tv_end;
  3601. #else
  3602. rcvdtime->tv_sec = head->ts.tv_sec;
  3603. rcvdtime->tv_usec = head->ts.tv_usec;
  3604. assert(head->ts.tv_sec);
  3605. #endif
  3606. }
  3607. return 1;
  3608. }
  3609. static bool accept_arp(const unsigned char *p, const struct pcap_pkthdr *head,
  3610. int datalink, size_t offset)
  3611. {
  3612. if (head->caplen < offset + 28)
  3613. return false;
  3614. /* hw type eth (0x0001), prot ip (0x0800),
  3615. hw size (0x06), prot size (0x04) */
  3616. if (memcmp(p + offset, "\x00\x01\x08\x00\x06\x04\x00\x02", 8) != 0)
  3617. return false;
  3618. if (datalink == DLT_EN10MB) {
  3619. return ntohs(*((u16 *) (p + 12))) == ETH_TYPE_ARP;
  3620. } else if (datalink == DLT_LINUX_SLL) {
  3621. return ntohs(*((u16 *) (p + 2))) == ARPHRD_ETHER && /* sll_hatype */
  3622. ntohs(*((u16 *) (p + 4))) == 6 && /* sll_halen */
  3623. ntohs(*((u16 *) (p + 14))) == ETH_TYPE_ARP; /* sll_protocol */
  3624. } else {
  3625. return false;
  3626. }
  3627. }
  3628. /* Attempts to read one IPv4/Ethernet ARP reply packet from the pcap
  3629. descriptor pd. If it receives one, fills in sendermac (must pass
  3630. in 6 bytes), senderIP, and rcvdtime (can be NULL if you don't care)
  3631. and returns 1. If it times out and reads no arp requests, returns
  3632. 0. to_usec is the timeout period in microseconds. Use 0 to avoid
  3633. blocking to the extent possible. Returns -1 or exits if there is
  3634. an error. The last parameter is a pointer to a callback function
  3635. that can be used for packet tracing. This is intended to be used
  3636. by Nmap only. Any other calling this should pass NULL instead. */
  3637. int read_arp_reply_pcap(pcap_t *pd, u8 *sendermac,
  3638. struct in_addr *senderIP, long to_usec,
  3639. struct timeval *rcvdtime,
  3640. void (*trace_callback)(int, const u8 *, u32, struct timeval *)) {
  3641. unsigned char *p;
  3642. struct pcap_pkthdr head;
  3643. int datalink;
  3644. size_t offset;
  3645. int rc;
  3646. rc = read_reply_pcap(pd, to_usec, accept_arp, &p, &head, rcvdtime, &datalink, &offset);
  3647. if (rc == 0)
  3648. return 0;
  3649. memcpy(sendermac, p + offset + 8, 6);
  3650. /* I think alignment should allow this ... */
  3651. memcpy(&senderIP->s_addr, p + offset + 14, 4);
  3652. if (trace_callback != NULL) {
  3653. /* TODO: First parameter "2" is a hardcoded value for Nmap's PacketTrace::RECV. */
  3654. trace_callback(2, (u8 *) p + offset, ARP_HDR_LEN + ARP_ETHIP_LEN, rcvdtime);
  3655. }
  3656. return 1;
  3657. }
  3658. static bool accept_ns(const unsigned char *p, const struct pcap_pkthdr *head,
  3659. int datalink, size_t offset)
  3660. {
  3661. struct icmpv6_hdr *icmp6_header;
  3662. struct icmpv6_msg_nd *na;
  3663. if (head->caplen < offset + IP6_HDR_LEN + 32)
  3664. return false;
  3665. icmp6_header = (struct icmpv6_hdr *)(p + offset + IP6_HDR_LEN);
  3666. na = (struct icmpv6_msg_nd *)(p + offset + IP6_HDR_LEN + ICMPV6_HDR_LEN);
  3667. return icmp6_header->icmpv6_type == ICMPV6_NEIGHBOR_ADVERTISEMENT &&
  3668. icmp6_header->icmpv6_code == 0 &&
  3669. na->icmpv6_option_type == 2 &&
  3670. na->icmpv6_option_length == 1;
  3671. }
  3672. /* Attempts to read one IPv6/Ethernet Neighbor Solicitation reply packet from the pcap
  3673. descriptor pd. If it receives one, fills in sendermac (must pass
  3674. in 6 bytes), senderIP, and rcvdtime (can be NULL if you don't care)
  3675. and returns 1. If it times out and reads no Neighbor Advertisement, returns
  3676. 0. to_usec is the timeout period in microseconds. Use 0 to avoid
  3677. blocking to the extent possible. Returns -1 or exits if there is
  3678. an error. The last parameter is a pointer to a callback function
  3679. that can be used for packet tracing. This is intended to be used
  3680. by Nmap only. Any other calling this should pass NULL instead. */
  3681. int read_ns_reply_pcap(pcap_t *pd, u8 *sendermac,
  3682. struct sockaddr_in6 *senderIP, long to_usec,
  3683. struct timeval *rcvdtime,
  3684. void (*trace_callback)(int, const u8 *, u32, struct timeval *)) {
  3685. unsigned char *p;
  3686. struct pcap_pkthdr head;
  3687. int datalink;
  3688. size_t offset;
  3689. int rc;
  3690. struct icmpv6_msg_nd *na;
  3691. rc = read_reply_pcap(pd, to_usec, accept_ns, &p, &head, rcvdtime, &datalink, &offset);
  3692. if (rc == 0)
  3693. return 0;
  3694. na = (struct icmpv6_msg_nd *)(p + offset + IP6_HDR_LEN + ICMPV6_HDR_LEN);
  3695. memcpy(sendermac, &na->icmpv6_mac, 6);
  3696. memcpy(&senderIP->sin6_addr.s6_addr, &na->icmpv6_target, 16);
  3697. if (trace_callback != NULL) {
  3698. /* TODO: First parameter "2" is a hardcoded value for Nmap's PacketTrace::RECV. */
  3699. trace_callback(2, (u8 *) p + offset, IP6_HDR_LEN + ICMPV6_HDR_LEN + 4 + 16 + 8, rcvdtime);
  3700. }
  3701. return 1;
  3702. }
  3703. /* Issues an Neighbor Solicitation for the MAC of targetss (which will be placed
  3704. in targetmac if obtained) from the source IP (srcip) and source mac
  3705. (srcmac) given. "The request is ussued using device dev to the
  3706. multicast MAC address. The transmission is attempted up to 3
  3707. times. If none of these elicit a response, false will be returned.
  3708. If the mac is determined, true is returned. The last parameter is
  3709. a pointer to a callback function that can be used for packet tracing.
  3710. This is intended to be used by Nmap only. Any other calling this
  3711. should pass NULL instead. */
  3712. bool doND(const char *dev, const u8 *srcmac,
  3713. const struct sockaddr_storage *srcip,
  3714. const struct sockaddr_storage *targetip,
  3715. u8 *targetmac,
  3716. void (*traceND_callback)(int, const u8 *, u32 , struct timeval *)
  3717. ) {
  3718. /* timeouts in microseconds ... the first ones are retransmit times, while
  3719. the final one is when we give up */
  3720. int timeouts[] = { 100000, 400000, 800000 };
  3721. int max_sends = 3;
  3722. int num_sends = 0; // How many we have sent so far
  3723. eth_t *ethsd;
  3724. u8 frame[ETH_HDR_LEN + IP6_HDR_LEN + ICMPV6_HDR_LEN + 4 + 16 + 8];
  3725. struct timeval start, now, rcvdtime;
  3726. int timeleft;
  3727. int listenrounds;
  3728. int rc;
  3729. pcap_t *pd;
  3730. struct sockaddr_storage rcvdIP;
  3731. rcvdIP.ss_family = AF_INET6;
  3732. bool foundit = false;
  3733. char filterstr[256];
  3734. struct sockaddr_in6 *target_sin6, *src_sin6;
  3735. struct sockaddr_in6 ns_dst_ip6;
  3736. if (targetip->ss_family != AF_INET6 || srcip->ss_family != AF_INET6)
  3737. netutil_fatal("%s can only handle IPv6 addresses", __func__);
  3738. target_sin6 = (struct sockaddr_in6 *) targetip;
  3739. src_sin6 = (struct sockaddr_in6 *) srcip;
  3740. unsigned char ns_dst_mac[6] = {0x33, 0x33, 0xff};
  3741. ns_dst_mac[3] = target_sin6->sin6_addr.s6_addr[13];
  3742. ns_dst_mac[4] = target_sin6->sin6_addr.s6_addr[14];
  3743. ns_dst_mac[5] = target_sin6->sin6_addr.s6_addr[15];
  3744. ns_dst_ip6 = *target_sin6;
  3745. unsigned char multicast_prefix[13] = {0};
  3746. multicast_prefix[0] = 0xff;
  3747. multicast_prefix[1] = 0x02;
  3748. multicast_prefix[11] = 0x1;
  3749. multicast_prefix[12] = 0xff;
  3750. memcpy(ns_dst_ip6.sin6_addr.s6_addr, multicast_prefix, sizeof(multicast_prefix));
  3751. /* Start listening */
  3752. if((pd=my_pcap_open_live(dev, 100, 1, 25))==NULL)
  3753. netutil_fatal("my_pcap_open_live(%s, 50, 1, 25) failed three times.", dev);
  3754. /* Libpcap: IPv6 upper-layer protocol is not supported by proto[x] */
  3755. /* Grab the ICMPv6 type using ip6[X:Y] syntax. This works only if there are no
  3756. extension headers (top-level nh is IPPROTO_ICMPV6). */
  3757. Snprintf(filterstr, 256, "ether dst %02X%02X%02X%02X%02X%02X and icmp6 and ip6[6:1] = %u and ip6[40:1] = %u",
  3758. srcmac[0], srcmac[1], srcmac[2], srcmac[3], srcmac[4], srcmac[5],
  3759. IPPROTO_ICMPV6, ICMPV6_NEIGHBOR_ADVERTISEMENT);
  3760. set_pcap_filter(dev, pd, filterstr);
  3761. /* Prepare probe and sending stuff */
  3762. ethsd = eth_open_cached(dev);
  3763. if (!ethsd)
  3764. netutil_fatal("%s: failed to open device %s", __func__, dev);
  3765. eth_pack_hdr(frame, *ns_dst_mac, *srcmac, ETH_TYPE_IPV6);
  3766. ip6_pack_hdr(frame + ETH_HDR_LEN, 0, 0, 32, 0x3a, 255, *src_sin6->sin6_addr.s6_addr, *ns_dst_ip6.sin6_addr.s6_addr);
  3767. icmpv6_pack_hdr_ns_mac(frame + ETH_HDR_LEN + IP6_HDR_LEN, target_sin6->sin6_addr.s6_addr, *srcmac);
  3768. ip6_checksum(frame + ETH_HDR_LEN, IP6_HDR_LEN + ICMPV6_HDR_LEN + 4 + 16 + 8);
  3769. gettimeofday(&start, NULL);
  3770. gettimeofday(&now, NULL);
  3771. while (!foundit && num_sends < max_sends) {
  3772. /* Send the sucker */
  3773. rc = eth_send(ethsd, frame, sizeof(frame));
  3774. if (rc != sizeof(frame)) {
  3775. netutil_error("WARNING: %s: eth_send of Neighbor Solicitation packet returned %u rather than expected %d bytes", __func__, rc, (int) sizeof(frame));
  3776. }
  3777. if(traceND_callback!=NULL){
  3778. /* TODO: First parameter "1" is a hardcoded value for Nmap's PacketTrace::SENT*/
  3779. traceND_callback(1, (u8 *) frame + ETH_HDR_LEN, IP6_HDR_LEN + ICMPV6_HDR_LEN + 4 + 16 + 8, &now);
  3780. }
  3781. num_sends++;
  3782. listenrounds = 0;
  3783. while (!foundit) {
  3784. gettimeofday(&now, NULL);
  3785. timeleft = timeouts[num_sends - 1] - TIMEVAL_SUBTRACT(now, start);
  3786. if (timeleft < 0) {
  3787. if (listenrounds > 0)
  3788. break;
  3789. else
  3790. timeleft = 25000;
  3791. }
  3792. listenrounds++;
  3793. /* Now listen until we reach our next timeout or get an answer */
  3794. rc = read_ns_reply_pcap(pd, targetmac, (struct sockaddr_in6 *) &rcvdIP, timeleft,
  3795. &rcvdtime, traceND_callback);
  3796. if (rc == -1)
  3797. netutil_fatal("%s: Received -1 response from read_ns_reply_pcap", __func__);
  3798. if (rc == 1) {
  3799. /* Yay, I got one! But is it the right one? */
  3800. if (sockaddr_storage_cmp(&rcvdIP,targetip) != 0)
  3801. continue; /* D'oh! */
  3802. foundit = true; /* WOOHOO! */
  3803. }
  3804. }
  3805. }
  3806. /* OK - let's close up shop ... */
  3807. pcap_close(pd);
  3808. /* No need to close ethsd due to caching */
  3809. return foundit;
  3810. }
  3811. /* Issues an ARP request for the MAC of targetss (which will be placed
  3812. in targetmac if obtained) from the source IP (srcip) and source mac
  3813. (srcmac) given. "The request is ussued using device dev to the
  3814. broadcast MAC address. The transmission is attempted up to 3
  3815. times. If none of these elicit a response, false will be returned.
  3816. If the mac is determined, true is returned. The last parameter is
  3817. a pointer to a callback function that can be used for packet tracing.
  3818. This is intended to be used by Nmap only. Any other calling this
  3819. should pass NULL instead. */
  3820. bool doArp(const char *dev, const u8 *srcmac,
  3821. const struct sockaddr_storage *srcip,
  3822. const struct sockaddr_storage *targetip,
  3823. u8 *targetmac,
  3824. void (*traceArp_callback)(int, const u8 *, u32 , struct timeval *)
  3825. ) {
  3826. /* timeouts in microseconds ... the first ones are retransmit times, while
  3827. the final one is when we give up */
  3828. int timeouts[] = { 100000, 400000, 800000 };
  3829. int max_sends = 3;
  3830. int num_sends = 0; // How many we have sent so far
  3831. eth_t *ethsd;
  3832. u8 frame[ETH_HDR_LEN + ARP_HDR_LEN + ARP_ETHIP_LEN];
  3833. const struct sockaddr_in *targetsin = (struct sockaddr_in *) targetip;
  3834. const struct sockaddr_in *srcsin = (struct sockaddr_in *) srcip;
  3835. struct timeval start, now, rcvdtime;
  3836. int timeleft;
  3837. int listenrounds;
  3838. int rc;
  3839. pcap_t *pd;
  3840. struct in_addr rcvdIP;
  3841. bool foundit = false;
  3842. char filterstr[256];
  3843. if (targetsin->sin_family != AF_INET || srcsin->sin_family != AF_INET)
  3844. netutil_fatal("%s can only handle IPv4 addresses", __func__);
  3845. /* Start listening */
  3846. if((pd=my_pcap_open_live(dev, 50, 1, 25))==NULL)
  3847. netutil_fatal("my_pcap_open_live(%s, 50, 1, 25) failed three times.", dev);
  3848. Snprintf(filterstr, 256, "arp and arp[18:4] = 0x%02X%02X%02X%02X and arp[22:2] = 0x%02X%02X",
  3849. srcmac[0], srcmac[1], srcmac[2], srcmac[3], srcmac[4], srcmac[5]);
  3850. set_pcap_filter(dev, pd, filterstr);
  3851. /* Prepare probe and sending stuff */
  3852. ethsd = eth_open_cached(dev);
  3853. if (!ethsd)
  3854. netutil_fatal("%s: failed to open device %s", __func__, dev);
  3855. eth_pack_hdr(frame, ETH_ADDR_BROADCAST, *srcmac, ETH_TYPE_ARP);
  3856. arp_pack_hdr_ethip(frame + ETH_HDR_LEN, ARP_OP_REQUEST, *srcmac,
  3857. srcsin->sin_addr, ETH_ADDR_BROADCAST,
  3858. targetsin->sin_addr);
  3859. gettimeofday(&start, NULL);
  3860. gettimeofday(&now, NULL);
  3861. while (!foundit && num_sends < max_sends) {
  3862. /* Send the sucker */
  3863. rc = eth_send(ethsd, frame, sizeof(frame));
  3864. if (rc != sizeof(frame)) {
  3865. netutil_error("WARNING: %s: eth_send of ARP packet returned %u rather than expected %d bytes", __func__, rc, (int) sizeof(frame));
  3866. }
  3867. if(traceArp_callback!=NULL){
  3868. /* TODO: First parameter "1" is a hardcoded value for Nmap's PacketTrace::SENT*/
  3869. traceArp_callback(1, (u8 *) frame + ETH_HDR_LEN, ARP_HDR_LEN + ARP_ETHIP_LEN, &now);
  3870. }
  3871. num_sends++;
  3872. listenrounds = 0;
  3873. while (!foundit) {
  3874. gettimeofday(&now, NULL);
  3875. timeleft = timeouts[num_sends - 1] - TIMEVAL_SUBTRACT(now, start);
  3876. if (timeleft < 0) {
  3877. if (listenrounds > 0)
  3878. break;
  3879. else
  3880. timeleft = 25000;
  3881. }
  3882. listenrounds++;
  3883. /* Now listen until we reach our next timeout or get an answer */
  3884. rc = read_arp_reply_pcap(pd, targetmac, &rcvdIP, timeleft,
  3885. &rcvdtime, traceArp_callback);
  3886. if (rc == -1)
  3887. netutil_fatal("%s: Received -1 response from readarp_reply_pcap", __func__);
  3888. if (rc == 1) {
  3889. /* Yay, I got one! But is it the right one? */
  3890. if (rcvdIP.s_addr != targetsin->sin_addr.s_addr)
  3891. continue; /* D'oh! */
  3892. foundit = true; /* WOOHOO! */
  3893. }
  3894. }
  3895. }
  3896. /* OK - let's close up shop ... */
  3897. pcap_close(pd);
  3898. /* No need to close ethsd due to caching */
  3899. return foundit;
  3900. }
  3901. static inline bool is_host_separator(int c) {
  3902. return c == ' ' || c == '\r' || c == '\n' || c == '\t' || c == '\0';
  3903. }
  3904. /* Read a single host specification from a file, as for -iL and --excludefile.
  3905. It returns the length of the string read; an overflow is indicated when the
  3906. return value is >= n. Returns 0 if there was no specification to be read. The
  3907. buffer is always null-terminated. */
  3908. size_t read_host_from_file(FILE *fp, char *buf, size_t n)
  3909. {
  3910. int ch;
  3911. size_t i;
  3912. i = 0;
  3913. ch = getc(fp);
  3914. while (is_host_separator(ch) || ch == '#') {
  3915. if (ch == '#') {
  3916. /* Skip comments to the end of the line. */
  3917. while ((ch = getc(fp)) != EOF && ch != '\n')
  3918. ;
  3919. } else {
  3920. ch = getc(fp);
  3921. }
  3922. }
  3923. while (ch != EOF && !(is_host_separator(ch) || ch == '#')) {
  3924. if (i < n)
  3925. buf[i] = ch;
  3926. i++;
  3927. ch = getc(fp);
  3928. }
  3929. if (ch != EOF)
  3930. ungetc(ch, fp);
  3931. if (i < n)
  3932. buf[i] = '\0';
  3933. else if (n > 0)
  3934. /* Null-terminate even though it was too long. */
  3935. buf[n - 1] = '\0';
  3936. return i;
  3937. }
  3938. /* Return next target host specification from the supplied stream.
  3939. * if parameter "random" is set to true, then the function will
  3940. * return a random, non-reserved, IP address in decimal-dot notation */
  3941. const char *grab_next_host_spec(FILE *inputfd, bool random, int argc, const char **argv) {
  3942. static char host_spec[1024];
  3943. struct in_addr ip;
  3944. size_t n;
  3945. if (random) {
  3946. do {
  3947. ip.s_addr = get_random_unique_u32();
  3948. } while (ip_is_reserved(&ip));
  3949. Strncpy(host_spec, inet_ntoa(ip), sizeof(host_spec));
  3950. } else if (!inputfd) {
  3951. return( (optind < argc)? argv[optind++] : NULL);
  3952. } else {
  3953. n = read_host_from_file(inputfd, host_spec, sizeof(host_spec));
  3954. if (n == 0)
  3955. return NULL;
  3956. else if (n >= sizeof(host_spec))
  3957. netutil_fatal("One of the host specifications from your input file is too long (>= %u chars)", (unsigned int) sizeof(host_spec));
  3958. }
  3959. return host_spec;
  3960. }
  3961. /** Tries to increase the open file descriptor limit for this process.
  3962. * @param "desired" is the number of desired max open descriptors. Pass a
  3963. * negative value to set the maximum allowed.
  3964. * @return the number of max open descriptors that could be set, or 0 in case
  3965. * of failure.
  3966. * @warning if "desired" is less than the current limit, no action is
  3967. * performed. This function may only be used to increase the limit, not to
  3968. * decrease it. */
  3969. int set_max_open_descriptors(int desired_max) {
  3970. #ifndef WIN32
  3971. struct rlimit r;
  3972. int maxfds=-1;
  3973. int flag=0;
  3974. #if (defined(RLIMIT_OFILE) || defined(RLIMIT_NOFILE))
  3975. #ifdef RLIMIT_NOFILE
  3976. flag=RLIMIT_NOFILE; /* Linux */
  3977. #else
  3978. flag=RLIMIT_OFILE; /* BSD */
  3979. #endif
  3980. if (!getrlimit(flag, &r)) {
  3981. /* If current limit is less than the desired, try to increase it */
  3982. if(r.rlim_cur < (rlim_t)desired_max){
  3983. if(desired_max<0){
  3984. r.rlim_cur=r.rlim_max; /* Set maximum */
  3985. }else{
  3986. r.rlim_cur = MIN( (int)r.rlim_max, desired_max );
  3987. }
  3988. if (setrlimit(flag, &r))
  3989. ; // netutil_debug("setrlimit(%d, %p) failed", flag, r);
  3990. if (!getrlimit(flag, &r)) {
  3991. maxfds = r.rlim_cur;
  3992. return maxfds;
  3993. }else {
  3994. return 0;
  3995. }
  3996. }
  3997. }
  3998. #endif /* (defined(RLIMIT_OFILE) || defined(RLIMIT_NOFILE)) */
  3999. #endif /* !WIN32 */
  4000. return 0;
  4001. }
  4002. /** Returns the open file descriptor limit for this process.
  4003. * @return the number of max open descriptors or 0 in case of failure. */
  4004. int get_max_open_descriptors() {
  4005. #ifndef WIN32
  4006. struct rlimit r;
  4007. int flag=0;
  4008. #if (defined(RLIMIT_OFILE) || defined(RLIMIT_NOFILE))
  4009. #ifdef RLIMIT_NOFILE
  4010. flag=RLIMIT_NOFILE; /* Linux */
  4011. #else
  4012. flag=RLIMIT_OFILE; /* BSD */
  4013. #endif
  4014. if (!getrlimit(flag, &r)) {
  4015. return (int)r.rlim_cur;
  4016. }
  4017. #endif /* (defined(RLIMIT_OFILE) || defined(RLIMIT_NOFILE)) */
  4018. #endif /* !WIN32 */
  4019. return 0;
  4020. }
  4021. /* Maximize the open file descriptor limit for this process go up to the
  4022. max allowed */
  4023. int max_sd() {
  4024. return set_max_open_descriptors(-1);
  4025. }