PageRenderTime 41ms CodeModel.GetById 22ms RepoModel.GetById 0ms app.codeStats 1ms

/libnetutil/netutil.cc

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